{"text": "/-\nCopyright (c) 2014 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Leonardo de Moura, Jeremy Avigad, Floris van Doorn\n-/\nimport Std.Tactic.Ext\nimport Std.Tactic.Lint.Basic\nimport Std.Logic\nimport Mathlib.Tactic.Alias\nimport Mathlib.Tactic.Basic\nimport Mathlib.Tactic.Relation.Rfl\nimport Mathlib.Tactic.Relation.Symm\nimport Mathlib.Mathport.Attributes\nimport Mathlib.Mathport.Rename\nimport Mathlib.Tactic.Relation.Trans\n\n#align opt_param_eq optParam_eq\n\n/- Implication -/\n\n@[deprecated] def Implies (a b : Prop) := a → b\n\n/-- Implication `→` is transitive. If `P → Q` and `Q → R` then `P → R`. -/\n-- FIXME This should have `@[trans]`, but the `trans` attribute PR'd in #253 rejects it.\n-- Note that it is still rejected after #857.\n@[deprecated] theorem Implies.trans {p q r : Prop} (h₁ : p → q) (h₂ : q → r) :\n p → r := fun hp ↦ h₂ (h₁ hp)\n\n/- Not -/\n\n@[deprecated] def NonContradictory (a : Prop) : Prop := ¬¬a\n\n#align non_contradictory_intro not_not_intro\n\n/- Eq -/\n\nalias proofIrrel ← proof_irrel\nalias congrFun ← congr_fun\nalias congrArg ← congr_arg\n\n@[deprecated] theorem trans_rel_left {α : Sort u} {a b c : α}\n (r : α → α → Prop) (h₁ : r a b) (h₂ : b = c) : r a c := h₂ ▸ h₁\n\n@[deprecated] theorem trans_rel_right {α : Sort u} {a b c : α}\n (r : α → α → Prop) (h₁ : a = b) (h₂ : r b c) : r a c := h₁ ▸ h₂\n\ntheorem not_of_eq_false {p : Prop} (h : p = False) : ¬p := fun hp ↦ h ▸ hp\n\ntheorem cast_proof_irrel (h₁ h₂ : α = β) (a : α) : cast h₁ a = cast h₂ a := rfl\n\nattribute [symm] Eq.symm\n\n/- Ne -/\n\ntheorem Ne.def {α : Sort u} (a b : α) : (a ≠ b) = ¬ (a = b) := rfl\n\nattribute [symm] Ne.symm\n\n/- HEq -/\n\nalias eqRec_heq ← eq_rec_heq\n\n-- FIXME This is still rejected after #857\n-- attribute [refl] HEq.refl\nattribute [symm] HEq.symm\nattribute [trans] HEq.trans\nattribute [trans] heq_of_eq_of_heq\n\ntheorem heq_of_eq_rec_left {φ : α → Sort v} {a a' : α} {p₁ : φ a} {p₂ : φ a'} :\n (e : a = a') → (h₂ : Eq.rec (motive := fun a _ ↦ φ a) p₁ e = p₂) → HEq p₁ p₂\n | rfl, rfl => HEq.rfl\n\ntheorem heq_of_eq_rec_right {φ : α → Sort v} {a a' : α} {p₁ : φ a} {p₂ : φ a'} :\n (e : a' = a) → (h₂ : p₁ = Eq.rec (motive := fun a _ ↦ φ a) p₂ e) → HEq p₁ p₂\n | rfl, rfl => HEq.rfl\n\ntheorem of_heq_true {a : Prop} (h : HEq a True) : a := of_eq_true (eq_of_heq h)\n\ntheorem eq_rec_compose {α β φ : Sort u} :\n ∀ (p₁ : β = φ) (p₂ : α = β) (a : α),\n (Eq.recOn p₁ (Eq.recOn p₂ a : β) : φ) = Eq.recOn (Eq.trans p₂ p₁) a\n | rfl, rfl, _ => rfl\n\n/- and -/\n\nvariable {a b c d : Prop}\n\n#align and.symm And.symm\n#align and.swap And.symm\n\n/- or -/\n\n#align non_contradictory_em not_not_em\n#align or.symm Or.symm\n#align or.swap Or.symm\n\n/- xor -/\n\ndef Xor' (a b : Prop) := (a ∧ ¬ b) ∨ (b ∧ ¬ a)\n#align xor Xor'\n\n/- iff -/\n\n#align iff.mp Iff.mp\n#align iff.elim_left Iff.mp\n#align iff.mpr Iff.mpr\n#align iff.elim_right Iff.mpr\n\nattribute [refl] Iff.refl\nattribute [trans] Iff.trans\nattribute [symm] Iff.symm\n\n-- This is needed for `calc` to work with `iff`.\ninstance : Trans Iff Iff Iff where\n trans := fun p q ↦ p.trans q\n\n#align not_congr not_congr\n#align not_iff_not_of_iff not_congr\n#align not_non_contradictory_iff_absurd not_not_not\n\nalias not_not_not ↔ not_of_not_not_not _\n\n-- FIXME\n-- attribute [congr] not_congr\n\n@[deprecated and_comm] theorem and_comm' (a b) : a ∧ b ↔ b ∧ a := and_comm\n#align and.comm and_comm\n#align and_comm and_comm'\n\n@[deprecated and_assoc] theorem and_assoc' (a b) : (a ∧ b) ∧ c ↔ a ∧ (b ∧ c) := and_assoc\n#align and_assoc and_assoc'\n#align and.assoc and_assoc\n\n#align and.left_comm and_left_comm\n\n#align and_iff_left and_iff_leftₓ -- reorder implicits\n\nvariable (p)\n\n-- FIXME: remove _iff and add _eq for the lean 4 core versions\ntheorem and_true_iff : p ∧ True ↔ p := iff_of_eq (and_true _)\n#align and_true and_true_iff\ntheorem true_and_iff : True ∧ p ↔ p := iff_of_eq (true_and _)\n#align true_and true_and_iff\ntheorem and_false_iff : p ∧ False ↔ False := iff_of_eq (and_false _)\n#align and_false and_false_iff\ntheorem false_and_iff : False ∧ p ↔ False := iff_of_eq (false_and _)\n#align false_and false_and_iff\n#align not_and_self not_and_self_iff\n#align and_not_self and_not_self_iff\ntheorem and_self_iff : p ∧ p ↔ p := iff_of_eq (and_self _)\n#align and_self and_self_iff\n\n#align or.imp Or.impₓ -- reorder implicits\n\n#align and.elim And.elimₓ\n#align iff.elim Iff.elimₓ\n#align imp_congr imp_congrₓ\n#align imp_congr_ctx imp_congr_ctxₓ\n#align imp_congr_right imp_congr_rightₓ\n\n#align eq_true_intro eq_true\n#align eq_false_intro eq_false\n\n@[deprecated or_comm] theorem or_comm' (a b) : a ∨ b ↔ b ∨ a := or_comm\n#align or.comm or_comm\n#align or_comm or_comm'\n\n@[deprecated or_assoc] theorem or_assoc' (a b) : (a ∨ b) ∨ c ↔ a ∨ (b ∨ c) := or_assoc\n#align or.assoc or_assoc\n#align or_assoc or_assoc'\n\n#align or_left_comm or_left_comm\n#align or.left_comm or_left_comm\n\n#align or_iff_left_of_imp or_iff_left_of_impₓ -- reorder implicits\n\ntheorem true_or_iff : True ∨ p ↔ True := iff_of_eq (true_or _)\n#align true_or true_or_iff\ntheorem or_true_iff : p ∨ True ↔ True := iff_of_eq (or_true _)\n#align or_true or_true_iff\ntheorem false_or_iff : False ∨ p ↔ p := iff_of_eq (false_or _)\n#align false_or false_or_iff\ntheorem or_false_iff : p ∨ False ↔ p := iff_of_eq (or_false _)\n#align or_false or_false_iff\ntheorem or_self_iff : p ∨ p ↔ p := iff_of_eq (or_self _)\n#align or_self or_self_iff\n\ntheorem not_or_of_not : ¬a → ¬b → ¬(a ∨ b) := fun h1 h2 ↦ not_or.2 ⟨h1, h2⟩\n#align not_or not_or_of_not\n\ntheorem iff_true_iff : (a ↔ True) ↔ a := iff_of_eq (iff_true _)\n#align iff_true iff_true_iff\ntheorem true_iff_iff : (True ↔ a) ↔ a := iff_of_eq (true_iff _)\n#align true_iff true_iff_iff\n\ntheorem iff_false_iff : (a ↔ False) ↔ ¬a := iff_of_eq (iff_false _)\n#align iff_false iff_false_iff\n\ntheorem false_iff_iff : (False ↔ a) ↔ ¬a := iff_of_eq (false_iff _)\n#align false_iff false_iff_iff\n\ntheorem iff_self_iff (a : Prop) : (a ↔ a) ↔ True := iff_of_eq (iff_self _)\n#align iff_self iff_self_iff\n\n#align iff_congr iff_congrₓ -- reorder implicits\n\n#align implies_true_iff imp_true_iff\n#align false_implies_iff false_imp_iff\n#align true_implies_iff true_imp_iff\n\n#align Exists Exists -- otherwise it would get the name ExistsCat\n\n-- TODO\n-- attribute [intro] Exists.intro\n\n/- exists unique -/\n\ndef ExistsUnique (p : α → Prop) := ∃ x, p x ∧ ∀ y, p y → y = x\n\nopen Lean TSyntax.Compat in\nmacro \"∃! \" xs:explicitBinders \", \" b:term : term => expandExplicitBinders ``ExistsUnique xs b\n\n/-- Pretty-printing for `ExistsUnique`, following the same pattern as pretty printing\n for `Exists`. -/\n@[app_unexpander ExistsUnique] def unexpandExistsUnique : Lean.PrettyPrinter.Unexpander\n | `($(_) fun $x:ident ↦ ∃! $xs:binderIdent*, $b) => `(∃! $x:ident $xs:binderIdent*, $b)\n | `($(_) fun $x:ident ↦ $b) => `(∃! $x:ident, $b)\n | `($(_) fun ($x:ident : $t) ↦ $b) => `(∃! ($x:ident : $t), $b)\n | _ => throw ()\n\n-- @[intro] -- TODO\ntheorem ExistsUnique.intro {p : α → Prop} (w : α)\n (h₁ : p w) (h₂ : ∀ y, p y → y = w) : ∃! x, p x := ⟨w, h₁, h₂⟩\n\ntheorem ExistsUnique.elim {α : Sort u} {p : α → Prop} {b : Prop}\n (h₂ : ∃! x, p x) (h₁ : ∀ x, p x → (∀ y, p y → y = x) → b) : b :=\n Exists.elim h₂ (λ w hw => h₁ w (And.left hw) (And.right hw))\n\ntheorem exists_unique_of_exists_of_unique {α : Sort u} {p : α → Prop}\n (hex : ∃ x, p x) (hunique : ∀ y₁ y₂, p y₁ → p y₂ → y₁ = y₂) : ∃! x, p x :=\n Exists.elim hex (λ x px => ExistsUnique.intro x px (λ y (h : p y) => hunique y x h px))\n\ntheorem ExistsUnique.exists {p : α → Prop} : (∃! x, p x) → ∃ x, p x | ⟨x, h, _⟩ => ⟨x, h⟩\n#align exists_of_exists_unique ExistsUnique.exists\n#align exists_unique.exists ExistsUnique.exists\n\ntheorem ExistsUnique.unique {α : Sort u} {p : α → Prop}\n (h : ∃! x, p x) {y₁ y₂ : α} (py₁ : p y₁) (py₂ : p y₂) : y₁ = y₂ :=\n let ⟨_, _, hy⟩ := h; (hy _ py₁).trans (hy _ py₂).symm\n#align unique_of_exists_unique ExistsUnique.unique\n#align exists_unique.unique ExistsUnique.unique\n\n/- exists, forall, exists unique congruences -/\n\n-- TODO\n-- attribute [congr] forall_congr'\n-- attribute [congr] exists_congr'\n#align forall_congr forall_congr'\n\n#align Exists.imp Exists.imp\n#align exists_imp_exists Exists.imp\n\n-- @[congr]\ntheorem exists_unique_congr {p q : α → Prop} (h : ∀ a, p a ↔ q a) : (∃! a, p a) ↔ ∃! a, q a :=\n exists_congr fun _ ↦ and_congr (h _) $ forall_congr' fun _ ↦ imp_congr_left (h _)\n\n/- decidable -/\n\n#align decidable.to_bool Decidable.decide\n\ntheorem decide_True' (h : Decidable True) : decide True = true := by simp\n#align to_bool_true_eq_tt decide_True'\n\ntheorem decide_False' (h : Decidable False) : decide False = false := by simp\n#align to_bool_false_eq_ff decide_False'\n\nnamespace Decidable\n\ndef recOn_true [h : Decidable p] {h₁ : p → Sort u} {h₂ : ¬p → Sort u}\n (h₃ : p) (h₄ : h₁ h₃) : Decidable.recOn h h₂ h₁ :=\n cast (by match h with | .isTrue _ => rfl) h₄\n#align decidable.rec_on_true Decidable.recOn_true\n\ndef recOn_false [h : Decidable p] {h₁ : p → Sort u} {h₂ : ¬p → Sort u} (h₃ : ¬p) (h₄ : h₂ h₃) :\n Decidable.recOn h h₂ h₁ :=\n cast (by match h with | .isFalse _ => rfl) h₄\n#align decidable.rec_on_false Decidable.recOn_false\n\nalias byCases ← by_cases\nalias byContradiction ← by_contradiction\nalias not_not ← not_not_iff\n\n@[deprecated not_or] theorem not_or_iff_and_not (p q) [Decidable p] [Decidable q] :\n ¬(p ∨ q) ↔ ¬p ∧ ¬q := not_or\n\nend Decidable\n\n#align decidable_of_decidable_of_iff decidable_of_decidable_of_iff\n#align decidable_of_decidable_of_eq decidable_of_decidable_of_eq\n#align or.by_cases Or.by_cases\n\nalias instDecidableOr ← Or.decidable\nalias instDecidableAnd ← And.decidable\nalias instDecidableNot ← Not.decidable\nalias instDecidableIff ← Iff.decidable\n\n#align or.decidable Or.decidable\n#align and.decidable And.decidable\n#align not.decidable Not.decidable\n#align iff.decidable Iff.decidable\n\ninstance [Decidable p] [Decidable q] : Decidable (Xor' p q) := inferInstanceAs (Decidable (Or ..))\n\ndef IsDecEq {α : Sort u} (p : α → α → Bool) : Prop := ∀ ⦃x y : α⦄, p x y = true → x = y\ndef IsDecRefl {α : Sort u} (p : α → α → Bool) : Prop := ∀ x, p x x = true\n\ndef decidableEq_of_bool_pred {α : Sort u} {p : α → α → Bool} (h₁ : IsDecEq p)\n (h₂ : IsDecRefl p) : DecidableEq α\n | x, y =>\n if hp : p x y = true then isTrue (h₁ hp)\n else isFalse (λ hxy : x = y => absurd (h₂ y) (by rwa [hxy] at hp))\n#align decidable_eq_of_bool_pred decidableEq_of_bool_pred\n\ntheorem decidableEq_inl_refl {α : Sort u} [h : DecidableEq α] (a : α) :\n h a a = isTrue (Eq.refl a) :=\n match h a a with\n | isTrue _ => rfl\n\ntheorem decidableEq_inr_neg {α : Sort u} [h : DecidableEq α] {a b : α}\n (n : a ≠ b) : h a b = isFalse n :=\n match h a b with\n | isFalse _ => rfl\n\n#align inhabited.default Inhabited.default\n#align arbitrary Inhabited.default\n#align nonempty_of_inhabited instNonempty\n\n/- subsingleton -/\n\ntheorem rec_subsingleton {p : Prop} [h : Decidable p] {h₁ : p → Sort u} {h₂ : ¬p → Sort u}\n [h₃ : ∀ h : p, Subsingleton (h₁ h)] [h₄ : ∀ h : ¬p, Subsingleton (h₂ h)] :\n Subsingleton (Decidable.recOn h h₂ h₁) :=\n match h with\n | isTrue h => h₃ h\n | isFalse h => h₄ h\n\n@[deprecated ite_self]\ntheorem if_t_t (c : Prop) [Decidable c] {α : Sort u} (t : α) : ite c t t = t := ite_self _\n\ntheorem imp_of_if_pos {c t e : Prop} [Decidable c] (h : ite c t e) (hc : c) : t :=\n by have := if_pos hc ▸ h; exact this\n#align implies_of_if_pos imp_of_if_pos\n\ntheorem imp_of_if_neg {c t e : Prop} [Decidable c] (h : ite c t e) (hnc : ¬c) : e :=\n by have := if_neg hnc ▸ h; exact this\n#align implies_of_if_neg imp_of_if_neg\n\ntheorem if_ctx_congr {α : Sort u} {b c : Prop} [dec_b : Decidable b] [dec_c : Decidable c]\n {x y u v : α} (h_c : b ↔ c) (h_t : c → x = u) (h_e : ¬c → y = v) : ite b x y = ite c u v :=\n match dec_b, dec_c with\n | isFalse _, isFalse h₂ => h_e h₂\n | isTrue _, isTrue h₂ => h_t h₂\n | isFalse h₁, isTrue h₂ => absurd h₂ (Iff.mp (not_congr h_c) h₁)\n | isTrue h₁, isFalse h₂ => absurd h₁ (Iff.mpr (not_congr h_c) h₂)\n\ntheorem if_congr {α : Sort u} {b c : Prop} [Decidable b] [Decidable c]\n {x y u v : α} (h_c : b ↔ c) (h_t : x = u) (h_e : y = v) : ite b x y = ite c u v :=\n if_ctx_congr h_c (λ _ => h_t) (λ _ => h_e)\n\ntheorem if_ctx_congr_prop {b c x y u v : Prop} [dec_b : Decidable b] [dec_c : Decidable c]\n (h_c : b ↔ c) (h_t : c → (x ↔ u)) (h_e : ¬c → (y ↔ v)) : ite b x y ↔ ite c u v :=\n match dec_b, dec_c with\n | isFalse _, isFalse h₂ => h_e h₂\n | isTrue _, isTrue h₂ => h_t h₂\n | isFalse h₁, isTrue h₂ => absurd h₂ (Iff.mp (not_congr h_c) h₁)\n | isTrue h₁, isFalse h₂ => absurd h₁ (Iff.mpr (not_congr h_c) h₂)\n\n-- @[congr]\ntheorem if_congr_prop {b c x y u v : Prop} [Decidable b] [Decidable c] (h_c : b ↔ c) (h_t : x ↔ u)\n (h_e : y ↔ v) : ite b x y ↔ ite c u v :=\n if_ctx_congr_prop h_c (λ _ => h_t) (λ _ => h_e)\n\ntheorem if_ctx_simp_congr_prop {b c x y u v : Prop} [Decidable b] (h_c : b ↔ c) (h_t : c → (x ↔ u))\n -- FIXME: after https://github.com/leanprover/lean4/issues/1867 is fixed,\n -- this should be changed back to:\n -- (h_e : ¬c → (y ↔ v)) : ite b x y ↔ ite c (h := decidable_of_decidable_of_iff h_c) u v :=\n (h_e : ¬c → (y ↔ v)) : ite b x y ↔ @ite _ c (decidable_of_decidable_of_iff h_c) u v :=\n if_ctx_congr_prop (dec_c := decidable_of_decidable_of_iff h_c) h_c h_t h_e\n\ntheorem if_simp_congr_prop {b c x y u v : Prop} [Decidable b] (h_c : b ↔ c) (h_t : x ↔ u)\n -- FIXME: after https://github.com/leanprover/lean4/issues/1867 is fixed,\n -- this should be changed back to:\n -- (h_e : y ↔ v) : ite b x y ↔ (ite c (h := decidable_of_decidable_of_iff h_c) u v) :=\n (h_e : y ↔ v) : ite b x y ↔ (@ite _ c (decidable_of_decidable_of_iff h_c) u v) :=\n if_ctx_simp_congr_prop h_c (λ _ => h_t) (λ _ => h_e)\n\n-- @[congr]\ntheorem dif_ctx_congr {α : Sort u} {b c : Prop} [dec_b : Decidable b] [dec_c : Decidable c]\n {x : b → α} {u : c → α} {y : ¬b → α} {v : ¬c → α}\n (h_c : b ↔ c) (h_t : ∀ h : c, x (Iff.mpr h_c h) = u h)\n (h_e : ∀ h : ¬c, y (Iff.mpr (not_congr h_c) h) = v h) :\n @dite α b dec_b x y = @dite α c dec_c u v :=\n match dec_b, dec_c with\n | isFalse _, isFalse h₂ => h_e h₂\n | isTrue _, isTrue h₂ => h_t h₂\n | isFalse h₁, isTrue h₂ => absurd h₂ (Iff.mp (not_congr h_c) h₁)\n | isTrue h₁, isFalse h₂ => absurd h₁ (Iff.mpr (not_congr h_c) h₂)\n\ntheorem dif_ctx_simp_congr {α : Sort u} {b c : Prop} [Decidable b]\n {x : b → α} {u : c → α} {y : ¬b → α} {v : ¬c → α}\n (h_c : b ↔ c) (h_t : ∀ h : c, x (Iff.mpr h_c h) = u h)\n (h_e : ∀ h : ¬c, y (Iff.mpr (not_congr h_c) h) = v h) :\n -- FIXME: after https://github.com/leanprover/lean4/issues/1867 is fixed,\n -- this should be changed back to:\n -- dite b x y = dite c (h := decidable_of_decidable_of_iff h_c) u v :=\n dite b x y = @dite _ c (decidable_of_decidable_of_iff h_c) u v :=\n dif_ctx_congr (dec_c := decidable_of_decidable_of_iff h_c) h_c h_t h_e\n\ndef AsTrue (c : Prop) [Decidable c] : Prop := if c then True else False\n\ndef AsFalse (c : Prop) [Decidable c] : Prop := if c then False else True\n\ntheorem AsTrue.get {c : Prop} [h₁ : Decidable c] (_ : AsTrue c) : c :=\n match h₁ with\n | isTrue h_c => h_c\n#align of_as_true AsTrue.get\n\n#align ulift ULift\n#align ulift.up ULift.up\n#align ulift.down ULift.down\n#align plift PLift\n#align plift.up PLift.up\n#align plift.down PLift.down\n\n/- Equalities for rewriting let-expressions -/\ntheorem let_value_eq {α : Sort u} {β : Sort v} {a₁ a₂ : α} (b : α → β)\n (h : a₁ = a₂) : (let x : α := a₁; b x) = (let x : α := a₂; b x) := congrArg b h\n\ntheorem let_value_heq {α : Sort v} {β : α → Sort u} {a₁ a₂ : α} (b : ∀ x : α, β x)\n (h : a₁ = a₂) : HEq (let x : α := a₁; b x) (let x : α := a₂; b x) := by cases h; rfl\n#align let_value_heq let_value_heq -- FIXME: mathport thinks this is a dubious translation\n\ntheorem let_body_eq {α : Sort v} {β : α → Sort u} (a : α) {b₁ b₂ : ∀ x : α, β x}\n (h : ∀ x, b₁ x = b₂ x) : (let x : α := a; b₁ x) = (let x : α := a; b₂ x) := by exact h _ ▸ rfl\n#align let_value_eq let_value_eq -- FIXME: mathport thinks this is a dubious translation\n\ntheorem let_eq {α : Sort v} {β : Sort u} {a₁ a₂ : α} {b₁ b₂ : α → β}\n (h₁ : a₁ = a₂) (h₂ : ∀ x, b₁ x = b₂ x) :\n (let x : α := a₁; b₁ x) = (let x : α := a₂; b₂ x) := by simp [h₁, h₂]\n#align let_eq let_eq -- FIXME: mathport thinks this is a dubious translation\n\nsection Relation\n\nvariable {α : Sort u} {β : Sort v} (r : β → β → Prop)\n\n/-- Local notation for an arbitrary binary relation `r`. -/\nlocal infix:50 \" ≺ \" => r\n\n/-- A reflexive relation relates every element to itself. -/\ndef Reflexive := ∀ x, x ≺ x\n\n/-- A relation is symmetric if `x ≺ y` implies `y ≺ x`. -/\ndef Symmetric := ∀ ⦃x y⦄, x ≺ y → y ≺ x\n\n/-- A relation is transitive if `x ≺ y` and `y ≺ z` together imply `x ≺ z`. -/\ndef Transitive := ∀ ⦃x y z⦄, x ≺ y → y ≺ z → x ≺ z\n\nlemma Equivalence.reflexive {r : β → β → Prop} (h : Equivalence r) : Reflexive r := h.refl\n\nlemma Equivalence.symmetric {r : β → β → Prop} (h : Equivalence r) : Symmetric r := λ _ _ => h.symm\n\nlemma Equivalence.transitive {r : β → β → Prop}(h : Equivalence r) : Transitive r :=\n λ _ _ _ => h.trans\n\n/-- A relation is total if for all `x` and `y`, either `x ≺ y` or `y ≺ x`. -/\ndef Total := ∀ x y, x ≺ y ∨ y ≺ x\n\n#align mk_equivalence Equivalence.mk\n\n/-- Irreflexive means \"not reflexive\". -/\ndef Irreflexive := ∀ x, ¬ x ≺ x\n\n/-- A relation is antisymmetric if `x ≺ y` and `y ≺ x` together imply that `x = y`. -/\ndef AntiSymmetric := ∀ ⦃x y⦄, x ≺ y → y ≺ x → x = y\n\n/-- An empty relation does not relate any elements. -/\n@[nolint unusedArguments]\ndef EmptyRelation := λ _ _ : α => False\n\ntheorem InvImage.trans (f : α → β) (h : Transitive r) : Transitive (InvImage r f) :=\n fun (a₁ a₂ a₃ : α) (h₁ : InvImage r f a₁ a₂) (h₂ : InvImage r f a₂ a₃) ↦ h h₁ h₂\n\ntheorem InvImage.irreflexive (f : α → β) (h : Irreflexive r) : Irreflexive (InvImage r f) :=\n fun (a : α) (h₁ : InvImage r f a a) ↦ h (f a) h₁\n\nend Relation\n\nsection Binary\n\nvariable {α : Type u} {β : Type v} (f : α → α → α) (inv : α → α) (one : α)\n\n/-- Local notation for `f`, high priority to avoid ambiguity with `HMul.hMul`. -/\nlocal infix:70 (priority := high) \" * \" => f\n\n/-- Local notation for `inv`, high priority to avoid ambiguity with `Inv.inv`. -/\nlocal postfix:100 (priority := high) \"⁻¹\" => inv\n\nvariable (g : α → α → α)\n\n/-- Local notation for `g`, high priority to avoid ambiguity with `HAdd.hAdd`. -/\nlocal infix:65 (priority := high) \" + \" => g\n\ndef Commutative := ∀ a b, a * b = b * a\ndef Associative := ∀ a b c, (a * b) * c = a * (b * c)\ndef LeftIdentity := ∀ a, one * a = a\ndef RightIdentity := ∀ a, a * one = a\ndef RightInverse := ∀ a, a * a⁻¹ = one\ndef LeftCancelative := ∀ a b c, a * b = a * c → b = c\ndef RightCancelative := ∀ a b c, a * b = c * b → a = c\ndef LeftDistributive := ∀ a b c, a * (b + c) = a * b + a * c\ndef RightDistributive := ∀ a b c, (a + b) * c = a * c + b * c\ndef RightCommutative (h : β → α → β) := ∀ b a₁ a₂, h (h b a₁) a₂ = h (h b a₂) a₁\ndef LeftCommutative (h : α → β → β) := ∀ a₁ a₂ b, h a₁ (h a₂ b) = h a₂ (h a₁ b)\n\ntheorem left_comm : Commutative f → Associative f → LeftCommutative f :=\n fun hcomm hassoc a b c ↦\n calc a*(b*c)\n _ = (a*b)*c := Eq.symm (hassoc a b c)\n _ = (b*a)*c := hcomm a b ▸ rfl\n _ = b*(a*c) := hassoc b a c\n\ntheorem right_comm : Commutative f → Associative f → RightCommutative f :=\n fun hcomm hassoc a b c ↦\n calc (a*b)*c\n _ = a*(b*c) := hassoc a b c\n _ = a*(c*b) := hcomm b c ▸ rfl\n _ = (a*c)*b := Eq.symm (hassoc a c b)\n\nend Binary\n\nnamespace WellFounded\n\nvariable {α : Sort u} {C : α → Sort v} {r : α → α → Prop}\n\nunsafe def fix'.impl (hwf : WellFounded r) (F : ∀ x, (∀ y, r y x → C y) → C x) (x : α) : C x :=\n F x fun y _ ↦ impl hwf F y\n\n@[implemented_by fix'.impl]\ndef fix' (hwf : WellFounded r) (F : ∀ x, (∀ y, r y x → C y) → C x) (x : α) : C x := hwf.fix F x\n\nend WellFounded\n\n#align not.elim Not.elim\n#align not.imp Not.imp\n#align not_not_of_not_imp not_not_of_not_imp\n#align not_of_not_imp not_of_not_imp\n#align imp_not_self imp_not_self\n#align iff_def iff_def\n#align iff_def' iff_def'\n#align iff_of_eq iff_of_eq\n#align iff_iff_eq iff_iff_eq\n#align eq_iff_iff eq_iff_iff\n#align iff_of_true iff_of_true\n#align iff_of_false iff_of_false\n#align iff_true_left iff_true_left\n#align iff_true_right iff_true_right\n#align iff_false_left iff_false_left\n#align iff_false_right iff_false_right\n#align imp_intro imp_intro\n#align imp_imp_imp imp_imp_imp\n#align imp_true_iff imp_true_iff\n#align imp_self imp_self\n#align imp_false imp_false\n#align imp_not_comm imp_not_comm\n#align and.imp_left And.imp_left\n#align and.imp_right And.imp_right\n#align and_congr_left' and_congr_left'\n#align and_rotate and_rotate\n#align and_and_and_comm and_and_and_comm\n#align and_iff_left_of_imp and_iff_left_of_imp\n#align and_iff_right_of_imp and_iff_right_of_imp\n#align and_iff_left_iff_imp and_iff_left_iff_imp\n#align and_iff_right_iff_imp and_iff_right_iff_imp\n#align iff_self_and iff_self_and\n#align iff_and_self iff_and_self\n#align and_self_left and_self_left\n#align and_self_right and_self_right\n#align not_and_of_not_left not_and_of_not_left\n#align not_and_of_not_right not_and_of_not_right\n#align and_not_self_iff and_not_self_iff\n#align not_and_self_iff not_and_self_iff\n#align or_or_or_comm or_or_or_comm\n#align or_or_distrib_left or_or_distrib_left\n#align or_or_distrib_right or_or_distrib_right\n#align or_rotate or_rotate\n#align or_iff_left_iff_imp or_iff_left_iff_imp\n#align or_iff_right_iff_imp or_iff_right_iff_imp\n#align or_iff_right or_iff_right\n#align not_imp_of_and_not not_imp_of_and_not\n#align and_imp and_imp\n#align not_and not_and\n#align not_and' not_and'\n#align not_and_of_not_or_not not_and_of_not_or_not\n#align or_self_left or_self_left\n#align or_self_right or_self_right\n#align forall_imp forall_imp\n#align forall₂_congr forall₂_congr\n#align exists₂_congr exists₂_congr\n#align forall₃_congr forall₃_congr\n#align exists₃_congr exists₃_congr\n#align forall₄_congr forall₄_congr\n#align exists₄_congr exists₄_congr\n#align forall₅_congr forall₅_congr\n#align exists₅_congr exists₅_congr\n#align not_exists not_exists\n#align exists_false exists_false\n#align forall_const forall_const\n#align not_forall_of_exists_not not_forall_of_exists_not\n#align forall_eq forall_eq\n#align forall_eq' forall_eq'\n#align exists_eq exists_eq\n#align exists_eq' exists_eq'\n#align exists_eq_left exists_eq_left\n#align exists_eq_right exists_eq_right\n#align exists_eq_left' exists_eq_left'\n#align forall_eq_or_imp forall_eq_or_imp\n#align exists_eq_right_right exists_eq_right_right\n#align exists_eq_right_right' exists_eq_right_right'\n#align exists_prop exists_prop\n#align exists_apply_eq_apply exists_apply_eq_apply\n#align forall_prop_of_true forall_prop_of_true\n#align decidable.not_not Decidable.not_not\n#align decidable.of_not_imp Decidable.of_not_imp\n#align decidable.not_imp_symm Decidable.not_imp_symm\n#align decidable.not_imp_comm Decidable.not_imp_comm\n#align decidable.not_imp_self Decidable.not_imp_self\n#align decidable.or_iff_not_imp_left Decidable.or_iff_not_imp_left\n#align decidable.not_imp_not Decidable.not_imp_not\n#align decidable.not_or_of_imp Decidable.not_or_of_imp\n#align decidable.imp_iff_not_or Decidable.imp_iff_not_or\n#align decidable.not_imp Decidable.not_imp\n#align decidable.peirce Decidable.peirce\n#align peirce' peirce'\n#align decidable.not_iff_not Decidable.not_iff_not\n#align decidable.not_iff_comm Decidable.not_iff_comm\n#align decidable.not_iff Decidable.not_iff\n#align decidable.iff_not_comm Decidable.iff_not_comm\n#align decidable.iff_iff_and_or_not_and_not Decidable.iff_iff_and_or_not_and_not\n#align decidable.iff_iff_not_or_and_or_not Decidable.iff_iff_not_or_and_or_not\n#align decidable.not_and_not_right Decidable.not_and_not_right\n#align decidable.or_iff_not_and_not Decidable.or_iff_not_and_not\n#align decidable.and_iff_not_or_not Decidable.and_iff_not_or_not\n#align decidable.imp_iff_right_iff Decidable.imp_iff_right_iff\n#align decidable.and_or_imp Decidable.and_or_imp\n#align heq_iff_eq heq_iff_eq\n#align proof_irrel_heq proof_irrel_heq\n#align eq_rec_constant eq_rec_constant\n#align ne_of_mem_of_not_mem ne_of_mem_of_not_mem\n#align ne_of_mem_of_not_mem' ne_of_mem_of_not_mem'\n#align apply_dite apply_dite\n#align apply_ite apply_ite\n#align dite_not dite_not\n#align ite_not ite_not\n#align empty.elim Empty.elim\n#align pempty.elim PEmpty.elim\n#align not_nonempty_pempty not_nonempty_pempty\n#align eq_iff_true_of_subsingleton eq_iff_true_of_subsingleton\n#align subsingleton_of_forall_eq subsingleton_of_forall_eq\n#align subsingleton_iff_forall_eq subsingleton_iff_forall_eq\n#align false_ne_true false_ne_true\n#align ne_comm ne_comm\n", "meta": {"author": "leanprover-community", "repo": "mathlib4", "sha": "b9a0a30342ca06e9817e22dbe46e75fc7f435500", "save_path": "github-repos/lean/leanprover-community-mathlib4", "path": "github-repos/lean/leanprover-community-mathlib4/mathlib4-b9a0a30342ca06e9817e22dbe46e75fc7f435500/Mathlib/Init/Logic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.476579651063676, "lm_q2_score": 0.10374862201684203, "lm_q1q2_score": 0.04944448207912379}} {"text": "/-\nCopyright (c) 2020 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Leonardo de Moura\n-/\nprelude\n\nuniverse u v w\n\n@[inline] def id {α : Sort u} (a : α) : α := a\n\n/-\nThe kernel definitional equality test (t =?= s) has special support for idDelta applications.\nIt implements the following rules\n\n 1) (idDelta t) =?= t\n 2) t =?= (idDelta t)\n 3) (idDelta t) =?= s IF (unfoldOf t) =?= s\n 4) t =?= idDelta s IF t =?= (unfoldOf s)\n\nThis is mechanism for controlling the delta reduction (aka unfolding) used in the kernel.\n\nWe use idDelta applications to address performance problems when Type checking\ntheorems generated by the equation Compiler.\n-/\n@[inline] def idDelta {α : Sort u} (a : α) : α := a\n\n/- `idRhs` is an auxiliary declaration used to implement \"smart unfolding\". It is used as a marker. -/\n@[macroInline, reducible] def idRhs (α : Sort u) (a : α) : α := a\n\nabbrev Function.comp {α : Sort u} {β : Sort v} {δ : Sort w} (f : β → δ) (g : α → β) : α → δ :=\n fun x => f (g x)\n\nabbrev Function.const {α : Sort u} (β : Sort v) (a : α) : β → α :=\n fun x => a\n\n@[reducible] def inferInstance {α : Type u} [i : α] : α := i\n@[reducible] def inferInstanceAs (α : Type u) [i : α] : α := i\n\nset_option bootstrap.inductiveCheckResultingUniverse false in\ninductive PUnit : Sort u\n | unit : PUnit\n\n/-- An abbreviation for `PUnit.{0}`, its most common instantiation.\n This Type should be preferred over `PUnit` where possible to avoid\n unnecessary universe parameters. -/\nabbrev Unit : Type := PUnit\n\n@[matchPattern] abbrev Unit.unit : Unit := PUnit.unit\n\n/-- Auxiliary unsafe constant used by the Compiler when erasing proofs from code. -/\nunsafe axiom lcProof {α : Prop} : α\n\n/-- Auxiliary unsafe constant used by the Compiler to mark unreachable code. -/\nunsafe axiom lcUnreachable {α : Sort u} : α\n\ninductive True : Prop\n | intro : True\n\ninductive False : Prop\n\ninductive Empty : Type\n\ndef Not (a : Prop) : Prop := a → False\n\n@[macroInline] def False.elim {C : Sort u} (h : False) : C :=\n False.rec (fun _ => C) h\n\n@[macroInline] def absurd {a : Prop} {b : Sort v} (h₁ : a) (h₂ : Not a) : b :=\n False.elim (h₂ h₁)\n\ninductive Eq {α : Sort u} (a : α) : α → Prop\n | refl {} : Eq a a\n\nabbrev Eq.ndrec.{u1, u2} {α : Sort u2} {a : α} {motive : α → Sort u1} (m : motive a) {b : α} (h : Eq a b) : motive b :=\n Eq.rec (motive := fun α _ => motive α) m h\n\n@[matchPattern] def rfl {α : Sort u} {a : α} : Eq a a := Eq.refl a\n\ntheorem Eq.subst {α : Sort u} {motive : α → Prop} {a b : α} (h₁ : Eq a b) (h₂ : motive a) : motive b :=\n Eq.ndrec h₂ h₁\n\ntheorem Eq.symm {α : Sort u} {a b : α} (h : Eq a b) : Eq b a :=\n h ▸ rfl\n\n@[macroInline] def cast {α β : Sort u} (h : Eq α β) (a : α) : β :=\n Eq.rec (motive := fun α _ => α) a h\n\ntheorem congrArg {α : Sort u} {β : Sort v} {a₁ a₂ : α} (f : α → β) (h : Eq a₁ a₂) : Eq (f a₁) (f a₂) :=\n h ▸ rfl\n\n/-\nInitialize the Quotient Module, which effectively adds the following definitions:\n\nconstant Quot {α : Sort u} (r : α → α → Prop) : Sort u\n\nconstant Quot.mk {α : Sort u} (r : α → α → Prop) (a : α) : Quot r\n\nconstant Quot.lift {α : Sort u} {r : α → α → Prop} {β : Sort v} (f : α → β) :\n (∀ a b : α, r a b → Eq (f a) (f b)) → Quot r → β\n\nconstant Quot.ind {α : Sort u} {r : α → α → Prop} {β : Quot r → Prop} :\n (∀ a : α, β (Quot.mk r a)) → ∀ q : Quot r, β q\n-/\ninit_quot\n\ninductive HEq {α : Sort u} (a : α) : {β : Sort u} → β → Prop\n | refl {} : HEq a a\n\n@[matchPattern] def HEq.rfl {α : Sort u} {a : α} : HEq a a :=\n HEq.refl a\n\ntheorem eqOfHEq {α : Sort u} {a a' : α} (h : HEq a a') : Eq a a' :=\n have : (α β : Sort u) → (a : α) → (b : β) → HEq a b → (h : Eq α β) → Eq (cast h a) b :=\n fun α β a b h₁ =>\n HEq.rec (motive := fun {β} (b : β) (h : HEq a b) => (h₂ : Eq α β) → Eq (cast h₂ a) b)\n (fun (h₂ : Eq α α) => rfl)\n h₁\n this α α a a' h rfl\n\nstructure Prod (α : Type u) (β : Type v) :=\n (fst : α) (snd : β)\n\nattribute [unbox] Prod\n\n/-- Similar to `Prod`, but `α` and `β` can be propositions.\n We use this Type internally to automatically generate the brecOn recursor. -/\nstructure PProd (α : Sort u) (β : Sort v) :=\n (fst : α) (snd : β)\n\n/-- Similar to `Prod`, but `α` and `β` are in the same universe. -/\nstructure MProd (α β : Type u) :=\n (fst : α) (snd : β)\n\nstructure And (a b : Prop) : Prop :=\n intro :: (left : a) (right : b)\n\ninductive Or (a b : Prop) : Prop\n | inl (h : a) : Or a b\n | inr (h : b) : Or a b\n\ninductive Bool : Type\n | false : Bool\n | true : Bool\n\nexport Bool (false true)\n\n/- Remark: Subtype must take a Sort instead of Type because of the axiom strongIndefiniteDescription. -/\nstructure Subtype {α : Sort u} (p : α → Prop) :=\n (val : α) (property : p val)\n\n/-- Gadget for optional parameter support. -/\n@[reducible] def optParam (α : Sort u) (default : α) : Sort u := α\n\n/-- Gadget for marking output parameters in type classes. -/\n@[reducible] def outParam (α : Sort u) : Sort u := α\n\n/-- Auxiliary Declaration used to implement the notation (a : α) -/\n@[reducible] def typedExpr (α : Sort u) (a : α) : α := a\n\n/-- Auxiliary Declaration used to implement the named patterns `x@p` -/\n@[reducible] def namedPattern {α : Sort u} (x a : α) : α := a\n\n/- Auxiliary axiom used to implement `sorry`. -/\naxiom sorryAx (α : Sort u) (synthetic := true) : α\n\ntheorem eqFalseOfNeTrue : {b : Bool} → Not (Eq b true) → Eq b false\n | true, h => False.elim (h rfl)\n | false, h => rfl\n\ntheorem eqTrueOfNeFalse : {b : Bool} → Not (Eq b false) → Eq b true\n | true, h => rfl\n | false, h => False.elim (h rfl)\n\ntheorem neFalseOfEqTrue : {b : Bool} → Eq b true → Not (Eq b false)\n | true, _ => fun h => Bool.noConfusion h\n | false, h => Bool.noConfusion h\n\ntheorem neTrueOfEqFalse : {b : Bool} → Eq b false → Not (Eq b true)\n | true, h => Bool.noConfusion h\n | false, _ => fun h => Bool.noConfusion h\n\nclass Inhabited (α : Sort u) :=\n mk {} :: (default : α)\n\nconstant arbitrary (α : Sort u) [s : Inhabited α] : α :=\n @Inhabited.default α s\n\ninstance (α : Sort u) {β : Sort v} [Inhabited β] : Inhabited (α → β) := {\n default := fun _ => arbitrary β\n}\n\ninstance (α : Sort u) {β : α → Sort v} [(a : α) → Inhabited (β a)] : Inhabited ((a : α) → β a) := {\n default := fun a => arbitrary (β a)\n}\n\n/-- Universe lifting operation from Sort to Type -/\nstructure PLift (α : Sort u) : Type u :=\n up :: (down : α)\n\n/- Bijection between α and PLift α -/\ntheorem PLift.upDown {α : Sort u} : ∀ (b : PLift α), Eq (up (down b)) b\n | up a => rfl\n\ntheorem PLift.downUp {α : Sort u} (a : α) : Eq (down (up a)) a :=\n rfl\n\n/- Pointed types -/\nstructure PointedType :=\n (type : Type u)\n (val : type)\n\ninstance : Inhabited PointedType.{u} := {\n default := { type := PUnit.{u+1}, val := ⟨⟩ }\n}\n\n/-- Universe lifting operation -/\nstructure ULift.{r, s} (α : Type s) : Type (max s r) :=\n up :: (down : α)\n\n/- Bijection between α and ULift.{v} α -/\ntheorem ULift.upDown {α : Type u} : ∀ (b : ULift.{v} α), Eq (up (down b)) b\n | up a => rfl\n\ntheorem ULift.downUp {α : Type u} (a : α) : Eq (down (up.{v} a)) a :=\n rfl\n\nclass inductive Decidable (p : Prop)\n | isFalse (h : Not p) : Decidable p\n | isTrue (h : p) : Decidable p\n\n@[inlineIfReduce, nospecialize] def Decidable.decide (p : Prop) [h : Decidable p] : Bool :=\n Decidable.casesOn (motive := fun _ => Bool) h (fun _ => false) (fun _ => true)\n\nexport Decidable (isTrue isFalse decide)\n\nabbrev DecidablePred {α : Sort u} (r : α → Prop) :=\n (a : α) → Decidable (r a)\n\nabbrev DecidableRel {α : Sort u} (r : α → α → Prop) :=\n (a b : α) → Decidable (r a b)\n\nabbrev DecidableEq (α : Sort u) :=\n (a b : α) → Decidable (Eq a b)\n\ndef decEq {α : Sort u} [s : DecidableEq α] (a b : α) : Decidable (Eq a b) :=\n s a b\n\ntheorem decideEqTrue : {p : Prop} → [s : Decidable p] → p → Eq (decide p) true\n | _, isTrue _, _ => rfl\n | _, isFalse h₁, h₂ => absurd h₂ h₁\n\ntheorem decideEqTrue' : [s : Decidable p] → p → Eq (decide p) true\n | isTrue _, _ => rfl\n | isFalse h₁, h₂ => absurd h₂ h₁\n\ntheorem decideEqFalse : {p : Prop} → [s : Decidable p] → Not p → Eq (decide p) false\n | _, isTrue h₁, h₂ => absurd h₁ h₂\n | _, isFalse h, _ => rfl\n\ntheorem ofDecideEqTrue {p : Prop} [s : Decidable p] : Eq (decide p) true → p := fun h =>\n match s with\n | isTrue h₁ => h₁\n | isFalse h₁ => absurd h (neTrueOfEqFalse (decideEqFalse h₁))\n\ntheorem ofDecideEqFalse {p : Prop} [s : Decidable p] : Eq (decide p) false → Not p := fun h =>\n match s with\n | isTrue h₁ => absurd h (neFalseOfEqTrue (decideEqTrue h₁))\n | isFalse h₁ => h₁\n\n@[inline] instance : DecidableEq Bool :=\n fun a b => match a, b with\n | false, false => isTrue rfl\n | false, true => isFalse (fun h => Bool.noConfusion h)\n | true, false => isFalse (fun h => Bool.noConfusion h)\n | true, true => isTrue rfl\n\nclass BEq (α : Type u) := (beq : α → α → Bool)\n\nopen BEq (beq)\n\ninstance {α : Type u} [DecidableEq α] : BEq α :=\n ⟨fun a b => decide (Eq a b)⟩\n\n-- We use \"dependent\" if-then-else to be able to communicate the if-then-else condition\n-- to the branches\n@[macroInline] def dite {α : Sort u} (c : Prop) [h : Decidable c] (t : c → α) (e : Not c → α) : α :=\n Decidable.casesOn (motive := fun _ => α) h e t\n", "meta": {"author": "Kha", "repo": "lean4-nightly", "sha": "b4c92de57090e6c47b29d3575df53d86fce52752", "save_path": "github-repos/lean/Kha-lean4-nightly", "path": "github-repos/lean/Kha-lean4-nightly/lean4-nightly-b4c92de57090e6c47b29d3575df53d86fce52752/tests/lean/Reformat/Input.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4726834766204328, "lm_q2_score": 0.10374862617358858, "lm_q1q2_score": 0.049040261314325484}} {"text": "/-\nCopyright (c) 2020 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Leonardo de Moura\n-/\nprelude\n\nuniverse u v w\n\n@[inline] def id {α : Sort u} (a : α) : α := a\n\n/-\nThe kernel definitional equality test (t =?= s) has special support for idDelta applications.\nIt implements the following rules\n\n 1) (idDelta t) =?= t\n 2) t =?= (idDelta t)\n 3) (idDelta t) =?= s IF (unfoldOf t) =?= s\n 4) t =?= idDelta s IF t =?= (unfoldOf s)\n\nThis is mechanism for controlling the delta reduction (aka unfolding) used in the kernel.\n\nWe use idDelta applications to address performance problems when Type checking\ntheorems generated by the equation Compiler.\n-/\n@[inline] def idDelta {α : Sort u} (a : α) : α := a\n\n/- `idRhs` is an auxiliary declaration used to implement \"smart unfolding\". It is used as a marker. -/\n@[macro_inline, reducible] def idRhs (α : Sort u) (a : α) : α := a\n\nabbrev Function.comp {α : Sort u} {β : Sort v} {δ : Sort w} (f : β → δ) (g : α → β) : α → δ :=\n fun x => f (g x)\n\nabbrev Function.const {α : Sort u} (β : Sort v) (a : α) : β → α :=\n fun x => a\n\n@[reducible] def inferInstance {α : Type u} [i : α] : α := i\n@[reducible] def inferInstanceAs (α : Type u) [i : α] : α := i\n\nset_option bootstrap.inductiveCheckResultingUniverse false in\ninductive PUnit : Sort u\n | unit : PUnit\n\n/-- An abbreviation for `PUnit.{0}`, its most common instantiation.\n This Type should be preferred over `PUnit` where possible to avoid\n unnecessary universe parameters. -/\nabbrev Unit : Type := PUnit\n\n@[match_pattern] abbrev Unit.unit : Unit := PUnit.unit\n\n/-- Auxiliary unsafe constant used by the Compiler when erasing proofs from code. -/\nunsafe axiom lcProof {α : Prop} : α\n\n/-- Auxiliary unsafe constant used by the Compiler to mark unreachable code. -/\nunsafe axiom lcUnreachable {α : Sort u} : α\n\ninductive True : Prop\n | intro : True\n\ninductive False : Prop\n\ninductive Empty : Type\n\ndef Not (a : Prop) : Prop := a → False\n\n@[macro_inline] def False.elim {C : Sort u} (h : False) : C :=\n False.rec (fun _ => C) h\n\n@[macro_inline] def absurd {a : Prop} {b : Sort v} (h₁ : a) (h₂ : Not a) : b :=\n False.elim (h₂ h₁)\n\ninductive Eq : α → α → Prop\n | refl (a : α) : Eq a a\n\nabbrev Eq.ndrec.{u1, u2} {α : Sort u2} {a : α} {motive : α → Sort u1} (m : motive a) {b : α} (h : Eq a b) : motive b :=\n Eq.rec (motive := fun α _ => motive α) m h\n\n@[match_pattern] def rfl {α : Sort u} {a : α} : Eq a a := Eq.refl a\n\ntheorem Eq.subst {α : Sort u} {motive : α → Prop} {a b : α} (h₁ : Eq a b) (h₂ : motive a) : motive b :=\n Eq.ndrec h₂ h₁\n\ntheorem Eq.symm {α : Sort u} {a b : α} (h : Eq a b) : Eq b a :=\n h ▸ rfl\n\n@[macro_inline] def cast {α β : Sort u} (h : Eq α β) (a : α) : β :=\n Eq.rec (motive := fun α _ => α) a h\n\ntheorem congrArg {α : Sort u} {β : Sort v} {a₁ a₂ : α} (f : α → β) (h : Eq a₁ a₂) : Eq (f a₁) (f a₂) :=\n h ▸ rfl\n\n/-\nInitialize the Quotient Module, which effectively adds the following definitions:\n\nopaque Quot {α : Sort u} (r : α → α → Prop) : Sort u\n\nopaque Quot.mk {α : Sort u} (r : α → α → Prop) (a : α) : Quot r\n\nopaque Quot.lift {α : Sort u} {r : α → α → Prop} {β : Sort v} (f : α → β) :\n (∀ a b : α, r a b → Eq (f a) (f b)) → Quot r → β\n\nopaque Quot.ind {α : Sort u} {r : α → α → Prop} {β : Quot r → Prop} :\n (∀ a : α, β (Quot.mk r a)) → ∀ q : Quot r, β q\n-/\ninit_quot\n\ninductive HEq : {α : Sort u} → α → {β : Sort u} → β → Prop\n | refl (a : α) : HEq a a\n\n@[match_pattern] def HEq.rfl {α : Sort u} {a : α} : HEq a a :=\n HEq.refl a\n\ntheorem eqOfHEq {α : Sort u} {a a' : α} (h : HEq a a') : Eq a a' :=\n have : (α β : Sort u) → (a : α) → (b : β) → HEq a b → (h : Eq α β) → Eq (cast h a) b :=\n fun α β a b h₁ =>\n HEq.rec (motive := fun {β} (b : β) (h : HEq a b) => (h₂ : Eq α β) → Eq (cast h₂ a) b)\n (fun (h₂ : Eq α α) => rfl)\n h₁\n this α α a a' h rfl\n\nstructure Prod (α : Type u) (β : Type v) :=\n (fst : α) (snd : β)\n\nattribute [unbox] Prod\n\n/-- Similar to `Prod`, but `α` and `β` can be propositions.\n We use this Type internally to automatically generate the brecOn recursor. -/\nstructure PProd (α : Sort u) (β : Sort v) :=\n (fst : α) (snd : β)\n\n/-- Similar to `Prod`, but `α` and `β` are in the same universe. -/\nstructure MProd (α β : Type u) :=\n (fst : α) (snd : β)\n\nstructure And (a b : Prop) : Prop :=\n intro :: (left : a) (right : b)\n\ninductive Or (a b : Prop) : Prop\n | inl (h : a) : Or a b\n | inr (h : b) : Or a b\n\ninductive Bool : Type\n | false : Bool\n | true : Bool\n\nexport Bool (false true)\n\n/- Remark: Subtype must take a Sort instead of Type because of the axiom strongIndefiniteDescription. -/\nstructure Subtype {α : Sort u} (p : α → Prop) :=\n (val : α) (property : p val)\n\n/-- Gadget for optional parameter support. -/\n@[reducible] def optParam (α : Sort u) (default : α) : Sort u := α\n\n/-- Gadget for marking output parameters in type classes. -/\n@[reducible] def outParam (α : Sort u) : Sort u := α\n\n/-- Auxiliary Declaration used to implement the notation (a : α) -/\n@[reducible] def typedExpr (α : Sort u) (a : α) : α := a\n\n/-- Auxiliary Declaration used to implement the named patterns `x@p` -/\n@[reducible] def namedPattern {α : Sort u} (x a : α) : α := a\n\n/- Auxiliary axiom used to implement `sorry`. -/\naxiom sorryAx (α : Sort u) (synthetic := true) : α\n\ntheorem eqFalseOfNeTrue : {b : Bool} → Not (Eq b true) → Eq b false\n | true, h => False.elim (h rfl)\n | false, h => rfl\n\ntheorem eqTrueOfNeFalse : {b : Bool} → Not (Eq b false) → Eq b true\n | true, h => rfl\n | false, h => False.elim (h rfl)\n\ntheorem neFalseOfEqTrue : {b : Bool} → Eq b true → Not (Eq b false)\n | true, _ => fun h => Bool.noConfusion h\n | false, h => Bool.noConfusion h\n\ntheorem neTrueOfEqFalse : {b : Bool} → Eq b false → Not (Eq b true)\n | true, h => Bool.noConfusion h\n | false, _ => fun h => Bool.noConfusion h\n\nclass Inhabited (α : Sort u) :=\n (default : α)\n\nopaque arbitrary (α : Sort u) [s : Inhabited α] : α :=\n @Inhabited.default α s\n\ninstance (α : Sort u) {β : Sort v} [Inhabited β] : Inhabited (α → β) := {default := fun _ => arbitrary β}\n\ninstance (α : Sort u) {β : α → Sort v} [(a : α) → Inhabited (β a)] : Inhabited ((a : α) → β a) := {default := fun a => arbitrary (β a)}\n\n/-- Universe lifting operation from Sort to Type -/\nstructure PLift (α : Sort u) : Type u :=\n up :: (down : α)\n\n/- Bijection between α and PLift α -/\ntheorem PLift.upDown {α : Sort u} : ∀ (b : PLift α), Eq (up (down b)) b\n | up a => rfl\n\ntheorem PLift.downUp {α : Sort u} (a : α) : Eq (down (up a)) a :=\n rfl\n\n/- Pointed types -/\nstructure PointedType :=\n (type : Type u)\n (val : type)\n\ninstance : Inhabited PointedType.{u} := {default := { type := PUnit.{u+1}, val := ⟨⟩ }}\n\n/-- Universe lifting operation -/\nstructure ULift.{r, s} (α : Type s) : Type (max s r) :=\n up :: (down : α)\n\n/- Bijection between α and ULift.{v} α -/\ntheorem ULift.upDown {α : Type u} : ∀ (b : ULift.{v} α), Eq (up (down b)) b\n | up a => rfl\n\ntheorem ULift.downUp {α : Type u} (a : α) : Eq (down (up.{v} a)) a :=\n rfl\n\nclass inductive Decidable (p : Prop)\n | isFalse (h : Not p) : Decidable p\n | isTrue (h : p) : Decidable p\n\n@[inline_if_reduce, nospecialize] def Decidable.decide (p : Prop) [h : Decidable p] : Bool :=\n Decidable.casesOn (motive := fun _ => Bool) h (fun _ => false) (fun _ => true)\n\nexport Decidable (isTrue isFalse decide)\n\nabbrev DecidablePred {α : Sort u} (r : α → Prop) :=\n (a : α) → Decidable (r a)\n\nabbrev DecidableRel {α : Sort u} (r : α → α → Prop) :=\n (a b : α) → Decidable (r a b)\n\nabbrev DecidableEq (α : Sort u) :=\n (a b : α) → Decidable (Eq a b)\n\ndef decEq {α : Sort u} [s : DecidableEq α] (a b : α) : Decidable (Eq a b) :=\n s a b\n\ntheorem decideEqTrue : {p : Prop} → [s : Decidable p] → p → Eq (decide p) true\n | _, isTrue _, _ => rfl\n | _, isFalse h₁, h₂ => absurd h₂ h₁\n\ntheorem decideEqTrue' : [s : Decidable p] → p → Eq (decide p) true\n | isTrue _, _ => rfl\n | isFalse h₁, h₂ => absurd h₂ h₁\n\ntheorem decideEqFalse : {p : Prop} → [s : Decidable p] → Not p → Eq (decide p) false\n | _, isTrue h₁, h₂ => absurd h₁ h₂\n | _, isFalse h, _ => rfl\n\ntheorem ofDecideEqTrue {p : Prop} [s : Decidable p] : Eq (decide p) true → p := fun h =>\n match s with\n | isTrue h₁ => h₁\n | isFalse h₁ => absurd h (neTrueOfEqFalse (decideEqFalse h₁))\n\ntheorem ofDecideEqFalse {p : Prop} [s : Decidable p] : Eq (decide p) false → Not p := fun h =>\n match s with\n | isTrue h₁ => absurd h (neFalseOfEqTrue (decideEqTrue h₁))\n | isFalse h₁ => h₁\n\n@[inline] instance : DecidableEq Bool :=\n fun a b => match a, b with\n | false, false => isTrue rfl\n | false, true => isFalse (fun h => Bool.noConfusion h)\n | true, false => isFalse (fun h => Bool.noConfusion h)\n | true, true => isTrue rfl\n\nclass BEq (α : Type u) := (beq : α → α → Bool)\n\nopen BEq (beq)\n\ninstance {α : Type u} [DecidableEq α] : BEq α :=\n ⟨fun a b => decide (Eq a b)⟩\n\n-- We use \"dependent\" if-then-else to be able to communicate the if-then-else condition\n-- to the branches\n@[macro_inline] def dite {α : Sort u} (c : Prop) [h : Decidable c] (t : c → α) (e : Not c → α) : α :=\n Decidable.casesOn (motive := fun _ => α) h e t\n", "meta": {"author": "leanprover", "repo": "lean4", "sha": "742d053a97bdd109a41a921facd1cd6a55e89bc7", "save_path": "github-repos/lean/leanprover-lean4", "path": "github-repos/lean/leanprover-lean4/lean4-742d053a97bdd109a41a921facd1cd6a55e89bc7/tests/lean/Reformat/Input.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.09807931885692363, "lm_q1q2_score": 0.049039659428461814}} {"text": "/-\nCopyright (c) 2018 Scott Morrison. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Scott Morrison, Jannis Limperg\n-/\n\n/-!\n# Monadic instances for `ulift` and `plift`\n\n> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.\n> Any changes to this file require a corresponding PR to mathlib4.\n\nIn this file we define `monad` and `is_lawful_monad` instances on `plift` and `ulift`. -/\n\nuniverses u v\n\nnamespace plift\n\nvariables {α : Sort u} {β : Sort v}\n\n/-- Functorial action. -/\nprotected def map (f : α → β) (a : plift α) : plift β :=\nplift.up (f a.down)\n\n@[simp] \n\n/-- Embedding of pure values. -/\n@[simp] protected def pure : α → plift α := up\n\n/-- Applicative sequencing. -/\nprotected def seq (f : plift (α → β)) (x : plift α) : plift β :=\nplift.up (f.down x.down)\n\n@[simp] lemma seq_up (f : α → β) (x : α) : (plift.up f).seq (plift.up x) = plift.up (f x) := rfl\n\n/-- Monadic bind. -/\nprotected def bind (a : plift α) (f : α → plift β) : plift β := f a.down\n\n@[simp] lemma bind_up (a : α) (f : α → plift β) : (plift.up a).bind f = f a := rfl\n\ninstance : monad plift :=\n{ map := @plift.map,\n pure := @plift.pure,\n seq := @plift.seq,\n bind := @plift.bind }\n\ninstance : is_lawful_functor plift :=\n{ id_map := λ α ⟨x⟩, rfl,\n comp_map := λ α β γ g h ⟨x⟩, rfl }\n\ninstance : is_lawful_applicative plift :=\n{ pure_seq_eq_map := λ α β g ⟨x⟩, rfl,\n map_pure := λ α β g x, rfl,\n seq_pure := λ α β ⟨g⟩ x, rfl,\n seq_assoc := λ α β γ ⟨x⟩ ⟨g⟩ ⟨h⟩, rfl }\n\ninstance : is_lawful_monad plift :=\n{ bind_pure_comp_eq_map := λ α β f ⟨x⟩, rfl,\n bind_map_eq_seq := λ α β ⟨a⟩ ⟨b⟩, rfl,\n pure_bind := λ α β x f, rfl,\n bind_assoc := λ α β γ ⟨x⟩ f g, rfl }\n\n@[simp] lemma rec.constant {α : Sort u} {β : Type v} (b : β) :\n @plift.rec α (λ _, β) (λ _, b) = λ _, b :=\nfunext (λ x, plift.cases_on x (λ a, eq.refl (plift.rec (λ a', b) {down := a})))\n\nend plift\n\n\nnamespace ulift\n\nvariables {α : Type u} {β : Type v}\n\n/-- Functorial action. -/\nprotected def map (f : α → β) (a : ulift α) : ulift β :=\nulift.up (f a.down)\n\n@[simp] lemma map_up (f : α → β) (a : α) : (ulift.up a).map f = ulift.up (f a) := rfl\n\n/-- Embedding of pure values. -/\n@[simp] protected def pure : α → ulift α := up\n\n/-- Applicative sequencing. -/\nprotected def seq (f : ulift (α → β)) (x : ulift α) : ulift β :=\nulift.up (f.down x.down)\n\n@[simp] lemma seq_up (f : α → β) (x : α) : (ulift.up f).seq (ulift.up x) = ulift.up (f x) := rfl\n\n/-- Monadic bind. -/\nprotected def bind (a : ulift α) (f : α → ulift β) : ulift β := f a.down\n\n@[simp] lemma bind_up (a : α) (f : α → ulift β) : (ulift.up a).bind f = f a := rfl\n\ninstance : monad ulift :=\n{ map := @ulift.map,\n pure := @ulift.pure,\n seq := @ulift.seq,\n bind := @ulift.bind }\n\ninstance : is_lawful_functor ulift :=\n{ id_map := λ α ⟨x⟩, rfl,\n comp_map := λ α β γ g h ⟨x⟩, rfl }\n\ninstance : is_lawful_applicative ulift :=\n{ to_is_lawful_functor := ulift.is_lawful_functor,\n pure_seq_eq_map := λ α β g ⟨x⟩, rfl,\n map_pure := λ α β g x, rfl,\n seq_pure := λ α β ⟨g⟩ x, rfl,\n seq_assoc := λ α β γ ⟨x⟩ ⟨g⟩ ⟨h⟩, rfl }\n\ninstance : is_lawful_monad ulift :=\n{ bind_pure_comp_eq_map := λ α β f ⟨x⟩, rfl,\n bind_map_eq_seq := λ α β ⟨a⟩ ⟨b⟩, rfl,\n pure_bind := λ α β x f,\n by { dsimp only [bind, pure, ulift.pure, ulift.bind], cases (f x), refl },\n bind_assoc := λ α β γ ⟨x⟩ f g,\n by { dsimp only [bind, pure, ulift.pure, ulift.bind], cases (f x), refl } }\n\n@[simp] lemma rec.constant {α : Type u} {β : Sort v} (b : β) :\n @ulift.rec α (λ _, β) (λ _, b) = λ _, b :=\nfunext (λ x, ulift.cases_on x (λ a, eq.refl (ulift.rec (λ a', b) {down := a})))\n\nend ulift\n", "meta": {"author": "leanprover-community", "repo": "mathlib", "sha": "5e526d18cea33550268dcbbddcb822d5cde40654", "save_path": "github-repos/lean/leanprover-community-mathlib", "path": "github-repos/lean/leanprover-community-mathlib/mathlib-5e526d18cea33550268dcbbddcb822d5cde40654/src/control/ulift.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4493926344647596, "lm_q2_score": 0.1081889459357195, "lm_q1q2_score": 0.04861931543401843}} {"text": "/-\nCopyright (c) 2016 Jeremy Avigad. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Jeremy Avigad, Leonardo de Moura\n-/\nimport tactic.doc_commands\nimport tactic.reserved_notation\n\n/-!\n# Basic logic properties\n\nThis file is one of the earliest imports in mathlib.\n\n## Implementation notes\n\nTheorems that require decidability hypotheses are in the namespace \"decidable\".\nClassical versions are in the namespace \"classical\".\n\nIn the presence of automation, this whole file may be unnecessary. On the other hand,\nmaybe it is useful for writing automation.\n-/\n\nopen function\nlocal attribute [instance, priority 10] classical.prop_decidable\n\nsection miscellany\n\n/- We add the `inline` attribute to optimize VM computation using these declarations. For example,\n `if p ∧ q then ... else ...` will not evaluate the decidability of `q` if `p` is false. -/\nattribute [inline] and.decidable or.decidable decidable.false xor.decidable iff.decidable\n decidable.true implies.decidable not.decidable ne.decidable\n bool.decidable_eq decidable.to_bool\n\nattribute [simp] cast_eq cast_heq\n\nvariables {α : Type*} {β : Type*}\n\n/-- An identity function with its main argument implicit. This will be printed as `hidden` even\nif it is applied to a large term, so it can be used for elision,\nas done in the `elide` and `unelide` tactics. -/\n@[reducible] def hidden {α : Sort*} {a : α} := a\n\n/-- Ex falso, the nondependent eliminator for the `empty` type. -/\ndef empty.elim {C : Sort*} : empty → C.\n\ninstance : subsingleton empty := ⟨λa, a.elim⟩\n\ninstance subsingleton.prod {α β : Type*} [subsingleton α] [subsingleton β] : subsingleton (α × β) :=\n⟨by { intros a b, cases a, cases b, congr, }⟩\n\ninstance : decidable_eq empty := λa, a.elim\n\ninstance sort.inhabited : inhabited (Sort*) := ⟨punit⟩\ninstance sort.inhabited' : inhabited (default (Sort*)) := ⟨punit.star⟩\n\ninstance psum.inhabited_left {α β} [inhabited α] : inhabited (psum α β) := ⟨psum.inl (default _)⟩\ninstance psum.inhabited_right {α β} [inhabited β] : inhabited (psum α β) := ⟨psum.inr (default _)⟩\n\n@[priority 10] instance decidable_eq_of_subsingleton\n {α} [subsingleton α] : decidable_eq α\n| a b := is_true (subsingleton.elim a b)\n\n@[simp] lemma eq_iff_true_of_subsingleton {α : Sort*} [subsingleton α] (x y : α) :\n x = y ↔ true :=\nby cc\n\n/-- If all points are equal to a given point `x`, then `α` is a subsingleton. -/\nlemma subsingleton_of_forall_eq {α : Sort*} (x : α) (h : ∀ y, y = x) : subsingleton α :=\n⟨λ a b, (h a).symm ▸ (h b).symm ▸ rfl⟩\n\nlemma subsingleton_iff_forall_eq {α : Sort*} (x : α) : subsingleton α ↔ ∀ y, y = x :=\n⟨λ h y, @subsingleton.elim _ h y x, subsingleton_of_forall_eq x⟩\n\n-- TODO[gh-6025]: make this an instance once safe to do so\nlemma subtype.subsingleton (α : Sort*) [subsingleton α] (p : α → Prop) : subsingleton (subtype p) :=\n⟨λ ⟨x,_⟩ ⟨y,_⟩, have x = y, from subsingleton.elim _ _, by { cases this, refl }⟩\n\n/-- Add an instance to \"undo\" coercion transitivity into a chain of coercions, because\n most simp lemmas are stated with respect to simple coercions and will not match when\n part of a chain. -/\n@[simp] theorem coe_coe {α β γ} [has_coe α β] [has_coe_t β γ]\n (a : α) : (a : γ) = (a : β) := rfl\n\ntheorem coe_fn_coe_trans\n {α β γ δ} [has_coe α β] [has_coe_t_aux β γ] [has_coe_to_fun γ δ]\n (x : α) : @coe_fn α _ _ x = @coe_fn β _ _ x := rfl\n\n/-- Non-dependent version of `coe_fn_coe_trans`, helps `rw` figure out the argument. -/\ntheorem coe_fn_coe_trans'\n {α β γ} {δ : out_param $ _} [has_coe α β] [has_coe_t_aux β γ] [has_coe_to_fun γ (λ _, δ)]\n (x : α) : @coe_fn α _ _ x = @coe_fn β _ _ x := rfl\n\n@[simp] theorem coe_fn_coe_base\n {α β γ} [has_coe α β] [has_coe_to_fun β γ]\n (x : α) : @coe_fn α _ _ x = @coe_fn β _ _ x := rfl\n\n/-- Non-dependent version of `coe_fn_coe_base`, helps `rw` figure out the argument. -/\ntheorem coe_fn_coe_base'\n {α β} {γ : out_param $ _} [has_coe α β] [has_coe_to_fun β (λ _, γ)]\n (x : α) : @coe_fn α _ _ x = @coe_fn β _ _ x := rfl\n\ntheorem coe_sort_coe_trans\n {α β γ δ} [has_coe α β] [has_coe_t_aux β γ] [has_coe_to_sort γ δ]\n (x : α) : @coe_sort α _ _ x = @coe_sort β _ _ x := rfl\n\n/--\nMany structures such as bundled morphisms coerce to functions so that you can\ntransparently apply them to arguments. For example, if `e : α ≃ β` and `a : α`\nthen you can write `e a` and this is elaborated as `⇑e a`. This type of\ncoercion is implemented using the `has_coe_to_fun` type class. There is one\nimportant consideration:\n\nIf a type coerces to another type which in turn coerces to a function,\nthen it **must** implement `has_coe_to_fun` directly:\n```lean\nstructure sparkling_equiv (α β) extends α ≃ β\n\n-- if we add a `has_coe` instance,\ninstance {α β} : has_coe (sparkling_equiv α β) (α ≃ β) :=\n⟨sparkling_equiv.to_equiv⟩\n\n-- then a `has_coe_to_fun` instance **must** be added as well:\ninstance {α β} : has_coe_to_fun (sparkling_equiv α β) :=\n⟨λ _, α → β, λ f, f.to_equiv.to_fun⟩\n```\n\n(Rationale: if we do not declare the direct coercion, then `⇑e a` is not in\nsimp-normal form. The lemma `coe_fn_coe_base` will unfold it to `⇑↑e a`. This\noften causes loops in the simplifier.)\n-/\nlibrary_note \"function coercion\"\n\n@[simp] theorem coe_sort_coe_base\n {α β γ} [has_coe α β] [has_coe_to_sort β γ]\n (x : α) : @coe_sort α _ _ x = @coe_sort β _ _ x := rfl\n\n/-- `pempty` is the universe-polymorphic analogue of `empty`. -/\n@[derive decidable_eq]\ninductive {u} pempty : Sort u\n\n/-- Ex falso, the nondependent eliminator for the `pempty` type. -/\ndef pempty.elim {C : Sort*} : pempty → C.\n\ninstance subsingleton_pempty : subsingleton pempty := ⟨λa, a.elim⟩\n\n@[simp] lemma not_nonempty_pempty : ¬ nonempty pempty :=\nassume ⟨h⟩, h.elim\n\n@[simp] theorem forall_pempty {P : pempty → Prop} : (∀ x : pempty, P x) ↔ true :=\n⟨λ h, trivial, λ h x, by cases x⟩\n\n@[simp] theorem exists_pempty {P : pempty → Prop} : (∃ x : pempty, P x) ↔ false :=\n⟨λ h, by { cases h with w, cases w }, false.elim⟩\n\nlemma congr_arg_heq {α} {β : α → Sort*} (f : ∀ a, β a) : ∀ {a₁ a₂ : α}, a₁ = a₂ → f a₁ == f a₂\n| a _ rfl := heq.rfl\n\nlemma plift.down_inj {α : Sort*} : ∀ (a b : plift α), a.down = b.down → a = b\n| ⟨a⟩ ⟨b⟩ rfl := rfl\n\n-- missing [symm] attribute for ne in core.\nattribute [symm] ne.symm\n\nlemma ne_comm {α} {a b : α} : a ≠ b ↔ b ≠ a := ⟨ne.symm, ne.symm⟩\n\n@[simp] lemma eq_iff_eq_cancel_left {b c : α} :\n (∀ {a}, a = b ↔ a = c) ↔ (b = c) :=\n⟨λ h, by rw [← h], λ h a, by rw h⟩\n\n@[simp] lemma eq_iff_eq_cancel_right {a b : α} :\n (∀ {c}, a = c ↔ b = c) ↔ (a = b) :=\n⟨λ h, by rw h, λ h a, by rw h⟩\n\n/-- Wrapper for adding elementary propositions to the type class systems.\nWarning: this can easily be abused. See the rest of this docstring for details.\n\nCertain propositions should not be treated as a class globally,\nbut sometimes it is very convenient to be able to use the type class system\nin specific circumstances.\n\nFor example, `zmod p` is a field if and only if `p` is a prime number.\nIn order to be able to find this field instance automatically by type class search,\nwe have to turn `p.prime` into an instance implicit assumption.\n\nOn the other hand, making `nat.prime` a class would require a major refactoring of the library,\nand it is questionable whether making `nat.prime` a class is desirable at all.\nThe compromise is to add the assumption `[fact p.prime]` to `zmod.field`.\n\nIn particular, this class is not intended for turning the type class system\ninto an automated theorem prover for first order logic. -/\nclass fact (p : Prop) : Prop := (out [] : p)\n\n/--\nIn most cases, we should not have global instances of `fact`; typeclass search only reads the head\nsymbol and then tries any instances, which means that adding any such instance will cause slowdowns\neverywhere. We instead make them as lemmata and make them local instances as required.\n-/\nlibrary_note \"fact non-instances\"\n\nlemma fact.elim {p : Prop} (h : fact p) : p := h.1\nlemma fact_iff {p : Prop} : fact p ↔ p := ⟨λ h, h.1, λ h, ⟨h⟩⟩\n\nend miscellany\n\n/-!\n### Declarations about propositional connectives\n-/\n\ntheorem false_ne_true : false ≠ true\n| h := h.symm ▸ trivial\n\nsection propositional\nvariables {a b c d : Prop}\n\n/-! ### Declarations about `implies` -/\n\ninstance : is_refl Prop iff := ⟨iff.refl⟩\ninstance : is_trans Prop iff := ⟨λ _ _ _, iff.trans⟩\n\ntheorem iff_of_eq (e : a = b) : a ↔ b := e ▸ iff.rfl\n\ntheorem iff_iff_eq : (a ↔ b) ↔ a = b := ⟨propext, iff_of_eq⟩\n\n@[simp] lemma eq_iff_iff {p q : Prop} : (p = q) ↔ (p ↔ q) := iff_iff_eq.symm\n\n@[simp] theorem imp_self : (a → a) ↔ true := iff_true_intro id\n\ntheorem imp_intro {α β : Prop} (h : α) : β → α := λ _, h\n\ntheorem imp_false : (a → false) ↔ ¬ a := iff.rfl\n\ntheorem imp_and_distrib {α} : (α → b ∧ c) ↔ (α → b) ∧ (α → c) :=\n⟨λ h, ⟨λ ha, (h ha).left, λ ha, (h ha).right⟩,\n λ h ha, ⟨h.left ha, h.right ha⟩⟩\n\n@[simp] theorem and_imp : (a ∧ b → c) ↔ (a → b → c) :=\niff.intro (λ h ha hb, h ⟨ha, hb⟩) (λ h ⟨ha, hb⟩, h ha hb)\n\ntheorem iff_def : (a ↔ b) ↔ (a → b) ∧ (b → a) :=\niff_iff_implies_and_implies _ _\n\ntheorem iff_def' : (a ↔ b) ↔ (b → a) ∧ (a → b) :=\niff_def.trans and.comm\n\ntheorem imp_true_iff {α : Sort*} : (α → true) ↔ true :=\niff_true_intro $ λ_, trivial\n\ntheorem imp_iff_right (ha : a) : (a → b) ↔ b :=\n⟨λf, f ha, imp_intro⟩\n\ntheorem decidable.imp_iff_right_iff [decidable a] : ((a → b) ↔ b) ↔ (a ∨ b) :=\n⟨λ H, (decidable.em a).imp_right $ λ ha', H.1 $ λ ha, (ha' ha).elim,\n λ H, H.elim imp_iff_right $ λ hb, ⟨λ hab, hb, λ _ _, hb⟩⟩\n\n@[simp] theorem imp_iff_right_iff : ((a → b) ↔ b) ↔ (a ∨ b) :=\ndecidable.imp_iff_right_iff\n\n/-! ### Declarations about `not` -/\n\n/-- Ex falso for negation. From `¬ a` and `a` anything follows. This is the same as `absurd` with\nthe arguments flipped, but it is in the `not` namespace so that projection notation can be used. -/\ndef not.elim {α : Sort*} (H1 : ¬a) (H2 : a) : α := absurd H2 H1\n\n@[reducible] theorem not.imp {a b : Prop} (H2 : ¬b) (H1 : a → b) : ¬a := mt H1 H2\n\ntheorem not_not_of_not_imp : ¬(a → b) → ¬¬a :=\nmt not.elim\n\ntheorem not_of_not_imp {a : Prop} : ¬(a → b) → ¬b :=\nmt imp_intro\n\ntheorem dec_em (p : Prop) [decidable p] : p ∨ ¬p := decidable.em p\n\ntheorem dec_em' (p : Prop) [decidable p] : ¬p ∨ p := (dec_em p).swap\n\ntheorem em (p : Prop) : p ∨ ¬p := classical.em _\n\ntheorem em' (p : Prop) : ¬p ∨ p := (em p).swap\n\ntheorem or_not {p : Prop} : p ∨ ¬p := em _\n\nsection eq_or_ne\n\nvariables {α : Sort*} (x y : α)\n\ntheorem decidable.eq_or_ne [decidable (x = y)] : x = y ∨ x ≠ y := dec_em $ x = y\n\ntheorem decidable.ne_or_eq [decidable (x = y)] : x ≠ y ∨ x = y := dec_em' $ x = y\n\ntheorem eq_or_ne : x = y ∨ x ≠ y := em $ x = y\n\ntheorem ne_or_eq : x ≠ y ∨ x = y := em' $ x = y\n\nend eq_or_ne\n\ntheorem by_contradiction {p} : (¬p → false) → p := decidable.by_contradiction\n\n-- alias by_contradiction ← by_contra\ntheorem by_contra {p} : (¬p → false) → p := decidable.by_contradiction\n\n/--\nIn most of mathlib, we use the law of excluded middle (LEM) and the axiom of choice (AC) freely.\nThe `decidable` namespace contains versions of lemmas from the root namespace that explicitly\nattempt to avoid the axiom of choice, usually by adding decidability assumptions on the inputs.\n\nYou can check if a lemma uses the axiom of choice by using `#print axioms foo` and seeing if\n`classical.choice` appears in the list.\n-/\nlibrary_note \"decidable namespace\"\n\n/--\nAs mathlib is primarily classical,\nif the type signature of a `def` or `lemma` does not require any `decidable` instances to state,\nit is preferable not to introduce any `decidable` instances that are needed in the proof\nas arguments, but rather to use the `classical` tactic as needed.\n\nIn the other direction, when `decidable` instances do appear in the type signature,\nit is better to use explicitly introduced ones rather than allowing Lean to automatically infer\nclassical ones, as these may cause instance mismatch errors later.\n-/\nlibrary_note \"decidable arguments\"\n\n-- See Note [decidable namespace]\nprotected theorem decidable.not_not [decidable a] : ¬¬a ↔ a :=\niff.intro decidable.by_contradiction not_not_intro\n\n/-- The Double Negation Theorem: `¬ ¬ P` is equivalent to `P`.\nThe left-to-right direction, double negation elimination (DNE),\nis classically true but not constructively. -/\n@[simp] theorem not_not : ¬¬a ↔ a := decidable.not_not\n\ntheorem of_not_not : ¬¬a → a := by_contra\n\n-- See Note [decidable namespace]\nprotected theorem decidable.of_not_imp [decidable a] (h : ¬ (a → b)) : a :=\ndecidable.by_contradiction (not_not_of_not_imp h)\n\ntheorem of_not_imp : ¬ (a → b) → a := decidable.of_not_imp\n\n-- See Note [decidable namespace]\nprotected theorem decidable.not_imp_symm [decidable a] (h : ¬a → b) (hb : ¬b) : a :=\ndecidable.by_contradiction $ hb ∘ h\n\ntheorem not.decidable_imp_symm [decidable a] : (¬a → b) → ¬b → a := decidable.not_imp_symm\n\ntheorem not.imp_symm : (¬a → b) → ¬b → a := not.decidable_imp_symm\n\n-- See Note [decidable namespace]\nprotected theorem decidable.not_imp_comm [decidable a] [decidable b] : (¬a → b) ↔ (¬b → a) :=\n⟨not.decidable_imp_symm, not.decidable_imp_symm⟩\n\ntheorem not_imp_comm : (¬a → b) ↔ (¬b → a) := decidable.not_imp_comm\n\n@[simp] theorem imp_not_self : (a → ¬a) ↔ ¬a := ⟨λ h ha, h ha ha, λ h _, h⟩\n\ntheorem decidable.not_imp_self [decidable a] : (¬a → a) ↔ a :=\nby { have := @imp_not_self (¬a), rwa decidable.not_not at this }\n\n@[simp] theorem not_imp_self : (¬a → a) ↔ a := decidable.not_imp_self\n\ntheorem imp.swap : (a → b → c) ↔ (b → a → c) :=\n⟨swap, swap⟩\n\ntheorem imp_not_comm : (a → ¬b) ↔ (b → ¬a) :=\nimp.swap\n\n/-! ### Declarations about `xor` -/\n\n@[simp] theorem xor_true : xor true = not := funext $ λ a, by simp [xor]\n\n@[simp] theorem xor_false : xor false = id := funext $ λ a, by simp [xor]\n\ntheorem xor_comm (a b) : xor a b = xor b a := by simp [xor, and_comm, or_comm]\n\ninstance : is_commutative Prop xor := ⟨xor_comm⟩\n\n@[simp] theorem xor_self (a : Prop) : xor a a = false := by simp [xor]\n\n/-! ### Declarations about `and` -/\n\ntheorem and_congr_left (h : c → (a ↔ b)) : a ∧ c ↔ b ∧ c :=\nand.comm.trans $ (and_congr_right h).trans and.comm\n\ntheorem and_congr_left' (h : a ↔ b) : a ∧ c ↔ b ∧ c := and_congr h iff.rfl\n\ntheorem and_congr_right' (h : b ↔ c) : a ∧ b ↔ a ∧ c := and_congr iff.rfl h\n\ntheorem not_and_of_not_left (b : Prop) : ¬a → ¬(a ∧ b) :=\nmt and.left\n\ntheorem not_and_of_not_right (a : Prop) {b : Prop} : ¬b → ¬(a ∧ b) :=\nmt and.right\n\ntheorem and.imp_left (h : a → b) : a ∧ c → b ∧ c :=\nand.imp h id\n\ntheorem and.imp_right (h : a → b) : c ∧ a → c ∧ b :=\nand.imp id h\n\nlemma and.right_comm : (a ∧ b) ∧ c ↔ (a ∧ c) ∧ b :=\nby simp only [and.left_comm, and.comm]\n\nlemma and_and_and_comm (a b c d : Prop) : (a ∧ b) ∧ c ∧ d ↔ (a ∧ c) ∧ b ∧ d :=\nby rw [←and_assoc, @and.right_comm a, and_assoc]\n\nlemma and.rotate : a ∧ b ∧ c ↔ b ∧ c ∧ a :=\nby simp only [and.left_comm, and.comm]\n\ntheorem and_not_self_iff (a : Prop) : a ∧ ¬ a ↔ false :=\niff.intro (assume h, (h.right) (h.left)) (assume h, h.elim)\n\ntheorem not_and_self_iff (a : Prop) : ¬ a ∧ a ↔ false :=\niff.intro (assume ⟨hna, ha⟩, hna ha) false.elim\n\ntheorem and_iff_left_of_imp {a b : Prop} (h : a → b) : (a ∧ b) ↔ a :=\niff.intro and.left (λ ha, ⟨ha, h ha⟩)\n\ntheorem and_iff_right_of_imp {a b : Prop} (h : b → a) : (a ∧ b) ↔ b :=\niff.intro and.right (λ hb, ⟨h hb, hb⟩)\n\n@[simp] theorem and_iff_left_iff_imp {a b : Prop} : ((a ∧ b) ↔ a) ↔ (a → b) :=\n⟨λ h ha, (h.2 ha).2, and_iff_left_of_imp⟩\n\n@[simp] theorem and_iff_right_iff_imp {a b : Prop} : ((a ∧ b) ↔ b) ↔ (b → a) :=\n⟨λ h ha, (h.2 ha).1, and_iff_right_of_imp⟩\n\n@[simp] lemma iff_self_and {p q : Prop} : (p ↔ p ∧ q) ↔ (p → q) :=\nby rw [@iff.comm p, and_iff_left_iff_imp]\n\n@[simp] lemma iff_and_self {p q : Prop} : (p ↔ q ∧ p) ↔ (p → q) :=\nby rw [and_comm, iff_self_and]\n\n@[simp] lemma and.congr_right_iff : (a ∧ b ↔ a ∧ c) ↔ (a → (b ↔ c)) :=\n⟨λ h ha, by simp [ha] at h; exact h, and_congr_right⟩\n\n@[simp] lemma and.congr_left_iff : (a ∧ c ↔ b ∧ c) ↔ c → (a ↔ b) :=\nby simp only [and.comm, ← and.congr_right_iff]\n\n@[simp] lemma and_self_left : a ∧ a ∧ b ↔ a ∧ b :=\n⟨λ h, ⟨h.1, h.2.2⟩, λ h, ⟨h.1, h.1, h.2⟩⟩\n\n@[simp] lemma and_self_right : (a ∧ b) ∧ b ↔ a ∧ b :=\n⟨λ h, ⟨h.1.1, h.2⟩, λ h, ⟨⟨h.1, h.2⟩, h.2⟩⟩\n\n/-! ### Declarations about `or` -/\n\ntheorem or_congr_left (h : a ↔ b) : a ∨ c ↔ b ∨ c := or_congr h iff.rfl\n\ntheorem or_congr_right (h : b ↔ c) : a ∨ b ↔ a ∨ c := or_congr iff.rfl h\n\ntheorem or.right_comm : (a ∨ b) ∨ c ↔ (a ∨ c) ∨ b := by rw [or_assoc, or_assoc, or_comm b]\n\ntheorem or_of_or_of_imp_of_imp (h₁ : a ∨ b) (h₂ : a → c) (h₃ : b → d) : c ∨ d :=\nor.imp h₂ h₃ h₁\n\ntheorem or_of_or_of_imp_left (h₁ : a ∨ c) (h : a → b) : b ∨ c :=\nor.imp_left h h₁\n\ntheorem or_of_or_of_imp_right (h₁ : c ∨ a) (h : a → b) : c ∨ b :=\nor.imp_right h h₁\n\ntheorem or.elim3 (h : a ∨ b ∨ c) (ha : a → d) (hb : b → d) (hc : c → d) : d :=\nor.elim h ha (assume h₂, or.elim h₂ hb hc)\n\ntheorem or_imp_distrib : (a ∨ b → c) ↔ (a → c) ∧ (b → c) :=\n⟨assume h, ⟨assume ha, h (or.inl ha), assume hb, h (or.inr hb)⟩,\n assume ⟨ha, hb⟩, or.rec ha hb⟩\n\n-- See Note [decidable namespace]\nprotected theorem decidable.or_iff_not_imp_left [decidable a] : a ∨ b ↔ (¬ a → b) :=\n⟨or.resolve_left, λ h, dite _ or.inl (or.inr ∘ h)⟩\n\ntheorem or_iff_not_imp_left : a ∨ b ↔ (¬ a → b) := decidable.or_iff_not_imp_left\n\n-- See Note [decidable namespace]\nprotected theorem decidable.or_iff_not_imp_right [decidable b] : a ∨ b ↔ (¬ b → a) :=\nor.comm.trans decidable.or_iff_not_imp_left\n\ntheorem or_iff_not_imp_right : a ∨ b ↔ (¬ b → a) := decidable.or_iff_not_imp_right\n\n-- See Note [decidable namespace]\nprotected theorem decidable.not_imp_not [decidable a] : (¬ a → ¬ b) ↔ (b → a) :=\n⟨assume h hb, decidable.by_contradiction $ assume na, h na hb, mt⟩\n\ntheorem not_imp_not : (¬ a → ¬ b) ↔ (b → a) := decidable.not_imp_not\n\n@[simp] theorem or_iff_left_iff_imp : (a ∨ b ↔ a) ↔ (b → a) :=\n⟨λ h hb, h.1 (or.inr hb), or_iff_left_of_imp⟩\n\n@[simp] theorem or_iff_right_iff_imp : (a ∨ b ↔ b) ↔ (a → b) :=\nby rw [or_comm, or_iff_left_iff_imp]\n\n/-! ### Declarations about distributivity -/\n\n/-- `∧` distributes over `∨` (on the left). -/\ntheorem and_or_distrib_left : a ∧ (b ∨ c) ↔ (a ∧ b) ∨ (a ∧ c) :=\n⟨λ ⟨ha, hbc⟩, hbc.imp (and.intro ha) (and.intro ha),\n or.rec (and.imp_right or.inl) (and.imp_right or.inr)⟩\n\n/-- `∧` distributes over `∨` (on the right). -/\ntheorem or_and_distrib_right : (a ∨ b) ∧ c ↔ (a ∧ c) ∨ (b ∧ c) :=\n(and.comm.trans and_or_distrib_left).trans (or_congr and.comm and.comm)\n\n/-- `∨` distributes over `∧` (on the left). -/\ntheorem or_and_distrib_left : a ∨ (b ∧ c) ↔ (a ∨ b) ∧ (a ∨ c) :=\n⟨or.rec (λha, and.intro (or.inl ha) (or.inl ha)) (and.imp or.inr or.inr),\n and.rec $ or.rec (imp_intro ∘ or.inl) (or.imp_right ∘ and.intro)⟩\n\n/-- `∨` distributes over `∧` (on the right). -/\ntheorem and_or_distrib_right : (a ∧ b) ∨ c ↔ (a ∨ c) ∧ (b ∨ c) :=\n(or.comm.trans or_and_distrib_left).trans (and_congr or.comm or.comm)\n\n@[simp] lemma or_self_left : a ∨ a ∨ b ↔ a ∨ b :=\n⟨λ h, h.elim or.inl id, λ h, h.elim or.inl (or.inr ∘ or.inr)⟩\n\n@[simp] lemma or_self_right : (a ∨ b) ∨ b ↔ a ∨ b :=\n⟨λ h, h.elim id or.inr, λ h, h.elim (or.inl ∘ or.inl) or.inr⟩\n\n/-! Declarations about `iff` -/\n\ntheorem iff_of_true (ha : a) (hb : b) : a ↔ b :=\n⟨λ_, hb, λ _, ha⟩\n\ntheorem iff_of_false (ha : ¬a) (hb : ¬b) : a ↔ b :=\n⟨ha.elim, hb.elim⟩\n\ntheorem iff_true_left (ha : a) : (a ↔ b) ↔ b :=\n⟨λ h, h.1 ha, iff_of_true ha⟩\n\ntheorem iff_true_right (ha : a) : (b ↔ a) ↔ b :=\niff.comm.trans (iff_true_left ha)\n\ntheorem iff_false_left (ha : ¬a) : (a ↔ b) ↔ ¬b :=\n⟨λ h, mt h.2 ha, iff_of_false ha⟩\n\ntheorem iff_false_right (ha : ¬a) : (b ↔ a) ↔ ¬b :=\niff.comm.trans (iff_false_left ha)\n\n@[simp]\nlemma iff_mpr_iff_true_intro {P : Prop} (h : P) : iff.mpr (iff_true_intro h) true.intro = h := rfl\n\n-- See Note [decidable namespace]\nprotected theorem decidable.not_or_of_imp [decidable a] (h : a → b) : ¬ a ∨ b :=\nif ha : a then or.inr (h ha) else or.inl ha\n\ntheorem not_or_of_imp : (a → b) → ¬ a ∨ b := decidable.not_or_of_imp\n\n-- See Note [decidable namespace]\nprotected theorem decidable.imp_iff_not_or [decidable a] : (a → b) ↔ (¬ a ∨ b) :=\n⟨decidable.not_or_of_imp, or.neg_resolve_left⟩\n\ntheorem imp_iff_not_or : (a → b) ↔ (¬ a ∨ b) := decidable.imp_iff_not_or\n\n-- See Note [decidable namespace]\nprotected theorem decidable.imp_or_distrib [decidable a] : (a → b ∨ c) ↔ (a → b) ∨ (a → c) :=\nby simp [decidable.imp_iff_not_or, or.comm, or.left_comm]\n\ntheorem imp_or_distrib : (a → b ∨ c) ↔ (a → b) ∨ (a → c) := decidable.imp_or_distrib\n\n-- See Note [decidable namespace]\nprotected theorem decidable.imp_or_distrib' [decidable b] : (a → b ∨ c) ↔ (a → b) ∨ (a → c) :=\nby by_cases b; simp [h, or_iff_right_of_imp ((∘) false.elim)]\n\ntheorem imp_or_distrib' : (a → b ∨ c) ↔ (a → b) ∨ (a → c) := decidable.imp_or_distrib'\n\ntheorem not_imp_of_and_not : a ∧ ¬ b → ¬ (a → b)\n| ⟨ha, hb⟩ h := hb $ h ha\n\n-- See Note [decidable namespace]\nprotected theorem decidable.not_imp [decidable a] : ¬(a → b) ↔ a ∧ ¬b :=\n⟨λ h, ⟨decidable.of_not_imp h, not_of_not_imp h⟩, not_imp_of_and_not⟩\n\ntheorem not_imp : ¬(a → b) ↔ a ∧ ¬b := decidable.not_imp\n\n-- for monotonicity\nlemma imp_imp_imp (h₀ : c → a) (h₁ : b → d) : (a → b) → (c → d) :=\nassume (h₂ : a → b), h₁ ∘ h₂ ∘ h₀\n\n-- See Note [decidable namespace]\nprotected theorem decidable.peirce (a b : Prop) [decidable a] : ((a → b) → a) → a :=\nif ha : a then λ h, ha else λ h, h ha.elim\n\ntheorem peirce (a b : Prop) : ((a → b) → a) → a := decidable.peirce _ _\n\ntheorem peirce' {a : Prop} (H : ∀ b : Prop, (a → b) → a) : a := H _ id\n\n-- See Note [decidable namespace]\nprotected theorem decidable.not_iff_not [decidable a] [decidable b] : (¬ a ↔ ¬ b) ↔ (a ↔ b) :=\nby rw [@iff_def (¬ a), @iff_def' a]; exact and_congr decidable.not_imp_not decidable.not_imp_not\n\ntheorem not_iff_not : (¬ a ↔ ¬ b) ↔ (a ↔ b) := decidable.not_iff_not\n\n-- See Note [decidable namespace]\nprotected theorem decidable.not_iff_comm [decidable a] [decidable b] : (¬ a ↔ b) ↔ (¬ b ↔ a) :=\nby rw [@iff_def (¬ a), @iff_def (¬ b)]; exact and_congr decidable.not_imp_comm imp_not_comm\n\ntheorem not_iff_comm : (¬ a ↔ b) ↔ (¬ b ↔ a) := decidable.not_iff_comm\n\n-- See Note [decidable namespace]\nprotected theorem decidable.not_iff : ∀ [decidable b], ¬ (a ↔ b) ↔ (¬ a ↔ b) :=\nby intro h; cases h; simp only [h, iff_true, iff_false]\n\ntheorem not_iff : ¬ (a ↔ b) ↔ (¬ a ↔ b) := decidable.not_iff\n\n-- See Note [decidable namespace]\nprotected theorem decidable.iff_not_comm [decidable a] [decidable b] : (a ↔ ¬ b) ↔ (b ↔ ¬ a) :=\nby rw [@iff_def a, @iff_def b]; exact and_congr imp_not_comm decidable.not_imp_comm\n\ntheorem iff_not_comm : (a ↔ ¬ b) ↔ (b ↔ ¬ a) := decidable.iff_not_comm\n\n-- See Note [decidable namespace]\nprotected theorem decidable.iff_iff_and_or_not_and_not [decidable b] :\n (a ↔ b) ↔ (a ∧ b) ∨ (¬ a ∧ ¬ b) :=\nby { split; intro h,\n { rw h; by_cases b; [left,right]; split; assumption },\n { cases h with h h; cases h; split; intro; { contradiction <|> assumption } } }\n\ntheorem iff_iff_and_or_not_and_not : (a ↔ b) ↔ (a ∧ b) ∨ (¬ a ∧ ¬ b) :=\ndecidable.iff_iff_and_or_not_and_not\n\nlemma decidable.iff_iff_not_or_and_or_not [decidable a] [decidable b] :\n (a ↔ b) ↔ ((¬a ∨ b) ∧ (a ∨ ¬b)) :=\nbegin\n rw [iff_iff_implies_and_implies a b],\n simp only [decidable.imp_iff_not_or, or.comm]\nend\n\nlemma iff_iff_not_or_and_or_not : (a ↔ b) ↔ ((¬a ∨ b) ∧ (a ∨ ¬b)) :=\ndecidable.iff_iff_not_or_and_or_not\n\n-- See Note [decidable namespace]\nprotected theorem decidable.not_and_not_right [decidable b] : ¬(a ∧ ¬b) ↔ (a → b) :=\n⟨λ h ha, h.decidable_imp_symm $ and.intro ha, λ h ⟨ha, hb⟩, hb $ h ha⟩\n\ntheorem not_and_not_right : ¬(a ∧ ¬b) ↔ (a → b) := decidable.not_and_not_right\n\n/-- Transfer decidability of `a` to decidability of `b`, if the propositions are equivalent.\n**Important**: this function should be used instead of `rw` on `decidable b`, because the\nkernel will get stuck reducing the usage of `propext` otherwise,\nand `dec_trivial` will not work. -/\n@[inline] def decidable_of_iff (a : Prop) (h : a ↔ b) [D : decidable a] : decidable b :=\ndecidable_of_decidable_of_iff D h\n\n/-- Transfer decidability of `b` to decidability of `a`, if the propositions are equivalent.\nThis is the same as `decidable_of_iff` but the iff is flipped. -/\n@[inline] def decidable_of_iff' (b : Prop) (h : a ↔ b) [D : decidable b] : decidable a :=\ndecidable_of_decidable_of_iff D h.symm\n\n/-- Prove that `a` is decidable by constructing a boolean `b` and a proof that `b ↔ a`.\n(This is sometimes taken as an alternate definition of decidability.) -/\ndef decidable_of_bool : ∀ (b : bool) (h : b ↔ a), decidable a\n| tt h := is_true (h.1 rfl)\n| ff h := is_false (mt h.2 bool.ff_ne_tt)\n\n/-! ### De Morgan's laws -/\n\ntheorem not_and_of_not_or_not (h : ¬ a ∨ ¬ b) : ¬ (a ∧ b)\n| ⟨ha, hb⟩ := or.elim h (absurd ha) (absurd hb)\n\n-- See Note [decidable namespace]\nprotected theorem decidable.not_and_distrib [decidable a] : ¬ (a ∧ b) ↔ ¬a ∨ ¬b :=\n⟨λ h, if ha : a then or.inr (λ hb, h ⟨ha, hb⟩) else or.inl ha, not_and_of_not_or_not⟩\n\n-- See Note [decidable namespace]\nprotected theorem decidable.not_and_distrib' [decidable b] : ¬ (a ∧ b) ↔ ¬a ∨ ¬b :=\n⟨λ h, if hb : b then or.inl (λ ha, h ⟨ha, hb⟩) else or.inr hb, not_and_of_not_or_not⟩\n\n/-- One of de Morgan's laws: the negation of a conjunction is logically equivalent to the\ndisjunction of the negations. -/\ntheorem not_and_distrib : ¬ (a ∧ b) ↔ ¬a ∨ ¬b := decidable.not_and_distrib\n\n@[simp] theorem not_and : ¬ (a ∧ b) ↔ (a → ¬ b) := and_imp\n\ntheorem not_and' : ¬ (a ∧ b) ↔ b → ¬a :=\nnot_and.trans imp_not_comm\n\n/-- One of de Morgan's laws: the negation of a disjunction is logically equivalent to the\nconjunction of the negations. -/\ntheorem not_or_distrib : ¬ (a ∨ b) ↔ ¬ a ∧ ¬ b :=\n⟨λ h, ⟨λ ha, h (or.inl ha), λ hb, h (or.inr hb)⟩,\n λ ⟨h₁, h₂⟩ h, or.elim h h₁ h₂⟩\n\n-- See Note [decidable namespace]\nprotected theorem decidable.or_iff_not_and_not [decidable a] [decidable b] : a ∨ b ↔ ¬ (¬a ∧ ¬b) :=\nby rw [← not_or_distrib, decidable.not_not]\n\ntheorem or_iff_not_and_not : a ∨ b ↔ ¬ (¬a ∧ ¬b) := decidable.or_iff_not_and_not\n\n-- See Note [decidable namespace]\nprotected theorem decidable.and_iff_not_or_not [decidable a] [decidable b] :\n a ∧ b ↔ ¬ (¬ a ∨ ¬ b) :=\nby rw [← decidable.not_and_distrib, decidable.not_not]\n\ntheorem and_iff_not_or_not : a ∧ b ↔ ¬ (¬ a ∨ ¬ b) := decidable.and_iff_not_or_not\n\nend propositional\n\n/-! ### Declarations about equality -/\n\nsection equality\nvariables {α : Sort*} {a b : α}\n\n@[simp] theorem heq_iff_eq : a == b ↔ a = b :=\n⟨eq_of_heq, heq_of_eq⟩\n\ntheorem proof_irrel_heq {p q : Prop} (hp : p) (hq : q) : hp == hq :=\nhave p = q, from propext ⟨λ _, hq, λ _, hp⟩,\nby subst q; refl\n\ntheorem ne_of_mem_of_not_mem {α β} [has_mem α β] {s : β} {a b : α}\n (h : a ∈ s) : b ∉ s → a ≠ b :=\nmt $ λ e, e ▸ h\n\nlemma ne_of_apply_ne {α β : Sort*} (f : α → β) {x y : α} (h : f x ≠ f y) : x ≠ y :=\nλ (w : x = y), h (congr_arg f w)\n\ntheorem eq_equivalence : equivalence (@eq α) :=\n⟨eq.refl, @eq.symm _, @eq.trans _⟩\n\n/-- Transport through trivial families is the identity. -/\n@[simp]\nlemma eq_rec_constant {α : Sort*} {a a' : α} {β : Sort*} (y : β) (h : a = a') :\n (@eq.rec α a (λ a, β) y a' h) = y :=\nby { cases h, refl, }\n\n@[simp]\nlemma eq_mp_eq_cast {α β : Sort*} (h : α = β) : eq.mp h = cast h := rfl\n\n@[simp]\nlemma eq_mpr_eq_cast {α β : Sort*} (h : α = β) : eq.mpr h = cast h.symm := rfl\n\n@[simp]\nlemma cast_cast : ∀ {α β γ : Sort*} (ha : α = β) (hb : β = γ) (a : α),\n cast hb (cast ha a) = cast (ha.trans hb) a\n| _ _ _ rfl rfl a := rfl\n\n@[simp] lemma congr_refl_left {α β : Sort*} (f : α → β) {a b : α} (h : a = b) :\n congr (eq.refl f) h = congr_arg f h :=\nrfl\n\n@[simp] lemma congr_refl_right {α β : Sort*} {f g : α → β} (h : f = g) (a : α) :\n congr h (eq.refl a) = congr_fun h a :=\nrfl\n\n@[simp] lemma congr_arg_refl {α β : Sort*} (f : α → β) (a : α) :\n congr_arg f (eq.refl a) = eq.refl (f a) :=\nrfl\n\n@[simp] lemma congr_fun_rfl {α β : Sort*} (f : α → β) (a : α) :\n congr_fun (eq.refl f) a = eq.refl (f a) :=\nrfl\n\n@[simp] lemma congr_fun_congr_arg {α β γ : Sort*} (f : α → β → γ) {a a' : α} (p : a = a') (b : β) :\n congr_fun (congr_arg f p) b = congr_arg (λ a, f a b) p :=\nrfl\n\nlemma heq_of_cast_eq :\n ∀ {α β : Sort*} {a : α} {a' : β} (e : α = β) (h₂ : cast e a = a'), a == a'\n| α ._ a a' rfl h := eq.rec_on h (heq.refl _)\n\nlemma cast_eq_iff_heq {α β : Sort*} {a : α} {a' : β} {e : α = β} : cast e a = a' ↔ a == a' :=\n⟨heq_of_cast_eq _, λ h, by cases h; refl⟩\n\nlemma rec_heq_of_heq {β} {C : α → Sort*} {x : C a} {y : β} (eq : a = b) (h : x == y) :\n @eq.rec α a C x b eq == y :=\nby subst eq; exact h\n\nprotected lemma eq.congr {x₁ x₂ y₁ y₂ : α} (h₁ : x₁ = y₁) (h₂ : x₂ = y₂) :\n (x₁ = x₂) ↔ (y₁ = y₂) :=\nby { subst h₁, subst h₂ }\n\nlemma eq.congr_left {x y z : α} (h : x = y) : x = z ↔ y = z := by rw [h]\nlemma eq.congr_right {x y z : α} (h : x = y) : z = x ↔ z = y := by rw [h]\n\nlemma congr_arg2 {α β γ : Sort*} (f : α → β → γ) {x x' : α} {y y' : β}\n (hx : x = x') (hy : y = y') : f x y = f x' y' :=\nby { subst hx, subst hy }\n\nend equality\n\n/-! ### Declarations about quantifiers -/\n\nsection quantifiers\nvariables {α : Sort*} {β : Sort*} {p q : α → Prop} {b : Prop}\n\nlemma forall_imp (h : ∀ a, p a → q a) : (∀ a, p a) → ∀ a, q a :=\nλ h' a, h a (h' a)\n\nlemma forall₂_congr {p q : α → β → Prop} (h : ∀ a b, p a b ↔ q a b) :\n (∀ a b, p a b) ↔ (∀ a b, q a b) :=\nforall_congr (λ a, forall_congr (h a))\n\nlemma forall₃_congr {γ : Sort*} {p q : α → β → γ → Prop}\n (h : ∀ a b c, p a b c ↔ q a b c) :\n (∀ a b c, p a b c) ↔ (∀ a b c, q a b c) :=\nforall_congr (λ a, forall₂_congr (h a))\n\nlemma forall₄_congr {γ δ : Sort*} {p q : α → β → γ → δ → Prop}\n (h : ∀ a b c d, p a b c d ↔ q a b c d) :\n (∀ a b c d, p a b c d) ↔ (∀ a b c d, q a b c d) :=\nforall_congr (λ a, forall₃_congr (h a))\n\nlemma Exists.imp (h : ∀ a, (p a → q a)) (p : ∃ a, p a) : ∃ a, q a := exists_imp_exists h p\n\nlemma exists_imp_exists' {p : α → Prop} {q : β → Prop} (f : α → β) (hpq : ∀ a, p a → q (f a))\n (hp : ∃ a, p a) : ∃ b, q b :=\nexists.elim hp (λ a hp', ⟨_, hpq _ hp'⟩)\n\nlemma exists₂_congr {p q : α → β → Prop} (h : ∀ a b, p a b ↔ q a b) :\n (∃ a b, p a b) ↔ (∃ a b, q a b) :=\nexists_congr (λ a, exists_congr (h a))\n\nlemma exists₃_congr {γ : Sort*} {p q : α → β → γ → Prop}\n (h : ∀ a b c, p a b c ↔ q a b c) :\n (∃ a b c, p a b c) ↔ (∃ a b c, q a b c) :=\nexists_congr (λ a, exists₂_congr (h a))\n\nlemma exists₄_congr {γ δ : Sort*} {p q : α → β → γ → δ → Prop}\n (h : ∀ a b c d, p a b c d ↔ q a b c d) :\n (∃ a b c d, p a b c d) ↔ (∃ a b c d, q a b c d) :=\nexists_congr (λ a, exists₃_congr (h a))\n\ntheorem forall_swap {p : α → β → Prop} : (∀ x y, p x y) ↔ ∀ y x, p x y :=\n⟨swap, swap⟩\n\n/-- We intentionally restrict the type of `α` in this lemma so that this is a safer to use in simp\nthan `forall_swap`. -/\nlemma imp_forall_iff {α : Type*} {p : Prop} {q : α → Prop} : (p → ∀ x, q x) ↔ (∀ x, p → q x) :=\nforall_swap\n\ntheorem exists_swap {p : α → β → Prop} : (∃ x y, p x y) ↔ ∃ y x, p x y :=\n⟨λ ⟨x, y, h⟩, ⟨y, x, h⟩, λ ⟨y, x, h⟩, ⟨x, y, h⟩⟩\n\n@[simp] theorem forall_exists_index {q : (∃ x, p x) → Prop} :\n (∀ h, q h) ↔ ∀ x (h : p x), q ⟨x, h⟩ :=\n⟨λ h x hpx, h ⟨x, hpx⟩, λ h ⟨x, hpx⟩, h x hpx⟩\n\ntheorem exists_imp_distrib : ((∃ x, p x) → b) ↔ ∀ x, p x → b :=\nforall_exists_index\n\n/--\nExtract an element from a existential statement, using `classical.some`.\n-/\n-- This enables projection notation.\n@[reducible] noncomputable def Exists.some {p : α → Prop} (P : ∃ a, p a) : α := classical.some P\n\n/--\nShow that an element extracted from `P : ∃ a, p a` using `P.some` satisfies `p`.\n-/\nlemma Exists.some_spec {p : α → Prop} (P : ∃ a, p a) : p (P.some) := classical.some_spec P\n\n--theorem forall_not_of_not_exists (h : ¬ ∃ x, p x) : ∀ x, ¬ p x :=\n--forall_imp_of_exists_imp h\n\ntheorem not_exists_of_forall_not (h : ∀ x, ¬ p x) : ¬ ∃ x, p x :=\nexists_imp_distrib.2 h\n\n@[simp] theorem not_exists : (¬ ∃ x, p x) ↔ ∀ x, ¬ p x :=\nexists_imp_distrib\n\ntheorem not_forall_of_exists_not : (∃ x, ¬ p x) → ¬ ∀ x, p x\n| ⟨x, hn⟩ h := hn (h x)\n\n-- See Note [decidable namespace]\nprotected theorem decidable.not_forall {p : α → Prop}\n [decidable (∃ x, ¬ p x)] [∀ x, decidable (p x)] : (¬ ∀ x, p x) ↔ ∃ x, ¬ p x :=\n⟨not.decidable_imp_symm $ λ nx x, nx.decidable_imp_symm $ λ h, ⟨x, h⟩,\n not_forall_of_exists_not⟩\n\n@[simp] theorem not_forall {p : α → Prop} : (¬ ∀ x, p x) ↔ ∃ x, ¬ p x := decidable.not_forall\n\n-- See Note [decidable namespace]\nprotected theorem decidable.not_forall_not [decidable (∃ x, p x)] :\n (¬ ∀ x, ¬ p x) ↔ ∃ x, p x :=\n(@decidable.not_iff_comm _ _ _ (decidable_of_iff (¬ ∃ x, p x) not_exists)).1 not_exists\n\ntheorem not_forall_not : (¬ ∀ x, ¬ p x) ↔ ∃ x, p x := decidable.not_forall_not\n\n-- See Note [decidable namespace]\nprotected theorem decidable.not_exists_not [∀ x, decidable (p x)] : (¬ ∃ x, ¬ p x) ↔ ∀ x, p x :=\nby simp [decidable.not_not]\n\n@[simp] theorem not_exists_not : (¬ ∃ x, ¬ p x) ↔ ∀ x, p x := decidable.not_exists_not\n\ntheorem forall_imp_iff_exists_imp [ha : nonempty α] : ((∀ x, p x) → b) ↔ ∃ x, p x → b :=\nlet ⟨a⟩ := ha in\n⟨λ h, not_forall_not.1 $ λ h', classical.by_cases (λ hb : b, h' a $ λ _, hb)\n (λ hb, hb $ h $ λ x, (not_imp.1 (h' x)).1), λ ⟨x, hx⟩ h, hx (h x)⟩\n\n-- TODO: duplicate of a lemma in core\ntheorem forall_true_iff : (α → true) ↔ true :=\nimplies_true_iff α\n\n-- Unfortunately this causes simp to loop sometimes, so we\n-- add the 2 and 3 cases as simp lemmas instead\ntheorem forall_true_iff' (h : ∀ a, p a ↔ true) : (∀ a, p a) ↔ true :=\niff_true_intro (λ _, of_iff_true (h _))\n\n@[simp] theorem forall_2_true_iff {β : α → Sort*} : (∀ a, β a → true) ↔ true :=\nforall_true_iff' $ λ _, forall_true_iff\n\n@[simp] theorem forall_3_true_iff {β : α → Sort*} {γ : Π a, β a → Sort*} :\n (∀ a (b : β a), γ a b → true) ↔ true :=\nforall_true_iff' $ λ _, forall_2_true_iff\n\nlemma exists_unique.exists {α : Sort*} {p : α → Prop} (h : ∃! x, p x) : ∃ x, p x :=\nexists.elim h (λ x hx, ⟨x, and.left hx⟩)\n\n@[simp] lemma exists_unique_iff_exists {α : Sort*} [subsingleton α] {p : α → Prop} :\n (∃! x, p x) ↔ ∃ x, p x :=\n⟨λ h, h.exists, Exists.imp $ λ x hx, ⟨hx, λ y _, subsingleton.elim y x⟩⟩\n\n@[simp] theorem forall_const (α : Sort*) [i : nonempty α] : (α → b) ↔ b :=\n⟨i.elim, λ hb x, hb⟩\n\n@[simp] theorem exists_const (α : Sort*) [i : nonempty α] : (∃ x : α, b) ↔ b :=\n⟨λ ⟨x, h⟩, h, i.elim exists.intro⟩\n\ntheorem exists_unique_const (α : Sort*) [i : nonempty α] [subsingleton α] :\n (∃! x : α, b) ↔ b :=\nby simp\n\ntheorem forall_and_distrib : (∀ x, p x ∧ q x) ↔ (∀ x, p x) ∧ (∀ x, q x) :=\n⟨λ h, ⟨λ x, (h x).left, λ x, (h x).right⟩, λ ⟨h₁, h₂⟩ x, ⟨h₁ x, h₂ x⟩⟩\n\ntheorem exists_or_distrib : (∃ x, p x ∨ q x) ↔ (∃ x, p x) ∨ (∃ x, q x) :=\n⟨λ ⟨x, hpq⟩, hpq.elim (λ hpx, or.inl ⟨x, hpx⟩) (λ hqx, or.inr ⟨x, hqx⟩),\n λ hepq, hepq.elim (λ ⟨x, hpx⟩, ⟨x, or.inl hpx⟩) (λ ⟨x, hqx⟩, ⟨x, or.inr hqx⟩)⟩\n\n@[simp] theorem exists_and_distrib_left {q : Prop} {p : α → Prop} :\n (∃x, q ∧ p x) ↔ q ∧ (∃x, p x) :=\n⟨λ ⟨x, hq, hp⟩, ⟨hq, x, hp⟩, λ ⟨hq, x, hp⟩, ⟨x, hq, hp⟩⟩\n\n@[simp] theorem exists_and_distrib_right {q : Prop} {p : α → Prop} :\n (∃x, p x ∧ q) ↔ (∃x, p x) ∧ q :=\nby simp [and_comm]\n\n@[simp] theorem forall_eq {a' : α} : (∀a, a = a' → p a) ↔ p a' :=\n⟨λ h, h a' rfl, λ h a e, e.symm ▸ h⟩\n\n@[simp] theorem forall_eq' {a' : α} : (∀a, a' = a → p a) ↔ p a' :=\nby simp [@eq_comm _ a']\n\ntheorem and_forall_ne (a : α) : (p a ∧ ∀ b ≠ a, p b) ↔ ∀ b, p b :=\nby simp only [← @forall_eq _ p a, ← forall_and_distrib, ← or_imp_distrib, classical.em,\n forall_const]\n\n-- this lemma is needed to simplify the output of `list.mem_cons_iff`\n@[simp] theorem forall_eq_or_imp {a' : α} : (∀ a, a = a' ∨ q a → p a) ↔ p a' ∧ ∀ a, q a → p a :=\nby simp only [or_imp_distrib, forall_and_distrib, forall_eq]\n\ntheorem exists_eq {a' : α} : ∃ a, a = a' := ⟨_, rfl⟩\n\n@[simp] theorem exists_eq' {a' : α} : ∃ a, a' = a := ⟨_, rfl⟩\n\n@[simp] theorem exists_unique_eq {a' : α} : ∃! a, a = a' :=\nby simp only [eq_comm, exists_unique, and_self, forall_eq', exists_eq']\n\n@[simp] theorem exists_unique_eq' {a' : α} : ∃! a, a' = a :=\nby simp only [exists_unique, and_self, forall_eq', exists_eq']\n\n@[simp] theorem exists_eq_left {a' : α} : (∃ a, a = a' ∧ p a) ↔ p a' :=\n⟨λ ⟨a, e, h⟩, e ▸ h, λ h, ⟨_, rfl, h⟩⟩\n\n@[simp] theorem exists_eq_right {a' : α} : (∃ a, p a ∧ a = a') ↔ p a' :=\n(exists_congr $ by exact λ a, and.comm).trans exists_eq_left\n\n@[simp] theorem exists_eq_right_right {a' : α} :\n (∃ (a : α), p a ∧ b ∧ a = a') ↔ p a' ∧ b :=\n⟨λ ⟨_, hp, hq, rfl⟩, ⟨hp, hq⟩, λ ⟨hp, hq⟩, ⟨a', hp, hq, rfl⟩⟩\n\n@[simp] theorem exists_eq_right_right' {a' : α} :\n (∃ (a : α), p a ∧ b ∧ a' = a) ↔ p a' ∧ b :=\n⟨λ ⟨_, hp, hq, rfl⟩, ⟨hp, hq⟩, λ ⟨hp, hq⟩, ⟨a', hp, hq, rfl⟩⟩\n\n@[simp] theorem exists_apply_eq_apply (f : α → β) (a' : α) : ∃ a, f a = f a' := ⟨a', rfl⟩\n\n@[simp] theorem exists_apply_eq_apply' (f : α → β) (a' : α) : ∃ a, f a' = f a := ⟨a', rfl⟩\n\n@[simp] theorem exists_exists_and_eq_and {f : α → β} {p : α → Prop} {q : β → Prop} :\n (∃ b, (∃ a, p a ∧ f a = b) ∧ q b) ↔ ∃ a, p a ∧ q (f a) :=\n⟨λ ⟨b, ⟨a, ha, hab⟩, hb⟩, ⟨a, ha, hab.symm ▸ hb⟩, λ ⟨a, hp, hq⟩, ⟨f a, ⟨a, hp, rfl⟩, hq⟩⟩\n\n@[simp] theorem exists_exists_eq_and {f : α → β} {p : β → Prop} :\n (∃ b, (∃ a, f a = b) ∧ p b) ↔ ∃ a, p (f a) :=\n⟨λ ⟨b, ⟨a, ha⟩, hb⟩, ⟨a, ha.symm ▸ hb⟩, λ ⟨a, ha⟩, ⟨f a, ⟨a, rfl⟩, ha⟩⟩\n\n@[simp] lemma exists_or_eq_left (y : α) (p : α → Prop) : ∃ (x : α), x = y ∨ p x :=\n⟨y, or.inl rfl⟩\n\n@[simp] lemma exists_or_eq_right (y : α) (p : α → Prop) : ∃ (x : α), p x ∨ x = y :=\n⟨y, or.inr rfl⟩\n\n@[simp] lemma exists_or_eq_left' (y : α) (p : α → Prop) : ∃ (x : α), y = x ∨ p x :=\n⟨y, or.inl rfl⟩\n\n@[simp] lemma exists_or_eq_right' (y : α) (p : α → Prop) : ∃ (x : α), p x ∨ y = x :=\n⟨y, or.inr rfl⟩\n\n@[simp] theorem forall_apply_eq_imp_iff {f : α → β} {p : β → Prop} :\n (∀ a, ∀ b, f a = b → p b) ↔ (∀ a, p (f a)) :=\n⟨λ h a, h a (f a) rfl, λ h a b hab, hab ▸ h a⟩\n\n@[simp] theorem forall_apply_eq_imp_iff' {f : α → β} {p : β → Prop} :\n (∀ b, ∀ a, f a = b → p b) ↔ (∀ a, p (f a)) :=\nby { rw forall_swap, simp }\n\n@[simp] theorem forall_eq_apply_imp_iff {f : α → β} {p : β → Prop} :\n (∀ a, ∀ b, b = f a → p b) ↔ (∀ a, p (f a)) :=\nby simp [@eq_comm _ _ (f _)]\n\n@[simp] theorem forall_eq_apply_imp_iff' {f : α → β} {p : β → Prop} :\n (∀ b, ∀ a, b = f a → p b) ↔ (∀ a, p (f a)) :=\nby { rw forall_swap, simp }\n\n@[simp] theorem forall_apply_eq_imp_iff₂ {f : α → β} {p : α → Prop} {q : β → Prop} :\n (∀ b, ∀ a, p a → f a = b → q b) ↔ ∀ a, p a → q (f a) :=\n⟨λ h a ha, h (f a) a ha rfl, λ h b a ha hb, hb ▸ h a ha⟩\n\n@[simp] theorem exists_eq_left' {a' : α} : (∃ a, a' = a ∧ p a) ↔ p a' :=\nby simp [@eq_comm _ a']\n\n@[simp] theorem exists_eq_right' {a' : α} : (∃ a, p a ∧ a' = a) ↔ p a' :=\nby simp [@eq_comm _ a']\n\ntheorem exists_comm {p : α → β → Prop} : (∃ a b, p a b) ↔ ∃ b a, p a b :=\n⟨λ ⟨a, b, h⟩, ⟨b, a, h⟩, λ ⟨b, a, h⟩, ⟨a, b, h⟩⟩\n\ntheorem and.exists {p q : Prop} {f : p ∧ q → Prop} : (∃ h, f h) ↔ ∃ hp hq, f ⟨hp, hq⟩ :=\n⟨λ ⟨h, H⟩, ⟨h.1, h.2, H⟩, λ ⟨hp, hq, H⟩, ⟨⟨hp, hq⟩, H⟩⟩\n\ntheorem forall_or_of_or_forall (h : b ∨ ∀x, p x) (x) : b ∨ p x :=\nh.imp_right $ λ h₂, h₂ x\n\n-- See Note [decidable namespace]\nprotected theorem decidable.forall_or_distrib_left {q : Prop} {p : α → Prop} [decidable q] :\n (∀x, q ∨ p x) ↔ q ∨ (∀x, p x) :=\n⟨λ h, if hq : q then or.inl hq else or.inr $ λ x, (h x).resolve_left hq,\n forall_or_of_or_forall⟩\n\ntheorem forall_or_distrib_left {q : Prop} {p : α → Prop} :\n (∀x, q ∨ p x) ↔ q ∨ (∀x, p x) := decidable.forall_or_distrib_left\n\n-- See Note [decidable namespace]\nprotected theorem decidable.forall_or_distrib_right {q : Prop} {p : α → Prop} [decidable q] :\n (∀x, p x ∨ q) ↔ (∀x, p x) ∨ q :=\nby simp [or_comm, decidable.forall_or_distrib_left]\n\ntheorem forall_or_distrib_right {q : Prop} {p : α → Prop} :\n (∀x, p x ∨ q) ↔ (∀x, p x) ∨ q := decidable.forall_or_distrib_right\n\n/-- A predicate holds everywhere on the image of a surjective functions iff\n it holds everywhere. -/\ntheorem forall_iff_forall_surj\n {α β : Type*} {f : α → β} (h : function.surjective f) {P : β → Prop} :\n (∀ a, P (f a)) ↔ ∀ b, P b :=\n⟨λ ha b, by cases h b with a hab; rw ←hab; exact ha a, λ hb a, hb $ f a⟩\n\n@[simp] theorem exists_prop {p q : Prop} : (∃ h : p, q) ↔ p ∧ q :=\n⟨λ ⟨h₁, h₂⟩, ⟨h₁, h₂⟩, λ ⟨h₁, h₂⟩, ⟨h₁, h₂⟩⟩\n\ntheorem exists_unique_prop {p q : Prop} : (∃! h : p, q) ↔ p ∧ q :=\nby simp\n\n@[simp] theorem exists_false : ¬ (∃a:α, false) := assume ⟨a, h⟩, h\n\n@[simp] lemma exists_unique_false : ¬ (∃! (a : α), false) := assume ⟨a, h, h'⟩, h\n\ntheorem Exists.fst {p : b → Prop} : Exists p → b\n| ⟨h, _⟩ := h\n\ntheorem Exists.snd {p : b → Prop} : ∀ h : Exists p, p h.fst\n| ⟨_, h⟩ := h\n\ntheorem forall_prop_of_true {p : Prop} {q : p → Prop} (h : p) : (∀ h' : p, q h') ↔ q h :=\n@forall_const (q h) p ⟨h⟩\n\ntheorem exists_prop_of_true {p : Prop} {q : p → Prop} (h : p) : (∃ h' : p, q h') ↔ q h :=\n@exists_const (q h) p ⟨h⟩\n\ntheorem exists_unique_prop_of_true {p : Prop} {q : p → Prop} (h : p) : (∃! h' : p, q h') ↔ q h :=\n@exists_unique_const (q h) p ⟨h⟩ _\n\ntheorem forall_prop_of_false {p : Prop} {q : p → Prop} (hn : ¬ p) :\n (∀ h' : p, q h') ↔ true :=\niff_true_intro $ λ h, hn.elim h\n\ntheorem exists_prop_of_false {p : Prop} {q : p → Prop} : ¬ p → ¬ (∃ h' : p, q h') :=\nmt Exists.fst\n\n@[congr] lemma exists_prop_congr {p p' : Prop} {q q' : p → Prop}\n (hq : ∀ h, q h ↔ q' h) (hp : p ↔ p') : Exists q ↔ ∃ h : p', q' (hp.2 h) :=\n⟨λ ⟨_, _⟩, ⟨hp.1 ‹_›, (hq _).1 ‹_›⟩, λ ⟨_, _⟩, ⟨_, (hq _).2 ‹_›⟩⟩\n\n@[congr] lemma exists_prop_congr' {p p' : Prop} {q q' : p → Prop}\n (hq : ∀ h, q h ↔ q' h) (hp : p ↔ p') : Exists q = ∃ h : p', q' (hp.2 h) :=\npropext (exists_prop_congr hq _)\n\n@[simp] lemma exists_true_left (p : true → Prop) : (∃ x, p x) ↔ p true.intro :=\nexists_prop_of_true _\n\n@[simp] lemma exists_false_left (p : false → Prop) : ¬ ∃ x, p x :=\nexists_prop_of_false not_false\n\nlemma exists_unique.unique {α : Sort*} {p : α → Prop} (h : ∃! x, p x)\n {y₁ y₂ : α} (py₁ : p y₁) (py₂ : p y₂) : y₁ = y₂ :=\nunique_of_exists_unique h py₁ py₂\n\n@[congr] lemma forall_prop_congr {p p' : Prop} {q q' : p → Prop}\n (hq : ∀ h, q h ↔ q' h) (hp : p ↔ p') : (∀ h, q h) ↔ ∀ h : p', q' (hp.2 h) :=\n⟨λ h1 h2, (hq _).1 (h1 (hp.2 _)), λ h1 h2, (hq _).2 (h1 (hp.1 h2))⟩\n\n@[congr] lemma forall_prop_congr' {p p' : Prop} {q q' : p → Prop}\n (hq : ∀ h, q h ↔ q' h) (hp : p ↔ p') : (∀ h, q h) = ∀ h : p', q' (hp.2 h) :=\npropext (forall_prop_congr hq _)\n\n@[simp] lemma forall_true_left (p : true → Prop) : (∀ x, p x) ↔ p true.intro :=\nforall_prop_of_true _\n\n@[simp] lemma forall_false_left (p : false → Prop) : (∀ x, p x) ↔ true :=\nforall_prop_of_false not_false\n\nlemma exists_unique.elim2 {α : Sort*} {p : α → Sort*} [∀ x, subsingleton (p x)]\n {q : Π x (h : p x), Prop} {b : Prop} (h₂ : ∃! x (h : p x), q x h)\n (h₁ : ∀ x (h : p x), q x h → (∀ y (hy : p y), q y hy → y = x) → b) : b :=\nbegin\n simp only [exists_unique_iff_exists] at h₂,\n apply h₂.elim,\n exact λ x ⟨hxp, hxq⟩ H, h₁ x hxp hxq (λ y hyp hyq, H y ⟨hyp, hyq⟩)\nend\n\nlemma exists_unique.intro2 {α : Sort*} {p : α → Sort*} [∀ x, subsingleton (p x)]\n {q : Π (x : α) (h : p x), Prop} (w : α) (hp : p w) (hq : q w hp)\n (H : ∀ y (hy : p y), q y hy → y = w) :\n ∃! x (hx : p x), q x hx :=\nbegin\n simp only [exists_unique_iff_exists],\n exact exists_unique.intro w ⟨hp, hq⟩ (λ y ⟨hyp, hyq⟩, H y hyp hyq)\nend\n\nlemma exists_unique.exists2 {α : Sort*} {p : α → Sort*} {q : Π (x : α) (h : p x), Prop}\n (h : ∃! x (hx : p x), q x hx) :\n ∃ x (hx : p x), q x hx :=\nh.exists.imp (λ x hx, hx.exists)\n\nlemma exists_unique.unique2 {α : Sort*} {p : α → Sort*} [∀ x, subsingleton (p x)]\n {q : Π (x : α) (hx : p x), Prop} (h : ∃! x (hx : p x), q x hx)\n {y₁ y₂ : α} (hpy₁ : p y₁) (hqy₁ : q y₁ hpy₁)\n (hpy₂ : p y₂) (hqy₂ : q y₂ hpy₂) : y₁ = y₂ :=\nbegin\n simp only [exists_unique_iff_exists] at h,\n exact h.unique ⟨hpy₁, hqy₁⟩ ⟨hpy₂, hqy₂⟩\nend\n\nend quantifiers\n\n/-! ### Classical lemmas -/\n\nnamespace classical\nvariables {α : Sort*} {p : α → Prop}\n\ntheorem cases {p : Prop → Prop} (h1 : p true) (h2 : p false) : ∀a, p a :=\nassume a, cases_on a h1 h2\n\n/- use shortened names to avoid conflict when classical namespace is open. -/\n/-- Any prop `p` is decidable classically. A shorthand for `classical.prop_decidable`. -/\nnoncomputable def dec (p : Prop) : decidable p :=\nby apply_instance\n/-- Any predicate `p` is decidable classically. -/\nnoncomputable def dec_pred (p : α → Prop) : decidable_pred p :=\nby apply_instance\n/-- Any relation `p` is decidable classically. -/\nnoncomputable def dec_rel (p : α → α → Prop) : decidable_rel p :=\nby apply_instance\n/-- Any type `α` has decidable equality classically. -/\nnoncomputable def dec_eq (α : Sort*) : decidable_eq α :=\nby apply_instance\n\n/-- Construct a function from a default value `H0`, and a function to use if there exists a value\nsatisfying the predicate. -/\n@[elab_as_eliminator]\nnoncomputable def {u} exists_cases {C : Sort u} (H0 : C) (H : ∀ a, p a → C) : C :=\nif h : ∃ a, p a then H (classical.some h) (classical.some_spec h) else H0\n\nlemma some_spec2 {α : Sort*} {p : α → Prop} {h : ∃a, p a}\n (q : α → Prop) (hpq : ∀a, p a → q a) : q (some h) :=\nhpq _ $ some_spec _\n\n/-- A version of classical.indefinite_description which is definitionally equal to a pair -/\nnoncomputable def subtype_of_exists {α : Type*} {P : α → Prop} (h : ∃ x, P x) : {x // P x} :=\n⟨classical.some h, classical.some_spec h⟩\n\n/-- A version of `by_contradiction` that uses types instead of propositions. -/\nprotected noncomputable def by_contradiction' {α : Sort*} (H : ¬ (α → false)) : α :=\nclassical.choice $ peirce _ false $ λ h, (H $ λ a, h ⟨a⟩).elim\n\n/-- `classical.by_contradiction'` is equivalent to lean's axiom `classical.choice`. -/\ndef choice_of_by_contradiction' {α : Sort*} (contra : ¬ (α → false) → α) : nonempty α → α :=\nλ H, contra H.elim\n\nend classical\n\n/-- This function has the same type as `exists.rec_on`, and can be used to case on an equality,\nbut `exists.rec_on` can only eliminate into Prop, while this version eliminates into any universe\nusing the axiom of choice. -/\n@[elab_as_eliminator]\nnoncomputable def {u} exists.classical_rec_on\n {α} {p : α → Prop} (h : ∃ a, p a) {C : Sort u} (H : ∀ a, p a → C) : C :=\nH (classical.some h) (classical.some_spec h)\n\n/-! ### Declarations about bounded quantifiers -/\n\nsection bounded_quantifiers\nvariables {α : Sort*} {r p q : α → Prop} {P Q : ∀ x, p x → Prop} {b : Prop}\n\ntheorem bex_def : (∃ x (h : p x), q x) ↔ ∃ x, p x ∧ q x :=\n⟨λ ⟨x, px, qx⟩, ⟨x, px, qx⟩, λ ⟨x, px, qx⟩, ⟨x, px, qx⟩⟩\n\ntheorem bex.elim {b : Prop} : (∃ x h, P x h) → (∀ a h, P a h → b) → b\n| ⟨a, h₁, h₂⟩ h' := h' a h₁ h₂\n\ntheorem bex.intro (a : α) (h₁ : p a) (h₂ : P a h₁) : ∃ x (h : p x), P x h :=\n⟨a, h₁, h₂⟩\n\ntheorem ball_congr (H : ∀ x h, P x h ↔ Q x h) :\n (∀ x h, P x h) ↔ (∀ x h, Q x h) :=\nforall_congr $ λ x, forall_congr (H x)\n\ntheorem bex_congr (H : ∀ x h, P x h ↔ Q x h) :\n (∃ x h, P x h) ↔ (∃ x h, Q x h) :=\nexists_congr $ λ x, exists_congr (H x)\n\ntheorem bex_eq_left {a : α} : (∃ x (_ : x = a), p x) ↔ p a :=\nby simp only [exists_prop, exists_eq_left]\n\ntheorem ball.imp_right (H : ∀ x h, (P x h → Q x h))\n (h₁ : ∀ x h, P x h) (x h) : Q x h :=\nH _ _ $ h₁ _ _\n\ntheorem bex.imp_right (H : ∀ x h, (P x h → Q x h)) :\n (∃ x h, P x h) → ∃ x h, Q x h\n| ⟨x, h, h'⟩ := ⟨_, _, H _ _ h'⟩\n\ntheorem ball.imp_left (H : ∀ x, p x → q x)\n (h₁ : ∀ x, q x → r x) (x) (h : p x) : r x :=\nh₁ _ $ H _ h\n\ntheorem bex.imp_left (H : ∀ x, p x → q x) :\n (∃ x (_ : p x), r x) → ∃ x (_ : q x), r x\n| ⟨x, hp, hr⟩ := ⟨x, H _ hp, hr⟩\n\ntheorem ball_of_forall (h : ∀ x, p x) (x) : p x :=\nh x\n\ntheorem forall_of_ball (H : ∀ x, p x) (h : ∀ x, p x → q x) (x) : q x :=\nh x $ H x\n\ntheorem bex_of_exists (H : ∀ x, p x) : (∃ x, q x) → ∃ x (_ : p x), q x\n| ⟨x, hq⟩ := ⟨x, H x, hq⟩\n\ntheorem exists_of_bex : (∃ x (_ : p x), q x) → ∃ x, q x\n| ⟨x, _, hq⟩ := ⟨x, hq⟩\n\n@[simp] theorem bex_imp_distrib : ((∃ x h, P x h) → b) ↔ (∀ x h, P x h → b) :=\nby simp\n\ntheorem not_bex : (¬ ∃ x h, P x h) ↔ ∀ x h, ¬ P x h :=\nbex_imp_distrib\n\ntheorem not_ball_of_bex_not : (∃ x h, ¬ P x h) → ¬ ∀ x h, P x h\n| ⟨x, h, hp⟩ al := hp $ al x h\n\n-- See Note [decidable namespace]\nprotected theorem decidable.not_ball [decidable (∃ x h, ¬ P x h)] [∀ x h, decidable (P x h)] :\n (¬ ∀ x h, P x h) ↔ (∃ x h, ¬ P x h) :=\n⟨not.decidable_imp_symm $ λ nx x h, nx.decidable_imp_symm $ λ h', ⟨x, h, h'⟩,\n not_ball_of_bex_not⟩\n\ntheorem not_ball : (¬ ∀ x h, P x h) ↔ (∃ x h, ¬ P x h) := decidable.not_ball\n\ntheorem ball_true_iff (p : α → Prop) : (∀ x, p x → true) ↔ true :=\niff_true_intro (λ h hrx, trivial)\n\ntheorem ball_and_distrib : (∀ x h, P x h ∧ Q x h) ↔ (∀ x h, P x h) ∧ (∀ x h, Q x h) :=\niff.trans (forall_congr $ λ x, forall_and_distrib) forall_and_distrib\n\ntheorem bex_or_distrib : (∃ x h, P x h ∨ Q x h) ↔ (∃ x h, P x h) ∨ (∃ x h, Q x h) :=\niff.trans (exists_congr $ λ x, exists_or_distrib) exists_or_distrib\n\ntheorem ball_or_left_distrib : (∀ x, p x ∨ q x → r x) ↔ (∀ x, p x → r x) ∧ (∀ x, q x → r x) :=\niff.trans (forall_congr $ λ x, or_imp_distrib) forall_and_distrib\n\ntheorem bex_or_left_distrib :\n (∃ x (_ : p x ∨ q x), r x) ↔ (∃ x (_ : p x), r x) ∨ (∃ x (_ : q x), r x) :=\nby simp only [exists_prop]; exact\niff.trans (exists_congr $ λ x, or_and_distrib_right) exists_or_distrib\n\nend bounded_quantifiers\n\nnamespace classical\nlocal attribute [instance] prop_decidable\n\ntheorem not_ball {α : Sort*} {p : α → Prop} {P : Π (x : α), p x → Prop} :\n (¬ ∀ x h, P x h) ↔ (∃ x h, ¬ P x h) := _root_.not_ball\n\nend classical\n\nlemma ite_eq_iff {α} {p : Prop} [decidable p] {a b c : α} :\n (if p then a else b) = c ↔ p ∧ a = c ∨ ¬p ∧ b = c :=\nby by_cases p; simp *\n\n@[simp] lemma ite_eq_left_iff {α} {p : Prop} [decidable p] {a b : α} :\n (if p then a else b) = a ↔ (¬p → b = a) :=\nby by_cases p; simp *\n\n@[simp] lemma ite_eq_right_iff {α} {p : Prop} [decidable p] {a b : α} :\n (if p then a else b) = b ↔ (p → a = b) :=\nby by_cases p; simp *\n\nlemma ite_eq_or_eq {α} {p : Prop} [decidable p] (a b : α) :\n ite p a b = a ∨ ite p a b = b :=\ndecidable.by_cases (λ h, or.inl (if_pos h)) (λ h, or.inr (if_neg h))\n\n/-! ### Declarations about `nonempty` -/\n\nsection nonempty\nvariables {α β : Type*} {γ : α → Type*}\n\nattribute [simp] nonempty_of_inhabited\n\n@[priority 20]\ninstance has_zero.nonempty [has_zero α] : nonempty α := ⟨0⟩\n@[priority 20]\ninstance has_one.nonempty [has_one α] : nonempty α := ⟨1⟩\n\nlemma exists_true_iff_nonempty {α : Sort*} : (∃a:α, true) ↔ nonempty α :=\niff.intro (λ⟨a, _⟩, ⟨a⟩) (λ⟨a⟩, ⟨a, trivial⟩)\n\n@[simp] lemma nonempty_Prop {p : Prop} : nonempty p ↔ p :=\niff.intro (assume ⟨h⟩, h) (assume h, ⟨h⟩)\n\nlemma not_nonempty_iff_imp_false {α : Sort*} : ¬ nonempty α ↔ α → false :=\n⟨λ h a, h ⟨a⟩, λ h ⟨a⟩, h a⟩\n\n@[simp] lemma nonempty_sigma : nonempty (Σa:α, γ a) ↔ (∃a:α, nonempty (γ a)) :=\niff.intro (assume ⟨⟨a, c⟩⟩, ⟨a, ⟨c⟩⟩) (assume ⟨a, ⟨c⟩⟩, ⟨⟨a, c⟩⟩)\n\n@[simp] lemma nonempty_subtype {α} {p : α → Prop} : nonempty (subtype p) ↔ (∃a:α, p a) :=\niff.intro (assume ⟨⟨a, h⟩⟩, ⟨a, h⟩) (assume ⟨a, h⟩, ⟨⟨a, h⟩⟩)\n\n@[simp] lemma nonempty_prod : nonempty (α × β) ↔ (nonempty α ∧ nonempty β) :=\niff.intro (assume ⟨⟨a, b⟩⟩, ⟨⟨a⟩, ⟨b⟩⟩) (assume ⟨⟨a⟩, ⟨b⟩⟩, ⟨⟨a, b⟩⟩)\n\n@[simp] lemma nonempty_pprod {α β} : nonempty (pprod α β) ↔ (nonempty α ∧ nonempty β) :=\niff.intro (assume ⟨⟨a, b⟩⟩, ⟨⟨a⟩, ⟨b⟩⟩) (assume ⟨⟨a⟩, ⟨b⟩⟩, ⟨⟨a, b⟩⟩)\n\n@[simp] lemma nonempty_sum : nonempty (α ⊕ β) ↔ (nonempty α ∨ nonempty β) :=\niff.intro\n (assume ⟨h⟩, match h with sum.inl a := or.inl ⟨a⟩ | sum.inr b := or.inr ⟨b⟩ end)\n (assume h, match h with or.inl ⟨a⟩ := ⟨sum.inl a⟩ | or.inr ⟨b⟩ := ⟨sum.inr b⟩ end)\n\n@[simp] lemma nonempty_psum {α β} : nonempty (psum α β) ↔ (nonempty α ∨ nonempty β) :=\niff.intro\n (assume ⟨h⟩, match h with psum.inl a := or.inl ⟨a⟩ | psum.inr b := or.inr ⟨b⟩ end)\n (assume h, match h with or.inl ⟨a⟩ := ⟨psum.inl a⟩ | or.inr ⟨b⟩ := ⟨psum.inr b⟩ end)\n\n@[simp] lemma nonempty_psigma {α} {β : α → Sort*} : nonempty (psigma β) ↔ (∃a:α, nonempty (β a)) :=\niff.intro (assume ⟨⟨a, c⟩⟩, ⟨a, ⟨c⟩⟩) (assume ⟨a, ⟨c⟩⟩, ⟨⟨a, c⟩⟩)\n\n@[simp] lemma nonempty_empty : ¬ nonempty empty :=\nassume ⟨h⟩, h.elim\n\n@[simp] lemma nonempty_ulift : nonempty (ulift α) ↔ nonempty α :=\niff.intro (assume ⟨⟨a⟩⟩, ⟨a⟩) (assume ⟨a⟩, ⟨⟨a⟩⟩)\n\n@[simp] lemma nonempty_plift {α} : nonempty (plift α) ↔ nonempty α :=\niff.intro (assume ⟨⟨a⟩⟩, ⟨a⟩) (assume ⟨a⟩, ⟨⟨a⟩⟩)\n\n@[simp] lemma nonempty.forall {α} {p : nonempty α → Prop} : (∀h:nonempty α, p h) ↔ (∀a, p ⟨a⟩) :=\niff.intro (assume h a, h _) (assume h ⟨a⟩, h _)\n\n@[simp] lemma nonempty.exists {α} {p : nonempty α → Prop} : (∃h:nonempty α, p h) ↔ (∃a, p ⟨a⟩) :=\niff.intro (assume ⟨⟨a⟩, h⟩, ⟨a, h⟩) (assume ⟨a, h⟩, ⟨⟨a⟩, h⟩)\n\nlemma classical.nonempty_pi {α} {β : α → Sort*} : nonempty (Πa:α, β a) ↔ (∀a:α, nonempty (β a)) :=\niff.intro (assume ⟨f⟩ a, ⟨f a⟩) (assume f, ⟨assume a, classical.choice $ f a⟩)\n\n/-- Using `classical.choice`, lifts a (`Prop`-valued) `nonempty` instance to a (`Type`-valued)\n `inhabited` instance. `classical.inhabited_of_nonempty` already exists, in\n `core/init/classical.lean`, but the assumption is not a type class argument,\n which makes it unsuitable for some applications. -/\nnoncomputable def classical.inhabited_of_nonempty' {α} [h : nonempty α] : inhabited α :=\n⟨classical.choice h⟩\n\n/-- Using `classical.choice`, extracts a term from a `nonempty` type. -/\n@[reducible] protected noncomputable def nonempty.some {α} (h : nonempty α) : α :=\nclassical.choice h\n\n/-- Using `classical.choice`, extracts a term from a `nonempty` type. -/\n@[reducible] protected noncomputable def classical.arbitrary (α) [h : nonempty α] : α :=\nclassical.choice h\n\n/-- Given `f : α → β`, if `α` is nonempty then `β` is also nonempty.\n `nonempty` cannot be a `functor`, because `functor` is restricted to `Type`. -/\nlemma nonempty.map {α β} (f : α → β) : nonempty α → nonempty β\n| ⟨h⟩ := ⟨f h⟩\n\nprotected lemma nonempty.map2 {α β γ : Sort*} (f : α → β → γ) : nonempty α → nonempty β → nonempty γ\n| ⟨x⟩ ⟨y⟩ := ⟨f x y⟩\n\nprotected lemma nonempty.congr {α β} (f : α → β) (g : β → α) :\n nonempty α ↔ nonempty β :=\n⟨nonempty.map f, nonempty.map g⟩\n\nlemma nonempty.elim_to_inhabited {α : Sort*} [h : nonempty α] {p : Prop}\n (f : inhabited α → p) : p :=\nh.elim $ f ∘ inhabited.mk\n\ninstance {α β} [h : nonempty α] [h2 : nonempty β] : nonempty (α × β) :=\nh.elim $ λ g, h2.elim $ λ g2, ⟨⟨g, g2⟩⟩\n\nend nonempty\n\nlemma subsingleton_of_not_nonempty {α : Sort*} (h : ¬ nonempty α) : subsingleton α :=\n⟨λ x, false.elim $ not_nonempty_iff_imp_false.mp h x⟩\n\nsection ite\n\n/-- A `dite` whose results do not actually depend on the condition may be reduced to an `ite`. -/\n@[simp]\nlemma dite_eq_ite (P : Prop) [decidable P] {α : Sort*} (x y : α) :\n dite P (λ h, x) (λ h, y) = ite P x y := rfl\n\n/-- A function applied to a `dite` is a `dite` of that function applied to each of the branches. -/\nlemma apply_dite {α β : Sort*} (f : α → β) (P : Prop) [decidable P] (x : P → α) (y : ¬P → α) :\n f (dite P x y) = dite P (λ h, f (x h)) (λ h, f (y h)) :=\nby { by_cases h : P; simp [h] }\n\n/-- A function applied to a `ite` is a `ite` of that function applied to each of the branches. -/\nlemma apply_ite {α β : Sort*} (f : α → β) (P : Prop) [decidable P] (x y : α) :\n f (ite P x y) = ite P (f x) (f y) :=\napply_dite f P (λ _, x) (λ _, y)\n\n/-- A two-argument function applied to two `dite`s is a `dite` of that two-argument function\napplied to each of the branches. -/\nlemma apply_dite2 {α β γ : Sort*} (f : α → β → γ) (P : Prop) [decidable P] (a : P → α)\n (b : ¬P → α) (c : P → β) (d : ¬P → β) :\n f (dite P a b) (dite P c d) = dite P (λ h, f (a h) (c h)) (λ h, f (b h) (d h)) :=\nby { by_cases h : P; simp [h] }\n\n/-- A two-argument function applied to two `ite`s is a `ite` of that two-argument function\napplied to each of the branches. -/\nlemma apply_ite2 {α β γ : Sort*} (f : α → β → γ) (P : Prop) [decidable P] (a b : α) (c d : β) :\n f (ite P a b) (ite P c d) = ite P (f a c) (f b d) :=\napply_dite2 f P (λ _, a) (λ _, b) (λ _, c) (λ _, d)\n\n/-- A 'dite' producing a `Pi` type `Π a, β a`, applied to a value `x : α`\nis a `dite` that applies either branch to `x`. -/\nlemma dite_apply {α : Sort*} {β : α → Sort*} (P : Prop) [decidable P]\n (f : P → Π a, β a) (g : ¬ P → Π a, β a) (x : α) :\n (dite P f g) x = dite P (λ h, f h x) (λ h, g h x) :=\nby { by_cases h : P; simp [h] }\n\n/-- A 'ite' producing a `Pi` type `Π a, β a`, applied to a value `x : α`\nis a `ite` that applies either branch to `x` -/\nlemma ite_apply {α : Sort*} {β : α → Sort*} (P : Prop) [decidable P]\n (f g : Π a, β a) (x : α) :\n (ite P f g) x = ite P (f x) (g x) :=\ndite_apply P (λ _, f) (λ _, g) x\n\n/-- Negation of the condition `P : Prop` in a `dite` is the same as swapping the branches. -/\n@[simp] lemma dite_not {α : Sort*} (P : Prop) [decidable P] (x : ¬ P → α) (y : ¬¬ P → α) :\n dite (¬ P) x y = dite P (λ h, y (not_not_intro h)) x :=\nby { by_cases h : P; simp [h] }\n\n/-- Negation of the condition `P : Prop` in a `ite` is the same as swapping the branches. -/\n@[simp] lemma ite_not {α : Sort*} (P : Prop) [decidable P] (x y : α) :\n ite (¬ P) x y = ite P y x :=\ndite_not P (λ _, x) (λ _, y)\n\nlemma ite_and {α} {p q : Prop} [decidable p] [decidable q] {x y : α} :\n ite (p ∧ q) x y = ite p (ite q x y) y :=\nby { by_cases hp : p; by_cases hq : q; simp [hp, hq] }\n\n\nend ite\n", "meta": {"author": "jjaassoonn", "repo": "projective_space", "sha": "11fe19fe9d7991a272e7a40be4b6ad9b0c10c7ce", "save_path": "github-repos/lean/jjaassoonn-projective_space", "path": "github-repos/lean/jjaassoonn-projective_space/projective_space-11fe19fe9d7991a272e7a40be4b6ad9b0c10c7ce/src/logic/basic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3415824860330003, "lm_q2_score": 0.14223190228178134, "lm_q1q2_score": 0.04858392677461364}} {"text": "import .lovelib\n\n\n/-! # LoVe Demo 8: Operational Semantics\n\nIn this and the next two lectures, we will see how to use Lean to specify the\nsyntax and semantics of programming languages and to reason about the\nsemantics. -/\n\n\nset_option pp.beta true\nset_option pp.generalized_field_notation false\n\nnamespace LoVe\n\n\n/-! ## Formal Semantics\n\nA formal semantics helps specify and reason about the programming language\nitself, and about individual programs.\n\nIt can form the basis of verified compilers, interpreters, verifiers, static\nanalyzers, type checkers, etc. Without formal proofs, these tools are\n**almost always wrong**.\n\nIn this area, proof assistants are widely used. Every year, about 10-20% of POPL\npapers are partially or totally formalized. Reasons for this success:\n\n* Little machinery (background libraries, tactics) is needed to get started,\n beyond inductive types and predicates and recursive functions.\n\n* The proofs tend to have lots of cases, which is a good match for computers.\n\n* Proof assistants keep track of what needs to be changed when as extend the\n programming language with more features.\n\nCase in point: WebAssembly. To quote Conrad Watt (with some abbreviations):\n\n We have produced a full Isabelle mechanisation of the core execution\n semantics and type system of the WebAssembly language. To complete this\n proof, **several deficiencies** in the official WebAssembly specification,\n uncovered by our proof and modelling work, needed to be corrected. In some\n cases, these meant that the type system was **originally unsound**.\n\n We have maintained a constructive dialogue with the working group,\n verifying new features as they are added. In particular, the mechanism by\n which a WebAssembly implementation interfaces with its host environment was\n not formally specified in the working group's original paper. Extending our\n mechanisation to model this feature revealed a deficiency in the WebAssembly\n specification that **sabotaged the soundness** of the type system.\n\n\n## A Minimalistic Imperative Language\n\nA state `s` is a function from variable names to values (`string → ℕ`).\n\n__WHILE__ is a minimalistic imperative language with the following grammar:\n\n S ::= skip -- no-op\n | x := a -- assignment\n | S ; S -- sequential composition\n | if b then S else S -- conditional statement\n | while b do S -- while loop\n\nwhere `S` stands for a statement (also called command or program), `x` for a\nvariable, `a` for an arithmetic expression, and `b` for a Boolean expression. -/\n\n#check state\n\ninductive stmt : Type\n| skip : stmt\n| assign : string → (state → ℕ) → stmt\n| seq : stmt → stmt → stmt\n| ite : (state → Prop) → stmt → stmt → stmt\n| while : (state → Prop) → stmt → stmt\n\ninfixr ` ;; ` : 90 := stmt.seq\n\n/-! In our grammar, we deliberately leave the syntax of arithmetic and Boolean\nexpressions unspecified. In Lean, we have the choice:\n\n* We could use a type such as `aexp` from lecture 1 and similarly for Boolean\n expressions.\n\n* We could decide that an arithmetic expression is simply a function from\n states to natural numbers (`state → ℕ`) and a Boolean expression is a\n predicate (`state → Prop` or `state → bool`).\n\nThis corresponds to the difference between deep and shallow embeddings:\n\n* A __deep embedding__ of some syntax (expression, formula, program, etc.)\n consists of an abstract syntax tree specified in the proof assistant\n (e.g., `aexp`) with a semantics (e.g., `eval`).\n\n* In contrast, a __shallow embedding__ simply reuses the corresponding\n mechanisms from the logic (e.g., λ-terms, functions and predicate types).\n\nA deep embedding allows us to reason about the syntax (and its semantics). A\nshallow embedding is more lightweight, because we can use it directly, without\nhaving to define a semantics.\n\nWe will use a deep embedding of programs (which we find interesting), and\nshallow embeddings of assignments and Boolean expressions (which we find\nboring). -/\n\ndef silly_loop : stmt :=\nstmt.while (λs, s \"x\" > s \"y\")\n (stmt.skip ;; stmt.assign \"x\" (λs, s \"x\" - 1))\n\n\n/-! ## Big-Step Semantics\n\nAn __operational semantics__ corresponds to an idealized interpreter (specified\nin a Prolog-like language). Two main variants:\n\n* big-step semantics;\n\n* small-step semantics.\n\nIn a __big-step semantics__ (also called __natural semantics__), judgments have\nthe form `(S, s) ⟹ t`:\n\n Starting in a state `s`, executing `S` terminates in the state `t`.\n\nExample:\n\n `(x := x + y; y := 0, [x ↦ 3, y ↦ 5]) ⟹ [x ↦ 8, y ↦ 0]`\n\nDerivation rules:\n\n ——————————————— Skip\n (skip, s) ⟹ s\n\n ——————————————————————————— Asn\n (x := a, s) ⟹ s[x ↦ s(a)]\n\n (S, s) ⟹ t (T, t) ⟹ u\n ——————————————————————————— Seq\n (S; T, s) ⟹ u\n\n (S, s) ⟹ t\n ————————————————————————————— If-True if s(b) is true\n (if b then S else T, s) ⟹ t\n\n (T, s) ⟹ t\n ————————————————————————————— If-False if s(b) is false\n (if b then S else T, s) ⟹ t\n\n (S, s) ⟹ t (while b do S, t) ⟹ u\n —————————————————————————————————————— While-True if s(b) is true\n (while b do S, s) ⟹ u\n\n ————————————————————————— While-False if s(b) is false\n (while b do S, s) ⟹ s\n\nAbove, `s(e)` denotes the value of expression `e` in state `s`.\n\nIn Lean, the judgment corresponds to an inductive predicate, and the derivation\nrules correspond to the predicate's introduction rules. Using an inductive\npredicate as opposed to a recursive function allows us to cope with\nnontermination (e.g., a diverging `while`) and nondeterminism (e.g.,\nmultithreading). -/\n\ninductive big_step : stmt × state → state → Prop\n| skip {s} :\n big_step (stmt.skip, s) s\n| assign {x a s} :\n big_step (stmt.assign x a, s) (s{x ↦ a s})\n| seq {S T s t u} (hS : big_step (S, s) t)\n (hT : big_step (T, t) u) :\n big_step (S ;; T, s) u\n| ite_true {b : state → Prop} {S T s t} (hcond : b s)\n (hbody : big_step (S, s) t) :\n big_step (stmt.ite b S T, s) t\n| ite_false {b : state → Prop} {S T s t} (hcond : ¬ b s)\n (hbody : big_step (T, s) t) :\n big_step (stmt.ite b S T, s) t\n| while_true {b : state → Prop} {S s t u} (hcond : b s)\n (hbody : big_step (S, s) t)\n (hrest : big_step (stmt.while b S, t) u) :\n big_step (stmt.while b S, s) u\n| while_false {b : state → Prop} {S s} (hcond : ¬ b s) :\n big_step (stmt.while b S, s) s\n\ninfix ` ⟹ ` : 110 := big_step\n\nlemma silly_loop_from_1_big_step :\n (silly_loop, (λ_, 0){\"x\" ↦ 1}) ⟹ (λ_, 0) :=\nbegin\n rw silly_loop,\n apply big_step.while_true,\n { simp },\n { apply big_step.seq,\n { apply big_step.skip },\n { apply big_step.assign } },\n { simp,\n apply big_step.while_false,\n linarith }\nend\n\n\n/-! ## Properties of the Big-Step Semantics\n\nEquipped with a big-step semantics, we can\n\n* prove properties of the programming language, such as **equivalence proofs**\n between programs and **determinism**;\n\n* reason about **concrete programs**, proving theorems relating final states `t`\n with initial states `s`. -/\n\nlemma big_step_deterministic {S s l r} (hl : (S, s) ⟹ l)\n (hr : (S, s) ⟹ r) :\n l = r :=\nbegin\n induction' hl,\n case skip {\n cases' hr,\n refl },\n case assign {\n cases' hr,\n refl },\n case seq : S T s t l hS hT ihS ihT {\n cases' hr with _ _ _ _ _ _ _ t' _ hS' hT',\n cases' ihS hS',\n cases' ihT hT',\n refl },\n case ite_true : b S T s t hb hS ih {\n cases' hr,\n { apply ih hr },\n { cc } },\n case ite_false : b S T s t hb hT ih {\n cases' hr,\n { cc },\n { apply ih hr } },\n case while_true : b S s t u hb hS hw ihS ihw {\n cases' hr,\n { cases' ihS hr,\n cases' ihw hr_1,\n refl },\n { cc } },\n { cases' hr,\n { cc },\n { refl } }\nend\n\nlemma big_step_terminates {S s} :\n ∃t, (S, s) ⟹ t :=\nsorry -- unprovable\n\nlemma big_step_doesnt_terminate {S s t} :\n ¬ (stmt.while (λ_, true) S, s) ⟹ t :=\nbegin\n intro hw,\n induction' hw,\n case while_true {\n assumption },\n case while_false {\n cc }\nend\n\n/-! We can define inversion rules about the big-step semantics: -/\n\n@[simp] lemma big_step_skip_iff {s t} :\n (stmt.skip, s) ⟹ t ↔ t = s :=\nbegin\n apply iff.intro,\n { intro h,\n cases' h,\n refl },\n { intro h,\n rw h,\n exact big_step.skip }\nend\n\n@[simp] lemma big_step_assign_iff {x a s t} :\n (stmt.assign x a, s) ⟹ t ↔ t = s{x ↦ a s} :=\nbegin\n apply iff.intro,\n { intro h,\n cases' h,\n refl },\n { intro h,\n rw h,\n exact big_step.assign }\nend\n\n@[simp] lemma big_step_seq_iff {S T s t} :\n (S ;; T, s) ⟹ t ↔ (∃u, (S, s) ⟹ u ∧ (T, u) ⟹ t) :=\nbegin\n apply iff.intro,\n { intro h,\n cases' h,\n apply exists.intro,\n apply and.intro; assumption },\n { intro h,\n cases' h,\n cases' h,\n apply big_step.seq; assumption }\nend\n\n@[simp] lemma big_step_ite_iff {b S T s t} :\n (stmt.ite b S T, s) ⟹ t ↔\n (b s ∧ (S, s) ⟹ t) ∨ (¬ b s ∧ (T, s) ⟹ t) :=\nbegin\n apply iff.intro,\n { intro h,\n cases' h,\n { apply or.intro_left,\n cc },\n { apply or.intro_right,\n cc } },\n { intro h,\n cases' h; cases' h,\n { apply big_step.ite_true; assumption },\n { apply big_step.ite_false; assumption } }\nend\n\nlemma big_step_while_iff {b S s u} :\n (stmt.while b S, s) ⟹ u ↔\n (∃t, b s ∧ (S, s) ⟹ t ∧ (stmt.while b S, t) ⟹ u)\n ∨ (¬ b s ∧ u = s) :=\nbegin\n apply iff.intro,\n { intro h,\n cases' h,\n { apply or.intro_left,\n apply exists.intro t,\n cc },\n { apply or.intro_right,\n cc } },\n { intro h,\n cases' h,\n case inl {\n cases' h with t h,\n cases' h with hb h,\n cases' h with hS hwhile,\n exact big_step.while_true hb hS hwhile },\n case inr {\n cases' h with hb hus,\n rw hus,\n exact big_step.while_false hb } }\nend\n\nlemma big_step_while_true_iff {b : state → Prop} {S s u}\n (hcond : b s) :\n (stmt.while b S, s) ⟹ u ↔\n (∃t, (S, s) ⟹ t ∧ (stmt.while b S, t) ⟹ u) :=\nby rw big_step_while_iff; simp [hcond]\n\n@[simp] lemma big_step_while_false_iff {b : state → Prop}\n {S s t} (hcond : ¬ b s) :\n (stmt.while b S, s) ⟹ t ↔ t = s :=\nby rw big_step_while_iff; simp [hcond]\n\n\n/-! ## Small-Step Semantics\n\nA big-step semantics\n\n* does not let us reason about intermediate states;\n\n* does not let us express nontermination or interleaving (for multithreading).\n\n__Small-step semantics__ (also called __structural operational semantics__)\nsolve the above issues.\n\nA judgment has the form `(S, s) ⇒ (T, t)`:\n\n Starting in a state `s`, executing one step of `S` leaves us in the\n state `t`, with the program `T` remaining to be executed.\n\nAn execution is a finite or infinite chain `(S₀, s₀) ⇒ (S₁, s₁) ⇒ …`.\n\nA pair `(S, s)` is called a __configuration__. It is __final__ if no transition\nof the form `(S, s) ⇒ _` is possible.\n\nExample:\n\n `(x := x + y; y := 0, [x ↦ 3, y ↦ 5])`\n `⇒ (skip; y := 0, [x ↦ 8, y ↦ 5])`\n `⇒ (y := 0, [x ↦ 8, y ↦ 5])`\n `⇒ (skip, [x ↦ 8, y ↦ 0])`\n\nDerivation rules:\n\n ————————————————————————————————— Asn\n (x := a, s) ⇒ (skip, s[x ↦ s(a)])\n\n (S, s) ⇒ (S', s')\n ———-————————————————————— Seq-Step\n (S ; T, s) ⇒ (S' ; T, s')\n\n —————————————————————— Seq-Skip\n (skip ; S, s) ⇒ (S, s)\n\n ———————————————————————————————— If-True if s(b) is true\n (if b then S else T, s) ⇒ (S, s)\n\n ———————————————————————————————— If-False if s(b) is false\n (if b then S else T, s) ⇒ (T, s)\n\n ——————————————————————————————————————————————————————————————— While\n (while b do S, s) ⇒ (if b then (S ; while b do S) else skip, s)\n\nThere is no rule for `skip` (why?). -/\n\ninductive small_step : stmt × state → stmt × state → Prop\n| assign {x a s} :\n small_step (stmt.assign x a, s) (stmt.skip, s{x ↦ a s})\n| seq_step {S S' T s s'} (hS : small_step (S, s) (S', s')) :\n small_step (S ;; T, s) (S' ;; T, s')\n| seq_skip {T s} :\n small_step (stmt.skip ;; T, s) (T, s)\n| ite_true {b : state → Prop} {S T s} (hcond : b s) :\n small_step (stmt.ite b S T, s) (S, s)\n| ite_false {b : state → Prop} {S T s} (hcond : ¬ b s) :\n small_step (stmt.ite b S T, s) (T, s)\n| while {b : state → Prop} {S s} :\n small_step (stmt.while b S, s)\n (stmt.ite b (S ;; stmt.while b S) stmt.skip, s)\n\ninfixr ` ⇒ ` := small_step\ninfixr ` ⇒* ` : 100 := star small_step\n\nlemma silly_loop_from_1_small_step :\n (silly_loop, (λ_, 0){\"x\" ↦ 1}) ⇒*\n (stmt.skip, ((λ_, 0) : state)) :=\nbegin\n rw silly_loop,\n apply star.head,\n { apply small_step.while },\n { apply star.head,\n { apply small_step.ite_true,\n simp },\n { apply star.head,\n { apply small_step.seq_step,\n apply small_step.seq_skip },\n { apply star.head,\n { apply small_step.seq_step,\n apply small_step.assign },\n { apply star.head,\n { apply small_step.seq_skip },\n { apply star.head,\n { apply small_step.while },\n { apply star.head,\n { apply small_step.ite_false,\n simp },\n { simp } } } } } } }\nend\n\n/-! Equipped with a small-step semantics, we can **define** a big-step\nsemantics:\n\n `(S, s) ⟹ t` if and only if `(S, s) ⇒* (skip, t)`\n\nwhere `r*` denotes the reflexive transitive closure of a relation `r`.\n\nAlternatively, if we have already defined a big-step semantics, we can **prove**\nthe above equivalence theorem to validate our definitions.\n\nThe main disadvantage of small-step semantics is that we now have two relations,\n`⇒` and `⇒*`, and reasoning tends to be more complicated.\n\n\n## Properties of the Small-Step Semantics\n\nWe can prove that a configuration `(S, s)` is final if and only if `S = skip`.\nThis ensures that we have not forgotten a derivation rule. -/\n\nlemma small_step_final (S s) :\n (¬ ∃T t, (S, s) ⇒ (T, t)) ↔ S = stmt.skip :=\nbegin\n induction' S,\n case skip {\n simp,\n intros T t hstep,\n cases' hstep },\n case assign : x a {\n simp,\n apply exists.intro stmt.skip,\n apply exists.intro (s{x ↦ a s}),\n exact small_step.assign },\n case seq : S T ihS ihT {\n simp,\n cases' classical.em (S = stmt.skip),\n case inl {\n rw h,\n apply exists.intro T,\n apply exists.intro s,\n exact small_step.seq_skip },\n case inr {\n simp [h, auto.not_forall_eq, auto.not_not_eq] at ihS,\n cases' ihS s with S' hS',\n cases' hS' with s' hs',\n apply exists.intro (S' ;; T),\n apply exists.intro s',\n exact small_step.seq_step hs' } },\n case ite : b S T ihS ihT {\n simp,\n cases' classical.em (b s),\n case inl {\n apply exists.intro S,\n apply exists.intro s,\n exact small_step.ite_true h },\n case inr {\n apply exists.intro T,\n apply exists.intro s,\n exact small_step.ite_false h } },\n case while : b S ih {\n simp,\n apply exists.intro (stmt.ite b (S ;; stmt.while b S) stmt.skip),\n apply exists.intro s,\n exact small_step.while }\nend\n\nlemma small_step_deterministic {S s Ll Rr}\n (hl : (S, s) ⇒ Ll) (hr : (S, s) ⇒ Rr) :\n Ll = Rr :=\nbegin\n induction' hl,\n case assign : x a s {\n cases' hr,\n refl },\n case seq_step : S S₁ T s s₁ hS₁ ih {\n cases' hr,\n case seq_step : S S₂ _ _ s₂ hS₂ {\n have hSs₁₂ := ih hS₂,\n cc },\n case seq_skip {\n cases' hS₁ } },\n case seq_skip : T s {\n cases' hr,\n case seq_step {\n cases' hr },\n case seq_skip {\n refl } },\n case ite_true : b S T s hcond {\n cases' hr,\n case ite_true {\n refl },\n case ite_false {\n cc } },\n case ite_false : b S T s hcond {\n cases' hr,\n case ite_true {\n cc },\n case ite_false {\n refl } },\n case while : b S s {\n cases' hr,\n refl }\nend\n\n/-! We can define inversion rules also about the small-step semantics. Here are\nthree examples: -/\n\nlemma small_step_skip {S s t} :\n ¬ ((stmt.skip, s) ⇒ (S, t)) :=\nby intro h; cases' h\n\n@[simp] lemma small_step_seq_iff {S T s Ut} :\n (S ;; T, s) ⇒ Ut ↔\n (∃S' t, (S, s) ⇒ (S', t) ∧ Ut = (S' ;; T, t))\n ∨ (S = stmt.skip ∧ Ut = (T, s)) :=\nbegin\n apply iff.intro,\n { intro h,\n cases' h,\n { apply or.intro_left,\n apply exists.intro S',\n apply exists.intro s',\n cc },\n { apply or.intro_right,\n cc } },\n { intro h,\n cases' h,\n { cases' h,\n cases' h,\n cases' h,\n rw right,\n apply small_step.seq_step,\n assumption },\n { cases' h,\n rw left,\n rw right,\n apply small_step.seq_skip } }\nend\n\n@[simp] lemma small_step_ite_iff {b S T s Us} :\n (stmt.ite b S T, s) ⇒ Us ↔\n (b s ∧ Us = (S, s)) ∨ (¬ b s ∧ Us = (T, s)) :=\nbegin\n apply iff.intro,\n { intro h,\n cases' h,\n { apply or.intro_left,\n cc },\n { apply or.intro_right,\n cc } },\n { intro h,\n cases' h,\n { cases' h,\n rw right,\n apply small_step.ite_true,\n assumption },\n { cases' h,\n rw right,\n apply small_step.ite_false,\n assumption } }\nend\n\n\n/-! ### Equivalence of the Big-Step and the Small-Step Semantics (**optional**)\n\nA more important result is the connection between the big-step and the\nsmall-step semantics:\n\n `(S, s) ⟹ t ↔ (S, s) ⇒* (stmt.skip, t)`\n\nIts proof, given below, is beyond the scope of this course. -/\n\nlemma star_small_step_seq {S T s u}\n (h : (S, s) ⇒* (stmt.skip, u)) :\n (S ;; T, s) ⇒* (stmt.skip ;; T, u) :=\nbegin\n apply star.lift (λSs, (prod.fst Ss ;; T, prod.snd Ss)) _ h,\n intros Ss Ss' h,\n cases' Ss,\n cases' Ss',\n apply small_step.seq_step,\n assumption\nend\n\nlemma star_small_step_of_big_step {S s t} (h : (S, s) ⟹ t) :\n (S, s) ⇒* (stmt.skip, t) :=\nbegin\n induction' h,\n case skip {\n refl },\n case assign {\n exact star.single small_step.assign },\n case seq : S T s t u hS hT ihS ihT {\n transitivity,\n exact star_small_step_seq ihS,\n apply star.head small_step.seq_skip ihT },\n case ite_true : b S T s t hs hst ih {\n exact star.head (small_step.ite_true hs) ih },\n case ite_false : b S T s t hs hst ih {\n exact star.head (small_step.ite_false hs) ih },\n case while_true : b S s t u hb hS hw ihS ihw {\n exact (star.head small_step.while\n (star.head (small_step.ite_true hb)\n (star.trans (star_small_step_seq ihS)\n (star.head small_step.seq_skip ihw)))) },\n case while_false : b S s hb {\n exact star.tail (star.single small_step.while)\n (small_step.ite_false hb) }\nend\n\nlemma big_step_of_small_step_of_big_step {S₀ S₁ s₀ s₁ s₂}\n (h₁ : (S₀, s₀) ⇒ (S₁, s₁)) :\n (S₁, s₁) ⟹ s₂ → (S₀, s₀) ⟹ s₂ :=\nbegin\n induction' h₁;\n simp [*, big_step_while_true_iff] {contextual := tt},\n case seq_step {\n intros u hS' hT,\n apply exists.intro u,\n exact and.intro (ih hS') hT }\nend\n\nlemma big_step_of_star_small_step {S s t} :\n (S, s) ⇒* (stmt.skip, t) → (S, s) ⟹ t :=\nbegin\n generalize hSs : (S, s) = Ss,\n intro h,\n induction h\n using LoVe.rtc.star.head_induction_on\n with _ S's' h h' ih\n generalizing S s;\n cases' hSs,\n { exact big_step.skip },\n { cases' S's' with S' s',\n apply big_step_of_small_step_of_big_step h,\n apply ih,\n refl }\nend\n\nlemma big_step_iff_star_small_step {S s t} :\n (S, s) ⟹ t ↔ (S, s) ⇒* (stmt.skip, t) :=\niff.intro star_small_step_of_big_step\n big_step_of_star_small_step\n\n\n/-! ## Parallelism (**optional**) -/\n\ninductive par_step :\n nat → list stmt × state → list stmt × state → Prop\n| intro {Ss Ss' S S' s s' i}\n (hi : i < list.length Ss)\n (hS : S = list.nth_le Ss i hi)\n (hs : (S, s) ⇒ (S', s'))\n (hS' : Ss' = list.update_nth Ss i S') :\n par_step i (Ss, s) (Ss', s')\n\nlemma par_step_diamond {i j Ss Ts Ts' s t t'}\n (hi : i < list.length Ss)\n (hj : j < list.length Ss)\n (hij : i ≠ j)\n (hT : par_step i (Ss, s) (Ts, t))\n (hT' : par_step j (Ss, s) (Ts', t')) :\n ∃u Us, par_step j (Ts, t) (Us, u) ∧\n par_step i (Ts', t') (Us, u) :=\nsorry -- unprovable\n\ndef stmt.W : stmt → set string\n| stmt.skip := ∅\n| (stmt.assign x _) := {x}\n| (stmt.seq S T) := stmt.W S ∪ stmt.W T\n| (stmt.ite _ S T) := stmt.W S ∪ stmt.W T\n| (stmt.while _ S) := stmt.W S\n\ndef exp.R {α : Type} : (state → α) → set string\n| f := {x | ∃s n, f (s{x ↦ n}) ≠ f s}\n\ndef stmt.R : stmt → set string\n| stmt.skip := ∅\n| (stmt.assign _ a) := exp.R a\n| (stmt.seq S T) := stmt.R S ∪ stmt.R T\n| (stmt.ite b S T) := exp.R b ∪ stmt.R S ∪ stmt.R T\n| (stmt.while b S) := exp.R b ∪ stmt.R S\n\ndef stmt.V : stmt → set string\n| S := stmt.W S ∪ stmt.R S\n\nlemma par_step_diamond_VW_disjoint {i j Ss Ts Ts' s t t'}\n (hiS : i < list.length Ss)\n (hjT : j < list.length Ts)\n (hij : i ≠ j)\n (hT : par_step i (Ss, s) (Ts, t))\n (hT' : par_step j (Ss, s) (Ts', t'))\n (hWV : stmt.W (list.nth_le Ss i hiS)\n ∩ stmt.V (list.nth_le Ts j hjT) = ∅)\n (hVW : stmt.V (list.nth_le Ss i hiS)\n ∩ stmt.W (list.nth_le Ts j hjT) = ∅) :\n ∃u Us, par_step j (Ts, t) (Us, u) ∧\n par_step i (Ts', t') (Us, u) :=\nsorry -- this should be provable\n\nend LoVe\n", "meta": {"author": "blanchette", "repo": "logical_verification_2021", "sha": "23b469c79afd482fa66da82e4726a317e3a7b5d5", "save_path": "github-repos/lean/blanchette-logical_verification_2021", "path": "github-repos/lean/blanchette-logical_verification_2021/logical_verification_2021-23b469c79afd482fa66da82e4726a317e3a7b5d5/lean/love08_operational_semantics_demo.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167793123159, "lm_q2_score": 0.10521052898760751, "lm_q1q2_score": 0.04850381922361186}} {"text": "/-\nCopyright (c) 2022 Damiano Testa. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Gabriel Ebner, Damiano Testa\n-/\nimport tactic.interactive\n\n/-! `congrm`: `congr` with pattern-matching\n\n`congrm e` gives to the use the functionality of using `congr` with an expression `e` \"guiding\"\n`congr` through the matching. This allows more flexibility than `congr' n`, which enters uniformly\nthrough `n` iterations. Instead, we can guide the matching deeper on some parts of the expression\nand stop earlier on other parts.\n\n## Implementation notes\n\n### Function underscores\n\nSee the doc-string to `tactic.interactive.congrm` for more details. Here we describe how to add\nmore \"function underscores\".\n\nThe pattern for generating a function underscore is to define a \"generic\" `n`-ary function, for some\nnumber `n`. You can take a look at `tactic.congrm_fun_1, ..., tactic.congrm_fun_4`.\nThese implement the \"function underscores\" `_₁, ..., _₄`. If you want a different arity for your\nfunction, simply\nintroduce\n```lean\n@[nolint unused_arguments]\ndef congrm_fun_n {α₁ … αₙ ρ} {r : ρ} : α₁ → ⋯ → aₙ → ρ := λ _ … _, r\nnotation `_ₙ` := congrm_fun_n\n```\n_Warning:_ `convert_to_explicit` checks that the first 18 characters in the name of `_ₙ` are\nidentical to `tactic.congrm_fun_` to perform its job. Thus, if you want to implement\n\"function underscores\" with different arity, either make sure that their names begin with\n`tactic.congrm_fun_` or you should change `convert_to_explicit` accordingly.\n-/\n\nnamespace tactic\n\n/-- A generic function with one argument. It is the \"function underscore\" input to `congrm`. -/\n@[nolint unused_arguments]\ndef congrm_fun_1 {α ρ} {r : ρ} : α → ρ := λ _, r\nnotation `_₁` := congrm_fun_1\n\n/-- A generic function with two arguments. It is the \"function underscore\" input to `congrm`. -/\n@[nolint unused_arguments]\ndef congrm_fun_2 {α β ρ} {r : ρ} : α → β → ρ := λ _ _, r\nnotation `_₂` := congrm_fun_2\n\n/-- A generic function with three arguments. It is the \"function underscore\" input to `congrm`. -/\n@[nolint unused_arguments]\ndef congrm_fun_3 {α β γ ρ} {r : ρ} : α → β → γ → ρ := λ _ _ _, r\nnotation `_₃` := congrm_fun_3\n\n/-- A generic function with four arguments. It is the \"function underscore\" input to `congrm`. -/\n@[nolint unused_arguments]\ndef congrm_fun_4 {α β γ δ ρ} {r : ρ} : α → β → γ → δ → ρ := λ _ _ _ _, r\nnotation `_₄` := congrm_fun_4\n\n/-- Replaces a \"function underscore\" input to `congrm` into the correct expression,\nread off from the left-hand-side of the target expression. -/\nmeta def convert_to_explicit (pat lhs : expr) : tactic expr :=\nif pat.get_app_fn.const_name.to_string.starts_with \"tactic.congrm_fun_\"\nthen\n pat.list_explicit_args >>= lhs.replace_explicit_args\nelse\n return pat\n\n/--\nFor each element of `list congr_arg_kind` that is `eq`, add a pair `(g, pat)` to the\nfinal list. Otherwise, discard an appropriate number of initial terms from each list\n(possibly none from the first) and repeat.\n\n`pat` is the given pattern-piece at the appropriate location, extracted from the last `list expr`.\nIt appears to be the list of arguments of a function application.\n\n`g` is possibly the proof of an equality? It is extracted from the first `list expr`.\n-/\nprivate meta def extract_subgoals : list expr → list congr_arg_kind → list expr →\n tactic (list (expr × expr))\n| (_ :: _ :: g :: prf_args) (congr_arg_kind.eq :: kinds) (pat :: pat_args) :=\n (λ rest, (g, pat) :: rest) <$> extract_subgoals prf_args kinds pat_args\n| (_ :: prf_args) (congr_arg_kind.fixed :: kinds) (_ :: pat_args) :=\n extract_subgoals prf_args kinds pat_args\n| prf_args (congr_arg_kind.fixed_no_param :: kinds) (_ :: pat_args) :=\n extract_subgoals prf_args kinds pat_args\n| (_ :: _ :: prf_args) (congr_arg_kind.cast :: kinds) (_ :: pat_args) :=\n extract_subgoals prf_args kinds pat_args\n| _ _ [] := pure []\n| _ _ _ := fail \"unsupported congr lemma\"\n\n/--\n`equate_with_pattern_core pat` solves a single goal of the form `lhs = rhs`\n(assuming that `lhs` and `rhs` are unifiable with `pat`)\nby applying congruence lemmas until `pat` is a metavariable.\nReturns the list of metavariables for the new subgoals at the leafs.\nCalls `set_goals []` at the end.\n-/\nmeta def equate_with_pattern_core : expr → tactic (list expr) | pat :=\n(applyc ``subsingleton.elim >> pure []) <|>\n(applyc ``rfl >> pure []) <|>\nif pat.is_mvar || pat.get_delayed_abstraction_locals.is_some then do\n try $ applyc ``_root_.propext,\n get_goals <* set_goals []\nelse match pat with\n| expr.app _ _ := do\n `(%%lhs = %%_) ← target,\n pat ← convert_to_explicit pat lhs,\n cl ← mk_specialized_congr_lemma pat,\n H_congr_lemma ← assertv `H_congr_lemma cl.type cl.proof,\n [prf] ← get_goals,\n apply H_congr_lemma <|> fail \"could not apply congr_lemma\",\n all_goals' $ try $ clear H_congr_lemma, -- given the `set_goals []` that follows, is this needed?\n set_goals [],\n prf ← instantiate_mvars prf,\n subgoals ← extract_subgoals prf.get_app_args cl.arg_kinds pat.get_app_args,\n subgoals ← subgoals.mmap (λ ⟨subgoal, subpat⟩, do\n set_goals [subgoal],\n equate_with_pattern_core subpat),\n pure subgoals.join\n| expr.lam _ _ _ body := do\n applyc ``_root_.funext,\n x ← intro pat.binding_name,\n equate_with_pattern_core $ body.instantiate_var x\n| expr.pi _ _ _ codomain := do\n applyc ``_root_.pi_congr,\n x ← intro pat.binding_name,\n equate_with_pattern_core $ codomain.instantiate_var x\n| _ := do\n pat ← pp pat,\n fail $ to_fmt \"unsupported pattern:\\n\" ++ pat\nend\n\n/--\n`equate_with_pattern pat` solves a single goal of the form `lhs = rhs`\n(assuming that `lhs` and `rhs` are unifiable with `pat`)\nby applying congruence lemmas until `pat` is a metavariable.\nThe subgoals for the leafs are prepended to the goals.\n-/\nmeta def equate_with_pattern (pat : expr) : tactic unit := do\ncongr_subgoals ← solve1 (equate_with_pattern_core pat),\ngs ← get_goals,\nset_goals $ congr_subgoals ++ gs\n\nend tactic\n\nnamespace tactic.interactive\nopen tactic interactive\nsetup_tactic_parser\n\n/--\nAssume that the goal is of the form `lhs = rhs` or `lhs ↔ rhs`.\n`congrm e` takes an expression `e` containing placeholders `_` and scans `e, lhs, rhs` in parallel.\n\nIt matches both `lhs` and `rhs` to the pattern `e`, and produces one goal for each placeholder,\nstating that the corresponding subexpressions in `lhs` and `rhs` are equal.\n\nExamples:\n```lean\nexample {a b c d : ℕ} :\n nat.pred a.succ * (d + (c + a.pred)) = nat.pred b.succ * (b + (c + d.pred)) :=\nbegin\n congrm nat.pred (nat.succ _) * (_ + _),\n/- Goals left:\n⊢ a = b\n⊢ d = b\n⊢ c + a.pred = c + d.pred\n-/\n sorry,\n sorry,\n sorry,\nend\n\nexample {a b : ℕ} (h : a = b) : (λ y : ℕ, ∀ z, a + a = z) = (λ x, ∀ z, b + a = z) :=\nbegin\n congrm λ x, ∀ w, _ + a = w,\n -- produces one goal for the underscore: ⊢ a = b\n exact h,\nend\n```\n\nThe tactic also allows for \"function underscores\", denoted by `_₁, ..., _₄`. The index denotes\nthe number of explicit arguments of the function to be matched.\nIf `e` has a \"function underscore\" in a location, then the tactic reads off the function `f` that\nappears in `lhs` at the current location, replacing the *explicit* arguments of `f` by the user\ninputs to the \"function underscore\". After that, `congrm` continues with its matching.\n-/\nmeta def congrm (arg : parse texpr) : tactic unit := do\ntry $ applyc ``_root_.eq.to_iff,\n`(@eq %%ty _ _) ← target | fail \"congrm: goal must be an equality or iff\",\nta ← to_expr ``((%%arg : %%ty)) tt ff,\nequate_with_pattern ta\n\nadd_tactic_doc\n{ name := \"congrm\",\n category := doc_category.tactic,\n decl_names := [`tactic.interactive.congrm],\n tags := [\"congruence\"] }\n\nend tactic.interactive\n", "meta": {"author": "leanprover-community", "repo": "mathlib", "sha": "5e526d18cea33550268dcbbddcb822d5cde40654", "save_path": "github-repos/lean/leanprover-community-mathlib", "path": "github-repos/lean/leanprover-community-mathlib/mathlib-5e526d18cea33550268dcbbddcb822d5cde40654/src/tactic/congrm.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.09670579589946719, "lm_q1q2_score": 0.048352897949733596}} {"text": "lemma example1 (x y z : mynat) : x * y + z = x * y + z :=\nbegin\nrefl,\nend\n", "meta": {"author": "chanha-park", "repo": "naturalNumberGame", "sha": "4e0d7100ce4575e1add92feefa38b1250431b879", "save_path": "github-repos/lean/chanha-park-naturalNumberGame", "path": "github-repos/lean/chanha-park-naturalNumberGame/naturalNumberGame-4e0d7100ce4575e1add92feefa38b1250431b879/Tutorial/1.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4921881357207955, "lm_q2_score": 0.09807931622061719, "lm_q1q2_score": 0.04827347580339596}} {"text": "/-\nCopyright (c) 2020 Simon Hudon. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Simon Hudon\n\n! This file was ported from Lean 3 source module control.uliftable\n! leanprover-community/mathlib commit cc8c90d4ac61725a8f6c92691d8abcd2dec88115\n! Please do not edit these lines, except to modify the commit id\n! if you have ported upstream changes.\n-/\nimport Mathbin.Control.Monad.Basic\nimport Mathbin.Control.Monad.Cont\nimport Mathbin.Control.Monad.Writer\nimport Mathbin.Logic.Equiv.Basic\nimport Mathbin.Tactic.Interactive\n\n/-!\n# Universe lifting for type families\n\nSome functors such as `option` and `list` are universe polymorphic. Unlike\ntype polymorphism where `option α` is a function application and reasoning and\ngeneralizations that apply to functions can be used, `option.{u}` and `option.{v}`\nare not one function applied to two universe names but one polymorphic definition\ninstantiated twice. This means that whatever works on `option.{u}` is hard\nto transport over to `option.{v}`. `uliftable` is an attempt at improving the situation.\n\n`uliftable option.{u} option.{v}` gives us a generic and composable way to use\n`option.{u}` in a context that requires `option.{v}`. It is often used in tandem with\n`ulift` but the two are purposefully decoupled.\n\n\n## Main definitions\n * `uliftable` class\n\n## Tags\n\nuniverse polymorphism functor\n\n-/\n\n\nuniverse u₀ u₁ v₀ v₁ v₂ w w₀ w₁\n\nvariable {s : Type u₀} {s' : Type u₁} {r r' w w' : Type _}\n\n/- ./././Mathport/Syntax/Translate/Command.lean:388:30: infer kinds are unsupported in Lean 4: #[`congr] [] -/\n/-- Given a universe polymorphic type family `M.{u} : Type u₁ → Type\nu₂`, this class convert between instantiations, from\n`M.{u} : Type u₁ → Type u₂` to `M.{v} : Type v₁ → Type v₂` and back -/\nclass Uliftable (f : Type u₀ → Type u₁) (g : Type v₀ → Type v₁) where\n congr {α β} : α ≃ β → f α ≃ g β\n#align uliftable Uliftable\n\nnamespace Uliftable\n\n/-- The most common practical use `uliftable` (together with `up`), this function takes\n`x : M.{u} α` and lifts it to M.{max u v} (ulift.{v} α) -/\n@[reducible]\ndef up {f : Type u₀ → Type u₁} {g : Type max u₀ v₀ → Type v₁} [Uliftable f g] {α} :\n f α → g (ULift α) :=\n (Uliftable.congr f g Equiv.ulift.symm).toFun\n#align uliftable.up Uliftable.up\n\n/-- The most common practical use of `uliftable` (together with `up`), this function takes\n`x : M.{max u v} (ulift.{v} α)` and lowers it to `M.{u} α` -/\n@[reducible]\ndef down {f : Type u₀ → Type u₁} {g : Type max u₀ v₀ → Type v₁} [Uliftable f g] {α} :\n g (ULift α) → f α :=\n (Uliftable.congr f g Equiv.ulift.symm).invFun\n#align uliftable.down Uliftable.down\n\n/-- convenient shortcut to avoid manipulating `ulift` -/\ndef adaptUp (F : Type v₀ → Type v₁) (G : Type max v₀ u₀ → Type u₁) [Uliftable F G] [Monad G] {α β}\n (x : F α) (f : α → G β) : G β :=\n up x >>= f ∘ ULift.down\n#align uliftable.adapt_up Uliftable.adaptUp\n\n/-- convenient shortcut to avoid manipulating `ulift` -/\ndef adaptDown {F : Type max u₀ v₀ → Type u₁} {G : Type v₀ → Type v₁} [L : Uliftable G F] [Monad F]\n {α β} (x : F α) (f : α → G β) : G β :=\n @down.{v₀, v₁, max u₀ v₀} G F L β <| x >>= @up.{v₀, v₁, max u₀ v₀} G F L β ∘ f\n#align uliftable.adapt_down Uliftable.adaptDown\n\n/-- map function that moves up universes -/\ndef upMap {F : Type u₀ → Type u₁} {G : Type max u₀ v₀ → Type v₁} [inst : Uliftable F G] [Functor G]\n {α β} (f : α → β) (x : F α) : G β :=\n Functor.map (f ∘ ULift.down) (up x)\n#align uliftable.up_map Uliftable.upMap\n\n/-- map function that moves down universes -/\ndef downMap {F : Type max u₀ v₀ → Type u₁} {G : Type u₀ → Type v₁} [inst : Uliftable G F]\n [Functor F] {α β} (f : α → β) (x : F α) : G β :=\n down (Functor.map (ULift.up ∘ f) x : F (ULift β))\n#align uliftable.down_map Uliftable.downMap\n\n@[simp]\ntheorem up_down {f : Type u₀ → Type u₁} {g : Type max u₀ v₀ → Type v₁} [Uliftable f g] {α}\n (x : g (ULift α)) : up (down x : f α) = x :=\n (Uliftable.congr f g Equiv.ulift.symm).right_inv _\n#align uliftable.up_down Uliftable.up_down\n\n@[simp]\ntheorem down_up {f : Type u₀ → Type u₁} {g : Type max u₀ v₀ → Type v₁} [Uliftable f g] {α}\n (x : f α) : down (up x : g _) = x :=\n (Uliftable.congr f g Equiv.ulift.symm).left_inv _\n#align uliftable.down_up Uliftable.down_up\n\nend Uliftable\n\nopen ULift\n\ninstance : Uliftable id id where congr α β F := F\n\n/-- for specific state types, this function helps to create a uliftable instance -/\ndef StateT.uliftable' {m : Type u₀ → Type v₀} {m' : Type u₁ → Type v₁} [Uliftable m m']\n (F : s ≃ s') : Uliftable (StateT s m) (StateT s' m')\n where congr α β G :=\n StateT.equiv <| Equiv.piCongr F fun _ => Uliftable.congr _ _ <| Equiv.prodCongr G F\n#align state_t.uliftable' StateTₓ.uliftable'\n\ninstance {m m'} [Uliftable m m'] : Uliftable (StateT s m) (StateT (ULift s) m') :=\n StateT.uliftable' Equiv.ulift.symm\n\n/-- for specific reader monads, this function helps to create a uliftable instance -/\ndef ReaderT.uliftable' {m m'} [Uliftable m m'] (F : s ≃ s') :\n Uliftable (ReaderT s m) (ReaderT s' m')\n where congr α β G := ReaderT.equiv <| Equiv.piCongr F fun _ => Uliftable.congr _ _ G\n#align reader_t.uliftable' ReaderTₓ.uliftable'\n\ninstance {m m'} [Uliftable m m'] : Uliftable (ReaderT s m) (ReaderT (ULift s) m') :=\n ReaderT.uliftable' Equiv.ulift.symm\n\n/-- for specific continuation passing monads, this function helps to create a uliftable instance -/\ndef ContT.uliftable' {m m'} [Uliftable m m'] (F : r ≃ r') : Uliftable (ContT r m) (ContT r' m')\n where congr α β := ContT.equiv (Uliftable.congr _ _ F)\n#align cont_t.uliftable' ContT.uliftable'\n\ninstance {s m m'} [Uliftable m m'] : Uliftable (ContT s m) (ContT (ULift s) m') :=\n ContT.uliftable' Equiv.ulift.symm\n\n/-- for specific writer monads, this function helps to create a uliftable instance -/\ndef WriterT.uliftable' {m m'} [Uliftable m m'] (F : w ≃ w') :\n Uliftable (WriterT w m) (WriterT w' m')\n where congr α β G := WriterT.equiv <| Uliftable.congr _ _ <| Equiv.prodCongr G F\n#align writer_t.uliftable' WriterTₓ.uliftable'\n\ninstance {m m'} [Uliftable m m'] : Uliftable (WriterT s m) (WriterT (ULift s) m') :=\n WriterT.uliftable' Equiv.ulift.symm\n\n", "meta": {"author": "leanprover-community", "repo": "mathlib3port", "sha": "62505aa236c58c8559783b16d33e30df3daa54f4", "save_path": "github-repos/lean/leanprover-community-mathlib3port", "path": "github-repos/lean/leanprover-community-mathlib3port/mathlib3port-62505aa236c58c8559783b16d33e30df3daa54f4/Mathbin/Control/Uliftable.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45713671682749474, "lm_q2_score": 0.10521053389745762, "lm_q1q2_score": 0.04809559804155162}} {"text": "/-\nCopyright (c) 2020 Jannis Limperg. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Jannis Limperg\n\n! This file was ported from Lean 3 source module tactic.clear\n! leanprover-community/mathlib commit e68fcf8dede813727dd0a47c873938ade3f90ef1\n! Please do not edit these lines, except to modify the commit id\n! if you have ported upstream changes.\n-/\nimport Mathbin.Data.Bool.Basic\nimport Mathbin.Tactic.Core\n\n/-!\n# Better `clear` tactics\n\nWe define two variants of the standard `clear` tactic:\n\n* `clear'` works like `clear` but the hypotheses that should be cleared can be\n given in any order. In contrast, `clear` can fail if hypotheses that depend on\n each other are given in the wrong order, even if all of them could be cleared.\n\n* `clear_dependent` works like `clear'` but also clears any hypotheses that\n depend on the given hypotheses.\n\n## Implementation notes\n\nThe implementation (ab)uses the native `revert_lst`, which can figure out\ndependencies between hypotheses. This implementation strategy was suggested by\nSimon Hudon.\n-/\n\n\nopen Native Tactic Interactive Lean.Parser\n\n/-- Clears all the hypotheses in `hyps`. The tactic fails if any of the `hyps`\nis not a local or if the target depends on any of the `hyps`. It also fails if\n`hyps` contains duplicates.\n\nIf there are local hypotheses or definitions, say `H`, which are not in `hyps`\nbut depend on one of the `hyps`, what we do depends on `clear_dependent`. If it\nis true, `H` is implicitly also cleared. If it is false, `clear'` fails. -/\nunsafe def tactic.clear' (clear_dependent : Bool) (hyps : List expr) : tactic Unit := do\n let tgt ← target\n -- Check if the target depends on any of the hyps. Doing this (instead of\n -- letting one of the later tactics fail) lets us give a much more informative\n -- error message.\n hyps\n fun h => do\n let dep ← kdepends_on tgt h\n when dep <| fail <| f! \"Cannot clear hypothesis {h} since the target depends on it.\"\n let n ← revert_lst hyps\n -- If revert_lst reverted more hypotheses than we wanted to clear, there must\n -- have been other hypotheses dependent on some of the hyps.\n when\n (!clear_dependent && n ≠ hyps) <|\n fail <|\n format.join\n [\"Some of the following hypotheses cannot be cleared because other \",\n \"hypotheses depend on (some of) them:\\n\", format.intercalate \", \" (hyps to_fmt)]\n let v ← mk_meta_var tgt\n intron n\n exact v\n let gs ← get_goals\n set_goals <| v :: gs\n#align tactic.clear' tactic.clear'\n\nnamespace Tactic.Interactive\n\n/-- An improved version of the standard `clear` tactic. `clear` is sensitive to the\norder of its arguments: `clear x y` may fail even though both `x` and `y` could\nbe cleared (if the type of `y` depends on `x`). `clear'` lifts this limitation.\n\n```lean\nexample {α} {β : α → Type} (a : α) (b : β a) : unit :=\nbegin\n try { clear a b }, -- fails since `b` depends on `a`\n clear' a b, -- succeeds\n exact ()\nend\n```\n-/\nunsafe def clear' (p : parse (many ident)) : tactic Unit := do\n let hyps ← p.mapM get_local\n tactic.clear' False hyps\n#align tactic.interactive.clear' tactic.interactive.clear'\n\n/-- A variant of `clear'` which clears not only the given hypotheses, but also any\nother hypotheses depending on them.\n\n```lean\nexample {α} {β : α → Type} (a : α) (b : β a) : unit :=\nbegin\n try { clear' a }, -- fails since `b` depends on `a`\n clear_dependent a, -- succeeds, clearing `a` and `b`\n exact ()\nend\n```\n -/\nunsafe def clear_dependent (p : parse (many ident)) : tactic Unit := do\n let hyps ← p.mapM get_local\n tactic.clear' True hyps\n#align tactic.interactive.clear_dependent tactic.interactive.clear_dependent\n\nadd_tactic_doc\n { Name := \"clear'\"\n category := DocCategory.tactic\n declNames := [`tactic.interactive.clear', `tactic.interactive.clear_dependent]\n tags := [\"context management\"]\n inheritDescriptionFrom := `tactic.interactive.clear' }\n\nend Tactic.Interactive\n\n", "meta": {"author": "leanprover-community", "repo": "mathlib3port", "sha": "62505aa236c58c8559783b16d33e30df3daa54f4", "save_path": "github-repos/lean/leanprover-community-mathlib3port", "path": "github-repos/lean/leanprover-community-mathlib3port/mathlib3port-62505aa236c58c8559783b16d33e30df3daa54f4/Mathbin/Tactic/Clear.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.36658973632215985, "lm_q2_score": 0.1311732135723892, "lm_q1q2_score": 0.04808675377603252}} {"text": "/-\nCopyright (c) 2020 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Leonardo de Moura, Mario Carneiro\n-/\nprelude\nimport Fixtures.Termination.Init.Prelude\nset_option linter.all false -- prevent error messages from runFrontend\n\n/-!\n# Coercion\n\nLean uses a somewhat elaborate system of typeclasses to drive the coercion system.\nHere a *coercion* means an invisible function that is automatically inserted\nto fix what would otherwise be a type error. For example, if we have:\n```\ndef f (x : Nat) : Int := x\n```\nthen this is clearly not type correct as is, because `x` has type `Nat` but\ntype `Int` is expected, and normally you will get an error message saying exactly that.\nBut before it shows that message, it will attempt to synthesize an instance of\n`CoeT Nat x Int`, which will end up going through all the other typeclasses defined\nbelow, to discover that there is an instance of `Coe Nat Int` defined.\n\nThis instance is defined as:\n```\ninstance : Coe Nat Int := ⟨Int.ofNat⟩\n```\nso Lean will elaborate the original function `f` as if it said:\n```\ndef f (x : Nat) : Int := Int.ofNat x\n```\nwhich is not a type error anymore.\n\nYou can also use the `↑` operator to explicitly indicate a coercion. Using `↑x`\ninstead of `x` in the example will result in the same output.\n\nBecause there are many polymorphic functions in Lean, it is often ambiguous where\nthe coercion can go. For example:\n```\ndef f (x y : Nat) : Int := x + y\n```\nThis could be either `↑x + ↑y` where `+` is the addition on `Int`, or `↑(x + y)`\nwhere `+` is addition on `Nat`, or even `x + y` using a heterogeneous addition\nwith the type `Nat → Nat → Int`. You can use the `↑` operator to disambiguate\nbetween these possibilities, but generally Lean will elaborate working from the\n\"outside in\", meaning that it will first look at the expression `_ + _ : Int`\nand assign the `+` to be the one for `Int`, and then need to insert coercions\nfor the subterms `↑x : Int` and `↑y : Int`, resulting in the `↑x + ↑y` version.\n\nNote that unlike most operators like `+`, `↑` is always eagerly unfolded at\nparse time into its definition. So if we look at the definition of `f` from\nbefore, we see no trace of the `CoeT.coe` function:\n```\ndef f (x : Nat) : Int := x\n#print f\n-- def f : Nat → Int :=\n-- fun (x : Nat) => Int.ofNat x\n```\n\n## Important typeclasses\n\nLean resolves a coercion by either inserting a `CoeDep` instance\nor chaining `CoeHead? CoeOut* Coe* CoeTail?` instances.\n(That is, zero or one `CoeHead` instances, an arbitrary number of `CoeOut`\ninstances, etc.)\n\nThe `CoeHead? CoeOut*` instances are chained from the \"left\" side.\nSo if Lean looks for a coercion from `Nat` to `Int`, it starts by trying coerce\n`Nat` using `CoeHead` by looking for a `CoeHead Nat ?α` instance, and then\ncontinuing with `CoeOut`. Similarly `Coe* CoeTail?` are chained from the \"right\".\n\nThese classes should be implemented for coercions:\n\n* `Coe α β` is the most basic class, and the usual one you will want to use\n when implementing a coercion for your own types.\n The variables in the type `α` must be a subset of the variables in `β`\n (or out-params of type class parameters),\n because `Coe` is chained right-to-left.\n\n* `CoeOut α β` is like `Coe α β` but chained left-to-right.\n Use this if the variables in the type `α` are a superset of the variables in `β`.\n\n* `CoeTail α β` is like `Coe α β`, but only applied once.\n Use this for coercions that would cause loops, like `[Ring R] → CoeTail Nat R`.\n\n* `CoeHead α β` is similar to `CoeOut α β`, but only applied once.\n Use this for coercions that would cause loops, like `[SetLike S α] → CoeHead S (Set α)`.\n\n* `CoeDep α (x : α) β` allows `β` to depend not only on `α` but on the value\n `x : α` itself. This is useful when the coercion function is dependent.\n An example of a dependent coercion is the instance for `Prop → Bool`, because\n it only holds for `Decidable` propositions. It is defined as:\n ```\n instance (p : Prop) [Decidable p] : CoeDep Prop p Bool := ...\n ```\n\n* `CoeFun α (γ : α → Sort v)` is a coercion to a function. `γ a` should be a\n (coercion-to-)function type, and this is triggered whenever an element\n `f : α` appears in an application like `f x` which would not make sense since\n `f` does not have a function type.\n `CoeFun` instances apply to `CoeOut` as well.\n\n* `CoeSort α β` is a coercion to a sort. `β` must be a universe, and if\n `a : α` appears in a place where a type is expected, like `(x : a)` or `a → a`.\n `CoeSort` instances apply to `CoeOut` as well.\n\nOn top of these instances this file defines several auxiliary type classes:\n * `CoeTC := Coe*`\n * `CoeOTC := CoeOut* Coe*`\n * `CoeHTC := CoeHead? CoeOut* Coe*`\n * `CoeHTCT := CoeHead? CoeOut* Coe* CoeTail?`\n * `CoeDep := CoeHead? CoeOut* Coe* CoeTail? | CoeDep`\n\n-/\n\nuniverse u v w w'\n\n/--\n`Coe α β` is the typeclass for coercions from `α` to `β`. It can be transitively\nchained with other `Coe` instances, and coercion is automatically used when\n`x` has type `α` but it is used in a context where `β` is expected.\nYou can use the `↑x` operator to explicitly trigger coercion.\n-/\nclass Coe (α : Sort u) (β : Sort v) where\n /-- Coerces a value of type `α` to type `β`. Accessible by the notation `↑x`,\n or by double type ascription `((x : α) : β)`. -/\n coe : α → β\nattribute [coe_decl] Coe.coe\n\n/--\nAuxiliary class implementing `Coe*`.\nUsers should generally not implement this directly.\n-/\nclass CoeTC (α : Sort u) (β : Sort v) where\n /-- Coerces a value of type `α` to type `β`. Accessible by the notation `↑x`,\n or by double type ascription `((x : α) : β)`. -/\n coe : α → β\nattribute [coe_decl] CoeTC.coe\n\ninstance [Coe β γ] [CoeTC α β] : CoeTC α γ where coe a := Coe.coe (CoeTC.coe a : β)\ninstance [Coe α β] : CoeTC α β where coe a := Coe.coe a\ninstance : CoeTC α α where coe a := a\n\n/--\n`CoeOut α β` is for coercions that are applied from left-to-right.\n-/\nclass CoeOut (α : Sort u) (β : Sort v) where\n /-- Coerces a value of type `α` to type `β`. Accessible by the notation `↑x`,\n or by double type ascription `((x : α) : β)`. -/\n coe : α → β\nattribute [coe_decl] CoeOut.coe\n\n/--\nAuxiliary class implementing `CoeOut* Coe*`.\nUsers should generally not implement this directly.\n-/\nclass CoeOTC (α : Sort u) (β : Sort v) where\n /-- Coerces a value of type `α` to type `β`. Accessible by the notation `↑x`,\n or by double type ascription `((x : α) : β)`. -/\n coe : α → β\nattribute [coe_decl] CoeOTC.coe\n\ninstance [CoeOut α β] [CoeOTC β γ] : CoeOTC α γ where coe a := CoeOTC.coe (CoeOut.coe a : β)\ninstance [CoeTC α β] : CoeOTC α β where coe a := CoeTC.coe a\ninstance : CoeOTC α α where coe a := a\n\n-- Note: ^^ We add reflexivity instances for CoeOTC/etc. so that we avoid going\n-- through a user-defined CoeTC/etc. instance. (Instances like\n-- `CoeTC F (A →+ B)` apply even when the two sides are defeq.)\n\n/--\n`CoeHead α β` is for coercions that are applied from left-to-right at most once\nat beginning of the coercion chain.\n-/\nclass CoeHead (α : Sort u) (β : Sort v) where\n /-- Coerces a value of type `α` to type `β`. Accessible by the notation `↑x`,\n or by double type ascription `((x : α) : β)`. -/\n coe : α → β\nattribute [coe_decl] CoeHead.coe\n\n/--\nAuxiliary class implementing `CoeHead CoeOut* Coe*`.\nUsers should generally not implement this directly.\n-/\nclass CoeHTC (α : Sort u) (β : Sort v) where\n /-- Coerces a value of type `α` to type `β`. Accessible by the notation `↑x`,\n or by double type ascription `((x : α) : β)`. -/\n coe : α → β\nattribute [coe_decl] CoeHTC.coe\n\ninstance [CoeHead α β] [CoeOTC β γ] : CoeHTC α γ where coe a := CoeOTC.coe (CoeHead.coe a : β)\ninstance [CoeOTC α β] : CoeHTC α β where coe a := CoeOTC.coe a\ninstance : CoeHTC α α where coe a := a\n\n/--\n`CoeTail α β` is for coercions that can only appear at the end of a\nsequence of coercions. That is, `α` can be further coerced via `Coe σ α` and\n`CoeHead τ σ` instances but `β` will only be the expected type of the expression.\n-/\nclass CoeTail (α : Sort u) (β : Sort v) where\n /-- Coerces a value of type `α` to type `β`. Accessible by the notation `↑x`,\n or by double type ascription `((x : α) : β)`. -/\n coe : α → β\nattribute [coe_decl] CoeTail.coe\n\n/--\nAuxiliary class implementing `CoeHead* Coe* CoeTail?`.\nUsers should generally not implement this directly.\n-/\nclass CoeHTCT (α : Sort u) (β : Sort v) where\n /-- Coerces a value of type `α` to type `β`. Accessible by the notation `↑x`,\n or by double type ascription `((x : α) : β)`. -/\n coe : α → β\nattribute [coe_decl] CoeHTCT.coe\n\ninstance [CoeTail β γ] [CoeHTC α β] : CoeHTCT α γ where coe a := CoeTail.coe (CoeHTC.coe a : β)\ninstance [CoeHTC α β] : CoeHTCT α β where coe a := CoeHTC.coe a\ninstance : CoeHTCT α α where coe a := a\n\n/--\n`CoeDep α (x : α) β` is a typeclass for dependent coercions, that is, the type `β`\ncan depend on `x` (or rather, the value of `x` is available to typeclass search\nso an instance that relates `β` to `x` is allowed).\n\nDependent coercions do not participate in the transitive chaining process of\nregular coercions: they must exactly match the type mismatch on both sides.\n-/\nclass CoeDep (α : Sort u) (_ : α) (β : Sort v) where\n /-- The resulting value of type `β`. The input `x : α` is a parameter to\n the type class, so the value of type `β` may possibly depend on additional\n typeclasses on `x`. -/\n coe : β\nattribute [coe_decl] CoeDep.coe\n\n/--\n`CoeT` is the core typeclass which is invoked by Lean to resolve a type error.\nIt can also be triggered explicitly with the notation `↑x` or by double type\nascription `((x : α) : β)`.\n\nA `CoeT` chain has the grammar `CoeHead? CoeOut* Coe* CoeTail? | CoeDep`.\n-/\nclass CoeT (α : Sort u) (_ : α) (β : Sort v) where\n /-- The resulting value of type `β`. The input `x : α` is a parameter to\n the type class, so the value of type `β` may possibly depend on additional\n typeclasses on `x`. -/\n coe : β\nattribute [coe_decl] CoeT.coe\n\ninstance [CoeHTCT α β] : CoeT α a β where coe := CoeHTCT.coe a\ninstance [CoeDep α a β] : CoeT α a β where coe := CoeDep.coe a\ninstance : CoeT α a α where coe := a\n\n/--\n`CoeFun α (γ : α → Sort v)` is a coercion to a function. `γ a` should be a\n(coercion-to-)function type, and this is triggered whenever an element\n`f : α` appears in an application like `f x` which would not make sense since\n`f` does not have a function type. This is automatically turned into `CoeFun.coe f x`.\n-/\nclass CoeFun (α : Sort u) (γ : outParam (α → Sort v)) where\n /-- Coerces a value `f : α` to type `γ f`, which should be either be a\n function type or another `CoeFun` type, in order to resolve a mistyped\n application `f x`. -/\n coe : (f : α) → γ f\nattribute [coe_decl] CoeFun.coe\n\ninstance [CoeFun α fun _ => β] : CoeOut α β where coe a := CoeFun.coe a\n\n/--\n`CoeSort α β` is a coercion to a sort. `β` must be a universe, and if\n`a : α` appears in a place where a type is expected, like `(x : a)` or `a → a`,\nthen it will be turned into `(x : CoeSort.coe a)`.\n-/\nclass CoeSort (α : Sort u) (β : outParam (Sort v)) where\n /-- Coerces a value of type `α` to `β`, which must be a universe. -/\n coe : α → β\nattribute [coe_decl] CoeSort.coe\n\ninstance [CoeSort α β] : CoeOut α β where coe a := CoeSort.coe a\n\n/--\n`↑x` represents a coercion, which converts `x` of type `α` to type `β`, using\ntypeclasses to resolve a suitable conversion function. You can often leave the\n`↑` off entirely, since coercion is triggered implicitly whenever there is a\ntype error, but in ambiguous cases it can be useful to use `↑` to disambiguate\nbetween e.g. `↑x + ↑y` and `↑(x + y)`.\n-/\nsyntax:1024 (name := coeNotation) \"↑\" term:1024 : term\n\n/-! # Basic instances -/\n\ninstance boolToProp : Coe Bool Prop where\n coe b := Eq b true\n\ninstance boolToSort : CoeSort Bool Prop where\n coe b := b\n\ninstance decPropToBool (p : Prop) [Decidable p] : CoeDep Prop p Bool where\n coe := decide p\n\ninstance optionCoe {α : Type u} : Coe α (Option α) where\n coe := some\n\ninstance subtypeCoe {α : Sort u} {p : α → Prop} : CoeOut (Subtype p) α where\n coe v := v.val\n\n/-! # Coe bridge -/\n\n/--\nHelper definition used by the elaborator. It is not meant to be used directly by users.\n\nThis is used for coercions between monads, in the case where we want to apply\na monad lift and a coercion on the result type at the same time.\n-/\n@[inline, coe_decl] def Lean.Internal.liftCoeM {m : Type u → Type v} {n : Type u → Type w} {α β : Type u}\n [MonadLiftT m n] [∀ a, CoeT α a β] [Monad n] (x : m α) : n β := do\n let a ← liftM x\n pure (CoeT.coe a)\n\n/--\nHelper definition used by the elaborator. It is not meant to be used directly by users.\n\nThis is used for coercing the result type under a monad.\n-/\n@[inline, coe_decl] def Lean.Internal.coeM {m : Type u → Type v} {α β : Type u}\n [∀ a, CoeT α a β] [Monad m] (x : m α) : m β := do\n let a ← x\n pure (CoeT.coe a)\n", "meta": {"author": "lurk-lab", "repo": "yatima", "sha": "f33b0bf1052d95f9acbbe61681b1b58c0b97121e", "save_path": "github-repos/lean/lurk-lab-yatima", "path": "github-repos/lean/lurk-lab-yatima/yatima-f33b0bf1052d95f9acbbe61681b1b58c0b97121e/Fixtures/Termination/Init/Coe.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47657965106367595, "lm_q2_score": 0.10087862070270603, "lm_q1q2_score": 0.04807669785428056}} {"text": "/-\nCopyright (c) 2021 Sébastien Gouëzel. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Sébastien Gouëzel\n-/\nimport measure_theory.measure.measure_space\n\n/-!\n# Almost everywhere measurable functions\n\nA function is almost everywhere measurable if it coincides almost everywhere with a measurable\nfunction. This property, called `ae_measurable f μ`, is defined in the file `measure_space_def`.\nWe discuss several of its properties that are analogous to properties of measurable functions.\n-/\n\nopen measure_theory measure_theory.measure filter set function\nopen_locale measure_theory filter classical ennreal interval\n\nvariables {ι α β γ δ R : Type*} {m0 : measurable_space α} [measurable_space β]\n [measurable_space γ] [measurable_space δ] {f g : α → β} {μ ν : measure α}\n\ninclude m0\n\nsection\n\n@[nontriviality, measurability]\nlemma subsingleton.ae_measurable [subsingleton α] : ae_measurable f μ :=\nsubsingleton.measurable.ae_measurable\n\n@[nontriviality, measurability]\nlemma ae_measurable_of_subsingleton_codomain [subsingleton β] : ae_measurable f μ :=\n(measurable_of_subsingleton_codomain f).ae_measurable\n\n@[simp, measurability] lemma ae_measurable_zero_measure : ae_measurable f (0 : measure α) :=\nbegin\n nontriviality α, inhabit α,\n exact ⟨λ x, f default, measurable_const, rfl⟩\nend\n\nnamespace ae_measurable\n\nlemma mono_measure (h : ae_measurable f μ) (h' : ν ≤ μ) : ae_measurable f ν :=\n⟨h.mk f, h.measurable_mk, eventually.filter_mono (ae_mono h') h.ae_eq_mk⟩\n\n\n\nprotected lemma mono' (h : ae_measurable f μ) (h' : ν ≪ μ) : ae_measurable f ν :=\n⟨h.mk f, h.measurable_mk, h' h.ae_eq_mk⟩\n\nlemma ae_mem_imp_eq_mk {s} (h : ae_measurable f (μ.restrict s)) :\n ∀ᵐ x ∂μ, x ∈ s → f x = h.mk f x :=\nae_imp_of_ae_restrict h.ae_eq_mk\n\nlemma ae_inf_principal_eq_mk {s} (h : ae_measurable f (μ.restrict s)) :\n f =ᶠ[μ.ae ⊓ 𝓟 s] h.mk f :=\nle_ae_restrict h.ae_eq_mk\n\n@[measurability]\nlemma sum_measure [countable ι] {μ : ι → measure α} (h : ∀ i, ae_measurable f (μ i)) :\n ae_measurable f (sum μ) :=\nbegin\n nontriviality β, inhabit β,\n set s : ι → set α := λ i, to_measurable (μ i) {x | f x ≠ (h i).mk f x},\n have hsμ : ∀ i, μ i (s i) = 0,\n { intro i, rw measure_to_measurable, exact (h i).ae_eq_mk },\n have hsm : measurable_set (⋂ i, s i),\n from measurable_set.Inter (λ i, measurable_set_to_measurable _ _),\n have hs : ∀ i x, x ∉ s i → f x = (h i).mk f x,\n { intros i x hx, contrapose! hx, exact subset_to_measurable _ _ hx },\n set g : α → β := (⋂ i, s i).piecewise (const α default) f,\n refine ⟨g, measurable_of_restrict_of_restrict_compl hsm _ _, ae_sum_iff.mpr $ λ i, _⟩,\n { rw [restrict_piecewise], simp only [set.restrict, const], exact measurable_const },\n { rw [restrict_piecewise_compl, compl_Inter],\n intros t ht,\n refine ⟨⋃ i, ((h i).mk f ⁻¹' t) ∩ (s i)ᶜ, measurable_set.Union $\n λ i, (measurable_mk _ ht).inter (measurable_set_to_measurable _ _).compl, _⟩,\n ext ⟨x, hx⟩,\n simp only [mem_preimage, mem_Union, subtype.coe_mk, set.restrict, mem_inter_iff,\n mem_compl_iff] at hx ⊢,\n split,\n { rintro ⟨i, hxt, hxs⟩, rwa hs _ _ hxs },\n { rcases hx with ⟨i, hi⟩, rw hs _ _ hi, exact λ h, ⟨i, h, hi⟩ } },\n { refine measure_mono_null (λ x (hx : f x ≠ g x), _) (hsμ i),\n contrapose! hx, refine (piecewise_eq_of_not_mem _ _ _ _).symm,\n exact λ h, hx (mem_Inter.1 h i) }\nend\n\n@[simp] lemma _root_.ae_measurable_sum_measure_iff [countable ι] {μ : ι → measure α} :\n ae_measurable f (sum μ) ↔ ∀ i, ae_measurable f (μ i) :=\n⟨λ h i, h.mono_measure (le_sum _ _), sum_measure⟩\n\n@[simp] lemma _root_.ae_measurable_add_measure_iff :\n ae_measurable f (μ + ν) ↔ ae_measurable f μ ∧ ae_measurable f ν :=\nby { rw [← sum_cond, ae_measurable_sum_measure_iff, bool.forall_bool, and.comm], refl }\n\n@[measurability]\nlemma add_measure {f : α → β} (hμ : ae_measurable f μ) (hν : ae_measurable f ν) :\n ae_measurable f (μ + ν) :=\nae_measurable_add_measure_iff.2 ⟨hμ, hν⟩\n\n@[measurability]\nprotected lemma Union [countable ι] {s : ι → set α} (h : ∀ i, ae_measurable f (μ.restrict (s i))) :\n ae_measurable f (μ.restrict (⋃ i, s i)) :=\n(sum_measure h).mono_measure $ restrict_Union_le\n\n@[simp] lemma _root_.ae_measurable_Union_iff [countable ι] {s : ι → set α} :\n ae_measurable f (μ.restrict (⋃ i, s i)) ↔ ∀ i, ae_measurable f (μ.restrict (s i)) :=\n⟨λ h i, h.mono_measure $ restrict_mono (subset_Union _ _) le_rfl, ae_measurable.Union⟩\n\n@[simp] lemma _root_.ae_measurable_union_iff {s t : set α} :\n ae_measurable f (μ.restrict (s ∪ t)) ↔\n ae_measurable f (μ.restrict s) ∧ ae_measurable f (μ.restrict t) :=\nby simp only [union_eq_Union, ae_measurable_Union_iff, bool.forall_bool, cond, and.comm]\n\n@[measurability]\nlemma smul_measure [monoid R] [distrib_mul_action R ℝ≥0∞] [is_scalar_tower R ℝ≥0∞ ℝ≥0∞]\n (h : ae_measurable f μ) (c : R) :\n ae_measurable f (c • μ) :=\n⟨h.mk f, h.measurable_mk, ae_smul_measure h.ae_eq_mk c⟩\n\nlemma comp_ae_measurable {f : α → δ} {g : δ → β}\n (hg : ae_measurable g (μ.map f)) (hf : ae_measurable f μ) : ae_measurable (g ∘ f) μ :=\n⟨hg.mk g ∘ hf.mk f, hg.measurable_mk.comp hf.measurable_mk,\n (ae_eq_comp hf hg.ae_eq_mk).trans ((hf.ae_eq_mk).fun_comp (mk g hg))⟩\n\nlemma comp_measurable {f : α → δ} {g : δ → β}\n (hg : ae_measurable g (μ.map f)) (hf : measurable f) : ae_measurable (g ∘ f) μ :=\nhg.comp_ae_measurable hf.ae_measurable\n\nlemma comp_quasi_measure_preserving {ν : measure δ} {f : α → δ} {g : δ → β} (hg : ae_measurable g ν)\n (hf : quasi_measure_preserving f μ ν) : ae_measurable (g ∘ f) μ :=\n(hg.mono' hf.absolutely_continuous).comp_measurable hf.measurable\n\nlemma map_map_of_ae_measurable {g : β → γ} {f : α → β}\n (hg : ae_measurable g (measure.map f μ)) (hf : ae_measurable f μ) :\n (μ.map f).map g = μ.map (g ∘ f) :=\nbegin\n ext1 s hs,\n let g' := hg.mk g,\n have A : map g (map f μ) = map g' (map f μ),\n { apply measure_theory.measure.map_congr,\n exact hg.ae_eq_mk },\n have B : map (g ∘ f) μ = map (g' ∘ f) μ,\n { apply measure_theory.measure.map_congr,\n exact ae_of_ae_map hf hg.ae_eq_mk },\n simp only [A, B, hs, hg.measurable_mk.ae_measurable.comp_ae_measurable hf, hg.measurable_mk,\n hg.measurable_mk hs, hf, map_apply, map_apply_of_ae_measurable],\n refl,\nend\n\n@[measurability]\nlemma prod_mk {f : α → β} {g : α → γ} (hf : ae_measurable f μ) (hg : ae_measurable g μ) :\n ae_measurable (λ x, (f x, g x)) μ :=\n⟨λ a, (hf.mk f a, hg.mk g a), hf.measurable_mk.prod_mk hg.measurable_mk,\n eventually_eq.prod_mk hf.ae_eq_mk hg.ae_eq_mk⟩\n\nlemma exists_ae_eq_range_subset (H : ae_measurable f μ) {t : set β} (ht : ∀ᵐ x ∂μ, f x ∈ t)\n (h₀ : t.nonempty) :\n ∃ g, measurable g ∧ range g ⊆ t ∧ f =ᵐ[μ] g :=\nbegin\n let s : set α := to_measurable μ {x | f x = H.mk f x ∧ f x ∈ t}ᶜ,\n let g : α → β := piecewise s (λ x, h₀.some) (H.mk f),\n refine ⟨g, _, _, _⟩,\n { exact measurable.piecewise (measurable_set_to_measurable _ _)\n measurable_const H.measurable_mk },\n { rintros _ ⟨x, rfl⟩,\n by_cases hx : x ∈ s,\n { simpa [g, hx] using h₀.some_mem },\n { simp only [g, hx, piecewise_eq_of_not_mem, not_false_iff],\n contrapose! hx,\n apply subset_to_measurable,\n simp only [hx, mem_compl_iff, mem_set_of_eq, not_and, not_false_iff, implies_true_iff]\n {contextual := tt} } },\n { have A : μ (to_measurable μ {x | f x = H.mk f x ∧ f x ∈ t}ᶜ) = 0,\n { rw [measure_to_measurable, ← compl_mem_ae_iff, compl_compl],\n exact H.ae_eq_mk.and ht },\n filter_upwards [compl_mem_ae_iff.2 A] with x hx,\n rw mem_compl_iff at hx,\n simp only [g, hx, piecewise_eq_of_not_mem, not_false_iff],\n contrapose! hx,\n apply subset_to_measurable,\n simp only [hx, mem_compl_iff, mem_set_of_eq, false_and, not_false_iff] }\nend\n\nlemma exists_measurable_nonneg {β} [preorder β] [has_zero β] {mβ : measurable_space β} {f : α → β}\n (hf : ae_measurable f μ) (f_nn : ∀ᵐ t ∂μ, 0 ≤ f t) :\n ∃ g, measurable g ∧ 0 ≤ g ∧ f =ᵐ[μ] g :=\nbegin\n obtain ⟨G, hG_meas, hG_mem, hG_ae_eq⟩ := hf.exists_ae_eq_range_subset f_nn ⟨0, le_rfl⟩,\n exact ⟨G, hG_meas, λ x, hG_mem (mem_range_self x), hG_ae_eq⟩,\nend\n\nlemma subtype_mk (h : ae_measurable f μ) {s : set β} {hfs : ∀ x, f x ∈ s} :\n ae_measurable (cod_restrict f s hfs) μ :=\nbegin\n nontriviality α, inhabit α,\n obtain ⟨g, g_meas, hg, fg⟩ : ∃ (g : α → β), measurable g ∧ range g ⊆ s ∧ f =ᵐ[μ] g :=\n h.exists_ae_eq_range_subset (eventually_of_forall hfs) ⟨_, hfs default⟩,\n refine ⟨cod_restrict g s (λ x, hg (mem_range_self _)), measurable.subtype_mk g_meas, _⟩,\n filter_upwards [fg] with x hx,\n simpa [subtype.ext_iff],\nend\n\nprotected lemma null_measurable (h : ae_measurable f μ) : null_measurable f μ :=\nlet ⟨g, hgm, hg⟩ := h in hgm.null_measurable.congr hg.symm\n\nend ae_measurable\n\nlemma ae_measurable_const' (h : ∀ᵐ x y ∂μ, f x = f y) : ae_measurable f μ :=\nbegin\n rcases eq_or_ne μ 0 with rfl | hμ,\n { exact ae_measurable_zero_measure },\n { haveI := ae_ne_bot.2 hμ,\n rcases h.exists with ⟨x, hx⟩,\n exact ⟨const α (f x), measurable_const, eventually_eq.symm hx⟩ }\nend\n\nlemma ae_measurable_uIoc_iff [linear_order α] {f : α → β} {a b : α} :\n (ae_measurable f $ μ.restrict $ Ι a b) ↔\n (ae_measurable f $ μ.restrict $ Ioc a b) ∧ (ae_measurable f $ μ.restrict $ Ioc b a) :=\nby rw [uIoc_eq_union, ae_measurable_union_iff]\n\nlemma ae_measurable_iff_measurable [μ.is_complete] :\n ae_measurable f μ ↔ measurable f :=\n⟨λ h, h.null_measurable.measurable_of_complete, λ h, h.ae_measurable⟩\n\nlemma measurable_embedding.ae_measurable_map_iff {g : β → γ} (hf : measurable_embedding f) :\n ae_measurable g (μ.map f) ↔ ae_measurable (g ∘ f) μ :=\nbegin\n refine ⟨λ H, H.comp_measurable hf.measurable, _⟩,\n rintro ⟨g₁, hgm₁, heq⟩,\n rcases hf.exists_measurable_extend hgm₁ (λ x, ⟨g x⟩) with ⟨g₂, hgm₂, rfl⟩,\n exact ⟨g₂, hgm₂, hf.ae_map_iff.2 heq⟩\nend\n\nlemma measurable_embedding.ae_measurable_comp_iff {g : β → γ}\n (hg : measurable_embedding g) {μ : measure α} :\n ae_measurable (g ∘ f) μ ↔ ae_measurable f μ :=\nbegin\n refine ⟨λ H, _, hg.measurable.comp_ae_measurable⟩,\n suffices : ae_measurable ((range_splitting g ∘ range_factorization g) ∘ f) μ,\n by rwa [(right_inverse_range_splitting hg.injective).comp_eq_id] at this,\n exact hg.measurable_range_splitting.comp_ae_measurable H.subtype_mk\nend\n\nlemma ae_measurable_restrict_iff_comap_subtype {s : set α} (hs : measurable_set s)\n {μ : measure α} {f : α → β} :\n ae_measurable f (μ.restrict s) ↔ ae_measurable (f ∘ coe : s → β) (comap coe μ) :=\nby rw [← map_comap_subtype_coe hs, (measurable_embedding.subtype_coe hs).ae_measurable_map_iff]\n\n@[simp, to_additive] lemma ae_measurable_one [has_one β] : ae_measurable (λ a : α, (1 : β)) μ :=\nmeasurable_one.ae_measurable\n\n@[simp] lemma ae_measurable_smul_measure_iff {c : ℝ≥0∞} (hc : c ≠ 0) :\n ae_measurable f (c • μ) ↔ ae_measurable f μ :=\n⟨λ h, ⟨h.mk f, h.measurable_mk, (ae_smul_measure_iff hc).1 h.ae_eq_mk⟩,\n λ h, ⟨h.mk f, h.measurable_mk, (ae_smul_measure_iff hc).2 h.ae_eq_mk⟩⟩\n\nlemma ae_measurable_of_ae_measurable_trim {α} {m m0 : measurable_space α}\n {μ : measure α} (hm : m ≤ m0) {f : α → β} (hf : ae_measurable f (μ.trim hm)) :\n ae_measurable f μ :=\n⟨hf.mk f, measurable.mono hf.measurable_mk hm le_rfl, ae_eq_of_ae_eq_trim hf.ae_eq_mk⟩\n\nlemma ae_measurable_restrict_of_measurable_subtype {s : set α}\n (hs : measurable_set s) (hf : measurable (λ x : s, f x)) : ae_measurable f (μ.restrict s) :=\n(ae_measurable_restrict_iff_comap_subtype hs).2 hf.ae_measurable\n\nlemma ae_measurable_map_equiv_iff (e : α ≃ᵐ β) {f : β → γ} :\n ae_measurable f (μ.map e) ↔ ae_measurable (f ∘ e) μ :=\ne.measurable_embedding.ae_measurable_map_iff\n\nend\n\nlemma ae_measurable.restrict (hfm : ae_measurable f μ) {s} :\n ae_measurable f (μ.restrict s) :=\n⟨ae_measurable.mk f hfm, hfm.measurable_mk, ae_restrict_of_ae hfm.ae_eq_mk⟩\n\nlemma ae_measurable_Ioi_of_forall_Ioc {β} {mβ : measurable_space β}\n [linear_order α] [(at_top : filter α).is_countably_generated] {x : α} {g : α → β}\n (g_meas : ∀ t > x, ae_measurable g (μ.restrict (Ioc x t))) :\n ae_measurable g (μ.restrict (Ioi x)) :=\nbegin\n haveI : nonempty α := ⟨x⟩,\n obtain ⟨u, hu_tendsto⟩ := exists_seq_tendsto (at_top : filter α),\n have Ioi_eq_Union : Ioi x = ⋃ n : ℕ, Ioc x (u n),\n { rw Union_Ioc_eq_Ioi_self_iff.mpr _,\n exact λ y _, (hu_tendsto.eventually (eventually_ge_at_top y)).exists },\n rw [Ioi_eq_Union, ae_measurable_Union_iff],\n intros n,\n cases lt_or_le x (u n),\n { exact g_meas (u n) h, },\n { rw [Ioc_eq_empty (not_lt.mpr h), measure.restrict_empty],\n exact ae_measurable_zero_measure, },\nend\n\nvariables [has_zero β]\n\nlemma ae_measurable_indicator_iff {s} (hs : measurable_set s) :\n ae_measurable (indicator s f) μ ↔ ae_measurable f (μ.restrict s) :=\nbegin\n split,\n { intro h,\n exact (h.mono_measure measure.restrict_le_self).congr (indicator_ae_eq_restrict hs) },\n { intro h,\n refine ⟨indicator s (h.mk f), h.measurable_mk.indicator hs, _⟩,\n have A : s.indicator f =ᵐ[μ.restrict s] s.indicator (ae_measurable.mk f h) :=\n (indicator_ae_eq_restrict hs).trans (h.ae_eq_mk.trans $ (indicator_ae_eq_restrict hs).symm),\n have B : s.indicator f =ᵐ[μ.restrict sᶜ] s.indicator (ae_measurable.mk f h) :=\n (indicator_ae_eq_restrict_compl hs).trans (indicator_ae_eq_restrict_compl hs).symm,\n exact ae_of_ae_restrict_of_ae_restrict_compl _ A B },\nend\n\n@[measurability]\nlemma ae_measurable.indicator (hfm : ae_measurable f μ) {s} (hs : measurable_set s) :\n ae_measurable (s.indicator f) μ :=\n(ae_measurable_indicator_iff hs).mpr hfm.restrict\n\nlemma measure_theory.measure.restrict_map_of_ae_measurable\n {f : α → δ} (hf : ae_measurable f μ) {s : set δ} (hs : measurable_set s) :\n (μ.map f).restrict s = (μ.restrict $ f ⁻¹' s).map f :=\ncalc\n(μ.map f).restrict s = (μ.map (hf.mk f)).restrict s :\n by { congr' 1, apply measure.map_congr hf.ae_eq_mk }\n... = (μ.restrict $ (hf.mk f) ⁻¹' s).map (hf.mk f) :\n measure.restrict_map hf.measurable_mk hs\n... = (μ.restrict $ (hf.mk f) ⁻¹' s).map f :\n measure.map_congr (ae_restrict_of_ae (hf.ae_eq_mk.symm))\n... = (μ.restrict $ f ⁻¹' s).map f :\nbegin\n apply congr_arg,\n ext1 t ht,\n simp only [ht, measure.restrict_apply],\n apply measure_congr,\n apply (eventually_eq.refl _ _).inter (hf.ae_eq_mk.symm.preimage s)\nend\n\nlemma measure_theory.measure.map_mono_of_ae_measurable\n {f : α → δ} (h : μ ≤ ν) (hf : ae_measurable f ν) :\n μ.map f ≤ ν.map f :=\nλ s hs, by simpa [hf, hs, hf.mono_measure h] using measure.le_iff'.1 h (f ⁻¹' s)\n", "meta": {"author": "leanprover-community", "repo": "mathlib", "sha": "5e526d18cea33550268dcbbddcb822d5cde40654", "save_path": "github-repos/lean/leanprover-community-mathlib", "path": "github-repos/lean/leanprover-community-mathlib/mathlib-5e526d18cea33550268dcbbddcb822d5cde40654/src/measure_theory/measure/ae_measurable.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48047867804790706, "lm_q2_score": 0.09947022189081604, "lm_q1q2_score": 0.04779332071923128}} {"text": "/-\nCopyright (c) 2021 Sébastien Gouëzel. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Sébastien Gouëzel\n-/\nimport measure_theory.measure.measure_space\n\n/-!\n# Almost everywhere measurable functions\n\nA function is almost everywhere measurable if it coincides almost everywhere with a measurable\nfunction. This property, called `ae_measurable f μ`, is defined in the file `measure_space_def`.\nWe discuss several of its properties that are analogous to properties of measurable functions.\n-/\n\nopen measure_theory measure_theory.measure filter set function\nopen_locale measure_theory filter classical ennreal interval\n\nvariables {ι α β γ δ R : Type*} {m0 : measurable_space α} [measurable_space β]\n [measurable_space γ] [measurable_space δ] {f g : α → β} {μ ν : measure α}\n\ninclude m0\n\nsection\n\n@[nontriviality, measurability]\nlemma subsingleton.ae_measurable [subsingleton α] : ae_measurable f μ :=\nsubsingleton.measurable.ae_measurable\n\n@[nontriviality, measurability]\nlemma ae_measurable_of_subsingleton_codomain [subsingleton β] : ae_measurable f μ :=\n(measurable_of_subsingleton_codomain f).ae_measurable\n\n@[simp, measurability] lemma ae_measurable_zero_measure : ae_measurable f (0 : measure α) :=\nbegin\n nontriviality α, inhabit α,\n exact ⟨λ x, f default, measurable_const, rfl⟩\nend\n\nnamespace ae_measurable\n\nlemma mono_measure (h : ae_measurable f μ) (h' : ν ≤ μ) : ae_measurable f ν :=\n⟨h.mk f, h.measurable_mk, eventually.filter_mono (ae_mono h') h.ae_eq_mk⟩\n\n\n\nprotected lemma mono' (h : ae_measurable f μ) (h' : ν ≪ μ) : ae_measurable f ν :=\n⟨h.mk f, h.measurable_mk, h' h.ae_eq_mk⟩\n\nlemma ae_mem_imp_eq_mk {s} (h : ae_measurable f (μ.restrict s)) :\n ∀ᵐ x ∂μ, x ∈ s → f x = h.mk f x :=\nae_imp_of_ae_restrict h.ae_eq_mk\n\nlemma ae_inf_principal_eq_mk {s} (h : ae_measurable f (μ.restrict s)) :\n f =ᶠ[μ.ae ⊓ 𝓟 s] h.mk f :=\nle_ae_restrict h.ae_eq_mk\n\n@[measurability]\nlemma sum_measure [encodable ι] {μ : ι → measure α} (h : ∀ i, ae_measurable f (μ i)) :\n ae_measurable f (sum μ) :=\nbegin\n nontriviality β, inhabit β,\n set s : ι → set α := λ i, to_measurable (μ i) {x | f x ≠ (h i).mk f x},\n have hsμ : ∀ i, μ i (s i) = 0,\n { intro i, rw measure_to_measurable, exact (h i).ae_eq_mk },\n have hsm : measurable_set (⋂ i, s i),\n from measurable_set.Inter (λ i, measurable_set_to_measurable _ _),\n have hs : ∀ i x, x ∉ s i → f x = (h i).mk f x,\n { intros i x hx, contrapose! hx, exact subset_to_measurable _ _ hx },\n set g : α → β := (⋂ i, s i).piecewise (const α default) f,\n refine ⟨g, measurable_of_restrict_of_restrict_compl hsm _ _, ae_sum_iff.mpr $ λ i, _⟩,\n { rw [restrict_piecewise], simp only [set.restrict, const], exact measurable_const },\n { rw [restrict_piecewise_compl, compl_Inter],\n intros t ht,\n refine ⟨⋃ i, ((h i).mk f ⁻¹' t) ∩ (s i)ᶜ, measurable_set.Union $\n λ i, (measurable_mk _ ht).inter (measurable_set_to_measurable _ _).compl, _⟩,\n ext ⟨x, hx⟩,\n simp only [mem_preimage, mem_Union, subtype.coe_mk, set.restrict, mem_inter_eq,\n mem_compl_iff] at hx ⊢,\n split,\n { rintro ⟨i, hxt, hxs⟩, rwa hs _ _ hxs },\n { rcases hx with ⟨i, hi⟩, rw hs _ _ hi, exact λ h, ⟨i, h, hi⟩ } },\n { refine measure_mono_null (λ x (hx : f x ≠ g x), _) (hsμ i),\n contrapose! hx, refine (piecewise_eq_of_not_mem _ _ _ _).symm,\n exact λ h, hx (mem_Inter.1 h i) }\nend\n\n@[simp] lemma _root_.ae_measurable_sum_measure_iff [encodable ι] {μ : ι → measure α} :\n ae_measurable f (sum μ) ↔ ∀ i, ae_measurable f (μ i) :=\n⟨λ h i, h.mono_measure (le_sum _ _), sum_measure⟩\n\n@[simp] lemma _root_.ae_measurable_add_measure_iff :\n ae_measurable f (μ + ν) ↔ ae_measurable f μ ∧ ae_measurable f ν :=\nby { rw [← sum_cond, ae_measurable_sum_measure_iff, bool.forall_bool, and.comm], refl }\n\n@[measurability]\nlemma add_measure {f : α → β} (hμ : ae_measurable f μ) (hν : ae_measurable f ν) :\n ae_measurable f (μ + ν) :=\nae_measurable_add_measure_iff.2 ⟨hμ, hν⟩\n\n@[measurability]\nprotected lemma Union [encodable ι] {s : ι → set α} (h : ∀ i, ae_measurable f (μ.restrict (s i))) :\n ae_measurable f (μ.restrict (⋃ i, s i)) :=\n(sum_measure h).mono_measure $ restrict_Union_le\n\n@[simp] lemma _root_.ae_measurable_Union_iff [encodable ι] {s : ι → set α} :\n ae_measurable f (μ.restrict (⋃ i, s i)) ↔ ∀ i, ae_measurable f (μ.restrict (s i)) :=\n⟨λ h i, h.mono_measure $ restrict_mono (subset_Union _ _) le_rfl, ae_measurable.Union⟩\n\n@[simp] lemma _root_.ae_measurable_union_iff {s t : set α} :\n ae_measurable f (μ.restrict (s ∪ t)) ↔\n ae_measurable f (μ.restrict s) ∧ ae_measurable f (μ.restrict t) :=\nby simp only [union_eq_Union, ae_measurable_Union_iff, bool.forall_bool, cond, and.comm]\n\n@[measurability]\nlemma smul_measure [monoid R] [distrib_mul_action R ℝ≥0∞] [is_scalar_tower R ℝ≥0∞ ℝ≥0∞]\n (h : ae_measurable f μ) (c : R) :\n ae_measurable f (c • μ) :=\n⟨h.mk f, h.measurable_mk, ae_smul_measure h.ae_eq_mk c⟩\n\nlemma comp_ae_measurable {f : α → δ} {g : δ → β}\n (hg : ae_measurable g (μ.map f)) (hf : ae_measurable f μ) : ae_measurable (g ∘ f) μ :=\n⟨hg.mk g ∘ hf.mk f, hg.measurable_mk.comp hf.measurable_mk,\n (ae_eq_comp hf hg.ae_eq_mk).trans ((hf.ae_eq_mk).fun_comp (mk g hg))⟩\n\nlemma comp_measurable {f : α → δ} {g : δ → β}\n (hg : ae_measurable g (μ.map f)) (hf : measurable f) : ae_measurable (g ∘ f) μ :=\nhg.comp_ae_measurable hf.ae_measurable\n\nlemma comp_measurable' {ν : measure δ} {f : α → δ} {g : δ → β} (hg : ae_measurable g ν)\n (hf : measurable f) (h : μ.map f ≪ ν) : ae_measurable (g ∘ f) μ :=\n(hg.mono' h).comp_measurable hf\n\nlemma map_map_of_ae_measurable {g : β → γ} {f : α → β}\n (hg : ae_measurable g (measure.map f μ)) (hf : ae_measurable f μ) :\n (μ.map f).map g = μ.map (g ∘ f) :=\nbegin\n ext1 s hs,\n let g' := hg.mk g,\n have A : map g (map f μ) = map g' (map f μ),\n { apply measure_theory.measure.map_congr,\n exact hg.ae_eq_mk },\n have B : map (g ∘ f) μ = map (g' ∘ f) μ,\n { apply measure_theory.measure.map_congr,\n exact ae_of_ae_map hf hg.ae_eq_mk },\n simp only [A, B, hs, hg.measurable_mk.ae_measurable.comp_ae_measurable hf, hg.measurable_mk,\n hg.measurable_mk hs, hf, map_apply, map_apply_of_ae_measurable],\n refl,\nend\n\n@[measurability]\nlemma prod_mk {f : α → β} {g : α → γ} (hf : ae_measurable f μ) (hg : ae_measurable g μ) :\n ae_measurable (λ x, (f x, g x)) μ :=\n⟨λ a, (hf.mk f a, hg.mk g a), hf.measurable_mk.prod_mk hg.measurable_mk,\n eventually_eq.prod_mk hf.ae_eq_mk hg.ae_eq_mk⟩\n\nlemma exists_ae_eq_range_subset (H : ae_measurable f μ) {t : set β} (ht : ∀ᵐ x ∂μ, f x ∈ t)\n (h₀ : t.nonempty) :\n ∃ g, measurable g ∧ range g ⊆ t ∧ f =ᵐ[μ] g :=\nbegin\n let s : set α := to_measurable μ {x | f x = H.mk f x ∧ f x ∈ t}ᶜ,\n let g : α → β := piecewise s (λ x, h₀.some) (H.mk f),\n refine ⟨g, _, _, _⟩,\n { exact measurable.piecewise (measurable_set_to_measurable _ _)\n measurable_const H.measurable_mk },\n { rintros _ ⟨x, rfl⟩,\n by_cases hx : x ∈ s,\n { simpa [g, hx] using h₀.some_mem },\n { simp only [g, hx, piecewise_eq_of_not_mem, not_false_iff],\n contrapose! hx,\n apply subset_to_measurable,\n simp only [hx, mem_compl_eq, mem_set_of_eq, not_and, not_false_iff, implies_true_iff]\n {contextual := tt} } },\n { have A : μ (to_measurable μ {x | f x = H.mk f x ∧ f x ∈ t}ᶜ) = 0,\n { rw [measure_to_measurable, ← compl_mem_ae_iff, compl_compl],\n exact H.ae_eq_mk.and ht },\n filter_upwards [compl_mem_ae_iff.2 A] with x hx,\n rw mem_compl_iff at hx,\n simp only [g, hx, piecewise_eq_of_not_mem, not_false_iff],\n contrapose! hx,\n apply subset_to_measurable,\n simp only [hx, mem_compl_eq, mem_set_of_eq, false_and, not_false_iff] }\nend\n\nlemma subtype_mk (h : ae_measurable f μ) {s : set β} {hfs : ∀ x, f x ∈ s} :\n ae_measurable (cod_restrict f s hfs) μ :=\nbegin\n nontriviality α, inhabit α,\n obtain ⟨g, g_meas, hg, fg⟩ : ∃ (g : α → β), measurable g ∧ range g ⊆ s ∧ f =ᵐ[μ] g :=\n h.exists_ae_eq_range_subset (eventually_of_forall hfs) ⟨_, hfs default⟩,\n refine ⟨cod_restrict g s (λ x, hg (mem_range_self _)), measurable.subtype_mk g_meas, _⟩,\n filter_upwards [fg] with x hx,\n simpa [subtype.ext_iff],\nend\n\nprotected lemma null_measurable (h : ae_measurable f μ) : null_measurable f μ :=\nlet ⟨g, hgm, hg⟩ := h in hgm.null_measurable.congr hg.symm\n\nend ae_measurable\n\nlemma ae_measurable_interval_oc_iff [linear_order α] {f : α → β} {a b : α} :\n (ae_measurable f $ μ.restrict $ Ι a b) ↔\n (ae_measurable f $ μ.restrict $ Ioc a b) ∧ (ae_measurable f $ μ.restrict $ Ioc b a) :=\nby rw [interval_oc_eq_union, ae_measurable_union_iff]\n\nlemma ae_measurable_iff_measurable [μ.is_complete] :\n ae_measurable f μ ↔ measurable f :=\n⟨λ h, h.null_measurable.measurable_of_complete, λ h, h.ae_measurable⟩\n\nlemma measurable_embedding.ae_measurable_map_iff {g : β → γ} (hf : measurable_embedding f) :\n ae_measurable g (μ.map f) ↔ ae_measurable (g ∘ f) μ :=\nbegin\n refine ⟨λ H, H.comp_measurable hf.measurable, _⟩,\n rintro ⟨g₁, hgm₁, heq⟩,\n rcases hf.exists_measurable_extend hgm₁ (λ x, ⟨g x⟩) with ⟨g₂, hgm₂, rfl⟩,\n exact ⟨g₂, hgm₂, hf.ae_map_iff.2 heq⟩\nend\n\nlemma measurable_embedding.ae_measurable_comp_iff {g : β → γ}\n (hg : measurable_embedding g) {μ : measure α} :\n ae_measurable (g ∘ f) μ ↔ ae_measurable f μ :=\nbegin\n refine ⟨λ H, _, hg.measurable.comp_ae_measurable⟩,\n suffices : ae_measurable ((range_splitting g ∘ range_factorization g) ∘ f) μ,\n by rwa [(right_inverse_range_splitting hg.injective).comp_eq_id] at this,\n exact hg.measurable_range_splitting.comp_ae_measurable H.subtype_mk\nend\n\nlemma ae_measurable_restrict_iff_comap_subtype {s : set α} (hs : measurable_set s)\n {μ : measure α} {f : α → β} :\n ae_measurable f (μ.restrict s) ↔ ae_measurable (f ∘ coe : s → β) (comap coe μ) :=\nby rw [← map_comap_subtype_coe hs, (measurable_embedding.subtype_coe hs).ae_measurable_map_iff]\n\n@[simp, to_additive] lemma ae_measurable_one [has_one β] : ae_measurable (λ a : α, (1 : β)) μ :=\nmeasurable_one.ae_measurable\n\n@[simp] lemma ae_measurable_smul_measure_iff {c : ℝ≥0∞} (hc : c ≠ 0) :\n ae_measurable f (c • μ) ↔ ae_measurable f μ :=\n⟨λ h, ⟨h.mk f, h.measurable_mk, (ae_smul_measure_iff hc).1 h.ae_eq_mk⟩,\n λ h, ⟨h.mk f, h.measurable_mk, (ae_smul_measure_iff hc).2 h.ae_eq_mk⟩⟩\n\nlemma ae_measurable_of_ae_measurable_trim {α} {m m0 : measurable_space α}\n {μ : measure α} (hm : m ≤ m0) {f : α → β} (hf : ae_measurable f (μ.trim hm)) :\n ae_measurable f μ :=\n⟨hf.mk f, measurable.mono hf.measurable_mk hm le_rfl, ae_eq_of_ae_eq_trim hf.ae_eq_mk⟩\n\nlemma ae_measurable_restrict_of_measurable_subtype {s : set α}\n (hs : measurable_set s) (hf : measurable (λ x : s, f x)) : ae_measurable f (μ.restrict s) :=\n(ae_measurable_restrict_iff_comap_subtype hs).2 hf.ae_measurable\n\nlemma ae_measurable_map_equiv_iff (e : α ≃ᵐ β) {f : β → γ} :\n ae_measurable f (μ.map e) ↔ ae_measurable (f ∘ e) μ :=\ne.measurable_embedding.ae_measurable_map_iff\n\nend\n\nlemma ae_measurable.restrict (hfm : ae_measurable f μ) {s} :\n ae_measurable f (μ.restrict s) :=\n⟨ae_measurable.mk f hfm, hfm.measurable_mk, ae_restrict_of_ae hfm.ae_eq_mk⟩\n\nvariables [has_zero β]\n\nlemma ae_measurable_indicator_iff {s} (hs : measurable_set s) :\n ae_measurable (indicator s f) μ ↔ ae_measurable f (μ.restrict s) :=\nbegin\n split,\n { intro h,\n exact (h.mono_measure measure.restrict_le_self).congr (indicator_ae_eq_restrict hs) },\n { intro h,\n refine ⟨indicator s (h.mk f), h.measurable_mk.indicator hs, _⟩,\n have A : s.indicator f =ᵐ[μ.restrict s] s.indicator (ae_measurable.mk f h) :=\n (indicator_ae_eq_restrict hs).trans (h.ae_eq_mk.trans $ (indicator_ae_eq_restrict hs).symm),\n have B : s.indicator f =ᵐ[μ.restrict sᶜ] s.indicator (ae_measurable.mk f h) :=\n (indicator_ae_eq_restrict_compl hs).trans (indicator_ae_eq_restrict_compl hs).symm,\n exact ae_of_ae_restrict_of_ae_restrict_compl _ A B },\nend\n\n@[measurability]\nlemma ae_measurable.indicator (hfm : ae_measurable f μ) {s} (hs : measurable_set s) :\n ae_measurable (s.indicator f) μ :=\n(ae_measurable_indicator_iff hs).mpr hfm.restrict\n\nlemma measure_theory.measure.restrict_map_of_ae_measurable\n {f : α → δ} (hf : ae_measurable f μ) {s : set δ} (hs : measurable_set s) :\n (μ.map f).restrict s = (μ.restrict $ f ⁻¹' s).map f :=\ncalc\n(μ.map f).restrict s = (μ.map (hf.mk f)).restrict s :\n by { congr' 1, apply measure.map_congr hf.ae_eq_mk }\n... = (μ.restrict $ (hf.mk f) ⁻¹' s).map (hf.mk f) :\n measure.restrict_map hf.measurable_mk hs\n... = (μ.restrict $ (hf.mk f) ⁻¹' s).map f :\n measure.map_congr (ae_restrict_of_ae (hf.ae_eq_mk.symm))\n... = (μ.restrict $ f ⁻¹' s).map f :\nbegin\n apply congr_arg,\n ext1 t ht,\n simp only [ht, measure.restrict_apply],\n apply measure_congr,\n apply (eventually_eq.refl _ _).inter (hf.ae_eq_mk.symm.preimage s)\nend\n\nlemma measure_theory.measure.map_mono_of_ae_measurable\n {f : α → δ} (h : μ ≤ ν) (hf : ae_measurable f ν) :\n μ.map f ≤ ν.map f :=\nλ s hs, by simpa [hf, hs, hf.mono_measure h] using measure.le_iff'.1 h (f ⁻¹' s)\n", "meta": {"author": "nick-kuhn", "repo": "leantools", "sha": "567a98c031fffe3f270b7b8dea48389bc70d7abb", "save_path": "github-repos/lean/nick-kuhn-leantools", "path": "github-repos/lean/nick-kuhn-leantools/leantools-567a98c031fffe3f270b7b8dea48389bc70d7abb/src/measure_theory/measure/ae_measurable.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4843800842769843, "lm_q2_score": 0.09807933006122668, "lm_q1q2_score": 0.047507674160887144}} {"text": "/-\nCopyright (c) 2019 Simon Hudon. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Simon Hudon\n-/\nimport category_theory.category\n\n/-!\n# Tools to reformulate category-theoretic axioms in a more associativity-friendly way\n\n## The `reassoc` attribute\n\nThe `reassoc` attribute can be applied to a lemma\n\n```lean\n@[reassoc]\nlemma some_lemma : foo ≫ bar = baz := ...\n```\n\nand produce\n\n```lean\nlemma some_lemma_assoc {Y : C} (f : X ⟶ Y) : foo ≫ bar ≫ f = baz ≫ f := ...\n```\n\nThe name of the produced lemma can be specified with `@[reassoc other_lemma_name]`. If\n`simp` is added first, the generated lemma will also have the `simp` attribute.\n\n## The `reassoc_axiom` command\n\nWhen declaring a class of categories, the axioms can be reformulated to be more amenable\nto manipulation in right associated expressions:\n\n```lean\nclass some_class (C : Type) [category C] :=\n(foo : Π X : C, X ⟶ X)\n(bar : ∀ {X Y : C} (f : X ⟶ Y), foo X ≫ f = f ≫ foo Y)\n\nreassoc_axiom some_class.bar\n```\n\nHere too, the `reassoc` attribute can be used instead. It works well when combined with\n`simp`:\n\n```lean\nattribute [simp, reassoc] some_class.bar\n```\n-/\n\nnamespace tactic\n\nopen interactive lean.parser category_theory\n\n/-- From an expression `f ≫ g`, extract the expression representing the category instance. -/\nmeta def get_cat_inst : expr → tactic expr\n| `(@category_struct.comp _ %%struct_inst _ _ _ _ _) := pure struct_inst\n| _ := failed\n\n/-- (internals for `@[reassoc]`)\nGiven a lemma of the form `∀ ..., f ≫ g = h`, proves a new lemma of the form\n`h : ∀ ... {W} (k), f ≫ (g ≫ k) = h ≫ k`, and returns the type and proof of this lemma.\n-/\nmeta def prove_reassoc (h : expr) : tactic (expr × expr) :=\ndo\n (vs,t) ← infer_type h >>= open_pis,\n (lhs,rhs) ← match_eq t,\n struct_inst ← get_cat_inst lhs <|> get_cat_inst rhs <|> fail \"no composition found in statement\",\n `(@quiver.hom _ %%hom_inst %%X %%Y) ← infer_type lhs,\n C ← infer_type X,\n X' ← mk_local' `X' binder_info.implicit C,\n ft ← to_expr ``(@quiver.hom _ %%hom_inst %%Y %%X'),\n f' ← mk_local_def `f' ft,\n t' ← to_expr ``(@category_struct.comp _ %%struct_inst _ _ _%%lhs %%f' =\n @category_struct.comp _ %%struct_inst _ _ _ %%rhs %%f'),\n let c' := h.mk_app vs,\n (_,pr) ← solve_aux t' (rewrite_target c'; reflexivity),\n pr ← instantiate_mvars pr,\n let s := simp_lemmas.mk,\n s ← s.add_simp ``category.assoc,\n s ← s.add_simp ``category.id_comp,\n s ← s.add_simp ``category.comp_id,\n (t'', pr', _) ← simplify s [] t',\n pr' ← mk_eq_mp pr' pr,\n t'' ← pis (vs ++ [X',f']) t'',\n pr' ← lambdas (vs ++ [X',f']) pr',\n pure (t'',pr')\n\n/-- (implementation for `@[reassoc]`)\nGiven a declaration named `n` of the form `∀ ..., f ≫ g = h`, proves a new lemma named `n'`\nof the form `∀ ... {W} (k), f ≫ (g ≫ k) = h ≫ k`.\n-/\nmeta def reassoc_axiom (n : name) (n' : name := n.append_suffix \"_assoc\") : tactic unit :=\ndo d ← get_decl n,\n let ls := d.univ_params.map level.param,\n let c := @expr.const tt n ls,\n (t'',pr') ← prove_reassoc c,\n add_decl $ declaration.thm n' d.univ_params t'' (pure pr'),\n copy_attribute `simp n n'\n\n/--\nThe `reassoc` attribute can be applied to a lemma\n\n```lean\n@[reassoc]\nlemma some_lemma : foo ≫ bar = baz := ...\n```\n\nto produce\n\n```lean\nlemma some_lemma_assoc {Y : C} (f : X ⟶ Y) : foo ≫ bar ≫ f = baz ≫ f := ...\n```\n\nThe name of the produced lemma can be specified with `@[reassoc other_lemma_name]`. If\n`simp` is added first, the generated lemma will also have the `simp` attribute.\n-/\n@[user_attribute]\nmeta def reassoc_attr : user_attribute unit (option name) :=\n{ name := `reassoc,\n descr := \"create a companion lemma for associativity-aware rewriting\",\n parser := optional ident,\n after_set := some (λ n _ _,\n do some n' ← reassoc_attr.get_param n | reassoc_axiom n (n.append_suffix \"_assoc\"),\n reassoc_axiom n $ n.get_prefix ++ n' ) }\n\nadd_tactic_doc\n{ name := \"reassoc\",\n category := doc_category.attr,\n decl_names := [`tactic.reassoc_attr],\n tags := [\"category theory\"] }\n\n/--\nWhen declaring a class of categories, the axioms can be reformulated to be more amenable\nto manipulation in right associated expressions:\n\n```lean\nclass some_class (C : Type) [category C] :=\n(foo : Π X : C, X ⟶ X)\n(bar : ∀ {X Y : C} (f : X ⟶ Y), foo X ≫ f = f ≫ foo Y)\n\nreassoc_axiom some_class.bar\n```\n\nThe above will produce:\n\n```lean\nlemma some_class.bar_assoc {Z : C} (g : Y ⟶ Z) :\n foo X ≫ f ≫ g = f ≫ foo Y ≫ g := ...\n```\n\nHere too, the `reassoc` attribute can be used instead. It works well when combined with\n`simp`:\n\n```lean\nattribute [simp, reassoc] some_class.bar\n```\n-/\n@[user_command]\nmeta def reassoc_cmd (_ : parse $ tk \"reassoc_axiom\") : lean.parser unit :=\ndo n ← ident,\n of_tactic $\n do n ← resolve_constant n,\n reassoc_axiom n\n\nadd_tactic_doc\n{ name := \"reassoc_axiom\",\n category := doc_category.cmd,\n decl_names := [`tactic.reassoc_cmd],\n tags := [\"category theory\"] }\n\nnamespace interactive\n\nsetup_tactic_parser\n\n/-- `reassoc h`, for assumption `h : x ≫ y = z`, creates a new assumption\n`h : ∀ {W} (f : Z ⟶ W), x ≫ y ≫ f = z ≫ f`.\n`reassoc! h`, does the same but deletes the initial `h` assumption.\n(You can also add the attribute `@[reassoc]` to lemmas to generate new declarations generalized\nin this way.)\n-/\nmeta def reassoc (del : parse (tk \"!\")?) (ns : parse ident*) : tactic unit :=\ndo ns.mmap' (λ n,\n do h ← get_local n,\n (t,pr) ← prove_reassoc h,\n assertv n t pr,\n when del.is_some (tactic.clear h) )\n\nend interactive\n\ndef calculated_Prop {α} (β : Prop) (hh : α) := β\n\nmeta def derive_reassoc_proof : tactic unit :=\ndo `(calculated_Prop %%v %%h) ← target,\n (t,pr) ← prove_reassoc h,\n unify v t,\n exact pr\n\nend tactic\n\n/-- With `h : x ≫ y ≫ z = x` (with universal quantifiers tolerated),\n`reassoc_of h : ∀ {X'} (f : W ⟶ X'), x ≫ y ≫ z ≫ f = x ≫ f`.\n\nThe type and proof of `reassoc_of h` is generated by `tactic.derive_reassoc_proof`\nwhich make `reassoc_of` meta-programming adjacent. It is not called as a tactic but as\nan expression. The goal is to avoid creating assumptions that are dismissed after one use:\n\n```lean\nexample (X Y Z W : C) (x : X ⟶ Y) (y : Y ⟶ Z) (z z' : Z ⟶ W) (w : X ⟶ Z)\n (h : x ≫ y = w)\n (h' : y ≫ z = y ≫ z') :\n x ≫ y ≫ z = w ≫ z' :=\nbegin\n rw [h',reassoc_of h],\nend\n```\n-/\ntheorem category_theory.reassoc_of {α} (hh : α) {β}\n (x : tactic.calculated_Prop β hh . tactic.derive_reassoc_proof) : β := x\n\n/--\n`reassoc_of h` takes local assumption `h` and add a ` ≫ f` term on the right of\nboth sides of the equality. Instead of creating a new assumption from the result, `reassoc_of h`\nstands for the proof of that reassociated statement. This keeps complicated assumptions that are\nused only once or twice from polluting the local context.\n\nIn the following, assumption `h` is needed in a reassociated form. Instead of proving it as a new\ngoal and adding it as an assumption, we use `reassoc_of h` as a rewrite rule which works just as\nwell.\n\n```lean\nexample (X Y Z W : C) (x : X ⟶ Y) (y : Y ⟶ Z) (z z' : Z ⟶ W) (w : X ⟶ Z)\n (h : x ≫ y = w)\n (h' : y ≫ z = y ≫ z') :\n x ≫ y ≫ z = w ≫ z' :=\nbegin\n -- reassoc_of h : ∀ {X' : C} (f : W ⟶ X'), x ≫ y ≫ f = w ≫ f\n rw [h',reassoc_of h],\nend\n```\n\nAlthough `reassoc_of` is not a tactic or a meta program, its type is generated\nthrough meta-programming to make it usable inside normal expressions.\n-/\nadd_tactic_doc\n{ name := \"category_theory.reassoc_of\",\n category := doc_category.tactic,\n decl_names := [`category_theory.reassoc_of],\n tags := [\"category theory\"] }\n", "meta": {"author": "JLimperg", "repo": "aesop3", "sha": "a4a116f650cc7403428e72bd2e2c4cda300fe03f", "save_path": "github-repos/lean/JLimperg-aesop3", "path": "github-repos/lean/JLimperg-aesop3/aesop3-a4a116f650cc7403428e72bd2e2c4cda300fe03f/src/tactic/reassoc_axiom.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40356686808225123, "lm_q2_score": 0.11757214436736566, "lm_q1q2_score": 0.04744822207605205}} {"text": "/-\nCopyright (c) 2021 Yakov Pechersky. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Yakov Pechersky\n\n! This file was ported from Lean 3 source module data.list.cycle\n! leanprover-community/mathlib commit 728baa2f54e6062c5879a3e397ac6bac323e506f\n! Please do not edit these lines, except to modify the commit id\n! if you have ported upstream changes.\n-/\nimport Mathbin.Data.Multiset.Sort\nimport Mathbin.Data.Fintype.List\nimport Mathbin.Data.List.Rotate\n\n/-!\n# Cycles of a list\n\n> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.\n> Any changes to this file require a corresponding PR to mathlib4.\n\nLists have an equivalence relation of whether they are rotational permutations of one another.\nThis relation is defined as `is_rotated`.\n\nBased on this, we define the quotient of lists by the rotation relation, called `cycle`.\n\nWe also define a representation of concrete cycles, available when viewing them in a goal state or\nvia `#eval`, when over representatble types. For example, the cycle `(2 1 4 3)` will be shown\nas `c[2, 1, 4, 3]`. Two equal cycles may be printed differently if their internal representation\nis different.\n\n-/\n\n\nnamespace List\n\nvariable {α : Type _} [DecidableEq α]\n\n#print List.nextOr /-\n/-- Return the `z` such that `x :: z :: _` appears in `xs`, or `default` if there is no such `z`. -/\ndef nextOr : ∀ (xs : List α) (x default : α), α\n | [], x, default => default\n | [y], x, default => default\n |-- Handles the not-found and the wraparound case\n y ::\n z :: xs,\n x, default => if x = y then z else next_or (z :: xs) x default\n#align list.next_or List.nextOr\n-/\n\n#print List.nextOr_nil /-\n@[simp]\ntheorem nextOr_nil (x d : α) : nextOr [] x d = d :=\n rfl\n#align list.next_or_nil List.nextOr_nil\n-/\n\n#print List.nextOr_singleton /-\n@[simp]\ntheorem nextOr_singleton (x y d : α) : nextOr [y] x d = d :=\n rfl\n#align list.next_or_singleton List.nextOr_singleton\n-/\n\n#print List.nextOr_self_cons_cons /-\n@[simp]\ntheorem nextOr_self_cons_cons (xs : List α) (x y d : α) : nextOr (x :: y :: xs) x d = y :=\n if_pos rfl\n#align list.next_or_self_cons_cons List.nextOr_self_cons_cons\n-/\n\n#print List.nextOr_cons_of_ne /-\ntheorem nextOr_cons_of_ne (xs : List α) (y x d : α) (h : x ≠ y) :\n nextOr (y :: xs) x d = nextOr xs x d :=\n by\n cases' xs with z zs\n · rfl\n · exact if_neg h\n#align list.next_or_cons_of_ne List.nextOr_cons_of_ne\n-/\n\n#print List.nextOr_eq_nextOr_of_mem_of_ne /-\n/-- `next_or` does not depend on the default value, if the next value appears. -/\ntheorem nextOr_eq_nextOr_of_mem_of_ne (xs : List α) (x d d' : α) (x_mem : x ∈ xs)\n (x_ne : x ≠ xs.getLast (ne_nil_of_mem x_mem)) : nextOr xs x d = nextOr xs x d' :=\n by\n induction' xs with y ys IH\n · cases x_mem\n cases' ys with z zs\n · simp at x_mem x_ne\n contradiction\n by_cases h : x = y\n · rw [h, next_or_self_cons_cons, next_or_self_cons_cons]\n · rw [next_or, next_or, IH] <;> simpa [h] using x_mem\n#align list.next_or_eq_next_or_of_mem_of_ne List.nextOr_eq_nextOr_of_mem_of_ne\n-/\n\n#print List.mem_of_nextOr_ne /-\ntheorem mem_of_nextOr_ne {xs : List α} {x d : α} (h : nextOr xs x d ≠ d) : x ∈ xs :=\n by\n induction' xs with y ys IH\n · simpa using h\n cases' ys with z zs\n · simpa using h\n · by_cases hx : x = y\n · simp [hx]\n · rw [next_or_cons_of_ne _ _ _ _ hx] at h\n simpa [hx] using IH h\n#align list.mem_of_next_or_ne List.mem_of_nextOr_ne\n-/\n\n#print List.nextOr_concat /-\ntheorem nextOr_concat {xs : List α} {x : α} (d : α) (h : x ∉ xs) : nextOr (xs ++ [x]) x d = d :=\n by\n induction' xs with z zs IH\n · simp\n · obtain ⟨hz, hzs⟩ := not_or_distrib.mp (mt (mem_cons_iff _ _ _).mp h)\n rw [cons_append, next_or_cons_of_ne _ _ _ _ hz, IH hzs]\n#align list.next_or_concat List.nextOr_concat\n-/\n\n#print List.nextOr_mem /-\ntheorem nextOr_mem {xs : List α} {x d : α} (hd : d ∈ xs) : nextOr xs x d ∈ xs :=\n by\n revert hd\n suffices ∀ (xs' : List α) (h : ∀ x ∈ xs, x ∈ xs') (hd : d ∈ xs'), next_or xs x d ∈ xs' by\n exact this xs fun _ => id\n intro xs' hxs' hd\n induction' xs with y ys ih\n · exact hd\n cases' ys with z zs\n · exact hd\n rw [next_or]\n split_ifs with h\n · exact hxs' _ (mem_cons_of_mem _ (mem_cons_self _ _))\n · exact ih fun _ h => hxs' _ (mem_cons_of_mem _ h)\n#align list.next_or_mem List.nextOr_mem\n-/\n\n#print List.next /-\n/-- Given an element `x : α` of `l : list α` such that `x ∈ l`, get the next\nelement of `l`. This works from head to tail, (including a check for last element)\nso it will match on first hit, ignoring later duplicates.\n\nFor example:\n * `next [1, 2, 3] 2 _ = 3`\n * `next [1, 2, 3] 3 _ = 1`\n * `next [1, 2, 3, 2, 4] 2 _ = 3`\n * `next [1, 2, 3, 2] 2 _ = 3`\n * `next [1, 1, 2, 3, 2] 1 _ = 1`\n-/\ndef next (l : List α) (x : α) (h : x ∈ l) : α :=\n nextOr l x (l.nthLe 0 (length_pos_of_mem h))\n#align list.next List.next\n-/\n\n#print List.prev /-\n/-- Given an element `x : α` of `l : list α` such that `x ∈ l`, get the previous\nelement of `l`. This works from head to tail, (including a check for last element)\nso it will match on first hit, ignoring later duplicates.\n\n * `prev [1, 2, 3] 2 _ = 1`\n * `prev [1, 2, 3] 1 _ = 3`\n * `prev [1, 2, 3, 2, 4] 2 _ = 1`\n * `prev [1, 2, 3, 4, 2] 2 _ = 1`\n * `prev [1, 1, 2] 1 _ = 2`\n-/\ndef prev : ∀ (l : List α) (x : α) (h : x ∈ l), α\n | [], _, h => by simpa using h\n | [y], _, _ => y\n | y :: z :: xs, x, h =>\n if hx : x = y then getLast (z :: xs) (cons_ne_nil _ _)\n else if x = z then y else prev (z :: xs) x (by simpa [hx] using h)\n#align list.prev List.prev\n-/\n\nvariable (l : List α) (x : α) (h : x ∈ l)\n\n#print List.next_singleton /-\n@[simp]\ntheorem next_singleton (x y : α) (h : x ∈ [y]) : next [y] x h = y :=\n rfl\n#align list.next_singleton List.next_singleton\n-/\n\n#print List.prev_singleton /-\n@[simp]\ntheorem prev_singleton (x y : α) (h : x ∈ [y]) : prev [y] x h = y :=\n rfl\n#align list.prev_singleton List.prev_singleton\n-/\n\n#print List.next_cons_cons_eq' /-\ntheorem next_cons_cons_eq' (y z : α) (h : x ∈ y :: z :: l) (hx : x = y) :\n next (y :: z :: l) x h = z := by rw [next, next_or, if_pos hx]\n#align list.next_cons_cons_eq' List.next_cons_cons_eq'\n-/\n\n#print List.next_cons_cons_eq /-\n@[simp]\ntheorem next_cons_cons_eq (z : α) (h : x ∈ x :: z :: l) : next (x :: z :: l) x h = z :=\n next_cons_cons_eq' l x x z h rfl\n#align list.next_cons_cons_eq List.next_cons_cons_eq\n-/\n\n/- warning: list.next_ne_head_ne_last -> List.next_ne_head_ne_getLast is a dubious translation:\nlean 3 declaration is\n forall {α : Type.{u1}} [_inst_1 : DecidableEq.{succ u1} α] (l : List.{u1} α) (x : α) (y : α) (h : Membership.Mem.{u1, u1} α (List.{u1} α) (List.hasMem.{u1} α) x (List.cons.{u1} α y l)) (hy : Ne.{succ u1} α x y), (Ne.{succ u1} α x (List.getLast.{u1} α (List.cons.{u1} α y l) (List.cons_ne_nil.{u1} α y l))) -> (Eq.{succ u1} α (List.next.{u1} α (fun (a : α) (b : α) => _inst_1 a b) (List.cons.{u1} α y l) x h) (List.next.{u1} α (fun (a : α) (b : α) => _inst_1 a b) l x (Eq.mpr.{0} (Membership.Mem.{u1, u1} α (List.{u1} α) (List.hasMem.{u1} α) x l) (Membership.Mem.{u1, u1} α (List.{u1} α) (List.hasMem.{u1} α) x l) (id_tag Tactic.IdTag.simp (Eq.{1} Prop (Membership.Mem.{u1, u1} α (List.{u1} α) (List.hasMem.{u1} α) x l) (Membership.Mem.{u1, u1} α (List.{u1} α) (List.hasMem.{u1} α) x l)) (rfl.{1} Prop (Membership.Mem.{u1, u1} α (List.{u1} α) (List.hasMem.{u1} α) x l))) (Eq.mp.{0} (Membership.Mem.{u1, u1} α (List.{u1} α) (List.hasMem.{u1} α) x (List.cons.{u1} α y l)) (Membership.Mem.{u1, u1} α (List.{u1} α) (List.hasMem.{u1} α) x l) (Eq.trans.{1} Prop (Membership.Mem.{u1, u1} α (List.{u1} α) (List.hasMem.{u1} α) x (List.cons.{u1} α y l)) (Or False (Membership.Mem.{u1, u1} α (List.{u1} α) (List.hasMem.{u1} α) x l)) (Membership.Mem.{u1, u1} α (List.{u1} α) (List.hasMem.{u1} α) x l) (Eq.trans.{1} Prop (Membership.Mem.{u1, u1} α (List.{u1} α) (List.hasMem.{u1} α) x (List.cons.{u1} α y l)) (Or (Eq.{succ u1} α x y) (Membership.Mem.{u1, u1} α (List.{u1} α) (List.hasMem.{u1} α) x l)) (Or False (Membership.Mem.{u1, u1} α (List.{u1} α) (List.hasMem.{u1} α) x l)) (propext (Membership.Mem.{u1, u1} α (List.{u1} α) (List.hasMem.{u1} α) x (List.cons.{u1} α y l)) (Or (Eq.{succ u1} α x y) (Membership.Mem.{u1, u1} α (List.{u1} α) (List.hasMem.{u1} α) x l)) (List.mem_cons.{u1} α x y l)) ((fun (a : Prop) (a_1 : Prop) (e_1 : Eq.{1} Prop a a_1) (b : Prop) (b_1 : Prop) (e_2 : Eq.{1} Prop b b_1) => congr.{1, 1} Prop Prop (Or a) (Or a_1) b b_1 (congr_arg.{1, 1} Prop (Prop -> Prop) a a_1 Or e_1) e_2) (Eq.{succ u1} α x y) False (propext (Eq.{succ u1} α x y) False (iff_false_intro (Eq.{succ u1} α x y) hy)) (Membership.Mem.{u1, u1} α (List.{u1} α) (List.hasMem.{u1} α) x l) (Membership.Mem.{u1, u1} α (List.{u1} α) (List.hasMem.{u1} α) x l) (rfl.{1} Prop (Membership.Mem.{u1, u1} α (List.{u1} α) (List.hasMem.{u1} α) x l)))) (propext (Or False (Membership.Mem.{u1, u1} α (List.{u1} α) (List.hasMem.{u1} α) x l)) (Membership.Mem.{u1, u1} α (List.{u1} α) (List.hasMem.{u1} α) x l) (false_or_iff (Membership.Mem.{u1, u1} α (List.{u1} α) (List.hasMem.{u1} α) x l)))) h))))\nbut is expected to have type\n forall {α : Type.{u1}} [_inst_1 : DecidableEq.{succ u1} α] (l : List.{u1} α) (x : α), (Membership.mem.{u1, u1} α (List.{u1} α) (List.instMembershipList.{u1} α) x l) -> (forall (h : α) (hy : Membership.mem.{u1, u1} α (List.{u1} α) (List.instMembershipList.{u1} α) x (List.cons.{u1} α h l)) (hx : Ne.{succ u1} α x h), (Ne.{succ u1} α x (List.getLast.{u1} α (List.cons.{u1} α h l) (List.cons_ne_nil.{u1} α h l))) -> (Eq.{succ u1} α (List.next.{u1} α (fun (a : α) (b : α) => _inst_1 a b) (List.cons.{u1} α h l) x hy) (List.next.{u1} α (fun (a : α) (b : α) => _inst_1 a b) l x (Eq.mp.{0} (Membership.mem.{u1, u1} α (List.{u1} α) (List.instMembershipList.{u1} α) x (List.cons.{u1} α h l)) (Membership.mem.{u1, u1} α (List.{u1} α) (List.instMembershipList.{u1} α) x l) (Eq.trans.{1} Prop (Membership.mem.{u1, u1} α (List.{u1} α) (List.instMembershipList.{u1} α) x (List.cons.{u1} α h l)) (Or False (Membership.mem.{u1, u1} α (List.{u1} α) (List.instMembershipList.{u1} α) x l)) (Membership.mem.{u1, u1} α (List.{u1} α) (List.instMembershipList.{u1} α) x l) (Eq.trans.{1} Prop (Membership.mem.{u1, u1} α (List.{u1} α) (List.instMembershipList.{u1} α) x (List.cons.{u1} α h l)) (Or (Eq.{succ u1} α x h) (Membership.mem.{u1, u1} α (List.{u1} α) (List.instMembershipList.{u1} α) x l)) (Or False (Membership.mem.{u1, u1} α (List.{u1} α) (List.instMembershipList.{u1} α) x l)) (Std.Data.List.Lemmas._auxLemma.2.{u1} α x h l) (congrFun.{1, 1} Prop (fun (b : Prop) => Prop) (Or (Eq.{succ u1} α x h)) (Or False) (congrArg.{1, 1} Prop (Prop -> Prop) (Eq.{succ u1} α x h) False Or (eq_false (Eq.{succ u1} α x h) hx)) (Membership.mem.{u1, u1} α (List.{u1} α) (List.instMembershipList.{u1} α) x l))) (false_or (Membership.mem.{u1, u1} α (List.{u1} α) (List.instMembershipList.{u1} α) x l))) hy))))\nCase conversion may be inaccurate. Consider using '#align list.next_ne_head_ne_last List.next_ne_head_ne_getLastₓ'. -/\ntheorem next_ne_head_ne_getLast (y : α) (h : x ∈ y :: l) (hy : x ≠ y)\n (hx : x ≠ getLast (y :: l) (cons_ne_nil _ _)) :\n next (y :: l) x h = next l x (by simpa [hy] using h) :=\n by\n rw [next, next, next_or_cons_of_ne _ _ _ _ hy, next_or_eq_next_or_of_mem_of_ne]\n · rwa [last_cons] at hx\n · simpa [hy] using h\n#align list.next_ne_head_ne_last List.next_ne_head_ne_getLast\n\n#print List.next_cons_concat /-\ntheorem next_cons_concat (y : α) (hy : x ≠ y) (hx : x ∉ l)\n (h : x ∈ y :: l ++ [x] := mem_append_right _ (mem_singleton_self x)) :\n next (y :: l ++ [x]) x h = y := by\n rw [next, next_or_concat]\n · rfl\n · simp [hy, hx]\n#align list.next_cons_concat List.next_cons_concat\n-/\n\n/- warning: list.next_last_cons -> List.next_getLast_cons is a dubious translation:\nlean 3 declaration is\n forall {α : Type.{u1}} [_inst_1 : DecidableEq.{succ u1} α] (l : List.{u1} α) (x : α) (y : α) (h : Membership.Mem.{u1, u1} α (List.{u1} α) (List.hasMem.{u1} α) x (List.cons.{u1} α y l)), (Ne.{succ u1} α x y) -> (Eq.{succ u1} α x (List.getLast.{u1} α (List.cons.{u1} α y l) (List.cons_ne_nil.{u1} α y l))) -> (List.Nodup.{u1} α l) -> (Eq.{succ u1} α (List.next.{u1} α (fun (a : α) (b : α) => _inst_1 a b) (List.cons.{u1} α y l) x h) y)\nbut is expected to have type\n forall {α : Type.{u1}} [_inst_1 : DecidableEq.{succ u1} α] (l : List.{u1} α) (x : α), (Membership.mem.{u1, u1} α (List.{u1} α) (List.instMembershipList.{u1} α) x l) -> (forall (h : α) (hy : Membership.mem.{u1, u1} α (List.{u1} α) (List.instMembershipList.{u1} α) x (List.cons.{u1} α h l)), (Ne.{succ u1} α x h) -> (Eq.{succ u1} α x (List.getLast.{u1} α (List.cons.{u1} α h l) (List.cons_ne_nil.{u1} α h l))) -> (List.Nodup.{u1} α l) -> (Eq.{succ u1} α (List.next.{u1} α (fun (a : α) (b : α) => _inst_1 a b) (List.cons.{u1} α h l) x hy) h))\nCase conversion may be inaccurate. Consider using '#align list.next_last_cons List.next_getLast_consₓ'. -/\ntheorem next_getLast_cons (y : α) (h : x ∈ y :: l) (hy : x ≠ y)\n (hx : x = getLast (y :: l) (cons_ne_nil _ _)) (hl : Nodup l) : next (y :: l) x h = y :=\n by\n rw [next, nth_le, ← init_append_last (cons_ne_nil y l), hx, next_or_concat]\n subst hx\n intro H\n obtain ⟨_ | k, hk, hk'⟩ := nth_le_of_mem H\n · simpa [init_eq_take, nth_le_take', hy.symm] using hk'\n suffices k.succ = l.length by simpa [this] using hk\n cases' l with hd tl\n · simpa using hk\n · rw [nodup_iff_nth_le_inj] at hl\n rw [length, Nat.succ_inj']\n apply hl\n simpa [init_eq_take, nth_le_take', last_eq_nth_le] using hk'\n#align list.next_last_cons List.next_getLast_cons\n\n#print List.prev_getLast_cons' /-\ntheorem prev_getLast_cons' (y : α) (h : x ∈ y :: l) (hx : x = y) :\n prev (y :: l) x h = getLast (y :: l) (cons_ne_nil _ _) := by cases l <;> simp [prev, hx]\n#align list.prev_last_cons' List.prev_getLast_cons'\n-/\n\n#print List.prev_getLast_cons /-\n@[simp]\ntheorem prev_getLast_cons (h : x ∈ x :: l) :\n prev (x :: l) x h = getLast (x :: l) (cons_ne_nil _ _) :=\n prev_getLast_cons' l x x h rfl\n#align list.prev_last_cons List.prev_getLast_cons\n-/\n\n#print List.prev_cons_cons_eq' /-\ntheorem prev_cons_cons_eq' (y z : α) (h : x ∈ y :: z :: l) (hx : x = y) :\n prev (y :: z :: l) x h = getLast (z :: l) (cons_ne_nil _ _) := by rw [prev, dif_pos hx]\n#align list.prev_cons_cons_eq' List.prev_cons_cons_eq'\n-/\n\n#print List.prev_cons_cons_eq /-\n@[simp]\ntheorem prev_cons_cons_eq (z : α) (h : x ∈ x :: z :: l) :\n prev (x :: z :: l) x h = getLast (z :: l) (cons_ne_nil _ _) :=\n prev_cons_cons_eq' l x x z h rfl\n#align list.prev_cons_cons_eq List.prev_cons_cons_eq\n-/\n\n#print List.prev_cons_cons_of_ne' /-\ntheorem prev_cons_cons_of_ne' (y z : α) (h : x ∈ y :: z :: l) (hy : x ≠ y) (hz : x = z) :\n prev (y :: z :: l) x h = y := by\n cases l\n · simp [prev, hy, hz]\n · rw [prev, dif_neg hy, if_pos hz]\n#align list.prev_cons_cons_of_ne' List.prev_cons_cons_of_ne'\n-/\n\n#print List.prev_cons_cons_of_ne /-\ntheorem prev_cons_cons_of_ne (y : α) (h : x ∈ y :: x :: l) (hy : x ≠ y) :\n prev (y :: x :: l) x h = y :=\n prev_cons_cons_of_ne' _ _ _ _ _ hy rfl\n#align list.prev_cons_cons_of_ne List.prev_cons_cons_of_ne\n-/\n\n#print List.prev_ne_cons_cons /-\ntheorem prev_ne_cons_cons (y z : α) (h : x ∈ y :: z :: l) (hy : x ≠ y) (hz : x ≠ z) :\n prev (y :: z :: l) x h = prev (z :: l) x (by simpa [hy] using h) :=\n by\n cases l\n · simpa [hy, hz] using h\n · rw [prev, dif_neg hy, if_neg hz]\n#align list.prev_ne_cons_cons List.prev_ne_cons_cons\n-/\n\ninclude h\n\n#print List.next_mem /-\ntheorem next_mem : l.next x h ∈ l :=\n nextOr_mem (nthLe_mem _ _ _)\n#align list.next_mem List.next_mem\n-/\n\n#print List.prev_mem /-\ntheorem prev_mem : l.prev x h ∈ l := by\n cases' l with hd tl\n · simpa using h\n induction' tl with hd' tl hl generalizing hd\n · simp\n · by_cases hx : x = hd\n · simp only [hx, prev_cons_cons_eq]\n exact mem_cons_of_mem _ (last_mem _)\n · rw [prev, dif_neg hx]\n split_ifs with hm\n · exact mem_cons_self _ _\n · exact mem_cons_of_mem _ (hl _ _)\n#align list.prev_mem List.prev_mem\n-/\n\n#print List.next_nthLe /-\ntheorem next_nthLe (l : List α) (h : Nodup l) (n : ℕ) (hn : n < l.length) :\n next l (l.nthLe n hn) (nthLe_mem _ _ _) =\n l.nthLe ((n + 1) % l.length) (Nat.mod_lt _ (n.zero_le.trans_lt hn)) :=\n by\n cases' l with x l\n · simpa using hn\n induction' l with y l hl generalizing x n\n · simp\n · cases n\n · simp\n · have hn' : n.succ ≤ l.length.succ :=\n by\n refine' Nat.succ_le_of_lt _\n simpa [Nat.succ_lt_succ_iff] using hn\n have hx' : (x :: y :: l).nthLe n.succ hn ≠ x :=\n by\n intro H\n suffices n.succ = 0 by simpa\n rw [nodup_iff_nth_le_inj] at h\n refine' h _ _ hn Nat.succ_pos' _\n simpa using H\n rcases hn'.eq_or_lt with (hn'' | hn'')\n · rw [next_last_cons]\n · simp [hn'']\n · exact hx'\n · simp [last_eq_nth_le, hn'']\n · exact h.of_cons\n · have : n < l.length := by simpa [Nat.succ_lt_succ_iff] using hn''\n rw [next_ne_head_ne_last _ _ _ _ hx']\n ·\n simp [Nat.mod_eq_of_lt (Nat.succ_lt_succ (Nat.succ_lt_succ this)), hl _ _ h.of_cons,\n Nat.mod_eq_of_lt (Nat.succ_lt_succ this)]\n · rw [last_eq_nth_le]\n intro H\n suffices n.succ = l.length.succ by exact absurd hn'' this.ge.not_lt\n rw [nodup_iff_nth_le_inj] at h\n refine' h _ _ hn _ _\n · simp\n · simpa using H\n#align list.next_nth_le List.next_nthLe\n-/\n\n#print List.prev_nthLe /-\ntheorem prev_nthLe (l : List α) (h : Nodup l) (n : ℕ) (hn : n < l.length) :\n prev l (l.nthLe n hn) (nthLe_mem _ _ _) =\n l.nthLe ((n + (l.length - 1)) % l.length) (Nat.mod_lt _ (n.zero_le.trans_lt hn)) :=\n by\n cases' l with x l\n · simpa using hn\n induction' l with y l hl generalizing n x\n · simp\n · rcases n with (_ | _ | n)\n · simpa [last_eq_nth_le, Nat.mod_eq_of_lt (Nat.succ_lt_succ l.length.lt_succ_self)]\n · simp only [mem_cons_iff, nodup_cons] at h\n push_neg at h\n simp [add_comm, prev_cons_cons_of_ne, h.left.left.symm]\n · rw [prev_ne_cons_cons]\n · convert hl _ _ h.of_cons _ using 1\n have : ∀ k hk, (y :: l).nthLe k hk = (x :: y :: l).nthLe (k + 1) (Nat.succ_lt_succ hk) :=\n by\n intros\n simpa\n rw [this]\n congr\n simp only [Nat.add_succ_sub_one, add_zero, length]\n simp only [length, Nat.succ_lt_succ_iff] at hn\n set k := l.length\n rw [Nat.succ_add, ← Nat.add_succ, Nat.add_mod_right, Nat.succ_add, ← Nat.add_succ _ k,\n Nat.add_mod_right, Nat.mod_eq_of_lt, Nat.mod_eq_of_lt]\n · exact Nat.lt_succ_of_lt hn\n · exact Nat.succ_lt_succ (Nat.lt_succ_of_lt hn)\n · intro H\n suffices n.succ.succ = 0 by simpa\n rw [nodup_iff_nth_le_inj] at h\n refine' h _ _ hn Nat.succ_pos' _\n simpa using H\n · intro H\n suffices n.succ.succ = 1 by simpa\n rw [nodup_iff_nth_le_inj] at h\n refine' h _ _ hn (Nat.succ_lt_succ Nat.succ_pos') _\n simpa using H\n#align list.prev_nth_le List.prev_nthLe\n-/\n\n#print List.pmap_next_eq_rotate_one /-\ntheorem pmap_next_eq_rotate_one (h : Nodup l) : (l.pmap l.next fun _ h => h) = l.rotate 1 :=\n by\n apply List.ext_nthLe\n · simp\n · intros\n rw [nth_le_pmap, nth_le_rotate, next_nth_le _ h]\n#align list.pmap_next_eq_rotate_one List.pmap_next_eq_rotate_one\n-/\n\n#print List.pmap_prev_eq_rotate_length_sub_one /-\ntheorem pmap_prev_eq_rotate_length_sub_one (h : Nodup l) :\n (l.pmap l.prev fun _ h => h) = l.rotate (l.length - 1) :=\n by\n apply List.ext_nthLe\n · simp\n · intro n hn hn'\n rw [nth_le_rotate, nth_le_pmap, prev_nth_le _ h]\n#align list.pmap_prev_eq_rotate_length_sub_one List.pmap_prev_eq_rotate_length_sub_one\n-/\n\n#print List.prev_next /-\ntheorem prev_next (l : List α) (h : Nodup l) (x : α) (hx : x ∈ l) :\n prev l (next l x hx) (next_mem _ _ _) = x :=\n by\n obtain ⟨n, hn, rfl⟩ := nth_le_of_mem hx\n simp only [next_nth_le, prev_nth_le, h, Nat.mod_add_mod]\n cases' l with hd tl\n · simp\n · have : n < 1 + tl.length := by simpa [add_comm] using hn\n simp [add_left_comm, add_comm, add_assoc, Nat.mod_eq_of_lt this]\n#align list.prev_next List.prev_next\n-/\n\n#print List.next_prev /-\ntheorem next_prev (l : List α) (h : Nodup l) (x : α) (hx : x ∈ l) :\n next l (prev l x hx) (prev_mem _ _ _) = x :=\n by\n obtain ⟨n, hn, rfl⟩ := nth_le_of_mem hx\n simp only [next_nth_le, prev_nth_le, h, Nat.mod_add_mod]\n cases' l with hd tl\n · simp\n · have : n < 1 + tl.length := by simpa [add_comm] using hn\n simp [add_left_comm, add_comm, add_assoc, Nat.mod_eq_of_lt this]\n#align list.next_prev List.next_prev\n-/\n\n#print List.prev_reverse_eq_next /-\ntheorem prev_reverse_eq_next (l : List α) (h : Nodup l) (x : α) (hx : x ∈ l) :\n prev l.reverse x (mem_reverse'.mpr hx) = next l x hx :=\n by\n obtain ⟨k, hk, rfl⟩ := nth_le_of_mem hx\n have lpos : 0 < l.length := k.zero_le.trans_lt hk\n have key : l.length - 1 - k < l.length :=\n (Nat.sub_le _ _).trans_lt (tsub_lt_self lpos Nat.succ_pos')\n rw [← nth_le_pmap l.next (fun _ h => h) (by simpa using hk)]\n simp_rw [← nth_le_reverse l k (key.trans_le (by simp)), pmap_next_eq_rotate_one _ h]\n rw [← nth_le_pmap l.reverse.prev fun _ h => h]\n · simp_rw [pmap_prev_eq_rotate_length_sub_one _ (nodup_reverse.mpr h), rotate_reverse,\n length_reverse, Nat.mod_eq_of_lt (tsub_lt_self lpos Nat.succ_pos'),\n tsub_tsub_cancel_of_le (Nat.succ_le_of_lt lpos)]\n rw [← nth_le_reverse]\n · simp [tsub_tsub_cancel_of_le (Nat.le_pred_of_lt hk)]\n · simpa using (Nat.sub_le _ _).trans_lt (tsub_lt_self lpos Nat.succ_pos')\n · simpa using (Nat.sub_le _ _).trans_lt (tsub_lt_self lpos Nat.succ_pos')\n#align list.prev_reverse_eq_next List.prev_reverse_eq_next\n-/\n\n#print List.next_reverse_eq_prev /-\ntheorem next_reverse_eq_prev (l : List α) (h : Nodup l) (x : α) (hx : x ∈ l) :\n next l.reverse x (mem_reverse'.mpr hx) = prev l x hx :=\n by\n convert(prev_reverse_eq_next l.reverse (nodup_reverse.mpr h) x (mem_reverse.mpr hx)).symm\n exact (reverse_reverse l).symm\n#align list.next_reverse_eq_prev List.next_reverse_eq_prev\n-/\n\n#print List.isRotated_next_eq /-\ntheorem isRotated_next_eq {l l' : List α} (h : l ~r l') (hn : Nodup l) {x : α} (hx : x ∈ l) :\n l.next x hx = l'.next x (h.mem_iff.mp hx) :=\n by\n obtain ⟨k, hk, rfl⟩ := nth_le_of_mem hx\n obtain ⟨n, rfl⟩ := id h\n rw [next_nth_le _ hn]\n simp_rw [← nth_le_rotate' _ n k]\n rw [next_nth_le _ (h.nodup_iff.mp hn), ← nth_le_rotate' _ n]\n simp [add_assoc]\n#align list.is_rotated_next_eq List.isRotated_next_eq\n-/\n\n#print List.isRotated_prev_eq /-\ntheorem isRotated_prev_eq {l l' : List α} (h : l ~r l') (hn : Nodup l) {x : α} (hx : x ∈ l) :\n l.prev x hx = l'.prev x (h.mem_iff.mp hx) :=\n by\n rw [← next_reverse_eq_prev _ hn, ← next_reverse_eq_prev _ (h.nodup_iff.mp hn)]\n exact is_rotated_next_eq h.reverse (nodup_reverse.mpr hn) _\n#align list.is_rotated_prev_eq List.isRotated_prev_eq\n-/\n\nend List\n\nopen List\n\n#print Cycle /-\n/-- `cycle α` is the quotient of `list α` by cyclic permutation.\nDuplicates are allowed.\n-/\ndef Cycle (α : Type _) : Type _ :=\n Quotient (IsRotated.setoid α)\n#align cycle Cycle\n-/\n\nnamespace Cycle\n\nvariable {α : Type _}\n\ninstance : Coe (List α) (Cycle α) :=\n ⟨Quot.mk _⟩\n\n#print Cycle.coe_eq_coe /-\n@[simp]\ntheorem coe_eq_coe {l₁ l₂ : List α} : (l₁ : Cycle α) = l₂ ↔ l₁ ~r l₂ :=\n @Quotient.eq' _ (IsRotated.setoid _) _ _\n#align cycle.coe_eq_coe Cycle.coe_eq_coe\n-/\n\n#print Cycle.mk_eq_coe /-\n@[simp]\ntheorem mk_eq_coe (l : List α) : Quot.mk _ l = (l : Cycle α) :=\n rfl\n#align cycle.mk_eq_coe Cycle.mk_eq_coe\n-/\n\n#print Cycle.mk''_eq_coe /-\n@[simp]\ntheorem mk''_eq_coe (l : List α) : Quotient.mk'' l = (l : Cycle α) :=\n rfl\n#align cycle.mk'_eq_coe Cycle.mk''_eq_coe\n-/\n\n#print Cycle.coe_cons_eq_coe_append /-\ntheorem coe_cons_eq_coe_append (l : List α) (a : α) : (↑(a :: l) : Cycle α) = ↑(l ++ [a]) :=\n Quot.sound ⟨1, by rw [rotate_cons_succ, rotate_zero]⟩\n#align cycle.coe_cons_eq_coe_append Cycle.coe_cons_eq_coe_append\n-/\n\n#print Cycle.nil /-\n/-- The unique empty cycle. -/\ndef nil : Cycle α :=\n ([] : List α)\n#align cycle.nil Cycle.nil\n-/\n\n#print Cycle.coe_nil /-\n@[simp]\ntheorem coe_nil : ↑([] : List α) = @nil α :=\n rfl\n#align cycle.coe_nil Cycle.coe_nil\n-/\n\n#print Cycle.coe_eq_nil /-\n@[simp]\ntheorem coe_eq_nil (l : List α) : (l : Cycle α) = nil ↔ l = [] :=\n coe_eq_coe.trans isRotated_nil_iff\n#align cycle.coe_eq_nil Cycle.coe_eq_nil\n-/\n\n/-- For consistency with `list.has_emptyc`. -/\ninstance : EmptyCollection (Cycle α) :=\n ⟨nil⟩\n\n#print Cycle.empty_eq /-\n@[simp]\ntheorem empty_eq : ∅ = @nil α :=\n rfl\n#align cycle.empty_eq Cycle.empty_eq\n-/\n\ninstance : Inhabited (Cycle α) :=\n ⟨nil⟩\n\n#print Cycle.induction_on /-\n/-- An induction principle for `cycle`. Use as `induction s using cycle.induction_on`. -/\n@[elab_as_elim]\ntheorem induction_on {C : Cycle α → Prop} (s : Cycle α) (H0 : C nil)\n (HI : ∀ (a) (l : List α), C ↑l → C ↑(a :: l)) : C s :=\n Quotient.inductionOn' s fun l => by\n apply List.recOn l <;> simp\n assumption'\n#align cycle.induction_on Cycle.induction_on\n-/\n\n#print Cycle.Mem /-\n/-- For `x : α`, `s : cycle α`, `x ∈ s` indicates that `x` occurs at least once in `s`. -/\ndef Mem (a : α) (s : Cycle α) : Prop :=\n Quot.liftOn s (fun l => a ∈ l) fun l₁ l₂ e => propext <| e.mem_iff\n#align cycle.mem Cycle.Mem\n-/\n\ninstance : Membership α (Cycle α) :=\n ⟨Mem⟩\n\n#print Cycle.mem_coe_iff /-\n@[simp]\ntheorem mem_coe_iff {a : α} {l : List α} : a ∈ (l : Cycle α) ↔ a ∈ l :=\n Iff.rfl\n#align cycle.mem_coe_iff Cycle.mem_coe_iff\n-/\n\n#print Cycle.not_mem_nil /-\n@[simp]\ntheorem not_mem_nil : ∀ a, a ∉ @nil α :=\n not_mem_nil\n#align cycle.not_mem_nil Cycle.not_mem_nil\n-/\n\ninstance [DecidableEq α] : DecidableEq (Cycle α) := fun s₁ s₂ =>\n Quotient.recOnSubsingleton₂' s₁ s₂ fun l₁ l₂ => decidable_of_iff' _ Quotient.eq''\n\ninstance [DecidableEq α] (x : α) (s : Cycle α) : Decidable (x ∈ s) :=\n Quotient.recOnSubsingleton' s fun l => List.decidableMem x l\n\n#print Cycle.reverse /-\n/-- Reverse a `s : cycle α` by reversing the underlying `list`. -/\ndef reverse (s : Cycle α) : Cycle α :=\n Quot.map reverse (fun l₁ l₂ => IsRotated.reverse) s\n#align cycle.reverse Cycle.reverse\n-/\n\n#print Cycle.reverse_coe /-\n@[simp]\ntheorem reverse_coe (l : List α) : (l : Cycle α).reverse = l.reverse :=\n rfl\n#align cycle.reverse_coe Cycle.reverse_coe\n-/\n\n#print Cycle.mem_reverse_iff /-\n@[simp]\ntheorem mem_reverse_iff {a : α} {s : Cycle α} : a ∈ s.reverse ↔ a ∈ s :=\n Quot.inductionOn s fun _ => mem_reverse'\n#align cycle.mem_reverse_iff Cycle.mem_reverse_iff\n-/\n\n#print Cycle.reverse_reverse /-\n@[simp]\ntheorem reverse_reverse (s : Cycle α) : s.reverse.reverse = s :=\n Quot.inductionOn s fun _ => by simp\n#align cycle.reverse_reverse Cycle.reverse_reverse\n-/\n\n#print Cycle.reverse_nil /-\n@[simp]\ntheorem reverse_nil : nil.reverse = @nil α :=\n rfl\n#align cycle.reverse_nil Cycle.reverse_nil\n-/\n\n#print Cycle.length /-\n/-- The length of the `s : cycle α`, which is the number of elements, counting duplicates. -/\ndef length (s : Cycle α) : ℕ :=\n Quot.liftOn s length fun l₁ l₂ e => e.Perm.length_eq\n#align cycle.length Cycle.length\n-/\n\n#print Cycle.length_coe /-\n@[simp]\ntheorem length_coe (l : List α) : length (l : Cycle α) = l.length :=\n rfl\n#align cycle.length_coe Cycle.length_coe\n-/\n\n#print Cycle.length_nil /-\n@[simp]\ntheorem length_nil : length (@nil α) = 0 :=\n rfl\n#align cycle.length_nil Cycle.length_nil\n-/\n\n#print Cycle.length_reverse /-\n@[simp]\ntheorem length_reverse (s : Cycle α) : s.reverse.length = s.length :=\n Quot.inductionOn s length_reverse\n#align cycle.length_reverse Cycle.length_reverse\n-/\n\n#print Cycle.Subsingleton /-\n/-- A `s : cycle α` that is at most one element. -/\ndef Subsingleton (s : Cycle α) : Prop :=\n s.length ≤ 1\n#align cycle.subsingleton Cycle.Subsingleton\n-/\n\n#print Cycle.subsingleton_nil /-\ntheorem subsingleton_nil : Subsingleton (@nil α) :=\n zero_le_one\n#align cycle.subsingleton_nil Cycle.subsingleton_nil\n-/\n\n#print Cycle.length_subsingleton_iff /-\ntheorem length_subsingleton_iff {s : Cycle α} : Subsingleton s ↔ length s ≤ 1 :=\n Iff.rfl\n#align cycle.length_subsingleton_iff Cycle.length_subsingleton_iff\n-/\n\n#print Cycle.subsingleton_reverse_iff /-\n@[simp]\ntheorem subsingleton_reverse_iff {s : Cycle α} : s.reverse.Subsingleton ↔ s.Subsingleton := by\n simp [length_subsingleton_iff]\n#align cycle.subsingleton_reverse_iff Cycle.subsingleton_reverse_iff\n-/\n\n#print Cycle.Subsingleton.congr /-\ntheorem Subsingleton.congr {s : Cycle α} (h : Subsingleton s) :\n ∀ ⦃x⦄ (hx : x ∈ s) ⦃y⦄ (hy : y ∈ s), x = y :=\n by\n induction' s using Quot.inductionOn with l\n simp only [length_subsingleton_iff, length_coe, mk_eq_coe, le_iff_lt_or_eq, Nat.lt_add_one_iff,\n length_eq_zero, length_eq_one, Nat.not_lt_zero, false_or_iff] at h\n rcases h with (rfl | ⟨z, rfl⟩) <;> simp\n#align cycle.subsingleton.congr Cycle.Subsingleton.congr\n-/\n\n#print Cycle.Nontrivial /-\n/-- A `s : cycle α` that is made up of at least two unique elements. -/\ndef Nontrivial (s : Cycle α) : Prop :=\n ∃ (x y : α)(h : x ≠ y), x ∈ s ∧ y ∈ s\n#align cycle.nontrivial Cycle.Nontrivial\n-/\n\n#print Cycle.nontrivial_coe_nodup_iff /-\n@[simp]\ntheorem nontrivial_coe_nodup_iff {l : List α} (hl : l.Nodup) :\n Nontrivial (l : Cycle α) ↔ 2 ≤ l.length :=\n by\n rw [Nontrivial]\n rcases l with (_ | ⟨hd, _ | ⟨hd', tl⟩⟩)\n · simp\n · simp\n · simp only [mem_cons_iff, exists_prop, mem_coe_iff, List.length, Ne.def, Nat.succ_le_succ_iff,\n zero_le, iff_true_iff]\n refine' ⟨hd, hd', _, by simp⟩\n simp only [not_or, mem_cons_iff, nodup_cons] at hl\n exact hl.left.left\n#align cycle.nontrivial_coe_nodup_iff Cycle.nontrivial_coe_nodup_iff\n-/\n\n#print Cycle.nontrivial_reverse_iff /-\n@[simp]\ntheorem nontrivial_reverse_iff {s : Cycle α} : s.reverse.Nontrivial ↔ s.Nontrivial := by\n simp [Nontrivial]\n#align cycle.nontrivial_reverse_iff Cycle.nontrivial_reverse_iff\n-/\n\n#print Cycle.length_nontrivial /-\ntheorem length_nontrivial {s : Cycle α} (h : Nontrivial s) : 2 ≤ length s :=\n by\n obtain ⟨x, y, hxy, hx, hy⟩ := h\n induction' s using Quot.inductionOn with l\n rcases l with (_ | ⟨hd, _ | ⟨hd', tl⟩⟩)\n · simpa using hx\n · simp only [mem_coe_iff, mk_eq_coe, mem_singleton] at hx hy\n simpa [hx, hy] using hxy\n · simp [bit0]\n#align cycle.length_nontrivial Cycle.length_nontrivial\n-/\n\n#print Cycle.Nodup /-\n/-- The `s : cycle α` contains no duplicates. -/\ndef Nodup (s : Cycle α) : Prop :=\n Quot.liftOn s Nodup fun l₁ l₂ e => propext <| e.nodup_iff\n#align cycle.nodup Cycle.Nodup\n-/\n\n#print Cycle.nodup_nil /-\n@[simp]\ntheorem nodup_nil : Nodup (@nil α) :=\n nodup_nil\n#align cycle.nodup_nil Cycle.nodup_nil\n-/\n\n#print Cycle.nodup_coe_iff /-\n@[simp]\ntheorem nodup_coe_iff {l : List α} : Nodup (l : Cycle α) ↔ l.Nodup :=\n Iff.rfl\n#align cycle.nodup_coe_iff Cycle.nodup_coe_iff\n-/\n\n#print Cycle.nodup_reverse_iff /-\n@[simp]\ntheorem nodup_reverse_iff {s : Cycle α} : s.reverse.Nodup ↔ s.Nodup :=\n Quot.inductionOn s fun _ => nodup_reverse\n#align cycle.nodup_reverse_iff Cycle.nodup_reverse_iff\n-/\n\n#print Cycle.Subsingleton.nodup /-\ntheorem Subsingleton.nodup {s : Cycle α} (h : Subsingleton s) : Nodup s :=\n by\n induction' s using Quot.inductionOn with l\n cases' l with hd tl\n · simp\n · have : tl = [] := by simpa [Subsingleton, length_eq_zero] using h\n simp [this]\n#align cycle.subsingleton.nodup Cycle.Subsingleton.nodup\n-/\n\n#print Cycle.Nodup.nontrivial_iff /-\ntheorem Nodup.nontrivial_iff {s : Cycle α} (h : Nodup s) : Nontrivial s ↔ ¬Subsingleton s :=\n by\n rw [length_subsingleton_iff]\n induction s using Quotient.inductionOn'\n simp only [mk'_eq_coe, nodup_coe_iff] at h\n simp [h, Nat.succ_le_iff]\n#align cycle.nodup.nontrivial_iff Cycle.Nodup.nontrivial_iff\n-/\n\n#print Cycle.toMultiset /-\n/-- The `s : cycle α` as a `multiset α`.\n-/\ndef toMultiset (s : Cycle α) : Multiset α :=\n Quotient.liftOn' s coe fun l₁ l₂ h => Multiset.coe_eq_coe.mpr h.Perm\n#align cycle.to_multiset Cycle.toMultiset\n-/\n\n#print Cycle.coe_toMultiset /-\n@[simp]\ntheorem coe_toMultiset (l : List α) : (l : Cycle α).toMultiset = l :=\n rfl\n#align cycle.coe_to_multiset Cycle.coe_toMultiset\n-/\n\n#print Cycle.nil_toMultiset /-\n@[simp]\ntheorem nil_toMultiset : nil.toMultiset = (0 : Multiset α) :=\n rfl\n#align cycle.nil_to_multiset Cycle.nil_toMultiset\n-/\n\n/- warning: cycle.card_to_multiset -> Cycle.card_toMultiset is a dubious translation:\nlean 3 declaration is\n forall {α : Type.{u1}} (s : Cycle.{u1} α), Eq.{1} Nat (coeFn.{succ u1, succ u1} (AddMonoidHom.{u1, 0} (Multiset.{u1} α) Nat (AddMonoid.toAddZeroClass.{u1} (Multiset.{u1} α) (AddRightCancelMonoid.toAddMonoid.{u1} (Multiset.{u1} α) (AddCancelMonoid.toAddRightCancelMonoid.{u1} (Multiset.{u1} α) (AddCancelCommMonoid.toAddCancelMonoid.{u1} (Multiset.{u1} α) (OrderedCancelAddCommMonoid.toCancelAddCommMonoid.{u1} (Multiset.{u1} α) (Multiset.orderedCancelAddCommMonoid.{u1} α)))))) (AddMonoid.toAddZeroClass.{0} Nat Nat.addMonoid)) (fun (_x : AddMonoidHom.{u1, 0} (Multiset.{u1} α) Nat (AddMonoid.toAddZeroClass.{u1} (Multiset.{u1} α) (AddRightCancelMonoid.toAddMonoid.{u1} (Multiset.{u1} α) (AddCancelMonoid.toAddRightCancelMonoid.{u1} (Multiset.{u1} α) (AddCancelCommMonoid.toAddCancelMonoid.{u1} (Multiset.{u1} α) (OrderedCancelAddCommMonoid.toCancelAddCommMonoid.{u1} (Multiset.{u1} α) (Multiset.orderedCancelAddCommMonoid.{u1} α)))))) (AddMonoid.toAddZeroClass.{0} Nat Nat.addMonoid)) => (Multiset.{u1} α) -> Nat) (AddMonoidHom.hasCoeToFun.{u1, 0} (Multiset.{u1} α) Nat (AddMonoid.toAddZeroClass.{u1} (Multiset.{u1} α) (AddRightCancelMonoid.toAddMonoid.{u1} (Multiset.{u1} α) (AddCancelMonoid.toAddRightCancelMonoid.{u1} (Multiset.{u1} α) (AddCancelCommMonoid.toAddCancelMonoid.{u1} (Multiset.{u1} α) (OrderedCancelAddCommMonoid.toCancelAddCommMonoid.{u1} (Multiset.{u1} α) (Multiset.orderedCancelAddCommMonoid.{u1} α)))))) (AddMonoid.toAddZeroClass.{0} Nat Nat.addMonoid)) (Multiset.card.{u1} α) (Cycle.toMultiset.{u1} α s)) (Cycle.length.{u1} α s)\nbut is expected to have type\n forall {α : Type.{u1}} (s : Cycle.{u1} α), Eq.{1} ((fun (x._@.Mathlib.Algebra.Hom.Group._hyg.403 : Multiset.{u1} α) => Nat) (Cycle.toMultiset.{u1} α s)) (FunLike.coe.{succ u1, succ u1, 1} (AddMonoidHom.{u1, 0} (Multiset.{u1} α) Nat (AddMonoid.toAddZeroClass.{u1} (Multiset.{u1} α) (AddRightCancelMonoid.toAddMonoid.{u1} (Multiset.{u1} α) (AddCancelMonoid.toAddRightCancelMonoid.{u1} (Multiset.{u1} α) (AddCancelCommMonoid.toAddCancelMonoid.{u1} (Multiset.{u1} α) (OrderedCancelAddCommMonoid.toCancelAddCommMonoid.{u1} (Multiset.{u1} α) (Multiset.instOrderedCancelAddCommMonoidMultiset.{u1} α)))))) (AddMonoid.toAddZeroClass.{0} Nat Nat.addMonoid)) (Multiset.{u1} α) (fun (_x : Multiset.{u1} α) => (fun (x._@.Mathlib.Algebra.Hom.Group._hyg.403 : Multiset.{u1} α) => Nat) _x) (AddHomClass.toFunLike.{u1, u1, 0} (AddMonoidHom.{u1, 0} (Multiset.{u1} α) Nat (AddMonoid.toAddZeroClass.{u1} (Multiset.{u1} α) (AddRightCancelMonoid.toAddMonoid.{u1} (Multiset.{u1} α) (AddCancelMonoid.toAddRightCancelMonoid.{u1} (Multiset.{u1} α) (AddCancelCommMonoid.toAddCancelMonoid.{u1} (Multiset.{u1} α) (OrderedCancelAddCommMonoid.toCancelAddCommMonoid.{u1} (Multiset.{u1} α) (Multiset.instOrderedCancelAddCommMonoidMultiset.{u1} α)))))) (AddMonoid.toAddZeroClass.{0} Nat Nat.addMonoid)) (Multiset.{u1} α) Nat (AddZeroClass.toAdd.{u1} (Multiset.{u1} α) (AddMonoid.toAddZeroClass.{u1} (Multiset.{u1} α) (AddRightCancelMonoid.toAddMonoid.{u1} (Multiset.{u1} α) (AddCancelMonoid.toAddRightCancelMonoid.{u1} (Multiset.{u1} α) (AddCancelCommMonoid.toAddCancelMonoid.{u1} (Multiset.{u1} α) (OrderedCancelAddCommMonoid.toCancelAddCommMonoid.{u1} (Multiset.{u1} α) (Multiset.instOrderedCancelAddCommMonoidMultiset.{u1} α))))))) (AddZeroClass.toAdd.{0} Nat (AddMonoid.toAddZeroClass.{0} Nat Nat.addMonoid)) (AddMonoidHomClass.toAddHomClass.{u1, u1, 0} (AddMonoidHom.{u1, 0} (Multiset.{u1} α) Nat (AddMonoid.toAddZeroClass.{u1} (Multiset.{u1} α) (AddRightCancelMonoid.toAddMonoid.{u1} (Multiset.{u1} α) (AddCancelMonoid.toAddRightCancelMonoid.{u1} (Multiset.{u1} α) (AddCancelCommMonoid.toAddCancelMonoid.{u1} (Multiset.{u1} α) (OrderedCancelAddCommMonoid.toCancelAddCommMonoid.{u1} (Multiset.{u1} α) (Multiset.instOrderedCancelAddCommMonoidMultiset.{u1} α)))))) (AddMonoid.toAddZeroClass.{0} Nat Nat.addMonoid)) (Multiset.{u1} α) Nat (AddMonoid.toAddZeroClass.{u1} (Multiset.{u1} α) (AddRightCancelMonoid.toAddMonoid.{u1} (Multiset.{u1} α) (AddCancelMonoid.toAddRightCancelMonoid.{u1} (Multiset.{u1} α) (AddCancelCommMonoid.toAddCancelMonoid.{u1} (Multiset.{u1} α) (OrderedCancelAddCommMonoid.toCancelAddCommMonoid.{u1} (Multiset.{u1} α) (Multiset.instOrderedCancelAddCommMonoidMultiset.{u1} α)))))) (AddMonoid.toAddZeroClass.{0} Nat Nat.addMonoid) (AddMonoidHom.addMonoidHomClass.{u1, 0} (Multiset.{u1} α) Nat (AddMonoid.toAddZeroClass.{u1} (Multiset.{u1} α) (AddRightCancelMonoid.toAddMonoid.{u1} (Multiset.{u1} α) (AddCancelMonoid.toAddRightCancelMonoid.{u1} (Multiset.{u1} α) (AddCancelCommMonoid.toAddCancelMonoid.{u1} (Multiset.{u1} α) (OrderedCancelAddCommMonoid.toCancelAddCommMonoid.{u1} (Multiset.{u1} α) (Multiset.instOrderedCancelAddCommMonoidMultiset.{u1} α)))))) (AddMonoid.toAddZeroClass.{0} Nat Nat.addMonoid)))) (Multiset.card.{u1} α) (Cycle.toMultiset.{u1} α s)) (Cycle.length.{u1} α s)\nCase conversion may be inaccurate. Consider using '#align cycle.card_to_multiset Cycle.card_toMultisetₓ'. -/\n@[simp]\ntheorem card_toMultiset (s : Cycle α) : s.toMultiset.card = s.length :=\n Quotient.inductionOn' s (by simp)\n#align cycle.card_to_multiset Cycle.card_toMultiset\n\n#print Cycle.toMultiset_eq_nil /-\n@[simp]\ntheorem toMultiset_eq_nil {s : Cycle α} : s.toMultiset = 0 ↔ s = Cycle.nil :=\n Quotient.inductionOn' s (by simp)\n#align cycle.to_multiset_eq_nil Cycle.toMultiset_eq_nil\n-/\n\n#print Cycle.map /-\n/-- The lift of `list.map`. -/\ndef map {β : Type _} (f : α → β) : Cycle α → Cycle β :=\n Quotient.map' (List.map f) fun l₁ l₂ h => h.map _\n#align cycle.map Cycle.map\n-/\n\n#print Cycle.map_nil /-\n@[simp]\ntheorem map_nil {β : Type _} (f : α → β) : map f nil = nil :=\n rfl\n#align cycle.map_nil Cycle.map_nil\n-/\n\n#print Cycle.map_coe /-\n@[simp]\ntheorem map_coe {β : Type _} (f : α → β) (l : List α) : map f ↑l = List.map f l :=\n rfl\n#align cycle.map_coe Cycle.map_coe\n-/\n\n#print Cycle.map_eq_nil /-\n@[simp]\ntheorem map_eq_nil {β : Type _} (f : α → β) (s : Cycle α) : map f s = nil ↔ s = nil :=\n Quotient.inductionOn' s (by simp)\n#align cycle.map_eq_nil Cycle.map_eq_nil\n-/\n\n#print Cycle.mem_map /-\n@[simp]\ntheorem mem_map {β : Type _} {f : α → β} {b : β} {s : Cycle α} :\n b ∈ s.map f ↔ ∃ a, a ∈ s ∧ f a = b :=\n Quotient.inductionOn' s (by simp)\n#align cycle.mem_map Cycle.mem_map\n-/\n\n#print Cycle.lists /-\n/-- The `multiset` of lists that can make the cycle. -/\ndef lists (s : Cycle α) : Multiset (List α) :=\n Quotient.liftOn' s (fun l => (l.cyclicPermutations : Multiset (List α))) fun l₁ l₂ h => by\n simpa using h.cyclic_permutations.perm\n#align cycle.lists Cycle.lists\n-/\n\n#print Cycle.lists_coe /-\n@[simp]\ntheorem lists_coe (l : List α) : lists (l : Cycle α) = ↑l.cyclicPermutations :=\n rfl\n#align cycle.lists_coe Cycle.lists_coe\n-/\n\n#print Cycle.mem_lists_iff_coe_eq /-\n@[simp]\ntheorem mem_lists_iff_coe_eq {s : Cycle α} {l : List α} : l ∈ s.lists ↔ (l : Cycle α) = s :=\n Quotient.inductionOn' s fun l =>\n by\n rw [Lists, Quotient.liftOn'_mk'']\n simp\n#align cycle.mem_lists_iff_coe_eq Cycle.mem_lists_iff_coe_eq\n-/\n\n#print Cycle.lists_nil /-\n@[simp]\ntheorem lists_nil : lists (@nil α) = [([] : List α)] := by\n rw [nil, lists_coe, cyclic_permutations_nil]\n#align cycle.lists_nil Cycle.lists_nil\n-/\n\nsection Decidable\n\nvariable [DecidableEq α]\n\n#print Cycle.decidableNontrivialCoe /-\n/-- Auxiliary decidability algorithm for lists that contain at least two unique elements.\n-/\ndef decidableNontrivialCoe : ∀ l : List α, Decidable (Nontrivial (l : Cycle α))\n | [] => isFalse (by simp [Nontrivial])\n | [x] => isFalse (by simp [Nontrivial])\n | x :: y :: l =>\n if h : x = y then\n @decidable_of_iff' _ (Nontrivial (x :: l : Cycle α)) (by simp [h, Nontrivial])\n (decidable_nontrivial_coe (x :: l))\n else isTrue ⟨x, y, h, by simp, by simp⟩\n#align cycle.decidable_nontrivial_coe Cycle.decidableNontrivialCoe\n-/\n\ninstance {s : Cycle α} : Decidable (Nontrivial s) :=\n Quot.recOnSubsingleton' s decidableNontrivialCoe\n\ninstance {s : Cycle α} : Decidable (Nodup s) :=\n Quot.recOnSubsingleton' s List.nodupDecidable\n\n#print Cycle.fintypeNodupCycle /-\ninstance fintypeNodupCycle [Fintype α] : Fintype { s : Cycle α // s.Nodup } :=\n Fintype.ofSurjective (fun l : { l : List α // l.Nodup } => ⟨l.val, by simpa using l.prop⟩)\n fun ⟨s, hs⟩ => by\n induction s using Quotient.inductionOn'\n exact ⟨⟨s, hs⟩, by simp⟩\n#align cycle.fintype_nodup_cycle Cycle.fintypeNodupCycle\n-/\n\n#print Cycle.fintypeNodupNontrivialCycle /-\ninstance fintypeNodupNontrivialCycle [Fintype α] :\n Fintype { s : Cycle α // s.Nodup ∧ s.Nontrivial } :=\n Fintype.subtype\n (((Finset.univ : Finset { s : Cycle α // s.Nodup }).map (Function.Embedding.subtype _)).filterₓ\n Cycle.Nontrivial)\n (by simp)\n#align cycle.fintype_nodup_nontrivial_cycle Cycle.fintypeNodupNontrivialCycle\n-/\n\n#print Cycle.toFinset /-\n/-- The `s : cycle α` as a `finset α`. -/\ndef toFinset (s : Cycle α) : Finset α :=\n s.toMultiset.toFinset\n#align cycle.to_finset Cycle.toFinset\n-/\n\n#print Cycle.toFinset_toMultiset /-\n@[simp]\ntheorem toFinset_toMultiset (s : Cycle α) : s.toMultiset.toFinset = s.toFinset :=\n rfl\n#align cycle.to_finset_to_multiset Cycle.toFinset_toMultiset\n-/\n\n#print Cycle.coe_toFinset /-\n@[simp]\ntheorem coe_toFinset (l : List α) : (l : Cycle α).toFinset = l.toFinset :=\n rfl\n#align cycle.coe_to_finset Cycle.coe_toFinset\n-/\n\n#print Cycle.nil_toFinset /-\n@[simp]\ntheorem nil_toFinset : (@nil α).toFinset = ∅ :=\n rfl\n#align cycle.nil_to_finset Cycle.nil_toFinset\n-/\n\n#print Cycle.toFinset_eq_nil /-\n@[simp]\ntheorem toFinset_eq_nil {s : Cycle α} : s.toFinset = ∅ ↔ s = Cycle.nil :=\n Quotient.inductionOn' s (by simp)\n#align cycle.to_finset_eq_nil Cycle.toFinset_eq_nil\n-/\n\n#print Cycle.next /-\n/-- Given a `s : cycle α` such that `nodup s`, retrieve the next element after `x ∈ s`. -/\ndef next : ∀ (s : Cycle α) (hs : Nodup s) (x : α) (hx : x ∈ s), α := fun s =>\n Quot.hrecOn s (fun l hn x hx => next l x hx) fun l₁ l₂ h =>\n Function.hfunext (propext h.nodup_iff) fun h₁ h₂ he =>\n Function.hfunext rfl fun x y hxy =>\n Function.hfunext (propext (by simpa [eq_of_hEq hxy] using h.mem_iff)) fun hm hm' he' =>\n hEq_of_eq (by simpa [eq_of_hEq hxy] using is_rotated_next_eq h h₁ _)\n#align cycle.next Cycle.next\n-/\n\n#print Cycle.prev /-\n/-- Given a `s : cycle α` such that `nodup s`, retrieve the previous element before `x ∈ s`. -/\ndef prev : ∀ (s : Cycle α) (hs : Nodup s) (x : α) (hx : x ∈ s), α := fun s =>\n Quot.hrecOn s (fun l hn x hx => prev l x hx) fun l₁ l₂ h =>\n Function.hfunext (propext h.nodup_iff) fun h₁ h₂ he =>\n Function.hfunext rfl fun x y hxy =>\n Function.hfunext (propext (by simpa [eq_of_hEq hxy] using h.mem_iff)) fun hm hm' he' =>\n hEq_of_eq (by simpa [eq_of_hEq hxy] using is_rotated_prev_eq h h₁ _)\n#align cycle.prev Cycle.prev\n-/\n\n#print Cycle.prev_reverse_eq_next /-\n@[simp]\ntheorem prev_reverse_eq_next (s : Cycle α) (hs : Nodup s) (x : α) (hx : x ∈ s) :\n s.reverse.prev (nodup_reverse_iff.mpr hs) x (mem_reverse_iff.mpr hx) = s.next hs x hx :=\n (Quotient.inductionOn' s prev_reverse_eq_next) hs x hx\n#align cycle.prev_reverse_eq_next Cycle.prev_reverse_eq_next\n-/\n\n#print Cycle.next_reverse_eq_prev /-\n@[simp]\ntheorem next_reverse_eq_prev (s : Cycle α) (hs : Nodup s) (x : α) (hx : x ∈ s) :\n s.reverse.next (nodup_reverse_iff.mpr hs) x (mem_reverse_iff.mpr hx) = s.prev hs x hx := by\n simp [← prev_reverse_eq_next]\n#align cycle.next_reverse_eq_prev Cycle.next_reverse_eq_prev\n-/\n\n#print Cycle.next_mem /-\n@[simp]\ntheorem next_mem (s : Cycle α) (hs : Nodup s) (x : α) (hx : x ∈ s) : s.next hs x hx ∈ s :=\n by\n induction s using Quot.inductionOn\n apply next_mem\n#align cycle.next_mem Cycle.next_mem\n-/\n\n#print Cycle.prev_mem /-\ntheorem prev_mem (s : Cycle α) (hs : Nodup s) (x : α) (hx : x ∈ s) : s.prev hs x hx ∈ s :=\n by\n rw [← next_reverse_eq_prev, ← mem_reverse_iff]\n apply next_mem\n#align cycle.prev_mem Cycle.prev_mem\n-/\n\n#print Cycle.prev_next /-\n@[simp]\ntheorem prev_next (s : Cycle α) (hs : Nodup s) (x : α) (hx : x ∈ s) :\n s.prev hs (s.next hs x hx) (next_mem s hs x hx) = x :=\n (Quotient.inductionOn' s prev_next) hs x hx\n#align cycle.prev_next Cycle.prev_next\n-/\n\n#print Cycle.next_prev /-\n@[simp]\ntheorem next_prev (s : Cycle α) (hs : Nodup s) (x : α) (hx : x ∈ s) :\n s.next hs (s.prev hs x hx) (prev_mem s hs x hx) = x :=\n (Quotient.inductionOn' s next_prev) hs x hx\n#align cycle.next_prev Cycle.next_prev\n-/\n\nend Decidable\n\n/-- We define a representation of concrete cycles, available when viewing them in a goal state or\nvia `#eval`, when over representable types. For example, the cycle `(2 1 4 3)` will be shown\nas `c[2, 1, 4, 3]`. Two equal cycles may be printed differently if their internal representation\nis different.\n-/\nunsafe instance [Repr α] : Repr (Cycle α) :=\n ⟨fun s => \"c[\" ++ String.intercalate \", \" (s.map repr).lists.unquot.headI ++ \"]\"⟩\n\n#print Cycle.Chain /-\n/-- `chain R s` means that `R` holds between adjacent elements of `s`.\n\n`chain R ([a, b, c] : cycle α) ↔ R a b ∧ R b c ∧ R c a` -/\ndef Chain (r : α → α → Prop) (c : Cycle α) : Prop :=\n Quotient.liftOn' c\n (fun l =>\n match l with\n | [] => True\n | a :: m => Chain r a (m ++ [a]))\n fun a b hab =>\n propext <| by\n cases' a with a l <;> cases' b with b m\n · rfl\n · have := is_rotated_nil_iff'.1 hab\n contradiction\n · have := is_rotated_nil_iff.1 hab\n contradiction\n · unfold chain._match_1\n cases' hab with n hn\n induction' n with d hd generalizing a b l m\n · simp only [rotate_zero] at hn\n rw [hn.1, hn.2]\n · cases' l with c s\n · simp only [rotate_singleton] at hn\n rw [hn.1, hn.2]\n · rw [Nat.succ_eq_one_add, ← rotate_rotate, rotate_cons_succ, rotate_zero, cons_append] at\n hn\n rw [← hd c _ _ _ hn]\n simp [and_comm]\n#align cycle.chain Cycle.Chain\n-/\n\n#print Cycle.Chain.nil /-\n@[simp]\ntheorem Chain.nil (r : α → α → Prop) : Cycle.Chain r (@nil α) := by trivial\n#align cycle.chain.nil Cycle.Chain.nil\n-/\n\n#print Cycle.chain_coe_cons /-\n@[simp]\ntheorem chain_coe_cons (r : α → α → Prop) (a : α) (l : List α) :\n Chain r (a :: l) ↔ List.Chain r a (l ++ [a]) :=\n Iff.rfl\n#align cycle.chain_coe_cons Cycle.chain_coe_cons\n-/\n\n#print Cycle.chain_singleton /-\n@[simp]\ntheorem chain_singleton (r : α → α → Prop) (a : α) : Chain r [a] ↔ r a a := by\n rw [chain_coe_cons, nil_append, chain_singleton]\n#align cycle.chain_singleton Cycle.chain_singleton\n-/\n\n#print Cycle.chain_ne_nil /-\ntheorem chain_ne_nil (r : α → α → Prop) {l : List α} :\n ∀ hl : l ≠ [], Chain r l ↔ List.Chain r (getLast l hl) l :=\n by\n apply l.reverse_rec_on\n exact fun hm => hm.irrefl.elim\n intro m a H _\n rw [← coe_cons_eq_coe_append, chain_coe_cons, last_append_singleton]\n#align cycle.chain_ne_nil Cycle.chain_ne_nil\n-/\n\n#print Cycle.chain_map /-\ntheorem chain_map {β : Type _} {r : α → α → Prop} (f : β → α) {s : Cycle β} :\n Chain r (s.map f) ↔ Chain (fun a b => r (f a) (f b)) s :=\n Quotient.inductionOn' s fun l => by\n cases' l with a l\n rfl\n convert List.chain_map f\n rw [map_append f l [a]]\n rfl\n#align cycle.chain_map Cycle.chain_map\n-/\n\n#print Cycle.chain_range_succ /-\ntheorem chain_range_succ (r : ℕ → ℕ → Prop) (n : ℕ) :\n Chain r (List.range n.succ) ↔ r n 0 ∧ ∀ m < n, r m m.succ := by\n rw [range_succ, ← coe_cons_eq_coe_append, chain_coe_cons, ← range_succ, chain_range_succ]\n#align cycle.chain_range_succ Cycle.chain_range_succ\n-/\n\nvariable {r : α → α → Prop} {s : Cycle α}\n\n#print Cycle.chain_of_pairwise /-\ntheorem chain_of_pairwise : (∀ a ∈ s, ∀ b ∈ s, r a b) → Chain r s :=\n by\n induction' s using Cycle.induction_on with a l _\n exact fun _ => Cycle.Chain.nil r\n intro hs\n have Ha : a ∈ (a :: l : Cycle α) := by simp\n have Hl : ∀ {b} (hb : b ∈ l), b ∈ (a :: l : Cycle α) := fun b hb => by simp [hb]\n rw [Cycle.chain_coe_cons]\n apply pairwise.chain\n rw [pairwise_cons]\n refine'\n ⟨fun b hb => _,\n pairwise_append.2\n ⟨pairwise_of_forall_mem_list fun b hb c hc => hs b (Hl hb) c (Hl hc),\n pairwise_singleton r a, fun b hb c hc => _⟩⟩\n · rw [mem_append] at hb\n cases hb\n · exact hs a Ha b (Hl hb)\n · rw [mem_singleton] at hb\n rw [hb]\n exact hs a Ha a Ha\n · rw [mem_singleton] at hc\n rw [hc]\n exact hs b (Hl hb) a Ha\n#align cycle.chain_of_pairwise Cycle.chain_of_pairwise\n-/\n\n#print Cycle.chain_iff_pairwise /-\ntheorem chain_iff_pairwise [IsTrans α r] : Chain r s ↔ ∀ a ∈ s, ∀ b ∈ s, r a b :=\n ⟨by\n induction' s using Cycle.induction_on with a l _\n exact fun _ b hb => hb.elim\n intro hs b hb c hc\n rw [Cycle.chain_coe_cons, chain_iff_pairwise] at hs\n simp only [pairwise_append, pairwise_cons, mem_append, mem_singleton, List.not_mem_nil,\n IsEmpty.forall_iff, imp_true_iff, pairwise.nil, forall_eq, true_and_iff] at hs\n simp only [mem_coe_iff, mem_cons_iff] at hb hc\n rcases hb with (rfl | hb) <;> rcases hc with (rfl | hc)\n · exact hs.1 c (Or.inr rfl)\n · exact hs.1 c (Or.inl hc)\n · exact hs.2.2 b hb\n · exact trans (hs.2.2 b hb) (hs.1 c (Or.inl hc)), Cycle.chain_of_pairwise⟩\n#align cycle.chain_iff_pairwise Cycle.chain_iff_pairwise\n-/\n\n#print Cycle.forall_eq_of_chain /-\ntheorem forall_eq_of_chain [IsTrans α r] [IsAntisymm α r] (hs : Chain r s) {a b : α} (ha : a ∈ s)\n (hb : b ∈ s) : a = b := by\n rw [chain_iff_pairwise] at hs\n exact antisymm (hs a ha b hb) (hs b hb a ha)\n#align cycle.forall_eq_of_chain Cycle.forall_eq_of_chain\n-/\n\nend Cycle\n\n", "meta": {"author": "leanprover-community", "repo": "mathlib3port", "sha": "62505aa236c58c8559783b16d33e30df3daa54f4", "save_path": "github-repos/lean/leanprover-community-mathlib3port", "path": "github-repos/lean/leanprover-community-mathlib3port/mathlib3port-62505aa236c58c8559783b16d33e30df3daa54f4/Mathbin/Data/List/Cycle.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47657965106367595, "lm_q2_score": 0.09947021454949946, "lm_q1q2_score": 0.04740548014122944}} {"text": "/-\nCopyright (c) 2022 Mario Carneiro. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Mario Carneiro\n-/\nimport Lean\nimport Mathlib.Tactic.OpenPrivate\nimport Mathlib.Data.List.Defs\n\n/-!\n\n# Backward compatible implementation of lean 3 `cases` tactic\n\nThis tactic is similar to the `cases` tactic in lean 4 core, but the syntax for giving\nnames is different:\n\n```\nexample (h : p ∨ q) : q ∨ p := by\n cases h with\n | inl hp => exact Or.inr hp\n | inr hq => exact Or.inl hq\n\nexample (h : p ∨ q) : q ∨ p := by\n cases' h with hp hq\n · exact Or.inr hp\n · exact Or.inl hq\n\nexample (h : p ∨ q) : q ∨ p := by\n rcases h with hp | hq\n · exact Or.inr hp\n · exact Or.inl hq\n```\n\nPrefer `cases` or `rcases` when possible, because these tactics promote structured proofs.\n-/\n\nnamespace Lean.Parser.Tactic\nopen Meta Elab Elab.Tactic\n\nopen private getAltNumFields in evalCases ElimApp.evalAlts.go in\ndef ElimApp.evalNames (elimInfo : ElimInfo) (alts : Array (Name × MVarId)) (withArg : Syntax)\n (numEqs := 0) (numGeneralized := 0) (toClear : Array FVarId := #[]) :\n TermElabM (Array MVarId) := do\n let mut names := if withArg.isNone then [] else\n withArg[1].getArgs.map (getNameOfIdent' ·[0]) |>.toList\n let mut subgoals := #[]\n for (altName, g) in alts do\n let numFields ← getAltNumFields elimInfo altName\n let (altVarNames, names') := names.splitAtD numFields `_\n names := names'\n let (_, g) ← introN g numFields altVarNames\n let some (g, _) ← Cases.unifyEqs numEqs g {} | pure ()\n let (_, g) ← introNP g numGeneralized\n let g ← liftM $ toClear.foldlM tryClear g\n subgoals := subgoals.push g\n pure subgoals\n\nopen private getElimNameInfo generalizeTargets generalizeVars in evalInduction in\nelab (name := induction') tk:\"induction' \" tgts:(casesTarget,+)\n usingArg:(\" using \" ident)?\n withArg:(\" with \" (colGt binderIdent)+)?\n genArg:(\" generalizing \" (colGt ident)+)? : tactic => do\n let targets ← elabCasesTargets tgts.getSepArgs\n let (elimName, elimInfo) ← getElimNameInfo usingArg targets (induction := true)\n let g ← getMainGoal\n withMVarContext g do\n let targets ← addImplicitTargets elimInfo targets\n evalInduction.checkTargets targets\n let targetFVarIds := targets.map (·.fvarId!)\n withMVarContext g do\n let genArgs ← if genArg.isNone then pure #[] else getFVarIds genArg[1].getArgs\n let forbidden ← mkGeneralizationForbiddenSet targets\n let mut s ← getFVarSetToGeneralize targets forbidden\n for v in genArgs do\n if forbidden.contains v then\n throwError \"variable cannot be generalized because target depends on it{indentExpr (mkFVar v)}\"\n if s.contains v then\n throwError \"unnecessary 'generalizing' argument, variable '{mkFVar v}' is generalized automatically\"\n s := s.insert v\n let (fvarIds, g) ← Meta.revert g (← sortFVarIds s.toArray)\n let result ← withRef tgts <| ElimApp.mkElimApp elimName elimInfo targets (← getMVarTag g)\n let elimArgs := result.elimApp.getAppArgs\n ElimApp.setMotiveArg g elimArgs[elimInfo.motivePos].mvarId! targetFVarIds\n assignExprMVar g result.elimApp\n let subgoals ← ElimApp.evalNames elimInfo result.alts withArg\n (numGeneralized := fvarIds.size) (toClear := targetFVarIds)\n setGoals (subgoals ++ result.others).toList\n\nopen private getElimNameInfo in evalCases in\nelab (name := cases') \"cases' \" tgts:(casesTarget,+) usingArg:(\" using \" ident)?\n withArg:(\" with \" (colGt binderIdent)+)? : tactic => do\n let targets ← elabCasesTargets tgts.getSepArgs\n let (elimName, elimInfo) ← getElimNameInfo usingArg targets (induction := false)\n let g ← getMainGoal\n withMVarContext g do\n let targets ← addImplicitTargets elimInfo targets\n let result ← withRef tgts <| ElimApp.mkElimApp elimName elimInfo targets (← getMVarTag g)\n let elimArgs := result.elimApp.getAppArgs\n let targets ← elimInfo.targetsPos.mapM (instantiateMVars elimArgs[·])\n let motive := elimArgs[elimInfo.motivePos]\n let g ← generalizeTargetsEq g (← inferType motive) targets\n let (targetsNew, g) ← introN g targets.size\n withMVarContext g do\n ElimApp.setMotiveArg g motive.mvarId! targetsNew\n assignExprMVar g result.elimApp\n let subgoals ← ElimApp.evalNames elimInfo result.alts withArg\n (numEqs := targets.size) (toClear := targetsNew)\n setGoals subgoals.toList\n", "meta": {"author": "JOSHCLUNE", "repo": "Keller_reduction", "sha": "dc392b3da352fc1ffcfbecb1d4717d05f5faed4a", "save_path": "github-repos/lean/JOSHCLUNE-Keller_reduction", "path": "github-repos/lean/JOSHCLUNE-Keller_reduction/Keller_reduction-dc392b3da352fc1ffcfbecb1d4717d05f5faed4a/Lean4_Clique/Mathlib/Mathlib/Tactic/Cases.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.476579651063676, "lm_q2_score": 0.09947021254732229, "lm_q1q2_score": 0.04740547918703254}} {"text": "/-\nCopyright (c) 2020 Markus Himmel. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Markus Himmel, Johan Commelin, Scott Morrison\n-/\n\nimport category_theory.limits.constructions.pullbacks\nimport category_theory.limits.shapes.biproducts\nimport category_theory.limits.shapes.images\nimport category_theory.limits.constructions.limits_of_products_and_equalizers\nimport category_theory.abelian.non_preadditive\n\n/-!\n# Abelian categories\n\nThis file contains the definition and basic properties of abelian categories.\n\nThere are many definitions of abelian category. Our definition is as follows:\nA category is called abelian if it is preadditive,\nhas a finite products, kernels and cokernels,\nand if every monomorphism and epimorphism is normal.\n\nIt should be noted that if we also assume coproducts, then preadditivity is\nactually a consequence of the other properties, as we show in\n`non_preadditive_abelian.lean`. However, this fact is of little practical\nrelevance, since essentially all interesting abelian categories come with a\npreadditive structure. In this way, by requiring preadditivity, we allow the\nuser to pass in the \"native\" preadditive structure for the specific category they are\nworking with.\n\n## Main definitions\n\n* `abelian` is the type class indicating that a category is abelian. It extends `preadditive`.\n* `abelian.image f` is `kernel (cokernel.π f)`, and\n* `abelian.coimage f` is `cokernel (kernel.ι f)`.\n\n## Main results\n\n* In an abelian category, mono + epi = iso.\n* If `f : X ⟶ Y`, then the map `factor_thru_image f : X ⟶ image f` is an epimorphism, and the map\n `factor_thru_coimage f : coimage f ⟶ Y` is a monomorphism.\n* Factoring through the image and coimage is a strong epi-mono factorisation. This means that\n * every abelian category has images. We provide the isomorphism\n `image_iso_image : abelian.image f ≅ limits.image f`.\n * the canonical morphism `coimage_image_comparison : coimage f ⟶ image f`\n is an isomorphism.\n* We provide the alternate characterisation of an abelian category as a category with\n (co)kernels and finite products, and in which the canonical coimage-image comparison morphism\n is always an isomorphism.\n* Every epimorphism is a cokernel of its kernel. Every monomorphism is a kernel of its cokernel.\n* The pullback of an epimorphism is an epimorphism. The pushout of a monomorphism is a monomorphism.\n (This is not to be confused with the fact that the pullback of a monomorphism is a monomorphism,\n which is true in any category).\n\n## Implementation notes\n\nThe typeclass `abelian` does not extend `non_preadditive_abelian`,\nto avoid having to deal with comparing the two `has_zero_morphisms` instances\n(one from `preadditive` in `abelian`, and the other a field of `non_preadditive_abelian`).\nAs a consequence, at the beginning of this file we trivially build\na `non_preadditive_abelian` instance from an `abelian` instance,\nand use this to restate a number of theorems,\nin each case just reusing the proof from `non_preadditive_abelian.lean`.\n\nWe don't show this yet, but abelian categories are finitely complete and finitely cocomplete.\nHowever, the limits we can construct at this level of generality will most likely be less nice than\nthe ones that can be created in specific applications. For this reason, we adopt the following\nconvention:\n\n* If the statement of a theorem involves limits, the existence of these limits should be made an\n explicit typeclass parameter.\n* If a limit only appears in a proof, but not in the statement of a theorem, the limit should not\n be a typeclass parameter, but instead be created using `abelian.has_pullbacks` or a similar\n definition.\n\n## References\n\n* [F. Borceux, *Handbook of Categorical Algebra 2*][borceux-vol2]\n* [P. Aluffi, *Algebra: Chapter 0*][aluffi2016]\n\n-/\n\nnoncomputable theory\n\nopen category_theory\nopen category_theory.preadditive\nopen category_theory.limits\n\nuniverses v u\n\nnamespace category_theory\n\nvariables {C : Type u} [category.{v} C]\n\nvariables (C)\n\n/--\nA (preadditive) category `C` is called abelian if it has all finite products,\nall kernels and cokernels, and if every monomorphism is the kernel of some morphism\nand every epimorphism is the cokernel of some morphism.\n\n(This definition implies the existence of zero objects:\nfinite products give a terminal object, and in a preadditive category\nany terminal object is a zero object.)\n-/\nclass abelian extends preadditive C, normal_mono_category C, normal_epi_category C :=\n[has_finite_products : has_finite_products C]\n[has_kernels : has_kernels C]\n[has_cokernels : has_cokernels C]\n\nattribute [instance, priority 100] abelian.has_finite_products\nattribute [instance, priority 100] abelian.has_kernels abelian.has_cokernels\n\nend category_theory\n\nopen category_theory\n\n/-!\nWe begin by providing an alternative constructor:\na preadditive category with kernels, cokernels, and finite products,\nin which the coimage-image comparison morphism is always an isomorphism,\nis an abelian category.\n-/\nnamespace category_theory.abelian\n\nvariables {C : Type u} [category.{v} C] [preadditive C]\nvariables [limits.has_kernels C] [limits.has_cokernels C]\n\nnamespace of_coimage_image_comparison_is_iso\n\n/-- The factorisation of a morphism through its abelian image. -/\n@[simps]\ndef image_mono_factorisation {X Y : C} (f : X ⟶ Y) : mono_factorisation f :=\n{ I := abelian.image f,\n m := kernel.ι _,\n m_mono := infer_instance,\n e := kernel.lift _ f (cokernel.condition _),\n fac' := kernel.lift_ι _ _ _ }\n\nlemma image_mono_factorisation_e' {X Y : C} (f : X ⟶ Y) :\n (image_mono_factorisation f).e = cokernel.π _ ≫ abelian.coimage_image_comparison f :=\nbegin\n ext,\n simp only [abelian.coimage_image_comparison, image_mono_factorisation_e,\n category.assoc, cokernel.π_desc_assoc],\nend\n\n/-- If the coimage-image comparison morphism for a morphism `f` is an isomorphism,\nwe obtain an image factorisation of `f`. -/\ndef image_factorisation {X Y : C} (f : X ⟶ Y) [is_iso (abelian.coimage_image_comparison f)] :\n image_factorisation f :=\n{ F := image_mono_factorisation f,\n is_image :=\n { lift := λ F, inv (abelian.coimage_image_comparison f) ≫ cokernel.desc _ F.e F.kernel_ι_comp,\n lift_fac' := λ F, begin\n simp only [image_mono_factorisation_m, is_iso.inv_comp_eq, category.assoc,\n abelian.coimage_image_comparison],\n ext,\n rw [limits.coequalizer.π_desc_assoc, limits.coequalizer.π_desc_assoc, F.fac, kernel.lift_ι]\n end } }\n\ninstance [has_zero_object C] {X Y : C} (f : X ⟶ Y) [mono f]\n [is_iso (abelian.coimage_image_comparison f)] :\n is_iso (image_mono_factorisation f).e :=\nby { rw image_mono_factorisation_e', exact is_iso.comp_is_iso }\n\ninstance [has_zero_object C] {X Y : C} (f : X ⟶ Y) [epi f] :\n is_iso (image_mono_factorisation f).m :=\nby { dsimp, apply_instance }\n\nvariables [∀ {X Y : C} (f : X ⟶ Y), is_iso (abelian.coimage_image_comparison f)]\n\n/-- A category in which coimage-image comparisons are all isomorphisms has images. -/\nlemma has_images : has_images C :=\n{ has_image := λ X Y f,\n { exists_image := ⟨image_factorisation f⟩ } }\n\nvariables [limits.has_finite_products C]\nlocal attribute [instance] limits.has_finite_biproducts.of_has_finite_products\n\n/--\nA category with finite products in which coimage-image comparisons are all isomorphisms\nis a normal mono category.\n-/\ndef normal_mono_category : normal_mono_category C :=\n{ normal_mono_of_mono := λ X Y f m,\n { Z := _,\n g := cokernel.π f,\n w := by simp,\n is_limit := begin\n haveI : limits.has_images C := has_images,\n haveI : has_equalizers C := preadditive.has_equalizers_of_has_kernels,\n letI : has_zero_object C := has_zero_object_of_has_finite_biproducts _,\n have aux : _ := _,\n refine is_limit_aux _ (λ A, limit.lift _ _ ≫ inv (image_mono_factorisation f).e) aux _,\n { intros A g hg,\n rw [kernel_fork.ι_of_ι] at hg,\n rw [← cancel_mono f, hg, ← aux, kernel_fork.ι_of_ι], },\n { intro A,\n simp only [kernel_fork.ι_of_ι, category.assoc],\n convert limit.lift_π _ _ using 2,\n rw [is_iso.inv_comp_eq, eq_comm],\n exact (image_mono_factorisation f).fac, },\n end }, }\n\n/--\nA category with finite products in which coimage-image comparisons are all isomorphisms\nis a normal epi category.\n-/\ndef normal_epi_category : normal_epi_category C :=\n{ normal_epi_of_epi := λ X Y f m,\n { W := kernel f,\n g := kernel.ι _,\n w := kernel.condition _,\n is_colimit := begin\n haveI : limits.has_images C := has_images,\n haveI : has_equalizers C := preadditive.has_equalizers_of_has_kernels,\n letI : has_zero_object C := has_zero_object_of_has_finite_biproducts _,\n have aux : _ := _,\n refine is_colimit_aux _\n (λ A, inv (image_mono_factorisation f).m ≫\n inv (abelian.coimage_image_comparison f) ≫ colimit.desc _ _)\n aux _,\n { intros A g hg,\n rw [cokernel_cofork.π_of_π] at hg,\n rw [← cancel_epi f, hg, ← aux, cokernel_cofork.π_of_π], },\n { intro A,\n simp only [cokernel_cofork.π_of_π, ← category.assoc],\n convert colimit.ι_desc _ _ using 2,\n rw [is_iso.comp_inv_eq, is_iso.comp_inv_eq, eq_comm, ←image_mono_factorisation_e'],\n exact (image_mono_factorisation f).fac, }\n end }, }\n\nend of_coimage_image_comparison_is_iso\n\nvariables [∀ {X Y : C} (f : X ⟶ Y), is_iso (abelian.coimage_image_comparison f)]\n [limits.has_finite_products C]\nlocal attribute [instance] of_coimage_image_comparison_is_iso.normal_mono_category\nlocal attribute [instance] of_coimage_image_comparison_is_iso.normal_epi_category\n\n/--\nA preadditive category with kernels, cokernels, and finite products,\nin which the coimage-image comparison morphism is always an isomorphism,\nis an abelian category.\n\nThe Stacks project uses this characterisation at the definition of an abelian category.\nSee https://stacks.math.columbia.edu/tag/0109.\n-/\ndef of_coimage_image_comparison_is_iso : abelian C := {}\n\nend category_theory.abelian\n\nnamespace category_theory.abelian\nvariables {C : Type u} [category.{v} C] [abelian C]\n\n/-- An abelian category has finite biproducts. -/\n@[priority 100]\ninstance has_finite_biproducts : has_finite_biproducts C :=\nlimits.has_finite_biproducts.of_has_finite_products\n\n@[priority 100]\ninstance has_binary_biproducts : has_binary_biproducts C :=\nlimits.has_binary_biproducts_of_finite_biproducts _\n\n@[priority 100]\ninstance has_zero_object : has_zero_object C :=\nhas_zero_object_of_has_initial_object\n\nsection to_non_preadditive_abelian\n\n/-- Every abelian category is, in particular, `non_preadditive_abelian`. -/\ndef non_preadditive_abelian : non_preadditive_abelian C := { ..‹abelian C› }\n\nend to_non_preadditive_abelian\n\nsection\n/-! We now promote some instances that were constructed using `non_preadditive_abelian`. -/\n\nlocal attribute [instance] non_preadditive_abelian\n\nvariables {P Q : C} (f : P ⟶ Q)\n\n/-- The map `p : P ⟶ image f` is an epimorphism -/\ninstance : epi (abelian.factor_thru_image f) := by apply_instance\n\ninstance is_iso_factor_thru_image [mono f] : is_iso (abelian.factor_thru_image f) :=\nby apply_instance\n\n/-- The canonical morphism `i : coimage f ⟶ Q` is a monomorphism -/\ninstance : mono (abelian.factor_thru_coimage f) := by apply_instance\n\ninstance is_iso_factor_thru_coimage [epi f] : is_iso (abelian.factor_thru_coimage f) :=\nby apply_instance\n\nend\n\nsection factor\nlocal attribute [instance] non_preadditive_abelian\n\nvariables {P Q : C} (f : P ⟶ Q)\n\nsection\n\nlemma mono_of_kernel_ι_eq_zero (h : kernel.ι f = 0) : mono f :=\nmono_of_kernel_zero h\n\nlemma epi_of_cokernel_π_eq_zero (h : cokernel.π f = 0) : epi f :=\nbegin\n apply normal_mono_category.epi_of_zero_cokernel _ (cokernel f),\n simp_rw ←h,\n exact is_colimit.of_iso_colimit (colimit.is_colimit (parallel_pair f 0)) (iso_of_π _)\nend\n\nend\n\nsection\nvariables {f}\n\nlemma image_ι_comp_eq_zero {R : C} {g : Q ⟶ R} (h : f ≫ g = 0) : abelian.image.ι f ≫ g = 0 :=\nzero_of_epi_comp (abelian.factor_thru_image f) $ by simp [h]\n\nlemma comp_coimage_π_eq_zero {R : C} {g : Q ⟶ R} (h : f ≫ g = 0) : f ≫ abelian.coimage.π g = 0 :=\nzero_of_comp_mono (abelian.factor_thru_coimage g) $ by simp [h]\n\nend\n\n/-- Factoring through the image is a strong epi-mono factorisation. -/\n@[simps] def image_strong_epi_mono_factorisation : strong_epi_mono_factorisation f :=\n{ I := abelian.image f,\n m := image.ι f,\n m_mono := by apply_instance,\n e := abelian.factor_thru_image f,\n e_strong_epi := strong_epi_of_epi _ }\n\n/-- Factoring through the coimage is a strong epi-mono factorisation. -/\n@[simps] def coimage_strong_epi_mono_factorisation : strong_epi_mono_factorisation f :=\n{ I := abelian.coimage f,\n m := abelian.factor_thru_coimage f,\n m_mono := by apply_instance,\n e := coimage.π f,\n e_strong_epi := strong_epi_of_epi _ }\n\nend factor\n\nsection has_strong_epi_mono_factorisations\n\n/-- An abelian category has strong epi-mono factorisations. -/\n@[priority 100] instance : has_strong_epi_mono_factorisations C :=\nhas_strong_epi_mono_factorisations.mk $ λ X Y f, image_strong_epi_mono_factorisation f\n\n/- In particular, this means that it has well-behaved images. -/\nexample : has_images C := by apply_instance\nexample : has_image_maps C := by apply_instance\n\nend has_strong_epi_mono_factorisations\n\nsection images\nvariables {X Y : C} (f : X ⟶ Y)\n\n/--\nThe coimage-image comparison morphism is always an isomorphism in an abelian category.\nSee `category_theory.abelian.of_coimage_image_comparison_is_iso` for the converse.\n-/\ninstance : is_iso (coimage_image_comparison f) :=\nbegin\n convert is_iso.of_iso (is_image.iso_ext (coimage_strong_epi_mono_factorisation f).to_mono_is_image\n (image_strong_epi_mono_factorisation f).to_mono_is_image),\n ext,\n change _ = _ ≫ (image_strong_epi_mono_factorisation f).m,\n simp [-image_strong_epi_mono_factorisation_to_mono_factorisation_m]\nend\n\n/-- There is a canonical isomorphism between the abelian coimage and the abelian image of a\n morphism. -/\nabbreviation coimage_iso_image : abelian.coimage f ≅ abelian.image f :=\nas_iso (coimage_image_comparison f)\n\n/-- There is a canonical isomorphism between the abelian coimage and the categorical image of a\n morphism. -/\nabbreviation coimage_iso_image' : abelian.coimage f ≅ image f :=\nis_image.iso_ext (coimage_strong_epi_mono_factorisation f).to_mono_is_image\n (image.is_image f)\n\n/-- There is a canonical isomorphism between the abelian image and the categorical image of a\n morphism. -/\nabbreviation image_iso_image : abelian.image f ≅ image f :=\nis_image.iso_ext (image_strong_epi_mono_factorisation f).to_mono_is_image (image.is_image f)\n\nend images\n\nsection cokernel_of_kernel\nvariables {X Y : C} {f : X ⟶ Y}\n\nlocal attribute [instance] non_preadditive_abelian\n\n/-- In an abelian category, an epi is the cokernel of its kernel. More precisely:\n If `f` is an epimorphism and `s` is some limit kernel cone on `f`, then `f` is a cokernel\n of `fork.ι s`. -/\ndef epi_is_cokernel_of_kernel [epi f] (s : fork f 0) (h : is_limit s) :\n is_colimit (cokernel_cofork.of_π f (kernel_fork.condition s)) :=\nnon_preadditive_abelian.epi_is_cokernel_of_kernel s h\n\n/-- In an abelian category, a mono is the kernel of its cokernel. More precisely:\n If `f` is a monomorphism and `s` is some colimit cokernel cocone on `f`, then `f` is a kernel\n of `cofork.π s`. -/\ndef mono_is_kernel_of_cokernel [mono f] (s : cofork f 0) (h : is_colimit s) :\n is_limit (kernel_fork.of_ι f (cokernel_cofork.condition s)) :=\nnon_preadditive_abelian.mono_is_kernel_of_cokernel s h\n\nvariables (f)\n\n/-- In an abelian category, any morphism that turns to zero when precomposed with the kernel of an\n epimorphism factors through that epimorphism. -/\ndef epi_desc [epi f] {T : C} (g : X ⟶ T) (hg : kernel.ι f ≫ g = 0) : Y ⟶ T :=\n(epi_is_cokernel_of_kernel _ (limit.is_limit _)).desc (cokernel_cofork.of_π _ hg)\n\n@[simp, reassoc]\nlemma comp_epi_desc [epi f] {T : C} (g : X ⟶ T) (hg : kernel.ι f ≫ g = 0) :\n f ≫ epi_desc f g hg = g :=\n(epi_is_cokernel_of_kernel _ (limit.is_limit _)).fac (cokernel_cofork.of_π _ hg)\n walking_parallel_pair.one\n\n/-- In an abelian category, any morphism that turns to zero when postcomposed with the cokernel of a\n monomorphism factors through that monomorphism. -/\ndef mono_lift [mono f] {T : C} (g : T ⟶ Y) (hg : g ≫ cokernel.π f = 0) : T ⟶ X :=\n(mono_is_kernel_of_cokernel _ (colimit.is_colimit _)).lift (kernel_fork.of_ι _ hg)\n\n@[simp, reassoc]\nlemma mono_lift_comp [mono f] {T : C} (g : T ⟶ Y) (hg : g ≫ cokernel.π f = 0) :\n mono_lift f g hg ≫ f = g :=\n(mono_is_kernel_of_cokernel _ (colimit.is_colimit _)).fac (kernel_fork.of_ι _ hg)\n walking_parallel_pair.zero\n\nend cokernel_of_kernel\n\nsection\n\n@[priority 100]\ninstance has_equalizers : has_equalizers C :=\npreadditive.has_equalizers_of_has_kernels\n\n/-- Any abelian category has pullbacks -/\n@[priority 100]\ninstance has_pullbacks : has_pullbacks C :=\nhas_pullbacks_of_has_binary_products_of_has_equalizers C\n\nend\n\nsection\n\n@[priority 100]\ninstance has_coequalizers : has_coequalizers C :=\npreadditive.has_coequalizers_of_has_cokernels\n\n/-- Any abelian category has pushouts -/\n@[priority 100]\ninstance has_pushouts : has_pushouts C :=\nhas_pushouts_of_has_binary_coproducts_of_has_coequalizers C\n\n@[priority 100]\ninstance has_finite_limits : has_finite_limits C :=\nlimits.finite_limits_from_equalizers_and_finite_products\n\n@[priority 100]\ninstance has_finite_colimits : has_finite_colimits C :=\nlimits.finite_colimits_from_coequalizers_and_finite_coproducts\n\nend\n\nnamespace pullback_to_biproduct_is_kernel\nvariables [limits.has_pullbacks C] {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z)\n\n/-! This section contains a slightly technical result about pullbacks and biproducts.\n We will need it in the proof that the pullback of an epimorphism is an epimorpism. -/\n\n/-- The canonical map `pullback f g ⟶ X ⊞ Y` -/\nabbreviation pullback_to_biproduct : pullback f g ⟶ X ⊞ Y :=\nbiprod.lift pullback.fst pullback.snd\n\n/-- The canonical map `pullback f g ⟶ X ⊞ Y` induces a kernel cone on the map\n `biproduct X Y ⟶ Z` induced by `f` and `g`. A slightly more intuitive way to think of\n this may be that it induces an equalizer fork on the maps induced by `(f, 0)` and\n `(0, g)`. -/\nabbreviation pullback_to_biproduct_fork : kernel_fork (biprod.desc f (-g)) :=\nkernel_fork.of_ι (pullback_to_biproduct f g) $\nby rw [biprod.lift_desc, comp_neg, pullback.condition, add_right_neg]\n\n/-- The canonical map `pullback f g ⟶ X ⊞ Y` is a kernel of the map induced by\n `(f, -g)`. -/\ndef is_limit_pullback_to_biproduct : is_limit (pullback_to_biproduct_fork f g) :=\nfork.is_limit.mk _\n (λ s, pullback.lift (fork.ι s ≫ biprod.fst) (fork.ι s ≫ biprod.snd) $\n sub_eq_zero.1 $ by rw [category.assoc, category.assoc, ←comp_sub, sub_eq_add_neg, ←comp_neg,\n ←biprod.desc_eq, kernel_fork.condition s])\n (λ s,\n begin\n ext; rw [fork.ι_of_ι, category.assoc],\n { rw [biprod.lift_fst, pullback.lift_fst] },\n { rw [biprod.lift_snd, pullback.lift_snd] }\n end)\n (λ s m h, by ext; simp [fork.ι_eq_app_zero, ←h walking_parallel_pair.zero])\n\nend pullback_to_biproduct_is_kernel\n\nnamespace biproduct_to_pushout_is_cokernel\nvariables [limits.has_pushouts C] {W X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z)\n\n/-- The canonical map `Y ⊞ Z ⟶ pushout f g` -/\nabbreviation biproduct_to_pushout : Y ⊞ Z ⟶ pushout f g :=\nbiprod.desc pushout.inl pushout.inr\n\n/-- The canonical map `Y ⊞ Z ⟶ pushout f g` induces a cokernel cofork on the map\n `X ⟶ Y ⊞ Z` induced by `f` and `-g`. -/\nabbreviation biproduct_to_pushout_cofork : cokernel_cofork (biprod.lift f (-g)) :=\ncokernel_cofork.of_π (biproduct_to_pushout f g) $\nby rw [biprod.lift_desc, neg_comp, pushout.condition, add_right_neg]\n\n/-- The cofork induced by the canonical map `Y ⊞ Z ⟶ pushout f g` is in fact a colimit cokernel\n cofork. -/\ndef is_colimit_biproduct_to_pushout : is_colimit (biproduct_to_pushout_cofork f g) :=\ncofork.is_colimit.mk _\n (λ s, pushout.desc (biprod.inl ≫ cofork.π s) (biprod.inr ≫ cofork.π s) $\n sub_eq_zero.1 $ by rw [←category.assoc, ←category.assoc, ←sub_comp, sub_eq_add_neg, ←neg_comp,\n ←biprod.lift_eq, cofork.condition s, zero_comp])\n (λ s, by ext; simp)\n (λ s m h, by ext; simp [cofork.π_eq_app_one, ←h walking_parallel_pair.one] )\n\nend biproduct_to_pushout_is_cokernel\n\nsection epi_pullback\nvariables [limits.has_pullbacks C] {W X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z)\n\n/-- In an abelian category, the pullback of an epimorphism is an epimorphism.\n Proof from [aluffi2016, IX.2.3], cf. [borceux-vol2, 1.7.6] -/\ninstance epi_pullback_of_epi_f [epi f] : epi (pullback.snd : pullback f g ⟶ Y) :=\n-- It will suffice to consider some morphism e : Y ⟶ R such that\n-- pullback.snd ≫ e = 0 and show that e = 0.\nepi_of_cancel_zero _ $ λ R e h,\nbegin\n -- Consider the morphism u := (0, e) : X ⊞ Y⟶ R.\n let u := biprod.desc (0 : X ⟶ R) e,\n -- The composite pullback f g ⟶ X ⊞ Y ⟶ R is zero by assumption.\n have hu : pullback_to_biproduct_is_kernel.pullback_to_biproduct f g ≫ u = 0 := by simpa,\n -- pullback_to_biproduct f g is a kernel of (f, -g), so (f, -g) is a\n -- cokernel of pullback_to_biproduct f g\n have := epi_is_cokernel_of_kernel _\n (pullback_to_biproduct_is_kernel.is_limit_pullback_to_biproduct f g),\n -- We use this fact to obtain a factorization of u through (f, -g) via some d : Z ⟶ R.\n obtain ⟨d, hd⟩ := cokernel_cofork.is_colimit.desc' this u hu,\n change Z ⟶ R at d,\n change biprod.desc f (-g) ≫ d = u at hd,\n -- But then f ≫ d = 0:\n have : f ≫ d = 0, calc\n f ≫ d = (biprod.inl ≫ biprod.desc f (-g)) ≫ d : by rw biprod.inl_desc\n ... = biprod.inl ≫ u : by rw [category.assoc, hd]\n ... = 0 : biprod.inl_desc _ _,\n -- But f is an epimorphism, so d = 0...\n have : d = 0 := (cancel_epi f).1 (by simpa),\n -- ...or, in other words, e = 0.\n calc\n e = biprod.inr ≫ u : by rw biprod.inr_desc\n ... = biprod.inr ≫ biprod.desc f (-g) ≫ d : by rw ←hd\n ... = biprod.inr ≫ biprod.desc f (-g) ≫ 0 : by rw this\n ... = (biprod.inr ≫ biprod.desc f (-g)) ≫ 0 : by rw ←category.assoc\n ... = 0 : has_zero_morphisms.comp_zero _ _\nend\n\n/-- In an abelian category, the pullback of an epimorphism is an epimorphism. -/\ninstance epi_pullback_of_epi_g [epi g] : epi (pullback.fst : pullback f g ⟶ X) :=\n-- It will suffice to consider some morphism e : X ⟶ R such that\n-- pullback.fst ≫ e = 0 and show that e = 0.\nepi_of_cancel_zero _ $ λ R e h,\nbegin\n -- Consider the morphism u := (e, 0) : X ⊞ Y ⟶ R.\n let u := biprod.desc e (0 : Y ⟶ R),\n -- The composite pullback f g ⟶ X ⊞ Y ⟶ R is zero by assumption.\n have hu : pullback_to_biproduct_is_kernel.pullback_to_biproduct f g ≫ u = 0 := by simpa,\n -- pullback_to_biproduct f g is a kernel of (f, -g), so (f, -g) is a\n -- cokernel of pullback_to_biproduct f g\n have := epi_is_cokernel_of_kernel _\n (pullback_to_biproduct_is_kernel.is_limit_pullback_to_biproduct f g),\n -- We use this fact to obtain a factorization of u through (f, -g) via some d : Z ⟶ R.\n obtain ⟨d, hd⟩ := cokernel_cofork.is_colimit.desc' this u hu,\n change Z ⟶ R at d,\n change biprod.desc f (-g) ≫ d = u at hd,\n -- But then (-g) ≫ d = 0:\n have : (-g) ≫ d = 0, calc\n (-g) ≫ d = (biprod.inr ≫ biprod.desc f (-g)) ≫ d : by rw biprod.inr_desc\n ... = biprod.inr ≫ u : by rw [category.assoc, hd]\n ... = 0 : biprod.inr_desc _ _,\n -- But g is an epimorphism, thus so is -g, so d = 0...\n have : d = 0 := (cancel_epi (-g)).1 (by simpa),\n -- ...or, in other words, e = 0.\n calc\n e = biprod.inl ≫ u : by rw biprod.inl_desc\n ... = biprod.inl ≫ biprod.desc f (-g) ≫ d : by rw ←hd\n ... = biprod.inl ≫ biprod.desc f (-g) ≫ 0 : by rw this\n ... = (biprod.inl ≫ biprod.desc f (-g)) ≫ 0 : by rw ←category.assoc\n ... = 0 : has_zero_morphisms.comp_zero _ _\nend\n\nlemma epi_snd_of_is_limit [epi f] {s : pullback_cone f g} (hs : is_limit s) : epi s.snd :=\nbegin\n convert epi_of_epi_fac (is_limit.cone_point_unique_up_to_iso_hom_comp (limit.is_limit _) hs _),\n { refl },\n { exact abelian.epi_pullback_of_epi_f _ _ }\nend\n\nlemma epi_fst_of_is_limit [epi g] {s : pullback_cone f g} (hs : is_limit s) : epi s.fst :=\nbegin\n convert epi_of_epi_fac (is_limit.cone_point_unique_up_to_iso_hom_comp (limit.is_limit _) hs _),\n { refl },\n { exact abelian.epi_pullback_of_epi_g _ _ }\nend\n\n/-- Suppose `f` and `g` are two morphisms with a common codomain and suppose we have written `g` as\n an epimorphism followed by a monomorphism. If `f` factors through the mono part of this\n factorization, then any pullback of `g` along `f` is an epimorphism. -/\nlemma epi_fst_of_factor_thru_epi_mono_factorization\n (g₁ : Y ⟶ W) [epi g₁] (g₂ : W ⟶ Z) [mono g₂] (hg : g₁ ≫ g₂ = g) (f' : X ⟶ W) (hf : f' ≫ g₂ = f)\n (t : pullback_cone f g) (ht : is_limit t) : epi t.fst :=\nby apply epi_fst_of_is_limit _ _ (pullback_cone.is_limit_of_factors f g g₂ f' g₁ hf hg t ht)\n\nend epi_pullback\n\nsection mono_pushout\nvariables [limits.has_pushouts C] {W X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z)\n\ninstance mono_pushout_of_mono_f [mono f] : mono (pushout.inr : Z ⟶ pushout f g) :=\nmono_of_cancel_zero _ $ λ R e h,\nbegin\n let u := biprod.lift (0 : R ⟶ Y) e,\n have hu : u ≫ biproduct_to_pushout_is_cokernel.biproduct_to_pushout f g = 0 := by simpa,\n have := mono_is_kernel_of_cokernel _\n (biproduct_to_pushout_is_cokernel.is_colimit_biproduct_to_pushout f g),\n obtain ⟨d, hd⟩ := kernel_fork.is_limit.lift' this u hu,\n change R ⟶ X at d,\n change d ≫ biprod.lift f (-g) = u at hd,\n have : d ≫ f = 0, calc\n d ≫ f = d ≫ biprod.lift f (-g) ≫ biprod.fst : by rw biprod.lift_fst\n ... = u ≫ biprod.fst : by rw [←category.assoc, hd]\n ... = 0 : biprod.lift_fst _ _,\n have : d = 0 := (cancel_mono f).1 (by simpa),\n calc\n e = u ≫ biprod.snd : by rw biprod.lift_snd\n ... = (d ≫ biprod.lift f (-g)) ≫ biprod.snd : by rw ←hd\n ... = (0 ≫ biprod.lift f (-g)) ≫ biprod.snd : by rw this\n ... = 0 ≫ biprod.lift f (-g) ≫ biprod.snd : by rw category.assoc\n ... = 0 : zero_comp\nend\n\ninstance mono_pushout_of_mono_g [mono g] : mono (pushout.inl : Y ⟶ pushout f g) :=\nmono_of_cancel_zero _ $ λ R e h,\nbegin\n let u := biprod.lift e (0 : R ⟶ Z),\n have hu : u ≫ biproduct_to_pushout_is_cokernel.biproduct_to_pushout f g = 0 := by simpa,\n have := mono_is_kernel_of_cokernel _\n (biproduct_to_pushout_is_cokernel.is_colimit_biproduct_to_pushout f g),\n obtain ⟨d, hd⟩ := kernel_fork.is_limit.lift' this u hu,\n change R ⟶ X at d,\n change d ≫ biprod.lift f (-g) = u at hd,\n have : d ≫ (-g) = 0, calc\n d ≫ (-g) = d ≫ biprod.lift f (-g) ≫ biprod.snd : by rw biprod.lift_snd\n ... = u ≫ biprod.snd : by rw [←category.assoc, hd]\n ... = 0 : biprod.lift_snd _ _,\n have : d = 0 := (cancel_mono (-g)).1 (by simpa),\n calc\n e = u ≫ biprod.fst : by rw biprod.lift_fst\n ... = (d ≫ biprod.lift f (-g)) ≫ biprod.fst : by rw ←hd\n ... = (0 ≫ biprod.lift f (-g)) ≫ biprod.fst : by rw this\n ... = 0 ≫ biprod.lift f (-g) ≫ biprod.fst : by rw category.assoc\n ... = 0 : zero_comp\nend\n\nlemma mono_inr_of_is_colimit [mono f] {s : pushout_cocone f g} (hs : is_colimit s) : mono s.inr :=\nbegin\n convert mono_of_mono_fac\n (is_colimit.comp_cocone_point_unique_up_to_iso_hom hs (colimit.is_colimit _) _),\n { refl },\n { exact abelian.mono_pushout_of_mono_f _ _ }\nend\n\n\n\n/-- Suppose `f` and `g` are two morphisms with a common domain and suppose we have written `g` as\n an epimorphism followed by a monomorphism. If `f` factors through the epi part of this\n factorization, then any pushout of `g` along `f` is a monomorphism. -/\nlemma mono_inl_of_factor_thru_epi_mono_factorization (f : X ⟶ Y) (g : X ⟶ Z)\n (g₁ : X ⟶ W) [epi g₁] (g₂ : W ⟶ Z) [mono g₂] (hg : g₁ ≫ g₂ = g) (f' : W ⟶ Y) (hf : g₁ ≫ f' = f)\n (t : pushout_cocone f g) (ht : is_colimit t) : mono t.inl :=\nby apply mono_inl_of_is_colimit _ _ (pushout_cocone.is_colimit_of_factors _ _ _ _ _ hf hg t ht)\n\nend mono_pushout\n\nend category_theory.abelian\n\nnamespace category_theory.non_preadditive_abelian\n\nvariables (C : Type u) [category.{v} C] [non_preadditive_abelian C]\n\n/-- Every non_preadditive_abelian category can be promoted to an abelian category. -/\ndef abelian : abelian C :=\n{ has_finite_products := by apply_instance,\n/- We need the `convert`s here because the instances we have are slightly different from the\n instances we need: `has_kernels` depends on an instance of `has_zero_morphisms`. In the\n case of `non_preadditive_abelian`, this instance is an explicit argument. However, in the case\n of `abelian`, the `has_zero_morphisms` instance is derived from `preadditive`. So we need to\n transform an instance of \"has kernels with non_preadditive_abelian.has_zero_morphisms\" to an\n instance of \"has kernels with non_preadditive_abelian.preadditive.has_zero_morphisms\". Luckily,\n we have a `subsingleton` instance for `has_zero_morphisms`, so `convert` can immediately close\n the goal it creates for the two instances of `has_zero_morphisms`, and the proof is complete. -/\n has_kernels := by convert (by apply_instance : limits.has_kernels C),\n has_cokernels := by convert (by apply_instance : limits.has_cokernels C),\n normal_mono_of_mono := by { introsI, convert normal_mono_of_mono f },\n normal_epi_of_epi := by { introsI, convert normal_epi_of_epi f },\n ..non_preadditive_abelian.preadditive }\n\nend category_theory.non_preadditive_abelian\n", "meta": {"author": "saisurbehera", "repo": "mathProof", "sha": "57c6bfe75652e9d3312d8904441a32aff7d6a75e", "save_path": "github-repos/lean/saisurbehera-mathProof", "path": "github-repos/lean/saisurbehera-mathProof/mathProof-57c6bfe75652e9d3312d8904441a32aff7d6a75e/src/tertiary_packages/mathlib/src/category_theory/abelian/basic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828339529583475, "lm_q2_score": 0.09670578808943048, "lm_q1q2_score": 0.04721983055306661}} {"text": "/-\nCopyright (c) 2020 Scott Morrison. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Scott Morrison\n-/\nimport algebra.category.Group.basic\nimport category_theory.limits.shapes.zero_objects\n\n/-!\n# The category of (commutative) (additive) groups has a zero object.\n\n`AddCommGroup` also has zero morphisms. For definitional reasons, we infer this from preadditivity\nrather than from the existence of a zero object.\n-/\n\nopen category_theory\nopen category_theory.limits\n\nuniverse u\n\nnamespace Group\n\n@[to_additive] lemma is_zero_of_subsingleton (G : Group) [subsingleton G] :\n is_zero G :=\nbegin\n refine ⟨λ X, ⟨⟨⟨1⟩, λ f, _⟩⟩, λ X, ⟨⟨⟨1⟩, λ f, _⟩⟩⟩,\n { ext, have : x = 1 := subsingleton.elim _ _, rw [this, map_one, map_one], },\n { ext, apply subsingleton.elim }\nend\n\n@[to_additive AddGroup.has_zero_object]\ninstance : has_zero_object Group :=\n⟨⟨of punit, is_zero_of_subsingleton _⟩⟩\n\nend Group\n\nnamespace CommGroup\n\n@[to_additive] lemma is_zero_of_subsingleton (G : CommGroup) [subsingleton G] :\n is_zero G :=\nbegin\n refine ⟨λ X, ⟨⟨⟨1⟩, λ f, _⟩⟩, λ X, ⟨⟨⟨1⟩, λ f, _⟩⟩⟩,\n { ext, have : x = 1 := subsingleton.elim _ _, rw [this, map_one, map_one], },\n { ext, apply subsingleton.elim }\nend\n\n@[to_additive AddCommGroup.has_zero_object]\ninstance : has_zero_object CommGroup :=\n⟨⟨of punit, is_zero_of_subsingleton _⟩⟩\n\nend CommGroup\n", "meta": {"author": "leanprover-community", "repo": "mathlib", "sha": "5e526d18cea33550268dcbbddcb822d5cde40654", "save_path": "github-repos/lean/leanprover-community-mathlib", "path": "github-repos/lean/leanprover-community-mathlib/mathlib-5e526d18cea33550268dcbbddcb822d5cde40654/src/algebra/category/Group/zero.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.09401018913531517, "lm_q1q2_score": 0.047005094567657585}} {"text": "/-\nCopyright (c) 2021 Scott Morrison. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Scott Morrison\n-/\nimport Mathlib.Init.Data.Nat.Basic\nimport Mathlib.Init.Logic\nimport Std.Tactic.RCases\nimport Mathlib.Tactic.Constructor\nimport Mathlib.Tactic.PermuteGoals\nimport Mathlib.Tactic.SolveByElim\n\nexample (h : Nat) : Nat := by solve_by_elim\nexample {α β : Type} (f : α → β) (a : α) : β := by solve_by_elim\nexample {α β : Type} (f : α → α → β) (a : α) : β := by solve_by_elim\nexample {α β γ : Type} (f : α → β) (g : β → γ) (a : α) : γ := by solve_by_elim\nexample {α β γ : Type} (_f : α → β) (g : β → γ) (b : β) : γ := by solve_by_elim\nexample {α : Nat → Type} (f : (n : Nat) → α n → α (n+1)) (a : α 0) : α 4 := by solve_by_elim\n\nexample (h : Nat) : Nat := by solve_by_elim []\nexample {α β : Type} (f : α → β) (a : α) : β := by solve_by_elim []\nexample {α β : Type} (f : α → α → β) (a : α) : β := by solve_by_elim []\nexample {α β γ : Type} (f : α → β) (g : β → γ) (a : α) : γ := by solve_by_elim []\nexample {α β γ : Type} (_f : α → β) (g : β → γ) (b : β) : γ := by solve_by_elim []\nexample {α : Nat → Type} (f : (n : Nat) → α n → α (n+1)) (a : α 0) : α 4 := by solve_by_elim []\n\nexample {α β : Type} (f : α → β) (a : α) : β := by\n fail_if_success solve_by_elim [-f]\n fail_if_success solve_by_elim [-a]\n fail_if_success solve_by_elim only [f]\n solve_by_elim\n\nexample {α β γ : Type} (f : α → β) (g : β → γ) (b : β) : γ := by\n fail_if_success solve_by_elim [-g]\n solve_by_elim [-f]\n\nexample (h : Nat) : Nat := by solve_by_elim only [h]\nexample {α β : Type} (f : α → β) (a : α) : β := by solve_by_elim only [f, a]\nexample {α β : Type} (f : α → α → β) (a : α) : β := by solve_by_elim only [f, a]\nexample {α β γ : Type} (f : α → β) (g : β → γ) (a : α) : γ := by solve_by_elim only [f, g, a]\nexample {α β γ : Type} (_f : α → β) (g : β → γ) (b : β) : γ := by solve_by_elim only [g, b]\nexample {α : Nat → Type} (f : (n : Nat) → α n → α (n+1)) (a : α 0) : α 4 := by\n solve_by_elim only [f, a]\n\nexample (h₁ h₂ : False) : True := by\n -- 'It doesn't make sense to remove local hypotheses when using `only` without `*`.'\n fail_if_success solve_by_elim only [-h₁]\n -- 'It does make sense to use `*` without `only`.'\n fail_if_success solve_by_elim [*, -h₁]\n solve_by_elim only [*, -h₁]\n\n-- Verify that already assigned metavariables are skipped.\nexample (P₁ P₂ : α → Prop) (f : ∀ (a : α), P₁ a → P₂ a → β)\n (a : α) (ha₁ : P₁ a) (ha₂ : P₂ a) : β := by\n solve_by_elim\n\nexample {X : Type} (x : X) : x = x := by\n fail_if_success solve_by_elim only -- needs the `rfl` lemma\n solve_by_elim\n\n-- Needs to apply `rfl` twice, with different implicit arguments each time.\n-- A naive implementation of solve_by_elim would get stuck.\nexample {X : Type} (x y : X) (p : Prop) (h : x = x → y = y → p) : p := by solve_by_elim\n\nexample : True := by\n fail_if_success solve_by_elim only -- needs the `trivial` lemma\n solve_by_elim\n\n-- Requires backtracking.\nexample (P₁ P₂ : α → Prop) (f : ∀ (a: α), P₁ a → P₂ a → β)\n (a : α) (_ha₁ : P₁ a)\n (a' : α) (ha'₁ : P₁ a') (ha'₂ : P₂ a') : β := by\n fail_if_success solve_by_elim (config := .noBackTracking)\n solve_by_elim\n\nexample {α : Type} {a b : α → Prop} (h₀ : b = a) (y : α) : a y = b y :=\nby\n fail_if_success solve_by_elim (config := {symm := false})\n solve_by_elim\n\nexample (P : True → False) : 3 = 7 := by\n fail_if_success solve_by_elim (config := {exfalso := false})\n solve_by_elim\n\n-- Verifying that `solve_by_elim` acts only on the main goal.\nexample (n : ℕ) : ℕ × ℕ := by\n constructor\n solve_by_elim\n solve_by_elim\n\n-- Verifying that `solve_by_elim*` acts on all remaining goals.\nexample (n : ℕ) : ℕ × ℕ := by\n constructor\n solve_by_elim*\n\n-- Verifying that `solve_by_elim*` backtracks when given multiple goals.\nexample (n m : ℕ) (f : ℕ → ℕ → Prop) (h : f n m) : ∃ p : ℕ × ℕ, f p.1 p.2 := by\n fconstructor\n fconstructor\n solve_by_elim*\n\n-- test that metavariables created for implicit arguments don't get stuck\nexample (P : ℕ → Type) (f : {n : ℕ} → P n) : P 2 × P 3 := by\n fconstructor\n solve_by_elim* only [f]\n\nexample : 6 = 6 ∧ [7] = [7] := by\n fconstructor\n solve_by_elim* only [@rfl _]\n\n-- Test that `solve_by_elim*`, which works on multiple goals,\n-- successfully uses the relevant local hypotheses for each goal.\nexample (f g : ℕ → Prop) : (∃ k : ℕ, f k) ∨ (∃ k : ℕ, g k) ↔ ∃ k : ℕ, f k ∨ g k := by\n dsimp at *\n fconstructor\n rintro (⟨n, fn⟩ | ⟨n, gn⟩)\n pick_goal 3\n rintro ⟨n, hf | hg⟩\n solve_by_elim* (config := {maxDepth := 13}) [Or.inl, Or.inr, Exists.intro]\n\n-- Test that `Config.intros` causes `solve_by_elim` to call `intro` on intermediate goals.\nexample (P : Prop) : P → P := by\n fail_if_success solve_by_elim\n solve_by_elim (config := .intros)\n\n-- This worked in mathlib3 without the `@`, but now goes into a loop.\n-- If someone wants to diagnose this, please do!\nexample (P Q : Prop) : P ∧ Q → P ∧ Q := by\n solve_by_elim [And.imp, @id]\n\nsection apply_assumption\n\nexample {a b : Type} (h₀ : a → b) (h₁ : a) : b := by\n apply_assumption\n apply_assumption\n\nexample {α : Type} {p : α → Prop} (h₀ : ∀ x, p x) (y : α) : p y := by\n apply_assumption\n\n-- Check that `apply_assumption` uses `symm`.\nexample (a b : α) (h : b = a) : a = b := by\n fail_if_success apply_assumption (config := {symm := false})\n apply_assumption\n\n-- Check that `apply_assumption` uses `exfalso`.\nexample {P Q : Prop} (p : P) (q : Q) (h : P → ¬ Q) : ℕ := by\n fail_if_success apply_assumption (config := {exfalso := false})\n apply_assumption <;> assumption\n\nend apply_assumption\n\nsection «using»\n\n@[dummy_label_attr] axiom foo : 1 = 2\n\nexample : 1 = 2 := by\n fail_if_success solve_by_elim\n solve_by_elim using dummy_label_attr\n\nend «using»\n\nsection issue1581\n\naxiom mySorry {α} : α\n\n@[dummy_label_attr] theorem le_rfl [LE α] {b c : α} (_h : b = c) : b ≤ c := mySorry\n\nexample : 5 ≤ 7 := by\n apply_rules using dummy_label_attr\n guard_target = 5 = 7\n exact mySorry\n\nexample : 5 ≤ 7 := by\n apply_rules [le_rfl]\n guard_target = 5 = 7\n exact mySorry\n\nend issue1581\n", "meta": {"author": "leanprover-community", "repo": "mathlib4", "sha": "b9a0a30342ca06e9817e22dbe46e75fc7f435500", "save_path": "github-repos/lean/leanprover-community-mathlib4", "path": "github-repos/lean/leanprover-community-mathlib4/mathlib4-b9a0a30342ca06e9817e22dbe46e75fc7f435500/test/solve_by_elim/basic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4263215925474903, "lm_q2_score": 0.10970576732865911, "lm_q1q2_score": 0.046769937439198384}} {"text": "/-\nCopyright (c) 2018 Scott Morrison. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Scott Morrison, Johannes Hölzl, Reid Barton, Sean Leather\n-/\nimport category_theory.category\n\n/-!\n# Bundled types\n\n`bundled c` provides a uniform structure for bundling a type equipped with a type class.\n\nWe provide `category` instances for these in `category_theory/unbundled_hom.lean`\n(for categories with unbundled homs, e.g. topological spaces)\nand in `category_theory/bundled_hom.lean` (for categories with bundled homs, e.g. monoids).\n-/\n\nuniverses u v\n\nnamespace category_theory\nvariables {c d : Type u → Type v} {α : Type u}\n\n/-- `bundled` is a type bundled with a type class instance for that type. Only\nthe type class is exposed as a parameter. -/\n@[nolint has_inhabited_instance]\nstructure bundled (c : Type u → Type v) : Type (max (u+1) v) :=\n(α : Type u)\n(str : c α . tactic.apply_instance)\n\nnamespace bundled\n\n/-- A generic function for lifting a type equipped with an instance to a bundled object. -/\n-- Usually explicit instances will provide their own version of this, e.g. `Mon.of` and `Top.of`.\ndef of {c : Type u → Type v} (α : Type u) [str : c α] : bundled c := ⟨α, str⟩\n\ninstance : has_coe_to_sort (bundled c) :=\n{ S := Type u, coe := bundled.α }\n\n@[simp]\nlemma coe_mk (α) (str) : (@bundled.mk c α str : Type u) = α := rfl\n\n/-\n`bundled.map` is reducible so that, if we define a category\n\n def Ring : Type (u+1) := induced_category SemiRing (bundled.map @ring.to_semiring)\n\ninstance search is able to \"see\" that a morphism R ⟶ S in Ring is really\na (semi)ring homomorphism from R.α to S.α, and not merely from\n`(bundled.map @ring.to_semiring R).α` to `(bundled.map @ring.to_semiring S).α`.\n-/\n/-- Map over the bundled structure -/\n@[reducible] def map (f : Π {α}, c α → d α) (b : bundled c) : bundled d :=\n⟨b, f b.str⟩\n\nend bundled\n\nend category_theory\n", "meta": {"author": "JLimperg", "repo": "aesop3", "sha": "a4a116f650cc7403428e72bd2e2c4cda300fe03f", "save_path": "github-repos/lean/JLimperg-aesop3", "path": "github-repos/lean/JLimperg-aesop3/aesop3-a4a116f650cc7403428e72bd2e2c4cda300fe03f/src/category_theory/concrete_category/bundled.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167793123159, "lm_q2_score": 0.10087861394487134, "lm_q1q2_score": 0.046506733702355064}} {"text": "/-\nCopyright (c) 2020 Scott Morrison. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Gabriel Ebner, Scott Morrison\n-/\nimport tactic.core\n\n/-!\n# simp_result\n\n`dsimp_result` and `simp_result` are a pair of tactics for\napplying `dsimp` or `simp` to the result produced by other tactics.\n\nAs examples, tactics which use `revert` and `intro`\nmay insert additional `id` terms in the result they produce.\nIf there is some reason these are undesirable\n(e.g. the result term needs to be human-readable, or\nsatisfying syntactic rather than just definitional properties),\nwrapping those tactics in `dsimp_result`\ncan remove the `id` terms \"after the fact\".\n\nSimilarly, tactics using `subst` and `rw` will nearly always introduce `eq.rec` terms,\nbut sometimes these will be easy to remove,\nfor example by simplifying using `eq_rec_constant`.\nThis is a non-definitional simplification lemma,\nand so wrapping these tactics in `simp_result` will result\nin a definitionally different result.\n\nThere are several examples in the associated test file,\ndemonstrating these interactions with `revert` and `subst`.\n\nThese tactics should be used with some caution.\nYou should consider whether there is any real need for the simplification of the result,\nand whether there is a more direct way of producing the result you wanted,\nbefore relying on these tactics.\n\nBoth are implemented in terms of a generic `intercept_result` tactic,\nwhich allows you to run an arbitrary tactic and modify the returned results.\n-/\n\nnamespace tactic\n\n/--\n`intercept_result m t`\nattempts to run a tactic `t`,\nintercepts any results `t` assigns to the goals,\nand runs `m : expr → tactic expr` on each of the expressions\nbefore assigning the returned values to the original goals.\n\nBecause `intercept_result` uses `unsafe.type_context.assign` rather than `unify`,\nif the tactic `m` does something unreasonable\nyou may produce terms that don't typecheck,\npossibly with mysterious error messages.\nBe careful!\n-/\nmeta def intercept_result {α} (m : expr → tactic expr) (t : tactic α) : tactic α := do\n-- Replace the goals with copies.\ngs ← get_goals,\ngs' ← gs.mmap (λ g, infer_type g >>= mk_meta_var),\nset_goals gs',\n-- Run the tactic on the copied goals.\na ← t,\n-- Run `m` on the produced terms,\n(gs.zip gs').mmap (λ ⟨g, g'⟩, do\n g' ← instantiate_mvars g',\n g'' ← with_local_goals' gs $ m g',\n -- and assign to the original goals.\n -- (We have to use `assign` here, as `unify` and `exact` are apparently\n -- unreliable about which way they do the assignment!)\n unsafe.type_context.run $ unsafe.type_context.assign g g''),\npure a\n\n/--\n`dsimp_result t`\nattempts to run a tactic `t`,\nintercepts any results it assigns to the goals,\nand runs `dsimp` on those results\nbefore assigning the simplified values to the original goals.\n-/\nmeta def dsimp_result {α} (t : tactic α)\n (cfg : dsimp_config := { fail_if_unchanged := ff }) (no_defaults := ff)\n (attr_names : list name := []) (hs : list simp_arg_type := []) : tactic α :=\nintercept_result (λ g,\n g.dsimp cfg no_defaults attr_names hs) t\n\n/--\n`simp_result t`\nattempts to run a tactic `t`,\nintercepts any results `t` assigns to the goals,\nand runs `simp` on those results\nbefore assigning the simplified values to the original goals.\n-/\nmeta def simp_result {α} (t : tactic α)\n (cfg : simp_config := { fail_if_unchanged := ff }) (discharger : tactic unit := failed)\n (no_defaults := ff) (attr_names : list name := []) (hs : list simp_arg_type := []) : tactic α :=\nintercept_result (λ g, prod.fst <$>\n g.simp cfg discharger no_defaults attr_names hs) t\n\nnamespace interactive\nsetup_tactic_parser\n\n/--\n`dsimp_result { tac }`\nattempts to run a tactic block `tac`,\nintercepts any results the tactic block would have assigned to the goals,\nand runs `dsimp` on those results\nbefore assigning the simplified values to the original goals.\n\nYou can use the usual interactive syntax for `dsimp`, e.g.\n`dsimp_result only [a, b, c] with attr { tac }`.\n-/\nmeta def dsimp_result\n (no_defaults : parse only_flag) (hs : parse simp_arg_list)\n (attr_names : parse with_ident_list)\n (t : itactic) : itactic :=\ntactic.dsimp_result t { fail_if_unchanged := ff } no_defaults attr_names hs\n\n/--\n`simp_result { tac }`\nattempts to run a tactic block `tac`,\nintercepts any results the tactic block would have assigned to the goals,\nand runs `simp` on those results\nbefore assigning the simplified values to the original goals.\n\nYou can use the usual interactive syntax for `simp`, e.g.\n`simp_result only [a, b, c] with attr { tac }`.\n-/\nmeta def simp_result\n (no_defaults : parse only_flag) (hs : parse simp_arg_list)\n (attr_names : parse with_ident_list)\n (t : itactic) : itactic :=\ntactic.simp_result t { fail_if_unchanged := ff } failed no_defaults attr_names hs\n\n/--\n`simp_result { tac }`\nattempts to run a tactic block `tac`,\nintercepts any results the tactic block would have assigned to the goals,\nand runs `simp` on those results\nbefore assigning the simplified values to the original goals.\n\nYou can use the usual interactive syntax for `simp`, e.g.\n`simp_result only [a, b, c] with attr { tac }`.\n\n`dsimp_result { tac }` works similarly, internally using `dsimp`\n(and so only simplifiying along definitional lemmas).\n-/\nadd_tactic_doc\n{ name := \"simp_result\",\n category := doc_category.tactic,\n decl_names := [``simp_result, ``dsimp_result],\n tags := [\"simplification\"] }\n\nend interactive\nend tactic\n", "meta": {"author": "leanprover-community", "repo": "mathlib", "sha": "5e526d18cea33550268dcbbddcb822d5cde40654", "save_path": "github-repos/lean/leanprover-community-mathlib", "path": "github-repos/lean/leanprover-community-mathlib/mathlib-5e526d18cea33550268dcbbddcb822d5cde40654/src/tactic/simp_result.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.33111973962899144, "lm_q2_score": 0.1403362476923775, "lm_q1q2_score": 0.04646810179640969}} {"text": "example (α : Type) : α → α :=\nbegin\n intro a,\n exact a\nend\n\nexample (α : Type) : ∀ x : α, x = x :=\nbegin\n intro x,\n exact eq.refl x\nend\n", "meta": {"author": "Ailrun", "repo": "Theorem_Proving_in_Lean", "sha": "2eb1b5caf93c6a5a555c79e9097cf2ba5a66cf68", "save_path": "github-repos/lean/Ailrun-Theorem_Proving_in_Lean", "path": "github-repos/lean/Ailrun-Theorem_Proving_in_Lean/Theorem_Proving_in_Lean-2eb1b5caf93c6a5a555c79e9097cf2ba5a66cf68/src/ch5/ex0202.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.411110869232168, "lm_q2_score": 0.11279540330049728, "lm_q1q2_score": 0.04637141629626039}} {"text": "-- 6. Interacting with Lean\n\n/- Not all of the information in this section will be useful right away. \n Skim this section to get a sense of Lean's features, and return later, as necessary. -/\n\n#print \"========================================\"\n#print \"Section 6.1. Importing Files\"\n#print \" \"\n\nnamespace Sec_6_1 \n /- When Lean starts, it automatically imports the contents of the library init folder, \n which includes a number of fundamental definitions and constructions. If you want to \n use additional files, they need to be imported manually. \n\n The command `import foo bar.baz.blah` imports the files `foo.lean` and `bar/baz/blah.lean`,\n where the descriptions are interpreted relative to the Lean search path. \n\n One can also specify imports relative to the current directory; for example,\n `import .foo ..bar.baz` tells Lean to import `foo.lean` from the current directory \n and `bar/baz.lean` relative to the parent of the current directory. -/\n\n\n\nend Sec_6_1 \n\n#print \"========================================\"\n#print \"Section 6.2. More on Sections\"\n#print \" \"\nnamespace Sec_6_2 \n /- The `section` command makes it possible not only to group together elements of a \n theory that go together, but also to declare variables that are inserted as arguments \n to theorems and definitions, as necessary. Remember that the point of the variable \n command is to declare variables for use in theorems, as in the following example: -/\n\n section\n variables x y : ℕ\n\n def double := x + x\n #check double y\n #check double (2 * x)\n\n theorem t₁ : double (x + y) = double x + double y :=\n by simp [double]\n end\n\n /- Note that double does not have y as argument. Variables are only included in \n declarations where they are actually mentioned. -/\n\nend Sec_6_2 \n\n#print \"========================================\"\n#print \"Section 6.3. More on Namespaces\"\n#print \" \"\n /- The command `namespace foo` causes foo to be prepended to the name of each definition \n and theorem until `end foo` is encountered. The command `open foo` then creates \n temporary aliases to definitions and theorems that begin with prefix `foo`. -/\n\nnamespace Sec_6_3 \n namespace foo\n def bar : ℕ := 1\n end foo\n\n open foo\n #check bar\n #check foo.bar\nend Sec_6_3 \n\n#print \"========================================\"\n#print \"Section 6.4. Attributes\"\n#print \" \"\n\nnamespace Sec_6_4 \n\nend Sec_6_4 \n\n#print \"========================================\"\n#print \"Section 6.5. More on Implicit Arguments\"\n#print \" \"\n\nnamespace Sec_6_5 \n\nend Sec_6_5 \n\n#print \"========================================\"\n#print \"Section 6.6. Notation\"\n#print \" \"\n\nnamespace Sec_6_6 \n\nend Sec_6_6 \n\n#print \"========================================\"\n#print \"Section 6.7. Coercions\"\n#print \" \"\n\nnamespace Sec_6_7 \n\nend Sec_6_7 \n\n#print \"========================================\"\n#print \"Section 6.8. Displaying Information\"\n#print \" \"\n\nnamespace Sec_6_8 \n\nend Sec_6_8 \n\n#print \"========================================\"\n#print \"Section 6.9. Setting Options\"\n#print \" \"\n\nnamespace Sec_6_9 \n\nend Sec_6_9 \n\n#print \"========================================\"\n#print \"Section 6.10. Elaboration Hints\"\n#print \" \"\n\nnamespace Sec_6_10\n\nend Sec_6_10\n\n#print \"========================================\"\n#print \"Section 6.11. Using the Library\"\n#print \" \"\n\nnamespace Sec_6_11\n\nend Sec_6_11\n\n", "meta": {"author": "williamdemeo", "repo": "LEAN_wjd", "sha": "13826c75c06ef435166a26a72e76fe984c15bad7", "save_path": "github-repos/lean/williamdemeo-LEAN_wjd", "path": "github-repos/lean/williamdemeo-LEAN_wjd/LEAN_wjd-13826c75c06ef435166a26a72e76fe984c15bad7/theorem_proving/06-interacting_with_lean.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40356685373537454, "lm_q2_score": 0.11436852467249821, "lm_q1q2_score": 0.04615534566843666}} {"text": "/-\nTactics in Lean are handled via the *tactic monad*. \nTo write your own tactics, one needs to be familiar with the tactic monad and how it works. \n-/\n\nimport tactic.interactive\n\nopen tactic \n\nvariables (a b c : Prop) \n\n\n/- In simple terms, tactics are programs which have return type `tactic α` for some type `α`. They act on the *tactic state*. \n\nSuch programs go in between `begin ... end` blocks. \n-/\n#check tactic \n#check intro \n#check exact\n#check apply\n#check cases \n#check repeat\n#check target \n\n/-\nMonads are an abstraction to emulate imperitive programming. As seen in the following example: (I)\n-/\n\nexample : a → b → a ∧ b := \nbegin\nintros h₁ h₂, \nsplit, repeat {assumption},\nend\n\nexample : a → b → a ∧ b := \nby do eh₁ ← intro `h₁,\n eh₂ ← intro `h₂, \n split, \n repeat assumption,\n trace_state \n\ndef my_fun : list ℕ :=\ndo l ← [1,2,3],\n l ← [4,5,6],\n return (l+1)\n\nexample : a → b → a ∧ b :=\nbegin\nintros ha hb,\nexact (and.intro ha hb),\nend\n\n-- example : a → b → a ∧ b := \n-- by do eh₁ ← intro `h₁, \n-- eh₂ ← intro `h₂, \n-- e ← pure `(and.intro %%eh₁ %%eh₂),\n-- exact e\n -- exact e \n\n/-\nIn the above, `expr`. `expr` is an inductive type which reflects internal representation of Lean expressions. During execution, the virtual machine replaces constructors of `expr` with their corresponding C++ internals and uses them during execution. \n\nSince `expr` is an inductive type, we can easily write functions to reason about them. (II)\n\n* Show `expr`.\n-/\n\nmeta def identify_conj : expr → tactic bool \n| `(%%a ∧ %%b) := pure tt \n| e := pure ff \n\n\n#check @list.mmap tactic _ expr expr \n#check infer_type \n\nmeta def foo : tactic unit := \ndo ctx ← local_context,\n g ← @list.mmap tactic _ expr expr infer_type ctx,\n -- trace ctx,\n -- trace g,\n l ← g.mfilter identify_conj,\n trace l, \n triv \n\nexample (h₁ : a ∧ b) (h₂ : c → a) (h₃ : b ∧ c) : true := by do foo \n\n\n/-\nWe can also add hypotheses to the local context. (III)\n-/\n\nexample (h₁ : a) (h₂ : b) : true :=\nby do hyp₁ ← get_local `h₁, \n hyp₂ ← get_local `h₂, \n typ₁ ← infer_type hyp₁, \n typ₂ ← infer_type hyp₂,\n typ ← to_expr ``(%%typ₁ ∧ %%typ₂),\n trm ← to_expr ``(and.intro %%hyp₁ %%hyp₂),\n n ← get_unused_name `h, \n assert n typ, exact trm,\n trace_state, triv \n\n\n/- \nThe backticks: \n\n`foo is a way to refer to a name. \n\n``foo resolves foo at parse time. \n\n`( my_expr ) constructs an expression at parse time. \n\n``( my_pexpr ) constructs a pre-expression at parse time, resolves name in the current namespace of the tactic. \n\n```( my_pexpr ) constructs a pre-expression but defers name resolution to tactic runtime (`begin ... end` block of the user). \n-/\n\n", "meta": {"author": "jesse-michael-han", "repo": "hanoi-lean-2019", "sha": "a5a9f368e394d563bfcc13e3773863924505b1ce", "save_path": "github-repos/lean/jesse-michael-han-hanoi-lean-2019", "path": "github-repos/lean/jesse-michael-han-hanoi-lean-2019/hanoi-lean-2019-a5a9f368e394d563bfcc13e3773863924505b1ce/src/kody/lecture.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4378234991142019, "lm_q2_score": 0.10521053249464328, "lm_q1q2_score": 0.04606364348047316}} {"text": "/-\nCopyright (c) 2017 Mario Carneiro. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Mario Carneiro\n-/\nimport data.list.basic\n\n/-!\n# Prefixes, subfixes, infixes\n\n> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.\n> Any changes to this file require a corresponding PR to mathlib4.\n\nThis file proves properties about\n* `list.prefix`: `l₁` is a prefix of `l₂` if `l₂` starts with `l₁`.\n* `list.subfix`: `l₁` is a subfix of `l₂` if `l₂` ends with `l₁`.\n* `list.infix`: `l₁` is an infix of `l₂` if `l₁` is a prefix of some subfix of `l₂`.\n* `list.inits`: The list of prefixes of a list.\n* `list.tails`: The list of prefixes of a list.\n* `insert` on lists\n\nAll those (except `insert`) are defined in `data.list.defs`.\n\n## Notation\n\n`l₁ <+: l₂`: `l₁` is a prefix of `l₂`.\n`l₁ <:+ l₂`: `l₁` is a subfix of `l₂`.\n`l₁ <:+: l₂`: `l₁` is an infix of `l₂`.\n-/\n\nopen nat\n\nvariables {α β : Type*}\n\nnamespace list\nvariables {l l₁ l₂ l₃ : list α} {a b : α} {m n : ℕ}\n\n/-! ### prefix, suffix, infix -/\n\nsection fix\n\n@[simp] lemma prefix_append (l₁ l₂ : list α) : l₁ <+: l₁ ++ l₂ := ⟨l₂, rfl⟩\n@[simp] lemma suffix_append (l₁ l₂ : list α) : l₂ <:+ l₁ ++ l₂ := ⟨l₁, rfl⟩\n\nlemma infix_append (l₁ l₂ l₃ : list α) : l₂ <:+: l₁ ++ l₂ ++ l₃ := ⟨l₁, l₃, rfl⟩\n\n@[simp] lemma infix_append' (l₁ l₂ l₃ : list α) : l₂ <:+: l₁ ++ (l₂ ++ l₃) :=\nby rw ← list.append_assoc; apply infix_append\n\nlemma is_prefix.is_infix : l₁ <+: l₂ → l₁ <:+: l₂ := λ ⟨t, h⟩, ⟨[], t, h⟩\nlemma is_suffix.is_infix : l₁ <:+ l₂ → l₁ <:+: l₂ := λ ⟨t, h⟩, ⟨t, [], by rw [h, append_nil]⟩\n\nlemma nil_prefix (l : list α) : [] <+: l := ⟨l, rfl⟩\nlemma nil_suffix (l : list α) : [] <:+ l := ⟨l, append_nil _⟩\nlemma nil_infix (l : list α) : [] <:+: l := (nil_prefix _).is_infix\n\n@[refl] lemma prefix_refl (l : list α) : l <+: l := ⟨[], append_nil _⟩\n@[refl] lemma suffix_refl (l : list α) : l <:+ l := ⟨[], rfl⟩\n@[refl] lemma infix_refl (l : list α) : l <:+: l := (prefix_refl l).is_infix\n\nlemma prefix_rfl : l <+: l := prefix_refl _\nlemma suffix_rfl : l <:+ l := suffix_refl _\nlemma infix_rfl : l <:+: l := infix_refl _\n\n@[simp] lemma suffix_cons (a : α) : ∀ l, l <:+ a :: l := suffix_append [a]\n\nlemma prefix_concat (a : α) (l) : l <+: concat l a := by simp\n\nlemma infix_cons : l₁ <:+: l₂ → l₁ <:+: a :: l₂ := λ ⟨L₁, L₂, h⟩, ⟨a :: L₁, L₂, h ▸ rfl⟩\nlemma infix_concat : l₁ <:+: l₂ → l₁ <:+: concat l₂ a :=\nλ ⟨L₁, L₂, h⟩, ⟨L₁, concat L₂ a, by simp_rw [←h, concat_eq_append, append_assoc]⟩\n\n@[trans] lemma is_prefix.trans : ∀ {l₁ l₂ l₃ : list α}, l₁ <+: l₂ → l₂ <+: l₃ → l₁ <+: l₃\n| l ._ ._ ⟨r₁, rfl⟩ ⟨r₂, rfl⟩ := ⟨r₁ ++ r₂, (append_assoc _ _ _).symm⟩\n\n@[trans] lemma is_suffix.trans : ∀ {l₁ l₂ l₃ : list α}, l₁ <:+ l₂ → l₂ <:+ l₃ → l₁ <:+ l₃\n| l ._ ._ ⟨l₁, rfl⟩ ⟨l₂, rfl⟩ := ⟨l₂ ++ l₁, append_assoc _ _ _⟩\n\n@[trans] lemma is_infix.trans : ∀ {l₁ l₂ l₃ : list α}, l₁ <:+: l₂ → l₂ <:+: l₃ → l₁ <:+: l₃\n| l ._ ._ ⟨l₁, r₁, rfl⟩ ⟨l₂, r₂, rfl⟩ := ⟨l₂ ++ l₁, r₁ ++ r₂, by simp only [append_assoc]⟩\n\nprotected lemma is_infix.sublist : l₁ <:+: l₂ → l₁ <+ l₂ :=\nλ ⟨s, t, h⟩, by { rw [← h], exact (sublist_append_right _ _).trans (sublist_append_left _ _) }\n\nprotected lemma is_infix.subset (hl : l₁ <:+: l₂) : l₁ ⊆ l₂ :=\nhl.sublist.subset\n\nprotected lemma is_prefix.sublist (h : l₁ <+: l₂) : l₁ <+ l₂ :=\nh.is_infix.sublist\n\nprotected lemma is_prefix.subset (hl : l₁ <+: l₂) : l₁ ⊆ l₂ :=\nhl.sublist.subset\n\nprotected lemma is_suffix.sublist (h : l₁ <:+ l₂) : l₁ <+ l₂ :=\nh.is_infix.sublist\n\nprotected lemma is_suffix.subset (hl : l₁ <:+ l₂) : l₁ ⊆ l₂ :=\nhl.sublist.subset\n\n@[simp] lemma reverse_suffix : reverse l₁ <:+ reverse l₂ ↔ l₁ <+: l₂ :=\n⟨λ ⟨r, e⟩, ⟨reverse r,\n by rw [← reverse_reverse l₁, ← reverse_append, e, reverse_reverse]⟩,\n λ ⟨r, e⟩, ⟨reverse r, by rw [← reverse_append, e]⟩⟩\n\n@[simp] lemma reverse_prefix : reverse l₁ <+: reverse l₂ ↔ l₁ <:+ l₂ :=\nby rw ← reverse_suffix; simp only [reverse_reverse]\n\n@[simp] lemma reverse_infix : reverse l₁ <:+: reverse l₂ ↔ l₁ <:+: l₂ :=\n⟨λ ⟨s, t, e⟩, ⟨reverse t, reverse s,\n by rw [← reverse_reverse l₁, append_assoc,\n ← reverse_append, ← reverse_append, e, reverse_reverse]⟩,\n λ ⟨s, t, e⟩, ⟨reverse t, reverse s,\n by rw [append_assoc, ← reverse_append, ← reverse_append, e]⟩⟩\n\nalias reverse_prefix ↔ _ is_suffix.reverse\nalias reverse_suffix ↔ _ is_prefix.reverse\nalias reverse_infix ↔ _ is_infix.reverse\n\nlemma is_infix.length_le (h : l₁ <:+: l₂) : l₁.length ≤ l₂.length := h.sublist.length_le\nlemma is_prefix.length_le (h : l₁ <+: l₂) : l₁.length ≤ l₂.length := h.sublist.length_le\nlemma is_suffix.length_le (h : l₁ <:+ l₂) : l₁.length ≤ l₂.length := h.sublist.length_le\n\nlemma eq_nil_of_infix_nil (h : l <:+: []) : l = [] := eq_nil_of_sublist_nil h.sublist\n\n@[simp] lemma infix_nil_iff : l <:+: [] ↔ l = [] :=\n⟨λ h, eq_nil_of_sublist_nil h.sublist, λ h, h ▸ infix_rfl⟩\n\nalias infix_nil_iff ↔ eq_nil_of_infix_nil _\n\n@[simp] lemma prefix_nil_iff : l <+: [] ↔ l = [] :=\n⟨λ h, eq_nil_of_infix_nil h.is_infix, λ h, h ▸ prefix_rfl⟩\n\n@[simp] lemma suffix_nil_iff : l <:+ [] ↔ l = [] :=\n⟨λ h, eq_nil_of_infix_nil h.is_infix, λ h, h ▸ suffix_rfl⟩\n\nalias prefix_nil_iff ↔ eq_nil_of_prefix_nil _\nalias suffix_nil_iff ↔ eq_nil_of_suffix_nil _\n\nlemma infix_iff_prefix_suffix (l₁ l₂ : list α) : l₁ <:+: l₂ ↔ ∃ t, l₁ <+: t ∧ t <:+ l₂ :=\n⟨λ ⟨s, t, e⟩, ⟨l₁ ++ t, ⟨_, rfl⟩, by rw [← e, append_assoc]; exact ⟨_, rfl⟩⟩,\n λ ⟨._, ⟨t, rfl⟩, s, e⟩, ⟨s, t, by rw append_assoc; exact e⟩⟩\n\nlemma eq_of_infix_of_length_eq (h : l₁ <:+: l₂) : l₁.length = l₂.length → l₁ = l₂ :=\nh.sublist.eq_of_length\n\nlemma eq_of_prefix_of_length_eq (h : l₁ <+: l₂) : l₁.length = l₂.length → l₁ = l₂ :=\nh.sublist.eq_of_length\n\nlemma eq_of_suffix_of_length_eq (h : l₁ <:+ l₂) : l₁.length = l₂.length → l₁ = l₂ :=\nh.sublist.eq_of_length\n\nlemma prefix_of_prefix_length_le : ∀ {l₁ l₂ l₃ : list α},\n l₁ <+: l₃ → l₂ <+: l₃ → length l₁ ≤ length l₂ → l₁ <+: l₂\n| [] l₂ l₃ h₁ h₂ _ := nil_prefix _\n| (a :: l₁) (b :: l₂) _ ⟨r₁, rfl⟩ ⟨r₂, e⟩ ll := begin\n injection e with _ e', subst b,\n rcases prefix_of_prefix_length_le ⟨_, rfl⟩ ⟨_, e'⟩\n (le_of_succ_le_succ ll) with ⟨r₃, rfl⟩,\n exact ⟨r₃, rfl⟩\nend\n\nlemma prefix_or_prefix_of_prefix (h₁ : l₁ <+: l₃) (h₂ : l₂ <+: l₃) : l₁ <+: l₂ ∨ l₂ <+: l₁ :=\n(le_total (length l₁) (length l₂)).imp\n (prefix_of_prefix_length_le h₁ h₂)\n (prefix_of_prefix_length_le h₂ h₁)\n\nlemma suffix_of_suffix_length_le (h₁ : l₁ <:+ l₃) (h₂ : l₂ <:+ l₃) (ll : length l₁ ≤ length l₂) :\n l₁ <:+ l₂ :=\nreverse_prefix.1 $ prefix_of_prefix_length_le\n (reverse_prefix.2 h₁) (reverse_prefix.2 h₂) (by simp [ll])\n\nlemma suffix_or_suffix_of_suffix (h₁ : l₁ <:+ l₃) (h₂ : l₂ <:+ l₃) : l₁ <:+ l₂ ∨ l₂ <:+ l₁ :=\n(prefix_or_prefix_of_prefix (reverse_prefix.2 h₁) (reverse_prefix.2 h₂)).imp\n reverse_prefix.1 reverse_prefix.1\n\nlemma suffix_cons_iff : l₁ <:+ a :: l₂ ↔ l₁ = a :: l₂ ∨ l₁ <:+ l₂ :=\nbegin\n split,\n { rintro ⟨⟨hd, tl⟩, hl₃⟩,\n { exact or.inl hl₃ },\n { simp only [cons_append] at hl₃,\n exact or.inr ⟨_, hl₃.2⟩ } },\n { rintro (rfl | hl₁),\n { exact (a :: l₂).suffix_refl },\n { exact hl₁.trans (l₂.suffix_cons _) } }\nend\n\nlemma infix_cons_iff : l₁ <:+: a :: l₂ ↔ l₁ <+: a :: l₂ ∨ l₁ <:+: l₂ :=\nbegin\n split,\n { rintro ⟨⟨hd, tl⟩, t, hl₃⟩,\n { exact or.inl ⟨t, hl₃⟩ },\n { simp only [cons_append] at hl₃,\n exact or.inr ⟨_, t, hl₃.2⟩ } },\n { rintro (h | hl₁),\n { exact h.is_infix },\n { exact infix_cons hl₁ } }\nend\n\nlemma infix_of_mem_join : ∀ {L : list (list α)}, l ∈ L → l <:+: join L\n| (_ :: L) (or.inl rfl) := infix_append [] _ _\n| (l' :: L) (or.inr h) := is_infix.trans (infix_of_mem_join h) $ (suffix_append _ _).is_infix\n\nlemma prefix_append_right_inj (l) : l ++ l₁ <+: l ++ l₂ ↔ l₁ <+: l₂ :=\nexists_congr $ λ r, by rw [append_assoc, append_right_inj]\n\nlemma prefix_cons_inj (a) : a :: l₁ <+: a :: l₂ ↔ l₁ <+: l₂ := prefix_append_right_inj [a]\n\nlemma take_prefix (n) (l : list α) : take n l <+: l := ⟨_, take_append_drop _ _⟩\nlemma drop_suffix (n) (l : list α) : drop n l <:+ l := ⟨_, take_append_drop _ _⟩\nlemma take_sublist (n) (l : list α) : take n l <+ l := (take_prefix n l).sublist\nlemma drop_sublist (n) (l : list α) : drop n l <+ l := (drop_suffix n l).sublist\nlemma take_subset (n) (l : list α) : take n l ⊆ l := (take_sublist n l).subset\nlemma drop_subset (n) (l : list α) : drop n l ⊆ l := (drop_sublist n l).subset\nlemma mem_of_mem_take (h : a ∈ l.take n) : a ∈ l := take_subset n l h\nlemma mem_of_mem_drop (h : a ∈ l.drop n) : a ∈ l := drop_subset n l h\n\nlemma slice_sublist (n m : ℕ) (l : list α) : l.slice n m <+ l :=\nbegin\n rw list.slice_eq,\n conv_rhs {rw ←list.take_append_drop n l},\n rw [list.append_sublist_append_left, add_comm, list.drop_add],\n exact list.drop_sublist _ _,\nend\nlemma slice_subset (n m : ℕ) (l : list α) : l.slice n m ⊆ l := (slice_sublist n m l).subset\nlemma mem_of_mem_slice {n m : ℕ} {l : list α} {a : α} (h : a ∈ l.slice n m) : a ∈ l :=\nslice_subset n m l h\n\nlemma take_while_prefix (p : α → Prop) [decidable_pred p] : l.take_while p <+: l :=\n⟨l.drop_while p, take_while_append_drop p l⟩\n\nlemma drop_while_suffix (p : α → Prop) [decidable_pred p] : l.drop_while p <:+ l :=\n⟨l.take_while p, take_while_append_drop p l⟩\n\nlemma init_prefix : ∀ (l : list α), l.init <+: l\n| [] := ⟨nil, by rw [init, list.append_nil]⟩\n| (a :: l) := ⟨_, init_append_last (cons_ne_nil a l)⟩\n\nlemma tail_suffix (l : list α) : tail l <:+ l := by rw ← drop_one; apply drop_suffix\n\nlemma init_sublist (l : list α) : l.init <+ l := (init_prefix l).sublist\n\n\nlemma prefix_iff_eq_append : l₁ <+: l₂ ↔ l₁ ++ drop (length l₁) l₂ = l₂ :=\n⟨by rintros ⟨r, rfl⟩; rw drop_left, λ e, ⟨_, e⟩⟩\n\nlemma suffix_iff_eq_append : l₁ <:+ l₂ ↔ take (length l₂ - length l₁) l₂ ++ l₁ = l₂ :=\n⟨by rintros ⟨r, rfl⟩; simp only [length_append, add_tsub_cancel_right, take_left], λ e, ⟨_, e⟩⟩\n\nlemma prefix_iff_eq_take : l₁ <+: l₂ ↔ l₁ = take (length l₁) l₂ :=\n⟨λ h, append_right_cancel $\n (prefix_iff_eq_append.1 h).trans (take_append_drop _ _).symm,\n λ e, e.symm ▸ take_prefix _ _⟩\n\nlemma suffix_iff_eq_drop : l₁ <:+ l₂ ↔ l₁ = drop (length l₂ - length l₁) l₂ :=\n⟨λ h, append_left_cancel $\n (suffix_iff_eq_append.1 h).trans (take_append_drop _ _).symm,\n λ e, e.symm ▸ drop_suffix _ _⟩\n\ninstance decidable_prefix [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <+: l₂)\n| [] l₂ := is_true ⟨l₂, rfl⟩\n| (a :: l₁) [] := is_false $ λ ⟨t, te⟩, list.no_confusion te\n| (a :: l₁) (b :: l₂) :=\n if h : a = b then\n decidable_of_decidable_of_iff (decidable_prefix l₁ l₂) (by rw [← h, prefix_cons_inj])\n else\n is_false $ λ ⟨t, te⟩, h $ by injection te\n\n-- Alternatively, use mem_tails\ninstance decidable_suffix [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <:+ l₂)\n| [] l₂ := is_true ⟨l₂, append_nil _⟩\n| (a :: l₁) [] := is_false $ mt (sublist.length_le ∘ is_suffix.sublist) dec_trivial\n| l₁ (b :: l₂) := decidable_of_decidable_of_iff (@or.decidable _ _\n _ (l₁.decidable_suffix l₂)) suffix_cons_iff.symm\n\ninstance decidable_infix [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <:+: l₂)\n| [] l₂ := is_true ⟨[], l₂, rfl⟩\n| (a :: l₁) [] := is_false $ λ ⟨s, t, te⟩, by simp at te; exact te\n| l₁ (b :: l₂) := decidable_of_decidable_of_iff (@or.decidable _ _\n (l₁.decidable_prefix (b :: l₂)) (l₁.decidable_infix l₂)) infix_cons_iff.symm\n\nlemma prefix_take_le_iff {L : list (list (option α))} (hm : m < L.length) :\n L.take m <+: L.take n ↔ m ≤ n :=\nbegin\n simp only [prefix_iff_eq_take, length_take],\n induction m with m IH generalizing L n,\n { simp only [min_eq_left, eq_self_iff_true, nat.zero_le, take] },\n cases L with l ls,\n { exact (not_lt_bot hm).elim },\n cases n,\n { refine iff_of_false _ (zero_lt_succ _).not_le,\n rw [take_zero, take_nil],\n simp only [take],\n exact not_false },\n { simp only [length] at hm,\n specialize @IH ls n (nat.lt_of_succ_lt_succ hm),\n simp only [le_of_lt (nat.lt_of_succ_lt_succ hm), min_eq_left] at IH,\n simp only [le_of_lt hm, IH, true_and, min_eq_left, eq_self_iff_true, length, take],\n exact ⟨nat.succ_le_succ, nat.le_of_succ_le_succ⟩ }\nend\n\nlemma cons_prefix_iff : a :: l₁ <+: b :: l₂ ↔ a = b ∧ l₁ <+: l₂ :=\nbegin\n split,\n { rintro ⟨L, hL⟩,\n simp only [cons_append] at hL,\n exact ⟨hL.left, ⟨L, hL.right⟩⟩ },\n { rintro ⟨rfl, h⟩,\n rwa [prefix_cons_inj] }\nend\n\nlemma is_prefix.map (h : l₁ <+: l₂) (f : α → β) : l₁.map f <+: l₂.map f :=\nbegin\n induction l₁ with hd tl hl generalizing l₂,\n { simp only [nil_prefix, map_nil] },\n { cases l₂ with hd₂ tl₂,\n { simpa only using eq_nil_of_prefix_nil h },\n { rw cons_prefix_iff at h,\n simp only [h, prefix_cons_inj, hl, map] } }\nend\n\nlemma is_prefix.filter_map (h : l₁ <+: l₂) (f : α → option β) :\n l₁.filter_map f <+: l₂.filter_map f :=\nbegin\n induction l₁ with hd₁ tl₁ hl generalizing l₂,\n { simp only [nil_prefix, filter_map_nil] },\n { cases l₂ with hd₂ tl₂,\n { simpa only using eq_nil_of_prefix_nil h },\n { rw cons_prefix_iff at h,\n rw [←@singleton_append _ hd₁ _, ←@singleton_append _ hd₂ _, filter_map_append,\n filter_map_append, h.left, prefix_append_right_inj],\n exact hl h.right } }\nend\n\nlemma is_prefix.reduce_option {l₁ l₂ : list (option α)} (h : l₁ <+: l₂) :\n l₁.reduce_option <+: l₂.reduce_option :=\nh.filter_map id\n\nlemma is_prefix.filter (p : α → Prop) [decidable_pred p] ⦃l₁ l₂ : list α⦄ (h : l₁ <+: l₂) :\n l₁.filter p <+: l₂.filter p :=\nbegin\n obtain ⟨xs, rfl⟩ := h,\n rw filter_append,\n exact prefix_append _ _\nend\n\nlemma is_suffix.filter (p : α → Prop) [decidable_pred p] ⦃l₁ l₂ : list α⦄ (h : l₁ <:+ l₂) :\n l₁.filter p <:+ l₂.filter p :=\nbegin\n obtain ⟨xs, rfl⟩ := h,\n rw filter_append,\n exact suffix_append _ _\nend\n\nlemma is_infix.filter (p : α → Prop) [decidable_pred p] ⦃l₁ l₂ : list α⦄ (h : l₁ <:+: l₂) :\n l₁.filter p <:+: l₂.filter p :=\nbegin\n obtain ⟨xs, ys, rfl⟩ := h,\n rw [filter_append, filter_append],\n exact infix_append _ _ _\nend\n\ninstance : is_partial_order (list α) (<+:) :=\n{ refl := prefix_refl,\n trans := λ _ _ _, is_prefix.trans,\n antisymm := λ _ _ h₁ h₂, eq_of_prefix_of_length_eq h₁ $ h₁.length_le.antisymm h₂.length_le }\n\ninstance : is_partial_order (list α) (<:+) :=\n{ refl := suffix_refl,\n trans := λ _ _ _, is_suffix.trans,\n antisymm := λ _ _ h₁ h₂, eq_of_suffix_of_length_eq h₁ $ h₁.length_le.antisymm h₂.length_le }\n\ninstance : is_partial_order (list α) (<:+:) :=\n{ refl := infix_refl,\n trans := λ _ _ _, is_infix.trans,\n antisymm := λ _ _ h₁ h₂, eq_of_infix_of_length_eq h₁ $ h₁.length_le.antisymm h₂.length_le }\n\nend fix\n\nsection inits_tails\n\n@[simp] lemma mem_inits : ∀ (s t : list α), s ∈ inits t ↔ s <+: t\n| s [] := suffices s = nil ↔ s <+: nil, by simpa only [inits, mem_singleton],\n ⟨λ h, h.symm ▸ prefix_refl [], eq_nil_of_prefix_nil⟩\n| s (a :: t) :=\n suffices (s = nil ∨ ∃ l ∈ inits t, a :: l = s) ↔ s <+: a :: t, by simpa,\n ⟨λ o, match s, o with\n | ._, or.inl rfl := ⟨_, rfl⟩\n | s, or.inr ⟨r, hr, hs⟩ := let ⟨s, ht⟩ := (mem_inits _ _).1 hr in\n by rw [← hs, ← ht]; exact ⟨s, rfl⟩\n end, λ mi, match s, mi with\n | [], ⟨._, rfl⟩ := or.inl rfl\n | (b :: s), ⟨r, hr⟩ := list.no_confusion hr $ λ ba (st : s++r = t), or.inr $\n by rw ba; exact ⟨_, (mem_inits _ _).2 ⟨_, st⟩, rfl⟩\n end⟩\n\n@[simp] lemma mem_tails : ∀ (s t : list α), s ∈ tails t ↔ s <:+ t\n| s [] := by simp only [tails, mem_singleton];\n exact ⟨λ h, by rw h; exact suffix_refl [], eq_nil_of_suffix_nil⟩\n| s (a :: t) := by simp only [tails, mem_cons_iff, mem_tails s t];\n exact show s = a :: t ∨ s <:+ t ↔ s <:+ a :: t, from\n ⟨λ o, match s, t, o with\n | ._, t, or.inl rfl := suffix_rfl\n | s, ._, or.inr ⟨l, rfl⟩ := ⟨a :: l, rfl⟩\n end, λ e, match s, t, e with\n | ._, t, ⟨[], rfl⟩ := or.inl rfl\n | s, t, ⟨b :: l, he⟩ := list.no_confusion he (λ ab lt, or.inr ⟨l, lt⟩)\n end⟩\n\nlemma inits_cons (a : α) (l : list α) : inits (a :: l) = [] :: l.inits.map (λ t, a :: t) := by simp\nlemma tails_cons (a : α) (l : list α) : tails (a :: l) = (a :: l) :: l.tails := by simp\n\n@[simp]\nlemma inits_append : ∀ (s t : list α), inits (s ++ t) = s.inits ++ t.inits.tail.map (λ l, s ++ l)\n| [] [] := by simp\n| [] (a :: t) := by simp\n| (a :: s) t := by simp [inits_append s t]\n\n@[simp]\nlemma tails_append : ∀ (s t : list α), tails (s ++ t) = s.tails.map (λ l, l ++ t) ++ t.tails.tail\n| [] [] := by simp\n| [] (a :: t) := by simp\n| (a :: s) t := by simp [tails_append s t]\n\n-- the lemma names `inits_eq_tails` and `tails_eq_inits` are like `sublists_eq_sublists'`\nlemma inits_eq_tails : ∀ (l : list α), l.inits = (reverse $ map reverse $ tails $ reverse l)\n| [] := by simp\n| (a :: l) := by simp [inits_eq_tails l, map_eq_map_iff]\n\nlemma tails_eq_inits : ∀ (l : list α), l.tails = (reverse $ map reverse $ inits $ reverse l)\n| [] := by simp\n| (a :: l) := by simp [tails_eq_inits l, append_left_inj]\n\nlemma inits_reverse (l : list α) : inits (reverse l) = reverse (map reverse l.tails) :=\nby { rw tails_eq_inits l, simp [reverse_involutive.comp_self] }\n\nlemma tails_reverse (l : list α) : tails (reverse l) = reverse (map reverse l.inits) :=\nby { rw inits_eq_tails l, simp [reverse_involutive.comp_self] }\n\nlemma map_reverse_inits (l : list α) : map reverse l.inits = (reverse $ tails $ reverse l) :=\nby { rw inits_eq_tails l, simp [reverse_involutive.comp_self] }\n\nlemma map_reverse_tails (l : list α) : map reverse l.tails = (reverse $ inits $ reverse l) :=\nby { rw tails_eq_inits l, simp [reverse_involutive.comp_self] }\n\n@[simp] lemma length_tails (l : list α) : length (tails l) = length l + 1 :=\nbegin\n induction l with x l IH,\n { simp },\n { simpa using IH }\nend\n\n@[simp] lemma length_inits (l : list α) : length (inits l) = length l + 1 :=\nby simp [inits_eq_tails]\n\n@[simp] lemma nth_le_tails (l : list α) (n : ℕ) (hn : n < length (tails l)) :\n nth_le (tails l) n hn = l.drop n :=\nbegin\n induction l with x l IH generalizing n,\n { simp },\n { cases n,\n { simp },\n { simpa using IH n _ } }\nend\n\n@[simp] lemma nth_le_inits (l : list α) (n : ℕ) (hn : n < length (inits l)) :\n nth_le (inits l) n hn = l.take n :=\nbegin\n induction l with x l IH generalizing n,\n { simp },\n { cases n,\n { simp },\n { simpa using IH n _ } }\nend\n\nend inits_tails\n\n/-! ### insert -/\n\nsection insert\nvariable [decidable_eq α]\n\n@[simp] lemma insert_nil (a : α) : insert a nil = [a] := rfl\n\nlemma insert.def (a : α) (l : list α) : insert a l = if a ∈ l then l else a :: l := rfl\n\n@[simp, priority 980]\nlemma insert_of_mem (h : a ∈ l) : insert a l = l := by simp only [insert.def, if_pos h]\n\n@[simp, priority 970]\nlemma insert_of_not_mem (h : a ∉ l) : insert a l = a :: l :=\nby simp only [insert.def, if_neg h]; split; refl\n\n@[simp] lemma mem_insert_iff : a ∈ insert b l ↔ a = b ∨ a ∈ l :=\nbegin\n by_cases h' : b ∈ l,\n { simp only [insert_of_mem h'],\n apply (or_iff_right_of_imp _).symm,\n exact λ e, e.symm ▸ h' },\n { simp only [insert_of_not_mem h', mem_cons_iff] }\nend\n\n@[simp] lemma suffix_insert (a : α) (l : list α) : l <:+ insert a l :=\nby by_cases a ∈ l; [simp only [insert_of_mem h], simp only [insert_of_not_mem h, suffix_cons]]\n\nlemma infix_insert (a : α) (l : list α) : l <:+: insert a l := (suffix_insert a l).is_infix\nlemma sublist_insert (a : α) (l : list α) : l <+ l.insert a := (suffix_insert a l).sublist\nlemma subset_insert (a : α) (l : list α) : l ⊆ l.insert a := (sublist_insert a l).subset\n\n@[simp] lemma mem_insert_self (a : α) (l : list α) : a ∈ l.insert a :=\nmem_insert_iff.2 $ or.inl rfl\n\nlemma mem_insert_of_mem (h : a ∈ l) : a ∈ insert b l := mem_insert_iff.2 (or.inr h)\n\nlemma eq_or_mem_of_mem_insert (h : a ∈ insert b l) : a = b ∨ a ∈ l := mem_insert_iff.1 h\n\n@[simp] lemma length_insert_of_mem (h : a ∈ l) : (insert a l).length = l.length :=\ncongr_arg _ $ insert_of_mem h\n\n@[simp] lemma length_insert_of_not_mem (h : a ∉ l) : (insert a l).length = l.length + 1 :=\ncongr_arg _ $ insert_of_not_mem h\n\nend insert\n\nlemma mem_of_mem_suffix (hx : a ∈ l₁) (hl : l₁ <:+ l₂) : a ∈ l₂ :=\nhl.subset hx\n\nend list\n", "meta": {"author": "leanprover-community", "repo": "mathlib", "sha": "5e526d18cea33550268dcbbddcb822d5cde40654", "save_path": "github-repos/lean/leanprover-community-mathlib", "path": "github-repos/lean/leanprover-community-mathlib/mathlib-5e526d18cea33550268dcbbddcb822d5cde40654/src/data/list/infix.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.09401018723156651, "lm_q1q2_score": 0.04590361341382642}} {"text": "/-\nCopyright (c) 2017 Mario Carneiro. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Mario Carneiro, Yury Kudryashov, Floris van Doorn\n-/\nimport tactic.transform_decl\nimport tactic.algebra\n\n/-!\n# Transport multiplicative to additive\n\nThis file defines an attribute `to_additive` that can be used to\nautomatically transport theorems and definitions (but not inductive\ntypes and structures) from a multiplicative theory to an additive theory.\n\nUsage information is contained in the doc string of `to_additive.attr`.\n\n### Missing features\n\n* Automatically transport structures and other inductive types.\n\n* For structures, automatically generate theorems like `group α ↔\n add_group (additive α)`.\n-/\n\nnamespace to_additive\nopen tactic\nsetup_tactic_parser\n\nsection performance_hack -- see Note [user attribute parameters]\n\nlocal attribute [semireducible] reflected\n\n/-- Temporarily change the `has_reflect` instance for `name`. -/\nlocal attribute [instance, priority 9000]\nmeta def hacky_name_reflect : has_reflect name :=\nλ n, `(id %%(expr.const n []) : name)\n\n/-- An auxiliary attribute used to store the names of the additive versions of declarations\nthat have been processed by `to_additive`. -/\n@[user_attribute]\nmeta def aux_attr : user_attribute (name_map name) name :=\n{ name := `to_additive_aux,\n descr := \"Auxiliary attribute for `to_additive`. DON'T USE IT\",\n parser := failed,\n cache_cfg := ⟨λ ns,\n ns.mfoldl\n (λ dict n', do\n let n := match n' with\n | name.mk_string s pre := if s = \"_to_additive\" then pre else n'\n | _ := n'\n end,\n param ← aux_attr.get_param_untyped n',\n pure $ dict.insert n param.app_arg.const_name)\n mk_name_map, []⟩ }\n\nend performance_hack\n\nsection extra_attributes\n\n/--\nAn attribute that tells `@[to_additive]` that certain arguments of this definition are not\ninvolved when using `@[to_additive]`.\nThis helps the heuristic of `@[to_additive]` by also transforming definitions if `ℕ` or another\nfixed type occurs as one of these arguments.\n-/\n@[user_attribute]\nmeta def ignore_args_attr : user_attribute (name_map $ list ℕ) (list ℕ) :=\n{ name := `to_additive_ignore_args,\n descr :=\n \"Auxiliary attribute for `to_additive` stating that certain arguments are not additivized.\",\n cache_cfg :=\n ⟨λ ns, ns.mfoldl\n (λ dict n, do\n param ← ignore_args_attr.get_param_untyped n, -- see Note [user attribute parameters]\n return $ dict.insert n (param.to_list expr.to_nat).iget)\n mk_name_map, []⟩,\n parser := (lean.parser.small_nat)* }\n\n/--\nAn attribute that is automatically added to declarations tagged with `@[to_additive]`, if needed.\n\nThis attribute tells which argument is the type where this declaration uses the multiplicative\nstructure. If there are multiple argument, we typically tag the first one.\nIf this argument contains a fixed type, this declaration will note be additivized.\nSee the Heuristics section of `to_additive.attr` for more details.\n\nIf a declaration is not tagged, it is presumed that the first argument is relevant.\n`@[to_additive]` uses the function `to_additive.first_multiplicative_arg` to automatically tag\ndeclarations. It is ok to update it manually if the automatic tagging made an error.\n\nImplementation note: we only allow exactly 1 relevant argument, even though some declarations\n(like `prod.group`) have multiple arguments with a multiplicative structure on it.\nThe reason is that whether we additivize a declaration is an all-or-nothing decision, and if\nwe will not be able to additivize declarations that (e.g.) talk about multiplication on `ℕ × α`\nanyway.\n\nWarning: adding `@[to_additive_reorder]` with an equal or smaller number than the number in this\nattribute is currently not supported.\n-/\n@[user_attribute]\nmeta def relevant_arg_attr : user_attribute (name_map ℕ) ℕ :=\n{ name := `to_additive_relevant_arg,\n descr :=\n \"Auxiliary attribute for `to_additive` stating which arguments are the types with a \" ++\n \"multiplicative structure.\",\n cache_cfg :=\n ⟨λ ns, ns.mfoldl\n (λ dict n, do\n param ← relevant_arg_attr.get_param_untyped n, -- see Note [user attribute parameters]\n -- we subtract 1 from the values provided by the user.\n return $ dict.insert n $ param.to_nat.iget.pred)\n mk_name_map, []⟩,\n parser := lean.parser.small_nat }\n\n/--\nAn attribute that stores all the declarations that needs their arguments reordered when\napplying `@[to_additive]`. Currently, we only support swapping consecutive arguments.\nThe list of the natural numbers contains the positions of the first of the two arguments\nto be swapped.\nIf the first two arguments are swapped, the first two universe variables are also swapped.\nExample: `@[to_additive_reorder 1 4]` swaps the first two arguments and the arguments in\npositions 4 and 5.\n-/\n@[user_attribute]\nmeta def reorder_attr : user_attribute (name_map $ list ℕ) (list ℕ) :=\n{ name := `to_additive_reorder,\n descr :=\n \"Auxiliary attribute for `to_additive` that stores arguments that need to be reordered.\",\n cache_cfg :=\n ⟨λ ns, ns.mfoldl\n (λ dict n, do\n param ← reorder_attr.get_param_untyped n, -- see Note [user attribute parameters]\n return $ dict.insert n (param.to_list expr.to_nat).iget)\n mk_name_map, []⟩,\n parser := do\n l ← (lean.parser.small_nat)*,\n guard (l.all (≠ 0)) <|> exceptional.fail \"The reorder positions must be positive\",\n return l }\n\nend extra_attributes\n\n/--\nFind the first argument of `nm` that has a multiplicative type-class on it.\nReturns 1 if there are no types with a multiplicative class as arguments.\nE.g. `prod.group` returns 1, and `pi.has_one` returns 2.\n-/\nmeta def first_multiplicative_arg (nm : name) : tactic ℕ := do\n d ← get_decl nm,\n let (es, _) := d.type.pi_binders,\n l ← es.mmap_with_index $ λ n bi, do\n { let tgt := bi.type.pi_codomain,\n let n_bi := bi.type.pi_binders.fst.length,\n tt ← has_attribute' `to_additive tgt.get_app_fn.const_name | return none,\n let n2 := tgt.get_app_args.head.get_app_fn.match_var.map $ λ m, n + n_bi - m,\n return $ n2 },\n let l := l.reduce_option,\n return $ if l = [] then 1 else l.foldr min l.head\n\n/-- A command that can be used to have future uses of `to_additive` change the `src` namespace\nto the `tgt` namespace.\n\nFor example:\n```\nrun_cmd to_additive.map_namespace `quotient_group `quotient_add_group\n```\n\nLater uses of `to_additive` on declarations in the `quotient_group` namespace will be created\nin the `quotient_add_group` namespaces.\n-/\nmeta def map_namespace (src tgt : name) : command :=\ndo let n := src.mk_string \"_to_additive\",\n let decl := declaration.thm n [] `(unit) (pure (reflect ())),\n add_decl decl,\n aux_attr.set n tgt tt\n\n/-- `value_type` is the type of the arguments that can be provided to `to_additive`.\n`to_additive.parser` parses the provided arguments:\n* `replace_all`: replace all multiplicative declarations, do not use the heuristic.\n* `trace`: output the generated additive declaration.\n* `tgt : name`: the name of the target (the additive declaration).\n* `doc`: an optional doc string.\n* if `allow_auto_name` is `ff` (default) then `@[to_additive]` will check whether the given name\n can be auto-generated.\n-/\n@[derive has_reflect, derive inhabited]\nstructure value_type : Type :=\n(replace_all : bool)\n(trace : bool)\n(tgt : name)\n(doc : option string)\n(allow_auto_name : bool)\n\n/-- `add_comm_prefix x s` returns `\"comm_\" ++ s` if `x = tt` and `s` otherwise. -/\nmeta def add_comm_prefix : bool → string → string\n| tt s := \"comm_\" ++ s\n| ff s := s\n\n/-- Dictionary used by `to_additive.guess_name` to autogenerate names. -/\nmeta def tr : bool → list string → list string\n| is_comm (\"one\" :: \"le\" :: s) := add_comm_prefix is_comm \"nonneg\" :: tr ff s\n| is_comm (\"one\" :: \"lt\" :: s) := add_comm_prefix is_comm \"pos\" :: tr ff s\n| is_comm (\"le\" :: \"one\" :: s) := add_comm_prefix is_comm \"nonpos\" :: tr ff s\n| is_comm (\"lt\" :: \"one\" :: s) := add_comm_prefix is_comm \"neg\" :: tr ff s\n| is_comm (\"mul\" :: \"support\" :: s) := add_comm_prefix is_comm \"support\" :: tr ff s\n| is_comm (\"mul\" :: \"indicator\" :: s) := add_comm_prefix is_comm \"indicator\" :: tr ff s\n| is_comm (\"mul\" :: s) := add_comm_prefix is_comm \"add\" :: tr ff s\n| is_comm (\"smul\" :: s) := add_comm_prefix is_comm \"vadd\" :: tr ff s\n| is_comm (\"inv\" :: s) := add_comm_prefix is_comm \"neg\" :: tr ff s\n| is_comm (\"div\" :: s) := add_comm_prefix is_comm \"sub\" :: tr ff s\n| is_comm (\"one\" :: s) := add_comm_prefix is_comm \"zero\" :: tr ff s\n| is_comm (\"prod\" :: s) := add_comm_prefix is_comm \"sum\" :: tr ff s\n| is_comm (\"finprod\" :: s) := add_comm_prefix is_comm \"finsum\" :: tr ff s\n| is_comm (\"npow\" :: s) := add_comm_prefix is_comm \"nsmul\" :: tr ff s\n| is_comm (\"zpow\" :: s) := add_comm_prefix is_comm \"zsmul\" :: tr ff s\n| is_comm (\"monoid\" :: s) := (\"add_\" ++ add_comm_prefix is_comm \"monoid\") :: tr ff s\n| is_comm (\"submonoid\" :: s) := (\"add_\" ++ add_comm_prefix is_comm \"submonoid\") :: tr ff s\n| is_comm (\"group\" :: s) := (\"add_\" ++ add_comm_prefix is_comm \"group\") :: tr ff s\n| is_comm (\"subgroup\" :: s) := (\"add_\" ++ add_comm_prefix is_comm \"subgroup\") :: tr ff s\n| is_comm (\"semigroup\" :: s) := (\"add_\" ++ add_comm_prefix is_comm \"semigroup\") :: tr ff s\n| is_comm (\"magma\" :: s) := (\"add_\" ++ add_comm_prefix is_comm \"magma\") :: tr ff s\n| is_comm (\"haar\" :: s) := (\"add_\" ++ add_comm_prefix is_comm \"haar\") :: tr ff s\n| is_comm (\"prehaar\" :: s) := (\"add_\" ++ add_comm_prefix is_comm \"prehaar\") :: tr ff s\n| is_comm (\"comm\" :: s) := tr tt s\n| is_comm (x :: s) := (add_comm_prefix is_comm x :: tr ff s)\n| tt [] := [\"comm\"]\n| ff [] := []\n\n/-- Autogenerate target name for `to_additive`. -/\nmeta def guess_name : string → string :=\nstring.map_tokens ''' $\nλ s, string.intercalate (string.singleton '_') $\ntr ff (s.split_on '_')\n\n/-- Return the provided target name or autogenerate one if one was not provided. -/\nmeta def target_name (src tgt : name) (dict : name_map name) (allow_auto_name : bool) :\n tactic name :=\n(if tgt.get_prefix ≠ name.anonymous ∨ allow_auto_name -- `tgt` is a full name\n then pure tgt\n else match src with\n | (name.mk_string s pre) :=\n do let tgt_auto := guess_name s,\n guard (tgt.to_string ≠ tgt_auto ∨ tgt = src)\n <|> trace (\"`to_additive \" ++ src.to_string ++ \"`: correctly autogenerated target \" ++\n \"name, you may remove the explicit \" ++ tgt_auto ++ \" argument.\"),\n pure $ name.mk_string\n (if tgt = name.anonymous then tgt_auto else tgt.to_string)\n (pre.map_prefix dict.find)\n | _ := fail (\"to_additive: can't transport \" ++ src.to_string)\n end) >>=\n(λ res,\n if res = src ∧ tgt ≠ src\n then fail (\"to_additive: can't transport \" ++ src.to_string ++ \" to itself.\nGive the desired additive name explicitly using `@[to_additive additive_name]`. \")\n else pure res)\n\n/-- the parser for the arguments to `to_additive`. -/\nmeta def parser : lean.parser value_type :=\ndo\n bang ← option.is_some <$> (tk \"!\")?,\n ques ← option.is_some <$> (tk \"?\")?,\n tgt ← ident?,\n e ← texpr?,\n doc ← match e with\n | some pe := some <$> ((to_expr pe >>= eval_expr string) : tactic string)\n | none := pure none\n end,\n return ⟨bang, ques, tgt.get_or_else name.anonymous, doc, ff⟩\n\nprivate meta def proceed_fields_aux (src tgt : name) (prio : ℕ) (f : name → tactic (list string)) :\n command :=\ndo\n src_fields ← f src,\n tgt_fields ← f tgt,\n guard (src_fields.length = tgt_fields.length) <|>\n fail (\"Failed to map fields of \" ++ src.to_string),\n (src_fields.zip tgt_fields).mmap' $\n λ names, guard (names.fst = names.snd) <|>\n aux_attr.set (src.append names.fst) (tgt.append names.snd) tt prio\n\n/-- Add the `aux_attr` attribute to the structure fields of `src`\nso that future uses of `to_additive` will map them to the corresponding `tgt` fields. -/\nmeta def proceed_fields (env : environment) (src tgt : name) (prio : ℕ) : command :=\nlet aux := proceed_fields_aux src tgt prio in\ndo\naux (λ n, pure $ list.map name.to_string $ (env.structure_fields n).get_or_else []) >>\naux (λ n, (list.map (λ (x : name), \"to_\" ++ x.to_string) <$> get_tagged_ancestors n)) >>\naux (λ n, (env.constructors_of n).mmap $\n λ cs, match cs with\n | (name.mk_string s pre) :=\n (guard (pre = n) <|> fail \"Bad constructor name\") >>\n pure s\n | _ := fail \"Bad constructor name\"\n end)\n\n/--\nThe attribute `to_additive` can be used to automatically transport theorems\nand definitions (but not inductive types and structures) from a multiplicative\ntheory to an additive theory.\n\nTo use this attribute, just write:\n\n```\n@[to_additive]\ntheorem mul_comm' {α} [comm_semigroup α] (x y : α) : x * y = y * x := comm_semigroup.mul_comm\n```\n\nThis code will generate a theorem named `add_comm'`. It is also\npossible to manually specify the name of the new declaration, and\nprovide a documentation string:\n\n```\n@[to_additive add_foo \"add_foo doc string\"]\n/-- foo doc string -/\ntheorem foo := sorry\n```\n\nThe transport tries to do the right thing in most cases using several\nheuristics described below. However, in some cases it fails, and\nrequires manual intervention.\n\nIf the declaration to be transported has attributes which need to be\ncopied to the additive version, then `to_additive` should come last:\n\n```\n@[simp, to_additive] lemma mul_one' {G : Type*} [group G] (x : G) : x * 1 = x := mul_one x\n```\n\nThe following attributes are supported and should be applied correctly by `to_additive` to\nthe new additivized declaration, if they were present on the original one:\n```\nreducible, _refl_lemma, simp, norm_cast, instance, refl, symm, trans, elab_as_eliminator, no_rsimp,\ncontinuity, ext, ematch, measurability, alias, _ext_core, _ext_lemma_core, nolint\n```\n\nThe exception to this rule is the `simps` attribute, which should come after `to_additive`:\n\n```\n@[to_additive, simps]\ninstance {M N} [has_mul M] [has_mul N] : has_mul (M × N) := ⟨λ p q, ⟨p.1 * q.1, p.2 * q.2⟩⟩\n```\n\nAdditionally the `mono` attribute is not handled by `to_additive` and should be applied afterwards\nto both the original and additivized lemma.\n\n## Implementation notes\n\nThe transport process generally works by taking all the names of\nidentifiers appearing in the name, type, and body of a declaration and\ncreating a new declaration by mapping those names to additive versions\nusing a simple string-based dictionary and also using all declarations\nthat have previously been labeled with `to_additive`.\n\nIn the `mul_comm'` example above, `to_additive` maps:\n* `mul_comm'` to `add_comm'`,\n* `comm_semigroup` to `add_comm_semigroup`,\n* `x * y` to `x + y` and `y * x` to `y + x`, and\n* `comm_semigroup.mul_comm'` to `add_comm_semigroup.add_comm'`.\n\n### Heuristics\n\n`to_additive` uses heuristics to determine whether a particular identifier has to be\nmapped to its additive version. The basic heuristic is\n\n* Only map an identifier to its additive version if its first argument doesn't\n contain any unapplied identifiers.\n\nExamples:\n* `@has_mul.mul ℕ n m` (i.e. `(n * m : ℕ)`) will not change to `+`, since its\n first argument is `ℕ`, an identifier not applied to any arguments.\n* `@has_mul.mul (α × β) x y` will change to `+`. It's first argument contains only the identifier\n `prod`, but this is applied to arguments, `α` and `β`.\n* `@has_mul.mul (α × ℤ) x y` will not change to `+`, since its first argument contains `ℤ`.\n\nThe reasoning behind the heuristic is that the first argument is the type which is \"additivized\",\nand this usually doesn't make sense if this is on a fixed type.\n\nThere are some exceptions to this heuristic:\n\n* Identifiers that have the `@[to_additive]` attribute are ignored.\n For example, multiplication in `↥Semigroup` is replaced by addition in `↥AddSemigroup`.\n* If an identifier `d` has attribute `@[to_additive_relevant_arg n]` then the argument\n in position `n` is checked for a fixed type, instead of checking the first argument.\n `@[to_additive]` will automatically add the attribute `@[to_additive_relevant_arg n]` to a\n declaration when the first argument has no multiplicative type-class, but argument `n` does.\n* If an identifier has attribute `@[to_additive_ignore_args n1 n2 ...]` then all the arguments in\n positions `n1`, `n2`, ... will not be checked for unapplied identifiers (start counting from 1).\n For example, `times_cont_mdiff_map` has attribute `@[to_additive_ignore_args 21]`, which means\n that its 21st argument `(n : with_top ℕ)` can contain `ℕ`\n (usually in the form `has_top.top ℕ ...`) and still be additivized.\n So `@has_mul.mul (C^∞⟮I, N; I', G⟯) _ f g` will be additivized.\n\n### Troubleshooting\n\nIf `@[to_additive]` fails because the additive declaration raises a type mismatch, there are\nvarious things you can try.\nThe first thing to do is to figure out what `@[to_additive]` did wrong by looking at the type\nmismatch error.\n\n* Option 1: It additivized a declaration `d` that should remain multiplicative. Solution:\n * Make sure the first argument of `d` is a type with a multiplicative structure. If not, can you\n reorder the (implicit) arguments of `d` so that the first argument becomes a type with a\n multiplicative structure (and not some indexing type)?\n The reason is that `@[to_additive]` doesn't additivize declarations if their first argument\n contains fixed types like `ℕ` or `ℝ`. See section Heuristics.\n If the first argument is not the argument with a multiplicative type-class, `@[to_additive]`\n should have automatically added the attribute `@[to_additive_relevant_arg]` to the declaration.\n You can test this by running the following (where `d` is the full name of the declaration):\n ```\n run_cmd to_additive.relevant_arg_attr.get_param `d >>= tactic.trace\n ```\n The expected output is `n` where the `n`-th argument of `d` is a type (family) with a\n multiplicative structure on it. If you get a different output (or a failure), you could add\n the attribute `@[to_additive_relevant_arg n]` manually, where `n` is an argument with a\n multiplicative structure.\n* Option 2: It didn't additivize a declaration that should be additivized.\n This happened because the heuristic applied, and the first argument contains a fixed type,\n like `ℕ` or `ℝ`. Solutions:\n * If the fixed type has an additive counterpart (like `↥Semigroup`), give it the `@[to_additive]`\n attribute.\n * If the fixed type occurs inside the `k`-th argument of a declaration `d`, and the\n `k`-th argument is not connected to the multiplicative structure on `d`, consider adding\n attribute `[to_additive_ignore_args k]` to `d`.\n * If you want to disable the heuristic and replace all multiplicative\n identifiers with their additive counterpart, use `@[to_additive!]`.\n* Option 3: Arguments / universe levels are incorrectly ordered in the additive version.\n This likely only happens when the multiplicative declaration involves `pow`/`^`. Solutions:\n * Ensure that the order of arguments of all relevant declarations are the same for the\n multiplicative and additive version. This might mean that arguments have an \"unnatural\" order\n (e.g. `monoid.npow n x` corresponds to `x ^ n`, but it is convenient that `monoid.npow` has this\n argument order, since it matches `add_monoid.nsmul n x`.\n * If this is not possible, add the `[to_additive_reorder k]` to the multiplicative declaration\n to indicate that the `k`-th and `(k+1)`-st arguments are reordered in the additive version.\n\nIf neither of these solutions work, and `to_additive` is unable to automatically generate the\nadditive version of a declaration, manually write and prove the additive version.\nOften the proof of a lemma/theorem can just be the multiplicative version of the lemma applied to\n`multiplicative G`.\nAfterwards, apply the attribute manually:\n\n```\nattribute [to_additive foo_add_bar] foo_bar\n```\n\nThis will allow future uses of `to_additive` to recognize that\n`foo_bar` should be replaced with `foo_add_bar`.\n\n### Handling of hidden definitions\n\nBefore transporting the “main” declaration `src`, `to_additive` first\nscans its type and value for names starting with `src`, and transports\nthem. This includes auxiliary definitions like `src._match_1`,\n`src._proof_1`.\n\nIn addition to transporting the “main” declaration, `to_additive` transports\nits equational lemmas and tags them as equational lemmas for the new declaration,\nattributes present on the original equational lemmas are also transferred first (notably\n`_refl_lemma`).\n\n### Structure fields and constructors\n\nIf `src` is a structure, then `to_additive` automatically adds\nstructure fields to its mapping, and similarly for constructors of\ninductive types.\n\nFor new structures this means that `to_additive` automatically handles\ncoercions, and for old structures it does the same, if ancestry\ninformation is present in `@[ancestor]` attributes. The `ancestor`\nattribute must come before the `to_additive` attribute, and it is\nessential that the order of the base structures passed to `ancestor` matches\nbetween the multiplicative and additive versions of the structure.\n\n### Name generation\n\n* If `@[to_additive]` is called without a `name` argument, then the\n new name is autogenerated. First, it takes the longest prefix of\n the source name that is already known to `to_additive`, and replaces\n this prefix with its additive counterpart. Second, it takes the last\n part of the name (i.e., after the last dot), and replaces common\n name parts (“mul”, “one”, “inv”, “prod”) with their additive versions.\n\n* Namespaces can be transformed using `map_namespace`. For example:\n ```\n run_cmd to_additive.map_namespace `quotient_group `quotient_add_group\n ```\n\n Later uses of `to_additive` on declarations in the `quotient_group`\n namespace will be created in the `quotient_add_group` namespaces.\n\n* If `@[to_additive]` is called with a `name` argument `new_name`\n /without a dot/, then `to_additive` updates the prefix as described\n above, then replaces the last part of the name with `new_name`.\n\n* If `@[to_additive]` is called with a `name` argument\n `new_namespace.new_name` /with a dot/, then `to_additive` uses this\n new name as is.\n\nAs a safety check, in the first case `to_additive` double checks\nthat the new name differs from the original one.\n\n-/\n@[user_attribute]\nprotected meta def attr : user_attribute unit value_type :=\n{ name := `to_additive,\n descr := \"Transport multiplicative to additive\",\n parser := parser,\n after_set := some $ λ src prio persistent, do\n guard persistent <|> fail \"`to_additive` can't be used as a local attribute\",\n env ← get_env,\n val ← attr.get_param src,\n dict ← aux_attr.get_cache,\n ignore ← ignore_args_attr.get_cache,\n relevant ← relevant_arg_attr.get_cache,\n reorder ← reorder_attr.get_cache,\n tgt ← target_name src val.tgt dict val.allow_auto_name,\n aux_attr.set src tgt tt,\n let dict := dict.insert src tgt,\n first_mult_arg ← first_multiplicative_arg src,\n when (first_mult_arg ≠ 1) $ relevant_arg_attr.set src first_mult_arg tt,\n if env.contains tgt\n then proceed_fields env src tgt prio\n else do\n transform_decl_with_prefix_dict dict val.replace_all val.trace relevant ignore reorder src tgt\n [`reducible, `_refl_lemma, `simp, `norm_cast, `instance, `refl, `symm, `trans,\n `elab_as_eliminator, `no_rsimp, `continuity, `ext, `ematch, `measurability, `alias,\n `_ext_core, `_ext_lemma_core, `nolint],\n mwhen (has_attribute' `simps src)\n (trace \"Apply the simps attribute after the to_additive attribute\"),\n mwhen (has_attribute' `mono src)\n (trace $ \"to_additive does not work with mono, apply the mono attribute to both\" ++\n \"versions after\"),\n match val.doc with\n | some doc := add_doc_string tgt doc\n | none := skip\n end }\n\nadd_tactic_doc\n{ name := \"to_additive\",\n category := doc_category.attr,\n decl_names := [`to_additive.attr],\n tags := [\"transport\", \"environment\", \"lemma derivation\"] }\n\nend to_additive\n\n/- map operations -/\nattribute [to_additive] has_mul has_one has_inv has_div\n/- the following types are supported by `@[to_additive]` and mapped to themselves. -/\nattribute [to_additive empty] empty\nattribute [to_additive pempty] pempty\nattribute [to_additive punit] punit\nattribute [to_additive unit] unit\n", "meta": {"author": "jjaassoonn", "repo": "projective_space", "sha": "11fe19fe9d7991a272e7a40be4b6ad9b0c10c7ce", "save_path": "github-repos/lean/jjaassoonn-projective_space", "path": "github-repos/lean/jjaassoonn-projective_space/projective_space-11fe19fe9d7991a272e7a40be4b6ad9b0c10c7ce/src/algebra/group/to_additive.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4921881357207956, "lm_q2_score": 0.09268778615821206, "lm_q1q2_score": 0.04561982867329816}} {"text": "/-\nCopyright (c) 2018 Simon Hudon. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Simon Hudon\n\n! This file was ported from Lean 3 source module data.lazy_list.basic\n! leanprover-community/mathlib commit 1f0096e6caa61e9c849ec2adbd227e960e9dff58\n! Please do not edit these lines, except to modify the commit id\n! if you have ported upstream changes.\n-/\nimport Mathlib.Control.Traversable.Equiv\nimport Mathlib.Control.Traversable.Instances\nimport Mathlib.Data.LazyList\n\n/-!\n## Definitions on lazy lists\n\nThis file contains various definitions and proofs on lazy lists.\n\nTODO: move the `LazyList.lean` file from core to mathlib.\n-/\n\n\nuniverse u\n\nnamespace Thunk\n\n-- Porting note: `Thunk.pure` appears to do the same thing.\n#align thunk.mk Thunk.pure\n\n-- Porting note: Added `Thunk.ext` to get `ext` tactic to work.\n@[ext]\n\n\ninstance {α : Type u} [DecidableEq α] : DecidableEq (Thunk α) := by\n intro a b\n have : a = b ↔ a.get = b.get := ⟨by intro x; rw [x], by intro; ext; assumption⟩\n rw [this]\n infer_instance\n\nend Thunk\n\nnamespace LazyList\n\nopen Function\n\n/-- Isomorphism between strict and lazy lists. -/\ndef listEquivLazyList (α : Type _) : List α ≃ LazyList α\n where\n toFun := LazyList.ofList\n invFun := LazyList.toList\n right_inv := by\n intro xs\n induction' xs using LazyList.rec with _ _ _ _ ih\n rfl\n simpa only [toList, ofList, cons.injEq, true_and]\n rw [Thunk.get, ih]\n left_inv := by\n intro xs\n induction xs\n rfl\n simpa [ofList, toList]\n#align lazy_list.list_equiv_lazy_list LazyList.listEquivLazyList\n\n-- Porting note: Added a name to make the recursion work.\ninstance decidableEq {α : Type u} [DecidableEq α] : DecidableEq (LazyList α)\n | nil, nil => isTrue rfl\n | cons x xs, cons y ys =>\n if h : x = y then\n match decidableEq xs.get ys.get with\n | isFalse h2 => by\n apply isFalse; simp only [cons.injEq, not_and]; intro _ xs_ys; apply h2; rw [xs_ys]\n | isTrue h2 => by apply isTrue; congr; ext; exact h2\n else by apply isFalse; simp only [cons.injEq, not_and]; intro; contradiction\n | nil, cons _ _ => by apply isFalse; simp\n | cons _ _, nil => by apply isFalse; simp\n\n/-- Traversal of lazy lists using an applicative effect. -/\nprotected def traverse {m : Type u → Type u} [Applicative m] {α β : Type u} (f : α → m β) :\n LazyList α → m (LazyList β)\n | LazyList.nil => pure LazyList.nil\n | LazyList.cons x xs => LazyList.cons <$> f x <*> Thunk.pure <$> xs.get.traverse f\n#align lazy_list.traverse LazyList.traverse\n\ninstance : Traversable LazyList\n where\n map := @LazyList.traverse Id _\n traverse := @LazyList.traverse\n\ninstance : IsLawfulTraversable LazyList := by\n apply Equiv.isLawfulTraversable' listEquivLazyList <;> intros <;> ext <;> rename_i f xs\n · induction' xs using LazyList.rec with _ _ _ _ ih\n rfl\n simpa only [Equiv.map, Functor.map, listEquivLazyList, Equiv.coe_fn_symm_mk, Equiv.coe_fn_mk,\n LazyList.traverse, Seq.seq, toList, ofList, cons.injEq, true_and]\n ext; apply ih\n · simp only [Equiv.map, listEquivLazyList, Equiv.coe_fn_symm_mk, Equiv.coe_fn_mk, comp,\n Functor.mapConst]\n induction' xs using LazyList.rec with _ _ _ _ ih\n rfl\n simpa only [toList, ofList, LazyList.traverse, Seq.seq, Functor.map, cons.injEq, true_and]\n congr; apply ih\n · simp only [traverse, Equiv.traverse, listEquivLazyList, Equiv.coe_fn_mk, Equiv.coe_fn_symm_mk]\n induction' xs using LazyList.rec with _ tl ih _ ih\n simp only [List.traverse, map_pure]; rfl\n have : tl.get.traverse f = ofList <$> tl.get.toList.traverse f := ih\n simp only [traverse._eq_2, ih, Functor.map_map, seq_map_assoc, toList, List.traverse, map_seq]\n . rfl\n . apply ih\n\n/-- `init xs`, if `xs` non-empty, drops the last element of the list.\nOtherwise, return the empty list. -/\ndef init {α} : LazyList α → LazyList α\n | LazyList.nil => LazyList.nil\n | LazyList.cons x xs =>\n let xs' := xs.get\n match xs' with\n | LazyList.nil => LazyList.nil\n | LazyList.cons _ _ => LazyList.cons x (init xs')\n#align lazy_list.init LazyList.init\n\n/-- Return the first object contained in the list that satisfies\npredicate `p` -/\ndef find {α} (p : α → Prop) [DecidablePred p] : LazyList α → Option α\n | nil => none\n | cons h t => if p h then some h else t.get.find p\n#align lazy_list.find LazyList.find\n\n/-- `interleave xs ys` creates a list where elements of `xs` and `ys` alternate. -/\ndef interleave {α} : LazyList α → LazyList α → LazyList α\n | LazyList.nil, xs => xs\n | a@(LazyList.cons _ _), LazyList.nil => a\n | LazyList.cons x xs, LazyList.cons y ys =>\n LazyList.cons x (LazyList.cons y (interleave xs.get ys.get))\n#align lazy_list.interleave LazyList.interleave\n\n/-- `interleaveAll (xs::ys::zs::xss)` creates a list where elements of `xs`, `ys`\nand `zs` and the rest alternate. Every other element of the resulting list is taken from\n`xs`, every fourth is taken from `ys`, every eighth is taken from `zs` and so on. -/\ndef interleaveAll {α} : List (LazyList α) → LazyList α\n | [] => LazyList.nil\n | x :: xs => interleave x (interleaveAll xs)\n#align lazy_list.interleave_all LazyList.interleaveAll\n\n/-- Monadic bind operation for `LazyList`. -/\nprotected def bind {α β} : LazyList α → (α → LazyList β) → LazyList β\n | LazyList.nil, _ => LazyList.nil\n | LazyList.cons x xs, f => (f x).append (xs.get.bind f)\n#align lazy_list.bind LazyList.bind\n\n/-- Reverse the order of a `LazyList`.\nIt is done by converting to a `List` first because reversal involves evaluating all\nthe list and if the list is all evaluated, `List` is a better representation for\nit than a series of thunks. -/\ndef reverse {α} (xs : LazyList α) : LazyList α :=\n ofList xs.toList.reverse\n#align lazy_list.reverse LazyList.reverse\n\ninstance : Monad LazyList where\n pure := @LazyList.singleton\n bind := @LazyList.bind\n\n-- Porting note: Added `Thunk.pure` to definition.\ntheorem append_nil {α} (xs : LazyList α) : xs.append (Thunk.pure LazyList.nil) = xs := by\n induction' xs using LazyList.rec with _ _ _ _ ih\n . rfl\n . simpa only [append, cons.injEq, true_and]\n . ext; apply ih\n#align lazy_list.append_nil LazyList.append_nil\n\ntheorem append_assoc {α} (xs ys zs : LazyList α) :\n (xs.append ys).append zs = xs.append (ys.append zs) := by\n induction' xs using LazyList.rec with _ _ _ _ ih\n . rfl\n . simpa only [append, cons.injEq, true_and]\n . ext; apply ih\n#align lazy_list.append_assoc LazyList.append_assoc\n\n-- Porting note: Rewrote proof of `append_bind`.\ntheorem append_bind {α β} (xs : LazyList α) (ys : Thunk (LazyList α)) (f : α → LazyList β) :\n (xs.append ys).bind f = (xs.bind f).append (ys.get.bind f) := by\n match xs with\n | LazyList.nil => rfl\n | LazyList.cons x xs =>\n simp only [append, Thunk.get, LazyList.bind]\n have := append_bind xs.get ys f\n simp only [Thunk.get] at this\n rw [this, append_assoc]\n#align lazy_list.append_bind LazyList.append_bind\n\ninstance : LawfulMonad LazyList := LawfulMonad.mk'\n (bind_pure_comp := by\n intro _ _ f xs\n simp only [bind, Functor.map, pure, singleton]\n induction' xs using LazyList.rec with _ _ _ _ ih\n . rfl\n . simp only [bind._eq_2, append, traverse._eq_2, Id.map_eq, cons.injEq, true_and]; congr\n . ext; apply ih)\n (pure_bind := by\n intros\n simp only [bind, pure, singleton, LazyList.bind]\n apply append_nil)\n (bind_assoc := by\n intro _ _ _ xs _ _\n induction' xs using LazyList.rec with _ _ _ _ ih\n . rfl\n . simp only [bind, LazyList.bind, append_bind]; congr\n . congr; funext; apply ih)\n (id_map := by\n intro _ xs\n induction' xs using LazyList.rec with _ _ _ _ ih\n . rfl\n . simpa only [Functor.map, traverse._eq_2, id_eq, Id.map_eq, Seq.seq, cons.injEq, true_and]\n . ext; apply ih)\n\n-- Porting note: This is a dubious translation. In the warning, u1 and u3 are swapped.\n/-- Try applying function `f` to every element of a `LazyList` and\nreturn the result of the first attempt that succeeds. -/\ndef mfirst {m} [Alternative m] {α β} (f : α → m β) : LazyList α → m β\n | nil => failure\n | cons x xs => f x <|> xs.get.mfirst f\n#align lazy_list.mfirst LazyList.mfirstₓ\n\n/-- Membership in lazy lists -/\nprotected def Mem {α} (x : α) : LazyList α → Prop\n | nil => False\n | cons y ys => x = y ∨ ys.get.Mem x\n#align lazy_list.mem LazyList.Mem\n\ninstance {α} : Membership α (LazyList α) :=\n ⟨LazyList.Mem⟩\n\ninstance Mem.decidable {α} [DecidableEq α] (x : α) : ∀ xs : LazyList α, Decidable (x ∈ xs)\n | LazyList.nil => by\n apply Decidable.isFalse\n simp [Membership.mem, LazyList.Mem]\n | LazyList.cons y ys =>\n if h : x = y then by\n apply Decidable.isTrue\n simp only [Membership.mem, LazyList.Mem]\n exact Or.inl h\n else by\n have := Mem.decidable x ys.get\n have : (x ∈ ys.get) ↔ (x ∈ cons y ys) := by simp [(· ∈ ·), LazyList.Mem, h]\n exact decidable_of_decidable_of_iff this\n#align lazy_list.mem.decidable LazyList.Mem.decidable\n\n@[simp]\ntheorem mem_nil {α} (x : α) : x ∈ @LazyList.nil α ↔ False :=\n Iff.rfl\n#align lazy_list.mem_nil LazyList.mem_nil\n\n@[simp]\ntheorem mem_cons {α} (x y : α) (ys : Thunk (LazyList α)) :\n x ∈ @LazyList.cons α y ys ↔ x = y ∨ x ∈ ys.get := by\n simp [Membership.mem, LazyList.Mem]\n#align lazy_list.mem_cons LazyList.mem_cons\n\ntheorem forall_mem_cons {α} {p : α → Prop} {a : α} {l : Thunk (LazyList α)} :\n (∀ x ∈ @LazyList.cons _ a l, p x) ↔ p a ∧ ∀ x ∈ l.get, p x := by\n simp only [Membership.mem, LazyList.Mem, or_imp, forall_and, forall_eq]\n#align lazy_list.forall_mem_cons LazyList.forall_mem_cons\n\n/-! ### map for partial functions -/\n\n\n/-- Partial map. If `f : ∀ a, p a → β` is a partial function defined on\n `a : α` satisfying `p`, then `pmap f l h` is essentially the same as `map f l`\n but is defined only when all members of `l` satisfy `p`, using the proof\n to apply `f`. -/\n@[simp]\ndef pmap {α β} {p : α → Prop} (f : ∀ a, p a → β) : ∀ l : LazyList α, (∀ a ∈ l, p a) → LazyList β\n | LazyList.nil, _ => LazyList.nil\n | LazyList.cons x xs, H =>\n LazyList.cons (f x (forall_mem_cons.1 H).1) (xs.get.pmap f (forall_mem_cons.1 H).2)\n#align lazy_list.pmap LazyList.pmap\n\n/-- \"Attach\" the proof that the elements of `l` are in `l` to produce a new `LazyList`\n with the same elements but in the type `{x // x ∈ l}`. -/\ndef attach {α} (l : LazyList α) : LazyList { x // x ∈ l } :=\n pmap Subtype.mk l fun _ ↦ id\n#align lazy_list.attach LazyList.attach\n\ninstance {α} [Repr α] : Repr (LazyList α) :=\n ⟨fun xs _ ↦ repr xs.toList⟩\n\nend LazyList\n", "meta": {"author": "leanprover-community", "repo": "mathlib4", "sha": "b9a0a30342ca06e9817e22dbe46e75fc7f435500", "save_path": "github-repos/lean/leanprover-community-mathlib4", "path": "github-repos/lean/leanprover-community-mathlib4/mathlib4-b9a0a30342ca06e9817e22dbe46e75fc7f435500/Mathlib/Data/LazyList/Basic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44939263446475963, "lm_q2_score": 0.1008786132690879, "lm_q1q2_score": 0.04533410577814707}} {"text": "/-\nCopyright (c) 2017 Mario Carneiro. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Mario Carneiro\n-/\nimport tactic.core\n\n/-!\n# The `alias` command\n\nThis file defines an `alias` command, which can be used to create copies\nof a theorem or definition with different names.\n\nSyntax:\n\n```lean\n/-- doc string -/\nalias my_theorem ← alias1 alias2 ...\n```\n\nThis produces defs or theorems of the form:\n\n```lean\n/-- doc string -/\n@[alias] theorem alias1 : := my_theorem\n\n/-- doc string -/\n@[alias] theorem alias2 : := my_theorem\n```\n\nIff alias syntax:\n\n```lean\nalias A_iff_B ↔ B_of_A A_of_B\nalias A_iff_B ↔ ..\n```\n\nThis gets an existing biconditional theorem `A_iff_B` and produces\nthe one-way implications `B_of_A` and `A_of_B` (with no change in\nimplicit arguments). A blank `_` can be used to avoid generating one direction.\nThe `..` notation attempts to generate the 'of'-names automatically when the\ninput theorem has the form `A_iff_B` or `A_iff_B_left` etc.\n-/\n\nopen lean.parser tactic interactive\n\nnamespace tactic.alias\n\n/-- An alias can be in one of three forms -/\n@[derive has_reflect]\nmeta inductive target\n| plain : name -> target\n| forward : name -> target\n| backwards : name -> target\n\n/-- The name underlying an alias target -/\nmeta def target.to_name : target → name\n| (target.plain n) := n\n| (target.forward n) := n\n| (target.backwards n) := n\n\n/-- The docstring for an alias. Used by `alias` _and_ by `to_additive` -/\nmeta def target.to_string : target → string\n| (target.plain n) := sformat!\"**Alias** of {n}`.\"\n| (target.forward n) := sformat!\"**Alias** of the forward direction of {n}`.\"\n| (target.backwards n) := sformat!\"**Alias** of the reverse direction of {n}`.\"\n\n@[user_attribute] meta def alias_attr : user_attribute unit target :=\n{ name := `alias, descr := \"This definition is an alias of another.\", parser := failed }\n\nmeta def alias_direct (d : declaration) (al : name) : tactic unit :=\ndo updateex_env $ λ env,\n env.add (match d.to_definition with\n | declaration.defn n ls t _ _ _ :=\n declaration.defn al ls t (expr.const n (level.param <$> ls))\n reducibility_hints.abbrev tt\n | declaration.thm n ls t _ :=\n declaration.thm al ls t $ task.pure $ expr.const n (level.param <$> ls)\n | _ := undefined\n end),\n let target := target.plain d.to_name,\n alias_attr.set al target tt,\n add_doc_string al target.to_string\n\nmeta def mk_iff_mp_app (iffmp : name) : expr → (ℕ → expr) → tactic expr\n| (expr.pi n bi e t) f := expr.lam n bi e <$> mk_iff_mp_app t (λ n, f (n+1) (expr.var n))\n| `(%%a ↔ %%b) f := pure $ @expr.const tt iffmp [] a b (f 0)\n| _ f := fail \"Target theorem must have the form `Π x y z, a ↔ b`\"\n\nmeta def alias_iff (d : declaration) (al : name) (is_forward : bool) : tactic unit :=\n(if al = `_ then skip else get_decl al >> skip) <|> do\n let ls := d.univ_params,\n let t := d.type,\n let target := if is_forward then target.forward d.to_name else target.backwards d.to_name,\n let iffmp := if is_forward then `iff.mp else `iff.mpr,\n v ← mk_iff_mp_app iffmp t (λ_, expr.const d.to_name (level.param <$> ls)),\n t' ← infer_type v,\n updateex_env $ λ env, env.add (declaration.thm al ls t' $ task.pure v),\n alias_attr.set al target tt,\n add_doc_string al target.to_string\n\nmeta def make_left_right : name → tactic (name × name)\n| (name.mk_string s p) := do\n let buf : char_buffer := s.to_char_buffer,\n let parts := s.split_on '_',\n (left, _::right) ← pure $ parts.span (≠ \"iff\"),\n let pfx (a b : string) := a.to_list.is_prefix_of b.to_list,\n (suffix', right') ← pure $ right.reverse.span (λ s, pfx \"left\" s ∨ pfx \"right\" s),\n let right := right'.reverse,\n let suffix := suffix'.reverse,\n pure (p <.> \"_\".intercalate (right ++ \"of\" :: left ++ suffix),\n p <.> \"_\".intercalate (left ++ \"of\" :: right ++ suffix))\n| _ := failed\n\n/--\nThe `alias` command can be used to create copies\nof a theorem or definition with different names.\n\nSyntax:\n\n```lean\n/-- doc string -/\nalias my_theorem ← alias1 alias2 ...\n```\n\nThis produces defs or theorems of the form:\n\n```lean\n/-- doc string -/\n@[alias] theorem alias1 : := my_theorem\n\n/-- doc string -/\n@[alias] theorem alias2 : := my_theorem\n```\n\nIff alias syntax:\n\n```lean\nalias A_iff_B ↔ B_of_A A_of_B\nalias A_iff_B ↔ ..\n```\n\nThis gets an existing biconditional theorem `A_iff_B` and produces\nthe one-way implications `B_of_A` and `A_of_B` (with no change in\nimplicit arguments). A blank `_` can be used to avoid generating one direction.\nThe `..` notation attempts to generate the 'of'-names automatically when the\ninput theorem has the form `A_iff_B` or `A_iff_B_left` etc.\n-/\n@[user_command] meta def alias_cmd (meta_info : decl_meta_info)\n (_ : parse $ tk \"alias\") : lean.parser unit :=\ndo old ← ident,\n d ← (do old ← resolve_constant old, get_decl old) <|>\n fail (\"declaration \" ++ to_string old ++ \" not found\"),\n let doc := λ (al : name) (inf : string), meta_info.doc_string.get_or_else $\n sformat!\"**Alias** of {inf}`{old}`.\",\n do\n { tk \"←\" <|> tk \"<-\",\n aliases ← many ident,\n ↑(aliases.mmap' $ λ al, alias_direct d al) } <|>\n do\n { tk \"↔\" <|> tk \"<->\",\n (left, right) ←\n mcond ((tk \"..\" >> pure tt) <|> pure ff)\n (make_left_right old <|> fail \"invalid name for automatic name generation\")\n (prod.mk <$> types.ident_ <*> types.ident_),\n alias_iff d left tt,\n alias_iff d right ff }\n\nadd_tactic_doc\n{ name := \"alias\",\n category := doc_category.cmd,\n decl_names := [`tactic.alias.alias_cmd],\n tags := [\"renaming\"] }\n\nmeta def get_lambda_body : expr → expr\n| (expr.lam _ _ _ b) := get_lambda_body b\n| a := a\n\nmeta def get_alias_target (n : name) : tactic (option target) :=\ndo tt ← has_attribute' `alias n | pure none,\n v ← alias_attr.get_param n,\n pure $ some v\n\nend tactic.alias\n", "meta": {"author": "nick-kuhn", "repo": "leantools", "sha": "567a98c031fffe3f270b7b8dea48389bc70d7abb", "save_path": "github-repos/lean/nick-kuhn-leantools", "path": "github-repos/lean/nick-kuhn-leantools/leantools-567a98c031fffe3f270b7b8dea48389bc70d7abb/src/tactic/alias.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34510528442897664, "lm_q2_score": 0.13117323395124272, "lm_q1q2_score": 0.045268576212212315}} {"text": "/-\nCopyright (c) 2022 Joël Riou. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Joël Riou\n\n! This file was ported from Lean 3 source module algebraic_topology.dold_kan.compatibility\n! leanprover-community/mathlib commit 160f568dcf772b2477791c844fc605f2f91f73d1\n! Please do not edit these lines, except to modify the commit id\n! if you have ported upstream changes.\n-/\nimport Mathbin.CategoryTheory.Equivalence\n\n/-! Tools for compatibilities between Dold-Kan equivalences\n\nThe purpose of this file is to introduce tools which will enable the\nconstruction of the Dold-Kan equivalence `simplicial_object C ≌ chain_complex C ℕ`\nfor a pseudoabelian category `C` from the equivalence\n`karoubi (simplicial_object C) ≌ karoubi (chain_complex C ℕ)` and the two\nequivalences `simplicial_object C ≅ karoubi (simplicial_object C)` and\n`chain_complex C ℕ ≅ karoubi (chain_complex C ℕ)`.\n\nIt is certainly possible to get an equivalence `simplicial_object C ≌ chain_complex C ℕ`\nusing a compositions of the three equivalences above, but then neither the functor\nnor the inverse would have good definitional properties. For example, it would be better\nif the inverse functor of the equivalence was exactly the functor\n`Γ₀ : simplicial_object C ⥤ chain_complex C ℕ` which was constructed in `functor_gamma.lean`.\n\nIn this file, given four categories `A`, `A'`, `B`, `B'`, equivalences `eA : A ≅ A'`,\n`eB : B ≅ B'`, `e' : A' ≅ B'`, functors `F : A ⥤ B'`, `G : B ⥤ A` equipped with certain\ncompatibilities, we construct successive equivalences:\n- `equivalence₀` from `A` to `B'`, which is the composition of `eA` and `e'`.\n- `equivalence₁` from `A` to `B'`, with the same inverse functor as `equivalence₀`,\nbut whose functor is `F`.\n- `equivalence₂` from `A` to `B`, which is the composition of `equivalence₁` and the\ninverse of `eB`:\n- `equivalence` from `A` to `B`, which has the same functor `F ⋙ eB.inverse` as `equivalence₂`,\nbut whose inverse functor is `G`.\n\nWhen extra assumptions are given, we shall also provide simplification lemmas for the\nunit and counit isomorphisms of `equivalence`. (TODO)\n\n-/\n\n\nopen CategoryTheory CategoryTheory.Category\n\nnamespace AlgebraicTopology\n\nnamespace DoldKan\n\nnamespace Compatibility\n\nvariable {A A' B B' : Type _} [Category A] [Category A'] [Category B] [Category B'] (eA : A ≌ A')\n (eB : B ≌ B') (e' : A' ≌ B') {F : A ⥤ B'} (hF : eA.Functor ⋙ e'.Functor ≅ F) {G : B ⥤ A}\n (hG : eB.Functor ⋙ e'.inverse ≅ G ⋙ eA.Functor)\n\n/-- A basic equivalence `A ≅ B'` obtained by composing `eA : A ≅ A'` and `e' : A' ≅ B'`. -/\n@[simps Functor inverse unit_iso_hom_app]\ndef equivalence₀ : A ≌ B' :=\n eA.trans e'\n#align algebraic_topology.dold_kan.compatibility.equivalence₀ AlgebraicTopology.DoldKan.Compatibility.equivalence₀\n\ninclude hF\n\nvariable {eA} {e'}\n\n/-- An intermediate equivalence `A ≅ B'` whose functor is `F` and whose inverse is\n`e'.inverse ⋙ eA.inverse`. -/\n@[simps Functor]\ndef equivalence₁ : A ≌ B' :=\n letI : is_equivalence F :=\n is_equivalence.of_iso hF (is_equivalence.of_equivalence (equivalence₀ eA e'))\n F.as_equivalence\n#align algebraic_topology.dold_kan.compatibility.equivalence₁ AlgebraicTopology.DoldKan.Compatibility.equivalence₁\n\ntheorem equivalence₁_inverse : (equivalence₁ hF).inverse = e'.inverse ⋙ eA.inverse :=\n rfl\n#align algebraic_topology.dold_kan.compatibility.equivalence₁_inverse AlgebraicTopology.DoldKan.Compatibility.equivalence₁_inverse\n\n/-- The counit isomorphism of the equivalence `equivalence₁` between `A` and `B'`. -/\n@[simps]\ndef equivalence₁CounitIso : (e'.inverse ⋙ eA.inverse) ⋙ F ≅ 𝟭 B' :=\n calc\n (e'.inverse ⋙ eA.inverse) ⋙ F ≅ (e'.inverse ⋙ eA.inverse) ⋙ eA.Functor ⋙ e'.Functor :=\n isoWhiskerLeft _ hF.symm\n _ ≅ e'.inverse ⋙ (eA.inverse ⋙ eA.Functor) ⋙ e'.Functor := (Iso.refl _)\n _ ≅ e'.inverse ⋙ 𝟭 _ ⋙ e'.Functor := (isoWhiskerLeft _ (isoWhiskerRight eA.counitIso _))\n _ ≅ e'.inverse ⋙ e'.Functor := (Iso.refl _)\n _ ≅ 𝟭 B' := e'.counitIso\n \n#align algebraic_topology.dold_kan.compatibility.equivalence₁_counit_iso AlgebraicTopology.DoldKan.Compatibility.equivalence₁CounitIso\n\ntheorem equivalence₁CounitIso_eq : (equivalence₁ hF).counitIso = equivalence₁CounitIso hF :=\n by\n ext Y\n dsimp [equivalence₀, equivalence₁, is_equivalence.inverse, is_equivalence.of_equivalence]\n simp only [equivalence₁_counit_iso_hom_app, CategoryTheory.Functor.map_id, comp_id]\n#align algebraic_topology.dold_kan.compatibility.equivalence₁_counit_iso_eq AlgebraicTopology.DoldKan.Compatibility.equivalence₁CounitIso_eq\n\n/-- The unit isomorphism of the equivalence `equivalence₁` between `A` and `B'`. -/\n@[simps]\ndef equivalence₁UnitIso : 𝟭 A ≅ F ⋙ e'.inverse ⋙ eA.inverse :=\n calc\n 𝟭 A ≅ eA.Functor ⋙ eA.inverse := eA.unitIso\n _ ≅ eA.Functor ⋙ 𝟭 A' ⋙ eA.inverse := (Iso.refl _)\n _ ≅ eA.Functor ⋙ (e'.Functor ⋙ e'.inverse) ⋙ eA.inverse :=\n (isoWhiskerLeft _ (isoWhiskerRight e'.unitIso _))\n _ ≅ (eA.Functor ⋙ e'.Functor) ⋙ e'.inverse ⋙ eA.inverse := (Iso.refl _)\n _ ≅ F ⋙ e'.inverse ⋙ eA.inverse := isoWhiskerRight hF _\n \n#align algebraic_topology.dold_kan.compatibility.equivalence₁_unit_iso AlgebraicTopology.DoldKan.Compatibility.equivalence₁UnitIso\n\ntheorem equivalence₁UnitIso_eq : (equivalence₁ hF).unitIso = equivalence₁UnitIso hF :=\n by\n ext X\n dsimp [equivalence₀, equivalence₁, nat_iso.hcomp, is_equivalence.of_equivalence]\n simp only [id_comp, assoc, equivalence₁_unit_iso_hom_app]\n#align algebraic_topology.dold_kan.compatibility.equivalence₁_unit_iso_eq AlgebraicTopology.DoldKan.Compatibility.equivalence₁UnitIso_eq\n\ninclude eB\n\n/-- An intermediate equivalence `A ≅ B` obtained as the composition of `equivalence₁` and\nthe inverse of `eB : B ≌ B'`. -/\n@[simps Functor]\ndef equivalence₂ : A ≌ B :=\n (equivalence₁ hF).trans eB.symm\n#align algebraic_topology.dold_kan.compatibility.equivalence₂ AlgebraicTopology.DoldKan.Compatibility.equivalence₂\n\ntheorem equivalence₂_inverse :\n (equivalence₂ eB hF).inverse = eB.Functor ⋙ e'.inverse ⋙ eA.inverse :=\n rfl\n#align algebraic_topology.dold_kan.compatibility.equivalence₂_inverse AlgebraicTopology.DoldKan.Compatibility.equivalence₂_inverse\n\n/-- The counit isomorphism of the equivalence `equivalence₂` between `A` and `B`. -/\n@[simps]\ndef equivalence₂CounitIso : (eB.Functor ⋙ e'.inverse ⋙ eA.inverse) ⋙ F ⋙ eB.inverse ≅ 𝟭 B :=\n calc\n (eB.Functor ⋙ e'.inverse ⋙ eA.inverse) ⋙ F ⋙ eB.inverse ≅\n eB.Functor ⋙ (e'.inverse ⋙ eA.inverse ⋙ F) ⋙ eB.inverse :=\n Iso.refl _\n _ ≅ eB.Functor ⋙ 𝟭 _ ⋙ eB.inverse :=\n (isoWhiskerLeft _ (isoWhiskerRight (equivalence₁CounitIso hF) _))\n _ ≅ eB.Functor ⋙ eB.inverse := (Iso.refl _)\n _ ≅ 𝟭 B := eB.unitIso.symm\n \n#align algebraic_topology.dold_kan.compatibility.equivalence₂_counit_iso AlgebraicTopology.DoldKan.Compatibility.equivalence₂CounitIso\n\ntheorem equivalence₂CounitIso_eq : (equivalence₂ eB hF).counitIso = equivalence₂CounitIso eB hF :=\n by\n ext Y'\n dsimp [equivalence₂, iso.refl]\n simp only [equivalence₁_counit_iso_eq, equivalence₂_counit_iso_hom_app,\n equivalence₁_counit_iso_hom_app, functor.map_comp, assoc]\n#align algebraic_topology.dold_kan.compatibility.equivalence₂_counit_iso_eq AlgebraicTopology.DoldKan.Compatibility.equivalence₂CounitIso_eq\n\n/-- The unit isomorphism of the equivalence `equivalence₂` between `A` and `B`. -/\n@[simps]\ndef equivalence₂UnitIso : 𝟭 A ≅ (F ⋙ eB.inverse) ⋙ eB.Functor ⋙ e'.inverse ⋙ eA.inverse :=\n calc\n 𝟭 A ≅ F ⋙ e'.inverse ⋙ eA.inverse := equivalence₁UnitIso hF\n _ ≅ F ⋙ 𝟭 B' ⋙ e'.inverse ⋙ eA.inverse := (Iso.refl _)\n _ ≅ F ⋙ (eB.inverse ⋙ eB.Functor) ⋙ e'.inverse ⋙ eA.inverse :=\n (isoWhiskerLeft _ (isoWhiskerRight eB.counitIso.symm _))\n _ ≅ (F ⋙ eB.inverse) ⋙ eB.Functor ⋙ e'.inverse ⋙ eA.inverse := Iso.refl _\n \n#align algebraic_topology.dold_kan.compatibility.equivalence₂_unit_iso AlgebraicTopology.DoldKan.Compatibility.equivalence₂UnitIso\n\ntheorem equivalence₂UnitIso_eq : (equivalence₂ eB hF).unitIso = equivalence₂UnitIso eB hF :=\n by\n ext X\n dsimp [equivalence₂]\n simpa only [equivalence₂_unit_iso_hom_app, equivalence₁_unit_iso_eq,\n equivalence₁_unit_iso_hom_app, assoc, nat_iso.cancel_nat_iso_hom_left]\n#align algebraic_topology.dold_kan.compatibility.equivalence₂_unit_iso_eq AlgebraicTopology.DoldKan.Compatibility.equivalence₂UnitIso_eq\n\nvariable {eB}\n\ninclude hG\n\n/-- The equivalence `A ≅ B` whose functor is `F ⋙ eB.inverse` and\nwhose inverse is `G : B ≅ A`. -/\n@[simps inverse]\ndef equivalence : A ≌ B :=\n letI : is_equivalence G :=\n by\n refine' is_equivalence.of_iso _ (is_equivalence.of_equivalence (equivalence₂ eB hF).symm)\n calc\n eB.functor ⋙ e'.inverse ⋙ eA.inverse ≅ (eB.functor ⋙ e'.inverse) ⋙ eA.inverse := iso.refl _\n _ ≅ (G ⋙ eA.functor) ⋙ eA.inverse := (iso_whisker_right hG _)\n _ ≅ G ⋙ 𝟭 A := (iso_whisker_left _ eA.unit_iso.symm)\n _ ≅ G := functor.right_unitor G\n \n G.as_equivalence.symm\n#align algebraic_topology.dold_kan.compatibility.equivalence AlgebraicTopology.DoldKan.Compatibility.equivalence\n\ntheorem equivalence_functor : (equivalence hF hG).Functor = F ⋙ eB.inverse :=\n rfl\n#align algebraic_topology.dold_kan.compatibility.equivalence_functor AlgebraicTopology.DoldKan.Compatibility.equivalence_functor\n\nend Compatibility\n\nend DoldKan\n\nend AlgebraicTopology\n\n", "meta": {"author": "leanprover-community", "repo": "mathlib3port", "sha": "62505aa236c58c8559783b16d33e30df3daa54f4", "save_path": "github-repos/lean/leanprover-community-mathlib3port", "path": "github-repos/lean/leanprover-community-mathlib3port/mathlib3port-62505aa236c58c8559783b16d33e30df3daa54f4/Mathbin/AlgebraicTopology/DoldKan/Compatibility.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42632160712508727, "lm_q2_score": 0.10521052828620035, "lm_q1q2_score": 0.04485352150545239}} {"text": "/-\nCopyright (c) 2020 Yakov Pechersky. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Yakov Pechersky\n-/\nimport data.string.basic\nimport data.buffer.basic\nimport data.nat.digits\n\n/-!\n# Parsers\n\n`parser α` is the type that describes a computation that can ingest a `char_buffer`\nand output, if successful, a term of type `α`.\nThis file expands on the definitions in the core library, proving that all the core library\nparsers are `mono`. There are also lemmas on the composability of parsers.\n\n## Main definitions\n\n* `parse_result.pos` : The position of a `char_buffer` at which a `parser α` has finished.\n* `parser.mono` : The property that a parser only moves forward within a buffer,\n in both cases of success or failure.\n\n## Implementation details\n\nLemmas about how parsers are mono are in the `mono` namespace. That allows using projection\nnotation for shorter term proofs that are parallel to the definitions of the parsers in structure.\n\n-/\n\nopen parser parse_result\n\n/--\nFor some `parse_result α`, give the position at which the result was provided, in either the\n`done` or the `fail` case.\n-/\n@[simp] def parse_result.pos {α} : parse_result α → ℕ\n| (done n _) := n\n| (fail n _) := n\n\nnamespace parser\n\nsection defn_lemmas\n\nvariables {α β : Type} (msgs : thunk (list string)) (msg : thunk string)\nvariables (p q : parser α) (cb : char_buffer) (n n' : ℕ) {err : dlist string}\nvariables {a : α} {b : β}\n\n/--\nA `p : parser α` is defined to be `mono` if the result `p cb n` it gives,\nfor some `cb : char_buffer` and `n : ℕ`, (whether `done` or `fail`),\nis always at a `parse_result.pos` that is at least `n`.\nThe `mono` property is used mainly for proper `orelse` behavior.\n-/\nclass mono : Prop :=\n(le' : ∀ (cb : char_buffer) (n : ℕ), n ≤ (p cb n).pos)\n\nlemma mono.le [p.mono] : n ≤ (p cb n).pos := mono.le' cb n\n\n/--\nA `parser α` is defined to be `static` if it does not move on success.\n-/\nclass static : Prop :=\n(of_done : ∀ {cb : char_buffer} {n n' : ℕ} {a : α}, p cb n = done n' a → n = n')\n\n/--\nA `parser α` is defined to be `err_static` if it does not move on error.\n-/\nclass err_static : Prop :=\n(of_fail : ∀ {cb : char_buffer} {n n' : ℕ} {err : dlist string}, p cb n = fail n' err → n = n')\n\n/--\nA `parser α` is defined to be `step` if it always moves exactly one char forward on success.\n-/\nclass step : Prop :=\n(of_done : ∀ {cb : char_buffer} {n n' : ℕ} {a : α}, p cb n = done n' a → n' = n + 1)\n\n/--\nA `parser α` is defined to be `prog` if it always moves forward on success.\n-/\nclass prog : Prop :=\n(of_done : ∀ {cb : char_buffer} {n n' : ℕ} {a : α}, p cb n = done n' a → n < n')\n\n/--\nA `parser a` is defined to be `bounded` if it produces a\n`fail` `parse_result` when it is parsing outside the provided `char_buffer`.\n-/\nclass bounded : Prop :=\n(ex' : ∀ {cb : char_buffer} {n : ℕ}, cb.size ≤ n → ∃ (n' : ℕ) (err : dlist string),\n p cb n = fail n' err)\n\nlemma bounded.exists (p : parser α) [p.bounded] {cb : char_buffer} {n : ℕ} (h : cb.size ≤ n) :\n ∃ (n' : ℕ) (err : dlist string), p cb n = fail n' err :=\nbounded.ex' h\n\n/--\nA `parser a` is defined to be `unfailing` if it always produces a `done` `parse_result`.\n-/\nclass unfailing : Prop :=\n(ex' : ∀ (cb : char_buffer) (n : ℕ), ∃ (n' : ℕ) (a : α), p cb n = done n' a)\n\n/--\nA `parser a` is defined to be `conditionally_unfailing` if it produces a\n`done` `parse_result` as long as it is parsing within the provided `char_buffer`.\n-/\nclass conditionally_unfailing : Prop :=\n(ex' : ∀ {cb : char_buffer} {n : ℕ}, n < cb.size → ∃ (n' : ℕ) (a : α), p cb n = done n' a)\n\nlemma fail_iff :\n (∀ pos' result, p cb n ≠ done pos' result) ↔\n ∃ (pos' : ℕ) (err : dlist string), p cb n = fail pos' err :=\nby cases p cb n; simp\n\nlemma success_iff :\n (∀ pos' err, p cb n ≠ fail pos' err) ↔ ∃ (pos' : ℕ) (result : α), p cb n = done pos' result :=\nby cases p cb n; simp\n\nvariables {p q cb n n' msgs msg}\n\nlemma mono.of_done [p.mono] (h : p cb n = done n' a) : n ≤ n' :=\nby simpa [h] using mono.le p cb n\n\nlemma mono.of_fail [p.mono] (h : p cb n = fail n' err) : n ≤ n' :=\nby simpa [h] using mono.le p cb n\n\nlemma bounded.of_done [p.bounded] (h : p cb n = done n' a) : n < cb.size :=\nbegin\n contrapose! h,\n obtain ⟨np, err, hp⟩ := bounded.exists p h,\n simp [hp]\nend\n\nlemma static.iff :\n static p ↔ (∀ (cb : char_buffer) (n n' : ℕ) (a : α), p cb n = done n' a → n = n') :=\n⟨λ h _ _ _ _ hp, by { haveI := h, exact static.of_done hp}, λ h, ⟨h⟩⟩\n\nlemma exists_done (p : parser α) [p.unfailing] (cb : char_buffer) (n : ℕ) :\n ∃ (n' : ℕ) (a : α), p cb n = done n' a :=\nunfailing.ex' cb n\n\nlemma unfailing.of_fail [p.unfailing] (h : p cb n = fail n' err) : false :=\nbegin\n obtain ⟨np, a, hp⟩ := p.exists_done cb n,\n simpa [hp] using h\nend\n\n@[priority 100] -- see Note [lower instance priority]\ninstance conditionally_unfailing_of_unfailing [p.unfailing] : conditionally_unfailing p :=\n⟨λ _ _ _, p.exists_done _ _⟩\n\nlemma exists_done_in_bounds (p : parser α) [p.conditionally_unfailing] {cb : char_buffer} {n : ℕ}\n (h : n < cb.size) : ∃ (n' : ℕ) (a : α), p cb n = done n' a :=\nconditionally_unfailing.ex' h\n\nlemma conditionally_unfailing.of_fail [p.conditionally_unfailing] (h : p cb n = fail n' err)\n (hn : n < cb.size) : false :=\nbegin\n obtain ⟨np, a, hp⟩ := p.exists_done_in_bounds hn,\n simpa [hp] using h\nend\n\nlemma decorate_errors_fail (h : p cb n = fail n' err) :\n @decorate_errors α msgs p cb n = fail n ((dlist.lazy_of_list (msgs ()))) :=\nby simp [decorate_errors, h]\n\nlemma decorate_errors_success (h : p cb n = done n' a) :\n @decorate_errors α msgs p cb n = done n' a :=\nby simp [decorate_errors, h]\n\nlemma decorate_error_fail (h : p cb n = fail n' err) :\n @decorate_error α msg p cb n = fail n ((dlist.lazy_of_list ([msg ()]))) :=\ndecorate_errors_fail h\n\nlemma decorate_error_success (h : p cb n = done n' a) :\n @decorate_error α msg p cb n = done n' a :=\ndecorate_errors_success h\n\n@[simp] lemma decorate_errors_eq_done :\n @decorate_errors α msgs p cb n = done n' a ↔ p cb n = done n' a :=\nby cases h : p cb n; simp [decorate_errors, h]\n\n@[simp] lemma decorate_error_eq_done :\n @decorate_error α msg p cb n = done n' a ↔ p cb n = done n' a :=\ndecorate_errors_eq_done\n\n@[simp] lemma decorate_errors_eq_fail :\n @decorate_errors α msgs p cb n = fail n' err ↔\n n = n' ∧ err = dlist.lazy_of_list (msgs ()) ∧ ∃ np err', p cb n = fail np err' :=\nby cases h : p cb n; simp [decorate_errors, h, eq_comm]\n\n@[simp] lemma decorate_error_eq_fail :\n @decorate_error α msg p cb n = fail n' err ↔\n n = n' ∧ err = dlist.lazy_of_list ([msg ()]) ∧ ∃ np err', p cb n = fail np err' :=\ndecorate_errors_eq_fail\n\n@[simp] lemma return_eq_pure : (@return parser _ _ a) = pure a := rfl\n\nlemma pure_eq_done : (@pure parser _ _ a) = λ _ n, done n a := rfl\n\n@[simp] lemma pure_ne_fail : (pure a : parser α) cb n ≠ fail n' err := by simp [pure_eq_done]\n\nsection bind\n\nvariable (f : α → parser β)\n\n@[simp] lemma bind_eq_bind : p.bind f = p >>= f := rfl\n\nvariable {f}\n\n@[simp] lemma bind_eq_done :\n (p >>= f) cb n = done n' b ↔\n ∃ (np : ℕ) (a : α), p cb n = done np a ∧ f a cb np = done n' b :=\nby cases hp : p cb n; simp [hp, ←bind_eq_bind, parser.bind, and_assoc]\n\n@[simp] lemma bind_eq_fail :\n (p >>= f) cb n = fail n' err ↔\n (p cb n = fail n' err) ∨ (∃ (np : ℕ) (a : α), p cb n = done np a ∧ f a cb np = fail n' err) :=\nby cases hp : p cb n; simp [hp, ←bind_eq_bind, parser.bind, and_assoc]\n\n@[simp] lemma and_then_eq_bind {α β : Type} {m : Type → Type} [monad m] (a : m α) (b : m β) :\n a >> b = a >>= (λ _, b) := rfl\n\nlemma and_then_fail :\n (p >> return ()) cb n = parse_result.fail n' err ↔ p cb n = fail n' err :=\nby simp [pure_eq_done]\n\nlemma and_then_success :\n (p >> return ()) cb n = parse_result.done n' () ↔ ∃ a, p cb n = done n' a:=\nby simp [pure_eq_done]\n\nend bind\n\nsection map\n\nvariable {f : α → β}\n\n@[simp] lemma map_eq_done : (f <$> p) cb n = done n' b ↔\n ∃ (a : α), p cb n = done n' a ∧ f a = b :=\nby cases hp : p cb n; simp [←is_lawful_monad.bind_pure_comp_eq_map, hp, and_assoc, pure_eq_done]\n\n@[simp] lemma map_eq_fail : (f <$> p) cb n = fail n' err ↔ p cb n = fail n' err :=\nby simp [←bind_pure_comp_eq_map, pure_eq_done]\n\n@[simp] lemma map_const_eq_done {b'} : (b <$ p) cb n = done n' b' ↔\n ∃ (a : α), p cb n = done n' a ∧ b = b' :=\nby simp [map_const_eq]\n\n@[simp] lemma map_const_eq_fail : (b <$ p) cb n = fail n' err ↔ p cb n = fail n' err :=\nby simp only [map_const_eq, map_eq_fail]\n\nlemma map_const_rev_eq_done {b'} : (p $> b) cb n = done n' b' ↔\n ∃ (a : α), p cb n = done n' a ∧ b = b' :=\nmap_const_eq_done\n\nlemma map_rev_const_eq_fail : (p $> b) cb n = fail n' err ↔ p cb n = fail n' err :=\nmap_const_eq_fail\n\nend map\n\n@[simp] lemma orelse_eq_orelse : p.orelse q = (p <|> q) := rfl\n\n@[simp] lemma orelse_eq_done : (p <|> q) cb n = done n' a ↔\n (p cb n = done n' a ∨ (q cb n = done n' a ∧ ∃ err, p cb n = fail n err)) :=\nbegin\n cases hp : p cb n with np resp np errp,\n { simp [hp, ←orelse_eq_orelse, parser.orelse] },\n { by_cases hn : np = n,\n { cases hq : q cb n with nq resq nq errq,\n { simp [hp, hn, hq, ←orelse_eq_orelse, parser.orelse] },\n { rcases lt_trichotomy nq n with H|rfl|H;\n simp [hp, hn, hq, H, not_lt_of_lt H, lt_irrefl, ←orelse_eq_orelse, parser.orelse] <|>\n simp [hp, hn, hq, lt_irrefl, ←orelse_eq_orelse, parser.orelse] } },\n { simp [hp, hn, ←orelse_eq_orelse, parser.orelse] } }\nend\n\n@[simp] lemma orelse_eq_fail_eq : (p <|> q) cb n = fail n err ↔\n (p cb n = fail n err ∧ ∃ (nq errq), n < nq ∧ q cb n = fail nq errq) ∨\n (∃ (errp errq), p cb n = fail n errp ∧ q cb n = fail n errq ∧ errp ++ errq = err)\n :=\nbegin\n cases hp : p cb n with np resp np errp,\n { simp [hp, ←orelse_eq_orelse, parser.orelse] },\n { by_cases hn : np = n,\n { cases hq : q cb n with nq resq nq errq,\n { simp [hp, hn, hq, ←orelse_eq_orelse, parser.orelse] },\n { rcases lt_trichotomy nq n with H|rfl|H;\n simp [hp, hq, hn, ←orelse_eq_orelse, parser.orelse, H,\n ne_of_gt H, ne_of_lt H, not_lt_of_lt H] <|>\n simp [hp, hq, hn, ←orelse_eq_orelse, parser.orelse, lt_irrefl] } },\n { simp [hp, hn, ←orelse_eq_orelse, parser.orelse] } }\nend\n\nlemma orelse_eq_fail_not_mono_lt (hn : n' < n) : (p <|> q) cb n = fail n' err ↔\n (p cb n = fail n' err) ∨\n (q cb n = fail n' err ∧ (∃ (errp), p cb n = fail n errp)) :=\nbegin\n cases hp : p cb n with np resp np errp,\n { simp [hp, ←orelse_eq_orelse, parser.orelse] },\n { by_cases h : np = n,\n { cases hq : q cb n with nq resq nq errq,\n { simp [hp, h, hn, hq, ne_of_gt hn, ←orelse_eq_orelse, parser.orelse] },\n { rcases lt_trichotomy nq n with H|H|H,\n { simp [hp, hq, h, H, ne_of_gt hn, not_lt_of_lt H, ←orelse_eq_orelse, parser.orelse] },\n { simp [hp, hq, h, H, ne_of_gt hn, lt_irrefl, ←orelse_eq_orelse, parser.orelse] },\n { simp [hp, hq, h, H, ne_of_gt (hn.trans H), ←orelse_eq_orelse, parser.orelse] } } },\n { simp [hp, h, ←orelse_eq_orelse, parser.orelse] } }\nend\n\nlemma orelse_eq_fail_of_mono_ne [q.mono] (hn : n ≠ n') :\n (p <|> q) cb n = fail n' err ↔ p cb n = fail n' err :=\nbegin\n cases hp : p cb n with np resp np errp,\n { simp [hp, ←orelse_eq_orelse, parser.orelse] },\n { by_cases h : np = n,\n { cases hq : q cb n with nq resq nq errq,\n { simp [hp, h, hn, hq, hn, ←orelse_eq_orelse, parser.orelse] },\n { have : n ≤ nq := mono.of_fail hq,\n rcases eq_or_lt_of_le this with rfl|H,\n { simp [hp, hq, h, hn, lt_irrefl, ←orelse_eq_orelse, parser.orelse] },\n { simp [hp, hq, h, hn, H, ←orelse_eq_orelse, parser.orelse] } } },\n { simp [hp, h, ←orelse_eq_orelse, parser.orelse] } },\nend\n\n@[simp] lemma failure_eq_failure : @parser.failure α = failure := rfl\n\n@[simp] lemma failure_def : (failure : parser α) cb n = fail n dlist.empty := rfl\n\nlemma not_failure_eq_done : ¬ (failure : parser α) cb n = done n' a :=\nby simp\n\nlemma failure_eq_fail : (failure : parser α) cb n = fail n' err ↔ n = n' ∧ err = dlist.empty :=\nby simp [eq_comm]\n\nlemma seq_eq_done {f : parser (α → β)} {p : parser α} : (f <*> p) cb n = done n' b ↔\n ∃ (nf : ℕ) (f' : α → β) (a : α), f cb n = done nf f' ∧ p cb nf = done n' a ∧ f' a = b :=\nby simp [seq_eq_bind_map]\n\nlemma seq_eq_fail {f : parser (α → β)} {p : parser α} : (f <*> p) cb n = fail n' err ↔\n (f cb n = fail n' err) ∨ (∃ (nf : ℕ) (f' : α → β), f cb n = done nf f' ∧ p cb nf = fail n' err) :=\nby simp [seq_eq_bind_map]\n\nlemma seq_left_eq_done {p : parser α} {q : parser β} : (p <* q) cb n = done n' a ↔\n ∃ (np : ℕ) (b : β), p cb n = done np a ∧ q cb np = done n' b :=\nbegin\n have : ∀ (p q : ℕ → α → Prop),\n (∃ (np : ℕ) (x : α), p np x ∧ q np x ∧ x = a) ↔ ∃ (np : ℕ), p np a ∧ q np a :=\n λ _ _, ⟨λ ⟨np, x, hp, hq, rfl⟩, ⟨np, hp, hq⟩, λ ⟨np, hp, hq⟩, ⟨np, a, hp, hq, rfl⟩⟩,\n simp [seq_left_eq, seq_eq_done, map_eq_done, this]\nend\n\nlemma seq_left_eq_fail {p : parser α} {q : parser β} : (p <* q) cb n = fail n' err ↔\n (p cb n = fail n' err) ∨ (∃ (np : ℕ) (a : α), p cb n = done np a ∧ q cb np = fail n' err) :=\nby simp [seq_left_eq, seq_eq_fail]\n\nlemma seq_right_eq_done {p : parser α} {q : parser β} : (p *> q) cb n = done n' b ↔\n ∃ (np : ℕ) (a : α), p cb n = done np a ∧ q cb np = done n' b :=\nby simp [seq_right_eq, seq_eq_done, map_eq_done, and.comm, and.assoc]\n\nlemma seq_right_eq_fail {p : parser α} {q : parser β} : (p *> q) cb n = fail n' err ↔\n (p cb n = fail n' err) ∨ (∃ (np : ℕ) (a : α), p cb n = done np a ∧ q cb np = fail n' err) :=\nby simp [seq_right_eq, seq_eq_fail]\n\nlemma mmap_eq_done {f : α → parser β} {a : α} {l : list α} {b : β} {l' : list β} :\n (a :: l).mmap f cb n = done n' (b :: l') ↔\n ∃ (np : ℕ), f a cb n = done np b ∧ l.mmap f cb np = done n' l' :=\nby simp [mmap, and.comm, and.assoc, and.left_comm, pure_eq_done]\n\nlemma mmap'_eq_done {f : α → parser β} {a : α} {l : list α} :\n (a :: l).mmap' f cb n = done n' () ↔\n ∃ (np : ℕ) (b : β), f a cb n = done np b ∧ l.mmap' f cb np = done n' () :=\nby simp [mmap']\n\nlemma guard_eq_done {p : Prop} [decidable p] {u : unit} :\n @guard parser _ p _ cb n = done n' u ↔ p ∧ n = n' :=\nby { by_cases hp : p; simp [guard, hp, pure_eq_done] }\n\nlemma guard_eq_fail {p : Prop} [decidable p] :\n @guard parser _ p _ cb n = fail n' err ↔ (¬ p) ∧ n = n' ∧ err = dlist.empty :=\nby { by_cases hp : p; simp [guard, hp, eq_comm, pure_eq_done] }\n\nnamespace mono\n\nvariables {sep : parser unit}\n\ninstance pure : mono (pure a) :=\n⟨λ _ _, by simp [pure_eq_done]⟩\n\ninstance bind {f : α → parser β} [p.mono] [∀ a, (f a).mono] :\n (p >>= f).mono :=\nbegin\n constructor,\n intros cb n,\n cases hx : (p >>= f) cb n,\n { obtain ⟨n', a, h, h'⟩ := bind_eq_done.mp hx,\n refine le_trans (of_done h) _,\n simpa [h'] using of_done h' },\n { obtain h | ⟨n', a, h, h'⟩ := bind_eq_fail.mp hx,\n { simpa [h] using of_fail h },\n { refine le_trans (of_done h) _,\n simpa [h'] using of_fail h' } }\nend\n\ninstance and_then {q : parser β} [p.mono] [q.mono] : (p >> q).mono := mono.bind\n\ninstance map [p.mono] {f : α → β} : (f <$> p).mono := mono.bind\n\ninstance seq {f : parser (α → β)} [f.mono] [p.mono] : (f <*> p).mono := mono.bind\n\ninstance mmap : Π {l : list α} {f : α → parser β} [∀ a ∈ l, (f a).mono],\n (l.mmap f).mono\n| [] _ _ := mono.pure\n| (a :: l) f h := begin\n convert mono.bind,\n { exact h _ (list.mem_cons_self _ _) },\n { intro,\n convert mono.map,\n convert mmap,\n exact (λ _ ha, h _ (list.mem_cons_of_mem _ ha)) }\nend\n\ninstance mmap' : Π {l : list α} {f : α → parser β} [∀ a ∈ l, (f a).mono],\n (l.mmap' f).mono\n| [] _ _ := mono.pure\n| (a :: l) f h := begin\n convert mono.and_then,\n { exact h _ (list.mem_cons_self _ _) },\n { convert mmap',\n exact (λ _ ha, h _ (list.mem_cons_of_mem _ ha)) }\nend\n\ninstance failure : (failure : parser α).mono :=\n⟨by simp [le_refl]⟩\n\ninstance guard {p : Prop} [decidable p] : mono (guard p) :=\n⟨by { by_cases h : p; simp [h, pure_eq_done, le_refl] }⟩\n\ninstance orelse [p.mono] [q.mono] : (p <|> q).mono :=\nbegin\n constructor,\n intros cb n,\n cases hx : (p <|> q) cb n with posx resx posx errx,\n { obtain h | ⟨h, -, -⟩ := orelse_eq_done.mp hx;\n simpa [h] using of_done h },\n { by_cases h : n = posx,\n { simp [hx, h] },\n { simp only [orelse_eq_fail_of_mono_ne h] at hx,\n exact of_fail hx } }\nend\n\ninstance decorate_errors [p.mono] :\n (@decorate_errors α msgs p).mono :=\nbegin\n constructor,\n intros cb n,\n cases h : p cb n,\n { simpa [decorate_errors, h] using of_done h },\n { simp [decorate_errors, h] }\nend\n\ninstance decorate_error [p.mono] : (@decorate_error α msg p).mono :=\nmono.decorate_errors\n\ninstance any_char : mono any_char :=\nbegin\n constructor,\n intros cb n,\n by_cases h : n < cb.size;\n simp [any_char, h],\nend\n\ninstance sat {p : char → Prop} [decidable_pred p] : mono (sat p) :=\nbegin\n constructor,\n intros cb n,\n simp only [sat],\n split_ifs;\n simp\nend\n\ninstance eps : mono eps := mono.pure\n\ninstance ch {c : char} : mono (ch c) := mono.decorate_error\n\ninstance char_buf {s : char_buffer} : mono (char_buf s) :=\nmono.decorate_error\n\ninstance one_of {cs : list char} : (one_of cs).mono :=\nmono.decorate_errors\n\ninstance one_of' {cs : list char} : (one_of' cs).mono :=\nmono.and_then\n\ninstance str {s : string} : (str s).mono :=\nmono.decorate_error\n\ninstance remaining : remaining.mono :=\n⟨λ _ _, le_refl _⟩\n\ninstance eof : eof.mono :=\nmono.decorate_error\n\ninstance foldr_core {f : α → β → β} {b : β} [p.mono] :\n ∀ {reps : ℕ}, (foldr_core f p b reps).mono\n| 0 := mono.failure\n| (reps + 1) := begin\n convert mono.orelse,\n { convert mono.bind,\n { apply_instance },\n { exact λ _, @mono.bind _ _ _ _ foldr_core _ } },\n { exact mono.pure }\nend\n\ninstance foldr {f : α → β → β} [p.mono] : mono (foldr f p b) :=\n⟨λ _ _, by { convert mono.le (foldr_core f p b _) _ _, exact mono.foldr_core }⟩\n\ninstance foldl_core {f : α → β → α} {p : parser β} [p.mono] :\n ∀ {a : α} {reps : ℕ}, (foldl_core f a p reps).mono\n| _ 0 := mono.failure\n| _ (reps + 1) := begin\n convert mono.orelse,\n { convert mono.bind,\n { apply_instance },\n { exact λ _, foldl_core } },\n { exact mono.pure }\nend\n\ninstance foldl {f : α → β → α} {p : parser β} [p.mono] : mono (foldl f a p) :=\n⟨λ _ _, by { convert mono.le (foldl_core f a p _) _ _, exact mono.foldl_core }⟩\n\ninstance many [p.mono] : p.many.mono :=\nmono.foldr\n\ninstance many_char {p : parser char} [p.mono] : p.many_char.mono :=\nmono.map\n\ninstance many' [p.mono] : p.many'.mono :=\nmono.and_then\n\ninstance many1 [p.mono] : p.many1.mono :=\nmono.seq\n\ninstance many_char1 {p : parser char} [p.mono] : p.many_char1.mono :=\nmono.map\n\ninstance sep_by1 [p.mono] [sep.mono] : mono (sep_by1 sep p) :=\nmono.seq\n\ninstance sep_by [p.mono] [hs : sep.mono] : mono (sep_by sep p) :=\nmono.orelse\n\nlemma fix_core {F : parser α → parser α} (hF : ∀ (p : parser α), p.mono → (F p).mono) :\n ∀ (max_depth : ℕ), mono (fix_core F max_depth)\n| 0 := mono.failure\n| (max_depth + 1) := hF _ (fix_core _)\n\ninstance digit : digit.mono :=\nmono.decorate_error\n\ninstance nat : nat.mono :=\nmono.decorate_error\n\nlemma fix {F : parser α → parser α} (hF : ∀ (p : parser α), p.mono → (F p).mono) :\n mono (fix F) :=\n⟨λ _ _, by { convert mono.le (parser.fix_core F _) _ _, exact fix_core hF _ }⟩\n\nend mono\n\n@[simp] lemma orelse_pure_eq_fail : (p <|> pure a) cb n = fail n' err ↔\n p cb n = fail n' err ∧ n ≠ n' :=\nbegin\n by_cases hn : n = n',\n { simp [hn, pure_eq_done] },\n { simp [orelse_eq_fail_of_mono_ne, hn] }\nend\n\nend defn_lemmas\n\nsection done\n\nvariables {α β : Type} {cb : char_buffer} {n n' : ℕ} {a a' : α} {b : β} {c : char} {u : unit}\n {err : dlist string}\n\nlemma any_char_eq_done : any_char cb n = done n' c ↔\n ∃ (hn : n < cb.size), n' = n + 1 ∧ cb.read ⟨n, hn⟩ = c :=\nbegin\n simp_rw [any_char],\n split_ifs with h;\n simp [h, eq_comm]\nend\n\nlemma any_char_eq_fail : any_char cb n = fail n' err ↔ n = n' ∧ err = dlist.empty ∧ cb.size ≤ n :=\nbegin\n simp_rw [any_char],\n split_ifs with h;\n simp [←not_lt, h, eq_comm]\nend\n\nlemma sat_eq_done {p : char → Prop} [decidable_pred p] : sat p cb n = done n' c ↔\n ∃ (hn : n < cb.size), p c ∧ n' = n + 1 ∧ cb.read ⟨n, hn⟩ = c :=\nbegin\n by_cases hn : n < cb.size,\n { by_cases hp : p (cb.read ⟨n, hn⟩),\n { simp only [sat, hn, hp, dif_pos, if_true, exists_prop_of_true],\n split,\n { rintro ⟨rfl, rfl⟩, simp [hp] },\n { rintro ⟨-, rfl, rfl⟩, simp } },\n { simp only [sat, hn, hp, dif_pos, false_iff, not_and, exists_prop_of_true, if_false],\n rintro H - rfl,\n exact hp H } },\n { simp [sat, hn] }\nend\n\nlemma sat_eq_fail {p : char → Prop} [decidable_pred p] : sat p cb n = fail n' err ↔\n n = n' ∧ err = dlist.empty ∧ ∀ (h : n < cb.size), ¬ p (cb.read ⟨n, h⟩) :=\nbegin\n dsimp only [sat],\n split_ifs;\n simp [*, eq_comm]\nend\n\nlemma eps_eq_done : eps cb n = done n' u ↔ n = n' := by simp [eps, pure_eq_done]\n\nlemma ch_eq_done : ch c cb n = done n' u ↔ ∃ (hn : n < cb.size), n' = n + 1 ∧ cb.read ⟨n, hn⟩ = c :=\nby simp [ch, eps_eq_done, sat_eq_done, and.comm, @eq_comm _ n']\n\nlemma char_buf_eq_done {cb' : char_buffer} : char_buf cb' cb n = done n' u ↔\n n + cb'.size = n' ∧ cb'.to_list <+: (cb.to_list.drop n) :=\nbegin\n simp only [char_buf, decorate_error_eq_done, ne.def, ←buffer.length_to_list],\n induction cb'.to_list with hd tl hl generalizing cb n n',\n { simp [pure_eq_done, mmap'_eq_done, -buffer.length_to_list, list.nil_prefix] },\n { simp only [ch_eq_done, and.comm, and.assoc, and.left_comm, hl, mmap', and_then_eq_bind,\n bind_eq_done, list.length, exists_and_distrib_left, exists_const],\n split,\n { rintro ⟨np, h, rfl, rfl, hn, rfl⟩,\n simp only [add_comm, add_left_comm, h, true_and, eq_self_iff_true, and_true],\n have : n < cb.to_list.length := by simpa using hn,\n rwa [←buffer.nth_le_to_list _ this, ←list.cons_nth_le_drop_succ this, list.prefix_cons_inj] },\n { rintro ⟨h, rfl⟩,\n by_cases hn : n < cb.size,\n { have : n < cb.to_list.length := by simpa using hn,\n rw [←list.cons_nth_le_drop_succ this, list.cons_prefix_iff] at h,\n use [n + 1, h.right],\n simpa [buffer.nth_le_to_list, add_comm, add_left_comm, add_assoc, hn] using h.left.symm },\n { have : cb.to_list.length ≤ n := by simpa using hn,\n rw list.drop_eq_nil_of_le this at h,\n simpa using h } } }\nend\n\nlemma one_of_eq_done {cs : list char} : one_of cs cb n = done n' c ↔\n ∃ (hn : n < cb.size), c ∈ cs ∧ n' = n + 1 ∧ cb.read ⟨n, hn⟩ = c :=\nby simp [one_of, sat_eq_done]\n\nlemma one_of'_eq_done {cs : list char} : one_of' cs cb n = done n' u ↔\n ∃ (hn : n < cb.size), cb.read ⟨n, hn⟩ ∈ cs ∧ n' = n + 1 :=\nbegin\n simp only [one_of', one_of_eq_done, eps_eq_done, and.comm, and_then_eq_bind, bind_eq_done,\n exists_eq_left, exists_and_distrib_left],\n split,\n { rintro ⟨c, hc, rfl, hn, rfl⟩,\n exact ⟨rfl, hn, hc⟩ },\n { rintro ⟨rfl, hn, hc⟩,\n exact ⟨cb.read ⟨n, hn⟩, hc, rfl, hn, rfl⟩ }\nend\n\nlemma str_eq_char_buf (s : string) : str s = char_buf s.to_list.to_buffer :=\nbegin\n ext cb n,\n rw [str, char_buf],\n congr,\n { simp [buffer.to_string, string.as_string_inv_to_list] },\n { simp }\nend\n\nlemma str_eq_done {s : string} : str s cb n = done n' u ↔\n n + s.length = n' ∧ s.to_list <+: (cb.to_list.drop n) :=\nby simp [str_eq_char_buf, char_buf_eq_done]\n\nlemma remaining_eq_done {r : ℕ} : remaining cb n = done n' r ↔ n = n' ∧ cb.size - n = r :=\nby simp [remaining]\n\nlemma remaining_ne_fail : remaining cb n ≠ fail n' err :=\nby simp [remaining]\n\nlemma eof_eq_done {u : unit} : eof cb n = done n' u ↔ n = n' ∧ cb.size ≤ n :=\nby simp [eof, guard_eq_done, remaining_eq_done, nat.sub_eq_zero_iff_le, and_comm, and_assoc]\n\n@[simp] lemma foldr_core_zero_eq_done {f : α → β → β} {p : parser α} {b' : β} :\n foldr_core f p b 0 cb n ≠ done n' b' :=\nby simp [foldr_core]\n\nlemma foldr_core_eq_done {f : α → β → β} {p : parser α} {reps : ℕ} {b' : β} :\n foldr_core f p b (reps + 1) cb n = done n' b' ↔\n (∃ (np : ℕ) (a : α) (xs : β), p cb n = done np a ∧ foldr_core f p b reps cb np = done n' xs\n ∧ f a xs = b') ∨\n (n = n' ∧ b = b' ∧ ∃ (err), (p cb n = fail n err) ∨\n (∃ (np : ℕ) (a : α), p cb n = done np a ∧ foldr_core f p b reps cb np = fail n err)) :=\nby simp [foldr_core, and.comm, and.assoc, pure_eq_done]\n\n@[simp] lemma foldr_core_zero_eq_fail {f : α → β → β} {p : parser α} {err : dlist string} :\n foldr_core f p b 0 cb n = fail n' err ↔ n = n' ∧ err = dlist.empty :=\nby simp [foldr_core, eq_comm]\n\nlemma foldr_core_succ_eq_fail {f : α → β → β} {p : parser α} {reps : ℕ} {err : dlist string} :\n foldr_core f p b (reps + 1) cb n = fail n' err ↔ n ≠ n' ∧\n (p cb n = fail n' err ∨\n ∃ (np : ℕ) (a : α), p cb n = done np a ∧ foldr_core f p b reps cb np = fail n' err) :=\nby simp [foldr_core, and_comm]\n\nlemma foldr_eq_done {f : α → β → β} {p : parser α} {b' : β} :\n foldr f p b cb n = done n' b' ↔\n ((∃ (np : ℕ) (a : α) (x : β), p cb n = done np a ∧\n foldr_core f p b (cb.size - n) cb np = done n' x ∧ f a x = b') ∨\n (n = n' ∧ b = b' ∧ (∃ (err), p cb n = parse_result.fail n err ∨\n ∃ (np : ℕ) (x : α), p cb n = done np x ∧ foldr_core f p b (cb.size - n) cb np = fail n err))) :=\nby simp [foldr, foldr_core_eq_done]\n\nlemma foldr_eq_fail_iff_mono_at_end {f : α → β → β} {p : parser α} {err : dlist string}\n [p.mono] (hc : cb.size ≤ n) : foldr f p b cb n = fail n' err ↔\n n < n' ∧ (p cb n = fail n' err ∨ ∃ (a : α), p cb n = done n' a ∧ err = dlist.empty) :=\nbegin\n have : cb.size - n = 0 := nat.sub_eq_zero_of_le hc,\n simp only [foldr, foldr_core_succ_eq_fail, this, and.left_comm, foldr_core_zero_eq_fail,\n ne_iff_lt_iff_le, exists_and_distrib_right, exists_eq_left, and.congr_left_iff,\n exists_and_distrib_left],\n rintro (h | ⟨⟨a, h⟩, rfl⟩),\n { exact mono.of_fail h },\n { exact mono.of_done h }\nend\n\nlemma foldr_eq_fail {f : α → β → β} {p : parser α} {err : dlist string} :\n foldr f p b cb n = fail n' err ↔ n ≠ n' ∧ (p cb n = fail n' err ∨\n ∃ (np : ℕ) (a : α), p cb n = done np a ∧ foldr_core f p b (cb.size - n) cb np = fail n' err) :=\nby simp [foldr, foldr_core_succ_eq_fail]\n\n@[simp] lemma foldl_core_zero_eq_done {f : β → α → β} {p : parser α} {b' : β} :\n foldl_core f b p 0 cb n = done n' b' ↔ false :=\nby simp [foldl_core]\n\nlemma foldl_core_eq_done {f : β → α → β} {p : parser α} {reps : ℕ} {b' : β} :\n foldl_core f b p (reps + 1) cb n = done n' b' ↔\n (∃ (np : ℕ) (a : α), p cb n = done np a ∧ foldl_core f (f b a) p reps cb np = done n' b') ∨\n (n = n' ∧ b = b' ∧ ∃ (err), (p cb n = fail n err) ∨\n (∃ (np : ℕ) (a : α), p cb n = done np a ∧ foldl_core f (f b a) p reps cb np = fail n err)) :=\nby simp [foldl_core, and.assoc, pure_eq_done]\n\n@[simp] lemma foldl_core_zero_eq_fail {f : β → α → β} {p : parser α} {err : dlist string} :\n foldl_core f b p 0 cb n = fail n' err ↔ n = n' ∧ err = dlist.empty :=\nby simp [foldl_core, eq_comm]\n\nlemma foldl_core_succ_eq_fail {f : β → α → β} {p : parser α} {reps : ℕ} {err : dlist string} :\n foldl_core f b p (reps + 1) cb n = fail n' err ↔ n ≠ n' ∧\n (p cb n = fail n' err ∨\n ∃ (np : ℕ) (a : α), p cb n = done np a ∧ foldl_core f (f b a) p reps cb np = fail n' err) :=\nby simp [foldl_core, and_comm]\n\nlemma foldl_eq_done {f : β → α → β} {p : parser α} {b' : β} :\n foldl f b p cb n = done n' b' ↔\n (∃ (np : ℕ) (a : α), p cb n = done np a ∧\n foldl_core f (f b a) p (cb.size - n) cb np = done n' b') ∨\n (n = n' ∧ b = b' ∧ ∃ (err), (p cb n = fail n err) ∨\n (∃ (np : ℕ) (a : α), p cb n = done np a ∧\n foldl_core f (f b a) p (cb.size - n) cb np = fail n err)) :=\nby simp [foldl, foldl_core_eq_done]\n\nlemma foldl_eq_fail {f : β → α → β} {p : parser α} {err : dlist string} :\n foldl f b p cb n = fail n' err ↔ n ≠ n' ∧ (p cb n = fail n' err ∨\n ∃ (np : ℕ) (a : α), p cb n = done np a ∧\n foldl_core f (f b a) p (cb.size - n) cb np = fail n' err) :=\nby simp [foldl, foldl_core_succ_eq_fail]\n\nlemma foldl_eq_fail_iff_mono_at_end {f : β → α → β} {p : parser α} {err : dlist string}\n [p.mono] (hc : cb.size ≤ n) : foldl f b p cb n = fail n' err ↔\n n < n' ∧ (p cb n = fail n' err ∨ ∃ (a : α), p cb n = done n' a ∧ err = dlist.empty) :=\nbegin\n have : cb.size - n = 0 := nat.sub_eq_zero_of_le hc,\n simp only [foldl, foldl_core_succ_eq_fail, this, and.left_comm, ne_iff_lt_iff_le, exists_eq_left,\n exists_and_distrib_right, and.congr_left_iff, exists_and_distrib_left,\n foldl_core_zero_eq_fail],\n rintro (h | ⟨⟨a, h⟩, rfl⟩),\n { exact mono.of_fail h },\n { exact mono.of_done h }\nend\n\nlemma many_eq_done_nil {p : parser α} : many p cb n = done n' (@list.nil α) ↔ n = n' ∧\n ∃ (err), p cb n = fail n err ∨ ∃ (np : ℕ) (a : α), p cb n = done np a ∧\n foldr_core list.cons p [] (cb.size - n) cb np = fail n err :=\nby simp [many, foldr_eq_done]\n\nlemma many_eq_done {p : parser α} {x : α} {xs : list α} :\n many p cb n = done n' (x :: xs) ↔ ∃ (np : ℕ), p cb n = done np x\n ∧ foldr_core list.cons p [] (cb.size - n) cb np = done n' xs :=\nby simp [many, foldr_eq_done, and.comm, and.assoc, and.left_comm]\n\nlemma many_eq_fail {p : parser α} {err : dlist string} :\n many p cb n = fail n' err ↔ n ≠ n' ∧ (p cb n = fail n' err ∨\n ∃ (np : ℕ) (a : α), p cb n = done np a ∧\n foldr_core list.cons p [] (cb.size - n) cb np = fail n' err) :=\nby simp [many, foldr_eq_fail]\n\nlemma many_char_eq_done_empty {p : parser char} : many_char p cb n = done n' string.empty ↔ n = n' ∧\n ∃ (err), p cb n = fail n err ∨ ∃ (np : ℕ) (c : char), p cb n = done np c ∧\n foldr_core list.cons p [] (cb.size - n) cb np = fail n err :=\nby simp [many_char, many_eq_done_nil, map_eq_done, list.as_string_eq]\n\nlemma many_char_eq_done_not_empty {p : parser char} {s : string} (h : s ≠ \"\") :\n many_char p cb n = done n' s ↔ ∃ (np : ℕ), p cb n = done np s.head ∧\n foldr_core list.cons p list.nil (buffer.size cb - n) cb np = done n' (s.popn 1).to_list :=\nby simp [many_char, list.as_string_eq, string.to_list_nonempty h, many_eq_done]\n\nlemma many_char_eq_many_of_to_list {p : parser char} {s : string} :\n many_char p cb n = done n' s ↔ many p cb n = done n' s.to_list :=\nby simp [many_char, list.as_string_eq]\n\nlemma many'_eq_done {p : parser α} : many' p cb n = done n' u ↔\n many p cb n = done n' [] ∨ ∃ (np : ℕ) (a : α) (l : list α), many p cb n = done n' (a :: l)\n ∧ p cb n = done np a ∧ foldr_core list.cons p [] (buffer.size cb - n) cb np = done n' l :=\nbegin\n simp only [many', eps_eq_done, many, foldr, and_then_eq_bind, exists_and_distrib_right,\n bind_eq_done, exists_eq_right],\n split,\n { rintro ⟨_ | ⟨hd, tl⟩, hl⟩,\n { exact or.inl hl },\n { have hl2 := hl,\n simp only [foldr_core_eq_done, or_false, exists_and_distrib_left, and_false, false_and,\n exists_eq_right_right] at hl,\n obtain ⟨np, hp, h⟩ := hl,\n refine or.inr ⟨np, _, _, hl2, hp, h⟩ } },\n { rintro (h | ⟨np, a, l, hp, h⟩),\n { exact ⟨[], h⟩ },\n { refine ⟨a :: l, hp⟩ } }\nend\n\n@[simp] lemma many1_ne_done_nil {p : parser α} : many1 p cb n ≠ done n' [] :=\nby simp [many1, seq_eq_done]\n\nlemma many1_eq_done {p : parser α} {l : list α} : many1 p cb n = done n' (a :: l) ↔\n ∃ (np : ℕ), p cb n = done np a ∧ many p cb np = done n' l :=\nby simp [many1, seq_eq_done, map_eq_done]\n\n\n\n@[simp] lemma many_char1_ne_empty {p : parser char} : many_char1 p cb n ≠ done n' \"\" :=\nby simp [many_char1, ←string.nil_as_string_eq_empty]\n\nlemma many_char1_eq_done {p : parser char} {s : string} (h : s ≠ \"\") :\n many_char1 p cb n = done n' s ↔\n ∃ (np : ℕ), p cb n = done np s.head ∧ many_char p cb np = done n' (s.popn 1) :=\nby simp [many_char1, list.as_string_eq, string.to_list_nonempty h, many1_eq_done,\n many_char_eq_many_of_to_list]\n\n@[simp] lemma sep_by1_ne_done_nil {sep : parser unit} {p : parser α} :\n sep_by1 sep p cb n ≠ done n' [] :=\nby simp [sep_by1, seq_eq_done]\n\nlemma sep_by1_eq_done {sep : parser unit} {p : parser α} {l : list α} :\n sep_by1 sep p cb n = done n' (a :: l) ↔ ∃ (np : ℕ), p cb n = done np a ∧\n (sep >> p).many cb np = done n' l :=\nby simp [sep_by1, seq_eq_done]\n\nlemma sep_by_eq_done_nil {sep : parser unit} {p : parser α} :\n sep_by sep p cb n = done n' [] ↔ n = n' ∧ ∃ (err), sep_by1 sep p cb n = fail n err :=\nby simp [sep_by, pure_eq_done]\n\n@[simp] lemma fix_core_ne_done_zero {F : parser α → parser α} :\n fix_core F 0 cb n ≠ done n' a :=\nby simp [fix_core]\n\nlemma fix_core_eq_done {F : parser α → parser α} {max_depth : ℕ} :\n fix_core F (max_depth + 1) cb n = done n' a ↔ F (fix_core F max_depth) cb n = done n' a :=\nby simp [fix_core]\n\nlemma digit_eq_done {k : ℕ} : digit cb n = done n' k ↔ ∃ (hn : n < cb.size), n' = n + 1 ∧ k ≤ 9 ∧\n (cb.read ⟨n, hn⟩).to_nat - '0'.to_nat = k ∧ '0' ≤ cb.read ⟨n, hn⟩ ∧ cb.read ⟨n, hn⟩ ≤ '9' :=\nbegin\n have c9 : '9'.to_nat - '0'.to_nat = 9 := rfl,\n have l09 : '0'.to_nat ≤ '9'.to_nat := dec_trivial,\n have le_iff_le : ∀ {c c' : char}, c ≤ c' ↔ c.to_nat ≤ c'.to_nat := λ _ _, iff.rfl,\n split,\n { simp only [digit, sat_eq_done, pure_eq_done, decorate_error_eq_done, bind_eq_done, ←c9],\n rintro ⟨np, c, ⟨hn, ⟨ge0, le9⟩, rfl, rfl⟩, rfl, rfl⟩,\n simpa [hn, ge0, le9, true_and, and_true, eq_self_iff_true, exists_prop_of_true,\n nat.sub_le_sub_right_iff, l09] using (le_iff_le.mp le9) },\n { simp only [digit, sat_eq_done, pure_eq_done, decorate_error_eq_done, bind_eq_done, ←c9,\n le_iff_le],\n rintro ⟨hn, rfl, -, rfl, ge0, le9⟩,\n use [n + 1, cb.read ⟨n, hn⟩],\n simp [hn, ge0, le9] }\nend\n\nlemma digit_eq_fail : digit cb n = fail n' err ↔ n = n' ∧ err = dlist.of_list [\"\"] ∧\n ∀ (h : n < cb.size), ¬ ((λ c, '0' ≤ c ∧ c ≤ '9') (cb.read ⟨n, h⟩)) :=\nby simp [digit, sat_eq_fail]\n\n\nend done\n\nnamespace static\n\nvariables {α β : Type} {p q : parser α} {msgs : thunk (list string)} {msg : thunk string}\n {cb : char_buffer} {n' n : ℕ} {err : dlist string} {a : α} {b : β} {sep : parser unit}\n\nlemma not_of_ne (h : p cb n = done n' a) (hne : n ≠ n') : ¬ static p :=\nby { introI, exact hne (of_done h) }\n\ninstance pure : static (pure a) :=\n⟨λ _ _ _ _, by { simp_rw pure_eq_done, rw [and.comm], simp }⟩\n\ninstance bind {f : α → parser β} [p.static] [∀ a, (f a).static] :\n (p >>= f).static :=\n⟨λ _ _ _ _, by { rw bind_eq_done, rintro ⟨_, _, hp, hf⟩, exact trans (of_done hp) (of_done hf) }⟩\n\ninstance and_then {q : parser β} [p.static] [q.static] : (p >> q).static := static.bind\n\ninstance map [p.static] {f : α → β} : (f <$> p).static :=\n⟨λ _ _ _ _, by { simp_rw map_eq_done, rintro ⟨_, hp, _⟩, exact of_done hp }⟩\n\ninstance seq {f : parser (α → β)} [f.static] [p.static] : (f <*> p).static := static.bind\n\ninstance mmap : Π {l : list α} {f : α → parser β} [∀ a, (f a).static], (l.mmap f).static\n| [] _ _ := static.pure\n| (a :: l) _ h := begin\n convert static.bind,\n { exact h _ },\n { intro,\n convert static.bind,\n { convert mmap,\n exact h },\n { exact λ _, static.pure } }\nend\n\ninstance mmap' : Π {l : list α} {f : α → parser β} [∀ a, (f a).static], (l.mmap' f).static\n| [] _ _ := static.pure\n| (a :: l) _ h := begin\n convert static.and_then,\n { exact h _ },\n { convert mmap',\n exact h }\nend\n\ninstance failure : @parser.static α failure :=\n⟨λ _ _ _ _, by simp⟩\n\ninstance guard {p : Prop} [decidable p] : static (guard p) :=\n⟨λ _ _ _ _, by simp [guard_eq_done]⟩\n\ninstance orelse [p.static] [q.static] : (p <|> q).static :=\n⟨λ _ _ _ _, by { simp_rw orelse_eq_done, rintro (h | ⟨h, -⟩); exact of_done h }⟩\n\ninstance decorate_errors [p.static] :\n (@decorate_errors α msgs p).static :=\n⟨λ _ _ _ _, by { rw decorate_errors_eq_done, exact of_done }⟩\n\ninstance decorate_error [p.static] : (@decorate_error α msg p).static :=\nstatic.decorate_errors\n\nlemma any_char : ¬ static any_char :=\nbegin\n have : any_char \"s\".to_char_buffer 0 = done 1 's',\n { have : 0 < \"s\".to_char_buffer.size := dec_trivial,\n simpa [any_char_eq_done, this] },\n exact not_of_ne this zero_ne_one\nend\n\nlemma sat_iff {p : char → Prop} [decidable_pred p] : static (sat p) ↔ ∀ c, ¬ p c :=\nbegin\n split,\n { introI,\n intros c hc,\n have : sat p [c].to_buffer 0 = done 1 c := by simp [sat_eq_done, hc],\n exact zero_ne_one (of_done this) },\n { contrapose!,\n simp only [iff, sat_eq_done, and_imp, exists_prop, exists_and_distrib_right,\n exists_and_distrib_left, exists_imp_distrib, not_forall],\n rintros _ _ _ a h hne rfl hp -,\n exact ⟨a, hp⟩ }\nend\n\ninstance sat : static (sat (λ _, false)) :=\nby { apply sat_iff.mpr, simp }\n\ninstance eps : static eps := static.pure\n\nlemma ch (c : char) : ¬ static (ch c) :=\nbegin\n have : ch c [c].to_buffer 0 = done 1 (),\n { have : 0 < [c].to_buffer.size := dec_trivial,\n simp [ch_eq_done, this] },\n exact not_of_ne this zero_ne_one\nend\n\nlemma char_buf_iff {cb' : char_buffer} : static (char_buf cb') ↔ cb' = buffer.nil :=\nbegin\n rw ←buffer.size_eq_zero_iff,\n have : char_buf cb' cb' 0 = done cb'.size () := by simp [char_buf_eq_done],\n cases hc : cb'.size with n,\n { simp only [eq_self_iff_true, iff_true],\n exact ⟨λ _ _ _ _ h, by simpa [hc] using (char_buf_eq_done.mp h).left⟩ },\n { rw hc at this,\n simpa [nat.succ_ne_zero] using not_of_ne this (nat.succ_ne_zero n).symm }\nend\n\nlemma one_of_iff {cs : list char} : static (one_of cs) ↔ cs = [] :=\nbegin\n cases cs with hd tl,\n { simp [one_of, static.decorate_errors] },\n { have : one_of (hd :: tl) (hd :: tl).to_buffer 0 = done 1 hd,\n { simp [one_of_eq_done] },\n simpa using not_of_ne this zero_ne_one }\nend\n\ninstance one_of : static (one_of []) :=\nby { apply one_of_iff.mpr, refl }\n\nlemma one_of'_iff {cs : list char} : static (one_of' cs) ↔ cs = [] :=\nbegin\n cases cs with hd tl,\n { simp [one_of', static.bind], },\n { have : one_of' (hd :: tl) (hd :: tl).to_buffer 0 = done 1 (),\n { simp [one_of'_eq_done] },\n simpa using not_of_ne this zero_ne_one }\nend\n\ninstance one_of' : static (one_of []) :=\nby { apply one_of_iff.mpr, refl }\n\nlemma str_iff {s : string} : static (str s) ↔ s = \"\" :=\nby simp [str_eq_char_buf, char_buf_iff, ←string.to_list_inj, buffer.ext_iff]\n\ninstance remaining : remaining.static :=\n⟨λ _ _ _ _ h, (remaining_eq_done.mp h).left⟩\n\ninstance eof : eof.static :=\nstatic.decorate_error\n\ninstance foldr_core {f : α → β → β} [p.static] :\n ∀ {b : β} {reps : ℕ}, (foldr_core f p b reps).static\n| _ 0 := static.failure\n| _ (reps + 1) := begin\n simp_rw parser.foldr_core,\n convert static.orelse,\n { convert static.bind,\n { apply_instance },\n { intro,\n convert static.bind,\n { exact foldr_core },\n { apply_instance } } },\n { exact static.pure }\nend\n\ninstance foldr {f : α → β → β} [p.static] : static (foldr f p b) :=\n⟨λ _ _ _ _, by { dsimp [foldr], exact of_done }⟩\n\ninstance foldl_core {f : α → β → α} {p : parser β} [p.static] :\n ∀ {a : α} {reps : ℕ}, (foldl_core f a p reps).static\n| _ 0 := static.failure\n| _ (reps + 1) := begin\n convert static.orelse,\n { convert static.bind,\n { apply_instance },\n { exact λ _, foldl_core } },\n { exact static.pure }\nend\n\ninstance foldl {f : α → β → α} {p : parser β} [p.static] : static (foldl f a p) :=\n⟨λ _ _ _ _, by { dsimp [foldl], exact of_done }⟩\n\ninstance many [p.static] : p.many.static :=\nstatic.foldr\n\ninstance many_char {p : parser char} [p.static] : p.many_char.static :=\nstatic.map\n\ninstance many' [p.static] : p.many'.static :=\nstatic.and_then\n\ninstance many1 [p.static] : p.many1.static :=\nstatic.seq\n\ninstance many_char1 {p : parser char} [p.static] : p.many_char1.static :=\nstatic.map\n\ninstance sep_by1 [p.static] [sep.static] : static (sep_by1 sep p) :=\nstatic.seq\n\ninstance sep_by [p.static] [sep.static] : static (sep_by sep p) :=\nstatic.orelse\n\nlemma fix_core {F : parser α → parser α} (hF : ∀ (p : parser α), p.static → (F p).static) :\n ∀ (max_depth : ℕ), static (fix_core F max_depth)\n| 0 := static.failure\n| (max_depth + 1) := hF _ (fix_core _)\n\nlemma digit : ¬ digit.static :=\nbegin\n have : digit \"1\".to_char_buffer 0 = done 1 1,\n { have : 0 < \"s\".to_char_buffer.size := dec_trivial,\n simpa [this] },\n exact not_of_ne this zero_ne_one\nend\n\nlemma nat : ¬ nat.static :=\nbegin\n have : nat \"1\".to_char_buffer 0 = done 1 1,\n { have : 0 < \"s\".to_char_buffer.size := dec_trivial,\n simpa [this] },\n exact not_of_ne this zero_ne_one\nend\n\nlemma fix {F : parser α → parser α} (hF : ∀ (p : parser α), p.static → (F p).static) :\n static (fix F) :=\n⟨λ cb n _ _ h,\n by { haveI := fix_core hF (cb.size - n + 1), dsimp [fix] at h, exact static.of_done h }⟩\n\nend static\n\nnamespace bounded\n\nvariables {α β : Type} {msgs : thunk (list string)} {msg : thunk string}\nvariables {p q : parser α} {cb : char_buffer} {n n' : ℕ} {err : dlist string}\nvariables {a : α} {b : β}\n\nlemma done_of_unbounded (h : ¬p.bounded) : ∃ (cb : char_buffer) (n n' : ℕ) (a : α),\n p cb n = done n' a ∧ cb.size ≤ n :=\nbegin\n contrapose! h,\n constructor,\n intros cb n hn,\n cases hp : p cb n,\n { exact absurd hn (h _ _ _ _ hp).not_le },\n { simp [hp] }\nend\n\nlemma pure : ¬ bounded (pure a) :=\nbegin\n introI,\n have : (pure a : parser α) buffer.nil 0 = done 0 a := by simp [pure_eq_done],\n exact absurd (bounded.of_done this) (lt_irrefl _)\nend\n\ninstance bind {f : α → parser β} [p.bounded] :\n (p >>= f).bounded :=\nbegin\n constructor,\n intros cb n hn,\n obtain ⟨_, _, hp⟩ := bounded.exists p hn,\n simp [hp]\nend\n\ninstance and_then {q : parser β} [p.bounded] : (p >> q).bounded :=\nbounded.bind\n\ninstance map [p.bounded] {f : α → β} : (f <$> p).bounded :=\nbounded.bind\n\ninstance seq {f : parser (α → β)} [f.bounded] : (f <*> p).bounded :=\nbounded.bind\n\ninstance mmap {a : α} {l : list α} {f : α → parser β} [∀ a, (f a).bounded] :\n ((a :: l).mmap f).bounded :=\nbounded.bind\n\ninstance mmap' {a : α} {l : list α} {f : α → parser β} [∀ a, (f a).bounded] :\n ((a :: l).mmap' f).bounded :=\nbounded.and_then\n\ninstance failure : @parser.bounded α failure :=\n⟨by simp⟩\n\nlemma guard_iff {p : Prop} [decidable p] : bounded (guard p) ↔ ¬ p :=\nby simpa [guard, apply_ite bounded, pure, failure] using λ _, bounded.failure\n\ninstance orelse [p.bounded] [q.bounded] : (p <|> q).bounded :=\nbegin\n constructor,\n intros cb n hn,\n cases hx : (p <|> q) cb n with posx resx posx errx,\n { obtain h | ⟨h, -, -⟩ := orelse_eq_done.mp hx;\n exact absurd hn (of_done h).not_le },\n { simp }\nend\n\ninstance decorate_errors [p.bounded] :\n (@decorate_errors α msgs p).bounded :=\nbegin\n constructor,\n intros _ _,\n simpa using bounded.exists p\nend\n\nlemma decorate_errors_iff : (@parser.decorate_errors α msgs p).bounded ↔ p.bounded :=\nbegin\n split,\n { introI,\n constructor,\n intros _ _ hn,\n obtain ⟨_, _, h⟩ := bounded.exists (@parser.decorate_errors α msgs p) hn,\n simp [decorate_errors_eq_fail] at h,\n exact h.right.right },\n { introI,\n constructor,\n intros _ _ hn,\n obtain ⟨_, _, h⟩ := bounded.exists p hn,\n simp [h] }\nend\n\ninstance decorate_error [p.bounded] : (@decorate_error α msg p).bounded :=\nbounded.decorate_errors\n\nlemma decorate_error_iff : (@parser.decorate_error α msg p).bounded ↔ p.bounded :=\ndecorate_errors_iff\n\ninstance any_char : bounded any_char :=\n⟨λ cb n hn, by simp [any_char, hn]⟩\n\ninstance sat {p : char → Prop} [decidable_pred p] : bounded (sat p) :=\n⟨λ cb n hn, by simp [sat, hn]⟩\n\nlemma eps : ¬ bounded eps := pure\n\ninstance ch {c : char} : bounded (ch c) :=\nbounded.decorate_error\n\nlemma char_buf_iff {cb' : char_buffer} : bounded (char_buf cb') ↔ cb' ≠ buffer.nil :=\nbegin\n have : cb' ≠ buffer.nil ↔ cb'.to_list ≠ [] :=\n not_iff_not_of_iff ⟨λ h, by simp [h], λ h, by simpa using congr_arg list.to_buffer h⟩,\n rw [char_buf, decorate_error_iff, this],\n cases cb'.to_list,\n { simp [pure, ch] },\n { simp only [iff_true, ne.def, not_false_iff],\n apply_instance }\nend\n\ninstance one_of {cs : list char} : (one_of cs).bounded :=\nbounded.decorate_errors\n\ninstance one_of' {cs : list char} : (one_of' cs).bounded :=\nbounded.and_then\n\nlemma str_iff {s : string} : (str s).bounded ↔ s ≠ \"\" :=\nbegin\n rw [str, decorate_error_iff],\n cases hs : s.to_list,\n { have : s = \"\",\n { cases s, rw [string.to_list] at hs, simpa [hs] },\n simp [pure, this] },\n { have : s ≠ \"\",\n { intro H, simpa [H] using hs },\n simp only [this, iff_true, ne.def, not_false_iff],\n apply_instance }\nend\n\nlemma remaining : ¬ remaining.bounded :=\nbegin\n introI,\n have : remaining buffer.nil 0 = done 0 0 := by simp [remaining_eq_done],\n exact absurd (bounded.of_done this) (lt_irrefl _)\nend\n\nlemma eof : ¬ eof.bounded :=\nbegin\n introI,\n have : eof buffer.nil 0 = done 0 () := by simp [eof_eq_done],\n exact absurd (bounded.of_done this) (lt_irrefl _)\nend\n\nsection fold\n\ninstance foldr_core_zero {f : α → β → β} : (foldr_core f p b 0).bounded :=\nbounded.failure\n\ninstance foldl_core_zero {f : β → α → β} {b : β} : (foldl_core f b p 0).bounded :=\nbounded.failure\n\nvariables {reps : ℕ} [hpb : p.bounded] (he : ∀ cb n n' err, p cb n = fail n' err → n ≠ n')\ninclude hpb he\n\nlemma foldr_core {f : α → β → β} : (foldr_core f p b reps).bounded :=\nbegin\n cases reps,\n { exact bounded.foldr_core_zero },\n constructor,\n intros cb n hn,\n obtain ⟨np, errp, hp⟩ := bounded.exists p hn,\n simpa [foldr_core_succ_eq_fail, hp] using he cb n np errp,\nend\n\nlemma foldr {f : α → β → β} : bounded (foldr f p b) :=\nbegin\n constructor,\n intros cb n hn,\n haveI : (parser.foldr_core f p b (cb.size - n + 1)).bounded := foldr_core he,\n obtain ⟨np, errp, hp⟩ := bounded.exists (parser.foldr_core f p b (cb.size - n + 1)) hn,\n simp [foldr, hp]\nend\n\nlemma foldl_core {f : β → α → β} :\n (foldl_core f b p reps).bounded :=\nbegin\n cases reps,\n { exact bounded.foldl_core_zero },\n constructor,\n intros cb n hn,\n obtain ⟨np, errp, hp⟩ := bounded.exists p hn,\n simpa [foldl_core_succ_eq_fail, hp] using he cb n np errp,\nend\n\nlemma foldl {f : β → α → β} : bounded (foldl f b p) :=\nbegin\n constructor,\n intros cb n hn,\n haveI : (parser.foldl_core f b p (cb.size - n + 1)).bounded := foldl_core he,\n obtain ⟨np, errp, hp⟩ := bounded.exists (parser.foldl_core f b p (cb.size - n + 1)) hn,\n simp [foldl, hp]\nend\n\nlemma many : p.many.bounded :=\nfoldr he\n\nomit hpb\nlemma many_char {pc : parser char} [pc.bounded]\n (he : ∀ cb n n' err, pc cb n = fail n' err → n ≠ n'): pc.many_char.bounded :=\nby { convert bounded.map, exact many he }\ninclude hpb\n\nlemma many' : p.many'.bounded :=\nby { convert bounded.and_then, exact many he }\n\nend fold\n\ninstance many1 [p.bounded] : p.many1.bounded :=\nbounded.seq\n\ninstance many_char1 {p : parser char} [p.bounded] : p.many_char1.bounded :=\nbounded.map\n\ninstance sep_by1 {sep : parser unit} [p.bounded] : bounded (sep_by1 sep p) :=\nbounded.seq\n\nlemma fix_core {F : parser α → parser α} (hF : ∀ (p : parser α), p.bounded → (F p).bounded) :\n ∀ (max_depth : ℕ), bounded (fix_core F max_depth)\n| 0 := bounded.failure\n| (max_depth + 1) := hF _ (fix_core _)\n\ninstance digit : digit.bounded :=\nbounded.decorate_error\n\ninstance nat : nat.bounded :=\nbounded.decorate_error\n\nlemma fix {F : parser α → parser α} (hF : ∀ (p : parser α), p.bounded → (F p).bounded) :\n bounded (fix F) :=\nbegin\n constructor,\n intros cb n hn,\n haveI : (parser.fix_core F (cb.size - n + 1)).bounded := fix_core hF _,\n obtain ⟨np, errp, hp⟩ := bounded.exists (parser.fix_core F (cb.size - n + 1)) hn,\n simp [fix, hp]\nend\n\nend bounded\n\nnamespace unfailing\n\nvariables {α β : Type} {p q : parser α} {msgs : thunk (list string)} {msg : thunk string}\n {cb : char_buffer} {n' n : ℕ} {err : dlist string} {a : α} {b : β} {sep : parser unit}\n\nlemma of_bounded [p.bounded] : ¬ unfailing p :=\nbegin\n introI,\n cases h : p buffer.nil 0,\n { simpa [lt_irrefl] using bounded.of_done h },\n { exact of_fail h }\nend\n\ninstance pure : unfailing (pure a) :=\n⟨λ _ _, by simp [pure_eq_done]⟩\n\ninstance bind {f : α → parser β} [p.unfailing] [∀ a, (f a).unfailing] :\n (p >>= f).unfailing :=\n⟨λ cb n, begin\n obtain ⟨np, a, hp⟩ := exists_done p cb n,\n simpa [hp, and.comm, and.left_comm, and.assoc] using exists_done (f a) cb np\nend⟩\n\ninstance and_then {q : parser β} [p.unfailing] [q.unfailing] : (p >> q).unfailing := unfailing.bind\n\ninstance map [p.unfailing] {f : α → β} : (f <$> p).unfailing := unfailing.bind\n\ninstance seq {f : parser (α → β)} [f.unfailing] [p.unfailing] : (f <*> p).unfailing :=\nunfailing.bind\n\ninstance mmap {l : list α} {f : α → parser β} [∀ a, (f a).unfailing] : (l.mmap f).unfailing :=\nbegin\n constructor,\n induction l with hd tl hl,\n { intros,\n simp [pure_eq_done] },\n { intros,\n obtain ⟨np, a, hp⟩ := exists_done (f hd) cb n,\n obtain ⟨n', b, hf⟩ := hl cb np,\n simp [hp, hf, and.comm, and.left_comm, and.assoc, pure_eq_done] }\nend\n\ninstance mmap' {l : list α} {f : α → parser β} [∀ a, (f a).unfailing] : (l.mmap' f).unfailing :=\nbegin\n constructor,\n induction l with hd tl hl,\n { intros,\n simp [pure_eq_done] },\n { intros,\n obtain ⟨np, a, hp⟩ := exists_done (f hd) cb n,\n obtain ⟨n', b, hf⟩ := hl cb np,\n simp [hp, hf, and.comm, and.left_comm, and.assoc, pure_eq_done] }\nend\n\nlemma failure : ¬ @parser.unfailing α failure :=\nbegin\n introI h,\n have : (failure : parser α) buffer.nil 0 = fail 0 dlist.empty := by simp,\n exact of_fail this\nend\n\ninstance guard_true : unfailing (guard true) := unfailing.pure\n\nlemma guard : ¬ unfailing (guard false) :=\nunfailing.failure\n\ninstance orelse [p.unfailing] : (p <|> q).unfailing :=\n⟨λ cb n, by { obtain ⟨_, _, h⟩ := p.exists_done cb n, simp [success_iff, h] }⟩\n\ninstance decorate_errors [p.unfailing] :\n (@decorate_errors α msgs p).unfailing :=\n⟨λ cb n, by { obtain ⟨_, _, h⟩ := p.exists_done cb n, simp [success_iff, h] }⟩\n\ninstance decorate_error [p.unfailing] : (@decorate_error α msg p).unfailing :=\nunfailing.decorate_errors\n\ninstance any_char : conditionally_unfailing any_char :=\n⟨λ _ _ hn, by simp [success_iff, any_char_eq_done, hn]⟩\n\nlemma sat : conditionally_unfailing (sat (λ _, true)) :=\n⟨λ _ _ hn, by simp [success_iff, sat_eq_done, hn]⟩\n\ninstance eps : unfailing eps := unfailing.pure\n\ninstance remaining : remaining.unfailing :=\n⟨λ _ _, by simp [success_iff, remaining_eq_done]⟩\n\nlemma foldr_core_zero {f : α → β → β} {b : β} : ¬ (foldr_core f p b 0).unfailing :=\nunfailing.failure\n\ninstance foldr_core_of_static {f : α → β → β} {b : β} {reps : ℕ} [p.static] [p.unfailing] :\n (foldr_core f p b (reps + 1)).unfailing :=\nbegin\n induction reps with reps hr,\n { constructor,\n intros cb n,\n obtain ⟨np, a, h⟩ := p.exists_done cb n,\n simpa [foldr_core_eq_done, h] using (static.of_done h).symm },\n { constructor,\n haveI := hr,\n intros cb n,\n obtain ⟨np, a, h⟩ := p.exists_done cb n,\n have : n = np := static.of_done h,\n subst this,\n obtain ⟨np, b', hf⟩ := exists_done (foldr_core f p b (reps + 1)) cb n,\n have : n = np := static.of_done hf,\n subst this,\n refine ⟨n, f a b', _⟩,\n rw foldr_core_eq_done,\n simp [h, hf, and.comm, and.left_comm, and.assoc] }\nend\n\ninstance foldr_core_one_of_err_static {f : α → β → β} {b : β} [p.static] [p.err_static] :\n (foldr_core f p b 1).unfailing :=\nbegin\n constructor,\n intros cb n,\n cases h : p cb n,\n { simpa [foldr_core_eq_done, h] using (static.of_done h).symm },\n { simpa [foldr_core_eq_done, h] using (err_static.of_fail h).symm }\nend\n\n-- TODO: add foldr and foldl, many, etc, fix_core\n\nlemma digit : ¬ digit.unfailing :=\nof_bounded\n\nlemma nat : ¬ nat.unfailing :=\nof_bounded\n\nend unfailing\n\nnamespace err_static\n\nvariables {α β : Type} {p q : parser α} {msgs : thunk (list string)} {msg : thunk string}\n {cb : char_buffer} {n' n : ℕ} {err : dlist string} {a : α} {b : β} {sep : parser unit}\n\nlemma not_of_ne (h : p cb n = fail n' err) (hne : n ≠ n') : ¬ err_static p :=\nby { introI, exact hne (of_fail h) }\n\ninstance pure : err_static (pure a) :=\n⟨λ _ _ _ _, by { simp [pure_eq_done] }⟩\n\ninstance bind {f : α → parser β} [p.static] [p.err_static] [∀ a, (f a).err_static] :\n (p >>= f).err_static :=\n⟨λ cb n n' err, begin\n rw bind_eq_fail,\n rintro (hp | ⟨_, _, hp, hf⟩),\n { exact of_fail hp },\n { exact trans (static.of_done hp) (of_fail hf) }\nend⟩\n\ninstance bind_of_unfailing {f : α → parser β} [p.err_static] [∀ a, (f a).unfailing] :\n (p >>= f).err_static :=\n⟨λ cb n n' err, begin\n rw bind_eq_fail,\n rintro (hp | ⟨_, _, hp, hf⟩),\n { exact of_fail hp },\n { exact false.elim (unfailing.of_fail hf) }\nend⟩\n\ninstance and_then {q : parser β} [p.static] [p.err_static] [q.err_static] : (p >> q).err_static :=\nerr_static.bind\n\ninstance and_then_of_unfailing {q : parser β} [p.err_static] [q.unfailing] : (p >> q).err_static :=\nerr_static.bind_of_unfailing\n\ninstance map [p.err_static] {f : α → β} : (f <$> p).err_static :=\n⟨λ _ _ _ _, by { rw map_eq_fail, exact of_fail }⟩\n\ninstance seq {f : parser (α → β)} [f.static] [f.err_static] [p.err_static] : (f <*> p).err_static :=\nerr_static.bind\n\ninstance seq_of_unfailing {f : parser (α → β)} [f.err_static] [p.unfailing] :\n (f <*> p).err_static :=\nerr_static.bind_of_unfailing\n\ninstance mmap : Π {l : list α} {f : α → parser β}\n [∀ a, (f a).static] [∀ a, (f a).err_static], (l.mmap f).err_static\n| [] _ _ _ := err_static.pure\n| (a :: l) _ h h' := begin\n convert err_static.bind,\n { exact h _ },\n { exact h' _ },\n { intro,\n convert err_static.bind,\n { convert static.mmap,\n exact h },\n { apply mmap,\n { exact h },\n { exact h' } },\n { exact λ _, err_static.pure } }\nend\n\ninstance mmap_of_unfailing : Π {l : list α} {f : α → parser β}\n [∀ a, (f a).unfailing] [∀ a, (f a).err_static], (l.mmap f).err_static\n| [] _ _ _ := err_static.pure\n| (a :: l) _ h h' := begin\n convert err_static.bind_of_unfailing,\n { exact h' _ },\n { intro,\n convert unfailing.bind,\n { convert unfailing.mmap,\n exact h },\n { exact λ _, unfailing.pure } }\nend\n\ninstance mmap' : Π {l : list α} {f : α → parser β}\n [∀ a, (f a).static] [∀ a, (f a).err_static], (l.mmap' f).err_static\n| [] _ _ _ := err_static.pure\n| (a :: l) _ h h' := begin\n convert err_static.and_then,\n { exact h _ },\n { exact h' _ },\n { convert mmap',\n { exact h },\n { exact h' } }\nend\n\ninstance mmap'_of_unfailing : Π {l : list α} {f : α → parser β}\n [∀ a, (f a).unfailing] [∀ a, (f a).err_static], (l.mmap' f).err_static\n| [] _ _ _ := err_static.pure\n| (a :: l) _ h h' := begin\n convert err_static.and_then_of_unfailing,\n { exact h' _ },\n { convert unfailing.mmap',\n exact h }\nend\n\ninstance failure : @parser.err_static α failure :=\n⟨λ _ _ _ _ h, (failure_eq_fail.mp h).left⟩\n\ninstance guard {p : Prop} [decidable p] : err_static (guard p) :=\n⟨λ _ _ _ _ h, (guard_eq_fail.mp h).right.left⟩\n\ninstance orelse [p.err_static] [q.mono] : (p <|> q).err_static :=\n⟨λ _ n n' _, begin\n by_cases hn : n = n',\n { exact λ _, hn },\n { rw orelse_eq_fail_of_mono_ne hn,\n { exact of_fail },\n { apply_instance } }\nend⟩\n\ninstance decorate_errors :\n (@decorate_errors α msgs p).err_static :=\n⟨λ _ _ _ _ h, (decorate_errors_eq_fail.mp h).left⟩\n\ninstance decorate_error : (@decorate_error α msg p).err_static :=\nerr_static.decorate_errors\n\ninstance any_char : err_static any_char :=\n⟨λ _ _ _ _, by { rw [any_char_eq_fail, and.comm], simp }⟩\n\ninstance sat_iff {p : char → Prop} [decidable_pred p] : err_static (sat p) :=\n⟨λ _ _ _ _ h, (sat_eq_fail.mp h).left⟩\n\ninstance eps : err_static eps := err_static.pure\n\ninstance ch (c : char) : err_static (ch c) :=\nerr_static.decorate_error\n\ninstance char_buf {cb' : char_buffer} : err_static (char_buf cb') :=\nerr_static.decorate_error\n\ninstance one_of {cs : list char} : err_static (one_of cs) :=\nerr_static.decorate_errors\n\ninstance one_of' {cs : list char} : err_static (one_of' cs) :=\nerr_static.and_then_of_unfailing\n\ninstance str {s : string} : err_static (str s) :=\nerr_static.decorate_error\n\ninstance remaining : remaining.err_static :=\n⟨λ _ _ _ _, by simp [remaining_ne_fail]⟩\n\ninstance eof : eof.err_static :=\nerr_static.decorate_error\n\n-- TODO: add foldr and foldl, many, etc, fix_core\n\nlemma fix_core {F : parser α → parser α} (hF : ∀ (p : parser α), p.err_static → (F p).err_static) :\n ∀ (max_depth : ℕ), err_static (fix_core F max_depth)\n| 0 := err_static.failure\n| (max_depth + 1) := hF _ (fix_core _)\n\ninstance digit : digit.err_static :=\nerr_static.decorate_error\n\ninstance nat : nat.err_static :=\nerr_static.decorate_error\n\nlemma fix {F : parser α → parser α} (hF : ∀ (p : parser α), p.err_static → (F p).err_static) :\n err_static (fix F) :=\n⟨λ cb n _ _ h,\n by { haveI := fix_core hF (cb.size - n + 1), dsimp [fix] at h, exact err_static.of_fail h }⟩\n\nend err_static\n\nnamespace step\n\nvariables {α β : Type} {p q : parser α} {msgs : thunk (list string)} {msg : thunk string}\n {cb : char_buffer} {n' n : ℕ} {err : dlist string} {a : α} {b : β} {sep : parser unit}\n\nlemma not_step_of_static_done [static p] (h : ∃ cb n n' a, p cb n = done n' a) : ¬ step p :=\nbegin\n introI,\n rcases h with ⟨cb, n, n', a, h⟩,\n have hs := static.of_done h,\n simpa [←hs] using of_done h\nend\n\nlemma pure (a : α) : ¬ step (pure a) :=\nbegin\n apply not_step_of_static_done,\n simp [pure_eq_done]\nend\n\ninstance bind {f : α → parser β} [p.step] [∀ a, (f a).static] :\n (p >>= f).step :=\n⟨λ _ _ _ _, by { simp_rw bind_eq_done, rintro ⟨_, _, hp, hf⟩,\n exact (static.of_done hf) ▸ (of_done hp) }⟩\n\ninstance bind' {f : α → parser β} [p.static] [∀ a, (f a).step] :\n (p >>= f).step :=\n⟨λ _ _ _ _, by { simp_rw bind_eq_done, rintro ⟨_, _, hp, hf⟩,\n rw static.of_done hp, exact of_done hf }⟩\n\ninstance and_then {q : parser β} [p.step] [q.static] : (p >> q).step := step.bind\n\ninstance and_then' {q : parser β} [p.static] [q.step] : (p >> q).step := step.bind'\n\ninstance map [p.step] {f : α → β} : (f <$> p).step :=\n⟨λ _ _ _ _, by { simp_rw map_eq_done, rintro ⟨_, hp, _⟩, exact of_done hp }⟩\n\ninstance seq {f : parser (α → β)} [f.step] [p.static] : (f <*> p).step := step.bind\n\ninstance seq' {f : parser (α → β)} [f.static] [p.step] : (f <*> p).step := step.bind'\n\ninstance mmap {f : α → parser β} [(f a).step] :\n ([a].mmap f).step :=\nbegin\n convert step.bind,\n { apply_instance },\n { intro,\n convert static.bind,\n { exact static.pure },\n { exact λ _, static.pure } }\nend\n\ninstance mmap' {f : α → parser β} [(f a).step] :\n ([a].mmap' f).step :=\nbegin\n convert step.and_then,\n { apply_instance },\n { exact static.pure }\nend\n\ninstance failure : @parser.step α failure :=\n⟨λ _ _ _ _, by simp⟩\n\nlemma guard_true : ¬ step (guard true) := pure _\n\ninstance guard : step (guard false) :=\nstep.failure\n\ninstance orelse [p.step] [q.step] : (p <|> q).step :=\n⟨λ _ _ _ _, by { simp_rw orelse_eq_done, rintro (h | ⟨h, -⟩); exact of_done h }⟩\n\nlemma decorate_errors_iff : (@parser.decorate_errors α msgs p).step ↔ p.step :=\nbegin\n split,\n { introI,\n constructor,\n intros cb n n' a h,\n have : (@parser.decorate_errors α msgs p) cb n = done n' a := by simpa using h,\n exact of_done this },\n { introI,\n constructor,\n intros _ _ _ _ h,\n rw decorate_errors_eq_done at h,\n exact of_done h }\nend\n\ninstance decorate_errors [p.step] :\n (@decorate_errors α msgs p).step :=\n⟨λ _ _ _ _, by { rw decorate_errors_eq_done, exact of_done }⟩\n\nlemma decorate_error_iff : (@parser.decorate_error α msg p).step ↔ p.step :=\ndecorate_errors_iff\n\ninstance decorate_error [p.step] : (@decorate_error α msg p).step :=\nstep.decorate_errors\n\ninstance any_char : step any_char :=\nbegin\n constructor,\n intros cb n,\n simp_rw [any_char_eq_done],\n rintro _ _ ⟨_, rfl, -⟩,\n simp\nend\n\ninstance sat {p : char → Prop} [decidable_pred p] : step (sat p) :=\nbegin\n constructor,\n intros cb n,\n simp_rw [sat_eq_done],\n rintro _ _ ⟨_, _, rfl, -⟩,\n simp\nend\n\nlemma eps : ¬ step eps := step.pure ()\n\ninstance ch {c : char} : step (ch c) := step.decorate_error\n\nlemma char_buf_iff {cb' : char_buffer} : (char_buf cb').step ↔ cb'.size = 1 :=\nbegin\n have : char_buf cb' cb' 0 = done cb'.size () := by simp [char_buf_eq_done],\n split,\n { introI,\n simpa using of_done this },\n { intro h,\n constructor,\n intros cb n n' _,\n rw [char_buf_eq_done, h],\n rintro ⟨rfl, -⟩,\n refl }\nend\n\ninstance one_of {cs : list char} : (one_of cs).step :=\nstep.decorate_errors\n\ninstance one_of' {cs : list char} : (one_of' cs).step :=\nstep.and_then\n\nlemma str_iff {s : string} : (str s).step ↔ s.length = 1 :=\nby simp [str_eq_char_buf, char_buf_iff, ←string.to_list_inj, buffer.ext_iff]\n\nlemma remaining : ¬ remaining.step :=\nbegin\n apply not_step_of_static_done,\n simp [remaining_eq_done]\nend\n\nlemma eof : ¬ eof.step :=\nbegin\n apply not_step_of_static_done,\n simp only [eof_eq_done, exists_eq_left', exists_const],\n use [buffer.nil, 0],\n simp\nend\n\n-- TODO: add foldr and foldl, many, etc, fix_core\n\nlemma fix_core {F : parser α → parser α} (hF : ∀ (p : parser α), p.step → (F p).step) :\n ∀ (max_depth : ℕ), step (fix_core F max_depth)\n| 0 := step.failure\n| (max_depth + 1) := hF _ (fix_core _)\n\ninstance digit : digit.step :=\nstep.decorate_error\n\nlemma fix {F : parser α → parser α} (hF : ∀ (p : parser α), p.step → (F p).step) :\n step (fix F) :=\n⟨λ cb n _ _ h,\n by { haveI := fix_core hF (cb.size - n + 1), dsimp [fix] at h, exact of_done h }⟩\n\nend step\n\nsection step\n\nvariables {α β : Type} {p q : parser α} {msgs : thunk (list string)} {msg : thunk string}\n {cb : char_buffer} {n' n : ℕ} {err : dlist string} {a : α} {b : β} {sep : parser unit}\n\nlemma many1_eq_done_iff_many_eq_done [p.step] [p.bounded] {x : α} {xs : list α} :\n many1 p cb n = done n' (x :: xs) ↔ many p cb n = done n' (x :: xs) :=\nbegin\n induction hx : (x :: xs) with hd tl IH generalizing x xs n n',\n { simpa using hx },\n split,\n { simp only [many1_eq_done, and_imp, exists_imp_distrib],\n intros np hp hm,\n have : np = n + 1 := step.of_done hp,\n have hn : n < cb.size := bounded.of_done hp,\n subst this,\n obtain ⟨k, hk⟩ : ∃ k, cb.size - n = k + 1 :=\n nat.exists_eq_succ_of_ne_zero (ne_of_gt (nat.sub_pos_of_lt hn)),\n cases k,\n { cases tl;\n simpa [many_eq_done_nil, nat.sub_succ, hk, many_eq_done, hp, foldr_core_eq_done] using hm },\n cases tl with hd' tl',\n { simpa [many_eq_done_nil, nat.sub_succ, hk, many_eq_done, hp, foldr_core_eq_done] using hm },\n { rw ←@IH hd' tl' at hm, swap, refl,\n simp only [many1_eq_done, many, foldr] at hm,\n obtain ⟨np, hp', hf⟩ := hm,\n have : np = n + 1 + 1 := step.of_done hp',\n subst this,\n simpa [nat.sub_succ, many_eq_done, hp, hk, foldr_core_eq_done, hp'] using hf } },\n { simp only [many_eq_done, many1_eq_done, and_imp, exists_imp_distrib],\n intros np hp hm,\n have : np = n + 1 := step.of_done hp,\n have hn : n < cb.size := bounded.of_done hp,\n subst this,\n obtain ⟨k, hk⟩ : ∃ k, cb.size - n = k + 1 :=\n nat.exists_eq_succ_of_ne_zero (ne_of_gt (nat.sub_pos_of_lt hn)),\n cases k,\n { cases tl;\n simpa [many_eq_done_nil, nat.sub_succ, hk, many_eq_done, hp, foldr_core_eq_done] using hm },\n cases tl with hd' tl',\n { simpa [many_eq_done_nil, nat.sub_succ, hk, many_eq_done, hp, foldr_core_eq_done] using hm },\n { simp [hp],\n rw ←@IH hd' tl' (n + 1) n', swap, refl,\n rw [hk, foldr_core_eq_done, or.comm] at hm,\n obtain (hm | ⟨np, hd', tl', hp', hf, hm⟩) := hm,\n { simpa using hm },\n simp only at hm,\n obtain ⟨rfl, rfl⟩ := hm,\n have : np = n + 1 + 1 := step.of_done hp',\n subst this,\n simp [nat.sub_succ, many, many1_eq_done, hp, hk, foldr_core_eq_done, hp', ←hf, foldr] } }\nend\n\nend step\n\nnamespace prog\n\nvariables {α β : Type} {p q : parser α} {msgs : thunk (list string)} {msg : thunk string}\n {cb : char_buffer} {n' n : ℕ} {err : dlist string} {a : α} {b : β} {sep : parser unit}\n\n@[priority 100] -- see Note [lower instance priority]\ninstance of_step [step p] : prog p :=\n⟨λ _ _ _ _ h, by { rw step.of_done h, exact nat.lt_succ_self _ }⟩\n\nlemma pure (a : α) : ¬ prog (pure a) :=\nbegin\n introI h,\n have : (pure a : parser α) buffer.nil 0 = done 0 a := by simp [pure_eq_done],\n replace this : 0 < 0 := prog.of_done this,\n exact (lt_irrefl _) this\nend\n\ninstance bind {f : α → parser β} [p.prog] [∀ a, (f a).mono] :\n (p >>= f).prog :=\n⟨λ _ _ _ _, by { simp_rw bind_eq_done, rintro ⟨_, _, hp, hf⟩,\n exact lt_of_lt_of_le (of_done hp) (mono.of_done hf) }⟩\n\ninstance and_then {q : parser β} [p.prog] [q.mono] : (p >> q).prog := prog.bind\n\ninstance map [p.prog] {f : α → β} : (f <$> p).prog :=\n⟨λ _ _ _ _, by { simp_rw map_eq_done, rintro ⟨_, hp, _⟩, exact of_done hp }⟩\n\ninstance seq {f : parser (α → β)} [f.prog] [p.mono] : (f <*> p).prog := prog.bind\n\ninstance mmap {l : list α} {f : α → parser β} [(f a).prog] [∀ a, (f a).mono] :\n ((a :: l).mmap f).prog :=\nbegin\n constructor,\n simp only [and_imp, bind_eq_done, return_eq_pure, mmap, exists_imp_distrib, pure_eq_done],\n rintro _ _ _ _ _ _ h _ _ hp rfl rfl,\n exact lt_of_lt_of_le (of_done h) (mono.of_done hp)\nend\n\ninstance mmap' {l : list α} {f : α → parser β} [(f a).prog] [∀ a, (f a).mono] :\n ((a :: l).mmap' f).prog :=\nbegin\n constructor,\n simp only [and_imp, bind_eq_done, mmap', exists_imp_distrib, and_then_eq_bind],\n intros _ _ _ _ _ _ h hm,\n exact lt_of_lt_of_le (of_done h) (mono.of_done hm)\nend\n\ninstance failure : @parser.prog α failure :=\nprog.of_step\n\nlemma guard_true : ¬ prog (guard true) := pure _\n\ninstance guard : prog (guard false) :=\nprog.failure\n\ninstance orelse [p.prog] [q.prog] : (p <|> q).prog :=\n⟨λ _ _ _ _, by { simp_rw orelse_eq_done, rintro (h | ⟨h, -⟩); exact of_done h }⟩\n\nlemma decorate_errors_iff : (@parser.decorate_errors α msgs p).prog ↔ p.prog :=\nbegin\n split,\n { introI,\n constructor,\n intros cb n n' a h,\n have : (@parser.decorate_errors α msgs p) cb n = done n' a := by simpa using h,\n exact of_done this },\n { introI,\n constructor,\n intros _ _ _ _ h,\n rw decorate_errors_eq_done at h,\n exact of_done h }\nend\n\ninstance decorate_errors [p.prog] :\n (@decorate_errors α msgs p).prog :=\n⟨λ _ _ _ _, by { rw decorate_errors_eq_done, exact of_done }⟩\n\nlemma decorate_error_iff : (@parser.decorate_error α msg p).prog ↔ p.prog :=\ndecorate_errors_iff\n\ninstance decorate_error [p.prog] : (@decorate_error α msg p).prog :=\nprog.decorate_errors\n\ninstance any_char : prog any_char :=\nprog.of_step\n\ninstance sat {p : char → Prop} [decidable_pred p] : prog (sat p) :=\nprog.of_step\n\nlemma eps : ¬ prog eps := prog.pure ()\n\ninstance ch {c : char} : prog (ch c) :=\nprog.of_step\n\nlemma char_buf_iff {cb' : char_buffer} : (char_buf cb').prog ↔ cb' ≠ buffer.nil :=\nbegin\n have : cb' ≠ buffer.nil ↔ cb'.to_list ≠ [] :=\n not_iff_not_of_iff ⟨λ h, by simp [h], λ h, by simpa using congr_arg list.to_buffer h⟩,\n rw [char_buf, this, decorate_error_iff],\n cases cb'.to_list,\n { simp [pure] },\n { simp only [iff_true, ne.def, not_false_iff],\n apply_instance }\nend\n\ninstance one_of {cs : list char} : (one_of cs).prog :=\nprog.decorate_errors\n\ninstance one_of' {cs : list char} : (one_of' cs).prog :=\nprog.and_then\n\nlemma str_iff {s : string} : (str s).prog ↔ s ≠ \"\" :=\nby simp [str_eq_char_buf, char_buf_iff, ←string.to_list_inj, buffer.ext_iff]\n\nlemma remaining : ¬ remaining.prog :=\nbegin\n introI h,\n have : remaining buffer.nil 0 = done 0 0 := by simp [remaining_eq_done],\n replace this : 0 < 0 := prog.of_done this,\n exact (lt_irrefl _) this\nend\n\nlemma eof : ¬ eof.prog :=\nbegin\n introI h,\n have : eof buffer.nil 0 = done 0 () := by simpa [remaining_eq_done],\n replace this : 0 < 0 := prog.of_done this,\n exact (lt_irrefl _) this\nend\n\n-- TODO: add foldr and foldl, many, etc, fix_core\n\ninstance many1 [p.mono] [p.prog] : p.many1.prog :=\nbegin\n constructor,\n rintro cb n n' (_ | ⟨hd, tl⟩),\n { simp },\n { rw many1_eq_done,\n rintro ⟨np, hp, h⟩,\n exact (of_done hp).trans_le (mono.of_done h) }\nend\n\nlemma fix_core {F : parser α → parser α} (hF : ∀ (p : parser α), p.prog → (F p).prog) :\n ∀ (max_depth : ℕ), prog (fix_core F max_depth)\n| 0 := prog.failure\n| (max_depth + 1) := hF _ (fix_core _)\n\ninstance digit : digit.prog :=\nprog.of_step\n\ninstance nat : nat.prog :=\nprog.decorate_error\n\nlemma fix {F : parser α → parser α} (hF : ∀ (p : parser α), p.prog → (F p).prog) :\n prog (fix F) :=\n⟨λ cb n _ _ h,\n by { haveI := fix_core hF (cb.size - n + 1), dsimp [fix] at h, exact of_done h }⟩\n\nend prog\n\nvariables {α β : Type} {msgs : thunk (list string)} {msg : thunk string}\nvariables {p q : parser α} {cb : char_buffer} {n n' : ℕ} {err : dlist string}\nvariables {a : α} {b : β}\n\nsection many\n\n-- TODO: generalize to p.prog instead of p.step\nlemma many_sublist_of_done [p.step] [p.bounded] {l : list α}\n (h : p.many cb n = done n' l) :\n ∀ k < n' - n, p.many cb (n + k) = done n' (l.drop k) :=\nbegin\n induction l with hd tl hl generalizing n,\n { rw many_eq_done_nil at h,\n simp [h.left] },\n intros m hm,\n cases m,\n { exact h },\n rw [list.drop, nat.add_succ, ←nat.succ_add],\n apply hl,\n { rw [←many1_eq_done_iff_many_eq_done, many1_eq_done] at h,\n obtain ⟨_, hp, h⟩ := h,\n convert h,\n exact (step.of_done hp).symm },\n { exact nat.lt_pred_iff.mpr hm },\nend\n\nlemma many_eq_nil_of_done [p.step] [p.bounded] {l : list α}\n (h : p.many cb n = done n' l) :\n p.many cb n' = done n' [] :=\nbegin\n induction l with hd tl hl generalizing n,\n { convert h,\n rw many_eq_done_nil at h,\n exact h.left.symm },\n { rw [←many1_eq_done_iff_many_eq_done, many1_eq_done] at h,\n obtain ⟨_, -, h⟩ := h,\n exact hl h }\nend\n\nlemma many_eq_nil_of_out_of_bound [p.bounded] {l : list α}\n (h : p.many cb n = done n' l) (hn : cb.size < n) :\n n' = n ∧ l = [] :=\nbegin\n cases l,\n { rw many_eq_done_nil at h,\n exact ⟨h.left.symm, rfl⟩ },\n { rw many_eq_done at h,\n obtain ⟨np, hp, -⟩ := h,\n exact absurd (bounded.of_done hp) hn.not_lt }\nend\n\nlemma many1_length_of_done [p.mono] [p.step] [p.bounded] {l : list α}\n (h : many1 p cb n = done n' l) :\n l.length = n' - n :=\nbegin\n induction l with hd tl hl generalizing n n',\n { simpa using h },\n { obtain ⟨k, hk⟩ : ∃ k, n' = n + k + 1 := nat.exists_eq_add_of_lt (prog.of_done h),\n subst hk,\n simp only [many1_eq_done] at h,\n obtain ⟨_, hp, h⟩ := h,\n have := step.of_done hp,\n subst this,\n cases tl,\n { simp only [many_eq_done_nil, add_left_inj, exists_and_distrib_right, self_eq_add_right] at h,\n rcases h with ⟨rfl, -⟩,\n simp },\n rw ←many1_eq_done_iff_many_eq_done at h,\n specialize hl h,\n simp [hl, add_comm, add_assoc, nat.sub_succ] }\nend\n\nlemma many1_bounded_of_done [p.step] [p.bounded] {l : list α}\n (h : many1 p cb n = done n' l) :\n n' ≤ cb.size :=\nbegin\n induction l with hd tl hl generalizing n n',\n { simpa using h },\n { simp only [many1_eq_done] at h,\n obtain ⟨np, hp, h⟩ := h,\n have := step.of_done hp,\n subst this,\n cases tl,\n { simp only [many_eq_done_nil, exists_and_distrib_right] at h,\n simpa [←h.left] using bounded.of_done hp },\n { rw ←many1_eq_done_iff_many_eq_done at h,\n exact hl h } }\nend\n\nend many\n\nsection nat\n/--\nThe `val : ℕ` produced by a successful parse of a `cb : char_buffer` is the numerical value\nrepresented by the string of decimal digits (possibly padded with 0s on the left)\nstarting from the parsing position `n` and ending at position `n'`. The number\nof characters parsed in is necessarily `n' - n`.\n\nThis is one of the directions of `nat_eq_done`.\n-/\nlemma nat_of_done {val : ℕ} (h : nat cb n = done n' val) :\n val = (nat.of_digits 10 ((((cb.to_list.drop n).take (n' - n)).reverse.map\n (λ c, c.to_nat - '0'.to_nat)))) :=\nbegin\n /- The parser `parser.nat` that generates a decimal number from a string of digit characters does\n several things. First it ingests in as many digits as it can with `many1 digit`. Then, it folds\n over the resulting `list ℕ` using a helper function that keeps track of both the running sum an\n and the magnitude so far, using a `(sum, magnitude) : (ℕ × ℕ)` pair. The final sum is extracted\n using a `prod.fst`.\n\n To prove that the value that `parser.nat` produces, after moving precisely `n' - n` steps, is\n precisely what `nat.of_digits` would give, if supplied the string that is in the ingested\n `char_buffer` (modulo conversion from `char` to `ℕ ), we need to induct over the length `n' - n`\n of `cb : char_buffer` ingested, and prove that the parser must have terminated due to hitting\n either the end of the `char_buffer` or a non-digit character.\n\n The statement of the lemma is phrased using a combination of `list.drop` and `list.map` because\n there is no currently better way to extract an \"interval\" from a `char_buffer`. Additionally, the\n statement uses a `list.reverse` because `nat.of_digits` is little-endian.\n\n We try to stop referring to the `cb : char_buffer` as soon as possible, so that we can instead\n regard a `list char` instead, which lends itself better to proofs via induction.\n -/\n /- We first prove some helper lemmas about the definition of `parser.nat`. Since it is defined\n in core, we have to work with how it is defined instead of changing its definition.\n In its definition, the function that folds over the parsed in digits is defined internally,\n as a lambda with anonymous destructor syntax, which leads to an unpleasant `nat._match_1` term\n when rewriting the definition of `parser.nat` away. Since we know exactly what the function is,\n we have a `rfl`-like lemma here to rewrite it back into a readable form.\n -/\n have natm : nat._match_1 = (λ (d : ℕ) p, ⟨p.1 + d * p.2, p.2 * 10⟩),\n { ext1, ext1 ⟨⟩, refl },\n -- We also have to prove what is the `prod.snd` of the result of the fold of a `list (ℕ × ℕ)` with\n -- the function above. We use this lemma later when we finish our inductive case.\n have hpow : ∀ l, (list.foldr (λ (digit : ℕ) (x : ℕ × ℕ), (x.fst + digit * x.snd, x.snd * 10))\n (0, 1) l).snd = 10 ^ l.length,\n { intro l,\n induction l with hd tl hl,\n { simp },\n { simp [hl, pow_succ, mul_comm] } },\n -- We convert the hypothesis that `parser.nat` has succeeded into an existential that there is\n -- some list of digits that it has parsed in, and that those digits, when folded over by the\n -- function above, give the value at hand.\n simp only [nat, pure_eq_done, natm, decorate_error_eq_done, bind_eq_done] at h,\n obtain ⟨n', l, hp, rfl, rfl⟩ := h,\n -- We now want to stop working with the `cb : char_buffer` and parse positions `n` and `n'`,\n -- and just deal with the parsed digit list `l : list ℕ`. To do so, we have to show that\n -- this is precisely the list that could have been parsed in, no smaller and no greater.\n induction l with lhd ltl IH generalizing n n' cb,\n { -- Base case: we parsed in no digits whatsoever. But this is impossible because `parser.many1`\n -- must produce a list that is not `list.nil`, by `many1_ne_done_nil`.\n simpa using hp },\n -- Inductive case:\n -- We must prove that the first digit parsed in `lhd : ℕ` is precisely the digit that is\n -- represented by the character at position `n` in `cb : char_buffer`.\n -- We will also prove the the correspondence between the subsequent digits `ltl : list ℕ` and the\n -- remaining characters past position `n` up to position `n'`.\n cases hx : (list.drop n (buffer.to_list cb)) with chd ctl,\n { -- Are there even characters left to parse, at position `n` in the `cb : char_buffer`? In other\n -- words, are we already out of bounds, and thus could not have parsed in any value\n -- successfully. But this must be a contradiction because `parser.digit` is a `bounded` parser,\n -- (due to its being defined via `parser.decorate_error`), which means it only succeeds\n -- in-bounds, and the `many1` parser combinator retains that property.\n have : cb.size ≤ n := by simpa using list.drop_eq_nil_iff_le.mp hx,\n exact absurd (bounded.of_done hp) this.not_lt },\n -- We prove that the first digit parsed in is precisely the digit that is represented by the\n -- character at position `n`, which we now call `chd : char`.\n have chdh : chd.to_nat - '0'.to_nat = lhd,\n { simp only [many1_eq_done] at hp,\n -- We know that `parser.digit` succeeded, so it has moved to a possibly different position.\n -- In fact, we know that this new position is `n + 1`, by the `step` property of\n -- `parser.digit`.\n obtain ⟨_, hp, -⟩ := hp,\n have := step.of_done hp,\n subst this,\n -- We now unfold what it means for `parser.digit` to succeed, which means that the character\n -- parsed in was \"numeric\" (for some definition of that property), and, more importantly,\n -- that the `n`th character of `cb`, let's say `c`, when converted to a `ℕ` via\n -- `char.to_nat c - '0'.to_nat`, must be equal to the resulting value, `lhd` in our case.\n simp only [digit_eq_done, buffer.read_eq_nth_le_to_list, hx, buffer.length_to_list, true_and,\n add_left_inj, list.length, list.nth_le, eq_self_iff_true, exists_and_distrib_left,\n fin.coe_mk] at hp,\n rcases hp with ⟨_, hn, rfl, _, _⟩,\n -- But we already know the list corresponding to `cb : char_buffer` from position `n` and on\n -- is equal to `(chd :: ctl) : list char`, so our `c` above must satisfy `c = chd`.\n have hn' : n < cb.to_list.length := by simpa using hn,\n rw ←list.cons_nth_le_drop_succ hn' at hx,\n -- We can ignore proving any correspondence of `ctl : list char` to the other portions of the\n -- `cb : char_buffer`.\n simp only at hx,\n simp [hx] },\n -- We know that we parsed in more than one character because of the `prog` property of\n -- `parser.digit`, which the `many1` parser combinator retains. In other words, we know that\n -- `n < n'`, and so, the list of digits `ltl` must correspond to the list of digits that\n -- `digit.many1 cb (n + 1)` would produce. We know that the shift of `1` in `n ↦ n + 1` holds\n -- due to the `step` property of `parser.digit`.\n -- We also get here `k : ℕ` which will indicate how many characters we parsed in past position\n -- `n`. We will prove later that this must be the number of digits we produced as well in `ltl`.\n obtain ⟨k, hk⟩ : ∃ k, n' = n + k + 1 := nat.exists_eq_add_of_lt (prog.of_done hp),\n have hdm : ltl = [] ∨ digit.many1 cb (n + 1) = done n' ltl,\n { cases ltl,\n { simp },\n { rw many1_eq_done at hp,\n obtain ⟨_, hp, hp'⟩ := hp,\n simpa [step.of_done hp, many1_eq_done_iff_many_eq_done] using hp' } },\n -- Now we case on the two possibilities, that there was only a single digit parsed in, and\n -- `ltl = []`, or, had we started parsing at `n + 1` instead, we'd parse in the value associated\n -- with `ltl`.\n -- We prove that the LHS, which is a fold over a `list ℕ` is equal to the RHS, which is that\n -- the `val : ℕ` that `nat.of_digits` produces when supplied a `list ℕ that has been produced\n -- via mapping a `list char` using `char.to_nat`. Specifically, that `list char` are the\n -- characters in the `cb : char_buffer`, from position `n` to position `n'` (excluding `n'`),\n -- in reverse.\n rcases hdm with rfl|hdm,\n { -- Case that `ltl = []`.\n simp only [many1_eq_done, many_eq_done_nil, exists_and_distrib_right] at hp,\n -- This means we must have failed parsing with `parser.digit` at some other position,\n -- which we prove must be `n + 1` via the `step` property.\n obtain ⟨_, hp, rfl, hp'⟩ := hp,\n have := step.of_done hp,\n subst this,\n -- Now we rely on the simplifier, which simplfies the LHS, which is a fold over a singleton\n -- list. On the RHS, `list.take (n + 1 - n)` also produces a singleton list, which, when\n -- reversed, is the same list. `nat.of_digits` of a singleton list is precisely the value in\n -- the list. And we already have that `chd.to_nat - '0'.to_nat = lhd`.\n simp [chdh] },\n -- We now have to deal with the case where we parsed in more than one digit, and thus\n -- `n + 1 < n'`, which means `ctl` has one or more elements. Similarly, `ltl` has one or more\n -- elements.\n -- We finish ridding ourselves of references to `cb : char_buffer`, by relying on the fact that\n -- our `ctl : list char` must be the appropriate portion of `cb` once enough elements have been\n -- dropped and taken.\n have rearr :\n list.take (n + (k + 1) - (n + 1)) (list.drop (n + 1) (buffer.to_list cb)) = ctl.take k,\n { simp [←list.tail_drop, hx, nat.sub_succ, hk] },\n -- We have to prove that the number of digits produced (given by `ltl`) is equal to the number\n -- of characters parsed in, as given by `ctl.take k`, and that this is precisely `k`. We phrase it\n -- in the statement using `min`, because lemmas about `list.length (list.take ...)` simplify to\n -- a statement that uses `min`. The `list.length` term appears from the reduction of the folding\n -- function, as proven above.\n have ltll : min k ctl.length = ltl.length,\n { -- Here is an example of how statements about the `list.length` of `list.take` simplify.\n have : (ctl.take k).length = min k ctl.length := by simp,\n -- We bring back the underlying definition of `ctl` as the result of a sequence of `list.take`\n -- and `list.drop`, so that lemmas about `list.length` of those can fire.\n rw [←this, ←rearr, many1_length_of_done hdm],\n -- Likewise, we rid ourselves of the `k` we generated earlier.\n have : k = n' - n - 1,\n { simp [hk, add_assoc] },\n subst this,\n simp only [nat.sub_succ, add_comm, ←nat.pred_sub, buffer.length_to_list, nat.pred_one_add,\n min_eq_left_iff, list.length_drop, nat.add_sub_cancel_left, list.length_take,\n nat.sub_zero],\n -- We now have a goal of proving an inequality dealing with `nat` subtraction and `nat.pred`,\n -- both of which require special care to provide positivity hypotheses.\n rw [nat.sub_le_sub_right_iff, nat.pred_le_iff],\n { -- We know that `n' ≤ cb.size` because of the `bounded` property, that a parser will not\n -- produce a `done` result at a position farther than the size of the underlying\n -- `char_buffer`.\n convert many1_bounded_of_done hp,\n -- What is now left to prove is that `0 < cb.size`, which can be rephrased\n -- as proving that it is nonempty.\n cases hc : cb.size,\n { -- Proof by contradiction. Let's say that `cb.size = 0`. But we know that we succeeded\n -- parsing in at position `n` using a `bounded` parser, so we must have that\n -- `n < cb.size`.\n have := bounded.of_done hp,\n rw hc at this,\n -- But then `n < 0`, a contradiction.\n exact absurd n.zero_le this.not_le },\n { simp } },\n { -- Here, we use the same result as above, that `n < cb.size`, and relate it to\n -- `n ≤ cb.size.pred`.\n exact nat.le_pred_of_lt (bounded.of_done hp) } },\n -- Finally, we simplify. On the LHS, we have a fold over `lhd :: ltl`, which simplifies to\n -- the operation of the summing folding function on `lhd` and the fold over `ltl`. To that we can\n -- apply the induction hypothesis, because we know that our parser would have succeeded had we\n -- started at position `n + 1`. We replace mentions of `cb : char_buffer` with the appropriate\n -- `chd :: ctl`, replace `lhd` with the appropriate statement of how it is calculated from `chd`,\n -- and use the lemmas describing the length of `ltl` and how it is associated with `k`. We also\n -- remove mentions of `n'` and replace with an expression using solely `n + k + 1`.\n -- We use the lemma we proved above about how the folding function produces the\n -- `prod.snd` value, which is `10` to the power of the length of the list provided to the fold.\n -- Finally, we rely on `nat.of_digits_append` for the related statement of how digits given\n -- are used in the `nat.of_digits` calculation, which also involves `10 ^ list.length ...`.\n -- The `list.append` operation appears due to the `list.reverse (chd :: ctl)`.\n -- We include some addition and multiplication lemmas to help the simplifier rearrange terms.\n simp [IH _ hdm, hx, hk, rearr, ←chdh, ←ltll, hpow, add_assoc, nat.of_digits_append, mul_comm]\nend\n\n/--\nIf we know that `parser.nat` was successful, starting at position `n` and ending at position `n'`,\nthen it must be the case that for all `k : ℕ`, `n ≤ k`, `k < n'`, the character at the `k`th\nposition in `cb : char_buffer` is \"numeric\", that is, is between `'0'` and `'9'` inclusive.\n\nThis is a necessary part of proving one of the directions of `nat_eq_done`.\n-/\nlemma nat_of_done_as_digit {val : ℕ} (h : nat cb n = done n' val) :\n ∀ (hn : n' ≤ cb.size) k (hk : k < n'), n ≤ k →\n '0' ≤ cb.read ⟨k, hk.trans_le hn⟩ ∧ cb.read ⟨k, hk.trans_le hn⟩ ≤ '9' :=\nbegin\n -- The properties to be shown for the characters involved rely solely on the success of\n -- `parser.digit` at the relevant positions, and not on the actual value `parser.nat` produced.\n -- We break done the success of `parser.nat` into the `parser.digit` success and throw away\n -- the resulting value given by `parser.nat`, and focus solely on the `list ℕ` generated by\n -- `parser.digit.many1`.\n simp only [nat, pure_eq_done, and.left_comm, decorate_error_eq_done, bind_eq_done,\n exists_eq_left, exists_and_distrib_left] at h,\n obtain ⟨xs, h, -⟩ := h,\n -- We want to avoid having to make statements about the `cb : char_buffer` itself. Instead, we\n -- induct on the `xs : list ℕ` that `parser.digit.many1` produced.\n induction xs with hd tl hl generalizing n n',\n { -- Base case: `xs` is empty. But this is a contradiction because `many1` always produces a\n -- nonempty list, as proven by `many1_ne_done_nil`.\n simpa using h },\n -- Inductive case: we prove that the `parser.digit.many1` produced a valid `(hd :: tl) : list ℕ`,\n -- by showing that is the case for the character at position `n`, which gave `hd`, and use the\n -- induction hypothesis on the remaining `tl`.\n -- We break apart a `many1` success into a success of the underlying `parser.digit` to give `hd`\n -- and a `parser.digit.many` which gives `tl`. We first deal with the `hd`.\n rw many1_eq_done at h,\n -- Right away, we can throw away the information about the \"new\" position that `parser.digit`\n -- ended on because we will soon prove that it must have been `n + 1`.\n obtain ⟨_, hp, h⟩ := h,\n -- The main lemma here is `digit_eq_done`, which already proves the necessary conditions about\n -- the character at hand. What is left to do is properly unpack the information.\n simp only [digit_eq_done, and.comm, and.left_comm, digit_eq_fail, true_and, exists_eq_left,\n eq_self_iff_true, exists_and_distrib_left, exists_and_distrib_left] at hp,\n obtain ⟨rfl, -, hn, ge0, le9, rfl⟩ := hp,\n -- Let's now consider a position `k` between `n` and `n'`, excluding `n'`.\n intros hn k hk hk',\n -- What if we are at `n`? What if we are past `n`? We case on the `n ≤ k`.\n rcases hk'.eq_or_lt with rfl|hk',\n { -- The `n = k` case. But this is exactly what we know already, so we provide the\n -- relevant hypotheses.\n exact ⟨ge0, le9⟩ },\n -- The `n < k` case. First, we check if there would have even been digits parsed in. So, we\n -- case on `tl : list ℕ`\n cases tl,\n { -- Case where `tl = []`. But that means `many` gave us a `[]` so either the character at\n -- position `k` was not \"numeric\" or we are out of bounds. More importantly, when `many`\n -- successfully produces a `[]`, it does not progress the parser head, so we have that\n -- `n + 1 = n'`. This will lead to a contradiction because now we have `n < k` and `k < n + 1`.\n simp only [many_eq_done_nil, exists_and_distrib_right] at h,\n -- Extract out just the `n + 1 = n'`.\n obtain ⟨rfl, -⟩ := h,\n -- Form the contradictory hypothesis, and discharge the goal.\n have : k < k := hk.trans_le (nat.succ_le_of_lt hk'),\n exact absurd this (lt_irrefl _) },\n { -- Case where `tl ≠ []`. But that means that `many` produced a nonempty list as a result, so\n -- `many1` would have successfully parsed at this position too. We use this statement to\n -- rewrite our hypothesis into something that works with the induction hypothesis, and apply it.\n rw ←many1_eq_done_iff_many_eq_done at h,\n apply hl h,\n -- All that is left to prove is that our `k` is at least our new \"lower bound\" `n + 1`, which\n -- we have from our original split of the `n ≤ k`, since we are now on the `n < k` case.\n exact nat.succ_le_of_lt hk' }\nend\n\n/--\nIf we know that `parser.nat` was successful, starting at position `n` and ending at position `n'`,\nthen it must be the case that for the ending position `n'`, either it is beyond the end of the\n`cb : char_buffer`, or the character at that position is not \"numeric\", that is, between `'0'` and\n`'9'` inclusive.\n\nThis is a necessary part of proving one of the directions of `nat_eq_done`.\n-/\nlemma nat_of_done_bounded {val : ℕ} (h : nat cb n = done n' val) :\n ∀ (hn : n' < cb.size), '0' ≤ cb.read ⟨n', hn⟩ → '9' < cb.read ⟨n', hn⟩ :=\nbegin\n -- The properties to be shown for the characters involved rely solely on the success of\n -- `parser.digit` at the relevant positions, and not on the actual value `parser.nat` produced.\n -- We break done the success of `parser.nat` into the `parser.digit` success and throw away\n -- the resulting value given by `parser.nat`, and focus solely on the `list ℕ` generated by\n -- `parser.digit.many1`.\n -- We deal with the case of `n'` is \"out-of-bounds\" right away by requiring that\n -- `∀ (hn : n' < cb.size)`. Thus we only have to prove the lemma for the cases where `n'` is still\n -- \"in-bounds\".\n simp only [nat, pure_eq_done, and.left_comm, decorate_error_eq_done, bind_eq_done,\n exists_eq_left, exists_and_distrib_left] at h,\n obtain ⟨xs, h, -⟩ := h,\n -- We want to avoid having to make statements about the `cb : char_buffer` itself. Instead, we\n -- induct on the `xs : list ℕ` that `parser.digit.many1` produced.\n induction xs with hd tl hl generalizing n n',\n { -- Base case: `xs` is empty. But this is a contradiction because `many1` always produces a\n -- nonempty list, as proven by `many1_ne_done_nil`.\n simpa using h },\n -- Inductive case: at least one character has been parsed in, starting at position `n`.\n -- We know that the size of `cb : char_buffer` must be at least `n + 1` because\n -- `parser.digit.many1` is `bounded` (`n < cb.size`).\n -- We show that either we parsed in just that one character, or we use the inductive hypothesis.\n obtain ⟨k, hk⟩ : ∃ k, cb.size = n + k + 1 := nat.exists_eq_add_of_lt (bounded.of_done h),\n cases tl,\n { -- Case where `tl = []`, so we parsed in only `hd`. That must mean that `parser.digit` failed\n -- at `n + 1`.\n simp only [many1_eq_done, many_eq_done_nil, and.left_comm, exists_and_distrib_right,\n exists_eq_left] at h,\n -- We throw away the success information of what happened at position `n`, and we do not need\n -- the \"error\" value that the failure produced.\n obtain ⟨-, _, h⟩ := h,\n -- If `parser.digit` failed at `n + 1`, then either we hit a non-numeric character, or\n -- we are out of bounds. `digit_eq_fail` provides us with those two cases.\n simp only [digit_eq_done, and.comm, and.left_comm, digit_eq_fail, true_and, exists_eq_left,\n eq_self_iff_true, exists_and_distrib_left] at h,\n obtain (⟨rfl, h⟩ | ⟨h, -⟩) := h,\n { -- First case: we are still in bounds, but the character is not numeric. We must prove\n -- that we are still in bounds. But we know that from our initial requirement.\n intro hn,\n simpa using h hn },\n { -- Second case: we are out of bounds, and somehow the fold that `many1` relied on failed.\n -- But we know that `parser.digit` is mono, that is, it never goes backward in position,\n -- in neither success nor in failure. We also have that `foldr_core` respects `mono`.\n -- But in this case, `foldr_core` is starting at position `n' + 1` but failing at\n -- position `n'`, which is a contradiction, because otherwise we would have `n' + 1 ≤ n'`.\n simpa using mono.of_fail h } },\n { -- Case where `tl ≠ []`. But that means that `many` produced a nonempty list as a result, so\n -- `many1` would have successfully parsed at this position too. We use this statement to\n -- rewrite our hypothesis into something that works with the induction hypothesis, and apply it.\n rw many1_eq_done at h,\n obtain ⟨_, -, h⟩ := h,\n rw ←many1_eq_done_iff_many_eq_done at h,\n exact hl h }\nend\n\n/--\nThe `val : ℕ` produced by a successful parse of a `cb : char_buffer` is the numerical value\nrepresented by the string of decimal digits (possibly padded with 0s on the left)\nstarting from the parsing position `n` and ending at position `n'`, where `n < n'`. The number\nof characters parsed in is necessarily `n' - n`. Additionally, all of the characters in the `cb`\nstarting at position `n` (inclusive) up to position `n'` (exclusive) are \"numeric\", in that they\nare between `'0'` and `'9'` inclusive. Such a `char_buffer` would produce the `ℕ` value encoded\nby its decimal characters.\n-/\nlemma nat_eq_done {val : ℕ} : nat cb n = done n' val ↔ ∃ (hn : n < n'),\n val = (nat.of_digits 10 ((((cb.to_list.drop n).take (n' - n)).reverse.map\n (λ c, c.to_nat - '0'.to_nat)))) ∧ (∀ (hn' : n' < cb.size),\n ('0' ≤ cb.read ⟨n', hn'⟩ → '9' < cb.read ⟨n', hn'⟩)) ∧ ∃ (hn'' : n' ≤ cb.size),\n (∀ k (hk : k < n'), n ≤ k →\n '0' ≤ cb.read ⟨k, hk.trans_le hn''⟩ ∧ cb.read ⟨k, hk.trans_le hn''⟩ ≤ '9') :=\nbegin\n -- To prove this iff, we have most of the way in the forward direction, using the lemmas proven\n -- above. First, we must use that `parser.nat` is `prog`, which means that on success, it must\n -- move forward. We also have to prove the statement that a success means the parsed in\n -- characters were properly \"numeric\". It involves first generating ane existential witness\n -- that the parse was completely \"in-bounds\".\n -- For the reverse direction, we first discharge the goals that deal with proving that our parser\n -- succeeded because it encountered characters with the proper \"numeric\" properties, was\n -- \"in-bounds\" and hit a nonnumeric character. The more difficult portion is proving that the\n -- list of characters from positions `n` to `n'`, when folded over by the function defined inside\n -- `parser.nat` gives exactly the same value as `nat.of_digits` when supplied with the same\n -- (modulo rearrangement) list. To reach this goal, we try to remove any reliance on the\n -- underlying `cb : char_buffer` or parsers as soon as possible, via a cased-induction.\n refine ⟨λ h, ⟨prog.of_done h, nat_of_done h, nat_of_done_bounded h, _⟩, _⟩,\n { -- To provide the existential witness that `n'` is within the bounds of the `cb : char_buffer`,\n -- we rely on the fact that `parser.nat` is primarily a `parser.digit.many1`, and that `many1`,\n -- must finish with the bounds of the `cb`, as long as the underlying parser is `step` and\n -- `bounded`, which `digit` is. We do not prove this as a separate lemma about `parser.nat`\n -- because it would almost always be only relevant in this larger theorem.\n -- We clone the success hypothesis `h` so that we can supply it back later.\n have H := h,\n -- We unwrap the `parser.nat` success down to the `many1` success, throwing away other info.\n rw [nat] at h,\n simp only [decorate_error_eq_done, bind_eq_done, pure_eq_done, and.left_comm, exists_eq_left,\n exists_and_distrib_left] at h,\n obtain ⟨_, h, -⟩ := h,\n -- Now we get our existential witness that `n' ≤ cb.size`.\n replace h := many1_bounded_of_done h,\n -- With that, we can use the lemma proved above that our characters are \"numeric\"\n exact ⟨h, nat_of_done_as_digit H h⟩ },\n -- We now prove that given the `cb : char_buffer` with characters within the `n ≤ k < n'` interval\n -- properly \"numeric\" and such that their `nat.of_digits` generates the `val : ℕ`, `parser.nat`\n -- of that `cb`, when starting at `n`, will finish at `n'` and produce the same `val`.\n -- We first introduce the relevant hypotheses, including the fact that we have a valid interval\n -- where `n < n'` and that characters at `n'` and beyond are no longer numeric.\n rintro ⟨hn, hv, hb, hn', ho⟩,\n -- We first unwrap the `parser.nat` definition to the underlying `parser.digit.many1` success\n -- and the fold function of the digits.\n rw nat,\n simp only [and.left_comm, pure_eq_done, hv, decorate_error_eq_done, list.map_reverse,\n bind_eq_done, exists_eq_left, exists_and_distrib_left],\n -- We won't actually need the `val : ℕ` itself, since it is entirely characterized by the\n -- underlying characters. Instead, we will induct over the `list char` of characters from\n -- position `n` onwards, showing that if we could have provided a list at `n`, we could have\n -- provided a valid list of characters at `n + 1` too.\n clear hv val,\n /- We first prove some helper lemmas about the definition of `parser.nat`. Since it is defined\n in core, we have to work with how it is defined instead of changing its definition.\n In its definition, the function that folds over the parsed in digits is defined internally,\n as a lambda with anonymous destructor syntax, which leads to an unpleasant `nat._match_1` term\n when rewriting the definition of `parser.nat` away. Since we know exactly what the function is,\n we have a `rfl`-like lemma here to rewrite it back into a readable form.\n -/\n have natm : nat._match_1 = (λ (d : ℕ) p, ⟨p.1 + d * p.2, p.2 * 10⟩),\n { ext1, ext1 ⟨⟩, refl },\n -- We induct over the characters available at position `n` and onwards. Because `cb` is used\n -- in other expressions, we utilize the `induction H : ...` tactic to induct separately from\n -- destructing `cb` itself.\n induction H : (cb.to_list.drop n) with hd tl IH generalizing n,\n { -- Base case: there are no characters at position `n` or onwards, which means that\n -- `cb.size ≤ n`. But this is a contradiction, since we have `n < n' ≤ cb.size`.\n rw list.drop_eq_nil_iff_le at H,\n refine absurd ((lt_of_le_of_lt H hn).trans_le hn') _,\n simp },\n { -- Inductive case: we prove that if we could have parsed from `n + 1`, we could have also parsed\n -- from `n`, if there was a valid numerical character at `n`. Most of the body\n -- of this inductive case is generating the appropriate conditions for use of the inductive\n -- hypothesis.\n specialize @IH (n + 1),\n -- We have, by the inductive case, that there is at least one character `hd` at position `n`,\n -- with the rest at `tl`. We rearrange our inductive case to make `tl` be expressed as\n -- list.drop (n + 1), which fits out induction hypothesis conditions better. To use the\n -- rearranging lemma, we must prove that we are \"dropping\" in bounds, which we supply on-the-fly\n simp only [←list.cons_nth_le_drop_succ\n (show n < cb.to_list.length, by simpa using hn.trans_le hn')] at H,\n -- We prove that parsing our `n`th character, `hd`, would have resulted in a success from\n -- `parser.digit`, with the appropriate `ℕ` success value. We use this later to simplify the\n -- unwrapped fold, since `hd` is our head character.\n have hdigit : digit cb n = done (n + 1) (hd.to_nat - '0'.to_nat),\n { -- By our necessary condition, we know that `n` is in bounds, and that the `n`th character\n -- has the necessary \"numeric\" properties.\n specialize ho n hn (le_refl _),\n -- We prove an additional result that the conversion of `hd : char` to a `ℕ` would give a\n -- value `x ≤ 9`, since that is part of the iff statement in the `digit_eq_done` lemma.\n have : (buffer.read cb ⟨n, hn.trans_le hn'⟩).to_nat - '0'.to_nat ≤ 9,\n { -- We rewrite the statement to be a statement about characters instead, and split the\n -- inequality into the case that our hypotheses prove, and that `'0' ≤ '9'`, which\n -- is true by computation, handled by `dec_trivial`.\n rw [show 9 = '9'.to_nat - '0'.to_nat, from dec_trivial, nat.sub_le_sub_right_iff],\n { exact ho.right },\n { dec_trivial } },\n -- We rely on the simplifier, mostly powered by `digit_eq_done`, and supply all the\n -- necessary conditions of bounds and identities about `hd`.\n simp [digit_eq_done, this, ←H.left, buffer.nth_le_to_list, hn.trans_le hn', ho] },\n -- We now case on whether we've moved to the end of our parse or not. We phrase this as\n -- casing on either `n + 1 < n` or `n ≤ n + 1`. The more difficult goal comes first.\n cases lt_or_ge (n + 1) n' with hn'' hn'',\n { -- Case `n + 1 < n'`. We can directly supply this to our induction hypothesis.\n -- We now have to prove, for the induction hypothesis, that the characters at positions `k`,\n -- `n + 1 ≤ k < n'` are \"numeric\". We already had this for `n ≤ k < n`, so we just rearrange\n -- the hypotheses we already have.\n specialize IH hn'' _ H.right,\n { intros k hk hk',\n apply ho,\n exact nat.le_of_succ_le hk' },\n -- With the induction hypothesis conditions satisfier, we can extract out a list that\n -- `parser.digit.many1` would have generated from position `n + 1`, as well as the associated\n -- property of the list, that it folds into what `nat.of_digits` generates from the\n -- characters in `cb : char_buffer`, now known as `hd :: tl`.\n obtain ⟨l, hdl, hvl⟩ := IH,\n -- Of course, the parsed in list from position `n` would be `l` prepended with the result\n -- of parsing in `hd`, which is provided explicitly.\n use (hd.to_nat - '0'.to_nat) :: l,\n -- We case on `l : list ℕ` so that we can make statements about the fold on `l`\n cases l with lhd ltl,\n { -- As before, if `l = []` then `many1` produced a `[]` success, which is a contradiction.\n simpa using hdl },\n -- Case `l = lhd :: ltl`. We can rewrite the fold of the function inside `parser.nat` on\n -- `lhd :: ltl`, which will be used to rewrite in the goal.\n simp only [natm, list.foldr] at hvl,\n -- We also expand the fold in the goal, using the expanded fold from our hypothesis, powered\n -- by `many1_eq_done` to proceed in the parsing. We know exactly what the next `many` will\n -- produce from `many1_eq_done_iff_many_eq_done.mp` of our `hdl` hypothesis. Finally,\n -- we also use `hdigit` to express what the single `parser.digit` result would be at `n`.\n simp only [natm, hvl, many1_eq_done, hdigit, many1_eq_done_iff_many_eq_done.mp hdl, true_and,\n and_true, eq_self_iff_true, list.foldr, exists_eq_left'],\n -- Now our goal is solely about the equality of two different folding functions, one from the\n -- function defined inside `parser.nat` and the other as `nat.of_digits`, when applied to\n -- similar list inputs.\n -- First, we rid ourselves of `n'` by replacing with `n + m + 1`, which allows us to\n -- simplify the term of how many elements we are keeping using a `list.take`.\n obtain ⟨m, rfl⟩ : ∃ m, n' = n + m + 1 := nat.exists_eq_add_of_lt hn,\n -- The following rearrangement lemma is to simplify the `list.take (n' - n)` expression we had\n have : n + m + 1 - n = m + 1,\n { rw [add_assoc, nat.sub_eq_iff_eq_add, add_comm],\n exact nat.le_add_right _ _ },\n -- We also have to prove what is the `prod.snd` of the result of the fold of a `list (ℕ × ℕ)`\n -- with the function above. We use this lemma to finish our inductive case.\n have hpow : ∀ l, (list.foldr (λ (digit : ℕ) (x : ℕ × ℕ),\n (x.fst + digit * x.snd, x.snd * 10)) (0, 1) l).snd = 10 ^ l.length,\n { intro l,\n induction l with hd tl hl,\n { simp },\n { simp [hl, pow_succ, mul_comm] } },\n -- We prove that the parsed list of digits `(lhd :: ltl) : list ℕ` must be of length `m`\n -- which is used later when the `parser.nat` fold places `ltl.length` in the exponent.\n have hml : ltl.length + 1 = m := by simpa using many1_length_of_done hdl,\n -- A simplified `list.length (list.take ...)` expression refers to the minimum of the\n -- underlying length and the amount of elements taken. We know that `m ≤ tl.length`, so\n -- we provide this auxiliary lemma so that the simplified \"take-length\" can simplify further\n have ltll : min m tl.length = m,\n { -- On the way to proving this, we have to actually show that `m ≤ tl.length`, by showing\n -- that since `tl` was a subsequence in `cb`, and was retrieved from `n + 1` to `n + m + 1`,\n -- then since `n + m + 1 ≤ cb.size`, we have that `tl` must be at least `m` in length.\n simpa [←H.right, ←nat.add_le_to_le_sub _ (hn''.trans_le hn').le, add_comm, add_assoc,\n add_left_comm] using hn' },\n -- Finally, we rely on the simplifier. We already expressions of `nat.of_digits` on both\n -- the LHS and RHS. All that is left to do is to prove that the summand on the LHS is produced\n -- by the fold of `nat.of_digits` on the RHS of `hd :: tl`. The `nat.of_digits_append` is used\n -- because of the append that forms from the included `list.reverse`. The lengths of the lists\n -- are placed in the exponents with `10` as a base, and are combined using `←pow_succ 10`.\n -- Any complicated expression about list lengths is further simplified by the auxiliary\n -- lemmas we just proved. Finally, we assist the simplifier by rearranging terms with our\n -- `n + m + 1 - n = m + 1` proof and `mul_comm`.\n simp [this, hpow, nat.of_digits_append, mul_comm, ←pow_succ 10, hml, ltll] },\n { -- Consider the case that `n' ≤ n + 1`. But then since `n < n' ≤ n + 1`, `n' = n + 1`.\n have : n' = n + 1 := le_antisymm hn'' (nat.succ_le_of_lt hn),\n subst this,\n -- This means we have only parsed in a single character, so the resulting parsed in list\n -- is explicitly formed from an expression we can construct from `hd`.\n use [[hd.to_nat - '0'.to_nat]],\n -- Our list expression simplifies nicely because it is a fold over a singleton, so we\n -- do not have to supply any auxiliary lemmas for it, other than what we already know about\n -- `hd` and the function defined in `parser.nat`. However, we will have to prove that our\n -- parse ended because of a good reason: either we are out of bounds or we hit a nonnumeric\n -- character.\n simp only [many1_eq_done, many_eq_done_nil, digit_eq_fail, natm, and.comm, and.left_comm,\n hdigit, true_and, mul_one, nat.of_digits_singleton, list.take, exists_eq_left,\n exists_and_distrib_right, nat.add_sub_cancel_left, eq_self_iff_true,\n list.reverse_singleton, zero_add, list.foldr, list.map],\n -- We take the route of proving that we hit a nonnumeric character, since we already have\n -- a hypothesis that says that characters at `n'` and past it are nonnumeric. (Note, by now\n -- we have substituted `n + 1` for `n'.\n -- We are also asked to provide the error value that our failed parse would report. But\n -- `digit_eq_fail` already knows what it is, so we can discharge that with an inline `rfl`.\n refine ⟨_, or.inl ⟨rfl, _⟩⟩,\n -- The nonnumeric condition looks almost exactly like the hypothesis we already have, so\n -- we let the simplifier align them for us\n simpa using hb } }\nend\n\nend nat\n\nend parser\n", "meta": {"author": "JLimperg", "repo": "aesop3", "sha": "a4a116f650cc7403428e72bd2e2c4cda300fe03f", "save_path": "github-repos/lean/JLimperg-aesop3", "path": "github-repos/lean/JLimperg-aesop3/aesop3-a4a116f650cc7403428e72bd2e2c4cda300fe03f/src/data/buffer/parser/basic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47268347662043286, "lm_q2_score": 0.09401017327074415, "lm_q1q2_score": 0.04443705553930464}} {"text": "/-\nCopyright (c) 2017 Mario Carneiro. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Mario Carneiro\n-/\nimport logic.is_empty\nimport control.traversable.basic\nimport tactic.basic\n\n/-!\n# Option of a type\n\n> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.\n> Any changes to this file require a corresponding PR to mathlib4.\n\nThis file develops the basic theory of option types.\n\nIf `α` is a type, then `option α` can be understood as the type with one more element than `α`.\n`option α` has terms `some a`, where `a : α`, and `none`, which is the added element.\nThis is useful in multiple ways:\n* It is the prototype of addition of terms to a type. See for example `with_bot α` which uses\n `none` as an element smaller than all others.\n* It can be used to define failsafe partial functions, which return `some the_result_we_expect`\n if we can find `the_result_we_expect`, and `none` if there is no meaningful result. This forces\n any subsequent use of the partial function to explicitly deal with the exceptions that make it\n return `none`.\n* `option` is a monad. We love monads.\n\n`part` is an alternative to `option` that can be seen as the type of `true`/`false` values\nalong with a term `a : α` if the value is `true`.\n\n## Implementation notes\n\n`option` is currently defined in core Lean, but this will change in Lean 4.\n-/\n\nnamespace option\nvariables {α β γ δ : Type*}\n\nlemma coe_def : (coe : α → option α) = some := rfl\nlemma some_eq_coe (a : α) : some a = a := rfl\n\nlemma some_ne_none (x : α) : some x ≠ none := λ h, option.no_confusion h\n@[simp] lemma coe_ne_none (a : α) : (a : option α) ≠ none .\n\nprotected lemma «forall» {p : option α → Prop} : (∀ x, p x) ↔ p none ∧ ∀ x, p (some x) :=\n⟨λ h, ⟨h _, λ x, h _⟩, λ h x, option.cases_on x h.1 h.2⟩\n\nprotected lemma «exists» {p : option α → Prop} : (∃ x, p x) ↔ p none ∨ ∃ x, p (some x) :=\n⟨λ ⟨x, hx⟩, (option.cases_on x or.inl $ λ x hx, or.inr ⟨x, hx⟩) hx,\n λ h, h.elim (λ h, ⟨_, h⟩) (λ ⟨x, hx⟩, ⟨_, hx⟩)⟩\n\n@[simp] theorem get_mem : ∀ {o : option α} (h : is_some o), option.get h ∈ o\n| (some a) _ := rfl\n\ntheorem get_of_mem {a : α} : ∀ {o : option α} (h : is_some o), a ∈ o → option.get h = a\n| _ _ rfl := rfl\n\n@[simp] lemma not_mem_none (a : α) : a ∉ (none : option α) :=\nλ h, option.no_confusion h\n\n@[simp] lemma some_get : ∀ {x : option α} (h : is_some x), some (option.get h) = x\n| (some x) hx := rfl\n\n@[simp] lemma get_some (x : α) (h : is_some (some x)) : option.get h = x := rfl\n\n@[simp] lemma get_or_else_some (x y : α) : option.get_or_else (some x) y = x := rfl\n\n@[simp] lemma get_or_else_none (x : α) : option.get_or_else none x = x := rfl\n\n@[simp] lemma get_or_else_coe (x y : α) : option.get_or_else ↑x y = x := rfl\n\nlemma get_or_else_of_ne_none {x : option α} (hx : x ≠ none) (y : α) : some (x.get_or_else y) = x :=\nby cases x; [contradiction, rw get_or_else_some]\n\n@[simp] lemma coe_get {o : option α} (h : o.is_some) : ((option.get h : α) : option α) = o :=\noption.some_get h\n\ntheorem mem_unique {o : option α} {a b : α} (ha : a ∈ o) (hb : b ∈ o) : a = b :=\noption.some.inj $ ha.symm.trans hb\n\ntheorem eq_of_mem_of_mem {a : α} {o1 o2 : option α} (h1 : a ∈ o1) (h2 : a ∈ o2) : o1 = o2 :=\nh1.trans h2.symm\n\ntheorem mem.left_unique : relator.left_unique ((∈) : α → option α → Prop) :=\nλ a o b, mem_unique\n\ntheorem some_injective (α : Type*) : function.injective (@some α) :=\nλ _ _, some_inj.mp\n\n/-- `option.map f` is injective if `f` is injective. -/\ntheorem map_injective {f : α → β} (Hf : function.injective f) : function.injective (option.map f)\n| none none H := rfl\n| (some a₁) (some a₂) H := by rw Hf (option.some.inj H)\n\n@[simp] theorem map_comp_some (f : α → β) : option.map f ∘ some = some ∘ f := rfl\n\n@[ext] theorem ext : ∀ {o₁ o₂ : option α}, (∀ a, a ∈ o₁ ↔ a ∈ o₂) → o₁ = o₂\n| none none H := rfl\n| (some a) o H := ((H _).1 rfl).symm\n| o (some b) H := (H _).2 rfl\n\ntheorem eq_none_iff_forall_not_mem {o : option α} :\n o = none ↔ (∀ a, a ∉ o) :=\n⟨λ e a h, by rw e at h; cases h, λ h, ext $ by simpa⟩\n\n@[simp] theorem none_bind {α β} (f : α → option β) : none >>= f = none := rfl\n\n@[simp] theorem some_bind {α β} (a : α) (f : α → option β) : some a >>= f = f a := rfl\n\n@[simp] theorem none_bind' (f : α → option β) : none.bind f = none := rfl\n\n@[simp] theorem some_bind' (a : α) (f : α → option β) : (some a).bind f = f a := rfl\n\n@[simp] theorem bind_some : ∀ x : option α, x >>= some = x :=\n@bind_pure α option _ _\n\n@[simp] theorem bind_some' : ∀ x : option α, x.bind some = x :=\nbind_some\n\n@[simp] theorem bind_eq_some {α β} {x : option α} {f : α → option β} {b : β} :\n x >>= f = some b ↔ ∃ a, x = some a ∧ f a = some b :=\nby cases x; simp\n\n@[simp] theorem bind_eq_some' {x : option α} {f : α → option β} {b : β} :\n x.bind f = some b ↔ ∃ a, x = some a ∧ f a = some b :=\nby cases x; simp\n\n@[simp] theorem bind_eq_none' {o : option α} {f : α → option β} :\n o.bind f = none ↔ (∀ b a, a ∈ o → b ∉ f a) :=\nby simp only [eq_none_iff_forall_not_mem, not_exists, not_and, mem_def, bind_eq_some']\n\n@[simp] theorem bind_eq_none {α β} {o : option α} {f : α → option β} :\n o >>= f = none ↔ (∀ b a, a ∈ o → b ∉ f a) :=\nbind_eq_none'\n\nlemma bind_comm {α β γ} {f : α → β → option γ} (a : option α) (b : option β) :\n a.bind (λx, b.bind (f x)) = b.bind (λy, a.bind (λx, f x y)) :=\nby cases a; cases b; refl\n\nlemma bind_assoc (x : option α) (f : α → option β) (g : β → option γ) :\n (x.bind f).bind g = x.bind (λ y, (f y).bind g) := by cases x; refl\n\nlemma join_eq_some {x : option (option α)} {a : α} : x.join = some a ↔ x = some (some a) := by simp\n\nlemma join_ne_none {x : option (option α)} : x.join ≠ none ↔ ∃ z, x = some (some z) := by simp\n\nlemma join_ne_none' {x : option (option α)} : ¬(x.join = none) ↔ ∃ z, x = some (some z) := by simp\n\nlemma join_eq_none {o : option (option α)} : o.join = none ↔ o = none ∨ o = some none :=\nby rcases o with _|_|_; simp\n\nlemma bind_id_eq_join {x : option (option α)} : x >>= id = x.join := by simp\n\nlemma join_eq_join : mjoin = @join α :=\nfunext (λ x, by rw [mjoin, bind_id_eq_join])\n\nlemma bind_eq_bind {α β : Type*} {f : α → option β} {x : option α} :\n x >>= f = x.bind f := rfl\n\n@[simp] lemma map_eq_map {α β} {f : α → β} :\n (<$>) f = option.map f := rfl\n\ntheorem map_none {α β} {f : α → β} : f <$> none = none := rfl\n\ntheorem map_some {α β} {a : α} {f : α → β} : f <$> some a = some (f a) := rfl\n\ntheorem map_coe {α β} {a : α} {f : α → β} : f <$> (a : option α) = ↑(f a) := rfl\n\n@[simp] theorem map_none' {f : α → β} : option.map f none = none := rfl\n\n@[simp] theorem map_some' {a : α} {f : α → β} : option.map f (some a) = some (f a) := rfl\n\n@[simp] theorem map_coe' {a : α} {f : α → β} : option.map f (a : option α) = ↑(f a) := rfl\n\ntheorem map_eq_some {α β} {x : option α} {f : α → β} {b : β} :\n f <$> x = some b ↔ ∃ a, x = some a ∧ f a = b :=\nby cases x; simp\n\n@[simp] theorem map_eq_some' {x : option α} {f : α → β} {b : β} :\n x.map f = some b ↔ ∃ a, x = some a ∧ f a = b :=\nby cases x; simp\n\nlemma map_eq_none {α β} {x : option α} {f : α → β} :\n f <$> x = none ↔ x = none :=\nby { cases x; simp only [map_none, map_some, eq_self_iff_true] }\n\n@[simp] lemma map_eq_none' {x : option α} {f : α → β} :\n x.map f = none ↔ x = none :=\nby { cases x; simp only [map_none', map_some', eq_self_iff_true] }\n\n/-- `option.map` as a function between functions is injective. -/\ntheorem map_injective' : function.injective (@option.map α β) :=\nλ f g h, funext $ λ x, some_injective _ $ by simp only [← map_some', h]\n\n@[simp] theorem map_inj {f g : α → β} : option.map f = option.map g ↔ f = g :=\nmap_injective'.eq_iff\n\nlemma map_congr {f g : α → β} {x : option α} (h : ∀ a ∈ x, f a = g a) :\n option.map f x = option.map g x :=\nby { cases x; simp only [map_none', map_some', h, mem_def] }\n\nattribute [simp] map_id\n\n@[simp] theorem map_eq_id {f : α → α} : option.map f = id ↔ f = id := map_injective'.eq_iff' map_id\n\n@[simp] lemma map_map (h : β → γ) (g : α → β) (x : option α) :\n option.map h (option.map g x) = option.map (h ∘ g) x :=\nby { cases x; simp only [map_none', map_some'] }\n\nlemma map_comm {f₁ : α → β} {f₂ : α → γ} {g₁ : β → δ} {g₂ : γ → δ} (h : g₁ ∘ f₁ = g₂ ∘ f₂) (a : α) :\n (option.map f₁ a).map g₁ = (option.map f₂ a).map g₂ :=\nby rw [map_map, h, ←map_map]\n\nlemma comp_map (h : β → γ) (g : α → β) (x : option α) :\n option.map (h ∘ g) x = option.map h (option.map g x) := (map_map _ _ _).symm\n\n@[simp] lemma map_comp_map (f : α → β) (g : β → γ) :\n option.map g ∘ option.map f = option.map (g ∘ f) :=\nby { ext x, rw comp_map }\n\nlemma mem_map_of_mem {a : α} {x : option α} (g : α → β) (h : a ∈ x) : g a ∈ x.map g :=\nmem_def.mpr ((mem_def.mp h).symm ▸ map_some')\n\nlemma mem_map {f : α → β} {y : β} {o : option α} : y ∈ o.map f ↔ ∃ x ∈ o, f x = y := by simp\n\nlemma forall_mem_map {f : α → β} {o : option α} {p : β → Prop} :\n (∀ y ∈ o.map f, p y) ↔ ∀ x ∈ o, p (f x) :=\nby simp\n\nlemma exists_mem_map {f : α → β} {o : option α} {p : β → Prop} :\n (∃ y ∈ o.map f, p y) ↔ ∃ x ∈ o, p (f x) :=\nby simp\n\nlemma bind_map_comm {α β} {x : option (option α) } {f : α → β} :\n x >>= option.map f = x.map (option.map f) >>= id :=\nby { cases x; simp }\n\nlemma join_map_eq_map_join {f : α → β} {x : option (option α)} :\n (x.map (option.map f)).join = x.join.map f :=\nby { rcases x with _ | _ | x; simp }\n\nlemma join_join {x : option (option (option α))} :\n x.join.join = (x.map join).join :=\nby { rcases x with _ | _ | _ | x; simp }\n\nlemma mem_of_mem_join {a : α} {x : option (option α)} (h : a ∈ x.join) : some a ∈ x :=\nmem_def.mpr ((mem_def.mp h).symm ▸ join_eq_some.mp h)\n\nsection pmap\n\nvariables {p : α → Prop} (f : Π (a : α), p a → β) (x : option α)\n\n@[simp] lemma pbind_eq_bind (f : α → option β) (x : option α) :\n x.pbind (λ a _, f a) = x.bind f :=\nby { cases x; simp only [pbind, none_bind', some_bind'] }\n\nlemma map_bind {α β γ} (f : β → γ) (x : option α) (g : α → option β) :\n option.map f (x >>= g) = (x >>= λ a, option.map f (g a)) :=\nby simp_rw [←map_eq_map, ←bind_pure_comp_eq_map,is_lawful_monad.bind_assoc]\n\nlemma map_bind' (f : β → γ) (x : option α) (g : α → option β) :\n option.map f (x.bind g) = x.bind (λ a, option.map f (g a)) :=\nby { cases x; simp }\n\nlemma map_pbind (f : β → γ) (x : option α) (g : Π a, a ∈ x → option β) :\n option.map f (x.pbind g) = (x.pbind (λ a H, option.map f (g a H))) :=\nby { cases x; simp only [pbind, map_none'] }\n\nlemma pbind_map (f : α → β) (x : option α) (g : Π (b : β), b ∈ x.map f → option γ) :\n pbind (option.map f x) g = x.pbind (λ a h, g (f a) (mem_map_of_mem _ h)) :=\nby { cases x; refl }\n\n@[simp] lemma pmap_none (f : Π (a : α), p a → β) {H} : pmap f (@none α) H = none := rfl\n\n@[simp] lemma pmap_some (f : Π (a : α), p a → β) {x : α} (h : p x) :\n pmap f (some x) = λ _, some (f x h) := rfl\n\nlemma mem_pmem {a : α} (h : ∀ a ∈ x, p a) (ha : a ∈ x) :\n f a (h a ha) ∈ pmap f x h :=\nby { rw mem_def at ha ⊢, subst ha, refl }\n\nlemma pmap_map (g : γ → α) (x : option γ) (H) :\n pmap f (x.map g) H = pmap (λ a h, f (g a) h) x (λ a h, H _ (mem_map_of_mem _ h)) :=\nby { cases x; simp only [map_none', map_some', pmap] }\n\nlemma map_pmap (g : β → γ) (f : Π a, p a → β) (x H) :\n option.map g (pmap f x H) = pmap (λ a h, g (f a h)) x H :=\nby { cases x; simp only [map_none', map_some', pmap] }\n\n@[simp] lemma pmap_eq_map (p : α → Prop) (f : α → β) (x H) :\n @pmap _ _ p (λ a _, f a) x H = option.map f x :=\nby { cases x; simp only [map_none', map_some', pmap] }\n\n\n\nlemma bind_pmap {α β γ} {p : α → Prop} (f : Π a, p a → β) (x : option α) (g : β → option γ) (H) :\n (pmap f x H) >>= g = x.pbind (λ a h, g (f a (H _ h))) :=\nby { cases x; simp only [pmap, none_bind, some_bind, pbind] }\n\nvariables {f x}\n\nlemma pbind_eq_none {f : Π (a : α), a ∈ x → option β}\n (h' : ∀ a ∈ x, f a H = none → x = none) :\n x.pbind f = none ↔ x = none :=\nbegin\n cases x,\n { simp },\n { simp only [pbind, iff_false],\n intro h,\n cases h' x rfl h }\nend\n\nlemma pbind_eq_some {f : Π (a : α), a ∈ x → option β} {y : β} :\n x.pbind f = some y ↔ ∃ (z ∈ x), f z H = some y :=\nbegin\n cases x,\n { simp },\n { simp only [pbind],\n split,\n { intro h,\n use x,\n simpa only [mem_def, exists_prop_of_true] using h },\n { rintro ⟨z, H, hz⟩,\n simp only [mem_def] at H,\n simpa only [H] using hz } }\nend\n\n@[simp] lemma pmap_eq_none_iff {h} :\n pmap f x h = none ↔ x = none :=\nby { cases x; simp }\n\n@[simp] lemma pmap_eq_some_iff {hf} {y : β} :\n pmap f x hf = some y ↔ ∃ (a : α) (H : x = some a), f a (hf a H) = y :=\nbegin\n cases x,\n { simp only [not_mem_none, exists_false, pmap, not_false_iff, exists_prop_of_false] },\n { split,\n { intro h,\n simp only [pmap] at h,\n exact ⟨x, rfl, h⟩ },\n { rintro ⟨a, H, rfl⟩,\n simp only [mem_def] at H,\n simp only [H, pmap] } }\nend\n\n@[simp] lemma join_pmap_eq_pmap_join {f : Π a, p a → β} {x : option (option α)} (H) :\n (pmap (pmap f) x H).join = pmap f x.join (λ a h, H (some a) (mem_of_mem_join h) _ rfl) :=\nby { rcases x with _ | _ | x; simp }\n\nend pmap\n\n@[simp] theorem seq_some {α β} {a : α} {f : α → β} : some f <*> some a = some (f a) := rfl\n\n@[simp] theorem some_orelse' (a : α) (x : option α) : (some a).orelse x = some a := rfl\n\n@[simp] theorem some_orelse (a : α) (x : option α) : (some a <|> x) = some a := rfl\n\n@[simp] theorem none_orelse' (x : option α) : none.orelse x = x :=\nby cases x; refl\n\n@[simp] theorem none_orelse (x : option α) : (none <|> x) = x := none_orelse' x\n\n@[simp] theorem orelse_none' (x : option α) : x.orelse none = x :=\nby cases x; refl\n\n@[simp] theorem orelse_none (x : option α) : (x <|> none) = x := orelse_none' x\n\n@[simp] theorem is_some_none : @is_some α none = ff := rfl\n\n@[simp] theorem is_some_some {a : α} : is_some (some a) = tt := rfl\n\ntheorem is_some_iff_exists {x : option α} : is_some x ↔ ∃ a, x = some a :=\nby cases x; simp [is_some]; exact ⟨_, rfl⟩\n\n@[simp] theorem is_none_none : @is_none α none = tt := rfl\n\n@[simp] theorem is_none_some {a : α} : is_none (some a) = ff := rfl\n\n@[simp] theorem not_is_some {a : option α} : is_some a = ff ↔ a.is_none = tt :=\nby cases a; simp\n\nlemma eq_some_iff_get_eq {o : option α} {a : α} :\n o = some a ↔ ∃ h : o.is_some, option.get h = a :=\nby cases o; simp\n\nlemma not_is_some_iff_eq_none {o : option α} : ¬o.is_some ↔ o = none :=\nby cases o; simp\n\nlemma ne_none_iff_is_some {o : option α} : o ≠ none ↔ o.is_some :=\nby cases o; simp\n\nlemma ne_none_iff_exists {o : option α} : o ≠ none ↔ ∃ (x : α), some x = o :=\nby {cases o; simp}\n\nlemma ne_none_iff_exists' {o : option α} : o ≠ none ↔ ∃ (x : α), o = some x :=\nne_none_iff_exists.trans $ exists_congr $ λ _, eq_comm\n\nlemma bex_ne_none {p : option α → Prop} :\n (∃ x ≠ none, p x) ↔ ∃ x, p (some x) :=\n⟨λ ⟨x, hx, hp⟩, ⟨get $ ne_none_iff_is_some.1 hx, by rwa [some_get]⟩,\n λ ⟨x, hx⟩, ⟨some x, some_ne_none x, hx⟩⟩\n\nlemma ball_ne_none {p : option α → Prop} :\n (∀ x ≠ none, p x) ↔ ∀ x, p (some x) :=\n⟨λ h x, h (some x) (some_ne_none x),\n λ h x hx, by simpa only [some_get] using h (get $ ne_none_iff_is_some.1 hx)⟩\n\ntheorem iget_mem [inhabited α] : ∀ {o : option α}, is_some o → o.iget ∈ o\n| (some a) _ := rfl\n\ntheorem iget_of_mem [inhabited α] {a : α} : ∀ {o : option α}, a ∈ o → o.iget = a\n| _ rfl := rfl\n\nlemma get_or_else_default_eq_iget [inhabited α] (o : option α) : o.get_or_else default = o.iget :=\nby cases o; refl\n\n@[simp] theorem guard_eq_some {p : α → Prop} [decidable_pred p] {a b : α} :\n guard p a = some b ↔ a = b ∧ p a :=\nby by_cases p a; simp [option.guard, h]; intro; contradiction\n\n@[simp] theorem guard_eq_some' {p : Prop} [decidable p] (u) : _root_.guard p = some u ↔ p :=\nbegin\n cases u,\n by_cases p; simp [_root_.guard, h]; refl <|> contradiction,\nend\n\ntheorem lift_or_get_choice {f : α → α → α} (h : ∀ a b, f a b = a ∨ f a b = b) :\n ∀ o₁ o₂, lift_or_get f o₁ o₂ = o₁ ∨ lift_or_get f o₁ o₂ = o₂\n| none none := or.inl rfl\n| (some a) none := or.inl rfl\n| none (some b) := or.inr rfl\n| (some a) (some b) := by simpa [lift_or_get] using h a b\n\n@[simp] lemma lift_or_get_none_left {f} {b : option α} : lift_or_get f none b = b :=\nby cases b; refl\n\n@[simp] lemma lift_or_get_none_right {f} {a : option α} : lift_or_get f a none = a :=\nby cases a; refl\n\n@[simp] lemma lift_or_get_some_some {f} {a b : α} :\n lift_or_get f (some a) (some b) = f a b := rfl\n\n/-- Given an element of `a : option α`, a default element `b : β` and a function `α → β`, apply this\nfunction to `a` if it comes from `α`, and return `b` otherwise. -/\ndef cases_on' : option α → β → (α → β) → β\n| none n s := n\n| (some a) n s := s a\n\n@[simp] lemma cases_on'_none (x : β) (f : α → β) : cases_on' none x f = x := rfl\n\n@[simp] lemma cases_on'_some (x : β) (f : α → β) (a : α) : cases_on' (some a) x f = f a := rfl\n\n@[simp] lemma cases_on'_coe (x : β) (f : α → β) (a : α) : cases_on' (a : option α) x f = f a := rfl\n\n@[simp] lemma cases_on'_none_coe (f : option α → β) (o : option α) :\n cases_on' o (f none) (f ∘ coe) = f o :=\nby cases o; refl\n\n@[simp] lemma get_or_else_map (f : α → β) (x : α) (o : option α) :\n get_or_else (o.map f) (f x) = f (get_or_else o x) :=\nby cases o; refl\n\nlemma orelse_eq_some (o o' : option α) (x : α) :\n (o <|> o') = some x ↔ o = some x ∨ (o = none ∧ o' = some x) :=\nbegin\n cases o,\n { simp only [true_and, false_or, eq_self_iff_true, none_orelse] },\n { simp only [some_orelse, or_false, false_and] }\nend\n\nlemma orelse_eq_some' (o o' : option α) (x : α) :\n o.orelse o' = some x ↔ o = some x ∨ (o = none ∧ o' = some x) :=\noption.orelse_eq_some o o' x\n\n@[simp] lemma orelse_eq_none (o o' : option α) :\n (o <|> o') = none ↔ (o = none ∧ o' = none) :=\nbegin\n cases o,\n { simp only [true_and, none_orelse, eq_self_iff_true] },\n { simp only [some_orelse, false_and], }\nend\n\n@[simp] lemma orelse_eq_none' (o o' : option α) :\n o.orelse o' = none ↔ (o = none ∧ o' = none) :=\noption.orelse_eq_none o o'\n\nsection\nopen_locale classical\n\n/-- An arbitrary `some a` with `a : α` if `α` is nonempty, and otherwise `none`. -/\nnoncomputable def choice (α : Type*) : option α :=\nif h : nonempty α then\n some h.some\nelse\n none\n\nlemma choice_eq {α : Type*} [subsingleton α] (a : α) : choice α = some a :=\nbegin\n dsimp [choice],\n rw dif_pos (⟨a⟩ : nonempty α),\n congr,\nend\n\nlemma choice_eq_none (α : Type*) [is_empty α] : choice α = none :=\ndif_neg (not_nonempty_iff_imp_false.mpr is_empty_elim)\n\nlemma choice_is_some_iff_nonempty {α : Type*} : (choice α).is_some ↔ nonempty α :=\nbegin\n fsplit,\n { intro h, exact ⟨option.get h⟩, },\n { intro h,\n dsimp only [choice],\n rw dif_pos h,\n exact is_some_some },\nend\n\nend\n\n@[simp] lemma to_list_some (a : α) : (a : option α).to_list = [a] :=\nrfl\n\n@[simp] lemma to_list_none (α : Type*) : (none : option α).to_list = [] :=\nrfl\n\n@[simp] lemma elim_none_some (f : option α → β) : option.elim (f none) (f ∘ some) = f :=\nfunext $ λ o, by cases o; refl\n\nend option\n", "meta": {"author": "leanprover-community", "repo": "mathlib", "sha": "5e526d18cea33550268dcbbddcb822d5cde40654", "save_path": "github-repos/lean/leanprover-community-mathlib", "path": "github-repos/lean/leanprover-community-mathlib/mathlib-5e526d18cea33550268dcbbddcb822d5cde40654/src/data/option/basic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43398146480389854, "lm_q2_score": 0.10087862813632467, "lm_q1q2_score": 0.043779454806009956}} {"text": "import tactic\nimport .tokens\nimport .commun\n\nnamespace tactic\nsetup_tactic_parser\n\n@[derive has_reflect]\nmeta inductive Supposons_args\n| regular : list pexpr → Supposons_args\n| absurde : name → option pexpr → Supposons_args\n\nmeta def Supposons_parser : lean.parser Supposons_args :=\nwith_desc \"... / Supposons par l'absurde ...\" $ \ndo { _ ← tk \"par\", _ ← tk \"l'absurde\", \n n ← ident,\n do { _ ← tk \":\", \n hyp ← texpr,\n pure (Supposons_args.absurde n (some hyp)) } <|>\n pure (Supposons_args.absurde n none)} <|>\nSupposons_args.regular <$> ((tk \"que\")? *>parse_binders tac_rbp)\n\nprivate meta def supposons_core (n : name) (ty : pexpr) :=\ndo verifie_nom n,\n t ← target,\n when (not $ t.is_pi) whnf_target,\n t ← target,\n when (not $ t.is_arrow) $\n fail \"Il n'y a rien à supposer ici, le but n'est pas une implication\",\n ty ← i_to_expr ty,\n unify ty t.binding_domain,\n intro_core n >> skip\n\nopen Supposons_args\n\n/-- Introduit une hypothèse quand le but est une implication,\nou bien démarre un raisonnement par l'absurde. -/\n@[interactive]\nmeta def Supposons : parse Supposons_parser → tactic unit\n| (regular le) := do le.mmap' (λ b : pexpr, \n supposons_core b.local_pp_name b.local_type)\n| (absurde n hyp) := do \n by_contradiction n, \n try (interactive.push_neg (loc.ns [n])),\n when hyp.is_some (do \n Hyp ← hyp >>= to_expr,\n let sp := simp_arg_type.symm_expr ``(exists_prop),\n try (interactive.simp_core {} skip tt [sp] [] $ loc.ns [n]),\n ehyp ← get_local n,\n change_core Hyp (some ehyp))\n\nend tactic\n\nexample : ∀ n > 0, true :=\nbegin\n intro n,\n success_if_fail { Supposons H : n < 0 },\n success_if_fail { Supposons n : n > 0 },\n Supposons H : n > 0,\n trivial\nend\n\nexample : ∀ n > 0, true :=\nbegin\n intro n,\n Supposons que H : n > 0,\n trivial\nend\n\nexample : ∀ n > 0, true :=\nbegin\n success_if_fail { Supposons n },\n intro n,\n Supposons H : n > 0,\n trivial\nend\n\nexample (P Q : Prop) (h : ¬ Q → ¬ P) : P → Q :=\nbegin\n Supposons hP,\n Supposons par l'absurde hnQ,\n exact h hnQ hP,\nend\n\nexample (P Q : Prop) (h : ¬ Q → ¬ P) : P → Q :=\nbegin\n Supposons hP,\n Supposons par l'absurde hnQ : ¬ Q,\n exact h hnQ hP,\nend\n\nexample (P Q : Prop) (h : Q → ¬ P) : P → ¬ Q :=\nbegin\n Supposons hP,\n Supposons par l'absurde hnQ : Q,\n exact h hnQ hP,\nend", "meta": {"author": "PatrickMassot", "repo": "MDD154", "sha": "00defe82a4b6b7992ed522a92f62abd685e8c943", "save_path": "github-repos/lean/PatrickMassot-MDD154", "path": "github-repos/lean/PatrickMassot-MDD154/MDD154-00defe82a4b6b7992ed522a92f62abd685e8c943/src/lib/Supposons.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44939264921326705, "lm_q2_score": 0.09670580110615863, "lm_q1q2_score": 0.04345887615338792}} {"text": "/-\nCopyright (c) 2018 Simon Hudon. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Simon Hudon\n\nGeneral utility functions for buffers.\n-/\nimport data.buffer\nimport data.array.lemmas\nimport control.traversable.instances\n\nnamespace buffer\n\nopen function\n\nvariables {α : Type*} {xs : list α}\n\ninstance : inhabited (buffer α) := ⟨nil⟩\n\n@[ext]\nlemma ext : ∀ {b₁ b₂ : buffer α}, to_list b₁ = to_list b₂ → b₁ = b₂\n| ⟨n₁, a₁⟩ ⟨n₂, a₂⟩ h := begin\n simp [to_list, to_array] at h,\n have e : n₁ = n₂ :=\n by rw [←array.to_list_length a₁, ←array.to_list_length a₂, h],\n subst e,\n have h : a₁ == a₂.to_list.to_array := h ▸ a₁.to_list_to_array.symm,\n rw eq_of_heq (h.trans a₂.to_list_to_array)\nend\n\nlemma ext_iff {b₁ b₂ : buffer α} : b₁ = b₂ ↔ to_list b₁ = to_list b₂ :=\n⟨λ h, h ▸ rfl, ext⟩\n\nlemma size_eq_zero_iff {b : buffer α} : b.size = 0 ↔ b = nil :=\nbegin\n rcases b with ⟨_|n, ⟨a⟩⟩,\n { simp only [size, nil, mk_buffer, true_and, true_iff, eq_self_iff_true, heq_iff_eq,\n sigma.mk.inj_iff],\n ext i,\n exact fin.elim0 i },\n { simp [size, nil, mk_buffer, nat.succ_ne_zero] }\nend\n\n@[simp] lemma size_nil : (@nil α).size = 0 :=\nby rw size_eq_zero_iff\n\n@[simp] lemma to_list_nil : to_list (@nil α) = [] := rfl\n\ninstance (α) [decidable_eq α] : decidable_eq (buffer α) :=\nby tactic.mk_dec_eq_instance\n\n@[simp]\nlemma to_list_append_list {b : buffer α} :\n to_list (append_list b xs) = to_list b ++ xs :=\nby induction xs generalizing b; simp! [*]; cases b; simp! [to_list,to_array]\n\n@[simp]\nlemma append_list_mk_buffer :\n append_list mk_buffer xs = array.to_buffer (list.to_array xs) :=\nby ext x : 1; simp [array.to_buffer,to_list,to_list_append_list];\n induction xs; [refl,skip]; simp [to_array]; refl\n\n@[simp] lemma to_buffer_to_list (b : buffer α) : b.to_list.to_buffer = b :=\nbegin\n cases b,\n rw [to_list, to_array, list.to_buffer, append_list_mk_buffer],\n congr,\n { simpa },\n { apply array.to_list_to_array }\nend\n\n@[simp] lemma to_list_to_buffer (l : list α) : l.to_buffer.to_list = l :=\nbegin\n cases l,\n { refl },\n { rw [list.to_buffer, to_list_append_list],\n refl }\nend\n\n@[simp] lemma to_list_to_array (b : buffer α) : b.to_array.to_list = b.to_list :=\nby { cases b, simp [to_list] }\n\n@[simp] lemma append_list_nil (b : buffer α) : b.append_list [] = b := rfl\n\nlemma to_buffer_cons (c : α) (l : list α) :\n (c :: l).to_buffer = [c].to_buffer.append_list l :=\nbegin\n induction l with hd tl hl,\n { simp },\n { apply ext,\n simp [hl] }\nend\n\n@[simp] lemma size_push_back (b : buffer α) (a : α) : (b.push_back a).size = b.size + 1 :=\nby { cases b, simp [size, push_back] }\n\n@[simp] lemma size_append_list (b : buffer α) (l : list α) :\n (b.append_list l).size = b.size + l.length :=\nbegin\n induction l with hd tl hl generalizing b,\n { simp },\n { simp [append_list, hl, add_comm, add_assoc] }\nend\n\n@[simp] lemma size_to_buffer (l : list α) : l.to_buffer.size = l.length :=\nbegin\n induction l with hd tl hl,\n { simpa },\n { rw [to_buffer_cons],\n have : [hd].to_buffer.size = 1 := rfl,\n simp [add_comm, this] }\nend\n\n@[simp] lemma length_to_list (b : buffer α) : b.to_list.length = b.size :=\nby rw [←to_buffer_to_list b, to_list_to_buffer, size_to_buffer]\n\nlemma size_singleton (a : α) : [a].to_buffer.size = 1 := rfl\n\nlemma read_push_back_left (b : buffer α) (a : α) {i : ℕ} (h : i < b.size) :\n (b.push_back a).read ⟨i, by { convert nat.lt_succ_of_lt h, simp }⟩ = b.read ⟨i, h⟩ :=\nby { cases b, convert array.read_push_back_left _, simp }\n\n@[simp] lemma read_push_back_right (b : buffer α) (a : α) :\n (b.push_back a).read ⟨b.size, by simp⟩ = a :=\nby { cases b, convert array.read_push_back_right }\n\nlemma read_append_list_left' (b : buffer α) (l : list α) {i : ℕ}\n (h : i < (b.append_list l).size) (h' : i < b.size) :\n (b.append_list l).read ⟨i, h⟩ = b.read ⟨i, h'⟩ :=\nbegin\n induction l with hd tl hl generalizing b,\n { refl },\n { have hb : i < ((b.push_back hd).append_list tl).size := by convert h using 1,\n have hb' : i < (b.push_back hd).size := by { convert nat.lt_succ_of_lt h', simp },\n have : (append_list b (hd :: tl)).read ⟨i, h⟩ =\n read ((push_back b hd).append_list tl) ⟨i, hb⟩ := rfl,\n simp [this, hl _ hb hb', read_push_back_left _ _ h'] }\nend\n\nlemma read_append_list_left (b : buffer α) (l : list α) {i : ℕ} (h : i < b.size) :\n (b.append_list l).read ⟨i, by simpa using nat.lt_add_right _ _ _ h⟩ = b.read ⟨i, h⟩ :=\nread_append_list_left' b l _ h\n\n@[simp] lemma read_append_list_right (b : buffer α) (l : list α) {i : ℕ} (h : i < l.length) :\n (b.append_list l).read ⟨b.size + i, by simp [h]⟩ = l.nth_le i h :=\nbegin\n induction l with hd tl hl generalizing b i,\n { exact absurd i.zero_le (not_le_of_lt h) },\n { convert_to ((b.push_back hd).append_list tl).read _ = _,\n cases i,\n { convert read_append_list_left _ _ _;\n simp },\n { rw [list.length, nat.succ_lt_succ_iff] at h,\n have : b.size + i.succ = (b.push_back hd).size + i,\n { simp [add_comm, add_left_comm, nat.succ_eq_add_one] },\n convert hl (b.push_back hd) h using 1,\n simpa [nat.add_succ, nat.succ_add] } }\nend\n\nlemma read_to_buffer' (l : list α) {i : ℕ} (h : i < l.to_buffer.size) (h' : i < l.length) :\n l.to_buffer.read ⟨i, h⟩ = l.nth_le i h' :=\nbegin\n cases l with hd tl,\n { simpa using h' },\n { have hi : i < ([hd].to_buffer.append_list tl).size := by simpa [add_comm] using h,\n convert_to ([hd].to_buffer.append_list tl).read ⟨i, hi⟩ = _,\n cases i,\n { convert read_append_list_left _ _ _,\n simp },\n { rw list.nth_le,\n convert read_append_list_right _ _ _,\n simp [nat.succ_eq_add_one, add_comm] } }\nend\n\n@[simp] lemma read_to_buffer (l : list α) (i) :\n l.to_buffer.read i = l.nth_le i (by { convert i.property, simp }) :=\nby { convert read_to_buffer' _ _ _, { simp }, { simpa using i.property } }\n\nlemma nth_le_to_list' (b : buffer α) {i : ℕ} (h h') :\n b.to_list.nth_le i h = b.read ⟨i, h'⟩ :=\nbegin\n have : b.to_list.to_buffer.read ⟨i, (by simpa using h')⟩ = b.read ⟨i, h'⟩,\n { congr' 1; simp [fin.heq_ext_iff] },\n simp [←this]\nend\n\nlemma nth_le_to_list (b : buffer α) {i : ℕ} (h) :\n b.to_list.nth_le i h = b.read ⟨i, by simpa using h⟩ :=\nnth_le_to_list' _ _ _\n\nlemma read_eq_nth_le_to_list (b : buffer α) (i) :\n b.read i = b.to_list.nth_le i (by simpa using i.is_lt) :=\nby simp [nth_le_to_list]\n\nlemma read_singleton (c : α) : [c].to_buffer.read ⟨0, by simp⟩ = c :=\nby simp\n\n/-- The natural equivalence between lists and buffers, using\n`list.to_buffer` and `buffer.to_list`. -/\ndef list_equiv_buffer (α : Type*) : list α ≃ buffer α :=\nbegin\n refine { to_fun := list.to_buffer, inv_fun := buffer.to_list, .. };\n simp [left_inverse,function.right_inverse]\nend\n\ninstance : traversable buffer :=\nequiv.traversable list_equiv_buffer\n\ninstance : is_lawful_traversable buffer :=\nequiv.is_lawful_traversable list_equiv_buffer\n\n/--\nA convenience wrapper around `read` that just fails if the index is out of bounds.\n-/\nmeta def read_t (b : buffer α) (i : ℕ) : tactic α :=\nif h : i < b.size then return $ b.read (fin.mk i h)\nelse tactic.fail \"invalid buffer access\"\n\nend buffer\n", "meta": {"author": "JLimperg", "repo": "aesop3", "sha": "a4a116f650cc7403428e72bd2e2c4cda300fe03f", "save_path": "github-repos/lean/JLimperg-aesop3", "path": "github-repos/lean/JLimperg-aesop3/aesop3-a4a116f650cc7403428e72bd2e2c4cda300fe03f/src/data/buffer/basic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46101677931231594, "lm_q2_score": 0.09401018278948647, "lm_q1q2_score": 0.04334027169217117}} {"text": "/-\nCopyright (c) 2020 Simon Hudon. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Simon Hudon\n-/\nimport control.monad.basic\nimport control.monad.cont\nimport control.monad.writer\nimport data.equiv.basic\nimport tactic.interactive\n\n/-!\n# Universe lifting for type families\n\nSome functors such as `option` and `list` are universe polymorphic. Unlike\ntype polymorphism where `option α` is a function application and reasoning and\ngeneralizations that apply to functions can be used, `option.{u}` and `option.{v}`\nare not one function applied to two universe names but one polymorphic definition\ninstantiated twice. This means that whatever works on `option.{u}` is hard\nto transport over to `option.{v}`. `uliftable` is an attempt at improving the situation.\n\n`uliftable option.{u} option.{v}` gives us a generic and composable way to use\n`option.{u}` in a context that requires `option.{v}`. It is often used in tandem with\n`ulift` but the two are purposefully decoupled.\n\n\n## Main definitions\n * `uliftable` class\n\n## Tags\n\nuniverse polymorphism functor\n\n-/\n\nuniverses u₀ u₁ v₀ v₁ v₂ w w₀ w₁\nvariables {s : Type u₀} {s' : Type u₁} {r r' w w' : Type*}\n\n/-- Given a universe polymorphic type family `M.{u} : Type u₁ → Type\nu₂`, this class convert between instantiations, from\n`M.{u} : Type u₁ → Type u₂` to `M.{v} : Type v₁ → Type v₂` and back -/\nclass uliftable (f : Type u₀ → Type u₁) (g : Type v₀ → Type v₁) :=\n(congr [] {α β} : α ≃ β → f α ≃ g β)\n\nnamespace uliftable\n\n/-- The most common practical use `uliftable` (together with `up`), this function takes\n`x : M.{u} α` and lifts it to M.{max u v} (ulift.{v} α) -/\n@[reducible]\ndef up {f : Type u₀ → Type u₁} {g : Type (max u₀ v₀) → Type v₁} [uliftable f g]\n {α} : f α → g (ulift α) :=\n(uliftable.congr f g equiv.ulift.symm).to_fun\n\n/-- The most common practical use of `uliftable` (together with `up`), this function takes\n`x : M.{max u v} (ulift.{v} α)` and lowers it to `M.{u} α` -/\n@[reducible]\ndef down {f : Type u₀ → Type u₁} {g : Type (max u₀ v₀) → Type v₁} [uliftable f g]\n {α} : g (ulift α) → f α :=\n(uliftable.congr f g equiv.ulift.symm).inv_fun\n\n/-- convenient shortcut to avoid manipulating `ulift` -/\ndef adapt_up (F : Type v₀ → Type v₁) (G : Type (max v₀ u₀) → Type u₁)\n [uliftable F G] [monad G] {α β}\n (x : F α) (f : α → G β) : G β :=\nup x >>= f ∘ ulift.down\n\n/-- convenient shortcut to avoid manipulating `ulift` -/\ndef adapt_down {F : Type (max u₀ v₀) → Type u₁} {G : Type v₀ → Type v₁}\n [L : uliftable G F] [monad F] {α β}\n (x : F α) (f : α → G β) : G β :=\n@down.{v₀ v₁ (max u₀ v₀)} G F L β $ x >>= @up.{v₀ v₁ (max u₀ v₀)} G F L β ∘ f\n\n/-- map function that moves up universes -/\ndef up_map {F : Type u₀ → Type u₁} {G : Type.{max u₀ v₀} → Type v₁} [inst : uliftable F G]\n [functor G] {α β} (f : α → β) (x : F α) : G β :=\nfunctor.map (f ∘ ulift.down) (up x)\n\n/-- map function that moves down universes -/\ndef down_map {F : Type.{max u₀ v₀} → Type u₁} {G : Type u₀ → Type v₁} [inst : uliftable G F]\n [functor F] {α β} (f : α → β) (x : F α) : G β :=\ndown (functor.map (ulift.up ∘ f) x : F (ulift β))\n\n@[simp]\nlemma up_down {f : Type u₀ → Type u₁} {g : Type (max u₀ v₀) → Type v₁} [uliftable f g]\n {α} (x : g (ulift α)) : up (down x : f α) = x :=\n(uliftable.congr f g equiv.ulift.symm).right_inv _\n\n@[simp]\nlemma down_up {f : Type u₀ → Type u₁} {g : Type (max u₀ v₀) → Type v₁} [uliftable f g]\n {α} (x : f α) : down (up x : g _) = x :=\n(uliftable.congr f g equiv.ulift.symm).left_inv _\n\nend uliftable\n\nopen ulift\n\ninstance : uliftable id id :=\n{ congr := λ α β F, F }\n\n/-- for specific state types, this function helps to create a uliftable instance -/\ndef state_t.uliftable' {m : Type u₀ → Type v₀} {m' : Type u₁ → Type v₁}\n [uliftable m m']\n (F : s ≃ s') :\n uliftable (state_t s m) (state_t s' m') :=\n{ congr :=\n λ α β G, state_t.equiv $ equiv.Pi_congr F $\n λ _, uliftable.congr _ _ $ equiv.prod_congr G F }\n\ninstance {m m'} [uliftable m m'] :\n uliftable (state_t s m) (state_t (ulift s) m') :=\nstate_t.uliftable' equiv.ulift.symm\n\n/-- for specific reader monads, this function helps to create a uliftable instance -/\ndef reader_t.uliftable' {m m'} [uliftable m m']\n (F : s ≃ s') :\n uliftable (reader_t s m) (reader_t s' m') :=\n{ congr :=\n λ α β G, reader_t.equiv $ equiv.Pi_congr F $\n λ _, uliftable.congr _ _ G }\n\ninstance {m m'} [uliftable m m'] : uliftable (reader_t s m) (reader_t (ulift s) m') :=\nreader_t.uliftable' equiv.ulift.symm\n\n/-- for specific continuation passing monads, this function helps to create a uliftable instance -/\ndef cont_t.uliftable' {m m'} [uliftable m m']\n (F : r ≃ r') :\n uliftable (cont_t r m) (cont_t r' m') :=\n{ congr :=\n λ α β, cont_t.equiv (uliftable.congr _ _ F) }\n\ninstance {s m m'} [uliftable m m'] : uliftable (cont_t s m) (cont_t (ulift s) m') :=\ncont_t.uliftable' equiv.ulift.symm\n\n/-- for specific writer monads, this function helps to create a uliftable instance -/\ndef writer_t.uliftable' {m m'} [uliftable m m']\n (F : w ≃ w') :\n uliftable (writer_t w m) (writer_t w' m') :=\n{ congr :=\n λ α β G, writer_t.equiv $ uliftable.congr _ _ $ equiv.prod_congr G F }\n\ninstance {m m'} [uliftable m m'] : uliftable (writer_t s m) (writer_t (ulift s) m') :=\nwriter_t.uliftable' equiv.ulift.symm\n", "meta": {"author": "jjaassoonn", "repo": "projective_space", "sha": "11fe19fe9d7991a272e7a40be4b6ad9b0c10c7ce", "save_path": "github-repos/lean/jjaassoonn-projective_space", "path": "github-repos/lean/jjaassoonn-projective_space/projective_space-11fe19fe9d7991a272e7a40be4b6ad9b0c10c7ce/src/control/uliftable.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4804786780479071, "lm_q2_score": 0.09009299274041059, "lm_q1q2_score": 0.04328776205329217}} {"text": "/-\nCopyright (c) 2022 Yaël Dillies. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Yaël Dillies\n\n! This file was ported from Lean 3 source module logic.lemmas\n! leanprover-community/mathlib commit 448144f7ae193a8990cb7473c9e9a01990f64ac7\n! Please do not edit these lines, except to modify the commit id\n! if you have ported upstream changes.\n-/\nimport Mathbin.Tactic.Congr\nimport Mathbin.Tactic.Protected\nimport Mathbin.Tactic.Rcases\nimport Mathbin.Tactic.SplitIfs\nimport Mathbin.Logic.Basic\n\n/-!\n# More basic logic properties\n\n> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.\n> Any changes to this file require a corresponding PR to mathlib4.\n\nA few more logic lemmas. These are in their own file, rather than `logic.basic`, because it is\nconvenient to be able to use the `split_ifs` tactic.\n\n## Implementation notes\n\nWe spell those lemmas out with `dite` and `ite` rather than the `if then else` notation because this\nwould result in less delta-reduced statements.\n-/\n\n\nalias heq_iff_eq ↔ HEq.eq Eq.heq\n#align heq.eq HEq.eq\n#align eq.heq Eq.heq\n\nattribute [protected] HEq.eq Eq.heq\n\nalias ne_of_eq_of_ne ← Eq.trans_ne\n#align eq.trans_ne Eq.trans_ne\n\nalias ne_of_ne_of_eq ← Ne.trans_eq\n#align ne.trans_eq Ne.trans_eq\n\nvariable {α : Sort _} {p q r : Prop} [Decidable p] [Decidable q] {a b c : α}\n\n#print dite_dite_distrib_left /-\ntheorem dite_dite_distrib_left {a : p → α} {b : ¬p → q → α} {c : ¬p → ¬q → α} :\n (dite p a fun hp => dite q (b hp) (c hp)) =\n dite q (fun hq => dite p a fun hp => b hp hq) fun hq => dite p a fun hp => c hp hq :=\n by split_ifs <;> rfl\n#align dite_dite_distrib_left dite_dite_distrib_left\n-/\n\n#print dite_dite_distrib_right /-\ntheorem dite_dite_distrib_right {a : p → q → α} {b : p → ¬q → α} {c : ¬p → α} :\n dite p (fun hp => dite q (a hp) (b hp)) c =\n dite q (fun hq => dite p (fun hp => a hp hq) c) fun hq => dite p (fun hp => b hp hq) c :=\n by split_ifs <;> rfl\n#align dite_dite_distrib_right dite_dite_distrib_right\n-/\n\n#print ite_dite_distrib_left /-\ntheorem ite_dite_distrib_left {a : α} {b : q → α} {c : ¬q → α} :\n ite p a (dite q b c) = dite q (fun hq => ite p a <| b hq) fun hq => ite p a <| c hq :=\n dite_dite_distrib_left\n#align ite_dite_distrib_left ite_dite_distrib_left\n-/\n\n#print ite_dite_distrib_right /-\ntheorem ite_dite_distrib_right {a : q → α} {b : ¬q → α} {c : α} :\n ite p (dite q a b) c = dite q (fun hq => ite p (a hq) c) fun hq => ite p (b hq) c :=\n dite_dite_distrib_right\n#align ite_dite_distrib_right ite_dite_distrib_right\n-/\n\n#print dite_ite_distrib_left /-\ntheorem dite_ite_distrib_left {a : p → α} {b : ¬p → α} {c : ¬p → α} :\n (dite p a fun hp => ite q (b hp) (c hp)) = ite q (dite p a b) (dite p a c) :=\n dite_dite_distrib_left\n#align dite_ite_distrib_left dite_ite_distrib_left\n-/\n\n#print dite_ite_distrib_right /-\ntheorem dite_ite_distrib_right {a : p → α} {b : p → α} {c : ¬p → α} :\n dite p (fun hp => ite q (a hp) (b hp)) c = ite q (dite p a c) (dite p b c) :=\n dite_dite_distrib_right\n#align dite_ite_distrib_right dite_ite_distrib_right\n-/\n\n#print ite_ite_distrib_left /-\ntheorem ite_ite_distrib_left : ite p a (ite q b c) = ite q (ite p a b) (ite p a c) :=\n dite_dite_distrib_left\n#align ite_ite_distrib_left ite_ite_distrib_left\n-/\n\n#print ite_ite_distrib_right /-\ntheorem ite_ite_distrib_right : ite p (ite q a b) c = ite q (ite p a c) (ite p b c) :=\n dite_dite_distrib_right\n#align ite_ite_distrib_right ite_ite_distrib_right\n-/\n\n#print Prop.forall /-\ntheorem Prop.forall {f : Prop → Prop} : (∀ p, f p) ↔ f True ∧ f False :=\n ⟨fun h => ⟨h _, h _⟩, by\n rintro ⟨h₁, h₀⟩ p\n by_cases hp : p <;> simp only [hp] <;> assumption⟩\n#align Prop.forall Prop.forall\n-/\n\n#print Prop.exists /-\ntheorem Prop.exists {f : Prop → Prop} : (∃ p, f p) ↔ f True ∨ f False :=\n ⟨fun ⟨p, h⟩ => by refine' (em p).imp _ _ <;> intro H <;> convert h <;> simp [H], by\n rintro (h | h) <;> exact ⟨_, h⟩⟩\n#align Prop.exists Prop.exists\n-/\n\n", "meta": {"author": "leanprover-community", "repo": "mathlib3port", "sha": "62505aa236c58c8559783b16d33e30df3daa54f4", "save_path": "github-repos/lean/leanprover-community-mathlib3port", "path": "github-repos/lean/leanprover-community-mathlib3port/mathlib3port-62505aa236c58c8559783b16d33e30df3daa54f4/Mathbin/Logic/Lemmas.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48047866316946014, "lm_q2_score": 0.09009298663270453, "lm_q1q2_score": 0.04328775777822591}} {"text": "/-\nCopyright (c) 2019 Reid Barton. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Reid Barton, Johan Commelin\n-/\n\nimport category_theory.limits.preserves\nimport category_theory.whiskering\nimport category_theory.equivalence\n\nnamespace category_theory\nopen category\nopen category_theory.limits\n\nuniverses v₁ v₂ v₃ u₁ u₂ u₃ -- declare the `v`'s first; see `category_theory.category` for an explanation\n\nlocal attribute [elab_simple] whisker_left whisker_right\n\nvariables {C : Type u₁} [𝒞 : category.{v₁} C] {D : Type u₂} [𝒟 : category.{v₂} D]\ninclude 𝒞 𝒟\n\n/--\n`adjunction F G` represents the data of an adjunction between two functors\n`F : C ⥤ D` and `G : D ⥤ C`. `F` is the left adjoint and `G` is the right adjoint.\n-/\nstructure adjunction (F : C ⥤ D) (G : D ⥤ C) :=\n(hom_equiv : Π (X Y), (F.obj X ⟶ Y) ≃ (X ⟶ G.obj Y))\n(unit : functor.id C ⟶ F.comp G)\n(counit : G.comp F ⟶ functor.id D)\n(hom_equiv_unit' : Π {X Y f}, (hom_equiv X Y) f = (unit : _ ⟹ _).app X ≫ G.map f . obviously)\n(hom_equiv_counit' : Π {X Y g}, (hom_equiv X Y).symm g = F.map g ≫ counit.app Y . obviously)\n\nnamespace adjunction\n\nrestate_axiom hom_equiv_unit'\nrestate_axiom hom_equiv_counit'\nattribute [simp, priority 1] hom_equiv_unit hom_equiv_counit\n\nsection\n\nvariables {F : C ⥤ D} {G : D ⥤ C} (adj : adjunction F G) {X' X : C} {Y Y' : D}\n\n@[simp, priority 1] lemma hom_equiv_naturality_left_symm (f : X' ⟶ X) (g : X ⟶ G.obj Y) :\n (adj.hom_equiv X' Y).symm (f ≫ g) = F.map f ≫ (adj.hom_equiv X Y).symm g :=\nby rw [hom_equiv_counit, F.map_comp, assoc, adj.hom_equiv_counit.symm]\n\n@[simp] lemma hom_equiv_naturality_left (f : X' ⟶ X) (g : F.obj X ⟶ Y) :\n (adj.hom_equiv X' Y) (F.map f ≫ g) = f ≫ (adj.hom_equiv X Y) g :=\nby rw [← equiv.eq_symm_apply]; simp [-hom_equiv_unit]\n\n@[simp, priority 1] lemma hom_equiv_naturality_right (f : F.obj X ⟶ Y) (g : Y ⟶ Y') :\n (adj.hom_equiv X Y') (f ≫ g) = (adj.hom_equiv X Y) f ≫ G.map g :=\nby rw [hom_equiv_unit, G.map_comp, ← assoc, ←hom_equiv_unit]\n\n@[simp] lemma hom_equiv_naturality_right_symm (f : X ⟶ G.obj Y) (g : Y ⟶ Y') :\n (adj.hom_equiv X Y').symm (f ≫ G.map g) = (adj.hom_equiv X Y).symm f ≫ g :=\nby rw [equiv.symm_apply_eq]; simp [-hom_equiv_counit]\n\n@[simp] lemma left_triangle :\n (whisker_right adj.unit F).vcomp (whisker_left F adj.counit) = nat_trans.id _ :=\nbegin\n ext1 X, dsimp,\n erw [← adj.hom_equiv_counit, equiv.symm_apply_eq, adj.hom_equiv_unit],\n simp\nend\n\n@[simp] lemma right_triangle :\n (whisker_left G adj.unit).vcomp (whisker_right adj.counit G) = nat_trans.id _ :=\nbegin\n ext1 Y, dsimp,\n erw [← adj.hom_equiv_unit, ← equiv.eq_symm_apply, adj.hom_equiv_counit],\n simp\nend\n\n@[simp] lemma left_triangle_components :\n F.map (adj.unit.app X) ≫ adj.counit.app (F.obj X) = 𝟙 _ :=\ncongr_arg (λ (t : _ ⟹ functor.id C ⋙ F), t.app X) adj.left_triangle\n\n@[simp] lemma right_triangle_components {Y : D} :\n adj.unit.app (G.obj Y) ≫ G.map (adj.counit.app Y) = 𝟙 _ :=\ncongr_arg (λ (t : _ ⟹ G ⋙ functor.id C), t.app Y) adj.right_triangle\n\nend\n\nstructure core_hom_equiv (F : C ⥤ D) (G : D ⥤ C) :=\n(hom_equiv : Π (X Y), (F.obj X ⟶ Y) ≃ (X ⟶ G.obj Y))\n(hom_equiv_naturality_left_symm' : Π {X' X Y} (f : X' ⟶ X) (g : X ⟶ G.obj Y),\n (hom_equiv X' Y).symm (f ≫ g) = F.map f ≫ (hom_equiv X Y).symm g . obviously)\n(hom_equiv_naturality_right' : Π {X Y Y'} (f : F.obj X ⟶ Y) (g : Y ⟶ Y'),\n (hom_equiv X Y') (f ≫ g) = (hom_equiv X Y) f ≫ G.map g . obviously)\n\nnamespace core_hom_equiv\n\nrestate_axiom hom_equiv_naturality_left_symm'\nrestate_axiom hom_equiv_naturality_right'\nattribute [simp, priority 1] hom_equiv_naturality_left_symm hom_equiv_naturality_right\n\nvariables {F : C ⥤ D} {G : D ⥤ C} (adj : core_hom_equiv F G) {X' X : C} {Y Y' : D}\n\n@[simp] lemma hom_equiv_naturality_left (f : X' ⟶ X) (g : F.obj X ⟶ Y) :\n (adj.hom_equiv X' Y) (F.map f ≫ g) = f ≫ (adj.hom_equiv X Y) g :=\nby rw [← equiv.eq_symm_apply]; simp\n\n@[simp] lemma hom_equiv_naturality_right_symm (f : X ⟶ G.obj Y) (g : Y ⟶ Y') :\n (adj.hom_equiv X Y').symm (f ≫ G.map g) = (adj.hom_equiv X Y).symm f ≫ g :=\nby rw [equiv.symm_apply_eq]; simp\n\nend core_hom_equiv\n\nstructure core_unit_counit (F : C ⥤ D) (G : D ⥤ C) :=\n(unit : functor.id C ⟶ F.comp G)\n(counit : G.comp F ⟶ functor.id D)\n(left_triangle' : (whisker_right unit F).vcomp (whisker_left F counit) = nat_trans.id _ . obviously)\n(right_triangle' : (whisker_left G unit).vcomp (whisker_right counit G) = nat_trans.id _ . obviously)\n\nnamespace core_unit_counit\n\nrestate_axiom left_triangle'\nrestate_axiom right_triangle'\nattribute [simp] left_triangle right_triangle\n\nend core_unit_counit\n\nvariables (F : C ⥤ D) (G : D ⥤ C)\n\ndef mk_of_hom_equiv (adj : core_hom_equiv F G) : adjunction F G :=\n{ unit :=\n { app := λ X, (adj.hom_equiv X (F.obj X)) (𝟙 (F.obj X)),\n naturality' :=\n begin\n intros,\n erw [← adj.hom_equiv_naturality_left, ← adj.hom_equiv_naturality_right],\n dsimp, simp\n end },\n counit :=\n { app := λ Y, (adj.hom_equiv _ _).inv_fun (𝟙 (G.obj Y)),\n naturality' :=\n begin\n intros,\n erw [← adj.hom_equiv_naturality_left_symm, ← adj.hom_equiv_naturality_right_symm],\n dsimp, simp\n end },\n hom_equiv_unit' := λ X Y f, by erw [← adj.hom_equiv_naturality_right]; simp,\n hom_equiv_counit' := λ X Y f, by erw [← adj.hom_equiv_naturality_left_symm]; simp,\n .. adj }\n\ndef mk_of_unit_counit (adj : core_unit_counit F G) : adjunction F G :=\n{ hom_equiv := λ X Y,\n { to_fun := λ f, adj.unit.app X ≫ G.map f,\n inv_fun := λ g, F.map g ≫ adj.counit.app Y,\n left_inv := λ f, begin\n change F.map (_ ≫ _) ≫ _ = _,\n rw [F.map_comp, assoc, ←functor.comp_map, adj.counit.naturality, ←assoc],\n convert id_comp _ f,\n exact congr_arg (λ t : _ ⟹ _, t.app _) adj.left_triangle\n end,\n right_inv := λ g, begin\n change _ ≫ G.map (_ ≫ _) = _,\n rw [G.map_comp, ←assoc, ←functor.comp_map, ←adj.unit.naturality, assoc],\n convert comp_id _ g,\n exact congr_arg (λ t : _ ⟹ _, t.app _) adj.right_triangle\n end },\n .. adj }\n\nsection\nomit 𝒟\n\ndef id : adjunction (functor.id C) (functor.id C) :=\n{ hom_equiv := λ X Y, equiv.refl _,\n unit := 𝟙 _,\n counit := 𝟙 _ }\n\nend\n\n/-\nTODO\n* define adjoint equivalences\n* show that every equivalence can be improved into an adjoint equivalence\n-/\n\nsection\nvariables {E : Type u₃} [ℰ : category.{v₃} E] (H : D ⥤ E) (I : E ⥤ D)\n\ndef comp (adj₁ : adjunction F G) (adj₂ : adjunction H I) : adjunction (F ⋙ H) (I ⋙ G) :=\n{ hom_equiv := λ X Z, equiv.trans (adj₂.hom_equiv _ _) (adj₁.hom_equiv _ _),\n unit := adj₁.unit ≫\n (whisker_left F $ whisker_right adj₂.unit G) ≫ (functor.associator _ _ _).inv,\n counit := (functor.associator _ _ _).hom ≫\n (whisker_left I $ whisker_right adj₁.counit H) ≫ adj₂.counit }\n\nend\n\nstructure is_left_adjoint (left : C ⥤ D) :=\n(right : D ⥤ C)\n(adj : adjunction left right)\n\nstructure is_right_adjoint (right : D ⥤ C) :=\n(left : C ⥤ D)\n(adj : adjunction left right)\n\nsection construct_left\n-- Construction of a left adjoint. In order to construct a left\n-- adjoint to a functor G : D → C, it suffices to give the object part\n-- of a functor F : C → D together with isomorphisms Hom(FX, Y) ≃\n-- Hom(X, GY) natural in Y. The action of F on morphisms can be\n-- constructed from this data.\nvariables {F_obj : C → D} {G}\nvariables (e : Π X Y, (F_obj X ⟶ Y) ≃ (X ⟶ G.obj Y))\nvariables (he : Π X Y Y' g h, e X Y' (h ≫ g) = e X Y h ≫ G.map g)\ninclude he\n\nprivate lemma he' {X Y Y'} (f g) : (e X Y').symm (f ≫ G.map g) = (e X Y).symm f ≫ g :=\nby intros; rw [equiv.symm_apply_eq, he]; simp\n\ndef left_adjoint_of_equiv : C ⥤ D :=\n{ obj := F_obj,\n map := λ X X' f, (e X (F_obj X')).symm (f ≫ e X' (F_obj X') (𝟙 _)),\n map_comp' := λ X X' X'' f f', begin\n rw [equiv.symm_apply_eq, he, equiv.apply_symm_apply],\n conv { to_rhs, rw [assoc, ←he, id_comp, equiv.apply_symm_apply] },\n simp\n end }\n\ndef adjunction_of_equiv_left : adjunction (left_adjoint_of_equiv e he) G :=\nmk_of_hom_equiv (left_adjoint_of_equiv e he) G\n{ hom_equiv := e,\n hom_equiv_naturality_left_symm' :=\n begin\n intros,\n erw [← he' e he, ← equiv.apply_eq_iff_eq],\n simp [(he _ _ _ _ _).symm]\n end }\n\nend construct_left\n\nsection construct_right\n-- Construction of a right adjoint, analogous to the above.\nvariables {F} {G_obj : D → C}\nvariables (e : Π X Y, (F.obj X ⟶ Y) ≃ (X ⟶ G_obj Y))\nvariables (he : Π X' X Y f g, e X' Y (F.map f ≫ g) = f ≫ e X Y g)\ninclude he\n\nprivate lemma he' {X' X Y} (f g) : F.map f ≫ (e X Y).symm g = (e X' Y).symm (f ≫ g) :=\nby intros; rw [equiv.eq_symm_apply, he]; simp\n\ndef right_adjoint_of_equiv : D ⥤ C :=\n{ obj := G_obj,\n map := λ Y Y' g, (e (G_obj Y) Y') ((e (G_obj Y) Y).symm (𝟙 _) ≫ g),\n map_comp' := λ Y Y' Y'' g g', begin\n rw [← equiv.eq_symm_apply, ← he' e he, equiv.symm_apply_apply],\n conv { to_rhs, rw [← assoc, he' e he, comp_id, equiv.symm_apply_apply] },\n simp\n end }\n\ndef adjunction_of_equiv_right : adjunction F (right_adjoint_of_equiv e he) :=\nmk_of_hom_equiv F (right_adjoint_of_equiv e he)\n{ hom_equiv := e,\n hom_equiv_naturality_left_symm' := by intros; rw [equiv.symm_apply_eq, he]; simp,\n hom_equiv_naturality_right' :=\n begin\n intros X Y Y' g h,\n erw [←he, equiv.apply_eq_iff_eq, ←assoc, he' e he, comp_id, equiv.symm_apply_apply]\n end }\n\nend construct_right\n\nend adjunction\n\nend category_theory\n\nnamespace category_theory.adjunction\nopen category_theory\nopen category_theory.functor\nopen category_theory.limits\n\nuniverses u₁ u₂ v\n\nvariables {C : Type u₁} [𝒞 : category.{v} C] {D : Type u₂} [𝒟 : category.{v} D]\ninclude 𝒞 𝒟\n\nvariables {F : C ⥤ D} {G : D ⥤ C} (adj : adjunction F G)\ninclude adj\n\nsection preservation_colimits\nvariables {J : Type v} [small_category J] (K : J ⥤ C)\n\ndef functoriality_is_left_adjoint :\n is_left_adjoint (@cocones.functoriality _ _ _ _ K _ _ F) :=\n{ right := (cocones.functoriality G) ⋙ (cocones.precompose\n (K.right_unitor.inv ≫ (whisker_left K adj.unit) ≫ (associator _ _ _).inv)),\n adj := mk_of_unit_counit _ _\n { unit :=\n { app := λ c,\n { hom := adj.unit.app c.X,\n w' := λ j, by have := adj.unit.naturality (c.ι.app j); tidy },\n naturality' := λ _ _ f, by have := adj.unit.naturality (f.hom); tidy },\n counit :=\n { app := λ c,\n { hom := adj.counit.app c.X,\n w' :=\n begin\n intro j,\n dsimp,\n erw [category.comp_id, category.id_comp, F.map_comp, category.assoc,\n adj.counit.naturality (c.ι.app j), ← category.assoc,\n adj.left_triangle_components, category.id_comp],\n refl,\n end },\n naturality' := λ _ _ f, by have := adj.counit.naturality (f.hom); tidy } } }\n\n/-- A left adjoint preserves colimits. -/\ndef left_adjoint_preserves_colimits : preserves_colimits F :=\nλ J 𝒥 K, by resetI; exact\n{ preserves := λ c hc, is_colimit_iso_unique_cocone_morphism.inv\n (λ s, (((adj.functoriality_is_left_adjoint _).adj).hom_equiv _ _).unique_of_equiv $\n is_colimit_iso_unique_cocone_morphism.hom hc _ ) }\n\nend preservation_colimits\n\nsection preservation_limits\nvariables {J : Type v} [small_category J] (K : J ⥤ D)\n\ndef functoriality_is_right_adjoint :\n is_right_adjoint (@cones.functoriality _ _ _ _ K _ _ G) :=\n{ left := (cones.functoriality F) ⋙ (cones.postcompose\n ((associator _ _ _).hom ≫ (whisker_left K adj.counit) ≫ K.right_unitor.hom)),\n adj := mk_of_unit_counit _ _\n { unit :=\n { app := λ c,\n { hom := adj.unit.app c.X,\n w' :=\n begin\n intro j,\n dsimp,\n erw [category.comp_id, category.id_comp, G.map_comp, ← category.assoc,\n ← adj.unit.naturality (c.π.app j), category.assoc,\n adj.right_triangle_components, category.comp_id],\n refl,\n end },\n naturality' := λ _ _ f, by have := adj.unit.naturality (f.hom); tidy },\n counit :=\n { app := λ c,\n { hom := adj.counit.app c.X,\n w' := λ j, by have := adj.counit.naturality (c.π.app j); tidy },\n naturality' := λ _ _ f, by have := adj.counit.naturality (f.hom); tidy } } }\n\n/-- A right adjoint preserves limits. -/\ndef right_adjoint_preserves_limits : preserves_limits G :=\nλ J 𝒥 K, by resetI; exact\n{ preserves := λ c hc, is_limit_iso_unique_cone_morphism.inv\n (λ s, (((adj.functoriality_is_right_adjoint _).adj).hom_equiv _ _).symm.unique_of_equiv $\n is_limit_iso_unique_cone_morphism.hom hc _) }\n\nend preservation_limits\n\n-- Note: this is natural in K, but we do not yet have the tools to formulate that.\ndef cocones_iso {J : Type v} [small_category J] {K : J ⥤ C} :\n (cocones J D).obj (op (K ⋙ F)) ≅ G ⋙ ((cocones J C).obj (op K)) :=\nnat_iso.of_components (λ Y,\n{ hom := λ t,\n { app := λ j, (adj.hom_equiv (K.obj j) Y) (t.app j),\n naturality' := λ j j' f, by erw [← adj.hom_equiv_naturality_left, t.naturality]; dsimp; simp },\n inv := λ t,\n { app := λ j, (adj.hom_equiv (K.obj j) Y).symm (t.app j),\n naturality' := λ j j' f, begin\n erw [← adj.hom_equiv_naturality_left_symm, ← adj.hom_equiv_naturality_right_symm, t.naturality],\n dsimp, simp\n end } } )\nbegin\n intros Y₁ Y₂ f,\n ext1 t,\n ext1 j,\n apply adj.hom_equiv_naturality_right\nend\n\n-- Note: this is natural in K, but we do not yet have the tools to formulate that.\ndef cones_iso {J : Type v} [small_category J] {K : J ⥤ D} :\n F.op ⋙ ((cones J D).obj K) ≅ (cones J C).obj (K ⋙ G) :=\nnat_iso.of_components (λ X,\n{ hom := λ t,\n { app := λ j, (adj.hom_equiv (unop X) (K.obj j)) (t.app j),\n naturality' := λ j j' f, begin\n erw [← adj.hom_equiv_naturality_right, ← t.naturality, category.id_comp, category.id_comp],\n refl\n end },\n inv := λ t,\n { app := λ j, (adj.hom_equiv (unop X) (K.obj j)).symm (t.app j),\n naturality' := λ j j' f, begin\n erw [← adj.hom_equiv_naturality_right_symm, ← t.naturality, category.id_comp, category.id_comp]\n end } } )\n(by tidy)\n\nend category_theory.adjunction\n", "meta": {"author": "digama0", "repo": "mathlib-ITP2019", "sha": "5cbd0362e04e671ef5db1284870592af6950197c", "save_path": "github-repos/lean/digama0-mathlib-ITP2019", "path": "github-repos/lean/digama0-mathlib-ITP2019/mathlib-ITP2019-5cbd0362e04e671ef5db1284870592af6950197c/src/category_theory/adjunction.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.08632347717391049, "lm_q1q2_score": 0.04282454436445077}} {"text": "/-\nCopyright (c) 2017 Mario Carneiro. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Mario Carneiro\n\n! This file was ported from Lean 3 source module data.option.basic\n! leanprover-community/mathlib commit 448144f7ae193a8990cb7473c9e9a01990f64ac7\n! Please do not edit these lines, except to modify the commit id\n! if you have ported upstream changes.\n-/\nimport Mathbin.Logic.IsEmpty\nimport Mathbin.Control.Traversable.Basic\nimport Mathbin.Tactic.Basic\n\n/-!\n# Option of a type\n\n> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.\n> Any changes to this file require a corresponding PR to mathlib4.\n\nThis file develops the basic theory of option types.\n\nIf `α` is a type, then `option α` can be understood as the type with one more element than `α`.\n`option α` has terms `some a`, where `a : α`, and `none`, which is the added element.\nThis is useful in multiple ways:\n* It is the prototype of addition of terms to a type. See for example `with_bot α` which uses\n `none` as an element smaller than all others.\n* It can be used to define failsafe partial functions, which return `some the_result_we_expect`\n if we can find `the_result_we_expect`, and `none` if there is no meaningful result. This forces\n any subsequent use of the partial function to explicitly deal with the exceptions that make it\n return `none`.\n* `option` is a monad. We love monads.\n\n`part` is an alternative to `option` that can be seen as the type of `true`/`false` values\nalong with a term `a : α` if the value is `true`.\n\n## Implementation notes\n\n`option` is currently defined in core Lean, but this will change in Lean 4.\n-/\n\n\nnamespace Option\n\nvariable {α β γ δ : Type _}\n\n#print Option.coe_def /-\ntheorem coe_def : (coe : α → Option α) = some :=\n rfl\n#align option.coe_def Option.coe_def\n-/\n\ntheorem some_eq_coe (a : α) : some a = a :=\n rfl\n#align option.some_eq_coe Option.some_eq_coe\n\n#print Option.some_ne_none /-\ntheorem some_ne_none (x : α) : some x ≠ none := fun h => Option.noConfusion h\n#align option.some_ne_none Option.some_ne_none\n-/\n\n@[simp]\ntheorem coe_ne_none (a : α) : (a : Option α) ≠ none :=\n fun.\n#align option.coe_ne_none Option.coe_ne_none\n\n#print Option.forall /-\nprotected theorem forall {p : Option α → Prop} : (∀ x, p x) ↔ p none ∧ ∀ x, p (some x) :=\n ⟨fun h => ⟨h _, fun x => h _⟩, fun h x => Option.casesOn x h.1 h.2⟩\n#align option.forall Option.forall\n-/\n\n#print Option.exists /-\nprotected theorem exists {p : Option α → Prop} : (∃ x, p x) ↔ p none ∨ ∃ x, p (some x) :=\n ⟨fun ⟨x, hx⟩ => (Option.casesOn x Or.inl fun x hx => Or.inr ⟨x, hx⟩) hx, fun h =>\n h.elim (fun h => ⟨_, h⟩) fun ⟨x, hx⟩ => ⟨_, hx⟩⟩\n#align option.exists Option.exists\n-/\n\n#print Option.get_mem /-\n@[simp]\ntheorem get_mem : ∀ {o : Option α} (h : isSome o), Option.get h ∈ o\n | some a, _ => rfl\n#align option.get_mem Option.get_mem\n-/\n\n#print Option.get_of_mem /-\ntheorem get_of_mem {a : α} : ∀ {o : Option α} (h : isSome o), a ∈ o → Option.get h = a\n | _, _, rfl => rfl\n#align option.get_of_mem Option.get_of_mem\n-/\n\n#print Option.not_mem_none /-\n@[simp]\ntheorem not_mem_none (a : α) : a ∉ (none : Option α) := fun h => Option.noConfusion h\n#align option.not_mem_none Option.not_mem_none\n-/\n\n#print Option.some_get /-\n@[simp]\ntheorem some_get : ∀ {x : Option α} (h : isSome x), some (Option.get h) = x\n | some x, hx => rfl\n#align option.some_get Option.some_get\n-/\n\n#print Option.get_some /-\n@[simp]\ntheorem get_some (x : α) (h : isSome (some x)) : Option.get h = x :=\n rfl\n#align option.get_some Option.get_some\n-/\n\n#print Option.getD_some /-\n@[simp]\ntheorem getD_some (x y : α) : Option.getD (some x) y = x :=\n rfl\n#align option.get_or_else_some Option.getD_some\n-/\n\n#print Option.getD_none /-\n@[simp]\ntheorem getD_none (x : α) : Option.getD none x = x :=\n rfl\n#align option.get_or_else_none Option.getD_none\n-/\n\n#print Option.getD_coe /-\n@[simp]\ntheorem getD_coe (x y : α) : Option.getD (↑x) y = x :=\n rfl\n#align option.get_or_else_coe Option.getD_coe\n-/\n\n#print Option.getD_of_ne_none /-\ntheorem getD_of_ne_none {x : Option α} (hx : x ≠ none) (y : α) : some (x.getD y) = x := by\n cases x <;> [contradiction, rw [get_or_else_some]]\n#align option.get_or_else_of_ne_none Option.getD_of_ne_none\n-/\n\n#print Option.coe_get /-\n@[simp]\ntheorem coe_get {o : Option α} (h : o.isSome) : ((Option.get h : α) : Option α) = o :=\n Option.some_get h\n#align option.coe_get Option.coe_get\n-/\n\n#print Option.mem_unique /-\ntheorem mem_unique {o : Option α} {a b : α} (ha : a ∈ o) (hb : b ∈ o) : a = b :=\n Option.some.inj <| ha.symm.trans hb\n#align option.mem_unique Option.mem_unique\n-/\n\n#print Option.eq_of_mem_of_mem /-\ntheorem eq_of_mem_of_mem {a : α} {o1 o2 : Option α} (h1 : a ∈ o1) (h2 : a ∈ o2) : o1 = o2 :=\n h1.trans h2.symm\n#align option.eq_of_mem_of_mem Option.eq_of_mem_of_mem\n-/\n\n#print Option.Mem.leftUnique /-\ntheorem Mem.leftUnique : Relator.LeftUnique ((· ∈ ·) : α → Option α → Prop) := fun a o b =>\n mem_unique\n#align option.mem.left_unique Option.Mem.leftUnique\n-/\n\n#print Option.some_injective /-\ntheorem some_injective (α : Type _) : Function.Injective (@some α) := fun _ _ => some_inj.mp\n#align option.some_injective Option.some_injective\n-/\n\n/- warning: option.map_injective -> Option.map_injective is a dubious translation:\nlean 3 declaration is\n forall {α : Type.{u1}} {β : Type.{u2}} {f : α -> β}, (Function.Injective.{succ u1, succ u2} α β f) -> (Function.Injective.{succ u1, succ u2} (Option.{u1} α) (Option.{u2} β) (Option.map.{u1, u2} α β f))\nbut is expected to have type\n forall {α : Type.{u2}} {β : Type.{u1}} {f : α -> β}, (Function.Injective.{succ u2, succ u1} α β f) -> (Function.Injective.{succ u2, succ u1} (Option.{u2} α) (Option.{u1} β) (Option.map.{u2, u1} α β f))\nCase conversion may be inaccurate. Consider using '#align option.map_injective Option.map_injectiveₓ'. -/\n/-- `option.map f` is injective if `f` is injective. -/\ntheorem map_injective {f : α → β} (Hf : Function.Injective f) : Function.Injective (Option.map f)\n | none, none, H => rfl\n | some a₁, some a₂, H => by rw [Hf (Option.some.inj H)]\n#align option.map_injective Option.map_injective\n\n/- warning: option.map_comp_some -> Option.map_comp_some is a dubious translation:\nlean 3 declaration is\n forall {α : Type.{u1}} {β : Type.{u2}} (f : α -> β), Eq.{max (succ u1) (succ u2)} (α -> (Option.{u2} β)) (Function.comp.{succ u1, succ u1, succ u2} α (Option.{u1} α) (Option.{u2} β) (Option.map.{u1, u2} α β f) (Option.some.{u1} α)) (Function.comp.{succ u1, succ u2, succ u2} α β (Option.{u2} β) (Option.some.{u2} β) f)\nbut is expected to have type\n forall {α : Type.{u2}} {β : Type.{u1}} (f : α -> β), Eq.{max (succ u2) (succ u1)} (α -> (Option.{u1} β)) (Function.comp.{succ u2, succ u2, succ u1} α (Option.{u2} α) (Option.{u1} β) (Option.map.{u2, u1} α β f) (Option.some.{u2} α)) (Function.comp.{succ u2, succ u1, succ u1} α β (Option.{u1} β) (Option.some.{u1} β) f)\nCase conversion may be inaccurate. Consider using '#align option.map_comp_some Option.map_comp_someₓ'. -/\n@[simp]\ntheorem map_comp_some (f : α → β) : Option.map f ∘ some = some ∘ f :=\n rfl\n#align option.map_comp_some Option.map_comp_some\n\n#print Option.ext /-\n@[ext]\ntheorem ext : ∀ {o₁ o₂ : Option α}, (∀ a, a ∈ o₁ ↔ a ∈ o₂) → o₁ = o₂\n | none, none, H => rfl\n | some a, o, H => ((H _).1 rfl).symm\n | o, some b, H => (H _).2 rfl\n#align option.ext Option.ext\n-/\n\n#print Option.eq_none_iff_forall_not_mem /-\ntheorem eq_none_iff_forall_not_mem {o : Option α} : o = none ↔ ∀ a, a ∉ o :=\n ⟨fun e a h => by rw [e] at h <;> cases h, fun h => ext <| by simpa⟩\n#align option.eq_none_iff_forall_not_mem Option.eq_none_iff_forall_not_mem\n-/\n\n/- warning: option.none_bind -> Option.none_bind is a dubious translation:\nlean 3 declaration is\n forall {α : Type.{u_1}} {β : Type.{u_1}} (f : α -> (Option.{u_1} β)), Eq.{succ u_1} (Option.{u_1} β) (Bind.bind.{u_1, u_1} Option.{u_1} (Monad.toHasBind.{u_1, u_1} Option.{u_1} Option.monad.{u_1}) α β (Option.none.{u_1} α) f) (Option.none.{u_1} β)\nbut is expected to have type\n forall {α : Type.{u_1}} {β : Type.{u_2}} (f : α -> (Option.{u_2} β)), Eq.{succ u_2} (Option.{u_2} β) (Option.bind.{u_1, u_2} α β (Option.none.{u_1} α) f) (Option.none.{u_2} β)\nCase conversion may be inaccurate. Consider using '#align option.none_bind Option.none_bindₓ'. -/\n@[simp]\ntheorem none_bind {α β} (f : α → Option β) : none >>= f = none :=\n rfl\n#align option.none_bind Option.none_bind\n\n/- warning: option.some_bind -> Option.some_bind is a dubious translation:\nlean 3 declaration is\n forall {α : Type.{u_1}} {β : Type.{u_1}} (a : α) (f : α -> (Option.{u_1} β)), Eq.{succ u_1} (Option.{u_1} β) (Bind.bind.{u_1, u_1} Option.{u_1} (Monad.toHasBind.{u_1, u_1} Option.{u_1} Option.monad.{u_1}) α β (Option.some.{u_1} α a) f) (f a)\nbut is expected to have type\n forall {α : Type.{u_1}} {β : Type.{u_2}} (a : α) (f : α -> (Option.{u_2} β)), Eq.{succ u_2} (Option.{u_2} β) (Option.bind.{u_1, u_2} α β (Option.some.{u_1} α a) f) (f a)\nCase conversion may be inaccurate. Consider using '#align option.some_bind Option.some_bindₓ'. -/\n@[simp]\ntheorem some_bind {α β} (a : α) (f : α → Option β) : some a >>= f = f a :=\n rfl\n#align option.some_bind Option.some_bind\n\n#print Option.none_bind' /-\n@[simp]\ntheorem none_bind' (f : α → Option β) : none.bind f = none :=\n rfl\n#align option.none_bind' Option.none_bind'\n-/\n\n#print Option.some_bind' /-\n@[simp]\ntheorem some_bind' (a : α) (f : α → Option β) : (some a).bind f = f a :=\n rfl\n#align option.some_bind' Option.some_bind'\n-/\n\n/- warning: option.bind_some -> Option.bind_some is a dubious translation:\nlean 3 declaration is\n forall {α : Type.{u1}} (x : Option.{u1} α), Eq.{succ u1} (Option.{u1} α) (Bind.bind.{u1, u1} Option.{u1} (Monad.toHasBind.{u1, u1} Option.{u1} Option.monad.{u1}) α α x (Option.some.{u1} α)) x\nbut is expected to have type\n forall {α : Type.{u1}} (x : Option.{u1} α), Eq.{succ u1} (Option.{u1} α) (Option.bind.{u1, u1} α α x (Option.some.{u1} α)) x\nCase conversion may be inaccurate. Consider using '#align option.bind_some Option.bind_someₓ'. -/\n@[simp]\ntheorem bind_some : ∀ x : Option α, x >>= some = x :=\n @bind_pure α Option _ _\n#align option.bind_some Option.bind_some\n\n@[simp]\ntheorem bind_some' : ∀ x : Option α, x.bind some = x :=\n bind_some\n#align option.bind_some' Option.bind_some'\n\n/- warning: option.bind_eq_some -> Option.bind_eq_some is a dubious translation:\nlean 3 declaration is\n forall {α : Type.{u_1}} {β : Type.{u_1}} {x : Option.{u_1} α} {f : α -> (Option.{u_1} β)} {b : β}, Iff (Eq.{succ u_1} (Option.{u_1} β) (Bind.bind.{u_1, u_1} Option.{u_1} (Monad.toHasBind.{u_1, u_1} Option.{u_1} Option.monad.{u_1}) α β x f) (Option.some.{u_1} β b)) (Exists.{succ u_1} α (fun (a : α) => And (Eq.{succ u_1} (Option.{u_1} α) x (Option.some.{u_1} α a)) (Eq.{succ u_1} (Option.{u_1} β) (f a) (Option.some.{u_1} β b))))\nbut is expected to have type\n forall {α : Type.{u_1}} {β : α} {x : Type.{u_2}} {f : Option.{u_2} x} {b : x -> (Option.{u_1} α)}, Iff (Eq.{succ u_1} (Option.{u_1} α) (Option.bind.{u_2, u_1} x α f b) (Option.some.{u_1} α β)) (Exists.{succ u_2} x (fun (a : x) => And (Eq.{succ u_2} (Option.{u_2} x) f (Option.some.{u_2} x a)) (Eq.{succ u_1} (Option.{u_1} α) (b a) (Option.some.{u_1} α β))))\nCase conversion may be inaccurate. Consider using '#align option.bind_eq_some Option.bind_eq_someₓ'. -/\n@[simp]\ntheorem bind_eq_some {α β} {x : Option α} {f : α → Option β} {b : β} :\n x >>= f = some b ↔ ∃ a, x = some a ∧ f a = some b := by cases x <;> simp\n#align option.bind_eq_some Option.bind_eq_some\n\n/- warning: option.bind_eq_some' -> Option.bind_eq_some' is a dubious translation:\nlean 3 declaration is\n forall {α : Type.{u1}} {β : Type.{u2}} {x : Option.{u1} α} {f : α -> (Option.{u2} β)} {b : β}, Iff (Eq.{succ u2} (Option.{u2} β) (Option.bind.{u1, u2} α β x f) (Option.some.{u2} β b)) (Exists.{succ u1} α (fun (a : α) => And (Eq.{succ u1} (Option.{u1} α) x (Option.some.{u1} α a)) (Eq.{succ u2} (Option.{u2} β) (f a) (Option.some.{u2} β b))))\nbut is expected to have type\n forall {α : Type.{u2}} {β : Type.{u1}} {x : Option.{u2} α} {f : α -> (Option.{u1} β)} {b : β}, Iff (Eq.{succ u1} (Option.{u1} β) (Option.bind.{u2, u1} α β x f) (Option.some.{u1} β b)) (Exists.{succ u2} α (fun (a : α) => And (Eq.{succ u2} (Option.{u2} α) x (Option.some.{u2} α a)) (Eq.{succ u1} (Option.{u1} β) (f a) (Option.some.{u1} β b))))\nCase conversion may be inaccurate. Consider using '#align option.bind_eq_some' Option.bind_eq_some'ₓ'. -/\n@[simp]\ntheorem bind_eq_some' {x : Option α} {f : α → Option β} {b : β} :\n x.bind f = some b ↔ ∃ a, x = some a ∧ f a = some b := by cases x <;> simp\n#align option.bind_eq_some' Option.bind_eq_some'\n\n/- warning: option.bind_eq_none' -> Option.bind_eq_none' is a dubious translation:\nlean 3 declaration is\n forall {α : Type.{u1}} {β : Type.{u2}} {o : Option.{u1} α} {f : α -> (Option.{u2} β)}, Iff (Eq.{succ u2} (Option.{u2} β) (Option.bind.{u1, u2} α β o f) (Option.none.{u2} β)) (forall (b : β) (a : α), (Membership.Mem.{u1, u1} α (Option.{u1} α) (Option.hasMem.{u1} α) a o) -> (Not (Membership.Mem.{u2, u2} β (Option.{u2} β) (Option.hasMem.{u2} β) b (f a))))\nbut is expected to have type\n forall {α : Type.{u2}} {β : Type.{u1}} {o : Option.{u2} α} {f : α -> (Option.{u1} β)}, Iff (Eq.{succ u1} (Option.{u1} β) (Option.bind.{u2, u1} α β o f) (Option.none.{u1} β)) (forall (b : β) (a : α), (Membership.mem.{u2, u2} α (Option.{u2} α) (Option.instMembershipOption.{u2} α) a o) -> (Not (Membership.mem.{u1, u1} β (Option.{u1} β) (Option.instMembershipOption.{u1} β) b (f a))))\nCase conversion may be inaccurate. Consider using '#align option.bind_eq_none' Option.bind_eq_none'ₓ'. -/\n@[simp]\ntheorem bind_eq_none' {o : Option α} {f : α → Option β} :\n o.bind f = none ↔ ∀ b a, a ∈ o → b ∉ f a := by\n simp only [eq_none_iff_forall_not_mem, not_exists, not_and, mem_def, bind_eq_some']\n#align option.bind_eq_none' Option.bind_eq_none'\n\n/- warning: option.bind_eq_none -> Option.bind_eq_none is a dubious translation:\nlean 3 declaration is\n forall {α : Type.{u_1}} {β : Type.{u_1}} {o : Option.{u_1} α} {f : α -> (Option.{u_1} β)}, Iff (Eq.{succ u_1} (Option.{u_1} β) (Bind.bind.{u_1, u_1} Option.{u_1} (Monad.toHasBind.{u_1, u_1} Option.{u_1} Option.monad.{u_1}) α β o f) (Option.none.{u_1} β)) (forall (b : β) (a : α), (Membership.Mem.{u_1, u_1} α (Option.{u_1} α) (Option.hasMem.{u_1} α) a o) -> (Not (Membership.Mem.{u_1, u_1} β (Option.{u_1} β) (Option.hasMem.{u_1} β) b (f a))))\nbut is expected to have type\n forall {α : Type.{u_1}} {β : Type.{u_2}} {o : Option.{u_1} α} {f : α -> (Option.{u_2} β)}, Iff (Eq.{succ u_2} (Option.{u_2} β) (Option.bind.{u_1, u_2} α β o f) (Option.none.{u_2} β)) (forall (b : β) (a : α), (Membership.mem.{u_1, u_1} α (Option.{u_1} α) (Option.instMembershipOption.{u_1} α) a o) -> (Not (Membership.mem.{u_2, u_2} β (Option.{u_2} β) (Option.instMembershipOption.{u_2} β) b (f a))))\nCase conversion may be inaccurate. Consider using '#align option.bind_eq_none Option.bind_eq_noneₓ'. -/\n@[simp]\ntheorem bind_eq_none {α β} {o : Option α} {f : α → Option β} :\n o >>= f = none ↔ ∀ b a, a ∈ o → b ∉ f a :=\n bind_eq_none'\n#align option.bind_eq_none Option.bind_eq_none\n\n/- warning: option.bind_comm -> Option.bind_comm is a dubious translation:\nlean 3 declaration is\n forall {α : Type.{u1}} {β : Type.{u2}} {γ : Type.{u3}} {f : α -> β -> (Option.{u3} γ)} (a : Option.{u1} α) (b : Option.{u2} β), Eq.{succ u3} (Option.{u3} γ) (Option.bind.{u1, u3} α γ a (fun (x : α) => Option.bind.{u2, u3} β γ b (f x))) (Option.bind.{u2, u3} β γ b (fun (y : β) => Option.bind.{u1, u3} α γ a (fun (x : α) => f x y)))\nbut is expected to have type\n forall {α : Type.{u3}} {β : Type.{u2}} {γ : Type.{u1}} {f : α -> β -> (Option.{u1} γ)} (a : Option.{u3} α) (b : Option.{u2} β), Eq.{succ u1} (Option.{u1} γ) (Option.bind.{u3, u1} α γ a (fun (x : α) => Option.bind.{u2, u1} β γ b (f x))) (Option.bind.{u2, u1} β γ b (fun (y : β) => Option.bind.{u3, u1} α γ a (fun (x : α) => f x y)))\nCase conversion may be inaccurate. Consider using '#align option.bind_comm Option.bind_commₓ'. -/\ntheorem bind_comm {α β γ} {f : α → β → Option γ} (a : Option α) (b : Option β) :\n (a.bind fun x => b.bind (f x)) = b.bind fun y => a.bind fun x => f x y := by\n cases a <;> cases b <;> rfl\n#align option.bind_comm Option.bind_comm\n\n/- warning: option.bind_assoc -> Option.bind_assoc is a dubious translation:\nlean 3 declaration is\n forall {α : Type.{u1}} {β : Type.{u2}} {γ : Type.{u3}} (x : Option.{u1} α) (f : α -> (Option.{u2} β)) (g : β -> (Option.{u3} γ)), Eq.{succ u3} (Option.{u3} γ) (Option.bind.{u2, u3} β γ (Option.bind.{u1, u2} α β x f) g) (Option.bind.{u1, u3} α γ x (fun (y : α) => Option.bind.{u2, u3} β γ (f y) g))\nbut is expected to have type\n forall {α : Type.{u3}} {β : Type.{u2}} {γ : Type.{u1}} (x : Option.{u3} α) (f : α -> (Option.{u2} β)) (g : β -> (Option.{u1} γ)), Eq.{succ u1} (Option.{u1} γ) (Option.bind.{u2, u1} β γ (Option.bind.{u3, u2} α β x f) g) (Option.bind.{u3, u1} α γ x (fun (y : α) => Option.bind.{u2, u1} β γ (f y) g))\nCase conversion may be inaccurate. Consider using '#align option.bind_assoc Option.bind_assocₓ'. -/\ntheorem bind_assoc (x : Option α) (f : α → Option β) (g : β → Option γ) :\n (x.bind f).bind g = x.bind fun y => (f y).bind g := by cases x <;> rfl\n#align option.bind_assoc Option.bind_assoc\n\n/- warning: option.join_eq_some -> Option.join_eq_some is a dubious translation:\nlean 3 declaration is\n forall {α : Type.{u1}} {x : Option.{u1} (Option.{u1} α)} {a : α}, Iff (Eq.{succ u1} (Option.{u1} α) (Option.join.{u1} α x) (Option.some.{u1} α a)) (Eq.{succ u1} (Option.{u1} (Option.{u1} α)) x (Option.some.{u1} (Option.{u1} α) (Option.some.{u1} α a)))\nbut is expected to have type\n forall {α : Type.{u1}} {x : α} {a : Option.{u1} (Option.{u1} α)}, Iff (Eq.{succ u1} (Option.{u1} α) (Option.join.{u1} α a) (Option.some.{u1} α x)) (Eq.{succ u1} (Option.{u1} (Option.{u1} α)) a (Option.some.{u1} (Option.{u1} α) (Option.some.{u1} α x)))\nCase conversion may be inaccurate. Consider using '#align option.join_eq_some Option.join_eq_someₓ'. -/\ntheorem join_eq_some {x : Option (Option α)} {a : α} : x.join = some a ↔ x = some (some a) := by\n simp\n#align option.join_eq_some Option.join_eq_some\n\n#print Option.join_ne_none /-\ntheorem join_ne_none {x : Option (Option α)} : x.join ≠ none ↔ ∃ z, x = some (some z) := by simp\n#align option.join_ne_none Option.join_ne_none\n-/\n\n#print Option.join_ne_none' /-\ntheorem join_ne_none' {x : Option (Option α)} : ¬x.join = none ↔ ∃ z, x = some (some z) := by simp\n#align option.join_ne_none' Option.join_ne_none'\n-/\n\n#print Option.join_eq_none /-\ntheorem join_eq_none {o : Option (Option α)} : o.join = none ↔ o = none ∨ o = some none := by\n rcases o with (_ | _ | _) <;> simp\n#align option.join_eq_none Option.join_eq_none\n-/\n\n/- warning: option.bind_id_eq_join -> Option.bind_id_eq_join is a dubious translation:\nlean 3 declaration is\n forall {α : Type.{u1}} {x : Option.{u1} (Option.{u1} α)}, Eq.{succ u1} (Option.{u1} α) (Bind.bind.{u1, u1} Option.{u1} (Monad.toHasBind.{u1, u1} Option.{u1} Option.monad.{u1}) (Option.{u1} α) α x (id.{succ u1} (Option.{u1} α))) (Option.join.{u1} α x)\nbut is expected to have type\n forall {α : Type.{u1}} {x : Option.{u1} (Option.{u1} α)}, Eq.{succ u1} (Option.{u1} α) (Option.bind.{u1, u1} (Option.{u1} α) α x (id.{succ u1} (Option.{u1} α))) (Option.join.{u1} α x)\nCase conversion may be inaccurate. Consider using '#align option.bind_id_eq_join Option.bind_id_eq_joinₓ'. -/\ntheorem bind_id_eq_join {x : Option (Option α)} : x >>= id = x.join := by simp\n#align option.bind_id_eq_join Option.bind_id_eq_join\n\n/- warning: option.join_eq_join -> Option.joinM_eq_join is a dubious translation:\nlean 3 declaration is\n forall {α : Type.{u1}}, Eq.{succ u1} ((Option.{u1} (Option.{u1} α)) -> (Option.{u1} α)) (joinM.{u1} Option.{u1} Option.monad.{u1} α) (Option.join.{u1} α)\nbut is expected to have type\n forall {α : Type.{u1}}, Eq.{succ u1} ((Option.{u1} (Option.{u1} α)) -> (Option.{u1} α)) (joinM.{u1} Option.{u1} instMonadOption.{u1} α) (Option.join.{u1} α)\nCase conversion may be inaccurate. Consider using '#align option.join_eq_join Option.joinM_eq_joinₓ'. -/\ntheorem joinM_eq_join : joinM = @join α :=\n funext fun x => by rw [joinM, bind_id_eq_join]\n#align option.join_eq_join Option.joinM_eq_join\n\n/- warning: option.bind_eq_bind -> Option.bind_eq_bind is a dubious translation:\nlean 3 declaration is\n forall {α : Type.{u1}} {β : Type.{u1}} {f : α -> (Option.{u1} β)} {x : Option.{u1} α}, Eq.{succ u1} (Option.{u1} β) (Bind.bind.{u1, u1} Option.{u1} (Monad.toHasBind.{u1, u1} Option.{u1} Option.monad.{u1}) α β x f) (Option.bind.{u1, u1} α β x f)\nbut is expected to have type\n forall {α : Type.{u1}} {β : Type.{u1}} {f : α -> (Option.{u1} β)} {x : Option.{u1} α}, Eq.{succ u1} (Option.{u1} β) (Bind.bind.{u1, u1} Option.{u1} (Monad.toBind.{u1, u1} Option.{u1} instMonadOption.{u1}) α β x f) (Option.bind.{u1, u1} α β x f)\nCase conversion may be inaccurate. Consider using '#align option.bind_eq_bind Option.bind_eq_bindₓ'. -/\ntheorem bind_eq_bind {α β : Type _} {f : α → Option β} {x : Option α} : x >>= f = x.bind f :=\n rfl\n#align option.bind_eq_bind Option.bind_eq_bind\n\n/- warning: option.map_eq_map -> Option.map_eq_map is a dubious translation:\nlean 3 declaration is\n forall {α : Type.{u1}} {β : Type.{u1}} {f : α -> β}, Eq.{succ u1} ((Option.{u1} α) -> (Option.{u1} β)) (Functor.map.{u1, u1} Option.{u1} (Traversable.toFunctor.{u1} Option.{u1} Option.traversable.{u1}) α β f) (Option.map.{u1, u1} α β f)\nbut is expected to have type\n forall {α : Type.{u1}} {β : Type.{u1}} {f : α -> β}, Eq.{succ u1} ((Option.{u1} α) -> (Option.{u1} β)) (Functor.map.{u1, u1} Option.{u1} instFunctorOption.{u1} α β f) (Option.map.{u1, u1} α β f)\nCase conversion may be inaccurate. Consider using '#align option.map_eq_map Option.map_eq_mapₓ'. -/\n@[simp]\ntheorem map_eq_map {α β} {f : α → β} : (· <$> ·) f = Option.map f :=\n rfl\n#align option.map_eq_map Option.map_eq_map\n\n/- warning: option.map_none -> Option.map_none is a dubious translation:\nlean 3 declaration is\n forall {α : Type.{u1}} {β : Type.{u1}} {f : α -> β}, Eq.{succ u1} (Option.{u1} β) (Functor.map.{u1, u1} Option.{u1} (Traversable.toFunctor.{u1} Option.{u1} Option.traversable.{u1}) α β f (Option.none.{u1} α)) (Option.none.{u1} β)\nbut is expected to have type\n forall {α : Type.{u1}} {β : Type.{u1}} {f : α -> β}, Eq.{succ u1} (Option.{u1} β) (Functor.map.{u1, u1} Option.{u1} instFunctorOption.{u1} α β f (Option.none.{u1} α)) (Option.none.{u1} β)\nCase conversion may be inaccurate. Consider using '#align option.map_none Option.map_noneₓ'. -/\ntheorem map_none {α β} {f : α → β} : f <$> none = none :=\n rfl\n#align option.map_none Option.map_none\n\n/- warning: option.map_some -> Option.map_some is a dubious translation:\nlean 3 declaration is\n forall {α : Type.{u1}} {β : Type.{u1}} {a : α} {f : α -> β}, Eq.{succ u1} (Option.{u1} β) (Functor.map.{u1, u1} Option.{u1} (Traversable.toFunctor.{u1} Option.{u1} Option.traversable.{u1}) α β f (Option.some.{u1} α a)) (Option.some.{u1} β (f a))\nbut is expected to have type\n forall {α : Type.{u1}} {β : Type.{u1}} {a : α -> β} {f : α}, Eq.{succ u1} (Option.{u1} β) (Functor.map.{u1, u1} Option.{u1} instFunctorOption.{u1} α β a (Option.some.{u1} α f)) (Option.some.{u1} β (a f))\nCase conversion may be inaccurate. Consider using '#align option.map_some Option.map_someₓ'. -/\ntheorem map_some {α β} {a : α} {f : α → β} : f <$> some a = some (f a) :=\n rfl\n#align option.map_some Option.map_some\n\n/- warning: option.map_coe -> Option.map_coe is a dubious translation:\nlean 3 declaration is\n forall {α : Type.{u1}} {β : Type.{u1}} {a : α} {f : α -> β}, Eq.{succ u1} (Option.{u1} β) (Functor.map.{u1, u1} (fun {α : Type.{u1}} => Option.{u1} α) (Traversable.toFunctor.{u1} (fun {α : Type.{u1}} => Option.{u1} α) Option.traversable.{u1}) α β f ((fun (a : Type.{u1}) (b : Type.{u1}) [self : HasLiftT.{succ u1, succ u1} a b] => self.0) α (Option.{u1} α) (HasLiftT.mk.{succ u1, succ u1} α (Option.{u1} α) (CoeTCₓ.coe.{succ u1, succ u1} α (Option.{u1} α) (coeOption.{u1} α))) a)) ((fun (a : Type.{u1}) (b : Type.{u1}) [self : HasLiftT.{succ u1, succ u1} a b] => self.0) β (Option.{u1} β) (HasLiftT.mk.{succ u1, succ u1} β (Option.{u1} β) (CoeTCₓ.coe.{succ u1, succ u1} β (Option.{u1} β) (coeOption.{u1} β))) (f a))\nbut is expected to have type\n forall {α : Type.{u1}} {β : Type.{u1}} {a : α} {f : α -> β}, Eq.{succ u1} (Option.{u1} β) (Functor.map.{u1, u1} Option.{u1} instFunctorOption.{u1} α β f (Option.some.{u1} α a)) (Option.some.{u1} β (f a))\nCase conversion may be inaccurate. Consider using '#align option.map_coe Option.map_coeₓ'. -/\ntheorem map_coe {α β} {a : α} {f : α → β} : f <$> (a : Option α) = ↑(f a) :=\n rfl\n#align option.map_coe Option.map_coe\n\n/- warning: option.map_none' -> Option.map_none' is a dubious translation:\nlean 3 declaration is\n forall {α : Type.{u1}} {β : Type.{u2}} {f : α -> β}, Eq.{succ u2} (Option.{u2} β) (Option.map.{u1, u2} α β f (Option.none.{u1} α)) (Option.none.{u2} β)\nbut is expected to have type\n forall {α : Type.{u2}} {β : Type.{u1}} (f : α -> β), Eq.{succ u1} (Option.{u1} β) (Option.map.{u2, u1} α β f (Option.none.{u2} α)) (Option.none.{u1} β)\nCase conversion may be inaccurate. Consider using '#align option.map_none' Option.map_none'ₓ'. -/\n@[simp]\ntheorem map_none' {f : α → β} : Option.map f none = none :=\n rfl\n#align option.map_none' Option.map_none'\n\n/- warning: option.map_some' -> Option.map_some' is a dubious translation:\nlean 3 declaration is\n forall {α : Type.{u1}} {β : Type.{u2}} {a : α} {f : α -> β}, Eq.{succ u2} (Option.{u2} β) (Option.map.{u1, u2} α β f (Option.some.{u1} α a)) (Option.some.{u2} β (f a))\nbut is expected to have type\n forall {α : Type.{u2}} {β : Type.{u1}} (a : α) (f : α -> β), Eq.{succ u1} (Option.{u1} β) (Option.map.{u2, u1} α β f (Option.some.{u2} α a)) (Option.some.{u1} β (f a))\nCase conversion may be inaccurate. Consider using '#align option.map_some' Option.map_some'ₓ'. -/\n@[simp]\ntheorem map_some' {a : α} {f : α → β} : Option.map f (some a) = some (f a) :=\n rfl\n#align option.map_some' Option.map_some'\n\n#print Option.map_coe' /-\n@[simp]\ntheorem map_coe' {a : α} {f : α → β} : Option.map f (a : Option α) = ↑(f a) :=\n rfl\n#align option.map_coe' Option.map_coe'\n-/\n\n/- warning: option.map_eq_some -> Option.map_eq_some is a dubious translation:\nlean 3 declaration is\n forall {α : Type.{u1}} {β : Type.{u1}} {x : Option.{u1} α} {f : α -> β} {b : β}, Iff (Eq.{succ u1} (Option.{u1} β) (Functor.map.{u1, u1} (fun {α : Type.{u1}} => Option.{u1} α) (Traversable.toFunctor.{u1} (fun {α : Type.{u1}} => Option.{u1} α) Option.traversable.{u1}) α β f x) (Option.some.{u1} β b)) (Exists.{succ u1} α (fun (a : α) => And (Eq.{succ u1} (Option.{u1} α) x (Option.some.{u1} α a)) (Eq.{succ u1} β (f a) b)))\nbut is expected to have type\n forall {α : Type.{u1}} {β : Type.{u1}} {x : α -> β} {f : Option.{u1} α} {b : β}, Iff (Eq.{succ u1} (Option.{u1} β) (Functor.map.{u1, u1} Option.{u1} instFunctorOption.{u1} α β x f) (Option.some.{u1} β b)) (Exists.{succ u1} α (fun (a : α) => And (Eq.{succ u1} (Option.{u1} α) f (Option.some.{u1} α a)) (Eq.{succ u1} β (x a) b)))\nCase conversion may be inaccurate. Consider using '#align option.map_eq_some Option.map_eq_someₓ'. -/\ntheorem map_eq_some {α β} {x : Option α} {f : α → β} {b : β} :\n f <$> x = some b ↔ ∃ a, x = some a ∧ f a = b := by cases x <;> simp\n#align option.map_eq_some Option.map_eq_some\n\n/- warning: option.map_eq_some' -> Option.map_eq_some' is a dubious translation:\nlean 3 declaration is\n forall {α : Type.{u1}} {β : Type.{u2}} {x : Option.{u1} α} {f : α -> β} {b : β}, Iff (Eq.{succ u2} (Option.{u2} β) (Option.map.{u1, u2} α β f x) (Option.some.{u2} β b)) (Exists.{succ u1} α (fun (a : α) => And (Eq.{succ u1} (Option.{u1} α) x (Option.some.{u1} α a)) (Eq.{succ u2} β (f a) b)))\nbut is expected to have type\n forall {α : Type.{u2}} {β : α} {x : Type.{u1}} {f : Option.{u1} x} {b : x -> α}, Iff (Eq.{succ u2} (Option.{u2} α) (Option.map.{u1, u2} x α b f) (Option.some.{u2} α β)) (Exists.{succ u1} x (fun (a : x) => And (Eq.{succ u1} (Option.{u1} x) f (Option.some.{u1} x a)) (Eq.{succ u2} α (b a) β)))\nCase conversion may be inaccurate. Consider using '#align option.map_eq_some' Option.map_eq_some'ₓ'. -/\n@[simp]\ntheorem map_eq_some' {x : Option α} {f : α → β} {b : β} :\n x.map f = some b ↔ ∃ a, x = some a ∧ f a = b := by cases x <;> simp\n#align option.map_eq_some' Option.map_eq_some'\n\n/- warning: option.map_eq_none -> Option.map_eq_none is a dubious translation:\nlean 3 declaration is\n forall {α : Type.{u1}} {β : Type.{u1}} {x : Option.{u1} α} {f : α -> β}, Iff (Eq.{succ u1} (Option.{u1} β) (Functor.map.{u1, u1} (fun {α : Type.{u1}} => Option.{u1} α) (Traversable.toFunctor.{u1} (fun {α : Type.{u1}} => Option.{u1} α) Option.traversable.{u1}) α β f x) (Option.none.{u1} β)) (Eq.{succ u1} (Option.{u1} α) x (Option.none.{u1} α))\nbut is expected to have type\n forall {α : Type.{u1}} {β : Type.{u1}} {x : α -> β} {f : Option.{u1} α}, Iff (Eq.{succ u1} (Option.{u1} β) (Functor.map.{u1, u1} Option.{u1} instFunctorOption.{u1} α β x f) (Option.none.{u1} β)) (Eq.{succ u1} (Option.{u1} α) f (Option.none.{u1} α))\nCase conversion may be inaccurate. Consider using '#align option.map_eq_none Option.map_eq_noneₓ'. -/\ntheorem map_eq_none {α β} {x : Option α} {f : α → β} : f <$> x = none ↔ x = none := by\n cases x <;> simp only [map_none, map_some, eq_self_iff_true]\n#align option.map_eq_none Option.map_eq_none\n\n/- warning: option.map_eq_none' -> Option.map_eq_none' is a dubious translation:\nlean 3 declaration is\n forall {α : Type.{u1}} {β : Type.{u2}} {x : Option.{u1} α} {f : α -> β}, Iff (Eq.{succ u2} (Option.{u2} β) (Option.map.{u1, u2} α β f x) (Option.none.{u2} β)) (Eq.{succ u1} (Option.{u1} α) x (Option.none.{u1} α))\nbut is expected to have type\n forall {α : Type.{u2}} {β : Option.{u2} α} {x : Type.{u1}} {f : α -> x}, Iff (Eq.{succ u1} (Option.{u1} x) (Option.map.{u2, u1} α x f β) (Option.none.{u1} x)) (Eq.{succ u2} (Option.{u2} α) β (Option.none.{u2} α))\nCase conversion may be inaccurate. Consider using '#align option.map_eq_none' Option.map_eq_none'ₓ'. -/\n@[simp]\ntheorem map_eq_none' {x : Option α} {f : α → β} : x.map f = none ↔ x = none := by\n cases x <;> simp only [map_none', map_some', eq_self_iff_true]\n#align option.map_eq_none' Option.map_eq_none'\n\n/- warning: option.map_injective' -> Option.map_injective' is a dubious translation:\nlean 3 declaration is\n forall {α : Type.{u1}} {β : Type.{u2}}, Function.Injective.{max (succ u1) (succ u2), max (succ u1) (succ u2)} (α -> β) ((Option.{u1} α) -> (Option.{u2} β)) (Option.map.{u1, u2} α β)\nbut is expected to have type\n forall {α : Type.{u2}} {β : Type.{u1}}, Function.Injective.{max (succ u2) (succ u1), max (succ u2) (succ u1)} (α -> β) ((Option.{u2} α) -> (Option.{u1} β)) (Option.map.{u2, u1} α β)\nCase conversion may be inaccurate. Consider using '#align option.map_injective' Option.map_injective'ₓ'. -/\n/-- `option.map` as a function between functions is injective. -/\ntheorem map_injective' : Function.Injective (@Option.map α β) := fun f g h =>\n funext fun x => some_injective _ <| by simp only [← map_some', h]\n#align option.map_injective' Option.map_injective'\n\n/- warning: option.map_inj -> Option.map_inj is a dubious translation:\nlean 3 declaration is\n forall {α : Type.{u1}} {β : Type.{u2}} {f : α -> β} {g : α -> β}, Iff (Eq.{max (succ u1) (succ u2)} ((Option.{u1} α) -> (Option.{u2} β)) (Option.map.{u1, u2} α β f) (Option.map.{u1, u2} α β g)) (Eq.{max (succ u1) (succ u2)} (α -> β) f g)\nbut is expected to have type\n forall {α : Type.{u2}} {β : Type.{u1}} {f : α -> β} {g : α -> β}, Iff (Eq.{max (succ u2) (succ u1)} ((Option.{u2} α) -> (Option.{u1} β)) (Option.map.{u2, u1} α β f) (Option.map.{u2, u1} α β g)) (Eq.{max (succ u2) (succ u1)} (α -> β) f g)\nCase conversion may be inaccurate. Consider using '#align option.map_inj Option.map_injₓ'. -/\n@[simp]\ntheorem map_inj {f g : α → β} : Option.map f = Option.map g ↔ f = g :=\n map_injective'.eq_iff\n#align option.map_inj Option.map_inj\n\n/- warning: option.map_congr -> Option.map_congr is a dubious translation:\nlean 3 declaration is\n forall {α : Type.{u1}} {β : Type.{u2}} {f : α -> β} {g : α -> β} {x : Option.{u1} α}, (forall (a : α), (Membership.Mem.{u1, u1} α (Option.{u1} α) (Option.hasMem.{u1} α) a x) -> (Eq.{succ u2} β (f a) (g a))) -> (Eq.{succ u2} (Option.{u2} β) (Option.map.{u1, u2} α β f x) (Option.map.{u1, u2} α β g x))\nbut is expected to have type\n forall {α : Type.{u2}} {β : Type.{u1}} {f : α -> β} {g : α -> β} {x : Option.{u2} α}, (forall (a : α), (Membership.mem.{u2, u2} α (Option.{u2} α) (Option.instMembershipOption.{u2} α) a x) -> (Eq.{succ u1} β (f a) (g a))) -> (Eq.{succ u1} (Option.{u1} β) (Option.map.{u2, u1} α β f x) (Option.map.{u2, u1} α β g x))\nCase conversion may be inaccurate. Consider using '#align option.map_congr Option.map_congrₓ'. -/\ntheorem map_congr {f g : α → β} {x : Option α} (h : ∀ a ∈ x, f a = g a) :\n Option.map f x = Option.map g x := by cases x <;> simp only [map_none', map_some', h, mem_def]\n#align option.map_congr Option.map_congr\n\nattribute [simp] map_id\n\n#print Option.map_eq_id /-\n@[simp]\ntheorem map_eq_id {f : α → α} : Option.map f = id ↔ f = id :=\n map_injective'.eq_iff' map_id\n#align option.map_eq_id Option.map_eq_id\n-/\n\n/- warning: option.map_map -> Option.map_map is a dubious translation:\nlean 3 declaration is\n forall {α : Type.{u1}} {β : Type.{u2}} {γ : Type.{u3}} (h : β -> γ) (g : α -> β) (x : Option.{u1} α), Eq.{succ u3} (Option.{u3} γ) (Option.map.{u2, u3} β γ h (Option.map.{u1, u2} α β g x)) (Option.map.{u1, u3} α γ (Function.comp.{succ u1, succ u2, succ u3} α β γ h g) x)\nbut is expected to have type\n forall {α : Type.{u3}} {β : Type.{u2}} {γ : Type.{u1}} (h : α -> β) (g : γ -> α) (x : Option.{u1} γ), Eq.{succ u2} (Option.{u2} β) (Option.map.{u3, u2} α β h (Option.map.{u1, u3} γ α g x)) (Option.map.{u1, u2} γ β (Function.comp.{succ u1, succ u3, succ u2} γ α β h g) x)\nCase conversion may be inaccurate. Consider using '#align option.map_map Option.map_mapₓ'. -/\n@[simp]\ntheorem map_map (h : β → γ) (g : α → β) (x : Option α) :\n Option.map h (Option.map g x) = Option.map (h ∘ g) x := by\n cases x <;> simp only [map_none', map_some']\n#align option.map_map Option.map_map\n\n/- warning: option.map_comm -> Option.map_comm is a dubious translation:\nlean 3 declaration is\n forall {α : Type.{u1}} {β : Type.{u2}} {γ : Type.{u3}} {δ : Type.{u4}} {f₁ : α -> β} {f₂ : α -> γ} {g₁ : β -> δ} {g₂ : γ -> δ}, (Eq.{max (succ u1) (succ u4)} (α -> δ) (Function.comp.{succ u1, succ u2, succ u4} α β δ g₁ f₁) (Function.comp.{succ u1, succ u3, succ u4} α γ δ g₂ f₂)) -> (forall (a : α), Eq.{succ u4} (Option.{u4} δ) (Option.map.{u2, u4} β δ g₁ (Option.map.{u1, u2} α β f₁ ((fun (a : Type.{u1}) (b : Type.{u1}) [self : HasLiftT.{succ u1, succ u1} a b] => self.0) α (Option.{u1} α) (HasLiftT.mk.{succ u1, succ u1} α (Option.{u1} α) (CoeTCₓ.coe.{succ u1, succ u1} α (Option.{u1} α) (coeOption.{u1} α))) a))) (Option.map.{u3, u4} γ δ g₂ (Option.map.{u1, u3} α γ f₂ ((fun (a : Type.{u1}) (b : Type.{u1}) [self : HasLiftT.{succ u1, succ u1} a b] => self.0) α (Option.{u1} α) (HasLiftT.mk.{succ u1, succ u1} α (Option.{u1} α) (CoeTCₓ.coe.{succ u1, succ u1} α (Option.{u1} α) (coeOption.{u1} α))) a))))\nbut is expected to have type\n forall {α : Type.{u4}} {β : Type.{u2}} {γ : Type.{u1}} {δ : Type.{u3}} {f₁ : α -> β} {f₂ : α -> γ} {g₁ : β -> δ} {g₂ : γ -> δ}, (Eq.{max (succ u4) (succ u3)} (α -> δ) (Function.comp.{succ u4, succ u2, succ u3} α β δ g₁ f₁) (Function.comp.{succ u4, succ u1, succ u3} α γ δ g₂ f₂)) -> (forall (a : α), Eq.{succ u3} (Option.{u3} δ) (Option.map.{u2, u3} β δ g₁ (Option.map.{u4, u2} α β f₁ (Option.some.{u4} α a))) (Option.map.{u1, u3} γ δ g₂ (Option.map.{u4, u1} α γ f₂ (Option.some.{u4} α a))))\nCase conversion may be inaccurate. Consider using '#align option.map_comm Option.map_commₓ'. -/\ntheorem map_comm {f₁ : α → β} {f₂ : α → γ} {g₁ : β → δ} {g₂ : γ → δ} (h : g₁ ∘ f₁ = g₂ ∘ f₂)\n (a : α) : (Option.map f₁ a).map g₁ = (Option.map f₂ a).map g₂ := by rw [map_map, h, ← map_map]\n#align option.map_comm Option.map_comm\n\n/- warning: option.comp_map -> Option.comp_map is a dubious translation:\nlean 3 declaration is\n forall {α : Type.{u1}} {β : Type.{u2}} {γ : Type.{u3}} (h : β -> γ) (g : α -> β) (x : Option.{u1} α), Eq.{succ u3} (Option.{u3} γ) (Option.map.{u1, u3} α γ (Function.comp.{succ u1, succ u2, succ u3} α β γ h g) x) (Option.map.{u2, u3} β γ h (Option.map.{u1, u2} α β g x))\nbut is expected to have type\n forall {α : Type.{u3}} {β : Type.{u2}} {γ : Type.{u1}} (h : α -> β) (g : γ -> α) (x : Option.{u1} γ), Eq.{succ u2} (Option.{u2} β) (Option.map.{u1, u2} γ β (Function.comp.{succ u1, succ u3, succ u2} γ α β h g) x) (Option.map.{u3, u2} α β h (Option.map.{u1, u3} γ α g x))\nCase conversion may be inaccurate. Consider using '#align option.comp_map Option.comp_mapₓ'. -/\ntheorem comp_map (h : β → γ) (g : α → β) (x : Option α) :\n Option.map (h ∘ g) x = Option.map h (Option.map g x) :=\n (map_map _ _ _).symm\n#align option.comp_map Option.comp_map\n\n/- warning: option.map_comp_map -> Option.map_comp_map is a dubious translation:\nlean 3 declaration is\n forall {α : Type.{u1}} {β : Type.{u2}} {γ : Type.{u3}} (f : α -> β) (g : β -> γ), Eq.{max (succ u1) (succ u3)} ((Option.{u1} α) -> (Option.{u3} γ)) (Function.comp.{succ u1, succ u2, succ u3} (Option.{u1} α) (Option.{u2} β) (Option.{u3} γ) (Option.map.{u2, u3} β γ g) (Option.map.{u1, u2} α β f)) (Option.map.{u1, u3} α γ (Function.comp.{succ u1, succ u2, succ u3} α β γ g f))\nbut is expected to have type\n forall {α : Type.{u3}} {β : Type.{u2}} {γ : Type.{u1}} (f : α -> β) (g : β -> γ), Eq.{max (succ u1) (succ u3)} ((Option.{u3} α) -> (Option.{u1} γ)) (Function.comp.{succ u3, succ u2, succ u1} (Option.{u3} α) (Option.{u2} β) (Option.{u1} γ) (Option.map.{u2, u1} β γ g) (Option.map.{u3, u2} α β f)) (Option.map.{u3, u1} α γ (Function.comp.{succ u3, succ u2, succ u1} α β γ g f))\nCase conversion may be inaccurate. Consider using '#align option.map_comp_map Option.map_comp_mapₓ'. -/\n@[simp]\ntheorem map_comp_map (f : α → β) (g : β → γ) : Option.map g ∘ Option.map f = Option.map (g ∘ f) :=\n by\n ext x\n rw [comp_map]\n#align option.map_comp_map Option.map_comp_map\n\n/- warning: option.mem_map_of_mem -> Option.mem_map_of_mem is a dubious translation:\nlean 3 declaration is\n forall {α : Type.{u1}} {β : Type.{u2}} {a : α} {x : Option.{u1} α} (g : α -> β), (Membership.Mem.{u1, u1} α (Option.{u1} α) (Option.hasMem.{u1} α) a x) -> (Membership.Mem.{u2, u2} β (Option.{u2} β) (Option.hasMem.{u2} β) (g a) (Option.map.{u1, u2} α β g x))\nbut is expected to have type\n forall {α : Type.{u2}} {β : Type.{u1}} {a : α} {x : Option.{u2} α} (g : α -> β), (Membership.mem.{u2, u2} α (Option.{u2} α) (Option.instMembershipOption.{u2} α) a x) -> (Membership.mem.{u1, u1} β (Option.{u1} β) (Option.instMembershipOption.{u1} β) (g a) (Option.map.{u2, u1} α β g x))\nCase conversion may be inaccurate. Consider using '#align option.mem_map_of_mem Option.mem_map_of_memₓ'. -/\ntheorem mem_map_of_mem {a : α} {x : Option α} (g : α → β) (h : a ∈ x) : g a ∈ x.map g :=\n mem_def.mpr ((mem_def.mp h).symm ▸ map_some')\n#align option.mem_map_of_mem Option.mem_map_of_mem\n\ntheorem mem_map {f : α → β} {y : β} {o : Option α} : y ∈ o.map f ↔ ∃ x ∈ o, f x = y := by simp\n#align option.mem_map Option.mem_map\n\ntheorem forall_mem_map {f : α → β} {o : Option α} {p : β → Prop} :\n (∀ y ∈ o.map f, p y) ↔ ∀ x ∈ o, p (f x) := by simp\n#align option.forall_mem_map Option.forall_mem_map\n\ntheorem exists_mem_map {f : α → β} {o : Option α} {p : β → Prop} :\n (∃ y ∈ o.map f, p y) ↔ ∃ x ∈ o, p (f x) := by simp\n#align option.exists_mem_map Option.exists_mem_map\n\n/- warning: option.bind_map_comm -> Option.bind_map_comm is a dubious translation:\nlean 3 declaration is\n forall {α : Type.{u_1}} {β : Type.{u_1}} {x : Option.{u_1} (Option.{u_1} α)} {f : α -> β}, Eq.{succ u_1} (Option.{u_1} β) (Bind.bind.{u_1, u_1} Option.{u_1} (Monad.toHasBind.{u_1, u_1} Option.{u_1} Option.monad.{u_1}) (Option.{u_1} α) β x (Option.map.{u_1, u_1} α β f)) (Bind.bind.{u_1, u_1} Option.{u_1} (Monad.toHasBind.{u_1, u_1} Option.{u_1} Option.monad.{u_1}) (Option.{u_1} β) β (Option.map.{u_1, u_1} (Option.{u_1} α) (Option.{u_1} β) (Option.map.{u_1, u_1} α β f) x) (id.{succ u_1} (Option.{u_1} β)))\nbut is expected to have type\n forall {α : Type.{u_1}} {β : Type.{u_2}} {x : Option.{u_1} (Option.{u_1} α)} {f : α -> β}, Eq.{succ u_2} (Option.{u_2} β) (Option.bind.{u_1, u_2} (Option.{u_1} α) β x (Option.map.{u_1, u_2} α β f)) (Option.bind.{u_2, u_2} (Option.{u_2} β) β (Option.map.{u_1, u_2} (Option.{u_1} α) (Option.{u_2} β) (Option.map.{u_1, u_2} α β f) x) (id.{succ u_2} (Option.{u_2} β)))\nCase conversion may be inaccurate. Consider using '#align option.bind_map_comm Option.bind_map_commₓ'. -/\ntheorem bind_map_comm {α β} {x : Option (Option α)} {f : α → β} :\n x >>= Option.map f = x.map (Option.map f) >>= id := by cases x <;> simp\n#align option.bind_map_comm Option.bind_map_comm\n\n/- warning: option.join_map_eq_map_join -> Option.join_map_eq_map_join is a dubious translation:\nlean 3 declaration is\n forall {α : Type.{u1}} {β : Type.{u2}} {f : α -> β} {x : Option.{u1} (Option.{u1} α)}, Eq.{succ u2} (Option.{u2} β) (Option.join.{u2} β (Option.map.{u1, u2} (Option.{u1} α) (Option.{u2} β) (Option.map.{u1, u2} α β f) x)) (Option.map.{u1, u2} α β f (Option.join.{u1} α x))\nbut is expected to have type\n forall {α : Type.{u2}} {β : Type.{u1}} {f : α -> β} {x : Option.{u2} (Option.{u2} α)}, Eq.{succ u1} (Option.{u1} β) (Option.join.{u1} β (Option.map.{u2, u1} (Option.{u2} α) (Option.{u1} β) (Option.map.{u2, u1} α β f) x)) (Option.map.{u2, u1} α β f (Option.join.{u2} α x))\nCase conversion may be inaccurate. Consider using '#align option.join_map_eq_map_join Option.join_map_eq_map_joinₓ'. -/\ntheorem join_map_eq_map_join {f : α → β} {x : Option (Option α)} :\n (x.map (Option.map f)).join = x.join.map f := by rcases x with (_ | _ | x) <;> simp\n#align option.join_map_eq_map_join Option.join_map_eq_map_join\n\n#print Option.join_join /-\ntheorem join_join {x : Option (Option (Option α))} : x.join.join = (x.map join).join := by\n rcases x with (_ | _ | _ | x) <;> simp\n#align option.join_join Option.join_join\n-/\n\n#print Option.mem_of_mem_join /-\ntheorem mem_of_mem_join {a : α} {x : Option (Option α)} (h : a ∈ x.join) : some a ∈ x :=\n mem_def.mpr ((mem_def.mp h).symm ▸ join_eq_some.mp h)\n#align option.mem_of_mem_join Option.mem_of_mem_join\n-/\n\nsection Pmap\n\nvariable {p : α → Prop} (f : ∀ a : α, p a → β) (x : Option α)\n\n#print Option.pbind_eq_bind /-\n@[simp]\ntheorem pbind_eq_bind (f : α → Option β) (x : Option α) : (x.pbind fun a _ => f a) = x.bind f := by\n cases x <;> simp only [pbind, none_bind', some_bind']\n#align option.pbind_eq_bind Option.pbind_eq_bind\n-/\n\n/- warning: option.map_bind -> Option.map_bind is a dubious translation:\nlean 3 declaration is\n forall {α : Type.{u1}} {β : Type.{u1}} {γ : Type.{u1}} (f : β -> γ) (x : Option.{u1} α) (g : α -> (Option.{u1} β)), Eq.{succ u1} (Option.{u1} γ) (Option.map.{u1, u1} β γ f (Bind.bind.{u1, u1} Option.{u1} (Monad.toHasBind.{u1, u1} Option.{u1} Option.monad.{u1}) α β x g)) (Bind.bind.{u1, u1} Option.{u1} (Monad.toHasBind.{u1, u1} Option.{u1} Option.monad.{u1}) α γ x (fun (a : α) => Option.map.{u1, u1} β γ f (g a)))\nbut is expected to have type\n forall {α : Type.{u1}} {β : Type.{u1}} {γ : Type.{u1}} (f : β -> γ) (x : Option.{u1} α) (g : α -> (Option.{u1} β)), Eq.{succ u1} (Option.{u1} γ) (Option.map.{u1, u1} β γ f (Bind.bind.{u1, u1} Option.{u1} (Monad.toBind.{u1, u1} Option.{u1} instMonadOption.{u1}) α β x g)) (Bind.bind.{u1, u1} Option.{u1} (Monad.toBind.{u1, u1} Option.{u1} instMonadOption.{u1}) α γ x (fun (a : α) => Option.map.{u1, u1} β γ f (g a)))\nCase conversion may be inaccurate. Consider using '#align option.map_bind Option.map_bindₓ'. -/\ntheorem map_bind {α β γ} (f : β → γ) (x : Option α) (g : α → Option β) :\n Option.map f (x >>= g) = x >>= fun a => Option.map f (g a) := by\n simp_rw [← map_eq_map, ← bind_pure_comp_eq_map, LawfulMonad.bind_assoc]\n#align option.map_bind Option.map_bind\n\n/- warning: option.map_bind' -> Option.map_bind' is a dubious translation:\nlean 3 declaration is\n forall {α : Type.{u1}} {β : Type.{u2}} {γ : Type.{u3}} (f : β -> γ) (x : Option.{u1} α) (g : α -> (Option.{u2} β)), Eq.{succ u3} (Option.{u3} γ) (Option.map.{u2, u3} β γ f (Option.bind.{u1, u2} α β x g)) (Option.bind.{u1, u3} α γ x (fun (a : α) => Option.map.{u2, u3} β γ f (g a)))\nbut is expected to have type\n forall {α : Type.{u3}} {β : Type.{u2}} {γ : Type.{u1}} (f : β -> γ) (x : Option.{u3} α) (g : α -> (Option.{u2} β)), Eq.{succ u1} (Option.{u1} γ) (Option.map.{u2, u1} β γ f (Option.bind.{u3, u2} α β x g)) (Option.bind.{u3, u1} α γ x (fun (a : α) => Option.map.{u2, u1} β γ f (g a)))\nCase conversion may be inaccurate. Consider using '#align option.map_bind' Option.map_bind'ₓ'. -/\ntheorem map_bind' (f : β → γ) (x : Option α) (g : α → Option β) :\n Option.map f (x.bind g) = x.bind fun a => Option.map f (g a) := by cases x <;> simp\n#align option.map_bind' Option.map_bind'\n\n/- warning: option.map_pbind -> Option.map_pbind is a dubious translation:\nlean 3 declaration is\n forall {α : Type.{u1}} {β : Type.{u2}} {γ : Type.{u3}} (f : β -> γ) (x : Option.{u1} α) (g : forall (a : α), (Membership.Mem.{u1, u1} α (Option.{u1} α) (Option.hasMem.{u1} α) a x) -> (Option.{u2} β)), Eq.{succ u3} (Option.{u3} γ) (Option.map.{u2, u3} β γ f (Option.pbind.{u1, u2} α β x g)) (Option.pbind.{u1, u3} α γ x (fun (a : α) (H : Membership.Mem.{u1, u1} α (Option.{u1} α) (Option.hasMem.{u1} α) a x) => Option.map.{u2, u3} β γ f (g a H)))\nbut is expected to have type\n forall {α : Type.{u3}} {β : Type.{u2}} {γ : Type.{u1}} (f : β -> γ) (x : Option.{u3} α) (g : forall (a : α), (Membership.mem.{u3, u3} α (Option.{u3} α) (Option.instMembershipOption.{u3} α) a x) -> (Option.{u2} β)), Eq.{succ u1} (Option.{u1} γ) (Option.map.{u2, u1} β γ f (Option.pbind.{u3, u2} α β x g)) (Option.pbind.{u3, u1} α γ x (fun (a : α) (H : Membership.mem.{u3, u3} α (Option.{u3} α) (Option.instMembershipOption.{u3} α) a x) => Option.map.{u2, u1} β γ f (g a H)))\nCase conversion may be inaccurate. Consider using '#align option.map_pbind Option.map_pbindₓ'. -/\ntheorem map_pbind (f : β → γ) (x : Option α) (g : ∀ a, a ∈ x → Option β) :\n Option.map f (x.pbind g) = x.pbind fun a H => Option.map f (g a H) := by\n cases x <;> simp only [pbind, map_none']\n#align option.map_pbind Option.map_pbind\n\n/- warning: option.pbind_map -> Option.pbind_map is a dubious translation:\nlean 3 declaration is\n forall {α : Type.{u1}} {β : Type.{u2}} {γ : Type.{u3}} (f : α -> β) (x : Option.{u1} α) (g : forall (b : β), (Membership.Mem.{u2, u2} β (Option.{u2} β) (Option.hasMem.{u2} β) b (Option.map.{u1, u2} α β f x)) -> (Option.{u3} γ)), Eq.{succ u3} (Option.{u3} γ) (Option.pbind.{u2, u3} β γ (Option.map.{u1, u2} α β f x) g) (Option.pbind.{u1, u3} α γ x (fun (a : α) (h : Membership.Mem.{u1, u1} α (Option.{u1} α) (Option.hasMem.{u1} α) a x) => g (f a) (Option.mem_map_of_mem.{u1, u2} α β a x f h)))\nbut is expected to have type\n forall {α : Type.{u3}} {β : Type.{u2}} {γ : Type.{u1}} (f : α -> β) (x : Option.{u3} α) (g : forall (b : β), (Membership.mem.{u2, u2} β (Option.{u2} β) (Option.instMembershipOption.{u2} β) b (Option.map.{u3, u2} α β f x)) -> (Option.{u1} γ)), Eq.{succ u1} (Option.{u1} γ) (Option.pbind.{u2, u1} β γ (Option.map.{u3, u2} α β f x) g) (Option.pbind.{u3, u1} α γ x (fun (a : α) (h : Membership.mem.{u3, u3} α (Option.{u3} α) (Option.instMembershipOption.{u3} α) a x) => g (f a) (Option.mem_map_of_mem.{u2, u3} α β a x f h)))\nCase conversion may be inaccurate. Consider using '#align option.pbind_map Option.pbind_mapₓ'. -/\ntheorem pbind_map (f : α → β) (x : Option α) (g : ∀ b : β, b ∈ x.map f → Option γ) :\n pbind (Option.map f x) g = x.pbind fun a h => g (f a) (mem_map_of_mem _ h) := by cases x <;> rfl\n#align option.pbind_map Option.pbind_map\n\n/- warning: option.pmap_none -> Option.pmap_none is a dubious translation:\nlean 3 declaration is\n forall {α : Type.{u1}} {β : Type.{u2}} {p : α -> Prop} (f : forall (a : α), (p a) -> β) {H : forall (a : α), (Membership.Mem.{u1, u1} α (Option.{u1} α) (Option.hasMem.{u1} α) a (Option.none.{u1} α)) -> (p a)}, Eq.{succ u2} (Option.{u2} β) (Option.pmap.{u1, u2} α β (fun (a : α) => p a) f (Option.none.{u1} α) H) (Option.none.{u2} β)\nbut is expected to have type\n forall {α : Type.{u2}} {β : Type.{u1}} {p : α -> Prop} (f : forall (a : α), (p a) -> β) {H : forall (a : α), (Membership.mem.{u2, u2} α (Option.{u2} α) (Option.instMembershipOption.{u2} α) a (Option.none.{u2} α)) -> (p a)}, Eq.{succ u1} (Option.{u1} β) (Option.pmap.{u2, u1} α β (fun (a : α) => p a) f (Option.none.{u2} α) H) (Option.none.{u1} β)\nCase conversion may be inaccurate. Consider using '#align option.pmap_none Option.pmap_noneₓ'. -/\n@[simp]\ntheorem pmap_none (f : ∀ a : α, p a → β) {H} : pmap f (@none α) H = none :=\n rfl\n#align option.pmap_none Option.pmap_none\n\n#print Option.pmap_some /-\n@[simp]\ntheorem pmap_some (f : ∀ a : α, p a → β) {x : α} (h : p x) :\n pmap f (some x) = fun _ => some (f x h) :=\n rfl\n#align option.pmap_some Option.pmap_some\n-/\n\n/- warning: option.mem_pmem -> Option.mem_pmem is a dubious translation:\nlean 3 declaration is\n forall {α : Type.{u1}} {β : Type.{u2}} {p : α -> Prop} (f : forall (a : α), (p a) -> β) (x : Option.{u1} α) {a : α} (h : forall (a : α), (Membership.Mem.{u1, u1} α (Option.{u1} α) (Option.hasMem.{u1} α) a x) -> (p a)) (ha : Membership.Mem.{u1, u1} α (Option.{u1} α) (Option.hasMem.{u1} α) a x), Membership.Mem.{u2, u2} β (Option.{u2} β) (Option.hasMem.{u2} β) (f a (h a ha)) (Option.pmap.{u1, u2} α β (fun (a : α) => p a) f x h)\nbut is expected to have type\n forall {α : Type.{u2}} {β : Type.{u1}} {p : α -> Prop} (f : forall (a : α), (p a) -> β) (x : Option.{u2} α) {a : α} (h : forall (a : α), (Membership.mem.{u2, u2} α (Option.{u2} α) (Option.instMembershipOption.{u2} α) a x) -> (p a)) (ha : Membership.mem.{u2, u2} α (Option.{u2} α) (Option.instMembershipOption.{u2} α) a x), Membership.mem.{u1, u1} β (Option.{u1} β) (Option.instMembershipOption.{u1} β) (f a (h a ha)) (Option.pmap.{u2, u1} α β (fun (a : α) => p a) f x h)\nCase conversion may be inaccurate. Consider using '#align option.mem_pmem Option.mem_pmemₓ'. -/\ntheorem mem_pmem {a : α} (h : ∀ a ∈ x, p a) (ha : a ∈ x) : f a (h a ha) ∈ pmap f x h :=\n by\n rw [mem_def] at ha⊢\n subst ha\n rfl\n#align option.mem_pmem Option.mem_pmem\n\n/- warning: option.pmap_map -> Option.pmap_map is a dubious translation:\nlean 3 declaration is\n forall {α : Type.{u1}} {β : Type.{u2}} {γ : Type.{u3}} {p : α -> Prop} (f : forall (a : α), (p a) -> β) (g : γ -> α) (x : Option.{u3} γ) (H : forall (a : α), (Membership.Mem.{u1, u1} α (Option.{u1} α) (Option.hasMem.{u1} α) a (Option.map.{u3, u1} γ α g x)) -> (p a)), Eq.{succ u2} (Option.{u2} β) (Option.pmap.{u1, u2} α β (fun (a : α) => p a) f (Option.map.{u3, u1} γ α g x) H) (Option.pmap.{u3, u2} γ β (fun (a : γ) => p (g a)) (fun (a : γ) (h : p (g a)) => f (g a) h) x (fun (a : γ) (h : Membership.Mem.{u3, u3} γ (Option.{u3} γ) (Option.hasMem.{u3} γ) a x) => H (g a) (Option.mem_map_of_mem.{u3, u1} γ α a x g h)))\nbut is expected to have type\n forall {α : Type.{u2}} {β : Type.{u1}} {γ : Type.{u3}} {p : α -> Prop} (f : forall (a : α), (p a) -> β) (g : γ -> α) (x : Option.{u3} γ) (H : forall (a : α), (Membership.mem.{u2, u2} α (Option.{u2} α) (Option.instMembershipOption.{u2} α) a (Option.map.{u3, u2} γ α g x)) -> (p a)), Eq.{succ u1} (Option.{u1} β) (Option.pmap.{u2, u1} α β (fun (a : α) => p a) f (Option.map.{u3, u2} γ α g x) H) (Option.pmap.{u3, u1} γ β (fun (a : γ) => p (g a)) (fun (a : γ) (h : p (g a)) => f (g a) h) x (fun (a : γ) (h : Membership.mem.{u3, u3} γ (Option.{u3} γ) (Option.instMembershipOption.{u3} γ) a x) => H (g a) (Option.mem_map_of_mem.{u2, u3} γ α a x g h)))\nCase conversion may be inaccurate. Consider using '#align option.pmap_map Option.pmap_mapₓ'. -/\ntheorem pmap_map (g : γ → α) (x : Option γ) (H) :\n pmap f (x.map g) H = pmap (fun a h => f (g a) h) x fun a h => H _ (mem_map_of_mem _ h) := by\n cases x <;> simp only [map_none', map_some', pmap]\n#align option.pmap_map Option.pmap_map\n\n/- warning: option.map_pmap -> Option.map_pmap is a dubious translation:\nlean 3 declaration is\n forall {α : Type.{u1}} {β : Type.{u2}} {γ : Type.{u3}} {p : α -> Prop} (g : β -> γ) (f : forall (a : α), (p a) -> β) (x : Option.{u1} α) (H : forall (a : α), (Membership.Mem.{u1, u1} α (Option.{u1} α) (Option.hasMem.{u1} α) a x) -> (p a)), Eq.{succ u3} (Option.{u3} γ) (Option.map.{u2, u3} β γ g (Option.pmap.{u1, u2} α β (fun (a : α) => p a) f x H)) (Option.pmap.{u1, u3} α γ (fun (a : α) => p a) (fun (a : α) (h : p a) => g (f a h)) x H)\nbut is expected to have type\n forall {α : Type.{u3}} {β : Type.{u1}} {γ : Type.{u2}} {p : α -> Prop} (g : β -> γ) (f : forall (a : α), (p a) -> β) (x : Option.{u3} α) (H : forall (a : α), (Membership.mem.{u3, u3} α (Option.{u3} α) (Option.instMembershipOption.{u3} α) a x) -> (p a)), Eq.{succ u2} (Option.{u2} γ) (Option.map.{u1, u2} β γ g (Option.pmap.{u3, u1} α β (fun (a : α) => p a) f x H)) (Option.pmap.{u3, u2} α γ (fun (a : α) => p a) (fun (a : α) (h : p a) => g (f a h)) x H)\nCase conversion may be inaccurate. Consider using '#align option.map_pmap Option.map_pmapₓ'. -/\ntheorem map_pmap (g : β → γ) (f : ∀ a, p a → β) (x H) :\n Option.map g (pmap f x H) = pmap (fun a h => g (f a h)) x H := by\n cases x <;> simp only [map_none', map_some', pmap]\n#align option.map_pmap Option.map_pmap\n\n/- warning: option.pmap_eq_map -> Option.pmap_eq_map is a dubious translation:\nlean 3 declaration is\n forall {α : Type.{u1}} {β : Type.{u2}} (p : α -> Prop) (f : α -> β) (x : Option.{u1} α) (H : forall (a : α), (Membership.Mem.{u1, u1} α (Option.{u1} α) (Option.hasMem.{u1} α) a x) -> (p a)), Eq.{succ u2} (Option.{u2} β) (Option.pmap.{u1, u2} α β p (fun (a : α) (_x : p a) => f a) x H) (Option.map.{u1, u2} α β f x)\nbut is expected to have type\n forall {α : Type.{u2}} {β : Type.{u1}} (p : α -> Prop) (f : α -> β) (x : Option.{u2} α) (H : forall (a : α), (Membership.mem.{u2, u2} α (Option.{u2} α) (Option.instMembershipOption.{u2} α) a x) -> (p a)), Eq.{succ u1} (Option.{u1} β) (Option.pmap.{u2, u1} α β p (fun (a : α) (_x : p a) => f a) x H) (Option.map.{u2, u1} α β f x)\nCase conversion may be inaccurate. Consider using '#align option.pmap_eq_map Option.pmap_eq_mapₓ'. -/\n@[simp]\ntheorem pmap_eq_map (p : α → Prop) (f : α → β) (x H) :\n @pmap _ _ p (fun a _ => f a) x H = Option.map f x := by\n cases x <;> simp only [map_none', map_some', pmap]\n#align option.pmap_eq_map Option.pmap_eq_map\n\n/- warning: option.pmap_bind -> Option.pmap_bind is a dubious translation:\nlean 3 declaration is\n forall {α : Type.{u1}} {β : Type.{u1}} {γ : Type.{u1}} {x : Option.{u1} α} {g : α -> (Option.{u1} β)} {p : β -> Prop} {f : forall (b : β), (p b) -> γ} (H : forall (a : β), (Membership.Mem.{u1, u1} β (Option.{u1} β) (Option.hasMem.{u1} β) a (Bind.bind.{u1, u1} Option.{u1} (Monad.toHasBind.{u1, u1} Option.{u1} Option.monad.{u1}) α β x g)) -> (p a)) (H' : forall (a : α) (b : β), (Membership.Mem.{u1, u1} β (Option.{u1} β) (Option.hasMem.{u1} β) b (g a)) -> (Membership.Mem.{u1, u1} β (Option.{u1} β) (Option.hasMem.{u1} β) b (Bind.bind.{u1, u1} Option.{u1} (Monad.toHasBind.{u1, u1} Option.{u1} Option.monad.{u1}) α β x g))), Eq.{succ u1} (Option.{u1} γ) (Option.pmap.{u1, u1} β γ (fun (b : β) => p b) f (Bind.bind.{u1, u1} Option.{u1} (Monad.toHasBind.{u1, u1} Option.{u1} Option.monad.{u1}) α β x g) H) (Bind.bind.{u1, u1} Option.{u1} (Monad.toHasBind.{u1, u1} Option.{u1} Option.monad.{u1}) α γ x (fun (a : α) => Option.pmap.{u1, u1} β γ (fun (b : β) => p b) f (g a) (fun (b : β) (h : Membership.Mem.{u1, u1} β (Option.{u1} β) (Option.hasMem.{u1} β) b (g a)) => H b (H' a b h))))\nbut is expected to have type\n forall {α : Type.{u1}} {β : Type.{u1}} {γ : Type.{u1}} {x : Option.{u1} α} {g : α -> (Option.{u1} β)} {p : β -> Prop} {f : forall (b : β), (p b) -> γ} (H : forall (a : β), (Membership.mem.{u1, u1} β (Option.{u1} β) (Option.instMembershipOption.{u1} β) a (Bind.bind.{u1, u1} Option.{u1} (Monad.toBind.{u1, u1} Option.{u1} instMonadOption.{u1}) α β x g)) -> (p a)) (H' : forall (a : α) (b : β), (Membership.mem.{u1, u1} β (Option.{u1} β) (Option.instMembershipOption.{u1} β) b (g a)) -> (Membership.mem.{u1, u1} β (Option.{u1} β) (Option.instMembershipOption.{u1} β) b (Bind.bind.{u1, u1} Option.{u1} (Monad.toBind.{u1, u1} Option.{u1} instMonadOption.{u1}) α β x g))), Eq.{succ u1} (Option.{u1} γ) (Option.pmap.{u1, u1} β γ (fun (b : β) => p b) f (Bind.bind.{u1, u1} Option.{u1} (Monad.toBind.{u1, u1} Option.{u1} instMonadOption.{u1}) α β x g) H) (Bind.bind.{u1, u1} Option.{u1} (Monad.toBind.{u1, u1} Option.{u1} instMonadOption.{u1}) α γ x (fun (a : α) => Option.pmap.{u1, u1} β γ (fun (b : β) => p b) f (g a) (fun (b : β) (h : Membership.mem.{u1, u1} β (Option.{u1} β) (Option.instMembershipOption.{u1} β) b (g a)) => H b (H' a b h))))\nCase conversion may be inaccurate. Consider using '#align option.pmap_bind Option.pmap_bindₓ'. -/\ntheorem pmap_bind {α β γ} {x : Option α} {g : α → Option β} {p : β → Prop} {f : ∀ b, p b → γ} (H)\n (H' : ∀ (a : α), ∀ b ∈ g a, b ∈ x >>= g) :\n pmap f (x >>= g) H = x >>= fun a => pmap f (g a) fun b h => H _ (H' a _ h) := by\n cases x <;> simp only [pmap, none_bind, some_bind]\n#align option.pmap_bind Option.pmap_bind\n\n/- warning: option.bind_pmap -> Option.bind_pmap is a dubious translation:\nlean 3 declaration is\n forall {α : Type.{u1}} {β : Type.{u2}} {γ : Type.{u2}} {p : α -> Prop} (f : forall (a : α), (p a) -> β) (x : Option.{u1} α) (g : β -> (Option.{u2} γ)) (H : forall (a : α), (Membership.Mem.{u1, u1} α (Option.{u1} α) (Option.hasMem.{u1} α) a x) -> (p a)), Eq.{succ u2} (Option.{u2} γ) (Bind.bind.{u2, u2} Option.{u2} (Monad.toHasBind.{u2, u2} Option.{u2} Option.monad.{u2}) β γ (Option.pmap.{u1, u2} α β (fun (a : α) => p a) f x H) g) (Option.pbind.{u1, u2} α γ x (fun (a : α) (h : Membership.Mem.{u1, u1} α (Option.{u1} α) (Option.hasMem.{u1} α) a x) => g (f a (H a h))))\nbut is expected to have type\n forall {α : Type.{u2}} {β : Type.{u1}} {γ : Type.{u1}} {p : α -> Prop} (f : forall (a : α), (p a) -> β) (x : Option.{u2} α) (g : β -> (Option.{u1} γ)) (H : forall (a : α), (Membership.mem.{u2, u2} α (Option.{u2} α) (Option.instMembershipOption.{u2} α) a x) -> (p a)), Eq.{succ u1} (Option.{u1} γ) (Bind.bind.{u1, u1} Option.{u1} (Monad.toBind.{u1, u1} Option.{u1} instMonadOption.{u1}) β γ (Option.pmap.{u2, u1} α β (fun (a : α) => p a) f x H) g) (Option.pbind.{u2, u1} α γ x (fun (a : α) (h : Membership.mem.{u2, u2} α (Option.{u2} α) (Option.instMembershipOption.{u2} α) a x) => g (f a (H a h))))\nCase conversion may be inaccurate. Consider using '#align option.bind_pmap Option.bind_pmapₓ'. -/\ntheorem bind_pmap {α β γ} {p : α → Prop} (f : ∀ a, p a → β) (x : Option α) (g : β → Option γ) (H) :\n pmap f x H >>= g = x.pbind fun a h => g (f a (H _ h)) := by\n cases x <;> simp only [pmap, none_bind, some_bind, pbind]\n#align option.bind_pmap Option.bind_pmap\n\nvariable {f x}\n\n/- warning: option.pbind_eq_none -> Option.pbind_eq_none is a dubious translation:\nlean 3 declaration is\n forall {α : Type.{u1}} {β : Type.{u2}} {x : Option.{u1} α} {f : forall (a : α), (Membership.Mem.{u1, u1} α (Option.{u1} α) (Option.hasMem.{u1} α) a x) -> (Option.{u2} β)}, (forall (a : α) (H : Membership.Mem.{u1, u1} α (Option.{u1} α) (Option.hasMem.{u1} α) a x), (Eq.{succ u2} (Option.{u2} β) (f a H) (Option.none.{u2} β)) -> (Eq.{succ u1} (Option.{u1} α) x (Option.none.{u1} α))) -> (Iff (Eq.{succ u2} (Option.{u2} β) (Option.pbind.{u1, u2} α β x f) (Option.none.{u2} β)) (Eq.{succ u1} (Option.{u1} α) x (Option.none.{u1} α)))\nbut is expected to have type\n forall {α : Type.{u2}} {β : Type.{u1}} {x : Option.{u2} α} {f : forall (a : α), (Membership.mem.{u2, u2} α (Option.{u2} α) (Option.instMembershipOption.{u2} α) a x) -> (Option.{u1} β)}, (forall (a : α) (H : Membership.mem.{u2, u2} α (Option.{u2} α) (Option.instMembershipOption.{u2} α) a x), (Eq.{succ u1} (Option.{u1} β) (f a H) (Option.none.{u1} β)) -> (Eq.{succ u2} (Option.{u2} α) x (Option.none.{u2} α))) -> (Iff (Eq.{succ u1} (Option.{u1} β) (Option.pbind.{u2, u1} α β x f) (Option.none.{u1} β)) (Eq.{succ u2} (Option.{u2} α) x (Option.none.{u2} α)))\nCase conversion may be inaccurate. Consider using '#align option.pbind_eq_none Option.pbind_eq_noneₓ'. -/\ntheorem pbind_eq_none {f : ∀ a : α, a ∈ x → Option β} (h' : ∀ a ∈ x, f a H = none → x = none) :\n x.pbind f = none ↔ x = none := by\n cases x\n · simp\n · simp only [pbind, iff_false_iff]\n intro h\n cases h' x rfl h\n#align option.pbind_eq_none Option.pbind_eq_none\n\n/- warning: option.pbind_eq_some -> Option.pbind_eq_some is a dubious translation:\nlean 3 declaration is\n forall {α : Type.{u1}} {β : Type.{u2}} {x : Option.{u1} α} {f : forall (a : α), (Membership.Mem.{u1, u1} α (Option.{u1} α) (Option.hasMem.{u1} α) a x) -> (Option.{u2} β)} {y : β}, Iff (Eq.{succ u2} (Option.{u2} β) (Option.pbind.{u1, u2} α β x f) (Option.some.{u2} β y)) (Exists.{succ u1} α (fun (z : α) => Exists.{0} (Membership.Mem.{u1, u1} α (Option.{u1} α) (Option.hasMem.{u1} α) z x) (fun (H : Membership.Mem.{u1, u1} α (Option.{u1} α) (Option.hasMem.{u1} α) z x) => Eq.{succ u2} (Option.{u2} β) (f z H) (Option.some.{u2} β y))))\nbut is expected to have type\n forall {α : Type.{u2}} {β : Type.{u1}} {x : Option.{u2} α} {f : forall (a : α), (Membership.mem.{u2, u2} α (Option.{u2} α) (Option.instMembershipOption.{u2} α) a x) -> (Option.{u1} β)} {y : β}, Iff (Eq.{succ u1} (Option.{u1} β) (Option.pbind.{u2, u1} α β x f) (Option.some.{u1} β y)) (Exists.{succ u2} α (fun (z : α) => Exists.{0} (Membership.mem.{u2, u2} α (Option.{u2} α) (Option.instMembershipOption.{u2} α) z x) (fun (H : Membership.mem.{u2, u2} α (Option.{u2} α) (Option.instMembershipOption.{u2} α) z x) => Eq.{succ u1} (Option.{u1} β) (f z H) (Option.some.{u1} β y))))\nCase conversion may be inaccurate. Consider using '#align option.pbind_eq_some Option.pbind_eq_someₓ'. -/\ntheorem pbind_eq_some {f : ∀ a : α, a ∈ x → Option β} {y : β} :\n x.pbind f = some y ↔ ∃ z ∈ x, f z H = some y :=\n by\n cases x\n · simp\n · simp only [pbind]\n constructor\n · intro h\n use x\n simpa only [mem_def, exists_prop_of_true] using h\n · rintro ⟨z, H, hz⟩\n simp only [mem_def] at H\n simpa only [H] using hz\n#align option.pbind_eq_some Option.pbind_eq_some\n\n/- warning: option.pmap_eq_none_iff -> Option.pmap_eq_none_iff is a dubious translation:\nlean 3 declaration is\n forall {α : Type.{u1}} {β : Type.{u2}} {p : α -> Prop} {f : forall (a : α), (p a) -> β} {x : Option.{u1} α} {h : forall (a : α), (Membership.Mem.{u1, u1} α (Option.{u1} α) (Option.hasMem.{u1} α) a x) -> (p a)}, Iff (Eq.{succ u2} (Option.{u2} β) (Option.pmap.{u1, u2} α β (fun (a : α) => p a) f x h) (Option.none.{u2} β)) (Eq.{succ u1} (Option.{u1} α) x (Option.none.{u1} α))\nbut is expected to have type\n forall {α : Type.{u2}} {β : Type.{u1}} {p : α -> Prop} {f : forall (a : α), (p a) -> β} {x : Option.{u2} α} {h : forall (a : α), (Membership.mem.{u2, u2} α (Option.{u2} α) (Option.instMembershipOption.{u2} α) a x) -> (p a)}, Iff (Eq.{succ u1} (Option.{u1} β) (Option.pmap.{u2, u1} α β (fun (a : α) => p a) f x h) (Option.none.{u1} β)) (Eq.{succ u2} (Option.{u2} α) x (Option.none.{u2} α))\nCase conversion may be inaccurate. Consider using '#align option.pmap_eq_none_iff Option.pmap_eq_none_iffₓ'. -/\n@[simp]\ntheorem pmap_eq_none_iff {h} : pmap f x h = none ↔ x = none := by cases x <;> simp\n#align option.pmap_eq_none_iff Option.pmap_eq_none_iff\n\n/- warning: option.pmap_eq_some_iff -> Option.pmap_eq_some_iff is a dubious translation:\nlean 3 declaration is\n forall {α : Type.{u1}} {β : Type.{u2}} {p : α -> Prop} {f : forall (a : α), (p a) -> β} {x : Option.{u1} α} {hf : forall (a : α), (Membership.Mem.{u1, u1} α (Option.{u1} α) (Option.hasMem.{u1} α) a x) -> (p a)} {y : β}, Iff (Eq.{succ u2} (Option.{u2} β) (Option.pmap.{u1, u2} α β (fun (a : α) => p a) f x hf) (Option.some.{u2} β y)) (Exists.{succ u1} α (fun (a : α) => Exists.{0} (Eq.{succ u1} (Option.{u1} α) x (Option.some.{u1} α a)) (fun (H : Eq.{succ u1} (Option.{u1} α) x (Option.some.{u1} α a)) => Eq.{succ u2} β (f a (hf a H)) y)))\nbut is expected to have type\n forall {α : Type.{u2}} {β : Type.{u1}} {p : α -> Prop} {f : forall (a : α), (p a) -> β} {x : Option.{u2} α} {hf : forall (a : α), (Membership.mem.{u2, u2} α (Option.{u2} α) (Option.instMembershipOption.{u2} α) a x) -> (p a)} {y : β}, Iff (Eq.{succ u1} (Option.{u1} β) (Option.pmap.{u2, u1} α β (fun (a : α) => p a) f x hf) (Option.some.{u1} β y)) (Exists.{succ u2} α (fun (a : α) => Exists.{0} (Eq.{succ u2} (Option.{u2} α) x (Option.some.{u2} α a)) (fun (H : Eq.{succ u2} (Option.{u2} α) x (Option.some.{u2} α a)) => Eq.{succ u1} β (f a (hf a H)) y)))\nCase conversion may be inaccurate. Consider using '#align option.pmap_eq_some_iff Option.pmap_eq_some_iffₓ'. -/\n@[simp]\ntheorem pmap_eq_some_iff {hf} {y : β} :\n pmap f x hf = some y ↔ ∃ (a : α)(H : x = some a), f a (hf a H) = y :=\n by\n cases x\n · simp only [not_mem_none, exists_false, pmap, not_false_iff, exists_prop_of_false]\n · constructor\n · intro h\n simp only [pmap] at h\n exact ⟨x, rfl, h⟩\n · rintro ⟨a, H, rfl⟩\n simp only [mem_def] at H\n simp only [H, pmap]\n#align option.pmap_eq_some_iff Option.pmap_eq_some_iff\n\n/- warning: option.join_pmap_eq_pmap_join -> Option.join_pmap_eq_pmap_join is a dubious translation:\nlean 3 declaration is\n forall {α : Type.{u1}} {β : Type.{u2}} {p : α -> Prop} {f : forall (a : α), (p a) -> β} {x : Option.{u1} (Option.{u1} α)} (H : forall (a : Option.{u1} α), (Membership.Mem.{u1, u1} (Option.{u1} α) (Option.{u1} (Option.{u1} α)) (Option.hasMem.{u1} (Option.{u1} α)) a x) -> (forall (a_1 : α), (Membership.Mem.{u1, u1} α (Option.{u1} α) (Option.hasMem.{u1} α) a_1 a) -> (p a_1))), Eq.{succ u2} (Option.{u2} β) (Option.join.{u2} β (Option.pmap.{u1, u2} (Option.{u1} α) (Option.{u2} β) (fun (a : Option.{u1} α) => forall (a_1 : α), (Membership.Mem.{u1, u1} α (Option.{u1} α) (Option.hasMem.{u1} α) a_1 a) -> (p a_1)) (Option.pmap.{u1, u2} α β (fun (a : α) => p a) f) x H)) (Option.pmap.{u1, u2} α β (fun (a : α) => p a) f (Option.join.{u1} α x) (fun (a : α) (h : Membership.Mem.{u1, u1} α (Option.{u1} α) (Option.hasMem.{u1} α) a (Option.join.{u1} α x)) => H (Option.some.{u1} α a) (Option.mem_of_mem_join.{u1} α a x h) a (rfl.{succ u1} (Option.{u1} α) (Option.some.{u1} α a))))\nbut is expected to have type\n forall {α : Type.{u2}} {β : Type.{u1}} {p : α -> Prop} {f : forall (a : α), (p a) -> β} {x : Option.{u2} (Option.{u2} α)} (H : forall (a : Option.{u2} α), (Membership.mem.{u2, u2} (Option.{u2} α) (Option.{u2} (Option.{u2} α)) (Option.instMembershipOption.{u2} (Option.{u2} α)) a x) -> (forall (a_1 : α), (Membership.mem.{u2, u2} α (Option.{u2} α) (Option.instMembershipOption.{u2} α) a_1 a) -> (p a_1))), Eq.{succ u1} (Option.{u1} β) (Option.join.{u1} β (Option.pmap.{u2, u1} (Option.{u2} α) (Option.{u1} β) (fun (a : Option.{u2} α) => forall (a_1 : α), (Membership.mem.{u2, u2} α (Option.{u2} α) (Option.instMembershipOption.{u2} α) a_1 a) -> (p a_1)) (Option.pmap.{u2, u1} α β (fun (a : α) => p a) f) x H)) (Option.pmap.{u2, u1} α β (fun (a : α) => p a) f (Option.join.{u2} α x) (fun (a : α) (h : Membership.mem.{u2, u2} α (Option.{u2} α) (Option.instMembershipOption.{u2} α) a (Option.join.{u2} α x)) => H (Option.some.{u2} α a) (Option.mem_of_mem_join.{u2} α a x h) a (rfl.{succ u2} (Option.{u2} α) (Option.some.{u2} α a))))\nCase conversion may be inaccurate. Consider using '#align option.join_pmap_eq_pmap_join Option.join_pmap_eq_pmap_joinₓ'. -/\n@[simp]\ntheorem join_pmap_eq_pmap_join {f : ∀ a, p a → β} {x : Option (Option α)} (H) :\n (pmap (pmap f) x H).join = pmap f x.join fun a h => H (some a) (mem_of_mem_join h) _ rfl := by\n rcases x with (_ | _ | x) <;> simp\n#align option.join_pmap_eq_pmap_join Option.join_pmap_eq_pmap_join\n\nend Pmap\n\n/- warning: option.seq_some -> Option.seq_some is a dubious translation:\nlean 3 declaration is\n forall {α : Type.{u1}} {β : Type.{u1}} {a : α} {f : α -> β}, Eq.{succ u1} (Option.{u1} β) (Seq.seq.{u1, u1} Option.{u1} (Applicative.toHasSeq.{u1, u1} Option.{u1} (Monad.toApplicative.{u1, u1} Option.{u1} Option.monad.{u1})) α β (Option.some.{u1} (α -> β) f) (Option.some.{u1} α a)) (Option.some.{u1} β (f a))\nbut is expected to have type\n forall {α : Type.{u1}} {β : Type.{u1}} {a : α} {f : α -> β}, Eq.{succ u1} (Option.{u1} β) (Seq.seq.{u1, u1} Option.{u1} (Applicative.toSeq.{u1, u1} Option.{u1} (Alternative.toApplicative.{u1, u1} Option.{u1} instAlternativeOption.{u1})) α β (Option.some.{u1} (α -> β) f) (fun (x._@.Mathlib.Data.Option.Basic._hyg.2260 : Unit) => Option.some.{u1} α a)) (Option.some.{u1} β (f a))\nCase conversion may be inaccurate. Consider using '#align option.seq_some Option.seq_someₓ'. -/\n@[simp]\ntheorem seq_some {α β} {a : α} {f : α → β} : some f <*> some a = some (f a) :=\n rfl\n#align option.seq_some Option.seq_some\n\n#print Option.some_orElse' /-\n@[simp]\ntheorem some_orElse' (a : α) (x : Option α) : (some a).orelse x = some a :=\n rfl\n#align option.some_orelse' Option.some_orElse'\n-/\n\n/- warning: option.some_orelse -> Option.some_orElse is a dubious translation:\nlean 3 declaration is\n forall {α : Type.{u1}} (a : α) (x : Option.{u1} α), Eq.{succ u1} (Option.{u1} α) (HasOrelse.orelse.{u1, u1} Option.{u1} (Alternative.toHasOrelse.{u1, u1} Option.{u1} Option.alternative.{u1}) α (Option.some.{u1} α a) x) (Option.some.{u1} α a)\nbut is expected to have type\n forall {α : Type.{u1}} (a : α) (x : Option.{u1} α), Eq.{succ u1} (Option.{u1} α) (HOrElse.hOrElse.{u1, u1, u1} (Option.{u1} α) (Option.{u1} α) (Option.{u1} α) (instHOrElse.{u1} (Option.{u1} α) (Option.instOrElseOption.{u1} α)) (Option.some.{u1} α a) (fun (x._@.Std.Data.Option.Lemmas._hyg.3089 : Unit) => x)) (Option.some.{u1} α a)\nCase conversion may be inaccurate. Consider using '#align option.some_orelse Option.some_orElseₓ'. -/\n@[simp]\ntheorem some_orElse (a : α) (x : Option α) : (some a <|> x) = some a :=\n rfl\n#align option.some_orelse Option.some_orElse\n\n/- warning: option.none_orelse' -> Option.none_orElse' is a dubious translation:\nlean 3 declaration is\n forall {α : Type.{u1}} (x : Option.{u1} α), Eq.{succ u1} (Option.{u1} α) (Option.orelse.{u1} α (Option.none.{u1} α) x) x\nbut is expected to have type\n forall {α : Type.{u1}} (x : Option.{u1} α), Eq.{succ u1} (Option.{u1} α) (Option.orElse.{u1} α (Option.none.{u1} α) (fun (x._@.Mathlib.Data.Option.Basic._hyg.2314 : Unit) => x)) x\nCase conversion may be inaccurate. Consider using '#align option.none_orelse' Option.none_orElse'ₓ'. -/\n@[simp]\ntheorem none_orElse' (x : Option α) : none.orelse x = x := by cases x <;> rfl\n#align option.none_orelse' Option.none_orElse'\n\n/- warning: option.none_orelse -> Option.none_orElse is a dubious translation:\nlean 3 declaration is\n forall {α : Type.{u1}} (x : Option.{u1} α), Eq.{succ u1} (Option.{u1} α) (HasOrelse.orelse.{u1, u1} Option.{u1} (Alternative.toHasOrelse.{u1, u1} Option.{u1} Option.alternative.{u1}) α (Option.none.{u1} α) x) x\nbut is expected to have type\n forall {α : Type.{u1}} (x : Option.{u1} α), Eq.{succ u1} (Option.{u1} α) (HOrElse.hOrElse.{u1, u1, u1} (Option.{u1} α) (Option.{u1} α) (Option.{u1} α) (instHOrElse.{u1} (Option.{u1} α) (Option.instOrElseOption.{u1} α)) (Option.none.{u1} α) (fun (x._@.Std.Data.Option.Lemmas._hyg.3103 : Unit) => x)) x\nCase conversion may be inaccurate. Consider using '#align option.none_orelse Option.none_orElseₓ'. -/\n@[simp]\ntheorem none_orElse (x : Option α) : (none <|> x) = x :=\n none_orElse' x\n#align option.none_orelse Option.none_orElse\n\n#print Option.orElse_none' /-\n@[simp]\ntheorem orElse_none' (x : Option α) : x.orelse none = x := by cases x <;> rfl\n#align option.orelse_none' Option.orElse_none'\n-/\n\n/- warning: option.orelse_none -> Option.orElse_none is a dubious translation:\nlean 3 declaration is\n forall {α : Type.{u1}} (x : Option.{u1} α), Eq.{succ u1} (Option.{u1} α) (HasOrelse.orelse.{u1, u1} Option.{u1} (Alternative.toHasOrelse.{u1, u1} Option.{u1} Option.alternative.{u1}) α x (Option.none.{u1} α)) x\nbut is expected to have type\n forall {α : Type.{u1}} (x : Option.{u1} α), Eq.{succ u1} (Option.{u1} α) (HOrElse.hOrElse.{u1, u1, u1} (Option.{u1} α) (Option.{u1} α) (Option.{u1} α) (instHOrElse.{u1} (Option.{u1} α) (Option.instOrElseOption.{u1} α)) x (fun (x._@.Std.Data.Option.Lemmas._hyg.3117 : Unit) => Option.none.{u1} α)) x\nCase conversion may be inaccurate. Consider using '#align option.orelse_none Option.orElse_noneₓ'. -/\n@[simp]\ntheorem orElse_none (x : Option α) : (x <|> none) = x :=\n orElse_none' x\n#align option.orelse_none Option.orElse_none\n\n#print Option.isSome_none /-\n@[simp]\ntheorem isSome_none : @isSome α none = false :=\n rfl\n#align option.is_some_none Option.isSome_none\n-/\n\n#print Option.isSome_some /-\n@[simp]\ntheorem isSome_some {a : α} : isSome (some a) = true :=\n rfl\n#align option.is_some_some Option.isSome_some\n-/\n\n#print Option.isSome_iff_exists /-\ntheorem isSome_iff_exists {x : Option α} : isSome x ↔ ∃ a, x = some a := by\n cases x <;> simp [is_some] <;> exact ⟨_, rfl⟩\n#align option.is_some_iff_exists Option.isSome_iff_exists\n-/\n\n#print Option.isNone_none /-\n@[simp]\ntheorem isNone_none : @isNone α none = true :=\n rfl\n#align option.is_none_none Option.isNone_none\n-/\n\n#print Option.isNone_some /-\n@[simp]\ntheorem isNone_some {a : α} : isNone (some a) = false :=\n rfl\n#align option.is_none_some Option.isNone_some\n-/\n\n#print Option.not_isSome /-\n@[simp]\ntheorem not_isSome {a : Option α} : isSome a = false ↔ a.isNone = true := by cases a <;> simp\n#align option.not_is_some Option.not_isSome\n-/\n\n#print Option.eq_some_iff_get_eq /-\ntheorem eq_some_iff_get_eq {o : Option α} {a : α} : o = some a ↔ ∃ h : o.isSome, Option.get h = a :=\n by cases o <;> simp\n#align option.eq_some_iff_get_eq Option.eq_some_iff_get_eq\n-/\n\n#print Option.not_isSome_iff_eq_none /-\ntheorem not_isSome_iff_eq_none {o : Option α} : ¬o.isSome ↔ o = none := by cases o <;> simp\n#align option.not_is_some_iff_eq_none Option.not_isSome_iff_eq_none\n-/\n\n#print Option.ne_none_iff_isSome /-\ntheorem ne_none_iff_isSome {o : Option α} : o ≠ none ↔ o.isSome := by cases o <;> simp\n#align option.ne_none_iff_is_some Option.ne_none_iff_isSome\n-/\n\n#print Option.ne_none_iff_exists /-\ntheorem ne_none_iff_exists {o : Option α} : o ≠ none ↔ ∃ x : α, some x = o := by cases o <;> simp\n#align option.ne_none_iff_exists Option.ne_none_iff_exists\n-/\n\n#print Option.ne_none_iff_exists' /-\ntheorem ne_none_iff_exists' {o : Option α} : o ≠ none ↔ ∃ x : α, o = some x :=\n ne_none_iff_exists.trans <| exists_congr fun _ => eq_comm\n#align option.ne_none_iff_exists' Option.ne_none_iff_exists'\n-/\n\n/- ./././Mathport/Syntax/Translate/Basic.lean:635:2: warning: expanding binder collection (x «expr ≠ » none[option.none]) -/\n#print Option.bex_ne_none /-\ntheorem bex_ne_none {p : Option α → Prop} : (∃ (x : _)(_ : x ≠ none), p x) ↔ ∃ x, p (some x) :=\n ⟨fun ⟨x, hx, hp⟩ => ⟨get <| ne_none_iff_isSome.1 hx, by rwa [some_get]⟩, fun ⟨x, hx⟩ =>\n ⟨some x, some_ne_none x, hx⟩⟩\n#align option.bex_ne_none Option.bex_ne_none\n-/\n\n/- ./././Mathport/Syntax/Translate/Basic.lean:635:2: warning: expanding binder collection (x «expr ≠ » none[option.none]) -/\n#print Option.ball_ne_none /-\ntheorem ball_ne_none {p : Option α → Prop} : (∀ (x) (_ : x ≠ none), p x) ↔ ∀ x, p (some x) :=\n ⟨fun h x => h (some x) (some_ne_none x), fun h x hx => by\n simpa only [some_get] using h (get <| ne_none_iff_is_some.1 hx)⟩\n#align option.ball_ne_none Option.ball_ne_none\n-/\n\n#print Option.iget_mem /-\ntheorem iget_mem [Inhabited α] : ∀ {o : Option α}, isSome o → o.iget ∈ o\n | some a, _ => rfl\n#align option.iget_mem Option.iget_mem\n-/\n\n#print Option.iget_of_mem /-\ntheorem iget_of_mem [Inhabited α] {a : α} : ∀ {o : Option α}, a ∈ o → o.iget = a\n | _, rfl => rfl\n#align option.iget_of_mem Option.iget_of_mem\n-/\n\n#print Option.getD_default_eq_iget /-\ntheorem getD_default_eq_iget [Inhabited α] (o : Option α) : o.getD default = o.iget := by\n cases o <;> rfl\n#align option.get_or_else_default_eq_iget Option.getD_default_eq_iget\n-/\n\n/- warning: option.guard_eq_some -> Option.guard_eq_some is a dubious translation:\nlean 3 declaration is\n forall {α : Type.{u1}} {p : α -> Prop} [_inst_1 : DecidablePred.{succ u1} α p] {a : α} {b : α}, Iff (Eq.{succ u1} (Option.{u1} α) (Option.guard.{u1} α p (fun (a : α) => _inst_1 a) a) (Option.some.{u1} α b)) (And (Eq.{succ u1} α a b) (p a))\nbut is expected to have type\n forall {α : Type.{u1}} {p : α -> Prop} {_inst_1 : α} {a : α} [b : DecidablePred.{succ u1} α p], Iff (Eq.{succ u1} (Option.{u1} α) (Option.guard.{u1} α p (fun (a : α) => b a) _inst_1) (Option.some.{u1} α a)) (And (Eq.{succ u1} α _inst_1 a) (p _inst_1))\nCase conversion may be inaccurate. Consider using '#align option.guard_eq_some Option.guard_eq_someₓ'. -/\n@[simp]\ntheorem guard_eq_some {p : α → Prop} [DecidablePred p] {a b : α} :\n guard p a = some b ↔ a = b ∧ p a := by\n by_cases p a <;> simp [Option.guard, h] <;> intro <;> contradiction\n#align option.guard_eq_some Option.guard_eq_some\n\n/- warning: option.guard_eq_some' -> Option.guard_eq_some' is a dubious translation:\nlean 3 declaration is\n forall {p : Prop} [_inst_1 : Decidable p] (u : Unit), Iff (Eq.{1} (Option.{0} Unit) (guard.{0} Option.{0} Option.alternative.{0} p _inst_1) (Option.some.{0} Unit u)) p\nbut is expected to have type\n forall {p : Prop} [_inst_1 : Decidable p] (u : Unit), Iff (Eq.{1} (Option.{0} Unit) (guard.{0} Option.{0} instAlternativeOption.{0} p _inst_1) (Option.some.{0} Unit u)) p\nCase conversion may be inaccurate. Consider using '#align option.guard_eq_some' Option.guard_eq_some'ₓ'. -/\n@[simp]\ntheorem guard_eq_some' {p : Prop} [Decidable p] (u) : guard p = some u ↔ p :=\n by\n cases u\n by_cases p <;> simp [_root_.guard, h] <;> first |rfl|contradiction\n#align option.guard_eq_some' Option.guard_eq_some'\n\n#print Option.liftOrGet_choice /-\ntheorem liftOrGet_choice {f : α → α → α} (h : ∀ a b, f a b = a ∨ f a b = b) :\n ∀ o₁ o₂, liftOrGet f o₁ o₂ = o₁ ∨ liftOrGet f o₁ o₂ = o₂\n | none, none => Or.inl rfl\n | some a, none => Or.inl rfl\n | none, some b => Or.inr rfl\n | some a, some b => by simpa [lift_or_get] using h a b\n#align option.lift_or_get_choice Option.liftOrGet_choice\n-/\n\n#print Option.liftOrGet_none_left /-\n@[simp]\ntheorem liftOrGet_none_left {f} {b : Option α} : liftOrGet f none b = b := by cases b <;> rfl\n#align option.lift_or_get_none_left Option.liftOrGet_none_left\n-/\n\n#print Option.liftOrGet_none_right /-\n@[simp]\ntheorem liftOrGet_none_right {f} {a : Option α} : liftOrGet f a none = a := by cases a <;> rfl\n#align option.lift_or_get_none_right Option.liftOrGet_none_right\n-/\n\n#print Option.liftOrGet_some_some /-\n@[simp]\ntheorem liftOrGet_some_some {f} {a b : α} : liftOrGet f (some a) (some b) = f a b :=\n rfl\n#align option.lift_or_get_some_some Option.liftOrGet_some_some\n-/\n\n#print Option.casesOn' /-\n/-- Given an element of `a : option α`, a default element `b : β` and a function `α → β`, apply this\nfunction to `a` if it comes from `α`, and return `b` otherwise. -/\ndef casesOn' : Option α → β → (α → β) → β\n | none, n, s => n\n | some a, n, s => s a\n#align option.cases_on' Option.casesOn'\n-/\n\n#print Option.casesOn'_none /-\n@[simp]\ntheorem casesOn'_none (x : β) (f : α → β) : casesOn' none x f = x :=\n rfl\n#align option.cases_on'_none Option.casesOn'_none\n-/\n\n#print Option.casesOn'_some /-\n@[simp]\ntheorem casesOn'_some (x : β) (f : α → β) (a : α) : casesOn' (some a) x f = f a :=\n rfl\n#align option.cases_on'_some Option.casesOn'_some\n-/\n\n#print Option.casesOn'_coe /-\n@[simp]\ntheorem casesOn'_coe (x : β) (f : α → β) (a : α) : casesOn' (a : Option α) x f = f a :=\n rfl\n#align option.cases_on'_coe Option.casesOn'_coe\n-/\n\n/- warning: option.cases_on'_none_coe -> Option.casesOn'_none_coe is a dubious translation:\nlean 3 declaration is\n forall {α : Type.{u1}} {β : Type.{u2}} (f : (Option.{u1} α) -> β) (o : Option.{u1} α), Eq.{succ u2} β (Option.casesOn'.{u1, u2} α β o (f (Option.none.{u1} α)) (Function.comp.{succ u1, succ u1, succ u2} α (Option.{u1} α) β f ((fun (a : Type.{u1}) (b : Type.{u1}) [self : HasLiftT.{succ u1, succ u1} a b] => self.0) α (Option.{u1} α) (HasLiftT.mk.{succ u1, succ u1} α (Option.{u1} α) (CoeTCₓ.coe.{succ u1, succ u1} α (Option.{u1} α) (coeOption.{u1} α)))))) (f o)\nbut is expected to have type\n forall {α : Type.{u2}} {β : Type.{u1}} (f : (Option.{u2} α) -> β) (o : Option.{u2} α), Eq.{succ u1} β (Option.casesOn'.{u2, u1} α β o (f (Option.none.{u2} α)) (Function.comp.{succ u2, succ u2, succ u1} α (Option.{u2} α) β f (fun (a : α) => Option.some.{u2} α a))) (f o)\nCase conversion may be inaccurate. Consider using '#align option.cases_on'_none_coe Option.casesOn'_none_coeₓ'. -/\n@[simp]\ntheorem casesOn'_none_coe (f : Option α → β) (o : Option α) : casesOn' o (f none) (f ∘ coe) = f o :=\n by cases o <;> rfl\n#align option.cases_on'_none_coe Option.casesOn'_none_coe\n\n/- warning: option.get_or_else_map -> Option.getD_map is a dubious translation:\nlean 3 declaration is\n forall {α : Type.{u1}} {β : Type.{u2}} (f : α -> β) (x : α) (o : Option.{u1} α), Eq.{succ u2} β (Option.getD.{u2} β (Option.map.{u1, u2} α β f o) (f x)) (f (Option.getD.{u1} α o x))\nbut is expected to have type\n forall {α : Type.{u2}} {β : Type.{u1}} (f : α -> β) (x : α) (o : Option.{u2} α), Eq.{succ u1} β (Option.getD.{u1} β (Option.map.{u2, u1} α β f o) (f x)) (f (Option.getD.{u2} α o x))\nCase conversion may be inaccurate. Consider using '#align option.get_or_else_map Option.getD_mapₓ'. -/\n@[simp]\ntheorem getD_map (f : α → β) (x : α) (o : Option α) : getD (o.map f) (f x) = f (getD o x) := by\n cases o <;> rfl\n#align option.get_or_else_map Option.getD_map\n\n/- warning: option.orelse_eq_some -> Option.orElse_eq_some is a dubious translation:\nlean 3 declaration is\n forall {α : Type.{u1}} (o : Option.{u1} α) (o' : Option.{u1} α) (x : α), Iff (Eq.{succ u1} (Option.{u1} α) (HasOrelse.orelse.{u1, u1} Option.{u1} (Alternative.toHasOrelse.{u1, u1} Option.{u1} Option.alternative.{u1}) α o o') (Option.some.{u1} α x)) (Or (Eq.{succ u1} (Option.{u1} α) o (Option.some.{u1} α x)) (And (Eq.{succ u1} (Option.{u1} α) o (Option.none.{u1} α)) (Eq.{succ u1} (Option.{u1} α) o' (Option.some.{u1} α x))))\nbut is expected to have type\n forall {α : Type.{u1}} (o : Option.{u1} α) (o' : Option.{u1} α) (x : α), Iff (Eq.{succ u1} (Option.{u1} α) (HOrElse.hOrElse.{u1, u1, u1} (Option.{u1} α) (Option.{u1} α) (Option.{u1} α) (instHOrElse.{u1} (Option.{u1} α) (Option.instOrElseOption.{u1} α)) o (fun (x._@.Mathlib.Data.Option.Basic._hyg.3038 : Unit) => o')) (Option.some.{u1} α x)) (Or (Eq.{succ u1} (Option.{u1} α) o (Option.some.{u1} α x)) (And (Eq.{succ u1} (Option.{u1} α) o (Option.none.{u1} α)) (Eq.{succ u1} (Option.{u1} α) o' (Option.some.{u1} α x))))\nCase conversion may be inaccurate. Consider using '#align option.orelse_eq_some Option.orElse_eq_someₓ'. -/\ntheorem orElse_eq_some (o o' : Option α) (x : α) :\n (o <|> o') = some x ↔ o = some x ∨ o = none ∧ o' = some x :=\n by\n cases o\n · simp only [true_and_iff, false_or_iff, eq_self_iff_true, none_orelse]\n · simp only [some_orelse, or_false_iff, false_and_iff]\n#align option.orelse_eq_some Option.orElse_eq_some\n\n/- warning: option.orelse_eq_some' -> Option.orElse_eq_some' is a dubious translation:\nlean 3 declaration is\n forall {α : Type.{u1}} (o : Option.{u1} α) (o' : Option.{u1} α) (x : α), Iff (Eq.{succ u1} (Option.{u1} α) (Option.orelse.{u1} α o o') (Option.some.{u1} α x)) (Or (Eq.{succ u1} (Option.{u1} α) o (Option.some.{u1} α x)) (And (Eq.{succ u1} (Option.{u1} α) o (Option.none.{u1} α)) (Eq.{succ u1} (Option.{u1} α) o' (Option.some.{u1} α x))))\nbut is expected to have type\n forall {α : Type.{u1}} (o : Option.{u1} α) (o' : Option.{u1} α) (x : α), Iff (Eq.{succ u1} (Option.{u1} α) (Option.orElse.{u1} α o (fun (x._@.Mathlib.Data.Option.Basic._hyg.3099 : Unit) => o')) (Option.some.{u1} α x)) (Or (Eq.{succ u1} (Option.{u1} α) o (Option.some.{u1} α x)) (And (Eq.{succ u1} (Option.{u1} α) o (Option.none.{u1} α)) (Eq.{succ u1} (Option.{u1} α) o' (Option.some.{u1} α x))))\nCase conversion may be inaccurate. Consider using '#align option.orelse_eq_some' Option.orElse_eq_some'ₓ'. -/\ntheorem orElse_eq_some' (o o' : Option α) (x : α) :\n o.orelse o' = some x ↔ o = some x ∨ o = none ∧ o' = some x :=\n Option.orElse_eq_some o o' x\n#align option.orelse_eq_some' Option.orElse_eq_some'\n\n/- warning: option.orelse_eq_none -> Option.orElse_eq_none is a dubious translation:\nlean 3 declaration is\n forall {α : Type.{u1}} (o : Option.{u1} α) (o' : Option.{u1} α), Iff (Eq.{succ u1} (Option.{u1} α) (HasOrelse.orelse.{u1, u1} Option.{u1} (Alternative.toHasOrelse.{u1, u1} Option.{u1} Option.alternative.{u1}) α o o') (Option.none.{u1} α)) (And (Eq.{succ u1} (Option.{u1} α) o (Option.none.{u1} α)) (Eq.{succ u1} (Option.{u1} α) o' (Option.none.{u1} α)))\nbut is expected to have type\n forall {α : Type.{u1}} (o : Option.{u1} α) (o' : Option.{u1} α), Iff (Eq.{succ u1} (Option.{u1} α) (HOrElse.hOrElse.{u1, u1, u1} (Option.{u1} α) (Option.{u1} α) (Option.{u1} α) (instHOrElse.{u1} (Option.{u1} α) (Option.instOrElseOption.{u1} α)) o (fun (x._@.Mathlib.Data.Option.Basic._hyg.3151 : Unit) => o')) (Option.none.{u1} α)) (And (Eq.{succ u1} (Option.{u1} α) o (Option.none.{u1} α)) (Eq.{succ u1} (Option.{u1} α) o' (Option.none.{u1} α)))\nCase conversion may be inaccurate. Consider using '#align option.orelse_eq_none Option.orElse_eq_noneₓ'. -/\n@[simp]\ntheorem orElse_eq_none (o o' : Option α) : (o <|> o') = none ↔ o = none ∧ o' = none :=\n by\n cases o\n · simp only [true_and_iff, none_orelse, eq_self_iff_true]\n · simp only [some_orelse, false_and_iff]\n#align option.orelse_eq_none Option.orElse_eq_none\n\n/- warning: option.orelse_eq_none' -> Option.orElse_eq_none' is a dubious translation:\nlean 3 declaration is\n forall {α : Type.{u1}} (o : Option.{u1} α) (o' : Option.{u1} α), Iff (Eq.{succ u1} (Option.{u1} α) (Option.orelse.{u1} α o o') (Option.none.{u1} α)) (And (Eq.{succ u1} (Option.{u1} α) o (Option.none.{u1} α)) (Eq.{succ u1} (Option.{u1} α) o' (Option.none.{u1} α)))\nbut is expected to have type\n forall {α : Type.{u1}} (o : Option.{u1} α) (o' : Option.{u1} α), Iff (Eq.{succ u1} (Option.{u1} α) (Option.orElse.{u1} α o (fun (x._@.Mathlib.Data.Option.Basic._hyg.3201 : Unit) => o')) (Option.none.{u1} α)) (And (Eq.{succ u1} (Option.{u1} α) o (Option.none.{u1} α)) (Eq.{succ u1} (Option.{u1} α) o' (Option.none.{u1} α)))\nCase conversion may be inaccurate. Consider using '#align option.orelse_eq_none' Option.orElse_eq_none'ₓ'. -/\n@[simp]\ntheorem orElse_eq_none' (o o' : Option α) : o.orelse o' = none ↔ o = none ∧ o' = none :=\n Option.orElse_eq_none o o'\n#align option.orelse_eq_none' Option.orElse_eq_none'\n\nsection\n\nopen Classical\n\n#print Option.choice /-\n/-- An arbitrary `some a` with `a : α` if `α` is nonempty, and otherwise `none`. -/\nnoncomputable def choice (α : Type _) : Option α :=\n if h : Nonempty α then some h.some else none\n#align option.choice Option.choice\n-/\n\n#print Option.choice_eq /-\ntheorem choice_eq {α : Type _} [Subsingleton α] (a : α) : choice α = some a :=\n by\n dsimp [choice]\n rw [dif_pos (⟨a⟩ : Nonempty α)]\n congr\n#align option.choice_eq Option.choice_eq\n-/\n\n#print Option.choice_eq_none /-\ntheorem choice_eq_none (α : Type _) [IsEmpty α] : choice α = none :=\n dif_neg (not_nonempty_iff_imp_false.mpr isEmptyElim)\n#align option.choice_eq_none Option.choice_eq_none\n-/\n\n#print Option.choice_isSome_iff_nonempty /-\ntheorem choice_isSome_iff_nonempty {α : Type _} : (choice α).isSome ↔ Nonempty α :=\n by\n fconstructor\n · intro h\n exact ⟨Option.get h⟩\n · intro h\n dsimp only [choice]\n rw [dif_pos h]\n exact is_some_some\n#align option.choice_is_some_iff_nonempty Option.choice_isSome_iff_nonempty\n-/\n\nend\n\n#print Option.to_list_some /-\n@[simp]\ntheorem to_list_some (a : α) : (a : Option α).toList = [a] :=\n rfl\n#align option.to_list_some Option.to_list_some\n-/\n\n#print Option.to_list_none /-\n@[simp]\ntheorem to_list_none (α : Type _) : (none : Option α).toList = [] :=\n rfl\n#align option.to_list_none Option.to_list_none\n-/\n\n/- warning: option.elim_none_some -> Option.elim_none_some is a dubious translation:\nlean 3 declaration is\n forall {α : Type.{u1}} {β : Type.{u2}} (f : (Option.{u1} α) -> β), Eq.{max (succ u1) (succ u2)} ((Option.{u1} α) -> β) (Option.elim'.{u1, u2} α β (f (Option.none.{u1} α)) (Function.comp.{succ u1, succ u1, succ u2} α (Option.{u1} α) β f (Option.some.{u1} α))) f\nbut is expected to have type\n forall {α : Type.{u2}} {β : Type.{u1}} (f : (Option.{u2} α) -> β), Eq.{max (succ u2) (succ u1)} ((Option.{u2} α) -> β) (fun (x : Option.{u2} α) => Option.elim.{u2, succ u1} α β x (f (Option.none.{u2} α)) (Function.comp.{succ u2, succ u2, succ u1} α (Option.{u2} α) β f (Option.some.{u2} α))) f\nCase conversion may be inaccurate. Consider using '#align option.elim_none_some Option.elim_none_someₓ'. -/\n@[simp]\ntheorem elim_none_some (f : Option α → β) : Option.elim' (f none) (f ∘ some) = f :=\n funext fun o => by cases o <;> rfl\n#align option.elim_none_some Option.elim_none_some\n\nend Option\n\n", "meta": {"author": "leanprover-community", "repo": "mathlib3port", "sha": "62505aa236c58c8559783b16d33e30df3daa54f4", "save_path": "github-repos/lean/leanprover-community-mathlib3port", "path": "github-repos/lean/leanprover-community-mathlib3port/mathlib3port-62505aa236c58c8559783b16d33e30df3daa54f4/Mathbin/Data/Option/Basic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42250463481418826, "lm_q2_score": 0.10087863016367529, "lm_q1q2_score": 0.042621688797859186}} {"text": "/-\nCopyright (c) 2021 Mario Carneiro. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthor: Mario Carneiro\n-/\nimport Mathlib.Tactic.NoMatch\nimport Lean.Elab.Command\n\nopen Lean Parser.Tactic Elab Command Elab.Tactic Meta\n\nsyntax (name := «variables») \"variables\" (bracketedBinder)* : command\n\n@[commandElab «variables»] def elabVariables : CommandElab\n | `(variables%$pos $binders*) => do\n logWarningAt pos \"'variables' has been replaced by 'variable' in lean 4\"\n elabVariable (← `(variable%$pos $binders*))\n | _ => throwUnsupportedSyntax\n\nmacro mods:declModifiers \"lemma\" n:declId sig:declSig val:declVal : command =>\n `($mods:declModifiers theorem $n $sig $val)\n\nmacro \"exfalso\" : tactic => `(apply False.elim)\n\nmacro \"_\" : tactic => `({})\n\nmacro_rules | `(tactic| rfl) => `(tactic| exact Iff.rfl)\n\n/-- `change` is a synonym for `show`,\nand can be used to replace a goal with a definitionally equal one. -/\nmacro_rules\n | `(tactic| change $e:term) => `(tactic| show $e)\n\n/-- `rwa` calls `rw`, then closes any remaining goals using `assumption`. -/\nsyntax \"rwa \" rwRuleSeq (location)? : tactic\n\nmacro_rules\n | `(tactic| rwa $rws:rwRuleSeq $[$loc:location]?) =>\n `(tactic| rw $rws:rwRuleSeq $[$loc:location]?; assumption)\n\nmacro \"by_cases \" h:ident \":\" e:term : tactic =>\n `(cases Decidable.em $e with | inl $h => ?pos | inr $h => ?neg)\n\nset_option hygiene false in\nmacro \"by_cases \" e:term : tactic =>\n `(cases Decidable.em $e with | inl h => ?pos | inr h => ?neg)\n\nmacro (name := classical) \"classical\" : tactic =>\n `(have em := Classical.propDecidable)\n\nsyntax \"transitivity\" (colGt term)? : tactic\nset_option hygiene false in\nmacro_rules\n | `(tactic| transitivity) => `(tactic| apply Nat.le_trans)\n | `(tactic| transitivity $e) => `(tactic| apply Nat.le_trans (m := $e))\nset_option hygiene false in\nmacro_rules\n | `(tactic| transitivity) => `(tactic| apply Nat.lt_trans)\n | `(tactic| transitivity $e) => `(tactic| apply Nat.lt_trans (m := $e))\n\n/--\nThe tactic `introv` allows the user to automatically introduce the variables of a theorem and\nexplicitly name the non-dependent hypotheses.\nAny dependent hypotheses are assigned their default names.\n\nExamples:\n```\nexample : ∀ a b : Nat, a = b → b = a := by\n introv h,\n exact h.symm\n```\nThe state after `introv h` is\n```\na b : ℕ,\nh : a = b\n⊢ b = a\n```\n\n```\nexample : ∀ a b : Nat, a = b → ∀ c, b = c → a = c := by\n introv h₁ h₂,\n exact h₁.trans h₂\n```\nThe state after `introv h₁ h₂` is\n```\na b : ℕ,\nh₁ : a = b,\nc : ℕ,\nh₂ : b = c\n⊢ a = c\n```\n-/\nsyntax (name := introv) \"introv \" (colGt binderIdent)* : tactic\n@[tactic introv] partial def evalIntrov : Tactic := fun stx => do\n match stx with\n | `(tactic| introv) => introsDep\n | `(tactic| introv $h:ident $hs:binderIdent*) =>\n evalTactic (← `(tactic| introv; intro $h:ident; introv $hs:binderIdent*))\n | `(tactic| introv _%$tk $hs:binderIdent*) =>\n evalTactic (← `(tactic| introv; intro _%$tk; introv $hs:binderIdent*))\n | _ => throwUnsupportedSyntax\nwhere\n introsDep : TacticM Unit := do\n let t ← getMainTarget\n match t with\n | Expr.forallE _ _ e _ =>\n if e.hasLooseBVars then\n intro1PStep\n introsDep\n | _ => pure ()\n intro1PStep : TacticM Unit :=\n liftMetaTactic fun mvarId => do\n let (_, mvarId) ← Meta.intro1P mvarId\n pure [mvarId]\n\n/-- Try calling `assumption` on all goals; succeeds if it closes at least one goal. -/\nmacro \"assumption'\" : tactic => `(any_goals assumption)\n\n/--\nLike `exact`, but takes a list of terms and checks that all goals are discharged after the tactic.\n-/\nelab (name := exacts) \"exacts\" \"[\" hs:term,* \"]\" : tactic => do\n for stx in hs.getElems do\n evalTactic (← `(tactic| exact $stx))\n evalTactic (← `(tactic| done))\n\n/-- Check syntactic equality of two expressions.\nSee also `guardExprEq` and `guardExprEq'` for testing\nup to alpha equality and definitional equality. -/\nelab (name := guardExprStrict) \"guard_expr \" r:term:51 \" == \" p:term : tactic => withMainContext do\n let r ← elabTerm r none\n let p ← elabTerm p none\n if not (r == p) then throwError \"failed: {r} != {p}\"\n\n/-- Check the target agrees (syntactically) with a given expression.\nSee also `guardTarget` and `guardTarget'` for testing\nup to alpha equality and definitional equality. -/\nelab (name := guardTargetStrict) \"guard_target\" \" == \" r:term : tactic => withMainContext do\n let r ← elabTerm r none\n let t ← getMainTarget\n let t := t.consumeMData\n if not (r == t) then throwError m!\"target of main goal is {t}, not {r}\"\n\nsyntax (name := guardHyp) \"guard_hyp \" ident\n ((\" : \" <|> \" :ₐ \") term)? ((\" := \" <|> \" :=ₐ \") term)? : tactic\n\n/-- Check that a named hypothesis has a given type and/or value.\n\n`guardHyp h : t` checks the type up to syntactic equality,\nwhile `guardHyp h :ₐ t` checks the type up to alpha equality.\n`guardHyp h := v` checks value up to syntactic equality,\nwhile `guardHyp h :=ₐ v` checks the value up to alpha equality. -/\n-- TODO implement checking type or value up to alpha equality.\n@[tactic guardHyp] def evalGuardHyp : Lean.Elab.Tactic.Tactic := fun stx =>\n match stx with\n | `(tactic| guard_hyp $h $[: $ty]? $[:= $val]?) => do\n withMainContext do\n let fvarid ← getFVarId h\n let lDecl ←\n match (← getLCtx).find? fvarid with\n | none => throwError m!\"hypothesis {h} not found\"\n | some lDecl => pure lDecl\n if let some p := ty then\n let e ← elabTerm p none\n let hty ← instantiateMVars lDecl.type\n let hty := hty.consumeMData\n if not (e == hty) then throwError m!\"hypothesis {h} has type {hty}\"\n match lDecl.value?, val with\n | none, some _ => throwError m!\"{h} is not a let binding\"\n | some _, none => throwError m!\"{h} is a let binding\"\n | some hval, some val =>\n let e ← elabTerm val none\n let hval ← instantiateMVars hval\n let hval := hval.consumeMData\n if not (e == hval) then throwError m!\"hypothesis {h} has value {hval}\"\n | none, none => pure ()\n | _ => throwUnsupportedSyntax\n\nelab \"match_target\" t:term : tactic => do\n withMainContext do\n let (val) ← elabTerm t (← inferType (← getMainTarget))\n if not (← isDefEq val (← getMainTarget)) then\n throwError \"failed\"\n\nsyntax (name := byContra) \"by_contra\" (ppSpace colGt ident)? : tactic\nmacro_rules\n | `(tactic| by_contra) => `(tactic| (match_target Not _; intro))\n | `(tactic| by_contra $e) => `(tactic| (match_target Not _; intro $e))\nmacro_rules\n | `(tactic| by_contra) => `(tactic| (apply Decidable.byContradiction; intro))\n | `(tactic| by_contra $e) => `(tactic| (apply Decidable.byContradiction; intro $e))\nmacro_rules\n | `(tactic| by_contra) => `(tactic| (apply Classical.byContradiction; intro))\n | `(tactic| by_contra $e) => `(tactic| (apply Classical.byContradiction; intro $e))\n\n/--\n`iterate n tac` runs `tac` exactly `n` times.\n`iterate tac` runs `tac` repeatedly until failure.\n\nTo run multiple tactics, one can do `iterate (tac₁; tac₂; ⋯)` or\n```lean\niterate\n tac₁\n tac₂\n ⋯\n```\n-/\nsyntax \"iterate\" (ppSpace num)? ppSpace tacticSeq : tactic\nmacro_rules\n | `(tactic|iterate $seq:tacticSeq) =>\n `(tactic|try ($seq:tacticSeq); iterate $seq:tacticSeq)\n | `(tactic|iterate $n $seq:tacticSeq) =>\n match n.toNat with\n | 0 => `(tactic| skip)\n | n+1 => `(tactic|($seq:tacticSeq); iterate $(quote n) $seq:tacticSeq)\n\npartial def repeat'Aux (seq : Syntax) : List MVarId → TacticM Unit\n| [] => pure ()\n| g::gs => do\n try\n let subgs ← evalTacticAt seq g\n appendGoals subgs\n repeat'Aux seq (subgs ++ gs)\n catch _ =>\n repeat'Aux seq gs\n\nelab \"repeat' \" seq:tacticSeq : tactic => do\n let gs ← getGoals\n repeat'Aux seq gs\n\nelab \"any_goals \" seq:tacticSeq : tactic => do\n let mvarIds ← getGoals\n let mut mvarIdsNew := #[]\n let mut anySuccess := false\n for mvarId in mvarIds do\n unless (← isExprMVarAssigned mvarId) do\n setGoals [mvarId]\n try\n evalTactic seq\n mvarIdsNew := mvarIdsNew ++ (← getUnsolvedGoals)\n anySuccess := true\n catch ex =>\n mvarIdsNew := mvarIdsNew.push mvarId\n if not anySuccess then\n throwError \"failed on all goals\"\n setGoals mvarIdsNew.toList\n\nelab \"fapply \" e:term : tactic =>\n evalApplyLikeTactic (Meta.apply (cfg := {newGoals := ApplyNewGoals.all})) e\n\nelab \"eapply \" e:term : tactic =>\n evalApplyLikeTactic (Meta.apply (cfg := {newGoals := ApplyNewGoals.nonDependentOnly})) e\n", "meta": {"author": "JOSHCLUNE", "repo": "Keller_reduction", "sha": "dc392b3da352fc1ffcfbecb1d4717d05f5faed4a", "save_path": "github-repos/lean/JOSHCLUNE-Keller_reduction", "path": "github-repos/lean/JOSHCLUNE-Keller_reduction/Keller_reduction-dc392b3da352fc1ffcfbecb1d4717d05f5faed4a/Lean4_Clique/Mathlib/Mathlib/Tactic/Basic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4765796510636759, "lm_q2_score": 0.08882029722399613, "lm_q1q2_score": 0.04232994625838406}} {"text": "import tactic\n\nopen tactic\n\nmeta def make_a_nat : tactic ℕ :=\nreturn 14\n\nmeta def trace_a_nat : tactic unit :=\ndo n ← make_a_nat,\n trace n\n\nrun_cmd trace_a_nat\n\n-- Comentario: Al colocar el cursor sobre run_cmd se obtiene 14.\n\nexample (a b c : ℤ) : false :=\nbegin \n trace_a_nat,\n sorry,\nend\n\n-- Comentario: Al colocar el cursor sobre trace_a_nat se obtiene 14.\n\nmeta def inspect : tactic unit :=\ndo t ← target,\n trace t,\n a_expr ← get_local `a <|> fail \"No hay ninguna a\",\n trace (expr.to_raw_fmt a_expr),\n a_type ← infer_type a_expr,\n trace a_type,\n ctx <- local_context,\n trace ctx,\n let new_nat := 40,\n trace new_nat,\n ctx' ← ctx.mmap (λ e, infer_type e),\n trace ctx'\n\nexample (a b c : ℤ) (p q : ℕ) : c = b :=\nby do inspect\n\n\n-- Comentario: Al colocar el cursor sobre do se obtiene\n-- c = b\n-- (local_const 0._fresh.476.10 a (const 1 []))\n-- ℤ\n-- [a, b, c, p, q]\n-- 40\n-- [ℤ, ℤ, ℤ, ℕ, ℕ]\n\nmeta def inspect2 : tactic unit :=\ndo t ← target,\n trace t,\n a_expr ← get_local `a <|> fail \"No hay ninguna a\",\n trace (expr.to_raw_fmt a_expr),\n a_type ← infer_type a_expr,\n trace a_type,\n ctx <- local_context,\n trace ctx,\n let new_nat := 40,\n trace new_nat,\n ctx' ← ctx.mmap (λ e, infer_type e),\n trace ctx',\n ctx.mmap' (λ e, do tp ← infer_type e, trace tp)\n\nexample (a b c : ℤ) (p q : ℕ) : c = b :=\nby do inspect2\n\n-- Comentario: Al colocar el cursor sobre do se obtiene\n-- c = b\n-- (local_const 0._fresh.619.1 a (const 1 []))\n-- ℤ\n-- [a, b, c, p, q]\n-- 40\n-- [ℤ, ℤ, ℤ, ℕ, ℕ]\n-- ℤ\n-- ℤ\n-- ℤ\n-- ℕ\n-- ℕ\n\n------------------------------------------------------------------------\n-- § Referencia --\n------------------------------------------------------------------------\n\n-- Basado en el vídeo \"Metaprogramming in Lean tutorial: video 4\" de Rob\n-- Lewis que se encuentra en https://youtu.be/qsmnBNXgZgc\n", "meta": {"author": "jaalonso", "repo": "Lean_para_matematicos", "sha": "924c77b7f010604b84f82d2f79967ad8b9cddc6e", "save_path": "github-repos/lean/jaalonso-Lean_para_matematicos", "path": "github-repos/lean/jaalonso-Lean_para_matematicos/Lean_para_matematicos-924c77b7f010604b84f82d2f79967ad8b9cddc6e/src/Metaprogramacion/Introduccion_a_la_metaprogramacion_4.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938145706677, "lm_q2_score": 0.08509905370824052, "lm_q1q2_score": 0.04221711417047516}} {"text": "/-\nCopyright (c) 2017 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Leonardo de Moura, Mario Carneiro\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.default\nimport Mathlib.control.traversable.equiv\nimport Mathlib.data.vector2\nimport Mathlib.PostPort\n\nuniverses u u_1 w v \n\nnamespace Mathlib\n\nnamespace d_array\n\n\nprotected instance inhabited {n : ℕ} {α : fin n → Type u} [(i : fin n) → Inhabited (α i)] :\n Inhabited (d_array n α) :=\n { default := mk fun (_x : fin n) => Inhabited.default }\n\nend d_array\n\n\nnamespace array\n\n\nprotected instance inhabited {n : ℕ} {α : Type u_1} [Inhabited α] : Inhabited (array n α) :=\n d_array.inhabited\n\ntheorem to_list_of_heq {n₁ : ℕ} {n₂ : ℕ} {α : Type u_1} {a₁ : array n₁ α} {a₂ : array n₂ α}\n (hn : n₁ = n₂) (ha : a₁ == a₂) : to_list a₁ = to_list a₂ :=\n sorry\n\n/- rev_list -/\n\ntheorem rev_list_reverse_aux {n : ℕ} {α : Type u} {a : array n α} (i : ℕ) (h : i ≤ n) (t : List α) :\n list.reverse_core\n (d_array.iterate_aux a (fun (_x : fin n) (_x : α) (_y : List α) => _x :: _y) i h []) t =\n d_array.rev_iterate_aux a (fun (_x : fin n) (_x : α) (_y : List α) => _x :: _y) i h t :=\n sorry\n\n@[simp] theorem rev_list_reverse {n : ℕ} {α : Type u} {a : array n α} :\n list.reverse (rev_list a) = to_list a :=\n rev_list_reverse_aux n d_array.iterate._proof_1 []\n\n@[simp] theorem to_list_reverse {n : ℕ} {α : Type u} {a : array n α} :\n list.reverse (to_list a) = rev_list a :=\n sorry\n\n/- mem -/\n\ntheorem mem.def {n : ℕ} {α : Type u} {v : α} {a : array n α} :\n v ∈ a ↔ ∃ (i : fin n), read a i = v :=\n iff.rfl\n\ntheorem mem_rev_list_aux {n : ℕ} {α : Type u} {v : α} {a : array n α} {i : ℕ} (h : i ≤ n) :\n (∃ (j : fin n), ↑j < i ∧ read a j = v) ↔\n v ∈ d_array.iterate_aux a (fun (_x : fin n) (_x : α) (_y : List α) => _x :: _y) i h [] :=\n sorry\n\n@[simp] theorem mem_rev_list {n : ℕ} {α : Type u} {v : α} {a : array n α} :\n v ∈ rev_list a ↔ v ∈ a :=\n sorry\n\n@[simp] theorem mem_to_list {n : ℕ} {α : Type u} {v : α} {a : array n α} : v ∈ to_list a ↔ v ∈ a :=\n eq.mpr (id (Eq._oldrec (Eq.refl (v ∈ to_list a ↔ v ∈ a)) (Eq.symm rev_list_reverse)))\n (iff.trans list.mem_reverse mem_rev_list)\n\n/- foldr -/\n\ntheorem rev_list_foldr_aux {n : ℕ} {α : Type u} {β : Type w} {b : β} {f : α → β → β} {a : array n α}\n {i : ℕ} (h : i ≤ n) :\n list.foldr f b\n (d_array.iterate_aux a (fun (_x : fin n) (_x : α) (_y : List α) => _x :: _y) i h []) =\n d_array.iterate_aux a (fun (_x : fin n) => f) i h b :=\n sorry\n\ntheorem rev_list_foldr {n : ℕ} {α : Type u} {β : Type w} {b : β} {f : α → β → β} {a : array n α} :\n list.foldr f b (rev_list a) = foldl a b f :=\n rev_list_foldr_aux d_array.iterate._proof_1\n\n/- foldl -/\n\ntheorem to_list_foldl {n : ℕ} {α : Type u} {β : Type w} {b : β} {f : β → α → β} {a : array n α} :\n list.foldl f b (to_list a) = foldl a b (function.swap f) :=\n sorry\n\n/- length -/\n\ntheorem rev_list_length_aux {n : ℕ} {α : Type u} (a : array n α) (i : ℕ) (h : i ≤ n) :\n list.length\n (d_array.iterate_aux a (fun (_x : fin n) (_x : α) (_y : List α) => _x :: _y) i h []) =\n i :=\n sorry\n\n@[simp] theorem rev_list_length {n : ℕ} {α : Type u} (a : array n α) :\n list.length (rev_list a) = n :=\n rev_list_length_aux a n d_array.iterate._proof_1\n\n@[simp] theorem to_list_length {n : ℕ} {α : Type u} (a : array n α) : list.length (to_list a) = n :=\n eq.mpr (id (Eq._oldrec (Eq.refl (list.length (to_list a) = n)) (Eq.symm rev_list_reverse)))\n (eq.mpr\n (id\n (Eq._oldrec (Eq.refl (list.length (list.reverse (rev_list a)) = n))\n (list.length_reverse (rev_list a))))\n (eq.mpr (id (Eq._oldrec (Eq.refl (list.length (rev_list a) = n)) (rev_list_length a)))\n (Eq.refl n)))\n\n/- nth -/\n\ntheorem to_list_nth_le_aux {n : ℕ} {α : Type u} {a : array n α} (i : ℕ) (ih : i < n) (j : ℕ)\n {jh : j ≤ n} {t : List α}\n {h' :\n i <\n list.length\n (d_array.rev_iterate_aux a (fun (_x : fin n) (_x : α) (_y : List α) => _x :: _y) j jh\n t)} :\n (∀ (k : ℕ) (tl : k < list.length t),\n j + k = i → list.nth_le t k tl = read a { val := i, property := ih }) →\n list.nth_le\n (d_array.rev_iterate_aux a (fun (_x : fin n) (_x : α) (_y : List α) => _x :: _y) j jh t)\n i h' =\n read a { val := i, property := ih } :=\n sorry\n\ntheorem to_list_nth_le {n : ℕ} {α : Type u} {a : array n α} (i : ℕ) (h : i < n)\n (h' : i < list.length (to_list a)) :\n list.nth_le (to_list a) i h' = read a { val := i, property := h } :=\n to_list_nth_le_aux i h n fun (k : ℕ) (tl : k < list.length []) => absurd tl (nat.not_lt_zero k)\n\n@[simp] theorem to_list_nth_le' {n : ℕ} {α : Type u} (a : array n α) (i : fin n)\n (h' : ↑i < list.length (to_list a)) : list.nth_le (to_list a) (↑i) h' = read a i :=\n sorry\n\ntheorem to_list_nth {n : ℕ} {α : Type u} {a : array n α} {i : ℕ} {v : α} :\n list.nth (to_list a) i = some v ↔ ∃ (h : i < n), read a { val := i, property := h } = v :=\n sorry\n\ntheorem write_to_list {n : ℕ} {α : Type u} {a : array n α} {i : fin n} {v : α} :\n to_list (write a i v) = list.update_nth (to_list a) (↑i) v :=\n sorry\n\n/- enum -/\n\ntheorem mem_to_list_enum {n : ℕ} {α : Type u} {a : array n α} {i : ℕ} {v : α} :\n (i, v) ∈ list.enum (to_list a) ↔ ∃ (h : i < n), read a { val := i, property := h } = v :=\n sorry\n\n/- to_array -/\n\n@[simp] theorem to_list_to_array {n : ℕ} {α : Type u} (a : array n α) :\n list.to_array (to_list a) == a :=\n sorry\n\n@[simp] theorem to_array_to_list {α : Type u} (l : List α) : to_list (list.to_array l) = l :=\n list.ext_le (to_list_length (list.to_array l))\n fun (n : ℕ) (h1 : n < list.length (to_list (list.to_array l))) (h2 : n < list.length l) =>\n to_list_nth_le n h2 h1\n\n/- push_back -/\n\ntheorem push_back_rev_list_aux {n : ℕ} {α : Type u} {v : α} {a : array n α} (i : ℕ) (h : i ≤ n + 1)\n (h' : i ≤ n) :\n d_array.iterate_aux (push_back a v) (fun (_x : fin (n + 1)) (_x : α) (_y : List α) => _x :: _y)\n i h [] =\n d_array.iterate_aux a (fun (_x : fin n) (_x : α) (_y : List α) => _x :: _y) i h' [] :=\n sorry\n\n@[simp] theorem push_back_rev_list {n : ℕ} {α : Type u} {v : α} {a : array n α} :\n rev_list (push_back a v) = v :: rev_list a :=\n sorry\n\n@[simp] theorem push_back_to_list {n : ℕ} {α : Type u} {v : α} {a : array n α} :\n to_list (push_back a v) = to_list a ++ [v] :=\n sorry\n\n/- foreach -/\n\n@[simp] theorem read_foreach {n : ℕ} {α : Type u} {β : Type v} {i : fin n} {f : fin n → α → β}\n {a : array n α} : read (foreach a f) i = f i (read a i) :=\n rfl\n\n/- map -/\n\ntheorem read_map {n : ℕ} {α : Type u} {β : Type v} {i : fin n} {f : α → β} {a : array n α} :\n read (map a f) i = f (read a i) :=\n read_foreach\n\n/- map₂ -/\n\n@[simp] theorem read_map₂ {n : ℕ} {α : Type u} {i : fin n} {f : α → α → α} {a₁ : array n α}\n {a₂ : array n α} : read (map₂ f a₁ a₂) i = f (read a₁ i) (read a₂ i) :=\n read_foreach\n\nend array\n\n\nnamespace equiv\n\n\n/-- The natural equivalence between length-`n` heterogeneous arrays\nand dependent functions from `fin n`. -/\ndef d_array_equiv_fin {n : ℕ} (α : fin n → Type u_1) : d_array n α ≃ ((i : fin n) → α i) :=\n mk d_array.read d_array.mk sorry sorry\n\n/-- The natural equivalence between length-`n` arrays and functions from `fin n`. -/\ndef array_equiv_fin (n : ℕ) (α : Type u_1) : array n α ≃ (fin n → α) :=\n d_array_equiv_fin fun (_x : fin n) => α\n\n/-- The natural equivalence between length-`n` vectors and functions from `fin n`. -/\ndef vector_equiv_fin (α : Type u_1) (n : ℕ) : vector α n ≃ (fin n → α) :=\n mk vector.nth vector.of_fn vector.of_fn_nth sorry\n\n/-- The natural equivalence between length-`n` vectors and length-`n` arrays. -/\ndef vector_equiv_array (α : Type u_1) (n : ℕ) : vector α n ≃ array n α :=\n equiv.trans (vector_equiv_fin α n) (equiv.symm (array_equiv_fin n α))\n\nend equiv\n\n\nnamespace array\n\n\nprotected instance traversable {n : ℕ} : traversable (array n) :=\n equiv.traversable fun (α : Type u_1) => equiv.vector_equiv_array α n\n\nprotected instance is_lawful_traversable {n : ℕ} : is_lawful_traversable (array n) :=\n equiv.is_lawful_traversable fun (α : Type u_1) => equiv.vector_equiv_array α n\n\nend Mathlib", "meta": {"author": "AurelienSaue", "repo": "Mathlib4_auto", "sha": "590df64109b08190abe22358fabc3eae000943f2", "save_path": "github-repos/lean/AurelienSaue-Mathlib4_auto", "path": "github-repos/lean/AurelienSaue-Mathlib4_auto/Mathlib4_auto-590df64109b08190abe22358fabc3eae000943f2/Mathlib/data/array/lemmas_auto.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.08389038698317783, "lm_q1q2_score": 0.041945193491588914}} {"text": "example (p q r : Prop) (hp : p) (hq : q) (hr : r) : p ∧ q ∧ r :=\n by split; try { split }; assumption\n", "meta": {"author": "Ailrun", "repo": "Theorem_Proving_in_Lean", "sha": "2eb1b5caf93c6a5a555c79e9097cf2ba5a66cf68", "save_path": "github-repos/lean/Ailrun-Theorem_Proving_in_Lean", "path": "github-repos/lean/Ailrun-Theorem_Proving_in_Lean/Theorem_Proving_in_Lean-2eb1b5caf93c6a5a555c79e9097cf2ba5a66cf68/src/ch5/ex0507.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4921881357207956, "lm_q2_score": 0.0850990380460446, "lm_q1q2_score": 0.04188473688751575}} {"text": "/-\nCopyright (c) 2018 Scott Morrison. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Scott Morrison, Johannes Hölzl, Reid Barton, Sean Leather\n-/\nimport tactic.pi_instances\n\n/-!\n# Bundled types\n\n`bundled c` provides a uniform structure for bundling a type equipped with a type class.\n\nWe provide `category` instances for these in `category_theory/unbundled_hom.lean`\n(for categories with unbundled homs, e.g. topological spaces)\nand in `category_theory/bundled_hom.lean` (for categories with bundled homs, e.g. monoids).\n-/\n\nuniverses u v\n\nnamespace category_theory\nvariables {c d : Type u → Type v} {α : Type u}\n\n/-- `bundled` is a type bundled with a type class instance for that type. Only\nthe type class is exposed as a parameter. -/\n@[nolint has_inhabited_instance]\nstructure bundled (c : Type u → Type v) : Type (max (u+1) v) :=\n(α : Type u)\n(str : c α . tactic.apply_instance)\n\nnamespace bundled\n\n/-- A generic function for lifting a type equipped with an instance to a bundled object. -/\n-- Usually explicit instances will provide their own version of this, e.g. `Mon.of` and `Top.of`.\ndef of {c : Type u → Type v} (α : Type u) [str : c α] : bundled c := ⟨α, str⟩\n\ninstance : has_coe_to_sort (bundled c) (Type u) := ⟨bundled.α⟩\n\n@[simp] lemma coe_mk (α) (str) : (@bundled.mk c α str : Type u) = α := rfl\n\n/-\n`bundled.map` is reducible so that, if we define a category\n\n def Ring : Type (u+1) := induced_category SemiRing (bundled.map @ring.to_semiring)\n\ninstance search is able to \"see\" that a morphism R ⟶ S in Ring is really\na (semi)ring homomorphism from R.α to S.α, and not merely from\n`(bundled.map @ring.to_semiring R).α` to `(bundled.map @ring.to_semiring S).α`.\n-/\n/-- Map over the bundled structure -/\n@[reducible] def map (f : Π {α}, c α → d α) (b : bundled c) : bundled d :=\n⟨b, f b.str⟩\n\nend bundled\n\nend category_theory\n", "meta": {"author": "jjaassoonn", "repo": "projective_space", "sha": "11fe19fe9d7991a272e7a40be4b6ad9b0c10c7ce", "save_path": "github-repos/lean/jjaassoonn-projective_space", "path": "github-repos/lean/jjaassoonn-projective_space/projective_space-11fe19fe9d7991a272e7a40be4b6ad9b0c10c7ce/src/category_theory/concrete_category/bundled.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44167300566462553, "lm_q2_score": 0.09401018469323504, "lm_q1q2_score": 0.04152176083654769}} {"text": "/-\nCopyright (c) 2019 Scott Morrison. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Scott Morrison\n-/\nimport category_theory.limits.shapes.products\nimport category_theory.limits.shapes.images\nimport category_theory.isomorphism_classes\nimport category_theory.limits.shapes.zero_objects\n\n/-!\n# Zero morphisms and zero objects\n\nA category \"has zero morphisms\" if there is a designated \"zero morphism\" in each morphism space,\nand compositions of zero morphisms with anything give the zero morphism. (Notice this is extra\nstructure, not merely a property.)\n\nA category \"has a zero object\" if it has an object which is both initial and terminal. Having a\nzero object provides zero morphisms, as the unique morphisms factoring through the zero object.\n\n## References\n\n* https://en.wikipedia.org/wiki/Zero_morphism\n* [F. Borceux, *Handbook of Categorical Algebra 2*][borceux-vol2]\n-/\n\nnoncomputable theory\n\nuniverses v u\nuniverses v' u'\n\nopen category_theory\nopen category_theory.category\nopen_locale classical\n\nnamespace category_theory.limits\n\nvariables (C : Type u) [category.{v} C]\nvariables (D : Type u') [category.{v'} D]\n\n/-- A category \"has zero morphisms\" if there is a designated \"zero morphism\" in each morphism space,\nand compositions of zero morphisms with anything give the zero morphism. -/\nclass has_zero_morphisms :=\n[has_zero : Π X Y : C, has_zero (X ⟶ Y)]\n(comp_zero' : ∀ {X Y : C} (f : X ⟶ Y) (Z : C), f ≫ (0 : Y ⟶ Z) = (0 : X ⟶ Z) . obviously)\n(zero_comp' : ∀ (X : C) {Y Z : C} (f : Y ⟶ Z), (0 : X ⟶ Y) ≫ f = (0 : X ⟶ Z) . obviously)\n\nattribute [instance] has_zero_morphisms.has_zero\nrestate_axiom has_zero_morphisms.comp_zero'\nrestate_axiom has_zero_morphisms.zero_comp'\n\nvariables {C}\n\n@[simp] lemma comp_zero [has_zero_morphisms C] {X Y : C} {f : X ⟶ Y} {Z : C} :\n f ≫ (0 : Y ⟶ Z) = (0 : X ⟶ Z) := has_zero_morphisms.comp_zero f Z\n@[simp] lemma zero_comp [has_zero_morphisms C] {X : C} {Y Z : C} {f : Y ⟶ Z} :\n (0 : X ⟶ Y) ≫ f = (0 : X ⟶ Z) := has_zero_morphisms.zero_comp X f\n\ninstance has_zero_morphisms_pempty : has_zero_morphisms (discrete pempty) :=\n{ has_zero := by tidy }\n\ninstance has_zero_morphisms_punit : has_zero_morphisms (discrete punit) :=\n{ has_zero := by tidy }\n\nnamespace has_zero_morphisms\nvariables {C}\n\n/-- This lemma will be immediately superseded by `ext`, below. -/\nprivate lemma ext_aux (I J : has_zero_morphisms C)\n (w : ∀ X Y : C, (@has_zero_morphisms.has_zero _ _ I X Y).zero =\n (@has_zero_morphisms.has_zero _ _ J X Y).zero) : I = J :=\nbegin\n casesI I, casesI J,\n congr,\n { ext X Y,\n exact w X Y },\n { apply proof_irrel_heq, },\n { apply proof_irrel_heq, }\nend\n\n/--\nIf you're tempted to use this lemma \"in the wild\", you should probably\ncarefully consider whether you've made a mistake in allowing two\ninstances of `has_zero_morphisms` to exist at all.\n\nSee, particularly, the note on `zero_morphisms_of_zero_object` below.\n-/\nlemma ext (I J : has_zero_morphisms C) : I = J :=\nbegin\n apply ext_aux,\n intros X Y,\n rw ←@has_zero_morphisms.comp_zero _ _ I X X (@has_zero_morphisms.has_zero _ _ J X X).zero,\n rw @has_zero_morphisms.zero_comp _ _ J,\nend\n\ninstance : subsingleton (has_zero_morphisms C) :=\n⟨ext⟩\n\nend has_zero_morphisms\n\nopen opposite has_zero_morphisms\n\ninstance has_zero_morphisms_opposite [has_zero_morphisms C] :\n has_zero_morphisms Cᵒᵖ :=\n{ has_zero := λ X Y, ⟨(0 : unop Y ⟶ unop X).op⟩,\n comp_zero' := λ X Y f Z, congr_arg quiver.hom.op (has_zero_morphisms.zero_comp (unop Z) f.unop),\n zero_comp' := λ X Y Z f, congr_arg quiver.hom.op (has_zero_morphisms.comp_zero f.unop (unop X)), }\n\nsection\nvariables {C} [has_zero_morphisms C]\n\nlemma zero_of_comp_mono {X Y Z : C} {f : X ⟶ Y} (g : Y ⟶ Z) [mono g] (h : f ≫ g = 0) : f = 0 :=\nby { rw [←zero_comp, cancel_mono] at h, exact h }\n\nlemma zero_of_epi_comp {X Y Z : C} (f : X ⟶ Y) {g : Y ⟶ Z} [epi f] (h : f ≫ g = 0) : g = 0 :=\nby { rw [←comp_zero, cancel_epi] at h, exact h }\n\nlemma eq_zero_of_image_eq_zero {X Y : C} {f : X ⟶ Y} [has_image f] (w : image.ι f = 0) : f = 0 :=\nby rw [←image.fac f, w, has_zero_morphisms.comp_zero]\n\nlemma nonzero_image_of_nonzero {X Y : C} {f : X ⟶ Y} [has_image f] (w : f ≠ 0) : image.ι f ≠ 0 :=\nλ h, w (eq_zero_of_image_eq_zero h)\nend\n\nsection\n\nvariables [has_zero_morphisms D]\n\ninstance : has_zero_morphisms (C ⥤ D) :=\n{ has_zero := λ F G, ⟨{ app := λ X, 0, }⟩ }\n\n@[simp] lemma zero_app (F G : C ⥤ D) (j : C) : (0 : F ⟶ G).app j = 0 := rfl\n\nend\n\nnamespace is_zero\nvariables [has_zero_morphisms C]\n\nlemma eq_zero_of_src {X Y : C} (o : is_zero X) (f : X ⟶ Y) : f = 0 :=\no.eq_of_src _ _\n\nlemma eq_zero_of_tgt {X Y : C} (o : is_zero Y) (f : X ⟶ Y) : f = 0 :=\no.eq_of_tgt _ _\n\nlemma iff_id_eq_zero (X : C) : is_zero X ↔ (𝟙 X = 0) :=\n⟨λ h, h.eq_of_src _ _,\n λ h, ⟨\n λ Y, ⟨⟨⟨0⟩, λ f, by { rw [←id_comp f, ←id_comp default, h, zero_comp, zero_comp], }⟩⟩,\n λ Y, ⟨⟨⟨0⟩, λ f, by { rw [←comp_id f, ←comp_id default, h, comp_zero, comp_zero], }⟩⟩⟩⟩\n\nlemma of_mono_zero (X Y : C) [mono (0 : X ⟶ Y)] : is_zero X :=\n(iff_id_eq_zero X).mpr ((cancel_mono (0 : X ⟶ Y)).1 (by simp))\n\nlemma of_epi_zero (X Y : C) [epi (0 : X ⟶ Y)] : is_zero Y :=\n(iff_id_eq_zero Y).mpr ((cancel_epi (0 : X ⟶ Y)).1 (by simp))\n\nlemma of_mono_eq_zero {X Y : C} (f : X ⟶ Y) [mono f] (h : f = 0) : is_zero X :=\nby { unfreezingI { subst h, }, apply of_mono_zero X Y, }\n\nlemma of_epi_eq_zero {X Y : C} (f : X ⟶ Y) [epi f] (h : f = 0) : is_zero Y :=\nby { unfreezingI { subst h, }, apply of_epi_zero X Y, }\n\nlemma iff_split_mono_eq_zero {X Y : C} (f : X ⟶ Y) [split_mono f] : is_zero X ↔ f = 0 :=\nbegin\n rw iff_id_eq_zero,\n split,\n { intro h, rw [←category.id_comp f, h, zero_comp], },\n { intro h, rw [←split_mono.id f], simp [h], },\nend\n\nlemma iff_split_epi_eq_zero {X Y : C} (f : X ⟶ Y) [split_epi f] : is_zero Y ↔ f = 0 :=\nbegin\n rw iff_id_eq_zero,\n split,\n { intro h, rw [←category.comp_id f, h, comp_zero], },\n { intro h, rw [←split_epi.id f], simp [h], },\nend\n\nlemma of_mono {X Y : C} (f : X ⟶ Y) [mono f] (i : is_zero Y) : is_zero X :=\nbegin\n unfreezingI { have hf := i.eq_zero_of_tgt f, subst hf, },\n exact is_zero.of_mono_zero X Y,\nend\n\nlemma of_epi {X Y : C} (f : X ⟶ Y) [epi f] (i : is_zero X) : is_zero Y :=\nbegin\n unfreezingI { have hf := i.eq_zero_of_src f, subst hf, },\n exact is_zero.of_epi_zero X Y,\nend\n\nend is_zero\n\n/-- A category with a zero object has zero morphisms.\n\n It is rarely a good idea to use this. Many categories that have a zero object have zero\n morphisms for some other reason, for example from additivity. Library code that uses\n `zero_morphisms_of_zero_object` will then be incompatible with these categories because\n the `has_zero_morphisms` instances will not be definitionally equal. For this reason library\n code should generally ask for an instance of `has_zero_morphisms` separately, even if it already\n asks for an instance of `has_zero_objects`. -/\ndef is_zero.has_zero_morphisms {O : C} (hO : is_zero O) : has_zero_morphisms C :=\n{ has_zero := λ X Y,\n { zero := hO.from X ≫ hO.to Y },\n zero_comp' := λ X Y Z f, by { rw category.assoc, congr, apply hO.eq_of_src, },\n comp_zero' := λ X Y Z f, by { rw ←category.assoc, congr, apply hO.eq_of_tgt, }}\n\nnamespace has_zero_object\n\nvariables [has_zero_object C]\nopen_locale zero_object\n\n/-- A category with a zero object has zero morphisms.\n\n It is rarely a good idea to use this. Many categories that have a zero object have zero\n morphisms for some other reason, for example from additivity. Library code that uses\n `zero_morphisms_of_zero_object` will then be incompatible with these categories because\n the `has_zero_morphisms` instances will not be definitionally equal. For this reason library\n code should generally ask for an instance of `has_zero_morphisms` separately, even if it already\n asks for an instance of `has_zero_objects`. -/\ndef zero_morphisms_of_zero_object : has_zero_morphisms C :=\n{ has_zero := λ X Y,\n { zero := (default : X ⟶ 0) ≫ default },\n zero_comp' := λ X Y Z f, by { dunfold has_zero.zero, rw category.assoc, congr, },\n comp_zero' := λ X Y Z f, by { dunfold has_zero.zero, rw ←category.assoc, congr, }}\n\nsection has_zero_morphisms\nvariables [has_zero_morphisms C]\n\n@[simp] lemma zero_iso_is_initial_hom {X : C} (t : is_initial X) :\n (zero_iso_is_initial t).hom = 0 :=\nby ext\n\n@[simp] lemma zero_iso_is_initial_inv {X : C} (t : is_initial X) :\n (zero_iso_is_initial t).inv = 0 :=\nby ext\n\n@[simp] lemma zero_iso_is_terminal_hom {X : C} (t : is_terminal X) :\n (zero_iso_is_terminal t).hom = 0 :=\nby ext\n\n@[simp] lemma zero_iso_is_terminal_inv {X : C} (t : is_terminal X) :\n (zero_iso_is_terminal t).inv = 0 :=\nby ext\n\n@[simp] lemma zero_iso_initial_hom [has_initial C] : zero_iso_initial.hom = (0 : 0 ⟶ ⊥_ C) :=\nby ext\n\n@[simp] lemma zero_iso_initial_inv [has_initial C] : zero_iso_initial.inv = (0 : ⊥_ C ⟶ 0) :=\nby ext\n\n@[simp] \n\n@[simp] lemma zero_iso_terminal_inv [has_terminal C] : zero_iso_terminal.inv = (0 : ⊤_ C ⟶ 0) :=\nby ext\n\nend has_zero_morphisms\n\nopen_locale zero_object\n\ninstance {B : Type*} [category B] : has_zero_object (B ⥤ C) :=\n(((category_theory.functor.const B).obj (0 : C)).is_zero $ λ X, is_zero_zero _).has_zero_object\n\nend has_zero_object\n\nopen_locale zero_object\n\nvariables {D}\n\n@[simp] lemma is_zero.map [has_zero_object D] [has_zero_morphisms D] {F : C ⥤ D} (hF : is_zero F)\n {X Y : C} (f : X ⟶ Y) : F.map f = 0 :=\n(hF.obj _).eq_of_src _ _\n\n@[simp] lemma _root_.category_theory.functor.zero_obj [has_zero_object D]\n (X : C) : is_zero ((0 : C ⥤ D).obj X) :=\n(is_zero_zero _).obj _\n\n@[simp] lemma _root_.category_theory.zero_map [has_zero_object D] [has_zero_morphisms D]\n {X Y : C} (f : X ⟶ Y) : (0 : C ⥤ D).map f = 0 :=\n(is_zero_zero _).map _\n\nsection\nvariables [has_zero_object C] [has_zero_morphisms C]\nopen_locale zero_object\n\n@[simp]\nlemma id_zero : 𝟙 (0 : C) = (0 : 0 ⟶ 0) :=\nby ext\n\n/-- An arrow ending in the zero object is zero -/\n-- This can't be a `simp` lemma because the left hand side would be a metavariable.\nlemma zero_of_to_zero {X : C} (f : X ⟶ 0) : f = 0 :=\nby ext\n\nlemma zero_of_target_iso_zero {X Y : C} (f : X ⟶ Y) (i : Y ≅ 0) : f = 0 :=\nbegin\n have h : f = f ≫ i.hom ≫ 𝟙 0 ≫ i.inv := by simp only [iso.hom_inv_id, id_comp, comp_id],\n simpa using h,\nend\n\n/-- An arrow starting at the zero object is zero -/\nlemma zero_of_from_zero {X : C} (f : 0 ⟶ X) : f = 0 :=\nby ext\n\nlemma zero_of_source_iso_zero {X Y : C} (f : X ⟶ Y) (i : X ≅ 0) : f = 0 :=\nbegin\n have h : f = i.hom ≫ 𝟙 0 ≫ i.inv ≫ f := by simp only [iso.hom_inv_id_assoc, id_comp, comp_id],\n simpa using h,\nend\n\nlemma zero_of_source_iso_zero' {X Y : C} (f : X ⟶ Y) (i : is_isomorphic X 0) : f = 0 :=\nzero_of_source_iso_zero f (nonempty.some i)\nlemma zero_of_target_iso_zero' {X Y : C} (f : X ⟶ Y) (i : is_isomorphic Y 0) : f = 0 :=\nzero_of_target_iso_zero f (nonempty.some i)\n\nlemma mono_of_source_iso_zero {X Y : C} (f : X ⟶ Y) (i : X ≅ 0) : mono f :=\n⟨λ Z g h w, by rw [zero_of_target_iso_zero g i, zero_of_target_iso_zero h i]⟩\n\nlemma epi_of_target_iso_zero {X Y : C} (f : X ⟶ Y) (i : Y ≅ 0) : epi f :=\n⟨λ Z g h w, by rw [zero_of_source_iso_zero g i, zero_of_source_iso_zero h i]⟩\n\n/--\nAn object `X` has `𝟙 X = 0` if and only if it is isomorphic to the zero object.\n\nBecause `X ≅ 0` contains data (even if a subsingleton), we express this `↔` as an `≃`.\n-/\ndef id_zero_equiv_iso_zero (X : C) : (𝟙 X = 0) ≃ (X ≅ 0) :=\n{ to_fun := λ h, { hom := 0, inv := 0, },\n inv_fun := λ i, zero_of_target_iso_zero (𝟙 X) i,\n left_inv := by tidy,\n right_inv := by tidy, }\n\n@[simp]\nlemma id_zero_equiv_iso_zero_apply_hom (X : C) (h : 𝟙 X = 0) :\n ((id_zero_equiv_iso_zero X) h).hom = 0 := rfl\n\n@[simp]\nlemma id_zero_equiv_iso_zero_apply_inv (X : C) (h : 𝟙 X = 0) :\n ((id_zero_equiv_iso_zero X) h).inv = 0 := rfl\n\n/-- If `0 : X ⟶ Y` is an monomorphism, then `X ≅ 0`. -/\n@[simps]\ndef iso_zero_of_mono_zero {X Y : C} (h : mono (0 : X ⟶ Y)) : X ≅ 0 :=\n{ hom := 0,\n inv := 0,\n hom_inv_id' := (cancel_mono (0 : X ⟶ Y)).mp (by simp) }\n\n/-- If `0 : X ⟶ Y` is an epimorphism, then `Y ≅ 0`. -/\n@[simps]\ndef iso_zero_of_epi_zero {X Y : C} (h : epi (0 : X ⟶ Y)) : Y ≅ 0 :=\n{ hom := 0,\n inv := 0,\n hom_inv_id' := (cancel_epi (0 : X ⟶ Y)).mp (by simp) }\n\n/-- If a monomorphism out of `X` is zero, then `X ≅ 0`. -/\ndef iso_zero_of_mono_eq_zero {X Y : C} {f : X ⟶ Y} [mono f] (h : f = 0) : X ≅ 0 :=\nby { unfreezingI { subst h, }, apply iso_zero_of_mono_zero ‹_›, }\n\n/-- If an epimorphism in to `Y` is zero, then `Y ≅ 0`. -/\ndef iso_zero_of_epi_eq_zero {X Y : C} {f : X ⟶ Y} [epi f] (h : f = 0) : Y ≅ 0 :=\nby { unfreezingI { subst h, }, apply iso_zero_of_epi_zero ‹_›, }\n\n/-- If an object `X` is isomorphic to 0, there's no need to use choice to construct\nan explicit isomorphism: the zero morphism suffices. -/\ndef iso_of_is_isomorphic_zero {X : C} (P : is_isomorphic X 0) : X ≅ 0 :=\n{ hom := 0,\n inv := 0,\n hom_inv_id' :=\n begin\n casesI P,\n rw ←P.hom_inv_id,\n rw ←category.id_comp P.inv,\n simp,\n end,\n inv_hom_id' := by simp, }\n\nend\n\nsection is_iso\nvariables [has_zero_morphisms C]\n\n/--\nA zero morphism `0 : X ⟶ Y` is an isomorphism if and only if\nthe identities on both `X` and `Y` are zero.\n-/\n@[simps]\ndef is_iso_zero_equiv (X Y : C) : is_iso (0 : X ⟶ Y) ≃ (𝟙 X = 0 ∧ 𝟙 Y = 0) :=\n{ to_fun := by { introsI i, rw ←is_iso.hom_inv_id (0 : X ⟶ Y),\n rw ←is_iso.inv_hom_id (0 : X ⟶ Y), simp },\n inv_fun := λ h, ⟨⟨(0 : Y ⟶ X), by tidy⟩⟩,\n left_inv := by tidy,\n right_inv := by tidy, }\n\n/--\nA zero morphism `0 : X ⟶ X` is an isomorphism if and only if\nthe identity on `X` is zero.\n-/\ndef is_iso_zero_self_equiv (X : C) : is_iso (0 : X ⟶ X) ≃ (𝟙 X = 0) :=\nby simpa using is_iso_zero_equiv X X\n\nvariables [has_zero_object C]\nopen_locale zero_object\n\n/--\nA zero morphism `0 : X ⟶ Y` is an isomorphism if and only if\n`X` and `Y` are isomorphic to the zero object.\n-/\ndef is_iso_zero_equiv_iso_zero (X Y : C) : is_iso (0 : X ⟶ Y) ≃ (X ≅ 0) × (Y ≅ 0) :=\nbegin\n -- This is lame, because `prod` can't cope with `Prop`, so we can't use `equiv.prod_congr`.\n refine (is_iso_zero_equiv X Y).trans _,\n symmetry,\n fsplit,\n { rintros ⟨eX, eY⟩, fsplit,\n exact (id_zero_equiv_iso_zero X).symm eX,\n exact (id_zero_equiv_iso_zero Y).symm eY, },\n { rintros ⟨hX, hY⟩, fsplit,\n exact (id_zero_equiv_iso_zero X) hX,\n exact (id_zero_equiv_iso_zero Y) hY, },\n { tidy, },\n { tidy, },\nend\n\nlemma is_iso_of_source_target_iso_zero {X Y : C} (f : X ⟶ Y) (i : X ≅ 0) (j : Y ≅ 0) : is_iso f :=\nbegin\n rw zero_of_source_iso_zero f i,\n exact (is_iso_zero_equiv_iso_zero _ _).inv_fun ⟨i, j⟩,\nend\n\n/--\nA zero morphism `0 : X ⟶ X` is an isomorphism if and only if\n`X` is isomorphic to the zero object.\n-/\ndef is_iso_zero_self_equiv_iso_zero (X : C) : is_iso (0 : X ⟶ X) ≃ (X ≅ 0) :=\n(is_iso_zero_equiv_iso_zero X X).trans subsingleton_prod_self_equiv\n\nend is_iso\n\n/-- If there are zero morphisms, any initial object is a zero object. -/\nlemma has_zero_object_of_has_initial_object\n [has_zero_morphisms C] [has_initial C] : has_zero_object C :=\nbegin\n refine ⟨⟨⊥_ C, λ X, ⟨⟨⟨0⟩, by tidy⟩⟩, λ X, ⟨⟨⟨0⟩, λ f, _⟩⟩⟩⟩,\n calc\n f = f ≫ 𝟙 _ : (category.comp_id _).symm\n ... = f ≫ 0 : by congr\n ... = 0 : has_zero_morphisms.comp_zero _ _\nend\n\n/-- If there are zero morphisms, any terminal object is a zero object. -/\nlemma has_zero_object_of_has_terminal_object\n [has_zero_morphisms C] [has_terminal C] : has_zero_object C :=\nbegin\n refine ⟨⟨⊤_ C, λ X, ⟨⟨⟨0⟩, λ f, _⟩⟩, λ X, ⟨⟨⟨0⟩, by tidy⟩⟩⟩⟩,\n calc\n f = 𝟙 _ ≫ f : (category.id_comp _).symm\n ... = 0 ≫ f : by congr\n ... = 0 : zero_comp\nend\n\n\nsection image\nvariable [has_zero_morphisms C]\n\nlemma image_ι_comp_eq_zero {X Y Z : C} {f : X ⟶ Y} {g : Y ⟶ Z} [has_image f]\n [epi (factor_thru_image f)] (h : f ≫ g = 0) : image.ι f ≫ g = 0 :=\nzero_of_epi_comp (factor_thru_image f) $ by simp [h]\n\nlemma comp_factor_thru_image_eq_zero {X Y Z : C} {f : X ⟶ Y} {g : Y ⟶ Z} [has_image g]\n (h : f ≫ g = 0) : f ≫ factor_thru_image g = 0 :=\nzero_of_comp_mono (image.ι g) $ by simp [h]\n\nvariables [has_zero_object C]\nopen_locale zero_object\n\n/--\nThe zero morphism has a `mono_factorisation` through the zero object.\n-/\n@[simps]\ndef mono_factorisation_zero (X Y : C) : mono_factorisation (0 : X ⟶ Y) :=\n{ I := 0, m := 0, e := 0, }\n\n/--\nThe factorisation through the zero object is an image factorisation.\n-/\ndef image_factorisation_zero (X Y : C) : image_factorisation (0 : X ⟶ Y) :=\n{ F := mono_factorisation_zero X Y,\n is_image := { lift := λ F', 0 } }\n\n\ninstance has_image_zero {X Y : C} : has_image (0 : X ⟶ Y) :=\nhas_image.mk $ image_factorisation_zero _ _\n\n/-- The image of a zero morphism is the zero object. -/\ndef image_zero {X Y : C} : image (0 : X ⟶ Y) ≅ 0 :=\nis_image.iso_ext (image.is_image (0 : X ⟶ Y)) (image_factorisation_zero X Y).is_image\n\n/-- The image of a morphism which is equal to zero is the zero object. -/\ndef image_zero' {X Y : C} {f : X ⟶ Y} (h : f = 0) [has_image f] : image f ≅ 0 :=\nimage.eq_to_iso h ≪≫ image_zero\n\n@[simp]\nlemma image.ι_zero {X Y : C} [has_image (0 : X ⟶ Y)] : image.ι (0 : X ⟶ Y) = 0 :=\nbegin\n rw ←image.lift_fac (mono_factorisation_zero X Y),\n simp,\nend\n\n/--\nIf we know `f = 0`,\nit requires a little work to conclude `image.ι f = 0`,\nbecause `f = g` only implies `image f ≅ image g`.\n-/\n@[simp]\nlemma image.ι_zero' [has_equalizers C] {X Y : C} {f : X ⟶ Y} (h : f = 0) [has_image f] :\n image.ι f = 0 :=\nby { rw image.eq_fac h, simp }\n\nend image\n\n/-- In the presence of zero morphisms, coprojections into a coproduct are (split) monomorphisms. -/\ninstance split_mono_sigma_ι\n {β : Type v} [has_zero_morphisms C]\n (f : β → C) [has_colimit (discrete.functor f)] (b : β) : split_mono (sigma.ι f b) :=\n{ retraction := sigma.desc (λ b', if h : b' = b then eq_to_hom (congr_arg f h) else 0), }\n\n/-- In the presence of zero morphisms, projections into a product are (split) epimorphisms. -/\ninstance split_epi_pi_π\n {β : Type v} [has_zero_morphisms C]\n (f : β → C) [has_limit (discrete.functor f)] (b : β) : split_epi (pi.π f b) :=\n{ section_ := pi.lift (λ b', if h : b = b' then eq_to_hom (congr_arg f h) else 0), }\n\n/-- In the presence of zero morphisms, coprojections into a coproduct are (split) monomorphisms. -/\ninstance split_mono_coprod_inl\n [has_zero_morphisms C] {X Y : C} [has_colimit (pair X Y)] :\n split_mono (coprod.inl : X ⟶ X ⨿ Y) :=\n{ retraction := coprod.desc (𝟙 X) 0, }\n/-- In the presence of zero morphisms, coprojections into a coproduct are (split) monomorphisms. -/\ninstance split_mono_coprod_inr\n [has_zero_morphisms C] {X Y : C} [has_colimit (pair X Y)] :\n split_mono (coprod.inr : Y ⟶ X ⨿ Y) :=\n{ retraction := coprod.desc 0 (𝟙 Y), }\n\n/-- In the presence of zero morphisms, projections into a product are (split) epimorphisms. -/\ninstance split_epi_prod_fst\n [has_zero_morphisms C] {X Y : C} [has_limit (pair X Y)] :\n split_epi (prod.fst : X ⨯ Y ⟶ X) :=\n{ section_ := prod.lift (𝟙 X) 0, }\n/-- In the presence of zero morphisms, projections into a product are (split) epimorphisms. -/\ninstance split_epi_prod_snd\n [has_zero_morphisms C] {X Y : C} [has_limit (pair X Y)] :\n split_epi (prod.snd : X ⨯ Y ⟶ Y) :=\n{ section_ := prod.lift 0 (𝟙 Y), }\n\nend category_theory.limits\n", "meta": {"author": "nick-kuhn", "repo": "leantools", "sha": "567a98c031fffe3f270b7b8dea48389bc70d7abb", "save_path": "github-repos/lean/nick-kuhn-leantools", "path": "github-repos/lean/nick-kuhn-leantools/leantools-567a98c031fffe3f270b7b8dea48389bc70d7abb/src/category_theory/limits/shapes/zero_morphisms.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48047867804790706, "lm_q2_score": 0.08632348305031282, "lm_q1q2_score": 0.041476593020505215}} {"text": "/-\nCopyright (c) 2020 Simon Hudon. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Simon Hudon\n-/\n\nimport order.omega_complete_partial_order\nimport category_theory.limits.shapes.products\nimport category_theory.limits.shapes.equalizers\nimport category_theory.limits.constructions.limits_of_products_and_equalizers\nimport category_theory.concrete_category.bundled_hom\n\n/-!\n# Category of types with a omega complete partial order\n\nIn this file, we bundle the class `omega_complete_partial_order` into a\nconcrete category and prove that continuous functions also form\na `omega_complete_partial_order`.\n\n## Main definitions\n\n * `ωCPO`\n * an instance of `category` and `concrete_category`\n\n -/\n\nopen category_theory\n\nuniverses u v\n\n/-- The category of types with a omega complete partial order. -/\ndef ωCPO : Type (u+1) := bundled omega_complete_partial_order\n\nnamespace ωCPO\n\nopen omega_complete_partial_order\n\ninstance : bundled_hom @continuous_hom :=\n{ to_fun := @continuous_hom.simps.apply,\n id := @continuous_hom.id,\n comp := @continuous_hom.comp,\n hom_ext := @continuous_hom.coe_inj }\n\nattribute [derive [large_category, concrete_category]] ωCPO\n\ninstance : has_coe_to_sort ωCPO Type* := bundled.has_coe_to_sort\n\n/-- Construct a bundled ωCPO from the underlying type and typeclass. -/\ndef of (α : Type*) [omega_complete_partial_order α] : ωCPO := bundled.of α\n\n@[simp] lemma coe_of (α : Type*) [omega_complete_partial_order α] : ↥(of α) = α := rfl\n\ninstance : inhabited ωCPO := ⟨of punit⟩\n\ninstance (α : ωCPO) : omega_complete_partial_order α := α.str\n\nsection\n\nopen category_theory.limits\n\nnamespace has_products\n\n/-- The pi-type gives a cone for a product. -/\ndef product {J : Type v} (f : J → ωCPO.{v}) : fan f :=\nfan.mk (of (Π j, f j)) (λ j, continuous_hom.of_mono (pi.eval_order_hom j) (λ c, rfl))\n\n/-- The pi-type is a limit cone for the product. -/\ndef is_product (J : Type v) (f : J → ωCPO) : is_limit (product f) :=\n{ lift := λ s,\n ⟨⟨λ t j, s.π.app ⟨j⟩ t, λ x y h j, (s.π.app ⟨j⟩).monotone h⟩,\n λ x, funext (λ j, (s.π.app ⟨j⟩).continuous x)⟩,\n uniq' := λ s m w,\n begin\n ext t j,\n change m t j = s.π.app ⟨j⟩ t,\n rw ← w ⟨j⟩,\n refl,\n end,\n fac' := λ s j, by { cases j, tidy, } }.\n\ninstance (J : Type v) (f : J → ωCPO.{v}) : has_product f :=\nhas_limit.mk ⟨_, is_product _ f⟩\n\nend has_products\n\ninstance omega_complete_partial_order_equalizer\n {α β : Type*} [omega_complete_partial_order α] [omega_complete_partial_order β]\n (f g : α →𝒄 β) : omega_complete_partial_order {a : α // f a = g a} :=\nomega_complete_partial_order.subtype _ $ λ c hc,\nbegin\n rw [f.continuous, g.continuous],\n congr' 1,\n ext,\n apply hc _ ⟨_, rfl⟩,\nend\n\nnamespace has_equalizers\n\n/-- The equalizer inclusion function as a `continuous_hom`. -/\ndef equalizer_ι {α β : Type*} [omega_complete_partial_order α] [omega_complete_partial_order β]\n (f g : α →𝒄 β) :\n {a : α // f a = g a} →𝒄 α :=\ncontinuous_hom.of_mono (order_hom.subtype.val _) (λ c, rfl)\n\n/-- A construction of the equalizer fork. -/\ndef equalizer {X Y : ωCPO.{v}} (f g : X ⟶ Y) :\n fork f g :=\n@fork.of_ι _ _ _ _ _ _ (ωCPO.of {a // f a = g a}) (equalizer_ι f g)\n (continuous_hom.ext _ _ (λ x, x.2))\n\n/-- The equalizer fork is a limit. -/\ndef is_equalizer {X Y : ωCPO.{v}} (f g : X ⟶ Y) : is_limit (equalizer f g) :=\nfork.is_limit.mk' _ $ λ s,\n⟨{ to_fun := λ x, ⟨s.ι x, by apply continuous_hom.congr_fun s.condition⟩,\n monotone' := λ x y h, s.ι.monotone h,\n cont := λ x, subtype.ext (s.ι.continuous x) },\n by { ext, refl },\n λ m hm,\n begin\n ext,\n apply continuous_hom.congr_fun hm,\n end⟩\n\nend has_equalizers\n\ninstance : has_products.{v} ωCPO.{v} :=\nλ J, { has_limit := λ F, has_limit_of_iso discrete.nat_iso_functor.symm }\n\ninstance {X Y : ωCPO.{v}} (f g : X ⟶ Y) : has_limit (parallel_pair f g) :=\nhas_limit.mk ⟨_, has_equalizers.is_equalizer f g⟩\n\ninstance : has_equalizers ωCPO.{v} := has_equalizers_of_has_limit_parallel_pair _\n\ninstance : has_limits ωCPO.{v} := has_limits_of_has_equalizers_and_products\n\nend\n\n\nend ωCPO\n", "meta": {"author": "leanprover-community", "repo": "mathlib", "sha": "5e526d18cea33550268dcbbddcb822d5cde40654", "save_path": "github-repos/lean/leanprover-community-mathlib", "path": "github-repos/lean/leanprover-community-mathlib/mathlib-5e526d18cea33550268dcbbddcb822d5cde40654/src/order/category/omega_complete_partial_order.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.08269734832693713, "lm_q1q2_score": 0.04134867416346857}} {"text": "/-\nCopyright (c) 2017 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Leonardo de Moura\n-/\nprelude\nimport init.data.bool\n\n/-\nSimplification lemmas for ite.\n\nWe don't prove them at logic.lean because it is easier to prove them using\nthe tactic framework.\n-/\n\n@[simp] lemma if_true_right_eq_or (p : Prop) [h : decidable p] (q : Prop) : (if p then q else true) = (¬p ∨ q) :=\nby by_cases p; simp [h]\n\n@[simp] lemma if_true_left_eq_or (p : Prop) [h : decidable p] (q : Prop) : (if p then true else q) = (p ∨ q) :=\nby by_cases p; simp [h]\n\n@[simp] lemma if_false_right_eq_and (p : Prop) [h : decidable p] (q : Prop) : (if p then q else false) = (p ∧ q) :=\nby by_cases p; simp [h]\n\n@[simp] lemma if_false_left_eq_and (p : Prop) [h : decidable p] (q : Prop) : (if p then false else q) = (¬p ∧ q) :=\nby by_cases p; simp [h]\n", "meta": {"author": "subfish-zhou", "repo": "N2Lean", "sha": "8e858cc5b01f1ad921094dc355db3cb9473a42fd", "save_path": "github-repos/lean/subfish-zhou-N2Lean", "path": "github-repos/lean/subfish-zhou-N2Lean/N2Lean-8e858cc5b01f1ad921094dc355db3cb9473a42fd/library/init/ite_simp.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46101677931231594, "lm_q2_score": 0.08882028878220906, "lm_q1q2_score": 0.04094764347196384}} {"text": "/-\nCopyright (c) 2020 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Leonardo de Moura, Mario Carneiro\n-/\nprelude\nimport Init.Prelude\nset_option linter.missingDocs true -- keep it documented\n\n/-!\n# Coercion\n\nLean uses a somewhat elaborate system of typeclasses to drive the coercion system.\nHere a *coercion* means an invisible function that is automatically inserted\nto fix what would otherwise be a type error. For example, if we have:\n```\ndef f (x : Nat) : Int := x\n```\nthen this is clearly not type correct as is, because `x` has type `Nat` but\ntype `Int` is expected, and normally you will get an error message saying exactly that.\nBut before it shows that message, it will attempt to synthesize an instance of\n`CoeT Nat x Int`, which will end up going through all the other typeclasses defined\nbelow, to discover that there is an instance of `Coe Nat Int` defined.\n\nThis instance is defined as:\n```\ninstance : Coe Nat Int := ⟨Int.ofNat⟩\n```\nso Lean will elaborate the original function `f` as if it said:\n```\ndef f (x : Nat) : Int := Int.ofNat x\n```\nwhich is not a type error anymore.\n\nYou can also use the `↑` operator to explicitly indicate a coercion. Using `↑x`\ninstead of `x` in the example will result in the same output.\n\nBecause there are many polymorphic functions in Lean, it is often ambiguous where\nthe coercion can go. For example:\n```\ndef f (x y : Nat) : Int := x + y\n```\nThis could be either `↑x + ↑y` where `+` is the addition on `Int`, or `↑(x + y)`\nwhere `+` is addition on `Nat`, or even `x + y` using a heterogeneous addition\nwith the type `Nat → Nat → Int`. You can use the `↑` operator to disambiguate\nbetween these possibilities, but generally Lean will elaborate working from the\n\"outside in\", meaning that it will first look at the expression `_ + _ : Int`\nand assign the `+` to be the one for `Int`, and then need to insert coercions\nfor the subterms `↑x : Int` and `↑y : Int`, resulting in the `↑x + ↑y` version.\n\nNote that unlike most operators like `+`, `↑` is always eagerly unfolded at\nparse time into its definition. So if we look at the definition of `f` from\nbefore, we see no trace of the `CoeT.coe` function:\n```\ndef f (x : Nat) : Int := x\n#print f\n-- def f : Nat → Int :=\n-- fun (x : Nat) => Int.ofNat x\n```\n\n## Important typeclasses\n\nLean resolves a coercion by either inserting a `CoeDep` instance\nor chaining `CoeHead? CoeOut* Coe* CoeTail?` instances.\n(That is, zero or one `CoeHead` instances, an arbitrary number of `CoeOut`\ninstances, etc.)\n\nThe `CoeHead? CoeOut*` instances are chained from the \"left\" side.\nSo if Lean looks for a coercion from `Nat` to `Int`, it starts by trying coerce\n`Nat` using `CoeHead` by looking for a `CoeHead Nat ?α` instance, and then\ncontinuing with `CoeOut`. Similarly `Coe* CoeTail?` are chained from the \"right\".\n\nThese classes should be implemented for coercions:\n\n* `Coe α β` is the most basic class, and the usual one you will want to use\n when implementing a coercion for your own types.\n The variables in the type `α` must be a subset of the variables in `β`\n (or out-params of type class parameters),\n because `Coe` is chained right-to-left.\n\n* `CoeOut α β` is like `Coe α β` but chained left-to-right.\n Use this if the variables in the type `α` are a superset of the variables in `β`.\n\n* `CoeTail α β` is like `Coe α β`, but only applied once.\n Use this for coercions that would cause loops, like `[Ring R] → CoeTail Nat R`.\n\n* `CoeHead α β` is similar to `CoeOut α β`, but only applied once.\n Use this for coercions that would cause loops, like `[SetLike S α] → CoeHead S (Set α)`.\n\n* `CoeDep α (x : α) β` allows `β` to depend not only on `α` but on the value\n `x : α` itself. This is useful when the coercion function is dependent.\n An example of a dependent coercion is the instance for `Prop → Bool`, because\n it only holds for `Decidable` propositions. It is defined as:\n ```\n instance (p : Prop) [Decidable p] : CoeDep Prop p Bool := ...\n ```\n\n* `CoeFun α (γ : α → Sort v)` is a coercion to a function. `γ a` should be a\n (coercion-to-)function type, and this is triggered whenever an element\n `f : α` appears in an application like `f x` which would not make sense since\n `f` does not have a function type.\n `CoeFun` instances apply to `CoeOut` as well.\n\n* `CoeSort α β` is a coercion to a sort. `β` must be a universe, and if\n `a : α` appears in a place where a type is expected, like `(x : a)` or `a → a`.\n `CoeSort` instances apply to `CoeOut` as well.\n\nOn top of these instances this file defines several auxiliary type classes:\n * `CoeTC := Coe*`\n * `CoeOTC := CoeOut* Coe*`\n * `CoeHTC := CoeHead? CoeOut* Coe*`\n * `CoeHTCT := CoeHead? CoeOut* Coe* CoeTail?`\n * `CoeDep := CoeHead? CoeOut* Coe* CoeTail? | CoeDep`\n\n-/\n\nuniverse u v w w'\n\n/--\n`Coe α β` is the typeclass for coercions from `α` to `β`. It can be transitively\nchained with other `Coe` instances, and coercion is automatically used when\n`x` has type `α` but it is used in a context where `β` is expected.\nYou can use the `↑x` operator to explicitly trigger coercion.\n-/\nclass Coe (α : Sort u) (β : Sort v) where\n /-- Coerces a value of type `α` to type `β`. Accessible by the notation `↑x`,\n or by double type ascription `((x : α) : β)`. -/\n coe : α → β\nattribute [coe_decl] Coe.coe\n\n/--\nAuxiliary class implementing `Coe*`.\nUsers should generally not implement this directly.\n-/\nclass CoeTC (α : Sort u) (β : Sort v) where\n /-- Coerces a value of type `α` to type `β`. Accessible by the notation `↑x`,\n or by double type ascription `((x : α) : β)`. -/\n coe : α → β\nattribute [coe_decl] CoeTC.coe\n\ninstance [Coe β γ] [CoeTC α β] : CoeTC α γ where coe a := Coe.coe (CoeTC.coe a : β)\ninstance [Coe α β] : CoeTC α β where coe a := Coe.coe a\ninstance : CoeTC α α where coe a := a\n\n/--\n`CoeOut α β` is for coercions that are applied from left-to-right.\n-/\nclass CoeOut (α : Sort u) (β : Sort v) where\n /-- Coerces a value of type `α` to type `β`. Accessible by the notation `↑x`,\n or by double type ascription `((x : α) : β)`. -/\n coe : α → β\nattribute [coe_decl] CoeOut.coe\n\n/--\nAuxiliary class implementing `CoeOut* Coe*`.\nUsers should generally not implement this directly.\n-/\nclass CoeOTC (α : Sort u) (β : Sort v) where\n /-- Coerces a value of type `α` to type `β`. Accessible by the notation `↑x`,\n or by double type ascription `((x : α) : β)`. -/\n coe : α → β\nattribute [coe_decl] CoeOTC.coe\n\ninstance [CoeOut α β] [CoeOTC β γ] : CoeOTC α γ where coe a := CoeOTC.coe (CoeOut.coe a : β)\ninstance [CoeTC α β] : CoeOTC α β where coe a := CoeTC.coe a\ninstance : CoeOTC α α where coe a := a\n\n-- Note: ^^ We add reflexivity instances for CoeOTC/etc. so that we avoid going\n-- through a user-defined CoeTC/etc. instance. (Instances like\n-- `CoeTC F (A →+ B)` apply even when the two sides are defeq.)\n\n/--\n`CoeHead α β` is for coercions that are applied from left-to-right at most once\nat beginning of the coercion chain.\n-/\nclass CoeHead (α : Sort u) (β : Sort v) where\n /-- Coerces a value of type `α` to type `β`. Accessible by the notation `↑x`,\n or by double type ascription `((x : α) : β)`. -/\n coe : α → β\nattribute [coe_decl] CoeHead.coe\n\n/--\nAuxiliary class implementing `CoeHead CoeOut* Coe*`.\nUsers should generally not implement this directly.\n-/\nclass CoeHTC (α : Sort u) (β : Sort v) where\n /-- Coerces a value of type `α` to type `β`. Accessible by the notation `↑x`,\n or by double type ascription `((x : α) : β)`. -/\n coe : α → β\nattribute [coe_decl] CoeHTC.coe\n\ninstance [CoeHead α β] [CoeOTC β γ] : CoeHTC α γ where coe a := CoeOTC.coe (CoeHead.coe a : β)\ninstance [CoeOTC α β] : CoeHTC α β where coe a := CoeOTC.coe a\ninstance : CoeHTC α α where coe a := a\n\n/--\n`CoeTail α β` is for coercions that can only appear at the end of a\nsequence of coercions. That is, `α` can be further coerced via `Coe σ α` and\n`CoeHead τ σ` instances but `β` will only be the expected type of the expression.\n-/\nclass CoeTail (α : Sort u) (β : Sort v) where\n /-- Coerces a value of type `α` to type `β`. Accessible by the notation `↑x`,\n or by double type ascription `((x : α) : β)`. -/\n coe : α → β\nattribute [coe_decl] CoeTail.coe\n\n/--\nAuxiliary class implementing `CoeHead* Coe* CoeTail?`.\nUsers should generally not implement this directly.\n-/\nclass CoeHTCT (α : Sort u) (β : Sort v) where\n /-- Coerces a value of type `α` to type `β`. Accessible by the notation `↑x`,\n or by double type ascription `((x : α) : β)`. -/\n coe : α → β\nattribute [coe_decl] CoeHTCT.coe\n\ninstance [CoeTail β γ] [CoeHTC α β] : CoeHTCT α γ where coe a := CoeTail.coe (CoeHTC.coe a : β)\ninstance [CoeHTC α β] : CoeHTCT α β where coe a := CoeHTC.coe a\ninstance : CoeHTCT α α where coe a := a\n\n/--\n`CoeDep α (x : α) β` is a typeclass for dependent coercions, that is, the type `β`\ncan depend on `x` (or rather, the value of `x` is available to typeclass search\nso an instance that relates `β` to `x` is allowed).\n\nDependent coercions do not participate in the transitive chaining process of\nregular coercions: they must exactly match the type mismatch on both sides.\n-/\nclass CoeDep (α : Sort u) (_ : α) (β : Sort v) where\n /-- The resulting value of type `β`. The input `x : α` is a parameter to\n the type class, so the value of type `β` may possibly depend on additional\n typeclasses on `x`. -/\n coe : β\nattribute [coe_decl] CoeDep.coe\n\n/--\n`CoeT` is the core typeclass which is invoked by Lean to resolve a type error.\nIt can also be triggered explicitly with the notation `↑x` or by double type\nascription `((x : α) : β)`.\n\nA `CoeT` chain has the grammar `CoeHead? CoeOut* Coe* CoeTail? | CoeDep`.\n-/\nclass CoeT (α : Sort u) (_ : α) (β : Sort v) where\n /-- The resulting value of type `β`. The input `x : α` is a parameter to\n the type class, so the value of type `β` may possibly depend on additional\n typeclasses on `x`. -/\n coe : β\nattribute [coe_decl] CoeT.coe\n\ninstance [CoeHTCT α β] : CoeT α a β where coe := CoeHTCT.coe a\ninstance [CoeDep α a β] : CoeT α a β where coe := CoeDep.coe a\ninstance : CoeT α a α where coe := a\n\n/--\n`CoeFun α (γ : α → Sort v)` is a coercion to a function. `γ a` should be a\n(coercion-to-)function type, and this is triggered whenever an element\n`f : α` appears in an application like `f x` which would not make sense since\n`f` does not have a function type. This is automatically turned into `CoeFun.coe f x`.\n-/\nclass CoeFun (α : Sort u) (γ : outParam (α → Sort v)) where\n /-- Coerces a value `f : α` to type `γ f`, which should be either be a\n function type or another `CoeFun` type, in order to resolve a mistyped\n application `f x`. -/\n coe : (f : α) → γ f\nattribute [coe_decl] CoeFun.coe\n\ninstance [CoeFun α fun _ => β] : CoeOut α β where coe a := CoeFun.coe a\n\n/--\n`CoeSort α β` is a coercion to a sort. `β` must be a universe, and if\n`a : α` appears in a place where a type is expected, like `(x : a)` or `a → a`,\nthen it will be turned into `(x : CoeSort.coe a)`.\n-/\nclass CoeSort (α : Sort u) (β : outParam (Sort v)) where\n /-- Coerces a value of type `α` to `β`, which must be a universe. -/\n coe : α → β\nattribute [coe_decl] CoeSort.coe\n\ninstance [CoeSort α β] : CoeOut α β where coe a := CoeSort.coe a\n\n/--\n`↑x` represents a coercion, which converts `x` of type `α` to type `β`, using\ntypeclasses to resolve a suitable conversion function. You can often leave the\n`↑` off entirely, since coercion is triggered implicitly whenever there is a\ntype error, but in ambiguous cases it can be useful to use `↑` to disambiguate\nbetween e.g. `↑x + ↑y` and `↑(x + y)`.\n-/\nsyntax:1024 (name := coeNotation) \"↑\" term:1024 : term\n\n/-! # Basic instances -/\n\ninstance boolToProp : Coe Bool Prop where\n coe b := Eq b true\n\ninstance boolToSort : CoeSort Bool Prop where\n coe b := b\n\ninstance decPropToBool (p : Prop) [Decidable p] : CoeDep Prop p Bool where\n coe := decide p\n\ninstance optionCoe {α : Type u} : Coe α (Option α) where\n coe := some\n\ninstance subtypeCoe {α : Sort u} {p : α → Prop} : CoeOut (Subtype p) α where\n coe v := v.val\n\n/-! # Coe bridge -/\n\n/--\nHelper definition used by the elaborator. It is not meant to be used directly by users.\n\nThis is used for coercions between monads, in the case where we want to apply\na monad lift and a coercion on the result type at the same time.\n-/\n@[inline, coe_decl] def Lean.Internal.liftCoeM {m : Type u → Type v} {n : Type u → Type w} {α β : Type u}\n [MonadLiftT m n] [∀ a, CoeT α a β] [Monad n] (x : m α) : n β := do\n let a ← liftM x\n pure (CoeT.coe a)\n\n/--\nHelper definition used by the elaborator. It is not meant to be used directly by users.\n\nThis is used for coercing the result type under a monad.\n-/\n@[inline, coe_decl] def Lean.Internal.coeM {m : Type u → Type v} {α β : Type u}\n [∀ a, CoeT α a β] [Monad m] (x : m α) : m β := do\n let a ← x\n pure (CoeT.coe a)\n", "meta": {"author": "leanprover", "repo": "lean4", "sha": "742d053a97bdd109a41a921facd1cd6a55e89bc7", "save_path": "github-repos/lean/leanprover-lean4", "path": "github-repos/lean/leanprover-lean4/lean4-742d053a97bdd109a41a921facd1cd6a55e89bc7/src/Init/Coe.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3886180267058489, "lm_q2_score": 0.10521053249464328, "lm_q1q2_score": 0.04088670952673987}} {"text": "/-\nCopyright (c) 2021 Eric Wieser. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Eric Wieser\n-/\nimport data.set.basic\nimport tactic.monotonicity.basic\n\n/-!\n# Typeclass for a type `A` with an injective map to `set B`\n\nThis typeclass is primarily for use by subobjects like `submonoid` and `submodule`.\n\nA typical subobject should be declared as:\n```\nstructure my_subobject (X : Type*) :=\n(carrier : set X)\n(op_mem : ∀ {x : X}, x ∈ carrier → sorry ∈ carrier)\n\nnamespace my_subobject\n\nvariables (X : Type*)\n\ninstance : set_like (my_subobject X) X :=\n⟨sub_mul_action.carrier, λ p q h, by cases p; cases q; congr'⟩\n\n@[simp] lemma mem_carrier {p : my_subobject X} : x ∈ p.carrier ↔ x ∈ (p : set X) := iff.rfl\n\n@[ext] theorem ext {p q : my_subobject X} (h : ∀ x, x ∈ p ↔ x ∈ q) : p = q := set_like.ext h\n\n/-- Copy of a `my_subobject` with a new `carrier` equal to the old one. Useful to fix definitional\nequalities. -/\nprotected def copy (p : my_subobject X) (s : set X) (hs : s = ↑p) : my_subobject X :=\n{ carrier := s,\n op_mem' := hs.symm ▸ p.op_mem' }\n\nend my_subobject\n```\n\nThis file will then provide a `coe_sort`, a `coe` to set, a `partial_order`, and various\nextensionality and simp lemmas.\n\n-/\nset_option old_structure_cmd true\n\n/-- A class to indicate that there is a canonical injection between `A` and `set B`. -/\n@[protect_proj]\nclass set_like (A : Type*) (B : out_param $ Type*) :=\n(coe : A → set B)\n(coe_injective' : function.injective coe)\n\nnamespace set_like\n\nvariables {A : Type*} {B : Type*} [i : set_like A B]\n\ninclude i\n\ninstance : has_coe_t A (set B) := ⟨set_like.coe⟩\n\n@[priority 100]\ninstance : has_mem B A := ⟨λ x p, x ∈ (p : set B)⟩\n\n-- `dangerous_instance` does not know that `B` is used only as an `out_param`\n@[nolint dangerous_instance, priority 100]\ninstance : has_coe_to_sort A := ⟨_, λ p, {x : B // x ∈ p}⟩\n\nvariables (p q : A)\n\n@[simp, norm_cast] theorem coe_sort_coe : ↥(p : set B) = p := rfl\n\nvariables {p q}\n\nprotected theorem «exists» {q : p → Prop} :\n (∃ x, q x) ↔ (∃ x ∈ p, q ⟨x, ‹_›⟩) := set_coe.exists\n\nprotected theorem «forall» {q : p → Prop} :\n (∀ x, q x) ↔ (∀ x ∈ p, q ⟨x, ‹_›⟩) := set_coe.forall\n\ntheorem coe_injective : function.injective (coe : A → set B) :=\nλ x y h, set_like.coe_injective' h\n\n@[simp, norm_cast] theorem coe_set_eq : (p : set B) = q ↔ p = q := coe_injective.eq_iff\n\ntheorem ext' (h : (p : set B) = q) : p = q := coe_injective h\n\ntheorem ext'_iff : p = q ↔ (p : set B) = q := coe_set_eq.symm\n\n/-- Note: implementers of `set_like` must copy this lemma in order to tag it with `@[ext]`. -/\ntheorem ext (h : ∀ x, x ∈ p ↔ x ∈ q) : p = q := coe_injective $ set.ext h\n\ntheorem ext_iff : p = q ↔ (∀ x, x ∈ p ↔ x ∈ q) := coe_injective.eq_iff.symm.trans set.ext_iff\n\n@[simp] theorem mem_coe {x : B} : x ∈ (p : set B) ↔ x ∈ p := iff.rfl\n\n@[simp, norm_cast] lemma coe_eq_coe {x y : p} : (x : B) = y ↔ x = y := subtype.ext_iff_val.symm\n\n@[simp, norm_cast] lemma coe_mk (x : B) (hx : x ∈ p) : ((⟨x, hx⟩ : p) : B) = x := rfl\n@[simp] lemma coe_mem (x : p) : (x : B) ∈ p := x.2\n\n@[simp] protected lemma eta (x : p) (hx : (x : B) ∈ p) : (⟨x, hx⟩ : p) = x := subtype.eta x hx\n\n-- `dangerous_instance` does not know that `B` is used only as an `out_param`\n@[nolint dangerous_instance, priority 100]\ninstance : partial_order A :=\n{ le := λ H K, ∀ ⦃x⦄, x ∈ H → x ∈ K,\n .. partial_order.lift (coe : A → set B) coe_injective }\n\nlemma le_def {S T : A} : S ≤ T ↔ ∀ ⦃x : B⦄, x ∈ S → x ∈ T := iff.rfl\n\n@[simp, norm_cast]\nlemma coe_subset_coe {S T : A} : (S : set B) ⊆ T ↔ S ≤ T := iff.rfl\n\n@[mono] lemma coe_mono : monotone (coe : A → set B) := λ a b, coe_subset_coe.mpr\n\n@[simp, norm_cast]\nlemma coe_ssubset_coe {S T : A} : (S : set B) ⊂ T ↔ S < T := iff.rfl\n\n@[mono] lemma coe_strict_mono : strict_mono (coe : A → set B) := λ a b, coe_ssubset_coe.mpr\n\nlemma not_le_iff_exists : ¬(p ≤ q) ↔ ∃ x ∈ p, x ∉ q := set.not_subset\n\nlemma exists_of_lt : p < q → ∃ x ∈ q, x ∉ p := set.exists_of_ssubset\n\nlemma lt_iff_le_and_exists : p < q ↔ p ≤ q ∧ ∃ x ∈ q, x ∉ p :=\nby rw [lt_iff_le_not_le, not_le_iff_exists]\n\nend set_like\n", "meta": {"author": "JLimperg", "repo": "aesop3", "sha": "a4a116f650cc7403428e72bd2e2c4cda300fe03f", "save_path": "github-repos/lean/JLimperg-aesop3", "path": "github-repos/lean/JLimperg-aesop3/aesop3-a4a116f650cc7403428e72bd2e2c4cda300fe03f/src/data/set_like.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4455295350395727, "lm_q2_score": 0.0913820962622169, "lm_q1q2_score": 0.04071342285864697}} {"text": "/-\nCopyright (c) 2020 Simon Hudon. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Simon Hudon\n-/\nimport control.monad.basic\nimport control.monad.cont\nimport control.monad.writer\nimport logic.equiv.basic\nimport tactic.interactive\n\n/-!\n# Universe lifting for type families\n\nSome functors such as `option` and `list` are universe polymorphic. Unlike\ntype polymorphism where `option α` is a function application and reasoning and\ngeneralizations that apply to functions can be used, `option.{u}` and `option.{v}`\nare not one function applied to two universe names but one polymorphic definition\ninstantiated twice. This means that whatever works on `option.{u}` is hard\nto transport over to `option.{v}`. `uliftable` is an attempt at improving the situation.\n\n`uliftable option.{u} option.{v}` gives us a generic and composable way to use\n`option.{u}` in a context that requires `option.{v}`. It is often used in tandem with\n`ulift` but the two are purposefully decoupled.\n\n\n## Main definitions\n * `uliftable` class\n\n## Tags\n\nuniverse polymorphism functor\n\n-/\n\nuniverses u₀ u₁ v₀ v₁ v₂ w w₀ w₁\nvariables {s : Type u₀} {s' : Type u₁} {r r' w w' : Type*}\n\n/-- Given a universe polymorphic type family `M.{u} : Type u₁ → Type\nu₂`, this class convert between instantiations, from\n`M.{u} : Type u₁ → Type u₂` to `M.{v} : Type v₁ → Type v₂` and back -/\nclass uliftable (f : Type u₀ → Type u₁) (g : Type v₀ → Type v₁) :=\n(congr [] {α β} : α ≃ β → f α ≃ g β)\n\nnamespace uliftable\n\n/-- The most common practical use `uliftable` (together with `up`), this function takes\n`x : M.{u} α` and lifts it to M.{max u v} (ulift.{v} α) -/\n@[reducible]\ndef up {f : Type u₀ → Type u₁} {g : Type (max u₀ v₀) → Type v₁} [uliftable f g]\n {α} : f α → g (ulift α) :=\n(uliftable.congr f g equiv.ulift.symm).to_fun\n\n/-- The most common practical use of `uliftable` (together with `up`), this function takes\n`x : M.{max u v} (ulift.{v} α)` and lowers it to `M.{u} α` -/\n@[reducible]\ndef down {f : Type u₀ → Type u₁} {g : Type (max u₀ v₀) → Type v₁} [uliftable f g]\n {α} : g (ulift α) → f α :=\n(uliftable.congr f g equiv.ulift.symm).inv_fun\n\n/-- convenient shortcut to avoid manipulating `ulift` -/\ndef adapt_up (F : Type v₀ → Type v₁) (G : Type (max v₀ u₀) → Type u₁)\n [uliftable F G] [monad G] {α β}\n (x : F α) (f : α → G β) : G β :=\nup x >>= f ∘ ulift.down\n\n/-- convenient shortcut to avoid manipulating `ulift` -/\ndef adapt_down {F : Type (max u₀ v₀) → Type u₁} {G : Type v₀ → Type v₁}\n [L : uliftable G F] [monad F] {α β}\n (x : F α) (f : α → G β) : G β :=\n@down.{v₀ v₁ (max u₀ v₀)} G F L β $ x >>= @up.{v₀ v₁ (max u₀ v₀)} G F L β ∘ f\n\n/-- map function that moves up universes -/\ndef up_map {F : Type u₀ → Type u₁} {G : Type.{max u₀ v₀} → Type v₁} [inst : uliftable F G]\n [functor G] {α β} (f : α → β) (x : F α) : G β :=\nfunctor.map (f ∘ ulift.down) (up x)\n\n/-- map function that moves down universes -/\ndef down_map {F : Type.{max u₀ v₀} → Type u₁} {G : Type u₀ → Type v₁} [inst : uliftable G F]\n [functor F] {α β} (f : α → β) (x : F α) : G β :=\ndown (functor.map (ulift.up ∘ f) x : F (ulift β))\n\n@[simp]\nlemma up_down {f : Type u₀ → Type u₁} {g : Type (max u₀ v₀) → Type v₁} [uliftable f g]\n {α} (x : g (ulift α)) : up (down x : f α) = x :=\n(uliftable.congr f g equiv.ulift.symm).right_inv _\n\n@[simp]\nlemma down_up {f : Type u₀ → Type u₁} {g : Type (max u₀ v₀) → Type v₁} [uliftable f g]\n {α} (x : f α) : down (up x : g _) = x :=\n(uliftable.congr f g equiv.ulift.symm).left_inv _\n\nend uliftable\n\nopen ulift\n\ninstance : uliftable id id :=\n{ congr := λ α β F, F }\n\n/-- for specific state types, this function helps to create a uliftable instance -/\ndef state_t.uliftable' {m : Type u₀ → Type v₀} {m' : Type u₁ → Type v₁}\n [uliftable m m']\n (F : s ≃ s') :\n uliftable (state_t s m) (state_t s' m') :=\n{ congr :=\n λ α β G, state_t.equiv $ equiv.Pi_congr F $\n λ _, uliftable.congr _ _ $ equiv.prod_congr G F }\n\ninstance {m m'} [uliftable m m'] :\n uliftable (state_t s m) (state_t (ulift s) m') :=\nstate_t.uliftable' equiv.ulift.symm\n\n/-- for specific reader monads, this function helps to create a uliftable instance -/\ndef reader_t.uliftable' {m m'} [uliftable m m']\n (F : s ≃ s') :\n uliftable (reader_t s m) (reader_t s' m') :=\n{ congr :=\n λ α β G, reader_t.equiv $ equiv.Pi_congr F $\n λ _, uliftable.congr _ _ G }\n\ninstance {m m'} [uliftable m m'] : uliftable (reader_t s m) (reader_t (ulift s) m') :=\nreader_t.uliftable' equiv.ulift.symm\n\n/-- for specific continuation passing monads, this function helps to create a uliftable instance -/\ndef cont_t.uliftable' {m m'} [uliftable m m']\n (F : r ≃ r') :\n uliftable (cont_t r m) (cont_t r' m') :=\n{ congr :=\n λ α β, cont_t.equiv (uliftable.congr _ _ F) }\n\ninstance {s m m'} [uliftable m m'] : uliftable (cont_t s m) (cont_t (ulift s) m') :=\ncont_t.uliftable' equiv.ulift.symm\n\n/-- for specific writer monads, this function helps to create a uliftable instance -/\ndef writer_t.uliftable' {m m'} [uliftable m m']\n (F : w ≃ w') :\n uliftable (writer_t w m) (writer_t w' m') :=\n{ congr :=\n λ α β G, writer_t.equiv $ uliftable.congr _ _ $ equiv.prod_congr G F }\n\ninstance {m m'} [uliftable m m'] : uliftable (writer_t s m) (writer_t (ulift s) m') :=\nwriter_t.uliftable' equiv.ulift.symm\n", "meta": {"author": "leanprover-community", "repo": "mathlib", "sha": "5e526d18cea33550268dcbbddcb822d5cde40654", "save_path": "github-repos/lean/leanprover-community-mathlib", "path": "github-repos/lean/leanprover-community-mathlib/mathlib-5e526d18cea33550268dcbbddcb822d5cde40654/src/control/uliftable.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.08269734889212697, "lm_q1q2_score": 0.04070265398026817}} {"text": "/-\nCopyright (c) 2017 Mario Carneiro. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Mario Carneiro, Yury Kudryashov, Floris van Doorn\n-/\nimport tactic.transform_decl\nimport tactic.algebra\nimport tactic.lint.basic\nimport tactic.alias\n\n/-!\n# Transport multiplicative to additive\n\nThis file defines an attribute `to_additive` that can be used to\nautomatically transport theorems and definitions (but not inductive\ntypes and structures) from a multiplicative theory to an additive theory.\n\nUsage information is contained in the doc string of `to_additive.attr`.\n\n### Missing features\n\n* Automatically transport structures and other inductive types.\n\n* For structures, automatically generate theorems like `group α ↔\n add_group (additive α)`.\n-/\n\nnamespace to_additive\nopen tactic\nsetup_tactic_parser\n\nsection performance_hack -- see Note [user attribute parameters]\n\nlocal attribute [semireducible] reflected\n\n/-- Temporarily change the `has_reflect` instance for `name`. -/\nlocal attribute [instance, priority 9000]\nmeta def hacky_name_reflect : has_reflect name :=\nλ n, `(id %%(expr.const n []) : name)\n\n/-- An auxiliary attribute used to store the names of the additive versions of declarations\nthat have been processed by `to_additive`. -/\n@[user_attribute]\nmeta def aux_attr : user_attribute (name_map name) name :=\n{ name := `to_additive_aux,\n descr := \"Auxiliary attribute for `to_additive`. DON'T USE IT\",\n parser := failed,\n cache_cfg := ⟨λ ns,\n ns.mfoldl\n (λ dict n', do\n let n := match n' with\n | name.mk_string s pre := if s = \"_to_additive\" then pre else n'\n | _ := n'\n end,\n param ← aux_attr.get_param_untyped n',\n pure $ dict.insert n param.app_arg.const_name)\n mk_name_map, []⟩ }\n\nend performance_hack\n\nsection extra_attributes\n\n/--\nAn attribute that tells `@[to_additive]` that certain arguments of this definition are not\ninvolved when using `@[to_additive]`.\nThis helps the heuristic of `@[to_additive]` by also transforming definitions if `ℕ` or another\nfixed type occurs as one of these arguments.\n-/\n@[user_attribute]\nmeta def ignore_args_attr : user_attribute (name_map $ list ℕ) (list ℕ) :=\n{ name := `to_additive_ignore_args,\n descr :=\n \"Auxiliary attribute for `to_additive` stating that certain arguments are not additivized.\",\n cache_cfg :=\n ⟨λ ns, ns.mfoldl\n (λ dict n, do\n param ← ignore_args_attr.get_param_untyped n, -- see Note [user attribute parameters]\n return $ dict.insert n (param.to_list expr.to_nat).iget)\n mk_name_map, []⟩,\n parser := (lean.parser.small_nat)* }\n\n/--\nAn attribute that is automatically added to declarations tagged with `@[to_additive]`, if needed.\n\nThis attribute tells which argument is the type where this declaration uses the multiplicative\nstructure. If there are multiple argument, we typically tag the first one.\nIf this argument contains a fixed type, this declaration will note be additivized.\nSee the Heuristics section of `to_additive.attr` for more details.\n\nIf a declaration is not tagged, it is presumed that the first argument is relevant.\n`@[to_additive]` uses the function `to_additive.first_multiplicative_arg` to automatically tag\ndeclarations. It is ok to update it manually if the automatic tagging made an error.\n\nImplementation note: we only allow exactly 1 relevant argument, even though some declarations\n(like `prod.group`) have multiple arguments with a multiplicative structure on it.\nThe reason is that whether we additivize a declaration is an all-or-nothing decision, and if\nwe will not be able to additivize declarations that (e.g.) talk about multiplication on `ℕ × α`\nanyway.\n\nWarning: adding `@[to_additive_reorder]` with an equal or smaller number than the number in this\nattribute is currently not supported.\n-/\n@[user_attribute]\nmeta def relevant_arg_attr : user_attribute (name_map ℕ) ℕ :=\n{ name := `to_additive_relevant_arg,\n descr :=\n \"Auxiliary attribute for `to_additive` stating which arguments are the types with a \" ++\n \"multiplicative structure.\",\n cache_cfg :=\n ⟨λ ns, ns.mfoldl\n (λ dict n, do\n param ← relevant_arg_attr.get_param_untyped n, -- see Note [user attribute parameters]\n -- we subtract 1 from the values provided by the user.\n return $ dict.insert n $ param.to_nat.iget.pred)\n mk_name_map, []⟩,\n parser := lean.parser.small_nat }\n\n/--\nAn attribute that stores all the declarations that needs their arguments reordered when\napplying `@[to_additive]`. Currently, we only support swapping consecutive arguments.\nThe list of the natural numbers contains the positions of the first of the two arguments\nto be swapped.\nIf the first two arguments are swapped, the first two universe variables are also swapped.\nExample: `@[to_additive_reorder 1 4]` swaps the first two arguments and the arguments in\npositions 4 and 5.\n-/\n@[user_attribute]\nmeta def reorder_attr : user_attribute (name_map $ list ℕ) (list ℕ) :=\n{ name := `to_additive_reorder,\n descr :=\n \"Auxiliary attribute for `to_additive` that stores arguments that need to be reordered.\",\n cache_cfg :=\n ⟨λ ns, ns.mfoldl\n (λ dict n, do\n param ← reorder_attr.get_param_untyped n, -- see Note [user attribute parameters]\n return $ dict.insert n (param.to_list expr.to_nat).iget)\n mk_name_map, []⟩,\n parser := do\n l ← (lean.parser.small_nat)*,\n guard (l.all (≠ 0)) <|> exceptional.fail \"The reorder positions must be positive\",\n return l }\n\nend extra_attributes\n\n/--\nFind the first argument of `nm` that has a multiplicative type-class on it.\nReturns 1 if there are no types with a multiplicative class as arguments.\nE.g. `prod.group` returns 1, and `pi.has_one` returns 2.\n-/\nmeta def first_multiplicative_arg (nm : name) : tactic ℕ := do\n d ← get_decl nm,\n let (es, _) := d.type.pi_binders,\n l ← es.mmap_with_index $ λ n bi, do\n { let tgt := bi.type.pi_codomain,\n let n_bi := bi.type.pi_binders.fst.length,\n tt ← has_attribute' `to_additive tgt.get_app_fn.const_name | return none,\n let n2 := tgt.get_app_args.head.get_app_fn.match_var.map $ λ m, n + n_bi - m,\n return $ n2 },\n let l := l.reduce_option,\n return $ if l = [] then 1 else l.foldr min l.head\n\n/-- A command that can be used to have future uses of `to_additive` change the `src` namespace\nto the `tgt` namespace.\n\nFor example:\n```\nrun_cmd to_additive.map_namespace `quotient_group `quotient_add_group\n```\n\nLater uses of `to_additive` on declarations in the `quotient_group` namespace will be created\nin the `quotient_add_group` namespaces.\n-/\nmeta def map_namespace (src tgt : name) : command :=\ndo let n := src.mk_string \"_to_additive\",\n let decl := declaration.thm n [] `(unit) (pure (reflect ())),\n add_decl decl,\n aux_attr.set n tgt tt\n\n/-- `value_type` is the type of the arguments that can be provided to `to_additive`.\n`to_additive.parser` parses the provided arguments:\n* `replace_all`: replace all multiplicative declarations, do not use the heuristic.\n* `trace`: output the generated additive declaration.\n* `tgt : name`: the name of the target (the additive declaration).\n* `doc`: an optional doc string.\n* if `allow_auto_name` is `ff` (default) then `@[to_additive]` will check whether the given name\n can be auto-generated.\n-/\n@[derive has_reflect, derive inhabited]\nstructure value_type : Type :=\n(replace_all : bool)\n(trace : bool)\n(tgt : name)\n(doc : option string)\n(allow_auto_name : bool)\n\n/-- `add_comm_prefix x s` returns `\"comm_\" ++ s` if `x = tt` and `s` otherwise. -/\nmeta def add_comm_prefix : bool → string → string\n| tt s := \"comm_\" ++ s\n| ff s := s\n\n/-- Dictionary used by `to_additive.guess_name` to autogenerate names. -/\nmeta def tr : bool → list string → list string\n| is_comm (\"one\" :: \"le\" :: s) := add_comm_prefix is_comm \"nonneg\" :: tr ff s\n| is_comm (\"one\" :: \"lt\" :: s) := add_comm_prefix is_comm \"pos\" :: tr ff s\n| is_comm (\"le\" :: \"one\" :: s) := add_comm_prefix is_comm \"nonpos\" :: tr ff s\n| is_comm (\"lt\" :: \"one\" :: s) := add_comm_prefix is_comm \"neg\" :: tr ff s\n| is_comm (\"mul\" :: \"single\" :: s) := add_comm_prefix is_comm \"single\" :: tr ff s\n| is_comm (\"mul\" :: \"support\" :: s) := add_comm_prefix is_comm \"support\" :: tr ff s\n| is_comm (\"mul\" :: \"tsupport\" :: s) := add_comm_prefix is_comm \"tsupport\" :: tr ff s\n| is_comm (\"mul\" :: \"indicator\" :: s) := add_comm_prefix is_comm \"indicator\" :: tr ff s\n| is_comm (\"mul\" :: s) := add_comm_prefix is_comm \"add\" :: tr ff s\n| is_comm (\"smul\" :: s) := add_comm_prefix is_comm \"vadd\" :: tr ff s\n| is_comm (\"inv\" :: s) := add_comm_prefix is_comm \"neg\" :: tr ff s\n| is_comm (\"div\" :: s) := add_comm_prefix is_comm \"sub\" :: tr ff s\n| is_comm (\"one\" :: s) := add_comm_prefix is_comm \"zero\" :: tr ff s\n| is_comm (\"prod\" :: s) := add_comm_prefix is_comm \"sum\" :: tr ff s\n| is_comm (\"finprod\" :: s) := add_comm_prefix is_comm \"finsum\" :: tr ff s\n| is_comm (\"pow\" :: s) := add_comm_prefix is_comm \"nsmul\" :: tr ff s\n| is_comm (\"npow\" :: s) := add_comm_prefix is_comm \"nsmul\" :: tr ff s\n| is_comm (\"zpow\" :: s) := add_comm_prefix is_comm \"zsmul\" :: tr ff s\n| is_comm (\"is\" :: \"square\" :: s) := add_comm_prefix is_comm \"even\" :: tr ff s\n| is_comm (\"is\" :: \"scalar\" :: \"tower\" :: s) :=\n add_comm_prefix is_comm \"vadd_assoc_class\" :: tr ff s\n| is_comm (\"is\" :: \"central\" :: \"scalar\" :: s) :=\n add_comm_prefix is_comm \"is_central_vadd\" :: tr ff s\n| is_comm (\"is\" :: \"regular\" :: s) := add_comm_prefix is_comm \"is_add_regular\" :: tr ff s\n| is_comm (\"is\" :: \"left\" :: \"regular\" :: s) :=\n add_comm_prefix is_comm \"is_add_left_regular\" :: tr ff s\n| is_comm (\"is\" :: \"right\" :: \"regular\" :: s) :=\n add_comm_prefix is_comm \"is_add_right_regular\" :: tr ff s\n| is_comm (\"division\" :: \"monoid\" :: s) :=\n \"subtraction\" :: add_comm_prefix is_comm \"monoid\" :: tr ff s\n| is_comm (\"monoid\" :: s) := (\"add_\" ++ add_comm_prefix is_comm \"monoid\") :: tr ff s\n| is_comm (\"submonoid\" :: s) := (\"add_\" ++ add_comm_prefix is_comm \"submonoid\") :: tr ff s\n| is_comm (\"group\" :: s) := (\"add_\" ++ add_comm_prefix is_comm \"group\") :: tr ff s\n| is_comm (\"subgroup\" :: s) := (\"add_\" ++ add_comm_prefix is_comm \"subgroup\") :: tr ff s\n| is_comm (\"semigroup\" :: s) := (\"add_\" ++ add_comm_prefix is_comm \"semigroup\") :: tr ff s\n| is_comm (\"magma\" :: s) := (\"add_\" ++ add_comm_prefix is_comm \"magma\") :: tr ff s\n| is_comm (\"haar\" :: s) := (\"add_\" ++ add_comm_prefix is_comm \"haar\") :: tr ff s\n| is_comm (\"prehaar\" :: s) := (\"add_\" ++ add_comm_prefix is_comm \"prehaar\") :: tr ff s\n| is_comm (\"unit\" :: s) := (\"add_\" ++ add_comm_prefix is_comm \"unit\") :: tr ff s\n| is_comm (\"units\" :: s) := (\"add_\" ++ add_comm_prefix is_comm \"units\") :: tr ff s\n| is_comm (\"comm\" :: s) := tr tt s\n| is_comm (\"root\" :: s) := add_comm_prefix is_comm \"div\" :: tr ff s\n| is_comm (\"rootable\" :: s) := add_comm_prefix is_comm \"divisible\" :: tr ff s\n| is_comm (\"prods\" :: s) := add_comm_prefix is_comm \"sums\" :: tr ff s\n| is_comm (x :: s) := (add_comm_prefix is_comm x :: tr ff s)\n| tt [] := [\"comm\"]\n| ff [] := []\n\n/-- Autogenerate target name for `to_additive`. -/\nmeta def guess_name : string → string :=\nstring.map_tokens ''' $\nλ s, string.intercalate (string.singleton '_') $\ntr ff (s.split_on '_')\n\n/-- Return the provided target name or autogenerate one if one was not provided. -/\nmeta def target_name (src tgt : name) (dict : name_map name) (allow_auto_name : bool) :\n tactic name :=\n(if tgt.get_prefix ≠ name.anonymous ∨ allow_auto_name -- `tgt` is a full name\n then pure tgt\n else match src with\n | (name.mk_string s pre) :=\n do let tgt_auto := guess_name s,\n guard (tgt.to_string ≠ tgt_auto ∨ tgt = src)\n <|> trace (\"`to_additive \" ++ src.to_string ++ \"`: correctly autogenerated target \" ++\n \"name, you may remove the explicit \" ++ tgt_auto ++ \" argument.\"),\n pure $ name.mk_string\n (if tgt = name.anonymous then tgt_auto else tgt.to_string)\n (pre.map_prefix dict.find)\n | _ := fail (\"to_additive: can't transport \" ++ src.to_string)\n end) >>=\n(λ res,\n if res = src ∧ tgt ≠ src\n then fail (\"to_additive: can't transport \" ++ src.to_string ++ \" to itself.\nGive the desired additive name explicitly using `@[to_additive additive_name]`. \")\n else pure res)\n\n/-- the parser for the arguments to `to_additive`. -/\nmeta def parser : lean.parser value_type :=\ndo\n bang ← option.is_some <$> (tk \"!\")?,\n ques ← option.is_some <$> (tk \"?\")?,\n tgt ← ident?,\n e ← texpr?,\n doc ← match e with\n | some pe := some <$> ((to_expr pe >>= eval_expr string) : tactic string)\n | none := pure none\n end,\n return ⟨bang, ques, tgt.get_or_else name.anonymous, doc, ff⟩\n\nprivate meta def proceed_fields_aux (src tgt : name) (prio : ℕ) (f : name → tactic (list string)) :\n command :=\ndo\n src_fields ← f src,\n tgt_fields ← f tgt,\n guard (src_fields.length = tgt_fields.length) <|>\n fail (\"Failed to map fields of \" ++ src.to_string),\n (src_fields.zip tgt_fields).mmap' $\n λ names, guard (names.fst = names.snd) <|>\n aux_attr.set (src.append names.fst) (tgt.append names.snd) tt prio\n\n/-- Add the `aux_attr` attribute to the structure fields of `src`\nso that future uses of `to_additive` will map them to the corresponding `tgt` fields. -/\nmeta def proceed_fields (env : environment) (src tgt : name) (prio : ℕ) : command :=\nlet aux := proceed_fields_aux src tgt prio in\ndo\naux (λ n, pure $ list.map name.to_string $ (env.structure_fields n).get_or_else []) >>\naux (λ n, (list.map (λ (x : name), \"to_\" ++ x.to_string) <$> get_tagged_ancestors n)) >>\naux (λ n, (env.constructors_of n).mmap $\n λ cs, match cs with\n | (name.mk_string s pre) :=\n (guard (pre = n) <|> fail \"Bad constructor name\") >>\n pure s\n | _ := fail \"Bad constructor name\"\n end)\n\n/--\nThe attribute `to_additive` can be used to automatically transport theorems\nand definitions (but not inductive types and structures) from a multiplicative\ntheory to an additive theory.\n\nTo use this attribute, just write:\n\n```\n@[to_additive]\ntheorem mul_comm' {α} [comm_semigroup α] (x y : α) : x * y = y * x := comm_semigroup.mul_comm\n```\n\nThis code will generate a theorem named `add_comm'`. It is also\npossible to manually specify the name of the new declaration:\n\n```\n@[to_additive add_foo]\ntheorem foo := sorry\n```\n\nAn existing documentation string will _not_ be automatically used, so if the theorem or definition\nhas a doc string, a doc string for the additive version should be passed explicitly to\n`to_additive`.\n\n```\n/-- Multiplication is commutative -/\n@[to_additive \"Addition is commutative\"]\ntheorem mul_comm' {α} [comm_semigroup α] (x y : α) : x * y = y * x := comm_semigroup.mul_comm\n```\n\nThe transport tries to do the right thing in most cases using several\nheuristics described below. However, in some cases it fails, and\nrequires manual intervention.\n\nIf the declaration to be transported has attributes which need to be\ncopied to the additive version, then `to_additive` should come last:\n\n```\n@[simp, to_additive] lemma mul_one' {G : Type*} [group G] (x : G) : x * 1 = x := mul_one x\n```\n\nThe following attributes are supported and should be applied correctly by `to_additive` to\nthe new additivized declaration, if they were present on the original one:\n```\nreducible, _refl_lemma, simp, norm_cast, instance, refl, symm, trans, elab_as_eliminator, no_rsimp,\ncontinuity, ext, ematch, measurability, alias, _ext_core, _ext_lemma_core, nolint\n```\n\nThe exception to this rule is the `simps` attribute, which should come after `to_additive`:\n\n```\n@[to_additive, simps]\ninstance {M N} [has_mul M] [has_mul N] : has_mul (M × N) := ⟨λ p q, ⟨p.1 * q.1, p.2 * q.2⟩⟩\n```\n\nAdditionally the `mono` attribute is not handled by `to_additive` and should be applied afterwards\nto both the original and additivized lemma.\n\n## Implementation notes\n\nThe transport process generally works by taking all the names of\nidentifiers appearing in the name, type, and body of a declaration and\ncreating a new declaration by mapping those names to additive versions\nusing a simple string-based dictionary and also using all declarations\nthat have previously been labeled with `to_additive`.\n\nIn the `mul_comm'` example above, `to_additive` maps:\n* `mul_comm'` to `add_comm'`,\n* `comm_semigroup` to `add_comm_semigroup`,\n* `x * y` to `x + y` and `y * x` to `y + x`, and\n* `comm_semigroup.mul_comm'` to `add_comm_semigroup.add_comm'`.\n\n### Heuristics\n\n`to_additive` uses heuristics to determine whether a particular identifier has to be\nmapped to its additive version. The basic heuristic is\n\n* Only map an identifier to its additive version if its first argument doesn't\n contain any unapplied identifiers.\n\nExamples:\n* `@has_mul.mul ℕ n m` (i.e. `(n * m : ℕ)`) will not change to `+`, since its\n first argument is `ℕ`, an identifier not applied to any arguments.\n* `@has_mul.mul (α × β) x y` will change to `+`. It's first argument contains only the identifier\n `prod`, but this is applied to arguments, `α` and `β`.\n* `@has_mul.mul (α × ℤ) x y` will not change to `+`, since its first argument contains `ℤ`.\n\nThe reasoning behind the heuristic is that the first argument is the type which is \"additivized\",\nand this usually doesn't make sense if this is on a fixed type.\n\nThere are some exceptions to this heuristic:\n\n* Identifiers that have the `@[to_additive]` attribute are ignored.\n For example, multiplication in `↥Semigroup` is replaced by addition in `↥AddSemigroup`.\n* If an identifier `d` has attribute `@[to_additive_relevant_arg n]` then the argument\n in position `n` is checked for a fixed type, instead of checking the first argument.\n `@[to_additive]` will automatically add the attribute `@[to_additive_relevant_arg n]` to a\n declaration when the first argument has no multiplicative type-class, but argument `n` does.\n* If an identifier has attribute `@[to_additive_ignore_args n1 n2 ...]` then all the arguments in\n positions `n1`, `n2`, ... will not be checked for unapplied identifiers (start counting from 1).\n For example, `cont_mdiff_map` has attribute `@[to_additive_ignore_args 21]`, which means\n that its 21st argument `(n : ℕ∞)` can contain `ℕ`\n (usually in the form `has_top.top ℕ ...`) and still be additivized.\n So `@has_mul.mul (C^∞⟮I, N; I', G⟯) _ f g` will be additivized.\n\n### Troubleshooting\n\nIf `@[to_additive]` fails because the additive declaration raises a type mismatch, there are\nvarious things you can try.\nThe first thing to do is to figure out what `@[to_additive]` did wrong by looking at the type\nmismatch error.\n\n* Option 1: It additivized a declaration `d` that should remain multiplicative. Solution:\n * Make sure the first argument of `d` is a type with a multiplicative structure. If not, can you\n reorder the (implicit) arguments of `d` so that the first argument becomes a type with a\n multiplicative structure (and not some indexing type)?\n The reason is that `@[to_additive]` doesn't additivize declarations if their first argument\n contains fixed types like `ℕ` or `ℝ`. See section Heuristics.\n If the first argument is not the argument with a multiplicative type-class, `@[to_additive]`\n should have automatically added the attribute `@[to_additive_relevant_arg]` to the declaration.\n You can test this by running the following (where `d` is the full name of the declaration):\n ```\n run_cmd to_additive.relevant_arg_attr.get_param `d >>= tactic.trace\n ```\n The expected output is `n` where the `n`-th argument of `d` is a type (family) with a\n multiplicative structure on it. If you get a different output (or a failure), you could add\n the attribute `@[to_additive_relevant_arg n]` manually, where `n` is an argument with a\n multiplicative structure.\n* Option 2: It didn't additivize a declaration that should be additivized.\n This happened because the heuristic applied, and the first argument contains a fixed type,\n like `ℕ` or `ℝ`. Solutions:\n * If the fixed type has an additive counterpart (like `↥Semigroup`), give it the `@[to_additive]`\n attribute.\n * If the fixed type occurs inside the `k`-th argument of a declaration `d`, and the\n `k`-th argument is not connected to the multiplicative structure on `d`, consider adding\n attribute `[to_additive_ignore_args k]` to `d`.\n * If you want to disable the heuristic and replace all multiplicative\n identifiers with their additive counterpart, use `@[to_additive!]`.\n* Option 3: Arguments / universe levels are incorrectly ordered in the additive version.\n This likely only happens when the multiplicative declaration involves `pow`/`^`. Solutions:\n * Ensure that the order of arguments of all relevant declarations are the same for the\n multiplicative and additive version. This might mean that arguments have an \"unnatural\" order\n (e.g. `monoid.npow n x` corresponds to `x ^ n`, but it is convenient that `monoid.npow` has this\n argument order, since it matches `add_monoid.nsmul n x`.\n * If this is not possible, add the `[to_additive_reorder k]` to the multiplicative declaration\n to indicate that the `k`-th and `(k+1)`-st arguments are reordered in the additive version.\n\nIf neither of these solutions work, and `to_additive` is unable to automatically generate the\nadditive version of a declaration, manually write and prove the additive version.\nOften the proof of a lemma/theorem can just be the multiplicative version of the lemma applied to\n`multiplicative G`.\nAfterwards, apply the attribute manually:\n\n```\nattribute [to_additive foo_add_bar] foo_bar\n```\n\nThis will allow future uses of `to_additive` to recognize that\n`foo_bar` should be replaced with `foo_add_bar`.\n\n### Handling of hidden definitions\n\nBefore transporting the “main” declaration `src`, `to_additive` first\nscans its type and value for names starting with `src`, and transports\nthem. This includes auxiliary definitions like `src._match_1`,\n`src._proof_1`.\n\nIn addition to transporting the “main” declaration, `to_additive` transports\nits equational lemmas and tags them as equational lemmas for the new declaration,\nattributes present on the original equational lemmas are also transferred first (notably\n`_refl_lemma`).\n\n### Structure fields and constructors\n\nIf `src` is a structure, then `to_additive` automatically adds\nstructure fields to its mapping, and similarly for constructors of\ninductive types.\n\nFor new structures this means that `to_additive` automatically handles\ncoercions, and for old structures it does the same, if ancestry\ninformation is present in `@[ancestor]` attributes. The `ancestor`\nattribute must come before the `to_additive` attribute, and it is\nessential that the order of the base structures passed to `ancestor` matches\nbetween the multiplicative and additive versions of the structure.\n\n### Name generation\n\n* If `@[to_additive]` is called without a `name` argument, then the\n new name is autogenerated. First, it takes the longest prefix of\n the source name that is already known to `to_additive`, and replaces\n this prefix with its additive counterpart. Second, it takes the last\n part of the name (i.e., after the last dot), and replaces common\n name parts (“mul”, “one”, “inv”, “prod”) with their additive versions.\n\n* Namespaces can be transformed using `map_namespace`. For example:\n ```\n run_cmd to_additive.map_namespace `quotient_group `quotient_add_group\n ```\n\n Later uses of `to_additive` on declarations in the `quotient_group`\n namespace will be created in the `quotient_add_group` namespaces.\n\n* If `@[to_additive]` is called with a `name` argument `new_name`\n /without a dot/, then `to_additive` updates the prefix as described\n above, then replaces the last part of the name with `new_name`.\n\n* If `@[to_additive]` is called with a `name` argument\n `new_namespace.new_name` /with a dot/, then `to_additive` uses this\n new name as is.\n\nAs a safety check, in the first case `to_additive` double checks\nthat the new name differs from the original one.\n\n-/\n@[user_attribute]\nprotected meta def attr : user_attribute unit value_type :=\n{ name := `to_additive,\n descr := \"Transport multiplicative to additive\",\n parser := parser,\n after_set := some $ λ src prio persistent, do\n guard persistent <|> fail \"`to_additive` can't be used as a local attribute\",\n env ← get_env,\n val ← attr.get_param src,\n dict ← aux_attr.get_cache,\n ignore ← ignore_args_attr.get_cache,\n relevant ← relevant_arg_attr.get_cache,\n reorder ← reorder_attr.get_cache,\n tgt ← target_name src val.tgt dict val.allow_auto_name,\n aux_attr.set src tgt tt,\n let dict := dict.insert src tgt,\n first_mult_arg ← first_multiplicative_arg src,\n when (first_mult_arg ≠ 1) $ relevant_arg_attr.set src first_mult_arg tt,\n if env.contains tgt\n then proceed_fields env src tgt prio\n else do\n transform_decl_with_prefix_dict dict val.replace_all val.trace relevant ignore reorder src tgt\n [`reducible, `_refl_lemma, `simp, `norm_cast, `instance, `refl, `symm, `trans,\n `elab_as_eliminator, `no_rsimp, `continuity, `ext, `ematch, `measurability, `alias,\n `_ext_core, `_ext_lemma_core, `nolint, `protected],\n mwhen (has_attribute' `simps src)\n (trace \"Apply the simps attribute after the to_additive attribute\"),\n mwhen (has_attribute' `mono src)\n (trace $ \"to_additive does not work with mono, apply the mono attribute to both\" ++\n \"versions after\"),\n match val.doc with\n | some doc := add_doc_string tgt doc\n | none := do\n some alias_target ← tactic.alias.get_alias_target src | skip,\n let alias_name := alias_target.to_name,\n some add_alias_name ← pure (dict.find alias_name) | skip,\n add_doc_string tgt alias_target.to_string\n end }\n\nadd_tactic_doc\n{ name := \"to_additive\",\n category := doc_category.attr,\n decl_names := [`to_additive.attr],\n tags := [\"transport\", \"environment\", \"lemma derivation\"] }\n\nend to_additive\n\n/- map operations -/\nattribute [to_additive] has_mul has_one has_inv has_div\n/- the following types are supported by `@[to_additive]` and mapped to themselves. -/\nattribute [to_additive empty] empty\nattribute [to_additive pempty] pempty\nattribute [to_additive punit] punit\nattribute [to_additive unit] unit\n\nsection linter\n\nopen tactic expr\n\n/-- A linter that checks that multiplicative and additive lemmas have both doc strings if one of\nthem has one -/\n@[linter] meta def linter.to_additive_doc : linter :=\n{ test := (λ d, do\n let mul_name := d.to_name,\n dict ← to_additive.aux_attr.get_cache,\n match dict.find mul_name with\n | some add_name := do\n mul_doc ← try_core $ doc_string mul_name,\n add_doc ← try_core $ doc_string add_name,\n match mul_doc.is_some, add_doc.is_some with\n | tt, ff := return $ some $ \"declaration has a docstring, but its additive version `\" ++\n add_name.to_string ++ \"` does not. You might want to pass a string argument to \" ++\n \"`to_additive`.\"\n | ff, tt := return $ some $ \"declaration has no docstring, but its additive version `\" ++\n add_name.to_string ++ \"` does. You might want to add a doc string to the declaration.\"\n | _, _ := return none\n end\n | none := return none\n end),\n auto_decls := ff,\n no_errors_found := \"Multiplicative and additive lemmas are consistently documented\",\n errors_found := \"The following declarations have doc strings, but their additive versions do \" ++\n \"not (or vice versa).\",\n is_fast := ff }\n\nend linter\n", "meta": {"author": "leanprover-community", "repo": "mathlib", "sha": "5e526d18cea33550268dcbbddcb822d5cde40654", "save_path": "github-repos/lean/leanprover-community-mathlib", "path": "github-repos/lean/leanprover-community-mathlib/mathlib-5e526d18cea33550268dcbbddcb822d5cde40654/src/tactic/to_additive.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.08389039041876535, "lm_q1q2_score": 0.040634834381070684}} {"text": "/-\nCopyright (c) 2022 Mario Carneiro. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Mario Carneiro\n-/\nimport Std.Tactic.NoMatch\nimport Std.Tactic.HaveI\nimport Std.Classes.LawfulMonad\nimport Std.Data.List.Init.Lemmas\nimport Std.Data.Array.Init.Basic\n\n/-!\n## Bootstrapping theorems about arrays\n\nThis file contains some theorems about `Array` and `List` needed for `Std.List.Basic`.\n-/\n\nnamespace Array\n\nattribute [simp] data_toArray uset\n\n@[simp] theorem mkEmpty_eq (α n) : @mkEmpty α n = #[] := rfl\n\n@[simp] theorem size_toArray (as : List α) : as.toArray.size = as.length := by simp [size]\n\n@[simp] theorem size_mk (as : List α) : (Array.mk as).size = as.length := by simp [size]\n\ntheorem getElem_eq_data_get (a : Array α) (h : i < a.size) : a[i] = a.data.get ⟨i, h⟩ := by\n by_cases i < a.size <;> simp [*] <;> rfl\n\ntheorem foldlM_eq_foldlM_data.aux [Monad m]\n (f : β → α → m β) (arr : Array α) (i j) (H : arr.size ≤ i + j) (b) :\n foldlM.loop f arr arr.size (Nat.le_refl _) i j b = (arr.data.drop j).foldlM f b := by\n unfold foldlM.loop\n split; split\n · cases Nat.not_le_of_gt ‹_› (Nat.zero_add _ ▸ H)\n · rename_i i; rw [Nat.succ_add] at H\n simp [foldlM_eq_foldlM_data.aux f arr i (j+1) H]\n conv => rhs; rw [← List.get_drop_eq_drop _ _ ‹_›]\n · rw [List.drop_length_le (Nat.ge_of_not_lt ‹_›)]; rfl\n\ntheorem foldlM_eq_foldlM_data [Monad m]\n (f : β → α → m β) (init : β) (arr : Array α) :\n arr.foldlM f init = arr.data.foldlM f init := by\n simp [foldlM, foldlM_eq_foldlM_data.aux]\n\ntheorem foldl_eq_foldl_data (f : β → α → β) (init : β) (arr : Array α) :\n arr.foldl f init = arr.data.foldl f init :=\n List.foldl_eq_foldlM .. ▸ foldlM_eq_foldlM_data ..\n\ntheorem foldrM_eq_reverse_foldlM_data.aux [Monad m]\n (f : α → β → m β) (arr : Array α) (init : β) (i h) :\n (arr.data.take i).reverse.foldlM (fun x y => f y x) init = foldrM.fold f arr 0 i h init := by\n unfold foldrM.fold\n match i with\n | 0 => simp [List.foldlM, List.take]\n | i+1 => rw [← List.take_concat_get _ _ h]; simp [← (aux f arr · i)]; rfl\n\ntheorem foldrM_eq_reverse_foldlM_data [Monad m] (f : α → β → m β) (init : β) (arr : Array α) :\n arr.foldrM f init = arr.data.reverse.foldlM (fun x y => f y x) init := by\n have : arr = #[] ∨ 0 < arr.size :=\n match arr with | ⟨[]⟩ => .inl rfl | ⟨a::l⟩ => .inr (Nat.zero_lt_succ _)\n match arr, this with | _, .inl rfl => rfl | arr, .inr h => ?_\n simp [foldrM, h, ← foldrM_eq_reverse_foldlM_data.aux, List.take_length]\n\ntheorem foldrM_eq_foldrM_data [Monad m]\n (f : α → β → m β) (init : β) (arr : Array α) :\n arr.foldrM f init = arr.data.foldrM f init := by\n rw [foldrM_eq_reverse_foldlM_data, List.foldlM_reverse]\n\ntheorem foldr_eq_foldr_data (f : α → β → β) (init : β) (arr : Array α) :\n arr.foldr f init = arr.data.foldr f init :=\n List.foldr_eq_foldrM .. ▸ foldrM_eq_foldrM_data ..\n\n@[simp] theorem push_data (arr : Array α) (a : α) : (arr.push a).data = arr.data ++ [a] := by\n simp [push, List.concat_eq_append]\n\ntheorem foldrM_push [Monad m] (f : α → β → m β) (init : β) (arr : Array α) (a : α) :\n (arr.push a).foldrM f init = f a init >>= arr.foldrM f := by\n simp [foldrM_eq_reverse_foldlM_data, -size_push]\n\n@[simp] theorem foldrM_push' [Monad m] (f : α → β → m β) (init : β) (arr : Array α) (a : α) :\n (arr.push a).foldrM f init (start := arr.size + 1) = f a init >>= arr.foldrM f := by\n simp [← foldrM_push]\n\ntheorem foldr_push (f : α → β → β) (init : β) (arr : Array α) (a : α) :\n (arr.push a).foldr f init = arr.foldr f (f a init) := foldrM_push ..\n\n@[simp] theorem foldr_push' (f : α → β → β) (init : β) (arr : Array α) (a : α) :\n (arr.push a).foldr f init (start := arr.size + 1) = arr.foldr f (f a init) := foldrM_push' ..\n\n@[simp] theorem toListAppend_eq (arr : Array α) (l) : arr.toListAppend l = arr.data ++ l := by\n simp [toListAppend, foldr_eq_foldr_data]\n\n@[simp] theorem toList_eq (arr : Array α) : arr.toList = arr.data := by\n simp [toList, foldr_eq_foldr_data]\n\n/-- A more efficient version of `arr.toList.reverse`. -/\n@[inline] def toListRev (arr : Array α) : List α := arr.foldl (fun l t => t :: l) []\n\n@[simp] theorem toListRev_eq (arr : Array α) : arr.toListRev = arr.data.reverse := by\n rw [toListRev, foldl_eq_foldl_data, ← List.foldr_reverse, List.foldr_self]\n\ntheorem SatisfiesM_foldlM [Monad m] [LawfulMonad m]\n {as : Array α} (motive : Nat → β → Prop) {init : β} (h0 : motive 0 init) {f : β → α → m β}\n (hf : ∀ i : Fin as.size, ∀ b, motive i.1 b → SatisfiesM (motive (i.1 + 1)) (f b as[i])) :\n SatisfiesM (motive as.size) (as.foldlM f init) := by\n let rec go {i j b} (h₁ : j ≤ as.size) (h₂ : as.size ≤ i + j) (H : motive j b) :\n SatisfiesM (motive as.size) (foldlM.loop f as as.size (Nat.le_refl _) i j b) := by\n unfold foldlM.loop; split\n · next hj =>\n split\n · cases Nat.not_le_of_gt (by simp [hj]) h₂\n · exact (hf ⟨j, hj⟩ b H).bind fun _ => go hj (by rwa [Nat.succ_add] at h₂)\n · next hj => exact Nat.le_antisymm h₁ (Nat.ge_of_not_lt hj) ▸ .pure H\n simp [foldlM]; exact go (Nat.zero_le _) (Nat.le_refl _) h0\n\ntheorem foldl_induction\n {as : Array α} (motive : Nat → β → Prop) {init : β} (h0 : motive 0 init) {f : β → α → β}\n (hf : ∀ i : Fin as.size, ∀ b, motive i.1 b → motive (i.1 + 1) (f b as[i])) :\n motive as.size (as.foldl f init) := by\n have := SatisfiesM_foldlM (m := Id) (as := as) (f := f) motive h0\n simp [SatisfiesM_Id_eq] at this\n exact this hf\n\ntheorem get_push_lt (a : Array α) (x : α) (i : Nat) (h : i < a.size) :\n haveI : i < (a.push x).size := by simp [*, Nat.lt_succ_of_le, Nat.le_of_lt]\n (a.push x)[i] = a[i] := by\n simp only [push, getElem_eq_data_get, List.concat_eq_append, List.get_append_left, h]\n\n@[simp] theorem get_push_eq (a : Array α) (x : α) : (a.push x)[a.size] = x := by\n simp only [push, getElem_eq_data_get, List.concat_eq_append]\n rw [List.get_append_right] <;> simp [getElem_eq_data_get]\n\ntheorem get_push (a : Array α) (x : α) (i : Nat) (h : i < (a.push x).size) :\n (a.push x)[i] = if h : i < a.size then a[i] else x := by\n if h' : i < a.size then\n simp [get_push_lt, h']\n else\n simp at h\n simp [get_push_lt, Nat.le_antisymm (Nat.le_of_lt_succ h) (Nat.ge_of_not_lt h')]\n\ntheorem SatisfiesM_mapM [Monad m] [LawfulMonad m] (as : Array α) (f : α → m β)\n (motive : Nat → Prop) (h0 : motive 0)\n (p : Fin as.size → β → Prop)\n (hs : ∀ i, motive i.1 → SatisfiesM (p i · ∧ motive (i + 1)) (f as[i])) :\n SatisfiesM\n (fun arr => motive as.size ∧ ∃ eq : arr.size = as.size, ∀ i h, p ⟨i, h⟩ (arr[i]'(eq ▸ h)))\n (Array.mapM f as) := by\n unfold mapM\n refine SatisfiesM_foldlM (m := m) (β := Array β)\n (motive := fun i arr => motive i ∧ arr.size = i ∧ ∀ i h2, p i (arr[i.1]'h2)) ?z ?s\n |>.imp fun ⟨h₁, eq, h₂⟩ => ⟨h₁, eq, fun _ _ => h₂ ..⟩\n · case z => exact ⟨h0, rfl, fun.⟩\n · case s =>\n intro ⟨i, hi⟩ arr ⟨ih₁, eq, ih₂⟩\n refine (hs _ ih₁).bind fun b ⟨h₁, h₂⟩ => .pure ⟨h₂, by simp [eq], fun j hj => ?_⟩\n simp [get_push] at hj ⊢; split; {apply ih₂}\n cases j; cases (Nat.le_or_eq_of_le_succ hj).resolve_left ‹_›; cases eq; exact h₁\n\ntheorem SatisfiesM_mapM' [Monad m] [LawfulMonad m] (as : Array α) (f : α → m β)\n (p : Fin as.size → β → Prop)\n (hs : ∀ i, SatisfiesM (p i) (f as[i])) :\n SatisfiesM\n (fun arr => ∃ eq : arr.size = as.size, ∀ i h, p ⟨i, h⟩ (arr[i]'(eq ▸ h)))\n (Array.mapM f as) :=\n (SatisfiesM_mapM _ _ (fun _ => True) trivial _ (fun _ h => (hs _).imp (⟨·, h⟩))).imp (·.2)\n\ntheorem size_mapM [Monad m] [LawfulMonad m] (f : α → m β) (as : Array α) :\n SatisfiesM (fun arr => arr.size = as.size) (Array.mapM f as) :=\n (SatisfiesM_mapM' _ _ (fun _ _ => True) (fun _ => .trivial)).imp (·.1)\n\n@[simp] theorem map_data (f : α → β) (arr : Array α) : (arr.map f).data = arr.data.map f := by\n apply congrArg data (foldl_eq_foldl_data (fun bs a => push bs (f a)) #[] arr) |>.trans\n have H (l arr) : List.foldl (fun bs a => push bs (f a)) arr l = ⟨arr.data ++ l.map f⟩ := by\n induction l generalizing arr <;> simp [*]\n simp [H]\n\n@[simp] theorem size_map (f : α → β) (arr : Array α) : (arr.map f).size = arr.size := by\n simp [size]\n\n@[simp] theorem getElem_map (f : α → β) (arr : Array α) (i : Nat) (h) :\n ((arr.map f)[i]'h) = f (arr[i]'(size_map .. ▸ h)) := by\n have := SatisfiesM_mapM' (m := Id) arr f (fun i b => b = f (arr[i]))\n simp [SatisfiesM_Id_eq] at this\n exact this.2 i (size_map .. ▸ h)\n\n@[simp] theorem pop_data (arr : Array α) : arr.pop.data = arr.data.dropLast := rfl\n\n@[simp] theorem append_eq_append (arr arr' : Array α) : arr.append arr' = arr ++ arr' := rfl\n\n@[simp] theorem append_data (arr arr' : Array α) :\n (arr ++ arr').data = arr.data ++ arr'.data := by\n rw [← append_eq_append]; unfold Array.append\n rw [foldl_eq_foldl_data]\n induction arr'.data generalizing arr <;> simp [*]\n\n@[simp] theorem appendList_eq_append\n (arr : Array α) (l : List α) : arr.appendList l = arr ++ l := rfl\n\n@[simp] theorem appendList_data (arr : Array α) (l : List α) :\n (arr ++ l).data = arr.data ++ l := by\n rw [← appendList_eq_append]; unfold Array.appendList\n induction l generalizing arr <;> simp [*]\n\ntheorem foldl_data_eq_bind (l : List α) (acc : Array β)\n (F : Array β → α → Array β) (G : α → List β)\n (H : ∀ acc a, (F acc a).data = acc.data ++ G a) :\n (l.foldl F acc).data = acc.data ++ l.bind G := by\n induction l generalizing acc <;> simp [*, List.bind]\n\ntheorem foldl_data_eq_map (l : List α) (acc : Array β) (G : α → β) :\n (l.foldl (fun acc a => acc.push (G a)) acc).data = acc.data ++ l.map G := by\n induction l generalizing acc <;> simp [*]\n\ntheorem size_uset (a : Array α) (v i h) : (uset a i v h).size = a.size := by simp\n", "meta": {"author": "leanprover", "repo": "std4", "sha": "5507f9d8409f93b984ce04eccf4914d534e6fca2", "save_path": "github-repos/lean/leanprover-std4", "path": "github-repos/lean/leanprover-std4/std4-5507f9d8409f93b984ce04eccf4914d534e6fca2/Std/Data/Array/Init/Lemmas.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4843800693903656, "lm_q2_score": 0.08389038354759046, "lm_q1q2_score": 0.04063482980396625}} {"text": "/-\nCopyright (c) 2022 Yaël Dillies. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Yaël Dillies\n-/\nimport order.category.BddDistLat\nimport order.heyting.hom\n\n/-!\n# The category of Heyting algebras\n\nThis file defines `HeytAlg`, the category of Heyting algebras.\n-/\n\nuniverses u\n\nopen category_theory opposite order\n\n/-- The category of Heyting algebras. -/\ndef HeytAlg := bundled heyting_algebra\n\nnamespace HeytAlg\n\ninstance : has_coe_to_sort HeytAlg Type* := bundled.has_coe_to_sort\ninstance (X : HeytAlg) : heyting_algebra X := X.str\n\n/-- Construct a bundled `HeytAlg` from a `heyting_algebra`. -/\ndef of (α : Type*) [heyting_algebra α] : HeytAlg := bundled.of α\n\n@[simp] lemma coe_of (α : Type*) [heyting_algebra α] : ↥(of α) = α := rfl\n\ninstance : inhabited HeytAlg := ⟨of punit⟩\n\ninstance bundled_hom : bundled_hom heyting_hom :=\n{ to_fun := λ α β [heyting_algebra α] [heyting_algebra β],\n by exactI (coe_fn : heyting_hom α β → α → β),\n id := heyting_hom.id,\n comp := @heyting_hom.comp,\n hom_ext := λ α β [heyting_algebra α] [heyting_algebra β], by exactI fun_like.coe_injective }\n\nattribute [derive [large_category, concrete_category]] HeytAlg\n\n@[simps]\ninstance has_forget_to_Lat : has_forget₂ HeytAlg BddDistLat :=\n{ forget₂ := { obj := λ X, BddDistLat.of X,\n map := λ X Y f, (f : bounded_lattice_hom X Y) } }\n\n/-- Constructs an isomorphism of Heyting algebras from an order isomorphism between them. -/\n@[simps] def iso.mk {α β : HeytAlg.{u}} (e : α ≃o β) : α ≅ β :=\n{ hom := e,\n inv := e.symm,\n hom_inv_id' := by { ext, exact e.symm_apply_apply _ },\n inv_hom_id' := by { ext, exact e.apply_symm_apply _ } }\n\nend HeytAlg\n", "meta": {"author": "leanprover-community", "repo": "mathlib", "sha": "5e526d18cea33550268dcbbddcb822d5cde40654", "save_path": "github-repos/lean/leanprover-community-mathlib", "path": "github-repos/lean/leanprover-community-mathlib/mathlib-5e526d18cea33550268dcbbddcb822d5cde40654/src/order/category/HeytAlg.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828341018881344, "lm_q2_score": 0.08269735002250668, "lm_q1q2_score": 0.04037974408256751}} {"text": "/-\nCopyright (c) 2017 Mario Carneiro. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Mario Carneiro\n\n! This file was ported from Lean 3 source module data.list.infix\n! leanprover-community/mathlib commit 26f081a2fb920140ed5bc5cc5344e84bcc7cb2b2\n! Please do not edit these lines, except to modify the commit id\n! if you have ported upstream changes.\n-/\nimport Mathlib.Data.List.Basic\n\n/-!\n# Prefixes, subfixes, infixes\n\nThis file proves properties about\n* `List.prefix`: `l₁` is a prefix of `l₂` if `l₂` starts with `l₁`.\n* `List.subfix`: `l₁` is a subfix of `l₂` if `l₂` ends with `l₁`.\n* `List.infix`: `l₁` is an infix of `l₂` if `l₁` is a prefix of some subfix of `l₂`.\n* `List.inits`: The list of prefixes of a list.\n* `List.tails`: The list of prefixes of a list.\n* `insert` on lists\n\nAll those (except `insert`) are defined in `Mathlib.Data.List.Defs`.\n\n## Notation\n\n`l₁ <+: l₂`: `l₁` is a prefix of `l₂`.\n`l₁ <:+ l₂`: `l₁` is a subfix of `l₂`.\n`l₁ <:+: l₂`: `l₁` is an infix of `l₂`.\n-/\n\nopen Nat\n\nvariable {α β : Type _}\n\nnamespace List\n\nvariable {l l₁ l₂ l₃ : List α} {a b : α} {m n : ℕ}\n\n/-! ### prefix, suffix, infix -/\n\n\nsection Fix\n\n@[simp]\ntheorem prefix_append (l₁ l₂ : List α) : l₁ <+: l₁ ++ l₂ :=\n ⟨l₂, rfl⟩\n#align list.prefix_append List.prefix_append\n\n@[simp]\ntheorem suffix_append (l₁ l₂ : List α) : l₂ <:+ l₁ ++ l₂ :=\n ⟨l₁, rfl⟩\n#align list.suffix_append List.suffix_append\n\ntheorem infix_append (l₁ l₂ l₃ : List α) : l₂ <:+: l₁ ++ l₂ ++ l₃ :=\n ⟨l₁, l₃, rfl⟩\n#align list.infix_append List.infix_append\n\n@[simp]\ntheorem infix_append' (l₁ l₂ l₃ : List α) : l₂ <:+: l₁ ++ (l₂ ++ l₃) := by\n rw [← List.append_assoc]; apply infix_append\n#align list.infix_append' List.infix_append'\n\ntheorem isPrefix.isInfix : l₁ <+: l₂ → l₁ <:+: l₂ := fun ⟨t, h⟩ => ⟨[], t, h⟩\n#align list.is_prefix.is_infix List.isPrefix.isInfix\n\ntheorem isSuffix.isInfix : l₁ <:+ l₂ → l₁ <:+: l₂ := fun ⟨t, h⟩ => ⟨t, [], by rw [h, append_nil]⟩\n#align list.is_suffix.is_infix List.isSuffix.isInfix\n\ntheorem nil_prefix (l : List α) : [] <+: l :=\n ⟨l, rfl⟩\n#align list.nil_prefix List.nil_prefix\n\ntheorem nil_suffix (l : List α) : [] <:+ l :=\n ⟨l, append_nil _⟩\n#align list.nil_suffix List.nil_suffix\n\ntheorem nil_infix (l : List α) : [] <:+: l :=\n (nil_prefix _).isInfix\n#align list.nil_infix List.nil_infix\n\n@[refl]\ntheorem prefix_refl (l : List α) : l <+: l :=\n ⟨[], append_nil _⟩\n#align list.prefix_refl List.prefix_refl\n\n@[refl]\ntheorem suffix_refl (l : List α) : l <:+ l :=\n ⟨[], rfl⟩\n#align list.suffix_refl List.suffix_refl\n\n@[refl]\ntheorem infix_refl (l : List α) : l <:+: l :=\n (prefix_refl l).isInfix\n#align list.infix_refl List.infix_refl\n\ntheorem prefix_rfl : l <+: l :=\n prefix_refl _\n#align list.prefix_rfl List.prefix_rfl\n\ntheorem suffix_rfl : l <:+ l :=\n suffix_refl _\n#align list.suffix_rfl List.suffix_rfl\n\ntheorem infix_rfl : l <:+: l :=\n infix_refl _\n#align list.infix_rfl List.infix_rfl\n\n@[simp]\ntheorem suffix_cons (a : α) : ∀ l, l <:+ a :: l :=\n suffix_append [a]\n#align list.suffix_cons List.suffix_cons\n\ntheorem prefix_concat (a : α) (l) : l <+: concat l a := by simp\n#align list.prefix_concat List.prefix_concat\n\ntheorem infix_cons : l₁ <:+: l₂ → l₁ <:+: a :: l₂ := fun ⟨L₁, L₂, h⟩ => ⟨a :: L₁, L₂, h ▸ rfl⟩\n#align list.infix_cons List.infix_cons\n\ntheorem infix_concat : l₁ <:+: l₂ → l₁ <:+: concat l₂ a := fun ⟨L₁, L₂, h⟩ =>\n ⟨L₁, concat L₂ a, by simp_rw [← h, concat_eq_append, append_assoc]⟩\n#align list.infix_concat List.infix_concat\n\n@[trans]\ntheorem isPrefix.trans : ∀ {l₁ l₂ l₃ : List α}, l₁ <+: l₂ → l₂ <+: l₃ → l₁ <+: l₃\n | _, _, _, ⟨r₁, rfl⟩, ⟨r₂, rfl⟩ => ⟨r₁ ++ r₂, (append_assoc _ _ _).symm⟩\n#align list.is_prefix.trans List.isPrefix.trans\n\n@[trans]\ntheorem isSuffix.trans : ∀ {l₁ l₂ l₃ : List α}, l₁ <:+ l₂ → l₂ <:+ l₃ → l₁ <:+ l₃\n | _, _, _, ⟨l₁, rfl⟩, ⟨l₂, rfl⟩ => ⟨l₂ ++ l₁, append_assoc _ _ _⟩\n#align list.is_suffix.trans List.isSuffix.trans\n\n@[trans]\ntheorem isInfix.trans : ∀ {l₁ l₂ l₃ : List α}, l₁ <:+: l₂ → l₂ <:+: l₃ → l₁ <:+: l₃\n | l, _, _, ⟨l₁, r₁, rfl⟩, ⟨l₂, r₂, rfl⟩ => ⟨l₂ ++ l₁, r₁ ++ r₂, by simp only [append_assoc]⟩\n#align list.is_infix.trans List.isInfix.trans\n\nprotected theorem isInfix.sublist : l₁ <:+: l₂ → l₁ <+ l₂ := fun ⟨s, t, h⟩ => by\n rw [← h]\n exact (sublist_append_right _ _).trans (sublist_append_left _ _)\n#align list.is_infix.sublist List.isInfix.sublist\n\nprotected theorem isInfix.subset (hl : l₁ <:+: l₂) : l₁ ⊆ l₂ :=\n hl.sublist.subset\n#align list.is_infix.subset List.isInfix.subset\n\nprotected theorem isPrefix.sublist (h : l₁ <+: l₂) : l₁ <+ l₂ :=\n h.isInfix.sublist\n#align list.is_prefix.sublist List.isPrefix.sublist\n\nprotected theorem isPrefix.subset (hl : l₁ <+: l₂) : l₁ ⊆ l₂ :=\n hl.sublist.subset\n#align list.is_prefix.subset List.isPrefix.subset\n\nprotected theorem isSuffix.sublist (h : l₁ <:+ l₂) : l₁ <+ l₂ :=\n h.isInfix.sublist\n#align list.is_suffix.sublist List.isSuffix.sublist\n\nprotected theorem isSuffix.subset (hl : l₁ <:+ l₂) : l₁ ⊆ l₂ :=\n hl.sublist.subset\n#align list.is_suffix.subset List.isSuffix.subset\n\n@[simp]\ntheorem reverse_suffix : reverse l₁ <:+ reverse l₂ ↔ l₁ <+: l₂ :=\n ⟨fun ⟨r, e⟩ => ⟨reverse r, by rw [← reverse_reverse l₁, ← reverse_append, e, reverse_reverse]⟩,\n fun ⟨r, e⟩ => ⟨reverse r, by rw [← reverse_append, e]⟩⟩\n#align list.reverse_suffix List.reverse_suffix\n\n@[simp]\ntheorem reverse_prefix : reverse l₁ <+: reverse l₂ ↔ l₁ <:+ l₂ := by\n rw [← reverse_suffix]; simp only [reverse_reverse]\n#align list.reverse_prefix List.reverse_prefix\n\n@[simp]\ntheorem reverse_infix : reverse l₁ <:+: reverse l₂ ↔ l₁ <:+: l₂ :=\n ⟨fun ⟨s, t, e⟩ =>\n ⟨reverse t, reverse s, by\n rw [← reverse_reverse l₁, append_assoc, ← reverse_append, ← reverse_append, e,\n reverse_reverse]⟩,\n fun ⟨s, t, e⟩ =>\n ⟨reverse t, reverse s, by rw [append_assoc, ← reverse_append, ← reverse_append, e]⟩⟩\n#align list.reverse_infix List.reverse_infix\n\nalias reverse_prefix ↔ _ isSuffix.reverse\n#align list.is_suffix.reverse List.isSuffix.reverse\n\nalias reverse_suffix ↔ _ isPrefix.reverse\n#align list.is_prefix.reverse List.isPrefix.reverse\n\nalias reverse_infix ↔ _ isInfix.reverse\n#align list.is_infix.reverse List.isInfix.reverse\n\ntheorem isInfix.length_le (h : l₁ <:+: l₂) : l₁.length ≤ l₂.length :=\n h.sublist.length_le\n#align list.is_infix.length_le List.isInfix.length_le\n\ntheorem isPrefix.length_le (h : l₁ <+: l₂) : l₁.length ≤ l₂.length :=\n h.sublist.length_le\n#align list.is_prefix.length_le List.isPrefix.length_le\n\ntheorem isSuffix.length_le (h : l₁ <:+ l₂) : l₁.length ≤ l₂.length :=\n h.sublist.length_le\n#align list.is_suffix.length_le List.isSuffix.length_le\n\ntheorem eq_nil_of_infix_nil (h : l <:+: []) : l = [] :=\n eq_nil_of_sublist_nil h.sublist\n#align list.eq_nil_of_infix_nil List.eq_nil_of_infix_nil\n\n@[simp]\ntheorem infix_nil_iff : l <:+: [] ↔ l = [] :=\n ⟨fun h => eq_nil_of_sublist_nil h.sublist, fun h => h ▸ infix_rfl⟩\n#align list.infix_nil_iff List.infix_nil_iff\n\n@[simp]\ntheorem prefix_nil_iff : l <+: [] ↔ l = [] :=\n ⟨fun h => eq_nil_of_infix_nil h.isInfix, fun h => h ▸ prefix_rfl⟩\n#align list.prefix_nil_iff List.prefix_nil_iff\n\n@[simp]\ntheorem suffix_nil_iff : l <:+ [] ↔ l = [] :=\n ⟨fun h => eq_nil_of_infix_nil h.isInfix, fun h => h ▸ suffix_rfl⟩\n#align list.suffix_nil_iff List.suffix_nil_iff\n\nalias prefix_nil_iff ↔ eq_nil_of_prefix_nil _\n#align list.eq_nil_of_prefix_nil List.eq_nil_of_prefix_nil\n\nalias suffix_nil_iff ↔ eq_nil_of_suffix_nil _\n#align list.eq_nil_of_suffix_nil List.eq_nil_of_suffix_nil\n\ntheorem infix_iff_prefix_suffix (l₁ l₂ : List α) : l₁ <:+: l₂ ↔ ∃ t, l₁ <+: t ∧ t <:+ l₂ :=\n ⟨fun ⟨s, t, e⟩ => ⟨l₁ ++ t, ⟨_, rfl⟩, by rw [← e, append_assoc]; exact ⟨_, rfl⟩⟩,\n fun ⟨_, ⟨t, rfl⟩, s, e⟩ => ⟨s, t, by rw [append_assoc]; exact e⟩⟩\n#align list.infix_iff_prefix_suffix List.infix_iff_prefix_suffix\n\ntheorem eq_of_infix_of_length_eq (h : l₁ <:+: l₂) : l₁.length = l₂.length → l₁ = l₂ :=\n h.sublist.eq_of_length\n#align list.eq_of_infix_of_length_eq List.eq_of_infix_of_length_eq\n\ntheorem eq_of_prefix_of_length_eq (h : l₁ <+: l₂) : l₁.length = l₂.length → l₁ = l₂ :=\n h.sublist.eq_of_length\n#align list.eq_of_prefix_of_length_eq List.eq_of_prefix_of_length_eq\n\ntheorem eq_of_suffix_of_length_eq (h : l₁ <:+ l₂) : l₁.length = l₂.length → l₁ = l₂ :=\n h.sublist.eq_of_length\n#align list.eq_of_suffix_of_length_eq List.eq_of_suffix_of_length_eq\n\ntheorem prefix_of_prefix_length_le : ∀ { l₁ l₂ l₃ : List α } ,\n l₁ <+: l₃ → l₂ <+: l₃ → length l₁ ≤ length l₂ → l₁ <+: l₂\n| [] , l₂ , _, _, _, _ => nil_prefix _\n| a :: l₁ , b :: l₂ , _ , ⟨ r₁ , rfl ⟩ , ⟨ r₂ , e ⟩ , ll => by\n injection e with _ e'\n subst b\n rcases prefix_of_prefix_length_le ⟨ _ , rfl ⟩ ⟨ _ , e' ⟩\n (le_of_succ_le_succ ll) with ⟨ r₃ , rfl ⟩\n exact ⟨ r₃ , rfl ⟩\n#align list.prefix_of_prefix_length_le List.prefix_of_prefix_length_le\n\ntheorem prefix_or_prefix_of_prefix (h₁ : l₁ <+: l₃) (h₂ : l₂ <+: l₃) : l₁ <+: l₂ ∨ l₂ <+: l₁ :=\n (le_total (length l₁) (length l₂)).imp (prefix_of_prefix_length_le h₁ h₂)\n (prefix_of_prefix_length_le h₂ h₁)\n#align list.prefix_or_prefix_of_prefix List.prefix_or_prefix_of_prefix\n\ntheorem suffix_of_suffix_length_le (h₁ : l₁ <:+ l₃) (h₂ : l₂ <:+ l₃) (ll : length l₁ ≤ length l₂) :\n l₁ <:+ l₂ :=\n reverse_prefix.1 <|\n prefix_of_prefix_length_le (reverse_prefix.2 h₁) (reverse_prefix.2 h₂) (by simp [ll])\n#align list.suffix_of_suffix_length_le List.suffix_of_suffix_length_le\n\ntheorem suffix_or_suffix_of_suffix (h₁ : l₁ <:+ l₃) (h₂ : l₂ <:+ l₃) : l₁ <:+ l₂ ∨ l₂ <:+ l₁ :=\n (prefix_or_prefix_of_prefix (reverse_prefix.2 h₁) (reverse_prefix.2 h₂)).imp reverse_prefix.1\n reverse_prefix.1\n#align list.suffix_or_suffix_of_suffix List.suffix_or_suffix_of_suffix\n\ntheorem suffix_cons_iff : l₁ <:+ a :: l₂ ↔ l₁ = a :: l₂ ∨ l₁ <:+ l₂ := by\n constructor\n · rintro ⟨⟨hd, tl⟩, hl₃⟩\n · exact Or.inl hl₃\n · simp only [cons_append] at hl₃\n injection hl₃ with _ hl₄\n exact Or.inr ⟨_, hl₄⟩\n · rintro (rfl | hl₁)\n · exact (a :: l₂).suffix_refl\n · exact hl₁.trans (l₂.suffix_cons _)\n#align list.suffix_cons_iff List.suffix_cons_iff\n\ntheorem infix_cons_iff : l₁ <:+: a :: l₂ ↔ l₁ <+: a :: l₂ ∨ l₁ <:+: l₂ := by\n constructor\n · rintro ⟨⟨hd, tl⟩, t, hl₃⟩\n · exact Or.inl ⟨t, hl₃⟩\n · simp only [cons_append] at hl₃\n injection hl₃ with _ hl₄\n exact Or.inr ⟨_, t, hl₄⟩\n · rintro (h | hl₁)\n · exact h.isInfix\n · exact infix_cons hl₁\n#align list.infix_cons_iff List.infix_cons_iff\n\ntheorem infix_of_mem_join : ∀ {L : List (List α)}, l ∈ L → l <:+: join L\n | l' :: _, h =>\n match h with\n | List.Mem.head .. => infix_append [] _ _\n | List.Mem.tail _ hlMemL =>\n isInfix.trans (infix_of_mem_join hlMemL) <| (suffix_append _ _).isInfix\n#align list.infix_of_mem_join List.infix_of_mem_join\n\ntheorem prefix_append_right_inj (l) : l ++ l₁ <+: l ++ l₂ ↔ l₁ <+: l₂ :=\n exists_congr fun r => by rw [append_assoc, append_right_inj]\n#align list.prefix_append_right_inj List.prefix_append_right_inj\n\ntheorem prefix_cons_inj (a) : a :: l₁ <+: a :: l₂ ↔ l₁ <+: l₂ :=\n prefix_append_right_inj [a]\n#align list.prefix_cons_inj List.prefix_cons_inj\n\ntheorem take_prefix (n) (l : List α) : take n l <+: l :=\n ⟨_, take_append_drop _ _⟩\n#align list.take_prefix List.take_prefix\n\ntheorem drop_suffix (n) (l : List α) : drop n l <:+ l :=\n ⟨_, take_append_drop _ _⟩\n#align list.drop_suffix List.drop_suffix\n\ntheorem take_sublist (n) (l : List α) : take n l <+ l :=\n (take_prefix n l).sublist\n#align list.take_sublist List.take_sublist\n\ntheorem drop_sublist (n) (l : List α) : drop n l <+ l :=\n (drop_suffix n l).sublist\n#align list.drop_sublist List.drop_sublist\n\ntheorem take_subset (n) (l : List α) : take n l ⊆ l :=\n (take_sublist n l).subset\n#align list.take_subset List.take_subset\n\ntheorem drop_subset (n) (l : List α) : drop n l ⊆ l :=\n (drop_sublist n l).subset\n#align list.drop_subset List.drop_subset\n\ntheorem mem_of_mem_take (h : a ∈ l.take n) : a ∈ l :=\n take_subset n l h\n#align list.mem_of_mem_take List.mem_of_mem_take\n\n#align list.mem_of_mem_drop List.mem_of_mem_drop\n\nlemma dropSlice_sublist (n m : ℕ) (l : List α) : l.dropSlice n m <+ l :=\n calc l.dropSlice n m = take n l ++ drop m (drop n l) := by rw [dropSlice_eq, drop_drop, add_comm]\n _ <+ take n l ++ drop n l := (Sublist.refl _).append (drop_sublist _ _)\n _ = _ := take_append_drop _ _\n#align list.slice_sublist List.dropSlice_sublist\n\nlemma dropSlice_subset (n m : ℕ) (l : List α) : l.dropSlice n m ⊆ l :=\n (dropSlice_sublist n m l).subset\n#align list.slice_subset List.dropSlice_subset\n\nlemma mem_of_mem_dropSlice {n m : ℕ} {l : List α} {a : α} (h : a ∈ l.dropSlice n m) : a ∈ l :=\n dropSlice_subset n m l h\n#align list.mem_of_mem_slice List.mem_of_mem_dropSlice\n\ntheorem takeWhile_prefix (p : α → Bool) : l.takeWhile p <+: l :=\n ⟨l.dropWhile p, takeWhile_append_drop p l⟩\n#align list.take_while_prefix List.takeWhile_prefix\n\ntheorem dropWhile_suffix (p : α → Bool) : l.dropWhile p <:+ l :=\n ⟨l.takeWhile p, takeWhile_append_drop p l⟩\n#align list.drop_while_suffix List.dropWhile_suffix\n\ntheorem dropLast_prefix : ∀ l : List α, l.dropLast <+: l\n | [] => ⟨nil, by rw [dropLast, List.append_nil]⟩\n | a :: l => ⟨_, dropLast_append_getLast (cons_ne_nil a l)⟩\n#align list.init_prefix List.dropLast_prefix\n\ntheorem tail_suffix (l : List α) : tail l <:+ l := by rw [← drop_one]; apply drop_suffix\n#align list.tail_suffix List.tail_suffix\n\ntheorem dropLast_sublist (l : List α) : l.dropLast <+ l :=\n (dropLast_prefix l).sublist\n#align list.init_sublist List.dropLast_sublist\n\ntheorem tail_sublist (l : List α) : l.tail <+ l :=\n (tail_suffix l).sublist\n#align list.tail_sublist List.tail_sublist\n\ntheorem dropLast_subset (l : List α) : l.dropLast ⊆ l :=\n (dropLast_sublist l).subset\n#align list.init_subset List.dropLast_subset\n\ntheorem tail_subset (l : List α) : tail l ⊆ l :=\n (tail_sublist l).subset\n#align list.tail_subset List.tail_subset\n\ntheorem mem_of_mem_dropLast (h : a ∈ l.dropLast) : a ∈ l :=\n dropLast_subset l h\n#align list.mem_of_mem_init List.mem_of_mem_dropLast\n\ntheorem mem_of_mem_tail (h : a ∈ l.tail) : a ∈ l :=\n tail_subset l h\n#align list.mem_of_mem_tail List.mem_of_mem_tail\n\ntheorem prefix_iff_eq_append : l₁ <+: l₂ ↔ l₁ ++ drop (length l₁) l₂ = l₂ :=\n ⟨by rintro ⟨r, rfl⟩; rw [drop_left], fun e => ⟨_, e⟩⟩\n#align list.prefix_iff_eq_append List.prefix_iff_eq_append\n\ntheorem suffix_iff_eq_append : l₁ <:+ l₂ ↔ take (length l₂ - length l₁) l₂ ++ l₁ = l₂ :=\n ⟨by rintro ⟨r, rfl⟩; simp only [length_append, add_tsub_cancel_right, take_left], fun e =>\n ⟨_, e⟩⟩\n#align list.suffix_iff_eq_append List.suffix_iff_eq_append\n\ntheorem prefix_iff_eq_take : l₁ <+: l₂ ↔ l₁ = take (length l₁) l₂ :=\n ⟨fun h => append_right_cancel <| (prefix_iff_eq_append.1 h).trans (take_append_drop _ _).symm,\n fun e => e.symm ▸ take_prefix _ _⟩\n#align list.prefix_iff_eq_take List.prefix_iff_eq_take\n\ntheorem suffix_iff_eq_drop : l₁ <:+ l₂ ↔ l₁ = drop (length l₂ - length l₁) l₂ :=\n ⟨fun h => append_left_cancel <| (suffix_iff_eq_append.1 h).trans (take_append_drop _ _).symm,\n fun e => e.symm ▸ drop_suffix _ _⟩\n#align list.suffix_iff_eq_drop List.suffix_iff_eq_drop\n\ninstance decidablePrefix [DecidableEq α] : ∀ l₁ l₂ : List α, Decidable (l₁ <+: l₂)\n | [], l₂ => isTrue ⟨l₂, rfl⟩\n | a :: l₁, [] => isFalse fun ⟨t, te⟩ => List.noConfusion te\n | a :: l₁, b :: l₂ =>\n if h : a = b then\n @decidable_of_decidable_of_iff _ _ (decidablePrefix l₁ l₂) (by rw [← h, prefix_cons_inj])\n else\n isFalse fun ⟨t, te⟩ => h <| by injection te\n#align list.decidable_prefix List.decidablePrefix\n\n-- Alternatively, use mem_tails\ninstance decidableSuffix [DecidableEq α] : ∀ l₁ l₂ : List α, Decidable (l₁ <:+ l₂)\n | [], l₂ => isTrue ⟨l₂, append_nil _⟩\n | a :: l₁, [] => isFalse <| mt (Sublist.length_le ∘ isSuffix.sublist) (by simp)\n | l₁, b :: l₂ =>\n @decidable_of_decidable_of_iff _ _\n (@instDecidableOr _ _ _ (l₁.decidableSuffix l₂))\n suffix_cons_iff.symm\ntermination_by decidableSuffix l₁ l₂ => (l₁, l₂)\n\n#align list.decidable_suffix List.decidableSuffix\n\ninstance decidableInfix [DecidableEq α] : ∀ l₁ l₂ : List α, Decidable (l₁ <:+: l₂)\n | [], l₂ => isTrue ⟨[], l₂, rfl⟩\n | a :: l₁, [] => isFalse fun ⟨s, t, te⟩ => by simp at te\n | l₁, b :: l₂ =>\n @decidable_of_decidable_of_iff _ _\n (@instDecidableOr _ _ (l₁.decidablePrefix (b :: l₂)) (l₁.decidableInfix l₂))\n infix_cons_iff.symm\ntermination_by decidableInfix l₁ l₂ => (l₁, l₂)\n#align list.decidable_infix List.decidableInfix\n\ntheorem prefix_take_le_iff {L : List (List (Option α))} (hm : m < L.length) :\n L.take m <+: L.take n ↔ m ≤ n := by\n simp only [prefix_iff_eq_take, length_take]\n induction m generalizing L n with\n | zero => simp [min_eq_left, eq_self_iff_true, Nat.zero_le, take]\n | succ m IH =>\n cases L with\n | nil => exact (not_lt_bot hm).elim\n | cons l ls =>\n cases n with\n | zero =>\n refine' iff_of_false _ (zero_lt_succ _).not_le\n rw [take_zero, take_nil]\n simp only [take]\n | succ n =>\n simp only [length] at hm\n have specializedIH := @IH n ls (Nat.lt_of_succ_lt_succ hm)\n simp only [le_of_lt (Nat.lt_of_succ_lt_succ hm), min_eq_left] at specializedIH\n simp [le_of_lt hm, specializedIH, true_and_iff, min_eq_left, eq_self_iff_true, length, take]\n exact ⟨Nat.succ_le_succ, Nat.le_of_succ_le_succ⟩\n#align list.prefix_take_le_iff List.prefix_take_le_iff\n\ntheorem cons_prefix_iff : a :: l₁ <+: b :: l₂ ↔ a = b ∧ l₁ <+: l₂ := by\n constructor\n · rintro ⟨L, hL⟩\n simp only [cons_append] at hL\n injection hL with hLLeft hLRight\n exact ⟨hLLeft, ⟨L, hLRight⟩⟩\n · rintro ⟨rfl, h⟩\n rwa [prefix_cons_inj]\n#align list.cons_prefix_iff List.cons_prefix_iff\n\ntheorem isPrefix.map (h : l₁ <+: l₂) (f : α → β) : l₁.map f <+: l₂.map f := by\n induction' l₁ with hd tl hl generalizing l₂\n · simp only [nil_prefix, map_nil]\n · cases' l₂ with hd₂ tl₂\n · simpa only using eq_nil_of_prefix_nil h\n · rw [cons_prefix_iff] at h\n simp only [List.map_cons, h, prefix_cons_inj, hl, map]\n#align list.is_prefix.map List.isPrefix.map\n\ntheorem isPrefix.filter_map (h : l₁ <+: l₂) (f : α → Option β) :\n l₁.filterMap f <+: l₂.filterMap f := by\n induction' l₁ with hd₁ tl₁ hl generalizing l₂\n · simp only [nil_prefix, filterMap_nil]\n · cases' l₂ with hd₂ tl₂\n · simpa only using eq_nil_of_prefix_nil h\n · rw [cons_prefix_iff] at h\n rw [← @singleton_append _ hd₁ _, ← @singleton_append _ hd₂ _, filterMap_append,\n filterMap_append, h.left, prefix_append_right_inj]\n exact hl h.right\n#align list.is_prefix.filter_map List.isPrefix.filter_map\n\ntheorem isPrefix.reduceOption {l₁ l₂ : List (Option α)} (h : l₁ <+: l₂) :\n l₁.reduceOption <+: l₂.reduceOption :=\n h.filter_map id\n#align list.is_prefix.reduce_option List.isPrefix.reduceOption\n\ntheorem isPrefix.filter (p : α → Bool) ⦃l₁ l₂ : List α⦄ (h : l₁ <+: l₂) :\n l₁.filter p <+: l₂.filter p := by\n obtain ⟨xs, rfl⟩ := h\n rw [filter_append]\n exact prefix_append _ _\n#align list.is_prefix.filter List.isPrefix.filter\n\ntheorem isSuffix.filter (p : α → Bool) ⦃l₁ l₂ : List α⦄ (h : l₁ <:+ l₂) :\n l₁.filter p <:+ l₂.filter p := by\n obtain ⟨xs, rfl⟩ := h\n rw [filter_append]\n exact suffix_append _ _\n#align list.is_suffix.filter List.isSuffix.filter\n\ntheorem isInfix.filter (p : α → Bool) ⦃l₁ l₂ : List α⦄ (h : l₁ <:+: l₂) :\n l₁.filter p <:+: l₂.filter p := by\n obtain ⟨xs, ys, rfl⟩ := h\n rw [filter_append, filter_append]\n exact infix_append _ _ _\n#align list.is_infix.filter List.isInfix.filter\n\ninstance : IsPartialOrder (List α) (· <+: ·) where\n refl := prefix_refl\n trans _ _ _ := isPrefix.trans\n antisymm _ _ h₁ h₂ := eq_of_prefix_of_length_eq h₁ <| h₁.length_le.antisymm h₂.length_le\n\ninstance : IsPartialOrder (List α) (· <:+ ·) where\n refl := suffix_refl\n trans _ _ _ := isSuffix.trans\n antisymm _ _ h₁ h₂ := eq_of_suffix_of_length_eq h₁ <| h₁.length_le.antisymm h₂.length_le\n\ninstance : IsPartialOrder (List α) (· <:+: ·) where\n refl := infix_refl\n trans _ _ _ := isInfix.trans\n antisymm _ _ h₁ h₂ := eq_of_infix_of_length_eq h₁ <| h₁.length_le.antisymm h₂.length_le\n\nend Fix\n\nsection InitsTails\n\n@[simp]\ntheorem mem_inits : ∀ s t : List α, s ∈ inits t ↔ s <+: t\n | s, [] =>\n suffices s = nil ↔ s <+: nil by simpa only [inits, mem_singleton]\n ⟨fun h => h.symm ▸ prefix_refl [], eq_nil_of_prefix_nil⟩\n | s, a :: t =>\n suffices (s = nil ∨ ∃ l ∈ inits t, a :: l = s) ↔ s <+: a :: t by simpa\n ⟨fun o =>\n match s, o with\n | _, Or.inl rfl => ⟨_, rfl⟩\n | s, Or.inr ⟨r, hr, hs⟩ => by\n let ⟨s, ht⟩ := (mem_inits _ _).1 hr\n rw [← hs, ← ht]; exact ⟨s, rfl⟩,\n fun mi =>\n match s, mi with\n | [], ⟨_, rfl⟩ => Or.inl rfl\n | b :: s, ⟨r, hr⟩ =>\n (List.noConfusion hr) fun ba (st : s ++ r = t) =>\n Or.inr <| by rw [ba]; exact ⟨_, (mem_inits _ _).2 ⟨_, st⟩, rfl⟩⟩\n#align list.mem_inits List.mem_inits\n\n@[simp]\ntheorem mem_tails : ∀ s t : List α, s ∈ tails t ↔ s <:+ t\n | s, [] => by\n simp only [tails, mem_singleton]\n exact ⟨fun h => by rw [h], eq_nil_of_suffix_nil⟩\n | s, a :: t => by\n simp only [tails, mem_cons, mem_tails s t];\n exact\n show s = a :: t ∨ s <:+ t ↔ s <:+ a :: t from\n ⟨fun o =>\n match s, t, o with\n | _, t, Or.inl rfl => suffix_rfl\n | s, _, Or.inr ⟨l, rfl⟩ => ⟨a :: l, rfl⟩,\n fun e =>\n match s, t, e with\n | _, t, ⟨[], rfl⟩ => Or.inl rfl\n | s, t, ⟨b :: l, he⟩ => List.noConfusion he fun _ lt => Or.inr ⟨l, lt⟩⟩\n#align list.mem_tails List.mem_tails\n\ntheorem inits_cons (a : α) (l : List α) : inits (a :: l) = [] :: l.inits.map fun t => a :: t := by\n simp\n#align list.inits_cons List.inits_cons\n\ntheorem tails_cons (a : α) (l : List α) : tails (a :: l) = (a :: l) :: l.tails := by simp\n#align list.tails_cons List.tails_cons\n\n@[simp]\ntheorem inits_append : ∀ s t : List α, inits (s ++ t) = s.inits ++ t.inits.tail.map fun l => s ++ l\n | [], [] => by simp\n | [], a :: t => by simp[· ∘ ·]\n | a :: s, t => by simp [inits_append s t, · ∘ ·]\n#align list.inits_append List.inits_append\n\n@[simp]\ntheorem tails_append :\n ∀ s t : List α, tails (s ++ t) = (s.tails.map fun l => l ++ t) ++ t.tails.tail\n | [], [] => by simp\n | [], a :: t => by simp\n | a :: s, t => by simp [tails_append s t]\n#align list.tails_append List.tails_append\n\n-- the lemma names `inits_eq_tails` and `tails_eq_inits` are like `sublists_eq_sublists'`\ntheorem inits_eq_tails : ∀ l : List α, l.inits = (reverse <| map reverse <| tails <| reverse l)\n | [] => by simp\n | a :: l => by simp [inits_eq_tails l, map_eq_map_iff, reverse_map]\n#align list.inits_eq_tails List.inits_eq_tails\n\ntheorem tails_eq_inits : ∀ l : List α, l.tails = (reverse <| map reverse <| inits <| reverse l)\n | [] => by simp\n | a :: l => by simp [tails_eq_inits l, append_left_inj]\n#align list.tails_eq_inits List.tails_eq_inits\n\ntheorem inits_reverse (l : List α) : inits (reverse l) = reverse (map reverse l.tails) := by\n rw [tails_eq_inits l]\n simp [reverse_involutive.comp_self, reverse_map]\n#align list.inits_reverse List.inits_reverse\n\ntheorem tails_reverse (l : List α) : tails (reverse l) = reverse (map reverse l.inits) := by\n rw [inits_eq_tails l]\n simp [reverse_involutive.comp_self, reverse_map]\n#align list.tails_reverse List.tails_reverse\n\ntheorem map_reverse_inits (l : List α) : map reverse l.inits = (reverse <| tails <| reverse l) := by\n rw [inits_eq_tails l]\n simp [reverse_involutive.comp_self, reverse_map]\n#align list.map_reverse_inits List.map_reverse_inits\n\ntheorem map_reverse_tails (l : List α) : map reverse l.tails = (reverse <| inits <| reverse l) := by\n rw [tails_eq_inits l]\n simp [reverse_involutive.comp_self, reverse_map]\n#align list.map_reverse_tails List.map_reverse_tails\n\n@[simp]\ntheorem length_tails (l : List α) : length (tails l) = length l + 1 := by\n induction' l with x l IH\n · simp\n · simpa using IH\n#align list.length_tails List.length_tails\n\n@[simp]\ntheorem length_inits (l : List α) : length (inits l) = length l + 1 := by simp [inits_eq_tails]\n#align list.length_inits List.length_inits\n\nsection deprecated\nset_option linter.deprecated false -- TODO(Henrik): make replacements for theorems in this section\n\n@[simp]\ntheorem nth_le_tails (l : List α) (n : ℕ) (hn : n < length (tails l)) :\n nthLe (tails l) n hn = l.drop n := by\n induction' l with x l IH generalizing n\n · simp\n · cases n\n · simp[nthLe_cons]\n · simpa[nthLe_cons] using IH _ _\n#align list.nth_le_tails List.nth_le_tails\n\n@[simp]\ntheorem nth_le_inits (l : List α) (n : ℕ) (hn : n < length (inits l)) :\n nthLe (inits l) n hn = l.take n := by\n induction' l with x l IH generalizing n\n · simp\n · cases n\n · simp[nthLe_cons]\n · simpa[nthLe_cons] using IH _ _\n#align list.nth_le_inits List.nth_le_inits\nend deprecated\n\nend InitsTails\n\n/-! ### insert -/\n\n\nsection Insert\n\nvariable [DecidableEq α]\n\n@[simp]\ntheorem insert_nil (a : α) : insert a nil = [a] :=\n rfl\n#align list.insert_nil List.insert_nil\n\ntheorem insert.def (a : α) (l : List α) : insert a l = if a ∈ l then l else a :: l :=\n rfl\n#align list.insert.def List.insert.def\n\n#align list.insert_of_mem List.insert_of_mem\n#align list.insert_of_not_mem List.insert_of_not_mem\n#align list.mem_insert_iff List.mem_insert_iff\n\n@[simp]\ntheorem suffix_insert (a : α) (l : List α) : l <:+ l.insert a := by\n by_cases h : a ∈ l\n · simp only [insert_of_mem h, insert, suffix_refl]\n · simp only [insert_of_not_mem h, suffix_cons, insert]\n\n#align list.suffix_insert List.suffix_insert\n\ntheorem infix_insert (a : α) (l : List α) : l <:+: l.insert a :=\n (suffix_insert a l).isInfix\n#align list.infix_insert List.infix_insert\n\ntheorem sublist_insert (a : α) (l : List α) : l <+ l.insert a :=\n (suffix_insert a l).sublist\n#align list.sublist_insert List.sublist_insert\n\ntheorem subset_insert (a : α) (l : List α) : l ⊆ l.insert a :=\n (sublist_insert a l).subset\n#align list.subset_insert List.subset_insert\n\n#align list.mem_insert_self List.mem_insert_self\n#align list.mem_insert_of_mem List.mem_insert_of_mem\n#align list.eq_or_mem_of_mem_insert List.eq_or_mem_of_mem_insert\n#align list.length_insert_of_mem List.length_insert_of_mem\n#align list.length_insert_of_not_mem List.length_insert_of_not_mem\n\nend Insert\n\ntheorem mem_of_mem_suffix (hx : a ∈ l₁) (hl : l₁ <:+ l₂) : a ∈ l₂ :=\n hl.subset hx\n#align list.mem_of_mem_suffix List.mem_of_mem_suffix\n\nend List\n", "meta": {"author": "leanprover-community", "repo": "mathlib4", "sha": "b9a0a30342ca06e9817e22dbe46e75fc7f435500", "save_path": "github-repos/lean/leanprover-community-mathlib4", "path": "github-repos/lean/leanprover-community-mathlib4/mathlib4-b9a0a30342ca06e9817e22dbe46e75fc7f435500/Mathlib/Data/List/Infix.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4416730056646256, "lm_q2_score": 0.0913820968808491, "lm_q1q2_score": 0.04036100539330063}} {"text": "/-\nCopyright (c) 2020 Scott Morrison. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Scott Morrison\n-/\nimport algebra.category.Group.basic\nimport category_theory.limits.shapes.zero_morphisms\n\n/-!\n# The category of (commutative) (additive) groups has a zero object.\n\n`AddCommGroup` also has zero morphisms. For definitional reasons, we infer this from preadditivity\nrather than from the existence of a zero object.\n-/\n\nopen category_theory\nopen category_theory.limits\n\nuniverse u\n\nnamespace Group\n\n@[to_additive] lemma is_zero_of_subsingleton (G : Group) [subsingleton G] :\n is_zero G :=\nbegin\n refine ⟨λ X, ⟨⟨⟨1⟩, λ f, _⟩⟩, λ X, ⟨⟨⟨1⟩, λ f, _⟩⟩⟩,\n { ext, have : x = 1 := subsingleton.elim _ _, rw [this, map_one, map_one], },\n { ext, apply subsingleton.elim }\nend\n\n@[to_additive AddGroup.has_zero_object]\ninstance : has_zero_object Group :=\n⟨⟨of punit, is_zero_of_subsingleton _⟩⟩\n\nend Group\n\nnamespace CommGroup\n\n@[to_additive] lemma is_zero_of_subsingleton (G : CommGroup) [subsingleton G] :\n is_zero G :=\nbegin\n refine ⟨λ X, ⟨⟨⟨1⟩, λ f, _⟩⟩, λ X, ⟨⟨⟨1⟩, λ f, _⟩⟩⟩,\n { ext, have : x = 1 := subsingleton.elim _ _, rw [this, map_one, map_one], },\n { ext, apply subsingleton.elim }\nend\n\n@[to_additive AddCommGroup.has_zero_object]\ninstance : has_zero_object CommGroup :=\n⟨⟨of punit, is_zero_of_subsingleton _⟩⟩\n\nend CommGroup\n", "meta": {"author": "nick-kuhn", "repo": "leantools", "sha": "567a98c031fffe3f270b7b8dea48389bc70d7abb", "save_path": "github-repos/lean/nick-kuhn-leantools", "path": "github-repos/lean/nick-kuhn-leantools/leantools-567a98c031fffe3f270b7b8dea48389bc70d7abb/src/algebra/category/Group/zero.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.08151976211114502, "lm_q1q2_score": 0.04012305973788721}} {"text": "example : (fun x y => (0 + x) + (0 + y)) = Nat.add := by\n conv =>\n lhs\n intro x y\n repeat rw [Nat.zero_add]\n", "meta": {"author": "leanprover", "repo": "lean4", "sha": "742d053a97bdd109a41a921facd1cd6a55e89bc7", "save_path": "github-repos/lean/leanprover-lean4", "path": "github-repos/lean/leanprover-lean4/lean4-742d053a97bdd109a41a921facd1cd6a55e89bc7/tests/lean/run/repeatConv.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4571367168274948, "lm_q2_score": 0.0875638323797629, "lm_q1q2_score": 0.04002864284691789}} {"text": "/-\nCopyright (c) 2014 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Leonardo de Moura\n\nnotation, basic datatypes and type classes\n-/\nprelude\nimport Fixtures.Termination.Init.Prelude\nimport Fixtures.Termination.Init.SizeOf\nset_option linter.all false -- prevent error messages from runFrontend\n\nuniverse u v w\n\n/--\n`inline (f x)` is an indication to the compiler to inline the definition of `f`\nat the application site itself (by comparison to the `@[inline]` attribute,\nwhich applies to all applications of the function).\n-/\ndef inline {α : Sort u} (a : α) : α := a\n\n/--\n`flip f a b` is `f b a`. It is useful for \"point-free\" programming,\nsince it can sometimes be used to avoid introducing variables.\nFor example, `(·<·)` is the less-than relation,\nand `flip (·<·)` is the greater-than relation.\n-/\n@[inline] def flip {α : Sort u} {β : Sort v} {φ : Sort w} (f : α → β → φ) : β → α → φ :=\n fun b a => f a b\n\n@[simp] theorem Function.const_apply {y : β} {x : α} : const α y x = y := rfl\n\n@[simp] theorem Function.comp_apply {f : β → δ} {g : α → β} {x : α} : comp f g x = f (g x) := rfl\n\nattribute [simp] namedPattern\n\n/--\n Thunks are \"lazy\" values that are evaluated when first accessed using `Thunk.get/map/bind`.\n The value is then stored and not recomputed for all further accesses. -/\n-- NOTE: the runtime has special support for the `Thunk` type to implement this behavior\nstructure Thunk (α : Type u) : Type u where\n /-- Constructs a new thunk from a function `Unit → α`\n that will be called when the thunk is forced. -/\n mk ::\n /-- Extract the getter function out of a thunk. Use `Thunk.get` instead. -/\n private fn : Unit → α\n\nattribute [extern \"lean_mk_thunk\"] Thunk.mk\n\n/-- Store a value in a thunk. Note that the value has already been computed, so there is no laziness. -/\n@[extern \"lean_thunk_pure\"] protected def Thunk.pure (a : α) : Thunk α :=\n ⟨fun _ => a⟩\n\n/--\nForces a thunk to extract the value. This will cache the result,\nso a second call to the same function will return the value in O(1)\ninstead of calling the stored getter function.\n-/\n-- NOTE: we use `Thunk.get` instead of `Thunk.fn` as the accessor primitive as the latter has an additional `Unit` argument\n@[extern \"lean_thunk_get_own\"] protected def Thunk.get (x : @& Thunk α) : α :=\n x.fn ()\n\n/-- Map a function over a thunk. -/\n@[inline] protected def Thunk.map (f : α → β) (x : Thunk α) : Thunk β :=\n ⟨fun _ => f x.get⟩\n/-- Constructs a thunk that applies `f` to the result of `x` when forced. -/\n@[inline] protected def Thunk.bind (x : Thunk α) (f : α → Thunk β) : Thunk β :=\n ⟨fun _ => (f x.get).get⟩\n\n@[simp] theorem Thunk.sizeOf_eq [SizeOf α] (a : Thunk α) : sizeOf a = 1 + sizeOf a.get := by\n cases a; rfl\n\ninstance thunkCoe : CoeTail α (Thunk α) where\n -- Since coercions are expanded eagerly, `a` is evaluated lazily.\n coe a := ⟨fun _ => a⟩\n\n/-- A variation on `Eq.ndrec` with the equality argument first. -/\nabbrev Eq.ndrecOn.{u1, u2} {α : Sort u2} {a : α} {motive : α → Sort u1} {b : α} (h : a = b) (m : motive a) : motive b :=\n Eq.ndrec m h\n\n/--\nIf and only if, or logical bi-implication. `a ↔ b` means that `a` implies `b` and vice versa.\nBy `propext`, this implies that `a` and `b` are equal and hence any expression involving `a`\nis equivalent to the corresponding expression with `b` instead.\n-/\nstructure Iff (a b : Prop) : Prop where\n /-- If `a → b` and `b → a` then `a` and `b` are equivalent. -/\n intro ::\n /-- Modus ponens for if and only if. If `a ↔ b` and `a`, then `b`. -/\n mp : a → b\n /-- Modus ponens for if and only if, reversed. If `a ↔ b` and `b`, then `a`. -/\n mpr : b → a\n\n@[inherit_doc] infix:20 \" <-> \" => Iff\n@[inherit_doc] infix:20 \" ↔ \" => Iff\n\n/--\n`Sum α β`, or `α ⊕ β`, is the disjoint union of types `α` and `β`.\nAn element of `α ⊕ β` is either of the form `.inl a` where `a : α`,\nor `.inr b` where `b : β`.\n-/\ninductive Sum (α : Type u) (β : Type v) where\n /-- Left injection into the sum type `α ⊕ β`. If `a : α` then `.inl a : α ⊕ β`. -/\n | inl (val : α) : Sum α β\n /-- Right injection into the sum type `α ⊕ β`. If `b : β` then `.inr b : α ⊕ β`. -/\n | inr (val : β) : Sum α β\n\n@[inherit_doc] infixr:30 \" ⊕ \" => Sum\n\n/--\n`PSum α β`, or `α ⊕' β`, is the disjoint union of types `α` and `β`.\nIt differs from `α ⊕ β` in that it allows `α` and `β` to have arbitrary sorts\n`Sort u` and `Sort v`, instead of restricting to `Type u` and `Type v`. This means\nthat it can be used in situations where one side is a proposition, like `True ⊕' Nat`.\n\nThe reason this is not the default is that this type lives in the universe `Sort (max 1 u v)`,\nwhich can cause problems for universe level unification,\nbecause the equation `max 1 u v = ?u + 1` has no solution in level arithmetic.\n`PSum` is usually only used in automation that constructs sums of arbitrary types.\n-/\ninductive PSum (α : Sort u) (β : Sort v) where\n /-- Left injection into the sum type `α ⊕' β`. If `a : α` then `.inl a : α ⊕' β`. -/\n | inl (val : α) : PSum α β\n /-- Right injection into the sum type `α ⊕' β`. If `b : β` then `.inr b : α ⊕' β`. -/\n | inr (val : β) : PSum α β\n\n@[inherit_doc] infixr:30 \" ⊕' \" => PSum\n\n/--\n`Sigma β`, also denoted `Σ a : α, β a` or `(a : α) × β a`, is the type of dependent pairs\nwhose first component is `a : α` and whose second component is `b : β a`\n(so the type of the second component can depend on the value of the first component).\nIt is sometimes known as the dependent sum type, since it is the type level version\nof an indexed summation.\n-/\nstructure Sigma {α : Type u} (β : α → Type v) where\n /-- Constructor for a dependent pair. If `a : α` and `b : β a` then `⟨a, b⟩ : Sigma β`.\n (This will usually require a type ascription to determine `β`\n since it is not determined from `a` and `b` alone.) -/\n mk ::\n /-- The first component of a dependent pair. If `p : @Sigma α β` then `p.1 : α`. -/\n fst : α\n /-- The second component of a dependent pair. If `p : Sigma β` then `p.2 : β p.1`. -/\n snd : β fst\n\nattribute [unbox] Sigma\n\n/--\n`PSigma β`, also denoted `Σ' a : α, β a` or `(a : α) ×' β a`, is the type of dependent pairs\nwhose first component is `a : α` and whose second component is `b : β a`\n(so the type of the second component can depend on the value of the first component).\nIt differs from `Σ a : α, β a` in that it allows `α` and `β` to have arbitrary sorts\n`Sort u` and `Sort v`, instead of restricting to `Type u` and `Type v`. This means\nthat it can be used in situations where one side is a proposition, like `(p : Nat) ×' p = p`.\n\nThe reason this is not the default is that this type lives in the universe `Sort (max 1 u v)`,\nwhich can cause problems for universe level unification,\nbecause the equation `max 1 u v = ?u + 1` has no solution in level arithmetic.\n`PSigma` is usually only used in automation that constructs pairs of arbitrary types.\n-/\nstructure PSigma {α : Sort u} (β : α → Sort v) where\n /-- Constructor for a dependent pair. If `a : α` and `b : β a` then `⟨a, b⟩ : PSigma β`.\n (This will usually require a type ascription to determine `β`\n since it is not determined from `a` and `b` alone.) -/\n mk ::\n /-- The first component of a dependent pair. If `p : @Sigma α β` then `p.1 : α`. -/\n fst : α\n /-- The second component of a dependent pair. If `p : Sigma β` then `p.2 : β p.1`. -/\n snd : β fst\n\n/--\nExistential quantification. If `p : α → Prop` is a predicate, then `∃ x : α, p x`\nasserts that there is some `x` of type `α` such that `p x` holds.\nTo create an existential proof, use the `exists` tactic,\nor the anonymous constructor notation `⟨x, h⟩`.\nTo unpack an existential, use `cases h` where `h` is a proof of `∃ x : α, p x`,\nor `let ⟨x, hx⟩ := h` where `.\n\nBecause Lean has proof irrelevance, any two proofs of an existential are\ndefinitionally equal. One consequence of this is that it is impossible to recover the\nwitness of an existential from the mere fact of its existence.\nFor example, the following does not compile:\n```\nexample (h : ∃ x : Nat, x = x) : Nat :=\n let ⟨x, _⟩ := h -- fail, because the goal is `Nat : Type`\n x\n```\nThe error message `recursor 'Exists.casesOn' can only eliminate into Prop` means\nthat this only works when the current goal is another proposition:\n```\nexample (h : ∃ x : Nat, x = x) : True :=\n let ⟨x, _⟩ := h -- ok, because the goal is `True : Prop`\n trivial\n```\n-/\ninductive Exists {α : Sort u} (p : α → Prop) : Prop where\n /-- Existential introduction. If `a : α` and `h : p a`,\n then `⟨a, h⟩` is a proof that `∃ x : α, p x`. -/\n | intro (w : α) (h : p w) : Exists p\n\n/--\nAuxiliary type used to compile `for x in xs` notation.\n\nThis is the return value of the body of a `ForIn` call,\nrepresenting the body of a for loop. It can be:\n\n* `.yield (a : α)`, meaning that we should continue the loop and `a` is the new state.\n `.yield` is produced by `continue` and reaching the bottom of the loop body.\n* `.done (a : α)`, meaning that we should early-exit the loop with state `a`.\n `.done` is produced by calls to `break` or `return` in the loop,\n-/\ninductive ForInStep (α : Type u) where\n /-- `.done a` means that we should early-exit the loop.\n `.done` is produced by calls to `break` or `return` in the loop. -/\n | done : α → ForInStep α\n /-- `.yield a` means that we should continue the loop.\n `.yield` is produced by `continue` and reaching the bottom of the loop body. -/\n | yield : α → ForInStep α\n deriving Inhabited\n\n/--\n`ForIn m ρ α` is the typeclass which supports `for x in xs` notation.\nHere `xs : ρ` is the type of the collection to iterate over, `x : α`\nis the element type which is made available inside the loop, and `m` is the monad\nfor the encompassing `do` block.\n-/\nclass ForIn (m : Type u₁ → Type u₂) (ρ : Type u) (α : outParam (Type v)) where\n /-- `forIn x b f : m β` runs a for-loop in the monad `m` with additional state `β`.\n This traverses over the \"contents\" of `x`, and passes the elements `a : α` to\n `f : α → β → m (ForInStep β)`. `b : β` is the initial state, and the return value\n of `f` is the new state as well as a directive `.done` or `.yield`\n which indicates whether to abort early or continue iteration.\n\n The expression\n ```\n let mut b := ...\n for x in xs do\n b ← foo x b\n ```\n in a `do` block is syntactic sugar for:\n ```\n let b := ...\n let b ← forIn xs b (fun x b => do\n let b ← foo x b\n return .yield b)\n ```\n (Here `b` corresponds to the variables mutated in the loop.) -/\n forIn {β} [Monad m] (x : ρ) (b : β) (f : α → β → m (ForInStep β)) : m β\n\nexport ForIn (forIn)\n\n/--\n`ForIn' m ρ α d` is a variation on the `ForIn m ρ α` typeclass which supports the\n`for h : x in xs` notation. It is the same as `for x in xs` except that `h : x ∈ xs`\nis provided as an additional argument to the body of the for-loop.\n-/\nclass ForIn' (m : Type u₁ → Type u₂) (ρ : Type u) (α : outParam (Type v)) (d : outParam $ Membership α ρ) where\n /-- `forIn' x b f : m β` runs a for-loop in the monad `m` with additional state `β`.\n This traverses over the \"contents\" of `x`, and passes the elements `a : α` along\n with a proof that `a ∈ x` to `f : (a : α) → a ∈ x → β → m (ForInStep β)`.\n `b : β` is the initial state, and the return value\n of `f` is the new state as well as a directive `.done` or `.yield`\n which indicates whether to abort early or continue iteration. -/\n forIn' {β} [Monad m] (x : ρ) (b : β) (f : (a : α) → a ∈ x → β → m (ForInStep β)) : m β\n\nexport ForIn' (forIn')\n\n\n/--\nAuxiliary type used to compile `do` notation. It is used when compiling a do block\nnested inside a combinator like `tryCatch`. It encodes the possible ways the\nblock can exit:\n* `pure (a : α) s` means that the block exited normally with return value `a`.\n* `return (b : β) s` means that the block exited via a `return b` early-exit command.\n* `break s` means that `break` was called, meaning that we should exit\n from the containing loop.\n* `continue s` means that `continue` was called, meaning that we should continue\n to the next iteration of the containing loop.\n\nAll cases return a value `s : σ` which bundles all the mutable variables of the do-block.\n-/\ninductive DoResultPRBC (α β σ : Type u) where\n /-- `pure (a : α) s` means that the block exited normally with return value `a` -/\n | pure : α → σ → DoResultPRBC α β σ\n /-- `return (b : β) s` means that the block exited via a `return b` early-exit command -/\n | return : β → σ → DoResultPRBC α β σ\n /-- `break s` means that `break` was called, meaning that we should exit\n from the containing loop -/\n | break : σ → DoResultPRBC α β σ\n /-- `continue s` means that `continue` was called, meaning that we should continue\n to the next iteration of the containing loop -/\n | continue : σ → DoResultPRBC α β σ\n\n/--\nAuxiliary type used to compile `do` notation. It is the same as\n`DoResultPRBC α β σ` except that `break` and `continue` are not available\nbecause we are not in a loop context.\n-/\ninductive DoResultPR (α β σ : Type u) where\n /-- `pure (a : α) s` means that the block exited normally with return value `a` -/\n | pure : α → σ → DoResultPR α β σ\n /-- `return (b : β) s` means that the block exited via a `return b` early-exit command -/\n | return : β → σ → DoResultPR α β σ\n\n/--\nAuxiliary type used to compile `do` notation. It is an optimization of\n`DoResultPRBC PEmpty PEmpty σ` to remove the impossible cases,\nused when neither `pure` nor `return` are possible exit paths.\n-/\ninductive DoResultBC (σ : Type u) where\n /-- `break s` means that `break` was called, meaning that we should exit\n from the containing loop -/\n | break : σ → DoResultBC σ\n /-- `continue s` means that `continue` was called, meaning that we should continue\n to the next iteration of the containing loop -/\n | continue : σ → DoResultBC σ\n\n/--\nAuxiliary type used to compile `do` notation. It is an optimization of\neither `DoResultPRBC α PEmpty σ` or `DoResultPRBC PEmpty α σ` to remove the\nimpossible case, used when either `pure` or `return` is never used.\n-/\ninductive DoResultSBC (α σ : Type u) where\n /-- This encodes either `pure (a : α)` or `return (a : α)`:\n * `pure (a : α) s` means that the block exited normally with return value `a`\n * `return (b : β) s` means that the block exited via a `return b` early-exit command\n\n The one that is actually encoded depends on the context of use. -/\n | pureReturn : α → σ → DoResultSBC α σ\n /-- `break s` means that `break` was called, meaning that we should exit\n from the containing loop -/\n | break : σ → DoResultSBC α σ\n /-- `continue s` means that `continue` was called, meaning that we should continue\n to the next iteration of the containing loop -/\n | continue : σ → DoResultSBC α σ\n\n/-- `HasEquiv α` is the typeclass which supports the notation `x ≈ y` where `x y : α`.-/\nclass HasEquiv (α : Sort u) where\n /-- `x ≈ y` says that `x` and `y` are equivalent. Because this is a typeclass,\n the notion of equivalence is type-dependent. -/\n Equiv : α → α → Sort v\n\n@[inherit_doc] infix:50 \" ≈ \" => HasEquiv.Equiv\n\n/-- `EmptyCollection α` is the typeclass which supports the notation `∅`, also written as `{}`. -/\nclass EmptyCollection (α : Type u) where\n /-- `∅` or `{}` is the empty set or empty collection.\n It is supported by the `EmptyCollection` typeclass. -/\n emptyCollection : α\n\n@[inherit_doc] notation \"{\" \"}\" => EmptyCollection.emptyCollection\n@[inherit_doc] notation \"∅\" => EmptyCollection.emptyCollection\n\n/--\n`Task α` is a primitive for asynchronous computation.\nIt represents a computation that will resolve to a value of type `α`,\npossibly being computed on another thread. This is similar to `Future` in Scala,\n`Promise` in Javascript, and `JoinHandle` in Rust.\n\nThe tasks have an overridden representation in the runtime.\n-/\nstructure Task (α : Type u) : Type u where\n /-- `Task.pure (a : α)` constructs a task that is already resolved with value `a`. -/\n pure ::\n /-- If `task : Task α` then `task.get : α` blocks the current thread until the\n value is available, and then returns the result of the task. -/\n get : α\n deriving Inhabited, Nonempty\n\nattribute [extern \"lean_task_pure\"] Task.pure\nattribute [extern \"lean_task_get_own\"] Task.get\n\nnamespace Task\n/-- Task priority. Tasks with higher priority will always be scheduled before ones with lower priority. -/\nabbrev Priority := Nat\n\n/-- The default priority for spawned tasks, also the lowest priority: `0`. -/\ndef Priority.default : Priority := 0\n/--\nThe highest regular priority for spawned tasks: `8`.\n\nSpawning a task with a priority higher than `Task.Priority.max` is not an error but\nwill spawn a dedicated worker for the task, see `Task.Priority.dedicated`.\nRegular priority tasks are placed in a thread pool and worked on according to the priority order.\n-/\n-- see `LEAN_MAX_PRIO`\ndef Priority.max : Priority := 8\n/--\nAny priority higher than `Task.Priority.max` will result in the task being scheduled\nimmediately on a dedicated thread. This is particularly useful for long-running and/or\nI/O-bound tasks since Lean will by default allocate no more non-dedicated workers\nthan the number of cores to reduce context switches.\n-/\ndef Priority.dedicated : Priority := 9\n\nset_option linter.unusedVariables.funArgs false in\n/--\n`spawn fn : Task α` constructs and immediately launches a new task for\nevaluating the function `fn () : α` asynchronously.\n\n`prio`, if provided, is the priority of the task.\n-/\n@[noinline, extern \"lean_task_spawn\"]\nprotected def spawn {α : Type u} (fn : Unit → α) (prio := Priority.default) : Task α :=\n ⟨fn ()⟩\n\nset_option linter.unusedVariables.funArgs false in\n/--\n`map f x` maps function `f` over the task `x`: that is, it constructs\n(and immediately launches) a new task which will wait for the value of `x` to\nbe available and then calls `f` on the result.\n\n`prio`, if provided, is the priority of the task.\n-/\n@[noinline, extern \"lean_task_map\"]\nprotected def map {α : Type u} {β : Type v} (f : α → β) (x : Task α) (prio := Priority.default) : Task β :=\n ⟨f x.get⟩\n\nset_option linter.unusedVariables.funArgs false in\n/--\n`bind x f` does a monad \"bind\" operation on the task `x` with function `f`:\nthat is, it constructs (and immediately launches) a new task which will wait\nfor the value of `x` to be available and then calls `f` on the result,\nresulting in a new task which is then run for a result.\n\n`prio`, if provided, is the priority of the task.\n-/\n@[noinline, extern \"lean_task_bind\"]\nprotected def bind {α : Type u} {β : Type v} (x : Task α) (f : α → Task β) (prio := Priority.default) : Task β :=\n ⟨(f x.get).get⟩\n\nend Task\n\n/--\n`NonScalar` is a type that is not a scalar value in our runtime.\nIt is used as a stand-in for an arbitrary boxed value to avoid excessive\nmonomorphization, and it is only created using `unsafeCast`. It is somewhat\nanalogous to C `void*` in usage, but the type itself is not special.\n-/\nstructure NonScalar where\n /-- You should not use this function -/ mk ::\n /-- You should not use this function -/ val : Nat\n\n/--\n`PNonScalar` is a type that is not a scalar value in our runtime.\nIt is used as a stand-in for an arbitrary boxed value to avoid excessive\nmonomorphization, and it is only created using `unsafeCast`. It is somewhat\nanalogous to C `void*` in usage, but the type itself is not special.\n\nThis is the universe-polymorphic version of `PNonScalar`; it is preferred to use\n`NonScalar` instead where applicable.\n-/\ninductive PNonScalar : Type u where\n /-- You should not use this function -/\n | mk (v : Nat) : PNonScalar\n\n@[simp] protected theorem Nat.add_zero (n : Nat) : n + 0 = n := rfl\n\ntheorem optParam_eq (α : Sort u) (default : α) : optParam α default = α := rfl\n\n/-! # Boolean operators -/\n\n/--\n`strictOr` is the same as `or`, but it does not use short-circuit evaluation semantics:\nboth sides are evaluated, even if the first value is `true`.\n-/\n@[extern c inline \"#1 || #2\"] def strictOr (b₁ b₂ : Bool) := b₁ || b₂\n\n/--\n`strictAnd` is the same as `and`, but it does not use short-circuit evaluation semantics:\nboth sides are evaluated, even if the first value is `false`.\n-/\n@[extern c inline \"#1 && #2\"] def strictAnd (b₁ b₂ : Bool) := b₁ && b₂\n\n/--\n`x != y` is boolean not-equal. It is the negation of `x == y` which is supplied by\nthe `BEq` typeclass.\n\nUnlike `x ≠ y` (which is notation for `Ne x y`), this is `Bool` valued instead of\n`Prop` valued. It is mainly intended for programming applications.\n-/\n@[inline] def bne {α : Type u} [BEq α] (a b : α) : Bool :=\n !(a == b)\n\n@[inherit_doc] infix:50 \" != \" => bne\n\n/--\n`LawfulBEq α` is a typeclass which asserts that the `BEq α` implementation\n(which supplies the `a == b` notation) coincides with logical equality `a = b`.\nIn other words, `a == b` implies `a = b`, and `a == a` is true.\n-/\nclass LawfulBEq (α : Type u) [BEq α] : Prop where\n /-- If `a == b` evaluates to `true`, then `a` and `b` are equal in the logic. -/\n eq_of_beq : {a b : α} → a == b → a = b\n /-- `==` is reflexive, that is, `(a == a) = true`. -/\n protected rfl : {a : α} → a == a\n\nexport LawfulBEq (eq_of_beq)\n\ninstance : LawfulBEq Bool where\n eq_of_beq {a b} h := by cases a <;> cases b <;> first | rfl | contradiction\n rfl {a} := by cases a <;> decide\n\ninstance [DecidableEq α] : LawfulBEq α where\n eq_of_beq := of_decide_eq_true\n rfl := of_decide_eq_self_eq_true _\n\ninstance : LawfulBEq Char := inferInstance\n\ninstance : LawfulBEq String := inferInstance\n\n/-! # Logical connectives and equality -/\n\n@[inherit_doc True.intro] def trivial : True := ⟨⟩\n\ntheorem mt {a b : Prop} (h₁ : a → b) (h₂ : ¬b) : ¬a :=\n fun ha => h₂ (h₁ ha)\n\ntheorem not_false : ¬False := id\n\ntheorem not_not_intro {p : Prop} (h : p) : ¬ ¬ p :=\n fun hn : ¬ p => hn h\n\n-- proof irrelevance is built in\ntheorem proofIrrel {a : Prop} (h₁ h₂ : a) : h₁ = h₂ := rfl\n\ntheorem id.def {α : Sort u} (a : α) : id a = a := rfl\n\n/--\nIf `h : α = β` is a proof of type equality, then `h.mp : α → β` is the induced\n\"cast\" operation, mapping elements of `α` to elements of `β`.\n\nYou can prove theorems about the resulting element by induction on `h`, since\n`rfl.mp` is definitionally the identity function.\n-/\n@[macro_inline] def Eq.mp {α β : Sort u} (h : α = β) (a : α) : β :=\n h ▸ a\n\n/--\nIf `h : α = β` is a proof of type equality, then `h.mpr : β → α` is the induced\n\"cast\" operation in the reverse direction, mapping elements of `β` to elements of `α`.\n\nYou can prove theorems about the resulting element by induction on `h`, since\n`rfl.mpr` is definitionally the identity function.\n-/\n@[macro_inline] def Eq.mpr {α β : Sort u} (h : α = β) (b : β) : α :=\n h ▸ b\n\n@[elab_as_elim]\ntheorem Eq.substr {α : Sort u} {p : α → Prop} {a b : α} (h₁ : b = a) (h₂ : p a) : p b :=\n h₁ ▸ h₂\n\ntheorem cast_eq {α : Sort u} (h : α = α) (a : α) : cast h a = a :=\n rfl\n\n/--\n`a ≠ b`, or `Ne a b` is defined as `¬ (a = b)` or `a = b → False`,\nand asserts that `a` and `b` are not equal.\n-/\n@[reducible] def Ne {α : Sort u} (a b : α) :=\n ¬(a = b)\n\n@[inherit_doc] infix:50 \" ≠ \" => Ne\n\nsection Ne\nvariable {α : Sort u}\nvariable {a b : α} {p : Prop}\n\ntheorem Ne.intro (h : a = b → False) : a ≠ b := h\n\ntheorem Ne.elim (h : a ≠ b) : a = b → False := h\n\ntheorem Ne.irrefl (h : a ≠ a) : False := h rfl\n\ntheorem Ne.symm (h : a ≠ b) : b ≠ a :=\n fun h₁ => h (h₁.symm)\n\ntheorem false_of_ne : a ≠ a → False := Ne.irrefl\n\ntheorem ne_false_of_self : p → p ≠ False :=\n fun (hp : p) (h : p = False) => h ▸ hp\n\ntheorem ne_true_of_not : ¬p → p ≠ True :=\n fun (hnp : ¬p) (h : p = True) =>\n have : ¬True := h ▸ hnp\n this trivial\n\ntheorem true_ne_false : ¬True = False :=\n ne_false_of_self trivial\n\nend Ne\n\ntheorem Bool.of_not_eq_true : {b : Bool} → ¬ (b = true) → b = false\n | true, h => absurd rfl h\n | false, _ => rfl\n\ntheorem Bool.of_not_eq_false : {b : Bool} → ¬ (b = false) → b = true\n | true, _ => rfl\n | false, h => absurd rfl h\n\ntheorem ne_of_beq_false [BEq α] [LawfulBEq α] {a b : α} (h : (a == b) = false) : a ≠ b := by\n intro h'; subst h'; have : true = false := Eq.trans LawfulBEq.rfl.symm h; contradiction\n\ntheorem beq_false_of_ne [BEq α] [LawfulBEq α] {a b : α} (h : a ≠ b) : (a == b) = false :=\n have : ¬ (a == b) = true := by\n intro h'; rw [eq_of_beq h'] at h; contradiction\n Bool.of_not_eq_true this\n\nsection\nvariable {α β φ : Sort u} {a a' : α} {b b' : β} {c : φ}\n\ntheorem HEq.ndrec.{u1, u2} {α : Sort u2} {a : α} {motive : {β : Sort u2} → β → Sort u1} (m : motive a) {β : Sort u2} {b : β} (h : HEq a b) : motive b :=\n h.rec m\n\ntheorem HEq.ndrecOn.{u1, u2} {α : Sort u2} {a : α} {motive : {β : Sort u2} → β → Sort u1} {β : Sort u2} {b : β} (h : HEq a b) (m : motive a) : motive b :=\n h.rec m\n\ntheorem HEq.elim {α : Sort u} {a : α} {p : α → Sort v} {b : α} (h₁ : HEq a b) (h₂ : p a) : p b :=\n eq_of_heq h₁ ▸ h₂\n\ntheorem HEq.subst {p : (T : Sort u) → T → Prop} (h₁ : HEq a b) (h₂ : p α a) : p β b :=\n HEq.ndrecOn h₁ h₂\n\ntheorem HEq.symm (h : HEq a b) : HEq b a :=\n h.rec (HEq.refl a)\n\ntheorem heq_of_eq (h : a = a') : HEq a a' :=\n Eq.subst h (HEq.refl a)\n\ntheorem HEq.trans (h₁ : HEq a b) (h₂ : HEq b c) : HEq a c :=\n HEq.subst h₂ h₁\n\ntheorem heq_of_heq_of_eq (h₁ : HEq a b) (h₂ : b = b') : HEq a b' :=\n HEq.trans h₁ (heq_of_eq h₂)\n\ntheorem heq_of_eq_of_heq (h₁ : a = a') (h₂ : HEq a' b) : HEq a b :=\n HEq.trans (heq_of_eq h₁) h₂\n\ntheorem type_eq_of_heq (h : HEq a b) : α = β :=\n h.rec (Eq.refl α)\n\nend\n\ntheorem eqRec_heq {α : Sort u} {φ : α → Sort v} {a a' : α} : (h : a = a') → (p : φ a) → HEq (Eq.recOn (motive := fun x _ => φ x) h p) p\n | rfl, p => HEq.refl p\n\ntheorem heq_of_eqRec_eq {α β : Sort u} {a : α} {b : β} (h₁ : α = β) (h₂ : Eq.rec (motive := fun α _ => α) a h₁ = b) : HEq a b := by\n subst h₁\n apply heq_of_eq\n exact h₂\n\ntheorem cast_heq {α β : Sort u} : (h : α = β) → (a : α) → HEq (cast h a) a\n | rfl, a => HEq.refl a\n\nvariable {a b c d : Prop}\n\ntheorem iff_iff_implies_and_implies (a b : Prop) : (a ↔ b) ↔ (a → b) ∧ (b → a) :=\n Iff.intro (fun h => And.intro h.mp h.mpr) (fun h => Iff.intro h.left h.right)\n\ntheorem Iff.refl (a : Prop) : a ↔ a :=\n Iff.intro (fun h => h) (fun h => h)\n\nprotected theorem Iff.rfl {a : Prop} : a ↔ a :=\n Iff.refl a\n\ntheorem Iff.trans (h₁ : a ↔ b) (h₂ : b ↔ c) : a ↔ c :=\n Iff.intro\n (fun ha => Iff.mp h₂ (Iff.mp h₁ ha))\n (fun hc => Iff.mpr h₁ (Iff.mpr h₂ hc))\n\ntheorem Iff.symm (h : a ↔ b) : b ↔ a :=\n Iff.intro (Iff.mpr h) (Iff.mp h)\n\ntheorem Iff.comm : (a ↔ b) ↔ (b ↔ a) :=\n Iff.intro Iff.symm Iff.symm\n\ntheorem Iff.of_eq (h : a = b) : a ↔ b :=\n h ▸ Iff.refl _\n\ntheorem And.comm : a ∧ b ↔ b ∧ a := by\n constructor <;> intro ⟨h₁, h₂⟩ <;> exact ⟨h₂, h₁⟩\n\n/-! # Exists -/\n\ntheorem Exists.elim {α : Sort u} {p : α → Prop} {b : Prop}\n (h₁ : Exists (fun x => p x)) (h₂ : ∀ (a : α), p a → b) : b :=\n match h₁ with\n | intro a h => h₂ a h\n\n/-! # Decidable -/\n\ntheorem decide_true_eq_true (h : Decidable True) : @decide True h = true :=\n match h with\n | isTrue _ => rfl\n | isFalse h => False.elim <| h ⟨⟩\n\ntheorem decide_false_eq_false (h : Decidable False) : @decide False h = false :=\n match h with\n | isFalse _ => rfl\n | isTrue h => False.elim h\n\n/-- Similar to `decide`, but uses an explicit instance -/\n@[inline] def toBoolUsing {p : Prop} (d : Decidable p) : Bool :=\n decide (h := d)\n\ntheorem toBoolUsing_eq_true {p : Prop} (d : Decidable p) (h : p) : toBoolUsing d = true :=\n decide_eq_true (inst := d) h\n\ntheorem ofBoolUsing_eq_true {p : Prop} {d : Decidable p} (h : toBoolUsing d = true) : p :=\n of_decide_eq_true (inst := d) h\n\ntheorem ofBoolUsing_eq_false {p : Prop} {d : Decidable p} (h : toBoolUsing d = false) : ¬ p :=\n of_decide_eq_false (inst := d) h\n\ninstance : Decidable True :=\n isTrue trivial\n\ninstance : Decidable False :=\n isFalse not_false\n\nnamespace Decidable\nvariable {p q : Prop}\n\n/--\nSynonym for `dite` (dependent if-then-else). We can construct an element `q`\n(of any sort, not just a proposition) by cases on whether `p` is true or false,\nprovided `p` is decidable.\n-/\n@[macro_inline] def byCases {q : Sort u} [dec : Decidable p] (h1 : p → q) (h2 : ¬p → q) : q :=\n match dec with\n | isTrue h => h1 h\n | isFalse h => h2 h\n\ntheorem em (p : Prop) [Decidable p] : p ∨ ¬p :=\n byCases Or.inl Or.inr\n\nset_option linter.unusedVariables.funArgs false in\ntheorem byContradiction [dec : Decidable p] (h : ¬p → False) : p :=\n byCases id (fun np => False.elim (h np))\n\ntheorem of_not_not [Decidable p] : ¬ ¬ p → p :=\n fun hnn => byContradiction (fun hn => absurd hn hnn)\n\ntheorem not_and_iff_or_not (p q : Prop) [d₁ : Decidable p] [d₂ : Decidable q] : ¬ (p ∧ q) ↔ ¬ p ∨ ¬ q :=\n Iff.intro\n (fun h => match d₁, d₂ with\n | isTrue h₁, isTrue h₂ => absurd (And.intro h₁ h₂) h\n | _, isFalse h₂ => Or.inr h₂\n | isFalse h₁, _ => Or.inl h₁)\n (fun (h) ⟨hp, hq⟩ => match h with\n | Or.inl h => h hp\n | Or.inr h => h hq)\n\nend Decidable\n\nsection\nvariable {p q : Prop}\n/-- Transfer a decidability proof across an equivalence of propositions. -/\n@[inline] def decidable_of_decidable_of_iff [Decidable p] (h : p ↔ q) : Decidable q :=\n if hp : p then\n isTrue (Iff.mp h hp)\n else\n isFalse fun hq => absurd (Iff.mpr h hq) hp\n\n/-- Transfer a decidability proof across an equality of propositions. -/\n@[inline] def decidable_of_decidable_of_eq [Decidable p] (h : p = q) : Decidable q :=\n decidable_of_decidable_of_iff (p := p) (h ▸ Iff.rfl)\nend\n\n@[macro_inline] instance {p q} [Decidable p] [Decidable q] : Decidable (p → q) :=\n if hp : p then\n if hq : q then isTrue (fun _ => hq)\n else isFalse (fun h => absurd (h hp) hq)\n else isTrue (fun h => absurd h hp)\n\ninstance {p q} [Decidable p] [Decidable q] : Decidable (p ↔ q) :=\n if hp : p then\n if hq : q then\n isTrue ⟨fun _ => hq, fun _ => hp⟩\n else\n isFalse fun h => hq (h.1 hp)\n else\n if hq : q then\n isFalse fun h => hp (h.2 hq)\n else\n isTrue ⟨fun h => absurd h hp, fun h => absurd h hq⟩\n\n/-! # if-then-else expression theorems -/\n\ntheorem if_pos {c : Prop} {h : Decidable c} (hc : c) {α : Sort u} {t e : α} : (ite c t e) = t :=\n match h with\n | isTrue _ => rfl\n | isFalse hnc => absurd hc hnc\n\ntheorem if_neg {c : Prop} {h : Decidable c} (hnc : ¬c) {α : Sort u} {t e : α} : (ite c t e) = e :=\n match h with\n | isTrue hc => absurd hc hnc\n | isFalse _ => rfl\n\ntheorem dif_pos {c : Prop} {h : Decidable c} (hc : c) {α : Sort u} {t : c → α} {e : ¬ c → α} : (dite c t e) = t hc :=\n match h with\n | isTrue _ => rfl\n | isFalse hnc => absurd hc hnc\n\ntheorem dif_neg {c : Prop} {h : Decidable c} (hnc : ¬c) {α : Sort u} {t : c → α} {e : ¬ c → α} : (dite c t e) = e hnc :=\n match h with\n | isTrue hc => absurd hc hnc\n | isFalse _ => rfl\n\n-- Remark: dite and ite are \"defally equal\" when we ignore the proofs.\ntheorem dif_eq_if (c : Prop) {h : Decidable c} {α : Sort u} (t : α) (e : α) : dite c (fun _ => t) (fun _ => e) = ite c t e :=\n match h with\n | isTrue _ => rfl\n | isFalse _ => rfl\n\ninstance {c t e : Prop} [dC : Decidable c] [dT : Decidable t] [dE : Decidable e] : Decidable (if c then t else e) :=\n match dC with\n | isTrue _ => dT\n | isFalse _ => dE\n\ninstance {c : Prop} {t : c → Prop} {e : ¬c → Prop} [dC : Decidable c] [dT : ∀ h, Decidable (t h)] [dE : ∀ h, Decidable (e h)] : Decidable (if h : c then t h else e h) :=\n match dC with\n | isTrue hc => dT hc\n | isFalse hc => dE hc\n\n/-- Auxiliary definition for generating compact `noConfusion` for enumeration types -/\nabbrev noConfusionTypeEnum {α : Sort u} {β : Sort v} [inst : DecidableEq β] (f : α → β) (P : Sort w) (x y : α) : Sort w :=\n (inst (f x) (f y)).casesOn\n (fun _ => P)\n (fun _ => P → P)\n\n/-- Auxiliary definition for generating compact `noConfusion` for enumeration types -/\nabbrev noConfusionEnum {α : Sort u} {β : Sort v} [inst : DecidableEq β] (f : α → β) {P : Sort w} {x y : α} (h : x = y) : noConfusionTypeEnum f P x y :=\n Decidable.casesOn\n (motive := fun (inst : Decidable (f x = f y)) => Decidable.casesOn (motive := fun _ => Sort w) inst (fun _ => P) (fun _ => P → P))\n (inst (f x) (f y))\n (fun h' => False.elim (h' (congrArg f h)))\n (fun _ => fun x => x)\n\n/-! # Inhabited -/\n\ninstance : Inhabited Prop where\n default := True\n\nderiving instance Inhabited for NonScalar, PNonScalar, True, ForInStep\n\ntheorem nonempty_of_exists {α : Sort u} {p : α → Prop} : Exists (fun x => p x) → Nonempty α\n | ⟨w, _⟩ => ⟨w⟩\n\n/-! # Subsingleton -/\n\n/--\nA \"subsingleton\" is a type with at most one element.\nIn other words, it is either empty, or has a unique element.\nAll propositions are subsingletons because of proof irrelevance, but some other types\nare subsingletons as well and they inherit many of the same properties as propositions.\n`Subsingleton α` is a typeclass, so it is usually used as an implicit argument and\ninferred by typeclass inference.\n-/\nclass Subsingleton (α : Sort u) : Prop where\n /-- Construct a proof that `α` is a subsingleton by showing that any two elements are equal. -/\n intro ::\n /-- Any two elements of a subsingleton are equal. -/\n allEq : (a b : α) → a = b\n\nprotected theorem Subsingleton.elim {α : Sort u} [h : Subsingleton α] : (a b : α) → a = b :=\n h.allEq\n\nprotected theorem Subsingleton.helim {α β : Sort u} [h₁ : Subsingleton α] (h₂ : α = β) (a : α) (b : β) : HEq a b := by\n subst h₂\n apply heq_of_eq\n apply Subsingleton.elim\n\ninstance (p : Prop) : Subsingleton p :=\n ⟨fun a b => proofIrrel a b⟩\n\ninstance (p : Prop) : Subsingleton (Decidable p) :=\n Subsingleton.intro fun\n | isTrue t₁ => fun\n | isTrue _ => rfl\n | isFalse f₂ => absurd t₁ f₂\n | isFalse f₁ => fun\n | isTrue t₂ => absurd t₂ f₁\n | isFalse _ => rfl\n\ntheorem recSubsingleton\n {p : Prop} [h : Decidable p]\n {h₁ : p → Sort u}\n {h₂ : ¬p → Sort u}\n [h₃ : ∀ (h : p), Subsingleton (h₁ h)]\n [h₄ : ∀ (h : ¬p), Subsingleton (h₂ h)]\n : Subsingleton (h.casesOn h₂ h₁) :=\n match h with\n | isTrue h => h₃ h\n | isFalse h => h₄ h\n\n/--\nAn equivalence relation `~ : α → α → Prop` is a relation that is:\n\n* reflexive: `x ~ x`\n* symmetric: `x ~ y` implies `y ~ x`\n* transitive: `x ~ y` and `y ~ z` implies `x ~ z`\n\nEquality is an equivalence relation, and equivalence relations share many of\nthe properties of equality. In particular, `Quot α r` is most well behaved\nwhen `r` is an equivalence relation, and in this case we use `Quotient` instead.\n-/\nstructure Equivalence {α : Sort u} (r : α → α → Prop) : Prop where\n /-- An equivalence relation is reflexive: `x ~ x` -/\n refl : ∀ x, r x x\n /-- An equivalence relation is symmetric: `x ~ y` implies `y ~ x` -/\n symm : ∀ {x y}, r x y → r y x\n /-- An equivalence relation is transitive: `x ~ y` and `y ~ z` implies `x ~ z` -/\n trans : ∀ {x y z}, r x y → r y z → r x z\n\n/-- The empty relation is the relation on `α` which is always `False`. -/\ndef emptyRelation {α : Sort u} (_ _ : α) : Prop :=\n False\n\n/--\n`Subrelation q r` means that `q ⊆ r` or `∀ x y, q x y → r x y`.\nIt is the analogue of the subset relation on relations.\n-/\ndef Subrelation {α : Sort u} (q r : α → α → Prop) :=\n ∀ {x y}, q x y → r x y\n\n/--\nThe inverse image of `r : β → β → Prop` by a function `α → β` is the relation\n`s : α → α → Prop` defined by `s a b = r (f a) (f b)`.\n-/\ndef InvImage {α : Sort u} {β : Sort v} (r : β → β → Prop) (f : α → β) : α → α → Prop :=\n fun a₁ a₂ => r (f a₁) (f a₂)\n\n/--\nThe transitive closure `r⁺` of a relation `r` is the smallest relation which is\ntransitive and contains `r`. `r⁺ a z` if and only if there exists a sequence\n`a r b r ... r z` of length at least 1 connecting `a` to `z`.\n-/\ninductive TC {α : Sort u} (r : α → α → Prop) : α → α → Prop where\n /-- If `r a b` then `r⁺ a b`. This is the base case of the transitive closure. -/\n | base : ∀ a b, r a b → TC r a b\n /-- The transitive closure is transitive. -/\n | trans : ∀ a b c, TC r a b → TC r b c → TC r a c\n\n/-! # Subtype -/\n\nnamespace Subtype\ntheorem existsOfSubtype {α : Type u} {p : α → Prop} : { x // p x } → Exists (fun x => p x)\n | ⟨a, h⟩ => ⟨a, h⟩\n\nvariable {α : Type u} {p : α → Prop}\n\nprotected theorem eq : ∀ {a1 a2 : {x // p x}}, val a1 = val a2 → a1 = a2\n | ⟨_, _⟩, ⟨_, _⟩, rfl => rfl\n\ntheorem eta (a : {x // p x}) (h : p (val a)) : mk (val a) h = a := by\n cases a\n exact rfl\n\ninstance {α : Type u} {p : α → Prop} {a : α} (h : p a) : Inhabited {x // p x} where\n default := ⟨a, h⟩\n\ninstance {α : Type u} {p : α → Prop} [DecidableEq α] : DecidableEq {x : α // p x} :=\n fun ⟨a, h₁⟩ ⟨b, h₂⟩ =>\n if h : a = b then isTrue (by subst h; exact rfl)\n else isFalse (fun h' => Subtype.noConfusion h' (fun h' => absurd h' h))\n\nend Subtype\n\n/-! # Sum -/\n\nsection\nvariable {α : Type u} {β : Type v}\n\ninstance Sum.inhabitedLeft [Inhabited α] : Inhabited (Sum α β) where\n default := Sum.inl default\n\ninstance Sum.inhabitedRight [Inhabited β] : Inhabited (Sum α β) where\n default := Sum.inr default\n\ninstance {α : Type u} {β : Type v} [DecidableEq α] [DecidableEq β] : DecidableEq (Sum α β) := fun a b =>\n match a, b with\n | Sum.inl a, Sum.inl b =>\n if h : a = b then isTrue (h ▸ rfl)\n else isFalse fun h' => Sum.noConfusion h' fun h' => absurd h' h\n | Sum.inr a, Sum.inr b =>\n if h : a = b then isTrue (h ▸ rfl)\n else isFalse fun h' => Sum.noConfusion h' fun h' => absurd h' h\n | Sum.inr _, Sum.inl _ => isFalse fun h => Sum.noConfusion h\n | Sum.inl _, Sum.inr _ => isFalse fun h => Sum.noConfusion h\n\nend\n\n/-! # Product -/\n\ninstance [Inhabited α] [Inhabited β] : Inhabited (α × β) where\n default := (default, default)\n\ninstance [Inhabited α] [Inhabited β] : Inhabited (MProd α β) where\n default := ⟨default, default⟩\n\ninstance [Inhabited α] [Inhabited β] : Inhabited (PProd α β) where\n default := ⟨default, default⟩\n\ninstance [DecidableEq α] [DecidableEq β] : DecidableEq (α × β) :=\n fun (a, b) (a', b') =>\n match decEq a a' with\n | isTrue e₁ =>\n match decEq b b' with\n | isTrue e₂ => isTrue (e₁ ▸ e₂ ▸ rfl)\n | isFalse n₂ => isFalse fun h => Prod.noConfusion h fun _ e₂' => absurd e₂' n₂\n | isFalse n₁ => isFalse fun h => Prod.noConfusion h fun e₁' _ => absurd e₁' n₁\n\ninstance [BEq α] [BEq β] : BEq (α × β) where\n beq := fun (a₁, b₁) (a₂, b₂) => a₁ == a₂ && b₁ == b₂\n\n/-- Lexicographical order for products -/\ndef Prod.lexLt [LT α] [LT β] (s : α × β) (t : α × β) : Prop :=\n s.1 < t.1 ∨ (s.1 = t.1 ∧ s.2 < t.2)\n\ninstance Prod.lexLtDec\n [LT α] [LT β] [DecidableEq α] [DecidableEq β]\n [(a b : α) → Decidable (a < b)] [(a b : β) → Decidable (a < b)]\n : (s t : α × β) → Decidable (Prod.lexLt s t) :=\n fun _ _ => inferInstanceAs (Decidable (_ ∨ _))\n\ntheorem Prod.lexLt_def [LT α] [LT β] (s t : α × β) : (Prod.lexLt s t) = (s.1 < t.1 ∨ (s.1 = t.1 ∧ s.2 < t.2)) :=\n rfl\n\ntheorem Prod.eta (p : α × β) : (p.1, p.2) = p := rfl\n\n/--\n`Prod.map f g : α₁ × β₁ → α₂ × β₂` maps across a pair\nby applying `f` to the first component and `g` to the second.\n-/\ndef Prod.map {α₁ : Type u₁} {α₂ : Type u₂} {β₁ : Type v₁} {β₂ : Type v₂}\n (f : α₁ → α₂) (g : β₁ → β₂) : α₁ × β₁ → α₂ × β₂\n | (a, b) => (f a, g b)\n\n/-! # Dependent products -/\n\ntheorem ex_of_PSigma {α : Type u} {p : α → Prop} : (PSigma (fun x => p x)) → Exists (fun x => p x)\n | ⟨x, hx⟩ => ⟨x, hx⟩\n\nprotected theorem PSigma.eta {α : Sort u} {β : α → Sort v} {a₁ a₂ : α} {b₁ : β a₁} {b₂ : β a₂}\n (h₁ : a₁ = a₂) (h₂ : Eq.ndrec b₁ h₁ = b₂) : PSigma.mk a₁ b₁ = PSigma.mk a₂ b₂ := by\n subst h₁\n subst h₂\n exact rfl\n\n/-! # Universe polymorphic unit -/\n\ntheorem PUnit.subsingleton (a b : PUnit) : a = b := by\n cases a; cases b; exact rfl\n\ntheorem PUnit.eq_punit (a : PUnit) : a = ⟨⟩ :=\n PUnit.subsingleton a ⟨⟩\n\ninstance : Subsingleton PUnit :=\n Subsingleton.intro PUnit.subsingleton\n\ninstance : Inhabited PUnit where\n default := ⟨⟩\n\ninstance : DecidableEq PUnit :=\n fun a b => isTrue (PUnit.subsingleton a b)\n\n/-! # Setoid -/\n\n/--\nA setoid is a type with a distinguished equivalence relation, denoted `≈`.\nThis is mainly used as input to the `Quotient` type constructor.\n-/\nclass Setoid (α : Sort u) where\n /-- `x ≈ y` is the distinguished equivalence relation of a setoid. -/\n r : α → α → Prop\n /-- The relation `x ≈ y` is an equivalence relation. -/\n iseqv : Equivalence r\n\ninstance {α : Sort u} [Setoid α] : HasEquiv α :=\n ⟨Setoid.r⟩\n\nnamespace Setoid\n\nvariable {α : Sort u} [Setoid α]\n\ntheorem refl (a : α) : a ≈ a :=\n iseqv.refl a\n\ntheorem symm {a b : α} (hab : a ≈ b) : b ≈ a :=\n iseqv.symm hab\n\ntheorem trans {a b c : α} (hab : a ≈ b) (hbc : b ≈ c) : a ≈ c :=\n iseqv.trans hab hbc\n\nend Setoid\n\n\n/-! # Propositional extensionality -/\n\n/--\nThe axiom of **propositional extensionality**. It asserts that if propositions\n`a` and `b` are logically equivalent (i.e. we can prove `a` from `b` and vice versa),\nthen `a` and `b` are *equal*, meaning that we can replace `a` with `b` in all\ncontexts.\n\nFor simple expressions like `a ∧ c ∨ d → e` we can prove that because all the logical\nconnectives respect logical equivalence, we can replace `a` with `b` in this expression\nwithout using `propext`. However, for higher order expressions like `P a` where\n`P : Prop → Prop` is unknown, or indeed for `a = b` itself, we cannot replace `a` with `b`\nwithout an axiom which says exactly this.\n\nThis is a relatively uncontroversial axiom, which is intuitionistically valid.\nIt does however block computation when using `#reduce` to reduce proofs directly\n(which is not recommended), meaning that canonicity,\nthe property that all closed terms of type `Nat` normalize to numerals,\nfails to hold when this (or any) axiom is used:\n```\nset_option pp.proofs true\n\ndef foo : Nat := by\n have : (True → True) ↔ True := ⟨λ _ => trivial, λ _ _ => trivial⟩\n have := propext this ▸ (2 : Nat)\n exact this\n\n#reduce foo\n-- propext { mp := fun x x => True.intro, mpr := fun x => True.intro } ▸ 2\n\n#eval foo -- 2\n```\n`#eval` can evaluate it to a numeral because the compiler erases casts and\ndoes not evaluate proofs, so `propext`, whose return type is a proposition,\ncan never block it.\n-/\naxiom propext {a b : Prop} : (a ↔ b) → a = b\n\ntheorem Eq.propIntro {a b : Prop} (h₁ : a → b) (h₂ : b → a) : a = b :=\n propext <| Iff.intro h₁ h₂\n\n-- Eq for Prop is now decidable if the equivalent Iff is decidable\ninstance {p q : Prop} [d : Decidable (p ↔ q)] : Decidable (p = q) :=\n match d with\n | isTrue h => isTrue (propext h)\n | isFalse h => isFalse fun heq => h (heq ▸ Iff.rfl)\n\ngen_injective_theorems% Prod\ngen_injective_theorems% PProd\ngen_injective_theorems% MProd\ngen_injective_theorems% Subtype\ngen_injective_theorems% Fin\ngen_injective_theorems% Array\ngen_injective_theorems% Sum\ngen_injective_theorems% PSum\ngen_injective_theorems% Nat\ngen_injective_theorems% Option\ngen_injective_theorems% List\ngen_injective_theorems% Except\ngen_injective_theorems% EStateM.Result\ngen_injective_theorems% Lean.Name\ngen_injective_theorems% Lean.Syntax\n\n@[simp] theorem beq_iff_eq [BEq α] [LawfulBEq α] (a b : α) : a == b ↔ a = b :=\n ⟨eq_of_beq, by intro h; subst h; exact LawfulBEq.rfl⟩\n\n/-! # Quotients -/\n\n/-- Iff can now be used to do substitutions in a calculation -/\ntheorem Iff.subst {a b : Prop} {p : Prop → Prop} (h₁ : a ↔ b) (h₂ : p a) : p b :=\n Eq.subst (propext h₁) h₂\n\nnamespace Quot\n/--\nThe **quotient axiom**, or at least the nontrivial part of the quotient\naxiomatization. Quotient types are introduced by the `init_quot` command\nin `Init.Prelude` which introduces the axioms:\n\n```\nopaque Quot {α : Sort u} (r : α → α → Prop) : Sort u\n\nopaque Quot.mk {α : Sort u} (r : α → α → Prop) (a : α) : Quot r\n\nopaque Quot.lift {α : Sort u} {r : α → α → Prop} {β : Sort v} (f : α → β) :\n (∀ a b : α, r a b → f a = f b) → Quot r → β\n\nopaque Quot.ind {α : Sort u} {r : α → α → Prop} {β : Quot r → Prop} :\n (∀ a : α, β (Quot.mk r a)) → ∀ q : Quot r, β q\n```\nAll of these axioms are true if we assume `Quot α r = α` and `Quot.mk` and\n`Quot.lift` are identity functions, so they do not add much. However this axiom\ncannot be explained in that way (it is false for that interpretation), so the\nreal power of quotient types come from this axiom.\n\nIt says that the quotient by `r` maps elements which are related by `r` to equal\nvalues in the quotient. Together with `Quot.lift` which says that functions\nwhich respect `r` can be lifted to functions on the quotient, we can deduce that\n`Quot α r` exactly consists of the equivalence classes with respect to `r`.\n\nIt is important to note that `r` need not be an equivalence relation in this axiom.\nWhen `r` is not an equivalence relation, we are actually taking a quotient with\nrespect to the equivalence relation generated by `r`.\n-/\naxiom sound : ∀ {α : Sort u} {r : α → α → Prop} {a b : α}, r a b → Quot.mk r a = Quot.mk r b\n\nprotected theorem liftBeta {α : Sort u} {r : α → α → Prop} {β : Sort v}\n (f : α → β)\n (c : (a b : α) → r a b → f a = f b)\n (a : α)\n : lift f c (Quot.mk r a) = f a :=\n rfl\n\nprotected theorem indBeta {α : Sort u} {r : α → α → Prop} {motive : Quot r → Prop}\n (p : (a : α) → motive (Quot.mk r a))\n (a : α)\n : (ind p (Quot.mk r a) : motive (Quot.mk r a)) = p a :=\n rfl\n\n/--\n`Quot.liftOn q f h` is the same as `Quot.lift f h q`. It just reorders\nthe argument `q : Quot r` to be first.\n-/\nprotected abbrev liftOn {α : Sort u} {β : Sort v} {r : α → α → Prop}\n (q : Quot r) (f : α → β) (c : (a b : α) → r a b → f a = f b) : β :=\n lift f c q\n\n@[elab_as_elim]\nprotected theorem inductionOn {α : Sort u} {r : α → α → Prop} {motive : Quot r → Prop}\n (q : Quot r)\n (h : (a : α) → motive (Quot.mk r a))\n : motive q :=\n ind h q\n\ntheorem exists_rep {α : Sort u} {r : α → α → Prop} (q : Quot r) : Exists (fun a => (Quot.mk r a) = q) :=\n q.inductionOn (fun a => ⟨a, rfl⟩)\n\nsection\nvariable {α : Sort u}\nvariable {r : α → α → Prop}\nvariable {motive : Quot r → Sort v}\n\n/-- Auxiliary definition for `Quot.rec`. -/\n@[reducible, macro_inline]\nprotected def indep (f : (a : α) → motive (Quot.mk r a)) (a : α) : PSigma motive :=\n ⟨Quot.mk r a, f a⟩\n\nprotected theorem indepCoherent\n (f : (a : α) → motive (Quot.mk r a))\n (h : (a b : α) → (p : r a b) → Eq.ndrec (f a) (sound p) = f b)\n : (a b : α) → r a b → Quot.indep f a = Quot.indep f b :=\n fun a b e => PSigma.eta (sound e) (h a b e)\n\nprotected theorem liftIndepPr1\n (f : (a : α) → motive (Quot.mk r a))\n (h : ∀ (a b : α) (p : r a b), Eq.ndrec (f a) (sound p) = f b)\n (q : Quot r)\n : (lift (Quot.indep f) (Quot.indepCoherent f h) q).1 = q := by\n induction q using Quot.ind\n exact rfl\n\n/--\nDependent recursion principle for `Quot`. This constructor can be tricky to use,\nso you should consider the simpler versions if they apply:\n* `Quot.lift`, for nondependent functions\n* `Quot.ind`, for theorems / proofs of propositions about quotients\n* `Quot.recOnSubsingleton`, when the target type is a `Subsingleton`\n* `Quot.hrecOn`, which uses `HEq (f a) (f b)` instead of a `sound p ▸ f a = f b` assummption\n-/\nprotected abbrev rec\n (f : (a : α) → motive (Quot.mk r a))\n (h : (a b : α) → (p : r a b) → Eq.ndrec (f a) (sound p) = f b)\n (q : Quot r) : motive q :=\n Eq.ndrecOn (Quot.liftIndepPr1 f h q) ((lift (Quot.indep f) (Quot.indepCoherent f h) q).2)\n\n@[inherit_doc Quot.rec] protected abbrev recOn\n (q : Quot r)\n (f : (a : α) → motive (Quot.mk r a))\n (h : (a b : α) → (p : r a b) → Eq.ndrec (f a) (sound p) = f b)\n : motive q :=\n q.rec f h\n\n/--\nDependent induction principle for a quotient, when the target type is a `Subsingleton`.\nIn this case the quotient's side condition is trivial so any function can be lifted.\n-/\nprotected abbrev recOnSubsingleton\n [h : (a : α) → Subsingleton (motive (Quot.mk r a))]\n (q : Quot r)\n (f : (a : α) → motive (Quot.mk r a))\n : motive q := by\n induction q using Quot.rec\n apply f\n apply Subsingleton.elim\n\n/--\nHeterogeneous dependent recursion principle for a quotient.\nThis may be easier to work with since it uses `HEq` instead of\nan `Eq.ndrec` in the hypothesis.\n-/\nprotected abbrev hrecOn\n (q : Quot r)\n (f : (a : α) → motive (Quot.mk r a))\n (c : (a b : α) → (p : r a b) → HEq (f a) (f b))\n : motive q :=\n Quot.recOn q f fun a b p => eq_of_heq <|\n have p₁ : HEq (Eq.ndrec (f a) (sound p)) (f a) := eqRec_heq (sound p) (f a)\n HEq.trans p₁ (c a b p)\n\nend\nend Quot\n\nset_option linter.unusedVariables.funArgs false in\n/--\n`Quotient α s` is the same as `Quot α r`, but it is specialized to a setoid `s`\n(that is, an equivalence relation) instead of an arbitrary relation.\nPrefer `Quotient` over `Quot` if your relation is actually an equivalence relation.\n-/\ndef Quotient {α : Sort u} (s : Setoid α) :=\n @Quot α Setoid.r\n\nnamespace Quotient\n\n/-- The canonical quotient map into a `Quotient`. -/\n@[inline]\nprotected def mk {α : Sort u} (s : Setoid α) (a : α) : Quotient s :=\n Quot.mk Setoid.r a\n\n/--\nThe canonical quotient map into a `Quotient`.\n(This synthesizes the setoid by typeclass inference.)\n-/\nprotected def mk' {α : Sort u} [s : Setoid α] (a : α) : Quotient s :=\n Quotient.mk s a\n\n/--\nThe analogue of `Quot.sound`: If `a` and `b` are related by the equivalence relation,\nthen they have equal equivalence classes.\n-/\ndef sound {α : Sort u} {s : Setoid α} {a b : α} : a ≈ b → Quotient.mk s a = Quotient.mk s b :=\n Quot.sound\n\n/--\nThe analogue of `Quot.lift`: if `f : α → β` respects the equivalence relation `≈`,\nthen it lifts to a function on `Quotient s` such that `lift f h (mk a) = f a`.\n-/\nprotected abbrev lift {α : Sort u} {β : Sort v} {s : Setoid α} (f : α → β) : ((a b : α) → a ≈ b → f a = f b) → Quotient s → β :=\n Quot.lift f\n\nprotected theorem ind {α : Sort u} {s : Setoid α} {motive : Quotient s → Prop} : ((a : α) → motive (Quotient.mk s a)) → (q : Quot Setoid.r) → motive q :=\n Quot.ind\n\n/--\nThe analogue of `Quot.liftOn`: if `f : α → β` respects the equivalence relation `≈`,\nthen it lifts to a function on `Quotient s` such that `lift (mk a) f h = f a`.\n-/\nprotected abbrev liftOn {α : Sort u} {β : Sort v} {s : Setoid α} (q : Quotient s) (f : α → β) (c : (a b : α) → a ≈ b → f a = f b) : β :=\n Quot.liftOn q f c\n\n@[elab_as_elim]\nprotected theorem inductionOn {α : Sort u} {s : Setoid α} {motive : Quotient s → Prop}\n (q : Quotient s)\n (h : (a : α) → motive (Quotient.mk s a))\n : motive q :=\n Quot.inductionOn q h\n\ntheorem exists_rep {α : Sort u} {s : Setoid α} (q : Quotient s) : Exists (fun (a : α) => Quotient.mk s a = q) :=\n Quot.exists_rep q\n\nsection\nvariable {α : Sort u}\nvariable {s : Setoid α}\nvariable {motive : Quotient s → Sort v}\n\n/-- The analogue of `Quot.rec` for `Quotient`. See `Quot.rec`. -/\n@[inline, elab_as_elim]\nprotected def rec\n (f : (a : α) → motive (Quotient.mk s a))\n (h : (a b : α) → (p : a ≈ b) → Eq.ndrec (f a) (Quotient.sound p) = f b)\n (q : Quotient s)\n : motive q :=\n Quot.rec f h q\n\n/-- The analogue of `Quot.recOn` for `Quotient`. See `Quot.recOn`. -/\n@[elab_as_elim]\nprotected abbrev recOn\n (q : Quotient s)\n (f : (a : α) → motive (Quotient.mk s a))\n (h : (a b : α) → (p : a ≈ b) → Eq.ndrec (f a) (Quotient.sound p) = f b)\n : motive q :=\n Quot.recOn q f h\n\n/-- The analogue of `Quot.recOnSubsingleton` for `Quotient`. See `Quot.recOnSubsingleton`. -/\n@[elab_as_elim]\nprotected abbrev recOnSubsingleton\n [h : (a : α) → Subsingleton (motive (Quotient.mk s a))]\n (q : Quotient s)\n (f : (a : α) → motive (Quotient.mk s a))\n : motive q :=\n Quot.recOnSubsingleton (h := h) q f\n\n/-- The analogue of `Quot.hrecOn` for `Quotient`. See `Quot.hrecOn`. -/\n@[elab_as_elim]\nprotected abbrev hrecOn\n (q : Quotient s)\n (f : (a : α) → motive (Quotient.mk s a))\n (c : (a b : α) → (p : a ≈ b) → HEq (f a) (f b))\n : motive q :=\n Quot.hrecOn q f c\nend\n\nsection\nuniverse uA uB uC\nvariable {α : Sort uA} {β : Sort uB} {φ : Sort uC}\nvariable {s₁ : Setoid α} {s₂ : Setoid β}\n\n/-- Lift a binary function to a quotient on both arguments. -/\nprotected abbrev lift₂\n (f : α → β → φ)\n (c : (a₁ : α) → (b₁ : β) → (a₂ : α) → (b₂ : β) → a₁ ≈ a₂ → b₁ ≈ b₂ → f a₁ b₁ = f a₂ b₂)\n (q₁ : Quotient s₁) (q₂ : Quotient s₂)\n : φ := by\n apply Quotient.lift (fun (a₁ : α) => Quotient.lift (f a₁) (fun (a b : β) => c a₁ a a₁ b (Setoid.refl a₁)) q₂) _ q₁\n intros\n induction q₂ using Quotient.ind\n apply c; assumption; apply Setoid.refl\n\n/-- Lift a binary function to a quotient on both arguments. -/\nprotected abbrev liftOn₂\n (q₁ : Quotient s₁)\n (q₂ : Quotient s₂)\n (f : α → β → φ)\n (c : (a₁ : α) → (b₁ : β) → (a₂ : α) → (b₂ : β) → a₁ ≈ a₂ → b₁ ≈ b₂ → f a₁ b₁ = f a₂ b₂)\n : φ :=\n Quotient.lift₂ f c q₁ q₂\n\n@[elab_as_elim]\nprotected theorem ind₂\n {motive : Quotient s₁ → Quotient s₂ → Prop}\n (h : (a : α) → (b : β) → motive (Quotient.mk s₁ a) (Quotient.mk s₂ b))\n (q₁ : Quotient s₁)\n (q₂ : Quotient s₂)\n : motive q₁ q₂ := by\n induction q₁ using Quotient.ind\n induction q₂ using Quotient.ind\n apply h\n\n@[elab_as_elim]\nprotected theorem inductionOn₂\n {motive : Quotient s₁ → Quotient s₂ → Prop}\n (q₁ : Quotient s₁)\n (q₂ : Quotient s₂)\n (h : (a : α) → (b : β) → motive (Quotient.mk s₁ a) (Quotient.mk s₂ b))\n : motive q₁ q₂ := by\n induction q₁ using Quotient.ind\n induction q₂ using Quotient.ind\n apply h\n\n@[elab_as_elim]\nprotected theorem inductionOn₃\n {s₃ : Setoid φ}\n {motive : Quotient s₁ → Quotient s₂ → Quotient s₃ → Prop}\n (q₁ : Quotient s₁)\n (q₂ : Quotient s₂)\n (q₃ : Quotient s₃)\n (h : (a : α) → (b : β) → (c : φ) → motive (Quotient.mk s₁ a) (Quotient.mk s₂ b) (Quotient.mk s₃ c))\n : motive q₁ q₂ q₃ := by\n induction q₁ using Quotient.ind\n induction q₂ using Quotient.ind\n induction q₃ using Quotient.ind\n apply h\n\nend\n\nsection Exact\n\nvariable {α : Sort u}\n\nprivate def rel {s : Setoid α} (q₁ q₂ : Quotient s) : Prop :=\n Quotient.liftOn₂ q₁ q₂\n (fun a₁ a₂ => a₁ ≈ a₂)\n (fun _ _ _ _ a₁b₁ a₂b₂ =>\n propext (Iff.intro\n (fun a₁a₂ => Setoid.trans (Setoid.symm a₁b₁) (Setoid.trans a₁a₂ a₂b₂))\n (fun b₁b₂ => Setoid.trans a₁b₁ (Setoid.trans b₁b₂ (Setoid.symm a₂b₂)))))\n\nprivate theorem rel.refl {s : Setoid α} (q : Quotient s) : rel q q :=\n q.inductionOn Setoid.refl\n\nprivate theorem rel_of_eq {s : Setoid α} {q₁ q₂ : Quotient s} : q₁ = q₂ → rel q₁ q₂ :=\n fun h => Eq.ndrecOn h (rel.refl q₁)\n\ntheorem exact {s : Setoid α} {a b : α} : Quotient.mk s a = Quotient.mk s b → a ≈ b :=\n fun h => rel_of_eq h\n\nend Exact\n\nsection\nuniverse uA uB uC\nvariable {α : Sort uA} {β : Sort uB}\nvariable {s₁ : Setoid α} {s₂ : Setoid β}\n\n/-- Lift a binary function to a quotient on both arguments. -/\n@[elab_as_elim]\nprotected abbrev recOnSubsingleton₂\n {motive : Quotient s₁ → Quotient s₂ → Sort uC}\n [s : (a : α) → (b : β) → Subsingleton (motive (Quotient.mk s₁ a) (Quotient.mk s₂ b))]\n (q₁ : Quotient s₁)\n (q₂ : Quotient s₂)\n (g : (a : α) → (b : β) → motive (Quotient.mk s₁ a) (Quotient.mk s₂ b))\n : motive q₁ q₂ := by\n induction q₁ using Quot.recOnSubsingleton\n induction q₂ using Quot.recOnSubsingleton\n apply g\n intro a; apply s\n induction q₂ using Quot.recOnSubsingleton\n intro a; apply s\n infer_instance\n\nend\nend Quotient\n\nsection\nvariable {α : Type u}\nvariable (r : α → α → Prop)\n\ninstance {α : Sort u} {s : Setoid α} [d : ∀ (a b : α), Decidable (a ≈ b)] : DecidableEq (Quotient s) :=\n fun (q₁ q₂ : Quotient s) =>\n Quotient.recOnSubsingleton₂ q₁ q₂\n fun a₁ a₂ =>\n match d a₁ a₂ with\n | isTrue h₁ => isTrue (Quotient.sound h₁)\n | isFalse h₂ => isFalse fun h => absurd (Quotient.exact h) h₂\n\n/-! # Function extensionality -/\n\n/--\n**Function extensionality** is the statement that if two functions take equal values\nevery point, then the functions themselves are equal: `(∀ x, f x = g x) → f = g`.\nIt is called \"extensionality\" because it talks about how to prove two objects are equal\nbased on the properties of the object (compare with set extensionality,\nwhich is `(∀ x, x ∈ s ↔ x ∈ t) → s = t`).\n\nThis is often an axiom in dependent type theory systems, because it cannot be proved\nfrom the core logic alone. However in lean's type theory this follows from the existence\nof quotient types (note the `Quot.sound` in the proof, as well as the `show` line\nwhich makes use of the definitional equality `Quot.lift f h (Quot.mk x) = f x`).\n-/\ntheorem funext {α : Sort u} {β : α → Sort v} {f g : (x : α) → β x}\n (h : ∀ x, f x = g x) : f = g := by\n let eqv (f g : (x : α) → β x) := ∀ x, f x = g x\n let extfunApp (f : Quot eqv) (x : α) : β x :=\n Quot.liftOn f\n (fun (f : ∀ (x : α), β x) => f x)\n (fun _ _ h => h x)\n show extfunApp (Quot.mk eqv f) = extfunApp (Quot.mk eqv g)\n exact congrArg extfunApp (Quot.sound h)\n\ninstance {α : Sort u} {β : α → Sort v} [∀ a, Subsingleton (β a)] : Subsingleton (∀ a, β a) where\n allEq f g := funext fun a => Subsingleton.elim (f a) (g a)\n\n/-! # Squash -/\n\n/--\n`Squash α` is the quotient of `α` by the always true relation.\nIt is empty if `α` is empty, otherwise it is a singleton.\n(Thus it is unconditionally a `Subsingleton`.)\nIt is the \"universal `Subsingleton`\" mapped from `α`.\n\nIt is similar to `Nonempty α`, which has the same properties, but unlike\n`Nonempty` this is a `Type u`, that is, it is \"data\", and the compiler\nrepresents an element of `Squash α` the same as `α` itself\n(as compared to `Nonempty α`, whose elements are represented by a dummy value).\n\n`Squash.lift` will extract a value in any subsingleton `β` from a function on `α`,\nwhile `Nonempty.rec` can only do the same when `β` is a proposition.\n-/\ndef Squash (α : Type u) := Quot (fun (_ _ : α) => True)\n\n/-- The canonical quotient map into `Squash α`. -/\ndef Squash.mk {α : Type u} (x : α) : Squash α := Quot.mk _ x\n\ntheorem Squash.ind {α : Type u} {motive : Squash α → Prop} (h : ∀ (a : α), motive (Squash.mk a)) : ∀ (q : Squash α), motive q :=\n Quot.ind h\n\n/-- If `β` is a subsingleton, then a function `α → β` lifts to `Squash α → β`. -/\n@[inline] def Squash.lift {α β} [Subsingleton β] (s : Squash α) (f : α → β) : β :=\n Quot.lift f (fun _ _ _ => Subsingleton.elim _ _) s\n\ninstance : Subsingleton (Squash α) where\n allEq a b := by\n induction a using Squash.ind\n induction b using Squash.ind\n apply Quot.sound\n trivial\n\n/-! # Relations -/\n\n/--\n`Antisymm (·≤·)` says that `(·≤·)` is antisymmetric, that is, `a ≤ b → b ≤ a → a = b`.\n-/\nclass Antisymm {α : Sort u} (r : α → α → Prop) where\n /-- An antisymmetric relation `(·≤·)` satisfies `a ≤ b → b ≤ a → a = b`. -/\n antisymm {a b : α} : r a b → r b a → a = b\n\nnamespace Lean\n/-! # Kernel reduction hints -/\n\n/--\nWhen the kernel tries to reduce a term `Lean.reduceBool c`, it will invoke the Lean interpreter to evaluate `c`.\nThe kernel will not use the interpreter if `c` is not a constant.\nThis feature is useful for performing proofs by reflection.\n\nRemark: the Lean frontend allows terms of the from `Lean.reduceBool t` where `t` is a term not containing\nfree variables. The frontend automatically declares a fresh auxiliary constant `c` and replaces the term with\n`Lean.reduceBool c`. The main motivation is that the code for `t` will be pre-compiled.\n\nWarning: by using this feature, the Lean compiler and interpreter become part of your trusted code base.\nThis is extra 30k lines of code. More importantly, you will probably not be able to check your development using\nexternal type checkers (e.g., Trepplein) that do not implement this feature.\nKeep in mind that if you are using Lean as programming language, you are already trusting the Lean compiler and interpreter.\nSo, you are mainly losing the capability of type checking your development using external checkers.\n\nRecall that the compiler trusts the correctness of all `[implemented_by ...]` and `[extern ...]` annotations.\nIf an extern function is executed, then the trusted code base will also include the implementation of the associated\nforeign function.\n-/\nopaque reduceBool (b : Bool) : Bool := b\n\n/--\nSimilar to `Lean.reduceBool` for closed `Nat` terms.\n\nRemark: we do not have plans for supporting a generic `reduceValue {α} (a : α) : α := a`.\nThe main issue is that it is non-trivial to convert an arbitrary runtime object back into a Lean expression.\nWe believe `Lean.reduceBool` enables most interesting applications (e.g., proof by reflection).\n-/\nopaque reduceNat (n : Nat) : Nat := n\n\n/--\nThe axiom `ofReduceBool` is used to perform proofs by reflection. See `reduceBool`.\n\nThis axiom is usually not used directly, because it has some syntactic restrictions.\nInstead, the `native_decide` tactic can be used to prove any proposition whose\ndecidability instance can be evaluated to `true` using the lean compiler / interpreter.\n\nWarning: by using this feature, the Lean compiler and interpreter become part of your trusted code base.\nThis is extra 30k lines of code. More importantly, you will probably not be able to check your development using\nexternal type checkers (e.g., Trepplein) that do not implement this feature.\nKeep in mind that if you are using Lean as programming language, you are already trusting the Lean compiler and interpreter.\nSo, you are mainly losing the capability of type checking your development using external checkers.\n-/\naxiom ofReduceBool (a b : Bool) (h : reduceBool a = b) : a = b\n\n/--\nThe axiom `ofReduceNat` is used to perform proofs by reflection. See `reduceBool`.\n\nWarning: by using this feature, the Lean compiler and interpreter become part of your trusted code base.\nThis is extra 30k lines of code. More importantly, you will probably not be able to check your development using\nexternal type checkers (e.g., Trepplein) that do not implement this feature.\nKeep in mind that if you are using Lean as programming language, you are already trusting the Lean compiler and interpreter.\nSo, you are mainly losing the capability of type checking your development using external checkers.\n-/\naxiom ofReduceNat (a b : Nat) (h : reduceNat a = b) : a = b\n\n/--\n`IsAssociative op` says that `op` is an associative operation,\ni.e. `(a ∘ b) ∘ c = a ∘ (b ∘ c)`. It is used by the `ac_rfl` tactic.\n-/\nclass IsAssociative {α : Sort u} (op : α → α → α) where\n /-- An associative operation satisfies `(a ∘ b) ∘ c = a ∘ (b ∘ c)`. -/\n assoc : (a b c : α) → op (op a b) c = op a (op b c)\n\n/--\n`IsCommutative op` says that `op` is a commutative operation,\ni.e. `a ∘ b = b ∘ a`. It is used by the `ac_rfl` tactic.\n-/\nclass IsCommutative {α : Sort u} (op : α → α → α) where\n /-- A commutative operation satisfies `a ∘ b = b ∘ a`. -/\n comm : (a b : α) → op a b = op b a\n\n/--\n`IsIdempotent op` says that `op` is an idempotent operation,\ni.e. `a ∘ a = a`. It is used by the `ac_rfl` tactic\n(which also simplifies up to idempotence when available).\n-/\nclass IsIdempotent {α : Sort u} (op : α → α → α) where\n /-- An idempotent operation satisfies `a ∘ a = a`. -/\n idempotent : (x : α) → op x x = x\n\n/--\n`IsNeutral op e` says that `e` is a neutral operation for `op`,\ni.e. `a ∘ e = a = e ∘ a`. It is used by the `ac_rfl` tactic\n(which also simplifies neutral elements when available).\n-/\nclass IsNeutral {α : Sort u} (op : α → α → α) (neutral : α) where\n /-- A neutral element can be cancelled on the left: `e ∘ a = a`. -/\n left_neutral : (a : α) → op neutral a = a\n /-- A neutral element can be cancelled on the right: `a ∘ e = a`. -/\n right_neutral : (a : α) → op a neutral = a\n\nend Lean\n", "meta": {"author": "lurk-lab", "repo": "yatima", "sha": "f33b0bf1052d95f9acbbe61681b1b58c0b97121e", "save_path": "github-repos/lean/lurk-lab-yatima", "path": "github-repos/lean/lurk-lab-yatima/yatima-f33b0bf1052d95f9acbbe61681b1b58c0b97121e/Fixtures/Termination/Init/Core.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.43782349911420193, "lm_q2_score": 0.0913820937876881, "lm_q1q2_score": 0.04000922805850778}} {"text": "/-\nCopyright (c) 2022 Devon Tuma. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Devon Tuma\n-/\nimport computational_monads.distribution_semantics.prod\n\n/-!\n# Oracle Simulation Semantics\n\nDefines the notion of simulating a computation by defining the outputs of oracle query.\nA method of simulation is given by `sim_oracle`, which contains an internal state\n as well as a function to return a value and update the state given a query to the oracle.\n\nIt also contains a `default_state`, specifying the value to use for the default oracle state.\nFor example a logging query would use an empty log as the default state.\n\nWe define `simulate'` to be simulation followed by discarding the state.\nThis is useful for things like a random oracle, where the final log isn't relevant in general.\n-/\n\nvariables {α β γ : Type} {spec spec' spec'' : oracle_spec} {S S' : Type}\n\n/-- Specifies a way to simulate a set of oracles using another set of oracles.\n e.g. using uniform random selection to simulate a hash oracle\n\n `default_state` can be provided as a standard initial state for simulation.\n Used when calling `default_simulate` or `default_simulate'` -/\nstructure sim_oracle (spec spec' : oracle_spec) (S : Type) :=\n(default_state : S)\n(o (i : spec.ι) : (spec.domain i × S) → oracle_comp spec' (spec.range i × S))\n\nnamespace sim_oracle\n\n/-- Example of an oracle maintaining in internal incrementing value,\n and returning a fake coin flip based on whether the state is even. -/\nexample : sim_oracle oracle_spec.coin_spec oracle_spec.coin_spec ℕ :=\n{ default_state := 0,\n o := λ i ⟨t, n⟩, return (if even n then tt else ff, n + 1) }\n\n/-- View a simulation oracle as a function corresponding to the internal oracle `o` -/\ninstance has_coe_to_fun : has_coe_to_fun (sim_oracle spec spec' S)\n (λ so, Π (i : spec.ι), spec.domain i × S → oracle_comp spec' (spec.range i × S)) :=\n{ coe := λ so, so.o }\n\nlemma has_coe_to_fun.def (so : sim_oracle spec spec' S) (i : spec.ι)\n (x : spec.domain i × S) : so i x = so.o i x := rfl\n\ndef inhabited_state (so : sim_oracle spec spec' S) : inhabited S := ⟨so.default_state⟩\n\ninstance inhabited [inhabited S] : inhabited (sim_oracle spec spec' S) :=\n⟨{default_state := default, o := λ _ _, return default}⟩\n\nend sim_oracle\n\nnamespace oracle_comp\n\nopen_locale big_operators ennreal\nopen oracle_spec\n\nvariables (so : sim_oracle spec spec' S) (so' : sim_oracle spec spec'' S')\n (a : α) (i : spec.ι) (t : spec.domain i) (oa oa' : oracle_comp spec α)\n (ob ob' : α → oracle_comp spec β) (oc : β → oracle_comp spec γ) (s : S) (f : α → β)\n\nsection simulate\n\n/-- Simulate an oracle comp to an oracle comp with a different spec.\nRequires providing a maximum recursion depth for the `repeat` constructor. -/\ndef simulate {spec spec' : oracle_spec} (so : sim_oracle spec spec' S) :\n Π {α : Type} (oa : oracle_comp spec α), S → oracle_comp spec' (α × S)\n| _ (pure' α a) state := return ⟨a, state⟩\n| _ (bind' α β oa ob) state := simulate oa state >>= λ x, simulate (ob x.1) x.2\n| _ (query i t) state := so i (t, state)\n\n/-- Convenience definition to use the default state as the initial state for `simulate`.\nMarked to be reduced and inlined, so the definition is essentially just notation. -/\n@[inline, reducible, simp]\ndef default_simulate (so : sim_oracle spec spec' S) (oa : oracle_comp spec α) :\n oracle_comp spec' (α × S) := simulate so oa so.default_state\n\n@[simp] lemma simulate_return : simulate so (return a) s = return (a, s) := rfl\n\nlemma simulate_pure' : simulate so (pure' α a) s = return (a, s) := rfl\n\nlemma simulate_pure : simulate so (pure a) s = return (a, s) := rfl\n\n@[simp] lemma simulate_bind : simulate so (oa >>= ob) s =\n simulate so oa s >>= λ x, simulate so (ob x.1) x.2 := rfl\n\nlemma simulate_bind' : simulate so (bind' α β oa ob) s =\n simulate so oa s >>= λ x, simulate so (ob x.1) x.2 := rfl\n\n@[simp] lemma simulate_query : simulate so (query i t) s = so i (t, s) := rfl\n\n@[simp] lemma simulate_map : simulate so (f <$> oa) s = prod.map f id <$> simulate so oa s := rfl\n\ninstance simulate.decidable [hoa : oa.decidable] [decidable_eq S]\n [h : ∀ i t s, (so i (t, s)).decidable] : (oa.simulate so s).decidable :=\nbegin\n unfreezingI {induction oa using oracle_comp.induction_on\n with α a α β oa ob hoa' hob' i t generalizing s},\n { haveI : decidable_eq α := decidable_eq_of_decidable' hoa,\n exact oracle_comp.decidable_return (a, s) },\n { haveI : oa.decidable := decidable_of_decidable_bind_fst hoa,\n haveI : ∀ a, (ob a).decidable := λ a, decidable_of_decidable_bind_snd a hoa,\n haveI : (simulate so oa s).decidable := hoa' _,\n haveI : ∀ (x : α × S), (simulate so (ob x.1) x.2).decidable := λ x, hob' _ _,\n refine oracle_comp.decidable_bind' _ _ },\n { exact h i t s }\nend\n\nsection support\n\nlemma support_simulate_return : (simulate so (return a) s).support = {(a, s)} := rfl\n\nlemma support_simulate_pure' : (simulate so (pure' α a) s).support = {(a, s)} := rfl\n\nlemma support_simulate_pure : (simulate so (pure a) s).support = {(a, s)} := rfl\n\nlemma support_simulate_bind : (simulate so (oa >>= ob) s).support =\n ⋃ x ∈ (simulate so oa s).support, (simulate so (ob $ prod.fst x) x.2).support := rfl\n\nlemma mem_support_simulate_bind_iff (x : β × S) : x ∈ (simulate so (oa >>= ob) s).support ↔\n ∃ (a : α) (s' : S), (a, s') ∈ (simulate so oa s).support ∧ x ∈ (simulate so (ob a) s').support :=\nby simp_rw [support_simulate_bind, set.mem_Union, prod.exists, exists_prop]\n\nlemma support_simulate_bind' : (simulate so (bind' α β oa ob) s).support\n = ⋃ x ∈ (simulate so oa s).support, (simulate so (ob $ prod.fst x) x.2).support := rfl\n\nlemma support_simulate_query : (simulate so (query i t) s).support = (so i (t, s)).support := rfl\n\nlemma support_simulate_map : (simulate so (f <$> oa) s).support =\n prod.map f id '' (simulate so oa s).support := by rw [simulate_map, support_map]\n\nend support\n\nsection fin_support\n\n\n\nend fin_support\n\nsection eval_dist\n\nlemma eval_dist_simulate_return : ⁅simulate so (return a) s⁆ = pmf.pure (a, s) := rfl\n\nlemma eval_dist_simulate_pure' : ⁅simulate so (pure' α a) s⁆ = pmf.pure (a, s) := rfl\n\nlemma eval_dist_simulate_pure : ⁅simulate so (pure a) s⁆ = pmf.pure (a, s) := rfl\n\n@[simp] lemma eval_dist_simulate_bind : ⁅simulate so (oa >>= ob) s⁆ =\n (⁅simulate so oa s⁆).bind (λ x, ⁅simulate so (ob x.1) x.2⁆) :=\n(congr_arg _ $ simulate_bind so oa ob s).trans (eval_dist_bind _ _)\n\nlemma eval_dist_simulate_bind' : ⁅simulate so (bind' α β oa ob) s⁆ =\n (⁅simulate so oa s⁆).bind (λ x, ⁅simulate so (ob x.1) x.2⁆) :=\neval_dist_simulate_bind so oa ob s\n\nlemma eval_dist_simulate_query : ⁅simulate so (query i t) s⁆ = ⁅so i (t, s)⁆ := rfl\n\nlemma eval_dist_simulate_map : ⁅simulate so (f <$> oa) s⁆ =\n ⁅simulate so oa s⁆.map (prod.map f id) := by rw [simulate_map, eval_dist_map]\n\n/-- Write the `eval_dist` of a simulation as a double summation over the possible\nintermediate outputs and states of the computation. -/\nlemma eval_dist_simulate_bind_apply_eq_tsum_tsum (x : β × S) : ⁅simulate so (oa >>= ob) s⁆ x =\n ∑' a s', ⁅simulate so oa s⁆ (a, s') * ⁅simulate so (ob a) s'⁆ x :=\nby rw [simulate_bind, eval_dist_prod_bind]\n\nlemma eval_dist_simulate_bind_apply_eq_sum_sum [fintype α] [fintype S] (x : β × S) :\n ⁅simulate so (oa >>= ob) s⁆ x = ∑ a s', ⁅simulate so oa s⁆ (a, s') * ⁅simulate so (ob a) s'⁆ x :=\nby simp only [simulate_bind, eval_dist_bind_apply_eq_sum, ← @finset.sum_product ℝ≥0∞ S α _\n finset.univ finset.univ (λ y, ⁅simulate so oa s⁆ (y.1, y.2) * ⁅simulate so (ob y.1) y.2⁆ x),\n finset.univ_product_univ, prod.mk.eta]\n\nend eval_dist\n\nsection prob_event\n\nlemma prob_event_simulate_return (e : set (α × S)) :\n ⁅e | simulate so (return a) s⁆ = e.indicator (λ _, 1) (a, s) :=\nprob_event_return_eq_indicator (a, s) e\n\nlemma prob_event_simulate_bind_eq_tsum_tsum (e : set (β × S)) : ⁅e | simulate so (oa >>= ob) s⁆ =\n ∑' a s', ⁅simulate so oa s⁆ (a, s') * ⁅e | simulate so (ob a) s'⁆ :=\nby simp_rw [simulate_bind, prob_event_bind_eq_tsum, ← ennreal.tsum_prod, prod.mk.eta]\n\nlemma prob_event_simulate_bind_eq_sum_sum [fintype α] [fintype S] (e : set (β × S)) :\n ⁅e | simulate so (oa >>= ob) s⁆ =\n ∑ a s', ⁅simulate so oa s⁆ (a, s') * ⁅e | simulate so (ob a) s'⁆ :=\nby simp only [simulate_bind, prob_event_bind_eq_sum, ← @finset.sum_product ℝ≥0∞ S α _ finset.univ\n finset.univ (λ x, ⁅simulate so oa s⁆ (x.1, x.2) * ⁅e | simulate so (ob x.1) x.2⁆),\n finset.univ_product_univ, prod.mk.eta]\n\nlemma prob_event_simulate_query (e : set (spec.range i × S)) :\n ⁅e | simulate so (query i t) s⁆ = ⁅e | so i (t, s)⁆ := rfl\n\nlemma prob_event_simulate_map (e : set (β × S)) :\n ⁅e | simulate so (f <$> oa) s⁆ = ⁅prod.map f id ⁻¹' e | simulate so oa s⁆ :=\nby rw [simulate_map, prob_event_map]\n\nend prob_event\n\nend simulate\n\nsection simulate'\n\n/-- Get the result of simulation without returning the internal oracle state -/\ndef simulate' (so : sim_oracle spec spec' S) (oa : oracle_comp spec α) (s : S) :\n oracle_comp spec' α := prod.fst <$> oa.simulate so s\n\n/-- Convenience definition to use the default state as the initial state for `simulate'`.\nMarked to be reduced and inlined, so the definition is essentially just notation. -/\n@[inline, reducible, simp]\ndef default_simulate' (so : sim_oracle spec spec' S) (oa : oracle_comp spec α) :\n oracle_comp spec' α := oa.simulate' so so.default_state\n\nlemma simulate'_def : simulate' so oa s = prod.fst <$> oa.simulate so s := rfl\n\n-- TODO: these should have a special simp category, to not be eagerly applied\n@[simp] lemma simulate'_return : simulate' so (return a) s = prod.fst <$> (return (a, s)) := rfl\n\nlemma simulate'_pure' : simulate' so (pure' α a) s = prod.fst <$> (return (a, s)) := rfl\n\nlemma simulate'_pure : simulate' so (pure a) s = prod.fst <$> (return (a, s)) := rfl\n\n@[simp] lemma simulate'_bind : simulate' so (oa >>= ob) s =\n prod.fst <$> (simulate so oa s >>= λ x, simulate so (ob x.1) x.2) := rfl\n\nlemma simulate'_bind' : simulate' so (bind' α β oa ob) s =\n prod.fst <$> (simulate so oa s >>= λ x, simulate so (ob x.1) x.2) := rfl\n\n@[simp] lemma simulate'_query : simulate' so (query i t) s = prod.fst <$> so i (t, s) := rfl\n\n@[simp] lemma simulate'_map : simulate' so (f <$> oa) s =\n prod.fst <$> (prod.map f id <$> simulate so oa s) := rfl\n\ninstance simulate'.decidable [hoa : oa.decidable] [decidable_eq S]\n [h : ∀ i t s, (so i (t, s)).decidable] : (oa.simulate' so s).decidable :=\nbegin\n haveI : decidable_eq α := decidable_eq_of_decidable oa,\n exact oracle_comp.decidable_map _ _,\nend\n\nsection support\n\n@[simp] lemma support_simulate' : (simulate' so oa s).support =\n prod.fst '' (simulate so oa s).support := by simp only [simulate', support_map]\n\nlemma mem_support_simulate'_iff_exists_state (a : α) :\n a ∈ (simulate' so oa s).support ↔ ∃ (s' : S), (a, s') ∈ (simulate so oa s).support :=\nby simp only [support_simulate', set.mem_image, prod.exists,\n exists_and_distrib_right, exists_eq_right]\n\nlemma support_simulate'_return (a : α) : (simulate' so (return a) s).support = {a} :=\nby simp only [simulate'_return, support_map, support_return, set.image_singleton]\n\nlemma support_simulate'_pure' (a : α) : (simulate' so (pure' α a) s).support = {a} :=\nsupport_simulate'_return so s a\n\nlemma support_simulate'_pure (a : α) : (simulate' so (pure a) s).support = {a} :=\nsupport_simulate'_return so s a\n\n@[simp] lemma support_simulate'_bind : (simulate' so (oa >>= ob) s).support =\n ⋃ x ∈ (simulate so oa s).support, (simulate' so (ob $ prod.fst x) x.snd).support :=\nby simp [set.image_Union]\n\nlemma support_simulate'_bind' : (simulate' so (bind' α β oa ob) s).support =\n ⋃ x ∈ (simulate so oa s).support, (simulate' so (ob $ prod.fst x) x.snd).support :=\nsupport_simulate'_bind so oa ob s\n\nlemma support_simulate'_query : (simulate' so (query i t) s).support =\n prod.fst '' (so i (t, s)).support := by simp only [simulate'_query, support_map]\n\n@[simp] lemma support_simulate'_map : (simulate' so (f <$> oa) s).support =\n f '' (simulate' so oa s).support :=\nby simp only [simulate', support_map, support_simulate_map, set.image_image, prod.map_fst]\n\nend support\n\nsection eval_dist\n\n@[simp] lemma eval_dist_simulate' : ⁅simulate' so oa s⁆ = ⁅simulate so oa s⁆.map prod.fst :=\neval_dist_map _ prod.fst\n\n/-- Express the probability of `simulate'` returning a specific value\nas the sum over all possible output states of the probability of `simulate` return it -/\nlemma eval_dist_simulate'_apply : ⁅simulate' so oa s⁆ a = ∑' s', ⁅simulate so oa s⁆ (a, s') :=\nbegin\n rw [eval_dist_simulate', pmf.map_apply],\n refine (tsum_prod_eq_tsum_snd a $ λ s a' ha', _).trans (tsum_congr (λ s', _)),\n { simp only [ne.symm ha', if_false] },\n { simp only [eq_self_iff_true, if_true] }\nend\n\nlemma eval_dist_simulate'_return : ⁅simulate' so (return a) s⁆ = pmf.pure a :=\nby simp only [simulate'_return, eval_dist_map, eval_dist_return, pmf.map_pure]\n\nlemma eval_dist_simulate'_pure' : ⁅simulate' so (pure' α a) s⁆ = pmf.pure a :=\neval_dist_simulate'_return so a s\n\nlemma eval_dist_simulate'_pure : ⁅simulate' so (pure a) s⁆ = pmf.pure a :=\neval_dist_simulate'_return so a s\n\nlemma eval_dist_simulate'_bind : ⁅simulate' so (oa >>= ob) s⁆ =\n ⁅simulate so oa s⁆.bind (λ x, ⁅simulate' so (ob x.1) x.2⁆) :=\nby simp only [simulate'_bind, eval_dist_map_bind, eval_dist_bind, eval_dist_map,\n eval_dist_simulate', eq_self_iff_true, pmf.map_bind]\n\nlemma eval_dist_simulate'_bind_apply (b : β) : ⁅simulate' so (oa >>= ob) s⁆ b\n = ∑' (a : α) (s' : S), ⁅simulate so oa s⁆ (a, s') * ⁅simulate' so (ob a) s'⁆ b :=\nby rw [eval_dist_simulate'_bind, pmf.bind_apply, tsum_prod'\n ennreal.summable (λ _, ennreal.summable)]\n\nlemma eval_dist_simulate'_bind' : ⁅simulate' so (bind' α β oa ob) s⁆ =\n ⁅simulate so oa s⁆.bind (λ x, ⁅simulate' so (ob x.1) x.2⁆) := eval_dist_simulate'_bind _ _ _ s\n\nlemma eval_dist_simulate'_query : ⁅simulate' so (query i t) s⁆ = ⁅so i (t, s)⁆.map prod.fst :=\nby simp only [simulate'_query, eval_dist_map]\n\n@[simp] lemma eval_dist_simulate'_map : ⁅simulate' so (f <$> oa) s⁆ = ⁅simulate' so oa s⁆.map f :=\nby simp_rw [eval_dist_simulate', eval_dist_simulate_map, pmf.map_comp, prod.map_fst']\n\nend eval_dist\n\nsection prob_event\n\nlemma prob_event_simulate' (e : set α) :\n ⁅e | simulate' so oa s⁆ = ⁅prod.fst ⁻¹' e | simulate so oa s⁆ :=\nby rw [simulate', prob_event_map]\n\nlemma prob_event_simulate'_return_eq_indicator (e : set α) :\n ⁅e | simulate' so (return a) s⁆ = e.indicator (λ _, 1) a :=\nbegin\n rw [prob_event_simulate', prob_event_simulate_return],\n by_cases ha : a ∈ e,\n { have : (a, s) ∈ (prod.fst ⁻¹' e : set (α × S)) := ha,\n rw [set.indicator_of_mem ha, set.indicator_of_mem this] },\n { have : (a, s) ∉ (prod.fst ⁻¹' e : set (α × S)) := ha,\n rw [set.indicator_of_not_mem ha, set.indicator_of_not_mem this] }\nend\n\nlemma prob_event_simulate'_return_eq_ite (e : set α) [decidable_pred (∈ e)] :\n ⁅e | simulate' so (return a) s⁆ = ite (a ∈ e) 1 0 :=\nby {rw [prob_event_simulate'_return_eq_indicator, set.indicator], congr}\n\nlemma prob_event_simulate'_bind_eq_tsum_tsum (e : set β) : ⁅e | simulate' so (oa >>= ob) s⁆ =\n ∑' a s', ⁅simulate so oa s⁆ (a, s') * ⁅e | simulate' so (ob a) s'⁆ :=\nby simp_rw [prob_event_simulate', prob_event_simulate_bind_eq_tsum_tsum]\n\nlemma prob_event_simulate'_bind_eq_sum_sum [fintype α] [fintype S] (e : set β) :\n ⁅e | simulate' so (oa >>= ob) s⁆ =\n ∑ a s', ⁅simulate so oa s⁆ (a, s') * ⁅e | simulate' so (ob a) s'⁆ :=\nby simp_rw [prob_event_simulate', prob_event_simulate_bind_eq_sum_sum]\n\nlemma prob_event_simulate'_query (e : set (spec.range i)) :\n ⁅e | simulate' so (query i t) s⁆ = ⁅prod.fst ⁻¹' e | so i (t, s)⁆ :=\nby rw [prob_event_simulate', prob_event_simulate_query]\n\nlemma prob_event_simulate'_map (e : set β) :\n ⁅e | simulate' so (f <$> oa) s⁆ = ⁅(f ∘ prod.fst) ⁻¹' e | simulate so oa s⁆ :=\nby simpa only [prob_event_simulate', prob_event_simulate_map, ← set.preimage_comp]\n\nend prob_event\n\nend simulate'\n\nend oracle_comp", "meta": {"author": "dtumad", "repo": "lean-crypto-formalization", "sha": "f975a9a9882120b509553a7ced9aa05b745ff154", "save_path": "github-repos/lean/dtumad-lean-crypto-formalization", "path": "github-repos/lean/dtumad-lean-crypto-formalization/lean-crypto-formalization-f975a9a9882120b509553a7ced9aa05b745ff154/src/computational_monads/simulation_semantics/simulate/basic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.476579651063676, "lm_q2_score": 0.08389039270915707, "lm_q1q2_score": 0.03998045408492483}} {"text": "/- refl: reflexive\nproves goals of form x=x -/\ntheorem example1 (x y z : Nat) : x * y + z = x * y + z :=\n rfl\n\n/- rw: rewrite (substitution)\n\n-/", "meta": {"author": "mothematician", "repo": "lean4-proof-stuff", "sha": "1f202b1d3059f3a36dab9abd7564594bf765ebf2", "save_path": "github-repos/lean/mothematician-lean4-proof-stuff", "path": "github-repos/lean/mothematician-lean4-proof-stuff/lean4-proof-stuff-1f202b1d3059f3a36dab9abd7564594bf765ebf2/documentation/tactics.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4493926492132671, "lm_q2_score": 0.08882028938519383, "lm_q1q2_score": 0.039915185150701284}} {"text": "/-\nCopyright (c) 2018 Simon Hudon. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Simon Hudon\n\nTransferring `traversable` instances using isomorphisms.\n-/\nimport data.equiv.basic category.traversable.lemmas\n\nuniverses u\n\nnamespace equiv\n\nsection functor\nparameters {t t' : Type u → Type u}\nparameters (eqv : Π α, t α ≃ t' α)\nvariables [functor t]\n\nopen functor\n\nprotected def map {α β : Type u} (f : α → β) (x : t' α) : t' β :=\neqv β $ map f ((eqv α).symm x)\n\nprotected def functor : functor t' :=\n{ map := @equiv.map _ }\n\nvariables [is_lawful_functor t]\n\nprotected lemma id_map {α : Type u} (x : t' α) : equiv.map id x = x :=\nby simp [equiv.map, id_map]\n\nprotected lemma comp_map {α β γ : Type u} (g : α → β) (h : β → γ) (x : t' α) :\n equiv.map (h ∘ g) x = equiv.map h (equiv.map g x) :=\nby simp [equiv.map]; apply comp_map\n\nprotected def is_lawful_functor : @is_lawful_functor _ equiv.functor :=\n{ id_map := @equiv.id_map _ _,\n comp_map := @equiv.comp_map _ _ }\n\nprotected def is_lawful_functor' [F : _root_.functor t']\n (h₀ : ∀ {α β} (f : α → β), _root_.functor.map f = equiv.map f)\n (h₁ : ∀ {α β} (f : β), _root_.functor.map_const f = (equiv.map ∘ function.const α) f) :\n _root_.is_lawful_functor t' :=\nbegin\n have : F = equiv.functor,\n { unfreezeI, cases F, dsimp [equiv.functor],\n congr; ext; [rw ← h₀, rw ← h₁] },\n constructor; intros;\n haveI F' := equiv.is_lawful_functor,\n { simp, intros, ext,\n rw [h₁], rw ← this at F',\n have k := @map_const_eq t' _ _ α β, rw this at ⊢ k, rw ← k, refl },\n { rw [h₀], rw ← this at F',\n have k := id_map x, rw this at k, apply k },\n { rw [h₀], rw ← this at F',\n have k := comp_map g h x, revert k, rw this, exact id },\nend\n\nend functor\n\nsection traversable\nparameters {t t' : Type u → Type u}\nparameters (eqv : Π α, t α ≃ t' α)\nvariables [traversable t]\nvariables {m : Type u → Type u} [applicative m]\nvariables {α β : Type u}\n\nprotected def traverse (f : α → m β) (x : t' α) : m (t' β) :=\neqv β <$> traverse f ((eqv α).symm x)\n\nprotected def traversable : traversable t' :=\n{ to_functor := equiv.functor eqv,\n traverse := @equiv.traverse _ }\n\nend traversable\n\nsection equiv\nparameters {t t' : Type u → Type u}\nparameters (eqv : Π α, t α ≃ t' α)\nvariables [traversable t] [is_lawful_traversable t]\nvariables {F G : Type u → Type u} [applicative F] [applicative G]\nvariables [is_lawful_applicative F] [is_lawful_applicative G]\nvariables (η : applicative_transformation F G)\nvariables {α β γ : Type u}\n\nopen is_lawful_traversable functor\n\nprotected lemma id_traverse (x : t' α) :\n equiv.traverse eqv id.mk x = x :=\nby simp! [equiv.traverse,id_bind,id_traverse,functor.map] with functor_norm\n\nprotected lemma traverse_eq_map_id (f : α → β) (x : t' α) :\n equiv.traverse eqv (id.mk ∘ f) x = id.mk (equiv.map eqv f x) :=\nby simp [equiv.traverse, traverse_eq_map_id] with functor_norm; refl\n\nprotected lemma comp_traverse (f : β → F γ) (g : α → G β) (x : t' α) :\n equiv.traverse eqv (comp.mk ∘ functor.map f ∘ g) x =\n comp.mk (equiv.traverse eqv f <$> equiv.traverse eqv g x) :=\nby simp [equiv.traverse,comp_traverse] with functor_norm; congr; ext; simp\n\nprotected lemma naturality (f : α → F β) (x : t' α) :\n η (equiv.traverse eqv f x) = equiv.traverse eqv (@η _ ∘ f) x :=\nby simp [equiv.traverse] with functor_norm\n\nprotected def is_lawful_traversable :\n @is_lawful_traversable t' (equiv.traversable eqv) :=\n{ to_is_lawful_functor := @equiv.is_lawful_functor _ _ eqv _ _,\n id_traverse := @equiv.id_traverse _ _,\n comp_traverse := @equiv.comp_traverse _ _,\n traverse_eq_map_id := @equiv.traverse_eq_map_id _ _,\n naturality := @equiv.naturality _ _ }\n\nprotected def is_lawful_traversable' [_i : traversable t']\n (h₀ : ∀ {α β} (f : α → β),\n map f = equiv.map eqv f)\n (h₁ : ∀ {α β} (f : β),\n map_const f = (equiv.map eqv ∘ function.const α) f)\n (h₂ : ∀ {F : Type u → Type u} [applicative F] [is_lawful_applicative F]\n {α β} (f : α → F β),\n traverse f = equiv.traverse eqv f) :\n _root_.is_lawful_traversable t' :=\nbegin\n -- we can't use the same approach as for `is_lawful_functor'` because\n -- h₂ needs a `is_lawful_applicative` assumption\n refine {to_is_lawful_functor :=\n equiv.is_lawful_functor' eqv @h₀ @h₁, ..}; intros; resetI,\n { rw [h₂, equiv.id_traverse], apply_instance },\n { rw [h₂, equiv.comp_traverse f g x, h₂], congr,\n rw [h₂], all_goals { apply_instance } },\n { rw [h₂, equiv.traverse_eq_map_id, h₀]; apply_instance },\n { rw [h₂, equiv.naturality, h₂]; apply_instance }\nend\n\nend equiv\nend equiv\n", "meta": {"author": "khoek", "repo": "mathlib-tidy", "sha": "866afa6ab597c47f1b72e8fe2b82b97fff5b980f", "save_path": "github-repos/lean/khoek-mathlib-tidy", "path": "github-repos/lean/khoek-mathlib-tidy/mathlib-tidy-866afa6ab597c47f1b72e8fe2b82b97fff5b980f/category/traversable/equiv.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.07921032465244027, "lm_q1q2_score": 0.039605162326220134}} {"text": "/-\nCopyright (c) 2020 Simon Hudon. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Simon Hudon\n-/\nimport control.monad.basic\nimport control.monad.cont\nimport control.monad.writer\nimport data.equiv.basic\nimport tactic.interactive\n\n/-!\n# Universe lifting for type families\n\nSome functors such as `option` and `list` are universe polymorphic. Unlike\ntype polymorphism where `option α` is a function application and reasoning and\ngeneralizations that apply to functions can be used, `option.{u}` and `option.{v}`\nare not one function applied to two universe names but one polymorphic definition\ninstantiated twice. This means that whatever works on `option.{u}` is hard\nto transport over to `option.{v}`. `uliftable` is an attempt at improving the situation.\n\n`uliftable option.{u} option.{v}` gives us a generic and composable way to use\n`option.{u}` in a context that requires `option.{v}`. It is often used in tandem with\n`ulift` but the two are purposefully decoupled.\n\n\n## Main definitions\n * `uliftable` class\n\n## Tags\n\nuniverse polymorphism functor\n\n-/\n\nuniverses u₀ u₁ v₀ v₁ v₂ w w₀ w₁\n\n/-- Given a universe polymorphic type family `M.{u} : Type u₁ → Type\nu₂`, this class convert between instantiations, from\n`M.{u} : Type u₁ → Type u₂` to `M.{v} : Type v₁ → Type v₂` and back -/\nclass uliftable (f : Type u₀ → Type u₁) (g : Type v₀ → Type v₁) :=\n(congr [] {α β} : α ≃ β → f α ≃ g β)\n\nnamespace uliftable\n\n/-- The most common practical use `uliftable` (together with `up`), this function takes\n`x : M.{u} α` and lifts it to M.{max u v} (ulift.{v} α) -/\n@[reducible]\ndef up {f : Type u₀ → Type u₁} {g : Type (max u₀ v₀) → Type v₁} [uliftable f g]\n {α} : f α → g (ulift α) :=\n(uliftable.congr f g equiv.ulift.symm).to_fun\n\n/-- The most common practical use of `uliftable` (together with `up`), this function takes\n`x : M.{max u v} (ulift.{v} α)` and lowers it to `M.{u} α` -/\n@[reducible]\ndef down {f : Type u₀ → Type u₁} {g : Type (max u₀ v₀) → Type v₁} [uliftable f g]\n {α} : g (ulift α) → f α :=\n(uliftable.congr f g equiv.ulift.symm).inv_fun\n\n/-- convenient shortcut to avoid manipulating `ulift` -/\ndef adapt_up (F : Type v₀ → Type v₁) (G : Type (max v₀ u₀) → Type u₁)\n [uliftable F G] [monad G] {α β}\n (x : F α) (f : α → G β) : G β :=\nup x >>= f ∘ ulift.down\n\n/-- convenient shortcut to avoid manipulating `ulift` -/\ndef adapt_down {F : Type (max u₀ v₀) → Type u₁} {G : Type v₀ → Type v₁}\n [L : uliftable G F] [monad F] {α β}\n (x : F α) (f : α → G β) : G β :=\n@down.{v₀ v₁ (max u₀ v₀)} G F L β $ x >>= @up.{v₀ v₁ (max u₀ v₀)} G F L β ∘ f\n\n/-- map function that moves up universes -/\ndef up_map {F : Type u₀ → Type u₁} {G : Type.{max u₀ v₀} → Type v₁} [inst : uliftable F G]\n [functor G] {α β} (f : α → β) (x : F α) : G β :=\nfunctor.map (f ∘ ulift.down) (up x)\n\n/-- map function that moves down universes -/\ndef down_map {F : Type.{max u₀ v₀} → Type u₁} {G : Type → Type v₁} [inst : uliftable G F]\n [functor F] {α β} (f : α → β) (x : F α) : G β :=\ndown (functor.map (ulift.up ∘ f) x : F (ulift β))\n\n@[simp]\nlemma up_down {f : Type u₀ → Type u₁} {g : Type (max u₀ v₀) → Type v₁} [uliftable f g]\n {α} (x : g (ulift α)) : up (down x : f α) = x :=\n(uliftable.congr f g equiv.ulift.symm).right_inv _\n\n@[simp]\nlemma down_up {f : Type u₀ → Type u₁} {g : Type (max u₀ v₀) → Type v₁} [uliftable f g]\n {α} (x : f α) : down (up x : g _) = x :=\n(uliftable.congr f g equiv.ulift.symm).left_inv _\n\nend uliftable\n\nopen ulift\n\ninstance : uliftable id id :=\n{ congr := λ α β F, F }\n\n/-- for specific state types, this function helps to create a uliftable instance -/\ndef state_t.uliftable' {s : Type u₀} {s' : Type u₁}\n {m : Type u₀ → Type v₀} {m' : Type u₁ → Type v₁}\n [uliftable m m']\n (F : s ≃ s') :\n uliftable (state_t s m) (state_t s' m') :=\n{ congr :=\n λ α β G, state_t.equiv $ equiv.Pi_congr F $\n λ _, uliftable.congr _ _ $ equiv.prod_congr G F }\n\ninstance {s m m'}\n [uliftable m m'] :\n uliftable (state_t s m) (state_t (ulift s) m') :=\nstate_t.uliftable' equiv.ulift.symm\n\n/-- for specific reader monads, this function helps to create a uliftable instance -/\ndef reader_t.uliftable' {s s' m m'}\n [uliftable m m']\n (F : s ≃ s') :\n uliftable (reader_t s m) (reader_t s' m') :=\n{ congr :=\n λ α β G, reader_t.equiv $ equiv.Pi_congr F $\n λ _, uliftable.congr _ _ G }\n\ninstance {s m m'} [uliftable m m'] : uliftable (reader_t s m) (reader_t (ulift s) m') :=\nreader_t.uliftable' equiv.ulift.symm\n\n/-- for specific continuation passing monads, this function helps to create a uliftable instance -/\ndef cont_t.uliftable' {r r' m m'}\n [uliftable m m']\n (F : r ≃ r') :\n uliftable (cont_t r m) (cont_t r' m') :=\n{ congr :=\n λ α β, cont_t.equiv (uliftable.congr _ _ F) }\n\ninstance {s m m'} [uliftable m m'] : uliftable (cont_t s m) (cont_t (ulift s) m') :=\ncont_t.uliftable' equiv.ulift.symm\n\n/-- for specific writer monads, this function helps to create a uliftable instance -/\ndef writer_t.uliftable' {w w' m m'}\n [uliftable m m']\n (F : w ≃ w') :\n uliftable (writer_t w m) (writer_t w' m') :=\n{ congr :=\n λ α β G, writer_t.equiv $ uliftable.congr _ _ $ equiv.prod_congr G F }\n\ninstance {s m m'} [uliftable m m'] : uliftable (writer_t s m) (writer_t (ulift s) m') :=\nwriter_t.uliftable' equiv.ulift.symm\n", "meta": {"author": "JLimperg", "repo": "aesop3", "sha": "a4a116f650cc7403428e72bd2e2c4cda300fe03f", "save_path": "github-repos/lean/JLimperg-aesop3", "path": "github-repos/lean/JLimperg-aesop3/aesop3-a4a116f650cc7403428e72bd2e2c4cda300fe03f/src/control/uliftable.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46490157137338844, "lm_q2_score": 0.08509903978628845, "lm_q1q2_score": 0.039562677319012}} {"text": "import Iris.BI\nimport Iris.Std\n\nnamespace Iris.Proofmode\nopen Iris.BI Iris.Std\nopen Lean\n\n/-- Single separation logic context, implemented as a list of hypotheses. A custom datatype is used\ninstead of the standard `List` to ensure that all operations are `reducible`. -/\ninductive Env (α : Type)\n | nil : Env α\n | cons : α → Env α → Env α\n\n-- Env Operations\nnamespace Env\n\n/-- Append a hypothesis to the end of the environment. -/\n@[reducible]\ndef append : Env α → α → Env α\n | .nil, b => .cons b .nil\n | .cons a as, b => .cons a <| as.append b\n\n/-- Return whether the environment is empty, i.e. it contains no hypotheses. -/\n@[reducible]\ndef isEmpty : Env α → Bool\n | .nil => true\n | .cons _ _ => false\n\n/-- Return the length of the environment, i.e. the number of contained hypotheses. -/\n@[reducible]\ndef length : Env α → Nat\n | .nil => 0\n | .cons _ as => as.length + 1\n\ntheorem length_cons_list_cons {a : α} {as : List α} {b : β} {bs : Env β} :\n (a :: as).length = (Env.cons b bs).length →\n as.length = bs.length\n:= by\n intro h\n simp only [length, List.length] at h\n rw' [Nat.add_right_cancel h]\n\n/-- Delete the hypothesis at the given index. -/\n@[reducible]\ndef delete : (Γ : Env α) → Fin (Γ.length) → Env α\n | .cons _ as, ⟨0 , _⟩ => as\n | .cons a as, ⟨i + 1, h⟩ => .cons a <| as.delete ⟨i, Nat.lt_of_succ_lt_succ h⟩\n\n/-- Return the hypothesis at a given index without removing it. -/\n@[reducible]\ndef get : (Γ : Env α) → Fin (Γ.length) → α\n | .cons a _ , ⟨0 , _⟩ => a\n | .cons _ as, ⟨i + 1, h⟩ => as.get ⟨i, Nat.lt_of_succ_lt_succ h⟩\n\n/-- Split the environment into two disjoint environments. The given boolean mask must have the same\nlength as the environment. If the boolean mask contains the value `true` at a given index, the\nhypothesis at the same index in the original environment is contained in the left environment in\nthe result. If the value is `false`, the hypothesis is contained in the right environment. -/\n@[reducible]\ndef split : (Γ : Env α) → (mask : List Bool) → (mask.length = Γ.length) → Env α × Env α\n | .nil, .nil, _ => (.nil, .nil)\n | .cons a as, b :: bs, h =>\n let (ls, rs) := split as bs (length_cons_list_cons h)\n if b then (.cons a ls, rs) else (ls, .cons a rs)\n\n/-- Return a list with exactly the hypotheses from the environment in the same order as in\nthe environment. -/\n@[reducible]\ndef toList : Env α → List α\n | .nil => []\n | .cons a as => a :: toList as\n\n/-- Proposition of membership for an hypothesis in an environment. -/\ninductive Mem : α → Env α → Prop\n | head (a : α) (as : Env α) : Mem a (.cons a as)\n | tail (a : α) {b : α} (as : Env α) : Mem b as → Mem b (.cons a as)\n\ninstance : Membership α (Env α) where\n mem := Mem\n\ninstance : Coe (Env α) (List α) where\n coe := toList\n\ndelab_rule toList\n | `($_ $env) => `($env)\n\ninstance [ToString α] : ToString <| Env α where\n toString e := e.toList.toString\n\nend Env\n\n-- Env Theorems\ntheorem env_mem_cons_1 [BI PROP] {P : PROP} {Ps : Env PROP} : P ∈ Env.cons P Ps := by\n simp [Membership.mem, Env.Mem.head]\n\ntheorem env_mem_cons_2 [BI PROP] {P Q : PROP} {Ps : Env PROP} : P ∈ Ps → P ∈ Env.cons Q Ps := by\n intro h_Ps\n apply Env.Mem.tail\n exact h_Ps\n\ntheorem env_delete_cons [BI PROP] {P : PROP} {Ps : Env PROP} {i : Nat} {h : i + 1 < (Env.cons P Ps).length} :\n (Env.cons P Ps).delete ⟨i + 1, h⟩ = (Env.cons P <| Ps.delete ⟨i, Nat.lt_of_succ_lt_succ h⟩)\n:= by\n rw' [Env.delete]\n · exact P\n · exact Nat.zero_lt_succ _\n\ntheorem env_get_cons [BI PROP] {P : PROP} {Ps : Env PROP} {i : Nat} {h : i + 1 < (Env.cons P Ps).length} :\n (Env.cons P Ps).get ⟨i + 1, h⟩ = Ps.get ⟨i, Nat.lt_of_succ_lt_succ h⟩\n:= by\n rw' [Env.get]\n · exact Ps\n · exact Nat.zero_lt_succ _\n\ntheorem env_big_op_sep_append [BI PROP] {Γ : Env PROP} {P : PROP} : [∗] (Γ.append P) ⊣⊢ [∗] Γ ∗ P := by\n induction Γ\n <;> simp only [Env.append, Env.toList]\n case nil =>\n simp only [big_op]\n rw' [(left_id : emp ∗ _ ⊣⊢ _)]\n case cons P' _ h_ind =>\n rw' [\n !big_op_sep_cons,\n h_ind,\n ← (assoc : _ ⊣⊢ (P' ∗ _) ∗ P)]\n\ntheorem env_big_op_and_append [BI PROP] {Γ : Env PROP} {P : PROP} : □ [∧] (Γ.append P) ⊣⊢ □ [∧] Γ ∗ □ P := by\n induction Γ\n <;> simp only [Env.append, Env.toList]\n case nil =>\n simp only [big_op]\n rw' [\n intuitionistically_True_emp,\n (left_id : emp ∗ _ ⊣⊢ _)]\n case cons P' _ h_ind =>\n rw' [\n !big_op_and_cons,\n !intuitionistically_and,\n !and_sep_intuitionistically,\n h_ind,\n ← (assoc : _ ⊣⊢ (□ P' ∗ _) ∗ □ P)]\n\ntheorem env_idx_rec [BI PROP] (P : (Γ : Env PROP) → Fin Γ.length → Prop)\n (zero : ∀ {P'} {Γ'} {is_lt}, P (.cons P' Γ') ⟨0, is_lt⟩)\n (succ : ∀ {P'} {Γ'} {val} {is_lt} {is_lt'}, P Γ' ⟨val, is_lt⟩ → P (.cons P' Γ') ⟨Nat.succ val, is_lt'⟩) :\n ∀ Γ i, P Γ i\n:= by\n intro Γ i\n let ⟨val, is_lt⟩ := i\n induction val generalizing Γ\n case zero =>\n cases Γ with\n | nil =>\n contradiction\n | cons P' Γ' =>\n exact zero\n case succ val h_ind =>\n cases Γ with\n | nil =>\n contradiction\n | cons P' Γ' =>\n let is_lt := Nat.lt_of_succ_lt_succ is_lt\n specialize h_ind Γ' ⟨val, is_lt⟩ is_lt\n exact succ h_ind\n\ntheorem env_big_op_sep_delete_get [BI PROP] {Γ : Env PROP} (i : Fin Γ.length) :\n [∗] Γ ⊣⊢ [∗] (Γ.delete i) ∗ (Γ.get i)\n:= by\n induction Γ, i using env_idx_rec\n case zero P' _ _ =>\n rw' [\n Env.delete,\n Env.get,\n big_op_sep_cons,\n (comm : P' ∗ _ ⊣⊢ _)]\n case succ P' _ _ _ _ h_ind =>\n rw' [\n env_delete_cons,\n env_get_cons,\n !big_op_sep_cons,\n ← (assoc : _ ⊣⊢ (P' ∗ _) ∗ _),\n ← h_ind]\n\ntheorem env_big_op_and_delete_get [BI PROP] {Γ : Env PROP} (i : Fin Γ.length) :\n □ [∧] Γ ⊣⊢ □ [∧] (Γ.delete i) ∗ □ (Γ.get i)\n:= by\n induction Γ, i using env_idx_rec\n case zero P' _ _ =>\n rw' [\n Env.delete,\n Env.get,\n big_op_and_cons,\n intuitionistically_and,\n and_sep_intuitionistically,\n (comm : □ P' ∗ _ ⊣⊢ _)]\n case succ P' _ _ _ _ h_ind =>\n rw' [\n env_delete_cons,\n env_get_cons,\n !big_op_and_cons,\n !intuitionistically_and,\n !and_sep_intuitionistically,\n ← (assoc : _ ⊣⊢ (□ P' ∗ _) ∗ _),\n ← h_ind]\n\ntheorem env_delete_length [BI PROP] {Γ : Env PROP} {i : Fin Γ.length} : (Γ.delete i).length = Γ.length - 1 := by\n induction Γ, i using env_idx_rec\n case zero =>\n rw [Env.delete, Env.length, Nat.add_sub_cancel]\n case succ _ _ is_lt _ h_ind =>\n rw [\n env_delete_cons,\n Env.length,\n h_ind,\n Env.length,\n Nat.add_sub_cancel,\n Nat.sub_add_cancel ?_]\n · apply Nat.succ_le_of_lt\n exact Nat.zero_lt_of_lt is_lt\n\ntheorem env_delete_idx_length [BI PROP] {Γ : Env PROP} {i : Fin Γ.length} : i ≤ (Γ.delete i).length := by\n let ⟨val, is_lt⟩ := i\n rw [env_delete_length]\n apply Nat.le_of_lt_succ\n rw [Nat.succ_eq_add_one, Nat.sub_add_cancel ?_]\n exact is_lt\n · apply Nat.succ_le_of_lt\n exact Nat.zero_lt_of_lt is_lt\n\ntheorem env_delete_idx_length_of_lt [BI PROP] {Γ : Env PROP} {i : Fin Γ.length} {j : Nat} : j < i → j < (Γ.delete i).length := by\n intro h\n apply Nat.lt_of_lt_of_le h ?_\n exact env_delete_idx_length\n\ntheorem env_delete_idx_pred_length [BI PROP] {Γ : Env PROP} (i : Fin Γ.length) (h : 0 < i.val) : ∀ {j}, (i - 1) < (Γ.delete j).length := by\n intro j\n let ⟨val, is_lt⟩ := i\n rw [env_delete_length]\n apply Nat.lt_sub_of_add_lt\n rw [Nat.sub_add_cancel]\n exact is_lt\n · apply Nat.succ_le_of_lt\n exact h\n\ntheorem env_split_cons_false [BI PROP] {P : PROP} {Ps : Env PROP} {bs : List Bool} {Γ₁ Γ₂ : Env PROP} {h : (false :: bs).length = (Env.cons P Ps).length} :\n (Γ₁, Γ₂) = (Env.cons P Ps).split (false :: bs) h →\n ∃ (Γ₂' : Env PROP), Γ₂ = Env.cons P Γ₂' ∧\n ∃ (h' : bs.length = Ps.length), (Γ₁, Γ₂') = Ps.split bs h'\n:= by\n intro h_split\n simp only [Env.split] at h_split\n cases h_split\n apply Exists.intro _\n apply And.intro rfl ?_\n apply Exists.intro (Env.length_cons_list_cons h)\n simp\n\ntheorem env_split_cons_true [BI PROP] {P : PROP} {Ps : Env PROP} {bs : List Bool} {Γ₁ Γ₂ : Env PROP} {h : (true :: bs).length = (Env.cons P Ps).length} :\n (Γ₁, Γ₂) = (Env.cons P Ps).split (true :: bs) h →\n ∃ (Γ₁' : Env PROP), Γ₁ = Env.cons P Γ₁' ∧\n ∃ (h' : bs.length = Ps.length), (Γ₁', Γ₂) = Ps.split bs h'\n:= by\n intro h_split\n simp only [Env.split] at h_split\n cases h_split\n apply Exists.intro _\n apply And.intro rfl ?_\n apply Exists.intro (Env.length_cons_list_cons h)\n simp\n\ntheorem env_big_op_sep_split [BI PROP] {Γ Γ₁ Γ₂ : Env PROP} {mask : List Bool} {h : mask.length = Γ.length} :\n (Γ₁, Γ₂) = Γ.split mask h →\n ([∗] Γ : PROP) ⊢ [∗] Γ₁ ∗ [∗] Γ₂\n:= by\n intro h_split\n induction Γ generalizing mask Γ₁ Γ₂\n case nil =>\n cases mask\n case nil =>\n simp only [Env.split] at h_split\n cases h_split\n simp only [big_op]\n rw' [(left_id : emp ∗ _ ⊣⊢ _)]\n case cons =>\n simp only [List.length, Env.length] at h\n contradiction\n case cons P Ps h_ind =>\n cases mask\n case nil =>\n simp only [List.length, Env.length] at h\n contradiction\n case cons b bs =>\n cases b\n case false =>\n let ⟨_, h_split_P, _, h_split_Ps⟩ := env_split_cons_false h_split\n rw' [h_split_P]\n simp only [Env.toList]\n rw' [\n !big_op_sep_cons,\n (assoc : _ ∗ (P ∗ _) ⊣⊢ _),\n (comm : _ ∗ P ⊣⊢ _),\n ← (assoc : _ ⊣⊢ (P ∗ _) ∗ _),\n h_ind h_split_Ps]\n case true =>\n let ⟨_, h_split_P, _, h_split_Ps⟩ := env_split_cons_true h_split\n rw' [h_split_P]\n simp only [Env.toList]\n rw' [\n !big_op_sep_cons,\n ← (assoc : _ ⊣⊢ (P ∗ _) ∗ _),\n h_ind h_split_Ps]\n\n\n/-- Combined separation logic context with two `Env` objects for the intuitionistic and\nspatial context. -/\nstructure Envs (PROP : Type) [BI PROP] where\n intuitionistic : Env PROP\n spatial : Env PROP\n\n/-- Embedding of a separation logic context in form of an `Envs` object in a separation\nlogic proposition. -/\ndef of_envs [BI PROP] : Envs PROP → PROP\n | ⟨Γₚ, Γₛ⟩ => `[iprop| □ [∧] Γₚ ∗ [∗] Γₛ]\n\n/-- Embedding of a separation logic context in form of an `Envs` object together with a separation\nlogic proposition in one separation logic proposition. This embedding is used in the Iris Proof\nMode where the embedded proposition is the goal of the proof. -/\ndef envs_entails [BI PROP] (Δ : Envs PROP) (Q : PROP) : Prop :=\n of_envs Δ ⊢ Q\n\n/-- Types of hypotheses. -/\ninductive HypothesisType\n | intuitionistic | spatial\n deriving BEq\n\n/-- Unbounded index of a hypothesis in a combined separation logic context.\n\nThis datatype is used for convenience on the meta level only - environment operations and theorems\nuse the bounded dataype `EnvsIndex` instead. -/\nstructure HypothesisIndex where\n type : HypothesisType\n index : Nat\n length : Nat\n deriving BEq\n\n/-- Bounded index of a hypothesis in a combined separation logic context.\n\nThe lengths of the individual contexts are used as type arguments instead of an `Envs` object to\nallow for an easier syntax generation on the meta level. -/\ninductive EnvsIndex (lₚ lₛ : Nat)\n | p : Fin lₚ → EnvsIndex lₚ lₛ\n | s : Fin lₛ → EnvsIndex lₚ lₛ\n\n/-- Return the hypothesis type of the hypothesis referenced by the given index. -/\n@[reducible]\ndef EnvsIndex.type : EnvsIndex lₚ lₛ → HypothesisType\n | .p _ => .intuitionistic\n | .s _ => .spatial\n\n/-- Return the unbounded index value of the given index. -/\n@[reducible]\ndef EnvsIndex.val : EnvsIndex lₚ lₛ → Nat\n | .p ⟨val, _⟩ => val\n | .s ⟨val, _⟩ => val\n\n/-- `EnvsIndex` type for the given `Envs` object. -/\nabbrev EnvsIndex.of [BI PROP] (Δ : Envs PROP) := EnvsIndex Δ.intuitionistic.length Δ.spatial.length\n\n/-- Generate the syntax of a (bounded) `EnvsIndex` object based on an unbounded `HypothesisIndex`.\nThe proofs of the index bounds are generated using the tactic `decide`. -/\ndef HypothesisIndex.quoteAsEnvsIndex : HypothesisIndex → MetaM (TSyntax `term)\n | ⟨.intuitionistic, index, length⟩ =>\n ``(EnvsIndex.p ⟨$(quote index), by show $(quote index) < $(quote length) ; decide⟩)\n | ⟨.spatial, index, length⟩ =>\n ``(EnvsIndex.s ⟨$(quote index), by show $(quote index) < $(quote length) ; decide⟩)\n\n-- Envs Operations\nnamespace Envs\n\n/-- Append a hypothesis to the end of one of the separation logic contexts. The boolean flag\nindicates whether the hypothesis should be appended to the intuitionistic (`true`) or spatial\n(`false`) context. -/\n@[reducible]\ndef append [BI PROP] : Bool → PROP → Envs PROP → Envs PROP\n | true, P, ⟨Γₚ, Γₛ⟩ => ⟨Γₚ.append P, Γₛ⟩\n | false, P, ⟨Γₚ, Γₛ⟩ => ⟨Γₚ, Γₛ.append P⟩\n\n/-- Delete the hypothesis at the given (combined) index. The boolean flag indicates whether the\nhypothesis should be deleted even if it is part of the intuitionistic context. -/\n@[reducible]\ndef delete [BI PROP] : Bool → (Δ : Envs PROP) → EnvsIndex.of Δ → Envs PROP\n | true , ⟨Γₚ, Γₛ⟩, .p i => ⟨Γₚ.delete i, Γₛ⟩\n | false, ⟨Γₚ, Γₛ⟩, .p _ => ⟨Γₚ, Γₛ⟩\n | _ , ⟨Γₚ, Γₛ⟩, .s i => ⟨Γₚ, Γₛ.delete i⟩\n\n/-- Return the hypothesis at the given index. -/\n@[reducible]\ndef lookup [BI PROP] : (Δ : Envs PROP) → EnvsIndex.of Δ → Bool × PROP\n | ⟨Γₚ, _⟩, .p i => (true, Γₚ.get i)\n | ⟨_, Γₛ⟩, .s i => (false, Γₛ.get i)\n\n/-- Replace the hypothesis at index `i` with the hypothesis `P`. The boolean flag `p` indicates\nwhether the new hypothesis should be placed in the intuitionistic (`true`) or spatial (`false`)\ncontext. If the boolean flag `rp` is set, the original hypothesis is removed even if it is part of\nthe intuitionistic context. If it is not set, the original hypothesis is kept. The new hypothesis\nis added in both cases. -/\n@[reducible]\ndef replace [BI PROP] (Δ : Envs PROP) (rp : Bool) (i : EnvsIndex.of Δ) (p : Bool) (P : PROP) : Envs PROP :=\n Δ.delete rp i |>.append p P\n\n/-- Split the spatial context into two disjoint parts. See `Env.split` for details. -/\n@[reducible]\ndef split [BI PROP] : (Δ : Envs PROP) → (mask : List Bool) → (mask.length = Δ.spatial.length) → Envs PROP × Envs PROP\n | ⟨Γₚ, Γₛ⟩, mask, h =>\n let ⟨Γₛ₁, Γₛ₂⟩ := Γₛ.split mask h\n (⟨Γₚ, Γₛ₁⟩, ⟨Γₚ, Γₛ₂⟩)\n\n/-- Update an index `j` of `Δ` to reference the same hypothesis in `Δ.delete rp i`, i.e. after the\nhypothesis at index `i` has been deleted. The indices `i` and `j` must reference\ndifferent hypotheses. -/\n@[reducible]\ndef updateIndexAfterDelete [BI PROP] (Δ : Envs PROP) : (rp : Bool) → (i : EnvsIndex.of Δ) → (j : EnvsIndex.of Δ) → (i.type = j.type → i.val ≠ j.val) → EnvsIndex.of (Δ.delete rp i)\n | rp, .p i, .s ⟨val, is_lt⟩, _ =>\n .s ⟨val, by cases rp <;> simp [is_lt]⟩\n | _, .s i, .p ⟨val, is_lt⟩, _ =>\n .p ⟨val, by simp [delete, is_lt]⟩\n | false, .p _, .p ⟨val, is_lt⟩, _ =>\n .p ⟨val, by simp [delete, is_lt]⟩\n | true, .p ⟨val_d, is_lt_d⟩, .p ⟨val, is_lt⟩, h_ne =>\n if h_lt : val < val_d then\n EnvsIndex.p ⟨val, env_delete_idx_length_of_lt h_lt⟩\n else if h_gt : val_d < val then\n EnvsIndex.p ⟨val - 1, env_delete_idx_pred_length ⟨val, is_lt⟩ (Nat.zero_lt_of_lt h_gt)⟩\n else by\n let h_ne := h_ne (by simp)\n let h_eq := Nat.eq_of_not_lt_not_lt h_gt h_lt\n contradiction\n | rp, .s ⟨val_d, is_lt_d⟩, .s ⟨val, is_lt⟩, h_ne =>\n if h_lt : val < val_d then\n EnvsIndex.s ⟨val, by simp only [delete] ; exact env_delete_idx_length_of_lt h_lt⟩\n else if h_gt : val_d < val then\n EnvsIndex.s ⟨val - 1, by simp only [delete] ; exact env_delete_idx_pred_length ⟨val, is_lt⟩ (Nat.zero_lt_of_lt h_gt)⟩\n else by\n let h_ne := h_ne (by simp)\n let h_eq := Nat.eq_of_not_lt_not_lt h_gt h_lt\n contradiction\n\nend Envs\n\n-- Envs Theorems\ntheorem envs_append_sound [BI PROP] {Δ : Envs PROP} (p : Bool) (Q : PROP) :\n of_envs Δ ⊢ □?p Q -∗ of_envs (Δ.append p Q)\n:= by\n apply wand_intro_l ?_\n cases p\n <;> simp only [bi_intuitionistically_if, ite_true, ite_false, of_envs]\n case false =>\n rw' [\n env_big_op_sep_append,\n (assoc : _ ∗ (_ ∗ Q) ⊣⊢ _),\n (comm : _ ∗ Q ⊣⊢ _)]\n case true =>\n rw' [\n env_big_op_and_append,\n (comm : _ ∗ □ Q ⊣⊢ _),\n ← (assoc : _ ⊣⊢ (□ Q ∗ _) ∗ _)]\n\ntheorem envs_lookup_delete_sound [BI PROP] {Δ : Envs PROP} {i : EnvsIndex.of Δ} {p : Bool} {P : PROP} (rp : Bool) :\n Δ.lookup i = (p, P) →\n of_envs Δ ⊢ □?p P ∗ of_envs (Δ.delete rp i)\n:= by\n cases i\n all_goals\n simp only [Envs.lookup]\n intro h_lookup\n cases h_lookup\n simp only [Envs.delete, of_envs, bi_intuitionistically_if, ite_true, ite_false]\n case s i =>\n rw' [\n (comm : Δ.spatial.get i ∗ _ ⊣⊢ _),\n ← (assoc : _ ⊣⊢ _ ∗ _),\n ← env_big_op_sep_delete_get]\n case p i =>\n cases rp\n <;> simp only\n case true =>\n rw' [\n (assoc : _ ∗ _ ⊣⊢ _),\n (comm : □ Δ.intuitionistic.get i ∗ _ ⊣⊢ _),\n ← env_big_op_and_delete_get i]\n case false =>\n rw' [\n (assoc : _ ∗ _ ⊣⊢ _),\n (comm : □ Δ.intuitionistic.get i ∗ _ ⊣⊢ _),\n env_big_op_and_delete_get i,\n ← (assoc : _ ⊣⊢ (_ ∗ _) ∗ □ Δ.intuitionistic.get i),\n ← intuitionistically_sep_dup]\n\ntheorem envs_lookup_replace_sound [BI PROP] {Δ : Envs PROP} {i : EnvsIndex.of Δ} {p : Bool} {P : PROP} (rp : Bool) (q : Bool) (Q : PROP) :\n Δ.lookup i = (p, P) →\n of_envs Δ ⊢ □?p P ∗ (□?q Q -∗ of_envs (Δ.replace rp i q Q))\n:= by\n intro h_lookup\n simp only [Envs.replace]\n rw' [\n ← envs_append_sound q Q,\n ← envs_lookup_delete_sound rp h_lookup]\n\ntheorem envs_split_env_spatial_split [BI PROP] {Δ Δ₁ Δ₂ : Envs PROP} {mask : List Bool} {h : mask.length = Δ.spatial.length} :\n Envs.split Δ mask h = (Δ₁, Δ₂) →\n Δ₁.intuitionistic = Δ.intuitionistic ∧\n Δ₂.intuitionistic = Δ.intuitionistic ∧\n (Δ₁.spatial, Δ₂.spatial) = Env.split Δ.spatial mask h\n:= by\n simp only [Envs.split]\n intro h_split\n cases h_split\n <;> simp\n\ntheorem envs_split_sound [BI PROP] {Δ Δ₁ Δ₂ : Envs PROP} {mask : List Bool} {h : mask.length = Δ.spatial.length} :\n Δ.split mask h = (Δ₁, Δ₂) →\n of_envs Δ ⊢ of_envs Δ₁ ∗ of_envs Δ₂\n:= by\n intro h_split_Δ\n let ⟨h_split_Γₚ₁, h_split_Γₚ₂, h_split_Γₛ⟩ := envs_split_env_spatial_split h_split_Δ\n simp only [of_envs]\n rw' [\n h_split_Γₚ₁,\n h_split_Γₚ₂,\n env_big_op_sep_split h_split_Γₛ,\n (assoc : _ ∗ (□ _ ∗ _) ⊣⊢ _),\n (comm : _ ∗ □ _ ⊣⊢ _),\n (assoc : □ _ ∗ (□ _ ∗ _) ⊣⊢ _),\n ← intuitionistically_sep_dup,\n ← (assoc : _ ⊣⊢ (_ ∗ _) ∗ _)]\n\ntheorem envs_spatial_is_empty_intuitionistically [BI PROP] {Δ : Envs PROP} :\n Δ.spatial.isEmpty = true →\n of_envs Δ ⊢ □ of_envs Δ\n:= by\n simp only [Env.isEmpty, of_envs]\n cases Δ.spatial\n <;> simp [big_op]\n rw' [\n (right_id : _ ∗ emp ⊣⊢ _),\n intuitionistically_idemp]\n\n-- AffineEnv\nclass AffineEnv [BI PROP] (Γ : Env PROP) where\n affineEnv : ∀ P, P ∈ Γ → Affine P\nexport AffineEnv (affineEnv)\n\ninstance affineEnvNil [BI PROP] :\n AffineEnv (PROP := PROP) .nil\nwhere\n affineEnv := by\n intro _ h\n cases h\n\ninstance affineEnvConcat [BI PROP] (P : PROP) (Γ : Env PROP) :\n [Affine P] →\n [AffineEnv Γ] →\n AffineEnv (.cons P Γ)\nwhere\n affineEnv := by\n intro P h\n cases h\n case head =>\n exact ⟨affine⟩\n case tail h =>\n exact affineEnv P h\n\ninstance (priority := default + 10) affineEnvBi (Γ : Env PROP) :\n [BIAffine PROP] →\n AffineEnv Γ\nwhere\n affineEnv := by\n intro P _\n exact BIAffine.affine P\n\nscoped instance affineEnvSpatial [BI PROP] (Γ : Env PROP)\n [inst : AffineEnv Γ] :\n Affine (`[iprop| [∗] Γ] : PROP)\nwhere\n affine := by\n induction Γ generalizing inst\n case nil =>\n rw' [big_op_sep_nil]\n case cons P Ps h_ind =>\n have : AffineEnv Ps := ⟨by\n intro P h_Ps\n exact inst.affineEnv P (env_mem_cons_2 h_Ps)⟩\n have : Affine P := inst.affineEnv P env_mem_cons_1\n rw' [big_op_sep_cons, h_ind, affine]\n\nend Iris.Proofmode\n", "meta": {"author": "larsk21", "repo": "iris-lean", "sha": "730e644d0ffaad78aac76e2e5f2cd8af0f1d2310", "save_path": "github-repos/lean/larsk21-iris-lean", "path": "github-repos/lean/larsk21-iris-lean/iris-lean-730e644d0ffaad78aac76e2e5f2cd8af0f1d2310/src/Iris/Proofmode/Environments.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45713671682749474, "lm_q2_score": 0.08632347893683115, "lm_q1q2_score": 0.039461631746310386}} {"text": "import .love05_inductive_predicates_demo\n\n\n/-! # LoVe Demo 7: Metaprogramming\n\nUsers can extend Lean with custom tactics and tools. This kind of\nprogramming—programming the prover—is called metaprogramming.\n\nLean's metaprogramming framework uses mostly the same notions and syntax as\nLean's input language itself. Abstract syntax trees __reflect__ internal data\nstructures, e.g., for expressions (terms). The prover's C++ internals are\nexposed through Lean interfaces, which we can use for\n\n* accessing the current context and goal;\n* unifying expressions;\n* querying and modifying the environment;\n* setting attributes.\n\nMost of Lean's predefined tactics are implemented in Lean (and not in C++).\n\nExample applications:\n\n* proof goal transformations;\n* heuristic proof search;\n* decision procedures;\n* definition generators;\n* advisor tools;\n* exporters;\n* ad hoc automation.\n\nAdvantages of Lean's metaprogramming framework:\n\n* Users do not need to learn another programming language to write\n metaprograms; they can work with the same constructs and notation used to\n define ordinary objects in the prover's library.\n\n* Everything in that library is available for metaprogramming purposes.\n\n* Metaprograms can be written and debugged in the same interactive environment,\n encouraging a style where formal libraries and supporting automation are\n developed at the same time. -/\n\n\nset_option pp.beta true\nset_option pp.generalized_field_notation false\n\nnamespace LoVe\n\n\n/-! ## Tactics and Tactic Combinators\n\nWhen programming our own tactics, we often need to repeat some actions on\nseveral goals, or to recover if a tactic fails. Tactic combinators help in such\ncase.\n\n`repeat` applies its argument repeatedly on all (sub…sub)goals until it cannot\nbe applied any further. -/\n\nlemma repeat_example :\n even 4 ∧ even 7 ∧ even 3 ∧ even 0 :=\nbegin\n repeat { apply and.intro },\n repeat { apply even.add_two },\n repeat { sorry }\nend\n\n/-! The \"orelse\" combinator `<|>` tries its first argument and applies its\nsecond argument in case of failure. -/\n\nlemma repeat_orelse_example :\n even 4 ∧ even 7 ∧ even 3 ∧ even 0 :=\nbegin\n repeat { apply and.intro },\n repeat {\n apply even.add_two\n <|> apply even.zero },\n repeat { sorry }\nend\n\n/-! `iterate` works repeatedly on the first goal until it fails; then it\nstops. -/\n\nlemma iterate_orelse_example :\n even 4 ∧ even 7 ∧ even 3 ∧ even 0 :=\nbegin\n repeat { apply and.intro },\n iterate {\n apply even.add_two\n <|> apply even.zero },\n repeat { sorry }\nend\n\n/-! `all_goals` applies its argument exactly once to each goal. It succeeds only\nif the argument succeeds on **all** goals. -/\n\nlemma all_goals_example :\n even 4 ∧ even 7 ∧ even 3 ∧ even 0 :=\nbegin\n repeat { apply and.intro },\n all_goals { apply even.add_two }, -- fails\n repeat { sorry }\nend\n\n/-! `try` transforms its argument into a tactic that never fails. -/\n\nlemma all_goals_try_example :\n even 4 ∧ even 7 ∧ even 3 ∧ even 0 :=\nbegin\n repeat { apply and.intro },\n all_goals { try { apply even.add_two } },\n repeat { sorry }\nend\n\n/-! `any_goals` applies its argument exactly once to each goal. It succeeds\nif the argument succeeds on **any** goal. -/\n\nlemma any_goals_example :\n even 4 ∧ even 7 ∧ even 3 ∧ even 0 :=\nbegin\n repeat { apply and.intro },\n any_goals { apply even.add_two },\n repeat { sorry }\nend\n\n/-! `solve1` transforms its argument into an all-or-nothing tactic. If the\nargument does not prove the goal, `solve1` fails. -/\n\nlemma any_goals_solve1_repeat_orelse_example :\n even 4 ∧ even 7 ∧ even 3 ∧ even 0 :=\nbegin\n repeat { apply and.intro },\n any_goals { solve1 { repeat {\n apply even.add_two\n <|> apply even.zero } } },\n repeat { sorry }\nend\n\n/-! The combinators `repeat`, `iterate`, `all_goals`, and `any_goals` can easily\nlead to infinite looping: -/\n\n/-\nlemma repeat_not_example :\n ¬ even 1 :=\nbegin\n repeat { apply not.intro },\n sorry\nend\n-/\n\n/-! Let us start with the actual metaprogramming, by coding a custom tactic. The\ntactic embodies the behavior we hardcoded in the `solve1` example above: -/\n\nmeta def intro_and_even : tactic unit :=\ndo\n tactic.repeat (tactic.applyc ``and.intro),\n tactic.any_goals (tactic.solve1 (tactic.repeat\n (tactic.applyc ``even.add_two\n <|> tactic.applyc ``even.zero))),\n pure ()\n\n/-! The `meta` keyword makes it possible for the function to call other\nmetafunctions. The `do` keyword enters a monad, and the `<|>` operator is the\n\"orelse\" operator of alternative monads. At the end, we return `()`, of type\n`unit`, to ensure the metaprogram has the desired type.\n\nAny executable Lean definition can be used as a metaprogram. In addition, we can\nput `meta` in front of a definition to indicate that is a metadefinition. Such\ndefinitions need not terminate but cannot be used in non-`meta` contexts.\n\nLet us apply our custom tactic: -/\n\nlemma any_goals_solve1_repeat_orelse_example₂ :\n even 4 ∧ even 7 ∧ even 3 ∧ even 0 :=\nbegin\n intro_and_even,\n repeat { sorry }\nend\n\n\n/-! ## The Metaprogramming Monad\n\nTactics have access to\n\n* the list of **goals** as metavariables (each metavariables has a type and a\n local context (hypothesis); they can optionally be instantiated);\n\n* the **elaborator** (to elaborate expressions and compute their type);\n\n* the **environment**, containing all declarations and inductive types;\n\n* the **attributes** (e.g., the list of `@[simp]` rules).\n\nThe tactic monad is an alternative monad, with `fail` and `<|>`. Tactics can\nalso produce trace messages. -/\n\nlemma even_14 :\n even 14 :=\nby do\n tactic.trace \"Proving evenness …\",\n intro_and_even\n\nmeta def hello_then_intro_and_even : tactic unit :=\ndo\n tactic.trace \"Proving evenness …\",\n intro_and_even\n\nlemma even_16 :\n even 16 :=\nby hello_then_intro_and_even\n\nrun_cmd tactic.trace \"Hello, Metaworld!\"\n\nmeta def trace_goals : tactic unit :=\ndo\n tactic.trace \"local context:\",\n ctx ← tactic.local_context,\n tactic.trace ctx,\n tactic.trace \"target:\",\n P ← tactic.target,\n tactic.trace P,\n tactic.trace \"all missing proofs:\",\n Hs ← tactic.get_goals,\n tactic.trace Hs,\n τs ← list.mmap tactic.infer_type Hs,\n tactic.trace τs\n\nlemma even_18_and_even_20 (α : Type) (a : α) :\n even 18 ∧ even 20 :=\nby do\n tactic.applyc ``and.intro,\n trace_goals,\n intro_and_even\n\nlemma triv_imp (a : Prop) (h : a) :\n a :=\nby do\n h ← tactic.get_local `h,\n tactic.trace \"h:\",\n tactic.trace h,\n tactic.trace \"raw h:\",\n tactic.trace (expr.to_raw_fmt h),\n tactic.trace \"type of h:\",\n τ ← tactic.infer_type h,\n tactic.trace τ,\n tactic.trace \"type of type of h:\",\n υ ← tactic.infer_type τ,\n tactic.trace υ,\n tactic.apply h\n\nmeta def exact_list : list expr → tactic unit\n| [] := tactic.fail \"no matching expression found\"\n| (h :: hs) :=\n do {\n tactic.trace \"trying\",\n tactic.trace h,\n tactic.exact h }\n <|> exact_list hs\n\nmeta def hypothesis : tactic unit :=\ndo\n hs ← tactic.local_context,\n exact_list hs\n\nlemma app_of_app {α : Type} {p : α → Prop} {a : α}\n (h : p a) :\n p a :=\nby hypothesis\n\n\n/-! ## Names, Expressions, Declarations, and Environments\n\nThe metaprogramming framework is articulated around five main types:\n\n* `tactic` manages the proof state, the global context, and more;\n\n* `name` represents a structured name (e.g., `x`, `even.add_two`);\n\n* `expr` represents an expression (a term) as an abstract syntax tree;\n\n* `declaration` represents a constant declaration, a definition, an axiom, or a\n lemma;\n\n* `environment` stores all the declarations and notations that make up the\n global context. -/\n\n#print expr\n\n#check expr tt -- elaborated expressions\n#check expr ff -- unelaborated expressions (pre-expressions)\n\n#print name\n\n#check (expr.const `ℕ [] : expr)\n#check expr.sort level.zero -- Sort 0, i.e., Prop\n#check expr.sort (level.succ level.zero)\n -- Sort 1, i.e., Type\n#check expr.var 0 -- bound variable with De Bruijn index 0\n#check (expr.local_const `uniq_name `pp_name binder_info.default\n `(ℕ) : expr)\n#check (expr.mvar `uniq_name `pp_name `(ℕ) : expr)\n#check (expr.pi `pp_name binder_info.default `(ℕ)\n (expr.sort level.zero) : expr)\n#check (expr.lam `pp_name binder_info.default `(ℕ)\n (expr.var 0) : expr)\n#check expr.elet\n#check expr.macro\n\n/-! We can create literal expressions conveniently using backticks and\nparentheses:\n\n* Expressions with a single backtick must be fully elaborated.\n\n* Expressions with two backticks are __pre-expressions__: They may contain some\n holes to be filled in later, based on some context.\n\n* Expressions with three backticks are pre-expressions without name checking. -/\n\nrun_cmd do\n let e : expr := `(list.map (λn : ℕ, n + 1) [1, 2, 3]),\n tactic.trace e\n\nrun_cmd do\n let e : expr := `(list.map _ [1, 2, 3]), -- fails\n tactic.trace e\n\nrun_cmd do\n let e₁ : pexpr := ``(list.map (λn, n + 1) [1, 2, 3]),\n let e₂ : pexpr := ``(list.map _ [1, 2, 3]),\n tactic.trace e₁,\n tactic.trace e₂\n\nrun_cmd do\n let e : pexpr := ```(seattle.washington),\n tactic.trace e\n\n/-! We can also create literal names with backticks:\n\n* Names with a single backtick, `n, are not checked for existence.\n\n* Names with two backticks, ``n, are resolved and checked. -/\n\nrun_cmd tactic.trace `and.intro\nrun_cmd tactic.trace `intro_and_even\nrun_cmd tactic.trace `seattle.washington\n\nrun_cmd tactic.trace ``and.intro\nrun_cmd tactic.trace ``intro_and_even\nrun_cmd tactic.trace ``seattle.washington -- fails\n\n/-! __Antiquotations__ embed an existing expression in a larger expression. They\nare announced by the prefix `%%` followed by a name from the current context.\nAntiquotations are available with one, two, and three backticks: -/\n\nrun_cmd do\n let x : expr := `(2 : ℕ),\n let e : expr := `(%%x + 1),\n tactic.trace e\n\nrun_cmd do\n let x : expr := `(@id ℕ),\n let e : pexpr := ``(list.map %%x),\n tactic.trace e\n\nrun_cmd do\n let x : expr := `(@id ℕ),\n let e : pexpr := ```(a _ %%x),\n tactic.trace e\n\nlemma one_add_two_eq_three :\n 1 + 2 = 3 :=\nby do\n `(%%a + %%b = %%c) ← tactic.target,\n tactic.trace a,\n tactic.trace b,\n tactic.trace c,\n `(@eq %%α %%l %%r) ← tactic.target,\n tactic.trace α,\n tactic.trace l,\n tactic.trace r,\n tactic.exact `(refl _ : 3 = 3)\n\n#print declaration\n\n/-! The `environment` type is presented as an abstract type, equipped with some\noperations to query and modify it. The `environment.fold` metafunction iterates\nover all declarations making up the environment. -/\n\nrun_cmd do\n env ← tactic.get_env,\n tactic.trace (environment.fold env 0 (λdecl n, n + 1))\n\n\n/-! ## First Example: A Conjuction-Destructing Tactic\n\nWe define a `destruct_and` tactic that automates the elimination of `∧` in\npremises, automating proofs such as these: -/\n\nlemma abcd_a (a b c d : Prop) (h : a ∧ (b ∧ c) ∧ d) :\n a :=\nand.elim_left h\n\nlemma abcd_b (a b c d : Prop) (h : a ∧ (b ∧ c) ∧ d) :\n b :=\nand.elim_left (and.elim_left (and.elim_right h))\n\nlemma abcd_bc (a b c d : Prop) (h : a ∧ (b ∧ c) ∧ d) :\n b ∧ c :=\nand.elim_left (and.elim_right h)\n\n/-! Our tactic relies on a helper metafunction, which takes as argument the\nhypothesis `h` to use as an expression rather than as a name: -/\n\nmeta def destruct_and_helper : expr → tactic unit\n| h :=\n do\n t ← tactic.infer_type h,\n match t with\n | `(%%a ∧ %%b) :=\n tactic.exact h\n <|>\n do {\n ha ← tactic.to_expr ``(and.elim_left %%h),\n destruct_and_helper ha }\n <|>\n do {\n hb ← tactic.to_expr ``(and.elim_right %%h),\n destruct_and_helper hb }\n | _ := tactic.exact h\n end\n\nmeta def destruct_and (nam : name) : tactic unit :=\ndo\n h ← tactic.get_local nam,\n destruct_and_helper h\n\n/-! Let us check that our tactic works: -/\n\nlemma abc_a (a b c : Prop) (h : a ∧ b ∧ c) :\n a :=\nby destruct_and `h\n\nlemma abc_b (a b c : Prop) (h : a ∧ b ∧ c) :\n b :=\nby destruct_and `h\n\nlemma abc_bc (a b c : Prop) (h : a ∧ b ∧ c) :\n b ∧ c :=\nby destruct_and `h\n\nlemma abc_ac (a b c : Prop) (h : a ∧ b ∧ c) :\n a ∧ c :=\nby destruct_and `h -- fails\n\n\n/-! ## Second Example: A Provability Advisor\n\nNext, we implement a `prove_direct` tool that traverses all lemmas in the\ndatabase and checks whether one of them can be used to prove the current goal. A\nsimilar tactic is available in `mathlib` under the name `library_search`. -/\n\nmeta def is_theorem : declaration → bool\n| (declaration.defn _ _ _ _ _ _) := ff\n| (declaration.thm _ _ _ _) := tt\n| (declaration.cnst _ _ _ _) := ff\n| (declaration.ax _ _ _) := tt\n\nmeta def get_all_theorems : tactic (list name) :=\ndo\n env ← tactic.get_env,\n pure (environment.fold env [] (λdecl nams,\n if is_theorem decl then declaration.to_name decl :: nams\n else nams))\n\nmeta def prove_with_name (nam : name) : tactic unit :=\ndo\n tactic.applyc nam\n ({ md := tactic.transparency.reducible, unify := ff }\n : tactic.apply_cfg),\n tactic.all_goals tactic.assumption,\n pure ()\n\nmeta def prove_direct : tactic unit :=\ndo\n nams ← get_all_theorems,\n list.mfirst (λnam,\n do\n prove_with_name nam,\n tactic.trace (\"directly proved by \" ++ to_string nam))\n nams\n\nlemma nat.eq_symm (x y : ℕ) (h : x = y) :\n y = x :=\nby prove_direct\n\nlemma nat.eq_symm₂ (x y : ℕ) (h : x = y) :\n y = x :=\nby library_search\n\nlemma list.reverse_twice (xs : list ℕ) :\n list.reverse (list.reverse xs) = xs :=\nby prove_direct\n\nlemma list.reverse_twice_symm (xs : list ℕ) :\n xs = list.reverse (list.reverse xs) :=\nby prove_direct -- fails\n\n/-! As a small refinement, we propose a version of `prove_direct` that also\nlooks for equalities stated in symmetric form. -/\n\nmeta def prove_direct_symm : tactic unit :=\nprove_direct\n<|>\ndo {\n tactic.applyc `eq.symm,\n prove_direct }\n\nlemma list.reverse_twice₂ (xs : list ℕ) :\n list.reverse (list.reverse xs) = xs :=\nby prove_direct_symm\n\nlemma list.reverse_twice_symm₂ (xs : list ℕ) :\n xs = list.reverse (list.reverse xs) :=\nby prove_direct_symm\n\n\n/-! ## A Look at Two Predefined Tactics\n\nQuite a few of Lean's predefined tactics are implemented as metaprograms and\nnot in C++. We can find these definitions by clicking the name of a construct\nin Visual Studio Code while holding the control or command key. -/\n\n#check tactic.intro\n#check tactic.assumption\n\nend LoVe\n", "meta": {"author": "blanchette", "repo": "logical_verification_2021", "sha": "23b469c79afd482fa66da82e4726a317e3a7b5d5", "save_path": "github-repos/lean/blanchette-logical_verification_2021", "path": "github-repos/lean/blanchette-logical_verification_2021/logical_verification_2021-23b469c79afd482fa66da82e4726a317e3a7b5d5/lean/love07_metaprogramming_demo.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3174262655876759, "lm_q2_score": 0.12421300511003351, "lm_q1q2_score": 0.03942847034950084}} {"text": "/-\nCopyright (c) 2018 Simon Hudon. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthor: Simon Hudon\n\nLemmas about traversing collections.\n\nInspired by:\n\n The Essence of the Iterator Pattern\n Jeremy Gibbons and Bruno César dos Santos Oliveira\n In Journal of Functional Programming. Vol. 19. No. 3&4. Pages 377−402. 2009.\n \n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.default\nimport Mathlib.control.traversable.basic\nimport Mathlib.control.applicative\nimport Mathlib.PostPort\n\nuniverses u \n\nnamespace Mathlib\n\nnamespace traversable\n\n\n/-- The natural applicative transformation from the identity functor\nto `F`, defined by `pure : Π {α}, α → F α`. -/\ndef pure_transformation (F : Type u → Type u) [Applicative F] [is_lawful_applicative F] : applicative_transformation id F :=\n applicative_transformation.mk pure sorry sorry\n\n@[simp] theorem pure_transformation_apply (F : Type u → Type u) [Applicative F] [is_lawful_applicative F] {α : Type u} (x : id α) : coe_fn (pure_transformation F) α x = pure x :=\n rfl\n\ntheorem map_eq_traverse_id {t : Type u → Type u} [traversable t] [is_lawful_traversable t] {β : Type u} {γ : Type u} (f : β → γ) : Functor.map f = traverse (id.mk ∘ f) :=\n funext fun (y : t β) => Eq.symm (is_lawful_traversable.traverse_eq_map_id f y)\n\ntheorem map_traverse {t : Type u → Type u} [traversable t] [is_lawful_traversable t] {F : Type u → Type u} [Applicative F] [is_lawful_applicative F] {α : Type u} {β : Type u} {γ : Type u} (g : α → F β) (f : β → γ) (x : t α) : Functor.map f <$> traverse g x = traverse (Functor.map f ∘ g) x := sorry\n\ntheorem traverse_map {t : Type u → Type u} [traversable t] [is_lawful_traversable t] {F : Type u → Type u} [Applicative F] [is_lawful_applicative F] {α : Type u} {β : Type u} {γ : Type u} (f : β → F γ) (g : α → β) (x : t α) : traverse f (g <$> x) = traverse (f ∘ g) x := sorry\n\ntheorem pure_traverse {t : Type u → Type u} [traversable t] [is_lawful_traversable t] {F : Type u → Type u} [Applicative F] [is_lawful_applicative F] {α : Type u} (x : t α) : traverse pure x = pure x :=\n eq.mp (Eq._oldrec (Eq.refl (traverse pure x = pure (traverse id.mk x))) (is_lawful_traversable.id_traverse x))\n (Eq.symm (is_lawful_traversable.naturality (pure_transformation F) id.mk x))\n\ntheorem id_sequence {t : Type u → Type u} [traversable t] [is_lawful_traversable t] {α : Type u} (x : t α) : sequence (id.mk <$> x) = id.mk x := sorry\n\ntheorem comp_sequence {t : Type u → Type u} [traversable t] [is_lawful_traversable t] {F : Type u → Type u} {G : Type u → Type u} [Applicative F] [is_lawful_applicative F] [Applicative G] [is_lawful_applicative G] {α : Type u} (x : t (F (G α))) : sequence (functor.comp.mk <$> x) = functor.comp.mk (sequence <$> sequence x) := sorry\n\ntheorem naturality' {t : Type u → Type u} [traversable t] [is_lawful_traversable t] {F : Type u → Type u} {G : Type u → Type u} [Applicative F] [is_lawful_applicative F] [Applicative G] [is_lawful_applicative G] {α : Type u} (η : applicative_transformation F G) (x : t (F α)) : coe_fn η (t α) (sequence x) = sequence (coe_fn η α <$> x) := sorry\n\ntheorem traverse_id {t : Type u → Type u} [traversable t] [is_lawful_traversable t] {α : Type u} : traverse id.mk = id.mk := sorry\n\ntheorem traverse_comp {t : Type u → Type u} [traversable t] [is_lawful_traversable t] {F : Type u → Type u} {G : Type u → Type u} [Applicative F] [is_lawful_applicative F] [Applicative G] [is_lawful_applicative G] {α : Type u} {β : Type u} {γ : Type u} (g : α → F β) (h : β → G γ) : traverse (functor.comp.mk ∘ Functor.map h ∘ g) = functor.comp.mk ∘ Functor.map (traverse h) ∘ traverse g := sorry\n\ntheorem traverse_eq_map_id' {t : Type u → Type u} [traversable t] [is_lawful_traversable t] {β : Type u} {γ : Type u} (f : β → γ) : traverse (id.mk ∘ f) = id.mk ∘ Functor.map f := sorry\n\n-- @[functor_norm]\n\ntheorem traverse_map' {t : Type u → Type u} [traversable t] [is_lawful_traversable t] {G : Type u → Type u} [Applicative G] [is_lawful_applicative G] {α : Type u} {β : Type u} {γ : Type u} (g : α → β) (h : β → G γ) : traverse (h ∘ g) = traverse h ∘ Functor.map g := sorry\n\ntheorem map_traverse' {t : Type u → Type u} [traversable t] [is_lawful_traversable t] {G : Type u → Type u} [Applicative G] [is_lawful_applicative G] {α : Type u} {β : Type u} {γ : Type u} (g : α → G β) (h : β → γ) : traverse (Functor.map h ∘ g) = Functor.map (Functor.map h) ∘ traverse g := sorry\n\ntheorem naturality_pf {t : Type u → Type u} [traversable t] [is_lawful_traversable t] {F : Type u → Type u} {G : Type u → Type u} [Applicative F] [is_lawful_applicative F] [Applicative G] [is_lawful_applicative G] {α : Type u} {β : Type u} (η : applicative_transformation F G) (f : α → F β) : traverse (coe_fn η β ∘ f) = coe_fn η (t β) ∘ traverse f := sorry\n\n", "meta": {"author": "AurelienSaue", "repo": "Mathlib4_auto", "sha": "590df64109b08190abe22358fabc3eae000943f2", "save_path": "github-repos/lean/AurelienSaue-Mathlib4_auto", "path": "github-repos/lean/AurelienSaue-Mathlib4_auto/Mathlib4_auto-590df64109b08190abe22358fabc3eae000943f2/Mathlib/control/traversable/lemmas.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48047867804790706, "lm_q2_score": 0.08151976490042974, "lm_q1q2_score": 0.03916850887413466}} {"text": "import .apply_fun\n\nmeta def my_first_tactic : tactic unit := tactic.trace \"Hello, World.\"\n\nexample : true :=\nbegin\n my_first_tactic,\n trivial\nend\nmeta def my_second_tactic : tactic unit :=\ntactic.trace \"Hello,\" >> tactic.trace \"World.\"\n example : true :=\nbegin\n my_second_tactic,\n trivial\nend\nmeta def my_failing_tactic : tactic unit := tactic.failed\n\nmeta def my_failing_tactic' : tactic unit :=\ntactic.fail \"This tactic failed, we apologize for the inconvenience.\"\nexample : true :=\nbegin\n my_failing_tactic',\n trivial\nend\nopen tactic\n/-\nWhen chaining instructions, the first failure interrupts the process. \nHowever the orelse combinator,\n denoted by an infix <|> allows to try its right-hand side if its left-hand \n side failed. The following will successfully deliver its message.\n-/\n\nmeta def my_orelse : tactic unit := \nfail \"this tactic fail\" <|> trace \"hello\"\n\nexample : true := begin \n my_orelse,\n trivial, \n end\nmeta def trace_goal : tactic unit :=\n tactic.target >>= tactic.trace\nexample (a b : ℤ) : a = b → (a+1 = b+1) := begin \n trace_goal, intro hyp, apply_fun (λ t, 1+ t) at hyp,\n exact hyp,\n end \n\n", "meta": {"author": "Or7ando", "repo": "group_representation", "sha": "9b576984f17764ebf26c8caa2a542d248f1b50d2", "save_path": "github-repos/lean/Or7ando-group_representation", "path": "github-repos/lean/Or7ando-group_representation/group_representation-9b576984f17764ebf26c8caa2a542d248f1b50d2/group_rep1/programmation/test_apply_fun.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.3557749071749625, "lm_q2_score": 0.10970577096716554, "lm_q1q2_score": 0.039030560482401014}} {"text": "/-\nCopyright (c) 2020 Scott Morrison. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Lucas Allen, Scott Morrison\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.default\nimport Mathlib.tactic.interactive\nimport Mathlib.tactic.converter.interactive\nimport Mathlib.PostPort\n\nnamespace Mathlib\n\n/-!\n## Introduce the `apply_congr` conv mode tactic.\n\n`apply_congr` will apply congruence lemmas inside `conv` mode.\nIt is particularly useful when the automatically generated congruence lemmas\nare not of the optimal shape. An example, described in the doc-string is\nrewriting inside the operand of a `finset.sum`.\n-/\n\nnamespace conv.interactive\n\n\n/--\nApply a congruence lemma inside `conv` mode.\n\nWhen called without an argument `apply_congr` will try applying all lemmas marked with `@[congr]`.\nOtherwise `apply_congr e` will apply the lemma `e`.\n\nRecall that a goal that appears as `∣ X` in `conv` mode\nrepresents a goal of `⊢ X = ?m`,\ni.e. an equation with a metavariable for the right hand side.\n\nTo successfully use `apply_congr e`, `e` will need to be an equation\n(possibly after function arguments),\nwhich can be unified with a goal of the form `X = ?m`.\nThe right hand side of `e` will then determine the metavariable,\nand `conv` will subsequently replace `X` with that right hand side.\n\nAs usual, `apply_congr` can create new goals;\nany of these which are _not_ equations with a metavariable on the right hand side\nwill be hard to deal with in `conv` mode.\nThus `apply_congr` automatically calls `intros` on any new goals,\nand fails if they are not then equations.\n\nIn particular it is useful for rewriting inside the operand of a `finset.sum`,\nas it provides an extra hypothesis asserting we are inside the domain.\n\nFor example:\n\n```lean\nexample (f g : ℤ → ℤ) (S : finset ℤ) (h : ∀ m ∈ S, f m = g m) :\n finset.sum S f = finset.sum S g :=\nbegin\n conv_lhs {\n -- If we just call `congr` here, in the second goal we're helpless,\n -- because we are only given the opportunity to rewrite `f`.\n -- However `apply_congr` uses the appropriate `@[congr]` lemma,\n -- so we get to rewrite `f x`, in the presence of the crucial `H : x ∈ S` hypothesis.\n apply_congr,\n skip,\n simp [h, H],\n }\nend\n```\n\nIn the above example, when the `apply_congr` tactic is called it gives the hypothesis `H : x ∈ S`\nwhich is then used to rewrite the `f x` to `g x`.\n-/\nend Mathlib", "meta": {"author": "AurelienSaue", "repo": "Mathlib4_auto", "sha": "590df64109b08190abe22358fabc3eae000943f2", "save_path": "github-repos/lean/AurelienSaue-Mathlib4_auto", "path": "github-repos/lean/AurelienSaue-Mathlib4_auto/Mathlib4_auto-590df64109b08190abe22358fabc3eae000943f2/Mathlib/tactic/converter/apply_congr_auto.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35577489351363034, "lm_q2_score": 0.10970577096716554, "lm_q1q2_score": 0.03903055898367404}} {"text": "/-\nCopyright (c) 2017 Simon Hudon. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthor: Simon Hudon\n\nStandard identity and composition functors\n-/\nimport tactic.ext tactic.cache category.basic\n\nuniverse variables u v w\n\nsection functor\n\nvariables {F : Type u → Type v}\nvariables {α β γ : Type u}\nvariables [functor F] [is_lawful_functor F]\n\nlemma functor.map_id : (<$>) id = (id : F α → F α) :=\nby apply funext; apply id_map\n\nlemma functor.map_comp_map (f : α → β) (g : β → γ) :\n ((<$>) g ∘ (<$>) f : F α → F γ) = (<$>) (g ∘ f) :=\nby apply funext; intro; rw comp_map\n\ntheorem functor.ext {F} : ∀ {F1 : functor F} {F2 : functor F}\n [@is_lawful_functor F F1] [@is_lawful_functor F F2]\n (H : ∀ α β (f : α → β) (x : F α),\n @functor.map _ F1 _ _ f x = @functor.map _ F2 _ _ f x),\n F1 = F2\n| ⟨m, mc⟩ ⟨m', mc'⟩ H1 H2 H :=\nbegin\n cases show @m = @m', by funext α β f x; apply H,\n congr, funext α β,\n have E1 := @map_const_eq _ ⟨@m, @mc⟩ H1,\n have E2 := @map_const_eq _ ⟨@m, @mc'⟩ H2,\n exact E1.trans E2.symm\nend\n\nend functor\n\ndef id.mk {α : Sort u} : α → id α := id\n\nnamespace functor\n\ndef const (α : Type*) (β : Type*) := α\n\n@[pattern] def const.mk {α β} (x : α) : const α β := x\n\ndef const.mk' {α} (x : α) : const α punit := x\n\ndef const.run {α β} (x : const α β) : α := x\n\nnamespace const\n\nprotected lemma ext {α β} {x y : const α β} (h : x.run = y.run) : x = y := h\n\nprotected def map {γ α β} (f : α → β) (x : const γ β) : const γ α := x\n\ninstance {γ} : functor (const γ) :=\n{ map := @const.map γ }\n\ninstance {γ} : is_lawful_functor (const γ) :=\nby constructor; intros; refl\n\nend const\n\ndef add_const (α : Type*) := const α\n\n@[pattern]\ndef add_const.mk {α β} (x : α) : add_const α β := x\n\ndef add_const.run {α β} : add_const α β → α := id\n\ninstance add_const.functor {γ} : functor (add_const γ) :=\n@const.functor γ\n\ninstance add_const.is_lawful_functor {γ} : is_lawful_functor (add_const γ) :=\n@const.is_lawful_functor γ\n\n/-- `functor.comp` is a wrapper around `function.comp` for types.\n It prevents Lean's type class resolution mechanism from trying\n a `functor (comp F id)` when `functor F` would do. -/\ndef comp (F : Type u → Type w) (G : Type v → Type u) (α : Type v) : Type w :=\nF $ G α\n\n@[pattern] def comp.mk {F : Type u → Type w} {G : Type v → Type u} {α : Type v}\n (x : F (G α)) : comp F G α := x\n\ndef comp.run {F : Type u → Type w} {G : Type v → Type u} {α : Type v}\n (x : comp F G α) : F (G α) := x\n\nnamespace comp\n\nvariables {F : Type u → Type w} {G : Type v → Type u}\n\nprotected lemma ext\n {α} {x y : comp F G α} : x.run = y.run → x = y := id\n\nvariables [functor F] [functor G]\n\nprotected def map {α β : Type v} (h : α → β) : comp F G α → comp F G β\n| (comp.mk x) := comp.mk ((<$>) h <$> x)\n\ninstance : functor (comp F G) := { map := @comp.map F G _ _ }\n\n@[functor_norm] lemma map_mk {α β} (h : α → β) (x : F (G α)) :\n h <$> comp.mk x = comp.mk ((<$>) h <$> x) := rfl\n\nvariables [is_lawful_functor F] [is_lawful_functor G]\nvariables {α β γ : Type v}\n\nprotected lemma id_map : ∀ (x : comp F G α), comp.map id x = x\n| (comp.mk x) := by simp [comp.map, functor.map_id]\n\nprotected lemma comp_map (g' : α → β) (h : β → γ) : ∀ (x : comp F G α),\n comp.map (h ∘ g') x = comp.map h (comp.map g' x)\n| (comp.mk x) := by simp [comp.map, functor.map_comp_map g' h] with functor_norm\n\n@[simp] protected lemma run_map (h : α → β) (x : comp F G α) :\n (h <$> x).run = (<$>) h <$> x.run := rfl\n\ninstance : is_lawful_functor (comp F G) :=\n{ id_map := @comp.id_map F G _ _ _ _,\n comp_map := @comp.comp_map F G _ _ _ _ }\n\ntheorem functor_comp_id {F} [AF : functor F] [is_lawful_functor F] :\n @comp.functor F id _ _ = AF :=\n@functor.ext F _ AF (@comp.is_lawful_functor F id _ _ _ _) _ (λ α β f x, rfl)\n\ntheorem functor_id_comp {F} [AF : functor F] [is_lawful_functor F] :\n @comp.functor id F _ _ = AF :=\n@functor.ext F _ AF (@comp.is_lawful_functor id F _ _ _ _) _ (λ α β f x, rfl)\n\nend comp\n\nend functor\n\nnamespace ulift\n\ninstance : functor ulift :=\n{ map := λ α β f, up ∘ f ∘ down }\n\nend ulift\n", "meta": {"author": "digama0", "repo": "mathlib-ITP2019", "sha": "5cbd0362e04e671ef5db1284870592af6950197c", "save_path": "github-repos/lean/digama0-mathlib-ITP2019", "path": "github-repos/lean/digama0-mathlib-ITP2019/mathlib-ITP2019-5cbd0362e04e671ef5db1284870592af6950197c/src/category/functor.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958346, "lm_q2_score": 0.07921031541437026, "lm_q1q2_score": 0.03867708175298269}} {"text": "/-\nCopyright (c) 2020 Anne Baanen. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Anne Baanen\n\n! This file was ported from Lean 3 source module tactic.simp_rw\n! leanprover-community/mathlib commit 610861666826c95213acd9dac829a2321e141b64\n! Please do not edit these lines, except to modify the commit id\n! if you have ported upstream changes.\n-/\nimport Mathbin.Tactic.Core\n\n/-!\n# The `simp_rw` tactic\n\nThis module defines a tactic `simp_rw` which functions as a mix of `simp` and\n`rw`. Like `rw`, it applies each rewrite rule in the given order, but like\n`simp` it repeatedly applies these rules and also under binders like `∀ x, ...`,\n`∃ x, ...` and `λ x, ...`.\n\n## Implementation notes\n\nThe tactic works by taking each rewrite rule in turn and applying `simp only` to\nit. Arguments to `simp_rw` are of the format used by `rw` and are translated to\ntheir equivalents for `simp`.\n-/\n\n\nnamespace Tactic.Interactive\n\nopen Interactive Interactive.Types Tactic\n\n/-- `simp_rw` functions as a mix of `simp` and `rw`. Like `rw`, it applies each\nrewrite rule in the given order, but like `simp` it repeatedly applies these\nrules and also under binders like `∀ x, ...`, `∃ x, ...` and `λ x, ...`.\n\nUsage:\n - `simp_rw [lemma_1, ..., lemma_n]` will rewrite the goal by applying the\n lemmas in that order. A lemma preceded by `←` is applied in the reverse direction.\n - `simp_rw [lemma_1, ..., lemma_n] at h₁ ... hₙ` will rewrite the given hypotheses.\n - `simp_rw [...] at ⊢ h₁ ... hₙ` rewrites the goal as well as the given hypotheses.\n - `simp_rw [...] at *` rewrites in the whole context: all hypotheses and the goal.\n\nLemmas passed to `simp_rw` must be expressions that are valid arguments to `simp`.\n\nFor example, neither `simp` nor `rw` can solve the following, but `simp_rw` can:\n```lean\nexample {α β : Type} {f : α → β} {t : set β} :\n (∀ s, f '' s ⊆ t) = ∀ s : set α, ∀ x ∈ s, x ∈ f ⁻¹' t :=\nby simp_rw [set.image_subset_iff, set.subset_def]\n```\n-/\nunsafe def simp_rw (q : parse rw_rules) (l : parse location) : tactic Unit :=\n q.rules.mapM' fun rule => do\n let simp_arg :=\n if rule.symm then simp_arg_type.symm_expr rule.rule else simp_arg_type.expr rule.rule\n save_info rule\n simp none none tt [simp_arg] [] l\n#align tactic.interactive.simp_rw tactic.interactive.simp_rw\n\n-- equivalent to `simp only [rule] at l`\nadd_tactic_doc\n { Name := \"simp_rw\"\n category := DocCategory.tactic\n declNames := [`tactic.interactive.simp_rw]\n tags := [\"simplification\"] }\n\nend Tactic.Interactive\n\n", "meta": {"author": "leanprover-community", "repo": "mathlib3port", "sha": "62505aa236c58c8559783b16d33e30df3daa54f4", "save_path": "github-repos/lean/leanprover-community-mathlib3port", "path": "github-repos/lean/leanprover-community-mathlib3port/mathlib3port-62505aa236c58c8559783b16d33e30df3daa54f4/Mathbin/Tactic/SimpRw.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38861801254413963, "lm_q2_score": 0.09947022255820849, "lm_q1q2_score": 0.038655920197894225}} {"text": "/-\nCopyright (c) 2020 Scott Morrison. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Scott Morrison\n\n! This file was ported from Lean 3 source module tactic.show_term\n! leanprover-community/mathlib commit afa534cdfa220967e744b2c39c1006e8aaae423e\n! Please do not edit these lines, except to modify the commit id\n! if you have ported upstream changes.\n-/\nimport Mathbin.Tactic.Core\n\nopen Tactic\n\nnamespace Tactic.Interactive\n\n/-- `show_term { tac }` runs the tactic `tac`,\nand then prints the term that was constructed.\n\nThis is useful for\n* constructing term mode proofs from tactic mode proofs, and\n* understanding what tactics are doing, and how metavariables are handled.\n\nAs an example, in\n```\nexample {P Q R : Prop} (h₁ : Q → P) (h₂ : R) (h₃ : R → Q) : P ∧ R :=\nby show_term { tauto }\n```\nthe term mode proof `⟨h₁ (h₃ h₂), eq.mpr rfl h₂⟩` produced by `tauto` will be printed.\n\nAs another example, if the goal is `ℕ × ℕ`, `show_term { split, exact 0 }` will\nprint `refine (0, _)`, and afterwards there will be one remaining goal (of type `ℕ`).\nThis indicates that `split, exact 0` partially filled in the original metavariable,\nbut created a new metavariable for the resulting sub-goal.\n-/\nunsafe def show_term (t : itactic) : itactic := do\n let g :: _ ← get_goals\n t\n let g ← tactic_statement g\n trace g\n#align tactic.interactive.show_term tactic.interactive.show_term\n\nadd_tactic_doc\n { Name := \"show_term\"\n category := DocCategory.tactic\n declNames := [`` show_term]\n tags := [\"debugging\"] }\n\nend Tactic.Interactive\n\n", "meta": {"author": "leanprover-community", "repo": "mathlib3port", "sha": "62505aa236c58c8559783b16d33e30df3daa54f4", "save_path": "github-repos/lean/leanprover-community-mathlib3port", "path": "github-repos/lean/leanprover-community-mathlib3port/mathlib3port-62505aa236c58c8559783b16d33e30df3daa54f4/Mathbin/Tactic/ShowTerm.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3073580295544412, "lm_q2_score": 0.12421301159407336, "lm_q1q2_score": 0.03817786648857734}} {"text": "/-!\n# Functor\n\nA `Functor` is any type that can act as a generic container that allows you to transform the\nunderlying values inside the container using a function, so that the values are all updated, but the\nstructure of the container is the same. This is called \"mapping\".\n\nA List is one of the most basic examples of a `Functor`.\n\nA list contains zero or more elements of the same, underlying type. When you `map` a function over\na list, you create a new list with the same number of elements, where each has been transformed by\nthe function:\n-/\n#eval List.map (λ x => toString x) [1,2,3] -- [\"1\", \"2\", \"3\"]\n\n-- you can also write this using dot notation on the List object\n#eval [1,2,3].map (λ x => toString x) -- [\"1\", \"2\", \"3\"]\n\n/-!\nHere we converted a list of natural numbers (Nat) to a list of strings where the lambda function\nhere used `toString` to do the transformation of each element. Notice that when you apply `map` the\n\"structure\" of the object remains the same, in this case the result is always a `List` of the same\nsize.\n\nNote that in Lean a lambda function can be written using `fun` keyword or the unicode\nsymbol `λ` which you can type in VS code using `\\la `.\n\nList has a specialized version of `map` defined as follows:\n-/\ndef map (f : α → β) : List α → List β\n | [] => []\n | a::as => f a :: map f as\n\n/-!\nThis is a very generic `map` function that can take any function that converts `(α → β)` and use it\nto convert `List α → List β`. Notice the function call `f a` above, this application of `f` is\nproducing the converted items for the new list.\n\nLet's look at some more examples:\n\n-/\n-- List String → List Nat\n#eval [\"elephant\", \"tiger\", \"giraffe\"].map (fun s => s.length)\n-- [8, 5, 7]\n\n-- List Nat → List Float\n#eval [1,2,3,4,5].map (fun s => (s.toFloat) ^ 3.0)\n-- [1.000000, 8.000000, 27.000000, 64.000000, 125.000000]\n\n--- List String → List String\n#eval [\"chris\", \"david\", \"mark\"].map (fun s => s.capitalize)\n-- [\"Chris\", \"David\", \"Mark\"]\n/-!\n\nAnother example of a functor is the `Option` type. Option contains a value or nothing and is handy\nfor code that has to deal with optional values, like optional command line arguments.\n\nRemember you can construct an Option using the type constructors `some` or `none`:\n\n-/\n#check some 5 -- Option Nat\n#eval some 5 -- some 5\n#eval (some 5).map (fun x => x + 1) -- some 6\n#eval (some 5).map (fun x => toString x) -- some \"5\"\n/-!\n\nLean also provides a convenient short hand syntax for `(fun x => x + 1)`, namely `(· + 1)`\nusing the middle dot unicode character which you can type in VS code using `\\. `.\n\n-/\n#eval (some 4).map (· * 5) -- some 20\n/-!\n\nThe `map` function preserves the `none` state of the Option, so again\nmap preserves the structure of the object.\n\n-/\ndef x : Option Nat := none\n#eval x.map (fun x => toString x) -- none\n#check x.map (fun x => toString x) -- Option String\n/-!\n\nNotice that even in the `none` case it has transformed `Option Nat` into `Option String` as\nyou see in the `#check` command.\n\n## How to make a Functor Instance?\n\nThe `List` type is made an official `Functor` by the following type class instance:\n\n-/\ninstance : Functor List where\n map := List.map\n/-!\n\nNotice all you need to do is provide the `map` function implementation. For a quick\nexample, let's supposed you create a new type describing the measurements of a home\nor apartment:\n\n-/\nstructure LivingSpace (α : Type) where\n totalSize : α\n numBedrooms : Nat\n masterBedroomSize : α\n livingRoomSize : α\n kitchenSize : α\n deriving Repr, BEq\n/-!\n\nNow you can construct a `LivingSpace` in square feet using floating point values:\n-/\nabbrev SquareFeet := Float\n\ndef mySpace : LivingSpace SquareFeet :=\n { totalSize := 1800, numBedrooms := 4, masterBedroomSize := 500,\n livingRoomSize := 900, kitchenSize := 400 }\n/-!\n\nNow, suppose you want anyone to be able to map a `LivingSpace` from one type of measurement unit to\nanother. Then you would provide a `Functor` instance as follows:\n\n-/\ndef LivingSpace.map (f : α → β) (s : LivingSpace α) : LivingSpace β :=\n { totalSize := f s.totalSize\n numBedrooms := s.numBedrooms\n masterBedroomSize := f s.masterBedroomSize\n livingRoomSize := f s.livingRoomSize\n kitchenSize := f s.kitchenSize }\n\ninstance : Functor LivingSpace where\n map := LivingSpace.map\n/-!\n\nNotice this functor instance takes `LivingSpace` and not the fully qualified type `LivingSpace SquareFeet`.\nNotice below that `LivingSpace` is a function from Type to Type. For example, if you give it type `SquareFeet`\nit gives you back the fully qualified type `LivingSpace SquareFeet`.\n\n-/\n#check LivingSpace -- Type → Type\n/-!\n\nSo the `instance : Functor` then is operating on the more abstract, or generic `LivingSpace` saying\nfor the whole family of types `LivingSpace α` you can map to `LivingSpace β` using the generic\n`LivingSpace.map` map function by simply providing a function that does the more primitive mapping\nfrom `(f : α → β)`. So `LivingSpace.map` is a sort of function applicator.\nThis is called a \"higher order function\" because it takes a function as input\n`(α → β)` and returns another function as output `F α → F β`.\n\nNotice that `LivingSpace.map` applies a function `f` to convert the units of all the LivingSpace\nfields, except for `numBedrooms` which is a count (and therefore is not a measurement that needs\nconverting).\n\nSo now you can define a simple conversion function, let's say you want square meters instead:\n\n-/\nabbrev SquareMeters := Float\ndef squareFeetToMeters (ft : SquareFeet ) : SquareMeters := (ft / 10.7639104)\n/-!\n\nand now bringing it all together you can use the simple function `squareFeetToMeters` to map\n`mySpace` to square meters:\n\n-/\n#eval mySpace.map squareFeetToMeters\n/-\n{ totalSize := 167.225472,\n numBedrooms := 4,\n masterBedroomSize := 46.451520,\n livingRoomSize := 83.612736,\n kitchenSize := 37.161216 }\n -/\n/-!\n\nLean also defines custom infix operator `<$>` for `Functor.map` which allows you to write this:\n-/\n#eval (fun s => s.length) <$> [\"elephant\", \"tiger\", \"giraffe\"] -- [8, 5, 7]\n#eval (fun x => x + 1) <$> (some 5) -- some 6\n/-!\n\nNote that the infix operator is left associative which means it binds more tightly to the\nfunction on the left than to the expression on the right, this means you can often drop the\nparentheses on the right like this:\n\n-/\n#eval (fun x => x + 1) <$> some 5 -- some 6\n/-!\n\nNote that Lean lets you define your own syntax, so `<$>` is nothing special.\nYou can define your own infix operator like this:\n\n-/\ninfixr:100 \" doodle \" => Functor.map\n\n#eval (· * 5) doodle [1, 2, 3] -- [5, 10, 15]\n\n/-!\nWow, this is pretty powerful. By providing a functor instance on `LivingSpace` with an\nimplementation of the `map` function it is now super easy for anyone to come along and\ntransform the units of a `LivingSpace` using very simple functions like `squareFeetToMeters`. Notice\nthat squareFeetToMeters knows nothing about `LivingSpace`.\n\n## How do Functors help with Monads ?\n\nFunctors are an abstract mathematical structure that is represented in Lean with a type class. The\nLean functor defines both `map` and a special case for working on constants more efficiently called\n`mapConst`:\n\n```lean\nclass Functor (f : Type u → Type v) : Type (max (u+1) v) where\n map : {α β : Type u} → (α → β) → f α → f β\n mapConst : {α β : Type u} → α → f β → f α\n```\n\nNote that `mapConst` has a default implementation, namely:\n`mapConst : {α β : Type u} → α → f β → f α := Function.comp map (Function.const _)` in the `Functor`\ntype class. So you can use this default implementation and you only need to replace it if\nyour functor has a more specialized variant than this (usually the custom version is more performant).\n\nIn general then, a functor is a function on types `F : Type u → Type v` equipped with an operator\ncalled `map` such that if you have a function `f` of type `α → β` then `map f` will convert your\ncontainer type from `F α → F β`. This corresponds to the category-theory notion of\n[functor](https://en.wikipedia.org/wiki/Functor) in the special case where the category is the\ncategory of types and functions between them.\n\nUnderstanding abstract mathematical structures is a little tricky for most people. So it helps to\nstart with a simpler idea like functors before you try to understand monads. Building on\nfunctors is the next abstraction called [Applicatives](applicatives.lean.md).\n-/", "meta": {"author": "leanprover", "repo": "lean4", "sha": "742d053a97bdd109a41a921facd1cd6a55e89bc7", "save_path": "github-repos/lean/leanprover-lean4", "path": "github-repos/lean/leanprover-lean4/lean4-742d053a97bdd109a41a921facd1cd6a55e89bc7/doc/monads/functors.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4416729909662418, "lm_q2_score": 0.08632347247278889, "lm_q1q2_score": 0.03812674627764871}} {"text": "/-\nCopyright (c) 2020 Scott Morrison. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Scott Morrison\n-/\nimport category_theory.monoidal.coherence\n\n/-!\n# Monoidal opposites\n\nWe write `Cᵐᵒᵖ` for the monoidal opposite of a monoidal category `C`.\n-/\n\n\nuniverses v₁ v₂ u₁ u₂\n\nvariables {C : Type u₁}\n\nnamespace category_theory\n\nopen category_theory.monoidal_category\n\n/-- A type synonym for the monoidal opposite. Use the notation `Cᴹᵒᵖ`. -/\n@[nolint has_inhabited_instance]\ndef monoidal_opposite (C : Type u₁) := C\n\nnamespace monoidal_opposite\n\nnotation C `ᴹᵒᵖ`:std.prec.max_plus := monoidal_opposite C\n\n/-- Think of an object of `C` as an object of `Cᴹᵒᵖ`. -/\n@[pp_nodot]\ndef mop (X : C) : Cᴹᵒᵖ := X\n\n/-- Think of an object of `Cᴹᵒᵖ` as an object of `C`. -/\n@[pp_nodot]\ndef unmop (X : Cᴹᵒᵖ) : C := X\n\nlemma op_injective : function.injective (mop : C → Cᴹᵒᵖ) := λ _ _, id\nlemma unop_injective : function.injective (unmop : Cᴹᵒᵖ → C) := λ _ _, id\n\n@[simp] lemma op_inj_iff (x y : C) : mop x = mop y ↔ x = y := iff.rfl\n@[simp] lemma unop_inj_iff (x y : Cᴹᵒᵖ) : unmop x = unmop y ↔ x = y := iff.rfl\n\nattribute [irreducible] monoidal_opposite\n\n@[simp] lemma mop_unmop (X : Cᴹᵒᵖ) : mop (unmop X) = X := rfl\n@[simp] lemma unmop_mop (X : C) : unmop (mop X) = X := rfl\n\ninstance monoidal_opposite_category [I : category.{v₁} C] : category Cᴹᵒᵖ :=\n{ hom := λ X Y, unmop X ⟶ unmop Y,\n id := λ X, 𝟙 (unmop X),\n comp := λ X Y Z f g, f ≫ g, }\n\nend monoidal_opposite\n\nend category_theory\n\nopen category_theory\nopen category_theory.monoidal_opposite\n\nvariables [category.{v₁} C]\n\n/-- The monoidal opposite of a morphism `f : X ⟶ Y` is just `f`, thought of as `mop X ⟶ mop Y`. -/\ndef quiver.hom.mop {X Y : C} (f : X ⟶ Y) : @quiver.hom Cᴹᵒᵖ _ (mop X) (mop Y) := f\n/-- We can think of a morphism `f : mop X ⟶ mop Y` as a morphism `X ⟶ Y`. -/\ndef quiver.hom.unmop {X Y : Cᴹᵒᵖ} (f : X ⟶ Y) : unmop X ⟶ unmop Y := f\n\nnamespace category_theory\n\nlemma mop_inj {X Y : C} :\n function.injective (quiver.hom.mop : (X ⟶ Y) → (mop X ⟶ mop Y)) :=\nλ _ _ H, congr_arg quiver.hom.unmop H\n\nlemma unmop_inj {X Y : Cᴹᵒᵖ} :\n function.injective (quiver.hom.unmop : (X ⟶ Y) → (unmop X ⟶ unmop Y)) :=\nλ _ _ H, congr_arg quiver.hom.mop H\n\n@[simp] lemma unmop_mop {X Y : C} {f : X ⟶ Y} : f.mop.unmop = f := rfl\n@[simp] lemma mop_unmop {X Y : Cᴹᵒᵖ} {f : X ⟶ Y} : f.unmop.mop = f := rfl\n\n@[simp] lemma mop_comp {X Y Z : C} {f : X ⟶ Y} {g : Y ⟶ Z} :\n (f ≫ g).mop = f.mop ≫ g.mop := rfl\n@[simp] lemma mop_id {X : C} : (𝟙 X).mop = 𝟙 (mop X) := rfl\n\n@[simp] lemma unmop_comp {X Y Z : Cᴹᵒᵖ} {f : X ⟶ Y} {g : Y ⟶ Z} :\n (f ≫ g).unmop = f.unmop ≫ g.unmop := rfl\n@[simp] lemma unmop_id {X : Cᴹᵒᵖ} : (𝟙 X).unmop = 𝟙 (unmop X) := rfl\n\n@[simp] lemma unmop_id_mop {X : C} : (𝟙 (mop X)).unmop = 𝟙 X := rfl\n@[simp] lemma mop_id_unmop {X : Cᴹᵒᵖ} : (𝟙 (unmop X)).mop = 𝟙 X := rfl\n\nnamespace iso\n\nvariables {X Y : C}\n\n/-- An isomorphism in `C` gives an isomorphism in `Cᴹᵒᵖ`. -/\n@[simps]\ndef mop (f : X ≅ Y) : mop X ≅ mop Y :=\n{ hom := f.hom.mop,\n inv := f.inv.mop,\n hom_inv_id' := unmop_inj f.hom_inv_id,\n inv_hom_id' := unmop_inj f.inv_hom_id }\n\nend iso\n\nvariables [monoidal_category.{v₁} C]\n\nopen opposite monoidal_category\n\ninstance monoidal_category_op : monoidal_category Cᵒᵖ :=\n{ tensor_obj := λ X Y, op (unop X ⊗ unop Y),\n tensor_hom := λ X₁ Y₁ X₂ Y₂ f g, (f.unop ⊗ g.unop).op,\n tensor_unit := op (𝟙_ C),\n associator := λ X Y Z, (α_ (unop X) (unop Y) (unop Z)).symm.op,\n left_unitor := λ X, (λ_ (unop X)).symm.op,\n right_unitor := λ X, (ρ_ (unop X)).symm.op,\n associator_naturality' := by { intros, apply quiver.hom.unop_inj, simp, },\n left_unitor_naturality' := by { intros, apply quiver.hom.unop_inj, simp, },\n right_unitor_naturality' := by { intros, apply quiver.hom.unop_inj, simp, },\n triangle' := by { intros, apply quiver.hom.unop_inj, coherence, },\n pentagon' := by { intros, apply quiver.hom.unop_inj, coherence, }, }\n\nlemma op_tensor_obj (X Y : Cᵒᵖ) : X ⊗ Y = op (unop X ⊗ unop Y) := rfl\nlemma op_tensor_unit : (𝟙_ Cᵒᵖ) = op (𝟙_ C) := rfl\n\ninstance monoidal_category_mop : monoidal_category Cᴹᵒᵖ :=\n{ tensor_obj := λ X Y, mop (unmop Y ⊗ unmop X),\n tensor_hom := λ X₁ Y₁ X₂ Y₂ f g, (g.unmop ⊗ f.unmop).mop,\n tensor_unit := mop (𝟙_ C),\n associator := λ X Y Z, (α_ (unmop Z) (unmop Y) (unmop X)).symm.mop,\n left_unitor := λ X, (ρ_ (unmop X)).mop,\n right_unitor := λ X, (λ_ (unmop X)).mop,\n associator_naturality' := by { intros, apply unmop_inj, simp, },\n left_unitor_naturality' := by { intros, apply unmop_inj, simp, },\n right_unitor_naturality' := by { intros, apply unmop_inj, simp, },\n triangle' := by { intros, apply unmop_inj, coherence, },\n pentagon' := by { intros, apply unmop_inj, coherence, }, }\n\nlemma mop_tensor_obj (X Y : Cᴹᵒᵖ) : X ⊗ Y = mop (unmop Y ⊗ unmop X) := rfl\nlemma mop_tensor_unit : (𝟙_ Cᴹᵒᵖ) = mop (𝟙_ C) := rfl\n\nend category_theory\n", "meta": {"author": "Parinya-Siri", "repo": "lean-machine-learning", "sha": "ec610bac246ae7108fc6f0c140b3440f0fbacc52", "save_path": "github-repos/lean/Parinya-Siri-lean-machine-learning", "path": "github-repos/lean/Parinya-Siri-lean-machine-learning/lean-machine-learning-ec610bac246ae7108fc6f0c140b3440f0fbacc52/matlib/category_theory/monoidal/opposite.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4804786780479071, "lm_q2_score": 0.07921032628268802, "lm_q1q2_score": 0.03805887286004933}} {"text": "lemma subsingleton_injective {α β : Sort*} [subsingleton α] (f : α → β) :\n function.injective f :=\nby { intros _ _, cc }\n", "meta": {"author": "rwbarton", "repo": "lean-omin", "sha": "fd733c6d95ef6f4743aae97de5e15df79877c00e", "save_path": "github-repos/lean/rwbarton-lean-omin", "path": "github-repos/lean/rwbarton-lean-omin/lean-omin-fd733c6d95ef6f4743aae97de5e15df79877c00e/src/for_mathlib/misc.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.5, "lm_q2_score": 0.07585818419975078, "lm_q1q2_score": 0.03792909209987539}} {"text": "/-\nCopyright (c) 2022 Devon Tuma. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Devon Tuma\n-/\nimport computational_monads.simulation_semantics.oracle_append\n\n/-!\n# Coercions Between Simulation Oracles With Target Spec Coercions\n\nThis file provides a number of `has_coe` instances for `sim_oracle`, when the\ntarget `oracle_spec` already defines computations with coercions,\nusing the coercion to respond to oracle queries in the new set of oracles.\n-/\n\nnamespace oracle_comp\n\nopen oracle_spec\n\nvariables (spec spec' spec'' spec''' : oracle_spec)\n (coe_spec coe_spec' coe_spec'' coe_spec''' : oracle_spec)\n (S S' : Type) {α : Type}\n\nsection coe_sim_oracle\n\n/-- Use a coercion on the resulting type of a simulation to coerce the simulation oracle itself.\n This allows for greater flexibility when specifying the simulation oracle when\n both the initial and final `oracle_spec` are some appended set of oracles -/\ninstance [coe_spec ⊂ₒ coe_spec'] :\n has_coe (sim_oracle spec coe_spec S) (sim_oracle spec coe_spec' S) :=\n{ coe := λ so, {default_state := so.default_state, o := λ i x, ↑(so i x)} }\n\n/-- Coerce a simulation oracle to include an additional number of resulting oracles -/\nexample (so : sim_oracle coe_spec coe_spec' S) :\n sim_oracle coe_spec (coe_spec' ++ spec ++ spec') S := ↑so\n\n/-- Can use coercions to seperately simulate both sides of appended oracle specs -/\nexample (so : sim_oracle spec spec'' S) (so' : sim_oracle spec' spec''' S') :\n sim_oracle (spec ++ spec') (spec'' ++ spec''') (S × S') :=\n↑so ++ₛ ↑so'\n\nend coe_sim_oracle\n\nend oracle_comp", "meta": {"author": "dtumad", "repo": "lean-crypto-formalization", "sha": "f975a9a9882120b509553a7ced9aa05b745ff154", "save_path": "github-repos/lean/dtumad-lean-crypto-formalization", "path": "github-repos/lean/dtumad-lean-crypto-formalization/lean-crypto-formalization-f975a9a9882120b509553a7ced9aa05b745ff154/src/computational_monads/coercions/sim_oracle.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44552952031526044, "lm_q2_score": 0.08509904558710156, "lm_q1q2_score": 0.03791413695970784}} {"text": "-- Copyright (c) Microsoft Corporation. All rights reserved.\n-- Licensed under the MIT license.\n\nimport .spec\nimport .lemmas\nimport ..irsem\n\n\nnamespace spec\n\nopen irsem\n/-\n - Lemmas about regfile.\n -/\n\n-- Induction principle of regfile.\nlemma regfile.induction: ∀ {sem} {P: regfile sem → Prop}\n {HP0: P (@regfile.empty sem)}\n {HPU: ∀ rf, P rf → ∀ n v, P (regfile.update sem rf n v)},\n ∀ rf, P rf\n:= begin\n intros,\n induction rf,\n { apply HP0 },\n {\n cases rf_hd,\n unfold regfile.update at HPU,\n apply HPU, assumption\n }\nend\n\n-- regfile.get returns none on regfile.empty\nlemma regfile.empty_get_none: ∀ {sem} rname,\n regfile.get sem (regfile.empty sem) rname = none\n:= begin\n intros,\n unfold regfile.empty,\n unfold regfile.get,\n simp,\n unfold regfile.get._match_1\nend\n\nlemma regfile.empty_apply_empty: ∀ {sem} f,\n regfile.apply_to_values sem (regfile.empty sem) f = regfile.empty sem\n:= begin\n intros,\n unfold regfile.empty,\n refl\nend\n\n-- regfile.get returns the value which is updated just before\n-- if rname = rname2\nlemma regfile.update_get_match: ∀ {sem} (rname rname2:string) vp rf\n (Hnameeq: rname2 = rname),\n regfile.get sem (regfile.update sem rf rname vp) rname2 = some vp\n:= begin\n intros,\n unfold regfile.get,\n unfold regfile.update,\n rw list.filter_cons_of_pos,\n { unfold regfile.get._match_1 },\n { simp, assumption }\nend\n\n-- Updating a register file does not affect the result\n-- of regfile.get if rname ≠ rname2\nlemma regfile.update_get_nomatch: ∀ {sem} (rname rname2:string) vp rf\n (Hnameeq: rname2 ≠ rname),\n regfile.get sem (regfile.update sem rf rname vp) rname2 =\n regfile.get sem rf rname2\n:= begin\n intros,\n unfold regfile.get,\n unfold regfile.update,\n rw list.filter_cons_of_neg,\n { simp, assumption },\nend\n\nlemma regfile.regnames_empty: ∀ {sem} n,\n n ∉ regfile.regnames sem (regfile.empty sem)\n:= begin\n intros,\n unfold regfile.regnames,\n unfold regfile.empty,\n simp\nend\n\nlemma regfile.reg_in_regnames_update: ∀ {sem} rf n n' v \n (H: n ∈ regfile.regnames sem rf),\n n ∈ regfile.regnames sem (regfile.update sem rf n' v)\n:= begin\n intros,\n unfold regfile.update,\n unfold regfile.regnames at *,\n simp,\n right, apply H\nend\n\nlemma regfile.reg_in_regnames_update2: ∀ {sem} rf n v,\n n ∈ regfile.regnames sem (regfile.update sem rf n v)\n:= begin\n intros,\n unfold regfile.update,\n unfold regfile.regnames at *,\n simp\nend\n\nlemma regfile.reg_in_regnames_update3: ∀ {sem} rf n n' v \n (H: n ∈ regfile.regnames sem (regfile.update sem rf n' v))\n (HNEQ: n ≠ n'),\n n ∈ regfile.regnames sem rf\n:= begin\n intros,\n unfold regfile.update at H,\n unfold regfile.regnames at *,\n simp at *,\n cases H,\n { exfalso, apply HNEQ, assumption },\n assumption\nend\n\nlemma regfile.reg_notin_regnames_get_none: ∀ {sem} (rname:string) (f:regfile sem),\n regfile.get sem f rname = none ↔ rname ∉ regfile.regnames sem f\n:= begin\n intros,\n split,\n {\n intros H,\n induction f,\n { unfold regfile.regnames, simp },\n {\n unfold regfile.get at H,\n unfold regfile.regnames,\n cases f_hd with n1 v1, unfold list.filter at H,\n simp,\n have H0: decidable (n1 = rname), apply_instance,\n cases H0,\n {\n rw if_neg at H,\n { intros H1,\n cases H1,\n { rw H1 at H0, apply H0, refl },\n { apply f_ih, apply H, apply H1 }\n },\n {\n simp, apply neq_symm, apply H0\n }\n },\n {\n rw if_pos at H,\n unfold regfile.get._match_1 at H, cases H,\n simp, rw H0\n }\n }\n },\n {\n intros H,\n induction f,\n {\n unfold regfile.get,\n simp, unfold regfile.get._match_1\n },\n {\n unfold regfile.regnames at H,\n simp at H,\n rw ← list.mem_cons_iff at H,\n rw list.notmem_and at H,\n unfold regfile.get,\n have H: decidable (f_hd.fst = rname), apply_instance,\n cases H,\n { -- first element is not rname\n unfold list.filter,\n rw if_neg, apply f_ih,\n cases H, apply H_right,\n intros H', rw H' at H_1, apply H_1, refl\n },\n {\n cases H, rw H_1 at H_left, exfalso, apply H_left, refl\n }\n }\n }\nend\n\nlemma regfile.reg_in_regnames_get_some: ∀ {sem} (rname:string) (f:regfile sem),\n (∃ v, regfile.get sem f rname = some v) ↔ rname ∈ regfile.regnames sem f\n:= begin\n intros,\n split,\n {\n apply regfile.induction f,\n {\n intros H, cases H,\n rw regfile.empty_get_none at H_h,\n cases H_h\n },\n {\n intros s Hind n v H,\n have HN:decidable (n = rname), apply_instance,\n cases HN,\n {\n rw regfile.update_get_nomatch at H,\n have H := Hind H,\n apply regfile.reg_in_regnames_update, assumption,\n apply neq_symm, assumption\n },\n {\n rw HN,\n apply regfile.reg_in_regnames_update2\n }\n }\n },\n {\n apply regfile.induction f,\n { intros H, cases H },\n {\n intros rf Hind n v H,\n have HN:decidable (n = rname), apply_instance,\n cases HN,\n {\n rw regfile.update_get_nomatch,\n apply Hind,\n apply regfile.reg_in_regnames_update3,\n { apply H },\n any_goals { apply neq_symm, assumption },\n },\n {\n rw HN,\n apply exists.intro v,\n apply regfile.update_get_match, refl\n }\n }\n }\nend\n\nlemma regfile.apply_update_comm: ∀ {sem} f n v rf,\n regfile.apply_to_values sem (regfile.update sem rf n v) f =\n regfile.update sem (regfile.apply_to_values sem rf f) n (f v)\n:= begin\n intros, unfold regfile.apply_to_values, unfold regfile.update, refl\nend\n\n-- Note: reverse direction does not hold!\nlemma regfile.reg_apply_some: ∀ {sem} (rf:regfile sem) (f:valty sem → valty sem) v n\n (H:regfile.get sem rf n = some v),\n regfile.get sem (regfile.apply_to_values sem rf f) n = some (f v)\n:= begin\n intros,\n revert H,\n apply regfile.induction rf,\n { intros H, rw regfile.empty_get_none at H, cases H },\n {\n intros rf Hind n1 v1 H,\n have HNAME: decidable(n1 = n), apply_instance,\n cases HNAME,\n {\n rw regfile.update_get_nomatch at H,\n have H' := Hind H,\n rw regfile.apply_update_comm,\n rw regfile.update_get_nomatch, assumption,\n any_goals { apply neq_symm, assumption }\n },\n {\n rw regfile.update_get_match at H,\n injection H, subst h_1,\n rw regfile.apply_update_comm,\n rw regfile.update_get_match,\n any_goals { rw HNAME }\n }\n }\nend\n\nlemma regfile.reg_apply_none: ∀ {sem} (rf:regfile sem) (f:valty sem → valty sem) n,\n regfile.get sem rf n = none ↔ regfile.get sem (regfile.apply_to_values sem rf f) n = none\n:= begin\n intros,\n split,\n {\n apply regfile.induction rf,\n {\n intros H, rw regfile.empty_apply_empty, assumption\n },\n {\n intros rf Hind n1 v1 H,\n have HNAME: decidable(n1 = n), apply_instance,\n cases HNAME,\n {\n rw regfile.update_get_nomatch at H,\n have H' := Hind H,\n rw regfile.apply_update_comm,\n rw regfile.update_get_nomatch, assumption,\n any_goals { apply neq_symm, assumption }\n },\n {\n rw regfile.update_get_match at H,\n injection H, rw HNAME\n }\n }\n },\n {\n apply regfile.induction rf,\n {\n intros H, rw regfile.empty_apply_empty at H, assumption\n },\n {\n intros rf Hind n1 v1 H,\n have HNAME: decidable(n1 = n), apply_instance,\n cases HNAME,\n {\n rw regfile.apply_update_comm at H,\n rw regfile.update_get_nomatch at H,\n have H' := Hind H,\n rw regfile.update_get_nomatch, assumption,\n any_goals { apply neq_symm, assumption }\n },\n {\n rw regfile.apply_update_comm at H,\n rw regfile.update_get_match at H,\n injection H, rw HNAME\n }\n }\n }\nend\n\nlemma irstate.updatereg_getreg_match_smt: ∀ (rname rname2:string) v st\n (Hnameeq: rname2 = rname),\n irstate.getreg irsem_smt (irstate.updatereg irsem_smt st rname v) rname2 = some v\n:= begin\n intros,\n unfold irstate.getreg,\n unfold irstate.updatereg,\n simp,\n apply regfile.update_get_match, assumption\nend\n\nlemma irstate.notin_regnames_getreg_smt: ∀ (rname:string) (s:irstate irsem_smt)\n (H:rname ∉ irstate.regnames irsem_smt s),\n irstate.getreg irsem_smt s rname = none\n:= begin\n intros,\n unfold irstate.getreg,\n unfold irstate.regnames at *,\n cases s,\n simp,\n rw regfile.reg_notin_regnames_get_none,\n apply H\nend\n\nlemma irstate.getreg_diff_smt: ∀ ss (n1 n2:string) v\n (H1: irstate.getreg irsem_smt ss n1 = none)\n (H2: irstate.getreg irsem_smt ss n2 = some v),\n n1 ≠ n2\n:= begin\n intros,\n intros HEQ,\n rw HEQ at H1,\n rw H1 at H2,\n cases H2\nend\n\nlemma irstate.updatereg_getreg_nomatch_smt: ∀ ss ss' (n1 n2:string) v v'\n (H1: irstate.getreg irsem_smt ss n1 = v)\n (H2: ss' = irstate.updatereg irsem_smt ss n2 v')\n (HDIFF:n1 ≠ n2),\n irstate.getreg irsem_smt ss' n1 = v\n:= begin\n intros,\n rw H2,\n unfold irstate.getreg at *,\n unfold irstate.updatereg at *,\n simp,\n rw regfile.update_get_nomatch, assumption, assumption\nend\n\nlemma irstate.updatereg_getreg_nomatch_inv_smt: ∀ ss ss' (n1 n2:string) v v'\n (H1: irstate.getreg irsem_smt ss' n1 = v)\n (H2: ss' = irstate.updatereg irsem_smt ss n2 v')\n (HDIFF:n1 ≠ n2),\n irstate.getreg irsem_smt ss n1 = v\n:= begin\n intros,\n rw H2 at H1,\n unfold irstate.getreg at *,\n unfold irstate.updatereg at *,\n simp at H1,\n rw regfile.update_get_nomatch at H1, assumption, assumption\nend\n\nlemma irstate.getreg_empty_none_smt: ∀ s n\n (H:irstate.regnames irsem_smt s = []),\n irstate.getreg irsem_smt s n = none\n:= begin\n intros,\n cases s with ub rf,\n unfold irstate.regnames at H,\n unfold regfile.regnames at H,\n simp at H,\n have H' : rf = [],\n { apply list.map_nil, apply H },\n rw H', unfold irstate.getreg, unfold regfile.get, simp,\n delta regfile.get._match_1, simp\nend\n\nlemma irstate.getub_equiv: ∀ {ss:irstate_smt} {se:irstate_exec}\n {sret} {eret} (HSTEQ:irstate_equiv ss se)\n (HSSRET: sret = ss.getub irsem_smt)\n (HSERET: eret = se.getub irsem_exec),\n b_equiv sret eret\n:= begin\n intros,\n cases HSTEQ,\n any_goals { -- irstate_equiv.noub\n unfold irstate.getub at HSSRET,\n unfold irstate.getub at HSERET,\n simp at HSSRET, simp at HSERET,\n subst HSSRET, subst HSERET, assumption\n }\nend\n\nlemma irstate.getub_updatereg_smt: ∀ (s:irstate irsem_smt) n v,\n irstate.getub irsem_smt (irstate.updatereg irsem_smt s n v) = irstate.getub irsem_smt s\n:= begin\n intros,\n unfold irstate.updatereg,\n refl\nend\n\nlemma irstate.getreg_apply_some_smt: ∀ (s:irstate irsem_smt) (f:valty_smt → valty_smt) v n\n (H: irstate.getreg irsem_smt s n = some v),\n irstate.getreg irsem_smt (irstate.apply_to_values irsem_smt s f) n = some (f v)\n:= begin\n intros,\n cases s,\n unfold irstate.apply_to_values,\n unfold irstate.getreg,\n apply regfile.reg_apply_some,\n apply H\nend\n\nlemma irstate.getreg_apply_none_smt: ∀ (s:irstate irsem_smt) (f:valty_smt → valty_smt) n,\n irstate.getreg irsem_smt s n = none ↔\n irstate.getreg irsem_smt (irstate.apply_to_values irsem_smt s f) n = none\n:= begin\n intros,\n split,\n {\n intros H, cases s,\n unfold irstate.apply_to_values,\n unfold irstate.getreg,\n rw ← regfile.reg_apply_none,\n apply H\n },\n {\n intros H, cases s,\n unfold irstate.apply_to_values at H,\n unfold irstate.getreg,\n rw regfile.reg_apply_none,\n apply H\n }\nend\n\nlemma irstate.empty_apply_empty_smt: ∀ f,\n irstate.apply_to_values irsem_smt (irstate.empty irsem_smt) f = irstate.empty irsem_smt\n:= begin\n intros,\n unfold irstate.empty,\n refl\nend\n\nlemma irstate.getub_apply_to_values: ∀ (s:irstate irsem_smt) f,\n irstate.getub irsem_smt (irstate.apply_to_values irsem_smt s f) =\n irstate.getub irsem_smt s\n:= begin\n intros,\n unfold irstate.getub,\n unfold irstate.apply_to_values\nend\n\nlemma irstate.setub_apply_to_values: ∀ (s:irstate irsem_smt) f b,\n irstate.setub irsem_smt (irstate.apply_to_values irsem_smt s f) b =\n irstate.apply_to_values irsem_smt (irstate.setub irsem_smt s b) f\n:= begin\n intros,\n unfold irstate.setub,\n unfold irstate.apply_to_values\nend\n\n\nend spec", "meta": {"author": "microsoft", "repo": "AliveInLean", "sha": "34370c2c15aa69f010d97b8d38e9e1955e9e387d", "save_path": "github-repos/lean/microsoft-AliveInLean", "path": "github-repos/lean/microsoft-AliveInLean/AliveInLean-34370c2c15aa69f010d97b8d38e9e1955e9e387d/src/spec/irstate.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.07807816621756582, "lm_q1q2_score": 0.03781950873265692}} {"text": "/-\nCopyright (c) 2020 Scott Morrison. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Scott Morrison\n-/\nimport category_theory.limits.types\nimport category_theory.limits.shapes.products\nimport category_theory.limits.shapes.binary_products\nimport category_theory.limits.shapes.terminal\n\n/-!\n# Special shapes for limits in `Type`.\n\nThe general shape (co)limits defined in `category_theory.limits.types`\nare intended for use through the limits API,\nand the actual implementation should mostly be considered \"sealed\".\n\nIn this file, we provide definitions of the \"standard\" special shapes of limits in `Type`,\ngiving the expected definitional implementation:\n* the terminal object is `punit`\n* the binary product of `X` and `Y` is `X × Y`\n* the product of a family `f : J → Type` is `Π j, f j`\n* the binary coproduct of `X` and `Y` is the sum type `X ⊕ Y`\n* the equalizer of a pair of maps `(g, h)` is the subtype `{x : Y // g x = h x}`\n* the pullback of `f : X ⟶ Z` and `g : Y ⟶ Z` is the subtype `{ p : X × Y // f p.1 = g p.2 }`\n of the product\n\nBecause these are not intended for use with the `has_limit` API,\nwe instead construct terms of `limit_data`.\n\nAs an example, when setting up the monoidal category structure on `Type`\nwe use the `types_has_terminal` and `types_has_binary_products` instances.\n-/\n\nuniverses u\n\nopen category_theory\nopen category_theory.limits\n\nnamespace category_theory.limits.types\n\n/-- A restatement of `types.lift_π_apply` that uses `pi.π` and `pi.lift`. -/\n@[simp]\nlemma pi_lift_π_apply\n {β : Type u} (f : β → Type u) {P : Type u} (s : Π b, P ⟶ f b) (b : β) (x : P) :\n (pi.π f b : (∏ f) → f b) (@pi.lift β _ _ f _ P s x) = s b x :=\ncongr_fun (limit.lift_π (fan.mk P s) b) x\n\n/-- A restatement of `types.map_π_apply` that uses `pi.π` and `pi.map`. -/\n@[simp]\nlemma pi_map_π_apply {β : Type u} {f g : β → Type u} (α : Π j, f j ⟶ g j) (b : β) (x) :\n (pi.π g b : (∏ g) → g b) (pi.map α x) = α b ((pi.π f b : (∏ f) → f b) x) :=\nlimit.map_π_apply _ _ _\n\n/-- The category of types has `punit` as a terminal object. -/\ndef terminal_limit_cone : limits.limit_cone (functor.empty (Type u)) :=\n{ cone :=\n { X := punit,\n π := by tidy, },\n is_limit := by tidy, }\n\n/-- The category of types has `pempty` as an initial object. -/\ndef initial_limit_cone : limits.colimit_cocone (functor.empty (Type u)) :=\n{ cocone :=\n { X := pempty,\n ι := by tidy, },\n is_colimit := by tidy, }\n\nopen category_theory.limits.walking_pair\n\n/-- The product type `X × Y` forms a cone for the binary product of `X` and `Y`. -/\n-- We manually generate the other projection lemmas since the simp-normal form for the legs is\n-- otherwise not created correctly.\n@[simps X]\ndef binary_product_cone (X Y : Type u) : binary_fan X Y :=\nbinary_fan.mk prod.fst prod.snd\n\n@[simp]\nlemma binary_product_cone_fst (X Y : Type u) :\n (binary_product_cone X Y).fst = prod.fst :=\nrfl\n@[simp]\nlemma binary_product_cone_snd (X Y : Type u) :\n (binary_product_cone X Y).snd = prod.snd :=\nrfl\n\n/-- The product type `X × Y` is a binary product for `X` and `Y`. -/\n@[simps]\ndef binary_product_limit (X Y : Type u) : is_limit (binary_product_cone X Y) :=\n{ lift := λ (s : binary_fan X Y) x, (s.fst x, s.snd x),\n fac' := λ s j, walking_pair.cases_on j rfl rfl,\n uniq' := λ s m w, funext $ λ x, prod.ext (congr_fun (w left) x) (congr_fun (w right) x) }\n\n/--\nThe category of types has `X × Y`, the usual cartesian product,\nas the binary product of `X` and `Y`.\n-/\n@[simps]\ndef binary_product_limit_cone (X Y : Type u) : limits.limit_cone (pair X Y) :=\n⟨_, binary_product_limit X Y⟩\n\n/-- The functor which sends `X, Y` to the product type `X × Y`. -/\n-- We add the option `type_md` to tell `@[simps]` to not treat homomorphisms `X ⟶ Y` in `Type*` as\n-- a function type\n@[simps {type_md := reducible}]\ndef binary_product_functor : Type u ⥤ Type u ⥤ Type u :=\n{ obj := λ X,\n { obj := λ Y, X × Y,\n map := λ Y₁ Y₂ f, (binary_product_limit X Y₂).lift (binary_fan.mk prod.fst (prod.snd ≫ f)) },\n map := λ X₁ X₂ f,\n { app := λ Y, (binary_product_limit X₂ Y).lift (binary_fan.mk (prod.fst ≫ f) prod.snd) } }\n\n/--\nThe product functor given by the instance `has_binary_products (Type u)` is isomorphic to the\nexplicit binary product functor given by the product type.\n-/\nnoncomputable def binary_product_iso_prod : binary_product_functor ≅ (prod.functor : Type u ⥤ _) :=\nbegin\n apply nat_iso.of_components (λ X, _) _,\n { apply nat_iso.of_components (λ Y, _) _,\n { exact ((limit.is_limit _).cone_point_unique_up_to_iso (binary_product_limit X Y)).symm },\n { intros Y₁ Y₂ f,\n ext1;\n simp } },\n { intros X₁ X₂ g,\n ext : 3;\n simp }\nend\n\n/-- The sum type `X ⊕ Y` forms a cocone for the binary coproduct of `X` and `Y`. -/\n@[simps]\ndef binary_coproduct_cocone (X Y : Type u) : cocone (pair X Y) :=\nbinary_cofan.mk sum.inl sum.inr\n\n/-- The sum type `X ⊕ Y` is a binary coproduct for `X` and `Y`. -/\n@[simps]\ndef binary_coproduct_colimit (X Y : Type u) : is_colimit (binary_coproduct_cocone X Y) :=\n{ desc := λ (s : binary_cofan X Y), sum.elim s.inl s.inr,\n fac' := λ s j, walking_pair.cases_on j rfl rfl,\n uniq' := λ s m w, funext $ λ x, sum.cases_on x (congr_fun (w left)) (congr_fun (w right)) }\n\n/--\nThe category of types has `X ⊕ Y`,\nas the binary coproduct of `X` and `Y`.\n-/\ndef binary_coproduct_colimit_cocone (X Y : Type u) : limits.colimit_cocone (pair X Y) :=\n⟨_, binary_coproduct_colimit X Y⟩\n\n/--\nThe category of types has `Π j, f j` as the product of a type family `f : J → Type`.\n-/\ndef product_limit_cone {J : Type u} (F : J → Type u) : limits.limit_cone (discrete.functor F) :=\n{ cone :=\n { X := Π j, F j,\n π := { app := λ j f, f j }, },\n is_limit :=\n { lift := λ s x j, s.π.app j x,\n uniq' := λ s m w, funext $ λ x, funext $ λ j, (congr_fun (w j) x : _) } }\n\n/--\nThe category of types has `Σ j, f j` as the coproduct of a type family `f : J → Type`.\n-/\ndef coproduct_colimit_cocone {J : Type u} (F : J → Type u) :\n limits.colimit_cocone (discrete.functor F) :=\n{ cocone :=\n { X := Σ j, F j,\n ι :=\n { app := λ j x, ⟨j, x⟩ }, },\n is_colimit :=\n { desc := λ s x, s.ι.app x.1 x.2,\n uniq' := λ s m w,\n begin\n ext ⟨j, x⟩,\n have := congr_fun (w j) x,\n exact this,\n end }, }\n\nsection fork\nvariables {X Y Z : Type u} (f : X ⟶ Y) {g h : Y ⟶ Z} (w : f ≫ g = f ≫ h)\n\n/--\nShow the given fork in `Type u` is an equalizer given that any element in the \"difference kernel\"\ncomes from `X`.\nThe converse of `unique_of_type_equalizer`.\n-/\nnoncomputable def type_equalizer_of_unique (t : ∀ (y : Y), g y = h y → ∃! (x : X), f x = y) :\n is_limit (fork.of_ι _ w) :=\nfork.is_limit.mk' _ $ λ s,\nbegin\n refine ⟨λ i, _, _, _⟩,\n { apply classical.some (t (s.ι i) _),\n apply congr_fun s.condition i },\n { ext i,\n apply (classical.some_spec (t (s.ι i) _)).1 },\n { intros m hm,\n ext i,\n apply (classical.some_spec (t (s.ι i) _)).2,\n apply congr_fun hm i },\nend\n\n/-- The converse of `type_equalizer_of_unique`. -/\nlemma unique_of_type_equalizer (t : is_limit (fork.of_ι _ w)) (y : Y) (hy : g y = h y) :\n ∃! (x : X), f x = y :=\nbegin\n let y' : punit ⟶ Y := λ _, y,\n have hy' : y' ≫ g = y' ≫ h := funext (λ _, hy),\n refine ⟨(fork.is_limit.lift' t _ hy').1 ⟨⟩, congr_fun (fork.is_limit.lift' t y' _).2 ⟨⟩, _⟩,\n intros x' hx',\n suffices : (λ (_ : punit), x') = (fork.is_limit.lift' t y' hy').1,\n rw ← this,\n apply fork.is_limit.hom_ext t,\n ext ⟨⟩,\n apply hx'.trans (congr_fun (fork.is_limit.lift' t _ hy').2 ⟨⟩).symm,\nend\n\nlemma type_equalizer_iff_unique :\n nonempty (is_limit (fork.of_ι _ w)) ↔ (∀ (y : Y), g y = h y → ∃! (x : X), f x = y) :=\n⟨λ i, unique_of_type_equalizer _ _ (classical.choice i), λ k, ⟨type_equalizer_of_unique f w k⟩⟩\n\n/-- Show that the subtype `{x : Y // g x = h x}` is an equalizer for the pair `(g,h)`. -/\ndef equalizer_limit : limits.limit_cone (parallel_pair g h) :=\n{ cone := fork.of_ι (subtype.val : {x : Y // g x = h x} → Y) (funext subtype.prop),\n is_limit := fork.is_limit.mk' _ $ λ s,\n ⟨λ i, ⟨s.ι i, by apply congr_fun s.condition i⟩,\n rfl,\n λ m hm, funext $ λ x, subtype.ext (congr_fun hm x)⟩ }\n\nend fork\n\nsection pullback\nopen category_theory.limits.walking_pair\nopen category_theory.limits.walking_cospan\nopen category_theory.limits.walking_cospan.hom\n\nvariables {W X Y Z : Type u}\nvariables (f : X ⟶ Z) (g : Y ⟶ Z)\n\n/--\nThe usual explicit pullback in the category of types, as a subtype of the product.\nThe full `limit_cone` data is bundled as `pullback_limit_cone f g`.\n-/\n@[nolint has_inhabited_instance]\nabbreviation pullback_obj : Type u := { p : X × Y // f p.1 = g p.2 }\n\n-- `pullback_obj f g` comes with a coercion to the product type `X × Y`.\nexample (p : pullback_obj f g) : X × Y := p\n\n/--\nThe explicit pullback cone on `pullback_obj f g`.\nThis is bundled with the `is_limit` data as `pullback_limit_cone f g`.\n-/\nabbreviation pullback_cone : limits.pullback_cone f g :=\npullback_cone.mk (λ p : pullback_obj f g, p.1.1) (λ p, p.1.2) (funext (λ p, p.2))\n\n/--\nThe explicit pullback in the category of types, bundled up as a `limit_cone`\nfor given `f` and `g`.\n-/\n@[simps]\ndef pullback_limit_cone (f : X ⟶ Z) (g : Y ⟶ Z) : limits.limit_cone (cospan f g) :=\n{ cone := pullback_cone f g,\n is_limit := pullback_cone.is_limit_aux _\n (λ s x, ⟨⟨s.fst x, s.snd x⟩, congr_fun s.condition x⟩)\n (by tidy)\n (by tidy)\n (λ s m w, funext $ λ x, subtype.ext $\n prod.ext (congr_fun (w walking_cospan.left) x)\n (congr_fun (w walking_cospan.right) x)) }\n\n/--\nThe pullback cone given by the instance `has_pullbacks (Type u)` is isomorphic to the\nexplicit pullback cone given by `pullback_limit_cone`.\n-/\nnoncomputable def pullback_cone_iso_pullback : limit.cone (cospan f g) ≅ pullback_cone f g :=\n(limit.is_limit _).unique_up_to_iso (pullback_limit_cone f g).is_limit\n\n/--\nThe pullback given by the instance `has_pullbacks (Type u)` is isomorphic to the\nexplicit pullback object given by `pullback_limit_obj`.\n-/\nnoncomputable def pullback_iso_pullback : pullback f g ≅ pullback_obj f g :=\n(cones.forget _).map_iso $ pullback_cone_iso_pullback f g\n\n@[simp] lemma pullback_iso_pullback_hom_fst (p : pullback f g) :\n ((pullback_iso_pullback f g).hom p : X × Y).fst = (pullback.fst : _ ⟶ X) p :=\ncongr_fun ((pullback_cone_iso_pullback f g).hom.w left) p\n\n@[simp] lemma pullback_iso_pullback_hom_snd (p : pullback f g) :\n ((pullback_iso_pullback f g).hom p : X × Y).snd = (pullback.snd : _ ⟶ Y) p :=\ncongr_fun ((pullback_cone_iso_pullback f g).hom.w right) p\n\n@[simp] lemma pullback_iso_pullback_inv_fst :\n (pullback_iso_pullback f g).inv ≫ pullback.fst = (λ p, (p : X × Y).fst) :=\n(pullback_cone_iso_pullback f g).inv.w left\n\n@[simp] lemma pullback_iso_pullback_inv_snd :\n (pullback_iso_pullback f g).inv ≫ pullback.snd = (λ p, (p : X × Y).snd) :=\n(pullback_cone_iso_pullback f g).inv.w right\n\nend pullback\n\nend category_theory.limits.types\n", "meta": {"author": "JLimperg", "repo": "aesop3", "sha": "a4a116f650cc7403428e72bd2e2c4cda300fe03f", "save_path": "github-repos/lean/JLimperg-aesop3", "path": "github-repos/lean/JLimperg-aesop3/aesop3-a4a116f650cc7403428e72bd2e2c4cda300fe03f/src/category_theory/limits/shapes/types.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4073334000459302, "lm_q2_score": 0.09268778803792116, "lm_q1q2_score": 0.03775483184422292}} {"text": "/-\nCopyright (c) 2017 Mario Carneiro. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Mario Carneiro\n-/\nimport tactic.core\n\n/-!\n# The `alias` command\n\nThis file defines an `alias` command, which can be used to create copies\nof a theorem or definition with different names.\n\nSyntax:\n\n```lean\n/-- doc string -/\nalias my_theorem ← alias1 alias2 ...\n```\n\nThis produces defs or theorems of the form:\n\n```lean\n/-- doc string -/\n@[alias] theorem alias1 : := my_theorem\n\n/-- doc string -/\n@[alias] theorem alias2 : := my_theorem\n```\n\nIff alias syntax:\n\n```lean\nalias A_iff_B ↔ B_of_A A_of_B\nalias A_iff_B ↔ ..\n```\n\nThis gets an existing biconditional theorem `A_iff_B` and produces\nthe one-way implications `B_of_A` and `A_of_B` (with no change in\nimplicit arguments). A blank `_` can be used to avoid generating one direction.\nThe `..` notation attempts to generate the 'of'-names automatically when the\ninput theorem has the form `A_iff_B` or `A_iff_B_left` etc.\n-/\n\nopen lean.parser tactic interactive\n\nnamespace tactic.alias\n\n/-- An alias can be in one of three forms -/\n@[derive has_reflect]\nmeta inductive target\n| plain : name → target\n| forward : name → target\n| backwards : name → target\n\n/-- The name underlying an alias target -/\nmeta def target.to_name : target → name\n| (target.plain n) := n\n| (target.forward n) := n\n| (target.backwards n) := n\n\n/-- The docstring for an alias. Used by `alias` _and_ by `to_additive` -/\nmeta def target.to_string : target → string\n| (target.plain n) := sformat!\"**Alias** of `{n}`.\"\n| (target.forward n) := sformat!\"**Alias** of the forward direction of `{n}`.\"\n| (target.backwards n) := sformat!\"**Alias** of the reverse direction of `{n}`.\"\n\n/-- An auxiliary attribute which is placed on definitions created by the `alias` command. -/\n@[user_attribute] meta def alias_attr : user_attribute unit target :=\n{ name := `alias, descr := \"This definition is an alias of another.\", parser := failed }\n\n/-- The core tactic which handles `alias d ← al`. Creates an alias `al` for declaration `d`. -/\nmeta def alias_direct (doc : option string) (d : declaration) (al : name) : tactic unit :=\ndo updateex_env $ λ env,\n env.add (match d.to_definition with\n | declaration.defn n ls t _ _ _ :=\n declaration.defn al ls t (expr.const n (level.param <$> ls))\n reducibility_hints.abbrev tt\n | declaration.thm n ls t _ :=\n declaration.thm al ls t $ task.pure $ expr.const n (level.param <$> ls)\n | _ := undefined\n end),\n let target := target.plain d.to_name,\n alias_attr.set al target tt,\n add_doc_string al (doc.get_or_else target.to_string)\n\n/-- Given a proof of `Π x y z, a ↔ b`, produces a proof of `Π x y z, a → b` or `Π x y z, b → a`\n(depending on whether `iffmp` is `iff.mp` or `iff.mpr`). The variable `f` supplies the proof,\nunder the specified number of binders. -/\nmeta def mk_iff_mp_app (iffmp : name) : expr → (ℕ → expr) → tactic expr\n| (expr.pi n bi e t) f := expr.lam n bi e <$> mk_iff_mp_app t (λ n, f (n+1) (expr.var n))\n| `(%%a ↔ %%b) f := pure $ @expr.const tt iffmp [] a b (f 0)\n| _ f := fail \"Target theorem must have the form `Π x y z, a ↔ b`\"\n\n/-- The core tactic which handles `alias d ↔ al _` or `alias d ↔ _ al`. `ns` is the current\nnamespace, and `is_forward` is true if this is the forward implication (the first form). -/\nmeta def alias_iff (doc : option string)\n (d : declaration) (ns al : name) (is_forward : bool) : tactic unit :=\nif al = `_ then skip else\n let al := ns.append_namespace al in\n (get_decl al >> skip) <|> do\n let ls := d.univ_params,\n let t := d.type,\n let target := if is_forward then target.forward d.to_name else target.backwards d.to_name,\n let iffmp := if is_forward then `iff.mp else `iff.mpr,\n v ← mk_iff_mp_app iffmp t (λ_, expr.const d.to_name (level.param <$> ls)),\n t' ← infer_type v,\n updateex_env $ λ env, env.add (declaration.thm al ls t' $ task.pure v),\n alias_attr.set al target tt,\n add_doc_string al (doc.get_or_else target.to_string)\n\n/-- Get the default names for left/right to be used by `alias d ↔ ..`. -/\nmeta def make_left_right : name → tactic (name × name)\n| (name.mk_string s p) := do\n let buf : char_buffer := s.to_char_buffer,\n let parts := s.split_on '_',\n (left, _::right) ← pure $ parts.span (≠ \"iff\"),\n let pfx (a b : string) := a.to_list.is_prefix_of b.to_list,\n (suffix', right') ← pure $ right.reverse.span (λ s, pfx \"left\" s ∨ pfx \"right\" s),\n let right := right'.reverse,\n let suffix := suffix'.reverse,\n pure (p <.> \"_\".intercalate (right ++ \"of\" :: left ++ suffix),\n p <.> \"_\".intercalate (left ++ \"of\" :: right ++ suffix))\n| _ := failed\n\n/--\nThe `alias` command can be used to create copies\nof a theorem or definition with different names.\n\nSyntax:\n\n```lean\n/-- doc string -/\nalias my_theorem ← alias1 alias2 ...\n```\n\nThis produces defs or theorems of the form:\n\n```lean\n/-- doc string -/\n@[alias] theorem alias1 : := my_theorem\n\n/-- doc string -/\n@[alias] theorem alias2 : := my_theorem\n```\n\nIff alias syntax:\n\n```lean\nalias A_iff_B ↔ B_of_A A_of_B\nalias A_iff_B ↔ ..\n```\n\nThis gets an existing biconditional theorem `A_iff_B` and produces\nthe one-way implications `B_of_A` and `A_of_B` (with no change in\nimplicit arguments). A blank `_` can be used to avoid generating one direction.\nThe `..` notation attempts to generate the 'of'-names automatically when the\ninput theorem has the form `A_iff_B` or `A_iff_B_left` etc.\n-/\n@[user_command] meta def alias_cmd (meta_info : decl_meta_info)\n (_ : parse $ tk \"alias\") : lean.parser unit :=\ndo old ← ident,\n d ← (do old ← resolve_constant old, get_decl old) <|>\n fail (\"declaration \" ++ to_string old ++ \" not found\"),\n ns ← get_current_namespace,\n let doc := meta_info.doc_string,\n do\n { tk \"←\" <|> tk \"<-\",\n aliases ← many ident,\n ↑(aliases.mmap' $ λ al, alias_direct doc d (ns.append_namespace al)) } <|>\n do\n { tk \"↔\" <|> tk \"<->\",\n (left, right) ←\n mcond ((tk \"..\" >> pure tt) <|> pure ff)\n (make_left_right old <|> fail \"invalid name for automatic name generation\")\n (prod.mk <$> types.ident_ <*> types.ident_),\n alias_iff doc d ns left tt,\n alias_iff doc d ns right ff }\n\nadd_tactic_doc\n{ name := \"alias\",\n category := doc_category.cmd,\n decl_names := [`tactic.alias.alias_cmd],\n tags := [\"renaming\"] }\n\n/-- Given a definition, look up the definition that it is an alias of.\nReturns `none` if this defintion is not an alias. -/\nmeta def get_alias_target (n : name) : tactic (option target) :=\ndo tt ← has_attribute' `alias n | pure none,\n v ← alias_attr.get_param n,\n pure $ some v\n\nend tactic.alias\n", "meta": {"author": "leanprover-community", "repo": "mathlib", "sha": "5e526d18cea33550268dcbbddcb822d5cde40654", "save_path": "github-repos/lean/leanprover-community-mathlib", "path": "github-repos/lean/leanprover-community-mathlib/mathlib-5e526d18cea33550268dcbbddcb822d5cde40654/src/tactic/alias.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3380771241500058, "lm_q2_score": 0.1112412168201335, "lm_q1q2_score": 0.037608110669497985}} {"text": "/-\nCopyright (c) 2020 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthor: Leonardo de Moura, Sebastian Ullrich\n-/\nprelude\nimport Init.Core\n\nuniverse u v w\n\n@[reducible]\ndef Functor.mapRev {f : Type u → Type v} [Functor f] {α β : Type u} : f α → (α → β) → f β :=\n fun a f => f <$> a\n\ninfixr:100 \" <&> \" => Functor.mapRev\n\n@[always_inline, inline]\ndef Functor.discard {f : Type u → Type v} {α : Type u} [Functor f] (x : f α) : f PUnit :=\n Functor.mapConst PUnit.unit x\n\nexport Functor (discard)\n\nclass Alternative (f : Type u → Type v) extends Applicative f : Type (max (u+1) v) where\n failure : {α : Type u} → f α\n orElse : {α : Type u} → f α → (Unit → f α) → f α\n\ninstance (f : Type u → Type v) (α : Type u) [Alternative f] : OrElse (f α) := ⟨Alternative.orElse⟩\n\nvariable {f : Type u → Type v} [Alternative f] {α : Type u}\n\nexport Alternative (failure)\n\n@[always_inline, inline] def guard {f : Type → Type v} [Alternative f] (p : Prop) [Decidable p] : f Unit :=\n if p then pure () else failure\n\n@[always_inline, inline] def optional (x : f α) : f (Option α) :=\n some <$> x <|> pure none\n\nclass ToBool (α : Type u) where\n toBool : α → Bool\n\nexport ToBool (toBool)\n\ninstance : ToBool Bool where\n toBool b := b\n\n@[macro_inline] def bool {β : Type u} {α : Type v} [ToBool β] (f t : α) (b : β) : α :=\n match toBool b with\n | true => t\n | false => f\n\n@[macro_inline] def orM {m : Type u → Type v} {β : Type u} [Monad m] [ToBool β] (x y : m β) : m β := do\n let b ← x\n match toBool b with\n | true => pure b\n | false => y\n\ninfixr:30 \" <||> \" => orM\n\n@[macro_inline] def andM {m : Type u → Type v} {β : Type u} [Monad m] [ToBool β] (x y : m β) : m β := do\n let b ← x\n match toBool b with\n | true => y\n | false => pure b\n\ninfixr:35 \" <&&> \" => andM\n\n@[macro_inline] def notM {m : Type → Type v} [Applicative m] (x : m Bool) : m Bool :=\n not <$> x\n\n/-!\n# How `MonadControl` works\n\nThere is a [tutorial by Alexis King](https://lexi-lambda.github.io/blog/2019/09/07/demystifying-monadbasecontrol/) that this docstring is based on.\n\nSuppose we have `foo : ∀ α, IO α → IO α` and `bar : StateT σ IO β` (ie, `bar : σ → IO (σ × β)`).\nWe might want to 'map' `bar` by `foo`. Concretely we would write this as:\n\n```lean\nopaque foo : ∀ {α}, IO α → IO α\nopaque bar : StateT σ IO β\n\ndef mapped_foo : StateT σ IO β := do\n let s ← get\n let (b, s') ← liftM <| foo <| StateT.run bar s\n set s'\n return b\n```\n\nThis is fine but it's not going to generalise, what if we replace `StateT Nat IO` with a large tower of monad transformers?\nWe would have to rewrite the above to handle each of the `run` functions for each transformer in the stack.\n\nIs there a way to generalise `run` as a kind of inverse of `lift`?\nWe have `lift : m α → StateT σ m α` for all `m`, but we also need to 'unlift' the state.\nBut `unlift : StateT σ IO α → IO α` can't be implemented. So we need something else.\n\nIf we look at the definition of `mapped_foo`, we see that `lift <| foo <| StateT.run bar s`\nhas the type `IO (σ × β)`. The key idea is that `σ × β` contains all of the information needed to reconstruct the state and the new value.\n\nNow lets define some values to generalise `mapped_foo`:\n- Write `IO (σ × β)` as `IO (stM β)`\n- Write `StateT.run . s` as `mapInBase : StateT σ IO α → IO (stM β)`\n- Define `restoreM : IO (stM α) → StateT σ IO α` as below\n\n```lean\ndef stM (α : Type) := α × σ\n\ndef restoreM (x : IO (stM α)) : StateT σ IO α := do\n let (a,s) ← liftM x\n set s\n return a\n```\n\nTo get:\n\n```lean\ndef mapped_foo' : StateT σ IO β := do\n let s ← get\n let mapInBase := fun z => StateT.run z s\n restoreM <| foo <| mapInBase bar\n```\n\nand finally define\n\n```lean\ndef control {α : Type}\n (f : ({β : Type} → StateT σ IO β → IO (stM β)) → IO (stM α))\n : StateT σ IO α := do\n let s ← get\n let mapInBase := fun {β} (z : StateT σ IO β) => StateT.run z s\n let r : IO (stM α) := f mapInBase\n restoreM r\n```\n\nNow we can write `mapped_foo` as:\n\n```lean\ndef mapped_foo'' : StateT σ IO β :=\n control (fun mapInBase => foo (mapInBase bar))\n```\n\nThe core idea of `mapInBase` is that given any `β`, it runs an instance of\n`StateT σ IO β` and 'packages' the result and state as `IO (stM β)` so that it can be piped through `foo`.\nOnce it's been through `foo` we can then unpack the state again with `restoreM`.\nHence we can apply `foo` to `bar` without losing track of the state.\n\nHere `stM β = σ × β` is the 'packaged result state', but we can generalise:\nif we have a tower `StateT σ₁ <| StateT σ₂ <| IO`, then the\ncomposite packaged state is going to be `stM₁₂ β := σ₁ × σ₂ × β` or `stM₁₂ := stM₁ ∘ stM₂`.\n\n`MonadControl m n` means that when programming in the monad `n`,\nwe can switch to a base monad `m` using `control`, just like with `liftM`.\nIn contrast to `liftM`, however, we also get a function `runInBase` that\nallows us to \"lower\" actions in `n` into `m`.\nThis is really useful when we have large towers of monad transformers, as we do in the metaprogramming library.\n\nFor example there is a function `withNewMCtxDepthImp : MetaM α → MetaM α` that runs the input monad instance\nin a new nested metavariable context. We can lift this to `withNewMctxDepth : n α → n α` using `MonadControlT MetaM n`\n(`MonadControlT` is the transitive closure of `MonadControl`).\nWhich means that we can also run `withNewMctxDepth` in the `Tactic` monad without needing to\nfaff around with lifts and all the other boilerplate needed in `mapped_foo`.\n\n## Relationship to `MonadFunctor`\n\nA stricter form of `MonadControl` is `MonadFunctor`, which defines\n`monadMap {α} : (∀ {β}, m β → m β) → n α → n α`. Using `monadMap` it is also possible to define `mapped_foo` above.\nHowever there are some mappings which can't be derived using `MonadFunctor`. For example:\n\n```lean,ignore\n @[inline] def map1MetaM [MonadControlT MetaM n] [Monad n] (f : forall {α}, (β → MetaM α) → MetaM α) {α} (k : β → n α) : n α :=\n control fun runInBase => f fun b => runInBase <| k b\n\n @[inline] def map2MetaM [MonadControlT MetaM n] [Monad n] (f : forall {α}, (β → γ → MetaM α) → MetaM α) {α} (k : β → γ → n α) : n α :=\n control fun runInBase => f fun b c => runInBase <| k b c\n```\n\nIn `monadMap`, we can only 'run in base' a single computation in `n` into the base monad `m`.\nUsing `control` means that `runInBase` can be used multiple times.\n\n-/\n\n\n/-- MonadControl is a way of stating that the monad `m` can be 'run inside' the monad `n`.\n\nThis is the same as [`MonadBaseControl`](https://hackage.haskell.org/package/monad-control-1.0.3.1/docs/Control-Monad-Trans-Control.html#t:MonadBaseControl) in Haskell.\nTo learn about `MonadControl`, see the comment above this docstring.\n\n-/\nclass MonadControl (m : Type u → Type v) (n : Type u → Type w) where\n stM : Type u → Type u\n liftWith : {α : Type u} → (({β : Type u} → n β → m (stM β)) → m α) → n α\n restoreM : {α : Type u} → m (stM α) → n α\n\n/-- Transitive closure of MonadControl. -/\nclass MonadControlT (m : Type u → Type v) (n : Type u → Type w) where\n stM : Type u → Type u\n liftWith : {α : Type u} → (({β : Type u} → n β → m (stM β)) → m α) → n α\n restoreM {α : Type u} : stM α → n α\n\nexport MonadControlT (stM liftWith restoreM)\n\n@[always_inline]\ninstance (m n o) [MonadControl n o] [MonadControlT m n] : MonadControlT m o where\n stM α := stM m n (MonadControl.stM n o α)\n liftWith f := MonadControl.liftWith fun x₂ => liftWith fun x₁ => f (x₁ ∘ x₂)\n restoreM := MonadControl.restoreM ∘ restoreM\n\ninstance (m : Type u → Type v) [Pure m] : MonadControlT m m where\n stM α := α\n liftWith f := f fun x => x\n restoreM x := pure x\n\n@[always_inline, inline]\ndef controlAt (m : Type u → Type v) {n : Type u → Type w} [MonadControlT m n] [Bind n] {α : Type u}\n (f : ({β : Type u} → n β → m (stM m n β)) → m (stM m n α)) : n α :=\n liftWith f >>= restoreM\n\n@[always_inline, inline]\ndef control {m : Type u → Type v} {n : Type u → Type w} [MonadControlT m n] [Bind n] {α : Type u}\n (f : ({β : Type u} → n β → m (stM m n β)) → m (stM m n α)) : n α :=\n controlAt m f\n\n/--\n Typeclass for the polymorphic `forM` operation described in the \"do unchained\" paper.\n Remark:\n - `γ` is a \"container\" type of elements of type `α`.\n - `α` is treated as an output parameter by the typeclass resolution procedure.\n That is, it tries to find an instance using only `m` and `γ`.\n-/\nclass ForM (m : Type u → Type v) (γ : Type w₁) (α : outParam (Type w₂)) where\n forM [Monad m] : γ → (α → m PUnit) → m PUnit\n\nexport ForM (forM)\n\n/-- Left-to-right composition of Kleisli arrows. -/\n@[always_inline]\ndef Bind.kleisliRight [Bind m] (f₁ : α → m β) (f₂ : β → m γ) (a : α) : m γ :=\n f₁ a >>= f₂\n\n/-- Right-to-left composition of Kleisli arrows. -/\n@[always_inline]\ndef Bind.kleisliLeft [Bind m] (f₂ : β → m γ) (f₁ : α → m β) (a : α) : m γ :=\n f₁ a >>= f₂\n\n/-- Same as `Bind.bind` but with arguments swapped. -/\n@[always_inline]\ndef Bind.bindLeft [Bind m] (f : α → m β) (ma : m α) : m β :=\n ma >>= f\n\n-- Precedence choice taken to be the same as in haskell:\n-- https://hackage.haskell.org/package/base-4.17.0.0/docs/Control-Monad.html#v:-61--60--60-\n@[inherit_doc] infixr:55 \" >=> \" => Bind.kleisliRight\n@[inherit_doc] infixr:55 \" <=< \" => Bind.kleisliLeft\n@[inherit_doc] infixr:55 \" =<< \" => Bind.bindLeft\n", "meta": {"author": "leanprover", "repo": "lean4", "sha": "742d053a97bdd109a41a921facd1cd6a55e89bc7", "save_path": "github-repos/lean/leanprover-lean4", "path": "github-repos/lean/leanprover-lean4/lean4-742d053a97bdd109a41a921facd1cd6a55e89bc7/src/Init/Control/Basic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4726834914771176, "lm_q2_score": 0.07921032084852897, "lm_q1q2_score": 0.03744141101970539}} {"text": "/-\nCopyright (c) 2017 Johannes Hölzl. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Johannes Hölzl\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.default\nimport Mathlib.logic.relator\nimport Mathlib.PostPort\n\nuniverses u_1 u_2 u_3 u_4 u \n\nnamespace Mathlib\n\n/-!\n# Quotient types\n\nThis module extends the core library's treatment of quotient types (`init.data.quot`).\n\n## Tags\n\nquotient\n-/\n\nnamespace setoid\n\n\ntheorem ext {α : Sort u_1} {s : setoid α} {t : setoid α} : (∀ (a b : α), r a b ↔ r a b) → s = t := sorry\n\nend setoid\n\n\nnamespace quot\n\n\nprotected instance inhabited {α : Sort u_1} {ra : α → α → Prop} [Inhabited α] : Inhabited (Quot ra) :=\n { default := Quot.mk ra Inhabited.default }\n\n/-- Recursion on two `quotient` arguments `a` and `b`, result type depends on `⟦a⟧` and `⟦b⟧`. -/\nprotected def hrec_on₂ {α : Sort u_1} {β : Sort u_2} {ra : α → α → Prop} {rb : β → β → Prop} {φ : Quot ra → Quot rb → Sort u_3} (qa : Quot ra) (qb : Quot rb) (f : (a : α) → (b : β) → φ (Quot.mk ra a) (Quot.mk rb b)) (ca : ∀ {b : β} {a₁ a₂ : α}, ra a₁ a₂ → f a₁ b == f a₂ b) (cb : ∀ {a : α} {b₁ b₂ : β}, rb b₁ b₂ → f a b₁ == f a b₂) : φ qa qb :=\n quot.hrec_on qa (fun (a : α) => quot.hrec_on qb (f a) sorry) sorry\n\n/-- Map a function `f : α → β` such that `ra x y` implies `rb (f x) (f y)`\nto a map `quot ra → quot rb`. -/\nprotected def map {α : Sort u_1} {β : Sort u_2} {ra : α → α → Prop} {rb : β → β → Prop} (f : α → β) (h : relator.lift_fun ra rb f f) : Quot ra → Quot rb :=\n Quot.lift (fun (x : α) => Quot.mk rb (f x)) sorry\n\n/-- If `ra` is a subrelation of `ra'`, then we have a natural map `quot ra → quot ra'`. -/\nprotected def map_right {α : Sort u_1} {ra : α → α → Prop} {ra' : α → α → Prop} (h : ∀ (a₁ a₂ : α), ra a₁ a₂ → ra' a₁ a₂) : Quot ra → Quot ra' :=\n quot.map id h\n\n/-- weaken the relation of a quotient -/\ndef factor {α : Type u_1} (r : α → α → Prop) (s : α → α → Prop) (h : ∀ (x y : α), r x y → s x y) : Quot r → Quot s :=\n Quot.lift (Quot.mk s) sorry\n\ntheorem factor_mk_eq {α : Type u_1} (r : α → α → Prop) (s : α → α → Prop) (h : ∀ (x y : α), r x y → s x y) : factor r s h ∘ Quot.mk r = Quot.mk s :=\n rfl\n\n/-- Descends a function `f : α → β → γ` to quotients of `α` and `β`. -/\nprotected def lift₂ {α : Sort u_1} {β : Sort u_2} {γ : Sort u_4} {r : α → α → Prop} {s : β → β → Prop} (f : α → β → γ) (hr : ∀ (a : α) (b₁ b₂ : β), s b₁ b₂ → f a b₁ = f a b₂) (hs : ∀ (a₁ a₂ : α) (b : β), r a₁ a₂ → f a₁ b = f a₂ b) (q₁ : Quot r) (q₂ : Quot s) : γ :=\n Quot.lift (fun (a : α) => Quot.lift (f a) (hr a)) sorry q₁ q₂\n\n@[simp] theorem lift₂_mk {α : Sort u_1} {β : Sort u_2} {γ : Sort u_4} {r : α → α → Prop} {s : β → β → Prop} (a : α) (b : β) (f : α → β → γ) (hr : ∀ (a : α) (b₁ b₂ : β), s b₁ b₂ → f a b₁ = f a b₂) (hs : ∀ (a₁ a₂ : α) (b : β), r a₁ a₂ → f a₁ b = f a₂ b) : quot.lift₂ f hr hs (Quot.mk r a) (Quot.mk s b) = f a b :=\n rfl\n\n/-- Descends a function `f : α → β → γ` to quotients of `α` and `β` and applies it. -/\nprotected def lift_on₂ {α : Sort u_1} {β : Sort u_2} {γ : Sort u_4} {r : α → α → Prop} {s : β → β → Prop} (p : Quot r) (q : Quot s) (f : α → β → γ) (hr : ∀ (a : α) (b₁ b₂ : β), s b₁ b₂ → f a b₁ = f a b₂) (hs : ∀ (a₁ a₂ : α) (b : β), r a₁ a₂ → f a₁ b = f a₂ b) : γ :=\n quot.lift₂ f hr hs p q\n\n@[simp] theorem lift_on₂_mk {α : Sort u_1} {β : Sort u_2} {γ : Sort u_4} {r : α → α → Prop} {s : β → β → Prop} (a : α) (b : β) (f : α → β → γ) (hr : ∀ (a : α) (b₁ b₂ : β), s b₁ b₂ → f a b₁ = f a b₂) (hs : ∀ (a₁ a₂ : α) (b : β), r a₁ a₂ → f a₁ b = f a₂ b) : quot.lift_on₂ (Quot.mk r a) (Quot.mk s b) f hr hs = f a b :=\n rfl\n\n/-- Descends a function `f : α → β → γ` to quotients of `α` and `β` wih values in a quotient of\n`γ`. -/\nprotected def map₂ {α : Sort u_1} {β : Sort u_2} {γ : Sort u_4} {r : α → α → Prop} {s : β → β → Prop} {t : γ → γ → Prop} (f : α → β → γ) (hr : ∀ (a : α) (b₁ b₂ : β), s b₁ b₂ → t (f a b₁) (f a b₂)) (hs : ∀ (a₁ a₂ : α) (b : β), r a₁ a₂ → t (f a₁ b) (f a₂ b)) (q₁ : Quot r) (q₂ : Quot s) : Quot t :=\n quot.lift₂ (fun (a : α) (b : β) => Quot.mk t (f a b)) sorry sorry q₁ q₂\n\n@[simp] theorem map₂_mk {α : Sort u_1} {β : Sort u_2} {γ : Sort u_4} {r : α → α → Prop} {s : β → β → Prop} {t : γ → γ → Prop} (f : α → β → γ) (hr : ∀ (a : α) (b₁ b₂ : β), s b₁ b₂ → t (f a b₁) (f a b₂)) (hs : ∀ (a₁ a₂ : α) (b : β), r a₁ a₂ → t (f a₁ b) (f a₂ b)) (a : α) (b : β) : quot.map₂ f hr hs (Quot.mk r a) (Quot.mk s b) = Quot.mk t (f a b) :=\n rfl\n\nprotected theorem induction_on₂ {α : Sort u_1} {β : Sort u_2} {r : α → α → Prop} {s : β → β → Prop} {δ : Quot r → Quot s → Prop} (q₁ : Quot r) (q₂ : Quot s) (h : ∀ (a : α) (b : β), δ (Quot.mk r a) (Quot.mk s b)) : δ q₁ q₂ :=\n Quot.ind (fun (a₁ : α) => Quot.ind (fun (a₂ : β) => h a₁ a₂) q₂) q₁\n\nprotected theorem induction_on₃ {α : Sort u_1} {β : Sort u_2} {γ : Sort u_4} {r : α → α → Prop} {s : β → β → Prop} {t : γ → γ → Prop} {δ : Quot r → Quot s → Quot t → Prop} (q₁ : Quot r) (q₂ : Quot s) (q₃ : Quot t) (h : ∀ (a : α) (b : β) (c : γ), δ (Quot.mk r a) (Quot.mk s b) (Quot.mk t c)) : δ q₁ q₂ q₃ :=\n Quot.ind (fun (a₁ : α) => Quot.ind (fun (a₂ : β) => Quot.ind (fun (a₃ : γ) => h a₁ a₂ a₃) q₃) q₂) q₁\n\nend quot\n\n\nnamespace quotient\n\n\nprotected instance inhabited {α : Sort u_1} [sa : setoid α] [Inhabited α] : Inhabited (quotient sa) :=\n { default := quotient.mk Inhabited.default }\n\n/-- Induction on two `quotient` arguments `a` and `b`, result type depends on `⟦a⟧` and `⟦b⟧`. -/\nprotected def hrec_on₂ {α : Sort u_1} {β : Sort u_2} [sa : setoid α] [sb : setoid β] {φ : quotient sa → quotient sb → Sort u_3} (qa : quotient sa) (qb : quotient sb) (f : (a : α) → (b : β) → φ (quotient.mk a) (quotient.mk b)) (c : ∀ (a₁ : α) (b₁ : β) (a₂ : α) (b₂ : β), a₁ ≈ a₂ → b₁ ≈ b₂ → f a₁ b₁ == f a₂ b₂) : φ qa qb :=\n quot.hrec_on₂ qa qb f sorry sorry\n\n/-- Map a function `f : α → β` that sends equivalent elements to equivalent elements\nto a function `quotient sa → quotient sb`. Useful to define unary operations on quotients. -/\nprotected def map {α : Sort u_1} {β : Sort u_2} [sa : setoid α] [sb : setoid β] (f : α → β) (h : relator.lift_fun has_equiv.equiv has_equiv.equiv f f) : quotient sa → quotient sb :=\n quot.map f h\n\n@[simp] theorem map_mk {α : Sort u_1} {β : Sort u_2} [sa : setoid α] [sb : setoid β] (f : α → β) (h : relator.lift_fun has_equiv.equiv has_equiv.equiv f f) (x : α) : quotient.map f h (quotient.mk x) = quotient.mk (f x) :=\n rfl\n\n/-- Map a function `f : α → β → γ` that sends equivalent elements to equivalent elements\nto a function `f : quotient sa → quotient sb → quotient sc`.\nUseful to define binary operations on quotients. -/\nprotected def map₂ {α : Sort u_1} {β : Sort u_2} [sa : setoid α] [sb : setoid β] {γ : Sort u_4} [sc : setoid γ] (f : α → β → γ) (h : relator.lift_fun has_equiv.equiv (has_equiv.equiv ⇒ has_equiv.equiv) f f) : quotient sa → quotient sb → quotient sc :=\n quotient.lift₂ (fun (x : α) (y : β) => quotient.mk (f x y)) sorry\n\nend quotient\n\n\ntheorem quot.eq {α : Type u_1} {r : α → α → Prop} {x : α} {y : α} : Quot.mk r x = Quot.mk r y ↔ eqv_gen r x y :=\n { mp := quot.exact r, mpr := quot.eqv_gen_sound }\n\n@[simp] theorem quotient.eq {α : Sort u_1} [r : setoid α] {x : α} {y : α} : quotient.mk x = quotient.mk y ↔ x ≈ y :=\n { mp := quotient.exact, mpr := quotient.sound }\n\ntheorem forall_quotient_iff {α : Type u_1} [r : setoid α] {p : quotient r → Prop} : (∀ (a : quotient r), p a) ↔ ∀ (a : α), p (quotient.mk a) :=\n { mp := fun (h : ∀ (a : quotient r), p a) (x : α) => h (quotient.mk x),\n mpr := fun (h : ∀ (a : α), p (quotient.mk a)) (a : quotient r) => quotient.induction_on a h }\n\n@[simp] theorem quotient.lift_beta {α : Sort u_1} {β : Sort u_2} [s : setoid α] (f : α → β) (h : ∀ (a b : α), a ≈ b → f a = f b) (x : α) : quotient.lift f h (quotient.mk x) = f x :=\n rfl\n\n@[simp] theorem quotient.lift_on_beta {α : Sort u_1} {β : Sort u_2} [s : setoid α] (f : α → β) (h : ∀ (a b : α), a ≈ b → f a = f b) (x : α) : quotient.lift_on (quotient.mk x) f h = f x :=\n rfl\n\n@[simp] theorem quotient.lift_on_beta₂ {α : Sort u_1} {β : Sort u_2} [setoid α] (f : α → α → β) (h : ∀ (a₁ a₂ b₁ b₂ : α), a₁ ≈ b₁ → a₂ ≈ b₂ → f a₁ a₂ = f b₁ b₂) (x : α) (y : α) : quotient.lift_on₂ (quotient.mk x) (quotient.mk y) f h = f x y :=\n rfl\n\n/-- `quot.mk r` is a surjective function. -/\ntheorem surjective_quot_mk {α : Sort u_1} (r : α → α → Prop) : function.surjective (Quot.mk r) :=\n quot.exists_rep\n\n/-- `quotient.mk` is a surjective function. -/\ntheorem surjective_quotient_mk (α : Sort u_1) [s : setoid α] : function.surjective quotient.mk :=\n quot.exists_rep\n\n/-- Choose an element of the equivalence class using the axiom of choice.\n Sound but noncomputable. -/\ndef quot.out {α : Sort u_1} {r : α → α → Prop} (q : Quot r) : α :=\n classical.some (quot.exists_rep q)\n\n/-- Unwrap the VM representation of a quotient to obtain an element of the equivalence class.\n Computable but unsound. -/\n@[simp] theorem quot.out_eq {α : Sort u_1} {r : α → α → Prop} (q : Quot r) : Quot.mk r (quot.out q) = q :=\n classical.some_spec (quot.exists_rep q)\n\n/-- Choose an element of the equivalence class using the axiom of choice.\n Sound but noncomputable. -/\ndef quotient.out {α : Sort u_1} [s : setoid α] : quotient s → α :=\n quot.out\n\n@[simp] theorem quotient.out_eq {α : Sort u_1} [s : setoid α] (q : quotient s) : quotient.mk (quotient.out q) = q :=\n quot.out_eq q\n\ntheorem quotient.mk_out {α : Sort u_1} [s : setoid α] (a : α) : quotient.out (quotient.mk a) ≈ a :=\n quotient.exact (quotient.out_eq (quotient.mk a))\n\nprotected instance pi_setoid {ι : Sort u_1} {α : ι → Sort u_2} [(i : ι) → setoid (α i)] : setoid ((i : ι) → α i) :=\n setoid.mk (fun (a b : (i : ι) → α i) => ∀ (i : ι), a i ≈ b i) sorry\n\n/-- Given a function `f : Π i, quotient (S i)`, returns the class of functions `Π i, α i` sending\neach `i` to an element of the class `f i`. -/\ndef quotient.choice {ι : Type u_1} {α : ι → Type u_2} [S : (i : ι) → setoid (α i)] (f : (i : ι) → quotient (S i)) : quotient Mathlib.pi_setoid :=\n quotient.mk fun (i : ι) => quotient.out (f i)\n\ntheorem quotient.choice_eq {ι : Type u_1} {α : ι → Type u_2} [(i : ι) → setoid (α i)] (f : (i : ι) → α i) : (quotient.choice fun (i : ι) => quotient.mk (f i)) = quotient.mk f :=\n quotient.sound fun (i : ι) => quotient.mk_out (f i)\n\ntheorem nonempty_quotient_iff {α : Sort u_1} (s : setoid α) : Nonempty (quotient s) ↔ Nonempty α := sorry\n\n/-- `trunc α` is the quotient of `α` by the always-true relation. This\n is related to the propositional truncation in HoTT, and is similar\n in effect to `nonempty α`, but unlike `nonempty α`, `trunc α` is data,\n so the VM representation is the same as `α`, and so this can be used to\n maintain computability. -/\ndef trunc (α : Sort u) :=\n Quot fun (_x _x : α) => True\n\ntheorem true_equivalence {α : Sort u_1} : equivalence fun (_x _x : α) => True :=\n { left := fun (_x : α) => trivial,\n right := { left := fun (_x _x : α) (_x : True) => trivial, right := fun (_x _x _x : α) (_x _x : True) => trivial } }\n\nnamespace trunc\n\n\n/-- Constructor for `trunc α` -/\ndef mk {α : Sort u_1} (a : α) : trunc α :=\n Quot.mk (fun (_x _x : α) => True) a\n\nprotected instance inhabited {α : Sort u_1} [Inhabited α] : Inhabited (trunc α) :=\n { default := mk Inhabited.default }\n\n/-- Any constant function lifts to a function out of the truncation -/\ndef lift {α : Sort u_1} {β : Sort u_2} (f : α → β) (c : ∀ (a b : α), f a = f b) : trunc α → β :=\n Quot.lift f sorry\n\ntheorem ind {α : Sort u_1} {β : trunc α → Prop} : (∀ (a : α), β (mk a)) → ∀ (q : trunc α), β q :=\n Quot.ind\n\nprotected theorem lift_beta {α : Sort u_1} {β : Sort u_2} (f : α → β) (c : ∀ (a b : α), f a = f b) (a : α) : lift f c (mk a) = f a :=\n rfl\n\n/-- Lift a constant function on `q : trunc α`. -/\nprotected def lift_on {α : Sort u_1} {β : Sort u_2} (q : trunc α) (f : α → β) (c : ∀ (a b : α), f a = f b) : β :=\n lift f c q\n\nprotected theorem induction_on {α : Sort u_1} {β : trunc α → Prop} (q : trunc α) (h : ∀ (a : α), β (mk a)) : β q :=\n ind h q\n\ntheorem exists_rep {α : Sort u_1} (q : trunc α) : ∃ (a : α), mk a = q :=\n quot.exists_rep q\n\nprotected theorem induction_on₂ {α : Sort u_1} {β : Sort u_2} {C : trunc α → trunc β → Prop} (q₁ : trunc α) (q₂ : trunc β) (h : ∀ (a : α) (b : β), C (mk a) (mk b)) : C q₁ q₂ :=\n trunc.induction_on q₁ fun (a₁ : α) => trunc.induction_on q₂ (h a₁)\n\nprotected theorem eq {α : Sort u_1} (a : trunc α) (b : trunc α) : a = b :=\n trunc.induction_on₂ a b fun (x y : α) => quot.sound trivial\n\nprotected instance subsingleton {α : Sort u_1} : subsingleton (trunc α) :=\n subsingleton.intro trunc.eq\n\n/-- The `bind` operator for the `trunc` monad. -/\ndef bind {α : Sort u_1} {β : Sort u_2} (q : trunc α) (f : α → trunc β) : trunc β :=\n trunc.lift_on q f sorry\n\n/-- A function `f : α → β` defines a function `map f : trunc α → trunc β`. -/\ndef map {α : Sort u_1} {β : Sort u_2} (f : α → β) (q : trunc α) : trunc β :=\n bind q (mk ∘ f)\n\nprotected instance monad : Monad trunc := sorry\n\nprotected instance is_lawful_monad : is_lawful_monad trunc :=\n is_lawful_monad.mk (fun (α β : Type u_1) (q : α) (f : α → trunc β) => rfl)\n fun (α β γ : Type u_1) (x : trunc α) (f : α → trunc β) (g : β → trunc γ) =>\n trunc.eq (x >>= f >>= g) (x >>= fun (x : α) => f x >>= g)\n\n/-- Recursion/induction principle for `trunc`. -/\nprotected def rec {α : Sort u_1} {C : trunc α → Sort u_3} (f : (a : α) → C (mk a)) (h : ∀ (a b : α), Eq._oldrec (f a) (rec._proof_1 a b) = f b) (q : trunc α) : C q :=\n quot.rec f sorry q\n\n/-- A version of `trunc.rec` taking `q : trunc α` as the first argument. -/\nprotected def rec_on {α : Sort u_1} {C : trunc α → Sort u_3} (q : trunc α) (f : (a : α) → C (mk a)) (h : ∀ (a b : α), Eq._oldrec (f a) (rec_on._proof_1 a b) = f b) : C q :=\n trunc.rec f h q\n\n/-- A version of `trunc.rec_on` assuming the codomain is a `subsingleton`. -/\nprotected def rec_on_subsingleton {α : Sort u_1} {C : trunc α → Sort u_3} [∀ (a : α), subsingleton (C (mk a))] (q : trunc α) (f : (a : α) → C (mk a)) : C q :=\n trunc.rec f sorry q\n\n/-- Noncomputably extract a representative of `trunc α` (using the axiom of choice). -/\ndef out {α : Sort u_1} : trunc α → α :=\n quot.out\n\n@[simp] theorem out_eq {α : Sort u_1} (q : trunc α) : mk (out q) = q :=\n trunc.eq (mk (out q)) q\n\nend trunc\n\n\ntheorem nonempty_of_trunc {α : Sort u_1} (q : trunc α) : Nonempty α :=\n (fun (_a : ∃ (a : α), trunc.mk a = q) =>\n Exists.dcases_on _a fun (w : α) (h : trunc.mk w = q) => idRhs (Nonempty α) (Nonempty.intro w))\n (trunc.exists_rep q)\n\nnamespace quotient\n\n\n/- Versions of quotient definitions and lemmas ending in `'` use unification instead\nof typeclass inference for inferring the `setoid` argument. This is useful when there are\nseveral different quotient relations on a type, for example quotient groups, rings and modules -/\n\n/-- A version of `quotient.mk` taking `{s : setoid α}` as an implicit argument instead of an\ninstance argument. -/\nprotected def mk' {α : Sort u_1} {s₁ : setoid α} (a : α) : quotient s₁ :=\n Quot.mk setoid.r a\n\n/-- `quotient.mk'` is a surjective function. -/\ntheorem surjective_quotient_mk' {α : Sort u_1} {s₁ : setoid α} : function.surjective quotient.mk' :=\n quot.exists_rep\n\n/-- A version of `quotient.lift_on` taking `{s : setoid α}` as an implicit argument instead of an\ninstance argument. -/\nprotected def lift_on' {α : Sort u_1} {φ : Sort u_4} {s₁ : setoid α} (q : quotient s₁) (f : α → φ) (h : ∀ (a b : α), setoid.r a b → f a = f b) : φ :=\n quotient.lift_on q f h\n\n@[simp] protected theorem lift_on'_beta {α : Sort u_1} {φ : Sort u_4} {s₁ : setoid α} (f : α → φ) (h : ∀ (a b : α), setoid.r a b → f a = f b) (x : α) : quotient.lift_on' (quotient.mk' x) f h = f x :=\n rfl\n\n/-- A version of `quotient.lift_on₂` taking `{s₁ : setoid α} {s₂ : setoid β}` as implicit arguments\ninstead of instance arguments. -/\nprotected def lift_on₂' {α : Sort u_1} {β : Sort u_2} {γ : Sort u_3} {s₁ : setoid α} {s₂ : setoid β} (q₁ : quotient s₁) (q₂ : quotient s₂) (f : α → β → γ) (h : ∀ (a₁ : α) (a₂ : β) (b₁ : α) (b₂ : β), setoid.r a₁ b₁ → setoid.r a₂ b₂ → f a₁ a₂ = f b₁ b₂) : γ :=\n quotient.lift_on₂ q₁ q₂ f h\n\n@[simp] protected theorem lift_on₂'_beta {α : Sort u_1} {β : Sort u_2} {γ : Sort u_3} {s₁ : setoid α} {s₂ : setoid β} (f : α → β → γ) (h : ∀ (a₁ : α) (a₂ : β) (b₁ : α) (b₂ : β), setoid.r a₁ b₁ → setoid.r a₂ b₂ → f a₁ a₂ = f b₁ b₂) (a : α) (b : β) : quotient.lift_on₂' (quotient.mk' a) (quotient.mk' b) f h = f a b :=\n rfl\n\n/-- A version of `quotient.ind` taking `{s : setoid α}` as an implicit argument instead of an\ninstance argument. -/\nprotected theorem ind' {α : Sort u_1} {s₁ : setoid α} {p : quotient s₁ → Prop} (h : ∀ (a : α), p (quotient.mk' a)) (q : quotient s₁) : p q :=\n quotient.ind h q\n\n/-- A version of `quotient.ind₂` taking `{s₁ : setoid α} {s₂ : setoid β}` as implicit arguments\ninstead of instance arguments. -/\nprotected theorem ind₂' {α : Sort u_1} {β : Sort u_2} {s₁ : setoid α} {s₂ : setoid β} {p : quotient s₁ → quotient s₂ → Prop} (h : ∀ (a₁ : α) (a₂ : β), p (quotient.mk' a₁) (quotient.mk' a₂)) (q₁ : quotient s₁) (q₂ : quotient s₂) : p q₁ q₂ :=\n quotient.ind₂ h q₁ q₂\n\n/-- A version of `quotient.induction_on` taking `{s : setoid α}` as an implicit argument instead\nof an instance argument. -/\nprotected theorem induction_on' {α : Sort u_1} {s₁ : setoid α} {p : quotient s₁ → Prop} (q : quotient s₁) (h : ∀ (a : α), p (quotient.mk' a)) : p q :=\n quotient.induction_on q h\n\n/-- A version of `quotient.induction_on₂` taking `{s₁ : setoid α} {s₂ : setoid β}` as implicit\narguments instead of instance arguments. -/\nprotected theorem induction_on₂' {α : Sort u_1} {β : Sort u_2} {s₁ : setoid α} {s₂ : setoid β} {p : quotient s₁ → quotient s₂ → Prop} (q₁ : quotient s₁) (q₂ : quotient s₂) (h : ∀ (a₁ : α) (a₂ : β), p (quotient.mk' a₁) (quotient.mk' a₂)) : p q₁ q₂ :=\n quotient.induction_on₂ q₁ q₂ h\n\n/-- A version of `quotient.induction_on₃` taking `{s₁ : setoid α} {s₂ : setoid β} {s₃ : setoid γ}`\nas implicit arguments instead of instance arguments. -/\nprotected theorem induction_on₃' {α : Sort u_1} {β : Sort u_2} {γ : Sort u_3} {s₁ : setoid α} {s₂ : setoid β} {s₃ : setoid γ} {p : quotient s₁ → quotient s₂ → quotient s₃ → Prop} (q₁ : quotient s₁) (q₂ : quotient s₂) (q₃ : quotient s₃) (h : ∀ (a₁ : α) (a₂ : β) (a₃ : γ), p (quotient.mk' a₁) (quotient.mk' a₂) (quotient.mk' a₃)) : p q₁ q₂ q₃ :=\n quotient.induction_on₃ q₁ q₂ q₃ h\n\n/-- Recursion on a `quotient` argument `a`, result type depends on `⟦a⟧`. -/\nprotected def hrec_on' {α : Sort u_1} {s₁ : setoid α} {φ : quotient s₁ → Sort u_2} (qa : quotient s₁) (f : (a : α) → φ (quotient.mk' a)) (c : ∀ (a₁ a₂ : α), a₁ ≈ a₂ → f a₁ == f a₂) : φ qa :=\n quot.hrec_on qa f c\n\n@[simp] theorem hrec_on'_mk' {α : Sort u_1} {s₁ : setoid α} {φ : quotient s₁ → Sort u_2} (f : (a : α) → φ (quotient.mk' a)) (c : ∀ (a₁ a₂ : α), a₁ ≈ a₂ → f a₁ == f a₂) (x : α) : quotient.hrec_on' (quotient.mk' x) f c = f x :=\n rfl\n\n/-- Recursion on two `quotient` arguments `a` and `b`, result type depends on `⟦a⟧` and `⟦b⟧`. -/\nprotected def hrec_on₂' {α : Sort u_1} {β : Sort u_2} {s₁ : setoid α} {s₂ : setoid β} {φ : quotient s₁ → quotient s₂ → Sort u_3} (qa : quotient s₁) (qb : quotient s₂) (f : (a : α) → (b : β) → φ (quotient.mk' a) (quotient.mk' b)) (c : ∀ (a₁ : α) (b₁ : β) (a₂ : α) (b₂ : β), a₁ ≈ a₂ → b₁ ≈ b₂ → f a₁ b₁ == f a₂ b₂) : φ qa qb :=\n quotient.hrec_on₂ qa qb f c\n\n@[simp] theorem hrec_on₂'_mk' {α : Sort u_1} {β : Sort u_2} {s₁ : setoid α} {s₂ : setoid β} {φ : quotient s₁ → quotient s₂ → Sort u_3} (f : (a : α) → (b : β) → φ (quotient.mk' a) (quotient.mk' b)) (c : ∀ (a₁ : α) (b₁ : β) (a₂ : α) (b₂ : β), a₁ ≈ a₂ → b₁ ≈ b₂ → f a₁ b₁ == f a₂ b₂) (x : α) (qb : quotient s₂) : quotient.hrec_on₂' (quotient.mk' x) qb f c = quotient.hrec_on' qb (f x) fun (b₁ b₂ : β) => c x b₁ x b₂ (setoid.refl x) :=\n rfl\n\n/-- Map a function `f : α → β` that sends equivalent elements to equivalent elements\nto a function `quotient sa → quotient sb`. Useful to define unary operations on quotients. -/\nprotected def map' {α : Sort u_1} {β : Sort u_2} {s₁ : setoid α} {s₂ : setoid β} (f : α → β) (h : relator.lift_fun has_equiv.equiv has_equiv.equiv f f) : quotient s₁ → quotient s₂ :=\n quot.map f h\n\n@[simp] theorem map'_mk' {α : Sort u_1} {β : Sort u_2} {s₁ : setoid α} {s₂ : setoid β} (f : α → β) (h : relator.lift_fun has_equiv.equiv has_equiv.equiv f f) (x : α) : quotient.map' f h (quotient.mk' x) = quotient.mk' (f x) :=\n rfl\n\n/-- A version of `quotient.map₂` using curly braces and unification. -/\nprotected def map₂' {α : Sort u_1} {β : Sort u_2} {γ : Sort u_3} {s₁ : setoid α} {s₂ : setoid β} {s₃ : setoid γ} (f : α → β → γ) (h : relator.lift_fun has_equiv.equiv (has_equiv.equiv ⇒ has_equiv.equiv) f f) : quotient s₁ → quotient s₂ → quotient s₃ :=\n quotient.map₂ f h\n\n@[simp] theorem map₂'_mk' {α : Sort u_1} {β : Sort u_2} {γ : Sort u_3} {s₁ : setoid α} {s₂ : setoid β} {s₃ : setoid γ} (f : α → β → γ) (h : relator.lift_fun has_equiv.equiv (has_equiv.equiv ⇒ has_equiv.equiv) f f) (x : α) : quotient.map₂' f h (quotient.mk' x) = quotient.map' (f x) (h (setoid.refl x)) :=\n rfl\n\ntheorem exact' {α : Sort u_1} {s₁ : setoid α} {a : α} {b : α} : quotient.mk' a = quotient.mk' b → setoid.r a b :=\n exact\n\ntheorem sound' {α : Sort u_1} {s₁ : setoid α} {a : α} {b : α} : setoid.r a b → quotient.mk' a = quotient.mk' b :=\n sound\n\n@[simp] protected theorem eq' {α : Sort u_1} {s₁ : setoid α} {a : α} {b : α} : quotient.mk' a = quotient.mk' b ↔ setoid.r a b :=\n eq\n\n/-- A version of `quotient.out` taking `{s₁ : setoid α}` as an implicit argument instead of an\ninstance argument. -/\ndef out' {α : Sort u_1} {s₁ : setoid α} (a : quotient s₁) : α :=\n out a\n\n@[simp] theorem out_eq' {α : Sort u_1} {s₁ : setoid α} (q : quotient s₁) : quotient.mk' (out' q) = q :=\n out_eq q\n\ntheorem mk_out' {α : Sort u_1} {s₁ : setoid α} (a : α) : setoid.r (out' (quotient.mk' a)) a :=\n exact (out_eq (quotient.mk' a))\n\n", "meta": {"author": "AurelienSaue", "repo": "Mathlib4_auto", "sha": "590df64109b08190abe22358fabc3eae000943f2", "save_path": "github-repos/lean/AurelienSaue-Mathlib4_auto", "path": "github-repos/lean/AurelienSaue-Mathlib4_auto/Mathlib4_auto-590df64109b08190abe22358fabc3eae000943f2/Mathlib/data/quot.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4649015713733885, "lm_q2_score": 0.08035747047400406, "lm_q1q2_score": 0.037358314294955154}} {"text": "/-\nCopyright (c) 2021 Anne Baanen. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Anne Baanen\n\n! This file was ported from Lean 3 source module data.fun_like.embedding\n! leanprover-community/mathlib commit 448144f7ae193a8990cb7473c9e9a01990f64ac7\n! Please do not edit these lines, except to modify the commit id\n! if you have ported upstream changes.\n-/\nimport Mathbin.Data.FunLike.Basic\n\n/-!\n# Typeclass for a type `F` with an injective map to `A ↪ B`\n\n> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.\n> Any changes to this file require a corresponding PR to mathlib4.\n\nThis typeclass is primarily for use by embeddings such as `rel_embedding`.\n\n## Basic usage of `embedding_like`\n\nA typical type of embedding should be declared as:\n```\nstructure my_embedding (A B : Type*) [my_class A] [my_class B] :=\n(to_fun : A → B)\n(injective' : function.injective to_fun)\n(map_op' : ∀ {x y : A}, to_fun (my_class.op x y) = my_class.op (to_fun x) (to_fun y))\n\nnamespace my_embedding\n\nvariables (A B : Type*) [my_class A] [my_class B]\n\n-- This instance is optional if you follow the \"Embedding class\" design below:\ninstance : embedding_like (my_embedding A B) A B :=\n{ coe := my_embedding.to_fun,\n coe_injective' := λ f g h, by cases f; cases g; congr',\n injective' := my_embedding.injective' }\n\n/-- Helper instance for when there's too many metavariables to directly\napply `fun_like.to_coe_fn`. -/\ninstance : has_coe_to_fun (my_embedding A B) (λ _, A → B) := ⟨my_embedding.to_fun⟩\n\n@[simp] lemma to_fun_eq_coe {f : my_embedding A B} : f.to_fun = (f : A → B) := rfl\n\n@[ext] theorem ext {f g : my_embedding A B} (h : ∀ x, f x = g x) : f = g := fun_like.ext f g h\n\n/-- Copy of a `my_embedding` with a new `to_fun` equal to the old one. Useful to fix definitional\nequalities. -/\nprotected def copy (f : my_embedding A B) (f' : A → B) (h : f' = ⇑f) : my_embedding A B :=\n{ to_fun := f',\n injective' := h.symm ▸ f.injective',\n map_op' := h.symm ▸ f.map_op' }\n\nend my_embedding\n```\n\nThis file will then provide a `has_coe_to_fun` instance and various\nextensionality and simp lemmas.\n\n## Embedding classes extending `embedding_like`\n\nThe `embedding_like` design provides further benefits if you put in a bit more work.\nThe first step is to extend `embedding_like` to create a class of those types satisfying\nthe axioms of your new type of morphisms.\nContinuing the example above:\n\n```\nsection\nset_option old_structure_cmd true\n\n/-- `my_embedding_class F A B` states that `F` is a type of `my_class.op`-preserving embeddings.\nYou should extend this class when you extend `my_embedding`. -/\nclass my_embedding_class (F : Type*) (A B : out_param $ Type*) [my_class A] [my_class B]\n extends embedding_like F A B :=\n(map_op : ∀ (f : F) (x y : A), f (my_class.op x y) = my_class.op (f x) (f y))\n\nend\n\n@[simp] lemma map_op {F A B : Type*} [my_class A] [my_class B] [my_embedding_class F A B]\n (f : F) (x y : A) : f (my_class.op x y) = my_class.op (f x) (f y) :=\nmy_embedding_class.map_op\n\n-- You can replace `my_embedding.embedding_like` with the below instance:\ninstance : my_embedding_class (my_embedding A B) A B :=\n{ coe := my_embedding.to_fun,\n coe_injective' := λ f g h, by cases f; cases g; congr',\n injective' := my_embedding.injective',\n map_op := my_embedding.map_op' }\n\n-- [Insert `has_coe_to_fun`, `to_fun_eq_coe`, `ext` and `copy` here]\n```\n\nThe second step is to add instances of your new `my_embedding_class` for all types extending\n`my_embedding`.\nTypically, you can just declare a new class analogous to `my_embedding_class`:\n\n```\nstructure cooler_embedding (A B : Type*) [cool_class A] [cool_class B]\n extends my_embedding A B :=\n(map_cool' : to_fun cool_class.cool = cool_class.cool)\n\nsection\nset_option old_structure_cmd true\n\nclass cooler_embedding_class (F : Type*) (A B : out_param $ Type*) [cool_class A] [cool_class B]\n extends my_embedding_class F A B :=\n(map_cool : ∀ (f : F), f cool_class.cool = cool_class.cool)\n\nend\n\n@[simp] lemma map_cool {F A B : Type*} [cool_class A] [cool_class B] [cooler_embedding_class F A B]\n (f : F) : f cool_class.cool = cool_class.cool :=\nmy_embedding_class.map_op\n\n-- You can also replace `my_embedding.embedding_like` with the below instance:\ninstance : cool_embedding_class (cool_embedding A B) A B :=\n{ coe := cool_embedding.to_fun,\n coe_injective' := λ f g h, by cases f; cases g; congr',\n injective' := my_embedding.injective',\n map_op := cool_embedding.map_op',\n map_cool := cool_embedding.map_cool' }\n\n-- [Insert `has_coe_to_fun`, `to_fun_eq_coe`, `ext` and `copy` here]\n```\n\nThen any declaration taking a specific type of morphisms as parameter can instead take the\nclass you just defined:\n```\n-- Compare with: lemma do_something (f : my_embedding A B) : sorry := sorry\nlemma do_something {F : Type*} [my_embedding_class F A B] (f : F) : sorry := sorry\n```\n\nThis means anything set up for `my_embedding`s will automatically work for `cool_embedding_class`es,\nand defining `cool_embedding_class` only takes a constant amount of effort,\ninstead of linearly increasing the work per `my_embedding`-related declaration.\n\n-/\n\n\n/- warning: embedding_like -> EmbeddingLike is a dubious translation:\nlean 3 declaration is\n Sort.{u1} -> (outParam.{succ u2} Sort.{u2}) -> (outParam.{succ u3} Sort.{u3}) -> Sort.{max 1 (imax u1 u2 u3)}\nbut is expected to have type\n Sort.{u1} -> (outParam.{succ u2} Sort.{u2}) -> (outParam.{succ u3} Sort.{u3}) -> Sort.{max (max (max 1 u1) u2) u3}\nCase conversion may be inaccurate. Consider using '#align embedding_like EmbeddingLikeₓ'. -/\n/-- The class `embedding_like F α β` expresses that terms of type `F` have an\ninjective coercion to injective functions `α ↪ β`.\n-/\nclass EmbeddingLike (F : Sort _) (α β : outParam (Sort _)) extends FunLike F α fun _ => β where\n injective' : ∀ f : F, @Function.Injective α β (coe f)\n#align embedding_like EmbeddingLike\n\nnamespace EmbeddingLike\n\nvariable {F α β γ : Sort _} [i : EmbeddingLike F α β]\n\ninclude i\n\n/- warning: embedding_like.injective -> EmbeddingLike.injective is a dubious translation:\nlean 3 declaration is\n forall {F : Sort.{u1}} {α : Sort.{u2}} {β : Sort.{u3}} [i : EmbeddingLike.{u1, u2, u3} F α β] (f : F), Function.Injective.{u2, u3} α β (coeFn.{u1, imax u2 u3} F (fun (_x : F) => α -> β) (FunLike.hasCoeToFun.{u1, u2, u3} F α (fun (_x : α) => β) (EmbeddingLike.toFunLike.{u1, u2, u3} F α β i)) f)\nbut is expected to have type\n forall {F : Sort.{u1}} {α : Sort.{u3}} {β : Sort.{u2}} [i : EmbeddingLike.{u1, u3, u2} F α β] (f : F), Function.Injective.{u3, u2} α β (FunLike.coe.{u1, u3, u2} F α (fun (_x : α) => (fun (x._@.Mathlib.Data.FunLike.Embedding._hyg.19 : α) => β) _x) (EmbeddingLike.toFunLike.{u1, u3, u2} F α β i) f)\nCase conversion may be inaccurate. Consider using '#align embedding_like.injective EmbeddingLike.injectiveₓ'. -/\nprotected theorem injective (f : F) : Function.Injective f :=\n injective' f\n#align embedding_like.injective EmbeddingLike.injective\n\n/- warning: embedding_like.apply_eq_iff_eq -> EmbeddingLike.apply_eq_iff_eq is a dubious translation:\nlean 3 declaration is\n forall {F : Sort.{u1}} {α : Sort.{u2}} {β : Sort.{u3}} [i : EmbeddingLike.{u1, u2, u3} F α β] (f : F) {x : α} {y : α}, Iff (Eq.{u3} β (coeFn.{u1, imax u2 u3} F (fun (_x : F) => α -> β) (FunLike.hasCoeToFun.{u1, u2, u3} F α (fun (_x : α) => β) (EmbeddingLike.toFunLike.{u1, u2, u3} F α β i)) f x) (coeFn.{u1, imax u2 u3} F (fun (_x : F) => α -> β) (FunLike.hasCoeToFun.{u1, u2, u3} F α (fun (_x : α) => β) (EmbeddingLike.toFunLike.{u1, u2, u3} F α β i)) f y)) (Eq.{u2} α x y)\nbut is expected to have type\n forall {F : Sort.{u2}} {α : Sort.{u1}} {β : Sort.{u3}} [i : EmbeddingLike.{u2, u1, u3} F α β] (f : F) {x : α} {y : α}, Iff (Eq.{u3} ((fun (x._@.Mathlib.Data.FunLike.Embedding._hyg.19 : α) => β) x) (FunLike.coe.{u2, u1, u3} F α (fun (_x : α) => (fun (x._@.Mathlib.Data.FunLike.Embedding._hyg.19 : α) => β) _x) (EmbeddingLike.toFunLike.{u2, u1, u3} F α β i) f x) (FunLike.coe.{u2, u1, u3} F α (fun (_x : α) => (fun (x._@.Mathlib.Data.FunLike.Embedding._hyg.19 : α) => β) _x) (EmbeddingLike.toFunLike.{u2, u1, u3} F α β i) f y)) (Eq.{u1} α x y)\nCase conversion may be inaccurate. Consider using '#align embedding_like.apply_eq_iff_eq EmbeddingLike.apply_eq_iff_eqₓ'. -/\n@[simp]\ntheorem apply_eq_iff_eq (f : F) {x y : α} : f x = f y ↔ x = y :=\n (EmbeddingLike.injective f).eq_iff\n#align embedding_like.apply_eq_iff_eq EmbeddingLike.apply_eq_iff_eq\n\nomit i\n\n/- warning: embedding_like.comp_injective -> EmbeddingLike.comp_injective is a dubious translation:\nlean 3 declaration is\n forall {α : Sort.{u1}} {β : Sort.{u2}} {γ : Sort.{u3}} {F : Sort.{u4}} [_inst_1 : EmbeddingLike.{u4, u2, u3} F β γ] (f : α -> β) (e : F), Iff (Function.Injective.{u1, u3} α γ (Function.comp.{u1, u2, u3} α β γ (coeFn.{u4, imax u2 u3} F (fun (_x : F) => β -> γ) (FunLike.hasCoeToFun.{u4, u2, u3} F β (fun (_x : β) => γ) (EmbeddingLike.toFunLike.{u4, u2, u3} F β γ _inst_1)) e) f)) (Function.Injective.{u1, u2} α β f)\nbut is expected to have type\n forall {α : Sort.{u1}} {β : Sort.{u3}} {γ : Sort.{u2}} {F : Sort.{u4}} [_inst_1 : EmbeddingLike.{u4, u3, u2} F β γ] (f : α -> β) (e : F), Iff (Function.Injective.{u1, u2} α γ (Function.comp.{u1, u3, u2} α β γ (FunLike.coe.{u4, u3, u2} F β (fun (_x : β) => (fun (x._@.Mathlib.Data.FunLike.Embedding._hyg.19 : β) => γ) _x) (EmbeddingLike.toFunLike.{u4, u3, u2} F β γ _inst_1) e) f)) (Function.Injective.{u1, u3} α β f)\nCase conversion may be inaccurate. Consider using '#align embedding_like.comp_injective EmbeddingLike.comp_injectiveₓ'. -/\n@[simp]\ntheorem comp_injective {F : Sort _} [EmbeddingLike F β γ] (f : α → β) (e : F) :\n Function.Injective (e ∘ f) ↔ Function.Injective f :=\n (EmbeddingLike.injective e).of_comp_iff f\n#align embedding_like.comp_injective EmbeddingLike.comp_injective\n\nend EmbeddingLike\n\n", "meta": {"author": "leanprover-community", "repo": "mathlib3port", "sha": "62505aa236c58c8559783b16d33e30df3daa54f4", "save_path": "github-repos/lean/leanprover-community-mathlib3port", "path": "github-repos/lean/leanprover-community-mathlib3port/mathlib3port-62505aa236c58c8559783b16d33e30df3daa54f4/Mathbin/Data/FunLike/Embedding.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46490157137338844, "lm_q2_score": 0.0803574649680142, "lm_q1q2_score": 0.03735831173521181}} {"text": "/-\nCopyright (c) 2018 Mario Carneiro. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Mario Carneiro, Kenny Lau\n-/\nimport data.list.basic\n\nuniverses u v w z\n\nvariables {α : Type u} {β : Type v} {γ : Type w} {δ : Type z}\n\nopen nat\n\nnamespace list\n\n/- zip & unzip -/\n\n@[simp] theorem zip_with_cons_cons (f : α → β → γ) (a : α) (b : β) (l₁ : list α) (l₂ : list β) :\n zip_with f (a :: l₁) (b :: l₂) = f a b :: zip_with f l₁ l₂ := rfl\n\n@[simp] theorem zip_cons_cons (a : α) (b : β) (l₁ : list α) (l₂ : list β) :\n zip (a :: l₁) (b :: l₂) = (a, b) :: zip l₁ l₂ := rfl\n\n@[simp] theorem zip_with_nil_left (f : α → β → γ) (l) : zip_with f [] l = [] := rfl\n\n@[simp] theorem zip_with_nil_right (f : α → β → γ) (l) : zip_with f l [] = [] :=\nby cases l; refl\n\n@[simp] lemma zip_with_eq_nil_iff {f : α → β → γ} {l l'} :\n zip_with f l l' = [] ↔ l = [] ∨ l' = [] :=\nby { cases l; cases l'; simp }\n\n@[simp] theorem zip_nil_left (l : list α) : zip ([] : list β) l = [] := rfl\n\n@[simp] theorem zip_nil_right (l : list α) : zip l ([] : list β) = [] :=\nzip_with_nil_right _ l\n\n@[simp] theorem zip_swap : ∀ (l₁ : list α) (l₂ : list β),\n (zip l₁ l₂).map prod.swap = zip l₂ l₁\n| [] l₂ := (zip_nil_right _).symm\n| l₁ [] := by rw zip_nil_right; refl\n| (a::l₁) (b::l₂) := by simp only [zip_cons_cons, map_cons, zip_swap l₁ l₂, prod.swap_prod_mk];\n split; refl\n\n@[simp] theorem length_zip_with (f : α → β → γ) : ∀ (l₁ : list α) (l₂ : list β),\n length (zip_with f l₁ l₂) = min (length l₁) (length l₂)\n| [] l₂ := rfl\n| l₁ [] := by simp only [length, min_zero, zip_with_nil_right]\n| (a::l₁) (b::l₂) := by by simp [length, zip_cons_cons, length_zip_with l₁ l₂, min_add_add_right]\n\n@[simp] theorem length_zip : ∀ (l₁ : list α) (l₂ : list β),\n length (zip l₁ l₂) = min (length l₁) (length l₂) :=\nlength_zip_with _\n\nlemma lt_length_left_of_zip_with {f : α → β → γ} {i : ℕ} {l : list α} {l' : list β}\n (h : i < (zip_with f l l').length) :\n i < l.length :=\nby { rw [length_zip_with, lt_min_iff] at h, exact h.left }\n\nlemma lt_length_right_of_zip_with {f : α → β → γ} {i : ℕ} {l : list α} {l' : list β}\n (h : i < (zip_with f l l').length) :\n i < l'.length :=\nby { rw [length_zip_with, lt_min_iff] at h, exact h.right }\n\nlemma lt_length_left_of_zip {i : ℕ} {l : list α} {l' : list β} (h : i < (zip l l').length) :\n i < l.length :=\nlt_length_left_of_zip_with h\n\nlemma lt_length_right_of_zip {i : ℕ} {l : list α} {l' : list β} (h : i < (zip l l').length) :\n i < l'.length :=\nlt_length_right_of_zip_with h\n\ntheorem zip_append : ∀ {l₁ r₁ : list α} {l₂ r₂ : list β} (h : length l₁ = length l₂),\n zip (l₁ ++ r₁) (l₂ ++ r₂) = zip l₁ l₂ ++ zip r₁ r₂\n| [] r₁ l₂ r₂ h := by simp only [eq_nil_of_length_eq_zero h.symm]; refl\n| l₁ r₁ [] r₂ h := by simp only [eq_nil_of_length_eq_zero h]; refl\n| (a::l₁) r₁ (b::l₂) r₂ h := by simp only [cons_append, zip_cons_cons, zip_append (succ.inj h)];\n split; refl\n\ntheorem zip_map (f : α → γ) (g : β → δ) : ∀ (l₁ : list α) (l₂ : list β),\n zip (l₁.map f) (l₂.map g) = (zip l₁ l₂).map (prod.map f g)\n| [] l₂ := rfl\n| l₁ [] := by simp only [map, zip_nil_right]\n| (a::l₁) (b::l₂) := by simp only [map, zip_cons_cons, zip_map l₁ l₂, prod.map]; split; refl\n\ntheorem zip_map_left (f : α → γ) (l₁ : list α) (l₂ : list β) :\n zip (l₁.map f) l₂ = (zip l₁ l₂).map (prod.map f id) :=\nby rw [← zip_map, map_id]\n\ntheorem zip_map_right (f : β → γ) (l₁ : list α) (l₂ : list β) :\n zip l₁ (l₂.map f) = (zip l₁ l₂).map (prod.map id f) :=\nby rw [← zip_map, map_id]\n\n@[simp] lemma zip_with_map {μ}\n (f : γ → δ → μ) (g : α → γ) (h : β → δ) (as : list α) (bs : list β) :\n zip_with f (as.map g) (bs.map h) =\n zip_with (λ a b, f (g a) (h b)) as bs :=\nbegin\n induction as generalizing bs,\n { simp },\n { cases bs; simp * }\nend\n\nlemma zip_with_map_left\n (f : α → β → γ) (g : δ → α) (l : list δ) (l' : list β) :\n zip_with f (l.map g) l' = zip_with (f ∘ g) l l' :=\nby { convert (zip_with_map f g id l l'), exact eq.symm (list.map_id _) }\n\nlemma zip_with_map_right\n (f : α → β → γ) (l : list α) (g : δ → β) (l' : list δ) :\n zip_with f l (l'.map g) = zip_with (λ x, f x ∘ g) l l' :=\nby { convert (list.zip_with_map f id g l l'), exact eq.symm (list.map_id _) }\n\ntheorem zip_map' (f : α → β) (g : α → γ) : ∀ (l : list α),\n zip (l.map f) (l.map g) = l.map (λ a, (f a, g a))\n| [] := rfl\n| (a::l) := by simp only [map, zip_cons_cons, zip_map' l]; split; refl\n\nlemma map_zip_with {δ : Type*} (f : α → β) (g : γ → δ → α) (l : list γ) (l' : list δ) :\n map f (zip_with g l l') = zip_with (λ x y, f (g x y)) l l' :=\nbegin\n induction l with hd tl hl generalizing l',\n { simp },\n { cases l',\n { simp },\n { simp [hl] } }\nend\n\ntheorem mem_zip {a b} : ∀ {l₁ : list α} {l₂ : list β},\n (a, b) ∈ zip l₁ l₂ → a ∈ l₁ ∧ b ∈ l₂\n| (_::l₁) (_::l₂) (or.inl rfl) := ⟨or.inl rfl, or.inl rfl⟩\n| (a'::l₁) (b'::l₂) (or.inr h) := by split; simp only [mem_cons_iff, or_true, mem_zip h]\n\ntheorem map_fst_zip : ∀ (l₁ : list α) (l₂ : list β),\n l₁.length ≤ l₂.length →\n map prod.fst (zip l₁ l₂) = l₁\n| [] bs _ := rfl\n| (a :: as) (b :: bs) h := by { simp at h, simp! * }\n| (a :: as) [] h := by { simp at h, contradiction }\n\ntheorem map_snd_zip : ∀ (l₁ : list α) (l₂ : list β),\n l₂.length ≤ l₁.length →\n map prod.snd (zip l₁ l₂) = l₂\n| _ [] _ := by { rw zip_nil_right, refl }\n| [] (b :: bs) h := by { simp at h, contradiction }\n| (a :: as) (b :: bs) h := by { simp at h, simp! * }\n\n@[simp] theorem unzip_nil : unzip (@nil (α × β)) = ([], []) := rfl\n\n@[simp] theorem unzip_cons (a : α) (b : β) (l : list (α × β)) :\n unzip ((a, b) :: l) = (a :: (unzip l).1, b :: (unzip l).2) :=\nby rw unzip; cases unzip l; refl\n\ntheorem unzip_eq_map : ∀ (l : list (α × β)), unzip l = (l.map prod.fst, l.map prod.snd)\n| [] := rfl\n| ((a, b) :: l) := by simp only [unzip_cons, map_cons, unzip_eq_map l]\n\ntheorem unzip_left (l : list (α × β)) : (unzip l).1 = l.map prod.fst :=\nby simp only [unzip_eq_map]\n\ntheorem unzip_right (l : list (α × β)) : (unzip l).2 = l.map prod.snd :=\nby simp only [unzip_eq_map]\n\ntheorem unzip_swap (l : list (α × β)) : unzip (l.map prod.swap) = (unzip l).swap :=\nby simp only [unzip_eq_map, map_map]; split; refl\n\ntheorem zip_unzip : ∀ (l : list (α × β)), zip (unzip l).1 (unzip l).2 = l\n| [] := rfl\n| ((a, b) :: l) := by simp only [unzip_cons, zip_cons_cons, zip_unzip l]; split; refl\n\ntheorem unzip_zip_left : ∀ {l₁ : list α} {l₂ : list β}, length l₁ ≤ length l₂ →\n (unzip (zip l₁ l₂)).1 = l₁\n| [] l₂ h := rfl\n| l₁ [] h := by rw eq_nil_of_length_eq_zero (eq_zero_of_le_zero h); refl\n| (a::l₁) (b::l₂) h := by simp only [zip_cons_cons, unzip_cons,\n unzip_zip_left (le_of_succ_le_succ h)]; split; refl\n\ntheorem unzip_zip_right {l₁ : list α} {l₂ : list β} (h : length l₂ ≤ length l₁) :\n (unzip (zip l₁ l₂)).2 = l₂ :=\nby rw [← zip_swap, unzip_swap]; exact unzip_zip_left h\n\ntheorem unzip_zip {l₁ : list α} {l₂ : list β} (h : length l₁ = length l₂) :\n unzip (zip l₁ l₂) = (l₁, l₂) :=\nby rw [← @prod.mk.eta _ _ (unzip (zip l₁ l₂)),\n unzip_zip_left (le_of_eq h), unzip_zip_right (ge_of_eq h)]\n\nlemma zip_of_prod {l : list α} {l' : list β} {lp : list (α × β)}\n (hl : lp.map prod.fst = l) (hr : lp.map prod.snd = l') :\n lp = l.zip l' :=\nby rw [←hl, ←hr, ←zip_unzip lp, ←unzip_left, ←unzip_right, zip_unzip, zip_unzip]\n\nlemma map_prod_left_eq_zip {l : list α} (f : α → β) : l.map (λ x, (x, f x)) = l.zip (l.map f) :=\nby { rw ←zip_map', congr, exact map_id _ }\n\n\n\nlemma zip_with_comm (f : α → α → β) (comm : ∀ (x y : α), f x y = f y x)\n (l l' : list α) :\n zip_with f l l' = zip_with f l' l :=\nbegin\n induction l with hd tl hl generalizing l',\n { simp },\n { cases l',\n { simp },\n { simp [comm, hl] } }\nend\n\ninstance (f : α → α → β) [is_symm_op α β f] : is_symm_op (list α) (list β) (zip_with f) :=\n⟨zip_with_comm f is_symm_op.symm_op⟩\n\n@[simp] theorem length_revzip (l : list α) : length (revzip l) = length l :=\nby simp only [revzip, length_zip, length_reverse, min_self]\n\n@[simp] theorem unzip_revzip (l : list α) : (revzip l).unzip = (l, l.reverse) :=\nunzip_zip (length_reverse l).symm\n\n@[simp] theorem revzip_map_fst (l : list α) : (revzip l).map prod.fst = l :=\nby rw [← unzip_left, unzip_revzip]\n\n@[simp] theorem revzip_map_snd (l : list α) : (revzip l).map prod.snd = l.reverse :=\nby rw [← unzip_right, unzip_revzip]\n\ntheorem reverse_revzip (l : list α) : reverse l.revzip = revzip l.reverse :=\nby rw [← zip_unzip.{u u} (revzip l).reverse, unzip_eq_map]; simp; simp [revzip]\n\ntheorem revzip_swap (l : list α) : (revzip l).map prod.swap = revzip l.reverse :=\nby simp [revzip]\n\nlemma nth_zip_with (f : α → β → γ) (l₁ : list α) (l₂ : list β) (i : ℕ) :\n (zip_with f l₁ l₂).nth i = ((l₁.nth i).map f).bind (λ g, (l₂.nth i).map g) :=\nbegin\n induction l₁ generalizing l₂ i,\n { simp [zip_with, (<*>)] },\n { cases l₂; simp only [zip_with, has_seq.seq, functor.map, nth, option.map_none'],\n { cases ((l₁_hd :: l₁_tl).nth i); refl },\n { cases i; simp only [option.map_some', nth, option.some_bind', *] } }\nend\n\nlemma nth_zip_with_eq_some {α β γ} (f : α → β → γ) (l₁ : list α) (l₂ : list β) (z : γ) (i : ℕ) :\n (zip_with f l₁ l₂).nth i = some z ↔ ∃ x y, l₁.nth i = some x ∧ l₂.nth i = some y ∧ f x y = z :=\nbegin\n induction l₁ generalizing l₂ i,\n { simp [zip_with] },\n { cases l₂; simp only [zip_with, nth, exists_false, and_false, false_and],\n cases i; simp *, },\nend\n\nlemma nth_zip_eq_some (l₁ : list α) (l₂ : list β) (z : α × β) (i : ℕ) :\n (zip l₁ l₂).nth i = some z ↔ l₁.nth i = some z.1 ∧ l₂.nth i = some z.2 :=\nbegin\n cases z,\n rw [zip, nth_zip_with_eq_some], split,\n { rintro ⟨x, y, h₀, h₁, h₂⟩, cc },\n { rintro ⟨h₀, h₁⟩, exact ⟨_,_,h₀,h₁,rfl⟩ }\nend\n\n@[simp] lemma nth_le_zip_with {f : α → β → γ} {l : list α} {l' : list β} {i : ℕ}\n {h : i < (zip_with f l l').length} :\n (zip_with f l l').nth_le i h =\n f (l.nth_le i (lt_length_left_of_zip_with h)) (l'.nth_le i (lt_length_right_of_zip_with h)) :=\nbegin\n rw [←option.some_inj, ←nth_le_nth, nth_zip_with_eq_some],\n refine ⟨l.nth_le i (lt_length_left_of_zip_with h), l'.nth_le i (lt_length_right_of_zip_with h),\n nth_le_nth _, _⟩,\n simp only [←nth_le_nth, eq_self_iff_true, and_self]\nend\n\n@[simp] lemma nth_le_zip {l : list α} {l' : list β} {i : ℕ} {h : i < (zip l l').length} :\n (zip l l').nth_le i h =\n (l.nth_le i (lt_length_left_of_zip h), l'.nth_le i (lt_length_right_of_zip h)) :=\nnth_le_zip_with\n\nlemma mem_zip_inits_tails {l : list α} {init tail : list α} :\n (init, tail) ∈ zip l.inits l.tails ↔ init ++ tail = l :=\nbegin\n induction l generalizing init tail;\n simp_rw [tails, inits, zip_cons_cons],\n { simp },\n { split; rw [mem_cons_iff, zip_map_left, mem_map, prod.exists],\n { rintros (⟨rfl, rfl⟩ | ⟨_, _, h, rfl, rfl⟩),\n { simp },\n { simp [l_ih.mp h], }, },\n { cases init,\n { simp },\n { intro h,\n right,\n use [init_tl, tail],\n simp * at *, }, }, },\nend\n\nlemma map_uncurry_zip_eq_zip_with\n (f : α → β → γ) (l : list α) (l' : list β) :\n map (function.uncurry f) (l.zip l') = zip_with f l l' :=\nbegin\n induction l with hd tl hl generalizing l',\n { simp },\n { cases l' with hd' tl',\n { simp },\n { simp [hl] } }\nend\n\n@[simp] lemma sum_zip_with_distrib_left {γ : Type*} [semiring γ]\n (f : α → β → γ) (n : γ) (l : list α) (l' : list β) :\n (l.zip_with (λ x y, n * f x y) l').sum = n * (l.zip_with f l').sum :=\nbegin\n induction l with hd tl hl generalizing f n l',\n { simp },\n { cases l' with hd' tl',\n { simp, },\n { simp [hl, mul_add] } }\nend\n\nsection distrib\n\n/-! ### Operations that can be applied before or after a `zip_with` -/\n\nvariables (f : α → β → γ) (l : list α) (l' : list β) (n : ℕ)\n\nlemma zip_with_distrib_take :\n (zip_with f l l').take n = zip_with f (l.take n) (l'.take n) :=\nbegin\n induction l with hd tl hl generalizing l' n,\n { simp },\n { cases l',\n { simp },\n { cases n,\n { simp },\n { simp [hl] } } }\nend\n\nlemma zip_with_distrib_drop :\n (zip_with f l l').drop n = zip_with f (l.drop n) (l'.drop n) :=\nbegin\n induction l with hd tl hl generalizing l' n,\n { simp },\n { cases l',\n { simp },\n { cases n,\n { simp },\n { simp [hl] } } }\nend\n\nlemma zip_with_distrib_tail :\n (zip_with f l l').tail = zip_with f l.tail l'.tail :=\nby simp_rw [←drop_one, zip_with_distrib_drop]\n\nlemma zip_with_append (f : α → β → γ) (l la : list α) (l' lb : list β) (h : l.length = l'.length) :\n zip_with f (l ++ la) (l' ++ lb) = zip_with f l l' ++ zip_with f la lb :=\nbegin\n induction l with hd tl hl generalizing l',\n { have : l' = [] := eq_nil_of_length_eq_zero (by simpa using h.symm),\n simp [this], },\n { cases l',\n { simpa using h },\n { simp only [add_left_inj, length] at h,\n simp [hl _ h] } }\nend\n\nlemma zip_with_distrib_reverse (h : l.length = l'.length) :\n (zip_with f l l').reverse = zip_with f l.reverse l'.reverse :=\nbegin\n induction l with hd tl hl generalizing l',\n { simp },\n { cases l' with hd' tl',\n { simp },\n { simp only [add_left_inj, length] at h,\n have : tl.reverse.length = tl'.reverse.length := by simp [h],\n simp [hl _ h, zip_with_append _ _ _ _ _ this] } }\nend\n\nend distrib\n\nend list\n", "meta": {"author": "JLimperg", "repo": "aesop3", "sha": "a4a116f650cc7403428e72bd2e2c4cda300fe03f", "save_path": "github-repos/lean/JLimperg-aesop3", "path": "github-repos/lean/JLimperg-aesop3/aesop3-a4a116f650cc7403428e72bd2e2c4cda300fe03f/src/data/list/zip.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4921881357207955, "lm_q2_score": 0.07585818315512396, "lm_q1q2_score": 0.03733649774628712}} {"text": "/-\nCopyright (c) 2018 Simon Hudon. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Simon Hudon, Scott Morrison\n-/\nimport tactic.core\n\n/-!\n# solve_by_elim\n\nA depth-first search backwards reasoner.\n\n`solve_by_elim` takes a list of lemmas, and repeating tries to `apply` these against\nthe goals, recursively acting on any generated subgoals.\n\nIt accepts a variety of configuration options described below, enabling\n* backtracking across multiple goals,\n* pruning the search tree, and\n* invoking other tactics before or after trying to apply lemmas.\n\nAt present it has no \"premise selection\", and simply tries the supplied lemmas in order\nat each step of the search.\n-/\n\nnamespace tactic\n\nnamespace solve_by_elim\n/--\n`mk_assumption_set` builds a collection of lemmas for use in\nthe backtracking search in `solve_by_elim`.\n\n* By default, it includes all local hypotheses, along with `rfl`, `trivial`, `congr_fun` and\n `congr_arg`.\n* The flag `no_dflt` removes these.\n* The argument `hs` is a list of `simp_arg_type`s,\n and can be used to add, or remove, lemmas or expressions from the set.\n* The argument `attr : list name` adds all lemmas tagged with one of a specified list of attributes.\n\n`mk_assumption_set` returns not a `list expr`, but a `list (tactic expr) × tactic (list expr)`.\nThere are two separate problems that need to be solved.\n\n### Relevant local hypotheses\n\n`solve_by_elim*` works with multiple goals,\nand we need to use separate sets of local hypotheses for each goal.\nThe second component of the returned value provides these local hypotheses.\n(Essentially using `local_context`, along with some filtering to remove hypotheses\nthat have been explicitly removed via `only` or `[-h]`.)\n\n### Stuck metavariables\n\nLemmas with implicit arguments would be filled in with metavariables if we created the\n`expr` objects immediately, so instead we return thunks that generate the expressions\non demand. This is the first component, with type `list (tactic expr)`.\n\nAs an example, we have `def rfl : ∀ {α : Sort u} {a : α}, a = a`, which on elaboration will become\n`@rfl ?m_1 ?m_2`.\n\nBecause `solve_by_elim` works by repeated application of lemmas against subgoals,\nthe first time such a lemma is successfully applied,\nthose metavariables will be unified, and thereafter have fixed values.\nThis would make it impossible to apply the lemma\na second time with different values of the metavariables.\n\nSee https://github.com/leanprover-community/mathlib/issues/2269\n\nAs an optimisation, after we build the list of `tactic expr`s, we actually run them, and replace any\nthat do not in fact produce metavariables with a simple `return` tactic.\n-/\nmeta def mk_assumption_set (no_dflt : bool) (hs : list simp_arg_type) (attr : list name) :\n tactic (list (tactic expr) × tactic (list expr)) :=\n-- We lock the tactic state so that any spurious goals generated during\n-- elaboration of pre-expressions are discarded\nlock_tactic_state $\ndo\n -- `hs` are expressions specified explicitly,\n -- `hex` are exceptions (specified via `solve_by_elim [-h]`) referring to local hypotheses,\n -- `gex` are the other exceptions\n (hs, gex, hex, all_hyps) ← decode_simp_arg_list hs,\n -- Recall, per the discussion above, we produce `tactic expr` thunks rather than actual `expr`s.\n -- Note that while we evaluate these thunks on two occasions below while preparing the list,\n -- this is a one-time cost during `mk_assumption_set`, rather than a cost proportional to the\n -- length of the search `solve_by_elim` executes.\n let hs := hs.map (λ h, i_to_expr_for_apply h),\n l ← attr.mmap $ λ a, attribute.get_instances a,\n let l := l.join,\n let m := l.map (λ h, mk_const h),\n -- In order to remove the expressions we need to evaluate the thunks.\n hs ← (hs ++ m).mfilter $ λ h, (do h ← h, return $ expr.const_name h ∉ gex),\n let hs := if no_dflt then hs else\n ([`rfl, `trivial, `congr_fun, `congr_arg].map (λ n, (mk_const n))) ++ hs,\n let locals : tactic (list expr) := if ¬ no_dflt ∨ all_hyps then do\n ctx ← local_context,\n -- Remove local exceptions specified in `hex`:\n return $ ctx.filter (λ h : expr, h.local_uniq_name ∉ hex)\n else return [],\n -- Finally, run all of the tactics: any that return an expression without metavariables can safely\n -- be replaced by a `return` tactic.\n hs ← hs.mmap (λ h : tactic expr, do\n e ← h,\n if e.has_meta_var then return h else return (return e)),\n return (hs, locals)\n\n/--\nConfiguration options for `solve_by_elim`.\n\n* `accept : list expr → tactic unit` determines whether the current branch should be explored.\n At each step, before the lemmas are applied,\n `accept` is passed the proof terms for the original goals,\n as reported by `get_goals` when `solve_by_elim` started.\n These proof terms may be metavariables (if no progress has been made on that goal)\n or may contain metavariables at some leaf nodes\n (if the goal has been partially solved by previous `apply` steps).\n If the `accept` tactic fails `solve_by_elim` aborts searching this branch and backtracks.\n By default `accept := λ _, skip` always succeeds.\n (There is an example usage in `tests/solve_by_elim.lean`.)\n* `pre_apply : tactic unit` specifies an additional tactic to run before each round of `apply`.\n* `discharger : tactic unit` specifies an additional tactic to apply on subgoals\n for which no lemma applies.\n If that tactic succeeds, `solve_by_elim` will continue applying lemmas on resulting goals.\n-/\nmeta structure basic_opt extends apply_any_opt :=\n(accept : list expr → tactic unit := λ _, skip)\n(pre_apply : tactic unit := skip)\n(discharger : tactic unit := failed)\n(max_depth : ℕ := 3)\n\ndeclare_trace solve_by_elim -- trace attempted lemmas\n\n/--\nA helper function for trace messages, prepending '....' depending on the current search depth.\n-/\nmeta def solve_by_elim_trace (n : ℕ) (f : format) : tactic unit :=\ntrace_if_enabled `solve_by_elim\n (format!\"[solve_by_elim {(list.replicate (n+1) '.').as_string} \" ++ f ++ \"]\")\n\n/-- A helper function to generate trace messages on successful applications. -/\nmeta def on_success (g : format) (n : ℕ) (e : expr) : tactic unit :=\ndo\n pp ← pp e,\n solve_by_elim_trace n (format!\"✅ `{pp}` solves `⊢ {g}`\")\n\n/-- A helper function to generate trace messages on unsuccessful applications. -/\nmeta def on_failure (g : format) (n : ℕ) : tactic unit :=\nsolve_by_elim_trace n (format!\"❌ failed to solve `⊢ {g}`\")\n\n/--\nA helper function to generate the tactic that print trace messages.\nThis function exists to ensure the target is pretty printed only as necessary.\n-/\nmeta def trace_hooks (n : ℕ) : tactic ((expr → tactic unit) × tactic unit) :=\nif is_trace_enabled_for `solve_by_elim then\n do\n g ← target >>= pp,\n return (on_success g n, on_failure g n)\nelse\n return (λ _, skip, skip)\n\n/--\nThe internal implementation of `solve_by_elim`, with a limiting counter.\n-/\nmeta def solve_by_elim_aux (opt : basic_opt) (original_goals : list expr)\n (lemmas : list (tactic expr)) (ctx : tactic (list expr)) :\n ℕ → tactic unit\n| n := do\n -- First, check that progress so far is `accept`able.\n lock_tactic_state (original_goals.mmap instantiate_mvars >>= opt.accept),\n -- Then check if we've finished.\n (done >> solve_by_elim_trace (opt.max_depth - n) \"success!\") <|> (do\n -- Otherwise, if there's more time left,\n (guard (n > 0) <|>\n solve_by_elim_trace opt.max_depth \"🛑 aborting, hit depth limit\" >> failed),\n -- run the `pre_apply` tactic, then\n opt.pre_apply,\n -- try either applying a lemma and recursing,\n (on_success, on_failure) ← trace_hooks (opt.max_depth - n),\n ctx_lemmas ← ctx,\n (apply_any_thunk (lemmas ++ (ctx_lemmas.map return)) opt.to_apply_any_opt\n (solve_by_elim_aux (n-1))\n on_success on_failure) <|>\n -- or if that doesn't work, run the discharger and recurse.\n (opt.discharger >> solve_by_elim_aux (n-1)))\n\n/--\nArguments for `solve_by_elim`:\n* By default `solve_by_elim` operates only on the first goal,\n but with `backtrack_all_goals := true`, it operates on all goals at once,\n backtracking across goals as needed,\n and only succeeds if it discharges all goals.\n* `lemmas` specifies the list of lemmas to use in the backtracking search.\n If `none`, `solve_by_elim` uses the local hypotheses,\n along with `rfl`, `trivial`, `congr_arg`, and `congr_fun`.\n* `lemma_thunks` provides the lemmas as a list of `tactic expr`,\n which are used to regenerate the `expr` objects to avoid binding metavariables.\n It should not usually be specified by the user.\n (If both `lemmas` and `lemma_thunks` are specified, only `lemma_thunks` is used.)\n* `ctx_thunk` is for internal use only: it returns the local hypotheses which will be used.\n* `max_depth` bounds the depth of the search.\n-/\nmeta structure opt extends basic_opt :=\n(backtrack_all_goals : bool := ff)\n(lemmas : option (list expr) := none)\n(lemma_thunks : option (list (tactic expr)) := lemmas.map (λ l, l.map return))\n(ctx_thunk : tactic (list expr) := local_context)\n\n/--\nIf no lemmas have been specified, generate the default set\n(local hypotheses, along with `rfl`, `trivial`, `congr_arg`, and `congr_fun`).\n-/\nmeta def opt.get_lemma_thunks (opt : opt) : tactic (list (tactic expr) × tactic (list expr)) :=\nmatch opt.lemma_thunks with\n| none := mk_assumption_set ff [] []\n| some lemma_thunks := return (lemma_thunks, opt.ctx_thunk)\nend\n\nend solve_by_elim\n\nopen solve_by_elim\n\n/--\n`solve_by_elim` repeatedly tries `apply`ing a lemma\nfrom the list of assumptions (passed via the `opt` argument),\nrecursively operating on any generated subgoals, backtracking as necessary.\n\n`solve_by_elim` succeeds only if it discharges the goal.\n(By default, `solve_by_elim` focuses on the first goal, and only attempts to solve that.\nWith the option `backtrack_all_goals := tt`,\nit attempts to solve all goals, and only succeeds if it does so.\nWith `backtrack_all_goals := tt`, `solve_by_elim` will backtrack a solution it has found for\none goal if it then can't discharge other goals.)\n\nIf passed an empty list of assumptions, `solve_by_elim` builds a default set\nas per the interactive tactic, using the `local_context` along with\n`rfl`, `trivial`, `congr_arg`, and `congr_fun`.\n\nTo pass a particular list of assumptions, use the `lemmas` field\nin the configuration argument. This expects an\n`option (list expr)`. In certain situations it may be necessary to instead use the\n`lemma_thunks` field, which expects a `option (list (tactic expr))`.\nThis allows for regenerating metavariables\nfor each application, which might otherwise get stuck.\n\nSee also the simpler tactic `apply_rules`, which does not perform backtracking.\n-/\nmeta def solve_by_elim (opt : opt := { }) : tactic unit :=\ndo\n tactic.fail_if_no_goals,\n (lemmas, ctx_lemmas) ← opt.get_lemma_thunks,\n (if opt.backtrack_all_goals then id else focus1) $ (do\n gs ← get_goals,\n solve_by_elim_aux opt.to_basic_opt gs lemmas ctx_lemmas opt.max_depth <|>\n fail (\"`solve_by_elim` failed.\\n\" ++\n \"Try `solve_by_elim { max_depth := N }` for `N > \" ++ (to_string opt.max_depth) ++ \"`\\n\" ++\n \"or use `set_option trace.solve_by_elim true` to view the search.\"))\n\nsetup_tactic_parser\n\nnamespace interactive\n/--\n`apply_assumption` looks for an assumption of the form `... → ∀ _, ... → head`\nwhere `head` matches the current goal.\n\nIf this fails, `apply_assumption` will call `symmetry` and try again.\n\nIf this also fails, `apply_assumption` will call `exfalso` and try again,\nso that if there is an assumption of the form `P → ¬ Q`, the new tactic state\nwill have two goals, `P` and `Q`.\n\nOptional arguments:\n- `lemmas`: a list of expressions to apply, instead of the local constants\n- `tac`: a tactic to run on each subgoal after applying an assumption; if\n this tactic fails, the corresponding assumption will be rejected and\n the next one will be attempted.\n-/\nmeta def apply_assumption\n (lemmas : parse pexpr_list?)\n (opt : apply_any_opt := {})\n (tac : tactic unit := skip) : tactic unit :=\ndo\n lemmas ← match lemmas with\n | none := local_context\n | some lemmas := lemmas.mmap to_expr\n end,\n tactic.apply_any lemmas opt tac\n\nadd_tactic_doc\n{ name := \"apply_assumption\",\n category := doc_category.tactic,\n decl_names := [`tactic.interactive.apply_assumption],\n tags := [\"context management\", \"lemma application\"] }\n\n/--\n`solve_by_elim` calls `apply` on the main goal to find an assumption whose head matches\nand then repeatedly calls `apply` on the generated subgoals until no subgoals remain,\nperforming at most `max_depth` recursive steps.\n\n`solve_by_elim` discharges the current goal or fails.\n\n`solve_by_elim` performs back-tracking if subgoals can not be solved.\n\nBy default, the assumptions passed to `apply` are the local context, `rfl`, `trivial`,\n`congr_fun` and `congr_arg`.\n\nThe assumptions can be modified with similar syntax as for `simp`:\n* `solve_by_elim [h₁, h₂, ..., hᵣ]` also applies the named lemmas.\n* `solve_by_elim with attr₁ ... attrᵣ` also applies all lemmas tagged with the specified attributes.\n* `solve_by_elim only [h₁, h₂, ..., hᵣ]` does not include the local context,\n `rfl`, `trivial`, `congr_fun`, or `congr_arg` unless they are explicitly included.\n* `solve_by_elim [-id_1, ... -id_n]` uses the default assumptions, removing the specified ones.\n\n`solve_by_elim*` tries to solve all goals together, using backtracking if a solution for one goal\nmakes other goals impossible.\n\noptional arguments passed via a configuration argument as `solve_by_elim { ... }`\n- max_depth: number of attempts at discharging generated sub-goals\n- discharger: a subsidiary tactic to try at each step when no lemmas apply\n (e.g. `cc` may be helpful).\n- pre_apply: a subsidiary tactic to run at each step before applying lemmas (e.g. `intros`).\n- accept: a subsidiary tactic `list expr → tactic unit` that at each step,\n before any lemmas are applied, is passed the original proof terms\n as reported by `get_goals` when `solve_by_elim` started\n (but which may by now have been partially solved by previous `apply` steps).\n If the `accept` tactic fails,\n `solve_by_elim` will abort searching the current branch and backtrack.\n This may be used to filter results, either at every step of the search,\n or filtering complete results\n (by testing for the absence of metavariables, and then the filtering condition).\n-/\nmeta def solve_by_elim (all_goals : parse $ (tk \"*\")?) (no_dflt : parse only_flag)\n (hs : parse simp_arg_list) (attr_names : parse with_ident_list) (opt : solve_by_elim.opt := { }) :\n tactic unit :=\ndo (lemma_thunks, ctx_thunk) ← mk_assumption_set no_dflt hs attr_names,\n tactic.solve_by_elim\n { backtrack_all_goals := all_goals.is_some ∨ opt.backtrack_all_goals,\n lemma_thunks := some lemma_thunks,\n ctx_thunk := ctx_thunk,\n ..opt }\n\nadd_tactic_doc\n{ name := \"solve_by_elim\",\n category := doc_category.tactic,\n decl_names := [`tactic.interactive.solve_by_elim],\n tags := [\"search\"] }\n\nend interactive\n\nend tactic\n", "meta": {"author": "leanprover-community", "repo": "mathlib", "sha": "5e526d18cea33550268dcbbddcb822d5cde40654", "save_path": "github-repos/lean/leanprover-community-mathlib", "path": "github-repos/lean/leanprover-community-mathlib/mathlib-5e526d18cea33550268dcbbddcb822d5cde40654/src/tactic/solve_by_elim.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.07696082934474628, "lm_q1q2_score": 0.03727829300403482}} {"text": "/-\nCopyright (c) 2022 Mario Carneiro. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Mario Carneiro\n-/\nimport Lean\nimport Std.Tactic.OpenPrivate\nimport Std.Data.List.Basic\nimport Mathlib.Lean.Expr.Basic\n\n/-!\n\n# Backward compatible implementation of lean 3 `cases` tactic\n\nThis tactic is similar to the `cases` tactic in lean 4 core, but the syntax for giving\nnames is different:\n\n```\nexample (h : p ∨ q) : q ∨ p := by\n cases h with\n | inl hp => exact Or.inr hp\n | inr hq => exact Or.inl hq\n\nexample (h : p ∨ q) : q ∨ p := by\n cases' h with hp hq\n · exact Or.inr hp\n · exact Or.inl hq\n\nexample (h : p ∨ q) : q ∨ p := by\n rcases h with hp | hq\n · exact Or.inr hp\n · exact Or.inl hq\n```\n\nPrefer `cases` or `rcases` when possible, because these tactics promote structured proofs.\n-/\n\nnamespace Lean.Parser.Tactic\nopen Meta Elab Elab.Tactic\n\nopen private getAltNumFields in evalCases ElimApp.evalAlts.go in\ndef ElimApp.evalNames (elimInfo : ElimInfo) (alts : Array ElimApp.Alt) (withArg : Syntax)\n (numEqs := 0) (numGeneralized := 0) (toClear : Array FVarId := #[]) :\n TermElabM (Array MVarId) := do\n let mut names : List Syntax := withArg[1].getArgs |>.toList\n let mut subgoals := #[]\n for { name := altName, mvarId := g, .. } in alts do\n let numFields ← getAltNumFields elimInfo altName\n let (altVarNames, names') := names.splitAtD numFields (Unhygienic.run `(_))\n names := names'\n let (fvars, g) ← g.introN numFields <| altVarNames.map (getNameOfIdent' ·[0])\n let some (g, subst) ← Cases.unifyEqs? numEqs g {} | pure ()\n let (_, g) ← g.introNP numGeneralized\n let g ← liftM $ toClear.foldlM (·.tryClear) g\n for fvar in fvars, stx in altVarNames do\n g.withContext <| (subst.apply <| .fvar fvar).addLocalVarInfoForBinderIdent ⟨stx⟩\n subgoals := subgoals.push g\n pure subgoals\n\nopen private getElimNameInfo generalizeTargets generalizeVars in evalInduction in\nelab (name := induction') \"induction' \" tgts:(casesTarget,+)\n usingArg:((\" using \" ident)?)\n withArg:((\" with \" (colGt binderIdent)+)?)\n genArg:((\" generalizing \" (colGt ident)+)?) : tactic => do\n let targets ← elabCasesTargets tgts.1.getSepArgs\n let g :: gs ← getUnsolvedGoals | throwNoGoalsToBeSolved\n g.withContext do\n let elimInfo ← getElimNameInfo usingArg targets (induction := true)\n let targets ← addImplicitTargets elimInfo targets\n evalInduction.checkTargets targets\n let targetFVarIds := targets.map (·.fvarId!)\n g.withContext do\n let genArgs ← if genArg.1.isNone then pure #[] else getFVarIds genArg.1[1].getArgs\n let forbidden ← mkGeneralizationForbiddenSet targets\n let mut s ← getFVarSetToGeneralize targets forbidden\n for v in genArgs do\n if forbidden.contains v then\n throwError (\"variable cannot be generalized \" ++\n \"because target depends on it{indentExpr (mkFVar v)}\")\n if s.contains v then\n throwError (\"unnecessary 'generalizing' argument, \" ++\n \"variable '{mkFVar v}' is generalized automatically\")\n s := s.insert v\n let (fvarIds, g) ← g.revert (← sortFVarIds s.toArray)\n let result ← withRef tgts <| ElimApp.mkElimApp elimInfo targets (← g.getTag)\n let elimArgs := result.elimApp.getAppArgs\n ElimApp.setMotiveArg g elimArgs[elimInfo.motivePos]!.mvarId! targetFVarIds\n g.assign result.elimApp\n let subgoals ← ElimApp.evalNames elimInfo result.alts withArg\n (numGeneralized := fvarIds.size) (toClear := targetFVarIds)\n setGoals <| (subgoals ++ result.others).toList ++ gs\n\nopen private getElimNameInfo in evalCases in\nelab (name := cases') \"cases' \" tgts:(casesTarget,+) usingArg:((\" using \" ident)?)\n withArg:((\" with \" (colGt binderIdent)+)?) : tactic => do\n let targets ← elabCasesTargets tgts.1.getSepArgs\n let g :: gs ← getUnsolvedGoals | throwNoGoalsToBeSolved\n g.withContext do\n let elimInfo ← getElimNameInfo usingArg targets (induction := false)\n let targets ← addImplicitTargets elimInfo targets\n let result ← withRef tgts <| ElimApp.mkElimApp elimInfo targets (← g.getTag)\n let elimArgs := result.elimApp.getAppArgs\n let targets ← elimInfo.targetsPos.mapM (instantiateMVars elimArgs[·]!)\n let motive := elimArgs[elimInfo.motivePos]!\n let g ← generalizeTargetsEq g (← inferType motive) targets\n let (targetsNew, g) ← g.introN targets.size\n g.withContext do\n ElimApp.setMotiveArg g motive.mvarId! targetsNew\n g.assign result.elimApp\n let subgoals ← ElimApp.evalNames elimInfo result.alts withArg\n (numEqs := targets.size) (toClear := targetsNew)\n setGoals <| subgoals.toList ++ gs\n", "meta": {"author": "leanprover-community", "repo": "mathlib4", "sha": "b9a0a30342ca06e9817e22dbe46e75fc7f435500", "save_path": "github-repos/lean/leanprover-community-mathlib4", "path": "github-repos/lean/leanprover-community-mathlib4/mathlib4-b9a0a30342ca06e9817e22dbe46e75fc7f435500/Mathlib/Tactic/Cases.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43014736319616964, "lm_q2_score": 0.08632348598851412, "lm_q1q2_score": 0.03713181987986085}} {"text": "/-\nCopyright (c) 2017 Johannes Hölzl. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Johannes Hölzl, Mario Carneiro\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.default\nimport Mathlib.data.equiv.basic\nimport Mathlib.data.sigma.basic\nimport Mathlib.algebra.group.defs\nimport Mathlib.PostPort\n\nuniverses u_1 u_2 l u v u_3 w x u_4 \n\nnamespace Mathlib\n\n/-!\n# Injective functions\n-/\n\nnamespace function\n\n\n/-- `α ↪ β` is a bundled injective function. -/\nstructure embedding (α : Sort u_1) (β : Sort u_2) where\n to_fun : α → β\n inj' : injective to_fun\n\ninfixr:25 \" ↪ \" => Mathlib.function.embedding\n\nprotected instance embedding.has_coe_to_fun {α : Sort u} {β : Sort v} : has_coe_to_fun (α ↪ β) :=\n has_coe_to_fun.mk (fun (x : α ↪ β) => α → β) embedding.to_fun\n\nend function\n\n\n/-- Convert an `α ≃ β` to `α ↪ β`. -/\n@[simp] theorem equiv.to_embedding_apply {α : Sort u} {β : Sort v} (f : α ≃ β) :\n ∀ (ᾰ : α), coe_fn (equiv.to_embedding f) ᾰ = coe_fn f ᾰ :=\n fun (ᾰ : α) => Eq.refl (coe_fn (equiv.to_embedding f) ᾰ)\n\nnamespace function\n\n\nnamespace embedding\n\n\ntheorem ext {α : Sort u_1} {β : Sort u_2} {f : α ↪ β} {g : α ↪ β}\n (h : ∀ (x : α), coe_fn f x = coe_fn g x) : f = g :=\n sorry\n\ntheorem ext_iff {α : Sort u_1} {β : Sort u_2} {f : α ↪ β} {g : α ↪ β} :\n (∀ (x : α), coe_fn f x = coe_fn g x) ↔ f = g :=\n sorry\n\n@[simp] theorem to_fun_eq_coe {α : Sort u_1} {β : Sort u_2} (f : α ↪ β) : to_fun f = ⇑f := rfl\n\n@[simp] theorem coe_fn_mk {α : Sort u_1} {β : Sort u_2} (f : α → β) (i : injective f) :\n ⇑(mk f i) = f :=\n rfl\n\ntheorem injective {α : Sort u_1} {β : Sort u_2} (f : α ↪ β) : injective ⇑f := inj' f\n\n@[simp] theorem refl_apply (α : Sort u_1) (a : α) : coe_fn (embedding.refl α) a = a := Eq.refl a\n\n@[simp] theorem trans_apply {α : Sort u_1} {β : Sort u_2} {γ : Sort u_3} (f : α ↪ β) (g : β ↪ γ) :\n ∀ (ᾰ : α), coe_fn (embedding.trans f g) ᾰ = coe_fn g (coe_fn f ᾰ) :=\n fun (ᾰ : α) => Eq.refl (coe_fn g (coe_fn f ᾰ))\n\n@[simp] theorem equiv_to_embedding_trans_symm_to_embedding {α : Sort u_1} {β : Sort u_2}\n (e : α ≃ β) :\n embedding.trans (equiv.to_embedding e) (equiv.to_embedding (equiv.symm e)) = embedding.refl α :=\n sorry\n\n@[simp] theorem equiv_symm_to_embedding_trans_to_embedding {α : Sort u_1} {β : Sort u_2}\n (e : α ≃ β) :\n embedding.trans (equiv.to_embedding (equiv.symm e)) (equiv.to_embedding e) = embedding.refl β :=\n sorry\n\nprotected def congr {α : Sort u} {β : Sort v} {γ : Sort w} {δ : Sort x} (e₁ : α ≃ β) (e₂ : γ ≃ δ)\n (f : α ↪ γ) : β ↪ δ :=\n embedding.trans (equiv.to_embedding (equiv.symm e₁)) (embedding.trans f (equiv.to_embedding e₂))\n\n/-- A right inverse `surj_inv` of a surjective function as an `embedding`. -/\nprotected def of_surjective {α : Sort u_1} {β : Sort u_2} (f : β → α) (hf : surjective f) : α ↪ β :=\n mk (surj_inv hf) (injective_surj_inv hf)\n\n/-- Convert a surjective `embedding` to an `equiv` -/\nprotected def equiv_of_surjective {α : Sort u_1} {β : Type u_2} (f : α ↪ β) (hf : surjective ⇑f) :\n α ≃ β :=\n equiv.of_bijective ⇑f sorry\n\nprotected def of_not_nonempty {α : Sort u_1} {β : Sort u_2} (hα : ¬Nonempty α) : α ↪ β :=\n mk (fun (a : α) => false.elim sorry) sorry\n\n/-- Change the value of an embedding `f` at one point. If the prescribed image\nis already occupied by some `f a'`, then swap the values at these two points. -/\ndef set_value {α : Sort u_1} {β : Sort u_2} (f : α ↪ β) (a : α) (b : β)\n [(a' : α) → Decidable (a' = a)] [(a' : α) → Decidable (coe_fn f a' = b)] : α ↪ β :=\n mk (fun (a' : α) => ite (a' = a) b (ite (coe_fn f a' = b) (coe_fn f a) (coe_fn f a'))) sorry\n\ntheorem set_value_eq {α : Sort u_1} {β : Sort u_2} (f : α ↪ β) (a : α) (b : β)\n [(a' : α) → Decidable (a' = a)] [(a' : α) → Decidable (coe_fn f a' = b)] :\n coe_fn (set_value f a b) a = b :=\n sorry\n\n/-- Embedding into `option` -/\nprotected def some {α : Type u_1} : α ↪ Option α := mk some (option.some_injective α)\n\n/-- Embedding of a `subtype`. -/\ndef subtype {α : Sort u_1} (p : α → Prop) : Subtype p ↪ α := mk coe sorry\n\n@[simp] theorem coe_subtype {α : Sort u_1} (p : α → Prop) : ⇑(subtype p) = coe := rfl\n\n/-- Choosing an element `b : β` gives an embedding of `punit` into `β`. -/\ndef punit {β : Sort u_1} (b : β) : PUnit ↪ β := mk (fun (_x : PUnit) => b) sorry\n\n/-- Fixing an element `b : β` gives an embedding `α ↪ α × β`. -/\ndef sectl (α : Type u_1) {β : Type u_2} (b : β) : α ↪ α × β := mk (fun (a : α) => (a, b)) sorry\n\n/-- Fixing an element `a : α` gives an embedding `β ↪ α × β`. -/\ndef sectr {α : Type u_1} (a : α) (β : Type u_2) : β ↪ α × β := mk (fun (b : β) => (a, b)) sorry\n\n/-- Restrict the codomain of an embedding. -/\ndef cod_restrict {α : Sort u_1} {β : Type u_2} (p : set β) (f : α ↪ β)\n (H : ∀ (a : α), coe_fn f a ∈ p) : α ↪ ↥p :=\n mk (fun (a : α) => { val := coe_fn f a, property := H a }) sorry\n\n@[simp] theorem cod_restrict_apply {α : Sort u_1} {β : Type u_2} (p : set β) (f : α ↪ β)\n (H : ∀ (a : α), coe_fn f a ∈ p) (a : α) :\n coe_fn (cod_restrict p f H) a = { val := coe_fn f a, property := H a } :=\n rfl\n\n/-- If `e₁` and `e₂` are embeddings, then so is `prod.map e₁ e₂ : (a, b) ↦ (e₁ a, e₂ b)`. -/\ndef prod_map {α : Type u_1} {β : Type u_2} {γ : Type u_3} {δ : Type u_4} (e₁ : α ↪ β) (e₂ : γ ↪ δ) :\n α × γ ↪ β × δ :=\n mk (prod.map ⇑e₁ ⇑e₂) sorry\n\n@[simp] theorem coe_prod_map {α : Type u_1} {β : Type u_2} {γ : Type u_3} {δ : Type u_4}\n (e₁ : α ↪ β) (e₂ : γ ↪ δ) : ⇑(prod_map e₁ e₂) = prod.map ⇑e₁ ⇑e₂ :=\n rfl\n\n/-- If `e₁` and `e₂` are embeddings, then so is `sum.map e₁ e₂`. -/\ndef sum_map {α : Type u_1} {β : Type u_2} {γ : Type u_3} {δ : Type u_4} (e₁ : α ↪ β) (e₂ : γ ↪ δ) :\n α ⊕ γ ↪ β ⊕ δ :=\n mk (sum.map ⇑e₁ ⇑e₂) sorry\n\n@[simp] theorem coe_sum_map {α : Type u_1} {β : Type u_2} {γ : Type u_3} {δ : Type u_4} (e₁ : α ↪ β)\n (e₂ : γ ↪ δ) : ⇑(sum_map e₁ e₂) = sum.map ⇑e₁ ⇑e₂ :=\n rfl\n\n/-- The embedding of `α` into the sum `α ⊕ β`. -/\n@[simp] theorem inl_apply {α : Type u_1} {β : Type u_2} (val : α) : coe_fn inl val = sum.inl val :=\n Eq.refl (coe_fn inl val)\n\n/-- The embedding of `β` into the sum `α ⊕ β`. -/\n@[simp] theorem inr_apply {α : Type u_1} {β : Type u_2} (val : β) : coe_fn inr val = sum.inr val :=\n Eq.refl (coe_fn inr val)\n\n/-- `sigma.mk` as an `function.embedding`. -/\n@[simp] theorem sigma_mk_apply {α : Type u_1} {β : α → Type u_3} (a : α) (snd : β a) :\n coe_fn (sigma_mk a) snd = sigma.mk a snd :=\n Eq.refl (coe_fn (sigma_mk a) snd)\n\n/-- If `f : α ↪ α'` is an embedding and `g : Π a, β α ↪ β' (f α)` is a family\nof embeddings, then `sigma.map f g` is an embedding. -/\n@[simp] theorem sigma_map_apply {α : Type u_1} {α' : Type u_2} {β : α → Type u_3}\n {β' : α' → Type u_4} (f : α ↪ α') (g : (a : α) → β a ↪ β' (coe_fn f a))\n (x : sigma fun (a : α) => β a) :\n coe_fn (sigma_map f g) x = sigma.map (⇑f) (fun (a : α) => ⇑(g a)) x :=\n Eq.refl (coe_fn (sigma_map f g) x)\n\ndef Pi_congr_right {α : Sort u_1} {β : α → Sort u_2} {γ : α → Sort u_3} (e : (a : α) → β a ↪ γ a) :\n ((a : α) → β a) ↪ (a : α) → γ a :=\n mk (fun (f : (a : α) → β a) (a : α) => coe_fn (e a) (f a)) sorry\n\ndef arrow_congr_left {α : Sort u} {β : Sort v} {γ : Sort w} (e : α ↪ β) : (γ → α) ↪ γ → β :=\n Pi_congr_right fun (_x : γ) => e\n\ndef arrow_congr_right {α : Sort u} {β : Sort v} {γ : Sort w} [Inhabited γ] (e : α ↪ β) :\n (α → γ) ↪ β → γ :=\n let f' : (α → γ) → β → γ :=\n fun (f : α → γ) (b : β) =>\n dite (∃ (c : α), coe_fn e c = b) (fun (h : ∃ (c : α), coe_fn e c = b) => f (classical.some h))\n fun (h : ¬∃ (c : α), coe_fn e c = b) => Inhabited.default;\n mk f' sorry\n\nprotected def subtype_map {α : Sort u_1} {β : Sort u_2} {p : α → Prop} {q : β → Prop} (f : α ↪ β)\n (h : ∀ {x : α}, p x → q (coe_fn f x)) :\n (Subtype fun (x : α) => p x) ↪ Subtype fun (y : β) => q y :=\n mk (subtype.map (⇑f) h) sorry\n\n/-- `set.image` as an embedding `set α ↪ set β`. -/\nprotected def image {α : Type u_1} {β : Type u_2} (f : α ↪ β) : set α ↪ set β :=\n mk (set.image ⇑f) sorry\n\ntheorem swap_apply {α : Type u_1} {β : Type u_2} [DecidableEq α] [DecidableEq β] (f : α ↪ β) (x : α)\n (y : α) (z : α) :\n coe_fn (equiv.swap (coe_fn f x) (coe_fn f y)) (coe_fn f z) =\n coe_fn f (coe_fn (equiv.swap x y) z) :=\n injective.swap_apply (injective f) x y z\n\ntheorem swap_comp {α : Type u_1} {β : Type u_2} [DecidableEq α] [DecidableEq β] (f : α ↪ β) (x : α)\n (y : α) : ⇑(equiv.swap (coe_fn f x) (coe_fn f y)) ∘ ⇑f = ⇑f ∘ ⇑(equiv.swap x y) :=\n injective.swap_comp (injective f) x y\n\nend embedding\n\n\nend function\n\n\nnamespace equiv\n\n\n@[simp] theorem refl_to_embedding {α : Type u_1} :\n equiv.to_embedding (equiv.refl α) = function.embedding.refl α :=\n rfl\n\n@[simp] theorem trans_to_embedding {α : Type u_1} {β : Type u_2} {γ : Type u_3} (e : α ≃ β)\n (f : β ≃ γ) :\n equiv.to_embedding (equiv.trans e f) =\n function.embedding.trans (equiv.to_embedding e) (equiv.to_embedding f) :=\n rfl\n\nend equiv\n\n\nnamespace set\n\n\n/-- The injection map is an embedding between subsets. -/\ndef embedding_of_subset {α : Type u_1} (s : set α) (t : set α) (h : s ⊆ t) : ↥s ↪ ↥t :=\n function.embedding.mk (fun (x : ↥s) => { val := subtype.val x, property := sorry }) sorry\n\nend set\n\n\n-- TODO: these two definitions probably belong somewhere else, so that we can remove the\n\n-- `algebra.group.defs` import.\n\n/--\nThe embedding of a left cancellative semigroup into itself\nby left multiplication by a fixed element.\n -/\n@[simp] theorem add_left_embedding_apply {G : Type u} [add_left_cancel_semigroup G] (g : G)\n (h : G) : coe_fn (add_left_embedding g) h = g + h :=\n Eq.refl (coe_fn (add_left_embedding g) h)\n\n/--\nThe embedding of a right cancellative semigroup into itself\nby right multiplication by a fixed element.\n -/\ndef mul_right_embedding {G : Type u} [right_cancel_semigroup G] (g : G) : G ↪ G :=\n function.embedding.mk (fun (h : G) => h * g) (mul_left_injective g)\n\nend Mathlib", "meta": {"author": "AurelienSaue", "repo": "Mathlib4_auto", "sha": "590df64109b08190abe22358fabc3eae000943f2", "save_path": "github-repos/lean/AurelienSaue-Mathlib4_auto", "path": "github-repos/lean/AurelienSaue-Mathlib4_auto/Mathlib4_auto-590df64109b08190abe22358fabc3eae000943f2/Mathlib/logic/embedding_auto.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.0747700362074065, "lm_q1q2_score": 0.0370929535918116}} {"text": "/-\nCopyright (c) 2019 Minchao Wu. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Minchao Wu, Mario Carneiro\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.default\nimport Mathlib.computability.halting\nimport Mathlib.PostPort\n\nuniverses u_1 u_2 u_3 u v \n\nnamespace Mathlib\n\n/-!\n# Strong reducibility and degrees.\n\nThis file defines the notions of computable many-one reduction and one-one\nreduction between sets, and shows that the corresponding degrees form a\nsemilattice.\n\n## Notations\n\nThis file uses the local notation `⊕'` for `sum.elim` to denote the disjoint union of two degrees.\n\n## References\n\n* [Robert Soare, *Recursively enumerable sets and degrees*][soare1987]\n\n## Tags\n\ncomputability, reducibility, reduction\n-/\n\n/--\n`p` is many-one reducible to `q` if there is a computable function translating questions about `p`\nto questions about `q`.\n-/\ndef many_one_reducible {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β] (p : α → Prop)\n (q : β → Prop) :=\n ∃ (f : α → β), computable f ∧ ∀ (a : α), p a ↔ q (f a)\n\ninfixl:1000 \" ≤₀ \" => Mathlib.many_one_reducible\n\ntheorem many_one_reducible.mk {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β]\n {f : α → β} (q : β → Prop) (h : computable f) : (fun (a : α) => q (f a)) ≤₀ q :=\n Exists.intro f { left := h, right := fun (a : α) => iff.rfl }\n\ntheorem many_one_reducible_refl {α : Type u_1} [primcodable α] (p : α → Prop) : p ≤₀ p := sorry\n\ntheorem many_one_reducible.trans {α : Type u_1} {β : Type u_2} {γ : Type u_3} [primcodable α]\n [primcodable β] [primcodable γ] {p : α → Prop} {q : β → Prop} {r : γ → Prop} :\n p ≤₀ q → q ≤₀ r → p ≤₀ r :=\n sorry\n\ntheorem reflexive_many_one_reducible {α : Type u_1} [primcodable α] :\n reflexive many_one_reducible :=\n many_one_reducible_refl\n\ntheorem transitive_many_one_reducible {α : Type u_1} [primcodable α] :\n transitive many_one_reducible :=\n fun (p q r : α → Prop) => many_one_reducible.trans\n\n/--\n`p` is one-one reducible to `q` if there is an injective computable function translating questions\nabout `p` to questions about `q`.\n-/\ndef one_one_reducible {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β] (p : α → Prop)\n (q : β → Prop) :=\n ∃ (f : α → β), computable f ∧ function.injective f ∧ ∀ (a : α), p a ↔ q (f a)\n\ninfixl:1000 \" ≤₁ \" => Mathlib.one_one_reducible\n\ntheorem one_one_reducible.mk {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β]\n {f : α → β} (q : β → Prop) (h : computable f) (i : function.injective f) :\n (fun (a : α) => q (f a)) ≤₁ q :=\n Exists.intro f { left := h, right := { left := i, right := fun (a : α) => iff.rfl } }\n\ntheorem one_one_reducible_refl {α : Type u_1} [primcodable α] (p : α → Prop) : p ≤₁ p := sorry\n\ntheorem one_one_reducible.trans {α : Type u_1} {β : Type u_2} {γ : Type u_3} [primcodable α]\n [primcodable β] [primcodable γ] {p : α → Prop} {q : β → Prop} {r : γ → Prop} :\n p ≤₁ q → q ≤₁ r → p ≤₁ r :=\n sorry\n\ntheorem one_one_reducible.to_many_one {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β]\n {p : α → Prop} {q : β → Prop} : p ≤₁ q → p ≤₀ q :=\n sorry\n\ntheorem one_one_reducible.of_equiv {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β]\n {e : α ≃ β} (q : β → Prop) (h : computable ⇑e) : (q ∘ ⇑e) ≤₁ q :=\n one_one_reducible.mk q h (equiv.injective e)\n\ntheorem one_one_reducible.of_equiv_symm {α : Type u_1} {β : Type u_2} [primcodable α]\n [primcodable β] {e : α ≃ β} (q : β → Prop) (h : computable ⇑(equiv.symm e)) : q ≤₁ (q ∘ ⇑e) :=\n sorry\n\ntheorem reflexive_one_one_reducible {α : Type u_1} [primcodable α] : reflexive one_one_reducible :=\n one_one_reducible_refl\n\ntheorem transitive_one_one_reducible {α : Type u_1} [primcodable α] :\n transitive one_one_reducible :=\n fun (p q r : α → Prop) => one_one_reducible.trans\n\nnamespace computable_pred\n\n\ntheorem computable_of_many_one_reducible {α : Type u_1} {β : Type u_2} [primcodable α]\n [primcodable β] {p : α → Prop} {q : β → Prop} (h₁ : p ≤₀ q) (h₂ : computable_pred q) :\n computable_pred p :=\n sorry\n\ntheorem computable_of_one_one_reducible {α : Type u_1} {β : Type u_2} [primcodable α]\n [primcodable β] {p : α → Prop} {q : β → Prop} (h : p ≤₁ q) :\n computable_pred q → computable_pred p :=\n computable_of_many_one_reducible (one_one_reducible.to_many_one h)\n\nend computable_pred\n\n\n/-- `p` and `q` are many-one equivalent if each one is many-one reducible to the other. -/\ndef many_one_equiv {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β] (p : α → Prop)\n (q : β → Prop) :=\n p ≤₀ q ∧ q ≤₀ p\n\n/-- `p` and `q` are one-one equivalent if each one is one-one reducible to the other. -/\ndef one_one_equiv {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β] (p : α → Prop)\n (q : β → Prop) :=\n p ≤₁ q ∧ q ≤₁ p\n\ntheorem many_one_equiv_refl {α : Type u_1} [primcodable α] (p : α → Prop) : many_one_equiv p p :=\n { left := many_one_reducible_refl p, right := many_one_reducible_refl p }\n\ntheorem many_one_equiv.symm {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β]\n {p : α → Prop} {q : β → Prop} : many_one_equiv p q → many_one_equiv q p :=\n and.swap\n\ntheorem many_one_equiv.trans {α : Type u_1} {β : Type u_2} {γ : Type u_3} [primcodable α]\n [primcodable β] [primcodable γ] {p : α → Prop} {q : β → Prop} {r : γ → Prop} :\n many_one_equiv p q → many_one_equiv q r → many_one_equiv p r :=\n sorry\n\ntheorem equivalence_of_many_one_equiv {α : Type u_1} [primcodable α] : equivalence many_one_equiv :=\n { left := many_one_equiv_refl,\n right :=\n { left := fun (x y : α → Prop) => many_one_equiv.symm,\n right := fun (x y z : α → Prop) => many_one_equiv.trans } }\n\ntheorem one_one_equiv_refl {α : Type u_1} [primcodable α] (p : α → Prop) : one_one_equiv p p :=\n { left := one_one_reducible_refl p, right := one_one_reducible_refl p }\n\ntheorem one_one_equiv.symm {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β]\n {p : α → Prop} {q : β → Prop} : one_one_equiv p q → one_one_equiv q p :=\n and.swap\n\ntheorem one_one_equiv.trans {α : Type u_1} {β : Type u_2} {γ : Type u_3} [primcodable α]\n [primcodable β] [primcodable γ] {p : α → Prop} {q : β → Prop} {r : γ → Prop} :\n one_one_equiv p q → one_one_equiv q r → one_one_equiv p r :=\n sorry\n\ntheorem equivalence_of_one_one_equiv {α : Type u_1} [primcodable α] : equivalence one_one_equiv :=\n { left := one_one_equiv_refl,\n right :=\n { left := fun (x y : α → Prop) => one_one_equiv.symm,\n right := fun (x y z : α → Prop) => one_one_equiv.trans } }\n\ntheorem one_one_equiv.to_many_one {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β]\n {p : α → Prop} {q : β → Prop} : one_one_equiv p q → many_one_equiv p q :=\n sorry\n\n/-- a computable bijection -/\ndef equiv.computable {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β] (e : α ≃ β) :=\n computable ⇑e ∧ computable ⇑(equiv.symm e)\n\ntheorem equiv.computable.symm {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β]\n {e : α ≃ β} : equiv.computable e → equiv.computable (equiv.symm e) :=\n and.swap\n\ntheorem equiv.computable.trans {α : Type u_1} {β : Type u_2} {γ : Type u_3} [primcodable α]\n [primcodable β] [primcodable γ] {e₁ : α ≃ β} {e₂ : β ≃ γ} :\n equiv.computable e₁ → equiv.computable e₂ → equiv.computable (equiv.trans e₁ e₂) :=\n sorry\n\ntheorem computable.eqv (α : Type u_1) [denumerable α] : equiv.computable (denumerable.eqv α) :=\n { left := computable.encode, right := computable.of_nat α }\n\ntheorem computable.equiv₂ (α : Type u_1) (β : Type u_2) [denumerable α] [denumerable β] :\n equiv.computable (denumerable.equiv₂ α β) :=\n equiv.computable.trans (computable.eqv α) (equiv.computable.symm (computable.eqv β))\n\ntheorem one_one_equiv.of_equiv {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β]\n {e : α ≃ β} (h : equiv.computable e) {p : β → Prop} : one_one_equiv (p ∘ ⇑e) p :=\n { left := one_one_reducible.of_equiv p (and.left h),\n right := one_one_reducible.of_equiv_symm p (and.right h) }\n\ntheorem many_one_equiv.of_equiv {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β]\n {e : α ≃ β} (h : equiv.computable e) {p : β → Prop} : many_one_equiv (p ∘ ⇑e) p :=\n one_one_equiv.to_many_one (one_one_equiv.of_equiv h)\n\ntheorem many_one_equiv.le_congr_left {α : Type u_1} {β : Type u_2} {γ : Type u_3} [primcodable α]\n [primcodable β] [primcodable γ] {p : α → Prop} {q : β → Prop} {r : γ → Prop}\n (h : many_one_equiv p q) : p ≤₀ r ↔ q ≤₀ r :=\n { mp := many_one_reducible.trans (and.right h), mpr := many_one_reducible.trans (and.left h) }\n\ntheorem many_one_equiv.le_congr_right {α : Type u_1} {β : Type u_2} {γ : Type u_3} [primcodable α]\n [primcodable β] [primcodable γ] {p : α → Prop} {q : β → Prop} {r : γ → Prop}\n (h : many_one_equiv q r) : p ≤₀ q ↔ p ≤₀ r :=\n { mp := fun (h' : p ≤₀ q) => many_one_reducible.trans h' (and.left h),\n mpr := fun (h' : p ≤₀ r) => many_one_reducible.trans h' (and.right h) }\n\ntheorem one_one_equiv.le_congr_left {α : Type u_1} {β : Type u_2} {γ : Type u_3} [primcodable α]\n [primcodable β] [primcodable γ] {p : α → Prop} {q : β → Prop} {r : γ → Prop}\n (h : one_one_equiv p q) : p ≤₁ r ↔ q ≤₁ r :=\n { mp := one_one_reducible.trans (and.right h), mpr := one_one_reducible.trans (and.left h) }\n\ntheorem one_one_equiv.le_congr_right {α : Type u_1} {β : Type u_2} {γ : Type u_3} [primcodable α]\n [primcodable β] [primcodable γ] {p : α → Prop} {q : β → Prop} {r : γ → Prop}\n (h : one_one_equiv q r) : p ≤₁ q ↔ p ≤₁ r :=\n { mp := fun (h' : p ≤₁ q) => one_one_reducible.trans h' (and.left h),\n mpr := fun (h' : p ≤₁ r) => one_one_reducible.trans h' (and.right h) }\n\ntheorem many_one_equiv.congr_left {α : Type u_1} {β : Type u_2} {γ : Type u_3} [primcodable α]\n [primcodable β] [primcodable γ] {p : α → Prop} {q : β → Prop} {r : γ → Prop}\n (h : many_one_equiv p q) : many_one_equiv p r ↔ many_one_equiv q r :=\n and_congr (many_one_equiv.le_congr_left h) (many_one_equiv.le_congr_right h)\n\ntheorem many_one_equiv.congr_right {α : Type u_1} {β : Type u_2} {γ : Type u_3} [primcodable α]\n [primcodable β] [primcodable γ] {p : α → Prop} {q : β → Prop} {r : γ → Prop}\n (h : many_one_equiv q r) : many_one_equiv p q ↔ many_one_equiv p r :=\n and_congr (many_one_equiv.le_congr_right h) (many_one_equiv.le_congr_left h)\n\ntheorem one_one_equiv.congr_left {α : Type u_1} {β : Type u_2} {γ : Type u_3} [primcodable α]\n [primcodable β] [primcodable γ] {p : α → Prop} {q : β → Prop} {r : γ → Prop}\n (h : one_one_equiv p q) : one_one_equiv p r ↔ one_one_equiv q r :=\n and_congr (one_one_equiv.le_congr_left h) (one_one_equiv.le_congr_right h)\n\ntheorem one_one_equiv.congr_right {α : Type u_1} {β : Type u_2} {γ : Type u_3} [primcodable α]\n [primcodable β] [primcodable γ] {p : α → Prop} {q : β → Prop} {r : γ → Prop}\n (h : one_one_equiv q r) : one_one_equiv p q ↔ one_one_equiv p r :=\n and_congr (one_one_equiv.le_congr_right h) (one_one_equiv.le_congr_left h)\n\n@[simp] theorem ulower.down_computable {α : Type u_1} [primcodable α] :\n equiv.computable (ulower.equiv α) :=\n { left := primrec.to_comp primrec.ulower_down, right := primrec.to_comp primrec.ulower_up }\n\ntheorem many_one_equiv_up {α : Type u_1} [primcodable α] {p : α → Prop} :\n many_one_equiv (p ∘ ulower.up) p :=\n many_one_equiv.of_equiv (equiv.computable.symm ulower.down_computable)\n\ntheorem one_one_reducible.disjoin_left {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β]\n {p : α → Prop} {q : β → Prop} : p ≤₁ sum.elim p q :=\n Exists.intro sum.inl\n { left := computable.sum_inl,\n right :=\n { left := fun (x y : α) => iff.mp sum.inl.inj_iff, right := fun (a : α) => iff.rfl } }\n\ntheorem one_one_reducible.disjoin_right {α : Type u_1} {β : Type u_2} [primcodable α]\n [primcodable β] {p : α → Prop} {q : β → Prop} : q ≤₁ sum.elim p q :=\n Exists.intro sum.inr\n { left := computable.sum_inr,\n right :=\n { left := fun (x y : β) => iff.mp sum.inr.inj_iff, right := fun (a : β) => iff.rfl } }\n\ntheorem disjoin_many_one_reducible {α : Type u_1} {β : Type u_2} {γ : Type u_3} [primcodable α]\n [primcodable β] [primcodable γ] {p : α → Prop} {q : β → Prop} {r : γ → Prop} :\n p ≤₀ r → q ≤₀ r → sum.elim p q ≤₀ r :=\n sorry\n\ntheorem disjoin_le {α : Type u_1} {β : Type u_2} {γ : Type u_3} [primcodable α] [primcodable β]\n [primcodable γ] {p : α → Prop} {q : β → Prop} {r : γ → Prop} :\n sum.elim p q ≤₀ r ↔ p ≤₀ r ∧ q ≤₀ r :=\n sorry\n\n/--\nComputable and injective mapping of predicates to sets of natural numbers.\n-/\ndef to_nat {α : Type u} [primcodable α] [Inhabited α] (p : set α) : set ℕ :=\n set_of fun (n : ℕ) => p (option.get_or_else (encodable.decode α n) Inhabited.default)\n\n@[simp] theorem to_nat_many_one_reducible {α : Type u} [primcodable α] [Inhabited α] {p : set α} :\n to_nat p ≤₀ p :=\n Exists.intro (fun (n : ℕ) => option.get_or_else (encodable.decode α n) Inhabited.default)\n { left := computable.option_get_or_else computable.decode (computable.const Inhabited.default),\n right := fun (_x : ℕ) => iff.rfl }\n\n@[simp] theorem many_one_reducible_to_nat {α : Type u} [primcodable α] [Inhabited α] {p : set α} :\n p ≤₀ to_nat p :=\n sorry\n\n@[simp] theorem many_one_reducible_to_nat_to_nat {α : Type u} [primcodable α] [Inhabited α]\n {β : Type v} [primcodable β] [Inhabited β] {p : set α} {q : set β} :\n to_nat p ≤₀ to_nat q ↔ p ≤₀ q :=\n sorry\n\n@[simp] theorem to_nat_many_one_equiv {α : Type u} [primcodable α] [Inhabited α] {p : set α} :\n many_one_equiv (to_nat p) p :=\n sorry\n\n@[simp] theorem many_one_equiv_to_nat {α : Type u} [primcodable α] [Inhabited α] {β : Type v}\n [primcodable β] [Inhabited β] (p : set α) (q : set β) :\n many_one_equiv (to_nat p) (to_nat q) ↔ many_one_equiv p q :=\n sorry\n\n/-- A many-one degree is an equivalence class of sets up to many-one equivalence. -/\ndef many_one_degree := quotient (setoid.mk many_one_equiv sorry)\n\nnamespace many_one_degree\n\n\n/-- The many-one degree of a set on a primcodable type. -/\ndef of {α : Type u} [primcodable α] [Inhabited α] (p : α → Prop) : many_one_degree :=\n quotient.mk' (to_nat p)\n\nprotected theorem ind_on {C : many_one_degree → Prop} (d : many_one_degree)\n (h : ∀ (p : set ℕ), C (of p)) : C d :=\n quotient.induction_on' d h\n\n/--\nLifts a function on sets of natural numbers to many-one degrees.\n-/\nprotected def lift_on {φ : Sort u_1} (d : many_one_degree) (f : set ℕ → φ)\n (h : ∀ (p q : ℕ → Prop), many_one_equiv p q → f p = f q) : φ :=\n quotient.lift_on' d f h\n\n@[simp] protected theorem lift_on_eq {φ : Sort u_1} (p : set ℕ) (f : set ℕ → φ)\n (h : ∀ (p q : ℕ → Prop), many_one_equiv p q → f p = f q) :\n many_one_degree.lift_on (of p) f h = f p :=\n rfl\n\n/--\nLifts a binary function on sets of natural numbers to many-one degrees.\n-/\n@[simp] protected def lift_on₂ {φ : Sort u_1} (d₁ : many_one_degree) (d₂ : many_one_degree)\n (f : set ℕ → set ℕ → φ)\n (h :\n ∀ (p₁ p₂ q₁ q₂ : ℕ → Prop), many_one_equiv p₁ p₂ → many_one_equiv q₁ q₂ → f p₁ q₁ = f p₂ q₂) :\n φ :=\n many_one_degree.lift_on d₁ (fun (p : set ℕ) => many_one_degree.lift_on d₂ (f p) sorry) sorry\n\n@[simp] protected theorem lift_on₂_eq {φ : Sort u_1} (p : set ℕ) (q : set ℕ) (f : set ℕ → set ℕ → φ)\n (h :\n ∀ (p₁ p₂ q₁ q₂ : ℕ → Prop), many_one_equiv p₁ p₂ → many_one_equiv q₁ q₂ → f p₁ q₁ = f p₂ q₂) :\n many_one_degree.lift_on₂ (of p) (of q) f h = f p q :=\n rfl\n\n@[simp] theorem of_eq_of {α : Type u} [primcodable α] [Inhabited α] {β : Type v} [primcodable β]\n [Inhabited β] {p : α → Prop} {q : β → Prop} : of p = of q ↔ many_one_equiv p q :=\n sorry\n\nprotected instance inhabited : Inhabited many_one_degree := { default := of ∅ }\n\n/--\nFor many-one degrees `d₁` and `d₂`, `d₁ ≤ d₂` if the sets in `d₁` are many-one reducible to the\nsets in `d₂`.\n-/\nprotected instance has_le : HasLessEq many_one_degree :=\n { LessEq :=\n fun (d₁ d₂ : many_one_degree) => many_one_degree.lift_on₂ d₁ d₂ many_one_reducible sorry }\n\n@[simp] theorem of_le_of {α : Type u} [primcodable α] [Inhabited α] {β : Type v} [primcodable β]\n [Inhabited β] {p : α → Prop} {q : β → Prop} : of p ≤ of q ↔ p ≤₀ q :=\n many_one_reducible_to_nat_to_nat\n\nprotected instance partial_order : partial_order many_one_degree :=\n partial_order.mk LessEq (preorder.lt._default LessEq) le_refl sorry sorry\n\n/-- The join of two degrees, induced by the disjoint union of two underlying sets. -/\nprotected instance has_add : Add many_one_degree :=\n { add :=\n fun (d₁ d₂ : many_one_degree) =>\n many_one_degree.lift_on₂ d₁ d₂ (fun (a b : set ℕ) => of (sum.elim a b)) sorry }\n\n@[simp] theorem add_of {α : Type u} [primcodable α] [Inhabited α] {β : Type v} [primcodable β]\n [Inhabited β] (p : set α) (q : set β) : of (sum.elim p q) = of p + of q :=\n sorry\n\n@[simp] protected theorem add_le {d₁ : many_one_degree} {d₂ : many_one_degree}\n {d₃ : many_one_degree} : d₁ + d₂ ≤ d₃ ↔ d₁ ≤ d₃ ∧ d₂ ≤ d₃ :=\n sorry\n\n@[simp] protected theorem le_add_left (d₁ : many_one_degree) (d₂ : many_one_degree) :\n d₁ ≤ d₁ + d₂ :=\n and.left (iff.mp many_one_degree.add_le (le_refl (d₁ + d₂)))\n\n@[simp] protected theorem le_add_right (d₁ : many_one_degree) (d₂ : many_one_degree) :\n d₂ ≤ d₁ + d₂ :=\n and.right (iff.mp many_one_degree.add_le (le_refl (d₁ + d₂)))\n\nprotected instance semilattice_sup : semilattice_sup many_one_degree :=\n semilattice_sup.mk Add.add partial_order.le partial_order.lt partial_order.le_refl\n partial_order.le_trans partial_order.le_antisymm many_one_degree.le_add_left\n many_one_degree.le_add_right sorry\n\nend Mathlib", "meta": {"author": "AurelienSaue", "repo": "Mathlib4_auto", "sha": "590df64109b08190abe22358fabc3eae000943f2", "save_path": "github-repos/lean/AurelienSaue-Mathlib4_auto", "path": "github-repos/lean/AurelienSaue-Mathlib4_auto/Mathlib4_auto-590df64109b08190abe22358fabc3eae000943f2/Mathlib/computability/reduce_auto.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.0758581847220642, "lm_q1q2_score": 0.03704029199706812}} {"text": "/-\nCopyright (c) 2019 Lucas Allen. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Lucas Allen and Scott Morrison\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.default\nimport Mathlib.data.mllist\nimport Mathlib.tactic.solve_by_elim\nimport Mathlib.PostPort\n\nuniverses l \n\nnamespace Mathlib\n\n/-!\n# `suggest` and `library_search`\n\n`suggest` and `library_search` are a pair of tactics for applying lemmas from the library to the\ncurrent goal.\n\n* `suggest` prints a list of `exact ...` or `refine ...` statements, which may produce new goals\n* `library_search` prints a single `exact ...` which closes the goal, or fails\n-/\n\nnamespace tactic\n\n\nnamespace suggest\n\n\n/-- Map a name (typically a head symbol) to a \"canonical\" definitional synonym.\nGiven a name `n`, we want a name `n'` such that a sufficiently applied\nexpression with head symbol `n` is always definitionally equal to an expression\nwith head symbol `n'`.\nThus, we can search through all lemmas with a result type of `n'`\nto solve a goal with head symbol `n`.\n\nFor example, `>` is mapped to `<` because `a > b` is definitionally equal to `b < a`,\nand `not` is mapped to `false` because `¬ a` is definitionally equal to `p → false`\nThe default is that the original argument is returned, so `<` is just mapped to `<`.\n\n`normalize_synonym` is called for every lemma in the library, so it needs to be fast.\n-/\n-- TODO this is a hack; if you suspect more cases here would help, please report them\n\n/--\nCompute the head symbol of an expression, then normalise synonyms.\n\nThis is only used when analysing the goal, so it is okay to do more expensive analysis here.\n-/\n-- We may want to tweak this further?\n\n-- We first have a various \"customisations\":\n\n-- Because in `ℕ` `a.succ ≤ b` is definitionally `a < b`,\n\n-- we add some special cases to allow looking for `<` lemmas even when the goal has a `≤`.\n\n-- Note we only do this in the `ℕ` case, for performance.\n\n-- And then the generic cases:\n\n/--\nA declaration can match the head symbol of the current goal in four possible ways:\n* `ex` : an exact match\n* `mp` : the declaration returns an `iff`, and the right hand side matches the goal\n* `mpr` : the declaration returns an `iff`, and the left hand side matches the goal\n* `both`: the declaration returns an `iff`, and the both sides match the goal\n-/\ninductive head_symbol_match where\n| ex : head_symbol_match\n| mp : head_symbol_match\n| mpr : head_symbol_match\n| both : head_symbol_match\n\n/-- a textual representation of a `head_symbol_match`, for trace debugging. -/\ndef head_symbol_match.to_string : head_symbol_match → string := sorry\n\n/-- Determine if, and in which way, a given expression matches the specified head symbol. -/\n/-- A package of `declaration` metadata, including the way in which its type matches the head symbol\nwhich we are searching for. -/\n/--\nGenerate a `decl_data` from the given declaration if\nit matches the head symbol `hs` for the current goal.\n-/\n-- We used to check here for private declarations, or declarations with certain suffixes.\n\n-- It turns out `apply` is so fast, it's better to just try them all.\n\n/-- Retrieve all library definitions with a given head symbol. -/\n/--\nWe unpack any element of a list of `decl_data` corresponding to an `↔` statement that could apply\nin both directions into two separate elements.\n\nThis ensures that both directions can be independently returned by `suggest`,\nand avoids a problem where the application of one direction prevents\nthe application of the other direction. (See `exp_le_exp` in the tests.)\n-/\n/--\nApply the lemma `e`, then attempt to close all goals using\n`solve_by_elim opt`, failing if `close_goals = tt`\nand there are any goals remaining.\n\nReturns the number of subgoals which were closed using `solve_by_elim`.\n-/\n-- Implementation note: as this is used by both `library_search` and `suggest`,\n\n-- we first run `solve_by_elim` separately on the independent goals,\n\n-- whether or not `close_goals` is set,\n\n-- and then run `solve_by_elim { all_goals := tt }`,\n\n-- requiring that it succeeds if `close_goals = tt`.\n\n/--\nApply the declaration `d` (or the forward and backward implications separately, if it is an `iff`),\nand then attempt to solve the subgoal using `apply_and_solve`.\n\nReturns the number of subgoals successfully closed.\n-/\n/-- An `application` records the result of a successful application of a library lemma. -/\nend suggest\n\n\n-- Call `apply_declaration`, then prepare the tactic script and\n\n-- count the number of local hypotheses used.\n\n-- (This tactic block is only executed when we evaluate the mllist,\n\n-- so we need to do the `focus1` here.)\n\n-- implementation note: we produce a `tactic (mllist tactic application)` first,\n\n-- because it's easier to work in the tactic monad, but in a moment we squash this\n\n-- down to an `mllist tactic application`.\n\n/--\nThe core `suggest` tactic.\nIt attempts to apply a declaration from the library,\nthen solve new goals using `solve_by_elim`.\n\nIt returns a list of `application`s consisting of fields:\n* `state`, a tactic state resulting from the successful application of a declaration from\n the library,\n* `script`, a string of the form `Try this: refine ...` or `Try this: exact ...` which will\n reproduce that tactic state,\n* `decl`, an `option declaration` indicating the declaration that was applied\n (or none, if `solve_by_elim` succeeded),\n* `num_goals`, the number of remaining goals, and\n* `hyps_used`, the number of local hypotheses used in the solution.\n-/\n/--\nSee `suggest_core`.\n\nReturns a list of at most `limit` `application`s,\nsorted by number of goals, and then (reverse) number of hypotheses used.\n-/\n/--\nReturns a list of at most `limit` strings, of the form `Try this: exact ...` or\n`Try this: refine ...`, which make progress on the current goal using a declaration\nfrom the library.\n-/\n/--\nReturns a string of the form `Try this: exact ...`, which closes the current goal.\n-/\nnamespace interactive\n\n\n/--\n`suggest` tries to apply suitable theorems/defs from the library, and generates\na list of `exact ...` or `refine ...` scripts that could be used at this step.\nIt leaves the tactic state unchanged. It is intended as a complement of the search\nfunction in your editor, the `#find` tactic, and `library_search`.\n\n`suggest` takes an optional natural number `num` as input and returns the first `num`\n(or less, if all possibilities are exhausted) possibilities ordered by length of lemma names.\nThe default for `num` is `50`.\nFor performance reasons `suggest` uses monadic lazy lists (`mllist`). This means that\n`suggest` might miss some results if `num` is not large enough. However, because\n`suggest` uses monadic lazy lists, smaller values of `num` run faster than larger values.\n\nYou can add additional lemmas to be used along with local hypotheses\nafter the application of a library lemma,\nusing the same syntax as for `solve_by_elim`, e.g.\n```\nexample {a b c d: nat} (h₁ : a < c) (h₂ : b < d) : max (c + d) (a + b) = (c + d) :=\nbegin\n suggest [add_lt_add], -- Says: `Try this: exact max_eq_left_of_lt (add_lt_add h₁ h₂)`\nend\n```\nYou can also use `suggest with attr` to include all lemmas with the attribute `attr`.\n-/\n/--\n`suggest` lists possible usages of the `refine` tactic and leaves the tactic state unchanged.\nIt is intended as a complement of the search function in your editor, the `#find` tactic, and\n`library_search`.\n\n`suggest` takes an optional natural number `num` as input and returns the first `num` (or less, if\nall possibilities are exhausted) possibilities ordered by length of lemma names.\nThe default for `num` is `50`.\n\nFor performance reasons `suggest` uses monadic lazy lists (`mllist`). This means that `suggest`\nmight miss some results if `num` is not large enough. However, because `suggest` uses monadic\nlazy lists, smaller values of `num` run faster than larger values.\n\nAn example of `suggest` in action,\n\n```lean\nexample (n : nat) : n < n + 1 :=\nbegin suggest, sorry end\n```\n\nprints the list,\n\n```lean\nTry this: exact nat.lt.base n\nTry this: exact nat.lt_succ_self n\nTry this: refine not_le.mp _\nTry this: refine gt_iff_lt.mp _\nTry this: refine nat.lt.step _\nTry this: refine lt_of_not_ge _\n...\n```\n-/\n-- Turn off `Try this: exact ...` trace message for `library_search`\n\n/--\n`library_search` is a tactic to identify existing lemmas in the library. It tries to close the\ncurrent goal by applying a lemma from the library, then discharging any new goals using\n`solve_by_elim`.\n\nIf it succeeds, it prints a trace message `exact ...` which can replace the invocation\nof `library_search`.\n\nTypical usage is:\n```lean\nexample (n m k : ℕ) : n * (m - k) = n * m - n * k :=\nby library_search -- Try this: exact nat.mul_sub_left_distrib n m k\n```\n\nBy default `library_search` only unfolds `reducible` definitions\nwhen attempting to match lemmas against the goal.\nPreviously, it would unfold most definitions, sometimes giving surprising answers, or slow answers.\nThe old behaviour is still available via `library_search!`.\n\nYou can add additional lemmas to be used along with local hypotheses\nafter the application of a library lemma,\nusing the same syntax as for `solve_by_elim`, e.g.\n```\nexample {a b c d: nat} (h₁ : a < c) (h₂ : b < d) : max (c + d) (a + b) = (c + d) :=\nbegin\n library_search [add_lt_add], -- Says: `Try this: exact max_eq_left_of_lt (add_lt_add h₁ h₂)`\nend\n```\nYou can also use `library_search with attr` to include all lemmas with the attribute `attr`.\n-/\nend interactive\n\n\n/-- Invoking the hole command `library_search` (\"Use `library_search` to complete the goal\") calls\nthe tactic `library_search` to produce a proof term with the type of the hole.\n\nRunning it on\n\n```lean\nexample : 0 < 1 :=\n{!!}\n```\n\nproduces\n\n```lean\nexample : 0 < 1 :=\nnat.one_pos\n```\n-/\nend Mathlib", "meta": {"author": "AurelienSaue", "repo": "Mathlib4_auto", "sha": "590df64109b08190abe22358fabc3eae000943f2", "save_path": "github-repos/lean/AurelienSaue-Mathlib4_auto", "path": "github-repos/lean/AurelienSaue-Mathlib4_auto/Mathlib4_auto-590df64109b08190abe22358fabc3eae000943f2/Mathlib/tactic/suggest_auto.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47268347662043286, "lm_q2_score": 0.07807816675387327, "lm_q1q2_score": 0.03690625930937071}} {"text": "/-\nCopyright (c) 2018 Simon Hudon. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthor: Simon Hudon\n\nInstances of `traversable` for types from the core library\n-/\n\nimport category.traversable.basic category.basic category.functor category.applicative\nimport data.list.basic data.set.lattice\n\nuniverses u v\n\nsection option\n\nopen functor\n\nvariables {F G : Type u → Type u}\nvariables [applicative F] [applicative G]\nvariables [is_lawful_applicative F] [is_lawful_applicative G]\n\nlemma option.id_traverse {α} (x : option α) : option.traverse id.mk x = x :=\nby cases x; refl\n\nlemma option.comp_traverse {α β γ} (f : β → F γ) (g : α → G β) (x : option α) :\n option.traverse (comp.mk ∘ (<$>) f ∘ g) x =\n comp.mk (option.traverse f <$> option.traverse g x) :=\nby cases x; simp! with functor_norm; refl\n\nlemma option.traverse_eq_map_id {α β} (f : α → β) (x : option α) :\n traverse (id.mk ∘ f) x = id.mk (f <$> x) :=\nby cases x; refl\n\nvariable (η : applicative_transformation F G)\n\nlemma option.naturality {α β} (f : α → F β) (x : option α) :\n η (option.traverse f x) = option.traverse (@η _ ∘ f) x :=\nby cases x with x; simp! [*] with functor_norm\n\nend option\n\ninstance : is_lawful_traversable option :=\n{ id_traverse := @option.id_traverse,\n comp_traverse := @option.comp_traverse,\n traverse_eq_map_id := @option.traverse_eq_map_id,\n naturality := @option.naturality }\n\nnamespace list\n\nvariables {F G : Type u → Type u}\nvariables [applicative F] [applicative G]\n\nsection\nvariables [is_lawful_applicative F] [is_lawful_applicative G]\n\nopen applicative functor\nopen list (cons)\n\nprotected lemma id_traverse {α} (xs : list α) :\n list.traverse id.mk xs = xs :=\nby induction xs; simp! * with functor_norm; refl\n\nprotected lemma comp_traverse {α β γ} (f : β → F γ) (g : α → G β) (x : list α) :\n list.traverse (comp.mk ∘ (<$>) f ∘ g) x =\n comp.mk (list.traverse f <$> list.traverse g x) :=\nby induction x; simp! * with functor_norm; refl\n\nprotected lemma traverse_eq_map_id {α β} (f : α → β) (x : list α) :\n list.traverse (id.mk ∘ f) x = id.mk (f <$> x) :=\nby induction x; simp! * with functor_norm; refl\n\nvariable (η : applicative_transformation F G)\n\nprotected lemma naturality {α β} (f : α → F β) (x : list α) :\n η (list.traverse f x) = list.traverse (@η _ ∘ f) x :=\nby induction x; simp! * with functor_norm\nopen nat\n\ninstance : is_lawful_traversable list :=\n{ id_traverse := @list.id_traverse,\n comp_traverse := @list.comp_traverse,\n traverse_eq_map_id := @list.traverse_eq_map_id,\n naturality := @list.naturality }\nend\n\nsection traverse\nvariables {α' β' : Type u} (f : α' → F β')\n\n@[simp] lemma traverse_nil : traverse f ([] : list α') = (pure [] : F (list β')) := rfl\n\n@[simp] lemma traverse_cons (a : α') (l : list α') :\n traverse f (a :: l) = (::) <$> f a <*> traverse f l := rfl\n\nvariables [is_lawful_applicative F]\n\n@[simp] lemma traverse_append :\n ∀ (as bs : list α'), traverse f (as ++ bs) = (++) <$> traverse f as <*> traverse f bs\n| [] bs :=\n have has_append.append ([] : list β') = id, by funext; refl,\n by simp [this] with functor_norm\n| (a :: as) bs := by simp [traverse_append as bs] with functor_norm; congr\n\nlemma mem_traverse {f : α' → set β'} :\n ∀(l : list α') (n : list β'), n ∈ traverse f l ↔ forall₂ (λb a, b ∈ f a) n l\n| [] [] := by simp\n| (a::as) [] := by simp; exact assume h, match h with end\n| [] (b::bs) := by simp\n| (a::as) (b::bs) :=\n suffices (b :: bs : list β') ∈ traverse f (a :: as) ↔ b ∈ f a ∧ bs ∈ traverse f as,\n by simpa [mem_traverse as bs],\n iff.intro\n (assume ⟨_, ⟨b, hb, rfl⟩, _, hl, rfl⟩, ⟨hb, hl⟩)\n (assume ⟨hb, hl⟩, ⟨_, ⟨b, hb, rfl⟩, _, hl, rfl⟩)\n\nend traverse\n\nend list\n\nnamespace sum\n\nsection traverse\nvariables {σ : Type u}\nvariables {F G : Type u → Type u}\nvariables [applicative F] [applicative G]\n\nopen applicative functor\nopen list (cons)\n\nvariables [is_lawful_applicative F] [is_lawful_applicative G]\n\nprotected lemma id_traverse {σ α} (x : σ ⊕ α) : sum.traverse id.mk x = x :=\nby cases x; refl\n\nprotected lemma comp_traverse {α β γ} (f : β → F γ) (g : α → G β) (x : σ ⊕ α) :\n sum.traverse (comp.mk ∘ (<$>) f ∘ g) x =\n comp.mk (sum.traverse f <$> sum.traverse g x) :=\nby cases x; simp! [sum.traverse,map_id] with functor_norm; refl\n\nprotected lemma traverse_eq_map_id {α β} (f : α → β) (x : σ ⊕ α) :\n sum.traverse (id.mk ∘ f) x = id.mk (f <$> x) :=\nby induction x; simp! * with functor_norm; refl\n\nprotected lemma map_traverse {α β γ} (g : α → G β) (f : β → γ) (x : σ ⊕ α) :\n (<$>) f <$> sum.traverse g x = sum.traverse ((<$>) f ∘ g) x :=\nby cases x; simp [sum.traverse, id_map] with functor_norm; congr; refl\n\nprotected lemma traverse_map {α β γ : Type u} (g : α → β) (f : β → G γ) (x : σ ⊕ α) :\n sum.traverse f (g <$> x) = sum.traverse (f ∘ g) x :=\nby cases x; simp [sum.traverse, id_map] with functor_norm; refl\n\nvariable (η : applicative_transformation F G)\n\nprotected lemma naturality {α β} (f : α → F β) (x : σ ⊕ α) :\n η (sum.traverse f x) = sum.traverse (@η _ ∘ f) x :=\nby cases x; simp! [sum.traverse] with functor_norm\n\nend traverse\n\ninstance {σ : Type u} : is_lawful_traversable.{u} (sum σ) :=\n{ id_traverse := @sum.id_traverse σ,\n comp_traverse := @sum.comp_traverse σ,\n traverse_eq_map_id := @sum.traverse_eq_map_id σ,\n naturality := @sum.naturality σ }\n\nend sum\n", "meta": {"author": "digama0", "repo": "mathlib-ITP2019", "sha": "5cbd0362e04e671ef5db1284870592af6950197c", "save_path": "github-repos/lean/digama0-mathlib-ITP2019", "path": "github-repos/lean/digama0-mathlib-ITP2019/mathlib-ITP2019-5cbd0362e04e671ef5db1284870592af6950197c/src/category/traversable/instances.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46490157137338844, "lm_q2_score": 0.07921032410902437, "lm_q1q2_score": 0.03682500414728083}} {"text": "/-\nCopyright (c) 2021 Anne Baanen. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Anne Baanen\n\n! This file was ported from Lean 3 source module data.fun_like.basic\n! leanprover-community/mathlib commit 448144f7ae193a8990cb7473c9e9a01990f64ac7\n! Please do not edit these lines, except to modify the commit id\n! if you have ported upstream changes.\n-/\nimport Mathbin.Logic.Function.Basic\nimport Mathbin.Tactic.Lint.Default\nimport Mathbin.Tactic.NormCast\n\n/-!\n# Typeclass for a type `F` with an injective map to `A → B`\n\n> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.\n> Any changes to this file require a corresponding PR to mathlib4.\n\nThis typeclass is primarily for use by homomorphisms like `monoid_hom` and `linear_map`.\n\n## Basic usage of `fun_like`\n\nA typical type of morphisms should be declared as:\n```\nstructure my_hom (A B : Type*) [my_class A] [my_class B] :=\n(to_fun : A → B)\n(map_op' : ∀ {x y : A}, to_fun (my_class.op x y) = my_class.op (to_fun x) (to_fun y))\n\nnamespace my_hom\n\nvariables (A B : Type*) [my_class A] [my_class B]\n\n-- This instance is optional if you follow the \"morphism class\" design below:\ninstance : fun_like (my_hom A B) A (λ _, B) :=\n{ coe := my_hom.to_fun, coe_injective' := λ f g h, by cases f; cases g; congr' }\n\n/-- Helper instance for when there's too many metavariables to apply\n`fun_like.has_coe_to_fun` directly. -/\ninstance : has_coe_to_fun (my_hom A B) (λ _, A → B) := fun_like.has_coe_to_fun\n\n@[simp] lemma to_fun_eq_coe {f : my_hom A B} : f.to_fun = (f : A → B) := rfl\n\n@[ext] theorem ext {f g : my_hom A B} (h : ∀ x, f x = g x) : f = g := fun_like.ext f g h\n\n/-- Copy of a `my_hom` with a new `to_fun` equal to the old one. Useful to fix definitional\nequalities. -/\nprotected def copy (f : my_hom A B) (f' : A → B) (h : f' = ⇑f) : my_hom A B :=\n{ to_fun := f',\n map_op' := h.symm ▸ f.map_op' }\n\nend my_hom\n```\n\nThis file will then provide a `has_coe_to_fun` instance and various\nextensionality and simp lemmas.\n\n## Morphism classes extending `fun_like`\n\nThe `fun_like` design provides further benefits if you put in a bit more work.\nThe first step is to extend `fun_like` to create a class of those types satisfying\nthe axioms of your new type of morphisms.\nContinuing the example above:\n\n```\nsection\nset_option old_structure_cmd true\n\n/-- `my_hom_class F A B` states that `F` is a type of `my_class.op`-preserving morphisms.\nYou should extend this class when you extend `my_hom`. -/\nclass my_hom_class (F : Type*) (A B : out_param $ Type*) [my_class A] [my_class B]\n extends fun_like F A (λ _, B) :=\n(map_op : ∀ (f : F) (x y : A), f (my_class.op x y) = my_class.op (f x) (f y))\n\nend\n@[simp] lemma map_op {F A B : Type*} [my_class A] [my_class B] [my_hom_class F A B]\n (f : F) (x y : A) : f (my_class.op x y) = my_class.op (f x) (f y) :=\nmy_hom_class.map_op\n\n-- You can replace `my_hom.fun_like` with the below instance:\ninstance : my_hom_class (my_hom A B) A B :=\n{ coe := my_hom.to_fun,\n coe_injective' := λ f g h, by cases f; cases g; congr',\n map_op := my_hom.map_op' }\n\n-- [Insert `has_coe_to_fun`, `to_fun_eq_coe`, `ext` and `copy` here]\n```\n\nThe second step is to add instances of your new `my_hom_class` for all types extending `my_hom`.\nTypically, you can just declare a new class analogous to `my_hom_class`:\n\n```\nstructure cooler_hom (A B : Type*) [cool_class A] [cool_class B]\n extends my_hom A B :=\n(map_cool' : to_fun cool_class.cool = cool_class.cool)\n\nsection\nset_option old_structure_cmd true\n\nclass cooler_hom_class (F : Type*) (A B : out_param $ Type*) [cool_class A] [cool_class B]\n extends my_hom_class F A B :=\n(map_cool : ∀ (f : F), f cool_class.cool = cool_class.cool)\n\nend\n\n@[simp] lemma map_cool {F A B : Type*} [cool_class A] [cool_class B] [cooler_hom_class F A B]\n (f : F) : f cool_class.cool = cool_class.cool :=\nmy_hom_class.map_op\n\n-- You can also replace `my_hom.fun_like` with the below instance:\ninstance : cool_hom_class (cool_hom A B) A B :=\n{ coe := cool_hom.to_fun,\n coe_injective' := λ f g h, by cases f; cases g; congr',\n map_op := cool_hom.map_op',\n map_cool := cool_hom.map_cool' }\n\n-- [Insert `has_coe_to_fun`, `to_fun_eq_coe`, `ext` and `copy` here]\n```\n\nThen any declaration taking a specific type of morphisms as parameter can instead take the\nclass you just defined:\n```\n-- Compare with: lemma do_something (f : my_hom A B) : sorry := sorry\nlemma do_something {F : Type*} [my_hom_class F A B] (f : F) : sorry := sorry\n```\n\nThis means anything set up for `my_hom`s will automatically work for `cool_hom_class`es,\nand defining `cool_hom_class` only takes a constant amount of effort,\ninstead of linearly increasing the work per `my_hom`-related declaration.\n\n-/\n\n\n-- This instance should have low priority, to ensure we follow the chain\n-- `fun_like → has_coe_to_fun`\nattribute [instance] coeFnTrans\n\n/- warning: fun_like -> FunLike is a dubious translation:\nlean 3 declaration is\n Sort.{u1} -> (forall (α : outParam.{succ u2} Sort.{u2}), (outParam.{max u2 (succ u3)} (α -> Sort.{u3})) -> Sort.{max 1 (imax u1 u2 u3)})\nbut is expected to have type\n Sort.{u1} -> (forall (α : outParam.{succ u2} Sort.{u2}), (outParam.{max u2 (succ u3)} (α -> Sort.{u3})) -> Sort.{max (max (max 1 u1) u2) u3})\nCase conversion may be inaccurate. Consider using '#align fun_like FunLikeₓ'. -/\n/-- The class `fun_like F α β` expresses that terms of type `F` have an\ninjective coercion to functions from `α` to `β`.\n\nThis typeclass is used in the definition of the homomorphism typeclasses,\nsuch as `zero_hom_class`, `mul_hom_class`, `monoid_hom_class`, ....\n-/\nclass FunLike (F : Sort _) (α : outParam (Sort _)) (β : outParam <| α → Sort _) where\n coe : F → ∀ a : α, β a\n coe_injective' : Function.Injective coe\n#align fun_like FunLike\n\nsection Dependent\n\n/-! ### `fun_like F α β` where `β` depends on `a : α` -/\n\n\nvariable (F α : Sort _) (β : α → Sort _)\n\nnamespace FunLike\n\nvariable {F α β} [i : FunLike F α β]\n\ninclude i\n\n-- Give this a priority between `coe_fn_trans` and the default priority\n-- `α` and `β` are out_params, so this instance should not be dangerous\n@[nolint dangerous_instance]\ninstance (priority := 100) : CoeFun F fun _ => ∀ a : α, β a where coe := FunLike.coe\n\n/- warning: fun_like.coe_eq_coe_fn -> FunLike.coe_eq_coe_fn is a dubious translation:\nlean 3 declaration is\n forall {F : Sort.{u1}} {α : Sort.{u2}} {β : α -> Sort.{u3}} [i : FunLike.{u1, u2, u3} F α β], Eq.{imax u1 u2 u3} (F -> (forall (a : α), β a)) (FunLike.coe.{u1, u2, u3} F α (fun (a : α) => β a) i) (coeFn.{u1, imax u2 u3} F (fun (ᾰ : F) => forall (a : α), β a) (FunLike.hasCoeToFun.{u1, u2, u3} F α β i))\nbut is expected to have type\n forall {F : Sort.{u3}} {α : Sort.{u2}} {β : α -> Sort.{u1}} [i : FunLike.{u3, u2, u1} F α β], Eq.{imax u3 u2 u1} (F -> (forall (a : α), β a)) (FunLike.coe.{u3, u2, u1} F α β i) (fun (f : F) => FunLike.coe.{u3, u2, u1} F α (fun (a : α) => β a) i f)\nCase conversion may be inaccurate. Consider using '#align fun_like.coe_eq_coe_fn FunLike.coe_eq_coe_fnₓ'. -/\n@[simp]\ntheorem coe_eq_coe_fn : (FunLike.coe : F → ∀ a : α, β a) = coeFn :=\n rfl\n#align fun_like.coe_eq_coe_fn FunLike.coe_eq_coe_fn\n\n/- warning: fun_like.coe_injective -> FunLike.coe_injective is a dubious translation:\nlean 3 declaration is\n forall {F : Sort.{u1}} {α : Sort.{u2}} {β : α -> Sort.{u3}} [i : FunLike.{u1, u2, u3} F α β], Function.Injective.{u1, imax u2 u3} F (forall (a : α), β a) (coeFn.{u1, imax u2 u3} F (fun (ᾰ : F) => forall (a : α), β a) (FunLike.hasCoeToFun.{u1, u2, u3} F α β i))\nbut is expected to have type\n forall {F : Sort.{u3}} {α : Sort.{u2}} {β : α -> Sort.{u1}} [i : FunLike.{u3, u2, u1} F α β], Function.Injective.{u3, imax u2 u1} F (forall (a : α), β a) (fun (f : F) => FunLike.coe.{u3, u2, u1} F α (fun (a : α) => β a) i f)\nCase conversion may be inaccurate. Consider using '#align fun_like.coe_injective FunLike.coe_injectiveₓ'. -/\ntheorem coe_injective : Function.Injective (coeFn : F → ∀ a : α, β a) :=\n FunLike.coe_injective'\n#align fun_like.coe_injective FunLike.coe_injective\n\n/- warning: fun_like.coe_fn_eq -> FunLike.coe_fn_eq is a dubious translation:\nlean 3 declaration is\n forall {F : Sort.{u1}} {α : Sort.{u2}} {β : α -> Sort.{u3}} [i : FunLike.{u1, u2, u3} F α β] {f : F} {g : F}, Iff (Eq.{imax u2 u3} ((fun (_x : F) => forall (a : α), β a) f) (coeFn.{u1, imax u2 u3} F (fun (_x : F) => forall (a : α), β a) (FunLike.hasCoeToFun.{u1, u2, u3} F α β i) f) (coeFn.{u1, imax u2 u3} F (fun (_x : F) => forall (a : α), β a) (FunLike.hasCoeToFun.{u1, u2, u3} F α β i) g)) (Eq.{u1} F f g)\nbut is expected to have type\n forall {F : Sort.{u1}} {α : Sort.{u3}} {β : α -> Sort.{u2}} [i : FunLike.{u1, u3, u2} F α β] {f : F} {g : F}, Iff (Eq.{imax u3 u2} (forall (a : α), β a) (FunLike.coe.{u1, u3, u2} F α (fun (_x : α) => β _x) i f) (FunLike.coe.{u1, u3, u2} F α (fun (_x : α) => β _x) i g)) (Eq.{u1} F f g)\nCase conversion may be inaccurate. Consider using '#align fun_like.coe_fn_eq FunLike.coe_fn_eqₓ'. -/\n@[simp, norm_cast]\ntheorem coe_fn_eq {f g : F} : (f : ∀ a : α, β a) = (g : ∀ a : α, β a) ↔ f = g :=\n ⟨fun h => @coe_injective _ _ _ i _ _ h, fun h => by cases h <;> rfl⟩\n#align fun_like.coe_fn_eq FunLike.coe_fn_eq\n\n/- warning: fun_like.ext' -> FunLike.ext' is a dubious translation:\nlean 3 declaration is\n forall {F : Sort.{u1}} {α : Sort.{u2}} {β : α -> Sort.{u3}} [i : FunLike.{u1, u2, u3} F α β] {f : F} {g : F}, (Eq.{imax u2 u3} ((fun (_x : F) => forall (a : α), β a) f) (coeFn.{u1, imax u2 u3} F (fun (_x : F) => forall (a : α), β a) (FunLike.hasCoeToFun.{u1, u2, u3} F α β i) f) (coeFn.{u1, imax u2 u3} F (fun (_x : F) => forall (a : α), β a) (FunLike.hasCoeToFun.{u1, u2, u3} F α β i) g)) -> (Eq.{u1} F f g)\nbut is expected to have type\n forall {F : Sort.{u1}} {α : Sort.{u3}} {β : α -> Sort.{u2}} [i : FunLike.{u1, u3, u2} F α β] {f : F} {g : F}, (Eq.{imax u3 u2} (forall (a : α), β a) (FunLike.coe.{u1, u3, u2} F α (fun (_x : α) => β _x) i f) (FunLike.coe.{u1, u3, u2} F α (fun (_x : α) => β _x) i g)) -> (Eq.{u1} F f g)\nCase conversion may be inaccurate. Consider using '#align fun_like.ext' FunLike.ext'ₓ'. -/\ntheorem ext' {f g : F} (h : (f : ∀ a : α, β a) = (g : ∀ a : α, β a)) : f = g :=\n coe_injective h\n#align fun_like.ext' FunLike.ext'\n\n/- warning: fun_like.ext'_iff -> FunLike.ext'_iff is a dubious translation:\nlean 3 declaration is\n forall {F : Sort.{u1}} {α : Sort.{u2}} {β : α -> Sort.{u3}} [i : FunLike.{u1, u2, u3} F α β] {f : F} {g : F}, Iff (Eq.{u1} F f g) (Eq.{imax u2 u3} ((fun (_x : F) => forall (a : α), β a) f) (coeFn.{u1, imax u2 u3} F (fun (_x : F) => forall (a : α), β a) (FunLike.hasCoeToFun.{u1, u2, u3} F α β i) f) (coeFn.{u1, imax u2 u3} F (fun (_x : F) => forall (a : α), β a) (FunLike.hasCoeToFun.{u1, u2, u3} F α β i) g))\nbut is expected to have type\n forall {F : Sort.{u3}} {α : Sort.{u2}} {β : α -> Sort.{u1}} [i : FunLike.{u3, u2, u1} F α β] {f : F} {g : F}, Iff (Eq.{u3} F f g) (Eq.{imax u2 u1} (forall (a : α), β a) (FunLike.coe.{u3, u2, u1} F α (fun (_x : α) => β _x) i f) (FunLike.coe.{u3, u2, u1} F α (fun (_x : α) => β _x) i g))\nCase conversion may be inaccurate. Consider using '#align fun_like.ext'_iff FunLike.ext'_iffₓ'. -/\ntheorem ext'_iff {f g : F} : f = g ↔ (f : ∀ a : α, β a) = (g : ∀ a : α, β a) :=\n coe_fn_eq.symm\n#align fun_like.ext'_iff FunLike.ext'_iff\n\n/- warning: fun_like.ext -> FunLike.ext is a dubious translation:\nlean 3 declaration is\n forall {F : Sort.{u1}} {α : Sort.{u2}} {β : α -> Sort.{u3}} [i : FunLike.{u1, u2, u3} F α β] (f : F) (g : F), (forall (x : α), Eq.{u3} (β x) (coeFn.{u1, imax u2 u3} F (fun (_x : F) => forall (a : α), β a) (FunLike.hasCoeToFun.{u1, u2, u3} F α β i) f x) (coeFn.{u1, imax u2 u3} F (fun (_x : F) => forall (a : α), β a) (FunLike.hasCoeToFun.{u1, u2, u3} F α β i) g x)) -> (Eq.{u1} F f g)\nbut is expected to have type\n forall {F : Sort.{u2}} {α : Sort.{u1}} {β : α -> Sort.{u3}} [i : FunLike.{u2, u1, u3} F α β] (f : F) (g : F), (forall (x : α), Eq.{u3} (β x) (FunLike.coe.{u2, u1, u3} F α (fun (_x : α) => β _x) i f x) (FunLike.coe.{u2, u1, u3} F α (fun (_x : α) => β _x) i g x)) -> (Eq.{u2} F f g)\nCase conversion may be inaccurate. Consider using '#align fun_like.ext FunLike.extₓ'. -/\ntheorem ext (f g : F) (h : ∀ x : α, f x = g x) : f = g :=\n coe_injective (funext h)\n#align fun_like.ext FunLike.ext\n\n/- warning: fun_like.ext_iff -> FunLike.ext_iff is a dubious translation:\nlean 3 declaration is\n forall {F : Sort.{u1}} {α : Sort.{u2}} {β : α -> Sort.{u3}} [i : FunLike.{u1, u2, u3} F α β] {f : F} {g : F}, Iff (Eq.{u1} F f g) (forall (x : α), Eq.{u3} (β x) (coeFn.{u1, imax u2 u3} F (fun (_x : F) => forall (a : α), β a) (FunLike.hasCoeToFun.{u1, u2, u3} F α β i) f x) (coeFn.{u1, imax u2 u3} F (fun (_x : F) => forall (a : α), β a) (FunLike.hasCoeToFun.{u1, u2, u3} F α β i) g x))\nbut is expected to have type\n forall {F : Sort.{u3}} {α : Sort.{u1}} {β : α -> Sort.{u2}} [i : FunLike.{u3, u1, u2} F α β] {f : F} {g : F}, Iff (Eq.{u3} F f g) (forall (x : α), Eq.{u2} (β x) (FunLike.coe.{u3, u1, u2} F α (fun (_x : α) => β _x) i f x) (FunLike.coe.{u3, u1, u2} F α (fun (_x : α) => β _x) i g x))\nCase conversion may be inaccurate. Consider using '#align fun_like.ext_iff FunLike.ext_iffₓ'. -/\ntheorem ext_iff {f g : F} : f = g ↔ ∀ x, f x = g x :=\n coe_fn_eq.symm.trans Function.funext_iff\n#align fun_like.ext_iff FunLike.ext_iff\n\n/- warning: fun_like.congr_fun -> FunLike.congr_fun is a dubious translation:\nlean 3 declaration is\n forall {F : Sort.{u1}} {α : Sort.{u2}} {β : α -> Sort.{u3}} [i : FunLike.{u1, u2, u3} F α β] {f : F} {g : F}, (Eq.{u1} F f g) -> (forall (x : α), Eq.{u3} (β x) (coeFn.{u1, imax u2 u3} F (fun (_x : F) => forall (a : α), β a) (FunLike.hasCoeToFun.{u1, u2, u3} F α β i) f x) (coeFn.{u1, imax u2 u3} F (fun (_x : F) => forall (a : α), β a) (FunLike.hasCoeToFun.{u1, u2, u3} F α β i) g x))\nbut is expected to have type\n forall {F : Sort.{u3}} {α : Sort.{u1}} {β : α -> Sort.{u2}} [i : FunLike.{u3, u1, u2} F α β] {f : F} {g : F}, (Eq.{u3} F f g) -> (forall (x : α), Eq.{u2} (β x) (FunLike.coe.{u3, u1, u2} F α (fun (_x : α) => β _x) i f x) (FunLike.coe.{u3, u1, u2} F α (fun (_x : α) => β _x) i g x))\nCase conversion may be inaccurate. Consider using '#align fun_like.congr_fun FunLike.congr_funₓ'. -/\nprotected theorem congr_fun {f g : F} (h₁ : f = g) (x : α) : f x = g x :=\n congr_fun (congr_arg _ h₁) x\n#align fun_like.congr_fun FunLike.congr_fun\n\n/- warning: fun_like.ne_iff -> FunLike.ne_iff is a dubious translation:\nlean 3 declaration is\n forall {F : Sort.{u1}} {α : Sort.{u2}} {β : α -> Sort.{u3}} [i : FunLike.{u1, u2, u3} F α β] {f : F} {g : F}, Iff (Ne.{u1} F f g) (Exists.{u2} α (fun (a : α) => Ne.{u3} (β a) (coeFn.{u1, imax u2 u3} F (fun (_x : F) => forall (a : α), β a) (FunLike.hasCoeToFun.{u1, u2, u3} F α β i) f a) (coeFn.{u1, imax u2 u3} F (fun (_x : F) => forall (a : α), β a) (FunLike.hasCoeToFun.{u1, u2, u3} F α β i) g a)))\nbut is expected to have type\n forall {F : Sort.{u3}} {α : Sort.{u2}} {β : α -> Sort.{u1}} [i : FunLike.{u3, u2, u1} F α β] {f : F} {g : F}, Iff (Ne.{u3} F f g) (Exists.{u2} α (fun (a : α) => Ne.{u1} (β a) (FunLike.coe.{u3, u2, u1} F α (fun (_x : α) => β _x) i f a) (FunLike.coe.{u3, u2, u1} F α (fun (_x : α) => β _x) i g a)))\nCase conversion may be inaccurate. Consider using '#align fun_like.ne_iff FunLike.ne_iffₓ'. -/\ntheorem ne_iff {f g : F} : f ≠ g ↔ ∃ a, f a ≠ g a :=\n ext_iff.Not.trans not_forall\n#align fun_like.ne_iff FunLike.ne_iff\n\n/- warning: fun_like.exists_ne -> FunLike.exists_ne is a dubious translation:\nlean 3 declaration is\n forall {F : Sort.{u1}} {α : Sort.{u2}} {β : α -> Sort.{u3}} [i : FunLike.{u1, u2, u3} F α β] {f : F} {g : F}, (Ne.{u1} F f g) -> (Exists.{u2} α (fun (x : α) => Ne.{u3} (β x) (coeFn.{u1, imax u2 u3} F (fun (_x : F) => forall (a : α), β a) (FunLike.hasCoeToFun.{u1, u2, u3} F α β i) f x) (coeFn.{u1, imax u2 u3} F (fun (_x : F) => forall (a : α), β a) (FunLike.hasCoeToFun.{u1, u2, u3} F α β i) g x)))\nbut is expected to have type\n forall {F : Sort.{u3}} {α : Sort.{u2}} {β : α -> Sort.{u1}} [i : FunLike.{u3, u2, u1} F α β] {f : F} {g : F}, (Ne.{u3} F f g) -> (Exists.{u2} α (fun (x : α) => Ne.{u1} (β x) (FunLike.coe.{u3, u2, u1} F α (fun (_x : α) => β _x) i f x) (FunLike.coe.{u3, u2, u1} F α (fun (_x : α) => β _x) i g x)))\nCase conversion may be inaccurate. Consider using '#align fun_like.exists_ne FunLike.exists_neₓ'. -/\ntheorem exists_ne {f g : F} (h : f ≠ g) : ∃ x, f x ≠ g x :=\n ne_iff.mp h\n#align fun_like.exists_ne FunLike.exists_ne\n\n/- warning: fun_like.subsingleton_cod -> FunLike.subsingleton_cod is a dubious translation:\nlean 3 declaration is\n forall {F : Sort.{u1}} {α : Sort.{u2}} {β : α -> Sort.{u3}} [i : FunLike.{u1, u2, u3} F α β] [_inst_1 : forall (a : α), Subsingleton.{u3} (β a)], Subsingleton.{u1} F\nbut is expected to have type\n forall {F : Sort.{u1}} {α : Sort.{u3}} {β : α -> Sort.{u2}} [i : FunLike.{u1, u3, u2} F α β] [_inst_1 : forall (a : α), Subsingleton.{u2} (β a)], Subsingleton.{u1} F\nCase conversion may be inaccurate. Consider using '#align fun_like.subsingleton_cod FunLike.subsingleton_codₓ'. -/\n/-- This is not an instance to avoid slowing down every single `subsingleton` typeclass search.-/\ntheorem subsingleton_cod [∀ a, Subsingleton (β a)] : Subsingleton F :=\n ⟨fun f g => coe_injective <| Subsingleton.elim _ _⟩\n#align fun_like.subsingleton_cod FunLike.subsingleton_cod\n\nend FunLike\n\nend Dependent\n\nsection NonDependent\n\n/-! ### `fun_like F α (λ _, β)` where `β` does not depend on `a : α` -/\n\n\nvariable {F α β : Sort _} [i : FunLike F α fun _ => β]\n\ninclude i\n\nnamespace FunLike\n\n/- warning: fun_like.congr -> FunLike.congr is a dubious translation:\nlean 3 declaration is\n forall {F : Sort.{u1}} {α : Sort.{u2}} {β : Sort.{u3}} [i : FunLike.{u1, u2, u3} F α (fun (_x : α) => β)] {f : F} {g : F} {x : α} {y : α}, (Eq.{u1} F f g) -> (Eq.{u2} α x y) -> (Eq.{u3} β (coeFn.{u1, imax u2 u3} F (fun (_x : F) => α -> β) (FunLike.hasCoeToFun.{u1, u2, u3} F α (fun (_x : α) => β) i) f x) (coeFn.{u1, imax u2 u3} F (fun (_x : F) => α -> β) (FunLike.hasCoeToFun.{u1, u2, u3} F α (fun (_x : α) => β) i) g y))\nbut is expected to have type\n forall {F : Sort.{u3}} {α : Sort.{u2}} {β : Sort.{u1}} [i : FunLike.{u3, u2, u1} F α (fun (_x : α) => β)] {f : F} {g : F} {x : α} {y : α}, (Eq.{u3} F f g) -> (Eq.{u2} α x y) -> (Eq.{u1} ((fun (x._@.Mathlib.Data.FunLike.Basic._hyg.614 : α) => β) x) (FunLike.coe.{u3, u2, u1} F α (fun (_x : α) => (fun (x._@.Mathlib.Data.FunLike.Basic._hyg.614 : α) => β) _x) i f x) (FunLike.coe.{u3, u2, u1} F α (fun (_x : α) => (fun (x._@.Mathlib.Data.FunLike.Basic._hyg.614 : α) => β) _x) i g y))\nCase conversion may be inaccurate. Consider using '#align fun_like.congr FunLike.congrₓ'. -/\nprotected theorem congr {f g : F} {x y : α} (h₁ : f = g) (h₂ : x = y) : f x = g y :=\n congr (congr_arg _ h₁) h₂\n#align fun_like.congr FunLike.congr\n\n/- warning: fun_like.congr_arg -> FunLike.congr_arg is a dubious translation:\nlean 3 declaration is\n forall {F : Sort.{u1}} {α : Sort.{u2}} {β : Sort.{u3}} [i : FunLike.{u1, u2, u3} F α (fun (_x : α) => β)] (f : F) {x : α} {y : α}, (Eq.{u2} α x y) -> (Eq.{u3} β (coeFn.{u1, imax u2 u3} F (fun (_x : F) => α -> β) (FunLike.hasCoeToFun.{u1, u2, u3} F α (fun (_x : α) => β) i) f x) (coeFn.{u1, imax u2 u3} F (fun (_x : F) => α -> β) (FunLike.hasCoeToFun.{u1, u2, u3} F α (fun (_x : α) => β) i) f y))\nbut is expected to have type\n forall {F : Sort.{u1}} {α : Sort.{u3}} {β : Sort.{u2}} [i : FunLike.{u1, u3, u2} F α (fun (_x : α) => β)] (f : F) {x : α} {y : α}, (Eq.{u3} α x y) -> (Eq.{u2} ((fun (x._@.Mathlib.Data.FunLike.Basic._hyg.657 : α) => β) x) (FunLike.coe.{u1, u3, u2} F α (fun (_x : α) => (fun (x._@.Mathlib.Data.FunLike.Basic._hyg.657 : α) => β) _x) i f x) (FunLike.coe.{u1, u3, u2} F α (fun (_x : α) => (fun (x._@.Mathlib.Data.FunLike.Basic._hyg.657 : α) => β) _x) i f y))\nCase conversion may be inaccurate. Consider using '#align fun_like.congr_arg FunLike.congr_argₓ'. -/\nprotected theorem congr_arg (f : F) {x y : α} (h₂ : x = y) : f x = f y :=\n congr_arg _ h₂\n#align fun_like.congr_arg FunLike.congr_arg\n\nend FunLike\n\nend NonDependent\n\n", "meta": {"author": "leanprover-community", "repo": "mathlib3port", "sha": "62505aa236c58c8559783b16d33e30df3daa54f4", "save_path": "github-repos/lean/leanprover-community-mathlib3port", "path": "github-repos/lean/leanprover-community-mathlib3port/mathlib3port-62505aa236c58c8559783b16d33e30df3daa54f4/Mathbin/Data/FunLike/Basic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45713671682749474, "lm_q2_score": 0.08035746882220708, "lm_q1q2_score": 0.036734349469951515}} {"text": "/-\nCopyright (c) 2018 Simon Hudon. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Simon Hudon, Scott Morrison\n\n! This file was ported from Lean 3 source module tactic.solve_by_elim\n! leanprover-community/mathlib commit f694c7dead66f5d4c80f446c796a5aad14707f0e\n! Please do not edit these lines, except to modify the commit id\n! if you have ported upstream changes.\n-/\nimport Mathbin.Tactic.Core\n\n/-!\n# solve_by_elim\n\nA depth-first search backwards reasoner.\n\n`solve_by_elim` takes a list of lemmas, and repeating tries to `apply` these against\nthe goals, recursively acting on any generated subgoals.\n\nIt accepts a variety of configuration options described below, enabling\n* backtracking across multiple goals,\n* pruning the search tree, and\n* invoking other tactics before or after trying to apply lemmas.\n\nAt present it has no \"premise selection\", and simply tries the supplied lemmas in order\nat each step of the search.\n-/\n\n\nnamespace Tactic\n\nnamespace SolveByElim\n\n/-- `mk_assumption_set` builds a collection of lemmas for use in\nthe backtracking search in `solve_by_elim`.\n\n* By default, it includes all local hypotheses, along with `rfl`, `trivial`, `congr_fun` and\n `congr_arg`.\n* The flag `no_dflt` removes these.\n* The argument `hs` is a list of `simp_arg_type`s,\n and can be used to add, or remove, lemmas or expressions from the set.\n* The argument `attr : list name` adds all lemmas tagged with one of a specified list of attributes.\n\n`mk_assumption_set` returns not a `list expr`, but a `list (tactic expr) × tactic (list expr)`.\nThere are two separate problems that need to be solved.\n\n### Relevant local hypotheses\n\n`solve_by_elim*` works with multiple goals,\nand we need to use separate sets of local hypotheses for each goal.\nThe second component of the returned value provides these local hypotheses.\n(Essentially using `local_context`, along with some filtering to remove hypotheses\nthat have been explicitly removed via `only` or `[-h]`.)\n\n### Stuck metavariables\n\nLemmas with implicit arguments would be filled in with metavariables if we created the\n`expr` objects immediately, so instead we return thunks that generate the expressions\non demand. This is the first component, with type `list (tactic expr)`.\n\nAs an example, we have `def rfl : ∀ {α : Sort u} {a : α}, a = a`, which on elaboration will become\n`@rfl ?m_1 ?m_2`.\n\nBecause `solve_by_elim` works by repeated application of lemmas against subgoals,\nthe first time such a lemma is successfully applied,\nthose metavariables will be unified, and thereafter have fixed values.\nThis would make it impossible to apply the lemma\na second time with different values of the metavariables.\n\nSee https://github.com/leanprover-community/mathlib/issues/2269\n\nAs an optimisation, after we build the list of `tactic expr`s, we actually run them, and replace any\nthat do not in fact produce metavariables with a simple `return` tactic.\n-/\nunsafe def mk_assumption_set (no_dflt : Bool) (hs : List simp_arg_type) (attr : List Name) :\n tactic (List (tactic expr) × tactic (List expr)) :=\n -- We lock the tactic state so that any spurious goals generated during\n -- elaboration of pre-expressions are discarded\n lock_tactic_state\n do\n let-- `hs` are expressions specified explicitly,\n -- `hex` are exceptions (specified via `solve_by_elim [-h]`) referring to local hypotheses,\n -- `gex` are the other exceptions\n (hs, gex, hex, all_hyps)\n ← decode_simp_arg_list hs\n let-- Recall, per the discussion above, we produce `tactic expr` thunks rather than actual `expr`s.\n -- Note that while we evaluate these thunks on two occasions below while preparing the list,\n -- this is a one-time cost during `mk_assumption_set`, rather than a cost proportional to the\n -- length of the search `solve_by_elim` executes.\n hs := hs.map fun h => i_to_expr_for_apply h\n let l ← attr.mapM fun a => attribute.get_instances a\n let l := l.join\n let m := l.map fun h => mk_const h\n let hs ←\n (-- In order to remove the expressions we need to evaluate the thunks.\n hs ++\n m).filterM\n fun h => do\n let h ← h\n return <| expr.const_name h ∉ gex\n let hs :=\n if no_dflt then hs\n else ([`rfl, `trivial, `congr_fun, `congr_arg].map fun n => mk_const n) ++ hs\n let locals : tactic (List expr) :=\n if ¬no_dflt ∨ all_hyps then do\n let ctx ← local_context\n -- Remove local exceptions specified in `hex`:\n return <|\n ctx fun h : expr => h ∉ hex\n else return []\n let hs\n ←-- Finally, run all of the tactics: any that return an expression without metavariables can safely\n -- be replaced by a `return` tactic.\n hs.mapM\n fun h : tactic expr => do\n let e ← h\n if e then return h else return (return e)\n return (hs, locals)\n#align tactic.solve_by_elim.mk_assumption_set tactic.solve_by_elim.mk_assumption_set\n\n/-- Configuration options for `solve_by_elim`.\n\n* `accept : list expr → tactic unit` determines whether the current branch should be explored.\n At each step, before the lemmas are applied,\n `accept` is passed the proof terms for the original goals,\n as reported by `get_goals` when `solve_by_elim` started.\n These proof terms may be metavariables (if no progress has been made on that goal)\n or may contain metavariables at some leaf nodes\n (if the goal has been partially solved by previous `apply` steps).\n If the `accept` tactic fails `solve_by_elim` aborts searching this branch and backtracks.\n By default `accept := λ _, skip` always succeeds.\n (There is an example usage in `tests/solve_by_elim.lean`.)\n* `pre_apply : tactic unit` specifies an additional tactic to run before each round of `apply`.\n* `discharger : tactic unit` specifies an additional tactic to apply on subgoals\n for which no lemma applies.\n If that tactic succeeds, `solve_by_elim` will continue applying lemmas on resulting goals.\n-/\nunsafe structure basic_opt extends apply_any_opt where\n accept : List expr → tactic Unit := fun _ => skip\n pre_apply : tactic Unit := skip\n discharger : tactic Unit := failed\n max_depth : ℕ := 3\n#align tactic.solve_by_elim.basic_opt tactic.solve_by_elim.basic_opt\n\ninitialize\n registerTraceClass.1 `solve_by_elim\n\n-- trace attempted lemmas\n/-- A helper function for trace messages, prepending '....' depending on the current search depth.\n-/\nunsafe def solve_by_elim_trace (n : ℕ) (f : format) : tactic Unit :=\n trace_if_enabled `solve_by_elim\n ((f!\"[solve_by_elim {(List.replicate (n + 1) '.').asString} \") ++ f ++ \"]\")\n#align tactic.solve_by_elim.solve_by_elim_trace tactic.solve_by_elim.solve_by_elim_trace\n\n/-- A helper function to generate trace messages on successful applications. -/\nunsafe def on_success (g : format) (n : ℕ) (e : expr) : tactic Unit := do\n let pp ← pp e\n solve_by_elim_trace n f! \"✅ `{pp }` solves `⊢ {g}`\"\n#align tactic.solve_by_elim.on_success tactic.solve_by_elim.on_success\n\n/-- A helper function to generate trace messages on unsuccessful applications. -/\nunsafe def on_failure (g : format) (n : ℕ) : tactic Unit :=\n solve_by_elim_trace n f! \"❌ failed to solve `⊢ {g}`\"\n#align tactic.solve_by_elim.on_failure tactic.solve_by_elim.on_failure\n\n/-- A helper function to generate the tactic that print trace messages.\nThis function exists to ensure the target is pretty printed only as necessary.\n-/\nunsafe def trace_hooks (n : ℕ) : tactic ((expr → tactic Unit) × tactic Unit) :=\n if is_trace_enabled_for `solve_by_elim then do\n let g ← target >>= pp\n return (on_success g n, on_failure g n)\n else return (fun _ => skip, skip)\n#align tactic.solve_by_elim.trace_hooks tactic.solve_by_elim.trace_hooks\n\n/-- The internal implementation of `solve_by_elim`, with a limiting counter.\n-/\nunsafe def solve_by_elim_aux (opt : basic_opt) (original_goals : List expr)\n (lemmas : List (tactic expr)) (ctx : tactic (List expr)) : ℕ → tactic Unit\n | n => do\n -- First, check that progress so far is `accept`able.\n lock_tactic_state\n (original_goals instantiate_mvars >>= opt)\n -- Then check if we've finished.\n done >>\n solve_by_elim_trace (opt - n) \"success!\" <|>\n do\n -- Otherwise, if there's more time left,\n guard\n (n > 0) <|>\n solve_by_elim_trace opt \"🛑 aborting, hit depth limit\" >> failed\n -- run the `pre_apply` tactic, then\n opt\n let-- try either applying a lemma and recursing,\n (on_success, on_failure)\n ← trace_hooks (opt - n)\n let ctx_lemmas ← ctx\n apply_any_thunk (lemmas ++ ctx_lemmas return) opt (solve_by_elim_aux (n - 1)) on_success\n on_failure <|>-- or if that doesn't work, run the discharger and recurse.\n opt >>\n solve_by_elim_aux (n - 1)\n#align tactic.solve_by_elim.solve_by_elim_aux tactic.solve_by_elim.solve_by_elim_aux\n\n/-- Arguments for `solve_by_elim`:\n* By default `solve_by_elim` operates only on the first goal,\n but with `backtrack_all_goals := true`, it operates on all goals at once,\n backtracking across goals as needed,\n and only succeeds if it discharges all goals.\n* `lemmas` specifies the list of lemmas to use in the backtracking search.\n If `none`, `solve_by_elim` uses the local hypotheses,\n along with `rfl`, `trivial`, `congr_arg`, and `congr_fun`.\n* `lemma_thunks` provides the lemmas as a list of `tactic expr`,\n which are used to regenerate the `expr` objects to avoid binding metavariables.\n It should not usually be specified by the user.\n (If both `lemmas` and `lemma_thunks` are specified, only `lemma_thunks` is used.)\n* `ctx_thunk` is for internal use only: it returns the local hypotheses which will be used.\n* `max_depth` bounds the depth of the search.\n-/\nunsafe structure opt extends basic_opt where\n backtrack_all_goals : Bool := false\n lemmas : Option (List expr) := none\n lemma_thunks : Option (List (tactic expr)) := lemmas.map fun l => l.map return\n ctx_thunk : tactic (List expr) := local_context\n#align tactic.solve_by_elim.opt tactic.solve_by_elim.opt\n\n/-- If no lemmas have been specified, generate the default set\n(local hypotheses, along with `rfl`, `trivial`, `congr_arg`, and `congr_fun`).\n-/\nunsafe def opt.get_lemma_thunks (opt : opt) : tactic (List (tactic expr) × tactic (List expr)) :=\n match opt.lemma_thunks with\n | none => mk_assumption_set false [] []\n | some lemma_thunks => return (lemma_thunks, opt.ctx_thunk)\n#align tactic.solve_by_elim.opt.get_lemma_thunks tactic.solve_by_elim.opt.get_lemma_thunks\n\nend SolveByElim\n\nopen SolveByElim\n\n/-- `solve_by_elim` repeatedly tries `apply`ing a lemma\nfrom the list of assumptions (passed via the `opt` argument),\nrecursively operating on any generated subgoals, backtracking as necessary.\n\n`solve_by_elim` succeeds only if it discharges the goal.\n(By default, `solve_by_elim` focuses on the first goal, and only attempts to solve that.\nWith the option `backtrack_all_goals := tt`,\nit attempts to solve all goals, and only succeeds if it does so.\nWith `backtrack_all_goals := tt`, `solve_by_elim` will backtrack a solution it has found for\none goal if it then can't discharge other goals.)\n\nIf passed an empty list of assumptions, `solve_by_elim` builds a default set\nas per the interactive tactic, using the `local_context` along with\n`rfl`, `trivial`, `congr_arg`, and `congr_fun`.\n\nTo pass a particular list of assumptions, use the `lemmas` field\nin the configuration argument. This expects an\n`option (list expr)`. In certain situations it may be necessary to instead use the\n`lemma_thunks` field, which expects a `option (list (tactic expr))`.\nThis allows for regenerating metavariables\nfor each application, which might otherwise get stuck.\n\nSee also the simpler tactic `apply_rules`, which does not perform backtracking.\n-/\nunsafe def solve_by_elim (opt : opt := { }) : tactic Unit := do\n tactic.fail_if_no_goals\n let (lemmas, ctx_lemmas) ← opt.get_lemma_thunks\n (if opt then id else focus1) do\n let gs ← get_goals\n solve_by_elim_aux opt gs lemmas ctx_lemmas opt <|>\n fail\n (\"`solve_by_elim` failed.\\n\" ++ \"Try `solve_by_elim { max_depth := N }` for `N > \" ++\n toString opt ++\n \"`\\n\" ++\n \"or use `set_option trace.solve_by_elim true` to view the search.\")\n#align tactic.solve_by_elim tactic.solve_by_elim\n\n/- ./././Mathport/Syntax/Translate/Tactic/Mathlib/Core.lean:38:34: unsupported: setup_tactic_parser -/\nnamespace Interactive\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:207:4: warning: unsupported notation `parser.optional -/\n/-- `apply_assumption` looks for an assumption of the form `... → ∀ _, ... → head`\nwhere `head` matches the current goal.\n\nIf this fails, `apply_assumption` will call `symmetry` and try again.\n\nIf this also fails, `apply_assumption` will call `exfalso` and try again,\nso that if there is an assumption of the form `P → ¬ Q`, the new tactic state\nwill have two goals, `P` and `Q`.\n\nOptional arguments:\n- `lemmas`: a list of expressions to apply, instead of the local constants\n- `tac`: a tactic to run on each subgoal after applying an assumption; if\n this tactic fails, the corresponding assumption will be rejected and\n the next one will be attempted.\n-/\nunsafe def apply_assumption (lemmas : parse (parser.optional pexpr_list))\n (opt : apply_any_opt := { }) (tac : tactic Unit := skip) : tactic Unit := do\n let lemmas ←\n match lemmas with\n | none => local_context\n | some lemmas => lemmas.mapM to_expr\n tactic.apply_any lemmas opt tac\n#align tactic.interactive.apply_assumption tactic.interactive.apply_assumption\n\nadd_tactic_doc\n { Name := \"apply_assumption\"\n category := DocCategory.tactic\n declNames := [`tactic.interactive.apply_assumption]\n tags := [\"context management\", \"lemma application\"] }\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:207:4: warning: unsupported notation `parser.optional -/\n/-- `solve_by_elim` calls `apply` on the main goal to find an assumption whose head matches\nand then repeatedly calls `apply` on the generated subgoals until no subgoals remain,\nperforming at most `max_depth` recursive steps.\n\n`solve_by_elim` discharges the current goal or fails.\n\n`solve_by_elim` performs back-tracking if subgoals can not be solved.\n\nBy default, the assumptions passed to `apply` are the local context, `rfl`, `trivial`,\n`congr_fun` and `congr_arg`.\n\nThe assumptions can be modified with similar syntax as for `simp`:\n* `solve_by_elim [h₁, h₂, ..., hᵣ]` also applies the named lemmas.\n* `solve_by_elim with attr₁ ... attrᵣ` also applies all lemmas tagged with the specified attributes.\n* `solve_by_elim only [h₁, h₂, ..., hᵣ]` does not include the local context,\n `rfl`, `trivial`, `congr_fun`, or `congr_arg` unless they are explicitly included.\n* `solve_by_elim [-id_1, ... -id_n]` uses the default assumptions, removing the specified ones.\n\n`solve_by_elim*` tries to solve all goals together, using backtracking if a solution for one goal\nmakes other goals impossible.\n\noptional arguments passed via a configuration argument as `solve_by_elim { ... }`\n- max_depth: number of attempts at discharging generated sub-goals\n- discharger: a subsidiary tactic to try at each step when no lemmas apply\n (e.g. `cc` may be helpful).\n- pre_apply: a subsidiary tactic to run at each step before applying lemmas (e.g. `intros`).\n- accept: a subsidiary tactic `list expr → tactic unit` that at each step,\n before any lemmas are applied, is passed the original proof terms\n as reported by `get_goals` when `solve_by_elim` started\n (but which may by now have been partially solved by previous `apply` steps).\n If the `accept` tactic fails,\n `solve_by_elim` will abort searching the current branch and backtrack.\n This may be used to filter results, either at every step of the search,\n or filtering complete results\n (by testing for the absence of metavariables, and then the filtering condition).\n-/\nunsafe def solve_by_elim (all_goals : parse <| parser.optional (tk \"*\")) (no_dflt : parse only_flag)\n (hs : parse simp_arg_list) (attr_names : parse with_ident_list)\n (opt : solve_by_elim.opt := { }) : tactic Unit := do\n let (lemma_thunks, ctx_thunk) ← mk_assumption_set no_dflt hs attr_names\n tactic.solve_by_elim\n { opt with\n backtrack_all_goals := all_goals ∨ opt\n lemma_thunks := some lemma_thunks\n ctx_thunk }\n#align tactic.interactive.solve_by_elim tactic.interactive.solve_by_elim\n\nadd_tactic_doc\n { Name := \"solve_by_elim\"\n category := DocCategory.tactic\n declNames := [`tactic.interactive.solve_by_elim]\n tags := [\"search\"] }\n\nend Interactive\n\nend Tactic\n\n", "meta": {"author": "leanprover-community", "repo": "mathlib3port", "sha": "62505aa236c58c8559783b16d33e30df3daa54f4", "save_path": "github-repos/lean/leanprover-community-mathlib3port", "path": "github-repos/lean/leanprover-community-mathlib3port/mathlib3port-62505aa236c58c8559783b16d33e30df3daa54f4/Mathbin/Tactic/SolveByElim.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48047867804790706, "lm_q2_score": 0.07585818419975078, "lm_q1q2_score": 0.03644824006341089}} {"text": "/-\nCopyright (c) 2018 Scott Morrison. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Scott Morrison, Johannes Hölzl, Reid Barton, Sean Leather\n-/\nimport tactic.lint\n\n/-!\n# Bundled types\n\n> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.\n> Any changes to this file require a corresponding PR to mathlib4.\n\n`bundled c` provides a uniform structure for bundling a type equipped with a type class.\n\nWe provide `category` instances for these in `category_theory/unbundled_hom.lean`\n(for categories with unbundled homs, e.g. topological spaces)\nand in `category_theory/bundled_hom.lean` (for categories with bundled homs, e.g. monoids).\n-/\n\nuniverses u v\n\nnamespace category_theory\nvariables {c d : Type u → Type v} {α : Type u}\n\n/-- `bundled` is a type bundled with a type class instance for that type. Only\nthe type class is exposed as a parameter. -/\n@[nolint has_nonempty_instance]\nstructure bundled (c : Type u → Type v) : Type (max (u+1) v) :=\n(α : Type u)\n(str : c α . tactic.apply_instance)\n\nnamespace bundled\n\n/-- A generic function for lifting a type equipped with an instance to a bundled object. -/\n-- Usually explicit instances will provide their own version of this, e.g. `Mon.of` and `Top.of`.\ndef of {c : Type u → Type v} (α : Type u) [str : c α] : bundled c := ⟨α, str⟩\n\ninstance : has_coe_to_sort (bundled c) (Type u) := ⟨bundled.α⟩\n\n@[simp] lemma coe_mk (α) (str) : (@bundled.mk c α str : Type u) = α := rfl\n\n/-\n`bundled.map` is reducible so that, if we define a category\n\n def Ring : Type (u+1) := induced_category SemiRing (bundled.map @ring.to_semiring)\n\ninstance search is able to \"see\" that a morphism R ⟶ S in Ring is really\na (semi)ring homomorphism from R.α to S.α, and not merely from\n`(bundled.map @ring.to_semiring R).α` to `(bundled.map @ring.to_semiring S).α`.\n-/\n/-- Map over the bundled structure -/\n@[reducible] def map (f : Π {α}, c α → d α) (b : bundled c) : bundled d :=\n⟨b, f b.str⟩\n\nend bundled\n\nend category_theory\n", "meta": {"author": "leanprover-community", "repo": "mathlib", "sha": "5e526d18cea33550268dcbbddcb822d5cde40654", "save_path": "github-repos/lean/leanprover-community-mathlib", "path": "github-repos/lean/leanprover-community-mathlib/mathlib-5e526d18cea33550268dcbbddcb822d5cde40654/src/category_theory/concrete_category/bundled.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4726834914771175, "lm_q2_score": 0.0769608415180331, "lm_q1q2_score": 0.03637811927576099}} {"text": "/-\nCopyright (c) 2021 Anne Baanen. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Anne Baanen\n\n! This file was ported from Lean 3 source module data.fun_like.equiv\n! leanprover-community/mathlib commit f340f229b1f461aa1c8ee11e0a172d0a3b301a4a\n! Please do not edit these lines, except to modify the commit id\n! if you have ported upstream changes.\n-/\nimport Mathlib.Data.FunLike.Embedding\n\n/-!\n# Typeclass for a type `F` with an injective map to `A ≃ B`\n\nThis typeclass is primarily for use by isomorphisms like `MonoidEquiv` and `LinearEquiv`.\n\n## Basic usage of `EquivLike`\n\nA typical type of morphisms should be declared as:\n```\nstructure MyIso (A B : Type _) [MyClass A] [MyClass B]\n extends Equiv A B :=\n(map_op' : ∀ {x y : A}, toFun (MyClass.op x y) = MyClass.op (toFun x) (toFun y))\n\nnamespace MyIso\n\nvariables (A B : Type _) [MyClass A] [MyClass B]\n\n-- This instance is optional if you follow the \"Isomorphism class\" design below:\ninstance : EquivLike (MyIso A B) A (λ _, B) :=\n{ coe := MyIso.toEquiv.toFun,\n inv := MyIso.toEquiv.invFun,\n left_inv := MyIso.toEquiv.left_inv,\n right_inv := MyIso.toEquiv.right_inv,\n coe_injective' := λ f g h, by cases f; cases g; congr' }\n\n/-- Helper instance for when there's too many metavariables to apply `EquivLike.coe` directly. -/\ninstance : CoeFun (MyIso A B) := FunLike.instCoeFunForAll\n\n@[ext] theorem ext {f g : MyIso A B} (h : ∀ x, f x = g x) : f = g := FunLike.ext f g h\n\n/-- Copy of a `MyIso` with a new `toFun` equal to the old one. Useful to fix definitional\nequalities. -/\nprotected def copy (f : MyIso A B) (f' : A → B) (f_inv : B → A) (h : f' = ⇑f) : MyIso A B :=\n{ toFun := f',\n invFun := f_inv,\n left_inv := h.symm ▸ f.left_inv,\n right_inv := h.symm ▸ f.right_inv,\n map_op' := h.symm ▸ f.map_op' }\n\nend MyIso\n```\n\nThis file will then provide a `CoeFun` instance and various\nextensionality and simp lemmas.\n\n## Isomorphism classes extending `EquivLike`\n\nThe `EquivLike` design provides further benefits if you put in a bit more work.\nThe first step is to extend `EquivLike` to create a class of those types satisfying\nthe axioms of your new type of isomorphisms.\nContinuing the example above:\n\n```\n\n/-- `MyIsoClass F A B` states that `F` is a type of `MyClass.op`-preserving morphisms.\nYou should extend this class when you extend `MyIso`. -/\nclass MyIsoClass (F : Type _) (A B : outParam <| Type _) [MyClass A] [MyClass B]\n extends EquivLike F A (λ _, B), MyHomClass F A B\n\nend\n\n-- You can replace `MyIso.EquivLike` with the below instance:\ninstance : MyIsoClass (MyIso A B) A B :=\n{ coe := MyIso.toFun,\n inv := MyIso.invFun,\n left_inv := MyIso.left_inv,\n right_inv := MyIso.right_inv,\n coe_injective' := λ f g h, by cases f; cases g; congr',\n map_op := MyIso.map_op' }\n\n-- [Insert `CoeFun`, `ext` and `copy` here]\n```\n\nThe second step is to add instances of your new `MyIsoClass` for all types extending `MyIso`.\nTypically, you can just declare a new class analogous to `MyIsoClass`:\n\n```\nstructure CoolerIso (A B : Type _) [CoolClass A] [CoolClass B]\n extends MyIso A B :=\n(map_cool' : toFun CoolClass.cool = CoolClass.cool)\n\nsection\nset_option old_structure_cmd true\n\nclass CoolerIsoClass (F : Type _) (A B : outParam <| Type _) [CoolClass A] [CoolClass B]\n extends MyIsoClass F A B :=\n(map_cool : ∀ (f : F), f CoolClass.cool = CoolClass.cool)\n\nend\n\n@[simp] lemma map_cool {F A B : Type _} [CoolClass A] [CoolClass B] [CoolerIsoClass F A B]\n (f : F) : f CoolClass.cool = CoolClass.cool :=\nCoolerIsoClass.map_cool\n\ninstance : CoolerIsoClass (CoolerIso A B) A B :=\n{ coe := CoolerIso.toFun,\n coe_injective' := λ f g h, by cases f; cases g; congr',\n map_op := CoolerIso.map_op',\n map_cool := CoolerIso.map_cool' }\n\n-- [Insert `CoeFun`, `ext` and `copy` here]\n```\n\nThen any declaration taking a specific type of morphisms as parameter can instead take the\nclass you just defined:\n```\n-- Compare with: lemma do_something (f : MyIso A B) : sorry := sorry\nlemma do_something {F : Type _} [MyIsoClass F A B] (f : F) : sorry := sorry\n```\n\nThis means anything set up for `MyIso`s will automatically work for `CoolerIsoClass`es,\nand defining `CoolerIsoClass` only takes a constant amount of effort,\ninstead of linearly increasing the work per `MyIso`-related declaration.\n\n-/\n\n\n/-- The class `EquivLike E α β` expresses that terms of type `E` have an\ninjective coercion to bijections between `α` and `β`.\n\nThis typeclass is used in the definition of the homomorphism typeclasses,\nsuch as `ZeroEquivClass`, `MulEquivClass`, `MonoidEquivClass`, ....\n-/\nclass EquivLike (E : Sort _) (α β : outParam (Sort _)) where\n /-- The coercion to a function in the forward direction. -/\n coe : E → α → β\n /-- The coercion to a function in the backwards direction. -/\n inv : E → β → α\n /-- The coercions are left inverses. -/\n left_inv : ∀ e, Function.LeftInverse (inv e) (coe e)\n /-- The coercions are right inverses. -/\n right_inv : ∀ e, Function.RightInverse (inv e) (coe e)\n /-- If two coercions to functions are jointly injective. -/\n coe_injective' : ∀ e g, coe e = coe g → inv e = inv g → e = g\n -- This is mathematically equivalent to either of the coercions to functions being injective, but\n -- the `inv` hypothesis makes this easier to prove with `congr'`\n#align equiv_like EquivLike\n\nnamespace EquivLike\n\nvariable {E F α β γ : Sort _} [iE : EquivLike E α β] [iF : EquivLike F β γ]\n\ntheorem inv_injective : Function.Injective (EquivLike.inv : E → β → α) := fun e g h ↦\n coe_injective' e g ((right_inv e).eq_rightInverse (h.symm ▸ left_inv g)) h\n#align equiv_like.inv_injective EquivLike.inv_injective\n\ninstance (priority := 100) toEmbeddingLike : EmbeddingLike E α β where\n coe := (coe : E → α → β)\n coe_injective' e g h :=\n coe_injective' e g h ((left_inv e).eq_rightInverse (h.symm ▸ right_inv g))\n injective' e := (left_inv e).injective\n\nprotected theorem injective (e : E) : Function.Injective e :=\n EmbeddingLike.injective e\n#align equiv_like.injective EquivLike.injective\n\nprotected theorem surjective (e : E) : Function.Surjective e :=\n (right_inv e).surjective\n#align equiv_like.surjective EquivLike.surjective\n\nprotected theorem bijective (e : E) : Function.Bijective (e : α → β) :=\n ⟨EquivLike.injective e, EquivLike.surjective e⟩\n#align equiv_like.bijective EquivLike.bijective\n\n\n\n@[simp]\ntheorem injective_comp (e : E) (f : β → γ) : Function.Injective (f ∘ e) ↔ Function.Injective f :=\n Function.Injective.of_comp_iff' f (EquivLike.bijective e)\n#align equiv_like.injective_comp EquivLike.injective_comp\n\n@[simp]\ntheorem surjective_comp (e : E) (f : β → γ) : Function.Surjective (f ∘ e) ↔ Function.Surjective f :=\n (EquivLike.surjective e).of_comp_iff f\n#align equiv_like.surjective_comp EquivLike.surjective_comp\n\n@[simp]\ntheorem bijective_comp (e : E) (f : β → γ) : Function.Bijective (f ∘ e) ↔ Function.Bijective f :=\n (EquivLike.bijective e).of_comp_iff f\n#align equiv_like.bijective_comp EquivLike.bijective_comp\n\n/-- This lemma is only supposed to be used in the generic context, when working with instances\nof classes extending `EquivLike`.\nFor concrete isomorphism types such as `Equiv`, you should use `Equiv.symm_apply_apply`\nor its equivalent.\n\nTODO: define a generic form of `Equiv.symm`. -/\n@[simp]\ntheorem inv_apply_apply (e : E) (a : α) : EquivLike.inv e (e a) = a :=\n left_inv _ _\n#align equiv_like.inv_apply_apply EquivLike.inv_apply_apply\n\n/-- This lemma is only supposed to be used in the generic context, when working with instances\nof classes extending `EquivLike`.\nFor concrete isomorphism types such as `Equiv`, you should use `Equiv.apply_symm_apply`\nor its equivalent.\n\nTODO: define a generic form of `Equiv.symm`. -/\n@[simp]\ntheorem apply_inv_apply (e : E) (b : β) : e (EquivLike.inv e b) = b :=\n right_inv _ _\n#align equiv_like.apply_inv_apply EquivLike.apply_inv_apply\n\ntheorem comp_injective (f : α → β) (e : F) : Function.Injective (e ∘ f) ↔ Function.Injective f :=\n EmbeddingLike.comp_injective f e\n#align equiv_like.comp_injective EquivLike.comp_injective\n\n@[simp]\ntheorem comp_surjective (f : α → β) (e : F) : Function.Surjective (e ∘ f) ↔ Function.Surjective f :=\n Function.Surjective.of_comp_iff' (EquivLike.bijective e) f\n#align equiv_like.comp_surjective EquivLike.comp_surjective\n\n@[simp]\ntheorem comp_bijective (f : α → β) (e : F) : Function.Bijective (e ∘ f) ↔ Function.Bijective f :=\n (EquivLike.bijective e).of_comp_iff' f\n#align equiv_like.comp_bijective EquivLike.comp_bijective\n\n/-- This is not an instance to avoid slowing down every single `Subsingleton` typeclass search.-/\nlemma subsingleton_dom [Subsingleton β] : Subsingleton F :=\n⟨fun f g ↦ FunLike.ext f g $ fun _ ↦ (right_inv f).injective $ Subsingleton.elim _ _⟩\n#align equiv_like.subsingleton_dom EquivLike.subsingleton_dom\n\nend EquivLike\n", "meta": {"author": "leanprover-community", "repo": "mathlib4", "sha": "b9a0a30342ca06e9817e22dbe46e75fc7f435500", "save_path": "github-repos/lean/leanprover-community-mathlib4", "path": "github-repos/lean/leanprover-community-mathlib4/mathlib4-b9a0a30342ca06e9817e22dbe46e75fc7f435500/Mathlib/Data/FunLike/Equiv.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4649015713733885, "lm_q2_score": 0.07807815978187677, "lm_q1q2_score": 0.03629865917253701}} {"text": "/-\nCopyright (c) 2019 Simon Hudon. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Simon Hudon\n\nMonad encapsulating continuation passing programming style, similar to\nHaskell's `Cont`, `ContT` and `MonadCont`:\n\n\n! This file was ported from Lean 3 source module control.monad.cont\n! leanprover-community/mathlib commit d6814c584384ddf2825ff038e868451a7c956f31\n! Please do not edit these lines, except to modify the commit id\n! if you have ported upstream changes.\n-/\nimport Mathbin.Control.Monad.Basic\nimport Mathbin.Control.Monad.Writer\n\nuniverse u v w u₀ u₁ v₀ v₁\n\nstructure MonadCont.Label (α : Type w) (m : Type u → Type v) (β : Type u) where\n apply : α → m β\n#align monad_cont.label MonadCont.Label\n\ndef MonadCont.goto {α β} {m : Type u → Type v} (f : MonadCont.Label α m β) (x : α) :=\n f.apply x\n#align monad_cont.goto MonadCont.goto\n\nclass MonadCont (m : Type u → Type v) where\n callCc : ∀ {α β}, (MonadCont.Label α m β → m α) → m α\n#align monad_cont MonadCont\n\nopen MonadCont\n\nclass IsLawfulMonadCont (m : Type u → Type v) [Monad m] [MonadCont m] extends LawfulMonad m where\n callCc_bind_right {α ω γ} (cmd : m α) (next : Label ω m γ → α → m ω) :\n (callCc fun f => cmd >>= next f) = cmd >>= fun x => callCc fun f => next f x\n callCc_bind_left {α} (β) (x : α) (dead : Label α m β → β → m α) :\n (callCc fun f : Label α m β => goto f x >>= dead f) = pure x\n callCc_dummy {α β} (dummy : m α) : (callCc fun f : Label α m β => dummy) = dummy\n#align is_lawful_monad_cont IsLawfulMonadCont\n\nexport IsLawfulMonadCont ()\n\ndef ContT (r : Type u) (m : Type u → Type v) (α : Type w) :=\n (α → m r) → m r\n#align cont_t ContT\n\n@[reducible]\ndef Cont (r : Type u) (α : Type w) :=\n ContT r id α\n#align cont Cont\n\nnamespace ContT\n\nexport MonadCont (Label goto)\n\nvariable {r : Type u} {m : Type u → Type v} {α β γ ω : Type w}\n\ndef run : ContT r m α → (α → m r) → m r :=\n id\n#align cont_t.run ContT.run\n\ndef map (f : m r → m r) (x : ContT r m α) : ContT r m α :=\n f ∘ x\n#align cont_t.map ContT.map\n\ntheorem run_contT_map_contT (f : m r → m r) (x : ContT r m α) : run (map f x) = f ∘ run x :=\n rfl\n#align cont_t.run_cont_t_map_cont_t ContT.run_contT_map_contT\n\ndef withContT (f : (β → m r) → α → m r) (x : ContT r m α) : ContT r m β := fun g => x <| f g\n#align cont_t.with_cont_t ContT.withContT\n\ntheorem run_withContT (f : (β → m r) → α → m r) (x : ContT r m α) :\n run (withContT f x) = run x ∘ f :=\n rfl\n#align cont_t.run_with_cont_t ContT.run_withContT\n\n@[ext]\nprotected theorem ext {x y : ContT r m α} (h : ∀ f, x.run f = y.run f) : x = y := by ext <;> apply h\n#align cont_t.ext ContT.ext\n\ninstance : Monad (ContT r m) where\n pure α x f := f x\n bind α β x f g := x fun i => f i g\n\ninstance : LawfulMonad (ContT r m)\n where\n id_map := by\n intros\n rfl\n pure_bind := by\n intros\n ext\n rfl\n bind_assoc := by\n intros\n ext\n rfl\n\ndef monadLift [Monad m] {α} : m α → ContT r m α := fun x f => x >>= f\n#align cont_t.monad_lift ContT.monadLift\n\ninstance [Monad m] : HasMonadLift m (ContT r m) where monadLift α := ContT.monadLift\n\ntheorem monadLift_bind [Monad m] [LawfulMonad m] {α β} (x : m α) (f : α → m β) :\n (monadLift (x >>= f) : ContT r m β) = monadLift x >>= monadLift ∘ f :=\n by\n ext\n simp only [monad_lift, HasMonadLift.monadLift, (· ∘ ·), (· >>= ·), bind_assoc, id.def, run,\n ContT.monadLift]\n#align cont_t.monad_lift_bind ContT.monadLift_bind\n\ninstance : MonadCont (ContT r m) where callCc α β f g := f ⟨fun x h => g x⟩ g\n\ninstance : IsLawfulMonadCont (ContT r m)\n where\n callCc_bind_right := by intros <;> ext <;> rfl\n callCc_bind_left := by intros <;> ext <;> rfl\n callCc_dummy := by intros <;> ext <;> rfl\n\ninstance (ε) [MonadExcept ε m] : MonadExcept ε (ContT r m)\n where\n throw x e f := throw e\n catch α act h f := catch (act f) fun e => h e f\n\ninstance : MonadRun (fun α => (α → m r) → ULift.{u, v} (m r)) (ContT.{u, v, u} r m)\n where run α f x := ⟨f x⟩\n\nend ContT\n\nvariable {m : Type u → Type v} [Monad m]\n\ndef ExceptT.mkLabel {α β ε} : Label (Except.{u, u} ε α) m β → Label α (ExceptT ε m) β\n | ⟨f⟩ => ⟨fun a => monadLift <| f (Except.ok a)⟩\n#align except_t.mk_label ExceptTₓ.mkLabel\n\ntheorem ExceptT.goto_mkLabel {α β ε : Type _} (x : Label (Except.{u, u} ε α) m β) (i : α) :\n goto (ExceptT.mkLabel x) i = ⟨Except.ok <$> goto x (Except.ok i)⟩ := by cases x <;> rfl\n#align except_t.goto_mk_label ExceptTₓ.goto_mkLabel\n\ndef ExceptT.callCc {ε} [MonadCont m] {α β : Type _} (f : Label α (ExceptT ε m) β → ExceptT ε m α) :\n ExceptT ε m α :=\n ExceptT.mk (callCc fun x : Label _ m β => ExceptT.run <| f (ExceptT.mkLabel x) : m (Except ε α))\n#align except_t.call_cc ExceptTₓ.callCc\n\ninstance {ε} [MonadCont m] : MonadCont (ExceptT ε m) where callCc α β := ExceptT.callCc\n\ninstance {ε} [MonadCont m] [IsLawfulMonadCont m] : IsLawfulMonadCont (ExceptT ε m)\n where\n callCc_bind_right := by\n intros\n simp [call_cc, ExceptT.callCc, call_cc_bind_right]\n ext\n dsimp\n congr with ⟨⟩ <;> simp [ExceptT.bindCont, @call_cc_dummy m _]\n callCc_bind_left := by\n intros\n simp [call_cc, ExceptT.callCc, call_cc_bind_right, ExceptT.goto_mkLabel, map_eq_bind_pure_comp,\n bind_assoc, @call_cc_bind_left m _]\n ext\n rfl\n callCc_dummy := by\n intros\n simp [call_cc, ExceptT.callCc, @call_cc_dummy m _]\n ext\n rfl\n\ndef OptionT.mkLabel {α β} : Label (Option.{u} α) m β → Label α (OptionT m) β\n | ⟨f⟩ => ⟨fun a => monadLift <| f (some a)⟩\n#align option_t.mk_label OptionTₓ.mkLabel\n\ntheorem OptionT.goto_mkLabel {α β : Type _} (x : Label (Option.{u} α) m β) (i : α) :\n goto (OptionT.mkLabel x) i = ⟨some <$> goto x (some i)⟩ := by cases x <;> rfl\n#align option_t.goto_mk_label OptionTₓ.goto_mkLabel\n\ndef OptionT.callCc [MonadCont m] {α β : Type _} (f : Label α (OptionT m) β → OptionT m α) :\n OptionT m α :=\n OptionT.mk (callCc fun x : Label _ m β => OptionT.run <| f (OptionT.mkLabel x) : m (Option α))\n#align option_t.call_cc OptionTₓ.callCc\n\ninstance [MonadCont m] : MonadCont (OptionT m) where callCc α β := OptionT.callCc\n\ninstance [MonadCont m] [IsLawfulMonadCont m] : IsLawfulMonadCont (OptionT m)\n where\n callCc_bind_right := by\n intros\n simp [call_cc, OptionT.callCc, call_cc_bind_right]\n ext\n dsimp\n congr with ⟨⟩ <;> simp [OptionT.bindCont, @call_cc_dummy m _]\n callCc_bind_left := by\n intros\n simp [call_cc, OptionT.callCc, call_cc_bind_right, OptionT.goto_mkLabel, map_eq_bind_pure_comp,\n bind_assoc, @call_cc_bind_left m _]\n ext\n rfl\n callCc_dummy := by\n intros\n simp [call_cc, OptionT.callCc, @call_cc_dummy m _]\n ext\n rfl\n\n/- warning: writer_t.mk_label -> WriterTₓ.mkLabel is a dubious translation:\nlean 3 declaration is\n forall {m : Type.{u1} -> Type.{u2}} [_inst_1 : Monad.{u1, u2} m] {α : Type.{u3}} {β : Type.{u1}} {ω : Type.{u1}} [_inst_2 : One.{u1} ω], (MonadCont.Label.{u1, u2, max u3 u1} (Prod.{u3, u1} α ω) m β) -> (MonadCont.Label.{u1, max u1 u2, u3} α (WriterTₓ.{u1, u2} ω m) β)\nbut is expected to have type\n forall {m : Type.{u2} -> Type.{u3}} [_inst_1 : Monad.{u2, u3} m] {α : Type.{u1}} {β : Type.{u2}} {ω : Type.{u2}} [_inst_2 : One.{u2} ω], (MonadCont.Label.{u2, u3, max u1 u2} (Prod.{u1, u2} α ω) m β) -> (MonadCont.Label.{u2, max u2 u3, u1} α (WriterTₓ.{u2, u3} ω m) β)\nCase conversion may be inaccurate. Consider using '#align writer_t.mk_label WriterTₓ.mkLabelₓ'. -/\ndef WriterT.mkLabel {α β ω} [One ω] : Label (α × ω) m β → Label α (WriterT ω m) β\n | ⟨f⟩ => ⟨fun a => monadLift <| f (a, 1)⟩\n#align writer_t.mk_label WriterTₓ.mkLabel\n\ntheorem WriterT.goto_mkLabel {α β ω : Type _} [One ω] (x : Label (α × ω) m β) (i : α) :\n goto (WriterT.mkLabel x) i = monadLift (goto x (i, 1)) := by cases x <;> rfl\n#align writer_t.goto_mk_label WriterTₓ.goto_mkLabel\n\ndef WriterT.callCc [MonadCont m] {α β ω : Type _} [One ω]\n (f : Label α (WriterT ω m) β → WriterT ω m α) : WriterT ω m α :=\n ⟨callCc (WriterT.run ∘ f ∘ WriterT.mkLabel : Label (α × ω) m β → m (α × ω))⟩\n#align writer_t.call_cc WriterTₓ.callCc\n\ninstance (ω) [Monad m] [One ω] [MonadCont m] : MonadCont (WriterT ω m)\n where callCc α β := WriterT.callCc\n\n/- warning: state_t.mk_label -> StateTₓ.mkLabel is a dubious translation:\nlean 3 declaration is\n forall {m : Type.{u1} -> Type.{u2}} [_inst_1 : Monad.{u1, u2} m] {α : Type.{u1}} {β : Type.{u1}} {σ : Type.{u1}}, (MonadCont.Label.{u1, u2, u1} (Prod.{u1, u1} α σ) m (Prod.{u1, u1} β σ)) -> (MonadCont.Label.{u1, max u1 u2, u1} α (StateTₓ.{u1, u2} σ m) β)\nbut is expected to have type\n forall {m : Type.{u1} -> Type.{u2}} {_inst_1 : Type.{u1}} {α : Type.{u1}} {β : Type.{u1}}, (MonadCont.Label.{u1, u2, u1} (Prod.{u1, u1} _inst_1 β) m (Prod.{u1, u1} α β)) -> (MonadCont.Label.{u1, max u1 u2, u1} _inst_1 (StateTₓ.{u1, u2} β m) α)\nCase conversion may be inaccurate. Consider using '#align state_t.mk_label StateTₓ.mkLabelₓ'. -/\ndef StateT.mkLabel {α β σ : Type u} : Label (α × σ) m (β × σ) → Label α (StateT σ m) β\n | ⟨f⟩ => ⟨fun a => ⟨fun s => f (a, s)⟩⟩\n#align state_t.mk_label StateTₓ.mkLabel\n\ntheorem StateT.goto_mkLabel {α β σ : Type u} (x : Label (α × σ) m (β × σ)) (i : α) :\n goto (StateT.mkLabel x) i = ⟨fun s => goto x (i, s)⟩ := by cases x <;> rfl\n#align state_t.goto_mk_label StateTₓ.goto_mkLabel\n\ndef StateT.callCc {σ} [MonadCont m] {α β : Type _} (f : Label α (StateT σ m) β → StateT σ m α) :\n StateT σ m α :=\n ⟨fun r => callCc fun f' => (f <| StateT.mkLabel f').run r⟩\n#align state_t.call_cc StateTₓ.callCc\n\ninstance {σ} [MonadCont m] : MonadCont (StateT σ m) where callCc α β := StateT.callCc\n\ninstance {σ} [MonadCont m] [IsLawfulMonadCont m] : IsLawfulMonadCont (StateT σ m)\n where\n callCc_bind_right := by\n intros\n simp [call_cc, StateT.callCc, call_cc_bind_right, (· >>= ·), StateT.bind]\n ext\n dsimp\n congr with ⟨x₀, x₁⟩\n rfl\n callCc_bind_left := by\n intros\n simp [call_cc, StateT.callCc, call_cc_bind_left, (· >>= ·), StateT.bind, StateT.goto_mkLabel]\n ext\n rfl\n callCc_dummy := by\n intros\n simp [call_cc, StateT.callCc, call_cc_bind_right, (· >>= ·), StateT.bind, @call_cc_dummy m _]\n ext\n rfl\n\n/- warning: reader_t.mk_label -> ReaderTₓ.mkLabel is a dubious translation:\nlean 3 declaration is\n forall {m : Type.{u1} -> Type.{u2}} [_inst_1 : Monad.{u1, u2} m] {α : Type.{u3}} {β : Type.{u1}} (ρ : Type.{u1}), (MonadCont.Label.{u1, u2, u3} α m β) -> (MonadCont.Label.{u1, max u1 u2, u3} α (ReaderTₓ.{u1, u2} ρ m) β)\nbut is expected to have type\n forall {m : Type.{u2} -> Type.{u3}} [_inst_1 : Monad.{u2, u3} m] {α : Type.{u1}} {β : Type.{u2}} (ρ : Type.{u2}), (MonadCont.Label.{u2, u3, u1} α m β) -> (MonadCont.Label.{u2, max u2 u3, u1} α (ReaderTₓ.{u2, u3} ρ m) β)\nCase conversion may be inaccurate. Consider using '#align reader_t.mk_label ReaderTₓ.mkLabelₓ'. -/\ndef ReaderT.mkLabel {α β} (ρ) : Label α m β → Label α (ReaderT ρ m) β\n | ⟨f⟩ => ⟨monadLift ∘ f⟩\n#align reader_t.mk_label ReaderTₓ.mkLabel\n\ntheorem ReaderT.goto_mkLabel {α ρ β} (x : Label α m β) (i : α) :\n goto (ReaderT.mkLabel ρ x) i = monadLift (goto x i) := by cases x <;> rfl\n#align reader_t.goto_mk_label ReaderTₓ.goto_mkLabel\n\ndef ReaderT.callCc {ε} [MonadCont m] {α β : Type _} (f : Label α (ReaderT ε m) β → ReaderT ε m α) :\n ReaderT ε m α :=\n ⟨fun r => callCc fun f' => (f <| ReaderT.mkLabel _ f').run r⟩\n#align reader_t.call_cc ReaderTₓ.callCc\n\ninstance {ρ} [MonadCont m] : MonadCont (ReaderT ρ m) where callCc α β := ReaderT.callCc\n\ninstance {ρ} [MonadCont m] [IsLawfulMonadCont m] : IsLawfulMonadCont (ReaderT ρ m)\n where\n callCc_bind_right := by\n intros\n simp [call_cc, ReaderT.callCc, call_cc_bind_right]\n ext\n rfl\n callCc_bind_left := by\n intros\n simp [call_cc, ReaderT.callCc, call_cc_bind_left, ReaderT.goto_mkLabel]\n ext\n rfl\n callCc_dummy := by\n intros\n simp [call_cc, ReaderT.callCc, @call_cc_dummy m _]\n ext\n rfl\n\n/-- reduce the equivalence between two continuation passing monads to the equivalence between\ntheir underlying monad -/\ndef ContT.equiv {m₁ : Type u₀ → Type v₀} {m₂ : Type u₁ → Type v₁} {α₁ r₁ : Type u₀}\n {α₂ r₂ : Type u₁} (F : m₁ r₁ ≃ m₂ r₂) (G : α₁ ≃ α₂) : ContT r₁ m₁ α₁ ≃ ContT r₂ m₂ α₂\n where\n toFun f r := F <| f fun x => F.symm <| r <| G x\n invFun f r := F.symm <| f fun x => F <| r <| G.symm x\n left_inv f := by funext r <;> simp\n right_inv f := by funext r <;> simp\n#align cont_t.equiv ContT.equiv\n\n", "meta": {"author": "leanprover-community", "repo": "mathlib3port", "sha": "62505aa236c58c8559783b16d33e30df3daa54f4", "save_path": "github-repos/lean/leanprover-community-mathlib3port", "path": "github-repos/lean/leanprover-community-mathlib3port/mathlib3port-62505aa236c58c8559783b16d33e30df3daa54f4/Mathbin/Control/Monad/Cont.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4493926344647596, "lm_q2_score": 0.08035746221501941, "lm_q1q2_score": 0.036112051643709946}} {"text": "/-\nCopyright (c) 2022 Andrew Yang. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Andrew Yang\n\n! This file was ported from Lean 3 source module category_theory.sites.subsheaf\n! leanprover-community/mathlib commit 70fd9563a21e7b963887c9360bd29b2393e6225a\n! Please do not edit these lines, except to modify the commit id\n! if you have ported upstream changes.\n-/\nimport Mathbin.CategoryTheory.Elementwise\nimport Mathbin.CategoryTheory.Adjunction.Evaluation\nimport Mathbin.CategoryTheory.Sites.Sheafification\n\n/-!\n\n# Subsheaf of types\n\nWe define the sub(pre)sheaf of a type valued presheaf.\n\n## Main results\n\n- `category_theory.grothendieck_topology.subpresheaf` :\n A subpresheaf of a presheaf of types.\n- `category_theory.grothendieck_topology.subpresheaf.sheafify` :\n The sheafification of a subpresheaf as a subpresheaf. Note that this is a sheaf only when the\n whole sheaf is.\n- `category_theory.grothendieck_topology.subpresheaf.sheafify_is_sheaf` :\n The sheafification is a sheaf\n- `category_theory.grothendieck_topology.subpresheaf.sheafify_lift` :\n The descent of a map into a sheaf to the sheafification.\n- `category_theory.grothendieck_topology.image_sheaf` : The image sheaf of a morphism.\n- `category_theory.grothendieck_topology.image_factorization` : The image sheaf as a\n `limits.image_factorization`.\n-/\n\n\nuniverse w v u\n\nopen Opposite CategoryTheory\n\nnamespace CategoryTheory.GrothendieckTopology\n\nvariable {C : Type u} [Category.{v} C] (J : GrothendieckTopology C)\n\n/-- A subpresheaf of a presheaf consists of a subset of `F.obj U` for every `U`,\ncompatible with the restriction maps `F.map i`. -/\n@[ext]\nstructure Subpresheaf (F : Cᵒᵖ ⥤ Type w) where\n obj : ∀ U, Set (F.obj U)\n map : ∀ {U V : Cᵒᵖ} (i : U ⟶ V), obj U ⊆ F.map i ⁻¹' obj V\n#align category_theory.grothendieck_topology.subpresheaf CategoryTheory.GrothendieckTopology.Subpresheaf\n\nvariable {F F' F'' : Cᵒᵖ ⥤ Type w} (G G' : Subpresheaf F)\n\ninstance : PartialOrder (Subpresheaf F) :=\n PartialOrder.lift Subpresheaf.obj Subpresheaf.ext\n\ninstance : Top (Subpresheaf F) :=\n ⟨⟨fun U => ⊤, fun U V i x h => trivial⟩⟩\n\ninstance : Nonempty (Subpresheaf F) :=\n inferInstance\n\n/-- The subpresheaf as a presheaf. -/\n@[simps]\ndef Subpresheaf.toPresheaf : Cᵒᵖ ⥤ Type w\n where\n obj U := G.obj U\n map U V i x := ⟨F.map i x, G.map i x.Prop⟩\n map_id' X := by\n ext ⟨x, _⟩\n dsimp\n rw [F.map_id]\n rfl\n map_comp' X Y Z i j := by\n ext ⟨x, _⟩\n dsimp\n rw [F.map_comp]\n rfl\n#align category_theory.grothendieck_topology.subpresheaf.to_presheaf CategoryTheory.GrothendieckTopology.Subpresheaf.toPresheaf\n\ninstance {U} : Coe (G.toPresheaf.obj U) (F.obj U) :=\n coeSubtype\n\n/-- The inclusion of a subpresheaf to the original presheaf. -/\n@[simps]\ndef Subpresheaf.ι : G.toPresheaf ⟶ F where app U x := x\n#align category_theory.grothendieck_topology.subpresheaf.ι CategoryTheory.GrothendieckTopology.Subpresheaf.ι\n\ninstance : Mono G.ι :=\n ⟨fun H f₁ f₂ e =>\n NatTrans.ext f₁ f₂ <|\n funext fun U => funext fun x => Subtype.ext <| congr_fun (congr_app e U) x⟩\n\n/-- The inclusion of a subpresheaf to a larger subpresheaf -/\n@[simps]\ndef Subpresheaf.homOfLe {G G' : Subpresheaf F} (h : G ≤ G') : G.toPresheaf ⟶ G'.toPresheaf\n where app U x := ⟨x, h U x.Prop⟩\n#align category_theory.grothendieck_topology.subpresheaf.hom_of_le CategoryTheory.GrothendieckTopology.Subpresheaf.homOfLe\n\ninstance {G G' : Subpresheaf F} (h : G ≤ G') : Mono (Subpresheaf.homOfLe h) :=\n ⟨fun H f₁ f₂ e =>\n NatTrans.ext f₁ f₂ <|\n funext fun U =>\n funext fun x =>\n Subtype.ext <| (congr_arg Subtype.val <| (congr_fun (congr_app e U) x : _) : _)⟩\n\n@[simp, reassoc.1]\ntheorem Subpresheaf.homOfLe_ι {G G' : Subpresheaf F} (h : G ≤ G') :\n Subpresheaf.homOfLe h ≫ G'.ι = G.ι := by\n ext\n rfl\n#align category_theory.grothendieck_topology.subpresheaf.hom_of_le_ι CategoryTheory.GrothendieckTopology.Subpresheaf.homOfLe_ι\n\ninstance : IsIso (Subpresheaf.ι (⊤ : Subpresheaf F)) :=\n by\n apply (config := { instances := false }) nat_iso.is_iso_of_is_iso_app\n · intro X\n rw [is_iso_iff_bijective]\n exact ⟨Subtype.coe_injective, fun x => ⟨⟨x, _root_.trivial⟩, rfl⟩⟩\n\ntheorem Subpresheaf.eq_top_iff_isIso : G = ⊤ ↔ IsIso G.ι :=\n by\n constructor\n · rintro rfl\n infer_instance\n · intro H\n ext (U x)\n apply (iff_true_iff _).mpr\n rw [← is_iso.inv_hom_id_apply (G.ι.app U) x]\n exact ((inv (G.ι.app U)) x).2\n#align category_theory.grothendieck_topology.subpresheaf.eq_top_iff_is_iso CategoryTheory.GrothendieckTopology.Subpresheaf.eq_top_iff_isIso\n\n/-- If the image of a morphism falls in a subpresheaf, then the morphism factors through it. -/\n@[simps]\ndef Subpresheaf.lift (f : F' ⟶ F) (hf : ∀ U x, f.app U x ∈ G.obj U) : F' ⟶ G.toPresheaf\n where\n app U x := ⟨f.app U x, hf U x⟩\n naturality' := by\n have := elementwise_of f.naturality\n intros\n ext\n simp [this]\n#align category_theory.grothendieck_topology.subpresheaf.lift CategoryTheory.GrothendieckTopology.Subpresheaf.lift\n\n@[simp, reassoc.1]\ntheorem Subpresheaf.lift_ι (f : F' ⟶ F) (hf : ∀ U x, f.app U x ∈ G.obj U) : G.lift f hf ≫ G.ι = f :=\n by\n ext\n rfl\n#align category_theory.grothendieck_topology.subpresheaf.lift_ι CategoryTheory.GrothendieckTopology.Subpresheaf.lift_ι\n\n/-- Given a subpresheaf `G` of `F`, an `F`-section `s` on `U`, we may define a sieve of `U`\nconsisting of all `f : V ⟶ U` such that the restriction of `s` along `f` is in `G`. -/\n@[simps]\ndef Subpresheaf.sieveOfSection {U : Cᵒᵖ} (s : F.obj U) : Sieve (unop U)\n where\n arrows V f := F.map f.op s ∈ G.obj (op V)\n downward_closed' V W i hi j :=\n by\n rw [op_comp, functor_to_types.map_comp_apply]\n exact G.map _ hi\n#align category_theory.grothendieck_topology.subpresheaf.sieve_of_section CategoryTheory.GrothendieckTopology.Subpresheaf.sieveOfSection\n\n/-- Given a `F`-section `s` on `U` and a subpresheaf `G`, we may define a family of elements in\n`G` consisting of the restrictions of `s` -/\ndef Subpresheaf.familyOfElementsOfSection {U : Cᵒᵖ} (s : F.obj U) :\n (G.sieveOfSection s).1.FamilyOfElements G.toPresheaf := fun V i hi => ⟨F.map i.op s, hi⟩\n#align category_theory.grothendieck_topology.subpresheaf.family_of_elements_of_section CategoryTheory.GrothendieckTopology.Subpresheaf.familyOfElementsOfSection\n\ntheorem Subpresheaf.family_of_elements_compatible {U : Cᵒᵖ} (s : F.obj U) :\n (G.familyOfElementsOfSection s).Compatible :=\n by\n intro Y₁ Y₂ Z g₁ g₂ f₁ f₂ h₁ h₂ e\n ext1\n change F.map g₁.op (F.map f₁.op s) = F.map g₂.op (F.map f₂.op s)\n rw [← functor_to_types.map_comp_apply, ← functor_to_types.map_comp_apply, ← op_comp, ← op_comp, e]\n#align category_theory.grothendieck_topology.subpresheaf.family_of_elements_compatible CategoryTheory.GrothendieckTopology.Subpresheaf.family_of_elements_compatible\n\ntheorem Subpresheaf.nat_trans_naturality (f : F' ⟶ G.toPresheaf) {U V : Cᵒᵖ} (i : U ⟶ V)\n (x : F'.obj U) : (f.app V (F'.map i x)).1 = F.map i (f.app U x).1 :=\n congr_arg Subtype.val (FunctorToTypes.naturality _ _ f i x)\n#align category_theory.grothendieck_topology.subpresheaf.nat_trans_naturality CategoryTheory.GrothendieckTopology.Subpresheaf.nat_trans_naturality\n\ninclude J\n\n/-- The sheafification of a subpresheaf as a subpresheaf.\nNote that this is a sheaf only when the whole presheaf is a sheaf. -/\ndef Subpresheaf.sheafify : Subpresheaf F\n where\n obj U := { s | G.sieveOfSection s ∈ J (unop U) }\n map := by\n rintro U V i s hs\n refine' J.superset_covering _ (J.pullback_stable i.unop hs)\n intro _ _ h\n dsimp at h⊢\n rwa [← functor_to_types.map_comp_apply]\n#align category_theory.grothendieck_topology.subpresheaf.sheafify CategoryTheory.GrothendieckTopology.Subpresheaf.sheafify\n\ntheorem Subpresheaf.le_sheafify : G ≤ G.sheafify J :=\n by\n intro U s hs\n change _ ∈ J _\n convert J.top_mem _\n rw [eq_top_iff]\n rintro V i -\n exact G.map i.op hs\n#align category_theory.grothendieck_topology.subpresheaf.le_sheafify CategoryTheory.GrothendieckTopology.Subpresheaf.le_sheafify\n\nvariable {J}\n\ntheorem Subpresheaf.eq_sheafify (h : Presieve.IsSheaf J F) (hG : Presieve.IsSheaf J G.toPresheaf) :\n G = G.sheafify J := by\n apply (G.le_sheafify J).antisymm\n intro U s hs\n suffices ((hG _ hs).amalgamate _ (G.family_of_elements_compatible s)).1 = s\n by\n rw [← this]\n exact ((hG _ hs).amalgamate _ (G.family_of_elements_compatible s)).2\n apply (h _ hs).IsSeparatedFor.ext\n intro V i hi\n exact (congr_arg Subtype.val ((hG _ hs).valid_glue (G.family_of_elements_compatible s) _ hi) : _)\n#align category_theory.grothendieck_topology.subpresheaf.eq_sheafify CategoryTheory.GrothendieckTopology.Subpresheaf.eq_sheafify\n\ntheorem Subpresheaf.sheafify_isSheaf (hF : Presieve.IsSheaf J F) :\n Presieve.IsSheaf J (G.sheafify J).toPresheaf :=\n by\n intro U S hS x hx\n let S' := sieve.bind S fun Y f hf => G.sieve_of_section (x f hf).1\n have := fun {V} {i : V ⟶ U} (hi : S' i) => hi\n choose W i₁ i₂ hi₂ h₁ h₂\n dsimp [-sieve.bind_apply] at *\n let x'' : presieve.family_of_elements F S' := fun V i hi => F.map (i₁ hi).op (x _ (hi₂ hi))\n have H : ∀ s, x.is_amalgamation s ↔ x''.is_amalgamation s.1 :=\n by\n intro s\n constructor\n · intro H V i hi\n dsimp only [x'']\n conv_lhs => rw [← h₂ hi]\n rw [← H _ (hi₂ hi)]\n exact functor_to_types.map_comp_apply F (i₂ hi).op (i₁ hi).op _\n · intro H V i hi\n ext1\n apply (hF _ (x i hi).2).IsSeparatedFor.ext\n intro V' i' hi'\n have hi'' : S' (i' ≫ i) := ⟨_, _, _, hi, hi', rfl⟩\n have := H _ hi''\n rw [op_comp, F.map_comp] at this\n refine' this.trans (congr_arg Subtype.val (hx _ _ (hi₂ hi'') hi (h₂ hi'')))\n have : x''.compatible := by\n intro V₁ V₂ V₃ g₁ g₂ g₃ g₄ S₁ S₂ e\n rw [← functor_to_types.map_comp_apply, ← functor_to_types.map_comp_apply]\n exact\n congr_arg Subtype.val\n (hx (g₁ ≫ i₁ S₁) (g₂ ≫ i₁ S₂) (hi₂ S₁) (hi₂ S₂) (by simp only [category.assoc, h₂, e]))\n obtain ⟨t, ht, ht'⟩ := hF _ (J.bind_covering hS fun V i hi => (x i hi).2) _ this\n refine' ⟨⟨t, _⟩, (H ⟨t, _⟩).mpr ht, fun y hy => Subtype.ext (ht' _ ((H _).mp hy))⟩\n show G.sieve_of_section t ∈ J _\n refine' J.superset_covering _ (J.bind_covering hS fun V i hi => (x i hi).2)\n intro V i hi\n dsimp\n rw [ht _ hi]\n exact h₁ hi\n#align category_theory.grothendieck_topology.subpresheaf.sheafify_is_sheaf CategoryTheory.GrothendieckTopology.Subpresheaf.sheafify_isSheaf\n\ntheorem Subpresheaf.eq_sheafify_iff (h : Presieve.IsSheaf J F) :\n G = G.sheafify J ↔ Presieve.IsSheaf J G.toPresheaf :=\n ⟨fun e => e.symm ▸ G.sheafify_isSheaf h, G.eq_sheafify h⟩\n#align category_theory.grothendieck_topology.subpresheaf.eq_sheafify_iff CategoryTheory.GrothendieckTopology.Subpresheaf.eq_sheafify_iff\n\ntheorem Subpresheaf.isSheaf_iff (h : Presieve.IsSheaf J F) :\n Presieve.IsSheaf J G.toPresheaf ↔\n ∀ (U) (s : F.obj U), G.sieveOfSection s ∈ J (unop U) → s ∈ G.obj U :=\n by\n rw [← G.eq_sheafify_iff h]\n change _ ↔ G.sheafify J ≤ G\n exact ⟨Eq.ge, (G.le_sheafify J).antisymm⟩\n#align category_theory.grothendieck_topology.subpresheaf.is_sheaf_iff CategoryTheory.GrothendieckTopology.Subpresheaf.isSheaf_iff\n\ntheorem Subpresheaf.sheafify_sheafify (h : Presieve.IsSheaf J F) :\n (G.sheafify J).sheafify J = G.sheafify J :=\n ((Subpresheaf.eq_sheafify_iff _ h).mpr <| G.sheafify_isSheaf h).symm\n#align category_theory.grothendieck_topology.subpresheaf.sheafify_sheafify CategoryTheory.GrothendieckTopology.Subpresheaf.sheafify_sheafify\n\n/-- The lift of a presheaf morphism onto the sheafification subpresheaf. -/\nnoncomputable def Subpresheaf.sheafifyLift (f : G.toPresheaf ⟶ F') (h : Presieve.IsSheaf J F') :\n (G.sheafify J).toPresheaf ⟶ F'\n where\n app U s := (h _ s.Prop).amalgamate _ ((G.family_of_elements_compatible ↑s).compPresheafMap f)\n naturality' := by\n intro U V i\n ext s\n apply (h _ ((subpresheaf.sheafify J G).toPresheaf.map i s).Prop).IsSeparatedFor.ext\n intro W j hj\n refine' (presieve.is_sheaf_for.valid_glue _ _ _ hj).trans _\n dsimp\n conv_rhs => rw [← functor_to_types.map_comp_apply]\n change _ = F'.map (j ≫ i.unop).op _\n refine' Eq.trans _ (presieve.is_sheaf_for.valid_glue _ _ _ _).symm\n · dsimp at hj⊢\n rwa [functor_to_types.map_comp_apply]\n · dsimp [presieve.family_of_elements.comp_presheaf_map]\n congr 1\n ext1\n exact (functor_to_types.map_comp_apply _ _ _ _).symm\n#align category_theory.grothendieck_topology.subpresheaf.sheafify_lift CategoryTheory.GrothendieckTopology.Subpresheaf.sheafifyLift\n\ntheorem Subpresheaf.to_sheafifyLift (f : G.toPresheaf ⟶ F') (h : Presieve.IsSheaf J F') :\n Subpresheaf.homOfLe (G.le_sheafify J) ≫ G.sheafifyLift f h = f :=\n by\n ext (U s)\n apply (h _ ((subpresheaf.hom_of_le (G.le_sheafify J)).app U s).Prop).IsSeparatedFor.ext\n intro V i hi\n have := elementwise_of f.naturality\n exact (presieve.is_sheaf_for.valid_glue _ _ _ hi).trans (this _ _)\n#align category_theory.grothendieck_topology.subpresheaf.to_sheafify_lift CategoryTheory.GrothendieckTopology.Subpresheaf.to_sheafifyLift\n\ntheorem Subpresheaf.to_sheafify_lift_unique (h : Presieve.IsSheaf J F')\n (l₁ l₂ : (G.sheafify J).toPresheaf ⟶ F')\n (e : Subpresheaf.homOfLe (G.le_sheafify J) ≫ l₁ = Subpresheaf.homOfLe (G.le_sheafify J) ≫ l₂) :\n l₁ = l₂ := by\n ext (U⟨s, hs⟩)\n apply (h _ hs).IsSeparatedFor.ext\n rintro V i hi\n dsimp at hi\n erw [← functor_to_types.naturality, ← functor_to_types.naturality]\n exact (congr_fun (congr_app e <| op V) ⟨_, hi⟩ : _)\n#align category_theory.grothendieck_topology.subpresheaf.to_sheafify_lift_unique CategoryTheory.GrothendieckTopology.Subpresheaf.to_sheafify_lift_unique\n\ntheorem Subpresheaf.sheafify_le (h : G ≤ G') (hF : Presieve.IsSheaf J F)\n (hG' : Presieve.IsSheaf J G'.toPresheaf) : G.sheafify J ≤ G' :=\n by\n intro U x hx\n convert((G.sheafify_lift (subpresheaf.hom_of_le h) hG').app U ⟨x, hx⟩).2\n apply (hF _ hx).IsSeparatedFor.ext\n intro V i hi\n have :=\n congr_arg (fun f : G.to_presheaf ⟶ G'.to_presheaf => (nat_trans.app f (op V) ⟨_, hi⟩).1)\n (G.to_sheafify_lift (subpresheaf.hom_of_le h) hG')\n convert this.symm\n erw [← subpresheaf.nat_trans_naturality]\n rfl\n#align category_theory.grothendieck_topology.subpresheaf.sheafify_le CategoryTheory.GrothendieckTopology.Subpresheaf.sheafify_le\n\nomit J\n\nsection Image\n\n/-- The image presheaf of a morphism, whose components are the set-theoretic images. -/\n@[simps]\ndef imagePresheaf (f : F' ⟶ F) : Subpresheaf F\n where\n obj U := Set.range (f.app U)\n map U V i := by\n rintro _ ⟨x, rfl⟩\n have := elementwise_of f.naturality\n exact ⟨_, this i x⟩\n#align category_theory.grothendieck_topology.image_presheaf CategoryTheory.GrothendieckTopology.imagePresheaf\n\n@[simp]\ntheorem top_subpresheaf_obj (U) : (⊤ : Subpresheaf F).obj U = ⊤ :=\n rfl\n#align category_theory.grothendieck_topology.top_subpresheaf_obj CategoryTheory.GrothendieckTopology.top_subpresheaf_obj\n\n@[simp]\ntheorem imagePresheaf_id : imagePresheaf (𝟙 F) = ⊤ :=\n by\n ext\n simp\n#align category_theory.grothendieck_topology.image_presheaf_id CategoryTheory.GrothendieckTopology.imagePresheaf_id\n\n/-- A morphism factors through the image presheaf. -/\n@[simps]\ndef toImagePresheaf (f : F' ⟶ F) : F' ⟶ (imagePresheaf f).toPresheaf :=\n (imagePresheaf f).lift f fun U x => Set.mem_range_self _\n#align category_theory.grothendieck_topology.to_image_presheaf CategoryTheory.GrothendieckTopology.toImagePresheaf\n\nvariable (J)\n\n/-- A morphism factors through the sheafification of the image presheaf. -/\n@[simps]\ndef toImagePresheafSheafify (f : F' ⟶ F) : F' ⟶ ((imagePresheaf f).sheafify J).toPresheaf :=\n toImagePresheaf f ≫ Subpresheaf.homOfLe ((imagePresheaf f).le_sheafify J)\n#align category_theory.grothendieck_topology.to_image_presheaf_sheafify CategoryTheory.GrothendieckTopology.toImagePresheafSheafify\n\nvariable {J}\n\n@[simp, reassoc.1]\ntheorem toImagePresheaf_ι (f : F' ⟶ F) : toImagePresheaf f ≫ (imagePresheaf f).ι = f :=\n (imagePresheaf f).lift_ι _ _\n#align category_theory.grothendieck_topology.to_image_presheaf_ι CategoryTheory.GrothendieckTopology.toImagePresheaf_ι\n\ntheorem imagePresheaf_comp_le (f₁ : F ⟶ F') (f₂ : F' ⟶ F'') :\n imagePresheaf (f₁ ≫ f₂) ≤ imagePresheaf f₂ := fun U x hx => ⟨f₁.app U hx.some, hx.choose_spec⟩\n#align category_theory.grothendieck_topology.image_presheaf_comp_le CategoryTheory.GrothendieckTopology.imagePresheaf_comp_le\n\ninstance {F F' : Cᵒᵖ ⥤ Type max v w} (f : F ⟶ F') [hf : Mono f] : IsIso (toImagePresheaf f) :=\n by\n apply (config := { instances := false }) nat_iso.is_iso_of_is_iso_app\n intro X\n rw [is_iso_iff_bijective]\n constructor\n · intro x y e\n have := (nat_trans.mono_iff_mono_app _ _).mp hf X\n rw [mono_iff_injective] at this\n exact this (congr_arg Subtype.val e : _)\n · rintro ⟨_, ⟨x, rfl⟩⟩\n exact ⟨x, rfl⟩\n\n/-- The image sheaf of a morphism between sheaves, defined to be the sheafification of\n`image_presheaf`. -/\n@[simps]\ndef imageSheaf {F F' : Sheaf J (Type w)} (f : F ⟶ F') : Sheaf J (Type w) :=\n ⟨((imagePresheaf f.1).sheafify J).toPresheaf,\n by\n rw [is_sheaf_iff_is_sheaf_of_type]\n apply subpresheaf.sheafify_is_sheaf\n rw [← is_sheaf_iff_is_sheaf_of_type]\n exact F'.2⟩\n#align category_theory.grothendieck_topology.image_sheaf CategoryTheory.GrothendieckTopology.imageSheaf\n\n/-- A morphism factors through the image sheaf. -/\n@[simps]\ndef toImageSheaf {F F' : Sheaf J (Type w)} (f : F ⟶ F') : F ⟶ imageSheaf f :=\n ⟨toImagePresheafSheafify J f.1⟩\n#align category_theory.grothendieck_topology.to_image_sheaf CategoryTheory.GrothendieckTopology.toImageSheaf\n\n/-- The inclusion of the image sheaf to the target. -/\n@[simps]\ndef imageSheafι {F F' : Sheaf J (Type w)} (f : F ⟶ F') : imageSheaf f ⟶ F' :=\n ⟨Subpresheaf.ι _⟩\n#align category_theory.grothendieck_topology.image_sheaf_ι CategoryTheory.GrothendieckTopology.imageSheafι\n\n@[simp, reassoc.1]\ntheorem toImageSheaf_ι {F F' : Sheaf J (Type w)} (f : F ⟶ F') :\n toImageSheaf f ≫ imageSheafι f = f := by\n ext1\n simp [to_image_presheaf_sheafify]\n#align category_theory.grothendieck_topology.to_image_sheaf_ι CategoryTheory.GrothendieckTopology.toImageSheaf_ι\n\ninstance {F F' : Sheaf J (Type w)} (f : F ⟶ F') : Mono (imageSheafι f) :=\n (sheafToPresheaf J _).mono_of_mono_map\n (by\n dsimp\n infer_instance)\n\ninstance {F F' : Sheaf J (Type w)} (f : F ⟶ F') : Epi (toImageSheaf f) :=\n by\n refine' ⟨fun G' g₁ g₂ e => _⟩\n ext (U⟨s, hx⟩)\n apply ((is_sheaf_iff_is_sheaf_of_type J _).mp G'.2 _ hx).IsSeparatedFor.ext\n rintro V i ⟨y, e'⟩\n change (g₁.val.app _ ≫ G'.val.map _) _ = (g₂.val.app _ ≫ G'.val.map _) _\n rw [← nat_trans.naturality, ← nat_trans.naturality]\n have E : (to_image_sheaf f).val.app (op V) y = (image_sheaf f).val.map i.op ⟨s, hx⟩ :=\n Subtype.ext e'\n have := congr_arg (fun f : F ⟶ G' => (Sheaf.hom.val f).app _ y) e\n dsimp at this⊢\n convert this <;> exact E.symm\n\n/-- The mono factorization given by `image_sheaf` for a morphism. -/\ndef imageMonoFactorization {F F' : Sheaf J (Type w)} (f : F ⟶ F') : Limits.MonoFactorisation f\n where\n i := imageSheaf f\n m := imageSheafι f\n e := toImageSheaf f\n#align category_theory.grothendieck_topology.image_mono_factorization CategoryTheory.GrothendieckTopology.imageMonoFactorization\n\n/-- The mono factorization given by `image_sheaf` for a morphism is an image. -/\nnoncomputable def imageFactorization {F F' : Sheaf J (Type max v u)} (f : F ⟶ F') :\n Limits.ImageFactorisation f where\n f := imageMonoFactorization f\n IsImage :=\n { lift := fun I =>\n by\n haveI := (Sheaf.hom.mono_iff_presheaf_mono J _ _).mp I.m_mono\n refine' ⟨subpresheaf.hom_of_le _ ≫ inv (to_image_presheaf I.m.1)⟩\n apply subpresheaf.sheafify_le\n · conv_lhs => rw [← I.fac]\n apply image_presheaf_comp_le\n · rw [← is_sheaf_iff_is_sheaf_of_type]\n exact F'.2\n · apply presieve.is_sheaf_iso J (as_iso <| to_image_presheaf I.m.1)\n rw [← is_sheaf_iff_is_sheaf_of_type]\n exact I.I.2\n lift_fac := fun I => by\n ext1\n dsimp [image_mono_factorization]\n generalize_proofs h\n rw [← subpresheaf.hom_of_le_ι h, category.assoc]\n congr 1\n rw [is_iso.inv_comp_eq, to_image_presheaf_ι] }\n#align category_theory.grothendieck_topology.image_factorization CategoryTheory.GrothendieckTopology.imageFactorization\n\ninstance : Limits.HasImages (Sheaf J (Type max v u)) :=\n ⟨fun _ _ f => ⟨⟨imageFactorization f⟩⟩⟩\n\nend Image\n\nend CategoryTheory.GrothendieckTopology\n\n", "meta": {"author": "leanprover-community", "repo": "mathlib3port", "sha": "62505aa236c58c8559783b16d33e30df3daa54f4", "save_path": "github-repos/lean/leanprover-community-mathlib3port", "path": "github-repos/lean/leanprover-community-mathlib3port/mathlib3port-62505aa236c58c8559783b16d33e30df3daa54f4/Mathbin/CategoryTheory/Sites/Subsheaf.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4687906266262438, "lm_q2_score": 0.07696083781311955, "lm_q1q2_score": 0.03607851938409303}} {"text": "import basic hp.core.source\n\n/-! System for assigning labels to things.\nLabels are chosen from hard-coded sets of letters.\nWhich set is used depends on the type of the thing being labelled.\nSo for example a group element should be labelled with `g`, `h` etc\nbut a point in a metric space should be labelled with `x`, `y` etc.\n\n[todo] Allow adding new suggested name lists with attributes.\n[todo] I think that a lot of non-humanproof tactics would benefit (in terms of user-friendliness) from\nusing this kind of labelling system. Perhaps there is some way it can be integrated with Lean.\n\n# Labelling pools\n\nA labelling pool is a dictionary `string ⇀ list string` sending a key string to a set of possible labels.\nA labeller is defined by three pools:\n- Class pool: sending names of classes `𝒞` to labels for types `α` that are instances of `𝒞`.\n For example a type `_ : Type` implementing `group _` should be labelled `G`.\n If a class has multiple arguments, the first argument is always bound to.\n- Element pool: Suppose we have `α : Type` and `[𝒞 α]` for some typeclass `𝒞`, then the element pool contains labels for the elements of `α`.\n For example, `{G : Type} [group G]` causes `_ : G` to be labelled `g` or `h`. While `[metric_space X]` will be labelled `x y : X`\n- Type pool: takes the function constant name of a type as the key and returns element names for that type.\n Eg terms of type `set α` will be labelled `A`, `B` etc.\n\n-/\nnamespace hp\n\nmeta def labeller.pool := listdict string string\n\n@[derive_setters]\nmeta structure labeller :=\n-- class pool\n(cp : labeller.pool)\n-- element pool\n(ep : labeller.pool)\n-- type pool\n(tp : labeller.pool)\n(in_play : table name)\n(counts : dictd string nat)\n\nnamespace labeller\n\nmeta instance : has_mem name labeller := ⟨λ n l, n ∈ l.in_play⟩\nmeta instance {n} {l : labeller} : decidable (n ∈ l) := by apply_instance\n\n/- [todo] user attribute that allows users to add their own -/\n\nmeta def default_labels := [\"x\", \"y\", \"z\", \"v\", \"w\", \"a\", \"b\", \"c\"]\n\nmeta def default_class_pool : pool :=\nlistdict.of [\n (\"category\", [\"C\", \"D\", \"E\"]),\n (\"group\", [\"G\", \"H\"]),\n -- (\"point\", [\"x\", \"y\", \"z\", \"v\", \"w\", \"a\", \"b\", \"c\"]),\n (\"has_mem\", [\"a\", \"b\", \"c\", \"x\", \"y\", \"z\", \"u\", \"v\", \"w\", \"p\", \"q\", \"r\", \"s\", \"t\"]),\n (\"metric_space\" , [\"X\", \"Y\", \"Z\"])\n]\n\nmeta def default_element_pool : pool :=\nlistdict.of [ (\"category\", [\"X\",\"Y\",\"Z\"])\n , (\"group\", [\"g\", \"h\", \"a\", \"b\", \"c\", \"x\", \"y\", \"z\"]) ]\n\n/-- pool for converting the head const of the type of an expression to its label -/\nmeta def default_type_pool : pool :=\nlistdict.of [ (\"\", [\"x\", \"y\", \"z\", \"a\", \"b\", \"c\"]) -- default\n , (\"→\", [\"f\", \"g\", \"h\"])\n , (\"sequence\" , [\"κ\", \"σ\", \"τ\"])\n , (\"set\", [\"A\", \"B\", \"C\", \"D\", \"E\", \"X\", \"Y\", \"Z\", \"U\", \"V\", \"W\", \"P\", \"Q\", \"R\", \"S\", \"T\"])\n , (\"fin\", [\"i\", \"j\", \"k\", \"r\", \"s\", \"t\"])\n , (\"nat\", [\"n\", \"m\", \"p\", \"q\", \"i\", \"j\", \"r\", \"t\"])\n , (\"hom\", [\"f\", \"g\", \"h\", \"k\", \"l\", \"q\", \"r\", \"s\", \"t\", \"u\", \"v\", \"w\"])\n -- , (\"real\", [\"x\", \"y\", \"z\"])\n , (\"real\", [\"ε\", \"δ\", \"η\", \"ζ\", \"θ\", \"α\", \"β\", \"γ\", \"ω\"])\n , (\"Type\", [\"α\", \"β\", \"γ\", \"δ\", \"ε\"])\n , (\"Prop\", [\"P\", \"Q\", \"R\"])\n]\n\nmeta instance : inhabited labeller :=\n⟨{ in_play := ∅\n, counts := dictd.empty (λ _, 0)\n, cp := default_class_pool\n, tp := default_type_pool\n, ep := default_element_pool\n}⟩\n\nmeta def to_subscript_digit : nat → string\n| 0 := \"₀\" | 1 := \"₁\" | 2 := \"₂\" | 3 := \"₃\" | 4 := \"₄\" | 5 := \"₅\" | 6 := \"₆\" | 7 := \"₇\" | 8 := \"₈\" | 9 := \"₉\"\n| n := \"♘\"\n\nmeta def to_digits_rev : nat → list nat\n| 0 := []\n| n := (n % 10) :: to_digits_rev (n / 10)\n\nmeta def to_subscript : nat → string\n| 0 := \"₀\"\n| n := string.join $ list.map to_subscript_digit $ list.reverse $ to_digits_rev $ n\n\n/- Here are the rules for looking up potential label names for a given expression (x : α).\n- if `α = f ..xs`, look up `f.last` in `type_pool`\n- if `α = Type`, look up \"Type\" in `type_pool`\n- if `α = Prop`, look up \"Prop\" in `type_pool`\n- if `α = expr.pi _ _ _ _`, look up \"→\" in `type_pool`,\n- if `[C α]` for some class `C`, look up `C` in `element_pool`.\n- if `[C x]` for some class `C`, look up `C` in `class_pool`.\n Also note that `[C x]` might not be in context yet, so might need to be clever with when labelling occurs.\n\n -/\n\nvariables {m : Type → Type} [monad m] [monad_state labeller m] [has_monad_lift tactic m] {α β : Type}\n\nmeta def get_fn_name : expr → string\n| (expr.app f _) := get_fn_name f\n| (expr.pi _ _ _ _) := \"→\"\n| (expr.sort level.zero) := \"Prop\"\n| (expr.sort _) := \"Type\"\n| (expr.const n _) := n.last\n| _ := \"none\"\n\nmeta def is_in_play : name → m bool | n:= do\n labs ← get,\n pure $ n ∈ in_play labs\n\nmeta def push_label : name → m unit | n := do\n modify $ labeller.modify_in_play $ insert n\n\nmeta def trace_label_state : m unit := do\n labs ← get,\n trace (to_string $ labs.in_play) (pure ()),\n pure ()\n\nmeta def select_label : list string → m name\n| [] := ⍐ $ tactic.fail \"need to select from at least one label\"\n| ss := do\n labs ← get,\n\n unused ← pure $ ss.find ((∉ labs) ∘ mk_simple_name),\n match unused with\n | (some h) := do\n n ← pure $ mk_simple_name h,\n push_label n,\n pure n\n | none := do\n ss ← pure $ ss.map (λ x, (x, labs.counts.get x)),\n some (base, i) ← pure $ ss.min_by (int.of_nat ∘ prod.snd),\n n ← pure $ mk_simple_name $ base ++ to_subscript i,\n modify $ labeller.modify_counts $ λ cs, cs.modify (+ 1) base,\n push_label n,\n pure n\n end\n\nmeta def label_intro (is_src : bool) : binder → cotelescope → m name\n| ⟨n,bi,y⟩ rest := do\n y ← ⍐ $ tactic.instantiate_mvars $ y,\n labs ← get,\n ip ← ⍐ $ tactic.is_prop y,\n if ip then do\n -- if it's a Prop, then make it an H or a T.\n base ← pure $ if is_src then \"H\" else \"T\",\n select_label [base]\n else if n ≠ name.anonymous ∧ n ∉ labs then do\n -- if the binder name is not anon and is not in the labeller\n -- then register it as a label and return it.\n push_label n,\n pure n\n else do\n -- instantiate the rest of the cotelescope with a local.\n rest ← pure $ assignable.instantiate_var rest $ expr.local_const n n bi y,\n\n cls ← pure $ rest.collect $ λ b,\n match b with\n | ⟨_, binder_info.inst_implicit, expr.app (expr.const f _) (expr.local_const un _ _ _)⟩ :=\n if un = n then labs.cp.get f.last else []\n | _ := []\n end,\n -- cs are the typeclasses that the type belongs to\n cs ← ⍐ $ tactic.get_classes y,\n\n els ← pure $ cs.collect $ λ c, labs.ep.get c.last,\n -- ⍐ $ tactic.trace $ get_fn_name y,\n tls ← pure $ labs.tp.get $ get_fn_name y,\n ns ← pure $ cls ++ els ++ tls,\n ns ← pure $ if ns.empty then default_labels else ns,\n -- ⍐ $ tactic.trace $ (\"selecting from names: \", ns),\n select_label ns\n\nmeta def label (p: pool) : expr → tactic (list string)\n| T := do\n cs ← tactic.get_classes T,\n ts : string ← pure $ match expr.app_fn T with\n | (expr.const f _) := f.head\n | (expr.pi _ _ _ _) := \"→\"\n | _ := \"none\"\n end,\n ls ← pure $ cs.collect $ λ c, p.get c.head,\n pure $ match ls with\n | [] := p.get \"\"\n | ls := ls\n end\n\n\n-- meta def get_fresh_label (ls : labeller) (type : string) (parent : name) : id (labeller × name) := do\n-- -- [todo] also check the local_context.\n-- if ¬(name.is_private parent ∨ parent = name.anonymous ∨ table.contains parent ls.in_play) then pure (ls, parent) else do\n-- base ← pure $ match parent with\n-- | name.anonymous := \"\"\n-- | name.mk_numeral i n := \"\"\n-- | name.mk_string s n := s\n-- end,\n-- pool ← pure $ ls.pools.get base,\n-- pool ← pure $ if pool.empty then ls.pools.get \"\" else pool,\n\n-- ls ← pure $ { labeller .\n-- in_play := ls.in_play.insert n,\n-- counts := ls.counts.modify (+ 1) base,\n-- ..ls\n-- },\n-- pure (ls, n)\n\nopen tactic.unsafe\n\nmeta def rename_meta : expr → m expr\n| m@(expr.mvar un pn _):= do\n -- ⍐ tactic.trace_state,\n y ← ⍐ $ tactic.infer_type m >>= tactic.instantiate_mvars,\n b ← pure $ binder.mk name.anonymous binder_info.default y,\n label ← label_intro ff b [],\n -- ⍐ $ tactic.trace (\"rename_meta\", un, y, label),\n -- [todo] check if pn is sensible or something like `_mvar_.....`\n ⍐ $ type_context.run $ do\n -- pure (ls, mvar)\n lctx ← type_context.get_context m,\n g ← type_context.mk_mvar label y lctx,\n type_context.assign m g,\n pure g\n| _ := ⍐ $ tactic.fail \"not an mvar\"\n\nmeta def type_to_label_type_key : expr → tactic string\n| e := pure $ expr.to_string e -- [todo]\n\n-- meta def rename_meta (ls : labeller) (mvar : expr) (parent : name := name.anonymous) : tactic (labeller × expr) := do\n-- y ← tactic.infer_type mvar,\n-- ip ← tactic.is_prop y,\n-- if ip then rename_meta_core ls \"target\" parent mvar else do\n-- type ← type_to_label_type_key y,\n-- rename_meta_core ls type parent mvar\n\n-- meta def get_fresh_binder_label (ls : labeller) : binder → tactic (labeller × binder)\n-- | ⟨n,bi,y⟩ := do\n-- ys ← type_to_label_type_key y,\n-- (ls, n) ← pure $ get_fresh_label ls ys n,\n-- pure (ls, ⟨n,bi,y⟩)\n\nmeta def label_cotelescope : cotelescope → m cotelescope\n| [] := pure []\n| (b :: rest) := do\n n ← label_intro tt b rest,\n -- ⍐ $ tactic.trace (\"relabel\", b, n),\n b ← pure $ {name := n, ..b},\n l ← ⍐ $ binder.mk_local b,\n rest ← pure $ @assignable.instantiate_var cotelescope (cotelescope.assignable) rest l,\n -- ⍐ $ tactic.trace (rest.reverse),\n rest ← label_cotelescope (rest),\n rest ← pure $ assignable.abstract_local rest l.local_uniq_name,\n -- ⍐ $ tactic.trace (rest.reverse),\n pure $ b :: rest\n\nmeta def label_telescope : telescope → m telescope :=\n(pure ∘ list.reverse) >=> label_cotelescope >=> (pure ∘ list.reverse)\n\nmeta def free_label (n : name) : m unit := do\n ls ← get,\n -- put $ ls.modify_in_play (dict.erase n),\n pure ()\n\nmeta def relabel_source : source → m source\n| src := do\n l ← label_intro tt ⟨src.label, binder_info.default, src.type⟩ [],\n pure {label := l, ..src}\n\n\nend labeller\n\nend hp", "meta": {"author": "EdAyers", "repo": "lean-humanproof-thesis", "sha": "ce8331df1883f286ab8cc7b61a328afdc006a059", "save_path": "github-repos/lean/EdAyers-lean-humanproof-thesis", "path": "github-repos/lean/EdAyers-lean-humanproof-thesis/lean-humanproof-thesis-ce8331df1883f286ab8cc7b61a328afdc006a059/src/hp/core/labeller.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4416730056646256, "lm_q2_score": 0.08151975541686203, "lm_q1q2_score": 0.0360050753960106}} {"text": "/-\nCopyright (c) 2018 Simon Hudon. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Simon Hudon\n\nGeneral utility functions for buffers.\n-/\nimport data.array.lemmas\nimport control.traversable.instances\n\nnamespace buffer\n\nopen function\n\nvariables {α : Type*} {xs : list α}\n\ninstance : inhabited (buffer α) := ⟨nil⟩\n\n@[ext]\nlemma ext : ∀ {b₁ b₂ : buffer α}, to_list b₁ = to_list b₂ → b₁ = b₂\n| ⟨n₁, a₁⟩ ⟨n₂, a₂⟩ h := begin\n simp [to_list, to_array] at h,\n have e : n₁ = n₂ :=\n by rw [←array.to_list_length a₁, ←array.to_list_length a₂, h],\n subst e,\n have h : a₁ == a₂.to_list.to_array := h ▸ a₁.to_list_to_array.symm,\n rw eq_of_heq (h.trans a₂.to_list_to_array)\nend\n\nlemma ext_iff {b₁ b₂ : buffer α} : b₁ = b₂ ↔ to_list b₁ = to_list b₂ :=\n⟨λ h, h ▸ rfl, ext⟩\n\nlemma size_eq_zero_iff {b : buffer α} : b.size = 0 ↔ b = nil :=\nbegin\n rcases b with ⟨_|n, ⟨a⟩⟩,\n { simp only [size, nil, mk_buffer, true_and, true_iff, eq_self_iff_true, heq_iff_eq,\n sigma.mk.inj_iff],\n ext i,\n exact fin.elim0 i },\n { simp [size, nil, mk_buffer, nat.succ_ne_zero] }\nend\n\n@[simp] lemma size_nil : (@nil α).size = 0 :=\nby rw size_eq_zero_iff\n\n@[simp] lemma to_list_nil : to_list (@nil α) = [] := rfl\n\ninstance (α) [decidable_eq α] : decidable_eq (buffer α) :=\nby tactic.mk_dec_eq_instance\n\n@[simp]\nlemma to_list_append_list {b : buffer α} :\n to_list (append_list b xs) = to_list b ++ xs :=\nby induction xs generalizing b; simp! [*]; cases b; simp! [to_list,to_array]\n\n@[simp]\nlemma append_list_mk_buffer :\n append_list mk_buffer xs = array.to_buffer (list.to_array xs) :=\nby ext x : 1; simp [array.to_buffer,to_list,to_list_append_list];\n induction xs; [refl,skip]; simp [to_array]; refl\n\n@[simp] lemma to_buffer_to_list (b : buffer α) : b.to_list.to_buffer = b :=\nbegin\n cases b,\n rw [to_list, to_array, list.to_buffer, append_list_mk_buffer],\n congr,\n { simpa },\n { apply array.to_list_to_array }\nend\n\n@[simp] lemma to_list_to_buffer (l : list α) : l.to_buffer.to_list = l :=\nbegin\n cases l,\n { refl },\n { rw [list.to_buffer, to_list_append_list],\n refl }\nend\n\n@[simp] lemma to_list_to_array (b : buffer α) : b.to_array.to_list = b.to_list :=\nby { cases b, simp [to_list] }\n\n@[simp] lemma append_list_nil (b : buffer α) : b.append_list [] = b := rfl\n\nlemma to_buffer_cons (c : α) (l : list α) :\n (c :: l).to_buffer = [c].to_buffer.append_list l :=\nbegin\n induction l with hd tl hl,\n { simp },\n { apply ext,\n simp [hl] }\nend\n\n@[simp] lemma size_push_back (b : buffer α) (a : α) : (b.push_back a).size = b.size + 1 :=\nby { cases b, simp [size, push_back] }\n\n@[simp] lemma size_append_list (b : buffer α) (l : list α) :\n (b.append_list l).size = b.size + l.length :=\nbegin\n induction l with hd tl hl generalizing b,\n { simp },\n { simp [append_list, hl, add_comm, add_assoc] }\nend\n\n@[simp] lemma size_to_buffer (l : list α) : l.to_buffer.size = l.length :=\nbegin\n induction l with hd tl hl,\n { simpa },\n { rw [to_buffer_cons],\n have : [hd].to_buffer.size = 1 := rfl,\n simp [add_comm, this] }\nend\n\n@[simp] lemma length_to_list (b : buffer α) : b.to_list.length = b.size :=\nby rw [←to_buffer_to_list b, to_list_to_buffer, size_to_buffer]\n\nlemma size_singleton (a : α) : [a].to_buffer.size = 1 := rfl\n\nlemma read_push_back_left (b : buffer α) (a : α) {i : ℕ} (h : i < b.size) :\n (b.push_back a).read ⟨i, by { convert nat.lt_succ_of_lt h, simp }⟩ = b.read ⟨i, h⟩ :=\nby { cases b, convert array.read_push_back_left _, simp }\n\n@[simp] lemma read_push_back_right (b : buffer α) (a : α) :\n (b.push_back a).read ⟨b.size, by simp⟩ = a :=\nby { cases b, convert array.read_push_back_right }\n\nlemma read_append_list_left' (b : buffer α) (l : list α) {i : ℕ}\n (h : i < (b.append_list l).size) (h' : i < b.size) :\n (b.append_list l).read ⟨i, h⟩ = b.read ⟨i, h'⟩ :=\nbegin\n induction l with hd tl hl generalizing b,\n { refl },\n { have hb : i < ((b.push_back hd).append_list tl).size := by convert h using 1,\n have hb' : i < (b.push_back hd).size := by { convert nat.lt_succ_of_lt h', simp },\n have : (append_list b (hd :: tl)).read ⟨i, h⟩ =\n read ((push_back b hd).append_list tl) ⟨i, hb⟩ := rfl,\n simp [this, hl _ hb hb', read_push_back_left _ _ h'] }\nend\n\nlemma read_append_list_left (b : buffer α) (l : list α) {i : ℕ} (h : i < b.size) :\n (b.append_list l).read ⟨i, by simpa using nat.lt_add_right _ _ _ h⟩ = b.read ⟨i, h⟩ :=\nread_append_list_left' b l _ h\n\n@[simp] lemma read_append_list_right (b : buffer α) (l : list α) {i : ℕ} (h : i < l.length) :\n (b.append_list l).read ⟨b.size + i, by simp [h]⟩ = l.nth_le i h :=\nbegin\n induction l with hd tl hl generalizing b i,\n { exact absurd i.zero_le (not_le_of_lt h) },\n { convert_to ((b.push_back hd).append_list tl).read _ = _,\n cases i,\n { convert read_append_list_left _ _ _;\n simp },\n { rw [list.length, nat.succ_lt_succ_iff] at h,\n have : b.size + i.succ = (b.push_back hd).size + i,\n { simp [add_comm, add_left_comm, nat.succ_eq_add_one] },\n convert hl (b.push_back hd) h using 1,\n simpa [nat.add_succ, nat.succ_add] } }\nend\n\nlemma read_to_buffer' (l : list α) {i : ℕ} (h : i < l.to_buffer.size) (h' : i < l.length) :\n l.to_buffer.read ⟨i, h⟩ = l.nth_le i h' :=\nbegin\n cases l with hd tl,\n { simpa using h' },\n { have hi : i < ([hd].to_buffer.append_list tl).size := by simpa [add_comm] using h,\n convert_to ([hd].to_buffer.append_list tl).read ⟨i, hi⟩ = _,\n cases i,\n { convert read_append_list_left _ _ _,\n simp },\n { rw list.nth_le,\n convert read_append_list_right _ _ _,\n simp [nat.succ_eq_add_one, add_comm] } }\nend\n\n@[simp] lemma read_to_buffer (l : list α) (i) :\n l.to_buffer.read i = l.nth_le i (by { convert i.property, simp }) :=\nby { convert read_to_buffer' _ _ _, { simp }, { simpa using i.property } }\n\nlemma nth_le_to_list' (b : buffer α) {i : ℕ} (h h') :\n b.to_list.nth_le i h = b.read ⟨i, h'⟩ :=\nbegin\n have : b.to_list.to_buffer.read ⟨i, (by simpa using h')⟩ = b.read ⟨i, h'⟩,\n { congr' 1; simp [fin.heq_ext_iff] },\n simp [←this]\nend\n\nlemma nth_le_to_list (b : buffer α) {i : ℕ} (h) :\n b.to_list.nth_le i h = b.read ⟨i, by simpa using h⟩ :=\nnth_le_to_list' _ _ _\n\nlemma read_eq_nth_le_to_list (b : buffer α) (i) :\n b.read i = b.to_list.nth_le i (by simp) :=\nby simp [nth_le_to_list]\n\nlemma read_singleton (c : α) : [c].to_buffer.read ⟨0, by simp⟩ = c :=\nby simp\n\n/-- The natural equivalence between lists and buffers, using\n`list.to_buffer` and `buffer.to_list`. -/\ndef list_equiv_buffer (α : Type*) : list α ≃ buffer α :=\nbegin\n refine { to_fun := list.to_buffer, inv_fun := buffer.to_list, .. };\n simp [left_inverse,function.right_inverse]\nend\n\ninstance : traversable buffer :=\nequiv.traversable list_equiv_buffer\n\ninstance : is_lawful_traversable buffer :=\nequiv.is_lawful_traversable list_equiv_buffer\n\n/--\nA convenience wrapper around `read` that just fails if the index is out of bounds.\n-/\nmeta def read_t (b : buffer α) (i : ℕ) : tactic α :=\nif h : i < b.size then return $ b.read (fin.mk i h)\nelse tactic.fail \"invalid buffer access\"\n\nend buffer\n", "meta": {"author": "leanprover-community", "repo": "mathlib", "sha": "5e526d18cea33550268dcbbddcb822d5cde40654", "save_path": "github-repos/lean/leanprover-community-mathlib", "path": "github-repos/lean/leanprover-community-mathlib/mathlib-5e526d18cea33550268dcbbddcb822d5cde40654/src/data/buffer/basic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4035668537353745, "lm_q2_score": 0.08882029420907209, "lm_q1q2_score": 0.03584492668180553}} {"text": "import tactic\n\n-- Если вы не работали с монадами и do-блоками раньше, почитайте туториал в интернете\n-- `tactic α` - функция, работающие в контексте состояния тактики и возвращает α\n-- `tactic unit` - ничего не возвращает (или же возвращает `()`)\n\nopen tactic\n\nmeta def make_nat : tactic ℕ := \nreturn 42\n\n-- Как использовать результат работы других тактик внутри do-блока?\n-- n ← make_nat\n\nmeta def trace_nat : tactic unit :=\ndo\n n ← make_nat,\n tactic.trace n\n\n-- Как дебагать тактики?\nexample : false :=\nbegin\n trace_nat,\n sorry,\nend\n\nrun_cmd trace_nat\n\n-- Как работать с окружением в тактике?\n-- Для первой цели есть функция tactic.target\n#check tactic.target\n\nmeta def show_goal : tactic unit :=\ndo\n t ← target,\n trace t\n -- trace $ expr.to_raw_fmt t покажет полную структуру, не pretty printed\n\nexample (a b : ℤ) : a^2 + b^2 ≥ 0 :=\nbegin\n show_goal,\n sorry,\nend\n\n-- Для локальных гипотез: функции get_local и local_context\n#check get_local\n#check tactic.local_context\n#check infer_type\n\nmeta def inspect_local_one (nm : name) : tactic unit :=\ndo\n a ← get_local nm,\n trace a,\n trace (expr.to_raw_fmt a),\n a_type ← infer_type a,\n trace a_type,\n trace (expr.to_raw_fmt a_type)\n\nexample (A : Type) (b c : A) (h : b = c) : false :=\nbegin\n inspect_local_one `A,\n inspect_local_one `h,\n sorry,\nend\n\n-- Для монадического программирования есть много (хоть и не так богато, как в Haskell) функций\n#check list.mmap\n\nmeta def inspect_all : tactic unit :=\ndo\n ctx ← local_context,\n trace ctx,\n ctx_types ← list.mmap (infer_type) ctx,\n trace ctx_types,\n ctx.mmap' (λ e, \n do \n e_type ← infer_type e, \n trace $ (to_string e) ++ \" : \" ++ (to_string e_type))\n\nexample (A : Type) (b c : A) (h : b = c) : false :=\nbegin\n inspect_all,\n sorry,\nend\n\n\n-- Наконец, реализуем версию тактики `assumption`\n\nmeta def assump_one (e : expr) : tactic unit :=\ndo\n tactic.exact e\n\n\nmeta def assump_list : list expr → tactic unit\n| [] := fail \"No assumption found!\"\n| (hd :: tl) := exact hd <|> assump_list tl\n\nmeta def assump : tactic unit := \ndo\n -- fail \"TODO: implement\" \n ctx ← local_context,\n assump_list ctx\n\n-- Тест\nexample {A B C : Prop} (ha : A) (hb : B) (hc : C) : B :=\nbegin\n assump,\n -- sorry,\nend\n\n-- Больше упражнений: https://github.com/leanprover-community/lftcm2020/blob/master/src/exercises_sources/monday/metaprogramming.lean", "meta": {"author": "VArtem", "repo": "lean-itmo", "sha": "dc44cd06f9f5b984d051831b3aaa7364e64c2dc4", "save_path": "github-repos/lean/VArtem-lean-itmo", "path": "github-repos/lean/VArtem-lean-itmo/lean-itmo-dc44cd06f9f5b984d051831b3aaa7364e64c2dc4/src/week07/solutions/e02_tactics.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40356685373537454, "lm_q2_score": 0.0888202936060873, "lm_q1q2_score": 0.03584492643846086}} {"text": "/-\nCopyright (c) 2017 Mario Carneiro. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Mario Carneiro, Jacob von Raumer\n-/\nimport Lean\n\n/-!\n\n# Recursive cases (`rcases`) tactic and related tactics\n\n`rcases` is a tactic that will perform `cases` recursively, according to a pattern. It is used to\ndestructure hypotheses or expressions composed of inductive types like `h1 : a ∧ b ∧ c ∨ d` or\n`h2 : ∃ x y, trans_rel R x y`. Usual usage might be `rcases h1 with ⟨ha, hb, hc⟩ | hd` or\n`rcases h2 with ⟨x, y, _ | ⟨z, hxz, hzy⟩⟩` for these examples.\n\nEach element of an `rcases` pattern is matched against a particular local hypothesis (most of which\nare generated during the execution of `rcases` and represent individual elements destructured from\nthe input expression). An `rcases` pattern has the following grammar:\n\n* A name like `x`, which names the active hypothesis as `x`.\n* A blank `_`, which does nothing (letting the automatic naming system used by `cases` name the\n hypothesis).\n* A hyphen `-`, which clears the active hypothesis and any dependents.\n* The keyword `rfl`, which expects the hypothesis to be `h : a = b`, and calls `subst` on the\n hypothesis (which has the effect of replacing `b` with `a` everywhere or vice versa).\n* A type ascription `p : ty`, which sets the type of the hypothesis to `ty` and then matches it\n against `p`. (Of course, `ty` must unify with the actual type of `h` for this to work.)\n* A tuple pattern `⟨p1, p2, p3⟩`, which matches a constructor with many arguments, or a series\n of nested conjunctions or existentials. For example if the active hypothesis is `a ∧ b ∧ c`,\n then the conjunction will be destructured, and `p1` will be matched against `a`, `p2` against `b`\n and so on.\n* An alternation pattern `p1 | p2 | p3`, which matches an inductive type with multiple constructors,\n or a nested disjunction like `a ∨ b ∨ c`.\n\nThe patterns are fairly liberal about the exact shape of the constructors, and will insert\nadditional alternation branches and tuple arguments if there are not enough arguments provided, and\nreuse the tail for further matches if there are too many arguments provided to alternation and\ntuple patterns.\n\nThis file also contains the `obtain` and `rintro` tactics, which use the same syntax of `rcases`\npatterns but with a slightly different use case:\n\n* `rintro` (or `rintros`) is used like `rintro x ⟨y, z⟩` and is the same as `intros` followed by\n `rcases` on the newly introduced arguments.\n* `obtain` is the same as `rcases` but with a syntax styled after `have` rather than `cases`.\n `obtain ⟨hx, hy⟩ | hz := foo` is equivalent to `rcases foo with ⟨hx, hy⟩ | hz`. Unlike `rcases`,\n `obtain` also allows one to omit `:= foo`, although a type must be provided in this case,\n as in `obtain ⟨hx, hy⟩ | hz : a ∧ b ∨ c`, in which case it produces a subgoal for proving\n `a ∧ b ∨ c` in addition to the subgoals `hx : a, hy : b |- goal` and `hz : c |- goal`.\n\n## Tags\n\nrcases, rintro, obtain, destructuring, cases, pattern matching, match\n-/\n\nnamespace Lean.Parser.Tactic\n\ndeclare_syntax_cat rcasesPat\nsyntax rcasesPatMed := sepBy1(rcasesPat, \" | \")\nsyntax rcasesPatLo := rcasesPatMed (\" : \" term)?\nsyntax (name := rcasesPat.one) ident : rcasesPat\nsyntax (name := rcasesPat.ignore) \"_\" : rcasesPat\nsyntax (name := rcasesPat.clear) \"-\" : rcasesPat\nsyntax (name := rcasesPat.tuple) \"⟨\" rcasesPatLo,* \"⟩\" : rcasesPat\nsyntax (name := rcasesPat.paren) \"(\" rcasesPatLo \")\" : rcasesPat\n\ndeclare_syntax_cat rintroPat\nsyntax (name := rintroPat.one) rcasesPat : rintroPat\nsyntax (name := rintroPat.binder) \"(\" rintroPat+ (\" : \" term)? \")\" : rintroPat\n\nend Lean.Parser.Tactic\n\n/- A list, with a disjunctive meaning (like a list of inductive constructors, or subgoals) -/\nlocal notation \"ListΣ\" => List\n\n/- A list, with a conjunctive meaning (like a list of constructor arguments, or hypotheses) -/\nlocal notation \"ListΠ\" => List\n\nnamespace Lean.Meta\n\n/-- Constructs a substitution consisting of `s` followed by `t`.\n This satisfies `(s.append t).apply e = t.apply (s.apply e)` -/\ndef FVarSubst.append (s t : FVarSubst) : FVarSubst :=\n s.1.foldl (fun s' k v => s'.insert k (t.apply v)) t\n\nnamespace RCases\n\n/--\nAn `rcases` pattern can be one of the following, in a nested combination:\n\n* A name like `foo`\n* The special keyword `rfl` (for pattern matching on equality using `subst`)\n* A hyphen `-`, which clears the active hypothesis and any dependents.\n* A type ascription like `pat : ty` (parentheses are optional)\n* A tuple constructor like `⟨p1, p2, p3⟩`\n* An alternation / variant pattern `p1 | p2 | p3`\n\nParentheses can be used for grouping; alternation is higher precedence than type ascription, so\n`p1 | p2 | p3 : ty` means `(p1 | p2 | p3) : ty`.\n\nN-ary alternations are treated as a group, so `p1 | p2 | p3` is not the same as `p1 | (p2 | p3)`,\nand similarly for tuples. However, note that an n-ary alternation or tuple can match an n-ary\nconjunction or disjunction, because if the number of patterns exceeds the number of constructors in\nthe type being destructed, the extra patterns will match on the last element, meaning that\n`p1 | p2 | p3` will act like `p1 | (p2 | p3)` when matching `a1 ∨ a2 ∨ a3`. If matching against a\ntype with 3 constructors, `p1 | (p2 | p3)` will act like `p1 | (p2 | p3) | _` instead.\n-/\ninductive RCasesPatt : Type\n| one : Syntax → Name → RCasesPatt\n| clear : Syntax → RCasesPatt\n| typed : Syntax → RCasesPatt → Syntax → RCasesPatt\n| tuple : Syntax → ListΠ RCasesPatt → RCasesPatt\n| alts : Syntax → ListΣ RCasesPatt → RCasesPatt\nderiving Repr\n\nnamespace RCasesPatt\n\ninstance : Inhabited RCasesPatt := ⟨RCasesPatt.one Syntax.missing `_⟩\n\n/-- Get the name from a pattern, if provided -/\npartial def name? : RCasesPatt → Option Name\n| one _ `_ => none\n| one _ `rfl => none\n| one _ n => n\n| typed _ p _ => p.name?\n| alts _ [p] => p.name?\n| _ => none\n\n/-- Get the syntax node from which this pattern was parsed. Used for error messages -/\ndef ref : RCasesPatt → Syntax\n| one ref _ => ref\n| clear ref => ref\n| typed ref _ _ => ref\n| tuple ref _ => ref\n| alts ref _ => ref\n\n/-- Interpret an rcases pattern as a tuple, where `p` becomes `⟨p⟩`\nif `p` is not already a tuple. -/\ndef asTuple : RCasesPatt → ListΠ RCasesPatt\n| tuple _ ps => ps\n| p => [p]\n\n/-- Interpret an rcases pattern as an alternation, where non-alternations are treated as one\nalternative. -/\ndef asAlts : RCasesPatt → ListΣ RCasesPatt\n| alts _ ps => ps\n| p => [p]\n\n/-- Convert a list of patterns to a tuple pattern, but mapping `[p]` to `p` instead of `⟨p⟩`. -/\ndef typed? (ref : Syntax) : RCasesPatt → Option Syntax → RCasesPatt\n| p, none => p\n| p, some ty => typed ref p ty\n\n/-- Convert a list of patterns to a tuple pattern, but mapping `[p]` to `p` instead of `⟨p⟩`. -/\ndef tuple' : ListΠ RCasesPatt → RCasesPatt\n| [p] => p\n| ps => tuple (ps.head?.map (·.ref) |>.getD Syntax.missing) ps\n\n/-- Convert a list of patterns to an alternation pattern, but mapping `[p]` to `p` instead of\na unary alternation `|p`. -/\ndef alts' (ref : Syntax) : ListΣ RCasesPatt → RCasesPatt\n| [p] => p\n| ps => alts ref ps\n\n/-- This function is used for producing rcases patterns based on a case tree. Suppose that we have\na list of patterns `ps` that will match correctly against the branches of the case tree for one\nconstructor. This function will merge tuples at the end of the list, so that `[a, b, ⟨c, d⟩]`\nbecomes `⟨a, b, c, d⟩` instead of `⟨a, b, ⟨c, d⟩⟩`.\n\nWe must be careful to turn `[a, ⟨⟩]` into `⟨a, ⟨⟩⟩` instead of `⟨a⟩` (which will not perform the\nnested match). -/\ndef tuple₁Core : ListΠ RCasesPatt → ListΠ RCasesPatt\n| [] => []\n| [tuple ref []] => [tuple ref []]\n| [tuple _ ps] => ps\n| p :: ps => p :: tuple₁Core ps\n\n/-- This function is used for producing rcases patterns based on a case tree. This is like\n`tuple₁Core` but it produces a pattern instead of a tuple pattern list, converting `[n]` to `n`\ninstead of `⟨n⟩` and `[]` to `_`, and otherwise just converting `[a, b, c]` to `⟨a, b, c⟩`. -/\ndef tuple₁ : ListΠ RCasesPatt → RCasesPatt\n| [] => default\n| [one ref n] => one ref n\n| ps => tuple ps.head!.ref $ tuple₁Core ps\n\n/-- This function is used for producing rcases patterns based on a case tree. Here we are given\nthe list of patterns to apply to each argument of each constructor after the main case, and must\nproduce a list of alternatives with the same effect. This function calls `tuple₁` to make the\nindividual alternatives, and handles merging `[a, b, c | d]` to `a | b | c | d` instead of\n`a | b | (c | d)`. -/\ndef alts₁Core : ListΣ (ListΠ RCasesPatt) → ListΣ RCasesPatt\n| [] => []\n| [[alts _ ps]] => ps\n| p :: ps => tuple₁ p :: alts₁Core ps\n\n/-- This function is used for producing rcases patterns based on a case tree. This is like\n`alts₁Core`, but it produces a cases pattern directly instead of a list of alternatives. We\nspecially translate the empty alternation to `⟨⟩`, and translate `|(a | b)` to `⟨a | b⟩` (because we\ndon't have any syntax for unary alternation). Otherwise we can use the regular merging of\nalternations at the last argument so that `a | b | (c | d)` becomes `a | b | c | d`. -/\ndef alts₁ (ref : Syntax) : ListΣ (ListΠ RCasesPatt) → RCasesPatt\n| [[]] => tuple Syntax.missing []\n| [[alts ref ps]] => tuple ref ps\n| ps => alts' ref $ alts₁Core ps\n\nopen MessageData in\npartial instance : ToMessageData RCasesPatt := ⟨fmt 0⟩ where\n parenAbove (tgt p : Nat) (m : MessageData) : MessageData :=\n if tgt < p then m.paren else m\n fmt : Nat → RCasesPatt → MessageData\n | _, one _ n => n\n | _, clear _ => \"-\"\n | p, typed _ pat ty => parenAbove 0 p m!\"{fmt 1 pat}: {ty}\"\n | _, tuple _ pats => bracket \"⟨\" (joinSep (pats.map (fmt 0)) (\",\" ++ Format.line)) \"⟩\"\n | p, alts _ pats => parenAbove 1 p (joinSep (pats.map (fmt 2)) \" | \")\n\nend RCasesPatt\n\n/-- Takes the number of fields of a single constructor and patterns to match its fields against\n(not necessarily the same number). The returned lists each contain one element per field of the\nconstructor. The `name` is the name which will be used in the top-level `cases` tactic, and the\n`rcases_patt` is the pattern which the field will be matched against by subsequent `cases`\ntactics. -/\ndef processConstructor (ref : Syntax) : Nat → ListΠ RCasesPatt → ListΠ Name × ListΠ RCasesPatt\n| 0, ps => ([], [])\n| 1, [] => ([`_], [default])\n| 1, [p] => ([p.name?.getD `_], [p])\n| 1, ps => ([`_], [RCasesPatt.tuple ref ps])\n| n + 1, p :: ps => let (ns, tl) := processConstructor ref n ps\n (p.name?.getD `_ :: ns, p :: tl)\n| _, _ => ([], [])\n\n/-- Takes a list of constructor names, and an (alternation) list of patterns, and matches each\npattern against its constructor. It returns the list of names that will be passed to `cases`,\nand the list of `(constructor name, patterns)` for each constructor, where `patterns` is the\n(conjunctive) list of patterns to apply to each constructor argument. -/\ndef processConstructors (ref : Syntax) (params : Nat) (altVarNames : Array AltVarNames := #[]) :\n ListΣ Name → ListΣ RCasesPatt → MetaM (Array AltVarNames × ListΣ (Name × ListΠ RCasesPatt))\n| [], ps => pure (altVarNames, [])\n| c :: cs, ps => do\n let n := FunInfo.getArity $ ← getFunInfo (← mkConstWithLevelParams c)\n let p := ps.headD default\n let t := ps.tailD []\n let (h, t) := match cs, t with\n | [], _ :: _ => ([RCasesPatt.alts ref ps], [])\n | _, _ => (p.asTuple, t)\n let (ns, ps) := processConstructor p.ref (n - params) h\n let (altVarNames, r) ← processConstructors ref params (altVarNames.push ⟨true, ns⟩) cs t\n pure (altVarNames, (c, ps) :: r)\n\nopen Elab Tactic\n\n-- this belongs in core; it is a variation on subst that passes fvarSubst through\ndef subst' (mvarId : MVarId) (hFVarId : FVarId)\n (fvarSubst : FVarSubst := {}) : MetaM (FVarSubst × MVarId) := do\n let hLocalDecl ← getLocalDecl hFVarId\n let error {α} _ : MetaM α := throwTacticEx `subst mvarId\n m!\"invalid equality proof, it is not of the form (x = t) or (t = x){indentExpr hLocalDecl.type}\"\n let some (α, lhs, rhs) ← matchEq? hLocalDecl.type | error ()\n let substReduced (newType : Expr) (symm : Bool) : MetaM (FVarSubst × MVarId) := do\n let mvarId ← assert mvarId hLocalDecl.userName newType (mkFVar hFVarId)\n let (hFVarId', mvarId) ← intro1P mvarId\n let mvarId ← clear mvarId hFVarId\n substCore mvarId hFVarId' (symm := symm) (tryToSkip := true) (fvarSubst := fvarSubst)\n let rhs' ← whnf rhs\n if rhs'.isFVar then\n if rhs != rhs' then\n substReduced (← mkEq lhs rhs') true\n else\n substCore mvarId hFVarId (symm := true) (tryToSkip := true) (fvarSubst := fvarSubst)\n else\n let lhs' ← whnf lhs\n if lhs'.isFVar then\n if lhs != lhs' then\n substReduced (← mkEq lhs' rhs) false\n else\n substCore mvarId hFVarId (symm := false) (tryToSkip := true) (fvarSubst := fvarSubst)\n else error ()\n\nmutual\n\n/-- This will match a pattern `pat` against a local hypothesis `e`.\n * `g`: The initial subgoal\n * `fs`: A running variable substitution, the result of `cases` operations upstream.\n The variable `e` must be run through this map before locating it in the context of `g`,\n and the output variable substitutions will be end extensions of this one.\n * `clears`: The list of variables to clear in all subgoals generated from this point on.\n We defer clear operations because clearing too early can cause `cases` to fail.\n The actual clearing happens in `RCases.finish`.\n * `e`: a local hypothesis, the scrutinee to match against.\n * `a`: opaque \"user data\" which is passed through all the goal calls at the end.\n * `pat`: the pattern to match against\n * `cont`: A continuation. This is called on every goal generated by the result of the pattern\n match, with updated values for `g` , `fs`, `clears`, and `a`. -/\npartial def rcasesCore (g : MVarId) (fs : FVarSubst) (clears : Array FVarId) (e : FVarId) (a : α)\n (pat : RCasesPatt) (cont : MVarId → FVarSubst → Array FVarId → α → TermElabM α) : TermElabM α :=\n let translate e : MetaM _ := do\n let e := fs.get e\n unless e.isFVar do\n throwError \"rcases tactic failed: {e} is not a fvar\"\n pure e\n withRef pat.ref <| withMVarContext g <| match pat with\n | RCasesPatt.one _ `rfl => do\n let (fs, g) ← subst' g (← translate e).fvarId! fs\n cont g fs clears a\n | RCasesPatt.one _ _ => cont g fs clears a\n | RCasesPatt.clear _ => cont g fs (clears.push e) a\n | RCasesPatt.typed _ pat ty => do\n let expected ← Term.elabType ty\n let e ← translate e\n let etype ← inferType e\n unless ← isDefEq etype expected do\n Term.throwTypeMismatchError \"rcases: scrutinee\" expected etype e\n let g ← replaceLocalDeclDefEq g e.fvarId! expected\n cont g fs clears a\n | RCasesPatt.alts _ [p] => rcasesCore g fs clears e a p cont\n | _ => do\n let e ← translate e\n let type ← whnfD (← inferType e)\n let failK {α} _ : TermElabM α :=\n throwError \"rcases tactic failed: {e} : {type} is not an inductive datatype\"\n let (r, subgoals) ← matchConst type.getAppFn failK fun\n | ConstantInfo.quotInfo info, _ => do\n unless info.kind matches QuotKind.type do failK ()\n let pat := pat.asAlts.headD default\n let ([x], ps) := processConstructor pat.ref 1 pat.asTuple | panic! \"rcases\"\n let (vars, g) ← Meta.revert g (← getFVarsToGeneralize #[e])\n withMVarContext g do\n let elimInfo ← getElimInfo `Quot.ind\n let res ← ElimApp.mkElimApp `Quot.ind elimInfo #[e] (← getMVarTag g)\n let elimArgs := res.elimApp.getAppArgs\n ElimApp.setMotiveArg g elimArgs[elimInfo.motivePos].mvarId! #[e.fvarId!]\n assignExprMVar g res.elimApp\n let #[(n, g)] := res.alts | panic! \"rcases\"\n let (v, g) ← intro g x\n let (varsOut, g) ← introNP g vars.size\n let fs' := (vars.zip varsOut).foldl (init := fs) fun fs (v, w) => fs.insert v (mkFVar w)\n pure ([(n, ps)], #[⟨⟨g, #[mkFVar v], fs'⟩, n⟩])\n | ConstantInfo.inductInfo info, _ => do\n let (altVarNames, r) ← processConstructors pat.ref info.numParams #[] info.ctors pat.asAlts\n (r, ·) <$> cases g e.fvarId! altVarNames\n | _, _ => failK ()\n (·.2) <$> subgoals.foldlM (init := (r, a)) fun (r, a) ⟨goal, ctorName⟩ => do\n let rec align\n | [] => pure ([], a)\n | (tgt, ps) :: as => do\n if tgt == ctorName then\n let fs := fs.append goal.subst\n (as, ·) <$> rcasesContinue goal.mvarId fs clears a (ps.zip goal.fields.toList) cont\n else\n align as\n align r\n\n/-- This will match a list of patterns against a list of hypotheses `e`. The arguments are similar\nto `rcasesCore`, but the patterns and local variables are in `pats`. Because the calls are all\nnested in continuations, later arguments can be matched many times, once per goal produced by\nearlier arguments. For example `⟨a | b, ⟨c, d⟩⟩` performs the `⟨c, d⟩` match twice, once on the\n`a` branch and once on `b`. -/\npartial def rcasesContinue (g : MVarId) (fs : FVarSubst) (clears : Array FVarId) (a : α)\n (pats : ListΠ (RCasesPatt × Expr)) (cont : MVarId → FVarSubst → Array FVarId → α → TermElabM α) :\n TermElabM α :=\n match pats with\n | [] => cont g fs clears a\n | ((pat, e) :: ps) => do\n unless e.isFVar do\n throwError \"rcases tactic failed: {e} is not a fvar\"\n rcasesCore g fs clears e.fvarId! a pat fun g fs clears a =>\n rcasesContinue g fs clears a ps cont\n\nend\n\n/-- Like `tryClearMany`, but also clears dependent hypotheses if possible -/\ndef tryClearMany' (mvarId : MVarId) (fvarIds : Array FVarId) : MetaM MVarId := do\n let mctx ← getMCtx\n let toErase := (← getMVarDecl mvarId).lctx.foldl (init := fvarIds) fun toErase localDecl =>\n if mctx.findLocalDeclDependsOn localDecl toErase.contains then\n toErase.push localDecl.fvarId\n else toErase\n tryClearMany mvarId toErase\n\n/-- The terminating continuation used in `rcasesCore` and `rcasesContinue`. We specialize the type\n`α` to `Array MVarId` to collect the list of goals, and given the list of `clears`, it attempts to\nclear them from the goal and adds the goal to the list. -/\ndef finish (g : MVarId) (fs : FVarSubst) (clears : Array FVarId)\n (gs : Array MVarId) : TermElabM (Array MVarId) := do\n let cs : Array Expr := (clears.map fs.get).filter Expr.isFVar\n gs.push <$> tryClearMany' g (cs.map Expr.fvarId!)\n\nopen Elab\n\n/-- Parses a `Syntax` into the `RCasesPatt` type used by the `RCases` tactic. -/\npartial def RCasesPatt.parse (stx : Syntax) : MetaM RCasesPatt :=\n match stx with\n | `(Lean.Parser.Tactic.rcasesPatMed| $ps:rcasesPat|*) => do\n pure $ RCasesPatt.alts' stx (← ps.getElems.toList.mapM parse)\n | `(Lean.Parser.Tactic.rcasesPatLo| $pat:rcasesPatMed : $t:term) => do\n pure $ RCasesPatt.typed stx (← parse pat) t\n | `(Lean.Parser.Tactic.rcasesPatLo| $pat:rcasesPatMed) => parse pat\n | `(rcasesPat| _) => pure $ RCasesPatt.one stx `_\n | `(rcasesPat| $h:ident) => pure $ RCasesPatt.one stx h.getId\n | `(rcasesPat| -) => pure $ RCasesPatt.clear stx\n | `(rcasesPat| ⟨$ps,*⟩) => do\n pure $ RCasesPatt.tuple stx (← ps.getElems.toList.mapM parse)\n | `(rcasesPat| ($pat)) => parse pat\n | _ => throwUnsupportedSyntax\n\n-- extracted from elabCasesTargets\ndef generalizeExceptFVar (mvarId : MVarId) (args : Array GeneralizeArg) : MetaM (Array Expr × MVarId) := do\n let argsToGeneralize := args.filter fun arg => !(arg.expr.isFVar && arg.hName?.isNone)\n let (fvarIdsNew, mvarId) ← generalize mvarId argsToGeneralize\n let mut result := #[]\n let mut j := 0\n for arg in args do\n if arg.expr.isFVar && arg.hName?.isNone then\n result := result.push arg.expr\n else\n result := result.push (mkFVar fvarIdsNew[j])\n j := j+1\n pure (result, mvarId)\n\n/-- Given a list of targets of the form `e` or `h : e`, and a pattern, match all the targets\nagainst the pattern. Returns the list of produced subgoals. -/\ndef rcases (tgts : Array (Option Name × Syntax))\n (pat : RCasesPatt) (g : MVarId) : TermElabM (List MVarId) := do\n let pats ← match tgts.size with\n | 0 => return [g]\n | 1 => pure [pat]\n | _ => pure (processConstructor pat.ref tgts.size pat.asTuple).2\n let (pats, args) := Array.unzip <|← (tgts.zip pats.toArray).mapM fun ((hName?, tgt), pat) => do\n let (pat, ty) ← match pat with\n | RCasesPatt.typed ref pat ty => pure (pat, some (← withRef ref <| Term.elabType ty))\n | _ => pure (pat, none)\n let expr ← Term.ensureHasType ty (← Term.elabTerm tgt ty)\n pure (pat, { expr, xName? := pat.name?, hName? : GeneralizeArg })\n let (vs, g) ← generalizeExceptFVar g args\n let gs ← rcasesContinue g {} #[] #[] (pats.zip vs).toList finish\n pure gs.toList\n\n/-- The `obtain` tactic in the no-target case. Given a type `T`, create a goal `|- T` and\nand pattern match `T` against the given pattern. Returns the list of goals, with the assumed goal\nfirst followed by the goals produced by the pattern match. -/\ndef obtainNone (pat : RCasesPatt) (ty : Syntax) (g : MVarId) : TermElabM (List MVarId) := do\n let ty ← Term.elabType ty\n let g₁ ← mkFreshExprMVar (some ty)\n let (v, g₂) ← intro1 (← assert g (pat.name?.getD default) ty g₁)\n let gs ← rcasesCore g₂ {} #[] v #[] pat finish\n pure (g₁.mvarId! :: gs.toList)\n\nmutual\n\npartial def rintroCore (g : MVarId) (fs : FVarSubst) (clears : Array FVarId) (a : α)\n (ref pat : Syntax) (ty? : Option Syntax)\n (cont : MVarId → FVarSubst → Array FVarId → α → TermElabM α) : TermElabM α := do\n match pat with\n | `(rintroPat| $pat:rcasesPat) =>\n let pat := (← RCasesPatt.parse pat).typed? ref ty?\n let (v, g) ← intro g (pat.name?.getD `_)\n rcasesCore g fs clears v a pat cont\n | `(rintroPat| ($(pats)* $[: $ty?]?)) =>\n rintroContinue g fs clears pat pats ty? a cont\n | _ => throwUnsupportedSyntax\n\npartial def rintroContinue (g : MVarId) (fs : FVarSubst) (clears : Array FVarId)\n (ref : Syntax) (pats : Array Syntax) (ty? : Option Syntax) (a : α)\n (cont : MVarId → FVarSubst → Array FVarId → α → TermElabM α) : TermElabM α := do\n withMVarContext g do\n let rec loop i g fs clears a := do\n if h : i < pats.size then\n rintroCore g fs clears a ref (pats.get ⟨i, h⟩) ty? (loop (i+1))\n else cont g fs clears a\n loop 0 g fs clears a\n\nend\n\ndef rintro (ref : Syntax) (pats : Array Syntax) (ty? : Option Syntax)\n (g : MVarId) : TermElabM (List MVarId) :=\n (·.toList) <$> rintroContinue g {} #[] ref pats ty? #[] finish\n\nend Lean.Meta.RCases\n\nnamespace Lean.Parser.Tactic\nopen Elab Elab.Tactic Meta RCases\n\nelab (name := rcases?) \"rcases?\" tgts:casesTarget,* num:(\" : \" num)? : tactic =>\n throwError \"unimplemented\"\n\nelab (name := rcases) tk:\"rcases\" tgts:casesTarget,* pat:(\" with \" rcasesPatLo)? : tactic => do\n let pat ← match pat.getArgs with\n | #[_, pat] => RCasesPatt.parse pat\n | #[] => pure $ RCasesPatt.tuple tk []\n | _ => throwUnsupportedSyntax\n let tgts := tgts.getElems.map fun tgt =>\n (if tgt[0].isNone then none else some tgt[0][0].getId, tgt[1])\n withMainContext do\n replaceMainGoal (← RCases.rcases tgts pat (← getMainGoal))\n\nelab (name := obtain) tk:\"obtain\"\n pat:(ppSpace rcasesPatMed)? ty:(\" : \" term)? val:(\" := \" term,+)? : tactic => do\n let pat ← liftM $ pat.getOptional?.mapM RCasesPatt.parse\n if val.isNone then\n if ty.isNone then throwError\n (\"`obtain` requires either an expected type or a value.\\n\" ++\n \"usage: `obtain ⟨patt⟩? : type (:= val)?` or `obtain ⟨patt⟩? (: type)? := val`\")\n let pat := pat.getD (RCasesPatt.one tk `this)\n withMainContext do\n replaceMainGoal (← RCases.obtainNone pat ty[1] (← getMainGoal))\n else\n let pat := pat.getD (RCasesPatt.one tk `_)\n let pat := pat.typed? tk $ if ty.isNone then none else some ty[1]\n let tgts := val[1].getSepArgs.map fun val => (none, val)\n withMainContext do\n replaceMainGoal (← RCases.rcases tgts pat (← getMainGoal))\n\nelab (name := rintro?) \"rintro?\" (\" : \" num)? : tactic =>\n throwError \"unimplemented\"\n\nelab (name := rintro) \"rintro\" pats:(ppSpace colGt rintroPat)+ ty:(\" : \" term)? : tactic => do\n let ty? := if ty.isNone then none else some ty[1]\n withMainContext do\n replaceMainGoal (← RCases.rintro ty pats.getArgs ty? (← getMainGoal))\n", "meta": {"author": "JOSHCLUNE", "repo": "Keller_reduction", "sha": "dc392b3da352fc1ffcfbecb1d4717d05f5faed4a", "save_path": "github-repos/lean/JOSHCLUNE-Keller_reduction", "path": "github-repos/lean/JOSHCLUNE-Keller_reduction/Keller_reduction-dc392b3da352fc1ffcfbecb1d4717d05f5faed4a/Lean4_Clique/Mathlib/Mathlib/Tactic/RCases.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.07159120142539067, "lm_q1q2_score": 0.03579560071269534}} {"text": "/-\nCopyright (c) 2022 Yakov Pechersky. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Yakov Pechersky\n\n! This file was ported from Lean 3 source module tactic.swap_var\n! leanprover-community/mathlib commit b3d0944867b430bb5557ba6391ca9c7749a16cbb\n! Please do not edit these lines, except to modify the commit id\n! if you have ported upstream changes.\n-/\nimport Mathbin.Tactic.Interactive\n\n/-!\n# Swap bound variable tactic\n\nThis files defines a tactic `swap_var` whose main purpose is to be a weaker\nversion of `wlog` that juggles bound names.\n\nIt is a helper around the core tactic `rename`.\n\n* `swap_var old new` renames all names named `old` to `new` and vice versa in the goal\n and all hypotheses.\n\n```lean\nexample (P Q : Prop) (hp : P) (hq : Q) : P ∧ Q :=\nbegin\n split,\n work_on_goal 1 { swap_var [P Q] },\n all_goals { exact ‹P› }\nend\n```\n\n# See also\n* `tactic.interactive.rename`\n* `tactic.interactive.rename_var`\n\n-/\n\n\nnamespace Tactic.Interactive\n\n/- ./././Mathport/Syntax/Translate/Tactic/Mathlib/Core.lean:38:34: unsupported: setup_tactic_parser -/\nprivate unsafe def swap_arg_parser : lean.parser (Name × Name) :=\n Prod.mk <$> ident <*> (optional (tk \"<->\" <|> tk \"↔\") *> ident)\n#align tactic.interactive.swap_arg_parser tactic.interactive.swap_arg_parser\n\nprivate unsafe def swap_args_parser : lean.parser (List (Name × Name)) :=\n Functor.map (fun x => [x]) swap_arg_parser <|> tk \"[\" *> sep_by (tk \",\") swap_arg_parser <* tk \"]\"\n#align tactic.interactive.swap_args_parser tactic.interactive.swap_args_parser\n\n/-- `swap_var [x y, P ↔ Q]` swaps the names `x` and `y`, `P` and `Q`.\nSuch a swapping can be used as a weak `wlog` if the tactic proofs use the same names.\n\n```lean\nexample (P Q : Prop) (hp : P) (hq : Q) : P ∧ Q :=\nbegin\n split,\n work_on_goal 1 { swap_var [P Q] },\n all_goals { exact ‹P› }\nend\n```\n-/\nunsafe def swap_var (renames : parse swap_args_parser) : tactic Unit := do\n renames fun e => do\n let n ← tactic.get_unused_name\n -- how to call `interactive.tactic.rename` here?\n propagate_tags <|\n tactic.rename_many <| native.rb_map.of_list [(e.1, n), (e.2, e.1)]\n propagate_tags <| tactic.rename_many <| native.rb_map.of_list [(n, e.2)]\n pure ()\n#align tactic.interactive.swap_var tactic.interactive.swap_var\n\nend Tactic.Interactive\n\nadd_tactic_doc\n { Name := \"swap_var\"\n category := DocCategory.tactic\n declNames := [`tactic.interactive.swap_var]\n tags := [\"renaming\"] }\n\n", "meta": {"author": "leanprover-community", "repo": "mathlib3port", "sha": "62505aa236c58c8559783b16d33e30df3daa54f4", "save_path": "github-repos/lean/leanprover-community-mathlib3port", "path": "github-repos/lean/leanprover-community-mathlib3port/mathlib3port-62505aa236c58c8559783b16d33e30df3daa54f4/Mathbin/Tactic/SwapVar.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.30735800417608683, "lm_q2_score": 0.1159607151988166, "lm_q1q2_score": 0.03564145398633989}} {"text": "/-\nCopyright (c) 2020 Scott Morrison. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Scott Morrison\n-/\nimport category_theory.monoidal.coherence\n\n/-!\n# Monoidal opposites\n\nWe write `Cᵐᵒᵖ` for the monoidal opposite of a monoidal category `C`.\n-/\n\n\nuniverses v₁ v₂ u₁ u₂\n\nvariables {C : Type u₁}\n\nnamespace category_theory\n\nopen category_theory.monoidal_category\n\n/-- A type synonym for the monoidal opposite. Use the notation `Cᴹᵒᵖ`. -/\n@[nolint has_nonempty_instance]\ndef monoidal_opposite (C : Type u₁) := C\n\nnamespace monoidal_opposite\n\nnotation C `ᴹᵒᵖ`:std.prec.max_plus := monoidal_opposite C\n\n/-- Think of an object of `C` as an object of `Cᴹᵒᵖ`. -/\n@[pp_nodot]\ndef mop (X : C) : Cᴹᵒᵖ := X\n\n/-- Think of an object of `Cᴹᵒᵖ` as an object of `C`. -/\n@[pp_nodot]\ndef unmop (X : Cᴹᵒᵖ) : C := X\n\nlemma op_injective : function.injective (mop : C → Cᴹᵒᵖ) := λ _ _, id\nlemma unop_injective : function.injective (unmop : Cᴹᵒᵖ → C) := λ _ _, id\n\n@[simp] lemma op_inj_iff (x y : C) : mop x = mop y ↔ x = y := iff.rfl\n@[simp] \n\nattribute [irreducible] monoidal_opposite\n\n@[simp] lemma mop_unmop (X : Cᴹᵒᵖ) : mop (unmop X) = X := rfl\n@[simp] lemma unmop_mop (X : C) : unmop (mop X) = X := rfl\n\ninstance monoidal_opposite_category [I : category.{v₁} C] : category Cᴹᵒᵖ :=\n{ hom := λ X Y, unmop X ⟶ unmop Y,\n id := λ X, 𝟙 (unmop X),\n comp := λ X Y Z f g, f ≫ g, }\n\nend monoidal_opposite\n\nend category_theory\n\nopen category_theory\nopen category_theory.monoidal_opposite\n\nvariables [category.{v₁} C]\n\n/-- The monoidal opposite of a morphism `f : X ⟶ Y` is just `f`, thought of as `mop X ⟶ mop Y`. -/\ndef quiver.hom.mop {X Y : C} (f : X ⟶ Y) : @quiver.hom Cᴹᵒᵖ _ (mop X) (mop Y) := f\n/-- We can think of a morphism `f : mop X ⟶ mop Y` as a morphism `X ⟶ Y`. -/\ndef quiver.hom.unmop {X Y : Cᴹᵒᵖ} (f : X ⟶ Y) : unmop X ⟶ unmop Y := f\n\nnamespace category_theory\n\nlemma mop_inj {X Y : C} :\n function.injective (quiver.hom.mop : (X ⟶ Y) → (mop X ⟶ mop Y)) :=\nλ _ _ H, congr_arg quiver.hom.unmop H\n\nlemma unmop_inj {X Y : Cᴹᵒᵖ} :\n function.injective (quiver.hom.unmop : (X ⟶ Y) → (unmop X ⟶ unmop Y)) :=\nλ _ _ H, congr_arg quiver.hom.mop H\n\n@[simp] lemma unmop_mop {X Y : C} {f : X ⟶ Y} : f.mop.unmop = f := rfl\n@[simp] lemma mop_unmop {X Y : Cᴹᵒᵖ} {f : X ⟶ Y} : f.unmop.mop = f := rfl\n\n@[simp] lemma mop_comp {X Y Z : C} {f : X ⟶ Y} {g : Y ⟶ Z} :\n (f ≫ g).mop = f.mop ≫ g.mop := rfl\n@[simp] lemma mop_id {X : C} : (𝟙 X).mop = 𝟙 (mop X) := rfl\n\n@[simp] lemma unmop_comp {X Y Z : Cᴹᵒᵖ} {f : X ⟶ Y} {g : Y ⟶ Z} :\n (f ≫ g).unmop = f.unmop ≫ g.unmop := rfl\n@[simp] lemma unmop_id {X : Cᴹᵒᵖ} : (𝟙 X).unmop = 𝟙 (unmop X) := rfl\n\n@[simp] lemma unmop_id_mop {X : C} : (𝟙 (mop X)).unmop = 𝟙 X := rfl\n@[simp] lemma mop_id_unmop {X : Cᴹᵒᵖ} : (𝟙 (unmop X)).mop = 𝟙 X := rfl\n\nnamespace iso\n\nvariables {X Y : C}\n\n/-- An isomorphism in `C` gives an isomorphism in `Cᴹᵒᵖ`. -/\n@[simps]\ndef mop (f : X ≅ Y) : mop X ≅ mop Y :=\n{ hom := f.hom.mop,\n inv := f.inv.mop,\n hom_inv_id' := unmop_inj f.hom_inv_id,\n inv_hom_id' := unmop_inj f.inv_hom_id }\n\nend iso\n\nvariables [monoidal_category.{v₁} C]\n\nopen opposite monoidal_category\n\ninstance monoidal_category_op : monoidal_category Cᵒᵖ :=\n{ tensor_obj := λ X Y, op (unop X ⊗ unop Y),\n tensor_hom := λ X₁ Y₁ X₂ Y₂ f g, (f.unop ⊗ g.unop).op,\n tensor_unit := op (𝟙_ C),\n associator := λ X Y Z, (α_ (unop X) (unop Y) (unop Z)).symm.op,\n left_unitor := λ X, (λ_ (unop X)).symm.op,\n right_unitor := λ X, (ρ_ (unop X)).symm.op,\n associator_naturality' := by { intros, apply quiver.hom.unop_inj, simp, },\n left_unitor_naturality' := by { intros, apply quiver.hom.unop_inj, simp, },\n right_unitor_naturality' := by { intros, apply quiver.hom.unop_inj, simp, },\n triangle' := by { intros, apply quiver.hom.unop_inj, coherence, },\n pentagon' := by { intros, apply quiver.hom.unop_inj, coherence, }, }\n\nlemma op_tensor_obj (X Y : Cᵒᵖ) : X ⊗ Y = op (unop X ⊗ unop Y) := rfl\nlemma op_tensor_unit : (𝟙_ Cᵒᵖ) = op (𝟙_ C) := rfl\n\ninstance monoidal_category_mop : monoidal_category Cᴹᵒᵖ :=\n{ tensor_obj := λ X Y, mop (unmop Y ⊗ unmop X),\n tensor_hom := λ X₁ Y₁ X₂ Y₂ f g, (g.unmop ⊗ f.unmop).mop,\n tensor_unit := mop (𝟙_ C),\n associator := λ X Y Z, (α_ (unmop Z) (unmop Y) (unmop X)).symm.mop,\n left_unitor := λ X, (ρ_ (unmop X)).mop,\n right_unitor := λ X, (λ_ (unmop X)).mop,\n associator_naturality' := by { intros, apply unmop_inj, simp, },\n left_unitor_naturality' := by { intros, apply unmop_inj, simp, },\n right_unitor_naturality' := by { intros, apply unmop_inj, simp, },\n triangle' := by { intros, apply unmop_inj, coherence, },\n pentagon' := by { intros, apply unmop_inj, coherence, }, }\n\nlemma mop_tensor_obj (X Y : Cᴹᵒᵖ) : X ⊗ Y = mop (unmop Y ⊗ unmop X) := rfl\nlemma mop_tensor_unit : (𝟙_ Cᴹᵒᵖ) = mop (𝟙_ C) := rfl\n\nend category_theory\n", "meta": {"author": "leanprover-community", "repo": "mathlib", "sha": "5e526d18cea33550268dcbbddcb822d5cde40654", "save_path": "github-repos/lean/leanprover-community-mathlib", "path": "github-repos/lean/leanprover-community-mathlib/mathlib-5e526d18cea33550268dcbbddcb822d5cde40654/src/category_theory/monoidal/opposite.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.476579651063676, "lm_q2_score": 0.07477003929997023, "lm_q1q2_score": 0.035633879239597155}} {"text": "/-\nCopyright (c) 2018 Mario Carneiro. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthor: Mario Carneiro\n\nA model of ZFC in Lean.\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.default\nimport Mathlib.data.set.basic\nimport Mathlib.PostPort\n\nuniverses u u_1 l u_2 u_3 v \n\nnamespace Mathlib\n\n/-- The type of `n`-ary functions `α → α → ... → α`. -/\ndef arity (α : Type u) : ℕ → Type u :=\n sorry\n\nnamespace arity\n\n\n/-- Constant `n`-ary function with value `a`. -/\ndef const {α : Type u} (a : α) (n : ℕ) : arity α n :=\n sorry\n\nprotected instance arity.inhabited {α : Type u_1} {n : ℕ} [Inhabited α] : Inhabited (arity α n) :=\n { default := const Inhabited.default n }\n\nend arity\n\n\n/-- The type of pre-sets in universe `u`. A pre-set\n is a family of pre-sets indexed by a type in `Type u`.\n The ZFC universe is defined as a quotient of this\n to ensure extensionality. -/\ninductive pSet \nwhere\n| mk : (α : Type u) → (α → pSet) → pSet\n\nnamespace pSet\n\n\n/-- The underlying type of a pre-set -/\ndef type : pSet → Type u :=\n sorry\n\n/-- The underlying pre-set family of a pre-set -/\ndef func (x : pSet) : type x → pSet :=\n sorry\n\ntheorem mk_type_func (x : pSet) : mk (type x) (func x) = x :=\n pSet.cases_on x\n fun (x_α : Type u_1) (x_A : x_α → pSet) =>\n idRhs (mk (type (mk x_α x_A)) (func (mk x_α x_A)) = mk (type (mk x_α x_A)) (func (mk x_α x_A))) rfl\n\n/-- Two pre-sets are extensionally equivalent if every\n element of the first family is extensionally equivalent to\n some element of the second family and vice-versa. -/\ndef equiv (x : pSet) (y : pSet) :=\n pSet.rec (fun (α : Type u_1) (z : α → pSet) (m : α → pSet → Prop) (_x : pSet) => sorry) x y\n\ntheorem equiv.refl (x : pSet) : equiv x x :=\n pSet.rec_on x\n fun (α : Type u_1) (A : α → pSet) (IH : ∀ (ᾰ : α), equiv (A ᾰ) (A ᾰ)) =>\n { left := fun (a : α) => Exists.intro a (IH a), right := fun (a : α) => Exists.intro a (IH a) }\n\ntheorem equiv.euc {x : pSet} {y : pSet} {z : pSet} : equiv x y → equiv z y → equiv x z := sorry\n\ntheorem equiv.symm {x : pSet} {y : pSet} : equiv x y → equiv y x :=\n equiv.euc (equiv.refl y)\n\ntheorem equiv.trans {x : pSet} {y : pSet} {z : pSet} (h1 : equiv x y) (h2 : equiv y z) : equiv x z :=\n equiv.euc h1 (equiv.symm h2)\n\nprotected instance setoid : setoid pSet :=\n setoid.mk equiv sorry\n\nprotected def subset : pSet → pSet → Prop :=\n sorry\n\nprotected instance has_subset : has_subset pSet :=\n has_subset.mk pSet.subset\n\ntheorem equiv.ext (x : pSet) (y : pSet) : equiv x y ↔ x ⊆ y ∧ y ⊆ x := sorry\n\ntheorem subset.congr_left {x : pSet} {y : pSet} {z : pSet} : equiv x y → (x ⊆ z ↔ y ⊆ z) := sorry\n\ntheorem subset.congr_right {x : pSet} {y : pSet} {z : pSet} : equiv x y → (z ⊆ x ↔ z ⊆ y) := sorry\n\n/-- `x ∈ y` as pre-sets if `x` is extensionally equivalent to a member\n of the family `y`. -/\ndef mem : pSet → pSet → Prop :=\n sorry\n\nprotected instance has_mem : has_mem pSet pSet :=\n has_mem.mk mem\n\ntheorem mem.mk {α : Type u} (A : α → pSet) (a : α) : A a ∈ mk α A :=\n (fun (this : mem (A a) (mk α A)) => this) (Exists.intro a (equiv.refl (A a)))\n\ntheorem mem.ext {x : pSet} {y : pSet} : (∀ (w : pSet), w ∈ x ↔ w ∈ y) → equiv x y := sorry\n\ntheorem mem.congr_right {x : pSet} {y : pSet} : equiv x y → ∀ {w : pSet}, w ∈ x ↔ w ∈ y := sorry\n\ntheorem equiv_iff_mem {x : pSet} {y : pSet} : equiv x y ↔ ∀ {w : pSet}, w ∈ x ↔ w ∈ y := sorry\n\ntheorem mem.congr_left {x : pSet} {y : pSet} : equiv x y → ∀ {w : pSet}, x ∈ w ↔ y ∈ w := sorry\n\n/-- Convert a pre-set to a `set` of pre-sets. -/\ndef to_set (u : pSet) : set pSet :=\n set_of fun (x : pSet) => x ∈ u\n\n/-- Two pre-sets are equivalent iff they have the same members. -/\ntheorem equiv.eq {x : pSet} {y : pSet} : equiv x y ↔ to_set x = to_set y :=\n iff.trans equiv_iff_mem (iff.symm set.ext_iff)\n\nprotected instance set.has_coe : has_coe pSet (set pSet) :=\n has_coe.mk to_set\n\n/-- The empty pre-set -/\nprotected def empty : pSet :=\n mk (ulift empty) fun (e : ulift empty) => sorry\n\nprotected instance has_emptyc : has_emptyc pSet :=\n has_emptyc.mk pSet.empty\n\nprotected instance inhabited : Inhabited pSet :=\n { default := ∅ }\n\ntheorem mem_empty (x : pSet) : ¬x ∈ ∅ := sorry\n\n/-- Insert an element into a pre-set -/\nprotected def insert : pSet → pSet → pSet :=\n sorry\n\nprotected instance has_insert : has_insert pSet pSet :=\n has_insert.mk pSet.insert\n\nprotected instance has_singleton : has_singleton pSet pSet :=\n has_singleton.mk fun (s : pSet) => insert s ∅\n\nprotected instance is_lawful_singleton : is_lawful_singleton pSet pSet :=\n is_lawful_singleton.mk fun (_x : pSet) => rfl\n\n/-- The n-th von Neumann ordinal -/\ndef of_nat : ℕ → pSet :=\n sorry\n\n/-- The von Neumann ordinal ω -/\ndef omega : pSet :=\n mk (ulift ℕ) fun (n : ulift ℕ) => of_nat (ulift.down n)\n\n/-- The separation operation `{x ∈ a | p x}` -/\nprotected def sep (p : set pSet) : pSet → pSet :=\n sorry\n\nprotected instance has_sep : has_sep pSet pSet :=\n has_sep.mk pSet.sep\n\n/-- The powerset operator -/\ndef powerset : pSet → pSet :=\n sorry\n\ntheorem mem_powerset {x : pSet} {y : pSet} : y ∈ powerset x ↔ y ⊆ x := sorry\n\n/-- The set union operator -/\ndef Union : pSet → pSet :=\n sorry\n\ntheorem mem_Union {x : pSet} {y : pSet} : y ∈ Union x ↔ ∃ (z : pSet), ∃ (_x : z ∈ x), y ∈ z := sorry\n\n/-- The image of a function -/\ndef image (f : pSet → pSet) : pSet → pSet :=\n sorry\n\ntheorem mem_image {f : pSet → pSet} (H : ∀ {x y : pSet}, equiv x y → equiv (f x) (f y)) {x : pSet} {y : pSet} : y ∈ image f x ↔ ∃ (z : pSet), ∃ (H : z ∈ x), equiv y (f z) := sorry\n\n/-- Universe lift operation -/\nprotected def lift : pSet → pSet :=\n sorry\n\n/-- Embedding of one universe in another -/\ndef embed : pSet :=\n mk (ulift pSet) fun (_x : ulift pSet) => sorry\n\ntheorem lift_mem_embed (x : pSet) : pSet.lift x ∈ embed :=\n Exists.intro (ulift.up x) (equiv.refl (pSet.lift x))\n\n/-- Function equivalence is defined so that `f ~ g` iff\n `∀ x y, x ~ y → f x ~ g y`. This extends to equivalence of n-ary\n functions. -/\ndef arity.equiv {n : ℕ} : arity pSet n → arity pSet n → Prop :=\n sorry\n\ntheorem arity.equiv_const {a : pSet} (n : ℕ) : arity.equiv (arity.const a n) (arity.const a n) := sorry\n\n/-- `resp n` is the collection of n-ary functions on `pSet` that respect\n equivalence, i.e. when the inputs are equivalent the output is as well. -/\ndef resp (n : ℕ) :=\n Subtype fun (x : arity pSet n) => arity.equiv x x\n\nprotected instance resp.inhabited {n : ℕ} : Inhabited (resp n) :=\n { default := { val := arity.const Inhabited.default n, property := sorry } }\n\ndef resp.f {n : ℕ} (f : resp (n + 1)) (x : pSet) : resp n :=\n { val := subtype.val f x, property := sorry }\n\ndef resp.equiv {n : ℕ} (a : resp n) (b : resp n) :=\n arity.equiv (subtype.val a) (subtype.val b)\n\ntheorem resp.refl {n : ℕ} (a : resp n) : resp.equiv a a :=\n subtype.property a\n\ntheorem resp.euc {n : ℕ} {a : resp n} {b : resp n} {c : resp n} : resp.equiv a b → resp.equiv c b → resp.equiv a c := sorry\n\nprotected instance resp.setoid {n : ℕ} : setoid (resp n) :=\n setoid.mk resp.equiv sorry\n\nend pSet\n\n\n/-- The ZFC universe of sets consists of the type of pre-sets,\n quotiented by extensional equivalence. -/\ndef Set :=\n quotient pSet.setoid\n\nnamespace pSet\n\n\nnamespace resp\n\n\ndef eval_aux {n : ℕ} : Subtype fun (f : resp n → arity Set n) => ∀ (a b : resp n), equiv a b → f a = f b :=\n sorry\n\n/-- An equivalence-respecting function yields an n-ary Set function. -/\ndef eval (n : ℕ) : resp n → arity Set n :=\n subtype.val eval_aux\n\ntheorem eval_val {n : ℕ} {f : resp (n + 1)} {x : pSet} : eval (n + 1) f (quotient.mk x) = eval n (f f x) :=\n rfl\n\nend resp\n\n\n/-- A set function is \"definable\" if it is the image of some n-ary pre-set\n function. This isn't exactly definability, but is useful as a sufficient\n condition for functions that have a computable image. -/\nclass inductive definable (n : ℕ) : arity Set n → Type (u + 1)\nwhere\n| mk : (f : resp n) → definable n (resp.eval n f)\n\ndef definable.eq_mk {n : ℕ} (f : resp n) {s : arity Set n} (H : resp.eval n f = s) : definable n s :=\n sorry\n\ndef definable.resp {n : ℕ} (s : arity Set n) [definable n s] : resp n :=\n sorry\n\ntheorem definable.eq {n : ℕ} (s : arity Set n) [H : definable n s] : resp.eval n (definable.resp s) = s := sorry\n\nend pSet\n\n\nnamespace classical\n\n\ndef all_definable {n : ℕ} (F : arity Set n) : pSet.definable n F :=\n sorry\n\nend classical\n\n\nnamespace Set\n\n\ndef mk : pSet → Set :=\n quotient.mk\n\n@[simp] theorem mk_eq (x : pSet) : quotient.mk x = mk x :=\n rfl\n\n@[simp] theorem eval_mk {n : ℕ} {f : pSet.resp (n + 1)} {x : pSet} : pSet.resp.eval (n + 1) f (mk x) = pSet.resp.eval n (pSet.resp.f f x) :=\n rfl\n\ndef mem : Set → Set → Prop :=\n quotient.lift₂ pSet.mem sorry\n\nprotected instance has_mem : has_mem Set Set :=\n has_mem.mk mem\n\n/-- Convert a ZFC set into a `set` of sets -/\ndef to_set (u : Set) : set Set :=\n set_of fun (x : Set) => x ∈ u\n\nprotected def subset (x : Set) (y : Set) :=\n ∀ {z : Set}, z ∈ x → z ∈ y\n\nprotected instance has_subset : has_subset Set :=\n has_subset.mk Set.subset\n\ntheorem subset_def {x : Set} {y : Set} : x ⊆ y ↔ ∀ {z : Set}, z ∈ x → z ∈ y :=\n iff.rfl\n\ntheorem subset_iff (x : pSet) (y : pSet) : mk x ⊆ mk y ↔ x ⊆ y := sorry\n\ntheorem ext {x : Set} {y : Set} : (∀ (z : Set), z ∈ x ↔ z ∈ y) → x = y :=\n quotient.induction_on₂ x y\n fun (u v : pSet) (h : ∀ (z : Set), z ∈ quotient.mk u ↔ z ∈ quotient.mk v) =>\n quotient.sound (pSet.mem.ext fun (w : pSet) => h (quotient.mk w))\n\ntheorem ext_iff {x : Set} {y : Set} : (∀ (z : Set), z ∈ x ↔ z ∈ y) ↔ x = y := sorry\n\n/-- The empty set -/\ndef empty : Set :=\n mk ∅\n\nprotected instance has_emptyc : has_emptyc Set :=\n has_emptyc.mk empty\n\nprotected instance inhabited : Inhabited Set :=\n { default := ∅ }\n\n@[simp] theorem mem_empty (x : Set) : ¬x ∈ ∅ :=\n quotient.induction_on x pSet.mem_empty\n\ntheorem eq_empty (x : Set) : x = ∅ ↔ ∀ (y : Set), ¬y ∈ x := sorry\n\n/-- `insert x y` is the set `{x} ∪ y` -/\nprotected def insert : Set → Set → Set :=\n pSet.resp.eval (bit0 1) { val := pSet.insert, property := sorry }\n\nprotected instance has_insert : has_insert Set Set :=\n has_insert.mk Set.insert\n\nprotected instance has_singleton : has_singleton Set Set :=\n has_singleton.mk fun (x : Set) => insert x ∅\n\nprotected instance is_lawful_singleton : is_lawful_singleton Set Set :=\n is_lawful_singleton.mk fun (x : Set) => rfl\n\n@[simp] theorem mem_insert {x : Set} {y : Set} {z : Set} : x ∈ insert y z ↔ x = y ∨ x ∈ z := sorry\n\n@[simp] theorem mem_singleton {x : Set} {y : Set} : x ∈ singleton y ↔ x = y :=\n iff.trans mem_insert\n { mp := fun (o : x = y ∨ x ∈ ∅) => Or._oldrec (fun (h : x = y) => h) (fun (n : x ∈ ∅) => absurd n (mem_empty x)) o,\n mpr := Or.inl }\n\n@[simp] theorem mem_pair {x : Set} {y : Set} {z : Set} : x ∈ insert y (singleton z) ↔ x = y ∨ x = z :=\n iff.trans mem_insert (or_congr iff.rfl mem_singleton)\n\n/-- `omega` is the first infinite von Neumann ordinal -/\ndef omega : Set :=\n mk pSet.omega\n\n@[simp] theorem omega_zero : ∅ ∈ omega :=\n (fun (this : pSet.mem ∅ pSet.omega) => this) (Exists.intro (ulift.up 0) (pSet.equiv.refl ∅))\n\n@[simp] theorem omega_succ {n : Set} : n ∈ omega → insert n n ∈ omega := sorry\n\n/-- `{x ∈ a | p x}` is the set of elements in `a` satisfying `p` -/\nprotected def sep (p : Set → Prop) : Set → Set :=\n pSet.resp.eval 1 { val := pSet.sep fun (y : pSet) => p (quotient.mk y), property := sorry }\n\nprotected instance has_sep : has_sep Set Set :=\n has_sep.mk Set.sep\n\n@[simp] theorem mem_sep {p : Set → Prop} {x : Set} {y : Set} : y ∈ has_sep.sep (fun (y : Set) => p y) x ↔ y ∈ x ∧ p y := sorry\n\n/-- The powerset operation, the collection of subsets of a set -/\ndef powerset : Set → Set :=\n pSet.resp.eval 1 { val := pSet.powerset, property := sorry }\n\n@[simp] theorem mem_powerset {x : Set} {y : Set} : y ∈ powerset x ↔ y ⊆ x := sorry\n\ntheorem Union_lem {α : Type u} {β : Type u} (A : α → pSet) (B : β → pSet) (αβ : ∀ (a : α), ∃ (b : β), pSet.equiv (A a) (B b)) (a : pSet.type (pSet.Union (pSet.mk α A))) : ∃ (b : pSet.type (pSet.Union (pSet.mk β B))),\n pSet.equiv (pSet.func (pSet.Union (pSet.mk α A)) a) (pSet.func (pSet.Union (pSet.mk β B)) b) := sorry\n\n/-- The union operator, the collection of elements of elements of a set -/\ndef Union : Set → Set :=\n pSet.resp.eval 1 { val := pSet.Union, property := sorry }\n\nnotation:1024 \"⋃\" => Mathlib.Set.Union\n\n@[simp] theorem mem_Union {x : Set} {y : Set} : y ∈ ⋃ ↔ ∃ (z : Set), ∃ (H : z ∈ x), y ∈ z := sorry\n\n@[simp] theorem Union_singleton {x : Set} : ⋃ = x := sorry\n\ntheorem singleton_inj {x : Set} {y : Set} (H : singleton x = singleton y) : x = y :=\n let this : ⋃ = ⋃ := congr_arg ⋃ H;\n eq.mp (Eq._oldrec (Eq.refl (x = ⋃)) Union_singleton) (eq.mp (Eq._oldrec (Eq.refl (⋃ = ⋃)) Union_singleton) this)\n\n/-- The binary union operation -/\nprotected def union (x : Set) (y : Set) : Set :=\n ⋃\n\n/-- The binary intersection operation -/\nprotected def inter (x : Set) (y : Set) : Set :=\n has_sep.sep (fun (z : Set) => z ∈ y) x\n\n/-- The set difference operation -/\nprotected def diff (x : Set) (y : Set) : Set :=\n has_sep.sep (fun (z : Set) => ¬z ∈ y) x\n\nprotected instance has_union : has_union Set :=\n has_union.mk Set.union\n\nprotected instance has_inter : has_inter Set :=\n has_inter.mk Set.inter\n\nprotected instance has_sdiff : has_sdiff Set :=\n has_sdiff.mk Set.diff\n\n@[simp] theorem mem_union {x : Set} {y : Set} {z : Set} : z ∈ x ∪ y ↔ z ∈ x ∨ z ∈ y := sorry\n\n@[simp] theorem mem_inter {x : Set} {y : Set} {z : Set} : z ∈ x ∩ y ↔ z ∈ x ∧ z ∈ y :=\n mem_sep\n\n@[simp] theorem mem_diff {x : Set} {y : Set} {z : Set} : z ∈ x \\ y ↔ z ∈ x ∧ ¬z ∈ y :=\n mem_sep\n\ntheorem induction_on {p : Set → Prop} (x : Set) (h : ∀ (x : Set), (∀ (y : Set), y ∈ x → p y) → p x) : p x := sorry\n\ntheorem regularity (x : Set) (h : x ≠ ∅) : ∃ (y : Set), ∃ (H : y ∈ x), x ∩ y = ∅ := sorry\n\n/-- The image of a (definable) set function -/\ndef image (f : Set → Set) [H : pSet.definable 1 f] : Set → Set :=\n let r : pSet.resp 1 := pSet.definable.resp f;\n pSet.resp.eval 1 { val := pSet.image (subtype.val r), property := sorry }\n\ntheorem image.mk (f : Set → Set) [H : pSet.definable 1 f] (x : Set) {y : Set} (h : y ∈ x) : f y ∈ image f x := sorry\n\n@[simp] theorem mem_image {f : Set → Set} [H : pSet.definable 1 f] {x : Set} {y : Set} : y ∈ image f x ↔ ∃ (z : Set), ∃ (H : z ∈ x), f z = y := sorry\n\n/-- Kuratowski ordered pair -/\ndef pair (x : Set) (y : Set) : Set :=\n insert (singleton x) (singleton (insert x (singleton y)))\n\n/-- A subset of pairs `{(a, b) ∈ x × y | p a b}` -/\ndef pair_sep (p : Set → Set → Prop) (x : Set) (y : Set) : Set :=\n has_sep.sep (fun (z : Set) => ∃ (a : Set), ∃ (H : a ∈ x), ∃ (b : Set), ∃ (H : b ∈ y), z = pair a b ∧ p a b)\n (powerset (powerset (x ∪ y)))\n\n@[simp] theorem mem_pair_sep {p : Set → Set → Prop} {x : Set} {y : Set} {z : Set} : z ∈ pair_sep p x y ↔ ∃ (a : Set), ∃ (H : a ∈ x), ∃ (b : Set), ∃ (H : b ∈ y), z = pair a b ∧ p a b := sorry\n\ntheorem pair_inj {x : Set} {y : Set} {x' : Set} {y' : Set} (H : pair x y = pair x' y') : x = x' ∧ y = y' := sorry\n\n/-- The cartesian product, `{(a, b) | a ∈ x, b ∈ y}` -/\ndef prod : Set → Set → Set :=\n pair_sep fun (a b : Set) => True\n\n@[simp] theorem mem_prod {x : Set} {y : Set} {z : Set} : z ∈ prod x y ↔ ∃ (a : Set), ∃ (H : a ∈ x), ∃ (b : Set), ∃ (H : b ∈ y), z = pair a b := sorry\n\n@[simp] theorem pair_mem_prod {x : Set} {y : Set} {a : Set} {b : Set} : pair a b ∈ prod x y ↔ a ∈ x ∧ b ∈ y := sorry\n\n/-- `is_func x y f` is the assertion `f : x → y` where `f` is a ZFC function\n (a set of ordered pairs) -/\ndef is_func (x : Set) (y : Set) (f : Set) :=\n f ⊆ prod x y ∧ ∀ (z : Set), z ∈ x → exists_unique fun (w : Set) => pair z w ∈ f\n\n/-- `funs x y` is `y ^ x`, the set of all set functions `x → y` -/\ndef funs (x : Set) (y : Set) : Set :=\n has_sep.sep (fun (f : Set) => is_func x y f) (powerset (prod x y))\n\n@[simp] theorem mem_funs {x : Set} {y : Set} {f : Set} : f ∈ funs x y ↔ is_func x y f := sorry\n\n-- TODO(Mario): Prove this computably\n\nprotected instance map_definable_aux (f : Set → Set) [H : pSet.definable 1 f] : pSet.definable 1 fun (y : Set) => pair y (f y) :=\n classical.all_definable fun (y : Set) => pair y (f y)\n\n/-- Graph of a function: `map f x` is the ZFC function which maps `a ∈ x` to `f a` -/\ndef map (f : Set → Set) [H : pSet.definable 1 f] : Set → Set :=\n image fun (y : Set) => pair y (f y)\n\n@[simp] theorem mem_map {f : Set → Set} [H : pSet.definable 1 f] {x : Set} {y : Set} : y ∈ map f x ↔ ∃ (z : Set), ∃ (H : z ∈ x), pair z (f z) = y :=\n mem_image\n\ntheorem map_unique {f : Set → Set} [H : pSet.definable 1 f] {x : Set} {z : Set} (zx : z ∈ x) : exists_unique fun (w : Set) => pair z w ∈ map f x := sorry\n\n@[simp] theorem map_is_func {f : Set → Set} [H : pSet.definable 1 f] {x : Set} {y : Set} : is_func x y (map f x) ↔ ∀ (z : Set), z ∈ x → f z ∈ y := sorry\n\nend Set\n\n\ndef Class :=\n set Set\n\nnamespace Class\n\n\nprotected instance has_subset : has_subset Class :=\n has_subset.mk set.subset\n\nprotected instance has_sep : has_sep Set Class :=\n has_sep.mk set.sep\n\nprotected instance has_emptyc : has_emptyc Class :=\n has_emptyc.mk fun (a : Set) => False\n\nprotected instance inhabited : Inhabited Class :=\n { default := ∅ }\n\nprotected instance has_insert : has_insert Set Class :=\n has_insert.mk set.insert\n\nprotected instance has_union : has_union Class :=\n has_union.mk set.union\n\nprotected instance has_inter : has_inter Class :=\n has_inter.mk set.inter\n\nprotected instance has_neg : Neg Class :=\n { neg := set.compl }\n\nprotected instance has_sdiff : has_sdiff Class :=\n has_sdiff.mk set.diff\n\n/-- Coerce a set into a class -/\ndef of_Set (x : Set) : Class :=\n set_of fun (y : Set) => y ∈ x\n\nprotected instance has_coe : has_coe Set Class :=\n has_coe.mk of_Set\n\n/-- The universal class -/\ndef univ : Class :=\n set.univ\n\n/-- Assert that `A` is a set satisfying `p` -/\ndef to_Set (p : Set → Prop) (A : Class) :=\n ∃ (x : Set), ↑x = A ∧ p x\n\n/-- `A ∈ B` if `A` is a set which is a member of `B` -/\nprotected def mem (A : Class) (B : Class) :=\n to_Set B A\n\nprotected instance has_mem : has_mem Class Class :=\n has_mem.mk Class.mem\n\ntheorem mem_univ {A : Class} : A ∈ univ ↔ ∃ (x : Set), ↑x = A :=\n exists_congr fun (x : Set) => and_true (↑x = A)\n\n/-- Convert a conglomerate (a collection of classes) into a class -/\ndef Cong_to_Class (x : set Class) : Class :=\n set_of fun (y : Set) => ↑y ∈ x\n\n/-- Convert a class into a conglomerate (a collection of classes) -/\ndef Class_to_Cong (x : Class) : set Class :=\n set_of fun (y : Class) => y ∈ x\n\n/-- The power class of a class is the class of all subclasses that are sets -/\ndef powerset (x : Class) : Class :=\n Cong_to_Class (𝒫 x)\n\n/-- The union of a class is the class of all members of sets in the class -/\ndef Union (x : Class) : Class :=\n ⋃₀Class_to_Cong x\n\nnotation:1024 \"⋃\" => Mathlib.Class.Union\n\ntheorem of_Set.inj {x : Set} {y : Set} (h : ↑x = ↑y) : x = y := sorry\n\n@[simp] theorem to_Set_of_Set (p : Set → Prop) (x : Set) : to_Set p ↑x ↔ p x := sorry\n\n@[simp] theorem mem_hom_left (x : Set) (A : Class) : ↑x ∈ A ↔ A x :=\n to_Set_of_Set (fun (x : Set) => A x) x\n\n@[simp] theorem mem_hom_right (x : Set) (y : Set) : coe y x ↔ x ∈ y :=\n iff.rfl\n\n@[simp] theorem subset_hom (x : Set) (y : Set) : ↑x ⊆ ↑y ↔ x ⊆ y :=\n iff.rfl\n\n@[simp] theorem sep_hom (p : Set → Prop) (x : Set) : ↑(has_sep.sep (fun (y : Set) => p y) x) = has_sep.sep (fun (y : Set) => p y) ↑x :=\n set.ext fun (y : Set) => Set.mem_sep\n\n@[simp] theorem empty_hom : ↑∅ = ∅ :=\n set.ext\n fun (y : Set) => (fun (this : y ∈ ↑∅ ↔ False) => this) (eq.mpr (id (propext (iff_false (y ∈ ↑∅)))) (Set.mem_empty y))\n\n@[simp] theorem insert_hom (x : Set) (y : Set) : insert x ↑y = ↑(insert x y) :=\n set.ext fun (z : Set) => iff.symm Set.mem_insert\n\n@[simp] theorem union_hom (x : Set) (y : Set) : ↑x ∪ ↑y = ↑(x ∪ y) :=\n set.ext fun (z : Set) => iff.symm Set.mem_union\n\n@[simp] theorem inter_hom (x : Set) (y : Set) : ↑x ∩ ↑y = ↑(x ∩ y) :=\n set.ext fun (z : Set) => iff.symm Set.mem_inter\n\n@[simp] theorem diff_hom (x : Set) (y : Set) : ↑x \\ ↑y = ↑(x \\ y) :=\n set.ext fun (z : Set) => iff.symm Set.mem_diff\n\n@[simp] theorem powerset_hom (x : Set) : powerset ↑x = ↑(Set.powerset x) :=\n set.ext fun (z : Set) => iff.symm Set.mem_powerset\n\n@[simp] theorem Union_hom (x : Set) : ⋃ = ↑⋃ := sorry\n\n/-- The definite description operator, which is {x} if `{a | p a} = {x}`\n and ∅ otherwise -/\ndef iota (p : Set → Prop) : Class :=\n ⋃\n\ntheorem iota_val (p : Set → Prop) (x : Set) (H : ∀ (y : Set), p y ↔ y = x) : iota p = ↑x := sorry\n\n/-- Unlike the other set constructors, the `iota` definite descriptor\n is a set for any set input, but not constructively so, so there is no\n associated `(Set → Prop) → Set` function. -/\ntheorem iota_ex (p : Set → Prop) : iota p ∈ univ := sorry\n\n/-- Function value -/\ndef fval (F : Class) (A : Class) : Class :=\n iota fun (y : Set) => to_Set (fun (x : Set) => F (Set.pair x y)) A\n\ninfixl:100 \"′\" => Mathlib.Class.fval\n\ntheorem fval_ex (F : Class) (A : Class) : F′A ∈ univ :=\n iota_ex fun (y : Set) => to_Set (fun (x : Set) => F (Set.pair x y)) A\n\nend Class\n\n\nnamespace Set\n\n\n@[simp] theorem map_fval {f : Set → Set} [H : pSet.definable 1 f] {x : Set} {y : Set} (h : y ∈ x) : ↑(map f x)′↑y = ↑(f y) := sorry\n\n/-- A choice function on the set of nonempty sets `x` -/\ndef choice (x : Set) : Set :=\n map (fun (y : Set) => classical.epsilon fun (z : Set) => z ∈ y) x\n\ntheorem choice_mem_aux (x : Set) (h : ¬∅ ∈ x) (y : Set) (yx : y ∈ x) : (classical.epsilon fun (z : Set) => z ∈ y) ∈ y := sorry\n\ntheorem choice_is_func (x : Set) (h : ¬∅ ∈ x) : is_func x ⋃ (choice x) := sorry\n\ntheorem choice_mem (x : Set) (h : ¬∅ ∈ x) (y : Set) (yx : y ∈ x) : ↑(choice x)′↑y ∈ ↑y := sorry\n\n", "meta": {"author": "AurelienSaue", "repo": "Mathlib4_auto", "sha": "590df64109b08190abe22358fabc3eae000943f2", "save_path": "github-repos/lean/AurelienSaue-Mathlib4_auto", "path": "github-repos/lean/AurelienSaue-Mathlib4_auto/Mathlib4_auto-590df64109b08190abe22358fabc3eae000943f2/Mathlib/set_theory/zfc.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879062662624377, "lm_q2_score": 0.07585817793199001, "lm_q1q2_score": 0.035561602767462695}} {"text": "/-\nCopyright (c) 2016 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Leonardo de Moura\n\nConverter monad for building simplifiers.\n\n! This file was ported from Lean 3 source module init.meta.converter.conv\n! leanprover-community/mathlib commit e83eca1fc5eda5ec3e0926a6913e02d9a574bf9e\n! Please do not edit these lines, except to modify the commit id\n! if you have ported upstream changes.\n-/\nprelude\nimport Leanbin.Init.Meta.Tactic\nimport Leanbin.Init.Meta.SimpTactic\nimport Leanbin.Init.Meta.Interactive\nimport Leanbin.Init.Meta.CongrLemma\nimport Leanbin.Init.Meta.MatchTactic\n\nopen Tactic\n\ndef Tactic.IdTag.conv : Unit :=\n ()\n#align tactic.id_tag.conv Tactic.IdTag.conv\n\nuniverse u\n\n/--\n`conv α` is a tactic for discharging goals of the form `lhs ~ rhs` for some relation `~` (usually equality) and fixed lhs, rhs.\nKnown in the literature as a __conversion__ tactic.\nSo for example, if one had the lemma `p : x = y`, then the conversion for `p` would be one that solves `p`.\n-/\nunsafe def conv (α : Type u) :=\n tactic α\n#align conv conv\n\nunsafe instance : Monad conv := by dsimp only [conv] <;> infer_instance\n\nunsafe instance : MonadFail conv := by dsimp only [conv] <;> infer_instance\n\nunsafe instance : Alternative conv := by dsimp only [conv] <;> infer_instance\n\nnamespace Conv\n\n/--\nApplies the conversion `c`. Returns `(rhs,p)` where `p : r lhs rhs`. Throws away the return value of `c`.-/\nunsafe def convert (c : conv Unit) (lhs : expr) (rel : Name := `eq) : tactic (expr × expr) := do\n let lhs_type ← infer_type lhs\n let rhs ← mk_meta_var lhs_type\n let new_target ← mk_app Rel [lhs, rhs]\n let new_g ← mk_meta_var new_target\n let gs ← get_goals\n set_goals [new_g]\n c\n try <| any_goals reflexivity\n let n ← num_goals\n when (n ≠ 0) (fail \"convert tactic failed, there are unsolved goals\")\n set_goals gs\n let rhs ← instantiate_mvars rhs\n let new_g ← instantiate_mvars new_g\n return (rhs, new_g)\n#align conv.convert conv.convert\n\nunsafe def lhs : conv expr := do\n let (_, lhs, rhs) ← target_lhs_rhs\n return lhs\n#align conv.lhs conv.lhs\n\nunsafe def rhs : conv expr := do\n let (_, lhs, rhs) ← target_lhs_rhs\n return rhs\n#align conv.rhs conv.rhs\n\n/-- `⊢ lhs = rhs` ~~> `⊢ lhs' = rhs` using `h : lhs = lhs'`. -/\nunsafe def update_lhs (new_lhs : expr) (h : expr) : conv Unit := do\n transitivity\n rhs >>= unify new_lhs\n exact h\n let t ← target >>= instantiate_mvars\n change t\n#align conv.update_lhs conv.update_lhs\n\n/-- Change `lhs` to something definitionally equal to it. -/\nunsafe def change (new_lhs : expr) : conv Unit := do\n let (r, lhs, rhs) ← target_lhs_rhs\n let new_target ← mk_app r [new_lhs, rhs]\n tactic.change new_target\n#align conv.change conv.change\n\n/-- Use reflexivity to prove. -/\nunsafe def skip : conv Unit :=\n reflexivity\n#align conv.skip conv.skip\n\n/-- Put LHS in WHNF. -/\nunsafe def whnf : conv Unit :=\n lhs >>= tactic.whnf >>= change\n#align conv.whnf conv.whnf\n\n/-- dsimp the LHS. -/\nunsafe def dsimp (s : Option simp_lemmas := none) (u : List Name := []) (cfg : DsimpConfig := { }) :\n conv Unit := do\n let s ←\n match s with\n | some s => return s\n | none => simp_lemmas.mk_default\n let l ← lhs\n s u l cfg >>= change\n#align conv.dsimp conv.dsimp\n\nprivate unsafe def congr_aux : List CongrArgKind → List expr → tactic (List expr × List expr)\n | [], [] => return ([], [])\n | k :: ks, a :: as => do\n let (gs, largs) ← congr_aux ks as\n match k with\n |-- parameter for the congruence lemma\n CongrArgKind.fixed =>\n return <| (gs, a :: largs)\n |-- parameter which is a subsingleton\n CongrArgKind.fixed_no_param =>\n return <| (gs, largs)\n | CongrArgKind.eq => do\n let a_type ← infer_type a\n let rhs ← mk_meta_var a_type\n let g_type ← mk_app `eq [a, rhs]\n let g ← mk_meta_var g_type\n -- proof that `a = rhs`\n return\n (g :: gs, a :: rhs :: g :: largs)\n | CongrArgKind.cast => return <| (gs, a :: largs)\n | _ => fail \"congr tactic failed, unsupported congruence lemma\"\n | ks, as => fail \"congr tactic failed, unsupported congruence lemma\"\n#align conv.congr_aux conv.congr_aux\n\n/--\nTake the target equality `f x y = X` and try to apply the congruence lemma for `f` to it (namely `x = x' → y = y' → f x y = f x' y'`). -/\nunsafe def congr : conv Unit := do\n let (r, lhs, rhs) ← target_lhs_rhs\n guard (r = `eq)\n let fn := lhs.get_app_fn\n let args := lhs.get_app_args\n let cgr_lemma ← mk_congr_lemma_simp fn (some args.length)\n let g :: gs ← get_goals\n let (new_gs, lemma_args) ← congr_aux cgr_lemma.arg_kinds args\n let g_val := cgr_lemma.proof.mk_app lemma_args\n unify g g_val\n set_goals <| new_gs ++ gs\n return ()\n#align conv.congr conv.congr\n\n/-- Create a conversion from the function extensionality tactic.-/\nunsafe def funext : conv Unit :=\n iterate' do\n let (r, lhs, rhs) ← target_lhs_rhs\n guard (r = `eq)\n let expr.lam n _ _ _ ← return lhs\n tactic.applyc `funext\n intro n\n return ()\n#align conv.funext conv.funext\n\nend Conv\n\n", "meta": {"author": "leanprover-community", "repo": "lean3port", "sha": "9ed1898f23e4379865ee93d62cb6353e5ed6c270", "save_path": "github-repos/lean/leanprover-community-lean3port", "path": "github-repos/lean/leanprover-community-lean3port/lean3port-9ed1898f23e4379865ee93d62cb6353e5ed6c270/Leanbin/Init/Meta/Converter/Conv.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4455295350395727, "lm_q2_score": 0.07921031813144958, "lm_q1q2_score": 0.03529053620744137}} {"text": "/-\nCopyright (c) 2016 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Leonardo de Moura\n-/\nprelude\nimport init.data.repr init.data.prod init.data.sum.basic\n\nuniverses u v\n\ninductive ordering\n| lt | eq | gt\n\ninstance : has_repr ordering :=\n⟨(λ s, match s with | ordering.lt := \"lt\" | ordering.eq := \"eq\" | ordering.gt := \"gt\" end)⟩\n\nnamespace ordering\ndef swap : ordering → ordering\n| lt := gt\n| eq := eq\n| gt := lt\n\n@[inline] def or_else : ordering → ordering → ordering\n| lt _ := lt\n| eq o := o\n| gt _ := gt\n\ntheorem swap_swap : ∀ (o : ordering), o.swap.swap = o\n| lt := rfl\n| eq := rfl\n| gt := rfl\nend ordering\n\ndef cmp_using {α : Type u} (lt : α → α → Prop) [decidable_rel lt] (a b : α) : ordering :=\nif lt a b then ordering.lt\nelse if lt b a then ordering.gt\nelse ordering.eq\n\ndef cmp {α : Type u} [has_lt α] [decidable_rel ((<) : α → α → Prop)] (a b : α) : ordering :=\ncmp_using (<) a b\n\ninstance : decidable_eq ordering :=\nλ a b,\n match a with\n | ordering.lt :=\n match b with\n | ordering.lt := is_true rfl\n | ordering.eq := is_false (λ h, ordering.no_confusion h)\n | ordering.gt := is_false (λ h, ordering.no_confusion h)\n end\n | ordering.eq :=\n match b with\n | ordering.lt := is_false (λ h, ordering.no_confusion h)\n | ordering.eq := is_true rfl\n | ordering.gt := is_false (λ h, ordering.no_confusion h)\n end\n | ordering.gt :=\n match b with\n | ordering.lt := is_false (λ h, ordering.no_confusion h)\n | ordering.eq := is_false (λ h, ordering.no_confusion h)\n | ordering.gt := is_true rfl\n end\n end\n", "meta": {"author": "subfish-zhou", "repo": "N2Lean", "sha": "8e858cc5b01f1ad921094dc355db3cb9473a42fd", "save_path": "github-repos/lean/subfish-zhou-N2Lean", "path": "github-repos/lean/subfish-zhou-N2Lean/N2Lean-8e858cc5b01f1ad921094dc355db3cb9473a42fd/library/init/data/ordering/basic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4493926344647597, "lm_q2_score": 0.07807816192710641, "lm_q1q2_score": 0.03508775088258845}} {"text": "/-\nCopyright (c) 2019 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Leonardo de Moura\n-/\nimport Lean.Meta.WHNF\nimport Lean.Meta.DiscrTreeTypes\n\nnamespace Lean.Meta.DiscrTree\n/-!\n (Imperfect) discrimination trees.\n We use a hybrid representation.\n - A `PersistentHashMap` for the root node which usually contains many children.\n - A sorted array of key/node pairs for inner nodes.\n\n The edges are labeled by keys:\n - Constant names (and arity). Universe levels are ignored.\n - Free variables (and arity). Thus, an entry in the discrimination tree\n may reference hypotheses from the local context.\n - Literals\n - Star/Wildcard. We use them to represent metavariables and terms\n we want to ignore. We ignore implicit arguments and proofs.\n - Other. We use to represent other kinds of terms (e.g., nested lambda, forall, sort, etc).\n\n We reduce terms using `TransparencyMode.reducible`. Thus, all reducible\n definitions in an expression `e` are unfolded before we insert it into the\n discrimination tree.\n\n Recall that projections from classes are **NOT** reducible.\n For example, the expressions `Add.add α (ringAdd ?α ?s) ?x ?x`\n and `Add.add Nat Nat.hasAdd a b` generates paths with the following keys\n respctively\n ```\n ⟨Add.add, 4⟩, *, *, *, *\n ⟨Add.add, 4⟩, *, *, ⟨a,0⟩, ⟨b,0⟩\n ```\n\n That is, we don't reduce `Add.add Nat inst a b` into `Nat.add a b`.\n We say the `Add.add` applications are the de-facto canonical forms in\n the metaprogramming framework.\n Moreover, it is the metaprogrammer's responsibility to re-pack applications such as\n `Nat.add a b` into `Add.add Nat inst a b`.\n\n Remark: we store the arity in the keys\n 1- To be able to implement the \"skip\" operation when retrieving \"candidate\"\n unifiers.\n 2- Distinguish partial applications `f a`, `f a b`, and `f a b c`.\n-/\n\ndef Key.ctorIdx : Key s → Nat\n | .star => 0\n | .other => 1\n | .lit .. => 2\n | .fvar .. => 3\n | .const .. => 4\n | .arrow => 5\n | .proj .. => 6\n\ndef Key.lt : Key s → Key s → Bool\n | .lit v₁, .lit v₂ => v₁ < v₂\n | .fvar n₁ a₁, .fvar n₂ a₂ => Name.quickLt n₁.name n₂.name || (n₁ == n₂ && a₁ < a₂)\n | .const n₁ a₁, .const n₂ a₂ => Name.quickLt n₁ n₂ || (n₁ == n₂ && a₁ < a₂)\n | .proj s₁ i₁ a₁, .proj s₂ i₂ a₂ => Name.quickLt s₁ s₂ || (s₁ == s₂ && i₁ < i₂) || (s₁ == s₂ && i₁ == i₂ && a₁ < a₂)\n | k₁, k₂ => k₁.ctorIdx < k₂.ctorIdx\n\ninstance : LT (Key s) := ⟨fun a b => Key.lt a b⟩\ninstance (a b : Key s) : Decidable (a < b) := inferInstanceAs (Decidable (Key.lt a b))\n\ndef Key.format : Key s → Format\n | .star => \"*\"\n | .other => \"◾\"\n | .lit (Literal.natVal v) => Std.format v\n | .lit (Literal.strVal v) => repr v\n | .const k _ => Std.format k\n | .proj s i _ => Std.format s ++ \".\" ++ Std.format i\n | .fvar k _ => Std.format k.name\n | .arrow => \"→\"\n\ninstance : ToFormat (Key s) := ⟨Key.format⟩\n\ndef Key.arity : (Key s) → Nat\n | .const _ a => a\n | .fvar _ a => a\n | .arrow => 2\n | .proj _ _ a => 1 + a\n | _ => 0\n\ninstance : Inhabited (Trie α s) := ⟨.node #[] #[]⟩\n\ndef empty : DiscrTree α s := { root := {} }\n\npartial def Trie.format [ToFormat α] : Trie α s → Format\n | .node vs cs => Format.group $ Format.paren $\n \"node\" ++ (if vs.isEmpty then Format.nil else \" \" ++ Std.format vs)\n ++ Format.join (cs.toList.map fun ⟨k, c⟩ => Format.line ++ Format.paren (Std.format k ++ \" => \" ++ format c))\n\ninstance [ToFormat α] : ToFormat (Trie α s) := ⟨Trie.format⟩\n\npartial def format [ToFormat α] (d : DiscrTree α s) : Format :=\n let (_, r) := d.root.foldl\n (fun (p : Bool × Format) k c =>\n (false, p.2 ++ (if p.1 then Format.nil else Format.line) ++ Format.paren (Std.format k ++ \" => \" ++ Std.format c)))\n (true, Format.nil)\n Format.group r\n\ninstance [ToFormat α] : ToFormat (DiscrTree α s) := ⟨format⟩\n\n/-- The discrimination tree ignores implicit arguments and proofs.\n We use the following auxiliary id as a \"mark\". -/\nprivate def tmpMVarId : MVarId := { name := `_discr_tree_tmp }\nprivate def tmpStar := mkMVar tmpMVarId\n\ninstance : Inhabited (DiscrTree α s) where\n default := {}\n\n/--\n Return true iff the argument should be treated as a \"wildcard\" by the discrimination tree.\n\n - We ignore proofs because of proof irrelevance. It doesn't make sense to try to\n index their structure.\n\n - We ignore instance implicit arguments (e.g., `[Add α]`) because they are \"morally\" canonical.\n Moreover, we may have many definitionally equal terms floating around.\n Example: `Ring.hasAdd Int Int.isRing` and `Int.hasAdd`.\n\n - We considered ignoring implicit arguments (e.g., `{α : Type}`) since users don't \"see\" them,\n and may not even understand why some simplification rule is not firing.\n However, in type class resolution, we have instance such as `Decidable (@Eq Nat x y)`,\n where `Nat` is an implicit argument. Thus, we would add the path\n ```\n Decidable -> Eq -> * -> * -> * -> [Nat.decEq]\n ```\n to the discrimination tree IF we ignored the implict `Nat` argument.\n This would be BAD since **ALL** decidable equality instances would be in the same path.\n So, we index implicit arguments if they are types.\n This setting seems sensible for simplification theorems such as:\n ```\n forall (x y : Unit), (@Eq Unit x y) = true\n ```\n If we ignore the implicit argument `Unit`, the `DiscrTree` will say it is a candidate\n simplification theorem for any equality in our goal.\n\n Remark: if users have problems with the solution above, we may provide a `noIndexing` annotation,\n and `ignoreArg` would return true for any term of the form `noIndexing t`.\n-/\nprivate def ignoreArg (a : Expr) (i : Nat) (infos : Array ParamInfo) : MetaM Bool := do\n if h : i < infos.size then\n let info := infos.get ⟨i, h⟩\n if info.isInstImplicit then\n return true\n else if info.isImplicit || info.isStrictImplicit then\n return not (← isType a)\n else\n isProof a\n else\n isProof a\n\nprivate partial def pushArgsAux (infos : Array ParamInfo) : Nat → Expr → Array Expr → MetaM (Array Expr)\n | i, .app f a, todo => do\n if (← ignoreArg a i infos) then\n pushArgsAux infos (i-1) f (todo.push tmpStar)\n else\n pushArgsAux infos (i-1) f (todo.push a)\n | _, _, todo => return todo\n\n/--\n Return true if `e` is one of the following\n - A nat literal (numeral)\n - `Nat.zero`\n - `Nat.succ x` where `isNumeral x`\n - `OfNat.ofNat _ x _` where `isNumeral x` -/\nprivate partial def isNumeral (e : Expr) : Bool :=\n if e.isNatLit then true\n else\n let f := e.getAppFn\n if !f.isConst then false\n else\n let fName := f.constName!\n if fName == ``Nat.succ && e.getAppNumArgs == 1 then isNumeral e.appArg!\n else if fName == ``OfNat.ofNat && e.getAppNumArgs == 3 then isNumeral (e.getArg! 1)\n else if fName == ``Nat.zero && e.getAppNumArgs == 0 then true\n else false\n\nprivate def isNatType (e : Expr) : MetaM Bool :=\n return (← whnf e).isConstOf ``Nat\n\n/--\n Return true if `e` is one of the following\n - `Nat.add _ k` where `isNumeral k`\n - `Add.add Nat _ _ k` where `isNumeral k`\n - `HAdd.hAdd _ Nat _ _ k` where `isNumeral k`\n - `Nat.succ _`\n This function assumes `e.isAppOf fName`\n-/\nprivate def isOffset (fName : Name) (e : Expr) : MetaM Bool := do\n if fName == ``Nat.add && e.getAppNumArgs == 2 then\n return isNumeral e.appArg!\n else if fName == ``Add.add && e.getAppNumArgs == 4 then\n if (← isNatType (e.getArg! 0)) then return isNumeral e.appArg! else return false\n else if fName == ``HAdd.hAdd && e.getAppNumArgs == 6 then\n if (← isNatType (e.getArg! 1)) then return isNumeral e.appArg! else return false\n else\n return fName == ``Nat.succ && e.getAppNumArgs == 1\n\n/--\n TODO: add hook for users adding their own functions for controlling `shouldAddAsStar`\n Different `DiscrTree` users may populate this set using, for example, attributes.\n\n Remark: we currently tag `Nat.zero` and \"offset\" terms to avoid having to add special\n support for `Expr.lit` and offset terms.\n Example, suppose the discrimination tree contains the entry\n `Nat.succ ?m |-> v`, and we are trying to retrieve the matches for `Expr.lit (Literal.natVal 1) _`.\n In this scenario, we want to retrieve `Nat.succ ?m |-> v` -/\nprivate def shouldAddAsStar (fName : Name) (e : Expr) : MetaM Bool := do\n if fName == ``Nat.zero then\n return true\n else\n isOffset fName e\n\ndef mkNoindexAnnotation (e : Expr) : Expr :=\n mkAnnotation `noindex e\n\ndef hasNoindexAnnotation (e : Expr) : Bool :=\n annotation? `noindex e |>.isSome\n\n/--\nReduction procedure for the discrimination tree indexing.\nThe parameter `simpleReduce` controls how aggressive the term is reduced.\nThe parameter at type `DiscrTree` controls this value.\nSee comment at `DiscrTree`.\n-/\npartial def reduce (e : Expr) (simpleReduce : Bool) : MetaM Expr := do\n let e ← whnfCore e (simpleReduceOnly := simpleReduce)\n match (← unfoldDefinition? e) with\n | some e => reduce e simpleReduce\n | none => match e.etaExpandedStrict? with\n | some e => reduce e simpleReduce\n | none => return e\n\n/--\n Return `true` if `fn` is a \"bad\" key. That is, `pushArgs` would add `Key.other` or `Key.star`.\n We use this function when processing \"root terms, and will avoid unfolding terms.\n Note that without this trick the pattern `List.map f ∘ List.map g` would be mapped into the key `Key.other`\n since the function composition `∘` would be unfolded and we would get `fun x => List.map g (List.map f x)`\n-/\nprivate def isBadKey (fn : Expr) : Bool :=\n match fn with\n | .lit .. => false\n | .const .. => false\n | .fvar .. => false\n | .proj .. => false\n | .forallE _ _ b _ => b.hasLooseBVars\n | _ => true\n\n/--\n Reduce `e` until we get an irreducible term (modulo current reducibility setting) or the resulting term\n is a bad key (see comment at `isBadKey`).\n We use this method instead of `reduce` for root terms at `pushArgs`. -/\nprivate partial def reduceUntilBadKey (e : Expr) (simpleReduce : Bool) : MetaM Expr := do\n let e ← step e\n match e.etaExpandedStrict? with\n | some e => reduceUntilBadKey e simpleReduce\n | none => return e\nwhere\n step (e : Expr) := do\n let e ← whnfCore e (simpleReduceOnly := simpleReduce)\n match (← unfoldDefinition? e) with\n | some e' => if isBadKey e'.getAppFn then return e else step e'\n | none => return e\n\n/-- whnf for the discrimination tree module -/\ndef reduceDT (e : Expr) (root : Bool) (simpleReduce : Bool) : MetaM Expr :=\n if root then reduceUntilBadKey e simpleReduce else reduce e simpleReduce\n\n/- Remark: we use `shouldAddAsStar` only for nested terms, and `root == false` for nested terms -/\n\nprivate def pushArgs (root : Bool) (todo : Array Expr) (e : Expr) : MetaM (Key s × Array Expr) := do\n if hasNoindexAnnotation e then\n return (.star, todo)\n else\n let e ← reduceDT e root (simpleReduce := s)\n let fn := e.getAppFn\n let push (k : Key s) (nargs : Nat) (todo : Array Expr): MetaM (Key s × Array Expr) := do\n let info ← getFunInfoNArgs fn nargs\n let todo ← pushArgsAux info.paramInfo (nargs-1) e todo\n return (k, todo)\n match fn with\n | .lit v => return (.lit v, todo)\n | .const c _ =>\n unless root do\n if (← shouldAddAsStar c e) then\n return (.star, todo)\n let nargs := e.getAppNumArgs\n push (.const c nargs) nargs todo\n | .proj s i a =>\n /-\n If `s` is a class, then `a` is an instance. Thus, we annotate `a` with `no_index` since we do not\n index instances. This should only happen if users mark a class projection function as `[reducible]`.\n\n TODO: add better support for projections that are functions\n -/\n let a := if isClass (← getEnv) s then mkNoindexAnnotation a else a\n let nargs := e.getAppNumArgs\n push (.proj s i nargs) nargs (todo.push a)\n | .fvar fvarId =>\n let nargs := e.getAppNumArgs\n push (.fvar fvarId nargs) nargs todo\n | .mvar mvarId =>\n if mvarId == tmpMVarId then\n -- We use `tmp to mark implicit arguments and proofs\n return (.star, todo)\n else if (← mvarId.isReadOnlyOrSyntheticOpaque) then\n return (.other, todo)\n else\n return (.star, todo)\n | .forallE _ d b _ =>\n if b.hasLooseBVars then\n return (.other, todo)\n else\n return (.arrow, todo.push d |>.push b)\n | _ =>\n return (.other, todo)\n\npartial def mkPathAux (root : Bool) (todo : Array Expr) (keys : Array (Key s)) : MetaM (Array (Key s)) := do\n if todo.isEmpty then\n return keys\n else\n let e := todo.back\n let todo := todo.pop\n let (k, todo) ← pushArgs root todo e\n mkPathAux false todo (keys.push k)\n\nprivate def initCapacity := 8\n\ndef mkPath (e : Expr) : MetaM (Array (Key s)) := do\n withReducible do\n let todo : Array Expr := .mkEmpty initCapacity\n let keys : Array (Key s) := .mkEmpty initCapacity\n mkPathAux (root := true) (todo.push e) keys\n\nprivate partial def createNodes (keys : Array (Key s)) (v : α) (i : Nat) : Trie α s :=\n if h : i < keys.size then\n let k := keys.get ⟨i, h⟩\n let c := createNodes keys v (i+1)\n .node #[] #[(k, c)]\n else\n .node #[v] #[]\n\nprivate def insertVal [BEq α] (vs : Array α) (v : α) : Array α :=\n if vs.contains v then vs else vs.push v\n\nprivate partial def insertAux [BEq α] (keys : Array (Key s)) (v : α) : Nat → Trie α s → Trie α s\n | i, .node vs cs =>\n if h : i < keys.size then\n let k := keys.get ⟨i, h⟩\n let c := Id.run $ cs.binInsertM\n (fun a b => a.1 < b.1)\n (fun ⟨_, s⟩ => let c := insertAux keys v (i+1) s; (k, c)) -- merge with existing\n (fun _ => let c := createNodes keys v (i+1); (k, c))\n (k, default)\n .node vs c\n else\n .node (insertVal vs v) cs\n\ndef insertCore [BEq α] (d : DiscrTree α s) (keys : Array (Key s)) (v : α) : DiscrTree α s :=\n if keys.isEmpty then panic! \"invalid key sequence\"\n else\n let k := keys[0]!\n match d.root.find? k with\n | none =>\n let c := createNodes keys v 1\n { root := d.root.insert k c }\n | some c =>\n let c := insertAux keys v 1 c\n { root := d.root.insert k c }\n\ndef insert [BEq α] (d : DiscrTree α s) (e : Expr) (v : α) : MetaM (DiscrTree α s) := do\n let keys ← mkPath e\n return d.insertCore keys v\n\nprivate def getKeyArgs (e : Expr) (isMatch root : Bool) : MetaM (Key s × Array Expr) := do\n let e ← reduceDT e root (simpleReduce := s)\n match e.getAppFn with\n | .lit v => return (.lit v, #[])\n | .const c _ =>\n if (← getConfig).isDefEqStuckEx && e.hasExprMVar then\n if (← isReducible c) then\n /- `e` is a term `c ...` s.t. `c` is reducible and `e` has metavariables, but it was not unfolded.\n This can happen if the metavariables in `e` are \"blocking\" smart unfolding.\n If `isDefEqStuckEx` is enabled, then we must throw the `isDefEqStuck` exception to postpone TC resolution.\n Here is an example. Suppose we have\n ```\n inductive Ty where\n | bool | fn (a ty : Ty)\n\n\n @[reducible] def Ty.interp : Ty → Type\n | bool => Bool\n | fn a b => a.interp → b.interp\n ```\n and we are trying to synthesize `BEq (Ty.interp ?m)`\n -/\n Meta.throwIsDefEqStuck\n else if let some matcherInfo := isMatcherAppCore? (← getEnv) e then\n -- A matcher application is stuck is one of the discriminants has a metavariable\n let args := e.getAppArgs\n for arg in args[matcherInfo.getFirstDiscrPos: matcherInfo.getFirstDiscrPos + matcherInfo.numDiscrs] do\n if arg.hasExprMVar then\n Meta.throwIsDefEqStuck\n else if (← isRec c) then\n /- Similar to the previous case, but for `match` and recursor applications. It may be stuck (i.e., did not reduce)\n because of metavariables. -/\n Meta.throwIsDefEqStuck\n let nargs := e.getAppNumArgs\n return (.const c nargs, e.getAppRevArgs)\n | .fvar fvarId =>\n let nargs := e.getAppNumArgs\n return (.fvar fvarId nargs, e.getAppRevArgs)\n | .mvar mvarId =>\n if isMatch then\n return (.other, #[])\n else do\n let ctx ← read\n if ctx.config.isDefEqStuckEx then\n /-\n When the configuration flag `isDefEqStuckEx` is set to true,\n we want `isDefEq` to throw an exception whenever it tries to assign\n a read-only metavariable.\n This feature is useful for type class resolution where\n we may want to notify the caller that the TC problem may be solveable\n later after it assigns `?m`.\n The method `DiscrTree.getUnify e` returns candidates `c` that may \"unify\" with `e`.\n That is, `isDefEq c e` may return true. Now, consider `DiscrTree.getUnify d (Add ?m)`\n where `?m` is a read-only metavariable, and the discrimination tree contains the keys\n `HadAdd Nat` and `Add Int`. If `isDefEqStuckEx` is set to true, we must treat `?m` as\n a regular metavariable here, otherwise we return the empty set of candidates.\n This is incorrect because it is equivalent to saying that there is no solution even if\n the caller assigns `?m` and try again. -/\n return (.star, #[])\n else if (← mvarId.isReadOnlyOrSyntheticOpaque) then\n return (.other, #[])\n else\n return (.star, #[])\n | .proj s i a .. =>\n let nargs := e.getAppNumArgs\n return (.proj s i nargs, #[a] ++ e.getAppRevArgs)\n | .forallE _ d b _ =>\n if b.hasLooseBVars then\n return (.other, #[])\n else\n return (.arrow, #[d, b])\n | _ =>\n return (.other, #[])\n\nprivate abbrev getMatchKeyArgs (e : Expr) (root : Bool) : MetaM (Key s × Array Expr) :=\n getKeyArgs e (isMatch := true) (root := root)\n\nprivate abbrev getUnifyKeyArgs (e : Expr) (root : Bool) : MetaM (Key s × Array Expr) :=\n getKeyArgs e (isMatch := false) (root := root)\n\nprivate def getStarResult (d : DiscrTree α s) : Array α :=\n let result : Array α := .mkEmpty initCapacity\n match d.root.find? .star with\n | none => result\n | some (.node vs _) => result ++ vs\n\nprivate abbrev findKey (cs : Array (Key s × Trie α s)) (k : Key s) : Option (Key s × Trie α s) :=\n cs.binSearch (k, default) (fun a b => a.1 < b.1)\n\nprivate partial def getMatchLoop (todo : Array Expr) (c : Trie α s) (result : Array α) : MetaM (Array α) := do\n match c with\n | .node vs cs =>\n if todo.isEmpty then\n return result ++ vs\n else if cs.isEmpty then\n return result\n else\n let e := todo.back\n let todo := todo.pop\n let first := cs[0]! /- Recall that `Key.star` is the minimal key -/\n let (k, args) ← getMatchKeyArgs e (root := false)\n /- We must always visit `Key.star` edges since they are wildcards.\n Thus, `todo` is not used linearly when there is `Key.star` edge\n and there is an edge for `k` and `k != Key.star`. -/\n let visitStar (result : Array α) : MetaM (Array α) :=\n if first.1 == .star then\n getMatchLoop todo first.2 result\n else\n return result\n let visitNonStar (k : Key s) (args : Array Expr) (result : Array α) : MetaM (Array α) :=\n match findKey cs k with\n | none => return result\n | some c => getMatchLoop (todo ++ args) c.2 result\n let result ← visitStar result\n match k with\n | .star => return result\n /-\n Note: dep-arrow vs arrow\n Recall that dependent arrows are `(Key.other, #[])`, and non-dependent arrows are `(Key.arrow, #[a, b])`.\n A non-dependent arrow may be an instance of a dependent arrow (stored at `DiscrTree`). Thus, we also visit the `Key.other` child.\n -/\n | .arrow => visitNonStar .other #[] (← visitNonStar k args result)\n | _ => visitNonStar k args result\n\nprivate def getMatchRoot (d : DiscrTree α s) (k : Key s) (args : Array Expr) (result : Array α) : MetaM (Array α) :=\n match d.root.find? k with\n | none => return result\n | some c => getMatchLoop args c result\n\nprivate def getMatchCore (d : DiscrTree α s) (e : Expr) : MetaM (Key s × Array α) :=\n withReducible do\n let result := getStarResult d\n let (k, args) ← getMatchKeyArgs e (root := true)\n match k with\n | .star => return (k, result)\n /- See note about \"dep-arrow vs arrow\" at `getMatchLoop` -/\n | .arrow => return (k, (← getMatchRoot d k args (← getMatchRoot d .other #[] result)))\n | _ => return (k, (← getMatchRoot d k args result))\n\n/--\n Find values that match `e` in `d`.\n-/\ndef getMatch (d : DiscrTree α s) (e : Expr) : MetaM (Array α) :=\n return (← getMatchCore d e).2\n\n/--\n Similar to `getMatch`, but returns solutions that are prefixes of `e`.\n We store the number of ignored arguments in the result.-/\npartial def getMatchWithExtra (d : DiscrTree α s) (e : Expr) : MetaM (Array (α × Nat)) := do\n let (k, result) ← getMatchCore d e\n let result := result.map (·, 0)\n if !e.isApp then\n return result\n else if !(← mayMatchPrefix k) then\n return result\n else\n go e.appFn! 1 result\nwhere\n mayMatchPrefix (k : Key s) : MetaM Bool :=\n let cont (k : Key s) : MetaM Bool :=\n if d.root.find? k |>.isSome then\n return true\n else\n mayMatchPrefix k\n match k with\n | .const f (n+1) => cont (.const f n)\n | .fvar f (n+1) => cont (.fvar f n)\n | .proj s i (n+1) => cont (.proj s i n)\n | _ => return false\n\n go (e : Expr) (numExtra : Nat) (result : Array (α × Nat)) : MetaM (Array (α × Nat)) := do\n let result := result ++ (← getMatch d e).map (., numExtra)\n if e.isApp then\n go e.appFn! (numExtra + 1) result\n else\n return result\n\npartial def getUnify (d : DiscrTree α s) (e : Expr) : MetaM (Array α) :=\n withReducible do\n let (k, args) ← getUnifyKeyArgs e (root := true)\n match k with\n | .star => d.root.foldlM (init := #[]) fun result k c => process k.arity #[] c result\n | _ =>\n let result := getStarResult d\n match d.root.find? k with\n | none => return result\n | some c => process 0 args c result\nwhere\n process (skip : Nat) (todo : Array Expr) (c : Trie α s) (result : Array α) : MetaM (Array α) := do\n match skip, c with\n | skip+1, .node _ cs =>\n if cs.isEmpty then\n return result\n else\n cs.foldlM (init := result) fun result ⟨k, c⟩ => process (skip + k.arity) todo c result\n | 0, .node vs cs => do\n if todo.isEmpty then\n return result ++ vs\n else if cs.isEmpty then\n return result\n else\n let e := todo.back\n let todo := todo.pop\n let (k, args) ← getUnifyKeyArgs e (root := false)\n let visitStar (result : Array α) : MetaM (Array α) :=\n let first := cs[0]!\n if first.1 == .star then\n process 0 todo first.2 result\n else\n return result\n let visitNonStar (k : Key s) (args : Array Expr) (result : Array α) : MetaM (Array α) :=\n match findKey cs k with\n | none => return result\n | some c => process 0 (todo ++ args) c.2 result\n match k with\n | .star => cs.foldlM (init := result) fun result ⟨k, c⟩ => process k.arity todo c result\n -- See comment a `getMatch` regarding non-dependent arrows vs dependent arrows\n | .arrow => visitNonStar .other #[] (← visitNonStar k args (← visitStar result))\n | _ => visitNonStar k args (← visitStar result)\n\nend Lean.Meta.DiscrTree\n", "meta": {"author": "leanprover", "repo": "lean4", "sha": "742d053a97bdd109a41a921facd1cd6a55e89bc7", "save_path": "github-repos/lean/leanprover-lean4", "path": "github-repos/lean/leanprover-lean4/lean4-742d053a97bdd109a41a921facd1cd6a55e89bc7/src/Lean/Meta/DiscrTree.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4687906414693485, "lm_q2_score": 0.0747700506393715, "lm_q1q2_score": 0.03505150000192664}} {"text": "/-\nCopyright (c) 2022 Andrew Yang. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Andrew Yang\n-/\nimport algebraic_geometry.morphisms.basic\nimport topology.spectral.hom\nimport algebraic_geometry.limits\n\n/-!\n# Quasi-compact morphisms\n\nA morphism of schemes is quasi-compact if the preimages of quasi-compact open sets are\nquasi-compact.\n\nIt suffices to check that preimages of affine open sets are compact\n(`quasi_compact_iff_forall_affine`).\n\n-/\n\nnoncomputable theory\n\nopen category_theory category_theory.limits opposite topological_space\n\nuniverse u\n\nopen_locale algebraic_geometry\n\nnamespace algebraic_geometry\n\nvariables {X Y : Scheme.{u}} (f : X ⟶ Y)\n\n/--\nA morphism is `quasi-compact` if the underlying map of topological spaces is, i.e. if the preimages\nof quasi-compact open sets are quasi-compact.\n-/\n@[mk_iff]\nclass quasi_compact (f : X ⟶ Y) : Prop :=\n(is_compact_preimage : ∀ U : set Y.carrier, is_open U → is_compact U → is_compact (f.1.base ⁻¹' U))\n\nlemma quasi_compact_iff_spectral : quasi_compact f ↔ is_spectral_map f.1.base :=\n⟨λ ⟨h⟩, ⟨by continuity, h⟩, λ h, ⟨h.2⟩⟩\n\n/-- The `affine_target_morphism_property` corresponding to `quasi_compact`, asserting that the\ndomain is a quasi-compact scheme. -/\ndef quasi_compact.affine_property : affine_target_morphism_property :=\nλ X Y f hf, compact_space X.carrier\n\n@[priority 900]\ninstance quasi_compact_of_is_iso {X Y : Scheme} (f : X ⟶ Y) [is_iso f] : quasi_compact f :=\nbegin\n constructor,\n intros U hU hU',\n convert hU'.image (inv f.1.base).continuous_to_fun using 1,\n rw set.image_eq_preimage_of_inverse,\n delta function.left_inverse,\n exacts [is_iso.inv_hom_id_apply f.1.base, is_iso.hom_inv_id_apply f.1.base]\nend\n\ninstance quasi_compact_comp {X Y Z : Scheme} (f : X ⟶ Y) (g : Y ⟶ Z)\n [quasi_compact f] [quasi_compact g] : quasi_compact (f ≫ g) :=\nbegin\n constructor,\n intros U hU hU',\n rw [Scheme.comp_val_base, coe_comp, set.preimage_comp],\n apply quasi_compact.is_compact_preimage,\n { exact continuous.is_open_preimage (by continuity) _ hU },\n apply quasi_compact.is_compact_preimage; assumption\nend\n\nlemma is_compact_open_iff_eq_finset_affine_union {X : Scheme} (U : set X.carrier) :\n is_compact U ∧ is_open U ↔\n ∃ (s : set X.affine_opens), s.finite ∧ U = ⋃ (i : X.affine_opens) (h : i ∈ s), i :=\nbegin\n apply opens.is_basis.is_compact_open_iff_eq_finite_Union\n (coe : X.affine_opens → opens X.carrier),\n { rw subtype.range_coe, exact is_basis_affine_open X },\n { exact λ i, i.2.is_compact }\nend\n\nlemma is_compact_open_iff_eq_basic_open_union {X : Scheme} [is_affine X] (U : set X.carrier) :\n is_compact U ∧ is_open U ↔\n ∃ (s : set (X.presheaf.obj (op ⊤))), s.finite ∧\n U = ⋃ (i : X.presheaf.obj (op ⊤)) (h : i ∈ s), X.basic_open i :=\n(is_basis_basic_open X).is_compact_open_iff_eq_finite_Union _\n (λ i, ((top_is_affine_open _).basic_open_is_affine _).is_compact) _\n\nlemma quasi_compact_iff_forall_affine : quasi_compact f ↔\n ∀ U : opens Y.carrier, is_affine_open U → is_compact (f.1.base ⁻¹' (U : set Y.carrier)) :=\nbegin\n rw quasi_compact_iff,\n refine ⟨λ H U hU, H U U.is_open hU.is_compact, _⟩,\n intros H U hU hU',\n obtain ⟨S, hS, rfl⟩ := (is_compact_open_iff_eq_finset_affine_union U).mp ⟨hU', hU⟩,\n simp only [set.preimage_Union, subtype.val_eq_coe],\n exact hS.is_compact_bUnion (λ i _, H i i.prop)\nend\n\n@[simp] lemma quasi_compact.affine_property_to_property {X Y : Scheme} (f : X ⟶ Y) :\n (quasi_compact.affine_property : _).to_property f ↔\n is_affine Y ∧ compact_space X.carrier :=\nby { delta affine_target_morphism_property.to_property quasi_compact.affine_property, simp }\n\nlemma quasi_compact_iff_affine_property :\n quasi_compact f ↔ target_affine_locally quasi_compact.affine_property f :=\nbegin\n rw quasi_compact_iff_forall_affine,\n transitivity (∀ U : Y.affine_opens, is_compact (f.1.base ⁻¹' (U : set Y.carrier))),\n { exact ⟨λ h U, h U U.prop, λ h U hU, h ⟨U, hU⟩⟩ },\n apply forall_congr,\n exact λ _, is_compact_iff_compact_space,\nend\n\nlemma quasi_compact_eq_affine_property :\n @quasi_compact = target_affine_locally quasi_compact.affine_property :=\nby { ext, exact quasi_compact_iff_affine_property _ }\n\nlemma is_compact_basic_open (X : Scheme) {U : opens X.carrier} (hU : is_compact (U : set X.carrier))\n (f : X.presheaf.obj (op U)) : is_compact (X.basic_open f : set X.carrier) :=\nbegin\n classical,\n refine ((is_compact_open_iff_eq_finset_affine_union _).mpr _).1,\n obtain ⟨s, hs, e⟩ := (is_compact_open_iff_eq_finset_affine_union _).mp ⟨hU, U.is_open⟩,\n let g : s → X.affine_opens,\n { intro V,\n use V.1 ⊓ X.basic_open f,\n have : V.1.1 ⟶ U,\n { apply hom_of_le, change _ ⊆ (U : set X.carrier), rw e,\n convert @set.subset_Union₂ _ _ _ (λ (U : X.affine_opens) (h : U ∈ s), ↑U) V V.prop using 1,\n refl },\n erw ← X.to_LocallyRingedSpace.to_RingedSpace.basic_open_res this.op,\n exact is_affine_open.basic_open_is_affine V.1.prop _ },\n haveI : finite s := hs.to_subtype,\n refine ⟨set.range g, set.finite_range g, _⟩,\n refine (set.inter_eq_right_iff_subset.mpr (set_like.coe_subset_coe.2 $\n RingedSpace.basic_open_le _ _)).symm.trans _,\n rw [e, set.Union₂_inter],\n apply le_antisymm; apply set.Union₂_subset,\n { intros i hi,\n refine set.subset.trans _ (set.subset_Union₂ _ (set.mem_range_self ⟨i, hi⟩)),\n exact set.subset.rfl },\n { rintro ⟨i, hi⟩ ⟨⟨j, hj⟩, hj'⟩,\n rw ← hj',\n refine set.subset.trans _ (set.subset_Union₂ j hj),\n exact set.subset.rfl }\nend\n\nlemma quasi_compact.affine_property_is_local :\n (quasi_compact.affine_property : _).is_local :=\nbegin\n split,\n { apply affine_target_morphism_property.respects_iso_mk; rintros X Y Z _ _ _ H,\n exacts [@@homeomorph.compact_space _ _ H (Top.homeo_of_iso (as_iso e.inv.1.base)), H] },\n { introv H,\n delta quasi_compact.affine_property at H ⊢,\n change compact_space ((opens.map f.val.base).obj (Y.basic_open r)),\n rw Scheme.preimage_basic_open f r,\n erw ← is_compact_iff_compact_space,\n rw ← is_compact_univ_iff at H,\n exact is_compact_basic_open X H _ },\n { rintros X Y H f S hS hS',\n resetI,\n rw ← is_affine_open.basic_open_union_eq_self_iff at hS,\n delta quasi_compact.affine_property,\n rw ← is_compact_univ_iff,\n change is_compact ((opens.map f.val.base).obj ⊤).1,\n rw ← hS,\n dsimp [opens.map],\n simp only [opens.coe_supr, set.preimage_Union, subtype.val_eq_coe],\n exacts [is_compact_Union (λ i, is_compact_iff_compact_space.mpr (hS' i)),\n top_is_affine_open _] }\nend\n\nlemma quasi_compact.affine_open_cover_tfae {X Y : Scheme.{u}} (f : X ⟶ Y) :\n tfae [quasi_compact f,\n ∃ (𝒰 : Scheme.open_cover.{u} Y) [∀ i, is_affine (𝒰.obj i)],\n ∀ (i : 𝒰.J), compact_space (pullback f (𝒰.map i)).carrier,\n ∀ (𝒰 : Scheme.open_cover.{u} Y) [∀ i, is_affine (𝒰.obj i)] (i : 𝒰.J),\n compact_space (pullback f (𝒰.map i)).carrier,\n ∀ {U : Scheme} (g : U ⟶ Y) [is_affine U] [is_open_immersion g],\n compact_space (pullback f g).carrier,\n ∃ {ι : Type u} (U : ι → opens Y.carrier) (hU : supr U = ⊤) (hU' : ∀ i, is_affine_open (U i)),\n ∀ i, compact_space (f.1.base ⁻¹' (U i).1)] :=\nquasi_compact_eq_affine_property.symm ▸\n quasi_compact.affine_property_is_local.affine_open_cover_tfae f\n\nlemma quasi_compact.is_local_at_target :\n property_is_local_at_target @quasi_compact :=\nquasi_compact_eq_affine_property.symm ▸\n quasi_compact.affine_property_is_local.target_affine_locally_is_local\n\nlemma quasi_compact.open_cover_tfae {X Y : Scheme.{u}} (f : X ⟶ Y) :\n tfae [quasi_compact f,\n ∃ (𝒰 : Scheme.open_cover.{u} Y), ∀ (i : 𝒰.J),\n quasi_compact (pullback.snd : (𝒰.pullback_cover f).obj i ⟶ 𝒰.obj i),\n ∀ (𝒰 : Scheme.open_cover.{u} Y) (i : 𝒰.J),\n quasi_compact (pullback.snd : (𝒰.pullback_cover f).obj i ⟶ 𝒰.obj i),\n ∀ (U : opens Y.carrier), quasi_compact (f ∣_ U),\n ∀ {U : Scheme} (g : U ⟶ Y) [is_open_immersion g],\n quasi_compact (pullback.snd : pullback f g ⟶ _),\n ∃ {ι : Type u} (U : ι → opens Y.carrier) (hU : supr U = ⊤), ∀ i, quasi_compact (f ∣_ (U i))] :=\nquasi_compact_eq_affine_property.symm ▸\n quasi_compact.affine_property_is_local.target_affine_locally_is_local.open_cover_tfae f\n\nlemma quasi_compact_over_affine_iff {X Y : Scheme} (f : X ⟶ Y) [is_affine Y] :\n quasi_compact f ↔ compact_space X.carrier :=\nquasi_compact_eq_affine_property.symm ▸\n quasi_compact.affine_property_is_local.affine_target_iff f\n\nlemma compact_space_iff_quasi_compact (X : Scheme) :\n compact_space X.carrier ↔ quasi_compact (terminal.from X) :=\n(quasi_compact_over_affine_iff _).symm\n\nlemma quasi_compact.affine_open_cover_iff {X Y : Scheme.{u}} (𝒰 : Scheme.open_cover.{u} Y)\n [∀ i, is_affine (𝒰.obj i)] (f : X ⟶ Y) :\n quasi_compact f ↔ ∀ i, compact_space (pullback f (𝒰.map i)).carrier :=\nquasi_compact_eq_affine_property.symm ▸\n quasi_compact.affine_property_is_local.affine_open_cover_iff f 𝒰\n\nlemma quasi_compact.open_cover_iff {X Y : Scheme.{u}} (𝒰 : Scheme.open_cover.{u} Y) (f : X ⟶ Y) :\n quasi_compact f ↔ ∀ i, quasi_compact (pullback.snd : pullback f (𝒰.map i) ⟶ _) :=\nquasi_compact_eq_affine_property.symm ▸\n quasi_compact.affine_property_is_local.target_affine_locally_is_local.open_cover_iff f 𝒰\n\n\n\nlemma quasi_compact_stable_under_composition :\n morphism_property.stable_under_composition @quasi_compact :=\nλ _ _ _ _ _ _ _, by exactI infer_instance\n\nlocal attribute [-simp] PresheafedSpace.as_coe SheafedSpace.as_coe\n\nlemma quasi_compact.affine_property_stable_under_base_change :\n quasi_compact.affine_property.stable_under_base_change :=\nbegin\n intros X Y S _ _ f g h,\n rw quasi_compact.affine_property at h ⊢,\n resetI,\n let 𝒰 := Scheme.pullback.open_cover_of_right Y.affine_cover.finite_subcover f g,\n haveI : finite 𝒰.J,\n { dsimp [𝒰], apply_instance },\n haveI : ∀ i, compact_space (𝒰.obj i).carrier,\n { intro i, dsimp, apply_instance },\n exact 𝒰.compact_space,\nend\n\nlemma quasi_compact_stable_under_base_change :\n morphism_property.stable_under_base_change @quasi_compact :=\nquasi_compact_eq_affine_property.symm ▸\n quasi_compact.affine_property_is_local.stable_under_base_change\n quasi_compact.affine_property_stable_under_base_change\n\nvariables {Z : Scheme.{u}}\n\ninstance (f : X ⟶ Z) (g : Y ⟶ Z) [quasi_compact g] :\n quasi_compact (pullback.fst : pullback f g ⟶ X) :=\nquasi_compact_stable_under_base_change.fst f g infer_instance\n\ninstance (f : X ⟶ Z) (g : Y ⟶ Z) [quasi_compact f] :\n quasi_compact (pullback.snd : pullback f g ⟶ Y) :=\nquasi_compact_stable_under_base_change.snd f g infer_instance\n\n@[elab_as_eliminator]\nlemma compact_open_induction_on {P : opens X.carrier → Prop} (S : opens X.carrier)\n (hS : is_compact S.1)\n (h₁ : P ⊥)\n (h₂ : ∀ (S : opens X.carrier) (hS : is_compact S.1) (U : X.affine_opens), P S → P (S ⊔ U)) :\n P S :=\nbegin\n classical,\n obtain ⟨s, hs, hs'⟩ := (is_compact_open_iff_eq_finset_affine_union S.1).mp ⟨hS, S.2⟩,\n replace hs' : S = supr (λ i : s, (i : opens X.carrier)) := by { ext1, simpa using hs' },\n subst hs',\n apply hs.induction_on,\n { convert h₁, rw supr_eq_bot, rintro ⟨_, h⟩, exact h.elim },\n { intros x s h₃ hs h₄,\n have : is_compact (⨆ i : s, (i : opens X.carrier)).1,\n { refine ((is_compact_open_iff_eq_finset_affine_union _).mpr _).1, exact ⟨s, hs, by simp⟩ },\n convert h₂ _ this x h₄,\n simp only [coe_coe],\n rw [supr_subtype, sup_comm],\n conv_rhs { rw supr_subtype },\n exact supr_insert }\nend\n\nlemma exists_pow_mul_eq_zero_of_res_basic_open_eq_zero_of_is_affine_open (X : Scheme)\n {U : opens X.carrier} (hU : is_affine_open U) (x f : X.presheaf.obj (op U))\n (H : x |_ X.basic_open f = 0) :\n ∃ n : ℕ, f ^ n * x = 0 :=\nbegin\n rw ← map_zero (X.presheaf.map (hom_of_le $ X.basic_open_le f : X.basic_open f ⟶ U).op) at H,\n have := (is_localization_basic_open hU f).3,\n obtain ⟨⟨_, n, rfl⟩, e⟩ := this.mp H,\n exact ⟨n, by simpa [mul_comm x] using e⟩,\nend\n\n/-- If `x : Γ(X, U)` is zero on `D(f)` for some `f : Γ(X, U)`, and `U` is quasi-compact, then\n`f ^ n * x = 0` for some `n`. -/\nlemma exists_pow_mul_eq_zero_of_res_basic_open_eq_zero_of_is_compact (X : Scheme)\n {U : opens X.carrier} (hU : is_compact U.1) (x f : X.presheaf.obj (op U))\n (H : x |_ X.basic_open f = 0) :\n ∃ n : ℕ, f ^ n * x = 0 :=\nbegin\n obtain ⟨s, hs, e⟩ := (is_compact_open_iff_eq_finset_affine_union U.1).mp ⟨hU, U.2⟩,\n replace e : U = supr (λ i : s, (i : opens X.carrier)),\n { ext1, simpa using e },\n have h₁ : ∀ i : s, i.1.1 ≤ U,\n { intro i, change (i : opens X.carrier) ≤ U, rw e, exact le_supr _ _ },\n have H' := λ (i : s), exists_pow_mul_eq_zero_of_res_basic_open_eq_zero_of_is_affine_open X i.1.2\n (X.presheaf.map (hom_of_le (h₁ i)).op x) (X.presheaf.map (hom_of_le (h₁ i)).op f) _,\n swap,\n { delta Top.presheaf.restrict_open Top.presheaf.restrict at H ⊢,\n convert congr_arg (X.presheaf.map (hom_of_le _).op) H,\n { simp only [← comp_apply, ← functor.map_comp], congr },\n { rw map_zero },\n { rw X.basic_open_res, exact set.inter_subset_right _ _ } },\n choose n hn using H',\n haveI := hs.to_subtype,\n casesI nonempty_fintype s,\n use finset.univ.sup n,\n suffices : ∀ (i : s), X.presheaf.map (hom_of_le (h₁ i)).op (f ^ (finset.univ.sup n) * x) = 0,\n { subst e,\n apply X.sheaf.eq_of_locally_eq (λ (i : s), (i : opens X.carrier)),\n intro i,\n rw map_zero,\n apply this },\n intro i,\n replace hn := congr_arg\n (λ x, X.presheaf.map (hom_of_le (h₁ i)).op (f ^ (finset.univ.sup n - n i)) * x) (hn i),\n dsimp at hn,\n simp only [← map_mul, ← map_pow] at hn,\n rwa [mul_zero, ← mul_assoc, ← pow_add, tsub_add_cancel_of_le] at hn,\n apply finset.le_sup (finset.mem_univ i)\nend\n\nend algebraic_geometry\n", "meta": {"author": "leanprover-community", "repo": "mathlib", "sha": "5e526d18cea33550268dcbbddcb822d5cde40654", "save_path": "github-repos/lean/leanprover-community-mathlib", "path": "github-repos/lean/leanprover-community-mathlib/mathlib-5e526d18cea33550268dcbbddcb822d5cde40654/src/algebraic_geometry/morphisms/quasi_compact.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.06954174595211297, "lm_q1q2_score": 0.03477087297605649}} {"text": "/-\nCopyright (c) 2020 Yakov Pechersky. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Yakov Pechersky\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.default\nimport Mathlib.data.string.basic\nimport Mathlib.PostPort\n\nnamespace Mathlib\n\n/-!\n# Parsers\n\n`parser α` is the type that describes a computation that can ingest a `char_buffer`\nand output, if successful, a term of type `α`.\nThis file expands on the definitions in the core library, proving that all the core library\nparsers are `valid`. There are also lemmas on the composability of parsers.\n\n## Main definitions\n\n* `parse_result.pos` : The position of a `char_buffer` at which a `parser α` has finished.\n* `parser.valid` : The property that a parser only moves forward within a buffer,\n in both cases of success or failure.\n\n## Implementation details\n\nLemmas about how parsers are valid are in the `valid` namespace. That allows using projection\nnotation for shorter term proofs that are parallel to the definitions of the parsers in structure.\n\n-/\n\n/--\nFor some `parse_result α`, give the position at which the result was provided, in either the\n`done` or the `fail` case.\n-/\n@[simp] def parse_result.pos {α : Type} : parse_result α → ℕ := sorry\n\nnamespace parser\n\n\n/--\nA `parser α` is defined to be `valid` if the result `p cb n` it gives,\nfor some `cb : char_buffer` and `n : ℕ`, (whether `done` or `fail`),\nis always at a `parse_result.pos` that is at least `n`. Additionally, if the position of the result\nof the parser was within the size of the `cb`, then the input to the parser must have been within\n`cb.size` too.\n-/\ndef valid {α : Type} (p : parser α) :=\n ∀ (cb : char_buffer) (n : ℕ),\n n ≤ parse_result.pos (p cb n) ∧\n (parse_result.pos (p cb n) ≤ buffer.size cb → n ≤ buffer.size cb)\n\ntheorem fail_iff {α : Type} (p : parser α) (cb : char_buffer) (n : ℕ) :\n (∀ (pos' : ℕ) (result : α), p cb n ≠ parse_result.done pos' result) ↔\n ∃ (pos' : ℕ), ∃ (err : dlist string), p cb n = parse_result.fail pos' err :=\n sorry\n\ntheorem success_iff {α : Type} (p : parser α) (cb : char_buffer) (n : ℕ) :\n (∀ (pos' : ℕ) (err : dlist string), p cb n ≠ parse_result.fail pos' err) ↔\n ∃ (pos' : ℕ), ∃ (result : α), p cb n = parse_result.done pos' result :=\n sorry\n\ntheorem decorate_errors_fail {α : Type} {msgs : thunk (List string)} {p : parser α}\n {cb : char_buffer} {n : ℕ} {n' : ℕ} {err : dlist string}\n (h : p cb n = parse_result.fail n' err) :\n decorate_errors msgs p cb n =\n parse_result.fail n (dlist.lazy_of_list fun (_ : Unit) => msgs Unit.unit) :=\n sorry\n\ntheorem decorate_errors_success {α : Type} {msgs : thunk (List string)} {p : parser α}\n {cb : char_buffer} {n : ℕ} {n' : ℕ} {a : α} (h : p cb n = parse_result.done n' a) :\n decorate_errors msgs p cb n = parse_result.done n' a :=\n sorry\n\ntheorem decorate_error_fail {α : Type} {msg : thunk string} {p : parser α} {cb : char_buffer}\n {n : ℕ} {n' : ℕ} {err : dlist string} (h : p cb n = parse_result.fail n' err) :\n decorate_error msg p cb n =\n parse_result.fail n (dlist.lazy_of_list fun (_ : Unit) => [msg Unit.unit]) :=\n decorate_errors_fail h\n\ntheorem decorate_error_success {α : Type} {msg : thunk string} {p : parser α} {cb : char_buffer}\n {n : ℕ} {n' : ℕ} {a : α} (h : p cb n = parse_result.done n' a) :\n decorate_error msg p cb n = parse_result.done n' a :=\n decorate_errors_success h\n\n@[simp] theorem decorate_errors_eq_done {α : Type} {msgs : thunk (List string)} {p : parser α}\n {cb : char_buffer} {n : ℕ} {n' : ℕ} {a : α} :\n decorate_errors msgs p cb n = parse_result.done n' a ↔ p cb n = parse_result.done n' a :=\n sorry\n\n@[simp] theorem decorate_error_eq_done {α : Type} {msg : thunk string} {p : parser α}\n {cb : char_buffer} {n : ℕ} {n' : ℕ} {a : α} :\n decorate_error msg p cb n = parse_result.done n' a ↔ p cb n = parse_result.done n' a :=\n decorate_errors_eq_done\n\n@[simp] theorem decorate_errors_eq_fail {α : Type} {msgs : thunk (List string)} {p : parser α}\n {cb : char_buffer} {n : ℕ} {err : dlist string} :\n decorate_errors msgs p cb n = parse_result.fail n err ↔\n (err = dlist.lazy_of_list fun (_ : Unit) => msgs Unit.unit) ∧\n ∃ (np : ℕ), ∃ (err' : dlist string), p cb n = parse_result.fail np err' :=\n sorry\n\n@[simp] theorem decorate_error_eq_fail {α : Type} {msg : thunk string} {p : parser α}\n {cb : char_buffer} {n : ℕ} {err : dlist string} :\n decorate_error msg p cb n = parse_result.fail n err ↔\n (err = dlist.lazy_of_list fun (_ : Unit) => [msg Unit.unit]) ∧\n ∃ (np : ℕ), ∃ (err' : dlist string), p cb n = parse_result.fail np err' :=\n decorate_errors_eq_fail\n\n@[simp] theorem return_eq_pure {α : Type} {a : α} : return a = pure a := rfl\n\ntheorem pure_eq_done {α : Type} {a : α} :\n pure a = fun (_x : char_buffer) (n : ℕ) => parse_result.done n a :=\n rfl\n\n@[simp] theorem pure_ne_fail {α : Type} {cb : char_buffer} {n : ℕ} {n' : ℕ} {err : dlist string}\n {a : α} : pure a cb n ≠ parse_result.fail n' err :=\n sorry\n\n@[simp] theorem bind_eq_bind {α : Type} {β : Type} {p : parser α} (f : α → parser β) :\n parser.bind p f = p >>= f :=\n rfl\n\n@[simp] theorem bind_eq_done {α : Type} {β : Type} {p : parser α} {cb : char_buffer} {n : ℕ}\n {n' : ℕ} {b : β} {f : α → parser β} :\n bind p f cb n = parse_result.done n' b ↔\n ∃ (np : ℕ),\n ∃ (a : α), p cb n = parse_result.done np a ∧ f a cb np = parse_result.done n' b :=\n sorry\n\n@[simp] theorem bind_eq_fail {α : Type} {β : Type} {p : parser α} {cb : char_buffer} {n : ℕ}\n {n' : ℕ} {err : dlist string} {f : α → parser β} :\n bind p f cb n = parse_result.fail n' err ↔\n p cb n = parse_result.fail n' err ∨\n ∃ (np : ℕ),\n ∃ (a : α), p cb n = parse_result.done np a ∧ f a cb np = parse_result.fail n' err :=\n sorry\n\n@[simp] theorem and_then_eq_bind {α : Type} {β : Type} {m : Type → Type} [Monad m] (a : m α)\n (b : m β) :\n a >> b =\n do \n a \n b :=\n rfl\n\ntheorem and_then_fail {α : Type} {p : parser α} {cb : char_buffer} {n : ℕ} {n' : ℕ}\n {err : dlist string} :\n has_bind.and_then p (return Unit.unit) cb n = parse_result.fail n' err ↔\n p cb n = parse_result.fail n' err :=\n sorry\n\ntheorem and_then_success {α : Type} {p : parser α} {cb : char_buffer} {n : ℕ} {n' : ℕ} :\n has_bind.and_then p (return Unit.unit) cb n = parse_result.done n' Unit.unit ↔\n ∃ (a : α), p cb n = parse_result.done n' a :=\n sorry\n\n@[simp] theorem map_eq_done {α : Type} {β : Type} {p : parser α} {cb : char_buffer} {n : ℕ} {n' : ℕ}\n {b : β} {f : α → β} :\n Functor.map f p cb n = parse_result.done n' b ↔\n ∃ (a : α), p cb n = parse_result.done n' a ∧ f a = b :=\n sorry\n\n@[simp] theorem map_eq_fail {α : Type} {β : Type} {p : parser α} {cb : char_buffer} {n : ℕ} {n' : ℕ}\n {err : dlist string} {f : α → β} :\n Functor.map f p cb n = parse_result.fail n' err ↔ p cb n = parse_result.fail n' err :=\n sorry\n\n@[simp] theorem map_const_eq_done {α : Type} {β : Type} {p : parser α} {cb : char_buffer} {n : ℕ}\n {n' : ℕ} {b : β} {b' : β} :\n Functor.mapConst b p cb n = parse_result.done n' b' ↔\n ∃ (a : α), p cb n = parse_result.done n' a ∧ b = b' :=\n sorry\n\n@[simp] theorem map_const_eq_fail {α : Type} {β : Type} {p : parser α} {cb : char_buffer} {n : ℕ}\n {n' : ℕ} {err : dlist string} {b : β} :\n Functor.mapConst b p cb n = parse_result.fail n' err ↔ p cb n = parse_result.fail n' err :=\n sorry\n\ntheorem map_const_rev_eq_done {α : Type} {β : Type} {p : parser α} {cb : char_buffer} {n : ℕ}\n {n' : ℕ} {b : β} {b' : β} :\n functor.map_const_rev p b cb n = parse_result.done n' b' ↔\n ∃ (a : α), p cb n = parse_result.done n' a ∧ b = b' :=\n map_const_eq_done\n\ntheorem map_rev_const_eq_fail {α : Type} {β : Type} {p : parser α} {cb : char_buffer} {n : ℕ}\n {n' : ℕ} {err : dlist string} {b : β} :\n functor.map_const_rev p b cb n = parse_result.fail n' err ↔ p cb n = parse_result.fail n' err :=\n map_const_eq_fail\n\n@[simp] theorem orelse_eq_orelse {α : Type} {p : parser α} {q : parser α} :\n parser.orelse p q = (p <|> q) :=\n rfl\n\n@[simp] theorem orelse_eq_done {α : Type} {p : parser α} {q : parser α} {cb : char_buffer} {n : ℕ}\n {n' : ℕ} {a : α} :\n has_orelse.orelse p q cb n = parse_result.done n' a ↔\n p cb n = parse_result.done n' a ∨\n q cb n = parse_result.done n' a ∧\n ∃ (err : dlist string), p cb n = parse_result.fail n err :=\n sorry\n\n@[simp] theorem orelse_eq_fail_eq {α : Type} {p : parser α} {q : parser α} {cb : char_buffer}\n {n : ℕ} {err : dlist string} :\n has_orelse.orelse p q cb n = parse_result.fail n err ↔\n (p cb n = parse_result.fail n err ∧\n ∃ (nq : ℕ), ∃ (errq : dlist string), n < nq ∧ q cb n = parse_result.fail nq errq) ∨\n ∃ (errp : dlist string),\n ∃ (errq : dlist string),\n p cb n = parse_result.fail n errp ∧\n q cb n = parse_result.fail n errq ∧ errp ++ errq = err :=\n sorry\n\ntheorem orelse_eq_fail_invalid_lt {α : Type} {p : parser α} {q : parser α} {cb : char_buffer}\n {n : ℕ} {n' : ℕ} {err : dlist string} (hn : n' < n) :\n has_orelse.orelse p q cb n = parse_result.fail n' err ↔\n p cb n = parse_result.fail n' err ∨\n q cb n = parse_result.fail n' err ∧\n ∃ (errp : dlist string), p cb n = parse_result.fail n errp :=\n sorry\n\ntheorem orelse_eq_fail_of_valid_ne {α : Type} {p : parser α} {q : parser α} {cb : char_buffer}\n {n : ℕ} {n' : ℕ} {err : dlist string} (hv : valid q) (hn : n ≠ n') :\n has_orelse.orelse p q cb n = parse_result.fail n' err ↔ p cb n = parse_result.fail n' err :=\n sorry\n\n@[simp] theorem failure_eq_failure {α : Type} : parser.failure = failure := rfl\n\n@[simp] theorem failure_def {α : Type} {cb : char_buffer} {n : ℕ} :\n failure cb n = parse_result.fail n dlist.empty :=\n rfl\n\ntheorem not_failure_eq_done {α : Type} {cb : char_buffer} {n : ℕ} {n' : ℕ} {a : α} :\n ¬failure cb n = parse_result.done n' a :=\n sorry\n\ntheorem failure_eq_fail {α : Type} {cb : char_buffer} {n : ℕ} {n' : ℕ} {err : dlist string} :\n failure cb n = parse_result.fail n' err ↔ n = n' ∧ err = dlist.empty :=\n sorry\n\ntheorem seq_eq_done {α : Type} {β : Type} {cb : char_buffer} {n : ℕ} {n' : ℕ} {b : β}\n {f : parser (α → β)} {p : parser α} :\n Seq.seq f p cb n = parse_result.done n' b ↔\n ∃ (nf : ℕ),\n ∃ (f' : α → β),\n ∃ (a : α),\n f cb n = parse_result.done nf f' ∧ p cb nf = parse_result.done n' a ∧ f' a = b :=\n sorry\n\ntheorem seq_eq_fail {α : Type} {β : Type} {cb : char_buffer} {n : ℕ} {n' : ℕ} {err : dlist string}\n {f : parser (α → β)} {p : parser α} :\n Seq.seq f p cb n = parse_result.fail n' err ↔\n f cb n = parse_result.fail n' err ∨\n ∃ (nf : ℕ),\n ∃ (f' : α → β), f cb n = parse_result.done nf f' ∧ p cb nf = parse_result.fail n' err :=\n sorry\n\ntheorem seq_left_eq_done {α : Type} {β : Type} {cb : char_buffer} {n : ℕ} {n' : ℕ} {a : α}\n {p : parser α} {q : parser β} :\n SeqLeft.seqLeft p q cb n = parse_result.done n' a ↔\n ∃ (np : ℕ), ∃ (b : β), p cb n = parse_result.done np a ∧ q cb np = parse_result.done n' b :=\n sorry\n\ntheorem seq_left_eq_fail {α : Type} {β : Type} {cb : char_buffer} {n : ℕ} {n' : ℕ}\n {err : dlist string} {p : parser α} {q : parser β} :\n SeqLeft.seqLeft p q cb n = parse_result.fail n' err ↔\n p cb n = parse_result.fail n' err ∨\n ∃ (np : ℕ),\n ∃ (a : α), p cb n = parse_result.done np a ∧ q cb np = parse_result.fail n' err :=\n sorry\n\ntheorem seq_right_eq_done {α : Type} {β : Type} {cb : char_buffer} {n : ℕ} {n' : ℕ} {b : β}\n {p : parser α} {q : parser β} :\n SeqRight.seqRight p q cb n = parse_result.done n' b ↔\n ∃ (np : ℕ), ∃ (a : α), p cb n = parse_result.done np a ∧ q cb np = parse_result.done n' b :=\n sorry\n\ntheorem seq_right_eq_fail {α : Type} {β : Type} {cb : char_buffer} {n : ℕ} {n' : ℕ}\n {err : dlist string} {p : parser α} {q : parser β} :\n SeqRight.seqRight p q cb n = parse_result.fail n' err ↔\n p cb n = parse_result.fail n' err ∨\n ∃ (np : ℕ),\n ∃ (a : α), p cb n = parse_result.done np a ∧ q cb np = parse_result.fail n' err :=\n sorry\n\ntheorem mmap_eq_done {α : Type} {β : Type} {cb : char_buffer} {n : ℕ} {n' : ℕ} {f : α → parser β}\n {a : α} {l : List α} {b : β} {l' : List β} :\n mmap f (a :: l) cb n = parse_result.done n' (b :: l') ↔\n ∃ (np : ℕ), f a cb n = parse_result.done np b ∧ mmap f l cb np = parse_result.done n' l' :=\n sorry\n\ntheorem mmap'_eq_done {α : Type} {β : Type} {cb : char_buffer} {n : ℕ} {n' : ℕ} {f : α → parser β}\n {a : α} {l : List α} :\n mmap' f (a :: l) cb n = parse_result.done n' Unit.unit ↔\n ∃ (np : ℕ),\n ∃ (b : β),\n f a cb n = parse_result.done np b ∧ mmap' f l cb np = parse_result.done n' Unit.unit :=\n sorry\n\ntheorem guard_eq_done {cb : char_buffer} {n : ℕ} {n' : ℕ} {p : Prop} [Decidable p] :\n guard p cb n = parse_result.done n' Unit.unit ↔ p ∧ n = n' :=\n sorry\n\ntheorem guard_eq_fail {cb : char_buffer} {n : ℕ} {n' : ℕ} {err : dlist string} {p : Prop}\n [Decidable p] : guard p cb n = parse_result.fail n' err ↔ ¬p ∧ n = n' ∧ err = dlist.empty :=\n sorry\n\nnamespace valid\n\n\ntheorem mono_done {α : Type} {p : parser α} {cb : char_buffer} {n : ℕ} {n' : ℕ} {a : α}\n (hp : valid p) (h : p cb n = parse_result.done n' a) : n ≤ n' :=\n sorry\n\ntheorem mono_fail {α : Type} {p : parser α} {cb : char_buffer} {n : ℕ} {n' : ℕ} {err : dlist string}\n (hp : valid p) (h : p cb n = parse_result.fail n' err) : n ≤ n' :=\n sorry\n\ntheorem pure {α : Type} {a : α} : valid (pure a) := sorry\n\n@[simp] theorem bind {α : Type} {β : Type} {p : parser α} {f : α → parser β} (hp : valid p)\n (hf : ∀ (a : α), valid (f a)) : valid (p >>= f) :=\n sorry\n\ntheorem and_then {α : Type} {β : Type} {p : parser α} {q : parser β} (hp : valid p) (hq : valid q) :\n valid (p >> q) :=\n bind hp fun (_x : α) => hq\n\n@[simp] theorem map {α : Type} {β : Type} {p : parser α} (hp : valid p) {f : α → β} :\n valid (f <$> p) :=\n bind hp fun (_x : α) => pure\n\n@[simp] theorem seq {α : Type} {β : Type} {p : parser α} {f : parser (α → β)} (hf : valid f)\n (hp : valid p) : valid (f <*> p) :=\n bind hf fun (_x : α → β) => map hp\n\n@[simp] theorem mmap {α : Type} {β : Type} {l : List α} {f : α → parser β}\n (h : ∀ (a : α), a ∈ l → valid (f a)) : valid (mmap f l) :=\n sorry\n\n@[simp] theorem mmap' {α : Type} {β : Type} {l : List α} {f : α → parser β}\n (h : ∀ (a : α), a ∈ l → valid (f a)) : valid (mmap' f l) :=\n sorry\n\n@[simp] theorem failure {α : Type} : valid failure := sorry\n\n@[simp] theorem guard {p : Prop} [Decidable p] : valid (guard p) := sorry\n\n@[simp] theorem orelse {α : Type} {p : parser α} {q : parser α} (hp : valid p) (hq : valid q) :\n valid (p <|> q) :=\n sorry\n\n@[simp] theorem decorate_errors {α : Type} {msgs : thunk (List string)} {p : parser α}\n (hp : valid p) : valid (decorate_errors msgs p) :=\n sorry\n\n@[simp] theorem decorate_error {α : Type} {msg : thunk string} {p : parser α} (hp : valid p) :\n valid (decorate_error msg p) :=\n decorate_errors hp\n\n@[simp] theorem any_char : valid any_char := sorry\n\n@[simp] theorem sat {p : char → Prop} [decidable_pred p] : valid (sat p) := sorry\n\n@[simp] theorem eps : valid eps := pure\n\ntheorem ch {c : char} : valid (ch c) := decorate_error (and_then sat eps)\n\ntheorem char_buf {s : char_buffer} : valid (char_buf s) :=\n decorate_error (mmap' fun (_x : char) (_x_1 : _x ∈ buffer.to_list s) => ch)\n\ntheorem one_of {cs : List char} : valid (one_of cs) := decorate_errors sat\n\ntheorem one_of' {cs : List char} : valid (one_of' cs) := and_then one_of eps\n\ntheorem str {s : string} : valid (str s) :=\n decorate_error (mmap' fun (_x : char) (_x_1 : _x ∈ string.to_list s) => ch)\n\ntheorem remaining : valid remaining :=\n fun (_x : char_buffer) (_x_1 : ℕ) =>\n { left := le_refl _x_1,\n right := fun (h : parse_result.pos (remaining _x _x_1) ≤ buffer.size _x) => h }\n\ntheorem eof : valid eof := decorate_error (bind remaining fun (_x : ℕ) => guard)\n\ntheorem foldr_core_zero {α : Type} {β : Type} {p : parser α} {f : α → β → β} {b : β} :\n valid (foldr_core f p b 0) :=\n failure\n\ntheorem foldr_core {α : Type} {β : Type} {p : parser α} {f : α → β → β} {b : β} (hp : valid p)\n {reps : ℕ} : valid (foldr_core f p b reps) :=\n sorry\n\ntheorem foldr {α : Type} {β : Type} {p : parser α} {b : β} {f : α → β → β} (hp : valid p) :\n valid (foldr f p b) :=\n fun (_x : char_buffer) (_x_1 : ℕ) => foldr_core hp _x _x_1\n\ntheorem foldl_core_zero {α : Type} {β : Type} {p : parser α} {f : β → α → β} {b : β} :\n valid (foldl_core f b p 0) :=\n failure\n\ntheorem foldl_core {α : Type} {β : Type} {f : α → β → α} {p : parser β} (hp : valid p) {a : α}\n {reps : ℕ} : valid (foldl_core f a p reps) :=\n sorry\n\ntheorem foldl {α : Type} {β : Type} {a : α} {f : α → β → α} {p : parser β} (hp : valid p) :\n valid (foldl f a p) :=\n fun (_x : char_buffer) (_x_1 : ℕ) => foldl_core hp _x _x_1\n\ntheorem many {α : Type} {p : parser α} (hp : valid p) : valid (many p) := foldr hp\n\ntheorem many_char {p : parser char} (hp : valid p) : valid (many_char p) := map (many hp)\n\ntheorem many' {α : Type} {p : parser α} (hp : valid p) : valid (many' p) := and_then (many hp) eps\n\ntheorem many1 {α : Type} {p : parser α} (hp : valid p) : valid (many1 p) := seq (map hp) (many hp)\n\ntheorem many_char1 {p : parser char} (hp : valid p) : valid (many_char1 p) := map (many1 hp)\n\ntheorem sep_by1 {α : Type} {p : parser α} {sep : parser Unit} (hp : valid p) (hs : valid sep) :\n valid (sep_by1 sep p) :=\n seq (map hp) (many (and_then hs hp))\n\ntheorem sep_by {α : Type} {p : parser α} {sep : parser Unit} (hp : valid p) (hs : valid sep) :\n valid (sep_by sep p) :=\n orelse (sep_by1 hp hs) pure\n\ntheorem fix_core {α : Type} {F : parser α → parser α} (hF : ∀ (p : parser α), valid p → valid (F p))\n (max_depth : ℕ) : valid (fix_core F max_depth) :=\n sorry\n\ntheorem digit : valid digit := decorate_error (bind sat fun (_x : char) => pure)\n\ntheorem nat : valid nat := decorate_error (bind (many1 digit) fun (_x : List ℕ) => pure)\n\ntheorem fix {α : Type} {F : parser α → parser α} (hF : ∀ (p : parser α), valid p → valid (F p)) :\n valid (fix F) :=\n fun (_x : char_buffer) (_x_1 : ℕ) => fix_core hF (buffer.size _x - _x_1 + 1) _x _x_1\n\nend valid\n\n\n@[simp] theorem orelse_pure_eq_fail {α : Type} {p : parser α} {cb : char_buffer} {n : ℕ} {n' : ℕ}\n {err : dlist string} {a : α} :\n has_orelse.orelse p (pure a) cb n = parse_result.fail n' err ↔\n p cb n = parse_result.fail n' err ∧ n ≠ n' :=\n sorry\n\ntheorem any_char_eq_done {cb : char_buffer} {n : ℕ} {n' : ℕ} (hn : n < buffer.size cb) {c : char} :\n any_char cb n = parse_result.done n' c ↔\n n' = n + 1 ∧ buffer.read cb { val := n, property := hn } = c :=\n sorry\n\ntheorem sat_eq_done {cb : char_buffer} {n : ℕ} {n' : ℕ} (hn : n < buffer.size cb) {c : char}\n {p : char → Prop} [decidable_pred p] :\n sat p cb n = parse_result.done n' c ↔\n p c ∧ n' = n + 1 ∧ buffer.read cb { val := n, property := hn } = c :=\n sorry\n\ntheorem eps_eq_done {cb : char_buffer} {n : ℕ} {n' : ℕ} :\n eps cb n = parse_result.done n' Unit.unit ↔ n = n' :=\n sorry\n\ntheorem ch_eq_done {cb : char_buffer} {n : ℕ} {n' : ℕ} (hn : n < buffer.size cb) {c : char} :\n ch c cb n = parse_result.done n' Unit.unit ↔\n n' = n + 1 ∧ buffer.read cb { val := n, property := hn } = c :=\n sorry\n\n-- TODO: add char_buf_eq_done, needs lemmas about matching buffers\n\ntheorem one_of_eq_done {cb : char_buffer} {n : ℕ} {n' : ℕ} (hn : n < buffer.size cb) {c : char}\n {cs : List char} :\n one_of cs cb n = parse_result.done n' c ↔\n c ∈ cs ∧ n' = n + 1 ∧ buffer.read cb { val := n, property := hn } = c :=\n sorry\n\ntheorem one_of'_eq_done {cb : char_buffer} {n : ℕ} {n' : ℕ} (hn : n < buffer.size cb)\n {cs : List char} :\n one_of' cs cb n = parse_result.done n' Unit.unit ↔\n buffer.read cb { val := n, property := hn } ∈ cs ∧ n' = n + 1 :=\n sorry\n\ntheorem remaining_eq_done {cb : char_buffer} {n : ℕ} {n' : ℕ} {r : ℕ} :\n remaining cb n = parse_result.done n' r ↔ n = n' ∧ buffer.size cb - n = r :=\n sorry\n\ntheorem eof_eq_done {cb : char_buffer} {n : ℕ} {n' : ℕ} :\n eof cb n = parse_result.done n' Unit.unit ↔ n = n' ∧ buffer.size cb ≤ n :=\n sorry\n\n@[simp] theorem foldr_core_zero_eq_done {α : Type} {β : Type} {cb : char_buffer} {n : ℕ} {n' : ℕ}\n {b : β} {f : α → β → β} {p : parser α} {b' : β} :\n foldr_core f p b 0 cb n ≠ parse_result.done n' b' :=\n sorry\n\ntheorem foldr_core_eq_done {α : Type} {β : Type} {cb : char_buffer} {n : ℕ} {n' : ℕ} {b : β}\n {f : α → β → β} {p : parser α} {reps : ℕ} {b' : β} :\n foldr_core f p b (reps + 1) cb n = parse_result.done n' b' ↔\n (∃ (np : ℕ),\n ∃ (a : α),\n ∃ (xs : β),\n p cb n = parse_result.done np a ∧\n foldr_core f p b reps cb np = parse_result.done n' xs ∧ f a xs = b') ∨\n n = n' ∧\n b = b' ∧\n ∃ (err : dlist string),\n p cb n = parse_result.fail n err ∨\n ∃ (np : ℕ),\n ∃ (a : α),\n p cb n = parse_result.done np a ∧\n foldr_core f p b reps cb np = parse_result.fail n err :=\n sorry\n\n@[simp] theorem foldr_core_zero_eq_fail {α : Type} {β : Type} {cb : char_buffer} {n : ℕ} {n' : ℕ}\n {b : β} {f : α → β → β} {p : parser α} {err : dlist string} :\n foldr_core f p b 0 cb n = parse_result.fail n' err ↔ n = n' ∧ err = dlist.empty :=\n sorry\n\ntheorem foldr_core_succ_eq_fail {α : Type} {β : Type} {cb : char_buffer} {n : ℕ} {n' : ℕ} {b : β}\n {f : α → β → β} {p : parser α} {reps : ℕ} {err : dlist string} :\n foldr_core f p b (reps + 1) cb n = parse_result.fail n' err ↔\n n ≠ n' ∧\n (p cb n = parse_result.fail n' err ∨\n ∃ (np : ℕ),\n ∃ (a : α),\n p cb n = parse_result.done np a ∧\n foldr_core f p b reps cb np = parse_result.fail n' err) :=\n sorry\n\ntheorem foldr_eq_done {α : Type} {β : Type} {cb : char_buffer} {n : ℕ} {n' : ℕ} {b : β}\n {f : α → β → β} {p : parser α} {b' : β} :\n foldr f p b cb n = parse_result.done n' b' ↔\n (∃ (np : ℕ),\n ∃ (a : α),\n ∃ (x : β),\n p cb n = parse_result.done np a ∧\n foldr_core f p b (buffer.size cb - n) cb np = parse_result.done n' x ∧\n f a x = b') ∨\n n = n' ∧\n b = b' ∧\n ∃ (err : dlist string),\n p cb n = parse_result.fail n err ∨\n ∃ (np : ℕ),\n ∃ (x : α),\n p cb n = parse_result.done np x ∧\n foldr_core f p b (buffer.size cb - n) cb np = parse_result.fail n err :=\n sorry\n\ntheorem foldr_eq_fail_of_valid_at_end {α : Type} {β : Type} {cb : char_buffer} {n : ℕ} {n' : ℕ}\n {b : β} {f : α → β → β} {p : parser α} {err : dlist string} (hp : valid p)\n (hc : buffer.size cb ≤ n) :\n foldr f p b cb n = parse_result.fail n' err ↔\n n < n' ∧\n (p cb n = parse_result.fail n' err ∨\n ∃ (a : α), p cb n = parse_result.done n' a ∧ err = dlist.empty) :=\n sorry\n\ntheorem foldr_eq_fail {α : Type} {β : Type} {cb : char_buffer} {n : ℕ} {n' : ℕ} {b : β}\n {f : α → β → β} {p : parser α} {err : dlist string} :\n foldr f p b cb n = parse_result.fail n' err ↔\n n ≠ n' ∧\n (p cb n = parse_result.fail n' err ∨\n ∃ (np : ℕ),\n ∃ (a : α),\n p cb n = parse_result.done np a ∧\n foldr_core f p b (buffer.size cb - n) cb np = parse_result.fail n' err) :=\n sorry\n\n@[simp] theorem foldl_core_zero_eq_done {α : Type} {β : Type} {cb : char_buffer} {n : ℕ} {n' : ℕ}\n {b : β} {f : β → α → β} {p : parser α} {b' : β} :\n foldl_core f b p 0 cb n = parse_result.done n' b' ↔ False :=\n sorry\n\ntheorem foldl_core_eq_done {α : Type} {β : Type} {cb : char_buffer} {n : ℕ} {n' : ℕ} {b : β}\n {f : β → α → β} {p : parser α} {reps : ℕ} {b' : β} :\n foldl_core f b p (reps + 1) cb n = parse_result.done n' b' ↔\n (∃ (np : ℕ),\n ∃ (a : α),\n p cb n = parse_result.done np a ∧\n foldl_core f (f b a) p reps cb np = parse_result.done n' b') ∨\n n = n' ∧\n b = b' ∧\n ∃ (err : dlist string),\n p cb n = parse_result.fail n err ∨\n ∃ (np : ℕ),\n ∃ (a : α),\n p cb n = parse_result.done np a ∧\n foldl_core f (f b a) p reps cb np = parse_result.fail n err :=\n sorry\n\n@[simp] theorem foldl_core_zero_eq_fail {α : Type} {β : Type} {cb : char_buffer} {n : ℕ} {n' : ℕ}\n {b : β} {f : β → α → β} {p : parser α} {err : dlist string} :\n foldl_core f b p 0 cb n = parse_result.fail n' err ↔ n = n' ∧ err = dlist.empty :=\n sorry\n\ntheorem foldl_core_succ_eq_fail {α : Type} {β : Type} {cb : char_buffer} {n : ℕ} {n' : ℕ} {b : β}\n {f : β → α → β} {p : parser α} {reps : ℕ} {err : dlist string} :\n foldl_core f b p (reps + 1) cb n = parse_result.fail n' err ↔\n n ≠ n' ∧\n (p cb n = parse_result.fail n' err ∨\n ∃ (np : ℕ),\n ∃ (a : α),\n p cb n = parse_result.done np a ∧\n foldl_core f (f b a) p reps cb np = parse_result.fail n' err) :=\n sorry\n\ntheorem foldl_eq_done {α : Type} {β : Type} {cb : char_buffer} {n : ℕ} {n' : ℕ} {b : β}\n {f : β → α → β} {p : parser α} {b' : β} :\n foldl f b p cb n = parse_result.done n' b' ↔\n (∃ (np : ℕ),\n ∃ (a : α),\n p cb n = parse_result.done np a ∧\n foldl_core f (f b a) p (buffer.size cb - n) cb np = parse_result.done n' b') ∨\n n = n' ∧\n b = b' ∧\n ∃ (err : dlist string),\n p cb n = parse_result.fail n err ∨\n ∃ (np : ℕ),\n ∃ (a : α),\n p cb n = parse_result.done np a ∧\n foldl_core f (f b a) p (buffer.size cb - n) cb np =\n parse_result.fail n err :=\n sorry\n\ntheorem foldl_eq_fail {α : Type} {β : Type} {cb : char_buffer} {n : ℕ} {n' : ℕ} {b : β}\n {f : β → α → β} {p : parser α} {err : dlist string} :\n foldl f b p cb n = parse_result.fail n' err ↔\n n ≠ n' ∧\n (p cb n = parse_result.fail n' err ∨\n ∃ (np : ℕ),\n ∃ (a : α),\n p cb n = parse_result.done np a ∧\n foldl_core f (f b a) p (buffer.size cb - n) cb np = parse_result.fail n' err) :=\n sorry\n\ntheorem many_eq_done_nil {α : Type} {cb : char_buffer} {n : ℕ} {n' : ℕ} {p : parser α} :\n many p cb n = parse_result.done n' [] ↔\n n = n' ∧\n ∃ (err : dlist string),\n p cb n = parse_result.fail n err ∨\n ∃ (np : ℕ),\n ∃ (a : α),\n p cb n = parse_result.done np a ∧\n foldr_core List.cons p [] (buffer.size cb - n) cb np =\n parse_result.fail n err :=\n sorry\n\ntheorem many_eq_done {α : Type} {cb : char_buffer} {n : ℕ} {n' : ℕ} {p : parser α} {x : α}\n {xs : List α} :\n many p cb n = parse_result.done n' (x :: xs) ↔\n ∃ (np : ℕ),\n p cb n = parse_result.done np x ∧\n foldr_core List.cons p [] (buffer.size cb - n) cb np = parse_result.done n' xs :=\n sorry\n\ntheorem many_eq_fail {α : Type} {cb : char_buffer} {n : ℕ} {n' : ℕ} {p : parser α}\n {err : dlist string} :\n many p cb n = parse_result.fail n' err ↔\n n ≠ n' ∧\n (p cb n = parse_result.fail n' err ∨\n ∃ (np : ℕ),\n ∃ (a : α),\n p cb n = parse_result.done np a ∧\n foldr_core List.cons p [] (buffer.size cb - n) cb np =\n parse_result.fail n' err) :=\n sorry\n\ntheorem many_char_eq_done_empty {cb : char_buffer} {n : ℕ} {n' : ℕ} {p : parser char} :\n many_char p cb n = parse_result.done n' string.empty ↔\n n = n' ∧\n ∃ (err : dlist string),\n p cb n = parse_result.fail n err ∨\n ∃ (np : ℕ),\n ∃ (c : char),\n p cb n = parse_result.done np c ∧\n foldr_core List.cons p [] (buffer.size cb - n) cb np =\n parse_result.fail n err :=\n sorry\n\ntheorem many_char_eq_done_not_empty {cb : char_buffer} {n : ℕ} {n' : ℕ} {p : parser char}\n {s : string} (h : s ≠ string.empty) :\n many_char p cb n = parse_result.done n' s ↔\n ∃ (np : ℕ),\n p cb n = parse_result.done np (string.head s) ∧\n foldr_core List.cons p [] (buffer.size cb - n) cb np =\n parse_result.done n' (string.to_list (string.popn s 1)) :=\n sorry\n\ntheorem many_char_eq_many_of_to_list {cb : char_buffer} {n : ℕ} {n' : ℕ} {p : parser char}\n {s : string} :\n many_char p cb n = parse_result.done n' s ↔\n many p cb n = parse_result.done n' (string.to_list s) :=\n sorry\n\ntheorem many'_eq_done {α : Type} {cb : char_buffer} {n : ℕ} {n' : ℕ} {p : parser α} :\n many' p cb n = parse_result.done n' Unit.unit ↔\n many p cb n = parse_result.done n' [] ∨\n ∃ (np : ℕ),\n ∃ (a : α),\n ∃ (l : List α),\n many p cb n = parse_result.done n' (a :: l) ∧\n p cb n = parse_result.done np a ∧\n foldr_core List.cons p [] (buffer.size cb - n) cb np = parse_result.done n' l :=\n sorry\n\n@[simp] theorem many1_ne_done_nil {α : Type} {cb : char_buffer} {n : ℕ} {n' : ℕ} {p : parser α} :\n many1 p cb n ≠ parse_result.done n' [] :=\n sorry\n\ntheorem many1_eq_done {α : Type} {cb : char_buffer} {n : ℕ} {n' : ℕ} {a : α} {p : parser α}\n {l : List α} :\n many1 p cb n = parse_result.done n' (a :: l) ↔\n ∃ (np : ℕ), p cb n = parse_result.done np a ∧ many p cb np = parse_result.done n' l :=\n sorry\n\ntheorem many1_eq_fail {α : Type} {cb : char_buffer} {n : ℕ} {n' : ℕ} {p : parser α}\n {err : dlist string} :\n many1 p cb n = parse_result.fail n' err ↔\n p cb n = parse_result.fail n' err ∨\n ∃ (np : ℕ),\n ∃ (a : α), p cb n = parse_result.done np a ∧ many p cb np = parse_result.fail n' err :=\n sorry\n\n@[simp] theorem many_char1_ne_empty {cb : char_buffer} {n : ℕ} {n' : ℕ} {p : parser char} :\n many_char1 p cb n ≠ parse_result.done n' string.empty :=\n sorry\n\ntheorem many_char1_eq_done {cb : char_buffer} {n : ℕ} {n' : ℕ} {p : parser char} {s : string}\n (h : s ≠ string.empty) :\n many_char1 p cb n = parse_result.done n' s ↔\n ∃ (np : ℕ),\n p cb n = parse_result.done np (string.head s) ∧\n many_char p cb np = parse_result.done n' (string.popn s 1) :=\n sorry\n\n@[simp] theorem sep_by1_ne_done_nil {α : Type} {cb : char_buffer} {n : ℕ} {n' : ℕ}\n {sep : parser Unit} {p : parser α} : sep_by1 sep p cb n ≠ parse_result.done n' [] :=\n sorry\n\ntheorem sep_by1_eq_done {α : Type} {cb : char_buffer} {n : ℕ} {n' : ℕ} {a : α} {sep : parser Unit}\n {p : parser α} {l : List α} :\n sep_by1 sep p cb n = parse_result.done n' (a :: l) ↔\n ∃ (np : ℕ),\n p cb n = parse_result.done np a ∧ many (sep >> p) cb np = parse_result.done n' l :=\n sorry\n\ntheorem sep_by_eq_done_nil {α : Type} {cb : char_buffer} {n : ℕ} {n' : ℕ} {sep : parser Unit}\n {p : parser α} :\n sep_by sep p cb n = parse_result.done n' [] ↔\n n = n' ∧ ∃ (err : dlist string), sep_by1 sep p cb n = parse_result.fail n err :=\n sorry\n\n@[simp] theorem fix_core_ne_done_zero {α : Type} {cb : char_buffer} {n : ℕ} {n' : ℕ} {a : α}\n {F : parser α → parser α} : fix_core F 0 cb n ≠ parse_result.done n' a :=\n sorry\n\ntheorem fix_core_eq_done {α : Type} {cb : char_buffer} {n : ℕ} {n' : ℕ} {a : α}\n {F : parser α → parser α} {max_depth : ℕ} :\n fix_core F (max_depth + 1) cb n = parse_result.done n' a ↔\n F (fix_core F max_depth) cb n = parse_result.done n' a :=\n sorry\n\ntheorem digit_eq_done {cb : char_buffer} {n : ℕ} {n' : ℕ} (hn : n < buffer.size cb) {k : ℕ} :\n digit cb n = parse_result.done n' k ↔\n n' = n + 1 ∧\n k ≤ bit1 (bit0 (bit0 1)) ∧\n char.to_nat (buffer.read cb { val := n, property := hn }) -\n char.to_nat (char.of_nat (bit0 (bit0 (bit0 (bit0 (bit1 1)))))) =\n k ∧\n char.of_nat (bit0 (bit0 (bit0 (bit0 (bit1 1))))) ≤\n buffer.read cb { val := n, property := hn } ∧\n buffer.read cb { val := n, property := hn } ≤\n char.of_nat (bit1 (bit0 (bit0 (bit1 (bit1 1))))) :=\n sorry\n\nend Mathlib", "meta": {"author": "AurelienSaue", "repo": "Mathlib4_auto", "sha": "590df64109b08190abe22358fabc3eae000943f2", "save_path": "github-repos/lean/AurelienSaue-Mathlib4_auto", "path": "github-repos/lean/AurelienSaue-Mathlib4_auto/Mathlib4_auto-590df64109b08190abe22358fabc3eae000943f2/Mathlib/data/buffer/parser/basic_auto.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46490157137338844, "lm_q2_score": 0.074770045485098, "lm_q1q2_score": 0.03476071163768179}} {"text": "/-\nCopyright (c) 2017 Mario Carneiro. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Mario Carneiro, Yury Kudryashov, Floris van Doorn\n-/\nimport tactic.transform_decl\nimport tactic.algebra\nimport tactic.lint.basic\n\n/-!\n# Transport multiplicative to additive\n\nThis file defines an attribute `to_additive` that can be used to\nautomatically transport theorems and definitions (but not inductive\ntypes and structures) from a multiplicative theory to an additive theory.\n\nUsage information is contained in the doc string of `to_additive.attr`.\n\n### Missing features\n\n* Automatically transport structures and other inductive types.\n\n* For structures, automatically generate theorems like `group α ↔\n add_group (additive α)`.\n-/\n\nnamespace to_additive\nopen tactic\nsetup_tactic_parser\n\nsection performance_hack -- see Note [user attribute parameters]\n\nlocal attribute [semireducible] reflected\n\n/-- Temporarily change the `has_reflect` instance for `name`. -/\nlocal attribute [instance, priority 9000]\nmeta def hacky_name_reflect : has_reflect name :=\nλ n, `(id %%(expr.const n []) : name)\n\n/-- An auxiliary attribute used to store the names of the additive versions of declarations\nthat have been processed by `to_additive`. -/\n@[user_attribute]\nmeta def aux_attr : user_attribute (name_map name) name :=\n{ name := `to_additive_aux,\n descr := \"Auxiliary attribute for `to_additive`. DON'T USE IT\",\n parser := failed,\n cache_cfg := ⟨λ ns,\n ns.mfoldl\n (λ dict n', do\n let n := match n' with\n | name.mk_string s pre := if s = \"_to_additive\" then pre else n'\n | _ := n'\n end,\n param ← aux_attr.get_param_untyped n',\n pure $ dict.insert n param.app_arg.const_name)\n mk_name_map, []⟩ }\n\nend performance_hack\n\nsection extra_attributes\n\n/--\nAn attribute that tells `@[to_additive]` that certain arguments of this definition are not\ninvolved when using `@[to_additive]`.\nThis helps the heuristic of `@[to_additive]` by also transforming definitions if `ℕ` or another\nfixed type occurs as one of these arguments.\n-/\n@[user_attribute]\nmeta def ignore_args_attr : user_attribute (name_map $ list ℕ) (list ℕ) :=\n{ name := `to_additive_ignore_args,\n descr :=\n \"Auxiliary attribute for `to_additive` stating that certain arguments are not additivized.\",\n cache_cfg :=\n ⟨λ ns, ns.mfoldl\n (λ dict n, do\n param ← ignore_args_attr.get_param_untyped n, -- see Note [user attribute parameters]\n return $ dict.insert n (param.to_list expr.to_nat).iget)\n mk_name_map, []⟩,\n parser := (lean.parser.small_nat)* }\n\n/--\nAn attribute that is automatically added to declarations tagged with `@[to_additive]`, if needed.\n\nThis attribute tells which argument is the type where this declaration uses the multiplicative\nstructure. If there are multiple argument, we typically tag the first one.\nIf this argument contains a fixed type, this declaration will note be additivized.\nSee the Heuristics section of `to_additive.attr` for more details.\n\nIf a declaration is not tagged, it is presumed that the first argument is relevant.\n`@[to_additive]` uses the function `to_additive.first_multiplicative_arg` to automatically tag\ndeclarations. It is ok to update it manually if the automatic tagging made an error.\n\nImplementation note: we only allow exactly 1 relevant argument, even though some declarations\n(like `prod.group`) have multiple arguments with a multiplicative structure on it.\nThe reason is that whether we additivize a declaration is an all-or-nothing decision, and if\nwe will not be able to additivize declarations that (e.g.) talk about multiplication on `ℕ × α`\nanyway.\n\nWarning: adding `@[to_additive_reorder]` with an equal or smaller number than the number in this\nattribute is currently not supported.\n-/\n@[user_attribute]\nmeta def relevant_arg_attr : user_attribute (name_map ℕ) ℕ :=\n{ name := `to_additive_relevant_arg,\n descr :=\n \"Auxiliary attribute for `to_additive` stating which arguments are the types with a \" ++\n \"multiplicative structure.\",\n cache_cfg :=\n ⟨λ ns, ns.mfoldl\n (λ dict n, do\n param ← relevant_arg_attr.get_param_untyped n, -- see Note [user attribute parameters]\n -- we subtract 1 from the values provided by the user.\n return $ dict.insert n $ param.to_nat.iget.pred)\n mk_name_map, []⟩,\n parser := lean.parser.small_nat }\n\n/--\nAn attribute that stores all the declarations that needs their arguments reordered when\napplying `@[to_additive]`. Currently, we only support swapping consecutive arguments.\nThe list of the natural numbers contains the positions of the first of the two arguments\nto be swapped.\nIf the first two arguments are swapped, the first two universe variables are also swapped.\nExample: `@[to_additive_reorder 1 4]` swaps the first two arguments and the arguments in\npositions 4 and 5.\n-/\n@[user_attribute]\nmeta def reorder_attr : user_attribute (name_map $ list ℕ) (list ℕ) :=\n{ name := `to_additive_reorder,\n descr :=\n \"Auxiliary attribute for `to_additive` that stores arguments that need to be reordered.\",\n cache_cfg :=\n ⟨λ ns, ns.mfoldl\n (λ dict n, do\n param ← reorder_attr.get_param_untyped n, -- see Note [user attribute parameters]\n return $ dict.insert n (param.to_list expr.to_nat).iget)\n mk_name_map, []⟩,\n parser := do\n l ← (lean.parser.small_nat)*,\n guard (l.all (≠ 0)) <|> exceptional.fail \"The reorder positions must be positive\",\n return l }\n\nend extra_attributes\n\n/--\nFind the first argument of `nm` that has a multiplicative type-class on it.\nReturns 1 if there are no types with a multiplicative class as arguments.\nE.g. `prod.group` returns 1, and `pi.has_one` returns 2.\n-/\nmeta def first_multiplicative_arg (nm : name) : tactic ℕ := do\n d ← get_decl nm,\n let (es, _) := d.type.pi_binders,\n l ← es.mmap_with_index $ λ n bi, do\n { let tgt := bi.type.pi_codomain,\n let n_bi := bi.type.pi_binders.fst.length,\n tt ← has_attribute' `to_additive tgt.get_app_fn.const_name | return none,\n let n2 := tgt.get_app_args.head.get_app_fn.match_var.map $ λ m, n + n_bi - m,\n return $ n2 },\n let l := l.reduce_option,\n return $ if l = [] then 1 else l.foldr min l.head\n\n/-- A command that can be used to have future uses of `to_additive` change the `src` namespace\nto the `tgt` namespace.\n\nFor example:\n```\nrun_cmd to_additive.map_namespace `quotient_group `quotient_add_group\n```\n\nLater uses of `to_additive` on declarations in the `quotient_group` namespace will be created\nin the `quotient_add_group` namespaces.\n-/\nmeta def map_namespace (src tgt : name) : command :=\ndo let n := src.mk_string \"_to_additive\",\n let decl := declaration.thm n [] `(unit) (pure (reflect ())),\n add_decl decl,\n aux_attr.set n tgt tt\n\n/-- `value_type` is the type of the arguments that can be provided to `to_additive`.\n`to_additive.parser` parses the provided arguments:\n* `replace_all`: replace all multiplicative declarations, do not use the heuristic.\n* `trace`: output the generated additive declaration.\n* `tgt : name`: the name of the target (the additive declaration).\n* `doc`: an optional doc string.\n* if `allow_auto_name` is `ff` (default) then `@[to_additive]` will check whether the given name\n can be auto-generated.\n-/\n@[derive has_reflect, derive inhabited]\nstructure value_type : Type :=\n(replace_all : bool)\n(trace : bool)\n(tgt : name)\n(doc : option string)\n(allow_auto_name : bool)\n\n/-- `add_comm_prefix x s` returns `\"comm_\" ++ s` if `x = tt` and `s` otherwise. -/\nmeta def add_comm_prefix : bool → string → string\n| tt s := \"comm_\" ++ s\n| ff s := s\n\n/-- Dictionary used by `to_additive.guess_name` to autogenerate names. -/\nmeta def tr : bool → list string → list string\n| is_comm (\"one\" :: \"le\" :: s) := add_comm_prefix is_comm \"nonneg\" :: tr ff s\n| is_comm (\"one\" :: \"lt\" :: s) := add_comm_prefix is_comm \"pos\" :: tr ff s\n| is_comm (\"le\" :: \"one\" :: s) := add_comm_prefix is_comm \"nonpos\" :: tr ff s\n| is_comm (\"lt\" :: \"one\" :: s) := add_comm_prefix is_comm \"neg\" :: tr ff s\n| is_comm (\"mul\" :: \"single\" :: s) := add_comm_prefix is_comm \"single\" :: tr ff s\n| is_comm (\"mul\" :: \"support\" :: s) := add_comm_prefix is_comm \"support\" :: tr ff s\n| is_comm (\"mul\" :: \"tsupport\" :: s) := add_comm_prefix is_comm \"tsupport\" :: tr ff s\n| is_comm (\"mul\" :: \"indicator\" :: s) := add_comm_prefix is_comm \"indicator\" :: tr ff s\n| is_comm (\"mul\" :: s) := add_comm_prefix is_comm \"add\" :: tr ff s\n| is_comm (\"smul\" :: s) := add_comm_prefix is_comm \"vadd\" :: tr ff s\n| is_comm (\"inv\" :: s) := add_comm_prefix is_comm \"neg\" :: tr ff s\n| is_comm (\"div\" :: s) := add_comm_prefix is_comm \"sub\" :: tr ff s\n| is_comm (\"one\" :: s) := add_comm_prefix is_comm \"zero\" :: tr ff s\n| is_comm (\"prod\" :: s) := add_comm_prefix is_comm \"sum\" :: tr ff s\n| is_comm (\"finprod\" :: s) := add_comm_prefix is_comm \"finsum\" :: tr ff s\n| is_comm (\"pow\" :: s) := add_comm_prefix is_comm \"nsmul\" :: tr ff s\n| is_comm (\"npow\" :: s) := add_comm_prefix is_comm \"nsmul\" :: tr ff s\n| is_comm (\"zpow\" :: s) := add_comm_prefix is_comm \"zsmul\" :: tr ff s\n| is_comm (\"is\" :: \"square\" :: s) := add_comm_prefix is_comm \"even\" :: tr ff s\n| is_comm (\"is\" :: \"regular\" :: s) := add_comm_prefix is_comm \"is_add_regular\" :: tr ff s\n| is_comm (\"is\" :: \"left\" :: \"regular\" :: s) :=\n add_comm_prefix is_comm \"is_add_left_regular\" :: tr ff s\n| is_comm (\"is\" :: \"right\" :: \"regular\" :: s) :=\n add_comm_prefix is_comm \"is_add_right_regular\" :: tr ff s\n| is_comm (\"monoid\" :: s) := (\"add_\" ++ add_comm_prefix is_comm \"monoid\") :: tr ff s\n| is_comm (\"submonoid\" :: s) := (\"add_\" ++ add_comm_prefix is_comm \"submonoid\") :: tr ff s\n| is_comm (\"group\" :: s) := (\"add_\" ++ add_comm_prefix is_comm \"group\") :: tr ff s\n| is_comm (\"subgroup\" :: s) := (\"add_\" ++ add_comm_prefix is_comm \"subgroup\") :: tr ff s\n| is_comm (\"semigroup\" :: s) := (\"add_\" ++ add_comm_prefix is_comm \"semigroup\") :: tr ff s\n| is_comm (\"magma\" :: s) := (\"add_\" ++ add_comm_prefix is_comm \"magma\") :: tr ff s\n| is_comm (\"haar\" :: s) := (\"add_\" ++ add_comm_prefix is_comm \"haar\") :: tr ff s\n| is_comm (\"prehaar\" :: s) := (\"add_\" ++ add_comm_prefix is_comm \"prehaar\") :: tr ff s\n| is_comm (\"unit\" :: s) := (\"add_\" ++ add_comm_prefix is_comm \"unit\") :: tr ff s\n| is_comm (\"units\" :: s) := (\"add_\" ++ add_comm_prefix is_comm \"units\") :: tr ff s\n| is_comm (\"comm\" :: s) := tr tt s\n| is_comm (x :: s) := (add_comm_prefix is_comm x :: tr ff s)\n| tt [] := [\"comm\"]\n| ff [] := []\n\n/-- Autogenerate target name for `to_additive`. -/\nmeta def guess_name : string → string :=\nstring.map_tokens ''' $\nλ s, string.intercalate (string.singleton '_') $\ntr ff (s.split_on '_')\n\n/-- Return the provided target name or autogenerate one if one was not provided. -/\nmeta def target_name (src tgt : name) (dict : name_map name) (allow_auto_name : bool) :\n tactic name :=\n(if tgt.get_prefix ≠ name.anonymous ∨ allow_auto_name -- `tgt` is a full name\n then pure tgt\n else match src with\n | (name.mk_string s pre) :=\n do let tgt_auto := guess_name s,\n guard (tgt.to_string ≠ tgt_auto ∨ tgt = src)\n <|> trace (\"`to_additive \" ++ src.to_string ++ \"`: correctly autogenerated target \" ++\n \"name, you may remove the explicit \" ++ tgt_auto ++ \" argument.\"),\n pure $ name.mk_string\n (if tgt = name.anonymous then tgt_auto else tgt.to_string)\n (pre.map_prefix dict.find)\n | _ := fail (\"to_additive: can't transport \" ++ src.to_string)\n end) >>=\n(λ res,\n if res = src ∧ tgt ≠ src\n then fail (\"to_additive: can't transport \" ++ src.to_string ++ \" to itself.\nGive the desired additive name explicitly using `@[to_additive additive_name]`. \")\n else pure res)\n\n/-- the parser for the arguments to `to_additive`. -/\nmeta def parser : lean.parser value_type :=\ndo\n bang ← option.is_some <$> (tk \"!\")?,\n ques ← option.is_some <$> (tk \"?\")?,\n tgt ← ident?,\n e ← texpr?,\n doc ← match e with\n | some pe := some <$> ((to_expr pe >>= eval_expr string) : tactic string)\n | none := pure none\n end,\n return ⟨bang, ques, tgt.get_or_else name.anonymous, doc, ff⟩\n\nprivate meta def proceed_fields_aux (src tgt : name) (prio : ℕ) (f : name → tactic (list string)) :\n command :=\ndo\n src_fields ← f src,\n tgt_fields ← f tgt,\n guard (src_fields.length = tgt_fields.length) <|>\n fail (\"Failed to map fields of \" ++ src.to_string),\n (src_fields.zip tgt_fields).mmap' $\n λ names, guard (names.fst = names.snd) <|>\n aux_attr.set (src.append names.fst) (tgt.append names.snd) tt prio\n\n/-- Add the `aux_attr` attribute to the structure fields of `src`\nso that future uses of `to_additive` will map them to the corresponding `tgt` fields. -/\nmeta def proceed_fields (env : environment) (src tgt : name) (prio : ℕ) : command :=\nlet aux := proceed_fields_aux src tgt prio in\ndo\naux (λ n, pure $ list.map name.to_string $ (env.structure_fields n).get_or_else []) >>\naux (λ n, (list.map (λ (x : name), \"to_\" ++ x.to_string) <$> get_tagged_ancestors n)) >>\naux (λ n, (env.constructors_of n).mmap $\n λ cs, match cs with\n | (name.mk_string s pre) :=\n (guard (pre = n) <|> fail \"Bad constructor name\") >>\n pure s\n | _ := fail \"Bad constructor name\"\n end)\n\n/--\nThe attribute `to_additive` can be used to automatically transport theorems\nand definitions (but not inductive types and structures) from a multiplicative\ntheory to an additive theory.\n\nTo use this attribute, just write:\n\n```\n@[to_additive]\ntheorem mul_comm' {α} [comm_semigroup α] (x y : α) : x * y = y * x := comm_semigroup.mul_comm\n```\n\nThis code will generate a theorem named `add_comm'`. It is also\npossible to manually specify the name of the new declaration:\n\n```\n@[to_additive add_foo]\ntheorem foo := sorry\n```\n\nAn existing documentation string will _not_ be automatically used, so if the theorem or definition\nhas a doc string, a doc string for the additive version should be passed explicitly to\n`to_additive`.\n\n```\n/-- Multiplication is commutative -/\n@[to_additive \"Addition is commutative\"]\ntheorem mul_comm' {α} [comm_semigroup α] (x y : α) : x * y = y * x := comm_semigroup.mul_comm\n```\n\nThe transport tries to do the right thing in most cases using several\nheuristics described below. However, in some cases it fails, and\nrequires manual intervention.\n\nIf the declaration to be transported has attributes which need to be\ncopied to the additive version, then `to_additive` should come last:\n\n```\n@[simp, to_additive] lemma mul_one' {G : Type*} [group G] (x : G) : x * 1 = x := mul_one x\n```\n\nThe following attributes are supported and should be applied correctly by `to_additive` to\nthe new additivized declaration, if they were present on the original one:\n```\nreducible, _refl_lemma, simp, norm_cast, instance, refl, symm, trans, elab_as_eliminator, no_rsimp,\ncontinuity, ext, ematch, measurability, alias, _ext_core, _ext_lemma_core, nolint\n```\n\nThe exception to this rule is the `simps` attribute, which should come after `to_additive`:\n\n```\n@[to_additive, simps]\ninstance {M N} [has_mul M] [has_mul N] : has_mul (M × N) := ⟨λ p q, ⟨p.1 * q.1, p.2 * q.2⟩⟩\n```\n\nAdditionally the `mono` attribute is not handled by `to_additive` and should be applied afterwards\nto both the original and additivized lemma.\n\n## Implementation notes\n\nThe transport process generally works by taking all the names of\nidentifiers appearing in the name, type, and body of a declaration and\ncreating a new declaration by mapping those names to additive versions\nusing a simple string-based dictionary and also using all declarations\nthat have previously been labeled with `to_additive`.\n\nIn the `mul_comm'` example above, `to_additive` maps:\n* `mul_comm'` to `add_comm'`,\n* `comm_semigroup` to `add_comm_semigroup`,\n* `x * y` to `x + y` and `y * x` to `y + x`, and\n* `comm_semigroup.mul_comm'` to `add_comm_semigroup.add_comm'`.\n\n### Heuristics\n\n`to_additive` uses heuristics to determine whether a particular identifier has to be\nmapped to its additive version. The basic heuristic is\n\n* Only map an identifier to its additive version if its first argument doesn't\n contain any unapplied identifiers.\n\nExamples:\n* `@has_mul.mul ℕ n m` (i.e. `(n * m : ℕ)`) will not change to `+`, since its\n first argument is `ℕ`, an identifier not applied to any arguments.\n* `@has_mul.mul (α × β) x y` will change to `+`. It's first argument contains only the identifier\n `prod`, but this is applied to arguments, `α` and `β`.\n* `@has_mul.mul (α × ℤ) x y` will not change to `+`, since its first argument contains `ℤ`.\n\nThe reasoning behind the heuristic is that the first argument is the type which is \"additivized\",\nand this usually doesn't make sense if this is on a fixed type.\n\nThere are some exceptions to this heuristic:\n\n* Identifiers that have the `@[to_additive]` attribute are ignored.\n For example, multiplication in `↥Semigroup` is replaced by addition in `↥AddSemigroup`.\n* If an identifier `d` has attribute `@[to_additive_relevant_arg n]` then the argument\n in position `n` is checked for a fixed type, instead of checking the first argument.\n `@[to_additive]` will automatically add the attribute `@[to_additive_relevant_arg n]` to a\n declaration when the first argument has no multiplicative type-class, but argument `n` does.\n* If an identifier has attribute `@[to_additive_ignore_args n1 n2 ...]` then all the arguments in\n positions `n1`, `n2`, ... will not be checked for unapplied identifiers (start counting from 1).\n For example, `cont_mdiff_map` has attribute `@[to_additive_ignore_args 21]`, which means\n that its 21st argument `(n : with_top ℕ)` can contain `ℕ`\n (usually in the form `has_top.top ℕ ...`) and still be additivized.\n So `@has_mul.mul (C^∞⟮I, N; I', G⟯) _ f g` will be additivized.\n\n### Troubleshooting\n\nIf `@[to_additive]` fails because the additive declaration raises a type mismatch, there are\nvarious things you can try.\nThe first thing to do is to figure out what `@[to_additive]` did wrong by looking at the type\nmismatch error.\n\n* Option 1: It additivized a declaration `d` that should remain multiplicative. Solution:\n * Make sure the first argument of `d` is a type with a multiplicative structure. If not, can you\n reorder the (implicit) arguments of `d` so that the first argument becomes a type with a\n multiplicative structure (and not some indexing type)?\n The reason is that `@[to_additive]` doesn't additivize declarations if their first argument\n contains fixed types like `ℕ` or `ℝ`. See section Heuristics.\n If the first argument is not the argument with a multiplicative type-class, `@[to_additive]`\n should have automatically added the attribute `@[to_additive_relevant_arg]` to the declaration.\n You can test this by running the following (where `d` is the full name of the declaration):\n ```\n run_cmd to_additive.relevant_arg_attr.get_param `d >>= tactic.trace\n ```\n The expected output is `n` where the `n`-th argument of `d` is a type (family) with a\n multiplicative structure on it. If you get a different output (or a failure), you could add\n the attribute `@[to_additive_relevant_arg n]` manually, where `n` is an argument with a\n multiplicative structure.\n* Option 2: It didn't additivize a declaration that should be additivized.\n This happened because the heuristic applied, and the first argument contains a fixed type,\n like `ℕ` or `ℝ`. Solutions:\n * If the fixed type has an additive counterpart (like `↥Semigroup`), give it the `@[to_additive]`\n attribute.\n * If the fixed type occurs inside the `k`-th argument of a declaration `d`, and the\n `k`-th argument is not connected to the multiplicative structure on `d`, consider adding\n attribute `[to_additive_ignore_args k]` to `d`.\n * If you want to disable the heuristic and replace all multiplicative\n identifiers with their additive counterpart, use `@[to_additive!]`.\n* Option 3: Arguments / universe levels are incorrectly ordered in the additive version.\n This likely only happens when the multiplicative declaration involves `pow`/`^`. Solutions:\n * Ensure that the order of arguments of all relevant declarations are the same for the\n multiplicative and additive version. This might mean that arguments have an \"unnatural\" order\n (e.g. `monoid.npow n x` corresponds to `x ^ n`, but it is convenient that `monoid.npow` has this\n argument order, since it matches `add_monoid.nsmul n x`.\n * If this is not possible, add the `[to_additive_reorder k]` to the multiplicative declaration\n to indicate that the `k`-th and `(k+1)`-st arguments are reordered in the additive version.\n\nIf neither of these solutions work, and `to_additive` is unable to automatically generate the\nadditive version of a declaration, manually write and prove the additive version.\nOften the proof of a lemma/theorem can just be the multiplicative version of the lemma applied to\n`multiplicative G`.\nAfterwards, apply the attribute manually:\n\n```\nattribute [to_additive foo_add_bar] foo_bar\n```\n\nThis will allow future uses of `to_additive` to recognize that\n`foo_bar` should be replaced with `foo_add_bar`.\n\n### Handling of hidden definitions\n\nBefore transporting the “main” declaration `src`, `to_additive` first\nscans its type and value for names starting with `src`, and transports\nthem. This includes auxiliary definitions like `src._match_1`,\n`src._proof_1`.\n\nIn addition to transporting the “main” declaration, `to_additive` transports\nits equational lemmas and tags them as equational lemmas for the new declaration,\nattributes present on the original equational lemmas are also transferred first (notably\n`_refl_lemma`).\n\n### Structure fields and constructors\n\nIf `src` is a structure, then `to_additive` automatically adds\nstructure fields to its mapping, and similarly for constructors of\ninductive types.\n\nFor new structures this means that `to_additive` automatically handles\ncoercions, and for old structures it does the same, if ancestry\ninformation is present in `@[ancestor]` attributes. The `ancestor`\nattribute must come before the `to_additive` attribute, and it is\nessential that the order of the base structures passed to `ancestor` matches\nbetween the multiplicative and additive versions of the structure.\n\n### Name generation\n\n* If `@[to_additive]` is called without a `name` argument, then the\n new name is autogenerated. First, it takes the longest prefix of\n the source name that is already known to `to_additive`, and replaces\n this prefix with its additive counterpart. Second, it takes the last\n part of the name (i.e., after the last dot), and replaces common\n name parts (“mul”, “one”, “inv”, “prod”) with their additive versions.\n\n* Namespaces can be transformed using `map_namespace`. For example:\n ```\n run_cmd to_additive.map_namespace `quotient_group `quotient_add_group\n ```\n\n Later uses of `to_additive` on declarations in the `quotient_group`\n namespace will be created in the `quotient_add_group` namespaces.\n\n* If `@[to_additive]` is called with a `name` argument `new_name`\n /without a dot/, then `to_additive` updates the prefix as described\n above, then replaces the last part of the name with `new_name`.\n\n* If `@[to_additive]` is called with a `name` argument\n `new_namespace.new_name` /with a dot/, then `to_additive` uses this\n new name as is.\n\nAs a safety check, in the first case `to_additive` double checks\nthat the new name differs from the original one.\n\n-/\n@[user_attribute]\nprotected meta def attr : user_attribute unit value_type :=\n{ name := `to_additive,\n descr := \"Transport multiplicative to additive\",\n parser := parser,\n after_set := some $ λ src prio persistent, do\n guard persistent <|> fail \"`to_additive` can't be used as a local attribute\",\n env ← get_env,\n val ← attr.get_param src,\n dict ← aux_attr.get_cache,\n ignore ← ignore_args_attr.get_cache,\n relevant ← relevant_arg_attr.get_cache,\n reorder ← reorder_attr.get_cache,\n tgt ← target_name src val.tgt dict val.allow_auto_name,\n aux_attr.set src tgt tt,\n let dict := dict.insert src tgt,\n first_mult_arg ← first_multiplicative_arg src,\n when (first_mult_arg ≠ 1) $ relevant_arg_attr.set src first_mult_arg tt,\n if env.contains tgt\n then proceed_fields env src tgt prio\n else do\n transform_decl_with_prefix_dict dict val.replace_all val.trace relevant ignore reorder src tgt\n [`reducible, `_refl_lemma, `simp, `norm_cast, `instance, `refl, `symm, `trans,\n `elab_as_eliminator, `no_rsimp, `continuity, `ext, `ematch, `measurability, `alias,\n `_ext_core, `_ext_lemma_core, `nolint, `protected],\n mwhen (has_attribute' `simps src)\n (trace \"Apply the simps attribute after the to_additive attribute\"),\n mwhen (has_attribute' `mono src)\n (trace $ \"to_additive does not work with mono, apply the mono attribute to both\" ++\n \"versions after\"),\n match val.doc with\n | some doc := add_doc_string tgt doc\n | none := skip\n end }\n\nadd_tactic_doc\n{ name := \"to_additive\",\n category := doc_category.attr,\n decl_names := [`to_additive.attr],\n tags := [\"transport\", \"environment\", \"lemma derivation\"] }\n\nend to_additive\n\n/- map operations -/\nattribute [to_additive] has_mul has_one has_inv has_div\n/- the following types are supported by `@[to_additive]` and mapped to themselves. -/\nattribute [to_additive empty] empty\nattribute [to_additive pempty] pempty\nattribute [to_additive punit] punit\nattribute [to_additive unit] unit\n\nsection linter\n\nopen tactic expr\n\n/-- A linter that checks that multiplicative and additive lemmas have both doc strings if one of\nthem has one -/\n@[linter] meta def linter.to_additive_doc : linter :=\n{ test := (λ d, do\n let mul_name := d.to_name,\n dict ← to_additive.aux_attr.get_cache,\n match dict.find mul_name with\n | some add_name := do\n mul_doc ← try_core $ doc_string mul_name,\n add_doc ← try_core $ doc_string add_name,\n match mul_doc.is_some, add_doc.is_some with\n | tt, ff := return $ some $ \"declaration has a docstring, but its additive version `\" ++\n add_name.to_string ++ \"` does not. You might want to pass a string argument to \" ++\n \"`to_additive`.\"\n | ff, tt := return $ some $ \"declaration has no docstring, but its additive version `\" ++\n add_name.to_string ++ \"` does. You might want to add a doc string to the declaration.\"\n | _, _ := return none\n end\n | none := return none\n end),\n auto_decls := ff,\n no_errors_found := \"Multiplicative and additive lemmas are consistently documented\",\n errors_found := \"The following declarations have doc strings, but their additive versions do \" ++\n \"not (or vice versa).\",\n is_fast := ff }\n\nend linter\n", "meta": {"author": "saisurbehera", "repo": "mathProof", "sha": "57c6bfe75652e9d3312d8904441a32aff7d6a75e", "save_path": "github-repos/lean/saisurbehera-mathProof", "path": "github-repos/lean/saisurbehera-mathProof/mathProof-57c6bfe75652e9d3312d8904441a32aff7d6a75e/src/tertiary_packages/mathlib/src/algebra/group/to_additive.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.39606816627404173, "lm_q2_score": 0.08756384249943205, "lm_q1q2_score": 0.034681250530659055}} {"text": "/-\nCopyright (c) 2020 Floris van Doorn. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Floris van Doorn\n\n! This file was ported from Lean 3 source module tactic.congr\n! leanprover-community/mathlib commit 28b66e1a5de3072ff425b43cf9ebb9a03312b435\n! Please do not edit these lines, except to modify the commit id\n! if you have ported upstream changes.\n-/\nimport Mathbin.Tactic.Lint.Default\nimport Mathbin.Tactic.Ext\n\n/-!\n# Congruence and related tactics\n\nThis file contains the tactic `congr'`, which is an extension of `congr`, and various tactics\nusing `congr'` internally.\n\n`congr'` has some advantages over `congr`:\n* It turns `↔` to equalities, before trying another congr lemma\n* You can write `congr' n` to give the maximal depth of recursive applications. This is useful if\n `congr` breaks down the goal to aggressively, and the resulting goals are false.\n* You can write `congr' with ...` to do `congr', ext ...` in a single tactic.\n\nOther tactics in this file:\n* `rcongr`: repeatedly apply `congr'` and `ext.`\n* `convert`: like `exact`, but produces an equality goal if the type doesn't match.\n* `convert_to`: changes the goal, if you prove an equality between the old goal and the new goal.\n* `ac_change`: like `convert_to`, but uses `ac_refl` to discharge the goals.\n-/\n\n\nopen Tactic\n\n/- ./././Mathport/Syntax/Translate/Tactic/Mathlib/Core.lean:38:34: unsupported: setup_tactic_parser -/\nnamespace Tactic\n\n/-- Apply the constant `iff_of_eq` to the goal. -/\nunsafe def apply_iff_congr_core : tactic Unit :=\n applyc `` iff_of_eq\n#align tactic.apply_iff_congr_core tactic.apply_iff_congr_core\n\n/-- The main part of the body for the loop in `congr'`. This will try to replace a goal `f x = f y`\n with `x = y`. Also has support for `==` and `↔`. -/\nunsafe def congr_core' : tactic Unit := do\n let tgt ← target\n apply_eq_congr_core tgt <|>\n apply_heq_congr_core <|> apply_iff_congr_core <|> fail \"congr tactic failed\"\n#align tactic.congr_core' tactic.congr_core'\n\n-- failed to format: unknown constant 'term.pseudo.antiquot'\n/--\n The main function in `convert_to`. Changes the goal to `r` and a proof obligation that the goal\n is equal to `r`. -/\n unsafe\n def\n convert_to_core\n ( r : pexpr ) : tactic Unit\n := do let tgt ← target let h ← to_expr ` `( ( _ : $ ( tgt ) = $ ( r ) ) ) rewrite_target h swap\n#align tactic.convert_to_core tactic.convert_to_core\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:330:4: warning: unsupported (TODO): `[tacs] -/\n/- ./././Mathport/Syntax/Translate/Expr.lean:330:4: warning: unsupported (TODO): `[tacs] -/\n/-- Attempts to prove the goal by proof irrelevance, but avoids unifying universe metavariables\nto do so. -/\nunsafe def by_proof_irrel : tactic Unit := do\n let tgt ← target\n let @expr.const tt n [level.zero] ← pure tgt.get_app_fn\n if n = `` Eq then sorry else if n = `` HEq then sorry else failed\n#align tactic.by_proof_irrel tactic.by_proof_irrel\n\n/-- Same as the `congr` tactic, but takes an optional argument which gives\nthe depth of recursive applications.\n* This is useful when `congr` is too aggressive in breaking down the goal.\n* For example, given `⊢ f (g (x + y)) = f (g (y + x))`, `congr'` produces the goals `⊢ x = y`\n and `⊢ y = x`, while `congr' 2` produces the intended `⊢ x + y = y + x`.\n* If, at any point, a subgoal matches a hypothesis then the subgoal will be closed.\n-/\nunsafe def congr' : Option ℕ → tactic Unit\n | o =>\n focus1 <|\n assumption <|>\n reflexivity Transparency.none <|>\n by_proof_irrel <|>\n (guard (o ≠ some 0) >> congr_core') >> all_goals' (try (congr' (Nat.pred <$> o))) <|>\n reflexivity\n#align tactic.congr' tactic.congr'\n\nnamespace Interactive\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:207:4: warning: unsupported notation `parser.optional -/\n/- ./././Mathport/Syntax/Translate/Expr.lean:207:4: warning: unsupported notation `parser.optional -/\n/- ./././Mathport/Syntax/Translate/Expr.lean:207:4: warning: unsupported notation `parser.many -/\n/- ./././Mathport/Syntax/Translate/Expr.lean:207:4: warning: unsupported notation `parser.optional -/\n/-- Same as the `congr` tactic, but takes an optional argument which gives\nthe depth of recursive applications.\n* This is useful when `congr` is too aggressive in breaking down the goal.\n* For example, given `⊢ f (g (x + y)) = f (g (y + x))`, `congr'` produces the goals `⊢ x = y`\n and `⊢ y = x`, while `congr' 2` produces the intended `⊢ x + y = y + x`.\n* If, at any point, a subgoal matches a hypothesis then the subgoal will be closed.\n* You can use `congr' with p (: n)?` to call `ext p (: n)?` to all subgoals generated by `congr'`.\n For example, if the goal is `⊢ f '' s = g '' s` then `congr' with x` generates the goal\n `x : α ⊢ f x = g x`.\n-/\nunsafe def congr' (n : parse (parser.optional (with_desc \"n\" small_nat))) :\n parse\n (parser.optional\n (tk \"with\" *> Prod.mk <$> parser.many rintro_patt_parse_hi <*>\n parser.optional (tk \":\" *> small_nat))) →\n tactic Unit\n | none => tactic.congr' n\n | some ⟨p, m⟩ => focus1 (tactic.congr' n >> all_goals' (tactic.ext p.join m $> ()))\n#align tactic.interactive.congr' tactic.interactive.congr'\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:207:4: warning: unsupported notation `parser.many -/\n/-- Repeatedly and apply `congr'` and `ext`, using the given patterns as arguments for `ext`.\n\nThere are two ways this tactic stops:\n* `congr'` fails (makes no progress), after having already applied `ext`.\n* `congr'` canceled out the last usage of `ext`. In this case, the state is reverted to before\n the `congr'` was applied.\n\nFor example, when the goal is\n```lean\n⊢ (λ x, f x + 3) '' s = (λ x, g x + 3) '' s\n```\nthen `rcongr x` produces the goal\n```lean\nx : α ⊢ f x = g x\n```\nThis gives the same result as `congr', ext x, congr'`.\n\nIn contrast, `congr'` would produce\n```lean\n⊢ (λ x, f x + 3) = (λ x, g x + 3)\n```\nand `congr' with x` (or `congr', ext x`) would produce\n```lean\nx : α ⊢ f x + 3 = g x + 3\n```\n-/\nunsafe def rcongr : parse (List.join <$> parser.many rintro_patt_parse_hi) → tactic Unit\n | ps => do\n let t ← target\n let qs ← try_core (tactic.ext ps none)\n let some () ←\n try_core\n (tactic.congr' none >>\n (done <|> do\n let s ← target\n guard <| ¬s == t)) |\n skip\n done <|> rcongr (qs ps)\n#align tactic.interactive.rcongr tactic.interactive.rcongr\n\nadd_tactic_doc\n { Name := \"congr'\"\n category := DocCategory.tactic\n declNames := [`tactic.interactive.congr', `tactic.interactive.congr, `tactic.interactive.rcongr]\n tags := [\"congruence\"]\n inheritDescriptionFrom := `tactic.interactive.congr' }\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:207:4: warning: unsupported notation `parser.optional -/\n/- ./././Mathport/Syntax/Translate/Expr.lean:207:4: warning: unsupported notation `parser.optional -/\n-- failed to format: unknown constant 'term.pseudo.antiquot'\n/--\n The `exact e` and `refine e` tactics require a term `e` whose type is\n definitionally equal to the goal. `convert e` is similar to `refine e`,\n but the type of `e` is not required to exactly match the\n goal. Instead, new goals are created for differences between the type\n of `e` and the goal. For example, in the proof state\n \n ```lean\n n : ℕ,\n e : prime (2 * n + 1)\n ⊢ prime (n + n + 1)\n ```\n \n the tactic `convert e` will change the goal to\n \n ```lean\n ⊢ n + n = 2 * n\n ```\n \n In this example, the new goal can be solved using `ring`.\n \n The `convert` tactic applies congruence lemmas eagerly before reducing,\n therefore it can fail in cases where `exact` succeeds:\n ```lean\n def p (n : ℕ) := true\n example (h : p 0) : p 1 := by exact h -- succeeds\n example (h : p 0) : p 1 := by convert h -- fails, with leftover goal `1 = 0`\n ```\n \n If `x y : t`, and an instance `subsingleton t` is in scope, then any goals of the form\n `x = y` are solved automatically.\n \n The syntax `convert ← e` will reverse the direction of the new goals\n (producing `⊢ 2 * n = n + n` in this example).\n \n Internally, `convert e` works by creating a new goal asserting that\n the goal equals the type of `e`, then simplifying it using\n `congr'`. The syntax `convert e using n` can be used to control the\n depth of matching (like `congr' n`). In the example, `convert e using\n 1` would produce a new goal `⊢ n + n + 1 = 2 * n + 1`.\n -/\n unsafe\n def\n convert\n ( sym : parse ( with_desc \"←\" ( parser.optional ( tk \"<-\" ) ) ) )\n ( r : parse texpr )\n ( n : parse ( parser.optional ( tk \"using\" *> small_nat ) ) )\n : tactic Unit\n :=\n do\n let tgt ← target\n let u ← infer_type tgt\n let r ← i_to_expr ` `( ( $ ( r ) : ( _ : $ ( u ) ) ) )\n let src ← infer_type r\n let src ← simp_lemmas.mk . dsimplify [ ] src { failIfUnchanged := false }\n let\n v\n ←\n to_expr\n (\n if\n Sym . isSome\n then\n ` `( $ ( src ) = $ ( tgt ) )\n else\n ` `( $ ( tgt ) = $ ( src ) )\n )\n true\n false\n >>=\n mk_meta_var\n ( if Sym then mk_eq_mp v r else mk_eq_mpr v r ) >>= tactic.exact\n let gs ← get_goals\n set_goals [ v ]\n try ( tactic.congr' n )\n let gs' ← get_goals\n set_goals <| gs' ++ gs\n#align tactic.interactive.convert tactic.interactive.convert\n\nadd_tactic_doc\n { Name := \"convert\"\n category := DocCategory.tactic\n declNames := [`tactic.interactive.convert]\n tags := [\"congruence\"] }\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:330:4: warning: unsupported (TODO): `[tacs] -/\n/- ./././Mathport/Syntax/Translate/Expr.lean:207:4: warning: unsupported notation `parser.optional -/\n/-- `convert_to g using n` attempts to change the current goal to `g`, but unlike `change`,\nit will generate equality proof obligations using `congr' n` to resolve discrepancies.\n`convert_to g` defaults to using `congr' 1`.\n\n`convert_to` is similar to `convert`, but `convert_to` takes a type (the desired subgoal) while\n`convert` takes a proof term.\nThat is, `convert_to g using n` is equivalent to `convert (_ : g) using n`.\n-/\nunsafe def convert_to (r : parse texpr) (n : parse (parser.optional (tk \"using\" *> small_nat))) :\n tactic Unit :=\n match n with\n | none => convert_to_core r >> sorry\n | some 0 => convert_to_core r\n | some o => convert_to_core r >> tactic.congr' o\n#align tactic.interactive.convert_to tactic.interactive.convert_to\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:207:4: warning: unsupported notation `parser.optional -/\n/-- `ac_change g using n` is `convert_to g using n` followed by `ac_refl`. It is useful for\nrearranging/reassociating e.g. sums:\n```lean\nexample (a b c d e f g N : ℕ) : (a + b) + (c + d) + (e + f) + g ≤ N :=\nbegin\n ac_change a + d + e + f + c + g + b ≤ _,\n-- ⊢ a + d + e + f + c + g + b ≤ N\nend\n```\n\n## Related tactic: `move_add`\nIn the case in which the expression to be changed is a sum of terms, tactic\n`tactive.interactive.move_add` can also be useful. -/\nunsafe def ac_change (r : parse texpr) (n : parse (parser.optional (tk \"using\" *> small_nat))) :\n tactic Unit :=\n andthen (convert_to r n) (try ac_refl)\n#align tactic.interactive.ac_change tactic.interactive.ac_change\n\nadd_tactic_doc\n { Name := \"convert_to\"\n category := DocCategory.tactic\n declNames := [`tactic.interactive.convert_to, `tactic.interactive.ac_change]\n tags := [\"congruence\"]\n inheritDescriptionFrom := `tactic.interactive.convert_to }\n\nend Interactive\n\nend Tactic\n\n", "meta": {"author": "leanprover-community", "repo": "mathlib3port", "sha": "62505aa236c58c8559783b16d33e30df3daa54f4", "save_path": "github-repos/lean/leanprover-community-mathlib3port", "path": "github-repos/lean/leanprover-community-mathlib3port/mathlib3port-62505aa236c58c8559783b16d33e30df3daa54f4/Mathbin/Tactic/Congr.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44167300566462553, "lm_q2_score": 0.07807816460864352, "lm_q1q2_score": 0.03448501763947697}} {"text": "/-\nCopyright (c) 2017 Mario Carneiro. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Mario Carneiro, Simon Hudon, Sebastien Gouezel, Scott Morrison\n-/\nimport data.dlist data.dlist.basic data.prod category.basic\n tactic.basic tactic.rcases tactic.generalize_proofs\n tactic.split_ifs logic.basic tactic.ext tactic.tauto tactic.replacer\n\nopen lean\nopen lean.parser\n\nlocal postfix `?`:9001 := optional\nlocal postfix *:9001 := many\n\nnamespace tactic\nnamespace interactive\nopen interactive interactive.types expr\n\n/--\nThe `rcases` tactic is the same as `cases`, but with more flexibility in the\n`with` pattern syntax to allow for recursive case splitting. The pattern syntax\nuses the following recursive grammar:\n\n```\npatt ::= (patt_list \"|\")* patt_list\npatt_list ::= id | \"_\" | \"⟨\" (patt \",\")* patt \"⟩\"\n```\n\nA pattern like `⟨a, b, c⟩ | ⟨d, e⟩` will do a split over the inductive datatype,\nnaming the first three parameters of the first constructor as `a,b,c` and the\nfirst two of the second constructor `d,e`. If the list is not as long as the\nnumber of arguments to the constructor or the number of constructors, the\nremaining variables will be automatically named. If there are nested brackets\nsuch as `⟨⟨a⟩, b | c⟩ | d` then these will cause more case splits as necessary.\nIf there are too many arguments, such as `⟨a, b, c⟩` for splitting on\n`∃ x, ∃ y, p x`, then it will be treated as `⟨a, ⟨b, c⟩⟩`, splitting the last\nparameter as necessary.\n\n`rcases` also has special support for quotient types: quotient induction into Prop works like\nmatching on the constructor `quot.mk`.\n\n`rcases? e` will perform case splits on `e` in the same way as `rcases e`,\nbut rather than accepting a pattern, it does a maximal cases and prints the\npattern that would produce this case splitting. The default maximum depth is 5,\nbut this can be modified with `rcases? e : n`.\n-/\nmeta def rcases : parse rcases_parse → tactic unit\n| (p, sum.inl ids) := tactic.rcases p ids\n| (p, sum.inr depth) := do\n patt ← tactic.rcases_hint p depth,\n pe ← pp p,\n trace $ ↑\"snippet: rcases \" ++ pe ++ \" with \" ++ to_fmt patt\n\n/--\nThe `rintro` tactic is a combination of the `intros` tactic with `rcases` to\nallow for destructuring patterns while introducing variables. See `rcases` for\na description of supported patterns. For example, `rintros (a | ⟨b, c⟩) ⟨d, e⟩`\nwill introduce two variables, and then do case splits on both of them producing\ntwo subgoals, one with variables `a d e` and the other with `b c d e`.\n\n`rintro?` will introduce and case split on variables in the same way as\n`rintro`, but will also print the `rintro` invocation that would have the same\nresult. Like `rcases?`, `rintro? : n` allows for modifying the\ndepth of splitting; the default is 5.\n-/\nmeta def rintro : parse rintro_parse → tactic unit\n| (sum.inl []) := intros []\n| (sum.inl l) := tactic.rintro l\n| (sum.inr depth) := do\n ps ← tactic.rintro_hint depth,\n trace $ ↑\"snippet: rintro\" ++ format.join (ps.map $ λ p,\n format.space ++ format.group (p.format tt))\n\n/-- Alias for `rintro`. -/\nmeta def rintros := rintro\n\n/--\nThis is a \"finishing\" tactic modification of `simp`. The tactic `simpa [rules, ...] using e`\nwill simplify the hypothesis `e` using `rules`, then simplify the goal using `rules`, and\ntry to close the goal using `assumption`. If `e` is a term instead of a local constant,\nit is first added to the local context using `have`.\n-/\nmeta def simpa (use_iota_eqn : parse $ (tk \"!\")?) (no_dflt : parse only_flag)\n (hs : parse simp_arg_list) (attr_names : parse with_ident_list)\n (tgt : parse (tk \"using\" *> texpr)?) (cfg : simp_config_ext := {}) : tactic unit :=\nlet simp_at (lc) := try (simp use_iota_eqn no_dflt hs attr_names (loc.ns lc) cfg) >> (assumption <|> trivial) in\nmatch tgt with\n| none := get_local `this >> simp_at [some `this, none] <|> simp_at [none]\n| some e := do\n e ← i_to_expr e <|> do {\n ty ← target,\n e ← i_to_expr_strict ``(%%e : %%ty), -- for positional error messages, don't care about the result\n pty ← pp ty, ptgt ← pp e,\n -- Fail deliberately, to advise regarding `simp; exact` usage\n fail (\"simpa failed, 'using' expression type not directly \" ++\n \"inferrable. Try:\\n\\nsimpa ... using\\nshow \" ++\n to_fmt pty ++ \",\\nfrom \" ++ ptgt : format) },\n match e with\n | local_const _ lc _ _ := simp_at [some lc, none]\n | e := do\n t ← infer_type e,\n assertv `this t e >> simp_at [some `this, none]\n end\nend\n\n/-- `try_for n { tac }` executes `tac` for `n` ticks, otherwise uses `sorry` to close the goal.\nNever fails. Useful for debugging. -/\nmeta def try_for (max : parse parser.pexpr) (tac : itactic) : tactic unit :=\ndo max ← i_to_expr_strict max >>= tactic.eval_expr nat,\n λ s, match _root_.try_for max (tac s) with\n | some r := r\n | none := (tactic.trace \"try_for timeout, using sorry\" >> admit) s\n end\n\n/-- Multiple subst. `substs x y z` is the same as `subst x, subst y, subst z`. -/\nmeta def substs (l : parse ident*) : tactic unit :=\nl.mmap' (λ h, get_local h >>= tactic.subst) >> try (tactic.reflexivity reducible)\n\n/-- Unfold coercion-related definitions -/\nmeta def unfold_coes (loc : parse location) : tactic unit :=\nunfold [``coe,``lift_t,``has_lift_t.lift,``coe_t,``has_coe_t.coe,``coe_b,``has_coe.coe,\n ``coe_fn, ``has_coe_to_fun.coe, ``coe_sort, ``has_coe_to_sort.coe] loc\n\n/-- Unfold auxiliary definitions associated with the currently declaration. -/\nmeta def unfold_aux : tactic unit :=\ndo tgt ← target,\n name ← decl_name,\n let to_unfold := (tgt.list_names_with_prefix name),\n guard (¬ to_unfold.empty),\n -- should we be using simp_lemmas.mk_default?\n simp_lemmas.mk.dsimplify to_unfold.to_list tgt >>= tactic.change\n\n/-- For debugging only. This tactic checks the current state for any\nmissing dropped goals and restores them. Useful when there are no\ngoals to solve but \"result contains meta-variables\". -/\nmeta def recover : tactic unit :=\nmetavariables >>= tactic.set_goals\n\n/-- Like `try { tac }`, but in the case of failure it continues\nfrom the failure state instead of reverting to the original state. -/\nmeta def continue (tac : itactic) : tactic unit :=\nλ s, result.cases_on (tac s)\n (λ a, result.success ())\n (λ e ref, result.success ())\n\n/-- Move goal `n` to the front. -/\nmeta def swap (n := 2) : tactic unit :=\ndo gs ← get_goals,\n match gs.nth (n-1) with\n | (some g) := set_goals (g :: gs.remove_nth (n-1))\n | _ := skip\n end\n\n/-- Generalize proofs in the goal, naming them with the provided list. -/\nmeta def generalize_proofs : parse ident_* → tactic unit :=\ntactic.generalize_proofs\n\n/-- Clear all hypotheses starting with `_`, like `_match` and `_let_match`. -/\nmeta def clear_ : tactic unit := tactic.repeat $ do\n l ← local_context,\n l.reverse.mfirst $ λ h, do\n name.mk_string s p ← return $ local_pp_name h,\n guard (s.front = '_'),\n cl ← infer_type h >>= is_class, guard (¬ cl),\n tactic.clear h\n\n/--\nSame as the `congr` tactic, but takes an optional argument which gives\nthe depth of recursive applications. This is useful when `congr`\nis too aggressive in breaking down the goal. For example, given\n`⊢ f (g (x + y)) = f (g (y + x))`, `congr'` produces the goals `⊢ x = y`\nand `⊢ y = x`, while `congr' 2` produces the intended `⊢ x + y = y + x`. -/\nmeta def congr' : parse (with_desc \"n\" small_nat)? → tactic unit\n| (some 0) := failed\n| o := focus1 (assumption <|> (congr_core >>\n all_goals (reflexivity <|> try (congr' (nat.pred <$> o)))))\n\n/--\nActs like `have`, but removes a hypothesis with the same name as\nthis one. For example if the state is `h : p ⊢ goal` and `f : p → q`,\nthen after `replace h := f h` the goal will be `h : q ⊢ goal`,\nwhere `have h := f h` would result in the state `h : p, h : q ⊢ goal`.\nThis can be used to simulate the `specialize` and `apply at` tactics\nof Coq. -/\nmeta def replace (h : parse ident?) (q₁ : parse (tk \":\" *> texpr)?) (q₂ : parse $ (tk \":=\" *> texpr)?) : tactic unit :=\ndo let h := h.get_or_else `this,\n old ← try_core (get_local h),\n «have» h q₁ q₂,\n match old, q₂ with\n | none, _ := skip\n | some o, some _ := tactic.clear o\n | some o, none := swap >> tactic.clear o >> swap\n end\n\n/--\n`apply_assumption` looks for an assumption of the form `... → ∀ _, ... → head`\nwhere `head` matches the current goal.\n\nalternatively, when encountering an assumption of the form `sg₀ → ¬ sg₁`,\nafter the main approach failed, the goal is dismissed and `sg₀` and `sg₁`\nare made into the new goal.\n\noptional arguments:\n- asms: list of rules to consider instead of the local constants\n- tac: a tactic to run on each subgoals after applying an assumption; if\n this tactic fails, the corresponding assumption will be rejected and\n the next one will be attempted.\n-/\nmeta def apply_assumption\n (asms : option (list expr) := none)\n (tac : tactic unit := return ()) : tactic unit :=\ntactic.apply_assumption asms tac\n\nopen nat\n\n/--\n`solve_by_elim` calls `apply_assumption` on the main goal to find an assumption whose head matches\nand repeated calls `apply_assumption` on the generated subgoals until no subgoals remains\nor up to `depth` times.\n\n`solve_by_elim` discharges the current goal or fails\n\n`solve_by_elim` does some back-tracking if `apply_assumption` chooses an unproductive assumption\n\noptional arguments:\n- discharger: a subsidiary tactic to try at each step (`cc` is often helpful)\n- asms: list of assumptions / rules to consider instead of local constants\n- depth: number of attempts at discharging generated sub-goals\n\nThe optional arguments can be specified as ``solve_by_elim { discharger := `[cc] }``.\n-/\nmeta def solve_by_elim (opt : by_elim_opt := { }) : tactic unit :=\ntactic.solve_by_elim opt\n\n/--\n`tautology` breaks down assumptions of the form `_ ∧ _`, `_ ∨ _`, `_ ↔ _` and `∃ _, _`\nand splits a goal of the form `_ ∧ _`, `_ ↔ _` or `∃ _, _` until it can be discharged\nusing `reflexivity` or `solve_by_elim`\n-/\nmeta def tautology := tactic.tautology\n\n/-- Shorter name for the tactic `tautology`. -/\nmeta def tauto := tautology\n\nprivate meta def generalize_arg_p_aux : pexpr → parser (pexpr × name)\n| (app (app (macro _ [const `eq _ ]) h) (local_const x _ _ _)) := pure (h, x)\n| _ := fail \"parse error\"\n\n\nprivate meta def generalize_arg_p : parser (pexpr × name) :=\nwith_desc \"expr = id\" $ parser.pexpr 0 >>= generalize_arg_p_aux\n\nlemma {u} generalize_a_aux {α : Sort u}\n (h : ∀ x : Sort u, (α → x) → x) : α := h α id\n\n/--\nLike `generalize` but also considers assumptions\nspecified by the user. The user can also specify to\nomit the goal.\n-/\nmeta def generalize_hyp (h : parse ident?) (_ : parse $ tk \":\")\n (p : parse generalize_arg_p)\n (l : parse location) :\n tactic unit :=\ndo h' ← get_unused_name `h,\n x' ← get_unused_name `x,\n g ← if ¬ l.include_goal then\n do refine ``(generalize_a_aux _),\n some <$> (prod.mk <$> tactic.intro x' <*> tactic.intro h')\n else pure none,\n n ← l.get_locals >>= tactic.revert_lst,\n generalize h () p,\n intron n,\n match g with\n | some (x',h') :=\n do tactic.apply h',\n tactic.clear h',\n tactic.clear x'\n | none := return ()\n end\n\n/--\nSimilar to `refine` but generates equality proof obligations\nfor every discrepancy between the goal and the type of the rule.\n-/\nmeta def convert (sym : parse (with_desc \"←\" (tk \"<-\")?)) (r : parse texpr) (n : parse (tk \"using\" *> small_nat)?) : tactic unit :=\ndo v ← mk_mvar,\n if sym.is_some\n then refine ``(eq.mp %%v %%r)\n else refine ``(eq.mpr %%v %%r),\n gs ← get_goals,\n set_goals [v],\n congr' n,\n gs' ← get_goals,\n set_goals $ gs' ++ gs\n\nmeta def clean_ids : list name :=\n[``id, ``id_rhs, ``id_delta]\n\n/--\nRemove identity functions from a term. These are normally\nautomatically generated with terms like `show t, from p` or\n`(p : t)` which translate to some variant on `@id t p` in\norder to retain the type. -/\nmeta def clean (q : parse texpr) : tactic unit :=\ndo tgt : expr ← target,\n e ← i_to_expr_strict ``(%%q : %%tgt),\n tactic.exact $ e.replace (λ e n,\n match e with\n | (app (app (const n _) _) e') :=\n if n ∈ clean_ids then some e' else none\n | (app (lam _ _ _ (var 0)) e') := some e'\n | _ := none\n end)\n\nmeta def source_fields (missing : list name) (e : pexpr) : tactic (list (name × pexpr)) :=\ndo e ← to_expr e,\n t ← infer_type e,\n let struct_n : name := t.get_app_fn.const_name,\n fields ← expanded_field_list struct_n,\n let exp_fields := fields.filter (λ x, x.2 ∈ missing),\n exp_fields.mmap $ λ ⟨p,n⟩,\n (prod.mk n ∘ to_pexpr) <$> mk_mapp (n.update_prefix p) [none,some e]\n\nmeta def collect_struct' : pexpr → state_t (list $ expr×structure_instance_info) tactic pexpr | e :=\ndo some str ← pure (e.get_structure_instance_info)\n | e.traverse collect_struct',\n v ← monad_lift mk_mvar,\n modify (list.cons (v,str)),\n pure $ to_pexpr v\n\nmeta def collect_struct (e : pexpr) : tactic $ pexpr × list (expr×structure_instance_info) :=\nprod.map id list.reverse <$> (collect_struct' e).run []\n\nmeta def refine_one (str : structure_instance_info) :\n tactic $ list (expr×structure_instance_info) :=\ndo tgt ← target,\n let struct_n : name := tgt.get_app_fn.const_name,\n exp_fields ← expanded_field_list struct_n,\n let missing_f := exp_fields.filter (λ f, (f.2 : name) ∉ str.field_names),\n (src_field_names,src_field_vals) ← (@list.unzip name _ ∘ list.join) <$> str.sources.mmap (source_fields $ missing_f.map prod.snd),\n let provided := exp_fields.filter (λ f, (f.2 : name) ∈ str.field_names),\n let missing_f' := missing_f.filter (λ x, x.2 ∉ src_field_names),\n vs ← mk_mvar_list missing_f'.length,\n (field_values,new_goals) ← list.unzip <$> (str.field_values.mmap collect_struct : tactic _),\n e' ← to_expr $ pexpr.mk_structure_instance\n { struct := some struct_n\n , field_names := str.field_names ++ missing_f'.map prod.snd ++ src_field_names\n , field_values := field_values ++ vs.map to_pexpr ++ src_field_vals },\n tactic.exact e',\n gs ← with_enable_tags (\n mzip_with (λ (n : name × name) v, do\n set_goals [v],\n try (interactive.unfold (provided.map $ λ ⟨s,f⟩, f.update_prefix s) (loc.ns [none])),\n apply_auto_param\n <|> apply_opt_param\n <|> (set_main_tag [`_field,n.2,n.1]),\n get_goals)\n missing_f' vs),\n set_goals gs.join,\n return new_goals.join\n\nmeta def refine_recursively : expr × structure_instance_info → tactic (list expr) | (e,str) :=\ndo set_goals [e],\n rs ← refine_one str,\n gs ← get_goals,\n gs' ← rs.mmap refine_recursively,\n return $ gs'.join ++ gs\n\n\n/--\n`refine_struct { .. }` acts like `refine` but works only with structure instance\nliterals. It creates a goal for each missing field and tags it with the name of the\nfield so that `have_field` can be used to generically refer to the field currently\nbeing refined.\n\nAs an example, we can use `refine_struct` to automate the construction semigroup\ninstances:\n```\nrefine_struct ( { .. } : semigroup α ),\n-- case semigroup, mul\n-- α : Type u,\n-- ⊢ α → α → α\n\n-- case semigroup, mul_assoc\n-- α : Type u,\n-- ⊢ ∀ (a b c : α), a * b * c = a * (b * c)\n```\n-/\nmeta def refine_struct : parse texpr → tactic unit | e :=\ndo (x,xs) ← collect_struct e,\n refine x,\n gs ← get_goals,\n xs' ← xs.mmap refine_recursively,\n set_goals (xs'.join ++ gs)\n\n/--\n`guard_hyp h := t` fails if the hypothesis `h` does not have type `t`.\nWe use this tactic for writing tests.\nFixes `guard_hyp` by instantiating meta variables\n-/\nmeta def guard_hyp' (n : parse ident) (p : parse $ tk \":=\" *> texpr) : tactic unit :=\ndo h ← get_local n >>= infer_type >>= instantiate_mvars, guard_expr_eq h p\n\nmeta def guard_hyp_nums (n : ℕ) : tactic unit :=\ndo k ← local_context,\n guard (n = k.length) <|> fail format!\"{k.length} hypotheses found\"\n\nmeta def guard_tags (tags : parse ident*) : tactic unit :=\ndo (t : list name) ← get_main_tag,\n guard (t = tags)\n\nmeta def get_current_field : tactic name :=\ndo [_,field,str] ← get_main_tag,\n expr.const_name <$> resolve_name (field.update_prefix str)\n\nmeta def field (n : parse ident) (tac : itactic) : tactic unit :=\ndo gs ← get_goals,\n ts ← gs.mmap get_tag,\n ([g],gs') ← pure $ (list.zip gs ts).partition (λ x, x.snd.nth 1 = some n),\n set_goals [g.1],\n tac, done,\n set_goals $ gs'.map prod.fst\n\n/--\n`have_field`, used after `refine_struct _` poses `field` as a local constant\nwith the type of the field of the current goal:\n\n```\nrefine_struct ({ .. } : semigroup α),\n{ have_field, ... },\n{ have_field, ... },\n```\nbehaves like\n```\nrefine_struct ({ .. } : semigroup α),\n{ have field := @semigroup.mul, ... },\n{ have field := @semigroup.mul_assoc, ... },\n```\n-/\nmeta def have_field : tactic unit :=\npropagate_tags $\nget_current_field\n>>= mk_const\n>>= note `field none\n>> return ()\n\n/-- `apply_field` functions as `have_field, apply field, clear field` -/\nmeta def apply_field : tactic unit :=\npropagate_tags $\nget_current_field >>= applyc\n\n/--`apply_rules hs n`: apply the list of rules `hs` (given as pexpr) and `assumption` on the\nfirst goal and the resulting subgoals, iteratively, at most `n` times.\n`n` is 50 by default. `hs` can contain user attributes: in this case all theorems with this\nattribute are added to the list of rules.\n\nexample, with or without user attribute:\n```\n@[user_attribute]\nmeta def mono_rules : user_attribute :=\n{ name := `mono_rules,\n descr := \"lemmas usable to prove monotonicity\" }\n\nattribute [mono_rules] add_le_add mul_le_mul_of_nonneg_right\n\nlemma my_test {a b c d e : real} (h1 : a ≤ b) (h2 : c ≤ d) (h3 : 0 ≤ e) :\na + c * e + a + c + 0 ≤ b + d * e + b + d + e :=\nby apply_rules mono_rules\n-- any of the following lines would also work:\n-- add_le_add (add_le_add (add_le_add (add_le_add h1 (mul_le_mul_of_nonneg_right h2 h3)) h1 ) h2) h3\n-- by apply_rules [add_le_add, mul_le_mul_of_nonneg_right]\n-- by apply_rules [mono_rules]\n```\n-/\nmeta def apply_rules (hs : parse pexpr_list_or_texpr) (n : nat := 50) : tactic unit :=\ntactic.apply_rules hs n\n\nmeta def return_cast (f : option expr) (t : option (expr × expr))\n (es : list (expr × expr × expr))\n (e x x' eq_h : expr) :\n tactic (option (expr × expr) × list (expr × expr × expr)) :=\n(do guard (¬ e.has_var),\n unify x x',\n u ← mk_meta_univ,\n f ← f <|> to_expr ``(@id %%(expr.sort u : expr)),\n t' ← infer_type e,\n some (f',t) ← pure t | return (some (f,t'), (e,x',eq_h) :: es),\n infer_type e >>= is_def_eq t,\n unify f f',\n return (some (f,t), (e,x',eq_h) :: es)) <|>\nreturn (t, es)\n\nmeta def list_cast_of_aux (x : expr) (t : option (expr × expr))\n (es : list (expr × expr × expr)) :\n expr → tactic (option (expr × expr) × list (expr × expr × expr))\n| e@`(cast %%eq_h %%x') := return_cast none t es e x x' eq_h\n| e@`(eq.mp %%eq_h %%x') := return_cast none t es e x x' eq_h\n| e@`(eq.mpr %%eq_h %%x') := mk_eq_symm eq_h >>= return_cast none t es e x x'\n| e@`(@eq.subst %%α %%p %%a %%b %%eq_h %%x') := return_cast p t es e x x' eq_h\n| e@`(@eq.substr %%α %%p %%a %%b %%eq_h %%x') := mk_eq_symm eq_h >>= return_cast p t es e x x'\n| e@`(@eq.rec %%α %%a %%f %%x' _ %%eq_h) := return_cast f t es e x x' eq_h\n| e@`(@eq.rec_on %%α %%a %%f %%b %%eq_h %%x') := return_cast f t es e x x' eq_h\n| e := return (t,es)\n\nmeta def list_cast_of (x tgt : expr) : tactic (list (expr × expr × expr)) :=\n(list.reverse ∘ prod.snd) <$> tgt.mfold (none, []) (λ e i es, list_cast_of_aux x es.1 es.2 e)\n\nprivate meta def h_generalize_arg_p_aux : pexpr → parser (pexpr × name)\n| (app (app (macro _ [const `heq _ ]) h) (local_const x _ _ _)) := pure (h, x)\n| _ := fail \"parse error\"\n\nprivate meta def h_generalize_arg_p : parser (pexpr × name) :=\nwith_desc \"expr == id\" $ parser.pexpr 0 >>= h_generalize_arg_p_aux\n\n/--\n`h_generalize Hx : e == x` matches on `cast _ e` in the goal and replaces it with\n`x`. It also adds `Hx : e == x` as an assumption. If `cast _ e` appears multiple\ntimes (not necessarily with the same proof), they are all replaced by `x`. `cast`\n`eq.mp`, `eq.mpr`, `eq.subst`, `eq.substr`, `eq.rec` and `eq.rec_on` are all treated\nas casts.\n\n`h_generalize Hx : e == x with h` adds hypothesis `α = β` with `e : α, x : β`.\n\n`h_generalize Hx : e == x with _` chooses automatically chooses the name of\nassumption `α = β`.\n\n`h_generalize! Hx : e == x` reverts `Hx`.\n\nwhen `Hx` is omitted, assumption `Hx : e == x` is not added.\n-/\nmeta def h_generalize (rev : parse (tk \"!\")?)\n (h : parse ident_?)\n (_ : parse (tk \":\"))\n (arg : parse h_generalize_arg_p)\n (eqs_h : parse ( (tk \"with\" >> pure <$> ident_) <|> pure [])) :\n tactic unit :=\ndo let (e,n) := arg,\n let h' := if h = `_ then none else h,\n h' ← (h' : tactic name) <|> get_unused_name (\"h\" ++ n.to_string : string),\n e ← to_expr e,\n tgt ← target,\n ((e,x,eq_h)::es) ← list_cast_of e tgt | fail \"no cast found\",\n interactive.generalize h' () (to_pexpr e, n),\n asm ← get_local h',\n v ← get_local n,\n hs ← es.mmap (λ ⟨e,_⟩, mk_app `eq [e,v]),\n (eqs_h.zip [e]).mmap' (λ ⟨h,e⟩, do\n h ← if h ≠ `_ then pure h else get_unused_name `h,\n () <$ note h none eq_h ),\n hs.mmap' (λ h,\n do h' ← assert `h h,\n tactic.exact asm,\n try (rewrite_target h'),\n tactic.clear h' ),\n when h.is_some (do\n (to_expr ``(heq_of_eq_rec_left %%eq_h %%asm)\n <|> to_expr ``(heq_of_eq_mp %%eq_h %%asm))\n >>= note h' none >> pure ()),\n tactic.clear asm,\n when rev.is_some (interactive.revert [n])\n\nend interactive\nend tactic\n", "meta": {"author": "khoek", "repo": "mathlib-tidy", "sha": "866afa6ab597c47f1b72e8fe2b82b97fff5b980f", "save_path": "github-repos/lean/khoek-mathlib-tidy", "path": "github-repos/lean/khoek-mathlib-tidy/mathlib-tidy-866afa6ab597c47f1b72e8fe2b82b97fff5b980f/tactic/interactive.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.06853748970246937, "lm_q1q2_score": 0.034268744851234684}} {"text": "/-\nCopyright (c) 2021 Anne Baanen. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Anne Baanen\n-/\n\nimport logic.function.basic\nimport tactic.lint\nimport tactic.norm_cast\n\n/-!\n# Typeclass for a type `F` with an injective map to `A → B`\n\n> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.\n> Any changes to this file require a corresponding PR to mathlib4.\n\nThis typeclass is primarily for use by homomorphisms like `monoid_hom` and `linear_map`.\n\n## Basic usage of `fun_like`\n\nA typical type of morphisms should be declared as:\n```\nstructure my_hom (A B : Type*) [my_class A] [my_class B] :=\n(to_fun : A → B)\n(map_op' : ∀ {x y : A}, to_fun (my_class.op x y) = my_class.op (to_fun x) (to_fun y))\n\nnamespace my_hom\n\nvariables (A B : Type*) [my_class A] [my_class B]\n\n-- This instance is optional if you follow the \"morphism class\" design below:\ninstance : fun_like (my_hom A B) A (λ _, B) :=\n{ coe := my_hom.to_fun, coe_injective' := λ f g h, by cases f; cases g; congr' }\n\n/-- Helper instance for when there's too many metavariables to apply\n`fun_like.has_coe_to_fun` directly. -/\ninstance : has_coe_to_fun (my_hom A B) (λ _, A → B) := fun_like.has_coe_to_fun\n\n@[simp] lemma to_fun_eq_coe {f : my_hom A B} : f.to_fun = (f : A → B) := rfl\n\n@[ext] theorem ext {f g : my_hom A B} (h : ∀ x, f x = g x) : f = g := fun_like.ext f g h\n\n/-- Copy of a `my_hom` with a new `to_fun` equal to the old one. Useful to fix definitional\nequalities. -/\nprotected def copy (f : my_hom A B) (f' : A → B) (h : f' = ⇑f) : my_hom A B :=\n{ to_fun := f',\n map_op' := h.symm ▸ f.map_op' }\n\nend my_hom\n```\n\nThis file will then provide a `has_coe_to_fun` instance and various\nextensionality and simp lemmas.\n\n## Morphism classes extending `fun_like`\n\nThe `fun_like` design provides further benefits if you put in a bit more work.\nThe first step is to extend `fun_like` to create a class of those types satisfying\nthe axioms of your new type of morphisms.\nContinuing the example above:\n\n```\nsection\nset_option old_structure_cmd true\n\n/-- `my_hom_class F A B` states that `F` is a type of `my_class.op`-preserving morphisms.\nYou should extend this class when you extend `my_hom`. -/\nclass my_hom_class (F : Type*) (A B : out_param $ Type*) [my_class A] [my_class B]\n extends fun_like F A (λ _, B) :=\n(map_op : ∀ (f : F) (x y : A), f (my_class.op x y) = my_class.op (f x) (f y))\n\nend\n@[simp] lemma map_op {F A B : Type*} [my_class A] [my_class B] [my_hom_class F A B]\n (f : F) (x y : A) : f (my_class.op x y) = my_class.op (f x) (f y) :=\nmy_hom_class.map_op\n\n-- You can replace `my_hom.fun_like` with the below instance:\ninstance : my_hom_class (my_hom A B) A B :=\n{ coe := my_hom.to_fun,\n coe_injective' := λ f g h, by cases f; cases g; congr',\n map_op := my_hom.map_op' }\n\n-- [Insert `has_coe_to_fun`, `to_fun_eq_coe`, `ext` and `copy` here]\n```\n\nThe second step is to add instances of your new `my_hom_class` for all types extending `my_hom`.\nTypically, you can just declare a new class analogous to `my_hom_class`:\n\n```\nstructure cooler_hom (A B : Type*) [cool_class A] [cool_class B]\n extends my_hom A B :=\n(map_cool' : to_fun cool_class.cool = cool_class.cool)\n\nsection\nset_option old_structure_cmd true\n\nclass cooler_hom_class (F : Type*) (A B : out_param $ Type*) [cool_class A] [cool_class B]\n extends my_hom_class F A B :=\n(map_cool : ∀ (f : F), f cool_class.cool = cool_class.cool)\n\nend\n\n@[simp] lemma map_cool {F A B : Type*} [cool_class A] [cool_class B] [cooler_hom_class F A B]\n (f : F) : f cool_class.cool = cool_class.cool :=\nmy_hom_class.map_op\n\n-- You can also replace `my_hom.fun_like` with the below instance:\ninstance : cool_hom_class (cool_hom A B) A B :=\n{ coe := cool_hom.to_fun,\n coe_injective' := λ f g h, by cases f; cases g; congr',\n map_op := cool_hom.map_op',\n map_cool := cool_hom.map_cool' }\n\n-- [Insert `has_coe_to_fun`, `to_fun_eq_coe`, `ext` and `copy` here]\n```\n\nThen any declaration taking a specific type of morphisms as parameter can instead take the\nclass you just defined:\n```\n-- Compare with: lemma do_something (f : my_hom A B) : sorry := sorry\nlemma do_something {F : Type*} [my_hom_class F A B] (f : F) : sorry := sorry\n```\n\nThis means anything set up for `my_hom`s will automatically work for `cool_hom_class`es,\nand defining `cool_hom_class` only takes a constant amount of effort,\ninstead of linearly increasing the work per `my_hom`-related declaration.\n\n-/\n\n-- This instance should have low priority, to ensure we follow the chain\n-- `fun_like → has_coe_to_fun`\nattribute [instance, priority 10] coe_fn_trans\n\n/-- The class `fun_like F α β` expresses that terms of type `F` have an\ninjective coercion to functions from `α` to `β`.\n\nThis typeclass is used in the definition of the homomorphism typeclasses,\nsuch as `zero_hom_class`, `mul_hom_class`, `monoid_hom_class`, ....\n-/\nclass fun_like (F : Sort*) (α : out_param Sort*) (β : out_param $ α → Sort*) :=\n(coe : F → Π a : α, β a)\n(coe_injective' : function.injective coe)\n\nsection dependent\n\n/-! ### `fun_like F α β` where `β` depends on `a : α` -/\n\nvariables (F α : Sort*) (β : α → Sort*)\n\nnamespace fun_like\n\nvariables {F α β} [i : fun_like F α β]\n\ninclude i\n\n@[priority 100, -- Give this a priority between `coe_fn_trans` and the default priority\n nolint dangerous_instance] -- `α` and `β` are out_params, so this instance should not be dangerous\ninstance : has_coe_to_fun F (λ _, Π a : α, β a) := { coe := fun_like.coe }\n\n@[simp] \n\ntheorem coe_injective : function.injective (coe_fn : F → Π a : α, β a) :=\nfun_like.coe_injective'\n\n@[simp, norm_cast]\ntheorem coe_fn_eq {f g : F} : (f : Π a : α, β a) = (g : Π a : α, β a) ↔ f = g :=\n⟨λ h, @coe_injective _ _ _ i _ _ h, λ h, by cases h; refl⟩\n\ntheorem ext' {f g : F} (h : (f : Π a : α, β a) = (g : Π a : α, β a)) : f = g :=\ncoe_injective h\n\ntheorem ext'_iff {f g : F} : f = g ↔ ((f : Π a : α, β a) = (g : Π a : α, β a)) :=\ncoe_fn_eq.symm\n\ntheorem ext (f g : F) (h : ∀ (x : α), f x = g x) : f = g :=\ncoe_injective (funext h)\n\ntheorem ext_iff {f g : F} : f = g ↔ (∀ x, f x = g x) :=\ncoe_fn_eq.symm.trans function.funext_iff\n\nprotected lemma congr_fun {f g : F} (h₁ : f = g) (x : α) : f x = g x :=\ncongr_fun (congr_arg _ h₁) x\n\nlemma ne_iff {f g : F} : f ≠ g ↔ ∃ a, f a ≠ g a :=\next_iff.not.trans not_forall\n\nlemma exists_ne {f g : F} (h : f ≠ g) : ∃ x, f x ≠ g x :=\nne_iff.mp h\n\n/-- This is not an instance to avoid slowing down every single `subsingleton` typeclass search.-/\nlemma subsingleton_cod [∀ a, subsingleton (β a)] : subsingleton F :=\n⟨λ f g, coe_injective $ subsingleton.elim _ _⟩\n\nend fun_like\n\nend dependent\n\nsection non_dependent\n\n/-! ### `fun_like F α (λ _, β)` where `β` does not depend on `a : α` -/\n\nvariables {F α β : Sort*} [i : fun_like F α (λ _, β)]\n\ninclude i\n\nnamespace fun_like\n\nprotected lemma congr {f g : F} {x y : α} (h₁ : f = g) (h₂ : x = y) : f x = g y :=\ncongr (congr_arg _ h₁) h₂\n\nprotected lemma congr_arg (f : F) {x y : α} (h₂ : x = y) : f x = f y :=\ncongr_arg _ h₂\n\nend fun_like\n\nend non_dependent\n", "meta": {"author": "leanprover-community", "repo": "mathlib", "sha": "5e526d18cea33550268dcbbddcb822d5cde40654", "save_path": "github-repos/lean/leanprover-community-mathlib", "path": "github-repos/lean/leanprover-community-mathlib/mathlib-5e526d18cea33550268dcbbddcb822d5cde40654/src/data/fun_like/basic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4111108548019597, "lm_q2_score": 0.08269734041427965, "lm_q1q2_score": 0.03399777430756315}} {"text": "/-\n Copyright (c) 2022 Arthur Paulino. All rights reserved.\n Released under Apache 2.0 license as described in the file LICENSE.\n Authors: Arthur Paulino\n-/\n\nimport FxyLang.Implementation.ASTUtilities\n\n/- Before we proceed, it's important to notice that a function that executes a\nprogram *has* to be `partial` because programs themselves may loop forever.\n\nThis file contains two partial functions capable of running Fxy programs:\n* `Program.run!` is fast but uses code that can't be reasoned on\n* `Program.run` is ~50% slower, but uses a function that implements small step\nsemantics and thus can be reasoned on\n\nAnother important detail is that the computation of a `Program` yields an\nintrinsic `Value`:\n* `skip` yields `nil`\n* `eval` yields the `Value` of the expression being evaluated\n* `seq` yields the `Value` of the second `Program`, unless the first one causes\nan error\n* `fork` yields the `Value` of the child `Program` executed\n* `loop` yields `nil` or an error\n-/\n\ndef cantEvalAsBool (e : Expression) (v : Value) : String :=\n s!\"I can't evaluate '{e}' as a 'bool' because it reduces to '{v}', of \" ++\n s!\"type '{v.typeStr}'\"\n\ndef notFound (n : String) : String :=\n s!\"I can't find the definition of '{n}'\"\n\ndef notAFunction (e : Expression) (v : Value) : String :=\n s!\"I can't apply arguments to '{e}' because it evaluates to '{v}', of \" ++\n s!\"type '{v.typeStr}'\"\n\ndef wrongNParameters (e : Expression) (allowed provided : Nat) : String :=\n s!\"I can't apply {provided} arguments to '{e}' because the maximum \" ++\n s!\"allowed is {allowed}\"\n\n/-- Takes a list of expressions and matches each element with an element from a\nlist of strings. For each match, it adds a declaration in the beginning of a\ngiven program, returning such modified program -/\ndef consume (p : Program) :\n NEList String → NEList Expression →\n Option ((Option (NEList String)) × Program)\n | .cons n ns, .cons e es => consume (.seq (.decl n (.eval e)) p) ns es\n | .cons n ns, .uno e => some (some ns, .seq (.decl n (.eval e)) p)\n | .uno n, .uno e => some (none, .seq (.decl n (.eval e)) p)\n | .uno _, .cons .. => none\n\n/-- Consuming elements from a non-duplicated NEList results in a non-duplicated\nNEList -/\ntheorem noDupOfConsumeNoDup\n (h : ns.noDup) (h' : consume p' ns es = some (some l, p)) :\n l.noDup = true := by\n induction ns generalizing p' es with\n | uno _ => cases es <;> cases h'\n | cons _ _ hi =>\n simp [NEList.noDup] at h\n cases es with\n | uno _ => simp [consume] at h'; simp only [h.2, ← h'.1]\n | cons _ _ => exact hi h.2 h'\n\n/- Next we're going to define a pair of mutual functions:\n* `reduce` computes over an expression with the goal of extracting a term of\n`Result` from it, which signals either a `Value` or an error.\n* `Program.run!` is similar to `reduce`, but it processes a `Program` instead\n\nThey are mutual because *i*) a program may rely on the resolution of expressions\nto move forward (for instance, knowing whether to loop again or not) and *ii*)\nan expression can be the application of a function, which may need to trigger\nthe execution of another term of `Program` (see the `app` case)\n-/\n\nmutual\n\n /-- Since we're already in the `partial` realm, let's allow ourselves to be\n carelessly recursive, always believing that `reduce` will compute *any*\n expression for us! -/\n partial def reduce (c : Context) : Expression → Result\n | .lit l => .val $ .lit l\n | .list l => .val $ .list l\n | .lam l => .val $ .lam l\n | .var n => match c[n] with\n | none => .err .name $ notFound n\n | some v => .val $ v\n | .app e es => match reduce c e with\n | .val $ .lam $ .mk ns h p => match h' : consume p ns es with\n | some (some l, p) => .val $ .lam $ .mk l (noDupOfConsumeNoDup h h') p\n | some (none, p) => (p.run! c).2\n | none => .err .runTime $ wrongNParameters e ns.length es.length\n | .val v => .err .type $ notAFunction e v\n | er@(.err ..) => er\n | .unOp o e => match reduce c e with\n | .val v => match v.unOp o with\n | .ok v => .val v\n | .error m => .err .type m\n | er@(.err ..) => er\n | .binOp o eₗ eᵣ => match (reduce c eₗ, reduce c eᵣ) with\n | (.val vₗ, .val vᵣ) => match vₗ.binOp vᵣ o with\n | .ok v => .val v\n | .error m => .err .type m\n | (er@(.err ..), _) => er\n | (_, er@(.err ..)) => er\n\n /-- And here we can allow ourselves to be careless too, trusting on `reduce`\n as well as on `run!`! -/\n partial def Program.run! (c : Context := default) :\n Program → Context × Result\n | skip => (c, .val .nil)\n | eval e => (c, (reduce c e))\n | seq p₁ p₂ =>\n let res := p₁.run! c\n match res.2 with\n | .err .. => res\n | _ => p₂.run! res.1\n | decl n p => match (p.run! c).2 with\n | er@(.err ..) => (c, er)\n | .val v => (c.insert n v, .val .nil)\n | fork e pT pF => match reduce c e with\n | .val $ .lit $ .bool b => if b then pT.run! c else pF.run! c\n | .val v => (c, .err .type $ cantEvalAsBool e v)\n | er@(.err ..) => (c, er)\n | loop e p => match reduce c e with\n | .val $ .lit $ .bool b =>\n if !b then (c, .val .nil) else\n match p.run! c with\n | er@(_, .err ..) => er\n | (c, _) => (loop e p).run! c\n | .val v => (c, .err .type $ cantEvalAsBool e v)\n | er@(.err ..) => (c, er)\n | print e => match reduce c e with\n | .val v => dbg_trace v; (c, .val .nil)\n | er@(.err ..) => (c, er)\n\nend\n\n/-- This is the function that will allow us to prove results about the semantics\nof Fxy. Let's dive into its details. -/\ndef State.step : State → State\n /- `skip` just goes straight into returning `nil` -/\n | prog c k .skip => ret c k .nil\n\n /- `eval` enters the `expr` state for expression evaluation -/\n | prog c k (.eval e) => expr c k e\n\n /- `seq` runs the first program and stacks the second -/\n | prog c k (.seq p₁ p₂) => prog c (.seq p₂ k) p₁\n\n /- `decl` calls for the execution of the innermost program and then stores the\n current context with the `block` continuation, which is recovered later on.\n This allows us to have functions running with their own contexts, being able\n to write on them as they need as they will be discarded anyway -/\n | prog c k (.decl n p) => prog c (.block c (.decl n k)) p\n\n /- `fork`, `loop` and `print` go to the expression evaluation step, keeping\n track of what needs to be done with the returned value later on -/\n | prog c k (.fork e pT pF) => expr c (.fork e pT pF k) e\n | prog c k (.loop e p) => expr c (.loop e p k) e\n | prog c k (.print e) => expr c (.print k) e\n\n /- If the expression resulted in a literal, a list or a function, just return\n them -/\n | expr c k (.lit l) => ret c k (.lit l)\n | expr c k (.list l) => ret c k (.list l)\n | expr c k (.lam l) => ret c k (.lam l)\n\n /- If we're supposed to extract the value of a variable, we need to check\n whether it's available in the context or not -/\n | expr c k (.var nm) => match c[nm] with\n | none => error c k .name $ notFound nm\n | some v => ret c k v\n \n /- For an application we need to evaluate what we're using to apply. We expect\n it to be a function! -/\n | expr c k (.app e es) => expr c (.app e es k) e\n\n /- For the unary operator we have to evaluate the (only) expression first -/\n | expr c k (.unOp o e) => expr c (.unOp o k) e\n\n /- For the binary operator, we need to evaluate the first expression first and\n stack up the evaluation of the second one -/\n | expr c k (.binOp o e₁ e₂) => expr c (.binOp₁ o e₂ k) e₁\n\n /- The `Continuation.exit` signals that there's nothing else to do -/\n | ret c .exit v => done c .exit v\n\n /- Here we print the returned value and then return `nil` -/\n | ret c (.print k) v => dbg_trace v; ret c k .nil\n\n /- When returning from the execution of the first program in a `seq`, we\n ignore the value and go straight to the execution of the second program -/\n | ret c (.seq p k) _ => prog c k p\n\n /- Here we do what we promised and recover the original context stacked with\n the `Continuation.block` constructor -/\n | ret _ (.block c k) v => ret c k v\n\n /- When returning from an `app` continuation, we need to inspect the value\n that was returned from the evaluation of the first expression -/\n | ret c (.app e es k) v => match v with\n\n /- The desired case: it's a function! Let's consume it's parameters -/\n | .lam $ .mk ns h p => match h' : consume p ns es with\n\n /- When `consume` didn't eat up all the arguments we return an\n yet-to-be-uncurried function -/\n | some (some l, p) =>\n ret c k (.lam $ .mk l (noDupOfConsumeNoDup h h') p)\n \n /- All arguments were consumed: let's run the lambda program and use\n `block` to save up the context -/\n | some (none, p) => prog c (.block c k) p\n \n /- This signals that too many arguments were provided -/\n | none => error c k .runTime $ wrongNParameters e ns.length es.length\n \n /- Anything but a function. Error! -/\n | v => error c k .type $ notAFunction e v\n\n /- Now we need to resolve a `fork` given the value returned from the\n expression. We expext it to be a boolean -/\n | ret c (.fork _ pT _ k) (.lit $ .bool true) => prog c k pT\n | ret c (.fork _ _ pF k) (.lit $ .bool false) => prog c k pF\n\n /- Not a boolean. Error! -/\n | ret c (.fork e _ _ k) v => error c k .type $ cantEvalAsBool e v\n\n /- Resolving a `loop` is similar to a `fork`. We should expect a boolean, at\n least. The difference is that in case of `true`, we run the program and stack\n up the same loop expression and program. In case of `false`, just break the\n loop and return `nil` -/\n | ret c (.loop e p k) (.lit $ .bool true) => prog c k (.seq p (.loop e p))\n | ret c (.loop _ _ k) (.lit $ .bool false) => ret c k .nil\n | ret c (.loop e _ k) v => error c k .type $ cantEvalAsBool e v\n\n /- The execution of the `decl` program is returning a value. We can finally\n add it to the context under the name recovered from the `Continuation.decl` -/\n | ret c (.decl nm k) v => ret (c.insert nm v) k .nil\n\n /- In the unary operator, let's compute it right away -/\n | ret c (.unOp o k) v => match v.unOp o with\n | .error m => error c k .type m\n | .ok v => ret c k v\n\n /- The binary operator is a bit more laborious. When returning from the\n evaluation of the first expression, we stack the result and call the\n evaluation of the second expression -/\n | ret c (.binOp₁ o e₂ k) v₁ => expr c (.binOp₂ o v₁ k) e₂\n \n /- Once the second evaluation is complete, we're good to go -/\n | ret c (.binOp₂ o v₁ k) v₂ => match v₁.binOp v₂ o with\n | .error m => error c k .type m\n | .ok v => ret c k v\n\n /- `error` and `done` states just loop into themselves! -/\n | s@(error ..) => s\n | s@(done ..) => s\n\n/-- And now we can finally define our partial function to run a program using\n`step`. It's really simple: call `step` until it yields a value or an error! -/\npartial def Program.run (p : Program) : Context × Result :=\n let rec run' (s : State) : Context × Result :=\n match s.step with\n | .error c _ t m => (c, .err t m)\n | .done c _ v => (c, .val v)\n | s => run' s\n run' $ State.prog default default p\n", "meta": {"author": "arthurpaulino", "repo": "FxyLang", "sha": "fe1c1df2af522bb3f5c7f4e5b895715e27671df0", "save_path": "github-repos/lean/arthurpaulino-FxyLang", "path": "github-repos/lean/arthurpaulino-FxyLang/FxyLang-fe1c1df2af522bb3f5c7f4e5b895715e27671df0/FxyLang/Implementation/Execution.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44167300566462553, "lm_q2_score": 0.07696083940093962, "lm_q1q2_score": 0.03399152525668554}} {"text": "/-\nCopyright (c) 2021 Gabriel Ebner. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Gabriel Ebner\n-/\nimport Lean\n\n/-!\n# Irreducible definitions\n\nThis file defines an `irreducible_def` command,\nwhich works almost like the `def` command\nexcept that the introduced definition\ndoes not reduce to the value.\nInstead, the command\nadds a `_def` lemma\nwhich can be used for rewriting.\n\n```\nirreducible_def frobnicate (a b : Nat) :=\n a + b\n\nexample : frobnicate a 0 = a := by\n simp [frobnicate_def]\n```\n\n-/\n\nnamespace Lean.Elab.Command\n\nopen Term Meta\n\n/-- `delta% t` elaborates to a head-delta reduced version of `t`. -/\nelab \"delta% \" t:term : term <= expectedType => do\n let t ← elabTerm t expectedType\n synthesizeSyntheticMVars\n let t ← instantiateMVars t\n let some t ← delta? t | throwError \"cannot delta reduce {t}\"\n pure t\n\n/- `eta_helper f = (· + 3)` elabs to `∀ x, f x = x + 3` -/\nlocal elab \"eta_helper \" t:term : term => do\n let t ← elabTerm t none\n let some (_, lhs, rhs) := t.eq? | throwError \"not an equation: {t}\"\n synthesizeSyntheticMVars\n let rhs ← instantiateMVars rhs\n lambdaLetTelescope rhs fun xs rhs ↦ do\n let lhs := (mkAppN lhs xs).headBeta\n mkForallFVars xs <|← mkEq lhs rhs\n\n/-- `value_proj x` elabs to `@x.value` -/\nlocal elab \"value_proj \" e:term : term => do\n let e ← elabTerm e none\n mkProjection e `value\n\n/--\nExecutes the commands,\nand stops after the first error.\nIn short, S-A-F-E.\n-/\nlocal syntax \"stop_at_first_error\" command* : command\nopen Command in elab_rules : command\n | `(stop_at_first_error $[$cmds]*) => do\n for cmd in cmds do\n elabCommand cmd.raw\n if (← get).messages.hasErrors then break\n\n/--\nIntroduces an irreducible definition.\n`irreducible_def foo := 42` generates\na constant `foo : Nat` as well as\na theorem `foo_def : foo = 42`.\n-/\nmacro mods:declModifiers \"irreducible_def\" n_id:declId declSig:optDeclSig val:declVal :\n command => do\n let (n, us) ← match n_id with\n | `(Parser.Command.declId| $n:ident $[.{$us,*}]?) => pure (n, us)\n | _ => Macro.throwUnsupported\n let us' := us.getD { elemsAndSeps := #[] }\n let n_def := mkIdent <| (·.review) <|\n let scopes := extractMacroScopes n.getId\n { scopes with name := scopes.name.appendAfter \"_def\" }\n `(stop_at_first_error\n def definition$[.{$us,*}]? $declSig:optDeclSig $val\n set_option genInjectivity false in -- generates awful simp lemmas\n structure Wrapper$[.{$us,*}]? where\n value : type_of% @definition.{$us',*}\n prop : Eq @value @(delta% @definition)\n opaque wrapped$[.{$us,*}]? : Wrapper.{$us',*} := ⟨_, rfl⟩\n $mods:declModifiers def $n:ident$[.{$us,*}]? := value_proj @wrapped.{$us',*}\n theorem $n_def:ident $[.{$us,*}]? : eta_helper Eq @$n.{$us',*} @(delta% @definition) := by\n intros\n simp only [$n:ident]\n rw [wrapped.prop])\n", "meta": {"author": "leanprover-community", "repo": "mathlib4", "sha": "b9a0a30342ca06e9817e22dbe46e75fc7f435500", "save_path": "github-repos/lean/leanprover-community-mathlib4", "path": "github-repos/lean/leanprover-community-mathlib4/mathlib4-b9a0a30342ca06e9817e22dbe46e75fc7f435500/Mathlib/Tactic/IrreducibleDef.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.44167299096624174, "lm_q2_score": 0.07696083357893281, "lm_q1q2_score": 0.033991521554062425}} {"text": "/-\nCopyright (c) 2014 Parikshit Khanna. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthor: Parikshit Khanna, Jeremy Avigad, Leonardo de Moura, Floris van Doorn\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.data.list.basic\nimport Mathlib.Lean3Lib.init.function\nimport Mathlib.Lean3Lib.init.meta.default\nimport Mathlib.Lean3Lib.init.data.nat.lemmas\nimport Mathlib.Lean3Lib.init.meta.interactive\nimport Mathlib.Lean3Lib.init.meta.smt.rsimp\n \n\nuniverses u v w w₂ w₁ \n\nnamespace Mathlib\n\nnamespace list\n\n\n/- append -/\n\n@[simp] theorem nil_append {α : Type u} (s : List α) : [] ++ s = s :=\n rfl\n\n@[simp] theorem cons_append {α : Type u} (x : α) (s : List α) (t : List α) : x :: s ++ t = x :: (s ++ t) :=\n rfl\n\n@[simp] theorem append_nil {α : Type u} (t : List α) : t ++ [] = t := sorry\n\n@[simp] theorem append_assoc {α : Type u} (s : List α) (t : List α) (u : List α) : s ++ t ++ u = s ++ (t ++ u) := sorry\n\n/- length -/\n\ntheorem length_cons {α : Type u} (a : α) (l : List α) : length (a :: l) = length l + 1 :=\n rfl\n\n@[simp] theorem length_append {α : Type u} (s : List α) (t : List α) : length (s ++ t) = length s + length t := sorry\n\n@[simp] theorem length_repeat {α : Type u} (a : α) (n : ℕ) : length (repeat a n) = n := sorry\n\n@[simp] theorem length_tail {α : Type u} (l : List α) : length (tail l) = length l - 1 :=\n list.cases_on l (Eq.refl (length (tail []))) fun (l_hd : α) (l_tl : List α) => Eq.refl (length (tail (l_hd :: l_tl)))\n\n-- TODO(Leo): cleanup proof after arith dec proc\n\n@[simp] theorem length_drop {α : Type u} (i : ℕ) (l : List α) : length (drop i l) = length l - i := sorry\n\n/- map -/\n\ntheorem map_cons {α : Type u} {β : Type v} (f : α → β) (a : α) (l : List α) : map f (a :: l) = f a :: map f l :=\n rfl\n\n@[simp] theorem map_append {α : Type u} {β : Type v} (f : α → β) (l₁ : List α) (l₂ : List α) : map f (l₁ ++ l₂) = map f l₁ ++ map f l₂ := sorry\n\ntheorem map_singleton {α : Type u} {β : Type v} (f : α → β) (a : α) : map f [a] = [f a] :=\n rfl\n\n@[simp] theorem map_id {α : Type u} (l : List α) : map id l = l := sorry\n\n@[simp] theorem map_map {α : Type u} {β : Type v} {γ : Type w} (g : β → γ) (f : α → β) (l : List α) : map g (map f l) = map (g ∘ f) l := sorry\n\n@[simp] theorem length_map {α : Type u} {β : Type v} (f : α → β) (l : List α) : length (map f l) = length l := sorry\n\n/- bind -/\n\n@[simp] theorem nil_bind {α : Type u} {β : Type v} (f : α → List β) : list.bind [] f = [] := sorry\n\n@[simp] theorem cons_bind {α : Type u} {β : Type v} (x : α) (xs : List α) (f : α → List β) : list.bind (x :: xs) f = f x ++ list.bind xs f := sorry\n\n@[simp] theorem append_bind {α : Type u} {β : Type v} (xs : List α) (ys : List α) (f : α → List β) : list.bind (xs ++ ys) f = list.bind xs f ++ list.bind ys f := sorry\n\n/- mem -/\n\n@[simp] theorem mem_nil_iff {α : Type u} (a : α) : a ∈ [] ↔ False :=\n iff.rfl\n\n@[simp] theorem not_mem_nil {α : Type u} (a : α) : ¬a ∈ [] :=\n iff.mp (mem_nil_iff a)\n\n@[simp] theorem mem_cons_self {α : Type u} (a : α) (l : List α) : a ∈ a :: l :=\n Or.inl rfl\n\n@[simp] theorem mem_cons_iff {α : Type u} (a : α) (y : α) (l : List α) : a ∈ y :: l ↔ a = y ∨ a ∈ l :=\n iff.rfl\n\ntheorem mem_cons_eq {α : Type u} (a : α) (y : α) (l : List α) : a ∈ y :: l = (a = y ∨ a ∈ l) :=\n rfl\n\ntheorem mem_cons_of_mem {α : Type u} (y : α) {a : α} {l : List α} : a ∈ l → a ∈ y :: l :=\n fun (H : a ∈ l) => Or.inr H\n\ntheorem eq_or_mem_of_mem_cons {α : Type u} {a : α} {y : α} {l : List α} : a ∈ y :: l → a = y ∨ a ∈ l :=\n fun (h : a ∈ y :: l) => h\n\n@[simp] theorem mem_append {α : Type u} {a : α} {s : List α} {t : List α} : a ∈ s ++ t ↔ a ∈ s ∨ a ∈ t := sorry\n\ntheorem mem_append_eq {α : Type u} (a : α) (s : List α) (t : List α) : a ∈ s ++ t = (a ∈ s ∨ a ∈ t) :=\n propext mem_append\n\ntheorem mem_append_left {α : Type u} {a : α} {l₁ : List α} (l₂ : List α) (h : a ∈ l₁) : a ∈ l₁ ++ l₂ :=\n iff.mpr mem_append (Or.inl h)\n\ntheorem mem_append_right {α : Type u} {a : α} (l₁ : List α) {l₂ : List α} (h : a ∈ l₂) : a ∈ l₁ ++ l₂ :=\n iff.mpr mem_append (Or.inr h)\n\n@[simp] theorem not_bex_nil {α : Type u} (p : α → Prop) : ¬∃ (x : α), ∃ (H : x ∈ []), p x := sorry\n\n@[simp] theorem ball_nil {α : Type u} (p : α → Prop) (x : α) (H : x ∈ []) : p x :=\n false.elim\n\n@[simp] theorem bex_cons {α : Type u} (p : α → Prop) (a : α) (l : List α) : (∃ (x : α), ∃ (H : x ∈ a :: l), p x) ↔ p a ∨ ∃ (x : α), ∃ (H : x ∈ l), p x := sorry\n\n@[simp] theorem ball_cons {α : Type u} (p : α → Prop) (a : α) (l : List α) : (∀ (x : α), x ∈ a :: l → p x) ↔ p a ∧ ∀ (x : α), x ∈ l → p x := sorry\n\n/- list subset -/\n\nprotected def subset {α : Type u} (l₁ : List α) (l₂ : List α) :=\n ∀ {a : α}, a ∈ l₁ → a ∈ l₂\n\nprotected instance has_subset {α : Type u} : has_subset (List α) :=\n has_subset.mk list.subset\n\n@[simp] theorem nil_subset {α : Type u} (l : List α) : [] ⊆ l :=\n fun (b : α) (i : b ∈ []) => false.elim (iff.mp (mem_nil_iff b) i)\n\n@[simp] theorem subset.refl {α : Type u} (l : List α) : l ⊆ l :=\n fun (b : α) (i : b ∈ l) => i\n\ntheorem subset.trans {α : Type u} {l₁ : List α} {l₂ : List α} {l₃ : List α} (h₁ : l₁ ⊆ l₂) (h₂ : l₂ ⊆ l₃) : l₁ ⊆ l₃ :=\n fun (b : α) (i : b ∈ l₁) => h₂ (h₁ i)\n\n@[simp] theorem subset_cons {α : Type u} (a : α) (l : List α) : l ⊆ a :: l :=\n fun (b : α) (i : b ∈ l) => Or.inr i\n\ntheorem subset_of_cons_subset {α : Type u} {a : α} {l₁ : List α} {l₂ : List α} : a :: l₁ ⊆ l₂ → l₁ ⊆ l₂ :=\n fun (s : a :: l₁ ⊆ l₂) (b : α) (i : b ∈ l₁) => s (mem_cons_of_mem a i)\n\ntheorem cons_subset_cons {α : Type u} {l₁ : List α} {l₂ : List α} (a : α) (s : l₁ ⊆ l₂) : a :: l₁ ⊆ a :: l₂ :=\n fun (b : α) (hin : b ∈ a :: l₁) =>\n or.elim (eq_or_mem_of_mem_cons hin) (fun (e : b = a) => Or.inl e) fun (i : b ∈ l₁) => Or.inr (s i)\n\n@[simp] theorem subset_append_left {α : Type u} (l₁ : List α) (l₂ : List α) : l₁ ⊆ l₁ ++ l₂ :=\n fun (b : α) => mem_append_left l₂\n\n@[simp] theorem subset_append_right {α : Type u} (l₁ : List α) (l₂ : List α) : l₂ ⊆ l₁ ++ l₂ :=\n fun (b : α) => mem_append_right l₁\n\ntheorem subset_cons_of_subset {α : Type u} (a : α) {l₁ : List α} {l₂ : List α} : l₁ ⊆ l₂ → l₁ ⊆ a :: l₂ :=\n fun (s : l₁ ⊆ l₂) (a_1 : α) (i : a_1 ∈ l₁) => Or.inr (s i)\n\ntheorem eq_nil_of_length_eq_zero {α : Type u} {l : List α} : length l = 0 → l = [] := sorry\n\ntheorem ne_nil_of_length_eq_succ {α : Type u} {l : List α} {n : ℕ} : length l = Nat.succ n → l ≠ [] := sorry\n\n@[simp] theorem length_map₂ {α : Type u} {β : Type v} {γ : Type w} (f : α → β → γ) (l₁ : List α) (l₂ : List β) : length (map₂ f l₁ l₂) = min (length l₁) (length l₂) := sorry\n\n@[simp] theorem length_take {α : Type u} (i : ℕ) (l : List α) : length (take i l) = min i (length l) := sorry\n\ntheorem length_take_le {α : Type u} (n : ℕ) (l : List α) : length (take n l) ≤ n := sorry\n\ntheorem length_remove_nth {α : Type u} (l : List α) (i : ℕ) : i < length l → length (remove_nth l i) = length l - 1 := sorry\n\n@[simp] theorem partition_eq_filter_filter {α : Type u} (p : α → Prop) [decidable_pred p] (l : List α) : partition p l = (filter p l, filter (Not ∘ p) l) := sorry\n\n/- sublists -/\n\ninductive sublist {α : Type u} : List α → List α → Prop\nwhere\n| slnil : sublist [] []\n| cons : ∀ (l₁ l₂ : List α) (a : α), sublist l₁ l₂ → sublist l₁ (a :: l₂)\n| cons2 : ∀ (l₁ l₂ : List α) (a : α), sublist l₁ l₂ → sublist (a :: l₁) (a :: l₂)\n\ninfixl:50 \" <+ \" => Mathlib.list.sublist\n\ntheorem length_le_of_sublist {α : Type u} {l₁ : List α} {l₂ : List α} : l₁ <+ l₂ → length l₁ ≤ length l₂ := sorry\n\n/- filter -/\n\n@[simp] theorem filter_nil {α : Type u} (p : α → Prop) [h : decidable_pred p] : filter p [] = [] :=\n rfl\n\n@[simp] theorem filter_cons_of_pos {α : Type u} {p : α → Prop} [h : decidable_pred p] {a : α} (l : List α) : p a → filter p (a :: l) = a :: filter p l :=\n fun (pa : p a) => if_pos pa\n\n@[simp] theorem filter_cons_of_neg {α : Type u} {p : α → Prop} [h : decidable_pred p] {a : α} (l : List α) : ¬p a → filter p (a :: l) = filter p l :=\n fun (pa : ¬p a) => if_neg pa\n\n@[simp] theorem filter_append {α : Type u} {p : α → Prop} [h : decidable_pred p] (l₁ : List α) (l₂ : List α) : filter p (l₁ ++ l₂) = filter p l₁ ++ filter p l₂ := sorry\n\n@[simp] theorem filter_sublist {α : Type u} {p : α → Prop} [h : decidable_pred p] (l : List α) : filter p l <+ l := sorry\n\n/- map_accumr -/\n\n-- This runs a function over a list returning the intermediate results and a\n\n-- a final result.\n\ndef map_accumr {α : Type u} {β : Type v} {σ : Type w₂} (f : α → σ → σ × β) : List α → σ → σ × List β :=\n sorry\n\n@[simp] theorem length_map_accumr {α : Type u} {β : Type v} {σ : Type w₂} (f : α → σ → σ × β) (x : List α) (s : σ) : length (prod.snd (map_accumr f x s)) = length x := sorry\n\n-- This runs a function over two lists returning the intermediate results and a\n\n-- a final result.\n\ndef map_accumr₂ {α : Type u} {β : Type v} {φ : Type w₁} {σ : Type w₂} (f : α → β → σ → σ × φ) : List α → List β → σ → σ × List φ :=\n sorry\n\n@[simp] theorem length_map_accumr₂ {α : Type u} {β : Type v} {φ : Type w₁} {σ : Type w₂} (f : α → β → σ → σ × φ) (x : List α) (y : List β) (c : σ) : length (prod.snd (map_accumr₂ f x y c)) = min (length x) (length y) := sorry\n\n", "meta": {"author": "AurelienSaue", "repo": "Mathlib4_auto", "sha": "590df64109b08190abe22358fabc3eae000943f2", "save_path": "github-repos/lean/AurelienSaue-Mathlib4_auto", "path": "github-repos/lean/AurelienSaue-Mathlib4_auto/Mathlib4_auto-590df64109b08190abe22358fabc3eae000943f2/Mathlib/Lean3Lib/init/data/list/lemmas.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167941228964, "lm_q2_score": 0.0736962747921971, "lm_q1q2_score": 0.03397522034349874}} {"text": "/-\nCopyright (c) 2022 Yaël Dillies. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Yaël Dillies\n-/\nimport category_theory.category.Pointed\n\n/-!\n# The category of bipointed types\n\nThis defines `Bipointed`, the category of bipointed types.\n\n## TODO\n\nMonoidal structure\n-/\n\nopen category_theory\n\nuniverses u\nvariables {α β : Type*}\n\n/-- The category of bipointed types. -/\nstructure Bipointed : Type.{u + 1} :=\n(X : Type.{u})\n(to_prod : X × X)\n\nnamespace Bipointed\n\ninstance : has_coe_to_sort Bipointed Type* := ⟨X⟩\n\nattribute [protected] Bipointed.X\n\n/-- Turns a bipointing into a bipointed type. -/\ndef of {X : Type*} (to_prod : X × X) : Bipointed := ⟨X, to_prod⟩\n\n@[simp] lemma coe_of {X : Type*} (to_prod : X × X) : ↥(of to_prod) = X := rfl\n\nalias of ← _root_.prod.Bipointed\n\ninstance : inhabited Bipointed := ⟨of ((), ())⟩\n\n/-- Morphisms in `Bipointed`. -/\n@[ext] protected structure hom (X Y : Bipointed.{u}) : Type u :=\n(to_fun : X → Y)\n(map_fst : to_fun X.to_prod.1 = Y.to_prod.1)\n(map_snd : to_fun X.to_prod.2 = Y.to_prod.2)\n\nnamespace hom\n\n/-- The identity morphism of `X : Bipointed`. -/\n@[simps] def id (X : Bipointed) : hom X X := ⟨id, rfl, rfl⟩\n\ninstance (X : Bipointed) : inhabited (hom X X) := ⟨id X⟩\n\n/-- Composition of morphisms of `Bipointed`. -/\n@[simps] def comp {X Y Z : Bipointed.{u}} (f : hom X Y) (g : hom Y Z) : hom X Z :=\n⟨g.to_fun ∘ f.to_fun, by rw [function.comp_apply, f.map_fst, g.map_fst],\n by rw [function.comp_apply, f.map_snd, g.map_snd]⟩\n\nend hom\n\ninstance large_category : large_category Bipointed :=\n{ hom := hom,\n id := hom.id,\n comp := @hom.comp,\n id_comp' := λ _ _ _, hom.ext _ _ rfl,\n comp_id' := λ _ _ _, hom.ext _ _ rfl,\n assoc' := λ _ _ _ _ _ _ _, hom.ext _ _ rfl }\n\ninstance concrete_category : concrete_category Bipointed :=\n{ forget := { obj := Bipointed.X, map := @hom.to_fun },\n forget_faithful := ⟨@hom.ext⟩ }\n\n/-- Swaps the pointed elements of a bipointed type. `prod.swap` as a functor. -/\n@[simps] def swap : Bipointed ⥤ Bipointed :=\n{ obj := λ X, ⟨X, X.to_prod.swap⟩, map := λ X Y f, ⟨f.to_fun, f.map_snd, f.map_fst⟩ }\n\n/-- The equivalence between `Bipointed` and itself induced by `prod.swap` both ways. -/\n@[simps] def swap_equiv : Bipointed ≌ Bipointed :=\nequivalence.mk swap swap\n (nat_iso.of_components (λ X, { hom := ⟨id, rfl, rfl⟩, inv := ⟨id, rfl, rfl⟩ }) $ λ X Y f, rfl)\n (nat_iso.of_components (λ X, { hom := ⟨id, rfl, rfl⟩, inv := ⟨id, rfl, rfl⟩ }) $ λ X Y f, rfl)\n\n@[simp] lemma swap_equiv_symm : swap_equiv.symm = swap_equiv := rfl\n\nend Bipointed\n\n/-- The forgetful functor from `Bipointed` to `Pointed` which forgets about the second point. -/\ndef Bipointed_to_Pointed_fst : Bipointed ⥤ Pointed :=\n{ obj := λ X, ⟨X, X.to_prod.1⟩, map := λ X Y f, ⟨f.to_fun, f.map_fst⟩ }\n\n/-- The forgetful functor from `Bipointed` to `Pointed` which forgets about the first point. -/\ndef Bipointed_to_Pointed_snd : Bipointed ⥤ Pointed :=\n{ obj := λ X, ⟨X, X.to_prod.2⟩, map := λ X Y f, ⟨f.to_fun, f.map_snd⟩ }\n\n@[simp] lemma Bipointed_to_Pointed_fst_comp_forget :\n Bipointed_to_Pointed_fst ⋙ forget Pointed = forget Bipointed := rfl\n\n@[simp] lemma Bipointed_to_Pointed_snd_comp_forget :\n Bipointed_to_Pointed_snd ⋙ forget Pointed = forget Bipointed := rfl\n\n@[simp] lemma swap_comp_Bipointed_to_Pointed_fst :\n Bipointed.swap ⋙ Bipointed_to_Pointed_fst = Bipointed_to_Pointed_snd := rfl\n\n@[simp] lemma swap_comp_Bipointed_to_Pointed_snd :\n Bipointed.swap ⋙ Bipointed_to_Pointed_snd = Bipointed_to_Pointed_fst := rfl\n\n/-- The functor from `Pointed` to `Bipointed` which bipoints the point. -/\ndef Pointed_to_Bipointed : Pointed.{u} ⥤ Bipointed :=\n{ obj := λ X, ⟨X, X.point, X.point⟩, map := λ X Y f, ⟨f.to_fun, f.map_point, f.map_point⟩ }\n\n/-- The functor from `Pointed` to `Bipointed` which adds a second point. -/\ndef Pointed_to_Bipointed_fst : Pointed.{u} ⥤ Bipointed :=\n{ obj := λ X, ⟨option X, X.point, none⟩,\n map := λ X Y f, ⟨option.map f.to_fun, congr_arg _ f.map_point, rfl⟩,\n map_id' := λ X, Bipointed.hom.ext _ _ option.map_id,\n map_comp' := λ X Y Z f g, Bipointed.hom.ext _ _ (option.map_comp_map _ _).symm }\n\n/-- The functor from `Pointed` to `Bipointed` which adds a first point. -/\ndef Pointed_to_Bipointed_snd : Pointed.{u} ⥤ Bipointed :=\n{ obj := λ X, ⟨option X, none, X.point⟩,\n map := λ X Y f, ⟨option.map f.to_fun, rfl, congr_arg _ f.map_point⟩,\n map_id' := λ X, Bipointed.hom.ext _ _ option.map_id,\n map_comp' := λ X Y Z f g, Bipointed.hom.ext _ _ (option.map_comp_map _ _).symm }\n\n@[simp] lemma Pointed_to_Bipointed_fst_comp_swap :\n Pointed_to_Bipointed_fst ⋙ Bipointed.swap = Pointed_to_Bipointed_snd := rfl\n\n@[simp] lemma Pointed_to_Bipointed_snd_comp_swap :\n Pointed_to_Bipointed_snd ⋙ Bipointed.swap = Pointed_to_Bipointed_fst := rfl\n\n/-- `Bipointed_to_Pointed_fst` is inverse to `Pointed_to_Bipointed`. -/\n@[simps] def Pointed_to_Bipointed_comp_Bipointed_to_Pointed_fst :\n Pointed_to_Bipointed ⋙ Bipointed_to_Pointed_fst ≅ 𝟭 _ :=\nnat_iso.of_components (λ X, { hom := ⟨id, rfl⟩, inv := ⟨id, rfl⟩ }) $ λ X Y f, rfl\n\n/-- `Bipointed_to_Pointed_snd` is inverse to `Pointed_to_Bipointed`. -/\n@[simps] def Pointed_to_Bipointed_comp_Bipointed_to_Pointed_snd :\n Pointed_to_Bipointed ⋙ Bipointed_to_Pointed_snd ≅ 𝟭 _ :=\nnat_iso.of_components (λ X, { hom := ⟨id, rfl⟩, inv := ⟨id, rfl⟩ }) $ λ X Y f, rfl\n\n/-- The free/forgetful adjunction between `Pointed_to_Bipointed_fst` and `Bipointed_to_Pointed_fst`.\n-/\ndef Pointed_to_Bipointed_fst_Bipointed_to_Pointed_fst_adjunction :\n Pointed_to_Bipointed_fst ⊣ Bipointed_to_Pointed_fst :=\nadjunction.mk_of_hom_equiv\n{ hom_equiv := λ X Y, { to_fun := λ f, ⟨f.to_fun ∘ option.some, f.map_fst⟩,\n inv_fun := λ f, ⟨λ o, o.elim Y.to_prod.2 f.to_fun, f.map_point, rfl⟩,\n left_inv := λ f, by { ext, cases x, exact f.map_snd.symm, refl },\n right_inv := λ f, Pointed.hom.ext _ _ rfl },\n hom_equiv_naturality_left_symm' := λ X' X Y f g, by { ext, cases x; refl } }\n\n/-- The free/forgetful adjunction between `Pointed_to_Bipointed_snd` and `Bipointed_to_Pointed_snd`.\n-/\ndef Pointed_to_Bipointed_snd_Bipointed_to_Pointed_snd_adjunction :\n Pointed_to_Bipointed_snd ⊣ Bipointed_to_Pointed_snd :=\nadjunction.mk_of_hom_equiv\n{ hom_equiv := λ X Y, { to_fun := λ f, ⟨f.to_fun ∘ option.some, f.map_snd⟩,\n inv_fun := λ f, ⟨λ o, o.elim Y.to_prod.1 f.to_fun, rfl, f.map_point⟩,\n left_inv := λ f, by { ext, cases x, exact f.map_fst.symm, refl },\n right_inv := λ f, Pointed.hom.ext _ _ rfl },\n hom_equiv_naturality_left_symm' := λ X' X Y f g, by { ext, cases x; refl } }\n", "meta": {"author": "Parinya-Siri", "repo": "lean-machine-learning", "sha": "ec610bac246ae7108fc6f0c140b3440f0fbacc52", "save_path": "github-repos/lean/Parinya-Siri-lean-machine-learning", "path": "github-repos/lean/Parinya-Siri-lean-machine-learning/lean-machine-learning-ec610bac246ae7108fc6f0c140b3440f0fbacc52/matlib/category_theory/category/Bipointed.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4455295350395727, "lm_q2_score": 0.07585818628900447, "lm_q1q2_score": 0.03379706246628545}} {"text": "/-\nCopyright (c) 2022 Andrew Yang. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Andrew Yang\n-/\nimport morphisms.affine\nimport ring_theory.local_properties\n\n/-!\n\n# Properties of morphisms from properties of ring homs.\n\nWe provide the basic framework for talking about properties of morphisms that come from properties\nof ring homs. For `P` a property of ring homs, we have two ways of defining a property of scheme\nmorphisms:\n\nLet `f : X ⟶ Y`,\n- `target_affine_locally (affine_and P)`: the preimage of an affine open `U = Spec A` is affine\n (`= Spec B`) and `A ⟶ B` satisfies `P`. (TODO)\n- `affine_locally P`: For each pair of affine open `U = Spec A ⊆ X` and `V = Spec B ⊆ f ⁻¹' U`,\n the ring hom `A ⟶ B` satisfies `P`.\n\nFor these notions to be well defined, we require `P` be a sufficient local property. For the former,\n`P` should be local on the source (`ring_hom.respects_iso P`, `ring_hom.localization_preserves P`,\n`ring_hom.of_localization_span`), and `target_affine_locally (affine_and P)` will be local on\nthe target. (TODO)\n\nFor the latter `P` should be local on the target (`ring_hom.property_is_local P`), and\n`affine_locally P` will be local on both the source and the target.\n\nFurther more, these properties are stable under compositions (resp. base change) if `P` is. (TODO)\n\n-/\n\nuniverse u\n\nopen category_theory opposite topological_space category_theory.limits algebraic_geometry\n\nvariable (P : ∀ {R S : Type u} [comm_ring R] [comm_ring S] (f : by exactI R →+* S), Prop)\n\nnamespace ring_hom\n\ninclude P\n\nvariable {P}\n\nlemma respects_iso.basic_open_iff (hP : respects_iso @P) {X Y : Scheme}\n [is_affine X] [is_affine Y] (f : X ⟶ Y) (r : Y.presheaf.obj (opposite.op ⊤)) :\n P (Scheme.Γ.map (f ∣_ Y.basic_open r).op) ↔\n P (@is_localization.away.map (Y.presheaf.obj (opposite.op ⊤)) _\n (Y.presheaf.obj (opposite.op $ Y.basic_open r)) _ _\n (X.presheaf.obj (opposite.op ⊤)) _ (X.presheaf.obj\n (opposite.op $ X.basic_open (Scheme.Γ.map f.op r))) _ _ (Scheme.Γ.map f.op) r _ _) :=\nbegin\n rw [Γ_map_morphism_restrict, hP.cancel_left_is_iso, hP.cancel_right_is_iso,\n ← (hP.cancel_right_is_iso (f.val.c.app (opposite.op (Y.basic_open r))) (X.presheaf.map\n (eq_to_hom (Scheme.preimage_basic_open f r).symm).op)), ← eq_iff_iff],\n congr,\n delta is_localization.away.map,\n refine is_localization.ring_hom_ext (submonoid.powers r) _,\n convert (is_localization.map_comp _).symm using 1,\n change Y.presheaf.map _ ≫ _ = _ ≫ X.presheaf.map _,\n rw f.val.c.naturality_assoc,\n erw ← X.presheaf.map_comp,\n congr,\nend\n\nlemma respects_iso.basic_open_iff_localization (hP : respects_iso @P)\n {X Y : Scheme} [is_affine X] [is_affine Y] (f : X ⟶ Y) (r : Y.presheaf.obj (opposite.op ⊤)) :\n P (Scheme.Γ.map (f ∣_ Y.basic_open r).op) ↔\n P (localization.away_map (Scheme.Γ.map f.op) r) :=\n(hP.basic_open_iff _ _).trans (hP.is_localization_away_iff _ _ _ _).symm\n\nlemma respects_iso.of_restrict_morphism_restrict_iff (hP : ring_hom.respects_iso @P)\n {X Y : Scheme} [is_affine Y] (f : X ⟶ Y) (r : Y.presheaf.obj (opposite.op ⊤))\n (U : opens X.carrier) (hU : is_affine_open U) {V : opens _}\n (e : V = (opens.map (X.of_restrict ((opens.map f.1.base).obj _).open_embedding).1.base).obj U) :\n P (Scheme.Γ.map ((X.restrict ((opens.map f.1.base).obj _).open_embedding).of_restrict\n V.open_embedding ≫ f ∣_ Y.basic_open r).op) ↔\n P (localization.away_map (Scheme.Γ.map (X.of_restrict U.open_embedding ≫ f).op) r) :=\nbegin\n subst e,\n convert (hP.is_localization_away_iff _ _ _ _).symm,\n rotate,\n { apply_instance },\n { apply ring_hom.to_algebra,\n refine X.presheaf.map\n (@hom_of_le _ _ ((is_open_map.functor _).obj _) ((is_open_map.functor _).obj _) _).op,\n rw [opens.le_def],\n dsimp,\n change coe '' (coe '' set.univ) ⊆ coe '' set.univ,\n rw [subtype.coe_image_univ, subtype.coe_image_univ],\n exact set.image_preimage_subset _ _ },\n { exact algebraic_geometry.Γ_restrict_is_localization Y r },\n { rw ← U.open_embedding_obj_top at hU,\n dsimp [Scheme.Γ_obj_op, Scheme.Γ_map_op, Scheme.restrict],\n apply algebraic_geometry.is_localization_of_eq_basic_open _ hU,\n rw [opens.open_embedding_obj_top, opens.functor_obj_map_obj],\n convert (X.basic_open_res (Scheme.Γ.map f.op r) (hom_of_le le_top).op).symm using 1,\n rw [opens.open_embedding_obj_top, opens.open_embedding_obj_top, inf_comm,\n Scheme.Γ_map_op, ← Scheme.preimage_basic_open] },\n { apply is_localization.ring_hom_ext (submonoid.powers r) _,\n swap, { exact algebraic_geometry.Γ_restrict_is_localization Y r },\n rw [is_localization.away.map, is_localization.map_comp, ring_hom.algebra_map_to_algebra,\n ring_hom.algebra_map_to_algebra, op_comp, functor.map_comp, op_comp, functor.map_comp],\n refine (@category.assoc CommRing _ _ _ _ _ _ _ _).symm.trans _,\n refine eq.trans _ (@category.assoc CommRing _ _ _ _ _ _ _ _),\n dsimp only [Scheme.Γ_map, quiver.hom.unop_op],\n rw [morphism_restrict_c_app, category.assoc, category.assoc, category.assoc],\n erw [f.1.c.naturality_assoc, ← X.presheaf.map_comp, ← X.presheaf.map_comp,\n ← X.presheaf.map_comp],\n congr },\nend\n\nlemma stable_under_base_change.Γ_pullback_fst\n (hP : stable_under_base_change @P) (hP' : respects_iso @P) {X Y S : Scheme}\n [is_affine X] [is_affine Y] [is_affine S]\n (f : X ⟶ S) (g : Y ⟶ S) (H : P (Scheme.Γ.map g.op)) :\n P (Scheme.Γ.map (pullback.fst : pullback f g ⟶ _).op) :=\nbegin\n rw [← preserves_pullback.iso_inv_fst AffineScheme.forget_to_Scheme\n (AffineScheme.of_hom f) (AffineScheme.of_hom g), op_comp, functor.map_comp,\n hP'.cancel_right_is_iso, AffineScheme.forget_to_Scheme_map],\n have := _root_.congr_arg quiver.hom.unop (preserves_pullback.iso_hom_fst AffineScheme.Γ.right_op\n (AffineScheme.of_hom f) (AffineScheme.of_hom g)),\n simp only [quiver.hom.unop_op, functor.right_op_map, unop_comp] at this,\n delta AffineScheme.Γ at this,\n simp only [quiver.hom.unop_op, functor.comp_map, AffineScheme.forget_to_Scheme_map,\n functor.op_map] at this,\n rw [← this, hP'.cancel_right_is_iso,\n ← pushout_iso_unop_pullback_inl_hom (quiver.hom.unop _) (quiver.hom.unop _),\n hP'.cancel_right_is_iso],\n exact hP.pushout_inl _ hP' _ _ H\nend\n\nend ring_hom\n\nnamespace algebraic_geometry\n\n/-- For `P` a property of ring homomorphisms, `source_affine_locally P` holds for `f : X ⟶ Y`\nwhenever `P` holds for the restriction of `f` on every affine open subset of `X`. -/\ndef source_affine_locally : affine_target_morphism_property :=\nλ X Y f hY, ∀ (U : X.affine_opens), P (Scheme.Γ.map (X.of_restrict U.1.open_embedding ≫ f).op)\n\n/-- For `P` a property of ring homomorphisms, `affine_locally P` holds for `f : X ⟶ Y` if for each\naffine open `U = Spec A ⊆ Y` and `V = Spec B ⊆ f ⁻¹' U`, the ring hom `A ⟶ B` satisfies `P`.\nAlso see `affine_locally_iff_affine_opens_le`. -/\nabbreviation affine_locally : morphism_property Scheme :=\ntarget_affine_locally (source_affine_locally @P)\n\nvariable {P}\n\nlemma source_affine_locally_respects_iso (h₁ : ring_hom.respects_iso @P) :\n (source_affine_locally @P).to_property.respects_iso :=\nbegin\n apply affine_target_morphism_property.respects_iso_mk,\n { introv H U,\n rw [← h₁.cancel_right_is_iso _ (Scheme.Γ.map (Scheme.restrict_map_iso e.inv U.1).hom.op),\n ← functor.map_comp, ← op_comp],\n convert H ⟨_, U.prop.map_is_iso e.inv⟩ using 3,\n rw [is_open_immersion.iso_of_range_eq_hom, is_open_immersion.lift_fac_assoc,\n category.assoc, e.inv_hom_id_assoc],\n refl },\n { introv H U,\n rw [← category.assoc, op_comp, functor.map_comp, h₁.cancel_left_is_iso],\n exact H U }\nend\n\nlemma affine_locally_mono\n (P₁ P₂ : ∀ ⦃R S : Type u⦄ [comm_ring R] [comm_ring S] (f : by exactI R →+* S), Prop)\n (H : ∀ {R S : Type u} [comm_ring R] [comm_ring S], by exactI ∀ (f : R →+* S), P₁ f → P₂ f) :\n affine_locally P₁ ≤ affine_locally P₂ :=\nbegin\n refine target_affine_locally_mono _,\n intros X Y f hY hf U,\n exact H _ (hf _),\nend\nlemma affine_locally_respects_iso (h : ring_hom.respects_iso @P) :\n (affine_locally @P).respects_iso :=\ntarget_affine_locally_respects_iso (source_affine_locally_respects_iso h)\n\nlemma affine_locally_iff_affine_opens_le\n (hP : ring_hom.respects_iso @P) {X Y : Scheme} (f : X ⟶ Y) :\n affine_locally @P f ↔\n (∀ (U : Y.affine_opens) (V : X.affine_opens) (e : V.1 ≤ (opens.map f.1.base).obj U.1),\n P (f.app_le e)) :=\nbegin\n apply forall_congr,\n intro U,\n delta source_affine_locally,\n simp_rw [op_comp, Scheme.Γ.map_comp, Γ_map_morphism_restrict, category.assoc, Scheme.Γ_map_op,\n hP.cancel_left_is_iso],\n split,\n { intros H V e,\n let U' := (opens.map f.val.base).obj U.1,\n have e' : U'.open_embedding.is_open_map.functor.obj ((opens.map U'.inclusion).obj V.1) = V.1,\n { ext1, refine set.image_preimage_eq_inter_range.trans (set.inter_eq_left_iff_subset.mpr _),\n convert e, exact subtype.range_coe },\n have := H ⟨(opens.map (X.of_restrict (U'.open_embedding)).1.base).obj V.1, _⟩,\n erw ← X.presheaf.map_comp at this,\n rw [← hP.cancel_right_is_iso _ (X.presheaf.map (eq_to_hom _)), category.assoc,\n ← X.presheaf.map_comp],\n convert this using 1,\n { dsimp only [functor.op, unop_op], rw opens.open_embedding_obj_top, congr' 1, exact e'.symm },\n { apply_instance },\n { apply (is_affine_open_iff_of_is_open_immersion (X.of_restrict _) _).mp,\n convert V.2,\n apply_instance } },\n { intros H V,\n specialize H ⟨_, V.2.image_is_open_immersion (X.of_restrict _)⟩ (subtype.coe_image_subset _ _),\n erw ← X.presheaf.map_comp,\n rw [← hP.cancel_right_is_iso _ (X.presheaf.map (eq_to_hom _)), category.assoc,\n ← X.presheaf.map_comp],\n convert H,\n { dsimp only [functor.op, unop_op], rw opens.open_embedding_obj_top, refl },\n { apply_instance } }\nend\n\nlemma Scheme_restrict_basic_open_of_localization_preserves\n (h₁ : ring_hom.respects_iso @P)\n (h₂ : ring_hom.localization_preserves @P)\n {X Y : Scheme} [is_affine Y] (f : X ⟶ Y) (r : Y.presheaf.obj (op ⊤))\n (H : source_affine_locally @P f)\n (U : (X.restrict ((opens.map f.1.base).obj $ Y.basic_open r).open_embedding).affine_opens) :\n P (Scheme.Γ.map\n ((X.restrict ((opens.map f.1.base).obj $ Y.basic_open r).open_embedding).of_restrict\n U.1.open_embedding ≫ f ∣_ Y.basic_open r).op) :=\nbegin\n specialize H ⟨_, U.2.image_is_open_immersion (X.of_restrict _)⟩,\n convert (h₁.of_restrict_morphism_restrict_iff _ _ _ _ _).mpr _ using 1,\n swap 5,\n { exact h₂.away r H },\n { apply_instance },\n { exact U.2.image_is_open_immersion _},\n { ext1, exact (set.preimage_image_eq _ subtype.coe_injective).symm }\nend\n\nlemma source_affine_locally_is_local\n (h₁ : ring_hom.respects_iso @P)\n (h₂ : ring_hom.localization_preserves @P)\n (h₃ : ring_hom.of_localization_span @P) : (source_affine_locally @P).is_local :=\nbegin\n constructor,\n { exact source_affine_locally_respects_iso h₁ },\n { introv H U,\n apply Scheme_restrict_basic_open_of_localization_preserves h₁ h₂; assumption },\n { introv hs hs' U,\n resetI,\n apply h₃ _ _ hs,\n intro r,\n have := hs' r ⟨(opens.map (X.of_restrict _).1.base).obj U.1, _⟩,\n rwa h₁.of_restrict_morphism_restrict_iff at this,\n { exact U.2 },\n { refl },\n { apply_instance },\n { suffices : ∀ (V = (opens.map f.val.base).obj (Y.basic_open r.val)),\n is_affine_open ((opens.map (X.of_restrict V.open_embedding).1.base).obj U.1),\n { exact this _ rfl, },\n intros V hV,\n rw Scheme.preimage_basic_open at hV,\n subst hV,\n exact U.2.map_restrict_basic_open (Scheme.Γ.map f.op r.1) } }\nend\n\nvariables {P} (hP : ring_hom.property_is_local @P)\n\nlemma source_affine_locally_of_source_open_cover_aux\n (h₁ : ring_hom.respects_iso @P)\n (h₃ : ring_hom.of_localization_span_target @P)\n {X Y : Scheme} (f : X ⟶ Y) (U : X.affine_opens)\n (s : set (X.presheaf.obj (op U.1))) (hs : ideal.span s = ⊤)\n (hs' : ∀ (r : s), P (Scheme.Γ.map (X.of_restrict (X.basic_open r.1).open_embedding ≫ f).op)) :\n P (Scheme.Γ.map (X.of_restrict U.1.open_embedding ≫ f).op) :=\nbegin\n apply_fun ideal.map (X.presheaf.map (eq_to_hom U.1.open_embedding_obj_top).op) at hs,\n rw [ideal.map_span, ideal.map_top] at hs,\n apply h₃ _ _ hs,\n rintro ⟨s, r, hr, hs⟩,\n have := (@@localization.alg_equiv _ _ _ _ _ (@@algebraic_geometry.Γ_restrict_is_localization\n _ U.2 s)).to_ring_equiv.to_CommRing_iso,\n refine (h₁.cancel_right_is_iso _ (@@localization.alg_equiv _ _ _ _ _\n (@@algebraic_geometry.Γ_restrict_is_localization _ U.2 s))\n .to_ring_equiv.to_CommRing_iso.hom).mp _,\n subst hs,\n rw [CommRing.comp_eq_ring_hom_comp, ← ring_hom.comp_assoc],\n erw [is_localization.map_comp, ring_hom.comp_id],\n rw [ring_hom.algebra_map_to_algebra, op_comp, functor.map_comp, ← CommRing.comp_eq_ring_hom_comp,\n Scheme.Γ_map_op, Scheme.Γ_map_op, Scheme.Γ_map_op, category.assoc],\n erw ← X.presheaf.map_comp,\n rw [← h₁.cancel_right_is_iso _ (X.presheaf.map (eq_to_hom _))],\n convert hs' ⟨r, hr⟩ using 1,\n { erw category.assoc, rw [← X.presheaf.map_comp, op_comp, Scheme.Γ.map_comp,\n Scheme.Γ_map_op, Scheme.Γ_map_op], congr },\n { dsimp [functor.op],\n conv_lhs { rw opens.open_embedding_obj_top },\n conv_rhs { rw opens.open_embedding_obj_top },\n erw Scheme.image_basic_open (X.of_restrict U.1.open_embedding),\n erw PresheafedSpace.is_open_immersion.of_restrict_inv_app_apply,\n rw Scheme.basic_open_res_eq },\n { apply_instance }\nend\n\nlemma is_open_immersion_comp_of_source_affine_locally (h₁ : ring_hom.respects_iso @P)\n {X Y Z : Scheme} [is_affine X] [is_affine Z] (f : X ⟶ Y) [is_open_immersion f] (g : Y ⟶ Z)\n (h₂ : source_affine_locally @P g) :\n P (Scheme.Γ.map (f ≫ g).op) :=\nbegin\n rw [← h₁.cancel_right_is_iso _ (Scheme.Γ.map (is_open_immersion.iso_of_range_eq\n (Y.of_restrict _) f _).hom.op), ← functor.map_comp, ← op_comp],\n convert h₂ ⟨_, range_is_affine_open_of_open_immersion f⟩ using 3,\n { rw [is_open_immersion.iso_of_range_eq_hom, is_open_immersion.lift_fac_assoc] },\n { apply_instance },\n { exact subtype.range_coe },\n { apply_instance }\nend\n\nend algebraic_geometry\n\nopen algebraic_geometry\n\nnamespace ring_hom.property_is_local\n\nvariables {P} (hP : ring_hom.property_is_local @P)\n\ninclude hP\n\nlemma source_affine_locally_of_source_open_cover\n {X Y : Scheme} (f : X ⟶ Y) [is_affine Y]\n (𝒰 : X.open_cover) [∀ i, is_affine (𝒰.obj i)] (H : ∀ i, P (Scheme.Γ.map (𝒰.map i ≫ f).op)) :\n source_affine_locally @P f :=\nbegin\n let S := λ i, (⟨⟨set.range (𝒰.map i).1.base, (𝒰.is_open i).base_open.open_range⟩,\n range_is_affine_open_of_open_immersion (𝒰.map i)⟩ : X.affine_opens),\n intros U,\n apply of_affine_open_cover U,\n swap 5, { exact set.range S },\n { intros U r H,\n convert hP.stable_under_composition _ _ H _ using 1,\n swap,\n { refine X.presheaf.map\n (@hom_of_le _ _ ((is_open_map.functor _).obj _) ((is_open_map.functor _).obj _) _).op,\n rw [unop_op, unop_op, opens.open_embedding_obj_top, opens.open_embedding_obj_top],\n exact X.basic_open_le _ },\n { rw [op_comp, op_comp, functor.map_comp, functor.map_comp],\n refine (eq.trans _ (category.assoc _ _ _).symm : _),\n congr' 1,\n refine eq.trans _ (X.presheaf.map_comp _ _),\n change X.presheaf.map _ = _,\n congr },\n convert hP.holds_for_localization_away _\n (X.presheaf.map (eq_to_hom U.1.open_embedding_obj_top).op r),\n { exact (ring_hom.algebra_map_to_algebra _).symm },\n { dsimp [Scheme.Γ],\n have := U.2,\n rw ← U.1.open_embedding_obj_top at this,\n convert is_localization_basic_open this _ using 6;\n rw opens.open_embedding_obj_top; exact (Scheme.basic_open_res_eq _ _ _).symm } },\n { introv hs hs',\n exact source_affine_locally_of_source_open_cover_aux hP.respects_iso hP.2 _ _ _ hs hs' },\n { rw set.eq_univ_iff_forall,\n intro x,\n rw set.mem_Union,\n exact ⟨⟨_, 𝒰.f x, rfl⟩, 𝒰.covers x⟩ },\n { rintro ⟨_, i, rfl⟩,\n specialize H i,\n rw ← hP.respects_iso.cancel_right_is_iso _ (Scheme.Γ.map (is_open_immersion.iso_of_range_eq\n (𝒰.map i) (X.of_restrict (S i).1.open_embedding) subtype.range_coe.symm).inv.op) at H,\n rwa [← Scheme.Γ.map_comp, ← op_comp, is_open_immersion.iso_of_range_eq_inv,\n is_open_immersion.lift_fac_assoc] at H }\nend\n\nlemma affine_open_cover_tfae {X Y : Scheme.{u}}\n [is_affine Y] (f : X ⟶ Y) :\n tfae [source_affine_locally @P f,\n ∃ (𝒰 : Scheme.open_cover.{u} X) [∀ i, is_affine (𝒰.obj i)],\n ∀ (i : 𝒰.J), P (Scheme.Γ.map (𝒰.map i ≫ f).op),\n ∀ (𝒰 : Scheme.open_cover.{u} X) [∀ i, is_affine (𝒰.obj i)] (i : 𝒰.J),\n P (Scheme.Γ.map (𝒰.map i ≫ f).op),\n ∀ {U : Scheme} (g : U ⟶ X) [is_affine U] [is_open_immersion g],\n P (Scheme.Γ.map (g ≫ f).op)] :=\nbegin\n tfae_have : 1 → 4,\n { intros H U g _ hg,\n resetI,\n specialize H ⟨⟨_, hg.base_open.open_range⟩,\n range_is_affine_open_of_open_immersion g⟩,\n rw [← hP.respects_iso.cancel_right_is_iso _ (Scheme.Γ.map (is_open_immersion.iso_of_range_eq\n g (X.of_restrict (opens.open_embedding ⟨_, hg.base_open.open_range⟩))\n subtype.range_coe.symm).hom.op), ← Scheme.Γ.map_comp, ← op_comp,\n is_open_immersion.iso_of_range_eq_hom] at H,\n erw is_open_immersion.lift_fac_assoc at H,\n exact H },\n tfae_have : 4 → 3,\n { intros H 𝒰 _ i, resetI, apply H },\n tfae_have : 3 → 2,\n { intro H, refine ⟨X.affine_cover, infer_instance, H _⟩ },\n tfae_have : 2 → 1,\n { rintro ⟨𝒰, _, h𝒰⟩,\n exactI hP.source_affine_locally_of_source_open_cover f 𝒰 h𝒰 },\n tfae_finish\nend\n\nlemma open_cover_tfae {X Y : Scheme.{u}} [is_affine Y] (f : X ⟶ Y) :\n tfae [source_affine_locally @P f,\n ∃ (𝒰 : Scheme.open_cover.{u} X), ∀ (i : 𝒰.J), source_affine_locally @P (𝒰.map i ≫ f),\n ∀ (𝒰 : Scheme.open_cover.{u} X) (i : 𝒰.J), source_affine_locally @P (𝒰.map i ≫ f),\n ∀ {U : Scheme} (g : U ⟶ X) [is_open_immersion g], source_affine_locally @P (g ≫ f)] :=\nbegin\n tfae_have : 1 → 4,\n { intros H U g hg V,\n resetI,\n rw (hP.affine_open_cover_tfae f).out 0 3 at H,\n haveI : is_affine _ := V.2,\n rw ← category.assoc,\n apply H },\n tfae_have : 4 → 3,\n { intros H 𝒰 _ i, resetI, apply H },\n tfae_have : 3 → 2,\n { intro H, refine ⟨X.affine_cover, H _⟩ },\n tfae_have : 2 → 1,\n { rintro ⟨𝒰, h𝒰⟩,\n rw (hP.affine_open_cover_tfae f).out 0 1,\n refine ⟨𝒰.bind (λ _, Scheme.affine_cover _), _, _⟩,\n { intro i, dsimp, apply_instance },\n { intro i,\n specialize h𝒰 i.1,\n rw (hP.affine_open_cover_tfae (𝒰.map i.fst ≫ f)).out 0 3 at h𝒰,\n erw category.assoc,\n apply @@h𝒰 _ (show _, from _),\n dsimp, apply_instance } },\n tfae_finish\nend\n\nlemma source_affine_locally_comp_of_is_open_immersion\n {X Y Z : Scheme.{u}} [is_affine Z] (f : X ⟶ Y) (g : Y ⟶ Z) [is_open_immersion f]\n (H : source_affine_locally @P g) : source_affine_locally @P (f ≫ g) :=\nby apply ((hP.open_cover_tfae g).out 0 3).mp H\n\nlemma source_affine_open_cover_iff {X Y : Scheme.{u}} (f : X ⟶ Y)\n [is_affine Y] (𝒰 : Scheme.open_cover.{u} X) [∀ i, is_affine (𝒰.obj i)] :\n source_affine_locally @P f ↔ (∀ i, P (Scheme.Γ.map (𝒰.map i ≫ f).op)) :=\n⟨λ H, let h := ((hP.affine_open_cover_tfae f).out 0 2).mp H in h 𝒰,\n λ H, let h := ((hP.affine_open_cover_tfae f).out 1 0).mp in h ⟨𝒰, infer_instance, H⟩⟩\n\nlemma is_local_source_affine_locally :\n (source_affine_locally @P).is_local :=\nsource_affine_locally_is_local hP.respects_iso hP.localization_preserves\n (@ring_hom.property_is_local.of_localization_span _ hP)\n\nlemma is_local_affine_locally :\n property_is_local_at_target (affine_locally @P) :=\nhP.is_local_source_affine_locally.target_affine_locally_is_local\n\nlemma affine_open_cover_iff {X Y : Scheme.{u}} (f : X ⟶ Y)\n (𝒰 : Scheme.open_cover.{u} Y) [∀ i, is_affine (𝒰.obj i)]\n (𝒰' : ∀ i, Scheme.open_cover.{u} ((𝒰.pullback_cover f).obj i)) [∀ i j, is_affine ((𝒰' i).obj j)] :\n affine_locally @P f ↔\n (∀ i j, P (Scheme.Γ.map ((𝒰' i).map j ≫ pullback.snd).op)) :=\n(hP.is_local_source_affine_locally.affine_open_cover_iff f 𝒰).trans\n (forall_congr (λ i, hP.source_affine_open_cover_iff _ (𝒰' i)))\n\nlemma source_open_cover_iff {X Y : Scheme.{u}} (f : X ⟶ Y)\n (𝒰 : Scheme.open_cover.{u} X) :\n affine_locally @P f ↔ ∀ i, affine_locally @P (𝒰.map i ≫ f) :=\nbegin\n split,\n { intros H i U,\n rw morphism_restrict_comp,\n delta morphism_restrict,\n apply hP.source_affine_locally_comp_of_is_open_immersion,\n apply H },\n { intros H U,\n haveI : is_affine _ := U.2,\n apply ((hP.open_cover_tfae (f ∣_ U.1)).out 1 0).mp,\n use 𝒰.pullback_cover (X.of_restrict _),\n intro i,\n specialize H i U,\n rw morphism_restrict_comp at H,\n delta morphism_restrict at H,\n have := source_affine_locally_respects_iso hP.respects_iso,\n rw [category.assoc, affine_cancel_left_is_iso this, ← affine_cancel_left_is_iso\n this (pullback_symmetry _ _).hom, pullback_symmetry_hom_comp_snd_assoc] at H,\n exact H }\nend\n\nlemma affine_locally_of_is_open_immersion (hP : ring_hom.property_is_local @P) {X Y : Scheme}\n (f : X ⟶ Y) [hf : is_open_immersion f] : affine_locally @P f :=\nbegin\n intro U,\n haveI H : is_affine _ := U.2,\n rw ← category.comp_id (f ∣_ U),\n apply hP.source_affine_locally_comp_of_is_open_immersion,\n rw hP.source_affine_open_cover_iff _ (Scheme.open_cover_of_is_iso (𝟙 _)),\n { intro i, erw [category.id_comp, op_id, Scheme.Γ.map_id],\n convert hP.holds_for_localization_away _ (1 : Scheme.Γ.obj _),\n { exact (ring_hom.algebra_map_to_algebra _).symm },\n { apply_instance },\n { refine is_localization.away_of_is_unit_of_bijective _ is_unit_one function.bijective_id } },\n { intro i, exact H }\nend\n\nlemma affine_locally_of_comp\n (H : ∀ {R S T : Type.{u}} [comm_ring R] [comm_ring S] [comm_ring T], by exactI\n ∀ (f : R →+* S) (g : S →+* T), P (g.comp f) → P g)\n {X Y Z : Scheme} {f : X ⟶ Y} {g : Y ⟶ Z} (h : affine_locally @P (f ≫ g)) :\n affine_locally @P f :=\nbegin\n let 𝒰 : ∀ i, ((Z.affine_cover.pullback_cover (f ≫ g)).obj i).open_cover,\n { intro i,\n refine Scheme.open_cover.bind _ (λ i, Scheme.affine_cover _),\n apply Scheme.open_cover.pushforward_iso _\n (pullback_right_pullback_fst_iso g (Z.affine_cover.map i) f).hom,\n apply Scheme.pullback.open_cover_of_right,\n exact (pullback g (Z.affine_cover.map i)).affine_cover },\n haveI h𝒰 : ∀ i j, is_affine ((𝒰 i).obj j), by { dsimp, apply_instance },\n let 𝒰' := (Z.affine_cover.pullback_cover g).bind (λ i, Scheme.affine_cover _),\n haveI h𝒰' : ∀ i, is_affine (𝒰'.obj i), by { dsimp, apply_instance },\n rw hP.affine_open_cover_iff f 𝒰' (λ i, Scheme.affine_cover _),\n rw hP.affine_open_cover_iff (f ≫ g) Z.affine_cover 𝒰 at h,\n rintros ⟨i, j⟩ k,\n dsimp at i j k,\n specialize h i ⟨j, k⟩,\n dsimp only [Scheme.open_cover.bind_map, Scheme.open_cover.pushforward_iso_obj,\n Scheme.pullback.open_cover_of_right_obj, Scheme.open_cover.pushforward_iso_map,\n Scheme.pullback.open_cover_of_right_map, Scheme.open_cover.bind_obj,\n Scheme.open_cover.pullback_cover_obj, Scheme.open_cover.pullback_cover_map] at h ⊢,\n rw [category.assoc, category.assoc, pullback_right_pullback_fst_iso_hom_snd,\n pullback.lift_snd_assoc, category.assoc, ← category.assoc, op_comp, functor.map_comp] at h,\n exact H _ _ h,\nend\n\nlemma affine_locally_stable_under_composition :\n (affine_locally @P).stable_under_composition :=\nbegin\n intros X Y S f g hf hg,\n let 𝒰 : ∀ i, ((S.affine_cover.pullback_cover (f ≫ g)).obj i).open_cover,\n { intro i,\n refine Scheme.open_cover.bind _ (λ i, Scheme.affine_cover _),\n apply Scheme.open_cover.pushforward_iso _\n (pullback_right_pullback_fst_iso g (S.affine_cover.map i) f).hom,\n apply Scheme.pullback.open_cover_of_right,\n exact (pullback g (S.affine_cover.map i)).affine_cover },\n rw hP.affine_open_cover_iff (f ≫ g) S.affine_cover _,\n rotate,\n { exact 𝒰 },\n { intros i j, dsimp at *, apply_instance },\n { rintros i ⟨j, k⟩,\n dsimp at i j k,\n dsimp only [Scheme.open_cover.bind_map, Scheme.open_cover.pushforward_iso_obj,\n Scheme.pullback.open_cover_of_right_obj, Scheme.open_cover.pushforward_iso_map,\n Scheme.pullback.open_cover_of_right_map, Scheme.open_cover.bind_obj],\n rw [category.assoc, category.assoc, pullback_right_pullback_fst_iso_hom_snd,\n pullback.lift_snd_assoc, category.assoc, ← category.assoc, op_comp, functor.map_comp],\n apply hP.stable_under_composition,\n { exact (hP.affine_open_cover_iff _ _ _).mp hg _ _ },\n { delta affine_locally at hf,\n rw (hP.is_local_source_affine_locally.affine_open_cover_tfae f).out 0 3 at hf,\n specialize hf ((pullback g (S.affine_cover.map i)).affine_cover.map j ≫ pullback.fst),\n rw (hP.affine_open_cover_tfae (pullback.snd : pullback f ((pullback g (S.affine_cover.map i))\n .affine_cover.map j ≫ pullback.fst) ⟶ _)).out 0 3 at hf,\n apply hf } }\nend\n\nlemma source_affine_locally_stable_under_base_change (h : ring_hom.stable_under_base_change @P) :\n (source_affine_locally @P).stable_under_base_change :=\nbegin\n intros X Y S hS hX f g H,\n resetI,\n rw (hP.affine_open_cover_tfae (pullback.fst : pullback f g ⟶ _)).out 0 1,\n rw (hP.affine_open_cover_tfae g).out 0 2 at H,\n use Scheme.pullback.open_cover_of_right Y.affine_cover f g,\n split,\n { intro i, dsimp, apply_instance },\n intro i,\n erw pullback.lift_fst,\n rw category.comp_id,\n exact h.Γ_pullback_fst hP.respects_iso _ _ (H Y.affine_cover i),\nend\n\nlemma affine_locally_stable_under_base_change (h : ring_hom.stable_under_base_change @P) :\n (affine_locally @P).stable_under_base_change :=\nhP.is_local_source_affine_locally.stable_under_base_change\n (source_affine_locally_stable_under_base_change hP h)\n\nlemma affine_locally_local_at_source :\n property_is_local_at_source (affine_locally @P) :=\nbegin\n constructor,\n { exact target_affine_locally_respects_iso (source_affine_locally_respects_iso hP.respects_iso) },\n { intros, apply affine_locally_stable_under_composition hP,\n { apply affine_locally_of_is_open_immersion hP },\n { assumption } },\n { intros, rwa source_open_cover_iff hP f 𝒰 }\nend\n\nend ring_hom.property_is_local\n\nnamespace algebraic_geometry\n\n\ninclude P\n\ndef affine_and : affine_target_morphism_property :=\nλ X Y f hY, is_affine X ∧ P (Scheme.Γ.map f.op)\n\nvariable {P}\n\nlemma affine_and_target_affine_locally_iff (hP : ring_hom.respects_iso @P)\n {X Y : Scheme} (f : X ⟶ Y) :\n target_affine_locally (affine_and @P) f ↔\n affine f ∧ (∀ U : opens Y.carrier, is_affine_open U → P (f.1.c.app (op U))) :=\nbegin\n delta target_affine_locally Scheme.affine_opens,\n simp_rw [affine_iff, ← forall_and_distrib, set_coe.forall],\n apply forall₂_congr,\n intros U hU,\n apply and_congr iff.rfl,\n rw [Γ_map_morphism_restrict, hP.cancel_left_is_iso, hP.cancel_right_is_iso],\n refl\nend\n\nomit P\n\nvariable (P)\n\nlemma target_affine_locally_affine_and_le_affine :\n target_affine_locally (affine_and @P) ≤ @affine :=\nbegin\n rw affine_eq_affine_property,\n apply target_affine_locally_mono,\n exact λ X Y f hY H, H.1\nend\n\nvariable {P}\n\nlemma _root_.ring_hom.property_is_local.affine_and_eq (hP : ring_hom.property_is_local @P) :\n target_affine_locally (affine_and @P) = @affine ⊓ affine_locally @P :=\nbegin\n rw [affine_eq_affine_property, ← target_affine_locally_and],\n congr' 1,\n ext X Y f hY,\n resetI,\n split,\n { intro H, refine ⟨H.1, _⟩,\n rw (hP.affine_open_cover_tfae f).out 0 1,\n refine ⟨Scheme.open_cover_of_is_iso (𝟙 _), λ i, H.1, λ _, _⟩,\n rw [Scheme.open_cover_of_is_iso_map, category.id_comp f],\n exact H.2 },\n { rintros ⟨h₁ : is_affine X, h₂⟩,\n rw (hP.affine_open_cover_tfae f).out 0 2 at h₂,\n have := @h₂ (Scheme.open_cover_of_is_iso (𝟙 _)) (λ _, h₁) punit.star,\n rw [Scheme.open_cover_of_is_iso_map, category.id_comp f] at this,\n refine ⟨h₁, this⟩ }\nend\n\nvariable (P)\n\nlemma is_local_affine_and\n (hP : ring_hom.respects_iso @P)\n (h₃ : ring_hom.localization_preserves @P)\n (h₄ : ring_hom.of_localization_span @P) : (affine_and @P).is_local :=\nbegin\n constructor,\n { apply affine_target_morphism_property.respects_iso_mk,\n { rintros X Y Z e f _ ⟨H₁, H₂⟩,\n resetI,\n refine ⟨is_affine_of_iso e.hom, _⟩,\n rw [op_comp, functor.map_comp],\n exact hP.1 (Scheme.Γ.map f.op) (Scheme.Γ.map_iso e.op).CommRing_iso_to_ring_equiv H₂ },\n { rintros X Y Z e f _ ⟨H₁, H₂⟩,\n resetI,\n refine ⟨H₁, _⟩,\n rw [op_comp, functor.map_comp],\n exact hP.2 (Scheme.Γ.map f.op) (Scheme.Γ.map_iso e.op).CommRing_iso_to_ring_equiv H₂ } },\n { rintros X Y hY f r ⟨H₁, H₂⟩,\n resetI,\n refine ⟨affine_affine_property_is_local.2 f r H₁, _⟩,\n rw hP.basic_open_iff,\n apply ring_hom.localization_preserves.away @h₃,\n all_goals { assumption } },\n { rintros X Y hY f s hs H,\n obtain ⟨H₁, H₂⟩ := forall_and_distrib.mp H,\n resetI,\n haveI := affine_affine_property_is_local.3 f s hs H₁,\n refine ⟨_, _⟩,\n swap,\n apply h₄ (Scheme.Γ.map f.op) ↑s hs,\n intro r,\n specialize H₂ r,\n rw hP.basic_open_iff_localization at H₂,\n all_goals { assumption } },\nend\n\nlemma affine_and_stable_under_composition (hP' : ring_hom.stable_under_composition @P) :\n (target_affine_locally (affine_and @P)).stable_under_composition :=\nbegin\n introv X h₁ h₂ U,\n obtain ⟨h₃, h₄⟩ := h₂ U,\n obtain ⟨h₅, h₆⟩ := h₁ ⟨_, h₃⟩,\n split,\n { exact h₅ },\n { rw [morphism_restrict_comp, op_comp, functor.map_comp],\n apply hP'; assumption }\nend\n\nlemma affine_and_stable_under_base_change\n (hP : ring_hom.respects_iso @P)\n (h₁ : ring_hom.localization_preserves @P)\n (h₂ : ring_hom.of_localization_span @P)\n (h₃ : _root_.ring_hom.stable_under_base_change @P) :\n (target_affine_locally (affine_and @P)).stable_under_base_change :=\nbegin\n apply (is_local_affine_and @P hP @h₁ @h₂).stable_under_base_change,\n rintros X Y S hS hX f g ⟨hY, H⟩,\n exactI ⟨infer_instance, h₃.Γ_pullback_fst hP _ _ H⟩\nend\n\nlemma affine_and_mono\n (P₁ P₂ : ∀ ⦃R S : Type u⦄ [comm_ring R] [comm_ring S] (f : by exactI R →+* S), Prop)\n (H : ∀ {R S : Type u} [comm_ring R] [comm_ring S], by exactI ∀ (f : R →+* S), P₁ f → P₂ f) :\n target_affine_locally (affine_and P₁) ≤ target_affine_locally (affine_and P₂) :=\nbegin\n apply target_affine_locally_mono,\n rintros X Y hY f ⟨hX, hf⟩,\n exact ⟨hX, H _ hf⟩,\nend\n\nlemma affine_and_Spec_iff {P}\n (h₁ : ring_hom.respects_iso @P) {R S : CommRing} (f : R ⟶ S) :\n affine_and @P (Scheme.Spec.map f.op) ↔ P f :=\nbegin\n dsimp only [affine_and],\n rw and_iff_right (show is_affine (Scheme.Spec.obj (op S)), by apply_instance),\n have := arrow.iso_w (Γ_Spec_arrow_iso f),\n dsimp only [arrow.mk_hom] at this,\n rw [this, h₁.cancel_left_is_iso, h₁.cancel_right_is_iso],\nend\n\nend algebraic_geometry", "meta": {"author": "erdOne", "repo": "lean-AG-morphisms", "sha": "bfb65e7d5c17f333abd7b1806717f12cd29427fd", "save_path": "github-repos/lean/erdOne-lean-AG-morphisms", "path": "github-repos/lean/erdOne-lean-AG-morphisms/lean-AG-morphisms-bfb65e7d5c17f333abd7b1806717f12cd29427fd/src/morphisms/ring_hom_properties.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.06853749493457365, "lm_q1q2_score": 0.03373334185882127}} {"text": "open classical\n\ntheorem dne {p : Prop} (h : ¬¬p) : p :=\n or.elim (em p)\n (assume hp : p, hp)\n (assume hnp : ¬p, absurd hnp h)\n", "meta": {"author": "Ailrun", "repo": "Theorem_Proving_in_Lean", "sha": "2eb1b5caf93c6a5a555c79e9097cf2ba5a66cf68", "save_path": "github-repos/lean/Ailrun-Theorem_Proving_in_Lean", "path": "github-repos/lean/Ailrun-Theorem_Proving_in_Lean/Theorem_Proving_in_Lean-2eb1b5caf93c6a5a555c79e9097cf2ba5a66cf68/src/ch3/ex0502.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4843800842769843, "lm_q2_score": 0.06954174788049287, "lm_q1q2_score": 0.03368463769912193}} {"text": "/-\nCopyright (c) 2018 Simon Hudon. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Simon Hudon\n\nTraversable instance for lazy_lists.\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.default\nimport Mathlib.control.traversable.equiv\nimport Mathlib.control.traversable.instances\nimport Mathlib.Lean3Lib.data.lazy_list\nimport Mathlib.PostPort\n\nuniverses u_1 u u_2 u_3 \n\nnamespace Mathlib\n\n/-!\n## Definitions on lazy lists\n\nThis file contains various definitions and proofs on lazy lists.\n\nTODO: move the `lazy_list.lean` file from core to mathlib.\n-/\n\nnamespace thunk\n\n\n/-- Creates a thunk with a (non-lazy) constant value. -/\ndef mk {α : Type u_1} (x : α) : thunk α := fun (_x : Unit) => x\n\nprotected instance decidable_eq {α : Type u} [DecidableEq α] : DecidableEq (thunk α) := sorry\n\nend thunk\n\n\nnamespace lazy_list\n\n\n/-- Isomorphism between strict and lazy lists. -/\ndef list_equiv_lazy_list (α : Type u_1) : List α ≃ lazy_list α :=\n equiv.mk of_list to_list sorry sorry\n\nprotected instance inhabited {α : Type u} : Inhabited (lazy_list α) := { default := nil }\n\nprotected instance decidable_eq {α : Type u} [DecidableEq α] : DecidableEq (lazy_list α) := sorry\n\n/-- Traversal of lazy lists using an applicative effect. -/\nprotected def traverse {m : Type u → Type u} [Applicative m] {α : Type u} {β : Type u}\n (f : α → m β) : lazy_list α → m (lazy_list β) :=\n sorry\n\nprotected instance traversable : traversable lazy_list := traversable.mk lazy_list.traverse\n\nprotected instance is_lawful_traversable : is_lawful_traversable lazy_list :=\n equiv.is_lawful_traversable' list_equiv_lazy_list sorry sorry sorry\n\n/-- `init xs`, if `xs` non-empty, drops the last element of the list.\nOtherwise, return the empty list. -/\ndef init {α : Type u_1} : lazy_list α → lazy_list α := sorry\n\n/-- Return the first object contained in the list that satisfies\npredicate `p` -/\ndef find {α : Type u_1} (p : α → Prop) [decidable_pred p] : lazy_list α → Option α := sorry\n\n/-- `interleave xs ys` creates a list where elements of `xs` and `ys` alternate. -/\ndef interleave {α : Type u_1} : lazy_list α → lazy_list α → lazy_list α := sorry\n\n/-- `interleave_all (xs::ys::zs::xss)` creates a list where elements of `xs`, `ys`\nand `zs` and the rest alternate. Every other element of the resulting list is taken from\n`xs`, every fourth is taken from `ys`, every eighth is taken from `zs` and so on. -/\ndef interleave_all {α : Type u_1} : List (lazy_list α) → lazy_list α := sorry\n\n/-- Monadic bind operation for `lazy_list`. -/\nprotected def bind {α : Type u_1} {β : Type u_2} : lazy_list α → (α → lazy_list β) → lazy_list β :=\n sorry\n\n/-- Reverse the order of a `lazy_list`.\nIt is done by converting to a `list` first because reversal involves evaluating all\nthe list and if the list is all evaluated, `list` is a better representation for\nit than a series of thunks. -/\ndef reverse {α : Type u_1} (xs : lazy_list α) : lazy_list α := of_list (list.reverse (to_list xs))\n\nprotected instance monad : Monad lazy_list := sorry\n\ntheorem append_nil {α : Type u_1} (xs : lazy_list α) : (append xs fun (_ : Unit) => nil) = xs :=\n sorry\n\ntheorem append_assoc {α : Type u_1} (xs : lazy_list α) (ys : lazy_list α) (zs : lazy_list α) :\n (append (append xs fun (_ : Unit) => ys) fun (_ : Unit) => zs) =\n append xs fun (_ : Unit) => append ys fun (_ : Unit) => zs :=\n sorry\n\ntheorem append_bind {α : Type u_1} {β : Type u_2} (xs : lazy_list α) (ys : thunk (lazy_list α))\n (f : α → lazy_list β) :\n lazy_list.bind (append xs ys) f =\n append (lazy_list.bind xs f) fun (_ : Unit) => lazy_list.bind (ys Unit.unit) f :=\n sorry\n\nprotected instance is_lawful_monad : is_lawful_monad lazy_list := sorry\n\n/-- Try applying function `f` to every element of a `lazy_list` and\nreturn the result of the first attempt that succeeds. -/\ndef mfirst {m : Type u_1 → Type u_2} [alternative m] {α : Type u_3} {β : Type u_1} (f : α → m β) :\n lazy_list α → m β :=\n sorry\n\n/-- Membership in lazy lists -/\nprotected def mem {α : Type u_1} (x : α) : lazy_list α → Prop := sorry\n\nprotected instance has_mem {α : outParam (Type u_1)} : has_mem α (lazy_list α) :=\n has_mem.mk lazy_list.mem\n\nprotected instance mem.decidable {α : Type u_1} [DecidableEq α] (x : α) (xs : lazy_list α) :\n Decidable (x ∈ xs) :=\n sorry\n\n@[simp] theorem mem_nil {α : Type u_1} (x : α) : x ∈ nil ↔ False := iff.rfl\n\n@[simp] theorem mem_cons {α : Type u_1} (x : α) (y : α) (ys : thunk (lazy_list α)) :\n x ∈ cons y ys ↔ x = y ∨ x ∈ ys Unit.unit :=\n iff.rfl\n\ntheorem forall_mem_cons {α : Type u_1} {p : α → Prop} {a : α} {l : thunk (lazy_list α)} :\n (∀ (x : α), x ∈ cons a l → p x) ↔ p a ∧ ∀ (x : α), x ∈ l Unit.unit → p x :=\n sorry\n\n/-! ### map for partial functions -/\n\n/-- Partial map. If `f : Π a, p a → β` is a partial function defined on\n `a : α` satisfying `p`, then `pmap f l h` is essentially the same as `map f l`\n but is defined only when all members of `l` satisfy `p`, using the proof\n to apply `f`. -/\n@[simp] def pmap {α : Type u_1} {β : Type u_2} {p : α → Prop} (f : (a : α) → p a → β)\n (l : lazy_list α) : (∀ (a : α), a ∈ l → p a) → lazy_list β :=\n sorry\n\n/-- \"Attach\" the proof that the elements of `l` are in `l` to produce a new `lazy_list`\n with the same elements but in the type `{x // x ∈ l}`. -/\ndef attach {α : Type u_1} (l : lazy_list α) : lazy_list (Subtype fun (x : α) => x ∈ l) :=\n pmap Subtype.mk l sorry\n\nprotected instance has_repr {α : Type u_1} [has_repr α] : has_repr (lazy_list α) :=\n has_repr.mk fun (xs : lazy_list α) => repr (to_list xs)\n\nend Mathlib", "meta": {"author": "AurelienSaue", "repo": "Mathlib4_auto", "sha": "590df64109b08190abe22358fabc3eae000943f2", "save_path": "github-repos/lean/AurelienSaue-Mathlib4_auto", "path": "github-repos/lean/AurelienSaue-Mathlib4_auto/Mathlib4_auto-590df64109b08190abe22358fabc3eae000943f2/Mathlib/data/lazy_list/basic_auto.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4687906266262437, "lm_q2_score": 0.07159119746371433, "lm_q1q2_score": 0.03356128231993779}} {"text": "/-\nCopyright (c) 2017 Mario Carneiro. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Mario Carneiro\n-/\nimport data.dlist\nimport tactic.core\nimport tactic.clear\n\n/-!\n\n# Recursive cases (`rcases`) tactic and related tactics\n\n`rcases` is a tactic that will perform `cases` recursively, according to a pattern. It is used to\ndestructure hypotheses or expressions composed of inductive types like `h1 : a ∧ b ∧ c ∨ d` or\n`h2 : ∃ x y, trans_rel R x y`. Usual usage might be `rcases h1 with ⟨ha, hb, hc⟩ | hd` or\n`rcases h2 with ⟨x, y, _ | ⟨z, hxz, hzy⟩⟩` for these examples.\n\nEach element of an `rcases` pattern is matched against a particular local hypothesis (most of which\nare generated during the execution of `rcases` and represent individual elements destructured from\nthe input expression). An `rcases` pattern has the following grammar:\n\n* A name like `x`, which names the active hypothesis as `x`.\n* A blank `_`, which does nothing (letting the automatic naming system used by `cases` name the\n hypothesis).\n* A hyphen `-`, which clears the active hypothesis and any dependents.\n* The keyword `rfl`, which expects the hypothesis to be `h : a = b`, and calls `subst` on the\n hypothesis (which has the effect of replacing `b` with `a` everywhere or vice versa).\n* A type ascription `p : ty`, which sets the type of the hypothesis to `ty` and then matches it\n against `p`. (Of course, `ty` must unify with the actual type of `h` for this to work.)\n* A tuple pattern `⟨p1, p2, p3⟩`, which matches a constructor with many arguments, or a series\n of nested conjunctions or existentials. For example if the active hypothesis is `a ∧ b ∧ c`,\n then the conjunction will be destructured, and `p1` will be matched against `a`, `p2` against `b`\n and so on.\n* An alteration pattern `p1 | p2 | p3`, which matches an inductive type with multiple constructors,\n or a nested disjunction like `a ∨ b ∨ c`.\n\nThe patterns are fairly liberal about the exact shape of the constructors, and will insert\nadditional alternation branches and tuple arguments if there are not enough arguments provided, and\nreuse the tail for further matches if there are too many arguments provided to alternation and\ntuple patterns.\n\nThis file also contains the `obtain` and `rintro` tactics, which use the same syntax of `rcases`\npatterns but with a slightly different use case:\n\n* `rintro` (or `rintros`) is used like `rintro x ⟨y, z⟩` and is the same as `intros` followed by\n `rcases` on the newly introduced arguments.\n* `obtain` is the same as `rcases` but with a syntax styled after `have` rather than `cases`.\n `obtain ⟨hx, hy⟩ | hz := foo` is equivalent to `rcases foo with ⟨hx, hy⟩ | hz`. Unlike `rcases`,\n `obtain` also allows one to omit `:= foo`, although a type must be provided in this case,\n as in `obtain ⟨hx, hy⟩ | hz : a ∧ b ∨ c`, in which case it produces a subgoal for proving\n `a ∧ b ∨ c` in addition to the subgoals `hx : a, hy : b |- goal` and `hz : c |- goal`.\n\n## Tags\n\nrcases, rintro, obtain, destructuring, cases, pattern matching, match\n-/\n\nopen lean lean.parser\n\nnamespace tactic\n\n/-!\nThese synonyms for `list` are used to clarify the meanings of the many\nusages of lists in this module.\n\n- `listΣ` is used where a list represents a disjunction, such as the\n list of possible constructors of an inductive type.\n\n- `listΠ` is used where a list represents a conjunction, such as the\n list of arguments of an individual constructor.\n\nThese are merely type synonyms, and so are not checked for consistency\nby the compiler.\n\nThe `def`/`local notation` combination makes Lean retain these\nannotations in reported types.\n-/\n\n/-- A list, with a disjunctive meaning (like a list of inductive constructors, or subgoals) -/\n@[reducible] def list_Sigma := list\n\n/-- A list, with a conjunctive meaning (like a list of constructor arguments, or hypotheses) -/\n@[reducible] def list_Pi := list\n\nlocal notation `listΣ` := list_Sigma\nlocal notation `listΠ` := list_Pi\n\n/-- A metavariable representing a subgoal, together with a list of local constants to clear. -/\n@[reducible] meta def uncleared_goal := list expr × expr\n\n/--\nAn `rcases` pattern can be one of the following, in a nested combination:\n\n* A name like `foo`\n* The special keyword `rfl` (for pattern matching on equality using `subst`)\n* A hyphen `-`, which clears the active hypothesis and any dependents.\n* A type ascription like `pat : ty` (parentheses are optional)\n* A tuple constructor like `⟨p1, p2, p3⟩`\n* An alternation / variant pattern `p1 | p2 | p3`\n\nParentheses can be used for grouping; alternation is higher precedence than type ascription, so\n`p1 | p2 | p3 : ty` means `(p1 | p2 | p3) : ty`.\n\nN-ary alternations are treated as a group, so `p1 | p2 | p3` is not the same as `p1 | (p2 | p3)`,\nand similarly for tuples. However, note that an n-ary alternation or tuple can match an n-ary\nconjunction or disjunction, because if the number of patterns exceeds the number of constructors in\nthe type being destructed, the extra patterns will match on the last element, meaning that\n`p1 | p2 | p3` will act like `p1 | (p2 | p3)` when matching `a1 ∨ a2 ∨ a3`. If matching against a\ntype with 3 constructors, `p1 | (p2 | p3)` will act like `p1 | (p2 | p3) | _` instead.\n-/\nmeta inductive rcases_patt : Type\n| one : name → rcases_patt\n| clear : rcases_patt\n| typed : rcases_patt → pexpr → rcases_patt\n| tuple : listΠ rcases_patt → rcases_patt\n| alts : listΣ rcases_patt → rcases_patt\n\nnamespace rcases_patt\nmeta instance inhabited : inhabited rcases_patt :=\n⟨one `_⟩\n\n/-- Get the name from a pattern, if provided -/\nmeta def name : rcases_patt → option name\n| (one `_) := none\n| (one `rfl) := none\n| (one n) := some n\n| (typed p _) := p.name\n| (alts [p]) := p.name\n| _ := none\n\n/-- Interpret an rcases pattern as a tuple, where `p` becomes `⟨p⟩`\nif `p` is not already a tuple. -/\nmeta def as_tuple : rcases_patt → listΠ rcases_patt\n| (tuple ps) := ps\n| p := [p]\n\n/-- Interpret an rcases pattern as an alternation, where non-alternations are treated as one\nalternative. -/\nmeta def as_alts : rcases_patt → listΣ rcases_patt\n| (alts ps) := ps\n| p := [p]\n\n/-- Convert a list of patterns to a tuple pattern, but mapping `[p]` to `p` instead of `⟨p⟩`. -/\nmeta def tuple' : listΠ rcases_patt → rcases_patt\n| [p] := p\n| ps := tuple ps\n\n/-- Convert a list of patterns to an alternation pattern, but mapping `[p]` to `p` instead of\na unary alternation `|p`. -/\nmeta def alts' : listΣ rcases_patt → rcases_patt\n| [p] := p\n| ps := alts ps\n\n/-- This function is used for producing rcases patterns based on a case tree. Suppose that we have\na list of patterns `ps` that will match correctly against the branches of the case tree for one\nconstructor. This function will merge tuples at the end of the list, so that `[a, b, ⟨c, d⟩]`\nbecomes `⟨a, b, c, d⟩` instead of `⟨a, b, ⟨c, d⟩⟩`.\n\nWe must be careful to turn `[a, ⟨⟩]` into `⟨a, ⟨⟩⟩` instead of `⟨a⟩` (which will not perform the\nnested match). -/\nmeta def tuple₁_core : listΠ rcases_patt → listΠ rcases_patt\n| [] := []\n| [tuple []] := [tuple []]\n| [tuple ps] := ps\n| (p :: ps) := p :: tuple₁_core ps\n\n/-- This function is used for producing rcases patterns based on a case tree. This is like\n`tuple₁_core` but it produces a pattern instead of a tuple pattern list, converting `[n]` to `n`\ninstead of `⟨n⟩` and `[]` to `_`, and otherwise just converting `[a, b, c]` to `⟨a, b, c⟩`. -/\nmeta def tuple₁ : listΠ rcases_patt → rcases_patt\n| [] := default _\n| [one n] := one n\n| ps := tuple (tuple₁_core ps)\n\n/-- This function is used for producing rcases patterns based on a case tree. Here we are given\nthe list of patterns to apply to each argument of each constructor after the main case, and must\nproduce a list of alternatives with the same effect. This function calls `tuple₁` to make the\nindividual alternatives, and handles merging `[a, b, c | d]` to `a | b | c | d` instead of\n`a | b | (c | d)`. -/\nmeta def alts₁_core : listΣ (listΠ rcases_patt) → listΣ rcases_patt\n| [] := []\n| [[alts ps]] := ps\n| (p :: ps) := tuple₁ p :: alts₁_core ps\n\n/-- This function is used for producing rcases patterns based on a case tree. This is like\n`alts₁_core`, but it produces a cases pattern directly instead of a list of alternatives. We\nspecially translate the empty alternation to `⟨⟩`, and translate `|(a | b)` to `⟨a | b⟩` (because we\ndon't have any syntax for unary alternation). Otherwise we can use the regular merging of\nalternations at the last argument so that `a | b | (c | d)` becomes `a | b | c | d`. -/\nmeta def alts₁ : listΣ (listΠ rcases_patt) → rcases_patt\n| [[]] := tuple []\n| [[alts ps]] := tuple [alts ps]\n| ps := alts' (alts₁_core ps)\n\nmeta instance has_reflect : has_reflect rcases_patt\n| (one n) := `(_)\n| clear := `(_)\n| (typed l e) :=\n (`(typed).subst (has_reflect l)).subst (reflect e)\n| (tuple l) := `(λ l, tuple l).subst $\n by haveI := has_reflect; exact list.reflect l\n| (alts l) := `(λ l, alts l).subst $\n by haveI := has_reflect; exact list.reflect l\n\n/-- Formats an `rcases` pattern. If the `bracket` argument is true, then it will be\nprinted at high precedence, i.e. it will have parentheses around it if it is not already a tuple\nor atomic name. -/\nprotected meta def format : ∀ bracket : bool, rcases_patt → tactic _root_.format\n| _ (one n) := pure $ to_fmt n\n| _ clear := pure \"-\"\n| _ (tuple []) := pure \"⟨⟩\"\n| _ (tuple ls) := do\n fs ← ls.mmap $ format ff,\n pure $ \"⟨\" ++ _root_.format.group (_root_.format.nest 1 $\n _root_.format.join $ list.intersperse (\",\" ++ _root_.format.line) fs) ++ \"⟩\"\n| br (alts ls) := do\n fs ← ls.mmap $ format tt,\n let fmt := _root_.format.join $ list.intersperse (↑\" |\" ++ _root_.format.space) fs,\n pure $ if br then _root_.format.bracket \"(\" \")\" fmt else fmt\n| br (typed p e) := do\n fp ← format ff p,\n fe ← pp e,\n let fmt := fp ++ \" : \" ++ fe,\n pure $ if br then _root_.format.bracket \"(\" \")\" fmt else fmt\n\nmeta instance has_to_tactic_format : has_to_tactic_format rcases_patt := ⟨rcases_patt.format ff⟩\n\nend rcases_patt\n\n/-- Takes the number of fields of a single constructor and patterns to match its fields against\n(not necessarily the same number). The returned lists each contain one element per field of the\nconstructor. The `name` is the name which will be used in the top-level `cases` tactic, and the\n`rcases_patt` is the pattern which the field will be matched against by subsequent `cases`\ntactics. -/\nmeta def rcases.process_constructor :\n nat → listΠ rcases_patt → listΠ name × listΠ rcases_patt\n| 0 ps := ([], [])\n| 1 [] := ([`_], [default _])\n| 1 [p] := ([p.name.get_or_else `_], [p])\n\n-- The interesting case: we matched the last field against multiple\n-- patterns, so split off the remaining patterns into a subsequent\n-- match. This handles matching `α × β × γ` against `⟨a, b, c⟩`.\n| 1 ps := ([`_], [rcases_patt.tuple ps])\n\n| (n+1) ps :=\n let hd := ps.head, (ns, tl) := rcases.process_constructor n ps.tail in\n (hd.name.get_or_else `_ :: ns, hd :: tl)\n\n/-- Takes a list of constructor names, and an (alternation) list of patterns, and matches each\npattern against its constructor. It returns the list of names that will be passed to `cases`,\nand the list of `(constructor name, patterns)` for each constructor, where `patterns` is the\n(conjunctive) list of patterns to apply to each constructor argument. -/\nmeta def rcases.process_constructors (params : nat) :\n listΣ name → listΣ rcases_patt →\n tactic (dlist name × listΣ (name × listΠ rcases_patt))\n| [] ps := pure (dlist.empty, [])\n| (c::cs) ps := do\n n ← mk_const c >>= get_arity,\n let (h, t) := (match cs, ps.tail with\n -- We matched the last constructor against multiple patterns,\n -- so split off the remaining constructors. This handles matching\n -- `α ⊕ β ⊕ γ` against `a|b|c`.\n | [], _::_ := ([rcases_patt.alts ps], [])\n | _, _ := (ps.head.as_tuple, ps.tail)\n end : _),\n let (ns, ps) := rcases.process_constructor (n - params) h,\n (l, r) ← rcases.process_constructors cs t,\n pure (dlist.of_list ns ++ l, (c, ps) :: r)\n\n/-- Like `zip`, but only elements satisfying a matching predicate `p` will go in the list,\nand elements of the first list that fail to match the second list will be skipped. -/\nprivate def align {α β} (p : α → β → Prop) [∀ a b, decidable (p a b)] :\n list α → list β → list (α × β)\n| (a::as) (b::bs) :=\n if p a b then (a, b) :: align as bs else align as (b::bs)\n| _ _ := []\n\n/-- Given a local constant `e`, get its type. *But* if `e` does not exist, go find a hypothesis\nwith the same pretty name as `e` and get it instead. This is needed because we can sometimes lose\ntrack of the unique names of hypotheses when they are revert/intro'd by `change` and `cases`. (A\nbetter solution would be for these tactics to return a map of renamed hypotheses so that we don't\nlose track of them.) -/\nprivate meta def get_local_and_type (e : expr) : tactic (expr × expr) :=\n(do t ← infer_type e, pure (t, e)) <|> (do\n e ← get_local e.local_pp_name,\n t ← infer_type e, pure (t, e))\n\n/--\n* `rcases_core p e` will match a pattern `p` against a local hypothesis `e`.\n It returns the list of subgoals that were produced.\n* `rcases.continue pes` will match a (conjunctive) list of `(p, e)` pairs which refer to\n patterns and local hypotheses to match against, and applies all of them. Note that this can\n involve matching later arguments multiple times given earlier arguments, for example\n `⟨a | b, ⟨c, d⟩⟩` performs the `⟨c, d⟩` match twice, once on the `a` branch and once on `b`.\n-/\nmeta mutual def rcases_core, rcases.continue\nwith rcases_core : rcases_patt → expr → tactic (list uncleared_goal)\n| (rcases_patt.one `rfl) e := do\n (t, e) ← get_local_and_type e,\n subst e,\n list.map (prod.mk []) <$> get_goals\n-- If the pattern is any other name, we already bound the name in the\n-- top-level `cases` tactic, so there is no more work to do for it.\n| (rcases_patt.one _) _ := list.map (prod.mk []) <$> get_goals\n| rcases_patt.clear e := do\n m ← try_core (get_local_and_type e),\n list.map (prod.mk $ m.elim [] (λ ⟨_, e⟩, [e])) <$> get_goals\n| (rcases_patt.typed p ty) e := do\n (t, e) ← get_local_and_type e,\n ty ← i_to_expr_no_subgoals ``(%%ty : Sort*),\n unify t ty,\n t ← instantiate_mvars t,\n ty ← instantiate_mvars ty,\n e ← if t =ₐ ty then pure e else\n change_core ty (some e) >> get_local e.local_pp_name,\n rcases_core p e\n| (rcases_patt.alts [p]) e := rcases_core p e\n| pat e := do\n (t, e) ← get_local_and_type e,\n t ← whnf t,\n env ← get_env,\n let I := t.get_app_fn.const_name,\n let pat := pat.as_alts,\n (ids, r, l) ← (if I ≠ `quot\n then do\n when (¬env.is_inductive I) $\n fail format!\"rcases tactic failed: {e} : {I} is not an inductive datatype\",\n let params := env.inductive_num_params I,\n let c := env.constructors_of I,\n (ids, r) ← rcases.process_constructors params c pat,\n l ← cases_core e ids.to_list,\n pure (ids, r, l)\n else do\n (ids, r) ← rcases.process_constructors 2 [`quot.mk] pat,\n [(_, d)] ← induction e ids.to_list `quot.induction_on |\n fail format!\"quotient induction on {e} failed. Maybe goal is not in Prop?\",\n -- the result from `induction` is missing the information that the original constructor was\n -- `quot.mk` so we fix this up:\n pure (ids, r, [(`quot.mk, d)])),\n gs ← get_goals,\n -- `cases_core` may not generate a new goal for every constructor,\n -- as some constructors may be impossible for type reasons. (See its\n -- documentation.) Match up the new goals with our remaining work\n -- by constructor name.\n let ls := align (λ (a : name × _) (b : _ × name × _), a.1 = b.2.1) r (gs.zip l),\n list.join <$> ls.mmap (λ⟨⟨_, ps⟩, g, _, hs, _⟩, set_goals [g] >> rcases.continue (ps.zip hs))\n\nwith rcases.continue : listΠ (rcases_patt × expr) → tactic (list uncleared_goal)\n| [] := list.map (prod.mk []) <$> get_goals\n| ((pat, e) :: pes) := do\n gs ← rcases_core pat e,\n list.join <$> gs.mmap (λ ⟨cs, g⟩, do\n set_goals [g],\n ugs ← rcases.continue pes,\n pure $ ugs.map $ λ ⟨cs', gs⟩, (cs ++ cs', gs))\n\n/-- Given a list of `uncleared_goal`s, each of which is a goal metavariable and\na list of variables to clear, actually perform the clear and set the goals with the result. -/\nmeta def clear_goals (ugs : list uncleared_goal) : tactic unit := do\n gs ← ugs.mmap (λ ⟨cs, g⟩, do\n set_goals [g],\n cs ← cs.mfoldr (λ c cs,\n (do (_, c) ← get_local_and_type c, pure (c :: cs)) <|> pure cs) [],\n clear' tt cs,\n [g] ← get_goals,\n pure g),\n set_goals gs\n\n/-- `rcases h e pat` performs case distinction on `e` using `pat` to\nname the arising new variables and assumptions. If `h` is `some` name,\na new assumption `h : e = pat` will relate the expression `e` with the\ncurrent pattern. See the module comment for the syntax of `pat`. -/\nmeta def rcases (h : option name) (p : pexpr) (pat : rcases_patt) : tactic unit := do\n let p := match pat with\n | rcases_patt.typed _ ty := ``(%%p : %%ty)\n | _ := p\n end,\n e ← match h with\n | some h := do\n x ← get_unused_name $ pat.name.get_or_else `this,\n interactive.generalize h () (p, x),\n get_local x\n | none := i_to_expr p\n end,\n if e.is_local_constant then\n focus1 (rcases_core pat e >>= clear_goals)\n else do\n x ← pat.name.elim mk_fresh_name pure,\n n ← revert_kdependencies e semireducible,\n tactic.generalize e x <|> (do\n t ← infer_type e,\n tactic.assertv x t e,\n get_local x >>= tactic.revert,\n pure ()),\n h ← tactic.intro1,\n focus1 (rcases_core pat h >>= clear_goals)\n\n/-- `rcases_many es pats` performs case distinction on the `es` using `pat` to\nname the arising new variables and assumptions.\nSee the module comment for the syntax of `pat`. -/\nmeta def rcases_many (ps : listΠ pexpr) (pat : rcases_patt) : tactic unit := do\n let (_, pats) := rcases.process_constructor ps.length pat.as_tuple,\n pes ← (ps.zip pats).mmap (λ ⟨p, pat⟩, do\n let p := match pat with\n | rcases_patt.typed _ ty := ``(%%p : %%ty)\n | _ := p\n end,\n e ← i_to_expr p,\n if e.is_local_constant then\n pure (pat, e)\n else do\n x ← pat.name.elim mk_fresh_name pure,\n n ← revert_kdependencies e semireducible,\n tactic.generalize e x <|> (do\n t ← infer_type e,\n tactic.assertv x t e,\n get_local x >>= tactic.revert,\n pure ()),\n prod.mk pat <$> tactic.intro1),\n focus1 (rcases.continue pes >>= clear_goals)\n\n/-- `rintro pat₁ pat₂ ... patₙ` introduces `n` arguments, then pattern matches on the `patᵢ` using\nthe same syntax as `rcases`. -/\nmeta def rintro (ids : listΠ rcases_patt) : tactic unit :=\ndo l ← ids.mmap (λ id, do\n e ← intro $ id.name.get_or_else `_,\n pure (id, e)),\n focus1 (rcases.continue l >>= clear_goals)\n\n/-- Like `zip_with`, but if the lists don't match in length, the excess elements will be put at the\nend of the result. -/\ndef merge_list {α} (m : α → α → α) : list α → list α → list α\n| [] l₂ := l₂\n| l₁ [] := l₁\n| (a :: l₁) (b :: l₂) := m a b :: merge_list l₁ l₂\n\n/-- Merge two `rcases` patterns. This is used to underapproximate a case tree by an `rcases`\npattern. The two patterns come from cases in two branches, that due to the syntax of `rcases`\npatterns are forced to overlap. The rule here is that we take only the case splits that are in\ncommon between both branches. For example if one branch does `⟨a, b⟩` and the other does `c`,\nthen we return `c` because we don't know that a case on `c` would be safe to do. -/\nmeta def rcases_patt.merge : rcases_patt → rcases_patt → rcases_patt\n| (rcases_patt.alts p₁) p₂ := rcases_patt.alts (merge_list rcases_patt.merge p₁ p₂.as_alts)\n| p₁ (rcases_patt.alts p₂) := rcases_patt.alts (merge_list rcases_patt.merge p₁.as_alts p₂)\n| (rcases_patt.tuple p₁) p₂ := rcases_patt.tuple (merge_list rcases_patt.merge p₁ p₂.as_tuple)\n| p₁ (rcases_patt.tuple p₂) := rcases_patt.tuple (merge_list rcases_patt.merge p₁.as_tuple p₂)\n| (rcases_patt.typed p₁ e) p₂ := rcases_patt.typed (p₁.merge p₂) e\n| p₁ (rcases_patt.typed p₂ e) := rcases_patt.typed (p₁.merge p₂) e\n| (rcases_patt.one `rfl) (rcases_patt.one `rfl) := rcases_patt.one `rfl\n| (rcases_patt.one `_) p := p\n| p (rcases_patt.one `_) := p\n| rcases_patt.clear p := p\n| p rcases_patt.clear := p\n| (rcases_patt.one n) _ := rcases_patt.one n\n\n/--\n* `rcases_hint_core depth e` does the same as `rcases p e`, except the pattern `p` is an output\n instead of an input, controlled only by the case depth argument `depth`. We use `cases` to depth\n `depth` and then reconstruct an `rcases` pattern `p` that would, if passed to `rcases`, perform\n the same thing as the case tree we just constructed (or at least, the nearest expressible\n approximation to this.)\n* `rcases_hint.process_constructors depth cs l` takes a list of constructor names `cs` and a\n matching list `l` of elements `(g, c', hs, _)` where `c'` is a constructor name (used for\n alignment with `cs`), `g` is the subgoal, and `hs` is the list of local hypotheses created by\n `cases` in that subgoal. It matches on all of them, and then produces a `ΣΠ`-list of `rcases`\n patterns describing the result, and the list of generated subgoals.\n* `rcases_hint.continue depth es` does the same as `rcases.continue (ps.zip es)`, except the\n patterns `ps` are an output instead of an input, created by matching on everything to depth\n `depth` and recording the successful cases. It returns `ps`, and the list of generated subgoals.\n-/\nmeta mutual def rcases_hint_core, rcases_hint.process_constructors, rcases_hint.continue\nwith rcases_hint_core : ℕ → expr → tactic (rcases_patt × list expr)\n| depth e := do\n (t, e) ← get_local_and_type e,\n t ← whnf t,\n env ← get_env,\n let I := t.get_app_fn.const_name,\n (do guard (I = ``eq),\n subst e,\n prod.mk (rcases_patt.one `rfl) <$> get_goals) <|>\n (do\n let c := env.constructors_of I,\n some l ← try_core (guard (depth ≠ 0) >> cases_core e) |\n let n := match e.local_pp_name with name.anonymous := `_ | n := n end in\n prod.mk (rcases_patt.one n) <$> get_goals,\n gs ← get_goals,\n if gs.empty then\n pure (rcases_patt.tuple [], [])\n else do\n (ps, gs') ← rcases_hint.process_constructors (depth - 1) c (gs.zip l),\n pure (rcases_patt.alts₁ ps, gs'))\n\nwith rcases_hint.process_constructors : ℕ → listΣ name →\n list (expr × name × listΠ expr × list (name × expr)) →\n tactic (listΣ (listΠ rcases_patt) × list expr)\n| depth [] _ := pure ([], [])\n| depth cs [] := pure (cs.map (λ _, []), [])\n| depth (c::cs) ls@((g, c', hs, _) :: l) :=\n if c ≠ c' then do\n (ps, gs) ← rcases_hint.process_constructors depth cs ls,\n pure ([] :: ps, gs)\n else do\n (p, gs) ← set_goals [g] >> rcases_hint.continue depth hs,\n (ps, gs') ← rcases_hint.process_constructors depth cs l,\n pure (p :: ps, gs ++ gs')\n\nwith rcases_hint.continue : ℕ → listΠ expr → tactic (listΠ rcases_patt × list expr)\n| depth [] := prod.mk [] <$> get_goals\n| depth (e :: es) := do\n (p, gs) ← rcases_hint_core depth e,\n (ps, gs') ← gs.mfoldl (λ (r : listΠ rcases_patt × list expr) g,\n do (ps, gs') ← set_goals [g] >> rcases_hint.continue depth es,\n pure (merge_list rcases_patt.merge r.1 ps, r.2 ++ gs')) ([], []),\n pure (p :: ps, gs')\n\n/--\n* `rcases? e` is like `rcases e with ...`, except it generates `...` by matching on everything it\ncan, and it outputs an `rcases` invocation that should have the same effect.\n* `rcases? e : n` can be used to control the depth of case splits (especially important for\nrecursive types like `nat`, which can be cased as many times as you like). -/\nmeta def rcases_hint (p : pexpr) (depth : nat) : tactic rcases_patt :=\ndo e ← i_to_expr p,\n if e.is_local_constant then\n focus1 $ do (p, gs) ← rcases_hint_core depth e, set_goals gs, pure p\n else do\n x ← mk_fresh_name,\n n ← revert_kdependencies e semireducible,\n tactic.generalize e x <|> (do\n t ← infer_type e,\n tactic.assertv x t e,\n get_local x >>= tactic.revert,\n pure ()),\n h ← tactic.intro1,\n focus1 $ do (p, gs) ← rcases_hint_core depth h, set_goals gs, pure p\n\n/--\n* `rcases? ⟨e1, e2, e3⟩` is like `rcases ⟨e1, e2, e3⟩ with ...`, except it\n generates `...` by matching on everything it can, and it outputs an `rcases`\n invocation that should have the same effect.\n* `rcases? ⟨e1, e2, e3⟩ : n` can be used to control the depth of case splits\n (especially important for recursive types like `nat`, which can be cased as many\n times as you like). -/\nmeta def rcases_hint_many (ps : list pexpr) (depth : nat) : tactic (listΠ rcases_patt) :=\ndo es ← ps.mmap (λ p, do\n e ← i_to_expr p,\n if e.is_local_constant then pure e\n else do\n x ← mk_fresh_name,\n n ← revert_kdependencies e semireducible,\n tactic.generalize e x <|> (do\n t ← infer_type e,\n tactic.assertv x t e,\n get_local x >>= tactic.revert,\n pure ()),\n tactic.intro1),\n focus1 $ do\n (ps, gs) ← rcases_hint.continue depth es,\n set_goals gs,\n pure ps\n\n/--\n* `rintro?` is like `rintro ...`, except it generates `...` by introducing and matching on\neverything it can, and it outputs an `rintro` invocation that should have the same effect.\n* `rintro? : n` can be used to control the depth of case splits (especially important for\nrecursive types like `nat`, which can be cased as many times as you like). -/\nmeta def rintro_hint (depth : nat) : tactic (listΠ rcases_patt) :=\ndo l ← intros,\n focus1 $ do\n (p, gs) ← rcases_hint.continue depth l,\n set_goals gs,\n pure p\n\nsetup_tactic_parser\n\n/--\n* `rcases_patt_parse tt` will parse a high precedence `rcases` pattern, `patt_hi`.\n This means only tuples and identifiers are allowed; alternations and type ascriptions\n require `(...)` instead, which switches to `patt`.\n* `rcases_patt_parse ff` will parse a low precedence `rcases` pattern, `patt`. This consists of a\n `patt_med` (which deals with alternations), optionally followed by a `: ty` type ascription. The\n expression `ty` is at `texpr` precedence because it can appear at the end of a tactic, for\n example in `rcases e with x : ty <|> skip`.\n* `rcases_patt_parse_list` will parse an alternation list, `patt_med`, one or more `patt`\n patterns separated by `|`. It does not parse a `:` at the end, so that `a | b : ty` parses as\n `(a | b) : ty` where `a | b` is the `patt_med` part.\n* `rcases_patt_parse_list_rest a` parses an alternation list after the initial pattern, `| b | c`.\n\n```lean\npatt ::= patt_med (\":\" expr)?\npatt_med ::= (patt_hi \"|\")* patt_hi\npatt_hi ::= id | \"rfl\" | \"_\" | \"⟨\" (patt \",\")* patt \"⟩\" | \"(\" patt \")\"\n```\n-/\nmeta mutual def rcases_patt_parse, rcases_patt_parse_list, rcases_patt_parse_list_rest\nwith rcases_patt_parse : bool → parser rcases_patt\n| tt := with_desc \"patt_hi\" $\n (brackets \"(\" \")\" (rcases_patt_parse ff)) <|>\n (rcases_patt.tuple <$> brackets \"⟨\" \"⟩\" (sep_by (tk \",\") (rcases_patt_parse ff))) <|>\n (tk \"-\" $> rcases_patt.clear) <|>\n (rcases_patt.one <$> ident_)\n| ff := with_desc \"patt\" $ do\n pat ← rcases_patt.alts' <$> rcases_patt_parse_list,\n (tk \":\" *> pat.typed <$> texpr) <|> pure pat\n\nwith rcases_patt_parse_list : parser (listΣ rcases_patt)\n| x := (with_desc \"patt_med\" $ rcases_patt_parse tt >>= rcases_patt_parse_list_rest) x\n\nwith rcases_patt_parse_list_rest : rcases_patt → parser (listΣ rcases_patt)\n| pat :=\n (tk \"|\" *> list.cons pat <$> rcases_patt_parse_list) <|>\n -- hack to support `-|-` patterns, because `|-` is a token\n (tk \"|-\" *> list.cons pat <$> rcases_patt_parse_list_rest rcases_patt.clear) <|>\n pure [pat]\n\n/-- Parse the optional depth argument `(: n)?` of `rcases?` and `rintro?`, with default depth 5. -/\nmeta def rcases_parse_depth : parser nat :=\ndo o ← (tk \":\" *> small_nat)?, pure $ o.get_or_else 5\n\n/-- The arguments to `rcases`, which in fact dispatch to several other tactics.\n* `rcases? expr (: n)?` or `rcases? ⟨expr, ...⟩ (: n)?` calls `rcases_hint`\n* `rcases? ⟨expr, ...⟩ (: n)?` calls `rcases_hint_many`\n* `rcases (h :)? expr (with patt)?` calls `rcases`\n* `rcases ⟨expr, ...⟩ (with patt)?` calls `rcases_many`\n-/\n@[derive has_reflect]\nmeta inductive rcases_args\n| hint (tgt : pexpr ⊕ list pexpr) (depth : nat)\n| rcases (name : option name) (tgt : pexpr) (pat : rcases_patt)\n| rcases_many (tgt : listΠ pexpr) (pat : rcases_patt)\n\n/-- Syntax for a `rcases` pattern:\n* `rcases? expr (: n)?`\n* `rcases (h :)? expr (with patt_list (: expr)?)?`. -/\nmeta def rcases_parse : parser rcases_args :=\nwith_desc \"('?' expr (: n)?) | ((h :)? expr (with patt)?)\" $ do\n hint ← (tk \"?\")?,\n p ← (sum.inr <$> brackets \"⟨\" \"⟩\" (sep_by (tk \",\") (parser.pexpr 0))) <|>\n (sum.inl <$> texpr),\n match hint with\n | none := do\n p ← (do\n sum.inl (expr.local_const h _ _ _) ← pure p,\n tk \":\" *> (@sum.inl _ (pexpr ⊕ list pexpr) ∘ prod.mk h) <$> texpr) <|>\n pure (sum.inr p),\n ids ← (tk \"with\" *> rcases_patt_parse ff)?,\n let ids := ids.get_or_else (rcases_patt.tuple []),\n pure $ match p with\n | sum.inl (name, tgt) := rcases_args.rcases (some name) tgt ids\n | sum.inr (sum.inl tgt) := rcases_args.rcases none tgt ids\n | sum.inr (sum.inr tgts) := rcases_args.rcases_many tgts ids\n end\n | some _ := do\n depth ← rcases_parse_depth,\n pure $ rcases_args.hint p depth\n end\n\n/--\n`rintro_patt_parse_hi` and `rintro_patt_parse` are like `rcases_patt_parse`, but is used for\nparsing top level `rintro` patterns, which allow sequences like `(x y : t)` in addition to simple\n`rcases` patterns.\n\n* `rintro_patt_parse_hi` will parse a high precedence `rcases` pattern, `rintro_patt_hi` below.\n This means only tuples and identifiers are allowed; alternations and type ascriptions\n require `(...)` instead, which switches to `patt`.\n* `rintro_patt_parse tt` will parse a low precedence `rcases` pattern, `rintro_patt` below.\n This consists of either a sequence of patterns `p1 p2 p3` or an alternation list `p1 | p2 | p3`\n treated as a single pattern, optionally followed by a `: ty` type ascription, which applies to\n every pattern in the list.\n* `rintro_patt_parse ff` parses `rintro_patt_low`, which is the same as `rintro_patt_parse tt` but\n it does not permit an unparenthesized alternation list, it must have the form `p1 p2 p3 (: ty)?`.\n\n```lean\nrintro_patt ::= (rintro_patt_hi+ | patt_med) (\":\" expr)?\nrintro_patt_low ::= rintro_patt_hi* (\":\" expr)?\nrintro_patt_hi ::= patt_hi | \"(\" rintro_patt \")\"\n```\n-/\nmeta mutual def rintro_patt_parse_hi, rintro_patt_parse\nwith rintro_patt_parse_hi : parser (listΠ rcases_patt)\n| x := (with_desc \"rintro_patt_hi\" $\n brackets \"(\" \")\" (rintro_patt_parse tt) <|>\n (do p ← rcases_patt_parse tt, pure [p])) x\nwith rintro_patt_parse : bool → parser (listΠ rcases_patt)\n| med := with_desc \"rintro_patt\" $ do\n ll ← rintro_patt_parse_hi*,\n pats ← match med, ll.join with\n | tt, [] := failure\n | tt, [pat] := do l ← rcases_patt_parse_list_rest pat, pure [rcases_patt.alts' l]\n | _, pats := pure pats\n end,\n (do tk \":\", e ← texpr, pure (pats.map (λ p, rcases_patt.typed p e))) <|>\n pure pats\n\n/-- Syntax for a `rintro` pattern: `('?' (: n)?) | rintro_patt`. -/\nmeta def rintro_parse : parser (listΠ rcases_patt ⊕ nat) :=\nwith_desc \"('?' (: n)?) | patt*\" $\n(tk \"?\" >> sum.inr <$> rcases_parse_depth) <|>\nsum.inl <$> rintro_patt_parse ff\n\nnamespace interactive\nopen interactive interactive.types expr\n\n/--\n`rcases` is a tactic that will perform `cases` recursively, according to a pattern. It is used to\ndestructure hypotheses or expressions composed of inductive types like `h1 : a ∧ b ∧ c ∨ d` or\n`h2 : ∃ x y, trans_rel R x y`. Usual usage might be `rcases h1 with ⟨ha, hb, hc⟩ | hd` or\n`rcases h2 with ⟨x, y, _ | ⟨z, hxz, hzy⟩⟩` for these examples.\n\nEach element of an `rcases` pattern is matched against a particular local hypothesis (most of which\nare generated during the execution of `rcases` and represent individual elements destructured from\nthe input expression). An `rcases` pattern has the following grammar:\n\n* A name like `x`, which names the active hypothesis as `x`.\n* A blank `_`, which does nothing (letting the automatic naming system used by `cases` name the\n hypothesis).\n* A hyphen `-`, which clears the active hypothesis and any dependents.\n* The keyword `rfl`, which expects the hypothesis to be `h : a = b`, and calls `subst` on the\n hypothesis (which has the effect of replacing `b` with `a` everywhere or vice versa).\n* A type ascription `p : ty`, which sets the type of the hypothesis to `ty` and then matches it\n against `p`. (Of course, `ty` must unify with the actual type of `h` for this to work.)\n* A tuple pattern `⟨p1, p2, p3⟩`, which matches a constructor with many arguments, or a series\n of nested conjunctions or existentials. For example if the active hypothesis is `a ∧ b ∧ c`,\n then the conjunction will be destructured, and `p1` will be matched against `a`, `p2` against `b`\n and so on.\n* An alteration pattern `p1 | p2 | p3`, which matches an inductive type with multiple constructors,\n or a nested disjunction like `a ∨ b ∨ c`.\n\nA pattern like `⟨a, b, c⟩ | ⟨d, e⟩` will do a split over the inductive datatype,\nnaming the first three parameters of the first constructor as `a,b,c` and the\nfirst two of the second constructor `d,e`. If the list is not as long as the\nnumber of arguments to the constructor or the number of constructors, the\nremaining variables will be automatically named. If there are nested brackets\nsuch as `⟨⟨a⟩, b | c⟩ | d` then these will cause more case splits as necessary.\nIf there are too many arguments, such as `⟨a, b, c⟩` for splitting on\n`∃ x, ∃ y, p x`, then it will be treated as `⟨a, ⟨b, c⟩⟩`, splitting the last\nparameter as necessary.\n\n`rcases` also has special support for quotient types: quotient induction into Prop works like\nmatching on the constructor `quot.mk`.\n\n`rcases h : e with PAT` will do the same as `rcases e with PAT` with the exception that an\nassumption `h : e = PAT` will be added to the context.\n\n`rcases? e` will perform case splits on `e` in the same way as `rcases e`,\nbut rather than accepting a pattern, it does a maximal cases and prints the\npattern that would produce this case splitting. The default maximum depth is 5,\nbut this can be modified with `rcases? e : n`.\n-/\nmeta def rcases : parse rcases_parse → tactic unit\n| (rcases_args.rcases h p ids) := tactic.rcases h p ids\n| (rcases_args.rcases_many ps ids) := tactic.rcases_many ps ids\n| (rcases_args.hint p depth) := do\n (pe, patt) ← match p with\n | sum.inl p := prod.mk <$> pp p <*> rcases_hint p depth\n | sum.inr ps := do\n patts ← rcases_hint_many ps depth,\n pes ← ps.mmap pp,\n pure (format.bracket \"⟨\" \"⟩\" (format.comma_separated pes), rcases_patt.tuple patts)\n end,\n ppat ← pp patt,\n trace $ ↑\"Try this: rcases \" ++ pe ++ \" with \" ++ ppat\n\nadd_tactic_doc\n{ name := \"rcases\",\n category := doc_category.tactic,\n decl_names := [`tactic.interactive.rcases],\n tags := [\"induction\"] }\n\n/--\nThe `rintro` tactic is a combination of the `intros` tactic with `rcases` to\nallow for destructuring patterns while introducing variables. See `rcases` for\na description of supported patterns. For example, `rintro (a | ⟨b, c⟩) ⟨d, e⟩`\nwill introduce two variables, and then do case splits on both of them producing\ntwo subgoals, one with variables `a d e` and the other with `b c d e`.\n\n`rintro`, unlike `rcases`, also supports the form `(x y : ty)` for introducing\nand type-ascripting multiple variables at once, similar to binders.\n\n`rintro?` will introduce and case split on variables in the same way as\n`rintro`, but will also print the `rintro` invocation that would have the same\nresult. Like `rcases?`, `rintro? : n` allows for modifying the\ndepth of splitting; the default is 5.\n\n`rintros` is an alias for `rintro`.\n-/\nmeta def rintro : parse rintro_parse → tactic unit\n| (sum.inl []) := intros []\n| (sum.inl l) := tactic.rintro l\n| (sum.inr depth) := do\n ps ← tactic.rintro_hint depth,\n fs ← ps.mmap (λ p, do\n f ← pp $ p.format tt,\n pure $ format.space ++ format.group f),\n trace $ ↑\"Try this: rintro\" ++ format.join fs\n\n/-- Alias for `rintro`. -/\nmeta def rintros := rintro\n\nadd_tactic_doc\n{ name := \"rintro\",\n category := doc_category.tactic,\n decl_names := [`tactic.interactive.rintro, `tactic.interactive.rintros],\n tags := [\"induction\"],\n inherit_description_from := `tactic.interactive.rintro }\n\nsetup_tactic_parser\n\n/-- Parses `patt? (: expr)? (:= expr)?`, the arguments for `obtain`.\n (This is almost the same as `rcases_patt_parse ff`,\nbut it allows the pattern part to be empty.) -/\nmeta def obtain_parse :\n parser ((option rcases_patt × option pexpr) × option (pexpr ⊕ list pexpr)) :=\nwith_desc \"patt? (: expr)? (:= expr)?\" $ do\n (pat, tp) ←\n (do pat ← rcases_patt_parse ff,\n pure $ match pat with\n | rcases_patt.typed pat tp := (some pat, some tp)\n | _ := (some pat, none)\n end) <|>\n prod.mk none <$> (tk \":\" >> texpr)?,\n prod.mk (pat, tp) <$> (do\n tk \":=\",\n (guard tp.is_none >>\n sum.inr <$> brackets \"⟨\" \"⟩\" (sep_by (tk \",\") (parser.pexpr 0))) <|>\n (sum.inl <$> texpr))?\n\n/--\nThe `obtain` tactic is a combination of `have` and `rcases`. See `rcases` for\na description of supported patterns.\n\n```lean\nobtain ⟨patt⟩ : type,\n{ ... }\n```\nis equivalent to\n```lean\nhave h : type,\n{ ... },\nrcases h with ⟨patt⟩\n```\n\nThe syntax `obtain ⟨patt⟩ : type := proof` is also supported.\n\nIf `⟨patt⟩` is omitted, `rcases` will try to infer the pattern.\n\nIf `type` is omitted, `:= proof` is required.\n-/\nmeta def obtain : parse obtain_parse → tactic unit\n| ((pat, _), some (sum.inr val)) :=\n tactic.rcases_many val (pat.get_or_else (default _))\n| ((pat, none), some (sum.inl val)) :=\n tactic.rcases none val (pat.get_or_else (default _))\n| ((pat, some tp), some (sum.inl val)) :=\n tactic.rcases none val $ (pat.get_or_else (default _)).typed tp\n| ((pat, some tp), none) := do\n nm ← mk_fresh_name,\n e ← to_expr tp >>= assert nm,\n (g :: gs) ← get_goals,\n set_goals gs,\n tactic.rcases none ``(%%e) (pat.get_or_else (rcases_patt.one `this)),\n gs ← get_goals,\n set_goals (g::gs)\n| ((pat, none), none) :=\n fail $ \"`obtain` requires either an expected type or a value.\\n\" ++\n \"usage: `obtain ⟨patt⟩? : type (:= val)?` or `obtain ⟨patt⟩? (: type)? := val`\"\n\nadd_tactic_doc\n{ name := \"obtain\",\n category := doc_category.tactic,\n decl_names := [`tactic.interactive.obtain],\n tags := [\"induction\"] }\n\nend interactive\nend tactic\n", "meta": {"author": "JLimperg", "repo": "aesop3", "sha": "a4a116f650cc7403428e72bd2e2c4cda300fe03f", "save_path": "github-repos/lean/JLimperg-aesop3", "path": "github-repos/lean/JLimperg-aesop3/aesop3-a4a116f650cc7403428e72bd2e2c4cda300fe03f/src/tactic/rcases.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879062662624377, "lm_q2_score": 0.07159119251161919, "lm_q1q2_score": 0.03356127999844201}} {"text": "/-\nCopyright (c) 2018 Simon Hudon. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Simon Hudon\n\n! This file was ported from Lean 3 source module data.dlist.basic\n! leanprover-community/mathlib commit d6aae1bcbd04b8de2022b9b83a5b5b10e10c777d\n! Please do not edit these lines, except to modify the commit id\n! if you have ported upstream changes.\n-/\nimport Std.Data.DList\nimport Mathlib.Mathport.Rename\nimport Mathlib.Tactic.Cases\n\n\n/-!\n# Difference list\n\nThis file provides a few results about `DList`, which is defined in `Std`.\n\nA difference list is a function that, given a list, returns the original content of the\ndifference list prepended to the given list. It is useful to represent elements of a given type\nas `a₁ + ... + aₙ` where `+ : α → α → α` is any operation, without actually computing.\n\nThis structure supports `O(1)` `append` and `concat` operations on lists, making it\nuseful for append-heavy uses such as logging and pretty printing.\n-/\n\nnamespace Std\n\n/-- Concatenates a list of difference lists to form a single difference list. Similar to\n`List.join`. -/\ndef DList.join {α : Type _} : List (DList α) → DList α\n | [] => DList.empty\n | x :: xs => x ++ DList.join xs\n#align dlist.join Std.DList.join\n\n/-- Convert a lazily-evaluated `List` to a `DList` -/\n-- Ported from Lean 3 core\ndef DList.lazy_ofList (l : Thunk (List α)) : DList α :=\n⟨fun xs => l.get ++ xs, fun t => by simp⟩\n#align dlist.lazy_of_list Std.DList.lazy_ofList\n\n@[simp]\ntheorem DList_singleton {α : Type _} {a : α} : DList.singleton a = DList.lazy_ofList [a] :=\n rfl\n#align dlist_singleton Std.DList_singleton\n\n@[simp]\ntheorem DList_lazy {α : Type _} {l : List α} : DList.lazy_ofList l = Std.DList.ofList l :=\n rfl\n#align dlist_lazy Std.DList_lazy\n\n-- Porting note: port from lean3\ntheorem DList.toList_ofList (l : List α) : DList.toList (DList.ofList l) = l := by\n cases l; rfl; simp only [DList.toList, DList.ofList, List.cons_append, List.append_nil]\n#align dlist.to_list_of_list Std.DList.toList_ofList\n\n-- Porting note: port from lean3\n\n\nend Std\n", "meta": {"author": "leanprover-community", "repo": "mathlib4", "sha": "b9a0a30342ca06e9817e22dbe46e75fc7f435500", "save_path": "github-repos/lean/leanprover-community-mathlib4", "path": "github-repos/lean/leanprover-community-mathlib4/mathlib4-b9a0a30342ca06e9817e22dbe46e75fc7f435500/Mathlib/Data/DList/Basic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.39981165504266236, "lm_q2_score": 0.08389039156396119, "lm_q1q2_score": 0.033540356293364326}} {"text": "/-\nCopyright (c) 2021 Andrew Yang. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Andrew Yang\n-/\nimport category_theory.sites.limits\nimport category_theory.flat_functors\nimport category_theory.limits.preserves.filtered\nimport category_theory.sites.left_exact\n\n/-!\n# Cover-preserving functors between sites.\n\nWe define cover-preserving functors between sites as functors that push covering sieves to\ncovering sieves. A cover-preserving and compatible-preserving functor `G : C ⥤ D` then pulls\nsheaves on `D` back to sheaves on `C` via `G.op ⋙ -`.\n\n## Main definitions\n\n* `category_theory.cover_preserving`: a functor between sites is cover-preserving if it\npushes covering sieves to covering sieves\n* `category_theory.compatible_preserving`: a functor between sites is compatible-preserving\nif it pushes compatible families of elements to compatible families.\n* `category_theory.pullback_sheaf`: the pullback of a sheaf along a cover-preserving and\ncompatible-preserving functor.\n* `category_theory.sites.pullback`: the induced functor `Sheaf K A ⥤ Sheaf J A` for a\ncover-preserving and compatible-preserving functor `G : (C, J) ⥤ (D, K)`.\n* `category_theory.sites.pushforward`: the induced functor `Sheaf J A ⥤ Sheaf K A` for a\ncover-preserving and compatible-preserving functor `G : (C, J) ⥤ (D, K)`.\n* `category_theory.sites.pushforward`: the induced functor `Sheaf J A ⥤ Sheaf K A` for a\ncover-preserving and compatible-preserving functor `G : (C, J) ⥤ (D, K)`.\n\n## Main results\n\n- `category_theory.sites.whiskering_left_is_sheaf_of_cover_preserving`: If `G : C ⥤ D` is\ncover-preserving and compatible-preserving, then `G ⋙ -` (`uᵖ`) as a functor\n`(Dᵒᵖ ⥤ A) ⥤ (Cᵒᵖ ⥤ A)` of presheaves maps sheaves to sheaves.\n\n## References\n\n* [Elephant]: *Sketches of an Elephant*, P. T. Johnstone: C2.3.\n* https://stacks.math.columbia.edu/tag/00WW\n\n-/\n\nuniverses w v₁ v₂ v₃ u₁ u₂ u₃\nnoncomputable theory\n\nopen category_theory\nopen opposite\nopen category_theory.presieve.family_of_elements\nopen category_theory.presieve\nopen category_theory.limits\n\nnamespace category_theory\nvariables {C : Type u₁} [category.{v₁} C] {D : Type u₂} [category.{v₂} D]\nvariables {A : Type u₃} [category.{v₃} A]\nvariables (J : grothendieck_topology C) (K : grothendieck_topology D)\nvariables {L : grothendieck_topology A}\n\n/--\nA functor `G : (C, J) ⥤ (D, K)` between sites is *cover-preserving*\nif for all covering sieves `R` in `C`, `R.pushforward_functor G` is a covering sieve in `D`.\n-/\n@[nolint has_inhabited_instance]\nstructure cover_preserving (G : C ⥤ D) : Prop :=\n(cover_preserve : ∀ {U : C} {S : sieve U} (hS : S ∈ J U), S.functor_pushforward G ∈ K (G.obj U))\n\n/-- The identity functor on a site is cover-preserving. -/\nlemma id_cover_preserving : cover_preserving J J (𝟭 _) := ⟨λ U S hS, by simpa using hS⟩\n\nvariables (J) (K)\n\n/-- The composition of two cover-preserving functors is cover-preserving. -/\nlemma cover_preserving.comp {F} (hF : cover_preserving J K F) {G} (hG : cover_preserving K L G) :\n cover_preserving J L (F ⋙ G) := ⟨λ U S hS,\nbegin\n rw sieve.functor_pushforward_comp,\n exact hG.cover_preserve (hF.cover_preserve hS)\nend⟩\n\n/--\nA functor `G : (C, J) ⥤ (D, K)` between sites is called compatible preserving if for each\ncompatible family of elements at `C` and valued in `G.op ⋙ ℱ`, and each commuting diagram\n`f₁ ≫ G.map g₁ = f₂ ≫ G.map g₂`, `x g₁` and `x g₂` coincide when restricted via `fᵢ`.\nThis is actually stronger than merely preserving compatible families because of the definition of\n`functor_pushforward` used.\n-/\n@[nolint has_inhabited_instance]\nstructure compatible_preserving (K : grothendieck_topology D) (G : C ⥤ D) : Prop :=\n(compatible :\n ∀ (ℱ : SheafOfTypes.{w} K) {Z} {T : presieve Z}\n {x : family_of_elements (G.op ⋙ ℱ.val) T} (h : x.compatible)\n {Y₁ Y₂} {X} (f₁ : X ⟶ G.obj Y₁) (f₂ : X ⟶ G.obj Y₂) {g₁ : Y₁ ⟶ Z} {g₂ : Y₂ ⟶ Z}\n (hg₁ : T g₁) (hg₂ : T g₂) (eq : f₁ ≫ G.map g₁ = f₂ ≫ G.map g₂),\n ℱ.val.map f₁.op (x g₁ hg₁) = ℱ.val.map f₂.op (x g₂ hg₂))\n\nvariables {J K} {G : C ⥤ D} (hG : compatible_preserving.{w} K G) (ℱ : SheafOfTypes.{w} K) {Z : C}\nvariables {T : presieve Z} {x : family_of_elements (G.op ⋙ ℱ.val) T} (h : x.compatible)\n\ninclude h hG\n\n/-- `compatible_preserving` functors indeed preserve compatible families. -/\nlemma presieve.family_of_elements.compatible.functor_pushforward :\n (x.functor_pushforward G).compatible :=\nbegin\n rintros Z₁ Z₂ W g₁ g₂ f₁' f₂' H₁ H₂ eq,\n unfold family_of_elements.functor_pushforward,\n rcases get_functor_pushforward_structure H₁ with ⟨X₁, f₁, h₁, hf₁, rfl⟩,\n rcases get_functor_pushforward_structure H₂ with ⟨X₂, f₂, h₂, hf₂, rfl⟩,\n suffices : ℱ.val.map (g₁ ≫ h₁).op (x f₁ hf₁) = ℱ.val.map (g₂ ≫ h₂).op (x f₂ hf₂),\n simpa using this,\n apply hG.compatible ℱ h _ _ hf₁ hf₂,\n simpa using eq\nend\n\n@[simp] lemma compatible_preserving.apply_map {Y : C} {f : Y ⟶ Z} (hf : T f) :\n x.functor_pushforward G (G.map f) (image_mem_functor_pushforward G T hf) = x f hf :=\nbegin\n unfold family_of_elements.functor_pushforward,\n rcases e₁ : get_functor_pushforward_structure (image_mem_functor_pushforward G T hf) with\n ⟨X, g, f', hg, eq⟩,\n simpa using hG.compatible ℱ h f' (𝟙 _) hg hf (by simp[eq])\nend\n\nomit h hG\n\nopen limits.walking_cospan\n\nlemma compatible_preserving_of_flat {C : Type u₁} [category.{v₁} C] {D : Type u₁} [category.{v₁} D]\n (K : grothendieck_topology D) (G : C ⥤ D) [representably_flat G] : compatible_preserving K G :=\nbegin\n constructor,\n intros ℱ Z T x hx Y₁ Y₂ X f₁ f₂ g₁ g₂ hg₁ hg₂ e,\n\n /- First, `f₁` and `f₂` form a cone over `cospan g₁ g₂ ⋙ u`. -/\n let c : cone (cospan g₁ g₂ ⋙ G) :=\n (cones.postcompose (diagram_iso_cospan (cospan g₁ g₂ ⋙ G)).inv).obj\n (pullback_cone.mk f₁ f₂ e),\n\n /-\n This can then be viewed as a cospan of structured arrows, and we may obtain an arbitrary cone\n over it since `structured_arrow W u` is cofiltered.\n Then, it suffices to prove that it is compatible when restricted onto `u(c'.X.right)`.\n -/\n let c' := is_cofiltered.cone (structured_arrow_cone.to_diagram c ⋙ structured_arrow.pre _ _ _),\n have eq₁ : f₁ = (c'.X.hom ≫ G.map (c'.π.app left).right) ≫ eq_to_hom (by simp),\n { erw ← (c'.π.app left).w, dsimp, simp },\n have eq₂ : f₂ = (c'.X.hom ≫ G.map (c'.π.app right).right) ≫ eq_to_hom (by simp),\n { erw ← (c'.π.app right).w, dsimp, simp },\n conv_lhs { rw eq₁ },\n conv_rhs { rw eq₂ },\n simp only [op_comp, functor.map_comp, types_comp_apply, eq_to_hom_op, eq_to_hom_map],\n congr' 1,\n\n /-\n Since everything now falls in the image of `u`,\n the result follows from the compatibility of `x` in the image of `u`.\n -/\n injection c'.π.naturality walking_cospan.hom.inl with _ e₁,\n injection c'.π.naturality walking_cospan.hom.inr with _ e₂,\n exact hx (c'.π.app left).right (c'.π.app right).right hg₁ hg₂ (e₁.symm.trans e₂)\nend\n\n/--\nIf `G` is cover-preserving and compatible-preserving,\nthen `G.op ⋙ _` pulls sheaves back to sheaves.\n\nThis result is basically https://stacks.math.columbia.edu/tag/00WW.\n-/\ntheorem pullback_is_sheaf_of_cover_preserving {G : C ⥤ D} (hG₁ : compatible_preserving.{v₃} K G)\n (hG₂ : cover_preserving J K G) (ℱ : Sheaf K A) :\n presheaf.is_sheaf J (G.op ⋙ ℱ.val) :=\nbegin\n intros X U S hS x hx,\n change family_of_elements (G.op ⋙ ℱ.val ⋙ coyoneda.obj (op X)) _ at x,\n let H := ℱ.2 X _ (hG₂.cover_preserve hS),\n let hx' := hx.functor_pushforward hG₁ (sheaf_over ℱ X),\n split, swap,\n { apply H.amalgamate (x.functor_pushforward G),\n exact hx' },\n split,\n { intros V f hf,\n convert H.is_amalgamation hx' (G.map f) (image_mem_functor_pushforward G S hf),\n rw hG₁.apply_map (sheaf_over ℱ X) hx },\n { intros y hy,\n refine H.is_separated_for _ y _ _\n (H.is_amalgamation (hx.functor_pushforward hG₁ (sheaf_over ℱ X))),\n rintros V f ⟨Z, f', g', h, rfl⟩,\n erw family_of_elements.comp_of_compatible (S.functor_pushforward G)\n hx' (image_mem_functor_pushforward G S h) g',\n dsimp,\n simp [hG₁.apply_map (sheaf_over ℱ X) hx h, ←hy f' h] }\nend\n\n/-- The pullback of a sheaf along a cover-preserving and compatible-preserving functor. -/\ndef pullback_sheaf {G : C ⥤ D} (hG₁ : compatible_preserving K G)\n (hG₂ : cover_preserving J K G) (ℱ : Sheaf K A) : Sheaf J A :=\n⟨G.op ⋙ ℱ.val, pullback_is_sheaf_of_cover_preserving hG₁ hG₂ ℱ⟩\n\nvariable (A)\n\n/--\nThe induced functor from `Sheaf K A ⥤ Sheaf J A` given by `G.op ⋙ _`\nif `G` is cover-preserving and compatible-preserving.\n-/\n@[simps] def sites.pullback {G : C ⥤ D} (hG₁ : compatible_preserving K G)\n (hG₂ : cover_preserving J K G) : Sheaf K A ⥤ Sheaf J A :=\n{ obj := λ ℱ, pullback_sheaf hG₁ hG₂ ℱ,\n map := λ _ _ f, ⟨(((whiskering_left _ _ _).obj G.op)).map f.val⟩,\n map_id' := λ ℱ, by { ext1, apply (((whiskering_left _ _ _).obj G.op)).map_id },\n map_comp' := λ _ _ _ f g, by { ext1, apply (((whiskering_left _ _ _).obj G.op)).map_comp } }\n\nend category_theory\n\nnamespace category_theory\n\nvariables {C : Type v₁} [small_category C] {D : Type v₁} [small_category D]\nvariables (A : Type u₂) [category.{v₁} A]\nvariables (J : grothendieck_topology C) (K : grothendieck_topology D)\n\ninstance [has_limits A] : creates_limits (Sheaf_to_presheaf J A) :=\ncategory_theory.Sheaf.category_theory.Sheaf_to_presheaf.category_theory.creates_limits.{u₂ v₁ v₁}\n\n-- The assumptions so that we have sheafification\nvariables [concrete_category.{v₁} A] [preserves_limits (forget A)] [has_colimits A] [has_limits A]\nvariables [preserves_filtered_colimits (forget A)] [reflects_isomorphisms (forget A)]\n\nlocal attribute [instance] reflects_limits_of_reflects_isomorphisms\n\ninstance {X : C} : is_cofiltered (J.cover X) := infer_instance\n\n/-- The pushforward functor `Sheaf J A ⥤ Sheaf K A` associated to a functor `G : C ⥤ D` in the\nsame direction as `G`. -/\n@[simps] def sites.pushforward (G : C ⥤ D) : Sheaf J A ⥤ Sheaf K A :=\nSheaf_to_presheaf J A ⋙ Lan G.op ⋙ presheaf_to_Sheaf K A\n\ninstance (G : C ⥤ D) [representably_flat G] :\n preserves_finite_limits (sites.pushforward A J K G) :=\nbegin\n apply_with comp_preserves_finite_limits { instances := ff },\n { apply_instance },\n apply_with comp_preserves_finite_limits { instances := ff },\n { apply category_theory.Lan_preserves_finite_limits_of_flat },\n { apply category_theory.presheaf_to_Sheaf.limits.preserves_finite_limits.{u₂ v₁ v₁},\n apply_instance }\nend\n\n/-- The pushforward functor is left adjoint to the pullback functor. -/\ndef sites.pullback_pushforward_adjunction {G : C ⥤ D} (hG₁ : compatible_preserving K G)\n (hG₂ : cover_preserving J K G) : sites.pushforward A J K G ⊣ sites.pullback A hG₁ hG₂ :=\n((Lan.adjunction A G.op).comp _ _ (sheafification_adjunction K A)).restrict_fully_faithful\n (Sheaf_to_presheaf J A) (𝟭 _)\n (nat_iso.of_components (λ _, iso.refl _)\n (λ _ _ _,(category.comp_id _).trans (category.id_comp _).symm))\n (nat_iso.of_components (λ _, iso.refl _)\n (λ _ _ _,(category.comp_id _).trans (category.id_comp _).symm))\n\nend category_theory\n", "meta": {"author": "Mel-TunaRoll", "repo": "Lean-Mordell-Weil-Mel-Branch", "sha": "4db36f86423976aacd2c2968c4e45787fcd86b97", "save_path": "github-repos/lean/Mel-TunaRoll-Lean-Mordell-Weil-Mel-Branch", "path": "github-repos/lean/Mel-TunaRoll-Lean-Mordell-Weil-Mel-Branch/Lean-Mordell-Weil-Mel-Branch-4db36f86423976aacd2c2968c4e45787fcd86b97/src/category_theory/sites/cover_preserving.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4610167941228964, "lm_q2_score": 0.07263669933452759, "lm_q1q2_score": 0.03348673826287263}} {"text": "/-\nCopyright (c) 2019 Paul-Nicolas Madelaine. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Paul-Nicolas Madelaine, Robert Y. Lewis\n\nNormalizing casts inside expressions.\n-/\nimport tactic.converter.interactive\nimport tactic.hint\n\n/-!\n# A tactic for normalizing casts inside expressions\n\nThis tactic normalizes casts inside expressions.\nIt can be thought of as a call to the simplifier with a specific set of lemmas to\nmove casts upwards in the expression.\nIt has special handling of numerals and a simple heuristic to help moving\ncasts \"past\" binary operators.\nContrary to simp, it should be safe to use as a non-terminating tactic.\n\nThe algorithm implemented here is described in the paper\n.\n\n## Important definitions\n* `tactic.interactive.norm_cast`\n* `tactic.interactive.push_cast`\n* `tactic.interactive.exact_mod_cast`\n* `tactic.interactive.apply_mod_cast`\n* `tactic.interactive.rw_mod_cast`\n* `tactic.interactive.assumption_mod_cast`\n-/\n\nsetup_tactic_parser\n\nnamespace tactic\n\n/--\nRuns `mk_instance` with a time limit.\n\nThis is a work around to the fact that in some cases\nmk_instance times out instead of failing,\nfor example: `has_lift_t ℤ ℕ`\n\n`mk_instance_fast` is used when we assume the type class search\nshould end instantly.\n-/\nmeta def mk_instance_fast (e : expr) (timeout := 1000) : tactic expr :=\ntry_for timeout (mk_instance e)\n\nend tactic\n\nnamespace norm_cast\n\nopen tactic expr\n\ndeclare_trace norm_cast\n\n/--\nOutput a trace message if `trace.norm_cast` is enabled.\n-/\nmeta def trace_norm_cast {α} [has_to_tactic_format α] (msg : string) (a : α) : tactic unit :=\nwhen_tracing `norm_cast $ do\na ← pp a,\ntrace (\"[norm_cast] \" ++ msg ++ a : format)\n\nmk_simp_attribute push_cast \"The `push_cast` simp attribute uses `norm_cast` lemmas\nto move casts toward the leaf nodes of the expression.\"\n\n/--\n`label` is a type used to classify `norm_cast` lemmas.\n* elim lemma: LHS has 0 head coes and ≥ 1 internal coe\n* move lemma: LHS has 1 head coe and 0 internal coes, RHS has 0 head coes and ≥ 1 internal coes\n* squash lemma: LHS has ≥ 1 head coes and 0 internal coes, RHS has fewer head coes\n-/\n@[derive [decidable_eq, has_reflect, inhabited]]\ninductive label\n| elim : label\n| move : label\n| squash : label\n\nnamespace label\n\n/-- Convert `label` into `string`. -/\nprotected def to_string : label → string\n| elim := \"elim\"\n| move := \"move\"\n| squash := \"squash\"\n\ninstance : has_to_string label := ⟨label.to_string⟩\ninstance : has_repr label := ⟨label.to_string⟩\nmeta instance : has_to_format label := ⟨λ l, l.to_string⟩\n\n/-- Convert `string` into `label`. -/\ndef of_string : string -> option label\n| \"elim\" := some elim\n| \"move\" := some move\n| \"squash\" := some squash\n| _ := none\n\nend label\n\nopen label\n\n/-- Count how many coercions are at the top of the expression. -/\nmeta def count_head_coes : expr → ℕ\n| `(coe %%e) := count_head_coes e + 1\n| `(coe_sort %%e) := count_head_coes e + 1\n| `(coe_fn %%e) := count_head_coes e + 1\n| _ := 0\n\n/-- Count how many coercions are inside the expression, including the top ones. -/\nmeta def count_coes : expr → tactic ℕ\n| `(coe %%e) := (+1) <$> count_coes e\n| `(coe_sort %%e) := (+1) <$> count_coes e\n| `(coe_fn %%e) := (+1) <$> count_coes e\n| (app `(coe_fn %%e) x) := (+) <$> count_coes x <*> (+1) <$> count_coes e\n| (expr.lam n bi t e) := do\n l ← mk_local' n bi t,\n count_coes $ e.instantiate_var l\n| e := do\n as ← e.get_simp_args,\n list.sum <$> as.mmap count_coes\n\n/-- Count how many coercions are inside the expression, excluding the top ones. -/\nprivate meta def count_internal_coes (e : expr) : tactic ℕ := do\nncoes ← count_coes e,\npure $ ncoes - count_head_coes e\n\n/--\nClassifies a declaration of type `ty` as a `norm_cast` rule.\n-/\nmeta def classify_type (ty : expr) : tactic label := do\n(_, ty) ← open_pis ty,\n(lhs, rhs) ← match ty with\n | `(%%lhs = %%rhs) := pure (lhs, rhs)\n | `(%%lhs ↔ %%rhs) := pure (lhs, rhs)\n | _ := fail \"norm_cast: lemma must be = or ↔\"\n end,\nlhs_coes ← count_coes lhs,\nwhen (lhs_coes = 0) $ fail \"norm_cast: badly shaped lemma, lhs must contain at least one coe\",\nlet lhs_head_coes := count_head_coes lhs,\nlhs_internal_coes ← count_internal_coes lhs,\nlet rhs_head_coes := count_head_coes rhs,\nrhs_internal_coes ← count_internal_coes rhs,\nif lhs_head_coes = 0 then\n return elim\nelse if lhs_head_coes = 1 then do\n when (rhs_head_coes ≠ 0) $ fail \"norm_cast: badly shaped lemma, rhs can't start with coe\",\n if rhs_internal_coes = 0 then\n return squash\n else\n return move\nelse if rhs_head_coes < lhs_head_coes then do\n return squash\nelse do\n fail \"norm_cast: badly shaped shaped squash lemma, rhs must have fewer head coes than lhs\"\n\n/-- The cache for `norm_cast` attribute stores three `simp_lemma` objects. -/\nmeta structure norm_cast_cache :=\n(up : simp_lemmas)\n(down : simp_lemmas)\n(squash : simp_lemmas)\n\n/-- Empty `norm_cast_cache`. -/\nmeta def empty_cache : norm_cast_cache :=\n{ up := simp_lemmas.mk,\n down := simp_lemmas.mk,\n squash := simp_lemmas.mk, }\n\nmeta instance : inhabited norm_cast_cache := ⟨empty_cache⟩\n\n/-- `add_elim cache e` adds `e` as an `elim` lemma to `cache`. -/\nmeta def add_elim (cache : norm_cast_cache) (e : expr) : tactic norm_cast_cache :=\ndo\n new_up ← simp_lemmas.add cache.up e,\n return\n { up := new_up,\n down := cache.down,\n squash := cache.squash, }\n\n/-- `add_move cache e` adds `e` as a `move` lemma to `cache`. -/\nmeta def add_move (cache : norm_cast_cache) (e : expr) : tactic norm_cast_cache :=\ndo\n ty ← infer_type e,\n new_up ← cache.up.add e tt,\n new_down ← simp_lemmas.add cache.down e,\n return {\n up := new_up,\n down := new_down,\n squash := cache.squash, }\n\n/-- `add_squash cache e` adds `e` as an `squash` lemma to `cache`. -/\nmeta def add_squash (cache : norm_cast_cache) (e : expr) : tactic norm_cast_cache :=\ndo\n new_squash ← simp_lemmas.add cache.squash e,\n new_down ← simp_lemmas.add cache.down e,\n return {\n up := cache.up,\n down := new_down,\n squash := new_squash, }\n\n/--\nThe type of the `norm_cast` attribute.\nThe optional label is used to overwrite the classifier.\n-/\nmeta def norm_cast_attr_ty : Type := user_attribute norm_cast_cache (option label)\n\n/--\nEfficient getter for the `@[norm_cast]` attribute parameter that does not call `eval_expr`.\n\nSee Note [user attribute parameters].\n-/\nmeta def get_label_param (attr : norm_cast_attr_ty) (decl : name) : tactic (option label) := do\np ← attr.get_param_untyped decl,\nmatch p with\n| `(none) := pure none\n| `(some label.elim) := pure label.elim\n| `(some label.move) := pure label.move\n| `(some label.squash) := pure label.squash\n| _ := fail p\nend\n\n/--\n`add_lemma cache decl` infers the proper `norm_cast` attribute for `decl` and adds it to `cache`.\n-/\nmeta def add_lemma (attr : norm_cast_attr_ty) (cache : norm_cast_cache) (decl : name) :\n tactic norm_cast_cache :=\ndo\n e ← mk_const decl,\n param ← get_label_param attr decl,\n l ← param <|> (infer_type e >>= classify_type),\n match l with\n | elim := add_elim cache e\n | move := add_move cache e\n | squash := add_squash cache e\n end\n\n-- special lemmas to handle the ≥, > and ≠ operators\nprivate lemma ge_from_le {α} [has_le α] : ∀ (x y : α), x ≥ y ↔ y ≤ x := λ _ _, iff.rfl\nprivate lemma gt_from_lt {α} [has_lt α] : ∀ (x y : α), x > y ↔ y < x := λ _ _, iff.rfl\nprivate lemma ne_from_not_eq {α} : ∀ (x y : α), x ≠ y ↔ ¬(x = y) := λ _ _, iff.rfl\n\n/--\n`mk_cache names` creates a `norm_cast_cache`. It infers the proper `norm_cast` attributes\nfor names in `names`, and collects the lemmas attributed with specific `norm_cast` attributes.\n-/\nmeta def mk_cache (attr : thunk norm_cast_attr_ty) (names : list name) :\n tactic norm_cast_cache := do\n-- names has the declarations in reverse order\ncache ← names.mfoldr (λ name cache, add_lemma (attr ()) cache name) empty_cache,\n\n--some special lemmas to handle binary relations\nlet up := cache.up,\nup ← up.add_simp ``ge_from_le,\nup ← up.add_simp ``gt_from_lt,\nup ← up.add_simp ``ne_from_not_eq,\n\nlet down := cache.down,\ndown ← down.add_simp ``coe_coe,\n\npure { up := up, down := down, squash := cache.squash }\n\n/--\nThe `norm_cast` attribute.\n-/\n@[user_attribute] meta def norm_cast_attr : user_attribute norm_cast_cache (option label) :=\n{ name := `norm_cast,\n descr := \"attribute for norm_cast\",\n parser :=\n (do some l ← (label.of_string ∘ to_string) <$> ident, return l)\n <|> return none,\n after_set := some (λ decl prio persistent, do\n param ← get_label_param norm_cast_attr decl,\n match param with\n | some l :=\n when (l ≠ elim) $ simp_attr.push_cast.set decl () tt\n | none := do\n e ← mk_const decl,\n ty ← infer_type e,\n l ← classify_type ty,\n norm_cast_attr.set decl l persistent prio\n end),\n before_unset := some $ λ _ _, tactic.skip,\n cache_cfg := { mk_cache := mk_cache norm_cast_attr, dependencies := [] } }\n\n/-- Classify a declaration as a `norm_cast` rule. -/\nmeta def make_guess (decl : name) : tactic label :=\ndo\n e ← mk_const decl,\n ty ← infer_type e,\n classify_type ty\n\n/--\nGets the `norm_cast` classification label for a declaration. Applies the\noverride specified on the attribute, if necessary.\n-/\nmeta def get_label (decl : name) : tactic label :=\ndo\n param ← get_label_param norm_cast_attr decl,\n param <|> make_guess decl\n\nend norm_cast\n\nnamespace tactic.interactive\nopen norm_cast\n\n/--\n`push_cast` rewrites the expression to move casts toward the leaf nodes.\nFor example, `↑(a + b)` will be written to `↑a + ↑b`.\nEquivalent to `simp only with push_cast`.\nCan also be used at hypotheses.\n\n`push_cast` can also be used at hypotheses and with extra simp rules.\n\n```lean\nexample (a b : ℕ) (h1 : ((a + b : ℕ) : ℤ) = 10) (h2 : ((a + b + 0 : ℕ) : ℤ) = 10) :\n ((a + b : ℕ) : ℤ) = 10 :=\nbegin\n push_cast,\n push_cast at h1,\n push_cast [int.add_zero] at h2,\nend\n```\n-/\nmeta def push_cast (hs : parse tactic.simp_arg_list) (l : parse location) : tactic unit :=\ntactic.interactive.simp none none tt hs [`push_cast] l\n\n\nend tactic.interactive\n\nnamespace norm_cast\nopen tactic expr\n\n/-- Prove `a = b` using the given simp set. -/\nmeta def prove_eq_using (s : simp_lemmas) (a b : expr) : tactic expr := do\n(a', a_a', _) ← simplify s [] a {fail_if_unchanged := ff},\n(b', b_b', _) ← simplify s [] b {fail_if_unchanged := ff},\non_exception (trace_norm_cast \"failed: \" (to_expr ``(%%a' = %%b') >>= pp)) $\n is_def_eq a' b' reducible,\nb'_b ← mk_eq_symm b_b',\nmk_eq_trans a_a' b'_b\n\n/-- Prove `a = b` by simplifying using move and squash lemmas. -/\nmeta def prove_eq_using_down (a b : expr) : tactic expr := do\ncache ← norm_cast_attr.get_cache,\ntrace_norm_cast \"proving: \" (to_expr ``(%%a = %%b) >>= pp),\nprove_eq_using cache.down a b\n\n/--\nThis is the main heuristic used alongside the elim and move lemmas.\nThe goal is to help casts move past operators by adding intermediate casts.\nAn expression of the shape: op (↑(x : α) : γ) (↑(y : β) : γ)\nis rewritten to: op (↑(↑(x : α) : β) : γ) (↑(y : β) : γ)\nwhen (↑(↑(x : α) : β) : γ) = (↑(x : α) : γ) can be proven with a squash lemma\n-/\nmeta def splitting_procedure : expr → tactic (expr × expr)\n| (app (app op x) y) :=\n(do\n `(@coe %%α %%δ %%coe1 %%xx) ← return x,\n `(@coe %%β %%γ %%coe2 %%yy) ← return y,\n success_if_fail $ is_def_eq α β,\n is_def_eq δ γ,\n\n (do\n coe3 ← mk_app `has_lift_t [α, β] >>= mk_instance_fast,\n new_x ← to_expr ``(@coe %%β %%δ %%coe2 (@coe %%α %%β %%coe3 %%xx)),\n let new_e := app (app op new_x) y,\n eq_x ← prove_eq_using_down x new_x,\n pr ← mk_congr_arg op eq_x,\n pr ← mk_congr_fun pr y,\n return (new_e, pr)\n ) <|> (do\n coe3 ← mk_app `has_lift_t [β, α] >>= mk_instance_fast,\n new_y ← to_expr ``(@coe %%α %%δ %%coe1 (@coe %%β %%α %%coe3 %%yy)),\n let new_e := app (app op x) new_y,\n eq_y ← prove_eq_using_down y new_y,\n pr ← mk_congr_arg (app op x) eq_y,\n return (new_e, pr)\n )\n) <|> (do\n `(@coe %%α %%β %%coe1 %%xx) ← return x,\n `(@has_one.one %%β %%h1) ← return y,\n h2 ← to_expr ``(has_one %%α) >>= mk_instance_fast,\n new_y ← to_expr ``(@coe %%α %%β %%coe1 (@has_one.one %%α %%h2)),\n eq_y ← prove_eq_using_down y new_y,\n let new_e := app (app op x) new_y,\n pr ← mk_congr_arg (app op x) eq_y,\n return (new_e, pr)\n ) <|> (do\n `(@coe %%α %%β %%coe1 %%xx) ← return x,\n `(@has_zero.zero %%β %%h1) ← return y,\n h2 ← to_expr ``(has_zero %%α) >>= mk_instance_fast,\n new_y ← to_expr ``(@coe %%α %%β %%coe1 (@has_zero.zero %%α %%h2)),\n eq_y ← prove_eq_using_down y new_y,\n let new_e := app (app op x) new_y,\n pr ← mk_congr_arg (app op x) eq_y,\n return (new_e, pr)\n) <|> (do\n `(@has_one.one %%β %%h1) ← return x,\n `(@coe %%α %%β %%coe1 %%xx) ← return y,\n h1 ← to_expr ``(has_one %%α) >>= mk_instance_fast,\n new_x ← to_expr ``(@coe %%α %%β %%coe1 (@has_one.one %%α %%h1)),\n eq_x ← prove_eq_using_down x new_x,\n let new_e := app (app op new_x) y,\n pr ← mk_congr_arg (lam `x binder_info.default β (app (app op (var 0)) y)) eq_x,\n return (new_e, pr)\n) <|> (do\n `(@has_zero.zero %%β %%h1) ← return x,\n `(@coe %%α %%β %%coe1 %%xx) ← return y,\n h1 ← to_expr ``(has_zero %%α) >>= mk_instance_fast,\n new_x ← to_expr ``(@coe %%α %%β %%coe1 (@has_zero.zero %%α %%h1)),\n eq_x ← prove_eq_using_down x new_x,\n let new_e := app (app op new_x) y,\n pr ← mk_congr_arg (lam `x binder_info.default β (app (app op (var 0)) y)) eq_x,\n return (new_e, pr)\n)\n| _ := failed\n\n/--\nDischarging function used during simplification in the \"squash\" step.\n\nTODO: norm_cast takes a list of expressions to use as lemmas for the discharger\nTODO: a tactic to print the results the discharger fails to proove\n-/\nprivate meta def prove : tactic unit :=\nassumption\n\n/--\nCore rewriting function used in the \"squash\" step, which moves casts upwards\nand eliminates them.\n\nIt tries to rewrite an expression using the elim and move lemmas.\nOn failure, it calls the splitting procedure heuristic.\n-/\nmeta def upward_and_elim (s : simp_lemmas) (e : expr) : tactic (expr × expr) :=\n(do\n r ← mcond (is_prop e) (return `iff) (return `eq),\n (new_e, pr) ← s.rewrite e prove r,\n pr ← match r with\n | `iff := mk_app `propext [pr]\n | _ := return pr\n end,\n return (new_e, pr)\n) <|> splitting_procedure e\n\n/-!\nThe following auxiliary functions are used to handle numerals.\n-/\n\n/--\nIf possible, rewrite `(n : α)` to `((n : ℕ) : α)` where `n` is a numeral and `α ≠ ℕ`.\nReturns a pair of the new expression and proof that they are equal.\n-/\nmeta def numeral_to_coe (e : expr) : tactic (expr × expr) :=\ndo\n α ← infer_type e,\n success_if_fail $ is_def_eq α `(ℕ),\n n ← e.to_nat,\n h1 ← mk_app `has_lift_t [`(ℕ), α] >>= mk_instance_fast,\n let new_e : expr := reflect n,\n new_e ← to_expr ``(@coe ℕ %%α %%h1 %%new_e),\n pr ← prove_eq_using_down e new_e,\n return (new_e, pr)\n\n/--\nIf possible, rewrite `((n : ℕ) : α)` to `(n : α)` where `n` is a numeral.\nReturns a pair of the new expression and proof that they are equal.\n-/\nmeta def coe_to_numeral (e : expr) : tactic (expr × expr) :=\ndo\n `(@coe ℕ %%α %%h1 %%e') ← return e,\n n ← e'.to_nat,\n -- replace e' by normalized numeral\n is_def_eq (reflect n) e' reducible,\n let e := e.app_fn (reflect n),\n new_e ← expr.of_nat α n,\n pr ← prove_eq_using_down e new_e,\n return (new_e, pr)\n\n/-- A local variant on `simplify_top_down`. -/\nprivate meta def simplify_top_down' {α} (a : α) (pre : α → expr → tactic (α × expr × expr))\n (e : expr) (cfg : simp_config := {}) : tactic (α × expr × expr) :=\next_simplify_core a cfg simp_lemmas.mk (λ _, failed)\n (λ a _ _ _ e, do\n (new_a, new_e, pr) ← pre a e,\n guard (¬ new_e =ₐ e),\n return (new_a, new_e, some pr, ff))\n (λ _ _ _ _ _, failed)\n `eq e\n\n/--\nThe core simplification routine of `norm_cast`.\n-/\nmeta def derive (e : expr) : tactic (expr × expr) :=\ndo\n cache ← norm_cast_attr.get_cache,\n e ← instantiate_mvars e,\n let cfg : simp_config := {\n zeta := ff,\n beta := ff,\n eta := ff,\n proj := ff,\n iota := ff,\n iota_eqn := ff,\n fail_if_unchanged := ff },\n let e0 := e,\n\n -- step 1: pre-processing of numerals\n ((), e1, pr1) ← simplify_top_down' () (λ _ e, prod.mk () <$> numeral_to_coe e) e0 cfg,\n trace_norm_cast \"after numeral_to_coe: \" e1,\n\n -- step 2: casts are moved upwards and eliminated\n ((), e2, pr2) ← simplify_bottom_up () (λ _ e, prod.mk () <$> upward_and_elim cache.up e) e1 cfg,\n trace_norm_cast \"after upward_and_elim: \" e2,\n\n -- step 3: casts are squashed\n (e3, pr3, _) ← simplify cache.squash [] e2 cfg,\n trace_norm_cast \"after squashing: \" e3,\n\n -- step 4: post-processing of numerals\n ((), e4, pr4) ← simplify_top_down' () (λ _ e, prod.mk () <$> coe_to_numeral e) e3 cfg,\n trace_norm_cast \"after coe_to_numeral: \" e4,\n\n let new_e := e4,\n guard (¬ new_e =ₐ e),\n pr ← mk_eq_trans pr1 pr2,\n pr ← mk_eq_trans pr pr3,\n pr ← mk_eq_trans pr pr4,\n return (new_e, pr)\n\n/--\nA small variant of `push_cast` suited for non-interactive use.\n\n`derive_push_cast extra_lems e` returns an expression `e'` and a proof that `e = e'`.\n-/\nmeta def derive_push_cast (extra_lems : list simp_arg_type) (e : expr) : tactic (expr × expr) :=\ndo (s, _) ← mk_simp_set tt [`push_cast] extra_lems,\n (e, prf, _) ← simplify (s.erase [`int.coe_nat_succ]) [] e {fail_if_unchanged := ff},\n return (e, prf)\n\nend norm_cast\n\nnamespace tactic\nopen expr norm_cast\n\n/-- `aux_mod_cast e` runs `norm_cast` on `e` and returns the result. If `include_goal` is true, it\nalso normalizes the goal. -/\nmeta def aux_mod_cast (e : expr) (include_goal : bool := tt) : tactic expr :=\nmatch e with\n| local_const _ lc _ _ := do\n e ← get_local lc,\n replace_at derive [e] include_goal,\n get_local lc\n| e := do\n t ← infer_type e,\n e ← assertv `this t e,\n replace_at derive [e] include_goal,\n get_local `this\nend\n\n/-- `exact_mod_cast e` runs `norm_cast` on the goal and `e`, and tries to use `e` to close the\ngoal. -/\nmeta def exact_mod_cast (e : expr) : tactic unit :=\ndecorate_error \"exact_mod_cast failed:\" $ do\n new_e ← aux_mod_cast e,\n exact new_e\n\n/-- `apply_mod_cast e` runs `norm_cast` on the goal and `e`, and tries to apply `e`. -/\nmeta def apply_mod_cast (e : expr) : tactic (list (name × expr)) :=\ndecorate_error \"apply_mod_cast failed:\" $ do\n new_e ← aux_mod_cast e,\n apply new_e\n\n/-- `assumption_mod_cast` runs `norm_cast` on the goal. For each local hypothesis `h`, it also\nnormalizes `h` and tries to use that to close the goal. -/\nmeta def assumption_mod_cast : tactic unit :=\ndecorate_error \"assumption_mod_cast failed:\" $ do\n let cfg : simp_config := {\n fail_if_unchanged := ff,\n canonize_instances := ff,\n canonize_proofs := ff,\n proj := ff\n },\n replace_at derive [] tt,\n ctx ← local_context,\n try_lst $ ctx.map (λ h, aux_mod_cast h ff >>= tactic.exact)\n\nend tactic\n\nnamespace tactic.interactive\nopen tactic norm_cast\n\n/--\nNormalize casts at the given locations by moving them \"upwards\".\nAs opposed to simp, norm_cast can be used without necessarily closing the goal.\n-/\nmeta def norm_cast (loc : parse location) : tactic unit :=\ndo\n ns ← loc.get_locals,\n tt ← replace_at derive ns loc.include_goal | fail \"norm_cast failed to simplify\",\n when loc.include_goal $ try tactic.reflexivity,\n when loc.include_goal $ try tactic.triv,\n when (¬ ns.empty) $ try tactic.contradiction\n\n/--\nRewrite with the given rules and normalize casts between steps.\n-/\nmeta def rw_mod_cast (rs : parse rw_rules) (loc : parse location) : tactic unit :=\ndecorate_error \"rw_mod_cast failed:\" $ do\n let cfg_norm : simp_config := {},\n let cfg_rw : rewrite_cfg := {},\n ns ← loc.get_locals,\n monad.mapm' (λ r : rw_rule, do\n save_info r.pos,\n replace_at derive ns loc.include_goal,\n rw ⟨[r], none⟩ loc {}\n ) rs.rules,\n replace_at derive ns loc.include_goal,\n skip\n\n/--\nNormalize the goal and the given expression, then close the goal with exact.\n-/\nmeta def exact_mod_cast (e : parse texpr) : tactic unit :=\ndo\n e ← i_to_expr e <|> do {\n ty ← target,\n e ← i_to_expr_strict ``(%%e : %%ty),\n pty ← pp ty, ptgt ← pp e,\n fail (\"exact_mod_cast failed, expression type not directly \" ++\n \"inferrable. Try:\\n\\nexact_mod_cast ...\\nshow \" ++\n to_fmt pty ++ \",\\nfrom \" ++ ptgt : format)\n },\n tactic.exact_mod_cast e\n\n/--\nNormalize the goal and the given expression, then apply the expression to the goal.\n-/\nmeta def apply_mod_cast (e : parse texpr) : tactic unit :=\ndo\n e ← i_to_expr_for_apply e,\n concat_tags $ tactic.apply_mod_cast e\n\n/--\nNormalize the goal and every expression in the local context, then close the goal with assumption.\n-/\nmeta def assumption_mod_cast : tactic unit :=\ntactic.assumption_mod_cast\n\nend tactic.interactive\n\nnamespace conv.interactive\nopen conv\nopen norm_cast (derive)\n\n/-- the converter version of `norm_cast' -/\nmeta def norm_cast : conv unit := replace_lhs derive\n\nend conv.interactive\n\n-- TODO: move this elsewhere?\n@[norm_cast] lemma ite_cast {α β} [has_lift_t α β]\n {c : Prop} [decidable c] {a b : α} :\n ↑(ite c a b) = ite c (↑a : β) (↑b : β) :=\nby by_cases h : c; simp [h]\n\n@[norm_cast] lemma dite_cast {α β} [has_lift_t α β]\n {c : Prop} [decidable c] {a : c → α} {b : ¬ c → α} :\n ↑(dite c a b) = dite c (λ h, (↑(a h) : β)) (λ h, (↑(b h) : β)) :=\nby by_cases h : c; simp [h]\n\nadd_hint_tactic \"norm_cast at *\"\n\n/--\nThe `norm_cast` family of tactics is used to normalize casts inside expressions.\nIt is basically a simp tactic with a specific set of lemmas to move casts\nupwards in the expression.\nTherefore it can be used more safely as a non-terminating tactic.\nIt also has special handling of numerals.\n\nFor instance, given an assumption\n```lean\na b : ℤ\nh : ↑a + ↑b < (10 : ℚ)\n```\n\nwriting `norm_cast at h` will turn `h` into\n```lean\nh : a + b < 10\n```\n\nYou can also use `exact_mod_cast`, `apply_mod_cast`, `rw_mod_cast`\nor `assumption_mod_cast`.\nWriting `exact_mod_cast h` and `apply_mod_cast h` will normalize the goal and\n`h` before using `exact h` or `apply h`.\nWriting `assumption_mod_cast` will normalize the goal and for every\nexpression `h` in the context it will try to normalize `h` and use\n`exact h`.\n`rw_mod_cast` acts like the `rw` tactic but it applies `norm_cast` between steps.\n\n`push_cast` rewrites the expression to move casts toward the leaf nodes.\nThis uses `norm_cast` lemmas in the forward direction.\nFor example, `↑(a + b)` will be written to `↑a + ↑b`.\nIt is equivalent to `simp only with push_cast`.\nIt can also be used at hypotheses with `push_cast at h`\nand with extra simp lemmas with `push_cast [int.add_zero]`.\n\n```lean\nexample (a b : ℕ) (h1 : ((a + b : ℕ) : ℤ) = 10) (h2 : ((a + b + 0 : ℕ) : ℤ) = 10) :\n ((a + b : ℕ) : ℤ) = 10 :=\nbegin\n push_cast,\n push_cast at h1,\n push_cast [int.add_zero] at h2,\nend\n```\n\nThe implementation and behavior of the `norm_cast` family is described in detail at\n.\n-/\nadd_tactic_doc\n{ name := \"norm_cast\",\n category := doc_category.tactic,\n decl_names := [``tactic.interactive.norm_cast, ``tactic.interactive.rw_mod_cast,\n ``tactic.interactive.apply_mod_cast, ``tactic.interactive.assumption_mod_cast,\n ``tactic.interactive.exact_mod_cast, ``tactic.interactive.push_cast],\n tags := [\"coercions\", \"simplification\"] }\n\n/--\nThe `norm_cast` attribute should be given to lemmas that describe the\nbehaviour of a coercion in regard to an operator, a relation, or a particular\nfunction.\n\nIt only concerns equality or iff lemmas involving `↑`, `⇑` and `↥`, describing the behavior of\nthe coercion functions.\nIt does not apply to the explicit functions that define the coercions.\n\nExamples:\n```lean\n@[norm_cast] theorem coe_nat_inj' {m n : ℕ} : (↑m : ℤ) = ↑n ↔ m = n\n\n@[norm_cast] theorem coe_int_denom (n : ℤ) : (n : ℚ).denom = 1\n\n@[norm_cast] theorem cast_id : ∀ n : ℚ, ↑n = n\n\n@[norm_cast] theorem coe_nat_add (m n : ℕ) : (↑(m + n) : ℤ) = ↑m + ↑n\n\n@[norm_cast] theorem cast_sub [add_group α] [has_one α] {m n} (h : m ≤ n) :\n ((n - m : ℕ) : α) = n - m\n\n@[norm_cast] theorem coe_nat_bit0 (n : ℕ) : (↑(bit0 n) : ℤ) = bit0 ↑n\n\n@[norm_cast] theorem cast_coe_nat (n : ℕ) : ((n : ℤ) : α) = n\n\n@[norm_cast] theorem cast_one : ((1 : ℚ) : α) = 1\n```\n\nLemmas tagged with `@[norm_cast]` are classified into three categories: `move`, `elim`, and\n`squash`. They are classified roughly as follows:\n\n* elim lemma: LHS has 0 head coes and ≥ 1 internal coe\n* move lemma: LHS has 1 head coe and 0 internal coes, RHS has 0 head coes and ≥ 1 internal coes\n* squash lemma: LHS has ≥ 1 head coes and 0 internal coes, RHS has fewer head coes\n\n`norm_cast` uses `move` and `elim` lemmas to factor coercions toward the root of an expression\nand to cancel them from both sides of an equation or relation. It uses `squash` lemmas to clean\nup the result.\n\nOccasionally you may want to override the automatic classification.\nYou can do this by giving an optional `elim`, `move`, or `squash` parameter to the attribute.\n\n```lean\n@[simp, norm_cast elim] lemma nat_cast_re (n : ℕ) : (n : ℂ).re = n :=\nby rw [← of_real_nat_cast, of_real_re]\n```\n\nDon't do this unless you understand what you are doing.\n\nA full description of the tactic, and the use of each lemma category, can be found at\n.\n-/\nadd_tactic_doc\n{ name := \"norm_cast attributes\",\n category := doc_category.attr,\n decl_names := [``norm_cast.norm_cast_attr],\n tags := [\"coercions\", \"simplification\"] }\n\n-- Lemmas defined in core.\nattribute [norm_cast]\n int.nat_abs_of_nat\n int.coe_nat_sub\n int.coe_nat_mul\n int.coe_nat_zero\n int.coe_nat_one\n int.coe_nat_add\n\n-- Lemmas about nat.succ need to get a low priority, so that they are tried last.\n-- This is because `nat.succ _` matches `1`, `3`, `x+1`, etc.\n-- Rewriting would then produce really wrong terms.\nattribute [norm_cast, priority 500] int.coe_nat_succ\n", "meta": {"author": "JLimperg", "repo": "aesop3", "sha": "a4a116f650cc7403428e72bd2e2c4cda300fe03f", "save_path": "github-repos/lean/JLimperg-aesop3", "path": "github-repos/lean/JLimperg-aesop3/aesop3-a4a116f650cc7403428e72bd2e2c4cda300fe03f/src/tactic/norm_cast.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45326184801538616, "lm_q2_score": 0.07369627631804176, "lm_q1q2_score": 0.03340371039576815}} {"text": "/-\nCopyright (c) 2017 Mario Carneiro. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Mario Carneiro, Yury Kudryashov, Floris van Doorn\n\n! This file was ported from Lean 3 source module tactic.to_additive\n! leanprover-community/mathlib commit bfe9e712c5178b227be330f7c10c2e91ab48eaf8\n! Please do not edit these lines, except to modify the commit id\n! if you have ported upstream changes.\n-/\nimport Mathbin.Tactic.TransformDecl\nimport Mathbin.Tactic.Algebra\nimport Mathbin.Tactic.Lint.Basic\nimport Mathbin.Tactic.Alias\n\n/-!\n# Transport multiplicative to additive\n\nThis file defines an attribute `to_additive` that can be used to\nautomatically transport theorems and definitions (but not inductive\ntypes and structures) from a multiplicative theory to an additive theory.\n\nUsage information is contained in the doc string of `to_additive.attr`.\n\n### Missing features\n\n* Automatically transport structures and other inductive types.\n\n* For structures, automatically generate theorems like `group α ↔\n add_group (additive α)`.\n-/\n\n\nnamespace ToAdditive\n\nopen Tactic\n\n/- ./././Mathport/Syntax/Translate/Tactic/Mathlib/Core.lean:38:34: unsupported: setup_tactic_parser -/\nsection PerformanceHack\n\n-- see Note [user attribute parameters]\nattribute [local semireducible] reflected\n\n/-- Temporarily change the `has_reflect` instance for `name`. -/\n@[local instance]\nunsafe def hacky_name_reflect : has_reflect Name := fun n => q((id $(expr.const n []) : Name))\n#align to_additive.hacky_name_reflect to_additive.hacky_name_reflect\n\n/-- An auxiliary attribute used to store the names of the additive versions of declarations\nthat have been processed by `to_additive`. -/\n@[user_attribute]\nunsafe def aux_attr : user_attribute (name_map Name) Name\n where\n Name := `to_additive_aux\n descr := \"Auxiliary attribute for `to_additive`. DON'T USE IT\"\n parser := failed\n cache_cfg :=\n ⟨fun ns =>\n ns.foldlM\n (fun dict n' => do\n let n :=\n match n' with\n | Name.mk_string s pre => if s = \"_to_additive\" then pre else n'\n | _ => n'\n let param ← aux_attr.get_param_untyped n'\n pure <| dict n param)\n mk_name_map,\n []⟩\n#align to_additive.aux_attr to_additive.aux_attr\n\nend PerformanceHack\n\nsection ExtraAttributes\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:207:4: warning: unsupported notation `parser.many -/\n/-- An attribute that tells `@[to_additive]` that certain arguments of this definition are not\ninvolved when using `@[to_additive]`.\nThis helps the heuristic of `@[to_additive]` by also transforming definitions if `ℕ` or another\nfixed type occurs as one of these arguments.\n-/\n@[user_attribute]\nunsafe def ignore_args_attr : user_attribute (name_map <| List ℕ) (List ℕ)\n where\n Name := `to_additive_ignore_args\n descr :=\n \"Auxiliary attribute for `to_additive` stating that certain arguments are not additivized.\"\n cache_cfg :=\n ⟨fun ns =>\n ns.foldlM\n (fun dict n => do\n let param ← ignore_args_attr.get_param_untyped n\n -- see Note [user attribute parameters]\n return <|\n dict n (param expr.to_nat).iget)\n mk_name_map,\n []⟩\n parser := parser.many lean.parser.small_nat\n#align to_additive.ignore_args_attr to_additive.ignore_args_attr\n\n/--\nAn attribute that is automatically added to declarations tagged with `@[to_additive]`, if needed.\n\nThis attribute tells which argument is the type where this declaration uses the multiplicative\nstructure. If there are multiple argument, we typically tag the first one.\nIf this argument contains a fixed type, this declaration will note be additivized.\nSee the Heuristics section of `to_additive.attr` for more details.\n\nIf a declaration is not tagged, it is presumed that the first argument is relevant.\n`@[to_additive]` uses the function `to_additive.first_multiplicative_arg` to automatically tag\ndeclarations. It is ok to update it manually if the automatic tagging made an error.\n\nImplementation note: we only allow exactly 1 relevant argument, even though some declarations\n(like `prod.group`) have multiple arguments with a multiplicative structure on it.\nThe reason is that whether we additivize a declaration is an all-or-nothing decision, and if\nwe will not be able to additivize declarations that (e.g.) talk about multiplication on `ℕ × α`\nanyway.\n\nWarning: adding `@[to_additive_reorder]` with an equal or smaller number than the number in this\nattribute is currently not supported.\n-/\n@[user_attribute]\nunsafe def relevant_arg_attr : user_attribute (name_map ℕ) ℕ\n where\n Name := `to_additive_relevant_arg\n descr :=\n \"Auxiliary attribute for `to_additive` stating which arguments are the types with a \" ++\n \"multiplicative structure.\"\n cache_cfg :=\n ⟨fun ns =>\n ns.foldlM\n (fun dict n => do\n let param ← relevant_arg_attr.get_param_untyped n\n -- see Note [user attribute parameters]\n -- we subtract 1 from the values provided by the user.\n return <|\n dict n <| param)\n mk_name_map,\n []⟩\n parser := lean.parser.small_nat\n#align to_additive.relevant_arg_attr to_additive.relevant_arg_attr\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:207:4: warning: unsupported notation `parser.many -/\n/-- An attribute that stores all the declarations that needs their arguments reordered when\napplying `@[to_additive]`. Currently, we only support swapping consecutive arguments.\nThe list of the natural numbers contains the positions of the first of the two arguments\nto be swapped.\nIf the first two arguments are swapped, the first two universe variables are also swapped.\nExample: `@[to_additive_reorder 1 4]` swaps the first two arguments and the arguments in\npositions 4 and 5.\n-/\n@[user_attribute]\nunsafe def reorder_attr : user_attribute (name_map <| List ℕ) (List ℕ)\n where\n Name := `to_additive_reorder\n descr := \"Auxiliary attribute for `to_additive` that stores arguments that need to be reordered.\"\n cache_cfg :=\n ⟨fun ns =>\n ns.foldlM\n (fun dict n => do\n let param ← reorder_attr.get_param_untyped n\n -- see Note [user attribute parameters]\n return <|\n dict n (param expr.to_nat).iget)\n mk_name_map,\n []⟩\n parser := do\n let l ← parser.many lean.parser.small_nat\n guard (l (· ≠ 0)) <|> exceptional.fail \"The reorder positions must be positive\"\n return l\n#align to_additive.reorder_attr to_additive.reorder_attr\n\nend ExtraAttributes\n\n/-- Find the first argument of `nm` that has a multiplicative type-class on it.\nReturns 1 if there are no types with a multiplicative class as arguments.\nE.g. `prod.group` returns 1, and `pi.has_one` returns 2.\n-/\nunsafe def first_multiplicative_arg (nm : Name) : tactic ℕ := do\n let d ← get_decl nm\n let (es, _) := d.type.pi_binders\n let l ←\n es.mapIdxM fun n bi => do\n let tgt := bi.type.pi_codomain\n let n_bi := bi.type.pi_binders.fst.length\n let tt ← has_attribute' `to_additive tgt.get_app_fn.const_name |\n return none\n let n2 := tgt.get_app_args.headI.get_app_fn.match_var.map fun m => n + n_bi - m\n return <| n2\n let l := l.reduceOption\n return <| if l = [] then 1 else l min l\n#align to_additive.first_multiplicative_arg to_additive.first_multiplicative_arg\n\n/-- A command that can be used to have future uses of `to_additive` change the `src` namespace\nto the `tgt` namespace.\n\nFor example:\n```\nrun_cmd to_additive.map_namespace `quotient_group `quotient_add_group\n```\n\nLater uses of `to_additive` on declarations in the `quotient_group` namespace will be created\nin the `quotient_add_group` namespaces.\n-/\nunsafe def map_namespace (src tgt : Name) : Tactic := do\n let n := src.mk_string \"_to_additive\"\n let decl := declaration.thm n [] q(Unit) (pure (reflect ()))\n add_decl decl\n aux_attr n tgt tt\n#align to_additive.map_namespace to_additive.map_namespace\n\n/-- `value_type` is the type of the arguments that can be provided to `to_additive`.\n`to_additive.parser` parses the provided arguments:\n* `replace_all`: replace all multiplicative declarations, do not use the heuristic.\n* `trace`: output the generated additive declaration.\n* `tgt : name`: the name of the target (the additive declaration).\n* `doc`: an optional doc string.\n* if `allow_auto_name` is `ff` (default) then `@[to_additive]` will check whether the given name\n can be auto-generated.\n-/\nstructure ValueType : Type where\n replaceAll : Bool\n trace : Bool\n tgt : Name\n doc : Option String\n allowAutoName : Bool\n deriving has_reflect, Inhabited\n#align to_additive.value_type ToAdditive.ValueType\n\n/-- `add_comm_prefix x s` returns `\"comm_\" ++ s` if `x = tt` and `s` otherwise. -/\nunsafe def add_comm_prefix : Bool → String → String\n | tt, s => \"comm_\" ++ s\n | ff, s => s\n#align to_additive.add_comm_prefix to_additive.add_comm_prefix\n\n/-- Dictionary used by `to_additive.guess_name` to autogenerate names. -/\nunsafe def tr : Bool → List String → List String\n | is_comm, \"one\" :: \"le\" :: s => add_comm_prefix is_comm \"nonneg\" :: tr false s\n | is_comm, \"one\" :: \"lt\" :: s => add_comm_prefix is_comm \"pos\" :: tr false s\n | is_comm, \"le\" :: \"one\" :: s => add_comm_prefix is_comm \"nonpos\" :: tr false s\n | is_comm, \"lt\" :: \"one\" :: s => add_comm_prefix is_comm \"neg\" :: tr false s\n | is_comm, \"mul\" :: \"single\" :: s => add_comm_prefix is_comm \"single\" :: tr false s\n | is_comm, \"mul\" :: \"support\" :: s => add_comm_prefix is_comm \"support\" :: tr false s\n | is_comm, \"mul\" :: \"tsupport\" :: s => add_comm_prefix is_comm \"tsupport\" :: tr false s\n | is_comm, \"mul\" :: \"indicator\" :: s => add_comm_prefix is_comm \"indicator\" :: tr false s\n | is_comm, \"mul\" :: s => add_comm_prefix is_comm \"add\" :: tr false s\n | is_comm, \"smul\" :: s => add_comm_prefix is_comm \"vadd\" :: tr false s\n | is_comm, \"inv\" :: s => add_comm_prefix is_comm \"neg\" :: tr false s\n | is_comm, \"div\" :: s => add_comm_prefix is_comm \"sub\" :: tr false s\n | is_comm, \"one\" :: s => add_comm_prefix is_comm \"zero\" :: tr false s\n | is_comm, \"prod\" :: s => add_comm_prefix is_comm \"sum\" :: tr false s\n | is_comm, \"finprod\" :: s => add_comm_prefix is_comm \"finsum\" :: tr false s\n | is_comm, \"pow\" :: s => add_comm_prefix is_comm \"nsmul\" :: tr false s\n | is_comm, \"npow\" :: s => add_comm_prefix is_comm \"nsmul\" :: tr false s\n | is_comm, \"zpow\" :: s => add_comm_prefix is_comm \"zsmul\" :: tr false s\n | is_comm, \"is\" :: \"square\" :: s => add_comm_prefix is_comm \"even\" :: tr false s\n | is_comm, \"is\" :: \"scalar\" :: \"tower\" :: s =>\n add_comm_prefix is_comm \"vadd_assoc_class\" :: tr false s\n | is_comm, \"is\" :: \"central\" :: \"scalar\" :: s =>\n add_comm_prefix is_comm \"is_central_vadd\" :: tr false s\n | is_comm, \"is\" :: \"regular\" :: s => add_comm_prefix is_comm \"is_add_regular\" :: tr false s\n | is_comm, \"is\" :: \"left\" :: \"regular\" :: s =>\n add_comm_prefix is_comm \"is_add_left_regular\" :: tr false s\n | is_comm, \"is\" :: \"right\" :: \"regular\" :: s =>\n add_comm_prefix is_comm \"is_add_right_regular\" :: tr false s\n | is_comm, \"division\" :: \"monoid\" :: s =>\n \"subtraction\" :: add_comm_prefix is_comm \"monoid\" :: tr false s\n | is_comm, \"monoid\" :: s => (\"add_\" ++ add_comm_prefix is_comm \"monoid\") :: tr false s\n | is_comm, \"submonoid\" :: s => (\"add_\" ++ add_comm_prefix is_comm \"submonoid\") :: tr false s\n | is_comm, \"group\" :: s => (\"add_\" ++ add_comm_prefix is_comm \"group\") :: tr false s\n | is_comm, \"subgroup\" :: s => (\"add_\" ++ add_comm_prefix is_comm \"subgroup\") :: tr false s\n | is_comm, \"semigroup\" :: s => (\"add_\" ++ add_comm_prefix is_comm \"semigroup\") :: tr false s\n | is_comm, \"magma\" :: s => (\"add_\" ++ add_comm_prefix is_comm \"magma\") :: tr false s\n | is_comm, \"haar\" :: s => (\"add_\" ++ add_comm_prefix is_comm \"haar\") :: tr false s\n | is_comm, \"prehaar\" :: s => (\"add_\" ++ add_comm_prefix is_comm \"prehaar\") :: tr false s\n | is_comm, \"unit\" :: s => (\"add_\" ++ add_comm_prefix is_comm \"unit\") :: tr false s\n | is_comm, \"units\" :: s => (\"add_\" ++ add_comm_prefix is_comm \"units\") :: tr false s\n | is_comm, \"comm\" :: s => tr true s\n | is_comm, \"root\" :: s => add_comm_prefix is_comm \"div\" :: tr false s\n | is_comm, \"rootable\" :: s => add_comm_prefix is_comm \"divisible\" :: tr false s\n | is_comm, \"prods\" :: s => add_comm_prefix is_comm \"sums\" :: tr false s\n | is_comm, x :: s => add_comm_prefix is_comm x :: tr false s\n | tt, [] => [\"comm\"]\n | ff, [] => []\n#align to_additive.tr to_additive.tr\n\n/-- Autogenerate target name for `to_additive`. -/\nunsafe def guess_name : String → String :=\n String.mapTokens ''' fun s =>\n String.intercalate (String.singleton '_') <| tr false (s.splitOn '_')\n#align to_additive.guess_name to_additive.guess_name\n\n/-- Return the provided target name or autogenerate one if one was not provided. -/\nunsafe def target_name (src tgt : Name) (dict : name_map Name) (allow_auto_name : Bool) :\n tactic Name :=\n (if tgt.getPrefix ≠ Name.anonymous ∨ allow_auto_name then\n -- `tgt` is a full name\n pure\n tgt\n else\n match src with\n | Name.mk_string s pre => do\n let tgt_auto := guess_name s\n guard (tgt ≠ tgt_auto ∨ tgt = src) <|>\n trace\n (\"`to_additive \" ++ src ++ \"`: correctly autogenerated target \" ++\n \"name, you may remove the explicit \" ++\n tgt_auto ++\n \" argument.\")\n pure <| Name.mk_string (if tgt = Name.anonymous then tgt_auto else tgt) (pre dict)\n | _ => fail (\"to_additive: can't transport \" ++ src.toString)) >>=\n fun res =>\n if res = src ∧ tgt ≠ src then\n fail\n (\"to_additive: can't transport \" ++ src.toString ++\n \" to itself.\\nGive the desired additive name explicitly using `@[to_additive additive_name]`. \")\n else pure res\n#align to_additive.target_name to_additive.target_name\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:207:4: warning: unsupported notation `parser.optional -/\n/- ./././Mathport/Syntax/Translate/Expr.lean:207:4: warning: unsupported notation `parser.optional -/\n/- ./././Mathport/Syntax/Translate/Expr.lean:207:4: warning: unsupported notation `parser.optional -/\n/- ./././Mathport/Syntax/Translate/Expr.lean:207:4: warning: unsupported notation `parser.optional -/\n/-- the parser for the arguments to `to_additive`. -/\nunsafe def parser : lean.parser ValueType := do\n let bang ← Option.isSome <$> parser.optional (tk \"!\")\n let ques ← Option.isSome <$> parser.optional (tk \"?\")\n let tgt ← parser.optional ident\n let e ← parser.optional texpr\n let doc ←\n match e with\n | some pe => some <$> (to_expr pe >>= eval_expr String : tactic String)\n | none => pure none\n return ⟨bang, ques, tgt Name.anonymous, doc, ff⟩\n#align to_additive.parser to_additive.parser\n\nprivate unsafe def proceed_fields_aux (src tgt : Name) (prio : ℕ)\n (f : Name → tactic (List String)) : Tactic := do\n let src_fields ← f src\n let tgt_fields ← f tgt\n guard (src_fields = tgt_fields) <|> fail (\"Failed to map fields of \" ++ src)\n (src_fields tgt_fields).mapM' fun names =>\n guard (names = names) <|> aux_attr (src names) (tgt names) tt prio\n#align to_additive.proceed_fields_aux to_additive.proceed_fields_aux\n\n/-- Add the `aux_attr` attribute to the structure fields of `src`\nso that future uses of `to_additive` will map them to the corresponding `tgt` fields. -/\nunsafe def proceed_fields (env : environment) (src tgt : Name) (prio : ℕ) : Tactic :=\n let aux := proceed_fields_aux src tgt prio\n do\n ((aux fun n => pure <| List.map Name.toString <| (env n).getD []) >>\n aux fun n => (List.map fun x : Name => \"to_\" ++ x) <$> get_tagged_ancestors n) >>\n aux fun n =>\n (env n).mapM fun cs =>\n match cs with\n | Name.mk_string s pre => (guard (pre = n) <|> fail \"Bad constructor name\") >> pure s\n | _ => fail \"Bad constructor name\"\n#align to_additive.proceed_fields to_additive.proceed_fields\n\n/-- The attribute `to_additive` can be used to automatically transport theorems\nand definitions (but not inductive types and structures) from a multiplicative\ntheory to an additive theory.\n\nTo use this attribute, just write:\n\n```\n@[to_additive]\ntheorem mul_comm' {α} [comm_semigroup α] (x y : α) : x * y = y * x := comm_semigroup.mul_comm\n```\n\nThis code will generate a theorem named `add_comm'`. It is also\npossible to manually specify the name of the new declaration:\n\n```\n@[to_additive add_foo]\ntheorem foo := sorry\n```\n\nAn existing documentation string will _not_ be automatically used, so if the theorem or definition\nhas a doc string, a doc string for the additive version should be passed explicitly to\n`to_additive`.\n\n```\n/-- Multiplication is commutative -/\n@[to_additive \"Addition is commutative\"]\ntheorem mul_comm' {α} [comm_semigroup α] (x y : α) : x * y = y * x := comm_semigroup.mul_comm\n```\n\nThe transport tries to do the right thing in most cases using several\nheuristics described below. However, in some cases it fails, and\nrequires manual intervention.\n\nIf the declaration to be transported has attributes which need to be\ncopied to the additive version, then `to_additive` should come last:\n\n```\n@[simp, to_additive] lemma mul_one' {G : Type*} [group G] (x : G) : x * 1 = x := mul_one x\n```\n\nThe following attributes are supported and should be applied correctly by `to_additive` to\nthe new additivized declaration, if they were present on the original one:\n```\nreducible, _refl_lemma, simp, norm_cast, instance, refl, symm, trans, elab_as_eliminator, no_rsimp,\ncontinuity, ext, ematch, measurability, alias, _ext_core, _ext_lemma_core, nolint\n```\n\nThe exception to this rule is the `simps` attribute, which should come after `to_additive`:\n\n```\n@[to_additive, simps]\ninstance {M N} [has_mul M] [has_mul N] : has_mul (M × N) := ⟨λ p q, ⟨p.1 * q.1, p.2 * q.2⟩⟩\n```\n\nAdditionally the `mono` attribute is not handled by `to_additive` and should be applied afterwards\nto both the original and additivized lemma.\n\n## Implementation notes\n\nThe transport process generally works by taking all the names of\nidentifiers appearing in the name, type, and body of a declaration and\ncreating a new declaration by mapping those names to additive versions\nusing a simple string-based dictionary and also using all declarations\nthat have previously been labeled with `to_additive`.\n\nIn the `mul_comm'` example above, `to_additive` maps:\n* `mul_comm'` to `add_comm'`,\n* `comm_semigroup` to `add_comm_semigroup`,\n* `x * y` to `x + y` and `y * x` to `y + x`, and\n* `comm_semigroup.mul_comm'` to `add_comm_semigroup.add_comm'`.\n\n### Heuristics\n\n`to_additive` uses heuristics to determine whether a particular identifier has to be\nmapped to its additive version. The basic heuristic is\n\n* Only map an identifier to its additive version if its first argument doesn't\n contain any unapplied identifiers.\n\nExamples:\n* `@has_mul.mul ℕ n m` (i.e. `(n * m : ℕ)`) will not change to `+`, since its\n first argument is `ℕ`, an identifier not applied to any arguments.\n* `@has_mul.mul (α × β) x y` will change to `+`. It's first argument contains only the identifier\n `prod`, but this is applied to arguments, `α` and `β`.\n* `@has_mul.mul (α × ℤ) x y` will not change to `+`, since its first argument contains `ℤ`.\n\nThe reasoning behind the heuristic is that the first argument is the type which is \"additivized\",\nand this usually doesn't make sense if this is on a fixed type.\n\nThere are some exceptions to this heuristic:\n\n* Identifiers that have the `@[to_additive]` attribute are ignored.\n For example, multiplication in `↥Semigroup` is replaced by addition in `↥AddSemigroup`.\n* If an identifier `d` has attribute `@[to_additive_relevant_arg n]` then the argument\n in position `n` is checked for a fixed type, instead of checking the first argument.\n `@[to_additive]` will automatically add the attribute `@[to_additive_relevant_arg n]` to a\n declaration when the first argument has no multiplicative type-class, but argument `n` does.\n* If an identifier has attribute `@[to_additive_ignore_args n1 n2 ...]` then all the arguments in\n positions `n1`, `n2`, ... will not be checked for unapplied identifiers (start counting from 1).\n For example, `cont_mdiff_map` has attribute `@[to_additive_ignore_args 21]`, which means\n that its 21st argument `(n : ℕ∞)` can contain `ℕ`\n (usually in the form `has_top.top ℕ ...`) and still be additivized.\n So `@has_mul.mul (C^∞⟮I, N; I', G⟯) _ f g` will be additivized.\n\n### Troubleshooting\n\nIf `@[to_additive]` fails because the additive declaration raises a type mismatch, there are\nvarious things you can try.\nThe first thing to do is to figure out what `@[to_additive]` did wrong by looking at the type\nmismatch error.\n\n* Option 1: It additivized a declaration `d` that should remain multiplicative. Solution:\n * Make sure the first argument of `d` is a type with a multiplicative structure. If not, can you\n reorder the (implicit) arguments of `d` so that the first argument becomes a type with a\n multiplicative structure (and not some indexing type)?\n The reason is that `@[to_additive]` doesn't additivize declarations if their first argument\n contains fixed types like `ℕ` or `ℝ`. See section Heuristics.\n If the first argument is not the argument with a multiplicative type-class, `@[to_additive]`\n should have automatically added the attribute `@[to_additive_relevant_arg]` to the declaration.\n You can test this by running the following (where `d` is the full name of the declaration):\n ```\n run_cmd to_additive.relevant_arg_attr.get_param `d >>= tactic.trace\n ```\n The expected output is `n` where the `n`-th argument of `d` is a type (family) with a\n multiplicative structure on it. If you get a different output (or a failure), you could add\n the attribute `@[to_additive_relevant_arg n]` manually, where `n` is an argument with a\n multiplicative structure.\n* Option 2: It didn't additivize a declaration that should be additivized.\n This happened because the heuristic applied, and the first argument contains a fixed type,\n like `ℕ` or `ℝ`. Solutions:\n * If the fixed type has an additive counterpart (like `↥Semigroup`), give it the `@[to_additive]`\n attribute.\n * If the fixed type occurs inside the `k`-th argument of a declaration `d`, and the\n `k`-th argument is not connected to the multiplicative structure on `d`, consider adding\n attribute `[to_additive_ignore_args k]` to `d`.\n * If you want to disable the heuristic and replace all multiplicative\n identifiers with their additive counterpart, use `@[to_additive!]`.\n* Option 3: Arguments / universe levels are incorrectly ordered in the additive version.\n This likely only happens when the multiplicative declaration involves `pow`/`^`. Solutions:\n * Ensure that the order of arguments of all relevant declarations are the same for the\n multiplicative and additive version. This might mean that arguments have an \"unnatural\" order\n (e.g. `monoid.npow n x` corresponds to `x ^ n`, but it is convenient that `monoid.npow` has this\n argument order, since it matches `add_monoid.nsmul n x`.\n * If this is not possible, add the `[to_additive_reorder k]` to the multiplicative declaration\n to indicate that the `k`-th and `(k+1)`-st arguments are reordered in the additive version.\n\nIf neither of these solutions work, and `to_additive` is unable to automatically generate the\nadditive version of a declaration, manually write and prove the additive version.\nOften the proof of a lemma/theorem can just be the multiplicative version of the lemma applied to\n`multiplicative G`.\nAfterwards, apply the attribute manually:\n\n```\nattribute [to_additive foo_add_bar] foo_bar\n```\n\nThis will allow future uses of `to_additive` to recognize that\n`foo_bar` should be replaced with `foo_add_bar`.\n\n### Handling of hidden definitions\n\nBefore transporting the “main” declaration `src`, `to_additive` first\nscans its type and value for names starting with `src`, and transports\nthem. This includes auxiliary definitions like `src._match_1`,\n`src._proof_1`.\n\nIn addition to transporting the “main” declaration, `to_additive` transports\nits equational lemmas and tags them as equational lemmas for the new declaration,\nattributes present on the original equational lemmas are also transferred first (notably\n`_refl_lemma`).\n\n### Structure fields and constructors\n\nIf `src` is a structure, then `to_additive` automatically adds\nstructure fields to its mapping, and similarly for constructors of\ninductive types.\n\nFor new structures this means that `to_additive` automatically handles\ncoercions, and for old structures it does the same, if ancestry\ninformation is present in `@[ancestor]` attributes. The `ancestor`\nattribute must come before the `to_additive` attribute, and it is\nessential that the order of the base structures passed to `ancestor` matches\nbetween the multiplicative and additive versions of the structure.\n\n### Name generation\n\n* If `@[to_additive]` is called without a `name` argument, then the\n new name is autogenerated. First, it takes the longest prefix of\n the source name that is already known to `to_additive`, and replaces\n this prefix with its additive counterpart. Second, it takes the last\n part of the name (i.e., after the last dot), and replaces common\n name parts (“mul”, “one”, “inv”, “prod”) with their additive versions.\n\n* Namespaces can be transformed using `map_namespace`. For example:\n ```\n run_cmd to_additive.map_namespace `quotient_group `quotient_add_group\n ```\n\n Later uses of `to_additive` on declarations in the `quotient_group`\n namespace will be created in the `quotient_add_group` namespaces.\n\n* If `@[to_additive]` is called with a `name` argument `new_name`\n /without a dot/, then `to_additive` updates the prefix as described\n above, then replaces the last part of the name with `new_name`.\n\n* If `@[to_additive]` is called with a `name` argument\n `new_namespace.new_name` /with a dot/, then `to_additive` uses this\n new name as is.\n\nAs a safety check, in the first case `to_additive` double checks\nthat the new name differs from the original one.\n\n-/\n@[user_attribute]\nprotected unsafe def attr : user_attribute Unit ValueType\n where\n Name := `to_additive\n descr := \"Transport multiplicative to additive\"\n parser := parser\n after_set :=\n some fun src prio persistent => do\n guard persistent <|> fail \"`to_additive` can't be used as a local attribute\"\n let env ← get_env\n let val ← attr.get_param src\n let dict ← aux_attr.get_cache\n let ignore ← ignore_args_attr.get_cache\n let relevant ← relevant_arg_attr.get_cache\n let reorder ← reorder_attr.get_cache\n let tgt ← target_name src val.tgt dict val.allowAutoName\n aux_attr src tgt tt\n let dict := dict.insert src tgt\n let first_mult_arg ← first_multiplicative_arg src\n when (first_mult_arg ≠ 1) <| relevant_arg_attr src first_mult_arg tt\n if env tgt then proceed_fields env src tgt prio\n else do\n transform_decl_with_prefix_dict dict val val relevant ignore reorder src tgt\n [`reducible, `_refl_lemma, `simp, `norm_cast, `instance, `refl, `symm, `trans,\n `elab_as_eliminator, `no_rsimp, `continuity, `ext, `ematch, `measurability, `alias,\n `_ext_core, `_ext_lemma_core, `nolint, `protected]\n whenM (has_attribute' `simps src)\n (trace \"Apply the simps attribute after the to_additive attribute\")\n whenM (has_attribute' `mono src)\n (trace <|\n \"to_additive does not work with mono, apply the mono attribute to both\" ++\n \"versions after\")\n match val with\n | some doc => add_doc_string tgt doc\n | none => do\n let some alias_target ← tactic.alias.get_alias_target src |\n skip\n let alias_name := alias_target\n let some add_alias_name ← pure (dict alias_name) |\n skip\n add_doc_string tgt alias_target\n#align to_additive.attr to_additive.attr\n\nadd_tactic_doc\n { Name := \"to_additive\"\n category := DocCategory.attr\n declNames := [`to_additive.attr]\n tags := [\"transport\", \"environment\", \"lemma derivation\"] }\n\nend ToAdditive\n\n-- map operations\nattribute [to_additive] Mul One Inv Div\n\n-- the following types are supported by `@[to_additive]` and mapped to themselves.\nattribute [to_additive Empty] Empty\n\nattribute [to_additive PEmpty] PEmpty\n\nattribute [to_additive PUnit] PUnit\n\nattribute [to_additive Unit] Unit\n\nsection Linter\n\nopen Tactic Expr\n\n/-- A linter that checks that multiplicative and additive lemmas have both doc strings if one of\nthem has one -/\n@[linter]\nunsafe def linter.to_additive_doc : linter\n where\n test d := do\n let mul_name := d.to_name\n let dict ← to_additive.aux_attr.get_cache\n match dict mul_name with\n | some add_name => do\n let mul_doc ← try_core <| doc_string mul_name\n let add_doc ← try_core <| doc_string add_name\n match mul_doc, add_doc with\n | tt, ff =>\n return <|\n some <|\n \"declaration has a docstring, but its additive version `\" ++ add_name ++\n \"` does not. You might want to pass a string argument to \" ++\n \"`to_additive`.\"\n | ff, tt =>\n return <|\n some <|\n \"declaration has no docstring, but its additive version `\" ++ add_name ++\n \"` does. You might want to add a doc string to the declaration.\"\n | _, _ => return none\n | none => return none\n auto_decls := false\n no_errors_found := \"Multiplicative and additive lemmas are consistently documented\"\n errors_found :=\n \"The following declarations have doc strings, but their additive versions do \" ++\n \"not (or vice versa).\"\n is_fast := false\n#align linter.to_additive_doc linter.to_additive_doc\n\nend Linter\n\n", "meta": {"author": "leanprover-community", "repo": "mathlib3port", "sha": "62505aa236c58c8559783b16d33e30df3daa54f4", "save_path": "github-repos/lean/leanprover-community-mathlib3port", "path": "github-repos/lean/leanprover-community-mathlib3port/mathlib3port-62505aa236c58c8559783b16d33e30df3daa54f4/Mathbin/Tactic/ToAdditive.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42632157796989345, "lm_q2_score": 0.07807817050802546, "lm_q1q2_score": 0.03328640885598381}} {"text": "/-\nCopyright (c) 2017 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthor: Leonardo de Moura\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.default\n\nuniverses u l \n\nnamespace Mathlib\n\n/--\nA difference list is a function that, given a list, returns the original\ncontents of the difference list prepended to the given list.\n\nThis structure supports `O(1)` `append` and `concat` operations on lists, making it\nuseful for append-heavy uses such as logging and pretty printing.\n-/\nstructure dlist (α : Type u) where\n apply : List α → List α\n invariant : ∀ (l : List α), apply l = apply [] ++ l\n\nnamespace dlist\n\n\n/-- Convert a list to a dlist -/\ndef of_list {α : Type u} (l : List α) : dlist α := mk (append l) sorry\n\n/-- Convert a lazily-evaluated list to a dlist -/\ndef lazy_of_list {α : Type u} (l : thunk (List α)) : dlist α :=\n mk (fun (xs : List α) => l Unit.unit ++ xs) sorry\n\n/-- Convert a dlist to a list -/\ndef to_list {α : Type u} : dlist α → List α := sorry\n\n/-- Create a dlist containing no elements -/\ndef empty {α : Type u} : dlist α := mk id sorry\n\n/-- Create dlist with a single element -/\ndef singleton {α : Type u} (x : α) : dlist α := mk (List.cons x) sorry\n\n/-- `O(1)` Prepend a single element to a dlist -/\ndef cons {α : Type u} (x : α) : dlist α → dlist α := sorry\n\n/-- `O(1)` Append a single element to a dlist -/\ndef concat {α : Type u} (x : α) : dlist α → dlist α := sorry\n\n/-- `O(1)` Append dlists -/\nprotected def append {α : Type u} : dlist α → dlist α → dlist α := sorry\n\nprotected instance has_append {α : Type u} : Append (dlist α) := { append := dlist.append }\n\ntheorem to_list_of_list {α : Type u} (l : List α) : to_list (of_list l) = l := sorry\n\ntheorem of_list_to_list {α : Type u} (l : dlist α) : of_list (to_list l) = l := sorry\n\ntheorem to_list_empty {α : Type u} : to_list empty = [] := sorry\n\ntheorem to_list_singleton {α : Type u} (x : α) : to_list (singleton x) = [x] := sorry\n\ntheorem to_list_append {α : Type u} (l₁ : dlist α) (l₂ : dlist α) :\n to_list (l₁ ++ l₂) = to_list l₁ ++ to_list l₂ :=\n sorry\n\ntheorem to_list_cons {α : Type u} (x : α) (l : dlist α) : to_list (cons x l) = x :: to_list l :=\n sorry\n\ntheorem to_list_concat {α : Type u} (x : α) (l : dlist α) :\n to_list (concat x l) = to_list l ++ [x] :=\n sorry\n\nend Mathlib", "meta": {"author": "AurelienSaue", "repo": "Mathlib4_auto", "sha": "590df64109b08190abe22358fabc3eae000943f2", "save_path": "github-repos/lean/AurelienSaue-Mathlib4_auto", "path": "github-repos/lean/AurelienSaue-Mathlib4_auto/Mathlib4_auto-590df64109b08190abe22358fabc3eae000943f2/Mathlib/Lean3Lib/data/dlist_auto.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43782349911420193, "lm_q2_score": 0.07585818628900447, "lm_q1q2_score": 0.033212496557508915}} {"text": "/-\nCopyright (c) 2018 Simon Hudon. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthor: Mario Carneiro, Johannes Hölzl, Simon Hudon, Kenny Lau\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.default\nimport Mathlib.data.multiset.basic\nimport Mathlib.control.traversable.lemmas\nimport Mathlib.control.traversable.instances\nimport Mathlib.PostPort\n\nuniverses u_1 u u_2 \n\nnamespace Mathlib\n\n/-!\n# Functoriality of `multiset`.\n-/\n\nnamespace multiset\n\n\nprotected instance functor : Functor multiset :=\n { map := map, mapConst := fun (α β : Type u_1) => map ∘ function.const β }\n\n@[simp] theorem fmap_def {α' : Type u_1} {β' : Type u_1} {s : multiset α'} (f : α' → β') : f <$> s = map f s :=\n rfl\n\nprotected instance is_lawful_functor : is_lawful_functor multiset := sorry\n\ndef traverse {F : Type u → Type u} [Applicative F] [is_comm_applicative F] {α' : Type u} {β' : Type u} (f : α' → F β') : multiset α' → F (multiset β') :=\n quotient.lift (Functor.map coe ∘ traverse f) sorry\n\nprotected instance monad : Monad multiset :=\n { toApplicative :=\n { toFunctor := { map := Functor.map, mapConst := Functor.mapConst },\n toPure := { pure := fun (α : Type u_1) (x : α) => x ::ₘ 0 },\n toSeq :=\n { seq := fun (α β : Type u_1) (f : multiset (α → β)) (x : multiset α) => bind f fun (_x : α → β) => map _x x },\n toSeqLeft :=\n { seqLeft :=\n fun (α β : Type u_1) (a : multiset α) (b : multiset β) =>\n (fun (α β : Type u_1) (f : multiset (α → β)) (x : multiset α) => bind f fun (_x : α → β) => map _x x) β α\n (map (function.const β) a) b },\n toSeqRight :=\n { seqRight :=\n fun (α β : Type u_1) (a : multiset α) (b : multiset β) =>\n (fun (α β : Type u_1) (f : multiset (α → β)) (x : multiset α) => bind f fun (_x : α → β) => map _x x) β β\n (map (function.const α id) a) b } },\n toBind := { bind := bind } }\n\n@[simp] theorem pure_def {α : Type u_1} : pure = fun (x : α) => x ::ₘ 0 :=\n rfl\n\n@[simp] theorem bind_def {α : Type u_1} {β : Type u_1} : bind = bind :=\n rfl\n\nprotected instance is_lawful_monad : is_lawful_monad multiset := sorry\n\n@[simp] theorem lift_beta {α : Type u_1} {β : Type u_2} (x : List α) (f : List α → β) (h : ∀ (a b : List α), a ≈ b → f a = f b) : quotient.lift f h ↑x = f x :=\n quotient.lift_beta f h x\n\n@[simp] theorem map_comp_coe {α : Type u_1} {β : Type u_1} (h : α → β) : Functor.map h ∘ coe = coe ∘ Functor.map h := sorry\n\ntheorem id_traverse {α : Type u_1} (x : multiset α) : traverse id.mk x = x := sorry\n\ntheorem comp_traverse {G : Type u_1 → Type u_1} {H : Type u_1 → Type u_1} [Applicative G] [Applicative H] [is_comm_applicative G] [is_comm_applicative H] {α : Type u_1} {β : Type u_1} {γ : Type u_1} (g : α → G β) (h : β → H γ) (x : multiset α) : traverse (functor.comp.mk ∘ Functor.map h ∘ g) x = functor.comp.mk (traverse h <$> traverse g x) := sorry\n\ntheorem map_traverse {G : Type u_1 → Type u_1} [Applicative G] [is_comm_applicative G] {α : Type u_1} {β : Type u_1} {γ : Type u_1} (g : α → G β) (h : β → γ) (x : multiset α) : Functor.map h <$> traverse g x = traverse (Functor.map h ∘ g) x := sorry\n\ntheorem traverse_map {G : Type u_1 → Type u_1} [Applicative G] [is_comm_applicative G] {α : Type u_1} {β : Type u_1} {γ : Type u_1} (g : α → β) (h : β → G γ) (x : multiset α) : traverse h (map g x) = traverse (h ∘ g) x := sorry\n\ntheorem naturality {G : Type u_1 → Type u_1} {H : Type u_1 → Type u_1} [Applicative G] [Applicative H] [is_comm_applicative G] [is_comm_applicative H] (eta : applicative_transformation G H) {α : Type u_1} {β : Type u_1} (f : α → G β) (x : multiset α) : coe_fn eta (multiset β) (traverse f x) = traverse (coe_fn eta β ∘ f) x := sorry\n\n", "meta": {"author": "AurelienSaue", "repo": "Mathlib4_auto", "sha": "590df64109b08190abe22358fabc3eae000943f2", "save_path": "github-repos/lean/AurelienSaue-Mathlib4_auto", "path": "github-repos/lean/AurelienSaue-Mathlib4_auto/Mathlib4_auto-590df64109b08190abe22358fabc3eae000943f2/Mathlib/data/multiset/functor.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4571367168274948, "lm_q2_score": 0.07263670736453835, "lm_q1q2_score": 0.033204905925784574}} {"text": "/-\nCopyright (c) 2017 Mario Carneiro. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Mario Carneiro, Yury Kudryashov.\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.default\nimport Mathlib.tactic.transform_decl\nimport Mathlib.tactic.algebra\nimport Mathlib.PostPort\n\nuniverses l \n\nnamespace Mathlib\n\n/-!\n# Transport multiplicative to additive\n\nThis file defines an attribute `to_additive` that can be used to\nautomatically transport theorems and definitions (but not inductive\ntypes and structures) from a multiplicative theory to an additive theory.\n\nUsage information is contained in the doc string of `to_additive.attr`.\n\n### Missing features\n\n* Automatically transport structures and other inductive types.\n\n* For structures, automatically generate theorems like `group α ↔\n add_group (additive α)`.\n\n* Rewrite rules for the last part of the name that work in more\n cases. E.g., we can replace `monoid` with `add_monoid` etc.\n-/\n\nnamespace to_additive\n\n\n/-- An auxiliary attribute used to store the names of the additive versions of declarations\nthat have been processed by `to_additive`. -/\n/-- A command that can be used to have future uses of `to_additive` change the `src` namespace\nto the `tgt` namespace.\n\nFor example:\n```\nrun_cmd to_additive.map_namespace `quotient_group `quotient_add_group\n```\n\nLater uses of `to_additive` on declarations in the `quotient_group` namespace will be created\nin the `quotient_add_group` namespaces.\n-/\n/-- `value_type` is the type of the arguments that can be provided to `to_additive`.\n`to_additive.parser` parses the provided arguments into `name` for the target and an\noptional doc string. -/\nstructure value_type where\n tgt : name\n doc : Option string\n\n/-- `add_comm_prefix x s` returns `\"comm_\" ++ s` if `x = tt` and `s` otherwise. -/\n/-- Dictionary used by `to_additive.guess_name` to autogenerate names. -/\n/-- Autogenerate target name for `to_additive`. -/\n/-- Return the provided target name or autogenerate one if one was not provided. -/\n/-- the parser for the arguments to `to_additive` -/\n/-- Add the `aux_attr` attribute to the structure fields of `src`\nso that future uses of `to_additive` will map them to the corresponding `tgt` fields. -/\n/--\nThe attribute `to_additive` can be used to automatically transport theorems\nand definitions (but not inductive types and structures) from a multiplicative\ntheory to an additive theory.\n\nTo use this attribute, just write:\n\n```\n@[to_additive]\ntheorem mul_comm' {α} [comm_semigroup α] (x y : α) : x * y = y * x := comm_semigroup.mul_comm\n```\n\nThis code will generate a theorem named `add_comm'`. It is also\npossible to manually specify the name of the new declaration, and\nprovide a documentation string:\n\n```\n@[to_additive add_foo \"add_foo doc string\"]\n/-- foo doc string -/\nend Mathlib", "meta": {"author": "AurelienSaue", "repo": "Mathlib4_auto", "sha": "590df64109b08190abe22358fabc3eae000943f2", "save_path": "github-repos/lean/AurelienSaue-Mathlib4_auto", "path": "github-repos/lean/AurelienSaue-Mathlib4_auto/Mathlib4_auto-590df64109b08190abe22358fabc3eae000943f2/Mathlib/algebra/group/to_additive_auto.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.36658973632215985, "lm_q2_score": 0.09009298418962222, "lm_q1q2_score": 0.03302716331855013}} {"text": "/-\nCopyright (c) 2017 Johannes Hölzl. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Johannes Hölzl\n\nBinder elimination\n-/\nimport order.complete_lattice\n\nnamespace old_conv\nopen tactic monad\n\nmeta instance : monad_fail old_conv :=\n{ fail := λ α s, (λr e, tactic.fail (to_fmt s) : old_conv α), ..old_conv.monad }\n\nmeta instance : has_monad_lift tactic old_conv :=\n⟨λα, lift_tactic⟩\n\nmeta instance (α : Type) : has_coe (tactic α) (old_conv α) :=\n⟨monad_lift⟩\n\nmeta def current_relation : old_conv name := λr lhs, return ⟨r, lhs, none⟩\n\nmeta def head_beta : old_conv unit :=\nλ r e, do n ← tactic.head_beta e, return ⟨(), n, none⟩\n\n/- congr should forward data! -/\nmeta def congr_arg : old_conv unit → old_conv unit := congr_core (return ())\nmeta def congr_fun : old_conv unit → old_conv unit := λc, congr_core c (return ())\n\nmeta def congr_rule (congr : expr) (cs : list (list expr → old_conv unit)) :\n old_conv unit :=\nλr lhs, do\n meta_rhs ← infer_type lhs >>= mk_meta_var, -- is maybe overly restricted for `heq`\n t ← mk_app r [lhs, meta_rhs],\n ((), meta_pr) ← solve_aux t (do\n apply congr,\n focus $ cs.map $ λc, (do\n xs ← intros,\n conversion (head_beta >> c xs)),\n done),\n rhs ← instantiate_mvars meta_rhs,\n pr ← instantiate_mvars meta_pr,\n return ⟨(), rhs, some pr⟩\n\nmeta def congr_binder (congr : name) (cs : expr → old_conv unit) : old_conv unit := do\n e ← mk_const congr,\n congr_rule e [λbs, do [b] ← return bs, cs b]\n\nmeta def funext' : (expr → old_conv unit) → old_conv unit := congr_binder ``_root_.funext\n\nmeta def propext' {α : Type} (c : old_conv α) : old_conv α := λr lhs, (do\n guard (r = `iff),\n c r lhs)\n<|> (do\n guard (r = `eq),\n ⟨res, rhs, pr⟩ ← c `iff lhs,\n match pr with\n | some pr := return ⟨res, rhs, (expr.const `propext [] : expr) lhs rhs pr⟩\n | none := return ⟨res, rhs, none⟩\n end)\n\nmeta def apply (pr : expr) : old_conv unit :=\nλ r e, do\n sl ← simp_lemmas.mk.add pr,\n apply_lemmas sl r e\n\nmeta def applyc (n : name) : old_conv unit :=\nλ r e, do\n sl ← simp_lemmas.mk.add_simp n,\n apply_lemmas sl r e\n\nmeta def apply' (n : name) : old_conv unit := do\n e ← mk_const n,\n congr_rule e []\n\nend old_conv\n\nopen expr tactic old_conv\n\n/- Binder elimination:\n\nWe assume a binder `B : p → Π (α : Sort u), (α → t) → t`, where `t` is a type depending on `p`.\nExamples:\n ∃: there is no `p` and `t` is `Prop`.\n ⨅, ⨆: here p is `β` and `[complete_lattice β]`, `p` is `β`\n\nProblem: ∀x, _ should be a binder, but is not a constant!\n\nProvide a mechanism to rewrite:\n\n B (x : α) ..x.. (h : x = t), p x = B ..x/t.., p t\n\nHere ..x.. are binders, maybe also some constants which provide commutativity rules with `B`.\n\n-/\n\nmeta structure binder_eq_elim :=\n(match_binder : expr → tactic (expr × expr)) -- returns the bound type and body\n(adapt_rel : old_conv unit → old_conv unit) -- optionally adapt `eq` to `iff`\n(apply_comm : old_conv unit) -- apply commutativity rule\n(apply_congr : (expr → old_conv unit) → old_conv unit) -- apply congruence rule\n(apply_elim_eq : old_conv unit) -- (B (x : β) (h : x = t), s x) = s t\n\nmeta def binder_eq_elim.check_eq (b : binder_eq_elim) (x : expr) : expr → tactic unit\n| `(@eq %%β %%l %%r) := guard ((l = x ∧ ¬ x.occurs r) ∨ (r = x ∧ ¬ x.occurs l))\n| _ := fail \"no match\"\n\nmeta def binder_eq_elim.pull (b : binder_eq_elim) (x : expr) : old_conv unit := do\n (β, f) ← lhs >>= (lift_tactic ∘ b.match_binder),\n guard (¬ x.occurs β)\n <|> b.check_eq x β\n <|> (do\n b.apply_congr $ λx, binder_eq_elim.pull,\n b.apply_comm)\n\nmeta def binder_eq_elim.push (b : binder_eq_elim) : old_conv unit :=\n b.apply_elim_eq\n<|> (do\n b.apply_comm,\n b.apply_congr $ λx, binder_eq_elim.push)\n<|> (do\n b.apply_congr $ b.pull,\n binder_eq_elim.push)\n\nmeta def binder_eq_elim.check (b : binder_eq_elim) (x : expr) : expr → tactic unit\n| e := do\n (β, f) ← b.match_binder e,\n b.check_eq x β\n <|> (do\n (lam n bi d bd) ← return f,\n x ← mk_local' n bi d,\n binder_eq_elim.check $ bd.instantiate_var x)\n\nmeta def binder_eq_elim.old_conv (b : binder_eq_elim) : old_conv unit := do\n (β, f) ← lhs >>= (lift_tactic ∘ b.match_binder),\n (lam n bi d bd) ← return f,\n x ← mk_local' n bi d,\n b.check x (bd.instantiate_var x),\n b.adapt_rel b.push\n\ntheorem {u v} exists_elim_eq_left {α : Sort u} (a : α) (p : Π(a':α), a' = a → Prop) :\n (∃(a':α)(h : a' = a), p a' h) ↔ p a rfl :=\n⟨λ⟨a', ⟨h, p_h⟩⟩, match a', h, p_h with ._, rfl, h := h end, λh, ⟨a, rfl, h⟩⟩\n\ntheorem {u v} exists_elim_eq_right {α : Sort u} (a : α) (p : Π(a':α), a = a' → Prop) :\n (∃(a':α)(h : a = a'), p a' h) ↔ p a rfl :=\n⟨λ⟨a', ⟨h, p_h⟩⟩, match a', h, p_h with ._, rfl, h := h end, λh, ⟨a, rfl, h⟩⟩\n\nmeta def exists_eq_elim : binder_eq_elim :=\n{ match_binder := λe, (do `(@Exists %%β %%f) ← return e, return (β, f)),\n adapt_rel := propext',\n apply_comm := applyc ``exists_comm,\n apply_congr := congr_binder ``exists_congr,\n apply_elim_eq := apply' ``exists_elim_eq_left <|> apply' ``exists_elim_eq_right }\n\ntheorem {u v} forall_comm {α : Sort u} {β : Sort v} (p : α → β → Prop) :\n (∀a b, p a b) ↔ (∀b a, p a b) :=\n⟨assume h b a, h a b, assume h b a, h a b⟩\n\ntheorem {u v} forall_elim_eq_left {α : Sort u} (a : α) (p : Π(a':α), a' = a → Prop) :\n (∀(a':α)(h : a' = a), p a' h) ↔ p a rfl :=\n⟨λh, h a rfl, λh a' h_eq, match a', h_eq with ._, rfl := h end⟩\n\ntheorem {u v} forall_elim_eq_right {α : Sort u} (a : α) (p : Π(a':α), a = a' → Prop) :\n (∀(a':α)(h : a = a'), p a' h) ↔ p a rfl :=\n⟨λh, h a rfl, λh a' h_eq, match a', h_eq with ._, rfl := h end⟩\n\nmeta def forall_eq_elim : binder_eq_elim :=\n{ match_binder := λe, (do (expr.pi n bi d bd) ← return e, return (d, expr.lam n bi d bd)),\n adapt_rel := propext',\n apply_comm := applyc ``forall_comm,\n apply_congr := congr_binder ``forall_congr,\n apply_elim_eq := apply' ``forall_elim_eq_left <|> apply' ``forall_elim_eq_right }\n\nmeta def supr_eq_elim : binder_eq_elim :=\n{ match_binder := λe, (do `(@supr %%α %%cl %%β %%f) ← return e, return (β, f)),\n adapt_rel := λc, (do r ← current_relation, guard (r = `eq), c),\n apply_comm := applyc ``supr_comm,\n apply_congr := congr_arg ∘ funext',\n apply_elim_eq := applyc ``supr_supr_eq_left <|> applyc ``supr_supr_eq_right }\n\nmeta def infi_eq_elim : binder_eq_elim :=\n{ match_binder := λe, (do `(@infi %%α %%cl %%β %%f) ← return e, return (β, f)),\n adapt_rel := λc, (do r ← current_relation, guard (r = `eq), c),\n apply_comm := applyc ``infi_comm,\n apply_congr := congr_arg ∘ funext',\n apply_elim_eq := applyc ``infi_infi_eq_left <|> applyc ``infi_infi_eq_right }\n\n\nuniverses u v w w₂\nvariables {α : Type u} {β : Type v} {ι : Sort w} {ι₂ : Sort w₂} {s t : set α} {a : α}\n\nsection\nvariables [complete_lattice α]\n\nexample {s : set β} {f : β → α} : Inf (set.image f s) = (⨅ a ∈ s, f a) :=\nbegin\n simp [Inf_eq_infi, infi_and],\n conversion infi_eq_elim.old_conv,\nend\n\nexample {s : set β} {f : β → α} : Sup (set.image f s) = (⨆ a ∈ s, f a) :=\nbegin\n simp [Sup_eq_supr, supr_and],\n conversion supr_eq_elim.old_conv,\nend\n\nend\n", "meta": {"author": "leanprover-community", "repo": "mathlib", "sha": "5e526d18cea33550268dcbbddcb822d5cde40654", "save_path": "github-repos/lean/leanprover-community-mathlib", "path": "github-repos/lean/leanprover-community-mathlib/mathlib-5e526d18cea33550268dcbbddcb822d5cde40654/src/tactic/converter/binders.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091946, "lm_q2_score": 0.06656919591493472, "lm_q1q2_score": 0.03302456732623985}} {"text": "variables {p q : Prop} (hp : p) (hq : q)\n\ninclude hp hq\n\nexample : p ∧ q ∧ p :=\nbegin\n apply and.intro hp,\n exact and.intro hq hp\nend\n", "meta": {"author": "Ailrun", "repo": "Theorem_Proving_in_Lean", "sha": "2eb1b5caf93c6a5a555c79e9097cf2ba5a66cf68", "save_path": "github-repos/lean/Ailrun-Theorem_Proving_in_Lean", "path": "github-repos/lean/Ailrun-Theorem_Proving_in_Lean/Theorem_Proving_in_Lean-2eb1b5caf93c6a5a555c79e9097cf2ba5a66cf68/src/ch5/ex0108.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.06754669395523943, "lm_q1q2_score": 0.03298192906547294}} {"text": "/-\nCopyright (c) 2017 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Leonardo de Moura\n-/\nprelude\nimport Init.Data.Option.Basic\n\nuniverse u v\n\ntheorem Option.eq_of_eq_some {α : Type u} : ∀ {x y : Option α}, (∀z, x = some z ↔ y = some z) → x = y\n | none, none, _ => rfl\n | none, some z, h => Option.noConfusion ((h z).2 rfl)\n | some z, none, h => Option.noConfusion ((h z).1 rfl)\n | some _, some w, h => Option.noConfusion ((h w).2 rfl) (congrArg some)\n\ntheorem Option.eq_none_of_isNone {α : Type u} : ∀ {o : Option α}, o.isNone → o = none\n | none, _ => rfl\n", "meta": {"author": "leanprover", "repo": "lean4", "sha": "742d053a97bdd109a41a921facd1cd6a55e89bc7", "save_path": "github-repos/lean/leanprover-lean4", "path": "github-repos/lean/leanprover-lean4/lean4-742d053a97bdd109a41a921facd1cd6a55e89bc7/src/Init/Data/Option/Instances.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958346, "lm_q2_score": 0.06754668691621382, "lm_q1q2_score": 0.03298192562843361}} {"text": "/-\nCopyright (c) 2017 Johannes Hölzl. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Johannes Hölzl, Mario Carneiro\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.default\nimport Mathlib.data.equiv.basic\nimport Mathlib.data.sigma.basic\nimport Mathlib.algebra.group.defs\nimport Mathlib.PostPort\n\nuniverses u_1 u_2 l u v u_3 w x u_4 \n\nnamespace Mathlib\n\n/-!\n# Injective functions\n-/\n\nnamespace function\n\n\n/-- `α ↪ β` is a bundled injective function. -/\nstructure embedding (α : Sort u_1) (β : Sort u_2) \nwhere\n to_fun : α → β\n inj' : injective to_fun\n\ninfixr:25 \" ↪ \" => Mathlib.function.embedding\n\nprotected instance embedding.has_coe_to_fun {α : Sort u} {β : Sort v} : has_coe_to_fun (α ↪ β) :=\n has_coe_to_fun.mk (fun (x : α ↪ β) => α → β) embedding.to_fun\n\nend function\n\n\n/-- Convert an `α ≃ β` to `α ↪ β`. -/\n@[simp] theorem equiv.to_embedding_apply {α : Sort u} {β : Sort v} (f : α ≃ β) : ∀ (ᾰ : α), coe_fn (equiv.to_embedding f) ᾰ = coe_fn f ᾰ :=\n fun (ᾰ : α) => Eq.refl (coe_fn (equiv.to_embedding f) ᾰ)\n\nnamespace function\n\n\nnamespace embedding\n\n\ntheorem ext {α : Sort u_1} {β : Sort u_2} {f : α ↪ β} {g : α ↪ β} (h : ∀ (x : α), coe_fn f x = coe_fn g x) : f = g := sorry\n\ntheorem ext_iff {α : Sort u_1} {β : Sort u_2} {f : α ↪ β} {g : α ↪ β} : (∀ (x : α), coe_fn f x = coe_fn g x) ↔ f = g := sorry\n\n@[simp] theorem to_fun_eq_coe {α : Sort u_1} {β : Sort u_2} (f : α ↪ β) : to_fun f = ⇑f :=\n rfl\n\n@[simp] theorem coe_fn_mk {α : Sort u_1} {β : Sort u_2} (f : α → β) (i : injective f) : ⇑(mk f i) = f :=\n rfl\n\ntheorem injective {α : Sort u_1} {β : Sort u_2} (f : α ↪ β) : injective ⇑f :=\n inj' f\n\n@[simp] theorem refl_apply (α : Sort u_1) (a : α) : coe_fn (embedding.refl α) a = a :=\n Eq.refl a\n\n@[simp] theorem trans_apply {α : Sort u_1} {β : Sort u_2} {γ : Sort u_3} (f : α ↪ β) (g : β ↪ γ) : ∀ (ᾰ : α), coe_fn (embedding.trans f g) ᾰ = coe_fn g (coe_fn f ᾰ) :=\n fun (ᾰ : α) => Eq.refl (coe_fn g (coe_fn f ᾰ))\n\n@[simp] theorem equiv_to_embedding_trans_symm_to_embedding {α : Sort u_1} {β : Sort u_2} (e : α ≃ β) : embedding.trans (equiv.to_embedding e) (equiv.to_embedding (equiv.symm e)) = embedding.refl α := sorry\n\n@[simp] theorem equiv_symm_to_embedding_trans_to_embedding {α : Sort u_1} {β : Sort u_2} (e : α ≃ β) : embedding.trans (equiv.to_embedding (equiv.symm e)) (equiv.to_embedding e) = embedding.refl β := sorry\n\nprotected def congr {α : Sort u} {β : Sort v} {γ : Sort w} {δ : Sort x} (e₁ : α ≃ β) (e₂ : γ ≃ δ) (f : α ↪ γ) : β ↪ δ :=\n embedding.trans (equiv.to_embedding (equiv.symm e₁)) (embedding.trans f (equiv.to_embedding e₂))\n\n/-- A right inverse `surj_inv` of a surjective function as an `embedding`. -/\nprotected def of_surjective {α : Sort u_1} {β : Sort u_2} (f : β → α) (hf : surjective f) : α ↪ β :=\n mk (surj_inv hf) (injective_surj_inv hf)\n\n/-- Convert a surjective `embedding` to an `equiv` -/\nprotected def equiv_of_surjective {α : Sort u_1} {β : Type u_2} (f : α ↪ β) (hf : surjective ⇑f) : α ≃ β :=\n equiv.of_bijective ⇑f sorry\n\nprotected def of_not_nonempty {α : Sort u_1} {β : Sort u_2} (hα : ¬Nonempty α) : α ↪ β :=\n mk (fun (a : α) => false.elim sorry) sorry\n\n/-- Change the value of an embedding `f` at one point. If the prescribed image\nis already occupied by some `f a'`, then swap the values at these two points. -/\ndef set_value {α : Sort u_1} {β : Sort u_2} (f : α ↪ β) (a : α) (b : β) [(a' : α) → Decidable (a' = a)] [(a' : α) → Decidable (coe_fn f a' = b)] : α ↪ β :=\n mk (fun (a' : α) => ite (a' = a) b (ite (coe_fn f a' = b) (coe_fn f a) (coe_fn f a'))) sorry\n\ntheorem set_value_eq {α : Sort u_1} {β : Sort u_2} (f : α ↪ β) (a : α) (b : β) [(a' : α) → Decidable (a' = a)] [(a' : α) → Decidable (coe_fn f a' = b)] : coe_fn (set_value f a b) a = b := sorry\n\n/-- Embedding into `option` -/\nprotected def some {α : Type u_1} : α ↪ Option α :=\n mk some (option.some_injective α)\n\n/-- Embedding of a `subtype`. -/\ndef subtype {α : Sort u_1} (p : α → Prop) : Subtype p ↪ α :=\n mk coe sorry\n\n@[simp] theorem coe_subtype {α : Sort u_1} (p : α → Prop) : ⇑(subtype p) = coe :=\n rfl\n\n/-- Choosing an element `b : β` gives an embedding of `punit` into `β`. -/\ndef punit {β : Sort u_1} (b : β) : PUnit ↪ β :=\n mk (fun (_x : PUnit) => b) sorry\n\n/-- Fixing an element `b : β` gives an embedding `α ↪ α × β`. -/\ndef sectl (α : Type u_1) {β : Type u_2} (b : β) : α ↪ α × β :=\n mk (fun (a : α) => (a, b)) sorry\n\n/-- Fixing an element `a : α` gives an embedding `β ↪ α × β`. -/\ndef sectr {α : Type u_1} (a : α) (β : Type u_2) : β ↪ α × β :=\n mk (fun (b : β) => (a, b)) sorry\n\n/-- Restrict the codomain of an embedding. -/\ndef cod_restrict {α : Sort u_1} {β : Type u_2} (p : set β) (f : α ↪ β) (H : ∀ (a : α), coe_fn f a ∈ p) : α ↪ ↥p :=\n mk (fun (a : α) => { val := coe_fn f a, property := H a }) sorry\n\n@[simp] theorem cod_restrict_apply {α : Sort u_1} {β : Type u_2} (p : set β) (f : α ↪ β) (H : ∀ (a : α), coe_fn f a ∈ p) (a : α) : coe_fn (cod_restrict p f H) a = { val := coe_fn f a, property := H a } :=\n rfl\n\n/-- If `e₁` and `e₂` are embeddings, then so is `prod.map e₁ e₂ : (a, b) ↦ (e₁ a, e₂ b)`. -/\ndef prod_map {α : Type u_1} {β : Type u_2} {γ : Type u_3} {δ : Type u_4} (e₁ : α ↪ β) (e₂ : γ ↪ δ) : α × γ ↪ β × δ :=\n mk (prod.map ⇑e₁ ⇑e₂) sorry\n\n@[simp] theorem coe_prod_map {α : Type u_1} {β : Type u_2} {γ : Type u_3} {δ : Type u_4} (e₁ : α ↪ β) (e₂ : γ ↪ δ) : ⇑(prod_map e₁ e₂) = prod.map ⇑e₁ ⇑e₂ :=\n rfl\n\n/-- If `e₁` and `e₂` are embeddings, then so is `sum.map e₁ e₂`. -/\ndef sum_map {α : Type u_1} {β : Type u_2} {γ : Type u_3} {δ : Type u_4} (e₁ : α ↪ β) (e₂ : γ ↪ δ) : α ⊕ γ ↪ β ⊕ δ :=\n mk (sum.map ⇑e₁ ⇑e₂) sorry\n\n@[simp] theorem coe_sum_map {α : Type u_1} {β : Type u_2} {γ : Type u_3} {δ : Type u_4} (e₁ : α ↪ β) (e₂ : γ ↪ δ) : ⇑(sum_map e₁ e₂) = sum.map ⇑e₁ ⇑e₂ :=\n rfl\n\n/-- The embedding of `α` into the sum `α ⊕ β`. -/\n@[simp] theorem inl_apply {α : Type u_1} {β : Type u_2} (val : α) : coe_fn inl val = sum.inl val :=\n Eq.refl (coe_fn inl val)\n\n/-- The embedding of `β` into the sum `α ⊕ β`. -/\n@[simp] theorem inr_apply {α : Type u_1} {β : Type u_2} (val : β) : coe_fn inr val = sum.inr val :=\n Eq.refl (coe_fn inr val)\n\n/-- `sigma.mk` as an `function.embedding`. -/\n@[simp] theorem sigma_mk_apply {α : Type u_1} {β : α → Type u_3} (a : α) (snd : β a) : coe_fn (sigma_mk a) snd = sigma.mk a snd :=\n Eq.refl (coe_fn (sigma_mk a) snd)\n\n/-- If `f : α ↪ α'` is an embedding and `g : Π a, β α ↪ β' (f α)` is a family\nof embeddings, then `sigma.map f g` is an embedding. -/\n@[simp] theorem sigma_map_apply {α : Type u_1} {α' : Type u_2} {β : α → Type u_3} {β' : α' → Type u_4} (f : α ↪ α') (g : (a : α) → β a ↪ β' (coe_fn f a)) (x : sigma fun (a : α) => β a) : coe_fn (sigma_map f g) x = sigma.map (⇑f) (fun (a : α) => ⇑(g a)) x :=\n Eq.refl (coe_fn (sigma_map f g) x)\n\ndef Pi_congr_right {α : Sort u_1} {β : α → Sort u_2} {γ : α → Sort u_3} (e : (a : α) → β a ↪ γ a) : ((a : α) → β a) ↪ (a : α) → γ a :=\n mk (fun (f : (a : α) → β a) (a : α) => coe_fn (e a) (f a)) sorry\n\ndef arrow_congr_left {α : Sort u} {β : Sort v} {γ : Sort w} (e : α ↪ β) : (γ → α) ↪ γ → β :=\n Pi_congr_right fun (_x : γ) => e\n\ndef arrow_congr_right {α : Sort u} {β : Sort v} {γ : Sort w} [Inhabited γ] (e : α ↪ β) : (α → γ) ↪ β → γ :=\n let f' : (α → γ) → β → γ :=\n fun (f : α → γ) (b : β) =>\n dite (∃ (c : α), coe_fn e c = b) (fun (h : ∃ (c : α), coe_fn e c = b) => f (classical.some h))\n fun (h : ¬∃ (c : α), coe_fn e c = b) => Inhabited.default;\n mk f' sorry\n\nprotected def subtype_map {α : Sort u_1} {β : Sort u_2} {p : α → Prop} {q : β → Prop} (f : α ↪ β) (h : ∀ {x : α}, p x → q (coe_fn f x)) : (Subtype fun (x : α) => p x) ↪ Subtype fun (y : β) => q y :=\n mk (subtype.map (⇑f) h) sorry\n\n/-- `set.image` as an embedding `set α ↪ set β`. -/\nprotected def image {α : Type u_1} {β : Type u_2} (f : α ↪ β) : set α ↪ set β :=\n mk (set.image ⇑f) sorry\n\ntheorem swap_apply {α : Type u_1} {β : Type u_2} [DecidableEq α] [DecidableEq β] (f : α ↪ β) (x : α) (y : α) (z : α) : coe_fn (equiv.swap (coe_fn f x) (coe_fn f y)) (coe_fn f z) = coe_fn f (coe_fn (equiv.swap x y) z) :=\n injective.swap_apply (injective f) x y z\n\ntheorem swap_comp {α : Type u_1} {β : Type u_2} [DecidableEq α] [DecidableEq β] (f : α ↪ β) (x : α) (y : α) : ⇑(equiv.swap (coe_fn f x) (coe_fn f y)) ∘ ⇑f = ⇑f ∘ ⇑(equiv.swap x y) :=\n injective.swap_comp (injective f) x y\n\nend embedding\n\n\nend function\n\n\nnamespace equiv\n\n\n@[simp] theorem refl_to_embedding {α : Type u_1} : equiv.to_embedding (equiv.refl α) = function.embedding.refl α :=\n rfl\n\n@[simp] theorem trans_to_embedding {α : Type u_1} {β : Type u_2} {γ : Type u_3} (e : α ≃ β) (f : β ≃ γ) : equiv.to_embedding (equiv.trans e f) = function.embedding.trans (equiv.to_embedding e) (equiv.to_embedding f) :=\n rfl\n\nend equiv\n\n\nnamespace set\n\n\n/-- The injection map is an embedding between subsets. -/\ndef embedding_of_subset {α : Type u_1} (s : set α) (t : set α) (h : s ⊆ t) : ↥s ↪ ↥t :=\n function.embedding.mk (fun (x : ↥s) => { val := subtype.val x, property := sorry }) sorry\n\nend set\n\n\n-- TODO: these two definitions probably belong somewhere else, so that we can remove the\n\n-- `algebra.group.defs` import.\n\n/--\nThe embedding of a left cancellative semigroup into itself\nby left multiplication by a fixed element.\n -/\n@[simp] theorem add_left_embedding_apply {G : Type u} [add_left_cancel_semigroup G] (g : G) (h : G) : coe_fn (add_left_embedding g) h = g + h :=\n Eq.refl (coe_fn (add_left_embedding g) h)\n\n/--\nThe embedding of a right cancellative semigroup into itself\nby right multiplication by a fixed element.\n -/\ndef mul_right_embedding {G : Type u} [right_cancel_semigroup G] (g : G) : G ↪ G :=\n function.embedding.mk (fun (h : G) => h * g) (mul_left_injective g)\n\n", "meta": {"author": "AurelienSaue", "repo": "Mathlib4_auto", "sha": "590df64109b08190abe22358fabc3eae000943f2", "save_path": "github-repos/lean/AurelienSaue-Mathlib4_auto", "path": "github-repos/lean/AurelienSaue-Mathlib4_auto/Mathlib4_auto-590df64109b08190abe22358fabc3eae000943f2/Mathlib/logic/embedding.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.06754668503914044, "lm_q1q2_score": 0.03298192471188985}} {"text": "/-\nCopyright (c) 2018 Simon Hudon. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Simon Hudon\n\nTraversable instance for lazy_lists.\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.default\nimport Mathlib.control.traversable.equiv\nimport Mathlib.control.traversable.instances\nimport Mathlib.Lean3Lib.data.lazy_list\nimport Mathlib.PostPort\n\nuniverses u_1 u u_2 u_3 \n\nnamespace Mathlib\n\n/-!\n## Definitions on lazy lists\n\nThis file contains various definitions and proofs on lazy lists.\n\nTODO: move the `lazy_list.lean` file from core to mathlib.\n-/\n\nnamespace thunk\n\n\n/-- Creates a thunk with a (non-lazy) constant value. -/\ndef mk {α : Type u_1} (x : α) : thunk α :=\n fun (_x : Unit) => x\n\nprotected instance decidable_eq {α : Type u} [DecidableEq α] : DecidableEq (thunk α) :=\n sorry\n\nend thunk\n\n\nnamespace lazy_list\n\n\n/-- Isomorphism between strict and lazy lists. -/\ndef list_equiv_lazy_list (α : Type u_1) : List α ≃ lazy_list α :=\n equiv.mk of_list to_list sorry sorry\n\nprotected instance inhabited {α : Type u} : Inhabited (lazy_list α) :=\n { default := nil }\n\nprotected instance decidable_eq {α : Type u} [DecidableEq α] : DecidableEq (lazy_list α) :=\n sorry\n\n/-- Traversal of lazy lists using an applicative effect. -/\nprotected def traverse {m : Type u → Type u} [Applicative m] {α : Type u} {β : Type u} (f : α → m β) : lazy_list α → m (lazy_list β) :=\n sorry\n\nprotected instance traversable : traversable lazy_list :=\n traversable.mk lazy_list.traverse\n\nprotected instance is_lawful_traversable : is_lawful_traversable lazy_list :=\n equiv.is_lawful_traversable' list_equiv_lazy_list sorry sorry sorry\n\n/-- `init xs`, if `xs` non-empty, drops the last element of the list.\nOtherwise, return the empty list. -/\ndef init {α : Type u_1} : lazy_list α → lazy_list α :=\n sorry\n\n/-- Return the first object contained in the list that satisfies\npredicate `p` -/\ndef find {α : Type u_1} (p : α → Prop) [decidable_pred p] : lazy_list α → Option α :=\n sorry\n\n/-- `interleave xs ys` creates a list where elements of `xs` and `ys` alternate. -/\ndef interleave {α : Type u_1} : lazy_list α → lazy_list α → lazy_list α :=\n sorry\n\n/-- `interleave_all (xs::ys::zs::xss)` creates a list where elements of `xs`, `ys`\nand `zs` and the rest alternate. Every other element of the resulting list is taken from\n`xs`, every fourth is taken from `ys`, every eighth is taken from `zs` and so on. -/\ndef interleave_all {α : Type u_1} : List (lazy_list α) → lazy_list α :=\n sorry\n\n/-- Monadic bind operation for `lazy_list`. -/\nprotected def bind {α : Type u_1} {β : Type u_2} : lazy_list α → (α → lazy_list β) → lazy_list β :=\n sorry\n\n/-- Reverse the order of a `lazy_list`.\nIt is done by converting to a `list` first because reversal involves evaluating all\nthe list and if the list is all evaluated, `list` is a better representation for\nit than a series of thunks. -/\ndef reverse {α : Type u_1} (xs : lazy_list α) : lazy_list α :=\n of_list (list.reverse (to_list xs))\n\nprotected instance monad : Monad lazy_list := sorry\n\ntheorem append_nil {α : Type u_1} (xs : lazy_list α) : (append xs fun (_ : Unit) => nil) = xs := sorry\n\ntheorem append_assoc {α : Type u_1} (xs : lazy_list α) (ys : lazy_list α) (zs : lazy_list α) : (append (append xs fun (_ : Unit) => ys) fun (_ : Unit) => zs) =\n append xs fun (_ : Unit) => append ys fun (_ : Unit) => zs := sorry\n\ntheorem append_bind {α : Type u_1} {β : Type u_2} (xs : lazy_list α) (ys : thunk (lazy_list α)) (f : α → lazy_list β) : lazy_list.bind (append xs ys) f = append (lazy_list.bind xs f) fun (_ : Unit) => lazy_list.bind (ys Unit.unit) f := sorry\n\nprotected instance is_lawful_monad : is_lawful_monad lazy_list := sorry\n\n/-- Try applying function `f` to every element of a `lazy_list` and\nreturn the result of the first attempt that succeeds. -/\ndef mfirst {m : Type u_1 → Type u_2} [alternative m] {α : Type u_3} {β : Type u_1} (f : α → m β) : lazy_list α → m β :=\n sorry\n\n/-- Membership in lazy lists -/\nprotected def mem {α : Type u_1} (x : α) : lazy_list α → Prop :=\n sorry\n\nprotected instance has_mem {α : outParam (Type u_1)} : has_mem α (lazy_list α) :=\n has_mem.mk lazy_list.mem\n\nprotected instance mem.decidable {α : Type u_1} [DecidableEq α] (x : α) (xs : lazy_list α) : Decidable (x ∈ xs) :=\n sorry\n\n@[simp] theorem mem_nil {α : Type u_1} (x : α) : x ∈ nil ↔ False :=\n iff.rfl\n\n@[simp] theorem mem_cons {α : Type u_1} (x : α) (y : α) (ys : thunk (lazy_list α)) : x ∈ cons y ys ↔ x = y ∨ x ∈ ys Unit.unit :=\n iff.rfl\n\ntheorem forall_mem_cons {α : Type u_1} {p : α → Prop} {a : α} {l : thunk (lazy_list α)} : (∀ (x : α), x ∈ cons a l → p x) ↔ p a ∧ ∀ (x : α), x ∈ l Unit.unit → p x := sorry\n\n/-! ### map for partial functions -/\n\n/-- Partial map. If `f : Π a, p a → β` is a partial function defined on\n `a : α` satisfying `p`, then `pmap f l h` is essentially the same as `map f l`\n but is defined only when all members of `l` satisfy `p`, using the proof\n to apply `f`. -/\n@[simp] def pmap {α : Type u_1} {β : Type u_2} {p : α → Prop} (f : (a : α) → p a → β) (l : lazy_list α) : (∀ (a : α), a ∈ l → p a) → lazy_list β :=\n sorry\n\n/-- \"Attach\" the proof that the elements of `l` are in `l` to produce a new `lazy_list`\n with the same elements but in the type `{x // x ∈ l}`. -/\ndef attach {α : Type u_1} (l : lazy_list α) : lazy_list (Subtype fun (x : α) => x ∈ l) :=\n pmap Subtype.mk l sorry\n\nprotected instance has_repr {α : Type u_1} [has_repr α] : has_repr (lazy_list α) :=\n has_repr.mk fun (xs : lazy_list α) => repr (to_list xs)\n\n", "meta": {"author": "AurelienSaue", "repo": "Mathlib4_auto", "sha": "590df64109b08190abe22358fabc3eae000943f2", "save_path": "github-repos/lean/AurelienSaue-Mathlib4_auto", "path": "github-repos/lean/AurelienSaue-Mathlib4_auto/Mathlib4_auto-590df64109b08190abe22358fabc3eae000943f2/Mathlib/data/lazy_list/basic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4921881357207956, "lm_q2_score": 0.06656919035938823, "lm_q1q2_score": 0.03276456569943005}} {"text": "/-\nCopyright (c) 2022 Devon Tuma. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Devon Tuma\n-/\nimport computational_monads.simulation_semantics.constructions.stateless_oracle\nimport computational_monads.constructions.uniform_select\n\n/-!\n# Coercions Between Computations With Additional Oracles\n\nThis file defines a `is_sub_spec` relation for pairs of `oracle_spec` where one can be\nthought of as an extension of the other with additional oracles.\nThe definition consists of a function from query inputs in the original oracle to a\ncomputation using the new set of oracles, such that the result of the mapping\ndoesn't affect the underlying probability distribution on the oracle call.\n\nWe use the notation `spec ⊂ₒ spec'` to represent that one set of oracles is a subset of another,\nwhere the non-exclusive subset symbol reflects that we avoid defining this instance reflexively.\nThis decision is based on the `is_coe` construction, where we don't want to coerce a computation\nto itself by calling a reflexive `is_sub_spec` construction.\n\nWe define the map to output a computation rather than a new set of oracle inputs in the new spec\nto avoid type checking issues, as the `query` output type will not be definitionally equal\nto the `query` output type in the original `oracle_spec`, causing issues in defining `has_coe`.\nIn practice the mapping will still usually output a `query` call,\nand the equality between the underlying distributions is generally sufficient.\n\nFrom this definition we construct a `is_coe` instance to coerce a computation with one set of\noracles to one with a larger set of oracles, using the `is_sub_spec` to call `simulate'`.\nWe show that this coercion has no effect on `support`, `eval_dist`, or `prob_event`.\n-/\n\nvariables {α β γ : Type}\n\nnamespace oracle_spec\n\nopen oracle_comp\n\n/-- Example of a computation that naturally should work, but doesn't without `sub_spec` coercions.\nThe fundamental issue being that the type system doesn't have a sense of \"additional\" oracles.\nIn this case, performing a validity check on the adversaries results isn't easily possible.\nNote the actual version is commented out, only the un-checked version will compile. -/\nexample {regular_spec adversary_spec : oracle_spec}\n (adversary : oracle_comp (regular_spec ++ adversary_spec) α)\n (validity_check : α → oracle_comp regular_spec bool) :\n oracle_comp (regular_spec ++ adversary_spec) (option α) :=\n-- do { x ← adversary, b ← validity_check x, return (if b = tt then some x else none) }\ndo { x ← adversary, return x }\n\n/-- Relation defining an inclusion of one set of oracles into another, where the mapping\ndoesn't affect the underlying probability distribution of the computation.\nInformally, `sub_spec ⊂ₒ super_spec` means that for any query to an oracle of `sub_spec`,\nit can be perfectly simulated by a computation using the oracles of `super_spec`. -/\nclass is_sub_spec (sub_spec super_spec : oracle_spec) :=\n(to_fun (i : sub_spec.ι) (t : sub_spec.domain i) : oracle_comp super_spec (sub_spec.range i))\n(eval_dist_to_fun' : ∀ i t, ⁅to_fun i t⁆ = ⁅query i t⁆)\n\ninfixl ` ⊂ₒ `:65 := is_sub_spec\n\nnamespace is_sub_spec\n\nvariables (sub_spec super_spec : oracle_spec) [h : sub_spec ⊂ₒ super_spec]\n (i : sub_spec.ι) (t : sub_spec.domain i)\n\n@[simp] lemma support_to_fun : (h.to_fun i t).support = ⊤ :=\nby rw [← support_eval_dist, h.eval_dist_to_fun', support_eval_dist, support_query]\n\n@[simp] lemma fin_support_to_fun [∀ i t, (h.to_fun i t).decidable] :\n (h.to_fun i t).fin_support = ⊤ :=\nby simp only [fin_support_eq_iff_support_eq_coe, finset.top_eq_univ,\n support_to_fun, set.top_eq_univ, finset.coe_univ]\n\n@[simp] lemma eval_dist_to_fun : ⁅h.to_fun i t⁆ = pmf.uniform_of_fintype (sub_spec.range i) :=\nby rw [h.eval_dist_to_fun', eval_dist_query]\n\n@[simp] lemma prob_event_to_fun (e : set (sub_spec.range i)) :\n ⁅e | h.to_fun i t⁆ = ⁅e | query i t⁆ :=\nprob_event_eq_of_eval_dist_eq (h.eval_dist_to_fun' i t) e\n\nend is_sub_spec\n\nend oracle_spec\n\nnamespace oracle_comp\n\nopen oracle_spec\n\n/-- Given a `is_sub_spec` instance between `sub_spec` and `super_spec`, we can coerce a computation\nwith oracles `sub_spec` to one with `super_spec` by simulating with `is_sub_spec.to_fun`. -/\ninstance coe_sub_spec (sub_spec super_spec : oracle_spec) [h : sub_spec ⊂ₒ super_spec] (α : Type) :\n has_coe (oracle_comp sub_spec α) (oracle_comp super_spec α) :=\n{coe := λ oa, default_simulate' ⟪λ i t, h.to_fun i t⟫ oa}\n\nlemma coe_sub_spec_def {sub_spec super_spec : oracle_spec} [h : sub_spec ⊂ₒ super_spec]\n (oa : oracle_comp sub_spec α) : (↑oa : oracle_comp super_spec α) =\n default_simulate' ⟪λ i t, h.to_fun i t⟫ oa := rfl\n\nsection coe_sub_spec\n\nvariables (sub_spec super_spec : oracle_spec) [h : sub_spec ⊂ₒ super_spec]\n (a : α) (oa : oracle_comp sub_spec α) (ob : α → oracle_comp sub_spec β)\n (i : sub_spec.ι) (t : sub_spec.domain i) (e : set α)\ninclude h\n\ninstance coe_sub_spec.decidable [∀ i t, (@is_sub_spec.to_fun sub_spec super_spec h i t).decidable]\n (oa : oracle_comp sub_spec α) [oa.decidable] : (↑oa : oracle_comp super_spec α).decidable :=\nsimulate'.decidable _ oa ()\n\nlemma coe_sub_spec_return : (↑(return a : oracle_comp sub_spec α) : oracle_comp super_spec α) =\n prod.fst <$> return (a, ()) := rfl\n\nlemma coe_sub_spec_bind : (↑(oa >>= ob) : oracle_comp super_spec β) =\n prod.fst <$> (default_simulate ⟪λ i t, h.to_fun i t⟫ oa >>=\n λ x, simulate ⟪λ i t, h.to_fun i t⟫ (ob x.1) x.2) :=\nby rw [coe_sub_spec_def, default_simulate', simulate'_bind]\n\nlemma coe_sub_spec_query : (↑(query i t) : oracle_comp super_spec (sub_spec.range i)) =\n prod.fst <$> (h.to_fun i t >>= λ u, return (u, ())) :=\nby rw [coe_sub_spec_def, default_simulate', simulate'_query, stateless_oracle.apply_eq]\n\n/-- `support` is unchanged after coercing a computation via a sub-spec instance. -/\n@[simp] lemma support_coe_sub_spec : (↑oa : oracle_comp super_spec α).support = oa.support :=\nstateless_oracle.support_simulate'_eq_support _ _ ()\n (λ i t, is_sub_spec.support_to_fun sub_spec super_spec i t)\n\n/-- `fin_support` is unchanged after coercing a computation via a sub-spec instance. -/\n@[simp] lemma fin_support_coe_sub_spec [∀ i t, (@is_sub_spec.to_fun sub_spec super_spec _ i t).decidable]\n [oa.decidable] : (↑oa : oracle_comp super_spec α).fin_support = oa.fin_support :=\nby rw [fin_support_eq_fin_support_iff_support_eq_support, support_coe_sub_spec]\n\n/-- `eval_dist` is unchanged after coercing a computation via a sub-spec instance. -/\n@[simp] lemma eval_dist_coe_sub_spec : ⁅(↑oa : oracle_comp super_spec α)⁆ = ⁅oa⁆ :=\nstateless_oracle.eval_dist_simulate'_eq_eval_dist _ _ ()\n (λ i t, is_sub_spec.eval_dist_to_fun sub_spec super_spec i t)\n\n/-- `prob_event` is unchanged after coercing a computation via a sub-spec instance. -/\n@[simp] lemma prob_event_coe_sub_spec : ⁅e | (↑oa : oracle_comp super_spec α)⁆ = ⁅e | oa⁆ :=\nstateless_oracle.prob_event_simulate'_eq_prob_event _ _ ()\n (λ i t, is_sub_spec.eval_dist_to_fun sub_spec super_spec i t) e\n\nend coe_sub_spec\n\nsection simulate_coe_sub_spec\n\nvariables {sub_spec super_spec spec : oracle_spec} [h : sub_spec ⊂ₒ super_spec] {S S' : Type}\n (so : sim_oracle sub_spec spec S) (so' : sim_oracle super_spec spec S')\n (s : S) (s' : S') (a : α) (oa : oracle_comp sub_spec α) (ob : α → oracle_comp sub_spec β)\n (i : sub_spec.ι) (t : sub_spec.domain i)\ninclude h\n\nsection support\n\n@[simp] lemma support_simulate_coe_sub_spec_return :\n (simulate so' (return a : oracle_comp sub_spec α) s').support = {(a, s')} :=\nby rw [coe_sub_spec_return, simulate_map, simulate_return, support_map, support_return,\n set.image_singleton, prod.map, id.def]\n\n@[simp] lemma support_simulate'_coe_sub_spec_return :\n (simulate' so' (return a : oracle_comp sub_spec α) s').support = {a} :=\nby simp only [support_simulate', support_simulate_coe_sub_spec_return, set.image_singleton]\n\n@[simp] lemma support_simulate_coe_sub_spec_bind :\n (simulate so' (↑(oa >>= ob) : oracle_comp super_spec β) s').support =\n ⋃ x ∈ (simulate so' (↑oa : oracle_comp super_spec α) s').support,\n (simulate so' ↑(ob $ prod.fst x) x.2).support :=\ncalc (simulate so' (↑(oa >>= ob) : oracle_comp super_spec β) s').support =\n (simulate so' ↑oa s' >>= λ (x : α × S'), simulate so' ↑(ob x.1) x.2).support :\n by simp_rw [coe_sub_spec_def, default_simulate', simulate', simulate_bind,\n support_simulate_map_bind, simulate_map, support_bind_map, support_map,\n simulate_eq_default_simulate, prod.map_snd, prod.map_fst, id.def]\n ... = ⋃ x ∈ (simulate so' (↑oa : oracle_comp super_spec α) s').support,\n (simulate so' ↑(ob $ prod.fst x) x.2).support : by rw [support_bind]\n\n@[simp] lemma support_simulate'_coe_sub_spec_bind :\n (simulate' so' (↑(oa >>= ob) : oracle_comp super_spec β) s').support =\n ⋃ x ∈ (simulate so' (↑oa : oracle_comp super_spec α) s').support,\n (simulate' so' ↑(ob $ prod.fst x) x.2).support :=\nby simp only [support_simulate', support_simulate_coe_sub_spec_bind, set.image_Union]\n\n@[simp] lemma support_simulate_coe_sub_spec_query :\n (simulate so' (↑(query i t) : oracle_comp super_spec (sub_spec.range i)) s').support =\n (simulate so' (h.to_fun i t) s').support :=\nby simp_rw [coe_sub_spec_def, default_simulate', simulate'_query, stateless_oracle.apply_eq,\n support_simulate_map, support_simulate_bind, support_simulate_return, set.image_Union,\n set.image_singleton, prod.map_mk, id.def, prod.mk.eta, set.bUnion_of_singleton]\n\n/-- Given two simulation oracles `so : sim_oracle spec spec'' S` and\n`so' : sim_oracle spec' spec'' : S'` with the starting specs satisfying `spec ⊂ₒ spec'`,\nand a function `f : S → S'` between their states, if the support after simulating the\nsub-spec coersion function with the second oracle looks like the support after simulating with the\nfirst oracle then applying `f`, then simulating the coercion of any computation with the second\noracle has the same support as simulating the uncoerced computation and mapping by `f`. -/\nlemma support_simulate_coe_sub_spec (f : S → S') (hf : ∀ i t s,\n (simulate so' (h.to_fun i t) (f s)).support = prod.map id f '' (so i (t, s)).support) :\n (simulate so' (↑oa : oracle_comp super_spec α) (f s)).support =\n (prod.map id f) '' (simulate so oa s).support :=\nbegin\n induction oa using oracle_comp.induction_on with α a α β oa ob hoa hob i t generalizing s,\n { simpa only [support_simulate_coe_sub_spec_return,\n support_simulate_return, set.image_singleton] },\n { ext y,\n simp_rw [support_simulate_coe_sub_spec_bind, hoa, support_simulate_bind,\n set.image_Union, ← hob, set.mem_Union],\n refine ⟨λ h, let ⟨x, ⟨y', hy', hxy⟩, hx⟩ := h in ⟨y', hy', by simpa only [← hxy] using hx⟩,\n λ h, let ⟨x, hy, hx⟩ := h in ⟨(x.1, f x.2), ⟨x, hy, rfl⟩, hx⟩⟩ },\n { rw [support_simulate_coe_sub_spec_query, hf, support_simulate_query] }\nend\n\n/-- Version of `support_simulate_coe_sub_spec` for `simulate'`. In this case we get exact equality\nbetween the support of the simulations, since the oracle states are irrelevent. -/\nlemma support_simulate'_coe_sub_spec (f : S → S') (hf : ∀ i t s,\n (simulate so' (h.to_fun i t) (f s)).support = prod.map id f '' (so i (t, s)).support) :\n (simulate' so' (↑oa : oracle_comp super_spec α) (f s)).support = (simulate' so oa s).support :=\nby simp only [support_simulate_coe_sub_spec so so' s oa f hf,\n set.image_image, support_simulate', prod_map, id.def]\n\nend support\n\nsection fin_support\n\n\n\nend fin_support\n\nsection eval_dist\n\n@[simp] lemma eval_dist_simulate_coe_sub_spec_return :\n ⁅simulate so' ↑(return a : oracle_comp sub_spec α) s'⁆ = pmf.pure (a, s') :=\nby simp only [coe_sub_spec_return, simulate_map, simulate_return, eval_dist_map, eval_dist_return,\n pmf.map_pure, prod.map_mk, id.def]\n\n@[simp] lemma eval_dist_simulate_coe_sub_spec_bind :\n ⁅simulate so' (↑(oa >>= ob) : oracle_comp super_spec β) s'⁆ =\n ⁅simulate so' ↑oa s'⁆.bind (λ x, ⁅simulate so' ↑(ob $ prod.fst x) x.2⁆) :=\ncalc ⁅simulate so' (↑(oa >>= ob) : oracle_comp super_spec β) s'⁆\n = ⁅simulate so' (default_simulate ⟪h.to_fun⟫ oa) s'⁆.bind (λ (x : (α × unit) × S'),\n ⁅simulate so' (simulate ⟪h.to_fun⟫ (ob x.1.1) x.1.2) x.2⁆.map (prod.map prod.fst id)) :\n by simp only [coe_sub_spec_bind, simulate_map, simulate_bind,\n eval_dist_map, eval_dist_bind, pmf.map_bind]\n ... = (⁅simulate so' (default_simulate ⟪h.to_fun⟫ oa) s'⁆.map (prod.map prod.fst id)).bind\n (λ x, ⁅simulate so' (default_simulate ⟪h.to_fun⟫ (ob x.1)) x.2⁆.map (prod.map prod.fst id)) :\n symm (trans (pmf.bind_map _ _ _) (congr_arg (λ _, pmf.bind _ _) (funext $ λ x, by simp only\n [function.comp_app, prod_map, id.def, stateless_oracle.simulate_eq_default_simulate])))\n ... = ⁅simulate so' (default_simulate' ⟪h.to_fun⟫ oa) s'⁆.bind (λ (x : α × S'),\n ⁅simulate so' (default_simulate ⟪h.to_fun⟫ (ob x.1)) x.2⁆.map (prod.map prod.fst id)) :\n by rw [default_simulate', simulate', eval_dist_simulate_map]\n ... = ⁅simulate so' ↑oa s'⁆.bind (λ (x : α × S'), ⁅simulate so' ↑(ob $ prod.fst x) x.2⁆) :\n by simp only [coe_sub_spec_def, simulate', eval_dist_simulate_map, default_simulate']\n\n@[simp] lemma eval_dist_simulate_coe_sub_spec_query :\n ⁅simulate so' (↑(query i t) : oracle_comp super_spec _) s'⁆ =\n ⁅simulate so' (h.to_fun i t) s'⁆ :=\nby simp only [coe_sub_spec_query, eval_dist_simulate_map_bind, eval_dist_simulate_return,\n pmf.map_pure, prod.map_mk, id.def, prod.mk.eta, pmf.bind_pure]\n\n/-- Given two simulation oracles `so : sim_oracle spec spec'' S` and\n`so' : sim_oracle spec' spec'' : S'` with the starting specs satisfying `spec ⊂ₒ spec'`,\nand a function `f : S → S'` between their states, if the distribution after simulating the\nsub-spec coersion function with the second oracle looks like the distribution after simulating with\nthe first oracle then applying `f`, then simulating the coercion of any computation with the second\noracle has the same distribution as simulating the uncoerced computation and mapping by `f`. -/\nlemma eval_dist_simulate_coe_sub_spec (f : S → S') (hf : ∀ i t s,\n ⁅simulate so' (h.to_fun i t) (f s)⁆ = pmf.map (prod.map id f) ⁅so i (t, s)⁆) :\n ⁅simulate so' (↑oa : oracle_comp super_spec α) (f s)⁆ =\n ⁅simulate so oa s⁆.map (prod.map id f) :=\nbegin\n induction oa using oracle_comp.induction_on with α a α β oa ob hoa hob i t generalizing s,\n { simp only [eval_dist_simulate_coe_sub_spec_return, simulate_return, eval_dist_return,\n pmf.map_pure, prod.map_mk, id.def] },\n { simp_rw [eval_dist_simulate_coe_sub_spec_bind, hoa,\n eval_dist_simulate_bind, pmf.map_bind, pmf.bind_map],\n refine congr_arg (λ _, pmf.bind _ _) (funext $ λ x, (hob _ _)) },\n { rw [eval_dist_simulate_query, eval_dist_simulate_coe_sub_spec_query, hf] }\nend\n\n/-- Version of `eval_dist_simulate_coe_sub_spec` for `simulate'`. In this case we get exact\nequality between the distributions of the simulations, since the oracle states are irrelevent. -/\nlemma eval_dist_simulate'_coe_sub_spec (f : S → S') (hf : ∀ i t s,\n ⁅simulate so' (h.to_fun i t) (f s)⁆ = pmf.map (prod.map id f) ⁅so i (t, s)⁆) :\n ⁅simulate' so' (↑oa : oracle_comp super_spec α) (f s)⁆ = ⁅simulate' so oa s⁆ :=\nby simp only [eval_dist_simulate', eval_dist_simulate_coe_sub_spec so so' s oa f hf, pmf.map_comp,\n prod.map_fst', function.comp.left_id]\n\nend eval_dist\n\nsection prob_event\n\n/-- Extension of `eval_dist_simulate_coe_sub_spec` to `prob_event`. We keep the same hypothesis\nabout `eval_dist` rather than a one in terms of `prob_event` for simplicity. -/\nlemma prob_event_simulate_coe_sub_spec (e : set (α × S')) (f : S → S') (hf : ∀ i t s,\n ⁅simulate so' (h.to_fun i t) (f s)⁆ = pmf.map (prod.map id f) ⁅so i (t, s)⁆) :\n ⁅e | simulate so' (↑oa : oracle_comp super_spec α) (f s)⁆ =\n ⁅e | prod.map id f <$> simulate so oa s⁆ :=\nby simp_rw [prob_event_eq_tsum_indicator, eval_dist_map,\n eval_dist_simulate_coe_sub_spec so so' s oa f hf]\n\n/-- Extension of `eval_dist_simulate'_coe_sub_spec` to `prob_event`. We keep the same hypothesis\nabout `eval_dist` rather than a one in terms of `prob_event` for simplicity. -/\nlemma prob_event_simulate'_coe_sub_spec (e : set α) (f : S → S') (hf : ∀ i t s,\n ⁅simulate so' (h.to_fun i t) (f s)⁆ = pmf.map (prod.map id f) ⁅so i (t, s)⁆) :\n ⁅e | simulate' so' (↑oa : oracle_comp super_spec α) (f s)⁆ = ⁅e | simulate' so oa s⁆ :=\nby simpa only [prob_event_simulate', prob_event_simulate_coe_sub_spec so so' s oa _ f hf,\n prob_event_map, set.preimage_preimage, prod.map_fst]\n\nend prob_event\n\nend simulate_coe_sub_spec\n\nend oracle_comp", "meta": {"author": "dtumad", "repo": "lean-crypto-formalization", "sha": "f975a9a9882120b509553a7ced9aa05b745ff154", "save_path": "github-repos/lean/dtumad-lean-crypto-formalization", "path": "github-repos/lean/dtumad-lean-crypto-formalization/lean-crypto-formalization-f975a9a9882120b509553a7ced9aa05b745ff154/src/computational_monads/coercions/sub_spec.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4378234844434674, "lm_q2_score": 0.0747700408462521, "lm_q1q2_score": 0.032736079815286485}} {"text": "/-\nCopyright (c) 2020 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Leonardo de Moura, Mario Carneiro\n-/\nprelude\nimport Fixtures.Termination.Init.Tactics\nset_option linter.all false -- prevent error messages from runFrontend\n\n/-! # SizeOf -/\n\n/--\n`SizeOf` is a typeclass automatically derived for every inductive type,\nwhich equips the type with a \"size\" function to `Nat`.\nThe default instance defines each constructor to be `1` plus the sum of the\nsizes of all the constructor fields.\n\nThis is used for proofs by well-founded induction, since every field of the\nconstructor has a smaller size than the constructor itself,\nand in many cases this will suffice to do the proof that a recursive function\nis only called on smaller values.\nIf the default proof strategy fails, it is recommended to supply a custom\nsize measure using the `termination_by` argument on the function definition.\n-/\nclass SizeOf (α : Sort u) where\n /-- The \"size\" of an element, a natural number which decreases on fields of\n each inductive type. -/\n sizeOf : α → Nat\n\nexport SizeOf (sizeOf)\n\n/-!\nDeclare `SizeOf` instances and theorems for types declared before `SizeOf`.\nFrom now on, the inductive compiler will automatically generate `SizeOf` instances and theorems.\n-/\n\n/--\nEvery type `α` has a default `SizeOf` instance that just returns `0`\nfor every element of `α`.\n-/\nprotected def default.sizeOf (α : Sort u) : α → Nat\n | _ => 0\n\ninstance (priority := low) (α : Sort u) : SizeOf α where\n sizeOf := default.sizeOf α\n\n@[simp] theorem sizeOf_default (n : α) : sizeOf n = 0 := rfl\n\ninstance : SizeOf Nat where\n sizeOf n := n\n\n@[simp] theorem sizeOf_nat (n : Nat) : sizeOf n = n := rfl\n\ninstance [SizeOf α] : SizeOf (Unit → α) where\n sizeOf f := sizeOf (f ())\n\n@[simp] theorem sizeOf_thunk [SizeOf α] (f : Unit → α) : sizeOf f = sizeOf (f ()) :=\n rfl\n\nderiving instance SizeOf for PUnit\nderiving instance SizeOf for Prod\nderiving instance SizeOf for PProd\nderiving instance SizeOf for MProd\nderiving instance SizeOf for Bool\nderiving instance SizeOf for Subtype\nderiving instance SizeOf for PLift\nderiving instance SizeOf for ULift\nderiving instance SizeOf for Decidable\nderiving instance SizeOf for Fin\nderiving instance SizeOf for UInt8\nderiving instance SizeOf for UInt16\nderiving instance SizeOf for UInt32\nderiving instance SizeOf for UInt64\nderiving instance SizeOf for USize\nderiving instance SizeOf for Char\nderiving instance SizeOf for Option\nderiving instance SizeOf for List\nderiving instance SizeOf for String\nderiving instance SizeOf for String.Pos\nderiving instance SizeOf for Substring\nderiving instance SizeOf for Array\nderiving instance SizeOf for Except\nderiving instance SizeOf for EStateM.Result\n\n@[simp] theorem Unit.sizeOf (u : Unit) : sizeOf u = 1 := rfl\n@[simp] theorem Unit.sizeOf' (u : Unit) : SizeOf.sizeOf u = 1 := by cases u <;> rfl\n@[simp] theorem Bool.sizeOf_eq_one (b : Bool) : sizeOf b = 1 := by cases b <;> rfl\n\nnamespace Lean\n\n/--\nWe manually define the `Lean.Name` instance because we use\nan opaque function for computing the hashcode field.\n-/\nprotected noncomputable def Name.sizeOf : Name → Nat\n | anonymous => 1\n | str p s => 1 + Name.sizeOf p + sizeOf s\n | num p n => 1 + Name.sizeOf p + sizeOf n\n\nnoncomputable instance : SizeOf Name where\n sizeOf n := n.sizeOf\n\n@[simp] theorem Name.anonymous.sizeOf_spec : sizeOf anonymous = 1 :=\n rfl\n@[simp] theorem Name.str.sizeOf_spec (p : Name) (s : String) : sizeOf (str p s) = 1 + sizeOf p + sizeOf s :=\n rfl\n@[simp] theorem Name.num.sizeOf_spec (p : Name) (n : Nat) : sizeOf (num p n) = 1 + sizeOf p + sizeOf n :=\n rfl\n\nderiving instance SizeOf for SourceInfo\nderiving instance SizeOf for Syntax\nderiving instance SizeOf for TSyntax\nderiving instance SizeOf for Syntax.SepArray\nderiving instance SizeOf for Syntax.TSepArray\nderiving instance SizeOf for ParserDescr\nderiving instance SizeOf for MacroScopesView\nderiving instance SizeOf for Macro.Context\nderiving instance SizeOf for Macro.Exception\nderiving instance SizeOf for Macro.State\nderiving instance SizeOf for Macro.Methods\n\nend Lean\n", "meta": {"author": "lurk-lab", "repo": "yatima", "sha": "f33b0bf1052d95f9acbbe61681b1b58c0b97121e", "save_path": "github-repos/lean/lurk-lab-yatima", "path": "github-repos/lean/lurk-lab-yatima/yatima-f33b0bf1052d95f9acbbe61681b1b58c0b97121e/Fixtures/Termination/Init/SizeOf.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4493926344647597, "lm_q2_score": 0.07263669883265193, "lm_q1q2_score": 0.032642397447228785}} {"text": "/-\nCopyright (c) 2017 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Leonardo de Moura, Mario Carneiro\n\n! This file was ported from Lean 3 source module data.array.lemmas\n! leanprover-community/mathlib commit 78314d08d707a6338079f00094bbdb90bf11fc41\n! Please do not edit these lines, except to modify the commit id\n! if you have ported upstream changes.\n-/\nimport Mathbin.Control.Traversable.Equiv\nimport Mathbin.Data.Vector.Basic\n\nuniverse u v w\n\nnamespace DArray\n\nvariable {n : ℕ} {α : Fin n → Type u}\n\ninstance [∀ i, Inhabited (α i)] : Inhabited (DArray n α) :=\n ⟨⟨default⟩⟩\n\nend DArray\n\nnamespace Array'\n\ninstance {n α} [Inhabited α] : Inhabited (Array' n α) :=\n DArray.inhabited\n\ntheorem toList_of_hEq {n₁ n₂ α} {a₁ : Array' n₁ α} {a₂ : Array' n₂ α} (hn : n₁ = n₂)\n (ha : HEq a₁ a₂) : a₁.toList = a₂.toList := by congr <;> assumption\n#align array.to_list_of_heq Array'.toList_of_hEq\n\n-- rev_list\nsection RevList\n\nvariable {n : ℕ} {α : Type u} {a : Array' n α}\n\ntheorem rev_list_reverse_aux :\n ∀ (i) (h : i ≤ n) (t : List α),\n (a.iterateAux (fun _ => (· :: ·)) i h []).reverseAux t =\n a.revIterateAux (fun _ => (· :: ·)) i h t\n | 0, h, t => rfl\n | i + 1, h, t => rev_list_reverse_aux i _ _\n#align array.rev_list_reverse_aux Array'.rev_list_reverse_aux\n\n@[simp]\ntheorem revList_reverse : a.revList.reverse = a.toList :=\n rev_list_reverse_aux _ _ _\n#align array.rev_list_reverse Array'.revList_reverse\n\n@[simp]\ntheorem toList_reverse : a.toList.reverse = a.revList := by\n rw [← rev_list_reverse, List.reverse_reverse]\n#align array.to_list_reverse Array'.toList_reverse\n\nend RevList\n\n-- mem\nsection Mem\n\nvariable {n : ℕ} {α : Type u} {v : α} {a : Array' n α}\n\ntheorem Mem.def : v ∈ a ↔ ∃ i, a.read i = v :=\n Iff.rfl\n#align array.mem.def Array'.Mem.def\n\ntheorem mem_rev_list_aux :\n ∀ {i} (h : i ≤ n),\n (∃ j : Fin n, (j : ℕ) < i ∧ read a j = v) ↔ v ∈ a.iterateAux (fun _ => (· :: ·)) i h []\n | 0, _ => ⟨fun ⟨i, n, _⟩ => absurd n i.val.not_lt_zero, False.elim⟩\n | i + 1, h =>\n let IH := mem_rev_list_aux (le_of_lt h)\n ⟨fun ⟨j, ji1, e⟩ =>\n Or.elim (lt_or_eq_of_le <| Nat.le_of_succ_le_succ ji1)\n (fun ji => List.mem_cons_of_mem _ <| IH.1 ⟨j, ji, e⟩) fun je => by\n simp [DArray.iterateAux] <;> apply Or.inl <;> unfold read at e <;>\n have H : j = ⟨i, h⟩ := Fin.eq_of_veq je <;>\n rwa [← H, e],\n fun m => by\n simp [DArray.iterateAux, List.Mem] at m\n cases' m with e m'\n exact ⟨⟨i, h⟩, Nat.lt_succ_self _, Eq.symm e⟩\n exact\n let ⟨j, ji, e⟩ := IH.2 m'\n ⟨j, Nat.le_succ_of_le ji, e⟩⟩\n#align array.mem_rev_list_aux Array'.mem_rev_list_aux\n\n@[simp]\ntheorem mem_revList : v ∈ a.revList ↔ v ∈ a :=\n Iff.symm <|\n Iff.trans\n (exists_congr fun j =>\n Iff.symm <| show j.1 < n ∧ read a j = v ↔ read a j = v from and_iff_right j.2)\n (mem_rev_list_aux _)\n#align array.mem_rev_list Array'.mem_revList\n\n@[simp]\ntheorem mem_toList : v ∈ a.toList ↔ v ∈ a := by\n rw [← rev_list_reverse] <;> exact list.mem_reverse.trans mem_rev_list\n#align array.mem_to_list Array'.mem_toList\n\nend Mem\n\n-- foldr\nsection Foldr\n\nvariable {n : ℕ} {α : Type u} {β : Type w} {b : β} {f : α → β → β} {a : Array' n α}\n\ntheorem rev_list_foldr_aux :\n ∀ {i} (h : i ≤ n),\n (DArray.iterateAux a (fun _ => (· :: ·)) i h []).foldr f b =\n DArray.iterateAux a (fun _ => f) i h b\n | 0, h => rfl\n | j + 1, h => congr_arg (f (read a ⟨j, h⟩)) (rev_list_foldr_aux _)\n#align array.rev_list_foldr_aux Array'.rev_list_foldr_aux\n\ntheorem revList_foldr : a.revList.foldr f b = a.foldl b f :=\n rev_list_foldr_aux _\n#align array.rev_list_foldr Array'.revList_foldr\n\nend Foldr\n\n-- foldl\nsection Foldl\n\nvariable {n : ℕ} {α : Type u} {β : Type w} {b : β} {f : β → α → β} {a : Array' n α}\n\ntheorem toList_foldl : a.toList.foldl f b = a.foldl b (Function.swap f) := by\n rw [← rev_list_reverse, List.foldl_reverse, rev_list_foldr]\n#align array.to_list_foldl Array'.toList_foldl\n\nend Foldl\n\n-- length\nsection Length\n\nvariable {n : ℕ} {α : Type u}\n\ntheorem rev_list_length_aux (a : Array' n α) (i h) :\n (a.iterateAux (fun _ => (· :: ·)) i h []).length = i := by\n induction i <;> simp [*, DArray.iterateAux]\n#align array.rev_list_length_aux Array'.rev_list_length_aux\n\n@[simp]\ntheorem revList_length (a : Array' n α) : a.revList.length = n :=\n rev_list_length_aux a _ _\n#align array.rev_list_length Array'.revList_length\n\n@[simp]\ntheorem toList_length (a : Array' n α) : a.toList.length = n := by\n rw [← rev_list_reverse, List.length_reverse, rev_list_length]\n#align array.to_list_length Array'.toList_length\n\nend Length\n\n-- nth\nsection Nth\n\nvariable {n : ℕ} {α : Type u} {a : Array' n α}\n\ntheorem to_list_nthLe_aux (i : ℕ) (ih : i < n) :\n ∀ (j) {jh t h'},\n (∀ k tl, j + k = i → List.nthLe t k tl = a.read ⟨i, ih⟩) →\n (a.revIterateAux (fun _ => (· :: ·)) j jh t).nthLe i h' = a.read ⟨i, ih⟩\n | 0, _, _, _, al => al i _ <| zero_add _\n | j + 1, jh, t, h', al =>\n to_list_nth_le_aux j fun k tl hjk =>\n show List.nthLe (a.read ⟨j, jh⟩ :: t) k tl = a.read ⟨i, ih⟩ from\n match k, hjk, tl with\n | 0, e, tl =>\n match i, e, ih with\n | _, rfl, _ => rfl\n | k' + 1, _, tl => by\n simp [List.nthLe] <;> exact al _ _ (by simp [add_comm, add_assoc, *] <;> cc)\n#align array.to_list_nth_le_aux Array'.to_list_nthLe_aux\n\ntheorem toList_nthLe (i : ℕ) (h h') : List.nthLe a.toList i h' = a.read ⟨i, h⟩ :=\n to_list_nthLe_aux _ _ _ fun k tl => absurd tl k.not_lt_zero\n#align array.to_list_nth_le Array'.toList_nthLe\n\n@[simp]\ntheorem toList_nth_le' (a : Array' n α) (i : Fin n) (h') : List.nthLe a.toList i h' = a.read i := by\n cases i <;> apply to_list_nth_le\n#align array.to_list_nth_le' Array'.toList_nth_le'\n\ntheorem toList_get? {i v} : List.get? a.toList i = some v ↔ ∃ h, a.read ⟨i, h⟩ = v :=\n by\n rw [List.get?_eq_some']\n have ll := to_list_length a\n constructor <;> intro h <;> cases' h with h e <;> subst v\n · exact ⟨ll ▸ h, (to_list_nth_le _ _ _).symm⟩\n · exact ⟨ll.symm ▸ h, to_list_nth_le _ _ _⟩\n#align array.to_list_nth Array'.toList_get?\n\ntheorem write_toList {i v} : (a.write i v).toList = a.toList.set i v :=\n List.ext_nthLe (by simp) fun j h₁ h₂ =>\n by\n have h₃ : j < n := by simpa using h₁\n rw [to_list_nth_le _ h₃]\n refine'\n let ⟨_, e⟩ := List.get?_eq_some'.1 _\n e.symm\n by_cases ij : (i : ℕ) = j\n · subst j\n rw [show (⟨(i : ℕ), h₃⟩ : Fin _) = i from Fin.eq_of_veq rfl, Array'.read_write,\n List.get?_set_eq_of_lt]\n simp [h₃]\n · rw [List.get?_set_ne _ _ ij, a.read_write_of_ne, to_list_nth.2 ⟨h₃, rfl⟩]\n exact Fin.ne_of_vne ij\n#align array.write_to_list Array'.write_toList\n\nend Nth\n\n-- enum\nsection Enum\n\nvariable {n : ℕ} {α : Type u} {a : Array' n α}\n\ntheorem mem_toList_enum {i v} : (i, v) ∈ a.toList.enum ↔ ∃ h, a.read ⟨i, h⟩ = v := by\n simp [List.mem_iff_get?, to_list_nth, and_comm, and_assoc, and_left_comm]\n#align array.mem_to_list_enum Array'.mem_toList_enum\n\nend Enum\n\n-- to_array\nsection ToArray\n\nvariable {n : ℕ} {α : Type u}\n\n@[simp]\ntheorem toList_toArray (a : Array' n α) : HEq a.toList.toArray a :=\n hEq_of_hEq_of_eq\n (@Eq.drecOn\n (fun m (e : a.toList.length = m) =>\n HEq (DArray.mk fun v => a.toList.nthLe v.1 v.2)\n (@DArray.mk m (fun _ => α) fun v => a.toList.nthLe v.1 <| e.symm ▸ v.2))\n a.toList_length HEq.rfl) <|\n DArray.ext fun ⟨i, h⟩ => toList_nthLe i h _\n#align array.to_list_to_array Array'.toList_toArray\n\n@[simp]\ntheorem toArray_toList (l : List α) : l.toArray.toList = l :=\n List.ext_nthLe (toList_length _) fun n h1 h2 => toList_nthLe _ h2 _\n#align array.to_array_to_list Array'.toArray_toList\n\nend ToArray\n\n-- push_back\nsection PushBack\n\nvariable {n : ℕ} {α : Type u} {v : α} {a : Array' n α}\n\ntheorem pushBack_rev_list_aux :\n ∀ i h h',\n DArray.iterateAux (a.pushBack v) (fun _ => (· :: ·)) i h [] =\n DArray.iterateAux a (fun _ => (· :: ·)) i h' []\n | 0, h, h' => rfl\n | i + 1, h, h' => by\n simp [DArray.iterateAux]\n refine' ⟨_, push_back_rev_list_aux _ _ _⟩\n dsimp [read, DArray.read, push_back]\n rw [dif_neg]; rfl\n exact ne_of_lt h'\n#align array.push_back_rev_list_aux Array'.pushBack_rev_list_aux\n\n@[simp]\ntheorem pushBack_revList : (a.pushBack v).revList = v :: a.revList :=\n by\n unfold push_back rev_list foldl iterate DArray.iterate\n dsimp [DArray.iterateAux, read, DArray.read, push_back]\n rw [dif_pos (Eq.refl n)]\n apply congr_arg\n apply push_back_rev_list_aux\n#align array.push_back_rev_list Array'.pushBack_revList\n\n@[simp]\ntheorem pushBack_toList : (a.pushBack v).toList = a.toList ++ [v] := by\n rw [← rev_list_reverse, ← rev_list_reverse, push_back_rev_list, List.reverse_cons]\n#align array.push_back_to_list Array'.pushBack_toList\n\n@[simp]\ntheorem read_pushBack_left (i : Fin n) : (a.pushBack v).read i.cast_succ = a.read i :=\n by\n cases' i with i hi\n have : ¬i = n := ne_of_lt hi\n simp [push_back, this, Fin.castSucc, Fin.castAdd, Fin.castLe, Fin.castLt, read, DArray.read]\n#align array.read_push_back_left Array'.read_pushBack_left\n\n@[simp]\ntheorem read_pushBack_right : (a.pushBack v).read (Fin.last _) = v :=\n by\n cases' hn : Fin.last n with k hk\n have : k = n := by simpa [Fin.eq_iff_veq] using hn.symm\n simp [push_back, this, Fin.castSucc, Fin.castAdd, Fin.castLe, Fin.castLt, read, DArray.read]\n#align array.read_push_back_right Array'.read_pushBack_right\n\nend PushBack\n\n-- foreach\nsection Foreach\n\nvariable {n : ℕ} {α : Type u} {β : Type v} {i : Fin n} {f : Fin n → α → β} {a : Array' n α}\n\n@[simp]\ntheorem read_foreach : (foreach a f).read i = f i (a.read i) :=\n rfl\n#align array.read_foreach Array'.read_foreach\n\nend Foreach\n\n-- map\nsection Map\n\nvariable {n : ℕ} {α : Type u} {β : Type v} {i : Fin n} {f : α → β} {a : Array' n α}\n\ntheorem read_map : (a.map f).read i = f (a.read i) :=\n read_foreach\n#align array.read_map Array'.read_map\n\nend Map\n\n-- map₂\nsection Map₂\n\nvariable {n : ℕ} {α : Type u} {i : Fin n} {f : α → α → α} {a₁ a₂ : Array' n α}\n\n@[simp]\ntheorem read_map₂ : (map₂ f a₁ a₂).read i = f (a₁.read i) (a₂.read i) :=\n read_foreach\n#align array.read_map₂ Array'.read_map₂\n\nend Map₂\n\nend Array'\n\n", "meta": {"author": "leanprover-community", "repo": "mathlib3port", "sha": "62505aa236c58c8559783b16d33e30df3daa54f4", "save_path": "github-repos/lean/leanprover-community-mathlib3port", "path": "github-repos/lean/leanprover-community-mathlib3port/mathlib3port-62505aa236c58c8559783b16d33e30df3daa54f4/Mathbin/Data/Array/Lemmas.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3775406547908327, "lm_q2_score": 0.08632348246267256, "lm_q1q2_score": 0.032590624092782364}} {"text": "/-\nCopyright (c) 2018 Simon Hudon. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Simon Hudon\n\nGeneral utility functions for buffers.\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.default\nimport Mathlib.Lean3Lib.data.buffer\nimport Mathlib.data.array.lemmas\nimport Mathlib.control.traversable.instances\nimport Mathlib.PostPort\n\nuniverses u_1 \n\nnamespace Mathlib\n\nnamespace buffer\n\n\nprotected instance inhabited {α : Type u_1} : Inhabited (buffer α) :=\n { default := nil }\n\ntheorem ext {α : Type u_1} {b₁ : buffer α} {b₂ : buffer α} : to_list b₁ = to_list b₂ → b₁ = b₂ := sorry\n\nprotected instance decidable_eq (α : Type u_1) [DecidableEq α] : DecidableEq (buffer α) :=\n id\n fun (_v : buffer α) =>\n sigma.cases_on _v\n fun (fst : ℕ) (snd : array fst α) (w : buffer α) =>\n sigma.cases_on w\n fun (w_fst : ℕ) (w_snd : array w_fst α) =>\n decidable.by_cases\n (fun (ᾰ : fst = w_fst) =>\n Eq._oldrec\n (fun (w_snd : array fst α) =>\n decidable.by_cases (fun (ᾰ : snd = w_snd) => Eq._oldrec (is_true sorry) ᾰ)\n fun (ᾰ : ¬snd = w_snd) => isFalse sorry)\n ᾰ w_snd)\n fun (ᾰ : ¬fst = w_fst) => isFalse sorry\n\n@[simp] theorem to_list_append_list {α : Type u_1} {xs : List α} {b : buffer α} : to_list (append_list b xs) = to_list b ++ xs := sorry\n\n@[simp] theorem append_list_mk_buffer {α : Type u_1} {xs : List α} : append_list mk_buffer xs = array.to_buffer (list.to_array xs) := sorry\n\n/-- The natural equivalence between lists and buffers, using\n`list.to_buffer` and `buffer.to_list`. -/\ndef list_equiv_buffer (α : Type u_1) : List α ≃ buffer α :=\n equiv.mk list.to_buffer to_list sorry sorry\n\nprotected instance traversable : traversable buffer :=\n equiv.traversable list_equiv_buffer\n\nprotected instance is_lawful_traversable : is_lawful_traversable buffer :=\n equiv.is_lawful_traversable list_equiv_buffer\n\n", "meta": {"author": "AurelienSaue", "repo": "Mathlib4_auto", "sha": "590df64109b08190abe22358fabc3eae000943f2", "save_path": "github-repos/lean/AurelienSaue-Mathlib4_auto", "path": "github-repos/lean/AurelienSaue-Mathlib4_auto/Mathlib4_auto-590df64109b08190abe22358fabc3eae000943f2/Mathlib/data/buffer/basic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4416730203630096, "lm_q2_score": 0.07263670033827888, "lm_q1q2_score": 0.03208167082761047}} {"text": "/-\nCopyright (c) 2020 Scott Morrison. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Bhavik Mehta, Scott Morrison\n-/\nimport category_theory.subobject.basic\nimport category_theory.preadditive.basic\n\n/-!\n# Factoring through subobjects\n\nThe predicate `h : P.factors f`, for `P : subobject Y` and `f : X ⟶ Y`\nasserts the existence of some `P.factor_thru f : X ⟶ (P : C)` making the obvious diagram commute.\n\n-/\n\nuniverses v₁ v₂ u₁ u₂\n\nnoncomputable theory\n\nopen category_theory category_theory.category category_theory.limits\n\nvariables {C : Type u₁} [category.{v₁} C] {X Y Z : C}\nvariables {D : Type u₂} [category.{v₂} D]\n\nnamespace category_theory\n\nnamespace mono_over\n\n/-- When `f : X ⟶ Y` and `P : mono_over Y`,\n`P.factors f` expresses that there exists a factorisation of `f` through `P`.\nGiven `h : P.factors f`, you can recover the morphism as `P.factor_thru f h`.\n-/\ndef factors {X Y : C} (P : mono_over Y) (f : X ⟶ Y) : Prop := ∃ g : X ⟶ (P : C), g ≫ P.arrow = f\n\nlemma factors_congr {X : C} {f g : mono_over X} {Y : C} (h : Y ⟶ X) (e : f ≅ g) :\n f.factors h ↔ g.factors h :=\n⟨λ ⟨u, hu⟩, ⟨u ≫ (((mono_over.forget _).map e.hom)).left, by simp [hu]⟩,\n λ ⟨u, hu⟩, ⟨u ≫ (((mono_over.forget _).map e.inv)).left, by simp [hu]⟩⟩\n\n/-- `P.factor_thru f h` provides a factorisation of `f : X ⟶ Y` through some `P : mono_over Y`,\ngiven the evidence `h : P.factors f` that such a factorisation exists. -/\ndef factor_thru {X Y : C} (P : mono_over Y) (f : X ⟶ Y) (h : factors P f) : X ⟶ (P : C) :=\nclassical.some h\n\nend mono_over\n\nnamespace subobject\n\n/-- When `f : X ⟶ Y` and `P : subobject Y`,\n`P.factors f` expresses that there exists a factorisation of `f` through `P`.\nGiven `h : P.factors f`, you can recover the morphism as `P.factor_thru f h`.\n-/\ndef factors {X Y : C} (P : subobject Y) (f : X ⟶ Y) : Prop :=\nquotient.lift_on' P (λ P, P.factors f)\nbegin\n rintros P Q ⟨h⟩,\n apply propext,\n split,\n { rintro ⟨i, w⟩,\n exact ⟨i ≫ h.hom.left, by erw [category.assoc, over.w h.hom, w]⟩, },\n { rintro ⟨i, w⟩,\n exact ⟨i ≫ h.inv.left, by erw [category.assoc, over.w h.inv, w]⟩, },\nend\n\n@[simp] \n\nlemma mk_factors_self (f : X ⟶ Y) [mono f] : (mk f).factors f := ⟨𝟙 _, by simp⟩\n\nlemma factors_iff {X Y : C} (P : subobject Y) (f : X ⟶ Y) :\n P.factors f ↔ (representative.obj P).factors f :=\nquot.induction_on P $ λ a, mono_over.factors_congr _ (representative_iso _).symm\n\nlemma factors_self {X : C} (P : subobject X) : P.factors P.arrow :=\n(factors_iff _ _).mpr ⟨𝟙 P, (by simp)⟩\n\nlemma factors_comp_arrow {X Y : C} {P : subobject Y} (f : X ⟶ P) : P.factors (f ≫ P.arrow) :=\n(factors_iff _ _).mpr ⟨f, rfl⟩\n\nlemma factors_of_factors_right {X Y Z : C} {P : subobject Z} (f : X ⟶ Y) {g : Y ⟶ Z}\n (h : P.factors g) : P.factors (f ≫ g) :=\nbegin\n revert P,\n refine quotient.ind' _,\n intro P,\n rintro ⟨g, rfl⟩,\n exact ⟨f ≫ g, by simp⟩,\nend\n\nlemma factors_zero [has_zero_morphisms C] {X Y : C} {P : subobject Y} :\n P.factors (0 : X ⟶ Y) :=\n(factors_iff _ _).mpr ⟨0, by simp⟩\n\nlemma factors_of_le {Y Z : C} {P Q : subobject Y} (f : Z ⟶ Y) (h : P ≤ Q) :\n P.factors f → Q.factors f :=\nby { simp only [factors_iff], exact λ ⟨u, hu⟩, ⟨u ≫ of_le _ _ h, by simp [←hu]⟩ }\n\n/-- `P.factor_thru f h` provides a factorisation of `f : X ⟶ Y` through some `P : subobject Y`,\ngiven the evidence `h : P.factors f` that such a factorisation exists. -/\ndef factor_thru {X Y : C} (P : subobject Y) (f : X ⟶ Y) (h : factors P f) : X ⟶ P :=\nclassical.some ((factors_iff _ _).mp h)\n\n@[simp, reassoc] lemma factor_thru_arrow {X Y : C} (P : subobject Y) (f : X ⟶ Y) (h : factors P f) :\n P.factor_thru f h ≫ P.arrow = f :=\nclassical.some_spec ((factors_iff _ _).mp h)\n\n@[simp] lemma factor_thru_self {X : C} (P : subobject X) (h) :\n P.factor_thru P.arrow h = 𝟙 P :=\nby { ext, simp, }\n\n@[simp] lemma factor_thru_mk_self (f : X ⟶ Y) [mono f] :\n (mk f).factor_thru f (mk_factors_self f) = (underlying_iso f).inv :=\nby { ext, simp, }\n\n@[simp] lemma factor_thru_comp_arrow {X Y : C} {P : subobject Y} (f : X ⟶ P) (h) :\n P.factor_thru (f ≫ P.arrow) h = f :=\nby { ext, simp, }\n\n@[simp] lemma factor_thru_eq_zero [has_zero_morphisms C]\n {X Y : C} {P : subobject Y} {f : X ⟶ Y} {h : factors P f} :\n P.factor_thru f h = 0 ↔ f = 0 :=\nbegin\n fsplit,\n { intro w,\n replace w := w =≫ P.arrow,\n simpa using w, },\n { rintro rfl,\n ext, simp, },\nend\n\nlemma factor_thru_right {X Y Z : C} {P : subobject Z} (f : X ⟶ Y) (g : Y ⟶ Z) (h : P.factors g) :\n f ≫ P.factor_thru g h = P.factor_thru (f ≫ g) (factors_of_factors_right f h) :=\nbegin\n apply (cancel_mono P.arrow).mp,\n simp,\nend\n\n@[simp]\nlemma factor_thru_zero\n [has_zero_morphisms C] {X Y : C} {P : subobject Y} (h : P.factors (0 : X ⟶ Y)) :\n P.factor_thru 0 h = 0 :=\nby simp\n\n-- `h` is an explicit argument here so we can use\n-- `rw factor_thru_le h`, obtaining a subgoal `P.factors f`.\n-- (While the reverse direction looks plausible as a simp lemma, it seems to be unproductive.)\nlemma factor_thru_of_le\n {Y Z : C} {P Q : subobject Y} {f : Z ⟶ Y} (h : P ≤ Q) (w : P.factors f) :\n Q.factor_thru f (factors_of_le f h w) = P.factor_thru f w ≫ of_le P Q h :=\nby { ext, simp, }\n\nsection preadditive\n\nvariables [preadditive C]\n\nlemma factors_add {X Y : C} {P : subobject Y} (f g : X ⟶ Y) (wf : P.factors f) (wg : P.factors g) :\n P.factors (f + g) :=\n(factors_iff _ _).mpr ⟨P.factor_thru f wf + P.factor_thru g wg, by simp⟩\n\n-- This can't be a `simp` lemma as `wf` and `wg` may not exist.\n-- However you can `rw` by it to assert that `f` and `g` factor through `P` separately.\nlemma factor_thru_add {X Y : C} {P : subobject Y} (f g : X ⟶ Y)\n (w : P.factors (f + g)) (wf : P.factors f) (wg : P.factors g) :\n P.factor_thru (f + g) w = P.factor_thru f wf + P.factor_thru g wg :=\nby { ext, simp, }\n\nlemma factors_left_of_factors_add {X Y : C} {P : subobject Y} (f g : X ⟶ Y)\n (w : P.factors (f + g)) (wg : P.factors g) : P.factors f :=\n(factors_iff _ _).mpr ⟨P.factor_thru (f + g) w - P.factor_thru g wg, by simp⟩\n\n@[simp]\nlemma factor_thru_add_sub_factor_thru_right {X Y : C} {P : subobject Y} (f g : X ⟶ Y)\n (w : P.factors (f + g)) (wg : P.factors g) :\n P.factor_thru (f + g) w - P.factor_thru g wg =\n P.factor_thru f (factors_left_of_factors_add f g w wg) :=\nby { ext, simp, }\n\nlemma factors_right_of_factors_add {X Y : C} {P : subobject Y} (f g : X ⟶ Y)\n (w : P.factors (f + g)) (wf : P.factors f) : P.factors g :=\n(factors_iff _ _).mpr ⟨P.factor_thru (f + g) w - P.factor_thru f wf, by simp⟩\n\n@[simp]\nlemma factor_thru_add_sub_factor_thru_left {X Y : C} {P : subobject Y} (f g : X ⟶ Y)\n (w : P.factors (f + g)) (wf : P.factors f) :\n P.factor_thru (f + g) w - P.factor_thru f wf =\n P.factor_thru g (factors_right_of_factors_add f g w wf) :=\nby { ext, simp, }\n\nend preadditive\n\nend subobject\n\nend category_theory\n", "meta": {"author": "leanprover-community", "repo": "mathlib", "sha": "5e526d18cea33550268dcbbddcb822d5cde40654", "save_path": "github-repos/lean/leanprover-community-mathlib", "path": "github-repos/lean/leanprover-community-mathlib/mathlib-5e526d18cea33550268dcbbddcb822d5cde40654/src/category_theory/subobject/factor_thru.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47268347662043286, "lm_q2_score": 0.06754669724011829, "lm_q1q2_score": 0.03192820768568691}} {"text": "/-\nCopyright (c) 2021 Gabriel Ebner. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthor: Gabriel Ebner\n-/\nimport Lean\n\n/-!\n# Irreducible definitions\n\nThis file defines an `irreducible_def` command,\nwhich works almost like the `def` command\nexcept that the introduced definition\ndoes not reduce to the value.\nInstead, the command\nadds a `_def` lemma\nwhich can be used for rewriting.\n\n```\nirreducible_def frobnicate (a b : Nat) :=\n a + b\n\nexample : frobnicate a 0 = a := by\n simp [frobnicate_def]\n```\n\n-/\n\nnamespace Lean.Elab.Command\n\nopen Term Meta\n\n/-- `delta% t` elaborates to a head-delta reduced version of `t`. -/\nelab \"delta% \" t:term : term <= expectedType => do\n let t ← elabTerm t expectedType\n synthesizeSyntheticMVars\n let t ← instantiateMVars t\n let some t ← delta? t | throwError \"cannot delta reduce {t}\"\n pure t\n\n/- `eta_helper f = (· + 3)` elabs to `∀ x, f x = x + 3` -/\nlocal elab \"eta_helper \" t:term : term => do\n let t ← elabTerm t none\n let some (_, lhs, rhs) := t.eq? | throwError \"not an equation: {t}\"\n synthesizeSyntheticMVars\n let rhs ← instantiateMVars rhs\n lambdaLetTelescope rhs fun xs rhs => do\n let lhs := (mkAppN lhs xs).headBeta\n mkForallFVars xs <|← mkEq lhs rhs\n\n/-- `value_proj x` elabs to `@x.value` -/\nlocal elab \"value_proj \" e:term : term => do\n let e ← elabTerm e none\n mkProjection e `value\n\n/--\nExecutes the commands,\nand stops after the first error.\nIn short, S-A-F-E.\n-/\nlocal syntax \"stop_at_first_error\" command* : command\nopen Command in elab_rules : command\n | `(stop_at_first_error $[$cmds]*) => do\n for cmd in cmds do\n elabCommand cmd\n if (← get).messages.hasErrors then break\n\n/--\nIntroduces an irreducible definition.\n`irreducible_def foo := 42` generates\na constant `foo : Nat` as well as\na theorem `foo_def : foo = 42`.\n-/\nmacro mods:declModifiers \"irreducible_def\" n_id:declId declSig:optDeclSig val:declVal : command => do\n let (n, us) ← match n_id with\n | `(Parser.Command.declId| $n:ident $[.{$us,*}]?) => pure (n, us)\n | _ => Macro.throwUnsupported\n let us' := us.getD (Syntax.SepArray.ofElems #[])\n let n_def := mkIdent <| (·.review) <|\n let scopes := extractMacroScopes n.getId\n { scopes with name := scopes.name.appendAfter \"_def\" }\n `(stop_at_first_error\n def definition$[.{$us,*}]? $declSig:optDeclSig $val\n structure Wrapper$[.{$us,*}]? where\n value : type_of% @definition.{$us',*}\n prop : Eq @value @(delta% @definition)\n constant wrapped$[.{$us,*}]? : Wrapper.{$us',*} := ⟨_, rfl⟩\n $mods:declModifiers def $n:ident$[.{$us,*}]? := value_proj @wrapped.{$us',*}\n theorem $n_def:ident $[.{$us,*}]? : eta_helper Eq @$n.{$us',*} @(delta% @definition) := by\n intros\n simp only [$n:ident]\n rw [wrapped.prop])\n", "meta": {"author": "JOSHCLUNE", "repo": "Keller_reduction", "sha": "dc392b3da352fc1ffcfbecb1d4717d05f5faed4a", "save_path": "github-repos/lean/JOSHCLUNE-Keller_reduction", "path": "github-repos/lean/JOSHCLUNE-Keller_reduction/Keller_reduction-dc392b3da352fc1ffcfbecb1d4717d05f5faed4a/Lean4_Clique/Mathlib/Mathlib/Tactic/IrreducibleDef.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4455295350395727, "lm_q2_score": 0.07159120390143847, "lm_q1q2_score": 0.03189599578713113}} {"text": "/-\n## Interface for MLIR dialects\n-/\n\n\n/-\n### Extended types and attributes\n\nDialects can define custom types and attributes that map to concrete Lean\ndatatypes satisfying the requirements of the type interface. These types and\nattributes can be mixed together with other dialects' and used in proofs.\n\nBecause it is impossible to know in advance what set of dialects an operation\nwill be used with, most proofs should either (1) quantify on a dialect\ninterface and handle default cases, or (2) come with a lifting theorem that\nperforms this closure under context automatically.\n-/\n\n/-- The `DialectTypeIntf` typeclass defines the requirements for dialect-\n supplied custom types. These properties are available even on unknown\n custom types, which allows type-generic functions and proofs to be written.\n\n In the interface, `σ` is the type of \"signatures\" (parameters), while `ε`\n is the type of \"extended values\". For instance for `builtin.tensor`, `σ` is\n a datatype holding the dimensions and base type of the tensor, while `ε` is\n the type of tensor values (for any particular signature).\n\n Type families that quantify over `Type` or higher universes are not\n supported to avoid universe polymorphism in the core data structures; in\n this case, `ε` can be made to implement specific instances of the family\n instead. -/\nclass DialectTypeIntf (σ: Type) (ε: σ → Type): Type where\n\n /-- The type should be inhabited, so that SSA value accesses can return\n defaults instead of requiring a proof that every access is dominated by\n a definition (which is a very annoying statement to maintain). -/\n inhabited: forall (s: σ), ε s\n\n /-- The signature should have decidable equality, so we can compare types. -/\n typeEq: DecidableEq σ\n /-- The type should have decidable equality, so that rewriting tools can\n find matches involving concrete values (eg. in PDL).\n Note: This might be relaxed into a `BEq` in the future. -/\n eq: forall (s: σ), DecidableEq (ε s)\n\n /-- String representation of values in the type (eg. a multi-dimensional\n array for tensors). -/\n str: (s: σ) → ε s → String\n /-- String representation of the type itself (eg. \"tensor<4x4xf64>\"). -/\n typeStr: σ → String\n\n -- TODO: DialectTypeIntf: Type signature, to match eg. \"any builtin.vector\"\n\ndef DialectTypeIntf.sigType {σ ε} (_: DialectTypeIntf σ ε): Type := σ\ndef DialectTypeIntf.extType {σ ε} (_: DialectTypeIntf σ ε) (s: σ): Type := ε s\n\n-- Expressing typeclass instances this way helps resolution\ninstance {σ ε} [i: DialectTypeIntf σ ε] (s: σ): Inhabited (ε s) where\n default := i.inhabited s\ninstance {σ ε} [i: DialectTypeIntf σ ε] (s: σ): ToString (ε s) where\n toString := i.str s\ninstance _DEq1 {σ ε} [i: DialectTypeIntf σ ε]: DecidableEq σ :=\n i.typeEq\ninstance _DEq2 {σ ε} [i: DialectTypeIntf σ ε] (s: σ): DecidableEq (ε s) :=\n i.eq s\n\n\n/-- The `DialectAttrIntf` typeclass defines the requirements for dialect-\n supplied custom attributes. -/\nclass DialectAttrIntf (α: Type) where\n\n /-- The attribute should have decidable equality so that rewriting can match\n against them (eg. in PDL). -/\n eq: DecidableEq α\n\n /-- String representation of attribute values. -/\n str: α → String\n\n -- TODO: More data on attributes\n\ndef DialectAttrIntf.type {α} (_: DialectAttrIntf α): Type := α\n\ninstance _DEq3 {α} [i: DialectAttrIntf α]: DecidableEq α := i.eq\n\n\n/-\n### Combinations of interfaces\n\nAs dialects can provide multiple sets of extended types and attributes (and\ndialects may themselves be combined), the interface must allow for different\nextensions to be combined.\n\nThe following instances allow extended types, attributes, and dialects to be\ncombined with `Sum`.\n-/\n\n-- Like Sum.rec, but not a recursor (hence supported for code generation)\n@[reducible]\ndef Sum.cases {α β γ} (fα: α → γ) (fβ: β → γ): (α ⊕ β) → γ\n | .inl a => fα a\n | .inr b => fβ b\n\ninstance {σ₁ ε₁ σ₂ ε₂} [i₁: DialectTypeIntf σ₁ ε₁] [i₂: DialectTypeIntf σ₂ ε₂]:\n DialectTypeIntf (σ₁ ⊕ σ₂) (Sum.cases ε₁ ε₂) where\n inhabited s :=\n match s with\n | .inl s₁ => i₁.inhabited s₁\n | .inr s₂ => i₂.inhabited s₂\n typeEq := inferInstance\n eq s :=\n match s with\n | .inl s₁ => i₁.eq s₁\n | .inr s₂ => i₂.eq s₂\n str s :=\n match s with\n | .inl s₁ => i₁.str s₁\n | .inr s₂ => i₂.str s₂\n typeStr := Sum.cases i₁.typeStr i₂.typeStr\n\ninstance {α₁ α₂} [i₁: DialectAttrIntf α₁] [i₂: DialectAttrIntf α₂]:\n DialectAttrIntf (α₁ ⊕ α₂) where\n eq := inferInstance\n str := Sum.cases i₁.str i₂.str\n\n\n/-\n### Dialects\n-/\n\n-- TODO: Document and finish the Dialect interface\nclass Dialect (α σ) (ε: σ → Type): Type :=\n name: String\n iα: DialectAttrIntf α\n iε: DialectTypeIntf σ ε\n\ninstance {α ε} [δ: Dialect α σ ε]: DialectAttrIntf α := δ.iα\ninstance {α ε} [δ: Dialect α σ ε]: DialectTypeIntf σ ε := δ.iε\n\n\n/-\n### Empty dialect\n\nThe empty dialect is a default value to start building hierarchies from. It is\nused in a couple of aliases, eg. `MLIRTy` (for `MLIRType Dialect.empty`) and\n`AttrVal` (for `AttrValue Dialect.empty`).\n-/\n\ninductive Void :=\nderiving DecidableEq\n\ninstance: DialectTypeIntf Void (fun _ => Unit) where\n inhabited s := nomatch s\n typeEq := inferInstance\n eq s := nomatch s\n str s := nomatch s\n typeStr s := nomatch s\n\ninstance: DialectAttrIntf Void where\n eq := inferInstance\n str a := nomatch a\n\ninstance Dialect.empty: Dialect Void Void (fun _ => Unit) where\n name := \"Empty\"\n iα := inferInstance\n iε := inferInstance\n\n\n-- We write combinations of dialects with + as usual (no risk of confusion)\ninstance {α₁ σ₁ ε₁ α₂ σ₂ ε₂}:\n HAdd (Dialect α₁ σ₁ ε₁) (Dialect α₂ σ₂ ε₂)\n (Dialect (α₁ ⊕ α₂) (σ₁ ⊕ σ₂) (Sum.cases ε₁ ε₂)) where\n hAdd δ₁ δ₂ := {\n name := s!\"({δ₁.name}+{δ₂.name})\"\n iα := inferInstance\n iε := inferInstance\n }\n\ninstance {α₁ σ₁ ε₁ α₂ σ₂ ε₂} [δ₁: Dialect α₁ σ₁ ε₁] [δ₂: Dialect α₂ σ₂ ε₂]:\n Dialect (α₁ ⊕ α₂) (σ₁ ⊕ σ₂) (Sum.cases ε₁ ε₂) :=\n δ₁ + δ₂\n\n\n/-\n### Coercions of dialects\n\nThe `CoeDialect` ckass is used to automatically inject individual dialects into\nsums of dialects, which in turn allows automatic conversion of instances of\ncommon MLIR data such as `MLIRType`, `AttrValue` and `Op` across dialects.\n-/\n\nclass CoeDialect (δ₁: Dialect α₁ σ₁ ε₁) (δ₂: Dialect α₂ σ₂ ε₂) where\n coe_α: α₁ → α₂\n coe_σ: σ₁ → σ₂\n coe_ε: forall s, ε₁ s → ε₂ (coe_σ s)\n\ninstance (δ₁: Dialect α₁ σ₁ ε₁) (δ₂: Dialect α₂ σ₂ ε₂) [c: CoeDialect δ₁ δ₂]:\n Coe α₁ α₂ where coe := c.coe_α\ninstance (δ₁: Dialect α₁ σ₁ ε₁) (δ₂: Dialect α₂ σ₂ ε₂) [c: CoeDialect δ₁ δ₂]:\n Coe σ₁ σ₂ where coe := c.coe_σ\ninstance (δ₁: Dialect α₁ σ₁ ε₁) (δ₂: Dialect α₂ σ₂ ε₂) [c: CoeDialect δ₁ δ₂] s:\n Coe (ε₁ s) (ε₂ /-coe-/s) where coe := c.coe_ε s\n\ninstance (δ: Dialect α σ ε): CoeDialect δ δ where\n coe_α := id\n coe_σ := id\n coe_ε s := id\n\ninstance (δ₁: Dialect α₁ σ₁ ε₁) (δ₂: Dialect α₂ σ₂ ε₂):\n CoeDialect δ₁ (δ₁ + δ₂) where\n coe_α := .inl\n coe_σ := .inl\n coe_ε s := id\n\ninstance (δ₁: Dialect α₁ σ₁ ε₁) (δ₂: Dialect α₂ σ₂ ε₂):\n CoeDialect δ₂ (δ₁ + δ₂) where\n coe_α := .inr\n coe_σ := .inr\n coe_ε s := id\n\ninstance (δ: Dialect α σ ε): CoeDialect Dialect.empty δ where\n coe_α a := nomatch a\n coe_σ s := nomatch s\n coe_ε s := nomatch s\n", "meta": {"author": "opencompl", "repo": "lean-mlir", "sha": "85fd61e38dec57e4d67d7af4d49a1ccc67828c1b", "save_path": "github-repos/lean/opencompl-lean-mlir", "path": "github-repos/lean/opencompl-lean-mlir/lean-mlir-85fd61e38dec57e4d67d7af4d49a1ccc67828c1b/MLIR/Dialects.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4843800842769843, "lm_q2_score": 0.06560483517543497, "lm_q1q2_score": 0.031777675591254856}} {"text": "/-\nCopyright (c) 2019 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Leonardo de Moura, Mario Carneiro\n-/\nimport Std.Data.List.Basic\n\nnamespace Std\n\n/--\n`AssocList α β` is \"the same as\" `List (α × β)`, but flattening the structure\nleads to one fewer pointer indirection (in the current code generator).\nIt is mainly intended as a component of `HashMap`, but it can also be used as a plain\nkey-value map.\n-/\ninductive AssocList (α : Type u) (β : Type v) where\n /-- An empty list -/\n | nil\n /-- Add a `key, value` pair to the list -/\n | cons (key : α) (value : β) (tail : AssocList α β)\n deriving Inhabited\n\nnamespace AssocList\n\n/--\n`O(n)`. Convert an `AssocList α β` into the equivalent `List (α × β)`.\nThis is used to give specifications for all the `AssocList` functions\nin terms of corresponding list functions.\n-/\n@[simp] def toList : AssocList α β → List (α × β)\n | nil => []\n | cons a b es => (a, b) :: es.toList\n\ninstance : EmptyCollection (AssocList α β) := ⟨nil⟩\n\n@[simp] theorem empty_eq : (∅ : AssocList α β) = nil := rfl\n\n/-- `O(1)`. Is the list empty? -/\ndef isEmpty : AssocList α β → Bool\n | nil => true\n | _ => false\n\n@[simp] theorem isEmpty_eq (l : AssocList α β) : isEmpty l = l.toList.isEmpty := by\n cases l <;> simp [*, isEmpty, List.isEmpty]\n\n/-- `O(n)`. Fold a monadic function over the list, from head to tail. -/\n@[specialize] def foldlM [Monad m] (f : δ → α → β → m δ) : (init : δ) → AssocList α β → m δ\n | d, nil => pure d\n | d, cons a b es => do foldlM f (← f d a b) es\n\n@[simp] theorem foldlM_eq [Monad m] (f : δ → α → β → m δ) (init l) :\n foldlM f init l = l.toList.foldlM (fun d (a, b) => f d a b) init := by\n induction l generalizing init <;> simp [*, foldlM]\n\n/-- `O(n)`. Fold a function over the list, from head to tail. -/\n@[inline] def foldl (f : δ → α → β → δ) (init : δ) (as : AssocList α β) : δ :=\n Id.run (foldlM f init as)\n\n@[simp] theorem foldl_eq (f : δ → α → β → δ) (init l) :\n foldl f init l = l.toList.foldl (fun d (a, b) => f d a b) init := by\n simp [List.foldl_eq_foldlM, foldl, Id.run]\n\n/-- Optimized version of `toList`. -/\ndef toListTR (as : AssocList α β) : List (α × β) :=\n as.foldl (init := #[]) (fun r a b => r.push (a, b)) |>.toList\n\n@[csimp] theorem toList_eq_toListTR : @toList = @toListTR := by\n funext α β as; simp [toListTR]\n exact .symm <| (Array.foldl_data_eq_map (toList as) _ id).trans (List.map_id _)\n\n/-- `O(n)`. Run monadic function `f` on all elements in the list, from head to tail. -/\n@[specialize] def forM [Monad m] (f : α → β → m PUnit) : AssocList α β → m PUnit\n | nil => pure ⟨⟩\n | cons a b es => do f a b; forM f es\n\n@[simp] theorem forM_eq [Monad m] (f : α → β → m PUnit) (l) :\n forM f l = l.toList.forM (fun (a, b) => f a b) := by\n induction l <;> simp [*, forM]\n\n/-- `O(n)`. Map a function `f` over the keys of the list. -/\n@[simp] def mapKey (f : α → δ) : AssocList α β → AssocList δ β\n | nil => nil\n | cons k v t => cons (f k) v (mapKey f t)\n\n@[simp] theorem mapKey_toList (f : α → δ) (l : AssocList α β) :\n (mapKey f l).toList = l.toList.map (fun (a, b) => (f a, b)) := by\n induction l <;> simp [*]\n\n/-- `O(n)`. Map a function `f` over the values of the list. -/\n@[simp] def mapVal (f : α → β → δ) : AssocList α β → AssocList α δ\n | nil => nil\n | cons k v t => cons k (f k v) (mapVal f t)\n\n@[simp] theorem mapVal_toList (f : α → β → δ) (l : AssocList α β) :\n (mapVal f l).toList = l.toList.map (fun (a, b) => (a, f a b)) := by\n induction l <;> simp [*]\n\n/-- `O(n)`. Returns the first entry in the list whose entry satisfies `p`. -/\n@[specialize] def findEntryP? (p : α → β → Bool) : AssocList α β → Option (α × β)\n | nil => none\n | cons k v es => bif p k v then some (k, v) else findEntryP? p es\n\n@[simp] theorem findEntryP?_eq (p : α → β → Bool) (l : AssocList α β) :\n findEntryP? p l = l.toList.find? fun (a, b) => p a b := by\n induction l <;> simp [findEntryP?]; split <;> simp [*]\n\n/-- `O(n)`. Returns the first entry in the list whose key is equal to `a`. -/\n@[inline] def findEntry? [BEq α] (a : α) (l : AssocList α β) : Option (α × β) :=\n findEntryP? (fun k _ => k == a) l\n\n@[simp] theorem findEntry?_eq [BEq α] (a : α) (l : AssocList α β) :\n findEntry? a l = l.toList.find? (·.1 == a) := findEntryP?_eq ..\n\n/-- `O(n)`. Returns the first value in the list whose key is equal to `a`. -/\ndef find? [BEq α] (a : α) : AssocList α β → Option β\n | nil => none\n | cons k v es => match k == a with\n | true => some v\n | false => find? a es\n\ntheorem find?_eq_findEntry? [BEq α] (a : α) (l : AssocList α β) :\n find? a l = (l.findEntry? a).map (·.2) := by\n induction l <;> simp [find?]; split <;> simp [*]\n\n@[simp] theorem find?_eq [BEq α] (a : α) (l : AssocList α β) :\n find? a l = (l.toList.find? (·.1 == a)).map (·.2) := by simp [find?_eq_findEntry?]\n\n/-- `O(n)`. Returns true if any entry in the list satisfies `p`. -/\n@[specialize] def any (p : α → β → Bool) : AssocList α β → Bool\n | nil => false\n | cons k v es => p k v || any p es\n\n@[simp] theorem any_eq (p : α → β → Bool) (l : AssocList α β) :\n any p l = l.toList.any fun (a, b) => p a b := by induction l <;> simp [any, *]\n\n/-- `O(n)`. Returns true if every entry in the list satisfies `p`. -/\n@[specialize] def all (p : α → β → Bool) : AssocList α β → Bool\n | nil => true\n | cons k v es => p k v && all p es\n\n@[simp] theorem all_eq (p : α → β → Bool) (l : AssocList α β) :\n all p l = l.toList.all fun (a, b) => p a b := by induction l <;> simp [all, *]\n\n/-- Returns true if every entry in the list satisfies `p`. -/\ndef All (p : α → β → Prop) (l : AssocList α β) : Prop := ∀ a ∈ l.toList, p a.1 a.2\n\n/-- `O(n)`. Returns true if there is an element in the list whose key is equal to `a`. -/\n@[inline] def contains [BEq α] (a : α) (l : AssocList α β) : Bool := any (fun k _ => k == a) l\n\n@[simp] theorem contains_eq [BEq α] (a : α) (l : AssocList α β) :\n contains a l = l.toList.any (·.1 == a) := by\n induction l <;> simp [*, contains]\n\n/--\n`O(n)`. Replace the first entry in the list\nwith key equal to `a` to have key `a` and value `b`.\n-/\n@[simp] def replace [BEq α] (a : α) (b : β) : AssocList α β → AssocList α β\n | nil => nil\n | cons k v es => match k == a with\n | true => cons a b es\n | false => cons k v (replace a b es)\n\n@[simp] theorem replace_toList [BEq α] (a : α) (b : β) (l : AssocList α β) :\n (replace a b l).toList =\n l.toList.replaceF (bif ·.1 == a then some (a, b) else none) := by\n induction l <;> simp [replace]; split <;> simp [*]\n\n/-- `O(n)`. Remove the first entry in the list with key equal to `a`. -/\n@[specialize, simp] def eraseP (p : α → β → Bool) : AssocList α β → AssocList α β\n | nil => nil\n | cons k v es => bif p k v then es else cons k v (eraseP p es)\n\n@[simp] theorem eraseP_toList (p) (l : AssocList α β) :\n (eraseP p l).toList = l.toList.eraseP fun (a, b) => p a b := by\n induction l <;> simp [List.eraseP, cond]; split <;> simp [*]\n\n/-- `O(n)`. Remove the first entry in the list with key equal to `a`. -/\n@[inline] def erase [BEq α] (a : α) (l : AssocList α β) : AssocList α β :=\n eraseP (fun k _ => k == a) l\n\n@[simp] theorem erase_toList [BEq α] (a : α) (l : AssocList α β) :\n (erase a l).toList = l.toList.eraseP (·.1 == a) := eraseP_toList ..\n\n/-- The implementation of `ForIn`, which enables `for (k, v) in aList do ...` notation. -/\n@[specialize] protected def forIn [Monad m]\n (as : AssocList α β) (init : δ) (f : (α × β) → δ → m (ForInStep δ)) : m δ :=\n match as with\n | nil => pure init\n | cons k v es => do\n match (← f (k, v) init) with\n | ForInStep.done d => pure d\n | ForInStep.yield d => es.forIn d f\n\ninstance : ForIn m (AssocList α β) (α × β) where\n forIn := AssocList.forIn\n\n@[simp] theorem forIn_eq [Monad m] (l : AssocList α β) (init : δ)\n (f : (α × β) → δ → m (ForInStep δ)) : forIn l init f = forIn l.toList init f := by\n simp [forIn, List.forIn]\n induction l generalizing init <;> simp [AssocList.forIn, List.forIn.loop]\n congr; funext a; split <;> simp [*]\n\n/-- Split the list into head and tail, if possible. -/\ndef pop? : AssocList α β → Option ((α × β) × AssocList α β)\n | nil => none\n | cons a b l => some ((a, b), l)\n\ninstance : ToStream (AssocList α β) (AssocList α β) := ⟨fun x => x⟩\ninstance : Stream (AssocList α β) (α × β) := ⟨pop?⟩\n\n/-- Converts a list into an `AssocList`. This is the inverse function to `AssocList.toList`. -/\n@[simp] def _root_.List.toAssocList : List (α × β) → AssocList α β\n | [] => nil\n | (a,b) :: es => cons a b (toAssocList es)\n\n@[simp] theorem _root_.List.toAssocList_toList (l : List (α × β)) : l.toAssocList.toList = l := by\n induction l <;> simp [*]\n\n@[simp] theorem toList_toAssocList (l : AssocList α β) : l.toList.toAssocList = l := by\n induction l <;> simp [*]\n", "meta": {"author": "leanprover", "repo": "std4", "sha": "5507f9d8409f93b984ce04eccf4914d534e6fca2", "save_path": "github-repos/lean/leanprover-std4", "path": "github-repos/lean/leanprover-std4/std4-5507f9d8409f93b984ce04eccf4914d534e6fca2/Std/Data/AssocList.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.31405054499180746, "lm_q2_score": 0.10087863219102594, "lm_q1q2_score": 0.031680989417619786}} {"text": "/-\nCopyright (c) 2016 Jeremy Avigad. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Jeremy Avigad, Leonardo de Moura\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.default\nimport Mathlib.tactic.doc_commands\nimport Mathlib.tactic.reserved_notation\nimport Mathlib.PostPort\n\nuniverses u_1 u_2 u_3 u_4 u l w v \n\nnamespace Mathlib\n\n/-!\n# Basic logic properties\n\nThis file is one of the earliest imports in mathlib.\n\n## Implementation notes\n\nTheorems that require decidability hypotheses are in the namespace \"decidable\".\nClassical versions are in the namespace \"classical\".\n\nIn the presence of automation, this whole file may be unnecessary. On the other hand,\nmaybe it is useful for writing automation.\n-/\n\n/- We add the `inline` attribute to optimize VM computation using these declarations. For example,\n `if p ∧ q then ... else ...` will not evaluate the decidability of `q` if `p` is false. -/\n\n/-- An identity function with its main argument implicit. This will be printed as `hidden` even\nif it is applied to a large term, so it can be used for elision,\nas done in the `elide` and `unelide` tactics. -/\ndef hidden {α : Sort u_1} {a : α} : α := a\n\n/-- Ex falso, the nondependent eliminator for the `empty` type. -/\ndef empty.elim {C : Sort u_1} : empty → C := sorry\n\nprotected instance empty.subsingleton : subsingleton empty :=\n subsingleton.intro fun (a : empty) => empty.elim a\n\nprotected instance subsingleton.prod {α : Type u_1} {β : Type u_2} [subsingleton α]\n [subsingleton β] : subsingleton (α × β) :=\n subsingleton.intro\n fun (a b : α × β) =>\n prod.cases_on a\n fun (a_fst : α) (a_snd : β) =>\n prod.cases_on b\n fun (b_fst : α) (b_snd : β) =>\n (fun (fst fst_1 : α) (snd snd_1 : β) =>\n Eq.trans ((fun (fst : α) (snd : β) => Eq.refl (fst, snd)) fst snd)\n (congr (congr (Eq.refl Prod.mk) (subsingleton.elim fst fst_1))\n (subsingleton.elim snd snd_1)))\n a_fst b_fst a_snd b_snd\n\nprotected instance empty.decidable_eq : DecidableEq empty := fun (a : empty) => empty.elim a\n\nprotected instance sort.inhabited : Inhabited (Sort u_1) := { default := PUnit }\n\nprotected instance sort.inhabited' : Inhabited Inhabited.default := { default := PUnit.unit }\n\nprotected instance psum.inhabited_left {α : Sort u_1} {β : Sort u_2} [Inhabited α] :\n Inhabited (psum α β) :=\n { default := psum.inl Inhabited.default }\n\nprotected instance psum.inhabited_right {α : Sort u_1} {β : Sort u_2} [Inhabited β] :\n Inhabited (psum α β) :=\n { default := psum.inr Inhabited.default }\n\nprotected instance decidable_eq_of_subsingleton {α : Sort u_1} [subsingleton α] : DecidableEq α :=\n sorry\n\n@[simp] theorem eq_iff_true_of_subsingleton {α : Type u_1} [subsingleton α] (x : α) (y : α) :\n x = y ↔ True :=\n of_eq_true\n (Eq.trans (iff_eq_of_eq_true_right (Eq.refl True))\n (eq_true_intro (Eq.symm (subsingleton.elim y x))))\n\n/-- Add an instance to \"undo\" coercion transitivity into a chain of coercions, because\n most simp lemmas are stated with respect to simple coercions and will not match when\n part of a chain. -/\n@[simp] theorem coe_coe {α : Sort u_1} {β : Sort u_2} {γ : Sort u_3} [has_coe α β] [has_coe_t β γ]\n (a : α) : ↑a = ↑↑a :=\n rfl\n\ntheorem coe_fn_coe_trans {α : Sort u_1} {β : Sort u_2} {γ : Sort u_3} [has_coe α β]\n [has_coe_t_aux β γ] [has_coe_to_fun γ] (x : α) : ⇑x = ⇑↑x :=\n rfl\n\n@[simp] theorem coe_fn_coe_base {α : Sort u_1} {β : Sort u_2} [has_coe α β] [has_coe_to_fun β]\n (x : α) : ⇑x = ⇑↑x :=\n rfl\n\ntheorem coe_sort_coe_trans {α : Sort u_1} {β : Sort u_2} {γ : Sort u_3} [has_coe α β]\n [has_coe_t_aux β γ] [has_coe_to_sort γ] (x : α) : ↥x = ↥↑x :=\n rfl\n\n/--\nMany structures such as bundled morphisms coerce to functions so that you can\ntransparently apply them to arguments. For example, if `e : α ≃ β` and `a : α`\nthen you can write `e a` and this is elaborated as `⇑e a`. This type of\ncoercion is implemented using the `has_coe_to_fun` type class. There is one\nimportant consideration:\n\nIf a type coerces to another type which in turn coerces to a function,\nthen it **must** implement `has_coe_to_fun` directly:\n```lean\nstructure sparkling_equiv (α β) extends α ≃ β\n\n-- if we add a `has_coe` instance,\n\n-- if we add a `has_coe` instance,\ninstance {α β} : has_coe (sparkling_equiv α β) (α ≃ β) :=\n⟨sparkling_equiv.to_equiv⟩\n\n-- then a `has_coe_to_fun` instance **must** be added as well:\n\n-- then a `has_coe_to_fun` instance **must** be added as well:\ninstance {α β} : has_coe_to_fun (sparkling_equiv α β) :=\n⟨λ _, α → β, λ f, f.to_equiv.to_fun⟩\n```\n\n(Rationale: if we do not declare the direct coercion, then `⇑e a` is not in\nsimp-normal form. The lemma `coe_fn_coe_base` will unfold it to `⇑↑e a`. This\noften causes loops in the simplifier.)\n-/\n@[simp] theorem coe_sort_coe_base {α : Sort u_1} {β : Sort u_2} [has_coe α β] [has_coe_to_sort β]\n (x : α) : ↥x = ↥↑x :=\n rfl\n\n/-- `pempty` is the universe-polymorphic analogue of `empty`. -/\ninductive pempty where\n\n/-- Ex falso, the nondependent eliminator for the `pempty` type. -/\ndef pempty.elim {C : Sort u_1} : pempty → C := sorry\n\nprotected instance subsingleton_pempty : subsingleton pempty :=\n subsingleton.intro fun (a : pempty) => pempty.elim a\n\n@[simp] theorem not_nonempty_pempty : ¬Nonempty pempty :=\n fun (_x : Nonempty pempty) =>\n (fun (_a : Nonempty pempty) =>\n nonempty.dcases_on _a fun (val : pempty) => idRhs False (pempty.elim val))\n _x\n\n@[simp] theorem forall_pempty {P : pempty → Prop} : (∀ (x : pempty), P x) ↔ True :=\n { mp := fun (h : ∀ (x : pempty), P x) => trivial,\n mpr := fun (h : True) (x : pempty) => pempty.cases_on (fun (x : pempty) => P x) x }\n\n@[simp] theorem exists_pempty {P : pempty → Prop} : (∃ (x : pempty), P x) ↔ False := sorry\n\ntheorem congr_arg_heq {α : Sort u_1} {β : α → Sort u_2} (f : (a : α) → β a) {a₁ : α} {a₂ : α} :\n a₁ = a₂ → f a₁ == f a₂ :=\n sorry\n\ntheorem plift.down_inj {α : Sort u_1} (a : plift α) (b : plift α) :\n plift.down a = plift.down b → a = b :=\n sorry\n\n-- missing [symm] attribute for ne in core.\n\ntheorem ne_comm {α : Sort u_1} {a : α} {b : α} : a ≠ b ↔ b ≠ a := { mp := ne.symm, mpr := ne.symm }\n\n@[simp] theorem eq_iff_eq_cancel_left {α : Type u_1} {b : α} {c : α} :\n (∀ {a : α}, a = b ↔ a = c) ↔ b = c :=\n { mp :=\n fun (h : ∀ {a : α}, a = b ↔ a = c) =>\n eq.mpr (id (Eq._oldrec (Eq.refl (b = c)) (Eq.symm (propext h)))) (Eq.refl b),\n mpr :=\n fun (h : b = c) (a : α) =>\n eq.mpr (id (Eq._oldrec (Eq.refl (a = b ↔ a = c)) h)) (iff.refl (a = c)) }\n\n@[simp] theorem eq_iff_eq_cancel_right {α : Type u_1} {a : α} {b : α} :\n (∀ {c : α}, a = c ↔ b = c) ↔ a = b :=\n { mp :=\n fun (h : ∀ {c : α}, a = c ↔ b = c) =>\n eq.mpr (id (Eq._oldrec (Eq.refl (a = b)) (propext h))) (Eq.refl b),\n mpr :=\n fun (h : a = b) (a_1 : α) =>\n eq.mpr (id (Eq._oldrec (Eq.refl (a = a_1 ↔ b = a_1)) h)) (iff.refl (b = a_1)) }\n\n/-- Wrapper for adding elementary propositions to the type class systems.\nWarning: this can easily be abused. See the rest of this docstring for details.\n\nCertain propositions should not be treated as a class globally,\nbut sometimes it is very convenient to be able to use the type class system\nin specific circumstances.\n\nFor example, `zmod p` is a field if and only if `p` is a prime number.\nIn order to be able to find this field instance automatically by type class search,\nwe have to turn `p.prime` into an instance implicit assumption.\n\nOn the other hand, making `nat.prime` a class would require a major refactoring of the library,\nand it is questionable whether making `nat.prime` a class is desirable at all.\nThe compromise is to add the assumption `[fact p.prime]` to `zmod.field`.\n\nIn particular, this class is not intended for turning the type class system\ninto an automated theorem prover for first order logic. -/\ndef fact (p : Prop) := p\n\ntheorem fact.elim {p : Prop} (h : fact p) : p := h\n\n/-!\n### Declarations about propositional connectives\n-/\n\ntheorem false_ne_true : False ≠ True :=\n fun (ᾰ : False = True) => idRhs ((fun (_x : Prop) => _x) False) (Eq.symm ᾰ ▸ trivial)\n\n/-! ### Declarations about `implies` -/\n\ntheorem iff_of_eq {a : Prop} {b : Prop} (e : a = b) : a ↔ b := e ▸ iff.rfl\n\ntheorem iff_iff_eq {a : Prop} {b : Prop} : a ↔ b ↔ a = b := { mp := propext, mpr := iff_of_eq }\n\n@[simp] theorem eq_iff_iff {p : Prop} {q : Prop} : p = q ↔ (p ↔ q) := iff.symm iff_iff_eq\n\n@[simp] theorem imp_self {a : Prop} : a → a ↔ True := iff_true_intro id\n\ntheorem imp_intro {α : Prop} {β : Prop} (h : α) : β → α := fun (_x : β) => h\n\ntheorem imp_false {a : Prop} : a → False ↔ ¬a := iff.rfl\n\ntheorem imp_and_distrib {b : Prop} {c : Prop} {α : Sort u_1} : α → b ∧ c ↔ (α → b) ∧ (α → c) :=\n { mp :=\n fun (h : α → b ∧ c) =>\n { left := fun (ha : α) => and.left (h ha), right := fun (ha : α) => and.right (h ha) },\n mpr :=\n fun (h : (α → b) ∧ (α → c)) (ha : α) => { left := and.left h ha, right := and.right h ha } }\n\n@[simp] theorem and_imp {a : Prop} {b : Prop} {c : Prop} : a ∧ b → c ↔ a → b → c := sorry\n\ntheorem iff_def {a : Prop} {b : Prop} : a ↔ b ↔ (a → b) ∧ (b → a) := iff_iff_implies_and_implies a b\n\ntheorem iff_def' {a : Prop} {b : Prop} : a ↔ b ↔ (b → a) ∧ (a → b) := iff.trans iff_def and.comm\n\ntheorem imp_true_iff {α : Sort u_1} : α → True ↔ True := iff_true_intro fun (_x : α) => trivial\n\n@[simp] theorem imp_iff_right {a : Prop} {b : Prop} (ha : a) : a → b ↔ b :=\n { mp := fun (f : a → b) => f ha, mpr := imp_intro }\n\n/-! ### Declarations about `not` -/\n\n/-- Ex falso for negation. From `¬ a` and `a` anything follows. This is the same as `absurd` with\nthe arguments flipped, but it is in the `not` namespace so that projection notation can be used. -/\ndef not.elim {a : Prop} {α : Sort u_1} (H1 : ¬a) (H2 : a) : α := absurd H2 H1\n\ntheorem not.imp {a : Prop} {b : Prop} (H2 : ¬b) (H1 : a → b) : ¬a := mt H1 H2\n\ntheorem not_not_of_not_imp {a : Prop} {b : Prop} : ¬(a → b) → ¬¬a := mt not.elim\n\ntheorem not_of_not_imp {b : Prop} {a : Prop} : ¬(a → b) → ¬b := mt imp_intro\n\ntheorem dec_em (p : Prop) [Decidable p] : p ∨ ¬p := decidable.em p\n\ntheorem em (p : Prop) : p ∨ ¬p := classical.em p\n\ntheorem or_not {p : Prop} : p ∨ ¬p := em p\n\ntheorem by_contradiction {p : Prop} : (¬p → False) → p := decidable.by_contradiction\n\n-- alias by_contradiction ← by_contra\n\ntheorem by_contra {p : Prop} : (¬p → False) → p := decidable.by_contradiction\n\n/--\nIn most of mathlib, we use the law of excluded middle (LEM) and the axiom of choice (AC) freely.\nThe `decidable` namespace contains versions of lemmas from the root namespace that explicitly\nattempt to avoid the axiom of choice, usually by adding decidability assumptions on the inputs.\n\nYou can check if a lemma uses the axiom of choice by using `#print axioms foo` and seeing if\n`classical.choice` appears in the list.\n-/\n-- See Note [decidable namespace]\n\nprotected theorem decidable.not_not {a : Prop} [Decidable a] : ¬¬a ↔ a :=\n { mp := decidable.by_contradiction, mpr := not_not_intro }\n\n/-- The Double Negation Theorem: `¬ ¬ P` is equivalent to `P`.\nThe left-to-right direction, double negation elimination (DNE),\nis classically true but not constructively. -/\n@[simp] theorem not_not {a : Prop} : ¬¬a ↔ a := decidable.not_not\n\ntheorem of_not_not {a : Prop} : ¬¬a → a := by_contra\n\n-- See Note [decidable namespace]\n\nprotected theorem decidable.of_not_imp {a : Prop} {b : Prop} [Decidable a] (h : ¬(a → b)) : a :=\n decidable.by_contradiction (not_not_of_not_imp h)\n\ntheorem of_not_imp {a : Prop} {b : Prop} : ¬(a → b) → a := decidable.of_not_imp\n\n-- See Note [decidable namespace]\n\nprotected theorem decidable.not_imp_symm {a : Prop} {b : Prop} [Decidable a] (h : ¬a → b)\n (hb : ¬b) : a :=\n decidable.by_contradiction (hb ∘ h)\n\ntheorem not.decidable_imp_symm {a : Prop} {b : Prop} [Decidable a] : (¬a → b) → ¬b → a :=\n decidable.not_imp_symm\n\ntheorem not.imp_symm {a : Prop} {b : Prop} : (¬a → b) → ¬b → a := not.decidable_imp_symm\n\n-- See Note [decidable namespace]\n\nprotected theorem decidable.not_imp_comm {a : Prop} {b : Prop} [Decidable a] [Decidable b] :\n ¬a → b ↔ ¬b → a :=\n { mp := not.decidable_imp_symm, mpr := not.decidable_imp_symm }\n\ntheorem not_imp_comm {a : Prop} {b : Prop} : ¬a → b ↔ ¬b → a := decidable.not_imp_comm\n\n@[simp] theorem imp_not_self {a : Prop} : a → ¬a ↔ ¬a :=\n { mp := fun (h : a → ¬a) (ha : a) => h ha ha, mpr := fun (h : ¬a) (_x : a) => h }\n\ntheorem decidable.not_imp_self {a : Prop} [Decidable a] : ¬a → a ↔ a :=\n eq.mp (Eq._oldrec (Eq.refl (¬a → ¬¬a ↔ ¬¬a)) (propext decidable.not_not)) imp_not_self\n\n@[simp] theorem not_imp_self {a : Prop} : ¬a → a ↔ a := decidable.not_imp_self\n\ntheorem imp.swap {a : Prop} {b : Prop} {c : Prop} : a → b → c ↔ b → a → c :=\n { mp := function.swap, mpr := function.swap }\n\ntheorem imp_not_comm {a : Prop} {b : Prop} : a → ¬b ↔ b → ¬a := imp.swap\n\n/-! ### Declarations about `and` -/\n\ntheorem and_congr_left {a : Prop} {b : Prop} {c : Prop} (h : c → (a ↔ b)) : a ∧ c ↔ b ∧ c :=\n iff.trans and.comm (iff.trans (and_congr_right h) and.comm)\n\ntheorem and_congr_left' {a : Prop} {b : Prop} {c : Prop} (h : a ↔ b) : a ∧ c ↔ b ∧ c :=\n and_congr h iff.rfl\n\ntheorem and_congr_right' {a : Prop} {b : Prop} {c : Prop} (h : b ↔ c) : a ∧ b ↔ a ∧ c :=\n and_congr iff.rfl h\n\ntheorem not_and_of_not_left {a : Prop} (b : Prop) : ¬a → ¬(a ∧ b) := mt and.left\n\ntheorem not_and_of_not_right (a : Prop) {b : Prop} : ¬b → ¬(a ∧ b) := mt and.right\n\ntheorem and.imp_left {a : Prop} {b : Prop} {c : Prop} (h : a → b) : a ∧ c → b ∧ c := and.imp h id\n\ntheorem and.imp_right {a : Prop} {b : Prop} {c : Prop} (h : a → b) : c ∧ a → c ∧ b := and.imp id h\n\ntheorem and.right_comm {a : Prop} {b : Prop} {c : Prop} : (a ∧ b) ∧ c ↔ (a ∧ c) ∧ b := sorry\n\ntheorem and.rotate {a : Prop} {b : Prop} {c : Prop} : a ∧ b ∧ c ↔ b ∧ c ∧ a := sorry\n\ntheorem and_not_self_iff (a : Prop) : a ∧ ¬a ↔ False :=\n { mp := fun (h : a ∧ ¬a) => and.right h (and.left h), mpr := fun (h : False) => false.elim h }\n\ntheorem not_and_self_iff (a : Prop) : ¬a ∧ a ↔ False := sorry\n\ntheorem and_iff_left_of_imp {a : Prop} {b : Prop} (h : a → b) : a ∧ b ↔ a :=\n { mp := and.left, mpr := fun (ha : a) => { left := ha, right := h ha } }\n\ntheorem and_iff_right_of_imp {a : Prop} {b : Prop} (h : b → a) : a ∧ b ↔ b :=\n { mp := and.right, mpr := fun (hb : b) => { left := h hb, right := hb } }\n\n@[simp] theorem and_iff_left_iff_imp {a : Prop} {b : Prop} : a ∧ b ↔ a ↔ a → b :=\n { mp := fun (h : a ∧ b ↔ a) (ha : a) => and.right (iff.mpr h ha), mpr := and_iff_left_of_imp }\n\n@[simp] theorem and_iff_right_iff_imp {a : Prop} {b : Prop} : a ∧ b ↔ b ↔ b → a :=\n { mp := fun (h : a ∧ b ↔ b) (ha : b) => and.left (iff.mpr h ha), mpr := and_iff_right_of_imp }\n\n@[simp] theorem and.congr_right_iff {a : Prop} {b : Prop} {c : Prop} :\n a ∧ b ↔ a ∧ c ↔ a → (b ↔ c) :=\n sorry\n\n@[simp] theorem and.congr_left_iff {a : Prop} {b : Prop} {c : Prop} : a ∧ c ↔ b ∧ c ↔ c → (a ↔ b) :=\n sorry\n\n@[simp] theorem and_self_left {a : Prop} {b : Prop} : a ∧ a ∧ b ↔ a ∧ b :=\n { mp := fun (h : a ∧ a ∧ b) => { left := and.left h, right := and.right (and.right h) },\n mpr :=\n fun (h : a ∧ b) =>\n { left := and.left h, right := { left := and.left h, right := and.right h } } }\n\n@[simp] theorem and_self_right {a : Prop} {b : Prop} : (a ∧ b) ∧ b ↔ a ∧ b :=\n { mp := fun (h : (a ∧ b) ∧ b) => { left := and.left (and.left h), right := and.right h },\n mpr :=\n fun (h : a ∧ b) =>\n { left := { left := and.left h, right := and.right h }, right := and.right h } }\n\n/-! ### Declarations about `or` -/\n\ntheorem or_congr_left {a : Prop} {b : Prop} {c : Prop} (h : a ↔ b) : a ∨ c ↔ b ∨ c :=\n or_congr h iff.rfl\n\ntheorem or_congr_right {a : Prop} {b : Prop} {c : Prop} (h : b ↔ c) : a ∨ b ↔ a ∨ c :=\n or_congr iff.rfl h\n\ntheorem or.right_comm {a : Prop} {b : Prop} {c : Prop} : (a ∨ b) ∨ c ↔ (a ∨ c) ∨ b :=\n eq.mpr (id (Eq._oldrec (Eq.refl ((a ∨ b) ∨ c ↔ (a ∨ c) ∨ b)) (propext (or_assoc a b))))\n (eq.mpr (id (Eq._oldrec (Eq.refl (a ∨ b ∨ c ↔ (a ∨ c) ∨ b)) (propext (or_assoc a c))))\n (eq.mpr (id (Eq._oldrec (Eq.refl (a ∨ b ∨ c ↔ a ∨ c ∨ b)) (propext (or_comm b c))))\n (iff.refl (a ∨ c ∨ b))))\n\ntheorem or_of_or_of_imp_of_imp {a : Prop} {b : Prop} {c : Prop} {d : Prop} (h₁ : a ∨ b) (h₂ : a → c)\n (h₃ : b → d) : c ∨ d :=\n or.imp h₂ h₃ h₁\n\ntheorem or_of_or_of_imp_left {a : Prop} {b : Prop} {c : Prop} (h₁ : a ∨ c) (h : a → b) : b ∨ c :=\n or.imp_left h h₁\n\ntheorem or_of_or_of_imp_right {a : Prop} {b : Prop} {c : Prop} (h₁ : c ∨ a) (h : a → b) : c ∨ b :=\n or.imp_right h h₁\n\ntheorem or.elim3 {a : Prop} {b : Prop} {c : Prop} {d : Prop} (h : a ∨ b ∨ c) (ha : a → d)\n (hb : b → d) (hc : c → d) : d :=\n or.elim h ha fun (h₂ : b ∨ c) => or.elim h₂ hb hc\n\ntheorem or_imp_distrib {a : Prop} {b : Prop} {c : Prop} : a ∨ b → c ↔ (a → c) ∧ (b → c) := sorry\n\n-- See Note [decidable namespace]\n\nprotected theorem decidable.or_iff_not_imp_left {a : Prop} {b : Prop} [Decidable a] :\n a ∨ b ↔ ¬a → b :=\n { mp := or.resolve_left, mpr := fun (h : ¬a → b) => dite a Or.inl (Or.inr ∘ h) }\n\ntheorem or_iff_not_imp_left {a : Prop} {b : Prop} : a ∨ b ↔ ¬a → b := decidable.or_iff_not_imp_left\n\n-- See Note [decidable namespace]\n\nprotected theorem decidable.or_iff_not_imp_right {a : Prop} {b : Prop} [Decidable b] :\n a ∨ b ↔ ¬b → a :=\n iff.trans or.comm decidable.or_iff_not_imp_left\n\ntheorem or_iff_not_imp_right {a : Prop} {b : Prop} : a ∨ b ↔ ¬b → a :=\n decidable.or_iff_not_imp_right\n\n-- See Note [decidable namespace]\n\nprotected theorem decidable.not_imp_not {a : Prop} {b : Prop} [Decidable a] : ¬a → ¬b ↔ b → a :=\n { mp := fun (h : ¬a → ¬b) (hb : b) => decidable.by_contradiction fun (na : ¬a) => h na hb,\n mpr := mt }\n\ntheorem not_imp_not {a : Prop} {b : Prop} : ¬a → ¬b ↔ b → a := decidable.not_imp_not\n\n@[simp] theorem or_iff_left_iff_imp {a : Prop} {b : Prop} : a ∨ b ↔ a ↔ b → a :=\n { mp := fun (h : a ∨ b ↔ a) (hb : b) => iff.mp h (Or.inr hb), mpr := or_iff_left_of_imp }\n\n@[simp] theorem or_iff_right_iff_imp {a : Prop} {b : Prop} : a ∨ b ↔ b ↔ a → b :=\n eq.mpr (id (Eq._oldrec (Eq.refl (a ∨ b ↔ b ↔ a → b)) (propext (or_comm a b))))\n (eq.mpr (id (Eq._oldrec (Eq.refl (b ∨ a ↔ b ↔ a → b)) (propext or_iff_left_iff_imp)))\n (iff.refl (a → b)))\n\n/-! ### Declarations about distributivity -/\n\n/-- `∧` distributes over `∨` (on the left). -/\ntheorem and_or_distrib_left {a : Prop} {b : Prop} {c : Prop} : a ∧ (b ∨ c) ↔ a ∧ b ∨ a ∧ c := sorry\n\n/-- `∧` distributes over `∨` (on the right). -/\ntheorem or_and_distrib_right {a : Prop} {b : Prop} {c : Prop} : (a ∨ b) ∧ c ↔ a ∧ c ∨ b ∧ c :=\n iff.trans (iff.trans and.comm and_or_distrib_left) (or_congr and.comm and.comm)\n\n/-- `∨` distributes over `∧` (on the left). -/\ntheorem or_and_distrib_left {a : Prop} {b : Prop} {c : Prop} : a ∨ b ∧ c ↔ (a ∨ b) ∧ (a ∨ c) :=\n { mp :=\n Or._oldrec (fun (ha : a) => { left := Or.inl ha, right := Or.inl ha })\n (and.imp Or.inr Or.inr),\n mpr := And._oldrec (Or._oldrec (imp_intro ∘ Or.inl) (or.imp_right ∘ And.intro)) }\n\n/-- `∨` distributes over `∧` (on the right). -/\ntheorem and_or_distrib_right {a : Prop} {b : Prop} {c : Prop} : a ∧ b ∨ c ↔ (a ∨ c) ∧ (b ∨ c) :=\n iff.trans (iff.trans or.comm or_and_distrib_left) (and_congr or.comm or.comm)\n\n@[simp] theorem or_self_left {a : Prop} {b : Prop} : a ∨ a ∨ b ↔ a ∨ b :=\n { mp := fun (h : a ∨ a ∨ b) => or.elim h Or.inl id,\n mpr := fun (h : a ∨ b) => or.elim h Or.inl (Or.inr ∘ Or.inr) }\n\n@[simp] theorem or_self_right {a : Prop} {b : Prop} : (a ∨ b) ∨ b ↔ a ∨ b :=\n { mp := fun (h : (a ∨ b) ∨ b) => or.elim h id Or.inr,\n mpr := fun (h : a ∨ b) => or.elim h (Or.inl ∘ Or.inl) Or.inr }\n\n/-! Declarations about `iff` -/\n\ntheorem iff_of_true {a : Prop} {b : Prop} (ha : a) (hb : b) : a ↔ b :=\n { mp := fun (_x : a) => hb, mpr := fun (_x : b) => ha }\n\ntheorem iff_of_false {a : Prop} {b : Prop} (ha : ¬a) (hb : ¬b) : a ↔ b :=\n { mp := not.elim ha, mpr := not.elim hb }\n\ntheorem iff_true_left {a : Prop} {b : Prop} (ha : a) : a ↔ b ↔ b :=\n { mp := fun (h : a ↔ b) => iff.mp h ha, mpr := iff_of_true ha }\n\ntheorem iff_true_right {a : Prop} {b : Prop} (ha : a) : b ↔ a ↔ b :=\n iff.trans iff.comm (iff_true_left ha)\n\ntheorem iff_false_left {a : Prop} {b : Prop} (ha : ¬a) : a ↔ b ↔ ¬b :=\n { mp := fun (h : a ↔ b) => mt (iff.mpr h) ha, mpr := iff_of_false ha }\n\ntheorem iff_false_right {a : Prop} {b : Prop} (ha : ¬a) : b ↔ a ↔ ¬b :=\n iff.trans iff.comm (iff_false_left ha)\n\n-- See Note [decidable namespace]\n\nprotected theorem decidable.not_or_of_imp {a : Prop} {b : Prop} [Decidable a] (h : a → b) :\n ¬a ∨ b :=\n dite a (fun (ha : a) => Or.inr (h ha)) fun (ha : ¬a) => Or.inl ha\n\ntheorem not_or_of_imp {a : Prop} {b : Prop} : (a → b) → ¬a ∨ b := decidable.not_or_of_imp\n\n-- See Note [decidable namespace]\n\nprotected theorem decidable.imp_iff_not_or {a : Prop} {b : Prop} [Decidable a] : a → b ↔ ¬a ∨ b :=\n { mp := decidable.not_or_of_imp, mpr := or.neg_resolve_left }\n\ntheorem imp_iff_not_or {a : Prop} {b : Prop} : a → b ↔ ¬a ∨ b := decidable.imp_iff_not_or\n\n-- See Note [decidable namespace]\n\nprotected theorem decidable.imp_or_distrib {a : Prop} {b : Prop} {c : Prop} [Decidable a] :\n a → b ∨ c ↔ (a → b) ∨ (a → c) :=\n sorry\n\ntheorem imp_or_distrib {a : Prop} {b : Prop} {c : Prop} : a → b ∨ c ↔ (a → b) ∨ (a → c) :=\n decidable.imp_or_distrib\n\n-- See Note [decidable namespace]\n\nprotected theorem decidable.imp_or_distrib' {a : Prop} {b : Prop} {c : Prop} [Decidable b] :\n a → b ∨ c ↔ (a → b) ∨ (a → c) :=\n sorry\n\ntheorem imp_or_distrib' {a : Prop} {b : Prop} {c : Prop} : a → b ∨ c ↔ (a → b) ∨ (a → c) :=\n decidable.imp_or_distrib'\n\ntheorem not_imp_of_and_not {a : Prop} {b : Prop} : a ∧ ¬b → ¬(a → b) :=\n fun (ᾰ : a ∧ ¬b) (ᾰ_1 : a → b) =>\n and.dcases_on ᾰ fun (ᾰ_left : a) (ᾰ_right : ¬b) => idRhs False (ᾰ_right (ᾰ_1 ᾰ_left))\n\n-- See Note [decidable namespace]\n\nprotected theorem decidable.not_imp {a : Prop} {b : Prop} [Decidable a] : ¬(a → b) ↔ a ∧ ¬b :=\n { mp := fun (h : ¬(a → b)) => { left := decidable.of_not_imp h, right := not_of_not_imp h },\n mpr := not_imp_of_and_not }\n\ntheorem not_imp {a : Prop} {b : Prop} : ¬(a → b) ↔ a ∧ ¬b := decidable.not_imp\n\n-- for monotonicity\n\ntheorem imp_imp_imp {a : Prop} {b : Prop} {c : Prop} {d : Prop} (h₀ : c → a) (h₁ : b → d) :\n (a → b) → c → d :=\n fun (h₂ : a → b) => h₁ ∘ h₂ ∘ h₀\n\n-- See Note [decidable namespace]\n\nprotected theorem decidable.peirce (a : Prop) (b : Prop) [Decidable a] : ((a → b) → a) → a :=\n dite a (fun (ha : a) (h : (a → b) → a) => ha) fun (ha : ¬a) (h : (a → b) → a) => h (not.elim ha)\n\ntheorem peirce (a : Prop) (b : Prop) : ((a → b) → a) → a := decidable.peirce a b\n\ntheorem peirce' {a : Prop} (H : ∀ (b : Prop), (a → b) → a) : a := H a id\n\n-- See Note [decidable namespace]\n\nprotected theorem decidable.not_iff_not {a : Prop} {b : Prop} [Decidable a] [Decidable b] :\n ¬a ↔ ¬b ↔ (a ↔ b) :=\n eq.mpr (id (Eq._oldrec (Eq.refl (¬a ↔ ¬b ↔ (a ↔ b))) (propext iff_def)))\n (eq.mpr (id (Eq._oldrec (Eq.refl ((¬a → ¬b) ∧ (¬b → ¬a) ↔ (a ↔ b))) (propext iff_def')))\n (and_congr decidable.not_imp_not decidable.not_imp_not))\n\ntheorem not_iff_not {a : Prop} {b : Prop} : ¬a ↔ ¬b ↔ (a ↔ b) := decidable.not_iff_not\n\n-- See Note [decidable namespace]\n\nprotected theorem decidable.not_iff_comm {a : Prop} {b : Prop} [Decidable a] [Decidable b] :\n ¬a ↔ b ↔ (¬b ↔ a) :=\n eq.mpr (id (Eq._oldrec (Eq.refl (¬a ↔ b ↔ (¬b ↔ a))) (propext iff_def)))\n (eq.mpr (id (Eq._oldrec (Eq.refl ((¬a → b) ∧ (b → ¬a) ↔ (¬b ↔ a))) (propext iff_def)))\n (and_congr decidable.not_imp_comm imp_not_comm))\n\ntheorem not_iff_comm {a : Prop} {b : Prop} : ¬a ↔ b ↔ (¬b ↔ a) := decidable.not_iff_comm\n\n-- See Note [decidable namespace]\n\nprotected theorem decidable.not_iff {a : Prop} {b : Prop} [Decidable b] : ¬(a ↔ b) ↔ (¬a ↔ b) :=\n sorry\n\ntheorem not_iff {a : Prop} {b : Prop} : ¬(a ↔ b) ↔ (¬a ↔ b) := decidable.not_iff\n\n-- See Note [decidable namespace]\n\nprotected theorem decidable.iff_not_comm {a : Prop} {b : Prop} [Decidable a] [Decidable b] :\n a ↔ ¬b ↔ (b ↔ ¬a) :=\n eq.mpr (id (Eq._oldrec (Eq.refl (a ↔ ¬b ↔ (b ↔ ¬a))) (propext iff_def)))\n (eq.mpr (id (Eq._oldrec (Eq.refl ((a → ¬b) ∧ (¬b → a) ↔ (b ↔ ¬a))) (propext iff_def)))\n (and_congr imp_not_comm decidable.not_imp_comm))\n\ntheorem iff_not_comm {a : Prop} {b : Prop} : a ↔ ¬b ↔ (b ↔ ¬a) := decidable.iff_not_comm\n\n-- See Note [decidable namespace]\n\nprotected theorem decidable.iff_iff_and_or_not_and_not {a : Prop} {b : Prop} [Decidable b] :\n a ↔ b ↔ a ∧ b ∨ ¬a ∧ ¬b :=\n sorry\n\ntheorem iff_iff_and_or_not_and_not {a : Prop} {b : Prop} : a ↔ b ↔ a ∧ b ∨ ¬a ∧ ¬b :=\n decidable.iff_iff_and_or_not_and_not\n\ntheorem decidable.iff_iff_not_or_and_or_not {a : Prop} {b : Prop} [Decidable a] [Decidable b] :\n a ↔ b ↔ (¬a ∨ b) ∧ (a ∨ ¬b) :=\n sorry\n\ntheorem iff_iff_not_or_and_or_not {a : Prop} {b : Prop} : a ↔ b ↔ (¬a ∨ b) ∧ (a ∨ ¬b) :=\n decidable.iff_iff_not_or_and_or_not\n\n-- See Note [decidable namespace]\n\nprotected theorem decidable.not_and_not_right {a : Prop} {b : Prop} [Decidable b] :\n ¬(a ∧ ¬b) ↔ a → b :=\n sorry\n\ntheorem not_and_not_right {a : Prop} {b : Prop} : ¬(a ∧ ¬b) ↔ a → b := decidable.not_and_not_right\n\n/-- Transfer decidability of `a` to decidability of `b`, if the propositions are equivalent.\n**Important**: this function should be used instead of `rw` on `decidable b`, because the\nkernel will get stuck reducing the usage of `propext` otherwise,\nand `dec_trivial` will not work. -/\ndef decidable_of_iff {b : Prop} (a : Prop) (h : a ↔ b) [D : Decidable a] : Decidable b :=\n decidable_of_decidable_of_iff D h\n\n/-- Transfer decidability of `b` to decidability of `a`, if the propositions are equivalent.\nThis is the same as `decidable_of_iff` but the iff is flipped. -/\ndef decidable_of_iff' {a : Prop} (b : Prop) (h : a ↔ b) [D : Decidable b] : Decidable a :=\n decidable_of_decidable_of_iff D (iff.symm h)\n\n/-- Prove that `a` is decidable by constructing a boolean `b` and a proof that `b ↔ a`.\n(This is sometimes taken as an alternate definition of decidability.) -/\ndef decidable_of_bool {a : Prop} (b : Bool) (h : ↥b ↔ a) : Decidable a := sorry\n\n/-! ### De Morgan's laws -/\n\ntheorem not_and_of_not_or_not {a : Prop} {b : Prop} (h : ¬a ∨ ¬b) : ¬(a ∧ b) :=\n fun (ᾰ : a ∧ b) =>\n and.dcases_on ᾰ\n fun (ᾰ_left : a) (ᾰ_right : b) => idRhs False (or.elim h (absurd ᾰ_left) (absurd ᾰ_right))\n\n-- See Note [decidable namespace]\n\nprotected theorem decidable.not_and_distrib {a : Prop} {b : Prop} [Decidable a] :\n ¬(a ∧ b) ↔ ¬a ∨ ¬b :=\n sorry\n\n-- See Note [decidable namespace]\n\nprotected theorem decidable.not_and_distrib' {a : Prop} {b : Prop} [Decidable b] :\n ¬(a ∧ b) ↔ ¬a ∨ ¬b :=\n sorry\n\n/-- One of de Morgan's laws: the negation of a conjunction is logically equivalent to the\ndisjunction of the negations. -/\ntheorem not_and_distrib {a : Prop} {b : Prop} : ¬(a ∧ b) ↔ ¬a ∨ ¬b := decidable.not_and_distrib\n\n@[simp] theorem not_and {a : Prop} {b : Prop} : ¬(a ∧ b) ↔ a → ¬b := and_imp\n\ntheorem not_and' {a : Prop} {b : Prop} : ¬(a ∧ b) ↔ b → ¬a := iff.trans not_and imp_not_comm\n\n/-- One of de Morgan's laws: the negation of a disjunction is logically equivalent to the\nconjunction of the negations. -/\ntheorem not_or_distrib {a : Prop} {b : Prop} : ¬(a ∨ b) ↔ ¬a ∧ ¬b := sorry\n\n-- See Note [decidable namespace]\n\nprotected theorem decidable.or_iff_not_and_not {a : Prop} {b : Prop} [Decidable a] [Decidable b] :\n a ∨ b ↔ ¬(¬a ∧ ¬b) :=\n eq.mpr (id (Eq._oldrec (Eq.refl (a ∨ b ↔ ¬(¬a ∧ ¬b))) (Eq.symm (propext not_or_distrib))))\n (eq.mpr (id (Eq._oldrec (Eq.refl (a ∨ b ↔ ¬¬(a ∨ b))) (propext decidable.not_not)))\n (iff.refl (a ∨ b)))\n\ntheorem or_iff_not_and_not {a : Prop} {b : Prop} : a ∨ b ↔ ¬(¬a ∧ ¬b) :=\n decidable.or_iff_not_and_not\n\n-- See Note [decidable namespace]\n\nprotected theorem decidable.and_iff_not_or_not {a : Prop} {b : Prop} [Decidable a] [Decidable b] :\n a ∧ b ↔ ¬(¬a ∨ ¬b) :=\n eq.mpr\n (id (Eq._oldrec (Eq.refl (a ∧ b ↔ ¬(¬a ∨ ¬b))) (Eq.symm (propext decidable.not_and_distrib))))\n (eq.mpr (id (Eq._oldrec (Eq.refl (a ∧ b ↔ ¬¬(a ∧ b))) (propext decidable.not_not)))\n (iff.refl (a ∧ b)))\n\ntheorem and_iff_not_or_not {a : Prop} {b : Prop} : a ∧ b ↔ ¬(¬a ∨ ¬b) :=\n decidable.and_iff_not_or_not\n\n/-! ### Declarations about equality -/\n\n@[simp] theorem heq_iff_eq {α : Sort u_1} {a : α} {b : α} : a == b ↔ a = b :=\n { mp := eq_of_heq, mpr := heq_of_eq }\n\ntheorem proof_irrel_heq {p : Prop} {q : Prop} (hp : p) (hq : q) : hp == hq :=\n (fun (this : p = q) => Eq._oldrec (fun (hq : p) => HEq.refl hp) this hq)\n (propext { mp := fun (_x : p) => hq, mpr := fun (_x : q) => hp })\n\ntheorem ne_of_mem_of_not_mem {α : outParam (Type u_1)} {β : Type u_2} [has_mem α β] {s : β} {a : α}\n {b : α} (h : a ∈ s) : ¬b ∈ s → a ≠ b :=\n mt fun (e : a = b) => e ▸ h\n\ntheorem eq_equivalence {α : Sort u_1} : equivalence Eq :=\n { left := Eq.refl, right := { left := Eq.symm, right := Eq.trans } }\n\n/-- Transport through trivial families is the identity. -/\n@[simp] theorem eq_rec_constant {α : Sort u_1} {a : α} {a' : α} {β : Sort u_2} (y : β)\n (h : a = a') : Eq._oldrec y h = y :=\n sorry\n\n@[simp] theorem eq_mp_rfl {α : Sort u_1} {a : α} : eq.mp (Eq.refl α) a = a := rfl\n\n@[simp] theorem eq_mpr_rfl {α : Sort u_1} {a : α} : eq.mpr (Eq.refl α) a = a := rfl\n\ntheorem heq_of_eq_mp {α : Sort u_1} {β : Sort u_1} {a : α} {a' : β} (e : α = β)\n (h₂ : eq.mp e a = a') : a == a' :=\n sorry\n\ntheorem rec_heq_of_heq {α : Sort u_1} {a : α} {b : α} {β : Sort u_2} {C : α → Sort u_2} {x : C a}\n {y : β} (eq : a = b) (h : x == y) : Eq._oldrec x eq == y :=\n eq.drec h eq\n\n@[simp] theorem eq_mpr_heq {α : Sort u} {β : Sort u} (h : β = α) (x : α) : eq.mpr h x == x :=\n eq.drec (fun (x : β) => HEq.refl (eq.mpr (Eq.refl β) x)) h x\n\nprotected theorem eq.congr {α : Sort u_1} {x₁ : α} {x₂ : α} {y₁ : α} {y₂ : α} (h₁ : x₁ = y₁)\n (h₂ : x₂ = y₂) : x₁ = x₂ ↔ y₁ = y₂ :=\n Eq._oldrec (Eq._oldrec (iff.refl (x₁ = x₂)) h₂) h₁\n\ntheorem eq.congr_left {α : Sort u_1} {x : α} {y : α} {z : α} (h : x = y) : x = z ↔ y = z :=\n eq.mpr (id (Eq._oldrec (Eq.refl (x = z ↔ y = z)) h)) (iff.refl (y = z))\n\ntheorem eq.congr_right {α : Sort u_1} {x : α} {y : α} {z : α} (h : x = y) : z = x ↔ z = y :=\n eq.mpr (id (Eq._oldrec (Eq.refl (z = x ↔ z = y)) h)) (iff.refl (z = y))\n\ntheorem congr_arg2 {α : Type u_1} {β : Type u_2} {γ : Type u_3} (f : α → β → γ) {x : α} {x' : α}\n {y : β} {y' : β} (hx : x = x') (hy : y = y') : f x y = f x' y' :=\n Eq._oldrec (Eq._oldrec (Eq.refl (f x y)) hy) hx\n\n/-! ### Declarations about quantifiers -/\n\ntheorem forall_imp {α : Sort u_1} {p : α → Prop} {q : α → Prop} (h : ∀ (a : α), p a → q a) :\n (∀ (a : α), p a) → ∀ (a : α), q a :=\n fun (h' : ∀ (a : α), p a) (a : α) => h a (h' a)\n\ntheorem forall₂_congr {α : Sort u_1} {β : Sort u_2} {p : α → β → Prop} {q : α → β → Prop}\n (h : ∀ (a : α) (b : β), p a b ↔ q a b) :\n (∀ (a : α) (b : β), p a b) ↔ ∀ (a : α) (b : β), q a b :=\n forall_congr fun (a : α) => forall_congr (h a)\n\ntheorem forall₃_congr {α : Sort u_1} {β : Sort u_2} {γ : Sort u_3} {p : α → β → γ → Prop}\n {q : α → β → γ → Prop} (h : ∀ (a : α) (b : β) (c : γ), p a b c ↔ q a b c) :\n (∀ (a : α) (b : β) (c : γ), p a b c) ↔ ∀ (a : α) (b : β) (c : γ), q a b c :=\n forall_congr fun (a : α) => forall₂_congr (h a)\n\ntheorem forall₄_congr {α : Sort u_1} {β : Sort u_2} {γ : Sort u_3} {δ : Sort u_4}\n {p : α → β → γ → δ → Prop} {q : α → β → γ → δ → Prop}\n (h : ∀ (a : α) (b : β) (c : γ) (d : δ), p a b c d ↔ q a b c d) :\n (∀ (a : α) (b : β) (c : γ) (d : δ), p a b c d) ↔ ∀ (a : α) (b : β) (c : γ) (d : δ), q a b c d :=\n forall_congr fun (a : α) => forall₃_congr (h a)\n\ntheorem Exists.imp {α : Sort u_1} {q : α → Prop} {p : α → Prop} (h : ∀ (a : α), p a → q a) :\n (∃ (a : α), p a) → ∃ (a : α), q a :=\n fun (p_1 : ∃ (a : α), p a) => exists_imp_exists h p_1\n\ntheorem exists_imp_exists' {α : Sort u_1} {β : Sort u_2} {p : α → Prop} {q : β → Prop} (f : α → β)\n (hpq : ∀ (a : α), p a → q (f a)) (hp : ∃ (a : α), p a) : ∃ (b : β), q b :=\n exists.elim hp fun (a : α) (hp' : p a) => Exists.intro (f a) (hpq a hp')\n\ntheorem exists₂_congr {α : Sort u_1} {β : Sort u_2} {p : α → β → Prop} {q : α → β → Prop}\n (h : ∀ (a : α) (b : β), p a b ↔ q a b) :\n (∃ (a : α), ∃ (b : β), p a b) ↔ ∃ (a : α), ∃ (b : β), q a b :=\n exists_congr fun (a : α) => exists_congr (h a)\n\ntheorem exists₃_congr {α : Sort u_1} {β : Sort u_2} {γ : Sort u_3} {p : α → β → γ → Prop}\n {q : α → β → γ → Prop} (h : ∀ (a : α) (b : β) (c : γ), p a b c ↔ q a b c) :\n (∃ (a : α), ∃ (b : β), ∃ (c : γ), p a b c) ↔ ∃ (a : α), ∃ (b : β), ∃ (c : γ), q a b c :=\n exists_congr fun (a : α) => exists₂_congr (h a)\n\ntheorem exists₄_congr {α : Sort u_1} {β : Sort u_2} {γ : Sort u_3} {δ : Sort u_4}\n {p : α → β → γ → δ → Prop} {q : α → β → γ → δ → Prop}\n (h : ∀ (a : α) (b : β) (c : γ) (d : δ), p a b c d ↔ q a b c d) :\n (∃ (a : α), ∃ (b : β), ∃ (c : γ), ∃ (d : δ), p a b c d) ↔\n ∃ (a : α), ∃ (b : β), ∃ (c : γ), ∃ (d : δ), q a b c d :=\n exists_congr fun (a : α) => exists₃_congr (h a)\n\ntheorem forall_swap {α : Sort u_1} {β : Sort u_2} {p : α → β → Prop} :\n (∀ (x : α) (y : β), p x y) ↔ ∀ (y : β) (x : α), p x y :=\n { mp := function.swap, mpr := function.swap }\n\ntheorem exists_swap {α : Sort u_1} {β : Sort u_2} {p : α → β → Prop} :\n (∃ (x : α), ∃ (y : β), p x y) ↔ ∃ (y : β), ∃ (x : α), p x y :=\n sorry\n\n@[simp] theorem exists_imp_distrib {α : Sort u_1} {p : α → Prop} {b : Prop} :\n (∃ (x : α), p x) → b ↔ ∀ (x : α), p x → b :=\n sorry\n\n/--\nExtract an element from a existential statement, using `classical.some`.\n-/\n-- This enables projection notation.\n\ndef Exists.some {α : Sort u_1} {p : α → Prop} (P : ∃ (a : α), p a) : α := classical.some P\n\n/--\nShow that an element extracted from `P : ∃ a, p a` using `P.some` satisfies `p`.\n-/\ntheorem Exists.some_spec {α : Sort u_1} {p : α → Prop} (P : ∃ (a : α), p a) : p (Exists.some P) :=\n classical.some_spec P\n\n--theorem forall_not_of_not_exists (h : ¬ ∃ x, p x) : ∀ x, ¬ p x :=\n\n--forall_imp_of_exists_imp h\n\ntheorem not_exists_of_forall_not {α : Sort u_1} {p : α → Prop} (h : ∀ (x : α), ¬p x) :\n ¬∃ (x : α), p x :=\n iff.mpr exists_imp_distrib h\n\n@[simp] theorem not_exists {α : Sort u_1} {p : α → Prop} : (¬∃ (x : α), p x) ↔ ∀ (x : α), ¬p x :=\n exists_imp_distrib\n\ntheorem not_forall_of_exists_not {α : Sort u_1} {p : α → Prop} :\n (∃ (x : α), ¬p x) → ¬∀ (x : α), p x :=\n fun (ᾰ : ∃ (x : α), ¬p x) (ᾰ_1 : ∀ (x : α), p x) =>\n Exists.dcases_on ᾰ fun (ᾰ_w : α) (ᾰ_h : ¬p ᾰ_w) => idRhs False (ᾰ_h (ᾰ_1 ᾰ_w))\n\n-- See Note [decidable namespace]\n\nprotected theorem decidable.not_forall {α : Sort u_1} {p : α → Prop} [Decidable (∃ (x : α), ¬p x)]\n [(x : α) → Decidable (p x)] : (¬∀ (x : α), p x) ↔ ∃ (x : α), ¬p x :=\n sorry\n\n@[simp] theorem not_forall {α : Sort u_1} {p : α → Prop} : (¬∀ (x : α), p x) ↔ ∃ (x : α), ¬p x :=\n decidable.not_forall\n\n-- See Note [decidable namespace]\n\nprotected theorem decidable.not_forall_not {α : Sort u_1} {p : α → Prop}\n [Decidable (∃ (x : α), p x)] : (¬∀ (x : α), ¬p x) ↔ ∃ (x : α), p x :=\n iff.mp decidable.not_iff_comm not_exists\n\ntheorem not_forall_not {α : Sort u_1} {p : α → Prop} : (¬∀ (x : α), ¬p x) ↔ ∃ (x : α), p x :=\n decidable.not_forall_not\n\n-- See Note [decidable namespace]\n\nprotected theorem decidable.not_exists_not {α : Sort u_1} {p : α → Prop}\n [(x : α) → Decidable (p x)] : (¬∃ (x : α), ¬p x) ↔ ∀ (x : α), p x :=\n sorry\n\n@[simp] theorem not_exists_not {α : Sort u_1} {p : α → Prop} :\n (¬∃ (x : α), ¬p x) ↔ ∀ (x : α), p x :=\n decidable.not_exists_not\n\n@[simp] theorem forall_true_iff {α : Sort u_1} : α → True ↔ True :=\n iff_true_intro fun (_x : α) => trivial\n\n-- Unfortunately this causes simp to loop sometimes, so we\n\n-- add the 2 and 3 cases as simp lemmas instead\n\ntheorem forall_true_iff' {α : Sort u_1} {p : α → Prop} (h : ∀ (a : α), p a ↔ True) :\n (∀ (a : α), p a) ↔ True :=\n iff_true_intro fun (_x : α) => of_iff_true (h _x)\n\n@[simp] theorem forall_2_true_iff {α : Sort u_1} {β : α → Sort u_2} :\n (∀ (a : α), β a → True) ↔ True :=\n forall_true_iff' fun (_x : α) => forall_true_iff\n\n@[simp] theorem forall_3_true_iff {α : Sort u_1} {β : α → Sort u_2} {γ : (a : α) → β a → Sort u_3} :\n (∀ (a : α) (b : β a), γ a b → True) ↔ True :=\n forall_true_iff' fun (_x : α) => forall_2_true_iff\n\n@[simp] theorem forall_const {b : Prop} (α : Sort u_1) [i : Nonempty α] : α → b ↔ b :=\n { mp := nonempty.elim i, mpr := fun (hb : b) (x : α) => hb }\n\n@[simp] theorem exists_const {b : Prop} (α : Sort u_1) [i : Nonempty α] : (∃ (x : α), b) ↔ b :=\n { mp :=\n fun (_x : ∃ (x : α), b) =>\n (fun (_a : ∃ (x : α), b) => Exists.dcases_on _a fun (w : α) (h : b) => idRhs b h) _x,\n mpr := nonempty.elim i exists.intro }\n\ntheorem forall_and_distrib {α : Sort u_1} {p : α → Prop} {q : α → Prop} :\n (∀ (x : α), p x ∧ q x) ↔ (∀ (x : α), p x) ∧ ∀ (x : α), q x :=\n sorry\n\ntheorem exists_or_distrib {α : Sort u_1} {p : α → Prop} {q : α → Prop} :\n (∃ (x : α), p x ∨ q x) ↔ (∃ (x : α), p x) ∨ ∃ (x : α), q x :=\n sorry\n\n@[simp] theorem exists_and_distrib_left {α : Sort u_1} {q : Prop} {p : α → Prop} :\n (∃ (x : α), q ∧ p x) ↔ q ∧ ∃ (x : α), p x :=\n sorry\n\n@[simp] theorem exists_and_distrib_right {α : Sort u_1} {q : Prop} {p : α → Prop} :\n (∃ (x : α), p x ∧ q) ↔ (∃ (x : α), p x) ∧ q :=\n sorry\n\n@[simp] theorem forall_eq {α : Sort u_1} {p : α → Prop} {a' : α} :\n (∀ (a : α), a = a' → p a) ↔ p a' :=\n { mp := fun (h : ∀ (a : α), a = a' → p a) => h a' rfl,\n mpr := fun (h : p a') (a : α) (e : a = a') => Eq.symm e ▸ h }\n\n@[simp] theorem forall_eq' {α : Sort u_1} {p : α → Prop} {a' : α} :\n (∀ (a : α), a' = a → p a) ↔ p a' :=\n sorry\n\n-- this lemma is needed to simplify the output of `list.mem_cons_iff`\n\n@[simp] theorem forall_eq_or_imp {α : Sort u_1} {p : α → Prop} {q : α → Prop} {a' : α} :\n (∀ (a : α), a = a' ∨ q a → p a) ↔ p a' ∧ ∀ (a : α), q a → p a :=\n sorry\n\n@[simp] theorem exists_eq {α : Sort u_1} {a' : α} : ∃ (a : α), a = a' := Exists.intro a' rfl\n\n@[simp] theorem exists_eq' {α : Sort u_1} {a' : α} : ∃ (a : α), a' = a := Exists.intro a' rfl\n\n@[simp] theorem exists_eq_left {α : Sort u_1} {p : α → Prop} {a' : α} :\n (∃ (a : α), a = a' ∧ p a) ↔ p a' :=\n sorry\n\n@[simp] theorem exists_eq_right {α : Sort u_1} {p : α → Prop} {a' : α} :\n (∃ (a : α), p a ∧ a = a') ↔ p a' :=\n iff.trans (exists_congr fun (a : α) => and.comm) exists_eq_left\n\n@[simp] theorem exists_eq_right_right {α : Sort u_1} {p : α → Prop} {b : Prop} {a' : α} :\n (∃ (a : α), p a ∧ b ∧ a = a') ↔ p a' ∧ b :=\n sorry\n\n@[simp] theorem exists_eq_right_right' {α : Sort u_1} {p : α → Prop} {b : Prop} {a' : α} :\n (∃ (a : α), p a ∧ b ∧ a' = a) ↔ p a' ∧ b :=\n sorry\n\n@[simp] theorem exists_apply_eq_apply {α : Type u_1} {β : Type u_2} (f : α → β) (a' : α) :\n ∃ (a : α), f a = f a' :=\n Exists.intro a' rfl\n\n@[simp] theorem exists_apply_eq_apply' {α : Type u_1} {β : Type u_2} (f : α → β) (a' : α) :\n ∃ (a : α), f a' = f a :=\n Exists.intro a' rfl\n\n@[simp] theorem exists_exists_and_eq_and {α : Sort u_1} {β : Sort u_2} {f : α → β} {p : α → Prop}\n {q : β → Prop} : (∃ (b : β), (∃ (a : α), p a ∧ f a = b) ∧ q b) ↔ ∃ (a : α), p a ∧ q (f a) :=\n sorry\n\n@[simp] theorem exists_exists_eq_and {α : Sort u_1} {β : Sort u_2} {f : α → β} {p : β → Prop} :\n (∃ (b : β), (∃ (a : α), f a = b) ∧ p b) ↔ ∃ (a : α), p (f a) :=\n sorry\n\n@[simp] theorem forall_apply_eq_imp_iff {α : Sort u_1} {β : Sort u_2} {f : α → β} {p : β → Prop} :\n (∀ (a : α) (b : β), f a = b → p b) ↔ ∀ (a : α), p (f a) :=\n { mp := fun (h : ∀ (a : α) (b : β), f a = b → p b) (a : α) => h a (f a) rfl,\n mpr := fun (h : ∀ (a : α), p (f a)) (a : α) (b : β) (hab : f a = b) => hab ▸ h a }\n\n@[simp] theorem forall_apply_eq_imp_iff' {α : Sort u_1} {β : Sort u_2} {f : α → β} {p : β → Prop} :\n (∀ (b : β) (a : α), f a = b → p b) ↔ ∀ (a : α), p (f a) :=\n sorry\n\n@[simp] theorem forall_eq_apply_imp_iff {α : Sort u_1} {β : Sort u_2} {f : α → β} {p : β → Prop} :\n (∀ (a : α) (b : β), b = f a → p b) ↔ ∀ (a : α), p (f a) :=\n sorry\n\n@[simp] theorem forall_eq_apply_imp_iff' {α : Sort u_1} {β : Sort u_2} {f : α → β} {p : β → Prop} :\n (∀ (b : β) (a : α), b = f a → p b) ↔ ∀ (a : α), p (f a) :=\n sorry\n\n@[simp] theorem forall_apply_eq_imp_iff₂ {α : Sort u_1} {β : Sort u_2} {f : α → β} {p : α → Prop}\n {q : β → Prop} : (∀ (b : β) (a : α), p a → f a = b → q b) ↔ ∀ (a : α), p a → q (f a) :=\n { mp := fun (h : ∀ (b : β) (a : α), p a → f a = b → q b) (a : α) (ha : p a) => h (f a) a ha rfl,\n mpr :=\n fun (h : ∀ (a : α), p a → q (f a)) (b : β) (a : α) (ha : p a) (hb : f a = b) => hb ▸ h a ha }\n\n@[simp] theorem exists_eq_left' {α : Sort u_1} {p : α → Prop} {a' : α} :\n (∃ (a : α), a' = a ∧ p a) ↔ p a' :=\n sorry\n\n@[simp] theorem exists_eq_right' {α : Sort u_1} {p : α → Prop} {a' : α} :\n (∃ (a : α), p a ∧ a' = a) ↔ p a' :=\n sorry\n\ntheorem exists_comm {α : Sort u_1} {β : Sort u_2} {p : α → β → Prop} :\n (∃ (a : α), ∃ (b : β), p a b) ↔ ∃ (b : β), ∃ (a : α), p a b :=\n sorry\n\ntheorem forall_or_of_or_forall {α : Sort u_1} {p : α → Prop} {b : Prop} (h : b ∨ ∀ (x : α), p x)\n (x : α) : b ∨ p x :=\n or.imp_right (fun (h₂ : ∀ (x : α), p x) => h₂ x) h\n\n-- See Note [decidable namespace]\n\nprotected theorem decidable.forall_or_distrib_left {α : Sort u_1} {q : Prop} {p : α → Prop}\n [Decidable q] : (∀ (x : α), q ∨ p x) ↔ q ∨ ∀ (x : α), p x :=\n sorry\n\ntheorem forall_or_distrib_left {α : Sort u_1} {q : Prop} {p : α → Prop} :\n (∀ (x : α), q ∨ p x) ↔ q ∨ ∀ (x : α), p x :=\n decidable.forall_or_distrib_left\n\n-- See Note [decidable namespace]\n\nprotected theorem decidable.forall_or_distrib_right {α : Sort u_1} {q : Prop} {p : α → Prop}\n [Decidable q] : (∀ (x : α), p x ∨ q) ↔ (∀ (x : α), p x) ∨ q :=\n sorry\n\ntheorem forall_or_distrib_right {α : Sort u_1} {q : Prop} {p : α → Prop} :\n (∀ (x : α), p x ∨ q) ↔ (∀ (x : α), p x) ∨ q :=\n decidable.forall_or_distrib_right\n\n/-- A predicate holds everywhere on the image of a surjective functions iff\n it holds everywhere. -/\ntheorem forall_iff_forall_surj {α : Type u_1} {β : Type u_2} {f : α → β} (h : function.surjective f)\n {P : β → Prop} : (∀ (a : α), P (f a)) ↔ ∀ (b : β), P b :=\n sorry\n\n@[simp] theorem exists_prop {p : Prop} {q : Prop} : (∃ (h : p), q) ↔ p ∧ q := sorry\n\n@[simp] theorem exists_false {α : Sort u_1} : ¬∃ (a : α), False :=\n fun (_x : ∃ (a : α), False) =>\n (fun (_a : ∃ (a : α), False) => Exists.dcases_on _a fun (w : α) (h : False) => idRhs False h) _x\n\n@[simp] theorem exists_unique_false {α : Sort u_1} : ¬exists_unique fun (a : α) => False := sorry\n\ntheorem Exists.fst {b : Prop} {p : b → Prop} : Exists p → b :=\n fun (ᾰ : Exists p) => Exists.dcases_on ᾰ fun (ᾰ_w : b) (ᾰ_h : p ᾰ_w) => idRhs b ᾰ_w\n\ntheorem Exists.snd {b : Prop} {p : b → Prop} (h : Exists p) : p (Exists.fst h) :=\n Exists.dcases_on h fun (h_w : b) (h_h : p h_w) => idRhs (p h_w) h_h\n\n@[simp] theorem forall_prop_of_true {p : Prop} {q : p → Prop} (h : p) : (∀ (h' : p), q h') ↔ q h :=\n forall_const p\n\n@[simp] theorem exists_prop_of_true {p : Prop} {q : p → Prop} (h : p) : (∃ (h' : p), q h') ↔ q h :=\n exists_const p\n\n@[simp] theorem forall_prop_of_false {p : Prop} {q : p → Prop} (hn : ¬p) :\n (∀ (h' : p), q h') ↔ True :=\n iff_true_intro fun (h : p) => not.elim hn h\n\n@[simp] theorem exists_prop_of_false {p : Prop} {q : p → Prop} : ¬p → ¬∃ (h' : p), q h' :=\n mt Exists.fst\n\ntheorem exists_unique.exists {α : Sort u_1} {p : α → Prop} (h : exists_unique fun (x : α) => p x) :\n ∃ (x : α), p x :=\n exists.elim h\n fun (x : α) (hx : (fun (x : α) => p x) x ∧ ∀ (y : α), p y → y = x) =>\n Exists.intro x (and.left hx)\n\ntheorem exists_unique.unique {α : Sort u_1} {p : α → Prop} (h : exists_unique fun (x : α) => p x)\n {y₁ : α} {y₂ : α} (py₁ : p y₁) (py₂ : p y₂) : y₁ = y₂ :=\n unique_of_exists_unique h py₁ py₂\n\n@[simp] theorem exists_unique_iff_exists {α : Sort u_1} [subsingleton α] {p : α → Prop} :\n (exists_unique fun (x : α) => p x) ↔ ∃ (x : α), p x :=\n { mp := fun (h : exists_unique fun (x : α) => p x) => exists_unique.exists h,\n mpr :=\n Exists.imp\n fun (x : α) (hx : p x) =>\n { left := hx, right := fun (y : α) (_x : p y) => subsingleton.elim y x } }\n\ntheorem exists_unique.elim2 {α : Sort u_1} {p : α → Sort u_2} [∀ (x : α), subsingleton (p x)]\n {q : (x : α) → p x → Prop} {b : Prop}\n (h₂ : exists_unique fun (x : α) => exists_unique fun (h : p x) => q x h)\n (h₁ : ∀ (x : α) (h : p x), q x h → (∀ (y : α) (hy : p y), q y hy → y = x) → b) : b :=\n sorry\n\ntheorem exists_unique.intro2 {α : Sort u_1} {p : α → Sort u_2} [∀ (x : α), subsingleton (p x)]\n {q : (x : α) → p x → Prop} (w : α) (hp : p w) (hq : q w hp)\n (H : ∀ (y : α) (hy : p y), q y hy → y = w) :\n exists_unique fun (x : α) => exists_unique fun (hx : p x) => q x hx :=\n sorry\n\ntheorem exists_unique.exists2 {α : Sort u_1} {p : α → Sort u_2} {q : (x : α) → p x → Prop}\n (h : exists_unique fun (x : α) => exists_unique fun (hx : p x) => q x hx) :\n ∃ (x : α), ∃ (hx : p x), q x hx :=\n Exists.imp (fun (x : α) (hx : exists_unique fun (hx : p x) => q x hx) => exists_unique.exists hx)\n (exists_unique.exists h)\n\ntheorem exists_unique.unique2 {α : Sort u_1} {p : α → Sort u_2} [∀ (x : α), subsingleton (p x)]\n {q : (x : α) → p x → Prop}\n (h : exists_unique fun (x : α) => exists_unique fun (hx : p x) => q x hx) {y₁ : α} {y₂ : α}\n (hpy₁ : p y₁) (hqy₁ : q y₁ hpy₁) (hpy₂ : p y₂) (hqy₂ : q y₂ hpy₂) : y₁ = y₂ :=\n sorry\n\n/-! ### Classical lemmas -/\n\nnamespace classical\n\n\ntheorem cases {p : Prop → Prop} (h1 : p True) (h2 : p False) (a : Prop) : p a := cases_on a h1 h2\n\n/- use shortened names to avoid conflict when classical namespace is open. -/\n\ntheorem dec (p : Prop) : Decidable p := prop_decidable p\n\ntheorem dec_pred {α : Sort u_1} (p : α → Prop) : decidable_pred p :=\n fun (a : α) => prop_decidable (p a)\n\ntheorem dec_rel {α : Sort u_1} (p : α → α → Prop) : DecidableRel p :=\n fun (a b : α) => prop_decidable (p a b)\n\ntheorem dec_eq (α : Sort u_1) : DecidableEq α := fun (a b : α) => prop_decidable (a = b)\n\n/--\nWe make decidability results that depends on `classical.choice` noncomputable lemmas.\n* We have to mark them as noncomputable, because otherwise Lean will try to generate bytecode\n for them, and fail because it depends on `classical.choice`.\n* We make them lemmas, and not definitions, because otherwise later definitions will raise\n \\\"failed to generate bytecode\\\" errors when writing something like\n `letI := classical.dec_eq _`.\nCf. \n-/\n/-- Construct a function from a default value `H0`, and a function to use if there exists a value\nsatisfying the predicate. -/\ndef exists_cases {α : Sort u_1} {p : α → Prop} {C : Sort u} (H0 : C) (H : (a : α) → p a → C) : C :=\n dite (∃ (a : α), p a) (fun (h : ∃ (a : α), p a) => H (some h) sorry)\n fun (h : ¬∃ (a : α), p a) => H0\n\ntheorem some_spec2 {α : Sort u_1} {p : α → Prop} {h : ∃ (a : α), p a} (q : α → Prop)\n (hpq : ∀ (a : α), p a → q a) : q (some h) :=\n hpq (some h) (some_spec h)\n\n/-- A version of classical.indefinite_description which is definitionally equal to a pair -/\ndef subtype_of_exists {α : Type u_1} {P : α → Prop} (h : ∃ (x : α), P x) :\n Subtype fun (x : α) => P x :=\n { val := some h, property := sorry }\n\nend classical\n\n\n/-- This function has the same type as `exists.rec_on`, and can be used to case on an equality,\nbut `exists.rec_on` can only eliminate into Prop, while this version eliminates into any universe\nusing the axiom of choice. -/\ndef exists.classical_rec_on {α : Sort u_1} {p : α → Prop} (h : ∃ (a : α), p a) {C : Sort u}\n (H : (a : α) → p a → C) : C :=\n H (classical.some h) sorry\n\n/-! ### Declarations about bounded quantifiers -/\n\ntheorem bex_def {α : Sort u_1} {p : α → Prop} {q : α → Prop} :\n (∃ (x : α), ∃ (h : p x), q x) ↔ ∃ (x : α), p x ∧ q x :=\n sorry\n\ntheorem bex.elim {α : Sort u_1} {p : α → Prop} {P : (x : α) → p x → Prop} {b : Prop} :\n (∃ (x : α), ∃ (h : p x), P x h) → (∀ (a : α) (h : p a), P a h → b) → b :=\n sorry\n\ntheorem bex.intro {α : Sort u_1} {p : α → Prop} {P : (x : α) → p x → Prop} (a : α) (h₁ : p a)\n (h₂ : P a h₁) : ∃ (x : α), ∃ (h : p x), P x h :=\n Exists.intro a (Exists.intro h₁ h₂)\n\ntheorem ball_congr {α : Sort u_1} {p : α → Prop} {P : (x : α) → p x → Prop}\n {Q : (x : α) → p x → Prop} (H : ∀ (x : α) (h : p x), P x h ↔ Q x h) :\n (∀ (x : α) (h : p x), P x h) ↔ ∀ (x : α) (h : p x), Q x h :=\n forall_congr fun (x : α) => forall_congr (H x)\n\ntheorem bex_congr {α : Sort u_1} {p : α → Prop} {P : (x : α) → p x → Prop}\n {Q : (x : α) → p x → Prop} (H : ∀ (x : α) (h : p x), P x h ↔ Q x h) :\n (∃ (x : α), ∃ (h : p x), P x h) ↔ ∃ (x : α), ∃ (h : p x), Q x h :=\n exists_congr fun (x : α) => exists_congr (H x)\n\ntheorem bex_eq_left {α : Sort u_1} {p : α → Prop} {a : α} :\n (∃ (x : α), ∃ (_x : x = a), p x) ↔ p a :=\n sorry\n\ntheorem ball.imp_right {α : Sort u_1} {p : α → Prop} {P : (x : α) → p x → Prop}\n {Q : (x : α) → p x → Prop} (H : ∀ (x : α) (h : p x), P x h → Q x h)\n (h₁ : ∀ (x : α) (h : p x), P x h) (x : α) (h : p x) : Q x h :=\n H x h (h₁ x h)\n\ntheorem bex.imp_right {α : Sort u_1} {p : α → Prop} {P : (x : α) → p x → Prop}\n {Q : (x : α) → p x → Prop} (H : ∀ (x : α) (h : p x), P x h → Q x h) :\n (∃ (x : α), ∃ (h : p x), P x h) → ∃ (x : α), ∃ (h : p x), Q x h :=\n sorry\n\ntheorem ball.imp_left {α : Sort u_1} {r : α → Prop} {p : α → Prop} {q : α → Prop}\n (H : ∀ (x : α), p x → q x) (h₁ : ∀ (x : α), q x → r x) (x : α) (h : p x) : r x :=\n h₁ x (H x h)\n\ntheorem bex.imp_left {α : Sort u_1} {r : α → Prop} {p : α → Prop} {q : α → Prop}\n (H : ∀ (x : α), p x → q x) : (∃ (x : α), ∃ (_x : p x), r x) → ∃ (x : α), ∃ (_x : q x), r x :=\n sorry\n\ntheorem ball_of_forall {α : Sort u_1} {p : α → Prop} (h : ∀ (x : α), p x) (x : α) : p x := h x\n\ntheorem forall_of_ball {α : Sort u_1} {p : α → Prop} {q : α → Prop} (H : ∀ (x : α), p x)\n (h : ∀ (x : α), p x → q x) (x : α) : q x :=\n h x (H x)\n\ntheorem bex_of_exists {α : Sort u_1} {p : α → Prop} {q : α → Prop} (H : ∀ (x : α), p x) :\n (∃ (x : α), q x) → ∃ (x : α), ∃ (_x : p x), q x :=\n fun (ᾰ : ∃ (x : α), q x) =>\n Exists.dcases_on ᾰ\n fun (ᾰ_w : α) (ᾰ_h : q ᾰ_w) =>\n idRhs (∃ (x : α), ∃ (_x : p x), q x) (Exists.intro ᾰ_w (Exists.intro (H ᾰ_w) ᾰ_h))\n\ntheorem exists_of_bex {α : Sort u_1} {p : α → Prop} {q : α → Prop} :\n (∃ (x : α), ∃ (_x : p x), q x) → ∃ (x : α), q x :=\n sorry\n\n@[simp] theorem bex_imp_distrib {α : Sort u_1} {p : α → Prop} {P : (x : α) → p x → Prop}\n {b : Prop} : (∃ (x : α), ∃ (h : p x), P x h) → b ↔ ∀ (x : α) (h : p x), P x h → b :=\n sorry\n\ntheorem not_bex {α : Sort u_1} {p : α → Prop} {P : (x : α) → p x → Prop} :\n (¬∃ (x : α), ∃ (h : p x), P x h) ↔ ∀ (x : α) (h : p x), ¬P x h :=\n bex_imp_distrib\n\ntheorem not_ball_of_bex_not {α : Sort u_1} {p : α → Prop} {P : (x : α) → p x → Prop} :\n (∃ (x : α), ∃ (h : p x), ¬P x h) → ¬∀ (x : α) (h : p x), P x h :=\n sorry\n\n-- See Note [decidable namespace]\n\nprotected theorem decidable.not_ball {α : Sort u_1} {p : α → Prop} {P : (x : α) → p x → Prop}\n [Decidable (∃ (x : α), ∃ (h : p x), ¬P x h)] [(x : α) → (h : p x) → Decidable (P x h)] :\n (¬∀ (x : α) (h : p x), P x h) ↔ ∃ (x : α), ∃ (h : p x), ¬P x h :=\n sorry\n\ntheorem not_ball {α : Sort u_1} {p : α → Prop} {P : (x : α) → p x → Prop} :\n (¬∀ (x : α) (h : p x), P x h) ↔ ∃ (x : α), ∃ (h : p x), ¬P x h :=\n decidable.not_ball\n\ntheorem ball_true_iff {α : Sort u_1} (p : α → Prop) : (∀ (x : α), p x → True) ↔ True :=\n iff_true_intro fun (h : α) (hrx : p h) => trivial\n\ntheorem ball_and_distrib {α : Sort u_1} {p : α → Prop} {P : (x : α) → p x → Prop}\n {Q : (x : α) → p x → Prop} :\n (∀ (x : α) (h : p x), P x h ∧ Q x h) ↔\n (∀ (x : α) (h : p x), P x h) ∧ ∀ (x : α) (h : p x), Q x h :=\n iff.trans (forall_congr fun (x : α) => forall_and_distrib) forall_and_distrib\n\ntheorem bex_or_distrib {α : Sort u_1} {p : α → Prop} {P : (x : α) → p x → Prop}\n {Q : (x : α) → p x → Prop} :\n (∃ (x : α), ∃ (h : p x), P x h ∨ Q x h) ↔\n (∃ (x : α), ∃ (h : p x), P x h) ∨ ∃ (x : α), ∃ (h : p x), Q x h :=\n iff.trans (exists_congr fun (x : α) => exists_or_distrib) exists_or_distrib\n\ntheorem ball_or_left_distrib {α : Sort u_1} {r : α → Prop} {p : α → Prop} {q : α → Prop} :\n (∀ (x : α), p x ∨ q x → r x) ↔ (∀ (x : α), p x → r x) ∧ ∀ (x : α), q x → r x :=\n iff.trans (forall_congr fun (x : α) => or_imp_distrib) forall_and_distrib\n\ntheorem bex_or_left_distrib {α : Sort u_1} {r : α → Prop} {p : α → Prop} {q : α → Prop} :\n (∃ (x : α), ∃ (_x : p x ∨ q x), r x) ↔\n (∃ (x : α), ∃ (_x : p x), r x) ∨ ∃ (x : α), ∃ (_x : q x), r x :=\n sorry\n\nnamespace classical\n\n\ntheorem not_ball {α : Sort u_1} {p : α → Prop} {P : (x : α) → p x → Prop} :\n (¬∀ (x : α) (h : p x), P x h) ↔ ∃ (x : α), ∃ (h : p x), ¬P x h :=\n not_ball\n\nend classical\n\n\ntheorem ite_eq_iff {α : Sort u_1} {p : Prop} [Decidable p] {a : α} {b : α} {c : α} :\n ite p a b = c ↔ p ∧ a = c ∨ ¬p ∧ b = c :=\n sorry\n\n@[simp] theorem ite_eq_left_iff {α : Sort u_1} {p : Prop} [Decidable p] {a : α} {b : α} :\n ite p a b = a ↔ ¬p → b = a :=\n sorry\n\n@[simp] theorem ite_eq_right_iff {α : Sort u_1} {p : Prop} [Decidable p] {a : α} {b : α} :\n ite p a b = b ↔ p → a = b :=\n sorry\n\n/-! ### Declarations about `nonempty` -/\n\nprotected instance has_zero.nonempty {α : Type u} [HasZero α] : Nonempty α := Nonempty.intro 0\n\nprotected instance has_one.nonempty {α : Type u} [HasOne α] : Nonempty α := Nonempty.intro 1\n\ntheorem exists_true_iff_nonempty {α : Sort u_1} : (∃ (a : α), True) ↔ Nonempty α := sorry\n\n@[simp] theorem nonempty_Prop {p : Prop} : Nonempty p ↔ p :=\n { mp :=\n fun (_x : Nonempty p) =>\n (fun (_a : Nonempty p) => nonempty.dcases_on _a fun (val : p) => idRhs p val) _x,\n mpr := fun (h : p) => Nonempty.intro h }\n\ntheorem not_nonempty_iff_imp_false {α : Type u} : ¬Nonempty α ↔ α → False := sorry\n\n@[simp] theorem nonempty_sigma {α : Type u} {γ : α → Type w} :\n Nonempty (sigma fun (a : α) => γ a) ↔ ∃ (a : α), Nonempty (γ a) :=\n sorry\n\n@[simp] theorem nonempty_subtype {α : Sort u} {p : α → Prop} :\n Nonempty (Subtype p) ↔ ∃ (a : α), p a :=\n sorry\n\n@[simp] theorem nonempty_prod {α : Type u} {β : Type v} :\n Nonempty (α × β) ↔ Nonempty α ∧ Nonempty β :=\n sorry\n\n@[simp] theorem nonempty_pprod {α : Sort u} {β : Sort v} :\n Nonempty (PProd α β) ↔ Nonempty α ∧ Nonempty β :=\n sorry\n\n@[simp] theorem nonempty_sum {α : Type u} {β : Type v} :\n Nonempty (α ⊕ β) ↔ Nonempty α ∨ Nonempty β :=\n sorry\n\n@[simp] theorem nonempty_psum {α : Sort u} {β : Sort v} :\n Nonempty (psum α β) ↔ Nonempty α ∨ Nonempty β :=\n sorry\n\n@[simp] theorem nonempty_psigma {α : Sort u} {β : α → Sort v} :\n Nonempty (psigma β) ↔ ∃ (a : α), Nonempty (β a) :=\n sorry\n\n@[simp] theorem nonempty_empty : ¬Nonempty empty :=\n fun (_x : Nonempty empty) =>\n (fun (_a : Nonempty empty) =>\n nonempty.dcases_on _a fun (val : empty) => idRhs False (empty.elim val))\n _x\n\n@[simp] theorem nonempty_ulift {α : Type u} : Nonempty (ulift α) ↔ Nonempty α := sorry\n\n@[simp] theorem nonempty_plift {α : Sort u} : Nonempty (plift α) ↔ Nonempty α := sorry\n\n@[simp] theorem nonempty.forall {α : Sort u} {p : Nonempty α → Prop} :\n (∀ (h : Nonempty α), p h) ↔ ∀ (a : α), p (Nonempty.intro a) :=\n sorry\n\n@[simp] theorem nonempty.exists {α : Sort u} {p : Nonempty α → Prop} :\n (∃ (h : Nonempty α), p h) ↔ ∃ (a : α), p (Nonempty.intro a) :=\n sorry\n\ntheorem classical.nonempty_pi {α : Sort u} {β : α → Sort v} :\n Nonempty ((a : α) → β a) ↔ ∀ (a : α), Nonempty (β a) :=\n sorry\n\n/-- Using `classical.choice`, lifts a (`Prop`-valued) `nonempty` instance to a (`Type`-valued)\n `inhabited` instance. `classical.inhabited_of_nonempty` already exists, in\n `core/init/classical.lean`, but the assumption is not a type class argument,\n which makes it unsuitable for some applications. -/\ndef classical.inhabited_of_nonempty' {α : Sort u} [h : Nonempty α] : Inhabited α :=\n { default := Classical.choice h }\n\n/-- Using `classical.choice`, extracts a term from a `nonempty` type. -/\nprotected def nonempty.some {α : Sort u} (h : Nonempty α) : α := Classical.choice h\n\n/-- Using `classical.choice`, extracts a term from a `nonempty` type. -/\nprotected def classical.arbitrary (α : Sort u) [h : Nonempty α] : α := Classical.choice h\n\n/-- Given `f : α → β`, if `α` is nonempty then `β` is also nonempty.\n `nonempty` cannot be a `functor`, because `functor` is restricted to `Type`. -/\ntheorem nonempty.map {α : Sort u} {β : Sort v} (f : α → β) : Nonempty α → Nonempty β :=\n fun (ᾰ : Nonempty α) =>\n nonempty.dcases_on ᾰ fun (ᾰ : α) => idRhs (Nonempty β) (Nonempty.intro (f ᾰ))\n\nprotected theorem nonempty.map2 {α : Sort u_1} {β : Sort u_2} {γ : Sort u_3} (f : α → β → γ) :\n Nonempty α → Nonempty β → Nonempty γ :=\n fun (ᾰ : Nonempty α) (ᾰ_1 : Nonempty β) =>\n nonempty.dcases_on ᾰ\n fun (ᾰ_1_1 : α) =>\n nonempty.dcases_on ᾰ_1 fun (ᾰ : β) => idRhs (Nonempty γ) (Nonempty.intro (f ᾰ_1_1 ᾰ))\n\nprotected theorem nonempty.congr {α : Sort u} {β : Sort v} (f : α → β) (g : β → α) :\n Nonempty α ↔ Nonempty β :=\n { mp := nonempty.map f, mpr := nonempty.map g }\n\ntheorem nonempty.elim_to_inhabited {α : Sort u_1} [h : Nonempty α] {p : Prop}\n (f : Inhabited α → p) : p :=\n nonempty.elim h (f ∘ Inhabited.mk)\n\nprotected instance prod.nonempty {α : Type u_1} {β : Type u_2} [h : Nonempty α] [h2 : Nonempty β] :\n Nonempty (α × β) :=\n nonempty.elim h fun (g : α) => nonempty.elim h2 fun (g2 : β) => Nonempty.intro (g, g2)\n\n/-- A function applied to a `dite` is a `dite` of that function applied to each of the branches. -/\ntheorem apply_dite {α : Sort u_1} {β : Sort u_2} (f : α → β) (P : Prop) [Decidable P] (x : P → α)\n (y : ¬P → α) : f (dite P x y) = dite P (fun (h : P) => f (x h)) fun (h : ¬P) => f (y h) :=\n sorry\n\n/-- A function applied to a `ite` is a `ite` of that function applied to each of the branches. -/\ntheorem apply_ite {α : Sort u_1} {β : Sort u_2} (f : α → β) (P : Prop) [Decidable P] (x : α)\n (y : α) : f (ite P x y) = ite P (f x) (f y) :=\n apply_dite f P (fun (_x : P) => x) fun (_x : ¬P) => y\n\n/-- A two-argument function applied to two `dite`s is a `dite` of that two-argument function\napplied to each of the branches. -/\ntheorem apply_dite2 {α : Sort u_1} {β : Sort u_2} {γ : Sort u_3} (f : α → β → γ) (P : Prop)\n [Decidable P] (a : P → α) (b : ¬P → α) (c : P → β) (d : ¬P → β) :\n f (dite P a b) (dite P c d) =\n dite P (fun (h : P) => f (a h) (c h)) fun (h : ¬P) => f (b h) (d h) :=\n sorry\n\n/-- A two-argument function applied to two `ite`s is a `ite` of that two-argument function\napplied to each of the branches. -/\ntheorem apply_ite2 {α : Sort u_1} {β : Sort u_2} {γ : Sort u_3} (f : α → β → γ) (P : Prop)\n [Decidable P] (a : α) (b : α) (c : β) (d : β) :\n f (ite P a b) (ite P c d) = ite P (f a c) (f b d) :=\n apply_dite2 f P (fun (_x : P) => a) (fun (_x : ¬P) => b) (fun (_x : P) => c) fun (_x : ¬P) => d\n\n/-- A 'dite' producing a `Pi` type `Π a, β a`, applied to a value `x : α`\nis a `dite` that applies either branch to `x`. -/\ntheorem dite_apply {α : Sort u_1} {β : α → Sort u_2} (P : Prop) [Decidable P]\n (f : P → (a : α) → β a) (g : ¬P → (a : α) → β a) (x : α) :\n dite P f g x = dite P (fun (h : P) => f h x) fun (h : ¬P) => g h x :=\n sorry\n\n/-- A 'ite' producing a `Pi` type `Π a, β a`, applied to a value `x : α`\nis a `ite` that applies either branch to `x` -/\ntheorem ite_apply {α : Sort u_1} {β : α → Sort u_2} (P : Prop) [Decidable P] (f : (a : α) → β a)\n (g : (a : α) → β a) (x : α) : ite P f g x = ite P (f x) (g x) :=\n dite_apply P (fun (_x : P) => f) (fun (_x : ¬P) => g) x\n\n/-- Negation of the condition `P : Prop` in a `dite` is the same as swapping the branches. -/\n@[simp] theorem dite_not {α : Sort u_1} (P : Prop) [Decidable P] (x : ¬P → α) (y : ¬¬P → α) :\n dite (¬P) x y = dite P (fun (h : P) => y (not_not_intro h)) x :=\n sorry\n\n/-- Negation of the condition `P : Prop` in a `ite` is the same as swapping the branches. -/\n@[simp] theorem ite_not {α : Sort u_1} (P : Prop) [Decidable P] (x : α) (y : α) :\n ite (¬P) x y = ite P y x :=\n dite_not P (fun (_x : ¬P) => x) fun (_x : ¬¬P) => y\n\ntheorem ite_and {α : Sort u_1} {p : Prop} {q : Prop} [Decidable p] [Decidable q] {x : α} {y : α} :\n ite (p ∧ q) x y = ite p (ite q x y) y :=\n sorry\n\nend Mathlib", "meta": {"author": "AurelienSaue", "repo": "Mathlib4_auto", "sha": "590df64109b08190abe22358fabc3eae000943f2", "save_path": "github-repos/lean/AurelienSaue-Mathlib4_auto", "path": "github-repos/lean/AurelienSaue-Mathlib4_auto/Mathlib4_auto-590df64109b08190abe22358fabc3eae000943f2/Mathlib/logic/basic_auto.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2689414096510108, "lm_q2_score": 0.11757213972942691, "lm_q1q2_score": 0.03162001699451769}} {"text": "/-\nCopyright (c) 2019 Simon Hudon. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Simon Hudon, Yury Kudryashov\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.default\nimport Mathlib.data.equiv.basic\nimport Mathlib.data.list.basic\nimport Mathlib.algebra.star.basic\nimport Mathlib.PostPort\n\nuniverses u_1 u_2 u_4 u_5 u_3 \n\nnamespace Mathlib\n\n/-!\n# Free monoid over a given alphabet\n\n## Main definitions\n\n* `free_monoid α`: free monoid over alphabet `α`; defined as a synonym for `list α`\n with multiplication given by `(++)`.\n* `free_monoid.of`: embedding `α → free_monoid α` sending each element `x` to `[x]`;\n* `free_monoid.lift`: natural equivalence between `α → M` and `free_monoid α →* M`\n* `free_monoid.map`: embedding of `α → β` into `free_monoid α →* free_monoid β` given by `list.map`.\n-/\n\n/-- Free monoid over a given alphabet. -/\ndef free_add_monoid (α : Type u_1) := List α\n\nnamespace free_monoid\n\n\nprotected instance Mathlib.free_add_monoid.add_monoid {α : Type u_1} :\n add_monoid (free_add_monoid α) :=\n add_monoid.mk (fun (x y : free_add_monoid α) => x ++ y) sorry [] sorry sorry\n\nprotected instance inhabited {α : Type u_1} : Inhabited (free_monoid α) := { default := 1 }\n\ntheorem one_def {α : Type u_1} : 1 = [] := rfl\n\ntheorem Mathlib.free_add_monoid.add_def {α : Type u_1} (xs : List α) (ys : List α) :\n xs + ys = xs ++ ys :=\n rfl\n\n/-- Embeds an element of `α` into `free_monoid α` as a singleton list. -/\ndef of {α : Type u_1} (x : α) : free_monoid α := [x]\n\ntheorem of_def {α : Type u_1} (x : α) : of x = [x] := rfl\n\ntheorem of_injective {α : Type u_1} : function.injective of :=\n fun (a b : α) => list.head_eq_of_cons_eq\n\n/-- Recursor for `free_monoid` using `1` and `of x * xs` instead of `[]` and `x :: xs`. -/\ndef rec_on {α : Type u_1} {C : free_monoid α → Sort u_2} (xs : free_monoid α) (h0 : C 1)\n (ih : (x : α) → (xs : free_monoid α) → C xs → C (of x * xs)) : C xs :=\n list.rec_on xs h0 ih\n\ntheorem hom_eq {α : Type u_1} {M : Type u_4} [monoid M] {f : free_monoid α →* M}\n {g : free_monoid α →* M} (h : ∀ (x : α), coe_fn f (of x) = coe_fn g (of x)) : f = g :=\n sorry\n\n/-- Equivalence between maps `α → M` and monoid homomorphisms `free_monoid α →* M`. -/\ndef lift {α : Type u_1} {M : Type u_4} [monoid M] : (α → M) ≃ (free_monoid α →* M) :=\n equiv.mk\n (fun (f : α → M) =>\n monoid_hom.mk (fun (l : free_monoid α) => list.prod (list.map f l)) sorry sorry)\n (fun (f : free_monoid α →* M) (x : α) => coe_fn f (of x)) sorry sorry\n\n@[simp] theorem Mathlib.free_add_monoid.lift_symm_apply {α : Type u_1} {M : Type u_4} [add_monoid M]\n (f : free_add_monoid α →+ M) :\n coe_fn (equiv.symm free_add_monoid.lift) f = ⇑f ∘ free_add_monoid.of :=\n rfl\n\ntheorem lift_apply {α : Type u_1} {M : Type u_4} [monoid M] (f : α → M) (l : free_monoid α) :\n coe_fn (coe_fn lift f) l = list.prod (list.map f l) :=\n rfl\n\ntheorem Mathlib.free_add_monoid.lift_comp_of {α : Type u_1} {M : Type u_4} [add_monoid M]\n (f : α → M) : ⇑(coe_fn free_add_monoid.lift f) ∘ free_add_monoid.of = f :=\n equiv.symm_apply_apply free_add_monoid.lift f\n\n@[simp] theorem Mathlib.free_add_monoid.lift_eval_of {α : Type u_1} {M : Type u_4} [add_monoid M]\n (f : α → M) (x : α) : coe_fn (coe_fn free_add_monoid.lift f) (free_add_monoid.of x) = f x :=\n congr_fun (free_add_monoid.lift_comp_of f) x\n\n@[simp] theorem lift_restrict {α : Type u_1} {M : Type u_4} [monoid M] (f : free_monoid α →* M) :\n coe_fn lift (⇑f ∘ of) = f :=\n equiv.apply_symm_apply lift f\n\ntheorem comp_lift {α : Type u_1} {M : Type u_4} [monoid M] {N : Type u_5} [monoid N] (g : M →* N)\n (f : α → M) : monoid_hom.comp g (coe_fn lift f) = coe_fn lift (⇑g ∘ f) :=\n sorry\n\ntheorem hom_map_lift {α : Type u_1} {M : Type u_4} [monoid M] {N : Type u_5} [monoid N] (g : M →* N)\n (f : α → M) (x : free_monoid α) :\n coe_fn g (coe_fn (coe_fn lift f) x) = coe_fn (coe_fn lift (⇑g ∘ f)) x :=\n iff.mp monoid_hom.ext_iff (comp_lift g f) x\n\n/-- The unique monoid homomorphism `free_monoid α →* free_monoid β` that sends\neach `of x` to `of (f x)`. -/\ndef map {α : Type u_1} {β : Type u_2} (f : α → β) : free_monoid α →* free_monoid β :=\n monoid_hom.mk (list.map f) sorry sorry\n\n@[simp] theorem map_of {α : Type u_1} {β : Type u_2} (f : α → β) (x : α) :\n coe_fn (map f) (of x) = of (f x) :=\n rfl\n\ntheorem Mathlib.free_add_monoid.lift_of_comp_eq_map {α : Type u_1} {β : Type u_2} (f : α → β) :\n (coe_fn free_add_monoid.lift fun (x : α) => free_add_monoid.of (f x)) = free_add_monoid.map f :=\n free_add_monoid.hom_eq fun (x : α) => rfl\n\ntheorem map_comp {α : Type u_1} {β : Type u_2} {γ : Type u_3} (g : β → γ) (f : α → β) :\n map (g ∘ f) = monoid_hom.comp (map g) (map f) :=\n hom_eq fun (x : α) => rfl\n\nprotected instance star_monoid {α : Type u_1} : star_monoid (free_monoid α) :=\n star_monoid.mk list.reverse_append\n\n@[simp] theorem star_of {α : Type u_1} (x : α) : star (of x) = of x := rfl\n\n/-- Note that `star_one` is already a global simp lemma, but this one works with dsimp too -/\n@[simp] theorem star_one {α : Type u_1} : star 1 = 1 := rfl\n\nend Mathlib", "meta": {"author": "AurelienSaue", "repo": "Mathlib4_auto", "sha": "590df64109b08190abe22358fabc3eae000943f2", "save_path": "github-repos/lean/AurelienSaue-Mathlib4_auto", "path": "github-repos/lean/AurelienSaue-Mathlib4_auto/Mathlib4_auto-590df64109b08190abe22358fabc3eae000943f2/Mathlib/algebra/free_monoid_auto.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4416730056646256, "lm_q2_score": 0.07159120093018112, "lm_q1q2_score": 0.031619900893973235}} {"text": "/-\nCopyright (c) 2018 Mario Carneiro. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthor: Mario Carneiro\n\nA computable model of hereditarily finite sets with atoms\n(ZFA without infinity). This is useful for calculations in naive\nset theory.\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.default\nimport Mathlib.data.list.basic\nimport Mathlib.data.sigma.default\nimport Mathlib.PostPort\n\nuniverses u l u_1 u_2 u_3 \n\nnamespace Mathlib\n\ninductive lists' (α : Type u) : Bool → Type u\nwhere\n| atom : α → lists' α false\n| nil : lists' α tt\n| cons' : {b : Bool} → lists' α b → lists' α tt → lists' α tt\n\ndef lists (α : Type u_1) :=\n sigma fun (b : Bool) => lists' α b\n\nnamespace lists'\n\n\nprotected instance inhabited {α : Type u_1} [Inhabited α] (b : Bool) : Inhabited (lists' α b) :=\n sorry\n\ndef cons {α : Type u_1} : lists α → lists' α tt → lists' α tt :=\n sorry\n\n@[simp] def to_list {α : Type u_1} {b : Bool} : lists' α b → List (lists α) :=\n sorry\n\n@[simp] theorem to_list_cons {α : Type u_1} (a : lists α) (l : lists' α tt) : to_list (cons a l) = a :: to_list l := sorry\n\n@[simp] def of_list {α : Type u_1} : List (lists α) → lists' α tt :=\n sorry\n\n@[simp] theorem to_of_list {α : Type u_1} (l : List (lists α)) : to_list (of_list l) = l := sorry\n\n@[simp] theorem of_to_list {α : Type u_1} (l : lists' α tt) : of_list (to_list l) = l := sorry\n\nend lists'\n\n\ndef lists'.subset {α : Type u_1} : lists' α tt → lists' α tt → Prop :=\n fun (ᾰ ᾰ_1 : lists' α tt) =>\n lists.equiv._mut_\n ((fun (idx : psigma fun (ᾰ : lists' α tt) => psigma fun (ᾰ : lists' α tt) => Unit) => psum.inr idx)\n ((fun (ᾰ ᾰ_2 : lists' α tt) => psigma.mk ᾰ (psigma.mk ᾰ_2 Unit.unit)) ᾰ ᾰ_1))\n\nnamespace lists'\n\n\nprotected instance has_subset {α : Type u_1} : has_subset (lists' α tt) :=\n has_subset.mk subset\n\nprotected instance has_mem {α : Type u_1} {b : Bool} : has_mem (lists α) (lists' α b) :=\n has_mem.mk fun (a : lists α) (l : lists' α b) => ∃ (a' : lists α), ∃ (H : a' ∈ to_list l), lists.equiv a a'\n\ntheorem mem_def {α : Type u_1} {b : Bool} {a : lists α} {l : lists' α b} : a ∈ l ↔ ∃ (a' : lists α), ∃ (H : a' ∈ to_list l), lists.equiv a a' :=\n iff.rfl\n\n@[simp] theorem mem_cons {α : Type u_1} {a : lists α} {y : lists α} {l : lists' α tt} : a ∈ cons y l ↔ lists.equiv a y ∨ a ∈ l := sorry\n\ntheorem cons_subset {α : Type u_1} {a : lists α} {l₁ : lists' α tt} {l₂ : lists' α tt} : cons a l₁ ⊆ l₂ ↔ a ∈ l₂ ∧ l₁ ⊆ l₂ := sorry\n\ntheorem of_list_subset {α : Type u_1} {l₁ : List (lists α)} {l₂ : List (lists α)} (h : l₁ ⊆ l₂) : of_list l₁ ⊆ of_list l₂ := sorry\n\ntheorem subset.refl {α : Type u_1} {l : lists' α tt} : l ⊆ l :=\n eq.mpr (id (Eq._oldrec (Eq.refl (l ⊆ l)) (Eq.symm (of_to_list l)))) (of_list_subset (list.subset.refl (to_list l)))\n\ntheorem subset_nil {α : Type u_1} {l : lists' α tt} : l ⊆ nil → l = nil := sorry\n\ntheorem mem_of_subset' {α : Type u_1} {a : lists α} {l₁ : lists' α tt} {l₂ : lists' α tt} (s : l₁ ⊆ l₂) (h : a ∈ to_list l₁) : a ∈ l₂ := sorry\n\ntheorem subset_def {α : Type u_1} {l₁ : lists' α tt} {l₂ : lists' α tt} : l₁ ⊆ l₂ ↔ ∀ (a : lists α), a ∈ to_list l₁ → a ∈ l₂ := sorry\n\nend lists'\n\n\nnamespace lists\n\n\ndef atom {α : Type u_1} (a : α) : lists α :=\n sigma.mk false (lists'.atom a)\n\ndef of' {α : Type u_1} (l : lists' α tt) : lists α :=\n sigma.mk tt l\n\n@[simp] def to_list {α : Type u_1} : lists α → List (lists α) :=\n sorry\n\ndef is_list {α : Type u_1} (l : lists α) :=\n ↥(sigma.fst l)\n\ndef of_list {α : Type u_1} (l : List (lists α)) : lists α :=\n of' (lists'.of_list l)\n\ntheorem is_list_to_list {α : Type u_1} (l : List (lists α)) : is_list (of_list l) :=\n Eq.refl (sigma.fst (of_list l))\n\ntheorem to_of_list {α : Type u_1} (l : List (lists α)) : to_list (of_list l) = l := sorry\n\ntheorem of_to_list {α : Type u_1} {l : lists α} : is_list l → of_list (to_list l) = l := sorry\n\nprotected instance inhabited {α : Type u_1} : Inhabited (lists α) :=\n { default := of' lists'.nil }\n\nprotected instance decidable_eq {α : Type u_1} [DecidableEq α] : DecidableEq (lists α) :=\n eq.mpr sorry fun (a b : sigma fun (b : Bool) => lists' α b) => sigma.decidable_eq a b\n\nprotected instance has_sizeof {α : Type u_1} [SizeOf α] : SizeOf (lists α) :=\n eq.mpr sorry (sigma.has_sizeof Bool fun (b : Bool) => lists' α b)\n\ndef induction_mut {α : Type u_1} (C : lists α → Sort u_2) (D : lists' α tt → Sort u_3) (C0 : (a : α) → C (atom a)) (C1 : (l : lists' α tt) → D l → C (of' l)) (D0 : D lists'.nil) (D1 : (a : lists α) → (l : lists' α tt) → C a → D l → D (lists'.cons a l)) : PProd ((l : lists α) → C l) ((l : lists' α tt) → D l) :=\n { fst := fun (_x : lists α) => sorry,\n snd :=\n fun (l : lists' α tt) =>\n pprod.snd\n ((fun (b : Bool) (l : lists' α b) =>\n lists'.rec (fun (a : α) => { fst := C0 a, snd := PUnit.unit }) { fst := C1 lists'.nil D0, snd := D0 }\n (fun {b : Bool} (a : lists' α b) (l : lists' α tt) (IH₁ : PProd (C (sigma.mk b a)) sorry)\n (IH₂ : PProd (C (sigma.mk tt l)) sorry) =>\n { fst := C1 (lists'.cons' a l) (D1 (sigma.mk b a) l (pprod.fst IH₁) (pprod.snd IH₂)),\n snd := D1 (sigma.mk b a) l (pprod.fst IH₁) (pprod.snd IH₂) })\n l)\n tt l) }\n\ndef mem {α : Type u_1} (a : lists α) : lists α → Prop :=\n sorry\n\nprotected instance has_mem {α : Type u_1} : has_mem (lists α) (lists α) :=\n has_mem.mk mem\n\ntheorem is_list_of_mem {α : Type u_1} {a : lists α} {l : lists α} : a ∈ l → is_list l := sorry\n\ntheorem equiv.antisymm_iff {α : Type u_1} {l₁ : lists' α tt} {l₂ : lists' α tt} : equiv (of' l₁) (of' l₂) ↔ l₁ ⊆ l₂ ∧ l₂ ⊆ l₁ := sorry\n\ntheorem equiv_atom {α : Type u_1} {a : α} {l : lists α} : equiv (atom a) l ↔ atom a = l := sorry\n\ntheorem equiv.symm {α : Type u_1} {l₁ : lists α} {l₂ : lists α} (h : equiv l₁ l₂) : equiv l₂ l₁ := sorry\n\ntheorem equiv.trans {α : Type u_1} {l₁ : lists α} {l₂ : lists α} {l₃ : lists α} : equiv l₁ l₂ → equiv l₂ l₃ → equiv l₁ l₃ := sorry\n\nprotected instance setoid {α : Type u_1} : setoid (lists α) :=\n setoid.mk equiv sorry\n\n@[simp] def equiv.decidable_meas {α : Type u_1} : psum (psigma fun (l₁ : lists α) => lists α)\n (psum (psigma fun (l₁ : lists' α tt) => lists' α tt) (psigma fun (a : lists α) => lists' α tt)) →\n ℕ :=\n sorry\n\ntheorem sizeof_pos {α : Type u_1} {b : Bool} (l : lists' α b) : 0 < sizeof l := sorry\n\ntheorem lt_sizeof_cons' {α : Type u_1} {b : Bool} (a : lists' α b) (l : lists' α tt) : sizeof (sigma.mk b a) < sizeof (lists'.cons' a l) := sorry\n\ninstance mem.decidable {α : Type u_1} [DecidableEq α] (a : lists α) (l : lists' α tt) : Decidable (a ∈ l) :=\n sorry\n\nend lists\n\n\nnamespace lists'\n\n\ntheorem mem_equiv_left {α : Type u_1} {l : lists' α tt} {a : lists α} {a' : lists α} : lists.equiv a a' → (a ∈ l ↔ a' ∈ l) := sorry\n\ntheorem mem_of_subset {α : Type u_1} {a : lists α} {l₁ : lists' α tt} {l₂ : lists' α tt} (s : l₁ ⊆ l₂) : a ∈ l₁ → a ∈ l₂ := sorry\n\ntheorem subset.trans {α : Type u_1} {l₁ : lists' α tt} {l₂ : lists' α tt} {l₃ : lists' α tt} (h₁ : l₁ ⊆ l₂) (h₂ : l₂ ⊆ l₃) : l₁ ⊆ l₃ :=\n iff.mpr subset_def fun (a₁ : lists α) (m₁ : a₁ ∈ to_list l₁) => mem_of_subset h₂ (mem_of_subset' h₁ m₁)\n\nend lists'\n\n\ndef finsets (α : Type u_1) :=\n quotient lists.setoid\n\nnamespace finsets\n\n\nprotected instance has_emptyc {α : Type u_1} : has_emptyc (finsets α) :=\n has_emptyc.mk (quotient.mk (lists.of' lists'.nil))\n\nprotected instance inhabited {α : Type u_1} : Inhabited (finsets α) :=\n { default := ∅ }\n\nprotected instance decidable_eq {α : Type u_1} [DecidableEq α] : DecidableEq (finsets α) :=\n eq.mpr sorry fun (a b : quotient lists.setoid) => quotient.decidable_eq a b\n\n", "meta": {"author": "AurelienSaue", "repo": "Mathlib4_auto", "sha": "590df64109b08190abe22358fabc3eae000943f2", "save_path": "github-repos/lean/AurelienSaue-Mathlib4_auto", "path": "github-repos/lean/AurelienSaue-Mathlib4_auto/Mathlib4_auto-590df64109b08190abe22358fabc3eae000943f2/Mathlib/set_theory/lists.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091946, "lm_q2_score": 0.06371499914110602, "lm_q1q2_score": 0.03160861791864763}} {"text": "/-\nCopyright (c) 2020 Scott Morrison. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Scott Morrison\n-/\nimport category_theory.monoidal.coherence\n\n/-!\n# Monoidal opposites\n\nWe write `Cᵐᵒᵖ` for the monoidal opposite of a monoidal category `C`.\n-/\n\n\nuniverses v₁ v₂ u₁ u₂\n\nvariables {C : Type u₁}\n\nnamespace category_theory\n\nopen category_theory.monoidal_category\n\n/-- A type synonym for the monoidal opposite. Use the notation `Cᴹᵒᵖ`. -/\n@[nolint has_inhabited_instance]\ndef monoidal_opposite (C : Type u₁) := C\n\nnamespace monoidal_opposite\n\nnotation C `ᴹᵒᵖ`:std.prec.max_plus := monoidal_opposite C\n\n/-- Think of an object of `C` as an object of `Cᴹᵒᵖ`. -/\n@[pp_nodot]\ndef mop (X : C) : Cᴹᵒᵖ := X\n\n/-- Think of an object of `Cᴹᵒᵖ` as an object of `C`. -/\n@[pp_nodot]\ndef unmop (X : Cᴹᵒᵖ) : C := X\n\nlemma op_injective : function.injective (mop : C → Cᴹᵒᵖ) := λ _ _, id\nlemma unop_injective : function.injective (unmop : Cᴹᵒᵖ → C) := λ _ _, id\n\n@[simp] lemma op_inj_iff (x y : C) : mop x = mop y ↔ x = y := iff.rfl\n@[simp] \n\nattribute [irreducible] monoidal_opposite\n\n@[simp] lemma mop_unmop (X : Cᴹᵒᵖ) : mop (unmop X) = X := rfl\n@[simp] lemma unmop_mop (X : C) : unmop (mop X) = X := rfl\n\ninstance monoidal_opposite_category [I : category.{v₁} C] : category Cᴹᵒᵖ :=\n{ hom := λ X Y, unmop X ⟶ unmop Y,\n id := λ X, 𝟙 (unmop X),\n comp := λ X Y Z f g, f ≫ g, }\n\nend monoidal_opposite\n\nend category_theory\n\nopen category_theory\nopen category_theory.monoidal_opposite\n\nvariables [category.{v₁} C]\n\n/-- The monoidal opposite of a morphism `f : X ⟶ Y` is just `f`, thought of as `mop X ⟶ mop Y`. -/\ndef quiver.hom.mop {X Y : C} (f : X ⟶ Y) : @quiver.hom Cᴹᵒᵖ _ (mop X) (mop Y) := f\n/-- We can think of a morphism `f : mop X ⟶ mop Y` as a morphism `X ⟶ Y`. -/\ndef quiver.hom.unmop {X Y : Cᴹᵒᵖ} (f : X ⟶ Y) : unmop X ⟶ unmop Y := f\n\nnamespace category_theory\n\nlemma mop_inj {X Y : C} :\n function.injective (quiver.hom.mop : (X ⟶ Y) → (mop X ⟶ mop Y)) :=\nλ _ _ H, congr_arg quiver.hom.unmop H\n\nlemma unmop_inj {X Y : Cᴹᵒᵖ} :\n function.injective (quiver.hom.unmop : (X ⟶ Y) → (unmop X ⟶ unmop Y)) :=\nλ _ _ H, congr_arg quiver.hom.mop H\n\n@[simp] lemma unmop_mop {X Y : C} {f : X ⟶ Y} : f.mop.unmop = f := rfl\n@[simp] lemma mop_unmop {X Y : Cᴹᵒᵖ} {f : X ⟶ Y} : f.unmop.mop = f := rfl\n\n@[simp] lemma mop_comp {X Y Z : C} {f : X ⟶ Y} {g : Y ⟶ Z} :\n (f ≫ g).mop = f.mop ≫ g.mop := rfl\n@[simp] lemma mop_id {X : C} : (𝟙 X).mop = 𝟙 (mop X) := rfl\n\n@[simp] lemma unmop_comp {X Y Z : Cᴹᵒᵖ} {f : X ⟶ Y} {g : Y ⟶ Z} :\n (f ≫ g).unmop = f.unmop ≫ g.unmop := rfl\n@[simp] lemma unmop_id {X : Cᴹᵒᵖ} : (𝟙 X).unmop = 𝟙 (unmop X) := rfl\n\n@[simp] lemma unmop_id_mop {X : C} : (𝟙 (mop X)).unmop = 𝟙 X := rfl\n@[simp] lemma mop_id_unmop {X : Cᴹᵒᵖ} : (𝟙 (unmop X)).mop = 𝟙 X := rfl\n\nnamespace iso\n\nvariables {X Y : C}\n\n/-- An isomorphism in `C` gives an isomorphism in `Cᴹᵒᵖ`. -/\n@[simps]\ndef mop (f : X ≅ Y) : mop X ≅ mop Y :=\n{ hom := f.hom.mop,\n inv := f.inv.mop,\n hom_inv_id' := unmop_inj f.hom_inv_id,\n inv_hom_id' := unmop_inj f.inv_hom_id }\n\nend iso\n\nvariables [monoidal_category.{v₁} C]\n\nopen opposite monoidal_category\n\ninstance monoidal_category_op : monoidal_category Cᵒᵖ :=\n{ tensor_obj := λ X Y, op (unop X ⊗ unop Y),\n tensor_hom := λ X₁ Y₁ X₂ Y₂ f g, (f.unop ⊗ g.unop).op,\n tensor_unit := op (𝟙_ C),\n associator := λ X Y Z, (α_ (unop X) (unop Y) (unop Z)).symm.op,\n left_unitor := λ X, (λ_ (unop X)).symm.op,\n right_unitor := λ X, (ρ_ (unop X)).symm.op,\n associator_naturality' := by { intros, apply quiver.hom.unop_inj, simp, },\n left_unitor_naturality' := by { intros, apply quiver.hom.unop_inj, simp, },\n right_unitor_naturality' := by { intros, apply quiver.hom.unop_inj, simp, },\n triangle' := by { intros, apply quiver.hom.unop_inj, coherence, },\n pentagon' := by { intros, apply quiver.hom.unop_inj, coherence, }, }\n\nlemma op_tensor_obj (X Y : Cᵒᵖ) : X ⊗ Y = op (unop X ⊗ unop Y) := rfl\nlemma op_tensor_unit : (𝟙_ Cᵒᵖ) = op (𝟙_ C) := rfl\n\ninstance monoidal_category_mop : monoidal_category Cᴹᵒᵖ :=\n{ tensor_obj := λ X Y, mop (unmop Y ⊗ unmop X),\n tensor_hom := λ X₁ Y₁ X₂ Y₂ f g, (g.unmop ⊗ f.unmop).mop,\n tensor_unit := mop (𝟙_ C),\n associator := λ X Y Z, (α_ (unmop Z) (unmop Y) (unmop X)).symm.mop,\n left_unitor := λ X, (ρ_ (unmop X)).mop,\n right_unitor := λ X, (λ_ (unmop X)).mop,\n associator_naturality' := by { intros, apply unmop_inj, simp, },\n left_unitor_naturality' := by { intros, apply unmop_inj, simp, },\n right_unitor_naturality' := by { intros, apply unmop_inj, simp, },\n triangle' := by { intros, apply unmop_inj, coherence, },\n pentagon' := by { intros, apply unmop_inj, coherence, }, }\n\nlemma mop_tensor_obj (X Y : Cᴹᵒᵖ) : X ⊗ Y = mop (unmop Y ⊗ unmop X) := rfl\nlemma mop_tensor_unit : (𝟙_ Cᴹᵒᵖ) = mop (𝟙_ C) := rfl\n\nend category_theory\n", "meta": {"author": "nick-kuhn", "repo": "leantools", "sha": "567a98c031fffe3f270b7b8dea48389bc70d7abb", "save_path": "github-repos/lean/nick-kuhn-leantools", "path": "github-repos/lean/nick-kuhn-leantools/leantools-567a98c031fffe3f270b7b8dea48389bc70d7abb/src/category_theory/monoidal/opposite.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4532618627863437, "lm_q2_score": 0.0695417406490685, "lm_q1q2_score": 0.03152061890800159}} {"text": "/-\nCopyright (c) 2020 Simon Hudon. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthor(s): Simon Hudon\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.default\nimport Mathlib.control.monad.basic\nimport Mathlib.control.monad.cont\nimport Mathlib.control.monad.writer\nimport Mathlib.data.equiv.basic\nimport Mathlib.tactic.interactive\nimport Mathlib.PostPort\n\nuniverses u₀ u₁ v₀ v₁ l u_1 u_2 u_3 u_4 u_5 u_6 \n\nnamespace Mathlib\n\n/-!\n# Universe lifting for type families\n\nSome functors such as `option` and `list` are universe polymorphic. Unlike\ntype polymorphism where `option α` is a function application and reasoning and\ngeneralizations that apply to functions can be used, `option.{u}` and `option.{v}`\nare not one function applied to two universe names but one polymorphic definition\ninstantiated twice. This means that whatever works on `option.{u}` is hard\nto transport over to `option.{v}`. `uliftable` is an attempt at improving the situation.\n\n`uliftable option.{u} option.{v}` gives us a generic and composable way to use\n`option.{u}` in a context that requires `option.{v}`. It is often used in tandem with\n`ulift` but the two are purposefully decoupled.\n\n\n## Main definitions\n * `uliftable` class\n\n## Tags\n\nuniverse polymorphism functor\n\n-/\n\n/-- Given a universe polymorphic type family `M.{u} : Type u₁ → Type\nu₂`, this class convert between instantiations, from\n`M.{u} : Type u₁ → Type u₂` to `M.{v} : Type v₁ → Type v₂` and back -/\nclass uliftable (f : Type u₀ → Type u₁) (g : Type v₀ → Type v₁) where\n congr : {α : Type u₀} → {β : Type v₀} → α ≃ β → f α ≃ g β\n\nnamespace uliftable\n\n\n/-- The most common practical use `uliftable` (together with `up`), this function takes\n`x : M.{u} α` and lifts it to M.{max u v} (ulift.{v} α) -/\ndef up {f : Type u₀ → Type u₁} {g : Type (max u₀ v₀) → Type v₁} [uliftable f g] {α : Type u₀} :\n f α → g (ulift α) :=\n equiv.to_fun (congr f g (equiv.symm equiv.ulift))\n\n/-- The most common practical use of `uliftable` (together with `up`), this function takes\n`x : M.{max u v} (ulift.{v} α)` and lowers it to `M.{u} α` -/\ndef down {f : Type u₀ → Type u₁} {g : Type (max u₀ v₀) → Type v₁} [uliftable f g] {α : Type u₀} :\n g (ulift α) → f α :=\n equiv.inv_fun (congr f g (equiv.symm equiv.ulift))\n\n/-- convenient shortcut to avoid manipulating `ulift` -/\ndef adapt_up (F : Type v₀ → Type v₁) (G : Type (max v₀ u₀) → Type u₁) [uliftable F G] [Monad G]\n {α : Type v₀} {β : Type (max v₀ u₀)} (x : F α) (f : α → G β) : G β :=\n up x >>= f ∘ ulift.down\n\n/-- convenient shortcut to avoid manipulating `ulift` -/\ndef adapt_down {F : Type (max u₀ v₀) → Type u₁} {G : Type v₀ → Type v₁} [L : uliftable G F]\n [Monad F] {α : Type (max u₀ v₀)} {β : Type v₀} (x : F α) (f : α → G β) : G β :=\n down (x >>= up ∘ f)\n\n/-- map function that moves up universes -/\ndef up_map {F : Type u₀ → Type u₁} {G : Type (max u₀ v₀) → Type v₁} [inst : uliftable F G]\n [Functor G] {α : Type u₀} {β : Type (max u₀ v₀)} (f : α → β) (x : F α) : G β :=\n (f ∘ ulift.down) <$> up x\n\n/-- map function that moves down universes -/\ndef down_map {F : Type (max u₀ v₀) → Type u₁} {G : Type → Type v₁} [inst : uliftable G F]\n [Functor F] {α : Type (max u₀ v₀)} {β : Type} (f : α → β) (x : F α) : G β :=\n down ((ulift.up ∘ f) <$> x)\n\n@[simp] theorem up_down {f : Type u₀ → Type u₁} {g : Type (max u₀ v₀) → Type v₁} [uliftable f g]\n {α : Type u₀} (x : g (ulift α)) : up (down x) = x :=\n equiv.right_inv (congr f g (equiv.symm equiv.ulift)) x\n\n@[simp] theorem down_up {f : Type u₀ → Type u₁} {g : Type (max u₀ v₀) → Type v₁} [uliftable f g]\n {α : Type u₀} (x : f α) : down (up x) = x :=\n equiv.left_inv (congr f g (equiv.symm equiv.ulift)) x\n\nend uliftable\n\n\nprotected instance id.uliftable : uliftable id id :=\n uliftable.mk fun (α : Type u_1) (β : Type u_2) (F : α ≃ β) => F\n\n/-- for specific state types, this function helps to create a uliftable instance -/\ndef state_t.uliftable' {s : Type u₀} {s' : Type u₁} {m : Type u₀ → Type v₀} {m' : Type u₁ → Type v₁}\n [uliftable m m'] (F : s ≃ s') : uliftable (state_t s m) (state_t s' m') :=\n uliftable.mk\n fun (α : Type u₀) (β : Type u₁) (G : α ≃ β) =>\n state_t.equiv (equiv.Pi_congr F fun (_x : s) => uliftable.congr m m' (equiv.prod_congr G F))\n\nprotected instance state_t.uliftable {s : Type u_1} {m : Type u_1 → Type u_2}\n {m' : Type (max u_1 u_3) → Type u_4} [uliftable m m'] :\n uliftable (state_t s m) (state_t (ulift s) m') :=\n state_t.uliftable' (equiv.symm equiv.ulift)\n\n/-- for specific reader monads, this function helps to create a uliftable instance -/\ndef reader_t.uliftable' {s : Type u_1} {s' : Type u_2} {m : Type u_1 → Type u_3}\n {m' : Type u_2 → Type u_4} [uliftable m m'] (F : s ≃ s') :\n uliftable (reader_t s m) (reader_t s' m') :=\n uliftable.mk\n fun (α : Type u_1) (β : Type u_2) (G : α ≃ β) =>\n reader_t.equiv (equiv.Pi_congr F fun (_x : s) => uliftable.congr m m' G)\n\nprotected instance reader_t.uliftable {s : Type u_1} {m : Type u_1 → Type u_2}\n {m' : Type (max u_1 u_3) → Type u_4} [uliftable m m'] :\n uliftable (reader_t s m) (reader_t (ulift s) m') :=\n reader_t.uliftable' (equiv.symm equiv.ulift)\n\n/-- for specific continuation passing monads, this function helps to create a uliftable instance -/\ndef cont_t.uliftable' {r : Type u_1} {r' : Type u_2} {m : Type u_1 → Type u_3}\n {m' : Type u_2 → Type u_4} [uliftable m m'] (F : r ≃ r') :\n uliftable (cont_t r m) (cont_t r' m') :=\n uliftable.mk fun (α : Type u_1) (β : Type u_2) => cont_t.equiv (uliftable.congr m m' F)\n\nprotected instance cont_t.uliftable {s : Type u_1} {m : Type u_1 → Type u_2}\n {m' : Type (max u_1 u_3) → Type u_4} [uliftable m m'] :\n uliftable (cont_t s m) (cont_t (ulift s) m') :=\n cont_t.uliftable' (equiv.symm equiv.ulift)\n\n/-- for specific writer monads, this function helps to create a uliftable instance -/\ndef writer_t.uliftable' {w : Type (max u_1 u_2)} {w' : Type (max u_3 u_4)}\n {m : Type (max u_1 u_2) → Type u_5} {m' : Type (max u_3 u_4) → Type u_6} [uliftable m m']\n (F : w ≃ w') : uliftable (writer_t w m) (writer_t w' m') :=\n uliftable.mk\n fun (α : Type (max u_1 u_2)) (β : Type (max u_3 u_4)) (G : α ≃ β) =>\n writer_t.equiv (uliftable.congr m m' (equiv.prod_congr G F))\n\nprotected instance writer_t.uliftable {s : Type (max u_1 u_2)} {m : Type (max u_1 u_2) → Type u_3}\n {m' : Type (max (max u_1 u_2) u_4) → Type u_5} [uliftable m m'] :\n uliftable (writer_t s m) (writer_t (ulift s) m') :=\n writer_t.uliftable' (equiv.symm equiv.ulift)\n\nend Mathlib", "meta": {"author": "AurelienSaue", "repo": "Mathlib4_auto", "sha": "590df64109b08190abe22358fabc3eae000943f2", "save_path": "github-repos/lean/AurelienSaue-Mathlib4_auto", "path": "github-repos/lean/AurelienSaue-Mathlib4_auto/Mathlib4_auto-590df64109b08190abe22358fabc3eae000943f2/Mathlib/control/uliftable_auto.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40356685373537454, "lm_q2_score": 0.0780781576366472, "lm_q1q2_score": 0.03150975642287632}} {"text": "/-\nCopyright (c) 2020 Scott Morrison. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Scott Morrison\n-/\nimport algebra.group_power.lemmas\nimport category_theory.pi.basic\nimport category_theory.shift.basic\nimport category_theory.concrete_category.basic\n\n/-!\n# The category of graded objects\n\nFor any type `β`, a `β`-graded object over some category `C` is just\na function `β → C` into the objects of `C`.\nWe put the \"pointwise\" category structure on these, as the non-dependent specialization of\n`category_theory.pi`.\n\nWe describe the `comap` functors obtained by precomposing with functions `β → γ`.\n\nAs a consequence a fixed element (e.g. `1`) in an additive group `β` provides a shift\nfunctor on `β`-graded objects\n\nWhen `C` has coproducts we construct the `total` functor `graded_object β C ⥤ C`,\nshow that it is faithful, and deduce that when `C` is concrete so is `graded_object β C`.\n-/\n\nopen category_theory.pi\nopen category_theory.limits\n\nnamespace category_theory\n\nuniverses w v u\n\n/-- A type synonym for `β → C`, used for `β`-graded objects in a category `C`. -/\ndef graded_object (β : Type w) (C : Type u) : Type (max w u) := β → C\n\n-- Satisfying the inhabited linter...\ninstance inhabited_graded_object (β : Type w) (C : Type u) [inhabited C] :\n inhabited (graded_object β C) :=\n⟨λ b, inhabited.default⟩\n\n/--\nA type synonym for `β → C`, used for `β`-graded objects in a category `C`\nwith a shift functor given by translation by `s`.\n-/\n@[nolint unused_arguments] -- `s` is here to distinguish type synonyms asking for different shifts\nabbreviation graded_object_with_shift {β : Type w} [add_comm_group β] (s : β) (C : Type u) :\n Type (max w u) := graded_object β C\n\nnamespace graded_object\n\nvariables {C : Type u} [category.{v} C]\n\ninstance category_of_graded_objects (β : Type w) : category.{max w v} (graded_object β C) :=\ncategory_theory.pi (λ _, C)\n\n/-- The projection of a graded object to its `i`-th component. -/\n@[simps] def eval {β : Type w} (b : β) : graded_object β C ⥤ C :=\n{ obj := λ X, X b,\n map := λ X Y f, f b, }\n\nsection\nvariable (C)\n\n/--\nThe natural isomorphism comparing between\npulling back along two propositionally equal functions.\n-/\n@[simps]\ndef comap_eq {β γ : Type w} {f g : β → γ} (h : f = g) : comap (λ _, C) f ≅ comap (λ _, C) g :=\n{ hom := { app := λ X b, eq_to_hom begin dsimp [comap], subst h, end },\n inv := { app := λ X b, eq_to_hom begin dsimp [comap], subst h, end }, }\n\nlemma comap_eq_symm {β γ : Type w} {f g : β → γ} (h : f = g) :\n comap_eq C h.symm = (comap_eq C h).symm :=\nby tidy\n\nlemma comap_eq_trans {β γ : Type w} {f g h : β → γ} (k : f = g) (l : g = h) :\n comap_eq C (k.trans l) = comap_eq C k ≪≫ comap_eq C l :=\nbegin\n ext X b,\n simp,\nend\n\n@[simp] lemma eq_to_hom_apply {β : Type w} {X Y : Π b : β, C} (h : X = Y) (b : β) :\n (eq_to_hom h : X ⟶ Y) b = eq_to_hom (by subst h) :=\nby { subst h, refl }\n\n/--\nThe equivalence between β-graded objects and γ-graded objects,\ngiven an equivalence between β and γ.\n-/\n@[simps]\ndef comap_equiv {β γ : Type w} (e : β ≃ γ) :\n (graded_object β C) ≌ (graded_object γ C) :=\n{ functor := comap (λ _, C) (e.symm : γ → β),\n inverse := comap (λ _, C) (e : β → γ),\n counit_iso := (comap_comp (λ _, C) _ _).trans (comap_eq C (by { ext, simp } )),\n unit_iso := (comap_eq C (by { ext, simp } )).trans (comap_comp _ _ _).symm,\n functor_unit_iso_comp' := λ X, by { ext b, dsimp, simp, }, } -- See note [dsimp, simp].\n\nend\n\ninstance has_shift {β : Type*} [add_comm_group β] (s : β) :\n has_shift (graded_object_with_shift s C) ℤ :=\nhas_shift_mk _ _\n{ F := λ n, comap (λ _, C) $ λ (b : β), b + n • s,\n zero := comap_eq C (by { ext, simp }) ≪≫ comap_id β (λ _, C),\n add := λ m n, comap_eq C (by { ext, simp [add_zsmul, add_comm], }) ≪≫\n (comap_comp _ _ _).symm,\n assoc_hom_app := λ m₁ m₂ m₃ X, by { ext, dsimp, simp, },\n zero_add_hom_app := λ n X, by { ext, dsimp, simpa, },\n add_zero_hom_app := λ n X, by { ext, dsimp, simpa, }, }\n\n@[simp] lemma shift_functor_obj_apply {β : Type*} [add_comm_group β]\n (s : β) (X : β → C) (t : β) (n : ℤ) :\n (shift_functor (graded_object_with_shift s C) n).obj X t = X (t + n • s) :=\nrfl\n\n@[simp] lemma shift_functor_map_apply {β : Type*} [add_comm_group β] (s : β)\n {X Y : graded_object_with_shift s C} (f : X ⟶ Y) (t : β) (n : ℤ) :\n (shift_functor (graded_object_with_shift s C) n).map f t = f (t + n • s) :=\nrfl\n\ninstance has_zero_morphisms [has_zero_morphisms C] (β : Type w) :\n has_zero_morphisms.{max w v} (graded_object β C) :=\n{ has_zero := λ X Y,\n { zero := λ b, 0 } }\n\n@[simp]\nlemma zero_apply [has_zero_morphisms C] (β : Type w) (X Y : graded_object β C) (b : β) :\n (0 : X ⟶ Y) b = 0 := rfl\n\nsection\nopen_locale zero_object\n\ninstance has_zero_object [has_zero_object C] [has_zero_morphisms C] (β : Type w) :\n has_zero_object.{max w v} (graded_object β C) :=\nby { refine ⟨⟨λ b, 0, λ X, ⟨⟨⟨λ b, 0⟩, λ f, _⟩⟩, λ X, ⟨⟨⟨λ b, 0⟩, λ f, _⟩⟩⟩⟩; ext, }\nend\n\nend graded_object\n\nnamespace graded_object\n-- The universes get a little hairy here, so we restrict the universe level for the grading to 0.\n-- Since we're typically interested in grading by ℤ or a finite group, this should be okay.\n-- If you're grading by things in higher universes, have fun!\nvariables (β : Type)\nvariables (C : Type u) [category.{v} C]\nvariables [has_coproducts.{0} C]\n\nsection\nlocal attribute [tidy] tactic.discrete_cases\n\n/--\nThe total object of a graded object is the coproduct of the graded components.\n-/\nnoncomputable def total : graded_object β C ⥤ C :=\n{ obj := λ X, ∐ (λ i : β, X i),\n map := λ X Y f, limits.sigma.map (λ i, f i) }.\n\nend\n\nvariables [has_zero_morphisms C]\n\n/--\nThe `total` functor taking a graded object to the coproduct of its graded components is faithful.\nTo prove this, we need to know that the coprojections into the coproduct are monomorphisms,\nwhich follows from the fact we have zero morphisms and decidable equality for the grading.\n-/\ninstance : faithful (total β C) :=\n{ map_injective' := λ X Y f g w,\n begin\n classical,\n ext i,\n replace w := sigma.ι (λ i : β, X i) i ≫= w,\n erw [colimit.ι_map, colimit.ι_map] at w,\n simp at *,\n exact mono.right_cancellation _ _ w,\n end }\n\nend graded_object\n\nnamespace graded_object\n\nnoncomputable theory\n\nvariables (β : Type)\nvariables (C : Type (u+1)) [large_category C] [concrete_category C]\n [has_coproducts.{0} C] [has_zero_morphisms C]\n\ninstance : concrete_category (graded_object β C) :=\n{ forget := total β C ⋙ forget C }\n\ninstance : has_forget₂ (graded_object β C) C :=\n{ forget₂ := total β C }\n\nend graded_object\n\nend category_theory\n", "meta": {"author": "leanprover-community", "repo": "mathlib", "sha": "5e526d18cea33550268dcbbddcb822d5cde40654", "save_path": "github-repos/lean/leanprover-community-mathlib", "path": "github-repos/lean/leanprover-community-mathlib/mathlib-5e526d18cea33550268dcbbddcb822d5cde40654/src/category_theory/graded_object.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45713673161914675, "lm_q2_score": 0.06853749731280298, "lm_q1q2_score": 0.03133100751493081}} {"text": "/-\nCopyright (c) 2020 Mario Carneiro. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Mario Carneiro\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.default\nimport Mathlib.logic.basic\nimport Mathlib.data.fintype.basic\nimport Mathlib.PostPort\n\nuniverses u_1 u_2 \n\nnamespace Mathlib\n\n/-!\n# Derive handler for `fintype` instances\n\nThis file introduces a derive handler to automatically generate `fintype`\ninstances for structures and inductives.\n\n## Implementation notes\n\nTo construct a fintype instance, we need 3 things:\n\n 1. A list `l` of elements\n 2. A proof that `l` has no duplicates\n 3. A proof that every element in the type is in `l`\n\nNow fintype is defined as a finset which enumerates all elements, so steps (1) and (2) are\nbundled together. It is possible to use finset operations that remove duplicates to avoid the need\nto prove (2), but this adds unnecessary functions to the constructed term, which makes it more\nexpensive to compute the list, and it also adds a dependence on decidable equality for the type,\nwhich we want to avoid.\n\nBecause we will rely on fintype instances for constructor arguments, we can't actually build a list\ndirectly, so (1) and (2) are necessarily somewhat intertwined. The inductive types we will be\nproving instances for look something like this:\n\n```\n@[derive fintype]\ninductive foo\n| zero : foo\n| one : bool → foo\n| two : ∀ x : fin 3, bar x → foo\n```\n\nThe list of elements that we generate is\n```\n{foo.zero}\n∪ (finset.univ : bool).map (λ b, finset.one b)\n∪ (finset.univ : Σ' x : fin 3, bar x).map (λ ⟨x, y⟩, finset.two x y)\n```\nexcept that instead of `∪`, that is `finset.union`, we use `finset.disj_union` which doesn't\nrequire any deduplication, but does require a proof that the two parts of the union are disjoint.\nWe use `finset.cons` to append singletons like `foo.zero`.\n\nThe proofs of disjointness would be somewhat expensive since there are quadratically many of them,\nso instead we use a \"discriminant\" function. Essentially, we define\n```\ndef foo.enum : foo → ℕ\n| foo.zero := 0\n| (foo.one _) := 1\n| (foo.two _ _) := 2\n```\nand now the existence of this function implies that foo.zero is not foo.two and so on because they\nmap to different natural numbers. We can prove that sets of natural numbers are mutually disjoint\nmore easily because they have a linear order: `0 < 1 < 2` so `0 ≠ 2`.\n\nTo package this argument up, we define `finset_above foo foo.enum n` to be a finset `s` together\nwith a proof that all elements `a ∈ s` have `n ≤ enum a`. Now we only have to prove that\n`enum foo.zero = 0`, `enum (foo.one _) = 1`, etc. (linearly many proofs, all `rfl`) in order to\nprove that all variants are mutually distinct.\n\nWe mirror the `finset.cons` and `finset.disj_union` functions into `finset_above.cons` and\n`finset_above.union`, and this forms the main part of the finset construction.\n\nThis only handles distinguishing variants of a finset. Now we must enumerate the elements of a\nvariant, for example `{foo.one ff, foo.one tt}`, while at the same time proving that all these\nelements have discriminant `1` in this case. To do that, we use the `finset_in` type, which\nis a finset satisfying a property `P`, here `λ a, foo.enum a = 1`.\n\nWe could use `finset.bind` many times to construct the finset but it turns out to be somewhat\ncomplicated to get good side goals for a naturally nodup version of `finset.bind` in the same way\nas we did with `finset.cons` and `finset.union`. Instead, we tuple up all arguments into one type,\nleveraging the `fintype` instance on `psigma`, and then define a map from this type to the\ninductive type that untuples them and applies the constructor. The injectivity property of the\nconstructor ensures that this function is injective, so we can use `finset.map` to apply it. This\nis the content of the constructor `finset_in.mk`.\n\nThat completes the proofs of (1) and (2). To prove (3), we perform one case analysis over the\ninductive type, proving theorems like\n```\nfoo.one a ∈ {foo.zero}\n ∪ (finset.univ : bool).map (λ b, finset.one b)\n ∪ (finset.univ : Σ' x : fin 3, bar x).map (λ ⟨x, y⟩, finset.two x y)\n```\nby seeking to the relevant disjunct and then supplying the constructor arguments. This part of the\nproof is quadratic, but quite simple. (We could do it in `O(n log n)` if we used a balanced tree\nfor the unions.)\n\nThe tactics perform the following parts of this proof scheme:\n* `mk_sigma` constructs the type `Γ` in `finset_in.mk`\n* `mk_sigma_elim` constructs the function `f` in `finset_in.mk`\n* `mk_sigma_elim_inj` proves that `f` is injective\n* `mk_sigma_elim_eq` proves that `∀ a, enum (f a) = k`\n* `mk_finset` constructs the finset `S = {foo.zero} ∪ ...` by recursion on the variants\n* `mk_finset_total` constructs the proof `|- foo.zero ∈ S; |- foo.one a ∈ S; |- foo.two a b ∈ S`\n by recursion on the subgoals coming out of the initial `cases`\n* `mk_fintype_instance` puts it all together to produce a proof of `fintype foo`.\n The construction of `foo.enum` is also done in this function.\n\n-/\n\nnamespace derive_fintype\n\n\n/-- A step in the construction of `finset.univ` for a finite inductive type.\nWe will set `enum` to the discriminant of the inductive type, so a `finset_above`\nrepresents a finset that enumerates all elements in a tail of the constructor list. -/\ndef finset_above (α : Type u_1) (enum : α → ℕ) (n : ℕ) :=\n Subtype fun (s : finset α) => ∀ (x : α), x ∈ s → n ≤ enum x\n\n/-- Construct a fintype instance from a completed `finset_above`. -/\ndef mk_fintype {α : Type u_1} (enum : α → ℕ) (s : finset_above α enum 0) (H : ∀ (x : α), x ∈ subtype.val s) : fintype α :=\n fintype.mk (subtype.val s) H\n\n/-- This is the case for a simple variant (no arguments) in an inductive type. -/\ndef finset_above.cons {α : Type u_1} {enum : α → ℕ} (n : ℕ) (a : α) (h : enum a = n) (s : finset_above α enum (n + 1)) : finset_above α enum n :=\n { val := finset.cons a (subtype.val s) sorry, property := sorry }\n\ntheorem finset_above.mem_cons_self {α : Type u_1} {enum : α → ℕ} {n : ℕ} {a : α} {h : enum a = n} {s : finset_above α enum (n + 1)} : a ∈ subtype.val (finset_above.cons n a h s) :=\n multiset.mem_cons_self a (finset.val (subtype.val s))\n\ntheorem finset_above.mem_cons_of_mem {α : Type u_1} {enum : α → ℕ} {n : ℕ} {a : α} {h : enum a = n} {s : finset_above α enum (n + 1)} {b : α} : b ∈ subtype.val s → b ∈ subtype.val (finset_above.cons n a h s) :=\n multiset.mem_cons_of_mem\n\n/-- The base case is when we run out of variants; we just put an empty finset at the end. -/\ndef finset_above.nil {α : Type u_1} {enum : α → ℕ} (n : ℕ) : finset_above α enum n :=\n { val := ∅, property := sorry }\n\nprotected instance finset_above.inhabited (α : Type u_1) (enum : α → ℕ) (n : ℕ) : Inhabited (finset_above α enum n) :=\n { default := finset_above.nil n }\n\n/-- This is a finset covering a nontrivial variant (with one or more constructor arguments).\nThe property `P` here is `λ a, enum a = n` where `n` is the discriminant for the current\nvariant. -/\ndef finset_in {α : Type u_1} (P : α → Prop) :=\n Subtype fun (s : finset α) => ∀ (x : α), x ∈ s → P x\n\n/-- To construct the finset, we use an injective map from the type `Γ`, which will be the\nsigma over all constructor arguments. We use sigma instances and existing fintype instances\nto prove that `Γ` is a fintype, and construct the function `f` that maps `⟨a, b, c, ...⟩`\nto `C_n a b c ...` where `C_n` is the nth constructor, and `mem` asserts\n`enum (C_n a b c ...) = n`. -/\ndef finset_in.mk {α : Type u_1} {P : α → Prop} (Γ : Type u_2) [fintype Γ] (f : Γ → α) (inj : function.injective f) (mem : ∀ (x : Γ), P (f x)) : finset_in P :=\n { val := finset.map (function.embedding.mk f inj) finset.univ, property := sorry }\n\ntheorem finset_in.mem_mk {α : Type u_1} {P : α → Prop} {Γ : Type u_2} {s : fintype Γ} {f : Γ → α} {inj : function.injective f} {mem : ∀ (x : Γ), P (f x)} {a : α} (b : Γ) (H : f b = a) : a ∈ subtype.val (finset_in.mk Γ f inj mem) :=\n iff.mpr finset.mem_map (Exists.intro b (Exists.intro (finset.mem_univ b) H))\n\n/-- For nontrivial variants, we split the constructor list into a `finset_in` component for the\ncurrent constructor and a `finset_above` for the rest. -/\ndef finset_above.union {α : Type u_1} {enum : α → ℕ} (n : ℕ) (s : finset_in fun (a : α) => enum a = n) (t : finset_above α enum (n + 1)) : finset_above α enum n :=\n { val := finset.disj_union (subtype.val s) (subtype.val t) sorry, property := sorry }\n\ntheorem finset_above.mem_union_left {α : Type u_1} {enum : α → ℕ} {n : ℕ} {s : finset_in fun (a : α) => enum a = n} {t : finset_above α enum (n + 1)} {a : α} (H : a ∈ subtype.val s) : a ∈ subtype.val (finset_above.union n s t) :=\n iff.mpr multiset.mem_add (Or.inl H)\n\ntheorem finset_above.mem_union_right {α : Type u_1} {enum : α → ℕ} {n : ℕ} {s : finset_in fun (a : α) => enum a = n} {t : finset_above α enum (n + 1)} {a : α} (H : a ∈ subtype.val t) : a ∈ subtype.val (finset_above.union n s t) :=\n iff.mpr multiset.mem_add (Or.inr H)\n\n", "meta": {"author": "AurelienSaue", "repo": "Mathlib4_auto", "sha": "590df64109b08190abe22358fabc3eae000943f2", "save_path": "github-repos/lean/AurelienSaue-Mathlib4_auto", "path": "github-repos/lean/AurelienSaue-Mathlib4_auto/Mathlib4_auto-590df64109b08190abe22358fabc3eae000943f2/Mathlib/tactic/derive_fintype.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879062662624366, "lm_q2_score": 0.06656918758161513, "lm_q1q2_score": 0.031207011160385316}} {"text": "/-\nCopyright (c) 2022 Yaël Dillies. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Yaël Dillies\n-/\nimport category_theory.category.Pointed\n\n/-!\n# The category of bipointed types\n\nThis defines `Bipointed`, the category of bipointed types.\n\n## TODO\n\nMonoidal structure\n-/\n\nopen category_theory\n\nuniverses u\nvariables {α β : Type*}\n\n/-- The category of bipointed types. -/\nstructure Bipointed : Type.{u + 1} :=\n(X : Type.{u})\n(to_prod : X × X)\n\nnamespace Bipointed\n\ninstance : has_coe_to_sort Bipointed Type* := ⟨X⟩\n\nattribute [protected] Bipointed.X\n\n/-- Turns a bipointing into a bipointed type. -/\ndef of {X : Type*} (to_prod : X × X) : Bipointed := ⟨X, to_prod⟩\n\n@[simp] lemma coe_of {X : Type*} (to_prod : X × X) : ↥(of to_prod) = X := rfl\n\nalias of ← prod.Bipointed\n\ninstance : inhabited Bipointed := ⟨of ((), ())⟩\n\n/-- Morphisms in `Bipointed`. -/\n@[ext] protected structure hom (X Y : Bipointed.{u}) : Type u :=\n(to_fun : X → Y)\n(map_fst : to_fun X.to_prod.1 = Y.to_prod.1)\n(map_snd : to_fun X.to_prod.2 = Y.to_prod.2)\n\nnamespace hom\n\n/-- The identity morphism of `X : Bipointed`. -/\n@[simps] def id (X : Bipointed) : hom X X := ⟨id, rfl, rfl⟩\n\ninstance (X : Bipointed) : inhabited (hom X X) := ⟨id X⟩\n\n/-- Composition of morphisms of `Bipointed`. -/\n@[simps] def comp {X Y Z : Bipointed.{u}} (f : hom X Y) (g : hom Y Z) : hom X Z :=\n⟨g.to_fun ∘ f.to_fun, by rw [function.comp_apply, f.map_fst, g.map_fst],\n by rw [function.comp_apply, f.map_snd, g.map_snd]⟩\n\nend hom\n\ninstance large_category : large_category Bipointed :=\n{ hom := hom,\n id := hom.id,\n comp := @hom.comp,\n id_comp' := λ _ _ _, hom.ext _ _ rfl,\n comp_id' := λ _ _ _, hom.ext _ _ rfl,\n assoc' := λ _ _ _ _ _ _ _, hom.ext _ _ rfl }\n\ninstance concrete_category : concrete_category Bipointed :=\n{ forget := { obj := Bipointed.X, map := @hom.to_fun },\n forget_faithful := ⟨@hom.ext⟩ }\n\n/-- Swaps the pointed elements of a bipointed type. `prod.swap` as a functor. -/\n@[simps] def swap : Bipointed ⥤ Bipointed :=\n{ obj := λ X, ⟨X, X.to_prod.swap⟩, map := λ X Y f, ⟨f.to_fun, f.map_snd, f.map_fst⟩ }\n\n/-- The equivalence between `Bipointed` and itself induced by `prod.swap` both ways. -/\n@[simps] def swap_equiv : Bipointed ≌ Bipointed :=\nequivalence.mk swap swap\n (nat_iso.of_components (λ X, { hom := ⟨id, rfl, rfl⟩, inv := ⟨id, rfl, rfl⟩ }) $ λ X Y f, rfl)\n (nat_iso.of_components (λ X, { hom := ⟨id, rfl, rfl⟩, inv := ⟨id, rfl, rfl⟩ }) $ λ X Y f, rfl)\n\n@[simp] lemma swap_equiv_symm : swap_equiv.symm = swap_equiv := rfl\n\nend Bipointed\n\n/-- The forgetful functor from `Bipointed` to `Pointed` which forgets about the second point. -/\ndef Bipointed_to_Pointed_fst : Bipointed ⥤ Pointed :=\n{ obj := λ X, ⟨X, X.to_prod.1⟩, map := λ X Y f, ⟨f.to_fun, f.map_fst⟩ }\n\n/-- The forgetful functor from `Bipointed` to `Pointed` which forgets about the first point. -/\ndef Bipointed_to_Pointed_snd : Bipointed ⥤ Pointed :=\n{ obj := λ X, ⟨X, X.to_prod.2⟩, map := λ X Y f, ⟨f.to_fun, f.map_snd⟩ }\n\n@[simp] lemma Bipointed_to_Pointed_fst_comp_forget :\n Bipointed_to_Pointed_fst ⋙ forget Pointed = forget Bipointed := rfl\n\n@[simp] lemma Bipointed_to_Pointed_snd_comp_forget :\n Bipointed_to_Pointed_snd ⋙ forget Pointed = forget Bipointed := rfl\n\n@[simp] lemma swap_comp_Bipointed_to_Pointed_fst :\n Bipointed.swap ⋙ Bipointed_to_Pointed_fst = Bipointed_to_Pointed_snd := rfl\n\n@[simp] lemma swap_comp_Bipointed_to_Pointed_snd :\n Bipointed.swap ⋙ Bipointed_to_Pointed_snd = Bipointed_to_Pointed_fst := rfl\n\n/-- The functor from `Pointed` to `Bipointed` which bipoints the point. -/\ndef Pointed_to_Bipointed : Pointed.{u} ⥤ Bipointed :=\n{ obj := λ X, ⟨X, X.point, X.point⟩, map := λ X Y f, ⟨f.to_fun, f.map_point, f.map_point⟩ }\n\n/-- The functor from `Pointed` to `Bipointed` which adds a second point. -/\ndef Pointed_to_Bipointed_fst : Pointed.{u} ⥤ Bipointed :=\n{ obj := λ X, ⟨option X, X.point, none⟩,\n map := λ X Y f, ⟨option.map f.to_fun, congr_arg _ f.map_point, rfl⟩,\n map_id' := λ X, Bipointed.hom.ext _ _ option.map_id,\n map_comp' := λ X Y Z f g, Bipointed.hom.ext _ _ (option.map_comp_map _ _).symm }\n\n/-- The functor from `Pointed` to `Bipointed` which adds a first point. -/\ndef Pointed_to_Bipointed_snd : Pointed.{u} ⥤ Bipointed :=\n{ obj := λ X, ⟨option X, none, X.point⟩,\n map := λ X Y f, ⟨option.map f.to_fun, rfl, congr_arg _ f.map_point⟩,\n map_id' := λ X, Bipointed.hom.ext _ _ option.map_id,\n map_comp' := λ X Y Z f g, Bipointed.hom.ext _ _ (option.map_comp_map _ _).symm }\n\n@[simp] lemma Pointed_to_Bipointed_fst_comp_swap :\n Pointed_to_Bipointed_fst ⋙ Bipointed.swap = Pointed_to_Bipointed_snd := rfl\n\n@[simp] lemma Pointed_to_Bipointed_snd_comp_swap :\n Pointed_to_Bipointed_snd ⋙ Bipointed.swap = Pointed_to_Bipointed_fst := rfl\n\n/-- `Bipointed_to_Pointed_fst` is inverse to `Pointed_to_Bipointed`. -/\n@[simps] def Pointed_to_Bipointed_comp_Bipointed_to_Pointed_fst :\n Pointed_to_Bipointed ⋙ Bipointed_to_Pointed_fst ≅ 𝟭 _ :=\nnat_iso.of_components (λ X, { hom := ⟨id, rfl⟩, inv := ⟨id, rfl⟩ }) $ λ X Y f, rfl\n\n/-- `Bipointed_to_Pointed_snd` is inverse to `Pointed_to_Bipointed`. -/\n@[simps] def Pointed_to_Bipointed_comp_Bipointed_to_Pointed_snd :\n Pointed_to_Bipointed ⋙ Bipointed_to_Pointed_snd ≅ 𝟭 _ :=\nnat_iso.of_components (λ X, { hom := ⟨id, rfl⟩, inv := ⟨id, rfl⟩ }) $ λ X Y f, rfl\n\n/-- The free/forgetful adjunction between `Pointed_to_Bipointed_fst` and `Bipointed_to_Pointed_fst`.\n-/\ndef Pointed_to_Bipointed_fst_Bipointed_to_Pointed_fst_adjunction :\n Pointed_to_Bipointed_fst ⊣ Bipointed_to_Pointed_fst :=\nadjunction.mk_of_hom_equiv\n{ hom_equiv := λ X Y, { to_fun := λ f, ⟨f.to_fun ∘ option.some, f.map_fst⟩,\n inv_fun := λ f, ⟨λ o, o.elim Y.to_prod.2 f.to_fun, f.map_point, rfl⟩,\n left_inv := λ f, by { ext, cases x, exact f.map_snd.symm, refl },\n right_inv := λ f, Pointed.hom.ext _ _ rfl },\n hom_equiv_naturality_left_symm' := λ X' X Y f g, by { ext, cases x; refl } }\n\n/-- The free/forgetful adjunction between `Pointed_to_Bipointed_snd` and `Bipointed_to_Pointed_snd`.\n-/\ndef Pointed_to_Bipointed_snd_Bipointed_to_Pointed_snd_adjunction :\n Pointed_to_Bipointed_snd ⊣ Bipointed_to_Pointed_snd :=\nadjunction.mk_of_hom_equiv\n{ hom_equiv := λ X Y, { to_fun := λ f, ⟨f.to_fun ∘ option.some, f.map_snd⟩,\n inv_fun := λ f, ⟨λ o, o.elim Y.to_prod.1 f.to_fun, rfl, f.map_point⟩,\n left_inv := λ f, by { ext, cases x, exact f.map_fst.symm, refl },\n right_inv := λ f, Pointed.hom.ext _ _ rfl },\n hom_equiv_naturality_left_symm' := λ X' X Y f g, by { ext, cases x; refl } }\n", "meta": {"author": "saisurbehera", "repo": "mathProof", "sha": "57c6bfe75652e9d3312d8904441a32aff7d6a75e", "save_path": "github-repos/lean/saisurbehera-mathProof", "path": "github-repos/lean/saisurbehera-mathProof/mathProof-57c6bfe75652e9d3312d8904441a32aff7d6a75e/src/tertiary_packages/mathlib/src/category_theory/category/Bipointed.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4339814501625211, "lm_q2_score": 0.07159119300682869, "lm_q1q2_score": 0.031069249759968453}} {"text": "/-\nCopyright (c) 2018 Simon Hudon. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Simon Hudon\n-/\nimport control.applicative\nimport data.list.forall2\nimport data.set.functor\n\n/-!\n# Traversable instances\n\n> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.\n> Any changes to this file require a corresponding PR to mathlib4.\n\nThis file provides instances of `traversable` for types from the core library: `option`, `list` and\n`sum`.\n-/\n\nuniverses u v\n\nsection option\n\nopen functor\n\nvariables {F G : Type u → Type u}\nvariables [applicative F] [applicative G]\nvariables [is_lawful_applicative F] [is_lawful_applicative G]\n\nlemma option.id_traverse {α} (x : option α) : option.traverse id.mk x = x :=\nby cases x; refl\n\n@[nolint unused_arguments]\nlemma option.comp_traverse {α β γ} (f : β → F γ) (g : α → G β) (x : option α) :\n option.traverse (comp.mk ∘ (<$>) f ∘ g) x =\n comp.mk (option.traverse f <$> option.traverse g x) :=\nby cases x; simp! with functor_norm; refl\n\nlemma option.traverse_eq_map_id {α β} (f : α → β) (x : option α) :\n traverse (id.mk ∘ f) x = id.mk (f <$> x) :=\nby cases x; refl\n\nvariable (η : applicative_transformation F G)\n\nlemma option.naturality {α β} (f : α → F β) (x : option α) :\n η (option.traverse f x) = option.traverse (@η _ ∘ f) x :=\nby cases x with x; simp! [*] with functor_norm\n\nend option\n\ninstance : is_lawful_traversable option :=\n{ id_traverse := @option.id_traverse,\n comp_traverse := @option.comp_traverse,\n traverse_eq_map_id := @option.traverse_eq_map_id,\n naturality := @option.naturality,\n .. option.is_lawful_monad }\n\nnamespace list\n\nvariables {F G : Type u → Type u}\nvariables [applicative F] [applicative G]\n\nsection\nvariables [is_lawful_applicative F] [is_lawful_applicative G]\n\nopen applicative functor list\n\nprotected \n\n@[nolint unused_arguments]\nprotected lemma comp_traverse {α β γ} (f : β → F γ) (g : α → G β) (x : list α) :\n list.traverse (comp.mk ∘ (<$>) f ∘ g) x =\n comp.mk (list.traverse f <$> list.traverse g x) :=\nby induction x; simp! * with functor_norm; refl\n\nprotected lemma traverse_eq_map_id {α β} (f : α → β) (x : list α) :\n list.traverse (id.mk ∘ f) x = id.mk (f <$> x) :=\nby induction x; simp! * with functor_norm; refl\n\nvariable (η : applicative_transformation F G)\n\nprotected lemma naturality {α β} (f : α → F β) (x : list α) :\n η (list.traverse f x) = list.traverse (@η _ ∘ f) x :=\nby induction x; simp! * with functor_norm\nopen nat\n\ninstance : is_lawful_traversable.{u} list :=\n{ id_traverse := @list.id_traverse,\n comp_traverse := @list.comp_traverse,\n traverse_eq_map_id := @list.traverse_eq_map_id,\n naturality := @list.naturality,\n .. list.is_lawful_monad }\nend\n\nsection traverse\nvariables {α' β' : Type u} (f : α' → F β')\n\n@[simp] lemma traverse_nil : traverse f ([] : list α') = (pure [] : F (list β')) := rfl\n\n@[simp] lemma traverse_cons (a : α') (l : list α') :\n traverse f (a :: l) = (::) <$> f a <*> traverse f l := rfl\n\nvariables [is_lawful_applicative F]\n\n@[simp] lemma traverse_append :\n ∀ (as bs : list α'), traverse f (as ++ bs) = (++) <$> traverse f as <*> traverse f bs\n| [] bs :=\n have has_append.append ([] : list β') = id, by funext; refl,\n by simp [this] with functor_norm\n| (a :: as) bs := by simp [traverse_append as bs] with functor_norm; congr\n\nlemma mem_traverse {f : α' → set β'} :\n ∀(l : list α') (n : list β'), n ∈ traverse f l ↔ forall₂ (λb a, b ∈ f a) n l\n| [] [] := by simp\n| (a::as) [] := by simp\n| [] (b::bs) := by simp\n| (a::as) (b::bs) := by simp [mem_traverse as bs]\n\nend traverse\n\nend list\n\nnamespace sum\n\nsection traverse\nvariables {σ : Type u}\nvariables {F G : Type u → Type u}\nvariables [applicative F] [applicative G]\n\nopen applicative functor\nopen list (cons)\n\nprotected lemma traverse_map {α β γ : Type u} (g : α → β) (f : β → G γ) (x : σ ⊕ α) :\n sum.traverse f (g <$> x) = sum.traverse (f ∘ g) x :=\nby cases x; simp [sum.traverse, id_map] with functor_norm; refl\n\nvariables [is_lawful_applicative F] [is_lawful_applicative G]\n\nprotected lemma id_traverse {σ α} (x : σ ⊕ α) : sum.traverse id.mk x = x :=\nby cases x; refl\n\n@[nolint unused_arguments]\nprotected lemma comp_traverse {α β γ} (f : β → F γ) (g : α → G β) (x : σ ⊕ α) :\n sum.traverse (comp.mk ∘ (<$>) f ∘ g) x =\n comp.mk (sum.traverse f <$> sum.traverse g x) :=\nby cases x; simp! [sum.traverse,map_id] with functor_norm; refl\n\nprotected lemma traverse_eq_map_id {α β} (f : α → β) (x : σ ⊕ α) :\n sum.traverse (id.mk ∘ f) x = id.mk (f <$> x) :=\nby induction x; simp! * with functor_norm; refl\n\nprotected lemma map_traverse {α β γ} (g : α → G β) (f : β → γ) (x : σ ⊕ α) :\n (<$>) f <$> sum.traverse g x = sum.traverse ((<$>) f ∘ g) x :=\nby cases x; simp [sum.traverse, id_map] with functor_norm; congr; refl\n\nvariable (η : applicative_transformation F G)\n\nprotected lemma naturality {α β} (f : α → F β) (x : σ ⊕ α) :\n η (sum.traverse f x) = sum.traverse (@η _ ∘ f) x :=\nby cases x; simp! [sum.traverse] with functor_norm\n\nend traverse\n\ninstance {σ : Type u} : is_lawful_traversable.{u} (sum σ) :=\n{ id_traverse := @sum.id_traverse σ,\n comp_traverse := @sum.comp_traverse σ,\n traverse_eq_map_id := @sum.traverse_eq_map_id σ,\n naturality := @sum.naturality σ,\n .. sum.is_lawful_monad }\n\nend sum\n", "meta": {"author": "leanprover-community", "repo": "mathlib", "sha": "5e526d18cea33550268dcbbddcb822d5cde40654", "save_path": "github-repos/lean/leanprover-community-mathlib", "path": "github-repos/lean/leanprover-community-mathlib/mathlib-5e526d18cea33550268dcbbddcb822d5cde40654/src/control/traversable/instances.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42632157796989345, "lm_q2_score": 0.07263670033827889, "lm_q1q2_score": 0.03096659270674135}} {"text": "example (p q r : Prop) (hp : p) (hq : q) (hr : r) : p ∧ ((p ∧ q) ∧ r) ∧ (q ∧ r ∧ p) :=\n by repeat { any_goals { split <|> assumption} }\n", "meta": {"author": "Ailrun", "repo": "Theorem_Proving_in_Lean", "sha": "2eb1b5caf93c6a5a555c79e9097cf2ba5a66cf68", "save_path": "github-repos/lean/Ailrun-Theorem_Proving_in_Lean", "path": "github-repos/lean/Ailrun-Theorem_Proving_in_Lean/Theorem_Proving_in_Lean-2eb1b5caf93c6a5a555c79e9097cf2ba5a66cf68/src/ch5/ex0512.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.39606816627404173, "lm_q2_score": 0.07807817050802546, "lm_q1q2_score": 0.03092427781914561}} {"text": "/-\nCopyright (c) 2017 Johannes Hölzl. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Johannes Hölzl\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.default\nimport Mathlib.tactic.basic\nimport Mathlib.PostPort\n\nuniverses u_1 u_2 u_3 u_4 u_5 u_6 \n\nnamespace Mathlib\n\n/-!\n# Extra facts about `prod`\n\nThis file defines `prod.swap : α × β → β × α` and proves various simple lemmas about `prod`.\n-/\n\n@[simp] theorem prod_map {α : Type u_1} {β : Type u_2} {γ : Type u_3} {δ : Type u_4} (f : α → γ) (g : β → δ) (p : α × β) : prod.map f g p = (f (prod.fst p), g (prod.snd p)) :=\n rfl\n\nnamespace prod\n\n\n@[simp] theorem forall {α : Type u_1} {β : Type u_2} {p : α × β → Prop} : (∀ (x : α × β), p x) ↔ ∀ (a : α) (b : β), p (a, b) := sorry\n\n@[simp] theorem exists {α : Type u_1} {β : Type u_2} {p : α × β → Prop} : (∃ (x : α × β), p x) ↔ ∃ (a : α), ∃ (b : β), p (a, b) := sorry\n\ntheorem forall' {α : Type u_1} {β : Type u_2} {p : α → β → Prop} : (∀ (x : α × β), p (fst x) (snd x)) ↔ ∀ (a : α) (b : β), p a b :=\n forall\n\ntheorem exists' {α : Type u_1} {β : Type u_2} {p : α → β → Prop} : (∃ (x : α × β), p (fst x) (snd x)) ↔ ∃ (a : α), ∃ (b : β), p a b :=\n exists\n\n@[simp] theorem map_mk {α : Type u_1} {β : Type u_2} {γ : Type u_3} {δ : Type u_4} (f : α → γ) (g : β → δ) (a : α) (b : β) : map f g (a, b) = (f a, g b) :=\n rfl\n\ntheorem map_fst {α : Type u_1} {β : Type u_2} {γ : Type u_3} {δ : Type u_4} (f : α → γ) (g : β → δ) (p : α × β) : fst (map f g p) = f (fst p) :=\n rfl\n\ntheorem map_snd {α : Type u_1} {β : Type u_2} {γ : Type u_3} {δ : Type u_4} (f : α → γ) (g : β → δ) (p : α × β) : snd (map f g p) = g (snd p) :=\n rfl\n\ntheorem map_fst' {α : Type u_1} {β : Type u_2} {γ : Type u_3} {δ : Type u_4} (f : α → γ) (g : β → δ) : fst ∘ map f g = f ∘ fst :=\n funext (map_fst f g)\n\ntheorem map_snd' {α : Type u_1} {β : Type u_2} {γ : Type u_3} {δ : Type u_4} (f : α → γ) (g : β → δ) : snd ∘ map f g = g ∘ snd :=\n funext (map_snd f g)\n\n/--\nComposing a `prod.map` with another `prod.map` is equal to\na single `prod.map` of composed functions.\n-/\ntheorem map_comp_map {α : Type u_1} {β : Type u_2} {γ : Type u_3} {δ : Type u_4} {ε : Type u_5} {ζ : Type u_6} (f : α → β) (f' : γ → δ) (g : β → ε) (g' : δ → ζ) : map g g' ∘ map f f' = map (g ∘ f) (g' ∘ f') :=\n rfl\n\n/--\nComposing a `prod.map` with another `prod.map` is equal to\na single `prod.map` of composed functions, fully applied.\n-/\ntheorem map_map {α : Type u_1} {β : Type u_2} {γ : Type u_3} {δ : Type u_4} {ε : Type u_5} {ζ : Type u_6} (f : α → β) (f' : γ → δ) (g : β → ε) (g' : δ → ζ) (x : α × γ) : map g g' (map f f' x) = map (g ∘ f) (g' ∘ f') x :=\n rfl\n\n@[simp] theorem mk.inj_iff {α : Type u_1} {β : Type u_2} {a₁ : α} {a₂ : α} {b₁ : β} {b₂ : β} : (a₁, b₁) = (a₂, b₂) ↔ a₁ = a₂ ∧ b₁ = b₂ := sorry\n\ntheorem mk.inj_left {α : Type u_1} {β : Type u_2} (a : α) : function.injective (Prod.mk a) := sorry\n\ntheorem mk.inj_right {α : Type u_1} {β : Type u_2} (b : β) : function.injective fun (a : α) => (a, b) := sorry\n\ntheorem ext_iff {α : Type u_1} {β : Type u_2} {p : α × β} {q : α × β} : p = q ↔ fst p = fst q ∧ snd p = snd q := sorry\n\ntheorem ext {α : Type u_1} {β : Type u_2} {p : α × β} {q : α × β} (h₁ : fst p = fst q) (h₂ : snd p = snd q) : p = q :=\n iff.mpr ext_iff { left := h₁, right := h₂ }\n\ntheorem map_def {α : Type u_1} {β : Type u_2} {γ : Type u_3} {δ : Type u_4} {f : α → γ} {g : β → δ} : map f g = fun (p : α × β) => (f (fst p), g (snd p)) :=\n funext fun (p : α × β) => ext (map_fst f g p) (map_snd f g p)\n\ntheorem id_prod {α : Type u_1} : (fun (p : α × α) => (fst p, snd p)) = id := sorry\n\ntheorem fst_surjective {α : Type u_1} {β : Type u_2} [h : Nonempty β] : function.surjective fst :=\n fun (x : α) => nonempty.elim h fun (y : β) => Exists.intro (x, y) rfl\n\ntheorem snd_surjective {α : Type u_1} {β : Type u_2} [h : Nonempty α] : function.surjective snd :=\n fun (y : β) => nonempty.elim h fun (x : α) => Exists.intro (x, y) rfl\n\ntheorem fst_injective {α : Type u_1} {β : Type u_2} [subsingleton β] : function.injective fst :=\n fun (x y : α × β) (h : fst x = fst y) => ext h (subsingleton.elim (snd x) (snd y))\n\ntheorem snd_injective {α : Type u_1} {β : Type u_2} [subsingleton α] : function.injective snd :=\n fun (x y : α × β) (h : snd x = snd y) => ext (subsingleton.elim (fst x) (fst y)) h\n\n/-- Swap the factors of a product. `swap (a, b) = (b, a)` -/\ndef swap {α : Type u_1} {β : Type u_2} : α × β → β × α :=\n fun (p : α × β) => (snd p, fst p)\n\n@[simp] theorem swap_swap {α : Type u_1} {β : Type u_2} (x : α × β) : swap (swap x) = x :=\n cases_on x fun (x_fst : α) (x_snd : β) => idRhs (swap (swap (x_fst, x_snd)) = swap (swap (x_fst, x_snd))) rfl\n\n@[simp] theorem fst_swap {α : Type u_1} {β : Type u_2} {p : α × β} : fst (swap p) = snd p :=\n rfl\n\n@[simp] theorem snd_swap {α : Type u_1} {β : Type u_2} {p : α × β} : snd (swap p) = fst p :=\n rfl\n\n@[simp] theorem swap_prod_mk {α : Type u_1} {β : Type u_2} {a : α} {b : β} : swap (a, b) = (b, a) :=\n rfl\n\n@[simp] theorem swap_swap_eq {α : Type u_1} {β : Type u_2} : swap ∘ swap = id :=\n funext swap_swap\n\n@[simp] theorem swap_left_inverse {α : Type u_1} {β : Type u_2} : function.left_inverse swap swap :=\n swap_swap\n\n@[simp] theorem swap_right_inverse {α : Type u_1} {β : Type u_2} : function.right_inverse swap swap :=\n swap_swap\n\ntheorem swap_injective {α : Type u_1} {β : Type u_2} : function.injective swap :=\n function.left_inverse.injective swap_left_inverse\n\ntheorem swap_surjective {α : Type u_1} {β : Type u_2} : function.surjective swap :=\n function.left_inverse.surjective swap_left_inverse\n\ntheorem swap_bijective {α : Type u_1} {β : Type u_2} : function.bijective swap :=\n { left := swap_injective, right := swap_surjective }\n\n@[simp] theorem swap_inj {α : Type u_1} {β : Type u_2} {p : α × β} {q : α × β} : swap p = swap q ↔ p = q :=\n function.injective.eq_iff swap_injective\n\ntheorem eq_iff_fst_eq_snd_eq {α : Type u_1} {β : Type u_2} {p : α × β} {q : α × β} : p = q ↔ fst p = fst q ∧ snd p = snd q := sorry\n\ntheorem fst_eq_iff {α : Type u_1} {β : Type u_2} {p : α × β} {x : α} : fst p = x ↔ p = (x, snd p) := sorry\n\ntheorem snd_eq_iff {α : Type u_1} {β : Type u_2} {p : α × β} {x : β} : snd p = x ↔ p = (fst p, x) := sorry\n\ntheorem lex_def {α : Type u_1} {β : Type u_2} (r : α → α → Prop) (s : β → β → Prop) {p : α × β} {q : α × β} : lex r s p q ↔ r (fst p) (fst q) ∨ fst p = fst q ∧ s (snd p) (snd q) := sorry\n\nprotected instance lex.decidable {α : Type u_1} {β : Type u_2} [DecidableEq α] (r : α → α → Prop) (s : β → β → Prop) [DecidableRel r] [DecidableRel s] : DecidableRel (lex r s) :=\n fun (p q : α × β) => decidable_of_decidable_of_iff or.decidable sorry\n\nend prod\n\n\ntheorem function.injective.prod_map {α : Type u_1} {β : Type u_2} {γ : Type u_3} {δ : Type u_4} {f : α → γ} {g : β → δ} (hf : function.injective f) (hg : function.injective g) : function.injective (prod.map f g) :=\n fun (x y : α × β) (h : prod.map f g x = prod.map f g y) =>\n prod.ext (hf (and.left (iff.mp prod.ext_iff h))) (hg (and.right (iff.mp prod.ext_iff h)))\n\ntheorem function.surjective.prod_map {α : Type u_1} {β : Type u_2} {γ : Type u_3} {δ : Type u_4} {f : α → γ} {g : β → δ} (hf : function.surjective f) (hg : function.surjective g) : function.surjective (prod.map f g) := sorry\n\n", "meta": {"author": "AurelienSaue", "repo": "Mathlib4_auto", "sha": "590df64109b08190abe22358fabc3eae000943f2", "save_path": "github-repos/lean/AurelienSaue-Mathlib4_auto", "path": "github-repos/lean/AurelienSaue-Mathlib4_auto/Mathlib4_auto-590df64109b08190abe22358fabc3eae000943f2/Mathlib/data/prod.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45713670203584295, "lm_q2_score": 0.06754668832401889, "lm_q1q2_score": 0.030878070333884976}} {"text": "/-\nCopyright (c) 2020 Bhavik Mehta, Edward Ayers. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Bhavik Mehta, Edward Ayers\n-/\n\nimport category_theory.limits.shapes\nimport category_theory.limits.preserves.limits\nimport category_theory.limits.over\nimport category_theory.limits.shapes.constructions.over\nimport tactic\n\n/-!\n# Pullbacks\n\nMany, many lemmas to work with pullbacks.\n-/\nopen category_theory category_theory.category category_theory.limits\n\nnoncomputable theory\nuniverses u v\nvariables {C : Type u} [category.{v} C]\nvariables {J : Type v} [small_category J]\n\nvariables {W X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z}\n\n/-- A supremely useful structure for elementary topos theory. -/\nstructure has_pullback_top (left : W ⟶ Y) (bottom : Y ⟶ Z) (right : X ⟶ Z) :=\n(top : W ⟶ X)\n(comm : top ≫ right = left ≫ bottom)\n(is_pb : is_limit (pullback_cone.mk _ _ comm))\n\nattribute [reassoc] has_pullback_top.comm\n\ninstance subsingleton_hpb (left : W ⟶ Y) (bottom : Y ⟶ Z) (right : X ⟶ Z) [mono right] :\n subsingleton (has_pullback_top left bottom right) :=\n⟨begin\n intros P Q,\n cases P,\n cases Q,\n congr,\n rw ← cancel_mono right,\n rw P_comm, rw Q_comm\nend⟩\n\ndef has_pullback_top_of_is_pb {U V W X : C}\n {f : U ⟶ V} {g : V ⟶ W} {h : U ⟶ X} {k : X ⟶ W}\n {comm : f ≫ g = h ≫ k}\n (pb : is_limit (pullback_cone.mk _ _ comm)) :\n has_pullback_top h k g :=\n{ top := f,\n comm := comm,\n is_pb := pb }\n\ndef is_limit.mk' (t : pullback_cone f g)\n (create : Π (s : pullback_cone f g), {l : s.X ⟶ t.X // l ≫ t.fst = s.fst ∧ l ≫ t.snd = s.snd ∧ ∀ {m : s.X ⟶ t.X}, m ≫ t.fst = s.fst → m ≫ t.snd = s.snd → m = l}) :\nis_limit t :=\npullback_cone.is_limit_aux' t create\n\ndef is_limit.mk'' (t : pullback_cone f g) [mono f]\n (create : Π (s : pullback_cone f g), {l : s.X ⟶ t.X // l ≫ t.snd = s.snd ∧ ∀ {m : s.X ⟶ t.X}, m ≫ t.fst = s.fst → m ≫ t.snd = s.snd → m = l}) :\nis_limit t :=\nis_limit.mk' t $\nbegin\n intro s,\n refine ⟨(create s).1, _, (create s).2.1, λ m m₁ m₂, (create s).2.2 m₁ m₂⟩,\n rw [← cancel_mono f, assoc, t.condition, s.condition, reassoc_of (create s).2.1]\nend\n\ndef is_limit.mk''' (t : pullback_cone f g) [mono f] (q : mono t.snd)\n (create : Π (s : pullback_cone f g), {l : s.X ⟶ t.X // l ≫ t.snd = s.snd}) :\nis_limit t :=\nis_limit.mk' t $\nbegin\n intro s,\n refine ⟨(create s).1, _, (create s).2, λ m _ m₂, _⟩,\n rw [← cancel_mono f, assoc, t.condition, s.condition, reassoc_of (create s).2],\n rw [← cancel_mono t.snd, m₂, (create s).2],\nend\n\ndef construct_type_pb {W X Y Z : Type u} {f : X ⟶ Z} {g : Y ⟶ Z} {h : W ⟶ _} {k} (comm : h ≫ f = k ≫ g) :\n (∀ (x : X) (y : Y), f x = g y → {t // h t = x ∧ k t = y ∧ ∀ t', h t' = x → k t' = y → t' = t}) → is_limit (pullback_cone.mk _ _ comm) :=\nbegin\n intro z,\n apply is_limit.mk' _ _,\n intro s,\n refine ⟨λ t, _, _, _, _⟩,\n refine (z (s.fst t) (s.snd t) (congr_fun s.condition t)).1,\n ext t,\n apply (z (s.fst t) (s.snd t) (congr_fun s.condition t)).2.1,\n ext t,\n apply (z (s.fst t) (s.snd t) (congr_fun s.condition t)).2.2.1,\n intros m m₁ m₂,\n ext t,\n apply (z (s.fst t) (s.snd t) (congr_fun s.condition t)).2.2.2,\n apply congr_fun m₁ t,\n apply congr_fun m₂ t,\nend\n\ndef pullback_mono_is_mono (c : pullback_cone f g) [mono f] (t : is_limit c) : mono c.snd :=\n⟨λ Z h k eq,\nbegin\n apply t.hom_ext,\n apply pullback_cone.equalizer_ext,\n rw [← cancel_mono f, assoc, c.condition, reassoc_of eq, assoc, c.condition],\n assumption\nend⟩\n\ndef cone_is_pullback {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) [has_limit (cospan f g)] :\n is_limit (pullback_cone.mk _ _ pullback.condition : pullback_cone f g) :=\nis_limit.mk' _ $ λ s,\n⟨ pullback.lift _ _ s.condition,\n pullback.lift_fst _ _ _,\n pullback.lift_snd _ _ _,\n λ m m₁ m₂, pullback.hom_ext (by simpa using m₁) (by simpa using m₂) ⟩\n\ndef is_limit_as_pullback_cone_mk (s : pullback_cone f g) (t : is_limit (pullback_cone.mk s.fst s.snd s.condition)) :\n is_limit s :=\n{ lift := λ c, t.lift c,\n fac' := λ c j,\n begin\n cases j,\n simp [← t.fac c none, ← s.w walking_cospan.hom.inl],\n cases j,\n exact t.fac c walking_cospan.left,\n exact t.fac c walking_cospan.right,\n end,\n uniq' := λ c m w,\n begin\n apply t.uniq,\n intro j,\n rw ← w,\n cases j,\n simp [← t.fac c none, ← s.w walking_cospan.hom.inl],\n cases j; refl,\n end }\n\ndef has_pullback_top_of_pb [has_limit (cospan f g)] :\n has_pullback_top (pullback.snd : pullback f g ⟶ Y) g f :=\n{ top := pullback.fst,\n comm := pullback.condition,\n is_pb := cone_is_pullback f g }\n\ndef left_pb_to_both_pb {U V W X Y Z : C}\n (f : U ⟶ V) (g : V ⟶ W) (h : U ⟶ X) (k : V ⟶ Y) (l : W ⟶ Z) (m : X ⟶ Y) (n : Y ⟶ Z)\n (left_comm : f ≫ k = h ≫ m)\n (right_comm : g ≫ l = k ≫ n)\n (left_pb : is_limit (pullback_cone.mk f h left_comm))\n (right_pb : is_limit (pullback_cone.mk g k right_comm)) :\nis_limit (pullback_cone.mk (f ≫ g) h (begin rw [assoc, right_comm, reassoc_of left_comm]end)) :=\nis_limit.mk' _ $\nbegin\n intro s,\n let t : s.X ⟶ V := right_pb.lift (pullback_cone.mk s.fst (s.snd ≫ m) (by rw [assoc, s.condition])),\n have l_comm : t ≫ k = s.snd ≫ m := right_pb.fac _ walking_cospan.right,\n let u : s.X ⟶ U := left_pb.lift (pullback_cone.mk _ _ l_comm),\n have uf : u ≫ f = t := left_pb.fac _ walking_cospan.left,\n have tg : t ≫ g = s.fst := right_pb.fac _ walking_cospan.left,\n refine ⟨u, _, left_pb.fac _ walking_cospan.right, _⟩,\n { rw [← tg, ← uf, assoc u f g], refl },\n { intros m' m₁ m₂,\n apply left_pb.hom_ext,\n apply (pullback_cone.mk f h left_comm).equalizer_ext,\n { apply right_pb.hom_ext,\n apply (pullback_cone.mk g k right_comm).equalizer_ext,\n { erw [uf, assoc, tg], exact m₁ },\n { erw [uf, assoc, left_comm, reassoc_of m₂, l_comm] } },\n { erw [left_pb.fac _ walking_cospan.right], exact m₂ } }\nend\n\ndef both_pb_to_left_pb {U V W X Y Z : C}\n (f : U ⟶ V) (g : V ⟶ W) (h : U ⟶ X) (k : V ⟶ Y) (l : W ⟶ Z) (m : X ⟶ Y) (n : Y ⟶ Z)\n (left_comm : f ≫ k = h ≫ m)\n (right_comm : g ≫ l = k ≫ n)\n (right_pb : is_limit (pullback_cone.mk g k right_comm))\n (entire_pb : is_limit (pullback_cone.mk (f ≫ g) h (begin rw [assoc, right_comm, reassoc_of left_comm] end))) :\nis_limit (pullback_cone.mk f h left_comm) :=\nis_limit.mk' _ $\nbegin\n intro s,\n let u : s.X ⟶ U := entire_pb.lift (pullback_cone.mk (s.fst ≫ g) s.snd (by rw [assoc, right_comm, s.condition_assoc])),\n have uf : u ≫ f = s.fst,\n { apply right_pb.hom_ext,\n apply (pullback_cone.mk g k right_comm).equalizer_ext,\n { rw [assoc], exact entire_pb.fac _ walking_cospan.left },\n { erw [assoc, left_comm, ← assoc, entire_pb.fac _ walking_cospan.right, s.condition], refl } },\n refine ⟨u, uf, entire_pb.fac _ walking_cospan.right, _⟩,\n { intros m' m₁ m₂,\n apply entire_pb.hom_ext,\n apply (pullback_cone.mk (f ≫ g) h _).equalizer_ext,\n { erw [reassoc_of uf, reassoc_of m₁] },\n { rwa entire_pb.fac _ walking_cospan.right } }\nend\n\ndef left_hpb_right_pb_to_both_hpb {U V W X Y Z : C}\n (g : V ⟶ W) (h : U ⟶ X) (k : V ⟶ Y) (l : W ⟶ Z) (m : X ⟶ Y) (n : Y ⟶ Z)\n (left : has_pullback_top h m k)\n (right_comm : g ≫ l = k ≫ n)\n (right_pb : is_limit (pullback_cone.mk g k right_comm)) :\n has_pullback_top h (m ≫ n) l :=\n{ top := left.top ≫ g,\n comm := by rw [assoc, right_comm, reassoc_of left.comm],\n is_pb := left_pb_to_both_pb left.top g h k l m n left.comm right_comm left.is_pb right_pb }\n\ndef right_both_hpb_to_left_hpb {U V W X Y Z : C}\n {h : U ⟶ X} {k : V ⟶ Y} (l : W ⟶ Z) {m : X ⟶ Y} (n : Y ⟶ Z)\n (both : has_pullback_top h (m ≫ n) l)\n (right : has_pullback_top k n l) :\n has_pullback_top h m k :=\nbegin\n let t : U ⟶ V := right.is_pb.lift (pullback_cone.mk both.top (h ≫ m) (by rw [assoc, both.comm])),\n refine ⟨t, right.is_pb.fac _ walking_cospan.right, _⟩,\n apply both_pb_to_left_pb t right.top h k l m n _ _ right.is_pb,\n convert both.is_pb,\n apply right.is_pb.fac _ walking_cospan.left,\nend\n\ndef left_right_hpb_to_both_hpb {U V W X Y Z : C}\n {h : U ⟶ X} (k : V ⟶ Y) {l : W ⟶ Z} {m : X ⟶ Y} {n : Y ⟶ Z}\n (left : has_pullback_top h m k)\n (right : has_pullback_top k n l) :\n has_pullback_top h (m ≫ n) l :=\n{ top := left.top ≫ right.top,\n comm := by rw [assoc, right.comm, reassoc_of left.comm],\n is_pb := left_pb_to_both_pb left.top right.top h k l m n left.comm right.comm left.is_pb right.is_pb }\n\ndef vpaste {U V W X Y Z : C} (f : U ⟶ V) (g : U ⟶ W) (h : V ⟶ X) (k : W ⟶ X) (l : W ⟶ Y) (m : X ⟶ Z) (n : Y ⟶ Z)\n (up_comm : f ≫ h = g ≫ k) (down_comm : k ≫ m = l ≫ n)\n (down_pb : is_limit (pullback_cone.mk _ _ down_comm))\n (up_pb : is_limit (pullback_cone.mk _ _ up_comm)) :\n is_limit (pullback_cone.mk f (g ≫ l) (by rw [reassoc_of up_comm, down_comm, assoc]) : pullback_cone (h ≫ m) n):=\nis_limit.mk' _ $\nbegin\n intro s,\n let c' : pullback_cone m n := pullback_cone.mk (pullback_cone.fst s ≫ h) (pullback_cone.snd s) (by simp [pullback_cone.condition s]),\n let t : s.X ⟶ W := down_pb.lift c',\n have tl : t ≫ l = pullback_cone.snd s := down_pb.fac c' walking_cospan.right,\n have tk : t ≫ k = pullback_cone.fst s ≫ h := down_pb.fac c' walking_cospan.left,\n let c'' : pullback_cone h k := pullback_cone.mk (pullback_cone.fst s) t (down_pb.fac c' walking_cospan.left).symm,\n let u : s.X ⟶ U := up_pb.lift c'',\n have uf : u ≫ f = pullback_cone.fst s := up_pb.fac c'' walking_cospan.left,\n have ug : u ≫ g = t := up_pb.fac c'' walking_cospan.right,\n refine ⟨u, uf, by erw [reassoc_of ug, tl], _⟩,\n intros m' m₁ m₂,\n apply up_pb.hom_ext,\n apply (pullback_cone.mk f g up_comm).equalizer_ext,\n change m' ≫ f = u ≫ f,\n erw [m₁, uf],\n erw ug,\n apply down_pb.hom_ext,\n apply (pullback_cone.mk _ _ down_comm).equalizer_ext,\n { change (m' ≫ g) ≫ k = t ≫ k,\n slice_lhs 2 3 {rw ← up_comm},\n slice_lhs 1 2 {erw m₁},\n rw tk },\n { change (m' ≫ g) ≫ l = t ≫ l,\n erw [assoc, m₂, tl] }\nend\n\ndef stretch_hpb_down {U V W X Y Z : C} (g : U ⟶ W) (h : V ⟶ X) (k : W ⟶ X) (l : W ⟶ Y) (m : X ⟶ Z) (n : Y ⟶ Z)\n (up : has_pullback_top g k h)\n (down_comm : k ≫ m = l ≫ n)\n (down_pb : is_limit (pullback_cone.mk _ _ down_comm)) :\nhas_pullback_top (g ≫ l) n (h ≫ m) :=\n{ top := up.top,\n comm := by rw [up.comm_assoc, down_comm, assoc],\n is_pb := vpaste up.top g h k l m n up.comm down_comm down_pb up.is_pb }\n\ndef vpaste' {U V W X Y Z : C} (f : U ⟶ V) (g : U ⟶ W) (h : V ⟶ X) (k : W ⟶ X) (l : W ⟶ Y) (m : X ⟶ Z) (n : Y ⟶ Z)\n (up_comm : f ≫ h = g ≫ k) (down_comm : k ≫ m = l ≫ n)\n (down_pb : is_limit (pullback_cone.mk _ _ down_comm))\n (entire_pb : is_limit (pullback_cone.mk f (g ≫ l) (by rw [reassoc_of up_comm, down_comm, assoc]) : pullback_cone (h ≫ m) n)) :\n is_limit (pullback_cone.mk _ _ up_comm) :=\nis_limit.mk' _ $\nbegin\n intro s,\n let c' : pullback_cone (h ≫ m) n := pullback_cone.mk (pullback_cone.fst s) (pullback_cone.snd s ≫ l) (by simp [pullback_cone.condition_assoc s, down_comm]),\n let t : s.X ⟶ U := entire_pb.lift c',\n have t₁ : t ≫ f = pullback_cone.fst s := entire_pb.fac c' walking_cospan.left,\n have t₂ : t ≫ g ≫ l = pullback_cone.snd s ≫ l := entire_pb.fac c' walking_cospan.right,\n have t₃ : t ≫ g = pullback_cone.snd s,\n apply down_pb.hom_ext,\n apply pullback_cone.equalizer_ext (pullback_cone.mk k l down_comm) _ _,\n erw [assoc, ← up_comm, reassoc_of t₁, pullback_cone.condition s], refl,\n rwa [assoc],\n refine ⟨t, t₁, t₃, _⟩,\n intros m' m₁ m₂,\n apply entire_pb.hom_ext,\n apply pullback_cone.equalizer_ext (pullback_cone.mk f (g ≫ l) _) _ _,\n exact m₁.trans t₁.symm,\n refine trans _ t₂.symm,\n erw [reassoc_of m₂]\nend\n\n-- The mono isn't strictly necessary but this version is convenient.\n-- XXX: It's to ensure g is unique - the alternate solution is to take g ≫ l as one of the arguments and calculate g\ndef cut_hpb_up {U V W X Y Z : C} (g : U ⟶ W) (h : V ⟶ X) (k : W ⟶ X) (l : W ⟶ Y) (m : X ⟶ Z) (n : Y ⟶ Z) [mono m]\n (all : has_pullback_top (g ≫ l) n (h ≫ m))\n (down_comm : k ≫ m = l ≫ n)\n (down_pb : is_limit (pullback_cone.mk _ _ down_comm)) :\nhas_pullback_top g k h :=\n{ top := all.top,\n comm := by rw [← cancel_mono m, assoc, all.comm, assoc, ← down_comm, assoc],\n is_pb := vpaste' _ _ _ _ _ _ _ _ _ down_pb all.is_pb }\n\ndef cut_hpb_up' {U V W X Y Z : C} (g : U ⟶ W) (h : V ⟶ X) (k : W ⟶ X) (l : W ⟶ Y) (m : X ⟶ Z) (n : Y ⟶ Z)\n (all : has_pullback_top (g ≫ l) n (h ≫ m))\n (up_comm : all.top ≫ h = g ≫ k)\n (down_comm : k ≫ m = l ≫ n)\n (down_pb : is_limit (pullback_cone.mk _ _ down_comm)) :\nhas_pullback_top g k h :=\n{ top := all.top,\n comm := up_comm,\n is_pb := vpaste' _ _ _ _ _ _ _ _ _ down_pb all.is_pb }\n\n-- Show\n-- D × A ⟶ B × A\n-- | |\n-- v v\n-- D ⟶ B\n-- is a pullback (needed in over/exponentiable_in_slice)\ndef pullback_prod (xy : X ⟶ Y) (Z : C) [has_binary_products.{v} C] :\n is_limit (pullback_cone.mk limits.prod.fst (limits.prod.map xy (𝟙 Z)) (limits.prod.map_fst _ _).symm) :=\nis_limit.mk' _ $\nbegin\n intro s,\n refine ⟨prod.lift (pullback_cone.fst s) (pullback_cone.snd s ≫ limits.prod.snd), limit.lift_π _ _, _, _⟩,\n { change limits.prod.lift (pullback_cone.fst s) (pullback_cone.snd s ≫ limits.prod.snd) ≫\n limits.prod.map xy (𝟙 Z) = pullback_cone.snd s,\n apply prod.hom_ext,\n rw [assoc, limits.prod.map_fst, prod.lift_fst_assoc, pullback_cone.condition s],\n rw [assoc, limits.prod.map_snd, prod.lift_snd_assoc, comp_id] },\n { intros m m₁ m₂,\n apply prod.hom_ext,\n simpa using m₁,\n erw [prod.lift_snd, ← m₂, assoc, limits.prod.map_snd, comp_id] },\nend\n\ndef pullback_prod' (xy : X ⟶ Y) (Z : C) [has_binary_products.{v} C] :\n is_limit (pullback_cone.mk limits.prod.snd (limits.prod.map (𝟙 Z) xy) (limits.prod.map_snd _ _).symm) :=\nis_limit.mk' _ $\nbegin\n intro s,\n refine ⟨prod.lift (pullback_cone.snd s ≫ limits.prod.fst) (pullback_cone.fst s), limit.lift_π _ _, _, _⟩,\n { apply prod.hom_ext,\n erw [assoc, limits.prod.map_fst, prod.lift_fst_assoc, comp_id],\n slice_lhs 2 3 {erw limits.prod.map_snd},\n rw [prod.lift_snd_assoc, pullback_cone.condition s] },\n { intros m m₁ m₂,\n apply prod.hom_ext,\n erw [prod.lift_fst, ← m₂, assoc, limits.prod.map_fst, comp_id],\n simpa using m₁ }\nend\n\ndef pullback_flip {W X Y Z : C} {f : W ⟶ X} {g : W ⟶ Y} {h : X ⟶ Z} {k : Y ⟶ Z} {comm : f ≫ h = g ≫ k} (t : is_limit (pullback_cone.mk _ _ comm.symm)) :\n is_limit (pullback_cone.mk _ _ comm) :=\nis_limit.mk' _ $ λ s,\nbegin\n refine ⟨(pullback_cone.is_limit.lift' t _ _ s.condition.symm).1,\n (pullback_cone.is_limit.lift' t _ _ _).2.2,\n (pullback_cone.is_limit.lift' t _ _ _).2.1, λ m m₁ m₂, t.hom_ext _⟩,\n apply (pullback_cone.mk g f _).equalizer_ext,\n { rw (pullback_cone.is_limit.lift' t _ _ _).2.1,\n exact m₂ },\n { rw (pullback_cone.is_limit.lift' t _ _ _).2.2,\n exact m₁ },\nend\n\ndef pullback_square_iso {W X Y Z : C} (f : W ⟶ X) (g : W ⟶ Y) (h : X ⟶ Z) (k : Y ⟶ Z) [mono h] [is_iso g] (comm : f ≫ h = g ≫ k) :\n is_limit (pullback_cone.mk _ _ comm) :=\nis_limit.mk''' _ (by dsimp [pullback_cone.mk]; apply_instance) $\n λ s, ⟨s.snd ≫ inv g, by erw [assoc, is_iso.inv_hom_id g, comp_id] ⟩\n\ndef left_iso_has_pullback_top {W X Y Z : C} (f : W ⟶ X) (g : W ⟶ Y) (h : X ⟶ Z) (k : Y ⟶ Z) [mono h] [is_iso g] (comm : f ≫ h = g ≫ k) :\n has_pullback_top g k h :=\n{ top := f,\n comm := comm,\n is_pb := pullback_square_iso f g h k comm }\n\ndef pullback_square_iso' {W X Y Z : C} (f : W ⟶ X) (g : W ⟶ Y) (h : X ⟶ Z) (k : Y ⟶ Z) [is_iso f] [mono k] (comm : f ≫ h = g ≫ k) :\n is_limit (pullback_cone.mk _ _ comm) :=\nis_limit.mk' _ $\nbegin\n intro s,\n refine ⟨pullback_cone.fst s ≫ inv f, _, _, _⟩,\n erw [assoc, is_iso.inv_hom_id, comp_id],\n erw [← cancel_mono k, assoc, ← comm, assoc, is_iso.inv_hom_id_assoc, pullback_cone.condition s],\n intros m m₁ m₂,\n erw [(as_iso f).eq_comp_inv, m₁]\nend\n\ndef top_iso_has_pullback_top {W X Y Z : C} (f : W ⟶ X) (g : W ⟶ Y) (h : X ⟶ Z) (k : Y ⟶ Z) [is_iso f] [mono k] (comm : f ≫ h = g ≫ k) :\n has_pullback_top g k h :=\n{ top := f,\n comm := comm,\n is_pb := pullback_square_iso' f g h k comm }\n\nlemma mono_of_pullback (X Y : C) (f : X ⟶ Y)\n (hl : is_limit (pullback_cone.mk (𝟙 X) (𝟙 X) (by simp) : pullback_cone f f)) : mono f :=\nbegin\n split, intros,\n set new_cone : pullback_cone f f := pullback_cone.mk g h w,\n exact (hl.fac new_cone walking_cospan.left).symm.trans (hl.fac new_cone walking_cospan.right),\nend\n\ndef pullback_of_mono {X Y : C} (f : X ⟶ Y) [hf : mono f] :\n is_limit (pullback_cone.mk (𝟙 X) (𝟙 X) rfl : pullback_cone f f) :=\npullback_square_iso' _ _ _ _ _\n\ndef mono_self_has_pullback_top {X Y : C} (f : X ⟶ Y) [hf : mono f] :\n has_pullback_top (𝟙 _) f f :=\n{ top := 𝟙 _,\n comm := by simp,\n is_pb := pullback_of_mono f }\n\nuniverse u₂\nvariables {D : Type u₂} [category.{v} D] (F : C ⥤ D)\n\n\ndef cone_cospan_equiv :\n cone (cospan (F.map f) (F.map g)) ≌ cone (cospan f g ⋙ F) :=\ncones.postcompose_equivalence (iso.symm (diagram_iso_cospan _))\n\nlocal attribute [tidy] tactic.case_bash\n\ndef convert_pb\n {W X Y Z : C}\n {f : W ⟶ X} {g : X ⟶ Z} {h : W ⟶ Y} {k : Y ⟶ Z} (comm : f ≫ g = h ≫ k) :\n(cones.postcompose (diagram_iso_cospan _).hom).obj (F.map_cone (pullback_cone.mk _ _ comm)) ≅\n (pullback_cone.mk (F.map f) (F.map h) (by rw [← F.map_comp, comm, F.map_comp]) : pullback_cone (F.map g) (F.map k)) :=\ncones.ext (iso.refl _) (by { dsimp [diagram_iso_cospan], tidy })\n\ndef thing2\n {W X Y Z : C}\n {f : W ⟶ X} {g : X ⟶ Z} {h : W ⟶ Y} {k : Y ⟶ Z} (comm : f ≫ g = h ≫ k) :\nis_limit (F.map_cone (pullback_cone.mk _ _ comm)) ≅ is_limit (pullback_cone.mk (F.map f) (F.map h) (by rw [← F.map_comp, comm, F.map_comp]) : pullback_cone (F.map g) (F.map k)) :=\n{ hom := λ p,\n begin\n apply is_limit.of_iso_limit _ (convert_pb F comm),\n apply is_limit.of_right_adjoint (cones.postcompose_equivalence ((diagram_iso_cospan _).symm)).inverse p,\n end,\n inv := λ p,\n begin\n have := is_limit.of_right_adjoint (cones.postcompose_equivalence (diagram_iso_cospan (cospan g k ⋙ F))).inverse p,\n apply is_limit.of_iso_limit this _,\n refine cones.ext (iso.refl _) _,\n dsimp [diagram_iso_cospan],\n simp_rw [id_comp],\n rintro (_ | _ | _),\n { dsimp, rw [comp_id, F.map_comp] },\n { dsimp, rw [comp_id] },\n { dsimp, rw [comp_id] },\n end,\n hom_inv_id' := subsingleton.elim _ _,\n inv_hom_id' := subsingleton.elim _ _ }\n\ndef preserves_pullback_cone\n [preserves_limits_of_shape walking_cospan F] {W X Y Z : C}\n (f : W ⟶ X) (g : X ⟶ Z) (h : W ⟶ Y) (k : Y ⟶ Z) (comm : f ≫ g = h ≫ k)\n (t : is_limit (pullback_cone.mk _ _ comm)) :\nis_limit (pullback_cone.mk (F.map f) (F.map h) (by rw [← F.map_comp, comm, F.map_comp]) : pullback_cone (F.map g) (F.map k)) :=\n(thing2 F comm).hom (preserves_limit.preserves t)\n\ndef reflects_pullback_cone\n [reflects_limits_of_shape walking_cospan F] {W X Y Z : C}\n {f : W ⟶ X} {g : X ⟶ Z} {h : W ⟶ Y} {k : Y ⟶ Z} (comm : f ≫ g = h ≫ k)\n (t : is_limit (pullback_cone.mk (F.map f) (F.map h) (by rw [← F.map_comp, comm, F.map_comp]) : pullback_cone (F.map g) (F.map k))) :\nis_limit (pullback_cone.mk _ _ comm) :=\nreflects_limit.reflects ((thing2 F comm).inv t)\n\nlemma preserves_mono_of_preserves_pullback\n [preserves_limits_of_shape walking_cospan F] (X Y : C) (f : X ⟶ Y) [mono f] :\n mono (F.map f) :=\nbegin\n apply mono_of_pullback,\n have : 𝟙 (F.obj X) = F.map (𝟙 X),\n rw F.map_id,\n convert preserves_pullback_cone F (𝟙 _) f (𝟙 _) f rfl (pullback_of_mono f),\nend\n\ndef preserves_walking_cospan_of_preserves_pb_cone {h : W ⟶ _} {k} (comm : h ≫ f = k ≫ g) (is_lim : is_limit (pullback_cone.mk _ _ comm))\n (t : is_limit (pullback_cone.mk (F.map h) (F.map k) (by rw [← F.map_comp, comm, F.map_comp]) : pullback_cone (F.map f) (F.map g))) :\n preserves_limit (cospan f g) F :=\nbegin\n apply preserves_limit_of_preserves_limit_cone is_lim,\n apply ((thing2 _ _).inv t),\nend\n\ndef preserves_hpb [preserves_limits_of_shape walking_cospan F] {g : X ⟶ Z} {h : W ⟶ Y} {k : Y ⟶ Z} (t : has_pullback_top h k g) :\nhas_pullback_top (F.map h) (F.map k) (F.map g) :=\n{ top := F.map t.top,\n comm := by rw [← F.map_comp, t.comm, F.map_comp],\n is_pb := preserves_pullback_cone F _ _ _ _ t.comm t.is_pb }\n\ndef fully_faithful_reflects_hpb [reflects_limits_of_shape walking_cospan F] [full F] [faithful F] {g : X ⟶ Z} {h : W ⟶ Y} {k : Y ⟶ Z}\n (t : has_pullback_top (F.map h) (F.map k) (F.map g)) :\nhas_pullback_top h k g :=\n{ top := F.preimage t.top,\n comm := by { apply F.map_injective, simp [t.comm] },\n is_pb :=\n begin\n refine reflects_pullback_cone F _ _,\n convert t.is_pb,\n simp,\n end }\n\n-- Strictly we don't need the assumption that C has pullbacks but oh well\ndef over_forget_preserves_hpb [has_pullbacks.{v} C] {B : C} {X Y Z W : over B} (g : X ⟶ Z) (h : Z ⟶ W) (k : Y ⟶ W) (t : has_pullback_top g h k) :\n has_pullback_top g.left h.left k.left :=\npreserves_hpb (over.forget _) t\n\ndef over_forget_reflects_hpb {B : C} {X Y Z W : over B} {g : X ⟶ Z} {h : Z ⟶ W} {k : Y ⟶ W}\n (t : has_pullback_top g.left h.left k.left ) :\n has_pullback_top g h k :=\n{ top :=\n begin\n apply over.hom_mk t.top _,\n simp only [auto_param_eq, ← over.w k, t.comm_assoc, over.w h, over.w g],\n end,\n comm := by { ext1, exact t.comm },\n is_pb :=\n begin\n apply reflects_pullback_cone (over.forget _),\n apply t.is_pb,\n refine ⟨λ K, by apply_instance⟩,\n end }", "meta": {"author": "b-mehta", "repo": "topos", "sha": "c9032b11789e36038bc841a1e2b486972421b983", "save_path": "github-repos/lean/b-mehta-topos", "path": "github-repos/lean/b-mehta-topos/topos-c9032b11789e36038bc841a1e2b486972421b983/src/category/pullbacks.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4843800842769843, "lm_q2_score": 0.06371499869663867, "lm_q1q2_score": 0.030862276438385787}} {"text": "import Std\n\ndef Nat.digitCharInv! : Char → Nat\n| '0' => 0\n| '1' => 1\n| '2' => 2\n| '3' => 3\n| '4' => 4\n| '5' => 5\n| '6' => 6\n| '7' => 7\n| '8' => 8\n| '9' => 9\n| 'a' | 'A' => 0xa\n| 'b' | 'B' => 0xb\n| 'c' | 'C' => 0xc\n| 'd' | 'D' => 0xd\n| 'e' | 'E' => 0xe\n| 'f' | 'F' => 0xf\n| _ => panic! \"nan\"\n\ndef Char.isHexDigit : Char → Bool\n| '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'\n| 'a' | 'b' | 'c' | 'd' | 'e' | 'f'\n| 'A' | 'B' | 'C' | 'D' | 'E' | 'F' => true\n| _ => false\n\ndef Nat.ofDigits? (base : Nat) (s : String) : Option Nat :=\n s.foldl (fun acc c =>\n acc.bind fun acc =>\n if c.isHexDigit then\n let d := Nat.digitCharInv! c\n if d < base then\n some <| acc * base + d\n else\n none\n else\n none)\n (some 0)\n\n@[simp] theorem UInt32.toNat_ofUInt8 : UInt32.toNat (UInt8.toUInt32 x) = x.val := by\n cases x; case mk val =>\n cases val; case mk val isLt =>\n have : val < 4294967295 + 1 := Nat.le_trans isLt (by decide)\n simp [UInt8.size] at isLt\n simp only [toNat]\n apply Nat.mod_eq_of_lt this\n\ninstance : Coe UInt8 Char where\n coe b := ⟨UInt8.toUInt32 b, by\n rcases b with ⟨⟨x,h⟩⟩\n apply Or.inl\n simp\n apply Nat.lt_trans h (by decide)\n ⟩\n\ndef Char.toUInt8 (c : Char) (h : c.val.val < UInt8.size := by decide) : UInt8 :=\n ⟨c.val.val, h⟩\n\ninstance (h : c.val.val < UInt8.size := by decide) : CoeDep Char c UInt8 := ⟨c.toUInt8 h⟩\n\nstructure ThunkCache (a : Unit → α) where\n val : Thunk α\n h_val : val.get = a ()\n\ndef ThunkCache.new : ThunkCache a := ⟨Thunk.mk a, by simp [Thunk.get]⟩\ninstance : Inhabited (ThunkCache a) := ⟨.new⟩\n\ndef List.pmap (L : List α) (f : (a : α) → a ∈ L → β) : List β :=\n match L with\n | [] => []\n | x::xs => (f x (List.Mem.head _)) :: xs.pmap (fun a h => f a (List.Mem.tail _ h))\n\n@[simp] theorem String.length_pushn (s : String) (c n)\n : (s.pushn c n).length = s.length + n := by\n induction n\n . simp [pushn, Nat.repeat]\n . simp [pushn, Nat.repeat, push, length]\n rw [Nat.add_succ, Nat.add_succ]\n congr\n\n@[simp] theorem String.length_append (s1 s2 : String)\n : (s1 ++ s2).length = s1.length + s2.length := by\n simp [HAppend.hAppend, Append.append, append, length]\n\n@[simp] theorem String.take_mk (L : List Char) (n)\n : (String.mk L).take n = String.mk (L.take n)\n := sorry\n\n@[simp] theorem String.drop_mk (L : List Char) (n)\n : (String.mk L).drop n = String.mk (L.drop n)\n := sorry\n\n@[simp] theorem String.length_take (s : String) (n)\n : (s.take n).length = min s.length n\n := by cases s; simp [length, Nat.min_comm]\n\n@[simp] theorem String.length_drop (s : String) (n)\n : (s.drop n).length = s.length - n\n := by cases s; simp [length, Nat.min_comm]\n\ntheorem List.mem_zipWith (h : x ∈ List.zipWith f L1 L2)\n : ∃ y z, x = f y z ∧ y ∈ L1 ∧ z ∈ L2\n := by induction L1 generalizing x L2\n . simp at h\n . next ih =>\n cases L2 <;> simp at *\n cases h\n . subst_vars\n exact ⟨_, _, rfl, .inl rfl, .inl rfl⟩\n . have := ih (by assumption)\n rcases this with ⟨y,z,rfl,hy,hz⟩\n refine ⟨y,z, rfl, .inr hy, .inr hz⟩\n\ntheorem List.mem_take (h : x ∈ List.take n L)\n : x ∈ L\n := by induction n generalizing L <;> cases L <;> simp at *\n next ih _ _ =>\n cases h\n . apply Or.inl; assumption\n . apply Or.inr; apply ih; assumption\n\n@[simp]\ntheorem List.length_join_replicate : (replicate n L).join.length = n * L.length := by\n induction n\n . simp\n . simp [Nat.succ_mul, Nat.add_comm]\n congr\n\ndef Function.update (f : α → β) [DecidableEq α] (x v) :=\n fun i => if i = x then v else f i\n", "meta": {"author": "JamesGallicchio", "repo": "c0deine", "sha": "afe36eb72c126bf0cf6682aac2048341a38e6b0d", "save_path": "github-repos/lean/JamesGallicchio-c0deine", "path": "github-repos/lean/JamesGallicchio-c0deine/c0deine-afe36eb72c126bf0cf6682aac2048341a38e6b0d/C0deine/AuxDefs.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.0637149933630307, "lm_q1q2_score": 0.03086227385489231}} {"text": "/-\nCopyright (c) 2021 Andrew Yang. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Andrew Yang\n-/\nimport algebraic_geometry.AffineScheme\nimport ring_theory.nilpotent\nimport topology.sheaves.sheaf_condition.sites\nimport category_theory.limits.constructions.binary_products\nimport algebra.category.Ring.constructions\nimport ring_theory.integral_domain\nimport ring_theory.local_properties\n\n/-!\n# Basic properties of schemes\n\nWe provide some basic properties of schemes\n\n## Main definition\n* `algebraic_geometry.is_integral`: A scheme is integral if it is nontrivial and all nontrivial\n components of the structure sheaf are integral domains.\n* `algebraic_geometry.is_reduced`: A scheme is reduced if all the components of the structure sheaf\n is reduced.\n-/\n\nopen topological_space opposite category_theory category_theory.limits Top\n\nnamespace algebraic_geometry\n\nvariable (X : Scheme)\n\ninstance : t0_space X.carrier :=\nbegin\n rw t0_space_iff_not_inseparable,\n intros x y h h',\n obtain ⟨U, R, ⟨e⟩⟩ := X.local_affine x,\n have hy := (h' _ U.1.2).mp U.2,\n erw ← subtype_inseparable_iff (⟨x, U.2⟩ : U.1.1) (⟨y, hy⟩ : U.1.1) at h',\n let e' : U.1 ≃ₜ prime_spectrum R :=\n homeo_of_iso ((LocallyRingedSpace.forget_to_SheafedSpace ⋙ SheafedSpace.forget _).map_iso e),\n have := t0_space_of_injective_of_continuous e'.injective e'.continuous,\n rw t0_space_iff_not_inseparable at this,\n exact this ⟨x, U.2⟩ ⟨y, hy⟩ (by simpa using h) h'\nend\n\ninstance : quasi_sober X.carrier :=\nbegin\n apply_with (quasi_sober_of_open_cover\n (set.range (λ x, set.range $ (X.affine_cover.map x).1.base)))\n { instances := ff },\n { rintro ⟨_,i,rfl⟩, exact (X.affine_cover.is_open i).base_open.open_range },\n { rintro ⟨_,i,rfl⟩,\n exact @@open_embedding.quasi_sober _ _ _\n (homeomorph.of_embedding _ (X.affine_cover.is_open i).base_open.to_embedding)\n .symm.open_embedding prime_spectrum.quasi_sober },\n { rw [set.top_eq_univ, set.sUnion_range, set.eq_univ_iff_forall],\n intro x, exact ⟨_, ⟨_, rfl⟩, X.affine_cover.covers x⟩ }\nend\n\n/-- A scheme `X` is reduced if all `𝒪ₓ(U)` are reduced. -/\nclass is_reduced : Prop :=\n(component_reduced : ∀ U, _root_.is_reduced (X.presheaf.obj (op U)) . tactic.apply_instance)\n\nattribute [instance] is_reduced.component_reduced\n\nlemma is_reduced_of_stalk_is_reduced [∀ x : X.carrier, _root_.is_reduced (X.presheaf.stalk x)] :\n is_reduced X :=\nbegin\n refine ⟨λ U, ⟨λ s hs, _⟩⟩,\n apply presheaf.section_ext X.sheaf U s 0,\n intro x,\n rw ring_hom.map_zero,\n change X.presheaf.germ x s = 0,\n exact (hs.map _).eq_zero\nend\n\ninstance stalk_is_reduced_of_reduced [is_reduced X] (x : X.carrier) :\n _root_.is_reduced (X.presheaf.stalk x) :=\nbegin\n constructor,\n rintros g ⟨n, e⟩,\n obtain ⟨U, hxU, s, rfl⟩ := X.presheaf.germ_exist x g,\n rw [← map_pow, ← map_zero (X.presheaf.germ ⟨x, hxU⟩)] at e,\n obtain ⟨V, hxV, iU, iV, e'⟩ := X.presheaf.germ_eq x hxU hxU _ 0 e,\n rw [map_pow, map_zero] at e',\n replace e' := (is_nilpotent.mk _ _ e').eq_zero,\n erw ← concrete_category.congr_hom (X.presheaf.germ_res iU ⟨x, hxV⟩) s,\n rw [comp_apply, e', map_zero]\nend\n\nlemma is_reduced_of_open_immersion {X Y : Scheme} (f : X ⟶ Y) [H : is_open_immersion f]\n [is_reduced Y] : is_reduced X :=\nbegin\n constructor,\n intro U,\n have : U = (opens.map f.1.base).obj (H.base_open.is_open_map.functor.obj U),\n { ext1, exact (set.preimage_image_eq _ H.base_open.inj).symm },\n rw this,\n exact is_reduced_of_injective (inv $ f.1.c.app (op $ H.base_open.is_open_map.functor.obj U))\n (as_iso $ f.1.c.app (op $ H.base_open.is_open_map.functor.obj U) : Y.presheaf.obj _ ≅ _).symm\n .CommRing_iso_to_ring_equiv.injective\nend\n\ninstance {R : CommRing} [H : _root_.is_reduced R] : is_reduced (Scheme.Spec.obj $ op R) :=\nbegin\n apply_with is_reduced_of_stalk_is_reduced { instances := ff },\n intro x, dsimp,\n haveI : _root_.is_reduced (CommRing.of $ localization.at_prime (prime_spectrum.as_ideal x)),\n { dsimp, apply_instance },\n exact is_reduced_of_injective (structure_sheaf.stalk_iso R x).hom\n (structure_sheaf.stalk_iso R x).CommRing_iso_to_ring_equiv.injective,\nend\n\nlemma affine_is_reduced_iff (R : CommRing) :\n is_reduced (Scheme.Spec.obj $ op R) ↔ _root_.is_reduced R :=\nbegin\n refine ⟨_, λ h, by exactI infer_instance⟩,\n intro h,\n resetI,\n haveI : _root_.is_reduced (LocallyRingedSpace.Γ.obj (op $ Spec.to_LocallyRingedSpace.obj $ op R)),\n { change _root_.is_reduced ((Scheme.Spec.obj $ op R).presheaf.obj $ op ⊤), apply_instance },\n exact is_reduced_of_injective (to_Spec_Γ R)\n ((as_iso $ to_Spec_Γ R).CommRing_iso_to_ring_equiv.injective)\nend\n\nlemma is_reduced_of_is_affine_is_reduced [is_affine X]\n [h : _root_.is_reduced (X.presheaf.obj (op ⊤))] : is_reduced X :=\nbegin\n haveI : is_reduced (Scheme.Spec.obj (op (Scheme.Γ.obj (op X)))),\n { rw affine_is_reduced_iff, exact h },\n exact is_reduced_of_open_immersion X.iso_Spec.hom,\nend\n\n/-- To show that a statement `P` holds for all open subsets of all schemes, it suffices to show that\n1. In any scheme `X`, if `P` holds for an open cover of `U`, then `P` holds for `U`.\n2. For an open immerison `f : X ⟶ Y`, if `P` holds for the entire space of `X`, then `P` holds for\n the image of `f`.\n3. `P` holds for the entire space of an affine scheme.\n-/\nlemma reduce_to_affine_global (P : ∀ (X : Scheme) (U : opens X.carrier), Prop)\n (h₁ : ∀ (X : Scheme) (U : opens X.carrier),\n (∀ (x : U), ∃ {V} (h : x.1 ∈ V) (i : V ⟶ U), P X V) → P X U)\n (h₂ : ∀ {X Y} (f : X ⟶ Y) [hf : is_open_immersion f], ∃ {U : set X.carrier} {V : set Y.carrier}\n (hU : U = ⊤) (hV : V = set.range f.1.base), P X ⟨U, hU.symm ▸ is_open_univ⟩ →\n P Y ⟨V, hV.symm ▸ hf.base_open.open_range⟩)\n (h₃ : ∀ (R : CommRing), P (Scheme.Spec.obj $ op R) ⊤) :\n ∀ (X : Scheme) (U : opens X.carrier), P X U :=\nbegin\n intros X U,\n apply h₁,\n intro x,\n obtain ⟨_,⟨j,rfl⟩,hx,i⟩ := X.affine_basis_cover_is_basis.exists_subset_of_mem_open x.prop U.2,\n let U' : opens _ := ⟨_, (X.affine_basis_cover.is_open j).base_open.open_range⟩,\n let i' : U' ⟶ U :=\n hom_of_le i,\n refine ⟨U', hx, i', _⟩,\n obtain ⟨_,_,rfl,rfl,h₂'⟩ := h₂ (X.affine_basis_cover.map j),\n apply h₂',\n apply h₃\nend\n.\n\n\nlemma eq_zero_of_basic_open_empty {X : Scheme} [hX : is_reduced X] {U : opens X.carrier}\n (s : X.presheaf.obj (op U)) (hs : X.basic_open s = ∅) :\n s = 0 :=\nbegin\n apply Top.presheaf.section_ext X.sheaf U,\n simp_rw ring_hom.map_zero,\n unfreezingI { revert X U hX s },\n refine reduce_to_affine_global _ _ _ _,\n { intros X U hx hX s hs x,\n obtain ⟨V, hx, i, H⟩ := hx x,\n unfreezingI { specialize H (X.presheaf.map i.op s) },\n erw Scheme.basic_open_res at H,\n rw [hs, ← subtype.coe_injective.eq_iff, opens.empty_eq, opens.inter_eq, inf_bot_eq] at H,\n specialize H rfl ⟨x, hx⟩,\n erw Top.presheaf.germ_res_apply at H,\n exact H },\n { rintros X Y f hf,\n have e : (f.val.base) ⁻¹' set.range ⇑(f.val.base) = ⊤,\n { rw [← set.image_univ, set.preimage_image_eq _ hf.base_open.inj, set.top_eq_univ] },\n refine ⟨_, _, e, rfl, _⟩,\n rintros H hX s hs ⟨_, x, rfl⟩,\n unfreezingI { haveI := is_reduced_of_open_immersion f },\n specialize H (f.1.c.app _ s) _ ⟨x, by { change x ∈ (f.val.base) ⁻¹' _, rw e, trivial }⟩,\n { rw [← Scheme.preimage_basic_open, hs], ext1, simp [opens.map] },\n { erw ← PresheafedSpace.stalk_map_germ_apply f.1 ⟨_,_⟩ ⟨x,_⟩ at H,\n apply_fun (inv $ PresheafedSpace.stalk_map f.val x) at H,\n erw [category_theory.is_iso.hom_inv_id_apply, map_zero] at H,\n exact H } },\n { intros R hX s hs x,\n erw [basic_open_eq_of_affine', prime_spectrum.basic_open_eq_bot_iff] at hs,\n replace hs := (hs.map (Spec_Γ_identity.app R).inv),\n -- what the hell?!\n replace hs := @is_nilpotent.eq_zero _ _ _ _ (show _, from _) hs,\n rw iso.hom_inv_id_apply at hs,\n rw [hs, map_zero],\n exact @@is_reduced.component_reduced hX ⊤ }\nend\n\n@[simp]\nlemma basic_open_eq_bot_iff {X : Scheme} [is_reduced X] {U : opens X.carrier}\n (s : X.presheaf.obj $ op U) :\n X.basic_open s = ⊥ ↔ s = 0 :=\nbegin\n refine ⟨eq_zero_of_basic_open_empty s, _⟩,\n rintro rfl,\n simp,\nend\n\n/-- A scheme `X` is integral if its carrier is nonempty,\nand `𝒪ₓ(U)` is an integral domain for each `U ≠ ∅`. -/\nclass is_integral : Prop :=\n(nonempty : nonempty X.carrier . tactic.apply_instance)\n(component_integral : ∀ (U : opens X.carrier) [_root_.nonempty U],\n is_domain (X.presheaf.obj (op U)) . tactic.apply_instance)\n\nattribute [instance] is_integral.component_integral is_integral.nonempty\n\ninstance [h : is_integral X] : is_domain (X.presheaf.obj (op ⊤)) :=\n@@is_integral.component_integral _ _ (by simp)\n\n@[priority 900]\ninstance is_reduced_of_is_integral [is_integral X] : is_reduced X :=\nbegin\n constructor,\n intro U,\n cases U.1.eq_empty_or_nonempty,\n { have : U = ∅ := subtype.eq h,\n haveI := CommRing.subsingleton_of_is_terminal (X.sheaf.is_terminal_of_eq_empty this),\n change _root_.is_reduced (X.sheaf.val.obj (op U)),\n apply_instance },\n { haveI : nonempty U := by simpa, apply_instance }\nend\n\ninstance is_irreducible_of_is_integral [is_integral X] : irreducible_space X.carrier :=\nbegin\n by_contradiction H,\n replace H : ¬ is_preirreducible (⊤ : set X.carrier) := λ h,\n H { to_preirreducible_space := ⟨h⟩, to_nonempty := infer_instance },\n simp_rw [is_preirreducible_iff_closed_union_closed, not_forall, not_or_distrib] at H,\n rcases H with ⟨S, T, hS, hT, h₁, h₂, h₃⟩,\n erw not_forall at h₂ h₃,\n simp_rw not_forall at h₂ h₃,\n haveI : nonempty (⟨Sᶜ, hS.1⟩ : opens X.carrier) := ⟨⟨_, h₂.some_spec.some_spec⟩⟩,\n haveI : nonempty (⟨Tᶜ, hT.1⟩ : opens X.carrier) := ⟨⟨_, h₃.some_spec.some_spec⟩⟩,\n haveI : nonempty (⟨Sᶜ, hS.1⟩ ⊔ ⟨Tᶜ, hT.1⟩ : opens X.carrier) :=\n ⟨⟨_, or.inl h₂.some_spec.some_spec⟩⟩,\n let e : X.presheaf.obj _ ≅ CommRing.of _ := (X.sheaf.is_product_of_disjoint ⟨_, hS.1⟩ ⟨_, hT.1⟩ _)\n .cone_point_unique_up_to_iso (CommRing.prod_fan_is_limit _ _),\n apply_with false_of_nontrivial_of_product_domain { instances := ff },\n { exact e.symm.CommRing_iso_to_ring_equiv.is_domain _ },\n { apply X.to_LocallyRingedSpace.component_nontrivial },\n { apply X.to_LocallyRingedSpace.component_nontrivial },\n { ext x,\n split,\n { rintros ⟨hS,hT⟩,\n cases h₁ (show x ∈ ⊤, by trivial),\n exacts [hS h, hT h] },\n { intro x, exact x.rec _ } }\nend\n\nlemma is_integral_of_is_irreducible_is_reduced [is_reduced X] [H : irreducible_space X.carrier] :\n is_integral X :=\nbegin\n split, refine λ U hU, ⟨λ a b e, _,\n (@@LocallyRingedSpace.component_nontrivial X.to_LocallyRingedSpace U hU).1⟩,\n simp_rw [← basic_open_eq_bot_iff, ← opens.not_nonempty_iff_eq_bot],\n by_contra' h,\n obtain ⟨_, ⟨x, hx₁, rfl⟩, ⟨x, hx₂, e'⟩⟩ := @@nonempty_preirreducible_inter _ H.1\n (X.basic_open a).2 (X.basic_open b).2\n h.1 h.2,\n replace e' := subtype.eq e',\n subst e',\n replace e := congr_arg (X.presheaf.germ x) e,\n rw [ring_hom.map_mul, ring_hom.map_zero] at e,\n refine @zero_ne_one (X.presheaf.stalk x.1) _ _ (is_unit_zero_iff.1 _),\n convert hx₁.mul hx₂,\n exact e.symm\nend\n\nlemma is_integral_iff_is_irreducible_and_is_reduced :\n is_integral X ↔ irreducible_space X.carrier ∧ is_reduced X :=\n⟨λ _, by exactI ⟨infer_instance, infer_instance⟩,\n λ ⟨_, _⟩, by exactI is_integral_of_is_irreducible_is_reduced X⟩\n\nlemma is_integral_of_open_immersion {X Y : Scheme} (f : X ⟶ Y) [H : is_open_immersion f]\n [is_integral Y] [nonempty X.carrier] : is_integral X :=\nbegin\n constructor,\n intros U hU,\n have : U = (opens.map f.1.base).obj (H.base_open.is_open_map.functor.obj U),\n { ext1, exact (set.preimage_image_eq _ H.base_open.inj).symm },\n rw this,\n haveI : is_domain (Y.presheaf.obj (op (H.base_open.is_open_map.functor.obj U))),\n { apply_with is_integral.component_integral { instances := ff },\n apply_instance,\n refine ⟨⟨_, _, hU.some.prop, rfl⟩⟩ },\n exact (as_iso $ f.1.c.app (op $ H.base_open.is_open_map.functor.obj U) :\n Y.presheaf.obj _ ≅ _).symm.CommRing_iso_to_ring_equiv.is_domain _\nend\n\ninstance {R : CommRing} [H : is_domain R] : is_integral (Scheme.Spec.obj $ op R) :=\nbegin\n apply_with is_integral_of_is_irreducible_is_reduced { instances := ff },\n { apply_instance },\n { dsimp [Spec.Top_obj],\n apply_instance },\nend\n\nlemma affine_is_integral_iff (R : CommRing) :\n is_integral (Scheme.Spec.obj $ op R) ↔ is_domain R :=\n⟨λ h, by exactI ring_equiv.is_domain ((Scheme.Spec.obj $ op R).presheaf.obj _)\n (as_iso $ to_Spec_Γ R).CommRing_iso_to_ring_equiv, λ h, by exactI infer_instance⟩\n\nlemma is_integral_of_is_affine_is_domain [is_affine X] [nonempty X.carrier]\n [h : is_domain (X.presheaf.obj (op ⊤))] : is_integral X :=\nbegin\n haveI : is_integral (Scheme.Spec.obj (op (Scheme.Γ.obj (op X)))),\n { rw affine_is_integral_iff, exact h },\n exact is_integral_of_open_immersion X.iso_Spec.hom,\nend\n\nlemma map_injective_of_is_integral [is_integral X] {U V : opens X.carrier} (i : U ⟶ V)\n [H : nonempty U] :\n function.injective (X.presheaf.map i.op) :=\nbegin\n rw injective_iff_map_eq_zero,\n intros x hx,\n rw ← basic_open_eq_bot_iff at ⊢ hx,\n rw Scheme.basic_open_res at hx,\n revert hx,\n contrapose!,\n simp_rw [← opens.not_nonempty_iff_eq_bot, not_not],\n apply nonempty_preirreducible_inter U.prop (RingedSpace.basic_open _ _).prop,\n simpa using H\nend\n\nend algebraic_geometry\n", "meta": {"author": "nick-kuhn", "repo": "leantools", "sha": "567a98c031fffe3f270b7b8dea48389bc70d7abb", "save_path": "github-repos/lean/nick-kuhn-leantools", "path": "github-repos/lean/nick-kuhn-leantools/leantools-567a98c031fffe3f270b7b8dea48389bc70d7abb/src/algebraic_geometry/properties.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.0637149898072923, "lm_q1q2_score": 0.030862272132563446}} {"text": "/-\nCopyright (c) 2022 Yaël Dillies. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Yaël Dillies\n-/\nimport category_theory.category.Pointed\n\n/-!\n# The category of bipointed types\n\nThis defines `Bipointed`, the category of bipointed types.\n\n## TODO\n\nMonoidal structure\n-/\n\nopen category_theory\n\nuniverses u\nvariables {α β : Type*}\n\n/-- The category of bipointed types. -/\nstructure Bipointed : Type.{u + 1} :=\n(X : Type.{u})\n(to_prod : X × X)\n\nnamespace Bipointed\n\ninstance : has_coe_to_sort Bipointed Type* := ⟨X⟩\n\nattribute [protected] Bipointed.X\n\n/-- Turns a bipointing into a bipointed type. -/\ndef of {X : Type*} (to_prod : X × X) : Bipointed := ⟨X, to_prod⟩\n\nalias of ← prod.Bipointed\n\ninstance : inhabited Bipointed := ⟨of ((), ())⟩\n\n/-- Morphisms in `Bipointed`. -/\n@[ext] protected structure hom (X Y : Bipointed.{u}) : Type u :=\n(to_fun : X → Y)\n(map_fst : to_fun X.to_prod.1 = Y.to_prod.1)\n(map_snd : to_fun X.to_prod.2 = Y.to_prod.2)\n\nnamespace hom\n\n/-- The identity morphism of `X : Bipointed`. -/\n@[simps] def id (X : Bipointed) : hom X X := ⟨id, rfl, rfl⟩\n\ninstance (X : Bipointed) : inhabited (hom X X) := ⟨id X⟩\n\n/-- Composition of morphisms of `Bipointed`. -/\n@[simps] def comp {X Y Z : Bipointed.{u}} (f : hom X Y) (g : hom Y Z) : hom X Z :=\n⟨g.to_fun ∘ f.to_fun, by rw [function.comp_apply, f.map_fst, g.map_fst],\n by rw [function.comp_apply, f.map_snd, g.map_snd]⟩\n\nend hom\n\ninstance large_category : large_category Bipointed :=\n{ hom := hom,\n id := hom.id,\n comp := @hom.comp,\n id_comp' := λ _ _ _, hom.ext _ _ rfl,\n comp_id' := λ _ _ _, hom.ext _ _ rfl,\n assoc' := λ _ _ _ _ _ _ _, hom.ext _ _ rfl }\n\ninstance concrete_category : concrete_category Bipointed :=\n{ forget := { obj := Bipointed.X, map := @hom.to_fun },\n forget_faithful := ⟨@hom.ext⟩ }\n\n/-- Swaps the pointed elements of a bipointed type. `prod.swap` as a functor. -/\n@[simps] def swap : Bipointed ⥤ Bipointed :=\n{ obj := λ X, ⟨X, X.to_prod.swap⟩, map := λ X Y f, ⟨f.to_fun, f.map_snd, f.map_fst⟩ }\n\n/-- The equivalence between `Bipointed` and itself induced by `prod.swap` both ways. -/\n@[simps] def swap_equiv : Bipointed ≌ Bipointed :=\nequivalence.mk swap swap\n (nat_iso.of_components (λ X, { hom := ⟨id, rfl, rfl⟩, inv := ⟨id, rfl, rfl⟩ }) $ λ X Y f, rfl)\n (nat_iso.of_components (λ X, { hom := ⟨id, rfl, rfl⟩, inv := ⟨id, rfl, rfl⟩ }) $ λ X Y f, rfl)\n\n@[simp] lemma swap_equiv_symm : swap_equiv.symm = swap_equiv := rfl\n\nend Bipointed\n\n/-- The forgetful functor from `Bipointed` to `Pointed` which forgets about the second point. -/\ndef Bipointed_to_Pointed_fst : Bipointed ⥤ Pointed :=\n{ obj := λ X, ⟨X, X.to_prod.1⟩, map := λ X Y f, ⟨f.to_fun, f.map_fst⟩ }\n\n/-- The forgetful functor from `Bipointed` to `Pointed` which forgets about the first point. -/\ndef Bipointed_to_Pointed_snd : Bipointed ⥤ Pointed :=\n{ obj := λ X, ⟨X, X.to_prod.2⟩, map := λ X Y f, ⟨f.to_fun, f.map_snd⟩ }\n\n@[simp] lemma Bipointed_to_Pointed_fst_comp_forget :\n Bipointed_to_Pointed_fst ⋙ forget Pointed = forget Bipointed := rfl\n\n@[simp] lemma Bipointed_to_Pointed_snd_comp_forget :\n Bipointed_to_Pointed_snd ⋙ forget Pointed = forget Bipointed := rfl\n\n@[simp] lemma swap_comp_Bipointed_to_Pointed_fst :\n Bipointed.swap ⋙ Bipointed_to_Pointed_fst = Bipointed_to_Pointed_snd := rfl\n\n@[simp] lemma swap_comp_Bipointed_to_Pointed_snd :\n Bipointed.swap ⋙ Bipointed_to_Pointed_snd = Bipointed_to_Pointed_fst := rfl\n\n--TODO: This is actually an equivalence\n/-- The functor from `Pointed` to `Bipointed` which adds a second point. -/\ndef Pointed_to_Bipointed_fst : Pointed.{u} ⥤ Bipointed :=\n{ obj := λ X, ⟨option X, X.point, none⟩,\n map := λ X Y f, ⟨option.map f.to_fun, congr_arg _ f.map_point, rfl⟩,\n map_id' := λ X, Bipointed.hom.ext _ _ option.map_id,\n map_comp' := λ X Y Z f g, Bipointed.hom.ext _ _ (option.map_comp_map _ _).symm }\n\n--TODO: This is actually an equivalence\n/-- The functor from `Pointed` to `Bipointed` which adds a first point. -/\ndef Pointed_to_Bipointed_snd : Pointed.{u} ⥤ Bipointed :=\n{ obj := λ X, ⟨option X, none, X.point⟩,\n map := λ X Y f, ⟨option.map f.to_fun, rfl, congr_arg _ f.map_point⟩,\n map_id' := λ X, Bipointed.hom.ext _ _ option.map_id,\n map_comp' := λ X Y Z f g, Bipointed.hom.ext _ _ (option.map_comp_map _ _).symm }\n\n@[simp] lemma Pointed_to_Bipointed_fst_comp :\n Pointed_to_Bipointed_fst ⋙ Bipointed.swap = Pointed_to_Bipointed_snd := rfl\n\n@[simp] lemma Pointed_to_Bipointed_snd_comp :\n Pointed_to_Bipointed_snd ⋙ Bipointed.swap = Pointed_to_Bipointed_fst := rfl\n\n/-- The free/forgetful adjunction between `Pointed_to_Bipointed_fst` and `Bipointed_to_Pointed_fst`.\n-/\ndef Pointed_to_Bipointed_fst_Bipointed_to_Pointed_fst_adjunction :\n Pointed_to_Bipointed_fst ⊣ Bipointed_to_Pointed_fst :=\nadjunction.mk_of_hom_equiv\n{ hom_equiv := λ X Y, { to_fun := λ f, ⟨f.to_fun ∘ option.some, f.map_fst⟩,\n inv_fun := λ f, ⟨λ o, o.elim Y.to_prod.2 f.to_fun, f.map_point, rfl⟩,\n left_inv := λ f, by { ext, cases x, exact f.map_snd.symm, refl },\n right_inv := λ f, Pointed.hom.ext _ _ rfl },\n hom_equiv_naturality_left_symm' := λ X' X Y f g, by { ext, cases x; refl } }\n\n/-- The free/forgetful adjunction between `Pointed_to_Bipointed_snd` and `Bipointed_to_Pointed_snd`.\n-/\ndef Pointed_to_Bipointed_snd_Bipointed_to_Pointed_snd_adjunction :\n Pointed_to_Bipointed_snd ⊣ Bipointed_to_Pointed_snd :=\nadjunction.mk_of_hom_equiv\n{ hom_equiv := λ X Y, { to_fun := λ f, ⟨f.to_fun ∘ option.some, f.map_snd⟩,\n inv_fun := λ f, ⟨λ o, o.elim Y.to_prod.1 f.to_fun, rfl, f.map_point⟩,\n left_inv := λ f, by { ext, cases x, exact f.map_fst.symm, refl },\n right_inv := λ f, Pointed.hom.ext _ _ rfl },\n hom_equiv_naturality_left_symm' := λ X' X Y f g, by { ext, cases x; refl } }\n", "meta": {"author": "Mel-TunaRoll", "repo": "Lean-Mordell-Weil-Mel-Branch", "sha": "4db36f86423976aacd2c2968c4e45787fcd86b97", "save_path": "github-repos/lean/Mel-TunaRoll-Lean-Mordell-Weil-Mel-Branch", "path": "github-repos/lean/Mel-TunaRoll-Lean-Mordell-Weil-Mel-Branch/Lean-Mordell-Weil-Mel-Branch-4db36f86423976aacd2c2968c4e45787fcd86b97/src/category_theory/category/Bipointed.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41869690935568665, "lm_q2_score": 0.07369627682665666, "lm_q1q2_score": 0.030856403338342258}} {"text": "/-\nCopyright (c) 2021 Anne Baanen. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Anne Baanen\n-/\n\nimport logic.function.basic\nimport tactic.lint\nimport tactic.norm_cast\n\n/-!\n# Typeclass for a type `F` with an injective map to `A → B`\n\nThis typeclass is primarily for use by homomorphisms like `monoid_hom` and `linear_map`.\n\n## Basic usage of `fun_like`\n\nA typical type of morphisms should be declared as:\n```\nstructure my_hom (A B : Type*) [my_class A] [my_class B] :=\n(to_fun : A → B)\n(map_op' : ∀ {x y : A}, to_fun (my_class.op x y) = my_class.op (to_fun x) (to_fun y))\n\nnamespace my_hom\n\nvariables (A B : Type*) [my_class A] [my_class B]\n\n-- This instance is optional if you follow the \"morphism class\" design below:\ninstance : fun_like (my_hom A B) A (λ _, B) :=\n{ coe := my_hom.to_fun, coe_injective' := λ f g h, by cases f; cases g; congr' }\n\n/-- Helper instance for when there's too many metavariables to apply `to_fun.to_coe_fn` directly. -/\ninstance : has_coe_to_fun (my_hom A B) (λ _, A → B) := to_fun.to_coe_fn\n\n@[simp] lemma to_fun_eq_coe {f : my_hom A B} : f.to_fun = (f : A → B) := rfl\n\n@[ext] theorem ext {f g : my_hom A B} (h : ∀ x, f x = g x) : f = g := fun_like.ext f g h\n\n/-- Copy of a `my_hom` with a new `to_fun` equal to the old one. Useful to fix definitional\nequalities. -/\nprotected def copy (f : my_hom A B) (f' : A → B) (h : f' = ⇑f) : my_hom A B :=\n{ to_fun := f',\n map_op' := h.symm ▸ f.map_op' }\n\nend my_hom\n```\n\nThis file will then provide a `has_coe_to_fun` instance and various\nextensionality and simp lemmas.\n\n## Morphism classes extending `fun_like`\n\nThe `fun_like` design provides further benefits if you put in a bit more work.\nThe first step is to extend `fun_like` to create a class of those types satisfying\nthe axioms of your new type of morphisms.\nContinuing the example above:\n\n```\n/-- `my_hom_class F A B` states that `F` is a type of `my_class.op`-preserving morphisms.\nYou should extend this class when you extend `my_hom`. -/\nclass my_hom_class (F : Type*) (A B : out_param $ Type*) [my_class A] [my_class B]\n extends fun_like F A (λ _, B) :=\n(map_op : ∀ (f : F) (x y : A), f (my_class.op x y) = my_class.op (f x) (f y))\n\n@[simp] lemma map_op {F A B : Type*} [my_class A] [my_class B] [my_hom_class F A B]\n (f : F) (x y : A) : f (my_class.op x y) = my_class.op (f x) (f y) :=\nmy_hom_class.map_op\n\n-- You can replace `my_hom.fun_like` with the below instance:\ninstance : my_hom_class (my_hom A B) A B :=\n{ coe := my_hom.to_fun,\n coe_injective' := λ f g h, by cases f; cases g; congr',\n map_op := my_hom.map_op' }\n\n-- [Insert `has_coe_to_fun`, `to_fun_eq_coe`, `ext` and `copy` here]\n```\n\nThe second step is to add instances of your new `my_hom_class` for all types extending `my_hom`.\nTypically, you can just declare a new class analogous to `my_hom_class`:\n\n```\nstructure cooler_hom (A B : Type*) [cool_class A] [cool_class B]\n extends my_hom A B :=\n(map_cool' : to_fun cool_class.cool = cool_class.cool)\n\nclass cooler_hom_class (F : Type*) (A B : out_param $ Type*) [cool_class A] [cool_class B]\n extends my_hom_class F A B :=\n(map_cool : ∀ (f : F), f cool_class.cool = cool_class.cool)\n\n@[simp] lemma map_cool {F A B : Type*} [cool_class A] [cool_class B] [cooler_hom_class F A B]\n (f : F) : f cool_class.cool = cool_class.cool :=\nmy_hom_class.map_op\n\n-- You can also replace `my_hom.fun_like` with the below instance:\ninstance : cool_hom_class (cool_hom A B) A B :=\n{ coe := cool_hom.to_fun,\n coe_injective' := λ f g h, by cases f; cases g; congr',\n map_op := cool_hom.map_op',\n map_cool := cool_hom.map_cool' }\n\n-- [Insert `has_coe_to_fun`, `to_fun_eq_coe`, `ext` and `copy` here]\n```\n\nThen any declaration taking a specific type of morphisms as parameter can instead take the\nclass you just defined:\n```\n-- Compare with: lemma do_something (f : my_hom A B) : sorry := sorry\nlemma do_something {F : Type*} [my_hom_class F A B] (f : F) : sorry := sorry\n```\n\nThis means anything set up for `my_hom`s will automatically work for `cool_hom_class`es,\nand defining `cool_hom_class` only takes a constant amount of effort,\ninstead of linearly increasing the work per `my_hom`-related declaration.\n\n-/\n\n-- This instance should have low priority, to ensure we follow the chain\n-- `fun_like → has_coe_to_fun`\nattribute [instance, priority 10] coe_fn_trans\n\n/-- The class `fun_like F α β` expresses that terms of type `F` have an\ninjective coercion to functions from `α` to `β`.\n\nThis typeclass is used in the definition of the homomorphism typeclasses,\nsuch as `zero_hom_class`, `mul_hom_class`, `monoid_hom_class`, ....\n-/\nclass fun_like (F : Sort*) (α : out_param Sort*) (β : out_param $ α → Sort*) :=\n(coe : F → Π a : α, β a)\n(coe_injective' : function.injective coe)\n\nsection dependent\n\n/-! ### `fun_like F α β` where `β` depends on `a : α` -/\n\nvariables (F α : Sort*) (β : α → Sort*)\n\nnamespace fun_like\n\nvariables {F α β} [i : fun_like F α β]\n\ninclude i\n\n@[priority 100, -- Give this a priority between `coe_fn_trans` and the default priority\n nolint dangerous_instance] -- `α` and `β` are out_params, so this instance should not be dangerous\ninstance : has_coe_to_fun F (λ _, Π a : α, β a) := { coe := fun_like.coe }\n\n@[simp] \n\ntheorem coe_injective : function.injective (coe_fn : F → Π a : α, β a) :=\nfun_like.coe_injective'\n\n@[simp, norm_cast]\ntheorem coe_fn_eq {f g : F} : (f : Π a : α, β a) = (g : Π a : α, β a) ↔ f = g :=\n⟨λ h, @coe_injective _ _ _ i _ _ h, λ h, by cases h; refl⟩\n\ntheorem ext' {f g : F} (h : (f : Π a : α, β a) = (g : Π a : α, β a)) : f = g :=\ncoe_injective h\n\ntheorem ext'_iff {f g : F} : f = g ↔ ((f : Π a : α, β a) = (g : Π a : α, β a)) :=\ncoe_fn_eq.symm\n\ntheorem ext (f g : F) (h : ∀ (x : α), f x = g x) : f = g :=\ncoe_injective (funext h)\n\ntheorem ext_iff {f g : F} : f = g ↔ (∀ x, f x = g x) :=\ncoe_fn_eq.symm.trans function.funext_iff\n\nprotected lemma congr_fun {f g : F} (h₁ : f = g) (x : α) : f x = g x :=\ncongr_fun (congr_arg _ h₁) x\n\nend fun_like\n\nend dependent\n\nsection non_dependent\n\n/-! ### `fun_like F α (λ _, β)` where `β` does not depend on `a : α` -/\n\nvariables {F α β : Sort*} [i : fun_like F α (λ _, β)]\n\ninclude i\n\nnamespace fun_like\n\nprotected lemma congr {f g : F} {x y : α} (h₁ : f = g) (h₂ : x = y) : f x = g y :=\ncongr (congr_arg _ h₁) h₂\n\nprotected lemma congr_arg (f : F) {x y : α} (h₂ : x = y) : f x = f y :=\ncongr_arg _ h₂\n\nend fun_like\n\nend non_dependent\n", "meta": {"author": "Mel-TunaRoll", "repo": "Lean-Mordell-Weil-Mel-Branch", "sha": "4db36f86423976aacd2c2968c4e45787fcd86b97", "save_path": "github-repos/lean/Mel-TunaRoll-Lean-Mordell-Weil-Mel-Branch", "path": "github-repos/lean/Mel-TunaRoll-Lean-Mordell-Weil-Mel-Branch/Lean-Mordell-Weil-Mel-Branch-4db36f86423976aacd2c2968c4e45787fcd86b97/src/data/fun_like/basic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41869692386284973, "lm_q2_score": 0.07369627072327817, "lm_q1q2_score": 0.03085640185200036}} {"text": "import tactic\nimport topology.instances.real\n\nimport .tokens\nimport .compute\nimport .commun\n\nnamespace tactic\nsetup_tactic_parser\n\n@[derive has_reflect]\nmeta inductive On_args \n| exct_aply : pexpr → list pexpr → On_args -- On conclut par ... (appliqué à ...)\n| aply : pexpr → On_args -- On applique ...\n| aply_at : pexpr → list pexpr → On_args -- On applique ... à ...\n| rwrite : interactive.rw_rules_t → option name → option pexpr → On_args -- On réécrit via ... (dans ... (qui devient ...))\n| rwrite_all : interactive.rw_rules_t → On_args -- On réécrit via ... partout\n| compute : On_args -- On calcule\n| compute_at : name → On_args -- On calcule dans ...\n| linar : list pexpr → On_args -- On combine ...\n| contrap (push : bool) : On_args -- On contrapose (simplement)\n| push_negation (hyp : option name) (new : option pexpr) : On_args -- On pousse la négation (dans ... (qui devient ...))\n| discussion : pexpr → On_args -- On discute en utilisant ... [cases]\n| discussion_hyp : pexpr → On_args -- On discute selon que ... [by_cases]\n| deplie : list name → On_args -- On déplie ...\n| deplie_at : list name → loc → option pexpr → On_args -- On déplie ... dans ... (qui devient ...)\n| rname : name → name → option loc → option pexpr → On_args -- On renomme ... en ... (dans ... (qui devient ...))\n| oubli : list name → On_args -- pour clear\n| reforml : name → pexpr → On_args -- pour change at\n\nopen On_args\n\nmeta def qui_devient_parser : lean.parser (option pexpr) := (tk \"qui\" *> tk \"devient\" *> texpr)?\n\n/-- Syntax for on parser-/\nmeta def On_parser : lean.parser On_args :=\nwith_desc \"conclut par ... (appliqué à ...) / On applique ... (à ...) / On calcule (dans ...) / On réécrit via ... (dans ... (qui devient ...)) / On combine ... / On contrapose / On discute selon ... / On discute selon que ... / On déplie ... (dans ... (qui devient ...)) / On renomme ... en ... (dans ... (qui devient ...)) / On oublie ... / On reformule ... en ... / On pousse la négation (dans ... (qui devient ...))\" $\n(exct_aply <$> (tk \"conclut\" *> tk \"par\" *> texpr) <*> applique_a_parser) <|>\n(do { e ← tk \"applique\" *> texpr,\n aply_at e <$> (tk \"à\" *> pexpr_list_or_texpr) <|> pure (aply e)}) <|>\n(tk \"calcule\" *> (compute_at <$> (tk \"dans\" *> ident) <|> pure compute)) <|>\n(linar <$> (tk \"combine\" *> pexpr_list_or_texpr)) <|>\ndo { rules ← tk \"réécrit\" *> tk \"via\" *> interactive.rw_rules,\n rwrite_all rules <$ tk \"partout\" <|>\n rwrite rules <$> (tk \"dans\" *> ident)? <*> qui_devient_parser } <|>\ndo { tk \"contrapose\", \n (contrap ff <$ tk \"simplement\") <|>\n pure (contrap tt) } <|>\npush_negation <$> (tk \"pousse\" *> tk \"la\" *> tk \"négation\" *> (tk \"dans\" *> ident)?) <*> qui_devient_parser <|>\ndo { tk \"discute\",\n discussion_hyp <$> (tk \"selon\" *> tk \"que\" *> texpr) <|>\n discussion <$> (tk \"en\" *> tk \"utilisant\" *> texpr) } <|>\ndo { ids ← tk \"déplie\" *> ident*,\n do { place ← tk \"dans\" *> ident,\n deplie_at ids (loc.ns [place]) <$> qui_devient_parser } <|> \n pure (deplie ids) } <|>\ndo { old ← tk \"renomme\" *> ident <* tk \"en\",\n new ← ident,\n do { place ← tk \"dans\" *> ident,\n rname old new (loc.ns [place]) <$> qui_devient_parser } <|> \n pure (rname old new none none) } <|>\nreforml <$> (tk \"reformule\" *> ident <* tk \"en\") <*> texpr <|>\noubli <$> (tk \"oublie\" *> ident*)\n\n\n/-- Action de démonstration -/\n@[interactive]\nmeta def On : parse On_parser → tactic unit\n| (exct_aply pe l) := conclure pe l\n| (aply pe) := focus1 (do \n to_expr pe >>= apply,\n all_goals (do try assumption, nettoyage),\n skip)\n| (aply_at pe pl) := do l ← pl.mmap to_expr,\n l.mmap' (apply_arrow_to_hyp pe) <|> interactive.specialize (pexpr_mk_app pe pl)\n| (rwrite pe l new) := do interactive.rewrite pe (loc.ns [l]),\n match (l, new) with\n | (some hyp, some newhyp) := do ne ← get_local hyp, \n enewhyp ← to_expr newhyp,\n infer_type ne >>= unify enewhyp\n | (_, some n) := fail \"On ne peut pas utiliser « qui devient » lorsqu'on réécrit via dans plusieurs endroits.\"\n | (_, none) := skip\n end\n| (rwrite_all pe) := interactive.rewrite pe loc.wildcard\n| compute := interactive.compute_at_goal'\n| (compute_at h) := interactive.compute_at_hyp' h\n| (linar le) := do le' ← le.mmap to_expr >>= split_ands,\n linarith ff tt le' <|> fail \"Combiner ces faits ce suffit pas.\"\n| (contrap push) := do \n `(%%P → %%Q) ← target | fail \"On ne peut pas contraposer, le but n'est pas une implication\",\n cp ← mk_mapp ``imp_of_not_imp_not [P, Q] <|> fail \"On ne peut pas contraposer, le but n'est pas une implication\",\n apply cp,\n if push then try (tactic.interactive.push_neg (loc.ns [none])) else skip\n| (discussion pe) := focus1 (do e ← to_expr pe,\n `(%%P ∨ %%Q) ← infer_type e <|> fail \"Cette expression n'est pas une disjonction.\",\n tgt ← target, \n `[refine (or.elim %%e _ _)],\n all_goals (try (clear e)) >> skip)\n| (discussion_hyp pe) := do e ← to_expr pe, \n `[refine (or.elim (classical.em %%e) _ _)]\n| (deplie le) := interactive.unfold le (loc.ns [none])\n| (deplie_at le loca new) := do interactive.unfold le loca,\n match (loca, new) with\n | (loc.ns [some hyp], some newhyp) := do ne ← get_local hyp, \n enewhyp ← to_expr newhyp,\n infer_type ne >>= unify enewhyp\n | (_, some n) := fail \"On ne peut pas utiliser « qui devient » lorsqu'on déplie dans plusieurs endroits.\"\n | (_, none) := skip\n end\n| (rname old new loca newhyp) := match (loca, newhyp) with\n | (some (loc.ns [some n]), some truc) := do e ← get_local n, \n rename_var_at_hyp old new e,\n interactive.guard_hyp_strict n truc <|>\n fail \"Ce n'est pas l'expression obtenue.\"\n | (some (loc.ns [some n]), none) := do e ← get_local n, \n rename_var_at_hyp old new e\n | _ := rename_var_at_goal old new\n end\n| (oubli l) := clear_lst l\n| (reforml n pe) := do h ← get_local n, e ← to_expr pe, change_core e (some h)\n| (push_negation n new) := do interactive.push_neg (loc.ns [n]),\n match (n, new) with\n | (some hyp, some stuff) := do e ← get_local hyp,\n enewhyp ← to_expr stuff,\n infer_type e >>= unify enewhyp\n | (none, some stuff) := fail \"On ne peut pas indiquer « qui devient » quand on pousse la négation dans le but.\"\n | _ := skip\n end\n\n\nend tactic\n\nexample (P Q R : Prop) (hRP : R → P) (hR : R) (hQ : Q) : P :=\nbegin\n fail_if_success { On conclut par hRP appliqué à hQ },\n On conclut par hRP appliqué à hR,\nend\n\nexample (P : ℕ → Prop) (h : ∀ n, P n) : P 0 :=\nbegin\n On conclut par h appliqué à _,\nend\n\nexample (P : ℕ → Prop) (h : ∀ n, P n) : P 0 :=\nbegin\n On conclut par h,\nend\n \n \nexample {a b : ℕ}: a + b = b + a :=\nbegin\n On calcule,\nend \n\nexample {a b : ℕ} (h : a + b - a = 0) : b = 0 :=\nbegin\n On calcule dans h,\n On conclut par h,\nend \n\nvariables k : nat\n\nexample (h : true) : true :=\nbegin\n On conclut par h,\nend\n\nexample (h : ∀ n : ℕ, true) : true :=\nbegin\n On conclut par h appliqué à 0,\nend\n\nexample (h : true → true) : true :=\nbegin\n On applique h,\n trivial,\nend\n\nexample (h : ∀ n k : ℕ, true) : true :=\nbegin\n On conclut par h appliqué à [0, 1],\nend\n\nexample (a b : ℕ) (h : a < b) : a ≤ b :=\nbegin\n On conclut par h,\nend\n\nexample (a b c : ℕ) (h : a < b ∧ a < c) : a ≤ b :=\nbegin\n On conclut par h,\nend\n\nexample (a b c : ℕ) (h : a ≤ b) (h' : b ≤ c) : a ≤ c :=\nbegin\n On combine [h, h'],\nend\n\nexample (a b c : ℤ) (h : a = b + c) (h' : b - a = c) : c = 0 :=\nbegin\n On combine [h, h'],\nend\n\nexample (a b c : ℕ) (h : a ≤ b) (h' : b ≤ c ∧ a+b ≤ a+c) : a ≤ c :=\nbegin\n On combine [h, h'],\nend\n\nexample (a b c : ℕ) (h : a = b) (h' : a = c) : b = c :=\nbegin\n On réécrit via ← h,\n On conclut par h',\nend\n\nexample (a b c : ℕ) (h : a = b) (h' : a = c) : b = c :=\nbegin\n On réécrit via h dans h',\n On conclut par h',\nend\n\nexample (f : ℕ → ℕ) (n : ℕ) (h : n > 0 → f n = 0) (hn : n > 0): f n = 0 :=\nbegin\n On réécrit via h,\n exact hn\nend\n\nexample (f : ℕ → ℕ) (n : ℕ) (h : ∀ n > 0, f n = 0) : f 1 = 0 :=\nbegin\n On réécrit via h,\n norm_num\nend\n\nexample (a b c : ℕ) (h : a = b) (h' : a = c) : b = c :=\nbegin\n success_if_fail { On réécrit via h dans h' qui devient a = c },\n On réécrit via h dans h' qui devient b = c,\n On conclut par h',\nend\n\nexample (a b c : ℕ) (h : a = b) (h' : a = c) : a = c :=\nbegin\n On réécrit via h partout,\n On conclut par h',\nend\n\nexample (P Q R : Prop) (h : P → Q) (h' : P) : Q :=\nbegin\n On applique h à h',\n On conclut par h',\nend\n\nexample (P Q R : Prop) (h : P → Q → R) (hP : P) (hQ : Q) : R :=\nbegin\n On conclut par h appliqué à [hP, hQ],\nend\n\nexample (f : ℕ → ℕ) (a b : ℕ) (h : a = b) : f a = f b :=\nbegin\n On applique f à h,\n On conclut par h,\nend\n\nexample (P : ℕ → Prop) (h : ∀ n, P n) : P 0 :=\nbegin\n On applique h à 0,\n On conclut par h\nend\n\nexample (x : ℝ) : (∀ ε > 0, x ≤ ε) → x ≤ 0 :=\nbegin\n On contrapose,\n intro h,\n use x/2,\n split,\n On conclut par h, -- linarith\n On conclut par h, -- linarith\nend\n\nexample (ε : ℝ) (h : ε > 0) : ε ≥ 0 := by On conclut par h\nexample (ε : ℝ) (h : ε > 0) : ε/2 > 0 := by On conclut par h\nexample (ε : ℝ) (h : ε > 0) : ε ≥ -1 := by On conclut par h\nexample (ε : ℝ) (h : ε > 0) : ε/2 ≥ -3 := by On conclut par h\n\nexample (x : ℝ) (h : x = 3) : 2*x = 6 := by On conclut par h\n\nexample (x : ℝ) : (∀ ε > 0, x ≤ ε) → x ≤ 0 :=\nbegin\n On contrapose simplement,\n intro h,\n On pousse la négation,\n On pousse la négation dans h,\n use x/2,\n split,\n On conclut par h, -- linarith\n On conclut par h, -- linarith\nend\n\nexample (x : ℝ) : (∀ ε > 0, x ≤ ε) → x ≤ 0 :=\nbegin\n On contrapose simplement,\n intro h,\n success_if_fail { On pousse la négation qui devient 0 < x },\n On pousse la négation,\n success_if_fail { On pousse la négation dans h qui devient ∃ (ε : ℝ), ε > 0 ∧ ε < x },\n On pousse la négation dans h qui devient 0 < x,\n use x/2,\n split,\n On conclut par h, -- linarith\n On conclut par h, -- linarith\nend\n\nexample : (∀ n : ℕ, false) → 0 = 1 :=\nbegin\n On contrapose,\n On calcule,\nend\n\nexample (P Q : Prop) (h : P ∨ Q) : true :=\nbegin\n On discute en utilisant h,\n all_goals { intro, trivial }\nend\n\nexample (P : Prop) (hP₁ : P → true) (hP₂ : ¬ P → true): true :=\nbegin\n On discute selon que P,\n intro h,\n exact hP₁ h,\n intro h,\n exact hP₂ h,\nend\n\ndef f (n : ℕ) := 2*n\n\nexample : f 2 = 4 :=\nbegin\n On déplie f,\n refl,\nend\n\nexample (h : f 2 = 4) : true → true :=\nbegin\n On déplie f dans h,\n guard_hyp_strict h : 2*2 = 4,\n exact id\nend\n\nexample (h : f 2 = 4) : true → true :=\nbegin\n success_if_fail { On déplie f dans h qui devient 2*2 = 5 },\n On déplie f dans h qui devient 2*2 = 4,\n exact id\nend\n\nexample (P : ℕ → ℕ → Prop) (h : ∀ n : ℕ, ∃ k, P n k) : true :=\nbegin\n On renomme n en p dans h,\n On renomme k en l dans h,\n guard_hyp_strict h : ∀ p, ∃ l, P p l,\n trivial\nend\n\nexample (P : ℕ → ℕ → Prop) (h : ∀ n : ℕ, ∃ k, P n k) : true :=\nbegin\n On renomme n en p dans h qui devient ∀ p, ∃ k, P p k,\n success_if_fail { On renomme k en l dans h qui devient ∀ p, ∃ j, P p j },\n On renomme k en l dans h qui devient ∀ p, ∃ l, P p l,\n trivial\nend\n\nexample (P : ℕ → ℕ → Prop) : (∀ n : ℕ, ∃ k, P n k) ∨ true :=\nbegin\n On renomme n en p,\n On renomme k en l,\n guard_target_strict (∀ p, ∃ l, P p l) ∨ true,\n right,\n trivial\nend\n\nexample (a b c : ℕ) : true :=\nbegin\n On oublie a,\n On oublie b c,\n trivial\nend\n\nexample (h : 1 + 1 = 2) : true :=\nbegin\n success_if_fail { On reformule h en 2 = 3 },\n On reformule h en 2 = 2,\n trivial,\nend\n", "meta": {"author": "PatrickMassot", "repo": "MDD154", "sha": "00defe82a4b6b7992ed522a92f62abd685e8c943", "save_path": "github-repos/lean/PatrickMassot-MDD154", "path": "github-repos/lean/PatrickMassot-MDD154/MDD154-00defe82a4b6b7992ed522a92f62abd685e8c943/src/lib/On.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3998116407397951, "lm_q2_score": 0.07696082934474628, "lm_q1q2_score": 0.03076983545301838}} {"text": "/-\nCopyright (c) 2021 Andrew Yang. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Andrew Yang\n-/\nimport category_theory.adjunction.comma\nimport category_theory.limits.preserves.shapes.terminal\nimport category_theory.structured_arrow\nimport category_theory.limits.shapes.equivalence\n\n/-!\n# Limits and the category of (co)cones\n\n> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.\n> Any changes to this file require a corresponding PR to mathlib4.\n\nThis files contains results that stem from the limit API. For the definition and the category\ninstance of `cone`, please refer to `category_theory/limits/cones.lean`.\n\n## Main results\n* The category of cones on `F : J ⥤ C` is equivalent to the category\n `costructured_arrow (const J) F`.\n* A cone is limiting iff it is terminal in the category of cones. As a corollary, an equivalence of\n categories of cones preserves limiting properties.\n\n-/\n\nnamespace category_theory.limits\n\nopen category_theory category_theory.functor\n\nuniverses v₁ v₂ v₃ v₄ u₁ u₂ u₃ u₄\n\nvariables {J : Type u₁} [category.{v₁} J] {K : Type u₂} [category.{v₂} K]\nvariables {C : Type u₃} [category.{v₃} C] {D : Type u₄} [category.{v₄} D]\n\n/-- Construct an object of the category `(Δ ↓ F)` from a cone on `F`. This is part of an\n equivalence, see `cone.equiv_costructured_arrow`. -/\n@[simps]\ndef cone.to_costructured_arrow (F : J ⥤ C) : cone F ⥤ costructured_arrow (const J) F :=\n{ obj := λ c, costructured_arrow.mk c.π,\n map := λ c d f, costructured_arrow.hom_mk f.hom $ by { ext, simp } }\n\n/-- Construct a cone on `F` from an object of the category `(Δ ↓ F)`. This is part of an\n equivalence, see `cone.equiv_costructured_arrow`. -/\n@[simps]\ndef cone.from_costructured_arrow (F : J ⥤ C) : costructured_arrow (const J) F ⥤ cone F :=\n{ obj := λ c, ⟨c.left, c.hom⟩,\n map := λ c d f,\n { hom := f.left,\n w' := λ j, by { convert (congr_fun (congr_arg nat_trans.app f.w) j), dsimp, simp } } }\n\n/-- The category of cones on `F` is just the comma category `(Δ ↓ F)`, where `Δ` is the constant\n functor. -/\n@[simps]\ndef cone.equiv_costructured_arrow (F : J ⥤ C) : cone F ≌ costructured_arrow (const J) F :=\nequivalence.mk (cone.to_costructured_arrow F) (cone.from_costructured_arrow F)\n (nat_iso.of_components cones.eta (by tidy))\n (nat_iso.of_components (λ c, (costructured_arrow.eta _).symm) (by tidy))\n\n/-- A cone is a limit cone iff it is terminal. -/\ndef cone.is_limit_equiv_is_terminal {F : J ⥤ C} (c : cone F) : is_limit c ≃ is_terminal c :=\nis_limit.iso_unique_cone_morphism.to_equiv.trans\n{ to_fun := λ h, by exactI is_terminal.of_unique _,\n inv_fun := λ h s, ⟨⟨is_terminal.from h s⟩, λ a, is_terminal.hom_ext h a _⟩,\n left_inv := by tidy,\n right_inv := by tidy }\n\nlemma has_limit_iff_has_terminal_cone (F : J ⥤ C) : has_limit F ↔ has_terminal (cone F) :=\n⟨λ h, by exactI (cone.is_limit_equiv_is_terminal _ (limit.is_limit F)).has_terminal,\n λ h, ⟨⟨by exactI ⟨⊤_ _, (cone.is_limit_equiv_is_terminal _).symm terminal_is_terminal⟩⟩⟩⟩\n\nlemma has_limits_of_shape_iff_is_left_adjoint_const :\n has_limits_of_shape J C ↔ nonempty (is_left_adjoint (const J : C ⥤ _)) :=\ncalc has_limits_of_shape J C\n ↔ ∀ F : J ⥤ C, has_limit F : ⟨λ h, h.has_limit, λ h, by exactI has_limits_of_shape.mk⟩\n ... ↔ ∀ F : J ⥤ C, has_terminal (cone F) : forall_congr has_limit_iff_has_terminal_cone\n ... ↔ ∀ F : J ⥤ C, has_terminal (costructured_arrow (const J) F) :\n forall_congr $ λ F, (cone.equiv_costructured_arrow F).has_terminal_iff\n ... ↔ nonempty (is_left_adjoint (const J : C ⥤ _)) :\n nonempty_is_left_adjoint_iff_has_terminal_costructured_arrow.symm\n\nlemma is_limit.lift_cone_morphism_eq_is_terminal_from {F : J ⥤ C} {c : cone F} (hc : is_limit c)\n (s : cone F) : hc.lift_cone_morphism s =\n is_terminal.from (cone.is_limit_equiv_is_terminal _ hc) _ := rfl\n\nlemma is_terminal.from_eq_lift_cone_morphism {F : J ⥤ C} {c : cone F} (hc : is_terminal c)\n (s : cone F) : is_terminal.from hc s =\n ((cone.is_limit_equiv_is_terminal _).symm hc).lift_cone_morphism s :=\nby convert (is_limit.lift_cone_morphism_eq_is_terminal_from _ s).symm\n\n/-- If `G : cone F ⥤ cone F'` preserves terminal objects, it preserves limit cones. -/\ndef is_limit.of_preserves_cone_terminal {F : J ⥤ C} {F' : K ⥤ D} (G : cone F ⥤ cone F')\n [preserves_limit (functor.empty.{0} _) G] {c : cone F} (hc : is_limit c) :\n is_limit (G.obj c) :=\n(cone.is_limit_equiv_is_terminal _).symm $\n (cone.is_limit_equiv_is_terminal _ hc).is_terminal_obj _ _\n\n/-- If `G : cone F ⥤ cone F'` reflects terminal objects, it reflects limit cones. -/\ndef is_limit.of_reflects_cone_terminal {F : J ⥤ C} {F' : K ⥤ D} (G : cone F ⥤ cone F')\n [reflects_limit (functor.empty.{0} _) G] {c : cone F} (hc : is_limit (G.obj c)) :\n is_limit c :=\n(cone.is_limit_equiv_is_terminal _).symm $\n (cone.is_limit_equiv_is_terminal _ hc).is_terminal_of_obj _ _\n\n/-- Construct an object of the category `(F ↓ Δ)` from a cocone on `F`. This is part of an\n equivalence, see `cocone.equiv_structured_arrow`. -/\n@[simps]\ndef cocone.to_structured_arrow (F : J ⥤ C) : cocone F ⥤ structured_arrow F (const J) :=\n{ obj := λ c, structured_arrow.mk c.ι,\n map := λ c d f, structured_arrow.hom_mk f.hom $ by { ext, simp } }\n\n/-- Construct a cocone on `F` from an object of the category `(F ↓ Δ)`. This is part of an\n equivalence, see `cocone.equiv_structured_arrow`. -/\n@[simps]\ndef cocone.from_structured_arrow (F : J ⥤ C) : structured_arrow F (const J) ⥤ cocone F :=\n{ obj := λ c, ⟨c.right, c.hom⟩,\n map := λ c d f,\n { hom := f.right,\n w' := λ j, by { convert (congr_fun (congr_arg nat_trans.app f.w) j).symm, dsimp, simp } } }\n\n/-- The category of cocones on `F` is just the comma category `(F ↓ Δ)`, where `Δ` is the constant\n functor. -/\n@[simps]\ndef cocone.equiv_structured_arrow (F : J ⥤ C) : cocone F ≌ structured_arrow F (const J) :=\nequivalence.mk (cocone.to_structured_arrow F) (cocone.from_structured_arrow F)\n (nat_iso.of_components cocones.eta (by tidy))\n (nat_iso.of_components (λ c, (structured_arrow.eta _).symm) (by tidy))\n\n/-- A cocone is a colimit cocone iff it is initial. -/\ndef cocone.is_colimit_equiv_is_initial {F : J ⥤ C} (c : cocone F) : is_colimit c ≃ is_initial c :=\nis_colimit.iso_unique_cocone_morphism.to_equiv.trans\n{ to_fun := λ h, by exactI is_initial.of_unique _,\n inv_fun := λ h s, ⟨⟨is_initial.to h s⟩, λ a, is_initial.hom_ext h a _⟩,\n left_inv := by tidy,\n right_inv := by tidy }\n\nlemma has_colimit_iff_has_initial_cocone (F : J ⥤ C) : has_colimit F ↔ has_initial (cocone F) :=\n⟨λ h, by exactI (cocone.is_colimit_equiv_is_initial _ (colimit.is_colimit F)).has_initial,\n λ h, ⟨⟨by exactI ⟨⊥_ _, (cocone.is_colimit_equiv_is_initial _).symm initial_is_initial⟩⟩⟩⟩\n\nlemma has_colimits_of_shape_iff_is_right_adjoint_const :\n has_colimits_of_shape J C ↔ nonempty (is_right_adjoint (const J : C ⥤ _)) :=\ncalc has_colimits_of_shape J C\n ↔ ∀ F : J ⥤ C, has_colimit F : ⟨λ h, h.has_colimit, λ h, by exactI has_colimits_of_shape.mk⟩\n ... ↔ ∀ F : J ⥤ C, has_initial (cocone F) : forall_congr has_colimit_iff_has_initial_cocone\n ... ↔ ∀ F : J ⥤ C, has_initial (structured_arrow F (const J)) :\n forall_congr $ λ F, (cocone.equiv_structured_arrow F).has_initial_iff\n ... ↔ nonempty (is_right_adjoint (const J : C ⥤ _)) :\n nonempty_is_right_adjoint_iff_has_initial_structured_arrow.symm\n\nlemma is_colimit.desc_cocone_morphism_eq_is_initial_to {F : J ⥤ C} {c : cocone F}\n (hc : is_colimit c) (s : cocone F) :\n hc.desc_cocone_morphism s =\n is_initial.to (cocone.is_colimit_equiv_is_initial _ hc) _ := rfl\n\nlemma is_initial.to_eq_desc_cocone_morphism {F : J ⥤ C} {c : cocone F}\n (hc : is_initial c) (s : cocone F) :\n is_initial.to hc s = ((cocone.is_colimit_equiv_is_initial _).symm hc).desc_cocone_morphism s :=\nby convert (is_colimit.desc_cocone_morphism_eq_is_initial_to _ s).symm\n\n/-- If `G : cocone F ⥤ cocone F'` preserves initial objects, it preserves colimit cocones. -/\ndef is_colimit.of_preserves_cocone_initial {F : J ⥤ C} {F' : K ⥤ D} (G : cocone F ⥤ cocone F')\n [preserves_colimit (functor.empty.{0} _) G] {c : cocone F} (hc : is_colimit c) :\n is_colimit (G.obj c) :=\n(cocone.is_colimit_equiv_is_initial _).symm $\n (cocone.is_colimit_equiv_is_initial _ hc).is_initial_obj _ _\n\n/-- If `G : cocone F ⥤ cocone F'` reflects initial objects, it reflects colimit cocones. -/\ndef is_colimit.of_reflects_cocone_initial {F : J ⥤ C} {F' : K ⥤ D} (G : cocone F ⥤ cocone F')\n [reflects_colimit (functor.empty.{0} _) G] {c : cocone F} (hc : is_colimit (G.obj c)) :\n is_colimit c :=\n(cocone.is_colimit_equiv_is_initial _).symm $\n (cocone.is_colimit_equiv_is_initial _ hc).is_initial_of_obj _ _\n\nend category_theory.limits\n", "meta": {"author": "leanprover-community", "repo": "mathlib", "sha": "5e526d18cea33550268dcbbddcb822d5cde40654", "save_path": "github-repos/lean/leanprover-community-mathlib", "path": "github-repos/lean/leanprover-community-mathlib/mathlib-5e526d18cea33550268dcbbddcb822d5cde40654/src/category_theory/limits/cone_category.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.06097517873196762, "lm_q1q2_score": 0.03048758936598381}} {"text": "/-\nCopyright (c) 2020 Yury G. Kudryashov. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthor: Yury G. Kudryashov\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.default\nimport Mathlib.linear_algebra.affine_space.affine_map\nimport Mathlib.algebra.invertible\nimport Mathlib.PostPort\n\nuniverses u_1 u_2 u_3 u_4 u_5 l u_6 u_7 u_8 u_9 u_10 \n\nnamespace Mathlib\n\n/-!\n# Affine equivalences\n\nIn this file we define `affine_equiv k P₁ P₂` (notation: `P₁ ≃ᵃ[k] P₂`) to be the type of affine\nequivalences between `P₁` and `P₂, i.e., equivalences such that both forward and inverse maps are\naffine maps.\n\nWe define the following equivalences:\n\n* `affine_equiv.refl k P`: the identity map as an `affine_equiv`;\n\n* `e.symm`: the inverse map of an `affine_equiv` as an `affine_equiv`;\n\n* `e.trans e'`: composition of two `affine_equiv`s; note that the order follows `mathlib`'s\n `category_theory` convention (apply `e`, then `e'`), not the convention used in function\n composition and compositions of bundled morphisms.\n\n## Tags\n\naffine space, affine equivalence\n-/\n\n/-- An affine equivalence is an equivalence between affine spaces such that both forward\nand inverse maps are affine.\n\nWe define it using an `equiv` for the map and a `linear_equiv` for the linear part in order\nto allow affine equivalences with good definitional equalities. -/\nstructure affine_equiv (k : Type u_1) (P₁ : Type u_2) (P₂ : Type u_3) {V₁ : Type u_4}\n {V₂ : Type u_5} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁]\n [add_comm_group V₂] [semimodule k V₂] [add_torsor V₂ P₂]\n extends P₁ ≃ P₂ where\n linear : linear_equiv k V₁ V₂\n map_vadd' : ∀ (p : P₁) (v : V₁), coe_fn _to_equiv (v +ᵥ p) = coe_fn linear v +ᵥ coe_fn _to_equiv p\n\nprotected instance affine_equiv.has_coe_to_fun (k : Type u_1) {V1 : Type u_2} (P1 : Type u_3)\n {V2 : Type u_4} (P2 : Type u_5) [ring k] [add_comm_group V1] [module k V1] [add_torsor V1 P1]\n [add_comm_group V2] [module k V2] [add_torsor V2 P2] : has_coe_to_fun (affine_equiv k P1 P2) :=\n has_coe_to_fun.mk (fun (e : affine_equiv k P1 P2) => P1 → P2)\n fun (e : affine_equiv k P1 P2) => equiv.to_fun (affine_equiv.to_equiv e)\n\nnamespace linear_equiv\n\n\n/-- Interpret a linear equivalence between modules as an affine equivalence. -/\ndef to_affine_equiv {k : Type u_1} {V₁ : Type u_2} {V₂ : Type u_3} [ring k] [add_comm_group V₁]\n [semimodule k V₁] [add_comm_group V₂] [semimodule k V₂] (e : linear_equiv k V₁ V₂) :\n affine_equiv k V₁ V₂ :=\n affine_equiv.mk (to_equiv e) e sorry\n\n@[simp] theorem coe_to_affine_equiv {k : Type u_1} {V₁ : Type u_2} {V₂ : Type u_3} [ring k]\n [add_comm_group V₁] [semimodule k V₁] [add_comm_group V₂] [semimodule k V₂]\n (e : linear_equiv k V₁ V₂) : ⇑(to_affine_equiv e) = ⇑e :=\n rfl\n\nend linear_equiv\n\n\nnamespace affine_equiv\n\n\n/-- Identity map as an `affine_equiv`. -/\ndef refl (k : Type u_1) {V₁ : Type u_2} (P₁ : Type u_6) [ring k] [add_comm_group V₁]\n [semimodule k V₁] [add_torsor V₁ P₁] : affine_equiv k P₁ P₁ :=\n mk (equiv.refl P₁) (linear_equiv.refl k V₁) sorry\n\n@[simp] theorem coe_refl (k : Type u_1) {V₁ : Type u_2} (P₁ : Type u_6) [ring k] [add_comm_group V₁]\n [semimodule k V₁] [add_torsor V₁ P₁] : ⇑(refl k P₁) = id :=\n rfl\n\ntheorem refl_apply (k : Type u_1) {V₁ : Type u_2} (P₁ : Type u_6) [ring k] [add_comm_group V₁]\n [semimodule k V₁] [add_torsor V₁ P₁] (x : P₁) : coe_fn (refl k P₁) x = x :=\n rfl\n\n@[simp] theorem to_equiv_refl (k : Type u_1) {V₁ : Type u_2} (P₁ : Type u_6) [ring k]\n [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] :\n to_equiv (refl k P₁) = equiv.refl P₁ :=\n rfl\n\n@[simp] theorem linear_refl (k : Type u_1) {V₁ : Type u_2} (P₁ : Type u_6) [ring k]\n [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] :\n linear (refl k P₁) = linear_equiv.refl k V₁ :=\n rfl\n\n@[simp] theorem map_vadd {k : Type u_1} {V₁ : Type u_2} {V₂ : Type u_3} {P₁ : Type u_6}\n {P₂ : Type u_7} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁]\n [add_comm_group V₂] [semimodule k V₂] [add_torsor V₂ P₂] (e : affine_equiv k P₁ P₂) (p : P₁)\n (v : V₁) : coe_fn e (v +ᵥ p) = coe_fn (linear e) v +ᵥ coe_fn e p :=\n map_vadd' e p v\n\n@[simp] theorem coe_to_equiv {k : Type u_1} {V₁ : Type u_2} {V₂ : Type u_3} {P₁ : Type u_6}\n {P₂ : Type u_7} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁]\n [add_comm_group V₂] [semimodule k V₂] [add_torsor V₂ P₂] (e : affine_equiv k P₁ P₂) :\n ⇑(to_equiv e) = ⇑e :=\n rfl\n\n/-- Reinterpret an `affine_equiv` as an `affine_map`. -/\ndef to_affine_map {k : Type u_1} {V₁ : Type u_2} {V₂ : Type u_3} {P₁ : Type u_6} {P₂ : Type u_7}\n [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] [add_comm_group V₂]\n [semimodule k V₂] [add_torsor V₂ P₂] (e : affine_equiv k P₁ P₂) : affine_map k P₁ P₂ :=\n affine_map.mk (⇑e) (↑(linear e)) (map_vadd' e)\n\n@[simp] theorem coe_to_affine_map {k : Type u_1} {V₁ : Type u_2} {V₂ : Type u_3} {P₁ : Type u_6}\n {P₂ : Type u_7} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁]\n [add_comm_group V₂] [semimodule k V₂] [add_torsor V₂ P₂] (e : affine_equiv k P₁ P₂) :\n ⇑(to_affine_map e) = ⇑e :=\n rfl\n\n@[simp] theorem to_affine_map_mk {k : Type u_1} {V₁ : Type u_2} {V₂ : Type u_3} {P₁ : Type u_6}\n {P₂ : Type u_7} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁]\n [add_comm_group V₂] [semimodule k V₂] [add_torsor V₂ P₂] (f : P₁ ≃ P₂)\n (f' : linear_equiv k V₁ V₂)\n (h : ∀ (p : P₁) (v : V₁), coe_fn f (v +ᵥ p) = coe_fn f' v +ᵥ coe_fn f p) :\n to_affine_map (mk f f' h) = affine_map.mk (⇑f) (↑f') h :=\n rfl\n\n@[simp] theorem linear_to_affine_map {k : Type u_1} {V₁ : Type u_2} {V₂ : Type u_3} {P₁ : Type u_6}\n {P₂ : Type u_7} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁]\n [add_comm_group V₂] [semimodule k V₂] [add_torsor V₂ P₂] (e : affine_equiv k P₁ P₂) :\n affine_map.linear (to_affine_map e) = ↑(linear e) :=\n rfl\n\ntheorem injective_to_affine_map {k : Type u_1} {V₁ : Type u_2} {V₂ : Type u_3} {P₁ : Type u_6}\n {P₂ : Type u_7} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁]\n [add_comm_group V₂] [semimodule k V₂] [add_torsor V₂ P₂] : function.injective to_affine_map :=\n sorry\n\n@[simp] theorem to_affine_map_inj {k : Type u_1} {V₁ : Type u_2} {V₂ : Type u_3} {P₁ : Type u_6}\n {P₂ : Type u_7} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁]\n [add_comm_group V₂] [semimodule k V₂] [add_torsor V₂ P₂] {e : affine_equiv k P₁ P₂}\n {e' : affine_equiv k P₁ P₂} : to_affine_map e = to_affine_map e' ↔ e = e' :=\n function.injective.eq_iff injective_to_affine_map\n\ntheorem ext {k : Type u_1} {V₁ : Type u_2} {V₂ : Type u_3} {P₁ : Type u_6} {P₂ : Type u_7} [ring k]\n [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] [add_comm_group V₂] [semimodule k V₂]\n [add_torsor V₂ P₂] {e : affine_equiv k P₁ P₂} {e' : affine_equiv k P₁ P₂}\n (h : ∀ (x : P₁), coe_fn e x = coe_fn e' x) : e = e' :=\n injective_to_affine_map (affine_map.ext h)\n\ntheorem injective_coe_fn {k : Type u_1} {V₁ : Type u_2} {V₂ : Type u_3} {P₁ : Type u_6}\n {P₂ : Type u_7} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁]\n [add_comm_group V₂] [semimodule k V₂] [add_torsor V₂ P₂] :\n function.injective fun (e : affine_equiv k P₁ P₂) (x : P₁) => coe_fn e x :=\n sorry\n\n@[simp] theorem coe_fn_inj {k : Type u_1} {V₁ : Type u_2} {V₂ : Type u_3} {P₁ : Type u_6}\n {P₂ : Type u_7} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁]\n [add_comm_group V₂] [semimodule k V₂] [add_torsor V₂ P₂] {e : affine_equiv k P₁ P₂}\n {e' : affine_equiv k P₁ P₂} : ⇑e = ⇑e' ↔ e = e' :=\n function.injective.eq_iff injective_coe_fn\n\ntheorem injective_to_equiv {k : Type u_1} {V₁ : Type u_2} {V₂ : Type u_3} {P₁ : Type u_6}\n {P₂ : Type u_7} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁]\n [add_comm_group V₂] [semimodule k V₂] [add_torsor V₂ P₂] : function.injective to_equiv :=\n fun (e e' : affine_equiv k P₁ P₂) (H : to_equiv e = to_equiv e') => ext (iff.mp equiv.ext_iff H)\n\n@[simp] theorem to_equiv_inj {k : Type u_1} {V₁ : Type u_2} {V₂ : Type u_3} {P₁ : Type u_6}\n {P₂ : Type u_7} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁]\n [add_comm_group V₂] [semimodule k V₂] [add_torsor V₂ P₂] {e : affine_equiv k P₁ P₂}\n {e' : affine_equiv k P₁ P₂} : to_equiv e = to_equiv e' ↔ e = e' :=\n function.injective.eq_iff injective_to_equiv\n\n/-- Construct an affine equivalence by verifying the relation between the map and its linear part at\none base point. Namely, this function takes an equivalence `e : P₁ ≃ P₂`, a linear equivalece\n`e' : V₁ ≃ₗ[k] V₂`, and a point `p` such that for any other point `p'` we have\n`e p' = e' (p' -ᵥ p) +ᵥ e p`. -/\ndef mk' {k : Type u_1} {V₁ : Type u_2} {V₂ : Type u_3} {P₁ : Type u_6} {P₂ : Type u_7} [ring k]\n [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] [add_comm_group V₂] [semimodule k V₂]\n [add_torsor V₂ P₂] (e : P₁ ≃ P₂) (e' : linear_equiv k V₁ V₂) (p : P₁)\n (h : ∀ (p' : P₁), coe_fn e p' = coe_fn e' (p' -ᵥ p) +ᵥ coe_fn e p) : affine_equiv k P₁ P₂ :=\n mk e e' sorry\n\n@[simp] theorem coe_mk' {k : Type u_1} {V₁ : Type u_2} {V₂ : Type u_3} {P₁ : Type u_6}\n {P₂ : Type u_7} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁]\n [add_comm_group V₂] [semimodule k V₂] [add_torsor V₂ P₂] (e : P₁ ≃ P₂)\n (e' : linear_equiv k V₁ V₂) (p : P₁)\n (h : ∀ (p' : P₁), coe_fn e p' = coe_fn e' (p' -ᵥ p) +ᵥ coe_fn e p) : ⇑(mk' e e' p h) = ⇑e :=\n rfl\n\n@[simp] theorem to_equiv_mk' {k : Type u_1} {V₁ : Type u_2} {V₂ : Type u_3} {P₁ : Type u_6}\n {P₂ : Type u_7} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁]\n [add_comm_group V₂] [semimodule k V₂] [add_torsor V₂ P₂] (e : P₁ ≃ P₂)\n (e' : linear_equiv k V₁ V₂) (p : P₁)\n (h : ∀ (p' : P₁), coe_fn e p' = coe_fn e' (p' -ᵥ p) +ᵥ coe_fn e p) :\n to_equiv (mk' e e' p h) = e :=\n rfl\n\n@[simp] theorem linear_mk' {k : Type u_1} {V₁ : Type u_2} {V₂ : Type u_3} {P₁ : Type u_6}\n {P₂ : Type u_7} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁]\n [add_comm_group V₂] [semimodule k V₂] [add_torsor V₂ P₂] (e : P₁ ≃ P₂)\n (e' : linear_equiv k V₁ V₂) (p : P₁)\n (h : ∀ (p' : P₁), coe_fn e p' = coe_fn e' (p' -ᵥ p) +ᵥ coe_fn e p) :\n linear (mk' e e' p h) = e' :=\n rfl\n\n/-- Inverse of an affine equivalence as an affine equivalence. -/\ndef symm {k : Type u_1} {V₁ : Type u_2} {V₂ : Type u_3} {P₁ : Type u_6} {P₂ : Type u_7} [ring k]\n [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] [add_comm_group V₂] [semimodule k V₂]\n [add_torsor V₂ P₂] (e : affine_equiv k P₁ P₂) : affine_equiv k P₂ P₁ :=\n mk (equiv.symm (to_equiv e)) (linear_equiv.symm (linear e)) sorry\n\n@[simp] theorem symm_to_equiv {k : Type u_1} {V₁ : Type u_2} {V₂ : Type u_3} {P₁ : Type u_6}\n {P₂ : Type u_7} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁]\n [add_comm_group V₂] [semimodule k V₂] [add_torsor V₂ P₂] (e : affine_equiv k P₁ P₂) :\n equiv.symm (to_equiv e) = to_equiv (symm e) :=\n rfl\n\n@[simp] theorem symm_linear {k : Type u_1} {V₁ : Type u_2} {V₂ : Type u_3} {P₁ : Type u_6}\n {P₂ : Type u_7} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁]\n [add_comm_group V₂] [semimodule k V₂] [add_torsor V₂ P₂] (e : affine_equiv k P₁ P₂) :\n linear_equiv.symm (linear e) = linear (symm e) :=\n rfl\n\nprotected theorem bijective {k : Type u_1} {V₁ : Type u_2} {V₂ : Type u_3} {P₁ : Type u_6}\n {P₂ : Type u_7} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁]\n [add_comm_group V₂] [semimodule k V₂] [add_torsor V₂ P₂] (e : affine_equiv k P₁ P₂) :\n function.bijective ⇑e :=\n equiv.bijective (to_equiv e)\n\nprotected theorem surjective {k : Type u_1} {V₁ : Type u_2} {V₂ : Type u_3} {P₁ : Type u_6}\n {P₂ : Type u_7} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁]\n [add_comm_group V₂] [semimodule k V₂] [add_torsor V₂ P₂] (e : affine_equiv k P₁ P₂) :\n function.surjective ⇑e :=\n equiv.surjective (to_equiv e)\n\nprotected theorem injective {k : Type u_1} {V₁ : Type u_2} {V₂ : Type u_3} {P₁ : Type u_6}\n {P₂ : Type u_7} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁]\n [add_comm_group V₂] [semimodule k V₂] [add_torsor V₂ P₂] (e : affine_equiv k P₁ P₂) :\n function.injective ⇑e :=\n equiv.injective (to_equiv e)\n\n@[simp] theorem range_eq {k : Type u_1} {V₁ : Type u_2} {V₂ : Type u_3} {P₁ : Type u_6}\n {P₂ : Type u_7} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁]\n [add_comm_group V₂] [semimodule k V₂] [add_torsor V₂ P₂] (e : affine_equiv k P₁ P₂) :\n set.range ⇑e = set.univ :=\n function.surjective.range_eq (affine_equiv.surjective e)\n\n@[simp] theorem apply_symm_apply {k : Type u_1} {V₁ : Type u_2} {V₂ : Type u_3} {P₁ : Type u_6}\n {P₂ : Type u_7} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁]\n [add_comm_group V₂] [semimodule k V₂] [add_torsor V₂ P₂] (e : affine_equiv k P₁ P₂) (p : P₂) :\n coe_fn e (coe_fn (symm e) p) = p :=\n equiv.apply_symm_apply (to_equiv e) p\n\n@[simp] theorem symm_apply_apply {k : Type u_1} {V₁ : Type u_2} {V₂ : Type u_3} {P₁ : Type u_6}\n {P₂ : Type u_7} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁]\n [add_comm_group V₂] [semimodule k V₂] [add_torsor V₂ P₂] (e : affine_equiv k P₁ P₂) (p : P₁) :\n coe_fn (symm e) (coe_fn e p) = p :=\n equiv.symm_apply_apply (to_equiv e) p\n\ntheorem apply_eq_iff_eq_symm_apply {k : Type u_1} {V₁ : Type u_2} {V₂ : Type u_3} {P₁ : Type u_6}\n {P₂ : Type u_7} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁]\n [add_comm_group V₂] [semimodule k V₂] [add_torsor V₂ P₂] (e : affine_equiv k P₁ P₂) {p₁ : P₁}\n {p₂ : P₂} : coe_fn e p₁ = p₂ ↔ p₁ = coe_fn (symm e) p₂ :=\n equiv.apply_eq_iff_eq_symm_apply (to_equiv e)\n\n@[simp] theorem apply_eq_iff_eq {k : Type u_1} {V₁ : Type u_2} {V₂ : Type u_3} {P₁ : Type u_6}\n {P₂ : Type u_7} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁]\n [add_comm_group V₂] [semimodule k V₂] [add_torsor V₂ P₂] (e : affine_equiv k P₁ P₂) {p₁ : P₁}\n {p₂ : P₁} : coe_fn e p₁ = coe_fn e p₂ ↔ p₁ = p₂ :=\n equiv.apply_eq_iff_eq (to_equiv e)\n\n@[simp] theorem symm_refl {k : Type u_1} {V₁ : Type u_2} {P₁ : Type u_6} [ring k]\n [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] : symm (refl k P₁) = refl k P₁ :=\n rfl\n\n/-- Composition of two `affine_equiv`alences, applied left to right. -/\ndef trans {k : Type u_1} {V₁ : Type u_2} {V₂ : Type u_3} {V₃ : Type u_4} {P₁ : Type u_6}\n {P₂ : Type u_7} {P₃ : Type u_8} [ring k] [add_comm_group V₁] [semimodule k V₁]\n [add_torsor V₁ P₁] [add_comm_group V₂] [semimodule k V₂] [add_torsor V₂ P₂] [add_comm_group V₃]\n [semimodule k V₃] [add_torsor V₃ P₃] (e : affine_equiv k P₁ P₂) (e' : affine_equiv k P₂ P₃) :\n affine_equiv k P₁ P₃ :=\n mk (equiv.trans (to_equiv e) (to_equiv e')) (linear_equiv.trans (linear e) (linear e')) sorry\n\n@[simp] theorem coe_trans {k : Type u_1} {V₁ : Type u_2} {V₂ : Type u_3} {V₃ : Type u_4}\n {P₁ : Type u_6} {P₂ : Type u_7} {P₃ : Type u_8} [ring k] [add_comm_group V₁] [semimodule k V₁]\n [add_torsor V₁ P₁] [add_comm_group V₂] [semimodule k V₂] [add_torsor V₂ P₂] [add_comm_group V₃]\n [semimodule k V₃] [add_torsor V₃ P₃] (e : affine_equiv k P₁ P₂) (e' : affine_equiv k P₂ P₃) :\n ⇑(trans e e') = ⇑e' ∘ ⇑e :=\n rfl\n\ntheorem trans_apply {k : Type u_1} {V₁ : Type u_2} {V₂ : Type u_3} {V₃ : Type u_4} {P₁ : Type u_6}\n {P₂ : Type u_7} {P₃ : Type u_8} [ring k] [add_comm_group V₁] [semimodule k V₁]\n [add_torsor V₁ P₁] [add_comm_group V₂] [semimodule k V₂] [add_torsor V₂ P₂] [add_comm_group V₃]\n [semimodule k V₃] [add_torsor V₃ P₃] (e : affine_equiv k P₁ P₂) (e' : affine_equiv k P₂ P₃)\n (p : P₁) : coe_fn (trans e e') p = coe_fn e' (coe_fn e p) :=\n rfl\n\ntheorem trans_assoc {k : Type u_1} {V₁ : Type u_2} {V₂ : Type u_3} {V₃ : Type u_4} {V₄ : Type u_5}\n {P₁ : Type u_6} {P₂ : Type u_7} {P₃ : Type u_8} {P₄ : Type u_9} [ring k] [add_comm_group V₁]\n [semimodule k V₁] [add_torsor V₁ P₁] [add_comm_group V₂] [semimodule k V₂] [add_torsor V₂ P₂]\n [add_comm_group V₃] [semimodule k V₃] [add_torsor V₃ P₃] [add_comm_group V₄] [semimodule k V₄]\n [add_torsor V₄ P₄] (e₁ : affine_equiv k P₁ P₂) (e₂ : affine_equiv k P₂ P₃)\n (e₃ : affine_equiv k P₃ P₄) : trans (trans e₁ e₂) e₃ = trans e₁ (trans e₂ e₃) :=\n ext fun (_x : P₁) => rfl\n\n@[simp] theorem trans_refl {k : Type u_1} {V₁ : Type u_2} {V₂ : Type u_3} {P₁ : Type u_6}\n {P₂ : Type u_7} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁]\n [add_comm_group V₂] [semimodule k V₂] [add_torsor V₂ P₂] (e : affine_equiv k P₁ P₂) :\n trans e (refl k P₂) = e :=\n ext fun (_x : P₁) => rfl\n\n@[simp] theorem refl_trans {k : Type u_1} {V₁ : Type u_2} {V₂ : Type u_3} {P₁ : Type u_6}\n {P₂ : Type u_7} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁]\n [add_comm_group V₂] [semimodule k V₂] [add_torsor V₂ P₂] (e : affine_equiv k P₁ P₂) :\n trans (refl k P₁) e = e :=\n ext fun (_x : P₁) => rfl\n\n@[simp] theorem trans_symm {k : Type u_1} {V₁ : Type u_2} {V₂ : Type u_3} {P₁ : Type u_6}\n {P₂ : Type u_7} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁]\n [add_comm_group V₂] [semimodule k V₂] [add_torsor V₂ P₂] (e : affine_equiv k P₁ P₂) :\n trans e (symm e) = refl k P₁ :=\n ext (symm_apply_apply e)\n\n@[simp] theorem symm_trans {k : Type u_1} {V₁ : Type u_2} {V₂ : Type u_3} {P₁ : Type u_6}\n {P₂ : Type u_7} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁]\n [add_comm_group V₂] [semimodule k V₂] [add_torsor V₂ P₂] (e : affine_equiv k P₁ P₂) :\n trans (symm e) e = refl k P₂ :=\n ext (apply_symm_apply e)\n\n@[simp] theorem apply_line_map {k : Type u_1} {V₁ : Type u_2} {V₂ : Type u_3} {P₁ : Type u_6}\n {P₂ : Type u_7} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁]\n [add_comm_group V₂] [semimodule k V₂] [add_torsor V₂ P₂] (e : affine_equiv k P₁ P₂) (a : P₁)\n (b : P₁) (c : k) :\n coe_fn e (coe_fn (affine_map.line_map a b) c) =\n coe_fn (affine_map.line_map (coe_fn e a) (coe_fn e b)) c :=\n affine_map.apply_line_map (to_affine_map e) a b c\n\nprotected instance group {k : Type u_1} {V₁ : Type u_2} {P₁ : Type u_6} [ring k] [add_comm_group V₁]\n [semimodule k V₁] [add_torsor V₁ P₁] : group (affine_equiv k P₁ P₁) :=\n group.mk (fun (e e' : affine_equiv k P₁ P₁) => trans e' e) sorry (refl k P₁) trans_refl refl_trans\n symm\n (div_inv_monoid.div._default (fun (e e' : affine_equiv k P₁ P₁) => trans e' e) sorry (refl k P₁)\n trans_refl refl_trans symm)\n trans_symm\n\ntheorem one_def {k : Type u_1} {V₁ : Type u_2} {P₁ : Type u_6} [ring k] [add_comm_group V₁]\n [semimodule k V₁] [add_torsor V₁ P₁] : 1 = refl k P₁ :=\n rfl\n\n@[simp] theorem coe_one {k : Type u_1} {V₁ : Type u_2} {P₁ : Type u_6} [ring k] [add_comm_group V₁]\n [semimodule k V₁] [add_torsor V₁ P₁] : ⇑1 = id :=\n rfl\n\ntheorem mul_def {k : Type u_1} {V₁ : Type u_2} {P₁ : Type u_6} [ring k] [add_comm_group V₁]\n [semimodule k V₁] [add_torsor V₁ P₁] (e : affine_equiv k P₁ P₁) (e' : affine_equiv k P₁ P₁) :\n e * e' = trans e' e :=\n rfl\n\n@[simp] theorem coe_mul {k : Type u_1} {V₁ : Type u_2} {P₁ : Type u_6} [ring k] [add_comm_group V₁]\n [semimodule k V₁] [add_torsor V₁ P₁] (e : affine_equiv k P₁ P₁) (e' : affine_equiv k P₁ P₁) :\n ⇑(e * e') = ⇑e ∘ ⇑e' :=\n rfl\n\ntheorem inv_def {k : Type u_1} {V₁ : Type u_2} {P₁ : Type u_6} [ring k] [add_comm_group V₁]\n [semimodule k V₁] [add_torsor V₁ P₁] (e : affine_equiv k P₁ P₁) : e⁻¹ = symm e :=\n rfl\n\n/-- The map `v ↦ v +ᵥ b` as an affine equivalence between a module `V` and an affine space `P` with\ntangent space `V`. -/\ndef vadd_const (k : Type u_1) {V₁ : Type u_2} {P₁ : Type u_6} [ring k] [add_comm_group V₁]\n [semimodule k V₁] [add_torsor V₁ P₁] (b : P₁) : affine_equiv k V₁ P₁ :=\n mk (equiv.vadd_const b) (linear_equiv.refl k V₁) sorry\n\n@[simp] theorem linear_vadd_const (k : Type u_1) {V₁ : Type u_2} {P₁ : Type u_6} [ring k]\n [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] (b : P₁) :\n linear (vadd_const k b) = linear_equiv.refl k V₁ :=\n rfl\n\n@[simp] theorem vadd_const_apply (k : Type u_1) {V₁ : Type u_2} {P₁ : Type u_6} [ring k]\n [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] (b : P₁) (v : V₁) :\n coe_fn (vadd_const k b) v = v +ᵥ b :=\n rfl\n\n@[simp] theorem vadd_const_symm_apply (k : Type u_1) {V₁ : Type u_2} {P₁ : Type u_6} [ring k]\n [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] (b : P₁) (p : P₁) :\n coe_fn (symm (vadd_const k b)) p = p -ᵥ b :=\n rfl\n\n/-- `p' ↦ p -ᵥ p'` as an equivalence. -/\ndef const_vsub (k : Type u_1) {V₁ : Type u_2} {P₁ : Type u_6} [ring k] [add_comm_group V₁]\n [semimodule k V₁] [add_torsor V₁ P₁] (p : P₁) : affine_equiv k P₁ V₁ :=\n mk (equiv.const_vsub p) (linear_equiv.neg k) sorry\n\n@[simp] theorem coe_const_vsub (k : Type u_1) {V₁ : Type u_2} {P₁ : Type u_6} [ring k]\n [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] (p : P₁) :\n ⇑(const_vsub k p) = has_vsub.vsub p :=\n rfl\n\n@[simp] theorem coe_const_vsub_symm (k : Type u_1) {V₁ : Type u_2} {P₁ : Type u_6} [ring k]\n [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] (p : P₁) :\n ⇑(symm (const_vsub k p)) = fun (v : V₁) => -v +ᵥ p :=\n rfl\n\n/-- The map `p ↦ v +ᵥ p` as an affine automorphism of an affine space. -/\ndef const_vadd (k : Type u_1) {V₁ : Type u_2} (P₁ : Type u_6) [ring k] [add_comm_group V₁]\n [semimodule k V₁] [add_torsor V₁ P₁] (v : V₁) : affine_equiv k P₁ P₁ :=\n mk (equiv.const_vadd P₁ v) (linear_equiv.refl k V₁) sorry\n\n@[simp] theorem linear_const_vadd (k : Type u_1) {V₁ : Type u_2} (P₁ : Type u_6) [ring k]\n [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] (v : V₁) :\n linear (const_vadd k P₁ v) = linear_equiv.refl k V₁ :=\n rfl\n\n@[simp] theorem const_vadd_apply (k : Type u_1) {V₁ : Type u_2} (P₁ : Type u_6) [ring k]\n [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] (v : V₁) (p : P₁) :\n coe_fn (const_vadd k P₁ v) p = v +ᵥ p :=\n rfl\n\n@[simp] theorem const_vadd_symm_apply (k : Type u_1) {V₁ : Type u_2} (P₁ : Type u_6) [ring k]\n [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] (v : V₁) (p : P₁) :\n coe_fn (symm (const_vadd k P₁ v)) p = -v +ᵥ p :=\n rfl\n\n/-- Point reflection in `x` as a permutation. -/\ndef point_reflection (k : Type u_1) {V₁ : Type u_2} {P₁ : Type u_6} [ring k] [add_comm_group V₁]\n [semimodule k V₁] [add_torsor V₁ P₁] (x : P₁) : affine_equiv k P₁ P₁ :=\n trans (const_vsub k x) (vadd_const k x)\n\ntheorem point_reflection_apply (k : Type u_1) {V₁ : Type u_2} {P₁ : Type u_6} [ring k]\n [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] (x : P₁) (y : P₁) :\n coe_fn (point_reflection k x) y = x -ᵥ y +ᵥ x :=\n rfl\n\n@[simp] theorem point_reflection_symm (k : Type u_1) {V₁ : Type u_2} {P₁ : Type u_6} [ring k]\n [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] (x : P₁) :\n symm (point_reflection k x) = point_reflection k x :=\n injective_to_equiv (equiv.point_reflection_symm x)\n\n@[simp] theorem to_equiv_point_reflection (k : Type u_1) {V₁ : Type u_2} {P₁ : Type u_6} [ring k]\n [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] (x : P₁) :\n to_equiv (point_reflection k x) = equiv.point_reflection x :=\n rfl\n\n@[simp] theorem point_reflection_self (k : Type u_1) {V₁ : Type u_2} {P₁ : Type u_6} [ring k]\n [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] (x : P₁) :\n coe_fn (point_reflection k x) x = x :=\n vsub_vadd x x\n\ntheorem point_reflection_involutive (k : Type u_1) {V₁ : Type u_2} {P₁ : Type u_6} [ring k]\n [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] (x : P₁) :\n function.involutive ⇑(point_reflection k x) :=\n equiv.point_reflection_involutive x\n\n/-- `x` is the only fixed point of `point_reflection x`. This lemma requires\n`x + x = y + y ↔ x = y`. There is no typeclass to use here, so we add it as an explicit argument. -/\ntheorem point_reflection_fixed_iff_of_injective_bit0 (k : Type u_1) {V₁ : Type u_2} {P₁ : Type u_6}\n [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] {x : P₁} {y : P₁}\n (h : function.injective bit0) : coe_fn (point_reflection k x) y = y ↔ y = x :=\n equiv.point_reflection_fixed_iff_of_injective_bit0 h\n\ntheorem injective_point_reflection_left_of_injective_bit0 (k : Type u_1) {V₁ : Type u_2}\n {P₁ : Type u_6} [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁]\n (h : function.injective bit0) (y : P₁) :\n function.injective fun (x : P₁) => coe_fn (point_reflection k x) y :=\n equiv.injective_point_reflection_left_of_injective_bit0 h y\n\ntheorem injective_point_reflection_left_of_module (k : Type u_1) {V₁ : Type u_2} {P₁ : Type u_6}\n [ring k] [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] [invertible (bit0 1)]\n (y : P₁) : function.injective fun (x : P₁) => coe_fn (point_reflection k x) y :=\n sorry\n\ntheorem point_reflection_fixed_iff_of_module (k : Type u_1) {V₁ : Type u_2} {P₁ : Type u_6} [ring k]\n [add_comm_group V₁] [semimodule k V₁] [add_torsor V₁ P₁] [invertible (bit0 1)] {x : P₁}\n {y : P₁} : coe_fn (point_reflection k x) y = y ↔ y = x :=\n iff.trans\n (function.injective.eq_iff' (injective_point_reflection_left_of_module k y)\n (point_reflection_self k y))\n eq_comm\n\nend affine_equiv\n\n\nnamespace affine_map\n\n\ntheorem line_map_vadd {k : Type u_1} {V₁ : Type u_2} {P₁ : Type u_6} [ring k] [add_comm_group V₁]\n [semimodule k V₁] [add_torsor V₁ P₁] (v : V₁) (v' : V₁) (p : P₁) (c : k) :\n coe_fn (line_map v v') c +ᵥ p = coe_fn (line_map (v +ᵥ p) (v' +ᵥ p)) c :=\n affine_equiv.apply_line_map (affine_equiv.vadd_const k p) v v' c\n\ntheorem line_map_vsub {k : Type u_1} {V₁ : Type u_2} {P₁ : Type u_6} [ring k] [add_comm_group V₁]\n [semimodule k V₁] [add_torsor V₁ P₁] (p₁ : P₁) (p₂ : P₁) (p₃ : P₁) (c : k) :\n coe_fn (line_map p₁ p₂) c -ᵥ p₃ = coe_fn (line_map (p₁ -ᵥ p₃) (p₂ -ᵥ p₃)) c :=\n affine_equiv.apply_line_map (affine_equiv.symm (affine_equiv.vadd_const k p₃)) p₁ p₂ c\n\ntheorem vsub_line_map {k : Type u_1} {V₁ : Type u_2} {P₁ : Type u_6} [ring k] [add_comm_group V₁]\n [semimodule k V₁] [add_torsor V₁ P₁] (p₁ : P₁) (p₂ : P₁) (p₃ : P₁) (c : k) :\n p₁ -ᵥ coe_fn (line_map p₂ p₃) c = coe_fn (line_map (p₁ -ᵥ p₂) (p₁ -ᵥ p₃)) c :=\n affine_equiv.apply_line_map (affine_equiv.const_vsub k p₁) p₂ p₃ c\n\ntheorem vadd_line_map {k : Type u_1} {V₁ : Type u_2} {P₁ : Type u_6} [ring k] [add_comm_group V₁]\n [semimodule k V₁] [add_torsor V₁ P₁] (v : V₁) (p₁ : P₁) (p₂ : P₁) (c : k) :\n v +ᵥ coe_fn (line_map p₁ p₂) c = coe_fn (line_map (v +ᵥ p₁) (v +ᵥ p₂)) c :=\n affine_equiv.apply_line_map (affine_equiv.const_vadd k P₁ v) p₁ p₂ c\n\ntheorem homothety_neg_one_apply {V₁ : Type u_2} {P₁ : Type u_6} [add_comm_group V₁]\n [add_torsor V₁ P₁] {R' : Type u_10} [comm_ring R'] [semimodule R' V₁] (c : P₁) (p : P₁) :\n coe_fn (homothety c (-1)) p = coe_fn (affine_equiv.point_reflection R' c) p :=\n sorry\n\nend Mathlib", "meta": {"author": "AurelienSaue", "repo": "Mathlib4_auto", "sha": "590df64109b08190abe22358fabc3eae000943f2", "save_path": "github-repos/lean/AurelienSaue-Mathlib4_auto", "path": "github-repos/lean/AurelienSaue-Mathlib4_auto/Mathlib4_auto-590df64109b08190abe22358fabc3eae000943f2/Mathlib/linear_algebra/affine_space/affine_equiv_auto.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.06278921298147408, "lm_q1q2_score": 0.030413844275651934}} {"text": "syntax \"foo\" : tactic\n\nmacro_rules | `(tactic| foo) => `(tactic| assumption)\nmacro_rules | `(tactic| foo) => `(tactic| apply Nat.pred_lt; assumption)\nmacro_rules | `(tactic| foo) => `(tactic| contradiction)\n\nexample (i : Nat) (h : i - 1 < i) : i - 1 < i := by\n foo\n\nexample (i : Nat) (h : i ≠ 0) : i - 1 < i := by\n foo\n\nexample (i : Nat) (h : False) : i - 1 < i := by\n foo\n", "meta": {"author": "leanprover", "repo": "lean4", "sha": "742d053a97bdd109a41a921facd1cd6a55e89bc7", "save_path": "github-repos/lean/leanprover-lean4", "path": "github-repos/lean/leanprover-lean4/lean4-742d053a97bdd109a41a921facd1cd6a55e89bc7/tests/lean/run/evalTacticBug.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.06097518342456152, "lm_q1q2_score": 0.03024941224778246}} {"text": "/-\nCopyright (c) 2021 Scott Morrison. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Adam Topaz, Scott Morrison\n-/\nimport category_theory.comma\nimport category_theory.punit\nimport category_theory.limits.shapes.terminal\n\n/-!\n# The category of \"structured arrows\"\n\nFor `T : C ⥤ D`, a `T`-structured arrow with source `S : D`\nis just a morphism `S ⟶ T.obj Y`, for some `Y : D`.\n\nThese form a category with morphisms `g : Y ⟶ Y'` making the obvious diagram commute.\n\nWe prove that `𝟙 (T.obj Y)` is the initial object in `T`-structured objects with source `T.obj Y`.\n-/\n\nnamespace category_theory\n\nuniverses v₁ v₂ u₁ u₂ -- morphism levels before object levels. See note [category_theory universes].\nvariables {C : Type u₁} [category.{v₁} C] {D : Type u₂} [category.{v₂} D]\n\n/--\nThe category of `T`-structured arrows with domain `S : D` (here `T : C ⥤ D`),\nhas as its objects `D`-morphisms of the form `S ⟶ T Y`, for some `Y : C`,\nand morphisms `C`-morphisms `Y ⟶ Y'` making the obvious triangle commute.\n-/\n@[derive category, nolint has_inhabited_instance]\ndef structured_arrow (S : D) (T : C ⥤ D) := comma (functor.from_punit S) T\n\nnamespace structured_arrow\n\nvariables {S S' S'' : D} {Y Y' : C} {T : C ⥤ D}\n\n/-- The obvious projection functor from structured arrows. -/\ndef proj : structured_arrow S T ⥤ C := comma.snd _ _\n\n/-- Construct a structured arrow from a morphism. -/\ndef mk (f : S ⟶ T.obj Y) : structured_arrow S T := ⟨⟨⟩, Y, f⟩\n\n@[simp] lemma mk_left (f : S ⟶ T.obj Y) : (mk f).left = punit.star := rfl\n@[simp] lemma mk_right (f : S ⟶ T.obj Y) : (mk f).right = Y := rfl\n@[simp] lemma mk_hom_eq_self (f : S ⟶ T.obj Y) : (mk f).hom = f := rfl\n\nlemma eq_mk (f : structured_arrow S T) : f = mk f.hom :=\nby { cases f, congr, ext, }\n\n/--\nTo construct a morphism of structured arrows,\nwe need a morphism of the objects underlying the target,\nand to check that the triangle commutes.\n-/\n@[simps]\ndef hom_mk {f f' : structured_arrow S T} (g : f.right ⟶ f'.right) (w : f.hom ≫ T.map g = f'.hom) :\n f ⟶ f' :=\n{ left := eq_to_hom (by ext),\n right := g,\n w' := by { dsimp, simpa using w.symm, }, }\n\n/--\nTo construct an isomorphism of structured arrows,\nwe need an isomorphism of the objects underlying the target,\nand to check that the triangle commutes.\n-/\n@[simps]\ndef iso_mk {f f' : structured_arrow S T} (g : f.right ≅ f'.right)\n (w : f.hom ≫ T.map g.hom = f'.hom) : f ≅ f' :=\ncomma.iso_mk (eq_to_iso (by ext)) g (by simpa using w.symm)\n\n/--\nA morphism between source objects `S ⟶ S'`\ncontravariantly induces a functor between structured arrows,\n`structured_arrow S' T ⥤ structured_arrow S T`.\n\nIdeally this would be described as a 2-functor from `D`\n(promoted to a 2-category with equations as 2-morphisms)\nto `Cat`.\n-/\n@[simps]\ndef map (f : S ⟶ S') : structured_arrow S' T ⥤ structured_arrow S T :=\ncomma.map_left _ ((functor.const _).map f)\n\n@[simp] \n\n@[simp] lemma map_id {f : structured_arrow S T} : (map (𝟙 S)).obj f = f :=\nby { rw eq_mk f, simp, }\n\n@[simp] lemma map_comp {f : S ⟶ S'} {f' : S' ⟶ S''} {h : structured_arrow S'' T} :\n (map (f ≫ f')).obj h = (map f).obj ((map f').obj h) :=\nby { rw eq_mk h, simp, }\n\nopen category_theory.limits\n\n/-- The identity structured arrow is initial. -/\ndef mk_id_initial [full T] [faithful T] : is_initial (mk (𝟙 (T.obj Y))) :=\n{ desc := λ c, hom_mk (T.preimage c.X.hom) (by { dsimp, simp, }),\n uniq' := begin\n rintros c m -,\n ext,\n apply T.map_injective,\n have := m.w.symm,\n dsimp at this,\n simpa using this,\n end }\n\nend structured_arrow\n\n\n/--\nThe category of `S`-costructured arrows with target `T : D` (here `S : C ⥤ D`),\nhas as its objects `D`-morphisms of the form `S Y ⟶ T`, for some `Y : C`,\nand morphisms `C`-morphisms `Y ⟶ Y'` making the obvious triangle commute.\n-/\n@[derive category, nolint has_inhabited_instance]\ndef costructured_arrow (S : C ⥤ D) (T : D) := comma S (functor.from_punit T)\n\nnamespace costructured_arrow\n\nvariables {T T' T'' : D} {Y Y' : C} {S : C ⥤ D}\n\n/-- The obviuous projection functor from costructured arrows. -/\ndef proj : costructured_arrow S T ⥤ C := comma.fst _ _\n\n/-- Construct a costructured arrow from a morphism. -/\ndef mk (f : S.obj Y ⟶ T) : costructured_arrow S T := ⟨Y, ⟨⟩, f⟩\n\n@[simp] lemma mk_left (f : S.obj Y ⟶ T) : (mk f).left = Y := rfl\n@[simp] lemma mk_right (f : S.obj Y ⟶ T) : (mk f).right = punit.star := rfl\n@[simp] lemma mk_hom_eq_self (f : S.obj Y ⟶ T) : (mk f).hom = f := rfl\n\nlemma eq_mk (f : costructured_arrow S T) : f = mk (f.hom) :=\nby { cases f, congr, ext, }\n\n/--\nTo construct a morphism of costructured arrows,\nwe need a morphism of the objects underlying the source,\nand to check that the triangle commutes.\n-/\n@[simps]\ndef hom_mk {f f' : costructured_arrow S T} (g : f.left ⟶ f'.left) (w : S.map g ≫ f'.hom = f.hom) :\n f ⟶ f' :=\n{ left := g,\n right := eq_to_hom (by ext),\n w' := by simpa using w, }\n\n/--\nTo construct an isomorphism of costructured arrows,\nwe need an isomorphism of the objects underlying the source,\nand to check that the triangle commutes.\n-/\n@[simps]\ndef iso_mk {f f' : costructured_arrow S T} (g : f.left ≅ f'.left)\n (w : S.map g.hom ≫ f'.hom = f.hom) : f ≅ f' :=\ncomma.iso_mk g (eq_to_iso (by ext)) (by simpa using w)\n\n/--\nA morphism between target objects `T ⟶ T'`\ncovariantly induces a functor between costructured arrows,\n`costructured_arrow S T ⥤ costructured_arrow S T'`.\n\nIdeally this would be described as a 2-functor from `D`\n(promoted to a 2-category with equations as 2-morphisms)\nto `Cat`.\n-/\n@[simps]\ndef map (f : T ⟶ T') : costructured_arrow S T ⥤ costructured_arrow S T' :=\ncomma.map_right _ ((functor.const _).map f)\n\n@[simp] lemma map_mk {f : S.obj Y ⟶ T} (g : T ⟶ T') :\n (map g).obj (mk f) = mk (f ≫ g) := rfl\n\n@[simp] lemma map_id {f : costructured_arrow S T} : (map (𝟙 T)).obj f = f :=\nby { rw eq_mk f, simp, }\n\n@[simp] lemma map_comp {f : T ⟶ T'} {f' : T' ⟶ T''} {h : costructured_arrow S T} :\n (map (f ≫ f')).obj h = (map f').obj ((map f).obj h) :=\nby { rw eq_mk h, simp, }\n\nopen category_theory.limits\n\n/-- The identity costructured arrow is terminal. -/\ndef mk_id_terminal [full S] [faithful S] : is_terminal (mk (𝟙 (S.obj Y))) :=\n{ lift := λ c, hom_mk (S.preimage c.X.hom) (by { dsimp, simp, }),\n uniq' := begin\n rintros c m -,\n ext,\n apply S.map_injective,\n have := m.w,\n dsimp at this,\n simpa using this,\n end }\n\nend costructured_arrow\n\nend category_theory\n", "meta": {"author": "JLimperg", "repo": "aesop3", "sha": "a4a116f650cc7403428e72bd2e2c4cda300fe03f", "save_path": "github-repos/lean/JLimperg-aesop3", "path": "github-repos/lean/JLimperg-aesop3/aesop3-a4a116f650cc7403428e72bd2e2c4cda300fe03f/src/category_theory/structured_arrow.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43398146480389854, "lm_q2_score": 0.06954174932677784, "lm_q1q2_score": 0.030179830237860573}} {"text": "/-\nCopyright (c) 2017 Simon Hudon. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Simon Hudon\n-/\nimport algebra.group.defs\nimport control.functor\n\n/-!\n# `applicative` instances\n\nThis file provides `applicative` instances for concrete functors:\n* `id`\n* `functor.comp`\n* `functor.const`\n* `functor.add_const`\n-/\n\nuniverses u v w\n\nsection lemmas\n\nopen function\n\nvariables {F : Type u → Type v}\nvariables [applicative F] [is_lawful_applicative F]\nvariables {α β γ σ : Type u}\n\nlemma applicative.map_seq_map (f : α → β → γ) (g : σ → β) (x : F α) (y : F σ) :\n (f <$> x) <*> (g <$> y) = (flip (∘) g ∘ f) <$> x <*> y :=\nby simp [flip] with functor_norm\n\nlemma applicative.pure_seq_eq_map' (f : α → β) : (<*>) (pure f : F (α → β)) = (<$>) f :=\nby ext; simp with functor_norm\n\ntheorem applicative.ext {F} : ∀ {A1 : applicative F} {A2 : applicative F}\n [@is_lawful_applicative F A1] [@is_lawful_applicative F A2]\n (H1 : ∀ {α : Type u} (x : α),\n @has_pure.pure _ A1.to_has_pure _ x = @has_pure.pure _ A2.to_has_pure _ x)\n (H2 : ∀ {α β : Type u} (f : F (α → β)) (x : F α),\n @has_seq.seq _ A1.to_has_seq _ _ f x = @has_seq.seq _ A2.to_has_seq _ _ f x),\n A1 = A2\n| {to_functor := F1, seq := s1, pure := p1, seq_left := sl1, seq_right := sr1}\n {to_functor := F2, seq := s2, pure := p2, seq_left := sl2, seq_right := sr2} L1 L2 H1 H2 :=\nbegin\n have : @p1 = @p2, {funext α x, apply H1}, subst this,\n have : @s1 = @s2, {funext α β f x, apply H2}, subst this,\n cases L1, cases L2,\n have : F1 = F2,\n { resetI, apply functor.ext, intros,\n exact (L1_pure_seq_eq_map _ _).symm.trans (L2_pure_seq_eq_map _ _) },\n subst this,\n congr; funext α β x y,\n { exact (L1_seq_left_eq _ _).trans (L2_seq_left_eq _ _).symm },\n { exact (L1_seq_right_eq _ _).trans (L2_seq_right_eq _ _).symm }\nend\n\nend lemmas\n\ninstance : is_comm_applicative id :=\nby refine { .. }; intros; refl\n\nnamespace functor\nnamespace comp\n\nopen function (hiding comp)\nopen functor\n\nvariables {F : Type u → Type w} {G : Type v → Type u}\n\nvariables [applicative F] [applicative G]\n\nvariables [is_lawful_applicative F] [is_lawful_applicative G]\nvariables {α β γ : Type v}\n\nlemma map_pure (f : α → β) (x : α) : (f <$> pure x : comp F G β) = pure (f x) :=\ncomp.ext $ by simp\n\nlemma seq_pure (f : comp F G (α → β)) (x : α) :\n f <*> pure x = (λ g : α → β, g x) <$> f :=\ncomp.ext $ by simp [(∘)] with functor_norm\n\n\n\nlemma pure_seq_eq_map (f : α → β) (x : comp F G α) :\n pure f <*> x = f <$> x :=\ncomp.ext $ by simp [applicative.pure_seq_eq_map'] with functor_norm\n\ninstance : is_lawful_applicative (comp F G) :=\n{ pure_seq_eq_map := @comp.pure_seq_eq_map F G _ _ _ _,\n map_pure := @comp.map_pure F G _ _ _ _,\n seq_pure := @comp.seq_pure F G _ _ _ _,\n seq_assoc := @comp.seq_assoc F G _ _ _ _ }\n\ntheorem applicative_id_comp {F} [AF : applicative F] [LF : is_lawful_applicative F] :\n @comp.applicative id F _ _ = AF :=\n@applicative.ext F _ _ (@comp.is_lawful_applicative id F _ _ _ _) _\n (λ α x, rfl) (λ α β f x, rfl)\n\ntheorem applicative_comp_id {F} [AF : applicative F] [LF : is_lawful_applicative F] :\n @comp.applicative F id _ _ = AF :=\n@applicative.ext F _ _ (@comp.is_lawful_applicative F id _ _ _ _) _\n (λ α x, rfl) (λ α β f x, show id <$> f <*> x = f <*> x, by rw id_map)\n\nopen is_comm_applicative\n\ninstance {f : Type u → Type w} {g : Type v → Type u}\n [applicative f] [applicative g]\n [is_comm_applicative f] [is_comm_applicative g] :\n is_comm_applicative (comp f g) :=\nby { refine { .. @comp.is_lawful_applicative f g _ _ _ _, .. },\n intros, casesm* comp _ _ _, simp! [map,has_seq.seq] with functor_norm,\n rw [commutative_map],\n simp [comp.mk,flip,(∘)] with functor_norm,\n congr, funext, rw [commutative_map], congr }\n\nend comp\nend functor\n\nopen functor\n\n@[functor_norm]\nlemma comp.seq_mk {α β : Type w}\n {f : Type u → Type v} {g : Type w → Type u}\n [applicative f] [applicative g]\n (h : f (g (α → β))) (x : f (g α)) :\n comp.mk h <*> comp.mk x = comp.mk (has_seq.seq <$> h <*> x) := rfl\n\ninstance {α} [has_one α] [has_mul α] : applicative (const α) :=\n{ pure := λ β x, (1 : α),\n seq := λ β γ f x, (f * x : α) }\n\ninstance {α} [monoid α] : is_lawful_applicative (const α) :=\nby refine { .. }; intros; simp [mul_assoc, (<$>), (<*>), pure]\n\ninstance {α} [has_zero α] [has_add α] : applicative (add_const α) :=\n{ pure := λ β x, (0 : α),\n seq := λ β γ f x, (f + x : α) }\n\ninstance {α} [add_monoid α] : is_lawful_applicative (add_const α) :=\nby refine { .. }; intros; simp [add_assoc, (<$>), (<*>), pure]\n", "meta": {"author": "jjaassoonn", "repo": "projective_space", "sha": "11fe19fe9d7991a272e7a40be4b6ad9b0c10c7ce", "save_path": "github-repos/lean/jjaassoonn-projective_space", "path": "github-repos/lean/jjaassoonn-projective_space/projective_space-11fe19fe9d7991a272e7a40be4b6ad9b0c10c7ce/src/control/applicative.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4148988313272769, "lm_q2_score": 0.07263669983640322, "lm_q1q2_score": 0.030136881873593903}} {"text": "import Lean\nimport Lean.Data.Json.Basic\nimport Lean.Data.Json.FromToJson\nimport LeanCodePrompts.ParseJson\nimport LeanCodePrompts.Utils\nimport LeanCodePrompts.TeXPrompts\n\nopen Lean\n\ninitialize texCommandCache : IO.Ref (HashMap String String) ← do\n -- IO.println \"Initialising TeX Command cache...\"\n -- let js ← Json.parseFile <| ← reroutePath \"data/texcmds.json\"\n -- let l := js.map $ fun j => (j[0]!.getStr!, j[1]!.getStr!)\n let .obj js ← IO.ofExcept $ Json.parse $ ← IO.FS.readFile (← reroutePath \"data/full-tex.json\") | panic! \"Invalid JSON format\"\n let l : List (String × String) := js.fold (λ as s j => (s, j.getStr!) :: as) []\n IO.mkRef $ HashMap.ofList l\n\n/-- Replaces the TeX sequences in a string with their \n corresponding Unicode characters using the `texcmds` list. -/\ndef teXToUnicode (s : String) : IO String := do\n match s.splitOn \"\\\\\" with\n | [] => return s\n | h :: ls =>\n -- filtering instances of `\\\\\\\\`\n let ls' := ls.filter (· != \"\")\n let us ← ls'.mapM $ fun l => do\n let cmd := l.takeWhile (· ∉ teXDelimiters)\n let s ← findUnicodeReplacement cmd\n pure $ s ++ l.dropWhile (· ∉ teXDelimiters)\n \n return .join (h :: us)\n\n where\n findUnicodeReplacement (cmd : String) : IO String := do\n if let .some u :=\n (← texCommandCache.get).find? cmd then\n pure u else\n pure <| \"\\\\\" ++ cmd\n\n teXDelimiters := [' ', '_', '^', '{', '}', '[', ']', '(', ')']\n\n\nnamespace List\n\ndef alternate : List α → List α × List α\n | [] => ([], [])\n | a :: as =>\n match alternate as with\n | (odds, evens) => (a :: evens, odds)\n\ndef interleave : List α → List α → List α\n | [], bs => bs\n | as, [] => as\n | a :: as, b :: bs =>\n a :: b :: interleave as bs\n\ntheorem alternate_interleave : (l : List α) → \n let (odds, evens) := l.alternate\n .interleave odds evens = l\n | [] => rfl\n | [a] => rfl\n | a :: a' :: as => by\n dsimp only [alternate, interleave]\n congr\n apply alternate_interleave\n\n#eval [1, 2, 3, 4, 5, 6].alternate\n\nend List\n\n\ndef openAIKey : IO (Option String) := IO.getEnv \"OPENAI_API_KEY\"\n\n/-- Query open-ai with given prompt and parameters -/\n-- this is delibrately different from the one in `Translate.lean`\n-- this is to keep everything at the `IO` level without disturbing the rest of the code\ndef openAIQuery (prompt : String)\n (n : Nat := 1)\n (temp : JsonNumber := ⟨2, 1⟩)\n (stopTokens : Array String := #[\":=\", \"-/\"]) : IO Json := do\n\n let .some key ← openAIKey | panic! \"OPENAI_API_KEY not set\"\n \n let data := Json.mkObj [\n (\"model\", \"code-davinci-002\"), \n (\"prompt\", prompt), \n (\"temperature\", Json.num temp), \n (\"n\", n), \n (\"max_tokens\", 150), \n (\"stop\", Json.arr <| stopTokens |>.map Json.str)\n ] |>.pretty\n \n let out ← IO.Process.output {\n cmd:= \"curl\", \n args:= #[\"https://api.openai.com/v1/completions\",\n \"-X\", \"POST\",\n \"-H\", \"Authorization: Bearer \" ++ key,\n \"-H\", \"Content-Type: application/json\",\n \"--data\", data]}\n \n IO.ofExcept $ Json.parse out.stdout\n\ndef makePrompt (formula : String) : IO String := do\n\n let teXPromptsProcessed ← teXPrompts.mapM $ λ (teXFormula, leanFormula) => do\n return s!\"TeX: ${← teXToUnicode teXFormula}$\\nLean: `{leanFormula}`\\n\\n\"\n\n let promptPrefix := String.join teXPromptsProcessed.toList \n\n return s!\"{promptPrefix}TeX: ${formula}$\\nLean: `\"\n\n/-- Translates a string representing a TeX formula to the corresponding Lean code. -/\ndef teXToLean (s : String) : IO String := do\n let t ← teXToUnicode s\n -- needs a better heuristic for triggering Codex-based translation\n if t.contains '\\\\' then\n IO.println s!\"Translating with Codex: {t}\"\n let prompt ← makePrompt s\n let codexOutput ← openAIQuery prompt (stopTokens := #[\"$\", \"$$\", \"\\\\[\", \"\\n\"])\n let translation := codexOutput[\"choices\"]![0]![\"text\"]!.getStr!\n return s!\"`{translation}`\"\n else\n IO.println s!\"Translated via Unicode mapping: {t}\"\n return s!\"`{t}`\" \n\n/-- Extracts the TeX formulas within `$` or `$$` in the given string,\n translates them individually to Lean code, and then\n replaces them back with `\\`` (backticks). -/\ndef translateTeX : String → IO String :=\n translateTeXAux \"$$\"\n (translateTeXAux \"$\" \n (translateTeXAux \"`\"\n pure\n pure)\n teXToLean)\n teXToLean\n where\n /-- Splits a string according to the delimiter.\n The substrings in the odd positions are processed as text,\n while those in the even positions are processed as formulas. -/\n translateTeXAux (teXDelimiter : String) \n (modText : String → IO String) \n (modFormula : String → IO String) :\n String → IO String := fun s => do\n let (text, formulas) := s.splitOn teXDelimiter |>.alternate\n let text' ← text.mapM modText\n let formulas' ← formulas.mapM modFormula\n let s' := .interleave text' formulas'\n return .join s'", "meta": {"author": "siddhartha-gadgil", "repo": "LeanAide", "sha": "7862af73ee2f0be08b20fd3e4148e20bf4a81054", "save_path": "github-repos/lean/siddhartha-gadgil-LeanAide", "path": "github-repos/lean/siddhartha-gadgil-LeanAide/LeanAide-7862af73ee2f0be08b20fd3e4148e20bf4a81054/LeanCodePrompts/TexToUnicode.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42632159254749036, "lm_q2_score": 0.07055959667590904, "lm_q1q2_score": 0.030081079624382147}} {"text": "/-\nCopyright (c) 2018 Scott Morrison. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Scott Morrison, Mario Carneiro\n-/\nimport tactic.ext\n\nopen interactive\n\nnamespace tactic\n\n/-\nThis file defines a `chain` tactic, which takes a list of tactics,\nand exhaustively tries to apply them to the goals, until no tactic succeeds on any goal.\n\nAlong the way, it generates auxiliary declarations, in order to speed up elaboration time\nof the resulting (sometimes long!) proofs.\n\nThis tactic is used by the `tidy` tactic.\n-/\n\n-- α is the return type of our tactics. When `chain` is called by `tidy`, this is string,\n-- describing what that tactic did as an interactive tactic.\nvariable {α : Type}\n\ninductive tactic_script (α : Type) : Type\n| base : α → tactic_script\n| work (index : ℕ) (first : α) (later : list tactic_script) (closed : bool) : tactic_script\n\nmeta def tactic_script.to_string : tactic_script string → string\n| (tactic_script.base a) := a\n| (tactic_script.work n a l c) := \"work_on_goal \" ++ (to_string (n+1)) ++\n \" { \" ++ (\", \".intercalate (a :: l.map tactic_script.to_string)) ++ \" }\"\n\nmeta instance : has_to_string (tactic_script string) :=\n{ to_string := λ s, s.to_string }\n\nmeta instance tactic_script_unit_has_to_string : has_to_string (tactic_script unit) :=\n{ to_string := λ s, \"[chain tactic]\" }\n\nmeta def abstract_if_success (tac : expr → tactic α) (g : expr) : tactic α :=\ndo\n type ← infer_type g,\n is_lemma ← is_prop type,\n if is_lemma then -- there's no point making the abstraction, and indeed it's slower\n tac g\n else do\n m ← mk_meta_var type,\n a ← tac m,\n do\n { val ← instantiate_mvars m,\n guard (val.list_meta_vars = []),\n c ← new_aux_decl_name,\n gs ← get_goals,\n set_goals [g],\n add_aux_decl c type val ff >>= unify g,\n set_goals gs }\n <|> unify m g,\n return a\n\n/--\n`chain_many tac` recursively tries `tac` on all goals, working depth-first on generated subgoals,\nuntil it no longer succeeds on any goal. `chain_many` automatically makes auxiliary definitions.\n-/\nmeta mutual def chain_single, chain_many, chain_iter {α} (tac : tactic α)\nwith chain_single : expr → tactic (α × list (tactic_script α)) | g :=\ndo set_goals [g],\n a ← tac,\n l ← get_goals >>= chain_many,\n return (a, l)\nwith chain_many : list expr → tactic (list (tactic_script α))\n| [] := return []\n| [g] := do\n{ (a, l) ← chain_single g,\n return (tactic_script.base a :: l) } <|> return []\n| gs := chain_iter gs []\nwith chain_iter : list expr → list expr → tactic (list (tactic_script α))\n| [] _ := return []\n| (g :: later_goals) stuck_goals := do\n{ (a, l) ← abstract_if_success chain_single g,\n new_goals ← get_goals,\n let w := tactic_script.work stuck_goals.length a l (new_goals = []),\n let current_goals := stuck_goals.reverse ++ new_goals ++ later_goals,\n set_goals current_goals, -- we keep the goals up to date, so they are correct at the end\n l' ← chain_many current_goals,\n return (w :: l') } <|> chain_iter later_goals (g :: stuck_goals)\n\nmeta def chain_core {α : Type} [has_to_string (tactic_script α)] (tactics : list (tactic α)) :\n tactic (list string) :=\ndo results ← (get_goals >>= chain_many (first tactics)),\n when results.empty (fail \"`chain` tactic made no progress\"),\n return (results.map to_string)\n\nvariables [has_to_string (tactic_script α)] [has_to_format α]\n\ndeclare_trace chain\n\nmeta def trace_output (t : tactic α) : tactic α :=\ndo tgt ← target,\n r ← t,\n name ← decl_name,\n trace format!\"`chain` successfully applied a tactic during elaboration of {name}:\",\n tgt ← pp tgt,\n trace format!\"previous target: {tgt}\",\n trace format!\"tactic result: {r}\",\n tgt ← try_core target,\n tgt ← match tgt with\n | (some tgt) := pp tgt\n | none := return \"no goals\"\n end,\n trace format!\"new target: {tgt}\",\n pure r\n\nmeta def chain (tactics : list (tactic α)) : tactic (list string) :=\nchain_core\n (if is_trace_enabled_for `chain then (tactics.map trace_output) else tactics)\n\nend tactic\n", "meta": {"author": "leanprover-community", "repo": "mathlib", "sha": "5e526d18cea33550268dcbbddcb822d5cde40654", "save_path": "github-repos/lean/leanprover-community-mathlib", "path": "github-repos/lean/leanprover-community-mathlib/mathlib-5e526d18cea33550268dcbbddcb822d5cde40654/src/tactic/chain.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4263215925474903, "lm_q2_score": 0.07055959472144475, "lm_q1q2_score": 0.03008107879115182}} {"text": "/-\nCopyright (c) 2019 Minchao Wu. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Minchao Wu, Mario Carneiro\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.default\nimport Mathlib.computability.halting\nimport Mathlib.PostPort\n\nuniverses u_1 u_2 u_3 u v \n\nnamespace Mathlib\n\n/-!\n# Strong reducibility and degrees.\n\nThis file defines the notions of computable many-one reduction and one-one\nreduction between sets, and shows that the corresponding degrees form a\nsemilattice.\n\n## Notations\n\nThis file uses the local notation `⊕'` for `sum.elim` to denote the disjoint union of two degrees.\n\n## References\n\n* [Robert Soare, *Recursively enumerable sets and degrees*][soare1987]\n\n## Tags\n\ncomputability, reducibility, reduction\n-/\n\n/--\n`p` is many-one reducible to `q` if there is a computable function translating questions about `p`\nto questions about `q`.\n-/\ndef many_one_reducible {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β] (p : α → Prop) (q : β → Prop) :=\n ∃ (f : α → β), computable f ∧ ∀ (a : α), p a ↔ q (f a)\n\ninfixl:1000 \" ≤₀ \" => Mathlib.many_one_reducible\n\ntheorem many_one_reducible.mk {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β] {f : α → β} (q : β → Prop) (h : computable f) : (fun (a : α) => q (f a)) ≤₀ q :=\n Exists.intro f { left := h, right := fun (a : α) => iff.rfl }\n\ntheorem many_one_reducible_refl {α : Type u_1} [primcodable α] (p : α → Prop) : p ≤₀ p := sorry\n\ntheorem many_one_reducible.trans {α : Type u_1} {β : Type u_2} {γ : Type u_3} [primcodable α] [primcodable β] [primcodable γ] {p : α → Prop} {q : β → Prop} {r : γ → Prop} : p ≤₀ q → q ≤₀ r → p ≤₀ r := sorry\n\ntheorem reflexive_many_one_reducible {α : Type u_1} [primcodable α] : reflexive many_one_reducible :=\n many_one_reducible_refl\n\ntheorem transitive_many_one_reducible {α : Type u_1} [primcodable α] : transitive many_one_reducible :=\n fun (p q r : α → Prop) => many_one_reducible.trans\n\n/--\n`p` is one-one reducible to `q` if there is an injective computable function translating questions\nabout `p` to questions about `q`.\n-/\ndef one_one_reducible {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β] (p : α → Prop) (q : β → Prop) :=\n ∃ (f : α → β), computable f ∧ function.injective f ∧ ∀ (a : α), p a ↔ q (f a)\n\ninfixl:1000 \" ≤₁ \" => Mathlib.one_one_reducible\n\ntheorem one_one_reducible.mk {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β] {f : α → β} (q : β → Prop) (h : computable f) (i : function.injective f) : (fun (a : α) => q (f a)) ≤₁ q :=\n Exists.intro f { left := h, right := { left := i, right := fun (a : α) => iff.rfl } }\n\ntheorem one_one_reducible_refl {α : Type u_1} [primcodable α] (p : α → Prop) : p ≤₁ p := sorry\n\ntheorem one_one_reducible.trans {α : Type u_1} {β : Type u_2} {γ : Type u_3} [primcodable α] [primcodable β] [primcodable γ] {p : α → Prop} {q : β → Prop} {r : γ → Prop} : p ≤₁ q → q ≤₁ r → p ≤₁ r := sorry\n\ntheorem one_one_reducible.to_many_one {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β] {p : α → Prop} {q : β → Prop} : p ≤₁ q → p ≤₀ q := sorry\n\ntheorem one_one_reducible.of_equiv {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β] {e : α ≃ β} (q : β → Prop) (h : computable ⇑e) : (q ∘ ⇑e) ≤₁ q :=\n one_one_reducible.mk q h (equiv.injective e)\n\ntheorem one_one_reducible.of_equiv_symm {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β] {e : α ≃ β} (q : β → Prop) (h : computable ⇑(equiv.symm e)) : q ≤₁ (q ∘ ⇑e) := sorry\n\ntheorem reflexive_one_one_reducible {α : Type u_1} [primcodable α] : reflexive one_one_reducible :=\n one_one_reducible_refl\n\ntheorem transitive_one_one_reducible {α : Type u_1} [primcodable α] : transitive one_one_reducible :=\n fun (p q r : α → Prop) => one_one_reducible.trans\n\nnamespace computable_pred\n\n\ntheorem computable_of_many_one_reducible {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β] {p : α → Prop} {q : β → Prop} (h₁ : p ≤₀ q) (h₂ : computable_pred q) : computable_pred p := sorry\n\ntheorem computable_of_one_one_reducible {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β] {p : α → Prop} {q : β → Prop} (h : p ≤₁ q) : computable_pred q → computable_pred p :=\n computable_of_many_one_reducible (one_one_reducible.to_many_one h)\n\nend computable_pred\n\n\n/-- `p` and `q` are many-one equivalent if each one is many-one reducible to the other. -/\ndef many_one_equiv {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β] (p : α → Prop) (q : β → Prop) :=\n p ≤₀ q ∧ q ≤₀ p\n\n/-- `p` and `q` are one-one equivalent if each one is one-one reducible to the other. -/\ndef one_one_equiv {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β] (p : α → Prop) (q : β → Prop) :=\n p ≤₁ q ∧ q ≤₁ p\n\ntheorem many_one_equiv_refl {α : Type u_1} [primcodable α] (p : α → Prop) : many_one_equiv p p :=\n { left := many_one_reducible_refl p, right := many_one_reducible_refl p }\n\ntheorem many_one_equiv.symm {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β] {p : α → Prop} {q : β → Prop} : many_one_equiv p q → many_one_equiv q p :=\n and.swap\n\ntheorem many_one_equiv.trans {α : Type u_1} {β : Type u_2} {γ : Type u_3} [primcodable α] [primcodable β] [primcodable γ] {p : α → Prop} {q : β → Prop} {r : γ → Prop} : many_one_equiv p q → many_one_equiv q r → many_one_equiv p r := sorry\n\ntheorem equivalence_of_many_one_equiv {α : Type u_1} [primcodable α] : equivalence many_one_equiv :=\n { left := many_one_equiv_refl,\n right :=\n { left := fun (x y : α → Prop) => many_one_equiv.symm, right := fun (x y z : α → Prop) => many_one_equiv.trans } }\n\ntheorem one_one_equiv_refl {α : Type u_1} [primcodable α] (p : α → Prop) : one_one_equiv p p :=\n { left := one_one_reducible_refl p, right := one_one_reducible_refl p }\n\ntheorem one_one_equiv.symm {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β] {p : α → Prop} {q : β → Prop} : one_one_equiv p q → one_one_equiv q p :=\n and.swap\n\ntheorem one_one_equiv.trans {α : Type u_1} {β : Type u_2} {γ : Type u_3} [primcodable α] [primcodable β] [primcodable γ] {p : α → Prop} {q : β → Prop} {r : γ → Prop} : one_one_equiv p q → one_one_equiv q r → one_one_equiv p r := sorry\n\ntheorem equivalence_of_one_one_equiv {α : Type u_1} [primcodable α] : equivalence one_one_equiv :=\n { left := one_one_equiv_refl,\n right :=\n { left := fun (x y : α → Prop) => one_one_equiv.symm, right := fun (x y z : α → Prop) => one_one_equiv.trans } }\n\ntheorem one_one_equiv.to_many_one {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β] {p : α → Prop} {q : β → Prop} : one_one_equiv p q → many_one_equiv p q := sorry\n\n/-- a computable bijection -/\ndef equiv.computable {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β] (e : α ≃ β) :=\n computable ⇑e ∧ computable ⇑(equiv.symm e)\n\ntheorem equiv.computable.symm {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β] {e : α ≃ β} : equiv.computable e → equiv.computable (equiv.symm e) :=\n and.swap\n\ntheorem equiv.computable.trans {α : Type u_1} {β : Type u_2} {γ : Type u_3} [primcodable α] [primcodable β] [primcodable γ] {e₁ : α ≃ β} {e₂ : β ≃ γ} : equiv.computable e₁ → equiv.computable e₂ → equiv.computable (equiv.trans e₁ e₂) := sorry\n\ntheorem computable.eqv (α : Type u_1) [denumerable α] : equiv.computable (denumerable.eqv α) :=\n { left := computable.encode, right := computable.of_nat α }\n\ntheorem computable.equiv₂ (α : Type u_1) (β : Type u_2) [denumerable α] [denumerable β] : equiv.computable (denumerable.equiv₂ α β) :=\n equiv.computable.trans (computable.eqv α) (equiv.computable.symm (computable.eqv β))\n\ntheorem one_one_equiv.of_equiv {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β] {e : α ≃ β} (h : equiv.computable e) {p : β → Prop} : one_one_equiv (p ∘ ⇑e) p :=\n { left := one_one_reducible.of_equiv p (and.left h), right := one_one_reducible.of_equiv_symm p (and.right h) }\n\ntheorem many_one_equiv.of_equiv {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β] {e : α ≃ β} (h : equiv.computable e) {p : β → Prop} : many_one_equiv (p ∘ ⇑e) p :=\n one_one_equiv.to_many_one (one_one_equiv.of_equiv h)\n\ntheorem many_one_equiv.le_congr_left {α : Type u_1} {β : Type u_2} {γ : Type u_3} [primcodable α] [primcodable β] [primcodable γ] {p : α → Prop} {q : β → Prop} {r : γ → Prop} (h : many_one_equiv p q) : p ≤₀ r ↔ q ≤₀ r :=\n { mp := many_one_reducible.trans (and.right h), mpr := many_one_reducible.trans (and.left h) }\n\ntheorem many_one_equiv.le_congr_right {α : Type u_1} {β : Type u_2} {γ : Type u_3} [primcodable α] [primcodable β] [primcodable γ] {p : α → Prop} {q : β → Prop} {r : γ → Prop} (h : many_one_equiv q r) : p ≤₀ q ↔ p ≤₀ r :=\n { mp := fun (h' : p ≤₀ q) => many_one_reducible.trans h' (and.left h),\n mpr := fun (h' : p ≤₀ r) => many_one_reducible.trans h' (and.right h) }\n\ntheorem one_one_equiv.le_congr_left {α : Type u_1} {β : Type u_2} {γ : Type u_3} [primcodable α] [primcodable β] [primcodable γ] {p : α → Prop} {q : β → Prop} {r : γ → Prop} (h : one_one_equiv p q) : p ≤₁ r ↔ q ≤₁ r :=\n { mp := one_one_reducible.trans (and.right h), mpr := one_one_reducible.trans (and.left h) }\n\ntheorem one_one_equiv.le_congr_right {α : Type u_1} {β : Type u_2} {γ : Type u_3} [primcodable α] [primcodable β] [primcodable γ] {p : α → Prop} {q : β → Prop} {r : γ → Prop} (h : one_one_equiv q r) : p ≤₁ q ↔ p ≤₁ r :=\n { mp := fun (h' : p ≤₁ q) => one_one_reducible.trans h' (and.left h),\n mpr := fun (h' : p ≤₁ r) => one_one_reducible.trans h' (and.right h) }\n\ntheorem many_one_equiv.congr_left {α : Type u_1} {β : Type u_2} {γ : Type u_3} [primcodable α] [primcodable β] [primcodable γ] {p : α → Prop} {q : β → Prop} {r : γ → Prop} (h : many_one_equiv p q) : many_one_equiv p r ↔ many_one_equiv q r :=\n and_congr (many_one_equiv.le_congr_left h) (many_one_equiv.le_congr_right h)\n\ntheorem many_one_equiv.congr_right {α : Type u_1} {β : Type u_2} {γ : Type u_3} [primcodable α] [primcodable β] [primcodable γ] {p : α → Prop} {q : β → Prop} {r : γ → Prop} (h : many_one_equiv q r) : many_one_equiv p q ↔ many_one_equiv p r :=\n and_congr (many_one_equiv.le_congr_right h) (many_one_equiv.le_congr_left h)\n\ntheorem one_one_equiv.congr_left {α : Type u_1} {β : Type u_2} {γ : Type u_3} [primcodable α] [primcodable β] [primcodable γ] {p : α → Prop} {q : β → Prop} {r : γ → Prop} (h : one_one_equiv p q) : one_one_equiv p r ↔ one_one_equiv q r :=\n and_congr (one_one_equiv.le_congr_left h) (one_one_equiv.le_congr_right h)\n\ntheorem one_one_equiv.congr_right {α : Type u_1} {β : Type u_2} {γ : Type u_3} [primcodable α] [primcodable β] [primcodable γ] {p : α → Prop} {q : β → Prop} {r : γ → Prop} (h : one_one_equiv q r) : one_one_equiv p q ↔ one_one_equiv p r :=\n and_congr (one_one_equiv.le_congr_right h) (one_one_equiv.le_congr_left h)\n\n@[simp] theorem ulower.down_computable {α : Type u_1} [primcodable α] : equiv.computable (ulower.equiv α) :=\n { left := primrec.to_comp primrec.ulower_down, right := primrec.to_comp primrec.ulower_up }\n\ntheorem many_one_equiv_up {α : Type u_1} [primcodable α] {p : α → Prop} : many_one_equiv (p ∘ ulower.up) p :=\n many_one_equiv.of_equiv (equiv.computable.symm ulower.down_computable)\n\ntheorem one_one_reducible.disjoin_left {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β] {p : α → Prop} {q : β → Prop} : p ≤₁ sum.elim p q :=\n Exists.intro sum.inl\n { left := computable.sum_inl,\n right := { left := fun (x y : α) => iff.mp sum.inl.inj_iff, right := fun (a : α) => iff.rfl } }\n\ntheorem one_one_reducible.disjoin_right {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β] {p : α → Prop} {q : β → Prop} : q ≤₁ sum.elim p q :=\n Exists.intro sum.inr\n { left := computable.sum_inr,\n right := { left := fun (x y : β) => iff.mp sum.inr.inj_iff, right := fun (a : β) => iff.rfl } }\n\ntheorem disjoin_many_one_reducible {α : Type u_1} {β : Type u_2} {γ : Type u_3} [primcodable α] [primcodable β] [primcodable γ] {p : α → Prop} {q : β → Prop} {r : γ → Prop} : p ≤₀ r → q ≤₀ r → sum.elim p q ≤₀ r := sorry\n\ntheorem disjoin_le {α : Type u_1} {β : Type u_2} {γ : Type u_3} [primcodable α] [primcodable β] [primcodable γ] {p : α → Prop} {q : β → Prop} {r : γ → Prop} : sum.elim p q ≤₀ r ↔ p ≤₀ r ∧ q ≤₀ r := sorry\n\n/--\nComputable and injective mapping of predicates to sets of natural numbers.\n-/\ndef to_nat {α : Type u} [primcodable α] [Inhabited α] (p : set α) : set ℕ :=\n set_of fun (n : ℕ) => p (option.get_or_else (encodable.decode α n) Inhabited.default)\n\n@[simp] theorem to_nat_many_one_reducible {α : Type u} [primcodable α] [Inhabited α] {p : set α} : to_nat p ≤₀ p :=\n Exists.intro (fun (n : ℕ) => option.get_or_else (encodable.decode α n) Inhabited.default)\n { left := computable.option_get_or_else computable.decode (computable.const Inhabited.default),\n right := fun (_x : ℕ) => iff.rfl }\n\n@[simp] theorem many_one_reducible_to_nat {α : Type u} [primcodable α] [Inhabited α] {p : set α} : p ≤₀ to_nat p := sorry\n\n@[simp] theorem many_one_reducible_to_nat_to_nat {α : Type u} [primcodable α] [Inhabited α] {β : Type v} [primcodable β] [Inhabited β] {p : set α} {q : set β} : to_nat p ≤₀ to_nat q ↔ p ≤₀ q := sorry\n\n@[simp] theorem to_nat_many_one_equiv {α : Type u} [primcodable α] [Inhabited α] {p : set α} : many_one_equiv (to_nat p) p := sorry\n\n@[simp] theorem many_one_equiv_to_nat {α : Type u} [primcodable α] [Inhabited α] {β : Type v} [primcodable β] [Inhabited β] (p : set α) (q : set β) : many_one_equiv (to_nat p) (to_nat q) ↔ many_one_equiv p q := sorry\n\n/-- A many-one degree is an equivalence class of sets up to many-one equivalence. -/\ndef many_one_degree :=\n quotient (setoid.mk many_one_equiv sorry)\n\nnamespace many_one_degree\n\n\n/-- The many-one degree of a set on a primcodable type. -/\ndef of {α : Type u} [primcodable α] [Inhabited α] (p : α → Prop) : many_one_degree :=\n quotient.mk' (to_nat p)\n\nprotected theorem ind_on {C : many_one_degree → Prop} (d : many_one_degree) (h : ∀ (p : set ℕ), C (of p)) : C d :=\n quotient.induction_on' d h\n\n/--\nLifts a function on sets of natural numbers to many-one degrees.\n-/\nprotected def lift_on {φ : Sort u_1} (d : many_one_degree) (f : set ℕ → φ) (h : ∀ (p q : ℕ → Prop), many_one_equiv p q → f p = f q) : φ :=\n quotient.lift_on' d f h\n\n@[simp] protected theorem lift_on_eq {φ : Sort u_1} (p : set ℕ) (f : set ℕ → φ) (h : ∀ (p q : ℕ → Prop), many_one_equiv p q → f p = f q) : many_one_degree.lift_on (of p) f h = f p :=\n rfl\n\n/--\nLifts a binary function on sets of natural numbers to many-one degrees.\n-/\n@[simp] protected def lift_on₂ {φ : Sort u_1} (d₁ : many_one_degree) (d₂ : many_one_degree) (f : set ℕ → set ℕ → φ) (h : ∀ (p₁ p₂ q₁ q₂ : ℕ → Prop), many_one_equiv p₁ p₂ → many_one_equiv q₁ q₂ → f p₁ q₁ = f p₂ q₂) : φ :=\n many_one_degree.lift_on d₁ (fun (p : set ℕ) => many_one_degree.lift_on d₂ (f p) sorry) sorry\n\n@[simp] protected theorem lift_on₂_eq {φ : Sort u_1} (p : set ℕ) (q : set ℕ) (f : set ℕ → set ℕ → φ) (h : ∀ (p₁ p₂ q₁ q₂ : ℕ → Prop), many_one_equiv p₁ p₂ → many_one_equiv q₁ q₂ → f p₁ q₁ = f p₂ q₂) : many_one_degree.lift_on₂ (of p) (of q) f h = f p q :=\n rfl\n\n@[simp] theorem of_eq_of {α : Type u} [primcodable α] [Inhabited α] {β : Type v} [primcodable β] [Inhabited β] {p : α → Prop} {q : β → Prop} : of p = of q ↔ many_one_equiv p q := sorry\n\nprotected instance inhabited : Inhabited many_one_degree :=\n { default := of ∅ }\n\n/--\nFor many-one degrees `d₁` and `d₂`, `d₁ ≤ d₂` if the sets in `d₁` are many-one reducible to the\nsets in `d₂`.\n-/\nprotected instance has_le : HasLessEq many_one_degree :=\n { LessEq := fun (d₁ d₂ : many_one_degree) => many_one_degree.lift_on₂ d₁ d₂ many_one_reducible sorry }\n\n@[simp] theorem of_le_of {α : Type u} [primcodable α] [Inhabited α] {β : Type v} [primcodable β] [Inhabited β] {p : α → Prop} {q : β → Prop} : of p ≤ of q ↔ p ≤₀ q :=\n many_one_reducible_to_nat_to_nat\n\nprotected instance partial_order : partial_order many_one_degree :=\n partial_order.mk LessEq (preorder.lt._default LessEq) le_refl sorry sorry\n\n/-- The join of two degrees, induced by the disjoint union of two underlying sets. -/\nprotected instance has_add : Add many_one_degree :=\n { add :=\n fun (d₁ d₂ : many_one_degree) => many_one_degree.lift_on₂ d₁ d₂ (fun (a b : set ℕ) => of (sum.elim a b)) sorry }\n\n@[simp] theorem add_of {α : Type u} [primcodable α] [Inhabited α] {β : Type v} [primcodable β] [Inhabited β] (p : set α) (q : set β) : of (sum.elim p q) = of p + of q := sorry\n\n@[simp] protected theorem add_le {d₁ : many_one_degree} {d₂ : many_one_degree} {d₃ : many_one_degree} : d₁ + d₂ ≤ d₃ ↔ d₁ ≤ d₃ ∧ d₂ ≤ d₃ := sorry\n\n@[simp] protected theorem le_add_left (d₁ : many_one_degree) (d₂ : many_one_degree) : d₁ ≤ d₁ + d₂ :=\n and.left (iff.mp many_one_degree.add_le (le_refl (d₁ + d₂)))\n\n@[simp] protected theorem le_add_right (d₁ : many_one_degree) (d₂ : many_one_degree) : d₂ ≤ d₁ + d₂ :=\n and.right (iff.mp many_one_degree.add_le (le_refl (d₁ + d₂)))\n\nprotected instance semilattice_sup : semilattice_sup many_one_degree :=\n semilattice_sup.mk Add.add partial_order.le partial_order.lt partial_order.le_refl partial_order.le_trans\n partial_order.le_antisymm many_one_degree.le_add_left many_one_degree.le_add_right sorry\n\n", "meta": {"author": "AurelienSaue", "repo": "Mathlib4_auto", "sha": "590df64109b08190abe22358fabc3eae000943f2", "save_path": "github-repos/lean/AurelienSaue-Mathlib4_auto", "path": "github-repos/lean/AurelienSaue-Mathlib4_auto/Mathlib4_auto-590df64109b08190abe22358fabc3eae000943f2/Mathlib/computability/reduce.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4378234991142019, "lm_q2_score": 0.06853749826409475, "lm_q1q2_score": 0.0300073273105195}} {"text": "/-\nCopyright (c) 2021 Scott Morrison. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Scott Morrison, David Renshaw\n-/\nimport Lean.Meta.Tactic.Apply\nimport Lean.Elab.Tactic.Basic\nimport Mathlib.Tactic.Core\nimport Mathlib.Lean.LocalContext\nimport Mathlib.Tactic.Relation.Symm\nimport Mathlib.Control.Basic\nimport Mathlib.Data.Sum.Basic\nimport Mathlib.Tactic.LabelAttr\n\n/-!\nA work-in-progress replacement for Lean3's `solve_by_elim` tactic.\nWe'll gradually bring it up to feature parity.\n-/\n\nopen Lean Meta Elab Tactic\n\n/-- Visualize an `Except` using a checkmark or a cross. -/\ndef exceptEmoji : Except ε α → String\n | .error _ => crossEmoji\n | .ok _ => checkEmoji\n\nnamespace Lean.MVarId\n\n/--\n`applyFirst lemmas cont goal` will try to apply one of the `lemmas` to the goal `goal`,\nand then call `cont` on the resulting `List MVarId` of subgoals.\n\nIt returns the result from `cont` for the first such lemma for which\nboth the `apply` and the call to `cont` succeed.\n\n``applyFirst (trace := `name)`` will construct trace nodes for ``name` indicating which\ncalls to `apply` succeeded or failed.\n-/\n-- Because the operation of this function via a continuation is fairly specific to `solve_by_elim`,\n-- we keep it here rather than moving it into `Mathlib/Lean/`.\ndef applyFirst (cfg : ApplyConfig := {}) (transparency : TransparencyMode := .default)\n (trace : Name := .anonymous) (lemmas : List Expr) (cont : List MVarId → MetaM α)\n (g : MVarId) : MetaM α :=\n lemmas.firstM fun e =>\n withTraceNode trace (return m!\"{exceptEmoji ·} trying to apply: {e}\") do\n let goals ← withTransparency transparency (g.apply e cfg)\n -- When we call `apply` interactively, `Lean.Elab.Tactic.evalApplyLikeTactic`\n -- deals with closing new typeclass goals by calling\n -- `Lean.Elab.Term.synthesizeSyntheticMVarsNoPostponing`.\n -- It seems we can't reuse that machinery down here in `MetaM`,\n -- so we just settle for trying to close each subgoal using `inferInstance`.\n cont (← goals.filterM fun g => try g.inferInstance; pure false catch _ => pure true)\n\nend Lean.MVarId\n\ninitialize registerTraceClass `Meta.Tactic.solveByElim\n\nnamespace Mathlib.Tactic.SolveByElim\n\n/--\nConfiguration structure to control the behaviour of `solve_by_elim`:\n* control the maximum depth and behaviour (fail or return subgoals) at the maximum depth,\n* whether to use `symm` on hypotheses and `exfalso` on the goal as needed,\n* and hooks allowing\n * modifying intermediate goals,\n * returning goals as subgoals, and\n * discharging subgoals.\n-/\nstructure Config extends ApplyConfig where\n /-- Maximum recursion depth. -/\n maxDepth : Nat := 6\n /-- If `failAtDepth`, then `solve_by_elim` will fail (and backtrack) upon reaching the max depth.\n Otherwise, upon reaching the max depth, all remaining goals will be returned.\n (defaults to `true`) -/\n failAtMaxDepth : Bool := true\n /-- Transparency mode for calls to `apply`. -/\n transparency : TransparencyMode := .default\n /-- Also use symmetric versions (via `@[symm]`) of local hypotheses. -/\n symm : Bool := true\n /-- Try proving the goal via `exfalso` if `solve_by_elim` otherwise fails.\n This is only used when operating on a single goal. -/\n exfalso : Bool := true\n /-- An arbitrary procedure which can be used to modify the list of goals\n before each attempt to apply a lemma.\n Called as `proc goals curr`, where `goals` are the original goals for `solve_by_elim`,\n and `curr` are the current goals.\n Returning `some l` will replace the current goals with `l` and recurse\n (consuming one step of maximum depth).\n Returning `none` will proceed to applying lemmas without changing goals.\n Failure will cause backtracking.\n (defaults to `none`) -/\n proc : List MVarId → List MVarId → MetaM (Option (List MVarId)) := fun _ _ => pure none\n /-- If `suspend g`, then we do not attempt to apply any further lemmas,\n but return `g` as a new subgoal. (defaults to `false`) -/\n suspend : MVarId → MetaM Bool := fun _ => pure false\n /-- `discharge g` is called on goals for which no lemmas apply.\n If `none` we return `g` as a new subgoal.\n If `some l`, we replace `g` by `l` in the list of active goals, and recurse.\n If failure, we backtrack. (defaults to failure) -/\n discharge : MVarId → MetaM (Option (List MVarId)) := fun _ => failure\n\n/-- The default `maxDepth` for `apply_rules` is higher. -/\nstructure ApplyRulesConfig extends Config where\n maxDepth := 50\n\n/--\nAllow elaboration of `Config` arguments to tactics.\n-/\ndeclare_config_elab elabConfig Config\n\n/--\nAllow elaboration of `ApplyRulesConfig` arguments to tactics.\n-/\ndeclare_config_elab elabApplyRulesConfig ApplyRulesConfig\n\nnamespace Config\n\n/-- Create or modify a `Config` which allows a class of goals to be returned as subgoals. -/\ndef accept (cfg : Config := {}) (test : MVarId → MetaM Bool) : Config :=\n{ cfg with\n discharge := fun g => do\n if (← test g) then\n pure none\n else\n cfg.discharge g }\n\n/-- Create or modify a `Config` which does no backtracking. -/\ndef noBackTracking (cfg : Config := {}) : Config := cfg.accept fun _ => pure true\n\n/--\nCreate or modify a `Config` which runs a tactic on the main goal.\nIf that tactic fails, fall back to the `proc` behaviour of `cfg`.\n-/\ndef mainGoalProc (cfg : Config := {}) (proc : MVarId → MetaM (List MVarId)) : Config :=\n{ cfg with\n proc := fun orig goals => match goals with\n | [] => pure none\n | g :: gs => try\n return (← proc g) ++ gs\n catch _ => cfg.proc orig goals }\n\n/-- Create or modify a `Config` which calls `intro` on each goal before applying lemmas. -/\ndef intros (cfg : Config := {}) : Config :=\n mainGoalProc cfg fun g => do pure [(← g.intro1P).2]\n\n/--\nCreate or modify a `Config` which rejects branches for which `test`,\napplied to the instantiations of the original goals, fails or returns `false`.\n-/\ndef testPartialSolutions (cfg : Config := {}) (test : List Expr → MetaM Bool) : Config :=\n{ cfg with\n proc := fun orig goals => do\n let .true ← test (← orig.mapM fun m => m.withContext do instantiateMVars (.mvar m)) | failure\n cfg.proc orig goals }\n\n/--\nCreate or modify a `Config` which rejects complete solutions for which `test`,\napplied to the instantiations of the original goals, fails or returns `false`.\n-/\ndef testSolutions (cfg : Config := {}) (test : List Expr → MetaM Bool) : Config :=\n cfg.testPartialSolutions fun sols => do\n if sols.any Expr.hasMVar then\n pure true\n else\n test sols\n\n/--\nCreate or modify a `Config` which only accept solutions\nfor which every expression in `use` appears as a subexpression.\n-/\ndef requireUsingAll (cfg : Config := {}) (use : List Expr) : Config :=\n cfg.testSolutions fun sols => do\n pure <| use.all fun e => sols.any fun s => e.occurs s\n\nend Config\n\n/--\nElaborate a list of lemmas and local context.\nSee `mkAssumptionSet` for an explanation of why this is needed.\n-/\ndef elabContextLemmas (g : MVarId) (lemmas : List (TermElabM Expr)) (ctx : TermElabM (List Expr)) :\n MetaM (List Expr) := do\n g.withContext (Elab.Term.TermElabM.run' do pure ((← lemmas.mapM id) ++ (← ctx)))\n\n/--\nSolve a collection of goals by repeatedly applying lemmas, backtracking as necessary.\n\nArguments:\n* `cfg : Config` additional configuration options\n (options for `apply`, maximum depth, and custom flow control)\n* `lemmas : List (TermElabM Expr)` lemmas to apply.\n These are thunks in `TermElabM` to avoid stuck metavariables.\n* `ctx : TermElabM (List Expr)` monadic function returning the local hypotheses to use.\n* `goals : List MVarId` the initial list of goals for `solveByElim`\n\nReturns a list of suspended goals, if it succeeded on all other subgoals.\nBy default `cfg.suspend` is `false,` `cfg.discharge` fails, and `cfg.failAtMaxDepth` is `true`,\nand so the returned list is always empty.\nCustom wrappers (e.g. `apply_assumption` and `apply_rules`) may modify this behaviour.\n-/\ndef solveByElim (cfg : Config) (lemmas : List (TermElabM Expr)) (ctx : TermElabM (List Expr))\n (goals : List MVarId) : MetaM (List MVarId) := do\n -- We handle `cfg.symm` by saturating hypotheses of all goals using `symm`.\n -- Implementation note:\n -- (We used to apply `symm` all throughout the `solve_by_elim` stage.)\n -- I initially reproduced the mathlib3 approach, but it had bad performance so switched to this.\n let goals ← if cfg.symm then\n goals.mapM fun g => g.symmSaturate\n else\n pure goals\n\n -- Implementation note: as with `cfg.symm`, this is different from the mathlib3 approach,\n -- for (not as bad) performance reasons.\n match cfg.exfalso, goals with\n | true, [g] => try\n run cfg.maxDepth [g] []\n catch _ => do\n withTraceNode `Meta.Tactic.solveByElim\n (fun _ => return m!\"⏮️ starting over using `exfalso`\") do\n let g ← g.exfalso\n run cfg.maxDepth [g] []\n | _, _ =>\n run cfg.maxDepth goals []\n where\n /--\n * `n : Nat` steps remaining.\n * `curr : List MVarId` the current list of unsolved goals.\n * `acc : List MVarId` a list of \"suspended\" goals, which will be returned as subgoals.\n -/\n run (n : Nat) (curr acc : List MVarId) : MetaM (List MVarId) := do\n match n with\n | 0 => do\n -- We're out of fuel.\n if cfg.failAtMaxDepth then\n throwError \"solve_by_elim exceeded the recursion limit\"\n else\n -- Before returning the goals, we run `cfg.proc` one last time.\n let curr := acc.reverse ++ curr\n return (← cfg.proc goals curr).getD curr\n | n + 1 => do\n -- First, run `cfg.proc`, to see if it wants to modify the goals.\n match ← cfg.proc goals curr with\n | some curr' => run n curr' acc\n | none =>\n match curr with\n -- If there are no active goals, return the accumulated goals.\n | [] => return acc.reverse\n | g :: gs =>\n -- Discard any goals which have already been assigned.\n if ← g.isAssigned then\n run (n+1) gs acc\n else\n withTraceNode `Meta.Tactic.solveByElim\n -- Note: the `addMessageContextFull` ensures we show the goal using the mvar context before\n -- the `do` block below runs, potentially unifying mvars in the goal.\n (return m!\"{exceptEmoji ·} working on: {← addMessageContextFull g}\")\n do\n -- Check if we should suspend the search here:\n if (← cfg.suspend g) then\n withTraceNode `Meta.Tactic.solveByElim\n (fun _ => return m!\"⏸️ suspending search and returning as subgoal\") do\n run (n+1) gs (g :: acc)\n else\n let es ← elabContextLemmas g lemmas ctx\n try\n -- We attempt to find an expression which can be applied,\n -- and for which all resulting sub-goals can be discharged using `solveByElim n`.\n g.applyFirst cfg.toApplyConfig cfg.transparency `Meta.Tactic.solveByElim es fun res =>\n run n (res ++ gs) acc\n catch _ =>\n -- No lemmas could be applied:\n match (← cfg.discharge g) with\n | none => (withTraceNode `Meta.Tactic.solveByElim\n (fun _ => return m!\"⏭️ deemed acceptable, returning as subgoal\") do\n run (n+1) gs (g :: acc))\n | some l => (withTraceNode `Meta.Tactic.solveByElim\n (fun _ => return m!\"⏬ discharger generated new subgoals\") do\n run n (l ++ gs) acc)\n termination_by run n curr acc => (n, curr)\n\n/--\nA `MetaM` analogue of the `apply_rules` user tactic.\n\nSince `apply_rules` does not backtrack, we don't need to worry about stuck metavariables\nand can pass the lemmas as a `List Expr`.\n\nBy default it uses all local hypotheses, but you can disable this with `only := true`.\nIf you need to remove particular local hypotheses, call `solveByElim` directly.\n-/\ndef _root_.Lean.MVarId.applyRules (cfg : Config) (lemmas : List Expr) (only : Bool := false)\n (g : MVarId) : MetaM (List MVarId) := do\n let lemmas := lemmas.map pure\n let ctx : TermElabM (List Expr) := if only then pure [] else do pure (← getLocalHyps).toList\n solveByElim { cfg.noBackTracking with failAtMaxDepth := false } lemmas ctx [g]\n\nopen Lean.Parser.Tactic\nopen Mathlib.Tactic.LabelAttr\n\n/--\n`mkAssumptionSet` builds a collection of lemmas for use in\nthe backtracking search in `solve_by_elim`.\n\n* By default, it includes all local hypotheses, along with `rfl`, `trivial`, `congrFun`\n and `congrArg`.\n* The flag `noDefaults` removes these.\n* The flag `star` includes all local hypotheses, but not `rfl`, `trivial`, `congrFun`,\n or `congrArg`. (It doesn't make sense to use `star` without `noDefaults`.)\n* The argument `add` is the list of terms inside the square brackets that did not have `-`\n and can be used to add expressions or local hypotheses\n* The argument `remove` is the list of terms inside the square brackets that had a `-`,\n and can be used to remove local hypotheses.\n (It doesn't make sense to remove expressions which are not local hypotheses,\n to remove local hypotheses unless `!noDefaults || star`,\n and it does not make sense to use `star` unless you remove at least one local hypothesis.)\n\n`mkAssumptionSet` returns not a `List expr`, but a `List (TermElabM Expr) × TermElabM (List Expr)`.\nThere are two separate problems that need to be solved.\n\n### Stuck metavariables\n\nLemmas with implicit arguments would be filled in with metavariables if we created the\n`Expr` objects immediately, so instead we return thunks that generate the expressions\non demand. This is the first component, with type `List (TermElabM expr)`.\n\nAs an example, we have `def rfl : ∀ {α : Sort u} {a : α}, a = a`, which on elaboration will become\n`@rfl ?m_1 ?m_2`.\n\nBecause `solve_by_elim` works by repeated application of lemmas against subgoals,\nthe first time such a lemma is successfully applied,\nthose metavariables will be unified, and thereafter have fixed values.\nThis would make it impossible to apply the lemma\na second time with different values of the metavariables.\n\nSee https://github.com/leanprover-community/mathlib/issues/2269\n\n### Relevant local hypotheses\n\n`solve_by_elim*` works with multiple goals,\nand we need to use separate sets of local hypotheses for each goal.\nThe second component of the returned value provides these local hypotheses.\n(Essentially using `local_context`, along with some filtering to remove hypotheses\nthat have been explicitly removed via `only` or `[-h]`.)\n\n-/\n-- These `TermElabM`s must be run inside a suitable `g.withContext`,\n-- usually using `elabContextLemmas`.\ndef mkAssumptionSet (noDefaults star : Bool) (add remove : List Term) (use : Array Ident) :\n MetaM (List (TermElabM Expr) × TermElabM (List Expr)) := do\n if star && !noDefaults then\n throwError \"It doesn't make sense to use `*` without `only`.\"\n\n let defaults : List (TermElabM Expr) :=\n [← `(rfl), ← `(trivial), ← `(congrFun), ← `(congrArg)].map elab'\n let labelledLemmas := (← use.mapM (labelled ·.raw.getId)).flatten.toList\n |>.map (liftM <| mkConstWithFreshMVarLevels ·)\n let lemmas := if noDefaults then\n add.map elab' ++ labelledLemmas\n else\n add.map elab' ++ labelledLemmas ++ defaults\n\n if !remove.isEmpty && noDefaults && !star then\n throwError \"It doesn't make sense to remove local hypotheses when using `only` without `*`.\"\n let locals : TermElabM (List Expr) := if noDefaults && !star then do\n pure []\n else do\n pure <| (← getLocalHyps).toList.removeAll (← remove.mapM elab')\n\n return (lemmas, locals)\n where\n /-- Run `elabTerm`. -/\n elab' (t : Term) : TermElabM Expr := Elab.Term.elabTerm t.raw none\n\n/-- Syntax for omitting a local hypothesis in `solve_by_elim`. -/\nsyntax erase := \"-\" term:max\n/-- Syntax for including all local hypotheses in `solve_by_elim`. -/\nsyntax star := \"*\"\n/-- Syntax for adding or removing a term, or `*`, in `solve_by_elim`. -/\nsyntax arg := star <|> erase <|> term\n/-- Syntax for adding and removing terms in `solve_by_elim`. -/\nsyntax args := \" [\" SolveByElim.arg,* \"] \"\n/-- Syntax for using all lemmas labelled with an attribute in `solve_by_elim`. -/\nsyntax using_ := \" using \" ident,*\n\nopen Syntax\n\n/--\nParse the lemma argument of a call to `solve_by_elim`.\nThe first component should be true if `*` appears at least once.\nThe second component should contain each term `t`in the arguments.\nThe third component should contain `t` for each `-t` in the arguments.\n-/\ndef parseArgs (s : Option (TSyntax ``args)) :\n Bool × List Term × List Term :=\n let args : Array (TSyntax ``arg) := match s with\n | some s => match s with\n | `(args| [$args,*]) => args.getElems\n | _ => #[]\n | none => #[]\n let args : Array (Option (Term ⊕ Term)) := args.map fun t => match t with\n | `(arg| $_:star) => none\n | `(arg| - $t:term) => some (Sum.inr t)\n | `(arg| $t:term) => some (Sum.inl t)\n | _ => panic! \"Unreachable parse of solve_by_elim arguments.\"\n let args := args.toList\n (args.contains none,\n args.filterMap fun o => o.bind Sum.getLeft,\n args.filterMap fun o => o.bind Sum.getRight)\n\n/-- Parse the `using ...` argument for `solve_by_elim`. -/\ndef parseUsing (s : Option (TSyntax ``using_)) : Array Ident :=\n match s with\n | some s => match s with\n | `(using_ | using $ids,*) => ids.getElems\n | _ => #[]\n | none => #[]\n\n/--\n`solve_by_elim` calls `apply` on the main goal to find an assumption whose head matches\nand then repeatedly calls `apply` on the generated subgoals until no subgoals remain,\nperforming at most `maxDepth` (defaults to 6) recursive steps.\n\n`solve_by_elim` discharges the current goal or fails.\n\n`solve_by_elim` performs backtracking if subgoals can not be solved.\n\nBy default, the assumptions passed to `apply` are the local context, `rfl`, `trivial`,\n`congrFun` and `congrArg`.\n\nThe assumptions can be modified with similar syntax as for `simp`:\n* `solve_by_elim [h₁, h₂, ..., hᵣ]` also applies the given expressions.\n* `solve_by_elim only [h₁, h₂, ..., hᵣ]` does not include the local context,\n `rfl`, `trivial`, `congrFun`, or `congrArg` unless they are explicitly included.\n* `solve_by_elim [-h₁, ... -hₙ]` removes the given local hypotheses.\n* `solve_by_elim using [a₁, ...]` uses all lemmas which have been labelled\n with the attributes `aᵢ` (these attributes must be created using `register_label_attr`).\n\n`solve_by_elim*` tries to solve all goals together, using backtracking if a solution for one goal\nmakes other goals impossible.\n(Adding or removing local hypotheses may not be well-behaved when starting with multiple goals.)\n\nOptional arguments passed via a configuration argument as `solve_by_elim (config := { ... })`\n- `maxDepth`: number of attempts at discharging generated subgoals\n- `symm`: adds all hypotheses derived by `symm` (defaults to `true`).\n- `exfalso`: allow calling `exfalso` and trying again if `solve_by_elim` fails\n (defaults to `true`).\n- `transparency`: change the transparency mode when calling `apply`. Defaults to `.default`,\n but it is often useful to change to `.reducible`,\n so semireducible definitions will not be unfolded when trying to apply a lemma.\n\nSee also the doc-comment for `Mathlib.Tactic.SolveByElim.Config` for the options\n`proc`, `suspend`, and `discharge` which allow further customization of `solve_by_elim`.\nBoth `apply_assumption` and `apply_rules` are implemented via these hooks.\n-/\nsyntax (name := solveByElimSyntax)\n \"solve_by_elim\" \"*\"? (config)? (&\" only\")? (args)? (using_)? : tactic\n\n/-- Wrapper for `solveByElim` that processes a list of `Term`s\nthat specify the lemmas to use. -/\ndef solveByElim.processSyntax (cfg : Config := {}) (only star : Bool) (add remove : List Term)\n (use : Array Ident) (goals : List MVarId) : MetaM (List MVarId) := do\n if !remove.isEmpty && goals.length > 1 then\n throwError \"Removing local hypotheses is not supported when operating on multiple goals.\"\n let ⟨lemmas, ctx⟩ ← mkAssumptionSet only star add remove use\n solveByElim cfg lemmas ctx goals\n\nelab_rules : tactic |\n `(tactic| solve_by_elim $[*%$s]? $[$cfg]? $[only%$o]? $[$t:args]? $[$use:using_]?) => do\n let (star, add, remove) := parseArgs t\n let use := parseUsing use\n let goals ← if s.isSome then\n getGoals\n else\n pure [← getMainGoal]\n let cfg ← elabConfig (mkOptionalNode cfg)\n let [] ← solveByElim.processSyntax cfg o.isSome star add remove use goals |\n throwError \"solve_by_elim unexpectedly returned subgoals\"\n pure ()\n\n/--\n`apply_assumption` looks for an assumption of the form `... → ∀ _, ... → head`\nwhere `head` matches the current goal.\n\nYou can specify additional rules to apply using `apply_assumption [...]`.\nBy default `apply_assumption` will also try `rfl`, `trivial`, `congrFun`, and `congrArg`.\nIf you don't want these, or don't want to use all hypotheses, use `apply_assumption only [...]`.\nYou can use `apply_assumption [-h]` to omit a local hypothesis.\nYou can use `apply_assumption using [a₁, ...]` to use all lemmas which have been labelled\nwith the attributes `aᵢ` (these attributes must be created using `register_label_attr`).\n\n`apply_assumption` will use consequences of local hypotheses obtained via `symm`.\n\nIf `apply_assumption` fails, it will call `exfalso` and try again.\nThus if there is an assumption of the form `P → ¬ Q`, the new tactic state\nwill have two goals, `P` and `Q`.\n\nYou can pass a further configuration via the syntax `apply_rules (config := {...}) lemmas`.\nThe options supported are the same as for `solve_by_elim` (and include all the options for `apply`).\n-/\nsyntax (name := applyAssumptionSyntax)\n \"apply_assumption\" (config)? (&\" only\")? (args)? (using_)? : tactic\n\nelab_rules : tactic |\n `(tactic| apply_assumption $[$cfg]? $[only%$o]? $[$t:args]? $[$use:using_]?) => do\n let (star, add, remove) := parseArgs t\n let use := parseUsing use\n let cfg ← elabConfig (mkOptionalNode cfg)\n let cfg := { cfg with\n maxDepth := 1\n failAtMaxDepth := false }\n replaceMainGoal (← solveByElim.processSyntax cfg o.isSome star add remove use [← getMainGoal])\n\n/--\n`apply_rules [l₁, l₂, ...]` tries to solve the main goal by iteratively\napplying the list of lemmas `[l₁, l₂, ...]` or by applying a local hypothesis.\nIf `apply` generates new goals, `apply_rules` iteratively tries to solve those goals.\nYou can use `apply_rules [-h]` to omit a local hypothesis.\n\n`apply_rules` will also use `rfl`, `trivial`, `congrFun` and `congrArg`.\nThese can be disabled, as can local hypotheses, by using `apply_rules only [...]`.\n\nYou can use `apply_rules using [a₁, ...]` to use all lemmas which have been labelled\nwith the attributes `aᵢ` (these attributes must be created using `register_label_attr`).\n\nYou can pass a further configuration via the syntax `apply_rules (config := {...})`.\nThe options supported are the same as for `solve_by_elim` (and include all the options for `apply`).\n\n`apply_rules` will try calling `symm` on hypotheses and `exfalso` on the goal as needed.\nThis can be disabled with `apply_rules (config := {symm := false, exfalso := false})`.\n\nYou can bound the iteration depth using the syntax `apply_rules (config := {maxDepth := n})`.\n\nUnlike `solve_by_elim`, `apply_rules` does not perform backtracking, and greedily applies\na lemma from the list until it gets stuck.\n-/\nsyntax (name := applyRulesSyntax) \"apply_rules\" (config)? (&\" only\")? (args)? (using_)? : tactic\n\n-- See also `Lean.MVarId.applyRules` for a `MetaM` level analogue of this tactic.\nelab_rules : tactic |\n `(tactic| apply_rules $[$cfg]? $[only%$o]? $[$t:args]? $[$use:using_]?) => do\n let (star, add, remove) := parseArgs t\n let use := parseUsing use\n let cfg ← elabApplyRulesConfig (mkOptionalNode cfg)\n let cfg := { cfg.noBackTracking with\n failAtMaxDepth := false }\n liftMetaTactic fun g => solveByElim.processSyntax cfg o.isSome star add remove use [g]\n", "meta": {"author": "leanprover-community", "repo": "mathlib4", "sha": "b9a0a30342ca06e9817e22dbe46e75fc7f435500", "save_path": "github-repos/lean/leanprover-community-mathlib4", "path": "github-repos/lean/leanprover-community-mathlib4/mathlib4-b9a0a30342ca06e9817e22dbe46e75fc7f435500/Mathlib/Tactic/SolveByElim.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45713673161914675, "lm_q2_score": 0.06560483197834707, "lm_q1q2_score": 0.02999037846900486}} {"text": "/-\nCopyright (c) 2018 Simon Hudon. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Simon Hudon\n-/\nimport control.applicative\nimport data.list.forall2\nimport data.set.lattice\n\n/-!\n# Traversable instances\n\nThis file provides instances of `traversable` for types from the core library: `option`, `list` and\n`sum`.\n-/\n\nuniverses u v\n\nsection option\n\nopen functor\n\nvariables {F G : Type u → Type u}\nvariables [applicative F] [applicative G]\nvariables [is_lawful_applicative F] [is_lawful_applicative G]\n\nlemma option.id_traverse {α} (x : option α) : option.traverse id.mk x = x :=\nby cases x; refl\n\n@[nolint unused_arguments]\nlemma option.comp_traverse {α β γ} (f : β → F γ) (g : α → G β) (x : option α) :\n option.traverse (comp.mk ∘ (<$>) f ∘ g) x =\n comp.mk (option.traverse f <$> option.traverse g x) :=\nby cases x; simp! with functor_norm; refl\n\nlemma option.traverse_eq_map_id {α β} (f : α → β) (x : option α) :\n traverse (id.mk ∘ f) x = id.mk (f <$> x) :=\nby cases x; refl\n\nvariable (η : applicative_transformation F G)\n\nlemma option.naturality {α β} (f : α → F β) (x : option α) :\n η (option.traverse f x) = option.traverse (@η _ ∘ f) x :=\nby cases x with x; simp! [*] with functor_norm\n\nend option\n\ninstance : is_lawful_traversable option :=\n{ id_traverse := @option.id_traverse,\n comp_traverse := @option.comp_traverse,\n traverse_eq_map_id := @option.traverse_eq_map_id,\n naturality := @option.naturality,\n .. option.is_lawful_monad }\n\nnamespace list\n\nvariables {F G : Type u → Type u}\nvariables [applicative F] [applicative G]\n\nsection\nvariables [is_lawful_applicative F] [is_lawful_applicative G]\n\nopen applicative functor\nopen list (cons)\n\nprotected \n\n@[nolint unused_arguments]\nprotected lemma comp_traverse {α β γ} (f : β → F γ) (g : α → G β) (x : list α) :\n list.traverse (comp.mk ∘ (<$>) f ∘ g) x =\n comp.mk (list.traverse f <$> list.traverse g x) :=\nby induction x; simp! * with functor_norm; refl\n\nprotected lemma traverse_eq_map_id {α β} (f : α → β) (x : list α) :\n list.traverse (id.mk ∘ f) x = id.mk (f <$> x) :=\nby induction x; simp! * with functor_norm; refl\n\nvariable (η : applicative_transformation F G)\n\nprotected lemma naturality {α β} (f : α → F β) (x : list α) :\n η (list.traverse f x) = list.traverse (@η _ ∘ f) x :=\nby induction x; simp! * with functor_norm\nopen nat\n\ninstance : is_lawful_traversable.{u} list :=\n{ id_traverse := @list.id_traverse,\n comp_traverse := @list.comp_traverse,\n traverse_eq_map_id := @list.traverse_eq_map_id,\n naturality := @list.naturality,\n .. list.is_lawful_monad }\nend\n\nsection traverse\nvariables {α' β' : Type u} (f : α' → F β')\n\n@[simp] lemma traverse_nil : traverse f ([] : list α') = (pure [] : F (list β')) := rfl\n\n@[simp] lemma traverse_cons (a : α') (l : list α') :\n traverse f (a :: l) = (::) <$> f a <*> traverse f l := rfl\n\nvariables [is_lawful_applicative F]\n\n@[simp] lemma traverse_append :\n ∀ (as bs : list α'), traverse f (as ++ bs) = (++) <$> traverse f as <*> traverse f bs\n| [] bs :=\n have has_append.append ([] : list β') = id, by funext; refl,\n by simp [this] with functor_norm\n| (a :: as) bs := by simp [traverse_append as bs] with functor_norm; congr\n\nlemma mem_traverse {f : α' → set β'} :\n ∀(l : list α') (n : list β'), n ∈ traverse f l ↔ forall₂ (λb a, b ∈ f a) n l\n| [] [] := by simp\n| (a::as) [] := by simp\n| [] (b::bs) := by simp\n| (a::as) (b::bs) := by simp [mem_traverse as bs]\n\nend traverse\n\nend list\n\nnamespace sum\n\nsection traverse\nvariables {σ : Type u}\nvariables {F G : Type u → Type u}\nvariables [applicative F] [applicative G]\n\nopen applicative functor\nopen list (cons)\n\nprotected lemma traverse_map {α β γ : Type u} (g : α → β) (f : β → G γ) (x : σ ⊕ α) :\n sum.traverse f (g <$> x) = sum.traverse (f ∘ g) x :=\nby cases x; simp [sum.traverse, id_map] with functor_norm; refl\n\nvariables [is_lawful_applicative F] [is_lawful_applicative G]\n\nprotected lemma id_traverse {σ α} (x : σ ⊕ α) : sum.traverse id.mk x = x :=\nby cases x; refl\n\n@[nolint unused_arguments]\nprotected lemma comp_traverse {α β γ} (f : β → F γ) (g : α → G β) (x : σ ⊕ α) :\n sum.traverse (comp.mk ∘ (<$>) f ∘ g) x =\n comp.mk (sum.traverse f <$> sum.traverse g x) :=\nby cases x; simp! [sum.traverse,map_id] with functor_norm; refl\n\nprotected lemma traverse_eq_map_id {α β} (f : α → β) (x : σ ⊕ α) :\n sum.traverse (id.mk ∘ f) x = id.mk (f <$> x) :=\nby induction x; simp! * with functor_norm; refl\n\nprotected lemma map_traverse {α β γ} (g : α → G β) (f : β → γ) (x : σ ⊕ α) :\n (<$>) f <$> sum.traverse g x = sum.traverse ((<$>) f ∘ g) x :=\nby cases x; simp [sum.traverse, id_map] with functor_norm; congr; refl\n\nvariable (η : applicative_transformation F G)\n\nprotected lemma naturality {α β} (f : α → F β) (x : σ ⊕ α) :\n η (sum.traverse f x) = sum.traverse (@η _ ∘ f) x :=\nby cases x; simp! [sum.traverse] with functor_norm\n\nend traverse\n\ninstance {σ : Type u} : is_lawful_traversable.{u} (sum σ) :=\n{ id_traverse := @sum.id_traverse σ,\n comp_traverse := @sum.comp_traverse σ,\n traverse_eq_map_id := @sum.traverse_eq_map_id σ,\n naturality := @sum.naturality σ,\n .. sum.is_lawful_monad }\n\nend sum\n", "meta": {"author": "jjaassoonn", "repo": "projective_space", "sha": "11fe19fe9d7991a272e7a40be4b6ad9b0c10c7ce", "save_path": "github-repos/lean/jjaassoonn-projective_space", "path": "github-repos/lean/jjaassoonn-projective_space/projective_space-11fe19fe9d7991a272e7a40be4b6ad9b0c10c7ce/src/control/traversable/instances.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43014733397551624, "lm_q2_score": 0.06954173968487863, "lm_q1q2_score": 0.0299131939254699}} {"text": "/-\nCopyright (c) 2020 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Leonardo de Moura\n\nExtra notation that depends on Init/Meta\n-/\nprelude\nimport Init.Meta\nimport Init.Data.Array.Subarray\nimport Init.Data.ToString\nnamespace Lean\n\nmacro \"Macro.trace[\" id:ident \"]\" s:interpolatedStr(term) : term =>\n `(Macro.trace $(quote id.getId.eraseMacroScopes) (s! $s))\n\n-- Auxiliary parsers and functions for declaring notation with binders\n\nsyntax unbracketedExplicitBinders := binderIdent+ (\" : \" term)?\nsyntax bracketedExplicitBinders := \"(\" withoutPosition(binderIdent+ \" : \" term) \")\"\nsyntax explicitBinders := bracketedExplicitBinders+ <|> unbracketedExplicitBinders\n\nopen TSyntax.Compat in\ndef expandExplicitBindersAux (combinator : Syntax) (idents : Array Syntax) (type? : Option Syntax) (body : Syntax) : MacroM Syntax :=\n let rec loop (i : Nat) (acc : Syntax) := do\n match i with\n | 0 => pure acc\n | i+1 =>\n let ident := idents[i]![0]\n let acc ← match ident.isIdent, type? with\n | true, none => `($combinator fun $ident => $acc)\n | true, some type => `($combinator fun $ident : $type => $acc)\n | false, none => `($combinator fun _ => $acc)\n | false, some type => `($combinator fun _ : $type => $acc)\n loop i acc\n loop idents.size body\n\ndef expandBrackedBindersAux (combinator : Syntax) (binders : Array Syntax) (body : Syntax) : MacroM Syntax :=\n let rec loop (i : Nat) (acc : Syntax) := do\n match i with\n | 0 => pure acc\n | i+1 =>\n let idents := binders[i]![1].getArgs\n let type := binders[i]![3]\n loop i (← expandExplicitBindersAux combinator idents (some type) acc)\n loop binders.size body\n\ndef expandExplicitBinders (combinatorDeclName : Name) (explicitBinders : Syntax) (body : Syntax) : MacroM Syntax := do\n let combinator := mkCIdentFrom (← getRef) combinatorDeclName\n let explicitBinders := explicitBinders[0]\n if explicitBinders.getKind == ``Lean.unbracketedExplicitBinders then\n let idents := explicitBinders[0].getArgs\n let type? := if explicitBinders[1].isNone then none else some explicitBinders[1][1]\n expandExplicitBindersAux combinator idents type? body\n else if explicitBinders.getArgs.all (·.getKind == ``Lean.bracketedExplicitBinders) then\n expandBrackedBindersAux combinator explicitBinders.getArgs body\n else\n Macro.throwError \"unexpected explicit binder\"\n\ndef expandBrackedBinders (combinatorDeclName : Name) (bracketedExplicitBinders : Syntax) (body : Syntax) : MacroM Syntax := do\n let combinator := mkCIdentFrom (← getRef) combinatorDeclName\n expandBrackedBindersAux combinator #[bracketedExplicitBinders] body\n\nsyntax unifConstraint := term patternIgnore(\" =?= \" <|> \" ≟ \") term\nsyntax unifConstraintElem := colGe unifConstraint \", \"?\n\nsyntax (docComment)? attrKind \"unif_hint \" (ident)? bracketedBinder* \" where \" withPosition(unifConstraintElem*) patternIgnore(\"|-\" <|> \"⊢ \") unifConstraint : command\n\nmacro_rules\n | `($[$doc?:docComment]? $kind:attrKind unif_hint $(n)? $bs* where $[$cs₁ ≟ $cs₂]* |- $t₁ ≟ $t₂) => do\n let mut body ← `($t₁ = $t₂)\n for (c₁, c₂) in cs₁.zip cs₂ |>.reverse do\n body ← `($c₁ = $c₂ → $body)\n let hint : Ident ← `(hint)\n `($[$doc?:docComment]? @[$kind unification_hint] def $(n.getD hint) $bs* : Sort _ := $body)\nend Lean\n\nopen Lean\n\nsection\nopen TSyntax.Compat\nmacro \"∃ \" xs:explicitBinders \", \" b:term : term => expandExplicitBinders ``Exists xs b\nmacro \"exists\" xs:explicitBinders \", \" b:term : term => expandExplicitBinders ``Exists xs b\nmacro \"Σ\" xs:explicitBinders \", \" b:term : term => expandExplicitBinders ``Sigma xs b\nmacro \"Σ'\" xs:explicitBinders \", \" b:term : term => expandExplicitBinders ``PSigma xs b\nmacro:35 xs:bracketedExplicitBinders \" × \" b:term:35 : term => expandBrackedBinders ``Sigma xs b\nmacro:35 xs:bracketedExplicitBinders \" ×' \" b:term:35 : term => expandBrackedBinders ``PSigma xs b\nend\n\n-- first step of a `calc` block\nsyntax calcFirstStep := ppIndent(colGe term (\" := \" term)?)\n-- enforce indentation of calc steps so we know when to stop parsing them\nsyntax calcStep := ppIndent(colGe term \" := \" term)\nsyntax calcSteps := ppLine withPosition(calcFirstStep) ppLine withPosition((calcStep ppLine)*)\n\n/-- Step-wise reasoning over transitive relations.\n```\ncalc\n a = b := pab\n b = c := pbc\n ...\n y = z := pyz\n```\nproves `a = z` from the given step-wise proofs. `=` can be replaced with any\nrelation implementing the typeclass `Trans`. Instead of repeating the right-\nhand sides, subsequent left-hand sides can be replaced with `_`.\n```\ncalc\n a = b := pab\n _ = c := pbc\n ...\n _ = z := pyz\n```\nIt is also possible to write the *first* relation as `\\n _ = :=\n`. This is useful for aligning relation symbols, especially on longer:\nidentifiers:\n```\ncalc abc\n _ = bce := pabce\n _ = cef := pbcef\n ...\n _ = xyz := pwxyz\n```\n\n`calc` has term mode and tactic mode variants. This is the term mode variant.\n\nSee [Theorem Proving in Lean 4][tpil4] for more information.\n\n[tpil4]: https://leanprover.github.io/theorem_proving_in_lean4/quantifiers_and_equality.html#calculational-proofs\n-/\nsyntax (name := calc) \"calc\" calcSteps : term\n\n/-- Step-wise reasoning over transitive relations.\n```\ncalc\n a = b := pab\n b = c := pbc\n ...\n y = z := pyz\n```\nproves `a = z` from the given step-wise proofs. `=` can be replaced with any\nrelation implementing the typeclass `Trans`. Instead of repeating the right-\nhand sides, subsequent left-hand sides can be replaced with `_`.\n```\ncalc\n a = b := pab\n _ = c := pbc\n ...\n _ = z := pyz\n```\nIt is also possible to write the *first* relation as `\\n _ = :=\n`. This is useful for aligning relation symbols:\n```\ncalc abc\n _ = bce := pabce\n _ = cef := pbcef\n ...\n _ = xyz := pwxyz\n```\n\n`calc` has term mode and tactic mode variants. This is the tactic mode variant,\nwhich supports an additional feature: it works even if the goal is `a = z'`\nfor some other `z'`; in this case it will not close the goal but will instead\nleave a subgoal proving `z = z'`.\n\nSee [Theorem Proving in Lean 4][tpil4] for more information.\n\n[tpil4]: https://leanprover.github.io/theorem_proving_in_lean4/quantifiers_and_equality.html#calculational-proofs\n-/\nsyntax (name := calcTactic) \"calc\" calcSteps : tactic\n\n@[app_unexpander Unit.unit] def unexpandUnit : Lean.PrettyPrinter.Unexpander\n | `($(_)) => `(())\n\n@[app_unexpander List.nil] def unexpandListNil : Lean.PrettyPrinter.Unexpander\n | `($(_)) => `([])\n\n@[app_unexpander List.cons] def unexpandListCons : Lean.PrettyPrinter.Unexpander\n | `($(_) $x []) => `([$x])\n | `($(_) $x [$xs,*]) => `([$x, $xs,*])\n | _ => throw ()\n\n@[app_unexpander List.toArray] def unexpandListToArray : Lean.PrettyPrinter.Unexpander\n | `($(_) [$xs,*]) => `(#[$xs,*])\n | _ => throw ()\n\n@[app_unexpander Prod.mk] def unexpandProdMk : Lean.PrettyPrinter.Unexpander\n | `($(_) $x ($y, $ys,*)) => `(($x, $y, $ys,*))\n | `($(_) $x $y) => `(($x, $y))\n | _ => throw ()\n\n@[app_unexpander ite] def unexpandIte : Lean.PrettyPrinter.Unexpander\n | `($(_) $c $t $e) => `(if $c then $t else $e)\n | _ => throw ()\n\n@[app_unexpander sorryAx] def unexpandSorryAx : Lean.PrettyPrinter.Unexpander\n | `($(_) _) => `(sorry)\n | `($(_) _ _) => `(sorry)\n | _ => throw ()\n\n@[app_unexpander Eq.ndrec] def unexpandEqNDRec : Lean.PrettyPrinter.Unexpander\n | `($(_) $m $h) => `($h ▸ $m)\n | _ => throw ()\n\n@[app_unexpander Eq.rec] def unexpandEqRec : Lean.PrettyPrinter.Unexpander\n | `($(_) $m $h) => `($h ▸ $m)\n | _ => throw ()\n\n@[app_unexpander Exists] def unexpandExists : Lean.PrettyPrinter.Unexpander\n | `($(_) fun $x:ident => ∃ $xs:binderIdent*, $b) => `(∃ $x:ident $xs:binderIdent*, $b)\n | `($(_) fun $x:ident => $b) => `(∃ $x:ident, $b)\n | `($(_) fun ($x:ident : $t) => $b) => `(∃ ($x:ident : $t), $b)\n | _ => throw ()\n\n@[app_unexpander Sigma] def unexpandSigma : Lean.PrettyPrinter.Unexpander\n | `($(_) fun ($x:ident : $t) => $b) => `(($x:ident : $t) × $b)\n | _ => throw ()\n\n@[app_unexpander PSigma] def unexpandPSigma : Lean.PrettyPrinter.Unexpander\n | `($(_) fun ($x:ident : $t) => $b) => `(($x:ident : $t) ×' $b)\n | _ => throw ()\n\n@[app_unexpander Subtype] def unexpandSubtype : Lean.PrettyPrinter.Unexpander\n | `($(_) fun ($x:ident : $type) => $p) => `({ $x : $type // $p })\n | `($(_) fun $x:ident => $p) => `({ $x // $p })\n | _ => throw ()\n\n@[app_unexpander TSyntax] def unexpandTSyntax : Lean.PrettyPrinter.Unexpander\n | `($f [$k]) => `($f $k)\n | _ => throw ()\n\n@[app_unexpander TSyntaxArray] def unexpandTSyntaxArray : Lean.PrettyPrinter.Unexpander\n | `($f [$k]) => `($f $k)\n | _ => throw ()\n\n@[app_unexpander Syntax.TSepArray] def unexpandTSepArray : Lean.PrettyPrinter.Unexpander\n | `($f [$k] $sep) => `($f $k $sep)\n | _ => throw ()\n\n@[app_unexpander GetElem.getElem] def unexpandGetElem : Lean.PrettyPrinter.Unexpander\n | `($_ $array $index $_) => `($array[$index])\n | _ => throw ()\n\n@[app_unexpander getElem!] def unexpandGetElem! : Lean.PrettyPrinter.Unexpander\n | `($_ $array $index) => `($array[$index]!)\n | _ => throw ()\n\n@[app_unexpander getElem?] def unexpandGetElem? : Lean.PrettyPrinter.Unexpander\n | `($_ $array $index) => `($array[$index]?)\n | _ => throw ()\n\n@[app_unexpander Name.mkStr1] def unexpandMkStr1 : Lean.PrettyPrinter.Unexpander\n | `($(_) $a:str) => return mkNode `Lean.Parser.Term.quotedName #[Syntax.mkNameLit s!\"`{a.getString}\"]\n | _ => throw ()\n\n@[app_unexpander Name.mkStr2] def unexpandMkStr2 : Lean.PrettyPrinter.Unexpander\n | `($(_) $a1:str $a2:str) => return mkNode `Lean.Parser.Term.quotedName #[Syntax.mkNameLit s!\"`{a1.getString}.{a2.getString}\"]\n | _ => throw ()\n\n@[app_unexpander Name.mkStr3] def unexpandMkStr3 : Lean.PrettyPrinter.Unexpander\n | `($(_) $a1:str $a2:str $a3:str) => return mkNode `Lean.Parser.Term.quotedName #[Syntax.mkNameLit s!\"`{a1.getString}.{a2.getString}.{a3.getString}\"]\n | _ => throw ()\n\n@[app_unexpander Name.mkStr4] def unexpandMkStr4 : Lean.PrettyPrinter.Unexpander\n | `($(_) $a1:str $a2:str $a3:str $a4:str) => return mkNode `Lean.Parser.Term.quotedName #[Syntax.mkNameLit s!\"`{a1.getString}.{a2.getString}.{a3.getString}.{a4.getString}\"]\n | _ => throw ()\n\n@[app_unexpander Name.mkStr5] def unexpandMkStr5 : Lean.PrettyPrinter.Unexpander\n | `($(_) $a1:str $a2:str $a3:str $a4:str $a5:str) => return mkNode `Lean.Parser.Term.quotedName #[Syntax.mkNameLit s!\"`{a1.getString}.{a2.getString}.{a3.getString}.{a4.getString}.{a5.getString}\"]\n | _ => throw ()\n\n@[app_unexpander Name.mkStr6] def unexpandMkStr6 : Lean.PrettyPrinter.Unexpander\n | `($(_) $a1:str $a2:str $a3:str $a4:str $a5:str $a6:str) => return mkNode `Lean.Parser.Term.quotedName #[Syntax.mkNameLit s!\"`{a1.getString}.{a2.getString}.{a3.getString}.{a4.getString}.{a5.getString}.{a6.getString}\"]\n | _ => throw ()\n\n@[app_unexpander Name.mkStr7] def unexpandMkStr7 : Lean.PrettyPrinter.Unexpander\n | `($(_) $a1:str $a2:str $a3:str $a4:str $a5:str $a6:str $a7:str) => return mkNode `Lean.Parser.Term.quotedName #[Syntax.mkNameLit s!\"`{a1.getString}.{a2.getString}.{a3.getString}.{a4.getString}.{a5.getString}.{a6.getString}.{a7.getString}\"]\n | _ => throw ()\n\n@[app_unexpander Name.mkStr8] def unexpandMkStr8 : Lean.PrettyPrinter.Unexpander\n | `($(_) $a1:str $a2:str $a3:str $a4:str $a5:str $a6:str $a7:str $a8:str) => return mkNode `Lean.Parser.Term.quotedName #[Syntax.mkNameLit s!\"`{a1.getString}.{a2.getString}.{a3.getString}.{a4.getString}.{a5.getString}.{a6.getString}.{a7.getString}.{a8.getString}\"]\n | _ => throw ()\n\n@[app_unexpander Array.empty] def unexpandArrayEmpty : Lean.PrettyPrinter.Unexpander\n | _ => `(#[])\n\n@[app_unexpander Array.mkArray0] def unexpandMkArray0 : Lean.PrettyPrinter.Unexpander\n | _ => `(#[])\n\n@[app_unexpander Array.mkArray1] def unexpandMkArray1 : Lean.PrettyPrinter.Unexpander\n | `($(_) $a1) => `(#[$a1])\n | _ => throw ()\n\n@[app_unexpander Array.mkArray2] def unexpandMkArray2 : Lean.PrettyPrinter.Unexpander\n | `($(_) $a1 $a2) => `(#[$a1, $a2])\n | _ => throw ()\n\n@[app_unexpander Array.mkArray3] def unexpandMkArray3 : Lean.PrettyPrinter.Unexpander\n | `($(_) $a1 $a2 $a3) => `(#[$a1, $a2, $a3])\n | _ => throw ()\n\n@[app_unexpander Array.mkArray4] def unexpandMkArray4 : Lean.PrettyPrinter.Unexpander\n | `($(_) $a1 $a2 $a3 $a4) => `(#[$a1, $a2, $a3, $a4])\n | _ => throw ()\n\n@[app_unexpander Array.mkArray5] def unexpandMkArray5 : Lean.PrettyPrinter.Unexpander\n | `($(_) $a1 $a2 $a3 $a4 $a5) => `(#[$a1, $a2, $a3, $a4, $a5])\n | _ => throw ()\n\n@[app_unexpander Array.mkArray6] def unexpandMkArray6 : Lean.PrettyPrinter.Unexpander\n | `($(_) $a1 $a2 $a3 $a4 $a5 $a6) => `(#[$a1, $a2, $a3, $a4, $a5, $a6])\n | _ => throw ()\n\n@[app_unexpander Array.mkArray7] def unexpandMkArray7 : Lean.PrettyPrinter.Unexpander\n | `($(_) $a1 $a2 $a3 $a4 $a5 $a6 $a7) => `(#[$a1, $a2, $a3, $a4, $a5, $a6, $a7])\n | _ => throw ()\n\n@[app_unexpander Array.mkArray8] def unexpandMkArray8 : Lean.PrettyPrinter.Unexpander\n | `($(_) $a1 $a2 $a3 $a4 $a5 $a6 $a7 $a8) => `(#[$a1, $a2, $a3, $a4, $a5, $a6, $a7, $a8])\n | _ => throw ()\n\n/--\nApply function extensionality and introduce new hypotheses.\nThe tactic `funext` will keep applying the `funext` lemma until the goal target is not reducible to\n```\n |- ((fun x => ...) = (fun x => ...))\n```\nThe variant `funext h₁ ... hₙ` applies `funext` `n` times, and uses the given identifiers to name the new hypotheses.\nPatterns can be used like in the `intro` tactic. Example, given a goal\n```\n |- ((fun x : Nat × Bool => ...) = (fun x => ...))\n```\n`funext (a, b)` applies `funext` once and performs pattern matching on the newly introduced pair.\n-/\nsyntax \"funext\" (ppSpace colGt term:max)* : tactic\n\nmacro_rules\n | `(tactic|funext) => `(tactic| repeat (apply funext; intro))\n | `(tactic|funext $x) => `(tactic| apply funext; intro $x:term)\n | `(tactic|funext $x $xs*) => `(tactic| apply funext; intro $x:term; funext $xs*)\n\nmacro_rules\n | `(%[ $[$x],* | $k ]) =>\n if x.size < 8 then\n x.foldrM (β := Term) (init := k) fun x k =>\n `(List.cons $x $k)\n else\n let m := x.size / 2\n let y := x[m:]\n let z := x[:m]\n `(let y := %[ $[$y],* | $k ]\n %[ $[$z],* | y ])\n\n/--\n Expands\n ```\n class abbrev C := D_1, ..., D_n\n ```\n into\n ```\n class C extends D_1, ..., D_n\n attribute [instance] C.mk\n ```\n-/\nsyntax (name := Lean.Parser.Command.classAbbrev)\n declModifiers \"class \" \"abbrev \" declId bracketedBinder* (\":\" term)?\n \":=\" withPosition(group(colGe term \",\"?)*) : command\n\nmacro_rules\n | `($mods:declModifiers class abbrev $id $params* $[: $ty]? := $[ $parents $[,]? ]*) =>\n let ctor := mkIdentFrom id <| id.raw[0].getId.modifyBase (. ++ `mk)\n `($mods:declModifiers class $id $params* extends $parents,* $[: $ty]?\n attribute [instance] $ctor)\n\nsyntax cdotTk := patternIgnore(\"· \" <|> \". \")\n/-- `· tac` focuses on the main goal and tries to solve it using `tac`, or else fails. -/\nsyntax (name := cdot) cdotTk tacticSeqIndentGt : tactic\n\n/--\n Similar to `first`, but succeeds only if one the given tactics solves the current goal.\n-/\nsyntax (name := solve) \"solve \" withPosition((colGe \"|\" tacticSeq)+) : tactic\n\nmacro_rules\n | `(tactic| solve $[| $ts]* ) => `(tactic| focus first $[| ($ts); done]*)\n\nnamespace Lean\n/-! # `repeat` and `while` notation -/\n\ninductive Loop where\n | mk\n\n@[inline]\npartial def Loop.forIn {β : Type u} {m : Type u → Type v} [Monad m] (_ : Loop) (init : β) (f : Unit → β → m (ForInStep β)) : m β :=\n let rec @[specialize] loop (b : β) : m β := do\n match ← f () b with\n | ForInStep.done b => pure b\n | ForInStep.yield b => loop b\n loop init\n\ninstance : ForIn m Loop Unit where\n forIn := Loop.forIn\n\nsyntax \"repeat \" doSeq : doElem\n\nmacro_rules\n | `(doElem| repeat $seq) => `(doElem| for _ in Loop.mk do $seq)\n\nsyntax \"while \" ident \" : \" termBeforeDo \" do \" doSeq : doElem\n\nmacro_rules\n | `(doElem| while $h : $cond do $seq) => `(doElem| repeat if $h : $cond then $seq else break)\n\nsyntax \"while \" termBeforeDo \" do \" doSeq : doElem\n\nmacro_rules\n | `(doElem| while $cond do $seq) => `(doElem| repeat if $cond then $seq else break)\n\nsyntax \"repeat \" doSeq \" until \" term : doElem\n\nmacro_rules\n | `(doElem| repeat $seq until $cond) => `(doElem| repeat do $seq:doSeq; if $cond then break)\n\nmacro:50 e:term:51 \" matches \" p:sepBy1(term:51, \"|\") : term =>\n `(((match $e:term with | $[$p:term]|* => true | _ => false) : Bool))\n\nend Lean\n", "meta": {"author": "leanprover", "repo": "lean4", "sha": "742d053a97bdd109a41a921facd1cd6a55e89bc7", "save_path": "github-repos/lean/leanprover-lean4", "path": "github-repos/lean/leanprover-lean4/lean4-742d053a97bdd109a41a921facd1cd6a55e89bc7/src/Init/NotationExtra.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41111086923216805, "lm_q2_score": 0.0726367028476572, "lm_q1q2_score": 0.02986173804585905}} {"text": "/-\nCopyright (c) 2019 Reid Barton. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Reid Barton, Johan Commelin, Bhavik Mehta\n-/\nimport category_theory.equivalence\nimport data.equiv.basic\n\nnamespace category_theory\nopen category\n\n-- declare the `v`'s first; see `category_theory.category` for an explanation\nuniverses v₁ v₂ v₃ u₁ u₂ u₃\n\nlocal attribute [elab_simple] whisker_left whisker_right\n\nvariables {C : Type u₁} [category.{v₁} C] {D : Type u₂} [category.{v₂} D]\n\n/--\n`F ⊣ G` represents the data of an adjunction between two functors\n`F : C ⥤ D` and `G : D ⥤ C`. `F` is the left adjoint and `G` is the right adjoint.\n\nTo construct an `adjunction` between two functors, it's often easier to instead use the\nconstructors `mk_of_hom_equiv` or `mk_of_unit_counit`. To construct a left adjoint,\nthere are also constructors `left_adjoint_of_equiv` and `adjunction_of_equiv_left` (as\nwell as their duals) which can be simpler in practice.\n\nUniqueness of adjoints is shown in `category_theory.adjunction.opposites`.\n\nSee https://stacks.math.columbia.edu/tag/0037.\n-/\nstructure adjunction (F : C ⥤ D) (G : D ⥤ C) :=\n(hom_equiv : Π (X Y), (F.obj X ⟶ Y) ≃ (X ⟶ G.obj Y))\n(unit : 𝟭 C ⟶ F.comp G)\n(counit : G.comp F ⟶ 𝟭 D)\n(hom_equiv_unit' : Π {X Y f}, (hom_equiv X Y) f = (unit : _ ⟶ _).app X ≫ G.map f . obviously)\n(hom_equiv_counit' : Π {X Y g}, (hom_equiv X Y).symm g = F.map g ≫ counit.app Y . obviously)\n\ninfix ` ⊣ `:15 := adjunction\n\n/-- A class giving a chosen right adjoint to the functor `left`. -/\nclass is_left_adjoint (left : C ⥤ D) :=\n(right : D ⥤ C)\n(adj : left ⊣ right)\n\n/-- A class giving a chosen left adjoint to the functor `right`. -/\nclass is_right_adjoint (right : D ⥤ C) :=\n(left : C ⥤ D)\n(adj : left ⊣ right)\n\n/-- Extract the left adjoint from the instance giving the chosen adjoint. -/\ndef left_adjoint (R : D ⥤ C) [is_right_adjoint R] : C ⥤ D :=\nis_right_adjoint.left R\n/-- Extract the right adjoint from the instance giving the chosen adjoint. -/\ndef right_adjoint (L : C ⥤ D) [is_left_adjoint L] : D ⥤ C :=\nis_left_adjoint.right L\n\n/-- The adjunction associated to a functor known to be a left adjoint. -/\ndef adjunction.of_left_adjoint (left : C ⥤ D) [is_left_adjoint left] :\n adjunction left (right_adjoint left) :=\nis_left_adjoint.adj\n/-- The adjunction associated to a functor known to be a right adjoint. -/\ndef adjunction.of_right_adjoint (right : C ⥤ D) [is_right_adjoint right] :\n adjunction (left_adjoint right) right :=\nis_right_adjoint.adj\n\nnamespace adjunction\n\nrestate_axiom hom_equiv_unit'\nrestate_axiom hom_equiv_counit'\nattribute [simp, priority 10] hom_equiv_unit hom_equiv_counit\n\nsection\n\nvariables {F : C ⥤ D} {G : D ⥤ C} (adj : F ⊣ G) {X' X : C} {Y Y' : D}\n\n@[simp, priority 10] lemma hom_equiv_naturality_left_symm (f : X' ⟶ X) (g : X ⟶ G.obj Y) :\n (adj.hom_equiv X' Y).symm (f ≫ g) = F.map f ≫ (adj.hom_equiv X Y).symm g :=\nby rw [hom_equiv_counit, F.map_comp, assoc, adj.hom_equiv_counit.symm]\n\n@[simp] lemma hom_equiv_naturality_left (f : X' ⟶ X) (g : F.obj X ⟶ Y) :\n (adj.hom_equiv X' Y) (F.map f ≫ g) = f ≫ (adj.hom_equiv X Y) g :=\nby rw [← equiv.eq_symm_apply]; simp [-hom_equiv_unit]\n\n@[simp, priority 10] lemma hom_equiv_naturality_right (f : F.obj X ⟶ Y) (g : Y ⟶ Y') :\n (adj.hom_equiv X Y') (f ≫ g) = (adj.hom_equiv X Y) f ≫ G.map g :=\nby rw [hom_equiv_unit, G.map_comp, ← assoc, ←hom_equiv_unit]\n\n@[simp] lemma hom_equiv_naturality_right_symm (f : X ⟶ G.obj Y) (g : Y ⟶ Y') :\n (adj.hom_equiv X Y').symm (f ≫ G.map g) = (adj.hom_equiv X Y).symm f ≫ g :=\nby rw [equiv.symm_apply_eq]; simp [-hom_equiv_counit]\n\n@[simp] lemma left_triangle :\n (whisker_right adj.unit F) ≫ (whisker_left F adj.counit) = nat_trans.id _ :=\nbegin\n ext, dsimp,\n erw [← adj.hom_equiv_counit, equiv.symm_apply_eq, adj.hom_equiv_unit],\n simp\nend\n\n@[simp] \n\n@[simp, reassoc] lemma left_triangle_components :\n F.map (adj.unit.app X) ≫ adj.counit.app (F.obj X) = 𝟙 (F.obj X) :=\ncongr_arg (λ (t : nat_trans _ (𝟭 C ⋙ F)), t.app X) adj.left_triangle\n\n@[simp, reassoc] lemma right_triangle_components {Y : D} :\n adj.unit.app (G.obj Y) ≫ G.map (adj.counit.app Y) = 𝟙 (G.obj Y) :=\ncongr_arg (λ (t : nat_trans _ (G ⋙ 𝟭 C)), t.app Y) adj.right_triangle\n\n@[simp, reassoc] lemma counit_naturality {X Y : D} (f : X ⟶ Y) :\n F.map (G.map f) ≫ (adj.counit).app Y = (adj.counit).app X ≫ f :=\nadj.counit.naturality f\n\n@[simp, reassoc] lemma unit_naturality {X Y : C} (f : X ⟶ Y) :\n (adj.unit).app X ≫ G.map (F.map f) = f ≫ (adj.unit).app Y :=\n(adj.unit.naturality f).symm\n\nlemma hom_equiv_apply_eq {A : C} {B : D} (f : F.obj A ⟶ B) (g : A ⟶ G.obj B) :\n adj.hom_equiv A B f = g ↔ f = (adj.hom_equiv A B).symm g :=\n⟨λ h, by {cases h, simp}, λ h, by {cases h, simp}⟩\n\nlemma eq_hom_equiv_apply {A : C} {B : D} (f : F.obj A ⟶ B) (g : A ⟶ G.obj B) :\n g = adj.hom_equiv A B f ↔ (adj.hom_equiv A B).symm g = f :=\n⟨λ h, by {cases h, simp}, λ h, by {cases h, simp}⟩\n\nend\n\nend adjunction\n\nnamespace adjunction\n\n/--\nThis is an auxiliary data structure useful for constructing adjunctions.\nSee `adjunction.mk_of_hom_equiv`.\nThis structure won't typically be used anywhere else.\n-/\n@[nolint has_inhabited_instance]\nstructure core_hom_equiv (F : C ⥤ D) (G : D ⥤ C) :=\n(hom_equiv : Π (X Y), (F.obj X ⟶ Y) ≃ (X ⟶ G.obj Y))\n(hom_equiv_naturality_left_symm' : Π {X' X Y} (f : X' ⟶ X) (g : X ⟶ G.obj Y),\n (hom_equiv X' Y).symm (f ≫ g) = F.map f ≫ (hom_equiv X Y).symm g . obviously)\n(hom_equiv_naturality_right' : Π {X Y Y'} (f : F.obj X ⟶ Y) (g : Y ⟶ Y'),\n (hom_equiv X Y') (f ≫ g) = (hom_equiv X Y) f ≫ G.map g . obviously)\n\nnamespace core_hom_equiv\n\nrestate_axiom hom_equiv_naturality_left_symm'\nrestate_axiom hom_equiv_naturality_right'\nattribute [simp, priority 10] hom_equiv_naturality_left_symm hom_equiv_naturality_right\n\nvariables {F : C ⥤ D} {G : D ⥤ C} (adj : core_hom_equiv F G) {X' X : C} {Y Y' : D}\n\n@[simp] lemma hom_equiv_naturality_left (f : X' ⟶ X) (g : F.obj X ⟶ Y) :\n (adj.hom_equiv X' Y) (F.map f ≫ g) = f ≫ (adj.hom_equiv X Y) g :=\nby rw [← equiv.eq_symm_apply]; simp\n\n@[simp] lemma hom_equiv_naturality_right_symm (f : X ⟶ G.obj Y) (g : Y ⟶ Y') :\n (adj.hom_equiv X Y').symm (f ≫ G.map g) = (adj.hom_equiv X Y).symm f ≫ g :=\nby rw [equiv.symm_apply_eq]; simp\n\nend core_hom_equiv\n\n/--\nThis is an auxiliary data structure useful for constructing adjunctions.\nSee `adjunction.mk_of_hom_equiv`.\nThis structure won't typically be used anywhere else.\n-/\n@[nolint has_inhabited_instance]\nstructure core_unit_counit (F : C ⥤ D) (G : D ⥤ C) :=\n(unit : 𝟭 C ⟶ F.comp G)\n(counit : G.comp F ⟶ 𝟭 D)\n(left_triangle' : whisker_right unit F ≫ (functor.associator F G F).hom ≫ whisker_left F counit =\n nat_trans.id (𝟭 C ⋙ F) . obviously)\n(right_triangle' : whisker_left G unit ≫ (functor.associator G F G).inv ≫ whisker_right counit G =\n nat_trans.id (G ⋙ 𝟭 C) . obviously)\n\nnamespace core_unit_counit\n\nrestate_axiom left_triangle'\nrestate_axiom right_triangle'\nattribute [simp] left_triangle right_triangle\n\nend core_unit_counit\n\nvariables {F : C ⥤ D} {G : D ⥤ C}\n\n/-- Construct an adjunction between `F` and `G` out of a natural bijection between each\n`F.obj X ⟶ Y` and `X ⟶ G.obj Y`. -/\n@[simps]\ndef mk_of_hom_equiv (adj : core_hom_equiv F G) : F ⊣ G :=\n{ unit :=\n { app := λ X, (adj.hom_equiv X (F.obj X)) (𝟙 (F.obj X)),\n naturality' :=\n begin\n intros,\n erw [← adj.hom_equiv_naturality_left, ← adj.hom_equiv_naturality_right],\n dsimp, simp -- See note [dsimp, simp].\n end },\n counit :=\n { app := λ Y, (adj.hom_equiv _ _).inv_fun (𝟙 (G.obj Y)),\n naturality' :=\n begin\n intros,\n erw [← adj.hom_equiv_naturality_left_symm, ← adj.hom_equiv_naturality_right_symm],\n dsimp, simp\n end },\n hom_equiv_unit' := λ X Y f, by erw [← adj.hom_equiv_naturality_right]; simp,\n hom_equiv_counit' := λ X Y f, by erw [← adj.hom_equiv_naturality_left_symm]; simp,\n .. adj }\n\n/-- Construct an adjunction between functors `F` and `G` given a unit and counit for the adjunction\nsatisfying the triangle identities. -/\n@[simps]\ndef mk_of_unit_counit (adj : core_unit_counit F G) : F ⊣ G :=\n{ hom_equiv := λ X Y,\n { to_fun := λ f, adj.unit.app X ≫ G.map f,\n inv_fun := λ g, F.map g ≫ adj.counit.app Y,\n left_inv := λ f, begin\n change F.map (_ ≫ _) ≫ _ = _,\n rw [F.map_comp, assoc, ←functor.comp_map, adj.counit.naturality, ←assoc],\n convert id_comp f,\n have t := congr_arg (λ t : nat_trans _ _, t.app _) adj.left_triangle,\n dsimp at t,\n simp only [id_comp] at t,\n exact t,\n end,\n right_inv := λ g, begin\n change _ ≫ G.map (_ ≫ _) = _,\n rw [G.map_comp, ←assoc, ←functor.comp_map, ←adj.unit.naturality, assoc],\n convert comp_id g,\n have t := congr_arg (λ t : nat_trans _ _, t.app _) adj.right_triangle,\n dsimp at t,\n simp only [id_comp] at t,\n exact t,\n end },\n .. adj }\n\n/-- The adjunction between the identity functor on a category and itself. -/\ndef id : 𝟭 C ⊣ 𝟭 C :=\n{ hom_equiv := λ X Y, equiv.refl _,\n unit := 𝟙 _,\n counit := 𝟙 _ }\n\n-- Satisfy the inhabited linter.\ninstance : inhabited (adjunction (𝟭 C) (𝟭 C)) := ⟨id⟩\n\n/-- If F and G are naturally isomorphic functors, establish an equivalence of hom-sets. -/\n@[simps]\ndef equiv_homset_left_of_nat_iso\n {F F' : C ⥤ D} (iso : F ≅ F') {X : C} {Y : D} :\n (F.obj X ⟶ Y) ≃ (F'.obj X ⟶ Y) :=\n{ to_fun := λ f, iso.inv.app _ ≫ f,\n inv_fun := λ g, iso.hom.app _ ≫ g,\n left_inv := λ f, by simp,\n right_inv := λ g, by simp }\n\n/-- If G and H are naturally isomorphic functors, establish an equivalence of hom-sets. -/\n@[simps]\ndef equiv_homset_right_of_nat_iso\n {G G' : D ⥤ C} (iso : G ≅ G') {X : C} {Y : D} :\n (X ⟶ G.obj Y) ≃ (X ⟶ G'.obj Y) :=\n{ to_fun := λ f, f ≫ iso.hom.app _,\n inv_fun := λ g, g ≫ iso.inv.app _,\n left_inv := λ f, by simp,\n right_inv := λ g, by simp }\n\n/-- Transport an adjunction along an natural isomorphism on the left. -/\ndef of_nat_iso_left\n {F G : C ⥤ D} {H : D ⥤ C} (adj : F ⊣ H) (iso : F ≅ G) :\n G ⊣ H :=\nadjunction.mk_of_hom_equiv\n{ hom_equiv := λ X Y, (equiv_homset_left_of_nat_iso iso.symm).trans (adj.hom_equiv X Y) }\n\n/-- Transport an adjunction along an natural isomorphism on the right. -/\ndef of_nat_iso_right\n {F : C ⥤ D} {G H : D ⥤ C} (adj : F ⊣ G) (iso : G ≅ H) :\n F ⊣ H :=\nadjunction.mk_of_hom_equiv\n{ hom_equiv := λ X Y, (adj.hom_equiv X Y).trans (equiv_homset_right_of_nat_iso iso) }\n\n/-- Transport being a right adjoint along a natural isomorphism. -/\ndef right_adjoint_of_nat_iso {F G : C ⥤ D} (h : F ≅ G) [r : is_right_adjoint F] :\n is_right_adjoint G :=\n{ left := r.left,\n adj := of_nat_iso_right r.adj h }\n\n/-- Transport being a left adjoint along a natural isomorphism. -/\ndef left_adjoint_of_nat_iso {F G : C ⥤ D} (h : F ≅ G) [r : is_left_adjoint F] : is_left_adjoint G :=\n{ right := r.right,\n adj := of_nat_iso_left r.adj h }\n\nsection\nvariables {E : Type u₃} [ℰ : category.{v₃} E] (H : D ⥤ E) (I : E ⥤ D)\n\n/--\nComposition of adjunctions.\n\nSee https://stacks.math.columbia.edu/tag/0DV0.\n-/\ndef comp (adj₁ : F ⊣ G) (adj₂ : H ⊣ I) : F ⋙ H ⊣ I ⋙ G :=\n{ hom_equiv := λ X Z, equiv.trans (adj₂.hom_equiv _ _) (adj₁.hom_equiv _ _),\n unit := adj₁.unit ≫\n (whisker_left F $ whisker_right adj₂.unit G) ≫ (functor.associator _ _ _).inv,\n counit := (functor.associator _ _ _).hom ≫\n (whisker_left I $ whisker_right adj₁.counit H) ≫ adj₂.counit }\n\n/-- If `F` and `G` are left adjoints then `F ⋙ G` is a left adjoint too. -/\ninstance left_adjoint_of_comp {E : Type u₃} [ℰ : category.{v₃} E] (F : C ⥤ D) (G : D ⥤ E)\n [Fl : is_left_adjoint F] [Gl : is_left_adjoint G] : is_left_adjoint (F ⋙ G) :=\n{ right := Gl.right ⋙ Fl.right,\n adj := comp _ _ Fl.adj Gl.adj }\n\n/-- If `F` and `G` are right adjoints then `F ⋙ G` is a right adjoint too. -/\ninstance right_adjoint_of_comp {E : Type u₃} [ℰ : category.{v₃} E] {F : C ⥤ D} {G : D ⥤ E}\n [Fr : is_right_adjoint F] [Gr : is_right_adjoint G] : is_right_adjoint (F ⋙ G) :=\n{ left := Gr.left ⋙ Fr.left,\n adj := comp _ _ Gr.adj Fr.adj }\n\nend\n\nsection construct_left\n-- Construction of a left adjoint. In order to construct a left\n-- adjoint to a functor G : D → C, it suffices to give the object part\n-- of a functor F : C → D together with isomorphisms Hom(FX, Y) ≃\n-- Hom(X, GY) natural in Y. The action of F on morphisms can be\n-- constructed from this data.\nvariables {F_obj : C → D} {G}\nvariables (e : Π X Y, (F_obj X ⟶ Y) ≃ (X ⟶ G.obj Y))\nvariables (he : ∀ X Y Y' g h, e X Y' (h ≫ g) = e X Y h ≫ G.map g)\ninclude he\n\nprivate lemma he' {X Y Y'} (f g) : (e X Y').symm (f ≫ G.map g) = (e X Y).symm f ≫ g :=\nby intros; rw [equiv.symm_apply_eq, he]; simp\n\n/-- Construct a left adjoint functor to `G`, given the functor's value on objects `F_obj` and\na bijection `e` between `F_obj X ⟶ Y` and `X ⟶ G.obj Y` satisfying a naturality law\n`he : ∀ X Y Y' g h, e X Y' (h ≫ g) = e X Y h ≫ G.map g`.\nDual to `right_adjoint_of_equiv`. -/\n@[simps]\ndef left_adjoint_of_equiv : C ⥤ D :=\n{ obj := F_obj,\n map := λ X X' f, (e X (F_obj X')).symm (f ≫ e X' (F_obj X') (𝟙 _)),\n map_comp' := λ X X' X'' f f', begin\n rw [equiv.symm_apply_eq, he, equiv.apply_symm_apply],\n conv { to_rhs, rw [assoc, ←he, id_comp, equiv.apply_symm_apply] },\n simp\n end }\n\n/-- Show that the functor given by `left_adjoint_of_equiv` is indeed left adjoint to `G`. Dual\nto `adjunction_of_equiv_right`. -/\n@[simps]\ndef adjunction_of_equiv_left : left_adjoint_of_equiv e he ⊣ G :=\nmk_of_hom_equiv\n{ hom_equiv := e,\n hom_equiv_naturality_left_symm' :=\n begin\n intros,\n erw [← he' e he, ← equiv.apply_eq_iff_eq],\n simp [(he _ _ _ _ _).symm]\n end }\n\nend construct_left\n\nsection construct_right\n-- Construction of a right adjoint, analogous to the above.\nvariables {F} {G_obj : D → C}\nvariables (e : Π X Y, (F.obj X ⟶ Y) ≃ (X ⟶ G_obj Y))\nvariables (he : ∀ X' X Y f g, e X' Y (F.map f ≫ g) = f ≫ e X Y g)\ninclude he\n\nprivate lemma he' {X' X Y} (f g) : F.map f ≫ (e X Y).symm g = (e X' Y).symm (f ≫ g) :=\nby intros; rw [equiv.eq_symm_apply, he]; simp\n\n/-- Construct a right adjoint functor to `F`, given the functor's value on objects `G_obj` and\na bijection `e` between `F.obj X ⟶ Y` and `X ⟶ G_obj Y` satisfying a naturality law\n`he : ∀ X Y Y' g h, e X' Y (F.map f ≫ g) = f ≫ e X Y g`.\nDual to `left_adjoint_of_equiv`. -/\n@[simps]\ndef right_adjoint_of_equiv : D ⥤ C :=\n{ obj := G_obj,\n map := λ Y Y' g, (e (G_obj Y) Y') ((e (G_obj Y) Y).symm (𝟙 _) ≫ g),\n map_comp' := λ Y Y' Y'' g g', begin\n rw [← equiv.eq_symm_apply, ← he' e he, equiv.symm_apply_apply],\n conv { to_rhs, rw [← assoc, he' e he, comp_id, equiv.symm_apply_apply] },\n simp\n end }\n\n/-- Show that the functor given by `right_adjoint_of_equiv` is indeed right adjoint to `F`. Dual\nto `adjunction_of_equiv_left`. -/\n@[simps]\ndef adjunction_of_equiv_right : F ⊣ right_adjoint_of_equiv e he :=\nmk_of_hom_equiv\n{ hom_equiv := e,\n hom_equiv_naturality_left_symm' := by intros; rw [equiv.symm_apply_eq, he]; simp,\n hom_equiv_naturality_right' :=\n begin\n intros X Y Y' g h,\n erw [←he, equiv.apply_eq_iff_eq, ←assoc, he' e he, comp_id, equiv.symm_apply_apply]\n end }\n\nend construct_right\n\n/--\nIf the unit and counit of a given adjunction are (pointwise) isomorphisms, then we can upgrade the\nadjunction to an equivalence.\n-/\n@[simps]\nnoncomputable\ndef to_equivalence (adj : F ⊣ G) [∀ X, is_iso (adj.unit.app X)] [∀ Y, is_iso (adj.counit.app Y)] :\n C ≌ D :=\n{ functor := F,\n inverse := G,\n unit_iso := nat_iso.of_components (λ X, as_iso (adj.unit.app X)) (by simp),\n counit_iso := nat_iso.of_components (λ Y, as_iso (adj.counit.app Y)) (by simp) }\n\n/--\nIf the unit and counit for the adjunction corresponding to a right adjoint functor are (pointwise)\nisomorphisms, then the functor is an equivalence of categories.\n-/\n@[simps]\nnoncomputable\ndef is_right_adjoint_to_is_equivalence [is_right_adjoint G]\n [∀ X, is_iso ((adjunction.of_right_adjoint G).unit.app X)]\n [∀ Y, is_iso ((adjunction.of_right_adjoint G).counit.app Y)] :\n is_equivalence G :=\nis_equivalence.of_equivalence_inverse (adjunction.of_right_adjoint G).to_equivalence\n\nend adjunction\n\nopen adjunction\n\nnamespace equivalence\n\n/-- The adjunction given by an equivalence of categories. (To obtain the opposite adjunction,\nsimply use `e.symm.to_adjunction`. -/\ndef to_adjunction (e : C ≌ D) : e.functor ⊣ e.inverse :=\nmk_of_unit_counit ⟨e.unit, e.counit,\n by { ext, dsimp, simp only [id_comp], exact e.functor_unit_comp _, },\n by { ext, dsimp, simp only [id_comp], exact e.unit_inverse_comp _, }⟩\n\nend equivalence\n\nnamespace functor\n\n/-- An equivalence `E` is left adjoint to its inverse. -/\ndef adjunction (E : C ⥤ D) [is_equivalence E] : E ⊣ E.inv :=\n(E.as_equivalence).to_adjunction\n\n/-- If `F` is an equivalence, it's a left adjoint. -/\n@[priority 10]\ninstance left_adjoint_of_equivalence {F : C ⥤ D} [is_equivalence F] : is_left_adjoint F :=\n{ right := _,\n adj := functor.adjunction F }\n\n@[simp]\nlemma right_adjoint_of_is_equivalence {F : C ⥤ D} [is_equivalence F] : right_adjoint F = inv F :=\nrfl\n\n/-- If `F` is an equivalence, it's a right adjoint. -/\n@[priority 10]\ninstance right_adjoint_of_equivalence {F : C ⥤ D} [is_equivalence F] : is_right_adjoint F :=\n{ left := _,\n adj := functor.adjunction F.inv }\n\n@[simp]\nlemma left_adjoint_of_is_equivalence {F : C ⥤ D} [is_equivalence F] : left_adjoint F = inv F :=\nrfl\n\nend functor\n\nend category_theory\n", "meta": {"author": "JLimperg", "repo": "aesop3", "sha": "a4a116f650cc7403428e72bd2e2c4cda300fe03f", "save_path": "github-repos/lean/JLimperg-aesop3", "path": "github-repos/lean/JLimperg-aesop3/aesop3-a4a116f650cc7403428e72bd2e2c4cda300fe03f/src/category_theory/adjunction/basic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44167302036300954, "lm_q2_score": 0.06754669348597105, "lm_q1q2_score": 0.029833552127483252}} {"text": "/-\nCopyright (c) 2023 Devon Tuma. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Devon Tuma\n-/\nimport computational_monads.simulation_semantics.simulate.support\nimport computational_monads.simulation_semantics.simulate.eval_dist\nimport computational_monads.simulation_semantics.simulate.subsingleton\nimport computational_monads.support.prod\n\n/-!\n# Tracking Simulation Oracles\n\nThis file defines a typeclass `sim_oracle.is_tracking` for oracles in which the\nquery responses are independent of the current oracle state. For example in `logging_oracle`\nthe internal state doesn't change the input and output, it just records them.\nThis allows for many lemmas to be automatically shared between these sorts of oracles.\n`sim_oracle.is_stateless` extends this further to oracles with no internal state at all.\n-/\n\nvariables {α β γ : Type} {spec spec' spec'' : oracle_spec} {S S' : Type}\n\nopen_locale big_operators ennreal\nopen oracle_comp oracle_spec\n\nnamespace sim_oracle\n\n/-- Typeclass for oracles in which the query responses are independent of the current oracle state.\nWe define this in terms of the existence of two functions `query_f` and `state_f`\nthat represent the behaviour of the oracle result and state update respectively.\n`eval_dist_apply` asserts that the oracle behaviour is captured exactly by these two functions. -/\nclass is_tracking (so : sim_oracle spec spec' S) :=\n(query_f : Π (i : spec.ι), spec.domain i → oracle_comp spec' (spec.range i))\n(state_f : Π (s : S) (i : spec.ι), spec.domain i → spec.range i → S)\n(apply_equiv_state_f_map_query_f : ∀ (i : spec.ι) (t : spec.domain i) (s : S),\n so i (t, s) ≃ₚ (λ u, (u, state_f s i t u)) <$> query_f i t)\n\nvariables (so : sim_oracle spec spec' S) (i : spec.ι)\n (t t' : spec.domain i) (s s' : S) (u u' : spec.range i)\n\n/-- Alias to be able to refer to the query function from the `sim_oracle` namespace. -/\n@[inline, reducible] def answer_query [hso : so.is_tracking] (i : spec.ι) (t : spec.domain i) :\n oracle_comp spec' (spec.range i) := hso.query_f i t\n\n/-- Alias to be able to refer to the state update function from the `sim_oracle` namespace. -/\n@[inline, reducible] def update_state [hso : so.is_tracking] (s : S) (i : spec.ι)\n (t : spec.domain i) (u : spec.range i) : S := hso.state_f s i t u\n\nnamespace is_tracking\n\nvariable [hso : so.is_tracking]\ninclude hso\n\nsection support\n\nlemma support_apply' : (so i (t, s)).support =\n ((λ u, (u, so.update_state s i t u)) <$> so.answer_query i t).support :=\nby simp_rw [← support_eval_dist, (hso.apply_equiv_state_f_map_query_f _ _ _).eval_dist_eq]\n\n@[simp] lemma support_apply : (so i (t, s)).support =\n (λ u, (u, so.update_state s i t u)) '' (so.answer_query i t).support :=\nby rw [support_apply', support_map]\n\nend support\n\nsection fin_support\n\nvariables [∀ i t, (so.o i t).decidable] [∀ i t, (so.answer_query i t).decidable]\n\nlemma fin_support_apply' [decidable_eq S] : (so i (t, s)).fin_support =\n ((λ u, (u, so.update_state s i t u)) <$> so.answer_query i t).fin_support :=\nby rw [fin_support_eq_fin_support_iff_support_eq_support, support_apply']\n\n@[simp] lemma fin_support_apply [decidable_eq S] : (so i (t, s)).fin_support =\n (so.answer_query i t).fin_support.image (λ u, (u, so.update_state s i t u)) :=\nby rw [fin_support_apply', fin_support_map]\n\nend fin_support\n\nsection eval_dist\n\nlemma eval_dist_apply' : ⁅so i (t, s)⁆ =\n ⁅(λ u, (u, so.update_state s i t u)) <$> so.answer_query i t⁆ :=\napply_equiv_state_f_map_query_f i t s\n\n@[simp] lemma eval_dist_apply : ⁅so i (t, s)⁆ =\n ⁅so.answer_query i t⁆.map (λ u, (u, so.update_state s i t u)) :=\nby rw [eval_dist_apply', eval_dist_map]\n\nend eval_dist\n\nsection prob_event\n\nlemma prob_event_apply' (e : set (spec.range i × S)) : ⁅e | so i (t, s)⁆ =\n ⁅e | (λ u, (u, so.update_state s i t u)) <$> so.answer_query i t⁆ :=\nprob_event_eq_of_eval_dist_eq (eval_dist_apply' so i t s) e\n\n@[simp] lemma prob_event_apply (e : set (spec.range i × S)) : ⁅e | so i (t, s)⁆ =\n ⁅(λ u, (u, so.update_state s i t u)) ⁻¹' e | so.answer_query i t⁆ :=\nby rw [prob_event_apply', prob_event_map]\n\nend prob_event\n\nend is_tracking\n\nend sim_oracle", "meta": {"author": "dtumad", "repo": "lean-crypto-formalization", "sha": "f975a9a9882120b509553a7ced9aa05b745ff154", "save_path": "github-repos/lean/dtumad-lean-crypto-formalization", "path": "github-repos/lean/dtumad-lean-crypto-formalization/lean-crypto-formalization-f975a9a9882120b509553a7ced9aa05b745ff154/src/computational_monads/simulation_semantics/is_tracking.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.480478678047907, "lm_q2_score": 0.06187598572364272, "lm_q1q2_score": 0.02973009182340702}} {"text": "/-\nCopyright (c) 2022 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Leonardo de Moura\n-/\nimport Lean.Meta.Eqns\nimport Lean.Util.CollectFVars\nimport Lean.Util.ForEachExprWhere\nimport Lean.Meta.Tactic.Split\nimport Lean.Meta.Tactic.Apply\nimport Lean.Meta.Tactic.Refl\nimport Lean.Meta.Match.MatchEqs\n\nnamespace Lean.Elab.Eqns\nopen Meta\n\nstructure EqnInfoCore where\n declName : Name\n levelParams : List Name\n type : Expr\n value : Expr\n deriving Inhabited\n\npartial def expand : Expr → Expr\n | Expr.letE _ _ v b _ => expand (b.instantiate1 v)\n | Expr.mdata _ b => expand b\n | e => e\n\ndef expandRHS? (mvarId : MVarId) : MetaM (Option MVarId) := do\n let target ← mvarId.getType'\n let some (_, lhs, rhs) := target.eq? | return none\n unless rhs.isLet || rhs.isMData do return none\n return some (← mvarId.replaceTargetDefEq (← mkEq lhs (expand rhs)))\n\ndef funext? (mvarId : MVarId) : MetaM (Option MVarId) := do\n let target ← mvarId.getType'\n let some (_, _, rhs) := target.eq? | return none\n unless rhs.isLambda do return none\n commitWhenSome? do\n let [mvarId] ← mvarId.apply (← mkConstWithFreshMVarLevels ``funext) | return none\n let (_, mvarId) ← mvarId.intro1\n return some mvarId\n\ndef simpMatch? (mvarId : MVarId) : MetaM (Option MVarId) := do\n let mvarId' ← Split.simpMatchTarget mvarId\n if mvarId != mvarId' then return some mvarId' else return none\n\ndef simpIf? (mvarId : MVarId) : MetaM (Option MVarId) := do\n let mvarId' ← simpIfTarget mvarId (useDecide := true)\n if mvarId != mvarId' then return some mvarId' else return none\n\nprivate def findMatchToSplit? (env : Environment) (e : Expr) (declNames : Array Name) (exceptionSet : ExprSet) : Option Expr :=\n e.findExt? fun e => Id.run do\n if e.hasLooseBVars || exceptionSet.contains e then\n return Expr.FindStep.visit\n else if let some info := isMatcherAppCore? env e then\n let args := e.getAppArgs\n -- If none of the discriminants is a free variable, then it is not worth splitting the match\n let mut hasFVarDiscr := false\n for i in [info.getFirstDiscrPos : info.getFirstDiscrPos + info.numDiscrs] do\n let discr := args[i]!\n if discr.isFVar then\n hasFVarDiscr := true\n break\n unless hasFVarDiscr do\n return Expr.FindStep.visit\n -- At least one alternative must contain a `declNames` application with loose bound variables.\n for i in [info.getFirstAltPos : info.getFirstAltPos + info.numAlts] do\n let alt := args[i]!\n if Option.isSome <| alt.find? fun e => declNames.any e.isAppOf && e.hasLooseBVars then\n return Expr.FindStep.found\n return Expr.FindStep.visit\n else\n let Expr.const declName .. := e.getAppFn | return Expr.FindStep.visit\n if declName == ``WellFounded.fix || isBRecOnRecursor env declName then\n -- We should not go inside unfolded nested recursive applications\n return Expr.FindStep.done\n else\n return Expr.FindStep.visit\n\npartial def splitMatch? (mvarId : MVarId) (declNames : Array Name) : MetaM (Option (List MVarId)) := commitWhenSome? do\n let target ← mvarId.getType'\n let rec go (badCases : ExprSet) : MetaM (Option (List MVarId)) := do\n if let some e := findMatchToSplit? (← getEnv) target declNames badCases then\n try\n Meta.Split.splitMatch mvarId e\n catch _ =>\n go (badCases.insert e)\n else\n trace[Meta.Tactic.split] \"did not find term to split\\n{MessageData.ofGoal mvarId}\"\n return none\n go {}\n\nstructure Context where\n declNames : Array Name\n\nprivate def lhsDependsOn (type : Expr) (fvarId : FVarId) : MetaM Bool :=\n forallTelescope type fun _ type => do\n if let some (_, lhs, _) ← matchEq? type then\n dependsOn lhs fvarId\n else\n dependsOn type fvarId\n\n/-- Try to close goal using `rfl` with smart unfolding turned off. -/\ndef tryURefl (mvarId : MVarId) : MetaM Bool :=\n withOptions (smartUnfolding.set · false) do\n try mvarId.refl; return true catch _ => return false\n\n/--\n Eliminate `namedPatterns` from equation, and trivial hypotheses.\n-/\ndef simpEqnType (eqnType : Expr) : MetaM Expr := do\n forallTelescopeReducing (← instantiateMVars eqnType) fun ys type => do\n let proofVars := collect type\n trace[Elab.definition] \"simpEqnType type: {type}\"\n let mut type ← Match.unfoldNamedPattern type\n let mut eliminated : FVarIdSet := {}\n for y in ys.reverse do\n trace[Elab.definition] \">> simpEqnType: {← inferType y}, {type}\"\n if proofVars.contains y.fvarId! then\n let some (_, Expr.fvar fvarId, rhs) ← matchEq? (← inferType y) | throwError \"unexpected hypothesis in altenative{indentExpr eqnType}\"\n eliminated := eliminated.insert fvarId\n type := type.replaceFVarId fvarId rhs\n else if eliminated.contains y.fvarId! then\n if (← dependsOn type y.fvarId!) then\n type ← mkForallFVars #[y] type\n else\n if let some (_, lhs, rhs) ← matchEq? (← inferType y) then\n if (← isDefEq lhs rhs) then\n if !(← dependsOn type y.fvarId!) then\n continue\n else if !(← lhsDependsOn type y.fvarId!) then\n -- Since the `lhs` of the `type` does not depend on `y`, we replace it with `Eq.refl` in the `rhs`\n type := type.replaceFVar y (← mkEqRefl lhs)\n continue\n type ← mkForallFVars #[y] type\n return type\nwhere\n -- Collect eq proof vars used in `namedPatterns`\n collect (e : Expr) : FVarIdSet :=\n let go (e : Expr) (ω) : ST ω FVarIdSet := do\n let ref ← ST.mkRef {}\n e.forEachWhere Match.isNamedPattern fun e => do\n let some e := Match.isNamedPattern? e | unreachable!\n let arg := e.appArg!.consumeMData\n if arg.isFVar then\n ST.Prim.Ref.modify ref (·.insert arg.fvarId!)\n ST.Prim.Ref.get ref\n runST (go e)\n\nprivate partial def saveEqn (mvarId : MVarId) : StateRefT (Array Expr) MetaM Unit := mvarId.withContext do\n let target ← mvarId.getType'\n let fvarState := collectFVars {} target\n let fvarState ← (← getLCtx).foldrM (init := fvarState) fun decl fvarState => do\n if fvarState.fvarSet.contains decl.fvarId then\n return collectFVars fvarState (← instantiateMVars decl.type)\n else\n return fvarState\n let mut fvarIdSet := fvarState.fvarSet\n let mut fvarIds ← sortFVarIds <| fvarState.fvarSet.toArray\n -- Include (relevant) propositions that are not already in `fvarIdSet`\n let mut modified := false\n repeat\n modified := false\n for decl in (← getLCtx) do\n unless fvarIdSet.contains decl.fvarId do\n if (← isProp decl.type) then\n let type ← instantiateMVars decl.type\n unless (← isIrrelevant fvarIdSet type) do\n modified := true\n (fvarIdSet, fvarIds) ← pushDecl fvarIdSet fvarIds decl\n until !modified\n let type ← mkForallFVars (fvarIds.map mkFVar) target\n let type ← simpEqnType type\n modify (·.push type)\nwhere\n /--\n We say the type/proposition is \"irrelevant\" if\n 1- It does not contain any variable in `fvarIdSet` OR\n 2- It is of the form `x = t` or `t = x` where `x` is a free variable\n that is not in `fvarIdSet`. This can of equality can be eliminated by substitution. -/\n isIrrelevant (fvarIdSet : FVarIdSet) (type : Expr) : MetaM Bool := do\n if Option.isNone <| type.find? fun e => e.isFVar && fvarIdSet.contains e.fvarId! then\n return true\n else if let some (_, lhs, rhs) := type.eq? then\n return (lhs.isFVar && !fvarIdSet.contains lhs.fvarId!)\n || (rhs.isFVar && !fvarIdSet.contains rhs.fvarId!)\n else\n return false\n\n pushDecl (fvarIdSet : FVarIdSet) (fvarIds : Array FVarId) (localDecl : LocalDecl) : MetaM (FVarIdSet × Array FVarId) := do\n let (fvarIdSet, fvarIds) ← collectDeps fvarIdSet fvarIds (← instantiateMVars localDecl.type)\n return (fvarIdSet.insert localDecl.fvarId, fvarIds.push localDecl.fvarId)\n\n collectDeps (fvarIdSet : FVarIdSet) (fvarIds : Array FVarId) (type : Expr) : MetaM (FVarIdSet × Array FVarId) := do\n let s := collectFVars {} type\n let usedFVarIds ← sortFVarIds <| s.fvarSet.toArray\n let mut fvarIdSet := fvarIdSet\n let mut fvarIds := fvarIds\n for fvarId in usedFVarIds do\n unless fvarIdSet.contains fvarId do\n (fvarIdSet, fvarIds) ← pushDecl fvarIdSet fvarIds (← fvarId.getDecl)\n return (fvarIdSet, fvarIds)\n\n/--\n Quick filter for deciding whether to use `simpMatch?` at `mkEqnTypes`.\n If the result is `false`, then it is not worth trying `simpMatch`.\n-/\nprivate def shouldUseSimpMatch (e : Expr) : MetaM Bool := do\n let env ← getEnv\n return Option.isSome <| e.find? fun e => Id.run do\n if let some info := isMatcherAppCore? env e then\n let args := e.getAppArgs\n for discr in args[info.getFirstDiscrPos : info.getFirstDiscrPos + info.numDiscrs] do\n if discr.isConstructorApp env then\n return true\n return false\n\npartial def mkEqnTypes (declNames : Array Name) (mvarId : MVarId) : MetaM (Array Expr) := do\n let (_, eqnTypes) ← go mvarId |>.run { declNames } |>.run #[]\n return eqnTypes\nwhere\n go (mvarId : MVarId) : ReaderT Context (StateRefT (Array Expr) MetaM) Unit := do\n trace[Elab.definition.eqns] \"mkEqnTypes step\\n{MessageData.ofGoal mvarId}\"\n if (← tryURefl mvarId) then\n saveEqn mvarId\n return ()\n\n if let some mvarId ← expandRHS? mvarId then\n return (← go mvarId)\n-- The following `funext?` was producing an overapplied `lhs`. Possible refinement: only do it if we want to apply `splitMatch` on the body of the lambda\n/- if let some mvarId ← funext? mvarId then\n return (← go mvarId) -/\n\n if (← shouldUseSimpMatch (← mvarId.getType')) then\n if let some mvarId ← simpMatch? mvarId then\n return (← go mvarId)\n\n if let some mvarIds ← splitMatch? mvarId declNames then\n return (← mvarIds.forM go)\n\n saveEqn mvarId\n\n/--\n Some of the hypotheses added by `mkEqnTypes` may not be used by the actual proof (i.e., `value` argument).\n This method eliminates them.\n\n Alternative solution: improve `saveEqn` and make sure it never includes unnecessary hypotheses.\n These hypotheses are leftovers from tactics such as `splitMatch?` used in `mkEqnTypes`.\n-/\ndef removeUnusedEqnHypotheses (declType declValue : Expr) : CoreM (Expr × Expr) := do\n go declType declValue #[] {}\nwhere\n go (type value : Expr) (xs : Array Expr) (lctx : LocalContext) : CoreM (Expr × Expr) := do\n match value with\n | .lam n d b bi =>\n let d := d.instantiateRev xs\n let fvarId ← mkFreshFVarId\n go (type.bindingBody!) b (xs.push (mkFVar fvarId)) (lctx.mkLocalDecl fvarId n d bi)\n | _ =>\n let type := type.instantiateRev xs\n let value := value.instantiateRev xs\n let mut s := collectFVars (collectFVars {} type) value\n let mut xsNew := #[]\n for x in xs.reverse do\n if s.fvarSet.contains x.fvarId! then\n s := collectFVars s (lctx.getFVar! x).type\n xsNew := xsNew.push x\n if xsNew.size == xs.size then\n return (declType, declValue)\n else\n xsNew := xsNew.reverse\n return (lctx.mkForall xsNew type, lctx.mkLambda xsNew value)\n\n/-- Delta reduce the equation left-hand-side -/\ndef deltaLHS (mvarId : MVarId) : MetaM MVarId := mvarId.withContext do\n let target ← mvarId.getType'\n let some (_, lhs, rhs) := target.eq? | throwTacticEx `deltaLHS mvarId \"equality expected\"\n let some lhs ← delta? lhs | throwTacticEx `deltaLHS mvarId \"failed to delta reduce lhs\"\n mvarId.replaceTargetDefEq (← mkEq lhs rhs)\n\ndef deltaRHS? (mvarId : MVarId) (declName : Name) : MetaM (Option MVarId) := mvarId.withContext do\n let target ← mvarId.getType'\n let some (_, lhs, rhs) := target.eq? | return none\n let some rhs ← delta? rhs.consumeMData (· == declName) | return none\n mvarId.replaceTargetDefEq (← mkEq lhs rhs)\n\nprivate partial def whnfAux (e : Expr) : MetaM Expr := do\n let e ← whnfI e -- Must reduce instances too, otherwise it will not be able to reduce `(Nat.rec ... ... (OfNat.ofNat 0))`\n let f := e.getAppFn\n match f with\n | .proj _ _ s => return mkAppN (f.updateProj! (← whnfAux s)) e.getAppArgs\n | _ => return e\n\n/-- Apply `whnfR` to lhs, return `none` if `lhs` was not modified -/\ndef whnfReducibleLHS? (mvarId : MVarId) : MetaM (Option MVarId) := mvarId.withContext do\n let target ← mvarId.getType'\n let some (_, lhs, rhs) := target.eq? | return none\n let lhs' ← whnfAux lhs\n if lhs' != lhs then\n return some (← mvarId.replaceTargetDefEq (← mkEq lhs' rhs))\n else\n return none\n\ndef tryContradiction (mvarId : MVarId) : MetaM Bool := do\n mvarId.contradictionCore { genDiseq := true }\n\nstructure UnfoldEqnExtState where\n map : PHashMap Name Name := {}\n deriving Inhabited\n\n/- We generate the unfold equation on demand, and do not save them on .olean files. -/\nbuiltin_initialize unfoldEqnExt : EnvExtension UnfoldEqnExtState ←\n registerEnvExtension (pure {})\n\n/--\n Auxiliary method for `mkUnfoldEq`. The structure is based on `mkEqnTypes`.\n `mvarId` is the goal to be proved. It is a goal of the form\n ```\n declName x_1 ... x_n = body[x_1, ..., x_n]\n ```\n The proof is constracted using the automatically generated equational theorems.\n We basically keep splitting the `match` and `if-then-else` expressions in the right hand side\n until one of the equational theorems is applicable.\n-/\npartial def mkUnfoldProof (declName : Name) (mvarId : MVarId) : MetaM Unit := do\n let some eqs ← getEqnsFor? declName | throwError \"failed to generate equations for '{declName}'\"\n let tryEqns (mvarId : MVarId) : MetaM Bool :=\n eqs.anyM fun eq => commitWhen do\n try\n let subgoals ← mvarId.apply (← mkConstWithFreshMVarLevels eq)\n subgoals.allM fun subgoal => do\n if (← subgoal.isAssigned) then\n return true -- Subgoal was already solved. This can happen when there are dependencies between the subgoals\n else\n subgoal.assumptionCore\n catch _ =>\n return false\n let rec go (mvarId : MVarId) : MetaM Unit := do\n if (← tryEqns mvarId) then\n return ()\n -- Remark: we removed funext? from `mkEqnTypes`\n -- else if let some mvarId ← funext? mvarId then\n -- go mvarId\n\n if (← shouldUseSimpMatch (← mvarId.getType')) then\n if let some mvarId ← simpMatch? mvarId then\n return (← go mvarId)\n\n if let some mvarIds ← splitTarget? mvarId (splitIte := false) then\n return (← mvarIds.forM go)\n\n if (← tryContradiction mvarId) then\n return ()\n\n throwError \"failed to generate unfold theorem for '{declName}'\\n{MessageData.ofGoal mvarId}\"\n go mvarId\n\n/-- Generate the \"unfold\" lemma for `declName`. -/\ndef mkUnfoldEq (declName : Name) (info : EqnInfoCore) : MetaM Name := withLCtx {} {} do\n let env ← getEnv\n withOptions (tactic.hygienic.set · false) do\n let baseName := mkPrivateName env declName\n lambdaTelescope info.value fun xs body => do\n let us := info.levelParams.map mkLevelParam\n let type ← mkEq (mkAppN (Lean.mkConst declName us) xs) body\n let goal ← mkFreshExprSyntheticOpaqueMVar type\n mkUnfoldProof declName goal.mvarId!\n let type ← mkForallFVars xs type\n let value ← mkLambdaFVars xs (← instantiateMVars goal)\n let name := baseName ++ `_unfold\n addDecl <| Declaration.thmDecl {\n name, type, value\n levelParams := info.levelParams\n }\n return name\n\ndef getUnfoldFor? (declName : Name) (getInfo? : Unit → Option EqnInfoCore) : MetaM (Option Name) := do\n let env ← getEnv\n if let some eq := unfoldEqnExt.getState env |>.map.find? declName then\n return some eq\n else if let some info := getInfo? () then\n let eq ← mkUnfoldEq declName info\n modifyEnv fun env => unfoldEqnExt.modifyState env fun s => { s with map := s.map.insert declName eq }\n return some eq\n else\n return none\n\nbuiltin_initialize\n registerTraceClass `Elab.definition.unfoldEqn\n registerTraceClass `Elab.definition.eqns\n\nend Lean.Elab.Eqns\n", "meta": {"author": "leanprover", "repo": "lean4", "sha": "742d053a97bdd109a41a921facd1cd6a55e89bc7", "save_path": "github-repos/lean/leanprover-lean4", "path": "github-repos/lean/leanprover-lean4/lean4-742d053a97bdd109a41a921facd1cd6a55e89bc7/src/Lean/Elab/PreDefinition/Eqns.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.480478678047907, "lm_q2_score": 0.06187597923634635, "lm_q1q2_score": 0.029730088706399437}} {"text": "/- Additional theroems for option. -/\nnamespace option\n\ntheorem failure_is_none (α : Type _) : (failure : option α) = none := rfl\n\ntheorem coe_is_some {α : Type _} (x:α) : (coe x : option α) = some x := rfl\n\ntheorem or_else_none {α : Type _} (x : option α) : (x <|> none) = x :=\nbegin\n cases x; trivial,\nend\n\ntheorem none_or_else {α : Type _} (x : option α) : (none <|> x) = x :=\nbegin\n cases x; trivial,\nend\n\ntheorem some_or_else {α : Type _} (x : α) (y : option α) : (some x <|> y) = some x :=\nbegin\n trivial,\nend\n\nend option\n", "meta": {"author": "joehendrix", "repo": "lean-containers", "sha": "ef6ff0533eada75f18922039f8312badf12e6124", "save_path": "github-repos/lean/joehendrix-lean-containers", "path": "github-repos/lean/joehendrix-lean-containers/lean-containers-ef6ff0533eada75f18922039f8312badf12e6124/data/containers/utils/option.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.38491214448393346, "lm_q2_score": 0.07696083410820614, "lm_q1q2_score": 0.02962315969786188}} {"text": "open Lean.Parser.Tactic in\nmacro \"rw0\" s:rwRuleSeq : tactic =>\n `(tactic| rw (config := { offsetCnstrs := false }) $s:rwRuleSeq)\n\nexample (m n : Nat) : Nat.ble (n+1) (n+0) = false := by\n rw0 [Nat.add_zero]\n trace_state\n admit\n", "meta": {"author": "leanprover", "repo": "lean4", "sha": "742d053a97bdd109a41a921facd1cd6a55e89bc7", "save_path": "github-repos/lean/leanprover-lean4", "path": "github-repos/lean/leanprover-lean4/lean4-742d053a97bdd109a41a921facd1cd6a55e89bc7/tests/lean/rwWithoutOffsetCnstrs.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.36296920551961687, "lm_q2_score": 0.08151974760686585, "lm_q1q2_score": 0.02958915802302379}} {"text": "/-\nCopyright (c) 2017 Johannes Hölzl. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthor: Johannes Hölzl\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.default\nimport Mathlib.tactic.lint.default\nimport Mathlib.tactic.ext\nimport Mathlib.PostPort\n\nuniverses u_1 u_4 u_2 u_3 u_5 u_6 \n\nnamespace Mathlib\n\nnamespace sigma\n\n\nprotected instance inhabited {α : Type u_1} {β : α → Type u_4} [Inhabited α]\n [Inhabited (β Inhabited.default)] : Inhabited (sigma β) :=\n { default := mk Inhabited.default Inhabited.default }\n\nprotected instance decidable_eq {α : Type u_1} {β : α → Type u_4} [h₁ : DecidableEq α]\n [h₂ : (a : α) → DecidableEq (β a)] : DecidableEq (sigma β) :=\n sorry\n\n@[simp] theorem mk.inj_iff {α : Type u_1} {β : α → Type u_4} {a₁ : α} {a₂ : α} {b₁ : β a₁}\n {b₂ : β a₂} : mk a₁ b₁ = mk a₂ b₂ ↔ a₁ = a₂ ∧ b₁ == b₂ :=\n sorry\n\n@[simp] theorem eta {α : Type u_1} {β : α → Type u_4} (x : sigma fun (a : α) => β a) :\n mk (fst x) (snd x) = x :=\n cases_on x\n fun (x_fst : α) (x_snd : β x_fst) =>\n idRhs\n (mk (fst (mk x_fst x_snd)) (snd (mk x_fst x_snd)) =\n mk (fst (mk x_fst x_snd)) (snd (mk x_fst x_snd)))\n rfl\n\ntheorem ext {α : Type u_1} {β : α → Type u_4} {x₀ : sigma β} {x₁ : sigma β} (h₀ : fst x₀ = fst x₁)\n (h₁ : snd x₀ == snd x₁) : x₀ = x₁ :=\n sorry\n\ntheorem ext_iff {α : Type u_1} {β : α → Type u_4} {x₀ : sigma β} {x₁ : sigma β} :\n x₀ = x₁ ↔ fst x₀ = fst x₁ ∧ snd x₀ == snd x₁ :=\n cases_on x₀\n fun (x₀_fst : α) (x₀_snd : β x₀_fst) =>\n cases_on x₁ fun (x₁_fst : α) (x₁_snd : β x₁_fst) => mk.inj_iff\n\n@[simp] theorem forall {α : Type u_1} {β : α → Type u_4} {p : (sigma fun (a : α) => β a) → Prop} :\n (∀ (x : sigma fun (a : α) => β a), p x) ↔ ∀ (a : α) (b : β a), p (mk a b) :=\n sorry\n\n@[simp] theorem exists {α : Type u_1} {β : α → Type u_4} {p : (sigma fun (a : α) => β a) → Prop} :\n (∃ (x : sigma fun (a : α) => β a), p x) ↔ ∃ (a : α), ∃ (b : β a), p (mk a b) :=\n sorry\n\n/-- Map the left and right components of a sigma -/\ndef map {α₁ : Type u_2} {α₂ : Type u_3} {β₁ : α₁ → Type u_5} {β₂ : α₂ → Type u_6} (f₁ : α₁ → α₂)\n (f₂ : (a : α₁) → β₁ a → β₂ (f₁ a)) (x : sigma β₁) : sigma β₂ :=\n mk (f₁ (fst x)) (f₂ (fst x) (snd x))\n\nend sigma\n\n\ntheorem sigma_mk_injective {α : Type u_1} {β : α → Type u_4} {i : α} :\n function.injective (sigma.mk i) :=\n sorry\n\ntheorem function.injective.sigma_map {α₁ : Type u_2} {α₂ : Type u_3} {β₁ : α₁ → Type u_5}\n {β₂ : α₂ → Type u_6} {f₁ : α₁ → α₂} {f₂ : (a : α₁) → β₁ a → β₂ (f₁ a)}\n (h₁ : function.injective f₁) (h₂ : ∀ (a : α₁), function.injective (f₂ a)) :\n function.injective (sigma.map f₁ f₂) :=\n sorry\n\ntheorem function.surjective.sigma_map {α₁ : Type u_2} {α₂ : Type u_3} {β₁ : α₁ → Type u_5}\n {β₂ : α₂ → Type u_6} {f₁ : α₁ → α₂} {f₂ : (a : α₁) → β₁ a → β₂ (f₁ a)}\n (h₁ : function.surjective f₁) (h₂ : ∀ (a : α₁), function.surjective (f₂ a)) :\n function.surjective (sigma.map f₁ f₂) :=\n sorry\n\n/-- Interpret a function on `Σ x : α, β x` as a dependent function with two arguments. -/\ndef sigma.curry {α : Type u_1} {β : α → Type u_4} {γ : (a : α) → β a → Type u_2}\n (f : (x : sigma β) → γ (sigma.fst x) (sigma.snd x)) (x : α) (y : β x) : γ x y :=\n f (sigma.mk x y)\n\n/-- Interpret a dependent function with two arguments as a function on `Σ x : α, β x` -/\ndef sigma.uncurry {α : Type u_1} {β : α → Type u_4} {γ : (a : α) → β a → Type u_2}\n (f : (x : α) → (y : β x) → γ x y) (x : sigma β) : γ (sigma.fst x) (sigma.snd x) :=\n f (sigma.fst x) (sigma.snd x)\n\n/-- Convert a product type to a Σ-type. -/\n@[simp] def prod.to_sigma {α : Type u_1} {β : Type u_2} : α × β → sigma fun (_x : α) => β := sorry\n\n@[simp] theorem prod.fst_to_sigma {α : Type u_1} {β : Type u_2} (x : α × β) :\n sigma.fst (prod.to_sigma x) = prod.fst x :=\n prod.cases_on x fun (x_fst : α) (x_snd : β) => Eq.refl (sigma.fst (prod.to_sigma (x_fst, x_snd)))\n\n@[simp] theorem prod.snd_to_sigma {α : Type u_1} {β : Type u_2} (x : α × β) :\n sigma.snd (prod.to_sigma x) = prod.snd x :=\n prod.cases_on x fun (x_fst : α) (x_snd : β) => Eq.refl (sigma.snd (prod.to_sigma (x_fst, x_snd)))\n\nnamespace psigma\n\n\n/-- Nondependent eliminator for `psigma`. -/\ndef elim {α : Sort u_1} {β : α → Sort u_2} {γ : Sort u_3} (f : (a : α) → β a → γ) (a : psigma β) :\n γ :=\n cases_on a f\n\n@[simp] theorem elim_val {α : Sort u_1} {β : α → Sort u_2} {γ : Sort u_3} (f : (a : α) → β a → γ)\n (a : α) (b : β a) : elim f (mk a b) = f a b :=\n rfl\n\nprotected instance inhabited {α : Sort u_1} {β : α → Sort u_2} [Inhabited α]\n [Inhabited (β Inhabited.default)] : Inhabited (psigma β) :=\n { default := mk Inhabited.default Inhabited.default }\n\nprotected instance decidable_eq {α : Sort u_1} {β : α → Sort u_2} [h₁ : DecidableEq α]\n [h₂ : (a : α) → DecidableEq (β a)] : DecidableEq (psigma β) :=\n sorry\n\ntheorem mk.inj_iff {α : Sort u_1} {β : α → Sort u_2} {a₁ : α} {a₂ : α} {b₁ : β a₁} {b₂ : β a₂} :\n mk a₁ b₁ = mk a₂ b₂ ↔ a₁ = a₂ ∧ b₁ == b₂ :=\n sorry\n\ntheorem ext {α : Sort u_1} {β : α → Sort u_2} {x₀ : psigma β} {x₁ : psigma β} (h₀ : fst x₀ = fst x₁)\n (h₁ : snd x₀ == snd x₁) : x₀ = x₁ :=\n sorry\n\ntheorem ext_iff {α : Sort u_1} {β : α → Sort u_2} {x₀ : psigma β} {x₁ : psigma β} :\n x₀ = x₁ ↔ fst x₀ = fst x₁ ∧ snd x₀ == snd x₁ :=\n cases_on x₀\n fun (x₀_fst : α) (x₀_snd : β x₀_fst) =>\n cases_on x₁ fun (x₁_fst : α) (x₁_snd : β x₁_fst) => mk.inj_iff\n\n/-- Map the left and right components of a sigma -/\ndef map {α₁ : Sort u_3} {α₂ : Sort u_4} {β₁ : α₁ → Sort u_5} {β₂ : α₂ → Sort u_6} (f₁ : α₁ → α₂)\n (f₂ : (a : α₁) → β₁ a → β₂ (f₁ a)) : psigma β₁ → psigma β₂ :=\n sorry\n\nend Mathlib", "meta": {"author": "AurelienSaue", "repo": "Mathlib4_auto", "sha": "590df64109b08190abe22358fabc3eae000943f2", "save_path": "github-repos/lean/AurelienSaue-Mathlib4_auto", "path": "github-repos/lean/AurelienSaue-Mathlib4_auto/Mathlib4_auto-590df64109b08190abe22358fabc3eae000943f2/Mathlib/data/sigma/basic_auto.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4921881357207955, "lm_q2_score": 0.06008665311947338, "lm_q1q2_score": 0.029573937780575724}} {"text": "/-\nCopyright (c) 2019 Simon Hudon. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthor: Simon Hudon\n\nMonad encapsulating continuation passing programming style, similar to\nHaskell's `Cont`, `ContT` and `MonadCont`:\n\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.default\nimport Mathlib.control.monad.writer\nimport Mathlib.PostPort\n\nuniverses u v w l u_1 u_2 u₀ u₁ v₀ v₁ \n\nnamespace Mathlib\n\nstructure monad_cont.label (α : Type w) (m : Type u → Type v) (β : Type u) where\n apply : α → m β\n\ndef monad_cont.goto {α : Type u_1} {β : Type u} {m : Type u → Type v} (f : monad_cont.label α m β)\n (x : α) : m β :=\n monad_cont.label.apply f x\n\nclass monad_cont (m : Type u → Type v) where\n call_cc : {α β : Type u} → (monad_cont.label α m β → m α) → m α\n\nclass is_lawful_monad_cont (m : Type u → Type v) [Monad m] [monad_cont m] extends is_lawful_monad m\n where\n call_cc_bind_right :\n ∀ {α ω γ : Type u} (cmd : m α) (next : monad_cont.label ω m γ → α → m ω),\n (monad_cont.call_cc fun (f : monad_cont.label ω m γ) => cmd >>= next f) =\n do \n let x ← cmd \n monad_cont.call_cc fun (f : monad_cont.label ω m γ) => next f x\n call_cc_bind_left :\n ∀ {α : Type u} (β : Type u) (x : α) (dead : monad_cont.label α m β → β → m α),\n (monad_cont.call_cc fun (f : monad_cont.label α m β) => monad_cont.goto f x >>= dead f) =\n pure x\n call_cc_dummy :\n ∀ {α β : Type u} (dummy : m α),\n (monad_cont.call_cc fun (f : monad_cont.label α m β) => dummy) = dummy\n\ndef cont_t (r : Type u) (m : Type u → Type v) (α : Type w) := (α → m r) → m r\n\ndef cont (r : Type u) (α : Type w) := cont_t r id α\n\nnamespace cont_t\n\n\ndef run {r : Type u} {m : Type u → Type v} {α : Type w} : cont_t r m α → (α → m r) → m r := id\n\ndef map {r : Type u} {m : Type u → Type v} {α : Type w} (f : m r → m r) (x : cont_t r m α) :\n cont_t r m α :=\n f ∘ x\n\ntheorem run_cont_t_map_cont_t {r : Type u} {m : Type u → Type v} {α : Type w} (f : m r → m r)\n (x : cont_t r m α) : run (map f x) = f ∘ run x :=\n rfl\n\ndef with_cont_t {r : Type u} {m : Type u → Type v} {α : Type w} {β : Type w}\n (f : (β → m r) → α → m r) (x : cont_t r m α) : cont_t r m β :=\n fun (g : β → m r) => x (f g)\n\ntheorem run_with_cont_t {r : Type u} {m : Type u → Type v} {α : Type w} {β : Type w}\n (f : (β → m r) → α → m r) (x : cont_t r m α) : run (with_cont_t f x) = run x ∘ f :=\n rfl\n\nprotected theorem ext {r : Type u} {m : Type u → Type v} {α : Type w} {x : cont_t r m α}\n {y : cont_t r m α} (h : ∀ (f : α → m r), run x f = run y f) : x = y :=\n funext fun (x_1 : α → m r) => h x_1\n\nprotected instance monad {r : Type u} {m : Type u → Type v} : Monad (cont_t r m) := sorry\n\nprotected instance is_lawful_monad {r : Type u} {m : Type u → Type v} :\n is_lawful_monad (cont_t r m) :=\n is_lawful_monad.mk\n (fun (α β : Type u_1) (x : α) (f : α → cont_t r m β) =>\n cont_t.ext fun (f_1 : β → m r) => Eq.refl (run (pure x >>= f) f_1))\n fun (α β γ : Type u_1) (x : cont_t r m α) (f : α → cont_t r m β) (g : β → cont_t r m γ) =>\n cont_t.ext fun (f_1 : γ → m r) => Eq.refl (run (x >>= f >>= g) f_1)\n\ndef monad_lift {r : Type u} {m : Type u → Type v} [Monad m] {α : Type u} : m α → cont_t r m α :=\n fun (x : m α) (f : α → m r) => x >>= f\n\nprotected instance has_monad_lift {r : Type u} {m : Type u → Type v} [Monad m] :\n has_monad_lift m (cont_t r m) :=\n has_monad_lift.mk fun (α : Type u) => monad_lift\n\ntheorem monad_lift_bind {r : Type u} {m : Type u → Type v} [Monad m] [is_lawful_monad m]\n {α : Type u} {β : Type u} (x : m α) (f : α → m β) :\n monad_lift (x >>= f) = monad_lift x >>= monad_lift ∘ f :=\n sorry\n\nprotected instance monad_cont {r : Type u} {m : Type u → Type v} : monad_cont (cont_t r m) :=\n monad_cont.mk\n fun (α β : Type u_1) (f : label α (cont_t r m) β → cont_t r m α) (g : α → m r) =>\n f (monad_cont.label.mk fun (x : α) (h : β → m r) => g x) g\n\nprotected instance is_lawful_monad_cont {r : Type u} {m : Type u → Type v} :\n is_lawful_monad_cont (cont_t r m) :=\n is_lawful_monad_cont.mk sorry sorry sorry\n\nprotected instance monad_except {r : Type u} {m : Type u → Type v} (ε : outParam (Type u_1))\n [monad_except ε m] : monad_except ε (cont_t r m) :=\n monad_except.mk (fun (x : Type u_2) (e : ε) (f : x → m r) => throw e)\n fun (α : Type u_2) (act : cont_t r m α) (h : ε → cont_t r m α) (f : α → m r) =>\n catch (act f) fun (e : ε) => h e f\n\nprotected instance monad_run {r : Type u} {m : Type u → Type v} :\n monad_run (fun (α : Type u) => (α → m r) → ulift (m r)) (cont_t r m) :=\n monad_run.mk fun (α : Type u) (f : cont_t r m α) (x : α → m r) => ulift.up (f x)\n\nend cont_t\n\n\ndef except_t.mk_label {m : Type u → Type v} [Monad m] {α : Type u} {β : Type u} {ε : Type u} :\n label (except ε α) m β → label α (except_t ε m) β :=\n sorry\n\ntheorem except_t.goto_mk_label {m : Type u → Type v} [Monad m] {α : Type u} {β : Type u}\n {ε : Type u} (x : label (except ε α) m β) (i : α) :\n goto (except_t.mk_label x) i = except_t.mk (except.ok <$> goto x (except.ok i)) :=\n monad_cont.label.cases_on x\n fun (x : except ε α → m β) => Eq.refl (goto (except_t.mk_label (monad_cont.label.mk x)) i)\n\ndef except_t.call_cc {m : Type u → Type v} [Monad m] {ε : Type u} [monad_cont m] {α : Type u}\n {β : Type u} (f : label α (except_t ε m) β → except_t ε m α) : except_t ε m α :=\n except_t.mk\n (monad_cont.call_cc fun (x : label (except ε α) m β) => except_t.run (f (except_t.mk_label x)))\n\nprotected instance except_t.monad_cont {m : Type u → Type v} [Monad m] {ε : Type u} [monad_cont m] :\n monad_cont (except_t ε m) :=\n monad_cont.mk fun (α β : Type u) => except_t.call_cc\n\nprotected instance except_t.is_lawful_monad_cont {m : Type u → Type v} [Monad m] {ε : Type u}\n [monad_cont m] [is_lawful_monad_cont m] : is_lawful_monad_cont (except_t ε m) :=\n is_lawful_monad_cont.mk sorry sorry sorry\n\ndef option_t.mk_label {m : Type u → Type v} [Monad m] {α : Type u} {β : Type u} :\n label (Option α) m β → label α (option_t m) β :=\n sorry\n\ntheorem option_t.goto_mk_label {m : Type u → Type v} [Monad m] {α : Type u} {β : Type u}\n (x : label (Option α) m β) (i : α) :\n goto (option_t.mk_label x) i = option_t.mk (some <$> goto x (some i)) :=\n monad_cont.label.cases_on x\n fun (x : Option α → m β) => Eq.refl (goto (option_t.mk_label (monad_cont.label.mk x)) i)\n\ndef option_t.call_cc {m : Type u → Type v} [Monad m] [monad_cont m] {α : Type u} {β : Type u}\n (f : label α (option_t m) β → option_t m α) : option_t m α :=\n option_t.mk\n (monad_cont.call_cc fun (x : label (Option α) m β) => option_t.run (f (option_t.mk_label x)))\n\nprotected instance option_t.monad_cont {m : Type u → Type v} [Monad m] [monad_cont m] :\n monad_cont (option_t m) :=\n monad_cont.mk fun (α β : Type u) => option_t.call_cc\n\nprotected instance option_t.is_lawful_monad_cont {m : Type u → Type v} [Monad m] [monad_cont m]\n [is_lawful_monad_cont m] : is_lawful_monad_cont (option_t m) :=\n is_lawful_monad_cont.mk sorry sorry sorry\n\ndef writer_t.mk_label {m : Type u → Type v} [Monad m] {α : Type u_1} {β : Type u} {ω : Type u}\n [HasOne ω] : label (α × ω) m β → label α (writer_t ω m) β :=\n sorry\n\ntheorem writer_t.goto_mk_label {m : Type u → Type v} [Monad m] {α : Type u_1} {β : Type u}\n {ω : Type u} [HasOne ω] (x : label (α × ω) m β) (i : α) :\n goto (writer_t.mk_label x) i = monad_lift (goto x (i, 1)) :=\n monad_cont.label.cases_on x\n fun (x : α × ω → m β) => Eq.refl (goto (writer_t.mk_label (monad_cont.label.mk x)) i)\n\ndef writer_t.call_cc {m : Type u → Type v} [Monad m] [monad_cont m] {α : Type u} {β : Type u}\n {ω : Type u} [HasOne ω] (f : label α (writer_t ω m) β → writer_t ω m α) : writer_t ω m α :=\n writer_t.mk (monad_cont.call_cc (writer_t.run ∘ f ∘ writer_t.mk_label))\n\nprotected instance writer_t.monad_cont {m : Type u → Type v} [Monad m] (ω : Type u) [Monad m]\n [HasOne ω] [monad_cont m] : monad_cont (writer_t ω m) :=\n monad_cont.mk fun (α β : Type u) => writer_t.call_cc\n\ndef state_t.mk_label {m : Type u → Type v} [Monad m] {α : Type u} {β : Type u} {σ : Type u} :\n label (α × σ) m (β × σ) → label α (state_t σ m) β :=\n sorry\n\ntheorem state_t.goto_mk_label {m : Type u → Type v} [Monad m] {α : Type u} {β : Type u} {σ : Type u}\n (x : label (α × σ) m (β × σ)) (i : α) :\n goto (state_t.mk_label x) i = state_t.mk fun (s : σ) => goto x (i, s) :=\n monad_cont.label.cases_on x\n fun (x : α × σ → m (β × σ)) => Eq.refl (goto (state_t.mk_label (monad_cont.label.mk x)) i)\n\ndef state_t.call_cc {m : Type u → Type v} [Monad m] {σ : Type u} [monad_cont m] {α : Type u}\n {β : Type u} (f : label α (state_t σ m) β → state_t σ m α) : state_t σ m α :=\n state_t.mk\n fun (r : σ) =>\n monad_cont.call_cc\n fun (f' : label (α × σ) m (β × σ)) => state_t.run (f (state_t.mk_label f')) r\n\nprotected instance state_t.monad_cont {m : Type u → Type v} [Monad m] {σ : Type u} [monad_cont m] :\n monad_cont (state_t σ m) :=\n monad_cont.mk fun (α β : Type u) => state_t.call_cc\n\nprotected instance state_t.is_lawful_monad_cont {m : Type u → Type v} [Monad m] {σ : Type u}\n [monad_cont m] [is_lawful_monad_cont m] : is_lawful_monad_cont (state_t σ m) :=\n is_lawful_monad_cont.mk sorry sorry sorry\n\ndef reader_t.mk_label {m : Type u → Type v} [Monad m] {α : Type u_1} {β : Type u} (ρ : Type u) :\n label α m β → label α (reader_t ρ m) β :=\n sorry\n\ntheorem reader_t.goto_mk_label {m : Type u → Type v} [Monad m] {α : Type u_1} {ρ : Type u}\n {β : Type u} (x : label α m β) (i : α) :\n goto (reader_t.mk_label ρ x) i = monad_lift (goto x i) :=\n monad_cont.label.cases_on x\n fun (x : α → m β) => Eq.refl (goto (reader_t.mk_label ρ (monad_cont.label.mk x)) i)\n\ndef reader_t.call_cc {m : Type u → Type v} [Monad m] {ε : Type u} [monad_cont m] {α : Type u}\n {β : Type u} (f : label α (reader_t ε m) β → reader_t ε m α) : reader_t ε m α :=\n reader_t.mk\n fun (r : ε) =>\n monad_cont.call_cc fun (f' : label α m β) => reader_t.run (f (reader_t.mk_label ε f')) r\n\nprotected instance reader_t.monad_cont {m : Type u → Type v} [Monad m] {ρ : Type u} [monad_cont m] :\n monad_cont (reader_t ρ m) :=\n monad_cont.mk fun (α β : Type u) => reader_t.call_cc\n\nprotected instance reader_t.is_lawful_monad_cont {m : Type u → Type v} [Monad m] {ρ : Type u}\n [monad_cont m] [is_lawful_monad_cont m] : is_lawful_monad_cont (reader_t ρ m) :=\n is_lawful_monad_cont.mk sorry sorry sorry\n\n/-- reduce the equivalence between two continuation passing monads to the equivalence between\ntheir underlying monad -/\ndef cont_t.equiv {m₁ : Type u₀ → Type v₀} {m₂ : Type u₁ → Type v₁} {α₁ : Type u₀} {r₁ : Type u₀}\n {α₂ : Type u₁} {r₂ : Type u₁} (F : m₁ r₁ ≃ m₂ r₂) (G : α₁ ≃ α₂) :\n cont_t r₁ m₁ α₁ ≃ cont_t r₂ m₂ α₂ :=\n equiv.mk\n (fun (f : cont_t r₁ m₁ α₁) (r : α₂ → m₂ r₂) =>\n coe_fn F (f fun (x : α₁) => coe_fn (equiv.symm F) (r (coe_fn G x))))\n (fun (f : cont_t r₂ m₂ α₂) (r : α₁ → m₁ r₁) =>\n coe_fn (equiv.symm F) (f fun (x : α₂) => coe_fn F (r (coe_fn (equiv.symm G) x))))\n sorry sorry\n\nend Mathlib", "meta": {"author": "AurelienSaue", "repo": "Mathlib4_auto", "sha": "590df64109b08190abe22358fabc3eae000943f2", "save_path": "github-repos/lean/AurelienSaue-Mathlib4_auto", "path": "github-repos/lean/AurelienSaue-Mathlib4_auto/Mathlib4_auto-590df64109b08190abe22358fabc3eae000943f2/Mathlib/control/monad/cont_auto.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.060086652277911726, "lm_q1q2_score": 0.029573937366369065}} {"text": "/-\nCopyright (c) 2022 Andrew Yang. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Andrew Yang\n-/\nimport category_theory.limits.shapes.diagonal\nimport category_theory.arrow\nimport category_theory.limits.shapes.comm_sq\nimport category_theory.concrete_category.basic\n\n/-!\n# Properties of morphisms\n\n> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.\n> Any changes to this file require a corresponding PR to mathlib4.\n\nWe provide the basic framework for talking about properties of morphisms.\nThe following meta-properties are defined\n\n* `respects_iso`: `P` respects isomorphisms if `P f → P (e ≫ f)` and `P f → P (f ≫ e)`, where\n `e` is an isomorphism.\n* `stable_under_composition`: `P` is stable under composition if `P f → P g → P (f ≫ g)`.\n* `stable_under_base_change`: `P` is stable under base change if in all pullback\n squares, the left map satisfies `P` if the right map satisfies it.\n* `stable_under_cobase_change`: `P` is stable under cobase change if in all pushout\n squares, the right map satisfies `P` if the left map satisfies it.\n\n-/\n\nuniverses v u\n\nopen category_theory category_theory.limits opposite\n\nnoncomputable theory\n\nnamespace category_theory\n\nvariables (C : Type u) [category.{v} C] {D : Type*} [category D]\n\n/-- A `morphism_property C` is a class of morphisms between objects in `C`. -/\n@[derive complete_lattice]\ndef morphism_property := ∀ ⦃X Y : C⦄ (f : X ⟶ Y), Prop\n\ninstance : inhabited (morphism_property C) := ⟨⊤⟩\n\nvariable {C}\n\nnamespace morphism_property\n\ninstance : has_subset (morphism_property C) :=\n⟨λ P₁ P₂, ∀ ⦃X Y : C⦄ (f : X ⟶ Y) (hf : P₁ f), P₂ f⟩\ninstance : has_inter (morphism_property C) :=\n⟨λ P₁ P₂ X Y f, P₁ f ∧ P₂ f⟩\n\n/-- The morphism property in `Cᵒᵖ` associated to a morphism property in `C` -/\n@[simp] def op (P : morphism_property C) : morphism_property Cᵒᵖ := λ X Y f, P f.unop\n\n/-- The morphism property in `C` associated to a morphism property in `Cᵒᵖ` -/\n@[simp] def unop (P : morphism_property Cᵒᵖ) : morphism_property C := λ X Y f, P f.op\n\nlemma unop_op (P : morphism_property C) : P.op.unop = P := rfl\nlemma op_unop (P : morphism_property Cᵒᵖ) : P.unop.op = P := rfl\n\n/-- The inverse image of a `morphism_property D` by a functor `C ⥤ D` -/\ndef inverse_image (P : morphism_property D) (F : C ⥤ D) : morphism_property C :=\nλ X Y f, P (F.map f)\n\n/-- A morphism property `respects_iso` if it still holds when composed with an isomorphism -/\ndef respects_iso (P : morphism_property C) : Prop :=\n (∀ {X Y Z} (e : X ≅ Y) (f : Y ⟶ Z), P f → P (e.hom ≫ f)) ∧\n (∀ {X Y Z} (e : Y ≅ Z) (f : X ⟶ Y), P f → P (f ≫ e.hom))\n\nlemma respects_iso.op {P : morphism_property C} (h : respects_iso P) : respects_iso P.op :=\n⟨λ X Y Z e f hf, h.2 e.unop f.unop hf, λ X Y Z e f hf, h.1 e.unop f.unop hf⟩\n\nlemma respects_iso.unop {P : morphism_property Cᵒᵖ} (h : respects_iso P) : respects_iso P.unop :=\n⟨λ X Y Z e f hf, h.2 e.op f.op hf, λ X Y Z e f hf, h.1 e.op f.op hf⟩\n\n/-- A morphism property is `stable_under_composition` if the composition of two such morphisms\nstill falls in the class. -/\ndef stable_under_composition (P : morphism_property C) : Prop :=\n ∀ ⦃X Y Z⦄ (f : X ⟶ Y) (g : Y ⟶ Z), P f → P g → P (f ≫ g)\n\nlemma stable_under_composition.op {P : morphism_property C} (h : stable_under_composition P) :\n stable_under_composition P.op := λ X Y Z f g hf hg, h g.unop f.unop hg hf\n\nlemma stable_under_composition.unop {P : morphism_property Cᵒᵖ} (h : stable_under_composition P) :\n stable_under_composition P.unop := λ X Y Z f g hf hg, h g.op f.op hg hf\n\n/-- A morphism property is `stable_under_inverse` if the inverse of a morphism satisfying\nthe property still falls in the class. -/\ndef stable_under_inverse (P : morphism_property C) : Prop :=\n∀ ⦃X Y⦄ (e : X ≅ Y), P e.hom → P e.inv\n\nlemma stable_under_inverse.op {P : morphism_property C} (h : stable_under_inverse P) :\n stable_under_inverse P.op := λ X Y e he, h e.unop he\n\nlemma stable_under_inverse.unop {P : morphism_property Cᵒᵖ} (h : stable_under_inverse P) :\n stable_under_inverse P.unop := λ X Y e he, h e.op he\n\n/-- A morphism property is `stable_under_base_change` if the base change of such a morphism\nstill falls in the class. -/\ndef stable_under_base_change (P : morphism_property C) : Prop :=\n∀ ⦃X Y Y' S : C⦄ ⦃f : X ⟶ S⦄ ⦃g : Y ⟶ S⦄ ⦃f' : Y' ⟶ Y⦄ ⦃g' : Y' ⟶ X⦄\n (sq : is_pullback f' g' g f) (hg : P g), P g'\n\n/-- A morphism property is `stable_under_cobase_change` if the cobase change of such a morphism\nstill falls in the class. -/\ndef stable_under_cobase_change (P : morphism_property C) : Prop :=\n∀ ⦃A A' B B' : C⦄ ⦃f : A ⟶ A'⦄ ⦃g : A ⟶ B⦄ ⦃f' : B ⟶ B'⦄ ⦃g' : A' ⟶ B'⦄\n (sq : is_pushout g f f' g') (hf : P f), P f'\n\nlemma stable_under_composition.respects_iso {P : morphism_property C}\n (hP : stable_under_composition P) (hP' : ∀ {X Y} (e : X ≅ Y), P e.hom) : respects_iso P :=\n⟨λ X Y Z e f hf, hP _ _ (hP' e) hf, λ X Y Z e f hf, hP _ _ hf (hP' e)⟩\n\nlemma respects_iso.cancel_left_is_iso {P : morphism_property C}\n (hP : respects_iso P) {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) [is_iso f] :\n P (f ≫ g) ↔ P g :=\n⟨λ h, by simpa using hP.1 (as_iso f).symm (f ≫ g) h, hP.1 (as_iso f) g⟩\n\nlemma respects_iso.cancel_right_is_iso {P : morphism_property C}\n (hP : respects_iso P) {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) [is_iso g] :\n P (f ≫ g) ↔ P f :=\n⟨λ h, by simpa using hP.2 (as_iso g).symm (f ≫ g) h, hP.2 (as_iso g) f⟩\n\nlemma respects_iso.arrow_iso_iff {P : morphism_property C}\n (hP : respects_iso P) {f g : arrow C} (e : f ≅ g) : P f.hom ↔ P g.hom :=\nby { rw [← arrow.inv_left_hom_right e.hom, hP.cancel_left_is_iso, hP.cancel_right_is_iso], refl }\n\nlemma respects_iso.arrow_mk_iso_iff {P : morphism_property C}\n (hP : respects_iso P) {W X Y Z : C} {f : W ⟶ X} {g : Y ⟶ Z} (e : arrow.mk f ≅ arrow.mk g) :\n P f ↔ P g :=\nhP.arrow_iso_iff e\n\nlemma respects_iso.of_respects_arrow_iso (P : morphism_property C)\n (hP : ∀ (f g : arrow C) (e : f ≅ g) (hf : P f.hom), P g.hom) : respects_iso P :=\nbegin\n split,\n { intros X Y Z e f hf,\n refine hP (arrow.mk f) (arrow.mk (e.hom ≫ f)) (arrow.iso_mk e.symm (iso.refl _) _) hf,\n dsimp,\n simp only [iso.inv_hom_id_assoc, category.comp_id], },\n { intros X Y Z e f hf,\n refine hP (arrow.mk f) (arrow.mk (f ≫ e.hom)) (arrow.iso_mk (iso.refl _) e _) hf,\n dsimp,\n simp only [category.id_comp], },\nend\n\nlemma stable_under_base_change.mk {P : morphism_property C} [has_pullbacks C]\n (hP₁ : respects_iso P)\n (hP₂ : ∀ (X Y S : C) (f : X ⟶ S) (g : Y ⟶ S) (hg : P g), P (pullback.fst : pullback f g ⟶ X)) :\n stable_under_base_change P := λ X Y Y' S f g f' g' sq hg,\nbegin\n let e := sq.flip.iso_pullback,\n rw [← hP₁.cancel_left_is_iso e.inv, sq.flip.iso_pullback_inv_fst],\n exact hP₂ _ _ _ f g hg,\nend\n\nlemma stable_under_base_change.respects_iso {P : morphism_property C}\n (hP : stable_under_base_change P) : respects_iso P :=\nbegin\n apply respects_iso.of_respects_arrow_iso,\n intros f g e,\n exact hP (is_pullback.of_horiz_is_iso (comm_sq.mk e.inv.w)),\nend\n\nlemma stable_under_base_change.fst {P : morphism_property C}\n (hP : stable_under_base_change P) {X Y S : C} (f : X ⟶ S) (g : Y ⟶ S) [has_pullback f g]\n (H : P g) : P (pullback.fst : pullback f g ⟶ X) :=\nhP (is_pullback.of_has_pullback f g).flip H\n\nlemma stable_under_base_change.snd {P : morphism_property C}\n (hP : stable_under_base_change P) {X Y S : C} (f : X ⟶ S) (g : Y ⟶ S) [has_pullback f g]\n (H : P f) : P (pullback.snd : pullback f g ⟶ Y) :=\nhP (is_pullback.of_has_pullback f g) H\n\nlemma stable_under_base_change.base_change_obj [has_pullbacks C] {P : morphism_property C}\n (hP : stable_under_base_change P) {S S' : C} (f : S' ⟶ S)\n (X : over S) (H : P X.hom) : P ((base_change f).obj X).hom :=\nhP.snd X.hom f H\n\nlemma stable_under_base_change.base_change_map [has_pullbacks C] {P : morphism_property C}\n (hP : stable_under_base_change P) {S S' : C} (f : S' ⟶ S)\n {X Y : over S} (g : X ⟶ Y) (H : P g.left) : P ((base_change f).map g).left :=\nbegin\n let e := pullback_right_pullback_fst_iso Y.hom f g.left ≪≫\n pullback.congr_hom (g.w.trans (category.comp_id _)) rfl,\n have : e.inv ≫ pullback.snd = ((base_change f).map g).left,\n { apply pullback.hom_ext; dsimp; simp },\n rw [← this, hP.respects_iso.cancel_left_is_iso],\n exact hP.snd _ _ H,\nend\n\nlemma stable_under_base_change.pullback_map [has_pullbacks C] {P : morphism_property C}\n (hP : stable_under_base_change P) (hP' : stable_under_composition P) {S X X' Y Y' : C}\n {f : X ⟶ S} {g : Y ⟶ S} {f' : X' ⟶ S} {g' : Y' ⟶ S} {i₁ : X ⟶ X'} {i₂ : Y ⟶ Y'}\n (h₁ : P i₁) (h₂ : P i₂) (e₁ : f = i₁ ≫ f') (e₂ : g = i₂ ≫ g') :\n P (pullback.map f g f' g' i₁ i₂ (𝟙 _)\n ((category.comp_id _).trans e₁) ((category.comp_id _).trans e₂)) :=\nbegin\n have : pullback.map f g f' g' i₁ i₂ (𝟙 _)\n ((category.comp_id _).trans e₁) ((category.comp_id _).trans e₂) =\n ((pullback_symmetry _ _).hom ≫\n ((base_change _).map (over.hom_mk _ e₂.symm : over.mk g ⟶ over.mk g')).left) ≫\n (pullback_symmetry _ _).hom ≫\n ((base_change g').map (over.hom_mk _ e₁.symm : over.mk f ⟶ over.mk f')).left,\n { apply pullback.hom_ext; dsimp; simp },\n rw this,\n apply hP'; rw hP.respects_iso.cancel_left_is_iso,\n exacts [hP.base_change_map _ (over.hom_mk _ e₂.symm : over.mk g ⟶ over.mk g') h₂,\n hP.base_change_map _ (over.hom_mk _ e₁.symm : over.mk f ⟶ over.mk f') h₁],\nend\n\nlemma stable_under_cobase_change.mk {P : morphism_property C} [has_pushouts C]\n (hP₁ : respects_iso P)\n (hP₂ : ∀ (A B A' : C) (f : A ⟶ A') (g : A ⟶ B) (hf : P f), P (pushout.inr : B ⟶ pushout f g)) :\n stable_under_cobase_change P := λ A A' B B' f g f' g' sq hf,\nbegin\n let e := sq.flip.iso_pushout,\n rw [← hP₁.cancel_right_is_iso _ e.hom, sq.flip.inr_iso_pushout_hom],\n exact hP₂ _ _ _ f g hf,\nend\n\nlemma stable_under_cobase_change.respects_iso {P : morphism_property C}\n (hP : stable_under_cobase_change P) : respects_iso P :=\nrespects_iso.of_respects_arrow_iso _ (λ f g e, hP (is_pushout.of_horiz_is_iso (comm_sq.mk e.hom.w)))\n\nlemma stable_under_cobase_change.inl {P : morphism_property C}\n (hP : stable_under_cobase_change P) {A B A' : C} (f : A ⟶ A') (g : A ⟶ B) [has_pushout f g]\n (H : P g) : P (pushout.inl : A' ⟶ pushout f g) :=\nhP (is_pushout.of_has_pushout f g) H\n\nlemma stable_under_cobase_change.inr {P : morphism_property C}\n (hP : stable_under_cobase_change P) {A B A' : C} (f : A ⟶ A') (g : A ⟶ B) [has_pushout f g]\n (H : P f) : P (pushout.inr : B ⟶ pushout f g) :=\nhP (is_pushout.of_has_pushout f g).flip H\n\nlemma stable_under_cobase_change.op {P : morphism_property C}\n (hP : stable_under_cobase_change P) : stable_under_base_change P.op :=\nλ X Y Y' S f g f' g' sq hg, hP sq.unop hg\n\nlemma stable_under_cobase_change.unop {P : morphism_property Cᵒᵖ}\n (hP : stable_under_cobase_change P) : stable_under_base_change P.unop :=\nλ X Y Y' S f g f' g' sq hg, hP sq.op hg\n\nlemma stable_under_base_change.op {P : morphism_property C}\n (hP : stable_under_base_change P) : stable_under_cobase_change P.op :=\nλ A A' B B' f g f' g' sq hf, hP sq.unop hf\n\nlemma stable_under_base_change.unop {P : morphism_property Cᵒᵖ}\n (hP : stable_under_base_change P) : stable_under_cobase_change P.unop :=\nλ A A' B B' f g f' g' sq hf, hP sq.op hf\n\n/-- If `P : morphism_property C` and `F : C ⥤ D`, then\n`P.is_inverted_by F` means that all morphisms in `P` are mapped by `F`\nto isomorphisms in `D`. -/\ndef is_inverted_by (P : morphism_property C) (F : C ⥤ D) : Prop :=\n∀ ⦃X Y : C⦄ (f : X ⟶ Y) (hf : P f), is_iso (F.map f)\n\nnamespace is_inverted_by\n\nlemma of_comp {C₁ C₂ C₃ : Type*} [category C₁] [category C₂] [category C₃]\n (W : morphism_property C₁) (F : C₁ ⥤ C₂) (hF : W.is_inverted_by F) (G : C₂ ⥤ C₃) :\n W.is_inverted_by (F ⋙ G) :=\nλ X Y f hf, by { haveI := hF f hf, dsimp, apply_instance, }\n\nlemma op {W : morphism_property C} {L : C ⥤ D} (h : W.is_inverted_by L) :\n W.op.is_inverted_by L.op :=\nλ X Y f hf, by { haveI := h f.unop hf, dsimp, apply_instance, }\n\nlemma right_op {W : morphism_property C} {L : Cᵒᵖ ⥤ D} (h : W.op.is_inverted_by L) :\n W.is_inverted_by L.right_op :=\nλ X Y f hf, by { haveI := h f.op hf, dsimp, apply_instance, }\n\nlemma left_op {W : morphism_property C} {L : C ⥤ Dᵒᵖ} (h : W.is_inverted_by L) :\n W.op.is_inverted_by L.left_op :=\nλ X Y f hf, by { haveI := h f.unop hf, dsimp, apply_instance, }\n\nlemma unop {W : morphism_property C} {L : Cᵒᵖ ⥤ Dᵒᵖ} (h : W.op.is_inverted_by L) :\n W.is_inverted_by L.unop :=\nλ X Y f hf, by { haveI := h f.op hf, dsimp, apply_instance, }\n\nend is_inverted_by\n\n/-- Given `app : Π X, F₁.obj X ⟶ F₂.obj X` where `F₁` and `F₂` are two functors,\nthis is the `morphism_property C` satisfied by the morphisms in `C` with respect\nto whom `app` is natural. -/\n@[simp]\ndef naturality_property {F₁ F₂ : C ⥤ D} (app : Π X, F₁.obj X ⟶ F₂.obj X) :\n morphism_property C := λ X Y f, F₁.map f ≫ app Y = app X ≫ F₂.map f\n\nnamespace naturality_property\n\nlemma is_stable_under_composition {F₁ F₂ : C ⥤ D} (app : Π X, F₁.obj X ⟶ F₂.obj X) :\n (naturality_property app).stable_under_composition := λ X Y Z f g hf hg,\nbegin\n simp only [naturality_property] at ⊢ hf hg,\n simp only [functor.map_comp, category.assoc, hg],\n slice_lhs 1 2 { rw hf },\n rw category.assoc,\nend\n\nlemma is_stable_under_inverse {F₁ F₂ : C ⥤ D} (app : Π X, F₁.obj X ⟶ F₂.obj X) :\n (naturality_property app).stable_under_inverse := λ X Y e he,\nbegin\n simp only [naturality_property] at ⊢ he,\n rw ← cancel_epi (F₁.map e.hom),\n slice_rhs 1 2 { rw he },\n simp only [category.assoc, ← F₁.map_comp_assoc, ← F₂.map_comp,\n e.hom_inv_id, functor.map_id, category.id_comp, category.comp_id],\nend\n\nend naturality_property\n\nlemma respects_iso.inverse_image {P : morphism_property D} (h : respects_iso P) (F : C ⥤ D) :\n respects_iso (P.inverse_image F) :=\nbegin\n split,\n all_goals\n { intros X Y Z e f hf,\n dsimp [inverse_image],\n rw F.map_comp, },\n exacts [h.1 (F.map_iso e) (F.map f) hf, h.2 (F.map_iso e) (F.map f) hf],\nend\n\nlemma stable_under_composition.inverse_image {P : morphism_property D}\n (h : stable_under_composition P) (F : C ⥤ D) : stable_under_composition (P.inverse_image F) :=\nλ X Y Z f g hf hg, by simpa only [← F.map_comp] using h (F.map f) (F.map g) hf hg\n\nvariable (C)\n\n/-- The `morphism_property C` satisfied by isomorphisms in `C`. -/\ndef isomorphisms : morphism_property C := λ X Y f, is_iso f\n\n/-- The `morphism_property C` satisfied by monomorphisms in `C`. -/\ndef monomorphisms : morphism_property C := λ X Y f, mono f\n\n/-- The `morphism_property C` satisfied by epimorphisms in `C`. -/\ndef epimorphisms : morphism_property C := λ X Y f, epi f\n\nsection\n\nvariables {C} {X Y : C} (f : X ⟶ Y)\n\n@[simp] lemma isomorphisms.iff : (isomorphisms C) f ↔ is_iso f := by refl\n@[simp] lemma monomorphisms.iff : (monomorphisms C) f ↔ mono f := by refl\n@[simp] lemma epimorphisms.iff : (epimorphisms C) f ↔ epi f := by refl\n\nlemma isomorphisms.infer_property [hf : is_iso f] : (isomorphisms C) f := hf\nlemma monomorphisms.infer_property [hf : mono f] : (monomorphisms C) f := hf\nlemma epimorphisms.infer_property [hf : epi f] : (epimorphisms C) f := hf\n\nend\n\nlemma respects_iso.monomorphisms : respects_iso (monomorphisms C) :=\nby { split; { intros X Y Z e f, simp only [monomorphisms.iff], introI, apply mono_comp, }, }\n\nlemma respects_iso.epimorphisms : respects_iso (epimorphisms C) :=\nby { split; { intros X Y Z e f, simp only [epimorphisms.iff], introI, apply epi_comp, }, }\n\nlemma respects_iso.isomorphisms : respects_iso (isomorphisms C) :=\nby { split; { intros X Y Z e f, simp only [isomorphisms.iff], introI, apply_instance, }, }\n\nlemma stable_under_composition.isomorphisms : stable_under_composition (isomorphisms C) :=\nλ X Y Z f g hf hg, begin\n rw isomorphisms.iff at hf hg ⊢,\n haveI := hf,\n haveI := hg,\n apply_instance,\nend\n\nlemma stable_under_composition.monomorphisms : stable_under_composition (monomorphisms C) :=\nλ X Y Z f g hf hg, begin\n rw monomorphisms.iff at hf hg ⊢,\n haveI := hf,\n haveI := hg,\n apply mono_comp,\nend\n\nlemma stable_under_composition.epimorphisms : stable_under_composition (epimorphisms C) :=\nλ X Y Z f g hf hg, begin\n rw epimorphisms.iff at hf hg ⊢,\n haveI := hf,\n haveI := hg,\n apply epi_comp,\nend\n\nvariable {C}\n\n/-- The full subcategory of `C ⥤ D` consisting of functors inverting morphisms in `W` -/\n@[derive category, nolint has_nonempty_instance]\ndef functors_inverting (W : morphism_property C) (D : Type*) [category D] :=\nfull_subcategory (λ (F : C ⥤ D), W.is_inverted_by F)\n\n/-- A constructor for `W.functors_inverting D` -/\ndef functors_inverting.mk {W : morphism_property C} {D : Type*} [category D]\n(F : C ⥤ D) (hF : W.is_inverted_by F) : W.functors_inverting D := ⟨F, hF⟩\n\nlemma is_inverted_by.iff_of_iso (W : morphism_property C) {F₁ F₂ : C ⥤ D} (e : F₁ ≅ F₂) :\n W.is_inverted_by F₁ ↔ W.is_inverted_by F₂ :=\nbegin\n suffices : ∀ (X Y : C) (f : X ⟶ Y), is_iso (F₁.map f) ↔ is_iso (F₂.map f),\n { split,\n exact λ h X Y f hf, by { rw ← this, exact h f hf, },\n exact λ h X Y f hf, by { rw this, exact h f hf, }, },\n intros X Y f,\n exact (respects_iso.isomorphisms D).arrow_mk_iso_iff\n (arrow.iso_mk (e.app X) (e.app Y) (by simp)),\nend\n\nsection diagonal\n\nvariables [has_pullbacks C] {P : morphism_property C}\n\n/-- For `P : morphism_property C`, `P.diagonal` is a morphism property that holds for `f : X ⟶ Y`\nwhenever `P` holds for `X ⟶ Y xₓ Y`. -/\ndef diagonal (P : morphism_property C) : morphism_property C :=\nλ X Y f, P (pullback.diagonal f)\n\nlemma diagonal_iff {X Y : C} {f : X ⟶ Y} : P.diagonal f ↔ P (pullback.diagonal f) := iff.rfl\n\nlemma respects_iso.diagonal (hP : P.respects_iso) : P.diagonal.respects_iso :=\nbegin\n split,\n { introv H,\n rwa [diagonal_iff, pullback.diagonal_comp, hP.cancel_left_is_iso, hP.cancel_left_is_iso,\n ← hP.cancel_right_is_iso _ _, ← pullback.condition, hP.cancel_left_is_iso],\n apply_instance },\n { introv H,\n delta diagonal,\n rwa [pullback.diagonal_comp, hP.cancel_right_is_iso] }\nend\n\nlemma stable_under_composition.diagonal\n (hP : stable_under_composition P) (hP' : respects_iso P) (hP'' : stable_under_base_change P) :\n P.diagonal.stable_under_composition :=\nbegin\n introv X h₁ h₂,\n rw [diagonal_iff, pullback.diagonal_comp],\n apply hP, { assumption },\n rw hP'.cancel_left_is_iso,\n apply hP''.snd,\n assumption\nend\n\nlemma stable_under_base_change.diagonal\n (hP : stable_under_base_change P) (hP' : respects_iso P) :\n P.diagonal.stable_under_base_change :=\nstable_under_base_change.mk hP'.diagonal\nbegin\n introv h,\n rw [diagonal_iff, diagonal_pullback_fst, hP'.cancel_left_is_iso, hP'.cancel_right_is_iso],\n convert hP.base_change_map f _ _; simp; assumption\nend\n\nend diagonal\n\nsection universally\n\n/-- `P.universally` holds for a morphism `f : X ⟶ Y` iff `P` holds for all `X ×[Y] Y' ⟶ Y'`. -/\ndef universally (P : morphism_property C) : morphism_property C :=\nλ X Y f, ∀ ⦃X' Y' : C⦄ (i₁ : X' ⟶ X) (i₂ : Y' ⟶ Y) (f' : X' ⟶ Y')\n (h : is_pullback f' i₁ i₂ f), P f'\n\nlemma universally_respects_iso (P : morphism_property C) :\n P.universally.respects_iso :=\nbegin\n constructor,\n { intros X Y Z e f hf X' Z' i₁ i₂ f' H,\n have : is_pullback (𝟙 _) (i₁ ≫ e.hom) i₁ e.inv := is_pullback.of_horiz_is_iso\n ⟨by rw [category.id_comp, category.assoc, e.hom_inv_id, category.comp_id]⟩,\n replace this := this.paste_horiz H,\n rw [iso.inv_hom_id_assoc, category.id_comp] at this,\n exact hf _ _ _ this },\n { intros X Y Z e f hf X' Z' i₁ i₂ f' H,\n have : is_pullback (𝟙 _) i₂ (i₂ ≫ e.inv) e.inv :=\n is_pullback.of_horiz_is_iso ⟨category.id_comp _⟩,\n replace this := H.paste_horiz this,\n rw [category.assoc, iso.hom_inv_id, category.comp_id, category.comp_id] at this,\n exact hf _ _ _ this },\nend\n\nlemma universally_stable_under_base_change (P : morphism_property C) :\n P.universally.stable_under_base_change :=\nλ X Y Y' S f g f' g' H h₁ Y'' X'' i₁ i₂ f'' H', h₁ _ _ _ (H'.paste_vert H.flip)\n\nlemma stable_under_composition.universally [has_pullbacks C]\n {P : morphism_property C} (hP : P.stable_under_composition) :\n P.universally.stable_under_composition :=\nbegin\n intros X Y Z f g hf hg X' Z' i₁ i₂ f' H,\n have := pullback.lift_fst _ _ (H.w.trans (category.assoc _ _ _).symm),\n rw ← this at H ⊢,\n apply hP _ _ _ (hg _ _ _ $ is_pullback.of_has_pullback _ _),\n exact hf _ _ _ (H.of_right (pullback.lift_snd _ _ _) (is_pullback.of_has_pullback i₂ g))\nend\n\nlemma universally_le (P : morphism_property C) :\n P.universally ≤ P :=\nbegin\n intros X Y f hf,\n exact hf (𝟙 _) (𝟙 _) _ (is_pullback.of_vert_is_iso ⟨by rw [category.comp_id, category.id_comp]⟩)\nend\n\nlemma stable_under_base_change.universally_eq\n {P : morphism_property C} (hP : P.stable_under_base_change) :\n P.universally = P :=\nP.universally_le.antisymm $ λ X Y f hf X' Y' i₁ i₂ f' H, hP H.flip hf\n\nlemma universally_mono : monotone (universally : morphism_property C → morphism_property C) :=\nλ P₁ P₂ h X Y f h₁ X' Y' i₁ i₂ f' H, h _ _ _ (h₁ _ _ _ H)\n\nend universally\n\nsection bijective\n\nvariables [concrete_category C]\n\nopen function\n\nlocal attribute [instance] concrete_category.has_coe_to_fun concrete_category.has_coe_to_sort\n\nvariable (C)\n\n/-- Injectiveness (in a concrete category) as a `morphism_property` -/\nprotected def injective : morphism_property C := λ X Y f, injective f\n\n/-- Surjectiveness (in a concrete category) as a `morphism_property` -/\nprotected def surjective : morphism_property C := λ X Y f, surjective f\n\n/-- Bijectiveness (in a concrete category) as a `morphism_property` -/\nprotected def bijective : morphism_property C := λ X Y f, bijective f\n\nlemma bijective_eq_sup : morphism_property.bijective C =\n morphism_property.injective C ⊓ morphism_property.surjective C :=\nrfl\n\nlemma injective_stable_under_composition :\n (morphism_property.injective C).stable_under_composition :=\nλ X Y Z f g hf hg, by { delta morphism_property.injective, rw coe_comp, exact hg.comp hf }\n\nlemma surjective_stable_under_composition :\n (morphism_property.surjective C).stable_under_composition :=\nλ X Y Z f g hf hg, by { delta morphism_property.surjective, rw coe_comp, exact hg.comp hf }\n\nlemma bijective_stable_under_composition :\n (morphism_property.bijective C).stable_under_composition :=\nλ X Y Z f g hf hg, by { delta morphism_property.bijective, rw coe_comp, exact hg.comp hf }\n\nlemma injective_respects_iso :\n (morphism_property.injective C).respects_iso :=\n(injective_stable_under_composition C).respects_iso\n (λ X Y e, ((forget C).map_iso e).to_equiv.injective)\n\nlemma surjective_respects_iso :\n (morphism_property.surjective C).respects_iso :=\n(surjective_stable_under_composition C).respects_iso\n (λ X Y e, ((forget C).map_iso e).to_equiv.surjective)\n\nlemma bijective_respects_iso :\n (morphism_property.bijective C).respects_iso :=\n(bijective_stable_under_composition C).respects_iso\n (λ X Y e, ((forget C).map_iso e).to_equiv.bijective)\n\nend bijective\n\nend morphism_property\n\nend category_theory\n", "meta": {"author": "leanprover-community", "repo": "mathlib", "sha": "5e526d18cea33550268dcbbddcb822d5cde40654", "save_path": "github-repos/lean/leanprover-community-mathlib", "path": "github-repos/lean/leanprover-community-mathlib/mathlib-5e526d18cea33550268dcbbddcb822d5cde40654/src/category_theory/morphism_property.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.476579651063676, "lm_q2_score": 0.061875980101319165, "lm_q1q2_score": 0.029488833005909647}} {"text": "/-\nCopyright (c) 2021 Anne Baanen. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Anne Baanen\n\n! This file was ported from Lean 3 source module data.fun_like.basic\n! leanprover-community/mathlib commit a148d797a1094ab554ad4183a4ad6f130358ef64\n! Please do not edit these lines, except to modify the commit id\n! if you have ported upstream changes.\n-/\nimport Mathlib.Logic.Function.Basic\nimport Mathlib.Tactic.NormCast\n\n/-!\n# Typeclass for a type `F` with an injective map to `A → B`\n\nThis typeclass is primarily for use by homomorphisms like `MonoidHom` and `LinearMap`.\n\n## Basic usage of `FunLike`\n\nA typical type of morphisms should be declared as:\n```\nstructure MyHom (A B : Type _) [MyClass A] [MyClass B] :=\n(toFun : A → B)\n(map_op' : ∀ {x y : A}, toFun (MyClass.op x y) = MyClass.op (toFun x) (toFun y))\n\nnamespace MyHom\n\nvariables (A B : Type _) [MyClass A] [MyClass B]\n\n-- This instance is optional if you follow the \"morphism class\" design below:\ninstance : FunLike (MyHom A B) A (λ _, B) :=\n{ coe := MyHom.toFun, coe_injective' := λ f g h, by cases f; cases g; congr' }\n\n/-- Helper instance for when there's too many metavariables to apply\n`FunLike.coe` directly. -/\ninstance : CoeFun (MyHom A B) (λ _, A → B) := ⟨MyHom.toFun⟩\n\n@[ext] theorem ext {f g : MyHom A B} (h : ∀ x, f x = g x) : f = g := FunLike.ext f g h\n\n/-- Copy of a `MyHom` with a new `toFun` equal to the old one. Useful to fix definitional\nequalities. -/\nprotected def copy (f : MyHom A B) (f' : A → B) (h : f' = ⇑f) : MyHom A B :=\n{ toFun := f',\n map_op' := h.symm ▸ f.map_op' }\n\nend MyHom\n```\n\nThis file will then provide a `CoeFun` instance and various\nextensionality and simp lemmas.\n\n## Morphism classes extending `FunLike`\n\nThe `FunLike` design provides further benefits if you put in a bit more work.\nThe first step is to extend `FunLike` to create a class of those types satisfying\nthe axioms of your new type of morphisms.\nContinuing the example above:\n\n```\n/-- `MyHomClass F A B` states that `F` is a type of `MyClass.op`-preserving morphisms.\nYou should extend this class when you extend `MyHom`. -/\nclass MyHomClass (F : Type _) (A B : outParam <| Type _) [MyClass A] [MyClass B]\n extends FunLike F A (λ _, B) :=\n(map_op : ∀ (f : F) (x y : A), f (MyClass.op x y) = MyClass.op (f x) (f y))\n\n@[simp] lemma map_op {F A B : Type _} [MyClass A] [MyClass B] [MyHomClass F A B]\n (f : F) (x y : A) : f (MyClass.op x y) = MyClass.op (f x) (f y) :=\nMyHomClass.map_op\n\n-- You can replace `MyHom.FunLike` with the below instance:\ninstance : MyHomClass (MyHom A B) A B :=\n{ coe := MyHom.toFun,\n coe_injective' := λ f g h, by cases f; cases g; congr',\n map_op := MyHom.map_op' }\n\n-- [Insert `CoeFun`, `ext` and `copy` here]\n```\n\nThe second step is to add instances of your new `MyHomClass` for all types extending `MyHom`.\nTypically, you can just declare a new class analogous to `MyHomClass`:\n\n```\nstructure CoolerHom (A B : Type _) [CoolClass A] [CoolClass B]\n extends MyHom A B :=\n(map_cool' : toFun CoolClass.cool = CoolClass.cool)\n\nclass CoolerHomClass (F : Type _) (A B : outParam <| Type _) [CoolClass A] [CoolClass B]\n extends MyHomClass F A B :=\n(map_cool : ∀ (f : F), f CoolClass.cool = CoolClass.cool)\n\n@[simp] lemma map_cool {F A B : Type _} [CoolClass A] [CoolClass B] [CoolerHomClass F A B]\n (f : F) : f CoolClass.cool = CoolClass.cool :=\nMyHomClass.map_op\n\n-- You can also replace `MyHom.FunLike` with the below instance:\ninstance : CoolerHomClass (CoolHom A B) A B :=\n{ coe := CoolHom.toFun,\n coe_injective' := λ f g h, by cases f; cases g; congr',\n map_op := CoolHom.map_op',\n map_cool := CoolHom.map_cool' }\n\n-- [Insert `CoeFun`, `ext` and `copy` here]\n```\n\nThen any declaration taking a specific type of morphisms as parameter can instead take the\nclass you just defined:\n```\n-- Compare with: lemma do_something (f : MyHom A B) : sorry := sorry\nlemma do_something {F : Type _} [MyHomClass F A B] (f : F) : sorry := sorry\n```\n\nThis means anything set up for `MyHom`s will automatically work for `CoolerHomClass`es,\nand defining `CoolerHomClass` only takes a constant amount of effort,\ninstead of linearly increasing the work per `MyHom`-related declaration.\n\n-/\n\n-- This instance should have low priority, to ensure we follow the chain\n-- `FunLike → CoeFun`\n-- Porting note: this is an elaboration detail from Lean 3, we are going to disable it\n-- until it is clearer what the Lean 4 elaborator needs.\n-- attribute [instance, priority 10] coe_fn_trans\n\n/-- The class `FunLike F α β` expresses that terms of type `F` have an\ninjective coercion to functions from `α` to `β`.\n\nThis typeclass is used in the definition of the homomorphism typeclasses,\nsuch as `ZeroHomClass`, `MulHomClass`, `MonoidHomClass`, ....\n-/\n@[notation_class * toFun Simps.findCoercionArgs]\nclass FunLike (F : Sort _) (α : outParam (Sort _)) (β : outParam <| α → Sort _) where\n /-- The coercion from `F` to a function. -/\n coe : F → ∀ a : α, β a\n /-- The coercion to functions must be injective. -/\n coe_injective' : Function.Injective coe\n#align fun_like FunLike\n\nsection Dependent\n\n/-! ### `FunLike F α β` where `β` depends on `a : α` -/\n\nvariable (F α : Sort _) (β : α → Sort _)\n\nnamespace FunLike\n\nvariable {F α β} [i : FunLike F α β]\n\ninstance (priority := 100) hasCoeToFun : CoeFun F fun _ ↦ ∀ a : α, β a where coe := FunLike.coe\n\n#eval Lean.Elab.Command.liftTermElabM do\n Std.Tactic.Coe.registerCoercion ``FunLike.coe\n (some { numArgs := 5, coercee := 4, type := .coeFun })\n\n-- @[simp] -- porting note: this loops in lean 4\ntheorem coe_eq_coe_fn : (FunLike.coe (F := F)) = (fun f => ↑f) := rfl\n#align fun_like.coe_eq_coe_fn FunLike.coe_eq_coe_fn\n\ntheorem coe_injective : Function.Injective (fun f : F ↦ (f : ∀ a : α, β a)) :=\n FunLike.coe_injective'\n#align fun_like.coe_injective FunLike.coe_injective\n\n@[simp]\ntheorem coe_fn_eq {f g : F} : (f : ∀ a : α, β a) = (g : ∀ a : α, β a) ↔ f = g :=\n ⟨fun h ↦ FunLike.coe_injective' h, fun h ↦ by cases h; rfl⟩\n#align fun_like.coe_fn_eq FunLike.coe_fn_eq\n\ntheorem ext' {f g : F} (h : (f : ∀ a : α, β a) = (g : ∀ a : α, β a)) : f = g :=\n FunLike.coe_injective' h\n#align fun_like.ext' FunLike.ext'\n\ntheorem ext'_iff {f g : F} : f = g ↔ (f : ∀ a : α, β a) = (g : ∀ a : α, β a) :=\n coe_fn_eq.symm\n#align fun_like.ext'_iff FunLike.ext'_iff\n\ntheorem ext (f g : F) (h : ∀ x : α, f x = g x) : f = g :=\n FunLike.coe_injective' (funext h)\n#align fun_like.ext FunLike.ext\n\ntheorem ext_iff {f g : F} : f = g ↔ ∀ x, f x = g x :=\n coe_fn_eq.symm.trans Function.funext_iff\n#align fun_like.ext_iff FunLike.ext_iff\n\nprotected theorem congr_fun {f g : F} (h₁ : f = g) (x : α) : f x = g x :=\n congr_fun (congr_arg _ h₁) x\n#align fun_like.congr_fun FunLike.congr_fun\n\ntheorem ne_iff {f g : F} : f ≠ g ↔ ∃ a, f a ≠ g a :=\n ext_iff.not.trans not_forall\n#align fun_like.ne_iff FunLike.ne_iff\n\n\n\n/-- This is not an instance to avoid slowing down every single `Subsingleton` typeclass search.-/\nlemma subsingleton_cod [∀ a, Subsingleton (β a)] : Subsingleton F :=\n⟨fun _ _ ↦ coe_injective $ Subsingleton.elim _ _⟩\n#align fun_like.subsingleton_cod FunLike.subsingleton_cod\n\nend FunLike\n\nend Dependent\n\nsection NonDependent\n\n/-! ### `FunLike F α (λ _, β)` where `β` does not depend on `a : α` -/\n\nvariable {F α β : Sort _} [i : FunLike F α fun _ ↦ β]\n\nnamespace FunLike\n\nprotected theorem congr {f g : F} {x y : α} (h₁ : f = g) (h₂ : x = y) : f x = g y :=\n congr (congr_arg _ h₁) h₂\n#align fun_like.congr FunLike.congr\n\nprotected theorem congr_arg (f : F) {x y : α} (h₂ : x = y) : f x = f y :=\n congr_arg _ h₂\n#align fun_like.congr_arg FunLike.congr_arg\n\nend FunLike\n\nend NonDependent\n", "meta": {"author": "leanprover-community", "repo": "mathlib4", "sha": "b9a0a30342ca06e9817e22dbe46e75fc7f435500", "save_path": "github-repos/lean/leanprover-community-mathlib4", "path": "github-repos/lean/leanprover-community-mathlib4/mathlib4-b9a0a30342ca06e9817e22dbe46e75fc7f435500/Mathlib/Data/FunLike/Basic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35577487985229844, "lm_q2_score": 0.08269734606617778, "lm_q1q2_score": 0.029421638360798343}} {"text": "/-\nCopyright (c) 2019 Simon Hudon. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Simon Hudon\n\n! This file was ported from Lean 3 source module tactic.apply\n! leanprover-community/mathlib commit 8f6fd1b69096c6a587f745d354306c0d46396915\n! Please do not edit these lines, except to modify the commit id\n! if you have ported upstream changes.\n-/\nimport Mathbin.Tactic.Core\n\n/-!\nThis file provides an alternative implementation for `apply` to fix the so-called \"apply bug\".\n\nThe issue arises when the goals is a Π-type -- whether it is visible or hidden behind a definition.\n\nFor instance, consider the following proof:\n\n```\nexample {α β} (x y z : α → β) (h₀ : x ≤ y) (h₁ : y ≤ z) : x ≤ z :=\nbegin\n apply le_trans,\nend\n```\n\nBecause `x ≤ z` is definitionally equal to `∀ i, x i ≤ z i`, `apply` will fail. The alternative\ndefinition, `apply'` fixes this. When `apply` would work, `apply` is used and otherwise,\na different strategy is deployed\n-/\n\n\nnamespace Tactic\n\n/-- With `gs` a list of proof goals, `reorder_goals gs new_g` will use the `new_goals` policy\n`new_g` to rearrange the dependent goals to either drop them, push them to the end of the list\nor leave them in place. The `bool` values in `gs` indicates whether the goal is dependent or not. -/\ndef reorderGoals {α} (gs : List (Bool × α)) : NewGoals → List α\n | new_goals.non_dep_first =>\n let ⟨dep, non_dep⟩ := gs.partitionₓ (coe ∘ Prod.fst)\n non_dep.map Prod.snd ++ dep.map Prod.snd\n | new_goals.non_dep_only => (gs.filterₓ (coe ∘ not ∘ Prod.fst)).map Prod.snd\n | new_goals.all => gs.map Prod.snd\n#align tactic.reorder_goals Tactic.reorderGoals\n\nprivate unsafe def has_opt_auto_param_inst_for_apply (ms : List (Name × expr)) : tactic Bool :=\n ms.foldlM\n (fun r m => do\n let type ← infer_type m.2\n let b ← is_class type\n return <| r || type `opt_param 2 || type `auto_param 2 || b)\n false\n#align tactic.has_opt_auto_param_inst_for_apply tactic.has_opt_auto_param_inst_for_apply\n\nprivate unsafe def try_apply_opt_auto_param_instance_for_apply (cfg : ApplyCfg)\n (ms : List (Name × expr)) : tactic Unit :=\n whenM (has_opt_auto_param_inst_for_apply ms) do\n let gs ← get_goals\n ms fun m =>\n whenM (not <$> is_assigned m.2) <|\n ((set_goals [m.2] >> try apply_instance) >> when cfg (try apply_opt_param)) >>\n when cfg (try apply_auto_param)\n set_goals gs\n#align tactic.try_apply_opt_auto_param_instance_for_apply tactic.try_apply_opt_auto_param_instance_for_apply\n\nprivate unsafe def retry_apply_aux :\n ∀ (e : expr) (cfg : ApplyCfg), List (Bool × Name × expr) → tactic (List (Name × expr))\n | e, cfg, gs =>\n (focus1 do\n let tgt : expr ← target\n let t ← infer_type e\n unify t tgt\n exact e\n let gs' ← get_goals\n let r := reorderGoals gs.reverse cfg.NewGoals\n set_goals (gs' ++ r Prod.snd)\n return r) <|>\n do\n let expr.pi n bi d b ← infer_type e >>= whnf |\n apply_core e cfg\n let v ← mk_meta_var d\n let b := b.has_var\n let e ← head_beta <| e v\n retry_apply_aux e cfg ((b, n, v) :: gs)\n#align tactic.retry_apply_aux tactic.retry_apply_aux\n\nprivate unsafe def retry_apply (e : expr) (cfg : ApplyCfg) : tactic (List (Name × expr)) :=\n apply_core e cfg <|> retry_apply_aux e cfg []\n#align tactic.retry_apply tactic.retry_apply\n\n/-- `apply'` mimics the behavior of `apply_core`. When\n`apply_core` fails, it is retried by providing the term with meta\nvariables as additional arguments. The meta variables can then\nbecome new goals depending on the `cfg.new_goals` policy.\n\n`apply'` also finds instances and applies opt_params and auto_params. -/\nunsafe def apply' (e : expr) (cfg : ApplyCfg := { }) : tactic (List (Name × expr)) := do\n let r ← retry_apply e cfg\n try_apply_opt_auto_param_instance_for_apply cfg r\n return r\n#align tactic.apply' tactic.apply'\n\n/-- Same as `apply'` but __all__ arguments that weren't inferred are added to goal list. -/\nunsafe def fapply' (e : expr) : tactic (List (Name × expr)) :=\n apply' e { NewGoals := NewGoals.all }\n#align tactic.fapply' tactic.fapply'\n\n/-- Same as `apply'` but only goals that don't depend on other goals are added to goal list. -/\nunsafe def eapply' (e : expr) : tactic (List (Name × expr)) :=\n apply' e { NewGoals := NewGoals.non_dep_only }\n#align tactic.eapply' tactic.eapply'\n\n/-- `relation_tactic` finds a proof rule for the relation found in the goal and uses `apply'`\nto make one proof step. -/\nprivate unsafe def relation_tactic (md : Transparency) (op_for : environment → Name → Option Name)\n (tac_name : String) : tactic Unit := do\n let tgt ← target >>= instantiate_mvars\n let env ← get_env\n let r := expr.get_app_fn tgt\n match op_for env (expr.const_name r) with\n | some refl => do\n let r ← mk_const refl\n retry_apply r\n { md\n NewGoals := new_goals.non_dep_only }\n return ()\n | none =>\n fail <|\n tac_name ++\n \" tactic failed, target is not a relation application with the expected property.\"\n#align tactic.relation_tactic tactic.relation_tactic\n\n/-- Similar to `reflexivity` with the difference that `apply'` is used instead of `apply` -/\nunsafe def reflexivity' (md := semireducible) : tactic Unit :=\n relation_tactic md environment.refl_for \"reflexivity\"\n#align tactic.reflexivity' tactic.reflexivity'\n\n/-- Similar to `symmetry` with the difference that `apply'` is used instead of `apply` -/\nunsafe def symmetry' (md := semireducible) : tactic Unit :=\n relation_tactic md environment.symm_for \"symmetry\"\n#align tactic.symmetry' tactic.symmetry'\n\n/-- Similar to `transitivity` with the difference that `apply'` is used instead of `apply` -/\nunsafe def transitivity' (md := semireducible) : tactic Unit :=\n relation_tactic md environment.trans_for \"transitivity\"\n#align tactic.transitivity' tactic.transitivity'\n\nnamespace Interactive\n\n/- ./././Mathport/Syntax/Translate/Tactic/Mathlib/Core.lean:38:34: unsupported: setup_tactic_parser -/\n/-- Similarly to `apply`, the `apply'` tactic tries to match the current goal against the conclusion\nof the type of term.\n\nIt differs from `apply` in that it does not unfold definition in order to find out what the\nassumptions of the provided term is. It is especially useful when defining relations on function\nspaces (e.g. `≤`) so that rules like transitivity on `le : (α → β) → (α → β) → (α → β)` will be\nconsidered to have three parameters and two assumptions (i.e. `f g h : α → β`, `H₀ : f ≤ g`,\n`H₁ : g ≤ h`) instead of three parameters, two assumptions and then one more parameter\n(i.e. `f g h : α → β`, `H₀ : f ≤ g`, `H₁ : g ≤ h`, `x : α`). Whereas `apply` would expect the goal\n`f x ≤ h x`, `apply'` will work with the goal `f ≤ h`.\n-/\nunsafe def apply' (q : parse texpr) : tactic Unit :=\n concat_tags do\n let h ← i_to_expr_for_apply q\n tactic.apply' h\n#align tactic.interactive.apply' tactic.interactive.apply'\n\n/-- Similar to the `apply'` tactic, but does not reorder goals.\n-/\nunsafe def fapply' (q : parse texpr) : tactic Unit :=\n concat_tags (i_to_expr_for_apply q >>= tactic.fapply')\n#align tactic.interactive.fapply' tactic.interactive.fapply'\n\n/--\nSimilar to the `apply'` tactic, but only creates subgoals for non-dependent premises that have not\nbeen fixed by type inference or type class resolution.\n-/\nunsafe def eapply' (q : parse texpr) : tactic Unit :=\n concat_tags (i_to_expr_for_apply q >>= tactic.eapply')\n#align tactic.interactive.eapply' tactic.interactive.eapply'\n\n/--\nSimilar to the `apply'` tactic, but allows the user to provide a `apply_cfg` configuration object.\n-/\nunsafe def apply_with' (q : parse parser.pexpr) (cfg : ApplyCfg) : tactic Unit :=\n concat_tags do\n let e ← i_to_expr_for_apply q\n tactic.apply' e cfg\n#align tactic.interactive.apply_with' tactic.interactive.apply_with'\n\n/-- Similar to the `apply'` tactic, but uses matching instead of unification.\n`mapply' t` is equivalent to `apply_with' t {unify := ff}`\n-/\nunsafe def mapply' (q : parse texpr) : tactic Unit :=\n concat_tags do\n let e ← i_to_expr_for_apply q\n tactic.apply' e { unify := ff }\n#align tactic.interactive.mapply' tactic.interactive.mapply'\n\n/-- Similar to `reflexivity` with the difference that `apply'` is used instead of `apply`.\n-/\nunsafe def reflexivity' : tactic Unit :=\n tactic.reflexivity'\n#align tactic.interactive.reflexivity' tactic.interactive.reflexivity'\n\n/-- Shorter name for the tactic `reflexivity'`.\n-/\nunsafe def refl' : tactic Unit :=\n tactic.reflexivity'\n#align tactic.interactive.refl' tactic.interactive.refl'\n\n/--\n`symmetry'` behaves like `symmetry` but also offers the option `symmetry' at h` to apply symmetry\nto assumption `h`\n-/\nunsafe def symmetry' : parse location → tactic Unit\n | l@loc.wildcard => l.try_apply symmetry_hyp tactic.symmetry'\n | loc.ns hs => (Loc.ns hs.reverse).apply symmetry_hyp tactic.symmetry'\n#align tactic.interactive.symmetry' tactic.interactive.symmetry'\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:207:4: warning: unsupported notation `parser.optional -/\n/-- Similar to `transitivity` with the difference that `apply'` is used instead of `apply`.\n-/\nunsafe def transitivity' (q : parse (parser.optional texpr)) : tactic Unit :=\n tactic.transitivity' >>\n match q with\n | none => skip\n | some q => do\n let (r, lhs, rhs) ← target_lhs_rhs\n let t ← infer_type lhs\n i_to_expr ``(($(q) : $(t))) >>= unify rhs\n#align tactic.interactive.transitivity' tactic.interactive.transitivity'\n\nend Interactive\n\nend Tactic\n\n", "meta": {"author": "leanprover-community", "repo": "mathlib3port", "sha": "62505aa236c58c8559783b16d33e30df3daa54f4", "save_path": "github-repos/lean/leanprover-community-mathlib3port", "path": "github-repos/lean/leanprover-community-mathlib3port/mathlib3port-62505aa236c58c8559783b16d33e30df3daa54f4/Mathbin/Tactic/Apply.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35936414516010196, "lm_q2_score": 0.08151976266900195, "lm_q1q2_score": 0.029295279825200277}} {"text": "/-\nCopyright (c) 2020 Dany Fabian. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Dany Fabian\n-/\n\nimport tactic.split_ifs\n/-!\n # Unfold cases tactic\n\n In Lean, pattern matching expressions are not atomic parts of the syntax, but\n rather they are compiled down into simpler terms that are later checked by the kernel.\n\n This allows Lean to have a minimalistic kernel but can occasionally lead an explosion\n of cases that need to be considered. What looks like one case in the `match` expression\n can in fact be compiled into many different cases that all need to proved by case analysis.\n\n This tactic automates the process by allowing us to write down an equation `f x = y`\n where we know that `f x = y` is provably true, but does not hold definitionally. In that\n case the `unfold_cases` tactic will continue unfolding `f` and introducing `cases` where\n necessary until the left hand side becomes definitionally equal to the right hand side.\n\n Consider a definition as follows:\n\n ```lean\n def myand : bool → bool → bool\n | ff _ := ff\n | _ ff := ff\n | _ _ := tt\n ```\n\n The equation compiler generates 4 equation lemmas for us:\n ```lean\n myand ff ff = ff\n myand ff tt = ff\n myand tt ff = ff\n myand tt tt = tt\n ```\n\n This is not in line with what one might expect looking at the definition.\n Whilst it is provably true, that `∀ x, myand ff x = ff` and `∀ x, myand x ff = ff`,\n we do not get these stronger lemmas from the compiler for free but must in fact\n prove them using `cases` or some other local reasoning.\n\n In other words, the following does not constitute a proof that lean accepts.\n ```lean\n example : ∀ x, myand ff x = ff :=\n begin\n intros, refl\n end\n ```\n\n However, you can use `unfold_cases { refl }` to prove `∀ x, myand ff x = ff` and\n `∀ x, myand x ff = ff`. For definitions with many cases, the savings can be very\n significant.\n\n The term that gets generated for the above definition looks like this:\n ```lean\n λ (a a_1 : bool),\n a.cases_on\n (a_1.cases_on (id_rhs bool ff) (id_rhs bool ff))\n (a_1.cases_on (id_rhs bool ff) (id_rhs bool tt))\n ```\n\n When the tactic tries to prove the goal `∀ x, myand ff x = ff`, it starts by `intros`,\n followed by unfolding the definition:\n ```lean\n ⊢ ff.cases_on\n (x.cases_on (id_rhs bool ff) (id_rhs bool ff))\n (x.cases_on (id_rhs bool ff) (id_rhs bool tt)) = ff\n ```\n\n At this point, it can make progress using `dsimp`. But then it gets stuck:\n ```lean\n ⊢ bool.rec (id_rhs bool ff) (id_rhs bool ff) x = ff\n ```\n\n Next, it can introduce a case split on `x`. At this point, it has to prove two\n goals:\n ```lean\n ⊢ bool.rec (id_rhs bool ff) (id_rhs bool ff) ff = ff\n ⊢ bool.rec (id_rhs bool ff) (id_rhs bool ff) tt = ff\n ```\n\n Now, however, both goals can be discharged using `refl`.\n-/\nnamespace tactic\nopen expr\nnamespace unfold_cases\n/--\n Given an equation `f x = y`, this tactic tries to infer an expression that can be\n used to do distinction by cases on to make progress.\n\n Pre-condition: assumes that the outer-most application cannot be beta-reduced\n (e.g. `whnf` or `dsimp`).\n-/\nmeta def find_splitting_expr : expr → tactic expr\n| `(@ite _ %%cond %%dec_inst _ _ = _) := pure `(@decidable.em %%cond %%dec_inst)\n| `(%%(app x y) = _) := pure y\n| e := fail!\"expected an expression of the form: f x = y. Got:\\n{e}\"\n\n/--\n Tries to finish the current goal using the `inner` tactic. If the tactic\n fails, it tries to find an expression on which to do a distinction by\n cases and calls itself recursively.\n\n The order of operations is significant. Because the unfolding can potentially\n be infinite, it is important to apply the `inner` tactic at every step.\n\n Notice, that if the `inner` tactic succeeds, the recursive unfolding is stopped.\n-/\nmeta def unfold_cases_core (inner : interactive.itactic) : tactic unit :=\ninner <|>\n(do split_ifs [], all_goals unfold_cases_core, skip) <|>\ndo\n tgt ← target,\n e ← find_splitting_expr tgt,\n focus1 $ do\n cases e,\n all_goals $ (dsimp_target >> unfold_cases_core) <|> skip,\n skip\n\n/--\n Given a target of the form `⊢ f x₁ ... xₙ = y`, unfolds `f` using a delta reduction.\n-/\nmeta def unfold_tgt : expr → tactic unit\n| `(%%l@(app _ _) = %%r) :=\n match l.get_app_fn with\n | const n ls := delta_target [n]\n | e := fail!\"couldn't unfold:\\n{e}\"\n end\n| e := fail!\"expected an expression of the form: f x = y. Got:\\n{e}\"\nend unfold_cases\n\nnamespace interactive\nopen unfold_cases\n\n/--\n This tactic unfolds the definition of a function or `match` expression.\n Then it recursively introduces a distinction by cases. The decision what expression\n to do the distinction on is driven by the pattern matching expression.\n\n A typical use case is using `unfold_cases { refl }` to collapse cases that need to be\n considered in a pattern matching.\n\n ```lean\n have h : foo x = y, by unfold_cases { refl },\n rw h,\n ```\n\n The tactic expects a goal in the form of an equation, possibly universally quantified.\n\n We can prove a theorem, even if the various case do not directly correspond to the\n function definition. Here is an example application of the tactic:\n\n ```lean\n def foo : ℕ → ℕ → ℕ\n | 0 0 := 17\n | (n+2) 17 := 17\n | 1 0 := 23\n | 0 (n+18) := 15\n | 0 17 := 17\n | 1 17 := 17\n | _ (n+18) := 27\n | _ _ := 15\n\n example : ∀ x, foo x 17 = 17 :=\n begin\n unfold_cases { refl },\n end\n ```\n\n The compiler generates 57 cases for `foo`. However, when we look at the definition, we see\n that whenever the function is applied to `17` in the second argument, it returns `17`.\n\n Proving this property consists of merely considering all the cases, eliminating invalid ones\n and applying `refl` on the ones which remain.\n\n Further examples can be found in `test/unfold_cases.lean`.\n-/\nmeta def unfold_cases (inner : itactic) : tactic unit := focus1 $ do\n tactic.intros,\n tgt ← target,\n unfold_tgt tgt,\n try dsimp_target,\n unfold_cases_core inner\n\nadd_tactic_doc\n{ name := \"unfold_cases\",\n category := doc_category.tactic,\n decl_names := [`tactic.interactive.unfold_cases],\n tags := [\"induction\", \"case bashing\"] }\n\nend interactive\nend tactic\n", "meta": {"author": "leanprover-community", "repo": "mathlib", "sha": "5e526d18cea33550268dcbbddcb822d5cde40654", "save_path": "github-repos/lean/leanprover-community-mathlib", "path": "github-repos/lean/leanprover-community-mathlib/mathlib-5e526d18cea33550268dcbbddcb822d5cde40654/src/tactic/unfold_cases.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2782567937024021, "lm_q2_score": 0.10521052968901465, "lm_q1q2_score": 0.0292755446549966}} {"text": "/-\nCopyright (c) 2021 Gabriel Ebner. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Gabriel Ebner\n-/\nimport Lean\nimport Mathlib.Logic.Nonempty\n\n/-!\n# Once-per-file cache for tactics\n\nThis file defines cache data structures for tactics\nthat are initialized the first time they are accessed.\nSince Lean 4 starts one process per file,\nthese caches are once-per-file\nand can for example be used to cache information\nabout the imported modules.\n\nThe `Cache α` data structure is\nthe most generic version we define.\nIt is created using `Cache.mk f`\nwhere `f : MetaM α` performs\nthe initialization of the cache:\n```\ninitialize numberOfImports : Cache Nat ← Cache.mk do\n (← getEnv).imports.size\n\n-- (does not work in the same module where the cache is defined)\n#eval show MetaM Nat from numberOfImports.get\n```\n\nThe `DeclCache α` data structure computes\na fold over the environment's constants:\n`DeclCache.mk empty f` constructs such a cache\nwhere `empty : α` and `f : Name → ConstantInfo → α → MetaM α`.\nThe result of the constants in the imports is cached\nbetween tactic invocations,\nwhile for constants defined in the same file\n`f` is evaluated again every time.\nThis kind of cache can be used e.g.\nto populate discrimination trees.\n-/\n\nopen Lean Meta\n\nnamespace Mathlib.Tactic\n\n/-- Once-per-file cache. -/\ndef Cache (α : Type) :=\n IO.Ref <| Sum (MetaM α) <|\n Task <| Except Exception α\n\ninstance : Nonempty (Cache α) :=\n inferInstanceAs <| Nonempty (IO.Ref _)\n\n/-- Creates a cache with an initialization function. -/\ndef Cache.mk (init : MetaM α) : IO (Cache α) :=\n IO.mkRef <| Sum.inl init\n\n/--\nAccess the cache.\nCalling this function for the first time\nwill initialize the cache with the function\nprovided in the constructor.\n-/\ndef Cache.get [Monad m] [MonadEnv m] [MonadLog m] [MonadOptions m] [MonadLiftT BaseIO m]\n [MonadExcept Exception m] (cache : Cache α) : m α := do\n let t ← match ← show BaseIO _ from ST.Ref.get cache with\n | Sum.inr t => pure t\n | Sum.inl init =>\n let env ← getEnv\n let fileName ← getFileName\n let fileMap ← getFileMap\n let options ← getOptions -- TODO: sanitize options?\n -- Default heartbeats to a reasonable value.\n -- otherwise librarySearch times out on mathlib\n -- TODO: add customization option\n let options := Core.maxHeartbeats.set options <|\n options.get? Core.maxHeartbeats.name |>.getD 1000000\n let res ← EIO.asTask do\n let metaCtx : Meta.Context := {}\n let metaState : Meta.State := {}\n let coreCtx : Core.Context := {options, fileName, fileMap}\n let coreState : Core.State := {env}\n pure (← ((init ‹_›).run ‹_› ‹_›).run ‹_›).1.1\n show BaseIO _ from cache.set (Sum.inr res)\n pure res\n match t.get with\n | Except.ok res => pure res\n | Except.error err => throw err\n\n/--\nCached fold over the environment's declarations,\nwhere a given function is applied to `α` for every constant.\n-/\ndef DeclCache (α : Type) :=\n Cache α × (Name → ConstantInfo → α → MetaM α)\n\ninstance : Nonempty (DeclCache α) :=\n inferInstanceAs <| Nonempty (_ × _)\n\n/--\nCreates a `DeclCache`.\nThe cached structure `α` is initialized with `empty`,\nand then `addDecl` is called for every constant in the environment.\nCalls to `addDecl` for imported constants are cached.\n-/\ndef DeclCache.mk (profilingName : String) (empty : α)\n (addDecl : Name → ConstantInfo → α → MetaM α) : IO (DeclCache α) := do\n let cache ← Cache.mk do\n profileitM Exception profilingName (← getOptions) do\n let mut a := empty\n for (n, c) in (← getEnv).constants.map₁.toList do\n a ← addDecl n c a\n return a\n pure (cache, addDecl)\n\n/--\nAccess the cache.\nCalling this function for the first time\nwill initialize the cache with the function\nprovided in the constructor.\n-/\ndef DeclCache.get (cache : DeclCache α) : MetaM α := do\n let mut a ← cache.1.get\n for (n, c) in (← getEnv).constants.map₂.toList do\n a ← cache.2 n c a\n return a\n", "meta": {"author": "leanprover-community", "repo": "mathlib4", "sha": "b9a0a30342ca06e9817e22dbe46e75fc7f435500", "save_path": "github-repos/lean/leanprover-community-mathlib4", "path": "github-repos/lean/leanprover-community-mathlib4/mathlib4-b9a0a30342ca06e9817e22dbe46e75fc7f435500/Mathlib/Tactic/Cache.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2974699426047947, "lm_q2_score": 0.098079318197847, "lm_q1q2_score": 0.029175649155030944}} {"text": "import category_theory.preadditive.functor_category\n\nimport pseudo_normed_group.FP\nimport locally_constant.SemiNormedGroup\nimport locally_constant.Vhat\n\n/-!\n\n# The category of locally constant maps\n\nVarious constructions of pseudo-normed groups of locally constant functions.\n\n## Main definitions\n\n- `LC V`: the functor sending a profinite set `S` to the locally constant\n functions from `S` to `V`\n- `LCFP V r' c n`: the functor sending a profinitely filtered pseudo-normed\n group with T⁻¹ to V(M_c^n), the locally constant functions from M_c^n to V.\n\n-/\nnamespace category_theory\nnamespace nat_trans\n\n@[simp] lemma op_comp {C D} [category C] [category D]\n {F G H : C ⥤ D} {α : F ⟶ G} {β : G ⟶ H} :\n nat_trans.op (α ≫ β) = nat_trans.op β ≫ nat_trans.op α := rfl\n\nend nat_trans\nend category_theory\n\nopen_locale classical nnreal big_operators\nnoncomputable theory\nlocal attribute [instance] type_pow\n\nopen SemiNormedGroup opposite Profinite pseudo_normed_group category_theory breen_deligne\nopen profinitely_filtered_pseudo_normed_group\n\nuniverse variable u\nvariables (r : ℝ≥0) (V : SemiNormedGroup) (r' : ℝ≥0)\nvariables (c c₁ c₂ c₃ c₄ : ℝ≥0) (l m n : ℕ)\n\n/-- `LC V n` is the functor that sends a profinite set `S` to `V(S)` -/\ndef LC (V : SemiNormedGroup) : Profiniteᵒᵖ ⥤ SemiNormedGroup :=\nLocallyConstant.obj V\n\nnamespace LC\n\nlemma map_norm_noninc {M₁ M₂} (f : M₁ ⟶ M₂) : ((LC V).map f).norm_noninc :=\nlocally_constant.comap_hom_norm_noninc _ _\n\ninstance obj.normed_with_aut [normed_with_aut r V] [fact (0 < r)] (A : Profiniteᵒᵖ) :\n normed_with_aut r ((LC V).obj A) :=\nSemiNormedGroup.normed_with_aut_LocallyConstant _ _ _\n\n@[simps hom_app_apply inv_app_apply {fully_applied := ff}]\ndef T [normed_with_aut r V] : LC V ≅ LC V :=\nLocallyConstant.map_iso normed_with_aut.T\n\nlemma T_eq [normed_with_aut r V] [fact (0 < r)] (A) :\n (T r V).hom.app A = normed_with_aut.T.hom := rfl\n\nlemma norm_T_le [normed_with_aut r V] [fact (0 < r)] (A) :\n ∥(LC.T r V).hom.app A∥ ≤ r :=\nbegin\n rw T_eq,\n refine normed_add_group_hom.op_norm_le_bound _ (nnreal.zero_le_coe) (λ v, _),\n exact le_of_eq (normed_with_aut.norm_T v)\nend\n\n@[simps {fully_applied := ff}]\ndef T_inv [normed_with_aut r V] [fact (0 < r)] : LC V ⟶ LC V :=\n(LocallyConstant.map (normed_with_aut.T.inv : V ⟶ V) : _)\n\nlemma T_inv_eq [normed_with_aut r V] [fact (0 < r)] : (T r V).inv = T_inv r V := rfl\n\nlemma T_inv_eq' [normed_with_aut r V] [fact (0 < r)] (A) :\n (T_inv r V).app A = normed_with_aut.T.inv := rfl\n\nlemma norm_T_inv_le [normed_with_aut r V] [fact (0 < r)] (A) :\n ∥(T_inv r V).app A∥ ≤ r⁻¹ :=\nbegin\n rw T_inv_eq',\n refine normed_add_group_hom.op_norm_le_bound _ (inv_nonneg.2 (nnreal.zero_le_coe)) (λ v, _),\n exact (normed_with_aut.norm_T_inv _ v).le\nend\n\nend LC\n\n/-- The \"functor\" that sends `M` and `c` to `V((filtration M c)^n)` -/\ndef LCFP (V : SemiNormedGroup) (r' : ℝ≥0) (c : ℝ≥0) (n : ℕ) :\n (ProFiltPseuNormGrpWithTinv r')ᵒᵖ ⥤ SemiNormedGroup :=\n(FiltrationPow r' c n).op ⋙ LC V\n\ntheorem LCFP_def (V : SemiNormedGroup) (r' : ℝ≥0) (c : ℝ≥0) (n : ℕ) :\n LCFP V r' c n = (FiltrationPow r' c n).op ⋙ LocallyConstant.obj V := rfl\n\nnamespace LCFP\n\nlemma map_norm_noninc {M₁ M₂} (f : M₁ ⟶ M₂) : ((LCFP V r' c n).map f).norm_noninc :=\nLC.map_norm_noninc _ _\n\n@[simps {fully_applied := ff}]\ndef res (r' : ℝ≥0) (c₁ c₂ : ℝ≥0) [fact (c₂ ≤ c₁)] (n : ℕ) : LCFP V r' c₁ n ⟶ LCFP V r' c₂ n :=\n(whisker_right (nat_trans.op (FiltrationPow.cast_le r' c₂ c₁ n)) (LocallyConstant.obj V) : _)\n\n@[simp] lemma res_refl : res V r' c c n = 𝟙 _ :=\nby { simp [res, FiltrationPow.cast_le_refl], refl }\n\nlemma res_comp_res [h₁ : fact (c₃ ≤ c₂)] [h₂ : fact (c₂ ≤ c₁)] :\n res V r' c₁ c₂ n ≫ res V r' c₂ c₃ n = @res V r' c₁ c₃ ⟨le_trans h₁.1 h₂.1⟩ n :=\nby simp only [res, ← whisker_right_comp, ← nat_trans.op_comp, FiltrationPow.cast_le_comp]\n\nlemma res_norm_noninc [fact (c₂ ≤ c₁)] (M) : ((res V r' c₁ c₂ n).app M).norm_noninc :=\nlocally_constant.comap_hom_norm_noninc _ _\n\nsection Tinv\nopen profinitely_filtered_pseudo_normed_group_with_Tinv\nvariables [fact (0 < r')]\n\n@[simps {fully_applied := ff}]\ndef Tinv [fact (c₂ ≤ r' * c₁)] : LCFP V r' c₁ n ⟶ LCFP V r' c₂ n :=\n(whisker_right (nat_trans.op $ FiltrationPow.Tinv r' c₂ c₁ n) (LocallyConstant.obj V) : _)\n\nlemma Tinv_def [fact (c₂ ≤ r' * c₁)] : Tinv V r' c₁ c₂ n =\n whisker_right (nat_trans.op $ FiltrationPow.Tinv r' c₂ c₁ n) (LC V) := rfl\n\nlemma res_comp_Tinv\n [fact (c₂ ≤ c₁)] [fact (c₃ ≤ c₂)] [fact (c₂ ≤ r' * c₁)] [fact (c₃ ≤ r' * c₂)] :\n res V r' c₁ c₂ n ≫ Tinv V r' c₂ c₃ n = Tinv V r' c₁ c₂ n ≫ res V r' c₂ c₃ n :=\nbegin\n simp only [Tinv, res, ← whisker_right_comp, ← nat_trans.op_comp],\n refl\nend\n\nlemma Tinv_norm_noninc [fact (c₂ ≤ r' * c₁)] (M) : ((Tinv V r' c₁ c₂ n).app M).norm_noninc :=\nlocally_constant.comap_hom_norm_noninc _ _\n\nend Tinv\n\nsection normed_with_aut\n\nvariables [normed_with_aut r V]\n\ninstance [fact (0 < r)] (M) : normed_with_aut r ((LCFP V r' c n).obj M) :=\nLC.obj.normed_with_aut _ _ _\n\n@[simps {fully_applied := ff}]\ndef T [fact (0 < r)] : LCFP V r' c n ≅ LCFP V r' c n :=\n((whiskering_left _ _ _).obj _).map_iso $ LC.T _ _\n\n@[simps app_apply {fully_applied := ff}]\ndef T_inv [fact (0 < r)] : LCFP V r' c n ⟶ LCFP V r' c n :=\n(whisker_left _ (LC.T_inv r V) : _)\n\nlemma T_inv_eq [fact (0 < r)] : (T r V r' c n).inv = T_inv r V r' c n := rfl\n\nlemma T_inv_def [fact (0 < r)] :\n T_inv r V r' c n = (whisker_left (FiltrationPow r' c n).op\n (LocallyConstant.map (normed_with_aut.T.inv : V ⟶ V)) : _) :=\nrfl\n\nend normed_with_aut\n\nend LCFP\n\nnamespace breen_deligne\n\nopen LCFP\n\nvariables {l m n}\n\nnamespace basic_universal_map\n\nvariables (ϕ : basic_universal_map m n)\n\ndef eval_LCFP (c₁ c₂ : ℝ≥0) [ϕ.suitable c₂ c₁] : LCFP V r' c₁ n ⟶ LCFP V r' c₂ m :=\n(whisker_right (nat_trans.op $ ϕ.eval_FP r' c₂ c₁) (LocallyConstant.obj V) : _)\n\ndef eval_LCFP' (c₁ c₂ : ℝ≥0) : LCFP V r' c₁ n ⟶ LCFP V r' c₂ m :=\nif H : ϕ.suitable c₂ c₁\nthen by exactI (whisker_right (nat_trans.op $ ϕ.eval_FP r' c₂ c₁) (LocallyConstant.obj V) : _)\nelse 0\n\nlemma eval_LCFP_eq_eval_LCFP' (h : ϕ.suitable c₂ c₁) :\n ϕ.eval_LCFP V r' c₁ c₂ = ϕ.eval_LCFP' V r' c₁ c₂ :=\nby { delta eval_LCFP eval_LCFP', rw dif_pos h }\n\nlemma eval_LCFP'_def [h : ϕ.suitable c₂ c₁] :\n ϕ.eval_LCFP' V r' c₁ c₂ =\n (whisker_right (nat_trans.op $ ϕ.eval_FP r' c₂ c₁) (LocallyConstant.obj V) : _) :=\ndif_pos h\n\nlemma eval_LCFP'_not_suitable (h : ¬ ϕ.suitable c₂ c₁) :\n ϕ.eval_LCFP' V r' c₁ c₂ = 0 :=\ndif_neg h\n\nlemma eval_LCFP'_comp (f : basic_universal_map m n) (g : basic_universal_map l m)\n [hf : f.suitable c₂ c₁] [hg : g.suitable c₃ c₂] :\n (basic_universal_map.comp f g).eval_LCFP' V r' c₁ c₃ = f.eval_LCFP' V r' c₁ c₂ ≫ g.eval_LCFP' V r' c₂ c₃ :=\nbegin\n haveI : (basic_universal_map.comp f g).suitable c₃ c₁ := suitable_comp c₂,\n simp only [eval_LCFP'_def, eval_FP_comp r' _ c₂, nat_trans.op_comp, whisker_right_comp]\nend\n\nlemma eval_LCFP_comp (f : basic_universal_map m n) (g : basic_universal_map l m)\n [hf : f.suitable c₂ c₁] [hg : g.suitable c₃ c₂] :\n @eval_LCFP V r' _ _ (basic_universal_map.comp f g) c₁ c₃ (suitable_comp c₂) =\n f.eval_LCFP V r' c₁ c₂ ≫ g.eval_LCFP V r' c₂ c₃ :=\nby { simp only [eval_LCFP_eq_eval_LCFP'], apply eval_LCFP'_comp }\n\nlemma res_comp_eval_LCFP\n [fact (c₂ ≤ c₁)] [fact (c₄ ≤ c₃)] [ϕ.suitable c₄ c₂] [ϕ.suitable c₃ c₁] :\n res V r' c₁ c₂ n ≫ ϕ.eval_LCFP V r' c₂ c₄ = ϕ.eval_LCFP V r' c₁ c₃ ≫ res V r' c₃ c₄ m :=\nby simp only [res, eval_LCFP, ← whisker_right_comp, ← nat_trans.op_comp,\n cast_le_comp_eval_FP _ c₄ c₃ c₂ c₁]\n\nlemma Tinv_comp_eval_LCFP [fact (0 < r')] [fact (c₂ ≤ r' * c₁)] [fact (c₄ ≤ r' * c₃)]\n [ϕ.suitable c₄ c₂] [ϕ.suitable c₃ c₁] :\n Tinv V r' c₁ c₂ n ≫ ϕ.eval_LCFP V r' c₂ c₄ = ϕ.eval_LCFP V r' c₁ c₃ ≫ Tinv V r' c₃ c₄ m :=\nby simp only [Tinv, eval_LCFP, ← whisker_right_comp, ← nat_trans.op_comp,\n Tinv_comp_eval_FP _ _ c₄ c₃ c₂ c₁]\n\nlemma T_inv_comp_eval_LCFP [normed_with_aut r V] [fact (0 < r)] [ϕ.suitable c₂ c₁] :\n T_inv r V r' c₁ n ≫ ϕ.eval_LCFP V r' c₁ c₂ = ϕ.eval_LCFP V r' c₁ c₂ ≫ T_inv r V r' c₂ m :=\nbegin\n ext M : 2,\n simp only [T_inv_def, eval_LCFP, nat_trans.comp_app, whisker_right_app, whisker_left_app,\n nat_trans.naturality]\nend\n\nend basic_universal_map\n\nnamespace universal_map\n\nopen free_abelian_group\n\nvariables (ϕ : universal_map m n)\n\ndef eval_LCFP [ϕ.suitable c₂ c₁] : LCFP V r' c₁ n ⟶ LCFP V r' c₂ m :=\n∑ g : {g : basic_universal_map m n // g ∈ ϕ.support},\n begin\n haveI := suitable_of_mem_support ϕ c₂ c₁ g g.2,\n exact coeff (g : basic_universal_map m n) ϕ • (basic_universal_map.eval_LCFP V r' g c₁ c₂)\n end\n\ndef eval_LCFP' : LCFP V r' c₁ n ⟶ LCFP V r' c₂ m :=\n∑ g in ϕ.support, coeff g ϕ • (g.eval_LCFP' V r' c₁ c₂)\n\nlemma eval_LCFP_eq_eval_LCFP' (h : ϕ.suitable c₂ c₁) :\n ϕ.eval_LCFP V r' c₁ c₂ = ϕ.eval_LCFP' V r' c₁ c₂ :=\nbegin\n simp only [eval_LCFP, eval_LCFP', basic_universal_map.eval_LCFP_eq_eval_LCFP',\n subtype.val_eq_coe],\n symmetry,\n apply finset.sum_subtype ϕ.support (λ _, iff.rfl),\nend\n\n@[simp] lemma eval_LCFP'_of (f : basic_universal_map m n) :\n eval_LCFP' V r' c₁ c₂ (of f) = f.eval_LCFP' V r' c₁ c₂ :=\nby simp only [eval_LCFP', support_of, coeff_of_self, one_smul, finset.sum_singleton]\n\n@[simp] lemma eval_LCFP_of (f : basic_universal_map m n) [f.suitable c₂ c₁] :\n eval_LCFP V r' c₁ c₂ (of f) = f.eval_LCFP V r' c₁ c₂ :=\nby rw [eval_LCFP_eq_eval_LCFP', eval_LCFP'_of, basic_universal_map.eval_LCFP_eq_eval_LCFP']\n\n@[simp] lemma eval_LCFP'_zero :\n (0 : universal_map m n).eval_LCFP' V r' c₁ c₂ = 0 :=\nby rw [eval_LCFP', support_zero, finset.sum_empty]\n\n@[simp] lemma eval_LCFP_zero :\n (0 : universal_map m n).eval_LCFP V r' c₁ c₂ = 0 :=\nby rw [eval_LCFP_eq_eval_LCFP', eval_LCFP'_zero]\n\n@[simp] lemma eval_LCFP'_neg (f : universal_map m n) :\n eval_LCFP' V r' c₁ c₂ (-f) = -f.eval_LCFP' V r' c₁ c₂ :=\nby simp only [eval_LCFP', add_monoid_hom.map_neg, finset.sum_neg_distrib, neg_smul, support_neg]\n\n@[simp] lemma eval_LCFP_neg (f : universal_map m n) [f.suitable c₂ c₁] :\n eval_LCFP V r' c₁ c₂ (-f) = -f.eval_LCFP V r' c₁ c₂ :=\nby simp only [eval_LCFP_eq_eval_LCFP', eval_LCFP'_neg]\n\nlemma eval_LCFP'_add (f g : universal_map m n) :\n eval_LCFP' V r' c₁ c₂ (f + g) = f.eval_LCFP' V r' c₁ c₂ + g.eval_LCFP' V r' c₁ c₂ :=\nbegin\n simp only [eval_LCFP'],\n rw finset.sum_subset (support_add f g), -- two goals\n simp only [add_monoid_hom.map_add _ f g, add_smul],\n convert finset.sum_add_distrib using 2, -- three goals\n apply finset.sum_subset (finset.subset_union_left _ _), swap,\n apply finset.sum_subset (finset.subset_union_right _ _),\n all_goals { rintros x - h, rw not_mem_support_iff at h, simp [h] },\nend\n\nlemma eval_LCFP_add (f g : universal_map m n) [f.suitable c₂ c₁] [g.suitable c₂ c₁] :\n eval_LCFP V r' c₁ c₂ (f + g) = f.eval_LCFP V r' c₁ c₂ + g.eval_LCFP V r' c₁ c₂ :=\nby simp only [eval_LCFP_eq_eval_LCFP', eval_LCFP'_add]\n\nlemma eval_LCFP_sub (f g : universal_map m n) [f.suitable c₂ c₁] [g.suitable c₂ c₁] :\n eval_LCFP V r' c₁ c₂ (f - g) = f.eval_LCFP V r' c₁ c₂ - g.eval_LCFP V r' c₁ c₂ :=\nby simp only [sub_eq_add_neg, eval_LCFP_add, eval_LCFP_neg]\n\nlemma eval_LCFP'_comp_of (g : basic_universal_map m n) (f : basic_universal_map l m)\n [hg : g.suitable c₂ c₁] [hf : f.suitable c₃ c₂] :\n eval_LCFP' V r' c₁ c₃ ((comp (of g)) (of f)) =\n eval_LCFP' V r' c₁ c₂ (of g) ≫ eval_LCFP' V r' c₂ c₃ (of f) :=\nbegin\n simp only [comp_of, eval_LCFP'_of],\n haveI hfg : (basic_universal_map.comp g f).suitable c₃ c₁ := basic_universal_map.suitable_comp c₂,\n rw ← basic_universal_map.eval_LCFP'_comp,\nend\n\nopen category_theory category_theory.limits category_theory.preadditive\n\nlemma eval_LCFP'_comp (g : universal_map m n) (f : universal_map l m)\n [hg : g.suitable c₂ c₁] [hf : f.suitable c₃ c₂] :\n (comp g f).eval_LCFP' V r' c₁ c₃ = g.eval_LCFP' V r' c₁ c₂ ≫ f.eval_LCFP' V r' c₂ c₃ :=\nbegin\n unfreezingI { revert hf },\n apply free_abelian_group.induction_on_free_predicate\n (suitable c₂ c₁) (suitable_free_predicate c₂ c₁) g hg; unfreezingI { clear_dependent g },\n { intros h₂,\n simp only [eval_LCFP'_zero, zero_comp, pi.zero_apply,\n add_monoid_hom.zero_apply, add_monoid_hom.map_zero] },\n { intros g hg hf,\n -- now do another nested induction on `f`\n apply free_abelian_group.induction_on_free_predicate\n (suitable c₃ c₂) (suitable_free_predicate c₃ c₂) f hf; unfreezingI { clear_dependent f },\n { simp only [eval_LCFP'_zero, comp_zero, add_monoid_hom.map_zero] },\n { intros f hf,\n rw suitable_of_iff at hf hg,\n resetI,\n apply eval_LCFP'_comp_of },\n { intros f hf IH,\n simp only [IH, eval_LCFP'_neg, add_monoid_hom.map_neg, comp_neg] },\n { rintros (f₁ : universal_map l m) (f₂ : universal_map l m) hf₁ hf₂ IH₁ IH₂, resetI,\n haveI Hg₁f : (comp (of g) f₁).suitable c₃ c₁ := suitable.comp c₂,\n haveI Hg₂f : (comp (of g) f₂).suitable c₃ c₁ := suitable.comp c₂,\n simp only [add_monoid_hom.map_add, eval_LCFP'_add, IH₁, IH₂, comp_add] } },\n { intros g hg IH hf, resetI, specialize IH,\n simp only [IH, add_monoid_hom.map_neg, eval_LCFP'_neg,\n add_monoid_hom.neg_apply, neg_inj, neg_comp] },\n { rintros (g₁ : universal_map m n) (g₂ : universal_map m n) hg₁ hg₂ IH₁ IH₂ hf, resetI,\n haveI Hg₁f : (comp g₁ f).suitable c₃ c₁ := suitable.comp c₂,\n haveI Hg₂f : (comp g₂ f).suitable c₃ c₁ := suitable.comp c₂,\n simp only [add_monoid_hom.map_add, add_monoid_hom.add_apply, eval_LCFP'_add, IH₁, IH₂, add_comp] }\nend\n\nlemma eval_LCFP_comp (g : universal_map m n) (f : universal_map l m)\n [hg : g.suitable c₂ c₁] [hf : f.suitable c₃ c₂] :\n @eval_LCFP V r' c₁ c₃ _ _ (comp g f) (suitable.comp c₂) =\n g.eval_LCFP V r' c₁ c₂ ≫ f.eval_LCFP V r' c₂ c₃ :=\nby { simp only [eval_LCFP_eq_eval_LCFP'], apply eval_LCFP'_comp }\n\nlemma res_comp_eval_LCFP [fact (c₂ ≤ c₁)] [fact (c₄ ≤ c₃)] [ϕ.suitable c₃ c₁] [ϕ.suitable c₄ c₂] :\n res V r' c₁ c₂ n ≫ ϕ.eval_LCFP V r' c₂ c₄ = ϕ.eval_LCFP V r' c₁ c₃ ≫ res V r' c₃ c₄ m :=\nbegin\n simp only [eval_LCFP, comp_sum, sum_comp, comp_zsmul, zsmul_comp],\n apply finset.sum_congr rfl,\n rintros ⟨g, hg⟩ -,\n haveI : g.suitable c₃ c₁ := suitable_of_mem_support ϕ _ _ g hg,\n haveI : g.suitable c₄ c₂ := suitable_of_mem_support ϕ _ _ g hg,\n simp only [subtype.coe_mk, g.res_comp_eval_LCFP V r' c₁ c₂ c₃ c₄],\nend\n\nlemma Tinv_comp_eval_LCFP [fact (0 < r')] [fact (c₂ ≤ r' * c₁)] [fact (c₄ ≤ r' * c₃)]\n [ϕ.suitable c₃ c₁] [ϕ.suitable c₄ c₂] :\n Tinv V r' c₁ c₂ n ≫ ϕ.eval_LCFP V r' c₂ c₄ = ϕ.eval_LCFP V r' c₁ c₃ ≫ Tinv V r' c₃ c₄ m :=\nbegin\n simp only [eval_LCFP, comp_sum, sum_comp, comp_zsmul, zsmul_comp],\n apply finset.sum_congr rfl,\n rintros ⟨g, hg⟩ -,\n haveI : g.suitable c₃ c₁ := suitable_of_mem_support ϕ _ _ g hg,\n haveI : g.suitable c₄ c₂ := suitable_of_mem_support ϕ _ _ g hg,\n congr' 1, apply basic_universal_map.Tinv_comp_eval_LCFP V r',\nend\n\nlemma T_inv_comp_eval_LCFP [normed_with_aut r V] [fact (0 < r)] [ϕ.suitable c₂ c₁] :\n T_inv r V r' c₁ n ≫ ϕ.eval_LCFP V r' c₁ c₂ =\n ϕ.eval_LCFP V r' c₁ c₂ ≫ T_inv r V r' c₂ m :=\nbegin\n simp only [eval_LCFP, comp_sum, sum_comp, comp_zsmul, zsmul_comp],\n apply finset.sum_congr rfl,\n rintros ⟨g, hg⟩ -,\n haveI : g.suitable c₂ c₁ := suitable_of_mem_support ϕ _ _ g hg,\n congr' 1,\n apply basic_universal_map.T_inv_comp_eval_LCFP r V r',\nend\n\nlemma norm_eval_LCFP_le [normed_with_aut r V] [fact (0 < r)] [ϕ.suitable c₂ c₁]\n (N : ℕ) (h : ϕ.bound_by N) (M) :\n ∥(ϕ.eval_LCFP V r' c₁ c₂).app M∥ ≤ N :=\nbegin\n rw [eval_LCFP_eq_eval_LCFP', eval_LCFP'],\n have : (∑ (g : basic_universal_map m n) in support ϕ, (coeff g ϕ).nat_abs : ℝ) ≤ N,\n { exact_mod_cast h },\n simp only [← nat_trans.app_hom_apply, add_monoid_hom.map_sum, add_monoid_hom.map_zsmul],\n refine le_trans (norm_sum_le_of_le ϕ.support _) this,\n intros g hg,\n have aux := ϕ.suitable_of_mem_support c₂ c₁ g hg,\n refine le_trans (norm_zsmul_le _ _) _,\n suffices : ∥(nat_trans.app_hom M) (basic_universal_map.eval_LCFP' V r' g c₁ c₂)∥ ≤ 1,\n { have aux₁ : ∥(coeff g) ϕ∥ = ↑(((coeff g) ϕ).nat_abs),\n { rw [@coe_coe ℕ ℤ ℝ _ _ _, ← int.abs_eq_nat_abs, int.cast_abs],\n refl },\n rw aux₁,\n exact mul_le_of_le_one_right ((coeff g) ϕ).nat_abs.cast_nonneg this },\n rw [← g.eval_LCFP_eq_eval_LCFP' V r' c₁ c₂, basic_universal_map.eval_LCFP],\n { apply normed_add_group_hom.norm_noninc.norm_noninc_iff_norm_le_one.1,\n exact locally_constant.comap_hom_norm_noninc _ _, exact aux },\nend\n\nend universal_map\n\nend breen_deligne\n", "meta": {"author": "leanprover-community", "repo": "lean-liquid", "sha": "92f188bd17f34dbfefc92a83069577f708851aec", "save_path": "github-repos/lean/leanprover-community-lean-liquid", "path": "github-repos/lean/leanprover-community-lean-liquid/lean-liquid-92f188bd17f34dbfefc92a83069577f708851aec/src/pseudo_normed_group/LC.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.05834583815560004, "lm_q1q2_score": 0.02917291907780002}} {"text": "/-\nCopyright (c) 2021 Anne Baanen. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Anne Baanen\n-/\n\nimport logic.function.basic\nimport tactic.lint\nimport tactic.norm_cast\n\n/-!\n# Typeclass for a type `F` with an injective map to `A → B`\n\nThis typeclass is primarily for use by homomorphisms like `monoid_hom` and `linear_map`.\n\n## Basic usage of `fun_like`\n\nA typical type of morphisms should be declared as:\n```\nstructure my_hom (A B : Type*) [my_class A] [my_class B] :=\n(to_fun : A → B)\n(map_op' : ∀ {x y : A}, to_fun (my_class.op x y) = my_class.op (to_fun x) (to_fun y))\n\nnamespace my_hom\n\nvariables (A B : Type*) [my_class A] [my_class B]\n\n-- This instance is optional if you follow the \"Hom class\" design below:\ninstance : fun_like (my_hom A B) A (λ _, B) :=\n{ coe := my_hom.to_fun, coe_injective' := λ f g h, by cases f; cases g; congr' }\n\n/-- Helper instance for when there's too many metavariables to apply `to_fun.to_coe_fn` directly. -/\ninstance : has_coe_to_fun (my_hom A B) := to_fun.to_coe_fn\n\n@[simp] lemma to_fun_eq_coe {f : my_hom A B} : f.to_fun = (f : A → B) := rfl\n\n@[ext] theorem ext {f g : my_hom A B} (h : ∀ x, f x = g x) : f = g := fun_like.ext f g h\n\n/-- Copy of a `my_hom` with a new `to_fun` equal to the old one. Useful to fix definitional\nequalities. -/\nprotected def copy (f : my_hom A B) (f' : A → B) (h : f' = ⇑f) : my_hom A B :=\n{ to_fun := f',\n map_op' := h.symm ▸ f.map_op' }\n\nend my_hom\n```\n\nThis file will then provide a `has_coe_to_fun` instance and various\nextensionality and simp lemmas.\n\n## Hom classes extending `fun_like`\n\nThe `fun_like` design provides further benefits if you put in a bit more work.\nThe first step is to extend `fun_like` to create a class of those types satisfying\nthe axioms of your new type of morphisms.\nContinuing the example above:\n\n```\n/-- `my_hom_class F A B` states that `F` is a type of `my_class.op`-preserving morphisms.\nYou should extend this class when you extend `my_hom`. -/\nclass my_hom_class (F : Type*) (A B : out_param $ Type*) [my_class A] [my_class B]\n extends fun_like F A (λ _, B) :=\n(map_op : ∀ (f : F) (x y : A), f (my_class.op x y) = my_class.op (f x) (f y))\n\n@[simp] lemma map_op {F A B : Type*} [my_class A] [my_class B] [my_hom_class F A B]\n (f : F) (x y : A) : f (my_class.op x y) = my_class.op (f x) (f y) :=\nmy_hom_class.map_op\n\n-- You can replace `my_hom.fun_like` with the below instance, or keep both:\ninstance : my_hom_class (my_hom A B) A B :=\n{ coe := my_hom.to_fun,\n coe_injective' := λ f g h, by cases f; cases g; congr',\n map_op := my_hom.map_op' }\n\n-- [Insert `has_coe_to_fun`, `to_fun_eq_coe`, `ext` and `copy` here]\n```\n\nThe second step is to add instances of your new `my_hom_class` for all types extending `my_hom`.\nTypically, you can just declare a new class analogous to `my_hom_class`:\n\n```\nstructure cooler_hom (A B : Type*) [cool_class A] [cool_class B]\n extends my_hom A B :=\n(map_cool' : to_fun cool_class.cool = cool_class.cool)\n\nclass cooler_hom_class (F : Type*) (A B : out_param $ Type*) [cool_class A] [cool_class B]\n extends my_hom_class F A B :=\n(map_cool : ∀ (f : F), f cool_class.cool = cool_class.cool)\n\n@[simp] lemma map_cool {F A B : Type*} [cool_class A] [cool_class B] [cooler_hom_class F A B]\n (f : F) : f cool_class.cool = cool_class.cool :=\nmy_hom_class.map_op\n\n-- You can also replace `my_hom.fun_like` with the below instance:\ninstance : cool_hom_class (cool_hom A B) A B :=\n{ coe := cool_hom.to_fun,\n coe_injective' := λ f g h, by cases f; cases g; congr',\n map_op := cool_hom.map_op',\n map_cool := cool_hom.map_cool' }\n\n-- [Insert `has_coe_to_fun`, `to_fun_eq_coe`, `ext` and `copy` here]\n```\n\nThen any declaration taking a specific type of morphisms as parameter can instead take the\nclass you just defined:\n```\n-- Compare with: lemma do_something (f : my_hom A B) : sorry := sorry\nlemma do_something {F : Type*} [my_hom_class F A B] (f : F) : sorry := sorry\n```\n\nThis means anything set up for `my_hom`s will automatically work for `cool_hom_class`es,\nand defining `cool_hom_class` only takes a constant amount of effort,\ninstead of linearly increasing the work per `my_hom`-related declaration.\n\n-/\n\n-- This instance should have low priority, to ensure we follow the chain\n-- `fun_like → has_coe_to_fun`\nattribute [instance, priority 10] coe_fn_trans\n\n/-- The class `fun_like F α β` expresses that terms of type `F` have an\ninjective coercion to functions from `α` to `β`.\n\nThis typeclass is used in the definition of the homomorphism typeclasses,\nsuch as `zero_hom_class`, `mul_hom_class`, `monoid_hom_class`, ....\n-/\nclass fun_like (F : Sort*) (α : out_param Sort*) (β : out_param $ α → Sort*) :=\n(coe : F → Π a : α, β a)\n(coe_injective' : function.injective coe)\n\nsection dependent\n\n/-! ### `fun_like F α β` where `β` depends on `a : α` -/\n\nvariables (F α : Sort*) (β : α → Sort*)\n\nnamespace fun_like\n\nvariables {F α β} [i : fun_like F α β]\n\ninclude i\n\n@[priority 100, -- Give this a priority between `coe_fn_trans` and the default priority\n nolint dangerous_instance] -- `α` and `β` are out_params, so this instance should not be dangerous\ninstance : has_coe_to_fun F (λ _, Π a : α, β a) := { coe := fun_like.coe }\n\ntheorem coe_injective : function.injective (coe_fn : F → Π a : α, β a) :=\nfun_like.coe_injective'\n\n@[simp, norm_cast]\ntheorem coe_fn_eq {f g : F} : (f : Π a : α, β a) = (g : Π a : α, β a) ↔ f = g :=\n⟨λ h, @coe_injective _ _ _ i _ _ h, λ h, by cases h; refl⟩\n\ntheorem ext' {f g : F} (h : (f : Π a : α, β a) = (g : Π a : α, β a)) : f = g :=\ncoe_injective h\n\ntheorem ext'_iff {f g : F} : f = g ↔ ((f : Π a : α, β a) = (g : Π a : α, β a)) :=\ncoe_fn_eq.symm\n\ntheorem ext (f g : F) (h : ∀ (x : α), f x = g x) : f = g :=\ncoe_injective (funext h)\n\ntheorem ext_iff {f g : F} : f = g ↔ (∀ x, f x = g x) :=\ncoe_fn_eq.symm.trans function.funext_iff\n\nprotected lemma congr_fun {f g : F} (h₁ : f = g) (x : α) : f x = g x :=\ncongr_fun (congr_arg _ h₁) x\n\nend fun_like\n\nend dependent\n\nsection non_dependent\n\n/-! ### `fun_like F α (λ _, β)` where `β` does not depend on `a : α` -/\n\nvariables {F α β : Sort*} [i : fun_like F α (λ _, β)]\n\ninclude i\n\nnamespace fun_like\n\nprotected lemma congr {f g : F} {x y : α} (h₁ : f = g) (h₂ : x = y) : f x = g y :=\ncongr (congr_arg _ h₁) h₂\n\nprotected lemma congr_arg (f : F) {x y : α} (h₂ : x = y) : f x = f y :=\ncongr_arg _ h₂\n\nend fun_like\n\nend non_dependent\n", "meta": {"author": "jjaassoonn", "repo": "projective_space", "sha": "11fe19fe9d7991a272e7a40be4b6ad9b0c10c7ce", "save_path": "github-repos/lean/jjaassoonn-projective_space", "path": "github-repos/lean/jjaassoonn-projective_space/projective_space-11fe19fe9d7991a272e7a40be4b6ad9b0c10c7ce/src/data/fun_like.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38861802670584894, "lm_q2_score": 0.07477004857766208, "lm_q1q2_score": 0.029056988734951505}} {"text": "/-\nCopyright (c) 2019 Simon Hudon. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Simon Hudon, Yury Kudryashov\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.default\nimport Mathlib.data.equiv.basic\nimport Mathlib.data.list.basic\nimport Mathlib.algebra.star.basic\nimport Mathlib.PostPort\n\nuniverses u_1 u_2 u_4 u_5 u_3 \n\nnamespace Mathlib\n\n/-!\n# Free monoid over a given alphabet\n\n## Main definitions\n\n* `free_monoid α`: free monoid over alphabet `α`; defined as a synonym for `list α`\n with multiplication given by `(++)`.\n* `free_monoid.of`: embedding `α → free_monoid α` sending each element `x` to `[x]`;\n* `free_monoid.lift`: natural equivalence between `α → M` and `free_monoid α →* M`\n* `free_monoid.map`: embedding of `α → β` into `free_monoid α →* free_monoid β` given by `list.map`.\n-/\n\n/-- Free monoid over a given alphabet. -/\ndef free_add_monoid (α : Type u_1) :=\n List α\n\nnamespace free_monoid\n\n\nprotected instance Mathlib.free_add_monoid.add_monoid {α : Type u_1} : add_monoid (free_add_monoid α) :=\n add_monoid.mk (fun (x y : free_add_monoid α) => x ++ y) sorry [] sorry sorry\n\nprotected instance inhabited {α : Type u_1} : Inhabited (free_monoid α) :=\n { default := 1 }\n\ntheorem one_def {α : Type u_1} : 1 = [] :=\n rfl\n\ntheorem Mathlib.free_add_monoid.add_def {α : Type u_1} (xs : List α) (ys : List α) : xs + ys = xs ++ ys :=\n rfl\n\n/-- Embeds an element of `α` into `free_monoid α` as a singleton list. -/\ndef of {α : Type u_1} (x : α) : free_monoid α :=\n [x]\n\ntheorem of_def {α : Type u_1} (x : α) : of x = [x] :=\n rfl\n\ntheorem of_injective {α : Type u_1} : function.injective of :=\n fun (a b : α) => list.head_eq_of_cons_eq\n\n/-- Recursor for `free_monoid` using `1` and `of x * xs` instead of `[]` and `x :: xs`. -/\ndef rec_on {α : Type u_1} {C : free_monoid α → Sort u_2} (xs : free_monoid α) (h0 : C 1) (ih : (x : α) → (xs : free_monoid α) → C xs → C (of x * xs)) : C xs :=\n list.rec_on xs h0 ih\n\ntheorem hom_eq {α : Type u_1} {M : Type u_4} [monoid M] {f : free_monoid α →* M} {g : free_monoid α →* M} (h : ∀ (x : α), coe_fn f (of x) = coe_fn g (of x)) : f = g := sorry\n\n/-- Equivalence between maps `α → M` and monoid homomorphisms `free_monoid α →* M`. -/\ndef lift {α : Type u_1} {M : Type u_4} [monoid M] : (α → M) ≃ (free_monoid α →* M) :=\n equiv.mk (fun (f : α → M) => monoid_hom.mk (fun (l : free_monoid α) => list.prod (list.map f l)) sorry sorry)\n (fun (f : free_monoid α →* M) (x : α) => coe_fn f (of x)) sorry sorry\n\n@[simp] theorem Mathlib.free_add_monoid.lift_symm_apply {α : Type u_1} {M : Type u_4} [add_monoid M] (f : free_add_monoid α →+ M) : coe_fn (equiv.symm free_add_monoid.lift) f = ⇑f ∘ free_add_monoid.of :=\n rfl\n\ntheorem lift_apply {α : Type u_1} {M : Type u_4} [monoid M] (f : α → M) (l : free_monoid α) : coe_fn (coe_fn lift f) l = list.prod (list.map f l) :=\n rfl\n\ntheorem Mathlib.free_add_monoid.lift_comp_of {α : Type u_1} {M : Type u_4} [add_monoid M] (f : α → M) : ⇑(coe_fn free_add_monoid.lift f) ∘ free_add_monoid.of = f :=\n equiv.symm_apply_apply free_add_monoid.lift f\n\n@[simp] theorem Mathlib.free_add_monoid.lift_eval_of {α : Type u_1} {M : Type u_4} [add_monoid M] (f : α → M) (x : α) : coe_fn (coe_fn free_add_monoid.lift f) (free_add_monoid.of x) = f x :=\n congr_fun (free_add_monoid.lift_comp_of f) x\n\n@[simp] theorem lift_restrict {α : Type u_1} {M : Type u_4} [monoid M] (f : free_monoid α →* M) : coe_fn lift (⇑f ∘ of) = f :=\n equiv.apply_symm_apply lift f\n\ntheorem comp_lift {α : Type u_1} {M : Type u_4} [monoid M] {N : Type u_5} [monoid N] (g : M →* N) (f : α → M) : monoid_hom.comp g (coe_fn lift f) = coe_fn lift (⇑g ∘ f) := sorry\n\ntheorem hom_map_lift {α : Type u_1} {M : Type u_4} [monoid M] {N : Type u_5} [monoid N] (g : M →* N) (f : α → M) (x : free_monoid α) : coe_fn g (coe_fn (coe_fn lift f) x) = coe_fn (coe_fn lift (⇑g ∘ f)) x :=\n iff.mp monoid_hom.ext_iff (comp_lift g f) x\n\n/-- The unique monoid homomorphism `free_monoid α →* free_monoid β` that sends\neach `of x` to `of (f x)`. -/\ndef map {α : Type u_1} {β : Type u_2} (f : α → β) : free_monoid α →* free_monoid β :=\n monoid_hom.mk (list.map f) sorry sorry\n\n@[simp] theorem map_of {α : Type u_1} {β : Type u_2} (f : α → β) (x : α) : coe_fn (map f) (of x) = of (f x) :=\n rfl\n\ntheorem Mathlib.free_add_monoid.lift_of_comp_eq_map {α : Type u_1} {β : Type u_2} (f : α → β) : (coe_fn free_add_monoid.lift fun (x : α) => free_add_monoid.of (f x)) = free_add_monoid.map f :=\n free_add_monoid.hom_eq fun (x : α) => rfl\n\ntheorem map_comp {α : Type u_1} {β : Type u_2} {γ : Type u_3} (g : β → γ) (f : α → β) : map (g ∘ f) = monoid_hom.comp (map g) (map f) :=\n hom_eq fun (x : α) => rfl\n\nprotected instance star_monoid {α : Type u_1} : star_monoid (free_monoid α) :=\n star_monoid.mk list.reverse_append\n\n@[simp] theorem star_of {α : Type u_1} (x : α) : star (of x) = of x :=\n rfl\n\n/-- Note that `star_one` is already a global simp lemma, but this one works with dsimp too -/\n@[simp] theorem star_one {α : Type u_1} : star 1 = 1 :=\n rfl\n\n", "meta": {"author": "AurelienSaue", "repo": "Mathlib4_auto", "sha": "590df64109b08190abe22358fabc3eae000943f2", "save_path": "github-repos/lean/AurelienSaue-Mathlib4_auto", "path": "github-repos/lean/AurelienSaue-Mathlib4_auto/Mathlib4_auto-590df64109b08190abe22358fabc3eae000943f2/Mathlib/algebra/free_monoid.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4416730056646256, "lm_q2_score": 0.06560484019943055, "lm_q1q2_score": 0.028975886957029948}} {"text": "/-\nCopyright (c) 2020 Scott Morrison. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Scott Morrison\n-/\nimport category_theory.limits.has_limits\nimport category_theory.products.basic\nimport category_theory.functor.currying\n\n/-!\n# A Fubini theorem for categorical limits\n\nWe prove that $lim_{J × K} G = lim_J (lim_K G(j, -))$ for a functor `G : J × K ⥤ C`,\nwhen all the appropriate limits exist.\n\nWe begin working with a functor `F : J ⥤ K ⥤ C`. We'll write `G : J × K ⥤ C` for the associated\n\"uncurried\" functor.\n\nIn the first part, given a coherent family `D` of limit cones over the functors `F.obj j`,\nand a cone `c` over `G`, we construct a cone over the cone points of `D`.\nWe then show that if `c` is a limit cone, the constructed cone is also a limit cone.\n\nIn the second part, we state the Fubini theorem in the setting where limits are\nprovided by suitable `has_limit` classes.\n\nWe construct\n`limit_uncurry_iso_limit_comp_lim F : limit (uncurry.obj F) ≅ limit (F ⋙ lim)`\nand give simp lemmas characterising it.\nFor convenience, we also provide\n`limit_iso_limit_curry_comp_lim G : limit G ≅ limit ((curry.obj G) ⋙ lim)`\nin terms of the uncurried functor.\n\n## Future work\n\nThe dual statement.\n-/\n\nuniverses v u\n\nopen category_theory\n\nnamespace category_theory.limits\n\nvariables {J K : Type v} [small_category J] [small_category K]\nvariables {C : Type u} [category.{v} C]\n\nvariables (F : J ⥤ K ⥤ C)\n\n/--\nA structure carrying a diagram of cones over the functors `F.obj j`.\n-/\n-- We could try introducing a \"dependent functor type\" to handle this?\nstructure diagram_of_cones :=\n(obj : Π j : J, cone (F.obj j))\n(map : Π {j j' : J} (f : j ⟶ j'), (cones.postcompose (F.map f)).obj (obj j) ⟶ obj j')\n(id : ∀ j : J, (map (𝟙 j)).hom = 𝟙 _ . obviously)\n(comp : ∀ {j₁ j₂ j₃ : J} (f : j₁ ⟶ j₂) (g : j₂ ⟶ j₃),\n (map (f ≫ g)).hom = (map f).hom ≫ (map g).hom . obviously)\n\nvariables {F}\n\n/--\nExtract the functor `J ⥤ C` consisting of the cone points and the maps between them,\nfrom a `diagram_of_cones`.\n-/\n@[simps]\ndef diagram_of_cones.cone_points (D : diagram_of_cones F) :\n J ⥤ C :=\n{ obj := λ j, (D.obj j).X,\n map := λ j j' f, (D.map f).hom,\n map_id' := λ j, D.id j,\n map_comp' := λ j₁ j₂ j₃ f g, D.comp f g, }\n\n/--\nGiven a diagram `D` of limit cones over the `F.obj j`, and a cone over `uncurry.obj F`,\nwe can construct a cone over the diagram consisting of the cone points from `D`.\n-/\n@[simps]\ndef cone_of_cone_uncurry\n {D : diagram_of_cones F} (Q : Π j, is_limit (D.obj j))\n (c : cone (uncurry.obj F)) :\n cone (D.cone_points) :=\n{ X := c.X,\n π :=\n { app := λ j, (Q j).lift\n { X := c.X,\n π :=\n { app := λ k, c.π.app (j, k),\n naturality' := λ k k' f,\n begin\n dsimp, simp only [category.id_comp],\n have := @nat_trans.naturality _ _ _ _ _ _ c.π (j, k) (j, k') (𝟙 j, f),\n dsimp at this,\n simp only [category.id_comp, category_theory.functor.map_id, nat_trans.id_app] at this,\n exact this,\n end } },\n naturality' := λ j j' f, (Q j').hom_ext\n begin\n dsimp,\n intro k,\n simp only [limits.cone_morphism.w, limits.cones.postcompose_obj_π, limits.is_limit.fac_assoc,\n limits.is_limit.fac, nat_trans.comp_app, category.id_comp, category.assoc],\n have := @nat_trans.naturality _ _ _ _ _ _ c.π (j, k) (j', k) (f, 𝟙 k),\n dsimp at this,\n simp only [category.id_comp, category.comp_id,\n category_theory.functor.map_id, nat_trans.id_app] at this,\n exact this,\n end, } }.\n\n/--\n`cone_of_cone_uncurry Q c` is a limit cone when `c` is a limit cone.`\n-/\ndef cone_of_cone_uncurry_is_limit\n {D : diagram_of_cones F} (Q : Π j, is_limit (D.obj j))\n {c : cone (uncurry.obj F)} (P : is_limit c) :\n is_limit (cone_of_cone_uncurry Q c) :=\n{ lift := λ s, P.lift\n { X := s.X,\n π :=\n { app := λ p, s.π.app p.1 ≫ (D.obj p.1).π.app p.2,\n naturality' := λ p p' f,\n begin\n dsimp, simp only [category.id_comp, category.assoc],\n rcases p with ⟨j, k⟩,\n rcases p' with ⟨j', k'⟩,\n rcases f with ⟨fj, fk⟩,\n dsimp,\n slice_rhs 3 4 { rw ←nat_trans.naturality, },\n slice_rhs 2 3 { rw ←(D.obj j).π.naturality, },\n simp only [functor.const_obj_map, category.id_comp, category.assoc],\n have w := (D.map fj).w k',\n dsimp at w,\n rw ←w,\n have n := s.π.naturality fj,\n dsimp at n,\n simp only [category.id_comp] at n,\n rw n,\n simp,\n end, } },\n fac' := λ s j,\n begin\n apply (Q j).hom_ext,\n intro k,\n simp,\n end,\n uniq' := λ s m w,\n begin\n refine P.uniq { X := s.X, π := _, } m _,\n rintro ⟨j, k⟩,\n dsimp,\n rw [←w j],\n simp,\n end, }\n\nsection\nvariables (F)\nvariables [has_limits_of_shape K C]\n\n/--\nGiven a functor `F : J ⥤ K ⥤ C`, with all needed limits,\nwe can construct a diagram consisting of the limit cone over each functor `F.obj j`,\nand the universal cone morphisms between these.\n-/\n@[simps]\nnoncomputable def diagram_of_cones.mk_of_has_limits : diagram_of_cones F :=\n{ obj := λ j, limit.cone (F.obj j),\n map := λ j j' f, { hom := lim.map (F.map f), }, }\n\n-- Satisfying the inhabited linter.\nnoncomputable instance diagram_of_cones_inhabited : inhabited (diagram_of_cones F) :=\n⟨diagram_of_cones.mk_of_has_limits F⟩\n\n@[simp]\nlemma diagram_of_cones.mk_of_has_limits_cone_points :\n (diagram_of_cones.mk_of_has_limits F).cone_points = (F ⋙ lim) :=\nrfl\n\nvariables [has_limit (uncurry.obj F)]\nvariables [has_limit (F ⋙ lim)]\n\n/--\nThe Fubini theorem for a functor `F : J ⥤ K ⥤ C`,\nshowing that the limit of `uncurry.obj F` can be computed as\nthe limit of the limits of the functors `F.obj j`.\n-/\nnoncomputable def limit_uncurry_iso_limit_comp_lim : limit (uncurry.obj F) ≅ limit (F ⋙ lim) :=\nbegin\n let c := limit.cone (uncurry.obj F),\n let P : is_limit c := limit.is_limit _,\n let G := diagram_of_cones.mk_of_has_limits F,\n let Q : Π j, is_limit (G.obj j) := λ j, limit.is_limit _,\n have Q' := cone_of_cone_uncurry_is_limit Q P,\n have Q'' := (limit.is_limit (F ⋙ lim)),\n exact is_limit.cone_point_unique_up_to_iso Q' Q'',\nend\n\n@[simp, reassoc]\nlemma limit_uncurry_iso_limit_comp_lim_hom_π_π {j} {k} :\n (limit_uncurry_iso_limit_comp_lim F).hom ≫ limit.π _ j ≫ limit.π _ k = limit.π _ (j, k) :=\nbegin\n dsimp [limit_uncurry_iso_limit_comp_lim, is_limit.cone_point_unique_up_to_iso,\n is_limit.unique_up_to_iso],\n simp,\nend\n\n@[simp, reassoc]\nlemma limit_uncurry_iso_limit_comp_lim_inv_π {j} {k} :\n (limit_uncurry_iso_limit_comp_lim F).inv ≫ limit.π _ (j, k) = limit.π _ j ≫ limit.π _ k :=\nbegin\n rw [←cancel_epi (limit_uncurry_iso_limit_comp_lim F).hom],\n simp,\nend\nend\n\nsection\n\nvariables (F) [has_limits_of_shape J C] [has_limits_of_shape K C]\n-- With only moderate effort these could be derived if needed:\nvariables [has_limits_of_shape (J × K) C] [has_limits_of_shape (K × J) C]\n\n/-- The limit of `F.flip ⋙ lim` is isomorphic to the limit of `F ⋙ lim`. -/\nnoncomputable\ndef limit_flip_comp_lim_iso_limit_comp_lim : limit (F.flip ⋙ lim) ≅ limit (F ⋙ lim) :=\n(limit_uncurry_iso_limit_comp_lim _).symm ≪≫\n has_limit.iso_of_nat_iso (uncurry_obj_flip _) ≪≫\n (has_limit.iso_of_equivalence (prod.braiding _ _)\n (nat_iso.of_components (λ _, by refl) (by tidy))) ≪≫\n limit_uncurry_iso_limit_comp_lim _\n\n@[simp, reassoc]\nlemma limit_flip_comp_lim_iso_limit_comp_lim_hom_π_π (j) (k) :\n (limit_flip_comp_lim_iso_limit_comp_lim F).hom ≫ limit.π _ j ≫ limit.π _ k =\n limit.π _ k ≫ limit.π _ j :=\nby { dsimp [limit_flip_comp_lim_iso_limit_comp_lim], simp, dsimp, simp, } -- See note [dsimp, simp]\n\n@[simp, reassoc]\nlemma limit_flip_comp_lim_iso_limit_comp_lim_inv_π_π (k) (j) :\n (limit_flip_comp_lim_iso_limit_comp_lim F).inv ≫ limit.π _ k ≫ limit.π _ j =\n limit.π _ j ≫ limit.π _ k :=\nby { dsimp [limit_flip_comp_lim_iso_limit_comp_lim], simp, dsimp, simp, dsimp, simp, }\n\nend\n\nsection\nvariables (G : J × K ⥤ C)\n\nsection\nvariables [has_limits_of_shape K C]\nvariables [has_limit G]\nvariables [has_limit ((curry.obj G) ⋙ lim)]\n\n/--\nThe Fubini theorem for a functor `G : J × K ⥤ C`,\nshowing that the limit of `G` can be computed as\nthe limit of the limits of the functors `G.obj (j, _)`.\n-/\nnoncomputable def limit_iso_limit_curry_comp_lim : limit G ≅ limit ((curry.obj G) ⋙ lim) :=\nbegin\n have i : G ≅ uncurry.obj ((@curry J _ K _ C _).obj G) := currying.symm.unit_iso.app G,\n haveI : limits.has_limit (uncurry.obj ((@curry J _ K _ C _).obj G)) :=\n has_limit_of_iso i,\n transitivity limit (uncurry.obj ((@curry J _ K _ C _).obj G)),\n apply has_limit.iso_of_nat_iso i,\n exact limit_uncurry_iso_limit_comp_lim ((@curry J _ K _ C _).obj G),\nend\n\n@[simp, reassoc]\nlemma limit_iso_limit_curry_comp_lim_hom_π_π {j} {k} :\n (limit_iso_limit_curry_comp_lim G).hom ≫ limit.π _ j ≫ limit.π _ k = limit.π _ (j, k) :=\nby simp [limit_iso_limit_curry_comp_lim, is_limit.cone_point_unique_up_to_iso,\n is_limit.unique_up_to_iso]\n\n@[simp, reassoc]\nlemma limit_iso_limit_curry_comp_lim_inv_π {j} {k} :\n (limit_iso_limit_curry_comp_lim G).inv ≫ limit.π _ (j, k) = limit.π _ j ≫ limit.π _ k :=\nbegin\n rw [←cancel_epi (limit_iso_limit_curry_comp_lim G).hom],\n simp,\nend\nend\n\n\nsection\nvariables [has_limits C] -- Certainly one could weaken the hypotheses here.\n\nopen category_theory.prod\n\n/--\nA variant of the Fubini theorem for a functor `G : J × K ⥤ C`,\nshowing that $\\lim_k \\lim_j G(j,k) ≅ \\lim_j \\lim_k G(j,k)$.\n-/\nnoncomputable\ndef limit_curry_swap_comp_lim_iso_limit_curry_comp_lim :\n limit ((curry.obj (swap K J ⋙ G)) ⋙ lim) ≅ limit ((curry.obj G) ⋙ lim) :=\ncalc\n limit ((curry.obj (swap K J ⋙ G)) ⋙ lim)\n ≅ limit (swap K J ⋙ G) : (limit_iso_limit_curry_comp_lim _).symm\n ... ≅ limit G : has_limit.iso_of_equivalence (braiding K J) (iso.refl _)\n ... ≅ limit ((curry.obj G) ⋙ lim) : limit_iso_limit_curry_comp_lim _\n\n@[simp]\nlemma limit_curry_swap_comp_lim_iso_limit_curry_comp_lim_hom_π_π {j} {k} :\n (limit_curry_swap_comp_lim_iso_limit_curry_comp_lim G).hom ≫ limit.π _ j ≫ limit.π _ k =\n limit.π _ k ≫ limit.π _ j :=\nbegin\n dsimp [limit_curry_swap_comp_lim_iso_limit_curry_comp_lim],\n simp only [iso.refl_hom, braiding_counit_iso_hom_app, limits.has_limit.iso_of_equivalence_hom_π,\n iso.refl_inv, limit_iso_limit_curry_comp_lim_hom_π_π, eq_to_iso_refl, category.assoc],\n erw [nat_trans.id_app], -- Why can't `simp` do this`?\n dsimp, simp,\nend\n\n@[simp]\nlemma limit_curry_swap_comp_lim_iso_limit_curry_comp_lim_inv_π_π {j} {k} :\n (limit_curry_swap_comp_lim_iso_limit_curry_comp_lim G).inv ≫ limit.π _ k ≫ limit.π _ j =\n limit.π _ j ≫ limit.π _ k :=\nbegin\n dsimp [limit_curry_swap_comp_lim_iso_limit_curry_comp_lim],\n simp only [iso.refl_hom, braiding_counit_iso_hom_app, limits.has_limit.iso_of_equivalence_inv_π,\n iso.refl_inv, limit_iso_limit_curry_comp_lim_hom_π_π, eq_to_iso_refl, category.assoc],\n erw [nat_trans.id_app], -- Why can't `simp` do this`?\n dsimp, simp,\nend\n\nend\n\nend\n\nend category_theory.limits\n", "meta": {"author": "leanprover-community", "repo": "mathlib", "sha": "5e526d18cea33550268dcbbddcb822d5cde40654", "save_path": "github-repos/lean/leanprover-community-mathlib", "path": "github-repos/lean/leanprover-community-mathlib/mathlib-5e526d18cea33550268dcbbddcb822d5cde40654/src/category_theory/limits/fubini.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.46101679412289653, "lm_q2_score": 0.06278920377418667, "lm_q1q2_score": 0.028946877429504816}} {"text": "/-\nCopyright (c) 2018 Scott Morrison. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Scott Morrison, Jannis Limperg\n\n! This file was ported from Lean 3 source module control.ulift\n! leanprover-community/mathlib commit 99e8971dc62f1f7ecf693d75e75fbbabd55849de\n! Please do not edit these lines, except to modify the commit id\n! if you have ported upstream changes.\n-/\n\nimport Mathlib.Mathport.Rename\n\n/-!\n# Monadic instances for `ULift` and `PLift`\n\nIn this file we define `Monad` and `IsLawfulMonad` instances on `PLift` and `ULift`. -/\n\n\nuniverse u v\n\nnamespace PLift\n\nvariable {α : Sort u} {β : Sort v}\n\n/-- Functorial action. -/\nprotected def map (f : α → β) (a : PLift α) : PLift β :=\n PLift.up (f a.down)\n#align plift.map PLift.map\n\n@[simp]\ntheorem map_up (f : α → β) (a : α) : (PLift.up a).map f = PLift.up (f a) :=\n rfl\n#align plift.map_up PLift.map_up\n\n/-- Embedding of pure values. -/\n@[simp]\nprotected def pure : α → PLift α :=\n up\n#align plift.pure PLift.pure\n\n/-- Applicative sequencing. -/\nprotected def seq (f : PLift (α → β)) (x : Unit → PLift α) : PLift β :=\n PLift.up (f.down (x ()).down)\n#align plift.seq PLift.seq\n\n@[simp]\ntheorem seq_up (f : α → β) (x : α) : (PLift.up f).seq (fun _ => PLift.up x) = PLift.up (f x) :=\n rfl\n#align plift.seq_up PLift.seq_up\n\n/-- Monadic bind. -/\nprotected def bind (a : PLift α) (f : α → PLift β) : PLift β :=\n f a.down\n#align plift.bind PLift.bind\n\n@[simp]\ntheorem bind_up (a : α) (f : α → PLift β) : (PLift.up a).bind f = f a :=\n rfl\n#align plift.bind_up PLift.bind_up\n\ninstance : Monad PLift where\n map := @PLift.map\n pure := @PLift.pure\n seq := @PLift.seq\n bind := @PLift.bind\n\ninstance : LawfulFunctor PLift where\n id_map := @fun _ ⟨_⟩ => rfl\n comp_map := @fun _ _ _ _ _ ⟨_⟩ => rfl\n map_const := @fun _ _ => rfl\n\ninstance : LawfulApplicative PLift where\n seqLeft_eq := @fun _ _ _ _ => rfl\n seqRight_eq := @fun _ _ _ _ => rfl\n pure_seq := @fun _ _ _ ⟨_⟩ => rfl\n map_pure := @fun _ _ _ _ => rfl\n seq_pure := @fun _ _ ⟨_⟩ _ => rfl\n seq_assoc := @fun _ _ _ ⟨_⟩ ⟨_⟩ ⟨_⟩ => rfl\n\ninstance : LawfulMonad PLift where\n bind_pure_comp := @fun _ _ _ ⟨_⟩ => rfl\n bind_map := @fun _ _ ⟨_⟩ ⟨_⟩ => rfl\n pure_bind := @fun _ _ _ _ => rfl\n bind_assoc := @fun _ _ _ ⟨_⟩ _ _ => rfl\n\n@[simp]\ntheorem rec.constant {α : Sort u} {β : Type v} (b : β) :\n (@PLift.rec α (fun _ => β) fun _ => b) = fun _ => b := rfl\n\n#align plift.rec.constant PLift.rec.constant\n\nend PLift\n\nnamespace ULift\n\nvariable {α : Type u} {β : Type v}\n\n/-- Functorial action. -/\nprotected def map (f : α → β) (a : ULift α) : ULift β :=\n ULift.up.{u} (f a.down)\n#align ulift.map ULift.map\n\n@[simp]\ntheorem map_up (f : α → β) (a : α) : (ULift.up.{u} a).map f = ULift.up.{u} (f a) :=\n rfl\n#align ulift.map_up ULift.map_up\n\n/-- Embedding of pure values. -/\n@[simp]\nprotected def pure : α → ULift α :=\n up\n#align ulift.pure ULift.pure\n\n/-- Applicative sequencing. -/\nprotected def seq {α β} (f : ULift (α → β)) (x : Unit → ULift α) : ULift β :=\n ULift.up.{u} (f.down (x ()).down)\n#align ulift.seq ULift.seq\n\n@[simp]\ntheorem seq_up (f : α → β) (x : α) : (ULift.up f).seq (fun _ => ULift.up x) = ULift.up (f x) :=\n rfl\n#align ulift.seq_up ULift.seq_up\n\n/-- Monadic bind. -/\nprotected def bind (a : ULift α) (f : α → ULift β) : ULift β :=\n f a.down\n#align ulift.bind ULift.bind\n\n@[simp]\ntheorem bind_up (a : α) (f : α → ULift β) : (ULift.up a).bind f = f a :=\n rfl\n#align ulift.bind_up ULift.bind_up\n\ninstance : Monad ULift where\n map := @ULift.map\n pure := @ULift.pure\n seq := @ULift.seq\n bind := @ULift.bind\n\ninstance : LawfulFunctor ULift where\n id_map := @fun _ ⟨_⟩ => rfl\n comp_map := @fun _ _ _ _ _ ⟨_⟩ => rfl\n map_const := @fun _ _ => rfl\n\ninstance : LawfulApplicative ULift where\n seqLeft_eq := @fun _ _ _ _ => rfl\n seqRight_eq := @fun _ _ _ _ => rfl\n pure_seq := @fun _ _ _ ⟨_⟩ => rfl\n map_pure := @fun _ _ _ _ => rfl\n seq_pure := @fun _ _ ⟨_⟩ _ => rfl\n seq_assoc := @fun _ _ _ ⟨_⟩ ⟨_⟩ ⟨_⟩ => rfl\n\ninstance : LawfulMonad ULift where\n bind_pure_comp := @fun _ _ _ ⟨_⟩ => rfl\n bind_map := @fun _ _ ⟨_⟩ ⟨_⟩ => rfl\n pure_bind := @fun _ _ _ _ => rfl\n bind_assoc := @fun _ _ _ ⟨_⟩ _ _ => rfl\n\n@[simp]\ntheorem rec.constant {α : Type u} {β : Sort v} (b : β) :\n (@ULift.rec α (fun _ => β) fun _ => b) = fun _ => b := rfl\n\n#align ulift.rec.constant ULift.rec.constant\n\nend ULift\n", "meta": {"author": "leanprover-community", "repo": "mathlib4", "sha": "b9a0a30342ca06e9817e22dbe46e75fc7f435500", "save_path": "github-repos/lean/leanprover-community-mathlib4", "path": "github-repos/lean/leanprover-community-mathlib4/mathlib4-b9a0a30342ca06e9817e22dbe46e75fc7f435500/Mathlib/Control/ULift.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4148988313272769, "lm_q2_score": 0.06954175077306284, "lm_q1q2_score": 0.028852791124196524}} {"text": "/-\nCopyright (c) 2020 Scott Morrison. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Gabriel Ebner, Scott Morrison\n\n! This file was ported from Lean 3 source module tactic.simp_result\n! leanprover-community/mathlib commit 3c11bd771ef17197a9e9fcd4a3fabfa2804d950c\n! Please do not edit these lines, except to modify the commit id\n! if you have ported upstream changes.\n-/\nimport Mathbin.Tactic.Core\n\n/-!\n# simp_result\n\n`dsimp_result` and `simp_result` are a pair of tactics for\napplying `dsimp` or `simp` to the result produced by other tactics.\n\nAs examples, tactics which use `revert` and `intro`\nmay insert additional `id` terms in the result they produce.\nIf there is some reason these are undesirable\n(e.g. the result term needs to be human-readable, or\nsatisfying syntactic rather than just definitional properties),\nwrapping those tactics in `dsimp_result`\ncan remove the `id` terms \"after the fact\".\n\nSimilarly, tactics using `subst` and `rw` will nearly always introduce `eq.rec` terms,\nbut sometimes these will be easy to remove,\nfor example by simplifying using `eq_rec_constant`.\nThis is a non-definitional simplification lemma,\nand so wrapping these tactics in `simp_result` will result\nin a definitionally different result.\n\nThere are several examples in the associated test file,\ndemonstrating these interactions with `revert` and `subst`.\n\nThese tactics should be used with some caution.\nYou should consider whether there is any real need for the simplification of the result,\nand whether there is a more direct way of producing the result you wanted,\nbefore relying on these tactics.\n\nBoth are implemented in terms of a generic `intercept_result` tactic,\nwhich allows you to run an arbitrary tactic and modify the returned results.\n-/\n\n\nnamespace Tactic\n\n/-- `intercept_result m t`\nattempts to run a tactic `t`,\nintercepts any results `t` assigns to the goals,\nand runs `m : expr → tactic expr` on each of the expressions\nbefore assigning the returned values to the original goals.\n\nBecause `intercept_result` uses `unsafe.type_context.assign` rather than `unify`,\nif the tactic `m` does something unreasonable\nyou may produce terms that don't typecheck,\npossibly with mysterious error messages.\nBe careful!\n-/\nunsafe def intercept_result {α} (m : expr → tactic expr) (t : tactic α) : tactic α := do\n let gs\n ←-- Replace the goals with copies.\n get_goals\n let gs' ← gs.mapM fun g => infer_type g >>= mk_meta_var\n set_goals gs'\n let a\n ←-- Run the tactic on the copied goals.\n t\n (-- Run `m` on the produced terms,\n gs\n gs').mapM\n fun ⟨g, g'⟩ => do\n let g' ← instantiate_mvars g'\n let g'' ← with_local_goals' gs <| m g'\n -- and assign to the original goals.\n -- (We have to use `assign` here, as `unify` and `exact` are apparently\n -- unreliable about which way they do the assignment!)\n unsafe.type_context.run <|\n unsafe.type_context.assign g g''\n pure a\n#align tactic.intercept_result tactic.intercept_result\n\n/-- `dsimp_result t`\nattempts to run a tactic `t`,\nintercepts any results it assigns to the goals,\nand runs `dsimp` on those results\nbefore assigning the simplified values to the original goals.\n-/\nunsafe def dsimp_result {α} (t : tactic α) (cfg : DsimpConfig := { failIfUnchanged := false })\n (no_defaults := false) (attr_names : List Name := []) (hs : List simp_arg_type := []) :\n tactic α :=\n intercept_result (fun g => g.dsimp cfg no_defaults attr_names hs) t\n#align tactic.dsimp_result tactic.dsimp_result\n\n/-- `simp_result t`\nattempts to run a tactic `t`,\nintercepts any results `t` assigns to the goals,\nand runs `simp` on those results\nbefore assigning the simplified values to the original goals.\n-/\nunsafe def simp_result {α} (t : tactic α) (cfg : SimpConfig := { failIfUnchanged := false })\n (discharger : tactic Unit := failed) (no_defaults := false) (attr_names : List Name := [])\n (hs : List simp_arg_type := []) : tactic α :=\n intercept_result (fun g => Prod.fst <$> g.simp cfg discharger no_defaults attr_names hs) t\n#align tactic.simp_result tactic.simp_result\n\nnamespace Interactive\n\n/- ./././Mathport/Syntax/Translate/Tactic/Mathlib/Core.lean:38:34: unsupported: setup_tactic_parser -/\n/-- `dsimp_result { tac }`\nattempts to run a tactic block `tac`,\nintercepts any results the tactic block would have assigned to the goals,\nand runs `dsimp` on those results\nbefore assigning the simplified values to the original goals.\n\nYou can use the usual interactive syntax for `dsimp`, e.g.\n`dsimp_result only [a, b, c] with attr { tac }`.\n-/\nunsafe def dsimp_result (no_defaults : parse only_flag) (hs : parse simp_arg_list)\n (attr_names : parse with_ident_list) (t : itactic) : itactic :=\n tactic.dsimp_result t { failIfUnchanged := false } no_defaults attr_names hs\n#align tactic.interactive.dsimp_result tactic.interactive.dsimp_result\n\n/-- `simp_result { tac }`\nattempts to run a tactic block `tac`,\nintercepts any results the tactic block would have assigned to the goals,\nand runs `simp` on those results\nbefore assigning the simplified values to the original goals.\n\nYou can use the usual interactive syntax for `simp`, e.g.\n`simp_result only [a, b, c] with attr { tac }`.\n-/\nunsafe def simp_result (no_defaults : parse only_flag) (hs : parse simp_arg_list)\n (attr_names : parse with_ident_list) (t : itactic) : itactic :=\n tactic.simp_result t { failIfUnchanged := false } failed no_defaults attr_names hs\n#align tactic.interactive.simp_result tactic.interactive.simp_result\n\n/-- `simp_result { tac }`\nattempts to run a tactic block `tac`,\nintercepts any results the tactic block would have assigned to the goals,\nand runs `simp` on those results\nbefore assigning the simplified values to the original goals.\n\nYou can use the usual interactive syntax for `simp`, e.g.\n`simp_result only [a, b, c] with attr { tac }`.\n\n`dsimp_result { tac }` works similarly, internally using `dsimp`\n(and so only simplifiying along definitional lemmas).\n-/\nadd_tactic_doc\n { Name := \"simp_result\"\n category := DocCategory.tactic\n declNames := [`` simp_result, `` dsimp_result]\n tags := [\"simplification\"] }\n\nend Interactive\n\nend Tactic\n\n", "meta": {"author": "leanprover-community", "repo": "mathlib3port", "sha": "62505aa236c58c8559783b16d33e30df3daa54f4", "save_path": "github-repos/lean/leanprover-community-mathlib3port", "path": "github-repos/lean/leanprover-community-mathlib3port/mathlib3port-62505aa236c58c8559783b16d33e30df3daa54f4/Mathbin/Tactic/SimpResult.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3276683008207139, "lm_q2_score": 0.08756383237976291, "lm_q1q2_score": 0.028691892169226723}} {"text": "/-\nCopyright (c) 2018 Reid Barton All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Reid Barton, Scott Morrison, David Wärn\n-/\nimport category_theory.full_subcategory\nimport category_theory.products.basic\nimport category_theory.pi.basic\nimport category_theory.category.basic\nimport combinatorics.quiver.connected_component\n\n/-!\n# Groupoids\n\n> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.\n> Any changes to this file require a corresponding PR to mathlib4.\n\nWe define `groupoid` as a typeclass extending `category`,\nasserting that all morphisms have inverses.\n\nThe instance `is_iso.of_groupoid (f : X ⟶ Y) : is_iso f` means that you can then write\n`inv f` to access the inverse of any morphism `f`.\n\n`groupoid.iso_equiv_hom : (X ≅ Y) ≃ (X ⟶ Y)` provides the equivalence between\nisomorphisms and morphisms in a groupoid.\n\nWe provide a (non-instance) constructor `groupoid.of_is_iso` from an existing category\nwith `is_iso f` for every `f`.\n\n## See also\n\nSee also `category_theory.core` for the groupoid of isomorphisms in a category.\n-/\n\nnamespace category_theory\n\nuniverses v v₂ u u₂ -- morphism levels before object levels. See note [category_theory universes].\n\n/-- A `groupoid` is a category such that all morphisms are isomorphisms. -/\nclass groupoid (obj : Type u) extends category.{v} obj : Type (max u (v+1)) :=\n(inv : Π {X Y : obj}, (X ⟶ Y) → (Y ⟶ X))\n(inv_comp' : ∀ {X Y : obj} (f : X ⟶ Y), comp (inv f) f = id Y . obviously)\n(comp_inv' : ∀ {X Y : obj} (f : X ⟶ Y), comp f (inv f) = id X . obviously)\n\nrestate_axiom groupoid.inv_comp'\nrestate_axiom groupoid.comp_inv'\n\n/--\nA `large_groupoid` is a groupoid\nwhere the objects live in `Type (u+1)` while the morphisms live in `Type u`.\n-/\nabbreviation large_groupoid (C : Type (u+1)) : Type (u+1) := groupoid.{u} C\n/--\nA `small_groupoid` is a groupoid\nwhere the objects and morphisms live in the same universe.\n-/\nabbreviation small_groupoid (C : Type u) : Type (u+1) := groupoid.{u} C\n\nsection\n\nvariables {C : Type u} [groupoid.{v} C] {X Y : C}\n\n@[priority 100] -- see Note [lower instance priority]\ninstance is_iso.of_groupoid (f : X ⟶ Y) : is_iso f :=\n⟨⟨groupoid.inv f, groupoid.comp_inv f, groupoid.inv_comp f⟩⟩\n\n@[simp] \n\n/-- `groupoid.inv` is involutive. -/\n@[simps] def groupoid.inv_equiv : (X ⟶ Y) ≃ (Y ⟶ X) :=\n⟨groupoid.inv, groupoid.inv, λ f, by simp, λ f, by simp⟩\n\n@[priority 100]\ninstance groupoid_has_involutive_reverse : quiver.has_involutive_reverse C :=\n{ reverse' := λ X Y f, groupoid.inv f,\n inv' := λ X Y f, by { dsimp [quiver.reverse], simp, } }\n\n@[simp] lemma groupoid.reverse_eq_inv (f : X ⟶ Y) : quiver.reverse f = groupoid.inv f := rfl\n\ninstance functor_map_reverse {D : Type*} [groupoid D] (F : C ⥤ D) :\n F.to_prefunctor.map_reverse :=\n{ map_reverse' := λ X Y f, by\n simp only [quiver.reverse, quiver.has_reverse.reverse', groupoid.inv_eq_inv,\n functor.to_prefunctor_map, functor.map_inv], }\n\nvariables (X Y)\n\n/-- In a groupoid, isomorphisms are equivalent to morphisms. -/\ndef groupoid.iso_equiv_hom : (X ≅ Y) ≃ (X ⟶ Y) :=\n{ to_fun := iso.hom,\n inv_fun := λ f, ⟨f, groupoid.inv f⟩,\n left_inv := λ i, iso.ext rfl,\n right_inv := λ f, rfl }\n\nvariables (C)\n\n/-- The functor from a groupoid `C` to its opposite sending every morphism to its inverse. -/\n@[simps] noncomputable def groupoid.inv_functor : C ⥤ Cᵒᵖ :=\n{ obj := opposite.op,\n map := λ {X Y} f, (inv f).op }\n\nend\n\nsection\n\nvariables {C : Type u} [category.{v} C]\n\n/-- A category where every morphism `is_iso` is a groupoid. -/\nnoncomputable\ndef groupoid.of_is_iso (all_is_iso : ∀ {X Y : C} (f : X ⟶ Y), is_iso f) : groupoid.{v} C :=\n{ inv := λ X Y f, inv f }\n\n/-- A category with a unique morphism between any two objects is a groupoid -/\ndef groupoid.of_hom_unique (all_unique : ∀ {X Y : C}, unique (X ⟶ Y)) : groupoid.{v} C :=\n{ inv := λ X Y f, all_unique.default }\n\nend\n\ninstance induced_category.groupoid {C : Type u} (D : Type u₂) [groupoid.{v} D] (F : C → D) :\n groupoid.{v} (induced_category D F) :=\n{ inv := λ X Y f, groupoid.inv f,\n inv_comp' := λ X Y f, groupoid.inv_comp f,\n comp_inv' := λ X Y f, groupoid.comp_inv f,\n .. induced_category.category F }\n\nsection\n\ninstance groupoid_pi {I : Type u} {J : I → Type u₂} [∀ i, groupoid.{v} (J i)] :\n groupoid.{max u v} (Π i : I, J i) :=\n{ inv := λ (x y : Π i, J i) (f : Π i, x i ⟶ y i), (λ i : I, groupoid.inv (f i)), }\n\ninstance groupoid_prod {α : Type u} {β : Type v} [groupoid.{u₂} α] [groupoid.{v₂} β] :\n groupoid.{max u₂ v₂} (α × β) :=\n{ inv := λ (x y : α × β) (f : x ⟶ y), (groupoid.inv f.1, groupoid.inv f.2) }\n\nend\n\nend category_theory\n", "meta": {"author": "leanprover-community", "repo": "mathlib", "sha": "5e526d18cea33550268dcbbddcb822d5cde40654", "save_path": "github-repos/lean/leanprover-community-mathlib", "path": "github-repos/lean/leanprover-community-mathlib/mathlib-5e526d18cea33550268dcbbddcb822d5cde40654/src/category_theory/groupoid.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879062662624377, "lm_q2_score": 0.06097517745216934, "lm_q1q2_score": 0.028584591646448877}} {"text": "/-\nCopyright (c) 2021 Anne Baanen. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Anne Baanen\n-/\n\nimport logic.function.basic\nimport tactic.lint\nimport tactic.norm_cast\n\n/-!\n# Typeclass for a type `F` with an injective map to `A → B`\n\nThis typeclass is primarily for use by homomorphisms like `monoid_hom` and `linear_map`.\n\n## Basic usage of `fun_like`\n\nA typical type of morphisms should be declared as:\n```\nstructure my_hom (A B : Type*) [my_class A] [my_class B] :=\n(to_fun : A → B)\n(map_op' : ∀ {x y : A}, to_fun (my_class.op x y) = my_class.op (to_fun x) (to_fun y))\n\nnamespace my_hom\n\nvariables (A B : Type*) [my_class A] [my_class B]\n\n-- This instance is optional if you follow the \"morphism class\" design below:\ninstance : fun_like (my_hom A B) A (λ _, B) :=\n{ coe := my_hom.to_fun, coe_injective' := λ f g h, by cases f; cases g; congr' }\n\n/-- Helper instance for when there's too many metavariables to apply\n`fun_like.has_coe_to_fun` directly. -/\ninstance : has_coe_to_fun (my_hom A B) (λ _, A → B) := fun_like.has_coe_to_fun\n\n@[simp] lemma to_fun_eq_coe {f : my_hom A B} : f.to_fun = (f : A → B) := rfl\n\n@[ext] theorem ext {f g : my_hom A B} (h : ∀ x, f x = g x) : f = g := fun_like.ext f g h\n\n/-- Copy of a `my_hom` with a new `to_fun` equal to the old one. Useful to fix definitional\nequalities. -/\nprotected def copy (f : my_hom A B) (f' : A → B) (h : f' = ⇑f) : my_hom A B :=\n{ to_fun := f',\n map_op' := h.symm ▸ f.map_op' }\n\nend my_hom\n```\n\nThis file will then provide a `has_coe_to_fun` instance and various\nextensionality and simp lemmas.\n\n## Morphism classes extending `fun_like`\n\nThe `fun_like` design provides further benefits if you put in a bit more work.\nThe first step is to extend `fun_like` to create a class of those types satisfying\nthe axioms of your new type of morphisms.\nContinuing the example above:\n\n```\n/-- `my_hom_class F A B` states that `F` is a type of `my_class.op`-preserving morphisms.\nYou should extend this class when you extend `my_hom`. -/\nclass my_hom_class (F : Type*) (A B : out_param $ Type*) [my_class A] [my_class B]\n extends fun_like F A (λ _, B) :=\n(map_op : ∀ (f : F) (x y : A), f (my_class.op x y) = my_class.op (f x) (f y))\n\n@[simp] lemma map_op {F A B : Type*} [my_class A] [my_class B] [my_hom_class F A B]\n (f : F) (x y : A) : f (my_class.op x y) = my_class.op (f x) (f y) :=\nmy_hom_class.map_op\n\n-- You can replace `my_hom.fun_like` with the below instance:\ninstance : my_hom_class (my_hom A B) A B :=\n{ coe := my_hom.to_fun,\n coe_injective' := λ f g h, by cases f; cases g; congr',\n map_op := my_hom.map_op' }\n\n-- [Insert `has_coe_to_fun`, `to_fun_eq_coe`, `ext` and `copy` here]\n```\n\nThe second step is to add instances of your new `my_hom_class` for all types extending `my_hom`.\nTypically, you can just declare a new class analogous to `my_hom_class`:\n\n```\nstructure cooler_hom (A B : Type*) [cool_class A] [cool_class B]\n extends my_hom A B :=\n(map_cool' : to_fun cool_class.cool = cool_class.cool)\n\nclass cooler_hom_class (F : Type*) (A B : out_param $ Type*) [cool_class A] [cool_class B]\n extends my_hom_class F A B :=\n(map_cool : ∀ (f : F), f cool_class.cool = cool_class.cool)\n\n@[simp] lemma map_cool {F A B : Type*} [cool_class A] [cool_class B] [cooler_hom_class F A B]\n (f : F) : f cool_class.cool = cool_class.cool :=\nmy_hom_class.map_op\n\n-- You can also replace `my_hom.fun_like` with the below instance:\ninstance : cool_hom_class (cool_hom A B) A B :=\n{ coe := cool_hom.to_fun,\n coe_injective' := λ f g h, by cases f; cases g; congr',\n map_op := cool_hom.map_op',\n map_cool := cool_hom.map_cool' }\n\n-- [Insert `has_coe_to_fun`, `to_fun_eq_coe`, `ext` and `copy` here]\n```\n\nThen any declaration taking a specific type of morphisms as parameter can instead take the\nclass you just defined:\n```\n-- Compare with: lemma do_something (f : my_hom A B) : sorry := sorry\nlemma do_something {F : Type*} [my_hom_class F A B] (f : F) : sorry := sorry\n```\n\nThis means anything set up for `my_hom`s will automatically work for `cool_hom_class`es,\nand defining `cool_hom_class` only takes a constant amount of effort,\ninstead of linearly increasing the work per `my_hom`-related declaration.\n\n-/\n\n-- This instance should have low priority, to ensure we follow the chain\n-- `fun_like → has_coe_to_fun`\nattribute [instance, priority 10] coe_fn_trans\n\n/-- The class `fun_like F α β` expresses that terms of type `F` have an\ninjective coercion to functions from `α` to `β`.\n\nThis typeclass is used in the definition of the homomorphism typeclasses,\nsuch as `zero_hom_class`, `mul_hom_class`, `monoid_hom_class`, ....\n-/\nclass fun_like (F : Sort*) (α : out_param Sort*) (β : out_param $ α → Sort*) :=\n(coe : F → Π a : α, β a)\n(coe_injective' : function.injective coe)\n\nsection dependent\n\n/-! ### `fun_like F α β` where `β` depends on `a : α` -/\n\nvariables (F α : Sort*) (β : α → Sort*)\n\nnamespace fun_like\n\nvariables {F α β} [i : fun_like F α β]\n\ninclude i\n\n@[priority 100, -- Give this a priority between `coe_fn_trans` and the default priority\n nolint dangerous_instance] -- `α` and `β` are out_params, so this instance should not be dangerous\ninstance : has_coe_to_fun F (λ _, Π a : α, β a) := { coe := fun_like.coe }\n\n@[simp] \n\ntheorem coe_injective : function.injective (coe_fn : F → Π a : α, β a) :=\nfun_like.coe_injective'\n\n@[simp, norm_cast]\ntheorem coe_fn_eq {f g : F} : (f : Π a : α, β a) = (g : Π a : α, β a) ↔ f = g :=\n⟨λ h, @coe_injective _ _ _ i _ _ h, λ h, by cases h; refl⟩\n\ntheorem ext' {f g : F} (h : (f : Π a : α, β a) = (g : Π a : α, β a)) : f = g :=\ncoe_injective h\n\ntheorem ext'_iff {f g : F} : f = g ↔ ((f : Π a : α, β a) = (g : Π a : α, β a)) :=\ncoe_fn_eq.symm\n\ntheorem ext (f g : F) (h : ∀ (x : α), f x = g x) : f = g :=\ncoe_injective (funext h)\n\ntheorem ext_iff {f g : F} : f = g ↔ (∀ x, f x = g x) :=\ncoe_fn_eq.symm.trans function.funext_iff\n\nprotected lemma congr_fun {f g : F} (h₁ : f = g) (x : α) : f x = g x :=\ncongr_fun (congr_arg _ h₁) x\n\nlemma ne_iff {f g : F} : f ≠ g ↔ ∃ a, f a ≠ g a :=\next_iff.not.trans not_forall\n\nlemma exists_ne {f g : F} (h : f ≠ g) : ∃ x, f x ≠ g x :=\nne_iff.mp h\n\nend fun_like\n\nend dependent\n\nsection non_dependent\n\n/-! ### `fun_like F α (λ _, β)` where `β` does not depend on `a : α` -/\n\nvariables {F α β : Sort*} [i : fun_like F α (λ _, β)]\n\ninclude i\n\nnamespace fun_like\n\nprotected lemma congr {f g : F} {x y : α} (h₁ : f = g) (h₂ : x = y) : f x = g y :=\ncongr (congr_arg _ h₁) h₂\n\nprotected lemma congr_arg (f : F) {x y : α} (h₂ : x = y) : f x = f y :=\ncongr_arg _ h₂\n\nend fun_like\n\nend non_dependent\n", "meta": {"author": "saisurbehera", "repo": "mathProof", "sha": "57c6bfe75652e9d3312d8904441a32aff7d6a75e", "save_path": "github-repos/lean/saisurbehera-mathProof", "path": "github-repos/lean/saisurbehera-mathProof/mathProof-57c6bfe75652e9d3312d8904441a32aff7d6a75e/src/tertiary_packages/mathlib/src/data/fun_like/basic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4225046202709847, "lm_q2_score": 0.06754668550840878, "lm_q1q2_score": 0.028538786711293875}} {"text": "import .love05_inductive_predicates_demo\n\n\n/- # LoVe Demo 7: Metaprogramming\n\nUsers can extend Lean with custom monadic tactics and tools. This kind of\nprogramming—programming the prover—is called metaprogramming.\n\nLean's metaprogramming framework uses mostly the same notions and syntax as\nLean's input language itself.\n\nAbstract syntax trees __reflect__ internal data structures, e.g., for\nexpressions (terms).\n\nThe prover's C++ internals are exposed through Lean interfaces, which we can\nuse for accessing the current context and goal, unifying expressions, querying\nand modifying the environment, and setting attributes (e.g., `@[simp]`).\n\nMost of Lean's predefined tactics are implemented in Lean (and not in C++).\n\nExample applications:\n\n* proof goal transformations;\n* heuristic proof search;\n* decision procedures;\n* definition generators;\n* advisor tools;\n* exporters;\n* ad hoc automation.\n\nAdvantages of Lean's metaprogramming framework:\n\n* Users do not need to learn another programming language to write\n metaprograms; they can work with the same constructs and notation used to\n define ordinary objects in the prover's library.\n\n* Everything in that library is available for metaprogramming purposes.\n\n* Metaprograms can be written and debugged in the same interactive environment,\n encouraging a style where formal libraries and supporting automation are\n developed at the same time. -/\n\n\nset_option pp.beta true\nset_option pp.generalized_field_notation false\n\nnamespace LoVe\n\n\n/- ## Tactics and Tactic Combinators\n\nWhen programming our own tactics, we often need to repeat some actions on\nseveral goals, or to recover if a tactic fails. Tactic combinators help in such\ncase.\n\n`repeat` applies its argument repeatedly on all (sub…sub)goals until it cannot\nbe applied any further. -/\n\nlemma repeat_example :\n even 4 ∧ even 7 ∧ even 3 ∧ even 0 :=\nbegin\n repeat { apply and.intro },\n repeat { apply even.add_two },\n repeat { sorry }\nend\n\n/- The \"orelse\" combinator `<|>` tries its first argument and applies its\nsecond argument in case of failure. -/\n\nlemma repeat_orelse_example :\n even 4 ∧ even 7 ∧ even 3 ∧ even 0 :=\nbegin\n repeat { apply and.intro },\n repeat {\n apply even.add_two\n <|> apply even.zero },\n repeat { sorry }\nend\n\n/- `iterate` works repeatedly on the first goal until it fails; then it\nstops. -/\n\nlemma iterate_orelse_example :\n even 4 ∧ even 7 ∧ even 3 ∧ even 0 :=\nbegin\n repeat { apply and.intro },\n iterate {\n apply even.add_two\n <|> apply even.zero },\n repeat { sorry }\nend\n\n/- `all_goals` applies its argument exactly once to each goal. It succeeds only\nif the argument succeeds on **all** goals. -/\n\nlemma all_goals_example :\n even 4 ∧ even 7 ∧ even 3 ∧ even 0 :=\nbegin\n repeat { apply and.intro },\n all_goals { apply even.add_two }, -- fails\n repeat { sorry }\nend\n\n/- `try` transforms its argument into a tactic that never fails. -/\n\nlemma all_goals_try_example :\n even 4 ∧ even 7 ∧ even 3 ∧ even 0 :=\nbegin\n repeat { apply and.intro },\n all_goals { try { apply even.add_two } },\n repeat { sorry }\nend\n\n/- `any_goals` applies its argument exactly once to each goal. It succeeds\nif the argument succeeds on **any** goal. -/\n\nlemma any_goals_example :\n even 4 ∧ even 7 ∧ even 3 ∧ even 0 :=\nbegin\n repeat { apply and.intro },\n any_goals { apply even.add_two },\n repeat { sorry }\nend\n\n/- `solve1` transforms its argument into an all-or-nothing tactic. If the\nargument does not prove the goal, `solve1` fails. -/\n\nlemma any_goals_solve1_repeat_orelse_example :\n even 4 ∧ even 7 ∧ even 3 ∧ even 0 :=\nbegin\n repeat { apply and.intro },\n any_goals { solve1 { repeat {\n apply even.add_two\n <|> apply even.zero } } },\n repeat { sorry }\nend\n\n/- The combinators `repeat`, `iterate`, `all_goals`, and `any_goals` can easily\nlead to infinite looping: -/\n\n/-\nlemma repeat_not_example :\n ¬ even 1 :=\nbegin\n repeat { apply not.intro },\n sorry\nend\n-/\n\n/- Let us start with the actual metaprogramming, by coding a custom tactic. The\ntactic embodies the behavior we hardcoded in the `solve1` example above: -/\n\nmeta def intro_and_even : tactic unit :=\ndo\n tactic.repeat (tactic.applyc ``and.intro),\n tactic.any_goals (tactic.solve1 (tactic.repeat\n (tactic.applyc ``even.add_two\n <|> tactic.applyc ``even.zero))),\n pure ()\n\n/- The `meta` keyword makes it possible for the function to call other\nmetafunctions. The `do` keyword enters a monad, and the `<|>` operator is the\n\"orelse\" operator of alternative monads. At the end, we return `()`, of type\n`unit`, to ensure the metaprogram has the desired type.\n\nAny executable Lean definition can be used as a metaprogram. In addition, we can\nput `meta` in front of a definition to indicate that is a metadefinition. Such\ndefinitions need not terminate but cannot be used in non-`meta` contexts.\n\nLet us apply our custom tactic: -/\n\nlemma any_goals_solve1_repeat_orelse_example₂ :\n even 4 ∧ even 7 ∧ even 3 ∧ even 0 :=\nbegin\n intro_and_even,\n repeat { sorry }\nend\n\n\n/- ## The Metaprogramming Monad\n\nTactics have access to\n\n* the list of **goals** as metavariables (each metavariables has a type and a\n local context (hypothesis); they can optionally be instantiated);\n\n* the **elaborator** (to elaborate expressions and compute their type);\n\n* the **environment**, containing all declarations and inductive types;\n\n* the **attributes** (e.g., the list of `@[simp]` rules).\n\nThe tactic monad is an alternative monad, with `fail` and `<|>`. Tactics can\nalso produce trace messages. -/\n\nlemma even_14 :\n even 14 :=\nby do\n tactic.trace \"Proving evenness …\",\n intro_and_even\n\nmeta def hello_then_intro_and_even : tactic unit :=\ndo\n tactic.trace \"Proving evenness …\",\n intro_and_even\n\nlemma even_16 :\n even 16 :=\nby hello_then_intro_and_even\n\nrun_cmd tactic.trace \"Hello, Metaworld!\"\n\nmeta def trace_goals : tactic unit :=\ndo\n tactic.trace \"local context:\",\n ctx ← tactic.local_context,\n tactic.trace ctx,\n tactic.trace \"target:\",\n P ← tactic.target,\n tactic.trace P,\n tactic.trace \"all missing proofs:\",\n Hs ← tactic.get_goals,\n tactic.trace Hs,\n τs ← list.mmap tactic.infer_type Hs,\n tactic.trace τs\n\nlemma even_18_and_even_20 (α : Type) (a : α) :\n even 18 ∧ even 20 :=\nby do\n tactic.applyc ``and.intro,\n trace_goals,\n intro_and_even\n\nlemma triv_imp (a : Prop) (h : a) :\n a :=\nby do\n h ← tactic.get_local `h,\n tactic.trace \"h:\",\n tactic.trace h,\n tactic.trace \"raw h:\",\n tactic.trace (expr.to_raw_fmt h),\n tactic.trace \"type of h:\",\n τ ← tactic.infer_type h,\n tactic.trace τ,\n tactic.trace \"type of type of h:\",\n υ ← tactic.infer_type τ,\n tactic.trace υ,\n tactic.apply h\n\nmeta def exact_list : list expr → tactic unit\n| [] := tactic.fail \"no matching expression found\"\n| (h :: hs) :=\n do {\n tactic.trace \"trying\",\n tactic.trace h,\n tactic.exact h }\n <|> exact_list hs\n\nmeta def hypothesis : tactic unit :=\ndo\n hs ← tactic.local_context,\n exact_list hs\n\nlemma app_of_app {α : Type} {p : α → Prop} {a : α}\n (h : p a) :\n p a :=\nby hypothesis\n\n\n/- ## Names, Expressions, Declarations, and Environments\n\nThe metaprogramming framework is articulated around five main types:\n\n* `tactic` manages the proof state, the global context, and more;\n\n* `name` represents a structured name (e.g., `x`, `even.add_two`);\n\n* `expr` represents an expression (a term) as an abstract syntax tree;\n\n* `declaration` represents a constant declaration, a definition, an axiom, or a\n lemma;\n\n* `environment` stores all the declarations and notations that make up the\n global context. -/\n\n#print expr\n\n#check expr tt -- elaborated expressions\n#check expr ff -- unelaborated expressions (pre-expressions)\n\n#print name\n\n#check (expr.const `ℕ [] : expr)\n#check expr.sort level.zero -- Sort 0, i.e., Prop\n#check expr.sort (level.succ level.zero)\n -- Sort 1, i.e., Type\n#check expr.var 0 -- bound variable with De Bruijn index 0\n#check (expr.local_const `uniq_name `pp_name binder_info.default\n `(ℕ) : expr)\n#check (expr.mvar `uniq_name `pp_name `(ℕ) : expr)\n#check (expr.pi `pp_name binder_info.default `(ℕ)\n (expr.sort level.zero) : expr)\n#check (expr.lam `pp_name binder_info.default `(ℕ)\n (expr.var 0) : expr)\n#check expr.elet\n#check expr.macro\n\n/- We can create literal expressions conveniently using backticks and\nparentheses:\n\n* Expressions with a single backtick must be fully elaborated.\n\n* Expressions with two backticks are __pre-expressions__: They may contain some\n holes to be filled in later, based on some context.\n\n* Expressions with three backticks are pre-expressions without name checking. -/\n\nrun_cmd do\n let e : expr := `(list.map (λn : ℕ, n + 1) [1, 2, 3]),\n tactic.trace e\n\nrun_cmd do\n let e : expr := `(list.map _ [1, 2, 3]), -- fails\n tactic.trace e\n\nrun_cmd do\n let e₁ : pexpr := ``(list.map (λn, n + 1) [1, 2, 3]),\n let e₂ : pexpr := ``(list.map _ [1, 2, 3]),\n tactic.trace e₁,\n tactic.trace e₂\n\nrun_cmd do\n let e : pexpr := ```(seattle.washington),\n tactic.trace e\n\n/- We can also create literal names with backticks:\n\n* Names with a single backtick, `n, are not checked for existence.\n\n* Names with two backticks, ``n, are resolved and checked. -/\n\nrun_cmd tactic.trace `and.intro\nrun_cmd tactic.trace `intro_and_even\nrun_cmd tactic.trace `seattle.washington\n\nrun_cmd tactic.trace ``and.intro\nrun_cmd tactic.trace ``intro_and_even\nrun_cmd tactic.trace ``seattle.washington -- fails\n\n/- __Antiquotations__ embed an existing expression in a larger expression. They\nare announced by the prefix `%%` followed by a name from the current context.\nAntiquotations are available with one, two, and three backticks: -/\n\nrun_cmd do\n let x : expr := `(2 : ℕ),\n let e : expr := `(%%x + 1),\n tactic.trace e\n\nrun_cmd do\n let x : expr := `(@id ℕ),\n let e : pexpr := ``(list.map %%x),\n tactic.trace e\n\nrun_cmd do\n let x : expr := `(@id ℕ),\n let e : pexpr := ```(a _ %%x),\n tactic.trace e\n\nlemma one_add_two_eq_three :\n 1 + 2 = 3 :=\nby do\n `(%%a + %%b = %%c) ← tactic.target,\n tactic.trace a,\n tactic.trace b,\n tactic.trace c,\n `(@eq %%α %%l %%r) ← tactic.target,\n tactic.trace α,\n tactic.trace l,\n tactic.trace r,\n tactic.exact `(refl _ : 3 = 3)\n\n#print declaration\n\n/- The `environment` type is presented as an abstract type, equipped with some\noperations to query and modify it. The `environment.fold` metafunction iterates\nover all declarations making up the environment. -/\n\nrun_cmd do\n env ← tactic.get_env,\n tactic.trace (environment.fold env 0 (λdecl n, n + 1))\n\n\n/- ## First Example: A Conjuction-Destructing Tactic\n\nWe define a `destruct_and` tactic that automates the elimination of `∧` in\npremises, automating proofs such as these: -/\n\nlemma abcd_a (a b c d : Prop) (h : a ∧ (b ∧ c) ∧ d) :\n a :=\nand.elim_left h\n\nlemma abcd_b (a b c d : Prop) (h : a ∧ (b ∧ c) ∧ d) :\n b :=\nand.elim_left (and.elim_left (and.elim_right h))\n\nlemma abcd_bc (a b c d : Prop) (h : a ∧ (b ∧ c) ∧ d) :\n b ∧ c :=\nand.elim_left (and.elim_right h)\n\n/- Our tactic relies on a helper metafunction, which takes as argument the\nhypothesis `h` to use as an expression rather than as a name: -/\n\nmeta def destruct_and_helper : expr → tactic unit\n| h :=\n do\n t ← tactic.infer_type h,\n match t with\n | `(%%a ∧ %%b) :=\n tactic.exact h\n <|>\n do {\n ha ← tactic.to_expr ``(and.elim_left %%h),\n destruct_and_helper ha }\n <|>\n do {\n hb ← tactic.to_expr ``(and.elim_right %%h),\n destruct_and_helper hb }\n | _ := tactic.exact h\n end\n\nmeta def destruct_and (nam : name) : tactic unit :=\ndo\n h ← tactic.get_local nam,\n destruct_and_helper h\n\n/- Let us check that our tactic works: -/\n\nlemma abc_a (a b c : Prop) (h : a ∧ b ∧ c) :\n a :=\nby destruct_and `h\n\nlemma abc_b (a b c : Prop) (h : a ∧ b ∧ c) :\n b :=\nby destruct_and `h\n\nlemma abc_bc (a b c : Prop) (h : a ∧ b ∧ c) :\n b ∧ c :=\nby destruct_and `h\n\nlemma abc_ac (a b c : Prop) (h : a ∧ b ∧ c) :\n a ∧ c :=\nby destruct_and `h -- fails\n\n\n/- ## Second Example: A Provability Advisor\n\nNext, we implement a `prove_direct` tool that traverses all lemmas in the\ndatabase and checks whether one of them can be used to prove the current goal. A\nsimilar tactic is available in `mathlib` under the name `library_search`. -/\n\nmeta def is_theorem : declaration → bool\n| (declaration.defn _ _ _ _ _ _) := ff\n| (declaration.thm _ _ _ _) := tt\n| (declaration.cnst _ _ _ _) := ff\n| (declaration.ax _ _ _) := tt\n\nmeta def get_all_theorems : tactic (list name) :=\ndo\n env ← tactic.get_env,\n pure (environment.fold env [] (λdecl nams,\n if is_theorem decl then declaration.to_name decl :: nams\n else nams))\n\nmeta def prove_with_name (nam : name) : tactic unit :=\ndo\n tactic.applyc nam\n ({ md := tactic.transparency.reducible, unify := ff }\n : tactic.apply_cfg),\n tactic.all_goals tactic.assumption,\n pure ()\n\nmeta def prove_direct : tactic unit :=\ndo\n nams ← get_all_theorems,\n list.mfirst (λnam,\n do\n prove_with_name nam,\n tactic.trace (\"directly proved by \" ++ to_string nam))\n nams\n\nlemma nat.eq_symm (x y : ℕ) (h : x = y) :\n y = x :=\nby prove_direct\n\nlemma nat.eq_symm₂ (x y : ℕ) (h : x = y) :\n y = x :=\nby library_search\n\nlemma list.reverse_twice (xs : list ℕ) :\n list.reverse (list.reverse xs) = xs :=\nby prove_direct\n\nlemma list.reverse_twice_symm (xs : list ℕ) :\n xs = list.reverse (list.reverse xs) :=\nby prove_direct -- fails\n\n/- As a small refinement, we propose a version of `prove_direct` that also\nlooks for equalities stated in symmetric form. -/\n\nmeta def prove_direct_symm : tactic unit :=\nprove_direct\n<|>\ndo {\n tactic.applyc `eq.symm,\n prove_direct }\n\nlemma list.reverse_twice₂ (xs : list ℕ) :\n list.reverse (list.reverse xs) = xs :=\nby prove_direct_symm\n\nlemma list.reverse_twice_symm₂ (xs : list ℕ) :\n xs = list.reverse (list.reverse xs) :=\nby prove_direct_symm\n\n\n/- ## A Look at Two Predefined Tactics\n\nQuite a few of Lean's predefined tactics are implemented as metaprograms and\nnot in C++. We can find these definitions by clicking the name of a construct\nin Visual Studio Code while holding the control or command key. -/\n\n#check tactic.intro\n#check tactic.assumption\n\nend LoVe\n", "meta": {"author": "blanchette", "repo": "logical_verification_2020", "sha": "7a9f4bd73498189d9beb5d4591e0f2b3ca316111", "save_path": "github-repos/lean/blanchette-logical_verification_2020", "path": "github-repos/lean/blanchette-logical_verification_2020/logical_verification_2020-7a9f4bd73498189d9beb5d4591e0f2b3ca316111/lean/love07_metaprogramming_demo.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.27825678173200435, "lm_q2_score": 0.10230470789265304, "lm_q1q2_score": 0.02846697877424242}} {"text": "/-\nCopyright (c) 2016 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthor: Leonardo de Moura\n-/\nprelude\nimport init.logic\n\nlemma punit_eq (a b : punit) : a = b :=\npunit.rec_on a (punit.rec_on b rfl)\n\nlemma punit_eq_star (a : punit) : a = punit.star :=\npunit_eq a punit.star\n\ninstance : subsingleton punit :=\nsubsingleton.intro punit_eq\n\ninstance : inhabited punit :=\n⟨punit.star⟩\n\ninstance : decidable_eq punit :=\nλ a b, is_true (punit_eq a b)\n", "meta": {"author": "subfish-zhou", "repo": "N2Lean", "sha": "8e858cc5b01f1ad921094dc355db3cb9473a42fd", "save_path": "github-repos/lean/subfish-zhou-N2Lean", "path": "github-repos/lean/subfish-zhou-N2Lean/N2Lean-8e858cc5b01f1ad921094dc355db3cb9473a42fd/library/init/data/punit.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.48047867804790706, "lm_q2_score": 0.05921025406152681, "lm_q1q2_score": 0.02844926459836312}} {"text": "/-\nCopyright (c) 2018 Simon Hudon. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Simon Hudon\n-/\nimport control.applicative\nimport data.list.forall2\nimport data.set.functor\n\n/-!\n# Traversable instances\n\nThis file provides instances of `traversable` for types from the core library: `option`, `list` and\n`sum`.\n-/\n\nuniverses u v\n\nsection option\n\nopen functor\n\nvariables {F G : Type u → Type u}\nvariables [applicative F] [applicative G]\nvariables [is_lawful_applicative F] [is_lawful_applicative G]\n\nlemma option.id_traverse {α} (x : option α) : option.traverse id.mk x = x :=\nby cases x; refl\n\n@[nolint unused_arguments]\nlemma option.comp_traverse {α β γ} (f : β → F γ) (g : α → G β) (x : option α) :\n option.traverse (comp.mk ∘ (<$>) f ∘ g) x =\n comp.mk (option.traverse f <$> option.traverse g x) :=\nby cases x; simp! with functor_norm; refl\n\nlemma option.traverse_eq_map_id {α β} (f : α → β) (x : option α) :\n traverse (id.mk ∘ f) x = id.mk (f <$> x) :=\nby cases x; refl\n\nvariable (η : applicative_transformation F G)\n\nlemma option.naturality {α β} (f : α → F β) (x : option α) :\n η (option.traverse f x) = option.traverse (@η _ ∘ f) x :=\nby cases x with x; simp! [*] with functor_norm\n\nend option\n\ninstance : is_lawful_traversable option :=\n{ id_traverse := @option.id_traverse,\n comp_traverse := @option.comp_traverse,\n traverse_eq_map_id := @option.traverse_eq_map_id,\n naturality := @option.naturality,\n .. option.is_lawful_monad }\n\nnamespace list\n\nvariables {F G : Type u → Type u}\nvariables [applicative F] [applicative G]\n\nsection\nvariables [is_lawful_applicative F] [is_lawful_applicative G]\n\nopen applicative functor list\n\nprotected \n\n@[nolint unused_arguments]\nprotected lemma comp_traverse {α β γ} (f : β → F γ) (g : α → G β) (x : list α) :\n list.traverse (comp.mk ∘ (<$>) f ∘ g) x =\n comp.mk (list.traverse f <$> list.traverse g x) :=\nby induction x; simp! * with functor_norm; refl\n\nprotected lemma traverse_eq_map_id {α β} (f : α → β) (x : list α) :\n list.traverse (id.mk ∘ f) x = id.mk (f <$> x) :=\nby induction x; simp! * with functor_norm; refl\n\nvariable (η : applicative_transformation F G)\n\nprotected lemma naturality {α β} (f : α → F β) (x : list α) :\n η (list.traverse f x) = list.traverse (@η _ ∘ f) x :=\nby induction x; simp! * with functor_norm\nopen nat\n\ninstance : is_lawful_traversable.{u} list :=\n{ id_traverse := @list.id_traverse,\n comp_traverse := @list.comp_traverse,\n traverse_eq_map_id := @list.traverse_eq_map_id,\n naturality := @list.naturality,\n .. list.is_lawful_monad }\nend\n\nsection traverse\nvariables {α' β' : Type u} (f : α' → F β')\n\n@[simp] lemma traverse_nil : traverse f ([] : list α') = (pure [] : F (list β')) := rfl\n\n@[simp] lemma traverse_cons (a : α') (l : list α') :\n traverse f (a :: l) = (::) <$> f a <*> traverse f l := rfl\n\nvariables [is_lawful_applicative F]\n\n@[simp] lemma traverse_append :\n ∀ (as bs : list α'), traverse f (as ++ bs) = (++) <$> traverse f as <*> traverse f bs\n| [] bs :=\n have has_append.append ([] : list β') = id, by funext; refl,\n by simp [this] with functor_norm\n| (a :: as) bs := by simp [traverse_append as bs] with functor_norm; congr\n\nlemma mem_traverse {f : α' → set β'} :\n ∀(l : list α') (n : list β'), n ∈ traverse f l ↔ forall₂ (λb a, b ∈ f a) n l\n| [] [] := by simp\n| (a::as) [] := by simp\n| [] (b::bs) := by simp\n| (a::as) (b::bs) := by simp [mem_traverse as bs]\n\nend traverse\n\nend list\n\nnamespace sum\n\nsection traverse\nvariables {σ : Type u}\nvariables {F G : Type u → Type u}\nvariables [applicative F] [applicative G]\n\nopen applicative functor\nopen list (cons)\n\nprotected lemma traverse_map {α β γ : Type u} (g : α → β) (f : β → G γ) (x : σ ⊕ α) :\n sum.traverse f (g <$> x) = sum.traverse (f ∘ g) x :=\nby cases x; simp [sum.traverse, id_map] with functor_norm; refl\n\nvariables [is_lawful_applicative F] [is_lawful_applicative G]\n\nprotected lemma id_traverse {σ α} (x : σ ⊕ α) : sum.traverse id.mk x = x :=\nby cases x; refl\n\n@[nolint unused_arguments]\nprotected lemma comp_traverse {α β γ} (f : β → F γ) (g : α → G β) (x : σ ⊕ α) :\n sum.traverse (comp.mk ∘ (<$>) f ∘ g) x =\n comp.mk (sum.traverse f <$> sum.traverse g x) :=\nby cases x; simp! [sum.traverse,map_id] with functor_norm; refl\n\nprotected lemma traverse_eq_map_id {α β} (f : α → β) (x : σ ⊕ α) :\n sum.traverse (id.mk ∘ f) x = id.mk (f <$> x) :=\nby induction x; simp! * with functor_norm; refl\n\nprotected lemma map_traverse {α β γ} (g : α → G β) (f : β → γ) (x : σ ⊕ α) :\n (<$>) f <$> sum.traverse g x = sum.traverse ((<$>) f ∘ g) x :=\nby cases x; simp [sum.traverse, id_map] with functor_norm; congr; refl\n\nvariable (η : applicative_transformation F G)\n\nprotected lemma naturality {α β} (f : α → F β) (x : σ ⊕ α) :\n η (sum.traverse f x) = sum.traverse (@η _ ∘ f) x :=\nby cases x; simp! [sum.traverse] with functor_norm\n\nend traverse\n\ninstance {σ : Type u} : is_lawful_traversable.{u} (sum σ) :=\n{ id_traverse := @sum.id_traverse σ,\n comp_traverse := @sum.comp_traverse σ,\n traverse_eq_map_id := @sum.traverse_eq_map_id σ,\n naturality := @sum.naturality σ,\n .. sum.is_lawful_monad }\n\nend sum\n", "meta": {"author": "nick-kuhn", "repo": "leantools", "sha": "567a98c031fffe3f270b7b8dea48389bc70d7abb", "save_path": "github-repos/lean/nick-kuhn-leantools", "path": "github-repos/lean/nick-kuhn-leantools/leantools-567a98c031fffe3f270b7b8dea48389bc70d7abb/src/control/traversable/instances.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4073333856566001, "lm_q2_score": 0.06954174113116343, "lm_q1q2_score": 0.028326672859411643}} {"text": "import Std.Tactic.SeqFocus\n\nexample : (True ∧ (∃ x : Nat, x = x)) ∧ True := by\n constructor\n constructor\n -- error: too many tactics\n fail_if_success map_tacs [trivial, exact ⟨0, rfl⟩, trivial, trivial]\n -- error: not enough tactics\n fail_if_success map_tacs [trivial, exact ⟨0, rfl⟩]\n map_tacs [trivial, exact ⟨0, rfl⟩, trivial]\n\nexample : ((True ∧ True) ∧ (∃ x : Nat, x = x)) ∧ (True ∧ (∃ x : Nat, x = x)) := by\n constructor\n constructor\n map_tacs [(constructor; trivial), exact ⟨0, rfl⟩, constructor]\n trivial\n trivial\n exact ⟨0, rfl⟩\n\nexample : (True ∧ (∃ x : Nat, x = x)) ∧ True := by\n constructor\n -- error: not enough tactics\n fail_if_success constructor <;> [trivial]\n map_tacs [constructor <;> [trivial, exact ⟨0, rfl⟩], constructor]\n", "meta": {"author": "leanprover", "repo": "std4", "sha": "5507f9d8409f93b984ce04eccf4914d534e6fca2", "save_path": "github-repos/lean/leanprover-std4", "path": "github-repos/lean/leanprover-std4/std4-5507f9d8409f93b984ce04eccf4914d534e6fca2/test/seq_focus.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.45713671682749485, "lm_q2_score": 0.0618759813987784, "lm_q1q2_score": 0.0282857829871167}} {"text": "/-\nCopyright (c) 2017 Simon Hudon. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Simon Hudon\n-/\nimport algebra.group.defs\nimport control.functor\n\n/-!\n# `applicative` instances\n\n> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.\n> Any changes to this file require a corresponding PR to mathlib4.\n\nThis file provides `applicative` instances for concrete functors:\n* `id`\n* `functor.comp`\n* `functor.const`\n* `functor.add_const`\n-/\n\nuniverses u v w\n\nsection lemmas\n\nopen function\n\nvariables {F : Type u → Type v}\nvariables [applicative F] [is_lawful_applicative F]\nvariables {α β γ σ : Type u}\n\nlemma applicative.map_seq_map (f : α → β → γ) (g : σ → β) (x : F α) (y : F σ) :\n (f <$> x) <*> (g <$> y) = (flip (∘) g ∘ f) <$> x <*> y :=\nby simp [flip] with functor_norm\n\nlemma applicative.pure_seq_eq_map' (f : α → β) : (<*>) (pure f : F (α → β)) = (<$>) f :=\nby ext; simp with functor_norm\n\ntheorem applicative.ext {F} : ∀ {A1 : applicative F} {A2 : applicative F}\n [@is_lawful_applicative F A1] [@is_lawful_applicative F A2]\n (H1 : ∀ {α : Type u} (x : α),\n @has_pure.pure _ A1.to_has_pure _ x = @has_pure.pure _ A2.to_has_pure _ x)\n (H2 : ∀ {α β : Type u} (f : F (α → β)) (x : F α),\n @has_seq.seq _ A1.to_has_seq _ _ f x = @has_seq.seq _ A2.to_has_seq _ _ f x),\n A1 = A2\n| {to_functor := F1, seq := s1, pure := p1, seq_left := sl1, seq_right := sr1}\n {to_functor := F2, seq := s2, pure := p2, seq_left := sl2, seq_right := sr2} L1 L2 H1 H2 :=\nbegin\n obtain rfl : @p1 = @p2, {funext α x, apply H1},\n obtain rfl : @s1 = @s2, {funext α β f x, apply H2},\n cases L1, cases L2,\n obtain rfl : F1 = F2,\n { resetI, apply functor.ext, intros,\n exact (L1_pure_seq_eq_map _ _).symm.trans (L2_pure_seq_eq_map _ _) },\n congr; funext α β x y,\n { exact (L1_seq_left_eq _ _).trans (L2_seq_left_eq _ _).symm },\n { exact (L1_seq_right_eq _ _).trans (L2_seq_right_eq _ _).symm }\nend\n\nend lemmas\n\ninstance : is_comm_applicative id :=\nby refine { .. }; intros; refl\n\nnamespace functor\nnamespace comp\n\nopen function (hiding comp)\nopen functor\n\nvariables {F : Type u → Type w} {G : Type v → Type u}\n\nvariables [applicative F] [applicative G]\n\nvariables [is_lawful_applicative F] [is_lawful_applicative G]\nvariables {α β γ : Type v}\n\nlemma map_pure (f : α → β) (x : α) : (f <$> pure x : comp F G β) = pure (f x) :=\ncomp.ext $ by simp\n\nlemma seq_pure (f : comp F G (α → β)) (x : α) :\n f <*> pure x = (λ g : α → β, g x) <$> f :=\ncomp.ext $ by simp [(∘)] with functor_norm\n\n\n\nlemma pure_seq_eq_map (f : α → β) (x : comp F G α) :\n pure f <*> x = f <$> x :=\ncomp.ext $ by simp [applicative.pure_seq_eq_map'] with functor_norm\n\ninstance : is_lawful_applicative (comp F G) :=\n{ pure_seq_eq_map := @comp.pure_seq_eq_map F G _ _ _ _,\n map_pure := @comp.map_pure F G _ _ _ _,\n seq_pure := @comp.seq_pure F G _ _ _ _,\n seq_assoc := @comp.seq_assoc F G _ _ _ _ }\n\ntheorem applicative_id_comp {F} [AF : applicative F] [LF : is_lawful_applicative F] :\n @comp.applicative id F _ _ = AF :=\n@applicative.ext F _ _ (@comp.is_lawful_applicative id F _ _ _ _) _\n (λ α x, rfl) (λ α β f x, rfl)\n\ntheorem applicative_comp_id {F} [AF : applicative F] [LF : is_lawful_applicative F] :\n @comp.applicative F id _ _ = AF :=\n@applicative.ext F _ _ (@comp.is_lawful_applicative F id _ _ _ _) _\n (λ α x, rfl) (λ α β f x, show id <$> f <*> x = f <*> x, by rw id_map)\n\nopen is_comm_applicative\n\ninstance {f : Type u → Type w} {g : Type v → Type u}\n [applicative f] [applicative g]\n [is_comm_applicative f] [is_comm_applicative g] :\n is_comm_applicative (comp f g) :=\nby { refine { .. @comp.is_lawful_applicative f g _ _ _ _, .. },\n intros, casesm* comp _ _ _, simp! [map,has_seq.seq] with functor_norm,\n rw [commutative_map],\n simp [comp.mk,flip,(∘)] with functor_norm,\n congr, funext, rw [commutative_map], congr }\n\nend comp\nend functor\n\nopen functor\n\n@[functor_norm]\nlemma comp.seq_mk {α β : Type w}\n {f : Type u → Type v} {g : Type w → Type u}\n [applicative f] [applicative g]\n (h : f (g (α → β))) (x : f (g α)) :\n comp.mk h <*> comp.mk x = comp.mk (has_seq.seq <$> h <*> x) := rfl\n\ninstance {α} [has_one α] [has_mul α] : applicative (const α) :=\n{ pure := λ β x, (1 : α),\n seq := λ β γ f x, (f * x : α) }\n\ninstance {α} [monoid α] : is_lawful_applicative (const α) :=\nby refine { .. }; intros; simp [mul_assoc, (<$>), (<*>), pure]\n\ninstance {α} [has_zero α] [has_add α] : applicative (add_const α) :=\n{ pure := λ β x, (0 : α),\n seq := λ β γ f x, (f + x : α) }\n\ninstance {α} [add_monoid α] : is_lawful_applicative (add_const α) :=\nby refine { .. }; intros; simp [add_assoc, (<$>), (<*>), pure]\n", "meta": {"author": "leanprover-community", "repo": "mathlib", "sha": "5e526d18cea33550268dcbbddcb822d5cde40654", "save_path": "github-repos/lean/leanprover-community-mathlib", "path": "github-repos/lean/leanprover-community-mathlib/mathlib-5e526d18cea33550268dcbbddcb822d5cde40654/src/control/applicative.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.37754066879814546, "lm_q2_score": 0.074770043938816, "lm_q1q2_score": 0.028228732394727316}} {"text": "import Lean\nsyntax (name := test) \"test%\" ident : command\n\nopen Lean.Elab\nopen Lean.Elab.Command\n\n@[commandElab test] def elabTest : CommandElab := fun stx => do\n let id ← resolveGlobalConstNoOverloadWithInfo stx[1]\n liftTermElabM none do\n IO.println (repr (← Lean.Meta.Match.getEquationsFor id))\n return ()\n\ndef f (x : List Nat) : Nat :=\n match x with\n | [] => 1\n | [a] => 2\n | _ => 3\n\ntest% f.match_1\n#check @f.match_1\n#check @f.match_1.splitter\n\ntheorem ex (x : List Nat) : f x > 0 := by\n simp [f]\n split <;> decide\n\ntest% Std.RBNode.balance1.match_1\n#check @Std.RBNode.balance1.match_1.splitter\n", "meta": {"author": "Kha", "repo": "lean4-nightly", "sha": "b4c92de57090e6c47b29d3575df53d86fce52752", "save_path": "github-repos/lean/Kha-lean4-nightly", "path": "github-repos/lean/Kha-lean4-nightly/lean4-nightly-b4c92de57090e6c47b29d3575df53d86fce52752/tests/lean/run/matchEqs.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44939263446475963, "lm_q2_score": 0.0627892042126289, "lm_q1q2_score": 0.028217005897059087}} {"text": "/-\nCopyright (c) 2019 Reid Barton. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Reid Barton, Scott Morrison\n\nFacts about epimorphisms and monomorphisms.\n\nThe definitions of `epi` and `mono` are in `category_theory.category`,\nsince they are used by some lemmas for `iso`, which is used everywhere.\n-/\nimport category_theory.adjunction.basic\nimport category_theory.opposites\n\nuniverses v₁ v₂ u₁ u₂\n\nnamespace category_theory\n\nvariables {C : Type u₁} [category.{v₁} C]\n\nsection\nvariables {D : Type u₂} [category.{v₂} D]\n\nlemma left_adjoint_preserves_epi {F : C ⥤ D} {G : D ⥤ C} (adj : F ⊣ G)\n {X Y : C} {f : X ⟶ Y} (hf : epi f) : epi (F.map f) :=\nbegin\n constructor,\n intros Z g h H,\n replace H := congr_arg (adj.hom_equiv X Z) H,\n rwa [adj.hom_equiv_naturality_left, adj.hom_equiv_naturality_left,\n cancel_epi, equiv.apply_eq_iff_eq] at H\nend\n\nlemma right_adjoint_preserves_mono {F : C ⥤ D} {G : D ⥤ C} (adj : F ⊣ G)\n {X Y : D} {f : X ⟶ Y} (hf : mono f) : mono (G.map f) :=\nbegin\n constructor,\n intros Z g h H,\n replace H := congr_arg (adj.hom_equiv Z Y).symm H,\n rwa [adj.hom_equiv_naturality_right_symm, adj.hom_equiv_naturality_right_symm,\n cancel_mono, equiv.apply_eq_iff_eq] at H\nend\n\ninstance is_equivalence.epi_map {F : C ⥤ D} [is_left_adjoint F] {X Y : C} {f : X ⟶ Y}\n [h : epi f] : epi (F.map f) :=\nleft_adjoint_preserves_epi (adjunction.of_left_adjoint F) h\n\ninstance is_equivalence.mono_map {F : C ⥤ D} [is_right_adjoint F] {X Y : C} {f : X ⟶ Y}\n [h : mono f] : mono (F.map f) :=\nright_adjoint_preserves_mono (adjunction.of_right_adjoint F) h\n\nlemma faithful_reflects_epi (F : C ⥤ D) [faithful F] {X Y : C} {f : X ⟶ Y}\n (hf : epi (F.map f)) : epi f :=\n⟨λ Z g h H, F.map_injective $\n by rw [←cancel_epi (F.map f), ←F.map_comp, ←F.map_comp, H]⟩\n\nlemma faithful_reflects_mono (F : C ⥤ D) [faithful F] {X Y : C} {f : X ⟶ Y}\n (hf : mono (F.map f)) : mono f :=\n⟨λ Z g h H, F.map_injective $\n by rw [←cancel_mono (F.map f), ←F.map_comp, ←F.map_comp, H]⟩\nend\n\n/--\nA split monomorphism is a morphism `f : X ⟶ Y` admitting a retraction `retraction f : Y ⟶ X`\nsuch that `f ≫ retraction f = 𝟙 X`.\n\nEvery split monomorphism is a monomorphism.\n-/\nclass split_mono {X Y : C} (f : X ⟶ Y) :=\n(retraction : Y ⟶ X)\n(id' : f ≫ retraction = 𝟙 X . obviously)\n\n/--\nA split epimorphism is a morphism `f : X ⟶ Y` admitting a section `section_ f : Y ⟶ X`\nsuch that `section_ f ≫ f = 𝟙 Y`.\n(Note that `section` is a reserved keyword, so we append an underscore.)\n\nEvery split epimorphism is an epimorphism.\n-/\nclass split_epi {X Y : C} (f : X ⟶ Y) :=\n(section_ : Y ⟶ X)\n(id' : section_ ≫ f = 𝟙 Y . obviously)\n\n/-- The chosen retraction of a split monomorphism. -/\ndef retraction {X Y : C} (f : X ⟶ Y) [split_mono f] : Y ⟶ X := split_mono.retraction f\n@[simp, reassoc]\nlemma split_mono.id {X Y : C} (f : X ⟶ Y) [split_mono f] : f ≫ retraction f = 𝟙 X :=\nsplit_mono.id'\n/-- The retraction of a split monomorphism is itself a split epimorphism. -/\ninstance retraction_split_epi {X Y : C} (f : X ⟶ Y) [split_mono f] : split_epi (retraction f) :=\n{ section_ := f }\n\n/-- A split mono which is epi is an iso. -/\nlemma is_iso_of_epi_of_split_mono {X Y : C} (f : X ⟶ Y) [split_mono f] [epi f] : is_iso f :=\n⟨⟨retraction f, ⟨by simp, by simp [← cancel_epi f]⟩⟩⟩\n\n/--\nThe chosen section of a split epimorphism.\n(Note that `section` is a reserved keyword, so we append an underscore.)\n-/\ndef section_ {X Y : C} (f : X ⟶ Y) [split_epi f] : Y ⟶ X := split_epi.section_ f\n@[simp, reassoc]\nlemma split_epi.id {X Y : C} (f : X ⟶ Y) [split_epi f] : section_ f ≫ f = 𝟙 Y :=\nsplit_epi.id'\n/-- The section of a split epimorphism is itself a split monomorphism. -/\ninstance section_split_mono {X Y : C} (f : X ⟶ Y) [split_epi f] : split_mono (section_ f) :=\n{ retraction := f }\n\n/-- A split epi which is mono is an iso. -/\nlemma is_iso_of_mono_of_split_epi {X Y : C} (f : X ⟶ Y) [mono f] [split_epi f] : is_iso f :=\n⟨⟨section_ f, ⟨by simp [← cancel_mono f], by simp⟩⟩⟩\n\n/-- Every iso is a split mono. -/\n@[priority 100]\nnoncomputable\ninstance split_mono.of_iso {X Y : C} (f : X ⟶ Y) [is_iso f] : split_mono f :=\n{ retraction := inv f }\n\n/-- Every iso is a split epi. -/\n@[priority 100]\nnoncomputable\ninstance split_epi.of_iso {X Y : C} (f : X ⟶ Y) [is_iso f] : split_epi f :=\n{ section_ := inv f }\n\n/-- Every split mono is a mono. -/\n@[priority 100]\ninstance split_mono.mono {X Y : C} (f : X ⟶ Y) [split_mono f] : mono f :=\n{ right_cancellation := λ Z g h w, begin replace w := w =≫ retraction f, simpa using w, end }\n\n/-- Every split epi is an epi. -/\n@[priority 100]\ninstance split_epi.epi {X Y : C} (f : X ⟶ Y) [split_epi f] : epi f :=\n{ left_cancellation := λ Z g h w, begin replace w := section_ f ≫= w, simpa using w, end }\n\n/-- Every split mono whose retraction is mono is an iso. -/\nlemma is_iso.of_mono_retraction {X Y : C} {f : X ⟶ Y} [split_mono f] [mono $ retraction f]\n : is_iso f :=\n⟨⟨retraction f, ⟨by simp, (cancel_mono_id $ retraction f).mp (by simp)⟩⟩⟩\n\n/-- Every split epi whose section is epi is an iso. -/\nlemma is_iso.of_epi_section {X Y : C} {f : X ⟶ Y} [split_epi f] [epi $ section_ f]\n : is_iso f :=\n⟨⟨section_ f, ⟨(cancel_epi_id $ section_ f).mp (by simp), by simp⟩⟩⟩\n\ninstance unop_mono_of_epi {A B : Cᵒᵖ} (f : A ⟶ B) [epi f] : mono f.unop :=\n⟨λ Z g h eq, quiver.hom.op_inj ((cancel_epi f).1 (quiver.hom.unop_inj eq))⟩\n\ninstance unop_epi_of_mono {A B : Cᵒᵖ} (f : A ⟶ B) [mono f] : epi f.unop :=\n⟨λ Z g h eq, quiver.hom.op_inj ((cancel_mono f).1 (quiver.hom.unop_inj eq))⟩\n\ninstance op_mono_of_epi {A B : C} (f : A ⟶ B) [epi f] : mono f.op :=\n⟨λ Z g h eq, quiver.hom.unop_inj ((cancel_epi f).1 (quiver.hom.op_inj eq))⟩\n\ninstance op_epi_of_mono {A B : C} (f : A ⟶ B) [mono f] : epi f.op :=\n⟨λ Z g h eq, quiver.hom.unop_inj ((cancel_mono f).1 (quiver.hom.op_inj eq))⟩\n\nsection\nvariables {D : Type u₂} [category.{v₂} D]\n\n/-- Split monomorphisms are also absolute monomorphisms. -/\ninstance {X Y : C} (f : X ⟶ Y) [split_mono f] (F : C ⥤ D) : split_mono (F.map f) :=\n{ retraction := F.map (retraction f),\n id' := by { rw [←functor.map_comp, split_mono.id, functor.map_id], } }\n\n/-- Split epimorphisms are also absolute epimorphisms. -/\ninstance {X Y : C} (f : X ⟶ Y) [split_epi f] (F : C ⥤ D) : split_epi (F.map f) :=\n{ section_ := F.map (section_ f),\n id' := by { rw [←functor.map_comp, split_epi.id, functor.map_id], } }\nend\n\nend category_theory\n", "meta": {"author": "JLimperg", "repo": "aesop3", "sha": "a4a116f650cc7403428e72bd2e2c4cda300fe03f", "save_path": "github-repos/lean/JLimperg-aesop3", "path": "github-repos/lean/JLimperg-aesop3/aesop3-a4a116f650cc7403428e72bd2e2c4cda300fe03f/src/category_theory/epi_mono.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4416729909662417, "lm_q2_score": 0.06371499647430197, "lm_q1q2_score": 0.028141193062208494}} {"text": "structure A where\n x : Nat\n w : Nat\n\nstructure B extends A where\n y : Nat\n\nstructure C extends B where\n z : Nat\n\ndef f1 (c : C) (a : A) : C :=\n { c with toA := a, x := 0 } -- Error, `toA` and `x` are both updates to field `x`\n\ndef f2 (c : C) (a : A) : C :=\n { c with toA := a }\n\ndef f3 (c : C) (a : A) : C :=\n { a, c with x := 0 }\n\ntheorem ex1 (a : A) (c : C) : (f3 c a).x = 0 :=\n rfl\n\ntheorem ex2 (a : A) (c : C) : (f3 c a).w = a.w :=\n rfl\n\ndef f4 (c : C) (a : A) : C :=\n { c, a with x := 0 } -- TODO: generate error that `a` was not used?\n\ntheorem ex3 (a : A) (c : C) : (f4 c a).w = c.w :=\n rfl\n\ntheorem ex4 (a : A) (c : C) : (f4 c a).x = 0 :=\n rfl\n\ndef f5 (c : C) (a : A) :=\n { c, a with x := 0 }\n\n#check f5\n\ndef f6 (c : C) (a : A) :=\n { a, c with x := 0 }\n\n#check f6\n", "meta": {"author": "leanprover", "repo": "lean4", "sha": "742d053a97bdd109a41a921facd1cd6a55e89bc7", "save_path": "github-repos/lean/leanprover-lean4", "path": "github-repos/lean/leanprover-lean4/lean4-742d053a97bdd109a41a921facd1cd6a55e89bc7/tests/lean/structInst1.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.056652419335261495, "lm_q1q2_score": 0.02810491565682224}} {"text": "/-\nCopyright (c) 2015 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthor: Leonardo de Moura\n\nQuotient types.\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.data.sigma.basic\nimport Mathlib.Lean3Lib.init.logic\nimport Mathlib.Lean3Lib.init.propext\nimport Mathlib.Lean3Lib.init.data.setoid\n \n\nuniverses u v u_a u_b u_c \n\nnamespace Mathlib\n\n/- We import propext here, otherwise we would need a quot.lift for propositions. -/\n\n-- iff can now be used to do substitutions in a calculation\n\ntheorem iff_subst {a : Prop} {b : Prop} {p : Prop → Prop} (h₁ : a ↔ b) (h₂ : p a) : p b :=\n propext h₁ ▸ h₂\n\nnamespace quot\n\n\naxiom sound {α : Sort u} {r : α → α → Prop} {a : α} {b : α} : r a b → Quot.mk r a = Quot.mk r bprotected theorem lift_beta {α : Sort u} {r : α → α → Prop} {β : Sort v} (f : α → β) (c : ∀ (a b : α), r a b → f a = f b) (a : α) : Quot.lift f c (Quot.mk r a) = f a :=\n rfl\n\nprotected theorem ind_beta {α : Sort u} {r : α → α → Prop} {β : Quot r → Prop} (p : ∀ (a : α), β (Quot.mk r a)) (a : α) : Quot.ind p (Quot.mk r a) = p a :=\n rfl\n\nprotected def lift_on {α : Sort u} {β : Sort v} {r : α → α → Prop} (q : Quot r) (f : α → β) (c : ∀ (a b : α), r a b → f a = f b) : β :=\n Quot.lift f c q\n\nprotected theorem induction_on {α : Sort u} {r : α → α → Prop} {β : Quot r → Prop} (q : Quot r) (h : ∀ (a : α), β (Quot.mk r a)) : β q :=\n Quot.ind h q\n\ntheorem exists_rep {α : Sort u} {r : α → α → Prop} (q : Quot r) : ∃ (a : α), Quot.mk r a = q :=\n quot.induction_on q fun (a : α) => Exists.intro a rfl\n\nprotected def indep {α : Sort u} {r : α → α → Prop} {β : Quot r → Sort v} (f : (a : α) → β (Quot.mk r a)) (a : α) : psigma β :=\n psigma.mk (Quot.mk r a) (f a)\n\nprotected theorem indep_coherent {α : Sort u} {r : α → α → Prop} {β : Quot r → Sort v} (f : (a : α) → β (Quot.mk r a)) (h : ∀ (a b : α) (p : r a b), Eq._oldrec (f a) (sound p) = f b) (a : α) (b : α) : r a b → quot.indep f a = quot.indep f b :=\n fun (e : r a b) => psigma.eq (sound e) (h a b e)\n\nprotected theorem lift_indep_pr1 {α : Sort u} {r : α → α → Prop} {β : Quot r → Sort v} (f : (a : α) → β (Quot.mk r a)) (h : ∀ (a b : α) (p : r a b), Eq._oldrec (f a) (sound p) = f b) (q : Quot r) : psigma.fst (Quot.lift (quot.indep f) (quot.indep_coherent f h) q) = q :=\n Quot.ind (fun (a : α) => Eq.refl (psigma.fst (quot.indep f a))) q\n\nprotected def rec {α : Sort u} {r : α → α → Prop} {β : Quot r → Sort v} (f : (a : α) → β (Quot.mk r a)) (h : ∀ (a b : α) (p : r a b), Eq._oldrec (f a) (sound p) = f b) (q : Quot r) : β q :=\n eq.rec_on (quot.lift_indep_pr1 f h q) (psigma.snd (Quot.lift (quot.indep f) (quot.indep_coherent f h) q))\n\nprotected def rec_on {α : Sort u} {r : α → α → Prop} {β : Quot r → Sort v} (q : Quot r) (f : (a : α) → β (Quot.mk r a)) (h : ∀ (a b : α) (p : r a b), Eq._oldrec (f a) (sound p) = f b) : β q :=\n quot.rec f h q\n\nprotected def rec_on_subsingleton {α : Sort u} {r : α → α → Prop} {β : Quot r → Sort v} [h : ∀ (a : α), subsingleton (β (Quot.mk r a))] (q : Quot r) (f : (a : α) → β (Quot.mk r a)) : β q :=\n quot.rec f sorry q\n\nprotected def hrec_on {α : Sort u} {r : α → α → Prop} {β : Quot r → Sort v} (q : Quot r) (f : (a : α) → β (Quot.mk r a)) (c : ∀ (a b : α), r a b → f a == f b) : β q :=\n quot.rec_on q f sorry\n\nend quot\n\n\ndef quotient {α : Sort u} (s : setoid α) :=\n Quot setoid.r\n\nnamespace quotient\n\n\nprotected def mk {α : Sort u} [s : setoid α] (a : α) : quotient s :=\n Quot.mk setoid.r a\n\ndef sound {α : Sort u} [s : setoid α] {a : α} {b : α} : a ≈ b → quotient.mk a = quotient.mk b :=\n quot.sound\n\nprotected def lift {α : Sort u} {β : Sort v} [s : setoid α] (f : α → β) : (∀ (a b : α), a ≈ b → f a = f b) → quotient s → β :=\n Quot.lift f\n\nprotected theorem ind {α : Sort u} [s : setoid α] {β : quotient s → Prop} : (∀ (a : α), β (quotient.mk a)) → ∀ (q : quotient s), β q :=\n Quot.ind\n\nprotected def lift_on {α : Sort u} {β : Sort v} [s : setoid α] (q : quotient s) (f : α → β) (c : ∀ (a b : α), a ≈ b → f a = f b) : β :=\n quot.lift_on q f c\n\nprotected theorem induction_on {α : Sort u} [s : setoid α] {β : quotient s → Prop} (q : quotient s) (h : ∀ (a : α), β (quotient.mk a)) : β q :=\n quot.induction_on q h\n\ntheorem exists_rep {α : Sort u} [s : setoid α] (q : quotient s) : ∃ (a : α), quotient.mk a = q :=\n quot.exists_rep q\n\nprotected def rec {α : Sort u} [s : setoid α] {β : quotient s → Sort v} (f : (a : α) → β (quotient.mk a)) (h : ∀ (a b : α) (p : a ≈ b), Eq._oldrec (f a) (sound p) = f b) (q : quotient s) : β q :=\n quot.rec f h q\n\nprotected def rec_on {α : Sort u} [s : setoid α] {β : quotient s → Sort v} (q : quotient s) (f : (a : α) → β (quotient.mk a)) (h : ∀ (a b : α) (p : a ≈ b), Eq._oldrec (f a) (sound p) = f b) : β q :=\n quot.rec_on q f h\n\nprotected def rec_on_subsingleton {α : Sort u} [s : setoid α] {β : quotient s → Sort v} [h : ∀ (a : α), subsingleton (β (quotient.mk a))] (q : quotient s) (f : (a : α) → β (quotient.mk a)) : β q :=\n quot.rec_on_subsingleton q f\n\nprotected def hrec_on {α : Sort u} [s : setoid α] {β : quotient s → Sort v} (q : quotient s) (f : (a : α) → β (quotient.mk a)) (c : ∀ (a b : α), a ≈ b → f a == f b) : β q :=\n quot.hrec_on q f c\n\nprotected def lift₂ {α : Sort u_a} {β : Sort u_b} {φ : Sort u_c} [s₁ : setoid α] [s₂ : setoid β] (f : α → β → φ) (c : ∀ (a₁ : α) (a₂ : β) (b₁ : α) (b₂ : β), a₁ ≈ b₁ → a₂ ≈ b₂ → f a₁ a₂ = f b₁ b₂) (q₁ : quotient s₁) (q₂ : quotient s₂) : φ :=\n quotient.lift (fun (a₁ : α) => quotient.lift (f a₁) sorry q₂) sorry q₁\n\nprotected def lift_on₂ {α : Sort u_a} {β : Sort u_b} {φ : Sort u_c} [s₁ : setoid α] [s₂ : setoid β] (q₁ : quotient s₁) (q₂ : quotient s₂) (f : α → β → φ) (c : ∀ (a₁ : α) (a₂ : β) (b₁ : α) (b₂ : β), a₁ ≈ b₁ → a₂ ≈ b₂ → f a₁ a₂ = f b₁ b₂) : φ :=\n quotient.lift₂ f c q₁ q₂\n\nprotected theorem ind₂ {α : Sort u_a} {β : Sort u_b} [s₁ : setoid α] [s₂ : setoid β] {φ : quotient s₁ → quotient s₂ → Prop} (h : ∀ (a : α) (b : β), φ (quotient.mk a) (quotient.mk b)) (q₁ : quotient s₁) (q₂ : quotient s₂) : φ q₁ q₂ :=\n quotient.ind (fun (a₁ : α) => quotient.ind (fun (a₂ : β) => h a₁ a₂) q₂) q₁\n\nprotected theorem induction_on₂ {α : Sort u_a} {β : Sort u_b} [s₁ : setoid α] [s₂ : setoid β] {φ : quotient s₁ → quotient s₂ → Prop} (q₁ : quotient s₁) (q₂ : quotient s₂) (h : ∀ (a : α) (b : β), φ (quotient.mk a) (quotient.mk b)) : φ q₁ q₂ :=\n quotient.ind (fun (a₁ : α) => quotient.ind (fun (a₂ : β) => h a₁ a₂) q₂) q₁\n\nprotected theorem induction_on₃ {α : Sort u_a} {β : Sort u_b} {φ : Sort u_c} [s₁ : setoid α] [s₂ : setoid β] [s₃ : setoid φ] {δ : quotient s₁ → quotient s₂ → quotient s₃ → Prop} (q₁ : quotient s₁) (q₂ : quotient s₂) (q₃ : quotient s₃) (h : ∀ (a : α) (b : β) (c : φ), δ (quotient.mk a) (quotient.mk b) (quotient.mk c)) : δ q₁ q₂ q₃ :=\n quotient.ind (fun (a₁ : α) => quotient.ind (fun (a₂ : β) => quotient.ind (fun (a₃ : φ) => h a₁ a₂ a₃) q₃) q₂) q₁\n\ntheorem exact {α : Sort u} [s : setoid α] {a : α} {b : α} : quotient.mk a = quotient.mk b → a ≈ b :=\n fun (h : quotient.mk a = quotient.mk b) => eq_imp_rel h\n\nprotected def rec_on_subsingleton₂ {α : Sort u_a} {β : Sort u_b} [s₁ : setoid α] [s₂ : setoid β] {φ : quotient s₁ → quotient s₂ → Sort u_c} [h : ∀ (a : α) (b : β), subsingleton (φ (quotient.mk a) (quotient.mk b))] (q₁ : quotient s₁) (q₂ : quotient s₂) (f : (a : α) → (b : β) → φ (quotient.mk a) (quotient.mk b)) : φ q₁ q₂ :=\n quotient.rec_on_subsingleton q₁ fun (a : α) => quotient.rec_on_subsingleton q₂ fun (b : β) => f a b\n\nend quotient\n\n\ninductive eqv_gen {α : Type u} (r : α → α → Prop) : α → α → Prop\nwhere\n| rel : ∀ (x y : α), r x y → eqv_gen r x y\n| refl : ∀ (x : α), eqv_gen r x x\n| symm : ∀ (x y : α), eqv_gen r x y → eqv_gen r y x\n| trans : ∀ (x y z : α), eqv_gen r x y → eqv_gen r y z → eqv_gen r x z\n\ntheorem eqv_gen.is_equivalence {α : Type u} (r : α → α → Prop) : equivalence (eqv_gen r) :=\n mk_equivalence (eqv_gen r) eqv_gen.refl eqv_gen.symm eqv_gen.trans\n\ndef eqv_gen.setoid {α : Type u} (r : α → α → Prop) : setoid α :=\n setoid.mk (eqv_gen r) (eqv_gen.is_equivalence r)\n\ntheorem quot.exact {α : Type u} (r : α → α → Prop) {a : α} {b : α} (H : Quot.mk r a = Quot.mk r b) : eqv_gen r a b :=\n quotient.exact (congr_arg (Quot.lift quotient.mk fun (x y : α) (h : r x y) => quot.sound (eqv_gen.rel x y h)) H)\n\ntheorem quot.eqv_gen_sound {α : Type u} {r : α → α → Prop} {a : α} {b : α} (H : eqv_gen r a b) : Quot.mk r a = Quot.mk r b := sorry\n\nprotected instance quotient.decidable_eq {α : Sort u} {s : setoid α} [d : (a b : α) → Decidable (a ≈ b)] : DecidableEq (quotient s) :=\n fun (q₁ q₂ : quotient s) => quotient.rec_on_subsingleton₂ q₁ q₂ fun (a₁ a₂ : α) => sorry\n\n", "meta": {"author": "AurelienSaue", "repo": "Mathlib4_auto", "sha": "590df64109b08190abe22358fabc3eae000943f2", "save_path": "github-repos/lean/AurelienSaue-Mathlib4_auto", "path": "github-repos/lean/AurelienSaue-Mathlib4_auto/Mathlib4_auto-590df64109b08190abe22358fabc3eae000943f2/Mathlib/Lean3Lib/init/data/quot.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4263215925474903, "lm_q2_score": 0.06560483745906928, "lm_q1q2_score": 0.027968758784369663}} {"text": "/-\nCopyright (c) 2018 Scott Morrison. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Scott Morrison, Mario Carneiro\n-/\nimport tactic.ext\n\nopen interactive\n\nnamespace tactic\n\n/-\nThis file defines a `chain` tactic, which takes a list of tactics,\nand exhaustively tries to apply them to the goals, until no tactic succeeds on any goal.\n\nAlong the way, it generates auxiliary declarations, in order to speed up elaboration time\nof the resulting (sometimes long!) proofs.\n\nThis tactic is used by the `tidy` tactic.\n-/\n\n-- α is the return type of our tactics. When `chain` is called by `tidy`, this is string,\n-- describing what that tactic did as an interactive tactic.\nvariable {α : Type}\n\ninductive tactic_script (α : Type) : Type\n| base : α → tactic_script\n| work (index : ℕ) (first : α) (later : list tactic_script) (closed : bool) : tactic_script\n\nmeta def tactic_script.to_string : tactic_script string → string\n| (tactic_script.base a) := a\n| (tactic_script.work n a l c) := \"work_on_goal \" ++ (to_string n) ++\n \" { \" ++ (\", \".intercalate (a :: l.map tactic_script.to_string)) ++ \" }\"\n\nmeta instance : has_to_string (tactic_script string) :=\n{ to_string := λ s, s.to_string }\n\nmeta instance tactic_script_unit_has_to_string : has_to_string (tactic_script unit) :=\n{ to_string := λ s, \"[chain tactic]\" }\n\nmeta def abstract_if_success (tac : expr → tactic α) (g : expr) : tactic α :=\ndo\n type ← infer_type g,\n is_lemma ← is_prop type,\n if is_lemma then -- there's no point making the abstraction, and indeed it's slower\n tac g\n else do\n m ← mk_meta_var type,\n a ← tac m,\n do\n { val ← instantiate_mvars m,\n guard (val.list_meta_vars = []),\n c ← new_aux_decl_name,\n gs ← get_goals,\n set_goals [g],\n add_aux_decl c type val ff >>= unify g,\n set_goals gs }\n <|> unify m g,\n return a\n\n/--\n`chain_many tac` recursively tries `tac` on all goals, working depth-first on generated subgoals,\nuntil it no longer succeeds on any goal. `chain_many` automatically makes auxiliary definitions.\n-/\nmeta mutual def chain_single, chain_many, chain_iter {α} (tac : tactic α)\nwith chain_single : expr → tactic (α × list (tactic_script α)) | g :=\ndo set_goals [g],\n a ← tac,\n l ← get_goals >>= chain_many,\n return (a, l)\nwith chain_many : list expr → tactic (list (tactic_script α))\n| [] := return []\n| [g] := do\n{ (a, l) ← chain_single g,\n return (tactic_script.base a :: l) } <|> return []\n| gs := chain_iter gs []\nwith chain_iter : list expr → list expr → tactic (list (tactic_script α))\n| [] _ := return []\n| (g :: later_goals) stuck_goals := do\n{ (a, l) ← abstract_if_success chain_single g,\n new_goals ← get_goals,\n let w := tactic_script.work stuck_goals.length a l (new_goals = []),\n let current_goals := stuck_goals.reverse ++ new_goals ++ later_goals,\n set_goals current_goals, -- we keep the goals up to date, so they are correct at the end\n l' ← chain_many current_goals,\n return (w :: l') } <|> chain_iter later_goals (g :: stuck_goals)\n\nmeta def chain_core {α : Type} [has_to_string (tactic_script α)] (tactics : list (tactic α)) :\n tactic (list string) :=\ndo results ← (get_goals >>= chain_many (first tactics)),\n when results.empty (fail \"`chain` tactic made no progress\"),\n return (results.map to_string)\n\nvariables [has_to_string (tactic_script α)] [has_to_format α]\n\ndeclare_trace chain\n\nmeta def trace_output (t : tactic α) : tactic α :=\ndo tgt ← target,\n r ← t,\n name ← decl_name,\n trace format!\"`chain` successfully applied a tactic during elaboration of {name}:\",\n tgt ← pp tgt,\n trace format!\"previous target: {tgt}\",\n trace format!\"tactic result: {r}\",\n tgt ← try_core target,\n tgt ← match tgt with\n | (some tgt) := pp tgt\n | none := return \"no goals\"\n end,\n trace format!\"new target: {tgt}\",\n pure r\n\nmeta def chain (tactics : list (tactic α)) : tactic (list string) :=\nchain_core\n (if is_trace_enabled_for `chain then (tactics.map trace_output) else tactics)\n\nend tactic\n", "meta": {"author": "jjaassoonn", "repo": "projective_space", "sha": "11fe19fe9d7991a272e7a40be4b6ad9b0c10c7ce", "save_path": "github-repos/lean/jjaassoonn-projective_space", "path": "github-repos/lean/jjaassoonn-projective_space/projective_space-11fe19fe9d7991a272e7a40be4b6ad9b0c10c7ce/src/tactic/chain.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3960681520167196, "lm_q2_score": 0.07055958836943614, "lm_q1q2_score": 0.027946405772542992}} {"text": "import data.polya.field\n\nnamespace tactic\n\nmeta def pexpr_of_pos_num (α h_one h_add : expr) : pos_num → pexpr\n| pos_num.one := ``(@has_one.one %%α %%h_one)\n| (pos_num.bit0 n) := ``(@bit0 %%α %%h_add (%%(pexpr_of_pos_num n)))\n| (pos_num.bit1 n) := ``(@bit1 %%α %%h_one %%h_add (%%(pexpr_of_pos_num n)))\n\nmeta def expr_of_num (α : expr) (n : num) : tactic expr :=\nmatch n with\n| num.zero := do\n h_zero ← mk_app `has_zero [α] >>= mk_instance,\n to_expr ``(@has_zero.zero %%α %%h_zero)\n| (num.pos (pos_num.one)) := do\n h_one ← mk_app `has_one [α] >>= mk_instance,\n to_expr ``(@has_one.one %%α %%h_one)\n| (num.pos m) := do\n h_one ← mk_app `has_one [α] >>= mk_instance,\n h_add ← mk_app `has_add [α] >>= mk_instance,\n to_expr (pexpr_of_pos_num α h_one h_add m)\nend\n\nmeta def expr_of_znum (α : expr) (n : znum) : tactic expr :=\nmatch n with\n| znum.zero := do\n h_zero ← mk_app `has_zero [α] >>= mk_instance,\n to_expr ``(@has_zero.zero %%α %%h_zero)\n| (znum.pos n) :=\n expr_of_num α (num.pos n)\n| (znum.neg n) := do\n h_neg ← mk_app `has_neg [α] >>= mk_instance,\n e ← expr_of_num α (num.pos n),\n to_expr ``(@has_neg.neg %%α %%h_neg %%e)\nend\n\nmeta def expr_of_rat (α : expr) (q : ℚ) : tactic expr :=\nlet n : znum := q.num in\nlet d : znum := q.denom in\nif d = 1 then\n expr_of_znum α n\nelse do\n a ← expr_of_znum α n,\n b ← expr_of_znum α d,\n to_expr ``(%%a / %%b)\n\nend tactic\n\nnamespace rat\n\nopen polya.field\n\ninstance : const_space ℚ :=\n{ df := by apply_instance,\n lt := (<),\n dec := by apply_instance,\n}\n\ninstance {α} [discrete_field α] [char_zero α] : morph ℚ α :=\n{ cast := by apply_instance,\n morph_zero := rat.cast_zero,\n morph_one := rat.cast_one,\n morph_add := rat.cast_add,\n morph_neg := rat.cast_neg,\n morph_mul := rat.cast_mul,\n morph_inv := rat.cast_inv,\n morph_inj := begin\n intros a ha,\n apply rat.cast_inj.mp,\n { rw rat.cast_zero, apply ha },\n { resetI, apply_instance }\n end,\n}\n\nend rat\n\nnamespace list\n\ndef pall {α : Type*} (l : list α) (f : α → Prop) : Prop :=\nl.foldr (λ a r, f a ∧ r) true\n\ntheorem pall_iff_forall_prop :\n ∀ {α : Type*} {p : α → Prop} [_inst_1 : decidable_pred p] {l : list α},\n list.pall l p ↔ ∀ (a : α), a ∈ l → p a :=\nbegin\n intros,\n apply iff.trans, swap,\n { exact @list.all_iff_forall_prop _ _ _inst_1 _ },\n { unfold pall, induction l with x xs ih,\n { simp },\n { simp [ih] }}\nend\n\nopen polya.field tactic\n\nmeta def expr_reflect (type : expr) : list expr → tactic expr\n| [] := to_expr ``([] : list %%type)\n| (h::t) := do e ← expr_reflect t, to_expr ``(list.cons (%%h : %%type) %%e)\n\ndef to_dict {α} [inhabited α] (l : list α) : dict α :=\n⟨λ i, list.func.get i l.reverse⟩\n\nend list\n\n--namespace finmap\n--open field\n--\n--def to_dict {α} [discrete_field α] (m : finmap (λ _ : num, α)) : dict α :=\n--⟨λ i, match finmap.lookup i m with (some x) := x | _ := 0 end⟩\n--\n--end finmap\n\nnamespace tactic\nopen native tactic\n\nnamespace polya.field\nopen polya.field polya.field.term\n\nmeta structure cache_ty :=\n( new_atom : num )\n( atoms : rb_map expr num )\n( dict : rb_map num expr )\n\nmeta instance : has_emptyc cache_ty :=\n⟨⟨0, rb_map.mk _ _, rb_map.mk _ _⟩⟩\n\nmeta def state_dict : Type → Type := state_t cache_ty tactic\n\nnamespace state_dict\nmeta instance : monad state_dict := state_t.monad\nmeta instance : monad_state cache_ty state_dict := state_t.monad_state\nmeta instance : alternative state_dict := state_t.alternative\nmeta instance {α} : has_coe (tactic α) (state_dict α) := ⟨state_t.lift⟩\nend state_dict\n\nmeta def get_atom (e : expr) : state_dict num :=\nget >>= λ s,\nmatch s.atoms.find e with\n| (some i) := return i\n| none := do\n let i := s.new_atom,\n put ⟨i + 1, s.atoms.insert e i, s.dict.insert i e⟩,\n return i\nend\n\nmeta def cache_ty.dict_expr (α : expr) (s : cache_ty) : tactic expr :=\ndo\n e ← s.dict.values.expr_reflect α,\n mk_app `list.to_dict [e]\n\nmeta def term_of_expr : expr → state_dict term | e :=\nmatch e with\n| `(%%a + %%b) := do y ← term_of_expr b, x ← term_of_expr a, return (add x y)\n| `(%%a - %%b) := do y ← term_of_expr b, x ← term_of_expr a, return (sub x y)\n| `(%%a * %%b) := do y ← term_of_expr b, x ← term_of_expr a, return (mul x y)\n| `(%%a / %%b) := do y ← term_of_expr b, x ← term_of_expr a, return (div x y)\n| `(-%%a) := do x ← term_of_expr a, return (neg x)\n| `((%%a)⁻¹) := do x ← term_of_expr a, return (inv x)\n| `(%%a ^ %%b) := do x ← term_of_expr a, ( (do n ← b.to_nat, return (pow_nat x n)) <|> (do n ← b.to_int, return (pow_int x n)) )\n| _ := do n ← e.to_nat, return (numeral n)\nend <|> do i ← get_atom e, return (atom i)\n\n--TODO: more generic\n@[reducible] def α := ℚ\n@[reducible] def γ := ℚ\n\nmeta def nterm_to_expr (s : cache_ty) : nterm γ → tactic expr\n| (nterm.atom i) := s.dict.find i\n| (nterm.const c) := expr_of_rat `(α) c\n| (nterm.add x y) := do a ← nterm_to_expr x, b ← nterm_to_expr y, to_expr ``(%%a + %%b)\n| (nterm.mul x y) := do a ← nterm_to_expr x, b ← nterm_to_expr y, to_expr ``(%%a * %%b)\n| (nterm.pow x n) := do a ← nterm_to_expr x, b ← expr_of_znum `(ℤ) n, to_expr ``(%%a ^ %%b)\n\nmeta def prove_norm_hyps (t : term) (s : cache_ty) : tactic (list expr × expr) :=\ndo\n let t_expr : expr := reflect t,\n ρ ← s.dict_expr `(α),\n\n let nhyps := norm_hyps γ t,\n nhyps ← monad.mapm (nterm_to_expr s) nhyps,\n nhyps ← monad.mapm (λ e, to_expr ``(%%e ≠ 0)) nhyps,\n mvars ← monad.mapm mk_meta_var nhyps,\n\n h ← to_expr ``(∀ x ∈ norm_hyps γ %%t_expr, nterm.eval %%ρ x ≠ 0),\n pe ← to_expr ( mvars.foldr (λ e pe, ``((and.intro %%e %%pe))) ``(trivial) ) tt ff,\n ((), pr) ← solve_aux h (refine ``(list.pall_iff_forall_prop.mp _) >> exact pe >> done),\n\n return (mvars, pr)\n\n-- norm_expr e s = (new_e, pr, mv, mvs, new_s)\n-- new_e is the canonized expression\n-- pr is a proof that e = new_e\n-- mv is a meta-variable to prove by reflexivity\n-- mvs are neta-variables for the nonzero hypothesis made by the normalizer\n-- new_s is the updated cache\nmeta def norm_expr (e : expr) (s : cache_ty) :\n tactic (expr × expr × expr × list expr × cache_ty) :=\ndo\n (t, s) ← (term_of_expr e).run s,\n let t_expr : expr := reflect t,\n let norm_t := norm γ t,\n norm_t_expr ← to_expr ``(norm γ %%t_expr),\n ρ_expr ← s.dict_expr `(α),\n\n (mvars, pr0) ← prove_norm_hyps t s,\n\n --reflexivity from expr to term\n h1 ← to_expr ``(%%e = term.eval %%ρ_expr %%t_expr),\n ((), pr1) ← solve_aux h1 `[refl, done],\n\n --correctness theorem\n --h2 ← to_expr ``(term.eval %%ρ_expr %%t_expr = nterm.eval %%ρ_expr %%norm_t_expr),\n pr2 ← mk_app `polya.field.correctness [pr0],\n\n --reflexivity from nterm to expr\n new_e ← nterm_to_expr s norm_t,\n h3 ← to_expr ``(nterm.eval %%ρ_expr %%norm_t_expr = %%new_e),\n pr3 ← mk_meta_var h3, --heavy computation in the kernel\n\n pr ← mk_eq_trans pr2 pr3 >>= mk_eq_trans pr1,\n return (new_e, pr, pr3, mvars, s)\n\nend polya.field\n\nmeta def prove_by_reflexivity (mvs : list expr) : tactic unit :=\ndo\n gs ← get_goals,\n set_goals mvs,\n all_goals reflexivity,\n set_goals gs\n\nend tactic\n\nopen tactic interactive interactive.types lean.parser\nopen tactic.polya.field\n\nmeta def tactic.interactive.field1 : tactic unit :=\ndo\n `(%%e1 = %%e2) ← target,\n\n (new_e1, pr1, mv1, mvs, s) ← norm_expr e1 ∅,\n (new_e2, pr2, mv2, mvs', s) ← norm_expr e2 s,\n\n ( do\n unify new_e1 new_e2,\n prove_by_reflexivity [mv1, mv2],\n gs ← get_goals,\n set_goals (gs ++ mvs ++ mvs'),\n pr ← mk_eq_symm pr2 >>= mk_eq_trans pr1,\n tactic.exact pr\n ) <|> ( do\n prove_by_reflexivity [mv1, mv2],\n pr0 ← to_expr ``(%%new_e1 = %%new_e2) >>= mk_meta_var,\n gs ← get_goals,\n set_goals (gs ++ [pr0] ++ mvs ++ mvs'),\n pr ← mk_eq_symm pr2 >>= mk_eq_trans pr0 >>= mk_eq_trans pr1,\n tactic.exact pr\n )\n", "meta": {"author": "lean-forward", "repo": "field", "sha": "7e2127ad485aec25e58a1b9c82a6bb74a599467a", "save_path": "github-repos/lean/lean-forward-field", "path": "github-repos/lean/lean-forward-field/field-7e2127ad485aec25e58a1b9c82a6bb74a599467a/src/tactic/polya/field/main.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.05582314152731158, "lm_q1q2_score": 0.02791157076365579}} {"text": "/-\nCopyright (c) 2019 Scott Morrison. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Scott Morrison, Bhavik Mehta, Adam Topaz\n-/\nimport category_theory.functor_category\nimport category_theory.fully_faithful\n\nnamespace category_theory\nopen category\n\nuniverses v₁ u₁ -- morphism levels before object levels. See note [category_theory universes].\n\nvariables (C : Type u₁) [category.{v₁} C]\n\n/--\nThe data of a monad on C consists of an endofunctor T together with natural transformations\nη : 𝟭 C ⟶ T and μ : T ⋙ T ⟶ T satisfying three equations:\n- T μ_X ≫ μ_X = μ_(TX) ≫ μ_X (associativity)\n- η_(TX) ≫ μ_X = 1_X (left unit)\n- Tη_X ≫ μ_X = 1_X (right unit)\n-/\nstructure monad extends C ⥤ C :=\n(η' [] : 𝟭 _ ⟶ to_functor)\n(μ' [] : to_functor ⋙ to_functor ⟶ to_functor)\n(assoc' : ∀ X, to_functor.map (nat_trans.app μ' X) ≫ μ'.app _ = μ'.app _ ≫ μ'.app _ . obviously)\n(left_unit' : ∀ X : C, η'.app (to_functor.obj X) ≫ μ'.app _ = 𝟙 _ . obviously)\n(right_unit' : ∀ X : C, to_functor.map (η'.app X) ≫ μ'.app _ = 𝟙 _ . obviously)\n\n/--\nThe data of a comonad on C consists of an endofunctor G together with natural transformations\nε : G ⟶ 𝟭 C and δ : G ⟶ G ⋙ G satisfying three equations:\n- δ_X ≫ G δ_X = δ_X ≫ δ_(GX) (coassociativity)\n- δ_X ≫ ε_(GX) = 1_X (left counit)\n- δ_X ≫ G ε_X = 1_X (right counit)\n-/\nstructure comonad extends C ⥤ C :=\n(ε' [] : to_functor ⟶ 𝟭 _)\n(δ' [] : to_functor ⟶ to_functor ⋙ to_functor)\n(coassoc' : ∀ X, nat_trans.app δ' _ ≫ to_functor.map (δ'.app X) = δ'.app _ ≫ δ'.app _ . obviously)\n(left_counit' : ∀ X : C, δ'.app X ≫ ε'.app (to_functor.obj X) = 𝟙 _ . obviously)\n(right_counit' : ∀ X : C, δ'.app X ≫ to_functor.map (ε'.app X) = 𝟙 _ . obviously)\n\nvariables {C} (T : monad C) (G : comonad C)\n\ninstance coe_monad : has_coe (monad C) (C ⥤ C) := ⟨λ T, T.to_functor⟩\ninstance coe_comonad : has_coe (comonad C) (C ⥤ C) := ⟨λ G, G.to_functor⟩\n\n@[simp] lemma monad_to_functor_eq_coe : T.to_functor = T := rfl\n@[simp] lemma comonad_to_functor_eq_coe : G.to_functor = G := rfl\n\n/-- The unit for the monad `T`. -/\ndef monad.η : 𝟭 _ ⟶ (T : C ⥤ C) := T.η'\n/-- The multiplication for the monad `T`. -/\ndef monad.μ : (T : C ⥤ C) ⋙ (T : C ⥤ C) ⟶ T := T.μ'\n\n/-- The counit for the comonad `G`. -/\ndef comonad.ε : (G : C ⥤ C) ⟶ 𝟭 _ := G.ε'\n/-- The comultiplication for the comonad `G`. -/\ndef comonad.δ : (G : C ⥤ C) ⟶ (G : C ⥤ C) ⋙ G := G.δ'\n\n/-- A custom simps projection for the functor part of a monad, as a coercion. -/\ndef monad.simps.coe := (T : C ⥤ C)\n/-- A custom simps projection for the unit of a monad, in simp normal form. -/\ndef monad.simps.η : 𝟭 _ ⟶ (T : C ⥤ C) := T.η\n/-- A custom simps projection for the multiplication of a monad, in simp normal form. -/\ndef monad.simps.μ : (T : C ⥤ C) ⋙ (T : C ⥤ C) ⟶ (T : C ⥤ C) := T.μ\n\n/-- A custom simps projection for the functor part of a comonad, as a coercion. -/\ndef comonad.simps.coe := (G : C ⥤ C)\n/-- A custom simps projection for the counit of a comonad, in simp normal form. -/\ndef comonad.simps.ε : (G : C ⥤ C) ⟶ 𝟭 _ := G.ε\n/-- A custom simps projection for the comultiplication of a comonad, in simp normal form. -/\ndef comonad.simps.δ : (G : C ⥤ C) ⟶ (G : C ⥤ C) ⋙ (G : C ⥤ C) := G.δ\n\ninitialize_simps_projections category_theory.monad (to_functor → coe, η' → η, μ' → μ)\ninitialize_simps_projections category_theory.comonad (to_functor → coe, ε' → ε, δ' → δ)\n\n@[reassoc]\nlemma monad.assoc (T : monad C) (X : C) :\n (T : C ⥤ C).map (T.μ.app X) ≫ T.μ.app _ = T.μ.app _ ≫ T.μ.app _ :=\nT.assoc' X\n\n@[simp, reassoc] lemma monad.left_unit (T : monad C) (X : C) :\n T.η.app ((T : C ⥤ C).obj X) ≫ T.μ.app X = 𝟙 ((T : C ⥤ C).obj X) :=\nT.left_unit' X\n\n@[simp, reassoc] lemma monad.right_unit (T : monad C) (X : C) :\n (T : C ⥤ C).map (T.η.app X) ≫ T.μ.app X = 𝟙 ((T : C ⥤ C).obj X) :=\nT.right_unit' X\n\n@[reassoc]\nlemma comonad.coassoc (G : comonad C) (X : C) :\n G.δ.app _ ≫ (G : C ⥤ C).map (G.δ.app X) = G.δ.app _ ≫ G.δ.app _ :=\nG.coassoc' X\n\n@[simp, reassoc] lemma comonad.left_counit (G : comonad C) (X : C) :\n G.δ.app X ≫ G.ε.app ((G : C ⥤ C).obj X) = 𝟙 ((G : C ⥤ C).obj X) :=\nG.left_counit' X\n\n@[simp, reassoc] lemma comonad.right_counit (G : comonad C) (X : C) :\n G.δ.app X ≫ (G : C ⥤ C).map (G.ε.app X) = 𝟙 ((G : C ⥤ C).obj X) :=\nG.right_counit' X\n\n/-- A morphism of monads is a natural transformation compatible with η and μ. -/\n@[ext]\nstructure monad_hom (T₁ T₂ : monad C) extends nat_trans (T₁ : C ⥤ C) T₂ :=\n(app_η' : ∀ {X}, T₁.η.app X ≫ app X = T₂.η.app X . obviously)\n(app_μ' : ∀ {X}, T₁.μ.app X ≫ app X = ((T₁ : C ⥤ C).map (app X) ≫ app _) ≫ T₂.μ.app X . obviously)\n\n/-- A morphism of comonads is a natural transformation compatible with ε and δ. -/\n@[ext]\nstructure comonad_hom (M N : comonad C) extends nat_trans (M : C ⥤ C) N :=\n(app_ε' : ∀ {X}, app X ≫ N.ε.app X = M.ε.app X . obviously)\n(app_δ' : ∀ {X}, app X ≫ N.δ.app X = M.δ.app X ≫ app (M.obj X) ≫ N.map (app X) . obviously)\n\nrestate_axiom monad_hom.app_η'\nrestate_axiom monad_hom.app_μ'\nattribute [simp, reassoc] monad_hom.app_η monad_hom.app_μ\n\nrestate_axiom comonad_hom.app_ε'\nrestate_axiom comonad_hom.app_δ'\nattribute [simp, reassoc] comonad_hom.app_ε comonad_hom.app_δ\n\ninstance : category (monad C) :=\n{ hom := monad_hom,\n id := λ M, { to_nat_trans := 𝟙 (M : C ⥤ C) },\n comp := λ _ _ _ f g,\n { to_nat_trans := { app := λ X, f.app X ≫ g.app X } } }\n\ninstance : category (comonad C) :=\n{ hom := comonad_hom,\n id := λ M, { to_nat_trans := 𝟙 (M : C ⥤ C) },\n comp := λ M N L f g,\n { to_nat_trans := { app := λ X, f.app X ≫ g.app X } } }\n\ninstance {T : monad C} : inhabited (monad_hom T T) := ⟨𝟙 T⟩\n\n@[simp] \n\ninstance {G : comonad C} : inhabited (comonad_hom G G) := ⟨𝟙 G⟩\n\n@[simp] lemma comonad_hom.id_to_nat_trans (T : comonad C) :\n (𝟙 T : T ⟶ T).to_nat_trans = 𝟙 (T : C ⥤ C) :=\nrfl\n@[simp] lemma comp_to_nat_trans {T₁ T₂ T₃ : comonad C} (f : T₁ ⟶ T₂) (g : T₂ ⟶ T₃) :\n (f ≫ g).to_nat_trans =\n ((f.to_nat_trans : _ ⟶ (T₂ : C ⥤ C)) ≫ g.to_nat_trans : (T₁ : C ⥤ C) ⟶ T₃) :=\nrfl\n\nvariable (C)\n\n/--\nThe forgetful functor from the category of monads to the category of endofunctors.\n-/\n@[simps]\ndef monad_to_functor : monad C ⥤ (C ⥤ C) :=\n{ obj := λ T, T,\n map := λ M N f, f.to_nat_trans }\n\ninstance : faithful (monad_to_functor C) := {}.\n\n/--\nThe forgetful functor from the category of comonads to the category of endofunctors.\n-/\n@[simps]\ndef comonad_to_functor : comonad C ⥤ (C ⥤ C) :=\n{ obj := λ G, G,\n map := λ M N f, f.to_nat_trans }\n\ninstance : faithful (comonad_to_functor C) := {}.\n\nvariable {C}\n\n/--\nAn isomorphism of monads gives a natural isomorphism of the underlying functors.\n-/\n@[simps {rhs_md := semireducible}]\ndef monad_iso.to_nat_iso {M N : monad C} (h : M ≅ N) : (M : C ⥤ C) ≅ N :=\n(monad_to_functor C).map_iso h\n\n/--\nAn isomorphism of comonads gives a natural isomorphism of the underlying functors.\n-/\n@[simps {rhs_md := semireducible}]\ndef comonad_iso.to_nat_iso {M N : comonad C} (h : M ≅ N) : (M : C ⥤ C) ≅ N :=\n(comonad_to_functor C).map_iso h\n\nvariable (C)\n\nnamespace monad\n\n/-- The identity monad. -/\n@[simps]\ndef id : monad C :=\n{ to_functor := 𝟭 C,\n η' := 𝟙 (𝟭 C),\n μ' := 𝟙 (𝟭 C) }\n\ninstance : inhabited (monad C) := ⟨monad.id C⟩\n\nend monad\n\nnamespace comonad\n\n/-- The identity comonad. -/\n@[simps]\ndef id : comonad C :=\n{ to_functor := 𝟭 _,\n ε' := 𝟙 (𝟭 C),\n δ' := 𝟙 (𝟭 C) }\n\ninstance : inhabited (comonad C) := ⟨comonad.id C⟩\n\nend comonad\n\nend category_theory\n", "meta": {"author": "JLimperg", "repo": "aesop3", "sha": "a4a116f650cc7403428e72bd2e2c4cda300fe03f", "save_path": "github-repos/lean/JLimperg-aesop3", "path": "github-repos/lean/JLimperg-aesop3/aesop3-a4a116f650cc7403428e72bd2e2c4cda300fe03f/src/category_theory/monad/basic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4921881357207955, "lm_q2_score": 0.056652428891601526, "lm_q1q2_score": 0.02788365336021229}} {"text": "/-\nCopyright (c) 2018 Mario Carneiro. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthor: Mario Carneiro\n\nAdditional equiv and encodable instances for lists, finsets, and fintypes.\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.default\nimport Mathlib.data.equiv.denumerable\nimport Mathlib.data.finset.sort\nimport Mathlib.PostPort\n\nuniverses u_1 u_2 \n\nnamespace Mathlib\n\nnamespace encodable\n\n\ndef encode_list {α : Type u_1} [encodable α] : List α → ℕ :=\n sorry\n\ndef decode_list {α : Type u_1} [encodable α] : ℕ → Option (List α) :=\n sorry\n\nprotected instance list {α : Type u_1} [encodable α] : encodable (List α) :=\n mk encode_list decode_list sorry\n\n@[simp] theorem encode_list_nil {α : Type u_1} [encodable α] : encode [] = 0 :=\n rfl\n\n@[simp] theorem encode_list_cons {α : Type u_1} [encodable α] (a : α) (l : List α) : encode (a :: l) = Nat.succ (nat.mkpair (encode a) (encode l)) :=\n rfl\n\n@[simp] theorem decode_list_zero {α : Type u_1} [encodable α] : decode (List α) 0 = some [] :=\n rfl\n\n@[simp] theorem decode_list_succ {α : Type u_1} [encodable α] (v : ℕ) : decode (List α) (Nat.succ v) =\n (fun (_x : α) (_y : List α) => _x :: _y) <$> decode α (prod.fst (nat.unpair v)) <*>\n decode (List α) (prod.snd (nat.unpair v)) := sorry\n\ntheorem length_le_encode {α : Type u_1} [encodable α] (l : List α) : list.length l ≤ encode l := sorry\n\ndef encode_multiset {α : Type u_1} [encodable α] (s : multiset α) : ℕ :=\n encode (multiset.sort enle s)\n\ndef decode_multiset {α : Type u_1} [encodable α] (n : ℕ) : Option (multiset α) :=\n coe <$> decode (List α) n\n\nprotected instance multiset {α : Type u_1} [encodable α] : encodable (multiset α) :=\n mk encode_multiset decode_multiset sorry\n\ndef encodable_of_list {α : Type u_1} [DecidableEq α] (l : List α) (H : ∀ (x : α), x ∈ l) : encodable α :=\n mk (fun (a : α) => list.index_of a l) (list.nth l) sorry\n\ndef trunc_encodable_of_fintype (α : Type u_1) [DecidableEq α] [fintype α] : trunc (encodable α) :=\n quot.rec_on_subsingleton (finset.val finset.univ)\n (fun (l : List α) (H : ∀ (x : α), x ∈ Quot.mk setoid.r l) => trunc.mk (encodable_of_list l H)) finset.mem_univ\n\n/-- A noncomputable way to arbitrarily choose an ordering on a finite type.\n It is not made into a global instance, since it involves an arbitrary choice.\n This can be locally made into an instance with `local attribute [instance] fintype.encodable`. -/\ndef fintype.encodable (α : Type u_1) [fintype α] : encodable α :=\n trunc.out (trunc_encodable_of_fintype α)\n\nprotected instance vector {α : Type u_1} [encodable α] {n : ℕ} : encodable (vector α n) :=\n encodable.subtype\n\nprotected instance fin_arrow {α : Type u_1} [encodable α] {n : ℕ} : encodable (fin n → α) :=\n of_equiv (vector α n) (equiv.symm (equiv.vector_equiv_fin α n))\n\nprotected instance fin_pi (n : ℕ) (π : fin n → Type u_1) [(i : fin n) → encodable (π i)] : encodable ((i : fin n) → π i) :=\n of_equiv (↥(set_of fun (f : fin n → sigma fun (i : fin n) => π i) => ∀ (i : fin n), sigma.fst (f i) = i))\n (equiv.pi_equiv_subtype_sigma (fin n) π)\n\nprotected instance array {α : Type u_1} [encodable α] {n : ℕ} : encodable (array n α) :=\n of_equiv (fin n → α) (equiv.array_equiv_fin n α)\n\nprotected instance finset {α : Type u_1} [encodable α] : encodable (finset α) :=\n of_equiv (Subtype fun (s : multiset α) => multiset.nodup s)\n (equiv.mk (fun (_x : finset α) => sorry) (fun (_x : Subtype fun (s : multiset α) => multiset.nodup s) => sorry) sorry\n sorry)\n\ndef fintype_arrow (α : Type u_1) (β : Type u_2) [DecidableEq α] [fintype α] [encodable β] : trunc (encodable (α → β)) :=\n trunc.map\n (fun (f : α ≃ fin (fintype.card α)) => of_equiv (fin (fintype.card α) → β) (equiv.arrow_congr f (equiv.refl β)))\n (fintype.equiv_fin α)\n\ndef fintype_pi (α : Type u_1) (π : α → Type u_2) [DecidableEq α] [fintype α] [(a : α) → encodable (π a)] : trunc (encodable ((a : α) → π a)) :=\n trunc.bind (trunc_encodable_of_fintype α)\n fun (a : encodable α) =>\n trunc.bind (fintype_arrow α (sigma fun (a : α) => π a))\n fun (f : encodable (α → sigma fun (a : α) => π a)) =>\n trunc.mk\n (of_equiv\n (Subtype\n fun (a : α → sigma fun (a : α) => π a) =>\n a ∈ set_of fun (f : α → sigma fun (a : α) => π a) => ∀ (i : α), sigma.fst (f i) = i)\n (equiv.pi_equiv_subtype_sigma α π))\n\n/-- The elements of a `fintype` as a sorted list. -/\ndef sorted_univ (α : Type u_1) [fintype α] [encodable α] : List α :=\n finset.sort (⇑(encode' α) ⁻¹'o LessEq) finset.univ\n\ntheorem mem_sorted_univ {α : Type u_1} [fintype α] [encodable α] (x : α) : x ∈ sorted_univ α :=\n iff.mpr (finset.mem_sort (⇑(encode' α) ⁻¹'o LessEq)) (finset.mem_univ x)\n\ntheorem length_sorted_univ {α : Type u_1} [fintype α] [encodable α] : list.length (sorted_univ α) = fintype.card α :=\n finset.length_sort (⇑(encode' α) ⁻¹'o LessEq)\n\ntheorem sorted_univ_nodup {α : Type u_1} [fintype α] [encodable α] : list.nodup (sorted_univ α) :=\n finset.sort_nodup (⇑(encode' α) ⁻¹'o LessEq) finset.univ\n\n/-- An encodable `fintype` is equivalent a `fin`.-/\ndef fintype_equiv_fin {α : Type u_1} [fintype α] [encodable α] : α ≃ fin (fintype.card α) :=\n equiv.trans (fintype.equiv_fin_of_forall_mem_list mem_sorted_univ sorted_univ_nodup) (equiv.cast sorry)\n\nprotected instance fintype_arrow_of_encodable {α : Type u_1} {β : Type u_2} [encodable α] [fintype α] [encodable β] : encodable (α → β) :=\n of_equiv (fin (fintype.card α) → β) (equiv.arrow_congr fintype_equiv_fin (equiv.refl β))\n\nend encodable\n\n\nnamespace denumerable\n\n\ntheorem denumerable_list_aux {α : Type u_1} [denumerable α] (n : ℕ) : ∃ (a : List α), ∃ (H : a ∈ encodable.decode_list n), encodable.encode_list a = n := sorry\n\nprotected instance denumerable_list {α : Type u_1} [denumerable α] : denumerable (List α) :=\n mk denumerable_list_aux\n\n@[simp] theorem list_of_nat_zero {α : Type u_1} [denumerable α] : of_nat (List α) 0 = [] :=\n rfl\n\n@[simp] theorem list_of_nat_succ {α : Type u_1} [denumerable α] (v : ℕ) : of_nat (List α) (Nat.succ v) = of_nat α (prod.fst (nat.unpair v)) :: of_nat (List α) (prod.snd (nat.unpair v)) := sorry\n\ndef lower : List ℕ → ℕ → List ℕ :=\n sorry\n\ndef raise : List ℕ → ℕ → List ℕ :=\n sorry\n\ntheorem lower_raise (l : List ℕ) (n : ℕ) : lower (raise l n) n = l := sorry\n\ntheorem raise_lower {l : List ℕ} {n : ℕ} : list.sorted LessEq (n :: l) → raise (lower l n) n = l := sorry\n\ntheorem raise_chain (l : List ℕ) (n : ℕ) : list.chain LessEq n (raise l n) := sorry\n\ntheorem raise_sorted (l : List ℕ) (n : ℕ) : list.sorted LessEq (raise l n) := sorry\n\n/- Warning: this is not the same encoding as used in `encodable` -/\n\nprotected instance multiset {α : Type u_1} [denumerable α] : denumerable (multiset α) :=\n mk'\n (equiv.mk\n (fun (s : multiset α) => encodable.encode (lower (multiset.sort LessEq (multiset.map encodable.encode s)) 0))\n (fun (n : ℕ) => multiset.map (of_nat α) ↑(raise (of_nat (List ℕ) n) 0)) sorry sorry)\n\ndef lower' : List ℕ → ℕ → List ℕ :=\n sorry\n\ndef raise' : List ℕ → ℕ → List ℕ :=\n sorry\n\ntheorem lower_raise' (l : List ℕ) (n : ℕ) : lower' (raise' l n) n = l := sorry\n\ntheorem raise_lower' {l : List ℕ} {n : ℕ} : (∀ (m : ℕ), m ∈ l → n ≤ m) → list.sorted Less l → raise' (lower' l n) n = l := sorry\n\ntheorem raise'_chain (l : List ℕ) {m : ℕ} {n : ℕ} : m < n → list.chain Less m (raise' l n) := sorry\n\ntheorem raise'_sorted (l : List ℕ) (n : ℕ) : list.sorted Less (raise' l n) := sorry\n\ndef raise'_finset (l : List ℕ) (n : ℕ) : finset ℕ :=\n finset.mk ↑(raise' l n) sorry\n\n/- Warning: this is not the same encoding as used in `encodable` -/\n\nprotected instance finset {α : Type u_1} [denumerable α] : denumerable (finset α) :=\n mk'\n (equiv.mk\n (fun (s : finset α) => encodable.encode (lower' (finset.sort LessEq (finset.map (equiv.to_embedding (eqv α)) s)) 0))\n (fun (n : ℕ) => finset.map (equiv.to_embedding (equiv.symm (eqv α))) (raise'_finset (of_nat (List ℕ) n) 0)) sorry\n sorry)\n\nend denumerable\n\n\nnamespace equiv\n\n\n/-- The type lists on unit is canonically equivalent to the natural numbers. -/\ndef list_unit_equiv : List Unit ≃ ℕ :=\n mk list.length (list.repeat Unit.unit) sorry sorry\n\ndef list_nat_equiv_nat : List ℕ ≃ ℕ :=\n denumerable.eqv (List ℕ)\n\ndef list_equiv_self_of_equiv_nat {α : Type} (e : α ≃ ℕ) : List α ≃ α :=\n equiv.trans (equiv.trans (list_equiv_of_equiv e) list_nat_equiv_nat) (equiv.symm e)\n\n", "meta": {"author": "AurelienSaue", "repo": "Mathlib4_auto", "sha": "590df64109b08190abe22358fabc3eae000943f2", "save_path": "github-repos/lean/AurelienSaue-Mathlib4_auto", "path": "github-repos/lean/AurelienSaue-Mathlib4_auto/Mathlib4_auto-590df64109b08190abe22358fabc3eae000943f2/Mathlib/data/equiv/list.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4571367168274948, "lm_q2_score": 0.06097517958516649, "lm_q1q2_score": 0.027873993403529893}} {"text": "/-\nCopyright (c) 2020 Scott Morrison. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Scott Morrison\n-/\nimport category_theory.category.Cat\nimport category_theory.limits.types\nimport category_theory.limits.preserves.basic\n\n/-!\n# The category of small categories has all small limits.\n\n> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.\n> Any changes to this file require a corresponding PR to mathlib4.\n\nAn object in the limit consists of a family of objects,\nwhich are carried to one another by the functors in the diagram.\nA morphism between two such objects is a family of morphisms between the corresponding objects,\nwhich are carried to one another by the action on morphisms of the functors in the diagram.\n\n## Future work\nCan the indexing category live in a lower universe?\n-/\n\nnoncomputable theory\n\nuniverses v u\n\nopen category_theory.limits\n\nnamespace category_theory\n\nvariables {J : Type v} [small_category J]\n\nnamespace Cat\n\nnamespace has_limits\n\ninstance category_objects {F : J ⥤ Cat.{u u}} {j} :\n small_category ((F ⋙ Cat.objects.{u u}).obj j) :=\n(F.obj j).str\n\n/-- Auxiliary definition:\nthe diagram whose limit gives the morphism space between two objects of the limit category. -/\n@[simps]\ndef hom_diagram {F : J ⥤ Cat.{v v}} (X Y : limit (F ⋙ Cat.objects.{v v})) : J ⥤ Type v :=\n{ obj := λ j, limit.π (F ⋙ Cat.objects) j X ⟶ limit.π (F ⋙ Cat.objects) j Y,\n map := λ j j' f g,\n begin\n refine eq_to_hom _ ≫ (F.map f).map g ≫ eq_to_hom _,\n exact (congr_fun (limit.w (F ⋙ Cat.objects) f) X).symm,\n exact (congr_fun (limit.w (F ⋙ Cat.objects) f) Y),\n end,\n map_id' := λ X, begin\n ext f, dsimp,\n simp [functor.congr_hom (F.map_id X) f],\n end,\n map_comp' := λ X Y Z f g, begin\n ext h, dsimp,\n simp [functor.congr_hom (F.map_comp f g) h, eq_to_hom_map],\n refl,\n end, }\n\n@[simps]\ninstance (F : J ⥤ Cat.{v v}) : category (limit (F ⋙ Cat.objects)) :=\n{ hom := λ X Y, limit (hom_diagram X Y),\n id := λ X, types.limit.mk.{v v} (hom_diagram X X) (λ j, 𝟙 _) (λ j j' f, by simp),\n comp := λ X Y Z f g, types.limit.mk.{v v} (hom_diagram X Z)\n (λ j, limit.π (hom_diagram X Y) j f ≫ limit.π (hom_diagram Y Z) j g)\n (λ j j' h, begin\n rw [←congr_fun (limit.w (hom_diagram X Y) h) f, ←congr_fun (limit.w (hom_diagram Y Z) h) g],\n dsimp,\n simp,\n end),\n id_comp' := λ _ _ _, by { ext, simp only [category.id_comp, types.limit.π_mk'] },\n comp_id' := λ _ _ _, by { ext, simp only [types.limit.π_mk', category.comp_id] } }\n\n/-- Auxiliary definition: the limit category. -/\n@[simps]\ndef limit_cone_X (F : J ⥤ Cat.{v v}) : Cat.{v v} :=\n{ α := limit (F ⋙ Cat.objects), }.\n\n/-- Auxiliary definition: the cone over the limit category. -/\n@[simps]\ndef limit_cone (F : J ⥤ Cat.{v v}) : cone F :=\n{ X := limit_cone_X F,\n π :=\n { app := λ j,\n { obj := limit.π (F ⋙ Cat.objects) j,\n map := λ X Y, limit.π (hom_diagram X Y) j, },\n naturality' := λ j j' f, category_theory.functor.ext\n (λ X, (congr_fun (limit.w (F ⋙ Cat.objects) f) X).symm)\n (λ X Y h, (congr_fun (limit.w (hom_diagram X Y) f) h).symm), } }\n\n/-- Auxiliary definition: the universal morphism to the proposed limit cone. -/\n@[simps]\ndef limit_cone_lift (F : J ⥤ Cat.{v v}) (s : cone F) : s.X ⟶ limit_cone_X F :=\n{ obj := limit.lift (F ⋙ Cat.objects)\n { X := s.X,\n π :=\n { app := λ j, (s.π.app j).obj,\n naturality' := λ j j' f, (congr_arg functor.obj (s.π.naturality f) : _), } },\n map := λ X Y f,\n begin\n fapply types.limit.mk.{v v},\n { intro j,\n refine eq_to_hom _ ≫ (s.π.app j).map f ≫ eq_to_hom _;\n simp, },\n { intros j j' h,\n dsimp,\n simp only [category.assoc, functor.map_comp,\n eq_to_hom_map, eq_to_hom_trans, eq_to_hom_trans_assoc],\n rw [←functor.comp_map],\n have := (s.π.naturality h).symm,\n conv at this { congr, skip, dsimp, simp, },\n erw [functor.congr_hom this f],\n dsimp, simp, },\n end,\n map_id' := λ X, by simp,\n map_comp' := λ X Y Z f g, by simp }\n\n@[simp]\nlemma limit_π_hom_diagram_eq_to_hom {F : J ⥤ Cat.{v v}}\n (X Y : limit (F ⋙ Cat.objects.{v v})) (j : J) (h : X = Y) :\n limit.π (hom_diagram X Y) j (eq_to_hom h) =\n eq_to_hom (congr_arg (limit.π (F ⋙ Cat.objects.{v v}) j) h) :=\nby { subst h, simp, }\n\n/-- Auxiliary definition: the proposed cone is a limit cone. -/\ndef limit_cone_is_limit (F : J ⥤ Cat.{v v}) : is_limit (limit_cone F) :=\n{ lift := limit_cone_lift F,\n fac' := λ s j, category_theory.functor.ext (by tidy) (λ X Y f, types.limit.π_mk _ _ _ _),\n uniq' := λ s m w,\n begin\n symmetry,\n fapply category_theory.functor.ext,\n { intro X,\n ext,\n dsimp, simp only [types.limit.lift_π_apply', ←w j],\n refl, },\n { intros X Y f,\n dsimp, simp [(λ j, functor.congr_hom (w j).symm f)],\n congr, },\n end, }\n\nend has_limits\n\n/-- The category of small categories has all small limits. -/\ninstance : has_limits (Cat.{v v}) :=\n{ has_limits_of_shape := λ J _, by exactI\n { has_limit := λ F, ⟨⟨⟨has_limits.limit_cone F, has_limits.limit_cone_is_limit F⟩⟩⟩, } }\n\ninstance : preserves_limits Cat.objects.{v v} :=\n{ preserves_limits_of_shape := λ J _, by exactI\n { preserves_limit := λ F,\n preserves_limit_of_preserves_limit_cone (has_limits.limit_cone_is_limit F)\n (limits.is_limit.of_iso_limit (limit.is_limit (F ⋙ Cat.objects))\n (cones.ext (by refl) (by tidy))), }}\n\nend Cat\n\nend category_theory\n", "meta": {"author": "leanprover-community", "repo": "mathlib", "sha": "5e526d18cea33550268dcbbddcb822d5cde40654", "save_path": "github-repos/lean/leanprover-community-mathlib", "path": "github-repos/lean/leanprover-community-mathlib/mathlib-5e526d18cea33550268dcbbddcb822d5cde40654/src/category_theory/category/Cat/limit.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4571367020358429, "lm_q2_score": 0.06097518086496481, "lm_q1q2_score": 0.02787399308664905}} {"text": "/-\nCopyright (c) 2018 Mario Carneiro. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthor: Mario Carneiro\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.default\nimport Mathlib.algebra.order\nimport Mathlib.data.fintype.basic\nimport Mathlib.data.pfun\nimport Mathlib.tactic.apply_fun\nimport Mathlib.logic.function.iterate\nimport Mathlib.PostPort\n\nuniverses u_1 u_2 u v l u_3 u_4 \n\nnamespace Mathlib\n\n/-!\n# Turing machines\n\nThis file defines a sequence of simple machine languages, starting with Turing machines and working\nup to more complex languages based on Wang B-machines.\n\n## Naming conventions\n\nEach model of computation in this file shares a naming convention for the elements of a model of\ncomputation. These are the parameters for the language:\n\n* `Γ` is the alphabet on the tape.\n* `Λ` is the set of labels, or internal machine states.\n* `σ` is the type of internal memory, not on the tape. This does not exist in the TM0 model, and\n later models achieve this by mixing it into `Λ`.\n* `K` is used in the TM2 model, which has multiple stacks, and denotes the number of such stacks.\n\nAll of these variables denote \"essentially finite\" types, but for technical reasons it is\nconvenient to allow them to be infinite anyway. When using an infinite type, we will be interested\nto prove that only finitely many values of the type are ever interacted with.\n\nGiven these parameters, there are a few common structures for the model that arise:\n\n* `stmt` is the set of all actions that can be performed in one step. For the TM0 model this set is\n finite, and for later models it is an infinite inductive type representing \"possible program\n texts\".\n* `cfg` is the set of instantaneous configurations, that is, the state of the machine together with\n its environment.\n* `machine` is the set of all machines in the model. Usually this is approximately a function\n `Λ → stmt`, although different models have different ways of halting and other actions.\n* `step : cfg → option cfg` is the function that describes how the state evolves over one step.\n If `step c = none`, then `c` is a terminal state, and the result of the computation is read off\n from `c`. Because of the type of `step`, these models are all deterministic by construction.\n* `init : input → cfg` sets up the initial state. The type `input` depends on the model;\n in most cases it is `list Γ`.\n* `eval : machine → input → roption output`, given a machine `M` and input `i`, starts from\n `init i`, runs `step` until it reaches an output, and then applies a function `cfg → output` to\n the final state to obtain the result. The type `output` depends on the model.\n* `supports : machine → finset Λ → Prop` asserts that a machine `M` starts in `S : finset Λ`, and\n can only ever jump to other states inside `S`. This implies that the behavior of `M` on any input\n cannot depend on its values outside `S`. We use this to allow `Λ` to be an infinite set when\n convenient, and prove that only finitely many of these states are actually accessible. This\n formalizes \"essentially finite\" mentioned above.\n-/\n\nnamespace turing\n\n\n/-- The `blank_extends` partial order holds of `l₁` and `l₂` if `l₂` is obtained by adding\nblanks (`default Γ`) to the end of `l₁`. -/\ndef blank_extends {Γ : Type u_1} [Inhabited Γ] (l₁ : List Γ) (l₂ : List Γ) :=\n ∃ (n : ℕ), l₂ = l₁ ++ list.repeat Inhabited.default n\n\ntheorem blank_extends.refl {Γ : Type u_1} [Inhabited Γ] (l : List Γ) : blank_extends l l := sorry\n\ntheorem blank_extends.trans {Γ : Type u_1} [Inhabited Γ] {l₁ : List Γ} {l₂ : List Γ} {l₃ : List Γ} : blank_extends l₁ l₂ → blank_extends l₂ l₃ → blank_extends l₁ l₃ := sorry\n\ntheorem blank_extends.below_of_le {Γ : Type u_1} [Inhabited Γ] {l : List Γ} {l₁ : List Γ} {l₂ : List Γ} : blank_extends l l₁ → blank_extends l l₂ → list.length l₁ ≤ list.length l₂ → blank_extends l₁ l₂ := sorry\n\n/-- Any two extensions by blank `l₁,l₂` of `l` have a common join (which can be taken to be the\nlonger of `l₁` and `l₂`). -/\ndef blank_extends.above {Γ : Type u_1} [Inhabited Γ] {l : List Γ} {l₁ : List Γ} {l₂ : List Γ} (h₁ : blank_extends l l₁) (h₂ : blank_extends l l₂) : Subtype fun (l' : List Γ) => blank_extends l₁ l' ∧ blank_extends l₂ l' :=\n dite (list.length l₁ ≤ list.length l₂) (fun (h : list.length l₁ ≤ list.length l₂) => { val := l₂, property := sorry })\n fun (h : ¬list.length l₁ ≤ list.length l₂) => { val := l₁, property := sorry }\n\ntheorem blank_extends.above_of_le {Γ : Type u_1} [Inhabited Γ] {l : List Γ} {l₁ : List Γ} {l₂ : List Γ} : blank_extends l₁ l → blank_extends l₂ l → list.length l₁ ≤ list.length l₂ → blank_extends l₁ l₂ := sorry\n\n/-- `blank_rel` is the symmetric closure of `blank_extends`, turning it into an equivalence\nrelation. Two lists are related by `blank_rel` if one extends the other by blanks. -/\ndef blank_rel {Γ : Type u_1} [Inhabited Γ] (l₁ : List Γ) (l₂ : List Γ) :=\n blank_extends l₁ l₂ ∨ blank_extends l₂ l₁\n\ntheorem blank_rel.refl {Γ : Type u_1} [Inhabited Γ] (l : List Γ) : blank_rel l l :=\n Or.inl (blank_extends.refl l)\n\ntheorem blank_rel.symm {Γ : Type u_1} [Inhabited Γ] {l₁ : List Γ} {l₂ : List Γ} : blank_rel l₁ l₂ → blank_rel l₂ l₁ :=\n or.symm\n\ntheorem blank_rel.trans {Γ : Type u_1} [Inhabited Γ] {l₁ : List Γ} {l₂ : List Γ} {l₃ : List Γ} : blank_rel l₁ l₂ → blank_rel l₂ l₃ → blank_rel l₁ l₃ := sorry\n\n/-- Given two `blank_rel` lists, there exists (constructively) a common join. -/\ndef blank_rel.above {Γ : Type u_1} [Inhabited Γ] {l₁ : List Γ} {l₂ : List Γ} (h : blank_rel l₁ l₂) : Subtype fun (l : List Γ) => blank_extends l₁ l ∧ blank_extends l₂ l :=\n dite (list.length l₁ ≤ list.length l₂) (fun (hl : list.length l₁ ≤ list.length l₂) => { val := l₂, property := sorry })\n fun (hl : ¬list.length l₁ ≤ list.length l₂) => { val := l₁, property := sorry }\n\n/-- Given two `blank_rel` lists, there exists (constructively) a common meet. -/\ndef blank_rel.old_below {Γ : Type u_1} [Inhabited Γ] {l₁ : List Γ} {l₂ : List Γ} (h : blank_rel l₁ l₂) : Subtype fun (l : List Γ) => blank_extends l l₁ ∧ blank_extends l l₂ :=\n dite (list.length l₁ ≤ list.length l₂)\n (fun (hl : list.length l₁ ≤ list.length l₂) => { val := l₁, property := blank_rel.below._proof_1 h hl })\n fun (hl : ¬list.length l₁ ≤ list.length l₂) => { val := l₂, property := blank_rel.below._proof_2 h hl }\n\ntheorem blank_rel.equivalence (Γ : Type u_1) [Inhabited Γ] : equivalence blank_rel :=\n { left := blank_rel.refl, right := { left := blank_rel.symm, right := blank_rel.trans } }\n\n/-- Construct a setoid instance for `blank_rel`. -/\ndef blank_rel.setoid (Γ : Type u_1) [Inhabited Γ] : setoid (List Γ) :=\n setoid.mk blank_rel (blank_rel.equivalence Γ)\n\n/-- A `list_blank Γ` is a quotient of `list Γ` by extension by blanks at the end. This is used to\nrepresent half-tapes of a Turing machine, so that we can pretend that the list continues\ninfinitely with blanks. -/\ndef list_blank (Γ : Type u_1) [Inhabited Γ] :=\n quotient (blank_rel.setoid Γ)\n\nprotected instance list_blank.inhabited {Γ : Type u_1} [Inhabited Γ] : Inhabited (list_blank Γ) :=\n { default := quotient.mk' [] }\n\nprotected instance list_blank.has_emptyc {Γ : Type u_1} [Inhabited Γ] : has_emptyc (list_blank Γ) :=\n has_emptyc.mk (quotient.mk' [])\n\n/-- A modified version of `quotient.lift_on'` specialized for `list_blank`, with the stronger\nprecondition `blank_extends` instead of `blank_rel`. -/\nprotected def list_blank.lift_on {Γ : Type u_1} [Inhabited Γ] {α : Sort u_2} (l : list_blank Γ) (f : List Γ → α) (H : ∀ (a b : List Γ), blank_extends a b → f a = f b) : α :=\n quotient.lift_on' l f sorry\n\n/-- The quotient map turning a `list` into a `list_blank`. -/\ndef list_blank.mk {Γ : Type u_1} [Inhabited Γ] : List Γ → list_blank Γ :=\n quotient.mk'\n\nprotected theorem list_blank.induction_on {Γ : Type u_1} [Inhabited Γ] {p : list_blank Γ → Prop} (q : list_blank Γ) (h : ∀ (a : List Γ), p (list_blank.mk a)) : p q :=\n quotient.induction_on' q h\n\n/-- The head of a `list_blank` is well defined. -/\ndef list_blank.head {Γ : Type u_1} [Inhabited Γ] (l : list_blank Γ) : Γ :=\n list_blank.lift_on l list.head sorry\n\n@[simp] theorem list_blank.head_mk {Γ : Type u_1} [Inhabited Γ] (l : List Γ) : list_blank.head (list_blank.mk l) = list.head l :=\n rfl\n\n/-- The tail of a `list_blank` is well defined (up to the tail of blanks). -/\ndef list_blank.tail {Γ : Type u_1} [Inhabited Γ] (l : list_blank Γ) : list_blank Γ :=\n list_blank.lift_on l (fun (l : List Γ) => list_blank.mk (list.tail l)) sorry\n\n@[simp] theorem list_blank.tail_mk {Γ : Type u_1} [Inhabited Γ] (l : List Γ) : list_blank.tail (list_blank.mk l) = list_blank.mk (list.tail l) :=\n rfl\n\n/-- We can cons an element onto a `list_blank`. -/\ndef list_blank.cons {Γ : Type u_1} [Inhabited Γ] (a : Γ) (l : list_blank Γ) : list_blank Γ :=\n list_blank.lift_on l (fun (l : List Γ) => list_blank.mk (a :: l)) sorry\n\n@[simp] theorem list_blank.cons_mk {Γ : Type u_1} [Inhabited Γ] (a : Γ) (l : List Γ) : list_blank.cons a (list_blank.mk l) = list_blank.mk (a :: l) :=\n rfl\n\n@[simp] theorem list_blank.head_cons {Γ : Type u_1} [Inhabited Γ] (a : Γ) (l : list_blank Γ) : list_blank.head (list_blank.cons a l) = a :=\n quotient.ind' fun (l : List Γ) => rfl\n\n@[simp] theorem list_blank.tail_cons {Γ : Type u_1} [Inhabited Γ] (a : Γ) (l : list_blank Γ) : list_blank.tail (list_blank.cons a l) = l :=\n quotient.ind' fun (l : List Γ) => rfl\n\n/-- The `cons` and `head`/`tail` functions are mutually inverse, unlike in the case of `list` where\nthis only holds for nonempty lists. -/\n@[simp] theorem list_blank.cons_head_tail {Γ : Type u_1} [Inhabited Γ] (l : list_blank Γ) : list_blank.cons (list_blank.head l) (list_blank.tail l) = l := sorry\n\n/-- The `cons` and `head`/`tail` functions are mutually inverse, unlike in the case of `list` where\nthis only holds for nonempty lists. -/\ntheorem list_blank.exists_cons {Γ : Type u_1} [Inhabited Γ] (l : list_blank Γ) : ∃ (a : Γ), ∃ (l' : list_blank Γ), l = list_blank.cons a l' :=\n Exists.intro (list_blank.head l) (Exists.intro (list_blank.tail l) (Eq.symm (list_blank.cons_head_tail l)))\n\n/-- The n-th element of a `list_blank` is well defined for all `n : ℕ`, unlike in a `list`. -/\ndef list_blank.nth {Γ : Type u_1} [Inhabited Γ] (l : list_blank Γ) (n : ℕ) : Γ :=\n list_blank.lift_on l (fun (l : List Γ) => list.inth l n) sorry\n\n@[simp] theorem list_blank.nth_mk {Γ : Type u_1} [Inhabited Γ] (l : List Γ) (n : ℕ) : list_blank.nth (list_blank.mk l) n = list.inth l n :=\n rfl\n\n@[simp] theorem list_blank.nth_zero {Γ : Type u_1} [Inhabited Γ] (l : list_blank Γ) : list_blank.nth l 0 = list_blank.head l := sorry\n\n@[simp] theorem list_blank.nth_succ {Γ : Type u_1} [Inhabited Γ] (l : list_blank Γ) (n : ℕ) : list_blank.nth l (n + 1) = list_blank.nth (list_blank.tail l) n := sorry\n\ntheorem list_blank.ext {Γ : Type u_1} [Inhabited Γ] {L₁ : list_blank Γ} {L₂ : list_blank Γ} : (∀ (i : ℕ), list_blank.nth L₁ i = list_blank.nth L₂ i) → L₁ = L₂ := sorry\n\n/-- Apply a function to a value stored at the nth position of the list. -/\n@[simp] def list_blank.modify_nth {Γ : Type u_1} [Inhabited Γ] (f : Γ → Γ) : ℕ → list_blank Γ → list_blank Γ :=\n sorry\n\ntheorem list_blank.nth_modify_nth {Γ : Type u_1} [Inhabited Γ] (f : Γ → Γ) (n : ℕ) (i : ℕ) (L : list_blank Γ) : list_blank.nth (list_blank.modify_nth f n L) i = ite (i = n) (f (list_blank.nth L i)) (list_blank.nth L i) := sorry\n\n/-- A pointed map of `inhabited` types is a map that sends one default value to the other. -/\nstructure pointed_map (Γ : Type u) (Γ' : Type v) [Inhabited Γ] [Inhabited Γ'] \nwhere\n f : Γ → Γ'\n map_pt' : f Inhabited.default = Inhabited.default\n\nprotected instance pointed_map.inhabited {Γ : Type u_1} {Γ' : Type u_2} [Inhabited Γ] [Inhabited Γ'] : Inhabited (pointed_map Γ Γ') :=\n { default := pointed_map.mk (fun (_x : Γ) => Inhabited.default) sorry }\n\nprotected instance pointed_map.has_coe_to_fun {Γ : Type u_1} {Γ' : Type u_2} [Inhabited Γ] [Inhabited Γ'] : has_coe_to_fun (pointed_map Γ Γ') :=\n has_coe_to_fun.mk (fun (x : pointed_map Γ Γ') => Γ → Γ') pointed_map.f\n\n@[simp] theorem pointed_map.mk_val {Γ : Type u_1} {Γ' : Type u_2} [Inhabited Γ] [Inhabited Γ'] (f : Γ → Γ') (pt : f Inhabited.default = Inhabited.default) : ⇑(pointed_map.mk f pt) = f :=\n rfl\n\n@[simp] theorem pointed_map.map_pt {Γ : Type u_1} {Γ' : Type u_2} [Inhabited Γ] [Inhabited Γ'] (f : pointed_map Γ Γ') : coe_fn f Inhabited.default = Inhabited.default :=\n pointed_map.map_pt' f\n\n@[simp] theorem pointed_map.head_map {Γ : Type u_1} {Γ' : Type u_2} [Inhabited Γ] [Inhabited Γ'] (f : pointed_map Γ Γ') (l : List Γ) : list.head (list.map (⇑f) l) = coe_fn f (list.head l) :=\n list.cases_on l (Eq.symm (pointed_map.map_pt f))\n fun (l_hd : Γ) (l_tl : List Γ) => Eq.refl (list.head (list.map (⇑f) (l_hd :: l_tl)))\n\n/-- The `map` function on lists is well defined on `list_blank`s provided that the map is\npointed. -/\ndef list_blank.map {Γ : Type u_1} {Γ' : Type u_2} [Inhabited Γ] [Inhabited Γ'] (f : pointed_map Γ Γ') (l : list_blank Γ) : list_blank Γ' :=\n list_blank.lift_on l (fun (l : List Γ) => list_blank.mk (list.map (⇑f) l)) sorry\n\n@[simp] theorem list_blank.map_mk {Γ : Type u_1} {Γ' : Type u_2} [Inhabited Γ] [Inhabited Γ'] (f : pointed_map Γ Γ') (l : List Γ) : list_blank.map f (list_blank.mk l) = list_blank.mk (list.map (⇑f) l) :=\n rfl\n\n@[simp] theorem list_blank.head_map {Γ : Type u_1} {Γ' : Type u_2} [Inhabited Γ] [Inhabited Γ'] (f : pointed_map Γ Γ') (l : list_blank Γ) : list_blank.head (list_blank.map f l) = coe_fn f (list_blank.head l) := sorry\n\n@[simp] theorem list_blank.tail_map {Γ : Type u_1} {Γ' : Type u_2} [Inhabited Γ] [Inhabited Γ'] (f : pointed_map Γ Γ') (l : list_blank Γ) : list_blank.tail (list_blank.map f l) = list_blank.map f (list_blank.tail l) := sorry\n\n@[simp] theorem list_blank.map_cons {Γ : Type u_1} {Γ' : Type u_2} [Inhabited Γ] [Inhabited Γ'] (f : pointed_map Γ Γ') (l : list_blank Γ) (a : Γ) : list_blank.map f (list_blank.cons a l) = list_blank.cons (coe_fn f a) (list_blank.map f l) := sorry\n\n@[simp] theorem list_blank.nth_map {Γ : Type u_1} {Γ' : Type u_2} [Inhabited Γ] [Inhabited Γ'] (f : pointed_map Γ Γ') (l : list_blank Γ) (n : ℕ) : list_blank.nth (list_blank.map f l) n = coe_fn f (list_blank.nth l n) := sorry\n\n/-- The `i`-th projection as a pointed map. -/\ndef proj {ι : Type u_1} {Γ : ι → Type u_2} [(i : ι) → Inhabited (Γ i)] (i : ι) : pointed_map ((i : ι) → Γ i) (Γ i) :=\n pointed_map.mk (fun (a : (i : ι) → Γ i) => a i) sorry\n\ntheorem proj_map_nth {ι : Type u_1} {Γ : ι → Type u_2} [(i : ι) → Inhabited (Γ i)] (i : ι) (L : list_blank ((i : ι) → Γ i)) (n : ℕ) : list_blank.nth (list_blank.map (proj i) L) n = list_blank.nth L n i := sorry\n\ntheorem list_blank.map_modify_nth {Γ : Type u_1} {Γ' : Type u_2} [Inhabited Γ] [Inhabited Γ'] (F : pointed_map Γ Γ') (f : Γ → Γ) (f' : Γ' → Γ') (H : ∀ (x : Γ), coe_fn F (f x) = f' (coe_fn F x)) (n : ℕ) (L : list_blank Γ) : list_blank.map F (list_blank.modify_nth f n L) = list_blank.modify_nth f' n (list_blank.map F L) := sorry\n\n/-- Append a list on the left side of a list_blank. -/\n@[simp] def list_blank.append {Γ : Type u_1} [Inhabited Γ] : List Γ → list_blank Γ → list_blank Γ :=\n sorry\n\n@[simp] theorem list_blank.append_mk {Γ : Type u_1} [Inhabited Γ] (l₁ : List Γ) (l₂ : List Γ) : list_blank.append l₁ (list_blank.mk l₂) = list_blank.mk (l₁ ++ l₂) := sorry\n\ntheorem list_blank.append_assoc {Γ : Type u_1} [Inhabited Γ] (l₁ : List Γ) (l₂ : List Γ) (l₃ : list_blank Γ) : list_blank.append (l₁ ++ l₂) l₃ = list_blank.append l₁ (list_blank.append l₂ l₃) := sorry\n\n/-- The `bind` function on lists is well defined on `list_blank`s provided that the default element\nis sent to a sequence of default elements. -/\ndef list_blank.bind {Γ : Type u_1} {Γ' : Type u_2} [Inhabited Γ] [Inhabited Γ'] (l : list_blank Γ) (f : Γ → List Γ') (hf : ∃ (n : ℕ), f Inhabited.default = list.repeat Inhabited.default n) : list_blank Γ' :=\n list_blank.lift_on l (fun (l : List Γ) => list_blank.mk (list.bind l f)) sorry\n\n@[simp] theorem list_blank.bind_mk {Γ : Type u_1} {Γ' : Type u_2} [Inhabited Γ] [Inhabited Γ'] (l : List Γ) (f : Γ → List Γ') (hf : ∃ (n : ℕ), f Inhabited.default = list.repeat Inhabited.default n) : list_blank.bind (list_blank.mk l) f hf = list_blank.mk (list.bind l f) :=\n rfl\n\n@[simp] theorem list_blank.cons_bind {Γ : Type u_1} {Γ' : Type u_2} [Inhabited Γ] [Inhabited Γ'] (a : Γ) (l : list_blank Γ) (f : Γ → List Γ') (hf : ∃ (n : ℕ), f Inhabited.default = list.repeat Inhabited.default n) : list_blank.bind (list_blank.cons a l) f hf = list_blank.append (f a) (list_blank.bind l f hf) := sorry\n\n/-- The tape of a Turing machine is composed of a head element (which we imagine to be the\ncurrent position of the head), together with two `list_blank`s denoting the portions of the tape\ngoing off to the left and right. When the Turing machine moves right, an element is pulled from the\nright side and becomes the new head, while the head element is consed onto the left side. -/\nstructure tape (Γ : Type u_1) [Inhabited Γ] \nwhere\n head : Γ\n left : list_blank Γ\n right : list_blank Γ\n\nprotected instance tape.inhabited {Γ : Type u_1} [Inhabited Γ] : Inhabited (tape Γ) :=\n { default := tape.mk Inhabited.default Inhabited.default Inhabited.default }\n\n/-- A direction for the turing machine `move` command, either\n left or right. -/\ninductive dir \nwhere\n| left : dir\n| right : dir\n\n/-- The \"inclusive\" left side of the tape, including both `left` and `head`. -/\ndef tape.left₀ {Γ : Type u_1} [Inhabited Γ] (T : tape Γ) : list_blank Γ :=\n list_blank.cons (tape.head T) (tape.left T)\n\n/-- The \"inclusive\" right side of the tape, including both `right` and `head`. -/\ndef tape.right₀ {Γ : Type u_1} [Inhabited Γ] (T : tape Γ) : list_blank Γ :=\n list_blank.cons (tape.head T) (tape.right T)\n\n/-- Move the tape in response to a motion of the Turing machine. Note that `T.move dir.left` makes\n`T.left` smaller; the Turing machine is moving left and the tape is moving right. -/\ndef tape.move {Γ : Type u_1} [Inhabited Γ] : dir → tape Γ → tape Γ :=\n sorry\n\n@[simp] theorem tape.move_left_right {Γ : Type u_1} [Inhabited Γ] (T : tape Γ) : tape.move dir.right (tape.move dir.left T) = T := sorry\n\n@[simp] theorem tape.move_right_left {Γ : Type u_1} [Inhabited Γ] (T : tape Γ) : tape.move dir.left (tape.move dir.right T) = T := sorry\n\n/-- Construct a tape from a left side and an inclusive right side. -/\ndef tape.mk' {Γ : Type u_1} [Inhabited Γ] (L : list_blank Γ) (R : list_blank Γ) : tape Γ :=\n tape.mk (list_blank.head R) L (list_blank.tail R)\n\n@[simp] theorem tape.mk'_left {Γ : Type u_1} [Inhabited Γ] (L : list_blank Γ) (R : list_blank Γ) : tape.left (tape.mk' L R) = L :=\n rfl\n\n@[simp] theorem tape.mk'_head {Γ : Type u_1} [Inhabited Γ] (L : list_blank Γ) (R : list_blank Γ) : tape.head (tape.mk' L R) = list_blank.head R :=\n rfl\n\n@[simp] theorem tape.mk'_right {Γ : Type u_1} [Inhabited Γ] (L : list_blank Γ) (R : list_blank Γ) : tape.right (tape.mk' L R) = list_blank.tail R :=\n rfl\n\n@[simp] theorem tape.mk'_right₀ {Γ : Type u_1} [Inhabited Γ] (L : list_blank Γ) (R : list_blank Γ) : tape.right₀ (tape.mk' L R) = R :=\n list_blank.cons_head_tail R\n\n@[simp] theorem tape.mk'_left_right₀ {Γ : Type u_1} [Inhabited Γ] (T : tape Γ) : tape.mk' (tape.left T) (tape.right₀ T) = T := sorry\n\ntheorem tape.exists_mk' {Γ : Type u_1} [Inhabited Γ] (T : tape Γ) : ∃ (L : list_blank Γ), ∃ (R : list_blank Γ), T = tape.mk' L R :=\n Exists.intro (tape.left T) (Exists.intro (tape.right₀ T) (Eq.symm (tape.mk'_left_right₀ T)))\n\n@[simp] theorem tape.move_left_mk' {Γ : Type u_1} [Inhabited Γ] (L : list_blank Γ) (R : list_blank Γ) : tape.move dir.left (tape.mk' L R) = tape.mk' (list_blank.tail L) (list_blank.cons (list_blank.head L) R) := sorry\n\n@[simp] theorem tape.move_right_mk' {Γ : Type u_1} [Inhabited Γ] (L : list_blank Γ) (R : list_blank Γ) : tape.move dir.right (tape.mk' L R) = tape.mk' (list_blank.cons (list_blank.head R) L) (list_blank.tail R) := sorry\n\n/-- Construct a tape from a left side and an inclusive right side. -/\ndef tape.mk₂ {Γ : Type u_1} [Inhabited Γ] (L : List Γ) (R : List Γ) : tape Γ :=\n tape.mk' (list_blank.mk L) (list_blank.mk R)\n\n/-- Construct a tape from a list, with the head of the list at the TM head and the rest going\nto the right. -/\ndef tape.mk₁ {Γ : Type u_1} [Inhabited Γ] (l : List Γ) : tape Γ :=\n tape.mk₂ [] l\n\n/-- The `nth` function of a tape is integer-valued, with index `0` being the head, negative indexes\non the left and positive indexes on the right. (Picture a number line.) -/\ndef tape.nth {Γ : Type u_1} [Inhabited Γ] (T : tape Γ) : ℤ → Γ :=\n sorry\n\n@[simp] theorem tape.nth_zero {Γ : Type u_1} [Inhabited Γ] (T : tape Γ) : tape.nth T 0 = tape.head T :=\n rfl\n\ntheorem tape.right₀_nth {Γ : Type u_1} [Inhabited Γ] (T : tape Γ) (n : ℕ) : list_blank.nth (tape.right₀ T) n = tape.nth T ↑n := sorry\n\n@[simp] theorem tape.mk'_nth_nat {Γ : Type u_1} [Inhabited Γ] (L : list_blank Γ) (R : list_blank Γ) (n : ℕ) : tape.nth (tape.mk' L R) ↑n = list_blank.nth R n := sorry\n\n@[simp] theorem tape.move_left_nth {Γ : Type u_1} [Inhabited Γ] (T : tape Γ) (i : ℤ) : tape.nth (tape.move dir.left T) i = tape.nth T (i - 1) := sorry\n\n@[simp] theorem tape.move_right_nth {Γ : Type u_1} [Inhabited Γ] (T : tape Γ) (i : ℤ) : tape.nth (tape.move dir.right T) i = tape.nth T (i + 1) := sorry\n\n@[simp] theorem tape.move_right_n_head {Γ : Type u_1} [Inhabited Γ] (T : tape Γ) (i : ℕ) : tape.head (nat.iterate (tape.move dir.right) i T) = tape.nth T ↑i := sorry\n\n/-- Replace the current value of the head on the tape. -/\ndef tape.write {Γ : Type u_1} [Inhabited Γ] (b : Γ) (T : tape Γ) : tape Γ :=\n tape.mk b (tape.left T) (tape.right T)\n\n@[simp] theorem tape.write_self {Γ : Type u_1} [Inhabited Γ] (T : tape Γ) : tape.write (tape.head T) T = T :=\n tape.cases_on T\n fun (T_head : Γ) (T_left T_right : list_blank Γ) =>\n Eq.refl (tape.write (tape.head (tape.mk T_head T_left T_right)) (tape.mk T_head T_left T_right))\n\n@[simp] theorem tape.write_nth {Γ : Type u_1} [Inhabited Γ] (b : Γ) (T : tape Γ) {i : ℤ} : tape.nth (tape.write b T) i = ite (i = 0) b (tape.nth T i) := sorry\n\n@[simp] theorem tape.write_mk' {Γ : Type u_1} [Inhabited Γ] (a : Γ) (b : Γ) (L : list_blank Γ) (R : list_blank Γ) : tape.write b (tape.mk' L (list_blank.cons a R)) = tape.mk' L (list_blank.cons b R) := sorry\n\n/-- Apply a pointed map to a tape to change the alphabet. -/\ndef tape.map {Γ : Type u_1} {Γ' : Type u_2} [Inhabited Γ] [Inhabited Γ'] (f : pointed_map Γ Γ') (T : tape Γ) : tape Γ' :=\n tape.mk (coe_fn f (tape.head T)) (list_blank.map f (tape.left T)) (list_blank.map f (tape.right T))\n\n@[simp] theorem tape.map_fst {Γ : Type u_1} {Γ' : Type u_2} [Inhabited Γ] [Inhabited Γ'] (f : pointed_map Γ Γ') (T : tape Γ) : tape.head (tape.map f T) = coe_fn f (tape.head T) :=\n tape.cases_on T\n fun (T_head : Γ) (T_left T_right : list_blank Γ) => Eq.refl (tape.head (tape.map f (tape.mk T_head T_left T_right)))\n\n@[simp] theorem tape.map_write {Γ : Type u_1} {Γ' : Type u_2} [Inhabited Γ] [Inhabited Γ'] (f : pointed_map Γ Γ') (b : Γ) (T : tape Γ) : tape.map f (tape.write b T) = tape.write (coe_fn f b) (tape.map f T) :=\n tape.cases_on T\n fun (T_head : Γ) (T_left T_right : list_blank Γ) =>\n Eq.refl (tape.map f (tape.write b (tape.mk T_head T_left T_right)))\n\n@[simp] theorem tape.write_move_right_n {Γ : Type u_1} [Inhabited Γ] (f : Γ → Γ) (L : list_blank Γ) (R : list_blank Γ) (n : ℕ) : tape.write (f (list_blank.nth R n)) (nat.iterate (tape.move dir.right) n (tape.mk' L R)) =\n nat.iterate (tape.move dir.right) n (tape.mk' L (list_blank.modify_nth f n R)) := sorry\n\ntheorem tape.map_move {Γ : Type u_1} {Γ' : Type u_2} [Inhabited Γ] [Inhabited Γ'] (f : pointed_map Γ Γ') (T : tape Γ) (d : dir) : tape.map f (tape.move d T) = tape.move d (tape.map f T) := sorry\n\ntheorem tape.map_mk' {Γ : Type u_1} {Γ' : Type u_2} [Inhabited Γ] [Inhabited Γ'] (f : pointed_map Γ Γ') (L : list_blank Γ) (R : list_blank Γ) : tape.map f (tape.mk' L R) = tape.mk' (list_blank.map f L) (list_blank.map f R) := sorry\n\ntheorem tape.map_mk₂ {Γ : Type u_1} {Γ' : Type u_2} [Inhabited Γ] [Inhabited Γ'] (f : pointed_map Γ Γ') (L : List Γ) (R : List Γ) : tape.map f (tape.mk₂ L R) = tape.mk₂ (list.map (⇑f) L) (list.map (⇑f) R) := sorry\n\ntheorem tape.map_mk₁ {Γ : Type u_1} {Γ' : Type u_2} [Inhabited Γ] [Inhabited Γ'] (f : pointed_map Γ Γ') (l : List Γ) : tape.map f (tape.mk₁ l) = tape.mk₁ (list.map (⇑f) l) :=\n tape.map_mk₂ f [] l\n\n/-- Run a state transition function `σ → option σ` \"to completion\". The return value is the last\nstate returned before a `none` result. If the state transition function always returns `some`,\nthen the computation diverges, returning `roption.none`. -/\ndef eval {σ : Type u_1} (f : σ → Option σ) : σ → roption σ :=\n pfun.fix fun (s : σ) => roption.some (option.elim (f s) (sum.inl s) sum.inr)\n\n/-- The reflexive transitive closure of a state transition function. `reaches f a b` means\nthere is a finite sequence of steps `f a = some a₁`, `f a₁ = some a₂`, ... such that `aₙ = b`.\nThis relation permits zero steps of the state transition function. -/\ndef reaches {σ : Type u_1} (f : σ → Option σ) : σ → σ → Prop :=\n relation.refl_trans_gen fun (a b : σ) => b ∈ f a\n\n/-- The transitive closure of a state transition function. `reaches₁ f a b` means there is a\nnonempty finite sequence of steps `f a = some a₁`, `f a₁ = some a₂`, ... such that `aₙ = b`.\nThis relation does not permit zero steps of the state transition function. -/\ndef reaches₁ {σ : Type u_1} (f : σ → Option σ) : σ → σ → Prop :=\n relation.trans_gen fun (a b : σ) => b ∈ f a\n\ntheorem reaches₁_eq {σ : Type u_1} {f : σ → Option σ} {a : σ} {b : σ} {c : σ} (h : f a = f b) : reaches₁ f a c ↔ reaches₁ f b c := sorry\n\ntheorem reaches_total {σ : Type u_1} {f : σ → Option σ} {a : σ} {b : σ} {c : σ} : reaches f a b → reaches f a c → reaches f b c ∨ reaches f c b :=\n relation.refl_trans_gen.total_of_right_unique fun (_x _x_1 _x_2 : σ) => option.mem_unique\n\ntheorem reaches₁_fwd {σ : Type u_1} {f : σ → Option σ} {a : σ} {b : σ} {c : σ} (h₁ : reaches₁ f a c) (h₂ : b ∈ f a) : reaches f b c := sorry\n\n/-- A variation on `reaches`. `reaches₀ f a b` holds if whenever `reaches₁ f b c` then\n`reaches₁ f a c`. This is a weaker property than `reaches` and is useful for replacing states with\nequivalent states without taking a step. -/\ndef reaches₀ {σ : Type u_1} (f : σ → Option σ) (a : σ) (b : σ) :=\n ∀ (c : σ), reaches₁ f b c → reaches₁ f a c\n\ntheorem reaches₀.trans {σ : Type u_1} {f : σ → Option σ} {a : σ} {b : σ} {c : σ} (h₁ : reaches₀ f a b) (h₂ : reaches₀ f b c) : reaches₀ f a c :=\n fun (c_1 : σ) (ᾰ : reaches₁ f c c_1) => idRhs (reaches₁ f a c_1) (h₁ c_1 (h₂ c_1 ᾰ))\n\ntheorem reaches₀.refl {σ : Type u_1} {f : σ → Option σ} (a : σ) : reaches₀ f a a :=\n fun (c : σ) (ᾰ : reaches₁ f a c) => idRhs (reaches₁ f a c) ᾰ\n\ntheorem reaches₀.single {σ : Type u_1} {f : σ → Option σ} {a : σ} {b : σ} (h : b ∈ f a) : reaches₀ f a b :=\n fun (c : σ) (ᾰ : reaches₁ f b c) =>\n idRhs (relation.trans_gen (fun (a b : σ) => b ∈ f a) a c) (relation.trans_gen.head h ᾰ)\n\ntheorem reaches₀.head {σ : Type u_1} {f : σ → Option σ} {a : σ} {b : σ} {c : σ} (h : b ∈ f a) (h₂ : reaches₀ f b c) : reaches₀ f a c :=\n reaches₀.trans (reaches₀.single h) h₂\n\ntheorem reaches₀.tail {σ : Type u_1} {f : σ → Option σ} {a : σ} {b : σ} {c : σ} (h₁ : reaches₀ f a b) (h : c ∈ f b) : reaches₀ f a c :=\n reaches₀.trans h₁ (reaches₀.single h)\n\ntheorem reaches₀_eq {σ : Type u_1} {f : σ → Option σ} {a : σ} {b : σ} (e : f a = f b) : reaches₀ f a b :=\n fun (c : σ) (ᾰ : reaches₁ f b c) => idRhs (reaches₁ f a c) (iff.mpr (reaches₁_eq e) ᾰ)\n\ntheorem reaches₁.to₀ {σ : Type u_1} {f : σ → Option σ} {a : σ} {b : σ} (h : reaches₁ f a b) : reaches₀ f a b :=\n fun (c : σ) (ᾰ : reaches₁ f b c) =>\n idRhs (relation.trans_gen (fun (a b : σ) => b ∈ f a) a c) (relation.trans_gen.trans h ᾰ)\n\ntheorem reaches.to₀ {σ : Type u_1} {f : σ → Option σ} {a : σ} {b : σ} (h : reaches f a b) : reaches₀ f a b :=\n fun (c : σ) (ᾰ : reaches₁ f b c) =>\n idRhs (relation.trans_gen (fun (a b : σ) => b ∈ f a) a c) (relation.trans_gen.trans_right h ᾰ)\n\ntheorem reaches₀.tail' {σ : Type u_1} {f : σ → Option σ} {a : σ} {b : σ} {c : σ} (h : reaches₀ f a b) (h₂ : c ∈ f b) : reaches₁ f a c :=\n h c (relation.trans_gen.single h₂)\n\n/-- (co-)Induction principle for `eval`. If a property `C` holds of any point `a` evaluating to `b`\nwhich is either terminal (meaning `a = b`) or where the next point also satisfies `C`, then it\nholds of any point where `eval f a` evaluates to `b`. This formalizes the notion that if\n`eval f a` evaluates to `b` then it reaches terminal state `b` in finitely many steps. -/\ndef eval_induction {σ : Type u_1} {f : σ → Option σ} {b : σ} {C : σ → Sort u_2} {a : σ} (h : b ∈ eval f a) (H : (a : σ) → b ∈ eval f a → ((a' : σ) → b ∈ eval f a' → f a = some a' → C a') → C a) : C a :=\n pfun.fix_induction h\n fun (a' : σ) (ha' : b ∈ pfun.fix (fun (s : σ) => roption.some (option.elim (f s) (sum.inl s) sum.inr)) a')\n (h' :\n (a'_1 : σ) →\n b ∈ pfun.fix (fun (s : σ) => roption.some (option.elim (f s) (sum.inl s) sum.inr)) a'_1 →\n sum.inr a'_1 ∈ roption.some (option.elim (f a') (sum.inl a') sum.inr) → C a'_1) =>\n H a' ha' fun (b' : σ) (hb' : b ∈ eval f b') (e : f a' = some b') => h' b' hb' sorry\n\ntheorem mem_eval {σ : Type u_1} {f : σ → Option σ} {a : σ} {b : σ} : b ∈ eval f a ↔ reaches f a b ∧ f b = none := sorry\n\ntheorem eval_maximal₁ {σ : Type u_1} {f : σ → Option σ} {a : σ} {b : σ} (h : b ∈ eval f a) (c : σ) : ¬reaches₁ f b c := sorry\n\ntheorem eval_maximal {σ : Type u_1} {f : σ → Option σ} {a : σ} {b : σ} (h : b ∈ eval f a) {c : σ} : reaches f b c ↔ c = b := sorry\n\ntheorem reaches_eval {σ : Type u_1} {f : σ → Option σ} {a : σ} {b : σ} (ab : reaches f a b) : eval f a = eval f b := sorry\n\n/-- Given a relation `tr : σ₁ → σ₂ → Prop` between state spaces, and state transition functions\n`f₁ : σ₁ → option σ₁` and `f₂ : σ₂ → option σ₂`, `respects f₁ f₂ tr` means that if `tr a₁ a₂` holds\ninitially and `f₁` takes a step to `a₂` then `f₂` will take one or more steps before reaching a\nstate `b₂` satisfying `tr a₂ b₂`, and if `f₁ a₁` terminates then `f₂ a₂` also terminates.\nSuch a relation `tr` is also known as a refinement. -/\ndef respects {σ₁ : Type u_1} {σ₂ : Type u_2} (f₁ : σ₁ → Option σ₁) (f₂ : σ₂ → Option σ₂) (tr : σ₁ → σ₂ → Prop) :=\n {a₁ : σ₁} → {a₂ : σ₂} → tr a₁ a₂ → sorry\n\ntheorem tr_reaches₁ {σ₁ : Type u_1} {σ₂ : Type u_2} {f₁ : σ₁ → Option σ₁} {f₂ : σ₂ → Option σ₂} {tr : σ₁ → σ₂ → Prop} (H : respects f₁ f₂ tr) {a₁ : σ₁} {a₂ : σ₂} (aa : tr a₁ a₂) {b₁ : σ₁} (ab : reaches₁ f₁ a₁ b₁) : ∃ (b₂ : σ₂), tr b₁ b₂ ∧ reaches₁ f₂ a₂ b₂ := sorry\n\ntheorem tr_reaches {σ₁ : Type u_1} {σ₂ : Type u_2} {f₁ : σ₁ → Option σ₁} {f₂ : σ₂ → Option σ₂} {tr : σ₁ → σ₂ → Prop} (H : respects f₁ f₂ tr) {a₁ : σ₁} {a₂ : σ₂} (aa : tr a₁ a₂) {b₁ : σ₁} (ab : reaches f₁ a₁ b₁) : ∃ (b₂ : σ₂), tr b₁ b₂ ∧ reaches f₂ a₂ b₂ := sorry\n\ntheorem tr_reaches_rev {σ₁ : Type u_1} {σ₂ : Type u_2} {f₁ : σ₁ → Option σ₁} {f₂ : σ₂ → Option σ₂} {tr : σ₁ → σ₂ → Prop} (H : respects f₁ f₂ tr) {a₁ : σ₁} {a₂ : σ₂} (aa : tr a₁ a₂) {b₂ : σ₂} (ab : reaches f₂ a₂ b₂) : ∃ (c₁ : σ₁), ∃ (c₂ : σ₂), reaches f₂ b₂ c₂ ∧ tr c₁ c₂ ∧ reaches f₁ a₁ c₁ := sorry\n\ntheorem tr_eval {σ₁ : Type u_1} {σ₂ : Type u_2} {f₁ : σ₁ → Option σ₁} {f₂ : σ₂ → Option σ₂} {tr : σ₁ → σ₂ → Prop} (H : respects f₁ f₂ tr) {a₁ : σ₁} {b₁ : σ₁} {a₂ : σ₂} (aa : tr a₁ a₂) (ab : b₁ ∈ eval f₁ a₁) : ∃ (b₂ : σ₂), tr b₁ b₂ ∧ b₂ ∈ eval f₂ a₂ := sorry\n\ntheorem tr_eval_rev {σ₁ : Type u_1} {σ₂ : Type u_2} {f₁ : σ₁ → Option σ₁} {f₂ : σ₂ → Option σ₂} {tr : σ₁ → σ₂ → Prop} (H : respects f₁ f₂ tr) {a₁ : σ₁} {b₂ : σ₂} {a₂ : σ₂} (aa : tr a₁ a₂) (ab : b₂ ∈ eval f₂ a₂) : ∃ (b₁ : σ₁), tr b₁ b₂ ∧ b₁ ∈ eval f₁ a₁ := sorry\n\ntheorem tr_eval_dom {σ₁ : Type u_1} {σ₂ : Type u_2} {f₁ : σ₁ → Option σ₁} {f₂ : σ₂ → Option σ₂} {tr : σ₁ → σ₂ → Prop} (H : respects f₁ f₂ tr) {a₁ : σ₁} {a₂ : σ₂} (aa : tr a₁ a₂) : roption.dom (eval f₂ a₂) ↔ roption.dom (eval f₁ a₁) := sorry\n\n/-- A simpler version of `respects` when the state transition relation `tr` is a function. -/\ndef frespects {σ₁ : Type u_1} {σ₂ : Type u_2} (f₂ : σ₂ → Option σ₂) (tr : σ₁ → σ₂) (a₂ : σ₂) : Option σ₁ → Prop :=\n sorry\n\ntheorem frespects_eq {σ₁ : Type u_1} {σ₂ : Type u_2} {f₂ : σ₂ → Option σ₂} {tr : σ₁ → σ₂} {a₂ : σ₂} {b₂ : σ₂} (h : f₂ a₂ = f₂ b₂) {b₁ : Option σ₁} : frespects f₂ tr a₂ b₁ ↔ frespects f₂ tr b₂ b₁ := sorry\n\ntheorem fun_respects {σ₁ : Type u_1} {σ₂ : Type u_2} {f₁ : σ₁ → Option σ₁} {f₂ : σ₂ → Option σ₂} {tr : σ₁ → σ₂} : (respects f₁ f₂ fun (a : σ₁) (b : σ₂) => tr a = b) ↔ ∀ {a₁ : σ₁}, frespects f₂ tr (tr a₁) (f₁ a₁) := sorry\n\ntheorem tr_eval' {σ₁ : Type u_1} {σ₂ : Type u_1} (f₁ : σ₁ → Option σ₁) (f₂ : σ₂ → Option σ₂) (tr : σ₁ → σ₂) (H : respects f₁ f₂ fun (a : σ₁) (b : σ₂) => tr a = b) (a₁ : σ₁) : eval f₂ (tr a₁) = tr <$> eval f₁ a₁ := sorry\n\n/-!\n## The TM0 model\n\nA TM0 turing machine is essentially a Post-Turing machine, adapted for type theory.\n\nA Post-Turing machine with symbol type `Γ` and label type `Λ` is a function\n`Λ → Γ → option (Λ × stmt)`, where a `stmt` can be either `move left`, `move right` or `write a`\nfor `a : Γ`. The machine works over a \"tape\", a doubly-infinite sequence of elements of `Γ`, and\nan instantaneous configuration, `cfg`, is a label `q : Λ` indicating the current internal state of\nthe machine, and a `tape Γ` (which is essentially `ℤ →₀ Γ`). The evolution is described by the\n`step` function:\n\n* If `M q T.head = none`, then the machine halts.\n* If `M q T.head = some (q', s)`, then the machine performs action `s : stmt` and then transitions\n to state `q'`.\n\nThe initial state takes a `list Γ` and produces a `tape Γ` where the head of the list is the head\nof the tape and the rest of the list extends to the right, with the left side all blank. The final\nstate takes the entire right side of the tape right or equal to the current position of the\nmachine. (This is actually a `list_blank Γ`, not a `list Γ`, because we don't know, at this level\nof generality, where the output ends. If equality to `default Γ` is decidable we can trim the list\nto remove the infinite tail of blanks.)\n-/\n\nnamespace TM0\n\n\n/-- A Turing machine \"statement\" is just a command to either move\n left or right, or write a symbol on the tape. -/\ninductive stmt (Γ : Type u_1) [Inhabited Γ] \nwhere\n| move : dir → stmt Γ\n| write : Γ → stmt Γ\n\nprotected instance stmt.inhabited (Γ : Type u_1) [Inhabited Γ] : Inhabited (stmt Γ) :=\n { default := stmt.write Inhabited.default }\n\n/-- A Post-Turing machine with symbol type `Γ` and label type `Λ`\n is a function which, given the current state `q : Λ` and\n the tape head `a : Γ`, either halts (returns `none`) or returns\n a new state `q' : Λ` and a `stmt` describing what to do,\n either a move left or right, or a write command.\n\n Both `Λ` and `Γ` are required to be inhabited; the default value\n for `Γ` is the \"blank\" tape value, and the default value of `Λ` is\n the initial state. -/\ndef machine (Γ : Type u_1) [Inhabited Γ] (Λ : Type u_2) [Inhabited Λ] :=\n Λ → Γ → Option (Λ × stmt Γ)\n\nprotected instance machine.inhabited (Γ : Type u_1) [Inhabited Γ] (Λ : Type u_2) [Inhabited Λ] : Inhabited (machine Γ Λ) :=\n eq.mpr sorry (pi.inhabited Λ)\n\n/-- The configuration state of a Turing machine during operation\n consists of a label (machine state), and a tape, represented in\n the form `(a, L, R)` meaning the tape looks like `L.rev ++ [a] ++ R`\n with the machine currently reading the `a`. The lists are\n automatically extended with blanks as the machine moves around. -/\nstructure cfg (Γ : Type u_1) [Inhabited Γ] (Λ : Type u_2) [Inhabited Λ] \nwhere\n q : Λ\n tape : tape Γ\n\nprotected instance cfg.inhabited (Γ : Type u_1) [Inhabited Γ] (Λ : Type u_2) [Inhabited Λ] : Inhabited (cfg Γ Λ) :=\n { default := cfg.mk Inhabited.default Inhabited.default }\n\n/-- Execution semantics of the Turing machine. -/\ndef step {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} [Inhabited Λ] (M : machine Γ Λ) : cfg Γ Λ → Option (cfg Γ Λ) :=\n sorry\n\n/-- The statement `reaches M s₁ s₂` means that `s₂` is obtained\n starting from `s₁` after a finite number of steps from `s₂`. -/\ndef reaches {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} [Inhabited Λ] (M : machine Γ Λ) : cfg Γ Λ → cfg Γ Λ → Prop :=\n relation.refl_trans_gen fun (a b : cfg Γ Λ) => b ∈ step M a\n\n/-- The initial configuration. -/\ndef init {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} [Inhabited Λ] (l : List Γ) : cfg Γ Λ :=\n cfg.mk Inhabited.default (tape.mk₁ l)\n\n/-- Evaluate a Turing machine on initial input to a final state,\n if it terminates. -/\ndef eval {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} [Inhabited Λ] (M : machine Γ Λ) (l : List Γ) : roption (list_blank Γ) :=\n roption.map (fun (c : cfg Γ Λ) => tape.right₀ (cfg.tape c)) (eval (step M) (init l))\n\n/-- The raw definition of a Turing machine does not require that\n `Γ` and `Λ` are finite, and in practice we will be interested\n in the infinite `Λ` case. We recover instead a notion of\n \"effectively finite\" Turing machines, which only make use of a\n finite subset of their states. We say that a set `S ⊆ Λ`\n supports a Turing machine `M` if `S` is closed under the\n transition function and contains the initial state. -/\ndef supports {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} [Inhabited Λ] (M : machine Γ Λ) (S : set Λ) :=\n Inhabited.default ∈ S ∧ ∀ {q : Λ} {a : Γ} {q' : Λ} {s : stmt Γ}, (q', s) ∈ M q a → q ∈ S → q' ∈ S\n\ntheorem step_supports {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} [Inhabited Λ] (M : machine Γ Λ) {S : set Λ} (ss : supports M S) {c : cfg Γ Λ} {c' : cfg Γ Λ} : c' ∈ step M c → cfg.q c ∈ S → cfg.q c' ∈ S := sorry\n\ntheorem univ_supports {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} [Inhabited Λ] (M : machine Γ Λ) : supports M set.univ :=\n { left := trivial,\n right := fun (q : Λ) (a : Γ) (q' : Λ) (s : stmt Γ) (h₁ : (q', s) ∈ M q a) (h₂ : q ∈ set.univ) => trivial }\n\n/-- Map a TM statement across a function. This does nothing to move statements and maps the write\nvalues. -/\ndef stmt.map {Γ : Type u_1} [Inhabited Γ] {Γ' : Type u_2} [Inhabited Γ'] (f : pointed_map Γ Γ') : stmt Γ → stmt Γ' :=\n sorry\n\n/-- Map a configuration across a function, given `f : Γ → Γ'` a map of the alphabets and\n`g : Λ → Λ'` a map of the machine states. -/\ndef cfg.map {Γ : Type u_1} [Inhabited Γ] {Γ' : Type u_2} [Inhabited Γ'] {Λ : Type u_3} [Inhabited Λ] {Λ' : Type u_4} [Inhabited Λ'] (f : pointed_map Γ Γ') (g : Λ → Λ') : cfg Γ Λ → cfg Γ' Λ' :=\n sorry\n\n/-- Because the state transition function uses the alphabet and machine states in both the input\nand output, to map a machine from one alphabet and machine state space to another we need functions\nin both directions, essentially an `equiv` without the laws. -/\ndef machine.map {Γ : Type u_1} [Inhabited Γ] {Γ' : Type u_2} [Inhabited Γ'] {Λ : Type u_3} [Inhabited Λ] {Λ' : Type u_4} [Inhabited Λ'] (M : machine Γ Λ) (f₁ : pointed_map Γ Γ') (f₂ : pointed_map Γ' Γ) (g₁ : Λ → Λ') (g₂ : Λ' → Λ) : machine Γ' Λ' :=\n sorry\n\ntheorem machine.map_step {Γ : Type u_1} [Inhabited Γ] {Γ' : Type u_2} [Inhabited Γ'] {Λ : Type u_3} [Inhabited Λ] {Λ' : Type u_4} [Inhabited Λ'] (M : machine Γ Λ) (f₁ : pointed_map Γ Γ') (f₂ : pointed_map Γ' Γ) (g₁ : Λ → Λ') (g₂ : Λ' → Λ) {S : set Λ} (f₂₁ : function.right_inverse ⇑f₁ ⇑f₂) (g₂₁ : ∀ (q : Λ), q ∈ S → g₂ (g₁ q) = q) (c : cfg Γ Λ) : cfg.q c ∈ S → option.map (cfg.map f₁ g₁) (step M c) = step (machine.map M f₁ f₂ g₁ g₂) (cfg.map f₁ g₁ c) := sorry\n\ntheorem map_init {Γ : Type u_1} [Inhabited Γ] {Γ' : Type u_2} [Inhabited Γ'] {Λ : Type u_3} [Inhabited Λ] {Λ' : Type u_4} [Inhabited Λ'] (f₁ : pointed_map Γ Γ') (g₁ : pointed_map Λ Λ') (l : List Γ) : cfg.map f₁ (⇑g₁) (init l) = init (list.map (⇑f₁) l) :=\n congr (congr_arg cfg.mk (pointed_map.map_pt g₁)) (tape.map_mk₁ f₁ l)\n\ntheorem machine.map_respects {Γ : Type u_1} [Inhabited Γ] {Γ' : Type u_2} [Inhabited Γ'] {Λ : Type u_3} [Inhabited Λ] {Λ' : Type u_4} [Inhabited Λ'] (M : machine Γ Λ) (f₁ : pointed_map Γ Γ') (f₂ : pointed_map Γ' Γ) (g₁ : pointed_map Λ Λ') (g₂ : Λ' → Λ) {S : set Λ} (ss : supports M S) (f₂₁ : function.right_inverse ⇑f₁ ⇑f₂) (g₂₁ : ∀ (q : Λ), q ∈ S → g₂ (coe_fn g₁ q) = q) : respects (step M) (step (machine.map M f₁ f₂ (⇑g₁) g₂))\n fun (a : cfg Γ Λ) (b : cfg Γ' Λ') => cfg.q a ∈ S ∧ cfg.map f₁ (⇑g₁) a = b := sorry\n\nend TM0\n\n\n/-!\n## The TM1 model\n\nThe TM1 model is a simplification and extension of TM0 (Post-Turing model) in the direction of\nWang B-machines. The machine's internal state is extended with a (finite) store `σ` of variables\nthat may be accessed and updated at any time.\n\nA machine is given by a `Λ` indexed set of procedures or functions. Each function has a body which\nis a `stmt`. Most of the regular commands are allowed to use the current value `a` of the local\nvariables and the value `T.head` on the tape to calculate what to write or how to change local\nstate, but the statements themselves have a fixed structure. The `stmt`s can be as follows:\n\n* `move d q`: move left or right, and then do `q`\n* `write (f : Γ → σ → Γ) q`: write `f a T.head` to the tape, then do `q`\n* `load (f : Γ → σ → σ) q`: change the internal state to `f a T.head`\n* `branch (f : Γ → σ → bool) qtrue qfalse`: If `f a T.head` is true, do `qtrue`, else `qfalse`\n* `goto (f : Γ → σ → Λ)`: Go to label `f a T.head`\n* `halt`: Transition to the halting state, which halts on the following step\n\nNote that here most statements do not have labels; `goto` commands can only go to a new function.\nOnly the `goto` and `halt` statements actually take a step; the rest is done by recursion on\nstatements and so take 0 steps. (There is a uniform bound on many statements can be executed before\nthe next `goto`, so this is an `O(1)` speedup with the constant depending on the machine.)\n\nThe `halt` command has a one step stutter before actually halting so that any changes made before\nthe halt have a chance to be \"committed\", since the `eval` relation uses the final configuration\nbefore the halt as the output, and `move` and `write` etc. take 0 steps in this model.\n-/\n\nnamespace TM1\n\n\n/-- The TM1 model is a simplification and extension of TM0\n (Post-Turing model) in the direction of Wang B-machines. The machine's\n internal state is extended with a (finite) store `σ` of variables\n that may be accessed and updated at any time.\n A machine is given by a `Λ` indexed set of procedures or functions.\n Each function has a body which is a `stmt`, which can either be a\n `move` or `write` command, a `branch` (if statement based on the\n current tape value), a `load` (set the variable value),\n a `goto` (call another function), or `halt`. Note that here\n most statements do not have labels; `goto` commands can only\n go to a new function. All commands have access to the variable value\n and current tape value. -/\ninductive stmt (Γ : Type u_1) [Inhabited Γ] (Λ : Type u_2) (σ : Type u_3) \nwhere\n| move : dir → stmt Γ Λ σ → stmt Γ Λ σ\n| write : (Γ → σ → Γ) → stmt Γ Λ σ → stmt Γ Λ σ\n| load : (Γ → σ → σ) → stmt Γ Λ σ → stmt Γ Λ σ\n| branch : (Γ → σ → Bool) → stmt Γ Λ σ → stmt Γ Λ σ → stmt Γ Λ σ\n| goto : (Γ → σ → Λ) → stmt Γ Λ σ\n| halt : stmt Γ Λ σ\n\nprotected instance stmt.inhabited (Γ : Type u_1) [Inhabited Γ] (Λ : Type u_2) (σ : Type u_3) : Inhabited (stmt Γ Λ σ) :=\n { default := stmt.halt }\n\n/-- The configuration of a TM1 machine is given by the currently\n evaluating statement, the variable store value, and the tape. -/\nstructure cfg (Γ : Type u_1) [Inhabited Γ] (Λ : Type u_2) (σ : Type u_3) \nwhere\n l : Option Λ\n var : σ\n tape : tape Γ\n\nprotected instance cfg.inhabited (Γ : Type u_1) [Inhabited Γ] (Λ : Type u_2) (σ : Type u_3) [Inhabited σ] : Inhabited (cfg Γ Λ σ) :=\n { default := cfg.mk Inhabited.default Inhabited.default Inhabited.default }\n\n/-- The semantics of TM1 evaluation. -/\ndef step_aux {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} {σ : Type u_3} : stmt Γ Λ σ → σ → tape Γ → cfg Γ Λ σ :=\n sorry\n\n/-- The state transition function. -/\ndef step {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} {σ : Type u_3} (M : Λ → stmt Γ Λ σ) : cfg Γ Λ σ → Option (cfg Γ Λ σ) :=\n sorry\n\n/-- A set `S` of labels supports the statement `q` if all the `goto`\n statements in `q` refer only to other functions in `S`. -/\ndef supports_stmt {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} {σ : Type u_3} (S : finset Λ) : stmt Γ Λ σ → Prop :=\n sorry\n\n/-- The subterm closure of a statement. -/\ndef stmts₁ {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} {σ : Type u_3} : stmt Γ Λ σ → finset (stmt Γ Λ σ) :=\n sorry\n\ntheorem stmts₁_self {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} {σ : Type u_3} {q : stmt Γ Λ σ} : q ∈ stmts₁ q := sorry\n\ntheorem stmts₁_trans {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} {σ : Type u_3} {q₁ : stmt Γ Λ σ} {q₂ : stmt Γ Λ σ} : q₁ ∈ stmts₁ q₂ → stmts₁ q₁ ⊆ stmts₁ q₂ := sorry\n\ntheorem stmts₁_supports_stmt_mono {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} {σ : Type u_3} {S : finset Λ} {q₁ : stmt Γ Λ σ} {q₂ : stmt Γ Λ σ} (h : q₁ ∈ stmts₁ q₂) (hs : supports_stmt S q₂) : supports_stmt S q₁ := sorry\n\n/-- The set of all statements in a turing machine, plus one extra value `none` representing the\nhalt state. This is used in the TM1 to TM0 reduction. -/\ndef stmts {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} {σ : Type u_3} (M : Λ → stmt Γ Λ σ) (S : finset Λ) : finset (Option (stmt Γ Λ σ)) :=\n finset.insert_none (finset.bUnion S fun (q : Λ) => stmts₁ (M q))\n\ntheorem stmts_trans {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} {σ : Type u_3} {M : Λ → stmt Γ Λ σ} {S : finset Λ} {q₁ : stmt Γ Λ σ} {q₂ : stmt Γ Λ σ} (h₁ : q₁ ∈ stmts₁ q₂) : some q₂ ∈ stmts M S → some q₁ ∈ stmts M S := sorry\n\n/-- A set `S` of labels supports machine `M` if all the `goto`\n statements in the functions in `S` refer only to other functions\n in `S`. -/\ndef supports {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} {σ : Type u_3} [Inhabited Λ] (M : Λ → stmt Γ Λ σ) (S : finset Λ) :=\n Inhabited.default ∈ S ∧ ∀ (q : Λ), q ∈ S → supports_stmt S (M q)\n\ntheorem stmts_supports_stmt {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} {σ : Type u_3} [Inhabited Λ] {M : Λ → stmt Γ Λ σ} {S : finset Λ} {q : stmt Γ Λ σ} (ss : supports M S) : some q ∈ stmts M S → supports_stmt S q := sorry\n\ntheorem step_supports {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} {σ : Type u_3} [Inhabited Λ] (M : Λ → stmt Γ Λ σ) {S : finset Λ} (ss : supports M S) {c : cfg Γ Λ σ} {c' : cfg Γ Λ σ} : c' ∈ step M c → cfg.l c ∈ finset.insert_none S → cfg.l c' ∈ finset.insert_none S := sorry\n\n/-- The initial state, given a finite input that is placed on the tape starting at the TM head and\ngoing to the right. -/\ndef init {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} {σ : Type u_3} [Inhabited Λ] [Inhabited σ] (l : List Γ) : cfg Γ Λ σ :=\n cfg.mk (some Inhabited.default) Inhabited.default (tape.mk₁ l)\n\n/-- Evaluate a TM to completion, resulting in an output list on the tape (with an indeterminate\nnumber of blanks on the end). -/\ndef eval {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} {σ : Type u_3} [Inhabited Λ] [Inhabited σ] (M : Λ → stmt Γ Λ σ) (l : List Γ) : roption (list_blank Γ) :=\n roption.map (fun (c : cfg Γ Λ σ) => tape.right₀ (cfg.tape c)) (eval (step M) (init l))\n\nend TM1\n\n\n/-!\n## TM1 emulator in TM0\n\nTo prove that TM1 computable functions are TM0 computable, we need to reduce each TM1 program to a\nTM0 program. So suppose a TM1 program is given. We take the following:\n\n* The alphabet `Γ` is the same for both TM1 and TM0\n* The set of states `Λ'` is defined to be `option stmt₁ × σ`, that is, a TM1 statement or `none`\n representing halt, and the possible settings of the internal variables.\n Note that this is an infinite set, because `stmt₁` is infinite. This is okay because we assume\n that from the initial TM1 state, only finitely many other labels are reachable, and there are\n only finitely many statements that appear in all of these functions.\n\nEven though `stmt₁` contains a statement called `halt`, we must separate it from `none`\n(`some halt` steps to `none` and `none` actually halts) because there is a one step stutter in the\nTM1 semantics.\n-/\n\nnamespace TM1to0\n\n\n/-- The base machine state space is a pair of an `option stmt₁` representing the current program\nto be executed, or `none` for the halt state, and a `σ` which is the local state (stored in the TM,\nnot the tape). Because there are an infinite number of programs, this state space is infinite, but\nfor a finitely supported TM1 machine and a finite type `σ`, only finitely many of these states are\nreachable. -/\n-- because of the inhabited instance, but we could avoid the inhabited instances on Λ and σ here.\n\n-- But they are parameters so we cannot easily skip them for just this definition.\n\ndef Λ' {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} [Inhabited Λ] {σ : Type u_3} [Inhabited σ] (M : Λ → TM1.stmt Γ Λ σ) :=\n Option (TM1.stmt Γ Λ σ) × σ\n\nprotected instance Λ'.inhabited {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} [Inhabited Λ] {σ : Type u_3} [Inhabited σ] (M : Λ → TM1.stmt Γ Λ σ) : Inhabited (Λ' M) :=\n { default := (some (M Inhabited.default), Inhabited.default) }\n\n/-- The core TM1 → TM0 translation function. Here `s` is the current value on the tape, and the\n`stmt₁` is the TM1 statement to translate, with local state `v : σ`. We evaluate all regular\ninstructions recursively until we reach either a `move` or `write` command, or a `goto`; in the\nlatter case we emit a dummy `write s` step and transition to the new target location. -/\ndef tr_aux {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} [Inhabited Λ] {σ : Type u_3} [Inhabited σ] (M : Λ → TM1.stmt Γ Λ σ) (s : Γ) : TM1.stmt Γ Λ σ → σ → Λ' M × TM0.stmt Γ :=\n sorry\n\n/-- The translated TM0 machine (given the TM1 machine input). -/\ndef tr {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} [Inhabited Λ] {σ : Type u_3} [Inhabited σ] (M : Λ → TM1.stmt Γ Λ σ) : TM0.machine Γ (Λ' M) :=\n sorry\n\n/-- Translate configurations from TM1 to TM0. -/\ndef tr_cfg {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} [Inhabited Λ] {σ : Type u_3} [Inhabited σ] (M : Λ → TM1.stmt Γ Λ σ) : TM1.cfg Γ Λ σ → TM0.cfg Γ (Λ' M) :=\n sorry\n\ntheorem tr_respects {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} [Inhabited Λ] {σ : Type u_3} [Inhabited σ] (M : Λ → TM1.stmt Γ Λ σ) : respects (TM1.step M) (TM0.step (tr M)) fun (c₁ : TM1.cfg Γ Λ σ) (c₂ : TM0.cfg Γ (Λ' M)) => tr_cfg M c₁ = c₂ := sorry\n\ntheorem tr_eval {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} [Inhabited Λ] {σ : Type u_3} [Inhabited σ] (M : Λ → TM1.stmt Γ Λ σ) (l : List Γ) : TM0.eval (tr M) l = TM1.eval M l := sorry\n\n/-- Given a finite set of accessible `Λ` machine states, there is a finite set of accessible\nmachine states in the target (even though the type `Λ'` is infinite). -/\ndef tr_stmts {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} [Inhabited Λ] {σ : Type u_3} [Inhabited σ] (M : Λ → TM1.stmt Γ Λ σ) [fintype σ] (S : finset Λ) : finset (Λ' M) :=\n finset.product (TM1.stmts M S) finset.univ\n\ntheorem tr_supports {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} [Inhabited Λ] {σ : Type u_3} [Inhabited σ] (M : Λ → TM1.stmt Γ Λ σ) [fintype σ] {S : finset Λ} (ss : TM1.supports M S) : TM0.supports (tr M) ↑(tr_stmts M S) := sorry\n\nend TM1to0\n\n\n/-!\n## TM1(Γ) emulator in TM1(bool)\n\nThe most parsimonious Turing machine model that is still Turing complete is `TM0` with `Γ = bool`.\nBecause our construction in the previous section reducing `TM1` to `TM0` doesn't change the\nalphabet, we can do the alphabet reduction on `TM1` instead of `TM0` directly.\n\nThe basic idea is to use a bijection between `Γ` and a subset of `vector bool n`, where `n` is a\nfixed constant. Each tape element is represented as a block of `n` bools. Whenever the machine\nwants to read a symbol from the tape, it traverses over the block, performing `n` `branch`\ninstructions to each any of the `2^n` results.\n\nFor the `write` instruction, we have to use a `goto` because we need to follow a different code\npath depending on the local state, which is not available in the TM1 model, so instead we jump to\na label computed using the read value and the local state, which performs the writing and returns\nto normal execution.\n\nEmulation overhead is `O(1)`. If not for the above `write` behavior it would be 1-1 because we are\nexploiting the 0-step behavior of regular commands to avoid taking steps, but there are\nnevertheless a bounded number of `write` calls between `goto` statements because TM1 statements are\nfinitely long.\n-/\n\nnamespace TM1to1\n\n\ntheorem exists_enc_dec {Γ : Type u_1} [Inhabited Γ] [fintype Γ] : ∃ (n : ℕ),\n ∃ (enc : Γ → vector Bool n),\n ∃ (dec : vector Bool n → Γ), enc Inhabited.default = vector.repeat false n ∧ ∀ (a : Γ), dec (enc a) = a := sorry\n\n/-- The configuration state of the TM. -/\ninductive Λ' {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} [Inhabited Λ] {σ : Type u_3} [Inhabited σ] \nwhere\n| normal : Λ → Λ'\n| write : Γ → TM1.stmt Γ Λ σ → Λ'\n\nprotected instance Λ'.inhabited {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} [Inhabited Λ] {σ : Type u_3} [Inhabited σ] : Inhabited Λ' :=\n { default := Λ'.normal Inhabited.default }\n\n/-- Read a vector of length `n` from the tape. -/\ndef read_aux {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} [Inhabited Λ] {σ : Type u_3} [Inhabited σ] (n : ℕ) : (vector Bool n → TM1.stmt Bool Λ' σ) → TM1.stmt Bool Λ' σ :=\n sorry\n\n/-- A move left or right corresponds to `n` moves across the super-cell. -/\ndef move {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} [Inhabited Λ] {σ : Type u_3} [Inhabited σ] {n : ℕ} (d : dir) (q : TM1.stmt Bool Λ' σ) : TM1.stmt Bool Λ' σ :=\n nat.iterate (TM1.stmt.move d) n q\n\n/-- To read a symbol from the tape, we use `read_aux` to traverse the symbol,\nthen return to the original position with `n` moves to the left. -/\ndef read {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} [Inhabited Λ] {σ : Type u_3} [Inhabited σ] {n : ℕ} (dec : vector Bool n → Γ) (f : Γ → TM1.stmt Bool Λ' σ) : TM1.stmt Bool Λ' σ :=\n read_aux n fun (v : vector Bool n) => move dir.left (f (dec v))\n\n/-- Write a list of bools on the tape. -/\ndef write {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} [Inhabited Λ] {σ : Type u_3} [Inhabited σ] : List Bool → TM1.stmt Bool Λ' σ → TM1.stmt Bool Λ' σ :=\n sorry\n\n/-- Translate a normal instruction. For the `write` command, we use a `goto` indirection so that\nwe can access the current value of the tape. -/\ndef tr_normal {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} [Inhabited Λ] {σ : Type u_3} [Inhabited σ] {n : ℕ} (dec : vector Bool n → Γ) : TM1.stmt Γ Λ σ → TM1.stmt Bool Λ' σ :=\n sorry\n\ntheorem step_aux_move {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} [Inhabited Λ] {σ : Type u_3} [Inhabited σ] {n : ℕ} (d : dir) (q : TM1.stmt Bool Λ' σ) (v : σ) (T : tape Bool) : TM1.step_aux (move d q) v T = TM1.step_aux q v (nat.iterate (tape.move d) n T) := sorry\n\ntheorem supports_stmt_move {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} [Inhabited Λ] {σ : Type u_3} [Inhabited σ] {n : ℕ} {S : finset Λ'} {d : dir} {q : TM1.stmt Bool Λ' σ} : TM1.supports_stmt S (move d q) = TM1.supports_stmt S q := sorry\n\ntheorem supports_stmt_write {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} [Inhabited Λ] {σ : Type u_3} [Inhabited σ] {S : finset Λ'} {l : List Bool} {q : TM1.stmt Bool Λ' σ} : TM1.supports_stmt S (write l q) = TM1.supports_stmt S q := sorry\n\ntheorem supports_stmt_read {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} [Inhabited Λ] {σ : Type u_3} [Inhabited σ] {n : ℕ} (dec : vector Bool n → Γ) {S : finset Λ'} {f : Γ → TM1.stmt Bool Λ' σ} : (∀ (a : Γ), TM1.supports_stmt S (f a)) → TM1.supports_stmt S (read dec f) := sorry\n\n/-- The low level tape corresponding to the given tape over alphabet `Γ`. -/\ndef tr_tape' {Γ : Type u_1} [Inhabited Γ] {n : ℕ} {enc : Γ → vector Bool n} (enc0 : enc Inhabited.default = vector.repeat false n) (L : list_blank Γ) (R : list_blank Γ) : tape Bool :=\n tape.mk' (list_blank.bind L (fun (x : Γ) => list.reverse (vector.to_list (enc x))) sorry)\n (list_blank.bind R (fun (x : Γ) => vector.to_list (enc x)) sorry)\n\n/-- The low level tape corresponding to the given tape over alphabet `Γ`. -/\ndef tr_tape {Γ : Type u_1} [Inhabited Γ] {n : ℕ} {enc : Γ → vector Bool n} (enc0 : enc Inhabited.default = vector.repeat false n) (T : tape Γ) : tape Bool :=\n tr_tape' enc0 (tape.left T) (tape.right₀ T)\n\ntheorem tr_tape_mk' {Γ : Type u_1} [Inhabited Γ] {n : ℕ} {enc : Γ → vector Bool n} (enc0 : enc Inhabited.default = vector.repeat false n) (L : list_blank Γ) (R : list_blank Γ) : tr_tape enc0 (tape.mk' L R) = tr_tape' enc0 L R := sorry\n\n/-- The top level program. -/\ndef tr {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} [Inhabited Λ] {σ : Type u_3} [Inhabited σ] {n : ℕ} (enc : Γ → vector Bool n) (dec : vector Bool n → Γ) (M : Λ → TM1.stmt Γ Λ σ) : Λ' → TM1.stmt Bool Λ' σ :=\n sorry\n\n/-- The machine configuration translation. -/\ndef tr_cfg {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} [Inhabited Λ] {σ : Type u_3} [Inhabited σ] {n : ℕ} {enc : Γ → vector Bool n} (enc0 : enc Inhabited.default = vector.repeat false n) : TM1.cfg Γ Λ σ → TM1.cfg Bool Λ' σ :=\n sorry\n\ntheorem tr_tape'_move_left {Γ : Type u_1} [Inhabited Γ] {n : ℕ} {enc : Γ → vector Bool n} (enc0 : enc Inhabited.default = vector.repeat false n) (L : list_blank Γ) (R : list_blank Γ) : nat.iterate (tape.move dir.left) n (tr_tape' enc0 L R) =\n tr_tape' enc0 (list_blank.tail L) (list_blank.cons (list_blank.head L) R) := sorry\n\ntheorem tr_tape'_move_right {Γ : Type u_1} [Inhabited Γ] {n : ℕ} {enc : Γ → vector Bool n} (enc0 : enc Inhabited.default = vector.repeat false n) (L : list_blank Γ) (R : list_blank Γ) : nat.iterate (tape.move dir.right) n (tr_tape' enc0 L R) =\n tr_tape' enc0 (list_blank.cons (list_blank.head R) L) (list_blank.tail R) := sorry\n\ntheorem step_aux_write {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} [Inhabited Λ] {σ : Type u_3} [Inhabited σ] {n : ℕ} {enc : Γ → vector Bool n} (enc0 : enc Inhabited.default = vector.repeat false n) (q : TM1.stmt Bool Λ' σ) (v : σ) (a : Γ) (b : Γ) (L : list_blank Γ) (R : list_blank Γ) : TM1.step_aux (write (vector.to_list (enc a)) q) v (tr_tape' enc0 L (list_blank.cons b R)) =\n TM1.step_aux q v (tr_tape' enc0 (list_blank.cons a L) R) := sorry\n\ntheorem step_aux_read {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} [Inhabited Λ] {σ : Type u_3} [Inhabited σ] {n : ℕ} {enc : Γ → vector Bool n} (dec : vector Bool n → Γ) (enc0 : enc Inhabited.default = vector.repeat false n) (encdec : ∀ (a : Γ), dec (enc a) = a) (f : Γ → TM1.stmt Bool Λ' σ) (v : σ) (L : list_blank Γ) (R : list_blank Γ) : TM1.step_aux (read dec f) v (tr_tape' enc0 L R) = TM1.step_aux (f (list_blank.head R)) v (tr_tape' enc0 L R) := sorry\n\ntheorem tr_respects {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} [Inhabited Λ] {σ : Type u_3} [Inhabited σ] {n : ℕ} {enc : Γ → vector Bool n} (dec : vector Bool n → Γ) (enc0 : enc Inhabited.default = vector.repeat false n) (M : Λ → TM1.stmt Γ Λ σ) (encdec : ∀ (a : Γ), dec (enc a) = a) : respects (TM1.step M) (TM1.step (tr enc dec M)) fun (c₁ : TM1.cfg Γ Λ σ) (c₂ : TM1.cfg Bool Λ' σ) => tr_cfg enc0 c₁ = c₂ := sorry\n\n/-- The set of accessible `Λ'.write` machine states. -/\ndef writes {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} [Inhabited Λ] {σ : Type u_3} [Inhabited σ] [fintype Γ] : TM1.stmt Γ Λ σ → finset Λ' :=\n sorry\n\n/-- The set of accessible machine states, assuming that the input machine is supported on `S`,\nare the normal states embedded from `S`, plus all write states accessible from these states. -/\ndef tr_supp {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} [Inhabited Λ] {σ : Type u_3} [Inhabited σ] (M : Λ → TM1.stmt Γ Λ σ) [fintype Γ] (S : finset Λ) : finset Λ' :=\n finset.bUnion S fun (l : Λ) => insert (Λ'.normal l) (writes (M l))\n\ntheorem tr_supports {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} [Inhabited Λ] {σ : Type u_3} [Inhabited σ] {n : ℕ} {enc : Γ → vector Bool n} (dec : vector Bool n → Γ) (M : Λ → TM1.stmt Γ Λ σ) [fintype Γ] {S : finset Λ} (ss : TM1.supports M S) : TM1.supports (tr enc dec M) (tr_supp M S) := sorry\n\nend TM1to1\n\n\n/-!\n## TM0 emulator in TM1\n\nTo establish that TM0 and TM1 are equivalent computational models, we must also have a TM0 emulator\nin TM1. The main complication here is that TM0 allows an action to depend on the value at the head\nand local state, while TM1 doesn't (in order to have more programming language-like semantics).\nSo we use a computed `goto` to go to a state that performes the desired action and then returns to\nnormal execution.\n\nOne issue with this is that the `halt` instruction is supposed to halt immediately, not take a step\nto a halting state. To resolve this we do a check for `halt` first, then `goto` (with an\nunreachable branch).\n-/\n\nnamespace TM0to1\n\n\n/-- The machine states for a TM1 emulating a TM0 machine. States of the TM0 machine are embedded\nas `normal q` states, but the actual operation is split into two parts, a jump to `act s q`\nfollowed by the action and a jump to the next `normal` state. -/\ninductive Λ' {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} [Inhabited Λ] \nwhere\n| normal : Λ → Λ'\n| act : TM0.stmt Γ → Λ → Λ'\n\nprotected instance Λ'.inhabited {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} [Inhabited Λ] : Inhabited Λ' :=\n { default := Λ'.normal Inhabited.default }\n\n/-- The program. -/\ndef tr {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} [Inhabited Λ] (M : TM0.machine Γ Λ) : Λ' → TM1.stmt Γ Λ' Unit :=\n sorry\n\n/-- The configuration translation. -/\ndef tr_cfg {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} [Inhabited Λ] (M : TM0.machine Γ Λ) : TM0.cfg Γ Λ → TM1.cfg Γ Λ' Unit :=\n sorry\n\ntheorem tr_respects {Γ : Type u_1} [Inhabited Γ] {Λ : Type u_2} [Inhabited Λ] (M : TM0.machine Γ Λ) : respects (TM0.step M) (TM1.step (tr M)) fun (a : TM0.cfg Γ Λ) (b : TM1.cfg Γ Λ' Unit) => tr_cfg M a = b := sorry\n\nend TM0to1\n\n\n/-!\n## The TM2 model\n\nThe TM2 model removes the tape entirely from the TM1 model, replacing it with an arbitrary (finite)\ncollection of stacks, each with elements of different types (the alphabet of stack `k : K` is\n`Γ k`). The statements are:\n\n* `push k (f : σ → Γ k) q` puts `f a` on the `k`-th stack, then does `q`.\n* `pop k (f : σ → option (Γ k) → σ) q` changes the state to `f a (S k).head`, where `S k` is the\n value of the `k`-th stack, and removes this element from the stack, then does `q`.\n* `peek k (f : σ → option (Γ k) → σ) q` changes the state to `f a (S k).head`, where `S k` is the\n value of the `k`-th stack, then does `q`.\n* `load (f : σ → σ) q` reads nothing but applies `f` to the internal state, then does `q`.\n* `branch (f : σ → bool) qtrue qfalse` does `qtrue` or `qfalse` according to `f a`.\n* `goto (f : σ → Λ)` jumps to label `f a`.\n* `halt` halts on the next step.\n\nThe configuration is a tuple `(l, var, stk)` where `l : option Λ` is the current label to run or\n`none` for the halting state, `var : σ` is the (finite) internal state, and `stk : ∀ k, list (Γ k)`\nis the collection of stacks. (Note that unlike the `TM0` and `TM1` models, these are not\n`list_blank`s, they have definite ends that can be detected by the `pop` command.)\n\nGiven a designated stack `k` and a value `L : list (Γ k)`, the initial configuration has all the\nstacks empty except the designated \"input\" stack; in `eval` this designated stack also functions\nas the output stack.\n-/\n\nnamespace TM2\n\n\n/-- The TM2 model removes the tape entirely from the TM1 model,\n replacing it with an arbitrary (finite) collection of stacks.\n The operation `push` puts an element on one of the stacks,\n and `pop` removes an element from a stack (and modifying the\n internal state based on the result). `peek` modifies the\n internal state but does not remove an element. -/\ninductive stmt {K : Type u_1} [DecidableEq K] (Γ : K → Type u_2) (Λ : Type u_3) (σ : Type u_4) \nwhere\n| push : (k : K) → (σ → Γ k) → stmt Γ Λ σ → stmt Γ Λ σ\n| peek : (k : K) → (σ → Option (Γ k) → σ) → stmt Γ Λ σ → stmt Γ Λ σ\n| pop : (k : K) → (σ → Option (Γ k) → σ) → stmt Γ Λ σ → stmt Γ Λ σ\n| load : (σ → σ) → stmt Γ Λ σ → stmt Γ Λ σ\n| branch : (σ → Bool) → stmt Γ Λ σ → stmt Γ Λ σ → stmt Γ Λ σ\n| goto : (σ → Λ) → stmt Γ Λ σ\n| halt : stmt Γ Λ σ\n\nprotected instance stmt.inhabited {K : Type u_1} [DecidableEq K] (Γ : K → Type u_2) (Λ : Type u_3) (σ : Type u_4) : Inhabited (stmt Γ Λ σ) :=\n { default := stmt.halt }\n\n/-- A configuration in the TM2 model is a label (or `none` for the halt state), the state of\nlocal variables, and the stacks. (Note that the stacks are not `list_blank`s, they have a definite\nsize.) -/\nstructure cfg {K : Type u_1} [DecidableEq K] (Γ : K → Type u_2) (Λ : Type u_3) (σ : Type u_4) \nwhere\n l : Option Λ\n var : σ\n stk : (k : K) → List (Γ k)\n\nprotected instance cfg.inhabited {K : Type u_1} [DecidableEq K] (Γ : K → Type u_2) (Λ : Type u_3) (σ : Type u_4) [Inhabited σ] : Inhabited (cfg Γ Λ σ) :=\n { default := cfg.mk Inhabited.default Inhabited.default Inhabited.default }\n\n/-- The step function for the TM2 model. -/\n@[simp] def step_aux {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} {Λ : Type u_3} {σ : Type u_4} : stmt Γ Λ σ → σ → ((k : K) → List (Γ k)) → cfg Γ Λ σ :=\n sorry\n\n/-- The step function for the TM2 model. -/\n@[simp] def step {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} {Λ : Type u_3} {σ : Type u_4} (M : Λ → stmt Γ Λ σ) : cfg Γ Λ σ → Option (cfg Γ Λ σ) :=\n sorry\n\n/-- The (reflexive) reachability relation for the TM2 model. -/\ndef reaches {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} {Λ : Type u_3} {σ : Type u_4} (M : Λ → stmt Γ Λ σ) : cfg Γ Λ σ → cfg Γ Λ σ → Prop :=\n relation.refl_trans_gen fun (a b : cfg Γ Λ σ) => b ∈ step M a\n\n/-- Given a set `S` of states, `support_stmt S q` means that `q` only jumps to states in `S`. -/\ndef supports_stmt {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} {Λ : Type u_3} {σ : Type u_4} (S : finset Λ) : stmt Γ Λ σ → Prop :=\n sorry\n\n/-- The set of subtree statements in a statement. -/\ndef stmts₁ {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} {Λ : Type u_3} {σ : Type u_4} : stmt Γ Λ σ → finset (stmt Γ Λ σ) :=\n sorry\n\ntheorem stmts₁_self {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} {Λ : Type u_3} {σ : Type u_4} {q : stmt Γ Λ σ} : q ∈ stmts₁ q := sorry\n\ntheorem stmts₁_trans {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} {Λ : Type u_3} {σ : Type u_4} {q₁ : stmt Γ Λ σ} {q₂ : stmt Γ Λ σ} : q₁ ∈ stmts₁ q₂ → stmts₁ q₁ ⊆ stmts₁ q₂ := sorry\n\ntheorem stmts₁_supports_stmt_mono {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} {Λ : Type u_3} {σ : Type u_4} {S : finset Λ} {q₁ : stmt Γ Λ σ} {q₂ : stmt Γ Λ σ} (h : q₁ ∈ stmts₁ q₂) (hs : supports_stmt S q₂) : supports_stmt S q₁ := sorry\n\n/-- The set of statements accessible from initial set `S` of labels. -/\ndef stmts {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} {Λ : Type u_3} {σ : Type u_4} (M : Λ → stmt Γ Λ σ) (S : finset Λ) : finset (Option (stmt Γ Λ σ)) :=\n finset.insert_none (finset.bUnion S fun (q : Λ) => stmts₁ (M q))\n\ntheorem stmts_trans {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} {Λ : Type u_3} {σ : Type u_4} {M : Λ → stmt Γ Λ σ} {S : finset Λ} {q₁ : stmt Γ Λ σ} {q₂ : stmt Γ Λ σ} (h₁ : q₁ ∈ stmts₁ q₂) : some q₂ ∈ stmts M S → some q₁ ∈ stmts M S := sorry\n\n/-- Given a TM2 machine `M` and a set `S` of states, `supports M S` means that all states in\n`S` jump only to other states in `S`. -/\ndef supports {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} {Λ : Type u_3} {σ : Type u_4} [Inhabited Λ] (M : Λ → stmt Γ Λ σ) (S : finset Λ) :=\n Inhabited.default ∈ S ∧ ∀ (q : Λ), q ∈ S → supports_stmt S (M q)\n\ntheorem stmts_supports_stmt {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} {Λ : Type u_3} {σ : Type u_4} [Inhabited Λ] {M : Λ → stmt Γ Λ σ} {S : finset Λ} {q : stmt Γ Λ σ} (ss : supports M S) : some q ∈ stmts M S → supports_stmt S q := sorry\n\ntheorem step_supports {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} {Λ : Type u_3} {σ : Type u_4} [Inhabited Λ] (M : Λ → stmt Γ Λ σ) {S : finset Λ} (ss : supports M S) {c : cfg Γ Λ σ} {c' : cfg Γ Λ σ} : c' ∈ step M c → cfg.l c ∈ finset.insert_none S → cfg.l c' ∈ finset.insert_none S := sorry\n\n/-- The initial state of the TM2 model. The input is provided on a designated stack. -/\ndef init {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} {Λ : Type u_3} {σ : Type u_4} [Inhabited Λ] [Inhabited σ] (k : K) (L : List (Γ k)) : cfg Γ Λ σ :=\n cfg.mk (some Inhabited.default) Inhabited.default (function.update (fun (_x : K) => []) k L)\n\n/-- Evaluates a TM2 program to completion, with the output on the same stack as the input. -/\ndef eval {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} {Λ : Type u_3} {σ : Type u_4} [Inhabited Λ] [Inhabited σ] (M : Λ → stmt Γ Λ σ) (k : K) (L : List (Γ k)) : roption (List (Γ k)) :=\n roption.map (fun (c : cfg Γ Λ σ) => cfg.stk c k) (eval (step M) (init k L))\n\nend TM2\n\n\n/-!\n## TM2 emulator in TM1\n\nTo prove that TM2 computable functions are TM1 computable, we need to reduce each TM2 program to a\nTM1 program. So suppose a TM2 program is given. This program has to maintain a whole collection of\nstacks, but we have only one tape, so we must \"multiplex\" them all together. Pictorially, if stack\n1 contains `[a, b]` and stack 2 contains `[c, d, e, f]` then the tape looks like this:\n\n```\n bottom: ... | _ | T | _ | _ | _ | _ | ...\n stack 1: ... | _ | b | a | _ | _ | _ | ...\n stack 2: ... | _ | f | e | d | c | _ | ...\n```\n\nwhere a tape element is a vertical slice through the diagram. Here the alphabet is\n`Γ' := bool × ∀ k, option (Γ k)`, where:\n\n* `bottom : bool` is marked only in one place, the initial position of the TM, and represents the\n tail of all stacks. It is never modified.\n* `stk k : option (Γ k)` is the value of the `k`-th stack, if in range, otherwise `none` (which is\n the blank value). Note that the head of the stack is at the far end; this is so that push and pop\n don't have to do any shifting.\n\nIn \"resting\" position, the TM is sitting at the position marked `bottom`. For non-stack actions,\nit operates in place, but for the stack actions `push`, `peek`, and `pop`, it must shuttle to the\nend of the appropriate stack, make its changes, and then return to the bottom. So the states are:\n\n* `normal (l : Λ)`: waiting at `bottom` to execute function `l`\n* `go k (s : st_act k) (q : stmt₂)`: travelling to the right to get to the end of stack `k` in\n order to perform stack action `s`, and later continue with executing `q`\n* `ret (q : stmt₂)`: travelling to the left after having performed a stack action, and executing\n `q` once we arrive\n\nBecause of the shuttling, emulation overhead is `O(n)`, where `n` is the current maximum of the\nlength of all stacks. Therefore a program that takes `k` steps to run in TM2 takes `O((m+k)k)`\nsteps to run when emulated in TM1, where `m` is the length of the input.\n-/\n\nnamespace TM2to1\n\n\n-- A displaced lemma proved in unnecessary generality\n\ntheorem stk_nth_val {K : Type u_1} {Γ : K → Type u_2} {L : list_blank ((k : K) → Option (Γ k))} {k : K} {S : List (Γ k)} (n : ℕ) (hL : list_blank.map (proj k) L = list_blank.mk (list.reverse (list.map some S))) : list_blank.nth L n k = list.nth (list.reverse S) n := sorry\n\n/-- The alphabet of the TM2 simulator on TM1 is a marker for the stack bottom,\nplus a vector of stack elements for each stack, or none if the stack does not extend this far. -/\n-- the decidable_eq assumption, and this is a local definition anyway so it's not important.\n\ndef Γ' {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} :=\n Bool × ((k : K) → Option (Γ k))\n\nprotected instance Γ'.inhabited {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} : Inhabited Γ' :=\n { default := (false, fun (_x : K) => none) }\n\nprotected instance Γ'.fintype {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} [fintype K] [(k : K) → fintype (Γ k)] : fintype Γ' :=\n prod.fintype Bool ((k : K) → Option (Γ k))\n\n/-- The bottom marker is fixed throughout the calculation, so we use the `add_bottom` function\nto express the program state in terms of a tape with only the stacks themselves. -/\ndef add_bottom {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} (L : list_blank ((k : K) → Option (Γ k))) : list_blank Γ' :=\n list_blank.cons (tt, list_blank.head L) (list_blank.map (pointed_map.mk (Prod.mk false) sorry) (list_blank.tail L))\n\ntheorem add_bottom_map {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} (L : list_blank ((k : K) → Option (Γ k))) : list_blank.map (pointed_map.mk prod.snd rfl) (add_bottom L) = L := sorry\n\ntheorem add_bottom_modify_nth {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} (f : ((k : K) → Option (Γ k)) → (k : K) → Option (Γ k)) (L : list_blank ((k : K) → Option (Γ k))) (n : ℕ) : list_blank.modify_nth (fun (a : Γ') => (prod.fst a, f (prod.snd a))) n (add_bottom L) =\n add_bottom (list_blank.modify_nth f n L) := sorry\n\ntheorem add_bottom_nth_snd {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} (L : list_blank ((k : K) → Option (Γ k))) (n : ℕ) : prod.snd (list_blank.nth (add_bottom L) n) = list_blank.nth L n := sorry\n\ntheorem add_bottom_nth_succ_fst {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} (L : list_blank ((k : K) → Option (Γ k))) (n : ℕ) : prod.fst (list_blank.nth (add_bottom L) (n + 1)) = false := sorry\n\ntheorem add_bottom_head_fst {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} (L : list_blank ((k : K) → Option (Γ k))) : prod.fst (list_blank.head (add_bottom L)) = tt := sorry\n\n/-- A stack action is a command that interacts with the top of a stack. Our default position\nis at the bottom of all the stacks, so we have to hold on to this action while going to the end\nto modify the stack. -/\ninductive st_act {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} {σ : Type u_4} [Inhabited σ] (k : K) \nwhere\n| push : (σ → Γ k) → st_act k\n| peek : (σ → Option (Γ k) → σ) → st_act k\n| pop : (σ → Option (Γ k) → σ) → st_act k\n\nprotected instance st_act.inhabited {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} {σ : Type u_4} [Inhabited σ] {k : K} : Inhabited (st_act k) :=\n { default := st_act.peek fun (s : σ) (_x : Option (Γ k)) => s }\n\n/-- The TM2 statement corresponding to a stack action. -/\n-- it is worth to omit the typeclass assumption without breaking the parameters\n\ndef st_run {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} {Λ : Type u_3} [Inhabited Λ] {σ : Type u_4} [Inhabited σ] {k : K} : st_act k → TM2.stmt Γ Λ σ → TM2.stmt Γ Λ σ :=\n sorry\n\n/-- The effect of a stack action on the local variables, given the value of the stack. -/\ndef st_var {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} {σ : Type u_4} [Inhabited σ] {k : K} (v : σ) (l : List (Γ k)) : st_act k → σ :=\n sorry\n\n/-- The effect of a stack action on the stack. -/\ndef st_write {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} {σ : Type u_4} [Inhabited σ] {k : K} (v : σ) (l : List (Γ k)) : st_act k → List (Γ k) :=\n sorry\n\n/-- We have partitioned the TM2 statements into \"stack actions\", which require going to the end\nof the stack, and all other actions, which do not. This is a modified recursor which lumps the\nstack actions into one. -/\ndef stmt_st_rec {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} {Λ : Type u_3} [Inhabited Λ] {σ : Type u_4} [Inhabited σ] {C : TM2.stmt Γ Λ σ → Sort l} (H₁ : (k : K) → (s : st_act k) → (q : TM2.stmt Γ Λ σ) → C q → C (st_run s q)) (H₂ : (a : σ → σ) → (q : TM2.stmt Γ Λ σ) → C q → C (TM2.stmt.load a q)) (H₃ : (p : σ → Bool) → (q₁ q₂ : TM2.stmt Γ Λ σ) → C q₁ → C q₂ → C (TM2.stmt.branch p q₁ q₂)) (H₄ : (l : σ → Λ) → C (TM2.stmt.goto l)) (H₅ : C TM2.stmt.halt) (n : TM2.stmt Γ Λ σ) : C n :=\n sorry\n\ntheorem supports_run {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} {Λ : Type u_3} [Inhabited Λ] {σ : Type u_4} [Inhabited σ] (S : finset Λ) {k : K} (s : st_act k) (q : TM2.stmt Γ Λ σ) : TM2.supports_stmt S (st_run s q) ↔ TM2.supports_stmt S q :=\n st_act.cases_on s (fun (s : σ → Γ k) => iff.refl (TM2.supports_stmt S (st_run (st_act.push s) q)))\n (fun (s : σ → Option (Γ k) → σ) => iff.refl (TM2.supports_stmt S (st_run (st_act.peek s) q)))\n fun (s : σ → Option (Γ k) → σ) => iff.refl (TM2.supports_stmt S (st_run (st_act.pop s) q))\n\n/-- The machine states of the TM2 emulator. We can either be in a normal state when waiting for the\nnext TM2 action, or we can be in the \"go\" and \"return\" states to go to the top of the stack and\nreturn to the bottom, respectively. -/\ninductive Λ' {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} {Λ : Type u_3} [Inhabited Λ] {σ : Type u_4} [Inhabited σ] \nwhere\n| normal : Λ → Λ'\n| go : (k : K) → st_act k → TM2.stmt Γ Λ σ → Λ'\n| ret : TM2.stmt Γ Λ σ → Λ'\n\nprotected instance Λ'.inhabited {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} {Λ : Type u_3} [Inhabited Λ] {σ : Type u_4} [Inhabited σ] : Inhabited Λ' :=\n { default := Λ'.normal Inhabited.default }\n\n/-- The program corresponding to state transitions at the end of a stack. Here we start out just\nafter the top of the stack, and should end just after the new top of the stack. -/\ndef tr_st_act {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} {Λ : Type u_3} [Inhabited Λ] {σ : Type u_4} [Inhabited σ] {k : K} (q : TM1.stmt Γ' Λ' σ) : st_act k → TM1.stmt Γ' Λ' σ :=\n sorry\n\n/-- The initial state for the TM2 emulator, given an initial TM2 state. All stacks start out empty\nexcept for the input stack, and the stack bottom mark is set at the head. -/\ndef tr_init {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} (k : K) (L : List (Γ k)) : List Γ' :=\n let L' : List Γ' := list.map (fun (a : Γ k) => (false, function.update (fun (_x : K) => none) k ↑a)) (list.reverse L);\n (tt, prod.snd (list.head L')) :: list.tail L'\n\ntheorem step_run {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} {Λ : Type u_3} [Inhabited Λ] {σ : Type u_4} [Inhabited σ] {k : K} (q : TM2.stmt Γ Λ σ) (v : σ) (S : (k : K) → List (Γ k)) (s : st_act k) : TM2.step_aux (st_run s q) v S = TM2.step_aux q (st_var v (S k) s) (function.update S k (st_write v (S k) s)) := sorry\n\n/-- The translation of TM2 statements to TM1 statements. regular actions have direct equivalents,\nbut stack actions are deferred by going to the corresponding `go` state, so that we can find the\nappropriate stack top. -/\ndef tr_normal {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} {Λ : Type u_3} [Inhabited Λ] {σ : Type u_4} [Inhabited σ] : TM2.stmt Γ Λ σ → TM1.stmt Γ' Λ' σ :=\n sorry\n\ntheorem tr_normal_run {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} {Λ : Type u_3} [Inhabited Λ] {σ : Type u_4} [Inhabited σ] {k : K} (s : st_act k) (q : TM2.stmt Γ Λ σ) : tr_normal (st_run s q) = TM1.stmt.goto fun (_x : Γ') (_x : σ) => Λ'.go k s q :=\n st_act.cases_on s (fun (s : σ → Γ k) => Eq.refl (tr_normal (st_run (st_act.push s) q)))\n (fun (s : σ → Option (Γ k) → σ) => Eq.refl (tr_normal (st_run (st_act.peek s) q)))\n fun (s : σ → Option (Γ k) → σ) => Eq.refl (tr_normal (st_run (st_act.pop s) q))\n\n/-- The set of machine states accessible from an initial TM2 statement. -/\ndef tr_stmts₁ {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} {Λ : Type u_3} [Inhabited Λ] {σ : Type u_4} [Inhabited σ] : TM2.stmt Γ Λ σ → finset Λ' :=\n sorry\n\ntheorem tr_stmts₁_run {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} {Λ : Type u_3} [Inhabited Λ] {σ : Type u_4} [Inhabited σ] {k : K} {s : st_act k} {q : TM2.stmt Γ Λ σ} : tr_stmts₁ (st_run s q) = insert (Λ'.go k s q) (singleton (Λ'.ret q)) ∪ tr_stmts₁ q := sorry\n\ntheorem tr_respects_aux₂ {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} {Λ : Type u_3} [Inhabited Λ] {σ : Type u_4} [Inhabited σ] {k : K} {q : TM1.stmt Γ' Λ' σ} {v : σ} {S : (k : K) → List (Γ k)} {L : list_blank ((k : K) → Option (Γ k))} (hL : ∀ (k : K), list_blank.map (proj k) L = list_blank.mk (list.reverse (list.map some (S k)))) (o : st_act k) : let v' : σ := st_var v (S k) o;\nlet Sk' : List (Γ k) := st_write v (S k) o;\nlet S' : (k : K) → List (Γ k) := function.update S k Sk';\n∃ (L' : list_blank ((k : K) → Option (Γ k))),\n (∀ (k : K), list_blank.map (proj k) L' = list_blank.mk (list.reverse (list.map some (S' k)))) ∧\n TM1.step_aux (tr_st_act q o) v (nat.iterate (tape.move dir.right) (list.length (S k)) (tape.mk' ∅ (add_bottom L))) =\n TM1.step_aux q v' (nat.iterate (tape.move dir.right) (list.length (S' k)) (tape.mk' ∅ (add_bottom L'))) := sorry\n\n/-- The TM2 emulator machine states written as a TM1 program.\nThis handles the `go` and `ret` states, which shuttle to and from a stack top. -/\ndef tr {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} {Λ : Type u_3} [Inhabited Λ] {σ : Type u_4} [Inhabited σ] (M : Λ → TM2.stmt Γ Λ σ) : Λ' → TM1.stmt Γ' Λ' σ :=\n sorry\n\n/-- The relation between TM2 configurations and TM1 configurations of the TM2 emulator. -/\ninductive tr_cfg {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} {Λ : Type u_3} [Inhabited Λ] {σ : Type u_4} [Inhabited σ] (M : Λ → TM2.stmt Γ Λ σ) : TM2.cfg Γ Λ σ → TM1.cfg Γ' Λ' σ → Prop\nwhere\n| mk : ∀ {q : Option Λ} {v : σ} {S : (k : K) → List (Γ k)} (L : list_blank ((k : K) → Option (Γ k))),\n (∀ (k : K), list_blank.map (proj k) L = list_blank.mk (list.reverse (list.map some (S k)))) →\n tr_cfg M (TM2.cfg.mk q v S) (TM1.cfg.mk (option.map Λ'.normal q) v (tape.mk' ∅ (add_bottom L)))\n\ntheorem tr_respects_aux₁ {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} {Λ : Type u_3} [Inhabited Λ] {σ : Type u_4} [Inhabited σ] (M : Λ → TM2.stmt Γ Λ σ) {k : K} (o : st_act k) (q : TM2.stmt Γ Λ σ) (v : σ) {S : List (Γ k)} {L : list_blank ((k : K) → Option (Γ k))} (hL : list_blank.map (proj k) L = list_blank.mk (list.reverse (list.map some S))) (n : ℕ) (H : n ≤ list.length S) : reaches₀ (TM1.step (tr M)) (TM1.cfg.mk (some (Λ'.go k o q)) v (tape.mk' ∅ (add_bottom L)))\n (TM1.cfg.mk (some (Λ'.go k o q)) v (nat.iterate (tape.move dir.right) n (tape.mk' ∅ (add_bottom L)))) := sorry\n\ntheorem tr_respects_aux₃ {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} {Λ : Type u_3} [Inhabited Λ] {σ : Type u_4} [Inhabited σ] (M : Λ → TM2.stmt Γ Λ σ) {q : TM2.stmt Γ Λ σ} {v : σ} {L : list_blank ((k : K) → Option (Γ k))} (n : ℕ) : reaches₀ (TM1.step (tr M))\n (TM1.cfg.mk (some (Λ'.ret q)) v (nat.iterate (tape.move dir.right) n (tape.mk' ∅ (add_bottom L))))\n (TM1.cfg.mk (some (Λ'.ret q)) v (tape.mk' ∅ (add_bottom L))) := sorry\n\ntheorem tr_respects_aux {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} {Λ : Type u_3} [Inhabited Λ] {σ : Type u_4} [Inhabited σ] (M : Λ → TM2.stmt Γ Λ σ) {q : TM2.stmt Γ Λ σ} {v : σ} {T : list_blank ((i : K) → Option (Γ i))} {k : K} {S : (k : K) → List (Γ k)} (hT : ∀ (k : K), list_blank.map (proj k) T = list_blank.mk (list.reverse (list.map some (S k)))) (o : st_act k) (IH : ∀ {v : σ} {S : (k : K) → List (Γ k)} {T : list_blank ((i : K) → Option (Γ i))},\n (∀ (k : K), list_blank.map (proj k) T = list_blank.mk (list.reverse (list.map some (S k)))) →\n ∃ (b : TM1.cfg Γ' Λ' σ),\n tr_cfg M (TM2.step_aux q v S) b ∧\n reaches (TM1.step (tr M)) (TM1.step_aux (tr_normal q) v (tape.mk' ∅ (add_bottom T))) b) : ∃ (b : TM1.cfg Γ' Λ' σ),\n tr_cfg M (TM2.step_aux (st_run o q) v S) b ∧\n reaches (TM1.step (tr M)) (TM1.step_aux (tr_normal (st_run o q)) v (tape.mk' ∅ (add_bottom T))) b := sorry\n\ntheorem tr_respects {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} {Λ : Type u_3} [Inhabited Λ] {σ : Type u_4} [Inhabited σ] (M : Λ → TM2.stmt Γ Λ σ) : respects (TM2.step M) (TM1.step (tr M)) (tr_cfg M) := sorry\n\ntheorem tr_cfg_init {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} {Λ : Type u_3} [Inhabited Λ] {σ : Type u_4} [Inhabited σ] (M : Λ → TM2.stmt Γ Λ σ) (k : K) (L : List (Γ k)) : tr_cfg M (TM2.init k L) (TM1.init (tr_init k L)) := sorry\n\ntheorem tr_eval_dom {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} {Λ : Type u_3} [Inhabited Λ] {σ : Type u_4} [Inhabited σ] (M : Λ → TM2.stmt Γ Λ σ) (k : K) (L : List (Γ k)) : roption.dom (TM1.eval (tr M) (tr_init k L)) ↔ roption.dom (TM2.eval M k L) :=\n tr_eval_dom (tr_respects M) (tr_cfg_init M k L)\n\ntheorem tr_eval {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} {Λ : Type u_3} [Inhabited Λ] {σ : Type u_4} [Inhabited σ] (M : Λ → TM2.stmt Γ Λ σ) (k : K) (L : List (Γ k)) {L₁ : list_blank Γ'} {L₂ : List (Γ k)} (H₁ : L₁ ∈ TM1.eval (tr M) (tr_init k L)) (H₂ : L₂ ∈ TM2.eval M k L) : ∃ (S : (k : K) → List (Γ k)),\n ∃ (L' : list_blank ((k : K) → Option (Γ k))),\n add_bottom L' = L₁ ∧\n (∀ (k : K), list_blank.map (proj k) L' = list_blank.mk (list.reverse (list.map some (S k)))) ∧ S k = L₂ := sorry\n\n/-- The support of a set of TM2 states in the TM2 emulator. -/\ndef tr_supp {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} {Λ : Type u_3} [Inhabited Λ] {σ : Type u_4} [Inhabited σ] (M : Λ → TM2.stmt Γ Λ σ) (S : finset Λ) : finset Λ' :=\n finset.bUnion S fun (l : Λ) => insert (Λ'.normal l) (tr_stmts₁ (M l))\n\ntheorem tr_supports {K : Type u_1} [DecidableEq K] {Γ : K → Type u_2} {Λ : Type u_3} [Inhabited Λ] {σ : Type u_4} [Inhabited σ] (M : Λ → TM2.stmt Γ Λ σ) {S : finset Λ} (ss : TM2.supports M S) : TM1.supports (tr M) (tr_supp M S) := sorry\n\n", "meta": {"author": "AurelienSaue", "repo": "Mathlib4_auto", "sha": "590df64109b08190abe22358fabc3eae000943f2", "save_path": "github-repos/lean/AurelienSaue-Mathlib4_auto", "path": "github-repos/lean/AurelienSaue-Mathlib4_auto/Mathlib4_auto-590df64109b08190abe22358fabc3eae000943f2/Mathlib/computability/turing_machine.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4649015713733885, "lm_q2_score": 0.059210252401406344, "lm_q1q2_score": 0.02752693938282876}} {"text": "/-\nCopyright (c) 2017 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Leonardo de Moura\n\n! This file was ported from Lean 3 source module init.meta.smt.interactive\n! leanprover-community/mathlib commit fb0b2a8d50453c4a5c63503d5d58746fe9f5deb8\n! Please do not edit these lines, except to modify the commit id\n! if you have ported upstream changes.\n-/\nprelude\nimport Leanbin.Init.Meta.Smt.SmtTactic\nimport Leanbin.Init.Meta.InteractiveBase\nimport Leanbin.Init.Meta.Smt.Rsimp\n\nnamespace SmtTactic\n\nunsafe def save_info (p : Pos) : smt_tactic Unit := do\n let (ss, ts) ← smt_tactic.read\n tactic.save_info_thunk p fun _ => smt_state.to_format ss ts\n#align smt_tactic.save_info smt_tactic.save_info\n\nunsafe def skip : smt_tactic Unit :=\n return ()\n#align smt_tactic.skip smt_tactic.skip\n\nunsafe def solve_goals : smt_tactic Unit :=\n iterate close\n#align smt_tactic.solve_goals smt_tactic.solve_goals\n\nunsafe def step {α : Type} (tac : smt_tactic α) : smt_tactic Unit :=\n tac >> solve_goals\n#align smt_tactic.step smt_tactic.step\n\nunsafe def istep {α : Type} (line0 col0 line col ast : Nat) (tac : smt_tactic α) :\n smt_tactic Unit :=\n ⟨fun ss ts =>\n (@scopeTrace _ line col fun _ => tactic.with_ast ast ((tac >> solve_goals).run ss) ts).clamp_pos\n line0 line col⟩\n#align smt_tactic.istep smt_tactic.istep\n\nunsafe def execute (tac : smt_tactic Unit) : tactic Unit :=\n using_smt tac\n#align smt_tactic.execute smt_tactic.execute\n\nunsafe def execute_with (cfg : SmtConfig) (tac : smt_tactic Unit) : tactic Unit :=\n using_smt tac cfg\n#align smt_tactic.execute_with smt_tactic.execute_with\n\nunsafe instance : interactive.executor smt_tactic\n where\n config_type := SmtConfig\n Inhabited := ⟨{ }⟩\n execute_with cfg tac := using_smt tac cfg\n\nnamespace Interactive\n\nopen Lean.Parser\n\nopen _Root_.Interactive\n\nopen Interactive.Types\n\n-- mathport name: «expr ?»\nlocal postfix:1024 \"?\" => optional\n\n-- mathport name: «expr *»\nlocal postfix:1024 \"*\" => many\n\nunsafe def itactic : Type :=\n smt_tactic Unit\n#align smt_tactic.interactive.itactic smt_tactic.interactive.itactic\n\nunsafe def intros : parse ident* → smt_tactic Unit\n | [] => smt_tactic.intros\n | hs => smt_tactic.intro_lst hs\n#align smt_tactic.interactive.intros smt_tactic.interactive.intros\n\n/-- Try to close main goal by using equalities implied by the congruence\n closure module.\n-/\nunsafe def close : smt_tactic Unit :=\n smt_tactic.close\n#align smt_tactic.interactive.close smt_tactic.interactive.close\n\n/-- Produce new facts using heuristic lemma instantiation based on E-matching.\n This tactic tries to match patterns from lemmas in the main goal with terms\n in the main goal. The set of lemmas is populated with theorems\n tagged with the attribute specified at smt_config.em_attr, and lemmas\n added using tactics such as `smt_tactic.add_lemmas`.\n The current set of lemmas can be retrieved using the tactic `smt_tactic.get_lemmas`.\n-/\nunsafe def ematch : smt_tactic Unit :=\n smt_tactic.ematch\n#align smt_tactic.interactive.ematch smt_tactic.interactive.ematch\n\nunsafe def apply (q : parse texpr) : smt_tactic Unit :=\n tactic.interactive.apply q\n#align smt_tactic.interactive.apply smt_tactic.interactive.apply\n\nunsafe def fapply (q : parse texpr) : smt_tactic Unit :=\n tactic.interactive.fapply q\n#align smt_tactic.interactive.fapply smt_tactic.interactive.fapply\n\nunsafe def apply_instance : smt_tactic Unit :=\n tactic.apply_instance\n#align smt_tactic.interactive.apply_instance smt_tactic.interactive.apply_instance\n\nunsafe def change (q : parse texpr) : smt_tactic Unit :=\n tactic.interactive.change q none (Loc.ns [none])\n#align smt_tactic.interactive.change smt_tactic.interactive.change\n\nunsafe def exact (q : parse texpr) : smt_tactic Unit :=\n tactic.interactive.exact q\n#align smt_tactic.interactive.exact smt_tactic.interactive.exact\n\nunsafe def from :=\n exact\n#align smt_tactic.interactive.from smt_tactic.interactive.from\n\nunsafe def assume :=\n tactic.interactive.assume\n#align smt_tactic.interactive.assume smt_tactic.interactive.assume\n\nunsafe def have (h : parse ident ?) (q₁ : parse (tk \":\" *> texpr)?)\n (q₂ : parse <| (tk \":=\" *> texpr)?) : smt_tactic Unit :=\n let h := h.getD `this\n (match q₁, q₂ with\n | some e, some p => do\n let t ← tactic.to_expr e\n let v ← tactic.to_expr ``(($(p) : $(t)))\n smt_tactic.assertv h t v\n | none, some p => do\n let p ← tactic.to_expr p\n smt_tactic.note h none p\n | some e, none => tactic.to_expr e >>= smt_tactic.assert h\n | none, none => do\n let u ← tactic.mk_meta_univ\n let e ← tactic.mk_meta_var (expr.sort u)\n smt_tactic.assert h e) >>\n return ()\n#align smt_tactic.interactive.have smt_tactic.interactive.have\n\nunsafe def let (h : parse ident ?) (q₁ : parse (tk \":\" *> texpr)?)\n (q₂ : parse <| (tk \":=\" *> texpr)?) : smt_tactic Unit :=\n let h := h.getD `this\n (match q₁, q₂ with\n | some e, some p => do\n let t ← tactic.to_expr e\n let v ← tactic.to_expr ``(($(p) : $(t)))\n smt_tactic.definev h t v\n | none, some p => do\n let p ← tactic.to_expr p\n smt_tactic.pose h none p\n | some e, none => tactic.to_expr e >>= smt_tactic.define h\n | none, none => do\n let u ← tactic.mk_meta_univ\n let e ← tactic.mk_meta_var (expr.sort u)\n smt_tactic.define h e) >>\n return ()\n#align smt_tactic.interactive.let smt_tactic.interactive.let\n\nunsafe def add_fact (q : parse texpr) : smt_tactic Unit := do\n let h ← tactic.get_unused_name `h none\n let p ← tactic.to_expr_strict q\n smt_tactic.note h none p\n#align smt_tactic.interactive.add_fact smt_tactic.interactive.add_fact\n\nunsafe def trace_state : smt_tactic Unit :=\n smt_tactic.trace_state\n#align smt_tactic.interactive.trace_state smt_tactic.interactive.trace_state\n\nunsafe def trace {α : Type} [has_to_tactic_format α] (a : α) : smt_tactic Unit :=\n tactic.trace a\n#align smt_tactic.interactive.trace smt_tactic.interactive.trace\n\nunsafe def destruct (q : parse texpr) : smt_tactic Unit := do\n let p ← tactic.to_expr_strict q\n smt_tactic.destruct p\n#align smt_tactic.interactive.destruct smt_tactic.interactive.destruct\n\nunsafe def by_cases (q : parse texpr) : smt_tactic Unit := do\n let p ← tactic.to_expr_strict q\n smt_tactic.by_cases p\n#align smt_tactic.interactive.by_cases smt_tactic.interactive.by_cases\n\nunsafe def by_contradiction : smt_tactic Unit :=\n smt_tactic.by_contradiction\n#align smt_tactic.interactive.by_contradiction smt_tactic.interactive.by_contradiction\n\nunsafe def by_contra : smt_tactic Unit :=\n smt_tactic.by_contradiction\n#align smt_tactic.interactive.by_contra smt_tactic.interactive.by_contra\n\nopen Tactic (resolve_name Transparency to_expr)\n\nprivate unsafe def report_invalid_em_lemma {α : Type} (n : Name) : smt_tactic α :=\n fail f! \"invalid ematch lemma '{n}'\"\n#align smt_tactic.interactive.report_invalid_em_lemma smt_tactic.interactive.report_invalid_em_lemma\n\nprivate unsafe def add_lemma_name (md : Transparency) (lhs_lemma : Bool) (n : Name) (ref : pexpr) :\n smt_tactic Unit := do\n let p ← resolve_name n\n match p with\n | expr.const n _ =>\n add_ematch_lemma_from_decl_core md lhs_lemma n >> tactic.save_const_type_info n ref <|>\n report_invalid_em_lemma n\n | _ =>\n (do\n let e ← to_expr p\n add_ematch_lemma_core md lhs_lemma e >> try (tactic.save_type_info e ref)) <|>\n report_invalid_em_lemma n\n#align smt_tactic.interactive.add_lemma_name smt_tactic.interactive.add_lemma_name\n\nprivate unsafe def add_lemma_pexpr (md : Transparency) (lhs_lemma : Bool) (p : pexpr) :\n smt_tactic Unit :=\n match p with\n | expr.const c [] => add_lemma_name md lhs_lemma c p\n | expr.local_const c _ _ _ => add_lemma_name md lhs_lemma c p\n | _ => do\n let new_e ← to_expr p\n add_ematch_lemma_core md lhs_lemma new_e\n#align smt_tactic.interactive.add_lemma_pexpr smt_tactic.interactive.add_lemma_pexpr\n\nprivate unsafe def add_lemma_pexprs (md : Transparency) (lhs_lemma : Bool) :\n List pexpr → smt_tactic Unit\n | [] => return ()\n | p :: ps => add_lemma_pexpr md lhs_lemma p >> add_lemma_pexprs ps\n#align smt_tactic.interactive.add_lemma_pexprs smt_tactic.interactive.add_lemma_pexprs\n\nunsafe def add_lemma (l : parse pexpr_list_or_texpr) : smt_tactic Unit :=\n add_lemma_pexprs reducible false l\n#align smt_tactic.interactive.add_lemma smt_tactic.interactive.add_lemma\n\nunsafe def add_lhs_lemma (l : parse pexpr_list_or_texpr) : smt_tactic Unit :=\n add_lemma_pexprs reducible true l\n#align smt_tactic.interactive.add_lhs_lemma smt_tactic.interactive.add_lhs_lemma\n\nprivate unsafe def add_eqn_lemmas_for_core (md : Transparency) : List Name → smt_tactic Unit\n | [] => return ()\n | c :: cs => do\n let p ← resolve_name c\n match p with\n | expr.const n _ => add_ematch_eqn_lemmas_for_core md n >> add_eqn_lemmas_for_core cs\n | _ => fail f! \"'{c}' is not a constant\"\n#align smt_tactic.interactive.add_eqn_lemmas_for_core smt_tactic.interactive.add_eqn_lemmas_for_core\n\nunsafe def add_eqn_lemmas_for (ids : parse ident*) : smt_tactic Unit :=\n add_eqn_lemmas_for_core reducible ids\n#align smt_tactic.interactive.add_eqn_lemmas_for smt_tactic.interactive.add_eqn_lemmas_for\n\nunsafe def add_eqn_lemmas (ids : parse ident*) : smt_tactic Unit :=\n add_eqn_lemmas_for ids\n#align smt_tactic.interactive.add_eqn_lemmas smt_tactic.interactive.add_eqn_lemmas\n\nprivate unsafe def add_hinst_lemma_from_name (md : Transparency) (lhs_lemma : Bool) (n : Name)\n (hs : hinst_lemmas) (ref : pexpr) : smt_tactic hinst_lemmas := do\n let p ← resolve_name n\n match p with\n | expr.const n _ =>\n (do\n let h ← hinst_lemma.mk_from_decl_core md n lhs_lemma\n tactic.save_const_type_info n ref\n return <| hs h) <|>\n (do\n let hs₁ ← mk_ematch_eqn_lemmas_for_core md n\n tactic.save_const_type_info n ref\n return <| hs hs₁) <|>\n report_invalid_em_lemma n\n | _ =>\n (do\n let e ← to_expr p\n let h ← hinst_lemma.mk_core md e lhs_lemma\n try (tactic.save_type_info e ref)\n return <| hs h) <|>\n report_invalid_em_lemma n\n#align smt_tactic.interactive.add_hinst_lemma_from_name smt_tactic.interactive.add_hinst_lemma_from_name\n\nprivate unsafe def add_hinst_lemma_from_pexpr (md : Transparency) (lhs_lemma : Bool) (p : pexpr)\n (hs : hinst_lemmas) : smt_tactic hinst_lemmas :=\n match p with\n | expr.const c [] => add_hinst_lemma_from_name md lhs_lemma c hs p\n | expr.local_const c _ _ _ => add_hinst_lemma_from_name md lhs_lemma c hs p\n | _ => do\n let new_e ← to_expr p\n let h ← hinst_lemma.mk_core md new_e lhs_lemma\n return <| hs h\n#align smt_tactic.interactive.add_hinst_lemma_from_pexpr smt_tactic.interactive.add_hinst_lemma_from_pexpr\n\nprivate unsafe def add_hinst_lemmas_from_pexprs (md : Transparency) (lhs_lemma : Bool) :\n List pexpr → hinst_lemmas → smt_tactic hinst_lemmas\n | [], hs => return hs\n | p :: ps, hs => do\n let hs₁ ← add_hinst_lemma_from_pexpr md lhs_lemma p hs\n add_hinst_lemmas_from_pexprs ps hs₁\n#align smt_tactic.interactive.add_hinst_lemmas_from_pexprs smt_tactic.interactive.add_hinst_lemmas_from_pexprs\n\nunsafe def ematch_using (l : parse pexpr_list_or_texpr) : smt_tactic Unit := do\n let hs ← add_hinst_lemmas_from_pexprs reducible false l hinst_lemmas.mk\n smt_tactic.ematch_using hs\n#align smt_tactic.interactive.ematch_using smt_tactic.interactive.ematch_using\n\n/-- Try the given tactic, and do nothing if it fails. -/\nunsafe def try (t : itactic) : smt_tactic Unit :=\n smt_tactic.try t\n#align smt_tactic.interactive.try smt_tactic.interactive.try\n\n/-- Keep applying the given tactic until it fails. -/\nunsafe def iterate (t : itactic) : smt_tactic Unit :=\n smt_tactic.iterate t\n#align smt_tactic.interactive.iterate smt_tactic.interactive.iterate\n\n/-- Apply the given tactic to all remaining goals. -/\nunsafe def all_goals (t : itactic) : smt_tactic Unit :=\n smt_tactic.all_goals t\n#align smt_tactic.interactive.all_goals smt_tactic.interactive.all_goals\n\nunsafe def induction (p : parse tactic.interactive.cases_arg_p) (rec_name : parse using_ident)\n (ids : parse with_ident_list) (revert : parse <| (tk \"generalizing\" *> ident*)?) :\n smt_tactic Unit :=\n slift (tactic.interactive.induction p rec_name ids revert)\n#align smt_tactic.interactive.induction smt_tactic.interactive.induction\n\nopen Tactic\n\n/-- Simplify the target type of the main goal. -/\nunsafe def simp (use_iota_eqn : parse <| (tk \"!\")?) (no_dflt : parse only_flag)\n (hs : parse simp_arg_list) (attr_names : parse with_ident_list) (cfg : simp_config_ext := { }) :\n smt_tactic Unit :=\n tactic.interactive.simp use_iota_eqn none no_dflt hs attr_names (Loc.ns [none]) cfg\n#align smt_tactic.interactive.simp smt_tactic.interactive.simp\n\nunsafe def dsimp (no_dflt : parse only_flag) (es : parse simp_arg_list)\n (attr_names : parse with_ident_list) : smt_tactic Unit :=\n tactic.interactive.dsimp no_dflt es attr_names (Loc.ns [none])\n#align smt_tactic.interactive.dsimp smt_tactic.interactive.dsimp\n\nunsafe def rsimp : smt_tactic Unit := do\n let ccs ← to_cc_state\n _root_.rsimp.rsimplify_goal ccs\n#align smt_tactic.interactive.rsimp smt_tactic.interactive.rsimp\n\nunsafe def add_simp_lemmas : smt_tactic Unit :=\n get_hinst_lemmas_for_attr `rsimp_attr >>= add_lemmas\n#align smt_tactic.interactive.add_simp_lemmas smt_tactic.interactive.add_simp_lemmas\n\n/-- Keep applying heuristic instantiation until the current goal is solved, or it fails. -/\nunsafe def eblast : smt_tactic Unit :=\n smt_tactic.eblast\n#align smt_tactic.interactive.eblast smt_tactic.interactive.eblast\n\n/--\nKeep applying heuristic instantiation using the given lemmas until the current goal is solved, or it fails. -/\nunsafe def eblast_using (l : parse pexpr_list_or_texpr) : smt_tactic Unit := do\n let hs ← add_hinst_lemmas_from_pexprs reducible false l hinst_lemmas.mk\n smt_tactic.iterate (smt_tactic.ematch_using hs >> smt_tactic.try smt_tactic.close)\n#align smt_tactic.interactive.eblast_using smt_tactic.interactive.eblast_using\n\nunsafe def guard_expr_eq (t : expr) (p : parse <| tk \":=\" *> texpr) : smt_tactic Unit := do\n let e ← to_expr p\n guard (expr.alpha_eqv t e)\n#align smt_tactic.interactive.guard_expr_eq smt_tactic.interactive.guard_expr_eq\n\nunsafe def guard_target (p : parse texpr) : smt_tactic Unit := do\n let t ← target\n guard_expr_eq t p\n#align smt_tactic.interactive.guard_target smt_tactic.interactive.guard_target\n\nend Interactive\n\nend SmtTactic\n\n", "meta": {"author": "leanprover-community", "repo": "lean3port", "sha": "9ed1898f23e4379865ee93d62cb6353e5ed6c270", "save_path": "github-repos/lean/leanprover-community-lean3port", "path": "github-repos/lean/leanprover-community-lean3port/lean3port-9ed1898f23e4379865ee93d62cb6353e5ed6c270/Leanbin/Init/Meta/Smt/Interactive.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34158251284363395, "lm_q2_score": 0.08035747157520208, "lm_q1q2_score": 0.027448707066418415}} {"text": "/-\nCopyright (c) 2018 Kenny Lau. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthor: Johannes Hölzl, Kenny Lau\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.default\nimport Mathlib.data.dfinsupp\nimport Mathlib.linear_algebra.basic\nimport Mathlib.PostPort\n\nuniverses u_1 u_3 u_2 u_4 \n\nnamespace Mathlib\n\n/-!\n# Properties of the semimodule `Π₀ i, M i`\n\nGiven an indexed collection of `R`-semimodules `M i`, the `R`-semimodule structure on `Π₀ i, M i`\nis defined in `data.dfinsupp`.\n\nIn this file we define `linear_map` versions of various maps:\n\n* `dfinsupp.lsingle a : M →ₗ[R] Π₀ i, M i`: `dfinsupp.single a` as a linear map;\n\n* `dfinsupp.lmk s : (Π i : (↑s : set ι), M i) →ₗ[R] Π₀ i, M i`: `dfinsupp.single a` as a linear map;\n\n* `dfinsupp.lapply i : (Π₀ i, M i) →ₗ[R] M`: the map `λ f, f i` as a linear map;\n\n* `dfinsupp.lsum`: `dfinsupp.sum` or `dfinsupp.lift_add_hom` as a `linear_map`;\n\n## Implementation notes\n\nThis file should try to mirror `linear_algebra.finsupp` where possible. The API of `finsupp` is\nmuch more developed, but many lemmas in that file should be eligible to copy over.\n\n## Tags\n\nfunction with finite support, semimodule, linear algebra\n-/\n\nnamespace dfinsupp\n\n\n/-- `dfinsupp.mk` as a `linear_map`. -/\ndef lmk {ι : Type u_1} {R : Type u_2} {M : ι → Type u_3} [dec_ι : DecidableEq ι] [semiring R]\n [(i : ι) → add_comm_monoid (M i)] [(i : ι) → semimodule R (M i)] (s : finset ι) :\n linear_map R ((i : ↥↑s) → M ↑i) (dfinsupp fun (i : ι) => M i) :=\n linear_map.mk (mk s) sorry sorry\n\n/-- `dfinsupp.single` as a `linear_map` -/\ndef lsingle {ι : Type u_1} {R : Type u_2} {M : ι → Type u_3} [dec_ι : DecidableEq ι] [semiring R]\n [(i : ι) → add_comm_monoid (M i)] [(i : ι) → semimodule R (M i)] (i : ι) :\n linear_map R (M i) (dfinsupp fun (i : ι) => M i) :=\n linear_map.mk (single i) sorry sorry\n\n/-- Two `R`-linear maps from `Π₀ i, M i` which agree on each `single i x` agree everywhere. -/\ntheorem lhom_ext {ι : Type u_1} {R : Type u_2} {M : ι → Type u_3} {N : Type u_4}\n [dec_ι : DecidableEq ι] [semiring R] [(i : ι) → add_comm_monoid (M i)]\n [(i : ι) → semimodule R (M i)] [add_comm_monoid N] [semimodule R N]\n {φ : linear_map R (dfinsupp fun (i : ι) => M i) N}\n {ψ : linear_map R (dfinsupp fun (i : ι) => M i) N}\n (h : ∀ (i : ι) (x : M i), coe_fn φ (single i x) = coe_fn ψ (single i x)) : φ = ψ :=\n linear_map.to_add_monoid_hom_injective (add_hom_ext h)\n\n/-- Two `R`-linear maps from `Π₀ i, M i` which agree on each `single i x` agree everywhere.\n\nSee note [partially-applied ext lemmas].\nAfter apply this lemma, if `M = R` then it suffices to verify `φ (single a 1) = ψ (single a 1)`. -/\ntheorem lhom_ext' {ι : Type u_1} {R : Type u_2} {M : ι → Type u_3} {N : Type u_4}\n [dec_ι : DecidableEq ι] [semiring R] [(i : ι) → add_comm_monoid (M i)]\n [(i : ι) → semimodule R (M i)] [add_comm_monoid N] [semimodule R N]\n {φ : linear_map R (dfinsupp fun (i : ι) => M i) N}\n {ψ : linear_map R (dfinsupp fun (i : ι) => M i) N}\n (h : ∀ (i : ι), linear_map.comp φ (lsingle i) = linear_map.comp ψ (lsingle i)) : φ = ψ :=\n lhom_ext fun (i : ι) => linear_map.congr_fun (h i)\n\n/-- Interpret `λ (f : Π₀ i, M i), f i` as a linear map. -/\ndef lapply {ι : Type u_1} {R : Type u_2} {M : ι → Type u_3} [semiring R]\n [(i : ι) → add_comm_monoid (M i)] [(i : ι) → semimodule R (M i)] (i : ι) :\n linear_map R (dfinsupp fun (i : ι) => M i) (M i) :=\n linear_map.mk (fun (f : dfinsupp fun (i : ι) => M i) => coe_fn f i) sorry sorry\n\n@[simp] theorem lmk_apply {ι : Type u_1} {R : Type u_2} {M : ι → Type u_3} [dec_ι : DecidableEq ι]\n [semiring R] [(i : ι) → add_comm_monoid (M i)] [(i : ι) → semimodule R (M i)] (s : finset ι)\n (x : (i : ↥↑s) → (fun (i : ι) => M i) ↑i) : coe_fn (lmk s) x = mk s x :=\n rfl\n\n@[simp] theorem lsingle_apply {ι : Type u_1} {R : Type u_2} {M : ι → Type u_3}\n [dec_ι : DecidableEq ι] [semiring R] [(i : ι) → add_comm_monoid (M i)]\n [(i : ι) → semimodule R (M i)] (i : ι) (x : M i) : coe_fn (lsingle i) x = single i x :=\n rfl\n\n@[simp] theorem lapply_apply {ι : Type u_1} {R : Type u_2} {M : ι → Type u_3} [semiring R]\n [(i : ι) → add_comm_monoid (M i)] [(i : ι) → semimodule R (M i)] (i : ι)\n (f : dfinsupp fun (i : ι) => M i) : coe_fn (lapply i) f = coe_fn f i :=\n rfl\n\n/-- The `dfinsupp` version of `finsupp.lsum`. -/\ndef lsum {ι : Type u_1} {R : Type u_2} {M : ι → Type u_3} {N : Type u_4} [dec_ι : DecidableEq ι]\n [semiring R] [(i : ι) → add_comm_monoid (M i)] [(i : ι) → semimodule R (M i)]\n [add_comm_monoid N] [semimodule R N] :\n ((i : ι) → linear_map R (M i) N) ≃+ linear_map R (dfinsupp fun (i : ι) => M i) N :=\n add_equiv.mk\n (fun (F : (i : ι) → linear_map R (M i) N) =>\n linear_map.mk ⇑(sum_add_hom fun (i : ι) => linear_map.to_add_monoid_hom (F i)) sorry sorry)\n (fun (F : linear_map R (dfinsupp fun (i : ι) => M i) N) (i : ι) =>\n linear_map.comp F (lsingle i))\n sorry sorry sorry\n\nend Mathlib", "meta": {"author": "AurelienSaue", "repo": "Mathlib4_auto", "sha": "590df64109b08190abe22358fabc3eae000943f2", "save_path": "github-repos/lean/AurelienSaue-Mathlib4_auto", "path": "github-repos/lean/AurelienSaue-Mathlib4_auto/Mathlib4_auto-590df64109b08190abe22358fabc3eae000943f2/Mathlib/linear_algebra/dfinsupp_auto.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44939263446475963, "lm_q2_score": 0.06097518001176593, "lm_q1q2_score": 0.027401796782450447}} {"text": "/-\nCopyright (c) 2020 Scott Morrison. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Scott Morrison\n-/\nimport category_theory.limits.has_limits\nimport category_theory.products.basic\nimport category_theory.currying\n\n/-!\n# A Fubini theorem for categorical limits\n\nWe prove that $lim_{J × K} G = lim_J (lim_K G(j, -))$ for a functor `G : J × K ⥤ C`,\nwhen all the appropriate limits exist.\n\nWe begin working with a functor `F : J ⥤ K ⥤ C`. We'll write `G : J × K ⥤ C` for the associated\n\"uncurried\" functor.\n\nIn the first part, given a coherent family `D` of limit cones over the functors `F.obj j`,\nand a cone `c` over `G`, we construct a cone over the cone points of `D`.\nWe then show that if `c` is a limit cone, the constructed cone is also a limit cone.\n\nIn the second part, we state the Fubini theorem in the setting where limits are\nprovided by suitable `has_limit` classes.\n\nWe construct\n`limit_uncurry_iso_limit_comp_lim F : limit (uncurry.obj F) ≅ limit (F ⋙ lim)`\nand give simp lemmas characterising it.\nFor convenience, we also provide\n`limit_iso_limit_curry_comp_lim G : limit G ≅ limit ((curry.obj G) ⋙ lim)`\nin terms of the uncurried functor.\n\n## Future work\n\nThe dual statement.\n-/\n\nuniverses v u\n\nopen category_theory\n\nnamespace category_theory.limits\n\nvariables {J K : Type v} [small_category J] [small_category K]\nvariables {C : Type u} [category.{v} C]\n\nvariables (F : J ⥤ K ⥤ C)\n\n/--\nA structure carrying a diagram of cones over the the functors `F.obj j`.\n-/\n-- We could try introducing a \"dependent functor type\" to handle this?\nstructure diagram_of_cones :=\n(obj : Π j : J, cone (F.obj j))\n(map : Π {j j' : J} (f : j ⟶ j'), (cones.postcompose (F.map f)).obj (obj j) ⟶ obj j')\n(id : ∀ j : J, (map (𝟙 j)).hom = 𝟙 _ . obviously)\n(comp : ∀ {j₁ j₂ j₃ : J} (f : j₁ ⟶ j₂) (g : j₂ ⟶ j₃),\n (map (f ≫ g)).hom = (map f).hom ≫ (map g).hom . obviously)\n\nvariables {F}\n\n/--\nExtract the functor `J ⥤ C` consisting of the cone points and the maps between them,\nfrom a `diagram_of_cones`.\n-/\n@[simps]\ndef diagram_of_cones.cone_points (D : diagram_of_cones F) :\n J ⥤ C :=\n{ obj := λ j, (D.obj j).X,\n map := λ j j' f, (D.map f).hom,\n map_id' := λ j, D.id j,\n map_comp' := λ j₁ j₂ j₃ f g, D.comp f g, }\n\n/--\nGiven a diagram `D` of limit cones over the `F.obj j`, and a cone over `uncurry.obj F`,\nwe can construct a cone over the diagram consisting of the cone points from `D`.\n-/\n@[simps]\ndef cone_of_cone_uncurry\n {D : diagram_of_cones F} (Q : Π j, is_limit (D.obj j))\n (c : cone (uncurry.obj F)) :\n cone (D.cone_points) :=\n{ X := c.X,\n π :=\n { app := λ j, (Q j).lift\n { X := c.X,\n π :=\n { app := λ k, c.π.app (j, k),\n naturality' := λ k k' f,\n begin\n dsimp, simp only [category.id_comp],\n have := @nat_trans.naturality _ _ _ _ _ _ c.π (j, k) (j, k') (𝟙 j, f),\n dsimp at this,\n simp only [category.id_comp, category_theory.functor.map_id, nat_trans.id_app] at this,\n exact this,\n end } },\n naturality' := λ j j' f, (Q j').hom_ext\n begin\n dsimp,\n intro k,\n simp only [limits.cone_morphism.w, limits.cones.postcompose_obj_π, limits.is_limit.fac_assoc,\n limits.is_limit.fac, nat_trans.comp_app, category.id_comp, category.assoc],\n have := @nat_trans.naturality _ _ _ _ _ _ c.π (j, k) (j', k) (f, 𝟙 k),\n dsimp at this,\n simp only [category.id_comp, category.comp_id,\n category_theory.functor.map_id, nat_trans.id_app] at this,\n exact this,\n end, } }.\n\n/--\n`cone_of_cone_uncurry Q c` is a limit cone when `c` is a limit cone.`\n-/\ndef cone_of_cone_uncurry_is_limit\n {D : diagram_of_cones F} (Q : Π j, is_limit (D.obj j))\n {c : cone (uncurry.obj F)} (P : is_limit c) :\n is_limit (cone_of_cone_uncurry Q c) :=\n{ lift := λ s, P.lift\n { X := s.X,\n π :=\n { app := λ p, s.π.app p.1 ≫ (D.obj p.1).π.app p.2,\n naturality' := λ p p' f,\n begin\n dsimp, simp only [category.id_comp, category.assoc],\n rcases p with ⟨j, k⟩,\n rcases p' with ⟨j', k'⟩,\n rcases f with ⟨fj, fk⟩,\n dsimp,\n slice_rhs 3 4 { rw ←nat_trans.naturality, },\n slice_rhs 2 3 { rw ←(D.obj j).π.naturality, },\n simp only [functor.const.obj_map, category.id_comp, category.assoc],\n have w := (D.map fj).w k',\n dsimp at w,\n rw ←w,\n have n := s.π.naturality fj,\n dsimp at n,\n simp only [category.id_comp] at n,\n rw n,\n simp,\n end, } },\n fac' := λ s j,\n begin\n apply (Q j).hom_ext,\n intro k,\n simp,\n end,\n uniq' := λ s m w,\n begin\n refine P.uniq { X := s.X, π := _, } m _,\n rintro ⟨j, k⟩,\n dsimp,\n rw [←w j],\n simp,\n end, }\n\nsection\nvariables (F)\nvariables [has_limits_of_shape K C]\n\n/--\nGiven a functor `F : J ⥤ K ⥤ C`, with all needed limits,\nwe can construct a diagram consisting of the limit cone over each functor `F.obj j`,\nand the universal cone morphisms between these.\n-/\n@[simps]\nnoncomputable def diagram_of_cones.mk_of_has_limits : diagram_of_cones F :=\n{ obj := λ j, limit.cone (F.obj j),\n map := λ j j' f, { hom := lim.map (F.map f), }, }\n\n-- Satisfying the inhabited linter.\nnoncomputable instance diagram_of_cones_inhabited : inhabited (diagram_of_cones F) :=\n⟨diagram_of_cones.mk_of_has_limits F⟩\n\n@[simp]\nlemma diagram_of_cones.mk_of_has_limits_cone_points :\n (diagram_of_cones.mk_of_has_limits F).cone_points = (F ⋙ lim) :=\nrfl\n\nvariables [has_limit (uncurry.obj F)]\nvariables [has_limit (F ⋙ lim)]\n\n/--\nThe Fubini theorem for a functor `F : J ⥤ K ⥤ C`,\nshowing that the limit of `uncurry.obj F` can be computed as\nthe limit of the limits of the functors `F.obj j`.\n-/\nnoncomputable def limit_uncurry_iso_limit_comp_lim : limit (uncurry.obj F) ≅ limit (F ⋙ lim) :=\nbegin\n let c := limit.cone (uncurry.obj F),\n let P : is_limit c := limit.is_limit _,\n let G := diagram_of_cones.mk_of_has_limits F,\n let Q : Π j, is_limit (G.obj j) := λ j, limit.is_limit _,\n have Q' := cone_of_cone_uncurry_is_limit Q P,\n have Q'' := (limit.is_limit (F ⋙ lim)),\n exact is_limit.cone_point_unique_up_to_iso Q' Q'',\nend\n\n@[simp]\nlemma limit_uncurry_iso_limit_comp_lim_hom_π_π {j} {k} :\n (limit_uncurry_iso_limit_comp_lim F).hom ≫ limit.π _ j ≫ limit.π _ k = limit.π _ (j, k) :=\nbegin\n dsimp [limit_uncurry_iso_limit_comp_lim, is_limit.cone_point_unique_up_to_iso,\n is_limit.unique_up_to_iso],\n simp,\nend\n\n@[simp]\nlemma limit_uncurry_iso_limit_comp_lim_inv_π {j} {k} :\n (limit_uncurry_iso_limit_comp_lim F).inv ≫ limit.π _ (j, k) = limit.π _ j ≫ limit.π _ k :=\nbegin\n rw [←cancel_epi (limit_uncurry_iso_limit_comp_lim F).hom],\n simp,\nend\nend\n\nsection\nvariables (G : J × K ⥤ C)\n\nsection\nvariables [has_limits_of_shape K C]\nvariables [has_limit G]\nvariables [has_limit ((curry.obj G) ⋙ lim)]\n\n/--\nThe Fubini theorem for a functor `G : J × K ⥤ C`,\nshowing that the limit of `G` can be computed as\nthe limit of the limits of the functors `G.obj (j, _)`.\n-/\nnoncomputable def limit_iso_limit_curry_comp_lim : limit G ≅ limit ((curry.obj G) ⋙ lim) :=\nbegin\n have i : G ≅ uncurry.obj ((@curry J _ K _ C _).obj G) := currying.symm.unit_iso.app G,\n haveI : limits.has_limit (uncurry.obj ((@curry J _ K _ C _).obj G)) :=\n has_limit_of_iso i,\n transitivity limit (uncurry.obj ((@curry J _ K _ C _).obj G)),\n apply has_limit.iso_of_nat_iso i,\n exact limit_uncurry_iso_limit_comp_lim ((@curry J _ K _ C _).obj G),\nend\n\n@[simp, reassoc]\nlemma limit_iso_limit_curry_comp_lim_hom_π_π {j} {k} :\n (limit_iso_limit_curry_comp_lim G).hom ≫ limit.π _ j ≫ limit.π _ k = limit.π _ (j, k) :=\nby simp [limit_iso_limit_curry_comp_lim, is_limit.cone_point_unique_up_to_iso,\n is_limit.unique_up_to_iso]\n\n@[simp, reassoc]\nlemma limit_iso_limit_curry_comp_lim_inv_π {j} {k} :\n (limit_iso_limit_curry_comp_lim G).inv ≫ limit.π _ (j, k) = limit.π _ j ≫ limit.π _ k :=\nbegin\n rw [←cancel_epi (limit_iso_limit_curry_comp_lim G).hom],\n simp,\nend\nend\n\n\nsection\nvariables [has_limits C] -- Certainly one could weaken the hypotheses here.\n\nopen category_theory.prod\n\n/--\nA variant of the Fubini theorem for a functor `G : J × K ⥤ C`,\nshowing that $\\lim_k \\lim_j G(j,k) ≅ \\lim_j \\lim_k G(j,k)$.\n-/\nnoncomputable\ndef limit_curry_swap_comp_lim_iso_limit_curry_comp_lim :\n limit ((curry.obj (swap K J ⋙ G)) ⋙ lim) ≅ limit ((curry.obj G) ⋙ lim) :=\ncalc\n limit ((curry.obj (swap K J ⋙ G)) ⋙ lim)\n ≅ limit (swap K J ⋙ G) : (limit_iso_limit_curry_comp_lim _).symm\n ... ≅ limit G : has_limit.iso_of_equivalence (braiding K J) (iso.refl _)\n ... ≅ limit ((curry.obj G) ⋙ lim) : limit_iso_limit_curry_comp_lim _\n\n@[simp]\nlemma limit_curry_swap_comp_lim_iso_limit_curry_comp_lim_hom_π_π {j} {k} :\n (limit_curry_swap_comp_lim_iso_limit_curry_comp_lim G).hom ≫ limit.π _ j ≫ limit.π _ k =\n limit.π _ k ≫ limit.π _ j :=\nbegin\n dsimp [limit_curry_swap_comp_lim_iso_limit_curry_comp_lim],\n simp only [iso.refl_hom, braiding_counit_iso_hom_app, limits.has_limit.iso_of_equivalence_hom_π,\n iso.refl_inv, limit_iso_limit_curry_comp_lim_hom_π_π, eq_to_iso_refl, category.assoc],\n erw [nat_trans.id_app], -- Why can't `simp` do this`?\n dsimp, simp,\nend\n\n@[simp]\nlemma limit_curry_swap_comp_lim_iso_limit_curry_comp_lim_inv_π_π {j} {k} :\n (limit_curry_swap_comp_lim_iso_limit_curry_comp_lim G).inv ≫ limit.π _ k ≫ limit.π _ j =\n limit.π _ j ≫ limit.π _ k :=\nbegin\n dsimp [limit_curry_swap_comp_lim_iso_limit_curry_comp_lim],\n simp only [iso.refl_hom, braiding_counit_iso_hom_app, limits.has_limit.iso_of_equivalence_inv_π,\n iso.refl_inv, limit_iso_limit_curry_comp_lim_hom_π_π, eq_to_iso_refl, category.assoc],\n erw [nat_trans.id_app], -- Why can't `simp` do this`?\n dsimp, simp,\nend\n\nend\n\nend\n\nend category_theory.limits\n", "meta": {"author": "JLimperg", "repo": "aesop3", "sha": "a4a116f650cc7403428e72bd2e2c4cda300fe03f", "save_path": "github-repos/lean/JLimperg-aesop3", "path": "github-repos/lean/JLimperg-aesop3/aesop3-a4a116f650cc7403428e72bd2e2c4cda300fe03f/src/category_theory/limits/fubini.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4765796361952087, "lm_q2_score": 0.05749328324142241, "lm_q1q2_score": 0.027400128010865183}} {"text": "/-\nCopyright (c) 2015 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthor: Mario Carneiro\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.default\nimport Mathlib.data.multiset.powerset\nimport Mathlib.data.multiset.range\nimport Mathlib.PostPort\n\nuniverses u_1 u_2 u_3 \n\nnamespace Mathlib\n\n/-!\n# The `nodup` predicate for multisets without duplicate elements.\n-/\n\nnamespace multiset\n\n\n/- nodup -/\n\n/-- `nodup s` means that `s` has no duplicates, i.e. the multiplicity of\n any element is at most 1. -/\ndef nodup {α : Type u_1} (s : multiset α) := quot.lift_on s list.nodup sorry\n\n@[simp] theorem coe_nodup {α : Type u_1} {l : List α} : nodup ↑l ↔ list.nodup l := iff.rfl\n\n@[simp] theorem nodup_zero {α : Type u_1} : nodup 0 := list.pairwise.nil\n\n@[simp] theorem nodup_cons {α : Type u_1} {a : α} {s : multiset α} :\n nodup (a ::ₘ s) ↔ ¬a ∈ s ∧ nodup s :=\n quot.induction_on s fun (l : List α) => list.nodup_cons\n\ntheorem nodup_cons_of_nodup {α : Type u_1} {a : α} {s : multiset α} (m : ¬a ∈ s) (n : nodup s) :\n nodup (a ::ₘ s) :=\n iff.mpr nodup_cons { left := m, right := n }\n\ntheorem nodup_singleton {α : Type u_1} (a : α) : nodup (a ::ₘ 0) := list.nodup_singleton\n\ntheorem nodup_of_nodup_cons {α : Type u_1} {a : α} {s : multiset α} (h : nodup (a ::ₘ s)) :\n nodup s :=\n and.right (iff.mp nodup_cons h)\n\ntheorem not_mem_of_nodup_cons {α : Type u_1} {a : α} {s : multiset α} (h : nodup (a ::ₘ s)) :\n ¬a ∈ s :=\n and.left (iff.mp nodup_cons h)\n\ntheorem nodup_of_le {α : Type u_1} {s : multiset α} {t : multiset α} (h : s ≤ t) :\n nodup t → nodup s :=\n le_induction_on h fun (l₁ l₂ : List α) => list.nodup_of_sublist\n\ntheorem not_nodup_pair {α : Type u_1} (a : α) : ¬nodup (a ::ₘ a ::ₘ 0) := list.not_nodup_pair\n\ntheorem nodup_iff_le {α : Type u_1} {s : multiset α} : nodup s ↔ ∀ (a : α), ¬a ::ₘ a ::ₘ 0 ≤ s :=\n quot.induction_on s\n fun (l : List α) =>\n iff.trans list.nodup_iff_sublist\n (forall_congr fun (a : α) => not_congr (iff.symm repeat_le_coe))\n\ntheorem nodup_iff_ne_cons_cons {α : Type u_1} {s : multiset α} :\n nodup s ↔ ∀ (a : α) (t : multiset α), s ≠ a ::ₘ a ::ₘ t :=\n sorry\n\ntheorem nodup_iff_count_le_one {α : Type u_1} [DecidableEq α] {s : multiset α} :\n nodup s ↔ ∀ (a : α), count a s ≤ 1 :=\n quot.induction_on s fun (l : List α) => list.nodup_iff_count_le_one\n\n@[simp] theorem count_eq_one_of_mem {α : Type u_1} [DecidableEq α] {a : α} {s : multiset α}\n (d : nodup s) (h : a ∈ s) : count a s = 1 :=\n le_antisymm (iff.mp nodup_iff_count_le_one d a) (iff.mpr count_pos h)\n\ntheorem nodup_iff_pairwise {α : Type u_1} {s : multiset α} : nodup s ↔ pairwise ne s :=\n quotient.induction_on s\n fun (l : List α) => iff.symm (pairwise_coe_iff_pairwise fun (a b : α) => ne.symm)\n\ntheorem pairwise_of_nodup {α : Type u_1} {r : α → α → Prop} {s : multiset α} :\n (∀ (a : α), a ∈ s → ∀ (b : α), b ∈ s → a ≠ b → r a b) → nodup s → pairwise r s :=\n sorry\n\ntheorem forall_of_pairwise {α : Type u_1} {r : α → α → Prop} (H : symmetric r) {s : multiset α}\n (hs : pairwise r s) (a : α) : a ∈ s → ∀ (b : α), b ∈ s → a ≠ b → r a b :=\n sorry\n\ntheorem nodup_add {α : Type u_1} {s : multiset α} {t : multiset α} :\n nodup (s + t) ↔ nodup s ∧ nodup t ∧ disjoint s t :=\n quotient.induction_on₂ s t fun (l₁ l₂ : List α) => list.nodup_append\n\ntheorem disjoint_of_nodup_add {α : Type u_1} {s : multiset α} {t : multiset α} (d : nodup (s + t)) :\n disjoint s t :=\n and.right (and.right (iff.mp nodup_add d))\n\ntheorem nodup_add_of_nodup {α : Type u_1} {s : multiset α} {t : multiset α} (d₁ : nodup s)\n (d₂ : nodup t) : nodup (s + t) ↔ disjoint s t :=\n sorry\n\ntheorem nodup_of_nodup_map {α : Type u_1} {β : Type u_2} (f : α → β) {s : multiset α} :\n nodup (map f s) → nodup s :=\n quot.induction_on s fun (l : List α) => list.nodup_of_nodup_map f\n\ntheorem nodup_map_on {α : Type u_1} {β : Type u_2} {f : α → β} {s : multiset α} :\n (∀ (x : α), x ∈ s → ∀ (y : α), y ∈ s → f x = f y → x = y) → nodup s → nodup (map f s) :=\n quot.induction_on s fun (l : List α) => list.nodup_map_on\n\ntheorem nodup_map {α : Type u_1} {β : Type u_2} {f : α → β} {s : multiset α}\n (hf : function.injective f) : nodup s → nodup (map f s) :=\n nodup_map_on fun (x : α) (_x : x ∈ s) (y : α) (_x : y ∈ s) (h : f x = f y) => hf h\n\ntheorem nodup_filter {α : Type u_1} (p : α → Prop) [decidable_pred p] {s : multiset α} :\n nodup s → nodup (filter p s) :=\n quot.induction_on s fun (l : List α) => list.nodup_filter p\n\n@[simp] theorem nodup_attach {α : Type u_1} {s : multiset α} : nodup (attach s) ↔ nodup s :=\n quot.induction_on s fun (l : List α) => list.nodup_attach\n\ntheorem nodup_pmap {α : Type u_1} {β : Type u_2} {p : α → Prop} {f : (a : α) → p a → β}\n {s : multiset α} {H : ∀ (a : α), a ∈ s → p a}\n (hf : ∀ (a : α) (ha : p a) (b : α) (hb : p b), f a ha = f b hb → a = b) :\n nodup s → nodup (pmap f s H) :=\n quot.induction_on s\n (fun (l : List α) (H : ∀ (a : α), a ∈ Quot.mk setoid.r l → p a) => list.nodup_pmap hf) H\n\nprotected instance nodup_decidable {α : Type u_1} [DecidableEq α] (s : multiset α) :\n Decidable (nodup s) :=\n quotient.rec_on_subsingleton s fun (l : List α) => list.nodup_decidable l\n\ntheorem nodup_erase_eq_filter {α : Type u_1} [DecidableEq α] (a : α) {s : multiset α} :\n nodup s → erase s a = filter (fun (_x : α) => _x ≠ a) s :=\n quot.induction_on s\n fun (l : List α) (d : nodup (Quot.mk setoid.r l)) =>\n congr_arg coe (list.nodup_erase_eq_filter a d)\n\ntheorem nodup_erase_of_nodup {α : Type u_1} [DecidableEq α] (a : α) {l : multiset α} :\n nodup l → nodup (erase l a) :=\n nodup_of_le (erase_le a l)\n\ntheorem mem_erase_iff_of_nodup {α : Type u_1} [DecidableEq α] {a : α} {b : α} {l : multiset α}\n (d : nodup l) : a ∈ erase l b ↔ a ≠ b ∧ a ∈ l :=\n sorry\n\ntheorem mem_erase_of_nodup {α : Type u_1} [DecidableEq α] {a : α} {l : multiset α} (h : nodup l) :\n ¬a ∈ erase l a :=\n sorry\n\ntheorem nodup_product {α : Type u_1} {β : Type u_2} {s : multiset α} {t : multiset β} :\n nodup s → nodup t → nodup (product s t) :=\n sorry\n\ntheorem nodup_sigma {α : Type u_1} {σ : α → Type u_2} {s : multiset α}\n {t : (a : α) → multiset (σ a)} :\n nodup s → (∀ (a : α), nodup (t a)) → nodup (multiset.sigma s t) :=\n sorry\n\ntheorem nodup_filter_map {α : Type u_1} {β : Type u_2} (f : α → Option β) {s : multiset α}\n (H : ∀ (a a' : α) (b : β), b ∈ f a → b ∈ f a' → a = a') : nodup s → nodup (filter_map f s) :=\n quot.induction_on s fun (l : List α) => list.nodup_filter_map H\n\ntheorem nodup_range (n : ℕ) : nodup (range n) := list.nodup_range n\n\ntheorem nodup_inter_left {α : Type u_1} [DecidableEq α] {s : multiset α} (t : multiset α) :\n nodup s → nodup (s ∩ t) :=\n nodup_of_le (inter_le_left s t)\n\ntheorem nodup_inter_right {α : Type u_1} [DecidableEq α] (s : multiset α) {t : multiset α} :\n nodup t → nodup (s ∩ t) :=\n nodup_of_le (inter_le_right s t)\n\n@[simp] theorem nodup_union {α : Type u_1} [DecidableEq α] {s : multiset α} {t : multiset α} :\n nodup (s ∪ t) ↔ nodup s ∧ nodup t :=\n sorry\n\n@[simp] theorem nodup_powerset {α : Type u_1} {s : multiset α} : nodup (powerset s) ↔ nodup s :=\n sorry\n\ntheorem nodup_powerset_len {α : Type u_1} {n : ℕ} {s : multiset α} (h : nodup s) :\n nodup (powerset_len n s) :=\n nodup_of_le (powerset_len_le_powerset n s) (iff.mpr nodup_powerset h)\n\n@[simp] theorem nodup_bind {α : Type u_1} {β : Type u_2} {s : multiset α} {t : α → multiset β} :\n nodup (bind s t) ↔\n (∀ (a : α), a ∈ s → nodup (t a)) ∧ pairwise (fun (a b : α) => disjoint (t a) (t b)) s :=\n sorry\n\ntheorem nodup_ext {α : Type u_1} {s : multiset α} {t : multiset α} :\n nodup s → nodup t → (s = t ↔ ∀ (a : α), a ∈ s ↔ a ∈ t) :=\n quotient.induction_on₂ s t\n fun (l₁ l₂ : List α) (d₁ : nodup (quotient.mk l₁)) (d₂ : nodup (quotient.mk l₂)) =>\n iff.trans quotient.eq (list.perm_ext d₁ d₂)\n\ntheorem le_iff_subset {α : Type u_1} {s : multiset α} {t : multiset α} :\n nodup s → (s ≤ t ↔ s ⊆ t) :=\n quotient.induction_on₂ s t\n fun (l₁ l₂ : List α) (d : nodup (quotient.mk l₁)) =>\n { mp := subset_of_le, mpr := list.subperm_of_subset_nodup d }\n\ntheorem range_le {m : ℕ} {n : ℕ} : range m ≤ range n ↔ m ≤ n :=\n iff.trans (le_iff_subset (nodup_range m)) range_subset\n\ntheorem mem_sub_of_nodup {α : Type u_1} [DecidableEq α] {a : α} {s : multiset α} {t : multiset α}\n (d : nodup s) : a ∈ s - t ↔ a ∈ s ∧ ¬a ∈ t :=\n sorry\n\ntheorem map_eq_map_of_bij_of_nodup {α : Type u_1} {β : Type u_2} {γ : Type u_3} (f : α → γ)\n (g : β → γ) {s : multiset α} {t : multiset β} (hs : nodup s) (ht : nodup t)\n (i : (a : α) → a ∈ s → β) (hi : ∀ (a : α) (ha : a ∈ s), i a ha ∈ t)\n (h : ∀ (a : α) (ha : a ∈ s), f a = g (i a ha))\n (i_inj : ∀ (a₁ a₂ : α) (ha₁ : a₁ ∈ s) (ha₂ : a₂ ∈ s), i a₁ ha₁ = i a₂ ha₂ → a₁ = a₂)\n (i_surj : ∀ (b : β), b ∈ t → ∃ (a : α), ∃ (ha : a ∈ s), b = i a ha) : map f s = map g t :=\n sorry\n\nend Mathlib", "meta": {"author": "AurelienSaue", "repo": "Mathlib4_auto", "sha": "590df64109b08190abe22358fabc3eae000943f2", "save_path": "github-repos/lean/AurelienSaue-Mathlib4_auto", "path": "github-repos/lean/AurelienSaue-Mathlib4_auto/Mathlib4_auto-590df64109b08190abe22358fabc3eae000943f2/Mathlib/data/multiset/nodup_auto.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879062662624377, "lm_q2_score": 0.058345840611681056, "lm_q1q2_score": 0.027351983181384903}} {"text": "/-\nCopyright (c) 2020 Bhavik Mehta. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Bhavik Mehta\n-/\nimport category_theory.limits.preserves.shapes.binary_products\nimport category_theory.limits.preserves.shapes.terminal\nimport category_theory.adjunction.fully_faithful\n\n/-!\n# Reflective functors\n\nBasic properties of reflective functors, especially those relating to their essential image.\n\nNote properties of reflective functors relating to limits and colimits are included in\n`category_theory.monad.limits`.\n-/\n\nuniverses v₁ v₂ v₃ u₁ u₂ u₃\n\nnoncomputable theory\n\nnamespace category_theory\n\nopen category adjunction limits\n\nvariables {C : Type u₁} {D : Type u₂} {E : Type u₃}\nvariables [category.{v₁} C] [category.{v₂} D] [category.{v₃} E]\n\n/--\nA functor is *reflective*, or *a reflective inclusion*, if it is fully faithful and right adjoint.\n-/\nclass reflective (R : D ⥤ C) extends is_right_adjoint R, full R, faithful R.\n\nvariables {i : D ⥤ C}\n\n/--\nFor a reflective functor `i` (with left adjoint `L`), with unit `η`, we have `η_iL = iL η`.\n-/\n-- TODO: This holds more generally for idempotent adjunctions, not just reflective adjunctions.\nlemma unit_obj_eq_map_unit [reflective i] (X : C) :\n (of_right_adjoint i).unit.app (i.obj ((left_adjoint i).obj X))\n = i.map ((left_adjoint i).map ((of_right_adjoint i).unit.app X)) :=\nbegin\n rw [←cancel_mono (i.map ((of_right_adjoint i).counit.app ((left_adjoint i).obj X))),\n ←i.map_comp],\n simp,\nend\n\n/--\nWhen restricted to objects in `D` given by `i : D ⥤ C`, the unit is an isomorphism. In other words,\n`η_iX` is an isomorphism for any `X` in `D`.\nMore generally this applies to objects essentially in the reflective subcategory, see\n`functor.ess_image.unit_iso`.\n-/\ninstance is_iso_unit_obj [reflective i] {B : D} :\n is_iso ((of_right_adjoint i).unit.app (i.obj B)) :=\nbegin\n have : (of_right_adjoint i).unit.app (i.obj B) =\n inv (i.map ((of_right_adjoint i).counit.app B)),\n { rw ← comp_hom_eq_id,\n apply (of_right_adjoint i).right_triangle_components },\n rw this,\n exact is_iso.inv_is_iso,\nend\n\n/--\nIf `A` is essentially in the image of a reflective functor `i`, then `η_A` is an isomorphism.\nThis gives that the \"witness\" for `A` being in the essential image can instead be given as the\nreflection of `A`, with the isomorphism as `η_A`.\n\n(For any `B` in the reflective subcategory, we automatically have that `ε_B` is an iso.)\n-/\nlemma functor.ess_image.unit_is_iso [reflective i] {A : C} (h : A ∈ i.ess_image) :\n is_iso ((of_right_adjoint i).unit.app A) :=\nbegin\n suffices : (of_right_adjoint i).unit.app A =\n h.get_iso.inv ≫ (of_right_adjoint i).unit.app (i.obj h.witness) ≫\n (left_adjoint i ⋙ i).map h.get_iso.hom,\n { rw this,\n apply_instance },\n rw ← nat_trans.naturality,\n simp,\nend\n\n/-- If `η_A` is an isomorphism, then `A` is in the essential image of `i`. -/\nlemma mem_ess_image_of_unit_is_iso [is_right_adjoint i] (A : C)\n [is_iso ((of_right_adjoint i).unit.app A)] : A ∈ i.ess_image :=\n⟨(left_adjoint i).obj A, ⟨(as_iso ((of_right_adjoint i).unit.app A)).symm⟩⟩\n\n/-- If `η_A` is a split monomorphism, then `A` is in the reflective subcategory. -/\nlemma mem_ess_image_of_unit_split_mono [reflective i] {A : C}\n [split_mono ((of_right_adjoint i).unit.app A)] : A ∈ i.ess_image :=\nbegin\n let η : 𝟭 C ⟶ left_adjoint i ⋙ i := (of_right_adjoint i).unit,\n haveI : is_iso (η.app (i.obj ((left_adjoint i).obj A))) := (i.obj_mem_ess_image _).unit_is_iso,\n have : epi (η.app A),\n { apply epi_of_epi (retraction (η.app A)) _,\n rw (show retraction _ ≫ η.app A = _, from η.naturality (retraction (η.app A))),\n apply epi_comp (η.app (i.obj ((left_adjoint i).obj A))) },\n resetI,\n haveI := is_iso_of_epi_of_split_mono (η.app A),\n exact mem_ess_image_of_unit_is_iso A,\nend\n\n/-- Composition of reflective functors. -/\ninstance reflective.comp (F : C ⥤ D) (G : D ⥤ E) [Fr : reflective F] [Gr : reflective G] :\n reflective (F ⋙ G) := { to_faithful := faithful.comp F G, }\n\n/-- (Implementation) Auxiliary definition for `unit_comp_partial_bijective`. -/\ndef unit_comp_partial_bijective_aux [reflective i] (A : C) (B : D) :\n (A ⟶ i.obj B) ≃ (i.obj ((left_adjoint i).obj A) ⟶ i.obj B) :=\n((adjunction.of_right_adjoint i).hom_equiv _ _).symm.trans (equiv_of_fully_faithful i)\n\n/-- The description of the inverse of the bijection `unit_comp_partial_bijective_aux`. -/\nlemma unit_comp_partial_bijective_aux_symm_apply [reflective i] {A : C} {B : D}\n (f : i.obj ((left_adjoint i).obj A) ⟶ i.obj B) :\n (unit_comp_partial_bijective_aux _ _).symm f = (of_right_adjoint i).unit.app A ≫ f :=\nby simp [unit_comp_partial_bijective_aux]\n\n/--\nIf `i` has a reflector `L`, then the function `(i.obj (L.obj A) ⟶ B) → (A ⟶ B)` given by\nprecomposing with `η.app A` is a bijection provided `B` is in the essential image of `i`.\nThat is, the function `λ (f : i.obj (L.obj A) ⟶ B), η.app A ≫ f` is bijective, as long as `B` is in\nthe essential image of `i`.\nThis definition gives an equivalence: the key property that the inverse can be described\nnicely is shown in `unit_comp_partial_bijective_symm_apply`.\n\nThis establishes there is a natural bijection `(A ⟶ B) ≃ (i.obj (L.obj A) ⟶ B)`. In other words,\nfrom the point of view of objects in `D`, `A` and `i.obj (L.obj A)` look the same: specifically\nthat `η.app A` is an isomorphism.\n-/\ndef unit_comp_partial_bijective [reflective i] (A : C) {B : C} (hB : B ∈ i.ess_image) :\n (A ⟶ B) ≃ (i.obj ((left_adjoint i).obj A) ⟶ B) :=\ncalc (A ⟶ B) ≃ (A ⟶ i.obj hB.witness) : iso.hom_congr (iso.refl _) hB.get_iso.symm\n ... ≃ (i.obj _ ⟶ i.obj hB.witness) : unit_comp_partial_bijective_aux _ _\n ... ≃ (i.obj ((left_adjoint i).obj A) ⟶ B) : iso.hom_congr (iso.refl _) hB.get_iso\n\n@[simp]\nlemma unit_comp_partial_bijective_symm_apply [reflective i] (A : C) {B : C}\n (hB : B ∈ i.ess_image) (f) :\n (unit_comp_partial_bijective A hB).symm f = (of_right_adjoint i).unit.app A ≫ f :=\nby simp [unit_comp_partial_bijective, unit_comp_partial_bijective_aux_symm_apply]\n\nlemma unit_comp_partial_bijective_symm_natural [reflective i] (A : C) {B B' : C} (h : B ⟶ B')\n (hB : B ∈ i.ess_image) (hB' : B' ∈ i.ess_image) (f : i.obj ((left_adjoint i).obj A) ⟶ B) :\n (unit_comp_partial_bijective A hB').symm (f ≫ h) =\n (unit_comp_partial_bijective A hB).symm f ≫ h :=\nby simp\n\nlemma unit_comp_partial_bijective_natural [reflective i] (A : C) {B B' : C} (h : B ⟶ B')\n (hB : B ∈ i.ess_image) (hB' : B' ∈ i.ess_image) (f : A ⟶ B) :\n (unit_comp_partial_bijective A hB') (f ≫ h) = unit_comp_partial_bijective A hB f ≫ h :=\nby rw [←equiv.eq_symm_apply, unit_comp_partial_bijective_symm_natural A h, equiv.symm_apply_apply]\n\nend category_theory\n", "meta": {"author": "JLimperg", "repo": "aesop3", "sha": "a4a116f650cc7403428e72bd2e2c4cda300fe03f", "save_path": "github-repos/lean/JLimperg-aesop3", "path": "github-repos/lean/JLimperg-aesop3/aesop3-a4a116f650cc7403428e72bd2e2c4cda300fe03f/src/category_theory/adjunction/reflective.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46101676450173545, "lm_q2_score": 0.05921024534589487, "lm_q1q2_score": 0.027296915734718392}} {"text": "structure BundledFunction (α β : Sort _) :=\n(toFun : α → β)\n\nnamespace BundledFunction\n\n-- `simp` doesn't seem to unify partial applications of structure projections:\n-- https://leanprover.zulipchat.com/#narrow/stream/287929-mathlib4/topic/.60simp.60.20failing.20on.20partial.20application.20of.20projections\ndef id (α) : BundledFunction α α := ⟨λ a => a⟩\n\n@[simp] theorem coe_id : (id α).toFun = _root_.id := rfl\n\nexample (x : α) : (id α).toFun x = x :=\nby simp only [coe_id, id_eq] -- should succeed\nexample (x : α) : (id α).toFun x = x :=\nby rw [coe_id, id_eq] -- succeeds\n\n-- seems to be another instance of the same behaviour:\n-- https://leanprover.zulipchat.com/#narrow/stream/287929-mathlib4/topic/.60simp.60.20calls.20broken.20in.20mathlib4.23922/near/314790371\n\ndef otherProjection (f : BundledFunction α β) : α → β := f.toFun\n\n-- Projections functions are expanded when populating the discrimination tree, and are indexed as `Expr.proj` objects.\n-- `@toFun α β` cannot be expanded into `Expr.proj` since there is a missing argument. The workaround is to add the missing argument.\n-- Then, we get `a.1 = otherProjection a`\n@[simp] theorem toFun_eq_otherProjection : @toFun α β a = otherProjection a := rfl\n@[simp] theorem id_apply : (id α).otherProjection x = x := rfl\n\nexample : (id α).toFun x = x := by simp only [toFun_eq_otherProjection, id_apply]; done -- should work\nexample : (id α).toFun x = x := by rw [toFun_eq_otherProjection, id_apply] -- succeeds\n\nend BundledFunction\n\n-- `simp` is happy with partial applications in other functions:\ndef id2 (x : α) := x\n\n@[simp] theorem id2_eq_id : @id2 α = id := rfl\n\nexample : id2 x = x := by simp only [id2_eq_id, id_eq] -- works fine\nexample : id2 x = x := by rw [id2_eq_id, id_eq] -- succeeds\n", "meta": {"author": "leanprover", "repo": "lean4", "sha": "742d053a97bdd109a41a921facd1cd6a55e89bc7", "save_path": "github-repos/lean/leanprover-lean4", "path": "github-repos/lean/leanprover-lean4/lean4-742d053a97bdd109a41a921facd1cd6a55e89bc7/tests/lean/run/1937.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40356685373537454, "lm_q2_score": 0.06754669254743426, "lm_q1q2_score": 0.027259606191598715}} {"text": "/-\nCopyright (c) 2018 Simon Hudon. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Simon Hudon\n\nInstances of `traversable` for types from the core library\n-/\nimport data.list.forall2\nimport data.set.lattice\nimport control.traversable.lemmas\n\nuniverses u v\n\nsection option\n\nopen functor\n\nvariables {F G : Type u → Type u}\nvariables [applicative F] [applicative G]\nvariables [is_lawful_applicative F] [is_lawful_applicative G]\n\nlemma option.id_traverse {α} (x : option α) : option.traverse id.mk x = x :=\nby cases x; refl\n\n@[nolint unused_arguments]\nlemma option.comp_traverse {α β γ} (f : β → F γ) (g : α → G β) (x : option α) :\n option.traverse (comp.mk ∘ (<$>) f ∘ g) x =\n comp.mk (option.traverse f <$> option.traverse g x) :=\nby cases x; simp! with functor_norm; refl\n\nlemma option.traverse_eq_map_id {α β} (f : α → β) (x : option α) :\n traverse (id.mk ∘ f) x = id.mk (f <$> x) :=\nby cases x; refl\n\nvariable (η : applicative_transformation F G)\n\nlemma option.naturality {α β} (f : α → F β) (x : option α) :\n η (option.traverse f x) = option.traverse (@η _ ∘ f) x :=\nby cases x with x; simp! [*] with functor_norm\n\nend option\n\ninstance : is_lawful_traversable option :=\n{ id_traverse := @option.id_traverse,\n comp_traverse := @option.comp_traverse,\n traverse_eq_map_id := @option.traverse_eq_map_id,\n naturality := @option.naturality,\n .. option.is_lawful_monad }\n\nnamespace list\n\nvariables {F G : Type u → Type u}\nvariables [applicative F] [applicative G]\n\nsection\nvariables [is_lawful_applicative F] [is_lawful_applicative G]\n\nopen applicative functor\nopen list (cons)\n\nprotected \n\n@[nolint unused_arguments]\nprotected lemma comp_traverse {α β γ} (f : β → F γ) (g : α → G β) (x : list α) :\n list.traverse (comp.mk ∘ (<$>) f ∘ g) x =\n comp.mk (list.traverse f <$> list.traverse g x) :=\nby induction x; simp! * with functor_norm; refl\n\nprotected lemma traverse_eq_map_id {α β} (f : α → β) (x : list α) :\n list.traverse (id.mk ∘ f) x = id.mk (f <$> x) :=\nby induction x; simp! * with functor_norm; refl\n\nvariable (η : applicative_transformation F G)\n\nprotected lemma naturality {α β} (f : α → F β) (x : list α) :\n η (list.traverse f x) = list.traverse (@η _ ∘ f) x :=\nby induction x; simp! * with functor_norm\nopen nat\n\ninstance : is_lawful_traversable.{u} list :=\n{ id_traverse := @list.id_traverse,\n comp_traverse := @list.comp_traverse,\n traverse_eq_map_id := @list.traverse_eq_map_id,\n naturality := @list.naturality,\n .. list.is_lawful_monad }\nend\n\nsection traverse\nvariables {α' β' : Type u} (f : α' → F β')\n\n@[simp] lemma traverse_nil : traverse f ([] : list α') = (pure [] : F (list β')) := rfl\n\n@[simp] lemma traverse_cons (a : α') (l : list α') :\n traverse f (a :: l) = (::) <$> f a <*> traverse f l := rfl\n\nvariables [is_lawful_applicative F]\n\n@[simp] lemma traverse_append :\n ∀ (as bs : list α'), traverse f (as ++ bs) = (++) <$> traverse f as <*> traverse f bs\n| [] bs :=\n have has_append.append ([] : list β') = id, by funext; refl,\n by simp [this] with functor_norm\n| (a :: as) bs := by simp [traverse_append as bs] with functor_norm; congr\n\nlemma mem_traverse {f : α' → set β'} :\n ∀(l : list α') (n : list β'), n ∈ traverse f l ↔ forall₂ (λb a, b ∈ f a) n l\n| [] [] := by simp\n| (a::as) [] := by simp; exact assume h, match h with end\n| [] (b::bs) := by simp\n| (a::as) (b::bs) :=\n suffices (b :: bs : list β') ∈ traverse f (a :: as) ↔ b ∈ f a ∧ bs ∈ traverse f as,\n by simp [mem_traverse as bs],\n iff.intro\n (assume ⟨_, ⟨b, hb, rfl⟩, _, hl, rfl⟩, ⟨hb, hl⟩)\n (assume ⟨hb, hl⟩, ⟨_, ⟨b, hb, rfl⟩, _, hl, rfl⟩)\n\nend traverse\n\nend list\n\nnamespace sum\n\nsection traverse\nvariables {σ : Type u}\nvariables {F G : Type u → Type u}\nvariables [applicative F] [applicative G]\n\nopen applicative functor\nopen list (cons)\n\nprotected lemma traverse_map {α β γ : Type u} (g : α → β) (f : β → G γ) (x : σ ⊕ α) :\n sum.traverse f (g <$> x) = sum.traverse (f ∘ g) x :=\nby cases x; simp [sum.traverse, id_map] with functor_norm; refl\n\nvariables [is_lawful_applicative F] [is_lawful_applicative G]\n\nprotected lemma id_traverse {σ α} (x : σ ⊕ α) : sum.traverse id.mk x = x :=\nby cases x; refl\n\n@[nolint unused_arguments]\nprotected lemma comp_traverse {α β γ} (f : β → F γ) (g : α → G β) (x : σ ⊕ α) :\n sum.traverse (comp.mk ∘ (<$>) f ∘ g) x =\n comp.mk (sum.traverse f <$> sum.traverse g x) :=\nby cases x; simp! [sum.traverse,map_id] with functor_norm; refl\n\nprotected lemma traverse_eq_map_id {α β} (f : α → β) (x : σ ⊕ α) :\n sum.traverse (id.mk ∘ f) x = id.mk (f <$> x) :=\nby induction x; simp! * with functor_norm; refl\n\nprotected lemma map_traverse {α β γ} (g : α → G β) (f : β → γ) (x : σ ⊕ α) :\n (<$>) f <$> sum.traverse g x = sum.traverse ((<$>) f ∘ g) x :=\nby cases x; simp [sum.traverse, id_map] with functor_norm; congr; refl\n\nvariable (η : applicative_transformation F G)\n\nprotected lemma naturality {α β} (f : α → F β) (x : σ ⊕ α) :\n η (sum.traverse f x) = sum.traverse (@η _ ∘ f) x :=\nby cases x; simp! [sum.traverse] with functor_norm\n\nend traverse\n\ninstance {σ : Type u} : is_lawful_traversable.{u} (sum σ) :=\n{ id_traverse := @sum.id_traverse σ,\n comp_traverse := @sum.comp_traverse σ,\n traverse_eq_map_id := @sum.traverse_eq_map_id σ,\n naturality := @sum.naturality σ,\n .. sum.is_lawful_monad }\n\nend sum\n", "meta": {"author": "JLimperg", "repo": "aesop3", "sha": "a4a116f650cc7403428e72bd2e2c4cda300fe03f", "save_path": "github-repos/lean/JLimperg-aesop3", "path": "github-repos/lean/JLimperg-aesop3/aesop3-a4a116f650cc7403428e72bd2e2c4cda300fe03f/src/control/traversable/instances.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4339814648038986, "lm_q2_score": 0.06278920640484009, "lm_q1q2_score": 0.027249351769446834}} {"text": "/-\nCopyright (c) 2018 Kenny Lau. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthor: Johannes Hölzl, Kenny Lau\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.default\nimport Mathlib.data.dfinsupp\nimport Mathlib.linear_algebra.basic\nimport Mathlib.PostPort\n\nuniverses u_1 u_3 u_2 u_4 \n\nnamespace Mathlib\n\n/-!\n# Properties of the semimodule `Π₀ i, M i`\n\nGiven an indexed collection of `R`-semimodules `M i`, the `R`-semimodule structure on `Π₀ i, M i`\nis defined in `data.dfinsupp`.\n\nIn this file we define `linear_map` versions of various maps:\n\n* `dfinsupp.lsingle a : M →ₗ[R] Π₀ i, M i`: `dfinsupp.single a` as a linear map;\n\n* `dfinsupp.lmk s : (Π i : (↑s : set ι), M i) →ₗ[R] Π₀ i, M i`: `dfinsupp.single a` as a linear map;\n\n* `dfinsupp.lapply i : (Π₀ i, M i) →ₗ[R] M`: the map `λ f, f i` as a linear map;\n\n* `dfinsupp.lsum`: `dfinsupp.sum` or `dfinsupp.lift_add_hom` as a `linear_map`;\n\n## Implementation notes\n\nThis file should try to mirror `linear_algebra.finsupp` where possible. The API of `finsupp` is\nmuch more developed, but many lemmas in that file should be eligible to copy over.\n\n## Tags\n\nfunction with finite support, semimodule, linear algebra\n-/\n\nnamespace dfinsupp\n\n\n/-- `dfinsupp.mk` as a `linear_map`. -/\ndef lmk {ι : Type u_1} {R : Type u_2} {M : ι → Type u_3} [dec_ι : DecidableEq ι] [semiring R] [(i : ι) → add_comm_monoid (M i)] [(i : ι) → semimodule R (M i)] (s : finset ι) : linear_map R ((i : ↥↑s) → M ↑i) (dfinsupp fun (i : ι) => M i) :=\n linear_map.mk (mk s) sorry sorry\n\n/-- `dfinsupp.single` as a `linear_map` -/\ndef lsingle {ι : Type u_1} {R : Type u_2} {M : ι → Type u_3} [dec_ι : DecidableEq ι] [semiring R] [(i : ι) → add_comm_monoid (M i)] [(i : ι) → semimodule R (M i)] (i : ι) : linear_map R (M i) (dfinsupp fun (i : ι) => M i) :=\n linear_map.mk (single i) sorry sorry\n\n/-- Two `R`-linear maps from `Π₀ i, M i` which agree on each `single i x` agree everywhere. -/\ntheorem lhom_ext {ι : Type u_1} {R : Type u_2} {M : ι → Type u_3} {N : Type u_4} [dec_ι : DecidableEq ι] [semiring R] [(i : ι) → add_comm_monoid (M i)] [(i : ι) → semimodule R (M i)] [add_comm_monoid N] [semimodule R N] {φ : linear_map R (dfinsupp fun (i : ι) => M i) N} {ψ : linear_map R (dfinsupp fun (i : ι) => M i) N} (h : ∀ (i : ι) (x : M i), coe_fn φ (single i x) = coe_fn ψ (single i x)) : φ = ψ :=\n linear_map.to_add_monoid_hom_injective (add_hom_ext h)\n\n/-- Two `R`-linear maps from `Π₀ i, M i` which agree on each `single i x` agree everywhere.\n\nSee note [partially-applied ext lemmas].\nAfter apply this lemma, if `M = R` then it suffices to verify `φ (single a 1) = ψ (single a 1)`. -/\ntheorem lhom_ext' {ι : Type u_1} {R : Type u_2} {M : ι → Type u_3} {N : Type u_4} [dec_ι : DecidableEq ι] [semiring R] [(i : ι) → add_comm_monoid (M i)] [(i : ι) → semimodule R (M i)] [add_comm_monoid N] [semimodule R N] {φ : linear_map R (dfinsupp fun (i : ι) => M i) N} {ψ : linear_map R (dfinsupp fun (i : ι) => M i) N} (h : ∀ (i : ι), linear_map.comp φ (lsingle i) = linear_map.comp ψ (lsingle i)) : φ = ψ :=\n lhom_ext fun (i : ι) => linear_map.congr_fun (h i)\n\n/-- Interpret `λ (f : Π₀ i, M i), f i` as a linear map. -/\ndef lapply {ι : Type u_1} {R : Type u_2} {M : ι → Type u_3} [semiring R] [(i : ι) → add_comm_monoid (M i)] [(i : ι) → semimodule R (M i)] (i : ι) : linear_map R (dfinsupp fun (i : ι) => M i) (M i) :=\n linear_map.mk (fun (f : dfinsupp fun (i : ι) => M i) => coe_fn f i) sorry sorry\n\n@[simp] theorem lmk_apply {ι : Type u_1} {R : Type u_2} {M : ι → Type u_3} [dec_ι : DecidableEq ι] [semiring R] [(i : ι) → add_comm_monoid (M i)] [(i : ι) → semimodule R (M i)] (s : finset ι) (x : (i : ↥↑s) → (fun (i : ι) => M i) ↑i) : coe_fn (lmk s) x = mk s x :=\n rfl\n\n@[simp] theorem lsingle_apply {ι : Type u_1} {R : Type u_2} {M : ι → Type u_3} [dec_ι : DecidableEq ι] [semiring R] [(i : ι) → add_comm_monoid (M i)] [(i : ι) → semimodule R (M i)] (i : ι) (x : M i) : coe_fn (lsingle i) x = single i x :=\n rfl\n\n@[simp] theorem lapply_apply {ι : Type u_1} {R : Type u_2} {M : ι → Type u_3} [semiring R] [(i : ι) → add_comm_monoid (M i)] [(i : ι) → semimodule R (M i)] (i : ι) (f : dfinsupp fun (i : ι) => M i) : coe_fn (lapply i) f = coe_fn f i :=\n rfl\n\n/-- The `dfinsupp` version of `finsupp.lsum`. -/\ndef lsum {ι : Type u_1} {R : Type u_2} {M : ι → Type u_3} {N : Type u_4} [dec_ι : DecidableEq ι] [semiring R] [(i : ι) → add_comm_monoid (M i)] [(i : ι) → semimodule R (M i)] [add_comm_monoid N] [semimodule R N] : ((i : ι) → linear_map R (M i) N) ≃+ linear_map R (dfinsupp fun (i : ι) => M i) N :=\n add_equiv.mk\n (fun (F : (i : ι) → linear_map R (M i) N) =>\n linear_map.mk ⇑(sum_add_hom fun (i : ι) => linear_map.to_add_monoid_hom (F i)) sorry sorry)\n (fun (F : linear_map R (dfinsupp fun (i : ι) => M i) N) (i : ι) => linear_map.comp F (lsingle i)) sorry sorry sorry\n\n", "meta": {"author": "AurelienSaue", "repo": "Mathlib4_auto", "sha": "590df64109b08190abe22358fabc3eae000943f2", "save_path": "github-repos/lean/AurelienSaue-Mathlib4_auto", "path": "github-repos/lean/AurelienSaue-Mathlib4_auto/Mathlib4_auto-590df64109b08190abe22358fabc3eae000943f2/Mathlib/linear_algebra/dfinsupp.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48047867804790706, "lm_q2_score": 0.056652427697058944, "lm_q1q2_score": 0.027220283568087516}} {"text": "import Lean\n\ndef checkWithMkMatcherInput (matcher : Lean.Name) : Lean.MetaM Unit :=\n Lean.Meta.Match.withMkMatcherInput matcher fun input => do\n let res ← Lean.Meta.Match.mkMatcher input\n let origMatcher ← Lean.getConstInfo matcher\n if not <| input.matcherName == matcher then\n throwError \"matcher name not reconstructed correctly: {matcher} ≟ {input.matcherName}\"\n\n let lCtx ← Lean.getLCtx\n let fvars ← Lean.collectFVars {} res.matcher\n let closure ← Lean.Meta.Closure.mkLambda (fvars.fvarSet.toList.toArray.map lCtx.get!) res.matcher\n\n let origTy := origMatcher.value!\n let newTy ← closure\n if not <| ←Lean.Meta.isDefEq origTy newTy then\n throwError \"matcher {matcher} does not round-trip correctly:\\n{origTy} ≟ {newTy}\"\n\nset_option smartUnfolding false\n\ndef f (xs : List Nat) : List Bool :=\nxs.map fun\n | 0 => true\n | _ => false\n#eval checkWithMkMatcherInput ``f.match_1\n\n#eval f [1, 2, 0, 2]\n\ntheorem ex1 : f [1, 0, 2] = [false, true, false] :=\nrfl\n\n#check f\n\nset_option pp.raw true\nset_option pp.raw.maxDepth 10\nset_option trace.Elab.step true in\ndef g (xs : List Nat) : List Bool :=\nxs.map <| by {\n intro\n | 0 => exact true\n | _ => exact false\n}\n\ntheorem ex2 : g [1, 0, 2] = [false, true, false] :=\nrfl\n\ntheorem ex3 {p q r : Prop} : p ∨ q → r → (q ∧ r) ∨ (p ∧ r) :=\nby intro\n | Or.inl hp, h => { apply Or.inr; apply And.intro; assumption; assumption }\n | Or.inr hq, h => { apply Or.inl; exact ⟨hq, h⟩ }\n#eval checkWithMkMatcherInput ``ex3.match_1\n\ninductive C\n| mk₁ : Nat → C\n| mk₂ : Nat → Nat → C\n\ndef C.x : C → Nat\n| C.mk₁ x => x\n| C.mk₂ x _ => x\n#eval checkWithMkMatcherInput ``C.x.match_1\n\ndef head : {α : Type} → List α → Option α\n| _, a::as => some a\n| _, _ => none\n#eval checkWithMkMatcherInput ``head.match_1\n\ntheorem ex4 : head [1, 2] = some 1 :=\nrfl\n\ndef head2 : {α : Type} → List α → Option α :=\n@fun\n | _, a::as => some a\n | _, _ => none\n\ntheorem ex5 : head2 [1, 2] = some 1 :=\nrfl\n\ndef head3 {α : Type} (xs : List α) : Option α :=\nlet rec aux : {α : Type} → List α → Option α\n | _, a::as => some a\n | _, _ => none;\naux xs\n\ntheorem ex6 : head3 [1, 2] = some 1 :=\nrfl\n\ninductive Vec.{u} (α : Type u) : Nat → Type u\n| nil : Vec α 0\n| cons {n} (head : α) (tail : Vec α n) : Vec α (n+1)\n\ndef Vec.mapHead1 {α β δ} : {n : Nat} → Vec α n → Vec β n → (α → β → δ) → Option δ\n| _, nil, nil, f => none\n| _, cons a as, cons b bs, f => some (f a b)\n#eval checkWithMkMatcherInput ``Vec.mapHead1.match_1\n\ndef Vec.mapHead2 {α β δ} : {n : Nat} → Vec α n → Vec β n → (α → β → δ) → Option δ\n| _, nil, nil, f => none\n| _, @cons _ n a as, cons b bs, f => some (f a b)\n#eval checkWithMkMatcherInput ``Vec.mapHead2.match_1\n\ndef Vec.mapHead3 {α β δ} : {n : Nat} → Vec α n → Vec β n → (α → β → δ) → Option δ\n| _, nil, nil, f => none\n| _, cons (tail := as) (head := a), cons b bs, f => some (f a b)\n\ninductive Foo\n| mk₁ (x y z w : Nat)\n| mk₂ (x y z w : Nat)\n\ndef Foo.z : Foo → Nat\n| mk₁ (z := z) .. => z\n| mk₂ (z := z) .. => z\n#eval checkWithMkMatcherInput ``Foo.z.match_1\n\n#eval (Foo.mk₁ 10 20 30 40).z\n\ntheorem ex7 : (Foo.mk₁ 10 20 30 40).z = 30 :=\nrfl\n\ndef Foo.addY? : Foo × Foo → Option Nat\n| (mk₁ (y := y₁) .., mk₁ (y := y₂) ..) => some (y₁ + y₂)\n| _ => none\n#eval checkWithMkMatcherInput ``Foo.addY?.match_1\n\n#eval Foo.addY? (Foo.mk₁ 1 2 3 4, Foo.mk₁ 10 20 30 40)\n\ntheorem ex8 : Foo.addY? (Foo.mk₁ 1 2 3 4, Foo.mk₁ 10 20 30 40) = some 22 :=\nrfl\n\ninstance {α} : Inhabited (Sigma fun m => Vec α m) :=\n⟨⟨0, Vec.nil⟩⟩\n\npartial def filter {α} (p : α → Bool) : {n : Nat} → Vec α n → Sigma fun m => Vec α m\n| _, Vec.nil => ⟨0, Vec.nil⟩\n| _, Vec.cons x xs => match p x, filter p xs with\n | true, ⟨_, ys⟩ => ⟨_, Vec.cons x ys⟩\n | false, ys => ys\n#eval checkWithMkMatcherInput ``filter.match_1\n\ninductive Bla\n| ofNat (x : Nat)\n| ofBool (x : Bool)\n\ndef Bla.optional? : Bla → Option Nat\n| ofNat x => some x\n| ofBool _ => none\n#eval checkWithMkMatcherInput ``Bla.optional?.match_1\n\ndef Bla.isNat? (b : Bla) : Option { x : Nat // optional? b = some x } :=\nmatch b.optional? with\n| some y => some ⟨y, rfl⟩\n| none => none\n#eval checkWithMkMatcherInput ``Bla.isNat?.match_1\n\ndef foo (b : Bla) : Option Nat := b.optional?\ntheorem fooEq (b : Bla) : foo b = b.optional? :=\nrfl\n\ndef Bla.isNat2? (b : Bla) : Option { x : Nat // optional? b = some x } :=\nmatch h:foo b with\n| some y => some ⟨y, Eq.trans (fooEq b).symm h⟩\n| none => none\n#eval checkWithMkMatcherInput ``Bla.isNat2?.match_1\n\ndef foo2 (x : Nat) : Nat :=\nmatch x, rfl : (y : Nat) → x = y → Nat with\n| 0, h => 0\n| x+1, h => 1\n#eval checkWithMkMatcherInput ``foo2.match_1\n", "meta": {"author": "subfish-zhou", "repo": "leanprover-zh_CN.github.io", "sha": "8b2985d4a3d458ceda9361ac454c28168d920d3f", "save_path": "github-repos/lean/subfish-zhou-leanprover-zh_CN.github.io", "path": "github-repos/lean/subfish-zhou-leanprover-zh_CN.github.io/leanprover-zh_CN.github.io-8b2985d4a3d458ceda9361ac454c28168d920d3f/tests/lean/run/match1.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47268347662043286, "lm_q2_score": 0.05749328404888363, "lm_q1q2_score": 0.027176125386552393}} {"text": "/-\nCopyright (c) 2018 Mario Carneiro. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Mario Carneiro, Minchao Wu\n-/\nimport meta.rb_map\nimport tactic.core\n/-!\n# `#explode` command\n\nDisplays a proof term in a line by line format somewhat akin to a Fitch style\nproof or the Metamath proof style.\n-/\n\nopen expr tactic\n\nnamespace tactic\nnamespace explode\n\n@[derive inhabited]\ninductive status : Type | reg | intro | lam | sintro\n\n/--\nA type to distinguish introduction or elimination rules represented as\nstrings from theorems referred to by their names.\n-/\nmeta inductive thm : Type\n| expr (e : expr)\n| name (n : name)\n| string (s : string)\n\n/--\nTurn a thm into a string.\n-/\nmeta def thm.to_string : thm → string\n| (thm.expr e) := e.to_string\n| (thm.name n) := n.to_string\n| (thm.string s) := s\n\nmeta structure entry : Type :=\n(expr : expr)\n(line : nat)\n(depth : nat)\n(status : status)\n(thm : thm)\n(deps : list nat)\n\nmeta def pad_right (l : list string) : list string :=\nlet n := l.foldl (λ r (s:string), max r s.length) 0 in\nl.map $ λ s, nat.iterate (λ s, s.push ' ') (n - s.length) s\n\n@[derive inhabited]\nmeta structure entries : Type := mk' ::\n(s : expr_map entry)\n(l : list entry)\n\nmeta def entries.find (es : entries) (e : expr) : option entry := es.s.find e\nmeta def entries.size (es : entries) : ℕ := es.s.size\n\nmeta def entries.add : entries → entry → entries\n| es@⟨s, l⟩ e := if s.contains e.expr then es else ⟨s.insert e.expr e, e :: l⟩\n\nmeta def entries.head (es : entries) : option entry := es.l.head'\n\nmeta def format_aux : list string → list string → list string → list entry → tactic format\n| (line :: lines) (dep :: deps) (thm :: thms) (en :: es) := do\n fmt ← do\n { let margin := string.join (list.repeat \" │\" en.depth),\n let margin := match en.status with\n | status.sintro := \" ├\" ++ margin\n | status.intro := \" │\" ++ margin ++ \" ┌\"\n | status.reg := \" │\" ++ margin ++ \"\"\n | status.lam := \" │\" ++ margin ++ \"\"\n end,\n p ← infer_type en.expr >>= pp,\n let lhs := line ++ \"│\" ++ dep ++ \"│ \" ++ thm ++ margin ++ \" \",\n return $ format.of_string lhs ++ (p.nest lhs.length).group ++ format.line },\n (++ fmt) <$> format_aux lines deps thms es\n| _ _ _ _ := return format.nil\n\nmeta instance : has_to_tactic_format entries :=\n⟨λ es : entries,\n let lines := pad_right $ es.l.map (λ en, to_string en.line),\n deps := pad_right $ es.l.map (λ en, string.intercalate \",\" (en.deps.map to_string)),\n thms := pad_right $ es.l.map (λ en, (entry.thm en).to_string) in\n format_aux lines deps thms es.l⟩\n\nmeta def append_dep (filter : expr → tactic unit)\n (es : entries) (e : expr) (deps : list nat) : tactic (list nat) :=\ndo { ei ← es.find e,\n filter ei.expr,\n return (ei.line :: deps) }\n<|> return deps\n\nmeta def may_be_proof (e : expr) : tactic bool :=\ndo expr.sort u ← infer_type e >>= infer_type,\n return $ bnot u.nonzero\n\nend explode\nopen explode\n\nmeta mutual def explode.core, explode.args (filter : expr → tactic unit)\nwith explode.core : expr → bool → nat → entries → tactic entries\n| e@(lam n bi d b) si depth es := do\n m ← mk_fresh_name,\n let l := local_const m n bi d,\n let b' := instantiate_var b l,\n if si then\n let en : entry := ⟨l, es.size, depth, status.sintro, thm.name n, []⟩ in do\n es' ← explode.core b' si depth (es.add en),\n return $ es'.add ⟨e, es'.size, depth, status.lam, thm.string \"∀I\", [es.size, es'.size - 1]⟩\n else do\n let en : entry := ⟨l, es.size, depth, status.intro, thm.name n, []⟩,\n es' ← explode.core b' si (depth + 1) (es.add en),\n -- in case of a \"have\" clause, the b' here has an annotation\n deps' ← explode.append_dep filter es' b'.erase_annotations [],\n deps' ← explode.append_dep filter es' l deps',\n return $ es'.add ⟨e, es'.size, depth, status.lam, thm.string \"∀I\", deps'⟩\n| e@(elet n t a b) si depth es := explode.core (reduce_lets e) si depth es\n| e@(macro n l) si depth es := explode.core l.head si depth es\n| e si depth es := filter e >>\n match get_app_fn_args e with\n | (nm@(const n _), args) :=\n explode.args e args depth es (thm.expr nm) []\n | (fn, []) := do\n let en : entry := ⟨fn, es.size, depth, status.reg, thm.expr fn, []⟩,\n return (es.add en)\n | (fn, args) := do\n es' ← explode.core fn ff depth es,\n -- in case of a \"have\" clause, the fn here has an annotation\n deps ← explode.append_dep filter es' fn.erase_annotations [],\n explode.args e args depth es' (thm.string \"∀E\") deps\n end\nwith explode.args : expr → list expr → nat → entries → thm → list nat → tactic entries\n| e (arg :: args) depth es thm deps := do\n es' ← explode.core arg ff depth es <|> return es,\n deps' ← explode.append_dep filter es' arg deps,\n explode.args e args depth es' thm deps'\n| e [] depth es thm deps :=\n return (es.add ⟨e, es.size, depth, status.reg, thm, deps.reverse⟩)\n\nmeta def explode_expr (e : expr) (hide_non_prop := tt) : tactic entries :=\nlet filter := if hide_non_prop then λ e, may_be_proof e >>= guardb else λ _, skip in\ntactic.explode.core filter e tt 0 (default _)\n\nmeta def explode (n : name) : tactic unit :=\ndo const n _ ← resolve_name n | fail \"cannot resolve name\",\n d ← get_decl n,\n v ← match d with\n | (declaration.defn _ _ _ v _ _) := return v\n | (declaration.thm _ _ _ v) := return v.get\n | _ := fail \"not a definition\"\n end,\n t ← pp d.type,\n explode_expr v <* trace (to_fmt n ++ \" : \" ++ t) >>= trace\n\nsetup_tactic_parser\n\n/--\n`#explode decl_name` displays a proof term in a line-by-line format somewhat akin to a Fitch-style\nproof or the Metamath proof style.\n`#explode_widget decl_name` renders a widget that displays an `#explode` proof.\n\n`#explode iff_true_intro` produces\n\n```lean\niff_true_intro : ∀ {a : Prop}, a → (a ↔ true)\n0│ │ a ├ Prop\n1│ │ h ├ a\n2│ │ hl │ ┌ a\n3│ │ trivial │ │ true\n4│2,3│ ∀I │ a → true\n5│ │ hr │ ┌ true\n6│5,1│ ∀I │ true → a\n7│4,6│ iff.intro │ a ↔ true\n8│1,7│ ∀I │ a → (a ↔ true)\n9│0,8│ ∀I │ ∀ {a : Prop}, a → (a ↔ true)\n```\n\nIn more detail:\n\nThe output of `#explode` is a Fitch-style proof in a four-column diagram modeled after Metamath\nproof displays like [this](http://us.metamath.org/mpeuni/ru.html). The headers of the columns are\n\"Step\", \"Hyp\", \"Ref\", \"Type\" (or \"Expression\" in the case of Metamath):\n* Step: An increasing sequence of numbers to number each step in the proof, used in the Hyp field.\n* Hyp: The direct children of the current step. Most theorems are implications like `A -> B -> C`,\n and so on the step proving `C` the Hyp field will refer to the steps that prove `A` and `B`.\n* Ref: The name of the theorem being applied. This is well-defined in Metamath, but in Lean there\n are some special steps that may have long names because the structure of proof terms doesn't\n exactly match this mold.\n * If the theorem is `foo (x y : Z) : A x -> B y -> C x y`:\n * the Ref field will contain `foo`,\n * `x` and `y` will be suppressed, because term construction is not interesting, and\n * the Hyp field will reference steps proving `A x` and `B y`. This corresponds to a proof term\n like `@foo x y pA pB` where `pA` and `pB` are subproofs.\n * If the head of the proof term is a local constant or lambda, then in this case the Ref will\n say `∀E` for forall-elimination. This happens when you have for example `h : A -> B` and\n `ha : A` and prove `b` by `h ha`; we reinterpret this as if it said `∀E h ha` where `∀E` is\n (n-ary) modus ponens.\n * If the proof term is a lambda, we will also use `∀I` for forall-introduction, referencing the\n body of the lambda. The indentation level will increase, and a bracket will surround the proof\n of the body of the lambda, starting at a proof step labeled with the name of the lambda variable\n and its type, and ending with the `∀I` step. Metamath doesn't have steps like this, but the\n style is based on Fitch proofs in first-order logic.\n* Type: This contains the type of the proof term, the theorem being proven at the current step.\n This proof layout differs from `#print` in using lots of intermediate step displays so that you\n can follow along and don't have to see term construction steps because they are implicitly in the\n intermediate step displays.\n\nAlso, it is common for a Lean theorem to begin with a sequence of lambdas introducing local\nconstants of the theorem. In order to minimize the indentation level, the `∀I` steps at the end of\nthe proof will be introduced in a group and the indentation will stay fixed. (The indentation\nbrackets are only needed in order to delimit the scope of assumptions, and these assumptions\nhave global scope anyway so detailed tracking is not necessary.)\n-/\n@[user_command]\nmeta def explode_cmd (_ : parse $ tk \"#explode\") : parser unit :=\ndo n ← ident,\n explode n\n.\n\nadd_tactic_doc\n{ name := \"#explode / #explode_widget\",\n category := doc_category.cmd,\n decl_names := [`tactic.explode_cmd, `tactic.explode_widget_cmd],\n inherit_description_from := `tactic.explode_cmd,\n tags := [\"proof display\", \"widgets\"] }\n\nend tactic\n", "meta": {"author": "jjaassoonn", "repo": "projective_space", "sha": "11fe19fe9d7991a272e7a40be4b6ad9b0c10c7ce", "save_path": "github-repos/lean/jjaassoonn-projective_space", "path": "github-repos/lean/jjaassoonn-projective_space/projective_space-11fe19fe9d7991a272e7a40be4b6ad9b0c10c7ce/src/tactic/explode.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3738758227716966, "lm_q2_score": 0.07263671087766833, "lm_q1q2_score": 0.027157110042818094}} {"text": "/-\nCopyright (c) 2017 Mario Carneiro. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Mario Carneiro, Yury Kudryashov.\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.default\nimport Mathlib.tactic.transform_decl\nimport Mathlib.tactic.algebra\nimport Mathlib.PostPort\n\nuniverses l \n\nnamespace Mathlib\n\n/-!\n# Transport multiplicative to additive\n\nThis file defines an attribute `to_additive` that can be used to\nautomatically transport theorems and definitions (but not inductive\ntypes and structures) from a multiplicative theory to an additive theory.\n\nUsage information is contained in the doc string of `to_additive.attr`.\n\n### Missing features\n\n* Automatically transport structures and other inductive types.\n\n* For structures, automatically generate theorems like `group α ↔\n add_group (additive α)`.\n\n* Rewrite rules for the last part of the name that work in more\n cases. E.g., we can replace `monoid` with `add_monoid` etc.\n-/\n\nnamespace to_additive\n\n\n/-- An auxiliary attribute used to store the names of the additive versions of declarations\nthat have been processed by `to_additive`. -/\n/-- A command that can be used to have future uses of `to_additive` change the `src` namespace\nto the `tgt` namespace.\n\nFor example:\n```\nrun_cmd to_additive.map_namespace `quotient_group `quotient_add_group\n```\n\nLater uses of `to_additive` on declarations in the `quotient_group` namespace will be created\nin the `quotient_add_group` namespaces.\n-/\n/-- `value_type` is the type of the arguments that can be provided to `to_additive`.\n`to_additive.parser` parses the provided arguments into `name` for the target and an\noptional doc string. -/\nstructure value_type \nwhere\n tgt : name\n doc : Option string\n\n/-- `add_comm_prefix x s` returns `\"comm_\" ++ s` if `x = tt` and `s` otherwise. -/\n/-- Dictionary used by `to_additive.guess_name` to autogenerate names. -/\n/-- Autogenerate target name for `to_additive`. -/\n/-- Return the provided target name or autogenerate one if one was not provided. -/\n/-- the parser for the arguments to `to_additive` -/\n/-- Add the `aux_attr` attribute to the structure fields of `src`\nso that future uses of `to_additive` will map them to the corresponding `tgt` fields. -/\n/--\nThe attribute `to_additive` can be used to automatically transport theorems\nand definitions (but not inductive types and structures) from a multiplicative\ntheory to an additive theory.\n\nTo use this attribute, just write:\n\n```\n@[to_additive]\ntheorem mul_comm' {α} [comm_semigroup α] (x y : α) : x * y = y * x := comm_semigroup.mul_comm\n```\n\nThis code will generate a theorem named `add_comm'`. It is also\npossible to manually specify the name of the new declaration, and\nprovide a documentation string:\n\n```\n@[to_additive add_foo \"add_foo doc string\"]\n/-- foo doc string -/\n", "meta": {"author": "AurelienSaue", "repo": "Mathlib4_auto", "sha": "590df64109b08190abe22358fabc3eae000943f2", "save_path": "github-repos/lean/AurelienSaue-Mathlib4_auto", "path": "github-repos/lean/AurelienSaue-Mathlib4_auto/Mathlib4_auto-590df64109b08190abe22358fabc3eae000943f2/Mathlib/algebra/group/to_additive.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35220178204788966, "lm_q2_score": 0.0769608415180331, "lm_q1q2_score": 0.027105745530556474}} {"text": "/-\nCopyright (c) 2019 Simon Hudon. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthor: Simon Hudon\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.default\nimport Mathlib.tactic.monotonicity.basic\nimport Mathlib.control.traversable.default\nimport Mathlib.control.traversable.derive\nimport Mathlib.Lean3Lib.data.dlist\nimport Mathlib.PostPort\n\nuniverses u v u_1 u_2 l \n\nnamespace Mathlib\n\nnamespace tactic.interactive\n\n\n/--\n`(prefix,left,right,suffix) ← match_assoc unif l r` finds the\nlongest prefix and suffix common to `l` and `r` and\nreturns them along with the differences -/\ndef apply_rel {α : Sort u} (R : α → α → Sort v) {x : α} {y : α} (x' : α) (y' : α) (h : R x y) (hx : x = x') (hy : y = y') : R x' y' :=\n eq.mpr sorry (eq.mpr sorry h)\n\n/-- tactic-facing function, similar to `interactive.tactic.generalize` with the\nexception that meta variables -/\ndef list.minimum_on {α : Type u_1} {β : Type u_2} [linear_order β] (f : α → β) : List α → List α :=\n sorry\n\n/--\n- `mono` applies a monotonicity rule.\n- `mono*` applies monotonicity rules repetitively.\n- `mono with x ≤ y` or `mono with [0 ≤ x,0 ≤ y]` creates an assertion for the listed\n propositions. Those help to select the right monotonicity rule.\n- `mono left` or `mono right` is useful when proving strict orderings:\n for `x + y < w + z` could be broken down into either\n - left: `x ≤ w` and `y < z` or\n - right: `x < w` and `y ≤ z`\n- `mono using [rule1,rule2]` calls `simp [rule1,rule2]` before applying mono.\n- The general syntax is `mono '*'? ('with' hyp | 'with' [hyp1,hyp2])? ('using' [hyp1,hyp2])? mono_cfg?\n\nTo use it, first import `tactic.monotonicity`.\n\nHere is an example of mono:\n\n```lean\nexample (x y z k : ℤ)\n (h : 3 ≤ (4 : ℤ))\n (h' : z ≤ y) :\n (k + 3 + x) - y ≤ (k + 4 + x) - z :=\nbegin\n mono, -- unfold `(-)`, apply add_le_add\n { -- ⊢ k + 3 + x ≤ k + 4 + x\n mono, -- apply add_le_add, refl\n -- ⊢ k + 3 ≤ k + 4\n mono },\n { -- ⊢ -y ≤ -z\n mono /- apply neg_le_neg -/ }\nend\n```\n\nMore succinctly, we can prove the same goal as:\n\n```lean\nexample (x y z k : ℤ)\n (h : 3 ≤ (4 : ℤ))\n (h' : z ≤ y) :\n (k + 3 + x) - y ≤ (k + 4 + x) - z :=\nby mono*\n```\n\n-/\n/--\ntransforms a goal of the form `f x ≼ f y` into `x ≤ y` using lemmas\nmarked as `monotonic`.\n\nSpecial care is taken when `f` is the repeated application of an\nassociative operator and if the operator is commutative\n-/\n/-- (repeat_until_or_at_most n t u): repeat tactic `t` at most n times or until u succeeds -/\ninductive rep_arity \nwhere\n| one : rep_arity\n| exactly : ℕ → rep_arity\n| many : rep_arity\n\n/--\n\n`ac_mono` reduces the `f x ⊑ f y`, for some relation `⊑` and a\nmonotonic function `f` to `x ≺ y`.\n\n`ac_mono*` unwraps monotonic functions until it can't.\n\n`ac_mono^k`, for some literal number `k` applies monotonicity `k`\ntimes.\n\n`ac_mono h`, with `h` a hypothesis, unwraps monotonic functions and\nuses `h` to solve the remaining goal. Can be combined with `*` or `^k`:\n`ac_mono* h`\n\n`ac_mono : p` asserts `p` and uses it to discharge the goal result\nunwrapping a series of monotonic functions. Can be combined with * or\n^k: `ac_mono* : p`\n\nIn the case where `f` is an associative or commutative operator,\n`ac_mono` will consider any possible permutation of its arguments and\nuse the one the minimizes the difference between the left-hand side\nand the right-hand side.\n\nTo use it, first import `tactic.monotonicity`.\n\n`ac_mono` can be used as follows:\n\n```lean\nexample (x y z k m n : ℕ)\n (h₀ : z ≥ 0)\n (h₁ : x ≤ y) :\n (m + x + n) * z + k ≤ z * (y + n + m) + k :=\nbegin\n ac_mono,\n -- ⊢ (m + x + n) * z ≤ z * (y + n + m)\n ac_mono,\n -- ⊢ m + x + n ≤ y + n + m\n ac_mono,\nend\n```\n\nAs with `mono*`, `ac_mono*` solves the goal in one go and so does\n`ac_mono* h₁`. The latter syntax becomes especially interesting in the\nfollowing example:\n\n```lean\nexample (x y z k m n : ℕ)\n (h₀ : z ≥ 0)\n (h₁ : m + x + n ≤ y + n + m) :\n (m + x + n) * z + k ≤ z * (y + n + m) + k :=\nby ac_mono* h₁.\n```\n\nBy giving `ac_mono` the assumption `h₁`, we are asking `ac_refl` to\nstop earlier than it would normally would.\n-/\n/-\nTODO(Simon): with `ac_mono h` and `ac_mono : p` split the remaining\n gaol if the provided rule does not solve it completely.\n-/\n\n", "meta": {"author": "AurelienSaue", "repo": "Mathlib4_auto", "sha": "590df64109b08190abe22358fabc3eae000943f2", "save_path": "github-repos/lean/AurelienSaue-Mathlib4_auto", "path": "github-repos/lean/AurelienSaue-Mathlib4_auto/Mathlib4_auto-590df64109b08190abe22358fabc3eae000943f2/Mathlib/tactic/monotonicity/interactive.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.05419873249666699, "lm_q1q2_score": 0.027099366248333496}} {"text": "/-\n## Finite interaction trees\n\nThe semantics framework for this project is extremely inspired by the Vellvm\nproject [1] and is essentially centered around interaction trees and monadic\ntransformers.\n\nInteractions trees are a particular instance of the freer monad; essentially,\nan ITree is a program that can have side effets through *interactions*, and\nthese interactions can either be interpreted into the program or kept as\nobservable side-effects.\n\nWhen giving semantics to a program, one usually starts with a rather simple\nITree where most of the complex features of the language (memory, I/O,\nexceptions, randomness, non-determinism, etc) are hidden behind interactions.\nThe interactions are then interpreted, which consists of (1) enriching the\nprogram's environment by a monadic transformation, and (2) replacing the\ninteraction with an actual implementation.\n\nThis approach allows monadic domains to be used while keeping each family of\ninteractions separate. This is relevant for Vellvm as LLVM IR has many complex\nfeatures, and even more relevant for MLIR since each dialect can bring more\ninteractions and environment transforms and all of them have to be studied and\ndefined independently.\n\nThe datatype of interaction trees normally has built-in non-termination by\nbeing defined coinductively. Support for coinduction is still limited in\nLean 4, so we currently use a finite version of ITrees (hence called Fitree)\nand we only model programs that always terminate.\n\n[1]: https://github.com/vellvm/vellvm\n-/\n\nimport MLIR.Semantics.SimpItree\nimport MLIR.Dialects\nimport MLIR.Util.WriterT\n\n/- Extendable effect families -/\n\nabbrev to1 (E: Type → Type u) (F: Type → Type v) :=\n ∀ T, E T → F T\nabbrev sum1 (E F: Type → Type) :=\n fun T => E T ⊕ F T\ninductive Void1: Type → Type :=\n\ninfixr:40 \" ~> \" => to1\ninfixr:60 \" +' \" => sum1\n\nclass Member (E: Type → Type) (F: Type → Type) where\n inject : E ~> F\n\ninstance MemberId {E}: Member E E where\n inject := (fun _ => id)\n\ninstance MemberSumL {E F G} [Member E F]: Member E (F +' G) where\n inject T := Sum.inl ∘ Member.inject T\n\ninstance MemberSumR {E F G} [Member E G]: Member E (F +' G) where\n inject T := Sum.inr ∘ Member.inject T\n\ninstance MemberSum {E F G H} [Member E G] [Member F H]:\n Member (E +' F) (G +' H) where\n inject T := Sum.cases (Member.inject T) (Member.inject T)\n\ninstance MemberVoid1 {E}:\n Member Void1 E where\n inject _ e := nomatch e\n\n-- Effects can now be put in context automatically by typeclass resolution\nexample E: Member E E := inferInstance\nexample E F: Member E (E +' F) := inferInstance\nexample E F: Member E (F +' (F +' E)) := inferInstance\nexample E F G: Member (E +' F) (E +' F +' G) := inferInstance\n\n\n/- The monadic domain; essentially finite Interaction Trees -/\n\ninductive Fitree (E: Type → Type) (R: Type) where\n | Ret (r: R): Fitree E R\n | Vis {T: Type} (e: E T) (k: T → Fitree E R): Fitree E R\n\ndef Fitree.map {E R R'} (f: R → R'): Fitree E R -> Fitree E R'\n| .Ret r => .Ret (f r)\n| .Vis e k => .Vis e (fun t => (k t).map f)\n\n@[simp_itree]\ndef Fitree.ret {E R}: R → Fitree E R :=\n Fitree.Ret\n\n@[simp_itree]\ndef Fitree.trigger {E: Type → Type} {F: Type → Type} {T} [Member E F]\n (e: E T): Fitree F T :=\n Fitree.Vis (Member.inject _ e) Fitree.ret\n\n\n@[simp_itree]\ndef Fitree.bind {E R T} (t: Fitree E T) (k: T → Fitree E R) :=\n match t with\n | Ret r => k r\n | Vis e k' => Vis e (fun r => bind (k' r) k)\n\ninstance {E}: Monad (Fitree E) where\n pure := Fitree.ret\n bind := Fitree.bind\n\n-- Since we only use finite ITrees, we can actually run them when they're\n-- fully interpreted (which leaves only the Ret constructor)\n@[simp_itree]\ndef Fitree.run {R}: Fitree Void1 R → R\n | Ret r => r\n | Vis e _ => nomatch e\n\n@[simp] theorem Fitree.run_ret:\n Fitree.run (Fitree.ret r) = r := rfl\n\n@[simp_itree]\ndef Fitree.translate {E F R} (f: E ~> F): Fitree E R → Fitree F R\n | Ret r => Ret r\n | Vis e k => Vis (f _ e) (fun r => translate f (k r))\n\n@[simp] theorem Fitree.translate_ret:\n Fitree.translate f (Fitree.ret r) = Fitree.ret r := rfl\n@[simp] theorem Fitree.translate_vis:\n Fitree.translate f (Vis e k) = Vis (f _ e) (fun r => translate f (k r)) :=\n rfl\n\n@[simp_itree]\ndef Fitree.case (h₁: E ~> G) (h₂: F ~> G): E +' F ~> G :=\n fun R ef => match ef with\n | Sum.inl e => h₁ R e\n | Sum.inr f => h₂ R f\n\n@[simp] theorem Fitree.case_left:\n Fitree.case h₁ h₂ _ (Sum.inl e) = h₁ _ e := rfl\n@[simp] theorem Fitree.case_right:\n Fitree.case h₁ h₂ _ (Sum.inr e) = h₂ _ e := rfl\n\n/-\n### Monadic interpretation\n-/\n\n@[simp_itree]\ndef Fitree.interp {M} [Monad M] {E} (h: E ~> M) {R}: Fitree E R → M R\n | .Ret r => pure r\n | .Vis e k => Bind.bind (h _ e) (fun t => interp h (k t))\n\n\n\n@[simp_itree]\ndef Fitree.interp' {E F} (h: E ~> Fitree Void1) {R} (t: Fitree (E +' F) R):\n Fitree F R :=\n interp (Fitree.case\n (fun _ e => (h _ e).translate $ fun _ e => nomatch e)\n (fun _ e => Fitree.trigger e)) t\n\n-- Interp `F` by lifting into a monad transformer (this is used when\n-- interpreting `E +' F` into the monad)\ndef Fitree.liftHandler {F M} [MonadLiftT (Fitree F) M]: F ~> M := fun R e =>\n monadLift (Fitree.trigger e: Fitree F R)\n\n-- Interpretation into various predefined monads. These are predefined so that\n-- rewriting theorems that expose the monad structure can be provided.\n\n@[simp_itree]\ndef Fitree.interpState {M S} [Monad M] {E} (h: E ~> StateT S M):\n forall {R}, Fitree E R → StateT S M R :=\n interp h\n\n@[simp_itree]\ndef Fitree.interpWriter {M} [Monad M] {E} (h: E ~> WriterT M):\n forall {R}, Fitree E R → WriterT M R :=\n interp h\n\n@[simp_itree]\ndef Fitree.interpOption {M} [Monad M] {E} (h: E ~> OptionT M):\n forall {R}, Fitree E R → OptionT M R :=\n interp h\n\n@[simp_itree]\ndef Fitree.interpExcept {M ε} [Monad M] {E} (h: E ~> ExceptT ε M) {R}:\n Fitree E R → ExceptT ε M R :=\n interp h\n\n/-\n### Combinator identities\n\nThe following theorems act as the main interface for computation on ITrees. We\ndon't unfold definitions because Lean 4 doesn't yet have the match-unfolding\nbehavior of Coq's `simpl` tactic, and runs into performance issues as unfolded\nterms grow larger. Instead, we aggressively rewrite the following simplifying\nequalities.\n-/\n\n@[simp] theorem Fitree.bind_ret:\n Fitree.bind (Fitree.ret r) k = k r := rfl\n\n@[simp] theorem Fitree.bind_Ret:\n Fitree.bind (Fitree.Ret r) k = k r := rfl\n\n@[simp] theorem Fitree.bind_ret':\n Fitree.bind t (fun r => Fitree.ret r) = t := by\n induction t with\n | Ret _ => rfl\n | Vis _ _ ih => simp [bind, ih]\n\n@[simp] theorem Fitree.bind_Ret':\n Fitree.bind t (fun r => Fitree.Ret r) = t := by\n induction t with\n | Ret _ => rfl\n | Vis _ _ ih => simp [bind, ih]\n\n@[simp] theorem Fitree.bind_bind:\n Fitree.bind (Fitree.bind t k) k' =\n Fitree.bind t (fun x => Fitree.bind (k x) k') := by\n induction t with\n | Ret _ => rfl\n | Vis _ _ ih => simp [bind, ih]\n\n@[simp] theorem Fitree.pure_is_ret:\n @Pure.pure (Fitree E) _ _ r = Fitree.ret r := rfl\n\n@[simp] theorem Fitree.bind_is_bind:\n @Bind.bind (Fitree E) _ _ _ t k = Fitree.bind t k := rfl\n\n@[simp] theorem Fitree.StateT_bind_is_bind (k: T → S → Fitree E (R × S)):\n StateT.bind (m := Fitree E) t k =\n fun s => Fitree.bind (t s) (fun (x,s) => k x s) := rfl\n\n@[simp] theorem Fitree.WriterT_bind_is_bind (k: T → Fitree E (R × String)):\n WriterT.bind (m := Fitree E) t k =\n Fitree.bind t (WriterT.bindCont k) := rfl\n\n@[simp] theorem Fitree.OptionT_bind_is_bind (k: T → Fitree E (Option R)):\n OptionT.bind (m := Fitree E) t k =\n Fitree.bind t (fun\n | some x => k x\n | none => Fitree.ret none) := rfl\n\n@[simp] theorem Fitree.ExceptT_bind_is_bind (k: T → Fitree E (Except ε R)):\n ExceptT.bind (m := Fitree E) t k = Fitree.bind t (ExceptT.bindCont k) := rfl\n\n@[simp] theorem Fitree.liftHandler_StateT_is_StateT_lift:\n @Fitree.liftHandler F (StateT S (Fitree F)) _ _ e =\n fun s => Fitree.bind (Fitree.trigger e) (fun x => Fitree.ret (x, s)) := rfl\n\n@[simp] theorem Fitree.liftHandler_WriterT_is_WriterT_lift:\n @Fitree.liftHandler F (WriterT (Fitree F)) _ _ e =\n Fitree.bind (Fitree.trigger e) (fun x => Fitree.ret (x, \"\")) := rfl\n\n@[simp] theorem Fitree.liftHandler_OptionT_is_OptionT_lift:\n @Fitree.liftHandler F (OptionT (Fitree F)) _ _ e =\n Fitree.bind (Fitree.trigger e) (fun x => Fitree.ret (some x)) := rfl\n\n@[simp] theorem Fitree.liftHandler_ExceptT_is_ExceptT_lift:\n @Fitree.liftHandler F (ExceptT ε (Fitree F)) _ _ e =\n Fitree.bind (Fitree.trigger e) (fun x => Fitree.ret (Except.ok x)) := rfl\n\n@[simp] theorem Member.injectId:\n @Member.inject E E MemberId _ e = e := rfl\n\n@[simp] theorem Member.injectSumL [Member E F]:\n @Member.inject E (F +' G) MemberSumL _ e = Sum.inl (Member.inject _ e) := rfl\n\n@[simp] theorem Member.injectSumR [Member E G]:\n @Member.inject E (F +' G) MemberSumR _ e = Sum.inr (Member.inject _ e) := rfl\n\n@[simp] theorem Member.injectSum_inl [Member E G] [Member F H]:\n @Member.inject (E +' F) (G +' H) MemberSum _ (Sum.inl e) =\n Sum.inl (Member.inject _ e) := rfl\n\n@[simp] theorem Member.injectSum_inr [Member E G] [Member F H]:\n @Member.inject (E +' F) (G +' H) MemberSum _ (Sum.inr e) =\n Sum.inr (Member.inject _ e) := rfl\n\n-- Interpretatin identities\n\n\n@[simp] theorem Fitree.interp_ret:\n Fitree.interp h (Fitree.ret r) = Fitree.ret r := rfl\n\n@[simp] theorem Fitree.interp_Ret:\n Fitree.interp h (Fitree.Ret r) = Fitree.ret r := rfl\n\n@[simp] theorem Fitree.interp_Vis:\n Fitree.interp h (Fitree.Vis e k) =\n Fitree.bind (h _ e) (fun x => Fitree.interp h (k x)) := rfl\n\n@[simp] theorem Fitree.interp'_ret:\n @Fitree.interp' E F h _ (Fitree.ret r) = Fitree.ret r := rfl\n\n@[simp] theorem Fitree.interp'_Vis_left:\n @Fitree.interp' E F h _ (Fitree.Vis (Sum.inl e) k) =\n Fitree.bind (Fitree.translate (fun _ e => nomatch e) (h _ e))\n (fun x => Fitree.interp' h (k x)) := rfl\n\n@[simp] theorem Fitree.interp'_Vis_right:\n @Fitree.interp' E F h _ (Fitree.Vis (Sum.inr e) k) =\n Fitree.bind (Fitree.trigger e)\n (fun x => Fitree.interp' h (k x)) := rfl\n\n@[simp] theorem Fitree.interpState_ret:\n Fitree.interpState h (Fitree.ret r) = (fun s => Fitree.ret (r, s)) := rfl\n\n@[simp] theorem Fitree.interpState_Vis {M S} [Monad M] (h: E ~> StateT S M):\n Fitree.interpState h (Fitree.Vis e k) =\n StateT.bind (h _ e) (fun x => Fitree.interpState h (k x)) := rfl\n\n@[simp] theorem Fitree.interpWriter_ret:\n Fitree.interpWriter h (Fitree.ret r) = Fitree.ret (r, \"\") := rfl\n\n@[simp] theorem Fitree.interpWriter_Vis {M} [Monad M] (h: E ~> WriterT M):\n Fitree.interpWriter h (Fitree.Vis e k) =\n WriterT.bind (h _ e) (fun x => Fitree.interpWriter h (k x)) := rfl\n\n@[simp] theorem Fitree.interpOption_ret:\n Fitree.interpOption h (Fitree.ret r) = Fitree.ret (some r) := rfl\n\n@[simp] theorem Fitree.interpOption_Vis {M} [Monad M] (h: E ~> OptionT M):\n Fitree.interpOption h (Fitree.Vis e k) =\n OptionT.bind (h _ e) (fun x => Fitree.interpOption h (k x)) := rfl\n\n@[simp] theorem Fitree.interpExcept_ret:\n Fitree.interpExcept h (Fitree.ret r) = Fitree.ret (.ok r) := rfl\n\n@[simp] theorem Fitree.interpExcept_Vis {M ε} [Monad M] (h: E ~> ExceptT ε M):\n Fitree.interpExcept h (Fitree.Vis e k) =\n ExceptT.bind (h _ e) (fun x => Fitree.interpExcept h (k x)) := rfl\n\n-- We don't assume [LawfulMonad M] so we can't simplify the continuation. But\n-- when it's an ITree the other simp lemmas will do it anyway.\n@[simp] theorem Fitree.interp_trigger [Member E F] [Monad M] (e: E T):\n Fitree.interp (M := M) (E := F) h (Fitree.trigger e) =\n Bind.bind (h _ (Member.inject _ e)) (fun x => pure x) := rfl\n\n@[simp] theorem Fitree.interp'_trigger_left (e: E R):\n @Fitree.interp' E F h _ (@Fitree.trigger (E +' F) _ _ MemberId (Sum.inl e)) =\n Fitree.bind\n (Fitree.translate (fun _ e => nomatch e) (h _ (Member.inject _ e)))\n (fun x => pure x) := rfl\n\n@[simp] theorem Fitree.interp'_trigger_right [Member G F]:\n @Fitree.interp' E F h _ (@Fitree.trigger (E +' G) (E +' F) _ _ (Sum.inr e)) =\n Fitree.trigger e := rfl\n\n-- The following theorems are only applied manually\n\ntheorem Fitree.run_bind {T R} (t: Fitree Void1 T) (k: T → Fitree Void1 R):\n run (bind t k) = run (k (run t)) :=\n match t with\n | Ret _ => rfl\n | Vis e _ => nomatch e\n\ntheorem Fitree.interp_bind:\n Fitree.interp h (Fitree.bind t k) =\n Fitree.bind (Fitree.interp h t) (fun x => Fitree.interp h (k x)) := by\n induction t with\n | Ret _ => rfl\n | Vis _ _ ih => simp [bind, ih]\n\ntheorem Fitree.interp'_bind:\n Fitree.interp' h (Fitree.bind t k) =\n Fitree.bind (Fitree.interp' h t) (fun x => Fitree.interp' h (k x)) := by\n simp [interp', interp_bind]\n\n-- Specialized interp_bind lemmas that unfold the monadic structure and expose\n-- the Fitree.bind directly rather than the monadic Bind.bind\n\ntheorem Fitree.interpState_bind (h: E ~> StateT S (Fitree F)) (t: Fitree E R):\n Fitree.interpState h (Fitree.bind t k) s =\n Fitree.bind (Fitree.interpState h t s)\n (fun (x,s') => Fitree.interpState h (k x) s') := by\n revert s\n induction t with\n | Ret _ => intros s; rfl\n | Vis _ _ ih =>\n simp [interpState] at *\n simp [interp, Bind.bind, StateT.bind]\n simp [ih]\n\nexample {F R}: WriterT (Fitree F) R = Fitree F (R × String) := by\n simp [WriterT]\n\ntheorem Fitree.interpWriter_bind (h: E ~> WriterT (Fitree F))\n (t: Fitree E T) (k: T → Fitree E R):\n Fitree.interpWriter h (Fitree.bind t k) =\n Fitree.bind (Fitree.interpWriter h t) fun (x,s₁) =>\n Fitree.bind (Fitree.interpWriter h (k x)) fun (y,s₂) =>\n Fitree.ret (y,s₁++s₂) := by\n induction t with\n | Ret _ =>\n simp [bind, interpWriter]\n have h₁: forall x, \"\" ++ x = x := by\n simp [HAppend.hAppend, Append.append, String.append]\n simp [List.nil_append]\n simp [h₁]\n have h₂: forall (α β: Type) (x: α × β), (x.fst, x.snd) = x := by simp\n simp [h₂]\n | Vis _ _ ih =>\n simp [interpWriter] at *\n simp [interp, Bind.bind, WriterT.bindCont, WriterT.mk]\n have h: forall (x y z: String), x ++ (y ++ z) = x ++ y ++ z := by\n simp [HAppend.hAppend, Append.append, String.append]\n simp [List.append_assoc]\n simp [ih, h]\n\ntheorem Fitree.interpOption_bind (h: E ~> OptionT (Fitree F))\n (t: Fitree E T) (k: T → Fitree E R):\n Fitree.interpOption h (Fitree.bind t k) =\n Fitree.bind (Fitree.interpOption h t) fun x? =>\n match x? with\n | some x => Fitree.interpOption h (k x)\n | none => Fitree.ret none := by\n induction t with\n | Ret _ => rfl\n | Vis _ _ ih =>\n simp [interpOption] at *\n simp [interp, bind, Bind.bind, OptionT.bind, OptionT.mk]\n -- I can't get a bind (match) → match (bind) theorem to rewrite, so...\n have fequal2 α β (f g: α → β) x y: f = g → x = y → f x = g y :=\n fun h₁ h₂ => by simp [h₁, h₂]\n apply fequal2; rfl; funext x\n cases x <;> simp [ih]\n\ntheorem Fitree.interpExcept_bind (h: E ~> ExceptT ε (Fitree F))\n (t: Fitree E T) (k: T → Fitree E R):\n Fitree.interpExcept h (Fitree.bind t k) =\n Fitree.bind (Fitree.interpExcept h t) fun x? =>\n match x? with\n | .error ε => Fitree.ret (.error ε)\n | .ok x => Fitree.interpExcept h (k x) := by\n induction t with\n | Ret _ => rfl\n | Vis _ _ ih =>\n simp [interpExcept] at *\n simp [interp, bind, Bind.bind]\n simp [ExceptT.bind, ExceptT.mk, ExceptT.bindCont]\n -- See above\n have fequal2 α β (f g: α → β) x y: f = g → x = y → f x = g y :=\n fun h₁ h₂ => by simp [h₁, h₂]\n apply fequal2; rfl; funext x\n cases x <;> simp [ih]\n\n-- This theorem has the drawback of hiding the continuation of `bind` into the\n-- `Vis` node, which blocks other theorems like `Fitree.bind_bind`.\ntheorem Fitree.bind_trigger [Member E F] (e: E T) (k: T → Fitree F R):\n Fitree.bind (Fitree.trigger e) k = Fitree.Vis (Member.inject _ e) k := rfl\n\n/-\n### Other properties\n-/\n\ninductive Fitree.noEventL {E F R}: Fitree (E +' F) R → Prop :=\n | Ret r: noEventL (Ret r)\n | Vis f k: (∀ t, noEventL (k t)) → noEventL (Vis (Sum.inr f) k)\n\n\n\n/-\n### Automation tools\n-/\n\n/- Rewriting tactics `simp_itree` and `dsimp_itree` -/\n\nopen Lean Elab.Tactic Parser.Tactic\n\ndef toSimpLemma (name: Name): Syntax :=\n mkNode `Lean.Parser.Tactic.simpLemma #[mkNullNode, mkNullNode, mkIdent name]\n\ndef tacticSimpItree (definitional: Bool): TacticM Unit := do\n -- TODO: Also handle .lemmaNames, not just unfolding!\n let lemmas := (← SimpItreeExtension.getTheorems).toUnfold.fold\n (init := #[]) (fun acc n => acc.push (toSimpLemma n))\n let others := [\n ``Fitree.liftHandler, ``Member.inject,\n ``StateT.bind, ``StateT.pure, ``StateT.lift,\n ``OptionT.bind, ``OptionT.pure, ``OptionT.mk, ``OptionT.lift,\n ``ExceptT.pure, ``ExceptT.mk,\n ``bind, ``pure, ``cast_eq, ``Eq.mpr].map toSimpLemma\n let fullSet :=\n (lemmas.reverse ++ others).toList.intersperse (mkAtom \",\") |>.toArray\n if definitional then\n evalTactic $ ← `(tactic|dsimp [$(⟨fullSet⟩),*])\n else\n evalTactic $ ← `(tactic|simp [$(⟨fullSet⟩),*])\n\nelab \"simp_itree\": tactic => tacticSimpItree false\nelab \"dsimp_itree\": tactic => tacticSimpItree true\n", "meta": {"author": "opencompl", "repo": "lean-mlir", "sha": "85fd61e38dec57e4d67d7af4d49a1ccc67828c1b", "save_path": "github-repos/lean/opencompl-lean-mlir", "path": "github-repos/lean/opencompl-lean-mlir/lean-mlir-85fd61e38dec57e4d67d7af4d49a1ccc67828c1b/MLIR/Semantics/Fitree.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4186969093556867, "lm_q2_score": 0.06465348745509981, "lm_q1q2_score": 0.027070215376516955}} {"text": "/-\nCopyright (c) 2017 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Leonardo de Moura\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.meta.default\nimport Mathlib.Lean3Lib.init.data.sigma.lex\nimport Mathlib.Lean3Lib.init.data.nat.lemmas\nimport Mathlib.Lean3Lib.init.data.list.instances\nimport Mathlib.Lean3Lib.init.data.list.qsort\n\nuniverses u v \n\nnamespace Mathlib\n\n/- TODO(Leo): move this lemma, or delete it after we add algebraic normalizer. -/\n\ntheorem nat.lt_add_of_zero_lt_left (a : ℕ) (b : ℕ) (h : 0 < b) : a < a + b :=\n (fun (this : a + 0 < a + b) => this) (nat.add_lt_add_left h a)\n\n/- TODO(Leo): move this lemma, or delete it after we add algebraic normalizer. -/\n\ntheorem nat.zero_lt_one_add (a : ℕ) : 0 < 1 + a := sorry\n\n/- TODO(Leo): move this lemma, or delete it after we add algebraic normalizer. -/\n\ntheorem nat.lt_add_right (a : ℕ) (b : ℕ) (c : ℕ) : a < b → a < b + c :=\n fun (h : a < b) => lt_of_lt_of_le h (nat.le_add_right b c)\n\n/- TODO(Leo): move this lemma, or delete it after we add algebraic normalizer. -/\n\ntheorem nat.lt_add_left (a : ℕ) (b : ℕ) (c : ℕ) : a < b → a < c + b :=\n fun (h : a < b) => lt_of_lt_of_le h (nat.le_add_left b c)\n\nprotected def psum.alt.sizeof {α : Type u} {β : Type v} [SizeOf α] [SizeOf β] : psum α β → ℕ :=\n sorry\n\nprotected def psum.has_sizeof_alt (α : Type u) (β : Type v) [SizeOf α] [SizeOf β] :\n SizeOf (psum α β) :=\n { sizeOf := psum.alt.sizeof }\n\nend Mathlib", "meta": {"author": "AurelienSaue", "repo": "Mathlib4_auto", "sha": "590df64109b08190abe22358fabc3eae000943f2", "save_path": "github-repos/lean/AurelienSaue-Mathlib4_auto", "path": "github-repos/lean/AurelienSaue-Mathlib4_auto/Mathlib4_auto-590df64109b08190abe22358fabc3eae000943f2/Mathlib/Lean3Lib/init/meta/well_founded_tactics_auto.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.05582314231270586, "lm_q1q2_score": 0.027039618378034556}} {"text": "/-\nCopyright (c) 2018 Simon Hudon. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Simon Hudon\n-/\nimport control.applicative\nimport data.list.forall2\nimport data.set.functor\n\n/-!\n# Traversable instances\n\nThis file provides instances of `traversable` for types from the core library: `option`, `list` and\n`sum`.\n-/\n\nuniverses u v\n\nsection option\n\nopen functor\n\nvariables {F G : Type u → Type u}\nvariables [applicative F] [applicative G]\nvariables [is_lawful_applicative F] [is_lawful_applicative G]\n\nlemma option.id_traverse {α} (x : option α) : option.traverse id.mk x = x :=\nby cases x; refl\n\n@[nolint unused_arguments]\nlemma option.comp_traverse {α β γ} (f : β → F γ) (g : α → G β) (x : option α) :\n option.traverse (comp.mk ∘ (<$>) f ∘ g) x =\n comp.mk (option.traverse f <$> option.traverse g x) :=\nby cases x; simp! with functor_norm; refl\n\nlemma option.traverse_eq_map_id {α β} (f : α → β) (x : option α) :\n traverse (id.mk ∘ f) x = id.mk (f <$> x) :=\nby cases x; refl\n\nvariable (η : applicative_transformation F G)\n\nlemma option.naturality {α β} (f : α → F β) (x : option α) :\n η (option.traverse f x) = option.traverse (@η _ ∘ f) x :=\nby cases x with x; simp! [*] with functor_norm\n\nend option\n\ninstance : is_lawful_traversable option :=\n{ id_traverse := @option.id_traverse,\n comp_traverse := @option.comp_traverse,\n traverse_eq_map_id := @option.traverse_eq_map_id,\n naturality := @option.naturality,\n .. option.is_lawful_monad }\n\nnamespace list\n\nvariables {F G : Type u → Type u}\nvariables [applicative F] [applicative G]\n\nsection\nvariables [is_lawful_applicative F] [is_lawful_applicative G]\n\nopen applicative functor list\n\nprotected lemma id_traverse {α} (xs : list α) :\n list.traverse id.mk xs = xs :=\nby induction xs; simp! * with functor_norm; refl\n\n@[nolint unused_arguments]\nprotected lemma comp_traverse {α β γ} (f : β → F γ) (g : α → G β) (x : list α) :\n list.traverse (comp.mk ∘ (<$>) f ∘ g) x =\n comp.mk (list.traverse f <$> list.traverse g x) :=\nby induction x; simp! * with functor_norm; refl\n\nprotected lemma traverse_eq_map_id {α β} (f : α → β) (x : list α) :\n list.traverse (id.mk ∘ f) x = id.mk (f <$> x) :=\nby induction x; simp! * with functor_norm; refl\n\nvariable (η : applicative_transformation F G)\n\nprotected lemma naturality {α β} (f : α → F β) (x : list α) :\n η (list.traverse f x) = list.traverse (@η _ ∘ f) x :=\nby induction x; simp! * with functor_norm\nopen nat\n\ninstance : is_lawful_traversable.{u} list :=\n{ id_traverse := @list.id_traverse,\n comp_traverse := @list.comp_traverse,\n traverse_eq_map_id := @list.traverse_eq_map_id,\n naturality := @list.naturality,\n .. list.is_lawful_monad }\nend\n\nsection traverse\nvariables {α' β' : Type u} (f : α' → F β')\n\n@[simp] lemma traverse_nil : traverse f ([] : list α') = (pure [] : F (list β')) := rfl\n\n@[simp] lemma traverse_cons (a : α') (l : list α') :\n traverse f (a :: l) = (::) <$> f a <*> traverse f l := rfl\n\nvariables [is_lawful_applicative F]\n\n@[simp] lemma traverse_append :\n ∀ (as bs : list α'), traverse f (as ++ bs) = (++) <$> traverse f as <*> traverse f bs\n| [] bs :=\n have has_append.append ([] : list β') = id, by funext; refl,\n by simp [this] with functor_norm\n| (a :: as) bs := by simp [traverse_append as bs] with functor_norm; congr\n\nlemma mem_traverse {f : α' → set β'} :\n ∀(l : list α') (n : list β'), n ∈ traverse f l ↔ forall₂ (λb a, b ∈ f a) n l\n| [] [] := by simp\n| (a::as) [] := by simp\n| [] (b::bs) := by simp\n| (a::as) (b::bs) := by simp [mem_traverse as bs]\n\nend traverse\n\nend list\n\nnamespace sum\n\nsection traverse\nvariables {σ : Type u}\nvariables {F G : Type u → Type u}\nvariables [applicative F] [applicative G]\n\nopen applicative functor\nopen list (cons)\n\nprotected lemma traverse_map {α β γ : Type u} (g : α → β) (f : β → G γ) (x : σ ⊕ α) :\n sum.traverse f (g <$> x) = sum.traverse (f ∘ g) x :=\nby cases x; simp [sum.traverse, id_map] with functor_norm; refl\n\nvariables [is_lawful_applicative F] [is_lawful_applicative G]\n\nprotected lemma id_traverse {σ α} (x : σ ⊕ α) : sum.traverse id.mk x = x :=\nby cases x; refl\n\n@[nolint unused_arguments]\nprotected lemma comp_traverse {α β γ} (f : β → F γ) (g : α → G β) (x : σ ⊕ α) :\n sum.traverse (comp.mk ∘ (<$>) f ∘ g) x =\n comp.mk (sum.traverse f <$> sum.traverse g x) :=\nby cases x; simp! [sum.traverse,map_id] with functor_norm; refl\n\nprotected lemma traverse_eq_map_id {α β} (f : α → β) (x : σ ⊕ α) :\n sum.traverse (id.mk ∘ f) x = id.mk (f <$> x) :=\nby induction x; simp! * with functor_norm; refl\n\nprotected lemma map_traverse {α β γ} (g : α → G β) (f : β → γ) (x : σ ⊕ α) :\n (<$>) f <$> sum.traverse g x = sum.traverse ((<$>) f ∘ g) x :=\nby cases x; simp [sum.traverse, id_map] with functor_norm; congr; refl\n\nvariable (η : applicative_transformation F G)\n\nprotected lemma naturality {α β} (f : α → F β) (x : σ ⊕ α) :\n η (sum.traverse f x) = sum.traverse (@η _ ∘ f) x :=\nby cases x; simp! [sum.traverse] with functor_norm\n\nend traverse\n\ninstance {σ : Type u} : is_lawful_traversable.{u} (sum σ) :=\n{ id_traverse := @sum.id_traverse σ,\n comp_traverse := @sum.comp_traverse σ,\n traverse_eq_map_id := @sum.traverse_eq_map_id σ,\n naturality := @sum.naturality σ,\n .. sum.is_lawful_monad }\n\nend sum\n", "meta": {"author": "Parinya-Siri", "repo": "lean-machine-learning", "sha": "ec610bac246ae7108fc6f0c140b3440f0fbacc52", "save_path": "github-repos/lean/Parinya-Siri-lean-machine-learning", "path": "github-repos/lean/Parinya-Siri-lean-machine-learning/lean-machine-learning-ec610bac246ae7108fc6f0c140b3440f0fbacc52/matlib/control/traversable/instances.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.36658972248186, "lm_q2_score": 0.07369627682665668, "lm_q1q2_score": 0.0270162976698304}} {"text": "/-\nCopyright (c) 2020 Simon Hudon. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthor(s): Simon Hudon\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.default\nimport Mathlib.control.monad.basic\nimport Mathlib.control.monad.cont\nimport Mathlib.control.monad.writer\nimport Mathlib.data.equiv.basic\nimport Mathlib.tactic.interactive\nimport Mathlib.PostPort\n\nuniverses u₀ u₁ v₀ v₁ l u_1 u_2 u_3 u_4 u_5 u_6 \n\nnamespace Mathlib\n\n/-!\n# Universe lifting for type families\n\nSome functors such as `option` and `list` are universe polymorphic. Unlike\ntype polymorphism where `option α` is a function application and reasoning and\ngeneralizations that apply to functions can be used, `option.{u}` and `option.{v}`\nare not one function applied to two universe names but one polymorphic definition\ninstantiated twice. This means that whatever works on `option.{u}` is hard\nto transport over to `option.{v}`. `uliftable` is an attempt at improving the situation.\n\n`uliftable option.{u} option.{v}` gives us a generic and composable way to use\n`option.{u}` in a context that requires `option.{v}`. It is often used in tandem with\n`ulift` but the two are purposefully decoupled.\n\n\n## Main definitions\n * `uliftable` class\n\n## Tags\n\nuniverse polymorphism functor\n\n-/\n\n/-- Given a universe polymorphic type family `M.{u} : Type u₁ → Type\nu₂`, this class convert between instantiations, from\n`M.{u} : Type u₁ → Type u₂` to `M.{v} : Type v₁ → Type v₂` and back -/\nclass uliftable (f : Type u₀ → Type u₁) (g : Type v₀ → Type v₁) \nwhere\n congr : {α : Type u₀} → {β : Type v₀} → α ≃ β → f α ≃ g β\n\nnamespace uliftable\n\n\n/-- The most common practical use `uliftable` (together with `up`), this function takes\n`x : M.{u} α` and lifts it to M.{max u v} (ulift.{v} α) -/\ndef up {f : Type u₀ → Type u₁} {g : Type (max u₀ v₀) → Type v₁} [uliftable f g] {α : Type u₀} : f α → g (ulift α) :=\n equiv.to_fun (congr f g (equiv.symm equiv.ulift))\n\n/-- The most common practical use of `uliftable` (together with `up`), this function takes\n`x : M.{max u v} (ulift.{v} α)` and lowers it to `M.{u} α` -/\ndef down {f : Type u₀ → Type u₁} {g : Type (max u₀ v₀) → Type v₁} [uliftable f g] {α : Type u₀} : g (ulift α) → f α :=\n equiv.inv_fun (congr f g (equiv.symm equiv.ulift))\n\n/-- convenient shortcut to avoid manipulating `ulift` -/\ndef adapt_up (F : Type v₀ → Type v₁) (G : Type (max v₀ u₀) → Type u₁) [uliftable F G] [Monad G] {α : Type v₀} {β : Type (max v₀ u₀)} (x : F α) (f : α → G β) : G β :=\n up x >>= f ∘ ulift.down\n\n/-- convenient shortcut to avoid manipulating `ulift` -/\ndef adapt_down {F : Type (max u₀ v₀) → Type u₁} {G : Type v₀ → Type v₁} [L : uliftable G F] [Monad F] {α : Type (max u₀ v₀)} {β : Type v₀} (x : F α) (f : α → G β) : G β :=\n down (x >>= up ∘ f)\n\n/-- map function that moves up universes -/\ndef up_map {F : Type u₀ → Type u₁} {G : Type (max u₀ v₀) → Type v₁} [inst : uliftable F G] [Functor G] {α : Type u₀} {β : Type (max u₀ v₀)} (f : α → β) (x : F α) : G β :=\n (f ∘ ulift.down) <$> up x\n\n/-- map function that moves down universes -/\ndef down_map {F : Type (max u₀ v₀) → Type u₁} {G : Type → Type v₁} [inst : uliftable G F] [Functor F] {α : Type (max u₀ v₀)} {β : Type} (f : α → β) (x : F α) : G β :=\n down ((ulift.up ∘ f) <$> x)\n\n@[simp] theorem up_down {f : Type u₀ → Type u₁} {g : Type (max u₀ v₀) → Type v₁} [uliftable f g] {α : Type u₀} (x : g (ulift α)) : up (down x) = x :=\n equiv.right_inv (congr f g (equiv.symm equiv.ulift)) x\n\n@[simp] theorem down_up {f : Type u₀ → Type u₁} {g : Type (max u₀ v₀) → Type v₁} [uliftable f g] {α : Type u₀} (x : f α) : down (up x) = x :=\n equiv.left_inv (congr f g (equiv.symm equiv.ulift)) x\n\nend uliftable\n\n\nprotected instance id.uliftable : uliftable id id :=\n uliftable.mk fun (α : Type u_1) (β : Type u_2) (F : α ≃ β) => F\n\n/-- for specific state types, this function helps to create a uliftable instance -/\ndef state_t.uliftable' {s : Type u₀} {s' : Type u₁} {m : Type u₀ → Type v₀} {m' : Type u₁ → Type v₁} [uliftable m m'] (F : s ≃ s') : uliftable (state_t s m) (state_t s' m') :=\n uliftable.mk\n fun (α : Type u₀) (β : Type u₁) (G : α ≃ β) =>\n state_t.equiv (equiv.Pi_congr F fun (_x : s) => uliftable.congr m m' (equiv.prod_congr G F))\n\nprotected instance state_t.uliftable {s : Type u_1} {m : Type u_1 → Type u_2} {m' : Type (max u_1 u_3) → Type u_4} [uliftable m m'] : uliftable (state_t s m) (state_t (ulift s) m') :=\n state_t.uliftable' (equiv.symm equiv.ulift)\n\n/-- for specific reader monads, this function helps to create a uliftable instance -/\ndef reader_t.uliftable' {s : Type u_1} {s' : Type u_2} {m : Type u_1 → Type u_3} {m' : Type u_2 → Type u_4} [uliftable m m'] (F : s ≃ s') : uliftable (reader_t s m) (reader_t s' m') :=\n uliftable.mk\n fun (α : Type u_1) (β : Type u_2) (G : α ≃ β) =>\n reader_t.equiv (equiv.Pi_congr F fun (_x : s) => uliftable.congr m m' G)\n\nprotected instance reader_t.uliftable {s : Type u_1} {m : Type u_1 → Type u_2} {m' : Type (max u_1 u_3) → Type u_4} [uliftable m m'] : uliftable (reader_t s m) (reader_t (ulift s) m') :=\n reader_t.uliftable' (equiv.symm equiv.ulift)\n\n/-- for specific continuation passing monads, this function helps to create a uliftable instance -/\ndef cont_t.uliftable' {r : Type u_1} {r' : Type u_2} {m : Type u_1 → Type u_3} {m' : Type u_2 → Type u_4} [uliftable m m'] (F : r ≃ r') : uliftable (cont_t r m) (cont_t r' m') :=\n uliftable.mk fun (α : Type u_1) (β : Type u_2) => cont_t.equiv (uliftable.congr m m' F)\n\nprotected instance cont_t.uliftable {s : Type u_1} {m : Type u_1 → Type u_2} {m' : Type (max u_1 u_3) → Type u_4} [uliftable m m'] : uliftable (cont_t s m) (cont_t (ulift s) m') :=\n cont_t.uliftable' (equiv.symm equiv.ulift)\n\n/-- for specific writer monads, this function helps to create a uliftable instance -/\ndef writer_t.uliftable' {w : Type (max u_1 u_2)} {w' : Type (max u_3 u_4)} {m : Type (max u_1 u_2) → Type u_5} {m' : Type (max u_3 u_4) → Type u_6} [uliftable m m'] (F : w ≃ w') : uliftable (writer_t w m) (writer_t w' m') :=\n uliftable.mk\n fun (α : Type (max u_1 u_2)) (β : Type (max u_3 u_4)) (G : α ≃ β) =>\n writer_t.equiv (uliftable.congr m m' (equiv.prod_congr G F))\n\nprotected instance writer_t.uliftable {s : Type (max u_1 u_2)} {m : Type (max u_1 u_2) → Type u_3} {m' : Type (max (max u_1 u_2) u_4) → Type u_5} [uliftable m m'] : uliftable (writer_t s m) (writer_t (ulift s) m') :=\n writer_t.uliftable' (equiv.symm equiv.ulift)\n\n", "meta": {"author": "AurelienSaue", "repo": "Mathlib4_auto", "sha": "590df64109b08190abe22358fabc3eae000943f2", "save_path": "github-repos/lean/AurelienSaue-Mathlib4_auto", "path": "github-repos/lean/AurelienSaue-Mathlib4_auto/Mathlib4_auto-590df64109b08190abe22358fabc3eae000943f2/Mathlib/control/uliftable.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3665897363221598, "lm_q2_score": 0.07369627275773762, "lm_q1q2_score": 0.027016297198185}} {"text": "def f : Prop → Prop := id\n\nclass Foo (foo : Prop → Prop) where\n l : x → foo x\n\ninstance : Foo f where\n l := by simp_all [f]\n\ntheorem test' (h : x = True) : f x := by\n have _ := True\n apply Foo.l -- `?foo ?x =?= [mdata noImplicitLambda:1 f x]`\n simp [h]\n", "meta": {"author": "leanprover", "repo": "lean4", "sha": "742d053a97bdd109a41a921facd1cd6a55e89bc7", "save_path": "github-repos/lean/leanprover-lean4", "path": "github-repos/lean/leanprover-lean4/lean4-742d053a97bdd109a41a921facd1cd6a55e89bc7/tests/lean/run/foApprox.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.476579651063676, "lm_q2_score": 0.05665242968796326, "lm_q1q2_score": 0.02699939517259897}} {"text": "/-\nCopyright (c) 2020 Scott Morrison. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Scott Morrison, Bhavik Mehta\n-/\nimport category_theory.limits.shapes.pullbacks\nimport category_theory.limits.shapes.strong_epi\nimport category_theory.limits.shapes.equalizers\n\n/-!\n# Definitions and basic properties of regular monomorphisms and epimorphisms.\n\nA regular monomorphism is a morphism that is the equalizer of some parallel pair.\n\nWe give the constructions\n* `split_mono → regular_mono` and\n* `regular_mono → mono`\nas well as the dual constructions for regular epimorphisms. Additionally, we give the\nconstruction\n* `regular_epi ⟶ strong_epi`.\n\n-/\n\nnoncomputable theory\n\nnamespace category_theory\nopen category_theory.limits\n\nuniverses v₁ u₁ u₂\n\nvariables {C : Type u₁} [category.{v₁} C]\n\nvariables {X Y : C}\n\n/-- A regular monomorphism is a morphism which is the equalizer of some parallel pair. -/\nclass regular_mono (f : X ⟶ Y) :=\n(Z : C)\n(left right : Y ⟶ Z)\n(w : f ≫ left = f ≫ right)\n(is_limit : is_limit (fork.of_ι f w))\n\nattribute [reassoc] regular_mono.w\n\n/-- Every regular monomorphism is a monomorphism. -/\n@[priority 100]\ninstance regular_mono.mono (f : X ⟶ Y) [regular_mono f] : mono f :=\nmono_of_is_limit_parallel_pair regular_mono.is_limit\n\ninstance equalizer_regular (g h : X ⟶ Y) [has_limit (parallel_pair g h)] :\n regular_mono (equalizer.ι g h) :=\n{ Z := Y,\n left := g,\n right := h,\n w := equalizer.condition g h,\n is_limit := fork.is_limit.mk _ (λ s, limit.lift _ s) (by simp) (λ s m w, by { ext1, simp [←w] }) }\n\n/-- Every split monomorphism is a regular monomorphism. -/\n@[priority 100]\ninstance regular_mono.of_split_mono (f : X ⟶ Y) [split_mono f] : regular_mono f :=\n{ Z := Y,\n left := 𝟙 Y,\n right := retraction f ≫ f,\n w := by tidy,\n is_limit := split_mono_equalizes f }\n\n/-- If `f` is a regular mono, then any map `k : W ⟶ Y` equalizing `regular_mono.left` and\n `regular_mono.right` induces a morphism `l : W ⟶ X` such that `l ≫ f = k`. -/\ndef regular_mono.lift' {W : C} (f : X ⟶ Y) [regular_mono f] (k : W ⟶ Y)\n (h : k ≫ (regular_mono.left : Y ⟶ @regular_mono.Z _ _ _ _ f _) = k ≫ regular_mono.right) :\n {l : W ⟶ X // l ≫ f = k} :=\nfork.is_limit.lift' regular_mono.is_limit _ h\n\n/--\nThe second leg of a pullback cone is a regular monomorphism if the right component is too.\n\nSee also `pullback.snd_of_mono` for the basic monomorphism version, and\n`regular_of_is_pullback_fst_of_regular` for the flipped version.\n-/\ndef regular_of_is_pullback_snd_of_regular {P Q R S : C} {f : P ⟶ Q} {g : P ⟶ R} {h : Q ⟶ S}\n {k : R ⟶ S} [hr : regular_mono h] (comm : f ≫ h = g ≫ k)\n (t : is_limit (pullback_cone.mk _ _ comm)) :\nregular_mono g :=\n{ Z := hr.Z,\n left := k ≫ hr.left,\n right := k ≫ hr.right,\n w := by rw [← reassoc_of comm, ← reassoc_of comm, hr.w],\n is_limit :=\n begin\n apply fork.is_limit.mk' _ _,\n intro s,\n have l₁ : (fork.ι s ≫ k) ≫ regular_mono.left = (fork.ι s ≫ k) ≫ regular_mono.right,\n rw [category.assoc, s.condition, category.assoc],\n obtain ⟨l, hl⟩ := fork.is_limit.lift' hr.is_limit _ l₁,\n obtain ⟨p, hp₁, hp₂⟩ := pullback_cone.is_limit.lift' t _ _ hl,\n refine ⟨p, hp₂, _⟩,\n intros m w,\n have z : m ≫ g = p ≫ g := w.trans hp₂.symm,\n apply t.hom_ext,\n apply (pullback_cone.mk f g comm).equalizer_ext,\n { erw [← cancel_mono h, category.assoc, category.assoc, comm, reassoc_of z] },\n { exact z },\n end }\n\n/--\nThe first leg of a pullback cone is a regular monomorphism if the left component is too.\n\nSee also `pullback.fst_of_mono` for the basic monomorphism version, and\n`regular_of_is_pullback_snd_of_regular` for the flipped version.\n-/\ndef regular_of_is_pullback_fst_of_regular {P Q R S : C} {f : P ⟶ Q} {g : P ⟶ R} {h : Q ⟶ S}\n {k : R ⟶ S} [hr : regular_mono k] (comm : f ≫ h = g ≫ k)\n (t : is_limit (pullback_cone.mk _ _ comm)) :\nregular_mono f :=\nregular_of_is_pullback_snd_of_regular comm.symm (pullback_cone.flip_is_limit t)\n\n/-- A regular monomorphism is an isomorphism if it is an epimorphism. -/\nlemma is_iso_of_regular_mono_of_epi (f : X ⟶ Y) [regular_mono f] [e : epi f] : is_iso f :=\n@is_iso_limit_cone_parallel_pair_of_epi _ _ _ _ _ _ _ regular_mono.is_limit e\n\n/-- A regular epimorphism is a morphism which is the coequalizer of some parallel pair. -/\nclass regular_epi (f : X ⟶ Y) :=\n(W : C)\n(left right : W ⟶ X)\n(w : left ≫ f = right ≫ f)\n(is_colimit : is_colimit (cofork.of_π f w))\n\nattribute [reassoc] regular_epi.w\n\n/-- Every regular epimorphism is an epimorphism. -/\n@[priority 100]\ninstance regular_epi.epi (f : X ⟶ Y) [regular_epi f] : epi f :=\nepi_of_is_colimit_parallel_pair regular_epi.is_colimit\n\ninstance coequalizer_regular (g h : X ⟶ Y) [has_colimit (parallel_pair g h)] :\n regular_epi (coequalizer.π g h) :=\n{ W := X,\n left := g,\n right := h,\n w := coequalizer.condition g h,\n is_colimit := cofork.is_colimit.mk _ (λ s, colimit.desc _ s) (by simp)\n (λ s m w, by { ext1, simp [←w] }) }\n\n/-- Every split epimorphism is a regular epimorphism. -/\n@[priority 100]\ninstance regular_epi.of_split_epi (f : X ⟶ Y) [split_epi f] : regular_epi f :=\n{ W := X,\n left := 𝟙 X,\n right := f ≫ section_ f,\n w := by tidy,\n is_colimit := split_epi_coequalizes f }\n\n/-- If `f` is a regular epi, then every morphism `k : X ⟶ W` coequalizing `regular_epi.left` and\n `regular_epi.right` induces `l : Y ⟶ W` such that `f ≫ l = k`. -/\ndef regular_epi.desc' {W : C} (f : X ⟶ Y) [regular_epi f] (k : X ⟶ W)\n (h : (regular_epi.left : regular_epi.W f ⟶ X) ≫ k = regular_epi.right ≫ k) :\n {l : Y ⟶ W // f ≫ l = k} :=\ncofork.is_colimit.desc' (regular_epi.is_colimit) _ h\n\n/--\nThe second leg of a pushout cocone is a regular epimorphism if the right component is too.\n\nSee also `pushout.snd_of_epi` for the basic epimorphism version, and\n`regular_of_is_pushout_fst_of_regular` for the flipped version.\n-/\ndef regular_of_is_pushout_snd_of_regular\n {P Q R S : C} {f : P ⟶ Q} {g : P ⟶ R} {h : Q ⟶ S} {k : R ⟶ S}\n [gr : regular_epi g] (comm : f ≫ h = g ≫ k) (t : is_colimit (pushout_cocone.mk _ _ comm)) :\nregular_epi h :=\n{ W := gr.W,\n left := gr.left ≫ f,\n right := gr.right ≫ f,\n w := by rw [category.assoc, category.assoc, comm, reassoc_of gr.w],\n is_colimit :=\n begin\n apply cofork.is_colimit.mk' _ _,\n intro s,\n have l₁ : gr.left ≫ f ≫ s.π = gr.right ≫ f ≫ s.π,\n rw [← category.assoc, ← category.assoc, s.condition],\n obtain ⟨l, hl⟩ := cofork.is_colimit.desc' gr.is_colimit (f ≫ cofork.π s) l₁,\n obtain ⟨p, hp₁, hp₂⟩ := pushout_cocone.is_colimit.desc' t _ _ hl.symm,\n refine ⟨p, hp₁, _⟩,\n intros m w,\n have z := w.trans hp₁.symm,\n apply t.hom_ext,\n apply (pushout_cocone.mk _ _ comm).coequalizer_ext,\n { exact z },\n { erw [← cancel_epi g, ← reassoc_of comm, ← reassoc_of comm, z], refl },\n end }\n\n/--\nThe first leg of a pushout cocone is a regular epimorphism if the left component is too.\n\nSee also `pushout.fst_of_epi` for the basic epimorphism version, and\n`regular_of_is_pushout_snd_of_regular` for the flipped version.\n-/\ndef regular_of_is_pushout_fst_of_regular\n {P Q R S : C} {f : P ⟶ Q} {g : P ⟶ R} {h : Q ⟶ S} {k : R ⟶ S}\n [fr : regular_epi f] (comm : f ≫ h = g ≫ k) (t : is_colimit (pushout_cocone.mk _ _ comm)) :\nregular_epi k :=\nregular_of_is_pushout_snd_of_regular comm.symm (pushout_cocone.flip_is_colimit t)\n\n/-- A regular epimorphism is an isomorphism if it is a monomorphism. -/\nlemma is_iso_of_regular_epi_of_mono (f : X ⟶ Y) [regular_epi f] [m : mono f] : is_iso f :=\n@is_iso_limit_cocone_parallel_pair_of_epi _ _ _ _ _ _ _ regular_epi.is_colimit m\n\n@[priority 100]\ninstance strong_epi_of_regular_epi (f : X ⟶ Y) [regular_epi f] : strong_epi f :=\n{ epi := by apply_instance,\n has_lift :=\n begin\n introsI,\n have : (regular_epi.left : regular_epi.W f ⟶ X) ≫ u = regular_epi.right ≫ u,\n { apply (cancel_mono z).1,\n simp only [category.assoc, h, regular_epi.w_assoc] },\n obtain ⟨t, ht⟩ := regular_epi.desc' f u this,\n exact arrow.has_lift.mk ⟨t, ht, (cancel_epi f).1\n (by simp only [←category.assoc, ht, ←h, arrow.mk_hom, arrow.hom_mk'_right])⟩,\n end }\n\nend category_theory\n", "meta": {"author": "jjaassoonn", "repo": "projective_space", "sha": "11fe19fe9d7991a272e7a40be4b6ad9b0c10c7ce", "save_path": "github-repos/lean/jjaassoonn-projective_space", "path": "github-repos/lean/jjaassoonn-projective_space/projective_space-11fe19fe9d7991a272e7a40be4b6ad9b0c10c7ce/src/category_theory/limits/shapes/regular_mono.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.476579651063676, "lm_q2_score": 0.05665242968796326, "lm_q1q2_score": 0.02699939517259897}} {"text": "inductive Foo: List α → Type _\n | mk (l): Foo l\n\ndef Foo.length: Foo l → Nat\n | mk l => l.length\n\nvariable {α : Type u} {Γ Γ': List α} {p: Foo Γ} {h: Γ = Γ'}\n\ntheorem eq_rec_length : (h ▸ p).length = p.length := by\n cases h; rfl\n\nexample : (h ▸ p).length = p.length :=\n eq_rec_length\n\nexample : (h ▸ p).length = p.length := by\n simp only [eq_rec_length]\n\nexample : (h ▸ p).length = p.length := by\n rw [eq_rec_length]\n\nexample : (h ▸ p).length = p.length := by\n subst h; rfl\n\nexample : (h ▸ p).length = p.length :=\n match h with\n | rfl => rfl\n\nexample : (h ▸ p).length = p.length :=\n let (rfl) := h; rfl\n", "meta": {"author": "leanprover", "repo": "lean4", "sha": "742d053a97bdd109a41a921facd1cd6a55e89bc7", "save_path": "github-repos/lean/leanprover-lean4", "path": "github-repos/lean/leanprover-lean4/lean4-742d053a97bdd109a41a921facd1cd6a55e89bc7/tests/lean/run/substWithoutExpectedType.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.46101677931231594, "lm_q2_score": 0.05834584143037475, "lm_q1q2_score": 0.02689841190249846}} {"text": "/-\n## Finite interaction trees\n\nThe semantics framework for this project is extremely inspired by the Vellvm\nproject [1] and is essentially centered around interaction trees and monadic\ntransformers.\n\nInteractions trees are a particular instance of the freer monad; essentially,\nan ITree is a program that can have side effets through *interactions*, and\nthese interactions can either be interpreted into the program or kept as\nobservable side-effects.\n\nWhen giving semantics to a program, one usually starts with a rather simple\nITree where most of the complex features of the language (memory, I/O,\nexceptions, randomness, non-determinism, etc) are hidden behind interactions.\nThe interactions are then interpreted, which consists of (1) enriching the\nprogram's environment by a monadic transformation, and (2) replacing the\ninteraction with an actual implementation.\n\nThis approach allows monadic domains to be used while keeping each family of\ninteractions separate. This is relevant for Vellvm as LLVM IR has many complex\nfeatures, and even more relevant for MLIR since each dialect can bring more\ninteractions and environment transforms and all of them have to be studied and\ndefined independently.\n\nThe datatype of interaction trees normally has built-in non-termination by\nbeing defined coinductively. Support for coinduction is still limited in Lean4,\nso we currently use a finite version of ITrees (hence called Fitree) which can\nonly model programs that always terminate.\n\n[1]: https://github.com/vellvm/vellvm\n-/\n\nimport MLIRSemantics.SimpItree\n\n/- Extendable effect families -/\n\nsection events\nuniverse u v\n\ndef pto (E: Type → Type u) (F: Type → Type v) :=\n ∀ T, E T → F T\ndef psum (E: Type → Type u) (F: Type → Type v) :=\n fun T => E T ⊕ F T\ninductive PVoid: Type -> Type u\n\ninfixr:40 \" ~> \" => pto\ninfixr:60 \" +' \" => psum\n\nclass Member (E: Type → Type u) (F: Type → Type v) where\n inject : E ~> F\n\ninstance {E}: Member E E where\n inject := (fun _ => id)\n\ninstance {E F G} [Member E F]: Member E (F +' G) where\n inject T := Sum.inl ∘ Member.inject T\n\ninstance {E F G} [Member E G]: Member E (F +' G) where\n inject T := Sum.inr ∘ Member.inject T\n\n-- Effects can now be put in context automatically by typeclass resolution\nexample (E: Type → Type u):\n Member E E := inferInstance\nexample (E: Type → Type u) (F: Type → Type v):\n Member E (E +' F) := inferInstance\nexample (E: Type → Type u) (F: Type → Type v):\n Member E (F +' (F +' E)) := inferInstance\n\n@[simp_itree]\ndef case_ (h1: E ~> G) (h2: F ~> G): E +' F ~> G :=\n fun R ef => match ef with\n | Sum.inl e => h1 R e\n | Sum.inr f => h2 R f\n\nend events\n\n\n/- Examples of interactions -/\n\ninductive StateE {S: Type}: Type → Type where\n | Read: Unit → StateE S\n | Write: S → StateE Unit\n\ninductive WriteE {W: Type}: Type → Type where\n | Tell: W → WriteE Unit\n\n\n/- The monadic domain; essentially finite Interaction Trees -/\n\nsection fitree\nuniverse u v\n\ninductive Fitree (E: Type → Type u) (R: Type) where\n | Ret (r: R): Fitree E R\n | Vis {T: Type} (e: E T) (k: T → Fitree E R): Fitree E R\n\n@[simp_itree]\ndef Fitree.ret {E R}: R → Fitree E R :=\n Fitree.Ret\n\n@[simp_itree]\ndef Fitree.trigger {E: Type → Type u} {F: Type → Type v} {T} [Member E F]\n (e: E T): Fitree F T :=\n Fitree.Vis (Member.inject _ e) Fitree.ret\n\n@[simp_itree]\ndef Fitree.bind {E R T} (t: Fitree E T) (k: T → Fitree E R) :=\n match t with\n | Ret r => k r\n | Vis e k' => Vis e (fun r => bind (k' r) k)\n\ninstance {E}: Monad (Fitree E) where\n pure := Fitree.ret\n bind := Fitree.bind\n\n\n-- Interpretation into the monad of finite ITrees\n@[simp_itree]\ndef interp {M} [Monad M] {E} (h: E ~> M):\n forall ⦃R⦄, Fitree E R → M R :=\n fun _ t =>\n match t with\n | Fitree.Ret r => pure r\n | Fitree.Vis e k => bind (h _ e) (fun t => interp h (k t))\n\n-- Interpretation into the state monad\n@[simp_itree]\ndef interp_state {M S} [Monad M] {E} (h: E ~> StateT S M):\n forall ⦃R⦄, Fitree E R → StateT S M R :=\n interp h\n\n-- Since we only use finite ITrees, we can actually run them when they're\n-- fully interpreted (which leaves only the Ret constructor)\ndef Fitree.run {R}: Fitree PVoid R → R\n | Ret r => r\n | Vis e k => nomatch e\n\nend fitree\n\n\n/- Predicates to reason about the absence of events -/\n\ninductive Fitree.no_event_l {E F R}: Fitree (E +' F) R → Prop :=\n | Ret r: no_event_l (Ret r)\n | Vis f k: (∀ t, no_event_l (k t)) → no_event_l (Vis (Sum.inr f) k)\n\n-- TODO: Tactic to automate the proof of no_event_l\n\n\n/- Rewriting tactic simp_itree -/\n\nopen Lean Elab.Tactic Parser.Tactic\n\ndef toSimpLemma (name : Name) : Syntax :=\n mkNode `Lean.Parser.Tactic.simpLemma\n #[mkNullNode, mkNullNode, mkIdent name]\n\nelab \"simp_itree\" : tactic => do\n -- TODO: Also handle .lemmaNames, not just unfolding!\n let lemmas := (← SimpItreeExtension.getTheorems).toUnfold.fold\n (init := #[]) (fun acc n => acc.push (toSimpLemma n))\n evalTactic $ ← `(tactic|simp [$lemmas.reverse,*,\n Member.inject, StateT.bind, StateT.pure, bind, pure, cast_eq])\n", "meta": {"author": "opencompl", "repo": "lean-mlir-semantics", "sha": "9ec41b134fd89a9799defae9e41de76b7d526266", "save_path": "github-repos/lean/opencompl-lean-mlir-semantics", "path": "github-repos/lean/opencompl-lean-mlir-semantics/lean-mlir-semantics-9ec41b134fd89a9799defae9e41de76b7d526266/MLIRSemantics/Fitree.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4339814501625211, "lm_q2_score": 0.061875983561210525, "lm_q1q2_score": 0.02685302907612646}} {"text": "/-\nCopyright (c) 2018 Simon Hudon. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Simon Hudon\n\nGeneral utility functions for buffers.\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.default\nimport Mathlib.Lean3Lib.data.buffer\nimport Mathlib.data.array.lemmas\nimport Mathlib.control.traversable.instances\nimport Mathlib.PostPort\n\nuniverses u_1 \n\nnamespace Mathlib\n\nnamespace buffer\n\n\nprotected instance inhabited {α : Type u_1} : Inhabited (buffer α) := { default := nil }\n\ntheorem ext {α : Type u_1} {b₁ : buffer α} {b₂ : buffer α} : to_list b₁ = to_list b₂ → b₁ = b₂ :=\n sorry\n\nprotected instance decidable_eq (α : Type u_1) [DecidableEq α] : DecidableEq (buffer α) :=\n id\n fun (_v : buffer α) =>\n sigma.cases_on _v\n fun (fst : ℕ) (snd : array fst α) (w : buffer α) =>\n sigma.cases_on w\n fun (w_fst : ℕ) (w_snd : array w_fst α) =>\n decidable.by_cases\n (fun (ᾰ : fst = w_fst) =>\n Eq._oldrec\n (fun (w_snd : array fst α) =>\n decidable.by_cases (fun (ᾰ : snd = w_snd) => Eq._oldrec (is_true sorry) ᾰ)\n fun (ᾰ : ¬snd = w_snd) => isFalse sorry)\n ᾰ w_snd)\n fun (ᾰ : ¬fst = w_fst) => isFalse sorry\n\n@[simp] theorem to_list_append_list {α : Type u_1} {xs : List α} {b : buffer α} :\n to_list (append_list b xs) = to_list b ++ xs :=\n sorry\n\n@[simp] theorem append_list_mk_buffer {α : Type u_1} {xs : List α} :\n append_list mk_buffer xs = array.to_buffer (list.to_array xs) :=\n sorry\n\n/-- The natural equivalence between lists and buffers, using\n`list.to_buffer` and `buffer.to_list`. -/\ndef list_equiv_buffer (α : Type u_1) : List α ≃ buffer α :=\n equiv.mk list.to_buffer to_list sorry sorry\n\nprotected instance traversable : traversable buffer := equiv.traversable list_equiv_buffer\n\nprotected instance is_lawful_traversable : is_lawful_traversable buffer :=\n equiv.is_lawful_traversable list_equiv_buffer\n\nend Mathlib", "meta": {"author": "AurelienSaue", "repo": "Mathlib4_auto", "sha": "590df64109b08190abe22358fabc3eae000943f2", "save_path": "github-repos/lean/AurelienSaue-Mathlib4_auto", "path": "github-repos/lean/AurelienSaue-Mathlib4_auto/Mathlib4_auto-590df64109b08190abe22358fabc3eae000943f2/Mathlib/data/buffer/basic_auto.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3960681662740416, "lm_q2_score": 0.06754669348597103, "lm_q1q2_score": 0.026753095026863297}} {"text": "/-\nCopyright (c) 2018 Simon Hudon. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Simon Hudon\n\nGeneral utility functions for buffers.\n\n! This file was ported from Lean 3 source module data.buffer.basic\n! leanprover-community/mathlib commit 70fd9563a21e7b963887c9360bd29b2393e6225a\n! Please do not edit these lines, except to modify the commit id\n! if you have ported upstream changes.\n-/\nimport Mathbin.Data.Array.Lemmas\nimport Mathbin.Control.Traversable.Instances\n\nnamespace Buffer\n\nopen Function\n\nvariable {α : Type _} {xs : List α}\n\ninstance : Inhabited (Buffer α) :=\n ⟨nil⟩\n\n@[ext]\ntheorem ext : ∀ {b₁ b₂ : Buffer α}, toList b₁ = toList b₂ → b₁ = b₂\n | ⟨n₁, a₁⟩, ⟨n₂, a₂⟩, h => by\n simp [to_list, to_array] at h\n have e : n₁ = n₂ := by rw [← Array'.toList_length a₁, ← Array'.toList_length a₂, h]\n subst e\n have h : HEq a₁ a₂.to_list.to_array := h ▸ a₁.to_list_to_array.symm\n rw [eq_of_hEq (h.trans a₂.to_list_to_array)]\n#align buffer.ext Buffer.ext\n\ntheorem ext_iff {b₁ b₂ : Buffer α} : b₁ = b₂ ↔ toList b₁ = toList b₂ :=\n ⟨fun h => h ▸ rfl, ext⟩\n#align buffer.ext_iff Buffer.ext_iff\n\ntheorem size_eq_zero_iff {b : Buffer α} : b.size = 0 ↔ b = nil :=\n by\n rcases b with ⟨_ | n, ⟨a⟩⟩\n · simp only [size, nil, mkBuffer, true_and_iff, true_iff_iff, eq_self_iff_true, heq_iff_eq,\n Sigma.mk.inj_iff]\n ext i\n exact Fin.elim0 i\n · simp [size, nil, mkBuffer, Nat.succ_ne_zero]\n#align buffer.size_eq_zero_iff Buffer.size_eq_zero_iff\n\n@[simp]\ntheorem size_nil : (@nil α).size = 0 := by rw [size_eq_zero_iff]\n#align buffer.size_nil Buffer.size_nil\n\n@[simp]\ntheorem toList_nil : toList (@nil α) = [] :=\n rfl\n#align buffer.to_list_nil Buffer.toList_nil\n\n/- ./././Mathport/Syntax/Translate/Tactic/Builtin.lean:69:18: unsupported non-interactive tactic tactic.mk_dec_eq_instance -/\ninstance (α) [DecidableEq α] : DecidableEq (Buffer α) := by\n run_tac\n tactic.mk_dec_eq_instance\n\n@[simp]\ntheorem toList_appendList {b : Buffer α} : toList (appendList b xs) = toList b ++ xs := by\n induction xs generalizing b <;> simp! [*] <;> cases b <;> simp! [to_list, to_array]\n#align buffer.to_list_append_list Buffer.toList_appendList\n\n@[simp]\ntheorem appendList_mkBuffer : appendList mkBuffer xs = Array'.toBuffer (List.toArray xs) := by\n ext x : 1 <;> simp [Array'.toBuffer, to_list, to_list_append_list] <;> induction xs <;> [rfl,\n skip] <;>\n simp [to_array] <;>\n rfl\n#align buffer.append_list_mk_buffer Buffer.appendList_mkBuffer\n\n@[simp]\ntheorem toBuffer_toList (b : Buffer α) : b.toList.toBuffer = b :=\n by\n cases b\n rw [to_list, to_array, List.toBuffer, append_list_mk_buffer]\n congr\n · simpa\n · apply Array'.toList_toArray\n#align buffer.to_buffer_to_list Buffer.toBuffer_toList\n\n@[simp]\ntheorem toList_toBuffer (l : List α) : l.toBuffer.toList = l :=\n by\n cases l\n · rfl\n · rw [List.toBuffer, to_list_append_list]\n rfl\n#align buffer.to_list_to_buffer Buffer.toList_toBuffer\n\n@[simp]\ntheorem toList_toArray (b : Buffer α) : b.toArray.toList = b.toList :=\n by\n cases b\n simp [to_list]\n#align buffer.to_list_to_array Buffer.toList_toArray\n\n@[simp]\ntheorem appendList_nil (b : Buffer α) : b.appendList [] = b :=\n rfl\n#align buffer.append_list_nil Buffer.appendList_nil\n\ntheorem toBuffer_cons (c : α) (l : List α) : (c :: l).toBuffer = [c].toBuffer.appendList l :=\n by\n induction' l with hd tl hl\n · simp\n · apply ext\n simp [hl]\n#align buffer.to_buffer_cons Buffer.toBuffer_cons\n\n@[simp]\ntheorem size_pushBack (b : Buffer α) (a : α) : (b.pushBack a).size = b.size + 1 :=\n by\n cases b\n simp [size, push_back]\n#align buffer.size_push_back Buffer.size_pushBack\n\n@[simp]\ntheorem size_appendList (b : Buffer α) (l : List α) : (b.appendList l).size = b.size + l.length :=\n by\n induction' l with hd tl hl generalizing b\n · simp\n · simp [append_list, hl, add_comm, add_assoc]\n#align buffer.size_append_list Buffer.size_appendList\n\n@[simp]\ntheorem size_toBuffer (l : List α) : l.toBuffer.size = l.length :=\n by\n induction' l with hd tl hl\n · simpa\n · rw [to_buffer_cons]\n have : [hd].toBuffer.size = 1 := rfl\n simp [add_comm, this]\n#align buffer.size_to_buffer Buffer.size_toBuffer\n\n@[simp]\ntheorem length_toList (b : Buffer α) : b.toList.length = b.size := by\n rw [← to_buffer_to_list b, to_list_to_buffer, size_to_buffer]\n#align buffer.length_to_list Buffer.length_toList\n\ntheorem size_singleton (a : α) : [a].toBuffer.size = 1 :=\n rfl\n#align buffer.size_singleton Buffer.size_singleton\n\ntheorem read_pushBack_left (b : Buffer α) (a : α) {i : ℕ} (h : i < b.size) :\n (b.pushBack a).read\n ⟨i, by\n convert Nat.lt_succ_of_lt h\n simp⟩ =\n b.read ⟨i, h⟩ :=\n by\n cases b\n convert Array'.read_pushBack_left _\n simp\n#align buffer.read_push_back_left Buffer.read_pushBack_left\n\n@[simp]\ntheorem read_pushBack_right (b : Buffer α) (a : α) : (b.pushBack a).read ⟨b.size, by simp⟩ = a :=\n by\n cases b\n convert Array'.read_pushBack_right\n#align buffer.read_push_back_right Buffer.read_pushBack_right\n\ntheorem read_appendList_left' (b : Buffer α) (l : List α) {i : ℕ} (h : i < (b.appendList l).size)\n (h' : i < b.size) : (b.appendList l).read ⟨i, h⟩ = b.read ⟨i, h'⟩ :=\n by\n induction' l with hd tl hl generalizing b\n · rfl\n · have hb : i < ((b.push_back hd).appendList tl).size := by convert h using 1\n have hb' : i < (b.push_back hd).size :=\n by\n convert Nat.lt_succ_of_lt h'\n simp\n have : (append_list b (hd :: tl)).read ⟨i, h⟩ = read ((push_back b hd).appendList tl) ⟨i, hb⟩ :=\n rfl\n simp [this, hl _ hb hb', read_push_back_left _ _ h']\n#align buffer.read_append_list_left' Buffer.read_appendList_left'\n\ntheorem read_appendList_left (b : Buffer α) (l : List α) {i : ℕ} (h : i < b.size) :\n (b.appendList l).read ⟨i, by simpa using Nat.lt_add_right _ _ _ h⟩ = b.read ⟨i, h⟩ :=\n read_appendList_left' b l _ h\n#align buffer.read_append_list_left Buffer.read_appendList_left\n\n@[simp]\ntheorem read_appendList_right (b : Buffer α) (l : List α) {i : ℕ} (h : i < l.length) :\n (b.appendList l).read ⟨b.size + i, by simp [h]⟩ = l.nthLe i h :=\n by\n induction' l with hd tl hl generalizing b i\n · exact absurd i.zero_le (not_le_of_lt h)\n · convert_to((b.push_back hd).appendList tl).read _ = _\n cases i\n · convert read_append_list_left _ _ _ <;> simp\n · rw [List.length, Nat.succ_lt_succ_iff] at h\n have : b.size + i.succ = (b.push_back hd).size + i := by\n simp [add_comm, add_left_comm, Nat.succ_eq_add_one]\n convert hl (b.push_back hd) h using 1\n simpa [Nat.add_succ, Nat.succ_add]\n#align buffer.read_append_list_right Buffer.read_appendList_right\n\ntheorem read_to_buffer' (l : List α) {i : ℕ} (h : i < l.toBuffer.size) (h' : i < l.length) :\n l.toBuffer.read ⟨i, h⟩ = l.nthLe i h' :=\n by\n cases' l with hd tl\n · simpa using h'\n · have hi : i < ([hd].toBuffer.appendList tl).size := by simpa [add_comm] using h\n convert_to([hd].toBuffer.appendList tl).read ⟨i, hi⟩ = _\n cases i\n · convert read_append_list_left _ _ _\n simp\n · rw [List.nthLe]\n convert read_append_list_right _ _ _\n simp [Nat.succ_eq_add_one, add_comm]\n#align buffer.read_to_buffer' Buffer.read_to_buffer'\n\n@[simp]\ntheorem read_toBuffer (l : List α) (i) :\n l.toBuffer.read i =\n l.nthLe i\n (by\n convert i.property\n simp) :=\n by\n convert read_to_buffer' _ _ _\n · simp\n · simpa using i.property\n#align buffer.read_to_buffer Buffer.read_toBuffer\n\ntheorem nthLe_to_list' (b : Buffer α) {i : ℕ} (h h') : b.toList.nthLe i h = b.read ⟨i, h'⟩ :=\n by\n have : b.to_list.to_buffer.read ⟨i, by simpa using h'⟩ = b.read ⟨i, h'⟩ := by\n congr 1 <;> simp [Fin.heq_ext_iff]\n simp [← this]\n#align buffer.nth_le_to_list' Buffer.nthLe_to_list'\n\ntheorem nthLe_toList (b : Buffer α) {i : ℕ} (h) :\n b.toList.nthLe i h = b.read ⟨i, by simpa using h⟩ :=\n nthLe_to_list' _ _ _\n#align buffer.nth_le_to_list Buffer.nthLe_toList\n\ntheorem read_eq_nthLe_toList (b : Buffer α) (i) : b.read i = b.toList.nthLe i (by simp) := by\n simp [nth_le_to_list]\n#align buffer.read_eq_nth_le_to_list Buffer.read_eq_nthLe_toList\n\ntheorem read_singleton (c : α) : [c].toBuffer.read ⟨0, by simp⟩ = c := by simp\n#align buffer.read_singleton Buffer.read_singleton\n\n/-- The natural equivalence between lists and buffers, using\n`list.to_buffer` and `buffer.to_list`. -/\ndef listEquivBuffer (α : Type _) : List α ≃ Buffer α := by\n refine'\n { toFun := List.toBuffer\n invFun := Buffer.toList.. } <;>\n simp [left_inverse, Function.RightInverse]\n#align buffer.list_equiv_buffer Buffer.listEquivBuffer\n\ninstance : Traversable Buffer :=\n Equiv.traversable listEquivBuffer\n\ninstance : IsLawfulTraversable Buffer :=\n Equiv.isLawfulTraversable listEquivBuffer\n\n/-- A convenience wrapper around `read` that just fails if the index is out of bounds.\n-/\nunsafe def read_t (b : Buffer α) (i : ℕ) : tactic α :=\n if h : i < b.size then return <| b.read (Fin.mk i h) else tactic.fail \"invalid buffer access\"\n#align buffer.read_t buffer.read_t\n\nend Buffer\n\n", "meta": {"author": "leanprover-community", "repo": "mathlib3port", "sha": "62505aa236c58c8559783b16d33e30df3daa54f4", "save_path": "github-repos/lean/leanprover-community-mathlib3port", "path": "github-repos/lean/leanprover-community-mathlib3port/mathlib3port-62505aa236c58c8559783b16d33e30df3daa54f4/Mathbin/Data/Buffer/Basic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.30735802955444114, "lm_q2_score": 0.08632348422559333, "lm_q1q2_score": 0.026532216015852247}} {"text": "/-\nCopyright (c) 2018 Mario Carneiro. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Mario Carneiro\n-/\nimport tactic.doc_commands\n\nopen interactive\nopen interactive.types\n\nnamespace tactic\nnamespace interactive\nopen expr lean.parser\n\nlocal postfix (name := parser.optional) `?`:9001 := optional\n\n/--\nThis is a \"finishing\" tactic modification of `simp`. It has two forms.\n\n* `simpa [rules, ...] using e` will simplify the goal and the type of\n `e` using `rules`, then try to close the goal using `e`.\n\n Simplifying the type of `e` makes it more likely to match the goal\n (which has also been simplified). This construction also tends to be\n more robust under changes to the simp lemma set.\n\n* `simpa [rules, ...]` will simplify the goal and the type of a\n hypothesis `this` if present in the context, then try to close the goal using\n the `assumption` tactic. -/\nmeta def simpa (use_iota_eqn : parse $ (tk \"!\")?) (trace_lemmas : parse $ (tk \"?\")?)\n (no_dflt : parse only_flag) (hs : parse simp_arg_list) (attr_names : parse with_ident_list)\n (tgt : parse (tk \"using\" *> texpr)?) (cfg : simp_config_ext := {}) : tactic unit :=\nlet simp_at lc (close_tac : tactic unit) := focus1 $\n simp use_iota_eqn trace_lemmas no_dflt hs attr_names (loc.ns lc)\n {fail_if_unchanged := ff, ..cfg} >>\n (((close_tac <|> trivial) >> done) <|> fail \"simpa failed\") in\nmatch tgt with\n| none := get_local `this >> simp_at [some `this, none] assumption <|> simp_at [none] assumption\n| some e := focus1 $ do\n e ← i_to_expr e <|> do\n { ty ← target,\n -- for positional error messages, we don't care about the result\n e ← i_to_expr_strict ``(%%e : %%ty),\n pty ← pp ty, ptgt ← pp e,\n -- Fail deliberately, to advise regarding `simp; exact` usage\n fail (\"simpa failed, 'using' expression type not directly \" ++\n \"inferrable. Try:\\n\\nsimpa ... using\\nshow \" ++\n to_fmt pty ++ \",\\nfrom \" ++ ptgt : format) },\n match e with\n | local_const _ lc _ _ := simp_at [some lc, none] (get_local lc >>= tactic.exact)\n | e := do\n t ← infer_type e,\n assertv `this t e,\n simp_at [some `this, none] (get_local `this >>= tactic.exact),\n all_goals (try apply_instance)\n end\nend\n\nadd_tactic_doc\n{ name := \"simpa\",\n category := doc_category.tactic,\n decl_names := [`tactic.interactive.simpa],\n tags := [\"simplification\"] }\n\nend interactive\nend tactic\n", "meta": {"author": "leanprover-community", "repo": "mathlib", "sha": "5e526d18cea33550268dcbbddcb822d5cde40654", "save_path": "github-repos/lean/leanprover-community-mathlib", "path": "github-repos/lean/leanprover-community-mathlib/mathlib-5e526d18cea33550268dcbbddcb822d5cde40654/src/tactic/simpa.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4263216071250873, "lm_q2_score": 0.061875989616020845, "lm_q1q2_score": 0.02637907133555722}} {"text": "/-\nCopyright (c) 2018 Scott Morrison. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Scott Morrison, Jannis Limperg\n\nFacts about `ulift` and `plift`.\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.default\nimport Mathlib.PostPort\n\nuniverses u v u_1 u_2 u_3 \n\nnamespace Mathlib\n\nnamespace plift\n\n\n/-- Functorial action. -/\n@[simp] protected def map {α : Sort u} {β : Sort v} (f : α → β) : plift α → plift β :=\n sorry\n\n/-- Embedding of pure values. -/\n@[simp] protected def pure {α : Sort u} : α → plift α :=\n up\n\n/-- Applicative sequencing. -/\n@[simp] protected def seq {α : Sort u} {β : Sort v} : plift (α → β) → plift α → plift β :=\n sorry\n\n/-- Monadic bind. -/\n@[simp] protected def bind {α : Sort u} {β : Sort v} : plift α → (α → plift β) → plift β :=\n sorry\n\nprotected instance monad : Monad plift :=\n { toApplicative :=\n { toFunctor := { map := plift.map, mapConst := fun (α β : Type u_1) => plift.map ∘ function.const β },\n toPure := { pure := plift.pure }, toSeq := { seq := plift.seq },\n toSeqLeft :=\n { seqLeft := fun (α β : Type u_1) (a : plift α) (b : plift β) => plift.seq (plift.map (function.const β) a) b },\n toSeqRight :=\n { seqRight :=\n fun (α β : Type u_1) (a : plift α) (b : plift β) => plift.seq (plift.map (function.const α id) a) b } },\n toBind := { bind := plift.bind } }\n\nprotected instance is_lawful_functor : is_lawful_functor plift :=\n is_lawful_functor.mk (fun (α : Type u_1) (_x : plift α) => sorry)\n fun (α β γ : Type u_1) (g : α → β) (h : β → γ) (_x : plift α) => sorry\n\nprotected instance is_lawful_applicative : is_lawful_applicative plift :=\n is_lawful_applicative.mk (fun (α β : Type u_1) (g : α → β) (_x : plift α) => sorry)\n (fun (α β : Type u_1) (g : α → β) (x : α) => rfl) (fun (α β : Type u_1) (_x : plift (α → β)) => sorry)\n fun (α β γ : Type u_1) (_x : plift α) => sorry\n\nprotected instance is_lawful_monad : is_lawful_monad plift :=\n is_lawful_monad.mk (fun (α β : Type u_1) (x : α) (f : α → plift β) => rfl)\n fun (α β γ : Type u_1) (_x : plift α) => sorry\n\n@[simp] theorem rec.constant {α : Sort u} {β : Type v} (b : β) : (plift.rec fun (_x : α) => b) = fun (_x : plift α) => b :=\n funext fun (x : plift α) => cases_on x fun (a : α) => Eq.refl (plift.rec (fun (_x : α) => b) (up a))\n\nend plift\n\n\nnamespace ulift\n\n\n/-- Functorial action. -/\n@[simp] protected def map {α : Type u} {β : Type v} (f : α → β) : ulift α → ulift β :=\n sorry\n\n/-- Embedding of pure values. -/\n@[simp] protected def pure {α : Type u} : α → ulift α :=\n up\n\n/-- Applicative sequencing. -/\n@[simp] protected def seq {α : Type u} {β : Type v} : ulift (α → β) → ulift α → ulift β :=\n sorry\n\n/-- Monadic bind. -/\n@[simp] protected def bind {α : Type u} {β : Type v} : ulift α → (α → ulift β) → ulift β :=\n sorry\n\n-- The `up ∘ down` gives us more universe polymorphism than simply `f a`.\n\nprotected instance monad : Monad ulift :=\n { toApplicative :=\n { toFunctor := { map := ulift.map, mapConst := fun (α β : Type u_1) => ulift.map ∘ function.const β },\n toPure := { pure := ulift.pure }, toSeq := { seq := ulift.seq },\n toSeqLeft :=\n { seqLeft := fun (α β : Type u_1) (a : ulift α) (b : ulift β) => ulift.seq (ulift.map (function.const β) a) b },\n toSeqRight :=\n { seqRight :=\n fun (α β : Type u_1) (a : ulift α) (b : ulift β) => ulift.seq (ulift.map (function.const α id) a) b } },\n toBind := { bind := ulift.bind } }\n\nprotected instance is_lawful_functor : is_lawful_functor ulift :=\n is_lawful_functor.mk (fun (α : Type u_1) (_x : ulift α) => sorry)\n fun (α β γ : Type u_1) (g : α → β) (h : β → γ) (_x : ulift α) => sorry\n\nprotected instance is_lawful_applicative : is_lawful_applicative ulift :=\n is_lawful_applicative.mk (fun (α β : Type u_1) (g : α → β) (_x : ulift α) => sorry)\n (fun (α β : Type u_1) (g : α → β) (x : α) => rfl) (fun (α β : Type u_1) (_x : ulift (α → β)) => sorry)\n fun (α β γ : Type u_1) (_x : ulift α) => sorry\n\nprotected instance is_lawful_monad : is_lawful_monad ulift :=\n is_lawful_monad.mk\n (fun (α β : Type u_1) (x : α) (f : α → ulift β) =>\n id (cases_on (f x) fun (down : β) => Eq.refl (up (down (up down)))))\n fun (α β γ : Type u_1) (_x : ulift α) => sorry\n\n@[simp] theorem rec.constant {α : Type u} {β : Sort v} (b : β) : (ulift.rec fun (_x : α) => b) = fun (_x : ulift α) => b :=\n funext fun (x : ulift α) => cases_on x fun (a : α) => Eq.refl (ulift.rec (fun (_x : α) => b) (up a))\n\n", "meta": {"author": "AurelienSaue", "repo": "Mathlib4_auto", "sha": "590df64109b08190abe22358fabc3eae000943f2", "save_path": "github-repos/lean/AurelienSaue-Mathlib4_auto", "path": "github-repos/lean/AurelienSaue-Mathlib4_auto/Mathlib4_auto-590df64109b08190abe22358fabc3eae000943f2/Mathlib/data/ulift.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4378234991142019, "lm_q2_score": 0.06008665269869255, "lm_q1q2_score": 0.026307348534601375}} {"text": "/-\nCopyright (c) 2017 Mario Carneiro. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Mario Carneiro, Jeremy Avigad, Simon Hudon\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.default\nimport Mathlib.data.rel\nimport Mathlib.PostPort\n\nuniverses u l u_1 u_2 u_3 \n\nnamespace Mathlib\n\n/-- `roption α` is the type of \"partial values\" of type `α`. It\n is similar to `option α` except the domain condition can be an\n arbitrary proposition, not necessarily decidable. -/\nstructure roption (α : Type u) \nwhere\n dom : Prop\n get : dom → α\n\nnamespace roption\n\n\n/-- Convert an `roption α` with a decidable domain to an option -/\ndef to_option {α : Type u_1} (o : roption α) [Decidable (dom o)] : Option α :=\n dite (dom o) (fun (h : dom o) => some (get o h)) fun (h : ¬dom o) => none\n\n/-- `roption` extensionality -/\ntheorem ext' {α : Type u_1} {o : roption α} {p : roption α} (H1 : dom o ↔ dom p) (H2 : ∀ (h₁ : dom o) (h₂ : dom p), get o h₁ = get p h₂) : o = p := sorry\n\n/-- `roption` eta expansion -/\n@[simp] theorem eta {α : Type u_1} (o : roption α) : (mk (dom o) fun (h : dom o) => get o h) = o := sorry\n\n/-- `a ∈ o` means that `o` is defined and equal to `a` -/\nprotected def mem {α : Type u_1} (a : α) (o : roption α) :=\n ∃ (h : dom o), get o h = a\n\nprotected instance has_mem {α : Type u_1} : has_mem α (roption α) :=\n has_mem.mk roption.mem\n\ntheorem mem_eq {α : Type u_1} (a : α) (o : roption α) : a ∈ o = ∃ (h : dom o), get o h = a :=\n rfl\n\ntheorem dom_iff_mem {α : Type u_1} {o : roption α} : dom o ↔ ∃ (y : α), y ∈ o := sorry\n\ntheorem get_mem {α : Type u_1} {o : roption α} (h : dom o) : get o h ∈ o :=\n Exists.intro h rfl\n\n/-- `roption` extensionality -/\ntheorem ext {α : Type u_1} {o : roption α} {p : roption α} (H : ∀ (a : α), a ∈ o ↔ a ∈ p) : o = p := sorry\n\n/-- The `none` value in `roption` has a `false` domain and an empty function. -/\ndef none {α : Type u_1} : roption α :=\n mk False False._oldrec\n\nprotected instance inhabited {α : Type u_1} : Inhabited (roption α) :=\n { default := none }\n\n@[simp] theorem not_mem_none {α : Type u_1} (a : α) : ¬a ∈ none :=\n fun (h : a ∈ none) => Exists.fst h\n\n/-- The `some a` value in `roption` has a `true` domain and the\n function returns `a`. -/\ndef some {α : Type u_1} (a : α) : roption α :=\n mk True fun (_x : True) => a\n\ntheorem mem_unique {α : Type u_1} : relator.left_unique has_mem.mem := sorry\n\ntheorem get_eq_of_mem {α : Type u_1} {o : roption α} {a : α} (h : a ∈ o) (h' : dom o) : get o h' = a :=\n mem_unique (Exists.intro h' rfl) h\n\n@[simp] theorem get_some {α : Type u_1} {a : α} (ha : dom (some a)) : get (some a) ha = a :=\n rfl\n\ntheorem mem_some {α : Type u_1} (a : α) : a ∈ some a :=\n Exists.intro trivial rfl\n\n@[simp] theorem mem_some_iff {α : Type u_1} {a : α} {b : α} : b ∈ some a ↔ b = a := sorry\n\ntheorem eq_some_iff {α : Type u_1} {a : α} {o : roption α} : o = some a ↔ a ∈ o := sorry\n\ntheorem eq_none_iff {α : Type u_1} {o : roption α} : o = none ↔ ∀ (a : α), ¬a ∈ o := sorry\n\ntheorem eq_none_iff' {α : Type u_1} {o : roption α} : o = none ↔ ¬dom o :=\n { mp := fun (e : o = none) => Eq.symm e ▸ id,\n mpr := fun (h : ¬dom o) => iff.mpr eq_none_iff fun (a : α) (h' : a ∈ o) => h (Exists.fst h') }\n\ntheorem some_ne_none {α : Type u_1} (x : α) : some x ≠ none :=\n id fun (h : some x = none) => id (eq.mpr (id (Eq._oldrec (Eq.refl (dom none)) (Eq.symm h))) trivial)\n\ntheorem ne_none_iff {α : Type u_1} {o : roption α} : o ≠ none ↔ ∃ (x : α), o = some x := sorry\n\ntheorem eq_none_or_eq_some {α : Type u_1} (o : roption α) : o = none ∨ ∃ (x : α), o = some x := sorry\n\n@[simp] theorem some_inj {α : Type u_1} {a : α} {b : α} : some a = some b ↔ a = b :=\n function.injective.eq_iff fun (a b : α) (h : some a = some b) => congr_fun (eq_of_heq (and.right (mk.inj h))) trivial\n\n@[simp] theorem some_get {α : Type u_1} {a : roption α} (ha : dom a) : some (get a ha) = a :=\n Eq.symm (iff.mpr eq_some_iff (Exists.intro ha rfl))\n\ntheorem get_eq_iff_eq_some {α : Type u_1} {a : roption α} {ha : dom a} {b : α} : get a ha = b ↔ a = some b := sorry\n\nprotected instance none_decidable {α : Type u_1} : Decidable (dom none) :=\n decidable.false\n\nprotected instance some_decidable {α : Type u_1} (a : α) : Decidable (dom (some a)) :=\n decidable.true\n\ndef get_or_else {α : Type u_1} (a : roption α) [Decidable (dom a)] (d : α) : α :=\n dite (dom a) (fun (ha : dom a) => get a ha) fun (ha : ¬dom a) => d\n\n@[simp] theorem get_or_else_none {α : Type u_1} (d : α) : get_or_else none d = d :=\n dif_neg id\n\n@[simp] theorem get_or_else_some {α : Type u_1} (a : α) (d : α) : get_or_else (some a) d = a :=\n dif_pos trivial\n\n@[simp] theorem mem_to_option {α : Type u_1} {o : roption α} [Decidable (dom o)] {a : α} : a ∈ to_option o ↔ a ∈ o := sorry\n\n/-- Convert an `option α` into an `roption α` -/\ndef of_option {α : Type u_1} : Option α → roption α :=\n sorry\n\n@[simp] theorem mem_of_option {α : Type u_1} {a : α} {o : Option α} : a ∈ of_option o ↔ a ∈ o := sorry\n\n@[simp] theorem of_option_dom {α : Type u_1} (o : Option α) : dom (of_option o) ↔ ↥(option.is_some o) := sorry\n\ntheorem of_option_eq_get {α : Type u_1} (o : Option α) : of_option o = mk (↥(option.is_some o)) option.get := sorry\n\nprotected instance has_coe {α : Type u_1} : has_coe (Option α) (roption α) :=\n has_coe.mk of_option\n\n@[simp] theorem mem_coe {α : Type u_1} {a : α} {o : Option α} : a ∈ ↑o ↔ a ∈ o :=\n mem_of_option\n\n@[simp] theorem coe_none {α : Type u_1} : ↑none = none :=\n rfl\n\n@[simp] theorem coe_some {α : Type u_1} (a : α) : ↑(some a) = some a :=\n rfl\n\nprotected theorem induction_on {α : Type u_1} {P : roption α → Prop} (a : roption α) (hnone : P none) (hsome : ∀ (a : α), P (some a)) : P a :=\n or.elim (classical.em (dom a)) (fun (h : dom a) => some_get h ▸ hsome (get a h))\n fun (h : ¬dom a) => Eq.symm (iff.mpr eq_none_iff' h) ▸ hnone\n\nprotected instance of_option_decidable {α : Type u_1} (o : Option α) : Decidable (dom (of_option o)) :=\n sorry\n\n@[simp] theorem to_of_option {α : Type u_1} (o : Option α) : to_option (of_option o) = o :=\n option.cases_on o (Eq.refl (to_option (of_option none))) fun (o : α) => Eq.refl (to_option (of_option (some o)))\n\n@[simp] theorem of_to_option {α : Type u_1} (o : roption α) [Decidable (dom o)] : of_option (to_option o) = o :=\n ext fun (a : α) => iff.trans mem_of_option mem_to_option\n\ndef equiv_option {α : Type u_1} : roption α ≃ Option α :=\n equiv.mk (fun (o : roption α) => to_option o) of_option sorry sorry\n\nprotected instance order_bot {α : Type u_1} : order_bot (roption α) :=\n order_bot.mk none (fun (x y : roption α) => ∀ (i : α), i ∈ x → i ∈ y)\n (partial_order.lt._default fun (x y : roption α) => ∀ (i : α), i ∈ x → i ∈ y) sorry sorry sorry sorry\n\nprotected instance preorder {α : Type u_1} : preorder (roption α) :=\n partial_order.to_preorder (roption α)\n\ntheorem le_total_of_le_of_le {α : Type u_1} {x : roption α} {y : roption α} (z : roption α) (hx : x ≤ z) (hy : y ≤ z) : x ≤ y ∨ y ≤ x := sorry\n\n/-- `assert p f` is a bind-like operation which appends an additional condition\n `p` to the domain and uses `f` to produce the value. -/\ndef assert {α : Type u_1} (p : Prop) (f : p → roption α) : roption α :=\n mk (∃ (h : p), dom (f h)) fun (ha : ∃ (h : p), dom (f h)) => get (f sorry) sorry\n\n/-- The bind operation has value `g (f.get)`, and is defined when all the\n parts are defined. -/\nprotected def bind {α : Type u_1} {β : Type u_2} (f : roption α) (g : α → roption β) : roption β :=\n assert (dom f) fun (b : dom f) => g (get f b)\n\n/-- The map operation for `roption` just maps the value and maintains the same domain. -/\ndef map {α : Type u_1} {β : Type u_2} (f : α → β) (o : roption α) : roption β :=\n mk (dom o) (f ∘ get o)\n\ntheorem mem_map {α : Type u_1} {β : Type u_2} (f : α → β) {o : roption α} {a : α} : a ∈ o → f a ∈ map f o := sorry\n\n@[simp] theorem mem_map_iff {α : Type u_1} {β : Type u_2} (f : α → β) {o : roption α} {b : β} : b ∈ map f o ↔ ∃ (a : α), ∃ (H : a ∈ o), f a = b := sorry\n\n@[simp] theorem map_none {α : Type u_1} {β : Type u_2} (f : α → β) : map f none = none := sorry\n\n@[simp] theorem map_some {α : Type u_1} {β : Type u_2} (f : α → β) (a : α) : map f (some a) = some (f a) :=\n iff.mpr eq_some_iff (mem_map f (mem_some a))\n\ntheorem mem_assert {α : Type u_1} {p : Prop} {f : p → roption α} {a : α} (h : p) : a ∈ f h → a ∈ assert p f := sorry\n\n@[simp] theorem mem_assert_iff {α : Type u_1} {p : Prop} {f : p → roption α} {a : α} : a ∈ assert p f ↔ ∃ (h : p), a ∈ f h := sorry\n\ntheorem assert_pos {α : Type u_1} {p : Prop} {f : p → roption α} (h : p) : assert p f = f h := sorry\n\ntheorem assert_neg {α : Type u_1} {p : Prop} {f : p → roption α} (h : ¬p) : assert p f = none := sorry\n\ntheorem mem_bind {α : Type u_1} {β : Type u_2} {f : roption α} {g : α → roption β} {a : α} {b : β} : a ∈ f → b ∈ g a → b ∈ roption.bind f g := sorry\n\n@[simp] theorem mem_bind_iff {α : Type u_1} {β : Type u_2} {f : roption α} {g : α → roption β} {b : β} : b ∈ roption.bind f g ↔ ∃ (a : α), ∃ (H : a ∈ f), b ∈ g a := sorry\n\n@[simp] theorem bind_none {α : Type u_1} {β : Type u_2} (f : α → roption β) : roption.bind none f = none := sorry\n\n@[simp] theorem bind_some {α : Type u_1} {β : Type u_2} (a : α) (f : α → roption β) : roption.bind (some a) f = f a := sorry\n\ntheorem bind_some_eq_map {α : Type u_1} {β : Type u_2} (f : α → β) (x : roption α) : roption.bind x (some ∘ f) = map f x := sorry\n\ntheorem bind_assoc {α : Type u_1} {β : Type u_2} {γ : Type u_3} (f : roption α) (g : α → roption β) (k : β → roption γ) : roption.bind (roption.bind f g) k = roption.bind f fun (x : α) => roption.bind (g x) k := sorry\n\n@[simp] theorem bind_map {α : Type u_1} {β : Type u_2} {γ : Type u_3} (f : α → β) (x : roption α) (g : β → roption γ) : roption.bind (map f x) g = roption.bind x fun (y : α) => g (f y) := sorry\n\n@[simp] theorem map_bind {α : Type u_1} {β : Type u_2} {γ : Type u_3} (f : α → roption β) (x : roption α) (g : β → γ) : map g (roption.bind x f) = roption.bind x fun (y : α) => map g (f y) := sorry\n\ntheorem map_map {α : Type u_1} {β : Type u_2} {γ : Type u_3} (g : β → γ) (f : α → β) (o : roption α) : map g (map f o) = map (g ∘ f) o := sorry\n\nprotected instance monad : Monad roption :=\n { toApplicative :=\n { toFunctor := { map := map, mapConst := fun (α β : Type u_1) => map ∘ function.const β },\n toPure := { pure := some },\n toSeq :=\n { seq :=\n fun (α β : Type u_1) (f : roption (α → β)) (x : roption α) => roption.bind f fun (_x : α → β) => map _x x },\n toSeqLeft :=\n { seqLeft :=\n fun (α β : Type u_1) (a : roption α) (b : roption β) =>\n (fun (α β : Type u_1) (f : roption (α → β)) (x : roption α) =>\n roption.bind f fun (_x : α → β) => map _x x)\n β α (map (function.const β) a) b },\n toSeqRight :=\n { seqRight :=\n fun (α β : Type u_1) (a : roption α) (b : roption β) =>\n (fun (α β : Type u_1) (f : roption (α → β)) (x : roption α) =>\n roption.bind f fun (_x : α → β) => map _x x)\n β β (map (function.const α id) a) b } },\n toBind := { bind := roption.bind } }\n\nprotected instance is_lawful_monad : is_lawful_monad roption :=\n is_lawful_monad.mk bind_some bind_assoc\n\ntheorem map_id' {α : Type u_1} {f : α → α} (H : ∀ (x : α), f x = x) (o : roption α) : map f o = o :=\n eq.mpr (id (Eq._oldrec (Eq.refl (map f o = o)) ((fun (this : f = id) => this) (funext H)))) (id_map o)\n\n@[simp] theorem bind_some_right {α : Type u_1} (x : roption α) : roption.bind x some = x := sorry\n\n@[simp] theorem pure_eq_some {α : Type u_1} (a : α) : pure a = some a :=\n rfl\n\n@[simp] theorem ret_eq_some {α : Type u_1} (a : α) : return a = some a :=\n rfl\n\n@[simp] theorem map_eq_map {α : Type u_1} {β : Type u_1} (f : α → β) (o : roption α) : f <$> o = map f o :=\n rfl\n\n@[simp] theorem bind_eq_bind {α : Type u_1} {β : Type u_1} (f : roption α) (g : α → roption β) : f >>= g = roption.bind f g :=\n rfl\n\ntheorem bind_le {β : Type u_2} {α : Type u_2} (x : roption α) (f : α → roption β) (y : roption β) : x >>= f ≤ y ↔ ∀ (a : α), a ∈ x → f a ≤ y := sorry\n\nprotected instance monad_fail : monad_fail roption :=\n monad_fail.mk fun (_x : Type u_1) (_x_1 : string) => none\n\n/- `restrict p o h` replaces the domain of `o` with `p`, and is well defined when\n `p` implies `o` is defined. -/\n\ndef restrict {α : Type u_1} (p : Prop) (o : roption α) : (p → dom o) → roption α :=\n sorry\n\n@[simp] theorem mem_restrict {α : Type u_1} (p : Prop) (o : roption α) (h : p → dom o) (a : α) : a ∈ restrict p o h ↔ p ∧ a ∈ o := sorry\n\n/-- `unwrap o` gets the value at `o`, ignoring the condition.\n (This function is unsound.) -/\ntheorem assert_defined {α : Type u_1} {p : Prop} {f : p → roption α} (h : p) : dom (f h) → dom (assert p f) :=\n exists.intro\n\ntheorem bind_defined {α : Type u_1} {β : Type u_2} {f : roption α} {g : α → roption β} (h : dom f) : dom (g (get f h)) → dom (roption.bind f g) :=\n assert_defined\n\n@[simp] theorem bind_dom {α : Type u_1} {β : Type u_2} {f : roption α} {g : α → roption β} : dom (roption.bind f g) ↔ ∃ (h : dom f), dom (g (get f h)) :=\n iff.rfl\n\nend roption\n\n\n/-- `pfun α β`, or `α →. β`, is the type of partial functions from\n `α` to `β`. It is defined as `α → roption β`. -/\ndef pfun (α : Type u_1) (β : Type u_2) :=\n α → roption β\n\ninfixr:25 \" →. \" => Mathlib.pfun\n\nnamespace pfun\n\n\nprotected instance inhabited {α : Type u_1} {β : Type u_2} : Inhabited (α →. β) :=\n { default := fun (a : α) => roption.none }\n\n/-- The domain of a partial function -/\ndef dom {α : Type u_1} {β : Type u_2} (f : α →. β) : set α :=\n set_of fun (a : α) => roption.dom (f a)\n\ntheorem mem_dom {α : Type u_1} {β : Type u_2} (f : α →. β) (x : α) : x ∈ dom f ↔ ∃ (y : β), y ∈ f x := sorry\n\ntheorem dom_eq {α : Type u_1} {β : Type u_2} (f : α →. β) : dom f = set_of fun (x : α) => ∃ (y : β), y ∈ f x :=\n set.ext (mem_dom f)\n\n/-- Evaluate a partial function -/\ndef fn {α : Type u_1} {β : Type u_2} (f : α →. β) (x : α) (h : dom f x) : β :=\n roption.get (f x) h\n\n/-- Evaluate a partial function to return an `option` -/\ndef eval_opt {α : Type u_1} {β : Type u_2} (f : α →. β) [D : decidable_pred (dom f)] (x : α) : Option β :=\n roption.to_option (f x)\n\n/-- Partial function extensionality -/\ntheorem ext' {α : Type u_1} {β : Type u_2} {f : α →. β} {g : α →. β} (H1 : ∀ (a : α), a ∈ dom f ↔ a ∈ dom g) (H2 : ∀ (a : α) (p : dom f a) (q : dom g a), fn f a p = fn g a q) : f = g :=\n funext fun (a : α) => roption.ext' (H1 a) (H2 a)\n\ntheorem ext {α : Type u_1} {β : Type u_2} {f : α →. β} {g : α →. β} (H : ∀ (a : α) (b : β), b ∈ f a ↔ b ∈ g a) : f = g :=\n funext fun (a : α) => roption.ext (H a)\n\n/-- Turn a partial function into a function out of a subtype -/\ndef as_subtype {α : Type u_1} {β : Type u_2} (f : α →. β) (s : ↥(dom f)) : β :=\n fn f ↑s sorry\n\n/-- The set of partial functions `α →. β` is equivalent to\nthe set of pairs `(p : α → Prop, f : subtype p → β)`. -/\ndef equiv_subtype {α : Type u_1} {β : Type u_2} : (α →. β) ≃ sigma fun (p : α → Prop) => Subtype p → β :=\n equiv.mk (fun (f : α →. β) => sigma.mk (fun (a : α) => roption.dom (f a)) (as_subtype f))\n (fun (f : sigma fun (p : α → Prop) => Subtype p → β) (x : α) =>\n roption.mk (sigma.fst f x) fun (h : sigma.fst f x) => sigma.snd f { val := x, property := h })\n sorry sorry\n\ntheorem as_subtype_eq_of_mem {α : Type u_1} {β : Type u_2} {f : α →. β} {x : α} {y : β} (fxy : y ∈ f x) (domx : x ∈ dom f) : as_subtype f { val := x, property := domx } = y :=\n roption.mem_unique (roption.get_mem (as_subtype._proof_1 f { val := x, property := domx })) fxy\n\n/-- Turn a total function into a partial function -/\nprotected def lift {α : Type u_1} {β : Type u_2} (f : α → β) : α →. β :=\n fun (a : α) => roption.some (f a)\n\nprotected instance has_coe {α : Type u_1} {β : Type u_2} : has_coe (α → β) (α →. β) :=\n has_coe.mk pfun.lift\n\n@[simp] theorem lift_eq_coe {α : Type u_1} {β : Type u_2} (f : α → β) : pfun.lift f = ↑f :=\n rfl\n\n@[simp] theorem coe_val {α : Type u_1} {β : Type u_2} (f : α → β) (a : α) : coe f a = roption.some (f a) :=\n rfl\n\n/-- The graph of a partial function is the set of pairs\n `(x, f x)` where `x` is in the domain of `f`. -/\ndef graph {α : Type u_1} {β : Type u_2} (f : α →. β) : set (α × β) :=\n set_of fun (p : α × β) => prod.snd p ∈ f (prod.fst p)\n\ndef graph' {α : Type u_1} {β : Type u_2} (f : α →. β) : rel α β :=\n fun (x : α) (y : β) => y ∈ f x\n\n/-- The range of a partial function is the set of values\n `f x` where `x` is in the domain of `f`. -/\ndef ran {α : Type u_1} {β : Type u_2} (f : α →. β) : set β :=\n set_of fun (b : β) => ∃ (a : α), b ∈ f a\n\n/-- Restrict a partial function to a smaller domain. -/\ndef restrict {α : Type u_1} {β : Type u_2} (f : α →. β) {p : set α} (H : p ⊆ dom f) : α →. β :=\n fun (x : α) => roption.restrict (x ∈ p) (f x) H\n\n@[simp] theorem mem_restrict {α : Type u_1} {β : Type u_2} {f : α →. β} {s : set α} (h : s ⊆ dom f) (a : α) (b : β) : b ∈ restrict f h a ↔ a ∈ s ∧ b ∈ f a := sorry\n\ndef res {α : Type u_1} {β : Type u_2} (f : α → β) (s : set α) : α →. β :=\n restrict (pfun.lift f) (set.subset_univ s)\n\ntheorem mem_res {α : Type u_1} {β : Type u_2} (f : α → β) (s : set α) (a : α) (b : β) : b ∈ res f s a ↔ a ∈ s ∧ f a = b := sorry\n\ntheorem res_univ {α : Type u_1} {β : Type u_2} (f : α → β) : res f set.univ = ↑f :=\n rfl\n\ntheorem dom_iff_graph {α : Type u_1} {β : Type u_2} (f : α →. β) (x : α) : x ∈ dom f ↔ ∃ (y : β), (x, y) ∈ graph f :=\n roption.dom_iff_mem\n\ntheorem lift_graph {α : Type u_1} {β : Type u_2} {f : α → β} {a : α} {b : β} : (a, b) ∈ graph ↑f ↔ f a = b := sorry\n\n/-- The monad `pure` function, the total constant `x` function -/\nprotected def pure {α : Type u_1} {β : Type u_2} (x : β) : α →. β :=\n fun (_x : α) => roption.some x\n\n/-- The monad `bind` function, pointwise `roption.bind` -/\ndef bind {α : Type u_1} {β : Type u_2} {γ : Type u_3} (f : α →. β) (g : β → α →. γ) : α →. γ :=\n fun (a : α) => roption.bind (f a) fun (b : β) => g b a\n\n/-- The monad `map` function, pointwise `roption.map` -/\ndef map {α : Type u_1} {β : Type u_2} {γ : Type u_3} (f : β → γ) (g : α →. β) : α →. γ :=\n fun (a : α) => roption.map f (g a)\n\nprotected instance monad {α : Type u_1} : Monad (pfun α) :=\n { toApplicative :=\n { toFunctor := { map := map, mapConst := fun (α_1 β : Type u_2) => map ∘ function.const β },\n toPure := { pure := pfun.pure },\n toSeq :=\n { seq := fun (α_1 β : Type u_2) (f : α →. α_1 → β) (x : α →. α_1) => bind f fun (_x : α_1 → β) => map _x x },\n toSeqLeft :=\n { seqLeft :=\n fun (α_1 β : Type u_2) (a : α →. α_1) (b : α →. β) =>\n (fun (α_2 β : Type u_2) (f : α →. α_2 → β) (x : α →. α_2) => bind f fun (_x : α_2 → β) => map _x x) β α_1\n (map (function.const β) a) b },\n toSeqRight :=\n { seqRight :=\n fun (α_1 β : Type u_2) (a : α →. α_1) (b : α →. β) =>\n (fun (α_2 β : Type u_2) (f : α →. α_2 → β) (x : α →. α_2) => bind f fun (_x : α_2 → β) => map _x x) β β\n (map (function.const α_1 id) a) b } },\n toBind := { bind := bind } }\n\nprotected instance is_lawful_monad {α : Type u_1} : is_lawful_monad (pfun α) :=\n is_lawful_monad.mk (fun (β γ : Type u_2) (x : β) (f : β → α →. γ) => funext fun (a : α) => roption.bind_some a (f x))\n fun (β γ δ : Type u_2) (f : α →. β) (g : β → α →. γ) (k : γ → α →. δ) =>\n funext fun (a : α) => roption.bind_assoc (f a) (fun (b : β) => g b a) fun (b : γ) => k b a\n\ntheorem pure_defined {α : Type u_1} {β : Type u_2} (p : set α) (x : β) : p ⊆ dom (pfun.pure x) :=\n set.subset_univ p\n\ntheorem bind_defined {α : Type u_1} {β : Type u_2} {γ : Type u_2} (p : set α) {f : α →. β} {g : β → α →. γ} (H1 : p ⊆ dom f) (H2 : ∀ (x : β), p ⊆ dom (g x)) : p ⊆ dom (f >>= g) :=\n fun (a : α) (ha : a ∈ p) => Exists.intro (H1 ha) (H2 (roption.get (f a) (H1 ha)) ha)\n\ndef fix {α : Type u_1} {β : Type u_2} (f : α →. β ⊕ α) : α →. β :=\n fun (a : α) =>\n roption.assert (acc (fun (x y : α) => sum.inr x ∈ f y) a)\n fun (h : acc (fun (x y : α) => sum.inr x ∈ f y) a) =>\n well_founded.fix_F\n (fun (a : α) (IH : (y : α) → sum.inr y ∈ f a → roption β) =>\n roption.assert (roption.dom (f a))\n fun (hf : roption.dom (f a)) =>\n (fun (_x : β ⊕ α) (e : roption.get (f a) hf = _x) =>\n sum.cases_on _x (fun (b : β) (e : roption.get (f a) hf = sum.inl b) => roption.some b)\n (fun (a' : α) (e : roption.get (f a) hf = sum.inr a') => IH a' sorry) e)\n (roption.get (f a) hf) sorry)\n a h\n\ntheorem dom_of_mem_fix {α : Type u_1} {β : Type u_2} {f : α →. β ⊕ α} {a : α} {b : β} (h : b ∈ fix f a) : roption.dom (f a) := sorry\n\ntheorem mem_fix_iff {α : Type u_1} {β : Type u_2} {f : α →. β ⊕ α} {a : α} {b : β} : b ∈ fix f a ↔ sum.inl b ∈ f a ∨ ∃ (a' : α), sum.inr a' ∈ f a ∧ b ∈ fix f a' := sorry\n\ndef fix_induction {α : Type u_1} {β : Type u_2} {f : α →. β ⊕ α} {b : β} {C : α → Sort u_3} {a : α} (h : b ∈ fix f a) (H : (a : α) → b ∈ fix f a → ((a' : α) → b ∈ fix f a' → sum.inr a' ∈ f a → C a') → C a) : C a := sorry\n\nend pfun\n\n\nnamespace pfun\n\n\ndef image {α : Type u_1} {β : Type u_2} (f : α →. β) (s : set α) : set β :=\n rel.image (graph' f) s\n\ntheorem image_def {α : Type u_1} {β : Type u_2} (f : α →. β) (s : set α) : image f s = set_of fun (y : β) => ∃ (x : α), ∃ (H : x ∈ s), y ∈ f x :=\n rfl\n\ntheorem mem_image {α : Type u_1} {β : Type u_2} (f : α →. β) (y : β) (s : set α) : y ∈ image f s ↔ ∃ (x : α), ∃ (H : x ∈ s), y ∈ f x :=\n iff.rfl\n\ntheorem image_mono {α : Type u_1} {β : Type u_2} (f : α →. β) {s : set α} {t : set α} (h : s ⊆ t) : image f s ⊆ image f t :=\n rel.image_mono (graph' f) h\n\ntheorem image_inter {α : Type u_1} {β : Type u_2} (f : α →. β) (s : set α) (t : set α) : image f (s ∩ t) ⊆ image f s ∩ image f t :=\n rel.image_inter (graph' f) s t\n\ntheorem image_union {α : Type u_1} {β : Type u_2} (f : α →. β) (s : set α) (t : set α) : image f (s ∪ t) = image f s ∪ image f t :=\n rel.image_union (graph' f) s t\n\ndef preimage {α : Type u_1} {β : Type u_2} (f : α →. β) (s : set β) : set α :=\n rel.preimage (fun (x : α) (y : β) => y ∈ f x) s\n\ntheorem preimage_def {α : Type u_1} {β : Type u_2} (f : α →. β) (s : set β) : preimage f s = set_of fun (x : α) => ∃ (y : β), ∃ (H : y ∈ s), y ∈ f x :=\n rfl\n\ntheorem mem_preimage {α : Type u_1} {β : Type u_2} (f : α →. β) (s : set β) (x : α) : x ∈ preimage f s ↔ ∃ (y : β), ∃ (H : y ∈ s), y ∈ f x :=\n iff.rfl\n\ntheorem preimage_subset_dom {α : Type u_1} {β : Type u_2} (f : α →. β) (s : set β) : preimage f s ⊆ dom f := sorry\n\ntheorem preimage_mono {α : Type u_1} {β : Type u_2} (f : α →. β) {s : set β} {t : set β} (h : s ⊆ t) : preimage f s ⊆ preimage f t :=\n rel.preimage_mono (fun (x : α) (y : β) => y ∈ f x) h\n\ntheorem preimage_inter {α : Type u_1} {β : Type u_2} (f : α →. β) (s : set β) (t : set β) : preimage f (s ∩ t) ⊆ preimage f s ∩ preimage f t :=\n rel.preimage_inter (fun (x : α) (y : β) => y ∈ f x) s t\n\ntheorem preimage_union {α : Type u_1} {β : Type u_2} (f : α →. β) (s : set β) (t : set β) : preimage f (s ∪ t) = preimage f s ∪ preimage f t :=\n rel.preimage_union (fun (x : α) (y : β) => y ∈ f x) s t\n\ntheorem preimage_univ {α : Type u_1} {β : Type u_2} (f : α →. β) : preimage f set.univ = dom f := sorry\n\ndef core {α : Type u_1} {β : Type u_2} (f : α →. β) (s : set β) : set α :=\n rel.core (graph' f) s\n\ntheorem core_def {α : Type u_1} {β : Type u_2} (f : α →. β) (s : set β) : core f s = set_of fun (x : α) => ∀ (y : β), y ∈ f x → y ∈ s :=\n rfl\n\ntheorem mem_core {α : Type u_1} {β : Type u_2} (f : α →. β) (x : α) (s : set β) : x ∈ core f s ↔ ∀ (y : β), y ∈ f x → y ∈ s :=\n iff.rfl\n\ntheorem compl_dom_subset_core {α : Type u_1} {β : Type u_2} (f : α →. β) (s : set β) : dom fᶜ ⊆ core f s :=\n fun (x : α) (hx : x ∈ (dom fᶜ)) (y : β) (fxy : graph' f x y) => absurd (iff.mpr (mem_dom f x) (Exists.intro y fxy)) hx\n\ntheorem core_mono {α : Type u_1} {β : Type u_2} (f : α →. β) {s : set β} {t : set β} (h : s ⊆ t) : core f s ⊆ core f t :=\n rel.core_mono (graph' f) h\n\ntheorem core_inter {α : Type u_1} {β : Type u_2} (f : α →. β) (s : set β) (t : set β) : core f (s ∩ t) = core f s ∩ core f t :=\n rel.core_inter (graph' f) s t\n\ntheorem mem_core_res {α : Type u_1} {β : Type u_2} (f : α → β) (s : set α) (t : set β) (x : α) : x ∈ core (res f s) t ↔ x ∈ s → f x ∈ t := sorry\n\ntheorem core_res {α : Type u_1} {β : Type u_2} (f : α → β) (s : set α) (t : set β) : core (res f s) t = sᶜ ∪ f ⁻¹' t := sorry\n\ntheorem core_restrict {α : Type u_1} {β : Type u_2} (f : α → β) (s : set β) : core (↑f) s = f ⁻¹' s := sorry\n\ntheorem preimage_subset_core {α : Type u_1} {β : Type u_2} (f : α →. β) (s : set β) : preimage f s ⊆ core f s := sorry\n\ntheorem preimage_eq {α : Type u_1} {β : Type u_2} (f : α →. β) (s : set β) : preimage f s = core f s ∩ dom f := sorry\n\ntheorem core_eq {α : Type u_1} {β : Type u_2} (f : α →. β) (s : set β) : core f s = preimage f s ∪ (dom fᶜ) := sorry\n\ntheorem preimage_as_subtype {α : Type u_1} {β : Type u_2} (f : α →. β) (s : set β) : as_subtype f ⁻¹' s = subtype.val ⁻¹' preimage f s := sorry\n\n", "meta": {"author": "AurelienSaue", "repo": "Mathlib4_auto", "sha": "590df64109b08190abe22358fabc3eae000943f2", "save_path": "github-repos/lean/AurelienSaue-Mathlib4_auto", "path": "github-repos/lean/AurelienSaue-Mathlib4_auto/Mathlib4_auto-590df64109b08190abe22358fabc3eae000943f2/Mathlib/data/pfun.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41869689484852374, "lm_q2_score": 0.06278921166614723, "lm_q1q2_score": 0.02628964795460255}} {"text": "/-\nCopyright (c) 2018 Scott Morrison. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Keeley Hoek, Scott Morrison\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.default\nimport Mathlib.tactic.rewrite_search.explain\nimport Mathlib.tactic.rewrite_search.discovery\nimport Mathlib.tactic.rewrite_search.search\nimport Mathlib.PostPort\n\nnamespace Mathlib\n\n/-!\n# `rewrite_search`: solving goals by searching for a series of rewrites.\n\n`rewrite_search` is a tactic for solving equalities or iff statements by searching for a\nsequence of rewrite tactic applications.\n\n## Algorithm sketch\n\nThe fundamental data structure behind the search algorithm is a graph of expressions. Each\nvertex represents one expression, and an edge in the graph represents a way to rewrite one\nexpression into another with a single application of a rewrite tactic. Thus, a path in the\ngraph represents a way to rewrite one expression into another with multiple applications of\na rewrite tactic.\n\nThe graph starts out with two vertices, one for the left hand side of the equality, and one\nfor the right hand side of the equality. The basic loop of the algorithm is to repeatedly add\nedges to the graph by taking vertices in the graph and applying a possible rewrite to them.\nThrough this process, the graph is made up of two connected components; one component contains\nexpressions that are equivalent to the left hand side, and one component contains expressions\nthat are equivalent to the right hand side. The algorithm completes when we discover an\nedge that connects the two components, creating a path of rewrites that connects the\nleft hand side and right hand side of the graph. For more detail, see Keeley's report at\nhttps://hoek.io/res/2018.s2.lean.report.pdf, although note that the edit distance mechanism\ndescribed is currently not implemented, only plain breadth-first search.\n\nThis algorithm is generally superior to one that only expands nodes starting from a single\nside, because it is replacing one tree of depth `2d` with two trees of depth `d`. This is\na quadratic speedup for regular trees; our trees aren't regular but it's still probably\na much better algorithm. We can only use this specific algorithm for rewrite-type tactics,\nthough, not general sequences of tactics, because it relies on the fact that any rewrite\ncan be reversed.\n\n## File structure\n\n* `discovery.lean` contains the logic for figuring out which rewrite rules to consider.\n* `search.lean` contains the graph algorithms to find a successful sequence of tactics.\n* `explain.lean` generates concise Lean code to run a tactic, from the autogenerated sequence\n of tactics.\n* `frontend.lean` contains the user-facing interface to the `rewrite_search` tactics.\n* `types.lean` contains data structures shared across multiple of these components.\n-/\n\nnamespace tactic.interactive\n\n\n/--\nParse a specification for a single rewrite rule.\nThe name of a lemma indicates using it as a rewrite. Prepending a \"←\" reverses the direction.\n-/\n/--\nSearch for a chain of rewrites to prove an equation or iff statement.\n\nCollects rewrite rules, runs a graph search to find a chain of rewrites to prove the\ncurrent target, and generates a string explanation for it.\n\nTakes an optional list of rewrite rules specified in the same way as the `rw` tactic accepts.\n-/\n", "meta": {"author": "AurelienSaue", "repo": "Mathlib4_auto", "sha": "590df64109b08190abe22358fabc3eae000943f2", "save_path": "github-repos/lean/AurelienSaue-Mathlib4_auto", "path": "github-repos/lean/AurelienSaue-Mathlib4_auto/Mathlib4_auto-590df64109b08190abe22358fabc3eae000943f2/Mathlib/tactic/rewrite_search/frontend.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4493926197162522, "lm_q2_score": 0.058345844295802765, "lm_q1q2_score": 0.026220191817647356}} {"text": "/-\n# Tactics\n\nTactics are Lean programs that manipulate a custom state. All tactics are, in\nthe end, of type `TacticM Unit`. This has the type:\n\n```lean\n-- from Lean/Elab/Tactic/Basic.lean\nTacticM = ReaderT Context $ StateRefT State TermElabM\n```\n\nBut before demonstrating how to use `TacticM`, we shall explore macro-based\ntactics.\n\n## Tactics by Macro Expansion\n\nJust like many other parts of the Lean 4 infrastructure, tactics too can be\ndeclared by lightweight macro expansion.\n\nFor example, we build an example of a `custom_sorry_macro` that elaborates into\na `sorry`. We write this as a macro expansion, which expands the piece of syntax\n`custom_sorry_macro` into the piece of syntax `sorry`:\n-/\n\nimport Lean.Elab.Tactic\n\nmacro \"custom_sorry_macro\" : tactic => `(tactic| sorry)\n\nexample : 1 = 42 := by\n custom_sorry_macro\n\n/-\n### Implementing `trivial`: Extensible Tactics by Macro Expansion\n\nAs more complex examples, we can write a tactic such as `custom_tactic`, which\nis initially completely unimplemented, and can be extended with more tactics.\nWe start by simply declaring the tactic with no implementation:\n-/\n\nsyntax \"custom_tactic\" : tactic\n\nexample : 42 = 42 := by\n custom_tactic\n-- tactic 'tacticCustom_tactic' has not been implemented\n sorry\n\n/-\nWe will now add the `rfl` tactic into `custom_tactic`, which will allow us to\nprove the previous theorem\n-/\n\nmacro_rules\n| `(tactic| custom_tactic) => `(tactic| rfl)\n\nexample : 42 = 42 := by\n custom_tactic\n-- Goals accomplished 🎉\n\n/-\nWe can now try a harder problem, that cannot be immediately dispatched by `rfl`:\n-/\n\nexample : 43 = 43 ∧ 42 = 42:= by\n custom_tactic\n-- tactic 'rfl' failed, equality expected\n-- 43 = 43 ∧ 42 = 42\n-- ⊢ 43 = 43 ∧ 42 = 42\n\n/-\nWe extend the `custom_tactic` tactic with a tactic that tries to break `And`\ndown with `apply And.intro`, and then (recursively (!)) applies `custom_tactic`\nto the two cases with `(<;> trivial)` to solve the generated subcases `43 = 43`,\n`42 = 42`.\n-/\n\nmacro_rules\n| `(tactic| custom_tactic) => `(tactic| apply And.intro <;> custom_tactic)\n\n/-\nThe above declaration uses `<;>` which is a *tactic combinator*. Here, `a <;> b`\nmeans \"run tactic `a`, and apply \"b\" to each goal produced by `a`\". Thus,\n`And.intro <;> custom_tactic` means \"run `And.intro`, and then run\n`custom_tactic` on each goal\". We test it out on our previous theorem and see\nthat we dispatch the theorem.\n-/\n\nexample : 43 = 43 ∧ 42 = 42 := by\n custom_tactic\n-- Goals accomplished 🎉\n\n/-\nIn summary, we declared an extensible tactic called `custom_tactic`. It\ninitially had no elaboration at all. We added the `rfl` as an elaboration of\n`custom_tactic`, which allowed it to solve the goal `42 = 42`. We then tried a\nharder theorem, `43 = 43 ∧ 42 = 42` which `custom_tactic` was unable to solve.\nWe were then able to enrich `custom_tactic` to split \"and\" with `And.intro`, and\nalso *recursively* call `custom_tactic` in the two subcases.\n\n### Implementing `<;>`: Tactic Combinators by Macro Expansion\n\nRecall that in the previous section, we said that `a <;> b` meant \"run `a`, and\nthen run `b` for all goals\". In fact, `<;>` itself is a tactic macro. In this\nsection, we will implement the syntax `a and_then b` which will stand for\n\"run `a`, and then run `b` for all goals\".\n-/\n\n-- 1. We declare the syntax `and_then`\nsyntax tactic \" and_then \" tactic : tactic\n\n-- 2. We write the expander that expands the tactic\n-- into running `a`, and then running `b` on all goals produced by `a`.\nmacro_rules\n| `(tactic| $a:tactic and_then $b:tactic) =>\n `(tactic| $a:tactic; all_goals $b:tactic)\n\n-- 3. We test this tactic.\ntheorem test_and_then: 1 = 1 ∧ 2 = 2 := by\n apply And.intro and_then rfl\n\n#print test_and_then\n-- theorem test_and_then : 1 = 1 ∧ 2 = 2 :=\n-- { left := Eq.refl 1, right := Eq.refl 2 }\n\n/-\n## Exploring `TacticM`\n\n### The simplest tactic: `sorry`\n\nIn this section, we wish to write a tactic that fills the proof with sorry:\n\n```lean\nexample : 1 = 2 := by\n custom_sorry\n```\n\nWe begin by declaring such a tactic:\n-/\n\nelab \"custom_sorry_0\" : tactic => do\n return\n\nexample : 1 = 2 := by\n custom_sorry_0\n-- unsolved goals: ⊢ 1 = 2\n\n/-\nThis defines a syntax extension to Lean, where we are naming the piece of syntax\n`custom_sorry_0` as living in `tactic` syntax category. This informs the\nelaborator that, in the context of elaborating `tactic`s, the piece of syntax\n`custom_sorry_0` must be elaborated as what we write to the right-hand-side of\nthe `=>` (the actual implementation of the tactic).\n\nNext, we write a term in `TacticM Unit` to fill in the goal with `sorryAx α`,\nwhich can synthesize an artificial term of type `α`. To do this, we first access\nthe goal with `Lean.Elab.Tactic.getMainGoal : Tactic MVarId`, which returns the\nmain goal, represented as a metavariable. Recall that under\ntypes-as-propositions, the type of our goal must be the proposition that `1 = 2`.\nWe check this by printing the type of `goal`.\n\nBut first we need to start our tactic with `Lean.Elab.Tactic.withMainContext`,\nwhich computes in `TacticM` with an updated context.\n-/\n\nelab \"custom_sorry_1\" : tactic =>\n Lean.Elab.Tactic.withMainContext do\n let goal ← Lean.Elab.Tactic.getMainGoal\n let goalDecl ← goal.getDecl\n let goalType := goalDecl.type\n dbg_trace f!\"goal type: {goalType}\"\n\nexample : 1 = 2 := by\n custom_sorry_1\n-- goal type: Eq.{1} Nat (OfNat.ofNat.{0} Nat 1 (instOfNatNat 1)) (OfNat.ofNat.{0} Nat 2 (instOfNatNat 2))\n-- unsolved goals: ⊢ 1 = 2\n\n/-\nTo `sorry` the goal, we can use the helper `Lean.Elab.admitGoal`:\n-/\n\nelab \"custom_sorry_2\" : tactic =>\n Lean.Elab.Tactic.withMainContext do\n let goal ← Lean.Elab.Tactic.getMainGoal\n Lean.Elab.admitGoal goal\n\ntheorem test_custom_sorry : 1 = 2 := by\n custom_sorry_2\n\n#print test_custom_sorry\n-- theorem test_custom_sorry : 1 = 2 :=\n-- sorryAx (1 = 2) true\n\n/-\nAnd we no longer have the error `unsolved goals: ⊢ 1 = 2`.\n\n### The `custom_assump` tactic: Accessing Hypotheses\n\nIn this section, we will learn how to access the hypotheses to prove a goal. In\nparticular, we shall attempt to implement a tactic `custom_assump`, which looks\nfor an exact match of the goal among the hypotheses, and solves the theorem if\npossible.\n\nIn the example below, we expect `custom_assump` to use `(H2 : 2 = 2)` to solve\nthe goal `(2 = 2)`:\n\n```lean\ntheorem assump_correct (H1 : 1 = 1) (H2 : 2 = 2) : 2 = 2 := by\n custom_assump\n\n#print assump_correct\n-- theorem assump_correct : 1 = 1 → 2 = 2 → 2 = 2 :=\n-- fun H1 H2 => H2\n```\n\nWhen we do not have a matching hypothesis to the goal, we expect the tactic\n`custom_assump` to throw an error, telling us that we cannot find a hypothesis\nof the type we are looking for:\n\n```lean\ntheorem assump_wrong (H1 : 1 = 1) : 2 = 2 := by\n custom_assump\n\n#print assump_wrong\n-- tactic 'custom_assump' failed, unable to find matching hypothesis of type (2 = 2)\n-- H1 : 1 = 1\n-- ⊢ 2 = 2\n```\n\nWe begin by accessing the goal and the type of the goal so we know what we\nare trying to prove. The `goal` variable will soon be used to help us create\nerror messages.\n-/\n\nelab \"custom_assump_0\" : tactic =>\n Lean.Elab.Tactic.withMainContext do\n let goalType ← Lean.Elab.Tactic.getMainTarget\n dbg_trace f!\"goal type: {goalType}\"\n\nexample (H1 : 1 = 1) (H2 : 2 = 2): 2 = 2 := by\n custom_assump_0\n-- goal type: Eq.{1} Nat (OfNat.ofNat.{0} Nat 2 (instOfNatNat 2)) (OfNat.ofNat.{0} Nat 2 (instOfNatNat 2))\n-- unsolved goals\n-- H1 : 1 = 1\n-- H2 : 2 = 2\n-- ⊢ 2 = 2\n\nexample (H1 : 1 = 1): 2 = 2 := by\n custom_assump_0\n-- goal type: Eq.{1} Nat (OfNat.ofNat.{0} Nat 2 (instOfNatNat 2)) (OfNat.ofNat.{0} Nat 2 (instOfNatNat 2))\n-- unsolved goals\n-- H1 : 1 = 1\n-- ⊢ 2 = 2\n\n/-\nNext, we access the list of hypotheses, which are stored in a data structure\ncalled `LocalContext`. This is accessed via `Lean.MonadLCtx.getLCtx`. The\n`LocalContext` contains `LocalDeclaration`s, from which we can extract\ninformation such as the name that is given to declarations (`.userName`), the\nexpression of the declaration (`.toExpr`). Let's write a tactic called\n`list_local_decls` that prints the local declarations:\n-/\n\nelab \"list_local_decls_1\" : tactic =>\n Lean.Elab.Tactic.withMainContext do\n let ctx ← Lean.MonadLCtx.getLCtx -- get the local context.\n ctx.forM fun decl: Lean.LocalDecl => do\n let declExpr := decl.toExpr -- Find the expression of the declaration.\n let declName := decl.userName -- Find the name of the declaration.\n dbg_trace f!\"+ local decl: name: {declName} | expr: {declExpr}\"\n\nexample (H1 : 1 = 1) (H2 : 2 = 2): 1 = 1 := by\n list_local_decls_1\n-- + local decl: name: test_list_local_decls_1 | expr: _uniq.3339\n-- + local decl: name: H1 | expr: _uniq.3340\n-- + local decl: name: H2 | expr: _uniq.3341\n rfl\n\n/-\nRecall that we are looking for a local declaration that has the same type as the\nhypothesis. We get the type of `LocalDecl` by calling\n`Lean.Meta.inferType` on the local declaration's expression.\n-/\n\nelab \"list_local_decls_2\" : tactic =>\n Lean.Elab.Tactic.withMainContext do\n let ctx ← Lean.MonadLCtx.getLCtx -- get the local context.\n ctx.forM fun decl: Lean.LocalDecl => do\n let declExpr := decl.toExpr -- Find the expression of the declaration.\n let declName := decl.userName -- Find the name of the declaration.\n let declType ← Lean.Meta.inferType declExpr -- **NEW:** Find the type.\n dbg_trace f!\"+ local decl: name: {declName} | expr: {declExpr} | type: {declType}\"\n\nexample (H1 : 1 = 1) (H2 : 2 = 2): 1 = 1 := by\n list_local_decls_2\n -- + local decl: name: test_list_local_decls_2 | expr: _uniq.4263 | type: (Eq.{1} Nat ...)\n -- + local decl: name: H1 | expr: _uniq.4264 | type: Eq.{1} Nat ...)\n -- + local decl: name: H2 | expr: _uniq.4265 | type: Eq.{1} Nat ...)\n rfl\n\n/-\nWe check if the type of the `LocalDecl` is equal to the goal type with\n`Lean.Meta.isExprDefEq`. See that we check if the types are equal at `eq?`, and\nwe print that `H1` has the same type as the goal\n(`local decl[EQUAL? true]: name: H1`), and we print that `H2` does not have the\nsame type (`local decl[EQUAL? false]: name: H2 `):\n-/\n\nelab \"list_local_decls_3\" : tactic =>\n Lean.Elab.Tactic.withMainContext do\n let goalType ← Lean.Elab.Tactic.getMainTarget\n let ctx ← Lean.MonadLCtx.getLCtx -- get the local context.\n ctx.forM fun decl: Lean.LocalDecl => do\n let declExpr := decl.toExpr -- Find the expression of the declaration.\n let declName := decl.userName -- Find the name of the declaration.\n let declType ← Lean.Meta.inferType declExpr -- Find the type.\n let eq? ← Lean.Meta.isExprDefEq declType goalType -- **NEW** Check if type equals goal type.\n dbg_trace f!\"+ local decl[EQUAL? {eq?}]: name: {declName}\"\n\nexample (H1 : 1 = 1) (H2 : 2 = 2): 1 = 1 := by\n list_local_decls_3\n-- + local decl[EQUAL? false]: name: test_list_local_decls_3\n-- + local decl[EQUAL? true]: name: H1\n-- + local decl[EQUAL? false]: name: H2\n rfl\n\n/-\nFinally, we put all of these parts together to write a tactic that loops over\nall declarations and finds one with the correct type. We loop over declarations\nwith `lctx.findDeclM?`. We infer the type of declarations with\n`Lean.Meta.inferType`. We check that the declaration has the same type as the\ngoal with `Lean.Meta.isExprDefEq`:\n-/\n\nelab \"custom_assump_1\" : tactic =>\n Lean.Elab.Tactic.withMainContext do\n let goalType ← Lean.Elab.Tactic.getMainTarget\n let lctx ← Lean.MonadLCtx.getLCtx\n -- Iterate over the local declarations...\n let option_matching_expr ← lctx.findDeclM? fun ldecl: Lean.LocalDecl => do\n let declExpr := ldecl.toExpr -- Find the expression of the declaration.\n let declType ← Lean.Meta.inferType declExpr -- Find the type.\n if (← Lean.Meta.isExprDefEq declType goalType) -- Check if type equals goal type.\n then return some declExpr -- If equal, success!\n else return none -- Not found.\n dbg_trace f!\"matching_expr: {option_matching_expr}\"\n\nexample (H1 : 1 = 1) (H2 : 2 = 2) : 2 = 2 := by\n custom_assump_1\n-- matching_expr: some _uniq.6241\n rfl\n\nexample (H1 : 1 = 1) : 2 = 2 := by\n custom_assump_1\n-- matching_expr: none\n rfl\n\n/-\nNow that we are able to find the matching expression, we need to close the\ntheorem by using the match. We do this with `Lean.Elab.Tactic.closeMainGoal`.\nWhen we do not have a matching expression, we throw an error with\n`Lean.Meta.throwTacticEx`, which allows us to report an error corresponding to a\ngiven goal. When throwing this error, we format the error using `m!\"...\"` which\nbuilds a `MessageData`. This provides nicer error messages than using `f!\"...\"`\nwhich builds a `Format`. This is because `MessageData` also runs *delaboration*,\nwhich allows it to convert raw Lean terms like\n`(Eq.{1} Nat (OfNat.ofNat.{0} Nat 2 (instOfNatNat 2)) (OfNat.ofNat.{0} Nat 2 (instOfNatNat 2)))`\ninto readable strings like`(2 = 2)`. The full code listing given below shows how\nto do this:\n-/\n\nelab \"custom_assump_2\" : tactic =>\n Lean.Elab.Tactic.withMainContext do\n let goal ← Lean.Elab.Tactic.getMainGoal\n let goalType ← Lean.Elab.Tactic.getMainTarget\n let ctx ← Lean.MonadLCtx.getLCtx\n let option_matching_expr ← ctx.findDeclM? fun decl: Lean.LocalDecl => do\n let declExpr := decl.toExpr\n let declType ← Lean.Meta.inferType declExpr\n if ← Lean.Meta.isExprDefEq declType goalType\n then return Option.some declExpr\n else return Option.none\n match option_matching_expr with\n | some e => Lean.Elab.Tactic.closeMainGoal e\n | none =>\n Lean.Meta.throwTacticEx `custom_assump_2 goal\n (m!\"unable to find matching hypothesis of type ({goalType})\")\n\nexample (H1 : 1 = 1) (H2 : 2 = 2) : 2 = 2 := by\n custom_assump_2\n\nexample (H1 : 1 = 1): 2 = 2 := by\n custom_assump_2\n-- tactic 'custom_assump_2' failed, unable to find matching hypothesis of type (2 = 2)\n-- H1 : 1 = 1\n-- ⊢ 2 = 2\n\n/-\n### Tweaking the context\n\nUntil now, we've only performed read-like operations with the context. But what\nif we want to change it? In this section we will see how to change the order of\ngoals and how to add content to it (new hypotheses).\n\nThen, after elaborating our terms, we will need to use the helper function\n`Lean.Elab.Tactic.liftMetaTactic`, which allows us to run computations in\n`MetaM` while also giving us the goal `MVarId` for us to play with. In the end\nof our computation, `liftMetaTactic` expects us to return a `List MVarId` as the\nresulting list of goals.\n\nThe only substantial difference between `custom_let` and `custom_have` is that\nthe former uses `Lean.MVarId.define` and the later uses `Lean.MVarId.assert`:\n-/\n\nopen Lean.Elab.Tactic in\nelab \"custom_let \" n:ident \" : \" t:term \" := \" v:term : tactic =>\n withMainContext do\n let t ← elabTerm t none\n let v ← elabTermEnsuringType v t\n liftMetaTactic fun mvarId => do\n let mvarIdNew ← mvarId.define n.getId t v\n let (_, mvarIdNew) ← mvarIdNew.intro1P\n return [mvarIdNew]\n\nopen Lean.Elab.Tactic in\nelab \"custom_have \" n:ident \" : \" t:term \" := \" v:term : tactic =>\n withMainContext do\n let t ← elabTerm t none\n let v ← elabTermEnsuringType v t\n liftMetaTactic fun mvarId => do\n let mvarIdNew ← mvarId.assert n.getId t v\n let (_, mvarIdNew) ← mvarIdNew.intro1P\n return [mvarIdNew]\n\ntheorem test_faq_have : True := by\n custom_let n : Nat := 5\n custom_have h : n = n := rfl\n-- n : Nat := 5\n-- h : n = n\n-- ⊢ True\n trivial\n\n/-\n### \"Getting\" and \"Setting\" the list of goals\n\nTo illustrate these, let's build a tactic that can reverse the list of goals.\nWe can use `Lean.Elab.Tactic.getGoals` and `Lean.Elab.Tactic.setGoals`:\n-/\n\nelab \"reverse_goals\" : tactic =>\n Lean.Elab.Tactic.withMainContext do\n let goals : List Lean.MVarId ← Lean.Elab.Tactic.getGoals\n Lean.Elab.Tactic.setGoals goals.reverse\n\ntheorem test_reverse_goals : (1 = 2 ∧ 3 = 4) ∧ 5 = 6 := by\n constructor\n constructor\n-- case left.left\n-- ⊢ 1 = 2\n-- case left.right\n-- ⊢ 3 = 4\n-- case right\n-- ⊢ 5 = 6\n reverse_goals\n-- case right\n-- ⊢ 5 = 6\n-- case left.right\n-- ⊢ 3 = 4\n-- case left.left\n-- ⊢ 1 = 2\n\n/-\n## FAQ\n\nIn this section, we collect common patterns that are used during writing tactics,\nto make it easy to find common patterns.\n\n**Q: How do I use goals?**\n\nA: Goals are represented as metavariables. The module `Lean.Elab.Tactic.Basic`\nhas many functions to add new goals, switch goals, etc.\n\n**Q: How do I get the main goal?**\n\nA: Use `Lean.Elab.Tactic.getMainGoal`.\n-/\n\nelab \"faq_main_goal\" : tactic =>\n Lean.Elab.Tactic.withMainContext do\n let goal ← Lean.Elab.Tactic.getMainGoal\n dbg_trace f!\"goal: {goal.name}\"\n\nexample : 1 = 1 := by\n faq_main_goal\n-- goal: _uniq.9298\n rfl\n\n/-\n**Q: How do I get the list of goals?**\n\nA: Use `getGoals`.\n-/\n\nelab \"faq_get_goals\" : tactic =>\n Lean.Elab.Tactic.withMainContext do\n let goals ← Lean.Elab.Tactic.getGoals\n goals.forM $ fun goal => do\n let goalType ← goal.getType\n dbg_trace f!\"goal: {goal.name} | type: {goalType}\"\n\nexample (b : Bool) : b = true := by\n cases b\n faq_get_goals\n-- goal: _uniq.10067 | type: Eq.{1} Bool Bool.false Bool.true\n-- goal: _uniq.10078 | type: Eq.{1} Bool Bool.true Bool.true\n sorry\n rfl\n\n/-\n**Q: How do I get the current hypotheses for a goal?**\n\nA: Use `Lean.MonadLCtx.getLCtx` which provides the local context, and then\niterate on the `LocalDeclaration`s of the `LocalContext` with accessors such as\n`foldlM` and `forM`.\n-/\n\nelab \"faq_get_hypotheses\" : tactic =>\n Lean.Elab.Tactic.withMainContext do\n let ctx ← Lean.MonadLCtx.getLCtx -- get the local context.\n ctx.forM (fun (decl : Lean.LocalDecl) => do\n let declExpr := decl.toExpr -- Find the expression of the declaration.\n let declType := decl.type -- Find the type of the declaration.\n let declName := decl.userName -- Find the name of the declaration.\n dbg_trace f!\" local decl: name: {declName} | expr: {declExpr} | type: {declType}\"\n )\n\nexample (H1 : 1 = 1) (H2 : 2 = 2): 3 = 3 := by\n faq_get_hypotheses\n -- local decl: name: _example | expr: _uniq.10814 | type: ...\n -- local decl: name: H1 | expr: _uniq.10815 | type: ...\n -- local decl: name: H2 | expr: _uniq.10816 | type: ...\n rfl\n\n/-\n**Q: How do I evaluate a tactic?**\n\nA: Use `Lean.Elab.Tactic.evalTactic: Syntax → TacticM Unit` which evaluates a\ngiven tactic syntax. One can create tactic syntax using the macro\n`` `(tactic| ⋯)``.\n\nFor example, one could call `try rfl` with the piece of code:\n\n```lean\nLean.Elab.Tactic.evalTactic (← `(tactic| try rfl))\n```\n\n**Q: How do I check if two expressions are equal?**\n\nA: Use `Lean.Meta.isExprDefEq `.\n-/\n\n#check Lean.Meta.isExprDefEq\n-- Lean.Meta.isExprDefEq : Lean.Expr → Lean.Expr → Lean.MetaM Bool\n\n/-\n**Q: How do I throw an error from a tactic?**\n\nA: Use `throwTacticEx `.\n-/\n\nelab \"faq_throw_error\" : tactic =>\n Lean.Elab.Tactic.withMainContext do\n let goal ← Lean.Elab.Tactic.getMainGoal\n Lean.Meta.throwTacticEx `faq_throw_error goal \"throwing an error at the current goal\"\n\nexample (b : Bool): b = true := by\n cases b;\n faq_throw_error\n -- case true\n -- ⊢ true = true\n -- tactic 'faq_throw_error' failed, throwing an error at the current goal\n -- case false\n -- ⊢ false = true\n\n/-\n**Q: What is the difference between `Lean.Elab.Tactic.*` and `Lean.Meta.Tactic.*`?**\n\nA: `Lean.Meta.Tactic.*` contains low level code that uses the `Meta` monad to\nimplement basic features such as rewriting. `Lean.Elab.Tactic.*` contains\nhigh-level code that connects the low level development in `Lean.Meta` to the\ntactic infrastructure and the parsing front-end.\n-/\n", "meta": {"author": "leanprover-community", "repo": "lean4-metaprogramming-book", "sha": "0b2e7e2c0cacac530ed947df878088c5d9715412", "save_path": "github-repos/lean/leanprover-community-lean4-metaprogramming-book", "path": "github-repos/lean/leanprover-community-lean4-metaprogramming-book/lean4-metaprogramming-book-0b2e7e2c0cacac530ed947df878088c5d9715412/lean/main/tactics.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1919327864472368, "lm_q2_score": 0.13660837596589698, "lm_q1q2_score": 0.02621962625116634}} {"text": "/-\nCopyright (c) 2019 Zhouhang Zhou. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Zhouhang Zhou, Yury Kudryashov\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.default\nimport Mathlib.measure_theory.l1_space\nimport Mathlib.PostPort\n\nuniverses u_1 u_2 u_3 u_4 \n\nnamespace Mathlib\n\n/-!\n# Density of simple functions\n\nShow that each Borel measurable function can be approximated,\nboth pointwise and in `L¹` norm, by a sequence of simple functions.\n\n## Main definitions\n\n* `measure_theory.simple_func.nearest_pt (e : ℕ → α) (N : ℕ) : α →ₛ ℕ`: the `simple_func` sending\n each `x : α` to the point `e k` which is the nearest to `x` among `e 0`, ..., `e N`.\n* `measure_theory.simple_func.approx_on (f : β → α) (hf : measurable f) (s : set α) (y₀ : α)\n (h₀ : y₀ ∈ s) [separable_space s] (n : ℕ) : β →ₛ α` : a simple function that takes values in `s`\n and approximates `f`. If `f x ∈ s`, then `measure_theory.simple_func.approx_on f hf s y₀ h₀ n x`\n tends to `f x` as `n` tends to `∞`. If `α` is a `normed_group`, `f x - y₀`\n is `measure_theory.integrable`, and `f x ∈ s` for a.e. `x`, then\n `simple_func.approx_on f hf s y₀ h₀ n` tends to `f` in `L₁`. The main use case is `s = univ`,\n `y₀ = 0`.\n\n## Notations\n\n* `α →ₛ β` (local notation): the type of simple functions `α → β`.\n-/\n\nnamespace measure_theory\n\n\nnamespace simple_func\n\n\n/-- `nearest_pt_ind e N x` is the index `k` such that `e k` is the nearest point to `x` among the\npoints `e 0`, ..., `e N`. If more than one point are at the same distance from `x`, then\n`nearest_pt_ind e N x` returns the least of their indexes. -/\ndef nearest_pt_ind {α : Type u_1} [measurable_space α] [emetric_space α] [opens_measurable_space α]\n (e : ℕ → α) : ℕ → simple_func α ℕ :=\n sorry\n\n/-- `nearest_pt e N x` is the nearest point to `x` among the points `e 0`, ..., `e N`. If more than\none point are at the same distance from `x`, then `nearest_pt e N x` returns the point with the\nleast possible index. -/\ndef nearest_pt {α : Type u_1} [measurable_space α] [emetric_space α] [opens_measurable_space α]\n (e : ℕ → α) (N : ℕ) : simple_func α α :=\n map e (nearest_pt_ind e N)\n\n@[simp] theorem nearest_pt_ind_zero {α : Type u_1} [measurable_space α] [emetric_space α]\n [opens_measurable_space α] (e : ℕ → α) : nearest_pt_ind e 0 = const α 0 :=\n rfl\n\n@[simp] theorem nearest_pt_zero {α : Type u_1} [measurable_space α] [emetric_space α]\n [opens_measurable_space α] (e : ℕ → α) : nearest_pt e 0 = const α (e 0) :=\n rfl\n\ntheorem nearest_pt_ind_succ {α : Type u_1} [measurable_space α] [emetric_space α]\n [opens_measurable_space α] (e : ℕ → α) (N : ℕ) (x : α) :\n coe_fn (nearest_pt_ind e (N + 1)) x =\n ite (∀ (k : ℕ), k ≤ N → edist (e (N + 1)) x < edist (e k) x) (N + 1)\n (coe_fn (nearest_pt_ind e N) x) :=\n sorry\n\ntheorem nearest_pt_ind_le {α : Type u_1} [measurable_space α] [emetric_space α]\n [opens_measurable_space α] (e : ℕ → α) (N : ℕ) (x : α) : coe_fn (nearest_pt_ind e N) x ≤ N :=\n sorry\n\ntheorem edist_nearest_pt_le {α : Type u_1} [measurable_space α] [emetric_space α]\n [opens_measurable_space α] (e : ℕ → α) (x : α) {k : ℕ} {N : ℕ} (hk : k ≤ N) :\n edist (coe_fn (nearest_pt e N) x) x ≤ edist (e k) x :=\n sorry\n\ntheorem tendsto_nearest_pt {α : Type u_1} [measurable_space α] [emetric_space α]\n [opens_measurable_space α] {e : ℕ → α} {x : α} (hx : x ∈ closure (set.range e)) :\n filter.tendsto (fun (N : ℕ) => coe_fn (nearest_pt e N) x) filter.at_top (nhds x) :=\n sorry\n\n/-- Approximate a measurable function by a sequence of simple functions `F n` such that\n`F n x ∈ s`. -/\ndef approx_on {α : Type u_1} {β : Type u_2} [measurable_space α] [emetric_space α]\n [opens_measurable_space α] [measurable_space β] (f : β → α) (hf : measurable f) (s : set α)\n (y₀ : α) (h₀ : y₀ ∈ s) [topological_space.separable_space ↥s] (n : ℕ) : simple_func β α :=\n comp (nearest_pt (fun (k : ℕ) => nat.cases_on k y₀ (coe ∘ topological_space.dense_seq ↥s)) n) f hf\n\n@[simp] theorem approx_on_zero {α : Type u_1} {β : Type u_2} [measurable_space α] [emetric_space α]\n [opens_measurable_space α] [measurable_space β] {f : β → α} (hf : measurable f) {s : set α}\n {y₀ : α} (h₀ : y₀ ∈ s) [topological_space.separable_space ↥s] (x : β) :\n coe_fn (approx_on f hf s y₀ h₀ 0) x = y₀ :=\n rfl\n\ntheorem approx_on_mem {α : Type u_1} {β : Type u_2} [measurable_space α] [emetric_space α]\n [opens_measurable_space α] [measurable_space β] {f : β → α} (hf : measurable f) {s : set α}\n {y₀ : α} (h₀ : y₀ ∈ s) [topological_space.separable_space ↥s] (n : ℕ) (x : β) :\n coe_fn (approx_on f hf s y₀ h₀ n) x ∈ s :=\n (fun (n_1 : ℕ) =>\n nat.cases_on n_1 h₀ fun (n : ℕ) => subtype.mem (topological_space.dense_seq (↥s) n))\n (coe_fn\n (nearest_pt_ind (fun (k : ℕ) => nat.cases_on k y₀ (coe ∘ topological_space.dense_seq ↥s)) n)\n (f x))\n\n@[simp] theorem approx_on_comp {α : Type u_1} {β : Type u_2} [measurable_space α] [emetric_space α]\n [opens_measurable_space α] [measurable_space β] {γ : Type u_3} [measurable_space γ] {f : β → α}\n (hf : measurable f) {g : γ → β} (hg : measurable g) {s : set α} {y₀ : α} (h₀ : y₀ ∈ s)\n [topological_space.separable_space ↥s] (n : ℕ) :\n approx_on (f ∘ g) (measurable.comp hf hg) s y₀ h₀ n = comp (approx_on f hf s y₀ h₀ n) g hg :=\n rfl\n\ntheorem tendsto_approx_on {α : Type u_1} {β : Type u_2} [measurable_space α] [emetric_space α]\n [opens_measurable_space α] [measurable_space β] {f : β → α} (hf : measurable f) {s : set α}\n {y₀ : α} (h₀ : y₀ ∈ s) [topological_space.separable_space ↥s] {x : β} (hx : f x ∈ closure s) :\n filter.tendsto (fun (n : ℕ) => coe_fn (approx_on f hf s y₀ h₀ n) x) filter.at_top\n (nhds (f x)) :=\n sorry\n\ntheorem edist_approx_on_le {α : Type u_1} {β : Type u_2} [measurable_space α] [emetric_space α]\n [opens_measurable_space α] [measurable_space β] {f : β → α} (hf : measurable f) {s : set α}\n {y₀ : α} (h₀ : y₀ ∈ s) [topological_space.separable_space ↥s] (x : β) (n : ℕ) :\n edist (coe_fn (approx_on f hf s y₀ h₀ n) x) (f x) ≤ edist y₀ (f x) :=\n id\n (edist_nearest_pt_le (Nat.rec y₀ fun (n : ℕ) (ih : α) => ↑(topological_space.dense_seq (↥s) n))\n (f x) (zero_le n))\n\ntheorem edist_approx_on_y0_le {α : Type u_1} {β : Type u_2} [measurable_space α] [emetric_space α]\n [opens_measurable_space α] [measurable_space β] {f : β → α} (hf : measurable f) {s : set α}\n {y₀ : α} (h₀ : y₀ ∈ s) [topological_space.separable_space ↥s] (x : β) (n : ℕ) :\n edist y₀ (coe_fn (approx_on f hf s y₀ h₀ n) x) ≤ edist y₀ (f x) + edist y₀ (f x) :=\n le_trans (edist_triangle_right y₀ (coe_fn (approx_on f hf s y₀ h₀ n) x) (f x))\n (add_le_add_left (edist_approx_on_le hf h₀ x n) (edist y₀ (f x)))\n\ntheorem norm_approx_on_zero_le {β : Type u_2} {E : Type u_4} [measurable_space β]\n [measurable_space E] [normed_group E] [opens_measurable_space E] {f : β → E} (hf : measurable f)\n {s : set E} (h₀ : 0 ∈ s) [topological_space.separable_space ↥s] (x : β) (n : ℕ) :\n norm (coe_fn (approx_on f hf s 0 h₀ n) x) ≤ norm (f x) + norm (f x) :=\n sorry\n\ntheorem tendsto_approx_on_l1_edist {β : Type u_2} {E : Type u_4} [measurable_space β]\n [measurable_space E] [normed_group E] [opens_measurable_space E] {f : β → E} (hf : measurable f)\n {s : set E} {y₀ : E} (h₀ : y₀ ∈ s) [topological_space.separable_space ↥s] {μ : measure β}\n (hμ : filter.eventually (fun (x : β) => f x ∈ closure s) (measure.ae μ))\n (hi : has_finite_integral fun (x : β) => f x - y₀) :\n filter.tendsto\n (fun (n : ℕ) =>\n lintegral μ fun (x : β) => edist (coe_fn (approx_on f hf s y₀ h₀ n) x) (f x))\n filter.at_top (nhds 0) :=\n sorry\n\ntheorem integrable_approx_on {β : Type u_2} {E : Type u_4} [measurable_space β] [measurable_space E]\n [normed_group E] [borel_space E] {f : β → E} {μ : measure β} (fmeas : measurable f)\n (hf : integrable f) {s : set E} {y₀ : E} (h₀ : y₀ ∈ s) [topological_space.separable_space ↥s]\n (hi₀ : integrable fun (x : β) => y₀) (n : ℕ) : integrable ⇑(approx_on f fmeas s y₀ h₀ n) :=\n sorry\n\ntheorem tendsto_approx_on_univ_l1_edist {β : Type u_2} {E : Type u_4} [measurable_space β]\n [measurable_space E] [normed_group E] [opens_measurable_space E]\n [topological_space.second_countable_topology E] {f : β → E} {μ : measure β}\n (fmeas : measurable f) (hf : integrable f) :\n filter.tendsto\n (fun (n : ℕ) =>\n lintegral μ\n fun (x : β) => edist (coe_fn (approx_on f fmeas set.univ 0 trivial n) x) (f x))\n filter.at_top (nhds 0) :=\n sorry\n\ntheorem integrable_approx_on_univ {β : Type u_2} {E : Type u_4} [measurable_space β]\n [measurable_space E] [normed_group E] [borel_space E]\n [topological_space.second_countable_topology E] {f : β → E} {μ : measure β}\n (fmeas : measurable f) (hf : integrable f) (n : ℕ) :\n integrable ⇑(approx_on f fmeas set.univ 0 trivial n) :=\n integrable_approx_on fmeas hf trivial (integrable_zero β E μ) n\n\ntheorem tendsto_approx_on_univ_l1 {β : Type u_2} {E : Type u_4} [measurable_space β]\n [measurable_space E] [normed_group E] [borel_space E]\n [topological_space.second_countable_topology E] {f : β → E} {μ : measure β}\n (fmeas : measurable f) (hf : integrable f) :\n filter.tendsto\n (fun (n : ℕ) =>\n l1.of_fun (⇑(approx_on f fmeas set.univ 0 trivial n))\n (integrable_approx_on_univ fmeas hf n))\n filter.at_top (nhds (l1.of_fun f hf)) :=\n iff.mpr tendsto_iff_edist_tendsto_0 (tendsto_approx_on_univ_l1_edist fmeas hf)\n\nend Mathlib", "meta": {"author": "AurelienSaue", "repo": "Mathlib4_auto", "sha": "590df64109b08190abe22358fabc3eae000943f2", "save_path": "github-repos/lean/AurelienSaue-Mathlib4_auto", "path": "github-repos/lean/AurelienSaue-Mathlib4_auto/Mathlib4_auto-590df64109b08190abe22358fabc3eae000943f2/Mathlib/measure_theory/simple_func_dense_auto.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.411110869232168, "lm_q2_score": 0.06371499914110602, "lm_q1q2_score": 0.026193928680026936}} {"text": "/-\nCopyright (c) 2018 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Leonardo de Moura\n-/\nimport Lean.Expr\n\nnamespace Lean\n/--\nReducibility hints are used in the convertibility checker.\nWhen trying to solve a constraint such a\n\n (f ...) =?= (g ...)\n\nwhere f and g are definitions, the checker has to decide which one will be unfolded.\n If f (g) is opaque, then g (f) is unfolded if it is also not marked as opaque,\n Else if f (g) is abbrev, then f (g) is unfolded if g (f) is also not marked as abbrev,\n Else if f and g are regular, then we unfold the one with the biggest definitional height.\n Otherwise both are unfolded.\n\nThe arguments of the `regular` Constructor are: the definitional height and the flag `selfOpt`.\n\nThe definitional height is by default computed by the kernel. It only takes into account\nother regular definitions used in a definition. When creating declarations using meta-programming,\nwe can specify the definitional depth manually.\n\nRemark: the hint only affects performance. None of the hints prevent the kernel from unfolding a\ndeclaration during Type checking.\n\nRemark: the ReducibilityHints are not related to the attributes: reducible/irrelevance/semireducible.\nThese attributes are used by the Elaborator. The ReducibilityHints are used by the kernel (and Elaborator).\nMoreover, the ReducibilityHints cannot be changed after a declaration is added to the kernel. -/\ninductive ReducibilityHints where\n | opaque : ReducibilityHints\n | abbrev : ReducibilityHints\n | regular : UInt32 → ReducibilityHints\n deriving Inhabited\n\n@[export lean_mk_reducibility_hints_regular]\ndef mkReducibilityHintsRegularEx (h : UInt32) : ReducibilityHints :=\n ReducibilityHints.regular h\n\n@[export lean_reducibility_hints_get_height]\ndef ReducibilityHints.getHeightEx (h : ReducibilityHints) : UInt32 :=\n match h with\n | ReducibilityHints.regular h => h\n | _ => 0\n\nnamespace ReducibilityHints\n\ndef lt : ReducibilityHints → ReducibilityHints → Bool\n | .abbrev, .abbrev => false\n | .abbrev, _ => true\n | .regular d₁, .regular d₂ => d₁ < d₂\n | .regular _, .opaque => true\n | _, _ => false\n\ndef isAbbrev : ReducibilityHints → Bool\n | .abbrev => true\n | _ => false\n\ndef isRegular : ReducibilityHints → Bool\n | regular .. => true\n | _ => false\n\nend ReducibilityHints\n\n/-- Base structure for `AxiomVal`, `DefinitionVal`, `TheoremVal`, `InductiveVal`, `ConstructorVal`, `RecursorVal` and `QuotVal`. -/\nstructure ConstantVal where\n name : Name\n levelParams : List Name\n type : Expr\n deriving Inhabited\n\nstructure AxiomVal extends ConstantVal where\n isUnsafe : Bool\n deriving Inhabited\n\n@[export lean_mk_axiom_val]\ndef mkAxiomValEx (name : Name) (levelParams : List Name) (type : Expr) (isUnsafe : Bool) : AxiomVal := {\n name := name,\n levelParams := levelParams,\n type := type,\n isUnsafe := isUnsafe\n}\n\n@[export lean_axiom_val_is_unsafe] def AxiomVal.isUnsafeEx (v : AxiomVal) : Bool :=\n v.isUnsafe\n\ninductive DefinitionSafety where\n | «unsafe» | safe | «partial»\n deriving Inhabited, BEq, Repr\n\nstructure DefinitionVal extends ConstantVal where\n value : Expr\n hints : ReducibilityHints\n safety : DefinitionSafety\n /--\n List of all (including this one) declarations in the same mutual block.\n Note that this information is not used by the kernel, and is only used\n to save the information provided by the user when using mutual blocks.\n Recall that the Lean kernel does not support recursive definitions and they\n are compiled using recursors and `WellFounded.fix`.\n -/\n all : List Name := [name]\n deriving Inhabited\n\n@[export lean_mk_definition_val]\ndef mkDefinitionValEx (name : Name) (levelParams : List Name) (type : Expr) (value : Expr) (hints : ReducibilityHints) (safety : DefinitionSafety) (all : List Name) : DefinitionVal := {\n name, levelParams, type, hints, safety, value, all\n}\n\n@[export lean_definition_val_get_safety] def DefinitionVal.getSafetyEx (v : DefinitionVal) : DefinitionSafety :=\n v.safety\n\nstructure TheoremVal extends ConstantVal where\n value : Expr\n /--\n List of all (including this one) declarations in the same mutual block.\n See comment at `DefinitionVal.all`. -/\n all : List Name := [name]\n deriving Inhabited\n\n/-- Value for an opaque constant declaration `opaque x : t := e` -/\nstructure OpaqueVal extends ConstantVal where\n value : Expr\n isUnsafe : Bool\n /--\n List of all (including this one) declarations in the same mutual block.\n See comment at `DefinitionVal.all`. -/\n all : List Name := [name]\n deriving Inhabited\n\n@[export lean_mk_opaque_val]\ndef mkOpaqueValEx (name : Name) (levelParams : List Name) (type : Expr) (value : Expr) (isUnsafe : Bool) (all : List Name) : OpaqueVal := {\n name, levelParams, type, value, isUnsafe, all\n}\n\n@[export lean_opaque_val_is_unsafe] def OpaqueVal.isUnsafeEx (v : OpaqueVal) : Bool :=\n v.isUnsafe\n\nstructure Constructor where\n name : Name\n type : Expr\n deriving Inhabited\n\nstructure InductiveType where\n name : Name\n type : Expr\n ctors : List Constructor\n deriving Inhabited\n\n/-- Declaration object that can be sent to the kernel. -/\ninductive Declaration where\n | axiomDecl (val : AxiomVal)\n | defnDecl (val : DefinitionVal)\n | thmDecl (val : TheoremVal)\n | opaqueDecl (val : OpaqueVal)\n | quotDecl\n | mutualDefnDecl (defns : List DefinitionVal) -- All definitions must be marked as `unsafe` or `partial`\n | inductDecl (lparams : List Name) (nparams : Nat) (types : List InductiveType) (isUnsafe : Bool)\n deriving Inhabited\n\n@[export lean_mk_inductive_decl]\ndef mkInductiveDeclEs (lparams : List Name) (nparams : Nat) (types : List InductiveType) (isUnsafe : Bool) : Declaration :=\n Declaration.inductDecl lparams nparams types isUnsafe\n\n@[export lean_is_unsafe_inductive_decl]\ndef Declaration.isUnsafeInductiveDeclEx : Declaration → Bool\n | Declaration.inductDecl _ _ _ isUnsafe => isUnsafe\n | _ => false\n\n@[specialize] def Declaration.foldExprM {α} {m : Type → Type} [Monad m] (d : Declaration) (f : α → Expr → m α) (a : α) : m α :=\n match d with\n | Declaration.quotDecl => pure a\n | Declaration.axiomDecl { type := type, .. } => f a type\n | Declaration.defnDecl { type := type, value := value, .. } => do let a ← f a type; f a value\n | Declaration.opaqueDecl { type := type, value := value, .. } => do let a ← f a type; f a value\n | Declaration.thmDecl { type := type, value := value, .. } => do let a ← f a type; f a value\n | Declaration.mutualDefnDecl vals => vals.foldlM (fun a v => do let a ← f a v.type; f a v.value) a\n | Declaration.inductDecl _ _ inductTypes _ =>\n inductTypes.foldlM\n (fun a inductType => do\n let a ← f a inductType.type\n inductType.ctors.foldlM (fun a ctor => f a ctor.type) a)\n a\n\n@[inline] def Declaration.forExprM {m : Type → Type} [Monad m] (d : Declaration) (f : Expr → m Unit) : m Unit :=\n d.foldExprM (fun _ a => f a) ()\n\n/-- The kernel compiles (mutual) inductive declarations (see `inductiveDecls`) into a set of\n - `Declaration.inductDecl` (for each inductive datatype in the mutual Declaration),\n - `Declaration.ctorDecl` (for each Constructor in the mutual Declaration),\n - `Declaration.recDecl` (automatically generated recursors).\n\n This data is used to implement iota-reduction efficiently and compile nested inductive\n declarations.\n\n A series of checks are performed by the kernel to check whether a `inductiveDecls`\n is valid or not. -/\nstructure InductiveVal extends ConstantVal where\n /-- Number of parameters. A parameter is an argument to the defined type that is fixed over constructors.\n An example of this is the `α : Type` argument in the vector constructors\n `nil : Vector α 0` and `cons : α → Vector α n → Vector α (n+1)`.\n\n The intuition is that the inductive type must exhibit _parametric polymorphism_ over the inductive\n parameter, as opposed to _ad-hoc polymorphism_.\n -/\n numParams : Nat\n /-- Number of indices. An index is an argument that varies over constructors.\n\n An example of this is the `n : Nat` argument in the vector constructor `cons : α → Vector α n → Vector α (n+1)`.\n -/\n numIndices : Nat\n /-- List of all (including this one) inductive datatypes in the mutual declaration containing this one -/\n all : List Name\n /-- List of the names of the constructors for this inductive datatype. -/\n ctors : List Name\n /-- `true` when recursive (that is, the inductive type appears as an argument in a constructor). -/\n isRec : Bool\n /-- Whether the definition is flagged as unsafe. -/\n isUnsafe : Bool\n /-- An inductive type is called reflexive if it has at least one constructor that takes as an argument a function returning the\n same type we are defining.\n Consider the type:\n ```\n inductive WideTree where\n | branch: (Nat -> WideTree) -> WideTree\n | leaf: WideTree\n ```\n this is reflexive due to the presence of the `branch : (Nat -> WideTree) -> WideTree` constructor.\n\n See also: 'Inductive Definitions in the system Coq Rules and Properties' by Christine Paulin-Mohring\n Section 2.2, Definition 3\n -/\n isReflexive : Bool\n /-- An inductive definition `T` is nested when there is a constructor with an argument `x : F T`,\n where `F : Type → Type` is some suitably behaved (ie strictly positive) function (Eg `Array T`, `List T`, `T × T`, ...). -/\n isNested : Bool\n deriving Inhabited\n\n@[export lean_mk_inductive_val]\ndef mkInductiveValEx (name : Name) (levelParams : List Name) (type : Expr) (numParams numIndices : Nat)\n (all ctors : List Name) (isRec isUnsafe isReflexive isNested : Bool) : InductiveVal := {\n name := name\n levelParams := levelParams\n type := type\n numParams := numParams\n numIndices := numIndices\n all := all\n ctors := ctors\n isRec := isRec\n isUnsafe := isUnsafe\n isReflexive := isReflexive\n isNested := isNested\n}\n\n@[export lean_inductive_val_is_rec] def InductiveVal.isRecEx (v : InductiveVal) : Bool := v.isRec\n@[export lean_inductive_val_is_unsafe] def InductiveVal.isUnsafeEx (v : InductiveVal) : Bool := v.isUnsafe\n@[export lean_inductive_val_is_reflexive] def InductiveVal.isReflexiveEx (v : InductiveVal) : Bool := v.isReflexive\n@[export lean_inductive_val_is_nested] def InductiveVal.isNestedEx (v : InductiveVal) : Bool := v.isNested\n\ndef InductiveVal.numCtors (v : InductiveVal) : Nat := v.ctors.length\n\nstructure ConstructorVal extends ConstantVal where\n /-- Inductive type this constructor is a member of -/\n induct : Name\n /-- Constructor index (i.e., Position in the inductive declaration) -/\n cidx : Nat\n /-- Number of parameters in inductive datatype. -/\n numParams : Nat\n /-- Number of fields (i.e., arity - nparams) -/\n numFields : Nat\n isUnsafe : Bool\n deriving Inhabited\n\n@[export lean_mk_constructor_val]\ndef mkConstructorValEx (name : Name) (levelParams : List Name) (type : Expr) (induct : Name) (cidx numParams numFields : Nat) (isUnsafe : Bool) : ConstructorVal := {\n name := name,\n levelParams := levelParams,\n type := type,\n induct := induct,\n cidx := cidx,\n numParams := numParams,\n numFields := numFields,\n isUnsafe := isUnsafe\n}\n\n@[export lean_constructor_val_is_unsafe] def ConstructorVal.isUnsafeEx (v : ConstructorVal) : Bool := v.isUnsafe\n\n/-- Information for reducing a recursor -/\nstructure RecursorRule where\n /-- Reduction rule for this Constructor -/\n ctor : Name\n /-- Number of fields (i.e., without counting inductive datatype parameters) -/\n nfields : Nat\n /-- Right hand side of the reduction rule -/\n rhs : Expr\n deriving Inhabited\n\nstructure RecursorVal extends ConstantVal where\n /-- List of all inductive datatypes in the mutual declaration that generated this recursor -/\n all : List Name\n /-- Number of parameters -/\n numParams : Nat\n /-- Number of indices -/\n numIndices : Nat\n /-- Number of motives -/\n numMotives : Nat\n /-- Number of minor premises -/\n numMinors : Nat\n /-- A reduction for each Constructor -/\n rules : List RecursorRule\n /-- It supports K-like reduction.\n A recursor is said to support K-like reduction if one can assume it behaves\n like `Eq` under axiom `K` --- that is, it has one constructor, the constructor has 0 arguments,\n and it is an inductive predicate (ie, it lives in Prop).\n\n Examples of inductives with K-like reduction is `Eq`, `Acc`, and `And.intro`.\n Non-examples are `exists` (where the constructor has arguments) and\n `Or.intro` (which has multiple constructors).\n -/\n k : Bool\n isUnsafe : Bool\n deriving Inhabited\n\n@[export lean_mk_recursor_val]\ndef mkRecursorValEx (name : Name) (levelParams : List Name) (type : Expr) (all : List Name) (numParams numIndices numMotives numMinors : Nat)\n (rules : List RecursorRule) (k isUnsafe : Bool) : RecursorVal := {\n name := name, levelParams := levelParams, type := type, all := all, numParams := numParams, numIndices := numIndices,\n numMotives := numMotives, numMinors := numMinors, rules := rules, k := k, isUnsafe := isUnsafe\n}\n\n@[export lean_recursor_k] def RecursorVal.kEx (v : RecursorVal) : Bool := v.k\n@[export lean_recursor_is_unsafe] def RecursorVal.isUnsafeEx (v : RecursorVal) : Bool := v.isUnsafe\n\ndef RecursorVal.getMajorIdx (v : RecursorVal) : Nat :=\n v.numParams + v.numMotives + v.numMinors + v.numIndices\n\ndef RecursorVal.getFirstIndexIdx (v : RecursorVal) : Nat :=\n v.numParams + v.numMotives + v.numMinors\n\ndef RecursorVal.getFirstMinorIdx (v : RecursorVal) : Nat :=\n v.numParams + v.numMotives\n\ndef RecursorVal.getInduct (v : RecursorVal) : Name :=\n v.name.getPrefix\n\ninductive QuotKind where\n | type -- `Quot`\n | ctor -- `Quot.mk`\n | lift -- `Quot.lift`\n | ind -- `Quot.ind`\n deriving Inhabited\n\nstructure QuotVal extends ConstantVal where\n kind : QuotKind\n deriving Inhabited\n\n@[export lean_mk_quot_val]\ndef mkQuotValEx (name : Name) (levelParams : List Name) (type : Expr) (kind : QuotKind) : QuotVal := {\n name := name, levelParams := levelParams, type := type, kind := kind\n}\n\n@[export lean_quot_val_kind] def QuotVal.kindEx (v : QuotVal) : QuotKind := v.kind\n\n/-- Information associated with constant declarations. -/\ninductive ConstantInfo where\n | axiomInfo (val : AxiomVal)\n | defnInfo (val : DefinitionVal)\n | thmInfo (val : TheoremVal)\n | opaqueInfo (val : OpaqueVal)\n | quotInfo (val : QuotVal)\n | inductInfo (val : InductiveVal)\n | ctorInfo (val : ConstructorVal)\n | recInfo (val : RecursorVal)\n deriving Inhabited\n\nnamespace ConstantInfo\n\ndef toConstantVal : ConstantInfo → ConstantVal\n | defnInfo {toConstantVal := d, ..} => d\n | axiomInfo {toConstantVal := d, ..} => d\n | thmInfo {toConstantVal := d, ..} => d\n | opaqueInfo {toConstantVal := d, ..} => d\n | quotInfo {toConstantVal := d, ..} => d\n | inductInfo {toConstantVal := d, ..} => d\n | ctorInfo {toConstantVal := d, ..} => d\n | recInfo {toConstantVal := d, ..} => d\n\ndef isUnsafe : ConstantInfo → Bool\n | defnInfo v => v.safety == .unsafe\n | axiomInfo v => v.isUnsafe\n | thmInfo _ => false\n | opaqueInfo v => v.isUnsafe\n | quotInfo _ => false\n | inductInfo v => v.isUnsafe\n | ctorInfo v => v.isUnsafe\n | recInfo v => v.isUnsafe\n\ndef isPartial : ConstantInfo → Bool\n | defnInfo v => v.safety == .partial\n | _ => false\n\ndef name (d : ConstantInfo) : Name :=\n d.toConstantVal.name\n\ndef levelParams (d : ConstantInfo) : List Name :=\n d.toConstantVal.levelParams\n\ndef numLevelParams (d : ConstantInfo) : Nat :=\n d.levelParams.length\n\ndef type (d : ConstantInfo) : Expr :=\n d.toConstantVal.type\n\ndef value? : ConstantInfo → Option Expr\n | defnInfo {value := r, ..} => some r\n | thmInfo {value := r, ..} => some r\n | _ => none\n\ndef hasValue : ConstantInfo → Bool\n | defnInfo _ => true\n | thmInfo _ => true\n | _ => false\n\ndef value! : ConstantInfo → Expr\n | defnInfo {value := r, ..} => r\n | thmInfo {value := r, ..} => r\n | _ => panic! \"declaration with value expected\"\n\ndef hints : ConstantInfo → ReducibilityHints\n | defnInfo {hints := r, ..} => r\n | _ => ReducibilityHints.opaque\n\ndef isCtor : ConstantInfo → Bool\n | ctorInfo _ => true\n | _ => false\n\ndef isInductive : ConstantInfo → Bool\n | inductInfo _ => true\n | _ => false\n\n/--\n List of all (including this one) declarations in the same mutual block.\n-/\ndef all : ConstantInfo → List Name\n | inductInfo val => val.all\n | defnInfo val => val.all\n | thmInfo val => val.all\n | opaqueInfo val => val.all\n | info => [info.name]\n\nend ConstantInfo\n\ndef mkRecName (declName : Name) : Name :=\n Name.mkStr declName \"rec\"\n\nend Lean\n", "meta": {"author": "leanprover", "repo": "lean4", "sha": "742d053a97bdd109a41a921facd1cd6a55e89bc7", "save_path": "github-repos/lean/leanprover-lean4", "path": "github-repos/lean/leanprover-lean4/lean4-742d053a97bdd109a41a921facd1cd6a55e89bc7/src/Lean/Declaration.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41111086923216794, "lm_q2_score": 0.06371499380749801, "lm_q1q2_score": 0.026193926487322706}} {"text": "/-\nCopyright (c) 2018 Scott Morrison. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Scott Morrison, Johannes Hölzl, Reid Barton, Sean Leather\n\nBundled type and structure.\n-/\nimport category_theory.functor\nimport category_theory.types\n\nuniverses u v\n\nnamespace category_theory\nvariables {c d : Type u → Type v} {α : Type u}\n\n/--\n`concrete_category @hom` collects the evidence that a type constructor `c` and a\nmorphism predicate `hom` can be thought of as a concrete category.\n\nIn a typical example, `c` is the type class `topological_space` and `hom` is\n`continuous`.\n-/\nstructure concrete_category (hom : out_param $ ∀ {α β}, c α → c β → (α → β) → Prop) :=\n(hom_id : ∀ {α} (ia : c α), hom ia ia id)\n(hom_comp : ∀ {α β γ} (ia : c α) (ib : c β) (ic : c γ) {f g}, hom ia ib f → hom ib ic g → hom ia ic (g ∘ f))\n\nattribute [class] concrete_category\n\n/-- `bundled` is a type bundled with a type class instance for that type. Only\nthe type class is exposed as a parameter. -/\nstructure bundled (c : Type u → Type v) : Type (max (u+1) v) :=\n(α : Type u)\n(str : c α)\n\ndef mk_ob {c : Type u → Type v} (α : Type u) [str : c α] : bundled c := ⟨α, str⟩\n\nnamespace bundled\n\ninstance : has_coe_to_sort (bundled c) :=\n{ S := Type u, coe := bundled.α }\n\n/-- Map over the bundled structure -/\ndef map (f : ∀ {α}, c α → d α) (b : bundled c) : bundled d :=\n⟨b.α, f b.str⟩\n\nsection concrete_category\nvariables (hom : ∀ {α β : Type u}, c α → c β → (α → β) → Prop)\nvariables [h : concrete_category @hom]\ninclude h\n\ninstance : category (bundled c) :=\n{ hom := λ a b, subtype (hom a.2 b.2),\n id := λ a, ⟨@id a.1, h.hom_id a.2⟩,\n comp := λ a b c f g, ⟨g.1 ∘ f.1, h.hom_comp a.2 b.2 c.2 f.2 g.2⟩ }\n\nvariables {X Y Z : bundled c}\n\n@[simp] lemma concrete_category_id (X : bundled c) : subtype.val (𝟙 X) = id :=\nrfl\n\n@[simp] lemma concrete_category_comp (f : X ⟶ Y) (g : Y ⟶ Z) :\n subtype.val (f ≫ g) = g.val ∘ f.val :=\nrfl\n\ninstance : has_coe_to_fun (X ⟶ Y) :=\n{ F := λ f, X → Y,\n coe := λ f, f.1 }\n\n@[simp] lemma bundled_hom_coe {X Y : bundled c} (val : X → Y) (prop) (x : X) :\n (⟨val, prop⟩ : X ⟶ Y) x = val x := rfl\n\nend concrete_category\n\nend bundled\n\ndef concrete_functor\n {C : Type u → Type v} {hC : ∀{α β}, C α → C β → (α → β) → Prop} [concrete_category @hC]\n {D : Type u → Type v} {hD : ∀{α β}, D α → D β → (α → β) → Prop} [concrete_category @hD]\n (m : ∀{α}, C α → D α) (h : ∀{α β} {ia : C α} {ib : C β} {f}, hC ia ib f → hD (m ia) (m ib) f) :\n bundled C ⥤ bundled D :=\n{ obj := bundled.map @m,\n map := λ X Y f, ⟨ f, h f.2 ⟩}\n\nsection forget\nvariables {C : Type u → Type v} {hom : ∀α β, C α → C β → (α → β) → Prop} [i : concrete_category hom]\ninclude i\n\n/-- The forgetful functor from a bundled category to `Type`. -/\ndef forget : bundled C ⥤ Type u := { obj := bundled.α, map := λa b h, h.1 }\n\ninstance forget.faithful : faithful (forget : bundled C ⥤ Type u) := {}\n\nend forget\n\nend category_theory\n", "meta": {"author": "digama0", "repo": "mathlib-ITP2019", "sha": "5cbd0362e04e671ef5db1284870592af6950197c", "save_path": "github-repos/lean/digama0-mathlib-ITP2019", "path": "github-repos/lean/digama0-mathlib-ITP2019/mathlib-ITP2019-5cbd0362e04e671ef5db1284870592af6950197c/src/category_theory/concrete_category.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4339814794452761, "lm_q2_score": 0.06008664470385729, "lm_q1q2_score": 0.026076490963482652}} {"text": "/-\nCopyright (c) 2020 Adam Topaz. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Adam Topaz\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.default\nimport Mathlib.category_theory.monad.basic\nimport Mathlib.category_theory.eq_to_hom\nimport Mathlib.PostPort\n\nuniverses v u l \n\nnamespace Mathlib\n\n/-!\n# Bundled Monads\n\nWe define bundled (co)monads as a structure consisting of a functor `func : C ⥤ C` endowed with\na term of type `(co)monad func`. See `category_theory.monad.basic` for the definition.\nThe type of bundled (co)monads on a category `C` is denoted `(Co)Monad C`.\n\nWe also define morphisms of bundled (co)monads as morphisms of their underlying (co)monads\nin the sense of `category_theory.(co)monad_hom`. We construct a category instance on `(Co)Monad C`.\n-/\n\nnamespace category_theory\n\n\n/-- Bundled monads. -/\nstructure Monad (C : Type u) [category C] \nwhere\n func : C ⥤ C\n str : autoParam (monad func)\n (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring \"Mathlib.tactic.apply_instance\")\n (Lean.Name.mkStr (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous \"Mathlib\") \"tactic\") \"apply_instance\") [])\n\n/-- Bundled comonads -/\nstructure Comonad (C : Type u) [category C] \nwhere\n func : C ⥤ C\n str : autoParam (comonad func)\n (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring \"Mathlib.tactic.apply_instance\")\n (Lean.Name.mkStr (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous \"Mathlib\") \"tactic\") \"apply_instance\") [])\n\nnamespace Monad\n\n\n/-- The initial monad. TODO: Prove it's initial. -/\ndef initial (C : Type u) [category C] : Monad C :=\n mk 𝟭\n\nprotected instance inhabited {C : Type u} [category C] : Inhabited (Monad C) :=\n { default := initial C }\n\nprotected instance func.category_theory.monad {C : Type u} [category C] {M : Monad C} : monad (func M) :=\n str M\n\n/-- Morphisms of bundled monads. -/\ndef hom {C : Type u} [category C] (M : Monad C) (N : Monad C) :=\n monad_hom (func M) (func N)\n\nnamespace hom\n\n\nend hom\n\n\nprotected instance hom.inhabited {C : Type u} [category C] {M : Monad C} : Inhabited (hom M M) :=\n { default := monad_hom.id (func M) }\n\nprotected instance category_theory.category {C : Type u} [category C] : category (Monad C) :=\n category.mk\n\n/-- The forgetful functor from `Monad C` to `C ⥤ C`. -/\ndef forget (C : Type u) [category C] : Monad C ⥤ C ⥤ C :=\n functor.mk func fun (_x _x_1 : Monad C) (f : _x ⟶ _x_1) => monad_hom.to_nat_trans f\n\n@[simp] theorem comp_to_nat_trans {C : Type u} [category C] {M : Monad C} {N : Monad C} {L : Monad C} (f : M ⟶ N) (g : N ⟶ L) : monad_hom.to_nat_trans (f ≫ g) = nat_trans.vcomp (monad_hom.to_nat_trans f) (monad_hom.to_nat_trans g) :=\n rfl\n\n@[simp] theorem assoc_func_app {C : Type u} [category C] {M : Monad C} {X : C} : functor.map (func M) (nat_trans.app μ_ X) ≫ nat_trans.app μ_ X =\n nat_trans.app μ_ (functor.obj (func M) X) ≫ nat_trans.app μ_ X :=\n monad.assoc X\n\nend Monad\n\n\nnamespace Comonad\n\n\n/-- The terminal comonad. TODO: Prove it's terminal. -/\ndef terminal (C : Type u) [category C] : Comonad C :=\n mk 𝟭\n\nprotected instance inhabited {C : Type u} [category C] : Inhabited (Comonad C) :=\n { default := terminal C }\n\nprotected instance func.category_theory.comonad {C : Type u} [category C] {M : Comonad C} : comonad (func M) :=\n str M\n\n/-- Morphisms of bundled comonads. -/\ndef hom {C : Type u} [category C] (M : Comonad C) (N : Comonad C) :=\n comonad_hom (func M) (func N)\n\nnamespace hom\n\n\nend hom\n\n\nprotected instance hom.inhabited {C : Type u} [category C] {M : Comonad C} : Inhabited (hom M M) :=\n { default := comonad_hom.id (func M) }\n\nprotected instance category_theory.category {C : Type u} [category C] : category (Comonad C) :=\n category.mk\n\n/-- The forgetful functor from `CoMonad C` to `C ⥤ C`. -/\ndef forget (C : Type u) [category C] : Comonad C ⥤ C ⥤ C :=\n functor.mk func fun (_x _x_1 : Comonad C) (f : _x ⟶ _x_1) => comonad_hom.to_nat_trans f\n\n@[simp] theorem comp_to_nat_trans {C : Type u} [category C] {M : Comonad C} {N : Comonad C} {L : Comonad C} (f : M ⟶ N) (g : N ⟶ L) : comonad_hom.to_nat_trans (f ≫ g) = nat_trans.vcomp (comonad_hom.to_nat_trans f) (comonad_hom.to_nat_trans g) :=\n rfl\n\n@[simp] theorem coassoc_func_app {C : Type u} [category C] {M : Comonad C} {X : C} : nat_trans.app δ_ X ≫ functor.map (func M) (nat_trans.app δ_ X) =\n nat_trans.app δ_ X ≫ nat_trans.app δ_ (functor.obj (func M) X) :=\n comonad.coassoc X\n\n", "meta": {"author": "AurelienSaue", "repo": "Mathlib4_auto", "sha": "590df64109b08190abe22358fabc3eae000943f2", "save_path": "github-repos/lean/AurelienSaue-Mathlib4_auto", "path": "github-repos/lean/AurelienSaue-Mathlib4_auto/Mathlib4_auto-590df64109b08190abe22358fabc3eae000943f2/Mathlib/category_theory/monad/bundled.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4148988457967688, "lm_q2_score": 0.06278920508951337, "lm_q1q2_score": 0.026051168720135697}} {"text": "-- Copyright (c) 2018 Scott Morrison. All rights reserved.\n-- Released under Apache 2.0 license as described in the file LICENSE.\n-- Authors: Scott Morrison, Mario Carneiro\n\nimport tactic\nimport data.option.defs\n\nopen interactive\n\nnamespace tactic\n\n/-\nThis file defines a `chain` tactic, which takes a list of tactics, and exhaustively tries to apply them\nto the goals, until no tactic succeeds on any goal.\n\nAlong the way, it generates auxiliary declarations, in order to speed up elaboration time\nof the resulting (sometimes long!) proofs.\n\nThis tactic is used by the `tidy` tactic.\n-/\n\n-- α is the return type of our tactics. When `chain` is called by `tidy`, this is string,\n-- describing what that tactic did as an interactive tactic.\nvariable {α : Type}\n\n/-\nBecause chain sometimes pauses work on the first goal and works on later goals, we need a method\nfor combining a list of results generated while working on a later goal into a single result.\nThis enables `tidy {trace_result := tt}` to output faithfully reproduces its operation, e.g.\n````\nintros,\nsimp,\napply lemma_1,\nwork_on_goal 2 {\n dsimp,\n simp\n},\nrefl\n````\n-/\n\nnamespace interactive\nopen lean.parser\nmeta def work_on_goal : parse small_nat → itactic → tactic unit\n| n t := do goals ← get_goals,\n let earlier_goals := goals.take n,\n let later_goals := goals.drop (n+1),\n set_goals (goals.nth n).to_list,\n t,\n new_goals ← get_goals,\n set_goals (earlier_goals ++ new_goals ++ later_goals)\nend interactive\n\ninductive tactic_script (α : Type) : Type\n| base : α → tactic_script\n| work (index : ℕ) (first : α) (later : list tactic_script) (closed : bool) : tactic_script\n\nmeta def tactic_script.to_string : tactic_script string → string\n| (tactic_script.base a) := a\n| (tactic_script.work n a l c) := \"work_on_goal \" ++ (to_string n) ++ \" { \" ++ (\", \".intercalate (a :: l.map tactic_script.to_string)) ++ \" }\"\n\nmeta instance : has_to_string (tactic_script string) :=\n{ to_string := λ s, s.to_string }\n\nmeta instance tactic_script_unit_has_to_string : has_to_string (tactic_script unit) :=\n{ to_string := λ s, \"[chain tactic]\" }\n\nmeta def abstract_if_success (tac : expr → tactic α) (g : expr) : tactic α :=\ndo\n type ← infer_type g,\n is_lemma ← is_prop type,\n if is_lemma then -- there's no point making the abstraction, and indeed it's slower\n tac g\n else do\n m ← mk_meta_var type,\n a ← tac m,\n do {\n val ← instantiate_mvars m,\n guard (val.list_meta_vars = []),\n c ← new_aux_decl_name,\n gs ← get_goals,\n set_goals [g],\n add_aux_decl c type val ff >>= unify g,\n set_goals gs }\n <|> unify m g,\n return a\n\n/--\n`chain_many tac` recursively tries `tac` on all goals, working depth-first on generated subgoals,\nuntil it no longer succeeds on any goal. `chain_many` automatically makes auxiliary definitions.\n-/\nmeta mutual def chain_single, chain_many, chain_iter {α} (tac : tactic α)\nwith chain_single : expr → tactic (α × list (tactic_script α)) | g :=\ndo set_goals [g],\n a ← tac,\n l ← get_goals >>= chain_many,\n return (a, l)\nwith chain_many : list expr → tactic (list (tactic_script α))\n| [] := return []\n| [g] := do {\n (a, l) ← chain_single g,\n return (tactic_script.base a :: l) } <|> return []\n| gs := chain_iter gs []\nwith chain_iter : list expr → list expr → tactic (list (tactic_script α))\n| [] _ := return []\n| (g :: later_goals) stuck_goals := do {\n (a, l) ← abstract_if_success chain_single g,\n new_goals ← get_goals,\n let w := tactic_script.work stuck_goals.length a l (new_goals = []),\n let current_goals := stuck_goals.reverse ++ new_goals ++ later_goals,\n set_goals current_goals, -- we keep the goals up to date, so they are correct at the end\n l' ← chain_many current_goals,\n return (w :: l') } <|> chain_iter later_goals (g :: stuck_goals)\n\nmeta def chain_core {α : Type} [has_to_string (tactic_script α)] (tactics : list (tactic α)) : tactic (list string) :=\ndo results ← (get_goals >>= chain_many (first tactics)),\n when results.empty (fail \"`chain` tactic made no progress\"),\n return (results.map to_string)\n\nvariables [has_to_string (tactic_script α)] [has_to_format α]\n\ndeclare_trace chain\n\nmeta def trace_output (t : tactic α) : tactic α :=\ndo tgt ← target,\n r ← t,\n name ← decl_name,\n trace format!\"`chain` successfully applied a tactic during elaboration of {name}:\",\n tgt ← pp tgt,\n trace format!\"previous target: {tgt}\",\n trace format!\"tactic result: {r}\",\n tgt ← try_core target,\n tgt ← match tgt with\n | (some tgt) := pp tgt\n | none := return \"no goals\"\n end,\n trace format!\"new target: {tgt}\",\n pure r\n\nmeta def chain (tactics : list (tactic α)) : tactic (list string) :=\nif is_trace_enabled_for `chain then\n chain_core (tactics.map trace_output)\nelse\n chain_core tactics\n\nend tactic\n", "meta": {"author": "digama0", "repo": "mathlib-ITP2019", "sha": "5cbd0362e04e671ef5db1284870592af6950197c", "save_path": "github-repos/lean/digama0-mathlib-ITP2019", "path": "github-repos/lean/digama0-mathlib-ITP2019/mathlib-ITP2019-5cbd0362e04e671ef5db1284870592af6950197c/src/tactic/chain.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4378234844434674, "lm_q2_score": 0.05921025323146657, "lm_q1q2_score": 0.025923639384580772}} {"text": "/-\nCopyright (c) 2018 Simon Hudon. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthor: Simon Hudon\n\nInstances of `traversable` for types from the core library\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.default\nimport Mathlib.data.list.forall2\nimport Mathlib.data.set.lattice\nimport Mathlib.control.traversable.lemmas\nimport Mathlib.PostPort\n\nuniverses u_1 u \n\nnamespace Mathlib\n\ntheorem option.id_traverse {α : Type u_1} (x : Option α) : option.traverse id.mk x = x :=\n option.cases_on x (Eq.refl (option.traverse id.mk none))\n fun (x : α) => Eq.refl (option.traverse id.mk (some x))\n\ntheorem option.comp_traverse {F : Type u → Type u} {G : Type u → Type u} [Applicative F]\n [Applicative G] [is_lawful_applicative F] [is_lawful_applicative G] {α : Type u_1} {β : Type u}\n {γ : Type u} (f : β → F γ) (g : α → G β) (x : Option α) :\n option.traverse (functor.comp.mk ∘ Functor.map f ∘ g) x =\n functor.comp.mk (option.traverse f <$> option.traverse g x) :=\n sorry\n\ntheorem option.traverse_eq_map_id {α : Type u_1} {β : Type u_1} (f : α → β) (x : Option α) :\n traverse (id.mk ∘ f) x = id.mk (f <$> x) :=\n option.cases_on x (Eq.refl (traverse (id.mk ∘ f) none))\n fun (x : α) => Eq.refl (traverse (id.mk ∘ f) (some x))\n\ntheorem option.naturality {F : Type u → Type u} {G : Type u → Type u} [Applicative F]\n [Applicative G] [is_lawful_applicative F] [is_lawful_applicative G]\n (η : applicative_transformation F G) {α : Type u_1} {β : Type u} (f : α → F β) (x : Option α) :\n coe_fn η (Option β) (option.traverse f x) = option.traverse (coe_fn η β ∘ f) x :=\n sorry\n\nprotected instance option.is_lawful_traversable : is_lawful_traversable Option :=\n is_lawful_traversable.mk option.id_traverse option.comp_traverse option.traverse_eq_map_id\n option.naturality\n\nnamespace list\n\n\nprotected theorem id_traverse {α : Type u_1} (xs : List α) : list.traverse id.mk xs = xs := sorry\n\nprotected theorem comp_traverse {F : Type u → Type u} {G : Type u → Type u} [Applicative F]\n [Applicative G] [is_lawful_applicative F] [is_lawful_applicative G] {α : Type u_1} {β : Type u}\n {γ : Type u} (f : β → F γ) (g : α → G β) (x : List α) :\n list.traverse (functor.comp.mk ∘ Functor.map f ∘ g) x =\n functor.comp.mk (list.traverse f <$> list.traverse g x) :=\n sorry\n\nprotected theorem traverse_eq_map_id {α : Type u_1} {β : Type u_1} (f : α → β) (x : List α) :\n list.traverse (id.mk ∘ f) x = id.mk (f <$> x) :=\n sorry\n\nprotected theorem naturality {F : Type u → Type u} {G : Type u → Type u} [Applicative F]\n [Applicative G] [is_lawful_applicative F] [is_lawful_applicative G]\n (η : applicative_transformation F G) {α : Type u_1} {β : Type u} (f : α → F β) (x : List α) :\n coe_fn η (List β) (list.traverse f x) = list.traverse (coe_fn η β ∘ f) x :=\n sorry\n\nprotected instance is_lawful_traversable : is_lawful_traversable List :=\n is_lawful_traversable.mk list.id_traverse list.comp_traverse list.traverse_eq_map_id\n list.naturality\n\n@[simp] theorem traverse_nil {F : Type u → Type u} [Applicative F] {α' : Type u} {β' : Type u}\n (f : α' → F β') : traverse f [] = pure [] :=\n rfl\n\n@[simp] theorem traverse_cons {F : Type u → Type u} [Applicative F] {α' : Type u} {β' : Type u}\n (f : α' → F β') (a : α') (l : List α') :\n traverse f (a :: l) = (fun (_x : β') (_y : List β') => _x :: _y) <$> f a <*> traverse f l :=\n rfl\n\n@[simp] theorem traverse_append {F : Type u → Type u} [Applicative F] {α' : Type u} {β' : Type u}\n (f : α' → F β') [is_lawful_applicative F] (as : List α') (bs : List α') :\n traverse f (as ++ bs) = append <$> traverse f as <*> traverse f bs :=\n sorry\n\ntheorem mem_traverse {α' : Type u} {β' : Type u} {f : α' → set β'} (l : List α') (n : List β') :\n n ∈ traverse f l ↔ forall₂ (fun (b : β') (a : α') => b ∈ f a) n l :=\n sorry\n\nend list\n\n\nnamespace sum\n\n\nprotected theorem traverse_map {σ : Type u} {G : Type u → Type u} [Applicative G] {α : Type u}\n {β : Type u} {γ : Type u} (g : α → β) (f : β → G γ) (x : σ ⊕ α) :\n sum.traverse f (g <$> x) = sum.traverse (f ∘ g) x :=\n sorry\n\nprotected theorem id_traverse {σ : Type u_1} {α : Type u_1} (x : σ ⊕ α) :\n sum.traverse id.mk x = x :=\n sum.cases_on x (fun (x : σ) => Eq.refl (sum.traverse id.mk (inl x)))\n fun (x : α) => Eq.refl (sum.traverse id.mk (inr x))\n\nprotected theorem comp_traverse {σ : Type u} {F : Type u → Type u} {G : Type u → Type u}\n [Applicative F] [Applicative G] [is_lawful_applicative F] [is_lawful_applicative G]\n {α : Type u_1} {β : Type u} {γ : Type u} (f : β → F γ) (g : α → G β) (x : σ ⊕ α) :\n sum.traverse (functor.comp.mk ∘ Functor.map f ∘ g) x =\n functor.comp.mk (sum.traverse f <$> sum.traverse g x) :=\n sorry\n\nprotected theorem traverse_eq_map_id {σ : Type u} {α : Type u} {β : Type u} (f : α → β)\n (x : σ ⊕ α) : sum.traverse (id.mk ∘ f) x = id.mk (f <$> x) :=\n sorry\n\nprotected theorem map_traverse {σ : Type u} {G : Type u → Type u} [Applicative G]\n [is_lawful_applicative G] {α : Type u_1} {β : Type u} {γ : Type u} (g : α → G β) (f : β → γ)\n (x : σ ⊕ α) : Functor.map f <$> sum.traverse g x = sum.traverse (Functor.map f ∘ g) x :=\n sorry\n\nprotected theorem naturality {σ : Type u} {F : Type u → Type u} {G : Type u → Type u}\n [Applicative F] [Applicative G] [is_lawful_applicative F] [is_lawful_applicative G]\n (η : applicative_transformation F G) {α : Type u_1} {β : Type u} (f : α → F β) (x : σ ⊕ α) :\n coe_fn η (σ ⊕ β) (sum.traverse f x) = sum.traverse (coe_fn η β ∘ f) x :=\n sorry\n\nprotected instance is_lawful_traversable {σ : Type u} : is_lawful_traversable (sum σ) :=\n is_lawful_traversable.mk sum.id_traverse sum.comp_traverse sum.traverse_eq_map_id sum.naturality\n\nend Mathlib", "meta": {"author": "AurelienSaue", "repo": "Mathlib4_auto", "sha": "590df64109b08190abe22358fabc3eae000943f2", "save_path": "github-repos/lean/AurelienSaue-Mathlib4_auto", "path": "github-repos/lean/AurelienSaue-Mathlib4_auto/Mathlib4_auto-590df64109b08190abe22358fabc3eae000943f2/Mathlib/control/traversable/instances_auto.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42250463481418826, "lm_q2_score": 0.06097518086496481, "lm_q1q2_score": 0.02576229652408104}} {"text": "/-\nCopyright (c) 2017 Simon Hudon. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Simon Hudon\n-/\nimport algebra.group.defs\nimport control.functor\n\n/-!\n# `applicative` instances\n\nThis file provides `applicative` instances for concrete functors:\n* `id`\n* `functor.comp`\n* `functor.const`\n* `functor.add_const`\n-/\n\nuniverses u v w\n\nsection lemmas\n\nopen function\n\nvariables {F : Type u → Type v}\nvariables [applicative F] [is_lawful_applicative F]\nvariables {α β γ σ : Type u}\n\nlemma applicative.map_seq_map (f : α → β → γ) (g : σ → β) (x : F α) (y : F σ) :\n (f <$> x) <*> (g <$> y) = (flip (∘) g ∘ f) <$> x <*> y :=\nby simp [flip] with functor_norm\n\nlemma applicative.pure_seq_eq_map' (f : α → β) : (<*>) (pure f : F (α → β)) = (<$>) f :=\nby ext; simp with functor_norm\n\ntheorem applicative.ext {F} : ∀ {A1 : applicative F} {A2 : applicative F}\n [@is_lawful_applicative F A1] [@is_lawful_applicative F A2]\n (H1 : ∀ {α : Type u} (x : α),\n @has_pure.pure _ A1.to_has_pure _ x = @has_pure.pure _ A2.to_has_pure _ x)\n (H2 : ∀ {α β : Type u} (f : F (α → β)) (x : F α),\n @has_seq.seq _ A1.to_has_seq _ _ f x = @has_seq.seq _ A2.to_has_seq _ _ f x),\n A1 = A2\n| {to_functor := F1, seq := s1, pure := p1, seq_left := sl1, seq_right := sr1}\n {to_functor := F2, seq := s2, pure := p2, seq_left := sl2, seq_right := sr2} L1 L2 H1 H2 :=\nbegin\n obtain rfl : @p1 = @p2, {funext α x, apply H1},\n obtain rfl : @s1 = @s2, {funext α β f x, apply H2},\n cases L1, cases L2,\n obtain rfl : F1 = F2,\n { resetI, apply functor.ext, intros,\n exact (L1_pure_seq_eq_map _ _).symm.trans (L2_pure_seq_eq_map _ _) },\n congr; funext α β x y,\n { exact (L1_seq_left_eq _ _).trans (L2_seq_left_eq _ _).symm },\n { exact (L1_seq_right_eq _ _).trans (L2_seq_right_eq _ _).symm }\nend\n\nend lemmas\n\ninstance : is_comm_applicative id :=\nby refine { .. }; intros; refl\n\nnamespace functor\nnamespace comp\n\nopen function (hiding comp)\nopen functor\n\nvariables {F : Type u → Type w} {G : Type v → Type u}\n\nvariables [applicative F] [applicative G]\n\nvariables [is_lawful_applicative F] [is_lawful_applicative G]\nvariables {α β γ : Type v}\n\nlemma map_pure (f : α → β) (x : α) : (f <$> pure x : comp F G β) = pure (f x) :=\ncomp.ext $ by simp\n\nlemma seq_pure (f : comp F G (α → β)) (x : α) :\n f <*> pure x = (λ g : α → β, g x) <$> f :=\ncomp.ext $ by simp [(∘)] with functor_norm\n\n\n\nlemma pure_seq_eq_map (f : α → β) (x : comp F G α) :\n pure f <*> x = f <$> x :=\ncomp.ext $ by simp [applicative.pure_seq_eq_map'] with functor_norm\n\ninstance : is_lawful_applicative (comp F G) :=\n{ pure_seq_eq_map := @comp.pure_seq_eq_map F G _ _ _ _,\n map_pure := @comp.map_pure F G _ _ _ _,\n seq_pure := @comp.seq_pure F G _ _ _ _,\n seq_assoc := @comp.seq_assoc F G _ _ _ _ }\n\ntheorem applicative_id_comp {F} [AF : applicative F] [LF : is_lawful_applicative F] :\n @comp.applicative id F _ _ = AF :=\n@applicative.ext F _ _ (@comp.is_lawful_applicative id F _ _ _ _) _\n (λ α x, rfl) (λ α β f x, rfl)\n\ntheorem applicative_comp_id {F} [AF : applicative F] [LF : is_lawful_applicative F] :\n @comp.applicative F id _ _ = AF :=\n@applicative.ext F _ _ (@comp.is_lawful_applicative F id _ _ _ _) _\n (λ α x, rfl) (λ α β f x, show id <$> f <*> x = f <*> x, by rw id_map)\n\nopen is_comm_applicative\n\ninstance {f : Type u → Type w} {g : Type v → Type u}\n [applicative f] [applicative g]\n [is_comm_applicative f] [is_comm_applicative g] :\n is_comm_applicative (comp f g) :=\nby { refine { .. @comp.is_lawful_applicative f g _ _ _ _, .. },\n intros, casesm* comp _ _ _, simp! [map,has_seq.seq] with functor_norm,\n rw [commutative_map],\n simp [comp.mk,flip,(∘)] with functor_norm,\n congr, funext, rw [commutative_map], congr }\n\nend comp\nend functor\n\nopen functor\n\n@[functor_norm]\nlemma comp.seq_mk {α β : Type w}\n {f : Type u → Type v} {g : Type w → Type u}\n [applicative f] [applicative g]\n (h : f (g (α → β))) (x : f (g α)) :\n comp.mk h <*> comp.mk x = comp.mk (has_seq.seq <$> h <*> x) := rfl\n\ninstance {α} [has_one α] [has_mul α] : applicative (const α) :=\n{ pure := λ β x, (1 : α),\n seq := λ β γ f x, (f * x : α) }\n\ninstance {α} [monoid α] : is_lawful_applicative (const α) :=\nby refine { .. }; intros; simp [mul_assoc, (<$>), (<*>), pure]\n\ninstance {α} [has_zero α] [has_add α] : applicative (add_const α) :=\n{ pure := λ β x, (0 : α),\n seq := λ β γ f x, (f + x : α) }\n\ninstance {α} [add_monoid α] : is_lawful_applicative (add_const α) :=\nby refine { .. }; intros; simp [add_assoc, (<$>), (<*>), pure]\n", "meta": {"author": "nick-kuhn", "repo": "leantools", "sha": "567a98c031fffe3f270b7b8dea48389bc70d7abb", "save_path": "github-repos/lean/nick-kuhn-leantools", "path": "github-repos/lean/nick-kuhn-leantools/leantools-567a98c031fffe3f270b7b8dea48389bc70d7abb/src/control/applicative.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3923368301671084, "lm_q2_score": 0.06560484156961123, "lm_q1q2_score": 0.025739195585036616}} {"text": "/-\nCopyright (c) 2018 Scott Morrison. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Scott Morrison, Mario Carneiro\n-/\nimport tactic.ext\n\nopen interactive\n\nnamespace tactic\n\n/-\nThis file defines a `chain` tactic, which takes a list of tactics,\nand exhaustively tries to apply them to the goals, until no tactic succeeds on any goal.\n\nAlong the way, it generates auxiliary declarations, in order to speed up elaboration time\nof the resulting (sometimes long!) proofs.\n\nThis tactic is used by the `tidy` tactic.\n-/\n\n-- α is the return type of our tactics. When `chain` is called by `tidy`, this is string,\n-- describing what that tactic did as an interactive tactic.\nvariable {α : Type}\n\ninductive tactic_script (α : Type) : Type\n| base : α → tactic_script\n| work (index : ℕ) (first : α) (later : list tactic_script) (closed : bool) : tactic_script\n\nmeta def tactic_script.to_string : tactic_script string → string\n| (tactic_script.base a) := a\n| (tactic_script.work n a l c) := \"work_on_goal \" ++ (to_string n) ++\n \" { \" ++ (\", \".intercalate (a :: l.map tactic_script.to_string)) ++ \" }\"\n\nmeta instance : has_to_string (tactic_script string) :=\n{ to_string := λ s, s.to_string }\n\nmeta instance tactic_script_unit_has_to_string : has_to_string (tactic_script unit) :=\n{ to_string := λ s, \"[chain tactic]\" }\n\nmeta def abstract_if_success (tac : expr → tactic α) (g : expr) : tactic α :=\ndo\n type ← infer_type g,\n is_lemma ← is_prop type,\n if is_lemma then -- there's no point making the abstraction, and indeed it's slower\n tac g\n else do\n m ← mk_meta_var type,\n a ← tac m,\n do {\n val ← instantiate_mvars m,\n guard (val.list_meta_vars = []),\n c ← new_aux_decl_name,\n gs ← get_goals,\n set_goals [g],\n add_aux_decl c type val ff >>= unify g,\n set_goals gs }\n <|> unify m g,\n return a\n\n/--\n`chain_many tac` recursively tries `tac` on all goals, working depth-first on generated subgoals,\nuntil it no longer succeeds on any goal. `chain_many` automatically makes auxiliary definitions.\n-/\nmeta mutual def chain_single, chain_many, chain_iter {α} (tac : tactic α)\nwith chain_single : expr → tactic (α × list (tactic_script α)) | g :=\ndo set_goals [g],\n a ← tac,\n l ← get_goals >>= chain_many,\n return (a, l)\nwith chain_many : list expr → tactic (list (tactic_script α))\n| [] := return []\n| [g] := do {\n (a, l) ← chain_single g,\n return (tactic_script.base a :: l) } <|> return []\n| gs := chain_iter gs []\nwith chain_iter : list expr → list expr → tactic (list (tactic_script α))\n| [] _ := return []\n| (g :: later_goals) stuck_goals := do {\n (a, l) ← abstract_if_success chain_single g,\n new_goals ← get_goals,\n let w := tactic_script.work stuck_goals.length a l (new_goals = []),\n let current_goals := stuck_goals.reverse ++ new_goals ++ later_goals,\n set_goals current_goals, -- we keep the goals up to date, so they are correct at the end\n l' ← chain_many current_goals,\n return (w :: l') } <|> chain_iter later_goals (g :: stuck_goals)\n\nmeta def chain_core {α : Type} [has_to_string (tactic_script α)] (tactics : list (tactic α)) :\n tactic (list string) :=\ndo results ← (get_goals >>= chain_many (first tactics)),\n when results.empty (fail \"`chain` tactic made no progress\"),\n return (results.map to_string)\n\nvariables [has_to_string (tactic_script α)] [has_to_format α]\n\ndeclare_trace chain\n\nmeta def trace_output (t : tactic α) : tactic α :=\ndo tgt ← target,\n r ← t,\n name ← decl_name,\n trace format!\"`chain` successfully applied a tactic during elaboration of {name}:\",\n tgt ← pp tgt,\n trace format!\"previous target: {tgt}\",\n trace format!\"tactic result: {r}\",\n tgt ← try_core target,\n tgt ← match tgt with\n | (some tgt) := pp tgt\n | none := return \"no goals\"\n end,\n trace format!\"new target: {tgt}\",\n pure r\n\nmeta def chain (tactics : list (tactic α)) : tactic (list string) :=\nchain_core\n (if is_trace_enabled_for `chain then (tactics.map trace_output) else tactics)\n\nend tactic\n", "meta": {"author": "JLimperg", "repo": "aesop3", "sha": "a4a116f650cc7403428e72bd2e2c4cda300fe03f", "save_path": "github-repos/lean/JLimperg-aesop3", "path": "github-repos/lean/JLimperg-aesop3/aesop3-a4a116f650cc7403428e72bd2e2c4cda300fe03f/src/tactic/chain.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.39233683016710835, "lm_q2_score": 0.06560483471870814, "lm_q1q2_score": 0.02573919289717501}} {"text": "import data.buffer data.dlist\n\ninstance (α : Type) [has_to_string α] : has_to_string (buffer α) :=\n⟨ fun b, to_string $ b.to_list ⟩\n\nuniverses u v\n\ninductive parse_result (α : Type u)\n| done (pos : ℕ) (result : α) : parse_result\n| fail (pos : ℕ) (expected : dlist string) : parse_result\n\ndef parser (elem : Type v) (α : Type u) :=\n∀ (input : buffer elem) (start : ℕ), parse_result α\n\n-- todo: refactor into parser core\nnamespace parser\n\n-- Type polymorphism is restricted here because of monad.bind\nvariables {elem α β γ : Type}\n\nprotected def bind (p : parser elem α) (f : α → parser elem β) : parser elem β :=\nλ input pos, match p input pos with\n| parse_result.done pos a := f a input pos\n| parse_result.fail ._ pos expected := parse_result.fail β pos expected\nend\n\nprotected def pure (a : α) : parser elem α :=\nλ input pos, parse_result.done pos a\n\nprivate lemma id_map (p : parser elem α) : parser.bind p parser.pure = p :=\nbegin\napply funext, intro input,\napply funext, intro pos,\ndunfold parser.bind,\ncases (p input pos); exact rfl\nend\n\nprivate lemma bind_assoc (p : parser elem α) (q : α → parser elem β) (r : β → parser elem γ) :\n parser.bind (parser.bind p q) r = parser.bind p (λ a, parser.bind (q a) r) :=\nbegin\napply funext, intro input,\napply funext, intro pos,\ndunfold parser.bind,\ncases (p input pos); try {dunfold bind},\ncases (q result input pos_1); try {dunfold bind},\nall_goals {refl}\nend\n\nprotected def fail (msg : string) : parser elem α :=\nλ _ pos, parse_result.fail α pos (dlist.singleton msg)\n\ninstance : monad_fail (parser elem) :=\n{ pure := @parser.pure elem,\n bind := @parser.bind elem,\n fail := @parser.fail elem,\n id_map := @id_map elem,\n pure_bind := λ _ _ _ _, rfl,\n bind_assoc := @bind_assoc elem }\n\nprotected def failure : parser elem α :=\nλ _ pos, parse_result.fail α pos dlist.empty\n\nprotected def orelse (p q : parser elem α) : parser elem α :=\nλ input pos, match p input pos with\n| parse_result.fail ._ pos₁ expected₁ :=\n if pos₁ ≠ pos then parse_result.fail _ pos₁ expected₁ else\n match q input pos with\n | parse_result.fail ._ pos₂ expected₂ :=\n if pos₁ < pos₂ then\n parse_result.fail _ pos₁ expected₁\n else if pos₂ < pos₁ then\n parse_result.fail _ pos₂ expected₂\n else -- pos₁ = pos₂\n parse_result.fail _ pos₁ (expected₁ ++ expected₂)\n | ok := ok\n end\n | ok := ok\nend\n\ninstance : alternative (parser elem) :=\n{ parser.monad_fail with\n failure := @parser.failure elem,\n orelse := @parser.orelse elem }\n\ninstance : inhabited (parser elem α) :=\n⟨parser.failure⟩\n\n/-- Overrides the expected token name, and does not consume input on failure. -/\ndef decorate_errors (msgs : thunk (list string)) (p : parser elem α) : parser elem α :=\nλ input pos, match p input pos with\n| parse_result.fail ._ _ expected :=\n parse_result.fail _ pos (dlist.lazy_of_list (msgs ()))\n| ok := ok\nend\n\n/-- Overrides the expected token name, and does not consume input on failure. -/\ndef decorate_error (msg : thunk string) (p : parser elem α) : parser elem α :=\ndecorate_errors [msg ()] p\n\n/-- Matches a single character satisfying the given predicate. -/\ndef sat (p : elem → Prop) [decidable_pred p] : parser elem elem :=\nλ input pos,\nif h : pos < input.size then\n let c := input.read ⟨pos, h⟩ in\n if p c then\n parse_result.done (pos+1) $ input.read ⟨pos, h⟩\n else\n parse_result.fail _ pos dlist.empty\nelse\n parse_result.fail _ pos dlist.empty\n\n/-- Matches the empty word. -/\ndef eps : parser elem unit := return ()\n\n/-- Matches the given character. -/\ndef el [decidable_eq elem] [has_to_string elem] (e : elem) : parser elem unit :=\ndecorate_error (to_string e) $ sat (= e) >> eps\n\n/-- Matches a whole char_buffer. Does not consume input in case of failure. -/\ndef buf [decidable_eq elem] [has_to_string elem] (buf : buffer elem) : parser elem unit :=\ndecorate_error (to_string buf) $ buf.to_list.mmap' el\n\n/-- Matches one out of a list of characters. -/\ndef one_of [decidable_eq elem] [has_to_string elem] (cs : list elem) : parser elem elem :=\ndecorate_errors (do c ← cs, return (to_string c)) $\nsat (∈ cs)\n\ndef one_of' [decidable_eq elem] [has_to_string elem] (cs : list elem) : parser elem unit :=\none_of cs >> eps\n\n/-- Number of remaining input characters. -/\ndef remaining : parser elem ℕ :=\nλ input pos, parse_result.done pos (input.size - pos)\n\n/-- Matches the end of the input. -/\ndef eof : parser elem unit :=\ndecorate_error \"\" $\ndo rem ← remaining, guard $ rem = 0\n\ndef foldr_core (f : α → β → β) (p : parser elem α) (b : β) : ∀ (reps : ℕ), parser elem β\n| 0 := failure\n| (reps+1) := (do x ← p, xs ← foldr_core reps, return (f x xs)) <|> return b\n\n/-- Matches zero or more occurrences of `p`, and folds the result. -/\ndef foldr (f : α → β → β) (p : parser elem α) (b : β) : parser elem β :=\nλ input pos, foldr_core f p b (input.size - pos + 1) input pos\n\ndef foldl_core (f : α → β → α) : ∀ (a : α) (p : parser elem β) (reps : ℕ), parser elem α\n| a p 0 := failure\n| a p (reps+1) := (do x ← p, foldl_core (f a x) p reps) <|> return a\n\n/-- Matches zero or more occurrences of `p`, and folds the result. -/\ndef foldl (f : α → β → α) (a : α) (p : parser elem β) : parser elem α :=\nλ input pos, foldl_core f a p (input.size - pos + 1) input pos\n\ndef choice (ps : list (parser elem α)) : parser elem α :=\n ps.foldr (<|>) failure\n\n/-- Matches zero or more occurrences of `p`. -/\ndef many (p : parser elem α) : parser elem (list α) :=\nfoldr list.cons p []\n\n/-- Matches zero or more occurrences of `p`. -/\ndef many' (p : parser elem α) : parser elem unit :=\nmany p >> eps\n\n/-- Matches one or more occurrences of `p`. -/\ndef many1 (p : parser elem α) : parser elem (list α) :=\nlist.cons <$> p <*> many p\n\ndef many_char1 (p : parser elem char) : parser elem string :=\nlist.as_string <$> many1 p\n\n/-- Matches one or more occurrences of `p`, separated by `sep`. -/\ndef sep_by1 (sep : parser elem unit) (p : parser elem α) : parser elem (list α) :=\nlist.cons <$> p <*> many (sep >> p)\n\n/-- Matches zero or more occurrences of `p`, separated by `sep`. -/\ndef sep_by (sep : parser elem unit) (p : parser elem α) : parser elem (list α) :=\nsep_by1 sep p <|> return []\n\n/-- An implementation of `try` from other parser combinator libraries,\n ensures that the parser does not consume input. -/\ndef try {elem α : Type u} (p : parser elem α) : parser elem α :=\nλ input pos, match p input pos with\n | parse_result.fail ._ _ expected1 := parse_result.fail _ pos expected1\n | succ := succ\n end\n\ndef fix_core (F : parser elem α → parser elem α) : ∀ (max_depth : ℕ), parser elem α\n| 0 := failure\n| (max_depth+1) := F (fix_core max_depth)\n\n/-- Fixpoint combinator satisfying `fix F = F (fix F)`. -/\ndef fix (F : parser elem α → parser elem α) : parser elem α :=\nλ input pos, fix_core F (input.size - pos + 1) input pos\n\ndef fix_core_fn {β : Type} (F : (β → parser elem α) → (β → parser elem α)) : ∀ (max_depth : ℕ), β → parser elem α\n| 0 a := failure\n| (max_depth+1) a := F (fix_core_fn max_depth) a\n\n/-- Fixpoint combinator satisfying `fix F = F (fix F)`. -/\ndef fix_fn {β : Type} (F : (β → parser elem α) → (β → parser elem α)) : β → parser elem α :=\nλ a input pos, fix_core_fn F (input.size - pos + 1) a input pos\n\nprivate def make_monospaced : char → char\n| '\\n' := ' '\n| '\\t' := ' '\n| '\\x0d' := ' '\n| c := c\n\ndef mk_error_msg {elem : Type} [has_to_string elem] (input : buffer elem) (pos : ℕ) (expected : dlist string) : char_buffer :=\nlet left_ctx := (input.take pos).take_right 10,\n right_ctx := (input.drop pos).take 10 in\n(to_string left_ctx).to_char_buffer ++ (to_string right_ctx).to_char_buffer ++ \"\\n\".to_char_buffer ++\n/- left_ctx.map (λ _, ' ') ++ -/ \"^\\n\".to_char_buffer ++\n\"\\n\".to_char_buffer ++\n\"expected: \".to_char_buffer\n ++ string.to_char_buffer (\" | \".intercalate expected.to_list)\n ++ \"\\n\".to_char_buffer\n\n/-- Runs a parser on the given input. The parser needs to match the complete input. -/\ndef run [has_to_string elem] (p : parser elem α) (input : buffer elem) : sum string α :=\nmatch (p <* eof) input 0 with\n| parse_result.done pos res := sum.inr res\n| parse_result.fail ._ pos expected :=\n sum.inl $ (mk_error_msg input pos expected).to_string\nend\n\nend parser\n", "meta": {"author": "jroesch", "repo": "parsing", "sha": "8ac39e59498d33b674fda526bfef44af66ca9df8", "save_path": "github-repos/lean/jroesch-parsing", "path": "github-repos/lean/jroesch-parsing/parsing-8ac39e59498d33b674fda526bfef44af66ca9df8/src/parsing/core.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48047867804790706, "lm_q2_score": 0.05340332509185711, "lm_q1q2_score": 0.025659159043498126}} {"text": "import Lean\nimport Lean.Parser.Syntax\n\nopen Lean Elab Command Term\n\n/- ## `Syntax`: Solutions -/\n\n/- ### 1. -/\n\nnamespace a\n scoped notation:71 lhs:50 \" 💀 \" rhs:72 => lhs - rhs\nend a\n\nnamespace b\n set_option quotPrecheck false\n scoped infixl:71 \" 💀 \" => fun lhs rhs => lhs - rhs\nend b\n\nnamespace c\n scoped syntax:71 term:50 \" 💀 \" term:72 : term\n scoped macro_rules | `($l:term 💀 $r:term) => `($l - $r)\nend c\n\nopen a\n#eval 5 * 8 💀 4 -- 20\n#eval 8 💀 6 💀 1 -- 1\n\n/- ### 2. -/\n\nsyntax \"good morning\" : term\nsyntax \"hello\" : command\nsyntax \"yellow\" : tactic\n\n-- Note: the following are highlighted in red, however that's just because we haven't implemented the semantics (\"elaboration function\") yet - the syntax parsing stage works.\n\n#eval good morning -- works\n-- good morning -- error: `expected command`\n\nhello -- works\n-- #eval hello -- error: `expected term`\n\nexample : 2 + 2 = 4 := by\n yellow -- works\n-- yellow -- error: `expected command`\n-- #eval yellow -- error: `unknown identifier 'yellow'`\n\n/- ### 3. -/\n\nsyntax (name := colors) ((\"blue\"+) <|> (\"red\"+)) num : command\n\n@[command_elab colors]\ndef elabColors : CommandElab := fun stx => Lean.logInfo \"success!\"\n\nblue blue 443\nred red red 4\n\n/- ### 4. -/\n\nsyntax (name := help) \"#better_help\" \"option\" (ident)? : command\n\n@[command_elab help]\ndef elabHelp : CommandElab := fun stx => Lean.logInfo \"success!\"\n\n#better_help option\n#better_help option pp.r\n#better_help option some.other.name\n\n/- ### 5. -/\n\n-- Note: std4 has to be in dependencies of your project for this to work.\nsyntax (name := bigsumin) \"∑ \" Std.ExtendedBinder.extBinder \"in \" term \",\" term : term\n\n@[term_elab bigsumin]\ndef elabSum : TermElab := fun stx tp =>\n return mkNatLit 666\n\n#eval ∑ x in { 1, 2, 3 }, x^2\n\ndef hi := (∑ x in { \"apple\", \"banana\", \"cherry\" }, x.length) + 1\n#eval hi\n", "meta": {"author": "leanprover-community", "repo": "lean4-metaprogramming-book", "sha": "0b2e7e2c0cacac530ed947df878088c5d9715412", "save_path": "github-repos/lean/leanprover-community-lean4-metaprogramming-book", "path": "github-repos/lean/leanprover-community-lean4-metaprogramming-book/lean4-metaprogramming-book-0b2e7e2c0cacac530ed947df878088c5d9715412/lean/solutions/syntax.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4455295350395727, "lm_q2_score": 0.05749327395561901, "lm_q1q2_score": 0.025614951613349715}} {"text": "/-\nCopyright (c) 2018 Mario Carneiro. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Mario Carneiro, Minchao Wu\n-/\nimport meta.rb_map\nimport tactic.core\n/-!\n# `#explode` command\n\nDisplays a proof term in a line by line format somewhat akin to a Fitch style\nproof or the Metamath proof style.\n-/\n\nopen expr tactic\n\nnamespace tactic\nnamespace explode\n\n@[derive inhabited]\ninductive status : Type | reg | intro | lam | sintro\n\n/--\nA type to distinguish introduction or elimination rules represented as\nstrings from theorems referred to by their names.\n-/\nmeta inductive thm : Type\n| expr (e : expr)\n| name (n : name)\n| string (s : string)\n\n/--\nTurn a thm into a string.\n-/\nmeta def thm.to_string : thm → string\n| (thm.expr e) := e.to_string\n| (thm.name n) := n.to_string\n| (thm.string s) := s\n\nmeta structure entry : Type :=\n(expr : expr)\n(line : nat)\n(depth : nat)\n(status : status)\n(thm : thm)\n(deps : list nat)\n\nmeta def pad_right (l : list string) : list string :=\nlet n := l.foldl (λ r (s:string), max r s.length) 0 in\nl.map $ λ s, nat.iterate (λ s, s.push ' ') (n - s.length) s\n\n@[derive inhabited]\nmeta structure entries : Type := mk' ::\n(s : expr_map entry)\n(l : list entry)\n\nmeta def entries.find (es : entries) (e : expr) : option entry := es.s.find e\nmeta def entries.size (es : entries) : ℕ := es.s.size\n\nmeta def entries.add : entries → entry → entries\n| es@⟨s, l⟩ e := if s.contains e.expr then es else ⟨s.insert e.expr e, e :: l⟩\n\nmeta def entries.head (es : entries) : option entry := es.l.head'\n\nmeta def format_aux : list string → list string → list string → list entry → tactic format\n| (line :: lines) (dep :: deps) (thm :: thms) (en :: es) := do\n fmt ← do\n { let margin := string.join (list.replicate en.depth \" │\"),\n let margin := match en.status with\n | status.sintro := \" ├\" ++ margin\n | status.intro := \" │\" ++ margin ++ \" ┌\"\n | status.reg := \" │\" ++ margin ++ \"\"\n | status.lam := \" │\" ++ margin ++ \"\"\n end,\n p ← infer_type en.expr >>= pp,\n let lhs := line ++ \"│\" ++ dep ++ \"│ \" ++ thm ++ margin ++ \" \",\n return $ format.of_string lhs ++ (p.nest lhs.length).group ++ format.line },\n (++ fmt) <$> format_aux lines deps thms es\n| _ _ _ _ := return format.nil\n\nmeta instance : has_to_tactic_format entries :=\n⟨λ es : entries,\n let lines := pad_right $ es.l.map (λ en, to_string en.line),\n deps := pad_right $ es.l.map (λ en, string.intercalate \",\" (en.deps.map to_string)),\n thms := pad_right $ es.l.map (λ en, (entry.thm en).to_string) in\n format_aux lines deps thms es.l⟩\n\nmeta def append_dep (filter : expr → tactic unit)\n (es : entries) (e : expr) (deps : list nat) : tactic (list nat) :=\ndo { ei ← es.find e,\n filter ei.expr,\n return (ei.line :: deps) }\n<|> return deps\n\nmeta def may_be_proof (e : expr) : tactic bool :=\ndo expr.sort u ← infer_type e >>= infer_type,\n return $ bnot u.nonzero\n\nend explode\nopen explode\n\nmeta mutual def explode.core, explode.args (filter : expr → tactic unit)\nwith explode.core : expr → bool → nat → entries → tactic entries\n| e@(lam n bi d b) si depth es := do\n m ← mk_fresh_name,\n let l := local_const m n bi d,\n let b' := instantiate_var b l,\n if si then\n let en : entry := ⟨l, es.size, depth, status.sintro, thm.name n, []⟩ in do\n es' ← explode.core b' si depth (es.add en),\n return $ es'.add ⟨e, es'.size, depth, status.lam, thm.string \"∀I\", [es.size, es'.size - 1]⟩\n else do\n let en : entry := ⟨l, es.size, depth, status.intro, thm.name n, []⟩,\n es' ← explode.core b' si (depth + 1) (es.add en),\n -- in case of a \"have\" clause, the b' here has an annotation\n deps' ← explode.append_dep filter es' b'.erase_annotations [],\n deps' ← explode.append_dep filter es' l deps',\n return $ es'.add ⟨e, es'.size, depth, status.lam, thm.string \"∀I\", deps'⟩\n| e@(elet n t a b) si depth es := explode.core (reduce_lets e) si depth es\n| e@(macro n l) si depth es := explode.core l.head si depth es\n| e si depth es := filter e >>\n match get_app_fn_args e with\n | (nm@(const n _), args) :=\n explode.args e args depth es (thm.expr nm) []\n | (fn, []) := do\n let en : entry := ⟨fn, es.size, depth, status.reg, thm.expr fn, []⟩,\n return (es.add en)\n | (fn, args) := do\n es' ← explode.core fn ff depth es,\n -- in case of a \"have\" clause, the fn here has an annotation\n deps ← explode.append_dep filter es' fn.erase_annotations [],\n explode.args e args depth es' (thm.string \"∀E\") deps\n end\nwith explode.args : expr → list expr → nat → entries → thm → list nat → tactic entries\n| e (arg :: args) depth es thm deps := do\n es' ← explode.core arg ff depth es <|> return es,\n deps' ← explode.append_dep filter es' arg deps,\n explode.args e args depth es' thm deps'\n| e [] depth es thm deps :=\n return (es.add ⟨e, es.size, depth, status.reg, thm, deps.reverse⟩)\n\nmeta def explode_expr (e : expr) (hide_non_prop := tt) : tactic entries :=\nlet filter := if hide_non_prop then λ e, may_be_proof e >>= guardb else λ _, skip in\ntactic.explode.core filter e tt 0 default\n\nmeta def explode (n : name) : tactic unit :=\ndo const n _ ← resolve_name n | fail \"cannot resolve name\",\n d ← get_decl n,\n v ← match d with\n | (declaration.defn _ _ _ v _ _) := return v\n | (declaration.thm _ _ _ v) := return v.get\n | _ := fail \"not a definition\"\n end,\n t ← pp d.type,\n explode_expr v <* trace (to_fmt n ++ \" : \" ++ t) >>= trace\n\nsetup_tactic_parser\n\n/--\n`#explode decl_name` displays a proof term in a line-by-line format somewhat akin to a Fitch-style\nproof or the Metamath proof style.\n`#explode_widget decl_name` renders a widget that displays an `#explode` proof.\n\n`#explode iff_true_intro` produces\n\n```lean\niff_true_intro : ∀ {a : Prop}, a → (a ↔ true)\n0│ │ a ├ Prop\n1│ │ h ├ a\n2│ │ hl │ ┌ a\n3│ │ trivial │ │ true\n4│2,3│ ∀I │ a → true\n5│ │ hr │ ┌ true\n6│5,1│ ∀I │ true → a\n7│4,6│ iff.intro │ a ↔ true\n8│1,7│ ∀I │ a → (a ↔ true)\n9│0,8│ ∀I │ ∀ {a : Prop}, a → (a ↔ true)\n```\n\nIn more detail:\n\nThe output of `#explode` is a Fitch-style proof in a four-column diagram modeled after Metamath\nproof displays like [this](http://us.metamath.org/mpeuni/ru.html). The headers of the columns are\n\"Step\", \"Hyp\", \"Ref\", \"Type\" (or \"Expression\" in the case of Metamath):\n* Step: An increasing sequence of numbers to number each step in the proof, used in the Hyp field.\n* Hyp: The direct children of the current step. Most theorems are implications like `A -> B -> C`,\n and so on the step proving `C` the Hyp field will refer to the steps that prove `A` and `B`.\n* Ref: The name of the theorem being applied. This is well-defined in Metamath, but in Lean there\n are some special steps that may have long names because the structure of proof terms doesn't\n exactly match this mold.\n * If the theorem is `foo (x y : Z) : A x -> B y -> C x y`:\n * the Ref field will contain `foo`,\n * `x` and `y` will be suppressed, because term construction is not interesting, and\n * the Hyp field will reference steps proving `A x` and `B y`. This corresponds to a proof term\n like `@foo x y pA pB` where `pA` and `pB` are subproofs.\n * If the head of the proof term is a local constant or lambda, then in this case the Ref will\n say `∀E` for forall-elimination. This happens when you have for example `h : A -> B` and\n `ha : A` and prove `b` by `h ha`; we reinterpret this as if it said `∀E h ha` where `∀E` is\n (n-ary) modus ponens.\n * If the proof term is a lambda, we will also use `∀I` for forall-introduction, referencing the\n body of the lambda. The indentation level will increase, and a bracket will surround the proof\n of the body of the lambda, starting at a proof step labeled with the name of the lambda variable\n and its type, and ending with the `∀I` step. Metamath doesn't have steps like this, but the\n style is based on Fitch proofs in first-order logic.\n* Type: This contains the type of the proof term, the theorem being proven at the current step.\n This proof layout differs from `#print` in using lots of intermediate step displays so that you\n can follow along and don't have to see term construction steps because they are implicitly in the\n intermediate step displays.\n\nAlso, it is common for a Lean theorem to begin with a sequence of lambdas introducing local\nconstants of the theorem. In order to minimize the indentation level, the `∀I` steps at the end of\nthe proof will be introduced in a group and the indentation will stay fixed. (The indentation\nbrackets are only needed in order to delimit the scope of assumptions, and these assumptions\nhave global scope anyway so detailed tracking is not necessary.)\n-/\n@[user_command]\nmeta def explode_cmd (_ : parse $ tk \"#explode\") : parser unit :=\ndo n ← ident,\n explode n\n.\n\nadd_tactic_doc\n{ name := \"#explode / #explode_widget\",\n category := doc_category.cmd,\n decl_names := [`tactic.explode_cmd, `tactic.explode_widget_cmd],\n inherit_description_from := `tactic.explode_cmd,\n tags := [\"proof display\", \"widgets\"] }\n\nend tactic\n", "meta": {"author": "leanprover-community", "repo": "mathlib", "sha": "5e526d18cea33550268dcbbddcb822d5cde40654", "save_path": "github-repos/lean/leanprover-community-mathlib", "path": "github-repos/lean/leanprover-community-mathlib/mathlib-5e526d18cea33550268dcbbddcb822d5cde40654/src/tactic/explode.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3960681520167196, "lm_q2_score": 0.0646534955652171, "lm_q1q2_score": 0.025607190509936713}} {"text": "/-\nCopyright (c) 2019 Simon Hudon. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Simon Hudon\n-/\nimport tactic.core\n\n/-!\nThis file provides an alternative implementation for `apply` to fix the so-called \"apply bug\".\n\nThe issue arises when the goals is a Π-type -- whether it is visible or hidden behind a definition.\n\nFor instance, consider the following proof:\n\n```\nexample {α β} (x y z : α → β) (h₀ : x ≤ y) (h₁ : y ≤ z) : x ≤ z :=\nbegin\n apply le_trans,\nend\n```\n\nBecause `x ≤ z` is definitionally equal to `∀ i, x i ≤ z i`, `apply` will fail. The alternative\ndefinition, `apply'` fixes this. When `apply` would work, `apply` is used and otherwise,\na different strategy is deployed\n-/\n\nnamespace tactic\n\n/-- With `gs` a list of proof goals, `reorder_goals gs new_g` will use the `new_goals` policy\n`new_g` to rearrange the dependent goals to either drop them, push them to the end of the list\nor leave them in place. The `bool` values in `gs` indicates whether the goal is dependent or not. -/\ndef reorder_goals {α} (gs : list (bool × α)) : new_goals → list α\n| new_goals.non_dep_first :=\n let ⟨dep,non_dep⟩ := gs.partition (coe ∘ prod.fst) in\n non_dep.map prod.snd ++ dep.map prod.snd\n| new_goals.non_dep_only := (gs.filter (coe ∘ bnot ∘ prod.fst)).map prod.snd\n| new_goals.all := gs.map prod.snd\n\nprivate meta def has_opt_auto_param_inst_for_apply (ms : list (name × expr)) : tactic bool :=\nms.mfoldl\n (λ r m, do type ← infer_type m.2,\n b ← is_class type,\n return $ r || type.is_napp_of `opt_param 2 || type.is_napp_of `auto_param 2 || b)\n ff\n\nprivate meta def try_apply_opt_auto_param_instance_for_apply (cfg : apply_cfg)\n (ms : list (name × expr)) : tactic unit :=\nmwhen (has_opt_auto_param_inst_for_apply ms) $ do\n gs ← get_goals,\n ms.mmap' (λ m, mwhen (bnot <$> (is_assigned m.2)) $\n set_goals [m.2] >>\n try apply_instance >>\n when cfg.opt_param (try apply_opt_param) >>\n when cfg.auto_param (try apply_auto_param)),\n set_goals gs\n\nprivate meta def retry_apply_aux :\n Π (e : expr) (cfg : apply_cfg), list (bool × name × expr) → tactic (list (name × expr))\n| e cfg gs :=\nfocus1 (do\n { tgt : expr ← target, t ← infer_type e,\n unify t tgt,\n exact e,\n gs' ← get_goals,\n let r := reorder_goals gs.reverse cfg.new_goals,\n set_goals (gs' ++ r.map prod.snd),\n return r }) <|>\ndo (expr.pi n bi d b) ← infer_type e >>= whnf | apply_core e cfg,\n v ← mk_meta_var d,\n let b := b.has_var,\n e ← head_beta $ e v,\n retry_apply_aux e cfg ((b, n, v) :: gs)\n\nprivate meta def retry_apply (e : expr) (cfg : apply_cfg) : tactic (list (name × expr)) :=\napply_core e cfg <|> retry_apply_aux e cfg []\n\n/-- `apply'` mimics the behavior of `apply_core`. When\n`apply_core` fails, it is retried by providing the term with meta\nvariables as additional arguments. The meta variables can then\nbecome new goals depending on the `cfg.new_goals` policy.\n\n`apply'` also finds instances and applies opt_params and auto_params. -/\nmeta def apply' (e : expr) (cfg : apply_cfg := {}) : tactic (list (name × expr)) :=\ndo r ← retry_apply e cfg,\n try_apply_opt_auto_param_instance_for_apply cfg r,\n return r\n\n/-- Same as `apply'` but __all__ arguments that weren't inferred are added to goal list. -/\nmeta def fapply' (e : expr) : tactic (list (name × expr)) :=\napply' e {new_goals := new_goals.all}\n/-- Same as `apply'` but only goals that don't depend on other goals are added to goal list. -/\nmeta def eapply' (e : expr) : tactic (list (name × expr)) :=\napply' e {new_goals := new_goals.non_dep_only}\n\n/-- `relation_tactic` finds a proof rule for the relation found in the goal and uses `apply'`\nto make one proof step. -/\nprivate meta def relation_tactic (md : transparency) (op_for : environment → name → option name)\n (tac_name : string) : tactic unit :=\ndo tgt ← target >>= instantiate_mvars,\n env ← get_env,\n let r := expr.get_app_fn tgt,\n match op_for env (expr.const_name r) with\n | (some refl) := do r ← mk_const refl,\n retry_apply r {md := md, new_goals := new_goals.non_dep_only },\n return ()\n | none := fail $ tac_name ++\n \" tactic failed, target is not a relation application with the expected property.\"\n end\n\n/-- Similar to `reflexivity` with the difference that `apply'` is used instead of `apply` -/\nmeta def reflexivity' (md := semireducible) : tactic unit :=\nrelation_tactic md environment.refl_for \"reflexivity\"\n\n/-- Similar to `symmetry` with the difference that `apply'` is used instead of `apply` -/\nmeta def symmetry' (md := semireducible) : tactic unit :=\nrelation_tactic md environment.symm_for \"symmetry\"\n\n/-- Similar to `transitivity` with the difference that `apply'` is used instead of `apply` -/\nmeta def transitivity' (md := semireducible) : tactic unit :=\nrelation_tactic md environment.trans_for \"transitivity\"\n\nnamespace interactive\n\nsetup_tactic_parser\n\n/--\nSimilarly to `apply`, the `apply'` tactic tries to match the current goal against the conclusion\nof the type of term.\n\nIt differs from `apply` in that it does not unfold definition in order to find out what the\nassumptions of the provided term is. It is especially useful when defining relations on function\nspaces (e.g. `≤`) so that rules like transitivity on `le : (α → β) → (α → β) → (α → β)` will be\nconsidered to have three parameters and two assumptions (i.e. `f g h : α → β`, `H₀ : f ≤ g`,\n`H₁ : g ≤ h`) instead of three parameters, two assumptions and then one more parameter\n(i.e. `f g h : α → β`, `H₀ : f ≤ g`, `H₁ : g ≤ h`, `x : α`). Whereas `apply` would expect the goal\n`f x ≤ h x`, `apply'` will work with the goal `f ≤ h`.\n-/\nmeta def apply' (q : parse texpr) : tactic unit :=\nconcat_tags (do h ← i_to_expr_for_apply q, tactic.apply' h)\n\n/--\nSimilar to the `apply'` tactic, but does not reorder goals.\n-/\nmeta def fapply' (q : parse texpr) : tactic unit :=\nconcat_tags (i_to_expr_for_apply q >>= tactic.fapply')\n\n/--\nSimilar to the `apply'` tactic, but only creates subgoals for non-dependent premises that have not\nbeen fixed by type inference or type class resolution.\n-/\nmeta def eapply' (q : parse texpr) : tactic unit :=\nconcat_tags (i_to_expr_for_apply q >>= tactic.eapply')\n\n/--\nSimilar to the `apply'` tactic, but allows the user to provide a `apply_cfg` configuration object.\n-/\nmeta def apply_with' (q : parse parser.pexpr) (cfg : apply_cfg) : tactic unit :=\nconcat_tags (do e ← i_to_expr_for_apply q, tactic.apply' e cfg)\n\n/--\nSimilar to the `apply'` tactic, but uses matching instead of unification.\n`mapply' t` is equivalent to `apply_with' t {unify := ff}`\n-/\nmeta def mapply' (q : parse texpr) : tactic unit :=\nconcat_tags (do e ← i_to_expr_for_apply q, tactic.apply' e {unify := ff})\n\n\n/--\nSimilar to `reflexivity` with the difference that `apply'` is used instead of `apply`.\n-/\nmeta def reflexivity' : tactic unit :=\ntactic.reflexivity'\n\n/--\nShorter name for the tactic `reflexivity'`.\n-/\nmeta def refl' : tactic unit :=\ntactic.reflexivity'\n\n/--\n`symmetry'` behaves like `symmetry` but also offers the option `symmetry' at h` to apply symmetry\nto assumption `h`\n-/\nmeta def symmetry' : parse location → tactic unit\n| l@loc.wildcard := l.try_apply symmetry_hyp tactic.symmetry'\n| (loc.ns hs) := (loc.ns hs.reverse).apply symmetry_hyp tactic.symmetry'\n\n/--\nSimilar to `transitivity` with the difference that `apply'` is used instead of `apply`.\n-/\nmeta def transitivity' (q : parse texpr?) : tactic unit :=\ntactic.transitivity' >> match q with\n| none := skip\n| some q :=\n do (r, lhs, rhs) ← target_lhs_rhs,\n t ← infer_type lhs,\n i_to_expr ``(%%q : %%t) >>= unify rhs\nend\n\nend interactive\n\nend tactic\n", "meta": {"author": "leanprover-community", "repo": "mathlib", "sha": "5e526d18cea33550268dcbbddcb822d5cde40654", "save_path": "github-repos/lean/leanprover-community-mathlib", "path": "github-repos/lean/leanprover-community-mathlib/mathlib-5e526d18cea33550268dcbbddcb822d5cde40654/src/tactic/apply.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3276682876897044, "lm_q2_score": 0.07807817265325534, "lm_q1q2_score": 0.02558374113923328}} {"text": "namespace List\n\n@[simp] theorem filter_nil {p : α → Bool} : filter p [] = [] := by\n simp [filter, filterAux, reverse, reverseAux]\n\ntheorem cons_eq_append (a : α) (as : List α) : a :: as = [a] ++ as := rfl\n\ntheorem filter_cons (a : α) (as : List α) :\n filter p (a :: as) = if p a then a :: filter p as else filter p as :=\n sorry\n\n@[simp] theorem filter_append {as bs : List α} {p : α → Bool} :\n filter p (as ++ bs) = filter p as ++ filter p bs :=\n match as with\n | [] => by simp\n | a :: as => by\n rw [filter_cons, cons_append, filter_cons]\n cases p a\n simp [filter_append]\n simp [filter_append]\n\n-- the previous contains a more complicated version of\ndef f : Nat → Nat\n | 0 => 1\n | i+1 => (fun x => f x) i\n", "meta": {"author": "gebner", "repo": "lean4-old", "sha": "ee51cdfaf63ee313c914d83264f91f414a0e3b6e", "save_path": "github-repos/lean/gebner-lean4-old", "path": "github-repos/lean/gebner-lean4-old/lean4-old-ee51cdfaf63ee313c914d83264f91f414a0e3b6e/tests/lean/run/structuralIssue2.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.5, "lm_q2_score": 0.05108273876282333, "lm_q1q2_score": 0.025541369381411664}} {"text": "/-\nCopyright (c) 2019 Paul-Nicolas Madelaine. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Paul-Nicolas Madelaine, Robert Y. Lewis, Mario Carneiro, Gabriel Ebner\n-/\nimport Lean.Meta.CongrTheorems\nimport Lean.Meta.Tactic.Simp.SimpTheorems\nimport Std.Tactic.CoeExt\n\nopen Lean Meta\n\nnamespace Std.Tactic.NormCast\nopen Tactic.Coe\n\n/--\n`Label` is a type used to classify `norm_cast` lemmas.\n* elim lemma: LHS has 0 head coes and ≥ 1 internal coe\n* move lemma: LHS has 1 head coe and 0 internal coes, RHS has 0 head coes and ≥ 1 internal coes\n* squash lemma: LHS has ≥ 1 head coes and 0 internal coes, RHS has fewer head coes\n-/\ninductive Label\n /-- elim lemma: LHS has 0 head coes and ≥ 1 internal coe -/\n | elim\n /-- move lemma: LHS has 1 head coe and 0 internal coes,\n RHS has 0 head coes and ≥ 1 internal coes -/\n | move\n /-- squash lemma: LHS has ≥ 1 head coes and 0 internal coes, RHS has fewer head coes -/\n | squash\n deriving DecidableEq, Repr, Inhabited\n\n/-- Assuming `e` is an application, returns the list of subterms that `simp` will rewrite in. -/\ndef getSimpArgs (e : Expr) : MetaM (Array Expr) := do\n match ← mkCongrSimp? e.getAppFn with\n | none => return e.getAppArgs\n | some {argKinds, ..} =>\n let mut args := #[]\n for a in e.getAppArgs, k in argKinds do\n if k matches .eq then\n args := args.push a\n return args\n\n/-- Count how many coercions are at the top of the expression. -/\npartial def countHeadCoes (e : Expr) : MetaM Nat := do\n if let Expr.const fn .. := e.getAppFn then\n if let some info ← getCoeFnInfo? fn then\n if e.getAppNumArgs >= info.numArgs then\n return (← countHeadCoes (e.getArg! info.coercee)) + 1\n return 0\n\n/-- Count how many coercions are inside the expression, including the top ones. -/\npartial def countCoes (e : Expr) : MetaM Nat :=\n lambdaTelescope e fun _ e => do\n if let Expr.const fn .. := e.getAppFn then\n if let some info ← getCoeFnInfo? fn then\n if e.getAppNumArgs >= info.numArgs then\n let mut coes := (← countHeadCoes (e.getArg! info.coercee)) + 1\n for i in [info.numArgs:e.getAppNumArgs] do\n coes := coes + (← countCoes (e.getArg! i))\n return coes\n return (← (← getSimpArgs e).mapM countCoes).foldl (·+·) 0\n\n/-- Count how many coercions are inside the expression, excluding the top ones. -/\ndef countInternalCoes (e : Expr) : MetaM Nat :=\n return (← countCoes e) - (← countHeadCoes e)\n\n/-- Classifies a declaration of type `ty` as a `norm_cast` rule. -/\ndef classifyType (ty : Expr) : MetaM Label :=\n forallTelescopeReducing ty fun _ ty => do\n let ty ← whnf ty\n let (lhs, rhs) ←\n if ty.isAppOfArity ``Eq 3 then pure (ty.getArg! 1, ty.getArg! 2)\n else if ty.isAppOfArity ``Iff 2 then pure (ty.getArg! 0, ty.getArg! 1)\n else throwError \"norm_cast: lemma must be = or ↔, but is{indentExpr ty}\"\n let lhsCoes ← countCoes lhs\n if lhsCoes = 0 then throwError \"norm_cast: badly shaped lemma, lhs must contain at least one coe{indentExpr lhs}\"\n let lhsHeadCoes ← countHeadCoes lhs\n let rhsHeadCoes ← countHeadCoes rhs\n let rhsInternalCoes ← countInternalCoes rhs\n if lhsHeadCoes = 0 then\n return Label.elim\n else if lhsHeadCoes = 1 then do\n unless rhsHeadCoes = 0 do throwError \"norm_cast: badly shaped lemma, rhs can't start with coe{indentExpr rhs}\"\n if rhsInternalCoes = 0 then\n return Label.squash\n else\n return Label.move\n else if rhsHeadCoes < lhsHeadCoes then do\n return Label.squash\n else do\n throwError \"norm_cast: badly shaped shaped squash lemma, rhs must have fewer head coes than lhs{indentExpr ty}\"\n\n/-- The `push_cast` simp attribute. -/\ninitialize pushCastExt : SimpExtension ←\n registerSimpAttr `push_cast <|\n \"The `push_cast` simp attribute uses `norm_cast` lemmas \" ++\n \"to move casts toward the leaf nodes of the expression.\"\n\n/-- The `norm_cast` attribute stores three simp sets. -/\nstructure NormCastExtension where\n /-- A simp set which lifts coercion arrows to the top level. -/\n up : SimpExtension\n /-- A simp set which pushes coercion arrows to the leaves. -/\n down : SimpExtension\n /-- A simp set which simplifies transitive coercions. -/\n squash : SimpExtension\n deriving Inhabited\n\n/-- The `norm_cast` extension data. -/\ninitialize normCastExt : NormCastExtension ← pure {\n up := ← mkSimpExt (decl_name% ++ `up)\n down := ← mkSimpExt (decl_name% ++ `down)\n squash := ← mkSimpExt (decl_name% ++ `squash)\n}\n\n/-- `addElim decl` adds `decl` as an `elim` lemma to the cache. -/\ndef addElim (decl : Name)\n (kind := AttributeKind.global) (prio := eval_prio default) : MetaM Unit :=\n addSimpTheorem normCastExt.up decl (post := true) (inv := false) kind prio\n\n/-- `addMove decl` adds `decl` as a `move` lemma to the cache. -/\ndef addMove (decl : Name)\n (kind := AttributeKind.global) (prio := eval_prio default) : MetaM Unit := do\n addSimpTheorem pushCastExt decl (post := true) (inv := false) kind prio\n addSimpTheorem normCastExt.up decl (post := true) (inv := true) kind prio\n addSimpTheorem normCastExt.down decl (post := true) (inv := false) kind prio\n\n/-- `addSquash decl` adds `decl` as a `squash` lemma to the cache. -/\ndef addSquash (decl : Name)\n (kind := AttributeKind.global) (prio := eval_prio default) : MetaM Unit := do\n addSimpTheorem pushCastExt decl (post := true) (inv := false) kind prio\n addSimpTheorem normCastExt.squash decl (post := true) (inv := false) kind prio\n addSimpTheorem normCastExt.down decl (post := true) (inv := false) kind prio\n\n/-- `addInfer decl` infers the label of `decl` and adds it to the cache.\n\n* elim lemma: LHS has 0 head coes and ≥ 1 internal coe\n* move lemma: LHS has 1 head coe and 0 internal coes, RHS has 0 head coes and ≥ 1 internal coes\n* squash lemma: LHS has ≥ 1 head coes and 0 internal coes, RHS has fewer head coes\n-/\ndef addInfer (decl : Name)\n (kind := AttributeKind.global) (prio := eval_prio default) : MetaM Unit := do\n let ty := (← getConstInfo decl).type\n match ← classifyType ty with\n | Label.elim => addElim decl kind prio\n | Label.squash => addSquash decl kind prio\n | Label.move => addMove decl kind prio\n\nnamespace Attr\n/-- The possible `norm_cast` kinds: `elim`, `move`, or `squash`. -/\nsyntax normCastLabel := &\"elim\" <|> &\"move\" <|> &\"squash\"\n\n\n/--\nThe `norm_cast` attribute should be given to lemmas that describe the\nbehaviour of a coercion in regard to an operator, a relation, or a particular\nfunction.\n\nIt only concerns equality or iff lemmas involving `↑`, `⇑` and `↥`, describing the behavior of\nthe coercion functions.\nIt does not apply to the explicit functions that define the coercions.\n\nExamples:\n```lean\n@[norm_cast] theorem coe_nat_inj' {m n : ℕ} : (↑m : ℤ) = ↑n ↔ m = n\n\n@[norm_cast] theorem coe_int_denom (n : ℤ) : (n : ℚ).denom = 1\n\n@[norm_cast] theorem cast_id : ∀ n : ℚ, ↑n = n\n\n@[norm_cast] theorem coe_nat_add (m n : ℕ) : (↑(m + n) : ℤ) = ↑m + ↑n\n\n@[norm_cast] theorem cast_coe_nat (n : ℕ) : ((n : ℤ) : α) = n\n\n@[norm_cast] theorem cast_one : ((1 : ℚ) : α) = 1\n```\n\nLemmas tagged with `@[norm_cast]` are classified into three categories: `move`, `elim`, and\n`squash`. They are classified roughly as follows:\n\n* elim lemma: LHS has 0 head coes and ≥ 1 internal coe\n* move lemma: LHS has 1 head coe and 0 internal coes, RHS has 0 head coes and ≥ 1 internal coes\n* squash lemma: LHS has ≥ 1 head coes and 0 internal coes, RHS has fewer head coes\n\n`norm_cast` uses `move` and `elim` lemmas to factor coercions toward the root of an expression\nand to cancel them from both sides of an equation or relation. It uses `squash` lemmas to clean\nup the result.\n\nOccasionally you may want to override the automatic classification.\nYou can do this by giving an optional `elim`, `move`, or `squash` parameter to the attribute.\n\n```lean\n@[simp, norm_cast elim] lemma nat_cast_re (n : ℕ) : (n : ℂ).re = n := by\n rw [← of_real_nat_cast, of_real_re]\n```\n\nDon't do this unless you understand what you are doing.\n\nA full description of the tactic, and the use of each lemma category, can be found at\n.\n-/\nsyntax (name := norm_cast) \"norm_cast\" (ppSpace normCastLabel)? (ppSpace num)? : attr\nend Attr\n\ninitialize registerBuiltinAttribute {\n name := `norm_cast\n descr := \"attribute for norm_cast\"\n add := fun decl stx kind => MetaM.run' do\n let `(attr| norm_cast $[$label:normCastLabel]? $[$prio]?) := stx | unreachable!\n let prio := (prio.bind (·.1.isNatLit?)).getD (eval_prio default)\n match label.bind (·.1.isStrLit?) with\n | \"elim\" => addElim decl kind prio\n | \"move\" => addMove decl kind prio\n | \"squash\" => addSquash decl kind prio\n | none => addInfer decl kind prio\n | _ => unreachable!\n}\n", "meta": {"author": "leanprover", "repo": "std4", "sha": "5507f9d8409f93b984ce04eccf4914d534e6fca2", "save_path": "github-repos/lean/leanprover-std4", "path": "github-repos/lean/leanprover-std4/std4-5507f9d8409f93b984ce04eccf4914d534e6fca2/Std/Tactic/NormCast/Ext.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45713670203584295, "lm_q2_score": 0.055823141920008715, "lm_q1q2_score": 0.025518806994591598}} {"text": "/-\nCopyright (c) 2017 Mario Carneiro. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Mario Carneiro, Jeremy Avigad, Simon Hudon\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.default\nimport Mathlib.data.rel\nimport Mathlib.PostPort\n\nuniverses u l u_1 u_2 u_3 \n\nnamespace Mathlib\n\n/-- `roption α` is the type of \"partial values\" of type `α`. It\n is similar to `option α` except the domain condition can be an\n arbitrary proposition, not necessarily decidable. -/\nstructure roption (α : Type u) where\n dom : Prop\n get : dom → α\n\nnamespace roption\n\n\n/-- Convert an `roption α` with a decidable domain to an option -/\ndef to_option {α : Type u_1} (o : roption α) [Decidable (dom o)] : Option α :=\n dite (dom o) (fun (h : dom o) => some (get o h)) fun (h : ¬dom o) => none\n\n/-- `roption` extensionality -/\ntheorem ext' {α : Type u_1} {o : roption α} {p : roption α} (H1 : dom o ↔ dom p)\n (H2 : ∀ (h₁ : dom o) (h₂ : dom p), get o h₁ = get p h₂) : o = p :=\n sorry\n\n/-- `roption` eta expansion -/\n@[simp] theorem eta {α : Type u_1} (o : roption α) : (mk (dom o) fun (h : dom o) => get o h) = o :=\n sorry\n\n/-- `a ∈ o` means that `o` is defined and equal to `a` -/\nprotected def mem {α : Type u_1} (a : α) (o : roption α) := ∃ (h : dom o), get o h = a\n\nprotected instance has_mem {α : Type u_1} : has_mem α (roption α) := has_mem.mk roption.mem\n\ntheorem mem_eq {α : Type u_1} (a : α) (o : roption α) : a ∈ o = ∃ (h : dom o), get o h = a := rfl\n\ntheorem dom_iff_mem {α : Type u_1} {o : roption α} : dom o ↔ ∃ (y : α), y ∈ o := sorry\n\ntheorem get_mem {α : Type u_1} {o : roption α} (h : dom o) : get o h ∈ o := Exists.intro h rfl\n\n/-- `roption` extensionality -/\ntheorem ext {α : Type u_1} {o : roption α} {p : roption α} (H : ∀ (a : α), a ∈ o ↔ a ∈ p) : o = p :=\n sorry\n\n/-- The `none` value in `roption` has a `false` domain and an empty function. -/\ndef none {α : Type u_1} : roption α := mk False False._oldrec\n\nprotected instance inhabited {α : Type u_1} : Inhabited (roption α) := { default := none }\n\n@[simp] theorem not_mem_none {α : Type u_1} (a : α) : ¬a ∈ none :=\n fun (h : a ∈ none) => Exists.fst h\n\n/-- The `some a` value in `roption` has a `true` domain and the\n function returns `a`. -/\ndef some {α : Type u_1} (a : α) : roption α := mk True fun (_x : True) => a\n\ntheorem mem_unique {α : Type u_1} : relator.left_unique has_mem.mem := sorry\n\ntheorem get_eq_of_mem {α : Type u_1} {o : roption α} {a : α} (h : a ∈ o) (h' : dom o) :\n get o h' = a :=\n mem_unique (Exists.intro h' rfl) h\n\n@[simp] theorem get_some {α : Type u_1} {a : α} (ha : dom (some a)) : get (some a) ha = a := rfl\n\ntheorem mem_some {α : Type u_1} (a : α) : a ∈ some a := Exists.intro trivial rfl\n\n@[simp] theorem mem_some_iff {α : Type u_1} {a : α} {b : α} : b ∈ some a ↔ b = a := sorry\n\ntheorem eq_some_iff {α : Type u_1} {a : α} {o : roption α} : o = some a ↔ a ∈ o := sorry\n\ntheorem eq_none_iff {α : Type u_1} {o : roption α} : o = none ↔ ∀ (a : α), ¬a ∈ o := sorry\n\ntheorem eq_none_iff' {α : Type u_1} {o : roption α} : o = none ↔ ¬dom o :=\n { mp := fun (e : o = none) => Eq.symm e ▸ id,\n mpr := fun (h : ¬dom o) => iff.mpr eq_none_iff fun (a : α) (h' : a ∈ o) => h (Exists.fst h') }\n\ntheorem some_ne_none {α : Type u_1} (x : α) : some x ≠ none :=\n id\n fun (h : some x = none) =>\n id (eq.mpr (id (Eq._oldrec (Eq.refl (dom none)) (Eq.symm h))) trivial)\n\ntheorem ne_none_iff {α : Type u_1} {o : roption α} : o ≠ none ↔ ∃ (x : α), o = some x := sorry\n\ntheorem eq_none_or_eq_some {α : Type u_1} (o : roption α) : o = none ∨ ∃ (x : α), o = some x :=\n sorry\n\n@[simp] theorem some_inj {α : Type u_1} {a : α} {b : α} : some a = some b ↔ a = b :=\n function.injective.eq_iff\n fun (a b : α) (h : some a = some b) => congr_fun (eq_of_heq (and.right (mk.inj h))) trivial\n\n@[simp] theorem some_get {α : Type u_1} {a : roption α} (ha : dom a) : some (get a ha) = a :=\n Eq.symm (iff.mpr eq_some_iff (Exists.intro ha rfl))\n\ntheorem get_eq_iff_eq_some {α : Type u_1} {a : roption α} {ha : dom a} {b : α} :\n get a ha = b ↔ a = some b :=\n sorry\n\nprotected instance none_decidable {α : Type u_1} : Decidable (dom none) := decidable.false\n\nprotected instance some_decidable {α : Type u_1} (a : α) : Decidable (dom (some a)) :=\n decidable.true\n\ndef get_or_else {α : Type u_1} (a : roption α) [Decidable (dom a)] (d : α) : α :=\n dite (dom a) (fun (ha : dom a) => get a ha) fun (ha : ¬dom a) => d\n\n@[simp] theorem get_or_else_none {α : Type u_1} (d : α) : get_or_else none d = d := dif_neg id\n\n@[simp] theorem get_or_else_some {α : Type u_1} (a : α) (d : α) : get_or_else (some a) d = a :=\n dif_pos trivial\n\n@[simp] theorem mem_to_option {α : Type u_1} {o : roption α} [Decidable (dom o)] {a : α} :\n a ∈ to_option o ↔ a ∈ o :=\n sorry\n\n/-- Convert an `option α` into an `roption α` -/\ndef of_option {α : Type u_1} : Option α → roption α := sorry\n\n@[simp] theorem mem_of_option {α : Type u_1} {a : α} {o : Option α} : a ∈ of_option o ↔ a ∈ o :=\n sorry\n\n@[simp] theorem of_option_dom {α : Type u_1} (o : Option α) :\n dom (of_option o) ↔ ↥(option.is_some o) :=\n sorry\n\ntheorem of_option_eq_get {α : Type u_1} (o : Option α) :\n of_option o = mk (↥(option.is_some o)) option.get :=\n sorry\n\nprotected instance has_coe {α : Type u_1} : has_coe (Option α) (roption α) := has_coe.mk of_option\n\n@[simp] theorem mem_coe {α : Type u_1} {a : α} {o : Option α} : a ∈ ↑o ↔ a ∈ o := mem_of_option\n\n@[simp] theorem coe_none {α : Type u_1} : ↑none = none := rfl\n\n@[simp] theorem coe_some {α : Type u_1} (a : α) : ↑(some a) = some a := rfl\n\nprotected theorem induction_on {α : Type u_1} {P : roption α → Prop} (a : roption α)\n (hnone : P none) (hsome : ∀ (a : α), P (some a)) : P a :=\n or.elim (classical.em (dom a)) (fun (h : dom a) => some_get h ▸ hsome (get a h))\n fun (h : ¬dom a) => Eq.symm (iff.mpr eq_none_iff' h) ▸ hnone\n\nprotected instance of_option_decidable {α : Type u_1} (o : Option α) :\n Decidable (dom (of_option o)) :=\n sorry\n\n@[simp] theorem to_of_option {α : Type u_1} (o : Option α) : to_option (of_option o) = o :=\n option.cases_on o (Eq.refl (to_option (of_option none)))\n fun (o : α) => Eq.refl (to_option (of_option (some o)))\n\n@[simp] theorem of_to_option {α : Type u_1} (o : roption α) [Decidable (dom o)] :\n of_option (to_option o) = o :=\n ext fun (a : α) => iff.trans mem_of_option mem_to_option\n\ndef equiv_option {α : Type u_1} : roption α ≃ Option α :=\n equiv.mk (fun (o : roption α) => to_option o) of_option sorry sorry\n\nprotected instance order_bot {α : Type u_1} : order_bot (roption α) :=\n order_bot.mk none (fun (x y : roption α) => ∀ (i : α), i ∈ x → i ∈ y)\n (partial_order.lt._default fun (x y : roption α) => ∀ (i : α), i ∈ x → i ∈ y) sorry sorry sorry\n sorry\n\nprotected instance preorder {α : Type u_1} : preorder (roption α) :=\n partial_order.to_preorder (roption α)\n\ntheorem le_total_of_le_of_le {α : Type u_1} {x : roption α} {y : roption α} (z : roption α)\n (hx : x ≤ z) (hy : y ≤ z) : x ≤ y ∨ y ≤ x :=\n sorry\n\n/-- `assert p f` is a bind-like operation which appends an additional condition\n `p` to the domain and uses `f` to produce the value. -/\ndef assert {α : Type u_1} (p : Prop) (f : p → roption α) : roption α :=\n mk (∃ (h : p), dom (f h)) fun (ha : ∃ (h : p), dom (f h)) => get (f sorry) sorry\n\n/-- The bind operation has value `g (f.get)`, and is defined when all the\n parts are defined. -/\nprotected def bind {α : Type u_1} {β : Type u_2} (f : roption α) (g : α → roption β) : roption β :=\n assert (dom f) fun (b : dom f) => g (get f b)\n\n/-- The map operation for `roption` just maps the value and maintains the same domain. -/\ndef map {α : Type u_1} {β : Type u_2} (f : α → β) (o : roption α) : roption β :=\n mk (dom o) (f ∘ get o)\n\ntheorem mem_map {α : Type u_1} {β : Type u_2} (f : α → β) {o : roption α} {a : α} :\n a ∈ o → f a ∈ map f o :=\n sorry\n\n@[simp] theorem mem_map_iff {α : Type u_1} {β : Type u_2} (f : α → β) {o : roption α} {b : β} :\n b ∈ map f o ↔ ∃ (a : α), ∃ (H : a ∈ o), f a = b :=\n sorry\n\n@[simp] theorem map_none {α : Type u_1} {β : Type u_2} (f : α → β) : map f none = none := sorry\n\n@[simp] theorem map_some {α : Type u_1} {β : Type u_2} (f : α → β) (a : α) :\n map f (some a) = some (f a) :=\n iff.mpr eq_some_iff (mem_map f (mem_some a))\n\ntheorem mem_assert {α : Type u_1} {p : Prop} {f : p → roption α} {a : α} (h : p) :\n a ∈ f h → a ∈ assert p f :=\n sorry\n\n@[simp] theorem mem_assert_iff {α : Type u_1} {p : Prop} {f : p → roption α} {a : α} :\n a ∈ assert p f ↔ ∃ (h : p), a ∈ f h :=\n sorry\n\ntheorem assert_pos {α : Type u_1} {p : Prop} {f : p → roption α} (h : p) : assert p f = f h := sorry\n\ntheorem assert_neg {α : Type u_1} {p : Prop} {f : p → roption α} (h : ¬p) : assert p f = none :=\n sorry\n\ntheorem mem_bind {α : Type u_1} {β : Type u_2} {f : roption α} {g : α → roption β} {a : α} {b : β} :\n a ∈ f → b ∈ g a → b ∈ roption.bind f g :=\n sorry\n\n@[simp] theorem mem_bind_iff {α : Type u_1} {β : Type u_2} {f : roption α} {g : α → roption β}\n {b : β} : b ∈ roption.bind f g ↔ ∃ (a : α), ∃ (H : a ∈ f), b ∈ g a :=\n sorry\n\n@[simp] theorem bind_none {α : Type u_1} {β : Type u_2} (f : α → roption β) :\n roption.bind none f = none :=\n sorry\n\n@[simp] theorem bind_some {α : Type u_1} {β : Type u_2} (a : α) (f : α → roption β) :\n roption.bind (some a) f = f a :=\n sorry\n\ntheorem bind_some_eq_map {α : Type u_1} {β : Type u_2} (f : α → β) (x : roption α) :\n roption.bind x (some ∘ f) = map f x :=\n sorry\n\ntheorem bind_assoc {α : Type u_1} {β : Type u_2} {γ : Type u_3} (f : roption α) (g : α → roption β)\n (k : β → roption γ) :\n roption.bind (roption.bind f g) k = roption.bind f fun (x : α) => roption.bind (g x) k :=\n sorry\n\n@[simp] theorem bind_map {α : Type u_1} {β : Type u_2} {γ : Type u_3} (f : α → β) (x : roption α)\n (g : β → roption γ) : roption.bind (map f x) g = roption.bind x fun (y : α) => g (f y) :=\n sorry\n\n@[simp] theorem map_bind {α : Type u_1} {β : Type u_2} {γ : Type u_3} (f : α → roption β)\n (x : roption α) (g : β → γ) :\n map g (roption.bind x f) = roption.bind x fun (y : α) => map g (f y) :=\n sorry\n\ntheorem map_map {α : Type u_1} {β : Type u_2} {γ : Type u_3} (g : β → γ) (f : α → β)\n (o : roption α) : map g (map f o) = map (g ∘ f) o :=\n sorry\n\nprotected instance monad : Monad roption :=\n { toApplicative :=\n { toFunctor := { map := map, mapConst := fun (α β : Type u_1) => map ∘ function.const β },\n toPure := { pure := some },\n toSeq :=\n { seq :=\n fun (α β : Type u_1) (f : roption (α → β)) (x : roption α) =>\n roption.bind f fun (_x : α → β) => map _x x },\n toSeqLeft :=\n { seqLeft :=\n fun (α β : Type u_1) (a : roption α) (b : roption β) =>\n (fun (α β : Type u_1) (f : roption (α → β)) (x : roption α) =>\n roption.bind f fun (_x : α → β) => map _x x)\n β α (map (function.const β) a) b },\n toSeqRight :=\n { seqRight :=\n fun (α β : Type u_1) (a : roption α) (b : roption β) =>\n (fun (α β : Type u_1) (f : roption (α → β)) (x : roption α) =>\n roption.bind f fun (_x : α → β) => map _x x)\n β β (map (function.const α id) a) b } },\n toBind := { bind := roption.bind } }\n\nprotected instance is_lawful_monad : is_lawful_monad roption :=\n is_lawful_monad.mk bind_some bind_assoc\n\ntheorem map_id' {α : Type u_1} {f : α → α} (H : ∀ (x : α), f x = x) (o : roption α) : map f o = o :=\n eq.mpr (id (Eq._oldrec (Eq.refl (map f o = o)) ((fun (this : f = id) => this) (funext H))))\n (id_map o)\n\n@[simp] theorem bind_some_right {α : Type u_1} (x : roption α) : roption.bind x some = x := sorry\n\n@[simp] theorem pure_eq_some {α : Type u_1} (a : α) : pure a = some a := rfl\n\n@[simp] theorem ret_eq_some {α : Type u_1} (a : α) : return a = some a := rfl\n\n@[simp] theorem map_eq_map {α : Type u_1} {β : Type u_1} (f : α → β) (o : roption α) :\n f <$> o = map f o :=\n rfl\n\n@[simp] theorem bind_eq_bind {α : Type u_1} {β : Type u_1} (f : roption α) (g : α → roption β) :\n f >>= g = roption.bind f g :=\n rfl\n\ntheorem bind_le {β : Type u_2} {α : Type u_2} (x : roption α) (f : α → roption β) (y : roption β) :\n x >>= f ≤ y ↔ ∀ (a : α), a ∈ x → f a ≤ y :=\n sorry\n\nprotected instance monad_fail : monad_fail roption :=\n monad_fail.mk fun (_x : Type u_1) (_x_1 : string) => none\n\n/- `restrict p o h` replaces the domain of `o` with `p`, and is well defined when\n `p` implies `o` is defined. -/\n\ndef restrict {α : Type u_1} (p : Prop) (o : roption α) : (p → dom o) → roption α := sorry\n\n@[simp] theorem mem_restrict {α : Type u_1} (p : Prop) (o : roption α) (h : p → dom o) (a : α) :\n a ∈ restrict p o h ↔ p ∧ a ∈ o :=\n sorry\n\n/-- `unwrap o` gets the value at `o`, ignoring the condition.\n (This function is unsound.) -/\ntheorem assert_defined {α : Type u_1} {p : Prop} {f : p → roption α} (h : p) :\n dom (f h) → dom (assert p f) :=\n exists.intro\n\ntheorem bind_defined {α : Type u_1} {β : Type u_2} {f : roption α} {g : α → roption β} (h : dom f) :\n dom (g (get f h)) → dom (roption.bind f g) :=\n assert_defined\n\n@[simp] theorem bind_dom {α : Type u_1} {β : Type u_2} {f : roption α} {g : α → roption β} :\n dom (roption.bind f g) ↔ ∃ (h : dom f), dom (g (get f h)) :=\n iff.rfl\n\nend roption\n\n\n/-- `pfun α β`, or `α →. β`, is the type of partial functions from\n `α` to `β`. It is defined as `α → roption β`. -/\ndef pfun (α : Type u_1) (β : Type u_2) := α → roption β\n\ninfixr:25 \" →. \" => Mathlib.pfun\n\nnamespace pfun\n\n\nprotected instance inhabited {α : Type u_1} {β : Type u_2} : Inhabited (α →. β) :=\n { default := fun (a : α) => roption.none }\n\n/-- The domain of a partial function -/\ndef dom {α : Type u_1} {β : Type u_2} (f : α →. β) : set α :=\n set_of fun (a : α) => roption.dom (f a)\n\ntheorem mem_dom {α : Type u_1} {β : Type u_2} (f : α →. β) (x : α) :\n x ∈ dom f ↔ ∃ (y : β), y ∈ f x :=\n sorry\n\ntheorem dom_eq {α : Type u_1} {β : Type u_2} (f : α →. β) :\n dom f = set_of fun (x : α) => ∃ (y : β), y ∈ f x :=\n set.ext (mem_dom f)\n\n/-- Evaluate a partial function -/\ndef fn {α : Type u_1} {β : Type u_2} (f : α →. β) (x : α) (h : dom f x) : β := roption.get (f x) h\n\n/-- Evaluate a partial function to return an `option` -/\ndef eval_opt {α : Type u_1} {β : Type u_2} (f : α →. β) [D : decidable_pred (dom f)] (x : α) :\n Option β :=\n roption.to_option (f x)\n\n/-- Partial function extensionality -/\ntheorem ext' {α : Type u_1} {β : Type u_2} {f : α →. β} {g : α →. β}\n (H1 : ∀ (a : α), a ∈ dom f ↔ a ∈ dom g)\n (H2 : ∀ (a : α) (p : dom f a) (q : dom g a), fn f a p = fn g a q) : f = g :=\n funext fun (a : α) => roption.ext' (H1 a) (H2 a)\n\ntheorem ext {α : Type u_1} {β : Type u_2} {f : α →. β} {g : α →. β}\n (H : ∀ (a : α) (b : β), b ∈ f a ↔ b ∈ g a) : f = g :=\n funext fun (a : α) => roption.ext (H a)\n\n/-- Turn a partial function into a function out of a subtype -/\ndef as_subtype {α : Type u_1} {β : Type u_2} (f : α →. β) (s : ↥(dom f)) : β := fn f ↑s sorry\n\n/-- The set of partial functions `α →. β` is equivalent to\nthe set of pairs `(p : α → Prop, f : subtype p → β)`. -/\ndef equiv_subtype {α : Type u_1} {β : Type u_2} :\n (α →. β) ≃ sigma fun (p : α → Prop) => Subtype p → β :=\n equiv.mk (fun (f : α →. β) => sigma.mk (fun (a : α) => roption.dom (f a)) (as_subtype f))\n (fun (f : sigma fun (p : α → Prop) => Subtype p → β) (x : α) =>\n roption.mk (sigma.fst f x) fun (h : sigma.fst f x) => sigma.snd f { val := x, property := h })\n sorry sorry\n\ntheorem as_subtype_eq_of_mem {α : Type u_1} {β : Type u_2} {f : α →. β} {x : α} {y : β}\n (fxy : y ∈ f x) (domx : x ∈ dom f) : as_subtype f { val := x, property := domx } = y :=\n roption.mem_unique (roption.get_mem (as_subtype._proof_1 f { val := x, property := domx })) fxy\n\n/-- Turn a total function into a partial function -/\nprotected def lift {α : Type u_1} {β : Type u_2} (f : α → β) : α →. β :=\n fun (a : α) => roption.some (f a)\n\nprotected instance has_coe {α : Type u_1} {β : Type u_2} : has_coe (α → β) (α →. β) :=\n has_coe.mk pfun.lift\n\n@[simp] theorem lift_eq_coe {α : Type u_1} {β : Type u_2} (f : α → β) : pfun.lift f = ↑f := rfl\n\n@[simp] theorem coe_val {α : Type u_1} {β : Type u_2} (f : α → β) (a : α) :\n coe f a = roption.some (f a) :=\n rfl\n\n/-- The graph of a partial function is the set of pairs\n `(x, f x)` where `x` is in the domain of `f`. -/\ndef graph {α : Type u_1} {β : Type u_2} (f : α →. β) : set (α × β) :=\n set_of fun (p : α × β) => prod.snd p ∈ f (prod.fst p)\n\ndef graph' {α : Type u_1} {β : Type u_2} (f : α →. β) : rel α β := fun (x : α) (y : β) => y ∈ f x\n\n/-- The range of a partial function is the set of values\n `f x` where `x` is in the domain of `f`. -/\ndef ran {α : Type u_1} {β : Type u_2} (f : α →. β) : set β :=\n set_of fun (b : β) => ∃ (a : α), b ∈ f a\n\n/-- Restrict a partial function to a smaller domain. -/\ndef restrict {α : Type u_1} {β : Type u_2} (f : α →. β) {p : set α} (H : p ⊆ dom f) : α →. β :=\n fun (x : α) => roption.restrict (x ∈ p) (f x) H\n\n@[simp] theorem mem_restrict {α : Type u_1} {β : Type u_2} {f : α →. β} {s : set α} (h : s ⊆ dom f)\n (a : α) (b : β) : b ∈ restrict f h a ↔ a ∈ s ∧ b ∈ f a :=\n sorry\n\ndef res {α : Type u_1} {β : Type u_2} (f : α → β) (s : set α) : α →. β :=\n restrict (pfun.lift f) (set.subset_univ s)\n\ntheorem mem_res {α : Type u_1} {β : Type u_2} (f : α → β) (s : set α) (a : α) (b : β) :\n b ∈ res f s a ↔ a ∈ s ∧ f a = b :=\n sorry\n\ntheorem res_univ {α : Type u_1} {β : Type u_2} (f : α → β) : res f set.univ = ↑f := rfl\n\ntheorem dom_iff_graph {α : Type u_1} {β : Type u_2} (f : α →. β) (x : α) :\n x ∈ dom f ↔ ∃ (y : β), (x, y) ∈ graph f :=\n roption.dom_iff_mem\n\ntheorem lift_graph {α : Type u_1} {β : Type u_2} {f : α → β} {a : α} {b : β} :\n (a, b) ∈ graph ↑f ↔ f a = b :=\n sorry\n\n/-- The monad `pure` function, the total constant `x` function -/\nprotected def pure {α : Type u_1} {β : Type u_2} (x : β) : α →. β := fun (_x : α) => roption.some x\n\n/-- The monad `bind` function, pointwise `roption.bind` -/\ndef bind {α : Type u_1} {β : Type u_2} {γ : Type u_3} (f : α →. β) (g : β → α →. γ) : α →. γ :=\n fun (a : α) => roption.bind (f a) fun (b : β) => g b a\n\n/-- The monad `map` function, pointwise `roption.map` -/\ndef map {α : Type u_1} {β : Type u_2} {γ : Type u_3} (f : β → γ) (g : α →. β) : α →. γ :=\n fun (a : α) => roption.map f (g a)\n\nprotected instance monad {α : Type u_1} : Monad (pfun α) :=\n { toApplicative :=\n { toFunctor := { map := map, mapConst := fun (α_1 β : Type u_2) => map ∘ function.const β },\n toPure := { pure := pfun.pure },\n toSeq :=\n { seq :=\n fun (α_1 β : Type u_2) (f : α →. α_1 → β) (x : α →. α_1) =>\n bind f fun (_x : α_1 → β) => map _x x },\n toSeqLeft :=\n { seqLeft :=\n fun (α_1 β : Type u_2) (a : α →. α_1) (b : α →. β) =>\n (fun (α_2 β : Type u_2) (f : α →. α_2 → β) (x : α →. α_2) =>\n bind f fun (_x : α_2 → β) => map _x x)\n β α_1 (map (function.const β) a) b },\n toSeqRight :=\n { seqRight :=\n fun (α_1 β : Type u_2) (a : α →. α_1) (b : α →. β) =>\n (fun (α_2 β : Type u_2) (f : α →. α_2 → β) (x : α →. α_2) =>\n bind f fun (_x : α_2 → β) => map _x x)\n β β (map (function.const α_1 id) a) b } },\n toBind := { bind := bind } }\n\nprotected instance is_lawful_monad {α : Type u_1} : is_lawful_monad (pfun α) :=\n is_lawful_monad.mk\n (fun (β γ : Type u_2) (x : β) (f : β → α →. γ) =>\n funext fun (a : α) => roption.bind_some a (f x))\n fun (β γ δ : Type u_2) (f : α →. β) (g : β → α →. γ) (k : γ → α →. δ) =>\n funext fun (a : α) => roption.bind_assoc (f a) (fun (b : β) => g b a) fun (b : γ) => k b a\n\ntheorem pure_defined {α : Type u_1} {β : Type u_2} (p : set α) (x : β) : p ⊆ dom (pfun.pure x) :=\n set.subset_univ p\n\ntheorem bind_defined {α : Type u_1} {β : Type u_2} {γ : Type u_2} (p : set α) {f : α →. β}\n {g : β → α →. γ} (H1 : p ⊆ dom f) (H2 : ∀ (x : β), p ⊆ dom (g x)) : p ⊆ dom (f >>= g) :=\n fun (a : α) (ha : a ∈ p) => Exists.intro (H1 ha) (H2 (roption.get (f a) (H1 ha)) ha)\n\ndef fix {α : Type u_1} {β : Type u_2} (f : α →. β ⊕ α) : α →. β :=\n fun (a : α) =>\n roption.assert (acc (fun (x y : α) => sum.inr x ∈ f y) a)\n fun (h : acc (fun (x y : α) => sum.inr x ∈ f y) a) =>\n well_founded.fix_F\n (fun (a : α) (IH : (y : α) → sum.inr y ∈ f a → roption β) =>\n roption.assert (roption.dom (f a))\n fun (hf : roption.dom (f a)) =>\n (fun (_x : β ⊕ α) (e : roption.get (f a) hf = _x) =>\n sum.cases_on _x\n (fun (b : β) (e : roption.get (f a) hf = sum.inl b) => roption.some b)\n (fun (a' : α) (e : roption.get (f a) hf = sum.inr a') => IH a' sorry) e)\n (roption.get (f a) hf) sorry)\n a h\n\ntheorem dom_of_mem_fix {α : Type u_1} {β : Type u_2} {f : α →. β ⊕ α} {a : α} {b : β}\n (h : b ∈ fix f a) : roption.dom (f a) :=\n sorry\n\ntheorem mem_fix_iff {α : Type u_1} {β : Type u_2} {f : α →. β ⊕ α} {a : α} {b : β} :\n b ∈ fix f a ↔ sum.inl b ∈ f a ∨ ∃ (a' : α), sum.inr a' ∈ f a ∧ b ∈ fix f a' :=\n sorry\n\ndef fix_induction {α : Type u_1} {β : Type u_2} {f : α →. β ⊕ α} {b : β} {C : α → Sort u_3} {a : α}\n (h : b ∈ fix f a)\n (H : (a : α) → b ∈ fix f a → ((a' : α) → b ∈ fix f a' → sum.inr a' ∈ f a → C a') → C a) : C a :=\n sorry\n\nend pfun\n\n\nnamespace pfun\n\n\ndef image {α : Type u_1} {β : Type u_2} (f : α →. β) (s : set α) : set β := rel.image (graph' f) s\n\ntheorem image_def {α : Type u_1} {β : Type u_2} (f : α →. β) (s : set α) :\n image f s = set_of fun (y : β) => ∃ (x : α), ∃ (H : x ∈ s), y ∈ f x :=\n rfl\n\ntheorem mem_image {α : Type u_1} {β : Type u_2} (f : α →. β) (y : β) (s : set α) :\n y ∈ image f s ↔ ∃ (x : α), ∃ (H : x ∈ s), y ∈ f x :=\n iff.rfl\n\ntheorem image_mono {α : Type u_1} {β : Type u_2} (f : α →. β) {s : set α} {t : set α} (h : s ⊆ t) :\n image f s ⊆ image f t :=\n rel.image_mono (graph' f) h\n\ntheorem image_inter {α : Type u_1} {β : Type u_2} (f : α →. β) (s : set α) (t : set α) :\n image f (s ∩ t) ⊆ image f s ∩ image f t :=\n rel.image_inter (graph' f) s t\n\ntheorem image_union {α : Type u_1} {β : Type u_2} (f : α →. β) (s : set α) (t : set α) :\n image f (s ∪ t) = image f s ∪ image f t :=\n rel.image_union (graph' f) s t\n\ndef preimage {α : Type u_1} {β : Type u_2} (f : α →. β) (s : set β) : set α :=\n rel.preimage (fun (x : α) (y : β) => y ∈ f x) s\n\ntheorem preimage_def {α : Type u_1} {β : Type u_2} (f : α →. β) (s : set β) :\n preimage f s = set_of fun (x : α) => ∃ (y : β), ∃ (H : y ∈ s), y ∈ f x :=\n rfl\n\ntheorem mem_preimage {α : Type u_1} {β : Type u_2} (f : α →. β) (s : set β) (x : α) :\n x ∈ preimage f s ↔ ∃ (y : β), ∃ (H : y ∈ s), y ∈ f x :=\n iff.rfl\n\ntheorem preimage_subset_dom {α : Type u_1} {β : Type u_2} (f : α →. β) (s : set β) :\n preimage f s ⊆ dom f :=\n sorry\n\ntheorem preimage_mono {α : Type u_1} {β : Type u_2} (f : α →. β) {s : set β} {t : set β}\n (h : s ⊆ t) : preimage f s ⊆ preimage f t :=\n rel.preimage_mono (fun (x : α) (y : β) => y ∈ f x) h\n\ntheorem preimage_inter {α : Type u_1} {β : Type u_2} (f : α →. β) (s : set β) (t : set β) :\n preimage f (s ∩ t) ⊆ preimage f s ∩ preimage f t :=\n rel.preimage_inter (fun (x : α) (y : β) => y ∈ f x) s t\n\ntheorem preimage_union {α : Type u_1} {β : Type u_2} (f : α →. β) (s : set β) (t : set β) :\n preimage f (s ∪ t) = preimage f s ∪ preimage f t :=\n rel.preimage_union (fun (x : α) (y : β) => y ∈ f x) s t\n\ntheorem preimage_univ {α : Type u_1} {β : Type u_2} (f : α →. β) : preimage f set.univ = dom f :=\n sorry\n\ndef core {α : Type u_1} {β : Type u_2} (f : α →. β) (s : set β) : set α := rel.core (graph' f) s\n\ntheorem core_def {α : Type u_1} {β : Type u_2} (f : α →. β) (s : set β) :\n core f s = set_of fun (x : α) => ∀ (y : β), y ∈ f x → y ∈ s :=\n rfl\n\ntheorem mem_core {α : Type u_1} {β : Type u_2} (f : α →. β) (x : α) (s : set β) :\n x ∈ core f s ↔ ∀ (y : β), y ∈ f x → y ∈ s :=\n iff.rfl\n\ntheorem compl_dom_subset_core {α : Type u_1} {β : Type u_2} (f : α →. β) (s : set β) :\n dom fᶜ ⊆ core f s :=\n fun (x : α) (hx : x ∈ (dom fᶜ)) (y : β) (fxy : graph' f x y) =>\n absurd (iff.mpr (mem_dom f x) (Exists.intro y fxy)) hx\n\ntheorem core_mono {α : Type u_1} {β : Type u_2} (f : α →. β) {s : set β} {t : set β} (h : s ⊆ t) :\n core f s ⊆ core f t :=\n rel.core_mono (graph' f) h\n\ntheorem core_inter {α : Type u_1} {β : Type u_2} (f : α →. β) (s : set β) (t : set β) :\n core f (s ∩ t) = core f s ∩ core f t :=\n rel.core_inter (graph' f) s t\n\ntheorem mem_core_res {α : Type u_1} {β : Type u_2} (f : α → β) (s : set α) (t : set β) (x : α) :\n x ∈ core (res f s) t ↔ x ∈ s → f x ∈ t :=\n sorry\n\ntheorem core_res {α : Type u_1} {β : Type u_2} (f : α → β) (s : set α) (t : set β) :\n core (res f s) t = sᶜ ∪ f ⁻¹' t :=\n sorry\n\ntheorem core_restrict {α : Type u_1} {β : Type u_2} (f : α → β) (s : set β) :\n core (↑f) s = f ⁻¹' s :=\n sorry\n\ntheorem preimage_subset_core {α : Type u_1} {β : Type u_2} (f : α →. β) (s : set β) :\n preimage f s ⊆ core f s :=\n sorry\n\ntheorem preimage_eq {α : Type u_1} {β : Type u_2} (f : α →. β) (s : set β) :\n preimage f s = core f s ∩ dom f :=\n sorry\n\ntheorem core_eq {α : Type u_1} {β : Type u_2} (f : α →. β) (s : set β) :\n core f s = preimage f s ∪ (dom fᶜ) :=\n sorry\n\ntheorem preimage_as_subtype {α : Type u_1} {β : Type u_2} (f : α →. β) (s : set β) :\n as_subtype f ⁻¹' s = subtype.val ⁻¹' preimage f s :=\n sorry\n\nend Mathlib", "meta": {"author": "AurelienSaue", "repo": "Mathlib4_auto", "sha": "590df64109b08190abe22358fabc3eae000943f2", "save_path": "github-repos/lean/AurelienSaue-Mathlib4_auto", "path": "github-repos/lean/AurelienSaue-Mathlib4_auto/Mathlib4_auto-590df64109b08190abe22358fabc3eae000943f2/Mathlib/data/pfun_auto.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.399811640739795, "lm_q2_score": 0.06371499025175957, "lm_q1q2_score": 0.02547399479227604}} {"text": "/-\nCopyright (c) 2020 Eric Wieser. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Eric Wieser\n-/\n\n/-!\n# Extra facts about `pprod`\n-/\n\nvariables {α : Sort*} {β : Sort*}\n\n@[simp] lemma pprod.mk.eta {p : pprod α β} : pprod.mk p.1 p.2 = p :=\npprod.cases_on p (λ a b, rfl)\n", "meta": {"author": "JLimperg", "repo": "aesop3", "sha": "a4a116f650cc7403428e72bd2e2c4cda300fe03f", "save_path": "github-repos/lean/JLimperg-aesop3", "path": "github-repos/lean/JLimperg-aesop3/aesop3-a4a116f650cc7403428e72bd2e2c4cda300fe03f/src/data/pprod.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.334589441253186, "lm_q2_score": 0.07585818733363134, "lm_q1q2_score": 0.025381348514439222}} {"text": "/-\nCopyright (c) 2020 Gabriel Ebner. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Gabriel Ebner\n-/\nimport Mathlib.Tactic.Lint.Basic\nimport Mathlib.Tactic.OpenPrivate\nimport Mathlib.Util.LibraryNote\nopen Lean Meta\n\nnamespace Mathlib.Tactic.Lint\n\n/-!\n# Linter for simplification lemmas\n\nThis files defines several linters that prevent common mistakes when declaring simp lemmas:\n\n * `simpNF` checks that the left-hand side of a simp lemma is not simplified by a different lemma.\n * `simpVarHead` checks that the head symbol of the left-hand side is not a variable.\n * `simpComm` checks that commutativity lemmas are not marked as simplification lemmas.\n-/\n\nstructure SimpTheoremInfo where\n hyps : Array Expr\n isConditional : Bool\n lhs : Expr\n rhs : Expr\n\ndef isConditionalHyps (eq : Expr) : List Expr → MetaM Bool\n | [] => pure false\n | h :: hs => do\n let ldecl ← getFVarLocalDecl h\n if !ldecl.binderInfo.isInstImplicit\n && !(← hs.anyM fun h' => do pure $ (← inferType h').containsFVar h.fvarId!)\n && !eq.containsFVar h.fvarId! then\n return true\n isConditionalHyps eq hs\n\nopen private preprocess from Lean.Meta.Tactic.Simp.SimpTheorems in\ndef withSimpTheoremInfos (ty : Expr) (k : SimpTheoremInfo → MetaM α) : MetaM (Array α) := withReducible do\n (← preprocess (← mkSorry ty true) ty (inv := false) (isGlobal := true))\n |>.toArray.mapM fun (_, ty') => do\n forallTelescopeReducing ty' fun hyps eq => do\n let some (_, lhs, rhs) := eq.eq? | throwError \"not an equality {eq}\"\n k {\n hyps, lhs, rhs\n isConditional := ← isConditionalHyps eq hyps.toList\n }\n\n/-- Checks whether two expressions are equal for the simplifier. That is,\nthey are reducibly-definitional equal, and they have the same head symbol. -/\ndef isSimpEq (a b : Expr) (whnfFirst := true) : MetaM Bool := withReducible do\n let a ← if whnfFirst then whnf a else pure a\n let b ← if whnfFirst then whnf b else pure b\n if a.getAppFn.constName? != b.getAppFn.constName? then return false\n isDefEq a b\n\ndef checkAllSimpTheoremInfos (ty : Expr) (k : SimpTheoremInfo → MetaM (Option MessageData)) : MetaM (Option MessageData) := do\n let errors := (← withSimpTheoremInfos ty fun i => do (← k i).mapM addMessageContextFull).filterMap id\n if errors.isEmpty then\n return none\n else\n return MessageData.joinSep errors.toList Format.line\n\ndef isSimpTheorem (declName : Name) : MetaM Bool := do\n pure $ (← getSimpTheorems).lemmaNames.contains declName\n\nopen Lean.Meta.DiscrTree\npartial def trieElements : Trie α → StateT (Array α) Id Unit\n | Trie.node vs children => do\n modify (· ++ vs)\n for (_, child) in children do\n trieElements child\n\ndef elements (d : DiscrTree α) : StateT (Array α) Id Unit := do\n for (_, child) in d.root.toList do\n trieElements child\n\nopen Std\n\n-- In Lean 4, the simplifier adds auxiliary lemmas if the declaration is not an equation.\n-- For example, for `decl : a ↔ b` it generates `decl._auxLemma.1 : a = b`.\n-- This function computes the map ``{`decl._auxLemma.1 ↦ `decl}``\ndef constToSimpDeclMap (ctx : Simp.Context) : HashMap Name Name := Id.run do\n let mut map : HashMap Name Name := {}\n for sls' in ctx.simpTheorems do\n for sls in [sls'.pre, sls'.post] do\n for sl in ((elements sls).run #[]).2 do\n if let some declName := sl.name? then\n if let some auxDeclName := sl.proof.getAppFn.constName? then\n map := map.insert auxDeclName declName\n return map\n\ndef isEqnLemma? (n : Name) : Option Name :=\n if n.isStr && n.getString!.startsWith \"_eq_\" then\n n.getPrefix\n else\n none\n\ndef heuristicallyExtractSimpTheoremsCore (ctx : Simp.Context) (constToSimpDecl : HashMap Name Name) (prf : Expr) : Array Name := Id.run do\n let mut cnsts : HashSet Name := {}\n for c in prf.getUsedConstants do\n if ctx.simpTheorems.isDeclToUnfold c then\n cnsts := cnsts.insert c\n else if ctx.congrTheorems.lemmas.contains c then\n cnsts := cnsts.insert c\n else if let some c' := constToSimpDecl.find? c then\n cnsts := cnsts.insert c'\n else if let some c' := isEqnLemma? c then\n cnsts := cnsts.insert c'\n return cnsts.toArray\n\n@[inline] def heuristicallyExtractSimpTheorems (ctx : Simp.Context) (prf : Expr) : Array Name :=\n heuristicallyExtractSimpTheoremsCore ctx (constToSimpDeclMap ctx) prf\n\ndef decorateError (msg : MessageData) (k : MetaM α) : MetaM α := do\n try k catch e => throw e\n\ndef formatLemmas (lems : Array Name) : CoreM MessageData := do\n toMessageData <$> lems.mapM mkConstWithLevelParams\n\n/-- A linter for simp lemmas whose lhs is not in simp-normal form, and which hence never fire. -/\n@[mathlibLinter] def simpNF : Linter where\n noErrorsFound := \"All left-hand sides of simp lemmas are in simp-normal form.\"\n errorsFound := \"SOME SIMP LEMMAS ARE NOT IN SIMP-NORMAL FORM.\nsee note [simp-normal form] for tips how to debug this.\nhttps://leanprover-community.github.io/mathlib_docs/notes.html#simp-normal%20form\"\n\n test := fun declName => do\n unless ← isSimpTheorem declName do return none\n -- TODO: equation lemmas\n let ctx ← Simp.Context.mkDefault\n checkAllSimpTheoremInfos (← getConstInfo declName).type fun {lhs, rhs, isConditional, ..} => do\n let ⟨lhs', prf1⟩ ← decorateError \"simplify fails on left-hand side:\" <| simp lhs ctx\n let prf1_lems := heuristicallyExtractSimpTheorems ctx (prf1.getD (mkBVar 0))\n if prf1_lems.contains declName then return none\n let ⟨rhs', prf2⟩ ← decorateError \"simplify fails on right-hand side:\" <| simp rhs ctx\n let lhs'_eq_rhs' ← isSimpEq lhs' rhs' (whnfFirst := false)\n let lhs_in_nf ← isSimpEq lhs' lhs\n if lhs'_eq_rhs' then do\n if prf1.isNone then return none -- TODO: cannot detect used rfl-lemmas\n let used_lemmas := heuristicallyExtractSimpTheorems ctx <|\n mkApp (prf1.getD (mkBVar 0)) (prf2.getD (mkBVar 0))\n return m!\"simp can prove this:\n by simp only {← formatLemmas used_lemmas}\nOne of the lemmas above could be a duplicate.\nIf that's not the case try reordering lemmas or adding @[priority].\n\"\n else if ¬ lhs_in_nf then do\n return m!\"Left-hand side simplifies from\n {lhs}\nto\n {lhs'}\nusing\n {← formatLemmas prf1_lems}\nTry to change the left-hand side to the simplified term!\n\"\n else if !isConditional && lhs == lhs' then\n return m!\"Left-hand side does not simplify.\nYou need to debug this yourself using `set_option trace.Meta.Tactic.simp.rewrite true`\"\n else\n return none\n\nlibrary_note \"simp-normal form\" /--\nThis note gives you some tips to debug any errors that the simp-normal form linter raises.\n\nThe reason that a lemma was considered faulty is because its left-hand side is not in simp-normal\nform.\nThese lemmas are hence never used by the simplifier.\n\nThis linter gives you a list of other simp lemmas: look at them!\n\nHere are some tips depending on the error raised by the linter:\n\n 1. 'the left-hand side reduces to XYZ':\n you should probably use XYZ as the left-hand side.\n\n 2. 'simp can prove this':\n This typically means that lemma is a duplicate, or is shadowed by another lemma:\n\n 2a. Always put more general lemmas after specific ones:\n ```\n @[simp] lemma zero_add_zero : 0 + 0 = 0 := rfl\n @[simp] lemma add_zero : x + 0 = x := rfl\n ```\n\n And not the other way around! The simplifier always picks the last matching lemma.\n\n 2b. You can also use `@[priority]` instead of moving simp-lemmas around in the file.\n\n Tip: the default priority is 1000.\n Use `@[priority 1100]` instead of moving a lemma down,\n and `@[priority 900]` instead of moving a lemma up.\n\n 2c. Conditional simp lemmas are tried last. If they are shadowed\n just remove the `simp` attribute.\n\n 2d. If two lemmas are duplicates, the linter will complain about the first one.\n Try to fix the second one instead!\n (You can find it among the other simp lemmas the linter prints out!)\n\n 3. 'try_for tactic failed, timeout':\n This typically means that there is a loop of simp lemmas.\n Try to apply squeeze_simp to the right-hand side (removing this lemma from the simp set) to see\n what lemmas might be causing the loop.\n\n Another trick is to `set_option trace.simplify.rewrite true` and\n then apply `try_for 10000 { simp }` to the right-hand side. You will\n see a periodic sequence of lemma applications in the trace message.\n-/\n\n/--\nA linter for simp lemmas whose lhs has a variable as head symbol,\nand which hence never fire.\n-/\n@[mathlibLinter] def simpVarHead : Linter where\n noErrorsFound :=\n \"No left-hand sides of a simp lemma has a variable as head symbol.\"\n errorsFound := \"LEFT-HAND SIDE HAS VARIABLE AS HEAD SYMBOL.\nSome simp lemmas have a variable as head symbol of the left-hand side:\"\n test := fun declName => do\n unless ← isSimpTheorem declName do return none\n checkAllSimpTheoremInfos (← getConstInfo declName).type fun {lhs, ..} => do\n let headSym := lhs.getAppFn\n unless headSym.isFVar do return none\n return m!\"Left-hand side has variable as head symbol: {headSym}\"\n\n/-- A linter for commutativity lemmas that are marked simp. -/\n@[mathlibLinter] def simpComm : Linter where\n noErrorsFound := \"No commutativity lemma is marked simp.\"\n errorsFound := \"COMMUTATIVITY LEMMA IS SIMP.\nSome commutativity lemmas are simp lemmas:\"\n test := fun declName => withReducible do\n unless ← isSimpTheorem declName do return none\n let ty := (← getConstInfo declName).type\n forallTelescopeReducing ty fun xs ty => do\n let some (_, lhs, rhs) := ty.eq? | return none\n unless lhs.getAppFn.constName? == rhs.getAppFn.constName? do return none\n let (mvars, bis, ty') ← forallMetaTelescopeReducing ty\n let some (_, lhs', rhs') := ty'.eq? | return none\n unless ← isDefEq rhs lhs' do return none\n unless ← withNewMCtxDepth (isDefEq rhs lhs') do return none\n -- ensure that the second application makes progress:\n if ← isDefEq lhs' rhs' then return none\n pure m!\"should not be marked simp\"\n", "meta": {"author": "JOSHCLUNE", "repo": "Keller_reduction", "sha": "dc392b3da352fc1ffcfbecb1d4717d05f5faed4a", "save_path": "github-repos/lean/JOSHCLUNE-Keller_reduction", "path": "github-repos/lean/JOSHCLUNE-Keller_reduction/Keller_reduction-dc392b3da352fc1ffcfbecb1d4717d05f5faed4a/Lean4_Clique/Mathlib/Mathlib/Tactic/Lint/Simp.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4378234991142019, "lm_q2_score": 0.057493280819038775, "lm_q1q2_score": 0.02517190938374698}} {"text": "/-\nCopyright 2021 Google LLC\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n -/\nimport measure_theory.measurable_space\n\nimport measure_theory.measure_space\nimport measure_theory.outer_measure\nimport measure_theory.lebesgue_measure\nimport measure_theory.integration\n\nimport measure_theory.borel_space\nimport data.set.countable\nimport formal_ml.nnreal\nimport formal_ml.sum\nimport formal_ml.lattice\nimport formal_ml.measurable_space\nimport formal_ml.classical\nimport data.equiv.list\nimport formal_ml.prod_measure\nimport formal_ml.finite_pi_measure\nimport formal_ml.probability_space\nimport formal_ml.random_variable_identical\nimport formal_ml.prod_probability_space\n\n/-\n This file proves that two IID distributions are identical.\n\n This result is subtle (i.e., why isn't it just by definition).\n IID variables can be constructed as IID, at which point they are \n obviously IID. However, they can be observed to be IID.\n\n \n\n Notice that, given X_1 and X_2, and Y_1 and Y_2, all coin flips.\n\n if X_1 is identical to Y_1, and X_2 is identical to Y_2, it is\n not enough to show that every event has the same probability. For\n example, maybe `Pr[ X_1 =ᵣ X_2] ≠ Pr[Y_1 =ᵣ Y_2]`. This kind of\n reasoning gives us a deeper understanding of the proof of VCD, which\n are based upon constructing an IID distribution through shuffling\n and subsampling.\n\n-/\n\n\n\n\ndef pi_base {δ:Type*} {π:δ → Type*} [M:Π (a:δ), measurable_space (π a)]\n (S:set (Π (a:δ), π a)):Prop := ∃ (f:Π (a:δ), set (π a)), (∀ i, measurable_set (f i)) ∧\n set.pi set.univ f = S\n\n\nlemma pi_base.closed_inter\n {δ:Type*} {π:δ → Type*} [M:Π (a:δ), measurable_space (π a)]\n (S T:set (Π (a:δ), π a)):pi_base S → pi_base T → pi_base (S ∩ T) :=\nbegin\n intros hS hT,\n cases hS with fS hS,\n cases hT with fT hT,\n apply exists.intro (λ i, (fS i) ∩ (fT i)),\n split,\n { intros i, apply measurable_set.inter, apply hS.left, apply hT.left },\n rw ← hS.right,\n rw ← hT.right,\n ext ω, split; intros h1; simp at h1; simp [h1],\nend\n\nlemma pi_base.empty\n {δ:Type*} [nonempty δ] {π:δ → Type*} [M:Π (a:δ), measurable_space (π a)]:\n pi_base (∅:set (Π (a : δ), π a)) := begin\n apply exists.intro (λ (d:δ), (∅:set (π d))),\n simp [set.pi], \nend\n\nlemma pi_base.univ\n {δ:Type*} [nonempty δ] {π:δ → Type*} [M:Π (a:δ), measurable_space (π a)]:\n pi_base (set.univ:set (Π (a : δ), π a)) := begin\n apply exists.intro (λ (d:δ), (set.univ:set (π d))),\n simp [set.pi], \nend\n\nlemma pi_base.closed_compl \n {δ:Type*} [fintype δ] [nonempty δ] {π:δ → Type*} [M:Π (a:δ), measurable_space (π a)]\n (s : set (Π (a : δ), π a)):\n pi_base s →\n (set.disjoint_union_closure pi_base) sᶜ := begin\n classical,\n intros h1,\n simp [pi_base] at h1,\n cases h1 with f h1,\n let f':(δ → bool) → set (Π (a : δ), π a) := \n (λ x, if (∀ (d:δ), x d) then ∅ else \n (set.pi (@set.univ δ) (λ (d:δ), if (x d) then (f d) else (f d)ᶜ))), \n begin\n have h2:sᶜ = set.Union f',\n { rw ← h1.right, simp [f'], ext; split; intros h2_1;\n simp at h2_1; simp [h2_1],\n { let i:δ → bool := (λ (d:δ), x d ∈ (f d)),\n apply exists.intro i,\n rw if_neg,\n simp [set.pi, i],\n intros d,\n cases classical.em (x d ∈ f d) with h2_2 h2_2,\n rw if_pos h2_2, apply h2_2,\n rw if_neg h2_2, apply h2_2,\n intros contra,\n cases h2_1 with d h2_1,\n apply h2_1,\n have contra_2 := contra d,\n simp [i] at contra_2,\n apply contra_2 },\n { cases h2_1 with i h2_1,\n cases classical.em (∀ (d : δ), (i d)) with h2_3 h2_3,\n { exfalso, rw if_pos h2_3 at h2_1, apply h2_1 },\n rw if_neg h2_3 at h2_1,\n rw classical.not_forall_iff_exists_not at h2_3,\n cases h2_3 with d h2_3,\n apply exists.intro d,\n simp [set.pi] at h2_1,\n have h2_4 := h2_1 d,\n rw if_neg h2_3 at h2_4,\n apply h2_4 } },\n rw h2,\n apply set.disjoint_union_closure_intro,\n intros b,\n { simp [f',pi_base],\n cases classical.em (∀ (d : δ), (b d)) with h3 h3,\n rw if_pos,\n apply pi_base.empty,\n apply h3,\n rw if_neg,\n { apply exists.intro (λ (d : δ), ite ↥(b d) (f d) (f d)ᶜ),\n rw and.comm,\n split,\n refl,\n intros d,\n simp,\n cases classical.em (b d) with h4 h4,\n rw if_pos,\n apply h1.left,\n apply h4,\n rw if_neg,\n apply measurable_set.compl,\n apply h1.left, apply h4 },\n apply h3 },\n intros b b' h_ne,\n simp [function.on_fun], rw disjoint_iff,\n simp,\n rw ← set.subset_empty_iff,\n rw set.subset_def,\n intros ω h_contra,\n exfalso,\n simp [f'] at h_contra,\n cases h_contra with h_contra_1 h_contra_2,\n cases classical.em (∀ (d : δ), (b d)) with h5 h5,\n { rw if_pos at h_contra_1,\n apply h_contra_1,\n apply h5 },\n rw if_neg h5 at h_contra_1,\n cases classical.em (∀ (d : δ), (b' d)) with h6 h6,\n { rw if_pos h6 at h_contra_2,\n apply h_contra_2 },\n rw if_neg h6 at h_contra_2,\n apply h_ne,\n simp [set.pi] at h_contra_1,\n simp [set.pi] at h_contra_2,\n ext i,\n have h_contra_1_i := h_contra_1 i,\n have h_contra_2_i := h_contra_2 i,\n destruct (b i); destruct (b' i);\n intros h_b'_i h_b_i;\n simp [h_b_i, h_b'_i];\n simp [h_b_i] at h_contra_1_i;\n simp [h_b'_i] at h_contra_2_i,\n apply h_contra_1_i h_contra_2_i,\n apply h_contra_2_i h_contra_1_i,\n end \nend\n\n\nlemma set.pi_as_preimage {δ:Type*} {π:δ → Type*} {f:Π (a:δ), set (π a)}:\n (set.pi set.univ f) = (⋂ (i:δ), (λ (d:Π (a:δ), π a), d i) ⁻¹' (f i)) := begin\n ext,split;intros A1; simp at A1; simp [A1],\nend\n\nlemma pi_base.measurable_set {δ:Type*} [encodable δ] {π:δ → Type*} \n [M:Π (a:δ), measurable_space (π a)]\n (S:set (Π (a:δ), π a)):pi_base S → measurable_set S :=\nbegin\n intros hS,\n cases hS with fS hS,\n cases hS with h_meas h_def,\n rw ← h_def,\n rw set.pi_as_preimage,\n apply measurable_set.Inter,\n intros b,\n have h_proj_meas:measurable (λ (d : Π (a : δ), π a), d b),\n { apply measurable_pi_apply },\n apply h_proj_meas,\n apply h_meas,\nend\n\nlemma pi_base.covers_generate {δ:Type*} [encodable δ] {π:δ → Type*} \n [M:Π (a:δ), measurable_space (π a)]\n (S:set (Π (a:δ), π a)):\n S ∈ \n (⋃ (i : δ),\n (measurable_space.comap (λ (b : Π (a : δ), (λ (a : δ), π a) a), b i)\n ((λ (a : δ), M a) i)).measurable_set') → \n pi_base S := begin\n intros h1,\n simp [pi_base],\n simp at h1,\n cases h1 with d h1,\n simp [measurable_space.comap] at h1,\n cases h1 with s h1,\n cases h1 with h1 h3,\n have h2:∀ (d':δ), ∃ (T:set (π d')), measurable_set T ∧\n (∀ (s':(Π (a:δ), π a)), s' ∈ S → s' d' ∈ T) ∧ (d' = d → T == s),\n { intros d',\n cases classical.em (d = d') with h2_1 h2_1,\n { subst d', apply exists.intro s, \n split,\n apply h1,\n split, \n intros s' h4, rw ← h3 at h4,\n simp at h4, apply h4, intros h5, refl },\n { apply exists.intro set.univ,\n split,\n apply measurable_set.univ,\n split,\n intros s' h6,\n simp,\n intros h2_1_not, exfalso, apply h2_1, rw h2_1_not, },\n },\n have h7 := classical.axiom_of_choice h2,\n cases h7 with f h7,\n apply exists.intro f,\n split,\n { intros d',\n apply (h7 d').left },\n { ext ω,\n simp [set.pi],split; intros h8,\n { rw ← h3,\n have h9:d = d := rfl,\n have h10 := (h7 d).right.right h9,\n simp at h10, rw ← h10, \n simp, apply h8 },\n { intros d',\n have h11 := (h7 d').right.left ω h8, apply h11 } },\nend\n\nlemma pi_base_eq_measurable_space_pi {δ:Type*} [encodable δ] {π:δ → Type*} \n [M:Π (a:δ), measurable_space (π a)]:\n @measurable_space.pi δ π M = measurable_space.generate_from pi_base :=\nbegin\n apply le_antisymm;\n apply measurable_space.generate_from_le;\n intros a h_a,\n { simp [measurable_space.generate_from],\n apply measurable_space.generate_measurable.basic,\n apply pi_base.covers_generate,\n simp at h_a, simp, cases h_a with i h_a, apply exists.intro i, apply h_a },\n { apply pi_base.measurable_set, apply h_a },\nend\n\nlemma pi_base_eq {δ:Type*} [fintype δ] {π:δ → Type*} [M:Π (a:δ), measurable_space (π a)]\n (S:measurable_setB (@measurable_space.pi δ π M)):pi_base S.val →\n ∃ (f:Π (b:δ), measurable_setB (M b)), (set.pi_measurable set.univ f) = S := begin\n intros h1,\n unfold pi_base at h1,\n cases h1 with g h1,\n cases h1 with h1 h2,\n let f := (λ (b:δ), @measurable_setB.mk _ _ (g b) (h1 b)),\n begin\n apply exists.intro f,\n apply subtype.eq,\n rw ← h2,\n simp [set.pi, set.pi_measurable, f],\n ext ω,split;intros h1; simp at h1; simp [h1]; intros i; apply h1,\n end\nend\n\nlemma pi_base_is_semialgebra {δ:Type*} [fintype δ] [nonempty δ] {π:δ → Type*} \n [M:Π (a:δ), measurable_space (π a)]:set.is_semialgebra (@pi_base δ π M) := {\n univ := pi_base.univ,\n empty := pi_base.empty,\n compl := pi_base.closed_compl,\n inter := pi_base.closed_inter,\n}\n\nlemma pi_union_all {Ω δ:Type*} [fintype δ] \n {P:probability_space Ω}\n {π:δ → Type*} [M:Π (a:δ), measurable_space (π a)]\n (f:Π (b:δ), measurable_setB (M b))\n {X:Π (b:δ), P →ᵣ (M b)}:\n (pi.random_variable_combine X ∈ᵣ (set.pi_measurable set.univ f)) =\n (∀ᵣ (b:δ), (X b) ∈ᵣ (f b)) := begin\n apply event.eq,\n simp [pi.random_variable_combine, set.pi_measurable, pi.measurable_fun],\n ext ω, split; intros h1; simp at h1; simp [h1],\nend\n\n \nlemma random_variable_independent_all {Ω β:Type*} {P:probability_space Ω} [fintype β]\n {γ:β → Type*} {M:Π (b:β), measurable_space (γ b)}\n (S:Π (b:β), measurable_setB (M b))\n {X:Π (b:β), P →ᵣ (M b)}:\n random_variable_independent X →\n Pr[∀ᵣ (b : β), X b ∈ᵣ S b] = finset.univ.prod (λ (b:β), Pr[X b ∈ᵣ S b]) := begin\n intros h1,\n simp [random_variable_independent] at h1,\n have h2 := h1 S,\n simp [independent_events] at h2,\n have h3 := h2 finset.univ,\n rw h3,\n refl,\nend\n \nlemma IID_identical_joint_base' {Ω₁ Ω₂ β γ:Type*} [fintype β] \n {P₁:probability_space Ω₁}\n {P₂:probability_space Ω₂}\n {M:measurable_space γ} \n {X₁:β → P₁ →ᵣ M} {X₂:β → P₂ →ᵣ M}\n (S:measurable_setB (@measurable_space.pi β (λ _, γ) (λ _, M))):\n pi_base S.val →\n (∀ (b:β), random_variable_identical (X₁ b) (X₂ b)) →\n (random_variables_IID X₁) →\n (random_variables_IID X₂) →\n (Pr[pi.random_variable_combine X₁ ∈ᵣ S] =\n Pr[pi.random_variable_combine X₂ ∈ᵣ S]) :=\nbegin\n intros h1 h2 h3 h4,\n have h5:=pi_base_eq S h1,\n cases h5 with f h5,\n rw ← h5,\n rw pi_union_all,\n rw pi_union_all,\n rw random_variable_independent_all,\n rw random_variable_independent_all,\n have h6:(λ (b : β), Pr[X₁ b ∈ᵣ f b]) = (λ (b : β), Pr[X₂ b ∈ᵣ f b]),\n { ext1 b, apply h2, },\n rw h6,\n apply h4.left,\n apply h3.left,\nend\n\n\nlemma IID_identical_joint' {Ω₁ Ω₂ β γ:Type*} [fintype β] [nonempty β] \n {P₁:probability_space Ω₁}\n {P₂:probability_space Ω₂}\n {M:measurable_space γ} \n {X₁:β → P₁ →ᵣ M} {X₂:β → P₂ →ᵣ M}:\n (∀ (b:β), random_variable_identical (X₁ b) (X₂ b)) →\n (random_variables_IID X₁) →\n (random_variables_IID X₂) →\n random_variable_identical (pi.random_variable_combine X₁)\n (pi.random_variable_combine X₂)\n :=\nbegin\n intros h1 h2 h3,\n haveI:encodable β := fintype.encodable β,\n apply random_variable_identical_on_semialgebra' pi_base, \n --apply pi_base\n apply pi_base.closed_inter,\n apply pi_base.closed_compl,\n apply pi_base.empty,\n apply pi_base.univ,\n { \n apply pi_base_eq_measurable_space_pi },\n intros T h_T,\n apply IID_identical_joint_base',\n apply h_T,\n apply h1,\n apply h2,\n apply h3,\nend\n\n\n\nlemma IID_identical_joint {Ω₁ Ω₂ β γ:Type*} [fintype β] [nonempty β]\n {P₁:probability_space Ω₁}\n {P₂:probability_space Ω₂}\n {M:measurable_space γ} \n {X₁:β → P₁ →ᵣ M} {X₂:β → P₂ →ᵣ M}: \n (∃ (b₁ b₂:β), random_variable_identical (X₁ b₁) (X₂ b₂)) →\n (random_variables_IID X₁) →\n (random_variables_IID X₂) →\n random_variable_identical (pi.random_variable_combine X₁)\n (pi.random_variable_combine X₂) :=\nbegin\n intros h1 h2 h3,\n apply IID_identical_joint',\n intros b,\n cases h1 with b₁ h1,\n cases h1 with b₂ h1,\n have h4:random_variable_identical (X₁ b) (X₁ b₁),\n { apply h2.right },\n apply random_variable_identical.trans h4,\n apply random_variable_identical.trans h1,\n apply h3.right,\n apply h2,\n apply h3,\nend\n\n", "meta": {"author": "google", "repo": "formal-ml", "sha": "630011d19fdd9539c8d6493a69fe70af5d193590", "save_path": "github-repos/lean/google-formal-ml", "path": "github-repos/lean/google-formal-ml/formal-ml-630011d19fdd9539c8d6493a69fe70af5d193590/src/formal_ml/random_variable_identical_IID.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.05033063420001163, "lm_q1q2_score": 0.025165317100005816}} {"text": "example (P Q R : Type) : (P → (Q → R)) → ((P → Q) → (P → R)) := by\n intro p_qr\n intro p_q\n intro p\n apply p_qr\n case a =>\n exact p\n case a =>\n apply p_q\n exact p\n\nexample (P Q R : Type) : (P → (Q → R)) → ((P → Q) → (P → R)) := by\n intro p_qr\n intro p_q\n intro p\n apply p_qr\n . exact p\n apply p_q\n exact p", "meta": {"author": "DevinTDHa", "repo": "natural-number-game-lean4", "sha": "7c5d06b4055fed266aeb709ecf801fad10a811bf", "save_path": "github-repos/lean/DevinTDHa-natural-number-game-lean4", "path": "github-repos/lean/DevinTDHa-natural-number-game-lean4/natural-number-game-lean4-7c5d06b4055fed266aeb709ecf801fad10a811bf/function_world/level6.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40356683938849797, "lm_q2_score": 0.06187598269623767, "lm_q1q2_score": 0.024971094770778027}} {"text": "/-\nCopyright (c) 2019 Paul-Nicolas Madelaine. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Paul-Nicolas Madelaine, Robert Y. Lewis\n-/\nimport tactic.converter.interactive\nimport tactic.hint\n\n/-!\n# A tactic for normalizing casts inside expressions\n\nThis tactic normalizes casts inside expressions.\nIt can be thought of as a call to the simplifier with a specific set of lemmas to\nmove casts upwards in the expression.\nIt has special handling of numerals and a simple heuristic to help moving\ncasts \"past\" binary operators.\nContrary to simp, it should be safe to use as a non-terminating tactic.\n\nThe algorithm implemented here is described in the paper\n.\n\n## Important definitions\n* `tactic.interactive.norm_cast`\n* `tactic.interactive.push_cast`\n* `tactic.interactive.exact_mod_cast`\n* `tactic.interactive.apply_mod_cast`\n* `tactic.interactive.rw_mod_cast`\n* `tactic.interactive.assumption_mod_cast`\n-/\n\nsetup_tactic_parser\n\nnamespace tactic\n\n/--\nRuns `mk_instance` with a time limit.\n\nThis is a work around to the fact that in some cases\nmk_instance times out instead of failing,\nfor example: `has_lift_t ℤ ℕ`\n\n`mk_instance_fast` is used when we assume the type class search\nshould end instantly.\n-/\nmeta def mk_instance_fast (e : expr) (timeout := 1000) : tactic expr :=\ntry_for timeout (mk_instance e)\n\nend tactic\n\nnamespace norm_cast\n\nopen tactic expr\n\ndeclare_trace norm_cast\n\n/--\nOutput a trace message if `trace.norm_cast` is enabled.\n-/\nmeta def trace_norm_cast {α} [has_to_tactic_format α] (msg : string) (a : α) : tactic unit :=\nwhen_tracing `norm_cast $ do\na ← pp a,\ntrace (\"[norm_cast] \" ++ msg ++ a : format)\n\nmk_simp_attribute push_cast \"The `push_cast` simp attribute uses `norm_cast` lemmas\nto move casts toward the leaf nodes of the expression.\"\n\n/--\n`label` is a type used to classify `norm_cast` lemmas.\n* elim lemma: LHS has 0 head coes and ≥ 1 internal coe\n* move lemma: LHS has 1 head coe and 0 internal coes, RHS has 0 head coes and ≥ 1 internal coes\n* squash lemma: LHS has ≥ 1 head coes and 0 internal coes, RHS has fewer head coes\n-/\n@[derive [decidable_eq, has_reflect, inhabited]]\ninductive label\n| elim : label\n| move : label\n| squash : label\n\nnamespace label\n\n/-- Convert `label` into `string`. -/\nprotected def to_string : label → string\n| elim := \"elim\"\n| move := \"move\"\n| squash := \"squash\"\n\ninstance : has_to_string label := ⟨label.to_string⟩\ninstance : has_repr label := ⟨label.to_string⟩\nmeta instance : has_to_format label := ⟨λ l, l.to_string⟩\n\n/-- Convert `string` into `label`. -/\ndef of_string : string -> option label\n| \"elim\" := some elim\n| \"move\" := some move\n| \"squash\" := some squash\n| _ := none\n\nend label\n\nopen label\n\n/-- Count how many coercions are at the top of the expression. -/\nmeta def count_head_coes : expr → ℕ\n| `(coe %%e) := count_head_coes e + 1\n| `(coe_sort %%e) := count_head_coes e + 1\n| `(coe_fn %%e) := count_head_coes e + 1\n| _ := 0\n\n/-- Count how many coercions are inside the expression, including the top ones. -/\nmeta def count_coes : expr → tactic ℕ\n| `(coe %%e) := (+1) <$> count_coes e\n| `(coe_sort %%e) := (+1) <$> count_coes e\n| `(coe_fn %%e) := (+1) <$> count_coes e\n| (app `(coe_fn %%e) x) := (+) <$> count_coes x <*> (+1) <$> count_coes e\n| (expr.lam n bi t e) := do\n l ← mk_local' n bi t,\n count_coes $ e.instantiate_var l\n| e := do\n as ← e.get_simp_args,\n list.sum <$> as.mmap count_coes\n\n/-- Count how many coercions are inside the expression, excluding the top ones. -/\nprivate meta def count_internal_coes (e : expr) : tactic ℕ := do\nncoes ← count_coes e,\npure $ ncoes - count_head_coes e\n\n/--\nClassifies a declaration of type `ty` as a `norm_cast` rule.\n-/\nmeta def classify_type (ty : expr) : tactic label := do\n(_, ty) ← open_pis ty,\n(lhs, rhs) ← match ty with\n | `(%%lhs = %%rhs) := pure (lhs, rhs)\n | `(%%lhs ↔ %%rhs) := pure (lhs, rhs)\n | _ := fail \"norm_cast: lemma must be = or ↔\"\n end,\nlhs_coes ← count_coes lhs,\nwhen (lhs_coes = 0) $ fail \"norm_cast: badly shaped lemma, lhs must contain at least one coe\",\nlet lhs_head_coes := count_head_coes lhs,\nlhs_internal_coes ← count_internal_coes lhs,\nlet rhs_head_coes := count_head_coes rhs,\nrhs_internal_coes ← count_internal_coes rhs,\nif lhs_head_coes = 0 then\n return elim\nelse if lhs_head_coes = 1 then do\n when (rhs_head_coes ≠ 0) $ fail \"norm_cast: badly shaped lemma, rhs can't start with coe\",\n if rhs_internal_coes = 0 then\n return squash\n else\n return move\nelse if rhs_head_coes < lhs_head_coes then do\n return squash\nelse do\n fail \"norm_cast: badly shaped shaped squash lemma, rhs must have fewer head coes than lhs\"\n\n/-- The cache for `norm_cast` attribute stores three `simp_lemma` objects. -/\nmeta structure norm_cast_cache :=\n(up : simp_lemmas)\n(down : simp_lemmas)\n(squash : simp_lemmas)\n\n/-- Empty `norm_cast_cache`. -/\nmeta def empty_cache : norm_cast_cache :=\n{ up := simp_lemmas.mk,\n down := simp_lemmas.mk,\n squash := simp_lemmas.mk, }\n\nmeta instance : inhabited norm_cast_cache := ⟨empty_cache⟩\n\n/-- `add_elim cache e` adds `e` as an `elim` lemma to `cache`. -/\nmeta def add_elim (cache : norm_cast_cache) (e : expr) : tactic norm_cast_cache :=\ndo\n new_up ← cache.up.add e,\n return\n { up := new_up,\n down := cache.down,\n squash := cache.squash, }\n\n/-- `add_move cache e` adds `e` as a `move` lemma to `cache`. -/\nmeta def add_move (cache : norm_cast_cache) (e : expr) : tactic norm_cast_cache :=\ndo\n new_up ← cache.up.add e tt,\n new_down ← cache.down.add e,\n return\n { up := new_up,\n down := new_down,\n squash := cache.squash, }\n\n/-- `add_squash cache e` adds `e` as an `squash` lemma to `cache`. -/\nmeta def add_squash (cache : norm_cast_cache) (e : expr) : tactic norm_cast_cache :=\ndo\n new_squash ← cache.squash.add e,\n new_down ← cache.down.add e,\n return\n { up := cache.up,\n down := new_down,\n squash := new_squash, }\n\n/--\nThe type of the `norm_cast` attribute.\nThe optional label is used to overwrite the classifier.\n-/\nmeta def norm_cast_attr_ty : Type := user_attribute norm_cast_cache (option label)\n\n/--\nEfficient getter for the `@[norm_cast]` attribute parameter that does not call `eval_expr`.\n\nSee Note [user attribute parameters].\n-/\nmeta def get_label_param (attr : norm_cast_attr_ty) (decl : name) : tactic (option label) := do\np ← attr.get_param_untyped decl,\nmatch p with\n| `(none) := pure none\n| `(some label.elim) := pure label.elim\n| `(some label.move) := pure label.move\n| `(some label.squash) := pure label.squash\n| _ := fail p\nend\n\n/--\n`add_lemma cache decl` infers the proper `norm_cast` attribute for `decl` and adds it to `cache`.\n-/\nmeta def add_lemma (attr : norm_cast_attr_ty) (cache : norm_cast_cache) (decl : name) :\n tactic norm_cast_cache :=\ndo\n e ← mk_const decl,\n param ← get_label_param attr decl,\n l ← param <|> (infer_type e >>= classify_type),\n match l with\n | elim := add_elim cache e\n | move := add_move cache e\n | squash := add_squash cache e\n end\n\n-- special lemmas to handle the ≥, > and ≠ operators\nprivate lemma ge_from_le {α} [has_le α] : ∀ (x y : α), x ≥ y ↔ y ≤ x := λ _ _, iff.rfl\nprivate lemma gt_from_lt {α} [has_lt α] : ∀ (x y : α), x > y ↔ y < x := λ _ _, iff.rfl\nprivate lemma ne_from_not_eq {α} : ∀ (x y : α), x ≠ y ↔ ¬(x = y) := λ _ _, iff.rfl\n\n/--\n`mk_cache names` creates a `norm_cast_cache`. It infers the proper `norm_cast` attributes\nfor names in `names`, and collects the lemmas attributed with specific `norm_cast` attributes.\n-/\nmeta def mk_cache (attr : thunk norm_cast_attr_ty) (names : list name) :\n tactic norm_cast_cache := do\n-- names has the declarations in reverse order\ncache ← names.mfoldr (λ name cache, add_lemma (attr ()) cache name) empty_cache,\n\n--some special lemmas to handle binary relations\nlet up := cache.up,\nup ← up.add_simp ``ge_from_le,\nup ← up.add_simp ``gt_from_lt,\nup ← up.add_simp ``ne_from_not_eq,\n\nlet down := cache.down,\ndown ← down.add_simp ``coe_coe,\n\npure { up := up, down := down, squash := cache.squash }\n\n/--\nThe `norm_cast` attribute.\n-/\n@[user_attribute] meta def norm_cast_attr : user_attribute norm_cast_cache (option label) :=\n{ name := `norm_cast,\n descr := \"attribute for norm_cast\",\n parser :=\n (do some l ← (label.of_string ∘ to_string) <$> ident, return l)\n <|> return none,\n after_set := some (λ decl prio persistent, do\n param ← get_label_param norm_cast_attr decl,\n match param with\n | some l :=\n when (l ≠ elim) $ simp_attr.push_cast.set decl () tt prio\n | none := do\n e ← mk_const decl,\n ty ← infer_type e,\n l ← classify_type ty,\n norm_cast_attr.set decl l persistent prio\n end),\n before_unset := some $ λ _ _, tactic.skip,\n cache_cfg := { mk_cache := mk_cache norm_cast_attr, dependencies := [] } }\n\n/-- Classify a declaration as a `norm_cast` rule. -/\nmeta def make_guess (decl : name) : tactic label :=\ndo\n e ← mk_const decl,\n ty ← infer_type e,\n classify_type ty\n\n/--\nGets the `norm_cast` classification label for a declaration. Applies the\noverride specified on the attribute, if necessary.\n-/\nmeta def get_label (decl : name) : tactic label :=\ndo\n param ← get_label_param norm_cast_attr decl,\n param <|> make_guess decl\n\nend norm_cast\n\nnamespace tactic.interactive\nopen norm_cast\n\n/--\n`push_cast` rewrites the expression to move casts toward the leaf nodes.\nFor example, `↑(a + b)` will be written to `↑a + ↑b`.\nEquivalent to `simp only with push_cast`.\nCan also be used at hypotheses.\n\n`push_cast` can also be used at hypotheses and with extra simp rules.\n\n```lean\nexample (a b : ℕ) (h1 : ((a + b : ℕ) : ℤ) = 10) (h2 : ((a + b + 0 : ℕ) : ℤ) = 10) :\n ((a + b : ℕ) : ℤ) = 10 :=\nbegin\n push_cast,\n push_cast at h1,\n push_cast [int.add_zero] at h2,\nend\n```\n-/\nmeta def push_cast (hs : parse tactic.simp_arg_list) (l : parse location) : tactic unit :=\ntactic.interactive.simp none none tt hs [`push_cast] l {discharger := tactic.assumption}\n\n\nend tactic.interactive\n\nnamespace norm_cast\nopen tactic expr\n\n/-- Prove `a = b` using the given simp set. -/\nmeta def prove_eq_using (s : simp_lemmas) (a b : expr) : tactic expr := do\n(a', a_a', _) ← simplify s [] a {fail_if_unchanged := ff},\n(b', b_b', _) ← simplify s [] b {fail_if_unchanged := ff},\non_exception (trace_norm_cast \"failed: \" (to_expr ``(%%a' = %%b') >>= pp)) $\n is_def_eq a' b' reducible,\nb'_b ← mk_eq_symm b_b',\nmk_eq_trans a_a' b'_b\n\n/-- Prove `a = b` by simplifying using move and squash lemmas. -/\nmeta def prove_eq_using_down (a b : expr) : tactic expr := do\ncache ← norm_cast_attr.get_cache,\ntrace_norm_cast \"proving: \" (to_expr ``(%%a = %%b) >>= pp),\nprove_eq_using cache.down a b\n\n/--\nThis is the main heuristic used alongside the elim and move lemmas.\nThe goal is to help casts move past operators by adding intermediate casts.\nAn expression of the shape: op (↑(x : α) : γ) (↑(y : β) : γ)\nis rewritten to: op (↑(↑(x : α) : β) : γ) (↑(y : β) : γ)\nwhen (↑(↑(x : α) : β) : γ) = (↑(x : α) : γ) can be proven with a squash lemma\n-/\nmeta def splitting_procedure : expr → tactic (expr × expr)\n| (app (app op x) y) :=\n(do\n `(@coe %%α %%δ %%coe1 %%xx) ← return x,\n `(@coe %%β %%γ %%coe2 %%yy) ← return y,\n success_if_fail $ is_def_eq α β,\n is_def_eq δ γ,\n\n (do\n coe3 ← mk_app `has_lift_t [α, β] >>= mk_instance_fast,\n new_x ← to_expr ``(@coe %%β %%δ %%coe2 (@coe %%α %%β %%coe3 %%xx)),\n let new_e := app (app op new_x) y,\n eq_x ← prove_eq_using_down x new_x,\n pr ← mk_congr_arg op eq_x,\n pr ← mk_congr_fun pr y,\n return (new_e, pr)\n ) <|> (do\n coe3 ← mk_app `has_lift_t [β, α] >>= mk_instance_fast,\n new_y ← to_expr ``(@coe %%α %%δ %%coe1 (@coe %%β %%α %%coe3 %%yy)),\n let new_e := app (app op x) new_y,\n eq_y ← prove_eq_using_down y new_y,\n pr ← mk_congr_arg (app op x) eq_y,\n return (new_e, pr)\n )\n) <|> (do\n `(@coe %%α %%β %%coe1 %%xx) ← return x,\n `(@has_one.one %%β %%h1) ← return y,\n h2 ← to_expr ``(has_one %%α) >>= mk_instance_fast,\n new_y ← to_expr ``(@coe %%α %%β %%coe1 (@has_one.one %%α %%h2)),\n eq_y ← prove_eq_using_down y new_y,\n let new_e := app (app op x) new_y,\n pr ← mk_congr_arg (app op x) eq_y,\n return (new_e, pr)\n ) <|> (do\n `(@coe %%α %%β %%coe1 %%xx) ← return x,\n `(@has_zero.zero %%β %%h1) ← return y,\n h2 ← to_expr ``(has_zero %%α) >>= mk_instance_fast,\n new_y ← to_expr ``(@coe %%α %%β %%coe1 (@has_zero.zero %%α %%h2)),\n eq_y ← prove_eq_using_down y new_y,\n let new_e := app (app op x) new_y,\n pr ← mk_congr_arg (app op x) eq_y,\n return (new_e, pr)\n) <|> (do\n `(@has_one.one %%β %%h1) ← return x,\n `(@coe %%α %%β %%coe1 %%xx) ← return y,\n h1 ← to_expr ``(has_one %%α) >>= mk_instance_fast,\n new_x ← to_expr ``(@coe %%α %%β %%coe1 (@has_one.one %%α %%h1)),\n eq_x ← prove_eq_using_down x new_x,\n let new_e := app (app op new_x) y,\n pr ← mk_congr_arg (lam `x binder_info.default β (app (app op (var 0)) y)) eq_x,\n return (new_e, pr)\n) <|> (do\n `(@has_zero.zero %%β %%h1) ← return x,\n `(@coe %%α %%β %%coe1 %%xx) ← return y,\n h1 ← to_expr ``(has_zero %%α) >>= mk_instance_fast,\n new_x ← to_expr ``(@coe %%α %%β %%coe1 (@has_zero.zero %%α %%h1)),\n eq_x ← prove_eq_using_down x new_x,\n let new_e := app (app op new_x) y,\n pr ← mk_congr_arg (lam `x binder_info.default β (app (app op (var 0)) y)) eq_x,\n return (new_e, pr)\n)\n| _ := failed\n\n/--\nDischarging function used during simplification in the \"squash\" step.\n\nTODO: norm_cast takes a list of expressions to use as lemmas for the discharger\nTODO: a tactic to print the results the discharger fails to proove\n-/\nprivate meta def prove : tactic unit :=\nassumption\n\n/--\nCore rewriting function used in the \"squash\" step, which moves casts upwards\nand eliminates them.\n\nIt tries to rewrite an expression using the elim and move lemmas.\nOn failure, it calls the splitting procedure heuristic.\n-/\nmeta def upward_and_elim (s : simp_lemmas) (e : expr) : tactic (expr × expr) :=\n(do\n r ← mcond (is_prop e) (return `iff) (return `eq),\n (new_e, pr) ← s.rewrite e prove r,\n pr ← match r with\n | `iff := mk_app `propext [pr]\n | _ := return pr\n end,\n return (new_e, pr)\n) <|> splitting_procedure e\n\n/-!\nThe following auxiliary functions are used to handle numerals.\n-/\n\n/--\nIf possible, rewrite `(n : α)` to `((n : ℕ) : α)` where `n` is a numeral and `α ≠ ℕ`.\nReturns a pair of the new expression and proof that they are equal.\n-/\nmeta def numeral_to_coe (e : expr) : tactic (expr × expr) :=\ndo\n α ← infer_type e,\n success_if_fail $ is_def_eq α `(ℕ),\n n ← e.to_nat,\n h1 ← mk_app `has_lift_t [`(ℕ), α] >>= mk_instance_fast,\n let new_e : expr := reflect n,\n new_e ← to_expr ``(@coe ℕ %%α %%h1 %%new_e),\n pr ← prove_eq_using_down e new_e,\n return (new_e, pr)\n\n/--\nIf possible, rewrite `((n : ℕ) : α)` to `(n : α)` where `n` is a numeral.\nReturns a pair of the new expression and proof that they are equal.\n-/\nmeta def coe_to_numeral (e : expr) : tactic (expr × expr) :=\ndo\n `(@coe ℕ %%α %%h1 %%e') ← return e,\n n ← e'.to_nat,\n -- replace e' by normalized numeral\n is_def_eq (reflect n) e' reducible,\n let e := e.app_fn (reflect n),\n new_e ← expr.of_nat α n,\n pr ← prove_eq_using_down e new_e,\n return (new_e, pr)\n\n/-- A local variant on `simplify_top_down`. -/\nprivate meta def simplify_top_down' {α} (a : α) (pre : α → expr → tactic (α × expr × expr))\n (e : expr) (cfg : simp_config := {}) : tactic (α × expr × expr) :=\next_simplify_core a cfg simp_lemmas.mk (λ _, failed)\n (λ a _ _ _ e, do\n (new_a, new_e, pr) ← pre a e,\n guard (¬ new_e =ₐ e),\n return (new_a, new_e, some pr, ff))\n (λ _ _ _ _ _, failed)\n `eq e\n\n/--\nThe core simplification routine of `norm_cast`.\n-/\nmeta def derive (e : expr) : tactic (expr × expr) :=\ndo\n cache ← norm_cast_attr.get_cache,\n e ← instantiate_mvars e,\n let cfg : simp_config :=\n { zeta := ff,\n beta := ff,\n eta := ff,\n proj := ff,\n iota := ff,\n iota_eqn := ff,\n fail_if_unchanged := ff },\n let e0 := e,\n\n -- step 1: pre-processing of numerals\n ((), e1, pr1) ← simplify_top_down' () (λ _ e, prod.mk () <$> numeral_to_coe e) e0 cfg,\n trace_norm_cast \"after numeral_to_coe: \" e1,\n\n -- step 2: casts are moved upwards and eliminated\n ((), e2, pr2) ← simplify_bottom_up () (λ _ e, prod.mk () <$> upward_and_elim cache.up e) e1 cfg,\n trace_norm_cast \"after upward_and_elim: \" e2,\n\n -- step 3: casts are squashed\n (e3, pr3, _) ← simplify cache.squash [] e2 cfg,\n trace_norm_cast \"after squashing: \" e3,\n\n -- step 4: post-processing of numerals\n ((), e4, pr4) ← simplify_top_down' () (λ _ e, prod.mk () <$> coe_to_numeral e) e3 cfg,\n trace_norm_cast \"after coe_to_numeral: \" e4,\n\n let new_e := e4,\n guard (¬ new_e =ₐ e),\n pr ← mk_eq_trans pr1 pr2,\n pr ← mk_eq_trans pr pr3,\n pr ← mk_eq_trans pr pr4,\n return (new_e, pr)\n\n/--\nA small variant of `push_cast` suited for non-interactive use.\n\n`derive_push_cast extra_lems e` returns an expression `e'` and a proof that `e = e'`.\n-/\nmeta def derive_push_cast (extra_lems : list simp_arg_type) (e : expr) : tactic (expr × expr) :=\ndo (s, _) ← mk_simp_set tt [`push_cast] extra_lems,\n (e, prf, _) ← simplify (s.erase [`nat.cast_succ]) [] e\n {fail_if_unchanged := ff} `eq tactic.assumption,\n return (e, prf)\n\nend norm_cast\n\nnamespace tactic\nopen expr norm_cast\n\n/-- `aux_mod_cast e` runs `norm_cast` on `e` and returns the result. If `include_goal` is true, it\nalso normalizes the goal. -/\nmeta def aux_mod_cast (e : expr) (include_goal : bool := tt) : tactic expr :=\nmatch e with\n| local_const _ lc _ _ := do\n e ← get_local lc,\n replace_at derive [e] include_goal,\n get_local lc\n| e := do\n t ← infer_type e,\n e ← assertv `this t e,\n replace_at derive [e] include_goal,\n get_local `this\nend\n\n/-- `exact_mod_cast e` runs `norm_cast` on the goal and `e`, and tries to use `e` to close the\ngoal. -/\nmeta def exact_mod_cast (e : expr) : tactic unit :=\ndecorate_error \"exact_mod_cast failed:\" $ do\n new_e ← aux_mod_cast e,\n exact new_e\n\n/-- `apply_mod_cast e` runs `norm_cast` on the goal and `e`, and tries to apply `e`. -/\nmeta def apply_mod_cast (e : expr) : tactic (list (name × expr)) :=\ndecorate_error \"apply_mod_cast failed:\" $ do\n new_e ← aux_mod_cast e,\n apply new_e\n\n/-- `assumption_mod_cast` runs `norm_cast` on the goal. For each local hypothesis `h`, it also\nnormalizes `h` and tries to use that to close the goal. -/\nmeta def assumption_mod_cast : tactic unit :=\ndecorate_error \"assumption_mod_cast failed:\" $ do\n let cfg : simp_config :=\n { fail_if_unchanged := ff,\n canonize_instances := ff,\n canonize_proofs := ff,\n proj := ff },\n replace_at derive [] tt,\n ctx ← local_context,\n ctx.mfirst (λ h, aux_mod_cast h ff >>= tactic.exact)\n\nend tactic\n\nnamespace tactic.interactive\nopen tactic norm_cast\n\n/--\nNormalize casts at the given locations by moving them \"upwards\".\nAs opposed to simp, norm_cast can be used without necessarily closing the goal.\n-/\nmeta def norm_cast (loc : parse location) : tactic unit :=\ndo\n ns ← loc.get_locals,\n tt ← replace_at derive ns loc.include_goal | fail \"norm_cast failed to simplify\",\n when loc.include_goal $ try tactic.reflexivity,\n when loc.include_goal $ try tactic.triv,\n when (¬ ns.empty) $ try tactic.contradiction\n\n/--\nRewrite with the given rules and normalize casts between steps.\n-/\nmeta def rw_mod_cast (rs : parse rw_rules) (loc : parse location) : tactic unit :=\ndecorate_error \"rw_mod_cast failed:\" $ do\n let cfg_norm : simp_config := {},\n let cfg_rw : rewrite_cfg := {},\n ns ← loc.get_locals,\n monad.mapm' (λ r : rw_rule, do\n save_info r.pos,\n replace_at derive ns loc.include_goal,\n rw ⟨[r], none⟩ loc {}\n ) rs.rules,\n replace_at derive ns loc.include_goal,\n skip\n\n/--\nNormalize the goal and the given expression, then close the goal with exact.\n-/\nmeta def exact_mod_cast (e : parse texpr) : tactic unit :=\ndo\n e ← i_to_expr e <|> do\n { ty ← target,\n e ← i_to_expr_strict ``(%%e : %%ty),\n pty ← pp ty, ptgt ← pp e,\n fail (\"exact_mod_cast failed, expression type not directly \" ++\n \"inferrable. Try:\\n\\nexact_mod_cast ...\\nshow \" ++\n to_fmt pty ++ \",\\nfrom \" ++ ptgt : format) },\n tactic.exact_mod_cast e\n\n/--\nNormalize the goal and the given expression, then apply the expression to the goal.\n-/\nmeta def apply_mod_cast (e : parse texpr) : tactic unit :=\ndo\n e ← i_to_expr_for_apply e,\n concat_tags $ tactic.apply_mod_cast e\n\n/--\nNormalize the goal and every expression in the local context, then close the goal with assumption.\n-/\nmeta def assumption_mod_cast : tactic unit :=\ntactic.assumption_mod_cast\n\nend tactic.interactive\n\nnamespace conv.interactive\nopen conv\nopen norm_cast (derive)\n\n/-- the converter version of `norm_cast' -/\nmeta def norm_cast : conv unit := replace_lhs derive\n\nend conv.interactive\n\n-- TODO: move this elsewhere?\n@[norm_cast] lemma ite_cast {α β} [has_lift_t α β]\n {c : Prop} [decidable c] {a b : α} :\n ↑(ite c a b) = ite c (↑a : β) (↑b : β) :=\nby by_cases h : c; simp [h]\n\n@[norm_cast] lemma dite_cast {α β} [has_lift_t α β]\n {c : Prop} [decidable c] {a : c → α} {b : ¬ c → α} :\n ↑(dite c a b) = dite c (λ h, (↑(a h) : β)) (λ h, (↑(b h) : β)) :=\nby by_cases h : c; simp [h]\n\nadd_hint_tactic \"norm_cast at *\"\n\n/--\nThe `norm_cast` family of tactics is used to normalize casts inside expressions.\nIt is basically a simp tactic with a specific set of lemmas to move casts\nupwards in the expression.\nTherefore it can be used more safely as a non-terminating tactic.\nIt also has special handling of numerals.\n\nFor instance, given an assumption\n```lean\na b : ℤ\nh : ↑a + ↑b < (10 : ℚ)\n```\n\nwriting `norm_cast at h` will turn `h` into\n```lean\nh : a + b < 10\n```\n\nYou can also use `exact_mod_cast`, `apply_mod_cast`, `rw_mod_cast`\nor `assumption_mod_cast`.\nWriting `exact_mod_cast h` and `apply_mod_cast h` will normalize the goal and\n`h` before using `exact h` or `apply h`.\nWriting `assumption_mod_cast` will normalize the goal and for every\nexpression `h` in the context it will try to normalize `h` and use\n`exact h`.\n`rw_mod_cast` acts like the `rw` tactic but it applies `norm_cast` between steps.\n\n`push_cast` rewrites the expression to move casts toward the leaf nodes.\nThis uses `norm_cast` lemmas in the forward direction.\nFor example, `↑(a + b)` will be written to `↑a + ↑b`.\nIt is equivalent to `simp only with push_cast`.\nIt can also be used at hypotheses with `push_cast at h`\nand with extra simp lemmas with `push_cast [int.add_zero]`.\n\n```lean\nexample (a b : ℕ) (h1 : ((a + b : ℕ) : ℤ) = 10) (h2 : ((a + b + 0 : ℕ) : ℤ) = 10) :\n ((a + b : ℕ) : ℤ) = 10 :=\nbegin\n push_cast,\n push_cast at h1,\n push_cast [int.add_zero] at h2,\nend\n```\n\nThe implementation and behavior of the `norm_cast` family is described in detail at\n.\n-/\nadd_tactic_doc\n{ name := \"norm_cast\",\n category := doc_category.tactic,\n decl_names := [``tactic.interactive.norm_cast, ``tactic.interactive.rw_mod_cast,\n ``tactic.interactive.apply_mod_cast, ``tactic.interactive.assumption_mod_cast,\n ``tactic.interactive.exact_mod_cast, ``tactic.interactive.push_cast],\n tags := [\"coercions\", \"simplification\"] }\n\n/--\nThe `norm_cast` attribute should be given to lemmas that describe the\nbehaviour of a coercion in regard to an operator, a relation, or a particular\nfunction.\n\nIt only concerns equality or iff lemmas involving `↑`, `⇑` and `↥`, describing the behavior of\nthe coercion functions.\nIt does not apply to the explicit functions that define the coercions.\n\nExamples:\n```lean\n@[norm_cast] theorem coe_nat_inj' {m n : ℕ} : (↑m : ℤ) = ↑n ↔ m = n\n\n@[norm_cast] theorem coe_int_denom (n : ℤ) : (n : ℚ).denom = 1\n\n@[norm_cast] theorem cast_id : ∀ n : ℚ, ↑n = n\n\n@[norm_cast] theorem coe_nat_add (m n : ℕ) : (↑(m + n) : ℤ) = ↑m + ↑n\n\n@[norm_cast] theorem cast_sub [add_group α] [has_one α] {m n} (h : m ≤ n) :\n ((n - m : ℕ) : α) = n - m\n\n@[norm_cast] theorem coe_nat_bit0 (n : ℕ) : (↑(bit0 n) : ℤ) = bit0 ↑n\n\n@[norm_cast] theorem cast_coe_nat (n : ℕ) : ((n : ℤ) : α) = n\n\n@[norm_cast] theorem cast_one : ((1 : ℚ) : α) = 1\n```\n\nLemmas tagged with `@[norm_cast]` are classified into three categories: `move`, `elim`, and\n`squash`. They are classified roughly as follows:\n\n* elim lemma: LHS has 0 head coes and ≥ 1 internal coe\n* move lemma: LHS has 1 head coe and 0 internal coes, RHS has 0 head coes and ≥ 1 internal coes\n* squash lemma: LHS has ≥ 1 head coes and 0 internal coes, RHS has fewer head coes\n\n`norm_cast` uses `move` and `elim` lemmas to factor coercions toward the root of an expression\nand to cancel them from both sides of an equation or relation. It uses `squash` lemmas to clean\nup the result.\n\nOccasionally you may want to override the automatic classification.\nYou can do this by giving an optional `elim`, `move`, or `squash` parameter to the attribute.\n\n```lean\n@[simp, norm_cast elim] lemma nat_cast_re (n : ℕ) : (n : ℂ).re = n :=\nby rw [← of_real_nat_cast, of_real_re]\n```\n\nDon't do this unless you understand what you are doing.\n\nA full description of the tactic, and the use of each lemma category, can be found at\n.\n-/\nadd_tactic_doc\n{ name := \"norm_cast attributes\",\n category := doc_category.attr,\n decl_names := [``norm_cast.norm_cast_attr],\n tags := [\"coercions\", \"simplification\"] }\n", "meta": {"author": "leanprover-community", "repo": "mathlib", "sha": "5e526d18cea33550268dcbbddcb822d5cde40654", "save_path": "github-repos/lean/leanprover-community-mathlib", "path": "github-repos/lean/leanprover-community-mathlib/mathlib-5e526d18cea33550268dcbbddcb822d5cde40654/src/tactic/norm_cast.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3849121303722487, "lm_q2_score": 0.06465349196072041, "lm_q1q2_score": 0.02488591332660595}} {"text": "/-\nCopyright (c) 2022 Andrew Yang. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Andrew Yang\n-/\nimport algebraic_geometry.morphisms.ring_hom_properties\nimport topology.local_at_target\n\n/-!\n\n# Open immersions\n\nA morphism is an open immersions if the underlying map of spaces is an open embedding\n`f : X ⟶ U ⊆ Y`, and the sheaf map `Y(V) ⟶ f _* X(V)` is an iso for each `V ⊆ U`.\n\nMost of the theories are developed in `algebraic_geometry/open_immersion`, and we provide the\nremaining theorems analogous to other lemmas in `algebraic_geometry/morphisms/*`.\n\n-/\n\nnoncomputable theory\n\nopen category_theory category_theory.limits opposite topological_space\n\nuniverse u\n\nnamespace algebraic_geometry\n\nvariables {X Y Z : Scheme.{u}} (f : X ⟶ Y) (g : Y ⟶ Z)\n\nlemma is_open_immersion_iff_stalk {f : X ⟶ Y} :\n is_open_immersion f ↔\n open_embedding f.1.base ∧ ∀ x, is_iso (PresheafedSpace.stalk_map f.1 x) :=\nbegin\n split,\n { intro h, exactI ⟨h.1, infer_instance⟩ },\n { rintro ⟨h₁, h₂⟩, exactI is_open_immersion.of_stalk_iso f h₁ }\nend\n\nlemma is_open_immersion_stable_under_composition :\n morphism_property.stable_under_composition @is_open_immersion :=\nbegin\n introsI X Y Z f g h₁ h₂, apply_instance\nend\n\nlemma is_open_immersion_respects_iso :\n morphism_property.respects_iso @is_open_immersion :=\nbegin\n apply is_open_immersion_stable_under_composition.respects_iso,\n intros _ _ _, apply_instance\nend\n\nlemma is_open_immersion_is_local_at_target : property_is_local_at_target @is_open_immersion :=\nbegin\n constructor,\n { exact is_open_immersion_respects_iso },\n { introsI, apply_instance },\n { intros X Y f 𝒰 H,\n rw is_open_immersion_iff_stalk,\n split,\n { apply (open_embedding_iff_open_embedding_of_supr_eq_top\n 𝒰.supr_opens_range f.1.base.2).mpr,\n intro i,\n have := ((is_open_immersion_respects_iso.arrow_iso_iff\n (morphism_restrict_opens_range f (𝒰.map i))).mpr (H i)).1,\n rwa [arrow.mk_hom, morphism_restrict_val_base] at this },\n { intro x,\n have := arrow.iso_w (morphism_restrict_stalk_map f ((𝒰.map $ 𝒰.f $ f.1 x).opens_range)\n ⟨x, 𝒰.covers _⟩),\n dsimp only [arrow.mk_hom] at this,\n rw this,\n haveI : is_open_immersion (f ∣_ (𝒰.map $ 𝒰.f $ f.1 x).opens_range) :=\n (is_open_immersion_respects_iso.arrow_iso_iff\n (morphism_restrict_opens_range f (𝒰.map _))).mpr (H _),\n apply_instance } }\nend\n\nlemma is_open_immersion.open_cover_tfae {X Y : Scheme.{u}} (f : X ⟶ Y) :\n tfae [is_open_immersion f,\n ∃ (𝒰 : Scheme.open_cover.{u} Y), ∀ (i : 𝒰.J),\n is_open_immersion (pullback.snd : (𝒰.pullback_cover f).obj i ⟶ 𝒰.obj i),\n ∀ (𝒰 : Scheme.open_cover.{u} Y) (i : 𝒰.J),\n is_open_immersion (pullback.snd : (𝒰.pullback_cover f).obj i ⟶ 𝒰.obj i),\n ∀ (U : opens Y.carrier), is_open_immersion (f ∣_ U),\n ∀ {U : Scheme} (g : U ⟶ Y) [is_open_immersion g],\n is_open_immersion (pullback.snd : pullback f g ⟶ _),\n ∃ {ι : Type u} (U : ι → opens Y.carrier) (hU : supr U = ⊤),\n ∀ i, is_open_immersion (f ∣_ (U i))] :=\nis_open_immersion_is_local_at_target.open_cover_tfae f\n\nlemma is_open_immersion.open_cover_iff {X Y : Scheme.{u}}\n (𝒰 : Scheme.open_cover.{u} Y) (f : X ⟶ Y) :\n is_open_immersion f ↔ ∀ i, is_open_immersion (pullback.snd : pullback f (𝒰.map i) ⟶ _) :=\nis_open_immersion_is_local_at_target.open_cover_iff f 𝒰\n\nlemma is_open_immersion_stable_under_base_change :\n morphism_property.stable_under_base_change @is_open_immersion :=\nmorphism_property.stable_under_base_change.mk is_open_immersion_respects_iso $\n by { introsI X Y Z f g H, apply_instance }\n\nend algebraic_geometry\n", "meta": {"author": "leanprover-community", "repo": "mathlib", "sha": "5e526d18cea33550268dcbbddcb822d5cde40654", "save_path": "github-repos/lean/leanprover-community-mathlib", "path": "github-repos/lean/leanprover-community-mathlib/mathlib-5e526d18cea33550268dcbbddcb822d5cde40654/src/algebraic_geometry/morphisms/open_immersion.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4726834766204328, "lm_q2_score": 0.052618955761897845, "lm_q1q2_score": 0.024872110945670628}} {"text": "/-\nCopyright (c) 2020 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Leonardo de Moura\n-/\nimport Std.ShareCommon\nimport Lean.MetavarContext\nimport Lean.Environment\nimport Lean.Util.FoldConsts\nimport Lean.Meta.Basic\nimport Lean.Meta.Check\n\n/-\n\nThis module provides functions for \"closing\" open terms and\ncreating auxiliary definitions. Here, we say a term is \"open\" if\nit contains free/meta-variables.\n\nThe \"closure\" is performed by lambda abstracting the\nfree/meta-variables. Recall that in dependent type theory\nlambda abstracting a let-variable may produce type incorrect terms.\nFor example, given the context\n```lean\n(n : Nat := 20)\n(x : Vector α n)\n(y : Vector α 20)\n```\nthe term `x = y` is correct. However, its closure using lambda abstractions\nis not.\n```lean\nfun (n : Nat) (x : Vector α n) (y : Vector α 20) => x = y\n```\nA previous version of this module would address this issue by\nalways use let-expressions to abstract let-vars. In the example above,\nit would produce\n```lean\nlet n : Nat := 20; fun (x : Vector α n) (y : Vector α 20) => x = y\n```\nThis approach produces correct result, but produces unsatisfactory\nresults when we want to create auxiliary definitions.\nFor example, consider the context\n```lean\n(x : Nat)\n(y : Nat := fact x)\n```\nand the term `h (g y)`, now suppose we want to create an auxiliary definition for `y`.\n The previous version of this module would compute the auxiliary definition\n```lean\ndef aux := fun (x : Nat) => let y : Nat := fact x; h (g y)\n```\nand would return the term `aux x` as a substitute for `h (g y)`.\nThis is correct, but we will re-evaluate `fact x` whenever we use `aux`.\nIn this module, we produce\n```lean\ndef aux := fun (y : Nat) => h (g y)\n```\nNote that in this particular case, it is safe to lambda abstract the let-varible `y`.\nThis module uses the following approach to decide whether it is safe or not to lambda\nabstract a let-variable.\n1) We enable zeta-expansion tracking in `MetaM`. That is, whenever we perform type checking\n if a let-variable needs to zeta expanded, we store it in the set `zetaFVarIds`.\n We say a let-variable is zeta expanded when we replace it with its value.\n2) We use the `MetaM` type checker `check` to type check the expression we want to close,\n and the type of the binders.\n3) If a let-variable is not in `zetaFVarIds`, we lambda abstract it.\n\nRemark: We still use let-expressions for let-variables in `zetaFVarIds`, but we move the\n`let` inside the lambdas. The idea is to make sure the auxiliary definition does not have\nan interleaving of `lambda` and `let` expressions. Thus, if the let-variable occurs in\nthe type of one of the lambdas, we simply zeta-expand it there.\nAs a final example consider the context\n```lean\n(x_1 : Nat)\n(x_2 : Nat)\n(x_3 : Nat)\n(x : Nat := fact (10 + x_1 + x_2 + x_3))\n(ty : Type := Nat → Nat)\n(f : ty := fun x => x)\n(n : Nat := 20)\n(z : f 10)\n```\nand we use this module to compute an auxiliary definition for the term\n```lean\n(let y : { v : Nat // v = n } := ⟨20, rfl⟩; y.1 + n + f x, z + 10)\n```\nwe obtain\n```lean\ndef aux (x : Nat) (f : Nat → Nat) (z : Nat) : Nat×Nat :=\nlet n : Nat := 20;\n(let y : {v // v=n} := {val := 20, property := ex._proof_1}; y.val+n+f x, z+10)\n```\n\nBTW, this module also provides the `zeta : Bool` flag. When set to true, it\nexpands all let-variables occurring in the target expression.\n-/\n\nnamespace Lean.Meta\nnamespace Closure\n\nstructure ToProcessElement where\n fvarId : FVarId\n newFVarId : FVarId\n deriving Inhabited\n\nstructure Context where\n zeta : Bool\n\nstructure State where\n visitedLevel : LevelMap Level := {}\n visitedExpr : ExprStructMap Expr := {}\n levelParams : Array Name := #[]\n nextLevelIdx : Nat := 1\n levelArgs : Array Level := #[]\n newLocalDecls : Array LocalDecl := #[]\n newLocalDeclsForMVars : Array LocalDecl := #[]\n newLetDecls : Array LocalDecl := #[]\n nextExprIdx : Nat := 1\n exprMVarArgs : Array Expr := #[]\n exprFVarArgs : Array Expr := #[]\n toProcess : Array ToProcessElement := #[]\n\nabbrev ClosureM := ReaderT Context $ StateRefT State MetaM\n\n@[inline] def visitLevel (f : Level → ClosureM Level) (u : Level) : ClosureM Level := do\n if !u.hasMVar && !u.hasParam then\n pure u\n else\n let s ← get\n match s.visitedLevel.find? u with\n | some v => pure v\n | none => do\n let v ← f u\n modify fun s => { s with visitedLevel := s.visitedLevel.insert u v }\n pure v\n\n@[inline] def visitExpr (f : Expr → ClosureM Expr) (e : Expr) : ClosureM Expr := do\n if !e.hasLevelParam && !e.hasFVar && !e.hasMVar then\n pure e\n else\n let s ← get\n match s.visitedExpr.find? e with\n | some r => pure r\n | none =>\n let r ← f e\n modify fun s => { s with visitedExpr := s.visitedExpr.insert e r }\n pure r\n\ndef mkNewLevelParam (u : Level) : ClosureM Level := do\n let s ← get\n let p := (`u).appendIndexAfter s.nextLevelIdx\n modify fun s => { s with levelParams := s.levelParams.push p, nextLevelIdx := s.nextLevelIdx + 1, levelArgs := s.levelArgs.push u }\n pure $ mkLevelParam p\n\npartial def collectLevelAux : Level → ClosureM Level\n | u@(Level.succ v _) => return u.updateSucc! (← visitLevel collectLevelAux v)\n | u@(Level.max v w _) => return u.updateMax! (← visitLevel collectLevelAux v) (← visitLevel collectLevelAux w)\n | u@(Level.imax v w _) => return u.updateIMax! (← visitLevel collectLevelAux v) (← visitLevel collectLevelAux w)\n | u@(Level.mvar mvarId _) => mkNewLevelParam u\n | u@(Level.param _ _) => mkNewLevelParam u\n | u@(Level.zero _) => pure u\n\ndef collectLevel (u : Level) : ClosureM Level := do\n -- u ← instantiateLevelMVars u\n visitLevel collectLevelAux u\n\ndef preprocess (e : Expr) : ClosureM Expr := do\n let e ← instantiateMVars e\n let ctx ← read\n -- If we are not zeta-expanding let-decls, then we use `check` to find\n -- which let-decls are dependent. We say a let-decl is dependent if its lambda abstraction is type incorrect.\n if !ctx.zeta then\n check e\n pure e\n\n/--\n Remark: This method does not guarantee unique user names.\n The correctness of the procedure does not rely on unique user names.\n Recall that the pretty printer takes care of unintended collisions. -/\ndef mkNextUserName : ClosureM Name := do\n let s ← get\n let n := (`_x).appendIndexAfter s.nextExprIdx\n modify fun s => { s with nextExprIdx := s.nextExprIdx + 1 }\n pure n\n\ndef pushToProcess (elem : ToProcessElement) : ClosureM Unit :=\n modify fun s => { s with toProcess := s.toProcess.push elem }\n\npartial def collectExprAux (e : Expr) : ClosureM Expr := do\n let collect (e : Expr) := visitExpr collectExprAux e\n match e with\n | Expr.proj _ _ s _ => return e.updateProj! (← collect s)\n | Expr.forallE _ d b _ => return e.updateForallE! (← collect d) (← collect b)\n | Expr.lam _ d b _ => return e.updateLambdaE! (← collect d) (← collect b)\n | Expr.letE _ t v b _ => return e.updateLet! (← collect t) (← collect v) (← collect b)\n | Expr.app f a _ => return e.updateApp! (← collect f) (← collect a)\n | Expr.mdata _ b _ => return e.updateMData! (← collect b)\n | Expr.sort u _ => return e.updateSort! (← collectLevel u)\n | Expr.const c us _ => return e.updateConst! (← us.mapM collectLevel)\n | Expr.mvar mvarId _ =>\n let mvarDecl ← getMVarDecl mvarId\n let type ← preprocess mvarDecl.type\n let type ← collect type\n let newFVarId ← mkFreshFVarId\n let userName ← mkNextUserName\n modify fun s => { s with\n newLocalDeclsForMVars := s.newLocalDeclsForMVars.push $ LocalDecl.cdecl arbitrary newFVarId userName type BinderInfo.default,\n exprMVarArgs := s.exprMVarArgs.push e\n }\n return mkFVar newFVarId\n | Expr.fvar fvarId _ =>\n match (← read).zeta, (← getLocalDecl fvarId).value? with\n | true, some value => collect (← preprocess value)\n | _, _ =>\n let newFVarId ← mkFreshFVarId\n pushToProcess ⟨fvarId, newFVarId⟩\n return mkFVar newFVarId\n | e => pure e\n\ndef collectExpr (e : Expr) : ClosureM Expr := do\n let e ← preprocess e\n visitExpr collectExprAux e\n\npartial def pickNextToProcessAux (lctx : LocalContext) (i : Nat) (toProcess : Array ToProcessElement) (elem : ToProcessElement)\n : ToProcessElement × Array ToProcessElement :=\n if h : i < toProcess.size then\n let elem' := toProcess.get ⟨i, h⟩\n if (lctx.get! elem.fvarId).index < (lctx.get! elem'.fvarId).index then\n pickNextToProcessAux lctx (i+1) (toProcess.set ⟨i, h⟩ elem) elem'\n else\n pickNextToProcessAux lctx (i+1) toProcess elem\n else\n (elem, toProcess)\n\ndef pickNextToProcess? : ClosureM (Option ToProcessElement) := do\n let lctx ← getLCtx\n let s ← get\n if s.toProcess.isEmpty then\n pure none\n else\n modifyGet fun s =>\n let elem := s.toProcess.back\n let toProcess := s.toProcess.pop\n let (elem, toProcess) := pickNextToProcessAux lctx 0 toProcess elem\n (some elem, { s with toProcess := toProcess })\n\ndef pushFVarArg (e : Expr) : ClosureM Unit :=\n modify fun s => { s with exprFVarArgs := s.exprFVarArgs.push e }\n\ndef pushLocalDecl (newFVarId : FVarId) (userName : Name) (type : Expr) (bi := BinderInfo.default) : ClosureM Unit := do\n let type ← collectExpr type\n modify fun s => { s with newLocalDecls := s.newLocalDecls.push <| LocalDecl.cdecl arbitrary newFVarId userName type bi }\n\npartial def process : ClosureM Unit := do\n match (← pickNextToProcess?) with\n | none => pure ()\n | some ⟨fvarId, newFVarId⟩ =>\n let localDecl ← getLocalDecl fvarId\n match localDecl with\n | LocalDecl.cdecl _ _ userName type bi =>\n pushLocalDecl newFVarId userName type bi\n pushFVarArg (mkFVar fvarId)\n process\n | LocalDecl.ldecl _ _ userName type val _ =>\n let zetaFVarIds ← getZetaFVarIds\n if !zetaFVarIds.contains fvarId then\n /- Non-dependent let-decl\n\n Recall that if `fvarId` is in `zetaFVarIds`, then we zeta-expanded it\n during type checking (see `check` at `collectExpr`).\n\n Our type checker may zeta-expand declarations that are not needed, but this\n check is conservative, and seems to work well in practice. -/\n pushLocalDecl newFVarId userName type\n pushFVarArg (mkFVar fvarId)\n process\n else\n /- Dependent let-decl -/\n let type ← collectExpr type\n let val ← collectExpr val\n modify fun s => { s with newLetDecls := s.newLetDecls.push <| LocalDecl.ldecl arbitrary newFVarId userName type val false }\n /- We don't want to interleave let and lambda declarations in our closure. So, we expand any occurrences of newFVarId\n at `newLocalDecls` -/\n modify fun s => { s with newLocalDecls := s.newLocalDecls.map (replaceFVarIdAtLocalDecl newFVarId val) }\n process\n\n@[inline] def mkBinding (isLambda : Bool) (decls : Array LocalDecl) (b : Expr) : Expr :=\n let xs := decls.map LocalDecl.toExpr\n let b := b.abstract xs\n decls.size.foldRev (init := b) fun i b =>\n let decl := decls[i]\n match decl with\n | LocalDecl.cdecl _ _ n ty bi =>\n let ty := ty.abstractRange i xs\n if isLambda then\n Lean.mkLambda n bi ty b\n else\n Lean.mkForall n bi ty b\n | LocalDecl.ldecl _ _ n ty val nonDep =>\n if b.hasLooseBVar 0 then\n let ty := ty.abstractRange i xs\n let val := val.abstractRange i xs\n mkLet n ty val b nonDep\n else\n b.lowerLooseBVars 1 1\n\ndef mkLambda (decls : Array LocalDecl) (b : Expr) : Expr :=\n mkBinding true decls b\n\ndef mkForall (decls : Array LocalDecl) (b : Expr) : Expr :=\n mkBinding false decls b\n\nstructure MkValueTypeClosureResult where\n levelParams : Array Name\n type : Expr\n value : Expr\n levelArgs : Array Level\n exprArgs : Array Expr\n\ndef mkValueTypeClosureAux (type : Expr) (value : Expr) : ClosureM (Expr × Expr) := do\n resetZetaFVarIds\n withTrackingZeta do\n let type ← collectExpr type\n let value ← collectExpr value\n process\n pure (type, value)\n\ndef mkValueTypeClosure (type : Expr) (value : Expr) (zeta : Bool) : MetaM MkValueTypeClosureResult := do\n let ((type, value), s) ← ((mkValueTypeClosureAux type value).run { zeta := zeta }).run {}\n let newLocalDecls := s.newLocalDecls.reverse ++ s.newLocalDeclsForMVars\n let newLetDecls := s.newLetDecls.reverse\n let type := mkForall newLocalDecls (mkForall newLetDecls type)\n let value := mkLambda newLocalDecls (mkLambda newLetDecls value)\n pure {\n type := type,\n value := value,\n levelParams := s.levelParams,\n levelArgs := s.levelArgs,\n exprArgs := s.exprFVarArgs.reverse ++ s.exprMVarArgs\n }\n\nend Closure\n\n/--\n Create an auxiliary definition with the given name, type and value.\n The parameters `type` and `value` may contain free and meta variables.\n A \"closure\" is computed, and a term of the form `name.{u_1 ... u_n} t_1 ... t_m` is\n returned where `u_i`s are universe parameters and metavariables `type` and `value` depend on,\n and `t_j`s are free and meta variables `type` and `value` depend on. -/\ndef mkAuxDefinition (name : Name) (type : Expr) (value : Expr) (zeta : Bool := false) (compile : Bool := true) : MetaM Expr := do\n trace[Meta.debug] \"{name} : {type} := {value}\"\n let result ← Closure.mkValueTypeClosure type value zeta\n let env ← getEnv\n let decl := Declaration.defnDecl {\n name := name,\n levelParams := result.levelParams.toList,\n type := result.type,\n value := result.value,\n hints := ReducibilityHints.regular (getMaxHeight env result.value + 1),\n safety := if env.hasUnsafe result.type || env.hasUnsafe result.value then DefinitionSafety.unsafe else DefinitionSafety.safe\n }\n trace[Meta.debug] \"{name} : {result.type} := {result.value}\"\n addDecl decl\n if compile then\n compileDecl decl\n return mkAppN (mkConst name result.levelArgs.toList) result.exprArgs\n\n/-- Similar to `mkAuxDefinition`, but infers the type of `value`. -/\ndef mkAuxDefinitionFor (name : Name) (value : Expr) : MetaM Expr := do\n let type ← inferType value\n let type := type.headBeta\n mkAuxDefinition name type value\n\nend Lean.Meta\n", "meta": {"author": "gebner", "repo": "lean4-old", "sha": "ee51cdfaf63ee313c914d83264f91f414a0e3b6e", "save_path": "github-repos/lean/gebner-lean4-old", "path": "github-repos/lean/gebner-lean4-old/lean4-old-ee51cdfaf63ee313c914d83264f91f414a0e3b6e/stage0/src/Lean/Meta/Closure.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4378234991142018, "lm_q2_score": 0.05665242411343132, "lm_q1q2_score": 0.024803762558644284}} {"text": "import Mathlib.Tactic.Linarith\nimport Aesop\n-- A translation from SSA + Regions to Tree, with no proofs.\n-- this allows for easy unfolding of the semantics.\n-- If we carry around proofs of well formedness, the dependent typing\n-- of the well-formedness leads to stuck terms.\n-- Thus, we eschew the need to have proofs, and simply YOLO translate from\n-- the origina SSA + Regions program into Tree.\n\nnamespace SSARgnVar2Tree\n\ninductive RgnName\n| r0\n| r1\n| r2\n| r3\n| r4\nderiving DecidableEq\n\ninductive VarName\n| null\n| x0\n| x1\n| x2\n| x3\n| x4\n| x5\n| x6\n| x7\n| y1\n| y2\n| y3\n| y4\n| z1\n| z2\n| z3\n| z4\nderiving DecidableEq\n\n\n\nsection StxSem\n\n-- | The environment is a mapping from variable names to values.\nabbrev Env (k : Type) (α : Type) := k → α\n\n\n-- | Extend the environment with a new variable.\n@[simp]\ndef Env.extend [DecidableEq k] (name : k) (v : α) (e: Env k α) : Env k α :=\n fun name' => if name = name' then v else e name'\n\n@[simp]\ndef Env.empty [Inhabited α] : Env k α :=\n fun _ => default\n\n@[simp]\ndef Env.map (f : α → β) (e : Env k α) : Env k β :=\n fun name => f (e name)\n\nnotation \"∅\" => Env.empty\nnotation e \"[\" name \"↦\" v \"]\" => Env.extend name v e\n\nabbrev VarEnv (α : Type) := Env VarName α\nabbrev RgnEnv (α : Type) := Env RgnName α\n\n-- The input semantics given by the user.\nclass UserSemantics (opcode : Type) where\n -- | Arguments given as (, , ... )\n -- | Consider not allowing users to not be access all of 'Env'.\n opcodeEval (op: opcode) (vals : Int × Int) (rgns : (Int × Int → Int)) : Int\n\nattribute [simp] UserSemantics.opcodeEval\n\ninductive ASTKind : Type where\n| O : ASTKind\n| Os : ASTKind\n| R : ASTKind\nderiving Inhabited, DecidableEq\n\n-- | The operations of the language.\ninductive AST (opcode : Type): ASTKind → Type where\n| assign (ret : VarName) (op : opcode)\n (args : VarName × VarName)\n (rgns : AST opcode .R) : AST opcode .O\n| ops1 (op : AST opcode .O) : AST opcode .Os\n| opsmany (op : AST opcode .O) (ops : AST opcode .Os) : AST opcode .Os\n| rgn (args : VarName × VarName) (body : AST opcode .Os) : AST opcode .R\n| rgnvar (var : RgnName) : AST opcode .R\n| rgn0 : AST opcode .R\n\ndef AST.retname : AST opcode .O → VarName\n| .assign (ret := ret) .. => ret\n\ninstance [Inhabited opcode] : Inhabited (AST opcode .O) where\n default := .assign .x0 default (.x0, .x0) .rgn0\n\ninstance [Inhabited opcode] : Inhabited (AST opcode .Os) where\n default := .ops1 default\n\ninstance [Inhabited opcode] : Inhabited (AST opcode .R) where\n default := .rgn (.x0, .x0) default\n\n\n\n@[simp]\ndef Ops.ofList [Inhabited opcode] : List (AST opcode .O) → AST opcode .Os\n| [] => panic! \"need non-empty list\"\n| [x] => .ops1 x\n| x :: xs => .opsmany x (Ops.ofList xs)\n\n@[reducible, simp]\ninstance [Inhabited opcode] : Coe (List (AST opcode .O)) (AST opcode .Os) := ⟨Ops.ofList⟩\n\n@[simp, reducible]\ndef ASTKind.eval : ASTKind → Type\n| .O => Int\n| .Os => Int\n| .R => (Int × Int → Int)\n-- evaluate an operation with repect to a particular user semantics.\n@[simp]\ndef AST.eval [S: UserSemantics opcode]\n {astk: ASTKind} (e: VarEnv Int)\n (re: RgnEnv (Int × Int → Int)): AST opcode astk → astk.eval × VarEnv Int\n| .assign ret op args r =>\n let (arg1, arg2) := args\n let retval := S.opcodeEval op (e arg1, e arg2) (r.eval e re).fst\n (retval, e.extend ret retval)\n| .ops1 op =>\n let (out, env) := op.eval e re\n (out, env)\n| .opsmany op ops =>\n let e' := (op.eval e re).snd\n ops.eval e' re\n| .rgnvar v => (re v, e)\n| .rgn args body =>\n (fun vals =>\n let e := Env.empty\n let e1 := e.extend args.fst vals.fst\n let e2 := e1.extend args.snd vals.snd\n let (outval, _e) := body.eval e2 re\n outval, e)\n| .rgn0 => (fun _ => default, e)\n\nend StxSem\n\n\nsection Tree\n\ninductive CtreeKind\n| O -- op\n| R -- region (higher order)\nderiving Inhabited\n\n-- closed trees, leaves are integers.\ninductive Ctree (opcode : Type) : CtreeKind → Type where\n| binop\n (op : opcode)\n (lhs : Ctree opcode .O)\n (rhs : Ctree opcode .O)\n (rgns: Ctree opcode .R) : Ctree opcode .O\n| rgn (f : Int × Int → Ctree opcode .O) : Ctree opcode .R\n| rgn0 : Ctree opcode .R\n| leaf (val : Int) : Ctree opcode .O\n\ninstance : Inhabited (Ctree opcode .O) where\n default := .leaf 10\n\ninstance : Inhabited (Ctree opcode .R) where\n default := .rgn0\n\n-- convert an AST into a closed tree under the given environment\n-- note that translation into a closed tree needs an environment,\n-- to learn the values of variables.\n-- This version has an `_` in the name since it needs a `Ctree.VarEnv`, not an\n-- `Env`. We will writea helper that converts `Env` into `Ctree.VarEnv`.\n@[simp, reducible]\ndef ASTKind.toCTree (opcode : Type) : ASTKind → Type\n| .O => Ctree opcode .O\n| .Os => Ctree opcode .O\n| .R => Ctree opcode .R\n\n@[simp]\ndef AST.toCtree_ {astk: ASTKind} (e : VarEnv (Ctree opcode .O))\n (re: RgnEnv (Ctree opcode .R)):\n AST opcode astk → (astk.toCTree opcode) × VarEnv (Ctree opcode .O)\n| .assign ret opcode (u, v) r =>\n let rval := (r.toCtree_ e re).fst\n let t := .binop opcode (e u) (e v) rval\n (t, e.extend ret t)\n| .rgnvar var => let e := Env.empty; (re var, e)\n| .rgn0 => let e := Env.empty; (.rgn0, e)\n| .rgn args body =>\n let e := Env.empty -- NOTE: regions are now isolated from above\n (.rgn fun vals =>\n let e1 := e.extend args.fst (.leaf vals.fst)\n let e2 := e1.extend args.snd (.leaf vals.snd)\n (body.toCtree_ e2 re).fst, e)\n| .ops1 op =>\n let (val, e) := op.toCtree_ e re\n (val, e)\n| .opsmany os o =>\n let (_, e) := os.toCtree_ e re\n o.toCtree_ e re\n\n-- wrap every element in a (.leaf) constructor\n@[simp]\ndef Ctree.VarEnv.ofEnv (e: VarEnv Int) : VarEnv (Ctree opcode .O) :=\n fun name => .leaf (e name)\n\n-- TODO: should these be coercions?\n@[simp]\ndef Ctree.RgnEnv.ofEnv (re: RgnEnv (Int × Int → Int)) :\n RgnEnv (Ctree opcode .R) :=\n fun name => Ctree.rgn (fun args => .leaf (re name args))\n\n-- this converts an AST into a Ctree, given an environment\n-- and an AST.\n@[simp]\ndef Op.toCtree (a: AST opcode .O) (e: VarEnv Int)\n (re: RgnEnv (Int × Int → Int)) : Ctree opcode .O :=\n (a.toCtree_ (Ctree.VarEnv.ofEnv e) (Ctree.RgnEnv.ofEnv re)).fst\n\n@[simp]\ndef Ops.toCtree (a: AST opcode .Os)\n (e: VarEnv Int) (re: RgnEnv (Int × Int → Int)) : Ctree opcode .O :=\n (a.toCtree_ (Ctree.VarEnv.ofEnv e) (Ctree.RgnEnv.ofEnv re)).fst\n\n@[simp]\ndef Region.toCtree (a: AST opcode .R)\n (e: VarEnv Int)\n (re: RgnEnv (Int × Int → Int)): Ctree opcode .R :=\n (a.toCtree_ (Ctree.VarEnv.ofEnv e) (Ctree.RgnEnv.ofEnv re)).fst\n\n\n-- evaluate a Ctree. note that this needs no environment.\n@[simp]\ndef CtreeKind.eval : CtreeKind → Type\n| .O => Int\n| .R => Int × Int → Int\n\n-- Note: is this literally \"just\" staging the partial evaluation against the environment?\ndef Ctree.eval [UserSemantics opcode] : Ctree opcode treek → treek.eval\n| .binop o l r rs =>\n UserSemantics.opcodeEval o (l.eval, r.eval) rs.eval\n| .leaf v => v\n| .rgn0 => fun _ => default\n| .rgn f => fun args => (f args).eval\n\nend Tree\n\nnamespace MultipleInstructionTree\ninductive Opcode\n| add\n| mul\n| loop : Opcode\n| ite : Opcode\n| run : Opcode\n| runnot : Opcode\n| not : Opcode\n| const : Int → Opcode\nderiving Inhabited\n\ndef loopSemantics (n : Nat) (f : Int → Int) (v : Int) : Int :=\n match n with\n | 0 => v -- inline id\n | n + 1 => f (loopSemantics n f v) -- inline ∘\n\n@[simp]\ninstance : UserSemantics Opcode where\n opcodeEval\n | .not, ⟨a, _⟩, _ => if a = 0 then 1 else 0\n | .mul, ⟨a, b⟩, _ => a * b\n | .add, ⟨a, b⟩, _ => a + b\n | .const i, ⟨_a, _b⟩, _ => i\n | .run, ⟨v, w⟩, r => r ⟨v, w⟩\n | .runnot, ⟨v, w⟩, r => r ⟨if v = 0 then 1 else 0, w⟩ -- execute: 'r(not v, w)'\n | .loop, ⟨n, init⟩, r => loopSemantics n.toNat (fun i => r ⟨i, 0⟩) init\n | _, _, _ => 42\n\n\ndef x_add_4_times_mul_val_eq (env: VarEnv Int):\n let p : AST Opcode .Os :=\n Ops.ofList [\n .assign .x1 .add (.x0, .x0) .rgn0,\n .assign .x2 .add (.x1, .x1) .rgn0\n ]\n let q : AST Opcode .Os := Ops.ofList [\n .assign .x1 (.const 4) (.x0, .x0) .rgn0\n , .assign .x2 .mul (.x1, .x0) .rgn0\n ]\n (Ops.toCtree p env renv).eval = (Ops.toCtree q env renv).eval := by {\n simp only [Ops.ofList, AST.eval, Ops.toCtree, AST.toCtree_];\n -- see that there are environments, which are folded away when calling\n -- Ctree.eval.\n simp[Ctree.eval];\n linarith\n }\n\n\ndef run_inline :\n let p : AST Opcode .R :=\n AST.rgn ⟨.x0, .x1⟩ $ Ops.ofList [\n .assign .x2 .add (.x0, .x1) .rgn0 -- x2 := x0 + x1\n ]\n let q : AST Opcode .R :=\n AST.rgn ⟨.x0, .x1⟩ $ Ops.ofList [\n .assign .x2 .run (.x0, .x1) (AST.rgn ⟨.x5, .x6⟩ (Ops.ofList [\n -- x2 := run (x0, x1) { ^(x5, x6): return x5 + x6 }\n .assign .y1 .add (.x5, .x6) .rgn0\n ]))\n ]\n (Region.toCtree p Env.empty Env.empty).eval =\n (Region.toCtree q Env.empty Env.empty).eval := by {\n simp\n dsimp only[Ctree.eval]\n }\n\n\n-- trying to convert an AST to a Ctree at any environment\n-- is equivalent to converting it in an empty environment.\n@[simp]\ntheorem AST.toCtree_rgn_equiv_empty\n (r: AST opcode .R)\n [Inhabited opcode] :\n AST.toCtree_ env renv r = AST.toCtree_ Env.empty renv r := by {\n simp; cases r <;> simp;\n}\n\ndef runnot_inline:\n let p : AST Opcode .R :=\n AST.rgn ⟨.x0, .x1⟩ $ Ops.ofList [\n .assign .y1 .run ⟨.x0, .x1⟩ (.rgnvar .r1) -- y1 := r(x0, x1)\n ]\n (Region.toCtree p Env.empty Env.empty).eval =\n (Region.toCtree (.rgnvar .r1 : AST Opcode .R) Env.empty Env.empty).eval := by {\n simp\n simp[Ctree.eval];\n -- this stil cannot be simplified away, since this is in fact false.\n -- We need some notion of the fact that z1, z2 is free in 'r',\n -- so that we can say that we can remove 'z2, z1' in the 'q'\n -- environment when we run 'r'.\n -- if we have this, then we are good, and we can prove the theorem.\n -- but how do we convince people that use MLIR that this is a sensible\n -- thing to reason about?\n\n }\n\nend MultipleInstructionTree\n\nend SSARgnVar2Tree\n", "meta": {"author": "bollu", "repo": "ssa", "sha": "19c73e48500bfe3f618c360423966677adb4673e", "save_path": "github-repos/lean/bollu-ssa", "path": "github-repos/lean/bollu-ssa/ssa-19c73e48500bfe3f618c360423966677adb4673e/SSA/Experiment/SSARgnVar2TreeNoProof.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.049589023510749994, "lm_q1q2_score": 0.024794511755374997}} {"text": "import .fol .abel\n\nuniverse u\n\n-- section weekdays\n-- @[derive has_reflect]\n-- inductive weekday : Type\n-- | monday : weekday\n-- | another_day : weekday → weekday\n\n-- open weekday\n\n-- meta def dump_weekday (f : weekday) : tactic unit :=\n-- tactic.trace $ to_string (expr.to_raw_fmt (reflect f).to_expr) \n\n-- -- run_cmd dump_weekday (another_day (another_day monday))\n-- --(app (const weekday.another_day []) (app (const weekday.another_day []) (const weekday.monday [])))\n\n-- inductive weekday' : Type\n-- | monday : weekday'\n-- | another_day : weekday' → weekday'\n\n-- open weekday'\n-- meta instance has_reflect_weekday' : has_reflect weekday'\n-- | weekday'.monday := `(monday)\n-- | (weekday'.another_day x) := `(λ l, weekday'.another_day l).subst $\n-- by haveI := has_reflect_weekday'; exact (reflect x)\n\n-- meta def dump_weekday' (f : weekday') : tactic unit :=\n-- tactic.trace $ to_string (expr.to_raw_fmt (reflect f).to_expr) \n\n\n-- -- run_cmd dump_weekday' (another_day (another_day monday))\n-- -- (app (const weekday'.another_day []) (app (const weekday'.another_day []) (const weekday'.monday [])))\n-- end weekdays\n-- -- meta instance has_reflect_preterm {L : Language.{u}} : Π{n : ℕ}, has_reflect (preterm L n)\n-- -- | 0 (var k) := `(@preterm.var L).subst (reflect k)\n\n-- -- @[derive has_reflect]\n\n-- open fol abel\n\n-- section preterm_aux \n-- inductive preterm_aux (L : Language.{u}) : Type u\n-- | var : ℕ → preterm_aux\n-- | func : ∀ k : ℕ, L.functions k → preterm_aux\n-- | app : preterm_aux → preterm_aux → preterm_aux\n\n-- def to_aux {L : Language.{u}} : ∀ {l : ℕ}, preterm L l → preterm_aux L\n-- | 0 (var n) := preterm_aux.var _ n\n-- | k (func f) := preterm_aux.func _ f\n-- | k (app t₁ t₂) := preterm_aux.app (to_aux t₁) (to_aux t₂)\n\n\n-- def L_abel_plus' (t₁ t₂ : preterm L_abel 0) : preterm L_abel 0 :=\n-- @term_of_function L_abel 2 (abel_functions.plus : L_abel.functions 2) t₁ t₂\n-- end preterm_aux\n\n-- local infix ` +' `:100 := L_abel_plus'\n\n-- local notation ` zero ` := (func abel_functions.zero : preterm L_abel 0)\n\n-- section L_abel_term_biopsy\n\n-- def sample1 : preterm L_abel 0 := (zero +' zero)\n\n-- def sample2 : preterm L_abel 0 := zero\n\n-- -- #reduce sample2\n\n-- open expr\n-- meta def sample2_expr : expr :=\n-- mk_app (const `preterm.func list.nil) ([(const `L_abel list.nil), `(0), const `abel_functions.zero list.nil] : list expr)\n\n-- end L_abel_term_biopsy\n\n-- section simpler_biopsy\n\n-- inductive my_inductive : Type\n-- | a : my_inductive\n-- | b : my_inductive\n-- | f : my_inductive → my_inductive\n\n-- open my_inductive\n-- def sample3 : my_inductive := f a\n\n-- open expr\n\n-- meta def sample3_expr : expr :=\n-- app (const `my_inductive.f list.nil) (const `my_inductive.a list.nil)\n\n-- def sample3_again : my_inductive := by tactic.exact (sample3_expr)\n\n-- example : sample3 = sample3_again := rfl\n\n-- end simpler_biopsy\n\n-- namespace tactic\n-- namespace interactive\n-- open interactive interactive.types expr\n\n-- def my_test_term : preterm L_abel 0 := (zero +' zero)\n\n-- end interactive\n-- end tactic\n\n-- section test\n-- -- def my_term : preterm L_abel 0 := sorry\n\n-- -- #check tactic.interactive.rcases\n\n-- end test\n\n-- section sample4\n\n-- /-- Note: this is the same as `dfin` -/\n-- inductive my_indexed_family : ℕ → Type u\n-- | z {} : my_indexed_family 0\n-- | s : ∀ {k}, my_indexed_family k → my_indexed_family (k+1)\n\n-- -- meta example : ∀ {n}, has_reflect (my_indexed_family n)\n-- -- | 0 z := `(z)\n\n\n-- open my_indexed_family\n\n-- def sample4 : my_indexed_family 1 := s z\n\n-- -- #check tactic.eval_expr\n\n-- end sample4\n\n-- section sample4\n\n-- inductive dfin'' : ℕ → Type\n-- | fz {n} : dfin'' (n+1)\n-- | fs {n} : dfin'' n → dfin'' (n+1)\n\n-- inductive dfin' : ℕ → Type u\n-- | gz {n} : dfin' (n+1)\n-- | gs {n} : dfin' n → dfin' (n+1)\n\n-- open dfin dfin'\n\n-- meta instance dfin.reflect : ∀ {n}, has_reflect (dfin'' n)\n-- | _ dfin''.fz := `(dfin''.fz)\n-- | _ (dfin''.fs n) := `(dfin''.fs).subst (dfin.reflect n)\n\n-- -- /- errors all over---why doesn't reflect like universe parameters? -/\n-- -- meta instance dfin'.reflect : ∀ {n}, has_reflect (dfin' n)\n-- -- | _ fz := `(fz)\n-- -- | _ (fs n) := `(fs).subst (dfin'.reflect n)\n\n-- end sample4\n\n-- section reflect_preterm\n\n-- /- Language with a single constant symbol -/\n-- inductive L_pt_functions : ℕ → Type\n-- | pt : L_pt_functions 0\n\n-- def L_pt : Language.{0} := ⟨L_pt_functions, λ _, empty⟩\n\n-- def pt_preterm : preterm L_pt 0 := preterm.func L_pt_functions.pt\n\n-- meta def pt_preterm_reflected : expr :=\n-- expr.mk_app (expr.const `preterm.func [level.zero]) [ (expr.const `L_pt list.nil), `(0), (expr.const `L_pt_functions.pt list.nil)]\n\n-- set_option trace.app_builder true\n\n-- -- meta def pt_preterm_reflected' : expr := by tactic.mk_app \"preterm.func\" [(expr.const `L_pt []), `(0), (expr.const `L_pt_functions.pt [])]\n\n-- #check tactic.mk_app\n\n-- meta def pt_preterm_reflected'' : tactic expr :=\n-- tactic.to_expr ```(preterm.func L_pt_functions.pt : preterm L_pt 0)\n\n-- def pt_preterm' : preterm L_pt 0 := by pt_preterm_reflected'' >>= tactic.exact\n\n-- -- def pt_preterm' : preterm L_pt 0 := by tactic.exact pt_preterm_reflected\n\n-- example : pt_preterm = pt_preterm' := rfl\n-- -- infer type failed, incorrect number of universe levels\n\n-- -- want: example : pt_preterm = pt_preterm' := rfl\n\n\n-- end reflect_preterm\n\n\n-- namespace hewwo\n-- section reflect_preterm2\n-- def L_pt.pt' : L_pt.functions 0 := L_pt_functions.pt\n\n-- #reduce (by apply_instance : reflected L_pt.pt')\n-- -- `(L_pt.pt')\n\n-- meta def pt_preterm_reflected : tactic expr :=\n-- tactic.mk_app ``preterm.func [`(L_pt.pt')]\n\n-- def pt_preterm' : preterm L_pt 0 := by pt_preterm_reflected >>= tactic.exact\n\n-- #eval tactic.trace (@expr.to_raw_fmt tt `(L_pt.pt'))\n\n-- #check reflect\n\n\n-- end reflect_preterm2\n-- end hewwo\n\n-- section reflect_preterm3\n\n-- inductive L_pt_func_functions : ℕ → Type\n-- | pt : L_pt_func_functions 0\n-- | foo : L_pt_func_functions 1\n\n-- open L_pt_func_functions\n\n-- def L_pt_func : Language.{0} :=\n-- ⟨L_pt_func_functions, λ _, ulift empty⟩\n\n-- -- def foo_pt_term : preterm L_pt_func 0 :=\n-- -- preterm.app (preterm.func L_pt_func_functions.foo) (preterm.func L_pt_func_functions.pt)\n\n-- -- def foo_pt_term_reflected : expr :=\n-- -- begin\n-- -- tactic.mk_app ``preterm.func [(by tactic.mk_app `preterm.func [`(L_pt_func_functions.foo)]), (by tactic.mk_app `preterm.func [`(L_pt_func_functions.pt)])]\n-- -- end\n\n-- -- def foo' : preterm L_pt_func 1 := preterm.func L_pt_func_functions.foo\n\n\n-- -- #reduce (by apply_instance : reflected L_pt_func_functions.foo)\n\n-- set_option trace.app_builder true\n\n-- def my_foo : L_pt_func.functions 1 := L_pt_func_functions.foo\n\n-- def my_pt : L_pt_func.functions 0 := L_pt_func_functions.pt\n\n-- -- meta def foo_pt_term_reflected : tactic expr := tactic.mk_app ``preterm.func [`()]\n\n-- meta def foo_pt_term_reflected' : tactic expr :=\n-- do e₁ <- tactic.mk_app ``preterm.func [`(my_foo)],\n-- e₂ <- tactic.mk_app ``preterm.func [`(my_pt)],\n-- tactic.mk_app ``preterm.app [e₁, e₂]\n-- -- #print foo_pt_term_reflected'\n\n\n\n-- -- meta def bar : tactic expr :=\n-- -- tactic.mk_app ``preterm.func [`(foo_mask)]\n\n-- set_option trace.app_builder true\n\n-- def foo_pt_term_reflected : preterm L_pt_func 0 := by (foo_pt_term_reflected' >>= tactic.exact)\n\n-- -- #reduce foo_pt_term_reflected\n\n\n-- end reflect_preterm3\n", "meta": {"author": "flypitch", "repo": "flypitch", "sha": "aea5800db1f4cce53fc4a113711454b27388ecf8", "save_path": "github-repos/lean/flypitch-flypitch", "path": "github-repos/lean/flypitch-flypitch/flypitch-aea5800db1f4cce53fc4a113711454b27388ecf8/src/reflect_test.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4921881357207956, "lm_q2_score": 0.05033063562448701, "lm_q1q2_score": 0.024772141717658923}} {"text": "/-\nCopyright (c) 2020 Mario Carneiro. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Mario Carneiro\n-/\nimport data.fintype.basic\n\n/-!\n# Derive handler for `fintype` instances\n\nThis file introduces a derive handler to automatically generate `fintype`\ninstances for structures and inductives.\n\n## Implementation notes\n\nTo construct a fintype instance, we need 3 things:\n\n 1. A list `l` of elements\n 2. A proof that `l` has no duplicates\n 3. A proof that every element in the type is in `l`\n\nNow fintype is defined as a finset which enumerates all elements, so steps (1) and (2) are\nbundled together. It is possible to use finset operations that remove duplicates to avoid the need\nto prove (2), but this adds unnecessary functions to the constructed term, which makes it more\nexpensive to compute the list, and it also adds a dependence on decidable equality for the type,\nwhich we want to avoid.\n\nBecause we will rely on fintype instances for constructor arguments, we can't actually build a list\ndirectly, so (1) and (2) are necessarily somewhat intertwined. The inductive types we will be\nproving instances for look something like this:\n\n```\n@[derive fintype]\ninductive foo\n| zero : foo\n| one : bool → foo\n| two : ∀ x : fin 3, bar x → foo\n```\n\nThe list of elements that we generate is\n```\n{foo.zero}\n∪ (finset.univ : bool).map (λ b, finset.one b)\n∪ (finset.univ : Σ' x : fin 3, bar x).map (λ ⟨x, y⟩, finset.two x y)\n```\nexcept that instead of `∪`, that is `finset.union`, we use `finset.disj_union` which doesn't\nrequire any deduplication, but does require a proof that the two parts of the union are disjoint.\nWe use `finset.cons` to append singletons like `foo.zero`.\n\nThe proofs of disjointness would be somewhat expensive since there are quadratically many of them,\nso instead we use a \"discriminant\" function. Essentially, we define\n```\ndef foo.enum : foo → ℕ\n| foo.zero := 0\n| (foo.one _) := 1\n| (foo.two _ _) := 2\n```\nand now the existence of this function implies that foo.zero is not foo.two and so on because they\nmap to different natural numbers. We can prove that sets of natural numbers are mutually disjoint\nmore easily because they have a linear order: `0 < 1 < 2` so `0 ≠ 2`.\n\nTo package this argument up, we define `finset_above foo foo.enum n` to be a finset `s` together\nwith a proof that all elements `a ∈ s` have `n ≤ enum a`. Now we only have to prove that\n`enum foo.zero = 0`, `enum (foo.one _) = 1`, etc. (linearly many proofs, all `rfl`) in order to\nprove that all variants are mutually distinct.\n\nWe mirror the `finset.cons` and `finset.disj_union` functions into `finset_above.cons` and\n`finset_above.union`, and this forms the main part of the finset construction.\n\nThis only handles distinguishing variants of a finset. Now we must enumerate the elements of a\nvariant, for example `{foo.one ff, foo.one tt}`, while at the same time proving that all these\nelements have discriminant `1` in this case. To do that, we use the `finset_in` type, which\nis a finset satisfying a property `P`, here `λ a, foo.enum a = 1`.\n\nWe could use `finset.bind` many times to construct the finset but it turns out to be somewhat\ncomplicated to get good side goals for a naturally nodup version of `finset.bind` in the same way\nas we did with `finset.cons` and `finset.union`. Instead, we tuple up all arguments into one type,\nleveraging the `fintype` instance on `psigma`, and then define a map from this type to the\ninductive type that untuples them and applies the constructor. The injectivity property of the\nconstructor ensures that this function is injective, so we can use `finset.map` to apply it. This\nis the content of the constructor `finset_in.mk`.\n\nThat completes the proofs of (1) and (2). To prove (3), we perform one case analysis over the\ninductive type, proving theorems like\n```\nfoo.one a ∈ {foo.zero}\n ∪ (finset.univ : bool).map (λ b, finset.one b)\n ∪ (finset.univ : Σ' x : fin 3, bar x).map (λ ⟨x, y⟩, finset.two x y)\n```\nby seeking to the relevant disjunct and then supplying the constructor arguments. This part of the\nproof is quadratic, but quite simple. (We could do it in `O(n log n)` if we used a balanced tree\nfor the unions.)\n\nThe tactics perform the following parts of this proof scheme:\n* `mk_sigma` constructs the type `Γ` in `finset_in.mk`\n* `mk_sigma_elim` constructs the function `f` in `finset_in.mk`\n* `mk_sigma_elim_inj` proves that `f` is injective\n* `mk_sigma_elim_eq` proves that `∀ a, enum (f a) = k`\n* `mk_finset` constructs the finset `S = {foo.zero} ∪ ...` by recursion on the variants\n* `mk_finset_total` constructs the proof `|- foo.zero ∈ S; |- foo.one a ∈ S; |- foo.two a b ∈ S`\n by recursion on the subgoals coming out of the initial `cases`\n* `mk_fintype_instance` puts it all together to produce a proof of `fintype foo`.\n The construction of `foo.enum` is also done in this function.\n\n-/\n\nnamespace derive_fintype\n\n/-- A step in the construction of `finset.univ` for a finite inductive type.\nWe will set `enum` to the discriminant of the inductive type, so a `finset_above`\nrepresents a finset that enumerates all elements in a tail of the constructor list. -/\ndef finset_above (α) (enum : α → ℕ) (n : ℕ) :=\n{s : finset α // ∀ x ∈ s, n ≤ enum x}\n\n/-- Construct a fintype instance from a completed `finset_above`. -/\ndef mk_fintype {α} (enum : α → ℕ) (s : finset_above α enum 0) (H : ∀ x, x ∈ s.1) :\n fintype α := ⟨s.1, H⟩\n\n/-- This is the case for a simple variant (no arguments) in an inductive type. -/\ndef finset_above.cons {α} {enum : α → ℕ} (n)\n (a : α) (h : enum a = n) (s : finset_above α enum (n+1)) : finset_above α enum n :=\nbegin\n refine ⟨finset.cons a s.1 _, _⟩,\n { intro h',\n have := s.2 _ h', rw h at this,\n exact nat.not_succ_le_self n this },\n { intros x h', rcases finset.mem_cons.1 h' with rfl | h',\n { exact ge_of_eq h },\n { exact nat.le_of_succ_le (s.2 _ h') } }\nend\n\ntheorem finset_above.mem_cons_self {α} {enum : α → ℕ} {n a h s} :\n a ∈ (@finset_above.cons α enum n a h s).1 := multiset.mem_cons_self _ _\n\ntheorem finset_above.mem_cons_of_mem {α} {enum : α → ℕ} {n a h s b} :\n b ∈ (s : finset_above _ _ _).1 → b ∈ (@finset_above.cons α enum n a h s).1 :=\nmultiset.mem_cons_of_mem\n\n/-- The base case is when we run out of variants; we just put an empty finset at the end. -/\ndef finset_above.nil {α} {enum : α → ℕ} (n) : finset_above α enum n := ⟨∅, by rintro _ ⟨⟩⟩\n\ninstance (α enum n) : inhabited (finset_above α enum n) := ⟨finset_above.nil _⟩\n\n/-- This is a finset covering a nontrivial variant (with one or more constructor arguments).\nThe property `P` here is `λ a, enum a = n` where `n` is the discriminant for the current\nvariant. -/\n@[nolint has_nonempty_instance]\ndef finset_in {α} (P : α → Prop) := {s : finset α // ∀ x ∈ s, P x}\n\n/-- To construct the finset, we use an injective map from the type `Γ`, which will be the\nsigma over all constructor arguments. We use sigma instances and existing fintype instances\nto prove that `Γ` is a fintype, and construct the function `f` that maps `⟨a, b, c, ...⟩`\nto `C_n a b c ...` where `C_n` is the nth constructor, and `mem` asserts\n`enum (C_n a b c ...) = n`. -/\ndef finset_in.mk {α} {P : α → Prop} (Γ) [fintype Γ]\n (f : Γ → α) (inj : function.injective f) (mem : ∀ x, P (f x)) : finset_in P :=\n⟨finset.univ.map ⟨f, inj⟩,\n λ x h, by rcases finset.mem_map.1 h with ⟨x, _, rfl⟩; exact mem x⟩\n\ntheorem finset_in.mem_mk {α} {P : α → Prop} {Γ} {s : fintype Γ} {f : Γ → α} {inj mem a}\n (b) (H : f b = a) : a ∈ (@finset_in.mk α P Γ s f inj mem).1 :=\nfinset.mem_map.2 ⟨_, finset.mem_univ _, H⟩\n\n/-- For nontrivial variants, we split the constructor list into a `finset_in` component for the\ncurrent constructor and a `finset_above` for the rest. -/\ndef finset_above.union {α} {enum : α → ℕ} (n)\n (s : finset_in (λ a, enum a = n)) (t : finset_above α enum (n+1)) : finset_above α enum n :=\nbegin\n refine ⟨finset.disj_union s.1 t.1 _, _⟩,\n { rw finset.disjoint_left,\n intros a hs ht,\n have := t.2 _ ht, rw s.2 _ hs at this,\n exact nat.not_succ_le_self n this },\n { intros x h', rcases finset.mem_disj_union.1 h' with h' | h',\n { exact ge_of_eq (s.2 _ h') },\n { exact nat.le_of_succ_le (t.2 _ h') } }\nend\n\ntheorem finset_above.mem_union_left {α} {enum : α → ℕ} {n s t a}\n (H : a ∈ (s : finset_in _).1) : a ∈ (@finset_above.union α enum n s t).1 :=\nmultiset.mem_add.2 (or.inl H)\n\ntheorem finset_above.mem_union_right {α} {enum : α → ℕ} {n s t a}\n (H : a ∈ (t : finset_above _ _ _).1) : a ∈ (@finset_above.union α enum n s t).1 :=\nmultiset.mem_add.2 (or.inr H)\n\nend derive_fintype\n\nnamespace tactic\n\nopen derive_fintype tactic expr\n\nnamespace derive_fintype\n\n/-- Construct the term `Σ' (a:A) (b:B a) (c:C a b), unit` from\n`Π (a:A) (b:B a), C a b → T` (the type of a constructor). -/\nmeta def mk_sigma : expr → tactic expr\n| (expr.pi n bi d b) := do\n p ← mk_local' n bi d,\n e ← mk_sigma (expr.instantiate_var b p),\n tactic.mk_app ``psigma [d, bind_lambda e p]\n| _ := pure `(unit)\n\n/-- Prove the goal `(Σ' (a:A) (b:B a) (c:C a b), unit) → T`\n(this is the function `f` in `finset_in.mk`) using recursive `psigma.elim`,\nfinishing with the constructor. The two arguments are the type of the constructor,\nand the constructor term itself; as we recurse we add arguments\nto the constructor application and destructure the pi type of the constructor. We return the number\nof `psigma.elim` applications constructed, which is the number of constructor arguments. -/\nmeta def mk_sigma_elim : expr → expr → tactic ℕ\n| (expr.pi n bi d b) c := do\n refine ``(@psigma.elim %%d _ _ _),\n i ← intro_fresh n,\n (+ 1) <$> mk_sigma_elim (expr.instantiate_var b i) (c i)\n| _ c := do intro1, exact c $> 0\n\n/-- Prove the goal `a, b |- f a = f b → g a = g b` where `f` is the function we constructed in\n`mk_sigma_elim`, and `g` is some other term that gets built up and eventually closed by\nreflexivity. Here `a` and `b` have sigma types so the proof approach is to case on `a` and `b`\nuntil the goal reduces to `C_n a1 ... am = C_n b1 ... bm → ⟨a1, ..., am⟩ = ⟨b1, ..., bm⟩`, at which\npoint cases on the equality reduces the problem to reflexivity.\n\nThe arguments are the number `m` returned from `mk_sigma_elim`, and the hypotheses `a,b` that we\nneed to case on. -/\nmeta def mk_sigma_elim_inj : ℕ → expr → expr → tactic unit\n| (m+1) x y := do\n [(_, [x1, x2])] ← cases x,\n [(_, [y1, y2])] ← cases y,\n mk_sigma_elim_inj m x2 y2\n| 0 x y := do\n cases x, cases y,\n is ← intro1 >>= injection,\n is.mmap' cases,\n reflexivity\n\n/-- Prove the goal `a |- enum (f a) = n`, where `f` is the function constructed in `mk_sigma_elim`,\nand `enum` is a function that reduces to `n` on the constructor `C_n`. Here we just have to case on\n`a` `m` times, and then `reflexivity` finishes the proof. -/\nmeta def mk_sigma_elim_eq : ℕ → expr → tactic unit\n| (n+1) x := do\n [(_, [x1, x2])] ← cases x,\n mk_sigma_elim_eq n x2\n| 0 x := reflexivity\n\n/-- Prove the goal `|- finset_above T enum k`, where `T` is the inductive type and `enum` is the\ndiscriminant function. The arguments are `args`, the parameters to the inductive type (and all\nconstructors), `k`, the index of the current variant, and `cs`, the list of constructor names.\nThis uses `finset_above.cons` for basic variants and `finset_above.union` for variants with\narguments, using the auxiliary functions `mk_sigma`, `mk_sigma_elim`, `mk_sigma_elim_inj`,\n`mk_sigma_elim_eq` to close subgoals. -/\nmeta def mk_finset (ls : list level) (args : list expr) : ℕ → list name → tactic unit\n| k (c::cs) := do\n let e := (expr.const c ls).mk_app args,\n t ← infer_type e,\n if is_pi t then do\n to_expr ``(finset_above.union %%(reflect k)) tt ff >>=\n (λ c, apply c {new_goals := new_goals.all}),\n Γ ← mk_sigma t,\n to_expr ``(finset_in.mk %%Γ) tt ff >>= (λ c, apply c {new_goals := new_goals.all}),\n n ← mk_sigma_elim t e,\n intro1 >>= (λ x, intro1 >>= mk_sigma_elim_inj n x),\n intro1 >>= mk_sigma_elim_eq n,\n mk_finset (k+1) cs\n else do\n c ← to_expr ``(finset_above.cons %%(reflect k) %%e) tt ff,\n apply c {new_goals := new_goals.all}, reflexivity,\n mk_finset (k+1) cs\n| k [] := applyc ``finset_above.nil\n\n/-- Prove the goal `|- Σ' (a:A) (b: B a) (c:C a b), unit` given a list of terms `a, b, c`. -/\nmeta def mk_sigma_mem : list expr → tactic unit\n| (x::xs) := fconstructor >> exact x >> mk_sigma_mem xs\n| [] := fconstructor $> ()\n\n/-- This function is called to prove `a : T |- a ∈ S.1` where `S` is the `finset_above` constructed\nby `mk_finset`, after the initial cases on `a : T`, producing a list of subgoals. For each case,\nwe have to navigate past all the variants that don't apply (which is what the `tac` input tactic\ndoes), and then call either `finset_above.mem_cons_self` for trivial variants or\n`finset_above.mem_union_left` and `finset_in.mem_mk` for nontrivial variants. Either way the proof\nis quite simple. -/\nmeta def mk_finset_total : tactic unit → list (name × list expr) → tactic unit\n| tac [] := done\n| tac ((_, xs) :: gs) := do\n tac,\n b ← succeeds (applyc ``finset_above.mem_cons_self),\n if b then\n mk_finset_total (tac >> applyc ``finset_above.mem_cons_of_mem) gs\n else do\n applyc ``finset_above.mem_union_left,\n applyc ``finset_in.mem_mk {new_goals := new_goals.all},\n mk_sigma_mem xs,\n reflexivity,\n mk_finset_total (tac >> applyc ``finset_above.mem_union_right) gs\n\nend derive_fintype\n\nopen tactic.derive_fintype\n\n/-- Proves `|- fintype T` where `T` is a non-recursive inductive type with no indices,\nwhere all arguments to all constructors are fintypes. -/\nmeta def mk_fintype_instance : tactic unit :=\ndo\n intros,\n `(fintype %%e) ← target >>= whnf,\n (const I ls, args) ← pure (get_app_fn_args e),\n env ← get_env,\n let cs := env.constructors_of I,\n guard (env.inductive_num_indices I = 0) <|>\n fail \"@[derive fintype]: inductive indices are not supported\",\n guard (¬ env.is_recursive I) <|>\n fail (\"@[derive fintype]: recursive inductive types are \" ++\n \"not supported (they are also usually infinite)\"),\n applyc ``mk_fintype {new_goals := new_goals.all},\n intro1 >>= cases >>= (λ gs,\n gs.enum.mmap' $ λ ⟨i, _⟩, exact (reflect i)),\n mk_finset ls args 0 cs,\n intro1 >>= cases >>= mk_finset_total skip\n\n/--\nTries to derive a `fintype` instance for inductives and structures.\n\nFor example:\n```\n@[derive fintype]\ninductive foo (n m : ℕ)\n| zero : foo\n| one : bool → foo\n| two : fin n → fin m → foo\n```\nHere, `@[derive fintype]` adds the instance `foo.fintype`. The underlying finset\ndefinitionally unfolds to a list that enumerates the elements of the inductive in\nlexicographic order.\n\nIf the structure/inductive has a type parameter `α`, then the generated instance will have an\nargument `fintype α`, even if it is not used. (This is due to the implementation using\n`instance_derive_handler`.)\n-/\n@[derive_handler] meta def fintype_instance : derive_handler :=\ninstance_derive_handler ``fintype mk_fintype_instance\n\nend tactic\n", "meta": {"author": "leanprover-community", "repo": "mathlib", "sha": "5e526d18cea33550268dcbbddcb822d5cde40654", "save_path": "github-repos/lean/leanprover-community-mathlib", "path": "github-repos/lean/leanprover-community-mathlib/mathlib-5e526d18cea33550268dcbbddcb822d5cde40654/src/tactic/derive_fintype.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47657965106367595, "lm_q2_score": 0.05184547086167825, "lm_q1q2_score": 0.024708496412490597}} {"text": "/-\nCopyright (c) 2022 Andrew Yang. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Andrew Yang\n-/\nimport category_theory.elementwise\nimport category_theory.adjunction.evaluation\nimport category_theory.sites.sheafification\n\n/-!\n\n# Subsheaf of types\n\nWe define the sub(pre)sheaf of a type valued presheaf.\n\n## Main results\n\n- `category_theory.grothendieck_topology.subpresheaf` :\n A subpresheaf of a presheaf of types.\n- `category_theory.grothendieck_topology.subpresheaf.sheafify` :\n The sheafification of a subpresheaf as a subpresheaf. Note that this is a sheaf only when the\n whole sheaf is.\n- `category_theory.grothendieck_topology.subpresheaf.sheafify_is_sheaf` :\n The sheafification is a sheaf\n- `category_theory.grothendieck_topology.subpresheaf.sheafify_lift` :\n The descent of a map into a sheaf to the sheafification.\n- `category_theory.grothendieck_topology.image_sheaf` : The image sheaf of a morphism.\n- `category_theory.grothendieck_topology.image_factorization` : The image sheaf as a\n `limits.image_factorization`.\n-/\n\nuniverses w v u\n\nopen opposite category_theory\n\nnamespace category_theory.grothendieck_topology\n\nvariables {C : Type u} [category.{v} C] (J : grothendieck_topology C)\n\n/-- A subpresheaf of a presheaf consists of a subset of `F.obj U` for every `U`,\ncompatible with the restriction maps `F.map i`. -/\n@[ext]\nstructure subpresheaf (F : Cᵒᵖ ⥤ Type w) :=\n(obj : Π U, set (F.obj U))\n(map : Π {U V : Cᵒᵖ} (i : U ⟶ V), (obj U) ⊆ (F.map i) ⁻¹' (obj V))\n\nvariables {F F' F'' : Cᵒᵖ ⥤ Type w} (G G' : subpresheaf F)\n\ninstance : partial_order (subpresheaf F) :=\npartial_order.lift subpresheaf.obj subpresheaf.ext\n\ninstance : has_top (subpresheaf F) :=\n⟨⟨λ U, ⊤, λ U V i x h, _root_.trivial⟩⟩\n\ninstance : nonempty (subpresheaf F) := infer_instance\n\n/-- The subpresheaf as a presheaf. -/\n@[simps]\ndef subpresheaf.to_presheaf : Cᵒᵖ ⥤ Type w :=\n{ obj := λ U, G.obj U,\n map := λ U V i x, ⟨F.map i x, G.map i x.prop⟩,\n map_id' := λ X, by { ext ⟨x, _⟩, dsimp, rw F.map_id, refl },\n map_comp' := λ X Y Z i j, by { ext ⟨x, _⟩, dsimp, rw F.map_comp, refl } }\n\ninstance {U} : has_coe (G.to_presheaf.obj U) (F.obj U) :=\ncoe_subtype\n\n/-- The inclusion of a subpresheaf to the original presheaf. -/\n@[simps]\ndef subpresheaf.ι : G.to_presheaf ⟶ F :=\n{ app := λ U x, x }\n\ninstance : mono G.ι :=\n⟨λ H f₁ f₂ e, nat_trans.ext f₁ f₂ $ funext $ λ U,\n funext $ λ x, subtype.ext $ congr_fun (congr_app e U) x⟩\n\n/-- The inclusion of a subpresheaf to a larger subpresheaf -/\n@[simps]\ndef subpresheaf.hom_of_le {G G' : subpresheaf F} (h : G ≤ G') : G.to_presheaf ⟶ G'.to_presheaf :=\n{ app := λ U x, ⟨x, h U x.prop⟩ }\n\ninstance {G G' : subpresheaf F} (h : G ≤ G') : mono (subpresheaf.hom_of_le h) :=\n⟨λ H f₁ f₂ e, nat_trans.ext f₁ f₂ $ funext $ λ U,\n funext $ λ x, subtype.ext $ (congr_arg subtype.val $ (congr_fun (congr_app e U) x : _) : _)⟩\n\n@[simp, reassoc]\nlemma subpresheaf.hom_of_le_ι {G G' : subpresheaf F} (h : G ≤ G') :\n subpresheaf.hom_of_le h ≫ G'.ι = G.ι :=\nby { ext, refl }\n\ninstance : is_iso (subpresheaf.ι (⊤ : subpresheaf F)) :=\nbegin\n apply_with nat_iso.is_iso_of_is_iso_app { instances := ff },\n { intro X, rw is_iso_iff_bijective,\n exact ⟨subtype.coe_injective, λ x, ⟨⟨x, _root_.trivial⟩, rfl⟩⟩ }\nend\n\nlemma subpresheaf.eq_top_iff_is_iso : G = ⊤ ↔ is_iso G.ι :=\nbegin\n split,\n { rintro rfl, apply_instance },\n { introI H, ext U x, apply (iff_true _).mpr, rw ← is_iso.inv_hom_id_apply (G.ι.app U) x,\n exact ((inv (G.ι.app U)) x).2 }\nend\n\n/-- If the image of a morphism falls in a subpresheaf, then the morphism factors through it. -/\n@[simps]\ndef subpresheaf.lift (f : F' ⟶ F) (hf : ∀ U x, f.app U x ∈ G.obj U) : F' ⟶ G.to_presheaf :=\n{ app := λ U x, ⟨f.app U x, hf U x⟩,\n naturality' := by { have := elementwise_of f.naturality, intros, ext, simp [this] } }\n\n@[simp, reassoc]\nlemma subpresheaf.lift_ι (f : F' ⟶ F) (hf : ∀ U x, f.app U x ∈ G.obj U) :\n G.lift f hf ≫ G.ι = f := by { ext, refl }\n\n/-- Given a subpresheaf `G` of `F`, an `F`-section `s` on `U`, we may define a sieve of `U`\nconsisting of all `f : V ⟶ U` such that the restriction of `s` along `f` is in `G`. -/\n@[simps]\ndef subpresheaf.sieve_of_section {U : Cᵒᵖ} (s : F.obj U) : sieve (unop U) :=\n{ arrows := λ V f, F.map f.op s ∈ G.obj (op V),\n downward_closed' := λ V W i hi j,\n by { rw [op_comp, functor_to_types.map_comp_apply], exact G.map _ hi } }\n\n/-- Given a `F`-section `s` on `U` and a subpresheaf `G`, we may define a family of elements in\n`G` consisting of the restrictions of `s` -/\ndef subpresheaf.family_of_elements_of_section {U : Cᵒᵖ} (s : F.obj U) :\n (G.sieve_of_section s).1.family_of_elements G.to_presheaf :=\nλ V i hi, ⟨F.map i.op s, hi⟩\n\nlemma subpresheaf.family_of_elements_compatible {U : Cᵒᵖ} (s : F.obj U) :\n (G.family_of_elements_of_section s).compatible :=\nbegin\n intros Y₁ Y₂ Z g₁ g₂ f₁ f₂ h₁ h₂ e,\n ext1,\n change F.map g₁.op (F.map f₁.op s) = F.map g₂.op (F.map f₂.op s),\n rw [← functor_to_types.map_comp_apply, ← functor_to_types.map_comp_apply,\n ← op_comp, ← op_comp, e],\nend\n\nlemma subpresheaf.nat_trans_naturality (f : F' ⟶ G.to_presheaf) {U V : Cᵒᵖ} (i : U ⟶ V)\n (x : F'.obj U) :\n (f.app V (F'.map i x)).1 = F.map i (f.app U x).1 :=\ncongr_arg subtype.val (functor_to_types.naturality _ _ f i x)\n\ninclude J\n\n/-- The sheafification of a subpresheaf as a subpresheaf.\nNote that this is a sheaf only when the whole presheaf is a sheaf. -/\ndef subpresheaf.sheafify : subpresheaf F :=\n{ obj := λ U, { s | G.sieve_of_section s ∈ J (unop U) },\n map := begin\n rintros U V i s hs,\n refine J.superset_covering _ (J.pullback_stable i.unop hs),\n intros _ _ h,\n dsimp at h ⊢,\n rwa ← functor_to_types.map_comp_apply,\n end }\n\nlemma subpresheaf.le_sheafify : G ≤ G.sheafify J :=\nbegin\n intros U s hs,\n change _ ∈ J _,\n convert J.top_mem _,\n rw eq_top_iff,\n rintros V i -,\n exact G.map i.op hs,\nend\n\nvariable {J}\n\nlemma subpresheaf.eq_sheafify (h : presieve.is_sheaf J F)\n (hG : presieve.is_sheaf J G.to_presheaf) : G = G.sheafify J :=\nbegin\n apply (G.le_sheafify J).antisymm,\n intros U s hs,\n suffices : ((hG _ hs).amalgamate _ (G.family_of_elements_compatible s)).1 = s,\n { rw ← this, exact ((hG _ hs).amalgamate _ (G.family_of_elements_compatible s)).2 },\n apply (h _ hs).is_separated_for.ext,\n intros V i hi,\n exact (congr_arg subtype.val ((hG _ hs).valid_glue (G.family_of_elements_compatible s) _ hi) : _)\nend\n\nlemma subpresheaf.sheafify_is_sheaf (hF : presieve.is_sheaf J F) :\n presieve.is_sheaf J (G.sheafify J).to_presheaf :=\nbegin\n intros U S hS x hx,\n let S' := sieve.bind S (λ Y f hf, G.sieve_of_section (x f hf).1),\n have := λ {V} {i : V ⟶ U} (hi : S' i), hi,\n choose W i₁ i₂ hi₂ h₁ h₂,\n dsimp [-sieve.bind_apply] at *,\n let x'' : presieve.family_of_elements F S' :=\n λ V i hi, F.map (i₁ hi).op (x _ (hi₂ hi)),\n have H : ∀ s, x.is_amalgamation s ↔ x''.is_amalgamation s.1,\n { intro s,\n split,\n { intros H V i hi,\n dsimp only [x''],\n conv_lhs { rw ← h₂ hi },\n rw ← H _ (hi₂ hi),\n exact functor_to_types.map_comp_apply F (i₂ hi).op (i₁ hi).op _ },\n { intros H V i hi,\n ext1,\n apply (hF _ (x i hi).2).is_separated_for.ext,\n intros V' i' hi',\n have hi'' : S' (i' ≫ i) := ⟨_, _, _, hi, hi', rfl⟩,\n have := H _ hi'',\n rw [op_comp, F.map_comp] at this,\n refine this.trans (congr_arg subtype.val (hx _ _ (hi₂ hi'') hi (h₂ hi''))) } },\n have : x''.compatible,\n { intros V₁ V₂ V₃ g₁ g₂ g₃ g₄ S₁ S₂ e,\n rw [← functor_to_types.map_comp_apply, ← functor_to_types.map_comp_apply],\n exact congr_arg subtype.val\n (hx (g₁ ≫ i₁ S₁) (g₂ ≫ i₁ S₂) (hi₂ S₁) (hi₂ S₂) (by simp only [category.assoc, h₂, e])) },\n obtain ⟨t, ht, ht'⟩ := hF _ (J.bind_covering hS (λ V i hi, (x i hi).2)) _ this,\n refine ⟨⟨t, _⟩, (H ⟨t, _⟩).mpr ht, λ y hy, subtype.ext (ht' _ ((H _).mp hy))⟩,\n show G.sieve_of_section t ∈ J _,\n refine J.superset_covering _ (J.bind_covering hS (λ V i hi, (x i hi).2)),\n intros V i hi,\n dsimp,\n rw ht _ hi,\n exact h₁ hi\nend\n\nlemma subpresheaf.eq_sheafify_iff (h : presieve.is_sheaf J F) :\n G = G.sheafify J ↔ presieve.is_sheaf J G.to_presheaf :=\n⟨λ e, e.symm ▸ G.sheafify_is_sheaf h, G.eq_sheafify h⟩\n\nlemma subpresheaf.is_sheaf_iff (h : presieve.is_sheaf J F) :\n presieve.is_sheaf J G.to_presheaf ↔\n ∀ U (s : F.obj U), G.sieve_of_section s ∈ J (unop U) → s ∈ G.obj U :=\nbegin\n rw ← G.eq_sheafify_iff h,\n change _ ↔ G.sheafify J ≤ G,\n exact ⟨eq.ge, (G.le_sheafify J).antisymm⟩\nend\n\nlemma subpresheaf.sheafify_sheafify (h : presieve.is_sheaf J F) :\n (G.sheafify J).sheafify J = G.sheafify J :=\n((subpresheaf.eq_sheafify_iff _ h).mpr $ G.sheafify_is_sheaf h).symm\n\n/-- The lift of a presheaf morphism onto the sheafification subpresheaf. -/\nnoncomputable\ndef subpresheaf.sheafify_lift (f : G.to_presheaf ⟶ F') (h : presieve.is_sheaf J F') :\n (G.sheafify J).to_presheaf ⟶ F' :=\n{ app := λ U s,\n (h _ s.prop).amalgamate _ ((G.family_of_elements_compatible ↑s).comp_presheaf_map f),\n naturality' :=\n begin\n intros U V i,\n ext s,\n apply (h _ ((subpresheaf.sheafify J G).to_presheaf.map i s).prop).is_separated_for.ext,\n intros W j hj,\n refine (presieve.is_sheaf_for.valid_glue _ _ _ hj).trans _,\n dsimp,\n conv_rhs { rw ← functor_to_types.map_comp_apply },\n change _ = F'.map (j ≫ i.unop).op _,\n refine eq.trans _ (presieve.is_sheaf_for.valid_glue _ _ _ _).symm,\n { dsimp at ⊢ hj, rwa functor_to_types.map_comp_apply },\n { dsimp [presieve.family_of_elements.comp_presheaf_map],\n congr' 1,\n ext1,\n exact (functor_to_types.map_comp_apply _ _ _ _).symm }\n end }\n\nlemma subpresheaf.to_sheafify_lift (f : G.to_presheaf ⟶ F') (h : presieve.is_sheaf J F') :\n subpresheaf.hom_of_le (G.le_sheafify J) ≫ G.sheafify_lift f h = f :=\nbegin\n ext U s,\n apply (h _ ((subpresheaf.hom_of_le (G.le_sheafify J)).app U s).prop).is_separated_for.ext,\n intros V i hi,\n have := elementwise_of f.naturality,\n exact (presieve.is_sheaf_for.valid_glue _ _ _ hi).trans (this _ _)\nend\n\nlemma subpresheaf.to_sheafify_lift_unique (h : presieve.is_sheaf J F')\n (l₁ l₂ : (G.sheafify J).to_presheaf ⟶ F')\n (e : subpresheaf.hom_of_le (G.le_sheafify J) ≫ l₁ =\n subpresheaf.hom_of_le (G.le_sheafify J) ≫ l₂) : l₁ = l₂ :=\nbegin\n ext U ⟨s, hs⟩,\n apply (h _ hs).is_separated_for.ext,\n rintros V i hi,\n dsimp at hi,\n erw [← functor_to_types.naturality, ← functor_to_types.naturality],\n exact (congr_fun (congr_app e $ op V) ⟨_, hi⟩ : _)\nend\n\nlemma subpresheaf.sheafify_le (h : G ≤ G') (hF : presieve.is_sheaf J F)\n (hG' : presieve.is_sheaf J G'.to_presheaf) :\n G.sheafify J ≤ G' :=\nbegin\n intros U x hx,\n convert ((G.sheafify_lift (subpresheaf.hom_of_le h) hG').app U ⟨x, hx⟩).2,\n apply (hF _ hx).is_separated_for.ext,\n intros V i hi,\n have := congr_arg (λ f : G.to_presheaf ⟶ G'.to_presheaf, (nat_trans.app f (op V) ⟨_, hi⟩).1)\n (G.to_sheafify_lift (subpresheaf.hom_of_le h) hG'),\n convert this.symm,\n erw ← subpresheaf.nat_trans_naturality,\n refl,\nend\n\nomit J\n\nsection image\n\n/-- The image presheaf of a morphism, whose components are the set-theoretic images. -/\n@[simps]\ndef image_presheaf (f : F' ⟶ F) : subpresheaf F :=\n{ obj := λ U, set.range (f.app U),\n map := λ U V i,\n by { rintros _ ⟨x, rfl⟩, have := elementwise_of f.naturality, exact ⟨_, this i x⟩ } }\n\n@[simp] lemma top_subpresheaf_obj (U) : (⊤ : subpresheaf F).obj U = ⊤ := rfl\n\n@[simp]\nlemma image_presheaf_id : image_presheaf (𝟙 F) = ⊤ :=\nby { ext, simp }\n\n/-- A morphism factors through the image presheaf. -/\n@[simps]\ndef to_image_presheaf (f : F' ⟶ F) : F' ⟶ (image_presheaf f).to_presheaf :=\n(image_presheaf f).lift f (λ U x, set.mem_range_self _)\n\nvariables (J)\n\n/-- A morphism factors through the sheafification of the image presheaf. -/\n@[simps]\ndef to_image_presheaf_sheafify (f : F' ⟶ F) : F' ⟶ ((image_presheaf f).sheafify J).to_presheaf :=\n to_image_presheaf f ≫ subpresheaf.hom_of_le ((image_presheaf f).le_sheafify J)\n\nvariables {J}\n\n@[simp, reassoc]\nlemma to_image_presheaf_ι (f : F' ⟶ F) : to_image_presheaf f ≫ (image_presheaf f).ι = f :=\n(image_presheaf f).lift_ι _ _\n\nlemma image_presheaf_comp_le (f₁ : F ⟶ F') (f₂ : F' ⟶ F'') :\n image_presheaf (f₁ ≫ f₂) ≤ image_presheaf f₂ :=\nλ U x hx, ⟨f₁.app U hx.some, hx.some_spec⟩\n\ninstance {F F' : Cᵒᵖ ⥤ Type (max v w)} (f : F ⟶ F') [hf : mono f] :\n is_iso (to_image_presheaf f) :=\nbegin\n apply_with nat_iso.is_iso_of_is_iso_app { instances := ff },\n intro X,\n rw is_iso_iff_bijective,\n split,\n { intros x y e,\n have := (nat_trans.mono_iff_mono_app _ _).mp hf X,\n rw mono_iff_injective at this,\n exact this (congr_arg subtype.val e : _) },\n { rintro ⟨_, ⟨x, rfl⟩⟩, exact ⟨x, rfl⟩ }\nend\n\n/-- The image sheaf of a morphism between sheaves, defined to be the sheafification of\n`image_presheaf`. -/\n@[simps]\ndef image_sheaf {F F' : Sheaf J (Type w)} (f : F ⟶ F') : Sheaf J (Type w) :=\n⟨((image_presheaf f.1).sheafify J).to_presheaf,\n by { rw is_sheaf_iff_is_sheaf_of_type, apply subpresheaf.sheafify_is_sheaf,\n rw ← is_sheaf_iff_is_sheaf_of_type, exact F'.2 }⟩\n\n/-- A morphism factors through the image sheaf. -/\n@[simps]\ndef to_image_sheaf {F F' : Sheaf J (Type w)} (f : F ⟶ F') : F ⟶ image_sheaf f :=\n⟨to_image_presheaf_sheafify J f.1⟩\n\n/-- The inclusion of the image sheaf to the target. -/\n@[simps]\ndef image_sheaf_ι {F F' : Sheaf J (Type w)} (f : F ⟶ F') : image_sheaf f ⟶ F' :=\n⟨subpresheaf.ι _⟩\n\n@[simp, reassoc]\nlemma to_image_sheaf_ι {F F' : Sheaf J (Type w)} (f : F ⟶ F') :\n to_image_sheaf f ≫ image_sheaf_ι f = f :=\nby { ext1, simp [to_image_presheaf_sheafify] }\n\ninstance {F F' : Sheaf J (Type w)} (f : F ⟶ F') : mono (image_sheaf_ι f) :=\n(Sheaf_to_presheaf J _).mono_of_mono_map (by { dsimp, apply_instance })\n\ninstance {F F' : Sheaf J (Type w)} (f : F ⟶ F') : epi (to_image_sheaf f) :=\nbegin\n refine ⟨λ G' g₁ g₂ e, _⟩,\n ext U ⟨s, hx⟩,\n apply ((is_sheaf_iff_is_sheaf_of_type J _).mp G'.2 _ hx).is_separated_for.ext,\n rintros V i ⟨y, e'⟩,\n change (g₁.val.app _ ≫ G'.val.map _) _ = (g₂.val.app _ ≫ G'.val.map _) _,\n rw [← nat_trans.naturality, ← nat_trans.naturality],\n have E : (to_image_sheaf f).val.app (op V) y =\n (image_sheaf f).val.map i.op ⟨s, hx⟩ := subtype.ext e',\n have := congr_arg (λ f : F ⟶ G', (Sheaf.hom.val f).app _ y) e,\n dsimp at this ⊢,\n convert this; exact E.symm\nend\n\n/-- The mono factorization given by `image_sheaf` for a morphism. -/\ndef image_mono_factorization {F F' : Sheaf J (Type w)} (f : F ⟶ F') :\n limits.mono_factorisation f :=\n{ I := image_sheaf f,\n m := image_sheaf_ι f,\n e := to_image_sheaf f }\n\n/-- The mono factorization given by `image_sheaf` for a morphism is an image. -/\nnoncomputable\ndef image_factorization {F F' : Sheaf J (Type (max v u))} (f : F ⟶ F') :\n limits.image_factorisation f :=\n{ F := image_mono_factorization f,\n is_image :=\n { lift := λ I, begin\n haveI := (Sheaf.hom.mono_iff_presheaf_mono J _ _).mp I.m_mono,\n refine ⟨subpresheaf.hom_of_le _ ≫ inv (to_image_presheaf I.m.1)⟩,\n apply subpresheaf.sheafify_le,\n { conv_lhs { rw ← I.fac }, apply image_presheaf_comp_le },\n { rw ← is_sheaf_iff_is_sheaf_of_type, exact F'.2 },\n { apply presieve.is_sheaf_iso J (as_iso $ to_image_presheaf I.m.1),\n rw ← is_sheaf_iff_is_sheaf_of_type, exact I.I.2 }\n end,\n lift_fac' := λ I, begin\n ext1,\n dsimp [image_mono_factorization],\n generalize_proofs h,\n rw [← subpresheaf.hom_of_le_ι h, category.assoc],\n congr' 1,\n rw [is_iso.inv_comp_eq, to_image_presheaf_ι],\n end } }\n\ninstance : limits.has_images (Sheaf J (Type (max v u))) :=\n⟨λ _ _ f, ⟨⟨image_factorization f⟩⟩⟩\n\nend image\n\nend category_theory.grothendieck_topology\n", "meta": {"author": "leanprover-community", "repo": "mathlib", "sha": "5e526d18cea33550268dcbbddcb822d5cde40654", "save_path": "github-repos/lean/leanprover-community-mathlib", "path": "github-repos/lean/leanprover-community-mathlib/mathlib-5e526d18cea33550268dcbbddcb822d5cde40654/src/category_theory/sites/subsheaf.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46101677931231594, "lm_q2_score": 0.0534033260334505, "lm_q1q2_score": 0.024619829372506907}} {"text": "import Mathlib.Tactic.Linarith\nimport Aesop\n-- A translation from SSA + Regions to Tree, with no proofs.\n-- this allows for easy unfolding of the semantics.\n-- If we carry around proofs of well formedness, the dependent typing\n-- of the well-formedness leads to stuck terms.\n-- Thus, we eschew the need to have proofs, and simply YOLO translate from\n-- the origina SSA + Regions program into Tree.\n\nnamespace SSARgn2Tree\n\ninductive VarName\n| null\n| x0\n| x1\n| x2\n| x3\n| x4\n| x5\n| x6\n| x7\n| y1\n| y2\n| y3\n| y4\n| z1\n| z2\n| z3\n| z4\nderiving DecidableEq\n\nsection StxSem\n\n-- | The environment is a mapping from variable names to values.\nabbrev Env (α : Type) := VarName → α\n\n-- | Extend the environment with a new variable.\n@[simp]\ndef Env.extend (name : VarName) (v : α) (e: Env α) : Env α :=\n fun name' => if name = name' then v else e name'\n\n@[simp]\ndef Env.empty [Inhabited α] : Env α :=\n fun _ => default\n\n@[simp]\ndef Env.map (f : α → β) (e : Env α) : Env β :=\n fun name => f (e name)\n\nnotation \"∅\" => Env.empty\nnotation e \"[\" name \"↦\" v \"]\" => Env.extend name v e\n\n\n-- The input semantics given by the user.\nclass UserSemantics (opcode : Type) where\n -- | Arguments given as (, , ... )\n -- | Consider not allowing users to not be access all of 'Env'.\n opcodeEval (op: opcode) (vals : Int × Int) (rgns : (Int × Int → Int)) : Int\n\nattribute [simp] UserSemantics.opcodeEval\n\ninductive ASTKind : Type where\n| O : ASTKind\n| Os : ASTKind\n| R : ASTKind\nderiving Inhabited, DecidableEq\n\n-- | The operations of the language.\ninductive AST (opcode : Type): ASTKind → Type where\n| assign (ret : VarName) (op : opcode)\n (args : VarName × VarName)\n (rgns : AST opcode .R) : AST opcode .O\n| ops1 (op : AST opcode .O) : AST opcode .Os\n| opsmany (op : AST opcode .O) (ops : AST opcode .Os) : AST opcode .Os\n| rgn (args : VarName × VarName) (body : AST opcode .Os) : AST opcode .R\n| rgn0 : AST opcode .R\n\ndef AST.retname : AST opcode .O → VarName\n| .assign (ret := ret) .. => ret\n\ninstance [Inhabited opcode] : Inhabited (AST opcode .O) where\n default := .assign .x0 default (.x0, .x0) .rgn0\n\ninstance [Inhabited opcode] : Inhabited (AST opcode .Os) where\n default := .ops1 default\n\ninstance [Inhabited opcode] : Inhabited (AST opcode .R) where\n default := .rgn (.x0, .x0) default\n\n\n\n@[simp]\ndef Ops.ofList [Inhabited opcode] : List (AST opcode .O) → AST opcode .Os\n| [] => panic! \"need non-empty list\"\n| [x] => .ops1 x\n| x :: xs => .opsmany x (Ops.ofList xs)\n\n@[reducible, simp]\ninstance [Inhabited opcode] : Coe (List (AST opcode .O)) (AST opcode .Os) := ⟨Ops.ofList⟩\n\n@[simp, reducible]\ndef ASTKind.eval : ASTKind → Type\n| .O => Int\n| .Os => Int\n| .R => (Int × Int → Int)\n-- evaluate an operation with repect to a particular user semantics.\n@[simp]\ndef AST.eval [S: UserSemantics opcode]\n {astk: ASTKind} (e: Env Int): AST opcode astk → astk.eval × Env Int\n| .assign ret op args r =>\n let (arg1, arg2) := args\n let retval := S.opcodeEval op (e arg1, e arg2) (r.eval e).fst\n (retval, e.extend ret retval)\n| .ops1 op =>\n let (out, env) := op.eval e\n (out, env)\n| .opsmany op ops =>\n let e' := (op.eval e).snd\n ops.eval e'\n| .rgn args body =>\n (fun vals =>\n let e := Env.empty\n let e1 := e.extend args.fst vals.fst\n let e2 := e1.extend args.snd vals.snd\n let (outval, _) := body.eval e2\n outval, e)\n| .rgn0 => (fun _ => default, e)\n\nend StxSem\n\n\nsection Tree\n\ninductive CtreeKind\n| O -- op\n| R -- region (higher order)\nderiving Inhabited\n\n-- closed trees, leaves are integers.\ninductive Ctree (opcode : Type) : CtreeKind → Type where\n| binop\n (op : opcode)\n (lhs : Ctree opcode .O)\n (rhs : Ctree opcode .O)\n (rgns: Ctree opcode .R) : Ctree opcode .O\n| rgn (f : Int × Int → Ctree opcode .O) : Ctree opcode .R\n| rgn0 : Ctree opcode .R\n| leaf (val : Int) : Ctree opcode .O\n\ninstance : Inhabited (Ctree opcode .O) where\n default := .leaf 10\n\ninstance : Inhabited (Ctree opcode .R) where\n default := .rgn0\n\n-- convert an AST into a closed tree under the given environment\n-- note that translation into a closed tree needs an environment,\n-- to learn the values of variables.\n-- This version has an `_` in the name since it needs a `Ctree.Env`, not an\n-- `Env`. We will writea helper that converts `Env` into `Ctree.Env`.\n@[simp, reducible]\ndef ASTKind.toCTree (opcode : Type) : ASTKind → Type\n| .O => Ctree opcode .O\n| .Os => Ctree opcode .O\n| .R => Ctree opcode .R\n\n@[simp]\ndef AST.toCtree_ {astk: ASTKind} (e : Env (Ctree opcode .O)) :\n AST opcode astk → (astk.toCTree opcode) × Env (Ctree opcode .O)\n| .assign ret opcode (u, v) r =>\n let rval := (r.toCtree_ e).fst\n let t := .binop opcode (e u) (e v) rval\n (t, e.extend ret t)\n| .rgn0 => (.rgn0, e)\n| .rgn args body =>\n (.rgn fun vals =>\n let e := Env.empty\n let e1 := e.extend args.fst (.leaf vals.fst)\n let e2 := e1.extend args.snd (.leaf vals.snd)\n (body.toCtree_ e2).fst, e)\n| .ops1 op =>\n let (val, e) :=op.toCtree_ e\n (val, e)\n| .opsmany os o =>\n let (_, e) := os.toCtree_ e\n o.toCtree_ e\n\n-- wrap every element in a (.leaf) constructor\n@[simp]\ndef Ctree.Env.ofEnv (e: Env Int) : Env (Ctree opcode .O) :=\n fun name => .leaf (e name)\n\n-- this converts an AST into a Ctree, given an environment\n-- and an AST.\n@[simp]\ndef Op.toCtree (a: AST opcode .O) (e: Env Int): Ctree opcode .O :=\n (a.toCtree_ (Ctree.Env.ofEnv e)).fst\n\n@[simp]\ndef Ops.toCtree (a: AST opcode .Os) (e: Env Int) : Ctree opcode .O :=\n (a.toCtree_ (Ctree.Env.ofEnv e)).fst\n\n@[simp]\ndef Region.toCtree (a: AST opcode .R) (e: Env Int) : Ctree opcode .R :=\n (a.toCtree_ (Ctree.Env.ofEnv e)).fst\n\n\n-- evaluate a Ctree. note that this needs no environment.\n@[simp]\ndef CtreeKind.eval : CtreeKind → Type\n| .O => Int\n| .R => Int × Int → Int\n\n-- Note: is this literally \"just\" staging the partial evaluation against the environment?\n@[simp]\ndef Ctree.eval [UserSemantics opcode] : Ctree opcode treek → treek.eval\n| .binop o l r rs =>\n UserSemantics.opcodeEval o (l.eval, r.eval) rs.eval\n| .leaf v => v\n| .rgn0 => fun _ => default\n| .rgn f => fun args => (f args).eval\n\nend Tree\n\nnamespace MultipleInstructionTree\ninductive Opcode\n| add\n| mul\n| loop : Opcode\n| ite : Opcode\n| run : Opcode\n| runnot : Opcode\n| not : Opcode\n| const : Int → Opcode\nderiving Inhabited\n\ndef loopSemantics (n : Nat) (f : Int → Int) (v : Int) : Int :=\n match n with\n | 0 => v -- inline id\n | n + 1 => f (loopSemantics n f v) -- inline ∘\n\n@[simp]\ninstance : UserSemantics Opcode where\n opcodeEval\n | .not, ⟨a, _⟩, _ => if a = 0 then 1 else 0\n | .mul, ⟨a, b⟩, _ => a * b\n | .add, ⟨a, b⟩, _ => a + b\n | .const i, ⟨_a, _b⟩, _ => i\n | .run, ⟨v, w⟩, r => r ⟨v, w⟩\n | .runnot, ⟨v, w⟩, r => r ⟨if v = 0 then 1 else 0, w⟩ -- execute: 'r(not v, w)'\n | .loop, ⟨n, init⟩, r => loopSemantics n.toNat (fun i => r ⟨i, 0⟩) init\n | _, _, _ => 42\n\n\ndef x_add_4_times_mul_val_eq (env: Env Int):\n let p : AST Opcode .Os :=\n Ops.ofList [\n .assign .x1 .add (.x0, .x0) .rgn0,\n .assign .x2 .add (.x1, .x1) .rgn0\n ]\n let q : AST Opcode .Os := Ops.ofList [\n .assign .x1 (.const 4) (.x0, .x0) .rgn0\n , .assign .x2 .mul (.x1, .x0) .rgn0\n ]\n (Ops.toCtree p env).eval = (Ops.toCtree q env).eval := by {\n simp only [Ops.ofList, AST.eval, Ops.toCtree, AST.toCtree_];\n -- see that there are environments, which are folded away when calling\n -- Ctree.eval.\n simp[Ctree.eval];\n linarith\n }\n\n\ndef run_inline:\n let p : AST Opcode .R :=\n AST.rgn ⟨.x0, .x1⟩ $ Ops.ofList [\n .assign .x2 .add (.x0, .x1) .rgn0 -- x2 := x0 + x1\n ]\n let q : AST Opcode .R :=\n AST.rgn ⟨.x0, .x1⟩ $ Ops.ofList [\n .assign .x2 .run (.x0, .x1) (AST.rgn ⟨.x5, .x6⟩ (Ops.ofList [ -- x2 := run (x0, x1) { ^(x5, x6): return x5 + x6 }\n .assign .y1 .add (.x5, .x6) .rgn0\n ]))\n ]\n (Region.toCtree p Env.empty).eval = (Region.toCtree q Env.empty).eval := by {\n simp\n }\n\n\n-- trying to convert an AST to a Ctree at any environment\n-- is equivalent to converting it in an empty environment.\n@[simp]\ntheorem AST.toCtree_rgn_equiv_empty (r: AST opcode .R) [Inhabited opcode] :\n (AST.toCtree_ env r).fst = (AST.toCtree_ Env.empty r).fst := by {\n simp\n cases r <;> simp;\n}\n\ndef runnot_inline :\n let p : AST Opcode .R :=\n AST.rgn ⟨.x0, .x1⟩ $ Ops.ofList [\n .assign .y1 .run ⟨.x0, .x1⟩ r -- y1 := r(x0, x1)\n ]\n (Region.toCtree p Env.empty).eval = (Region.toCtree r Env.empty).eval := by {\n simp\n }\n\nend MultipleInstructionTree\n\nend SSARgn2Tree\n", "meta": {"author": "bollu", "repo": "ssa", "sha": "19c73e48500bfe3f618c360423966677adb4673e", "save_path": "github-repos/lean/bollu-ssa", "path": "github-repos/lean/bollu-ssa/ssa-19c73e48500bfe3f618c360423966677adb4673e/SSA/Experiment/SSARgn2TreeNoProof.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4726834766204328, "lm_q2_score": 0.05184546426914175, "lm_q1q2_score": 0.024506494297738348}} {"text": "/-\nCopyright (c) 2018 Mario Carneiro. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthor: Mario Carneiro\n\nDefine a sequence of simple machine languages, starting with Turing\nmachines and working up to more complex lanaguages based on\nWang B-machines.\n-/\nimport data.fintype data.pfun logic.relation\n\nopen relation\n\nnamespace turing\n\n/-- A direction for the turing machine `move` command, either\n left or right. -/\n@[derive decidable_eq]\ninductive dir | left | right\n\ndef tape (Γ) := Γ × list Γ × list Γ\n\ndef tape.mk {Γ} [inhabited Γ] (l : list Γ) : tape Γ :=\n(l.head, [], l.tail)\n\ndef tape.mk' {Γ} [inhabited Γ] (L R : list Γ) : tape Γ :=\n(R.head, L, R.tail)\n\ndef tape.move {Γ} [inhabited Γ] : dir → tape Γ → tape Γ\n| dir.left (a, L, R) := (L.head, L.tail, a :: R)\n| dir.right (a, L, R) := (R.head, a :: L, R.tail)\n\ndef tape.nth {Γ} [inhabited Γ] : tape Γ → ℤ → Γ\n| (a, L, R) 0 := a\n| (a, L, R) (n+1:ℕ) := R.inth n\n| (a, L, R) -[1+ n] := L.inth n\n\n@[simp] theorem tape.nth_zero {Γ} [inhabited Γ] :\n ∀ (T : tape Γ), T.nth 0 = T.1\n| (a, L, R) := rfl\n\n@[simp] theorem tape.move_left_nth {Γ} [inhabited Γ] :\n ∀ (T : tape Γ) (i : ℤ), (T.move dir.left).nth i = T.nth (i-1)\n| (a, L, R) -[1+ n] := by cases L; refl\n| (a, L, R) 0 := by cases L; refl\n| (a, L, R) 1 := rfl\n| (a, L, R) ((n+1:ℕ)+1) := by rw add_sub_cancel; refl\n\n@[simp] theorem tape.move_right_nth {Γ} [inhabited Γ] :\n ∀ (T : tape Γ) (i : ℤ), (T.move dir.right).nth i = T.nth (i+1)\n| (a, L, R) (n+1:ℕ) := by cases R; refl\n| (a, L, R) 0 := by cases R; refl\n| (a, L, R) -1 := rfl\n| (a, L, R) -[1+ n+1] := show _ = tape.nth _ (-[1+ n] - 1 + 1),\n by rw sub_add_cancel; refl\n\ndef tape.write {Γ} (b : Γ) : tape Γ → tape Γ\n| (a, LR) := (b, LR)\n\n@[simp] theorem tape.write_self {Γ} : ∀ (T : tape Γ), T.write T.1 = T\n| (a, LR) := rfl\n\n@[simp] theorem tape.write_nth {Γ} [inhabited Γ] (b : Γ) :\n ∀ (T : tape Γ) {i : ℤ}, (T.write b).nth i = if i = 0 then b else T.nth i\n| (a, L, R) 0 := rfl\n| (a, L, R) (n+1:ℕ) := rfl\n| (a, L, R) -[1+ n] := rfl\n\ndef tape.map {Γ Γ'} (f : Γ → Γ') : tape Γ → tape Γ'\n| (a, L, R) := (f a, L.map f, R.map f)\n\n@[simp] theorem tape.map_fst {Γ Γ'} (f : Γ → Γ') : ∀ (T : tape Γ), (T.map f).1 = f T.1\n| (a, L, R) := rfl\n\n@[simp] theorem tape.map_write {Γ Γ'} (f : Γ → Γ') (b : Γ) :\n ∀ (T : tape Γ), (T.write b).map f = (T.map f).write (f b)\n| (a, L, R) := rfl\n\n@[class] def pointed_map {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : Γ → Γ') :=\nf (default _) = default _\n\ntheorem tape.map_move {Γ Γ'} [inhabited Γ] [inhabited Γ']\n (f : Γ → Γ') [pointed_map f] :\n ∀ (T : tape Γ) d, (T.move d).map f = (T.map f).move d\n| (a, [], R) dir.left := by simpa!\n| (a, b::L, R) dir.left := by simp!\n| (a, L, []) dir.right := by simpa!\n| (a, L, b::R) dir.right := by simp!\n\ntheorem tape.map_mk {Γ Γ'} [inhabited Γ] [inhabited Γ']\n (f : Γ → Γ') [f0 : pointed_map f] :\n ∀ (l : list Γ), (tape.mk l).map f = tape.mk (l.map f)\n| [] := by simpa! [tape.mk]\n| (a::l) := rfl\n\ndef eval {σ} (f : σ → option σ) : σ → roption σ :=\npfun.fix (λ s, roption.some $\n match f s with none := sum.inl s | some s' := sum.inr s' end)\n\ndef reaches {σ} (f : σ → option σ) : σ → σ → Prop :=\nrefl_trans_gen (λ a b, b ∈ f a)\n\ndef reaches₁ {σ} (f : σ → option σ) : σ → σ → Prop :=\ntrans_gen (λ a b, b ∈ f a)\n\ntheorem reaches₁_eq {σ} {f : σ → option σ} {a b c}\n (h : f a = f b) : reaches₁ f a c ↔ reaches₁ f b c :=\ntrans_gen.head'_iff.trans (trans_gen.head'_iff.trans $ by rw h).symm\n\ntheorem reaches_total {σ} {f : σ → option σ}\n {a b c} : reaches f a b → reaches f a c →\n reaches f b c ∨ reaches f c b :=\nrefl_trans_gen.total_of_right_unique $ λ _ _ _, option.mem_unique\n\ntheorem reaches₁_fwd {σ} {f : σ → option σ}\n {a b c} (h₁ : reaches₁ f a c) (h₂ : b ∈ f a) : reaches f b c :=\nbegin\n rcases trans_gen.head'_iff.1 h₁ with ⟨b', hab, hbc⟩,\n cases option.mem_unique hab h₂, exact hbc\nend\n\ndef reaches₀ {σ} (f : σ → option σ) (a b : σ) : Prop :=\n∀ c, reaches₁ f b c → reaches₁ f a c\n\ntheorem reaches₀.trans {σ} {f : σ → option σ} {a b c : σ}\n (h₁ : reaches₀ f a b) (h₂ : reaches₀ f b c) : reaches₀ f a c\n| d h₃ := h₁ _ (h₂ _ h₃)\n\n@[refl] theorem reaches₀.refl {σ} {f : σ → option σ} (a : σ) : reaches₀ f a a\n| b h := h\n\ntheorem reaches₀.single {σ} {f : σ → option σ} {a b : σ}\n (h : b ∈ f a) : reaches₀ f a b\n| c h₂ := h₂.head h\n\ntheorem reaches₀.head {σ} {f : σ → option σ} {a b c : σ}\n (h : b ∈ f a) (h₂ : reaches₀ f b c) : reaches₀ f a c :=\n(reaches₀.single h).trans h₂\n\ntheorem reaches₀.tail {σ} {f : σ → option σ} {a b c : σ}\n (h₁ : reaches₀ f a b) (h : c ∈ f b) : reaches₀ f a c :=\nh₁.trans (reaches₀.single h)\n\ntheorem reaches₀_eq {σ} {f : σ → option σ} {a b}\n (e : f a = f b) : reaches₀ f a b\n| d h := (reaches₁_eq e).2 h\n\ntheorem reaches₁.to₀ {σ} {f : σ → option σ} {a b : σ}\n (h : reaches₁ f a b) : reaches₀ f a b\n| c h₂ := h.trans h₂\n\ntheorem reaches.to₀ {σ} {f : σ → option σ} {a b : σ}\n (h : reaches f a b) : reaches₀ f a b\n| c h₂ := h₂.trans_right h\n\ntheorem reaches₀.tail' {σ} {f : σ → option σ} {a b c : σ}\n (h : reaches₀ f a b) (h₂ : c ∈ f b) : reaches₁ f a c :=\nh _ (trans_gen.single h₂)\n\ntheorem mem_eval {σ} {f : σ → option σ} {a b} :\n b ∈ eval f a ↔ reaches f a b ∧ f b = none :=\n⟨λ h, begin\n refine pfun.fix_induction h (λ a h IH, _),\n cases e : f a with a',\n { rw roption.mem_unique h (pfun.mem_fix_iff.2 $ or.inl $\n roption.mem_some_iff.2 $ by rw e; refl),\n exact ⟨refl_trans_gen.refl, e⟩ },\n { rcases pfun.mem_fix_iff.1 h with h | ⟨_, h, h'⟩;\n rw e at h; cases roption.mem_some_iff.1 h,\n cases IH a' h' (by rwa e) with h₁ h₂,\n exact ⟨refl_trans_gen.head e h₁, h₂⟩ }\nend, λ ⟨h₁, h₂⟩, begin\n refine refl_trans_gen.head_induction_on h₁ _ (λ a a' h _ IH, _),\n { refine pfun.mem_fix_iff.2 (or.inl _),\n rw h₂, apply roption.mem_some },\n { refine pfun.mem_fix_iff.2 (or.inr ⟨_, _, IH⟩),\n rw show f a = _, from h,\n apply roption.mem_some }\nend⟩\n\ntheorem eval_maximal₁ {σ} {f : σ → option σ} {a b}\n (h : b ∈ eval f a) (c) : ¬ reaches₁ f b c | bc :=\nlet ⟨ab, b0⟩ := mem_eval.1 h, ⟨b', h', _⟩ := trans_gen.head'_iff.1 bc in\nby cases b0.symm.trans h'\n\ntheorem eval_maximal {σ} {f : σ → option σ} {a b}\n (h : b ∈ eval f a) {c} : reaches f b c ↔ c = b :=\nlet ⟨ab, b0⟩ := mem_eval.1 h in\nrefl_trans_gen_iff_eq $ λ b' h', by cases b0.symm.trans h'\n\ntheorem reaches_eval {σ} {f : σ → option σ} {a b}\n (ab : reaches f a b) : eval f a = eval f b :=\nroption.ext $ λ c,\n ⟨λ h, let ⟨ac, c0⟩ := mem_eval.1 h in\n mem_eval.2 ⟨(or_iff_left_of_imp $ by exact\n λ cb, (eval_maximal h).1 cb ▸ refl_trans_gen.refl).1\n (reaches_total ab ac), c0⟩,\n λ h, let ⟨bc, c0⟩ := mem_eval.1 h in mem_eval.2 ⟨ab.trans bc, c0⟩,⟩\n\ndef respects {σ₁ σ₂}\n (f₁ : σ₁ → option σ₁) (f₂ : σ₂ → option σ₂) (tr : σ₁ → σ₂ → Prop) :=\n∀ ⦃a₁ a₂⦄, tr a₁ a₂ → (match f₁ a₁ with\n | some b₁ := ∃ b₂, tr b₁ b₂ ∧ reaches₁ f₂ a₂ b₂\n | none := f₂ a₂ = none\n end : Prop)\n\ntheorem tr_reaches₁ {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop}\n (H : respects f₁ f₂ tr) {a₁ a₂} (aa : tr a₁ a₂) {b₁} (ab : reaches₁ f₁ a₁ b₁) :\n ∃ b₂, tr b₁ b₂ ∧ reaches₁ f₂ a₂ b₂ :=\nbegin\n induction ab with c₁ ac c₁ d₁ ac cd IH,\n { have := H aa,\n rwa (show f₁ a₁ = _, from ac) at this },\n { rcases IH with ⟨c₂, cc, ac₂⟩,\n have := H cc,\n rw (show f₁ c₁ = _, from cd) at this,\n rcases this with ⟨d₂, dd, cd₂⟩,\n exact ⟨_, dd, ac₂.trans cd₂⟩ }\nend\n\ntheorem tr_reaches {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop}\n (H : respects f₁ f₂ tr) {a₁ a₂} (aa : tr a₁ a₂) {b₁} (ab : reaches f₁ a₁ b₁) :\n ∃ b₂, tr b₁ b₂ ∧ reaches f₂ a₂ b₂ :=\nbegin\n rcases refl_trans_gen_iff_eq_or_trans_gen.1 ab with rfl | ab,\n { exact ⟨_, aa, refl_trans_gen.refl⟩ },\n { exact let ⟨b₂, bb, h⟩ := tr_reaches₁ H aa ab in\n ⟨b₂, bb, h.to_refl⟩ }\nend\n\ntheorem tr_reaches_rev {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop}\n (H : respects f₁ f₂ tr) {a₁ a₂} (aa : tr a₁ a₂) {b₂} (ab : reaches f₂ a₂ b₂) :\n ∃ c₁ c₂, reaches f₂ b₂ c₂ ∧ tr c₁ c₂ ∧ reaches f₁ a₁ c₁ :=\nbegin\n induction ab with c₂ d₂ ac cd IH,\n { exact ⟨_, _, refl_trans_gen.refl, aa, refl_trans_gen.refl⟩ },\n { rcases IH with ⟨e₁, e₂, ce, ee, ae⟩,\n rcases refl_trans_gen.cases_head ce with rfl | ⟨d', cd', de⟩,\n { have := H ee, revert this,\n cases eg : f₁ e₁ with g₁; simp [respects],\n { intro c0, cases cd.symm.trans c0 },\n { intros g₂ gg cg,\n rcases trans_gen.head'_iff.1 cg with ⟨d', cd', dg⟩,\n cases option.mem_unique cd cd',\n exact ⟨_, _, dg, gg, ae.tail eg⟩ } },\n { cases option.mem_unique cd cd',\n exact ⟨_, _, de, ee, ae⟩ } }\nend\n\ntheorem tr_eval {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop}\n (H : respects f₁ f₂ tr) {a₁ b₁ a₂} (aa : tr a₁ a₂)\n (ab : b₁ ∈ eval f₁ a₁) : ∃ b₂, tr b₁ b₂ ∧ b₂ ∈ eval f₂ a₂ :=\nbegin\n cases mem_eval.1 ab with ab b0,\n rcases tr_reaches H aa ab with ⟨b₂, bb, ab⟩,\n refine ⟨_, bb, mem_eval.2 ⟨ab, _⟩⟩,\n have := H bb, rwa b0 at this\nend\n\ntheorem tr_eval_rev {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop}\n (H : respects f₁ f₂ tr) {a₁ b₂ a₂} (aa : tr a₁ a₂)\n (ab : b₂ ∈ eval f₂ a₂) : ∃ b₁, tr b₁ b₂ ∧ b₁ ∈ eval f₁ a₁ :=\nbegin\n cases mem_eval.1 ab with ab b0,\n rcases tr_reaches_rev H aa ab with ⟨c₁, c₂, bc, cc, ac⟩,\n cases (refl_trans_gen_iff_eq\n (by exact option.eq_none_iff_forall_not_mem.1 b0)).1 bc,\n refine ⟨_, cc, mem_eval.2 ⟨ac, _⟩⟩,\n have := H cc, cases f₁ c₁ with d₁, {refl},\n rcases this with ⟨d₂, dd, bd⟩,\n rcases trans_gen.head'_iff.1 bd with ⟨e, h, _⟩,\n cases b0.symm.trans h\nend\n\ntheorem tr_eval_dom {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop}\n (H : respects f₁ f₂ tr) {a₁ a₂} (aa : tr a₁ a₂) :\n (eval f₂ a₂).dom ↔ (eval f₁ a₁).dom :=\n⟨λ h, let ⟨b₂, tr, h, _⟩ := tr_eval_rev H aa ⟨h, rfl⟩ in h,\n λ h, let ⟨b₂, tr, h, _⟩ := tr_eval H aa ⟨h, rfl⟩ in h⟩\n\ndef frespects {σ₁ σ₂} (f₂ : σ₂ → option σ₂) (tr : σ₁ → σ₂) (a₂ : σ₂) : option σ₁ → Prop\n| (some b₁) := reaches₁ f₂ a₂ (tr b₁)\n| none := f₂ a₂ = none\n\ntheorem frespects_eq {σ₁ σ₂} {f₂ : σ₂ → option σ₂} {tr : σ₁ → σ₂} {a₂ b₂}\n (h : f₂ a₂ = f₂ b₂) : ∀ {b₁}, frespects f₂ tr a₂ b₁ ↔ frespects f₂ tr b₂ b₁\n| (some b₁) := reaches₁_eq h\n| none := by simp [frespects, h]\n\ntheorem fun_respects {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂} :\n respects f₁ f₂ (λ a b, tr a = b) ↔ ∀ ⦃a₁⦄, frespects f₂ tr (tr a₁) (f₁ a₁) :=\nforall_congr $ λ a₁, by cases f₁ a₁; simp [frespects, respects]\n\ntheorem tr_eval' {σ₁ σ₂}\n (f₁ : σ₁ → option σ₁) (f₂ : σ₂ → option σ₂) (tr : σ₁ → σ₂)\n (H : respects f₁ f₂ (λ a b, tr a = b))\n (a₁) : eval f₂ (tr a₁) = tr <$> eval f₁ a₁ :=\nroption.ext $ λ b₂, by simp; exact\n ⟨λ h, let ⟨b₁, bb, hb⟩ :=\n tr_eval_rev H rfl h in ⟨b₁, hb, bb⟩,\n λ ⟨b₁, ab, bb⟩, begin\n rcases tr_eval H rfl ab with ⟨_, rfl, h⟩,\n rwa bb at h\n end⟩\n\ndef dwrite {K} [decidable_eq K] {C : K → Type*}\n (S : ∀ k, C k) (k') (l : C k') (k) : C k :=\nif h : k = k' then eq.rec_on h.symm l else S k\n\n@[simp] theorem dwrite_eq {K} [decidable_eq K] {C : K → Type*}\n (S : ∀ k, C k) (k) (l : C k) : dwrite S k l k = l :=\nby simp [dwrite]\n\n@[simp] theorem dwrite_ne {K} [decidable_eq K] {C : K → Type*}\n (S : ∀ k, C k) (k') (l : C k') (k) (h : ¬ k = k') : dwrite S k' l k = S k :=\nby simp [dwrite, h]\n\n@[simp] theorem dwrite_self\n {K} [decidable_eq K] {C : K → Type*}\n (S : ∀ k, C k) (k) : dwrite S k (S k) = S :=\nfunext $ λ k', by unfold dwrite; split_ifs; [subst h, refl]\n\nnamespace TM0\n\nsection\nparameters (Γ : Type*) [inhabited Γ] -- type of tape symbols\nparameters (Λ : Type*) [inhabited Λ] -- type of \"labels\" or TM states\n\n/-- A Turing machine \"statement\" is just a command to either move\n left or right, or write a symbol on the tape. -/\ninductive stmt\n| move {} : dir → stmt\n| write {} : Γ → stmt\n\n/-- A Post-Turing machine with symbol type `Γ` and label type `Λ`\n is a function which, given the current state `q : Λ` and\n the tape head `a : Γ`, either halts (returns `none`) or returns\n a new state `q' : Λ` and a `stmt` describing what to do,\n either a move left or right, or a write command.\n \n Both `Λ` and `Γ` are required to be inhabited; the default value\n for `Γ` is the \"blank\" tape value, and the default value of `Λ` is\n the initial state. -/\ndef machine := Λ → Γ → option (Λ × stmt)\n\n/-- The configuration state of a Turing machine during operation\n consists of a label (machine state), and a tape, represented in\n the form `(a, L, R)` meaning the tape looks like `L.rev ++ [a] ++ R`\n with the machine currently reading the `a`. The lists are\n automatically extended with blanks as the machine moves around. -/\nstructure cfg :=\n(q : Λ)\n(tape : tape Γ)\n\nparameters {Γ Λ}\n/-- Execution semantics of the Turing machine. -/\ndef step (M : machine) : cfg → option cfg\n| ⟨q, T⟩ := (M q T.1).map (λ ⟨q', a⟩, ⟨q',\n match a with\n | stmt.move d := T.move d\n | stmt.write a := T.write a\n end⟩)\n\n/-- The statement `reaches M s₁ s₂` means that `s₂` is obtained\n starting from `s₁` after a finite number of steps from `s₂`. -/\ndef reaches (M : machine) : cfg → cfg → Prop :=\nrefl_trans_gen (λ a b, b ∈ step M a)\n\n/-- The initial configuration. -/\ndef init (l : list Γ) : cfg :=\n⟨default Λ, tape.mk l⟩\n\n/-- Evaluate a Turing machine on initial input to a final state,\n if it terminates. -/\ndef eval (M : machine) (l : list Γ) : roption (list Γ) :=\n(eval (step M) (init l)).map (λ c, c.tape.2.2)\n\n/-- The raw definition of a Turing machine does not require that\n `Γ` and `Λ` are finite, and in practice we will be interested\n in the infinite `Λ` case. We recover instead a notion of\n \"effectively finite\" Turing machines, which only make use of a\n finite subset of their states. We say that a set `S ⊆ Λ`\n supports a Turing machine `M` if `S` is closed under the\n transition function and contains the initial state. -/\ndef supports (M : machine) (S : set Λ) :=\ndefault Λ ∈ S ∧ ∀ {q a q' s}, (q', s) ∈ M q a → q ∈ S → q' ∈ S\n\ntheorem step_supports (M : machine) {S}\n (ss : supports M S) : ∀ {c c' : cfg},\n c' ∈ step M c → c.q ∈ S → c'.q ∈ S\n| ⟨q, T⟩ c' h₁ h₂ := begin\n rcases option.map_eq_some'.1 h₁ with ⟨⟨q', a⟩, h, rfl⟩,\n exact ss.2 h h₂,\nend\n\ntheorem univ_supports (M : machine) : supports M set.univ :=\n⟨trivial, λ q a q' s h₁ h₂, trivial⟩\n\nend\n\nsection\nvariables {Γ : Type*} [inhabited Γ]\nvariables {Γ' : Type*} [inhabited Γ']\nvariables {Λ : Type*} [inhabited Λ]\nvariables {Λ' : Type*} [inhabited Λ']\n\ndef stmt.map (f : Γ → Γ') : stmt Γ → stmt Γ'\n| (stmt.move d) := stmt.move d\n| (stmt.write a) := stmt.write (f a)\n\ndef cfg.map (f : Γ → Γ') (g : Λ → Λ') : cfg Γ Λ → cfg Γ' Λ'\n| ⟨q, T⟩ := ⟨g q, T.map f⟩\n\nvariables (M : machine Γ Λ)\n (f₁ : Γ → Γ') (f₂ : Γ' → Γ) (g₁ : Λ → Λ') (g₂ : Λ' → Λ)\n\ndef machine.map : machine Γ' Λ'\n| q l := (M (g₂ q) (f₂ l)).map (prod.map g₁ (stmt.map f₁))\n\ntheorem machine.map_step {S} (ss : supports M S)\n [pointed_map f₁] (f₂₁ : function.right_inverse f₁ f₂)\n (g₂₁ : ∀ q ∈ S, g₂ (g₁ q) = q) :\n ∀ c : cfg Γ Λ, c.q ∈ S → \n (step M c).map (cfg.map f₁ g₁) =\n step (M.map f₁ f₂ g₁ g₂) (cfg.map f₁ g₁ c)\n| ⟨q, T⟩ h := begin\n simp! [g₂₁ q h, f₂₁ _],\n rcases M q T.1 with _|⟨q', d|a⟩, {refl},\n { simp! [tape.map_move f₁] },\n { simp! }\nend\n\ntheorem map_init [pointed_map f₁] [g0 : pointed_map g₁] (l : list Γ) :\n (init l).map f₁ g₁ = init (l.map f₁) :=\nby simp [init, cfg.map]; exact ⟨g0, tape.map_mk _ _⟩\n\ntheorem machine.map_respects {S} (ss : supports M S)\n [pointed_map f₁] [pointed_map g₁]\n (f₂₁ : function.right_inverse f₁ f₂)\n (g₂₁ : ∀ q ∈ S, g₂ (g₁ q) = q) :\n respects (step M) (step (M.map f₁ f₂ g₁ g₂))\n (λ a b, a.q ∈ S ∧ cfg.map f₁ g₁ a = b)\n| c _ ⟨cs, rfl⟩ := begin\n cases e : step M c with c'; simp!,\n { rw [← M.map_step f₁ f₂ g₁ g₂ ss f₂₁ g₂₁ _ cs, e], refl },\n { refine ⟨_, ⟨step_supports M ss e cs, rfl⟩, trans_gen.single _⟩,\n rw [← M.map_step f₁ f₂ g₁ g₂ ss f₂₁ g₂₁ _ cs, e], exact rfl }\nend\n\nend\n\nend TM0\n\nnamespace TM1\n\nsection\nparameters (Γ : Type*) [inhabited Γ] -- Type of tape symbols\nparameters (Λ : Type*) -- Type of function labels\nparameters (σ : Type*) -- Type of variable settings\n\n/-- The TM1 model is a simplification and extension of TM0\n (Post-Turing model) in the direction of Wang B-machines. The machine's\n internal state is extended with a (finite) store `σ` of variables\n that may be accessed and updated at any time.\n A machine is given by a `Λ` indexed set of procedures or functions.\n Each function has a body which is a `stmt`, which can either be a\n `move` or `write` command, a `branch` (if statement based on the\n current tape value), a `load` (set the variable value),\n a `goto` (call another function), or `halt`. Note that here\n most statements do not have labels; `goto` commands can only\n go to a new function. All commands have access to the variable value\n and current tape value. -/\ninductive stmt\n| move : dir → stmt → stmt\n| write : (Γ → σ → Γ) → stmt → stmt\n| load : (Γ → σ → σ) → stmt → stmt\n| branch : (Γ → σ → bool) → stmt → stmt → stmt\n| goto {} : (Γ → σ → Λ) → stmt\n| halt {} : stmt\nopen stmt\n\n/-- The configuration of a TM1 machine is given by the currently\n evaluating statement, the variable store value, and the tape. -/\nstructure cfg :=\n(l : option Λ)\n(var : σ)\n(tape : tape Γ)\n\nparameters {Γ Λ σ}\n/-- The semantics of TM1 evaluation. -/\ndef step_aux : stmt → σ → tape Γ → cfg\n| (move d q) v T := step_aux q v (T.move d)\n| (write a q) v T := step_aux q v (T.write (a T.1 v))\n| (load s q) v T := step_aux q (s T.1 v) T\n| (branch p q₁ q₂) v T :=\n cond (p T.1 v) (step_aux q₁ v T) (step_aux q₂ v T)\n| (goto l) v T := ⟨some (l T.1 v), v, T⟩\n| halt v T := ⟨none, v, T⟩\n\ndef step (M : Λ → stmt) : cfg → option cfg\n| ⟨none, v, T⟩ := none\n| ⟨some l, v, T⟩ := some (step_aux (M l) v T)\n\nvariables [inhabited Λ] [inhabited σ]\ndef init (l : list Γ) : cfg :=\n⟨some (default _), default _, tape.mk l⟩\n\ndef eval (M : Λ → stmt) (l : list Γ) : roption (list Γ) :=\n(eval (step M) (init l)).map (λ c, c.tape.2.2)\n\nvariables [fintype Γ]\ndef supports_stmt (S : finset Λ) : stmt → Prop\n| (move d q) := supports_stmt q\n| (write a q) := supports_stmt q\n| (load s q) := supports_stmt q\n| (branch p q₁ q₂) := supports_stmt q₁ ∧ supports_stmt q₂\n| (goto l) := ∀ a v, l a v ∈ S\n| halt := true\n\n/-- A set `S` of labels supports machine `M` if all the `goto`\n statements in the functions in `S` refer only to other functions\n in `S`. -/\ndef supports (M : Λ → stmt) (S : finset Λ) :=\ndefault Λ ∈ S ∧ ∀ q ∈ S, supports_stmt S (M q)\n\nlocal attribute [instance] classical.dec\nnoncomputable def stmts₁ : stmt → finset stmt\n| Q@(move d q) := insert Q (stmts₁ q)\n| Q@(write a q) := insert Q (stmts₁ q)\n| Q@(load s q) := insert Q (stmts₁ q)\n| Q@(branch p q₁ q₂) := insert Q (stmts₁ q₁ ∪ stmts₁ q₂)\n| Q := {Q}\n\ntheorem stmts₁_self {q} : q ∈ stmts₁ q :=\nby cases q; simp [stmts₁]\n\ntheorem stmts₁_trans {q₁ q₂} :\n q₁ ∈ stmts₁ q₂ → stmts₁ q₁ ⊆ stmts₁ q₂ :=\nbegin\n intros h₁₂ q₀ h₀₁,\n induction q₂ with _ q IH _ q IH _ q IH;\n simp [stmts₁, finset.subset_iff] at h₁₂ ⊢,\n iterate 3 {\n rcases h₁₂ with rfl | h₁₂,\n { simp [stmts₁] at h₀₁, rcases h₀₁ with rfl | h; simp * },\n { exact or.inr (IH h₁₂) } },\n case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ {\n rcases h₁₂ with rfl | h₁₂ | h₁₂,\n { simp [stmts₁] at h₀₁, rcases h₀₁ with rfl | h; simp * },\n { simp [IH₁ h₁₂] }, { simp [IH₂ h₁₂] } },\n case TM1.stmt.goto : l {\n subst h₁₂, simpa [stmts₁] using h₀₁ },\n case TM1.stmt.halt {\n subst h₁₂, simpa [stmts₁] using h₀₁ }\nend\n\ntheorem stmts₁_supports_stmt_mono {S q₁ q₂}\n (h : q₁ ∈ stmts₁ q₂) (hs : supports_stmt S q₂) : supports_stmt S q₁ :=\nbegin\n induction q₂ with _ q IH _ q IH _ q IH;\n simp [stmts₁, supports_stmt] at h hs,\n iterate 3 { rcases h with rfl | h; [exact hs, exact IH h hs] },\n case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ {\n rcases h with rfl | h | h, exacts [hs, IH₁ h hs.1, IH₂ h hs.2] },\n case TM1.stmt.goto : l { subst h, exact hs },\n case TM1.stmt.halt { subst h, trivial }\nend\n\nnoncomputable def stmts\n (M : Λ → stmt) (S : finset Λ) : finset (option stmt) :=\n(S.bind (λ q, stmts₁ (M q))).insert_none\n\ntheorem stmts_trans {M : Λ → stmt} {S q₁ q₂}\n (h₁ : q₁ ∈ stmts₁ q₂) : some q₂ ∈ stmts M S → some q₁ ∈ stmts M S :=\nby simp [stmts]; exact λ l ls h₂, ⟨_, ls, stmts₁_trans h₂ h₁⟩\n\ntheorem stmts_supports_stmt {M : Λ → stmt} {S q}\n (ss : supports M S) : some q ∈ stmts M S → supports_stmt S q :=\nby simp [stmts]; exact\nλ l ls h, stmts₁_supports_stmt_mono h (ss.2 _ ls)\n\nlocal attribute [-simp] finset.mem_insert_none\ntheorem step_supports (M : Λ → stmt) {S}\n (ss : supports M S) : ∀ {c c' : cfg},\n c' ∈ step M c → c.l ∈ S.insert_none → c'.l ∈ S.insert_none\n| ⟨some l₁, v, T⟩ c' h₁ h₂ := begin\n replace h₂ := ss.2 _ (finset.some_mem_insert_none.1 h₂),\n simp [step] at h₁, subst c',\n revert h₂, induction M l₁ with _ q IH _ q IH _ q IH generalizing v T;\n intro hs,\n iterate 3 { exact IH _ _ hs },\n case TM1.stmt.branch : p q₁' q₂' IH₁ IH₂ {\n simp [step_aux], cases p T.1 v,\n { exact IH₂ _ _ hs.2 },\n { exact IH₁ _ _ hs.1 } },\n case TM1.stmt.goto { exact finset.some_mem_insert_none.2 (hs _ _) },\n case TM1.stmt.halt { apply multiset.mem_cons_self }\nend\n\nend\n\nend TM1\n\nnamespace TM1to0\n\nsection\nparameters {Γ : Type*} [inhabited Γ]\nparameters {Λ : Type*} [inhabited Λ]\nparameters {σ : Type*} [inhabited σ]\n\nlocal notation `stmt₁` := TM1.stmt Γ Λ σ\nlocal notation `cfg₁` := TM1.cfg Γ Λ σ\nlocal notation `stmt₀` := TM0.stmt Γ\n\nparameters (M : Λ → stmt₁)\ninclude M\n\ndef Λ' := option stmt₁ × σ\ninstance : inhabited Λ' := ⟨(some (M (default _)), default _)⟩\n\nopen TM0.stmt\n\ndef tr_aux (s : Γ) : stmt₁ → σ → Λ' × stmt₀\n| (TM1.stmt.move d q) v := ((some q, v), move d)\n| (TM1.stmt.write a q) v := ((some q, v), write (a s v))\n| (TM1.stmt.load a q) v := tr_aux q (a s v)\n| (TM1.stmt.branch p q₁ q₂) v := cond (p s v) (tr_aux q₁ v) (tr_aux q₂ v)\n| (TM1.stmt.goto l) v := ((some (M (l s v)), v), write s)\n| TM1.stmt.halt v := ((none, v), write s)\n\nlocal notation `cfg₀` := TM0.cfg Γ Λ'\n\ndef tr : TM0.machine Γ Λ'\n| (none, v) s := none\n| (some q, v) s := some (tr_aux s q v)\n\ndef tr_cfg : cfg₁ → cfg₀\n| ⟨l, v, T⟩ := ⟨(l.map M, v), T⟩\n\ntheorem tr_respects : respects (TM1.step M) (TM0.step tr)\n (λ c₁ c₂, tr_cfg c₁ = c₂) :=\nfun_respects.2 $ λ ⟨l₁, v, T⟩, begin\n cases l₁ with l₁, {exact rfl},\n simp!,\n induction M l₁ with _ q IH _ q IH _ q IH generalizing v T,\n case TM1.stmt.move : d q IH { exact trans_gen.head rfl (IH _ _) },\n case TM1.stmt.write : a q IH { exact trans_gen.head rfl (IH _ _) },\n case TM1.stmt.load : a q IH { exact (reaches₁_eq (by refl)).2 (IH _ _) },\n case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ {\n simp [TM1.step_aux], cases e : p T.1 v,\n { exact (reaches₁_eq (by simp! [e])).2 (IH₂ _ _) },\n { exact (reaches₁_eq (by simp! [e])).2 (IH₁ _ _) } },\n case TM1.stmt.goto : l { apply trans_gen.single, simp! },\n case TM1.stmt.halt { apply trans_gen.single, simp! }\nend\n\nvariables [fintype Γ] [fintype σ]\nnoncomputable def tr_stmts (S : finset Λ) : finset Λ' :=\n(TM1.stmts M S).product finset.univ\n\nlocal attribute [instance] classical.dec\nlocal attribute [simp] TM1.stmts₁_self\ntheorem tr_supports {S : finset Λ} (ss : TM1.supports M S) :\n TM0.supports tr (↑(tr_stmts S)) :=\n⟨by simp [tr_stmts]; exact finset.some_mem_insert_none.2\n (finset.mem_bind.2 ⟨_, ss.1, TM1.stmts₁_self⟩),\n λ q a q' s h₁ h₂, begin\n rcases q with ⟨_|q, v⟩, {cases h₁},\n cases q' with q' v', simp [tr_stmts] at h₂ ⊢,\n cases q', {simp [TM1.stmts]},\n simp [tr] at h₁,\n have := TM1.stmts_supports_stmt ss h₂,\n revert this, induction q generalizing v; intro hs,\n case TM1.stmt.move : d q {\n cases h₁, refine TM1.stmts_trans _ h₂, simp [TM1.stmts₁] },\n case TM1.stmt.write : b q {\n cases h₁, refine TM1.stmts_trans _ h₂, simp [TM1.stmts₁] },\n case TM1.stmt.load : b q IH {\n refine IH (TM1.stmts_trans _ h₂) _ h₁ hs, simp [TM1.stmts₁] },\n case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ {\n simp! at h₁, cases p a v,\n { refine IH₂ (TM1.stmts_trans _ h₂) _ h₁ hs.2, simp [TM1.stmts₁] },\n { refine IH₁ (TM1.stmts_trans _ h₂) _ h₁ hs.1, simp [TM1.stmts₁] } },\n case TM1.stmt.goto : l {\n cases h₁, exact finset.some_mem_insert_none.2\n (finset.mem_bind.2 ⟨_, hs _ _, TM1.stmts₁_self⟩) },\n case TM1.stmt.halt { cases h₁ }\nend⟩\n\ntheorem tr_eval (l : list Γ) : TM0.eval tr l = TM1.eval M l :=\n(congr_arg _ (tr_eval' _ _ _ tr_respects ⟨some _, _, _⟩)).trans begin\n simp [tr_cfg],\n rw [roption.map_map, TM1.eval],\n congr', exact funext (λ ⟨_, _, _⟩, rfl)\nend\n\nend\nend TM1to0\n\n/- Reduce an n-symbol Turing machine to a 2-symbol Turing machine -/\nnamespace TM1to1\nopen TM1\n\nsection\nparameters {Γ : Type*} [inhabited Γ]\n\ntheorem exists_enc_dec [fintype Γ] :\n ∃ n (enc : Γ → vector bool n) (dec : vector bool n → Γ),\n enc (default _) = vector.repeat ff n ∧ ∀ a, dec (enc a) = a :=\nbegin\n rcases fintype.exists_equiv_fin Γ with ⟨n, ⟨F⟩⟩,\n let G : fin n ↪ fin n → bool := ⟨λ a b, a = b,\n λ a b h, by simpa using congr_fun h b⟩,\n let H := (F.to_embedding.trans G).trans\n (equiv.vector_equiv_fin _ _).symm.to_embedding,\n let enc := H.set_value (default _) (vector.repeat ff n),\n exact ⟨_, enc, function.inv_fun enc,\n H.set_value_eq _ _, function.left_inverse_inv_fun enc.2⟩\nend\n\nparameters {Λ : Type*} [inhabited Λ]\nparameters {σ : Type*} [inhabited σ]\n\nlocal notation `stmt₁` := stmt Γ Λ σ\nlocal notation `cfg₁` := cfg Γ Λ σ\n\ninductive Λ' : Type (max u_1 u_2 u_3)\n| normal : Λ → Λ'\n| write : Γ → stmt₁ → Λ'\ninstance : inhabited Λ' := ⟨Λ'.normal (default _)⟩\n\nlocal notation `stmt'` := stmt bool Λ' σ\nlocal notation `cfg'` := cfg bool Λ' σ\n\ndef read_aux : ∀ n, (vector bool n → stmt') → stmt'\n| 0 f := f vector.nil\n| (i+1) f := stmt.branch (λ a s, a)\n (stmt.move dir.right $ read_aux i (λ v, f (tt :: v)))\n (stmt.move dir.right $ read_aux i (λ v, f (ff :: v)))\n\nparameters {n : ℕ} (enc : Γ → vector bool n) (dec : vector bool n → Γ)\n\ndef move (d : dir) (q : stmt') : stmt' := (stmt.move d)^[n] q\n\ndef read (f : Γ → stmt') : stmt' :=\nread_aux n (λ v, move dir.left $ f (dec v))\n\ndef write : list bool → stmt' → stmt'\n| [] q := q\n| (a :: l) q := stmt.write (λ _ _, a) $ stmt.move dir.right $ write l q\n\ndef tr_normal : stmt₁ → stmt'\n| (stmt.move dir.left q) := move dir.right $ (move dir.left)^[2] $ tr_normal q\n| (stmt.move dir.right q) := move dir.right $ tr_normal q\n| (stmt.write f q) := read $ λ a, stmt.goto $ λ _ s, Λ'.write (f a s) q\n| (stmt.load f q) := read $ λ a, stmt.load (λ _ s, f a s) $ tr_normal q\n| (stmt.branch p q₁ q₂) := read $ λ a,\n stmt.branch (λ _ s, p a s) (tr_normal q₁) (tr_normal q₂)\n| (stmt.goto l) := read $ λ a,\n stmt.goto (λ _ s, Λ'.normal (l a s))\n| stmt.halt := move dir.right $ move dir.left $ stmt.halt\n\ndef tr_tape' (L R : list Γ) : tape bool :=\ntape.mk'\n (L.bind (λ x, (enc x).to_list.reverse))\n (R.bind (λ x, (enc x).to_list) ++ [default _])\n\ndef tr_tape : tape Γ → tape bool\n| (a, L, R) := tr_tape' L (a :: R)\n\ntheorem tr_tape_drop_right : ∀ R : list Γ,\n list.drop n (R.bind (λ x, (enc x).to_list)) =\n R.tail.bind (λ x, (enc x).to_list)\n| [] := list.drop_nil _\n| (a::R) := by simp; exact list.drop_left' (enc a).2\n\nparameters (enc0 : enc (default _) = vector.repeat ff n)\n\nsection\ninclude enc0\ntheorem tr_tape_take_right : ∀ R : list Γ,\n list.take' n (R.bind (λ x, (enc x).to_list)) =\n (enc R.head).to_list\n| [] := by simp; exact (congr_arg vector.to_list enc0).symm\n| (a::R) := by simp; exact list.take'_left' (enc a).2\nend\n\nparameters (M : Λ → stmt₁)\n\ndef tr : Λ' → stmt'\n| (Λ'.normal l) := tr_normal (M l)\n| (Λ'.write a q) := write (enc a).to_list $ move dir.left $ tr_normal q\n\ndef tr_cfg : cfg₁ → cfg'\n| ⟨l, v, T⟩ := ⟨l.map Λ'.normal, v, tr_tape T⟩\n\ninclude enc0\n\ntheorem tr_tape'_move_left (L R) :\n (tape.move dir.left)^[n] (tr_tape' L R) =\n (tr_tape' L.tail (L.head :: R)) :=\nbegin\n cases L with a L,\n { simp [enc0, vector.repeat, tr_tape'],\n suffices : ∀ i R', default _ ∈ R' →\n (tape.move dir.left^[i]) (tape.mk' [] R') =\n tape.mk' [] (list.repeat ff i ++ R'),\n from this n _ (by simp),\n intros i R' hR, induction i with i IH, {refl},\n rw [nat.iterate_succ', IH],\n simp [tape.mk', tape.move],\n exact list.cons_head_tail\n (list.ne_nil_of_mem $ list.mem_append_right _ hR) },\n { simp [tr_tape'],\n suffices : ∀ L' R' l₁ l₂\n (hR : default _ ∈ R')\n (e : vector.to_list (enc a) = list.reverse_core l₁ l₂),\n (tape.move dir.left^[l₁.length]) (tape.mk' (l₁ ++ L') (l₂ ++ R')) =\n tape.mk' L' (vector.to_list (enc a) ++ R'),\n { simpa using this _ _ _ _ _ (list.reverse_reverse _).symm,\n simp },\n intros, induction l₁ with b l₁ IH generalizing l₂,\n { cases e, refl },\n simp [nat.iterate_succ, -add_comm],\n convert IH _ e,\n simp [tape.move, tape.mk'],\n exact list.cons_head_tail\n (list.ne_nil_of_mem $ list.mem_append_right _ hR) }\nend\n\ntheorem tr_tape'_move_right (L R) :\n (tape.move dir.right)^[n] (tr_tape' L R) =\n (tr_tape' (R.head :: L) R.tail) :=\nbegin\n cases R with a R,\n { simp [enc0, vector.repeat, tr_tape'],\n suffices : ∀ i L',\n (tape.move dir.right^[i]) (ff, L', []) =\n (ff, list.repeat ff i ++ L', []),\n from this n _,\n intros, induction i;\n simp [nat.iterate_succ', tape.move, *]; refl },\n { simp [tr_tape'],\n suffices : ∀ L' R' l₁ l₂ : list bool,\n (tape.move dir.right^[l₂.length]) (tape.mk' (l₁ ++ L') (l₂ ++ R')) =\n tape.mk' (list.reverse_core l₂ l₁ ++ L') R',\n { simpa using this _ _ [] (enc a).to_list },\n intros, induction l₂ with b l₂ IH generalizing l₁, {refl},\n simp [-add_comm, nat.iterate_succ],\n exact IH (b::l₁) }\nend\n\ntheorem step_aux_move (d q v T) :\n step_aux (move d q) v T =\n step_aux q v ((tape.move d)^[n] T) :=\nbegin\n simp [move],\n suffices : ∀ i,\n step_aux (stmt.move d^[i] q) v T =\n step_aux q v (tape.move d^[i] T), from this n,\n intro, induction i with i IH generalizing T, {refl},\n rw [nat.iterate_succ', step_aux, IH, ← nat.iterate_succ]\nend\n\nparameters (encdec : ∀ a, dec (enc a) = a)\ninclude encdec\n\ntheorem step_aux_read (f v L R) :\n step_aux (read f) v (tr_tape' L R) =\n step_aux (f R.head) v (tr_tape' L (R.head :: R.tail)) :=\nbegin\n suffices : ∀ f,\n step_aux (read_aux n f) v (tr_tape' enc L R) =\n step_aux (f (enc R.head)) v\n (tr_tape' enc (R.head :: L) R.tail),\n { rw [read, this, step_aux_move enc enc0, encdec,\n tr_tape'_move_left enc enc0], refl },\n cases R with a R,\n { suffices : ∀ i f L',\n step_aux (read_aux i f) v (ff, L', []) =\n step_aux (f (vector.repeat ff i)) v\n (ff, list.repeat ff i ++ L', []),\n { intro f, convert this n f _,\n simp [tr_tape', tape.mk', enc0, vector.repeat] },\n clear f L, intros, induction i with i IH generalizing L', {refl},\n simp [read_aux, step_aux, tape.mk', tape.move],\n rw [IH], congr',\n simpa using congr_arg (++ L') (list.repeat_add ff i 1).symm },\n { simp [tr_tape'],\n suffices : ∀ i f L' R' l₁ l₂ h,\n step_aux (read_aux i f) v\n (tape.mk' (l₁ ++ L') (l₂ ++ R')) =\n step_aux (f ⟨l₂, h⟩) v\n (tape.mk' (l₂.reverse_core l₁ ++ L') R'),\n { intro f, convert this n f _ _ _ _ (enc a).2; simp },\n clear f L a R, intros, subst i,\n induction l₂ with a l₂ IH generalizing l₁, {refl},\n dsimp [read_aux, step_aux],\n change (tape.mk' (l₁ ++ L') (a :: (l₂ ++ R'))).1 with a,\n transitivity step_aux\n (read_aux l₂.length (λ v, f (a :: v))) v\n (tape.mk' (a :: l₁ ++ L') (l₂ ++ R')),\n { cases a; refl },\n rw IH, refl }\nend\n\ntheorem step_aux_write (q v a b L R) :\n step_aux (write (enc a).to_list q) v (tr_tape' L (b :: R)) =\n step_aux q v (tr_tape' (a :: L) R) :=\nbegin\n simp [tr_tape'],\n suffices : ∀ {L' R'} (l₁ l₂ l₂' : list bool)\n (e : l₂'.length = l₂.length),\n step_aux (write l₂ q) v (tape.mk' (l₁ ++ L') (l₂' ++ R')) =\n step_aux q v (tape.mk' (list.reverse_core l₂ l₁ ++ L') R'),\n from this [] _ _ ((enc b).2.trans (enc a).2.symm),\n clear a b L R, intros,\n induction l₂ with a l₂ IH generalizing l₁ l₂',\n { cases list.length_eq_zero.1 e, refl },\n cases l₂' with b l₂'; injection e with e,\n simp [write, step_aux],\n convert IH _ _ e, refl\nend\n\ntheorem tr_respects : respects (step M) (step tr)\n (λ c₁ c₂, tr_cfg c₁ = c₂) :=\nfun_respects.2 $ λ ⟨l₁, v, (a, L, R)⟩, begin\n cases l₁ with l₁, {exact rfl},\n suffices : ∀ q R, reaches (step (tr enc dec M))\n (step_aux (tr_normal dec q) v (tr_tape' enc L R))\n (tr_cfg enc (step_aux q v (tape.mk' L R))),\n { refine trans_gen.head' rfl (this _ (a::R)) },\n clear R l₁, intros,\n induction q with _ q IH _ q IH _ q IH generalizing v L R,\n case TM1.stmt.move : d q IH {\n cases d; simp [tr_normal, step_aux_move enc enc0, step_aux,\n tr_tape'_move_left enc enc0, tr_tape'_move_right enc enc0];\n apply IH },\n case TM1.stmt.write : a q IH {\n simp [tr_normal, step_aux_read enc dec enc0 encdec, step_aux],\n refine refl_trans_gen.head rfl _,\n simp [tr, tr_normal, step_aux,\n step_aux_write enc dec enc0 encdec,\n step_aux_move enc enc0, tr_tape'_move_left enc enc0],\n apply IH },\n case TM1.stmt.load : a q IH {\n simp [tr_normal, step_aux_read enc dec enc0 encdec],\n apply IH },\n case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ {\n simp [tr_normal, step_aux_read enc dec enc0 encdec, step_aux],\n change (tape.mk' L R).1 with R.head,\n cases p R.head v; [apply IH₂, apply IH₁] },\n case TM1.stmt.goto : l {\n simp [tr_normal, step_aux_read enc dec enc0 encdec, step_aux], \n apply refl_trans_gen.refl },\n case TM1.stmt.halt {\n simp [tr_normal, step_aux, tr_cfg, step_aux_move enc enc0,\n tr_tape'_move_left enc enc0, tr_tape'_move_right enc enc0],\n apply refl_trans_gen.refl }\nend\n\nomit enc0 encdec\nlocal attribute [instance] classical.dec\nparameters [fintype Γ]\nnoncomputable def writes : stmt₁ → finset Λ'\n| (stmt.move d q) := writes q\n| (stmt.write f q) := finset.univ.image (λ a, Λ'.write a q) ∪ writes q\n| (stmt.load f q) := writes q\n| (stmt.branch p q₁ q₂) := writes q₁ ∪ writes q₂\n| (stmt.goto l) := ∅\n| stmt.halt := ∅\n\nnoncomputable def tr_supp (S : finset Λ) : finset Λ' :=\nS.bind (λ l, insert (Λ'.normal l) (writes (M l)))\n\ntheorem supports_stmt_move {S d q} :\n supports_stmt S (move d q) = supports_stmt S q :=\nsuffices ∀ {i}, supports_stmt S (stmt.move d^[i] q) = _, from this,\nby intro; induction i generalizing q; simp [*, supports_stmt]\n\ntheorem supports_stmt_write {S l q} :\n supports_stmt S (write l q) = supports_stmt S q :=\nby induction l with a l IH; simp [write, supports_stmt, *]\n\nlocal attribute [simp] supports_stmt_move supports_stmt_write\n\ntheorem supports_stmt_read {S} : ∀ {f : Γ → stmt'},\n (∀ a, supports_stmt S (f a)) → supports_stmt S (read f) :=\nsuffices ∀ i (f : vector bool i → stmt'),\n (∀ v, supports_stmt S (f v)) → supports_stmt S (read_aux i f),\nfrom λ f hf, this n _ (by simp [hf]),\nλ i f hf, begin\n induction i with i IH, {exact hf _},\n split; simp [supports_stmt]; apply IH; simp [hf],\nend\n\ntheorem tr_supports {S} (ss : supports M S) :\n supports tr (tr_supp S) :=\n⟨by simp [tr_supp]; exact ⟨_, ss.1, or.inl rfl⟩, λ q h, begin\n simp [tr_supp] at h,\n suffices : ∀ q, supports_stmt S q →\n (∀ q' ∈ writes q, q' ∈ tr_supp M S) →\n supports_stmt (tr_supp M S) (tr_normal dec q) ∧\n ∀ q' ∈ writes q, supports_stmt (tr_supp M S) (tr enc dec M q'),\n { rcases h with ⟨l, hl, h⟩,\n have := this _ (ss.2 _ hl) (λ q' hq,\n by simp [tr_supp]; exact ⟨_, hl, or.inr hq⟩),\n rcases h with rfl | h,\n exacts [this.1, this.2 _ h] },\n intros q hs hw, induction q,\n case TM1.stmt.move : d q IH {\n dsimp [writes] at hw ⊢,\n replace IH := IH hs hw, refine ⟨_, IH.2⟩,\n cases d; simp [tr_normal, IH] },\n case TM1.stmt.write : f q IH {\n simp [writes] at hw ⊢,\n replace IH := IH hs (λ q hq, hw q (or.inl hq)),\n refine ⟨supports_stmt_read _ $ λ a _ s,\n hw _ (or.inr ⟨_, rfl⟩), λ q' hq, _⟩,\n rcases hq with hq | ⟨a, q₂, rfl⟩,\n { exact IH.2 _ hq }, { simp [tr, IH.1] } },\n case TM1.stmt.load : a q IH {\n dsimp [writes] at hw ⊢,\n replace IH := IH hs hw,\n refine ⟨supports_stmt_read _ (λ a, _), IH.2⟩,\n simp [tr_normal, supports_stmt, IH.1] },\n case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ {\n simp [writes] at hw ⊢,\n replace IH₁ := IH₁ hs.1 (λ q hq, hw q (or.inl hq)),\n replace IH₂ := IH₂ hs.2 (λ q hq, hw q (or.inr hq)),\n exact ⟨supports_stmt_read _ (λ a, ⟨IH₁.1, IH₂.1⟩),\n λ q, or.rec (IH₁.2 _) (IH₂.2 _)⟩ },\n case TM1.stmt.goto : l {\n simp [writes],\n refine supports_stmt_read _ (λ a _ s, _),\n simp [tr_supp], exact ⟨_, hs _ _, or.inl rfl⟩ },\n case TM1.stmt.halt {\n simp [supports_stmt, writes, tr_normal] }\nend⟩\n\nend\n\nend TM1to1\n\nnamespace TM0to1\n\nsection\nparameters {Γ : Type*} [inhabited Γ]\nparameters {Λ : Type*} [inhabited Λ]\n\ninductive Λ'\n| normal : Λ → Λ'\n| act : TM0.stmt Γ → Λ → Λ'\ninstance : inhabited Λ' := ⟨Λ'.normal (default _)⟩\n\nlocal notation `cfg₀` := TM0.cfg Γ Λ\nlocal notation `stmt₁` := TM1.stmt Γ Λ' unit\nlocal notation `cfg₁` := TM1.cfg Γ Λ' unit\n\nparameters (M : TM0.machine Γ Λ)\n\nopen TM1.stmt\n\ndef tr : Λ' → stmt₁\n| (Λ'.normal q) :=\n branch (λ a _, (M q a).is_none) halt $\n goto (λ a _, match M q a with\n | none := default _\n | some (q', s) := Λ'.act s q'\n end)\n| (Λ'.act (TM0.stmt.move d) q) :=\n move d $ goto (λ _ _, Λ'.normal q)\n| (Λ'.act (TM0.stmt.write a) q) :=\n write (λ _ _, a) $ goto (λ _ _, Λ'.normal q)\n\ndef tr_cfg : cfg₀ → cfg₁\n| ⟨q, T⟩ := ⟨cond (M q T.1).is_some\n (some (Λ'.normal q)) none, (), T⟩\n\ntheorem tr_respects : respects (TM0.step M) (TM1.step tr)\n (λ a b, tr_cfg a = b) :=\nfun_respects.2 $ λ ⟨q, T⟩, begin\n simp [TM0.step],\n cases e : M q T.1,\n { simp [frespects, TM1.step, tr_cfg, e] },\n cases val with q' s,\n simp [frespects, TM0.step, tr_cfg, e],\n have : TM1.step (tr M) ⟨some (Λ'.act s q'), (), T⟩ =\n some ⟨some (Λ'.normal q'), (), TM0.step._match_1 T s⟩,\n { cases s with d a; refl },\n refine trans_gen.head _ (trans_gen.head' this _);\n simp [TM1.step, TM1.step_aux, tr, e, TM0.step],\n cases e' : M q' (TM0.step._match_1 T s).1,\n { apply refl_trans_gen.single,\n simp [TM1.step, e', tr, TM1.step_aux] },\n { refl }\nend\n\nend\n\nend TM0to1\n\nnamespace TM2\n\nsection\nparameters {K : Type*} [decidable_eq K] -- Index type of stacks\nparameters (Γ : K → Type*) -- Type of stack elements\nparameters (Λ : Type*) -- Type of function labels\nparameters (σ : Type*) -- Type of variable settings\n\n/-- The TM2 model removes the tape entirely from the TM1 model,\n replacing it with an arbitrary (finite) collection of stacks.\n The operation `push` puts an element on one of the stacks,\n and `pop` removes an element from a stack (and modifying the\n internal state based on the result). `peek` modifies the\n internal state but does not remove an element. -/\ninductive stmt\n| push {} : ∀ k, (σ → Γ k) → stmt → stmt\n| peek {} : ∀ k, (σ → option (Γ k) → σ) → stmt → stmt\n| pop {} : ∀ k, (σ → option (Γ k) → σ) → stmt → stmt\n| load : (σ → σ) → stmt → stmt\n| branch : (σ → bool) → stmt → stmt → stmt\n| goto {} : (σ → Λ) → stmt\n| halt {} : stmt\nopen stmt\n\nstructure cfg :=\n(l : option Λ)\n(var : σ)\n(stk : ∀ k, list (Γ k))\n\nparameters {Γ Λ σ K}\ndef step_aux : stmt → σ → (∀ k, list (Γ k)) → cfg\n| (push k f q) v S := step_aux q v (dwrite S k (f v :: S k))\n| (peek k f q) v S := step_aux q (f v (S k).head') S\n| (pop k f q) v S := step_aux q (f v (S k).head') (dwrite S k (S k).tail)\n| (load a q) v S := step_aux q (a v) S\n| (branch f q₁ q₂) v S :=\n cond (f v) (step_aux q₁ v S) (step_aux q₂ v S)\n| (goto f) v S := ⟨some (f v), v, S⟩\n| halt v S := ⟨none, v, S⟩\n\ndef step (M : Λ → stmt) : cfg → option cfg\n| ⟨none, v, S⟩ := none\n| ⟨some l, v, S⟩ := some (step_aux (M l) v S)\n\ndef reaches (M : Λ → stmt) : cfg → cfg → Prop :=\nrefl_trans_gen (λ a b, b ∈ step M a)\n\nvariables [inhabited Λ] [inhabited σ]\ndef init (k) (L : list (Γ k)) : cfg :=\n⟨some (default _), default _, dwrite (λ _, []) k L⟩\n\ndef eval (M : Λ → stmt) (k) (L : list (Γ k)) : roption (list (Γ k)) :=\n(eval (step M) (init k L)).map $ λ c, c.stk k\n\nvariables [fintype K] [∀ k, fintype (Γ k)] [fintype σ]\ndef supports_stmt (S : finset Λ) : stmt → Prop\n| (push k f q) := supports_stmt q\n| (peek k f q) := supports_stmt q\n| (pop k f q) := supports_stmt q\n| (load a q) := supports_stmt q\n| (branch f q₁ q₂) := supports_stmt q₁ ∧ supports_stmt q₂\n| (goto l) := ∀ v, l v ∈ S\n| halt := true\n\ndef supports (M : Λ → stmt) (S : finset Λ) :=\ndefault Λ ∈ S ∧ ∀ q ∈ S, supports_stmt S (M q)\n\nlocal attribute [instance] classical.dec\nnoncomputable def stmts₁ : stmt → finset stmt\n| Q@(push k f q) := insert Q (stmts₁ q)\n| Q@(peek k f q) := insert Q (stmts₁ q)\n| Q@(pop k f q) := insert Q (stmts₁ q)\n| Q@(load a q) := insert Q (stmts₁ q)\n| Q@(branch f q₁ q₂) := insert Q (stmts₁ q₁ ∪ stmts₁ q₂)\n| Q@(goto l) := {Q}\n| Q@halt := {Q}\n\ntheorem stmts₁_self {q} : q ∈ stmts₁ q :=\nby cases q; simp [stmts₁]\n\ntheorem stmts₁_trans {q₁ q₂} :\n q₁ ∈ stmts₁ q₂ → stmts₁ q₁ ⊆ stmts₁ q₂ :=\nbegin\n intros h₁₂ q₀ h₀₁,\n induction q₂ with _ _ q IH _ _ q IH _ _ q IH _ q IH;\n simp [stmts₁, finset.subset_iff] at h₁₂ ⊢,\n iterate 4 {\n rcases h₁₂ with rfl | h₁₂,\n { simp [stmts₁] at h₀₁, rcases h₀₁ with rfl | h; simp * },\n { exact or.inr (IH h₁₂) } },\n case TM2.stmt.branch : f q₁ q₂ IH₁ IH₂ {\n rcases h₁₂ with rfl | h₁₂ | h₁₂,\n { simp [stmts₁] at h₀₁, rcases h₀₁ with rfl | h; simp * },\n { simp [IH₁ h₁₂] }, { simp [IH₂ h₁₂] } },\n case TM2.stmt.goto : l {\n subst h₁₂, simpa [stmts₁] using h₀₁ },\n case TM2.stmt.halt {\n subst h₁₂, simpa [stmts₁] using h₀₁ }\nend\n\ntheorem stmts₁_supports_stmt_mono {S q₁ q₂}\n (h : q₁ ∈ stmts₁ q₂) (hs : supports_stmt S q₂) : supports_stmt S q₁ :=\nbegin\n induction q₂ with _ _ q IH _ _ q IH _ _ q IH _ q IH;\n simp [stmts₁, supports_stmt] at h hs,\n iterate 4 { rcases h with rfl | h; [exact hs, exact IH h hs] },\n case TM2.stmt.branch : f q₁ q₂ IH₁ IH₂ {\n rcases h with rfl | h | h, exacts [hs, IH₁ h hs.1, IH₂ h hs.2] },\n case TM2.stmt.goto : l { subst h, exact hs },\n case TM2.stmt.halt { subst h, trivial }\nend\n\nnoncomputable def stmts\n (M : Λ → stmt) (S : finset Λ) : finset (option stmt) :=\n(S.bind (λ q, stmts₁ (M q))).insert_none\n\ntheorem stmts_trans {M : Λ → stmt} {S q₁ q₂}\n (h₁ : q₁ ∈ stmts₁ q₂) : some q₂ ∈ stmts M S → some q₁ ∈ stmts M S :=\nby simp [stmts]; exact λ l ls h₂, ⟨_, ls, stmts₁_trans h₂ h₁⟩\n\ntheorem stmts_supports_stmt {M : Λ → stmt} {S q}\n (ss : supports M S) : some q ∈ stmts M S → supports_stmt S q :=\nby simp [stmts]; exact\nλ l ls h, stmts₁_supports_stmt_mono h (ss.2 _ ls)\n\nlocal attribute [-simp] finset.mem_insert_none\ntheorem step_supports (M : Λ → stmt) {S}\n (ss : supports M S) : ∀ {c c' : cfg},\n c' ∈ step M c → c.l ∈ S.insert_none → c'.l ∈ S.insert_none\n| ⟨some l₁, v, T⟩ c' h₁ h₂ := begin\n replace h₂ := ss.2 _ (finset.some_mem_insert_none.1 h₂),\n simp [step] at h₁, subst c',\n revert h₂, induction M l₁ with _ _ q IH _ _ q IH _ _ q IH _ q IH generalizing v T;\n intro hs,\n iterate 4 { exact IH _ _ hs },\n case TM2.stmt.branch : p q₁' q₂' IH₁ IH₂ {\n simp [step_aux], cases p v,\n { exact IH₂ _ _ hs.2 },\n { exact IH₁ _ _ hs.1 } },\n case TM2.stmt.goto { exact finset.some_mem_insert_none.2 (hs _) },\n case TM2.stmt.halt { apply multiset.mem_cons_self }\nend\n\nend\n\nend TM2\n\nnamespace TM2to1\n\nsection\nparameters {K : Type*} [decidable_eq K]\nparameters {Γ : K → Type*}\nparameters {Λ : Type*} [inhabited Λ]\nparameters {σ : Type*} [inhabited σ]\n\nlocal notation `stmt₂` := TM2.stmt Γ Λ σ\nlocal notation `cfg₂` := TM2.cfg Γ Λ σ\n\ninductive stackel (k : K)\n| val : Γ k → stackel\n| bottom : stackel\n| top : stackel\n\ninstance stackel.inhabited (k) : inhabited (stackel k) :=\n⟨stackel.top _⟩\n\ndef stackel.is_bottom {k} : stackel k → bool\n| (stackel.bottom _) := tt\n| _ := ff \n\ndef stackel.is_top {k} : stackel k → bool\n| (stackel.top _) := tt\n| _ := ff \n\ndef stackel.get {k} : stackel k → option (Γ k)\n| (stackel.val a) := some a\n| _ := none\n\nsection\nopen stackel\n\ndef stackel_equiv {k} : stackel k ≃ option (option (Γ k)) :=\nbegin\n refine ⟨λ s, _, λ s, _, _, _⟩,\n { cases s, exacts [some (some s), none, some none] },\n { rcases s with _|_|s, exacts [bottom _, top _, val s] },\n { intro s, cases s; refl },\n { intro s, rcases s with _|_|s; refl },\nend\n\nend\n\ndef Γ' := ∀ k, stackel k\n\ninstance Γ'.inhabited : inhabited Γ' := ⟨λ _, default _⟩\n\ninstance stackel.fintype {k} [fintype (Γ k)] : fintype (stackel k) :=\nfintype.of_equiv _ stackel_equiv.symm\n\ninstance Γ'.fintype [fintype K] [∀ k, fintype (Γ k)] : fintype Γ' :=\npi.fintype\n\ninductive st_act (k : K)\n| push {} : (σ → Γ k) → st_act\n| pop {} : bool → (σ → option (Γ k) → σ) → st_act\n\nsection\nopen st_act\n\ndef st_run {k : K} : st_act k → stmt₂ → stmt₂\n| (push f) := TM2.stmt.push k f\n| (pop ff f) := TM2.stmt.peek k f\n| (pop tt f) := TM2.stmt.pop k f\n\ndef st_var {k : K} (v : σ) (l : list (Γ k)) : st_act k → σ\n| (push f) := v\n| (pop b f) := f v l.head'\n\ndef st_write {k : K} (v : σ) (l : list (Γ k)) : st_act k → list (Γ k)\n| (push f) := f v :: l\n| (pop ff f) := l\n| (pop tt f) := l.tail\n\n@[elab_as_eliminator] theorem {l} stmt_st_rec\n {C : stmt₂ → Sort l}\n (H₁ : Π k (s : st_act k) q (IH : C q), C (st_run s q))\n (H₂ : Π a q (IH : C q), C (TM2.stmt.load a q))\n (H₃ : Π p q₁ q₂ (IH₁ : C q₁) (IH₂ : C q₂), C (TM2.stmt.branch p q₁ q₂))\n (H₄ : Π l, C (TM2.stmt.goto l))\n (H₅ : C TM2.stmt.halt) : ∀ n, C n\n| (TM2.stmt.push k f q) := H₁ _ (push f) _ (stmt_st_rec q)\n| (TM2.stmt.peek k f q) := H₁ _ (pop ff f) _ (stmt_st_rec q)\n| (TM2.stmt.pop k f q) := H₁ _ (pop tt f) _ (stmt_st_rec q)\n| (TM2.stmt.load a q) := H₂ _ _ (stmt_st_rec q)\n| (TM2.stmt.branch a q₁ q₂) := H₃ _ _ _ (stmt_st_rec q₁) (stmt_st_rec q₂)\n| (TM2.stmt.goto l) := H₄ _\n| TM2.stmt.halt := H₅\n\ntheorem supports_run [fintype K] [∀ k, fintype (Γ k)] [fintype σ]\n (S : finset Λ) {k} (s : st_act k) (q) :\n TM2.supports_stmt S (st_run s q) ↔ TM2.supports_stmt S q :=\nby rcases s with _|_|_; refl\n\nend\n\ninductive Λ' : Type (max u_1 u_2 u_3 u_4)\n| normal {} : Λ → Λ'\n| go (k) : st_act k → stmt₂ → Λ'\n| ret {} : K → stmt₂ → Λ'\nopen Λ'\ninstance : inhabited Λ' := ⟨normal (default _)⟩\n\nlocal notation `stmt₁` := TM1.stmt Γ' Λ' σ\nlocal notation `cfg₁` := TM1.cfg Γ' Λ' σ\n\nopen TM1.stmt\n\ndef tr_st_act {k} (q : stmt₁) : st_act k → stmt₁\n| (st_act.push f) :=\n write (λ a s, dwrite a k $ stackel.val $ f s) $\n move dir.right $\n write (λ a s, dwrite a k $ stackel.top k) q\n| (st_act.pop b f) :=\n move dir.left $\n load (λ a s, f s (a k).get) $\n cond b\n ( branch (λ a s, (a k).is_bottom)\n ( move dir.right q )\n ( move dir.right $\n write (λ a s, dwrite a k $ default _) $\n move dir.left $\n write (λ a s, dwrite a k $ stackel.top k) q ) )\n ( move dir.right q )\n\ndef tr_init (k) (L : list (Γ k)) : list Γ' :=\nstackel.bottom :: match L.reverse with\n| [] := [stackel.top]\n| (a::L') := dwrite stackel.top k (stackel.val a) ::\n (L'.map stackel.val ++ [stackel.top k]).map (dwrite (default _) k)\nend\n\ntheorem step_run {k : K} (q v S) : ∀ s : st_act k,\n TM2.step_aux (st_run s q) v S =\n TM2.step_aux q (st_var v (S k) s) (dwrite S k (st_write v (S k) s))\n| (st_act.push f) := rfl\n| (st_act.pop ff f) := by simp!\n| (st_act.pop tt f) := rfl\n\ndef tr_normal : stmt₂ → stmt₁\n| (TM2.stmt.push k f q) := goto (λ _ _, go k (st_act.push f) q)\n| (TM2.stmt.peek k f q) := goto (λ _ _, go k (st_act.pop ff f) q)\n| (TM2.stmt.pop k f q) := goto (λ _ _, go k (st_act.pop tt f) q)\n| (TM2.stmt.load a q) := load (λ _, a) (tr_normal q)\n| (TM2.stmt.branch f q₁ q₂) := branch (λ a, f) (tr_normal q₁) (tr_normal q₂)\n| (TM2.stmt.goto l) := goto (λ a s, normal (l s))\n| TM2.stmt.halt := halt\n\ntheorem tr_normal_run {k} (s q) :\n tr_normal (st_run s q) = goto (λ _ _, go k s q) :=\nby rcases s with _|_|_; refl\n\nparameters (M : Λ → stmt₂)\ninclude M\n\ndef tr : Λ' → stmt₁\n| (normal q) := tr_normal (M q)\n| (go k s q) :=\n branch (λ a s, (a k).is_top) (tr_st_act (goto (λ _ _, ret k q)) s)\n (move dir.right $ goto (λ _ _, go k s q))\n| (ret k q) :=\n branch (λ a s, (a k).is_bottom) (tr_normal q)\n (move dir.left $ goto (λ _ _, ret k q))\n\ndef tr_stk {k} (S : list (Γ k)) (L : list (stackel k)) : Prop :=\n∃ n, L = (S.map stackel.val).reverse_core (stackel.top k :: list.repeat (default _) n)\n\nlocal attribute [pp_using_anonymous_constructor] turing.TM1.cfg\ninductive tr_cfg : cfg₂ → cfg₁ → Prop\n| mk {q v} {S : ∀ k, list (Γ k)} {L : list Γ'} :\n (∀ k, tr_stk (S k) (L.map (λ a, a k))) →\n tr_cfg ⟨q, v, S⟩ ⟨q.map normal, v, (stackel.bottom, [], L)⟩\n\ntheorem tr_respects_aux₁ {k} (o q v) : ∀ S₁ {s S₂} {T : list Γ'},\n T.map (λ (a : Γ'), a k) = (list.map stackel.val S₁).reverse_core (s :: S₂) →\n ∃ a T₁ T₂,\n T = list.reverse_core T₁ (a :: T₂) ∧\n a k = s ∧\n T₁.map (λ (a : Γ'), a k) = S₁.map stackel.val ∧\n T₂.map (λ (a : Γ'), a k) = S₂ ∧\n reaches₀ (TM1.step tr)\n ⟨some (go k o q), v, (stackel.bottom, [], T)⟩\n ⟨some (go k o q), v, (a, T₁ ++ [stackel.bottom], T₂)⟩\n| [] s S₂ (a :: T) hT := by injection hT with es e₂; exact\n ⟨a, [], _, rfl, es, rfl, e₂, reaches₀.single rfl⟩\n| (s' :: S₁) s S₂ T hT :=\n let ⟨a, T₁, b'::T₂, e, es', e₁, e₂, H⟩ := tr_respects_aux₁ S₁ hT in\n by injection e₂ with es e₂; exact\n ⟨b', a::T₁, T₂, e, es, by simpa [es'], e₂, H.tail (by simp! [es'])⟩\n\nlocal attribute [simp] TM1.step TM1.step_aux tr tr_st_act st_var st_write\n tape.move tape.write list.reverse_core stackel.get stackel.is_bottom\n\ntheorem tr_respects_aux₂\n {k q v} {S : Π k, list (Γ k)} {T₁ T₂ : list Γ'} {a : Γ'}\n (hT : ∀ k, tr_stk (S k) ((T₁.reverse_core (a :: T₂)).map (λ (a : Γ'), a k)))\n (e₁ : T₁.map (λ (a : Γ'), a k) = list.map stackel.val (S k))\n (ea : a k = stackel.top k) (o) :\n let v' := st_var v (S k) o,\n Sk' := st_write v (S k) o,\n S' : ∀ k, list (Γ k) := dwrite S k Sk' in\n ∃ b (T₁' T₂' : list Γ'),\n (∀ (k' : K), tr_stk (S' k') ((T₁'.reverse_core (b :: T₂')).map (λ (a : Γ'), a k'))) ∧\n T₁'.map (λ a, a k) = Sk'.map stackel.val ∧\n b k = stackel.top k ∧\n TM1.step_aux (tr_st_act q o) v (a, T₁ ++ [stackel.bottom], T₂) =\n TM1.step_aux q v' (b, T₁' ++ [stackel.bottom], T₂') :=\nbegin\n dsimp, cases o with f b f,\n { -- push\n refine ⟨_, dwrite a k (stackel.val (f v)) :: T₁,\n _, _, by simp [e₁]; refl, by simp, rfl⟩,\n intro k', cases hT k' with n e,\n by_cases h : k' = k,\n { subst k', existsi n.pred,\n simp [list.reverse_core_eq, e₁, list.append_left_inj] at e ⊢,\n simp [e] },\n { cases T₂ with t T₂,\n { existsi n+1,\n simpa [h, list.reverse_core_eq, e₁, list.repeat_add] using\n congr_arg (++ [default Γ' k']) e },\n { existsi n,\n simpa [h, list.reverse_core_eq] using e } } },\n have dw := dwrite_self S k,\n cases T₁ with t T₁; cases eS : S k with s Sk;\n rw eS at e₁ dw; injection e₁ with tk e₁'; cases b,\n { -- peek nil\n simp [eS, dw],\n exact ⟨_, [], _, hT, rfl, ea, rfl⟩ },\n { -- pop nil\n simp [eS, dw],\n exact ⟨_, [], _, hT, rfl, ea, rfl⟩ },\n { -- peek cons\n dsimp at tk,\n simp [eS, tk, dw],\n exact ⟨_, t::T₁, _, hT, e₁, ea, rfl⟩ },\n { -- pop cons\n dsimp at tk,\n simp [eS, tk],\n refine ⟨_, _, _, _, e₁', by simp, rfl⟩,\n intro k', cases hT k' with n e,\n by_cases h : k' = k,\n { subst k', existsi n+1,\n simp [list.reverse_core_eq, eS, e₁', list.append_left_inj] at e ⊢,\n simp [e] },\n { existsi n, simpa [h, list.map_reverse_core] using e } },\nend\n\ntheorem tr_respects_aux₃ {k q v}\n {S : Π k, list (Γ k)} {T : list Γ'}\n (hT : ∀ k, tr_stk (S k) (T.map (λ (a : Γ'), a k))) :\n ∀ (T₁ : list Γ') {T₂ : list Γ'} {a : Γ'} {S₁}\n (e : T = T₁.reverse_core (a :: T₂))\n (ha : (a k).is_bottom = ff)\n (e₁ : T₁.map (λ (a : Γ'), a k) = list.map stackel.val S₁),\n reaches₀ (TM1.step tr)\n ⟨some (ret k q), v, (a, T₁ ++ [stackel.bottom], T₂)⟩\n ⟨some (ret k q), v, (stackel.bottom, [], T)⟩\n| [] T₂ a S₁ e ha e₁ := reaches₀.single (by simp [ha, e])\n| (b :: T₁) T₂ a (s :: S₁) e ha e₁ := begin\n injection e₁ with es e₁, dsimp at es,\n refine reaches₀.head _ (tr_respects_aux₃ T₁ e (by simp [es]) e₁),\n simp [ha]\n end\n\ntheorem tr_respects_aux {q v T k} {S : Π k, list (Γ k)}\n (hT : ∀ (k : K), tr_stk (S k) (list.map (λ (a : Γ'), a k) T))\n (o : st_act k)\n (IH : ∀ {v : σ} {S : Π (k : K), list (Γ k)} {T : list Γ'},\n (∀ (k : K), tr_stk (S k) (list.map (λ (a : Γ'), a k) T)) →\n (∃ b, tr_cfg (TM2.step_aux q v S) b ∧\n reaches (TM1.step tr) (TM1.step_aux (tr_normal q) v (stackel.bottom, [], T)) b)) :\n ∃ b, tr_cfg (TM2.step_aux (st_run o q) v S) b ∧\n reaches (TM1.step tr) (TM1.step_aux (tr_normal (st_run o q))\n v (stackel.bottom, [], T)) b :=\nbegin\n rcases hT k with ⟨n, hTk⟩,\n simp [tr_normal_run],\n rcases tr_respects_aux₁ M o q v _ hTk with ⟨a, T₁, T₂, rfl, ea, e₁, e₂, hgo⟩,\n rcases tr_respects_aux₂ M hT e₁ ea _ with ⟨b, T₁', T₂', hT', e₁', eb, hrun⟩,\n have hret := tr_respects_aux₃ M hT' _ rfl (by simp [eb]) e₁',\n have := hgo.tail' rfl,\n simp [ea, tr] at this, rw [hrun, TM1.step_aux] at this,\n rcases IH hT' with ⟨c, gc, rc⟩,\n simp [step_run],\n refine ⟨c, gc, (this.to₀.trans hret _ (trans_gen.head' rfl rc)).to_refl⟩\nend\n\nlocal attribute [simp] respects TM2.step TM2.step_aux tr_normal\n\ntheorem tr_respects : respects (TM2.step M) (TM1.step tr) tr_cfg :=\nλ c₁ c₂ h, begin\n cases h with l v S L hT, clear h,\n cases l; simp!,\n suffices : ∃ b, _ ∧ reaches (TM1.step (tr M)) _ _,\n from let ⟨b, c, r⟩ := this in ⟨b, c, trans_gen.head' rfl r⟩,\n rw [tr],\n revert v S L hT, refine stmt_st_rec _ _ _ _ _ (M l); intros,\n { exact tr_respects_aux M hT s @IH },\n { simp [IH hT] },\n { simp, cases p v; [exact IH₂ hT, exact IH₁ hT] },\n { exact ⟨_, ⟨hT⟩, refl_trans_gen.refl⟩ },\n { exact ⟨_, ⟨hT⟩, refl_trans_gen.refl⟩ }\nend\n\ntheorem tr_cfg_init (k) (L : list (Γ k)) :\n tr_cfg (TM2.init k L) (TM1.init (tr_init k L)) :=\n⟨λ k', begin\n simp [tr_init, (∘)],\n cases e : L.reverse with a L'; simp [tr_init],\n { cases list.reverse_eq_nil.1 e, simp, exact ⟨0, rfl⟩ },\n by_cases k' = k,\n { subst k', existsi 0,\n simp [list.reverse_core_eq, (∘)],\n rw [← list.map_reverse, e], refl },\n { simp [h, (∘)],\n existsi L'.length + 1,\n rw list.repeat_add, refl }\nend⟩\n\ntheorem tr_eval_dom (k) (L : list (Γ k)) :\n (TM1.eval tr (tr_init k L)).dom ↔ (TM2.eval M k L).dom :=\ntr_eval_dom tr_respects (tr_cfg_init _ _)\n\ntheorem tr_eval (k) (L : list (Γ k)) {L₁ L₂}\n (H₁ : L₁ ∈ TM1.eval tr (tr_init k L))\n (H₂ : L₂ ∈ TM2.eval M k L) :\n ∃ S : ∀ k, list (Γ k),\n (∀ k', tr_stk (S k') (L₁.map (λ a, a k'))) ∧ S k = L₂ :=\nbegin\n rcases (roption.mem_map_iff _).1 H₁ with ⟨c₁, h₁, rfl⟩,\n rcases (roption.mem_map_iff _).1 H₂ with ⟨c₂, h₂, rfl⟩,\n rcases tr_eval (tr_respects M) (tr_cfg_init M k L) h₂\n with ⟨_, ⟨q, v, S, L₁', hT⟩, h₃⟩,\n cases roption.mem_unique h₁ h₃,\n exact ⟨S, hT, rfl⟩\nend\n\nvariables [fintype K] [∀ k, fintype (Γ k)] [fintype σ]\nlocal attribute [instance] classical.dec\nlocal attribute [simp] TM2.stmts₁_self\n\nnoncomputable def tr_stmts₁ : stmt₂ → finset Λ'\n| Q@(TM2.stmt.push k f q) := {go k (st_act.push f) q, ret k q} ∪ tr_stmts₁ q\n| Q@(TM2.stmt.peek k f q) := {go k (st_act.pop ff f) q, ret k q} ∪ tr_stmts₁ q\n| Q@(TM2.stmt.pop k f q) := {go k (st_act.pop tt f) q, ret k q} ∪ tr_stmts₁ q\n| Q@(TM2.stmt.load a q) := tr_stmts₁ q\n| Q@(TM2.stmt.branch f q₁ q₂) := tr_stmts₁ q₁ ∪ tr_stmts₁ q₂\n| _ := ∅\n\ntheorem tr_stmts₁_run {k s q} : tr_stmts₁ (st_run s q) = {go k s q, ret k q} ∪ tr_stmts₁ q :=\nby rcases s with _|_|_; dsimp [tr_stmts₁, st_run]; congr\n\nnoncomputable def tr_supp (S : finset Λ) : finset Λ' :=\nS.bind (λ l, insert (normal l) (tr_stmts₁ (M l)))\n\nlocal attribute [simp] tr_stmts₁ tr_stmts₁_run supports_run\n tr_normal_run TM1.supports_stmt TM2.supports_stmt\n\ntheorem tr_supports {S} (ss : TM2.supports M S) :\n TM1.supports tr (tr_supp S) :=\n⟨finset.mem_bind.2 ⟨_, ss.1, finset.mem_insert.2 $ or.inl rfl⟩,\nλ l' h, begin\n suffices : ∀ q (ss' : TM2.supports_stmt S q)\n (sub : ∀ x ∈ tr_stmts₁ M q, x ∈ tr_supp M S),\n TM1.supports_stmt (tr_supp M S) (tr_normal q) ∧\n (∀ l' ∈ tr_stmts₁ M q, TM1.supports_stmt (tr_supp M S) (tr M l')),\n { simp [tr_supp] at h,\n rcases h with ⟨l, lS, h⟩,\n have := this _ (ss.2 l lS) (λ x hx,\n finset.mem_bind.2 ⟨_, lS, finset.mem_insert_of_mem hx⟩),\n rcases h with rfl | h; [exact this.1, exact this.2 _ h] },\n refine stmt_st_rec _ _ _ _ _; clear h l'; intros,\n { -- stack op\n simp at sub ss',\n have hgo := sub _ (or.inr $ or.inr rfl),\n have hret := sub _ (or.inl rfl),\n cases IH ss' (λ x hx, sub x $ or.inr $ or.inl hx) with IH₁ IH₂,\n refine ⟨by simp [hgo], λ l h, _⟩,\n rw [tr_stmts₁_run] at h, simp at h,\n rcases h with rfl | h | rfl,\n { simp [hret], exact IH₁ },\n { exact IH₂ _ h },\n { simp [hgo],\n rcases s with _|_|_; simp! [hret] } },\n { -- load\n dsimp at sub ⊢, exact IH ss' sub },\n { -- branch\n simp at sub,\n cases IH₁ ss'.1 (λ x hx, sub x $ or.inl hx) with IH₁₁ IH₁₂,\n cases IH₂ ss'.2 (λ x hx, sub x $ or.inr hx) with IH₂₁ IH₂₂,\n refine ⟨⟨IH₁₁, IH₂₁⟩, λ l h, _⟩,\n rw [tr_stmts₁] at h, simp at h,\n rcases h with h | h; [exact IH₁₂ _ h, exact IH₂₂ _ h] },\n { -- goto\n rw tr_stmts₁, simp [tr_normal],\n exact λ v, finset.mem_bind.2 ⟨_, ss' v, by simp⟩ },\n { simp } -- halt\nend⟩\n\nend\n\nend TM2to1\n\nend turing\n", "meta": {"author": "khoek", "repo": "mathlib-tidy", "sha": "866afa6ab597c47f1b72e8fe2b82b97fff5b980f", "save_path": "github-repos/lean/khoek-mathlib-tidy", "path": "github-repos/lean/khoek-mathlib-tidy/mathlib-tidy-866afa6ab597c47f1b72e8fe2b82b97fff5b980f/computability/turing_machine.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46490155654565424, "lm_q2_score": 0.05261895409053963, "lm_q1q2_score": 0.024462633660496193}} {"text": "namespace Ex1\n\ninductive T: Type :=\n | mk: String → Option T → T\n\ndef runT: T → Nat\n | .mk _ none => 0\n | .mk _ (some t) => runT t\n\nclass Run (α: Type) where\n run: α → Nat\ninstance: Run T := ⟨runT⟩\n\ndef x := T.mk \"PrettyLong\" (some <| .mk \"PrettyLong\" none)\n\ntheorem equivalent: Run.run x = Run.run x := by\n -- simp (config := { dsimp := false, decide := false, etaStruct := .none }) [Run.run]\n apply Eq.refl (runT x)\n\nexample : Run.run x = Run.run x := by\n simp [Run.run]\n\nend Ex1\n\nnamespace Ex2\n\ninductive Wrapper where\n | wrap: Wrapper\n\ndef Wrapper.extend: Wrapper → (Unit × Unit)\n | .wrap => ((), ())\n\nmutual\ninductive Op where\n | mk: String → Block → Op\n\ninductive Assign where\n | mk : String → Op → Assign\n\ninductive Block where\n | mk: Assign → Block\n | empty: Block\nend\n\nmutual\ndef runOp: Op → Wrapper\n | .mk _ r => let r' := runBlock r; .wrap\n\ndef runAssign: Assign → Wrapper\n | .mk _ op => runOp op\n\ndef runBlock: Block → Wrapper\n | .mk a => runAssign a\n | .empty => .wrap\nend\n\nprivate def b: Assign := .mk \"r\" (.mk \"APrettyLongString\" .empty)\n\ntheorem bug: (runAssign b).extend.snd = (runAssign b).extend.snd := by\n --unfold b -- extremely slow\n sorry\n\nend Ex2\n\nnamespace Ex3\n\ninductive ProgramType := | Op | Assign | Block\n\nsection\nset_option hygiene false\nnotation \"Op\" => Program ProgramType.Op\nnotation \"Assign\" => Program ProgramType.Assign\nnotation \"Block\" => Program ProgramType.Block\nend\n\ninductive Program: (type: ProgramType) → Type :=\n | mkOp: String → Block → Op\n | mkAssign: String → Op → Assign\n | mkBlock: Assign → Block\n | emptyBlock: Block\n\ndef runBase: Program type → Nat\n | .mkOp _ v => let _ := runBase v; 0\n | .mkAssign _ t => runBase t\n | .mkBlock u => runBase u\n | .emptyBlock => 0\n\nclass Run (α: Type) where\n run: α → Nat\ninstance: Run Assign := ⟨runBase⟩\n\ndef x: Assign := .mkAssign \"PrettyLong\" <| .mkOp \"PrettyLong\" .emptyBlock\n-- Now runs fine\ntheorem equivalent: Run.run x = Run.run x := by simp [Run.run]\n\nend Ex3\n", "meta": {"author": "leanprover", "repo": "lean4", "sha": "742d053a97bdd109a41a921facd1cd6a55e89bc7", "save_path": "github-repos/lean/leanprover-lean4", "path": "github-repos/lean/leanprover-lean4/lean4-742d053a97bdd109a41a921facd1cd6a55e89bc7/tests/lean/run/lazyUnfoldingPerfIssue.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4687906266262437, "lm_q2_score": 0.05184546976292211, "lm_q1q2_score": 0.02430467025789223}} {"text": "/-\nCopyright (c) 2022 Andrew Yang. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Andrew Yang\n-/\nimport morphisms.ring_hom_properties\nimport ring_theory.ring_hom.finite_type\nimport dimension_theory.jacobson\nimport algebraic_geometry.surjective_on_stalks\n\n/-!\n# Morphisms of finite type\n\nA morphism of schemes `f : X ⟶ Y` is locally of finite type if for each affine `U ⊆ Y` and\n`V ⊆ f ⁻¹' U`, The induced map `Γ(Y, U) ⟶ Γ(X, V)` is of finite type.\n\nA morphism of schemes is of finite type if it is both locally of finite type and quasi-compact.\n\nWe show that these properties are local, and are stable under compositions.\n\n-/\n\nnoncomputable theory\n\nopen category_theory category_theory.limits opposite topological_space\n\nuniverses v u\n\nnamespace algebraic_geometry\n\nvariables {X Y : Scheme.{u}} (f : X ⟶ Y)\n\n/--\nA morphism of schemes `f : X ⟶ Y` is locally of finite type if for each affine `U ⊆ Y` and\n`V ⊆ f ⁻¹' U`, The induced map `Γ(Y, U) ⟶ Γ(X, V)` is of finite type.\n-/\n@[mk_iff]\nclass locally_of_finite_type (f : X ⟶ Y) : Prop :=\n(finite_type_of_affine_subset :\n ∀ (U : Y.affine_opens) (V : X.affine_opens) (e : V.1 ≤ (opens.map f.1.base).obj U.1),\n (f.app_le e).finite_type)\n\nlemma locally_of_finite_type_eq :\n @locally_of_finite_type = affine_locally @ring_hom.finite_type :=\nbegin\n ext X Y f,\n rw [locally_of_finite_type_iff, affine_locally_iff_affine_opens_le],\n exact ring_hom.finite_type_respects_iso\nend\n\n@[priority 900]\ninstance locally_of_finite_type_of_is_open_immersion {X Y : Scheme} (f : X ⟶ Y)\n [is_open_immersion f] : locally_of_finite_type f :=\nlocally_of_finite_type_eq.symm ▸\n ring_hom.finite_type_is_local.affine_locally_of_is_open_immersion f\n\nlemma locally_of_finite_type_stable_under_composition :\n morphism_property.stable_under_composition @locally_of_finite_type :=\nlocally_of_finite_type_eq.symm ▸\nring_hom.finite_type_is_local.affine_locally_stable_under_composition\n\ninstance locally_of_finite_type_comp {X Y Z : Scheme} (f : X ⟶ Y) (g : Y ⟶ Z)\n [hf : locally_of_finite_type f] [hg : locally_of_finite_type g] :\n locally_of_finite_type (f ≫ g) :=\nlocally_of_finite_type_stable_under_composition f g hf hg\n\nlemma locally_of_finite_type_of_comp {X Y Z : Scheme} (f : X ⟶ Y) (g : Y ⟶ Z)\n [hf : locally_of_finite_type (f ≫ g)] :\n locally_of_finite_type f :=\nbegin\n unfreezingI { revert hf },\n rw [locally_of_finite_type_eq],\n apply ring_hom.finite_type_is_local.affine_locally_of_comp,\n introv H,\n exactI ring_hom.finite_type.of_comp_finite_type H,\nend\n\nlemma locally_of_finite_type.affine_open_cover_iff {X Y : Scheme.{u}} (f : X ⟶ Y)\n (𝒰 : Scheme.open_cover.{u} Y) [∀ i, is_affine (𝒰.obj i)]\n (𝒰' : ∀ i, Scheme.open_cover.{u} ((𝒰.pullback_cover f).obj i))\n [∀ i j, is_affine ((𝒰' i).obj j)] :\n locally_of_finite_type f ↔\n (∀ i j, (Scheme.Γ.map ((𝒰' i).map j ≫ pullback.snd).op).finite_type) :=\nlocally_of_finite_type_eq.symm ▸ ring_hom.finite_type_is_local.affine_open_cover_iff f 𝒰 𝒰'\n\nlemma locally_of_finite_type.source_open_cover_iff {X Y : Scheme.{u}} (f : X ⟶ Y)\n (𝒰 : Scheme.open_cover.{u} X) :\n locally_of_finite_type f ↔ (∀ i, locally_of_finite_type (𝒰.map i ≫ f)) :=\nlocally_of_finite_type_eq.symm ▸ ring_hom.finite_type_is_local.source_open_cover_iff f 𝒰\n\nlemma locally_of_finite_type.open_cover_iff {X Y : Scheme.{u}} (f : X ⟶ Y)\n (𝒰 : Scheme.open_cover.{u} Y) :\n locally_of_finite_type f ↔\n (∀ i, locally_of_finite_type (pullback.snd : pullback f (𝒰.map i) ⟶ _)) :=\nlocally_of_finite_type_eq.symm ▸\n ring_hom.finite_type_is_local.is_local_affine_locally.open_cover_iff f 𝒰\n\nlemma locally_of_finite_type_respects_iso :\n morphism_property.respects_iso @locally_of_finite_type :=\nlocally_of_finite_type_eq.symm ▸ target_affine_locally_respects_iso\n (source_affine_locally_respects_iso ring_hom.finite_type_respects_iso)\n\nlemma locally_of_finite_type_is_local_at_target :\n property_is_local_at_target @locally_of_finite_type :=\nlocally_of_finite_type_eq.symm ▸\n (source_affine_locally_is_local ring_hom.finite_type_respects_iso\n ring_hom.finite_type_is_local.localization_preserves \n ring_hom.finite_type_is_local.of_localization_span).target_affine_locally_is_local\n\nlemma locally_of_finite_type_is_local_at_source :\n property_is_local_at_source @locally_of_finite_type :=\nlocally_of_finite_type_eq.symm ▸\n ring_hom.finite_type_is_local.affine_locally_local_at_source\n\n-- move me\nlemma subalgebra.map_top {R S T : Type*} [comm_ring R] [comm_ring S] [comm_ring T]\n [algebra R S] [algebra R T] (f : S →ₐ[R] T) : (⊤ : subalgebra R S).map f = f.range := \nbegin\n ext, simp,\nend\n\n-- move me\nlemma _root_.ring_hom.finite_type_stable_under_base_change :\n ring_hom.stable_under_base_change @ring_hom.finite_type :=\nbegin\n classical,\n rintros R S T _ _ _ _ i7 ⟨⟨s, hs⟩⟩,\n resetI,\n suffices : algebra.finite_type S (tensor_product R S T),\n { delta ring_hom.finite_type, convert this, apply algebra.algebra_ext, intro _, refl },\n replace hs : algebra.adjoin R (↑s : set T) = ⊤,\n { have : i7 = (algebra_map R T).to_algebra := algebra.algebra_ext _ _ (λ _, rfl), convert hs },\n refine ⟨⟨s.image algebra.tensor_product.include_right, _⟩⟩,\n rw [finset.coe_image, ← @algebra.adjoin_adjoin_of_tower R S (tensor_product R S T),\n algebra.adjoin_image, hs, subalgebra.map_top, eq_top_iff],\n rintro x -,\n induction x using tensor_product.induction_on with x y x y hx hy,\n { exact zero_mem _ },\n { convert_to x • ((1 : S) ⊗ₜ y) ∈ _,\n { rw [tensor_product.smul_tmul', ← algebra.algebra_map_eq_smul_one], refl },\n { exact subalgebra.smul_mem _ (algebra.subset_adjoin ⟨y, rfl⟩) _ } },\n { exact add_mem hx hy }\nend\n\nlemma locally_of_finite_type_stable_under_base_change :\n morphism_property.stable_under_base_change @locally_of_finite_type :=\nlocally_of_finite_type_eq.symm ▸\n ring_hom.finite_type_is_local.affine_locally_stable_under_base_change\n ring_hom.finite_type_stable_under_base_change\n\ninstance {X Y Z : Scheme} (f : X ⟶ Z) (g : Y ⟶ Z) [locally_of_finite_type g] : \n locally_of_finite_type (pullback.fst : pullback f g ⟶ _) :=\nlocally_of_finite_type_stable_under_base_change.fst _ _ ‹_›\n\ninstance {X Y Z : Scheme} (f : X ⟶ Z) (g : Y ⟶ Z) [locally_of_finite_type f] : \n locally_of_finite_type (pullback.snd : pullback f g ⟶ _) :=\nlocally_of_finite_type_stable_under_base_change.snd _ _ ‹_›\n\n-- generalize me\nlemma locally_of_finite_type_Spec_iff {R S : CommRing} (f : R ⟶ S) :\n locally_of_finite_type (Scheme.Spec.map f.op) ↔ ring_hom.finite_type f :=\nbegin\n transitivity (@affine ⊓ @locally_of_finite_type) (Scheme.Spec.map f.op),\n { refine (and_iff_right _).symm, apply_instance },\n { rw [locally_of_finite_type_eq, ← ring_hom.property_is_local.affine_and_eq,\n (is_local_affine_and _ _ _ _).affine_target_iff, affine_and_Spec_iff],\n exacts [ring_hom.finite_type_respects_iso, ring_hom.finite_type_respects_iso,\n ring_hom.finite_type_is_local.localization_preserves,\n ring_hom.finite_type_is_local.of_localization_span,\n ring_hom.finite_type_is_local] }\nend\n\nlemma locally_of_finite_type.is_jacobson [locally_of_finite_type f] (hY : is_jacobson Y.carrier) :\n is_jacobson X.carrier :=\nbegin\n let 𝒰 : X.open_cover := (Y.affine_cover.pullback_cover f).bind (λ _, Scheme.affine_cover _),\n rw is_jacobson_iff_of_supr_eq_top 𝒰.supr_opens_range,\n intro i,\n refine is_jacobson.of_closed_embedding _ (homeomorph.of_embedding (𝒰.map i).1.base\n (is_open_immersion.base_open _).to_embedding).symm.closed_embedding,\n let g : 𝒰.obj i ⟶ _ := (Scheme.affine_cover _).map _ ≫ pullback.snd,\n refine prime_spectrum.is_jacobson_iff_is_jacobson.mp _,\n apply_with\n (@@is_jacobson_of_ring_hom_finite_type _ _ (Scheme.Spec.preimage g).unop) { instances := ff },\n { refine prime_spectrum.is_jacobson_iff_is_jacobson.mpr _,\n exact is_jacobson.of_open_embedding hY (is_open_immersion.base_open $ Y.affine_cover.map _) },\n rw [← locally_of_finite_type_Spec_iff, quiver.hom.op_unop, Scheme.Spec.image_preimage],\n apply_instance\nend\n\nend algebraic_geometry\n", "meta": {"author": "erdOne", "repo": "lean-AG-morphisms", "sha": "bfb65e7d5c17f333abd7b1806717f12cd29427fd", "save_path": "github-repos/lean/erdOne-lean-AG-morphisms", "path": "github-repos/lean/erdOne-lean-AG-morphisms/lean-AG-morphisms-bfb65e7d5c17f333abd7b1806717f12cd29427fd/src/morphisms/finite_type.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167645017354, "lm_q2_score": 0.052618953347713764, "lm_q1q2_score": 0.02425821962383076}} {"text": "/- \"Hello world\" -/\n\n#eval \"hello\" ++ \" \" ++ \"world\"\n-- \"hello world\"\n\n#check true\n-- Bool\n\ndef x := 10\n\n#eval x + 2\n-- 12\n\ndef double (x : Int) := 2*x\n\n#eval double 3\n-- 6\n#check double\n-- Int → Int\nexample : double 4 = 8 := rfl\n\n\n", "meta": {"author": "leanprover", "repo": "lean4", "sha": "742d053a97bdd109a41a921facd1cd6a55e89bc7", "save_path": "github-repos/lean/leanprover-lean4", "path": "github-repos/lean/leanprover-lean4/lean4-742d053a97bdd109a41a921facd1cd6a55e89bc7/doc/examples/NFM2022/nfm1.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.32423541204073586, "lm_q2_score": 0.07477004703138002, "lm_q1q2_score": 0.024243097007524698}} {"text": "/-\nCopyright (c) 2018 Simon Hudon. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Simon Hudon, Patrick Massot\n\n! This file was ported from Lean 3 source module group_theory.group_action.pi\n! leanprover-community/mathlib commit c3291da49cfa65f0d43b094750541c0731edc932\n! Please do not edit these lines, except to modify the commit id\n! if you have ported upstream changes.\n-/\nimport Mathbin.Algebra.Group.Pi\nimport Mathbin.GroupTheory.GroupAction.Defs\n\n/-!\n# Pi instances for multiplicative actions\n\n> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.\n> Any changes to this file require a corresponding PR to mathlib4.\n\nThis file defines instances for mul_action and related structures on Pi types.\n\n## See also\n\n* `group_theory.group_action.option`\n* `group_theory.group_action.prod`\n* `group_theory.group_action.sigma`\n* `group_theory.group_action.sum`\n-/\n\n\nuniverse u v w\n\nvariable {I : Type u}\n\n-- The indexing type\nvariable {f : I → Type v}\n\n-- The family of types already equipped with instances\nvariable (x y : ∀ i, f i) (i : I)\n\nnamespace Pi\n\n#print Pi.smul' /-\n@[to_additive Pi.vadd']\ninstance smul' {g : I → Type _} [∀ i, SMul (f i) (g i)] : SMul (∀ i, f i) (∀ i : I, g i) :=\n ⟨fun s x => fun i => s i • x i⟩\n#align pi.has_smul' Pi.smul'\n#align pi.has_vadd' Pi.vadd'\n-/\n\n/- warning: pi.smul_apply' -> Pi.smul_apply' is a dubious translation:\nlean 3 declaration is\n forall {I : Type.{u1}} {f : I -> Type.{u2}} (i : I) {g : I -> Type.{u3}} [_inst_1 : forall (i : I), SMul.{u2, u3} (f i) (g i)] (s : forall (i : I), f i) (x : forall (i : I), g i), Eq.{succ u3} (g i) (SMul.smul.{max u1 u2, max u1 u3} (forall (i : I), f i) (forall (i : I), g i) (Pi.smul'.{u1, u2, u3} I (fun (i : I) => f i) (fun (i : I) => g i) (fun (i : I) => _inst_1 i)) s x i) (SMul.smul.{u2, u3} (f i) (g i) (_inst_1 i) (s i) (x i))\nbut is expected to have type\n forall {I : Type.{u2}} {f : I -> Type.{u3}} (i : I) {g : I -> Type.{u1}} [_inst_1 : forall (i : I), SMul.{u3, u1} (f i) (g i)] (s : forall (i : I), f i) (x : forall (i : I), g i), Eq.{succ u1} (g i) (HSMul.hSMul.{max u2 u3, max u2 u1, max u2 u1} (forall (i : I), f i) (forall (i : I), g i) (forall (i : I), g i) (instHSMul.{max u2 u3, max u2 u1} (forall (i : I), f i) (forall (i : I), g i) (Pi.smul'.{u2, u3, u1} I (fun (i : I) => f i) (fun (i : I) => g i) (fun (i : I) => _inst_1 i))) s x i) (HSMul.hSMul.{u3, u1, u1} (f i) (g i) (g i) (instHSMul.{u3, u1} (f i) (g i) (_inst_1 i)) (s i) (x i))\nCase conversion may be inaccurate. Consider using '#align pi.smul_apply' Pi.smul_apply'ₓ'. -/\n@[simp, to_additive]\ntheorem smul_apply' {g : I → Type _} [∀ i, SMul (f i) (g i)] (s : ∀ i, f i) (x : ∀ i, g i) :\n (s • x) i = s i • x i :=\n rfl\n#align pi.smul_apply' Pi.smul_apply'\n#align pi.vadd_apply' Pi.vadd_apply'\n\n#print Pi.isScalarTower /-\n@[to_additive]\ninstance isScalarTower {α β : Type _} [SMul α β] [∀ i, SMul β <| f i] [∀ i, SMul α <| f i]\n [∀ i, IsScalarTower α β (f i)] : IsScalarTower α β (∀ i : I, f i) :=\n ⟨fun x y z => funext fun i => smul_assoc x y (z i)⟩\n#align pi.is_scalar_tower Pi.isScalarTower\n#align pi.vadd_assoc_class Pi.vaddAssocClass\n-/\n\n#print Pi.isScalarTower' /-\n@[to_additive]\ninstance isScalarTower' {g : I → Type _} {α : Type _} [∀ i, SMul α <| f i] [∀ i, SMul (f i) (g i)]\n [∀ i, SMul α <| g i] [∀ i, IsScalarTower α (f i) (g i)] :\n IsScalarTower α (∀ i : I, f i) (∀ i : I, g i) :=\n ⟨fun x y z => funext fun i => smul_assoc x (y i) (z i)⟩\n#align pi.is_scalar_tower' Pi.isScalarTower'\n#align pi.vadd_assoc_class' Pi.vaddAssocClass'\n-/\n\n#print Pi.isScalarTower'' /-\n@[to_additive]\ninstance isScalarTower'' {g : I → Type _} {h : I → Type _} [∀ i, SMul (f i) (g i)]\n [∀ i, SMul (g i) (h i)] [∀ i, SMul (f i) (h i)] [∀ i, IsScalarTower (f i) (g i) (h i)] :\n IsScalarTower (∀ i, f i) (∀ i, g i) (∀ i, h i) :=\n ⟨fun x y z => funext fun i => smul_assoc (x i) (y i) (z i)⟩\n#align pi.is_scalar_tower'' Pi.isScalarTower''\n#align pi.vadd_assoc_class'' Pi.vaddAssocClass''\n-/\n\n#print Pi.smulCommClass /-\n@[to_additive]\ninstance smulCommClass {α β : Type _} [∀ i, SMul α <| f i] [∀ i, SMul β <| f i]\n [∀ i, SMulCommClass α β (f i)] : SMulCommClass α β (∀ i : I, f i) :=\n ⟨fun x y z => funext fun i => smul_comm x y (z i)⟩\n#align pi.smul_comm_class Pi.smulCommClass\n#align pi.vadd_comm_class Pi.vaddCommClass\n-/\n\n#print Pi.smulCommClass' /-\n@[to_additive]\ninstance smulCommClass' {g : I → Type _} {α : Type _} [∀ i, SMul α <| g i] [∀ i, SMul (f i) (g i)]\n [∀ i, SMulCommClass α (f i) (g i)] : SMulCommClass α (∀ i : I, f i) (∀ i : I, g i) :=\n ⟨fun x y z => funext fun i => smul_comm x (y i) (z i)⟩\n#align pi.smul_comm_class' Pi.smulCommClass'\n#align pi.vadd_comm_class' Pi.vaddCommClass'\n-/\n\n#print Pi.smulCommClass'' /-\n@[to_additive]\ninstance smulCommClass'' {g : I → Type _} {h : I → Type _} [∀ i, SMul (g i) (h i)]\n [∀ i, SMul (f i) (h i)] [∀ i, SMulCommClass (f i) (g i) (h i)] :\n SMulCommClass (∀ i, f i) (∀ i, g i) (∀ i, h i) :=\n ⟨fun x y z => funext fun i => smul_comm (x i) (y i) (z i)⟩\n#align pi.smul_comm_class'' Pi.smulCommClass''\n#align pi.vadd_comm_class'' Pi.vaddCommClass''\n-/\n\n@[to_additive]\ninstance {α : Type _} [∀ i, SMul α <| f i] [∀ i, SMul αᵐᵒᵖ <| f i] [∀ i, IsCentralScalar α (f i)] :\n IsCentralScalar α (∀ i, f i) :=\n ⟨fun r m => funext fun i => op_smul_eq_smul _ _⟩\n\n/- warning: pi.has_faithful_smul_at -> Pi.faithfulSMul_at is a dubious translation:\nlean 3 declaration is\n forall {I : Type.{u1}} {f : I -> Type.{u2}} {α : Type.{u3}} [_inst_1 : forall (i : I), SMul.{u3, u2} α (f i)] [_inst_2 : forall (i : I), Nonempty.{succ u2} (f i)] (i : I) [_inst_3 : FaithfulSMul.{u3, u2} α (f i) (_inst_1 i)], FaithfulSMul.{u3, max u1 u2} α (forall (i : I), f i) (Pi.instSMul.{u1, u2, u3} I α (fun (i : I) => f i) (fun (i : I) => _inst_1 i))\nbut is expected to have type\n forall {I : Type.{u2}} {f : I -> Type.{u3}} {α : Type.{u1}} [_inst_1 : forall (i : I), SMul.{u1, u3} α (f i)] [_inst_2 : forall (i : I), Nonempty.{succ u3} (f i)] (i : I) [_inst_3 : FaithfulSMul.{u1, u3} α (f i) (_inst_1 i)], FaithfulSMul.{u1, max u2 u3} α (forall (i : I), f i) (Pi.instSMul.{u2, u3, u1} I α (fun (i : I) => f i) (fun (i : I) => _inst_1 i))\nCase conversion may be inaccurate. Consider using '#align pi.has_faithful_smul_at Pi.faithfulSMul_atₓ'. -/\n/-- If `f i` has a faithful scalar action for a given `i`, then so does `Π i, f i`. This is\nnot an instance as `i` cannot be inferred. -/\n@[to_additive Pi.faithfulVAdd_at\n \"If `f i` has a faithful additive action for a given `i`, then\\nso does `Π i, f i`. This is not an instance as `i` cannot be inferred\"]\ntheorem faithfulSMul_at {α : Type _} [∀ i, SMul α <| f i] [∀ i, Nonempty (f i)] (i : I)\n [FaithfulSMul α (f i)] : FaithfulSMul α (∀ i, f i) :=\n ⟨fun x y h =>\n eq_of_smul_eq_smul fun a : f i => by\n classical\n have :=\n congr_fun (h <| Function.update (fun j => Classical.choice (‹∀ i, Nonempty (f i)› j)) i a)\n i\n simpa using this⟩\n#align pi.has_faithful_smul_at Pi.faithfulSMul_at\n#align pi.has_faithful_vadd_at Pi.faithfulVAdd_at\n\n#print Pi.faithfulSMul /-\n@[to_additive Pi.faithfulVAdd]\ninstance faithfulSMul {α : Type _} [Nonempty I] [∀ i, SMul α <| f i] [∀ i, Nonempty (f i)]\n [∀ i, FaithfulSMul α (f i)] : FaithfulSMul α (∀ i, f i) :=\n let ⟨i⟩ := ‹Nonempty I›\n faithfulSMul_at i\n#align pi.has_faithful_smul Pi.faithfulSMul\n#align pi.has_faithful_vadd Pi.faithfulVAdd\n-/\n\n#print Pi.mulAction /-\n@[to_additive]\ninstance mulAction (α) {m : Monoid α} [∀ i, MulAction α <| f i] : @MulAction α (∀ i : I, f i) m\n where\n smul := (· • ·)\n mul_smul r s f := funext fun i => mul_smul _ _ _\n one_smul f := funext fun i => one_smul α _\n#align pi.mul_action Pi.mulAction\n#align pi.add_action Pi.addAction\n-/\n\n#print Pi.mulAction' /-\n@[to_additive]\ninstance mulAction' {g : I → Type _} {m : ∀ i, Monoid (f i)} [∀ i, MulAction (f i) (g i)] :\n @MulAction (∀ i, f i) (∀ i : I, g i) (@Pi.monoid I f m)\n where\n smul := (· • ·)\n mul_smul r s f := funext fun i => mul_smul _ _ _\n one_smul f := funext fun i => one_smul _ _\n#align pi.mul_action' Pi.mulAction'\n#align pi.add_action' Pi.addAction'\n-/\n\n#print Pi.smulZeroClass /-\ninstance smulZeroClass (α) {n : ∀ i, Zero <| f i} [∀ i, SMulZeroClass α <| f i] :\n @SMulZeroClass α (∀ i : I, f i) (@Pi.instZero I f n)\n where smul_zero c := funext fun i => smul_zero _\n#align pi.smul_zero_class Pi.smulZeroClass\n-/\n\n#print Pi.smulZeroClass' /-\ninstance smulZeroClass' {g : I → Type _} {n : ∀ i, Zero <| g i} [∀ i, SMulZeroClass (f i) (g i)] :\n @SMulZeroClass (∀ i, f i) (∀ i : I, g i) (@Pi.instZero I g n)\n where smul_zero := by\n intros\n ext x\n apply smul_zero\n#align pi.smul_zero_class' Pi.smulZeroClass'\n-/\n\n#print Pi.distribSMul /-\ninstance distribSMul (α) {n : ∀ i, AddZeroClass <| f i} [∀ i, DistribSMul α <| f i] :\n @DistribSMul α (∀ i : I, f i) (@Pi.addZeroClass I f n)\n where smul_add c f g := funext fun i => smul_add _ _ _\n#align pi.distrib_smul Pi.distribSMul\n-/\n\n#print Pi.distribSMul' /-\ninstance distribSMul' {g : I → Type _} {n : ∀ i, AddZeroClass <| g i}\n [∀ i, DistribSMul (f i) (g i)] : @DistribSMul (∀ i, f i) (∀ i : I, g i) (@Pi.addZeroClass I g n)\n where smul_add := by\n intros\n ext x\n apply smul_add\n#align pi.distrib_smul' Pi.distribSMul'\n-/\n\n#print Pi.distribMulAction /-\ninstance distribMulAction (α) {m : Monoid α} {n : ∀ i, AddMonoid <| f i}\n [∀ i, DistribMulAction α <| f i] : @DistribMulAction α (∀ i : I, f i) m (@Pi.addMonoid I f n) :=\n { Pi.mulAction _, Pi.distribSMul _ with }\n#align pi.distrib_mul_action Pi.distribMulAction\n-/\n\n#print Pi.distribMulAction' /-\ninstance distribMulAction' {g : I → Type _} {m : ∀ i, Monoid (f i)} {n : ∀ i, AddMonoid <| g i}\n [∀ i, DistribMulAction (f i) (g i)] :\n @DistribMulAction (∀ i, f i) (∀ i : I, g i) (@Pi.monoid I f m) (@Pi.addMonoid I g n) :=\n { Pi.mulAction', Pi.distribSMul' with }\n#align pi.distrib_mul_action' Pi.distribMulAction'\n-/\n\n/- warning: pi.single_smul -> Pi.single_smul is a dubious translation:\nlean 3 declaration is\n forall {I : Type.{u1}} {f : I -> Type.{u2}} {α : Type.{u3}} [_inst_1 : Monoid.{u3} α] [_inst_2 : forall (i : I), AddMonoid.{u2} (f i)] [_inst_3 : forall (i : I), DistribMulAction.{u3, u2} α (f i) _inst_1 (_inst_2 i)] [_inst_4 : DecidableEq.{succ u1} I] (i : I) (r : α) (x : f i), Eq.{max (succ u1) (succ u2)} (forall (i : I), f i) (Pi.single.{u1, u2} I (fun (i : I) => f i) (fun (a : I) (b : I) => _inst_4 a b) (fun (i : I) => AddZeroClass.toHasZero.{u2} (f i) (AddMonoid.toAddZeroClass.{u2} (f i) (_inst_2 i))) i (SMul.smul.{u3, u2} α (f i) (SMulZeroClass.toHasSmul.{u3, u2} α (f i) (AddZeroClass.toHasZero.{u2} (f i) (AddMonoid.toAddZeroClass.{u2} (f i) (_inst_2 i))) (DistribSMul.toSmulZeroClass.{u3, u2} α (f i) (AddMonoid.toAddZeroClass.{u2} (f i) (_inst_2 i)) (DistribMulAction.toDistribSMul.{u3, u2} α (f i) _inst_1 (_inst_2 i) (_inst_3 i)))) r x)) (SMul.smul.{u3, max u1 u2} α (forall (i : I), f i) (Pi.instSMul.{u1, u2, u3} I α (fun (i : I) => f i) (fun (i : I) => SMulZeroClass.toHasSmul.{u3, u2} α (f i) (AddZeroClass.toHasZero.{u2} (f i) (AddMonoid.toAddZeroClass.{u2} (f i) (_inst_2 i))) (DistribSMul.toSmulZeroClass.{u3, u2} α (f i) (AddMonoid.toAddZeroClass.{u2} (f i) (_inst_2 i)) (DistribMulAction.toDistribSMul.{u3, u2} α (f i) _inst_1 (_inst_2 i) (_inst_3 i))))) r (Pi.single.{u1, u2} I (fun (i : I) => f i) (fun (a : I) (b : I) => _inst_4 a b) (fun (i : I) => AddZeroClass.toHasZero.{u2} (f i) (AddMonoid.toAddZeroClass.{u2} (f i) (_inst_2 i))) i x))\nbut is expected to have type\n forall {I : Type.{u2}} {f : I -> Type.{u3}} {α : Type.{u1}} [_inst_1 : Monoid.{u1} α] [_inst_2 : forall (i : I), AddMonoid.{u3} (f i)] [_inst_3 : forall (i : I), DistribMulAction.{u1, u3} α (f i) _inst_1 (_inst_2 i)] [_inst_4 : DecidableEq.{succ u2} I] (i : I) (r : α) (x : f i), Eq.{max (succ u2) (succ u3)} (forall (i : I), f i) (Pi.single.{u2, u3} I f (fun (a : I) (b : I) => _inst_4 a b) (fun (i : I) => AddMonoid.toZero.{u3} (f i) (_inst_2 i)) i (HSMul.hSMul.{u1, u3, u3} α (f i) (f i) (instHSMul.{u1, u3} α (f i) (SMulZeroClass.toSMul.{u1, u3} α (f i) (AddMonoid.toZero.{u3} (f i) (_inst_2 i)) (DistribSMul.toSMulZeroClass.{u1, u3} α (f i) (AddMonoid.toAddZeroClass.{u3} (f i) (_inst_2 i)) (DistribMulAction.toDistribSMul.{u1, u3} α (f i) _inst_1 (_inst_2 i) (_inst_3 i))))) r x)) (HSMul.hSMul.{u1, max u3 u2, max u2 u3} α (forall (j : I), f j) (forall (i : I), f i) (instHSMul.{u1, max u2 u3} α (forall (j : I), f j) (Pi.instSMul.{u2, u3, u1} I α (fun (j : I) => f j) (fun (i : I) => SMulZeroClass.toSMul.{u1, u3} α (f i) (AddMonoid.toZero.{u3} (f i) (_inst_2 i)) (DistribSMul.toSMulZeroClass.{u1, u3} α (f i) (AddMonoid.toAddZeroClass.{u3} (f i) (_inst_2 i)) (DistribMulAction.toDistribSMul.{u1, u3} α (f i) _inst_1 (_inst_2 i) (_inst_3 i)))))) r (Pi.single.{u2, u3} I f (fun (a : I) (b : I) => _inst_4 a b) (fun (i : I) => AddMonoid.toZero.{u3} (f i) (_inst_2 i)) i x))\nCase conversion may be inaccurate. Consider using '#align pi.single_smul Pi.single_smulₓ'. -/\ntheorem single_smul {α} [Monoid α] [∀ i, AddMonoid <| f i] [∀ i, DistribMulAction α <| f i]\n [DecidableEq I] (i : I) (r : α) (x : f i) : single i (r • x) = r • single i x :=\n single_op (fun i : I => ((· • ·) r : f i → f i)) (fun j => smul_zero _) _ _\n#align pi.single_smul Pi.single_smul\n\n/- warning: pi.single_smul' -> Pi.single_smul' is a dubious translation:\nlean 3 declaration is\n forall {I : Type.{u1}} {α : Type.{u2}} {β : Type.{u3}} [_inst_1 : Monoid.{u2} α] [_inst_2 : AddMonoid.{u3} β] [_inst_3 : DistribMulAction.{u2, u3} α β _inst_1 _inst_2] [_inst_4 : DecidableEq.{succ u1} I] (i : I) (r : α) (x : β), Eq.{max (succ u1) (succ u3)} (I -> β) (Pi.single.{u1, u3} I (fun (i : I) => β) (fun (a : I) (b : I) => _inst_4 a b) (fun (i : I) => AddZeroClass.toHasZero.{u3} β (AddMonoid.toAddZeroClass.{u3} β _inst_2)) i (SMul.smul.{u2, u3} α β (SMulZeroClass.toHasSmul.{u2, u3} α β (AddZeroClass.toHasZero.{u3} β (AddMonoid.toAddZeroClass.{u3} β _inst_2)) (DistribSMul.toSmulZeroClass.{u2, u3} α β (AddMonoid.toAddZeroClass.{u3} β _inst_2) (DistribMulAction.toDistribSMul.{u2, u3} α β _inst_1 _inst_2 _inst_3))) r x)) (SMul.smul.{u2, max u1 u3} α (I -> β) (Pi.instSMul.{u1, u3, u2} I α (fun (i : I) => β) (fun (i : I) => SMulZeroClass.toHasSmul.{u2, u3} α β (AddZeroClass.toHasZero.{u3} β (AddMonoid.toAddZeroClass.{u3} β _inst_2)) (DistribSMul.toSmulZeroClass.{u2, u3} α β (AddMonoid.toAddZeroClass.{u3} β _inst_2) (DistribMulAction.toDistribSMul.{u2, u3} α β _inst_1 _inst_2 _inst_3)))) r (Pi.single.{u1, u3} I (fun (i : I) => β) (fun (a : I) (b : I) => _inst_4 a b) (fun (i : I) => AddZeroClass.toHasZero.{u3} β (AddMonoid.toAddZeroClass.{u3} β _inst_2)) i x))\nbut is expected to have type\n forall {I : Type.{u3}} {α : Type.{u2}} {β : Type.{u1}} [_inst_1 : Monoid.{u2} α] [_inst_2 : AddMonoid.{u1} β] [_inst_3 : DistribMulAction.{u2, u1} α β _inst_1 _inst_2] [_inst_4 : DecidableEq.{succ u3} I] (i : I) (r : α) (x : β), Eq.{max (succ u3) (succ u1)} (I -> β) (Pi.single.{u3, u1} I (fun (i : I) => β) (fun (a : I) (b : I) => _inst_4 a b) (fun (i : I) => AddMonoid.toZero.{u1} ((fun (x._@.Mathlib.GroupTheory.GroupAction.Pi._hyg.1984 : I) => β) i) _inst_2) i (HSMul.hSMul.{u2, u1, u1} α β β (instHSMul.{u2, u1} α β (SMulZeroClass.toSMul.{u2, u1} α β (AddMonoid.toZero.{u1} β _inst_2) (DistribSMul.toSMulZeroClass.{u2, u1} α β (AddMonoid.toAddZeroClass.{u1} β _inst_2) (DistribMulAction.toDistribSMul.{u2, u1} α β _inst_1 _inst_2 _inst_3)))) r x)) (HSMul.hSMul.{u2, max u1 u3, max u3 u1} α (forall (j : I), (fun (x._@.Mathlib.GroupTheory.GroupAction.Pi._hyg.2001 : I) => β) j) (forall (i : I), (fun (x._@.Mathlib.GroupTheory.GroupAction.Pi._hyg.2001 : I) => β) i) (instHSMul.{u2, max u3 u1} α (forall (j : I), (fun (x._@.Mathlib.GroupTheory.GroupAction.Pi._hyg.2001 : I) => β) j) (Pi.instSMul.{u3, u1, u2} I α (fun (j : I) => (fun (x._@.Mathlib.GroupTheory.GroupAction.Pi._hyg.2001 : I) => β) j) (fun (i : I) => SMulZeroClass.toSMul.{u2, u1} α ((fun (x._@.Mathlib.GroupTheory.GroupAction.Pi._hyg.2001 : I) => β) i) (AddMonoid.toZero.{u1} ((fun (x._@.Mathlib.GroupTheory.GroupAction.Pi._hyg.2001 : I) => β) i) _inst_2) (DistribSMul.toSMulZeroClass.{u2, u1} α ((fun (x._@.Mathlib.GroupTheory.GroupAction.Pi._hyg.2001 : I) => β) i) (AddMonoid.toAddZeroClass.{u1} ((fun (x._@.Mathlib.GroupTheory.GroupAction.Pi._hyg.2001 : I) => β) i) _inst_2) (DistribMulAction.toDistribSMul.{u2, u1} α ((fun (x._@.Mathlib.GroupTheory.GroupAction.Pi._hyg.2001 : I) => β) i) _inst_1 _inst_2 _inst_3))))) r (Pi.single.{u3, u1} I (fun (i : I) => β) (fun (a : I) (b : I) => _inst_4 a b) (fun (i : I) => AddMonoid.toZero.{u1} ((fun (x._@.Mathlib.GroupTheory.GroupAction.Pi._hyg.2001 : I) => β) i) _inst_2) i x))\nCase conversion may be inaccurate. Consider using '#align pi.single_smul' Pi.single_smul'ₓ'. -/\n/-- A version of `pi.single_smul` for non-dependent functions. It is useful in cases Lean fails\nto apply `pi.single_smul`. -/\ntheorem single_smul' {α β} [Monoid α] [AddMonoid β] [DistribMulAction α β] [DecidableEq I] (i : I)\n (r : α) (x : β) : single i (r • x) = r • single i x :=\n single_smul i r x\n#align pi.single_smul' Pi.single_smul'\n\n/- warning: pi.single_smul₀ -> Pi.single_smul₀ is a dubious translation:\nlean 3 declaration is\n forall {I : Type.{u1}} {f : I -> Type.{u2}} {g : I -> Type.{u3}} [_inst_1 : forall (i : I), MonoidWithZero.{u2} (f i)] [_inst_2 : forall (i : I), AddMonoid.{u3} (g i)] [_inst_3 : forall (i : I), DistribMulAction.{u2, u3} (f i) (g i) (MonoidWithZero.toMonoid.{u2} (f i) (_inst_1 i)) (_inst_2 i)] [_inst_4 : DecidableEq.{succ u1} I] (i : I) (r : f i) (x : g i), Eq.{max (succ u1) (succ u3)} (forall (i : I), g i) (Pi.single.{u1, u3} I (fun (i : I) => g i) (fun (a : I) (b : I) => _inst_4 a b) (fun (i : I) => AddZeroClass.toHasZero.{u3} (g i) (AddMonoid.toAddZeroClass.{u3} (g i) (_inst_2 i))) i (SMul.smul.{u2, u3} (f i) (g i) (SMulZeroClass.toHasSmul.{u2, u3} (f i) (g i) (AddZeroClass.toHasZero.{u3} (g i) (AddMonoid.toAddZeroClass.{u3} (g i) (_inst_2 i))) (DistribSMul.toSmulZeroClass.{u2, u3} (f i) (g i) (AddMonoid.toAddZeroClass.{u3} (g i) (_inst_2 i)) (DistribMulAction.toDistribSMul.{u2, u3} (f i) (g i) (MonoidWithZero.toMonoid.{u2} (f i) (_inst_1 i)) (_inst_2 i) (_inst_3 i)))) r x)) (SMul.smul.{max u1 u2, max u1 u3} (forall (i : I), f i) (forall (i : I), g i) (Pi.smul'.{u1, u2, u3} I (fun (i : I) => f i) (fun (i : I) => g i) (fun (i : I) => SMulZeroClass.toHasSmul.{u2, u3} (f i) (g i) (AddZeroClass.toHasZero.{u3} (g i) (AddMonoid.toAddZeroClass.{u3} (g i) (_inst_2 i))) (DistribSMul.toSmulZeroClass.{u2, u3} (f i) (g i) (AddMonoid.toAddZeroClass.{u3} (g i) (_inst_2 i)) (DistribMulAction.toDistribSMul.{u2, u3} (f i) (g i) (MonoidWithZero.toMonoid.{u2} (f i) (_inst_1 i)) (_inst_2 i) (_inst_3 i))))) (Pi.single.{u1, u2} I (fun (i : I) => f i) (fun (a : I) (b : I) => _inst_4 a b) (fun (i : I) => MulZeroClass.toHasZero.{u2} (f i) (MulZeroOneClass.toMulZeroClass.{u2} (f i) (MonoidWithZero.toMulZeroOneClass.{u2} (f i) (_inst_1 i)))) i r) (Pi.single.{u1, u3} I (fun (i : I) => g i) (fun (a : I) (b : I) => _inst_4 a b) (fun (i : I) => AddZeroClass.toHasZero.{u3} (g i) (AddMonoid.toAddZeroClass.{u3} (g i) (_inst_2 i))) i x))\nbut is expected to have type\n forall {I : Type.{u2}} {f : I -> Type.{u3}} {g : I -> Type.{u1}} [_inst_1 : forall (i : I), MonoidWithZero.{u3} (f i)] [_inst_2 : forall (i : I), AddMonoid.{u1} (g i)] [_inst_3 : forall (i : I), DistribMulAction.{u3, u1} (f i) (g i) (MonoidWithZero.toMonoid.{u3} (f i) (_inst_1 i)) (_inst_2 i)] [_inst_4 : DecidableEq.{succ u2} I] (i : I) (r : f i) (x : g i), Eq.{max (succ u2) (succ u1)} (forall (i : I), g i) (Pi.single.{u2, u1} I g (fun (a : I) (b : I) => _inst_4 a b) (fun (i : I) => AddMonoid.toZero.{u1} (g i) (_inst_2 i)) i (HSMul.hSMul.{u3, u1, u1} (f i) (g i) (g i) (instHSMul.{u3, u1} (f i) (g i) (SMulZeroClass.toSMul.{u3, u1} (f i) (g i) (AddMonoid.toZero.{u1} (g i) (_inst_2 i)) (DistribSMul.toSMulZeroClass.{u3, u1} (f i) (g i) (AddMonoid.toAddZeroClass.{u1} (g i) (_inst_2 i)) (DistribMulAction.toDistribSMul.{u3, u1} (f i) (g i) (MonoidWithZero.toMonoid.{u3} (f i) (_inst_1 i)) (_inst_2 i) (_inst_3 i))))) r x)) (HSMul.hSMul.{max u3 u2, max u1 u2, max u2 u1} (forall (j : I), f j) (forall (i : I), g i) (forall (i : I), g i) (instHSMul.{max u2 u3, max u2 u1} (forall (j : I), f j) (forall (j : I), g j) (Pi.smul'.{u2, u3, u1} I (fun (j : I) => f j) (fun (j : I) => g j) (fun (i : I) => SMulZeroClass.toSMul.{u3, u1} (f i) (g i) (AddMonoid.toZero.{u1} (g i) (_inst_2 i)) (DistribSMul.toSMulZeroClass.{u3, u1} (f i) (g i) (AddMonoid.toAddZeroClass.{u1} (g i) (_inst_2 i)) (DistribMulAction.toDistribSMul.{u3, u1} (f i) (g i) (MonoidWithZero.toMonoid.{u3} (f i) (_inst_1 i)) (_inst_2 i) (_inst_3 i)))))) (Pi.single.{u2, u3} I f (fun (a : I) (b : I) => _inst_4 a b) (fun (i : I) => MonoidWithZero.toZero.{u3} (f i) (_inst_1 i)) i r) (Pi.single.{u2, u1} I g (fun (a : I) (b : I) => _inst_4 a b) (fun (i : I) => AddMonoid.toZero.{u1} (g i) (_inst_2 i)) i x))\nCase conversion may be inaccurate. Consider using '#align pi.single_smul₀ Pi.single_smul₀ₓ'. -/\ntheorem single_smul₀ {g : I → Type _} [∀ i, MonoidWithZero (f i)] [∀ i, AddMonoid (g i)]\n [∀ i, DistribMulAction (f i) (g i)] [DecidableEq I] (i : I) (r : f i) (x : g i) :\n single i (r • x) = single i r • single i x :=\n single_op₂ (fun i : I => ((· • ·) : f i → g i → g i)) (fun j => smul_zero _) _ _ _\n#align pi.single_smul₀ Pi.single_smul₀\n\n#print Pi.mulDistribMulAction /-\ninstance mulDistribMulAction (α) {m : Monoid α} {n : ∀ i, Monoid <| f i}\n [∀ i, MulDistribMulAction α <| f i] :\n @MulDistribMulAction α (∀ i : I, f i) m (@Pi.monoid I f n) :=\n { Pi.mulAction _ with\n smul_one := fun c => funext fun i => smul_one _\n smul_mul := fun c f g => funext fun i => smul_mul' _ _ _ }\n#align pi.mul_distrib_mul_action Pi.mulDistribMulAction\n-/\n\n#print Pi.mulDistribMulAction' /-\ninstance mulDistribMulAction' {g : I → Type _} {m : ∀ i, Monoid (f i)} {n : ∀ i, Monoid <| g i}\n [∀ i, MulDistribMulAction (f i) (g i)] :\n @MulDistribMulAction (∀ i, f i) (∀ i : I, g i) (@Pi.monoid I f m) (@Pi.monoid I g n)\n where\n smul_mul := by\n intros\n ext x\n apply smul_mul'\n smul_one := by\n intros\n ext x\n apply smul_one\n#align pi.mul_distrib_mul_action' Pi.mulDistribMulAction'\n-/\n\nend Pi\n\nnamespace Function\n\n#print Function.hasSMul /-\n/-- Non-dependent version of `pi.has_smul`. Lean gets confused by the dependent instance if this\nis not present. -/\n@[to_additive\n \"Non-dependent version of `pi.has_vadd`. Lean gets confused by the dependent instance\\nif this is not present.\"]\ninstance hasSMul {ι R M : Type _} [SMul R M] : SMul R (ι → M) :=\n Pi.instSMul\n#align function.has_smul Function.hasSMul\n#align function.has_vadd Function.hasVAdd\n-/\n\n#print Function.smulCommClass /-\n/-- Non-dependent version of `pi.smul_comm_class`. Lean gets confused by the dependent instance if\nthis is not present. -/\n@[to_additive\n \"Non-dependent version of `pi.vadd_comm_class`. Lean gets confused by the dependent\\ninstance if this is not present.\"]\ninstance smulCommClass {ι α β M : Type _} [SMul α M] [SMul β M] [SMulCommClass α β M] :\n SMulCommClass α β (ι → M) :=\n Pi.smulCommClass\n#align function.smul_comm_class Function.smulCommClass\n#align function.vadd_comm_class Function.vaddCommClass\n-/\n\n/- warning: function.update_smul -> Function.update_smul is a dubious translation:\nlean 3 declaration is\n forall {I : Type.{u1}} {f : I -> Type.{u2}} {α : Type.{u3}} [_inst_1 : forall (i : I), SMul.{u3, u2} α (f i)] [_inst_2 : DecidableEq.{succ u1} I] (c : α) (f₁ : forall (i : I), f i) (i : I) (x₁ : f i), Eq.{max (succ u1) (succ u2)} (forall (a : I), f a) (Function.update.{succ u1, succ u2} I (fun (i : I) => f i) (fun (a : I) (b : I) => _inst_2 a b) (SMul.smul.{u3, max u1 u2} α (forall (a : I), f a) (Pi.instSMul.{u1, u2, u3} I α (fun (a : I) => f a) (fun (i : I) => _inst_1 i)) c f₁) i (SMul.smul.{u3, u2} α (f i) (_inst_1 i) c x₁)) (SMul.smul.{u3, max u1 u2} α (forall (a : I), f a) (Pi.instSMul.{u1, u2, u3} I α (fun (a : I) => f a) (fun (i : I) => _inst_1 i)) c (Function.update.{succ u1, succ u2} I (fun (a : I) => f a) (fun (a : I) (b : I) => _inst_2 a b) f₁ i x₁))\nbut is expected to have type\n forall {I : Type.{u2}} {f : I -> Type.{u3}} {α : Type.{u1}} [_inst_1 : forall (i : I), SMul.{u1, u3} α (f i)] [_inst_2 : DecidableEq.{succ u2} I] (c : α) (f₁ : forall (i : I), f i) (i : I) (x₁ : f i), Eq.{max (succ u2) (succ u3)} (forall (a : I), f a) (Function.update.{succ u2, succ u3} I (fun (i : I) => f i) (fun (a : I) (b : I) => _inst_2 a b) (HSMul.hSMul.{u1, max u2 u3, max u2 u3} α (forall (i : I), f i) (forall (a : I), f a) (instHSMul.{u1, max u2 u3} α (forall (i : I), f i) (Pi.instSMul.{u2, u3, u1} I α (fun (i : I) => f i) (fun (i : I) => _inst_1 i))) c f₁) i (HSMul.hSMul.{u1, u3, u3} α (f i) (f i) (instHSMul.{u1, u3} α (f i) (_inst_1 i)) c x₁)) (HSMul.hSMul.{u1, max u2 u3, max u2 u3} α (forall (a : I), f a) (forall (a : I), f a) (instHSMul.{u1, max u2 u3} α (forall (a : I), f a) (Pi.instSMul.{u2, u3, u1} I α (fun (a : I) => f a) (fun (i : I) => _inst_1 i))) c (Function.update.{succ u2, succ u3} I (fun (a : I) => f a) (fun (a : I) (b : I) => _inst_2 a b) f₁ i x₁))\nCase conversion may be inaccurate. Consider using '#align function.update_smul Function.update_smulₓ'. -/\n@[to_additive]\ntheorem update_smul {α : Type _} [∀ i, SMul α (f i)] [DecidableEq I] (c : α) (f₁ : ∀ i, f i) (i : I)\n (x₁ : f i) : update (c • f₁) i (c • x₁) = c • update f₁ i x₁ :=\n funext fun j => (apply_update (fun i => (· • ·) c) f₁ i x₁ j).symm\n#align function.update_smul Function.update_smul\n#align function.update_vadd Function.update_vadd\n\nend Function\n\nnamespace Set\n\n/- warning: set.piecewise_smul -> Set.piecewise_smul is a dubious translation:\nlean 3 declaration is\n forall {I : Type.{u1}} {f : I -> Type.{u2}} {α : Type.{u3}} [_inst_1 : forall (i : I), SMul.{u3, u2} α (f i)] (s : Set.{u1} I) [_inst_2 : forall (i : I), Decidable (Membership.Mem.{u1, u1} I (Set.{u1} I) (Set.hasMem.{u1} I) i s)] (c : α) (f₁ : forall (i : I), f i) (g₁ : forall (i : I), f i), Eq.{max (succ u1) (succ u2)} (forall (i : I), f i) (Set.piecewise.{u1, succ u2} I (fun (i : I) => f i) s (SMul.smul.{u3, max u1 u2} α (forall (i : I), f i) (Pi.instSMul.{u1, u2, u3} I α (fun (i : I) => f i) (fun (i : I) => _inst_1 i)) c f₁) (SMul.smul.{u3, max u1 u2} α (forall (i : I), f i) (Pi.instSMul.{u1, u2, u3} I α (fun (i : I) => f i) (fun (i : I) => _inst_1 i)) c g₁) (fun (j : I) => _inst_2 j)) (SMul.smul.{u3, max u1 u2} α (forall (i : I), f i) (Pi.instSMul.{u1, u2, u3} I α (fun (i : I) => f i) (fun (i : I) => _inst_1 i)) c (Set.piecewise.{u1, succ u2} I (fun (i : I) => f i) s f₁ g₁ (fun (j : I) => _inst_2 j)))\nbut is expected to have type\n forall {I : Type.{u2}} {f : I -> Type.{u3}} {α : Type.{u1}} [_inst_1 : forall (i : I), SMul.{u1, u3} α (f i)] (s : Set.{u2} I) [_inst_2 : forall (i : I), Decidable (Membership.mem.{u2, u2} I (Set.{u2} I) (Set.instMembershipSet.{u2} I) i s)] (c : α) (f₁ : forall (i : I), f i) (g₁ : forall (i : I), f i), Eq.{max (succ u2) (succ u3)} (forall (i : I), f i) (Set.piecewise.{u2, succ u3} I (fun (i : I) => f i) s (HSMul.hSMul.{u1, max u2 u3, max u2 u3} α (forall (i : I), f i) (forall (i : I), f i) (instHSMul.{u1, max u2 u3} α (forall (i : I), f i) (Pi.instSMul.{u2, u3, u1} I α (fun (i : I) => f i) (fun (i : I) => _inst_1 i))) c f₁) (HSMul.hSMul.{u1, max u2 u3, max u2 u3} α (forall (i : I), f i) (forall (i : I), f i) (instHSMul.{u1, max u2 u3} α (forall (i : I), f i) (Pi.instSMul.{u2, u3, u1} I α (fun (i : I) => f i) (fun (i : I) => _inst_1 i))) c g₁) (fun (j : I) => _inst_2 j)) (HSMul.hSMul.{u1, max u2 u3, max u2 u3} α (forall (i : I), f i) (forall (i : I), f i) (instHSMul.{u1, max u2 u3} α (forall (i : I), f i) (Pi.instSMul.{u2, u3, u1} I α (fun (i : I) => f i) (fun (i : I) => _inst_1 i))) c (Set.piecewise.{u2, succ u3} I (fun (i : I) => f i) s f₁ g₁ (fun (j : I) => _inst_2 j)))\nCase conversion may be inaccurate. Consider using '#align set.piecewise_smul Set.piecewise_smulₓ'. -/\n@[to_additive]\ntheorem piecewise_smul {α : Type _} [∀ i, SMul α (f i)] (s : Set I) [∀ i, Decidable (i ∈ s)] (c : α)\n (f₁ g₁ : ∀ i, f i) : s.piecewise (c • f₁) (c • g₁) = c • s.piecewise f₁ g₁ :=\n s.piecewise_op _ _ fun _ => (· • ·) c\n#align set.piecewise_smul Set.piecewise_smul\n#align set.piecewise_vadd Set.piecewise_vadd\n\nend Set\n\nsection Extend\n\n/- warning: function.extend_smul -> Function.extend_smul is a dubious translation:\nlean 3 declaration is\n forall {R : Type.{u1}} {α : Type.{u2}} {β : Type.{u3}} {γ : Type.{u4}} [_inst_1 : SMul.{u1, u4} R γ] (r : R) (f : α -> β) (g : α -> γ) (e : β -> γ), Eq.{max (succ u3) (succ u4)} (β -> γ) (Function.extend.{succ u2, succ u3, succ u4} α β γ f (SMul.smul.{u1, max u2 u4} R (α -> γ) (Function.hasSMul.{u2, u1, u4} α R γ _inst_1) r g) (SMul.smul.{u1, max u3 u4} R (β -> γ) (Function.hasSMul.{u3, u1, u4} β R γ _inst_1) r e)) (SMul.smul.{u1, max u3 u4} R (β -> γ) (Function.hasSMul.{u3, u1, u4} β R γ _inst_1) r (Function.extend.{succ u2, succ u3, succ u4} α β γ f g e))\nbut is expected to have type\n forall {R : Type.{u4}} {α : Type.{u3}} {β : Type.{u2}} {γ : Type.{u1}} [_inst_1 : SMul.{u4, u1} R γ] (r : R) (f : α -> β) (g : α -> γ) (e : β -> γ), Eq.{max (succ u2) (succ u1)} (β -> γ) (Function.extend.{succ u3, succ u2, succ u1} α β γ f (HSMul.hSMul.{u4, max u3 u1, max u3 u1} R (α -> γ) (α -> γ) (instHSMul.{u4, max u3 u1} R (α -> γ) (Pi.instSMul.{u3, u1, u4} α R (fun (a._@.Mathlib.GroupTheory.GroupAction.Pi._hyg.2657 : α) => γ) (fun (i : α) => _inst_1))) r g) (HSMul.hSMul.{u4, max u2 u1, max u2 u1} R (β -> γ) (β -> γ) (instHSMul.{u4, max u2 u1} R (β -> γ) (Pi.instSMul.{u2, u1, u4} β R (fun (a._@.Mathlib.GroupTheory.GroupAction.Pi._hyg.2660 : β) => γ) (fun (i : β) => _inst_1))) r e)) (HSMul.hSMul.{u4, max u2 u1, max u2 u1} R (β -> γ) (β -> γ) (instHSMul.{u4, max u2 u1} R (β -> γ) (Pi.instSMul.{u2, u1, u4} β R (fun (a._@.Mathlib.Logic.Function.Basic._hyg.7460 : β) => γ) (fun (i : β) => _inst_1))) r (Function.extend.{succ u3, succ u2, succ u1} α β γ f g e))\nCase conversion may be inaccurate. Consider using '#align function.extend_smul Function.extend_smulₓ'. -/\n@[to_additive]\ntheorem Function.extend_smul {R α β γ : Type _} [SMul R γ] (r : R) (f : α → β) (g : α → γ)\n (e : β → γ) : Function.extend f (r • g) (r • e) = r • Function.extend f g e :=\n funext fun _ => by convert(apply_dite ((· • ·) r) _ _ _).symm\n#align function.extend_smul Function.extend_smul\n#align function.extend_vadd Function.extend_vadd\n\nend Extend\n\n", "meta": {"author": "leanprover-community", "repo": "mathlib3port", "sha": "62505aa236c58c8559783b16d33e30df3daa54f4", "save_path": "github-repos/lean/leanprover-community-mathlib3port", "path": "github-repos/lean/leanprover-community-mathlib3port/mathlib3port-62505aa236c58c8559783b16d33e30df3daa54f4/Mathbin/GroupTheory/GroupAction/Pi.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43398147944527615, "lm_q2_score": 0.05582314231270587, "lm_q1q2_score": 0.024226209888152286}} {"text": "import tactic.interactive\n\nlemma a {α} [nonempty α] : ∃ a : α, a = a :=\nby inhabit α; use default; refl\n\nnoncomputable def b {α} [nonempty α] : α :=\nby inhabit α; apply default\n\nlemma c {α} [nonempty α] : ∀ n : ℕ, ∃ b : α, n = n :=\nby inhabit α; intro; use default; refl\n\nnoncomputable def d {α} [nonempty α] : ∀ n : ℕ, α :=\nby inhabit α; intro; apply default\n", "meta": {"author": "leanprover-community", "repo": "mathlib", "sha": "5e526d18cea33550268dcbbddcb822d5cde40654", "save_path": "github-repos/lean/leanprover-community-mathlib", "path": "github-repos/lean/leanprover-community-mathlib/mathlib-5e526d18cea33550268dcbbddcb822d5cde40654/test/inhabit.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.37022537869825406, "lm_q2_score": 0.06465348880678597, "lm_q1q2_score": 0.023936362377655663}} {"text": "/-\nCopyright (c) 2018 Mario Carneiro. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Mario Carneiro, Minchao Wu\n-/\nimport tactic.core\n/-!\n# `#explode` command\n\nDisplays a proof term in a line by line format somewhat akin to a Fitch style\nproof or the Metamath proof style.\n-/\n\nopen expr tactic\n\nnamespace tactic\nnamespace explode\n\n@[derive inhabited]\ninductive status : Type | reg | intro | lam | sintro\n\n/--\nA type to distinguish introduction or elimination rules represented as\nstrings from theorems referred to by their names.\n-/\nmeta inductive thm : Type\n| expr (e : expr)\n| name (n : name)\n| string (s : string)\n\n/--\nTurn a thm into a string.\n-/\nmeta def thm.to_string : thm → string\n| (thm.expr e) := e.to_string\n| (thm.name n) := n.to_string\n| (thm.string s) := s\n\nmeta structure entry : Type :=\n(expr : expr)\n(line : nat)\n(depth : nat)\n(status : status)\n(thm : thm)\n(deps : list nat)\n\nmeta def pad_right (l : list string) : list string :=\nlet n := l.foldl (λ r (s:string), max r s.length) 0 in\nl.map $ λ s, nat.iterate (λ s, s.push ' ') (n - s.length) s\n\n@[derive inhabited]\nmeta structure entries : Type := mk' ::\n(s : expr_map entry)\n(l : list entry)\n\nmeta def entries.find (es : entries) (e : expr) : option entry := es.s.find e\nmeta def entries.size (es : entries) : ℕ := es.s.size\n\nmeta def entries.add : entries → entry → entries\n| es@⟨s, l⟩ e := if s.contains e.expr then es else ⟨s.insert e.expr e, e :: l⟩\n\nmeta def entries.head (es : entries) : option entry := es.l.head'\n\nmeta def format_aux : list string → list string → list string → list entry → tactic format\n| (line :: lines) (dep :: deps) (thm :: thms) (en :: es) := do\n fmt ← do {\n let margin := string.join (list.repeat \" │\" en.depth),\n let margin := match en.status with\n | status.sintro := \" ├\" ++ margin\n | status.intro := \" │\" ++ margin ++ \" ┌\"\n | status.reg := \" │\" ++ margin ++ \"\"\n | status.lam := \" │\" ++ margin ++ \"\"\n end,\n p ← infer_type en.expr >>= pp,\n let lhs := line ++ \"│\" ++ dep ++ \"│ \" ++ thm ++ margin ++ \" \",\n return $ format.of_string lhs ++ (p.nest lhs.length).group ++ format.line },\n (++ fmt) <$> format_aux lines deps thms es\n| _ _ _ _ := return format.nil\n\nmeta instance : has_to_tactic_format entries :=\n⟨λ es : entries,\n let lines := pad_right $ es.l.map (λ en, to_string en.line),\n deps := pad_right $ es.l.map (λ en, string.intercalate \",\" (en.deps.map to_string)),\n thms := pad_right $ es.l.map (λ en, (entry.thm en).to_string) in\n format_aux lines deps thms es.l⟩\n\nmeta def append_dep (filter : expr → tactic unit)\n (es : entries) (e : expr) (deps : list nat) : tactic (list nat) :=\ndo { ei ← es.find e,\n filter ei.expr,\n return (ei.line :: deps) }\n<|> return deps\n\nmeta def may_be_proof (e : expr) : tactic bool :=\ndo expr.sort u ← infer_type e >>= infer_type,\n return $ bnot u.nonzero\n\nend explode\nopen explode\n\nmeta mutual def explode.core, explode.args (filter : expr → tactic unit)\nwith explode.core : expr → bool → nat → entries → tactic entries\n| e@(lam n bi d b) si depth es := do\n m ← mk_fresh_name,\n let l := local_const m n bi d,\n let b' := instantiate_var b l,\n if si then\n let en : entry := ⟨l, es.size, depth, status.sintro, thm.name n, []⟩ in do\n es' ← explode.core b' si depth (es.add en),\n return $ es'.add ⟨e, es'.size, depth, status.lam, thm.string \"∀I\", [es.size, es'.size - 1]⟩\n else do\n let en : entry := ⟨l, es.size, depth, status.intro, thm.name n, []⟩,\n es' ← explode.core b' si (depth + 1) (es.add en),\n -- in case of a \"have\" clause, the b' here has an annotation\n deps' ← explode.append_dep filter es' b'.erase_annotations [],\n deps' ← explode.append_dep filter es' l deps',\n return $ es'.add ⟨e, es'.size, depth, status.lam, thm.string \"∀I\", deps'⟩\n| e@(elet n t a b) si depth es := explode.core (reduce_lets e) si depth es\n| e@(macro n l) si depth es := explode.core l.head si depth es\n| e si depth es := filter e >>\n match get_app_fn_args e with\n | (nm@(const n _), args) :=\n explode.args e args depth es (thm.expr nm) []\n | (fn, []) := do\n let en : entry := ⟨fn, es.size, depth, status.reg, thm.expr fn, []⟩,\n return (es.add en)\n | (fn, args) := do\n es' ← explode.core fn ff depth es,\n -- in case of a \"have\" clause, the fn here has an annotation\n deps ← explode.append_dep filter es' fn.erase_annotations [],\n explode.args e args depth es' (thm.string \"∀E\") deps\n end\nwith explode.args : expr → list expr → nat → entries → thm → list nat → tactic entries\n| e (arg :: args) depth es thm deps := do\n es' ← explode.core arg ff depth es <|> return es,\n deps' ← explode.append_dep filter es' arg deps,\n explode.args e args depth es' thm deps'\n| e [] depth es thm deps :=\n return (es.add ⟨e, es.size, depth, status.reg, thm, deps.reverse⟩)\n\nmeta def explode_expr (e : expr) (hide_non_prop := tt) : tactic entries :=\nlet filter := if hide_non_prop then λ e, may_be_proof e >>= guardb else λ _, skip in\ntactic.explode.core filter e tt 0 (default _)\n\nmeta def explode (n : name) : tactic unit :=\ndo const n _ ← resolve_name n | fail \"cannot resolve name\",\n d ← get_decl n,\n v ← match d with\n | (declaration.defn _ _ _ v _ _) := return v\n | (declaration.thm _ _ _ v) := return v.get\n | _ := fail \"not a definition\"\n end,\n t ← pp d.type,\n explode_expr v <* trace (to_fmt n ++ \" : \" ++ t) >>= trace\n\nopen interactive lean lean.parser interaction_monad.result\n\n/--\n`#explode decl_name` displays a proof term in a line-by-line format somewhat akin to a Fitch-style\nproof or the Metamath proof style.\n`#explode_widget decl_name` renders a widget that displays an `#explode` proof.\n\n`#explode iff_true_intro` produces\n\n```lean\niff_true_intro : ∀ {a : Prop}, a → (a ↔ true)\n0│ │ a ├ Prop\n1│ │ h ├ a\n2│ │ hl │ ┌ a\n3│ │ trivial │ │ true\n4│2,3│ ∀I │ a → true\n5│ │ hr │ ┌ true\n6│5,1│ ∀I │ true → a\n7│4,6│ iff.intro │ a ↔ true\n8│1,7│ ∀I │ a → (a ↔ true)\n9│0,8│ ∀I │ ∀ {a : Prop}, a → (a ↔ true)\n```\n\nIn more detail:\n\nThe output of `#explode` is a Fitch-style proof in a four-column diagram modeled after Metamath\nproof displays like [this](http://us.metamath.org/mpeuni/ru.html). The headers of the columns are\n\"Step\", \"Hyp\", \"Ref\", \"Type\" (or \"Expression\" in the case of Metamath):\n* Step: An increasing sequence of numbers to number each step in the proof, used in the Hyp field.\n* Hyp: The direct children of the current step. Most theorems are implications like `A -> B -> C`,\n and so on the step proving `C` the Hyp field will refer to the steps that prove `A` and `B`.\n* Ref: The name of the theorem being applied. This is well-defined in Metamath, but in Lean there\n are some special steps that may have long names because the structure of proof terms doesn't\n exactly match this mold.\n * If the theorem is `foo (x y : Z) : A x -> B y -> C x y`:\n * the Ref field will contain `foo`,\n * `x` and `y` will be suppressed, because term construction is not interesting, and\n * the Hyp field will reference steps proving `A x` and `B y`. This corresponds to a proof term\n like `@foo x y pA pB` where `pA` and `pB` are subproofs.\n * If the head of the proof term is a local constant or lambda, then in this case the Ref will\n say `∀E` for forall-elimination. This happens when you have for example `h : A -> B` and\n `ha : A` and prove `b` by `h ha`; we reinterpret this as if it said `∀E h ha` where `∀E` is\n (n-ary) modus ponens.\n * If the proof term is a lambda, we will also use `∀I` for forall-introduction, referencing the\n body of the lambda. The indentation level will increase, and a bracket will surround the proof\n of the body of the lambda, starting at a proof step labeled with the name of the lambda variable\n and its type, and ending with the `∀I` step. Metamath doesn't have steps like this, but the\n style is based on Fitch proofs in first-order logic.\n* Type: This contains the type of the proof term, the theorem being proven at the current step.\n This proof layout differs from `#print` in using lots of intermediate step displays so that you\n can follow along and don't have to see term construction steps because they are implicitly in the\n intermediate step displays.\n\nAlso, it is common for a Lean theorem to begin with a sequence of lambdas introducing local\nconstants of the theorem. In order to minimize the indentation level, the `∀I` steps at the end of\nthe proof will be introduced in a group and the indentation will stay fixed. (The indentation\nbrackets are only needed in order to delimit the scope of assumptions, and these assumptions\nhave global scope anyway so detailed tracking is not necessary.)\n-/\n@[user_command]\nmeta def explode_cmd (_ : parse $ tk \"#explode\") : parser unit :=\ndo n ← ident,\n explode n\n.\n\nadd_tactic_doc\n{ name := \"#explode / #explode_widget\",\n category := doc_category.cmd,\n decl_names := [`tactic.explode_cmd, `tactic.explode_widget_cmd],\n inherit_description_from := `tactic.explode_cmd,\n tags := [\"proof display\", \"widgets\"] }\n\nend tactic\n", "meta": {"author": "JLimperg", "repo": "aesop3", "sha": "a4a116f650cc7403428e72bd2e2c4cda300fe03f", "save_path": "github-repos/lean/JLimperg-aesop3", "path": "github-repos/lean/JLimperg-aesop3/aesop3-a4a116f650cc7403428e72bd2e2c4cda300fe03f/src/tactic/explode.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35936413143782797, "lm_q2_score": 0.06656918387791788, "lm_q1q2_score": 0.02392257694481302}} {"text": "/-\nCopyright (c) 2016 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Leonardo de Moura\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.meta.tactic\nimport Mathlib.Lean3Lib.init.meta.format\nimport Mathlib.Lean3Lib.init.function\n\nuniverses l \n\nnamespace Mathlib\n\n/-- This is a kind attached to an argument of a congruence lemma that tells the simplifier how to fill it in.\n- `fixed`: It is a parameter for the congruence lemma, the parameter occurs in the left and right hand sides.\n For example the α in the congruence generated from `f: Π {α : Type} α → α`.\n- `fixed_no_param`: It is not a parameter for the congruence lemma, the lemma was specialized for this parameter.\n This only happens if the parameter is a subsingleton/proposition, and other parameters depend on it.\n- `eq`: The lemma contains three parameters for this kind of argument `a_i`, `b_i` and `(eq_i : a_i = b_i)`.\n `a_i` and `b_i` represent the left and right hand sides, and `eq_i` is a proof for their equality.\n For example the second argument in `f: Π {α : Type}, α → α`.\n- `cast`: corresponds to arguments that are subsingletons/propositions.\n For example the `p` in the congruence generated from `f : Π (x y : ℕ) (p: x < y), ℕ`.\n- `heq` The lemma contains three parameters for this kind of argument `a_i`, `b_i` and `(eq_i : a_i == b_i)`.\n `a_i` and `b_i` represent the left and right hand sides, and eq_i is a proof for their heterogeneous equality.\n-/\ninductive congr_arg_kind where\n| fixed : congr_arg_kind\n| fixed_no_param : congr_arg_kind\n| eq : congr_arg_kind\n| cast : congr_arg_kind\n| heq : congr_arg_kind\n\nnamespace congr_arg_kind\n\n\ndef to_string : congr_arg_kind → string := sorry\n\nprotected instance has_repr : has_repr congr_arg_kind := has_repr.mk to_string\n\nend Mathlib", "meta": {"author": "AurelienSaue", "repo": "Mathlib4_auto", "sha": "590df64109b08190abe22358fabc3eae000943f2", "save_path": "github-repos/lean/AurelienSaue-Mathlib4_auto", "path": "github-repos/lean/AurelienSaue-Mathlib4_auto/Mathlib4_auto-590df64109b08190abe22358fabc3eae000943f2/Mathlib/Lean3Lib/init/meta/congr_lemma_auto.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4148988313272768, "lm_q2_score": 0.05749328364515302, "lm_q1q2_score": 0.023853896193541623}} {"text": "/-\nCopyright (c) 2022 Joël Riou. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Joël Riou\n-/\n\nimport for_mathlib.idempotents.functor_extension2\nimport category_theory.natural_isomorphism\n\nimport category_theory.functor.fully_faithful\n\nopen category_theory.category\nopen category_theory.idempotents\nopen category_theory.idempotents.karoubi\n\nnamespace category_theory\n\nnamespace idempotents\n\nvariables {C D : Type*} [category C] [category D]\n\n@[simps]\ndef whiskering_left_to_karoubi_hom_equiv\n (F G : karoubi C ⥤ D) : (F ⟶ G) ≃ (to_karoubi _ ⋙ F ⟶ to_karoubi _ ⋙ G) :=\n{ to_fun := λ φ,\n { app := λ X, φ.app ((to_karoubi C).obj X),\n naturality' := λ X Y f, by simp only [nat_trans.naturality, functor.comp_map], },\n inv_fun := λ ψ,\n { app := λ P, F.map (decomp_id_i P) ≫ (ψ.app P.X) ≫ G.map (decomp_id_p P),\n naturality' := λ P Q f, by {\n slice_lhs 1 2 { rw [← F.map_comp], },\n slice_rhs 3 4 { rw [← G.map_comp], },\n rw [decomp_id_i_naturality, decomp_id_p_naturality,\n F.map_comp, G.map_comp],\n slice_lhs 2 3 { erw ψ.naturality, },\n simp only [assoc],\n refl, }, },\n left_inv := λ φ, by { ext P, exact (nat_trans_eq φ P).symm, },\n right_inv := λ ψ, begin\n ext X,\n dsimp,\n erw [decomp_id_i_to_karoubi, decomp_id_p_to_karoubi,\n F.map_id, G.map_id, comp_id, id_comp],\n end }\n\nlemma whiskering_left_to_karoubi_hom_inv_fun_comp\n {F G H : karoubi C ⥤ D} (φ : to_karoubi _ ⋙ F ⟶ to_karoubi _ ⋙ G)\n (ψ : to_karoubi _ ⋙ G ⟶ to_karoubi _ ⋙ H) :\n (whiskering_left_to_karoubi_hom_equiv F H).inv_fun (φ ≫ ψ) =\n (whiskering_left_to_karoubi_hom_equiv F G).inv_fun φ ≫\n (whiskering_left_to_karoubi_hom_equiv G H).inv_fun ψ :=\nbegin\n ext P,\n dsimp,\n slice_rhs 3 4 { rw [← G.map_comp, ← decomp_p], },\n erw ψ.naturality P.p,\n slice_rhs 4 5 { erw [← H.map_comp], },\n simp only [assoc],\n congr,\n ext,\n simp only [decomp_id_p_f, comp_f, to_karoubi_map_f, P.idem],\nend\n\nlemma whiskering_left_to_karoubi_hom_inv_fun_id\n {F : karoubi C ⥤ D} :\n (whiskering_left_to_karoubi_hom_equiv F F).inv_fun (𝟙 _) = 𝟙 _ :=\nbegin\n ext P,\n simp only [whiskering_left_to_karoubi_hom_equiv_symm_apply_app, nat_trans.id_app, equiv.inv_fun_as_coe],\n erw [id_comp, ← F.map_comp, ← decomp_id, F.map_id],\nend\n\n@[simps]\ndef whiskering_left_to_karoubi_iso_equiv\n (F G : karoubi C ⥤ D) : (F ≅ G) ≃ (to_karoubi _ ⋙ F ≅ to_karoubi _ ⋙ G) :=\n{ to_fun := λ φ,\n { hom := (whiskering_left_to_karoubi_hom_equiv F G).to_fun φ.hom,\n inv := (whiskering_left_to_karoubi_hom_equiv G F).to_fun φ.inv, },\n inv_fun := λ ψ,\n { hom := (whiskering_left_to_karoubi_hom_equiv F G).inv_fun ψ.hom,\n inv := (whiskering_left_to_karoubi_hom_equiv G F).inv_fun ψ.inv,\n hom_inv_id' := by rw [← whiskering_left_to_karoubi_hom_inv_fun_comp, iso.hom_inv_id, whiskering_left_to_karoubi_hom_inv_fun_id],\n inv_hom_id' := by rw [← whiskering_left_to_karoubi_hom_inv_fun_comp, iso.inv_hom_id, whiskering_left_to_karoubi_hom_inv_fun_id], },\n left_inv := λ φ, by { ext P, simp only [equiv.to_fun_as_coe, equiv.symm_apply_apply,\n equiv.inv_fun_as_coe], },\n right_inv := λ ψ, by { ext X, simp only [equiv.to_fun_as_coe, equiv.apply_symm_apply,\n equiv.inv_fun_as_coe], } }\n\nlemma karoubi_universal₁_inverse_preimage (F G : karoubi C ⥤ karoubi D)\n (φ : ((karoubi_universal₁ C D).inverse).obj F ⟶ ((karoubi_universal₁ C D).inverse).obj G) :\n (karoubi_universal₁ C D).inverse.preimage φ = (whiskering_left_to_karoubi_hom_equiv F G).inv_fun φ :=\nbegin\n apply functor.map_injective (((whiskering_left C (karoubi C) (karoubi D)).obj (to_karoubi C))),\n erw functor.image_preimage,\n ext1, ext1 X,\n dsimp [decomp_id_i, decomp_id_p],\n erw [F.map_id, G.map_id, id_comp, comp_id],\nend\n\n--lemma karoubi_universal'_inverse_preimage_iso (F G : karoubi C ⥤ karoubi D)\n-- (e : ((karoubi_universal' C D).inverse).obj F ≅ ((karoubi_universal' C D).inverse).obj G) :\n-- preimage_iso e = (whiskering_left_to_karoubi_iso_equiv F G).inv_fun e :=\n--by { ext1, exact karoubi_universal'_inverse_preimage F G e.hom, }\n\nlemma whiskering_left_to_karoubi_hom_equiv_inv_fun_compat {F G : karoubi C ⥤ D}\n (ψ : to_karoubi _ ⋙ F ⟶ to_karoubi _ ⋙ G) (X : C) :\n ((whiskering_left_to_karoubi_hom_equiv _ _).inv_fun ψ).app ((to_karoubi _).obj X) = ψ.app X :=\ncongr_app ((whiskering_left_to_karoubi_hom_equiv _ _).right_inv ψ) X\n\nend idempotents\n\nend category_theory\n", "meta": {"author": "joelriou", "repo": "dold-kan", "sha": "a083fe264275774ac49ac520caf25f2ee29debb1", "save_path": "github-repos/lean/joelriou-dold-kan", "path": "github-repos/lean/joelriou-dold-kan/dold-kan-a083fe264275774ac49ac520caf25f2ee29debb1/src/for_mathlib/idempotents/nat_trans.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.480478678047907, "lm_q2_score": 0.04958902017486778, "lm_q1q2_score": 0.02382646685931146}} {"text": "/-\nCopyright (c) 2019 Simon Hudon. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthor: Simon Hudon\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.default\nimport Mathlib.tactic.monotonicity.basic\nimport Mathlib.control.traversable.default\nimport Mathlib.control.traversable.derive\nimport Mathlib.Lean3Lib.data.dlist\nimport Mathlib.PostPort\n\nuniverses u v u_1 u_2 l \n\nnamespace Mathlib\n\nnamespace tactic.interactive\n\n\n/--\n`(prefix,left,right,suffix) ← match_assoc unif l r` finds the\nlongest prefix and suffix common to `l` and `r` and\nreturns them along with the differences -/\ndef apply_rel {α : Sort u} (R : α → α → Sort v) {x : α} {y : α} (x' : α) (y' : α) (h : R x y)\n (hx : x = x') (hy : y = y') : R x' y' :=\n eq.mpr sorry (eq.mpr sorry h)\n\n/-- tactic-facing function, similar to `interactive.tactic.generalize` with the\nexception that meta variables -/\ndef list.minimum_on {α : Type u_1} {β : Type u_2} [linear_order β] (f : α → β) : List α → List α :=\n sorry\n\n/--\n- `mono` applies a monotonicity rule.\n- `mono*` applies monotonicity rules repetitively.\n- `mono with x ≤ y` or `mono with [0 ≤ x,0 ≤ y]` creates an assertion for the listed\n propositions. Those help to select the right monotonicity rule.\n- `mono left` or `mono right` is useful when proving strict orderings:\n for `x + y < w + z` could be broken down into either\n - left: `x ≤ w` and `y < z` or\n - right: `x < w` and `y ≤ z`\n- `mono using [rule1,rule2]` calls `simp [rule1,rule2]` before applying mono.\n- The general syntax is `mono '*'? ('with' hyp | 'with' [hyp1,hyp2])? ('using' [hyp1,hyp2])? mono_cfg?\n\nTo use it, first import `tactic.monotonicity`.\n\nHere is an example of mono:\n\n```lean\nexample (x y z k : ℤ)\n (h : 3 ≤ (4 : ℤ))\n (h' : z ≤ y) :\n (k + 3 + x) - y ≤ (k + 4 + x) - z :=\nbegin\n mono, -- unfold `(-)`, apply add_le_add\n { -- ⊢ k + 3 + x ≤ k + 4 + x\n mono, -- apply add_le_add, refl\n -- ⊢ k + 3 ≤ k + 4\n mono },\n { -- ⊢ -y ≤ -z\n mono /- apply neg_le_neg -/ }\nend\n```\n\nMore succinctly, we can prove the same goal as:\n\n```lean\nexample (x y z k : ℤ)\n (h : 3 ≤ (4 : ℤ))\n (h' : z ≤ y) :\n (k + 3 + x) - y ≤ (k + 4 + x) - z :=\nby mono*\n```\n\n-/\n/--\ntransforms a goal of the form `f x ≼ f y` into `x ≤ y` using lemmas\nmarked as `monotonic`.\n\nSpecial care is taken when `f` is the repeated application of an\nassociative operator and if the operator is commutative\n-/\n/-- (repeat_until_or_at_most n t u): repeat tactic `t` at most n times or until u succeeds -/\ninductive rep_arity where\n| one : rep_arity\n| exactly : ℕ → rep_arity\n| many : rep_arity\n\n/--\n\n`ac_mono` reduces the `f x ⊑ f y`, for some relation `⊑` and a\nmonotonic function `f` to `x ≺ y`.\n\n`ac_mono*` unwraps monotonic functions until it can't.\n\n`ac_mono^k`, for some literal number `k` applies monotonicity `k`\ntimes.\n\n`ac_mono h`, with `h` a hypothesis, unwraps monotonic functions and\nuses `h` to solve the remaining goal. Can be combined with `*` or `^k`:\n`ac_mono* h`\n\n`ac_mono : p` asserts `p` and uses it to discharge the goal result\nunwrapping a series of monotonic functions. Can be combined with * or\n^k: `ac_mono* : p`\n\nIn the case where `f` is an associative or commutative operator,\n`ac_mono` will consider any possible permutation of its arguments and\nuse the one the minimizes the difference between the left-hand side\nand the right-hand side.\n\nTo use it, first import `tactic.monotonicity`.\n\n`ac_mono` can be used as follows:\n\n```lean\nexample (x y z k m n : ℕ)\n (h₀ : z ≥ 0)\n (h₁ : x ≤ y) :\n (m + x + n) * z + k ≤ z * (y + n + m) + k :=\nbegin\n ac_mono,\n -- ⊢ (m + x + n) * z ≤ z * (y + n + m)\n ac_mono,\n -- ⊢ m + x + n ≤ y + n + m\n ac_mono,\nend\n```\n\nAs with `mono*`, `ac_mono*` solves the goal in one go and so does\n`ac_mono* h₁`. The latter syntax becomes especially interesting in the\nfollowing example:\n\n```lean\nexample (x y z k m n : ℕ)\n (h₀ : z ≥ 0)\n (h₁ : m + x + n ≤ y + n + m) :\n (m + x + n) * z + k ≤ z * (y + n + m) + k :=\nby ac_mono* h₁.\n```\n\nBy giving `ac_mono` the assumption `h₁`, we are asking `ac_refl` to\nstop earlier than it would normally would.\n-/\n/-\nTODO(Simon): with `ac_mono h` and `ac_mono : p` split the remaining\n gaol if the provided rule does not solve it completely.\n-/\n\nend Mathlib", "meta": {"author": "AurelienSaue", "repo": "Mathlib4_auto", "sha": "590df64109b08190abe22358fabc3eae000943f2", "save_path": "github-repos/lean/AurelienSaue-Mathlib4_auto", "path": "github-repos/lean/AurelienSaue-Mathlib4_auto/Mathlib4_auto-590df64109b08190abe22358fabc3eae000943f2/Mathlib/tactic/monotonicity/interactive_auto.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4726834766204328, "lm_q2_score": 0.05033063651478413, "lm_q1q2_score": 0.023790460248327466}} {"text": "/-\nCopyright (c) 2018 Simon Hudon. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Simon Hudon, Patrick Massot\n-/\nimport algebra.group.pi\nimport group_theory.group_action.defs\n\n/-!\n# Pi instances for multiplicative actions\n\nThis file defines instances for mul_action and related structures on Pi types.\n\n## See also\n\n* `group_theory.group_action.prod`\n* `group_theory.group_action.sigma`\n* `group_theory.group_action.sum`\n-/\n\nuniverses u v w\nvariable {I : Type u} -- The indexing type\nvariable {f : I → Type v} -- The family of types already equipped with instances\nvariables (x y : Π i, f i) (i : I)\n\nnamespace pi\n\n@[to_additive pi.has_vadd]\ninstance has_smul {α : Type*} [Π i, has_smul α $ f i] :\n has_smul α (Π i : I, f i) :=\n⟨λ s x, λ i, s • (x i)⟩\n\n@[to_additive]\nlemma smul_def {α : Type*} [Π i, has_smul α $ f i] (s : α) : s • x = λ i, s • x i := rfl\n@[simp, to_additive]\nlemma smul_apply {α : Type*} [Π i, has_smul α $ f i] (s : α) : (s • x) i = s • x i := rfl\n\n@[to_additive pi.has_vadd']\ninstance has_smul' {g : I → Type*} [Π i, has_smul (f i) (g i)] :\n has_smul (Π i, f i) (Π i : I, g i) :=\n⟨λ s x, λ i, (s i) • (x i)⟩\n\n@[simp, to_additive]\nlemma smul_apply' {g : I → Type*} [∀ i, has_smul (f i) (g i)] (s : Π i, f i) (x : Π i, g i) :\n (s • x) i = s i • x i :=\nrfl\ninstance is_scalar_tower {α β : Type*}\n [has_smul α β] [Π i, has_smul β $ f i] [Π i, has_smul α $ f i]\n [Π i, is_scalar_tower α β (f i)] : is_scalar_tower α β (Π i : I, f i) :=\n⟨λ x y z, funext $ λ i, smul_assoc x y (z i)⟩\n\ninstance is_scalar_tower' {g : I → Type*} {α : Type*}\n [Π i, has_smul α $ f i] [Π i, has_smul (f i) (g i)] [Π i, has_smul α $ g i]\n [Π i, is_scalar_tower α (f i) (g i)] : is_scalar_tower α (Π i : I, f i) (Π i : I, g i) :=\n⟨λ x y z, funext $ λ i, smul_assoc x (y i) (z i)⟩\n\ninstance is_scalar_tower'' {g : I → Type*} {h : I → Type*}\n [Π i, has_smul (f i) (g i)] [Π i, has_smul (g i) (h i)] [Π i, has_smul (f i) (h i)]\n [Π i, is_scalar_tower (f i) (g i) (h i)] : is_scalar_tower (Π i, f i) (Π i, g i) (Π i, h i) :=\n⟨λ x y z, funext $ λ i, smul_assoc (x i) (y i) (z i)⟩\n\n@[to_additive]\ninstance smul_comm_class {α β : Type*}\n [Π i, has_smul α $ f i] [Π i, has_smul β $ f i] [∀ i, smul_comm_class α β (f i)] :\n smul_comm_class α β (Π i : I, f i) :=\n⟨λ x y z, funext $ λ i, smul_comm x y (z i)⟩\n\n@[to_additive]\ninstance smul_comm_class' {g : I → Type*} {α : Type*}\n [Π i, has_smul α $ g i] [Π i, has_smul (f i) (g i)] [∀ i, smul_comm_class α (f i) (g i)] :\n smul_comm_class α (Π i : I, f i) (Π i : I, g i) :=\n⟨λ x y z, funext $ λ i, smul_comm x (y i) (z i)⟩\n\n@[to_additive]\ninstance smul_comm_class'' {g : I → Type*} {h : I → Type*}\n [Π i, has_smul (g i) (h i)] [Π i, has_smul (f i) (h i)]\n [∀ i, smul_comm_class (f i) (g i) (h i)] : smul_comm_class (Π i, f i) (Π i, g i) (Π i, h i) :=\n⟨λ x y z, funext $ λ i, smul_comm (x i) (y i) (z i)⟩\n\ninstance {α : Type*} [Π i, has_smul α $ f i] [Π i, has_smul αᵐᵒᵖ $ f i]\n [∀ i, is_central_scalar α (f i)] : is_central_scalar α (Π i, f i) :=\n⟨λ r m, funext $ λ i, op_smul_eq_smul _ _⟩\n\n/-- If `f i` has a faithful scalar action for a given `i`, then so does `Π i, f i`. This is\nnot an instance as `i` cannot be inferred. -/\n@[to_additive pi.has_faithful_vadd_at]\nlemma has_faithful_smul_at {α : Type*}\n [Π i, has_smul α $ f i] [Π i, nonempty (f i)] (i : I) [has_faithful_smul α (f i)] :\n has_faithful_smul α (Π i, f i) :=\n⟨λ x y h, eq_of_smul_eq_smul $ λ a : f i, begin\n classical,\n have := congr_fun (h $ function.update (λ j, classical.choice (‹Π i, nonempty (f i)› j)) i a) i,\n simpa using this,\nend⟩\n\n@[to_additive pi.has_faithful_vadd]\ninstance has_faithful_smul {α : Type*}\n [nonempty I] [Π i, has_smul α $ f i] [Π i, nonempty (f i)] [Π i, has_faithful_smul α (f i)] :\n has_faithful_smul α (Π i, f i) :=\nlet ⟨i⟩ := ‹nonempty I› in has_faithful_smul_at i\n\n@[to_additive]\ninstance mul_action (α) {m : monoid α} [Π i, mul_action α $ f i] :\n @mul_action α (Π i : I, f i) m :=\n{ smul := (•),\n mul_smul := λ r s f, funext $ λ i, mul_smul _ _ _,\n one_smul := λ f, funext $ λ i, one_smul α _ }\n\n@[to_additive]\ninstance mul_action' {g : I → Type*} {m : Π i, monoid (f i)} [Π i, mul_action (f i) (g i)] :\n @mul_action (Π i, f i) (Π i : I, g i) (@pi.monoid I f m) :=\n{ smul := (•),\n mul_smul := λ r s f, funext $ λ i, mul_smul _ _ _,\n one_smul := λ f, funext $ λ i, one_smul _ _ }\n\ninstance distrib_mul_action (α) {m : monoid α} {n : ∀ i, add_monoid $ f i}\n [∀ i, distrib_mul_action α $ f i] :\n @distrib_mul_action α (Π i : I, f i) m (@pi.add_monoid I f n) :=\n{ smul_zero := λ c, funext $ λ i, smul_zero _,\n smul_add := λ c f g, funext $ λ i, smul_add _ _ _,\n ..pi.mul_action _ }\n\ninstance distrib_mul_action' {g : I → Type*} {m : Π i, monoid (f i)} {n : Π i, add_monoid $ g i}\n [Π i, distrib_mul_action (f i) (g i)] :\n @distrib_mul_action (Π i, f i) (Π i : I, g i) (@pi.monoid I f m) (@pi.add_monoid I g n) :=\n{ smul_add := by { intros, ext x, apply smul_add },\n smul_zero := by { intros, ext x, apply smul_zero } }\n\nlemma single_smul {α} [monoid α] [Π i, add_monoid $ f i]\n [Π i, distrib_mul_action α $ f i] [decidable_eq I] (i : I) (r : α) (x : f i) :\n single i (r • x) = r • single i x :=\nsingle_op (λ i : I, ((•) r : f i → f i)) (λ j, smul_zero _) _ _\n\n/-- A version of `pi.single_smul` for non-dependent functions. It is useful in cases Lean fails\nto apply `pi.single_smul`. -/\nlemma single_smul' {α β} [monoid α] [add_monoid β]\n [distrib_mul_action α β] [decidable_eq I] (i : I) (r : α) (x : β) :\n single i (r • x) = r • single i x :=\nsingle_smul i r x\n\nlemma single_smul₀ {g : I → Type*} [Π i, monoid_with_zero (f i)] [Π i, add_monoid (g i)]\n [Π i, distrib_mul_action (f i) (g i)] [decidable_eq I] (i : I) (r : f i) (x : g i) :\n single i (r • x) = single i r • single i x :=\nsingle_op₂ (λ i : I, ((•) : f i → g i → g i)) (λ j, smul_zero _) _ _ _\n\ninstance mul_distrib_mul_action (α) {m : monoid α} {n : Π i, monoid $ f i}\n [Π i, mul_distrib_mul_action α $ f i] :\n @mul_distrib_mul_action α (Π i : I, f i) m (@pi.monoid I f n) :=\n{ smul_one := λ c, funext $ λ i, smul_one _,\n smul_mul := λ c f g, funext $ λ i, smul_mul' _ _ _,\n ..pi.mul_action _ }\n\ninstance mul_distrib_mul_action' {g : I → Type*} {m : Π i, monoid (f i)} {n : Π i, monoid $ g i}\n [Π i, mul_distrib_mul_action (f i) (g i)] :\n @mul_distrib_mul_action (Π i, f i) (Π i : I, g i) (@pi.monoid I f m) (@pi.monoid I g n) :=\n{ smul_mul := by { intros, ext x, apply smul_mul' },\n smul_one := by { intros, ext x, apply smul_one } }\n\nend pi\n\nnamespace function\n\n/-- Non-dependent version of `pi.has_smul`. Lean gets confused by the dependent instance if this\nis not present. -/\n@[to_additive]\ninstance has_smul {ι R M : Type*} [has_smul R M] :\n has_smul R (ι → M) :=\npi.has_smul\n\n/-- Non-dependent version of `pi.smul_comm_class`. Lean gets confused by the dependent instance if\nthis is not present. -/\n@[to_additive]\ninstance smul_comm_class {ι α β M : Type*}\n [has_smul α M] [has_smul β M] [smul_comm_class α β M] :\n smul_comm_class α β (ι → M) :=\npi.smul_comm_class\n\n@[to_additive]\nlemma update_smul {α : Type*} [Π i, has_smul α (f i)] [decidable_eq I]\n (c : α) (f₁ : Π i, f i) (i : I) (x₁ : f i) :\n update (c • f₁) i (c • x₁) = c • update f₁ i x₁ :=\nfunext $ λ j, (apply_update (λ i, (•) c) f₁ i x₁ j).symm\n\nend function\n\nnamespace set\n\n@[to_additive]\nlemma piecewise_smul {α : Type*} [Π i, has_smul α (f i)] (s : set I) [Π i, decidable (i ∈ s)]\n (c : α) (f₁ g₁ : Π i, f i) :\n s.piecewise (c • f₁) (c • g₁) = c • s.piecewise f₁ g₁ :=\ns.piecewise_op _ _ (λ _, (•) c)\n\nend set\n\nsection extend\n\n@[to_additive] lemma function.extend_smul {R α β γ : Type*} [has_smul R γ]\n (r : R) (f : α → β) (g : α → γ) (e : β → γ) :\n function.extend f (r • g) (r • e) = r • function.extend f g e :=\nfunext $ λ _, by convert (apply_dite ((•) r) _ _ _).symm\n\nend extend\n", "meta": {"author": "Parinya-Siri", "repo": "lean-machine-learning", "sha": "ec610bac246ae7108fc6f0c140b3440f0fbacc52", "save_path": "github-repos/lean/Parinya-Siri-lean-machine-learning", "path": "github-repos/lean/Parinya-Siri-lean-machine-learning/lean-machine-learning-ec610bac246ae7108fc6f0c140b3440f0fbacc52/matlib/group_theory/group_action/pi.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4378234991142019, "lm_q2_score": 0.05419872409429726, "lm_q1q2_score": 0.02372947503049043}} {"text": "import tactic --hide \n\n/-Lemma\nIf $P,Q$ are logical statements with respective proofs $p,q$, then $Q$ is true.\n-/\nlemma example_two (P Q : Prop) (p : P) (q : Q) : Q :=\nbegin\n exact q,\n\n\nend\n", "meta": {"author": "CBirkbeck", "repo": "logic_projic", "sha": "0b029af0fbfc0ac6eafae47401d5bbf8e641d7d2", "save_path": "github-repos/lean/CBirkbeck-logic_projic", "path": "github-repos/lean/CBirkbeck-logic_projic/logic_projic-0b029af0fbfc0ac6eafae47401d5bbf8e641d7d2/src/tutorial/tut2.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.41869690935568665, "lm_q2_score": 0.056652420927984726, "lm_q1q2_score": 0.023720193550064626}} {"text": "import Lean\nimport Duper.TPTPParser.SyntaxDecl\n\nopen Lean\nopen Lean.Parser\nopen TSyntax.Compat\n\nnamespace TPTP\n\ndef explicitBinder : Parser := Term.explicitBinder false\n\naxiom iota : Type\nprivate axiom iotaInhabited : iota\nnoncomputable instance : Inhabited iota := ⟨iotaInhabited⟩\n\ndef processThfDefinedType (ty : Syntax) : MacroM Syntax := do\n match ty with\n | `(defined_type|🍉$id) =>\n match id.getId with\n | `i => `(TPTP.iota)\n | `o => `(Prop)\n | `tType => `(Type)\n | _ => Macro.throwError s!\"Unsupported thf_defined_type: {ty}\"\n | _ => Macro.throwError s!\"{ty} is not a defined type\"\n\ndef processThfDefinedTerm (term : Syntax) : MacroM Syntax := do\n match term with\n | `(defined_term|🍉$id) =>\n match id.getId with\n | `true => `(True)\n | `false => `(False)\n | _ => Macro.throwError s!\"Unsupported thf_defined_term: {term}\"\n | _ => Macro.throwError s!\"{term} is not a defined term\" \n\npartial def processThfAtomicType (stx : Syntax) : MacroM Syntax := do\n match stx with\n | `(thf_type| $ty:thf_atomic_type) => processThfAtomicType ty\n | `(thf_atomic_type| $ty:ident) => pure ty\n | `(thf_atomic_type| $ty:defined_type) => processThfDefinedType ty\n | `(thf_atomic_type| $f:ident $args:thf_type_arguments) => do\n let ts ←\n pure $ ← ((@Syntax.SepArray.mk \",\" args.raw[1].getArgs) : Array Syntax).mapM\n fun arg => processThfAtomicType arg\n let ts := mkNode ``many ts\n let ts := mkNode ``Term.app #[f, ts]\n `($ts)\n | _ => Macro.throwError s!\"Unsupported thf_atomic_type: {stx}\"\n\n/-- In addition to returning the syntax that corresponds to the type of `stx`, if the\n type of `stx` is `Type` or has the form `A → B → ... → Type`, then we also return\n an Array containing the stx for `A`, `B`, etc. (in reverse order. So `A → B → Type` would\n have the stx array #[B, A]) This is so that we can add the appropriate `Inhabited` constraints\n to the newly declared type. -/\npartial def processThfType (stx : Syntax) : MacroM (Syntax × Option (Array Syntax)) := do\n match stx with\n | `(thf_type| ( $t:thf_type ) ) => processThfType t\n | `(thf_type| $ty:thf_atomic_type) =>\n let res ← processThfAtomicType ty\n let typeStx ← `(Type)\n if res == typeStx then return (res, some #[])\n else return (res, none)\n | `(thf_type| $arg:thf_type > $ret:thf_type) =>\n -- Although the current parser syntax has thf_type > thf_type, this pattern should\n -- only appear in TPTP files when both arg and ret are of the category thf_atomic_type\n let (ret, stxListOpt) ← processThfType ret\n let (arg, _) ← processThfType arg\n let res ← `($arg → $ret)\n match stxListOpt with\n | none => return (res, none)\n | some stxList => return (res, some (stxList.push arg))\n | `(thf_type| ( $args:thf_xprod_args ) > $ret:thf_atomic_type) =>\n let ret ← processThfAtomicType ret\n let args : Array Syntax := @Syntax.SepArray.mk \"*\" args.raw[0].getArgs\n let args ← args.mapM (fun a => processThfAtomicType a)\n let res ← args.foldrM (fun (a acc : Syntax) => `($a → $acc)) ret\n let typeStx ← `(Type)\n if ret == typeStx then return (res, some args.reverse)\n else return (res, none)\n | `(thf_type| $q:th1_quantifier [ $vs,* ] : $ty) =>\n let (ty, _) ← processThfType ty\n let vs : Array Syntax := vs\n let res ← vs.foldrM\n fun v acc => do\n let (v, v_ty) ← match v with\n | `(thf_variable| $v:ident) =>\n -- throw Error?\n pure (v, (← `(_) : Syntax))\n | `(thf_variable| $v:ident : $v_ty:thf_type) =>\n pure (v, (← processThfType v_ty).1)\n | _ => Macro.throwError s!\"Unsupported thf_variable: {v} when trying to process a tf1_quantified_type\"\n match q.raw[0].getKind with\n | Name.str _ \"!>\" => `(∀ ($v : $v_ty), $acc)\n | _ => Macro.throwError s!\"Unsupported th1_quantifier: {q.raw[0].getKind}\"\n ty\n return (res, none)\n | _ => Macro.throwError s!\"Unsupported thf_type: {stx}\"\n\npartial def processThfTerm (stx : Syntax) (is_untyped : Bool) : MacroM Syntax := do\n match stx with\n | `(thf_term| $d:defined_term) => processThfDefinedTerm d\n | `(thf_term| ( $t:thf_term ) ) => processThfTerm t is_untyped\n | `(thf_term| ~ $t:thf_term ) =>\n let t ← processThfTerm t is_untyped\n `(¬ $t)\n | `(thf_term| $t₁:thf_term @ $t₂:thf_term) => do\n let t₁ ← processThfTerm t₁ is_untyped\n let t₂ ← processThfTerm t₂ is_untyped\n `(($t₁ $t₂))\n | `(thf_term| $t₁:thf_term $conn:bexpOp $t₂:thf_term ) => do\n let t₁ ← processThfTerm t₁ is_untyped\n let t₂ ← processThfTerm t₂ is_untyped\n match conn.raw[0].getKind with\n | Name.str _ \"&\" => `($t₁ ∧ $t₂)\n | Name.str _ \"=>\" => `($t₁ → $t₂)\n | Name.str _ \"|\"=> `($t₁ ∨ $t₂)\n | Name.str _ \"<=>\" => `($t₁ ↔ $t₂)\n | Name.str _ \"<~>\" => `(¬ ($t₁ ↔ $t₂))\n | Name.str _ \"~|\" => `(¬ ($t₁ ∨ $t₂))\n | Name.str _ \"~&\" => `(¬ ($t₁ ∧ $t₂))\n | _ => Macro.throwError s!\"Unsupported bexpOp: {conn.raw[0].getKind}\"\n | `(thf_term| $t₁:thf_term $conn:eqOp $t₂:thf_term ) => do\n let t₁ ← processThfTerm t₁ is_untyped\n let t₂ ← processThfTerm t₂ is_untyped\n match conn.raw[0].getKind with\n | Name.str _ \"=\" => `($t₁ = $t₂)\n | Name.str _ \"!=\" => `($t₁ ≠ $t₂)\n | _ => Macro.throwError s!\"Unsupported eqOp: {conn.raw[0].getKind}\"\n | `(thf_term| $f:ident $args:thf_arguments ?) => do\n let ts : Array Syntax ← match args with\n | some args =>\n ((@Syntax.SepArray.mk \",\" args.raw[1].getArgs) : Array Syntax).mapM\n fun arg => processThfTerm arg is_untyped\n | none => pure #[]\n let ts := mkNode ``many ts\n let ts := mkNode ``Term.app #[f, ts]\n `($ts)\n | `(thf_term| $q:quantifier [ $vs,* ] : $body) => do\n let body ← processThfTerm body is_untyped\n let vs : Array Syntax := vs\n vs.foldrM\n fun v acc => do\n let (v, ty) ← match v with\n | `(thf_variable| $v:ident) =>\n if is_untyped then\n let iotaTypeSyntax ← `(TPTP.iota)\n pure (v, iotaTypeSyntax.raw)\n else\n -- throw Error?\n pure (v, (← `(_) : Syntax))\n | `(thf_variable| $v:ident : $ty:thf_type) =>\n pure (v, (← processThfType ty).1)\n | _ => Macro.throwError s!\"Unsupported thf_variable: {v}\"\n match q.raw[0].getKind with\n | Name.str _ \"!\" => `(∀ ($v : $ty), $acc)\n | Name.str _ \"?\" => `(Exists fun ($v : $ty) => $acc)\n | Name.str _ \"^\" => `(fun ($v : $ty) => $acc)\n | _ => Macro.throwError s!\"Unsupported quantifier: {q.raw[0].getKind}\"\n body\n | _ => Macro.throwError s!\"Unsupported thf_term: {stx}\"\n\n/-- Determines whether an identifier is a variable by checking whether the first character is capital -/\ndef isVar (stx : TSyntax `ident) : MacroM Bool := do\n match stx with\n | Syntax.ident _ rawVal _ _ => return (rawVal.get 0).isUpper\n | _ => Macro.throwError \"Non-ident passed into isVar\"\n\n/-- Given a piece of syntax, returns the list of variables that appear in said syntax. This function\n may return lists in which the same variable appears multiple times. -/\npartial def getVarsHelper (stx : Syntax) : MacroM (List (TSyntax `ident)) := do\n match stx with\n | `(thf_term| ( $t:thf_term )) => getVarsHelper t\n | `(thf_term| ~ $t:thf_term ) => getVarsHelper t\n | `(thf_term| $t1:thf_term $conn:bexpOp $t2:thf_term ) =>\n return (← getVarsHelper t1).append (← getVarsHelper t2)\n | `(thf_term| $t1:thf_term $conn:eqOp $t2:thf_term ) =>\n return (← getVarsHelper t1).append (← getVarsHelper t2)\n | `(thf_term| $f:ident $args:thf_arguments ?) =>\n match args with\n | none =>\n if (← isVar f) then return [f]\n else return []\n | some args =>\n let args := ((@Syntax.SepArray.mk \",\" args.raw[1].getArgs) : Array Syntax)\n let argsVars ← args.mapM (fun arg => getVarsHelper arg)\n let argsVars := argsVars.foldl\n (fun acc varList => varList.append acc) []\n if (← isVar f) then return f :: argsVars\n else return argsVars\n | _ => Macro.throwError s!\"Unsupported cnf term: {stx}\"\n\n/-- Given a piece of syntax, returns the list of variables that appear in said syntax. This function is needed\n because cnf clauses are implicitly universally quantified (but Lean requires that we explicitly universally\n quantify the variables). This function is only intended to be called on cnf clauses. -/\ndef getVars (stx : Syntax) : MacroM (List (TSyntax `ident)) := do\n let varsWithDuplicates ← getVarsHelper stx\n let vars := varsWithDuplicates.foldl\n (fun acc var => if acc.contains var then acc else var :: acc) []\n return vars\n\npartial def processCnfTerm (stx : Syntax) : MacroM Syntax := do\n let vars ← getVars stx\n let iotaTypeSyntax ← `(TPTP.iota)\n let unquantifiedRes ← processThfTerm stx true\n let quantifiedRes ← vars.foldlM\n (fun acc (var : TSyntax `ident) => `(∀ ($var : $iotaTypeSyntax), $acc)) unquantifiedRes\n return quantifiedRes\n\n/-- Note: This function is only meant to be used for fof/cnf formats (tff files declare their own symbols).\n\n Returns a list in which each element is `(explicitBinder| ($name : $ty)) where $name is a symbol that\n appears in stx (and isn't a variable) and $ty is the type of said symbol.\n\n In fof/cnf formats, the only base types are Prop and `iota. All symbols therefore must be of type Prop, type\n `iota, or functions that output Prop or iota. Which of these is the case can be determined by the position\n of the symbol in the overall formula.\n\n The topType argument is used to keep track of what the overall type of stx is supposed to be. -/\npartial def getNonVarSymbols (acc : HashMap String (TSyntax `TPTP.explicitBinder)) (topType : TSyntax `thf_type)\n (stx : Syntax) : MacroM (HashMap String (TSyntax `TPTP.explicitBinder)) := do\n match stx with\n | `(thf_term|🍉$id:ident) => return acc\n | `(thf_term| ( $t:thf_term )) => getNonVarSymbols acc topType t\n | `(thf_term| ~ $t:thf_term ) =>\n if topType != (← `(Prop)) then Macro.throwError s!\"Error: cnf/fof term: {stx} is supposed to have type {topType}\"\n else getNonVarSymbols acc (← `(Prop)) t\n | `(thf_term| $t1:thf_term $conn:bexpOp $t2:thf_term ) =>\n if topType != (← `(Prop)) then Macro.throwError s!\"Error: cnf/fof term: {stx} is supposed to have type {topType}\"\n else\n match conn.raw[0].getKind with\n | Name.str _ \"&\" => getNonVarSymbols (← getNonVarSymbols acc (← `(Prop)) t1) (← `(Prop)) t2\n | Name.str _ \"=>\" => getNonVarSymbols (← getNonVarSymbols acc (← `(Prop)) t1) (← `(Prop)) t2\n | Name.str _ \"|\" => getNonVarSymbols (← getNonVarSymbols acc (← `(Prop)) t1) (← `(Prop)) t2\n | Name.str _ \"<=>\" => getNonVarSymbols (← getNonVarSymbols acc (← `(Prop)) t1) (← `(Prop)) t2\n | Name.str _ \"<~>\" => getNonVarSymbols (← getNonVarSymbols acc (← `(Prop)) t1) (← `(Prop)) t2\n | Name.str _ \"~|\" => getNonVarSymbols (← getNonVarSymbols acc (← `(Prop)) t1) (← `(Prop)) t2\n | Name.str _ \"~&\" => getNonVarSymbols (← getNonVarSymbols acc (← `(Prop)) t1) (← `(Prop)) t2\n | _ => Macro.throwError s!\"Unsupported bexpOp: {conn.raw[0].getKind}\"\n | `(thf_term| $t1:thf_term $conn:eqOp $t2:thf_term ) =>\n if topType != (← `(Prop)) then Macro.throwError s!\"Error: cnf/fof term: {stx} is supposed to have type {topType}\"\n else\n match conn.raw[0].getKind with\n | Name.str _ \"=\" => getNonVarSymbols (← getNonVarSymbols acc (← `(TPTP.iota)) t1) (← `(TPTP.iota)) t2\n | Name.str _ \"!=\" => getNonVarSymbols (← getNonVarSymbols acc (← `(TPTP.iota)) t1) (← `(TPTP.iota)) t2\n | _ => Macro.throwError s!\"Unsupported eqOp: {conn.raw[0].getKind}\"\n | `(thf_term| $f:ident $args:thf_arguments ?) =>\n if (← isVar f) then\n if let some _ := args then\n Macro.throwError s!\"Variable used as function in cnf/fof term: {stx}\"\n else\n return acc\n match args with\n | none =>\n let s := f.getId.getString!\n let binder ← `(explicitBinder| ($f : $topType))\n return acc.insert s binder\n | some args =>\n let args := ((@Syntax.SepArray.mk \",\" args.raw[1].getArgs) : Array Syntax)\n let iotaTypeSyntax ← `(TPTP.iota)\n let fType ← args.foldlM (fun (acc _ : Syntax) => do\n `($iotaTypeSyntax → $acc)) topType\n let acc ← args.foldlM (fun acc arg => do\n getNonVarSymbols acc (← `(TPTP.iota)) arg) acc\n let s := f.getId.getString!\n let binder ← `(explicitBinder| ($f : $fType))\n return acc.insert s binder\n | `(thf_term| $q:quantifier [ $vs,* ] : $body) =>\n if topType != (← `(Prop)) then Macro.throwError s!\"Error: cnf/fof term: {stx} is supposed to have type {topType}\"\n else getNonVarSymbols acc (← `(Prop)) body\n | _ => Macro.throwError s!\"Unsupported cnf/fof term: {stx}\"\n\nmacro \"BEGIN_TPTP\" name:ident s:TPTP_file \"END_TPTP\" proof:term : command => do\n let mut symtab : HashMap String (TSyntax `TPTP.explicitBinder) := HashMap.empty\n let sargs := s.raw[0].getArgs\n for input in sargs do\n match input with\n | `(TPTP_input| tff($name:ident,$role,$term:thf_term $annotation:annotation ?).) =>\n pure () -- Only need to retrieve symbols from cnf and fof files\n | `(TPTP_input| tff($n:ident,type,$name:ident : $ty:thf_type $annotation:annotation ?).) =>\n pure () -- Only need to retrieve symbols from cnf and fof files\n | `(TPTP_input| thf($name:ident,$role,$term:thf_term $annotation:annotation ?).) =>\n pure ()\n | `(TPTP_input| thf($n:ident,type,$name:ident : $ty:thf_type $annotation:annotation ?).) =>\n pure () -- Only need to retrieve symbols from cnf and fof files\n | `(TPTP_input| cnf($name:ident,$role,$term:thf_term $annotation:annotation ?).) =>\n symtab ← getNonVarSymbols symtab (← `(Prop)) term\n | `(TPTP_input| fof($name:ident,$role,$term:thf_term $annotation:annotation ?).) =>\n symtab ← getNonVarSymbols symtab (← `(Prop)) term\n | _ => Macro.throwError s!\"Unsupported TPTP_input: {input}\"\n -- Perform a foldl so that we only have one binder for each symbol\n let nonVarSymbols := (symtab.toList).foldl\n (fun acc (_, binder) =>\n if List.contains acc binder then acc\n else binder :: acc) []\n let mut hyps : Array (TSyntax `TPTP.explicitBinder) := #[]\n for input in sargs do\n match input with\n | `(TPTP_input| tff($name:ident,$role,$term:thf_term $annotation:annotation ?).) =>\n let term ← processThfTerm term false\n let name := (mkIdent $ name.getId.appendBefore \"h\")\n if role.getId == `conjecture then\n hyps := hyps.push (← `(explicitBinder| ($name : ¬ $term)))\n else\n hyps := hyps.push (← `(explicitBinder| ($name : $term)))\n | `(TPTP_input| tff($n:ident,type,$name:ident : $ty:thf_type $annotation:annotation ?).) =>\n let (ty, stxArrOpt) ← processThfType ty\n hyps := hyps.push (← `(explicitBinder| ($name : $ty)))\n match stxArrOpt with\n | none => continue\n | some stxArr =>\n let typeArgName := `typeArg\n let mut counter := 0\n let mut nameApp ← `($name)\n let mut typeArgs : Array Ident := #[]\n for _ in stxArr do\n let typeArg := mkIdent $ typeArgName.appendAfter (toString counter)\n nameApp ← `($nameApp $typeArg)\n counter := counter + 1\n typeArgs := typeArgs.push typeArg\n let mut quantifiedNameApp ← `(Inhabited $nameApp)\n for (stx, typeArg) in stxArr.zip typeArgs.reverse do\n quantifiedNameApp ← `(∀ $typeArg : $stx, $quantifiedNameApp)\n hyps := hyps.push (← `(explicitBinder| (_ : $quantifiedNameApp)))\n | `(TPTP_input| thf($name:ident,$role,$term:thf_term $annotation:annotation ?).) =>\n let term ← processThfTerm term false\n let name := (mkIdent $ name.getId.appendBefore \"h\")\n if role.getId == `conjecture then\n hyps := hyps.push (← `(explicitBinder| ($name : ¬ $term)))\n else\n hyps := hyps.push (← `(explicitBinder| ($name : $term)))\n | `(TPTP_input| thf($n:ident,type,$name:ident : $ty:thf_type $annotation:annotation ?).) =>\n let (ty, stxArrOpt) ← processThfType ty\n hyps := hyps.push (← `(explicitBinder| ($name : $ty)))\n match stxArrOpt with\n | none => continue\n | some stxArr =>\n let typeArgName := `typeArg\n let mut counter := 0\n let mut nameApp ← `($name)\n let mut typeArgs : Array Ident := #[]\n for _ in stxArr do\n let typeArg := mkIdent $ typeArgName.appendAfter (toString counter)\n nameApp ← `($nameApp $typeArg)\n counter := counter + 1\n typeArgs := typeArgs.push typeArg\n let mut quantifiedNameApp ← `(Inhabited $nameApp)\n for (stx, typeArg) in stxArr.zip typeArgs.reverse do\n quantifiedNameApp ← `(∀ $typeArg : $stx, $quantifiedNameApp)\n hyps := hyps.push (← `(explicitBinder| (_ : $quantifiedNameApp)))\n | `(TPTP_input| cnf($name:ident,$role,$term:thf_term $annotation:annotation ?).) =>\n let term ← processCnfTerm term\n let name := (mkIdent $ name.getId.appendBefore \"h\")\n if role.getId == `conjecture then\n hyps := hyps.push (← `(explicitBinder| ($name : ¬ $term)))\n else\n hyps := hyps.push (← `(explicitBinder| ($name : $term)))\n | `(TPTP_input| fof($name:ident,$role,$term:thf_term $annotation:annotation ?).) =>\n -- Although tff differs from fof, I think that processThfTerm will do what we want for fof terms\n let term ← processThfTerm term true\n let name := (mkIdent $ name.getId.appendBefore \"h\")\n if role.getId == `conjecture then\n hyps := hyps.push (← `(explicitBinder| ($name : ¬ $term)))\n else\n hyps := hyps.push (← `(explicitBinder| ($name : $term)))\n | _ => Macro.throwError s!\"Unsupported TPTP_input: {input}\"\n let hypall := mkNode ``many (nonVarSymbols.toArray.append hyps)\n let spec ← `(Term.typeSpec| : False)\n let sig := mkNode ``Command.declSig #[hypall,spec]\n `(theorem $name $sig := $proof)", "meta": {"author": "leanprover-community", "repo": "duper", "sha": "96b8f8383363e800976b0fa99830c1b5e8c19b09", "save_path": "github-repos/lean/leanprover-community-duper", "path": "github-repos/lean/leanprover-community-duper/duper-96b8f8383363e800976b0fa99830c1b5e8c19b09/Duper/TPTPParser/MacroDecl.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.048136776066685504, "lm_q1q2_score": 0.023692350071871347}} {"text": "import MLIR.Semantics.Fitree\nimport MLIR.Semantics.Semantics\nimport MLIR.Semantics.SSAEnv\nimport MLIR.Semantics.UB\nimport MLIR.Util.Metagen\nimport MLIR.AST\nimport MLIR.EDSL\nimport Mathlib.Data.List.Dedup\nopen MLIR.AST\n\n/-\n### Dialect: `scf`\n-/\n\ninstance scf: Dialect Void Void (fun _x => Unit) where\n name := \"scf\"\n iα := inferInstance\n iε := inferInstance\n\n-- Operations of `scf` that unfold into regions need to expose these regions\n-- | run a loop, decrementing i from n to -\n-- | ix := lo + (n - i) * step\ndef run_loop_bounded_stepped_go [Monad m] (n: Nat) (i: Nat) (lo: Int) (step: Int)\n (accum: a) (eff: Int -> a -> m a): m a := do\n let ix : Int := lo + (n - i) * step\n let accum <- eff ix accum\n match i with\n | .zero => return accum\n | .succ i' => run_loop_bounded_stepped_go n i' lo step accum eff\n\n-- | TODO: make this model the `yield` as well.\ndef run_loop_bounded_stepped [Monad m] (n: Nat) (lo: Int) (step: Int) (accum: a) (eff: Int -> a -> m a): m a :=\n run_loop_bounded_stepped_go n n lo step accum eff\n\n\n-- | TODO: make this model the `yield` as well.\ndef run_loop_bounded\n (n: Nat)\n (ix: Int)\n (start: TypedArgs Δ)\n (rgn: TypedArgs Δ → OpM Δ (TypedArgs Δ)): OpM Δ (TypedArgs Δ):= do\n match n with\n | 0 => return start\n | .succ n' => do\n let (_: TypedArgs Δ) <- rgn [⟨MLIRType.index, ix⟩]\n run_loop_bounded n' (ix + 1) ([]) rgn\n\n\n-- | TODO: refactor to (1) an effect, (2) an interpretation\n-- | TODO: use the return type of Scf.For. For now, just do unit.\ndef scf_semantics_op: IOp Δ → OpM Δ (TypedArgs Δ)\n | IOp.mk \"scf.if\" _ [⟨.i1, b⟩] [rthen, relse] _ => do\n (if b = 1 then rthen else relse) []\n | IOp.mk \"scf.for\" _ [⟨.index, lo⟩, ⟨.index, hi⟩, ⟨.index, step⟩] [body] _ => do\n let nsteps : Int := (hi - lo) / step\n let _ ← run_loop_bounded_stepped\n (a := TypedArgs Δ)\n (n := nsteps.toNat)\n (lo := lo)\n (step := step)\n (accum := default)\n (eff := (fun i _ => body [⟨.index, i⟩]))\n return []\n | IOp.mk \"scf.for'\" _ [⟨.index, lo⟩, ⟨.index, hi⟩] [body] _ => do\n run_loop_bounded (n := (hi - lo).toNat) (ix := lo) [] body\n | IOp.mk \"scf.yield\" _ vs [] _ =>\n return vs\n | IOp.mk \"scf.assert\" _ [⟨.i1, arg⟩] [] attrs =>\n if arg == 0 then\n let err := match attrs.find \"msg\" with -- TODO: convert this to a pattern match.\n | .some (.str str) => str\n | _ => \"\"\n OpM.Error s!\"{err}: {arg} \"\n else return [] -- success\n | IOp.mk \"scf.execute_region\" _ args [rgn] _ => do\n rgn args\n | IOp.mk name .. => OpM.Unhandled (\"scf unhandled: \" ++ name)\n\ninstance: Semantics scf where\n semantics_op := scf_semantics_op\n\n/-\n### Theorems\n-/\n\nnamespace SCF.IF\n-- Proof that `scf.if` with a fixed condition simplifies to its \"then\" or\n-- \"else\" region depending on the value\n\ndef LHS (r₁ r₂: Region scf): Region scf := [mlir_region|\n{\n \"scf.if\" (%b) ($(r₁), $(r₂)) : (i1) -> ()\n}]\n\ndef INPUT (b: Bool): SSAEnv scf :=\n SSAEnv.set \"b\" MLIRType.i1 (if b then 1 else 0) SSAEnv.empty\n\n\n-- Pure unfolding-style proof\ntheorem equivalent (b: Bool):\n run ⟦LHS r₁ r₂⟧ (INPUT b) =\n run (TopM.scoped (denoteRegion\n (Δ := scf)\n (rgn := if b then r₁ else r₂)\n (args := []))) (INPUT b) := by\n simp[LHS];\n simp[run_denoteRegion];\n simp[run_bind_success];\n rw[run_seq];\n simp[run_denoteTypedArgs_nil];\n simp [run_denoteOps_singleton];\n simp[run_denoteOp];\n simp[run_bind];\n simp[run_denoteOp];\n simp[run_denoteOpArgs_cons_];\n simp[run_bind];\n simp[INPUT];\n rw[run_TopM_get_];\n simp[SSAEnv.get_set_eq];\n simp[run_denoteOpArgs_nil];\n simp[run_pure];\n simp[INPUT];\n simp[TopM.mapDenoteRegion]; -- TODO: make run version of this\n save\n simp[OpM.denoteRegions] -- TODO: make run version\n simp[Semantics.semantics_op]; -- TODO: make run version\n simp[scf_semantics_op]; -- SLOW\n save\n -- VERY SLOW\n cases b <;> simp;\n case false => {\n rw[OpM_toTopM_denoteRegion]; -- TODO: make run version\n simp[TopM.denoteRegionsByIx]; -- TODO: make run version\n }\n case true => {\n -- TODO, FIXME, BUG: lean does not unfold the definition in the\n -- 'true' branch, while it does on the 'false' branch.\n -- This seems to be a tactic bug, because even after\n -- 'sorry'ing, we still get an error.\n sorry\n /-\n rw[OpM_toTopM_denoteRegion];\n simp[TopM.denoteRegionsByIx];\n -/\n }\n -- | but having this sorry here fixes the 'case true' error,\n -- even though lean knows that this tactic in unreachable:\n -- 'this tactic is never executed [linter.unreachableTactic]'\n sorry\n\nend SCF.IF\n\n\n\nnamespace SCF.FOR_PEELING\ndef LHS (r: Region scf): Region scf := [mlir_region|\n{\n \"scf.for'\" (%c0, %cn_plus_1) ($(r)) : (index, index) -> ()\n}]\ndef RHS (r: Region scf): Region scf := [mlir_region|\n{\n \"scf.execute_region\" (%c0) ($(r)) : (index) -> ()\n \"scf.for'\" (%c1, %cn_plus_1) ($(r)) : (index, index) -> ()\n}]\ndef INPUT (n: Nat): SSAEnv scf :=\n SSAEnv.set \"cn\" .index n\n (SSAEnv.set \"cn_plus_1\" .index (n + 1)\n (SSAEnv.set \"c0\" .index 0\n (SSAEnv.set \"c1\" .index 1 SSAEnv.empty)))\n/-\nSSAEnv.One [\n ⟨\"cn\", .index, n⟩,\n ⟨\"cn_plus_1\", .index, n + 1⟩,\n ⟨\"c0\", .index, 0⟩,\n ⟨\"c1\", .index, 1⟩]\n-/\n\n -- The main requirement for this theorem is that `r` satisfies SSA invariants,\n-- ie. values available before it runs are unchanged by its execution. Here we\n-- assume something quite a bit stronger, to simplify the proof of the actual\n-- property, which is that a read can commute with running the region.\n\n\ntheorem CORRECT_r (n:Nat) (r: Region scf) args:\n (run (denoteRegion scf r args) (INPUT n)) = .ok ([], INPUT n) := by\n sorry\n\n/-\ntheorem CORRECT_r_commute_run_interpRegion_SSAEnvE_get [S: Semantics scf]\n (CORRECT_r: (run (denoteRegion scf r args) (INPUT n)) = .ok (.Ret [], INPUT n))\n (name: SSAVal) (τ: MLIRType scf) (v: MLIRType.eval τ)\n (ENV: SSAEnv.get name τ (INPUT n) = some v)\n (k: BlockResult scf → τ.eval → Fitree (SSAEnvE scf +' UBE) R):\n run (Fitree.bind\n (interpRegion scf [denoteRegion scf r] _ (Sum.inl <| RegionE.RunRegion 0 args))\n (fun discr =>\n Fitree.Vis (Sum.inl <| SSAEnvE.Get τ name) fun v => k discr v)) (INPUT n) =\n run (Fitree.Vis (Sum.inl <| SSAEnvE.Get τ name) fun v =>\n (Fitree.bind (interpRegion scf [denoteRegion scf r] _ (Sum.inl <| RegionE.RunRegion 0 args))\n (fun discr => k discr v))) (INPUT n) := by\n simp [run_bind, interpRegion, List.get!]\n simp [CORRECT_r]\n simp [run_SSAEnvE_get _ _ _ _ _ ENV]\n simp [run_bind, CORRECT_r]\n-/\nprivate theorem identity₁ (n: Nat):\n Int.toNat (Int.ofNat n + 1 - 0) = n + 1 := by\n sorry\n\n\nset_option maxHeartbeats 999999999 in\n-- Pretty slow due to simplifying scf_semantics_op\n-- which contains a large match\ntheorem equivalent (n: Nat) (r: Region scf):\n (run ⟦LHS r⟧ (INPUT n)) =\n (run ⟦RHS r⟧ (INPUT n)) := by {\n simp[LHS, RHS];\n simp[run_denoteRegion];\n simp[run_bind];\n simp[run_denoteTypedArgs_nil];\n simp[run_denoteOps_singleton];\n simp[run_denoteOp];\n simp[run_bind];\n simp[INPUT];\n simp[run_denoteOpArgs_cons_];\n simp[run_bind];\n rw[run_TopM_get_];\n rw[SSAEnv.get_set_ne_val];\n rw[SSAEnv.get_set_ne_val];\n rw[SSAEnv.get_set_eq_val] <;> simp;\n simp[run_denoteOpArgs_cons_];\n simp[run_bind];\n rw[run_TopM_get_];\n rw[SSAEnv.get_set_ne_val];\n rw[SSAEnv.get_set_eq_val] <;> simp;\n simp[run_denoteOpArgs_nil];\n simp[run_pure];\n simp[TopM.mapDenoteRegion]; -- TODO: make a 'run' version of this.\n simp[Semantics.semantics_op, scf_semantics_op]; -- SLOW :(\n simp[OpM.denoteRegions];\n apply Eq.symm;\n simp[run_denoteOps_cons];\n simp[run_bind];\n simp[run_denoteOps_singleton];\n simp[run_denoteOp];\n simp[run_bind];\n simp[run_denoteOpArgs_cons_];\n simp[run_bind];\n rw[run_TopM_get_];\n rw[SSAEnv.get_set_ne_val];\n rw[SSAEnv.get_set_ne_val];\n rw[SSAEnv.get_set_eq_val];\n simp;\n simp[run_denoteOpArgs_nil];\n simp[run_pure];\n simp[TopM_mapDenoteRegion_cons];\n simp[TopM_mapDenoteRegion_nil];\n simp[Semantics.semantics_op, scf_semantics_op];\n simp[OpM_denoteRegions_cons];\n save\n -- tactic 'simp' failed, nested error:\n -- (deterministic) timeout at 'whnf', maximum number of heartbeats (200000)\n -- has been reached (use 'set_option maxHeartbeats ' to set the limit)\n simp[OpM_denoteRegions_nil];\n simp[run_OpM_toTopM_denoteRegion];\n simp[run_TopM_denoteRegionsByIx_cons];\n sorry\n sorry\n simp; simp; simp; simp;\n}\n\n /-\n simp [LHS, RHS]\n simp [denoteTypedArgs, denoteOps, denoteOp]\n simp [denoteOpBase, Semantics.semantics_op, scf_semantics_op]; simp_itree\n -/\n /-\n -- simp [denoteRegions]\n rw [run_SSAEnvE_get \"c0\" .index 0]\n rw [run_SSAEnvE_get \"cn_plus_1\" .index (n+1)]\n rw [run_SSAEnvE_get \"c0\" .index 0]\n have h := CORRECT_r n r [⟨.index, 0⟩]\n rw [CORRECT_r_commute_run_interpRegion_SSAEnvE_get h \"c1\" .index 1]\n rw [run_SSAEnvE_get \"c1\" .index 1]\n rw [CORRECT_r_commute_run_interpRegion_SSAEnvE_get h \"cn_plus_1\" .index (n+1)]\n rw [run_SSAEnvE_get \"cn_plus_1\" .index (n+1)]\n rw [identity₁]\n simp [(by sorry: (Int.ofNat n + 1 - 1).toNat = n)]\n simp [peel_run_loop_bounded, Fitree.interp_bind]\n simp [(by sorry: (0:Int) + (1:Int) = (1:Int))]\n all_goals simp [INPUT, cast_eq]\n -/\nend SCF.FOR_PEELING\n\n\nnamespace SCF.FOR_FUSION\ndef LHS (r: Region scf): Region scf := [mlir_region|\n{\n \"scf.for'\" (%c0, %cn) ($(r)) : (index, index) -> ()\n \"scf.for'\" (%cn, %cn_plus_m) ($(r)) : (index, index) -> ()\n}]\ndef RHS (r: Region scf): Region scf := [mlir_region|\n{\n \"scf.for'\" (%c0, %cn_plus_m) ($(r)) : (index, index) -> ()\n}]\ndef INPUT (n m: Nat): SSAEnv scf := SSAEnv.One [\n ⟨\"cn\", .index, n⟩,\n ⟨\"cn_plus_m\", .index, n + m⟩,\n ⟨\"c0\", .index, 0⟩]\n\n/- theorem interp_region_of_run_loop_bounded\n (r: Region scf) (n: Nat)\n (rhs: Fitree (SSAEnvE scf +' Semantics.E scf +' UBE) (BlockResult scf)):\n Fitree.interp (interpRegion scf (denoteRegions scf [r]))\n (run_loop_bounded n 0 (BlockResult.Ret [])) = rhs := by {\n induction n;\n case zero => {\n simp [run_loop_bounded];\n sorry\n }\n case succ n' => {\n simp [run_loop_bounded];\n simp [Fitree.interp];\n sorry\n }\n } -/\n/-\ntheorem equivalent (n m: Nat) (r: Region scf):\n (run ⟦LHS r⟧ (INPUT n m)) =\n (run ⟦RHS r⟧ (INPUT n m)) := by\n simp [LHS, RHS, INPUT]\n simp [denoteRegion, denoteOps, denoteOp, denoteOpBase]\n simp_itree\n simp [Semantics.semantics_op, scf_semantics_op]\n simp [run];\n simp [StateT.run];\n simp [Except.bind];\n simp [denoteTypedArgs];\n simp [pure];\n simp [StateT.pure];\n simp [pure];\n simp [Except.pure];\n simp [List.mapM, List.mapM.loop];\n simp [bind, StateT.bind, Except.bind, TopM.get];\n sorry\n -- At this point we need something similar to CORRECT_r_* above.\n -- simp [run_denoteOp_interp_region]\n -- all_goals simp [INPUT, cast_eq]\n-/\nend SCF.FOR_FUSION\n", "meta": {"author": "opencompl", "repo": "lean-mlir", "sha": "85fd61e38dec57e4d67d7af4d49a1ccc67828c1b", "save_path": "github-repos/lean/opencompl-lean-mlir", "path": "github-repos/lean/opencompl-lean-mlir/lean-mlir-85fd61e38dec57e4d67d7af4d49a1ccc67828c1b/MLIR/Dialects/ScfSemantics.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41111086923216794, "lm_q2_score": 0.057493284856344876, "lm_q1q2_score": 0.02363611431230458}} {"text": "import fo.basic\nimport tactic\n\nopen signature\n\n\ndef signature.substitution.domain {σ : signature} (ν : σ.substitution) :=\n subtype {v : σ.var | ν v ≠ (term.var v)}\n\n\n@[simp]\ndef signature.substitution.is_ground {σ : signature} (ν : σ.substitution) :=\n ∀ v, (ν v).is_ground\n\ndef signature.ground_substitution (σ : signature) : Type :=\n subtype {ν : σ.substitution | ν.is_ground}\n\ndef signature.variable_renaming (σ : signature) (r : σ.var → σ.var) (h : function.bijective r) : σ.substitution :=\n (λ v, term.var (r v))\n\ndef signature.substitution.free {σ : signature} : σ.substitution → σ.var → σ.substitution :=\n (λ ν v v',\n if (v = v') then\n term.var v\n else\n (ν v)\n )\n\n@[reducible]\ndef signature.term.substitute {σ : signature} : σ.term → σ.substitution → σ.term \n | (term.var v) ν := (ν v)\n | (term.func f ts) ν := term.func f (λ i, (ts i).substitute ν)\n\n@[reducible]\ninstance signature.subst_term {σ : signature} : σ.substitutable σ.term :=\n {substitute := signature.term.substitute}\n\n@[reducible]\ndef signature.substitution.substitute {σ : signature} (ρ ν : σ.substitution) : σ.substitution :=\n (λ v : σ.var, (ρ v) ↓ ν)\n\n@[reducible]\ninstance signature.subst_substitution {σ : signature} : σ.substitutable σ.substitution :=\n {\n substitute := signature.substitution.substitute\n }\n\n@[reducible]\ndef signature.var.occurrs {σ : signature} : σ.var → σ.term → Prop \n | v (term.var v') := v = v'\n | v (term.func f ts) := ∃ i, v.occurrs (ts i)\n\ndef signature.var.is_bound {σ : signature} (v : σ.var) (φ : σ.formula) : Prop :=\n ¬φ.is_free v\n\n@[simp]\ndef signature.formula.substitute {σ : signature} : σ.formula → σ.substitution → σ.formula\n | (formula.neg φ) ν := φ.substitute ν\n | (formula.conj hn Φ) ν := formula.conj hn (λ i, (Φ i).substitute ν)\n | (formula.disj hn Φ) ν := formula.disj hn (λ i, (Φ i).substitute ν)\n | (formula.fall x φ) ν := formula.fall x (φ.substitute (ν.free x))\n | (formula.xist x φ) ν := formula.xist x (φ.substitute (ν.free x))\n | (formula.rel r ts) ν := formula.rel r (λ i, (ts i).substitute ν)\n | φ ν := φ\n\n@[reducible]\ninstance signature.sub_formula {σ : signature} : σ.substitutable σ.formula :=\n {\n substitute := signature.formula.substitute\n }\n\ndef signature.term.contains {σ : signature} : σ.term → σ.var → Prop \n | (term.var v') v := v' = v\n | (term.func f ts) v := ∃ i, (ts i).contains v\n \n@[reducible]\ndef signature.formula.contains {σ : signature} : σ.formula → σ.var → Prop \n | (formula.neg φ) v := φ.contains v\n | (formula.conj hn Φ) v := ∃ i, (Φ i).contains v\n | (formula.disj hn Φ) v := ∃ i, (Φ i).contains v\n | (formula.fall x φ) v := φ.contains v\n | (formula.xist x φ) v := φ.contains v\n | (formula.rel r ts) v := (∃ i, v.occurrs (ts i))\n | φ v := false\n\n@[reducible]\ndef signature.substitution.is_free {σ : signature} : σ.substitution → σ.formula → Prop \n | ν (formula.neg φ) := ν.is_free φ\n | ν (formula.conj hn Φ) := ∀ i, ν.is_free (Φ i)\n | ν (formula.disj hn Φ) := ∀ i, ν.is_free (Φ i)\n | ν (formula.fall x φ) := (∀ v : σ.var, (φ.contains v → φ.is_free v → ¬(ν v).contains x)) ∧ ν.is_free φ\n | ν (formula.xist x φ) := (∀ v : σ.var, (φ.contains v → φ.is_free v → ¬(ν v).contains x)) ∧ ν.is_free φ\n | ν φ := true\n\n\n@[reducible]\ndef signature.substitution.is_free1 {σ : signature} (ν : σ.substitution) (φ : σ.formula) : Prop :=\n ∀ (v : σ.var), (φ.is_free v) → ∀ (v' : σ.var), v'.occurrs (ν v) → φ.is_free v'\n \ndef signature.substitution.compose {σ : signature} (ν₁ : σ.substitution) (ν₂ : σ.substitution) : σ.substitution :=\n (λ v, (ν₁ v).substitute ν₂)\n\ndef signature.substitution.id {σ : signature} : σ.substitution :=\n (λ v, term.var v)\n\ndef signature.id_subst (σ : signature) : σ.substitution :=\n (λ v : σ.var, term.var v)\n\ndef subid {σ : signature} : σ.substitution := \n (λ v : σ.var, term.var v)\n\nlemma signature.term.term_eq_term_subst_id {σ : signature} : ∀ t : σ.term, t ↓ σ.id_subst = t :=\n begin\n intro t,\n induction t with v f ts,\n simp,\n refl,\n simp [signature.term.substitute],\n dsimp at t_ih,\n ext i,\n exact (t_ih i),\n end \n\ndef signature.term.more_general {σ : signature} (t₁ t₂ : σ.term) : Prop :=\n ∃ (ν : σ.substitution), t₁ ↓ ν = t₂\n\n\nsection more_general_preorder\n\n variable σ : signature\n variable t : σ.term\n variable ν₁ : σ.substitution\n variable ν₂ : σ.substitution\n\n lemma signature.compose_sub : ((t ↓ ν₁) ↓ ν₂) = t ↓ (ν₁ ↓ ν₂) :=\n begin\n induction t with v f ts ih,\n simp,\n dsimp at ih,\n simp [signature.term.substitute],\n ext i,\n exact ih i,\n end\n\n lemma refl_more_general : (reflexive (@signature.term.more_general σ)) :=\n begin\n intro t,\n existsi signature.substitution.id,\n exact signature.term.term_eq_term_subst_id t,\n end\n\n lemma trans_more_general : (transitive (@signature.term.more_general σ)) :=\n begin\n intros x y z hxy hyz,\n cases hxy with νx hνx,\n cases hyz with νy hνy,\n rw [← hνy, ← hνx],\n use (νx ↓ νy),\n rw signature.compose_sub,\n end\n\nend more_general_preorder\n\n\nsection\n\n variable σ : signature\n variable t : σ.term\n variable φ : σ.formula\n variable ν₁ : σ.substitution\n variable ν₂ : σ.substitution\n\n lemma signature.compose_free (h : ν₁.is_free φ) : ∀ v, (φ ↓ (ν₁.free v ↓ ν₂.free v)) = (φ ↓ (ν₁ ↓ ν₂).free v) :=\n begin\n sorry,\n end\n\n lemma signature.sub_free_eq_imp_sub_eq (h : ν₁.is_free φ) : ∀ v, (φ ↓ ν₁) ↓ ν₂ = φ ↓ (ν₁ ↓ ν₂) → (φ ↓ ν₁.free v ↓ ν₂.free v) = (φ ↓ (ν₁.free v ↓ ν₂.free v)) :=\n begin\n intro v,\n intro h',\n induction φ,\n simp,\n simp,\n simp,\n {\n exact (φ_ih h) h',\n },\n {\n simp [signature.formula.substitute],\n ext j,\n simp [signature.substitution.is_free] at h,\n simp at h',\n dsimp at φ_ih,\n exact φ_ih i (h j) (h' j),\n }\n sorry,\n sorry,\n sorry,\n sorry,\n sorry,\n sorry,\n end\n\n theorem signature.compose_sub_formula1 (h : ν₁.is_free φ) : (φ ↓ ν₁) ↓ ν₂ = φ ↓ (ν₁ ↓ ν₂) :=\n begin\n induction φ,\n refl,refl,\n {\n simp [signature.formula.substitute],\n exact φ_ih h,\n },\n {\n simp [signature.formula.substitute],\n ext i,\n dsimp at *,\n have h' := φ_ih i,\n simp [signature.substitution.is_free] at h,\n exact h' (h i),\n },\n {\n simp [signature.formula.substitute],\n ext i,\n dsimp at *,\n have h' := φ_ih i,\n simp [signature.substitution.is_free] at h,\n exact h' (h i),\n },\n {\n simp [signature.formula.substitute],\n simp [signature.substitution.is_free] at h,\n have h' := signature.compose_free σ φ_f ν₁ ν₂ (h.right) φ_v,\n simp [signature.formula.substitute] at h',\n rw ← h',\n apply signature.sub_free_eq_imp_sub_eq,\n exact h.right,\n exact φ_ih h.right,\n },\n {\n simp [signature.formula.substitute],\n simp [signature.substitution.is_free] at h,\n have h' := signature.compose_free σ φ_f ν₁ ν₂ (h.right) φ_v,\n simp [signature.formula.substitute] at h',\n rw ← h',\n apply signature.sub_free_eq_imp_sub_eq,\n exact h.right,\n exact φ_ih h.right,\n },\n {\n simp [signature.formula.substitute],\n ext i,\n exact signature.compose_sub σ (φ_ts i) _ _,\n },\n end\n\nend\n\n\n\n\ndef signature.term.equivalent {σ : signature} (t₁ t₂ : σ.term) : Prop :=\n t₁.more_general t₂ ∧ t₂.more_general t₁\n\n\nlemma signature.term.refl_equivalent {σ : signature} : reflexive (@signature.term.equivalent σ) :=\n begin \n intro t,\n use σ.id_subst,\n rw signature.term.term_eq_term_subst_id,\n use σ.id_subst,\n rw signature.term.term_eq_term_subst_id,\n end\n\nlemma signature.term.trans_equivalent {σ : signature} : transitive (@signature.term.equivalent σ) :=\n begin \n intros x y z hxy hyz,\n split,\n {\n cases hxy.left with νxy h₁,\n cases hyz.left with νyz h₂,\n use (νxy ↓ νyz),\n rw ← signature.compose_sub,\n rw [h₁, h₂],\n },\n {\n cases hxy.right with νxy h₁,\n cases hyz.right with νyz h₂,\n use (νyz ↓ νxy),\n rw ← signature.compose_sub,\n rw [h₂, h₁],\n }\n end\n\nlemma signature.term.symm_equivalent {σ : signature} : symmetric (@signature.term.equivalent σ) :=\n begin \n intros x y hxy,\n split,\n exact hxy.right,\n exact hxy.left,\n end\n\nlemma signature.term.equiv_equivalent {σ : signature} : equivalence (@signature.term.equivalent σ) :=\n begin\n split,\n exact signature.term.refl_equivalent, \n split,\n exact signature.term.symm_equivalent,\n exact signature.term.trans_equivalent, \n end\n\ninstance signature.equiv_setoid (σ : signature) : setoid σ.term :=\n {\n r := signature.term.equivalent,\n iseqv := signature.term.equiv_equivalent,\n }\n\n@[reducible]\ndef signature.term_equiv (σ : signature) := quotient σ.equiv_setoid\n\n\n\nexample (σ : signature) (t : σ.term) : ⟦t⟧ = quotient.mk t :=\n begin\n refl,\n end \n\nlemma signature.term.substitution_is_well_defined {σ : signature} (ν : σ.substitution) (t₁ t₂ : σ.term) (h : t₁ ≈ t₂) : ⟦t₁ ↓ ν⟧ = ⟦t₂ ↓ ν⟧ :=\n begin\n apply quotient.sound,\n cases h,\n split,\n cases h_left with ν_left hν_left,\n cases h_right with ν_right hν_right,\n sorry, sorry,\n end\n\ndef signature.term_equiv.substitute {σ : signature} (ν : σ.substitution) : σ.term_equiv → σ.term_equiv := \n quotient.lift (λ (t : σ.term) , ⟦t ↓ ν⟧) (signature.term.substitution_is_well_defined ν)\n\n@[reducible]\ninstance signature.subst_term_equiv (σ : signature) : σ.substitutable σ.term_equiv :=\n {\n substitute := (λ t ν, signature.term_equiv.substitute ν t)\n }\n\n\n\n", "meta": {"author": "huterguier", "repo": "atp", "sha": "f162d05c485590f6992bb7013a45f3067ce03023", "save_path": "github-repos/lean/huterguier-atp", "path": "github-repos/lean/huterguier-atp/atp-f162d05c485590f6992bb7013a45f3067ce03023/src/fo/substitution.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42632160712508727, "lm_q2_score": 0.055005292553523225, "lm_q1q2_score": 0.023449944721803617}} {"text": "inductive AltCore (α : Type)\n | default (val : α)\n | alt (name : String) (val : α)\n\ninductive Code where\n | cases (alt: AltCore Code)\n | return (id : Nat)\n\nabbrev Alt := AltCore Code\n\ndef AltCore.getCode : Alt → Code\n | .default c => c\n | .alt _ c => c\n\ndef AltCore.update (alt : Alt) (c : Code) : Alt :=\n match alt with\n | .default _ => if true then alt else .default c\n | .alt n _ => if true then alt else .alt n c\n\nexample (alt : Alt) : Code :=\n alt.getCode\n\ndef Alt.getCode' : Alt → Code\n | .default c => c\n | .alt _ c => c\n\nexample (alt : Alt) : Code :=\n if true then .return 1 else alt.getCode'\n\nexample (alt : Alt) : Code :=\n if true then alt.getCode' else .return 0\n", "meta": {"author": "leanprover", "repo": "lean4", "sha": "742d053a97bdd109a41a921facd1cd6a55e89bc7", "save_path": "github-repos/lean/leanprover-lean4", "path": "github-repos/lean/leanprover-lean4/lean4-742d053a97bdd109a41a921facd1cd6a55e89bc7/tests/lean/run/dottedNameBug.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43782349911420193, "lm_q2_score": 0.053403333942835626, "lm_q1q2_score": 0.023381234531216523}} {"text": "/-\nCopyright (c) 2020 Adam Topaz. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Bhavik Mehta, Adam Topaz\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.default\nimport Mathlib.data.fintype.basic\nimport Mathlib.data.fin\nimport Mathlib.category_theory.concrete_category.bundled\nimport Mathlib.category_theory.concrete_category.default\nimport Mathlib.category_theory.full_subcategory\nimport Mathlib.category_theory.skeletal\nimport Mathlib.PostPort\n\nuniverses u_1 \n\nnamespace Mathlib\n\n/-!\n# The category of finite types.\n\nWe define the category of finite types, denoted `Fintype` as\n(bundled) types with a `fintype` instance.\n\nWe also define `Fintype.skeleton`, the standard skeleton of `Fintype` whose objects are `fin n`\nfor `n : ℕ`. We prove that the obvious inclusion functor `Fintype.skeleton ⥤ Fintype` is an\nequivalence of categories in `Fintype.skeleton.equivalence`.\nWe prove that `Fintype.skeleton` is a skeleton of `Fintype` in `Fintype.is_skeleton`.\n-/\n\n/-- The category of finite types. -/\ndef Fintype := category_theory.bundled fintype\n\nnamespace Fintype\n\n\n/-- Construct a bundled `Fintype` from the underlying type and typeclass. -/\ndef of (X : Type u_1) [fintype X] : Fintype := category_theory.bundled.of X\n\nprotected instance inhabited : Inhabited Fintype := { default := category_theory.bundled.mk pempty }\n\nprotected instance fintype {X : Fintype} : fintype ↥X := category_theory.bundled.str X\n\nprotected instance category_theory.category : category_theory.category Fintype :=\n category_theory.induced_category.category category_theory.bundled.α\n\n/-- The fully faithful embedding of `Fintype` into the category of types. -/\n@[simp] theorem incl_map (x : category_theory.induced_category (Type u_1) category_theory.bundled.α)\n (y : category_theory.induced_category (Type u_1) category_theory.bundled.α) (f : x ⟶ y) :\n ∀ (ᾰ : category_theory.bundled.α x), category_theory.functor.map incl f ᾰ = f ᾰ :=\n fun (ᾰ : category_theory.bundled.α x) => Eq.refl (f ᾰ)\n\nprotected instance category_theory.concrete_category : category_theory.concrete_category Fintype :=\n category_theory.concrete_category.mk incl\n\n/--\nThe \"standard\" skeleton for `Fintype`. This is the full subcategory of `Fintype` spanned by objects\nof the form `fin n` for `n : ℕ`. We parameterize the objects of `Fintype.skeleton` directly as `ℕ`,\nas the type `fin m ≃ fin n` is nonempty if and only if `n = m`.\n-/\ndef skeleton := ℕ\n\nnamespace skeleton\n\n\n/-- Given any natural number `n`, this creates the associated object of `Fintype.skeleton`. -/\ndef mk : ℕ → skeleton := id\n\nprotected instance inhabited : Inhabited skeleton := { default := mk 0 }\n\n/-- Given any object of `Fintype.skeleton`, this returns the associated natural number. -/\ndef to_nat : skeleton → ℕ := id\n\nprotected instance category_theory.category : category_theory.category skeleton :=\n category_theory.category.mk\n\ntheorem is_skeletal : category_theory.skeletal skeleton := sorry\n\n/-- The canonical fully faithful embedding of `Fintype.skeleton` into `Fintype`. -/\ndef incl : skeleton ⥤ Fintype :=\n category_theory.functor.mk (fun (X : skeleton) => of (fin X))\n fun (_x _x_1 : skeleton) (f : _x ⟶ _x_1) => f\n\nprotected instance incl.category_theory.full : category_theory.full incl :=\n category_theory.full.mk\n fun (_x _x_1 : skeleton)\n (f : category_theory.functor.obj incl _x ⟶ category_theory.functor.obj incl _x_1) => f\n\nprotected instance incl.category_theory.faithful : category_theory.faithful incl :=\n category_theory.faithful.mk\n\nprotected instance incl.category_theory.ess_surj : category_theory.ess_surj incl :=\n category_theory.ess_surj.mk\n fun (X : Fintype) =>\n let F : ↥X ≃ fin (fintype.card ↥X) := trunc.out (fintype.equiv_fin ↥X);\n Exists.intro (fintype.card ↥X) (Nonempty.intro (category_theory.iso.mk ⇑(equiv.symm F) ⇑F))\n\nprotected instance incl.category_theory.is_equivalence : category_theory.is_equivalence incl :=\n category_theory.equivalence.equivalence_of_fully_faithfully_ess_surj incl\n\n/-- The equivalence between `Fintype.skeleton` and `Fintype`. -/\ndef equivalence : skeleton ≌ Fintype := category_theory.functor.as_equivalence incl\n\n@[simp] theorem incl_mk_nat_card (n : ℕ) :\n fintype.card ↥(category_theory.functor.obj incl (mk n)) = n :=\n finset.card_fin n\n\nend skeleton\n\n\n/-- `Fintype.skeleton` is a skeleton of `Fintype`. -/\ndef is_skeleton : category_theory.is_skeleton_of Fintype skeleton skeleton.incl :=\n category_theory.is_skeleton_of.mk skeleton.is_skeletal\n skeleton.incl.category_theory.is_equivalence\n\nend Mathlib", "meta": {"author": "AurelienSaue", "repo": "Mathlib4_auto", "sha": "590df64109b08190abe22358fabc3eae000943f2", "save_path": "github-repos/lean/AurelienSaue-Mathlib4_auto", "path": "github-repos/lean/AurelienSaue-Mathlib4_auto/Mathlib4_auto-590df64109b08190abe22358fabc3eae000943f2/Mathlib/category_theory/Fintype_auto.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.41869692386284973, "lm_q2_score": 0.05582314663237466, "lm_q1q2_score": 0.023372979775320067}} {"text": "/-\nCopyright (c) 2016 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Leonardo de Moura\n\n! This file was ported from Lean 3 source module init.meta.simp_tactic\n! leanprover-community/mathlib commit 4a03bdeb31b3688c31d02d7ff8e0ff2e5d6174db\n! Please do not edit these lines, except to modify the commit id\n! if you have ported upstream changes.\n-/\nprelude\nimport Leanbin.Init.Meta.Tactic\nimport Leanbin.Init.Meta.Attribute\nimport Leanbin.Init.Meta.ConstructorTactic\nimport Leanbin.Init.Meta.RelationTactics\nimport Leanbin.Init.Meta.Occurrences\nimport Leanbin.Init.Data.Option.Basic\n\nopen Tactic\n\ndef Tactic.IdTag.simp : Unit :=\n ()\n#align tactic.id_tag.simp Tactic.IdTag.simp\n\ndef Simp.defaultMaxSteps :=\n 10000000\n#align simp.default_max_steps Simp.defaultMaxSteps\n\n/-- Prefix the given `attr_name` with `\"simp_attr\"`. -/\nunsafe axiom mk_simp_attr_decl_name (attr_name : Name) : Name\n#align mk_simp_attr_decl_name mk_simp_attr_decl_name\n\n/-- Simp lemmas are used by the \"simplifier\" family of tactics.\n`simp_lemmas` is essentially a pair of tables `rb_map (expr_type × name) (priority_list simp_lemma)`.\nOne of the tables is for congruences and one is for everything else.\nAn individual simp lemma is:\n- A kind which can be `Refl`, `Simp` or `Congr`.\n- A pair of `expr`s `l ~> r`. The rb map is indexed by the name of `get_app_fn(l)`.\n- A proof that `l = r` or `l ↔ r`.\n- A list of the metavariables that must be filled before the proof can be applied.\n- A priority number\n-/\nunsafe axiom simp_lemmas : Type\n#align simp_lemmas simp_lemmas\n\n/-- Make a new table of simp lemmas -/\nunsafe axiom simp_lemmas.mk : simp_lemmas\n#align simp_lemmas.mk simp_lemmas.mk\n\n/-- Merge the simp_lemma tables. -/\nunsafe axiom simp_lemmas.join : simp_lemmas → simp_lemmas → simp_lemmas\n#align simp_lemmas.join simp_lemmas.join\n\n/-- Remove the given lemmas from the table. Use the names of the lemmas. -/\nunsafe axiom simp_lemmas.erase : simp_lemmas → List Name → simp_lemmas\n#align simp_lemmas.erase simp_lemmas.erase\n\n/-- Remove all simp lemmas from the table. -/\nunsafe axiom simp_lemmas.erase_simp_lemmas : simp_lemmas → simp_lemmas\n#align simp_lemmas.erase_simp_lemmas simp_lemmas.erase_simp_lemmas\n\n/-- Makes the default simp_lemmas table which is composed of all lemmas tagged with `simp`. -/\nunsafe axiom simp_lemmas.mk_default : tactic simp_lemmas\n#align simp_lemmas.mk_default simp_lemmas.mk_default\n\n/--\nAdd a simplification lemma by an expression `p`. Some conditions on `p` must hold for it to be added, see list below.\nIf your lemma is not being added, you can see the reasons by setting `set_option trace.simp_lemmas true`.\n\n- `p` must have the type `Π (h₁ : _) ... (hₙ : _), LHS ~ RHS` for some reflexive, transitive relation (usually `=`).\n- Any of the hypotheses `hᵢ` should either be present in `LHS` or otherwise a `Prop` or a typeclass instance.\n- `LHS` should not occur within `RHS`.\n- `LHS` should not occur within a hypothesis `hᵢ`.\n\n -/\nunsafe axiom simp_lemmas.add (s : simp_lemmas) (e : expr) (symm : Bool := False) :\n tactic simp_lemmas\n#align simp_lemmas.add simp_lemmas.add\n\n/--\nAdd a simplification lemma by it's declaration name. See `simp_lemmas.add` for more information.-/\nunsafe axiom simp_lemmas.add_simp (s : simp_lemmas) (id : Name) (symm : Bool := False) :\n tactic simp_lemmas\n#align simp_lemmas.add_simp simp_lemmas.add_simp\n\n/-- Adds a congruence simp lemma to simp_lemmas.\nA congruence simp lemma is a lemma that breaks the simplification down into separate problems.\nFor example, to simplify `a ∧ b` to `c ∧ d`, we should try to simp `a` to `c` and `b` to `d`.\nFor examples of congruence simp lemmas look for lemmas with the `@[congr]` attribute.\n```lean\nlemma if_simp_congr ... (h_c : b ↔ c) (h_t : x = u) (h_e : y = v) : ite b x y = ite c u v := ...\nlemma imp_congr_right (h : a → (b ↔ c)) : (a → b) ↔ (a → c) := ...\nlemma and_congr (h₁ : a ↔ c) (h₂ : b ↔ d) : (a ∧ b) ↔ (c ∧ d) := ...\n```\n-/\nunsafe axiom simp_lemmas.add_congr : simp_lemmas → Name → tactic simp_lemmas\n#align simp_lemmas.add_congr simp_lemmas.add_congr\n\n/-- Add expressions to a set of simp lemmas using `simp_lemmas.add`.\n\n This is the new version of `simp_lemmas.append`,\n which also allows you to set the `symm` flag.\n-/\nunsafe def simp_lemmas.append_with_symm (s : simp_lemmas) (hs : List (expr × Bool)) :\n tactic simp_lemmas :=\n hs.foldlM (fun s h => simp_lemmas.add s h.fst h.snd) s\n#align simp_lemmas.append_with_symm simp_lemmas.append_with_symm\n\n/-- Add expressions to a set of simp lemmas using `simp_lemmas.add`.\n\n This is the backwards-compatibility version of `simp_lemmas.append_with_symm`,\n and sets all `symm` flags to `ff`.\n-/\nunsafe def simp_lemmas.append (s : simp_lemmas) (hs : List expr) : tactic simp_lemmas :=\n hs.foldlM (fun s h => simp_lemmas.add s h false) s\n#align simp_lemmas.append simp_lemmas.append\n\n/-- `simp_lemmas.rewrite s e prove R` apply a simplification lemma from 's'\n\n - 'e' is the expression to be \"simplified\"\n - 'prove' is used to discharge proof obligations.\n - 'r' is the equivalence relation being used (e.g., 'eq', 'iff')\n - 'md' is the transparency; how aggresively should the simplifier perform reductions.\n\n Result (new_e, pr) is the new expression 'new_e' and a proof (pr : e R new_e) -/\nunsafe axiom simp_lemmas.rewrite (s : simp_lemmas) (e : expr) (prove : tactic Unit := failed)\n (r : Name := `eq) (md := reducible) : tactic (expr × expr)\n#align simp_lemmas.rewrite simp_lemmas.rewrite\n\nunsafe axiom simp_lemmas.rewrites (s : simp_lemmas) (e : expr) (prove : tactic Unit := failed)\n (r : Name := `eq) (md := reducible) : tactic <| List (expr × expr)\n#align simp_lemmas.rewrites simp_lemmas.rewrites\n\n/-- `simp_lemmas.drewrite s e` tries to rewrite 'e' using only refl lemmas in 's' -/\nunsafe axiom simp_lemmas.drewrite (s : simp_lemmas) (e : expr) (md := reducible) : tactic expr\n#align simp_lemmas.drewrite simp_lemmas.drewrite\n\nunsafe axiom is_valid_simp_lemma_cnst : Name → tactic Bool\n#align is_valid_simp_lemma_cnst is_valid_simp_lemma_cnst\n\nunsafe axiom is_valid_simp_lemma : expr → tactic Bool\n#align is_valid_simp_lemma is_valid_simp_lemma\n\nunsafe axiom simp_lemmas.pp : simp_lemmas → tactic format\n#align simp_lemmas.pp simp_lemmas.pp\n\nunsafe instance : has_to_tactic_format simp_lemmas :=\n ⟨simp_lemmas.pp⟩\n\nnamespace Tactic\n\n-- Remark: `transform` should not change the target.\n/-- Revert a local constant, change its type using `transform`. -/\nunsafe def revert_and_transform (transform : expr → tactic expr) (h : expr) : tactic Unit := do\n let num_reverted : ℕ ← revert h\n let t ← target\n match t with\n | expr.pi n bi d b => do\n let h_simp ← transform d\n unsafe_change <| expr.pi n bi h_simp b\n | expr.elet n g e f => do\n let h_simp ← transform g\n unsafe_change <| expr.elet n h_simp e f\n | _ => fail \"reverting hypothesis created neither a pi nor an elet expr (unreachable?)\"\n intron num_reverted\n#align tactic.revert_and_transform tactic.revert_and_transform\n\n/--\n`get_eqn_lemmas_for deps d` returns the automatically generated equational lemmas for definition d.\n If deps is tt, then lemmas for automatically generated auxiliary declarations used to define d are also included. -/\nunsafe def get_eqn_lemmas_for (deps : Bool) (d : Name) : tactic (List Name) := do\n let env ← get_env\n pure <| if deps then env d else env d\n#align tactic.get_eqn_lemmas_for tactic.get_eqn_lemmas_for\n\nstructure DsimpConfig where\n md := reducible\n -- reduction mode: how aggressively constants are replaced with their definitions.\n maxSteps : Nat := Simp.defaultMaxSteps\n -- The maximum number of steps allowed before failing.\n canonizeInstances : Bool := true\n -- See the documentation in `src/library/defeq_canonizer.h`\n singlePass : Bool := false\n -- Visit each subterm no more than once.\n failIfUnchanged := true\n -- Don't throw if dsimp didn't do anything.\n eta := true\n -- allow eta-equivalence: `(λ x, F $ x) ↝ F`\n zeta : Bool := true\n -- do zeta-reductions: `let x : a := b in c ↝ c[x/b]`.\n beta : Bool := true\n -- do beta-reductions: `(λ x, E) $ (y) ↝ E[x/y]`.\n proj : Bool := true\n -- reduce projections: `⟨a,b⟩.1 ↝ a`.\n iota : Bool := true\n -- reduce recursors for inductive datatypes: eg `nat.rec_on (succ n) Z R ↝ R n $ nat.rec_on n Z R`\n unfoldReducible := false\n -- if tt, definitions with `reducible` transparency will be unfolded (delta-reduced)\n memoize := true\n#align tactic.dsimp_config Tactic.DsimpConfig\n\n-- Perform caching of dsimps of subterms.\nend Tactic\n\n/--\n(Definitional) Simplify the given expression using *only* reflexivity equality lemmas from the given set of lemmas.\n The resulting expression is definitionally equal to the input.\n\n The list `u` contains defintions to be delta-reduced, and projections to be reduced.-/\nunsafe axiom simp_lemmas.dsimplify (s : simp_lemmas) (u : List Name := []) (e : expr)\n (cfg : Tactic.DsimpConfig := { }) : tactic expr\n#align simp_lemmas.dsimplify simp_lemmas.dsimplify\n\nnamespace Tactic\n\n/-- Remark: the configuration parameters `cfg.md` and `cfg.eta` are ignored by this tactic. -/\nunsafe axiom dsimplify_core\n -- The user state type.\n {α : Type}\n -- Initial user data\n (a : α)\n /- (pre a e) is invoked before visiting the children of subterm 'e',\n if it succeeds the result (new_a, new_e, flag) where\n - 'new_a' is the new value for the user data\n - 'new_e' is a new expression that must be definitionally equal to 'e',\n - 'flag' if tt 'new_e' children should be visited, and 'post' invoked. -/\n (pre : α → expr → tactic (α × expr × Bool))\n /- (post a e) is invoked after visiting the children of subterm 'e',\n The output is similar to (pre a e), but the 'flag' indicates whether\n the new expression should be revisited or not. -/\n (post : α → expr → tactic (α × expr × Bool))\n (e : expr) (cfg : DsimpConfig := { }) : tactic (α × expr)\n#align tactic.dsimplify_core tactic.dsimplify_core\n\nunsafe def dsimplify (pre : expr → tactic (expr × Bool)) (post : expr → tactic (expr × Bool)) :\n expr → tactic expr := fun e => do\n let (a, new_e) ←\n dsimplify_core ()\n (fun u e => do\n let r ← pre e\n return (u, r))\n (fun u e => do\n let r ← post e\n return (u, r))\n e\n return new_e\n#align tactic.dsimplify tactic.dsimplify\n\nunsafe def get_simp_lemmas_or_default : Option simp_lemmas → tactic simp_lemmas\n | none => simp_lemmas.mk_default\n | some s => return s\n#align tactic.get_simp_lemmas_or_default tactic.get_simp_lemmas_or_default\n\nunsafe def dsimp_target (s : Option simp_lemmas := none) (u : List Name := [])\n (cfg : DsimpConfig := { }) : tactic Unit := do\n let s ← get_simp_lemmas_or_default s\n let t ← target >>= instantiate_mvars\n s u t cfg >>= unsafe_change\n#align tactic.dsimp_target tactic.dsimp_target\n\nunsafe def dsimp_hyp (h : expr) (s : Option simp_lemmas := none) (u : List Name := [])\n (cfg : DsimpConfig := { }) : tactic Unit := do\n let s ← get_simp_lemmas_or_default s\n revert_and_transform (fun e => s u e cfg) h\n#align tactic.dsimp_hyp tactic.dsimp_hyp\n\n/- Remark: we use transparency.instances by default to make sure that we\n can unfold projections of type classes. Example:\n\n (@has_add.add nat nat.has_add a b)\n-/\n/-- Tries to unfold `e` if it is a constant or a constant application.\n Remark: this is not a recursive procedure. -/\nunsafe axiom dunfold_head (e : expr) (md := Transparency.instances) : tactic expr\n#align tactic.dunfold_head tactic.dunfold_head\n\nstructure DunfoldConfig extends DsimpConfig where\n md := Transparency.instances\n#align tactic.dunfold_config Tactic.DunfoldConfig\n\n/-! Remark: in principle, dunfold can be implemented on top of dsimp. We don't do it for\n performance reasons. -/\n\n\nunsafe axiom dunfold (cs : List Name) (e : expr) (cfg : DunfoldConfig := { }) : tactic expr\n#align tactic.dunfold tactic.dunfold\n\nunsafe def dunfold_target (cs : List Name) (cfg : DunfoldConfig := { }) : tactic Unit := do\n let t ← target\n dunfold cs t cfg >>= unsafe_change\n#align tactic.dunfold_target tactic.dunfold_target\n\nunsafe def dunfold_hyp (cs : List Name) (h : expr) (cfg : DunfoldConfig := { }) : tactic Unit :=\n revert_and_transform (fun e => dunfold cs e cfg) h\n#align tactic.dunfold_hyp tactic.dunfold_hyp\n\nstructure DeltaConfig where\n maxSteps := Simp.defaultMaxSteps\n visitInstances := true\n#align tactic.delta_config Tactic.DeltaConfig\n\nprivate unsafe def is_delta_target (e : expr) (cs : List Name) : Bool :=\n cs.any fun c =>\n if e.is_app_of c then true\n else-- Exact match\n let f := e.get_app_fn\n -- f is an auxiliary constant generated when compiling c\n f.is_constant &&\n f.const_name.is_internal &&\n f.const_name.getPrefix = c\n#align tactic.is_delta_target tactic.is_delta_target\n\n/-- Delta reduce the given constant names -/\nunsafe def delta (cs : List Name) (e : expr) (cfg : DeltaConfig := { }) : tactic expr :=\n let unfold (u : Unit) (e : expr) : tactic (Unit × expr × Bool) := do\n guard (is_delta_target e cs)\n let expr.const f_name f_lvls ← return e.get_app_fn\n let env ← get_env\n let decl ← env.get f_name\n let new_f ← decl.instantiate_value_univ_params f_lvls\n let new_e ← head_beta (expr.mk_app new_f e.get_app_args)\n return (u, new_e, tt)\n do\n let (c, new_e) ←\n dsimplify_core () (fun c e => failed) unfold e\n { maxSteps := cfg.maxSteps\n canonizeInstances := cfg.visitInstances }\n return new_e\n#align tactic.delta tactic.delta\n\nunsafe def delta_target (cs : List Name) (cfg : DeltaConfig := { }) : tactic Unit := do\n let t ← target\n delta cs t cfg >>= unsafe_change\n#align tactic.delta_target tactic.delta_target\n\nunsafe def delta_hyp (cs : List Name) (h : expr) (cfg : DeltaConfig := { }) : tactic Unit :=\n revert_and_transform (fun e => delta cs e cfg) h\n#align tactic.delta_hyp tactic.delta_hyp\n\nstructure UnfoldProjConfig extends DsimpConfig where\n md := Transparency.instances\n#align tactic.unfold_proj_config Tactic.UnfoldProjConfig\n\n/-- If `e` is a projection application, try to unfold it, otherwise fail. -/\nunsafe axiom unfold_proj (e : expr) (md := Transparency.instances) : tactic expr\n#align tactic.unfold_proj tactic.unfold_proj\n\nunsafe def unfold_projs (e : expr) (cfg : UnfoldProjConfig := { }) : tactic expr :=\n let unfold (changed : Bool) (e : expr) : tactic (Bool × expr × Bool) := do\n let new_e ← unfold_proj e cfg.md\n return (tt, new_e, tt)\n do\n let (tt, new_e) ← dsimplify_core false (fun c e => failed) unfold e cfg.toDsimpConfig |\n fail \"no projections to unfold\"\n return new_e\n#align tactic.unfold_projs tactic.unfold_projs\n\nunsafe def unfold_projs_target (cfg : UnfoldProjConfig := { }) : tactic Unit := do\n let t ← target\n unfold_projs t cfg >>= unsafe_change\n#align tactic.unfold_projs_target tactic.unfold_projs_target\n\nunsafe def unfold_projs_hyp (h : expr) (cfg : UnfoldProjConfig := { }) : tactic Unit :=\n revert_and_transform (fun e => unfold_projs e cfg) h\n#align tactic.unfold_projs_hyp tactic.unfold_projs_hyp\n\nstructure SimpConfig where\n maxSteps : Nat := Simp.defaultMaxSteps\n contextual : Bool := false\n liftEq : Bool := true\n canonizeInstances : Bool := true\n canonizeProofs : Bool := false\n useAxioms : Bool := true\n zeta : Bool := true\n beta : Bool := true\n eta : Bool := true\n proj : Bool := true\n -- reduce projections\n iota : Bool := true\n iotaEqn : Bool := false\n -- reduce using all equation lemmas generated by equation/pattern-matching compiler\n constructorEq : Bool := true\n singlePass : Bool := false\n failIfUnchanged := true\n memoize := true\n traceLemmas := false\n#align tactic.simp_config Tactic.SimpConfig\n\n/-- `simplify s e cfg r prove` simplify `e` using `s` using bottom-up traversal.\n `discharger` is a tactic for dischaging new subgoals created by the simplifier.\n If it fails, the simplifier tries to discharge the subgoal by simplifying it to `true`.\n\n The parameter `to_unfold` specifies definitions that should be delta-reduced,\n and projection applications that should be unfolded.\n-/\nunsafe axiom simplify (s : simp_lemmas) (to_unfold : List Name := []) (e : expr)\n (cfg : SimpConfig := { }) (r : Name := `eq) (discharger : tactic Unit := failed) :\n tactic (expr × expr × name_set)\n#align tactic.simplify tactic.simplify\n\nunsafe def simp_target (s : simp_lemmas) (to_unfold : List Name := []) (cfg : SimpConfig := { })\n (discharger : tactic Unit := failed) : tactic name_set := do\n let t ← target >>= instantiate_mvars\n let (new_t, pr, lms) ← simplify s to_unfold t cfg `eq discharger\n replace_target new_t pr `` id_tag.simp\n return lms\n#align tactic.simp_target tactic.simp_target\n\nunsafe def simp_hyp (s : simp_lemmas) (to_unfold : List Name := []) (h : expr)\n (cfg : SimpConfig := { }) (discharger : tactic Unit := failed) : tactic (expr × name_set) := do\n when (expr.is_local_constant h = ff)\n (fail \"tactic simp_at failed, the given expression is not a hypothesis\")\n let htype ← infer_type h\n let (h_new_type, pr, lms) ← simplify s to_unfold htype cfg `eq discharger\n let new_hyp ← replace_hyp h h_new_type pr `` id_tag.simp\n return (new_hyp, lms)\n#align tactic.simp_hyp tactic.simp_hyp\n\n/-- `ext_simplify_core a c s discharger pre post r e`:\n\n- `a : α` - initial user data\n- `c : simp_config` - simp configuration options\n- `s : simp_lemmas` - the set of simp_lemmas to use. Remark: the simplification lemmas are not applied automatically like in the simplify tactic. The caller must use them at pre/post.\n- `discharger : α → tactic α` - tactic for dischaging hypothesis in conditional rewriting rules. The argument 'α' is the current user data.\n- `pre a s r p e` is invoked before visiting the children of subterm 'e'.\n + arguments:\n - `a` is the current user data\n - `s` is the updated set of lemmas if 'contextual' is `tt`,\n - `r` is the simplification relation being used,\n - `p` is the \"parent\" expression (if there is one).\n - `e` is the current subexpression in question.\n + if it succeeds the result is `(new_a, new_e, new_pr, flag)` where\n - `new_a` is the new value for the user data\n - `new_e` is a new expression s.t. `r e new_e`\n - `new_pr` is a proof for `r e new_e`, If it is none, the proof is assumed to be by reflexivity\n - `flag` if tt `new_e` children should be visited, and `post` invoked.\n- `(post a s r p e)` is invoked after visiting the children of subterm `e`,\n The output is similar to `(pre a r s p e)`, but the 'flag' indicates whether the new expression should be revisited or not.\n- `r` is the simplification relation. Usually `=` or `↔`.\n- `e` is the input expression to be simplified.\n\nThe method returns `(a,e,pr)` where\n\n - `a` is the final user data\n - `e` is the new expression\n - `pr` is the proof that the given expression equals the input expression.\n\nNote that `ext_simplify_core` will succeed even if `pre` and `post` fail, as failures are used to indicate that the method should move on to the next subterm.\nIf it is desirable to propagate errors from `pre`, they can be propagated through the \"user data\".\nAn easy way to do this is to call `tactic.capture (do ...)` in the parts of `pre`/`post` where errors matter, and then use `tactic.unwrap a` on the result.\n\nAdditionally, `ext_simplify_core` does not propagate changes made to the tactic state by `pre` and `post.\nIf it is desirable to propagate changes to the tactic state in addition to errors, use `tactic.resume` instead of `tactic.unwrap`.\n-/\nunsafe axiom ext_simplify_core {α : Type} (a : α) (c : SimpConfig) (s : simp_lemmas)\n (discharger : α → tactic α)\n (pre : α → simp_lemmas → Name → Option expr → expr → tactic (α × expr × Option expr × Bool))\n (post : α → simp_lemmas → Name → Option expr → expr → tactic (α × expr × Option expr × Bool))\n (r : Name) : expr → tactic (α × expr × expr)\n#align tactic.ext_simplify_core tactic.ext_simplify_core\n\nprivate unsafe def is_equation : expr → Bool\n | expr.pi n bi d b => is_equation b\n | e =>\n match expr.is_eq e with\n | some a => true\n | none => false\n#align tactic.is_equation tactic.is_equation\n\nunsafe def collect_ctx_simps : tactic (List expr) :=\n local_context\n#align tactic.collect_ctx_simps tactic.collect_ctx_simps\n\nsection SimpIntros\n\nunsafe def intro1_aux : Bool → List Name → tactic expr\n | ff, _ => intro1\n | tt, n :: ns => intro n\n | _, _ => failed\n#align tactic.intro1_aux tactic.intro1_aux\n\nstructure SimpIntrosConfig extends SimpConfig where\n useHyps := false\n#align tactic.simp_intros_config Tactic.SimpIntrosConfig\n\nunsafe def simp_intros_aux (cfg : SimpConfig) (use_hyps : Bool) (to_unfold : List Name) :\n simp_lemmas → Bool → List Name → tactic simp_lemmas\n | S, tt, [] => try (simp_target S to_unfold cfg) >> return S\n | S, use_ns, ns => do\n let t ← target\n if t `not 1 then intro1_aux use_ns ns >> simp_intros_aux S use_ns ns\n else\n if t then\n (do\n let d ← return t\n let (new_d, h_d_eq_new_d, lms) ← simplify S to_unfold d cfg\n let h_d ← intro1_aux use_ns ns\n let h_new_d ← mk_eq_mp h_d_eq_new_d h_d\n assertv_core h_d new_d h_new_d\n clear h_d\n let h_new ← intro1\n let new_S ←\n if use_hyps then condM (is_prop new_d) (S h_new ff) (return S) else return S\n simp_intros_aux new_S use_ns\n ns) <|>-- failed to simplify... we just introduce and continue\n intro1_aux\n use_ns ns >>\n simp_intros_aux S use_ns ns\n else\n if t || t then intro1_aux use_ns ns >> simp_intros_aux S use_ns ns\n else do\n let new_t ← whnf t reducible\n if new_t then unsafe_change new_t >> simp_intros_aux S use_ns ns\n else\n try (simp_target S to_unfold cfg) >>\n condM (expr.is_pi <$> target) (simp_intros_aux S use_ns ns)\n (if use_ns ∧ ¬ns then failed else return S)\n#align tactic.simp_intros_aux tactic.simp_intros_aux\n\nunsafe def simp_intros (s : simp_lemmas) (to_unfold : List Name := []) (ids : List Name := [])\n (cfg : SimpIntrosConfig := { }) : tactic Unit :=\n step <| simp_intros_aux cfg.toSimpConfig cfg.useHyps to_unfold s (not ids.Empty) ids\n#align tactic.simp_intros tactic.simp_intros\n\nend SimpIntros\n\nunsafe def mk_eq_simp_ext (simp_ext : expr → tactic (expr × expr)) : tactic Unit := do\n let (lhs, rhs) ← target >>= match_eq\n let (new_rhs, HEq) ← simp_ext lhs\n unify rhs new_rhs\n exact HEq\n#align tactic.mk_eq_simp_ext tactic.mk_eq_simp_ext\n\n/-! Simp attribute support -/\n\n\nunsafe def to_simp_lemmas : simp_lemmas → List Name → tactic simp_lemmas\n | S, [] => return S\n | S, n :: ns => do\n let S' ← has_attribute `congr n >> S.add_congr n <|> S.add_simp n false\n to_simp_lemmas S' ns\n#align tactic.to_simp_lemmas tactic.to_simp_lemmas\n\nunsafe def mk_simp_attr (attr_name : Name) (attr_deps : List Name := []) : Tactic := do\n let t := q(user_attribute simp_lemmas)\n let v :=\n q(({ Name := attr_name\n descr := \"simplifier attribute\"\n cache_cfg :=\n { mk_cache := fun ns => do\n let s ← tactic.to_simp_lemmas simp_lemmas.mk ns\n let s ←\n attr_deps.foldlM\n (fun s attr_name => do\n let ns ← attribute.get_instances attr_name\n to_simp_lemmas s ns)\n s\n return s\n dependencies := `reducibility :: attr_deps } } :\n user_attribute simp_lemmas))\n let n := mk_simp_attr_decl_name attr_name\n add_decl (declaration.defn n [] t v ReducibilityHints.abbrev ff)\n attribute.register n\n#align tactic.mk_simp_attr tactic.mk_simp_attr\n\n/-- ### Example usage:\n```lean\n-- make a new simp attribute called \"my_reduction\"\nrun_cmd mk_simp_attr `my_reduction\n-- Add \"my_reduction\" attributes to these if-reductions\nattribute [my_reduction] if_pos if_neg dif_pos dif_neg\n\n-- will return the simp_lemmas with the `my_reduction` attribute.\n#eval get_user_simp_lemmas `my_reduction\n\n```\n -/\nunsafe def get_user_simp_lemmas (attr_name : Name) : tactic simp_lemmas :=\n if attr_name = `default then simp_lemmas.mk_default\n else get_attribute_cache_dyn (mk_simp_attr_decl_name attr_name)\n#align tactic.get_user_simp_lemmas tactic.get_user_simp_lemmas\n\nunsafe def join_user_simp_lemmas_core : simp_lemmas → List Name → tactic simp_lemmas\n | S, [] => return S\n | S, attr_name :: R => do\n let S' ← get_user_simp_lemmas attr_name\n join_user_simp_lemmas_core (S S') R\n#align tactic.join_user_simp_lemmas_core tactic.join_user_simp_lemmas_core\n\nunsafe def join_user_simp_lemmas (no_dflt : Bool) (attrs : List Name) : tactic simp_lemmas := do\n let s ← simp_lemmas.mk_default\n let s := if no_dflt then s.erase_simp_lemmas else s\n join_user_simp_lemmas_core s attrs\n#align tactic.join_user_simp_lemmas tactic.join_user_simp_lemmas\n\nunsafe def simplify_top_down {α} (a : α) (pre : α → expr → tactic (α × expr × expr)) (e : expr)\n (cfg : SimpConfig := { }) : tactic (α × expr × expr) :=\n ext_simplify_core a cfg simp_lemmas.mk (fun _ => failed)\n (fun a _ _ _ e => do\n let (new_a, new_e, pr) ← pre a e\n guard ¬new_e == e\n return (new_a, new_e, some pr, tt))\n (fun _ _ _ _ _ => failed) `eq e\n#align tactic.simplify_top_down tactic.simplify_top_down\n\nunsafe def simp_top_down (pre : expr → tactic (expr × expr)) (cfg : SimpConfig := { }) :\n tactic Unit := do\n let t ← target\n let (_, new_target, pr) ←\n simplify_top_down ()\n (fun _ e => do\n let (new_e, pr) ← pre e\n return ((), new_e, pr))\n t cfg\n replace_target new_target pr `` id_tag.simp\n#align tactic.simp_top_down tactic.simp_top_down\n\nunsafe def simplify_bottom_up {α} (a : α) (post : α → expr → tactic (α × expr × expr)) (e : expr)\n (cfg : SimpConfig := { }) : tactic (α × expr × expr) :=\n ext_simplify_core a cfg simp_lemmas.mk (fun _ => failed) (fun _ _ _ _ _ => failed)\n (fun a _ _ _ e => do\n let (new_a, new_e, pr) ← post a e\n guard ¬new_e == e\n return (new_a, new_e, some pr, tt))\n `eq e\n#align tactic.simplify_bottom_up tactic.simplify_bottom_up\n\nunsafe def simp_bottom_up (post : expr → tactic (expr × expr)) (cfg : SimpConfig := { }) :\n tactic Unit := do\n let t ← target\n let (_, new_target, pr) ←\n simplify_bottom_up ()\n (fun _ e => do\n let (new_e, pr) ← post e\n return ((), new_e, pr))\n t cfg\n replace_target new_target pr `` id_tag.simp\n#align tactic.simp_bottom_up tactic.simp_bottom_up\n\nprivate unsafe def remove_deps (s : name_set) (h : expr) : name_set :=\n if s.Empty then s\n else h.fold s fun e o s => if e.is_local_constant then s.eraseₓ e.local_uniq_name else s\n#align tactic.remove_deps tactic.remove_deps\n\n/-- Return the list of hypothesis that are propositions and do not have\n forward dependencies. -/\nunsafe def non_dep_prop_hyps : tactic (List expr) := do\n let ctx ← local_context\n let s ←\n ctx.foldlM\n (fun s h => do\n let h_type ← infer_type h\n let s := remove_deps s h_type\n let h_val ← head_zeta h\n let s := if h_val == h then s else remove_deps s h_val\n condM (is_prop h_type) (return <| s h) (return s))\n mk_name_set\n let t ← target\n let s := remove_deps s t\n return <| ctx fun h => s h\n#align tactic.non_dep_prop_hyps tactic.non_dep_prop_hyps\n\nsection SimpAll\n\nunsafe structure simp_all_entry where\n h : expr\n -- hypothesis\n new_type : expr\n -- new type\n pr : Option expr\n -- proof that type of h is equal to new_type\n s : simp_lemmas\n#align tactic.simp_all_entry tactic.simp_all_entry\n\n-- simplification lemmas for simplifying new_type\nprivate unsafe def update_simp_lemmas (es : List simp_all_entry) (h : expr) :\n tactic (List simp_all_entry) :=\n es.mapM fun e => do\n let new_s ← e.s.add h false\n return { e with s := new_s }\n#align tactic.update_simp_lemmas tactic.update_simp_lemmas\n\n/-- Helper tactic for `init`.\n Remark: the following tactic is quadratic on the length of list expr (the list of non dependent propositions).\n We can make it more efficient as soon as we have an efficient simp_lemmas.erase. -/\nprivate unsafe def init_aux :\n List expr → simp_lemmas → List simp_all_entry → tactic (simp_lemmas × List simp_all_entry)\n | [], s, r => return (s, r)\n | h :: hs, s, r => do\n let new_r ← update_simp_lemmas r h\n let new_s ← s.add h false\n let h_type ← infer_type h\n init_aux hs new_s (⟨h, h_type, none, s⟩ :: new_r)\n#align tactic.init_aux tactic.init_aux\n\nprivate unsafe def init (s : simp_lemmas) (hs : List expr) :\n tactic (simp_lemmas × List simp_all_entry) :=\n init_aux hs s []\n#align tactic.init tactic.init\n\nprivate unsafe def add_new_hyps (es : List simp_all_entry) : tactic Unit :=\n es.mapM' fun e =>\n match e.pr with\n | none => return ()\n | some pr => assert e.h.local_pp_name e.new_type >> mk_eq_mp pr e.h >>= exact\n#align tactic.add_new_hyps tactic.add_new_hyps\n\nprivate unsafe def clear_old_hyps (es : List simp_all_entry) : tactic Unit :=\n es.mapM' fun e => when (e.pr ≠ none) (try (clear e.h))\n#align tactic.clear_old_hyps tactic.clear_old_hyps\n\nprivate unsafe def join_pr : Option expr → expr → tactic expr\n | none, pr₂ => return pr₂\n | some pr₁, pr₂ => mk_eq_trans pr₁ pr₂\n#align tactic.join_pr tactic.join_pr\n\nprivate unsafe def loop (cfg : SimpConfig) (discharger : tactic Unit) (to_unfold : List Name) :\n List simp_all_entry → List simp_all_entry → simp_lemmas → Bool → tactic name_set\n | [], r, s, m =>\n if m then loop r [] s false\n else do\n add_new_hyps r\n let (lms, target_changed) ←\n (simp_target s to_unfold cfg discharger >>= fun ns => return (ns, true)) <|>\n return (mk_name_set, false)\n guard (cfg = ff ∨ target_changed ∨ r fun e => e ≠ none) <|>\n fail \"simp_all tactic failed to simplify\"\n clear_old_hyps r\n return lms\n | e :: es, r, s, m => do\n let ⟨h, h_type, h_pr, s'⟩ := e\n let (new_h_type, new_pr, lms) ←\n simplify s' to_unfold h_type { cfg with failIfUnchanged := false } `eq discharger\n if h_type == new_h_type then do\n let new_lms ← loop es (e :: r) s m\n return (new_lms lms fun n ns => name_set.insert ns n)\n else do\n let new_pr ← join_pr h_pr new_pr\n let new_fact_pr ← mk_eq_mp new_pr h\n if new_h_type = q(False) then do\n let tgt ← target\n to_expr ``(@False.ndrec $(tgt) $(new_fact_pr)) >>= exact\n return mk_name_set\n else do\n let h0_type ← infer_type h\n let new_fact_pr := mk_tagged_proof new_h_type new_fact_pr `` id_tag.simp\n let new_es ← update_simp_lemmas es new_fact_pr\n let new_r ← update_simp_lemmas r new_fact_pr\n let new_r :=\n { e with\n new_type := new_h_type\n pr := new_pr } ::\n new_r\n let new_s ← s new_fact_pr ff\n let new_lms ← loop new_es new_r new_s tt\n return (new_lms lms fun n ns => name_set.insert ns n)\n#align tactic.loop tactic.loop\n\nunsafe def simp_all (s : simp_lemmas) (to_unfold : List Name) (cfg : SimpConfig := { })\n (discharger : tactic Unit := failed) : tactic name_set := do\n let hs ← non_dep_prop_hyps\n let (s, es) ← init s hs\n loop cfg discharger to_unfold es [] s ff\n#align tactic.simp_all tactic.simp_all\n\nend SimpAll\n\n/-! debugging support for algebraic normalizer -/\n\n\nunsafe axiom trace_algebra_info : expr → tactic Unit\n#align tactic.trace_algebra_info tactic.trace_algebra_info\n\nend Tactic\n\nexport Tactic (mk_simp_attr)\n\nrun_cmd\n mk_simp_attr `norm [`simp]\n\n", "meta": {"author": "leanprover-community", "repo": "lean3port", "sha": "9ed1898f23e4379865ee93d62cb6353e5ed6c270", "save_path": "github-repos/lean/leanprover-community-lean3port", "path": "github-repos/lean/leanprover-community-lean3port/lean3port-9ed1898f23e4379865ee93d62cb6353e5ed6c270/Leanbin/Init/Meta/SimpTactic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41869690935568665, "lm_q2_score": 0.055823140741917285, "lm_q1q2_score": 0.02337297649916828}} {"text": "@[simp] theorem liftOn_mk (a : α) (f : α → γ) (h : ∀ a₁ a₂, r a₁ a₂ → f a₁ = f a₂) :\n Quot.liftOn (Quot.mk r a) f h = f a := rfl\n\ntheorem eq_iff_true_of_subsingleton [Subsingleton α] (x y : α) : x = y ↔ True :=\n iff_true _ ▸ Subsingleton.elim ..\n\nsection attribute [simp] eq_iff_true_of_subsingleton end\n\n@[simp] theorem PUnit.default_eq_unit : (default : PUnit) = PUnit.unit := rfl\n\nset_option trace.Meta.Tactic.simp.discharge true\nset_option trace.Meta.Tactic.simp.unify true\nset_option trace.Meta.Tactic.simp.rewrite true\nexample : (default : PUnit) = x := by simp\n", "meta": {"author": "leanprover", "repo": "lean4", "sha": "742d053a97bdd109a41a921facd1cd6a55e89bc7", "save_path": "github-repos/lean/leanprover-lean4", "path": "github-repos/lean/leanprover-lean4/lean4-742d053a97bdd109a41a921facd1cd6a55e89bc7/tests/lean/discrTreeIota.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4455295350395727, "lm_q2_score": 0.05184547012917415, "lm_q1q2_score": 0.023098688200559013}} {"text": "/-\nCopyright (c) 2016 Jeremy Avigad. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Jeremy Avigad, Leonardo de Moura\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.default\nimport Mathlib.tactic.doc_commands\nimport Mathlib.tactic.reserved_notation\nimport Mathlib.PostPort\n\nuniverses u_1 u_2 u_3 u_4 u l w v \n\nnamespace Mathlib\n\n/-!\n# Basic logic properties\n\nThis file is one of the earliest imports in mathlib.\n\n## Implementation notes\n\nTheorems that require decidability hypotheses are in the namespace \"decidable\".\nClassical versions are in the namespace \"classical\".\n\nIn the presence of automation, this whole file may be unnecessary. On the other hand,\nmaybe it is useful for writing automation.\n-/\n\n/- We add the `inline` attribute to optimize VM computation using these declarations. For example,\n `if p ∧ q then ... else ...` will not evaluate the decidability of `q` if `p` is false. -/\n\n/-- An identity function with its main argument implicit. This will be printed as `hidden` even\nif it is applied to a large term, so it can be used for elision,\nas done in the `elide` and `unelide` tactics. -/\ndef hidden {α : Sort u_1} {a : α} : α :=\n a\n\n/-- Ex falso, the nondependent eliminator for the `empty` type. -/\ndef empty.elim {C : Sort u_1} : empty → C :=\n sorry\n\nprotected instance empty.subsingleton : subsingleton empty :=\n subsingleton.intro fun (a : empty) => empty.elim a\n\nprotected instance subsingleton.prod {α : Type u_1} {β : Type u_2} [subsingleton α] [subsingleton β] : subsingleton (α × β) :=\n subsingleton.intro\n fun (a b : α × β) =>\n prod.cases_on a\n fun (a_fst : α) (a_snd : β) =>\n prod.cases_on b\n fun (b_fst : α) (b_snd : β) =>\n (fun (fst fst_1 : α) (snd snd_1 : β) =>\n Eq.trans ((fun (fst : α) (snd : β) => Eq.refl (fst, snd)) fst snd)\n (congr (congr (Eq.refl Prod.mk) (subsingleton.elim fst fst_1)) (subsingleton.elim snd snd_1)))\n a_fst b_fst a_snd b_snd\n\nprotected instance empty.decidable_eq : DecidableEq empty :=\n fun (a : empty) => empty.elim a\n\nprotected instance sort.inhabited : Inhabited (Sort u_1) :=\n { default := PUnit }\n\nprotected instance sort.inhabited' : Inhabited Inhabited.default :=\n { default := PUnit.unit }\n\nprotected instance psum.inhabited_left {α : Sort u_1} {β : Sort u_2} [Inhabited α] : Inhabited (psum α β) :=\n { default := psum.inl Inhabited.default }\n\nprotected instance psum.inhabited_right {α : Sort u_1} {β : Sort u_2} [Inhabited β] : Inhabited (psum α β) :=\n { default := psum.inr Inhabited.default }\n\nprotected instance decidable_eq_of_subsingleton {α : Sort u_1} [subsingleton α] : DecidableEq α :=\n sorry\n\n@[simp] theorem eq_iff_true_of_subsingleton {α : Type u_1} [subsingleton α] (x : α) (y : α) : x = y ↔ True :=\n of_eq_true (Eq.trans (iff_eq_of_eq_true_right (Eq.refl True)) (eq_true_intro (Eq.symm (subsingleton.elim y x))))\n\n/-- Add an instance to \"undo\" coercion transitivity into a chain of coercions, because\n most simp lemmas are stated with respect to simple coercions and will not match when\n part of a chain. -/\n@[simp] theorem coe_coe {α : Sort u_1} {β : Sort u_2} {γ : Sort u_3} [has_coe α β] [has_coe_t β γ] (a : α) : ↑a = ↑↑a :=\n rfl\n\ntheorem coe_fn_coe_trans {α : Sort u_1} {β : Sort u_2} {γ : Sort u_3} [has_coe α β] [has_coe_t_aux β γ] [has_coe_to_fun γ] (x : α) : ⇑x = ⇑↑x :=\n rfl\n\n@[simp] theorem coe_fn_coe_base {α : Sort u_1} {β : Sort u_2} [has_coe α β] [has_coe_to_fun β] (x : α) : ⇑x = ⇑↑x :=\n rfl\n\ntheorem coe_sort_coe_trans {α : Sort u_1} {β : Sort u_2} {γ : Sort u_3} [has_coe α β] [has_coe_t_aux β γ] [has_coe_to_sort γ] (x : α) : ↥x = ↥↑x :=\n rfl\n\n/--\nMany structures such as bundled morphisms coerce to functions so that you can\ntransparently apply them to arguments. For example, if `e : α ≃ β` and `a : α`\nthen you can write `e a` and this is elaborated as `⇑e a`. This type of\ncoercion is implemented using the `has_coe_to_fun` type class. There is one\nimportant consideration:\n\nIf a type coerces to another type which in turn coerces to a function,\nthen it **must** implement `has_coe_to_fun` directly:\n```lean\nstructure sparkling_equiv (α β) extends α ≃ β\n\n-- if we add a `has_coe` instance,\n\n-- if we add a `has_coe` instance,\ninstance {α β} : has_coe (sparkling_equiv α β) (α ≃ β) :=\n⟨sparkling_equiv.to_equiv⟩\n\n-- then a `has_coe_to_fun` instance **must** be added as well:\n\n-- then a `has_coe_to_fun` instance **must** be added as well:\ninstance {α β} : has_coe_to_fun (sparkling_equiv α β) :=\n⟨λ _, α → β, λ f, f.to_equiv.to_fun⟩\n```\n\n(Rationale: if we do not declare the direct coercion, then `⇑e a` is not in\nsimp-normal form. The lemma `coe_fn_coe_base` will unfold it to `⇑↑e a`. This\noften causes loops in the simplifier.)\n-/\n@[simp] theorem coe_sort_coe_base {α : Sort u_1} {β : Sort u_2} [has_coe α β] [has_coe_to_sort β] (x : α) : ↥x = ↥↑x :=\n rfl\n\n/-- `pempty` is the universe-polymorphic analogue of `empty`. -/\ninductive pempty \nwhere\n\n/-- Ex falso, the nondependent eliminator for the `pempty` type. -/\ndef pempty.elim {C : Sort u_1} : pempty → C :=\n sorry\n\nprotected instance subsingleton_pempty : subsingleton pempty :=\n subsingleton.intro fun (a : pempty) => pempty.elim a\n\n@[simp] theorem not_nonempty_pempty : ¬Nonempty pempty :=\n fun (_x : Nonempty pempty) =>\n (fun (_a : Nonempty pempty) => nonempty.dcases_on _a fun (val : pempty) => idRhs False (pempty.elim val)) _x\n\n@[simp] theorem forall_pempty {P : pempty → Prop} : (∀ (x : pempty), P x) ↔ True :=\n { mp := fun (h : ∀ (x : pempty), P x) => trivial,\n mpr := fun (h : True) (x : pempty) => pempty.cases_on (fun (x : pempty) => P x) x }\n\n@[simp] theorem exists_pempty {P : pempty → Prop} : (∃ (x : pempty), P x) ↔ False := sorry\n\ntheorem congr_arg_heq {α : Sort u_1} {β : α → Sort u_2} (f : (a : α) → β a) {a₁ : α} {a₂ : α} : a₁ = a₂ → f a₁ == f a₂ := sorry\n\ntheorem plift.down_inj {α : Sort u_1} (a : plift α) (b : plift α) : plift.down a = plift.down b → a = b := sorry\n\n-- missing [symm] attribute for ne in core.\n\ntheorem ne_comm {α : Sort u_1} {a : α} {b : α} : a ≠ b ↔ b ≠ a :=\n { mp := ne.symm, mpr := ne.symm }\n\n@[simp] theorem eq_iff_eq_cancel_left {α : Type u_1} {b : α} {c : α} : (∀ {a : α}, a = b ↔ a = c) ↔ b = c :=\n { mp :=\n fun (h : ∀ {a : α}, a = b ↔ a = c) => eq.mpr (id (Eq._oldrec (Eq.refl (b = c)) (Eq.symm (propext h)))) (Eq.refl b),\n mpr := fun (h : b = c) (a : α) => eq.mpr (id (Eq._oldrec (Eq.refl (a = b ↔ a = c)) h)) (iff.refl (a = c)) }\n\n@[simp] theorem eq_iff_eq_cancel_right {α : Type u_1} {a : α} {b : α} : (∀ {c : α}, a = c ↔ b = c) ↔ a = b :=\n { mp := fun (h : ∀ {c : α}, a = c ↔ b = c) => eq.mpr (id (Eq._oldrec (Eq.refl (a = b)) (propext h))) (Eq.refl b),\n mpr := fun (h : a = b) (a_1 : α) => eq.mpr (id (Eq._oldrec (Eq.refl (a = a_1 ↔ b = a_1)) h)) (iff.refl (b = a_1)) }\n\n/-- Wrapper for adding elementary propositions to the type class systems.\nWarning: this can easily be abused. See the rest of this docstring for details.\n\nCertain propositions should not be treated as a class globally,\nbut sometimes it is very convenient to be able to use the type class system\nin specific circumstances.\n\nFor example, `zmod p` is a field if and only if `p` is a prime number.\nIn order to be able to find this field instance automatically by type class search,\nwe have to turn `p.prime` into an instance implicit assumption.\n\nOn the other hand, making `nat.prime` a class would require a major refactoring of the library,\nand it is questionable whether making `nat.prime` a class is desirable at all.\nThe compromise is to add the assumption `[fact p.prime]` to `zmod.field`.\n\nIn particular, this class is not intended for turning the type class system\ninto an automated theorem prover for first order logic. -/\ndef fact (p : Prop) :=\n p\n\ntheorem fact.elim {p : Prop} (h : fact p) : p :=\n h\n\n/-!\n### Declarations about propositional connectives\n-/\n\ntheorem false_ne_true : False ≠ True :=\n fun (ᾰ : False = True) => idRhs ((fun (_x : Prop) => _x) False) (Eq.symm ᾰ ▸ trivial)\n\n/-! ### Declarations about `implies` -/\n\ntheorem iff_of_eq {a : Prop} {b : Prop} (e : a = b) : a ↔ b :=\n e ▸ iff.rfl\n\ntheorem iff_iff_eq {a : Prop} {b : Prop} : a ↔ b ↔ a = b :=\n { mp := propext, mpr := iff_of_eq }\n\n@[simp] theorem eq_iff_iff {p : Prop} {q : Prop} : p = q ↔ (p ↔ q) :=\n iff.symm iff_iff_eq\n\n@[simp] theorem imp_self {a : Prop} : a → a ↔ True :=\n iff_true_intro id\n\ntheorem imp_intro {α : Prop} {β : Prop} (h : α) : β → α :=\n fun (_x : β) => h\n\ntheorem imp_false {a : Prop} : a → False ↔ ¬a :=\n iff.rfl\n\ntheorem imp_and_distrib {b : Prop} {c : Prop} {α : Sort u_1} : α → b ∧ c ↔ (α → b) ∧ (α → c) :=\n { mp := fun (h : α → b ∧ c) => { left := fun (ha : α) => and.left (h ha), right := fun (ha : α) => and.right (h ha) },\n mpr := fun (h : (α → b) ∧ (α → c)) (ha : α) => { left := and.left h ha, right := and.right h ha } }\n\n@[simp] theorem and_imp {a : Prop} {b : Prop} {c : Prop} : a ∧ b → c ↔ a → b → c := sorry\n\ntheorem iff_def {a : Prop} {b : Prop} : a ↔ b ↔ (a → b) ∧ (b → a) :=\n iff_iff_implies_and_implies a b\n\ntheorem iff_def' {a : Prop} {b : Prop} : a ↔ b ↔ (b → a) ∧ (a → b) :=\n iff.trans iff_def and.comm\n\ntheorem imp_true_iff {α : Sort u_1} : α → True ↔ True :=\n iff_true_intro fun (_x : α) => trivial\n\n@[simp] theorem imp_iff_right {a : Prop} {b : Prop} (ha : a) : a → b ↔ b :=\n { mp := fun (f : a → b) => f ha, mpr := imp_intro }\n\n/-! ### Declarations about `not` -/\n\n/-- Ex falso for negation. From `¬ a` and `a` anything follows. This is the same as `absurd` with\nthe arguments flipped, but it is in the `not` namespace so that projection notation can be used. -/\ndef not.elim {a : Prop} {α : Sort u_1} (H1 : ¬a) (H2 : a) : α :=\n absurd H2 H1\n\ntheorem not.imp {a : Prop} {b : Prop} (H2 : ¬b) (H1 : a → b) : ¬a :=\n mt H1 H2\n\ntheorem not_not_of_not_imp {a : Prop} {b : Prop} : ¬(a → b) → ¬¬a :=\n mt not.elim\n\ntheorem not_of_not_imp {b : Prop} {a : Prop} : ¬(a → b) → ¬b :=\n mt imp_intro\n\ntheorem dec_em (p : Prop) [Decidable p] : p ∨ ¬p :=\n decidable.em p\n\ntheorem em (p : Prop) : p ∨ ¬p :=\n classical.em p\n\ntheorem or_not {p : Prop} : p ∨ ¬p :=\n em p\n\ntheorem by_contradiction {p : Prop} : (¬p → False) → p :=\n decidable.by_contradiction\n\n-- alias by_contradiction ← by_contra\n\ntheorem by_contra {p : Prop} : (¬p → False) → p :=\n decidable.by_contradiction\n\n/--\nIn most of mathlib, we use the law of excluded middle (LEM) and the axiom of choice (AC) freely.\nThe `decidable` namespace contains versions of lemmas from the root namespace that explicitly\nattempt to avoid the axiom of choice, usually by adding decidability assumptions on the inputs.\n\nYou can check if a lemma uses the axiom of choice by using `#print axioms foo` and seeing if\n`classical.choice` appears in the list.\n-/\n-- See Note [decidable namespace]\n\nprotected theorem decidable.not_not {a : Prop} [Decidable a] : ¬¬a ↔ a :=\n { mp := decidable.by_contradiction, mpr := not_not_intro }\n\n/-- The Double Negation Theorem: `¬ ¬ P` is equivalent to `P`.\nThe left-to-right direction, double negation elimination (DNE),\nis classically true but not constructively. -/\n@[simp] theorem not_not {a : Prop} : ¬¬a ↔ a :=\n decidable.not_not\n\ntheorem of_not_not {a : Prop} : ¬¬a → a :=\n by_contra\n\n-- See Note [decidable namespace]\n\nprotected theorem decidable.of_not_imp {a : Prop} {b : Prop} [Decidable a] (h : ¬(a → b)) : a :=\n decidable.by_contradiction (not_not_of_not_imp h)\n\ntheorem of_not_imp {a : Prop} {b : Prop} : ¬(a → b) → a :=\n decidable.of_not_imp\n\n-- See Note [decidable namespace]\n\nprotected theorem decidable.not_imp_symm {a : Prop} {b : Prop} [Decidable a] (h : ¬a → b) (hb : ¬b) : a :=\n decidable.by_contradiction (hb ∘ h)\n\ntheorem not.decidable_imp_symm {a : Prop} {b : Prop} [Decidable a] : (¬a → b) → ¬b → a :=\n decidable.not_imp_symm\n\ntheorem not.imp_symm {a : Prop} {b : Prop} : (¬a → b) → ¬b → a :=\n not.decidable_imp_symm\n\n-- See Note [decidable namespace]\n\nprotected theorem decidable.not_imp_comm {a : Prop} {b : Prop} [Decidable a] [Decidable b] : ¬a → b ↔ ¬b → a :=\n { mp := not.decidable_imp_symm, mpr := not.decidable_imp_symm }\n\ntheorem not_imp_comm {a : Prop} {b : Prop} : ¬a → b ↔ ¬b → a :=\n decidable.not_imp_comm\n\n@[simp] theorem imp_not_self {a : Prop} : a → ¬a ↔ ¬a :=\n { mp := fun (h : a → ¬a) (ha : a) => h ha ha, mpr := fun (h : ¬a) (_x : a) => h }\n\ntheorem decidable.not_imp_self {a : Prop} [Decidable a] : ¬a → a ↔ a :=\n eq.mp (Eq._oldrec (Eq.refl (¬a → ¬¬a ↔ ¬¬a)) (propext decidable.not_not)) imp_not_self\n\n@[simp] theorem not_imp_self {a : Prop} : ¬a → a ↔ a :=\n decidable.not_imp_self\n\ntheorem imp.swap {a : Prop} {b : Prop} {c : Prop} : a → b → c ↔ b → a → c :=\n { mp := function.swap, mpr := function.swap }\n\ntheorem imp_not_comm {a : Prop} {b : Prop} : a → ¬b ↔ b → ¬a :=\n imp.swap\n\n/-! ### Declarations about `and` -/\n\ntheorem and_congr_left {a : Prop} {b : Prop} {c : Prop} (h : c → (a ↔ b)) : a ∧ c ↔ b ∧ c :=\n iff.trans and.comm (iff.trans (and_congr_right h) and.comm)\n\ntheorem and_congr_left' {a : Prop} {b : Prop} {c : Prop} (h : a ↔ b) : a ∧ c ↔ b ∧ c :=\n and_congr h iff.rfl\n\ntheorem and_congr_right' {a : Prop} {b : Prop} {c : Prop} (h : b ↔ c) : a ∧ b ↔ a ∧ c :=\n and_congr iff.rfl h\n\ntheorem not_and_of_not_left {a : Prop} (b : Prop) : ¬a → ¬(a ∧ b) :=\n mt and.left\n\ntheorem not_and_of_not_right (a : Prop) {b : Prop} : ¬b → ¬(a ∧ b) :=\n mt and.right\n\ntheorem and.imp_left {a : Prop} {b : Prop} {c : Prop} (h : a → b) : a ∧ c → b ∧ c :=\n and.imp h id\n\ntheorem and.imp_right {a : Prop} {b : Prop} {c : Prop} (h : a → b) : c ∧ a → c ∧ b :=\n and.imp id h\n\ntheorem and.right_comm {a : Prop} {b : Prop} {c : Prop} : (a ∧ b) ∧ c ↔ (a ∧ c) ∧ b := sorry\n\ntheorem and.rotate {a : Prop} {b : Prop} {c : Prop} : a ∧ b ∧ c ↔ b ∧ c ∧ a := sorry\n\ntheorem and_not_self_iff (a : Prop) : a ∧ ¬a ↔ False :=\n { mp := fun (h : a ∧ ¬a) => and.right h (and.left h), mpr := fun (h : False) => false.elim h }\n\ntheorem not_and_self_iff (a : Prop) : ¬a ∧ a ↔ False := sorry\n\ntheorem and_iff_left_of_imp {a : Prop} {b : Prop} (h : a → b) : a ∧ b ↔ a :=\n { mp := and.left, mpr := fun (ha : a) => { left := ha, right := h ha } }\n\ntheorem and_iff_right_of_imp {a : Prop} {b : Prop} (h : b → a) : a ∧ b ↔ b :=\n { mp := and.right, mpr := fun (hb : b) => { left := h hb, right := hb } }\n\n@[simp] theorem and_iff_left_iff_imp {a : Prop} {b : Prop} : a ∧ b ↔ a ↔ a → b :=\n { mp := fun (h : a ∧ b ↔ a) (ha : a) => and.right (iff.mpr h ha), mpr := and_iff_left_of_imp }\n\n@[simp] theorem and_iff_right_iff_imp {a : Prop} {b : Prop} : a ∧ b ↔ b ↔ b → a :=\n { mp := fun (h : a ∧ b ↔ b) (ha : b) => and.left (iff.mpr h ha), mpr := and_iff_right_of_imp }\n\n@[simp] theorem and.congr_right_iff {a : Prop} {b : Prop} {c : Prop} : a ∧ b ↔ a ∧ c ↔ a → (b ↔ c) := sorry\n\n@[simp] theorem and.congr_left_iff {a : Prop} {b : Prop} {c : Prop} : a ∧ c ↔ b ∧ c ↔ c → (a ↔ b) := sorry\n\n@[simp] theorem and_self_left {a : Prop} {b : Prop} : a ∧ a ∧ b ↔ a ∧ b :=\n { mp := fun (h : a ∧ a ∧ b) => { left := and.left h, right := and.right (and.right h) },\n mpr := fun (h : a ∧ b) => { left := and.left h, right := { left := and.left h, right := and.right h } } }\n\n@[simp] theorem and_self_right {a : Prop} {b : Prop} : (a ∧ b) ∧ b ↔ a ∧ b :=\n { mp := fun (h : (a ∧ b) ∧ b) => { left := and.left (and.left h), right := and.right h },\n mpr := fun (h : a ∧ b) => { left := { left := and.left h, right := and.right h }, right := and.right h } }\n\n/-! ### Declarations about `or` -/\n\ntheorem or_congr_left {a : Prop} {b : Prop} {c : Prop} (h : a ↔ b) : a ∨ c ↔ b ∨ c :=\n or_congr h iff.rfl\n\ntheorem or_congr_right {a : Prop} {b : Prop} {c : Prop} (h : b ↔ c) : a ∨ b ↔ a ∨ c :=\n or_congr iff.rfl h\n\ntheorem or.right_comm {a : Prop} {b : Prop} {c : Prop} : (a ∨ b) ∨ c ↔ (a ∨ c) ∨ b :=\n eq.mpr (id (Eq._oldrec (Eq.refl ((a ∨ b) ∨ c ↔ (a ∨ c) ∨ b)) (propext (or_assoc a b))))\n (eq.mpr (id (Eq._oldrec (Eq.refl (a ∨ b ∨ c ↔ (a ∨ c) ∨ b)) (propext (or_assoc a c))))\n (eq.mpr (id (Eq._oldrec (Eq.refl (a ∨ b ∨ c ↔ a ∨ c ∨ b)) (propext (or_comm b c)))) (iff.refl (a ∨ c ∨ b))))\n\ntheorem or_of_or_of_imp_of_imp {a : Prop} {b : Prop} {c : Prop} {d : Prop} (h₁ : a ∨ b) (h₂ : a → c) (h₃ : b → d) : c ∨ d :=\n or.imp h₂ h₃ h₁\n\ntheorem or_of_or_of_imp_left {a : Prop} {b : Prop} {c : Prop} (h₁ : a ∨ c) (h : a → b) : b ∨ c :=\n or.imp_left h h₁\n\ntheorem or_of_or_of_imp_right {a : Prop} {b : Prop} {c : Prop} (h₁ : c ∨ a) (h : a → b) : c ∨ b :=\n or.imp_right h h₁\n\ntheorem or.elim3 {a : Prop} {b : Prop} {c : Prop} {d : Prop} (h : a ∨ b ∨ c) (ha : a → d) (hb : b → d) (hc : c → d) : d :=\n or.elim h ha fun (h₂ : b ∨ c) => or.elim h₂ hb hc\n\ntheorem or_imp_distrib {a : Prop} {b : Prop} {c : Prop} : a ∨ b → c ↔ (a → c) ∧ (b → c) := sorry\n\n-- See Note [decidable namespace]\n\nprotected theorem decidable.or_iff_not_imp_left {a : Prop} {b : Prop} [Decidable a] : a ∨ b ↔ ¬a → b :=\n { mp := or.resolve_left, mpr := fun (h : ¬a → b) => dite a Or.inl (Or.inr ∘ h) }\n\ntheorem or_iff_not_imp_left {a : Prop} {b : Prop} : a ∨ b ↔ ¬a → b :=\n decidable.or_iff_not_imp_left\n\n-- See Note [decidable namespace]\n\nprotected theorem decidable.or_iff_not_imp_right {a : Prop} {b : Prop} [Decidable b] : a ∨ b ↔ ¬b → a :=\n iff.trans or.comm decidable.or_iff_not_imp_left\n\ntheorem or_iff_not_imp_right {a : Prop} {b : Prop} : a ∨ b ↔ ¬b → a :=\n decidable.or_iff_not_imp_right\n\n-- See Note [decidable namespace]\n\nprotected theorem decidable.not_imp_not {a : Prop} {b : Prop} [Decidable a] : ¬a → ¬b ↔ b → a :=\n { mp := fun (h : ¬a → ¬b) (hb : b) => decidable.by_contradiction fun (na : ¬a) => h na hb, mpr := mt }\n\ntheorem not_imp_not {a : Prop} {b : Prop} : ¬a → ¬b ↔ b → a :=\n decidable.not_imp_not\n\n@[simp] theorem or_iff_left_iff_imp {a : Prop} {b : Prop} : a ∨ b ↔ a ↔ b → a :=\n { mp := fun (h : a ∨ b ↔ a) (hb : b) => iff.mp h (Or.inr hb), mpr := or_iff_left_of_imp }\n\n@[simp] theorem or_iff_right_iff_imp {a : Prop} {b : Prop} : a ∨ b ↔ b ↔ a → b :=\n eq.mpr (id (Eq._oldrec (Eq.refl (a ∨ b ↔ b ↔ a → b)) (propext (or_comm a b))))\n (eq.mpr (id (Eq._oldrec (Eq.refl (b ∨ a ↔ b ↔ a → b)) (propext or_iff_left_iff_imp))) (iff.refl (a → b)))\n\n/-! ### Declarations about distributivity -/\n\n/-- `∧` distributes over `∨` (on the left). -/\ntheorem and_or_distrib_left {a : Prop} {b : Prop} {c : Prop} : a ∧ (b ∨ c) ↔ a ∧ b ∨ a ∧ c := sorry\n\n/-- `∧` distributes over `∨` (on the right). -/\ntheorem or_and_distrib_right {a : Prop} {b : Prop} {c : Prop} : (a ∨ b) ∧ c ↔ a ∧ c ∨ b ∧ c :=\n iff.trans (iff.trans and.comm and_or_distrib_left) (or_congr and.comm and.comm)\n\n/-- `∨` distributes over `∧` (on the left). -/\ntheorem or_and_distrib_left {a : Prop} {b : Prop} {c : Prop} : a ∨ b ∧ c ↔ (a ∨ b) ∧ (a ∨ c) :=\n { mp := Or._oldrec (fun (ha : a) => { left := Or.inl ha, right := Or.inl ha }) (and.imp Or.inr Or.inr),\n mpr := And._oldrec (Or._oldrec (imp_intro ∘ Or.inl) (or.imp_right ∘ And.intro)) }\n\n/-- `∨` distributes over `∧` (on the right). -/\ntheorem and_or_distrib_right {a : Prop} {b : Prop} {c : Prop} : a ∧ b ∨ c ↔ (a ∨ c) ∧ (b ∨ c) :=\n iff.trans (iff.trans or.comm or_and_distrib_left) (and_congr or.comm or.comm)\n\n@[simp] theorem or_self_left {a : Prop} {b : Prop} : a ∨ a ∨ b ↔ a ∨ b :=\n { mp := fun (h : a ∨ a ∨ b) => or.elim h Or.inl id, mpr := fun (h : a ∨ b) => or.elim h Or.inl (Or.inr ∘ Or.inr) }\n\n@[simp] theorem or_self_right {a : Prop} {b : Prop} : (a ∨ b) ∨ b ↔ a ∨ b :=\n { mp := fun (h : (a ∨ b) ∨ b) => or.elim h id Or.inr, mpr := fun (h : a ∨ b) => or.elim h (Or.inl ∘ Or.inl) Or.inr }\n\n/-! Declarations about `iff` -/\n\ntheorem iff_of_true {a : Prop} {b : Prop} (ha : a) (hb : b) : a ↔ b :=\n { mp := fun (_x : a) => hb, mpr := fun (_x : b) => ha }\n\ntheorem iff_of_false {a : Prop} {b : Prop} (ha : ¬a) (hb : ¬b) : a ↔ b :=\n { mp := not.elim ha, mpr := not.elim hb }\n\ntheorem iff_true_left {a : Prop} {b : Prop} (ha : a) : a ↔ b ↔ b :=\n { mp := fun (h : a ↔ b) => iff.mp h ha, mpr := iff_of_true ha }\n\ntheorem iff_true_right {a : Prop} {b : Prop} (ha : a) : b ↔ a ↔ b :=\n iff.trans iff.comm (iff_true_left ha)\n\ntheorem iff_false_left {a : Prop} {b : Prop} (ha : ¬a) : a ↔ b ↔ ¬b :=\n { mp := fun (h : a ↔ b) => mt (iff.mpr h) ha, mpr := iff_of_false ha }\n\ntheorem iff_false_right {a : Prop} {b : Prop} (ha : ¬a) : b ↔ a ↔ ¬b :=\n iff.trans iff.comm (iff_false_left ha)\n\n-- See Note [decidable namespace]\n\nprotected theorem decidable.not_or_of_imp {a : Prop} {b : Prop} [Decidable a] (h : a → b) : ¬a ∨ b :=\n dite a (fun (ha : a) => Or.inr (h ha)) fun (ha : ¬a) => Or.inl ha\n\ntheorem not_or_of_imp {a : Prop} {b : Prop} : (a → b) → ¬a ∨ b :=\n decidable.not_or_of_imp\n\n-- See Note [decidable namespace]\n\nprotected theorem decidable.imp_iff_not_or {a : Prop} {b : Prop} [Decidable a] : a → b ↔ ¬a ∨ b :=\n { mp := decidable.not_or_of_imp, mpr := or.neg_resolve_left }\n\ntheorem imp_iff_not_or {a : Prop} {b : Prop} : a → b ↔ ¬a ∨ b :=\n decidable.imp_iff_not_or\n\n-- See Note [decidable namespace]\n\nprotected theorem decidable.imp_or_distrib {a : Prop} {b : Prop} {c : Prop} [Decidable a] : a → b ∨ c ↔ (a → b) ∨ (a → c) := sorry\n\ntheorem imp_or_distrib {a : Prop} {b : Prop} {c : Prop} : a → b ∨ c ↔ (a → b) ∨ (a → c) :=\n decidable.imp_or_distrib\n\n-- See Note [decidable namespace]\n\nprotected theorem decidable.imp_or_distrib' {a : Prop} {b : Prop} {c : Prop} [Decidable b] : a → b ∨ c ↔ (a → b) ∨ (a → c) := sorry\n\ntheorem imp_or_distrib' {a : Prop} {b : Prop} {c : Prop} : a → b ∨ c ↔ (a → b) ∨ (a → c) :=\n decidable.imp_or_distrib'\n\ntheorem not_imp_of_and_not {a : Prop} {b : Prop} : a ∧ ¬b → ¬(a → b) :=\n fun (ᾰ : a ∧ ¬b) (ᾰ_1 : a → b) => and.dcases_on ᾰ fun (ᾰ_left : a) (ᾰ_right : ¬b) => idRhs False (ᾰ_right (ᾰ_1 ᾰ_left))\n\n-- See Note [decidable namespace]\n\nprotected theorem decidable.not_imp {a : Prop} {b : Prop} [Decidable a] : ¬(a → b) ↔ a ∧ ¬b :=\n { mp := fun (h : ¬(a → b)) => { left := decidable.of_not_imp h, right := not_of_not_imp h }, mpr := not_imp_of_and_not }\n\ntheorem not_imp {a : Prop} {b : Prop} : ¬(a → b) ↔ a ∧ ¬b :=\n decidable.not_imp\n\n-- for monotonicity\n\ntheorem imp_imp_imp {a : Prop} {b : Prop} {c : Prop} {d : Prop} (h₀ : c → a) (h₁ : b → d) : (a → b) → c → d :=\n fun (h₂ : a → b) => h₁ ∘ h₂ ∘ h₀\n\n-- See Note [decidable namespace]\n\nprotected theorem decidable.peirce (a : Prop) (b : Prop) [Decidable a] : ((a → b) → a) → a :=\n dite a (fun (ha : a) (h : (a → b) → a) => ha) fun (ha : ¬a) (h : (a → b) → a) => h (not.elim ha)\n\ntheorem peirce (a : Prop) (b : Prop) : ((a → b) → a) → a :=\n decidable.peirce a b\n\ntheorem peirce' {a : Prop} (H : ∀ (b : Prop), (a → b) → a) : a :=\n H a id\n\n-- See Note [decidable namespace]\n\nprotected theorem decidable.not_iff_not {a : Prop} {b : Prop} [Decidable a] [Decidable b] : ¬a ↔ ¬b ↔ (a ↔ b) :=\n eq.mpr (id (Eq._oldrec (Eq.refl (¬a ↔ ¬b ↔ (a ↔ b))) (propext iff_def)))\n (eq.mpr (id (Eq._oldrec (Eq.refl ((¬a → ¬b) ∧ (¬b → ¬a) ↔ (a ↔ b))) (propext iff_def')))\n (and_congr decidable.not_imp_not decidable.not_imp_not))\n\ntheorem not_iff_not {a : Prop} {b : Prop} : ¬a ↔ ¬b ↔ (a ↔ b) :=\n decidable.not_iff_not\n\n-- See Note [decidable namespace]\n\nprotected theorem decidable.not_iff_comm {a : Prop} {b : Prop} [Decidable a] [Decidable b] : ¬a ↔ b ↔ (¬b ↔ a) :=\n eq.mpr (id (Eq._oldrec (Eq.refl (¬a ↔ b ↔ (¬b ↔ a))) (propext iff_def)))\n (eq.mpr (id (Eq._oldrec (Eq.refl ((¬a → b) ∧ (b → ¬a) ↔ (¬b ↔ a))) (propext iff_def)))\n (and_congr decidable.not_imp_comm imp_not_comm))\n\ntheorem not_iff_comm {a : Prop} {b : Prop} : ¬a ↔ b ↔ (¬b ↔ a) :=\n decidable.not_iff_comm\n\n-- See Note [decidable namespace]\n\nprotected theorem decidable.not_iff {a : Prop} {b : Prop} [Decidable b] : ¬(a ↔ b) ↔ (¬a ↔ b) := sorry\n\ntheorem not_iff {a : Prop} {b : Prop} : ¬(a ↔ b) ↔ (¬a ↔ b) :=\n decidable.not_iff\n\n-- See Note [decidable namespace]\n\nprotected theorem decidable.iff_not_comm {a : Prop} {b : Prop} [Decidable a] [Decidable b] : a ↔ ¬b ↔ (b ↔ ¬a) :=\n eq.mpr (id (Eq._oldrec (Eq.refl (a ↔ ¬b ↔ (b ↔ ¬a))) (propext iff_def)))\n (eq.mpr (id (Eq._oldrec (Eq.refl ((a → ¬b) ∧ (¬b → a) ↔ (b ↔ ¬a))) (propext iff_def)))\n (and_congr imp_not_comm decidable.not_imp_comm))\n\ntheorem iff_not_comm {a : Prop} {b : Prop} : a ↔ ¬b ↔ (b ↔ ¬a) :=\n decidable.iff_not_comm\n\n-- See Note [decidable namespace]\n\nprotected theorem decidable.iff_iff_and_or_not_and_not {a : Prop} {b : Prop} [Decidable b] : a ↔ b ↔ a ∧ b ∨ ¬a ∧ ¬b := sorry\n\ntheorem iff_iff_and_or_not_and_not {a : Prop} {b : Prop} : a ↔ b ↔ a ∧ b ∨ ¬a ∧ ¬b :=\n decidable.iff_iff_and_or_not_and_not\n\ntheorem decidable.iff_iff_not_or_and_or_not {a : Prop} {b : Prop} [Decidable a] [Decidable b] : a ↔ b ↔ (¬a ∨ b) ∧ (a ∨ ¬b) := sorry\n\ntheorem iff_iff_not_or_and_or_not {a : Prop} {b : Prop} : a ↔ b ↔ (¬a ∨ b) ∧ (a ∨ ¬b) :=\n decidable.iff_iff_not_or_and_or_not\n\n-- See Note [decidable namespace]\n\nprotected theorem decidable.not_and_not_right {a : Prop} {b : Prop} [Decidable b] : ¬(a ∧ ¬b) ↔ a → b := sorry\n\ntheorem not_and_not_right {a : Prop} {b : Prop} : ¬(a ∧ ¬b) ↔ a → b :=\n decidable.not_and_not_right\n\n/-- Transfer decidability of `a` to decidability of `b`, if the propositions are equivalent.\n**Important**: this function should be used instead of `rw` on `decidable b`, because the\nkernel will get stuck reducing the usage of `propext` otherwise,\nand `dec_trivial` will not work. -/\ndef decidable_of_iff {b : Prop} (a : Prop) (h : a ↔ b) [D : Decidable a] : Decidable b :=\n decidable_of_decidable_of_iff D h\n\n/-- Transfer decidability of `b` to decidability of `a`, if the propositions are equivalent.\nThis is the same as `decidable_of_iff` but the iff is flipped. -/\ndef decidable_of_iff' {a : Prop} (b : Prop) (h : a ↔ b) [D : Decidable b] : Decidable a :=\n decidable_of_decidable_of_iff D (iff.symm h)\n\n/-- Prove that `a` is decidable by constructing a boolean `b` and a proof that `b ↔ a`.\n(This is sometimes taken as an alternate definition of decidability.) -/\ndef decidable_of_bool {a : Prop} (b : Bool) (h : ↥b ↔ a) : Decidable a :=\n sorry\n\n/-! ### De Morgan's laws -/\n\ntheorem not_and_of_not_or_not {a : Prop} {b : Prop} (h : ¬a ∨ ¬b) : ¬(a ∧ b) :=\n fun (ᾰ : a ∧ b) =>\n and.dcases_on ᾰ fun (ᾰ_left : a) (ᾰ_right : b) => idRhs False (or.elim h (absurd ᾰ_left) (absurd ᾰ_right))\n\n-- See Note [decidable namespace]\n\nprotected theorem decidable.not_and_distrib {a : Prop} {b : Prop} [Decidable a] : ¬(a ∧ b) ↔ ¬a ∨ ¬b := sorry\n\n-- See Note [decidable namespace]\n\nprotected theorem decidable.not_and_distrib' {a : Prop} {b : Prop} [Decidable b] : ¬(a ∧ b) ↔ ¬a ∨ ¬b := sorry\n\n/-- One of de Morgan's laws: the negation of a conjunction is logically equivalent to the\ndisjunction of the negations. -/\ntheorem not_and_distrib {a : Prop} {b : Prop} : ¬(a ∧ b) ↔ ¬a ∨ ¬b :=\n decidable.not_and_distrib\n\n@[simp] theorem not_and {a : Prop} {b : Prop} : ¬(a ∧ b) ↔ a → ¬b :=\n and_imp\n\ntheorem not_and' {a : Prop} {b : Prop} : ¬(a ∧ b) ↔ b → ¬a :=\n iff.trans not_and imp_not_comm\n\n/-- One of de Morgan's laws: the negation of a disjunction is logically equivalent to the\nconjunction of the negations. -/\ntheorem not_or_distrib {a : Prop} {b : Prop} : ¬(a ∨ b) ↔ ¬a ∧ ¬b := sorry\n\n-- See Note [decidable namespace]\n\nprotected theorem decidable.or_iff_not_and_not {a : Prop} {b : Prop} [Decidable a] [Decidable b] : a ∨ b ↔ ¬(¬a ∧ ¬b) :=\n eq.mpr (id (Eq._oldrec (Eq.refl (a ∨ b ↔ ¬(¬a ∧ ¬b))) (Eq.symm (propext not_or_distrib))))\n (eq.mpr (id (Eq._oldrec (Eq.refl (a ∨ b ↔ ¬¬(a ∨ b))) (propext decidable.not_not))) (iff.refl (a ∨ b)))\n\ntheorem or_iff_not_and_not {a : Prop} {b : Prop} : a ∨ b ↔ ¬(¬a ∧ ¬b) :=\n decidable.or_iff_not_and_not\n\n-- See Note [decidable namespace]\n\nprotected theorem decidable.and_iff_not_or_not {a : Prop} {b : Prop} [Decidable a] [Decidable b] : a ∧ b ↔ ¬(¬a ∨ ¬b) :=\n eq.mpr (id (Eq._oldrec (Eq.refl (a ∧ b ↔ ¬(¬a ∨ ¬b))) (Eq.symm (propext decidable.not_and_distrib))))\n (eq.mpr (id (Eq._oldrec (Eq.refl (a ∧ b ↔ ¬¬(a ∧ b))) (propext decidable.not_not))) (iff.refl (a ∧ b)))\n\ntheorem and_iff_not_or_not {a : Prop} {b : Prop} : a ∧ b ↔ ¬(¬a ∨ ¬b) :=\n decidable.and_iff_not_or_not\n\n/-! ### Declarations about equality -/\n\n@[simp] theorem heq_iff_eq {α : Sort u_1} {a : α} {b : α} : a == b ↔ a = b :=\n { mp := eq_of_heq, mpr := heq_of_eq }\n\ntheorem proof_irrel_heq {p : Prop} {q : Prop} (hp : p) (hq : q) : hp == hq :=\n (fun (this : p = q) => Eq._oldrec (fun (hq : p) => HEq.refl hp) this hq)\n (propext { mp := fun (_x : p) => hq, mpr := fun (_x : q) => hp })\n\ntheorem ne_of_mem_of_not_mem {α : outParam (Type u_1)} {β : Type u_2} [has_mem α β] {s : β} {a : α} {b : α} (h : a ∈ s) : ¬b ∈ s → a ≠ b :=\n mt fun (e : a = b) => e ▸ h\n\ntheorem eq_equivalence {α : Sort u_1} : equivalence Eq :=\n { left := Eq.refl, right := { left := Eq.symm, right := Eq.trans } }\n\n/-- Transport through trivial families is the identity. -/\n@[simp] theorem eq_rec_constant {α : Sort u_1} {a : α} {a' : α} {β : Sort u_2} (y : β) (h : a = a') : Eq._oldrec y h = y := sorry\n\n@[simp] theorem eq_mp_rfl {α : Sort u_1} {a : α} : eq.mp (Eq.refl α) a = a :=\n rfl\n\n@[simp] theorem eq_mpr_rfl {α : Sort u_1} {a : α} : eq.mpr (Eq.refl α) a = a :=\n rfl\n\ntheorem heq_of_eq_mp {α : Sort u_1} {β : Sort u_1} {a : α} {a' : β} (e : α = β) (h₂ : eq.mp e a = a') : a == a' := sorry\n\ntheorem rec_heq_of_heq {α : Sort u_1} {a : α} {b : α} {β : Sort u_2} {C : α → Sort u_2} {x : C a} {y : β} (eq : a = b) (h : x == y) : Eq._oldrec x eq == y :=\n eq.drec h eq\n\n@[simp] theorem eq_mpr_heq {α : Sort u} {β : Sort u} (h : β = α) (x : α) : eq.mpr h x == x :=\n eq.drec (fun (x : β) => HEq.refl (eq.mpr (Eq.refl β) x)) h x\n\nprotected theorem eq.congr {α : Sort u_1} {x₁ : α} {x₂ : α} {y₁ : α} {y₂ : α} (h₁ : x₁ = y₁) (h₂ : x₂ = y₂) : x₁ = x₂ ↔ y₁ = y₂ :=\n Eq._oldrec (Eq._oldrec (iff.refl (x₁ = x₂)) h₂) h₁\n\ntheorem eq.congr_left {α : Sort u_1} {x : α} {y : α} {z : α} (h : x = y) : x = z ↔ y = z :=\n eq.mpr (id (Eq._oldrec (Eq.refl (x = z ↔ y = z)) h)) (iff.refl (y = z))\n\ntheorem eq.congr_right {α : Sort u_1} {x : α} {y : α} {z : α} (h : x = y) : z = x ↔ z = y :=\n eq.mpr (id (Eq._oldrec (Eq.refl (z = x ↔ z = y)) h)) (iff.refl (z = y))\n\ntheorem congr_arg2 {α : Type u_1} {β : Type u_2} {γ : Type u_3} (f : α → β → γ) {x : α} {x' : α} {y : β} {y' : β} (hx : x = x') (hy : y = y') : f x y = f x' y' :=\n Eq._oldrec (Eq._oldrec (Eq.refl (f x y)) hy) hx\n\n/-! ### Declarations about quantifiers -/\n\ntheorem forall_imp {α : Sort u_1} {p : α → Prop} {q : α → Prop} (h : ∀ (a : α), p a → q a) : (∀ (a : α), p a) → ∀ (a : α), q a :=\n fun (h' : ∀ (a : α), p a) (a : α) => h a (h' a)\n\ntheorem forall₂_congr {α : Sort u_1} {β : Sort u_2} {p : α → β → Prop} {q : α → β → Prop} (h : ∀ (a : α) (b : β), p a b ↔ q a b) : (∀ (a : α) (b : β), p a b) ↔ ∀ (a : α) (b : β), q a b :=\n forall_congr fun (a : α) => forall_congr (h a)\n\ntheorem forall₃_congr {α : Sort u_1} {β : Sort u_2} {γ : Sort u_3} {p : α → β → γ → Prop} {q : α → β → γ → Prop} (h : ∀ (a : α) (b : β) (c : γ), p a b c ↔ q a b c) : (∀ (a : α) (b : β) (c : γ), p a b c) ↔ ∀ (a : α) (b : β) (c : γ), q a b c :=\n forall_congr fun (a : α) => forall₂_congr (h a)\n\ntheorem forall₄_congr {α : Sort u_1} {β : Sort u_2} {γ : Sort u_3} {δ : Sort u_4} {p : α → β → γ → δ → Prop} {q : α → β → γ → δ → Prop} (h : ∀ (a : α) (b : β) (c : γ) (d : δ), p a b c d ↔ q a b c d) : (∀ (a : α) (b : β) (c : γ) (d : δ), p a b c d) ↔ ∀ (a : α) (b : β) (c : γ) (d : δ), q a b c d :=\n forall_congr fun (a : α) => forall₃_congr (h a)\n\ntheorem Exists.imp {α : Sort u_1} {q : α → Prop} {p : α → Prop} (h : ∀ (a : α), p a → q a) : (∃ (a : α), p a) → ∃ (a : α), q a :=\n fun (p_1 : ∃ (a : α), p a) => exists_imp_exists h p_1\n\ntheorem exists_imp_exists' {α : Sort u_1} {β : Sort u_2} {p : α → Prop} {q : β → Prop} (f : α → β) (hpq : ∀ (a : α), p a → q (f a)) (hp : ∃ (a : α), p a) : ∃ (b : β), q b :=\n exists.elim hp fun (a : α) (hp' : p a) => Exists.intro (f a) (hpq a hp')\n\ntheorem exists₂_congr {α : Sort u_1} {β : Sort u_2} {p : α → β → Prop} {q : α → β → Prop} (h : ∀ (a : α) (b : β), p a b ↔ q a b) : (∃ (a : α), ∃ (b : β), p a b) ↔ ∃ (a : α), ∃ (b : β), q a b :=\n exists_congr fun (a : α) => exists_congr (h a)\n\ntheorem exists₃_congr {α : Sort u_1} {β : Sort u_2} {γ : Sort u_3} {p : α → β → γ → Prop} {q : α → β → γ → Prop} (h : ∀ (a : α) (b : β) (c : γ), p a b c ↔ q a b c) : (∃ (a : α), ∃ (b : β), ∃ (c : γ), p a b c) ↔ ∃ (a : α), ∃ (b : β), ∃ (c : γ), q a b c :=\n exists_congr fun (a : α) => exists₂_congr (h a)\n\ntheorem exists₄_congr {α : Sort u_1} {β : Sort u_2} {γ : Sort u_3} {δ : Sort u_4} {p : α → β → γ → δ → Prop} {q : α → β → γ → δ → Prop} (h : ∀ (a : α) (b : β) (c : γ) (d : δ), p a b c d ↔ q a b c d) : (∃ (a : α), ∃ (b : β), ∃ (c : γ), ∃ (d : δ), p a b c d) ↔ ∃ (a : α), ∃ (b : β), ∃ (c : γ), ∃ (d : δ), q a b c d :=\n exists_congr fun (a : α) => exists₃_congr (h a)\n\ntheorem forall_swap {α : Sort u_1} {β : Sort u_2} {p : α → β → Prop} : (∀ (x : α) (y : β), p x y) ↔ ∀ (y : β) (x : α), p x y :=\n { mp := function.swap, mpr := function.swap }\n\ntheorem exists_swap {α : Sort u_1} {β : Sort u_2} {p : α → β → Prop} : (∃ (x : α), ∃ (y : β), p x y) ↔ ∃ (y : β), ∃ (x : α), p x y := sorry\n\n@[simp] theorem exists_imp_distrib {α : Sort u_1} {p : α → Prop} {b : Prop} : (∃ (x : α), p x) → b ↔ ∀ (x : α), p x → b := sorry\n\n/--\nExtract an element from a existential statement, using `classical.some`.\n-/\n-- This enables projection notation.\n\ndef Exists.some {α : Sort u_1} {p : α → Prop} (P : ∃ (a : α), p a) : α :=\n classical.some P\n\n/--\nShow that an element extracted from `P : ∃ a, p a` using `P.some` satisfies `p`.\n-/\ntheorem Exists.some_spec {α : Sort u_1} {p : α → Prop} (P : ∃ (a : α), p a) : p (Exists.some P) :=\n classical.some_spec P\n\n--theorem forall_not_of_not_exists (h : ¬ ∃ x, p x) : ∀ x, ¬ p x :=\n\n--forall_imp_of_exists_imp h\n\ntheorem not_exists_of_forall_not {α : Sort u_1} {p : α → Prop} (h : ∀ (x : α), ¬p x) : ¬∃ (x : α), p x :=\n iff.mpr exists_imp_distrib h\n\n@[simp] theorem not_exists {α : Sort u_1} {p : α → Prop} : (¬∃ (x : α), p x) ↔ ∀ (x : α), ¬p x :=\n exists_imp_distrib\n\ntheorem not_forall_of_exists_not {α : Sort u_1} {p : α → Prop} : (∃ (x : α), ¬p x) → ¬∀ (x : α), p x :=\n fun (ᾰ : ∃ (x : α), ¬p x) (ᾰ_1 : ∀ (x : α), p x) =>\n Exists.dcases_on ᾰ fun (ᾰ_w : α) (ᾰ_h : ¬p ᾰ_w) => idRhs False (ᾰ_h (ᾰ_1 ᾰ_w))\n\n-- See Note [decidable namespace]\n\nprotected theorem decidable.not_forall {α : Sort u_1} {p : α → Prop} [Decidable (∃ (x : α), ¬p x)] [(x : α) → Decidable (p x)] : (¬∀ (x : α), p x) ↔ ∃ (x : α), ¬p x := sorry\n\n@[simp] theorem not_forall {α : Sort u_1} {p : α → Prop} : (¬∀ (x : α), p x) ↔ ∃ (x : α), ¬p x :=\n decidable.not_forall\n\n-- See Note [decidable namespace]\n\nprotected theorem decidable.not_forall_not {α : Sort u_1} {p : α → Prop} [Decidable (∃ (x : α), p x)] : (¬∀ (x : α), ¬p x) ↔ ∃ (x : α), p x :=\n iff.mp decidable.not_iff_comm not_exists\n\ntheorem not_forall_not {α : Sort u_1} {p : α → Prop} : (¬∀ (x : α), ¬p x) ↔ ∃ (x : α), p x :=\n decidable.not_forall_not\n\n-- See Note [decidable namespace]\n\nprotected theorem decidable.not_exists_not {α : Sort u_1} {p : α → Prop} [(x : α) → Decidable (p x)] : (¬∃ (x : α), ¬p x) ↔ ∀ (x : α), p x := sorry\n\n@[simp] theorem not_exists_not {α : Sort u_1} {p : α → Prop} : (¬∃ (x : α), ¬p x) ↔ ∀ (x : α), p x :=\n decidable.not_exists_not\n\n@[simp] theorem forall_true_iff {α : Sort u_1} : α → True ↔ True :=\n iff_true_intro fun (_x : α) => trivial\n\n-- Unfortunately this causes simp to loop sometimes, so we\n\n-- add the 2 and 3 cases as simp lemmas instead\n\ntheorem forall_true_iff' {α : Sort u_1} {p : α → Prop} (h : ∀ (a : α), p a ↔ True) : (∀ (a : α), p a) ↔ True :=\n iff_true_intro fun (_x : α) => of_iff_true (h _x)\n\n@[simp] theorem forall_2_true_iff {α : Sort u_1} {β : α → Sort u_2} : (∀ (a : α), β a → True) ↔ True :=\n forall_true_iff' fun (_x : α) => forall_true_iff\n\n@[simp] theorem forall_3_true_iff {α : Sort u_1} {β : α → Sort u_2} {γ : (a : α) → β a → Sort u_3} : (∀ (a : α) (b : β a), γ a b → True) ↔ True :=\n forall_true_iff' fun (_x : α) => forall_2_true_iff\n\n@[simp] theorem forall_const {b : Prop} (α : Sort u_1) [i : Nonempty α] : α → b ↔ b :=\n { mp := nonempty.elim i, mpr := fun (hb : b) (x : α) => hb }\n\n@[simp] theorem exists_const {b : Prop} (α : Sort u_1) [i : Nonempty α] : (∃ (x : α), b) ↔ b :=\n { mp := fun (_x : ∃ (x : α), b) => (fun (_a : ∃ (x : α), b) => Exists.dcases_on _a fun (w : α) (h : b) => idRhs b h) _x,\n mpr := nonempty.elim i exists.intro }\n\ntheorem forall_and_distrib {α : Sort u_1} {p : α → Prop} {q : α → Prop} : (∀ (x : α), p x ∧ q x) ↔ (∀ (x : α), p x) ∧ ∀ (x : α), q x := sorry\n\ntheorem exists_or_distrib {α : Sort u_1} {p : α → Prop} {q : α → Prop} : (∃ (x : α), p x ∨ q x) ↔ (∃ (x : α), p x) ∨ ∃ (x : α), q x := sorry\n\n@[simp] theorem exists_and_distrib_left {α : Sort u_1} {q : Prop} {p : α → Prop} : (∃ (x : α), q ∧ p x) ↔ q ∧ ∃ (x : α), p x := sorry\n\n@[simp] theorem exists_and_distrib_right {α : Sort u_1} {q : Prop} {p : α → Prop} : (∃ (x : α), p x ∧ q) ↔ (∃ (x : α), p x) ∧ q := sorry\n\n@[simp] theorem forall_eq {α : Sort u_1} {p : α → Prop} {a' : α} : (∀ (a : α), a = a' → p a) ↔ p a' :=\n { mp := fun (h : ∀ (a : α), a = a' → p a) => h a' rfl, mpr := fun (h : p a') (a : α) (e : a = a') => Eq.symm e ▸ h }\n\n@[simp] theorem forall_eq' {α : Sort u_1} {p : α → Prop} {a' : α} : (∀ (a : α), a' = a → p a) ↔ p a' := sorry\n\n-- this lemma is needed to simplify the output of `list.mem_cons_iff`\n\n@[simp] theorem forall_eq_or_imp {α : Sort u_1} {p : α → Prop} {q : α → Prop} {a' : α} : (∀ (a : α), a = a' ∨ q a → p a) ↔ p a' ∧ ∀ (a : α), q a → p a := sorry\n\n@[simp] theorem exists_eq {α : Sort u_1} {a' : α} : ∃ (a : α), a = a' :=\n Exists.intro a' rfl\n\n@[simp] theorem exists_eq' {α : Sort u_1} {a' : α} : ∃ (a : α), a' = a :=\n Exists.intro a' rfl\n\n@[simp] theorem exists_eq_left {α : Sort u_1} {p : α → Prop} {a' : α} : (∃ (a : α), a = a' ∧ p a) ↔ p a' := sorry\n\n@[simp] theorem exists_eq_right {α : Sort u_1} {p : α → Prop} {a' : α} : (∃ (a : α), p a ∧ a = a') ↔ p a' :=\n iff.trans (exists_congr fun (a : α) => and.comm) exists_eq_left\n\n@[simp] theorem exists_eq_right_right {α : Sort u_1} {p : α → Prop} {b : Prop} {a' : α} : (∃ (a : α), p a ∧ b ∧ a = a') ↔ p a' ∧ b := sorry\n\n@[simp] theorem exists_eq_right_right' {α : Sort u_1} {p : α → Prop} {b : Prop} {a' : α} : (∃ (a : α), p a ∧ b ∧ a' = a) ↔ p a' ∧ b := sorry\n\n@[simp] theorem exists_apply_eq_apply {α : Type u_1} {β : Type u_2} (f : α → β) (a' : α) : ∃ (a : α), f a = f a' :=\n Exists.intro a' rfl\n\n@[simp] theorem exists_apply_eq_apply' {α : Type u_1} {β : Type u_2} (f : α → β) (a' : α) : ∃ (a : α), f a' = f a :=\n Exists.intro a' rfl\n\n@[simp] theorem exists_exists_and_eq_and {α : Sort u_1} {β : Sort u_2} {f : α → β} {p : α → Prop} {q : β → Prop} : (∃ (b : β), (∃ (a : α), p a ∧ f a = b) ∧ q b) ↔ ∃ (a : α), p a ∧ q (f a) := sorry\n\n@[simp] theorem exists_exists_eq_and {α : Sort u_1} {β : Sort u_2} {f : α → β} {p : β → Prop} : (∃ (b : β), (∃ (a : α), f a = b) ∧ p b) ↔ ∃ (a : α), p (f a) := sorry\n\n@[simp] theorem forall_apply_eq_imp_iff {α : Sort u_1} {β : Sort u_2} {f : α → β} {p : β → Prop} : (∀ (a : α) (b : β), f a = b → p b) ↔ ∀ (a : α), p (f a) :=\n { mp := fun (h : ∀ (a : α) (b : β), f a = b → p b) (a : α) => h a (f a) rfl,\n mpr := fun (h : ∀ (a : α), p (f a)) (a : α) (b : β) (hab : f a = b) => hab ▸ h a }\n\n@[simp] theorem forall_apply_eq_imp_iff' {α : Sort u_1} {β : Sort u_2} {f : α → β} {p : β → Prop} : (∀ (b : β) (a : α), f a = b → p b) ↔ ∀ (a : α), p (f a) := sorry\n\n@[simp] theorem forall_eq_apply_imp_iff {α : Sort u_1} {β : Sort u_2} {f : α → β} {p : β → Prop} : (∀ (a : α) (b : β), b = f a → p b) ↔ ∀ (a : α), p (f a) := sorry\n\n@[simp] theorem forall_eq_apply_imp_iff' {α : Sort u_1} {β : Sort u_2} {f : α → β} {p : β → Prop} : (∀ (b : β) (a : α), b = f a → p b) ↔ ∀ (a : α), p (f a) := sorry\n\n@[simp] theorem forall_apply_eq_imp_iff₂ {α : Sort u_1} {β : Sort u_2} {f : α → β} {p : α → Prop} {q : β → Prop} : (∀ (b : β) (a : α), p a → f a = b → q b) ↔ ∀ (a : α), p a → q (f a) :=\n { mp := fun (h : ∀ (b : β) (a : α), p a → f a = b → q b) (a : α) (ha : p a) => h (f a) a ha rfl,\n mpr := fun (h : ∀ (a : α), p a → q (f a)) (b : β) (a : α) (ha : p a) (hb : f a = b) => hb ▸ h a ha }\n\n@[simp] theorem exists_eq_left' {α : Sort u_1} {p : α → Prop} {a' : α} : (∃ (a : α), a' = a ∧ p a) ↔ p a' := sorry\n\n@[simp] theorem exists_eq_right' {α : Sort u_1} {p : α → Prop} {a' : α} : (∃ (a : α), p a ∧ a' = a) ↔ p a' := sorry\n\ntheorem exists_comm {α : Sort u_1} {β : Sort u_2} {p : α → β → Prop} : (∃ (a : α), ∃ (b : β), p a b) ↔ ∃ (b : β), ∃ (a : α), p a b := sorry\n\ntheorem forall_or_of_or_forall {α : Sort u_1} {p : α → Prop} {b : Prop} (h : b ∨ ∀ (x : α), p x) (x : α) : b ∨ p x :=\n or.imp_right (fun (h₂ : ∀ (x : α), p x) => h₂ x) h\n\n-- See Note [decidable namespace]\n\nprotected theorem decidable.forall_or_distrib_left {α : Sort u_1} {q : Prop} {p : α → Prop} [Decidable q] : (∀ (x : α), q ∨ p x) ↔ q ∨ ∀ (x : α), p x := sorry\n\ntheorem forall_or_distrib_left {α : Sort u_1} {q : Prop} {p : α → Prop} : (∀ (x : α), q ∨ p x) ↔ q ∨ ∀ (x : α), p x :=\n decidable.forall_or_distrib_left\n\n-- See Note [decidable namespace]\n\nprotected theorem decidable.forall_or_distrib_right {α : Sort u_1} {q : Prop} {p : α → Prop} [Decidable q] : (∀ (x : α), p x ∨ q) ↔ (∀ (x : α), p x) ∨ q := sorry\n\ntheorem forall_or_distrib_right {α : Sort u_1} {q : Prop} {p : α → Prop} : (∀ (x : α), p x ∨ q) ↔ (∀ (x : α), p x) ∨ q :=\n decidable.forall_or_distrib_right\n\n/-- A predicate holds everywhere on the image of a surjective functions iff\n it holds everywhere. -/\ntheorem forall_iff_forall_surj {α : Type u_1} {β : Type u_2} {f : α → β} (h : function.surjective f) {P : β → Prop} : (∀ (a : α), P (f a)) ↔ ∀ (b : β), P b := sorry\n\n@[simp] theorem exists_prop {p : Prop} {q : Prop} : (∃ (h : p), q) ↔ p ∧ q := sorry\n\n@[simp] theorem exists_false {α : Sort u_1} : ¬∃ (a : α), False :=\n fun (_x : ∃ (a : α), False) =>\n (fun (_a : ∃ (a : α), False) => Exists.dcases_on _a fun (w : α) (h : False) => idRhs False h) _x\n\n@[simp] theorem exists_unique_false {α : Sort u_1} : ¬exists_unique fun (a : α) => False := sorry\n\ntheorem Exists.fst {b : Prop} {p : b → Prop} : Exists p → b :=\n fun (ᾰ : Exists p) => Exists.dcases_on ᾰ fun (ᾰ_w : b) (ᾰ_h : p ᾰ_w) => idRhs b ᾰ_w\n\ntheorem Exists.snd {b : Prop} {p : b → Prop} (h : Exists p) : p (Exists.fst h) :=\n Exists.dcases_on h fun (h_w : b) (h_h : p h_w) => idRhs (p h_w) h_h\n\n@[simp] theorem forall_prop_of_true {p : Prop} {q : p → Prop} (h : p) : (∀ (h' : p), q h') ↔ q h :=\n forall_const p\n\n@[simp] theorem exists_prop_of_true {p : Prop} {q : p → Prop} (h : p) : (∃ (h' : p), q h') ↔ q h :=\n exists_const p\n\n@[simp] theorem forall_prop_of_false {p : Prop} {q : p → Prop} (hn : ¬p) : (∀ (h' : p), q h') ↔ True :=\n iff_true_intro fun (h : p) => not.elim hn h\n\n@[simp] theorem exists_prop_of_false {p : Prop} {q : p → Prop} : ¬p → ¬∃ (h' : p), q h' :=\n mt Exists.fst\n\ntheorem exists_unique.exists {α : Sort u_1} {p : α → Prop} (h : exists_unique fun (x : α) => p x) : ∃ (x : α), p x :=\n exists.elim h fun (x : α) (hx : (fun (x : α) => p x) x ∧ ∀ (y : α), p y → y = x) => Exists.intro x (and.left hx)\n\ntheorem exists_unique.unique {α : Sort u_1} {p : α → Prop} (h : exists_unique fun (x : α) => p x) {y₁ : α} {y₂ : α} (py₁ : p y₁) (py₂ : p y₂) : y₁ = y₂ :=\n unique_of_exists_unique h py₁ py₂\n\n@[simp] theorem exists_unique_iff_exists {α : Sort u_1} [subsingleton α] {p : α → Prop} : (exists_unique fun (x : α) => p x) ↔ ∃ (x : α), p x :=\n { mp := fun (h : exists_unique fun (x : α) => p x) => exists_unique.exists h,\n mpr := Exists.imp fun (x : α) (hx : p x) => { left := hx, right := fun (y : α) (_x : p y) => subsingleton.elim y x } }\n\ntheorem exists_unique.elim2 {α : Sort u_1} {p : α → Sort u_2} [∀ (x : α), subsingleton (p x)] {q : (x : α) → p x → Prop} {b : Prop} (h₂ : exists_unique fun (x : α) => exists_unique fun (h : p x) => q x h) (h₁ : ∀ (x : α) (h : p x), q x h → (∀ (y : α) (hy : p y), q y hy → y = x) → b) : b := sorry\n\ntheorem exists_unique.intro2 {α : Sort u_1} {p : α → Sort u_2} [∀ (x : α), subsingleton (p x)] {q : (x : α) → p x → Prop} (w : α) (hp : p w) (hq : q w hp) (H : ∀ (y : α) (hy : p y), q y hy → y = w) : exists_unique fun (x : α) => exists_unique fun (hx : p x) => q x hx := sorry\n\ntheorem exists_unique.exists2 {α : Sort u_1} {p : α → Sort u_2} {q : (x : α) → p x → Prop} (h : exists_unique fun (x : α) => exists_unique fun (hx : p x) => q x hx) : ∃ (x : α), ∃ (hx : p x), q x hx :=\n Exists.imp (fun (x : α) (hx : exists_unique fun (hx : p x) => q x hx) => exists_unique.exists hx)\n (exists_unique.exists h)\n\ntheorem exists_unique.unique2 {α : Sort u_1} {p : α → Sort u_2} [∀ (x : α), subsingleton (p x)] {q : (x : α) → p x → Prop} (h : exists_unique fun (x : α) => exists_unique fun (hx : p x) => q x hx) {y₁ : α} {y₂ : α} (hpy₁ : p y₁) (hqy₁ : q y₁ hpy₁) (hpy₂ : p y₂) (hqy₂ : q y₂ hpy₂) : y₁ = y₂ := sorry\n\n/-! ### Classical lemmas -/\n\nnamespace classical\n\n\ntheorem cases {p : Prop → Prop} (h1 : p True) (h2 : p False) (a : Prop) : p a :=\n cases_on a h1 h2\n\n/- use shortened names to avoid conflict when classical namespace is open. -/\n\ntheorem dec (p : Prop) : Decidable p :=\n prop_decidable p\n\ntheorem dec_pred {α : Sort u_1} (p : α → Prop) : decidable_pred p :=\n fun (a : α) => prop_decidable (p a)\n\ntheorem dec_rel {α : Sort u_1} (p : α → α → Prop) : DecidableRel p :=\n fun (a b : α) => prop_decidable (p a b)\n\ntheorem dec_eq (α : Sort u_1) : DecidableEq α :=\n fun (a b : α) => prop_decidable (a = b)\n\n/--\nWe make decidability results that depends on `classical.choice` noncomputable lemmas.\n* We have to mark them as noncomputable, because otherwise Lean will try to generate bytecode\n for them, and fail because it depends on `classical.choice`.\n* We make them lemmas, and not definitions, because otherwise later definitions will raise\n \\\"failed to generate bytecode\\\" errors when writing something like\n `letI := classical.dec_eq _`.\nCf. \n-/\n/-- Construct a function from a default value `H0`, and a function to use if there exists a value\nsatisfying the predicate. -/\ndef exists_cases {α : Sort u_1} {p : α → Prop} {C : Sort u} (H0 : C) (H : (a : α) → p a → C) : C :=\n dite (∃ (a : α), p a) (fun (h : ∃ (a : α), p a) => H (some h) sorry) fun (h : ¬∃ (a : α), p a) => H0\n\ntheorem some_spec2 {α : Sort u_1} {p : α → Prop} {h : ∃ (a : α), p a} (q : α → Prop) (hpq : ∀ (a : α), p a → q a) : q (some h) :=\n hpq (some h) (some_spec h)\n\n/-- A version of classical.indefinite_description which is definitionally equal to a pair -/\ndef subtype_of_exists {α : Type u_1} {P : α → Prop} (h : ∃ (x : α), P x) : Subtype fun (x : α) => P x :=\n { val := some h, property := sorry }\n\nend classical\n\n\n/-- This function has the same type as `exists.rec_on`, and can be used to case on an equality,\nbut `exists.rec_on` can only eliminate into Prop, while this version eliminates into any universe\nusing the axiom of choice. -/\ndef exists.classical_rec_on {α : Sort u_1} {p : α → Prop} (h : ∃ (a : α), p a) {C : Sort u} (H : (a : α) → p a → C) : C :=\n H (classical.some h) sorry\n\n/-! ### Declarations about bounded quantifiers -/\n\ntheorem bex_def {α : Sort u_1} {p : α → Prop} {q : α → Prop} : (∃ (x : α), ∃ (h : p x), q x) ↔ ∃ (x : α), p x ∧ q x := sorry\n\ntheorem bex.elim {α : Sort u_1} {p : α → Prop} {P : (x : α) → p x → Prop} {b : Prop} : (∃ (x : α), ∃ (h : p x), P x h) → (∀ (a : α) (h : p a), P a h → b) → b := sorry\n\ntheorem bex.intro {α : Sort u_1} {p : α → Prop} {P : (x : α) → p x → Prop} (a : α) (h₁ : p a) (h₂ : P a h₁) : ∃ (x : α), ∃ (h : p x), P x h :=\n Exists.intro a (Exists.intro h₁ h₂)\n\ntheorem ball_congr {α : Sort u_1} {p : α → Prop} {P : (x : α) → p x → Prop} {Q : (x : α) → p x → Prop} (H : ∀ (x : α) (h : p x), P x h ↔ Q x h) : (∀ (x : α) (h : p x), P x h) ↔ ∀ (x : α) (h : p x), Q x h :=\n forall_congr fun (x : α) => forall_congr (H x)\n\ntheorem bex_congr {α : Sort u_1} {p : α → Prop} {P : (x : α) → p x → Prop} {Q : (x : α) → p x → Prop} (H : ∀ (x : α) (h : p x), P x h ↔ Q x h) : (∃ (x : α), ∃ (h : p x), P x h) ↔ ∃ (x : α), ∃ (h : p x), Q x h :=\n exists_congr fun (x : α) => exists_congr (H x)\n\ntheorem bex_eq_left {α : Sort u_1} {p : α → Prop} {a : α} : (∃ (x : α), ∃ (_x : x = a), p x) ↔ p a := sorry\n\ntheorem ball.imp_right {α : Sort u_1} {p : α → Prop} {P : (x : α) → p x → Prop} {Q : (x : α) → p x → Prop} (H : ∀ (x : α) (h : p x), P x h → Q x h) (h₁ : ∀ (x : α) (h : p x), P x h) (x : α) (h : p x) : Q x h :=\n H x h (h₁ x h)\n\ntheorem bex.imp_right {α : Sort u_1} {p : α → Prop} {P : (x : α) → p x → Prop} {Q : (x : α) → p x → Prop} (H : ∀ (x : α) (h : p x), P x h → Q x h) : (∃ (x : α), ∃ (h : p x), P x h) → ∃ (x : α), ∃ (h : p x), Q x h := sorry\n\ntheorem ball.imp_left {α : Sort u_1} {r : α → Prop} {p : α → Prop} {q : α → Prop} (H : ∀ (x : α), p x → q x) (h₁ : ∀ (x : α), q x → r x) (x : α) (h : p x) : r x :=\n h₁ x (H x h)\n\ntheorem bex.imp_left {α : Sort u_1} {r : α → Prop} {p : α → Prop} {q : α → Prop} (H : ∀ (x : α), p x → q x) : (∃ (x : α), ∃ (_x : p x), r x) → ∃ (x : α), ∃ (_x : q x), r x := sorry\n\ntheorem ball_of_forall {α : Sort u_1} {p : α → Prop} (h : ∀ (x : α), p x) (x : α) : p x :=\n h x\n\ntheorem forall_of_ball {α : Sort u_1} {p : α → Prop} {q : α → Prop} (H : ∀ (x : α), p x) (h : ∀ (x : α), p x → q x) (x : α) : q x :=\n h x (H x)\n\ntheorem bex_of_exists {α : Sort u_1} {p : α → Prop} {q : α → Prop} (H : ∀ (x : α), p x) : (∃ (x : α), q x) → ∃ (x : α), ∃ (_x : p x), q x :=\n fun (ᾰ : ∃ (x : α), q x) =>\n Exists.dcases_on ᾰ\n fun (ᾰ_w : α) (ᾰ_h : q ᾰ_w) => idRhs (∃ (x : α), ∃ (_x : p x), q x) (Exists.intro ᾰ_w (Exists.intro (H ᾰ_w) ᾰ_h))\n\ntheorem exists_of_bex {α : Sort u_1} {p : α → Prop} {q : α → Prop} : (∃ (x : α), ∃ (_x : p x), q x) → ∃ (x : α), q x := sorry\n\n@[simp] theorem bex_imp_distrib {α : Sort u_1} {p : α → Prop} {P : (x : α) → p x → Prop} {b : Prop} : (∃ (x : α), ∃ (h : p x), P x h) → b ↔ ∀ (x : α) (h : p x), P x h → b := sorry\n\ntheorem not_bex {α : Sort u_1} {p : α → Prop} {P : (x : α) → p x → Prop} : (¬∃ (x : α), ∃ (h : p x), P x h) ↔ ∀ (x : α) (h : p x), ¬P x h :=\n bex_imp_distrib\n\ntheorem not_ball_of_bex_not {α : Sort u_1} {p : α → Prop} {P : (x : α) → p x → Prop} : (∃ (x : α), ∃ (h : p x), ¬P x h) → ¬∀ (x : α) (h : p x), P x h := sorry\n\n-- See Note [decidable namespace]\n\nprotected theorem decidable.not_ball {α : Sort u_1} {p : α → Prop} {P : (x : α) → p x → Prop} [Decidable (∃ (x : α), ∃ (h : p x), ¬P x h)] [(x : α) → (h : p x) → Decidable (P x h)] : (¬∀ (x : α) (h : p x), P x h) ↔ ∃ (x : α), ∃ (h : p x), ¬P x h := sorry\n\ntheorem not_ball {α : Sort u_1} {p : α → Prop} {P : (x : α) → p x → Prop} : (¬∀ (x : α) (h : p x), P x h) ↔ ∃ (x : α), ∃ (h : p x), ¬P x h :=\n decidable.not_ball\n\ntheorem ball_true_iff {α : Sort u_1} (p : α → Prop) : (∀ (x : α), p x → True) ↔ True :=\n iff_true_intro fun (h : α) (hrx : p h) => trivial\n\ntheorem ball_and_distrib {α : Sort u_1} {p : α → Prop} {P : (x : α) → p x → Prop} {Q : (x : α) → p x → Prop} : (∀ (x : α) (h : p x), P x h ∧ Q x h) ↔ (∀ (x : α) (h : p x), P x h) ∧ ∀ (x : α) (h : p x), Q x h :=\n iff.trans (forall_congr fun (x : α) => forall_and_distrib) forall_and_distrib\n\ntheorem bex_or_distrib {α : Sort u_1} {p : α → Prop} {P : (x : α) → p x → Prop} {Q : (x : α) → p x → Prop} : (∃ (x : α), ∃ (h : p x), P x h ∨ Q x h) ↔ (∃ (x : α), ∃ (h : p x), P x h) ∨ ∃ (x : α), ∃ (h : p x), Q x h :=\n iff.trans (exists_congr fun (x : α) => exists_or_distrib) exists_or_distrib\n\ntheorem ball_or_left_distrib {α : Sort u_1} {r : α → Prop} {p : α → Prop} {q : α → Prop} : (∀ (x : α), p x ∨ q x → r x) ↔ (∀ (x : α), p x → r x) ∧ ∀ (x : α), q x → r x :=\n iff.trans (forall_congr fun (x : α) => or_imp_distrib) forall_and_distrib\n\ntheorem bex_or_left_distrib {α : Sort u_1} {r : α → Prop} {p : α → Prop} {q : α → Prop} : (∃ (x : α), ∃ (_x : p x ∨ q x), r x) ↔ (∃ (x : α), ∃ (_x : p x), r x) ∨ ∃ (x : α), ∃ (_x : q x), r x := sorry\n\nnamespace classical\n\n\ntheorem not_ball {α : Sort u_1} {p : α → Prop} {P : (x : α) → p x → Prop} : (¬∀ (x : α) (h : p x), P x h) ↔ ∃ (x : α), ∃ (h : p x), ¬P x h :=\n not_ball\n\nend classical\n\n\ntheorem ite_eq_iff {α : Sort u_1} {p : Prop} [Decidable p] {a : α} {b : α} {c : α} : ite p a b = c ↔ p ∧ a = c ∨ ¬p ∧ b = c := sorry\n\n@[simp] theorem ite_eq_left_iff {α : Sort u_1} {p : Prop} [Decidable p] {a : α} {b : α} : ite p a b = a ↔ ¬p → b = a := sorry\n\n@[simp] theorem ite_eq_right_iff {α : Sort u_1} {p : Prop} [Decidable p] {a : α} {b : α} : ite p a b = b ↔ p → a = b := sorry\n\n/-! ### Declarations about `nonempty` -/\n\nprotected instance has_zero.nonempty {α : Type u} [HasZero α] : Nonempty α :=\n Nonempty.intro 0\n\nprotected instance has_one.nonempty {α : Type u} [HasOne α] : Nonempty α :=\n Nonempty.intro 1\n\ntheorem exists_true_iff_nonempty {α : Sort u_1} : (∃ (a : α), True) ↔ Nonempty α := sorry\n\n@[simp] theorem nonempty_Prop {p : Prop} : Nonempty p ↔ p :=\n { mp := fun (_x : Nonempty p) => (fun (_a : Nonempty p) => nonempty.dcases_on _a fun (val : p) => idRhs p val) _x,\n mpr := fun (h : p) => Nonempty.intro h }\n\ntheorem not_nonempty_iff_imp_false {α : Type u} : ¬Nonempty α ↔ α → False := sorry\n\n@[simp] theorem nonempty_sigma {α : Type u} {γ : α → Type w} : Nonempty (sigma fun (a : α) => γ a) ↔ ∃ (a : α), Nonempty (γ a) := sorry\n\n@[simp] theorem nonempty_subtype {α : Sort u} {p : α → Prop} : Nonempty (Subtype p) ↔ ∃ (a : α), p a := sorry\n\n@[simp] theorem nonempty_prod {α : Type u} {β : Type v} : Nonempty (α × β) ↔ Nonempty α ∧ Nonempty β := sorry\n\n@[simp] theorem nonempty_pprod {α : Sort u} {β : Sort v} : Nonempty (PProd α β) ↔ Nonempty α ∧ Nonempty β := sorry\n\n@[simp] theorem nonempty_sum {α : Type u} {β : Type v} : Nonempty (α ⊕ β) ↔ Nonempty α ∨ Nonempty β := sorry\n\n@[simp] theorem nonempty_psum {α : Sort u} {β : Sort v} : Nonempty (psum α β) ↔ Nonempty α ∨ Nonempty β := sorry\n\n@[simp] theorem nonempty_psigma {α : Sort u} {β : α → Sort v} : Nonempty (psigma β) ↔ ∃ (a : α), Nonempty (β a) := sorry\n\n@[simp] theorem nonempty_empty : ¬Nonempty empty :=\n fun (_x : Nonempty empty) =>\n (fun (_a : Nonempty empty) => nonempty.dcases_on _a fun (val : empty) => idRhs False (empty.elim val)) _x\n\n@[simp] theorem nonempty_ulift {α : Type u} : Nonempty (ulift α) ↔ Nonempty α := sorry\n\n@[simp] theorem nonempty_plift {α : Sort u} : Nonempty (plift α) ↔ Nonempty α := sorry\n\n@[simp] theorem nonempty.forall {α : Sort u} {p : Nonempty α → Prop} : (∀ (h : Nonempty α), p h) ↔ ∀ (a : α), p (Nonempty.intro a) := sorry\n\n@[simp] theorem nonempty.exists {α : Sort u} {p : Nonempty α → Prop} : (∃ (h : Nonempty α), p h) ↔ ∃ (a : α), p (Nonempty.intro a) := sorry\n\ntheorem classical.nonempty_pi {α : Sort u} {β : α → Sort v} : Nonempty ((a : α) → β a) ↔ ∀ (a : α), Nonempty (β a) := sorry\n\n/-- Using `classical.choice`, lifts a (`Prop`-valued) `nonempty` instance to a (`Type`-valued)\n `inhabited` instance. `classical.inhabited_of_nonempty` already exists, in\n `core/init/classical.lean`, but the assumption is not a type class argument,\n which makes it unsuitable for some applications. -/\ndef classical.inhabited_of_nonempty' {α : Sort u} [h : Nonempty α] : Inhabited α :=\n { default := Classical.choice h }\n\n/-- Using `classical.choice`, extracts a term from a `nonempty` type. -/\nprotected def nonempty.some {α : Sort u} (h : Nonempty α) : α :=\n Classical.choice h\n\n/-- Using `classical.choice`, extracts a term from a `nonempty` type. -/\nprotected def classical.arbitrary (α : Sort u) [h : Nonempty α] : α :=\n Classical.choice h\n\n/-- Given `f : α → β`, if `α` is nonempty then `β` is also nonempty.\n `nonempty` cannot be a `functor`, because `functor` is restricted to `Type`. -/\ntheorem nonempty.map {α : Sort u} {β : Sort v} (f : α → β) : Nonempty α → Nonempty β :=\n fun (ᾰ : Nonempty α) => nonempty.dcases_on ᾰ fun (ᾰ : α) => idRhs (Nonempty β) (Nonempty.intro (f ᾰ))\n\nprotected theorem nonempty.map2 {α : Sort u_1} {β : Sort u_2} {γ : Sort u_3} (f : α → β → γ) : Nonempty α → Nonempty β → Nonempty γ :=\n fun (ᾰ : Nonempty α) (ᾰ_1 : Nonempty β) =>\n nonempty.dcases_on ᾰ\n fun (ᾰ_1_1 : α) => nonempty.dcases_on ᾰ_1 fun (ᾰ : β) => idRhs (Nonempty γ) (Nonempty.intro (f ᾰ_1_1 ᾰ))\n\nprotected theorem nonempty.congr {α : Sort u} {β : Sort v} (f : α → β) (g : β → α) : Nonempty α ↔ Nonempty β :=\n { mp := nonempty.map f, mpr := nonempty.map g }\n\ntheorem nonempty.elim_to_inhabited {α : Sort u_1} [h : Nonempty α] {p : Prop} (f : Inhabited α → p) : p :=\n nonempty.elim h (f ∘ Inhabited.mk)\n\nprotected instance prod.nonempty {α : Type u_1} {β : Type u_2} [h : Nonempty α] [h2 : Nonempty β] : Nonempty (α × β) :=\n nonempty.elim h fun (g : α) => nonempty.elim h2 fun (g2 : β) => Nonempty.intro (g, g2)\n\n/-- A function applied to a `dite` is a `dite` of that function applied to each of the branches. -/\ntheorem apply_dite {α : Sort u_1} {β : Sort u_2} (f : α → β) (P : Prop) [Decidable P] (x : P → α) (y : ¬P → α) : f (dite P x y) = dite P (fun (h : P) => f (x h)) fun (h : ¬P) => f (y h) := sorry\n\n/-- A function applied to a `ite` is a `ite` of that function applied to each of the branches. -/\ntheorem apply_ite {α : Sort u_1} {β : Sort u_2} (f : α → β) (P : Prop) [Decidable P] (x : α) (y : α) : f (ite P x y) = ite P (f x) (f y) :=\n apply_dite f P (fun (_x : P) => x) fun (_x : ¬P) => y\n\n/-- A two-argument function applied to two `dite`s is a `dite` of that two-argument function\napplied to each of the branches. -/\ntheorem apply_dite2 {α : Sort u_1} {β : Sort u_2} {γ : Sort u_3} (f : α → β → γ) (P : Prop) [Decidable P] (a : P → α) (b : ¬P → α) (c : P → β) (d : ¬P → β) : f (dite P a b) (dite P c d) = dite P (fun (h : P) => f (a h) (c h)) fun (h : ¬P) => f (b h) (d h) := sorry\n\n/-- A two-argument function applied to two `ite`s is a `ite` of that two-argument function\napplied to each of the branches. -/\ntheorem apply_ite2 {α : Sort u_1} {β : Sort u_2} {γ : Sort u_3} (f : α → β → γ) (P : Prop) [Decidable P] (a : α) (b : α) (c : β) (d : β) : f (ite P a b) (ite P c d) = ite P (f a c) (f b d) :=\n apply_dite2 f P (fun (_x : P) => a) (fun (_x : ¬P) => b) (fun (_x : P) => c) fun (_x : ¬P) => d\n\n/-- A 'dite' producing a `Pi` type `Π a, β a`, applied to a value `x : α`\nis a `dite` that applies either branch to `x`. -/\ntheorem dite_apply {α : Sort u_1} {β : α → Sort u_2} (P : Prop) [Decidable P] (f : P → (a : α) → β a) (g : ¬P → (a : α) → β a) (x : α) : dite P f g x = dite P (fun (h : P) => f h x) fun (h : ¬P) => g h x := sorry\n\n/-- A 'ite' producing a `Pi` type `Π a, β a`, applied to a value `x : α`\nis a `ite` that applies either branch to `x` -/\ntheorem ite_apply {α : Sort u_1} {β : α → Sort u_2} (P : Prop) [Decidable P] (f : (a : α) → β a) (g : (a : α) → β a) (x : α) : ite P f g x = ite P (f x) (g x) :=\n dite_apply P (fun (_x : P) => f) (fun (_x : ¬P) => g) x\n\n/-- Negation of the condition `P : Prop` in a `dite` is the same as swapping the branches. -/\n@[simp] theorem dite_not {α : Sort u_1} (P : Prop) [Decidable P] (x : ¬P → α) (y : ¬¬P → α) : dite (¬P) x y = dite P (fun (h : P) => y (not_not_intro h)) x := sorry\n\n/-- Negation of the condition `P : Prop` in a `ite` is the same as swapping the branches. -/\n@[simp] theorem ite_not {α : Sort u_1} (P : Prop) [Decidable P] (x : α) (y : α) : ite (¬P) x y = ite P y x :=\n dite_not P (fun (_x : ¬P) => x) fun (_x : ¬¬P) => y\n\ntheorem ite_and {α : Sort u_1} {p : Prop} {q : Prop} [Decidable p] [Decidable q] {x : α} {y : α} : ite (p ∧ q) x y = ite p (ite q x y) y := sorry\n\n", "meta": {"author": "AurelienSaue", "repo": "Mathlib4_auto", "sha": "590df64109b08190abe22358fabc3eae000943f2", "save_path": "github-repos/lean/AurelienSaue-Mathlib4_auto", "path": "github-repos/lean/AurelienSaue-Mathlib4_auto/Mathlib4_auto-590df64109b08190abe22358fabc3eae000943f2/Mathlib/logic/basic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.24220562872535947, "lm_q2_score": 0.09534945911506375, "lm_q1q2_score": 0.023094175693586974}} {"text": "/-\nCopyright (c) 2018 Simon Hudon. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthor: Simon Hudon\n-/\nimport data.pfun category.functor category.applicative data.list.sort data.list.basic\n\nuniverses u v\n\nlemma eq_mp_heq :\n ∀ {α β : Sort*} {a : α} {a' : β} (h₂ : a == a'), (eq.mp (type_eq_of_heq h₂) a) = a'\n| α ._ a a' heq.rfl := rfl\n\nnamespace sigma\nvariables {α₁ α₂ α₃ : Type u}\nvariables {β₁ : α₁ → Type v} {β₂ : α₂ → Type v} {β₃ : α₃ → Type v}\nvariables {g : sigma β₂ → sigma β₃} {f : sigma β₁ → sigma β₂}\n\ntheorem eq_fst {s₁ s₂ : sigma β₁} : s₁ = s₂ → s₁.1 = s₂.1 :=\nby cases s₁; cases s₂; cc\n\ntheorem eq_snd {s₁ s₂ : sigma β₁} : s₁ = s₂ → s₁.2 == s₂.2 :=\nby cases s₁; cases s₂; cc\n\n@[extensionality]\nlemma ext {x₀ x₁ : sigma β₁}\n (h₀ : x₀.1 = x₁.1)\n (h₁ : x₀.1 = x₁.1 → x₀.2 == x₁.2) :\n x₀ = x₁ :=\nby casesm* sigma _; cases h₀; cases h₁ h₀; refl\n\nlemma eta (x : sigma β₁) : sigma.mk x.1 x.2 = x :=\nby cases x; refl\n\nend sigma\n\nnamespace list\n\ndef zip_with₃ {α β γ φ} (f : α → β → γ → φ) : list α → list β → list γ → list φ\n| (x::xs) (y::ys) (z::zs) := f x y z :: zip_with₃ xs ys zs\n| _ _ _ := []\n\nvariables {m : Type u → Type v} [applicative m]\n\ndef mzip_with₃ {α β γ φ} (f : α → β → γ → m φ) : list α → list β → list γ → m (list φ)\n| (x::xs) (y::ys) (z::zs) := (::) <$> f x y z <*> mzip_with₃ xs ys zs\n| _ _ _ := pure []\n\ndef mzip_with₄ {α β γ φ ψ} (f : α → β → γ → φ → m ψ) :\n list α → list β → list γ → list φ → m (list ψ)\n| (w :: ws) (x::xs) (y::ys) (z::zs) := (::) <$> f w x y z <*> mzip_with₄ ws xs ys zs\n| _ _ _ _ := pure []\n\n-- def mmap_enum_if' {α} (p : α → Prop) [decidable_pred p] (f : ℕ → α → m α) : ℕ → list α → m (list α)\n-- | n [] := pure []\n-- | n (x :: xs) :=\n-- if p x then (::) <$> f n x <*> mmap_enum_if' (n+1) xs\n-- else cons x <$> mmap_enum_if' n xs\n\n-- def mmap_enum_if {α} (p : α → Prop) [decidable_pred p] (f : ℕ → α → m α) : list α → m (list α) :=\n-- mmap_enum_if' p f 0\n\nend list\nnamespace roption\nvariables {α : Type*} {β : Type*} {γ : Type*}\n\nopen function\nlemma assert_if_neg {p : Prop}\n (x : p → roption α)\n (h : ¬ p)\n: assert p x = roption.none :=\nby { dsimp [assert,roption.none],\n have : (∃ (h : p), (x h).dom) ↔ false,\n { split ; intros h' ; repeat { cases h' with h' },\n exact h h' },\n congr,\n repeat { rw this <|> apply hfunext },\n intros h h', cases h', }\n\nlemma assert_if_pos {p : Prop}\n (x : p → roption α)\n (h : p)\n: assert p x = x h :=\nby { dsimp [assert],\n have : (∃ (h : p), (x h).dom) ↔ (x h).dom,\n { split ; intros h'\n ; cases h' <|> split\n ; assumption, },\n cases hx : x h, congr, rw [this,hx],\n apply hfunext, rw [this,hx],\n intros, simp [hx] }\n\n@[simp]\nlemma roption.none_bind {α β : Type*} (f : α → roption β)\n: roption.none >>= f = roption.none :=\nby simp [roption.none,has_bind.bind,roption.bind,assert_if_neg]\n\nend roption\n\nnamespace monad\n\n@[simp]\nlemma bind_pure_star {m} [monad m] [is_lawful_monad m] (x : m punit) :\n x >>= (λ (_x : punit), pure punit.star : punit → m punit) = x :=\nby { transitivity,\n { apply congr_arg, ext z, cases z, refl },\n { simp } }\n\nvariables {α β γ : Type u}\nvariables {m : Type u → Type v} [monad m]\n\n@[reducible]\ndef pipe (a : α → m β) (b : β → m γ) : α → m γ :=\nλ x, a x >>= b\n\ninfixr ` >=> `:55 := pipe\n\n@[functor_norm]\nlemma map_bind_eq_bind_comp {α β γ} {m} [monad m] [is_lawful_monad m]\n (f : α → β) (cmd : m α) (g : β → m γ) :\n (f <$> cmd) >>= g = cmd >>= g ∘ f :=\nby rw [← bind_pure_comp_eq_map,bind_assoc,(∘)]; simp\n\n@[functor_norm]\nlemma bind_map {α β γ} {m} [monad m] [is_lawful_monad m]\n (f : α → γ → β) (cmd : m α) (g : α → m γ) :\n cmd >>= (λ x, f x <$> g x) = do { x ← cmd, y ← g x, pure $ f x y } :=\nby congr; ext; rw [← bind_pure (g x),map_bind]; simp\n\n@[functor_norm]\nlemma bind_seq {α β γ : Type u} {m} [monad m] [is_lawful_monad m]\n (f : α → m (γ → β)) (cmd : m α) (g : α → m γ) :\n cmd >>= (λ x, f x <*> g x) = do { x ← cmd, h ← f x, y ← g x, pure $ h y } :=\nby congr; ext; simp [seq_eq_bind_map] with functor_norm\n\nend monad\n\nattribute [functor_norm] bind_assoc has_bind.and_then map_bind seq_left_eq seq_right_eq\n\nnamespace sum\n\nvariables {e : Type v} {α β : Type u}\n\nprotected def seq : Π (x : sum e (α → β)) (f : sum e α), sum e β\n| (sum.inl e) _ := sum.inl e\n| (sum.inr f) x := f <$> x\n\ninstance : applicative (sum e) :=\n{ seq := @sum.seq e,\n pure := @sum.inr e }\n\ninstance : is_lawful_applicative (sum e) :=\nby constructor; intros;\n casesm* _ ⊕ _; simp [(<*>),sum.seq,pure,(<$>)];\n refl\n\nend sum\n\nnamespace functor\ndef foldl (α : Type u) (β : Type v) := α → α\ndef foldr (α : Type u) (β : Type v) := α → α\n\ninstance foldr.applicative {α} : applicative (foldr α) :=\n{ pure := λ _ _, id,\n seq := λ _ _ f x, f ∘ x }\n\ninstance foldl.applicative {α} : applicative (foldl α) :=\n{ pure := λ _ _, id,\n seq := λ _ _ f x, x ∘ f }\n\ninstance foldr.is_lawful_applicative {α} : is_lawful_applicative (foldr α) :=\nby refine { .. }; intros; refl\n\ninstance foldl.is_lawful_applicative {α} : is_lawful_applicative (foldl α) :=\nby refine { .. }; intros; refl\n\ndef foldr.eval {α β} (x : foldr α β) : α → α := x\n\ndef foldl.eval {α β} (x : foldl α β) : α → α := x\n\ndef foldl.cons {α β} (x : α) : foldl (list α) β :=\nlist.cons x\n\ndef foldr.cons {α β} (x : α) : foldr (list α) β :=\nlist.cons x\n\ndef foldl.cons' {α} (x : α) : foldl (list α) punit :=\nlist.cons x\n\ndef foldl.lift {α} (x : α → α) : foldl α punit := x\ndef foldr.lift {α} (x : α → α) : foldr α punit := x\n\nend functor\n\ninstance {α : Type u} : traversable (prod.{u u} α) :=\n{ map := λ β γ f (x : α × β), prod.mk x.1 $ f x.2,\n traverse := λ m _ β γ f (x : α × β), by exactI prod.mk x.1 <$> f x.2 }\n\nnamespace traversable\n\nvariables {t : Type u → Type u} [traversable t]\n\ndef to_list {α} (x : t α) : list α :=\n@functor.foldr.eval _ (t punit) (traverse functor.foldr.cons x) []\n\nend traversable\n\n/-\nnamespace name\n\n-- def append_suffix : name → string → name\n-- | (mk_string s n) s' := mk_string (s ++ s') n\n-- | n _ := n\n\nend name\n-/\n\nnamespace level\n\nmeta def fold_mvar {α} : level → (name → α → α) → α → α\n| zero f := id\n| (succ a) f := fold_mvar a f\n| (param a) f := id\n| (mvar a) f := f a\n| (max a b) f := fold_mvar a f ∘ fold_mvar b f\n| (imax a b) f := fold_mvar a f ∘ fold_mvar b f\n\nmeta def pred : level → level\n| level.zero := level.zero\n| (level.succ a) := a\n| (level.max a b) := max (pred a) (pred b)\n| (level.imax a b) := max (pred a) (pred b)\n| l@(level.param a) := l\n| l@(level.mvar a) := l\n\n\nend level\n\nnamespace native\nnamespace rb_map\n\n-- #check rb_map\n\nvariables {key : Type} {val val' : Type}\n\n-- section\n\nvariables [has_lt key] [decidable_rel ((<) : key → key → Prop)]\nvariables (f : val → val → val)\n\n-- def intersect' : list (key × val) → list (key × val) → list (key × val)\n-- | [] m := []\n-- | ((k,x)::xs) [] := []\n-- | ((k,x)::xs) ((k',x')::xs') :=\n-- if h : k < k' then intersect' xs ((k',x')::xs')\n-- else if k' < k then intersect' ((k,x)::xs) xs'\n-- else (k,f x x') :: intersect' xs xs'\n\nopen function (on_fun)\ndef sort {α : Type} (f : α → key) : list α → list α := list.merge_sort (on_fun (<) f)\n\n-- end\n\nmeta def filter_map (f : key → val → option val') (x : rb_map key val) : rb_map key val' :=\nfold x (mk _ _) $ λa b m', (insert m' a <$> f a b).get_or_else m'\n\nmeta def intersect_with (m m' : rb_map key val) : rb_map key val :=\nm.filter_map $ λ k x, f x <$> m'.find k\n\nmeta def intersect (x y : rb_map key val) : rb_map key val :=\nintersect_with (function.const val) x y\n\nmeta def difference (m m' : rb_map key val) : rb_map key val :=\nm.filter_map (λ k x, guard (¬ m'.contains k) >> pure x)\n\nend rb_map\nend native\n\nnamespace expr\n\nmeta def replace_all (e : expr) (p : expr → Prop) [decidable_pred p] (r : expr) : expr :=\ne.replace $ λ e i, guard (p e) >> pure (r.lift_vars 0 i)\n\nmeta def const_params : expr → list level\n| (const _ ls) := ls\n| _ := []\n\nmeta def sort_univ : expr → level\n| (sort ls) := ls\n| _ := level.zero\n\nmeta def collect_meta_univ (e : expr) : list name :=\nnative.rb_set.to_list $ e.fold native.mk_rb_set $ λ e' i s,\nmatch e' with\n| (sort u) := u.fold_mvar (flip native.rb_set.insert) s\n| (const _ ls) := ls.foldl (λ s' l, l.fold_mvar (flip native.rb_set.insert) s') s\n| _ := s\nend\n\nmeta def instantiate_pi : expr → list expr → expr\n| (expr.pi n bi d b) (e::es) := instantiate_pi (b.instantiate_var e) es\n| e _ := e\n\nend expr\n\nnamespace tactic\n\nmeta def unify_univ (u u' : level) : tactic unit :=\nunify (expr.sort u) (expr.sort u')\n\nmeta def add_decl' (d : declaration) : tactic expr :=\ndo add_decl d,\n pure $ expr.const d.to_name $ d.univ_params.map level.param\n\nmeta def renew : expr → tactic expr\n| (expr.local_const uniq pp bi t) := mk_local' pp bi t\n| e := fail format!\"{e} is not a local constant\"\n\nmeta def trace_expr (e : expr) : tactic expr :=\ndo t ← infer_type e >>= pp,\n e' ← pp e,\n trace format!\"{e'} : {t}\",\n pure e\n\nopen declaration (defn)\nmeta def trace_def (n : name) : tactic unit :=\ndo (defn n _ t df _ _) ← get_decl n,\n t ← pp t, df ← pp df,\n trace format!\"\\ndef {n} : {t} :=\\n{df}\\n\"\n\nmeta def is_type (e : expr) : tactic bool :=\ndo (expr.sort _) ← infer_type e | pure ff,\n pure tt\n\nmeta def list_macros : expr → list (name × list expr) | e :=\ne.fold [] (λ m i s,\n match m with\n | (expr.macro m args) := (expr.macro_def_name m, args) :: s\n | _ := s end)\n\nmeta def expand_untrusted (tac : tactic unit) : tactic unit :=\ndo tgt ← target,\n mv ← mk_meta_var tgt,\n gs ← get_goals,\n set_goals [mv],\n tac,\n env ← get_env,\n pr ← env.unfold_untrusted_macros <$> instantiate_mvars mv,\n set_goals gs,\n exact pr\n\nmeta def binders : expr → tactic (list expr)\n| (expr.pi n bi d b) :=\n do v ← mk_local' n bi d,\n (::) v <$> binders (b.instantiate_var v)\n| _ := pure []\n\nmeta def rec_args_count (t c : name) : tactic ℕ :=\ndo ct ← mk_const c >>= infer_type,\n (list.length ∘ list.filter (λ v : expr, v.local_type.is_app_of t)) <$> binders ct\n\nmeta def match_induct_hyp (n : name) : list expr → list expr → tactic (list $ expr × option expr)\n| [] [] := pure []\n| [] _ := fail \"wrong number of inductive hypotheses\"\n| (x :: xs) [] := (::) (x,none) <$> match_induct_hyp xs []\n| (x :: xs) (h :: hs) :=\ndo t ← infer_type x,\n if t.is_app_of n\n then (::) (x,h) <$> match_induct_hyp xs hs\n else (::) (x,none) <$> match_induct_hyp xs (h :: hs)\n\nmeta def is_recursive_type (n : name) : tactic bool :=\ndo e ← get_env,\n let cs := e.constructors_of n,\n rs ← cs.mmap (rec_args_count n),\n pure $ rs.any (λ r, r > 0)\n\nmeta def better_induction (e : expr) : tactic $ list (name × list (expr × option expr) × list (name × expr)) :=\ndo t ← infer_type e,\n let tn := t.get_app_fn.const_name,\n env ← get_env,\n focus1 $\n do vs ← induction e,\n gs ← get_goals,\n vs' ← list.mzip_with₃ (λ n g (pat : name × list expr × list (name × expr)),\n do let ⟨_,args,σ⟩ := pat,\n set_goals [g],\n nrec ← rec_args_count tn n,\n let ⟨args,rec⟩ := args.split_at (args.length - nrec),\n args ← match_induct_hyp tn args rec,\n pure ((n,args,σ))) (env.constructors_of tn) gs vs,\n set_goals gs,\n pure vs'\n\nmeta def extract_def' {α} (n : name) (trusted : bool) (elab_def : tactic α) : tactic α :=\ndo cxt ← list.map to_implicit <$> local_context,\n t ← target,\n (r,d) ← solve_aux t elab_def,\n d ← instantiate_mvars d,\n t' ← pis cxt t,\n d' ← lambdas cxt d,\n let univ := t'.collect_univ_params,\n add_decl $ declaration.defn n univ t' d' (reducibility_hints.regular 1 tt) trusted,\n r <$ (applyc n; assumption)\n\nopen expr list nat\n\nmeta def remove_intl_const : expr → tactic expr\n| v@(local_const uniq pp bi _) :=\n do t ← infer_type v,\n pure $ local_const uniq pp bi t\n| e := pure e\n\nmeta def intron' : ℕ → tactic (list expr)\n| 0 := pure []\n| (succ n) := (::) <$> intro1 <*> intron' n\n\nmeta def unpi : expr → tactic (list expr × expr)\n| (pi n bi d b) :=\n do v ← mk_local' n bi d,\n prod.map (cons v) id <$> unpi (b.instantiate_var v)\n| e := pure ([],e)\n\nmeta def unify_app_aux : expr → expr → list expr → tactic expr\n| e (pi _ _ d b) (a :: as) :=\ndo t ← infer_type a,\n unify t d,\n e' ← head_beta (e a),\n b' ← whnf (b.instantiate_var a),\n unify_app_aux e' b' as\n| e t (_ :: _) := fail \"too many arguments\"\n| e _ [] := pure e\n\nmeta def unify_app (e : expr) (args : list expr) : tactic expr :=\ndo t ← infer_type e >>= whnf,\n unify_app_aux e t args\n\nmeta def unify_mapp_aux : expr → expr → list (option expr) → tactic expr\n| e (pi _ _ d b) (none :: as) :=\ndo a ← mk_mvar,\n t ← infer_type a,\n unify t d,\n e' ← head_beta (e a),\n b' ← whnf (b.instantiate_var a),\n unify_mapp_aux e' b' as\n| e (pi _ _ d b) (some a :: as) :=\ndo t ← infer_type a,\n unify t d,\n e' ← head_beta (e a),\n b' ← whnf (b.instantiate_var a),\n unify_mapp_aux e' b' as\n| e t (_ :: _) := fail \"too many arguments\"\n| e _ [] := pure e\n\nmeta def unify_mapp (e : expr) (args : list (option expr)) : tactic expr :=\ndo t ← infer_type e >>= whnf,\n unify_mapp_aux e t args\n\nmeta def mk_to_string (t : expr) (fn of_string : name) (ls : list expr) (out : expr) : tactic expr :=\ndo let n := t.get_app_fn.const_name,\n d ← get_decl n,\n let r : reducibility_hints := reducibility_hints.regular 1 tt,\n env ← get_env,\n ls ← local_context,\n sig ← to_expr ``(%%t → %%out),\n of_string ← mk_const of_string,\n (_,df) ← solve_aux sig $ do\n { match env.structure_fields n with\n | (some fs) :=\n do a ← intro1,\n [(_,xs,_)] ← cases_core a,\n let l := xs.length,\n fn' ← mk_const fn,\n out ← list.mzip_with₄ (λ x (fn : name) (y : expr) z,\n do let fn := (fn.update_prefix name.anonymous).to_string,\n to_expr ``(%%of_string (%%(reflect x) ++ %%(reflect fn) ++ \" := \") ++ %%fn' %%y ++ %%of_string %%(reflect z)))\n (\"{ \" :: list.repeat \" \" (l-1)) fs xs (list.repeat \",\\n\" (l-1) ++ [\" }\"]),\n to_expr (out.foldr (λ e acc, ``(%%e ++ %%acc)) ``(%%of_string %%(reflect \"\" : expr))) >>= exact,\n pure ()\n | none :=\n do g ← main_goal,\n a ← intro1,\n xs ← cases_core a,\n fn ← mk_const fn,\n out ← xs.mmap $ λ ⟨c,xs,_⟩,\n do { out ← xs.mmap $ λ x, to_expr ``(%%of_string \" (\" ++ %%fn %%x ++ %%of_string \")\"),\n let c := (c.update_prefix name.anonymous).to_string,\n to_expr (out.foldr (λ e acc, ``(%%e ++ %%acc)) ``(%%of_string %%(reflect c : expr))) >>= exact },\n pure () end },\n df ← instantiate_mvars df >>= lambdas ls,\n t ← infer_type df,\n add_decl' $ declaration.defn (n ++ fn) d.univ_params t df r d.is_trusted\n\nmeta def mk_has_to_format : tactic unit :=\ndo `(has_to_format %%t) ← target,\n ls ← local_context,\n e ← mk_to_string t `to_fmt `format.of_string ls `(format),\n refine ``( { to_format := %%(e.mk_app ls) } ),\n pure ()\n\nmeta def mk_has_repr : tactic unit :=\ndo `(has_repr %%t) ← target,\n ls ← local_context,\n e ← mk_to_string t `repr `id ls `(string),\n refine ``( { repr := %%(e.mk_app ls) } ),\n pure ()\n\n@[derive_handler]\nmeta def has_repr_derive_handler : derive_handler :=\ninstance_derive_handler ``has_repr mk_has_repr\n\n@[derive_handler]\nmeta def has_to_format_derive_handler : derive_handler :=\ninstance_derive_handler ``has_to_format mk_has_to_format\n\ninstance name.has_repr : has_repr name :=\n{ repr := λ x, \"`\" ++ x.to_string }\n\nprivate meta def report_invalid_simp_lemma {α : Type} (n : name): tactic α :=\nfail format!\"invalid simplification lemma '{n}' (use command 'set_option trace.simp_lemmas true' for more details)\"\n\nprivate meta def check_no_overload (p : pexpr) : tactic unit :=\nwhen p.is_choice_macro $\n match p with\n | macro _ ps :=\n fail $ to_fmt \"ambiguous overload, possible interpretations\" ++\n format.join (ps.map (λ p, (to_fmt p).indent 4))\n | _ := failed\n end\n\nprivate meta def add_simps : simp_lemmas → list name → tactic simp_lemmas\n| s [] := return s\n| s (n::ns) := do s' ← s.add_simp n, add_simps s' ns\n\nprivate meta def simp_lemmas.resolve_and_add (s : simp_lemmas) (u : list name) (n : name) (ref : pexpr) : tactic (simp_lemmas × list name) :=\ndo\n p ← resolve_name n,\n check_no_overload p,\n -- unpack local refs\n let e := p.erase_annotations.get_app_fn.erase_annotations,\n match e with\n | const n _ :=\n (do b ← is_valid_simp_lemma_cnst n, guard b, save_const_type_info n ref, s ← s.add_simp n, return (s, u))\n <|>\n (do eqns ← get_eqn_lemmas_for tt n, guard (eqns.length > 0), save_const_type_info n ref, s ← add_simps s eqns, return (s, u))\n <|>\n (do env ← get_env, guard (env.is_projection n).is_some, return (s, n::u))\n <|>\n report_invalid_simp_lemma n\n | _ :=\n (do e ← i_to_expr_no_subgoals p, b ← is_valid_simp_lemma e, guard b, try (save_type_info e ref), s ← s.add e, return (s, u))\n <|>\n report_invalid_simp_lemma n\n end\n\nmeta def simp_lemmas.add_pexpr (s : simp_lemmas) (u : list name) (p : pexpr) : tactic (simp_lemmas × list name) :=\nmatch p with\n| (const c []) := simp_lemmas.resolve_and_add s u c p\n| (local_const c _ _ _) := simp_lemmas.resolve_and_add s u c p\n| _ := do new_e ← i_to_expr_no_subgoals p, s ← s.add new_e, return (s, u)\nend\n\nmeta def simp_lemmas.append_pexprs : simp_lemmas → list name → list pexpr → tactic (simp_lemmas × list name)\n| s u [] := return (s, u)\n| s u (l::ls) := do (s, u) ← simp_lemmas.add_pexpr s u l, simp_lemmas.append_pexprs s u ls\n\n\nmeta def simp_only (ls : list pexpr) (attrs : list name := []) : tactic unit :=\ndo let ls := ls.map (simp_arg_type.expr), -- >>= simp_lemmas.append_pexprs simp_lemmas.mk [],\n -- interactive.dsimp tt ls [] (interactive.loc.ns [none])\n interactive.simp none tt ls attrs (interactive.loc.ns [none])\n\nmeta def mk_substitution (vs : list expr) : tactic (list expr × list (name × expr)) :=\ndo vs' ← intron' vs.length,\n let σ := (vs.map expr.local_uniq_name).zip vs',\n pure (vs', σ)\nopen interactive.types interactive lean.parser\n\n@[user_command]\nmeta def test_signature_cmd (_ : parse $ tk \"#test\") : lean.parser unit :=\ndo e ← ident,\nshow tactic unit, from\ndo d ← get_decl e,\n let e := @const tt d.to_name d.univ_levels,\n t ← infer_type e >>= pp,\n e.collect_meta_univ.enum.mmap' $ λ ⟨i,v⟩, unify_univ (level.mvar v) (level.param (\"u_\" ++ to_string i : string)),\n e ← instantiate_mvars e,\n e ← pp e,\n trace format!\"\\nexample : {t} :=\\n{e}\\n\",\n pure ()\n\nend tactic\n\nnamespace tactic.interactive\n\nopen lean lean.parser interactive interactive.types tactic\n\nlocal postfix `*`:9000 := many\n\nmeta def splita := split; [skip, assumption]\n\n@[hole_command]\nmeta def whnf_type_hole : hole_command :=\n{ name := \"Reduce expected type\",\n descr := \"Reduce expected type\",\n action := λ es,\n do t ← match es with\n | [h] := to_expr h >>= infer_type >>= whnf\n | [] := target >>= whnf\n | _ := fail \"too many expressions\"\n end,\n trace t,\n pure [] }\n\nmeta def trace_error {α} (tac : tactic α) : tactic α\n| s :=\nmatch tac s with\n| r@(interaction_monad.result.success a a_1) := r\n| r@(interaction_monad.result.exception none a_1 a_2) := (trace \"(no error message)\" >> interaction_monad.result.exception none a_1) s\n| r@(interaction_monad.result.exception (some msg) a_1 a_2) := (trace (msg ()) >> interaction_monad.result.exception none a_1) s\nend\n\n\nend tactic.interactive\n\ninstance subsingleton.fin0 {α} : subsingleton (fin 0 → α) :=\nsubsingleton.intro $ λ a b, funext $ λ i, fin.elim0 i\n\nattribute [extensionality] function.hfunext\n\nmeta def options.list_names (o : options) : list name := o.fold [] (::)\n\nnamespace expr\n\nmeta def bracket (p : ℕ) (fmt : format) (p' : ℕ) : format :=\nif p' < p then format.paren fmt else fmt\n\nmeta def fmt_binder (n : name) : binder_info → format → format\n| binder_info.default t := format!\"({n} : {t})\"\n| binder_info.implicit t := format!\"{{{n} : {t}}\"\n| binder_info.strict_implicit t := format!\"⦃{n} : {t}⦄\"\n| binder_info.inst_implicit t := format!\"[{n} : {t}]\"\n| binder_info.aux_decl t := \"_\"\n\nmeta def parsable_printer' : expr → list name → ℕ → format\n| (expr.var a) l := λ _, format!\"@{(l.nth a).get_or_else name.anonymous}\"\n| (expr.sort level.zero) l := λ _, to_fmt \"Prop\"\n| (expr.sort (level.succ u)) l := λ _, format!\"Type.{{{u}}\"\n| (expr.sort u) l := λ _, format!\"Sort.{{{u}}\"\n| (expr.const a []) l := λ _, format!\"@{a}\"\n| (expr.const a ls) l := λ _, format!\"@{a}.{{{format.intercalate \\\" \\\" $ list.map to_fmt ls}}\"\n| (expr.mvar a a_1 a_2) l := λ _, to_fmt a\n| (expr.local_const a a_1 a_2 a_3) l := λ _, to_fmt a_1\n| (expr.app a a_1) l := bracket 10 $ format!\"{parsable_printer' a l 10} {parsable_printer' a_1 l 9}\"\n| (expr.lam a a_1 a_2 a_3) l := bracket 8 $ format!\"λ {fmt_binder a a_1 $ parsable_printer' a_2 l 10}, {parsable_printer' a_3 (a :: l) 10}\"\n| (expr.pi a a_1 a_2 a_3) l :=\n if a_3.has_var_idx 0\n then bracket 8 $ format!\"Π {fmt_binder a a_1 $ parsable_printer' a_2 l 10}, {parsable_printer' a_3 (a :: l) 10}\"\n else bracket 8 $ format!\"{parsable_printer' a_2 l 7} → {parsable_printer' a_3 (a :: l) 7}\"\n| (expr.elet a a_1 a_2 a_3) l := bracket 8 $ format!\"let {a} : {parsable_printer' a_1 l 10} := {parsable_printer' a_2 l 10} in {parsable_printer' a_3 (a :: l) 10}\"\n| (expr.macro a a_1) l := λ _, to_fmt \"unsupported\"\n\nmeta def parsable_printer (e : expr) : format := parsable_printer' e [] 10\n\nmeta def as_binder (e : expr) := fmt_binder e.local_pp_name e.binding_info (parsable_printer e.local_type)\n\nend expr\n\nmeta def stack_trace : vm_monitor ℕ :=\n{ init := 0,\n step := λ i,\n do j ← vm.stack_size,\n if i = j then pure i else do\n fn ← vm.curr_fn,\n vm.put_str $ (list.repeat ' ' j).as_string ++ fn.to_string,\n pure j }\n\nlemma mpr_mpr : Π {α β} (h : α = β) (h' : β = α) (x : α), h.mpr (h'.mpr x) = x\n| _ _ rfl rfl x := rfl\n", "meta": {"author": "avigad", "repo": "qpf", "sha": "debe2eacb8cf46b21aba2eaf3f2e20940da0263b", "save_path": "github-repos/lean/avigad-qpf", "path": "github-repos/lean/avigad-qpf/qpf-debe2eacb8cf46b21aba2eaf3f2e20940da0263b/src/for_mathlib.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40733340004593027, "lm_q2_score": 0.05665243048432501, "lm_q1q2_score": 0.023076427130045814}} {"text": "/-\n## SSA environment\n\nThis file implements the SSA environment which maps variables names from\ndifferent scopes to explicitly-typed values. It is, conceptually, a map\n`SSAVal → (α: MLIRType δ) × α` for each scope.\n\nThe main concern with such state is the definition, maintainance and use of the\nproperty that the values are defined only once, allowing us to study sections\nof the code while skipping/omitting operations very freely. Bundling uniqueness\ninvariants with the data structure would result in very tedious and context-\ndependent maintenance, which is not a friendly option.\n\nInstead, we ignore the SSA constraints when defining semantics and interpreting\nprograms, assuming the language allows shadowing and overriding values (of\ncourse, valid programs won't do that). We only define SSA constraints later on\nto prove that transformations are context-independent.\n\n`SSAScope` implements a single scope as a list of name/value pairs and supports\nedition.\n\n`SSAEnv` implements a stack of scopes. New scopes are created when entering\nregions. Here again nothing prevents a region from shadowing variables or\naccessing out-of-scope values (in the case of an isolated region), but we only\ncare when proving the correction of transformations.\n-/\n\nimport MLIR.Semantics.Fitree\nimport MLIR.Semantics.Types\nimport MLIR.Util.WriterT\nimport MLIR.Util.Tactics\n\nimport MLIR.AST\nopen MLIR.AST\n\nsection\nvariable {α σ: Type} {ε: σ → Type}\n\n-- SSAScope\n\ndef SSAScope (δ: Dialect α σ ε) :=\n List (SSAVal × (τ: MLIRType δ) × τ.eval)\n\n@[simp]\ndef SSAScope.getT {δ: Dialect α σ ε} (name: SSAVal):\n SSAScope δ → Option ((τ: MLIRType δ) × τ.eval)\n | [] => none\n | ⟨name', τ, v⟩ :: l =>\n if name' = name then some ⟨τ,v⟩ else getT name l\n\n@[simp]\ndef SSAScope.get {δ: Dialect α σ ε} (name: SSAVal):\n SSAScope δ → (τ: MLIRType δ) → Option τ.eval\n | [], _ => none\n | ⟨name', τ', v'⟩ :: l, τ =>\n if H: name' = name then\n if H': τ' = τ then\n some (cast (by simp [H']) v')\n else\n none\n else get name l τ\n\n@[simp]\ndef SSAScope.set {δ: Dialect α σ ε} (name: SSAVal) (τ: MLIRType δ) (v: τ.eval):\n SSAScope δ → SSAScope δ\n | [] => [⟨name, τ, v⟩]\n | ⟨name', τ', v'⟩ :: l =>\n if name' = name\n then ⟨name', τ, v⟩ :: l\n else ⟨name', τ', v'⟩ :: set name τ v l\n\ndef SSAScope.str {δ: Dialect α σ ε} (scope: SSAScope δ): String :=\n \"\\n\".intercalate <| scope.map fun ⟨name, τ, v⟩ => s!\"{name} = {v} : {τ}\"\n\n-- Leibniz-ish equality\ndef SSAScope.equiv {δ: Dialect α σ ε} (scope1 scope2: SSAScope δ): Prop :=\n ∀ name τ, scope1.get name τ = scope2.get name τ\n\ninstance {δ: Dialect α σ ε}: ToString (SSAScope δ) where\n toString := SSAScope.str\n\n/- Maybe useful in the future, for proofs\ndef SSAScope.has (name: SSAVal) (l: SSAScope): Bool :=\n l.any (fun ⟨name', _, _⟩ => name' == name)\n\ndef SSAScope.free (name: SSAVal) (l: SSAScope): Bool :=\n l.all (fun ⟨name', _, _⟩ => name' != name)\n\ndef SSAScope.maps (l: SSAScope) (name: SSAVal) (τ: MLIRTy) (v: τ.eval) :=\n l.Mem ⟨name, τ, v⟩ -/\n\n/-\n### SSAScope proofs\n-/\n\ntheorem SSAScope.equiv_refl {δ: Dialect α σ ε} (scope: SSAScope δ):\n scope.equiv scope := by intros name τ; rfl\n\ntheorem SSAScope.equiv_symm {δ: Dialect α σ ε} ⦃scope scope': SSAScope δ⦄:\n scope.equiv scope' → scope'.equiv scope := by\n intros H name τ\n specialize H name τ\n simp [H]\n\ntheorem SSAScope.equiv_trans {δ: Dialect α σ ε} ⦃scope₁ scope₂: SSAScope δ⦄:\n scope₁.equiv scope₂ →\n ∀ ⦃scope₃⦄, scope₂.equiv scope₃ →\n scope₁.equiv scope₃ := by\n intros H1 scope₃ H2 name τ\n specialize H1 name τ\n specialize H2 name τ\n simp [H1, H2]\n\ntheorem SSAScope.get_to_getT {δ: Dialect α σ ε} (name: SSAVal)\n (scope: SSAScope δ) (τ: MLIRType δ):\n scope.get name τ =\n match scope.getT name with\n | none => none\n | some ⟨τ', v'⟩ =>\n if H: τ' = τ then\n some (cast (by simp [H]) v')\n else\n none := by\n induction scope\n case nil => simp\n case cons head tail HInd =>\n unfold getT get\n byCases Hname: head.fst = name\n case h2 =>\n rw [HInd]\n\ntheorem SSAScope.get_some_getT {δ: Dialect α σ ε} ⦃name: SSAVal⦄\n ⦃scope: SSAScope δ⦄ ⦃τ: MLIRType δ⦄ ⦃v⦄:\n scope.get name τ = some v →\n scope.getT name = some ⟨τ, v⟩ := by\n rw [get_to_getT]\n split <;> simp at * <;> try contradiction\n case h_2 _ τ' _ Hget =>\n byCases Hτ: τ' = τ\n intros H\n rw [←H, Hget]\n rfl\n\ntheorem SSAScope.getT_none_get {δ: Dialect α σ ε} ⦃name: SSAVal⦄\n ⦃scope: SSAScope δ⦄:\n scope.getT name = none →\n ∀ τ, scope.get name τ = none := by\n induction scope <;> simp\n case cons head tail HInd =>\n byCases Hname: head.fst = name <;> assumption\n\ntheorem SSAScope.getT_some_get {δ: Dialect α σ ε} ⦃name: SSAVal⦄\n ⦃scope: SSAScope δ⦄ ⦃τ v⦄:\n scope.getT name = some ⟨τ, v⟩ →\n scope.get name τ = some v := by\n induction scope <;> simp\n case cons head tail HInd =>\n byCases Hname: head.fst = name <;> try assumption\n have ⟨headName, headτ, headVal⟩ := head; simp at *\n intros H; cases H\n simp;\n\ntheorem SSAScope.get_none_getT {δ: Dialect α σ ε} ⦃name: SSAVal⦄\n ⦃scope: SSAScope δ⦄:\n (∀ τ, scope.get name τ = none) →\n scope.getT name = none := by\n induction scope <;> simp\n case cons head tail HInd =>\n byCases Hname: head.fst = name <;> try assumption\n\ntheorem SSAScope.getT_set_ne ⦃v v': SSAVal⦄:\n v' ≠ v →\n ∀ ⦃scope: SSAScope δ⦄ ⦃τ: MLIRType δ⦄ ⦃val⦄,\n getT v (set v' τ val scope) = getT v scope := by\n intros Hne scope τ val\n induction scope with\n | nil => simp [Hne]\n | cons head tail =>\n simp\n byCases H: head.fst = v'\n . simp [Hne]\n . byCases H2: head.fst = v\n assumption\n\ntheorem SSAScope.getT_set_eq (scope: SSAScope δ) (v: SSAVal) (τ: MLIRType δ) val:\n getT v (set v τ val scope) = some ⟨τ, val⟩ := by\n induction scope with\n | nil => simp\n | cons head tail =>\n simp\n byCases H: head.fst = v\n assumption\n\ntheorem SSAScope.get_set_ne_val ⦃v v': SSAVal⦄:\n v' ≠ v →\n ∀ ⦃scope: SSAScope δ⦄ ⦃τ τ' val⦄,\n get v (set v' τ val scope) τ' = get v scope τ' := by\n intros Hne scope τ τ' val\n induction scope with\n | nil => simp [Hne]\n | cons head nil =>\n simp\n byCases H: head.fst = v'\n . simp [Hne]\n . byCases H2: head.fst = v <;> try assumption\n\ntheorem SSAScope.get_set_ne_type ⦃τ τ': MLIRType δ⦄:\n τ' ≠ τ →\n ∀ ⦃scope: SSAScope δ⦄ ⦃v: SSAVal⦄ ⦃val⦄,\n get v (set v τ' val scope) τ = none := by\n intros Hne scope v val\n induction scope with\n | nil => simp [Hne]\n | cons head tail Hind =>\n simp\n byCases H: head.fst = v\n . simp [Hne]\n . byCases H2: head.fst = v <;> try assumption\n\ntheorem SSAScope.get_set_eq (v: SSAVal) (scope: SSAScope δ) (τ: MLIRType δ) val:\n get v (set v τ val scope) τ = some val := by\n induction scope with\n | nil => simp;\n | cons head nil =>\n simp\n byCases H: head.fst = v <;> try apply cast_eq\n assumption\n\ntheorem SSAScope.set_commutes ⦃v v': SSAVal⦄:\n v' ≠ v →\n ∀ ⦃scope: SSAScope δ⦄ ⦃τ τ' val val'⦄,\n (set v τ val (set v' τ' val' scope)).equiv (set v' τ' val' (set v τ val scope)) := by\n intros Hne scope τ τ' val val'\n induction scope with\n | nil =>\n simp; simp [Hne, Hne.symm]\n simp [equiv]; intros name τ''\n byCases Hv: v' = name\n byCases Hτ: τ' = τ'' <;> simp [Hne.symm]\n | cons head tail Hind =>\n simp [equiv] at *\n intros name; specialize Hind name\n simp at *\n byCases Hv': head.fst = v' <;> simp [Hne]\n byCases Hv: head.fst = v <;> simp [Hv']\n byCases Hname: head.fst = name <;> assumption\n\n/-\n### SSAEnv\n-/\n\ninductive SSAEnv (δ: Dialect α σ ε) :=\n | One (scope: SSAScope δ)\n | Cons (head: SSAScope δ) (tail: SSAEnv δ)\n\ninstance: Inhabited (SSAEnv δ) where\n default := .One []\n\n-- An SSA environment with a single empty SSAScope\ndef SSAEnv.empty {δ: Dialect α σ ε}: SSAEnv δ := One []\n\ndef SSAEnv.str {δ: Dialect α σ ε} (env: SSAEnv δ): String :=\n match env with\n | One s => s.toString\n | Cons head tail => head.toString ++ \"---\\n\" ++ tail.str\n\ninstance {δ: Dialect α σ ε}: ToString (SSAEnv δ) where\n toString := SSAEnv.str\n\ndef SSAEnv.getT {δ: Dialect α σ ε} (name: SSAVal):\n SSAEnv δ → Option ((τ: MLIRType δ) × τ.eval)\n | One s => s.getT name\n | Cons s l => s.getT name <|> getT name l\n\ndef SSAEnv.get {δ: Dialect α σ ε} (name: SSAVal) (τ: MLIRType δ) (env: SSAEnv δ) : Option (τ.eval) :=\n match env.getT name with\n | none => none\n | some ⟨τ', v'⟩ =>\n if H': τ' = τ then\n some (cast (by simp [H']) v')\n else\n none\n\ndef SSAEnv.set {δ: Dialect α σ ε} (name: SSAVal) (τ: MLIRType δ) (v: τ.eval):\n SSAEnv δ → SSAEnv δ\n | One s => One (s.set name τ v)\n | Cons s l => Cons (s.set name τ v) l\n\n@[simp] def SSAEnv.set_One:\n SSAEnv.set name τ v (.One scope) = .One (scope.set name τ v) := rfl\n\ninstance {δ: Dialect α σ ε}: DecidableEq ((τ: MLIRType δ) × τ.eval) :=\n fun ⟨τ₁, v₁⟩ ⟨τ₂, v₂⟩ =>\n if H: τ₁ = τ₂ then\n if H': cast (by simp [H]) v₁ = v₂ then\n isTrue (by cases H; cases H'; simp [cast_eq])\n else isFalse fun h => by cases h; cases H' rfl\n else isFalse fun h => by cases h; cases H rfl\n\ndef SSAEnv.eqOn (l: List SSAVal) (env₁ env₂: SSAEnv δ): Bool :=\n l.all (fun v => env₁.getT v == env₂.getT v)\n\n-- Leibniz-ish equality\ndef SSAEnv.equiv (env₁ env₂: SSAEnv δ): Prop :=\n ∀ name τ, env₁.get name τ = env₂.get name τ\n\n-- SSAEnv theorems\n\ntheorem SSAEnv.equiv_rfl {δ: Dialect α σ ε} (env: SSAEnv δ):\n env.equiv env := by intros v τ; rfl\n\ntheorem SSAEnv.equiv_symm {δ: Dialect α σ ε} ⦃env env': SSAEnv δ⦄:\n env.equiv env' → env'.equiv env := by\n intros H name\n specialize H name\n simp [H]\n\ntheorem SSAEnv.equiv_trans {δ: Dialect α σ ε}:\n ∀ ⦃env₁ env₂: SSAEnv δ⦄, env₁.equiv env₂ →\n ∀ ⦃env₃⦄, env₂.equiv env₃ →\n env₁.equiv env₃ := by\n intros _ _ H1 _ H2 name\n specialize H1 name\n specialize H2 name\n simp [H1, H2]\n\ntheorem SSAEnv.getT_set_ne ⦃v v': SSAVal⦄:\n v' ≠ v →\n ∀ ⦃env: SSAEnv δ⦄ ⦃τ: MLIRType δ⦄ ⦃val⦄,\n getT v (set v' τ val env) = getT v env := by\n intros Hne env τ val\n cases env with\n | One s =>\n simp [getT, set]\n rw [SSAScope.getT_set_ne]\n assumption\n | Cons head tail =>\n simp [getT, set, HOrElse.hOrElse, OrElse.orElse, Option.orElse]\n rw [SSAScope.getT_set_ne]\n assumption\n\ntheorem SSAEnv.getT_set_eq (env: SSAEnv δ) (v: SSAVal) (τ: MLIRType δ) val:\n getT v (SSAEnv.set v τ val env) = some ⟨τ, val⟩ := by\n cases env with\n | One s =>\n simp [getT, set]\n rw [SSAScope.getT_set_eq]\n | Cons head tail =>\n simp [getT, set, HOrElse.hOrElse, OrElse.orElse, Option.orElse]\n simp [SSAScope.getT_set_eq]\n\ntheorem SSAEnv.get_set_ne_val ⦃v v': SSAVal⦄:\n v' ≠ v →\n ∀ ⦃env: SSAEnv δ⦄ ⦃τ τ': MLIRType δ⦄ ⦃val⦄,\n get v τ (set v' τ' val env) = get v τ env := by\n intros Hne env τ τ' val\n simp [get]\n rw [SSAEnv.getT_set_ne]\n assumption\n\ntheorem SSAEnv.get_set_eq_val {δ: Dialect α σ ε} (τ τ': MLIRType δ)\n (env: SSAEnv δ) (v: SSAVal) (val: τ'.eval):\n get v τ (set v τ' val env) =\n if H': τ' = τ then\n some (cast (by simp [H']) val)\n else\n none := by\n simp [get, getT_set_eq]\n\ntheorem SSAEnv.get_set {δ: Dialect α σ ε} (τ τ': MLIRType δ)\n (env: SSAEnv δ) (v v': SSAVal) (val: τ'.eval):\n get v τ (set v' τ' val env) =\n if v' = v then\n if H: τ' = τ then\n some (cast (by simp [H]) val)\n else\n none\n else\n get v τ env := by\n byCases H: v' = v\n . simp [get_set_eq_val]\n . rw [get_set_ne_val]\n assumption\n\ntheorem SSAEnv.get_set_eq (v: SSAVal) (env: SSAEnv δ) (τ: MLIRType δ) val:\n get v τ (set v τ val env) = some val := by\n simp [get, getT_set_eq]\n\ntheorem SSAEnv.get_set_neq (v v': SSAVal) (NEQ: v' ≠ v) (env: SSAEnv δ) (τ: MLIRType δ) val:\n get v τ (set v' τ val env) = get v τ env := by\n simp[get];\n rw[SSAEnv.getT_set_ne]; try assumption;\n\ntheorem SSAEnv.equiv_set {δ: Dialect α σ ε} ⦃env₁ env₂: SSAEnv δ⦄:\n env₁.equiv env₂ →\n ∀ ⦃name τ v⦄, (set name τ v env₁).equiv (set name τ v env₂) := by\n intros HEnv name τ v name' τ'\n byCases Hname: name = name'\n . simp [get_set_eq_val]\n . repeat rw [get_set_ne_val] <;> try assumption\n apply HEnv\n\ntheorem SSAEnv.set_commutes ⦃v v': SSAVal⦄:\n v' ≠ v →\n ∀ ⦃env: SSAEnv δ⦄ ⦃τ τ': MLIRType δ⦄ ⦃val val'⦄,\n equiv (set v τ val (set v' τ' val' env)) (set v' τ' val' (set v τ val env)) := by\n intros Hne env τ τ' val val' v₂ τ₂\n repeat rw [get_set]\n split\n . subst v\n simp [Hne]\n . split <;> simp\n\n/-\n### Interactions manipulating the environment\n-/\n\ninductive SSAEnvE (δ: Dialect α σ ε): Type → Type where\n | Get: (τ: MLIRType δ) → [Inhabited τ.eval] → SSAVal → SSAEnvE δ τ.eval\n | Set: (τ: MLIRType δ) → SSAVal → τ.eval → SSAEnvE δ Unit\n\n@[simp_itree]\ndef SSAEnvE.handle {E}: SSAEnvE δ ~> StateT (SSAEnv δ) (Fitree E) :=\n fun _ e env =>\n match e with\n | Get τ name =>\n match env.get name τ with\n | some v => return (v, env)\n | none => return (default, env)\n | Set τ name v =>\n return (.unit, env.set name τ v)\n\ndef SSAEnvE.handleLogged {E}:\n SSAEnvE δ ~> WriterT (StateT (SSAEnv δ) (Fitree E)) :=\n fun _ e => do\n let env <- WriterT.lift StateT.get\n match e with\n | Get τ name =>\n match env.get name τ with\n | some v => do\n logWriterT s!\"get {name} (={v}); \"\n return v\n | none =>\n logWriterT s!\"get {name} (not found!); \"\n return default\n | Set τ name v =>\n logWriterT s!\"set {name}={v}; \"\n WriterT.lift $ StateT.set (env.set name τ v)\n return ()\n\n@[simp_itree]\ndef SSAEnv.get? {E} (δ: Dialect α σ ε) [Member (SSAEnvE δ) E]\n (τ: MLIRType δ) (name: SSAVal): Fitree E τ.eval :=\n Fitree.trigger (SSAEnvE.Get τ name)\n\n@[simp_itree]\ndef SSAEnv.set? {E} {δ: Dialect α σ ε} [Member (SSAEnvE δ) E]\n (τ: MLIRType δ) (name?: Option SSAVal) (v: τ.eval): Fitree E Unit :=\n match name? with\n | some name =>\n Fitree.trigger (SSAEnvE.Set τ name v)\n | none =>\n return ()\n\n-- Handlers\n\ndef interpSSA (t: Fitree (SSAEnvE δ) R): StateT (SSAEnv δ) (Fitree Void1) R :=\n t.interpState SSAEnvE.handle\n\ndef interpSSA' {E} (t: Fitree (SSAEnvE δ +' E) R):\n StateT (SSAEnv δ) (Fitree E) R :=\n t.interpState (Fitree.case SSAEnvE.handle Fitree.liftHandler)\n\ndef interpSSALogged (t: Fitree (SSAEnvE δ) R):\n WriterT (StateT (SSAEnv δ) (Fitree Void1)) R :=\n t.interp SSAEnvE.handleLogged\n\ndef interpSSALogged' {E} (t: Fitree (SSAEnvE δ +' E) R):\n WriterT (StateT (SSAEnv δ) (Fitree E)) R :=\n t.interp (Fitree.case SSAEnvE.handleLogged Fitree.liftHandler)\n\n@[simp] theorem interpSSA'_Vis_left {δ: Dialect α σ ε}\n (k: T → Fitree (SSAEnvE δ +' E) R) (e: SSAEnvE δ T) (s₁: SSAEnv δ):\n interpSSA' (Fitree.Vis (Sum.inl e) k) s₁ =\n Fitree.bind (SSAEnvE.handle _ e s₁) (fun (x,s₂) => interpSSA' (k x) s₂) :=\n rfl\n\n@[simp] theorem interpSSA'_Vis_right (k: T → Fitree (SSAEnvE Δ +' E) R):\n interpSSA' (Fitree.Vis (Sum.inr e) k) =\n fun s => Fitree.Vis e (fun x => interpSSA' (k x) s) := rfl\n\n@[simp] theorem interpSSA'_ret {δ: Dialect α σ ε}:\n @interpSSA' _ _ _ δ _ E (Fitree.ret r) = fun s => Fitree.ret (r,s) := rfl\n\nprivate theorem pair_eta {α β: Type} (x: α × β): (x.fst, x.snd) = x :=\n match x with\n | (_, _) => rfl\n\n@[simp] theorem interpSSA'_trigger_MemberSumL {Δ: Dialect α' σ' ε'}\n (e: SSAEnvE Δ T) (s₁: SSAEnv Δ):\n interpSSA' (@Fitree.trigger (SSAEnvE Δ) (SSAEnvE Δ +' E) _ MemberSumL e) s₁ =\n SSAEnvE.handle _ e s₁ := by\n simp [Fitree.trigger, pair_eta]\n\ntheorem interpSSA'_bind {δ: Dialect α σ ε}\n (t: Fitree (SSAEnvE δ +' E) T) (k: T → Fitree (SSAEnvE δ +' E) R)\n (s₁: SSAEnv δ):\n interpSSA' (δ := δ) (Fitree.bind t k) s₁ =\n Fitree.bind (interpSSA' t s₁) (fun (x,s₂) => interpSSA' (k x) s₂) := by\n apply Fitree.interpState_bind\n\n\nmacro \"simp_ssaenv\" : tactic =>\n `(tactic| repeat progress (\n try rw [SSAEnv.getT_set_eq];\n try rw [SSAEnv.getT_set_ne (by assumption)]\n try rw [SSAEnv.get_set_eq]\n try rw [SSAEnv.get_set_eq_val]\n try rw [SSAEnv.get_set_ne_val (by assumption)]) )\n\nmacro \"simp_ssaenv\" \"at\" Hname:ident : tactic =>\n `(tactic| (repeat rw [SSAEnv.getT_set_eq] at $Hname:ident) <;>\n (repeat rw [SSAEnv.getT_set_ne (by assumption)] at $Hname:ident) <;>\n (repeat rw [SSAEnv.get_set_eq] at $Hname:ident) <;>\n (repeat rw [SSAEnv.get_set_eq_val] at $Hname:ident) <;>\n (repeat rw [SSAEnv.get_set_ne_val (by assumption)] at $Hname:ident))\n\nmacro \"simp_ssaenv\" \"at\" \"*\" : tactic =>\n `(tactic| (repeat rw [SSAEnv.getT_set_eq] at *) <;>\n (repeat rw [SSAEnv.getT_set_ne (by assumption)] at *) <;>\n (repeat rw [SSAEnv.get_set_eq] at *) <;>\n (repeat rw [SSAEnv.get_set_eq_val] at *) <;>\n (repeat rw [SSAEnv.get_set_ne_val (by assumption)] at *))\n", "meta": {"author": "opencompl", "repo": "lean-mlir", "sha": "85fd61e38dec57e4d67d7af4d49a1ccc67828c1b", "save_path": "github-repos/lean/opencompl-lean-mlir", "path": "github-repos/lean/opencompl-lean-mlir/lean-mlir-85fd61e38dec57e4d67d7af4d49a1ccc67828c1b/MLIR/Semantics/SSAEnv.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4073334000459302, "lm_q2_score": 0.05665241893708069, "lm_q1q2_score": 0.02307642242646752}} {"text": "/-\nCopyright (c) 2020 Adam Topaz. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Bhavik Mehta, Adam Topaz\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.default\nimport Mathlib.data.fintype.basic\nimport Mathlib.data.fin\nimport Mathlib.category_theory.concrete_category.bundled\nimport Mathlib.category_theory.concrete_category.default\nimport Mathlib.category_theory.full_subcategory\nimport Mathlib.category_theory.skeletal\nimport Mathlib.PostPort\n\nuniverses u_1 \n\nnamespace Mathlib\n\n/-!\n# The category of finite types.\n\nWe define the category of finite types, denoted `Fintype` as\n(bundled) types with a `fintype` instance.\n\nWe also define `Fintype.skeleton`, the standard skeleton of `Fintype` whose objects are `fin n`\nfor `n : ℕ`. We prove that the obvious inclusion functor `Fintype.skeleton ⥤ Fintype` is an\nequivalence of categories in `Fintype.skeleton.equivalence`.\nWe prove that `Fintype.skeleton` is a skeleton of `Fintype` in `Fintype.is_skeleton`.\n-/\n\n/-- The category of finite types. -/\ndef Fintype :=\n category_theory.bundled fintype\n\nnamespace Fintype\n\n\n/-- Construct a bundled `Fintype` from the underlying type and typeclass. -/\ndef of (X : Type u_1) [fintype X] : Fintype :=\n category_theory.bundled.of X\n\nprotected instance inhabited : Inhabited Fintype :=\n { default := category_theory.bundled.mk pempty }\n\nprotected instance fintype {X : Fintype} : fintype ↥X :=\n category_theory.bundled.str X\n\nprotected instance category_theory.category : category_theory.category Fintype :=\n category_theory.induced_category.category category_theory.bundled.α\n\n/-- The fully faithful embedding of `Fintype` into the category of types. -/\n@[simp] theorem incl_map (x : category_theory.induced_category (Type u_1) category_theory.bundled.α) (y : category_theory.induced_category (Type u_1) category_theory.bundled.α) (f : x ⟶ y) : ∀ (ᾰ : category_theory.bundled.α x), category_theory.functor.map incl f ᾰ = f ᾰ :=\n fun (ᾰ : category_theory.bundled.α x) => Eq.refl (f ᾰ)\n\nprotected instance category_theory.concrete_category : category_theory.concrete_category Fintype :=\n category_theory.concrete_category.mk incl\n\n/--\nThe \"standard\" skeleton for `Fintype`. This is the full subcategory of `Fintype` spanned by objects\nof the form `fin n` for `n : ℕ`. We parameterize the objects of `Fintype.skeleton` directly as `ℕ`,\nas the type `fin m ≃ fin n` is nonempty if and only if `n = m`.\n-/\ndef skeleton :=\n ℕ\n\nnamespace skeleton\n\n\n/-- Given any natural number `n`, this creates the associated object of `Fintype.skeleton`. -/\ndef mk : ℕ → skeleton :=\n id\n\nprotected instance inhabited : Inhabited skeleton :=\n { default := mk 0 }\n\n/-- Given any object of `Fintype.skeleton`, this returns the associated natural number. -/\ndef to_nat : skeleton → ℕ :=\n id\n\nprotected instance category_theory.category : category_theory.category skeleton :=\n category_theory.category.mk\n\ntheorem is_skeletal : category_theory.skeletal skeleton := sorry\n\n/-- The canonical fully faithful embedding of `Fintype.skeleton` into `Fintype`. -/\ndef incl : skeleton ⥤ Fintype :=\n category_theory.functor.mk (fun (X : skeleton) => of (fin X)) fun (_x _x_1 : skeleton) (f : _x ⟶ _x_1) => f\n\nprotected instance incl.category_theory.full : category_theory.full incl :=\n category_theory.full.mk\n fun (_x _x_1 : skeleton) (f : category_theory.functor.obj incl _x ⟶ category_theory.functor.obj incl _x_1) => f\n\nprotected instance incl.category_theory.faithful : category_theory.faithful incl :=\n category_theory.faithful.mk\n\nprotected instance incl.category_theory.ess_surj : category_theory.ess_surj incl :=\n category_theory.ess_surj.mk\n fun (X : Fintype) =>\n let F : ↥X ≃ fin (fintype.card ↥X) := trunc.out (fintype.equiv_fin ↥X);\n Exists.intro (fintype.card ↥X) (Nonempty.intro (category_theory.iso.mk ⇑(equiv.symm F) ⇑F))\n\nprotected instance incl.category_theory.is_equivalence : category_theory.is_equivalence incl :=\n category_theory.equivalence.equivalence_of_fully_faithfully_ess_surj incl\n\n/-- The equivalence between `Fintype.skeleton` and `Fintype`. -/\ndef equivalence : skeleton ≌ Fintype :=\n category_theory.functor.as_equivalence incl\n\n@[simp] theorem incl_mk_nat_card (n : ℕ) : fintype.card ↥(category_theory.functor.obj incl (mk n)) = n :=\n finset.card_fin n\n\nend skeleton\n\n\n/-- `Fintype.skeleton` is a skeleton of `Fintype`. -/\ndef is_skeleton : category_theory.is_skeleton_of Fintype skeleton skeleton.incl :=\n category_theory.is_skeleton_of.mk skeleton.is_skeletal skeleton.incl.category_theory.is_equivalence\n\n", "meta": {"author": "AurelienSaue", "repo": "Mathlib4_auto", "sha": "590df64109b08190abe22358fabc3eae000943f2", "save_path": "github-repos/lean/AurelienSaue-Mathlib4_auto", "path": "github-repos/lean/AurelienSaue-Mathlib4_auto/Mathlib4_auto-590df64109b08190abe22358fabc3eae000943f2/Mathlib/category_theory/Fintype.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.36658973632215985, "lm_q2_score": 0.06278920772016684, "lm_q1q2_score": 0.023017879102013288}} {"text": "/-\nCopyright (c) 2017 Scott Morrison. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Patrick Massot, Scott Morrison, Mario Carneiro, Andrew Yang\n-/\nimport topology.category.Top.epi_mono\nimport category_theory.limits.preserves.limits\nimport category_theory.category.ulift\nimport category_theory.limits.shapes.types\nimport category_theory.limits.concrete_category\n\n/-!\n# The category of topological spaces has all limits and colimits\n\nFurther, these limits and colimits are preserved by the forgetful functor --- that is, the\nunderlying types are just the limits in the category of types.\n-/\n\nopen topological_space\nopen category_theory\nopen category_theory.limits\nopen opposite\n\nuniverses u v w\n\nnoncomputable theory\n\nnamespace Top\n\nvariables {J : Type u} [small_category J]\n\nlocal notation `forget` := forget Top\n\n/--\nA choice of limit cone for a functor `F : J ⥤ Top`.\nGenerally you should just use `limit.cone F`, unless you need the actual definition\n(which is in terms of `types.limit_cone`).\n-/\ndef limit_cone (F : J ⥤ Top.{u}) : cone F :=\n{ X := Top.of {u : Π j : J, F.obj j | ∀ {i j : J} (f : i ⟶ j), F.map f (u i) = u j},\n π :=\n { app := λ j,\n { to_fun := λ u, u.val j,\n continuous_to_fun := show continuous ((λ u : Π j : J, F.obj j, u j) ∘ subtype.val),\n by continuity } } }\n\n/--\nA choice of limit cone for a functor `F : J ⥤ Top` whose topology is defined as an\ninfimum of topologies infimum.\nGenerally you should just use `limit.cone F`, unless you need the actual definition\n(which is in terms of `types.limit_cone`).\n-/\ndef limit_cone_infi (F : J ⥤ Top.{u}) : cone F :=\n{ X := ⟨(types.limit_cone (F ⋙ forget)).X, ⨅j,\n (F.obj j).str.induced ((types.limit_cone (F ⋙ forget)).π.app j)⟩,\n π :=\n { app := λ j, ⟨(types.limit_cone (F ⋙ forget)).π.app j,\n continuous_iff_le_induced.mpr (infi_le _ _)⟩,\n naturality' := λ j j' f,\n continuous_map.coe_inj ((types.limit_cone (F ⋙ forget)).π.naturality f) } }\n\n/--\nThe chosen cone `Top.limit_cone F` for a functor `F : J ⥤ Top` is a limit cone.\nGenerally you should just use `limit.is_limit F`, unless you need the actual definition\n(which is in terms of `types.limit_cone_is_limit`).\n-/\ndef limit_cone_is_limit (F : J ⥤ Top.{u}) : is_limit (limit_cone F) :=\n{ lift := λ S, { to_fun := λ x, ⟨λ j, S.π.app _ x, λ i j f, by { dsimp, erw ← S.w f, refl }⟩ },\n uniq' := λ S m h, by { ext : 3, simpa [← h] } }\n\n/--\nThe chosen cone `Top.limit_cone_infi F` for a functor `F : J ⥤ Top` is a limit cone.\nGenerally you should just use `limit.is_limit F`, unless you need the actual definition\n(which is in terms of `types.limit_cone_is_limit`).\n-/\ndef limit_cone_infi_is_limit (F : J ⥤ Top.{u}) : is_limit (limit_cone_infi F) :=\nby { refine is_limit.of_faithful forget (types.limit_cone_is_limit _) (λ s, ⟨_, _⟩) (λ s, rfl),\n exact continuous_iff_coinduced_le.mpr (le_infi $ λ j,\n coinduced_le_iff_le_induced.mp $ (continuous_iff_coinduced_le.mp (s.π.app j).continuous :\n _) ) }\n\ninstance Top_has_limits : has_limits.{u} Top.{u} :=\n{ has_limits_of_shape := λ J 𝒥, by exactI\n { has_limit := λ F, has_limit.mk { cone := limit_cone F, is_limit := limit_cone_is_limit F } } }\n\ninstance forget_preserves_limits : preserves_limits (forget : Top.{u} ⥤ Type u) :=\n{ preserves_limits_of_shape := λ J 𝒥,\n { preserves_limit := λ F,\n by exactI preserves_limit_of_preserves_limit_cone\n (limit_cone_is_limit F) (types.limit_cone_is_limit (F ⋙ forget)) } }\n\n/--\nA choice of colimit cocone for a functor `F : J ⥤ Top`.\nGenerally you should just use `colimit.coone F`, unless you need the actual definition\n(which is in terms of `types.colimit_cocone`).\n-/\ndef colimit_cocone (F : J ⥤ Top.{u}) : cocone F :=\n{ X := ⟨(types.colimit_cocone (F ⋙ forget)).X, ⨆ j,\n (F.obj j).str.coinduced ((types.colimit_cocone (F ⋙ forget)).ι.app j)⟩,\n ι :=\n { app := λ j, ⟨(types.colimit_cocone (F ⋙ forget)).ι.app j,\n continuous_iff_coinduced_le.mpr (le_supr _ j)⟩,\n naturality' := λ j j' f,\n continuous_map.coe_inj ((types.colimit_cocone (F ⋙ forget)).ι.naturality f) } }\n\n/--\nThe chosen cocone `Top.colimit_cocone F` for a functor `F : J ⥤ Top` is a colimit cocone.\nGenerally you should just use `colimit.is_colimit F`, unless you need the actual definition\n(which is in terms of `types.colimit_cocone_is_colimit`).\n-/\ndef colimit_cocone_is_colimit (F : J ⥤ Top.{u}) : is_colimit (colimit_cocone F) :=\nby { refine is_colimit.of_faithful forget (types.colimit_cocone_is_colimit _) (λ s, ⟨_, _⟩)\n (λ s, rfl),\n exact continuous_iff_le_induced.mpr (supr_le $ λ j,\n coinduced_le_iff_le_induced.mp $ (continuous_iff_coinduced_le.mp (s.ι.app j).continuous :\n _) ) }\n\ninstance Top_has_colimits : has_colimits.{u} Top.{u} :=\n{ has_colimits_of_shape := λ J 𝒥, by exactI\n { has_colimit := λ F, has_colimit.mk { cocone := colimit_cocone F, is_colimit :=\n colimit_cocone_is_colimit F } } }\n\ninstance forget_preserves_colimits : preserves_colimits (forget : Top.{u} ⥤ Type u) :=\n{ preserves_colimits_of_shape := λ J 𝒥,\n { preserves_colimit := λ F,\n by exactI preserves_colimit_of_preserves_colimit_cocone\n (colimit_cocone_is_colimit F) (types.colimit_cocone_is_colimit (F ⋙ forget)) } }\n\n/-- The projection from the product as a bundled continous map. -/\nabbreviation pi_π {ι : Type u} (α : ι → Top.{u}) (i : ι) : Top.of (Π i, α i) ⟶ α i :=\n⟨λ f, f i, continuous_apply i⟩\n\n/-- The explicit fan of a family of topological spaces given by the pi type. -/\n@[simps X π_app]\ndef pi_fan {ι : Type u} (α : ι → Top.{u}) : fan α :=\nfan.mk (Top.of (Π i, α i)) (pi_π α)\n\n/-- The constructed fan is indeed a limit -/\ndef pi_fan_is_limit {ι : Type u} (α : ι → Top.{u}) : is_limit (pi_fan α) :=\n{ lift := λ S, { to_fun := λ s i, S.π.app i s },\n uniq' := by { intros S m h, ext x i, simp [← h i] } }\n\n/--\nThe product is homeomorphic to the product of the underlying spaces,\nequipped with the product topology.\n-/\ndef pi_iso_pi {ι : Type u} (α : ι → Top.{u}) : ∏ α ≅ Top.of (Π i, α i) :=\n(limit.is_limit _).cone_point_unique_up_to_iso (pi_fan_is_limit α)\n\n@[simp, reassoc]\nlemma pi_iso_pi_inv_π {ι : Type u} (α : ι → Top) (i : ι) :\n (pi_iso_pi α).inv ≫ pi.π α i = pi_π α i :=\nby simp [pi_iso_pi]\n\n@[simp]\nlemma pi_iso_pi_inv_π_apply {ι : Type u} (α : ι → Top.{u}) (i : ι) (x : Π i, α i) :\n (pi.π α i : _) ((pi_iso_pi α).inv x) = x i :=\nconcrete_category.congr_hom (pi_iso_pi_inv_π α i) x\n\n@[simp]\nlemma pi_iso_pi_hom_apply {ι : Type u} (α : ι → Top.{u}) (i : ι) (x : ∏ α) :\n (pi_iso_pi α).hom x i = (pi.π α i : _) x :=\nbegin\n have := pi_iso_pi_inv_π α i,\n rw iso.inv_comp_eq at this,\n exact concrete_category.congr_hom this x\nend\n\n/-- The inclusion to the coproduct as a bundled continous map. -/\nabbreviation sigma_ι {ι : Type u} (α : ι → Top.{u}) (i : ι) : α i ⟶ Top.of (Σ i, α i) :=\n⟨sigma.mk i⟩\n\n/-- The explicit cofan of a family of topological spaces given by the sigma type. -/\n@[simps X ι_app]\ndef sigma_cofan {ι : Type u} (α : ι → Top.{u}) : cofan α :=\ncofan.mk (Top.of (Σ i, α i)) (sigma_ι α)\n\n/-- The constructed cofan is indeed a colimit -/\ndef sigma_cofan_is_colimit {ι : Type u} (α : ι → Top.{u}) : is_colimit (sigma_cofan α) :=\n{ desc := λ S, { to_fun := λ s, S.ι.app s.1 s.2,\n continuous_to_fun := by { continuity, dsimp only, continuity } },\n uniq' := by { intros S m h, ext ⟨i, x⟩, simp [← h i] } }\n\n/--\nThe coproduct is homeomorphic to the disjoint union of the topological spaces.\n-/\ndef sigma_iso_sigma {ι : Type u} (α : ι → Top.{u}) : ∐ α ≅ Top.of (Σ i, α i) :=\n(colimit.is_colimit _).cocone_point_unique_up_to_iso (sigma_cofan_is_colimit α)\n\n@[simp, reassoc]\nlemma sigma_iso_sigma_hom_ι {ι : Type u} (α : ι → Top) (i : ι) :\n sigma.ι α i ≫ (sigma_iso_sigma α).hom = sigma_ι α i :=\nby simp [sigma_iso_sigma]\n\n@[simp]\nlemma sigma_iso_sigma_hom_ι_apply {ι : Type u} (α : ι → Top) (i : ι) (x : α i) :\n (sigma_iso_sigma α).hom ((sigma.ι α i : _) x) = sigma.mk i x :=\nconcrete_category.congr_hom (sigma_iso_sigma_hom_ι α i) x\n\n@[simp]\nlemma sigma_iso_sigma_inv_apply {ι : Type u} (α : ι → Top) (i : ι) (x : α i) :\n (sigma_iso_sigma α).inv ⟨i, x⟩ = (sigma.ι α i : _) x :=\nby { rw [← sigma_iso_sigma_hom_ι_apply, ← comp_app], simp, }\n\nlemma induced_of_is_limit {F : J ⥤ Top.{u}} (C : cone F) (hC : is_limit C) :\n C.X.topological_space = ⨅ j, (F.obj j).topological_space.induced (C.π.app j) :=\nbegin\n let homeo := homeo_of_iso (hC.cone_point_unique_up_to_iso (limit_cone_infi_is_limit F)),\n refine homeo.inducing.induced.trans _,\n change induced homeo (⨅ (j : J), _) = _,\n simpa [induced_infi, induced_compose],\nend\n\nlemma limit_topology (F : J ⥤ Top.{u}) :\n (limit F).topological_space = ⨅ j, (F.obj j).topological_space.induced (limit.π F j) :=\ninduced_of_is_limit _ (limit.is_limit F)\n\nsection prod\n\n/-- The first projection from the product. -/\nabbreviation prod_fst {X Y : Top.{u}} : Top.of (X × Y) ⟶ X := ⟨prod.fst⟩\n\n/-- The second projection from the product. -/\nabbreviation prod_snd {X Y : Top.{u}} : Top.of (X × Y) ⟶ Y := ⟨prod.snd⟩\n\n/-- The explicit binary cofan of `X, Y` given by `X × Y`. -/\ndef prod_binary_fan (X Y : Top.{u}) : binary_fan X Y :=\nbinary_fan.mk prod_fst prod_snd\n\n/-- The constructed binary fan is indeed a limit -/\ndef prod_binary_fan_is_limit (X Y : Top.{u}) : is_limit (prod_binary_fan X Y) :=\n{ lift := λ (S : binary_fan X Y), { to_fun := λ s, (S.fst s, S.snd s) },\n fac' := begin\n rintros S (_|_),\n tidy\n end,\n uniq' := begin\n intros S m h,\n ext x,\n { specialize h walking_pair.left,\n apply_fun (λ e, (e x)) at h,\n exact h },\n { specialize h walking_pair.right,\n apply_fun (λ e, (e x)) at h,\n exact h },\n end }\n\n/--\nThe homeomorphism between `X ⨯ Y` and the set-theoretic product of `X` and `Y`,\nequipped with the product topology.\n-/\ndef prod_iso_prod (X Y : Top.{u}) : X ⨯ Y ≅ Top.of (X × Y) :=\n(limit.is_limit _).cone_point_unique_up_to_iso (prod_binary_fan_is_limit X Y)\n\n@[simp, reassoc] lemma prod_iso_prod_hom_fst (X Y : Top.{u}) :\n (prod_iso_prod X Y).hom ≫ prod_fst = limits.prod.fst :=\nby simpa [← iso.eq_inv_comp, prod_iso_prod]\n\n@[simp, reassoc] lemma prod_iso_prod_hom_snd (X Y : Top.{u}) :\n (prod_iso_prod X Y).hom ≫ prod_snd = limits.prod.snd :=\nby simpa [← iso.eq_inv_comp, prod_iso_prod]\n\n@[simp] lemma prod_iso_prod_hom_apply {X Y : Top.{u}} (x : X ⨯ Y) :\n (prod_iso_prod X Y).hom x =\n ((limits.prod.fst : X ⨯ Y ⟶ _) x, (limits.prod.snd : X ⨯ Y ⟶ _) x) :=\nbegin\n ext,\n { exact concrete_category.congr_hom (prod_iso_prod_hom_fst X Y) x },\n { exact concrete_category.congr_hom (prod_iso_prod_hom_snd X Y) x }\nend\n\n@[simp, reassoc, elementwise] lemma prod_iso_prod_inv_fst (X Y : Top.{u}) :\n (prod_iso_prod X Y).inv ≫ limits.prod.fst = prod_fst :=\nby simp [iso.inv_comp_eq]\n\n@[simp, reassoc, elementwise] lemma prod_iso_prod_inv_snd (X Y : Top.{u}) :\n (prod_iso_prod X Y).inv ≫ limits.prod.snd = prod_snd :=\nby simp [iso.inv_comp_eq]\n\nlemma prod_topology {X Y : Top} :\n (X ⨯ Y).topological_space =\n induced (limits.prod.fst : X ⨯ Y ⟶ _) X.topological_space ⊓\n induced (limits.prod.snd : X ⨯ Y ⟶ _) Y.topological_space :=\nbegin\n let homeo := homeo_of_iso (prod_iso_prod X Y),\n refine homeo.inducing.induced.trans _,\n change induced homeo (_ ⊓ _) = _,\n simpa [induced_compose]\nend\n\nlemma range_prod_map {W X Y Z : Top.{u}} (f : W ⟶ Y) (g : X ⟶ Z) :\n set.range (limits.prod.map f g) =\n (limits.prod.fst : Y ⨯ Z ⟶ _) ⁻¹' (set.range f) ∩\n (limits.prod.snd : Y ⨯ Z ⟶ _) ⁻¹' (set.range g) :=\nbegin\n ext,\n split,\n { rintros ⟨y, rfl⟩,\n simp only [set.mem_preimage, set.mem_range, set.mem_inter_eq, ←comp_apply],\n simp only [limits.prod.map_fst, limits.prod.map_snd,\n exists_apply_eq_apply, comp_apply, and_self] },\n { rintros ⟨⟨x₁, hx₁⟩, ⟨x₂, hx₂⟩⟩,\n use (prod_iso_prod W X).inv (x₁, x₂),\n apply concrete.limit_ext,\n rintro ⟨⟩,\n { simp only [← comp_apply, category.assoc], erw limits.prod.map_fst, simp [hx₁] },\n { simp only [← comp_apply, category.assoc], erw limits.prod.map_snd, simp [hx₂] } }\nend\n\nlemma inducing_prod_map {W X Y Z : Top} {f : W ⟶ X} {g : Y ⟶ Z}\n (hf : inducing f) (hg : inducing g) : inducing (limits.prod.map f g) :=\nbegin\n constructor,\n simp only [prod_topology, induced_compose, ←coe_comp, limits.prod.map_fst, limits.prod.map_snd,\n induced_inf],\n simp only [coe_comp],\n rw [← @induced_compose _ _ _ _ _ f, ← @induced_compose _ _ _ _ _ g, ← hf.induced, ← hg.induced]\nend\n\nlemma embedding_prod_map {W X Y Z : Top} {f : W ⟶ X} {g : Y ⟶ Z}\n (hf : embedding f) (hg : embedding g) : embedding (limits.prod.map f g) :=\n⟨inducing_prod_map hf.to_inducing hg.to_inducing,\nbegin\n haveI := (Top.mono_iff_injective _).mpr hf.inj,\n haveI := (Top.mono_iff_injective _).mpr hg.inj,\n exact (Top.mono_iff_injective _).mp infer_instance\nend⟩\n\nend prod\n\nsection pullback\n\nvariables {X Y Z : Top.{u}}\n\n/-- The first projection from the pullback. -/\nabbreviation pullback_fst (f : X ⟶ Z) (g : Y ⟶ Z) : Top.of { p : X × Y // f p.1 = g p.2 } ⟶ X :=\n⟨prod.fst ∘ subtype.val⟩\n\n/-- The second projection from the pullback. -/\nabbreviation pullback_snd (f : X ⟶ Z) (g : Y ⟶ Z) : Top.of { p : X × Y // f p.1 = g p.2 } ⟶ Y :=\n⟨prod.snd ∘ subtype.val⟩\n\n/-- The explicit pullback cone of `X, Y` given by `{ p : X × Y // f p.1 = g p.2 }`. -/\ndef pullback_cone (f : X ⟶ Z) (g : Y ⟶ Z) : pullback_cone f g :=\npullback_cone.mk (pullback_fst f g) (pullback_snd f g) (by { ext ⟨x, h⟩, simp [h] })\n\n/-- The constructed cone is a limit. -/\ndef pullback_cone_is_limit (f : X ⟶ Z) (g : Y ⟶ Z) :\n is_limit (pullback_cone f g) := pullback_cone.is_limit_aux' _\nbegin\n intro s,\n split, swap,\n exact { to_fun := λ x, ⟨⟨s.fst x, s.snd x⟩,\n by simpa using concrete_category.congr_hom s.condition x⟩ },\n refine ⟨_,_,_⟩,\n { ext, delta pullback_cone, simp },\n { ext, delta pullback_cone, simp },\n { intros m h₁ h₂,\n ext x,\n { simpa using concrete_category.congr_hom h₁ x },\n { simpa using concrete_category.congr_hom h₂ x } }\nend\n\n/-- The pullback of two maps can be identified as a subspace of `X × Y`. -/\ndef pullback_iso_prod_subtype (f : X ⟶ Z) (g : Y ⟶ Z) :\n pullback f g ≅ Top.of { p : X × Y // f p.1 = g p.2 } :=\n(limit.is_limit _).cone_point_unique_up_to_iso (pullback_cone_is_limit f g)\n\n@[simp, reassoc] lemma pullback_iso_prod_subtype_inv_fst (f : X ⟶ Z) (g : Y ⟶ Z) :\n (pullback_iso_prod_subtype f g).inv ≫ pullback.fst = pullback_fst f g :=\nby simpa [pullback_iso_prod_subtype]\n\n@[simp] lemma pullback_iso_prod_subtype_inv_fst_apply (f : X ⟶ Z) (g : Y ⟶ Z)\n (x : { p : X × Y // f p.1 = g p.2 }) :\n (pullback.fst : pullback f g ⟶ _) ((pullback_iso_prod_subtype f g).inv x) = (x : X × Y).fst :=\nconcrete_category.congr_hom (pullback_iso_prod_subtype_inv_fst f g) x\n\n@[simp, reassoc] lemma pullback_iso_prod_subtype_inv_snd (f : X ⟶ Z) (g : Y ⟶ Z) :\n (pullback_iso_prod_subtype f g).inv ≫ pullback.snd = pullback_snd f g :=\nby simpa [pullback_iso_prod_subtype]\n\n@[simp] lemma pullback_iso_prod_subtype_inv_snd_apply (f : X ⟶ Z) (g : Y ⟶ Z)\n (x : { p : X × Y // f p.1 = g p.2 }) :\n (pullback.snd : pullback f g ⟶ _) ((pullback_iso_prod_subtype f g).inv x) = (x : X × Y).snd :=\nconcrete_category.congr_hom (pullback_iso_prod_subtype_inv_snd f g) x\n\nlemma pullback_iso_prod_subtype_hom_fst (f : X ⟶ Z) (g : Y ⟶ Z) :\n (pullback_iso_prod_subtype f g).hom ≫ pullback_fst f g = pullback.fst :=\nby rw [←iso.eq_inv_comp, pullback_iso_prod_subtype_inv_fst]\n\nlemma pullback_iso_prod_subtype_hom_snd (f : X ⟶ Z) (g : Y ⟶ Z) :\n (pullback_iso_prod_subtype f g).hom ≫ pullback_snd f g = pullback.snd :=\nby rw [←iso.eq_inv_comp, pullback_iso_prod_subtype_inv_snd]\n\n@[simp] lemma pullback_iso_prod_subtype_hom_apply {f : X ⟶ Z} {g : Y ⟶ Z}\n (x : pullback f g) : (pullback_iso_prod_subtype f g).hom x =\n ⟨⟨(pullback.fst : pullback f g ⟶ _) x, (pullback.snd : pullback f g ⟶ _) x⟩,\n by simpa using concrete_category.congr_hom pullback.condition x⟩ :=\nbegin\n ext,\n exacts [concrete_category.congr_hom (pullback_iso_prod_subtype_hom_fst f g) x,\n concrete_category.congr_hom (pullback_iso_prod_subtype_hom_snd f g) x]\nend\n\nlemma pullback_topology {X Y Z : Top.{u}} (f : X ⟶ Z) (g : Y ⟶ Z) :\n (pullback f g).topological_space =\n induced (pullback.fst : pullback f g ⟶ _) X.topological_space ⊓\n induced (pullback.snd : pullback f g ⟶ _) Y.topological_space :=\nbegin\n let homeo := homeo_of_iso (pullback_iso_prod_subtype f g),\n refine homeo.inducing.induced.trans _,\n change induced homeo (induced _ (_ ⊓ _)) = _,\n simpa [induced_compose]\nend\n\nlemma range_pullback_to_prod {X Y Z : Top} (f : X ⟶ Z) (g : Y ⟶ Z) :\n set.range (prod.lift pullback.fst pullback.snd : pullback f g ⟶ X ⨯ Y) =\n { x | (limits.prod.fst ≫ f) x = (limits.prod.snd ≫ g) x } :=\nbegin\n ext x,\n split,\n { rintros ⟨y, rfl⟩,\n simp only [←comp_apply, set.mem_set_of_eq],\n congr' 1,\n simp [pullback.condition] },\n { intro h,\n use (pullback_iso_prod_subtype f g).inv ⟨⟨_, _⟩, h⟩,\n apply concrete.limit_ext,\n rintro ⟨⟩; simp }\nend\n\nlemma inducing_pullback_to_prod {X Y Z : Top} (f : X ⟶ Z) (g : Y ⟶ Z) :\n inducing ⇑(prod.lift pullback.fst pullback.snd : pullback f g ⟶ X ⨯ Y) :=\n⟨by simp [prod_topology, pullback_topology, induced_compose, ←coe_comp]⟩\n\nlemma embedding_pullback_to_prod {X Y Z : Top} (f : X ⟶ Z) (g : Y ⟶ Z) :\n embedding ⇑(prod.lift pullback.fst pullback.snd : pullback f g ⟶ X ⨯ Y) :=\n⟨inducing_pullback_to_prod f g, (Top.mono_iff_injective _).mp infer_instance⟩\n\n/-- If the map `S ⟶ T` is mono, then there is a description of the image of `W ×ₛ X ⟶ Y ×ₜ Z`. -/\nlemma range_pullback_map {W X Y Z S T : Top} (f₁ : W ⟶ S) (f₂ : X ⟶ S)\n (g₁ : Y ⟶ T) (g₂ : Z ⟶ T) (i₁ : W ⟶ Y) (i₂ : X ⟶ Z) (i₃ : S ⟶ T) [H₃ : mono i₃]\n (eq₁ : f₁ ≫ i₃ = i₁ ≫ g₁) (eq₂ : f₂ ≫ i₃ = i₂ ≫ g₂) :\n set.range (pullback.map f₁ f₂ g₁ g₂ i₁ i₂ i₃ eq₁ eq₂) =\n (pullback.fst : pullback g₁ g₂ ⟶ _) ⁻¹' (set.range i₁) ∩\n (pullback.snd : pullback g₁ g₂ ⟶ _) ⁻¹' (set.range i₂) :=\nbegin\n ext,\n split,\n { rintro ⟨y, rfl⟩, simp, },\n rintros ⟨⟨x₁, hx₁⟩, ⟨x₂, hx₂⟩⟩,\n have : f₁ x₁ = f₂ x₂,\n { apply (Top.mono_iff_injective _).mp H₃,\n simp only [←comp_apply, eq₁, eq₂],\n simp only [comp_apply, hx₁, hx₂],\n simp only [←comp_apply, pullback.condition] },\n use (pullback_iso_prod_subtype f₁ f₂).inv ⟨⟨x₁, x₂⟩, this⟩,\n apply concrete.limit_ext,\n rintros (_|_|_),\n { simp only [Top.comp_app, limit.lift_π_apply, category.assoc, pullback_cone.mk_π_app_one,\n hx₁, pullback_iso_prod_subtype_inv_fst_apply, subtype.coe_mk],\n simp only [← comp_apply],\n congr,\n apply limit.w _ walking_cospan.hom.inl },\n { simp [hx₁] },\n { simp [hx₂] },\nend\n\nlemma pullback_fst_range {X Y S : Top} (f : X ⟶ S) (g : Y ⟶ S) :\n set.range (pullback.fst : pullback f g ⟶ _) = { x : X | ∃ y : Y, f x = g y} :=\nbegin\n ext x,\n split,\n { rintro ⟨y, rfl⟩,\n use (pullback.snd : pullback f g ⟶ _) y,\n exact concrete_category.congr_hom pullback.condition y },\n { rintro ⟨y, eq⟩,\n use (Top.pullback_iso_prod_subtype f g).inv ⟨⟨x, y⟩, eq⟩,\n simp },\nend\n\nlemma pullback_snd_range {X Y S : Top} (f : X ⟶ S) (g : Y ⟶ S) :\n set.range (pullback.snd : pullback f g ⟶ _) = { y : Y | ∃ x : X, f x = g y} :=\nbegin\n ext y,\n split,\n { rintro ⟨x, rfl⟩,\n use (pullback.fst : pullback f g ⟶ _) x,\n exact concrete_category.congr_hom pullback.condition x },\n { rintro ⟨x, eq⟩,\n use (Top.pullback_iso_prod_subtype f g).inv ⟨⟨x, y⟩, eq⟩,\n simp },\nend\n\n/--\nIf there is a diagram where the morphisms `W ⟶ Y` and `X ⟶ Z` are embeddings,\nthen the induced morphism `W ×ₛ X ⟶ Y ×ₜ Z` is also an embedding.\n\n W ⟶ Y\n ↘ ↘\n S ⟶ T\n ↗ ↗\n X ⟶ Z\n-/\nlemma pullback_map_embedding_of_embeddings {W X Y Z S T : Top}\n (f₁ : W ⟶ S) (f₂ : X ⟶ S) (g₁ : Y ⟶ T) (g₂ : Z ⟶ T) {i₁ : W ⟶ Y} {i₂ : X ⟶ Z}\n (H₁ : embedding i₁) (H₂ : embedding i₂) (i₃ : S ⟶ T)\n (eq₁ : f₁ ≫ i₃ = i₁ ≫ g₁) (eq₂ : f₂ ≫ i₃ = i₂ ≫ g₂) :\n embedding (pullback.map f₁ f₂ g₁ g₂ i₁ i₂ i₃ eq₁ eq₂) :=\nbegin\n refine embedding_of_embedding_compose (continuous_map.continuous_to_fun _)\n (show continuous (prod.lift pullback.fst pullback.snd : pullback g₁ g₂ ⟶ Y ⨯ Z), from\n continuous_map.continuous_to_fun _) _,\n suffices : embedding\n (prod.lift pullback.fst pullback.snd ≫ limits.prod.map i₁ i₂ : pullback f₁ f₂ ⟶ _),\n { simpa [←coe_comp] using this },\n rw coe_comp,\n refine embedding.comp (embedding_prod_map H₁ H₂)\n (embedding_pullback_to_prod _ _)\nend\n\n/--\nIf there is a diagram where the morphisms `W ⟶ Y` and `X ⟶ Z` are open embeddings, and `S ⟶ T`\nis mono, then the induced morphism `W ×ₛ X ⟶ Y ×ₜ Z` is also an open embedding.\n W ⟶ Y\n ↘ ↘\n S ⟶ T\n ↗ ↗\n X ⟶ Z\n-/\nlemma pullback_map_open_embedding_of_open_embeddings {W X Y Z S T : Top}\n (f₁ : W ⟶ S) (f₂ : X ⟶ S) (g₁ : Y ⟶ T) (g₂ : Z ⟶ T) {i₁ : W ⟶ Y} {i₂ : X ⟶ Z}\n (H₁ : open_embedding i₁) (H₂ : open_embedding i₂) (i₃ : S ⟶ T) [H₃ : mono i₃]\n (eq₁ : f₁ ≫ i₃ = i₁ ≫ g₁) (eq₂ : f₂ ≫ i₃ = i₂ ≫ g₂) :\n open_embedding (pullback.map f₁ f₂ g₁ g₂ i₁ i₂ i₃ eq₁ eq₂) :=\nbegin\n split,\n { apply pullback_map_embedding_of_embeddings\n f₁ f₂ g₁ g₂ H₁.to_embedding H₂.to_embedding i₃ eq₁ eq₂ },\n { rw range_pullback_map,\n apply is_open.inter; apply continuous.is_open_preimage,\n continuity,\n exacts [H₁.open_range, H₂.open_range] }\nend\n\nlemma snd_embedding_of_left_embedding {X Y S : Top}\n {f : X ⟶ S} (H : embedding f) (g : Y ⟶ S) :\n embedding ⇑(pullback.snd : pullback f g ⟶ Y) :=\nbegin\n convert (homeo_of_iso (as_iso (pullback.snd : pullback (𝟙 S) g ⟶ _))).embedding.comp\n (pullback_map_embedding_of_embeddings f g (𝟙 _) g H\n (homeo_of_iso (iso.refl _)).embedding (𝟙 _) rfl (by simp)),\n erw ←coe_comp,\n simp\nend\n\nlemma fst_embedding_of_right_embedding {X Y S : Top}\n (f : X ⟶ S) {g : Y ⟶ S} (H : embedding g) :\n embedding ⇑(pullback.fst : pullback f g ⟶ X) :=\nbegin\n convert (homeo_of_iso (as_iso (pullback.fst : pullback f (𝟙 S) ⟶ _))).embedding.comp\n (pullback_map_embedding_of_embeddings f g f (𝟙 _)\n (homeo_of_iso (iso.refl _)).embedding H (𝟙 _) rfl (by simp)),\n erw ←coe_comp,\n simp\nend\n\nlemma embedding_of_pullback_embeddings {X Y S : Top}\n {f : X ⟶ S} {g : Y ⟶ S} (H₁ : embedding f) (H₂ : embedding g) :\n embedding (limit.π (cospan f g) walking_cospan.one) :=\nbegin\n convert H₂.comp (snd_embedding_of_left_embedding H₁ g),\n erw ←coe_comp,\n congr,\n exact (limit.w _ walking_cospan.hom.inr).symm\nend\n\nlemma snd_open_embedding_of_left_open_embedding {X Y S : Top}\n {f : X ⟶ S} (H : open_embedding f) (g : Y ⟶ S) :\n open_embedding ⇑(pullback.snd : pullback f g ⟶ Y) :=\nbegin\n convert (homeo_of_iso (as_iso (pullback.snd : pullback (𝟙 S) g ⟶ _))).open_embedding.comp\n (pullback_map_open_embedding_of_open_embeddings f g (𝟙 _) g H\n (homeo_of_iso (iso.refl _)).open_embedding (𝟙 _) rfl (by simp)),\n erw ←coe_comp,\n simp\nend\n\nlemma fst_open_embedding_of_right_open_embedding {X Y S : Top}\n (f : X ⟶ S) {g : Y ⟶ S} (H : open_embedding g) :\n open_embedding ⇑(pullback.fst : pullback f g ⟶ X) :=\nbegin\n convert (homeo_of_iso (as_iso (pullback.fst : pullback f (𝟙 S) ⟶ _))).open_embedding.comp\n (pullback_map_open_embedding_of_open_embeddings f g f (𝟙 _)\n (homeo_of_iso (iso.refl _)).open_embedding H (𝟙 _) rfl (by simp)),\n erw ←coe_comp,\n simp\nend\n\n/-- If `X ⟶ S`, `Y ⟶ S` are open embeddings, then so is `X ×ₛ Y ⟶ S`. -/\nlemma open_embedding_of_pullback_open_embeddings {X Y S : Top}\n {f : X ⟶ S} {g : Y ⟶ S} (H₁ : open_embedding f) (H₂ : open_embedding g) :\n open_embedding (limit.π (cospan f g) walking_cospan.one) :=\nbegin\n convert H₂.comp (snd_open_embedding_of_left_open_embedding H₁ g),\n erw ←coe_comp,\n congr,\n exact (limit.w _ walking_cospan.hom.inr).symm\nend\n\nlemma fst_iso_of_right_embedding_range_subset {X Y S : Top} (f : X ⟶ S) {g : Y ⟶ S}\n (hg : embedding g) (H : set.range f ⊆ set.range g) : is_iso (pullback.fst : pullback f g ⟶ X) :=\nbegin\n let : (pullback f g : Top) ≃ₜ X :=\n (homeomorph.of_embedding _ (fst_embedding_of_right_embedding f hg)).trans\n { to_fun := coe,\n inv_fun := (λ x, ⟨x,\n by { rw pullback_fst_range, exact ⟨_, (H (set.mem_range_self x)).some_spec.symm⟩ }⟩),\n left_inv := λ ⟨_,_⟩, rfl,\n right_inv := λ x, rfl },\n convert is_iso.of_iso (iso_of_homeo this),\n ext,\n refl\nend\n\nlemma snd_iso_of_left_embedding_range_subset {X Y S : Top} {f : X ⟶ S} (hf : embedding f)\n (g : Y ⟶ S) (H : set.range g ⊆ set.range f) : is_iso (pullback.snd : pullback f g ⟶ Y) :=\nbegin\n let : (pullback f g : Top) ≃ₜ Y :=\n (homeomorph.of_embedding _ (snd_embedding_of_left_embedding hf g)).trans\n { to_fun := coe,\n inv_fun := (λ x, ⟨x,\n by { rw pullback_snd_range, exact ⟨_, (H (set.mem_range_self x)).some_spec⟩ }⟩),\n left_inv := λ ⟨_,_⟩, rfl,\n right_inv := λ x, rfl },\n convert is_iso.of_iso (iso_of_homeo this),\n ext,\n refl\nend\n\nend pullback\n\n--TODO: Add analogous constructions for `coprod` and `pushout`.\n\nlemma coinduced_of_is_colimit {F : J ⥤ Top.{u}} (c : cocone F) (hc : is_colimit c) :\n c.X.topological_space = ⨆ j, (F.obj j).topological_space.coinduced (c.ι.app j) :=\nbegin\n let homeo := homeo_of_iso (hc.cocone_point_unique_up_to_iso (colimit_cocone_is_colimit F)),\n ext,\n refine homeo.symm.is_open_preimage.symm.trans (iff.trans _ is_open_supr_iff.symm),\n exact is_open_supr_iff\nend\n\nlemma colimit_topology (F : J ⥤ Top.{u}) :\n (colimit F).topological_space = ⨆ j, (F.obj j).topological_space.coinduced (colimit.ι F j) :=\ncoinduced_of_is_colimit _ (colimit.is_colimit F)\n\nlemma colimit_is_open_iff (F : J ⥤ Top.{u}) (U : set ((colimit F : _) : Type u)) :\n is_open U ↔ ∀ j, is_open (colimit.ι F j ⁻¹' U) :=\nbegin\n conv_lhs { rw colimit_topology F },\n exact is_open_supr_iff\nend\n\nlemma coequalizer_is_open_iff (F : walking_parallel_pair.{u} ⥤ Top.{u})\n (U : set ((colimit F : _) : Type u)) :\n is_open U ↔ is_open (colimit.ι F walking_parallel_pair.one ⁻¹' U) :=\nbegin\n rw colimit_is_open_iff,\n split,\n { intro H, exact H _ },\n { intros H j,\n cases j,\n { rw ←colimit.w F walking_parallel_pair_hom.left,\n exact (F.map walking_parallel_pair_hom.left).continuous_to_fun.is_open_preimage _ H },\n { exact H } }\nend\n\nend Top\n\nnamespace Top\n\nsection cofiltered_limit\n\nvariables {J : Type u} [small_category J] [is_cofiltered J] (F : J ⥤ Top.{u})\n (C : cone F) (hC : is_limit C)\n\ninclude hC\n\n/--\nGiven a *compatible* collection of topological bases for the factors in a cofiltered limit\nwhich contain `set.univ` and are closed under intersections, the induced *naive* collection\nof sets in the limit is, in fact, a topological basis.\n-/\ntheorem is_topological_basis_cofiltered_limit\n (T : Π j, set (set (F.obj j))) (hT : ∀ j, is_topological_basis (T j))\n (univ : ∀ (i : J), set.univ ∈ T i)\n (inter : ∀ i (U1 U2 : set (F.obj i)), U1 ∈ T i → U2 ∈ T i → U1 ∩ U2 ∈ T i)\n (compat : ∀ (i j : J) (f : i ⟶ j) (V : set (F.obj j)) (hV : V ∈ T j), (F.map f) ⁻¹' V ∈ T i) :\n is_topological_basis { U : set C.X | ∃ j (V : set (F.obj j)), V ∈ T j ∧ U = C.π.app j ⁻¹' V } :=\nbegin\n classical,\n -- The limit cone for `F` whose topology is defined as an infimum.\n let D := limit_cone_infi F,\n -- The isomorphism between the cone point of `C` and the cone point of `D`.\n let E : C.X ≅ D.X := hC.cone_point_unique_up_to_iso (limit_cone_infi_is_limit _),\n have hE : inducing E.hom := (Top.homeo_of_iso E).inducing,\n -- Reduce to the assertion of the theorem with `D` instead of `C`.\n suffices : is_topological_basis\n { U : set D.X | ∃ j (V : set (F.obj j)), V ∈ T j ∧ U = D.π.app j ⁻¹' V },\n { convert this.inducing hE,\n ext U0,\n split,\n { rintro ⟨j, V, hV, rfl⟩,\n refine ⟨D.π.app j ⁻¹' V, ⟨j, V, hV, rfl⟩, rfl⟩ },\n { rintro ⟨W, ⟨j, V, hV, rfl⟩, rfl⟩,\n refine ⟨j, V, hV, rfl⟩ } },\n -- Using `D`, we can apply the characterization of the topological basis of a\n -- topology defined as an infimum...\n convert is_topological_basis_infi hT (λ j (x : D.X), D.π.app j x),\n ext U0,\n split,\n { rintros ⟨j, V, hV, rfl⟩,\n let U : Π i, set (F.obj i) := λ i, if h : i = j then (by {rw h, exact V}) else set.univ,\n refine ⟨U,{j},_,_⟩,\n { rintro i h,\n rw finset.mem_singleton at h,\n dsimp [U],\n rw dif_pos h,\n subst h,\n exact hV },\n { dsimp [U],\n simp } },\n { rintros ⟨U, G, h1, h2⟩,\n obtain ⟨j, hj⟩ := is_cofiltered.inf_objs_exists G,\n let g : ∀ e (he : e ∈ G), j ⟶ e := λ _ he, (hj he).some,\n let Vs : J → set (F.obj j) := λ e, if h : e ∈ G then F.map (g e h) ⁻¹' (U e) else set.univ,\n let V : set (F.obj j) := ⋂ (e : J) (he : e ∈ G), Vs e,\n refine ⟨j, V, _, _⟩,\n { -- An intermediate claim used to apply induction along `G : finset J` later on.\n have : ∀ (S : set (set (F.obj j))) (E : finset J) (P : J → set (F.obj j))\n (univ : set.univ ∈ S)\n (inter : ∀ A B : set (F.obj j), A ∈ S → B ∈ S → A ∩ B ∈ S)\n (cond : ∀ (e : J) (he : e ∈ E), P e ∈ S), (⋂ e (he : e ∈ E), P e) ∈ S,\n { intros S E,\n apply E.induction_on,\n { intros P he hh,\n simpa },\n { intros a E ha hh1 hh2 hh3 hh4 hh5,\n rw finset.set_bInter_insert,\n refine hh4 _ _ (hh5 _ (finset.mem_insert_self _ _)) (hh1 _ hh3 hh4 _),\n intros e he,\n exact hh5 e (finset.mem_insert_of_mem he) } },\n -- use the intermediate claim to finish off the goal using `univ` and `inter`.\n refine this _ _ _ (univ _) (inter _) _,\n intros e he,\n dsimp [Vs],\n rw dif_pos he,\n exact compat j e (g e he) (U e) (h1 e he), },\n { -- conclude...\n rw h2,\n dsimp [V],\n rw set.preimage_Inter,\n congr' 1,\n ext1 e,\n rw set.preimage_Inter,\n congr' 1,\n ext1 he,\n dsimp [Vs],\n rw [dif_pos he, ← set.preimage_comp],\n congr' 1,\n change _ = ⇑(D.π.app j ≫ F.map (g e he)),\n rw D.w } }\nend\n\nend cofiltered_limit\n\nsection topological_konig\n\n/-!\n## Topological Kőnig's lemma\n\nA topological version of Kőnig's lemma is that the inverse limit of nonempty compact Hausdorff\nspaces is nonempty. (Note: this can be generalized further to inverse limits of nonempty compact\nT0 spaces, where all the maps are closed maps; see [Stone1979] --- however there is an erratum\nfor Theorem 4 that the element in the inverse limit can have cofinally many components that are\nnot closed points.)\n\nWe give this in a more general form, which is that cofiltered limits\nof nonempty compact Hausdorff spaces are nonempty\n(`nonempty_limit_cone_of_compact_t2_cofiltered_system`).\n\nThis also applies to inverse limits, where `{J : Type u} [directed_order J]` and `F : Jᵒᵖ ⥤ Top`.\n\nThe theorem is specialized to nonempty finite types (which are compact Hausdorff with the\ndiscrete topology) in `nonempty_sections_of_fintype_cofiltered_system` and\n`nonempty_sections_of_fintype_inverse_system`.\n\n(See https://stacks.math.columbia.edu/tag/086J for the Set version.)\n-/\n\nvariables {J : Type u} [small_category J]\nvariables (F : J ⥤ Top.{u})\n\nprivate abbreviation finite_diagram_arrow {J : Type u} [small_category J] (G : finset J) :=\nΣ' (X Y : J) (mX : X ∈ G) (mY : Y ∈ G), X ⟶ Y\nprivate abbreviation finite_diagram (J : Type u) [small_category J] :=\nΣ (G : finset J), finset (finite_diagram_arrow G)\n\n/--\nPartial sections of a cofiltered limit are sections when restricted to\na finite subset of objects and morphisms of `J`.\n-/\ndef partial_sections {J : Type u} [small_category J] (F : J ⥤ Top.{u})\n {G : finset J} (H : finset (finite_diagram_arrow G)) : set (Π j, F.obj j) :=\n{ u | ∀ {f : finite_diagram_arrow G} (hf : f ∈ H), F.map f.2.2.2.2 (u f.1) = u f.2.1 }\n\nlemma partial_sections.nonempty [is_cofiltered J] [h : Π (j : J), nonempty (F.obj j)]\n {G : finset J} (H : finset (finite_diagram_arrow G)) :\n (partial_sections F H).nonempty :=\nbegin\n classical,\n use λ (j : J), if hj : j ∈ G\n then F.map (is_cofiltered.inf_to G H hj) (h (is_cofiltered.inf G H)).some\n else (h _).some,\n rintros ⟨X, Y, hX, hY, f⟩ hf,\n dsimp only,\n rwa [dif_pos hX, dif_pos hY, ←comp_app, ←F.map_comp,\n @is_cofiltered.inf_to_commutes _ _ _ G H],\nend\n\nlemma partial_sections.directed :\n directed superset (λ (G : finite_diagram J), partial_sections F G.2) :=\nbegin\n classical,\n intros A B,\n let ιA : finite_diagram_arrow A.1 → finite_diagram_arrow (A.1 ⊔ B.1) :=\n λ f, ⟨f.1, f.2.1, finset.mem_union_left _ f.2.2.1, finset.mem_union_left _ f.2.2.2.1,\n f.2.2.2.2⟩,\n let ιB : finite_diagram_arrow B.1 → finite_diagram_arrow (A.1 ⊔ B.1) :=\n λ f, ⟨f.1, f.2.1, finset.mem_union_right _ f.2.2.1, finset.mem_union_right _ f.2.2.2.1,\n f.2.2.2.2⟩,\n refine ⟨⟨A.1 ⊔ B.1, A.2.image ιA ⊔ B.2.image ιB⟩, _, _⟩,\n { rintro u hu f hf,\n have : ιA f ∈ A.2.image ιA ⊔ B.2.image ιB,\n { apply finset.mem_union_left,\n rw finset.mem_image,\n refine ⟨f, hf, rfl⟩ },\n exact hu this },\n { rintro u hu f hf,\n have : ιB f ∈ A.2.image ιA ⊔ B.2.image ιB,\n { apply finset.mem_union_right,\n rw finset.mem_image,\n refine ⟨f, hf, rfl⟩ },\n exact hu this }\nend\n\nlemma partial_sections.closed [Π (j : J), t2_space (F.obj j)]\n {G : finset J} (H : finset (finite_diagram_arrow G)) :\n is_closed (partial_sections F H) :=\nbegin\n have : partial_sections F H =\n ⋂ {f : finite_diagram_arrow G} (hf : f ∈ H), { u | F.map f.2.2.2.2 (u f.1) = u f.2.1 },\n { ext1,\n simp only [set.mem_Inter, set.mem_set_of_eq],\n refl, },\n rw this,\n apply is_closed_bInter,\n intros f hf,\n apply is_closed_eq,\n continuity,\nend\n\n/--\nCofiltered limits of nonempty compact Hausdorff spaces are nonempty topological spaces.\n--/\nlemma nonempty_limit_cone_of_compact_t2_cofiltered_system\n [is_cofiltered J]\n [Π (j : J), nonempty (F.obj j)]\n [Π (j : J), compact_space (F.obj j)]\n [Π (j : J), t2_space (F.obj j)] :\n nonempty (Top.limit_cone F).X :=\nbegin\n classical,\n obtain ⟨u, hu⟩ := is_compact.nonempty_Inter_of_directed_nonempty_compact_closed\n (λ G, partial_sections F _)\n (partial_sections.directed F)\n (λ G, partial_sections.nonempty F _)\n (λ G, is_closed.is_compact (partial_sections.closed F _))\n (λ G, partial_sections.closed F _),\n use u,\n intros X Y f,\n let G : finite_diagram J :=\n ⟨{X, Y},\n {⟨X, Y,\n by simp only [true_or, eq_self_iff_true, finset.mem_insert],\n by simp only [eq_self_iff_true, or_true, finset.mem_insert, finset.mem_singleton],\n f⟩}⟩,\n exact hu _ ⟨G, rfl⟩ (finset.mem_singleton_self _),\nend\n\nend topological_konig\n\nend Top\n\nsection fintype_konig\n\n/-- This bootstraps `nonempty_sections_of_fintype_inverse_system`. In this version,\nthe `F` functor is between categories of the same universe, and it is an easy\ncorollary to `Top.nonempty_limit_cone_of_compact_t2_inverse_system`. -/\nlemma nonempty_sections_of_fintype_cofiltered_system.init\n {J : Type u} [small_category J] [is_cofiltered J] (F : J ⥤ Type u)\n [hf : Π (j : J), fintype (F.obj j)] [hne : Π (j : J), nonempty (F.obj j)] :\n F.sections.nonempty :=\nbegin\n let F' : J ⥤ Top := F ⋙ Top.discrete,\n haveI : Π (j : J), fintype (F'.obj j) := hf,\n haveI : Π (j : J), nonempty (F'.obj j) := hne,\n obtain ⟨⟨u, hu⟩⟩ := Top.nonempty_limit_cone_of_compact_t2_cofiltered_system F',\n exact ⟨u, λ _ _ f, hu f⟩,\nend\n\n/-- The cofiltered limit of nonempty finite types is nonempty.\n\nSee `nonempty_sections_of_fintype_inverse_system` for a specialization to inverse limits. -/\ntheorem nonempty_sections_of_fintype_cofiltered_system\n {J : Type u} [category.{w} J] [is_cofiltered J] (F : J ⥤ Type v)\n [Π (j : J), fintype (F.obj j)] [Π (j : J), nonempty (F.obj j)] :\n F.sections.nonempty :=\nbegin\n -- Step 1: lift everything to the `max u v w` universe.\n let J' : Type (max w v u) := as_small.{max w v} J,\n let down : J' ⥤ J := as_small.down,\n let F' : J' ⥤ Type (max u v w) := down ⋙ F ⋙ ulift_functor.{(max u w) v},\n haveI : ∀ i, nonempty (F'.obj i) := λ i, ⟨⟨classical.arbitrary (F.obj (down.obj i))⟩⟩,\n haveI : ∀ i, fintype (F'.obj i) := λ i, fintype.of_equiv (F.obj (down.obj i)) equiv.ulift.symm,\n -- Step 2: apply the bootstrap theorem\n obtain ⟨u, hu⟩ := nonempty_sections_of_fintype_cofiltered_system.init F',\n -- Step 3: interpret the results\n use λ j, (u ⟨j⟩).down,\n intros j j' f,\n have h := @hu (⟨j⟩ : J') (⟨j'⟩ : J') (ulift.up f),\n simp only [as_small.down, functor.comp_map, ulift_functor_map, functor.op_map] at h,\n simp_rw [←h],\n refl,\nend\n\n/-- The inverse limit of nonempty finite types is nonempty.\n\nSee `nonempty_sections_of_fintype_cofiltered_system` for a generalization to cofiltered limits.\nThat version applies in almost all cases, and the only difference is that this version\nallows `J` to be empty.\n\nThis may be regarded as a generalization of Kőnig's lemma.\nTo specialize: given a locally finite connected graph, take `Jᵒᵖ` to be `ℕ` and\n`F j` to be length-`j` paths that start from an arbitrary fixed vertex.\nElements of `F.sections` can be read off as infinite rays in the graph. -/\ntheorem nonempty_sections_of_fintype_inverse_system\n {J : Type u} [directed_order J] (F : Jᵒᵖ ⥤ Type v)\n [Π (j : Jᵒᵖ), fintype (F.obj j)] [Π (j : Jᵒᵖ), nonempty (F.obj j)] :\n F.sections.nonempty :=\nbegin\n tactic.unfreeze_local_instances,\n by_cases h : nonempty J,\n { apply nonempty_sections_of_fintype_cofiltered_system, },\n { rw not_nonempty_iff_imp_false at h,\n exact ⟨λ j, false.elim (h j.unop), λ j, false.elim (h j.unop)⟩, },\nend\n\nend fintype_konig\n", "meta": {"author": "jjaassoonn", "repo": "projective_space", "sha": "11fe19fe9d7991a272e7a40be4b6ad9b0c10c7ce", "save_path": "github-repos/lean/jjaassoonn-projective_space", "path": "github-repos/lean/jjaassoonn-projective_space/projective_space-11fe19fe9d7991a272e7a40be4b6ad9b0c10c7ce/src/topology/category/Top/limits.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.04603390141766851, "lm_q1q2_score": 0.023016950708834256}} {"text": "import \n tactic.induction\n tactic.linarith\n ...compiler\n ...semantics\n\nopen vm_big_step env_big_step\n\n-- convert from environment-preserving to regular big_step\nlemma env_vm_big_step {env env' P S R} :\n (env, P, S) ⟹ₙᵥ (env', R)\n → (env, P, S) ⟹ᵥₘ R :=\nbegin\n assume hnv,\n induction' hnv,\n case ERunEmpty {\n apply RunEmpty\n },\n case ERunPush {\n apply RunPush,\n exact ih\n },\n case ERunOpInstr {\n apply RunOpInstr,\n exact ih\n },\n case ERunTBranch {\n apply RunTBranch,\n exact ih\n },\n case ERunFBranch {\n apply RunFBranch,\n { exact _x },\n { exact ih }\n },\n case ERunJump {\n apply RunJump,\n { exact _x },\n { exact ih }\n },\n case ERunLookup {\n apply RunLookup,\n { exact _x },\n { exact ih }\n },\n case ERunOpenScope {\n apply RunOpenScope,\n exact ih\n },\n case ERunCloseScope {\n apply RunCloseScope,\n exact ih\n }\nend\n\ntheorem from_interm_results\n {E₁ E₂ Eᵢ P₁ P₂ S S' I R} :\n (E₁, P₁, S) ⟹ₙᵥ (Eᵢ, I)\n → (Eᵢ, P₂, I ++ S') ⟹ₙᵥ (E₂, R)\n → (E₁, P₁ ++ P₂, S ++ S') ⟹ₙᵥ (E₂, R) :=\nbegin\n assume h1 h2,\n induction' h1,\n { exact h2 },\n { apply ERunPush,\n rw ←list.cons_append,\n apply ih h2 },\n case ERunOpInstr {\n rw list.cons_append,\n apply ERunOpInstr,\n apply ih h2\n },\n case ERunTBranch {\n rw list.cons_append,\n apply ERunTBranch,\n apply ih h2\n },\n case ERunFBranch {\n rw list.cons_append,\n apply ERunFBranch,\n { rw [at_least, list.length_append], \n rw [at_least] at _x,\n linarith },\n rw [list.drop_append_of_le_length],\n apply ih h2,\n exact _x\n },\n case ERunJump {\n rw list.cons_append,\n apply ERunJump,\n { rw [at_least, list.length_append], \n rw [at_least] at _x,\n linarith },\n rw [list.drop_append_of_le_length],\n apply ih h2,\n exact _x\n },\n case ERunLookup {\n apply ERunLookup _x,\n rw ←list.cons_append,\n apply ih h2\n },\n case ERunOpenScope {\n rw list.cons_append,\n apply ERunOpenScope,\n apply ih h2\n },\n case ERunCloseScope {\n rw list.cons_append,\n apply ERunCloseScope,\n apply ih h2\n }\nend\n\nlemma from_interm_results'\n {E₁ E₂ Eᵢ P₁ P₂ S I R} :\n (E₁, P₁, S) ⟹ₙᵥ (Eᵢ, I)\n → (Eᵢ, P₂, I) ⟹ₙᵥ (E₂, R)\n → (E₁, P₁ ++ P₂, S) ⟹ₙᵥ (E₂, R) :=\nbegin\n assume h1 h2,\n rw ←list.append_nil I at h2,\n rw ←list.append_nil S,\n exact from_interm_results h1 h2\nend\n\ntheorem to_interm_results {E₁ E₂ e P S S' r} :\n (E₁, compile e ++ P, S) ⟹ₙᵥ (E₂, r :: S')\n → ∃ v, (E₁, compile e, S) ⟹ₙᵥ (E₁, v :: S) ∧ \n (E₁, P, v :: S) ⟹ₙᵥ (E₂, r :: S') :=\nbegin\n assume hnv,\n induction' e,\n case EVal {\n rw compile at hnv ⊢,\n cases' hnv,\n use v,\n apply and.intro,\n { apply ERunPush,\n exact ERunEmpty },\n { exact hnv }\n },\n case EOp {\n rw compile at hnv ⊢,\n simp at hnv ⊢,\n cases' ih_e_1 hnv,\n cases' h with he_1 h,\n cases' ih_e h with u h',\n cases' h' with he h',\n cases' h',\n use eval n m op,\n apply and.intro,\n { apply from_interm_results' he_1,\n apply from_interm_results' he,\n apply ERunOpInstr,\n exact ERunEmpty },\n { exact h' }\n },\n case EIf {\n rw compile at hnv ⊢,\n simp at hnv ⊢,\n cases' ih_e hnv, clear hnv,\n cases' h with he h,\n cases' h,\n case ERunTBranch {\n cases' ih_e_1 h with w h',\n cases' h' with he_1 h',\n cases' h',\n rw [list.drop_append_of_le_length,\n list.drop_length,\n list.nil_append] at h',\n use w,\n apply and.intro,\n { apply from_interm_results' he,\n apply ERunTBranch,\n apply from_interm_results' he_1,\n apply ERunJump,\n exact at_least_refl,\n rw list.drop_length,\n exact ERunEmpty },\n { exact h' },\n refl\n },\n case ERunFBranch {\n rw [nat.add_comm, \n list.drop_add, \n list.drop_one,\n list.drop_append_of_le_length,\n list.drop_length,\n list.nil_append,\n list.tail] at h,\n cases' ih_e_2 h with w h',\n cases' h' with he_2 h',\n use w,\n apply and.intro,\n { apply from_interm_results' he,\n apply ERunFBranch,\n { rw [at_least, \n list.length_append, \n list.length_cons], \n linarith },\n rw [nat.add_comm, \n list.drop_add, \n list.drop_one,\n list.drop_append_of_le_length,\n list.drop_length,\n list.nil_append,\n list.tail],\n exact he_2,\n refl },\n { exact h' },\n refl\n }\n },\n case EVar {\n rw compile at hnv ⊢,\n cases' hnv,\n use v,\n apply and.intro,\n { apply ERunLookup _x,\n exact ERunEmpty },\n { exact hnv }\n },\n case ELet {\n rw compile at hnv ⊢,\n simp at hnv ⊢,\n cases' ih_e hnv,\n cases' h with he h,\n cases' h,\n cases' ih_e_1 h with u h',\n cases' h' with he_1 h',\n cases' h',\n use u,\n apply and.intro,\n { apply from_interm_results' he,\n apply ERunOpenScope,\n apply from_interm_results' he_1,\n apply ERunCloseScope,\n exact ERunEmpty },\n { exact h' }\n }\nend", "meta": {"author": "sourceCode4", "repo": "VeriCompiler", "sha": "851ae7b178ffd801fafe9d6e0392f22555f89081", "save_path": "github-repos/lean/sourceCode4-VeriCompiler", "path": "github-repos/lean/sourceCode4-VeriCompiler/VeriCompiler-851ae7b178ffd801fafe9d6e0392f22555f89081/lean/proofs/lemmas/big_step.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4571367168274948, "lm_q2_score": 0.05033063776120014, "lm_q1q2_score": 0.023007982501988967}} {"text": "import data.option.basic\n\nexample (α : Type*) (a : α) [subsingleton α] : option.choice α = some a :=\nbegin\n delta option.choice,\n rw dif_pos,\n congr,\n use a,\nend\n", "meta": {"author": "kbuzzard", "repo": "xena", "sha": "cd2f0b5e948b7171dbafc5cb519a3220d318bd9d", "save_path": "github-repos/lean/kbuzzard-xena", "path": "github-repos/lean/kbuzzard-xena/xena-cd2f0b5e948b7171dbafc5cb519a3220d318bd9d/Examples/termle_solution.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4493926344647597, "lm_q2_score": 0.05108273659589833, "lm_q1q2_score": 0.02295620557450014}} {"text": "import category_theory.limits.shapes\nimport category_theory.limits.preserves.limits\nimport category_theory.limits.shapes.reflexive\n\nimport subobject_classifier\n\n/-!\n# Pullbacks inside a topos\n\nLemmas to work with pullbacks in topos\n-/\n/-\n Convention (compatible with mathlib)\n \n pullback_cone f g\n pullback_cone.mk fst snd\n\n X -snd-> Y\n | |\n fst g\n | |\n Z --f--> W\n-/\n\nopen category_theory category_theory.category category_theory.limits classifier\n\nnoncomputable theory\nuniverses u v\nvariables {C : Type u} [category.{v} C] [has_finite_limits C] [has_subobject_classifier C]\n\n\nlemma pb_classifier_condition {X Y : C} (m : X ⟶ Y) [mono m] : \n m ≫ classifier_of m = lift_truth X := \nbegin\n rw (classifies m).comm, \nend\n\n/- Useful lemmas about pb -/\nvariables {X Y : C} (m : X ⟶ Y) [mono m]\n\ndef monic_to_pb_cone : pullback_cone (truth C) (classifier_of m) :=\npullback_cone.mk (terminal.from _) m (classifier.comm _).symm\n\ndef sub_iso_cano : X ≅ s{ classifier_of m }s := \n (limit.iso_limit_cone (limit_cone.mk _ (classifies m).is_pb)).symm\n\n/- Given\n X ---> ⊤\n | |\n W -> Y ---> Ω \n h\n and the appropriate commutation, we lift it to a map W -> X,\n and we prove the commutativity of the triangle W X Y, and the uniqueness\n\n-/\ndef pb_lift_from_monic {W X Y : C} (m : X ⟶ Y) [mono m] (h : W ⟶ Y) \n (w : h ≫ (classifier_of m) = lift_truth _) := \npullback_cone.is_limit.lift' (classifies m).is_pb h (terminal.from W) w\n\ndef pb_lift_from_monic.map {W X Y : C} (m : X ⟶ Y) [mono m] (h : W ⟶ Y) \n (w : h ≫ (classifier_of m) = lift_truth _) : \n W ⟶ X := \n(pb_lift_from_monic m h w).1\n\nlemma pb_lift_from_monic.comm {W X Y : C} (m : X ⟶ Y) [mono m] (h : W ⟶ Y) \n (w : h ≫ (classifier_of m) = lift_truth _) : \n (pb_lift_from_monic.map m h w) ≫ m = h := \n(pb_lift_from_monic m h w).2.left\n\nlemma pb_lift_from_monic.unique {W X Y : C} (m : X ⟶ Y) [mono m] (h : W ⟶ Y) \n (w : h ≫ (classifier_of m) = lift_truth _) : \n ∀ u : W ⟶ X, u ≫ m = h → u = pb_lift_from_monic.map m h w := \nbegin\n intros u h1,\n have h :=\n calc \n u ≫ m = h : by assumption\n ... = (pb_lift_from_monic.map m h w) ≫ m : by symmetry; apply pb_lift_from_monic.comm,\n rw ←cancel_mono m, assumption\nend\n\n-- The product of two pullback square is a pullback square,\n-- already in mathlib in a more abstract way (i.e. limits commutes)\n-- but redoing it here is probably easier\n\nopen category_theory.limits.prod\n\nvariables {U V W Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} \n {s : pullback_cone f g} {h : U ⟶ W} {k : V ⟶ W} \n {t : pullback_cone h k} \n\ndef map_lift (s_lim : is_limit s) (t_lim : is_limit t) (u : pullback_cone (map f h) (map g k)) :\n {l // l ≫ s.fst = u.fst ≫ fst ∧ l ≫ s.snd = u.snd ≫ fst} \n× {l // l ≫ t.fst = u.fst ≫ snd ∧ l ≫ t.snd = u.snd ≫ snd} :=\nbegin\n let u_fst := eq_whisker u.condition fst,\n let u_snd := eq_whisker u.condition snd,\n rw [assoc, assoc] at u_fst u_snd,\n rw [map_fst, map_fst, ←assoc, ←assoc] at u_fst,\n rw [map_snd, map_snd, ←assoc, ←assoc] at u_snd,\n exact (pullback_cone.is_limit.lift' s_lim (u.fst ≫ fst) (u.snd ≫ fst) u_fst, \n pullback_cone.is_limit.lift' t_lim (u.fst ≫ snd) (u.snd ≫ snd) u_snd)\nend\n\nlemma is_pullback_of_prod_pullback (s_lim : is_limit s) (t_lim : is_limit t) :\n is_limit (pullback_cone.mk (map s.fst t.fst) (map s.snd t.snd) \n (by { rw [map_map, s.condition, t.condition, ←map_map] })) := \nbegin\n apply pullback_cone.is_limit.mk _ \n (λ u, lift (map_lift s_lim t_lim u).1.val (map_lift s_lim t_lim u).2.val); \n simp only; intro u,\n { rw lift_map, \n erw [(map_lift s_lim t_lim u).1.prop.left, (map_lift s_lim t_lim u).2.prop.left],\n rw [←comp_lift, lift_fst_snd, comp_id] },\n { rw lift_map, \n erw [(map_lift s_lim t_lim u).1.prop.right, (map_lift s_lim t_lim u).2.prop.right],\n rw [←comp_lift, lift_fst_snd, comp_id] },\n { intros l' hfst hsnd,\n apply hom_ext, \n { apply pullback_cone.is_limit.hom_ext s_lim, \n rw [lift_fst, assoc, ←map_fst s.fst t.fst, ←assoc, hfst], \n erw [(map_lift s_lim t_lim u).1.prop.left],\n \n rw [lift_fst, assoc, ←map_fst s.snd t.snd, ←assoc, hsnd], \n erw [(map_lift s_lim t_lim u).1.prop.right] },\n { apply pullback_cone.is_limit.hom_ext t_lim, \n rw [lift_snd, assoc, ←map_snd s.fst t.fst, ←assoc, hfst], \n erw [(map_lift s_lim t_lim u).2.prop.left],\n \n rw [lift_snd, assoc, ←map_snd s.snd t.snd, ←assoc, hsnd], \n erw [(map_lift s_lim t_lim u).2.prop.right] } }\nend\n\nlemma is_pullback_square_ids_fst{c d : C} (f : c ⟶ d) : \n is_limit (pullback_cone.mk f (𝟙 c) (by simp) : pullback_cone (𝟙 d) f) :=\nbegin\n apply pullback_cone.is_limit.mk _ (λ s, s.snd); simp only,\n exact (λ s, by { rw [←s.condition, comp_id] }),\n exact (λ s, by rw comp_id s.snd),\n exact (λ s t h1 h2, by { rw [←h2, comp_id] })\nend\n\nlemma is_pullback_square_ids_snd {c d : C} (f : c ⟶ d) : \n is_limit (pullback_cone.mk (𝟙 c) f (by simp) : pullback_cone f (𝟙 d)) :=\nbegin\n apply pullback_cone.is_limit.mk _ (λ s, s.fst); simp only,\n exact (λ s, by rw comp_id s.fst),\n exact (λ s, by { rw [s.condition, comp_id] }),\n exact (λ s t h1 h2, by { rw [←h1, comp_id] })\nend\n\n\ndef lift_pullback_of_equalizer_coreflexive_pair {c d : C} {h k : c ⟶ d} {u : fork k h} \n [is_coreflexive_pair h k] (u_lim : is_limit u) (s : pullback_cone h k) : \n {l // l ≫ u.ι = s.fst ∧ l ≫ u.ι = s.snd} := \nbegin\n have cond := eq_whisker s.condition (common_retraction h k),\n rw [assoc, assoc, right_comp_retraction, left_comp_retraction, comp_id, comp_id] at cond,\n rw ←cond, simp only [and_self],\n refine fork.is_limit.lift' u_lim s.fst _,\n nth_rewrite 0 cond,\n exact s.condition.symm\nend\n\ndef is_pullback_of_equalizer_coreflexive_pair {c d : C} {h k : c ⟶ d} {u : fork k h} \n (u_lim : is_limit u) [is_coreflexive_pair h k] : \n is_limit (pullback_cone.mk u.ι u.ι (by rw u.condition) : pullback_cone h k) :=\nbegin\n apply pullback_cone.is_limit.mk _ \n (λ s, (lift_pullback_of_equalizer_coreflexive_pair u_lim s).val); \n intro s; simp only,\n exact (lift_pullback_of_equalizer_coreflexive_pair u_lim s).prop.left,\n exact (lift_pullback_of_equalizer_coreflexive_pair u_lim s).prop.right,\n intros m hfst hsnd, apply fork.is_limit.hom_ext u_lim,\n erw [hfst, (lift_pullback_of_equalizer_coreflexive_pair u_lim s).prop.left]\nend\n\nlemma is_pullback_id_cone_of_monic {c d : C} (k : c ⟶ d) [mono k] :\n is_limit (pullback_cone.mk (𝟙 c) (𝟙 c) (by rw id_comp) : pullback_cone k k) :=\nbegin\n apply pullback_cone.is_limit.mk _ (λ s, s.fst); intro s; simp only,\n { rw comp_id },\n { rw [comp_id, ←cancel_mono k, s.condition] },\n { intros u hf hs, rw ←hf, rw comp_id }\nend", "meta": {"author": "cchanavat", "repo": "lean-topos", "sha": "c8e22c35ed4dc4ea0d74a59c91785b8a4c8e48a4", "save_path": "github-repos/lean/cchanavat-lean-topos", "path": "github-repos/lean/cchanavat-lean-topos/lean-topos-c8e22c35ed4dc4ea0d74a59c91785b8a4c8e48a4/pullbacks.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44939264921326705, "lm_q2_score": 0.05108273424839635, "lm_q1q2_score": 0.022956205272944123}} {"text": "inductive Con : Type\n| nil : Con\n| foo : Con\n\ninductive Conw : Con → Prop\n| nilw : Conw Con.nil\n\nexample (x : Conw Con.nil) : x = Conw.nilw := by\n cases x\n traceState\n rfl\n", "meta": {"author": "gebner", "repo": "lean4-old", "sha": "ee51cdfaf63ee313c914d83264f91f414a0e3b6e", "save_path": "github-repos/lean/gebner-lean4-old", "path": "github-repos/lean/gebner-lean4-old/lean4-old-ee51cdfaf63ee313c914d83264f91f414a0e3b6e/tests/lean/421.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4416730056646256, "lm_q2_score": 0.05184546628352781, "lm_q1q2_score": 0.022898742923529735}} {"text": "\nimport data.serial\n\nopen serial serializer\n\nstructure point :=\n(x y z : ℕ)\n\ninstance : serial point :=\nby mk_serializer (point.mk <$> ser_field point.x <*> ser_field point.y <*> ser_field point.z)\n\nexample : serial point :=\nbegin\n apply of_serializer (point.mk <$> ser_field point.x <*> ser_field point.y <*> ser_field point.z),\n intro w, cases w,\n apply there_and_back_again_seq,\n apply there_and_back_again_seq,\n apply there_and_back_again_map,\n { simp },\n { refl },\n { simp },\n { refl },\n { simp },\nend\n\n@[derive serial]\ninductive my_sum\n| first : my_sum\n| second : ℕ → my_sum\n| third (n : ℕ) (xs : list ℕ) : n ≤ xs.length → my_sum\n\n@[derive serial]\nstructure my_struct :=\n(x : ℕ)\n(xs : list ℕ)\n(bounded : xs.length ≤ x)\n\n@[derive [serial, decidable_eq]]\ninductive tree' (α : Type)\n| leaf {} : tree'\n| node2 : α → tree' → tree' → tree'\n| node3 : α → tree' → tree' → tree' → tree'\n\nopen tree'\n\nmeta def tree'.repr {α} [has_repr α] : tree' α → string\n| leaf := \"leaf\"\n| (node2 x t₀ t₁) := to_string $ format!\"(node2 {repr x} {tree'.repr t₀} {tree'.repr t₁})\"\n| (node3 x t₀ t₁ t₂) := to_string $ format!\"(node3 {repr x} {tree'.repr t₀} {tree'.repr t₁} {tree'.repr t₂})\"\n\nmeta instance {α} [has_repr α] : has_repr (tree' α) := ⟨ tree'.repr ⟩\n\ndef x := node2 2 (node3 77777777777777 leaf leaf (node2 1 leaf leaf)) leaf\n\n#eval serialize x\n-- [17, 1, 5, 2, 430029026, 72437, 0, 0, 1, 3, 0, 0, 0]\n#eval deserialize (tree' ℕ) [17, 1, 5, 2, 430029026, 72437, 0, 0, 1, 3, 0, 0, 0]\n-- (some (node2 2 (node3 77777777777777 leaf leaf (node2 1 leaf leaf)) leaf))\n#eval (deserialize _ (serialize x) = some x : bool)\n-- tt\n\nopen medium\n\nexample (x : tree' ℕ) : deserialize _ (serialize x) = some x :=\nby { dsimp [serialize,deserialize],\n rw [eval_eval,serial.correctness],\n refl }\n", "meta": {"author": "leanprover-community", "repo": "mathlib-nursery", "sha": "0479b31fa5b4d39f41e89b8584c9f5bf5271e8ec", "save_path": "github-repos/lean/leanprover-community-mathlib-nursery", "path": "github-repos/lean/leanprover-community-mathlib-nursery/mathlib-nursery-0479b31fa5b4d39f41e89b8584c9f5bf5271e8ec/test/data/serial.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828341018881344, "lm_q2_score": 0.04672496294029601, "lm_q1q2_score": 0.022815024245433663}} {"text": "inductive Con : Type\n| nil : Con\n| foo : Con\n\ninductive Conw : Con → Prop\n| nilw : Conw Con.nil\n\nexample (x : Conw Con.nil) : x = Conw.nilw := by\n cases x\n trace_state\n rfl\n", "meta": {"author": "leanprover", "repo": "lean4", "sha": "742d053a97bdd109a41a921facd1cd6a55e89bc7", "save_path": "github-repos/lean/leanprover-lean4", "path": "github-repos/lean/leanprover-lean4/lean4-742d053a97bdd109a41a921facd1cd6a55e89bc7/tests/lean/421.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44552953503957266, "lm_q2_score": 0.051082740568594215, "lm_q1q2_score": 0.022758869654072898}} {"text": "import for_mathlib.Profinite.extend\nimport for_mathlib.Profinite.product\n\nimport data.fintype.card\nimport category_theory.limits.functor_category\nimport category_theory.limits.shapes.binary_products\nimport category_theory.functor.currying\n\nimport facts\nimport hacks_and_tricks.type_pow\n\nimport Lbar.basic\nimport pseudo_normed_group.profinitely_filtered\n\n/-!\n# $\\overline{\\mathcal{M}}_{r'}(S)_{≤ c}$\n\nIn this file we put a profinite topology on the subspace\n`Lbar_le r' S c` of `Lbar r' S` consisting of power series\n`F_s = ∑ a_{n,s}T^n ∈ Tℤ⟦T⟧` such that `∑_{n,s} |a_{n,s}|r'^n ≤ c`.\n-/\n\nuniverse u\n\nnoncomputable theory\nopen_locale big_operators nnreal\nopen pseudo_normed_group category_theory category_theory.limits\nlocal attribute [instance] type_pow\n\nvariables {r' : ℝ≥0} {S : Type u} [fintype S] {c c₁ c₂ c₃ : ℝ≥0}\n\n/-- `Lbar_le r' S c` is the set of power series\n`F_s = ∑ a_{n,s}T^n ∈ Tℤ[[T]]` such that `∑_{n,s} |a_{n,s}|r'^n ≤ c` -/\ndef Lbar_le (r' : ℝ≥0) (S : Type u) [fintype S] (c : ℝ≥0) :=\n{ F : Lbar r' S // F ∈ filtration (Lbar r' S) c }\n\nnamespace Lbar_le\n\ninstance has_coe : has_coe (Lbar_le r' S c) (Lbar r' S) := ⟨subtype.val⟩\n\ninstance has_coe_to_fun : has_coe_to_fun (Lbar_le r' S c) (λ F, S → ℕ → ℤ) := ⟨λ F, F.1⟩\n\n@[simp] lemma coe_coe_to_fun (F : Lbar_le r' S c) : ⇑(F : Lbar r' S) = F := rfl\n\n@[simp] lemma coe_mk (x h) : ((⟨x, h⟩ : Lbar_le r' S c) : S → ℕ → ℤ) = x := rfl\n\n@[simp] protected lemma coeff_zero (x : Lbar_le r' S c) (s : S) : x s 0 = 0 := x.1.coeff_zero' s\n\nprotected lemma summable (x : Lbar_le r' S c) (s : S) :\n summable (λ n, (↑(x s n).nat_abs * r'^n)) := x.1.summable' s\n\nprotected lemma mem_filtration (x : Lbar_le r' S c) :\n x.1 ∈ filtration (Lbar r' S) c := x.property\n\n/-- The inclusion map `Lbar_le r' S c₁ → Lbar_le r' S c₂` for `c₁ ≤ c₂`. -/\nprotected def cast_le [hc : fact (c₁ ≤ c₂)] (x : Lbar_le r' S c₁) : Lbar_le r' S c₂ :=\n⟨⟨x, x.coeff_zero, x.summable⟩, filtration_mono hc.out x.mem_filtration⟩\n\n@[simp] lemma coe_cast_le [hc : fact (c₁ ≤ c₂)] (x : Lbar_le r' S c₁) :\n ((x.cast_le : Lbar_le r' S c₂) : Lbar r' S) = x :=\nby { ext, refl }\n\n@[simp] lemma cast_le_apply [hc : fact (c₁ ≤ c₂)] (x : Lbar_le r' S c₁) (s : S) (i : ℕ) :\n (x.cast_le : Lbar_le r' S c₂) s i = x s i :=\nrfl\n\nlemma injective_cast_le [fact (c₁ ≤ c₂)] :\n function.injective (Lbar_le.cast_le : Lbar_le r' S c₁ → Lbar_le r' S c₂) :=\nλ x y h,\nbegin\n ext s n,\n change x.cast_le s n = y.cast_le s n,\n rw h,\nend\n\n@[ext] lemma ext (x y : Lbar_le r' S c) (h : (⇑x: S → ℕ → ℤ) = y) : x = y :=\nby { ext:2, exact h }\n\ninstance : has_zero (Lbar_le r' S c) := ⟨⟨0, zero_mem_filtration _⟩⟩\n\ninstance : inhabited (Lbar_le r' S c) := ⟨0⟩\n\nend Lbar_le\n\nvariables (c₃)\n\n/-- The addition on `Lbar_le`.\nThis addition is not homogeneous, but has type\n`(Lbar_le r' S c₁) → (Lbar_le r' S c₂) → (Lbar_le r' S c₃)`\nfor `c₁ + c₂ ≤ c₃`. -/\ndef Lbar_le.add [h : fact (c₁ + c₂ ≤ c₃)]\n (F : Lbar_le r' S c₁) (G : Lbar_le r' S c₂) :\n Lbar_le r' S c₃ :=\nsubtype.mk (F + G) $ filtration_mono h.out $ add_mem_filtration F.mem_filtration G.mem_filtration\n\n/-- An uncurried version of addition on `Lbar_le`,\nmeaning that it takes only 1 input, coming from a product type. -/\ndef Lbar_le.add' [fact (c₁ + c₂ ≤ c₃)] :\n Lbar_le r' S c₁ × Lbar_le r' S c₂ → Lbar_le r' S c₃ :=\nλ x, Lbar_le.add c₃ x.1 x.2\n\n-- TODO: register this as an instance??\n/-- The negation on `Lbar_le`. -/\ndef Lbar_le.neg (F : Lbar_le r' S c) : Lbar_le r' S c :=\nsubtype.mk (-F) $ neg_mem_filtration F.mem_filtration\n\nnamespace Lbar_le\n\n/-- The truncation map from Lbar_le to `Lbar_bdd`. -/\n@[simps] def truncate (M : ℕ) (F : Lbar_le r' S c) : Lbar_bdd r' ⟨S⟩ c M :=\n{ to_fun := λ s n, F s n,\n coeff_zero' := by simp,\n sum_le' :=\n begin\n refine le_trans _ F.mem_filtration,\n apply finset.sum_le_sum,\n rintros (s : S) -,\n rw fin.sum_univ_eq_sum_range (λ i, (↑(F s i).nat_abs * r' ^i)) (M+1),\n exact sum_le_tsum _ (λ _ _, subtype.property (_ : ℝ≥0)) (F.summable s),\n end }\n\nlemma truncate_surjective (M : ℕ) :\n function.surjective (truncate M : Lbar_le r' S c → Lbar_bdd r' ⟨S⟩ c M) :=\nbegin\n intro x,\n have aux : _ := _,\n let F : Lbar_le r' S c :=\n ⟨{ to_fun := λ s n, if h : n < M + 1 then x s ⟨n, h⟩ else 0,\n summable' := aux, .. }, _⟩,\n { use F, ext s i, simp only [truncate_to_fun], dsimp,\n rw dif_pos i.is_lt, simp only [fin.eta] },\n { intro s, rw dif_pos (nat.zero_lt_succ _), exact x.coeff_zero s },\n { apply le_trans _ x.sum_le,\n apply finset.sum_le_sum,\n rintro s -,\n rw [← sum_add_tsum_nat_add' (M + 1), tsum_eq_zero, add_zero],\n { rw ← fin.sum_univ_eq_sum_range,\n apply finset.sum_le_sum,\n rintro i -,\n simp only [dif_pos i.is_lt, fin.eta, Lbar.coe_mk] },\n { intro i,\n dsimp,\n rw [dif_neg, int.nat_abs_zero, nat.cast_zero, zero_mul],\n linarith },\n { dsimp, apply aux } },\n { intro s,\n apply @summable_of_ne_finset_zero _ _ _ _ _ (finset.range (M+1)),\n intros i hi,\n rw finset.mem_range at hi,\n simp only [hi, zero_mul, dif_neg, not_false_iff, nat.cast_zero, int.nat_abs_zero] }\nend\n\n/-- Injectivity of the map `Lbar_le` to the limit of the `Lbar_bdd`. -/\nlemma eq_iff_truncate_eq (x y : Lbar_le r' S c)\n (cond : ∀ M, truncate M x = truncate M y) : x = y :=\nbegin\n ext s n,\n change (truncate n x).1 s ⟨n, by linarith⟩ = (truncate n y).1 s ⟨n,_⟩,\n rw cond,\nend\n\nlemma truncate_cast_le (M : ℕ) [hc : fact (c₁ ≤ c₂)] (x : Lbar_le r' S c₁) :\n truncate M (Lbar_le.cast_le x : Lbar_le r' S c₂) = Lbar_bdd.cast_le (truncate M x) :=\nrfl\n\n/-- Underlying function of the element of `Lbar_le r' S c` associated to a sequence of\n elements of the truncated Lbars. -/\ndef mk_seq (T : Π (M : ℕ), Lbar_bdd r' ⟨S⟩ c M) : S → ℕ → ℤ :=\nλ s n, (T n).1 s ⟨n, lt_add_one n⟩\n\n@[simp] lemma mk_seq_zero {T : Π (M : ℕ), Lbar_bdd r' ⟨S⟩ c M} (s : S) : mk_seq T s 0 = 0 :=\n(T 0).coeff_zero s\n\nlemma mk_seq_eq_of_compat {T : Π (M : ℕ), Lbar_bdd r' ⟨S⟩ c M}\n (compat : ∀ (M N : ℕ) (h : M ≤ N), Lbar_bdd.transition r' h (T N) = T M)\n {s : S} {n : ℕ} {M : ℕ} (hnM : n < M + 1) :\n mk_seq T s n = (T M).1 s ⟨n, hnM⟩ :=\nbegin\n have hnM : n ≤ M := nat.lt_succ_iff.mp hnM,\n unfold mk_seq,\n rw ← compat n M hnM,\n apply Lbar_bdd.transition_eq,\nend\n\nlemma mk_seq_sum_range_eq (T : Π (M : ℕ), Lbar_bdd r' ⟨S⟩ c M)\n (compat : ∀ (M N : ℕ) (h : M ≤ N), Lbar_bdd.transition r' h (T N) = T M) (s : S) (n) :\n ∑ i in finset.range (n+1), (↑(mk_seq T s i).nat_abs * r'^i) =\n ∑ i : fin (n+1), (↑((T n).1 s i).nat_abs * r'^(i:ℕ)) :=\nbegin\n rw ← fin.sum_univ_eq_sum_range,\n congr',\n ext ⟨i, hi⟩,\n congr',\n exact mk_seq_eq_of_compat compat _,\nend\n\nlemma mk_seq_summable {T : Π (M : ℕ), Lbar_bdd r' ⟨S⟩ c M}\n (compat : ∀ (M N : ℕ) (h : M ≤ N), Lbar_bdd.transition r' h (T N) = T M) (s : S) :\n summable (λ (n : ℕ), (↑(mk_seq T s n).nat_abs * r' ^ n)) :=\nbegin\n apply @nnreal.summable_of_sum_range_le _ c,\n rintro (_|n),\n { simp only [finset.sum_empty, finset.range_zero, zero_le'] },\n { rw mk_seq_sum_range_eq T compat s n,\n refine le_trans _ (T n).sum_le,\n refine finset.single_le_sum (λ _ _, _) (finset.mem_univ s),\n apply zero_le' },\nend\n\nopen filter\n\nlemma mk_seq_tendsto {T : Π (M : ℕ), Lbar_bdd r' ⟨S⟩ c M}\n (compat : ∀ (M N : ℕ) (h : M ≤ N), Lbar_bdd.transition r' h (T N) = T M) :\n tendsto (λ (n : ℕ), ∑ (s : S), ∑ i in finset.range n, (↑(mk_seq T s i).nat_abs * r'^i))\n at_top (nhds $ ∑ (s : S), ∑' n, (↑(mk_seq T s n).nat_abs * r'^n)) :=\ntendsto_finset_sum _ $ λ s _, has_sum.tendsto_sum_nat $ summable.has_sum $ mk_seq_summable compat s\n\nlemma mk_seq_sum_le {T : Π (M : ℕ), Lbar_bdd r' ⟨S⟩ c M}\n (compat : ∀ (M N : ℕ) (h : M ≤ N), Lbar_bdd.transition r' h (T N) = T M) :\n (∑ s, ∑' (n : ℕ), (↑(mk_seq T s n).nat_abs * r' ^ n)) ≤ c :=\nbegin\n refine le_of_tendsto (mk_seq_tendsto compat) (eventually_of_forall _),\n rintro (_|n),\n { simp only [finset.sum_empty, finset.range_zero, finset.sum_const_zero, zero_le'] },\n { convert (T n).sum_le,\n funext,\n rw mk_seq_sum_range_eq T compat s n,\n refl }\nend\n\nlemma truncate_mk_seq {T : Π (M : ℕ), Lbar_bdd r' ⟨S⟩ c M}\n (compat : ∀ (M N : ℕ) (h : M ≤ N), Lbar_bdd.transition r' h (T N) = T M) (M : ℕ) :\n truncate M ⟨⟨mk_seq T, mk_seq_zero, mk_seq_summable compat⟩, mk_seq_sum_le compat⟩ = T M :=\nbegin\n ext s ⟨i, hi⟩,\n exact mk_seq_eq_of_compat compat _,\nend\n\n/-- `of_compat hT` is the limit of a compatible family `T M : Lbar_bdd r' ⟨S⟩ c M`.\nThis realizes `Lbar_le` as the profinite limit of the spaces `Lbar_bdd`,\nsee also `Lbar_le.eqv`. -/\ndef of_compat {T : Π (M : ℕ), Lbar_bdd r' ⟨S⟩ c M}\n (compat : ∀ (M N : ℕ) (h : M ≤ N), Lbar_bdd.transition r' h (T N) = T M) : Lbar_le r' S c :=\n⟨⟨mk_seq T, mk_seq_zero, mk_seq_summable compat⟩, mk_seq_sum_le compat⟩\n\n@[simp] lemma truncate_of_compat {T : Π (M : ℕ), Lbar_bdd r' ⟨S⟩ c M}\n (compat : ∀ (M N : ℕ) (h : M ≤ N), Lbar_bdd.transition r' h (T N) = T M) (M : ℕ) :\n truncate M (of_compat compat) = T M :=\nbegin\n ext s ⟨i, hi⟩,\n exact mk_seq_eq_of_compat compat _,\nend\n\n/-- The equivalence (as types) between `Lbar_le r' S c`\nand the profinite limit of the spaces `Lbar_bdd r' ⟨S⟩ c M`. -/\ndef eqv : Lbar_le r' S c ≃ Lbar_bdd.limit r' ⟨S⟩ c :=\n{ to_fun := λ F, ⟨λ N, truncate _ F, by { intros, refl }⟩,\n inv_fun := λ F, of_compat F.2,\n left_inv := λ x, by { ext, refl },\n right_inv := by { rintro ⟨x, hx⟩, simp only [truncate_of_compat], } }\n\nsection topological_structure\n\ninstance : topological_space (Lbar_le r' S c) := topological_space.induced eqv (by apply_instance)\n\nlemma is_open_iff {U : set (Lbar_bdd.limit r' ⟨S⟩ c)} : is_open (eqv ⁻¹' U) ↔ is_open U :=\nbegin\n rw is_open_induced_iff,\n have := function.surjective.preimage_injective (equiv.surjective (eqv : Lbar_le r' S c ≃ _)),\n simp only [iff_self, this.eq_iff],\n simp only [exists_eq_right],\nend\n\n/-- The homeomorphism between `Lbar_le r' S c`\nand the profinite limit of the spaces `Lbar_bdd r' ⟨S⟩ c M`.\n\nThis is `Lbar_le.eqv`, lifted to a homeomorphism by transporting\nthe topology from the profinite limit to `Lbar_le`. -/\ndef homeo : Lbar_le r' S c ≃ₜ Lbar_bdd.limit r' ⟨S⟩ c :=\n{ continuous_to_fun := begin\n simp only [equiv.to_fun_as_coe, continuous_def],\n intros U hU,\n rwa is_open_iff\n end,\n continuous_inv_fun := begin\n simp only [equiv.to_fun_as_coe, continuous_def],\n intros U hU,\n erw [← eqv.image_eq_preimage, ← is_open_iff],\n rwa eqv.preimage_image U,\n end,\n ..eqv }\n\nlemma truncate_eq (M : ℕ) :\n (truncate M : Lbar_le r' S c → Lbar_bdd r' ⟨S⟩ c M) = (Lbar_bdd.proj M) ∘ homeo := rfl\n\ninstance : t2_space (Lbar_le r' S c) :=\n⟨λ x y h, separated_by_continuous homeo.continuous (λ c, h $ homeo.injective c)⟩\n\ninstance [fact (0 < r')] : compact_space (Lbar_le r' S c) :=\nbegin\n constructor,\n rw homeo.embedding.is_compact_iff_is_compact_image,\n simp only [set.image_univ, homeomorph.range_coe],\n obtain ⟨h⟩ := (by apply_instance : compact_space (Lbar_bdd.limit r' ⟨S⟩ c)),\n exact h,\nend\n\ninstance : totally_disconnected_space (Lbar_le r' S c) :=\n{ is_totally_disconnected_univ :=\n begin\n rintros A - hA,\n suffices subsing : (homeo '' A).subsingleton,\n { intros x hx y hy, apply_rules [homeo.injective, subsing, set.mem_image_of_mem] },\n obtain ⟨h⟩ := (by apply_instance : totally_disconnected_space (Lbar_bdd.limit r' ⟨S⟩ c)),\n exact h _ (by tauto) (is_preconnected.image hA _ homeo.continuous.continuous_on)\n end }\n\nlemma continuous_iff {α : Type*} [topological_space α] (f : α → Lbar_le r' S c) :\n continuous f ↔ (∀ M, continuous ((truncate M) ∘ f)) :=\nbegin\n split,\n { intros hf M,\n rw [truncate_eq, function.comp.assoc],\n revert M,\n rw ← Lbar_bdd.continuous_iff,\n refine continuous.comp homeo.continuous hf },\n { intro h,\n suffices : continuous (homeo ∘ f), by rwa homeo.comp_continuous_iff at this,\n rw Lbar_bdd.continuous_iff,\n exact h }\nend\n\nlemma continuous_truncate {M} : continuous (@truncate r' S _ c M) :=\n(continuous_iff id).mp continuous_id _\n\nlemma continuous_add' :\n continuous (Lbar_le.add' (c₁ + c₂) : Lbar_le r' S c₁ × Lbar_le r' S c₂ → Lbar_le r' S (c₁+c₂)) :=\nbegin\n rw continuous_iff,\n intros M,\n have : truncate M ∘ (λ x : Lbar_le r' S c₁ × Lbar_le r' S c₂, Lbar_le.add _ x.1 x.2) =\n (λ x : (Lbar_le r' S c₁ × Lbar_le r' S c₂), Lbar_bdd.add (truncate M x.1) (truncate M x.2)) :=\n by {ext; refl},\n erw this,\n suffices : continuous (λ x : Lbar_bdd r' ⟨S⟩ c₁ M × Lbar_bdd r' ⟨S⟩ c₂ M, Lbar_bdd.add x.1 x.2),\n { have claim : (λ x : (Lbar_le r' S c₁ × Lbar_le r' S c₂),\n Lbar_bdd.add (truncate M x.1) (truncate M x.2)) =\n (λ x : Lbar_bdd r' ⟨S⟩ c₁ M × Lbar_bdd r' ⟨S⟩ c₂ M, Lbar_bdd.add x.1 x.2) ∘\n (λ x : Lbar_le r' S c₁ × Lbar_le r' S c₂, (truncate M x.1, truncate M x.2)), by {ext, refl},\n rw claim,\n refine continuous.comp this _,\n refine continuous.prod_map continuous_truncate continuous_truncate },\n exact continuous_of_discrete_topology,\nend\n\nlemma continuous_neg : continuous (Lbar_le.neg : Lbar_le r' S c → Lbar_le r' S c) :=\nbegin\n rw continuous_iff,\n intro M,\n change continuous (λ x : Lbar_le r' S c, Lbar_bdd.neg (truncate M x)),\n exact continuous.comp continuous_of_discrete_topology continuous_truncate,\nend\n\nend topological_structure\n\nlemma continuous_cast_le (r' : ℝ≥0) (S : Type u) [fintype S] (c₁ c₂ : ℝ≥0) [hc : fact (c₁ ≤ c₂)] :\n continuous (@Lbar_le.cast_le r' S _ c₁ c₂ _) :=\nbegin\n rw continuous_iff,\n intro M,\n simp only [function.comp, truncate_cast_le],\n exact continuous_bot.comp continuous_truncate\nend\n\n/-! We now prove some scaffolding lemmas\nin order to prove that the action of `T⁻¹` is continuous. -/\n\nlemma continuous_of_normed_group_hom\n (f : (Lbar r' S) →+ (Lbar r' S))\n (g : Lbar_le r' S c₁ → Lbar_le r' S c₂)\n (h : ∀ x, ↑(g x) = f x)\n (H : ∀ M, ∃ N, ∀ (F : Lbar r' S),\n (∀ s i, i < N + 1 → F s i = 0) → (∀ s i, i < M + 1 → f F s i = 0)) :\n continuous g :=\nbegin\n rw continuous_iff,\n intros M,\n rcases H M with ⟨N, hN⟩,\n let φ : Lbar_bdd r' ⟨S⟩ c₁ N → Lbar_le r' S c₁ :=\n classical.some (truncate_surjective N).has_right_inverse,\n have hφ : function.right_inverse φ (truncate N) :=\n classical.some_spec (truncate_surjective N).has_right_inverse,\n suffices : truncate M ∘ g = truncate M ∘ g ∘ φ ∘ truncate N,\n { rw [this, ← function.comp.assoc, ← function.comp.assoc],\n apply continuous_bot.comp continuous_truncate },\n ext1 x,\n suffices : ∀ s i, i < M + 1 → (g x) s i = (g (φ (truncate N x))) s i,\n { ext s i, dsimp [function.comp], apply this, exact i.property },\n intros s i hi,\n rw [← coe_coe_to_fun, h, ← coe_coe_to_fun, h, ← sub_eq_zero],\n show ((f x) - f (φ (truncate N x))) s i = 0,\n rw [← f.map_sub],\n apply hN _ _ _ _ hi,\n clear hi i s, intros s i hi,\n simp only [Lbar.coe_sub, pi.sub_apply, sub_eq_zero],\n suffices : ∀ s i, (truncate N x) s i = truncate N (φ (truncate N x)) s i,\n { exact this s ⟨i, hi⟩ },\n intros s i, congr' 1,\n rw hφ (truncate N x)\nend\n\n/-- Construct a map between `Lbar_le r' S c₁` and `Lbar_le r' S c₂`\nfrom a bounded group homomorphism `Lbar r' S → Lbar r' S`.\n\nIf `f` satisfies a suitable criterion,\nthen the constructed map is continuous for the profinite topology;\nsee `continuous_of_normed_group_hom`. -/\ndef hom_of_normed_group_hom {C : ℝ≥0} (c₁ c₂ : ℝ≥0) [hc : fact (C * c₁ ≤ c₂)]\n (f : Lbar r' S →+ Lbar r' S) (h : f ∈ filtration (Lbar r' S →+ Lbar r' S) C)\n (F : Lbar_le r' S c₁) :\n Lbar_le r' S c₂ :=\n⟨{ to_fun := λ s i, f F s i,\n coeff_zero' := Lbar.coeff_zero _,\n summable' := Lbar.summable _ },\n filtration_mono hc.out (h F.mem_filtration)⟩\n\nlemma continuous_hom_of_normed_group_hom {C : ℝ≥0} (c₁ c₂ : ℝ≥0)\n [hc : fact (C * c₁ ≤ c₂)]\n (f : Lbar r' S →+ Lbar r' S) (h : f ∈ filtration (Lbar r' S →+ Lbar r' S) C)\n (H : ∀ M, ∃ N, ∀ (F : Lbar r' S),\n (∀ s i, i < N + 1 → F s i = 0) → (∀ s i, i < M + 1 → f F s i = 0)) :\n continuous (hom_of_normed_group_hom c₁ c₂ f h) :=\ncontinuous_of_normed_group_hom f _ (λ F, by { ext, refl }) H\n\n@[simp] lemma coe_hom_of_normed_group_hom_apply {C : ℝ≥0} (c₁ c₂ : ℝ≥0)\n [hc : fact (C * c₁ ≤ c₂)]\n (f : Lbar r' S →+ Lbar r' S) (h : f ∈ filtration (Lbar r' S →+ Lbar r' S) C)\n (F : (Lbar_le r' S c₁)) (s : S) (i : ℕ) :\n (hom_of_normed_group_hom c₁ c₂ f h) F s i = f F s i := rfl\n\nsection Tinv\n\n/-!\n### The action of T⁻¹\n-/\n\n/-- The action of `T⁻¹` as map `Lbar_le r S c₁ → Lbar_le r S c₂`.\n\nThis action is induced by the action of `T⁻¹` on power series modulo constants: `ℤ⟦T⟧/ℤ`.\nSo `T⁻¹` sends `T^(n+1)` to `T^n`, but `T^0 = 0`. -/\ndef Tinv {r : ℝ≥0} {S : Type u} [fintype S] {c₁ c₂ : ℝ≥0} [fact (0 < r)] [fact (r⁻¹ * c₁ ≤ c₂)] :\n Lbar_le r S c₁ → Lbar_le r S c₂ :=\nhom_of_normed_group_hom c₁ c₂ Lbar.Tinv Lbar.Tinv_mem_filtration\n\n@[simp] lemma Tinv_apply {r : ℝ≥0} {S : Type u} [fintype S] {c₁ c₂ : ℝ≥0}\n [fact (0 < r)] [fact (r⁻¹ * c₁ ≤ c₂)] (F : Lbar_le r S c₁) (s : S) (i : ℕ) :\n (Tinv F : Lbar_le r S c₂) s i = Lbar.Tinv (F : Lbar r S) s i :=\nrfl\n\nlemma continuous_Tinv (r : ℝ≥0) (S : Type u) [fintype S] (c₁ c₂ : ℝ≥0)\n [fact (0 < r)] [fact (r⁻¹ * c₁ ≤ c₂)] :\n continuous (@Tinv r S _ c₁ c₂ _ _) :=\ncontinuous_hom_of_normed_group_hom c₁ c₂ _ Lbar.Tinv_mem_filtration $\nbegin\n intros M,\n use M+1,\n rintro F hF s (_|i) hi,\n { simp only [Lbar.Tinv, add_monoid_hom.mk'_apply, Lbar.coe_mk, Lbar.Tinv_aux_zero] },\n { simp only [Lbar.Tinv, Lbar.Tinv_aux_succ, add_monoid_hom.mk'_apply, Lbar.coe_mk],\n apply hF,\n exact nat.succ_lt_succ hi },\nend\n\nend Tinv\n\n/-\n\nsection map\n\n/-- TODO -/\ndef map {S T : Fintype} (f : S ⟶ T) : Lbar_le r' S c → Lbar_le r' T c := λ F,\n⟨(F : Lbar r' S).map f, Lbar.nnnorm_map_le_of_nnnorm_le _ _ F.2⟩\n\nlemma map_truncate {S T : Fintype} (f : S ⟶ T) (F : Lbar_le r' S c) (M : ℕ) :\n ((F.truncate M).map f) = (F.map f).truncate M := rfl\n\nlemma map_continuous {S T : Fintype} (f : S ⟶ T) : continuous\n (map f : Lbar_le r' S c → Lbar_le r' T c) :=\nbegin\n rw continuous_iff,\n intros M,\n have : truncate M ∘ (map f : Lbar_le r' S c → Lbar_le r' T c) =\n Lbar_bdd.map f ∘ truncate M, { ext, refl },\n rw this,\n refine continuous.comp _ continuous_truncate,\n continuity,\nend\n\nend map\n\nvariables (r' c)\n\n/-- A version of `Lbar_le` which is functorial in `S`. -/\n@[simps]\ndef Fintype_functor [fact (0 < r')] : Fintype.{u} ⥤ Profinite.{u} :=\n{ obj := λ S, Profinite.of $ Lbar_le r' S c,\n map := λ S T f,\n { to_fun := map f,\n continuous_to_fun := map_continuous _ },\n map_id' := λ S, begin\n ext1,\n exact subtype.ext x.1.map_id,\n end,\n map_comp' := λ S T U f g, begin\n ext1,\n exact subtype.ext (x.1.map_comp f g),\n end }\n\nvariables (c₁ c₂)\n/-- The functor sending `S` to the (categorical) product\n of `Lbar_le r' S c₁` and `Lbar_le r' S c₂`. -/\n@[simps]\ndef Fintype_functor_prod [fact (0 < r')] : Fintype.{u} ⥤ Profinite.{u} :=\n{ obj := λ S, (S,S),\n map := λ _ _ f, (f,f) } ⋙\n (Fintype_functor r' c₁).prod (Fintype_functor r' c₂) ⋙\n (uncurry.obj prod.functor)\n\n/-- This is a functorial version of `add'`. -/\n@[simps]\ndef Fintype_add_functor [fact (0 < r')] :\n Fintype_functor_prod.{u} r' c₁ c₂ ⟶ Fintype_functor.{u} r' (c₁ + c₂) :=\n{ app := λ S, (Profinite.prod_iso _ _).hom ≫ ⟨add' _, continuous_add'⟩,\n naturality' := begin\n intros S T f,\n ext,\n dsimp only [functor.prod, Profinite.prod_iso, Fintype_functor_prod,\n uncurry, prod.functor, functor.comp_map],\n rw [category_theory.limits.prod.map_map, category.comp_id, category.id_comp],\n dsimp [map, Lbar.map, add', add, is_limit.cone_point_unique_up_to_iso,\n is_limit.unique_up_to_iso],\n rw finset.sum_add_distrib,\n -- annoying\n have useful : ∀ {A B C : Profinite} (f : A ⟶ B) (g : B ⟶ C) (a : A),\n (f ≫ g) a = g (f a) := λ _ _ _ _ _ _, rfl,\n congr,\n { have : binary_fan.fst (limit.cone (pair (Profinite.of (Lbar_le r' ↥T c₁))\n (Profinite.of (Lbar_le r' ↥T c₂)))) = category_theory.limits.prod.fst := rfl,\n rw [this, ← useful, category_theory.limits.prod.map_fst],\n refl },\n { have : binary_fan.snd (limit.cone (pair (Profinite.of (Lbar_le r' ↥T c₁))\n (Profinite.of (Lbar_le r' ↥T c₂)))) = category_theory.limits.prod.snd := rfl,\n rw [this, ← useful, category_theory.limits.prod.map_snd],\n refl },\n end}\n\n/-- Negation on `Lbar_le` as a functor in `S`. -/\ndef Fintype_neg_functor [fact (0 < r')] : Fintype_functor.{u} r' c ⟶ Fintype_functor.{u} r' c :=\n{ app := λ S, ⟨Lbar_le.neg, Lbar_le.continuous_neg⟩,\n naturality' := begin\n intros A B f,\n ext,\n dsimp [map, neg],\n simp,\n end }\n\nvariables {c₁ c₂}\n\nopen category_theory\n\n/-- A bifunctor version of `Fintype_functor`, where `c` can vary. -/\n@[simps]\ndef Fintype_bifunctor [fact (0 < r')] : ℝ≥0 ⥤ Fintype.{u} ⥤ Profinite.{u} :=\n{ obj := λ c, Fintype_functor r' c,\n map := λ c₁ c₂ f,\n { app := λ S,\n { to_fun := @Lbar_le.cast_le r' S _ c₁ c₂ ⟨le_of_hom f⟩,\n continuous_to_fun := by apply continuous_cast_le } },\n map_id' := λ c, by { ext, refl },\n map_comp' := λ a b c f g, by { ext, refl } }\n\n/-- The extension of `Fintype_functor` to `Profinite` obtained by taking limits. -/\n@[simps]\ndef functor [fact (0 < r')] : Profinite.{u} ⥤ Profinite.{u} :=\nProfinite.extend (Fintype_functor r' c)\n\nvariables (c₁ c₂)\n\n/-- The profinite variant of `Fintype_functor_prod`. -/\n@[simps]\ndef functor_prod [fact (0 < r')] : Profinite.{u} ⥤ Profinite.{u} :=\n{ obj := λ S, (S,S), map := λ _ _ f, (f, f) } ⋙\n (functor r' c₁).prod (functor r' c₂) ⋙\n (uncurry.obj prod.functor)\n\n/-- A cone over `(S.fintype_diagram ⋙ Fintype_functor_prod r' c₁ c₂)` used in the definition\n of `add_functor`. -/\ndef functor_prod_cone [fact (0 < r')] (S : Profinite) :\n cone (S.fintype_diagram ⋙ Fintype_functor_prod.{u} r' c₁ c₂) :=\n{ X := (functor_prod r' c₁ c₂).obj S,\n π :=\n { app := λ I, category_theory.limits.prod.map (limit.π _ I) (limit.π _ I),\n naturality' := begin\n intros I J f,\n dsimp [Fintype_functor_prod],\n simp [← limit.w _ f],\n end } }\n\n-- TODO: this proof is SLOW.\n/-- The profinite variant of `Fintype_add_functor`. -/\ndef add_functor [fact (0 < r')] : functor_prod.{u} r' c₁ c₂ ⟶ functor.{u} r' (c₁ + c₂) :=\n-- Why doesn't this work without the \"by apply ...\"?\n{ app := λ S, by apply limit.lift _ (functor_prod_cone r' c₁ c₂ S) ≫\n category_theory.limits.lim.map (whisker_left _ (Fintype_add_functor _ _ _)),\n naturality' := begin\n intros S T f,\n erw [limits.limit.lift_map, limits.limit.lift_map],\n dsimp only [whisker_left, limits.cones.postcompose],\n apply limit.hom_ext,\n intros I,\n dsimp only [nat_trans.comp_app, functor, Profinite.extend, Profinite.change_cone],\n simp_rw [category.assoc, limits.limit.lift_π],\n change _ = _ ≫ limit.π _ _ ≫ _,\n simp_rw [← category.assoc, limits.limit.lift_π],\n dsimp only [nat_trans.comp_app, functor_prod_cone, functor_prod,\n functor.comp_map, uncurry, limits.prod.functor],\n simp only [limits.prod.map_map, category.id_comp, category.comp_id, category.assoc],\n let e : Fintype.of (I.comap f.continuous) ⟶ Fintype.of I := discrete_quotient.map (le_refl _),\n erw ← (Fintype_add_functor r' c₁ c₂).naturality e,\n simp_rw ← category.assoc,\n dsimp only [Fintype_functor_prod, functor.comp_map, uncurry, limits.prod.functor,\n functor.prod, functor, Profinite.extend],\n simp only [limits.prod.map_map, category.id_comp, category.comp_id, limits.limit.lift_π],\n refl,\n end }\n\n/-- The profinite functorial variant of negation on `Lbar_le`. -/\ndef neg_functor [fact (0 < r')] : functor.{u} r' c ⟶ functor.{u} r' c :=\n{ app := λ X, limits.lim.map $ whisker_left _ $ Fintype_neg_functor _ _,\n naturality' := begin\n intros A B f,\n apply limit.hom_ext,\n intros S,\n dsimp,\n simp,\n end }\n\nvariables {c₁ c₂}\n\n/-- A bifunctor version of `functor`, where `c` can vary. -/\n@[simps]\ndef bifunctor [fact (0 < r')] : ℝ≥0 ⥤ Profinite.{u} ⥤ Profinite.{u} :=\n{ obj := λ c, functor r' c,\n map := λ a b f, Profinite.extend_nat_trans $ (Fintype_bifunctor r').map f,\n map_id' := begin\n intros c,\n rw (Fintype_bifunctor r').map_id,\n exact Profinite.extend_nat_trans_id _,\n end,\n map_comp' := begin\n intros a b c α β,\n rw (Fintype_bifunctor r').map_comp,\n exact Profinite.extend_nat_trans_comp _ _,\n end }\n\n/-- `Lbar_le.functor r' c` is indeed an extension of `Lbar_le.Fintype_functor r' c`. -/\n@[simps]\ndef functor_extends [fact (0 < r')] :\n Fintype.to_Profinite ⋙ functor.{u} r' c ≅ Fintype_functor.{u} r' c :=\nProfinite.extend_extends _ .\n\nvariables {r' c}\n\n-/\n\nend Lbar_le\n\ninstance [fact (0 < r')] : profinitely_filtered_pseudo_normed_group (Lbar r' S) :=\n{ topology := λ c, show topological_space (Lbar_le r' S c), by apply_instance,\n t2 := λ c, show t2_space (Lbar_le r' S c), by apply_instance,\n td := λ c, show totally_disconnected_space (Lbar_le r' S c), by apply_instance,\n compact := λ c, show compact_space (Lbar_le r' S c), by apply_instance,\n continuous_add' := λ c₁ c₂, Lbar_le.continuous_add',\n continuous_neg' := λ c, Lbar_le.continuous_neg,\n continuous_cast_le := λ c₁ c₂,\n begin\n introI h,\n rw show pseudo_normed_group.cast_le = (Lbar_le.cast_le : Lbar_le r' S c₁ → Lbar_le r' S c₂),\n by {ext, refl},\n exact Lbar_le.continuous_cast_le r' S c₁ c₂,\n end,\n .. Lbar.pseudo_normed_group }\n\n/-\n\nnamespace Lbar\n\n\nvariable r'\n\n/-- The diagram whose colimit yields `Lbar.profinite`. -/\ndef profinite_diagram [fact (0 < r')] : ℝ≥0 ⥤ Profinite.{u} ⥤ Type u :=\nlet E := (whiskering_right Profinite _ _).obj (forget Profinite) in\n ((whiskering_right _ _ _).obj E).obj (Lbar_le.bifunctor.{u} r')\n\n/-- The functor `Lbar : Profinite ⥤ Type*`. -/\n@[nolint check_univs] -- TODO remove this\ndef profinite [fact (0 < r')] : Profinite ⥤ Type* :=\n(as_small.down ⋙ profinite_diagram r').flip ⋙ colim\n\nattribute [nolint check_univs] profinite._proof_1\n\n-- TODO: Move this to the condensed folder, once it's more stable!\n/-- The representable presheaf associated to a profinite set. -/\ndef representable : Profinite.{u} ⥤ (as_small.{u+1} Profinite.{u})ᵒᵖ ⥤ Type (u+1) :=\nlet Y := @yoneda (as_small.{u+1} Profinite.{u}) _ in\n((whiskering_right Profinite.{u} _ _).obj Y).obj as_small.up\n\n/-- The diagram whose colimit yields `Lbar.precondensed`. -/\ndef precondensed_diagram [fact (0 < r')] :\n ℝ≥0 ⥤ Profinite.{u} ⥤ (as_small.{u+1} Profinite.{u})ᵒᵖ ⥤ Type (u+1) :=\nlet E := (whiskering_right Profinite _ _).obj representable in\n((whiskering_right _ _ _).obj E).obj $ Lbar_le.bifunctor.{u} r'\n\n/-- A functor associating to every `S : Profinite` the presheaf associated to the condensed set\n`Lbar(S)`. -/\n-- TODO: Prove that it is a condensed set!\ndef precondensed [fact (0 < r')] : Profinite.{u} ⥤ (as_small.{u+1} Profinite.{u})ᵒᵖ ⥤ Type (u+1) :=\n(as_small.down.{_ _ (u+1)} ⋙ precondensed_diagram.{u} r').flip ⋙ colim\n\nend Lbar\n\n-/\n\n#lint-\n", "meta": {"author": "leanprover-community", "repo": "lean-liquid", "sha": "92f188bd17f34dbfefc92a83069577f708851aec", "save_path": "github-repos/lean/leanprover-community-lean-liquid", "path": "github-repos/lean/leanprover-community-lean-liquid/lean-liquid-92f188bd17f34dbfefc92a83069577f708851aec/src/Lbar/Lbar_le.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44552952031526044, "lm_q2_score": 0.051082741290902595, "lm_q1q2_score": 0.02275886922372438}} {"text": "\nnamespace Lean4Axiomatic\n\n/-! # Handedness -/\n\n/--\nHandedness: either left-handed or right-handed.\n\nIntended to be used as a more meaniningful `Bool` type in contexts where it\napplies. One example is in selecting the left- or right-hand side of an ordered\npair. Another is in specifying which side of a binary operator an algebraic\nproperty acts on; a common one is the concept of a left inverse (`a⁻¹ * a ≃ 1`)\nvs. a right inverse (`a * a⁻¹ ≃ 1`).\n-/\ninductive Hand where\n| /-- Left hand. -/ L\n| /-- Right hand. -/ R\n\n/--\nSelects the left-hand or right-hand argument, according to the given `Hand`.\n\n**Named parameters**\n- `α`: The `Sort` of the items to select.\n-/\nabbrev Hand.pick {α : Sort u} : Hand → α → α → α\n| L, x, _ => x\n| R, _, y => y\n\nend Lean4Axiomatic\n", "meta": {"author": "cruhland", "repo": "lean4-axiomatic", "sha": "6384bd38b8ba104530247d25456858775fe3c442", "save_path": "github-repos/lean/cruhland-lean4-axiomatic", "path": "github-repos/lean/cruhland-lean4-axiomatic/lean4-axiomatic-6384bd38b8ba104530247d25456858775fe3c442/Lean4Axiomatic/Hand.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.36658973632215985, "lm_q2_score": 0.06187599221093973, "lm_q1q2_score": 0.022683103669280412}} {"text": "/-\nCopyright (c) 2020 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Leonardo de Moura\n-/\nprelude\nimport Init.Notation\n\n/- SizeOf -/\n\nclass SizeOf (α : Sort u) where\n sizeOf : α → Nat\n\nexport SizeOf (sizeOf)\n\n/-\nDeclare sizeOf instances and theorems for types declared before SizeOf.\nFrom now on, the inductive Compiler will automatically generate sizeOf instances and theorems.\n-/\n\n/- Every Type `α` has a default SizeOf instance that just returns 0 for every element of `α` -/\nprotected def default.sizeOf (α : Sort u) : α → Nat\n | a => 0\n\ninstance (priority := low) (α : Sort u) : SizeOf α where\n sizeOf := default.sizeOf α\n\n@[simp] theorem sizeOf_default (n : α) : sizeOf n = 0 := rfl\n\ninstance : SizeOf Nat where\n sizeOf n := n\n\n@[simp] theorem sizeOf_nat (n : Nat) : sizeOf n = n := rfl\n\nderiving instance SizeOf for Prod\nderiving instance SizeOf for PUnit\nderiving instance SizeOf for Bool\nderiving instance SizeOf for Option\nderiving instance SizeOf for List\nderiving instance SizeOf for Array\nderiving instance SizeOf for Subtype\nderiving instance SizeOf for Fin\nderiving instance SizeOf for USize\nderiving instance SizeOf for UInt8\nderiving instance SizeOf for UInt16\nderiving instance SizeOf for UInt32\nderiving instance SizeOf for UInt64\nderiving instance SizeOf for Char\nderiving instance SizeOf for String\nderiving instance SizeOf for Substring\nderiving instance SizeOf for Except\nderiving instance SizeOf for EStateM.Result\n\n/- We manually define `Lean.Name` instance because we use\n an opaque function for computing the hashcode field. -/\nprotected noncomputable def Lean.Name.sizeOf : Name → Nat\n | anonymous => 1\n | str p s _ => 1 + Name.sizeOf p + sizeOf s\n | num p n _ => 1 + Name.sizeOf p + sizeOf n\n\nnoncomputable instance : SizeOf Lean.Name where\n sizeOf n := n.sizeOf\n\nderiving instance SizeOf for Lean.Syntax\n", "meta": {"author": "Kha", "repo": "lean4-nightly", "sha": "b4c92de57090e6c47b29d3575df53d86fce52752", "save_path": "github-repos/lean/Kha-lean4-nightly", "path": "github-repos/lean/Kha-lean4-nightly/lean4-nightly-b4c92de57090e6c47b29d3575df53d86fce52752/stage0/src/Init/SizeOf.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.411110869232168, "lm_q2_score": 0.05500528596978023, "lm_q1q2_score": 0.022613270927400324}} {"text": "import .fol .abel\n\nuniverse u\n\nsection weekdays\n@[derive has_reflect]\ninductive weekday : Type\n| monday : weekday\n| another_day : weekday → weekday\n\nopen weekday\n\nmeta def dump_weekday (f : weekday) : tactic unit :=\ntactic.trace $ to_string (expr.to_raw_fmt (reflect f).to_expr) \n\n-- run_cmd dump_weekday (another_day (another_day monday))\n--(app (const weekday.another_day []) (app (const weekday.another_day []) (const weekday.monday [])))\n\ninductive weekday' : Type\n| monday : weekday'\n| another_day : weekday' → weekday'\n\nopen weekday'\nmeta instance has_reflect_weekday' : has_reflect weekday'\n| weekday'.monday := `(monday)\n| (weekday'.another_day x) := `(λ l, weekday'.another_day l).subst $\n by haveI := has_reflect_weekday'; exact (reflect x)\n\nmeta def dump_weekday' (f : weekday') : tactic unit :=\ntactic.trace $ to_string (expr.to_raw_fmt (reflect f).to_expr) \n\n\n-- run_cmd dump_weekday' (another_day (another_day monday))\n-- (app (const weekday'.another_day []) (app (const weekday'.another_day []) (const weekday'.monday [])))\nend weekdays\n-- meta instance has_reflect_preterm {L : Language.{u}} : Π{n : ℕ}, has_reflect (preterm L n)\n-- | 0 (var k) := `(@preterm.var L).subst (reflect k)\n\n-- @[derive has_reflect]\n\nopen fol abel\n\nsection preterm_aux \ninductive preterm_aux (L : Language.{u}) : Type u\n| var : ℕ → preterm_aux\n| func : ∀ k : ℕ, L.functions k → preterm_aux\n| app : preterm_aux → preterm_aux → preterm_aux\n\ndef to_aux {L : Language.{u}} : ∀ {l : ℕ}, preterm L l → preterm_aux L\n| 0 (var n) := preterm_aux.var _ n\n| k (func f) := preterm_aux.func _ f\n| k (app t₁ t₂) := preterm_aux.app (to_aux t₁) (to_aux t₂)\n\n\ndef L_abel_plus' (t₁ t₂ : preterm L_abel 0) : preterm L_abel 0 :=\n@term_of_function L_abel 2 (abel_functions.plus : L_abel.functions 2) t₁ t₂\nend preterm_aux\n\nlocal infix ` +' `:100 := L_abel_plus'\n\nlocal notation ` zero ` := (func abel_functions.zero : preterm L_abel 0)\n\nsection L_abel_term_biopsy\n\ndef sample1 : preterm L_abel 0 := (zero +' zero)\n\ndef sample2 : preterm L_abel 0 := zero\n\n-- #reduce sample2\n\nopen expr\nmeta def sample2_expr : expr :=\nmk_app (const `preterm.func list.nil) ([(const `L_abel list.nil), `(0), const `abel_functions.zero list.nil] : list expr)\n\nend L_abel_term_biopsy\n\nsection simpler_biopsy\n\ninductive my_inductive : Type\n| a : my_inductive\n| b : my_inductive\n| f : my_inductive → my_inductive\n\nopen my_inductive\ndef sample3 : my_inductive := f a\n\nopen expr\n\nmeta def sample3_expr : expr :=\napp (const `my_inductive.f list.nil) (const `my_inductive.a list.nil)\n\ndef sample3_again : my_inductive := by tactic.exact (sample3_expr)\n\nexample : sample3 = sample3_again := rfl\n\nend simpler_biopsy\n\nnamespace tactic\nnamespace interactive\nopen interactive interactive.types expr\n\ndef my_test_term : preterm L_abel 0 := (zero +' zero)\n\nend interactive\nend tactic\n\nsection test\n-- def my_term : preterm L_abel 0 := sorry\n\n-- #check tactic.interactive.rcases\n\nend test\n\nsection sample4\n\n/-- Note: this is the same as `dfin` -/\ninductive my_indexed_family : ℕ → Type u\n| z {} : my_indexed_family 0\n| s : ∀ {k}, my_indexed_family k → my_indexed_family (k+1)\n\n-- meta example : ∀ {n}, has_reflect (my_indexed_family n)\n-- | 0 z := `(z)\n\n\nopen my_indexed_family\n\ndef sample4 : my_indexed_family 1 := s z\n\n-- #check tactic.eval_expr\n\nend sample4\n\nsection sample4\n\ninductive dfin'' : ℕ → Type\n| fz {n} : dfin'' (n+1)\n| fs {n} : dfin'' n → dfin'' (n+1)\n\ninductive dfin' : ℕ → Type u\n| gz {n} : dfin' (n+1)\n| gs {n} : dfin' n → dfin' (n+1)\n\nopen dfin dfin'\n\nmeta instance dfin.reflect : ∀ {n}, has_reflect (dfin'' n)\n| _ dfin''.fz := `(dfin''.fz)\n| _ (dfin''.fs n) := `(dfin''.fs).subst (dfin.reflect n)\n\n-- /- errors all over---why doesn't reflect like universe parameters? -/\n-- meta instance dfin'.reflect : ∀ {n}, has_reflect (dfin' n)\n-- | _ fz := `(fz)\n-- | _ (fs n) := `(fs).subst (dfin'.reflect n)\n\nend sample4\n\nsection reflect_preterm\n\n/- Language with a single constant symbol -/\ninductive L_pt_functions : ℕ → Type\n| pt : L_pt_functions 0\n\ndef L_pt : Language.{0} := ⟨L_pt_functions, λ _, empty⟩\n\ndef pt_preterm : preterm L_pt 0 := preterm.func L_pt_functions.pt\n\nmeta def pt_preterm_reflected : expr :=\nexpr.mk_app (expr.const `preterm.func [level.zero]) [ (expr.const `L_pt list.nil), `(0), (expr.const `L_pt_functions.pt list.nil)]\n\nset_option trace.app_builder true\n\n-- meta def pt_preterm_reflected' : expr := by tactic.mk_app \"preterm.func\" [(expr.const `L_pt []), `(0), (expr.const `L_pt_functions.pt [])]\n\n#check tactic.mk_app\n\nmeta def pt_preterm_reflected'' : tactic expr :=\ntactic.to_expr ```(preterm.func L_pt_functions.pt : preterm L_pt 0)\n\ndef pt_preterm' : preterm L_pt 0 := by pt_preterm_reflected'' >>= tactic.exact\n\n-- def pt_preterm' : preterm L_pt 0 := by tactic.exact pt_preterm_reflected\n\nexample : pt_preterm = pt_preterm' := rfl\n -- infer type failed, incorrect number of universe levels\n\n-- want: example : pt_preterm = pt_preterm' := rfl\n\n\nend reflect_preterm\n\n\nnamespace hewwo\nsection reflect_preterm2\ndef L_pt.pt' : L_pt.functions 0 := L_pt_functions.pt\n\n#reduce (by apply_instance : reflected L_pt.pt')\n-- `(L_pt.pt')\n\nmeta def pt_preterm_reflected : tactic expr :=\ntactic.mk_app ``preterm.func [`(L_pt.pt')]\n\ndef pt_preterm' : preterm L_pt 0 := by pt_preterm_reflected >>= tactic.exact\n\n#eval tactic.trace (@expr.to_raw_fmt tt `(L_pt.pt'))\n\n#check reflect\n\n\nend reflect_preterm2\nend hewwo\n\nsection reflect_preterm3\n\ninductive L_pt_func_functions : ℕ → Type\n| pt : L_pt_func_functions 0\n| foo : L_pt_func_functions 1\n\nopen L_pt_func_functions\n\ndef L_pt_func : Language.{0} :=\n⟨L_pt_func_functions, λ _, ulift empty⟩\n\n-- def foo_pt_term : preterm L_pt_func 0 :=\n-- preterm.app (preterm.func L_pt_func_functions.foo) (preterm.func L_pt_func_functions.pt)\n\n-- def foo_pt_term_reflected : expr :=\n-- begin\n-- tactic.mk_app ``preterm.func [(by tactic.mk_app `preterm.func [`(L_pt_func_functions.foo)]), (by tactic.mk_app `preterm.func [`(L_pt_func_functions.pt)])]\n-- end\n\n-- def foo' : preterm L_pt_func 1 := preterm.func L_pt_func_functions.foo\n\n\n-- #reduce (by apply_instance : reflected L_pt_func_functions.foo)\n\nset_option trace.app_builder true\n\ndef my_foo : L_pt_func.functions 1 := L_pt_func_functions.foo\n\ndef my_pt : L_pt_func.functions 0 := L_pt_func_functions.pt\n\n-- meta def foo_pt_term_reflected : tactic expr := tactic.mk_app ``preterm.func [`()]\n\nmeta def foo_pt_term_reflected' : tactic expr :=\ndo e₁ <- tactic.mk_app ``preterm.func [`(my_foo)],\n e₂ <- tactic.mk_app ``preterm.func [`(my_pt)],\n tactic.mk_app ``preterm.app [e₁, e₂]\n-- #print foo_pt_term_reflected'\n\n\n\n-- meta def bar : tactic expr :=\n-- tactic.mk_app ``preterm.func [`(foo_mask)]\n\nset_option trace.app_builder true\n\ndef foo_pt_term_reflected : preterm L_pt_func 0 := by (foo_pt_term_reflected' >>= tactic.exact)\n\n-- #reduce foo_pt_term_reflected\n\n\nend reflect_preterm3\n", "meta": {"author": "flypitch", "repo": "flypitch", "sha": "aea5800db1f4cce53fc4a113711454b27388ecf8", "save_path": "github-repos/lean/flypitch-flypitch", "path": "github-repos/lean/flypitch-flypitch/flypitch-aea5800db1f4cce53fc4a113711454b27388ecf8/old/reflect_test.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4225046348141883, "lm_q2_score": 0.05340333205964859, "lm_q1q2_score": 0.022563155309722662}} {"text": "structure A where\n x : Nat\n w : Nat\n\nstructure B extends A where\n y : Nat\n\nstructure C extends B where\n z : Nat\n\ndef f1 (c : C) (a : A) : C :=\n { c with toA := a, x := 0 } -- Error, `toA` and `x` are both updates to field `x`\n\ndef f2 (c : C) (a : A) : C :=\n { c with toA := a }\n\ndef f3 (c : C) (a : A) : C :=\n { a, c with x := 0 }\n\ntheorem ex1 (a : A) (c : C) : (f3 c a).x = 0 :=\n rfl\n\ntheorem ex2 (a : A) (c : C) : (f3 c a).w = a.w :=\n rfl\n\ndef f4 (c : C) (a : A) : C :=\n { c, a with x := 0 } -- TODO: generate error that `a` was not used?\n\ntheorem ex3 (a : A) (c : C) : (f4 c a).w = c.w :=\n rfl\n\ntheorem ex4 (a : A) (c : C) : (f4 c a).x = 0 :=\n rfl\n\ndef f5 (c : C) (a : A) :=\n { c, a with x := 0 } -- Error\n", "meta": {"author": "Kha", "repo": "lean4-nightly", "sha": "b4c92de57090e6c47b29d3575df53d86fce52752", "save_path": "github-repos/lean/Kha-lean4-nightly", "path": "github-repos/lean/Kha-lean4-nightly/lean4-nightly-b4c92de57090e6c47b29d3575df53d86fce52752/tests/lean/structInst1.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43398146480389854, "lm_q2_score": 0.05184546939667007, "lm_q1q2_score": 0.02249997275221257}} {"text": "import QL.FOL.deduction\n\nuniverses u v\nopen_locale logic_symbol\n\nnamespace fol\nopen logic subformula\nvariables (L : language.{u})\n\nstructure Structure (L : language.{u}) :=\n(dom : Type u)\n(fn : ∀ {n}, L.fn n → (fin n → dom) → dom)\n(pr : ∀ {n}, L.pr n → (fin n → dom) → Prop)\n\ninstance Structure_coe {L : language} : has_coe_to_sort (Structure L) (Type*) := ⟨Structure.dom⟩\n\nstructure nonempty_Structure (L : language.{u}) extends Structure L :=\n(dom_inhabited : inhabited dom)\n\ninstance nonempty_to_Structure_coe (L : language.{u}) : has_coe_t (nonempty_Structure L) (Structure L) := ⟨nonempty_Structure.to_Structure⟩\n\ninstance nonempty_Structure_dom_coe {L : language} : has_coe_to_sort (nonempty_Structure L) (Type*) :=\n⟨λ S, ((S : Structure L) : Type*)⟩\n\ninstance (S : nonempty_Structure L) : inhabited S := S.dom_inhabited\n\nstructure finite_Structure (L : language.{u}) extends Structure L :=\n(dom_finite : finite dom)\n\ninstance finite_Structure_coe (L : language.{u}) : has_coe_t (finite_Structure L) (Structure L) := ⟨finite_Structure.to_Structure⟩\n\nvariables {L} {μ : Type v} {μ₁ : Type*} {μ₂ : Type*}\n\nopen subterm subformula\n\nnamespace subterm\nvariables (S : Structure L) {n : ℕ} (Φ : μ → S) (e : fin n → S)\n\n@[simp] def val (Φ : μ → S) (e : fin n → S) : subterm L μ n → S\n| (&x) := Φ x\n| (#x) := e x\n| (function f v) := S.fn f (λ i, (v i).val)\n\nlemma val_rew (s : μ₁ → subterm L μ₂ n) (Φ : μ₂ → S) (e : fin n → S) (t : subterm L μ₁ n) :\n (rew s t).val S Φ e = t.val S (λ x, val S Φ e (s x)) e :=\nby induction t; simp*\n\nlemma val_map (f : μ₁ → μ₂) (Φ : μ₂ → S) (e : fin n → S) (t : subterm L μ₁ n) :\n (map f t).val S Φ e = t.val S (λ x, Φ (f x)) e :=\nby simp[map, val_rew]\n\nlemma val_subst (u : subterm L μ n) (t : subterm L μ (n + 1)) :\n (subst u t).val S Φ e = t.val S Φ (e <* u.val S Φ e) :=\nby { induction t; simp*, case var : x { refine fin.last_cases _ _ x; simp } }\n\nlemma val_lift (x : S) (t : subterm L μ n) :\n t.lift.val S Φ (x *> e) = t.val S Φ e :=\nby induction t; simp*\n\nsection bounded_subterm\nvariables {m : ℕ} {Ψ : fin m → S}\n\nlemma val_mlift (x : S) (t : bounded_subterm L m n) :\n t.mlift.val S (Ψ <* x) e = t.val S Ψ e :=\nby simp[mlift, val_rew, val_map]\n\nlemma val_push (x : S) (e : fin n → S) (t : bounded_subterm L m (n + 1)) :\n val S (Ψ <* x) e t.push = val S Ψ (e <* x) t :=\nby { induction t; simp*, case var : u { refine fin.last_cases _ _ u; simp } }\n\nlemma val_pull (x : S) (e : fin n → S) (t : bounded_subterm L (m + 1) n) :\n val S Ψ (e <* x) t.pull = val S (Ψ <* x) e t :=\nby { induction t; simp*, case metavar : u { refine fin.last_cases _ _ u; simp } }\n\nend bounded_subterm\n\nend subterm\n\nnamespace subformula\nvariables {μ μ₁ μ₂} (S : Structure L) {n : ℕ} {Φ : μ → S} {e : fin n → S}\n\n@[simp] def subval' (Φ : μ → S) : ∀ {n} (e : fin n → S), subformula L μ n → Prop\n| n _ verum := true\n| n e (relation p v) := S.pr p (subterm.val S Φ e ∘ v)\n| n e (imply p q) := p.subval' e → q.subval' e\n| n e (neg p) := ¬(p.subval' e)\n| n e (fal p) := ∀ x : S.dom, (p.subval' (x *> e))\n\n@[irreducible] def subval (Φ : μ → S) (e : fin n → S) : subformula L μ n →ₗ Prop :=\n{ to_fun := subval' S Φ e,\n map_neg' := λ _, by refl,\n map_imply' := λ _ _, by refl,\n map_and' := λ p q, by unfold has_inf.inf; simp[and]; refl,\n map_or' := λ p q, by unfold has_sup.sup; simp[or, ←or_iff_not_imp_left]; refl,\n map_top' := by refl,\n map_bot' := by simp[bot_def]; unfold has_top.top has_negation.neg; simp }\n\n@[reducible] def val (Φ : μ → S) : formula L μ →ₗ Prop := subformula.subval S Φ fin.nil\n\n@[simp] lemma subval_relation {p} {r : L.pr p} {v} :\n subval S Φ e (relation r v) ↔ S.pr r (λ i, subterm.val S Φ e (v i)) := by simp[subval]; refl\n\n@[simp] lemma subval_fal {p : subformula L μ (n + 1)} :\n subval S Φ e (∀'p) ↔ ∀ x : S, subval S Φ (x *> e) p := by simp[subval]; refl\n\n@[simp] lemma subval_ex {p : subformula L μ (n + 1)} :\n subval S Φ e (∃'p) ↔ ∃ x : S, subval S Φ (x *> e) p := by simp[ex_def]\n\nlemma subval_rew {Φ : μ₂ → S} {n} {e : fin n → S} {s : μ₁ → subterm L μ₂ n} {p : subformula L μ₁ n} :\n subval S Φ e (rew s p) ↔ subval S (λ x, subterm.val S Φ e (s x)) e p :=\nby induction p using fol.subformula.ind_on; intros; simp[*, subterm.val_rew, subterm.val_lift]\n\nlemma subval_map {Φ : μ₂ → S} {n} {e : fin n → S} {f : μ₁ → μ₂} {p : subformula L μ₁ n} :\n subval S Φ e (map f p) ↔ subval S (λ x, Φ (f x)) e p :=\nby simp[map, subval_rew]\n\n@[simp] lemma subval_subst {n} {p : subformula L μ (n + 1)} : ∀ {e : fin n → S} {t : subterm L μ n},\n subval S Φ e (subst t p) ↔ subval S Φ (e <* subterm.val S Φ e t) p :=\nby apply ind_succ_on p; intros; simp[*, subterm.val_subst, subterm.val_lift, fin.left_right_concat_assoc]\n\nsection bounded_subformula\nvariables {m : ℕ} {Ψ : fin m → S}\n\nlemma subval_mlift {x} {p : bounded_subformula L m n} :\n subval S (Ψ <* x) e p.mlift = subval S Ψ e p := by simp[mlift, (∘), subval_map]\n\nlemma subval_push {x} {n} {p : bounded_subformula L m (n + 1)} : ∀ {e : fin n → S},\n subval S (Ψ <* x) e p.push ↔ subval S Ψ (e <* x) p :=\nby apply ind_succ_on p; intros; simp[*, subterm.val_push, fin.left_right_concat_assoc]\n\nlemma subval_pull {x} {n} {p : bounded_subformula L (m + 1) n} : ∀ {e : fin n → S},\n subval S Ψ (e <* x) p.pull ↔ subval S (Ψ <* x) e p :=\nby induction p using fol.subformula.ind_on generalizing Ψ; intros; simp[*, subterm.val_pull, fin.left_right_concat_assoc]\n\nlemma subval_dummy {x} : ∀ {n} {e : fin n → S} {p : bounded_subformula L m n},\n subval S Ψ (e <* x) p.dummy ↔ subval S Ψ e p :=\nby simp[dummy, subval_pull, subval_mlift]\n\nend bounded_subformula\n\nend subformula\n\nnamespace nonempty_Structure\nvariables (M : nonempty_Structure L)\n\nlemma coe_def : (M : Structure L) = M.to_Structure := rfl\n\n@[simp] lemma fn_coe : @Structure.fn L (M : Structure L) = @Structure.fn L M.to_Structure := rfl\n\n@[simp] lemma pr_coe : @Structure.pr L (M : Structure L) = @Structure.pr L M.to_Structure := rfl\n\ninstance : inhabited (nonempty_Structure L) :=\n⟨{ dom := punit,\n fn := λ k f v, punit.star,\n pr := λ k r v, false,\n dom_inhabited := punit.inhabited }⟩\n\nend nonempty_Structure\n\nnamespace Structure\n\n@[ext] lemma ext (S₁ S₂ : Structure L)\n (hdom : @dom L S₁ = @dom L S₂)\n (hfn : ∀ {k} (f : L.fn k), @fn L S₁ k f == @fn L S₂ k f)\n (hpr : ∀ {k} (r : L.pr k), @pr L S₁ k r == @pr L S₂ k r) : S₁ = S₂ :=\nbegin\n rcases S₁, rcases S₂, simp at hdom ⊢ hfn hpr, refine ⟨hdom, _, _⟩,\n { ext; simp, rintros k k rfl, ext; simp, rintros f f rfl, exact hfn f },\n { ext; simp, rintros k k rfl, ext; simp, rintros r r rfl, exact hpr r }\nend\n\nlemma eta (S : Structure L) : ({dom := S.dom, fn := @fn L S, pr := @pr L S} : Structure L) = S :=\nby ext; simp\n\nclass Structure.proper_equal [L.has_equal] (S : Structure L)\n(val_eq : ∀ {n : ℕ} {t u : subterm L μ n} {Φ e}, subformula.subval S Φ e (t =' u) ↔ (t.val S Φ e = u.val S Φ e))\n\ndef nonempty (S : Structure L) [c : inhabited S] : nonempty_Structure L :=\n{ dom_inhabited := c, ..S }\n\nvariables (S : Structure L) [inhabited S]\n\n@[simp] lemma coe_nonempty : (S.nonempty : Type*) = S := rfl\n\n@[simp] lemma to_Structure_nonempty : (S.nonempty : Structure L) = S := by simp[nonempty, nonempty_Structure.coe_def, eta]\n\ninstance : inhabited (Structure L) :=\n⟨(default : nonempty_Structure L)⟩\n\nend Structure\n\nnamespace subformula\nvariables (S : Structure L) {Φ : μ → S}\n\nnotation S` ⊧[`:80 e`] `p :50 := val S e p\n\nvariables {S} {p q : formula L μ}\n\n@[simp] lemma models_relation {k} {r : L.pr k} {v} :\n S ⊧[Φ] relation r v ↔ S.pr r (λ i, subterm.val S Φ fin.nil (v i)) := by simp[val]\n\nsection bounded\nvariables {m : ℕ} {Ψ : fin m → S}\n\n@[simp] lemma val_fal {p : bounded_subformula L m 1} :\n S ⊧[Ψ] ∀'p ↔ ∀ x, S ⊧[Ψ <* x] p.push :=\nby simp[val, subval_push, fin.concat_zero]\n\n@[simp] lemma val_ex {p : bounded_subformula L m 1} :\n S ⊧[Ψ] ∃'p ↔ ∃ x, S ⊧[Ψ <* x] p.push :=\nby simp[val, subval_push, fin.concat_zero]\n\n@[simp] lemma val_subst {p : bounded_subformula L m 1} {t : bounded_subterm L m 0} :\n S ⊧[Ψ] subst t p ↔ S ⊧[Ψ <* subterm.val S Ψ fin.nil t] p.push :=\nby simp[val, subval_subst, subval_push]\n\n@[simp] lemma val_mlift {x : S} {p : bounded_subformula L m 0} : S ⊧[Ψ <* x] p.mlift ↔ S ⊧[Ψ] p :=\nby simp[val, subval_mlift]\n\nend bounded\n\nend subformula\n\ndef models (S : Structure L) (p : formula L μ) : Prop := ∀ e, S ⊧[e] p\n\ninstance : semantics (formula L μ) (Structure L) := ⟨models⟩\n\ninstance : semantics (formula L μ) (nonempty_Structure L) := ⟨λ S p, (S : Structure L) ⊧ p⟩\n\nnamespace Structure\n\nvariables {S : Structure L} {σ τ : sentence L}\n\nlemma models_def {p : formula L μ} : S ⊧ p ↔ (∀ e, S ⊧[e] p) := by refl\n\nlemma sentence_models_def :\n S ⊧ σ ↔ S ⊧[fin.nil] σ := by simp[models_def, fin.nil]\n\n@[simp] lemma formula_verum : S ⊧ (⊤ : formula L μ) := by simp[models_def]\n\n@[simp] lemma sentence_falsum : ¬S ⊧ (⊥ : sentence L) := by simp[models_def]\n\n@[simp] lemma sentence_relation {k} (r : L.pr k) (v : fin k → bounded_subterm L 0 0) :\n S ⊧ (relation r v) ↔ S.pr r (subterm.val S fin.nil fin.nil ∘ v) := by simp[sentence_models_def]\n\n@[simp] lemma sentence_imply : S ⊧ σ ⟶ τ ↔ (S ⊧ σ → S ⊧ τ) := by simp[sentence_models_def]\n\n@[simp] lemma sentence_neg : S ⊧ ∼σ ↔ ¬S ⊧ σ := by simp[sentence_models_def]\n\n@[simp] lemma sentence_and : S ⊧ σ ⊓ τ ↔ S ⊧ σ ∧ S ⊧ τ := by simp[sentence_models_def]\n\n@[simp] lemma sentence_or : S ⊧ σ ⊔ τ ↔ S ⊧ σ ∨ S ⊧ τ := by simp[sentence_models_def]\n\n@[simp] lemma sentence_equiv : S ⊧ σ ⟷ τ ↔ (S ⊧ σ ↔ S ⊧ τ) := by simp[sentence_models_def]\n\ninstance : semantics.nontrivial (sentence L) (Structure L) :=\n⟨by simp[models_def], by simp[models_def]⟩\n\nabbreviation valid (p : formula L μ) : Prop := semantics.valid (Structure L) p\n\nabbreviation satisfiable (p : formula L μ) : Prop := semantics.satisfiable (Structure L) p\n\nlemma valid_def (p : formula L μ) : valid p ↔ ∀ S : Structure L, S ⊧ p := by refl\n\nlemma satisfiable_def (p : formula L μ) : satisfiable p ↔ ∃ S : Structure L, S ⊧ p := by refl\n\nabbreviation Satisfiable (T : preTheory L μ) : Prop := semantics.Satisfiable (Structure L) T\n\nlemma Satisfiable_def (T : preTheory L μ) : Satisfiable T ↔ ∃ S: Structure L, S ⊧ T := by refl\n\n@[simp] lemma sentence_not_valid_iff_satisfiable (σ : sentence L) : ¬valid σ ↔ satisfiable (∼σ) :=\nby simp[valid_def, satisfiable_def]\n\n@[simp] lemma models_mlift [inhabited S] {m} {p : bounded_formula L m} : S ⊧ p.mlift ↔ S ⊧ p :=\nby{ simp[models_def], split,\n { intros h e,\n have : S ⊧[e <* default] p.mlift, from h _,\n simpa using this },\n { intros h e, rw ←fin.right_concat_eq e, simpa using h (e ∘ fin.cast_succ)} }\n\nend Structure\n\nnamespace nonempty_Structure\n\nvariables {M : nonempty_Structure L} {σ τ : sentence L} {m : ℕ} {T : bounded_preTheory L m}\n\nlemma models_def {p : formula L μ} :\n M ⊧ p ↔ (∀ e, ↑M ⊧[e] p) := by refl\n\nlemma sentence_models_def {σ : sentence L} :\n M ⊧ σ ↔ ↑M ⊧[fin.nil] σ := by simp[models_def, fin.nil]\n\n@[simp] lemma formula_verum : M ⊧ (⊤ : formula L μ) := by simp[models_def]\n\n@[simp] lemma formula_falsum : ¬M ⊧ (⊥ : formula L μ) := by simp[models_def]\n\n@[simp] lemma sentence_relation {k} {r : L.pr k} {v : fin k → bounded_subterm L 0 0} :\n M ⊧ (relation r v) ↔ M.pr r (subterm.val M fin.nil fin.nil ∘ v) := by simp[sentence_models_def]\n\n@[simp] lemma sentence_imply : M ⊧ σ ⟶ τ ↔ (M ⊧ σ → M ⊧ τ) := by simp[sentence_models_def]\n\n@[simp] lemma sentence_neg : M ⊧ ∼σ ↔ ¬M ⊧ σ := by simp[sentence_models_def]\n\n@[simp] lemma sentence_and : M ⊧ σ ⊓ τ ↔ M ⊧ σ ∧ M ⊧ τ := by simp[sentence_models_def]\n\n@[simp] lemma sentence_or : M ⊧ σ ⊔ τ ↔ M ⊧ σ ∨ M ⊧ τ := by simp[sentence_models_def]\n\n@[simp] lemma sentence_equiv : M ⊧ σ ⟷ τ ↔ (M ⊧ σ ↔ M ⊧ τ) := by simp[sentence_models_def]\n\ninstance : semantics.nontrivial (formula L μ) (nonempty_Structure L) :=\n⟨by simp[models_def], by simp[models_def]⟩\n\nabbreviation valid (p : formula L μ) : Prop := semantics.valid (nonempty_Structure L) p\n\nabbreviation satisfiable (p : formula L μ) : Prop := semantics.satisfiable (nonempty_Structure L) p\n\nlemma valid_def (p : formula L μ) : valid p ↔ ∀ M : nonempty_Structure L, M ⊧ p := by refl\n\nlemma satisfiable_def (p : formula L μ) : satisfiable p ↔ ∃ M : nonempty_Structure L, M ⊧ p := by refl\n\nabbreviation Satisfiable (T : preTheory L μ) : Prop := semantics.Satisfiable (nonempty_Structure L) T\n\nlemma Satisfiable_def (T : preTheory L μ) : Satisfiable T ↔ ∃ M : nonempty_Structure L, M ⊧ T := by refl\n\n@[simp] lemma sentence_not_valid_iff_satisfiable (σ : sentence L) : ¬valid σ ↔ satisfiable (∼σ) :=\nby simp[valid_def, satisfiable_def]\n\nlemma coe_models_iff (p : formula L μ) : (M : Structure L) ⊧ p ↔ M ⊧ p := by refl\n\n@[simp] lemma models_mlift {m} {p : bounded_formula L m} : M ⊧ p.mlift ↔ M ⊧ p :=\nby simp[←coe_models_iff]\n\nlemma coe_models_Theory_iff (T : preTheory L μ) : (M : Structure L) ⊧ T ↔ M ⊧ T := by refl\n\nend nonempty_Structure\n\nnamespace Structure\nopen bounded_preTheory\nvariables {S : Structure L} {σ τ : sentence L} {m : ℕ} {T : bounded_preTheory L m}\n\nlemma nonempty_models_iff [inhabited S] (p : formula L μ) : S.nonempty ⊧ p ↔ S ⊧ p :=\nby simp[←nonempty_Structure.coe_models_iff]\n\nlemma nonempty_models_Theory_iff [inhabited S] (T : preTheory L μ) : S.nonempty ⊧ T ↔ S ⊧ T :=\nby simp[←nonempty_Structure.coe_models_Theory_iff]\n\n@[simp] lemma models_Theory_mlift [inhabited S] : S ⊧ T.mlift ↔ S ⊧ T :=\n⟨by { intros h p hp,\n have : S ⊧ p.mlift, from @h p.mlift (by simpa using hp),\n exact models_mlift.mp this },\n by { intros h p hp,\n rcases mem_mlift_iff.mp hp with ⟨q, hq, rfl⟩,\n exact models_mlift.mpr (h hq) }⟩\n\ndef consequence : preTheory L μ → formula L μ → Prop := semantics.consequence (Structure L)\n\ninfix ` ⊧₀ ` :55 := consequence\n\nlemma consequence_def {T : preTheory L μ} {p : formula L μ} :\n T ⊧₀ p ↔ (∀ S : Structure L, S ⊧ T → S ⊧ p) := by refl\n\nend Structure\n\nnamespace nonempty_Structure\nopen bounded_preTheory\nvariables {M : nonempty_Structure L} {σ τ : sentence L} {m : ℕ} {T : bounded_preTheory L m}\n\n@[simp] lemma models_Theory_mlift : M ⊧ T.mlift ↔ M ⊧ T :=\nby simp[←coe_models_Theory_iff]\n\ninstance : has_double_turnstile (preTheory L μ) (formula L μ) := ⟨semantics.consequence (nonempty_Structure L)⟩\n\nlemma consequence_def {T : preTheory L μ} {p : formula L μ} :\n T ⊧ p ↔ (∀ M : nonempty_Structure L, M ⊧ T → M ⊧ p) := by refl\n\nend nonempty_Structure\n\nvariables {S : Structure L}\nopen subformula\n\ntheorem soundness {m} {T : bounded_preTheory L m} {p} : T ⊢ p → T ⊧₀ p :=\nbegin\n intros h,\n apply provable.rec_on h,\n { intros m T p b IH S hT Φ,\n simp[subformula.val], intros x,\n haveI : inhabited S, from ⟨x⟩,\n have : S ⊧ p, from @IH S (by simpa using hT),\n exact this (Φ <* x) },\n { intros m T p q b₁ b₂ m₁ m₂ S hT Φ,\n have h₁ : S ⊧[Φ] p → S ⊧[Φ] q, by simpa using m₁ hT Φ,\n have h₂ : S ⊧[Φ] p, from m₂ hT Φ,\n exact h₁ h₂ },\n { intros m T p hp S hS, exact hS hp },\n { intros m T S h Φ, simp },\n { intros m T p q S hS Φ, simp, intros h _, exact h },\n { intros m T p q r S hS Φ, simp, intros h₁ h₂ h₃, exact h₁ h₃ (h₂ h₃) },\n { intros m T p q S hS Φ, simp, intros h₁, contrapose, exact h₁ },\n { intros m T p t S hS Φ, simp, intros h, exact h _ },\n { intros m T p q S hS Φ, simp, intros h₁ h₂ x, exact h₁ x h₂ }\nend\n\ninstance {m} : logic.sound (bounded_formula L m) (Structure L) :=\n⟨λ T p, soundness⟩\n\ntheorem nonempty_soundness {m} {T : bounded_preTheory L m} {p} : T ⊢ p → T ⊧ p :=\nby intros h M hM; exact soundness h hM\n\ninstance {m} : logic.sound (bounded_formula L m) (nonempty_Structure L) :=\n⟨λ T p, nonempty_soundness⟩\n\nend fol", "meta": {"author": "iehality", "repo": "lean-logic", "sha": "201cef2500203f7de83deb7fa8287934e2e142b2", "save_path": "github-repos/lean/iehality-lean-logic", "path": "github-repos/lean/iehality-lean-logic/lean-logic-201cef2500203f7de83deb7fa8287934e2e142b2/src/QL/FOL/semantics.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958347, "lm_q2_score": 0.04603389732778596, "lm_q1q2_score": 0.022477587685911182}} {"text": "import .datatypes .additive .reconstruction_theorems tactic.norm_num\nnamespace polya\n\nopen expr tactic diseq_proof\n--#check mk_nat_val_ne_proof use something like this below?\ntheorem fake_ne_zero_pf (q : ℚ) : q ≠ 0 := sorry\ntheorem fake_gt_zero_pf (q : ℚ) : q > 0 := sorry\ntheorem fake_lt_zero_pf (q : ℚ) : q < 0 := sorry\ntheorem fake_eq_zero_pf (q : ℚ) : q = 0 := sorry\ntheorem fake_ne_pf (q1 q2 : ℚ) : q1 ≠ q2 := sorry\n\nprivate meta def solve_by_norm_num (e : expr) : tactic expr :=\ndo (_, pf) ← solve_aux e `[norm_num, tactic.done],\n return pf\n\nmeta def mk_ne_zero_pf (q : ℚ) : tactic expr :=\n--do qe ← to_expr ``(%%(quote q) : ℚ),\n-- to_expr ``(fake_ne_zero_pf (%%qe : ℚ))\n--return `(fake_ne_zero_pf q) \nsolve_by_norm_num `(q ≠ 0)\n\n \n-- proves that q > 0, q < 0, or q = 0\nmeta def mk_sign_pf (q : ℚ) : tactic expr :=\n/-do qe ← to_expr `(%%(quote q) : ℚ),\n if q > 0 then to_expr `(fake_gt_zero_pf (%%qe : ℚ))\n else if q < 0 then to_expr `(fake_lt_zero_pf (%%qe : ℚ))\n else to_expr ``(fake_eq_zero_pf (%%qe : ℚ))-/\nif q > 0 then --return `(fake_gt_zero_pf q)\n solve_by_norm_num `(q > 0)\nelse if q < 0 then --return `(fake_lt_zero_pf q)\n solve_by_norm_num `(q < 0)\nelse --return `(fake_eq_zero_pf q)\n solve_by_norm_num `(q = 0)\n\nmeta def mk_ne_pf (q1 q2 : ℚ) : tactic expr :=\n/-do q1e ← to_expr ``(%%(quote q1) : ℚ),\n q2e ← to_expr ``(%%(quote q2) : ℚ),\n to_expr `(fake_ne_pf %%q1e %%q2e)-/\n--return `(fake_ne_pf q1 q2)\nsolve_by_norm_num `(q1 ≠ q2)\n\nmeta def mk_int_sign_pf (z : ℤ) : tactic expr :=\nif z > 0 then solve_by_norm_num `(z > 0) --return `(sorry : z > 0)\nelse if z < 0 then solve_by_norm_num `(z < 0)--return `(sorry : z < 0)\nelse solve_by_norm_num `(z = 0) --return `(sorry : z = 0)\n\n-- proves z % 2 = 0 or z % 2 = 1\nmeta def mk_int_mod_pf (z : ℤ) : tactic expr :=\nif z % 2 = 0 then return `(sorry : z % 2 = 0)\nelse return `(sorry : z % 2 = 1)\n\nnamespace diseq_proof\nprivate meta def reconstruct_hyp (lhs rhs : expr) (c : ℚ) (pf : expr) : tactic expr :=\ndo mvc ← mk_mvar,\n pft ← infer_type pf,\n to_expr ``(%%lhs ≠ %%mvc * %%rhs) >>= unify pft,\n c' ← eval_expr rat mvc,\n if c = c' then return pf else fail \"diseq_proof.reconstruct_hyp failed\"\n\nprivate meta def reconstruct_sym (rc : Π {lhs rhs : expr} {c : ℚ}, diseq_proof lhs rhs c → tactic expr)\n {lhs rhs c} (dp : diseq_proof lhs rhs c) : tactic expr :=\ndo symp ← rc dp,\n cnep ← mk_ne_zero_pf c,\n mk_mapp ``diseq_sym [none, none, none, cnep, symp] -- why doesn't mk_app work?\n\nmeta def reconstruct : Π {lhs rhs : expr} {c : ℚ}, diseq_proof lhs rhs c → tactic expr\n| .(_) .(_) .(_) (hyp (lhs) (rhs) (c) e) := reconstruct_hyp lhs rhs c e\n| .(_) .(_) .(_) (@sym lhs rhs c dp) := reconstruct_sym @reconstruct dp\n\nend diseq_proof\n\nnamespace eq_proof\n\n\nprivate meta def reconstruct_hyp (lhs rhs : expr) (c : ℚ) (pf : expr) : tactic expr :=\ndo mvc ← mk_mvar,\n pft ← infer_type pf,\n to_expr ``(%%lhs = %%mvc * %%rhs) >>= unify pft,\n c' ← eval_expr rat mvc,\n if c = c' then return pf else fail \"eq_proof.reconstruct_hyp failed\"\n\nprivate meta def reconstruct_sym (rc : Π {lhs rhs : expr} {c : ℚ}, eq_proof lhs rhs c → tactic expr)\n {lhs rhs c} (dp : eq_proof lhs rhs c) : tactic expr :=\ndo symp ← rc dp,\n cnep ← mk_ne_zero_pf c, -- 5/1 ≠ 0\n-- infer_type symp >>= trace,\n-- infer_type cnep >>= trace,\n mk_mapp ``eq_sym [none, none, none, cnep, symp] -- why doesn't mk_app work?\n\nvariable iepr_fn : Π {lhs rhs i}, ineq_proof lhs rhs i → tactic expr\n\nprivate meta def reconstruct_of_opp_ineqs_aux {lhs rhs i} (c : ℚ) (iep : ineq_proof lhs rhs i) \n (iepr : ineq_proof lhs rhs i.reverse) : tactic expr :=\ndo guard (bnot i.strict),\n pr1 ← iepr_fn iep, pr2 ← iepr_fn iepr,\n if i.to_comp.is_less then\n mk_mapp ``op_ineq [none, none, none, some pr1, some pr2]\n else\n mk_mapp ``op_ineq [none, none, none, some pr2, some pr1]\n\nprivate theorem eq_sub_of_add_eq_facs {c1 c2 e1 e2 : ℚ} (hc1 : c1 ≠ 0) (h : c1 * e1 + c2 * e2 = 0) : e1 = -(c2/c1) * e2 :=\nsorry\n\n\nprivate meta def reconstruct_of_sum_form_proof (sfpr : Π {sf}, Π (sp : sum_form_proof sf), tactic expr) : expr → expr → ℚ → Π {sf},\n Π (sp : sum_form_proof ⟨sf, spec_comp.eq⟩), tactic expr | lhs rhs c sf sp :=\nif lhs.lt rhs then -- flipped? \n reconstruct_of_sum_form_proof rhs lhs (1/c) sp\nelse do\n guard $ (sf.contains lhs) && (sf.contains rhs),\n let a := sf.get_coeff lhs in let b := sf.get_coeff rhs in do\n guard $ c = -(b/a),\n pf ← sfpr sp,\n nez ← mk_ne_zero_pf a,\n mk_app ``eq_sub_of_add_eq_facs [nez, pf] \n-- fail \"eq_proof.reconstruct_of_sum_proof not implemented yet\"\n\nmeta def reconstruct_aux (sfpr : Π {sf}, Π (sp : sum_form_proof sf), tactic expr) : Π {lhs rhs : expr} {c : ℚ}, eq_proof lhs rhs c → tactic expr\n| .(_) .(_) .(_) (hyp (lhs) (rhs) (c) e) := reconstruct_hyp lhs rhs c e\n| .(_) .(_) .(_) (@sym lhs rhs c dp) := reconstruct_sym @reconstruct_aux dp\n| .(_) .(_) .(_) (@of_opp_ineqs lhs rhs i c iep iepr) := reconstruct_of_opp_ineqs_aux @iepr_fn c iep iepr\n| .(_) .(_) .(_) (@of_sum_form_proof lhs rhs c _ sp) := reconstruct_of_sum_form_proof @sfpr lhs rhs c sp\n| .(_) .(_) .(_) (adhoc _ _ _ _ t) := t\n\nend eq_proof\n\nnamespace ineq_proof\n\nmeta def guard_is_ineq (lhs rhs : expr) (iq : ineq) (pf : expr) : tactic expr :=\ndo mvc ← mk_mvar, pft ← infer_type pf, \nmatch iq.to_comp with\n| comp.lt := to_expr ``(%%lhs < %%mvc * %%rhs) >>= unify pft >> return mvc\n| comp.le := to_expr ``(%%lhs ≤ %%mvc * %%rhs) >>= unify pft >> return mvc\n| comp.gt := to_expr ``(%%lhs > %%mvc * %%rhs) >>= unify pft >> return mvc\n| comp.ge := to_expr ``(%%lhs ≥ %%mvc * %%rhs) >>= unify pft >> return mvc\nend\n\nprivate meta def reconstruct_hyp (lhs rhs : expr) (iq : ineq) (pf : expr) : tactic expr :=\nmatch iq.to_slope with\n| slope.horiz := \n do tp ← infer_type pf, --trace \"unifying tp in reconstruct_hyp1\", trace tp,\n to_expr ``( %%(iq.to_comp.to_pexpr) %%rhs 0) >>= unify tp,\n return pf\n| slope.some c :=\n do m ← guard_is_ineq lhs rhs iq pf,\n m' ← eval_expr rat m,\n if m' = c then return pf else fail \"ineq_proof.reconstruct_hyp failed\"\nend\n\nsection\nvariable (rc : Π {lhs rhs : expr} {iq : ineq}, ineq_proof lhs rhs iq → tactic expr)\ninclude rc\n\nprivate meta def reconstruct_sym \n {lhs rhs iq} (ip : ineq_proof lhs rhs iq) : tactic expr :=\nmatch iq.to_slope with\n| slope.horiz := do p ← pp (lhs, rhs), fail $ \"reconstruct_sym failed on horiz slope: \" ++ p.to_string\n| slope.some m := \n do --trace \"in reconstruct sym\", trace (lhs, rhs, m),\n symp ← rc ip, sgnp ← mk_sign_pf m, --trace \"have proof of:\", infer_type symp >>= trace,\n--trace (\"m\", m), trace (\"lhs, rhs\", lhs, rhs), trace \"sgnp\", infer_type sgnp >>= trace, trace \"symp\", trace ip, infer_type symp >>= trace,\n --mk_mapp (name_of_c_and_comp m iq.to_comp) [none, none, none, some sgnp, some symp]\n mk_app (if m < 0 then ``sym_op_neg else ``sym_op_pos) [sgnp, symp]\nend\n\n-- x ≥ 2y and x ≠ 2y implies x > 2y\nprivate meta def reconstruct_ineq_diseq {lhs rhs iq c} (ip : ineq_proof lhs rhs iq) (dp : diseq_proof lhs rhs c) : tactic expr :=\nmatch iq.to_slope with\n| slope.horiz := fail \"reconstruct_ineq_diseq needs non-horiz slope\"\n| slope.some m := \n if bnot (m=c) then\n fail \"reconstruct_ineq_diseq found non-matching slopes\"\n else if iq.strict then rc ip\n else do ipp ← rc ip, dpp ← dp.reconstruct,\n /-if iq.to_comp.is_less then\n mk_mapp ``ineq_diseq_le [none, none, none, some dpp, some ipp]\n else \n mk_mapp ``ineq_diseq_ge [none, none, none, some dpp, some ipp]-/\n mk_app ``ineq_diseq [dpp, ipp]\nend\n\nvariable (rcs : Π {e gc}, sign_proof e gc → tactic expr)\ninclude rcs\n\n-- x ≤ 0y and x ≠ 0 implies x < 0y\nprivate meta def reconstruct_ineq_sign_lhs {lhs rhs iq c} (ip : ineq_proof lhs rhs iq) (sp : sign_proof lhs c) : tactic expr :=\nif iq.strict || bnot (c = gen_comp.ne) then fail \"reconstruct_ineq_sign_lhs assumes a weak ineq and a diseq-0\" else\nmatch iq.to_slope with\n| slope.horiz := fail \"reconstruct_ineq_sign_lhs assumes a 0 slope\"\n| slope.some m :=\n if m = 0 then do\n ipp ← rc ip, spp ← rcs sp,\n-- mk_app (if iq.to_comp.is_less then ``ineq_diseq_sign_lhs_le else ``ineq_diseq_sign_lhs_ge) [spp, ipp] \n mk_app ``ineq_diseq_sign_lhs [spp, ipp] \n else fail \"reconstruct_ineq_sign_lhs assumes a 0 slope\"\nend\n\n-- this might be wrong: should we produce proofs of y < 0?\nprivate meta def reconstruct_ineq_sign_rhs {lhs rhs iq c} (ip : ineq_proof lhs rhs iq) (sp : sign_proof rhs c) : tactic expr :=\nif iq.strict || bnot (c = gen_comp.ne) then fail \"reconstruct_ineq_sign_rhs assumes a weak ineq and a diseq-0\" else\nmatch iq.to_slope with\n| slope.horiz := do ipp ← rc ip, spp ← rcs sp,\n-- mk_app (if iq.to_comp.is_less then ``ineq_diseq_sign_rhs_le else ``ineq_diseq_sign_rhs_ge) [spp, ipp]\n mk_app ``ineq_diseq_sign_rhs [spp, ipp]\n| _ := fail \"reconstruct_ineq_sign_rhs assumes a horizontal slope\"\nend\n\n\nomit rc\n\n-- x ≥ 0 implies x ≥ 0*y\nprivate meta def reconstruct_zero_comp_of_sign {lhs c} (rhs : expr) (iq : ineq) (sp : sign_proof lhs c) : tactic expr :=\nif bnot ((iq.to_comp.to_gen_comp = c) && (iq.is_zero_slope)) then fail $ \"reconstruct_zero_comp_of_sign only produces comps with zero\" ++ (to_fmt iq).to_string ++ (to_fmt iq.to_comp.to_gen_comp).to_string ++ (to_fmt c).to_string\n--else do spp ← rcs sp, mk_app (zero_mul_name_of_comp iq.to_comp) [rhs, spp]\nelse do spp ← rcs sp, mk_mapp ``op_zero_mul [none, some rhs, none, none, some spp]\n\n\nprivate meta def reconstruct_horiz_of_sign {rhs c} (lhs : expr) (iq : ineq) (sp : sign_proof rhs c) : tactic expr :=\nif bnot ((iq.to_comp.to_gen_comp = c) && (iq.is_horiz)) then fail $ \"reconstruct_horiz_of_sign failed\"\nelse rcs sp\n\nend\n\n\n/-\nprivate theorem eq_sub_of_add_eq_facs {c1 c2 e1 e2 : ℚ} (hc1 : c1 ≠ 0) (h : c1 * e1 + c2 * e2 = 0) : e1 = -(c2/c1) * e2 :=\nsorry\n\n\nprivate meta def reconstruct_of_sum_form_proof (sfpr : Π {sf}, Π (sp : sum_form_proof sf), tactic expr) : expr → expr → ℚ → Π {sf},\n Π (sp : sum_form_proof ⟨sf, spec_comp.eq⟩), tactic expr | lhs rhs c sf sp :=\nif rhs.lt lhs then \n reconstruct_of_sum_form_proof rhs lhs (1/c) sp\nelse do\n guard $ (sf.contains lhs) && (sf.contains rhs),\n let a := sf.get_coeff lhs in let b := sf.get_coeff rhs in do\n guard $ c = -(b/a),\n pf ← sfpr sp,\n nez ← mk_ne_zero_pf a,\n mk_app ``eq_sub_of_add_eq_facs [nez, pf] \n-/\n\n\nprivate meta def reconstruct_of_sum_form_proof (sfpr : Π {sf}, Π (sp : sum_form_proof sf), tactic expr) :\n expr → expr → ineq → Π {sfc}, sum_form_proof sfc → tactic expr | lhs rhs i sfc sp :=\nif lhs.lt rhs then -- flipped?\n reconstruct_of_sum_form_proof rhs lhs i.reverse sp\nelse\n (match i.to_slope with\n| slope.some m := do {\n guard $ (sfc.sf.contains lhs) && (sfc.sf.contains rhs),\n guard $ sfc.sf.keys.length = 2,\n let a := sfc.sf.get_coeff lhs in let b := sfc.sf.get_coeff rhs in do\n guard $ m = -(b/a),\n guard $ if a < 0 then sfc.c.to_comp = i.to_comp.reverse else sfc.c.to_comp = i.to_comp,\n rhs' ← to_expr ``(%%(↑(rat.reflect m) : expr) * %%rhs), -- better way to do this?\n tp ← i.to_comp.to_function lhs rhs',\n sgnp ← mk_sign_pf a,\n pf ← sfpr sp,\n --trace \"have: \", infer_type pf >>= trace, trace (\"lhs: \", lhs), trace (\"rhs: \", rhs),\n let thnm := if a < 0 then ``op_of_sum_op_zero_neg else ``op_of_sum_op_zero_pos in \n mk_app thnm [pf, sgnp]}\n --to_expr ``(sorry : %%tp)\n-- fail \"ineq_proof.reconstruct_of_sum_proof not implemented yet\"\n| slope.horiz := fail \"ineq_proof.reconstruct_of_sum_proof failed, cannot turn a sum into a horiz slope\"\nend)\n \nmeta def reconstruct_aux (rcs : Π {e gc}, sign_proof e gc → tactic expr) (sfpr : Π {sf}, Π (sp : sum_form_proof sf), tactic expr) :\n Π {lhs rhs : expr} {iq : ineq}, ineq_proof lhs rhs iq → tactic expr\n| _ _ _ (hyp lhs rhs iq e) := reconstruct_hyp lhs rhs iq e\n| _ _ _ (sym ip) := reconstruct_sym @reconstruct_aux ip\n| _ _ _ (of_ineq_proof_and_diseq ip dp) := reconstruct_ineq_diseq @reconstruct_aux ip dp\n| _ _ _ (of_ineq_proof_and_sign_lhs ip sp) := reconstruct_ineq_sign_lhs @reconstruct_aux @rcs ip sp\n| _ _ _ (of_ineq_proof_and_sign_rhs ip sp) := reconstruct_ineq_sign_rhs @reconstruct_aux @rcs ip sp\n| _ _ _ (zero_comp_of_sign_proof rhs iq sp) := reconstruct_zero_comp_of_sign @rcs rhs iq sp\n| _ _ _ (horiz_of_sign_proof lhs iq sp) := reconstruct_horiz_of_sign @rcs lhs iq sp\n| _ _ _ (of_sum_form_proof lhs rhs i sp) := reconstruct_of_sum_form_proof @sfpr lhs rhs i sp\n| _ _ _ (adhoc _ _ _ _ t) := t\n\nend ineq_proof\n\nnamespace sign_proof\n\nprivate meta def reconstruct_hyp (e : expr) (gc : gen_comp) (pf : expr) : tactic expr :=\nlet pex := match gc with\n| gen_comp.ge := ``(%%e ≥ 0)\n| gen_comp.gt := ``(%%e > 0)\n| gen_comp.le := ``(%%e ≤ 0)\n| gen_comp.lt := ``(%%e < 0)\n| gen_comp.eq := ``(%%e = 0)\n| gen_comp.ne := ``(%%e ≠ 0)\nend in do tp ← infer_type pf, to_expr pex >>= unify tp >> return pf\n\nprivate meta def reconstruct_scaled_hyp (e : expr) (gc : gen_comp) (pf : expr) (q : ℚ) : tactic expr :=\ndo sp ← mk_sign_pf q,\n if q > 0 then\n mk_mapp ``op_zero_of_mul_op_zero_of_pos [none, none, none, none, pf, sp]\n else\n mk_mapp ``op_zero_of_mul_op_zero_of_neg [none, none, none, none, pf, sp]\n\nsection\nparameter rc : Π {e c}, sign_proof e c → tactic expr\nparameter sfpr : Π {sf}, Π (sp : sum_form_proof sf), tactic expr\nprivate meta def rci := @ineq_proof.reconstruct_aux @rc @sfpr\nprivate meta def rce := @eq_proof.reconstruct_aux @rci @sfpr\n\n-- x ≤ 0*y to x ≤ 0\nprivate meta def reconstruct_ineq_lhs (c : gen_comp) {lhs rhs iqp} (ip : ineq_proof lhs rhs iqp) : tactic expr :=\nif bnot ((iqp.to_comp.to_gen_comp = c) && (iqp.is_zero_slope)) then fail \"reconstruct_ineq_lhs must take a comparison with 0\"\n--else do ipp ← rci ip, mk_app (zero_mul'_name_of_comp iqp.to_comp) [ipp]\nelse do ipp ← rci ip, mk_app ``op_zero_mul' [ipp]\n\nprivate meta def reconstruct_ineq_rhs (c : gen_comp) {lhs rhs iqp} (ip : ineq_proof lhs rhs iqp) : tactic expr :=\nif bnot ((iqp.to_comp.to_gen_comp = c) && (iqp.is_horiz)) then fail \"reconstruct_ineq_rhs must take a horiz comp\"\nelse rci ip\n\nprivate meta def reconstruct_eq_of_two_eqs_lhs {lhs rhs eqp1 eqp2} (ep1 : eq_proof lhs rhs eqp1) (ep2 : eq_proof lhs rhs eqp2) : tactic expr :=\nif h : eqp1 = eqp2 then fail \"reconstruct_eq_of_two_eqs lhs cannot infer anything from the same equality twice\"\nelse do epp1 ← rce ep1, epp2 ← rce ep2, nep ← mk_ne_pf eqp1 eqp2,\n mk_app ``eq_zero_of_two_eqs_lhs [epp1, epp2, nep]\n\nprivate meta def reconstruct_eq_of_two_eqs_rhs {lhs rhs eqp1 eqp2} (ep1 : eq_proof lhs rhs eqp1) (ep2 : eq_proof lhs rhs eqp2) : tactic expr :=\nif h : eqp1 = eqp2 then fail \"reconstruct_eq_of_two_eqs lhs cannot infer anything from the same equality twice\"\nelse do epp1 ← rce ep1, epp2 ← rce ep2, nep ← mk_ne_pf eqp1 eqp2,\n mk_app ``eq_zero_of_two_eqs_rhs [epp1, epp2, nep]\n\nprivate meta def reconstruct_diseq_of_diseq_zero {lhs rhs} (dp : diseq_proof lhs rhs 0) : tactic expr :=\ndo dpp ← dp.reconstruct,\n mk_app ``ne_zero_of_ne_mul_zero [dpp]\n\nprivate meta def reconstruct_eq_of_eq_zero {lhs rhs} (ep : eq_proof lhs rhs 0) : tactic expr :=\ndo epp ← rce ep,\n mk_app ``eq_zero_of_eq_mul_zero [epp]\n\n/-\nprivate meta def reconstruct_ineqs (rct : contrad → tactic expr) {lhs rhs} (ii : ineq_info lhs rhs) (id : ineq_data lhs rhs) : tactic expr := do trace \"ineqs!!\",\nmatch ii with\n| ineq_info.no_comps := fail \"reconstruct_ineqs cannot find a contradiction with no known comps\"\n| ineq_info.one_comp id2 := reconstruct_two_ineq_data rct id id2\n| ineq_info.equal ed := reconstruct_eq_ineq ed id\n| ineq_info.two_comps id1 id2 := \n let sfid := sum_form_comp_data.of_ineq_data id,\n sfid1 := sum_form_comp_data.of_ineq_data id1,\n sfid2 := sum_form_comp_data.of_ineq_data id2 in\n match find_contrad_in_sfcd_list [sfid, sfid1, sfid2] with\n | some ctr := rct ctr\n | option.none := fail \"reconstruct_ineqs failed to find contr\"\n end\nend\n-/\n\n\nprivate theorem {u} ge_of_not_lt {α : Type u} [linear_order α] {a b : α} (h : ¬ a < b) : (a ≥ b) := le_of_not_gt h\n\nprivate theorem {u} gt_of_not_le {α : Type u} [linear_order α] {a b : α} (h : ¬ a ≤ b) : (a > b) := lt_of_not_ge h\n\n\nprivate meta def neg_op_lemma_name : comp → name\n| comp.lt := ``lt_of_not_ge\n| comp.le := ``le_of_not_gt\n| comp.ge := ``ge_of_not_lt\n| comp.gt := ``gt_of_not_le\n\nmeta def reconstruct_ineq_of_eq_and_ineq_aux\n-- (sfpr : Π {sf : sum_form_comp}, Π (sp : sum_form_proof sf), tactic.{0} (expr tt))\n {lhs rhs iq c} (c' : gen_comp) (ep : eq_proof lhs rhs c) (ip : ineq_proof lhs rhs iq) (pvt : expr) : tactic expr :=\ndo negt ← c'.to_comp.to_function pvt `(0 : ℚ),\n (_, notpf) ← solve_aux negt (do\n applyc $ neg_op_lemma_name c'.to_comp,\n hypv ← intro `h,\n let sfid := sum_form_comp_data.of_ineq_data ⟨_, ip⟩ in\n let sfed := sum_form_comp_data.of_eq_data ⟨_, ep⟩ in\n let sfsd := sum_form_comp_data.of_sign_data ⟨c'.negate, hyp pvt _ hypv⟩ in\n match find_contrad_sfcd_in_sfcd_list [sfid, sfed, sfsd] with\n | none := fail \"reconstruct_ineq_of_eq_and_ineq failed to find proof\"\n | some ⟨_, sfp, _⟩ := do ctrp ← sfpr sfp, fp ← mk_mapp ``lt_irrefl [none, none, none, ctrp], apply fp\n--applyc ``lt_irrefl, trace \"apply3\", apply ctrp, trace \"apply4\"\n end),\n return notpf\n\n\n\n--#check @reconstruct_ineq_of_eq_and_ineq_aux\n-- these are the hard cases. Is this the right place to handle them?\nprivate meta def reconstruct_ineq_of_eq_and_ineq_lhs {lhs rhs iq c} (c' : gen_comp) (ep : eq_proof lhs rhs c) (ip : ineq_proof lhs rhs iq) : tactic expr :=\nreconstruct_ineq_of_eq_and_ineq_aux c' ep ip lhs\n--fail \"reconstruct_ineq_of_eq_and_ineq not implemented\"\n\nprivate meta def reconstruct_ineq_of_eq_and_ineq_rhs {lhs rhs iq c} (c' : gen_comp) (ep : eq_proof lhs rhs c) (ip : ineq_proof lhs rhs iq) : tactic expr :=\nreconstruct_ineq_of_eq_and_ineq_aux c' ep ip rhs\n/-do negt ← c'.to_comp.to_function rhs `(0 : ℚ),\n (_, notpf) ← solve_aux negt (do\n applyc $ neg_op_lemma_name c'.to_comp,\n hypv ← intro `h,\n let sfid := sum_form_comp_data.of_ineq_data ⟨_, ip⟩ in\n let sfed := sum_form_comp_data.of_eq_data ⟨_, ep⟩ in\n let sfsd := sum_form_comp_data.of_sign_data ⟨c', hyp rhs _ hypv⟩ in\n match find_contrad_sfcd_in_sfcd_list [sfid, sfed, sfsd] with\n | none := fail \"reconstruct_ineq_of_eq_and_ineq_rhs failed to find proof\"\n | some ⟨_, sfp, _⟩ := do ctrp ← sfpr sfp, applyc ``lt_irrefl, apply ctrp\n end),\n return notpf-/\n-- fail \"reconstruct_ineq_of_eq_and_ineq not implemented\"\n\n-- TODO\nprivate meta def reconstruct_ineq_of_ineq_and_eq_zero_rhs {lhs rhs iq} (c : gen_comp) (ip : ineq_proof lhs rhs iq) (sp : sign_proof lhs gen_comp.eq) : tactic expr :=\nfail \"reconstruct_ineq_of_ineq_and_eq_zero not implemented\"\n \nprivate meta def reconstruct_diseq_of_strict_ineq {e c} (sp : sign_proof e c) : tactic expr :=\nif c.is_strict then do\n spp ← rc sp,\n mk_app ``ne_of_strict_op [spp]\nelse fail \"reconstruct_diseq_of_strict_ineq failed, comp is not strict\"\n\nend\n\n\n-- TODO\nprivate meta def reconstruct_of_sum_form_proof (sfpr : Π {sf}, Π (sp : sum_form_proof sf), tactic expr) (e : expr) (c : gen_comp) {sfc}\n (sp : sum_form_proof sfc) : tactic expr :=\ndo \n pf' ← sfpr sp,\n --trace \"in sign_proof.reconstruct_of_sum_form_proof\",\n --infer_type e >>= trace,\n --trace c,\n let coeff := sfc.sf.get_coeff e,\n if coeff = 0 then fail \"sign_proof.reconstruct_of_sum_form_proof failed, zero coeff\" else do\n coeff_sign_pr ← mk_sign_pf coeff,\n-- if coeff < 0 then\n mk_mapp (if coeff < 0 then ``rev_op_zero_of_neg_mul_op_zero else ``op_zero_of_pos_mul_op_zero) [none, none, none, none, coeff_sign_pr, pf']\n -- else if coeff > 0 then\n -- mk_mapp ``op_zero_of_pos_mul_op_zero [none, none, none, none, coeff_sign_]\n -- fail \"sign_proof.reconstruct_of_sum_form_proof failed, not implemented yet\"\n\nmeta def reconstruct_eq_of_le_of_ge (rct : Π {e c}, sign_proof e c → tactic expr) {e} (lep : sign_proof e gen_comp.le) (gep : sign_proof e gen_comp.ge) : tactic expr :=\ndo lep' ← rct lep, gep' ← rct gep,\n mk_app ``le_antisymm' [lep', gep']\n\nmeta def reconstruct_aux (sfpr : Π {sf}, Π (sp : sum_form_proof sf), tactic expr) : Π {e c}, sign_proof e c → tactic expr\n| .(_) .(_) (hyp e c pf) := reconstruct_hyp e c pf\n| .(_) .(_) (scaled_hyp e c pf q) := reconstruct_scaled_hyp e c pf q\n| .(_) .(_) (@ineq_lhs c _ _ _ ip) := reconstruct_ineq_lhs @reconstruct_aux @sfpr c ip\n| .(_) .(_) (@ineq_rhs c _ _ _ ip) := reconstruct_ineq_rhs @reconstruct_aux @sfpr c ip\n| .(_) .(_) (@eq_of_two_eqs_lhs _ _ _ _ ep1 ep2) := reconstruct_eq_of_two_eqs_lhs @reconstruct_aux @sfpr ep1 ep2\n| .(_) .(_) (@eq_of_two_eqs_rhs _ _ _ _ ep1 ep2) := reconstruct_eq_of_two_eqs_rhs @reconstruct_aux @sfpr ep1 ep2\n| .(_) .(_) (@diseq_of_diseq_zero _ _ dp) := reconstruct_diseq_of_diseq_zero dp\n| .(_) .(_) (@eq_of_eq_zero _ _ ep) := reconstruct_eq_of_eq_zero @reconstruct_aux @sfpr ep\n| .(_) .(_) (eq_of_le_of_ge lep gep) := reconstruct_eq_of_le_of_ge @reconstruct_aux lep gep\n| .(_) .(_) (@ineq_of_eq_and_ineq_lhs _ _ _ _ c' ep ip) := reconstruct_ineq_of_eq_and_ineq_lhs @sfpr c' ep ip\n| .(_) .(_) (@ineq_of_eq_and_ineq_rhs _ _ _ _ c' ep ip) := reconstruct_ineq_of_eq_and_ineq_rhs @sfpr c' ep ip\n| .(_) .(_) (@ineq_of_ineq_and_eq_zero_rhs _ _ _ c ip sp) := reconstruct_ineq_of_ineq_and_eq_zero_rhs c ip sp\n| .(_) .(_) (@diseq_of_strict_ineq _ _ sp) := reconstruct_diseq_of_strict_ineq @reconstruct_aux sp\n| .(_) .(_) (@of_sum_form_proof e c _ sp) := reconstruct_of_sum_form_proof @sfpr e c sp\n| .(_) .(_) (adhoc _ _ _ t) := t\n\nend sign_proof\n\n\nnamespace sum_form_proof\nsection \nparameter sfrc : Π {sfc}, sum_form_proof sfc → tactic expr\nprivate meta def sprc := @sign_proof.reconstruct_aux @sfrc\nprivate meta def iprc := @ineq_proof.reconstruct_aux @sprc @sfrc\nprivate meta def eprc := @eq_proof.reconstruct_aux @iprc @sfrc\n\n\n-- assumes lhs < rhs\nprivate meta def reconstruct_of_ineq_proof : \n Π {lhs rhs iq}, ineq_proof lhs rhs iq → tactic expr | lhs rhs iq ip :=\nif expr.lt lhs rhs then reconstruct_of_ineq_proof ip.sym else \n--trace \"ipp is:\" >> iprc ip >>= infer_type >>= trace >> trace \"const is:\" >> infer_type ↑`(@polya.mul_lt_of_lt) >>= trace >>\nmatch iq.to_slope with\n| slope.horiz := \n do ipp ← iprc ip, \n tactic.mk_mapp (sum_form_name_of_comp_single iq.to_comp) [none, none, ipp]\n| slope.some m := \n do ipp ← iprc ip, \n--trace (\"ipp\", ip, ipp), infer_type ipp >>= trace, trace (\"comp\", iq.to_comp), trace (\"iq\", iq),\n if m = 0 then\n tactic.mk_mapp (sum_form_name_of_comp_single iq.to_comp) [none, none, ipp]\n else\n tactic.mk_mapp (sum_form_name_of_comp iq.to_comp) [none, none, none, ipp]\n-- tactic.mk_mapp ((if m = 0 then sum_form_name_of_comp_single else sum_form_name_of_comp) iq.to_comp) [none, none, ipp]\nend\n--include sfrc\n\n\nprivate meta def reconstruct_of_eq_proof : \n Π {lhs rhs c}, eq_proof lhs rhs c → tactic expr | lhs rhs c ep :=\nif expr.lt lhs rhs then reconstruct_of_eq_proof ep.sym else\ndo ipp ← eprc ep,\n mk_app ``sub_eq_zero_of_eq [ipp]\n--fail \"sum_form_proof.reconstruct_of_eq_proof not implemented yet\"\n\nprivate meta def reconstruct_of_sign_proof :\n Π {e c}, sign_proof e c → tactic expr | e c sp :=\nif c.is_less then sprc sp \nelse do spp ← sprc sp,\n --trace \"spp type is\", infer_type spp >>= trace,\n mk_mapp ``rev_op_zero_of_op [none, none, none, some spp]\n--fail \"sum_form_proof.reconstruct_of_sign_proof not implemented yet\"\n\n\n\n-- sum_form_proof ⟨lhs.add_factor rhs m, spec_comp.strongest c1 c2⟩ \n-- wait for algebraic normalizer?\n-- TODO\nprivate theorem reconstruct_of_add_factor_aux (P : Prop) {Q R : Prop} (h : Q) (h2 : R) : P := sorry\n\nprivate meta def reconstruct_of_add_factor_same_comp {lhs rhs c1 c2} (m : ℚ) \n (sfpl : sum_form_proof ⟨lhs, c1⟩) (sfpr : sum_form_proof ⟨rhs, c2⟩) : tactic expr :=\nlet sum := lhs + rhs.scale m in\ndo tp ← sum_form.to_expr sum,\n tp' ← (spec_comp.strongest c1 c2).to_comp.to_function tp `(0 : ℚ),\n pf1 ← sfrc sfpl, pf2 ← sfrc sfpr,\n mk_mapp ``reconstruct_of_add_factor_aux [some tp', none, none, some pf1, some pf2] --to_expr `(sorry : %%tp) \n--fail \"reconstruct_of_add_factor_same_comp failed, not implemented yet\"\n\nprivate theorem reconstruct_of_add_eq_factor_op_comp_aux (P : Prop) {Q R : Prop} (h : Q) (h2 : R) : P := sorry\n\n/-\nm is negative\n-/\nprivate meta def reconstruct_of_add_eq_factor_op_comp {lhs rhs c1} (m : ℚ) \n (sfpl : sum_form_proof ⟨lhs, c1⟩) (sfpr : sum_form_proof ⟨rhs, spec_comp.eq⟩) : tactic expr :=\nlet sum := lhs + rhs.scale m in\ndo tp ← sum_form.to_expr sum,\n tp' ← c1.to_comp.to_function tp `(0 : ℚ),\n pf1 ← sfrc sfpl, pf2 ← sfrc sfpr,\n mk_mapp ``reconstruct_of_add_eq_factor_op_comp_aux [some tp', none, none, some pf1, some pf2]\n--fail \"reconstruct_of_add_eq_factor_op_comp not implemented yet\"\n\n\nprivate theorem reconstruct_of_scale_aux (P : Prop) {Q : Prop} (h : Q) : P := sorry\n\nprivate meta def reconstruct_of_scale (rct : Π {sfc}, sum_form_proof sfc → tactic expr) \n {sfc} (m : ℚ) (sfp : sum_form_proof sfc) : tactic expr :=\ndo tp ← sum_form.to_expr (sfc.sf.scale m),\n tp' ← sfc.c.to_comp.to_function tp `(0 : ℚ),\n pf ← rct sfp,\n mk_mapp ``reconstruct_of_scale_aux [some tp', none, some pf] -- to_expr `(sorry : %%tp')\n \nend \n\n-- TODO (alg norm)\ntheorem reconstruct_of_expr_def_aux (P : Prop) : P := sorry\n\nprivate meta def reconstruct_of_expr_def (e : expr) (sf : sum_form) : tactic expr :=\ndo tp ← sum_form.to_expr sf,\n tp' ← to_expr ``(%%tp = 0),\n-- (_, pf) ← solve_aux tp' (simp >> done),\n mk_app ``reconstruct_of_expr_def_aux [tp']\n-- instantiate_mvars pf\n--fail \"reconstruct_of_expr_def failed, not implemented yet\"\n\nmeta def reconstruct : Π {sfc}, sum_form_proof sfc → tactic expr\n| _ (of_ineq_proof ip) := reconstruct_of_ineq_proof @reconstruct ip\n| _ (of_eq_proof ep) := reconstruct_of_eq_proof @reconstruct ep\n| _ (of_sign_proof sp) := reconstruct_of_sign_proof @reconstruct sp\n| _ (of_add_factor_same_comp m sfpl sfpr) := \n reconstruct_of_add_factor_same_comp @reconstruct m sfpl sfpr \n| _ (of_add_eq_factor_op_comp m sfpl sfpr) :=\n reconstruct_of_add_eq_factor_op_comp @reconstruct m sfpl sfpr\n| _ (of_scale m sfp) := reconstruct_of_scale @reconstruct m sfp\n| _ (of_expr_def e sf) := reconstruct_of_expr_def e sf\n| _ (fake sd) := fail \"cannot reconstruct a fake proof\"\n\n\n\n\n/-meta def reconstruct : Π {sfc}, sum_form_proof sfc → tactic expr | sfc sfp :=\nif sfc.sf.keys.length = 0 then do\n ex ← sfc.c.to_comp.to_function ```(0 : ℚ) ```(0 : ℚ),\n to_expr `(sorry : %%ex) else\nlet sfcd : sum_form_comp_data := ⟨_, sfp, mk_rb_set⟩ in\nmatch sfcd.to_ineq_data with\n| option.some ⟨lhs, rhs, id⟩ := do ex ← ineq_data.to_expr id, to_expr `(sorry : %%ex)\n| none := trace sfc >> fail \"fake sum_form_proof.reconstruct failed, no ineq data\"\nend-/\n\nend sum_form_proof\n\n\nmeta def sign_proof.reconstruct := @sign_proof.reconstruct_aux @sum_form_proof.reconstruct\nmeta def ineq_proof.reconstruct := @ineq_proof.reconstruct_aux @sign_proof.reconstruct @sum_form_proof.reconstruct\nmeta def eq_proof.reconstruct := @eq_proof.reconstruct_aux @ineq_proof.reconstruct @sum_form_proof.reconstruct\n\n\nmeta def ineq_data.to_expr {lhs rhs} (id : ineq_data lhs rhs) : tactic expr :=\nmatch id.inq.to_slope with\n| slope.horiz := id.inq.to_comp.to_function rhs `(0 : ℚ)\n| slope.some m := if m = 0 then id.inq.to_comp.to_function lhs `(0 : ℚ)\n else do rhs' ← to_expr ``(%%(m.reflect : expr)*%%rhs), id.inq.to_comp.to_function lhs rhs'\nend\n\nnamespace contrad\n\nprivate meta def reconstruct_eq_diseq {lhs rhs} (ed : eq_data lhs rhs) (dd : diseq_data lhs rhs) : tactic expr :=\nif bnot (ed.c = dd.c) then fail \"reconstruct_eq_diseq failed: given different coefficients\"\nelse do ddp ← dd.prf.reconstruct, edp ← ed.prf.reconstruct, return $ ddp.app edp\n\nprivate meta def reconstruct_two_ineq_data {lhs rhs} (rct : contrad → tactic expr) (id1 id2 : ineq_data lhs rhs) : tactic expr :=\nlet sfid1 := sum_form_comp_data.of_ineq_data id1,\n sfid2 := sum_form_comp_data.of_ineq_data id2 in\nmatch find_contrad_in_sfcd_list [sfid1, sfid2] with\n| some ctr := rct ctr\n| option.none := fail \"reconstruct_two_ineq_data failed to find contr\"\nend\n\nprivate meta def reconstruct_eq_ineq {lhs rhs} (ed : eq_data lhs rhs) (id : ineq_data lhs rhs) : tactic expr :=\nfail \"reconstruct_eq_ineq not implemented\"\n\n-- TODO: this is the hard part. Should this be refactored into smaller pieces?\nprivate meta def reconstruct_ineqs (rct : contrad → tactic expr) {lhs rhs} (ii : ineq_info lhs rhs) (id : ineq_data lhs rhs) : tactic expr := --do trace \"ineqs!!\",\nmatch ii with\n| ineq_info.no_comps := fail \"reconstruct_ineqs cannot find a contradiction with no known comps\"\n| ineq_info.one_comp id2 := reconstruct_two_ineq_data rct id id2\n| ineq_info.equal ed := reconstruct_eq_ineq ed id\n| ineq_info.two_comps id1 id2 := \n let sfid := sum_form_comp_data.of_ineq_data id,\n sfid1 := sum_form_comp_data.of_ineq_data id1,\n sfid2 := sum_form_comp_data.of_ineq_data id2 in\n match find_contrad_in_sfcd_list [sfid, sfid1, sfid2] with\n | some ctr := rct ctr\n | option.none := fail \"reconstruct_ineqs failed to find contr\"\n end\nend\n\nprivate meta def reconstruct_sign_ne_eq {e} (nepr : sign_proof e gen_comp.ne) (eqpr : sign_proof e gen_comp.eq) : tactic expr :=\ndo neprp ← nepr.reconstruct, eqprp ← eqpr.reconstruct,\n return $ neprp.app eqprp\n\nprivate meta def reconstruct_sign_le_gt {e} (lepr : sign_proof e gen_comp.le) (gtpr : sign_proof e gen_comp.gt) : tactic expr :=\ndo leprp ← lepr.reconstruct, gtprp ← gtpr.reconstruct,\n mk_app ``le_gt_contr [leprp, gtprp]\n\nprivate meta def reconstruct_sign_ge_lt {e} (gepr : sign_proof e gen_comp.ge) (ltpr : sign_proof e gen_comp.lt) : tactic expr :=\ndo geprp ← gepr.reconstruct, ltprp ← ltpr.reconstruct,\n mk_app ``ge_lt_contr [geprp, ltprp]\n\nprivate meta def reconstruct_sign_gt_lt {e} (gtpr : sign_proof e gen_comp.gt) (ltpr : sign_proof e gen_comp.lt) : tactic expr :=\ndo gtprp ← gtpr.reconstruct, ltprp ← ltpr.reconstruct,\n mk_app ``gt_lt_contr [gtprp, ltprp]\n\n\nprivate meta def reconstruct_sign {e} : sign_data e → sign_data e → tactic expr\n| ⟨gen_comp.ne, prf1⟩ ⟨gen_comp.eq, prf2⟩ := reconstruct_sign_ne_eq prf1 prf2\n| ⟨gen_comp.eq, prf1⟩ ⟨gen_comp.ne, prf2⟩ := reconstruct_sign_ne_eq prf2 prf1\n| ⟨gen_comp.le, prf1⟩ ⟨gen_comp.gt, prf2⟩ := reconstruct_sign_le_gt prf1 prf2\n| ⟨gen_comp.gt, prf1⟩ ⟨gen_comp.le, prf2⟩ := reconstruct_sign_le_gt prf2 prf1\n| ⟨gen_comp.lt, prf1⟩ ⟨gen_comp.ge, prf2⟩ := reconstruct_sign_ge_lt prf2 prf1\n| ⟨gen_comp.ge, prf1⟩ ⟨gen_comp.lt, prf2⟩ := reconstruct_sign_ge_lt prf1 prf2\n| ⟨gen_comp.gt, prf1⟩ ⟨gen_comp.lt, prf2⟩ := reconstruct_sign_gt_lt prf1 prf2\n| ⟨gen_comp.lt, prf1⟩ ⟨gen_comp.gt, prf2⟩ := reconstruct_sign_gt_lt prf2 prf1\n| s1 s2 := trace e >> trace s1.c >> trace s2.c >> fail \"reconstruct_sign failed: given non-opposite comps\"\n\nprivate meta def reconstruct_strict_ineq_self {e} (id : ineq_data e e) : tactic expr := \nmatch id.inq.to_comp, id.inq.to_slope with\n| comp.gt, slope.some m := \n if bnot (m = 1) then fail \"reconstruct_strict_ineq_self failed: given non-one slope\"\n else do idp ← id.prf.reconstruct,\n mk_app ``gt_self_contr [idp]\n| comp.lt, slope.some m := \n if bnot (m = 1) then fail \"reconstruct_strict_ineq_self failed: given non-one slope\"\n else do idp ← id.prf.reconstruct,\n mk_app ``lt_self_contr [idp]\n| _, _ := fail \"reconstruct_strict_ineq_self failed: given non-strict comp or non-one slope\"\nend\n\nmeta def reconstruct_sum_form {sfc} (sfp : sum_form_proof sfc) : tactic expr :=\nif sfc.is_contr then do\n zltz ← sfp.reconstruct,\n mk_mapp ``lt_irrefl [option.none, option.none, option.none, some zltz]\nelse fail \"reconstruct_sum_form requires proof of 0 < 0\"\n\nmeta def reconstruct : contrad → tactic expr\n| none := fail \"cannot reconstruct contr: no contradiction is known\"\n| (@eq_diseq lhs rhs ed dd) := reconstruct_eq_diseq ed dd\n| (@ineqs lhs rhs ii id) := reconstruct_ineqs reconstruct ii id\n| (@sign e sd1 sd2) := reconstruct_sign sd1 sd2\n| (@strict_ineq_self e id) := reconstruct_strict_ineq_self id\n| (@sum_form _ sfp) := reconstruct_sum_form sfp\n\nend contrad\n\nnamespace prod_form_proof\n\n/-private meta def mk_prod_ne_zero_prf_aux : expr → list (Σ e : expr, sign_proof e gen_comp.ne) → tactic expr\n| e [] := return e\n| e (⟨e', sp⟩::t) := do ene ← sp.reconstruct, pf ← mk_app ``mul_ne_zero [e, ene], mk_prod_ne_zero_prf_aux pf t\n\nprivate meta def mk_prod_ne_zero_prf (c : ℚ) : list (Σ e : expr, sign_proof e gen_comp.ne) → tactic expr \n| [] := if c = 0 then fail \"mk_prod_ne_zero_prf failed, c = 0\" else mk_app ``fake_ne_zero_pf [`(c)]\n| (⟨e, sp⟩::t) :=\n if c = 0 then fail \"mk_prod_ne_zero_prf failed, c = 0\" else\n do cprf ← mk_app ``fake_ne_zero_pf [`(c)],\n hpf ← sp.reconstruct,\n prodprf ← mk_prod_ne_zero_prf_aux hpf t,\n mk_app ``mul_ne_zero [hpf, prodprf]\n-/\n/-#check spec_comp_and_flipped_of_comp\n-- not finished: need to orient c\nprivate meta def reconstruct_of_ineq_proof_pos_lhs {lhs rhs iq} (id : ineq_proof lhs rhs iq) \n (sp : sign_proof lhs gen_comp.gt) (nzprs : hash_map expr (λ e, sign_proof e gen_comp.ne)) : tactic expr :=\nmatch (spec_comp_and_flipped_of_comp iq.to_comp), iq.to_slope with\n| _, slope.horiz := fail \"reconstruct_of_ineq_proof_pos_lhs failed, cannot make a prod_form with 0 slope\"\n| (c, flipped), slope.some m := \n if m = 0 then fail \"reconstruct_of_ineq_proof_pos_lhs failed, cannot make a prod_form with 0 slope\"\n else do -- lhs c m*rhs --> 1 c m*(lhs⁻¹*rhs)\n idp ← id.reconstruct,\n spp ← sp.reconstruct,\n opp ← mk_app ``one_op_inv_mul_of_op_of_pos [idp, spp], -- 1 r lhs⁻¹*rhs\n if bnot flipped then \n return opp\n else do\n mprf ← mk_sign_pf m,\n failed\nend-/\n \n\nprivate meta def reconstruct_of_ineq_proof_aux {lhs rhs iq c1 c2} (id : ineq_proof lhs rhs iq) \n (spl : sign_proof lhs c1) (spr : sign_proof rhs c2) (fail_cond : ℚ → bool) \n (unflipped_name flipped_name : name) --flipped_lt_name flipped_le_name : name) \n : tactic expr :=\nmatch (spec_comp_and_flipped_of_comp iq.to_comp), iq.to_slope with\n| _, slope.horiz := fail \"reconstruct_of_ineq_proof_pos_pos failed, cannot make a prod_form with 0 slope\"\n| (c, flipped), slope.some m := --trace \"okay, roipa\" >> trace flipped >> trace iq >>\n if fail_cond m then fail \"reconstruct_of_ineq_proof_aux failed check\" \n else do\n idp ← id.reconstruct, --trace \"idp_type:\", infer_type idp >>= trace,\n splp ← spl.reconstruct, --trace \"splp_type:\", infer_type splp >>= trace, trace \"c1 is:\", trace c1, trace spl,\n opp ← mk_app unflipped_name [idp, splp],\n --trace \"opp\", infer_type opp >>= trace,\n if bnot flipped then return opp\n else do\n msgn ← mk_sign_pf m,\n sprp ← spr.reconstruct,\n trace \"HERE\", infer_type opp >>= trace, infer_type splp >>= trace, infer_type sprp >>= trace, infer_type msgn >>= trace, trace unflipped_name, trace iq,\n mk_app flipped_name-- (if c=spec_comp.lt then flipped_lt_name else flipped_le_name) \n [opp, splp, sprp, msgn] \nend\n\n\n\nprivate meta def reconstruct_of_ineq_proof_pos_pos {lhs rhs iq} (id : ineq_proof lhs rhs iq) \n (spl : sign_proof lhs gen_comp.gt) (spr : sign_proof rhs gen_comp.gt) : tactic expr := \nreconstruct_of_ineq_proof_aux id spl spr (λ m, m ≤ 0)\n ``one_op_inv_mul_of_op_of_pos ``one_op_inv_mul_of_lt_of_pos_pos_flipped' -- ``one_le_inv_mul_of_le_of_pos_pos_flipped\n/-match (spec_comp_and_flipped_of_comp iq.to_comp), iq.to_slope with\n| _, slope.horiz := fail \"reconstruct_of_ineq_proof_pos_pos failed, cannot make a prod_form with 0 slope\"\n| (c, flipped), slope.some m := \n if m ≤ 0 then fail \"reconstruct_of_ineq_proof_pos_pos failed, m ≤ 0\"\n else do\n idp ← id.reconstruct,\n splp ← spl.reconstruct,\n opp ← mk_app ``one_op_inv_mul_of_op_of_pos [idp, splp],\n if bnot flipped then return opp\n else do\n msgn ← mk_sign_pf m,\n sprp ← spr.reconstruct,\n mk_app (if c=spec_comp.lt then ``one_lt_inv_mul_of_lt_of_pos_flipped \n else ``one_le_inv_mul_of_le_of_pos_flipped) \n [opp, splp, sprp, msgn]\nend-/ \n\n\n\nprivate meta def reconstruct_of_ineq_proof_pos_neg {lhs rhs iq} (id : ineq_proof lhs rhs iq) \n (spl : sign_proof lhs gen_comp.gt) (spr : sign_proof rhs gen_comp.lt) : tactic expr := \nreconstruct_of_ineq_proof_aux id spl spr (λ m, m ≥ 0)\n ``one_op_inv_mul_of_op_of_pos ``one_op_inv_mul_of_lt_of_pos_neg_flipped -- ``one_le_inv_mul_of_le_of_pos_neg_flipped\n\n\n\nprivate meta def reconstruct_of_ineq_proof_neg_pos {lhs rhs iq} (id : ineq_proof lhs rhs iq) \n (spl : sign_proof lhs gen_comp.lt) (spr : sign_proof rhs gen_comp.gt) : tactic expr := \nreconstruct_of_ineq_proof_aux id spl spr (λ m, m ≥ 0)\n ``one_op_inv_mul_of_op_of_neg ``one_op_inv_mul_of_lt_of_neg_pos_flipped -- ``one_le_inv_mul_of_le_of_neg_flipped\n\n\nprivate meta def reconstruct_of_ineq_proof_neg_neg {lhs rhs iq} (id : ineq_proof lhs rhs iq) \n (spl : sign_proof lhs gen_comp.lt) (spr : sign_proof rhs gen_comp.lt) : tactic expr := \nreconstruct_of_ineq_proof_aux id spl spr (λ m, m ≤ 0)\n ``one_op_inv_mul_of_op_of_neg ``one_op_inv_mul_of_lt_of_neg_neg_flipped\n\n/-\npos_neg\ncmatch (spec_comp_and_flipped_of_comp iq.to_comp), iq.to_slope with\n| _, slope.horiz := fail \"reconstruct_of_ineq_proof_pos_pos failed, cannot make a prod_form with 0 slope\"\n| (c, flipped), slope.some m := \n if m ≥ 0 then fail \"reconstruct_of_ineq_proof_pos_neg failed, m ≥ 0\"\n else do\n idp ← id.reconstruct,\n splp ← spl.reconstruct,\n opp ← mk_app ``one_op_inv_mul_of_op_of_pos [idp, splp],\n if bnot flipped then return opp\n else do\n msgn ← mk_sign_pf m,\n sprp ← spr.reconstruct,\n mk_app (if c=spec_comp.lt then ``one_lt_inv_mul_of_lt_of_pos_flipped \n else ``one_le_inv_mul_of_le_of_pos_flipped) \n [opp, splp, sprp, msgn]\nend -/\n\nprivate meta def reconstruct_of_ineq_proof {lhs rhs iq} (id : ineq_proof lhs rhs iq) :\n Π {cl cr}, sign_proof lhs cl → sign_proof rhs cr → tactic expr\n| gen_comp.gt gen_comp.gt spl spr := reconstruct_of_ineq_proof_pos_pos id spl spr\n| gen_comp.gt gen_comp.lt spl spr := reconstruct_of_ineq_proof_pos_neg id spl spr\n| gen_comp.lt gen_comp.gt spl spr := reconstruct_of_ineq_proof_neg_pos id spl spr\n| gen_comp.lt gen_comp.lt spl spr := reconstruct_of_ineq_proof_neg_neg id spl spr\n| _ _ _ _ := fail \"reconstruct_of_ineq_proof failed, need to know signs of components\"\n\n/-\n-- TODO\nprivate meta def reconstruct_of_ineq_proof_neg_lhs {lhs rhs iq} (id : ineq_proof lhs rhs iq) \n (sp : sign_proof lhs gen_comp.lt) (nzprs : hash_map expr (λ e, sign_proof e gen_comp.ne)) : tactic expr :=\nmatch iq.to_slope with\n| slope.horiz := fail \"reconstruct_of_ineq_proof_neg_lhs failed, cannot make a prod_form with 0 slope\"\n| slope.some m := \n if m = 0 then fail \"reconstruct_of_ineq_proof_pos_lhs failed, cannot make a prod_form with 0 slope\"\n else\n failed\nend-/\n\nprivate meta def reconstruct_of_eq_proof {lhs rhs c} (id : eq_proof lhs rhs c) \n (lhsne : sign_proof lhs gen_comp.ne) : tactic expr :=\nif c = 0 then fail \"reconstruct_of_eq_proof failed, cannot make a prod_form with 0 slope\"\nelse do\n lhsnep ← lhsne.reconstruct,\n idpf ← id.reconstruct,\n mk_app ``one_eq_div_of_eq [idpf, lhsnep]\n\ntheorem reconstruct_of_expr_def_aux (P : Prop) : P := sorry\n\n/-\n\n-- TODO\n\nprivate meta def reconstruct_of_expr_def (e : expr) (sf : sum_form) : tactic expr :=\ndo tp ← sum_form.to_expr sf,\n tp' ← to_expr ``(%%tp = 0),\n-- (_, pf) ← solve_aux tp' (simp >> done),\n mk_app ``reconstruct_of_expr_def_aux [tp']\n-- instantiate_mvars pf\n--fail \"reconstruct_of_expr_def failed, not implemented yet\"\n-/\n\n-- TODO (alg_nom)\nprivate meta def reconstruct_of_expr_def (e : expr) (pf : prod_form) : tactic expr :=\ndo --trace \"in reconstruct_of_expr_def\",\n tp ← prod_form.to_expr pf,\n -- trace \"tp:\", trace tp,\n tp' ← to_expr ``(1 = %%tp),\n -- trace \"tp':\", trace tp',\n-- (_, pf) ← solve_aux tp' (simp >> done),\n mk_app ``reconstruct_of_expr_def_aux [tp']\n\nsection\nvariable (rct : Π {pfc}, prod_form_proof pfc → tactic expr) \n\n-- Given an expr of the form e := (p1^e1)^k, produces a proof that\n-- e = p1^(e1*k)\nprivate meta def simp_pow_aux_aux (p e k : expr) : tactic expr :=\nmk_app ``rat.pow_pow [p, e, k]\n\n/-private meta def simp_pow_aux_aux : expr → tactic expr \n| `(rat.pow (rat.pow %%p %%e) %%k) := mk_app ``rat.pow_pow [p, e, k]\n| _ := failed\n-/\n\n\n-- Given an expr of the form e := (p1^e1*...*pn^en)^k, produces a proof that\n-- e = (p1^(e1*k) * ... * pn^(en*k)\nprivate meta def simp_pow_aux : expr → tactic expr | e := \nmatch e with\n| `(rat.pow (%%a * (rat.pow %%b %%n)) %%k) := \n let prod' := `(rat.pow %%a %%k) in\n do prod_pf ← simp_pow_aux prod',\n pow_pf ← mk_app ``rat.mul_pow [a, `(rat.pow %%b %%n), k],\n one_pow_pf ← simp_pow_aux_aux b n k,\n-- trace \"doing rewrite\",\n-- infer_type pow_pf >>= trace, trace e,\n (e', pf1, []) ← rewrite pow_pf e,\n (e'', pf2, []) ← rewrite one_pow_pf e',\n (e''', pf3, []) ← rewrite prod_pf e'',\n t1 ← mk_app ``eq.trans [pf1, pf2],\n mk_app ``eq.trans [t1, pf3]\n| `(rat.pow (rat.pow %%a %%n) %%k) := \n simp_pow_aux_aux a n k \n| e := do f ← pp e, fail $ \"simp_pow_aux failed on \" ++ f.to_string\nend\n\n\n-- Given an expr of the form e := (c*(p1^e1*...*pn^en))^k, produces a proof that\n-- e = c^k * (p1^(e1*k) * ... * pn^(en*k))\nmeta def simp_pow (e : expr) : tactic expr :=\n--do trace \"simp pow called on:\", trace e,\nmatch e with\n| `(rat.pow (%%coeff * %%prod) %%k) := \n let prod' := `(rat.pow %%prod %%k) in\n do prod_pf ← simp_pow_aux prod',\n pow_pf ← mk_app ``rat.mul_pow [coeff, prod, k],\n --trace \"doing rewrite\",\n (e', pf1, []) ← rewrite pow_pf e,\n (e'', pf2, []) ← rewrite prod_pf e',\n mk_app ``eq.trans [pf1, pf2]\n| _ := fail \"simp_pow got malformed arg\"\nend\n\n\n/-example (a b c : ℚ) (m n k : ℤ) : rat.pow (a * (rat.pow b m * rat.pow c n)) k = rat.pow a k * (rat.pow b (m*k) * rat.pow c (n*k)) :=\nby do\n(lhs, rhs) ← target >>= match_eq,\ne ← simp_pow lhs,\ninfer_type e >>= trace,\nexact e-/\n\nprivate meta def simp_pow_expr (pf tgt : expr) : tactic expr :=\ndo sls ← (simp_lemmas.mk.add_simp ``rat.mul_pow_rev) >>= λ t, t.add pf,\n --trace \"target\", trace tgt,\n --trace \"pf tp\", infer_type pf >>= trace,\n (do (_, npf) ← simplify sls [] tgt,-- <|> do rpr ← to_expr ``(eq.refl %%tgt), return (`(()), rpr),\n --(_, npf) ← solve_aux tgt (simp_target sls >> done),\n return npf) <|> to_expr ``(eq.refl %%tgt)\n\nmeta def simp_lemmas.add_simp_list : simp_lemmas → list name → tactic simp_lemmas\n| s [] := return s\n| s (h::t) := s.add_simp h >>= λ s', simp_lemmas.add_simp_list s' t\n\n\nprivate meta def simp_pow_expr' (tgt : expr) : tactic expr :=\ndo --sls ← (simp_lemmas.mk.add_simp ``rat.mul_pow) >>= (λ s, simp_lemmas.add_simp s ``rat.pow_one) >>= (λ s, simp_lemmas.add_simp s ``rat.pow_neg_one),\n sls ← simp_lemmas.add_simp_list simp_lemmas.mk [``rat.mul_pow, ``rat.pow_one, ``rat.pow_neg_one, ``rat.one_pow, ``rat.pow_pow, ``rat.one_div_pow],\n --trace \"target\", trace tgt,\n-- trace \"pf tp\", infer_type pf >>= trace,\n-- (do (_, npf) ← simplify sls [] tgt,-- <|> do rpr ← to_expr ``(eq.refl %%tgt), return (`(()), rpr),\n (_, npf) ← solve_aux tgt ( /-trace_state >>-/ simp_target sls >>/- trace \"!!!\" >> trace_state >>-/ reflexivity), -- `[simp [rat.mul_pow_rev, rat.pow_one], done],\n return npf\n\nsection\nopen expr\nprivate meta def reconstruct_of_pow_pos {pfc} (z : ℤ) (pfp : prod_form_proof pfc) : tactic expr :=\nif z ≤ 0 then fail \"reconstruct_of_pow_pos failed, given negative exponent\" else\ndo zsn ← mk_int_sign_pf z,\n pf1 ← rct pfp,\n --trace \"here\", /-trace pfc,-/ trace pfp, trace z, infer_type pf1 >>= trace,\n pf2 ← mk_mapp (if pfc.c = spec_comp.lt then ``lt_pos_pow' else ``le_pos_pow') [none, pf1, none, zsn],\n --trace \"pf2tp\", infer_type pf2 >>= trace,\n pf2tp ← infer_type pf2,\n match pf2tp with\n | (app (app (app o i) lhs) rhs) :=\n do eqp ← simp_pow rhs,\n (new_type, prf, []) ← rewrite eqp pf2tp,\n mk_eq_mp prf pf2\n-- failed\n | _ := fail \"reconstruct_of_pow_pos failed\"\n end\n/-\n match pf2tp with\n | app (app (app o i) lhs) rhs := do tgt ← prod_form.to_expr (pfc.pf.pow z), pf ← to_expr ``(%%rhs = %%tgt) >>= simp_pow_expr',\n trace \"pf2tp\", trace pf2tp, trace \"pftp\", infer_type pf >>= trace,\n trace \"o\", trace o,\n-- trace `(%%o %%lhs %%tgt),\n tgt' ← return $ app (app (app o i) lhs) tgt,--to_expr ``(%%o %%lhs %%tgt),\n trace \"new tgt:\", trace tgt',\n pf1 ← to_expr ``(eq.symm %%pf),\n (_, pf') ← solve_aux tgt' (rewrite_target pf1 >> apply pf2),\n trace \"proved\", infer_type pf' >>= trace,\n return pf'\n | _ := failed\n end\n-- tgt ← prod_form.to_expr (pfc.pf.pow z),\n-- simp_pow_expr pf2 tgt -/\n\nend\n\n/-private meta def reconstruct_of_pow_neg {pfc} (z : ℤ) (pfp : prod_form_proof pfc) : tactic expr :=\nif z ≥ 0 then fail \"reconstruct_of_pow_neg failed, given positive exponent\" else\nfailed-/\n\nprivate meta def reconstruct_of_pow_eq {pfc} (z : ℤ) (pfp : prod_form_proof pfc) : tactic expr :=\ndo --trace \"pfp is:\", trace pfp, \n pf1 ← rct pfp, --trace \"reconstructed\", infer_type pf1 >>= trace,\n tpf ← mk_app ``eq_pow [pf1, `(z)],\n tpf' ← mk_app ``eq_pow' [tpf],\n tpf_tp ← infer_type tpf',\n tgt ← prod_form.to_expr (pfc.pf.pow z),\n --trace \"target is:\", trace tgt,\n tgt' ← to_expr ``(1 = %%tgt),\n --trace \"tgt', tpf\", trace tgt', infer_type tpf >>= trace,\n (_, pf') ← solve_aux tgt' (assertv `h tpf_tp tpf' >> `[simp only [rat.mul_pow, rat.pow_pow], simp only [rat.mul_pow, rat.pow_pow] at h, apply h] >> done),\n return pf'\n-- simp_pow_expr tpf tgt\n\nprivate meta def reconstruct_of_pow {pfc} (z : ℤ) (pfp : prod_form_proof pfc) : tactic expr :=\nif pfc.c = spec_comp.eq then reconstruct_of_pow_eq @rct z pfp else reconstruct_of_pow_pos @rct z pfp\n\nprivate theorem reconstruct_of_mul_aux (P : Prop) {Q R : Prop} : Q → R → P := sorry\n\nprivate meta def reconstruct_of_mul (rct : Π {pfc}, prod_form_proof pfc → tactic expr) \n {lhs rhs c1 c2} (pfp1 : prod_form_proof ⟨lhs, c1⟩) (pfp2 : prod_form_proof ⟨rhs, c2⟩)\n (sgns : list Σ e : expr, sign_proof e gen_comp.ne) : tactic expr :=\nlet prod := lhs * rhs in\ndo /-trace \"in reconstruct_of_mul\",\n trace prod,-/\n tp ← prod_form.to_expr prod,\n --trace tp,\n tp' ← (spec_comp.strongest c1 c2).to_comp.to_function `(1 : ℚ) tp,\n --trace tp',\n pf1 ← rct pfp1, pf2 ← rct pfp2,-- trace \"**\",\n mk_mapp ``reconstruct_of_mul_aux [tp', none, none, pf1, pf2]\n/-\nlet sum := lhs + rhs.scale m in\ndo tp ← sum_form.to_expr sum,\n tp' ← (spec_comp.strongest c1 c2).to_comp.to_function tp `(0 : ℚ),\n pf1 ← sfrc sfpl, pf2 ← sfrc sfpr,\n mk_mapp ``reconstruct_of_add_factor_aux [some tp', none, none, some pf1, some pf2] \n-/\n\nend\n\n\nmeta def reconstruct : Π {pfc}, prod_form_proof pfc → tactic expr\n--| .(_) (@of_ineq_proof_pos_lhs _ _ _ id sp nzprs) := reconstruct_of_ineq_proof_pos_lhs id sp nzprs\n--| .(_) (@of_ineq_proof_neg_lhs _ _ _ id sp nzprs) := reconstruct_of_ineq_proof_neg_lhs id sp nzprs\n| .(_) (@of_ineq_proof _ _ _ _ _ id spl spr) := reconstruct_of_ineq_proof id spl spr\n| .(_) (@of_eq_proof _ _ _ id lhsne) := reconstruct_of_eq_proof id lhsne\n| .(_) (@of_expr_def e pf) := reconstruct_of_expr_def e pf\n| .(_) (@of_pow _ z pfp) := reconstruct_of_pow @reconstruct z pfp\n| .(_) (@of_mul _ _ _ _ pfp1 pfp2 sgns) := reconstruct_of_mul @reconstruct pfp1 pfp2 sgns\n| .(_) (adhoc _ _ t) := t\n| .(_) (fake _) := fail \"prod_form_proof.reconstruct failed: cannot reconstruct fake\"\n\nend prod_form_proof\n\nend polya\n\n", "meta": {"author": "robertylewis", "repo": "lean_polya", "sha": "1da14d60a55ad6cd8af8017b1b64990fccb66ab7", "save_path": "github-repos/lean/robertylewis-lean_polya", "path": "github-repos/lean/robertylewis-lean_polya/lean_polya-1da14d60a55ad6cd8af8017b1b64990fccb66ab7/src/proof_reconstruction.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48047869292635403, "lm_q2_score": 0.04672495746457613, "lm_q1q2_score": 0.02245034648961903}} {"text": "import Lean\n\nexample : True := by\n apply True.intro\n --^ textDocument/hover\n\nexample : True := by\n simp [True.intro]\n --^ textDocument/hover\n\nexample (n : Nat) : True := by\n match n with\n | Nat.zero => _\n --^ textDocument/hover\n | n + 1 => _\n\n\n/-- My tactic -/\nmacro \"mytac\" o:\"only\"? e:term : tactic => `(tactic| exact $e)\n\nexample : True := by\n mytac only True.intro\n--^ textDocument/hover\n --^ textDocument/hover\n --^ textDocument/hover\n\n/-- My way better tactic -/\nmacro_rules\n | `(tactic| mytac $[only]? $e:term) =>\n --^ textDocument/hover\n --^ textDocument/hover\n `(tactic| apply $e:term)\n --^ textDocument/hover\n --^ textDocument/hover\n\nexample : True := by\n mytac only True.intro\n--^ textDocument/hover\n\n/-- My ultimate tactic -/\nelab_rules : tactic\n | `(tactic| mytac $[only]? $e) => do Lean.Elab.Tactic.evalTactic (← `(tactic| refine $e))\n\nexample : True := by\n mytac only True.intro\n--^ textDocument/hover\n\n\n/-- My notation -/\nmacro (name := myNota) \"mynota\" e:term : term => pure e\n --^ textDocument/hover\n\n#check mynota 1\n --^ textDocument/hover\n\n/-- My way better notation -/\nmacro_rules\n | `(mynota $e) => `(2 * $e)\n\n#check mynota 1\n --^ textDocument/hover\n\n-- macro_rules take precedence over elab_rules for term/command, so use new syntax\nsyntax \"mynota'\" term : term\n\n/-- My ultimate notation -/\nelab_rules : term\n | `(mynota' $e) => `($e * $e) >>= (Lean.Elab.Term.elabTerm · none)\n\n#check mynota' 1\n --^ textDocument/hover\n\n@[inherit_doc]\ninfix:65 (name := myInfix) \" >+< \" => Nat.add\n --^ textDocument/hover\n --^ textDocument/hover\n\n#check 1 >+< 2\n --^ textDocument/hover\n\n@[inherit_doc] notation \"ℕ\" => Nat\n\n#check ℕ\n --^ textDocument/hover\n\n/-- My command -/\nmacro \"mycmd\" e:term : command => do\n let seq ← `(Lean.Parser.Term.doSeq| $e:term)\n --^ textDocument/hover\n `(def hi := Id.run do $seq:doSeq)\n --^ textDocument/hover\n\nmycmd 1\n--^ textDocument/hover\n\n/-- My way better command -/\nmacro_rules\n | `(mycmd $e) => `(@[inline] def hi := $e)\n\nmycmd 1\n--^ textDocument/hover\n\nsyntax \"mycmd'\" ppSpace sepBy1(term, \" + \") : command\n --^ textDocument/hover\n --^ textDocument/hover\n --^ textDocument/hover\n\n/-- My ultimate command -/\nelab_rules : command\n | `(mycmd' $e) => do Lean.Elab.Command.elabCommand (← `(/-- hi -/ @[inline] def hi := $e))\n\nmycmd' 1\n--^ textDocument/hover\n\n\n#check ({ a := }) -- should not show `sorry`\n --^ textDocument/hover\n\nexample : True := by\n simp [id True.intro]\n --^ textDocument/hover\n --^ textDocument/hover\n\n\nexample : Id Nat := do\n let mut n := 1\n n := 2\n--^ textDocument/hover\n n\n\n\nopaque foo : Nat\n\n#check _root_.foo\n --^ textDocument/hover\n\nnamespace Bar\n\nopaque foo : Nat\n --^ textDocument/hover\n\n#check _root_.foo\n --^ textDocument/hover\n\ndef bar := 1\n --^ textDocument/hover\n\nstructure Foo := mk ::\n --^ textDocument/hover\n --^ textDocument/hover\n hi : Nat\n--^ textDocument/hover\n\ninductive Bar\n --^ textDocument/hover\n | mk : Bar\n --^ textDocument/hover\n\ninstance : ToString Nat := ⟨toString⟩\n--^ textDocument/hover\ninstance f : ToString Nat := ⟨toString⟩\n --^ textDocument/hover\n\nexample : Type 0 := Nat\n --^ textDocument/hover\n\ndef foo.bar : Nat := 1\n --^ textDocument/hover\n --^ textDocument/hover\n\nexample : Nat → Nat → Nat :=\n fun x y =>\n --^ textDocument/hover\n --v textDocument/definition\n x\n --^ textDocument/hover\n\n -- textDocument/definition -- removed because the result is platform-dependent\nset_option linter.unusedVariables false in\n --^ textDocument/hover\nexample : Nat → Nat → Nat := by\n intro x y\n --^ textDocument/hover\n --v textDocument/definition\n exact x\n --^ textDocument/hover\n\ndef g (n : Nat) : Nat := g 0\ntermination_by g n => n\ndecreasing_by have n' := n; admit\n --^ textDocument/hover\n\n@[inline]\n--^ textDocument/hover\ndef one := 1\n\nexample : True ∧ False := by\n constructor\n · constructor\n--^ textDocument/hover\n\nexample : Nat := Id.run do (← 1)\n --^ textDocument/hover\n\n#check (· + ·)\n --^ textDocument/hover\n --^ textDocument/hover\nmacro \"my_intro\" x:(ident <|> \"_\") : tactic =>\n match x with\n | `($x:ident) => `(tactic| intro $x:ident)\n | _ => `(tactic| intro _%$x)\n\nexample : α → α := by intro x; assumption\n --^ textDocument/hover\nexample : α → α := by intro _; assumption\n --^ textDocument/hover\nexample : α → α := by my_intro x; assumption\n --^ textDocument/hover\nexample : α → α := by my_intro _; assumption\n --^ textDocument/hover\n\nexample : Nat → True := by\n intro x\n --^ textDocument/hover\n cases x with\n | zero => trivial\n --^ textDocument/hover\n --v textDocument/hover\n | succ x => trivial\n --^ textDocument/hover\n\nexample : Nat → True := by\n intro x\n --^ textDocument/hover\n induction x with\n --^ textDocument/hover\n | zero => trivial\n --^ textDocument/hover\n --v textDocument/hover\n | succ _ ih => exact ih\n --^ textDocument/hover\n\nexample : Nat → Nat\n --v textDocument/hover\n | .zero => .zero\n --^ textDocument/hover\n --v textDocument/hover\n | .succ x => .succ x\n --^ textDocument/hover\n\nexample : Inhabited Nat := ⟨Nat.zero⟩\n --^ textDocument/hover\n --^ textDocument/hover\n\nexample : Nat :=\n let x := match 0 with | _ => 0\n _\n--^ textDocument/hover\n\ndef auto (o : Nat := by exact 1) : Nat := o\n --^ textDocument/hover\n", "meta": {"author": "leanprover", "repo": "lean4", "sha": "742d053a97bdd109a41a921facd1cd6a55e89bc7", "save_path": "github-repos/lean/leanprover-lean4", "path": "github-repos/lean/leanprover-lean4/lean4-742d053a97bdd109a41a921facd1cd6a55e89bc7/tests/lean/interactive/hover.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45713670203584295, "lm_q2_score": 0.04885777827594124, "lm_q1q2_score": 0.02233468362986223}} {"text": "import tactic.interactive\n\nlemma a {α} [nonempty α] : ∃ a : α, a = a :=\nby inhabit α; use default _; refl\n\nnoncomputable def b {α} [nonempty α] : α :=\nby inhabit α; apply default\n\nlemma c {α} [nonempty α] : ∀ n : ℕ, ∃ b : α, n = n :=\nby inhabit α; intro; use default _; refl\n\nnoncomputable def d {α} [nonempty α] : ∀ n : ℕ, α :=\nby inhabit α; intro; apply default\n", "meta": {"author": "JLimperg", "repo": "aesop3", "sha": "a4a116f650cc7403428e72bd2e2c4cda300fe03f", "save_path": "github-repos/lean/JLimperg-aesop3", "path": "github-repos/lean/JLimperg-aesop3/aesop3-a4a116f650cc7403428e72bd2e2c4cda300fe03f/test/inhabit.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.37022539259558657, "lm_q2_score": 0.06008665185713089, "lm_q1q2_score": 0.022245604273560614}} {"text": "example (P : Prop) : ∀ x ∈ (∅ : set ℕ), P :=\nbegin\n intro x,\n intro hx,\n cases hx,\nend \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nexample (P : Prop) : ∀ x ∈ (∅ : set ℕ), P :=\nbegin\n intros x hx, cases hx,\nend\n", "meta": {"author": "ImperialCollegeLondon", "repo": "M40001_lean", "sha": "62a76fa92654c855af2b2fc2bef8e60acd16ccec", "save_path": "github-repos/lean/ImperialCollegeLondon-M40001_lean", "path": "github-repos/lean/ImperialCollegeLondon-M40001_lean/M40001_lean-62a76fa92654c855af2b2fc2bef8e60acd16ccec/src/2019/lectures/emptyset.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34864513533394575, "lm_q2_score": 0.06371499114069418, "lm_q1q2_score": 0.022213921709048477}} {"text": "import data.pfun\n\n/-! Need to figure out how to port over the stuff from `turing.reaches` and `turing.eval` to the slightly more\ngeneral setting with any generic `pfun` (i.e. instead of iterating `f : α → option α`, we should be able to\niterate `f : α → β ⊕ α` and more easily convert between `f.fix x`, a sequence of applications `ℕ → α` given by\n`x, f(x), f(f(x)), ...`, and a `reaches`-prop `reaches x y` which indicates that `y = f(f(...f(x)))` for some number\nof `f`'s.\n\nThese are useful in the `pfun` setting, not just Turing machine states.\n-/\n\n\nnamespace pfun\nlemma exists_preimage_of_fix_dom {α β : Type*} {f : α →. β ⊕ α} {a : α} {b : β} (h : b ∈ f.fix a) :\n ∃ a', sum.inl b ∈ f a' :=\nby apply fix_induction' _ _ h; tauto\n\nvariables {α₁ α₂ β₁ β₂ : Type*}\nvariables (f₁ : α₁ →. β₁ ⊕ α₁) (f₂ : α₂ →. β₂ ⊕ α₂)\n\n/-- We just extract a very special case, which is all we need here: two functions `f₁` and `f₂` satisfy\n`frespects_once` wrt `F` if whenever `f₁` takes a single step from `a₁ : α₁` to `a₁' : α₁`, `f₂` takes\nthe corresponding step from `a₂ = F a₁` to `a₂' = F a₁'`, and moreover, if `f₁` diverges on a state iff `f₂` diverges\non the corresponding one, and `f₁` halts on a state iff `f₂` halts on the corresponding one. \n\nWe use a slightly weaker definition which is equivalent to the above description. -/\ndef frespects_once (F : α₁ → α₂) : Prop :=\n∀ a₁, ((f₂ (F a₁)).dom → (f₁ a₁).dom) ∧ (∀ a₁', sum.inr a₁' ∈ f₁ a₁ → (sum.inr $ F a₁') ∈ (f₂ (F a₁)))\n ∧ ((∃ b₁, sum.inl b₁ ∈ f₁ a₁) → ∃ b₂, sum.inl b₂ ∈ f₂ (F a₁))\n\nvariables {F : α₁ → α₂} (hF : frespects_once f₁ f₂ F) {f₁ f₂}\ninclude hF\n\nlemma dom_iff_dom (a : α₁) : (f₁ a).dom ↔ (f₂ (F a)).dom :=\nbegin\n specialize hF a, split, swap, { exact hF.1, },\n { intro h, \n rw part.dom_iff_mem at h ⊢,\n obtain ⟨y, hy⟩ := h,\n cases y with ly ry,\n { obtain ⟨b₂, hb₂⟩ := hF.2.2 ⟨ly, hy⟩, use sum.inl b₂, assumption, },\n exact ⟨_, hF.2.1 ry hy⟩, }\nend\n\nlemma fwd_preimage_of_fwd {a : α₁} {a' : α₂} (ha' : sum.inr a' ∈ f₂ (F a)) : ∃ a₁', sum.inr a₁' ∈ f₁ a ∧ F a₁' = a' :=\nbegin\n have : (f₁ a).dom, { rw [dom_iff_dom hF a, part.dom_iff_mem], exact ⟨_, ha'⟩, }, \n specialize hF a,\n suffices h : ∃ a₁', sum.inr a₁' ∈ f₁ a, \n { obtain ⟨a₁', h⟩ := h, use a₁', refine ⟨h, _⟩, exact sum.inr_injective (part.mem_unique (hF.2.1 a₁' h) ha'), },\n cases (f₁ a) with d v, cases e : v this with vb va,\n { exfalso, cases hF.2.2 ⟨vb, _⟩ with _ H, { have := part.mem_unique ha' H, contradiction, },\n use this, exact e, },\n use va, use this, exact e,\nend\n\nlemma fwd_iff_fwd (a : α₁) : (∃ a', sum.inr a' ∈ f₁ a) ↔ ∃ a', sum.inr a' ∈ f₂ (F a) :=\nbegin\n split; rintro ⟨a', ha'⟩,\n { exact ⟨_, (hF a).2.1 a' ha'⟩, },\n { obtain ⟨a₁', ha₁'⟩ := fwd_preimage_of_fwd hF ha', exact ⟨a₁', ha₁'.1⟩, }\nend\n\nlemma stop_iff_stop (a : α₁) : (∃ b₁, sum.inl b₁ ∈ f₁ a) ↔ ∃ b₂, sum.inl b₂ ∈ f₂ (F a) :=\nbegin\n split, { exact (hF a).2.2, },\n rintro ⟨b₂, hb₂⟩,\n have : (f₁ a).dom, { rw [dom_iff_dom hF a, part.dom_iff_mem], exact ⟨_, hb₂⟩, }, \n have H := (fwd_iff_fwd hF a).mp,\n cases (f₁ a) with d v, cases e : v this with vb va,\n { use vb, use this, exact e, },\n exfalso, specialize H ⟨va, _⟩, { use this, exact e, },\n obtain ⟨a₂', ha₂'⟩ := H, have := part.mem_unique hb₂ ha₂', contradiction,\nend\n\nlemma frespects_last_step {a : α₁} {b₁ : β₁} {b₂ : β₂} (hb₁ : b₁ ∈ f₁.fix a) (hb₂ : b₂ ∈ f₂.fix (F a)) :\n ∃ a' : α₁, sum.inl b₁ ∈ f₁ a' ∧ sum.inl b₂ ∈ f₂ (F a') :=\nbegin\n revert hb₂,\n apply fix_induction' _ _ hb₁; clear hb₁ a,\n { intros a' ha' hb₂, use [a', ha'],\n obtain ⟨b₂', hb₂'⟩ := (stop_iff_stop hF a').mp ⟨b₁, ha'⟩,\n have : b₂ = b₂' := part.mem_unique hb₂ (fix_stop _ hb₂'), subst this,\n assumption, },\n intros a a' ha' ha ih hb₂,\n refine ih _,\n rwa ← fix_fwd _ _ ((hF a).2.1 _ ha),\nend\n\nvariable (F)\ntheorem eq_dom_of_frespects_once (a : α₁) :\n (f₁.fix a).dom ↔ (f₂.fix (F a)).dom :=\nbegin\n split; intro h;\n rw part.dom_iff_mem at h;\n cases h with y h,\n { apply fix_induction' _ _ h; clear h a,\n { intros a h, obtain ⟨b₂, hb₂⟩ := (stop_iff_stop hF a).mp ⟨_, h⟩,\n rw [part.dom_iff_mem], use b₂, exact fix_stop _ hb₂, },\n intros a a' hy ha ha',\n rw part.dom_iff_mem at ⊢ ha',\n rw fix_fwd, { exact ha', }, exact (hF a).2.1 a' ha, },\n suffices : ∀ a', F a' = F a → (f₁.fix a').dom, { exact this a rfl, },\n apply @fix_induction' _ _ f₂ y (λ z, ∀ a', F a' = z → (f₁.fix a').dom) _ h; clear h a,\n { intros a ha a' ha', subst ha',\n have : ∃ y', sum.inl y' ∈ f₁ a', { rw stop_iff_stop hF a', exact ⟨_, ha⟩, },\n rw part.dom_iff_mem, obtain ⟨y', hy'⟩ := this, exact ⟨y', fix_stop _ hy'⟩, },\n intros a a' ha' ha ih x hx, subst hx,\n rw part.dom_iff_mem,\n obtain ⟨y', hy', hyF⟩ := fwd_preimage_of_fwd hF ha,\n specialize ih y' hyF,\n rw part.dom_iff_mem at ih, \n rwa fix_fwd _ _ hy'\nend\n\nend pfun", "meta": {"author": "prakol16", "repo": "lean_complexity_theory_polytime_defs", "sha": "b4e5f5544e11cd5aca1a5a4b5b0231537af4962c", "save_path": "github-repos/lean/prakol16-lean_complexity_theory_polytime_defs", "path": "github-repos/lean/prakol16-lean_complexity_theory_polytime_defs/lean_complexity_theory_polytime_defs-b4e5f5544e11cd5aca1a5a4b5b0231537af4962c/src/frespects_pfun.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4532618480153861, "lm_q2_score": 0.04885777464048789, "lm_q1q2_score": 0.022145365223466808}} {"text": "import Lean\n\nimport Meta.Boolean\nimport Meta.Pull\n\nopen Lean Elab.Tactic Meta\n\ndef congDupOr (i : Nat) (nm : Ident) (last : Bool) : TacticM Syntax :=\n match i with\n | 0 =>\n if last then `(dupOr₂ $nm)\n else `(dupOr $nm)\n | (i' + 1) => do\n let nm' := mkIdent (Name.mkSimple \"w\")\n let r ← congDupOr i' nm' last\n let r: Term := ⟨r⟩\n `(congOrLeft (fun $nm' => $r) $nm)\n\n-- i: the index fixed in the original list\n-- j: the index of li.head! in the original list\ndef loop (i j n : Nat) (pivot : Expr) (li : List Expr) (nm : Ident) : TacticM Ident :=\n match li with\n | [] => return nm\n | e::es =>\n if e == pivot then do\n -- step₁: move expr that is equal to the pivot to position i + 1\n let step₁ ←\n if j > i + 1 then\n let fname ← mkIdent <$> mkFreshId\n let e ← getTypeFromName nm.getId\n let t ← instantiateMVars e\n pullIndex2 (i + 1) j nm t fname\n pure fname\n else pure nm\n\n -- step₂: apply congOrLeft i times with dupOr\n let step₂: Ident ← do\n let last := i + 1 == n - 1\n let tactic ← congDupOr i step₁ last \n let tactic := ⟨tactic⟩\n let fname ← mkIdent <$> mkFreshId\n evalTactic (← `(tactic| have $fname := $tactic))\n pure fname\n\n loop i j (n - 1) pivot es step₂\n else loop i (j + 1) n pivot es nm\n\ndef factorCore (type : Expr) (source : Ident) : TacticM Unit :=\n withMainContext do\n let mut li := collectPropsInOrChain type\n let n := li.length\n let mut answer := source\n for i in List.range n do\n li := List.drop i li\n match li with\n | [] => break\n | e::es => do\n answer ← loop i (i + 1) (li.length + i) e es answer\n let e ← getTypeFromName answer.getId\n let t ← instantiateMVars e\n li := collectPropsInOrChain t\n evalTactic (← `(tactic| exact $answer))\n\nsyntax (name := factor) \"factor\" term : tactic\n\n@[tactic factor] def evalFactor : Tactic := fun stx =>\n withMainContext do\n let e ← elabTerm stx[1] none\n let type ← inferType e\n let source := ⟨stx[1]⟩\n factorCore type source\n\nexample : A ∨ A ∨ A ∨ A ∨ B ∨ A ∨ B ∨ A ∨ C ∨ B ∨ C ∨ B ∨ A → A ∨ B ∨ C :=\n by intro h\n factor h\n", "meta": {"author": "tomaz1502", "repo": "Reconstruction", "sha": "3cd76aacfa5e4acb47de7d45b831e24bf607fb4c", "save_path": "github-repos/lean/tomaz1502-Reconstruction", "path": "github-repos/lean/tomaz1502-Reconstruction/Reconstruction-3cd76aacfa5e4acb47de7d45b831e24bf607fb4c/Meta/Factor.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.04401864860883462, "lm_q1q2_score": 0.02200932430441731}} {"text": "import «smt-lean»\n\nexample {α : Type} {z : α} {x y : list α}\n (h : (z :: x : list α) = z :: y)\n : x = y :=\nbegin\n veriT,\nend\n", "meta": {"author": "cipher1024", "repo": "smt-lean", "sha": "a1ad7855ae01aca1f8be5b8c8df95a01a175d08e", "save_path": "github-repos/lean/cipher1024-smt-lean", "path": "github-repos/lean/cipher1024-smt-lean/smt-lean-a1ad7855ae01aca1f8be5b8c8df95a01a175d08e/test/ex5.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4571367168274948, "lm_q2_score": 0.048136771116634815, "lm_q1q2_score": 0.02200508550693502}} {"text": "import ..lectures.love05_inductive_predicates_demo\n\n\n/-! # LoVe Demo 7: Metaprogramming\n\nNote for Brown FPV students: we are not following this demo directly!\nBut I'm posting it because some definitions in here are used in the exercises.\n --Rob\n\nUsers can extend Lean with custom tactics and tools. This kind of\nprogramming—programming the prover—is called metaprogramming.\n\nLean's metaprogramming framework uses mostly the same notions and syntax as\nLean's input language itself. Abstract syntax trees __reflect__ internal data\nstructures, e.g., for expressions (terms). The prover's C++ internals are\nexposed through Lean interfaces, which we can use for\n\n* accessing the current context and goal;\n* unifying expressions;\n* querying and modifying the environment;\n* setting attributes.\n\nMost of Lean's predefined tactics are implemented in Lean (and not in C++).\n\nExample applications:\n\n* proof goal transformations;\n* heuristic proof search;\n* decision procedures;\n* definition generators;\n* advisor tools;\n* exporters;\n* ad hoc automation.\n\nAdvantages of Lean's metaprogramming framework:\n\n* Users do not need to learn another programming language to write\n metaprograms; they can work with the same constructs and notation used to\n define ordinary objects in the prover's library.\n\n* Everything in that library is available for metaprogramming purposes.\n\n* Metaprograms can be written and debugged in the same interactive environment,\n encouraging a style where formal libraries and supporting automation are\n developed at the same time. -/\n\n\nset_option pp.beta true\nset_option pp.generalized_field_notation false\n\nnamespace LoVe\n\n\n/-! ## Tactics and Tactic Combinators\n\nWhen programming our own tactics, we often need to repeat some actions on\nseveral goals, or to recover if a tactic fails. Tactic combinators help in such\ncase.\n\n`repeat` applies its argument repeatedly on all (sub…sub)goals until it cannot\nbe applied any further. -/\n\nlemma repeat_example :\n even 4 ∧ even 7 ∧ even 3 ∧ even 0 :=\nbegin\n repeat { apply and.intro },\n repeat { apply even.add_two },\n repeat { sorry }\nend\n\n/-! The \"orelse\" combinator `<|>` tries its first argument and applies its\nsecond argument in case of failure. -/\n\nlemma repeat_orelse_example :\n even 4 ∧ even 7 ∧ even 3 ∧ even 0 :=\nbegin\n repeat { apply and.intro },\n repeat {\n apply even.add_two\n <|> apply even.zero },\n repeat { sorry }\nend\n\n/-! `iterate` works repeatedly on the first goal until it fails; then it\nstops. -/\n\nlemma iterate_orelse_example :\n even 4 ∧ even 7 ∧ even 3 ∧ even 0 :=\nbegin\n repeat { apply and.intro },\n iterate {\n apply even.add_two\n <|> apply even.zero },\n repeat { sorry }\nend\n\n/-! `all_goals` applies its argument exactly once to each goal. It succeeds only\nif the argument succeeds on **all** goals. -/\n\nlemma all_goals_example :\n even 4 ∧ even 7 ∧ even 3 ∧ even 0 :=\nbegin\n repeat { apply and.intro },\n all_goals { apply even.add_two }, -- fails\n repeat { sorry }\nend\n\n/-! `try` transforms its argument into a tactic that never fails. -/\n\nlemma all_goals_try_example :\n even 4 ∧ even 7 ∧ even 3 ∧ even 0 :=\nbegin\n repeat { apply and.intro },\n all_goals { try { apply even.add_two } },\n repeat { sorry }\nend\n\n/-! `any_goals` applies its argument exactly once to each goal. It succeeds\nif the argument succeeds on **any** goal. -/\n\nlemma any_goals_example :\n even 4 ∧ even 7 ∧ even 3 ∧ even 0 :=\nbegin\n repeat { apply and.intro },\n any_goals { apply even.add_two },\n repeat { sorry }\nend\n\n/-! `solve1` transforms its argument into an all-or-nothing tactic. If the\nargument does not prove the goal, `solve1` fails. -/\n\nlemma any_goals_solve1_repeat_orelse_example :\n even 4 ∧ even 7 ∧ even 3 ∧ even 0 :=\nbegin\n repeat { apply and.intro },\n any_goals { solve1 { repeat {\n apply even.add_two\n <|> apply even.zero } } },\n repeat { sorry }\nend\n\n/-! The combinators `repeat`, `iterate`, `all_goals`, and `any_goals` can easily\nlead to infinite looping: -/\n\n/-\nlemma repeat_not_example :\n ¬ even 1 :=\nbegin\n repeat { apply not.intro },\n sorry\nend\n-/\n\n/-! Let us start with the actual metaprogramming, by coding a custom tactic. The\ntactic embodies the behavior we hardcoded in the `solve1` example above: -/\n\nmeta def intro_and_even : tactic unit :=\ndo\n tactic.repeat (tactic.applyc ``and.intro),\n tactic.any_goals (tactic.solve1 (tactic.repeat\n (tactic.applyc ``even.add_two\n <|> tactic.applyc ``even.zero))),\n pure ()\n\n/-! The `meta` keyword makes it possible for the function to call other\nmetafunctions. The `do` keyword enters a monad, and the `<|>` operator is the\n\"orelse\" operator of alternative monads. At the end, we return `()`, of type\n`unit`, to ensure the metaprogram has the desired type.\n\nAny executable Lean definition can be used as a metaprogram. In addition, we can\nput `meta` in front of a definition to indicate that is a metadefinition. Such\ndefinitions need not terminate but cannot be used in non-`meta` contexts.\n\nLet us apply our custom tactic: -/\n\nlemma any_goals_solve1_repeat_orelse_example₂ :\n even 4 ∧ even 7 ∧ even 3 ∧ even 0 :=\nbegin\n intro_and_even,\n repeat { sorry }\nend\n\n\n/-! ## The Metaprogramming Monad\n\nTactics have access to\n\n* the list of **goals** as metavariables (each metavariables has a type and a\n local context (hypothesis); they can optionally be instantiated);\n\n* the **elaborator** (to elaborate expressions and compute their type);\n\n* the **environment**, containing all declarations and inductive types;\n\n* the **attributes** (e.g., the list of `@[simp]` rules).\n\nThe tactic monad is an alternative monad, with `fail` and `<|>`. Tactics can\nalso produce trace messages. -/\n\nlemma even_14 :\n even 14 :=\nby do\n tactic.trace \"Proving evenness …\",\n intro_and_even\n\nmeta def hello_then_intro_and_even : tactic unit :=\ndo\n tactic.trace \"Proving evenness …\",\n intro_and_even\n\nlemma even_16 :\n even 16 :=\nby hello_then_intro_and_even\n\nrun_cmd tactic.trace \"Hello, Metaworld!\"\n\nmeta def trace_goals : tactic unit :=\ndo\n tactic.trace \"local context:\",\n ctx ← tactic.local_context,\n tactic.trace ctx,\n tactic.trace \"target:\",\n P ← tactic.target,\n tactic.trace P,\n tactic.trace \"all missing proofs:\",\n Hs ← tactic.get_goals,\n tactic.trace Hs,\n τs ← list.mmap tactic.infer_type Hs,\n tactic.trace τs\n\nlemma even_18_and_even_20 (α : Type) (a : α) :\n even 18 ∧ even 20 :=\nby do\n tactic.applyc ``and.intro,\n trace_goals,\n intro_and_even\n\nlemma triv_imp (a : Prop) (h : a) :\n a :=\nby do\n h ← tactic.get_local `h,\n tactic.trace \"h:\",\n tactic.trace h,\n tactic.trace \"raw h:\",\n tactic.trace (expr.to_raw_fmt h),\n tactic.trace \"type of h:\",\n τ ← tactic.infer_type h,\n tactic.trace τ,\n tactic.trace \"type of type of h:\",\n υ ← tactic.infer_type τ,\n tactic.trace υ,\n tactic.apply h\n\nmeta def exact_list : list expr → tactic unit\n| [] := tactic.fail \"no matching expression found\"\n| (h :: hs) :=\n do {\n tactic.trace \"trying\",\n tactic.trace h,\n tactic.exact h }\n <|> exact_list hs\n\nmeta def hypothesis : tactic unit :=\ndo\n hs ← tactic.local_context,\n exact_list hs\n\nlemma app_of_app {α : Type} {p : α → Prop} {a : α}\n (h : p a) :\n p a :=\nby hypothesis\n\n\n/-! ## Names, Expressions, Declarations, and Environments\n\nThe metaprogramming framework is articulated around five main types:\n\n* `tactic` manages the proof state, the global context, and more;\n\n* `name` represents a structured name (e.g., `x`, `even.add_two`);\n\n* `expr` represents an expression (a term) as an abstract syntax tree;\n\n* `declaration` represents a constant declaration, a definition, an axiom, or a\n lemma;\n\n* `environment` stores all the declarations and notations that make up the\n global context. -/\n\n#print expr\n\n#check expr tt -- elaborated expressions\n#check expr ff -- unelaborated expressions (pre-expressions)\n\n#print name\n\n#check (expr.const `ℕ [] : expr)\n#check expr.sort level.zero -- Sort 0, i.e., Prop\n#check expr.sort (level.succ level.zero)\n -- Sort 1, i.e., Type\n#check expr.var 0 -- bound variable with De Bruijn index 0\n#check (expr.local_const `uniq_name `pp_name binder_info.default\n `(ℕ) : expr)\n#check (expr.mvar `uniq_name `pp_name `(ℕ) : expr)\n#check (expr.pi `pp_name binder_info.default `(ℕ)\n (expr.sort level.zero) : expr)\n#check (expr.lam `pp_name binder_info.default `(ℕ)\n (expr.var 0) : expr)\n#check expr.elet\n#check expr.macro\n\n/-! We can create literal expressions conveniently using backticks and\nparentheses:\n\n* Expressions with a single backtick must be fully elaborated.\n\n* Expressions with two backticks are __pre-expressions__: They may contain some\n holes to be filled in later, based on some context.\n\n* Expressions with three backticks are pre-expressions without name checking. -/\n\nrun_cmd do\n let e : expr := `(list.map (λn : ℕ, n + 1) [1, 2, 3]),\n tactic.trace e\n\nrun_cmd do\n let e : expr := `(list.map _ [1, 2, 3]), -- fails\n tactic.trace e\n\nrun_cmd do\n let e₁ : pexpr := ``(list.map (λn, n + 1) [1, 2, 3]),\n let e₂ : pexpr := ``(list.map _ [1, 2, 3]),\n tactic.trace e₁,\n tactic.trace e₂\n\nrun_cmd do\n let e : pexpr := ```(seattle.washington),\n tactic.trace e\n\n/-! We can also create literal names with backticks:\n\n* Names with a single backtick, `n, are not checked for existence.\n\n* Names with two backticks, ``n, are resolved and checked. -/\n\nrun_cmd tactic.trace `and.intro\nrun_cmd tactic.trace `intro_and_even\nrun_cmd tactic.trace `seattle.washington\n\nrun_cmd tactic.trace ``and.intro\nrun_cmd tactic.trace ``intro_and_even\nrun_cmd tactic.trace ``seattle.washington -- fails\n\n/-! __Antiquotations__ embed an existing expression in a larger expression. They\nare announced by the prefix `%%` followed by a name from the current context.\nAntiquotations are available with one, two, and three backticks: -/\n\nrun_cmd do\n let x : expr := `(2 : ℕ),\n let e : expr := `(%%x + 1),\n tactic.trace e\n\nrun_cmd do\n let x : expr := `(@id ℕ),\n let e : pexpr := ``(list.map %%x),\n tactic.trace e\n\nrun_cmd do\n let x : expr := `(@id ℕ),\n let e : pexpr := ```(a _ %%x),\n tactic.trace e\n\nlemma one_add_two_eq_three :\n 1 + 2 = 3 :=\nby do\n `(%%a + %%b = %%c) ← tactic.target,\n tactic.trace a,\n tactic.trace b,\n tactic.trace c,\n `(@eq %%α %%l %%r) ← tactic.target,\n tactic.trace α,\n tactic.trace l,\n tactic.trace r,\n tactic.exact `(refl _ : 3 = 3)\n\n#print declaration\n\n/-! The `environment` type is presented as an abstract type, equipped with some\noperations to query and modify it. The `environment.fold` metafunction iterates\nover all declarations making up the environment. -/\n\nrun_cmd do\n env ← tactic.get_env,\n tactic.trace (environment.fold env 0 (λdecl n, n + 1))\n\n\n/-! ## First Example: A Conjuction-Destructing Tactic\n\nWe define a `destruct_and` tactic that automates the elimination of `∧` in\npremises, automating proofs such as these: -/\n\nlemma abcd_a (a b c d : Prop) (h : a ∧ (b ∧ c) ∧ d) :\n a :=\nand.elim_left h\n\nlemma abcd_b (a b c d : Prop) (h : a ∧ (b ∧ c) ∧ d) :\n b :=\nand.elim_left (and.elim_left (and.elim_right h))\n\nlemma abcd_bc (a b c d : Prop) (h : a ∧ (b ∧ c) ∧ d) :\n b ∧ c :=\nand.elim_left (and.elim_right h)\n\n/-! Our tactic relies on a helper metafunction, which takes as argument the\nhypothesis `h` to use as an expression rather than as a name: -/\n\nmeta def destruct_and_helper : expr → tactic unit\n| h :=\n do\n t ← tactic.infer_type h,\n match t with\n | `(%%a ∧ %%b) :=\n tactic.exact h\n <|>\n do {\n ha ← tactic.to_expr ``(and.elim_left %%h),\n destruct_and_helper ha }\n <|>\n do {\n hb ← tactic.to_expr ``(and.elim_right %%h),\n destruct_and_helper hb }\n | _ := tactic.exact h\n end\n\nmeta def destruct_and (nam : name) : tactic unit :=\ndo\n h ← tactic.get_local nam,\n destruct_and_helper h\n\n/-! Let us check that our tactic works: -/\n\nlemma abc_a (a b c : Prop) (h : a ∧ b ∧ c) :\n a :=\nby destruct_and `h\n\nlemma abc_b (a b c : Prop) (h : a ∧ b ∧ c) :\n b :=\nby destruct_and `h\n\nlemma abc_bc (a b c : Prop) (h : a ∧ b ∧ c) :\n b ∧ c :=\nby destruct_and `h\n\nlemma abc_ac (a b c : Prop) (h : a ∧ b ∧ c) :\n a ∧ c :=\nby destruct_and `h -- fails\n\n\n/-! ## Second Example: A Provability Advisor\n\nNext, we implement a `prove_direct` tool that traverses all lemmas in the\ndatabase and checks whether one of them can be used to prove the current goal. A\nsimilar tactic is available in `mathlib` under the name `library_search`. -/\n\nmeta def is_theorem : declaration → bool\n| (declaration.defn _ _ _ _ _ _) := ff\n| (declaration.thm _ _ _ _) := tt\n| (declaration.cnst _ _ _ _) := ff\n| (declaration.ax _ _ _) := tt\n\nmeta def get_all_theorems : tactic (list name) :=\ndo\n env ← tactic.get_env,\n pure (environment.fold env [] (λdecl nams,\n if is_theorem decl then declaration.to_name decl :: nams\n else nams))\n\nmeta def prove_with_name (nam : name) : tactic unit :=\ndo\n tactic.applyc nam\n ({ md := tactic.transparency.reducible, unify := ff }\n : tactic.apply_cfg),\n tactic.all_goals tactic.assumption,\n pure ()\n\nmeta def prove_direct : tactic unit :=\ndo\n nams ← get_all_theorems,\n list.mfirst (λnam,\n do\n prove_with_name nam,\n tactic.trace (\"directly proved by \" ++ to_string nam))\n nams\n\nlemma nat.eq_symm (x y : ℕ) (h : x = y) :\n y = x :=\nby prove_direct\n\nlemma nat.eq_symm₂ (x y : ℕ) (h : x = y) :\n y = x :=\nby library_search\n\nlemma list.reverse_twice (xs : list ℕ) :\n list.reverse (list.reverse xs) = xs :=\nby prove_direct\n\nlemma list.reverse_twice_symm (xs : list ℕ) :\n xs = list.reverse (list.reverse xs) :=\nby prove_direct -- fails\n\n/-! As a small refinement, we propose a version of `prove_direct` that also\nlooks for equalities stated in symmetric form. -/\n\nmeta def prove_direct_symm : tactic unit :=\nprove_direct\n<|>\ndo {\n tactic.applyc `eq.symm,\n prove_direct }\n\nlemma list.reverse_twice₂ (xs : list ℕ) :\n list.reverse (list.reverse xs) = xs :=\nby prove_direct_symm\n\nlemma list.reverse_twice_symm₂ (xs : list ℕ) :\n xs = list.reverse (list.reverse xs) :=\nby prove_direct_symm\n\n\n/-! ## A Look at Two Predefined Tactics\n\nQuite a few of Lean's predefined tactics are implemented as metaprograms and\nnot in C++. We can find these definitions by clicking the name of a construct\nin Visual Studio Code while holding the control or command key. -/\n\n#check tactic.intro\n#check tactic.assumption\n\nend LoVe\n", "meta": {"author": "BrownCS1951x", "repo": "fpv2021", "sha": "10bdbd92e64fb34115b68794b8ff480468f4dcaa", "save_path": "github-repos/lean/BrownCS1951x-fpv2021", "path": "github-repos/lean/BrownCS1951x-fpv2021/fpv2021-10bdbd92e64fb34115b68794b8ff480468f4dcaa/src/exercises/love07_metaprogramming_demo.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2538610069692489, "lm_q2_score": 0.08632347188514872, "lm_q1q2_score": 0.0219141634978455}} {"text": "/-\nCopyright (c) 2023 Thomas Murrills. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Thomas Murrills\n-/\nimport Lean\n\n/-!\n# Fail if no progress\n\nThis implements the `fail_if_no_progress` tactic, which fails if no actual progress is made by the\nfollowing tactic sequence.\n\n\"Actual progress\" means that either the number of goals has changed, that the\nnumber or presence of expressions in the context has changed, or that the type of some expression\nin the context or the type of the goal is no longer definitionally equal to what it used to be at\nreducible transparency.\n\nThis means that, for example, `1 - 1` changing to `0` does not count as actual progress, since\n```lean\nexample : (1 - 1 = 0) := by with_reducible rfl\n```\n\nThis tactic is useful in situations where we want to stop iterating some tactics if they're not\nhaving any effect, e.g. `repeat (fail_if_no_progress simp <;> ring_nf)`.\n\n-/\n\nnamespace Mathlib.Tactic\n\nopen Lean Meta Elab Tactic\n\n/-- `fail_if_no_progress tacs` evaluates `tacs`, and fails if no progress is made on the main goal\nor the local context at reducible transparency. -/\nsyntax (name := failIfNoProgress ) \"fail_if_no_progress \" tacticSeq : tactic\n\n/-- `lctxIsDefEq l₁ l₂` compares two lists of `Option LocalDecl`s (as returned from e.g.\n`(← (← getMainGoal).getDecl).lctx.decls.toList`). It returns `true` if they contain expressions of\nthe same type in the same order (up to defeq), and `false` otherwise. -/\ndef lctxIsDefEq : (l₁ l₂ : List (Option LocalDecl)) → MetaM Bool\n | some d₁ :: l₁, some d₂ :: l₂ => do\n unless (← withNewMCtxDepth <| isDefEq d₁.type d₂.type) do\n return false\n lctxIsDefEq l₁ l₂\n | none :: l₁, none :: l₂ => lctxIsDefEq l₁ l₂\n | [], [] => return true\n | _, _ => return false\n\n/-- Run `tacs : TacticM Unit` on `goal`, and fail if no progress is made. -/\ndef runAndFailIfNoProgress (goal : MVarId) (tacs : TacticM Unit) : TacticM (List MVarId) := do\n let l ← run goal tacs\n try\n let [newGoal] := l | failure\n guard <|← withNewMCtxDepth <| withReducible <| isDefEq (← newGoal.getType) (← goal.getType)\n let ctxDecls := (← goal.getDecl).lctx.decls.toList\n let newCtxDecls := (← newGoal.getDecl).lctx.decls.toList\n guard <|← withNewMCtxDepth <| withReducible <| lctxIsDefEq ctxDecls newCtxDecls\n catch _ =>\n return l\n throwError \"no progress made on {goal}\"\n\nelab_rules : tactic\n| `(tactic| fail_if_no_progress $tacs) => do\n let goal ← getMainGoal\n let l ← runAndFailIfNoProgress goal (evalTactic tacs)\n replaceMainGoal l\n", "meta": {"author": "leanprover-community", "repo": "mathlib4", "sha": "b9a0a30342ca06e9817e22dbe46e75fc7f435500", "save_path": "github-repos/lean/leanprover-community-mathlib4", "path": "github-repos/lean/leanprover-community-mathlib4/mathlib4-b9a0a30342ca06e9817e22dbe46e75fc7f435500/Mathlib/Tactic/FailIfNoProgress.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.25386100696924885, "lm_q2_score": 0.08632347129750852, "lm_q1q2_score": 0.02191416334866656}} {"text": "example [Subsingleton α] (p : α → Prop) : Subsingleton (Subtype p) :=\n ⟨fun ⟨x, _⟩ ⟨y, _⟩ => Subsingleton.elim x y ▸ sorry⟩\n", "meta": {"author": "leanprover", "repo": "lean4", "sha": "742d053a97bdd109a41a921facd1cd6a55e89bc7", "save_path": "github-repos/lean/leanprover-lean4", "path": "github-repos/lean/leanprover-lean4/lean4-742d053a97bdd109a41a921facd1cd6a55e89bc7/tests/lean/run/1575.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.414898860266261, "lm_q2_score": 0.05261895631901726, "lm_q1q2_score": 0.021831545005160432}} {"text": "import .def_coords\n\nuniverse u\n\nnamespace o_minimal\n\nopen_locale finvec\n\nvariables {R : Type u} (S : struc R)\n\n-- We set up a minimal theory of (literal) definable subsets of Rⁿ\n-- and definable functions between them.\n\n/-- A bundled definable subset of some Rⁿ. -/\nstructure Def : Type u :=\n(ambdim : ℕ)\n(to_set : set (finvec ambdim R))\n(is_definable : S.definable to_set)\n\nvariables {S}\n\ninstance : has_coe_to_sort (Def S) :=\n⟨Type u, λ X, X.to_set⟩\n\nlemma Def.is_def_coords (X : Def S) : S.def_coords (set.univ : set X) :=\nbegin\n unfold struc.def_coords,\n convert X.is_definable,\n simp\nend\n\nvariables (S)\n\ndef struc.definable_fun {X Y : Def S} (f : X → Y) : Prop :=\nS.def_coords {z : X × Y | f z.1 = z.2}\n\nvariables {S}\n\n@[ext] structure Hom (X Y : Def S) : Type u :=\n(to_fun : X → Y)\n(is_definable : S.definable_fun to_fun)\n\ninstance {X Y : Def S} : has_coe_to_fun (Hom X Y) :=\n⟨_, λ f, f.to_fun⟩\n\n--instance : category_theory.has_hom (Def S) := { hom := Hom }\nlocal infixr ` ⟶ `:10 := Hom\n\n@[simp] lemma Hom.to_fun_eq_coe {X Y : Def S} (f : X ⟶ Y) :\n f.to_fun = f :=\nrfl\n\n-- TODO float out proofs of definability of identity, composition\n-- (useful later in presheaf stuff, notably representable instance)\n\ndef Def.id (X : Def S) : X ⟶ X :=\n{ to_fun := id,\n is_definable := struc.def_coords.diag X.is_def_coords }\n\ndef Hom.comp {X Y Z : Def S} (g : Y ⟶ Z) (f : X ⟶ Y) : X ⟶ Z :=\n{ to_fun := g.to_fun ∘ f.to_fun,\n is_definable := begin\n suffices : S.def_coords {p : X × Z | ∃ y, f p.1 = y ∧ g y = p.2},\n { convert this,\n ext ⟨x, z⟩,\n simp [struc.definable_fun] },\n have dXZY : S.def_coords (set.univ : set ((X × Z) × Y)) :=\n (X.is_def_coords.prod_univ Z.is_def_coords).prod_univ Y.is_def_coords,\n apply struc.def_coords.exists,\n apply struc.def_coords.inter,\n { let φ : (X × Z) × Y → X × Y := λ p, (p.1.1, p.2),\n have : is_reindexing R φ :=\n is_reindexing.prod R ((is_reindexing.fst R).comp R (is_reindexing.fst R)) (is_reindexing.snd R),\n refine struc.def_coords.reindex dXZY this f.is_definable },\n { let φ : (X × Z) × Y → Y × Z := λ p, (p.2, p.1.2),\n have : is_reindexing R φ :=\n is_reindexing.prod R (is_reindexing.snd R) ((is_reindexing.snd R).comp R (is_reindexing.fst R)),\n refine struc.def_coords.reindex dXZY this g.is_definable },\n end }\n\nlemma Hom.comp_id {X Y : Def S} (f : X ⟶ Y) : f.comp (Def.id X) = f :=\nby { ext, refl }\n\nlemma Hom.id_comp {X Y : Def S} (f : X ⟶ Y) : (Def.id Y).comp f = f :=\nby { ext, refl }\n\nlemma Hom.comp_assoc {W X Y Z : Def S} (h : Y ⟶ Z) (g : X ⟶ Y) (f : W ⟶ X) :\n (h.comp g).comp f = h.comp (g.comp f) :=\nrfl\n\ndef pt : Def S :=\n{ ambdim := 0,\n to_set := set.univ,\n is_definable := S.definable_univ 0 }\n\ninstance pt.unique : unique (pt : Def S) :=\n⟨⟨⟨fin_zero_elim, trivial⟩⟩, λ x, by { ext i, fin_cases i }⟩\n\n/-! ### Presheaf stuff -/\n\nvariables (S)\n\n-- TODO: generalize to Sort?\nclass definable_psh (X : Type*) :=\n(definable : Π {K : Def S}, (K → X) → Prop)\n(definable_precomp : ∀ {L K : Def S} (φ : L ⟶ K) {f : K → X},\n definable f → definable (f ∘ φ))\n\n-- TODO: apply bug??\ndef definable {X : Type*} [definable_psh S X] (x : X) : Prop :=\ndefinable_psh.definable (λ (_ : (pt : Def S)), x)\n\nvariables {S}\n\ndef definable_psh.definable' {X : Type*} (h : definable_psh S X) {K : Def S} (f : K → X) : Prop :=\ndefinable_psh.definable f\n\ninstance Def.definable_psh (X : Def S) : definable_psh S X :=\n{ definable := λ K f, S.definable_fun f,\n definable_precomp := begin\n rintros L K φ f h,\n exact ((⟨f, h⟩ : K ⟶ X).comp φ).is_definable\n end }\n\nlemma pt.definable {K : Def S} {f : K → (pt : Def S)} : definable_psh.definable f :=\nbegin\n change S.definable _,\n convert K.is_def_coords using 1,\n ext x,\n split,\n { rintros ⟨⟨k, p⟩, -, rfl⟩,\n refine ⟨k, trivial, _⟩,\n simp },\n { rintros ⟨k, -, rfl⟩,\n refine ⟨⟨k, default _⟩, show _ = _, by cc, _⟩,\n simp }\nend\n\ninstance {X Y : Type*} [definable_psh S X] [definable_psh S Y] : definable_psh S (X × Y) :=\n{ definable := λ K f, definable_psh.definable (prod.fst ∘ f) ∧ definable_psh.definable (prod.snd ∘ f),\n definable_precomp := begin\n rintros L K φ _ ⟨h₁, h₂⟩,\n exact ⟨definable_psh.definable_precomp φ h₁, definable_psh.definable_precomp φ h₂⟩,\n end }\n\ninstance function.definable_psh {X Y : Type*} [hX : definable_psh S X] [hY : definable_psh S Y] :\n definable_psh S (X → Y) :=\n{ definable := λ K f, ∀ (M : Def S) {g : M → K × X} (h : definable_psh.definable g),\n definable_psh.definable (function.uncurry f ∘ g),\n definable_precomp := λ L K φ f hf M g hg, begin\n suffices : definable_psh.definable (λ m, (φ (g m).1, (g m).2)),\n { apply hf M this },\n split,\n { exact definable_psh.definable_precomp ⟨λ m, (g m).1, hg.1⟩\n (show definable_psh.definable φ, from φ.is_definable) },\n { exact hg.2 }\n end }\n\nlemma definable_fun {X Y : Type*} [definable_psh S X] [definable_psh S Y]\n {f : X → Y} : definable S f ↔\n ∀ {K : Def S} (φ : K → X), definable_psh.definable φ → definable_psh.definable (f ∘ φ) :=\nbegin\n split; intro H,\n { intros K φ hφ,\n -- TODO: This proof is awkward\n specialize H K,\n swap,\n { exact (λ k, (default _, φ k)) },\n exact H ⟨pt.definable, hφ⟩ },\n { intros K φ hφ,\n exact H _ hφ.2 }\nend\n\nlemma definable_app {X Y : Type*} [definable_psh S X] [definable_psh S Y]\n {f : X → Y} (hf : definable S f) {x : X} (hx : definable S x) : definable S (f x) :=\nbegin\n rw definable_fun at hf,\n exact hf _ hx\nend\n\nlemma definable.app_ctx {Γ X Y : Type*} [definable_psh S Γ] [definable_psh S X] [definable_psh S Y]\n {f : Γ → X → Y} (hf : definable S f) {x : Γ → X} (hx : definable S x) :\n definable S (λ γ, f γ (x γ)) :=\nbegin\n rw definable_fun at ⊢ hf hx,\n intros K φ hφ,\n change definable_psh.definable (λ k, f (φ k) (x (φ k))),\n specialize hf φ hφ,\n specialize hf K,\n swap, { exact λ k, (k, x (φ k)) },\n exact hf ⟨(Def.id K).is_definable, hx φ hφ⟩\nend\n\nlemma definable_yoneda {K : Def S} {X : Type*} [definable_psh S X]\n {f : K → X} : definable_psh.definable f ↔ definable S f :=\nbegin\n rw definable_fun,\n split,\n { intros h L φ hφ,\n exact definable_psh.definable_precomp ⟨φ, hφ⟩ h },\n { intros H,\n refine H id _,\n exact (Def.id K).is_definable }\nend\n\nlemma definable_prod_mk {X Y : Type*} [definable_psh S X] [definable_psh S Y] :\n definable S (prod.mk : X → Y → X × Y) :=\n-- I have no idea how to come up with these proofs.\n-- Maybe we should tweak the type of definable_precomp (or write a lemma)\n-- that takes the underlying map φ and its proof of definability separately\n-- so that Lean has a better chance of guessing what's happening?\nλ L g h L' g' h',\n⟨definable_psh.definable_precomp ⟨λ x, (g' x).fst, h'.1⟩ h.2, h'.2⟩\n\nlemma definable_fst {X Y : Type*} [definable_psh S X] [definable_psh S Y] :\n definable S (prod.fst : X × Y → X) :=\nbegin\n rw definable_fun,\n intros K φ hφ,\n exact hφ.1\nend\n\nlemma definable_snd {X Y : Type*} [definable_psh S X] [definable_psh S Y] :\n definable S (prod.snd : X × Y → Y) :=\nbegin\n rw definable_fun,\n intros K φ hφ,\n exact hφ.2\nend\n\nlemma definable.prod_mk {W X Y : Type*} [definable_psh S W] [definable_psh S X] [definable_psh S Y]\n {f : W → X} (hf : definable S f) {g : W → Y} (hg : definable S g) :\n definable S (λ w, (f w, g w)) :=\nbegin\n rw definable_fun at ⊢ hf hg,\n intros K φ hφ,\n exact ⟨hf φ hφ, hg φ hφ⟩\nend\n\nlemma definable_fun₂ {X Y Z : Type*} [definable_psh S X] [definable_psh S Y] [definable_psh S Z]\n {f : X → Y → Z} :\n (∀ {L : Def S} (φ : L → X), definable S φ → definable S (f ∘ φ)) ↔\n (∀ {L : Def S} (φ : L → X × Y), definable S φ → definable S (function.uncurry f ∘ φ)) :=\nbegin\n split; intro H,\n { intros L φ hφ,\n rw definable_fun at ⊢,\n intros K ψ hψ,\n have : definable S (prod.fst ∘ φ),\n { rw ←definable_yoneda at ⊢ hφ,\n exact hφ.1 },\n specialize H (λ l, (φ l).1) this,\n rw definable_fun at H,\n specialize H ψ hψ,\n specialize H K,\n swap, { exact λ k, (k, (φ (ψ k)).2) },\n refine H ⟨(Def.id K).is_definable, _⟩, clear H,\n rw ←definable_yoneda at hφ,\n exact definable_psh.definable_precomp ⟨ψ, hψ⟩ hφ.2 },\n { intros L φ hφ,\n rw definable_fun,\n intros K ψ hψ,\n intros K' ψ' hψ',\n dsimp [function.uncurry, function.comp],\n specialize H (λ k', (φ (ψ (ψ' k').1), (ψ' k').2)),\n have : definable S (λ k', (φ (ψ (ψ' k').1), (ψ' k').2)),\n { rw ←definable_yoneda at ⊢ hφ,\n split,\n { refine definable_psh.definable_precomp ⟨λ k', ψ (ψ' k').fst, _⟩ hφ,\n exact (Hom.comp ⟨ψ, hψ⟩ ⟨_, hψ'.1⟩).is_definable },\n { exact hψ'.2 } },\n specialize H this,\n rw definable_fun at H,\n exact H _ (Def.id _).is_definable }\nend\n\nlemma definable_comp {X Y Z : Type*} [definable_psh S X] [definable_psh S Y] [definable_psh S Z] :\n definable S (function.comp : (Y → Z) → (X → Y) → (X → Z)) :=\nbegin\n -- TODO: Make these 4 lines a lemma.\n rw definable_fun,\n intros L₁ φ₁ hφ₁,\n rw definable_yoneda at ⊢ hφ₁,\n revert L₁,\n -- end lemma\n rw definable_fun₂,\n rw definable_fun₂,\n rintros L φ hφ,\n rw ←definable_yoneda at hφ,\n obtain ⟨⟨hφ₁, hφ₂⟩, hφ₃⟩ := hφ,\n rw definable_yoneda at hφ₁ hφ₂ hφ₃,\n dsimp [function.uncurry, function.comp],\n exact hφ₁.app_ctx (hφ₂.app_ctx hφ₃)\nend\n\nlemma definable.comp {X Y Z : Type*} [definable_psh S X] [definable_psh S Y] [definable_psh S Z]\n {g : Y → Z} (hg : definable S g) {f : X → Y} (hf : definable S f) :\n definable S (g ∘ f) :=\ndefinable_app (definable_app definable_comp hg) hf\n\nlemma definable.comp_ctx {Γ X Y Z : Type*} [definable_psh S Γ] [definable_psh S X] [definable_psh S Y] [definable_psh S Z]\n {g : Γ → Y → Z} (hg : definable S g) {f : Γ → X → Y} (hf : definable S f) :\n definable S (λ γ, g γ ∘ f γ) :=\ndefinable.app_ctx (definable.comp definable_comp hg) hf\n\nlemma definable_curry {X Y Z : Type*} [definable_psh S X] [definable_psh S Y] [definable_psh S Z] :\n definable S (function.curry : (X × Y → Z) → X → Y → Z) :=\nbegin\n -- TODO: Make these 4 lines a lemma.\n rw definable_fun,\n intros L₁ φ₁ hφ₁,\n rw definable_yoneda at ⊢ hφ₁,\n revert L₁,\n -- end lemma\n rw definable_fun₂,\n rw definable_fun₂,\n rintros L φ hφ,\n rw ←definable_yoneda at hφ,\n obtain ⟨⟨hφ₁, hφ₂⟩, hφ₃⟩ := hφ,\n rw definable_yoneda at hφ₁ hφ₂ hφ₃,\n exact definable.app_ctx hφ₁ (hφ₂.prod_mk hφ₃)\nend\n\ninstance Prop.definable_psh : definable_psh S Prop :=\n{ definable := λ K s, S.def_coords s,\n definable_precomp := λ L K φ f hf, sorry } -- preimage\n\ninstance set.definable_psh {X : Type*} [definable_psh S X] : definable_psh S (set X) :=\nshow definable_psh S (X → Prop), by apply_instance\n\nlemma definable_and : definable S (∧) :=\nbegin\n suffices : definable S (λ r : Prop × Prop, r.1 ∧ r.2),\n { exact definable_app definable_curry this },\n rw definable_fun,\n rintros K φ ⟨hφ₁, hφ₂⟩,\n exact hφ₁.inter hφ₂\nend\n\nlemma definable.and {W : Type*} [definable_psh S W]\n {f : W → Prop} (hf : definable S f) {g : W → Prop} (hg : definable S g) :\n definable S (λ w, f w ∧ g w) :=\ndefinable.app_ctx (definable.comp definable_and hf) hg\n\nlemma definable_inter {X : Type*} [definable_psh S X] :\n definable S ((∩) : set X → set X → set X) :=\nbegin\n suffices : definable S (λ (r : set X × set X) (x : X), r.1 x ∧ r.2 x),\n { exact (definable_app definable_curry this : _) },\n -- TODO: Make these 4 lines a lemma.\n rw definable_fun,\n intros L₁ φ₁ hφ₁,\n rw definable_yoneda at ⊢ hφ₁,\n revert L₁,\n -- end lemma\n rw definable_fun₂,\n intros L φ hφ,\n rw ←definable_yoneda at hφ,\n obtain ⟨⟨hφ₁, hφ₂⟩, hφ₃⟩ := hφ,\n rw definable_yoneda at hφ₁ hφ₂ hφ₃,\n apply definable.and,\n { exact hφ₁.app_ctx hφ₃ },\n { exact hφ₂.app_ctx hφ₃ }\nend\n\n/-\ninstance foo {X Y : Type*} [definable_psh S X] [definable_psh S Y]\n {p : X → Prop}\n : definable_psh S (Π (x : X) (h : p x), Y) :=\nsorry\n-/\n\nlemma definable_definable {X : Type*} [definable_psh S X] :\n definable S (definable S : X → Prop) :=\nbegin\n rw definable_fun,\n intros K φ hφ,\n change S.def_coords _,\n convert K.is_def_coords,\n apply set.eq_univ_of_forall,\n intro x,\n change definable S (φ x),\n apply definable_app,\n { rw ←definable_yoneda, exact hφ },\n -- now we need to know that every point of a representable guy\n -- is definable. this needs definable constants!\n sorry\n -- In general, the definable elements of a structure\n -- might or might not form a definable set.\n -- Counterexample: take (ℝ, +, *) without constants;\n -- definable elements are the algebraic real numbers,\n -- but only tame sets can be definable.\n -- However, once the structure has definable constants,\n -- then everything is definable and of course the set `univ` is definable.\nend\n-- Important note: it is definitely *not* true that\n-- `definable S` = `set.univ` on *every* X with a definable_psh structure;\n-- just represented guys.\n\n/-\nsimilarly, in an o-minimal structure:\n\nlemma definable_finite [DUNLO R] [o_minimal S] :\n definable S (set.finite : set R → Prop) := sorry\n\nbecause \"finite\" is equivalent to \"does not contain an interval\"\non the tame = definable sets, which are the only ones that matter.\n-/\n\ninstance self : definable_psh S R := sorry\n\nvariables (S)\n\n#exit\nclass definable_fam {X : Type*} [definable_psh S X] (Y : X → Sort*) :=\n(definable : Π {K : Def S} (x : K → X) (hx : definable_psh.definable x), (Π k, Y (x k)) → Prop)\n-- s.t. blah blah blah...\n\ninstance moo {X : Type*} {Y : X → Type*} [definable_psh S X] [definable_fam S Y] :\n definable_psh S (Π (x : X), Y x) :=\nsorry\n\nconstant choice : Π (X : set R), X.nonempty → X\n\nexample : definable S (set.nonempty : set R → Prop) :=\nsorry\n\ninstance : definable_fam S (set.nonempty : set R → Prop) := sorry\n\ninstance pi {X : Type*} [definable_psh S X] {Y Z : X → Sort*} [definable_fam S Y] [definable_fam S Z] :\n definable_fam S (λ x, Y x → Z x) :=\nsorry\n\ninstance subtype {X : Type*} [definable_psh S X] : definable_fam S (λ (s : set X), s) :=\nsorry\n\nexample : definable S ((λ x hx₁ hx₂, choice x hx₁) : Π (X : set R), X.nonempty → X.nonempty → X) :=\nsorry\n\n-- can we do without this `definable_fam` stuff? even as a hack?\n-- or maybe stick with this for now?\n\n/- TODO:\n* class represented [has_coordinates R X] expressing compatibility\n* prove this notion of definability of functions, sets reduces\n to the original one in the represented case\nThen:\n* prove stuff like `is_least : set R → R → Prop` is definable\n-/\n\nend o_minimal\n", "meta": {"author": "rwbarton", "repo": "lean-omin", "sha": "fd733c6d95ef6f4743aae97de5e15df79877c00e", "save_path": "github-repos/lean/rwbarton-lean-omin", "path": "github-repos/lean/rwbarton-lean-omin/lean-omin-fd733c6d95ef6f4743aae97de5e15df79877c00e/omin/presheaf2.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4843800842769843, "lm_q2_score": 0.04468086597932324, "lm_q1q2_score": 0.021642521628633234}} {"text": "/-\nCopyright (c) 2020 Eric Wieser. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Eric Wieser\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.default\nimport Mathlib.PostPort\n\nuniverses u_1 u_2 \n\nnamespace Mathlib\n\n/-!\n# Extra facts about `pprod`\n-/\n\n@[simp] theorem pprod.mk.eta {α : Sort u_1} {β : Sort u_2} {p : PProd α β} :\n { fst := pprod.fst p, snd := pprod.snd p } = p :=\n pprod.cases_on p fun (a : α) (b : β) => rfl\n\nend Mathlib", "meta": {"author": "AurelienSaue", "repo": "Mathlib4_auto", "sha": "590df64109b08190abe22358fabc3eae000943f2", "save_path": "github-repos/lean/AurelienSaue-Mathlib4_auto", "path": "github-repos/lean/AurelienSaue-Mathlib4_auto/Mathlib4_auto-590df64109b08190abe22358fabc3eae000943f2/Mathlib/data/pprod_auto.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.334589441253186, "lm_q2_score": 0.06465348204835548, "lm_q1q2_score": 0.021632372433632155}} {"text": "import tactic.interactive\n\nexample (b : bool) (h : b = tt) : true :=\nbegin\n let b₁ : bool := b,\n /-\n This test shows that `tactic.revert_target_deps`\n will revert `b₁` because it occurse in the `have` statement below,\n but recursively also reverts `b` (and hence `h`),\n because `b` occurs in the body of the `let` statement that introduces `b₁`,\n even though `b` doesn't occur directly in the `have` statement below.\n -/\n have : ∀ b₂ : bool, b₂ ≠ b₁ → b₂ = ff,\n { revert_target_deps,\n tactic.interactive.guard_target\n ``(∀ (b : bool), b = tt → (let b₁ : bool := b in ∀ (b₂ : bool), b₂ ≠ b₁ → b₂ = ff)),\n exact dec_trivial },\n trivial\nend\n", "meta": {"author": "leanprover-community", "repo": "mathlib", "sha": "5e526d18cea33550268dcbbddcb822d5cde40654", "save_path": "github-repos/lean/leanprover-community-mathlib", "path": "github-repos/lean/leanprover-community-mathlib/mathlib-5e526d18cea33550268dcbbddcb822d5cde40654/test/revert_target_deps.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.3923368301671084, "lm_q2_score": 0.055005285969780236, "lm_q1q2_score": 0.0215805995398189}} {"text": "import tactic.linarith\nimport category_theory.shift\nimport algebra.homology.homological_complex\nimport algebra.homology.homotopy_category\nimport for_mathlib.category_theory.quotient_shift\nimport for_mathlib.algebra.homology.hom_complex\nimport for_mathlib.category_theory.shift_misc\n\nnoncomputable theory\n\nopen category_theory category_theory.category category_theory.limits\n\nvariables (C : Type*) [category C] [preadditive C]\n\nnamespace cochain_complex\n\nopen homological_complex\n\nlocal attribute [simp] X_iso_of_eq_hom_naturality X_iso_of_eq_inv_naturality\n\n@[simps obj_d map_f]\ndef shift_functor (n : ℤ) : cochain_complex C ℤ ⥤ cochain_complex C ℤ :=\n{ obj := λ K,\n { X := λ i, K.X (i+n),\n d := λ i j, cochain_complex.hom_complex.ε n • K.d _ _,\n shape' := λ i j hij, begin\n rw [K.shape, smul_zero],\n intro hij',\n apply hij,\n dsimp [complex_shape.up] at hij' ⊢,\n linarith,\n end, },\n map := λ K₁ K₂ φ,\n { f := λ i, φ.f _, }, }\n\nvariable {C}\n\n@[simp]\nlemma X_iso_of_eq_of_shift_functor (K : cochain_complex C ℤ) (n : ℤ) {i i' : ℤ} (h : i = i') :\n ((shift_functor C n).obj K).X_iso_of_eq h = K.X_iso_of_eq (by subst h) := rfl\n\n@[simp]\ndef shift_functor_obj_X_iso (K : cochain_complex C ℤ) (n i m : ℤ) (hm : m = i + n) :\n ((shift_functor C n).obj K).X i ≅ K.X m :=\nX_iso_of_eq K hm.symm\n\nvariable (C)\n\n@[simp]\ndef shift_functor_congr {n n' : ℤ} (h : n = n') :\n shift_functor C n ≅ shift_functor C n' :=\nnat_iso.of_components\n (λ K, hom.iso_of_components (λ i, K.X_iso_of_eq (by subst h))\n (λ i j hij, by { dsimp, simp [h], })) (λ K₁ K₂ φ, by { ext, dsimp, simp, })\n\n@[simps]\ndef shift_functor_zero' (n : ℤ) (h : n = 0) :\n shift_functor C n ≅ 𝟭 _ :=\nnat_iso.of_components (λ K, hom.iso_of_components\n (λ i, K.shift_functor_obj_X_iso _ _ _ (by linarith))\n (by { subst h, tidy, })) (by tidy)\n\n@[simps]\ndef shift_functor_add' (n₁ n₂ n₁₂ : ℤ) (h : n₁₂ = n₁ + n₂) :\n shift_functor C n₁ ⋙ shift_functor C n₂ ≅ shift_functor C n₁₂ :=\nnat_iso.of_components\n (λ K, hom.iso_of_components (λ i, K.X_iso_of_eq (by linarith))\n (λ i j hij, begin\n subst h,\n dsimp,\n simp only [linear.comp_smul, X_iso_of_eq_hom_comp_d, linear.smul_comp,\n d_comp_X_iso_of_eq_hom, ← mul_smul, ← cochain_complex.hom_complex.ε_add, add_comm n₁],\n end)) (by tidy)\n\ninstance : has_shift (cochain_complex C ℤ) ℤ :=\nhas_shift_mk _ _\n{ F := shift_functor C,\n ε := (shift_functor_zero' C _ rfl).symm,\n μ := λ n₁ n₂, shift_functor_add' C n₁ n₂ _ rfl,\n associativity := λ n₁ n₂ n₃ K, by { ext i, dsimp [X_iso_of_eq], simp, }, }\n\nvariable {C}\n\n@[simp]\nlemma shift_functor_map_f' {K L : cochain_complex C ℤ} (φ : K ⟶ L) (n p : ℤ) :\n ((category_theory.shift_functor (cochain_complex C ℤ) n).map φ).f p = φ.f (p+n) := rfl\n\n@[simp]\nlemma shift_functor_obj_d' (K : cochain_complex C ℤ) (n i j : ℤ) :\n ((category_theory.shift_functor (cochain_complex C ℤ) n).obj K).d i j =\n cochain_complex.hom_complex.ε n • K.d _ _ := rfl\n\nlemma shift_functor_add_inv_app_f (K : cochain_complex C ℤ) (a b n : ℤ) :\n ((shift_functor_add (cochain_complex C ℤ) a b).inv.app K : _ ⟶ _).f n =\n (K.X_iso_of_eq (by { dsimp, rw [add_comm a, add_assoc],})).hom := rfl\n\nlemma shift_functor_add_hom_app_f (K : cochain_complex C ℤ) (a b n : ℤ) :\n ((shift_functor_add (cochain_complex C ℤ) a b).hom.app K : _ ⟶ _).f n =\n (K.X_iso_of_eq (by { dsimp, rw [add_comm a, add_assoc],})).inv :=\nbegin\n haveI : is_iso (((shift_functor_add (cochain_complex C ℤ) a b).inv.app K : _ ⟶ _).f n),\n { rw shift_functor_add_inv_app_f,\n apply_instance, },\n rw [← cancel_mono (((shift_functor_add (cochain_complex C ℤ) a b).inv.app K : _ ⟶ _).f n),\n ← homological_complex.comp_f, iso.hom_inv_id_app, homological_complex.id_f,\n shift_functor_add_inv_app_f, iso.inv_hom_id],\nend\n\nlemma shift_functor_add_comm_hom_app_f (K : cochain_complex C ℤ) (a b n : ℤ) :\n ((shift_functor_add_comm (cochain_complex C ℤ) a b).hom.app K : _ ⟶ _).f n =\n (K.X_iso_of_eq (by { dsimp, simp only [add_assoc, add_comm a], })).hom :=\nbegin\n dsimp only [shift_functor_add_comm, iso.trans, iso.symm],\n simpa only [nat_trans.comp_app, homological_complex.comp_f,\n shift_functor_add_hom_app_f, shift_functor_add_inv_app_f,\n homological_complex.X_iso_of_eq, eq_to_iso.inv, eq_to_iso.hom, eq_to_hom_app,\n homological_complex.eq_to_hom_f, eq_to_hom_trans],\nend\n\nvariable (C)\n\nlemma shift_functor_add'_eq (a b c : ℤ) (h : c = a + b) :\n category_theory.shift_functor_add' (cochain_complex C ℤ) a b c h =\n (shift_functor_add' C a b c h).symm :=\nbegin\n subst h,\n dsimp only [category_theory.shift_functor_add'],\n ext K n,\n dsimp only [iso.trans, shift_functor_add', nat_iso.of_components,\n nat_trans.comp_app, homological_complex.comp_f, hom.iso_of_components],\n simp only [eq_to_hom_app, eq_to_hom_f, shift_functor_add_hom_app_f,\n X_iso_of_eq, eq_to_iso, eq_to_hom_trans, eq_to_hom_refl, nat_trans.id_app,\n homological_complex.id_f, id_comp],\nend\n\nlemma shift_functor_add_eq (a b : ℤ) :\n category_theory.shift_functor_add (cochain_complex C ℤ) a b =\n (shift_functor_add' C a b _ rfl).symm :=\nbegin\n ext1,\n rw ← shift_functor_add'_eq,\n dsimp [category_theory.shift_functor_add'],\n rw id_comp,\nend\n\nlemma shift_functor_zero_eq :\n (category_theory.shift_functor_zero (cochain_complex C ℤ) ℤ) =\n (shift_functor_zero' C 0 rfl) :=\nbegin\n change (category_theory.shift_functor_zero (cochain_complex C ℤ) ℤ).symm.symm =\n (shift_functor_zero' C 0 rfl).symm.symm,\n congr' 1,\n ext1,\n refl,\nend\n\nvariables {C} {D : Type*} [category D] (F : C ⥤ D) [preadditive D] [functor.additive F]\n\ndef map_cochain_complex_shift_iso (n : ℤ) :\n shift_functor C n ⋙ F.map_homological_complex (complex_shape.up ℤ) ≅\n F.map_homological_complex (complex_shape.up ℤ) ⋙ shift_functor D n :=\nnat_iso.of_components (λ K, hom.iso_of_components (λ i, iso.refl _)\n (λ i j hij, by { dsimp, rw [id_comp, comp_id, functor.map_zsmul], })) (by tidy)\n\ninstance map_cochain_complex_has_comm_shift :\n (functor.map_homological_complex F (complex_shape.up ℤ)).has_comm_shift ℤ :=\n{ iso := λ n, map_cochain_complex_shift_iso F n,\n iso_zero := begin\n ext K i,\n rw [functor.comm_shift.unit_hom_app, comp_f,\n functor.map_homological_complex_map_f, shift_functor_zero_eq,\n shift_functor_zero_eq,\n shift_functor_zero'_hom_app_f, shift_functor_zero'_inv_app_f],\n dsimp [X_iso_of_eq],\n simpa only [eq_to_hom_map, eq_to_hom_trans],\n end,\n iso_add := λ a b, begin\n ext K i,\n simp only [functor.comm_shift.add_hom_app, comp_f, iso.symm_inv,\n functor.map_homological_complex_map_f, shift_functor_add_eq, iso.symm_hom,\n shift_functor_add'_inv_app_f, shift_functor_add'_hom_app_f,\n shift_functor_map_f'],\n dsimp [map_cochain_complex_shift_iso, iso.refl,\n X_iso_of_eq],\n erw [eq_to_hom_map, id_comp, id_comp, eq_to_hom_trans, eq_to_hom_refl],\n end, }\n\nend cochain_complex\n", "meta": {"author": "joelriou", "repo": "homotopical_algebra", "sha": "697f49d6744b09c5ef463cfd3e35932bdf2c78a3", "save_path": "github-repos/lean/joelriou-homotopical_algebra", "path": "github-repos/lean/joelriou-homotopical_algebra/homotopical_algebra-697f49d6744b09c5ef463cfd3e35932bdf2c78a3/src/for_mathlib/algebra/homology/shift.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091946, "lm_q2_score": 0.0433658021638845, "lm_q1q2_score": 0.021513506863559746}} {"text": "class foo (F : Type) where\n foo : F\n\nclass foobar (F : outParam Type) [foo F] where\n bar : F\n\nclass C (α : Type) where\n val : α\n\nclass D (α : Type) (β : outParam Type) [C β] where\n val1 : α\n val2 : β := C.val\n\ninstance : C String where\n val := \"hello\"\n\ninstance : C Nat where\n val := 42\n\ninstance : D Nat String where\n val1 := 37\n\ndef f (α : Type) {β : Type} {_ : C β} [D α β] : α × β :=\n (D.val1, D.val2 α)\n\nexample : f Nat = (37, \"hello\") := rfl\n", "meta": {"author": "leanprover", "repo": "lean4", "sha": "742d053a97bdd109a41a921facd1cd6a55e89bc7", "save_path": "github-repos/lean/leanprover-lean4", "path": "github-repos/lean/leanprover-lean4/lean4-742d053a97bdd109a41a921facd1cd6a55e89bc7/tests/lean/run/1852.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48047867804790706, "lm_q2_score": 0.04468086995462597, "lm_q1q2_score": 0.021468205329829133}} {"text": "/-\nCopyright (c) 2020 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Leonardo de Moura\n-/\nimport Lean.MetavarContext\nimport Lean.Environment\nimport Lean.Util.FoldConsts\nimport Lean.Meta.Basic\nimport Lean.Meta.Check\n\n/-!\n\nThis module provides functions for \"closing\" open terms and\ncreating auxiliary definitions. Here, we say a term is \"open\" if\nit contains free/meta-variables.\n\nThe \"closure\" is performed by lambda abstracting the\nfree/meta-variables. Recall that in dependent type theory\nlambda abstracting a let-variable may produce type incorrect terms.\nFor example, given the context\n```lean\n(n : Nat := 20)\n(x : Vector α n)\n(y : Vector α 20)\n```\nthe term `x = y` is correct. However, its closure using lambda abstractions\nis not.\n```lean\nfun (n : Nat) (x : Vector α n) (y : Vector α 20) => x = y\n```\nA previous version of this module would address this issue by\nalways use let-expressions to abstract let-vars. In the example above,\nit would produce\n```lean\nlet n : Nat := 20; fun (x : Vector α n) (y : Vector α 20) => x = y\n```\nThis approach produces correct result, but produces unsatisfactory\nresults when we want to create auxiliary definitions.\nFor example, consider the context\n```lean\n(x : Nat)\n(y : Nat := fact x)\n```\nand the term `h (g y)`, now suppose we want to create an auxiliary definition for `y`.\n The previous version of this module would compute the auxiliary definition\n```lean\ndef aux := fun (x : Nat) => let y : Nat := fact x; h (g y)\n```\nand would return the term `aux x` as a substitute for `h (g y)`.\nThis is correct, but we will re-evaluate `fact x` whenever we use `aux`.\nIn this module, we produce\n```lean\ndef aux := fun (y : Nat) => h (g y)\n```\nNote that in this particular case, it is safe to lambda abstract the let-varible `y`.\nThis module uses the following approach to decide whether it is safe or not to lambda\nabstract a let-variable.\n1) We enable zeta-expansion tracking in `MetaM`. That is, whenever we perform type checking\n if a let-variable needs to zeta expanded, we store it in the set `zetaFVarIds`.\n We say a let-variable is zeta expanded when we replace it with its value.\n2) We use the `MetaM` type checker `check` to type check the expression we want to close,\n and the type of the binders.\n3) If a let-variable is not in `zetaFVarIds`, we lambda abstract it.\n\nRemark: We still use let-expressions for let-variables in `zetaFVarIds`, but we move the\n`let` inside the lambdas. The idea is to make sure the auxiliary definition does not have\nan interleaving of `lambda` and `let` expressions. Thus, if the let-variable occurs in\nthe type of one of the lambdas, we simply zeta-expand it there.\nAs a final example consider the context\n```lean\n(x_1 : Nat)\n(x_2 : Nat)\n(x_3 : Nat)\n(x : Nat := fact (10 + x_1 + x_2 + x_3))\n(ty : Type := Nat → Nat)\n(f : ty := fun x => x)\n(n : Nat := 20)\n(z : f 10)\n```\nand we use this module to compute an auxiliary definition for the term\n```lean\n(let y : { v : Nat // v = n } := ⟨20, rfl⟩; y.1 + n + f x, z + 10)\n```\nwe obtain\n```lean\ndef aux (x : Nat) (f : Nat → Nat) (z : Nat) : Nat×Nat :=\nlet n : Nat := 20;\n(let y : {v // v=n} := {val := 20, property := ex._proof_1}; y.val+n+f x, z+10)\n```\n\nBTW, this module also provides the `zeta : Bool` flag. When set to true, it\nexpands all let-variables occurring in the target expression.\n-/\n\nnamespace Lean.Meta\nnamespace Closure\n\nstructure ToProcessElement where\n fvarId : FVarId\n newFVarId : FVarId\n deriving Inhabited\n\nstructure Context where\n zeta : Bool\n\nstructure State where\n visitedLevel : LevelMap Level := {}\n visitedExpr : ExprStructMap Expr := {}\n levelParams : Array Name := #[]\n nextLevelIdx : Nat := 1\n levelArgs : Array Level := #[]\n newLocalDecls : Array LocalDecl := #[]\n newLocalDeclsForMVars : Array LocalDecl := #[]\n newLetDecls : Array LocalDecl := #[]\n nextExprIdx : Nat := 1\n exprMVarArgs : Array Expr := #[]\n exprFVarArgs : Array Expr := #[]\n toProcess : Array ToProcessElement := #[]\n\nabbrev ClosureM := ReaderT Context $ StateRefT State MetaM\n\n@[inline] def visitLevel (f : Level → ClosureM Level) (u : Level) : ClosureM Level := do\n if !u.hasMVar && !u.hasParam then\n pure u\n else\n let s ← get\n match s.visitedLevel.find? u with\n | some v => pure v\n | none => do\n let v ← f u\n modify fun s => { s with visitedLevel := s.visitedLevel.insert u v }\n pure v\n\n@[inline] def visitExpr (f : Expr → ClosureM Expr) (e : Expr) : ClosureM Expr := do\n if !e.hasLevelParam && !e.hasFVar && !e.hasMVar then\n pure e\n else\n let s ← get\n match s.visitedExpr.find? e with\n | some r => pure r\n | none =>\n let r ← f e\n modify fun s => { s with visitedExpr := s.visitedExpr.insert e r }\n pure r\n\ndef mkNewLevelParam (u : Level) : ClosureM Level := do\n let s ← get\n let p := (`u).appendIndexAfter s.nextLevelIdx\n modify fun s => { s with levelParams := s.levelParams.push p, nextLevelIdx := s.nextLevelIdx + 1, levelArgs := s.levelArgs.push u }\n pure $ mkLevelParam p\n\npartial def collectLevelAux : Level → ClosureM Level\n | u@(Level.succ v) => return u.updateSucc! (← visitLevel collectLevelAux v)\n | u@(Level.max v w) => return u.updateMax! (← visitLevel collectLevelAux v) (← visitLevel collectLevelAux w)\n | u@(Level.imax v w) => return u.updateIMax! (← visitLevel collectLevelAux v) (← visitLevel collectLevelAux w)\n | u@(Level.mvar ..) => mkNewLevelParam u\n | u@(Level.param ..) => mkNewLevelParam u\n | u@(Level.zero) => pure u\n\ndef collectLevel (u : Level) : ClosureM Level := do\n -- u ← instantiateLevelMVars u\n visitLevel collectLevelAux u\n\ndef preprocess (e : Expr) : ClosureM Expr := do\n let e ← instantiateMVars e\n let ctx ← read\n -- If we are not zeta-expanding let-decls, then we use `check` to find\n -- which let-decls are dependent. We say a let-decl is dependent if its lambda abstraction is type incorrect.\n if !ctx.zeta then\n check e\n pure e\n\n/--\n Remark: This method does not guarantee unique user names.\n The correctness of the procedure does not rely on unique user names.\n Recall that the pretty printer takes care of unintended collisions. -/\ndef mkNextUserName : ClosureM Name := do\n let s ← get\n let n := (`_x).appendIndexAfter s.nextExprIdx\n modify fun s => { s with nextExprIdx := s.nextExprIdx + 1 }\n pure n\n\ndef pushToProcess (elem : ToProcessElement) : ClosureM Unit :=\n modify fun s => { s with toProcess := s.toProcess.push elem }\n\npartial def collectExprAux (e : Expr) : ClosureM Expr := do\n let collect (e : Expr) := visitExpr collectExprAux e\n match e with\n | Expr.proj _ _ s => return e.updateProj! (← collect s)\n | Expr.forallE _ d b _ => return e.updateForallE! (← collect d) (← collect b)\n | Expr.lam _ d b _ => return e.updateLambdaE! (← collect d) (← collect b)\n | Expr.letE _ t v b _ => return e.updateLet! (← collect t) (← collect v) (← collect b)\n | Expr.app f a => return e.updateApp! (← collect f) (← collect a)\n | Expr.mdata _ b => return e.updateMData! (← collect b)\n | Expr.sort u => return e.updateSort! (← collectLevel u)\n | Expr.const _ us => return e.updateConst! (← us.mapM collectLevel)\n | Expr.mvar mvarId =>\n let mvarDecl ← mvarId.getDecl\n let type ← preprocess mvarDecl.type\n let type ← collect type\n let newFVarId ← mkFreshFVarId\n let userName ← mkNextUserName\n modify fun s => { s with\n newLocalDeclsForMVars := s.newLocalDeclsForMVars.push $ .cdecl default newFVarId userName type .default .default,\n exprMVarArgs := s.exprMVarArgs.push e\n }\n return mkFVar newFVarId\n | Expr.fvar fvarId =>\n match (← read).zeta, (← fvarId.getValue?) with\n | true, some value => collect (← preprocess value)\n | _, _ =>\n let newFVarId ← mkFreshFVarId\n pushToProcess ⟨fvarId, newFVarId⟩\n return mkFVar newFVarId\n | e => pure e\n\ndef collectExpr (e : Expr) : ClosureM Expr := do\n let e ← preprocess e\n visitExpr collectExprAux e\n\npartial def pickNextToProcessAux (lctx : LocalContext) (i : Nat) (toProcess : Array ToProcessElement) (elem : ToProcessElement)\n : ToProcessElement × Array ToProcessElement :=\n if h : i < toProcess.size then\n let elem' := toProcess.get ⟨i, h⟩\n if (lctx.get! elem.fvarId).index < (lctx.get! elem'.fvarId).index then\n pickNextToProcessAux lctx (i+1) (toProcess.set ⟨i, h⟩ elem) elem'\n else\n pickNextToProcessAux lctx (i+1) toProcess elem\n else\n (elem, toProcess)\n\ndef pickNextToProcess? : ClosureM (Option ToProcessElement) := do\n let lctx ← getLCtx\n let s ← get\n if s.toProcess.isEmpty then\n pure none\n else\n modifyGet fun s =>\n let elem := s.toProcess.back\n let toProcess := s.toProcess.pop\n let (elem, toProcess) := pickNextToProcessAux lctx 0 toProcess elem\n (some elem, { s with toProcess := toProcess })\n\ndef pushFVarArg (e : Expr) : ClosureM Unit :=\n modify fun s => { s with exprFVarArgs := s.exprFVarArgs.push e }\n\ndef pushLocalDecl (newFVarId : FVarId) (userName : Name) (type : Expr) (bi := BinderInfo.default) : ClosureM Unit := do\n let type ← collectExpr type\n modify fun s => { s with newLocalDecls := s.newLocalDecls.push <| .cdecl default newFVarId userName type bi .default }\n\npartial def process : ClosureM Unit := do\n match (← pickNextToProcess?) with\n | none => pure ()\n | some ⟨fvarId, newFVarId⟩ =>\n match (← fvarId.getDecl) with\n | .cdecl _ _ userName type bi _ =>\n pushLocalDecl newFVarId userName type bi\n pushFVarArg (mkFVar fvarId)\n process\n | .ldecl _ _ userName type val _ _ =>\n let zetaFVarIds ← getZetaFVarIds\n if !zetaFVarIds.contains fvarId then\n /- Non-dependent let-decl\n\n Recall that if `fvarId` is in `zetaFVarIds`, then we zeta-expanded it\n during type checking (see `check` at `collectExpr`).\n\n Our type checker may zeta-expand declarations that are not needed, but this\n check is conservative, and seems to work well in practice. -/\n pushLocalDecl newFVarId userName type\n pushFVarArg (mkFVar fvarId)\n process\n else\n /- Dependent let-decl -/\n let type ← collectExpr type\n let val ← collectExpr val\n modify fun s => { s with newLetDecls := s.newLetDecls.push <| .ldecl default newFVarId userName type val false .default }\n /- We don't want to interleave let and lambda declarations in our closure. So, we expand any occurrences of newFVarId\n at `newLocalDecls` -/\n modify fun s => { s with newLocalDecls := s.newLocalDecls.map (·.replaceFVarId newFVarId val) }\n process\n\n@[inline] def mkBinding (isLambda : Bool) (decls : Array LocalDecl) (b : Expr) : Expr :=\n let xs := decls.map LocalDecl.toExpr\n let b := b.abstract xs\n decls.size.foldRev (init := b) fun i b =>\n let decl := decls[i]!\n match decl with\n | .cdecl _ _ n ty bi _ =>\n let ty := ty.abstractRange i xs\n if isLambda then\n Lean.mkLambda n bi ty b\n else\n Lean.mkForall n bi ty b\n | .ldecl _ _ n ty val nonDep _ =>\n if b.hasLooseBVar 0 then\n let ty := ty.abstractRange i xs\n let val := val.abstractRange i xs\n mkLet n ty val b nonDep\n else\n b.lowerLooseBVars 1 1\n\ndef mkLambda (decls : Array LocalDecl) (b : Expr) : Expr :=\n mkBinding true decls b\n\ndef mkForall (decls : Array LocalDecl) (b : Expr) : Expr :=\n mkBinding false decls b\n\nstructure MkValueTypeClosureResult where\n levelParams : Array Name\n type : Expr\n value : Expr\n levelArgs : Array Level\n exprArgs : Array Expr\n\ndef mkValueTypeClosureAux (type : Expr) (value : Expr) : ClosureM (Expr × Expr) := do\n resetZetaFVarIds\n withTrackingZeta do\n let type ← collectExpr type\n let value ← collectExpr value\n process\n pure (type, value)\n\ndef mkValueTypeClosure (type : Expr) (value : Expr) (zeta : Bool) : MetaM MkValueTypeClosureResult := do\n let ((type, value), s) ← ((mkValueTypeClosureAux type value).run { zeta := zeta }).run {}\n let newLocalDecls := s.newLocalDecls.reverse ++ s.newLocalDeclsForMVars\n let newLetDecls := s.newLetDecls.reverse\n let type := mkForall newLocalDecls (mkForall newLetDecls type)\n let value := mkLambda newLocalDecls (mkLambda newLetDecls value)\n pure {\n type := type,\n value := value,\n levelParams := s.levelParams,\n levelArgs := s.levelArgs,\n exprArgs := s.exprFVarArgs.reverse ++ s.exprMVarArgs\n }\n\nend Closure\n\n/--\n Create an auxiliary definition with the given name, type and value.\n The parameters `type` and `value` may contain free and meta variables.\n A \"closure\" is computed, and a term of the form `name.{u_1 ... u_n} t_1 ... t_m` is\n returned where `u_i`s are universe parameters and metavariables `type` and `value` depend on,\n and `t_j`s are free and meta variables `type` and `value` depend on. -/\ndef mkAuxDefinition (name : Name) (type : Expr) (value : Expr) (zeta : Bool := false) (compile : Bool := true) : MetaM Expr := do\n let result ← Closure.mkValueTypeClosure type value zeta\n let env ← getEnv\n let decl := Declaration.defnDecl {\n name := name\n levelParams := result.levelParams.toList\n type := result.type\n value := result.value\n hints := ReducibilityHints.regular (getMaxHeight env result.value + 1)\n safety := if env.hasUnsafe result.type || env.hasUnsafe result.value then DefinitionSafety.unsafe else DefinitionSafety.safe\n }\n addDecl decl\n if compile then\n compileDecl decl\n return mkAppN (mkConst name result.levelArgs.toList) result.exprArgs\n\n/-- Similar to `mkAuxDefinition`, but infers the type of `value`. -/\ndef mkAuxDefinitionFor (name : Name) (value : Expr) (zeta : Bool := false) : MetaM Expr := do\n let type ← inferType value\n let type := type.headBeta\n mkAuxDefinition name type value (zeta := zeta)\n\nend Lean.Meta\n", "meta": {"author": "leanprover", "repo": "lean4", "sha": "742d053a97bdd109a41a921facd1cd6a55e89bc7", "save_path": "github-repos/lean/leanprover-lean4", "path": "github-repos/lean/leanprover-lean4/lean4-742d053a97bdd109a41a921facd1cd6a55e89bc7/src/Lean/Meta/Closure.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3960681662740416, "lm_q2_score": 0.054198732496667, "lm_q1q2_score": 0.02146639259433221}} {"text": "/-\nCopyright (c) 2022 Devon Tuma. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Devon Tuma\n-/\nimport computational_monads.simulation_semantics.simulate.basic\n\n/-!\n# Composition of Simulation Oracles\n\nThis file defines an operator `∘ₛ` for composing two simulation oracles in the natural way,\nsuch that simulation corresponds to a two step simulation by both.\n-/\n\nopen oracle_comp oracle_spec\n\nvariables {spec spec' spec'' : oracle_spec} {α β γ : Type} {S S' : Type}\n\nnamespace sim_oracle\n\n/-- Compose two `sim_oracles`, using the first oracle to simulate the queries of the second.\nFor example a random oracle is a uniform oracle composed with a cacheing oracle,\ni.e. one that caches previous responses and calls a uniform random oracle for any new queries.\nFor type inference reasons we list the arguments in the opposite order of `function.comp`. -/\ndef oracle_compose (so : sim_oracle spec spec' S) (so' : sim_oracle spec' spec'' S') :\n sim_oracle spec spec'' (S × S') :=\n{ default_state := (so.default_state, so'.default_state),\n o := λ i x, simulate so' (so i (x.1, x.2.1)) x.2.2 >>= λ u_s, return (u_s.1.1, u_s.1.2, u_s.2) }\n\n-- We use `notation` over `infixl` to swap the arguments without invoking `function.comp`.\nnotation so' `∘ₛ` so := oracle_compose so so'\n\nnamespace oracle_compose\n\nvariables (so : sim_oracle spec spec' S) (so' : sim_oracle spec' spec'' S')\n\nlemma apply_eq (i : spec.ι) (s : S × S') : (so' ∘ₛ so) i =\n λ x, simulate so' (so i (x.1, x.2.1)) x.2.2 >>= λ u_s, return (u_s.1.1, u_s.1.2, u_s.2) := rfl\n\nend oracle_compose\n\nend sim_oracle", "meta": {"author": "dtumad", "repo": "lean-crypto-formalization", "sha": "f975a9a9882120b509553a7ced9aa05b745ff154", "save_path": "github-repos/lean/dtumad-lean-crypto-formalization", "path": "github-repos/lean/dtumad-lean-crypto-formalization/lean-crypto-formalization-f975a9a9882120b509553a7ced9aa05b745ff154/src/computational_monads/simulation_semantics/oracle_compose.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4263215925474903, "lm_q2_score": 0.05033063206329864, "lm_q1q2_score": 0.021457035215147253}} {"text": "/-\n# Introduction\n\n## What's the goal of this book?\n\nThis book aims to build up enough knowledge about metaprogramming in Lean 4 so\nyou can be comfortable enough to:\n\n* Start building your own meta helpers\n* Read and discuss metaprogramming API's like the ones in Lean 4 core and\nMathlib4\n\nWe by no means intend to provide an exhaustive exploration/explanation of the\nentire Lean 4 metaprogramming API. We also don't cover the topic of monadic\nprogramming in Lean 4. However, we hope that the examples provided will be\nsimple enough for the reader to follow and comprehend without a super deep\nunderstanding of monadic programming. The book\n[Functional Programming in Lean](https://leanprover.github.io/functional_programming_in_lean/)\nis a highly recomended source on that subject.\n\n## Book structure\n\nThe book is organized in a way to build up enough content for the chapters that\ncover DSLs and tactics. Backtracking the pre-requisites for each chapter, the\ndependency structure is as follows:\n\n* \"Tactics\" builds on top of \"Macros\" and \"Elaboration\"\n* \"DSLs\" builds on top of \"Elaboration\"\n* \"Macros\" builds on top of \"`Syntax`\"\n* \"Elaboration\" builds on top of \"`Syntax`\" and \"`MetaM`\"\n* \"`MetaM`\" builds on top of \"Expressions\"\n\nAfter the chapter on tactics, you find a cheat-sheet containing a wrap-up of key\nconcepts and functions. And after that, There are some chapters with extra\ncontent, showing other applications of metaprogramming in Lean 4.\n\nThe rest of this chapter is a gentle introduction for what metaprogramming is,\noffering some small examples to serve as appetizers for what the book shall\ncover.\n\nNote: the code snippets aren't self-contained. They are supposed to be run/read\nincrementally,starting from the beginning of each chapter.\n\n## What does it mean to be in meta?\n\nWhen we write code in most programming languages such as Python, C, Java or\nScala, we usually have to stick to a pre-defined syntax otherwise the compiler\nor the interpreter won't be able to figure out what we're trying to say. In\nLean, that would be defining an inductive type, implementing a function, proving\na theorem etc. The compiler, then, has to parse the code, build an abstract\nsyntax tree and elaborate its syntax nodes into terms that can be processed by\nthe language kernel. We say that such activities performed by the compiler are\ndone in the __meta-level__, which will be studied throughout the book. And we\nalso say that the common usage of the language syntax is done in the\n__object-level__.\n\nIn most systems, the meta-level activities are done in a different language to\nthe one that we use to write code. In Isabelle, the meta-level language is ML\nand Scala. In Coq, it's OCaml. In Agda it's Haskell. In Lean 4, the meta code is\nmostly written in Lean itself, with a few components written in C++.\n\nOne cool thing about Lean, though, is that it allows us to define custom syntax\nnodes and to implement our own meta-level routines to elaborate those in the\nvery same development environment that we use to perform object-level\nactivities. So for example, one can write their own notation to instantiate a\nterm of a certain type and use it right away, on the same file! This concept is\ngenerally called\n[__reflection__](https://en.wikipedia.org/wiki/Reflective_programming). We can\nsay that, in Lean, the meta-level is _reflected_ to the object-level.\n\nSince the objects defined in the meta-level are not the ones we're most\ninterested in proving theorems about, it can sometimes be overly tedious to\nprove that they are type correct. For example, we don't care about proving that\na recursive function to traverse an expression is well founded. Thus, we can\nuse the `partial` keyword if we're convinced that our function terminates. In\nthe worst case scenario, our function gets stuck in a loop but the kernel is\nnot reached/affected.\n\nLet's see some example use cases of metaprogramming in Lean.\n\n## Metaprogramming examples\n\nThe following examples are meant for mere illustration. Don't worry if you don't\nunderstand the details for now.\n\n### Introducing notation (defining new syntax)\n\nOften one wants to introduce new notation, for example one more suitable for (a branch of) mathematics. For instance, in mathematics one would write the function adding `2` to a natural number as `x : Nat ↦ x + 2` or simply `x ↦ x + 2` if the domain can be inferred to be the natural numbers. The corresponding lean definitions `fun x : Nat => x + 2` and `fun x => x + 2` use `=>` which in mathematics means _implication_, so may be confusing to some.\n\nWe can introduce notation using a `macro` which transforms our syntax to lean's own syntax (or syntax we previously defined). Here we introduce the `↦` notation for functions.\n-/\nimport Lean\n\nmacro x:ident \":\" t:term \" ↦ \" y:term : term => do\n `(fun $x : $t => $y)\n\n#eval (x : Nat ↦ x + 2) 2 -- 4\n\nmacro x:ident \" ↦ \" y:term : term => do\n `(fun $x => $y)\n\n#eval (x ↦ x + 2) 2 -- 4\n/-!\n\n### Building a command\n\nSuppose we want to build a helper command `#assertType` which tells whether a\ngiven term is of a certain type. The usage will be:\n\n`#assertType : `\n\nLet's see the code:\n-/\nelab \"#assertType \" termStx:term \" : \" typeStx:term : command =>\n open Lean Lean.Elab Command Term in\n liftTermElabM\n try\n let tp ← elabType typeStx\n discard $ elabTermEnsuringType termStx tp\n synthesizeSyntheticMVarsNoPostponing\n logInfo \"success\"\n catch | _ => throwError \"failure\"\n\n#assertType 5 : Nat -- success\n#assertType [] : Nat -- failure\n\n/-! We started by using `elab` to define a `command` syntax, which, when parsed\nby the compiler, will trigger the incoming computation.\n\nAt this point, the code should be running in the `CommandElabM` monad. We then\nuse `liftTermElabM` to access the `TermElabM` monad, which allows us to use\n`elabType` and `elabTermEnsuringType` in order to build expressions out of the\nsyntax nodes `typeStx` and `termStx`.\n\nFirst we elaborate the expected type `tp : Expr` and then we use it to elaborate\nthe term expression, which should have the type `tp` otherwise an error will be\nthrown. The term expression itself doesn't matter to us here, as we're calling\n`elabTermEnsuringType` as a sanity check.\n\nWe also add `synthesizeSyntheticMVarsNoPostponing`, which forces Lean to\nelaborate metavariables right away. Without that line, `#assertType 5 : ?_`\nwould result in `success`.\n\nIf no error is thrown until now then the elaboration succeeded and we can use\n`logInfo` to output \"success\". If, instead, some error is caught, then we use\n`throwError` with the appropriate message.\n\n### Building a DSL and a syntax for it\n\nLet's parse a classic grammar, the grammar of arithmetic expressions with\naddition, multiplication, naturals, and variables. We'll define an AST\n(Abstract Syntax Tree) to encode the data of our expressions, and use operators\n`+` and `*` to denote building an arithmetic AST. Here's the AST that we will be\nparsing:\n-/\n\ninductive Arith : Type where\n | add : Arith → Arith → Arith -- e + f\n | mul : Arith → Arith → Arith -- e * f\n | nat : Nat → Arith -- constant\n | var : String → Arith -- variable\n\n/-! Now we declare a syntax category to describe the grammar that we will be\nparsing. Notice that we control the precedence of `+` and `*` by giving a lower\nprecedence weight to the `+` syntax than to the `*` syntax indicating that\nmultiplication binds tighter than addition (the higher the number, the tighter\nthe binding). This allows us to declare _precedence_ when defining new syntax.\n-/\n\ndeclare_syntax_cat arith\nsyntax num : arith -- nat for Arith.nat\nsyntax str : arith -- strings for Arith.var\nsyntax:50 arith:50 \" + \" arith:51 : arith -- Arith.add\nsyntax:60 arith:60 \" * \" arith:61 : arith -- Arith.mul\nsyntax \" ( \" arith \" ) \" : arith -- bracketed expressions\n\n-- Auxiliary notation for translating `arith` into `term`\nsyntax \" ⟪ \" arith \" ⟫ \" : term\n\n-- Our macro rules perform the \"obvious\" translation:\nmacro_rules\n | `(⟪ $s:str ⟫) => `(Arith.var $s)\n | `(⟪ $num:num ⟫) => `(Arith.nat $num)\n | `(⟪ $x:arith + $y:arith ⟫) => `(Arith.add ⟪ $x ⟫ ⟪ $y ⟫)\n | `(⟪ $x:arith * $y:arith ⟫) => `(Arith.mul ⟪ $x ⟫ ⟪ $y ⟫)\n | `(⟪ ( $x ) ⟫) => `( ⟪ $x ⟫ )\n\n#check ⟪ \"x\" * \"y\" ⟫\n-- Arith.mul (Arith.var \"x\") (Arith.var \"y\") : Arith\n\n#check ⟪ \"x\" + \"y\" ⟫\n-- Arith.add (Arith.var \"x\") (Arith.var \"y\") : Arith\n\n#check ⟪ \"x\" + 20 ⟫\n-- Arith.add (Arith.var \"x\") (Arith.nat 20) : Arith\n\n#check ⟪ \"x\" + \"y\" * \"z\" ⟫ -- precedence\n-- Arith.add (Arith.var \"x\") (Arith.mul (Arith.var \"y\") (Arith.var \"z\")) : Arith\n\n#check ⟪ \"x\" * \"y\" + \"z\" ⟫ -- precedence\n-- Arith.add (Arith.mul (Arith.var \"x\") (Arith.var \"y\")) (Arith.var \"z\") : Arith\n\n#check ⟪ (\"x\" + \"y\") * \"z\" ⟫ -- brackets\n-- Arith.mul (Arith.add (Arith.symbol \"x\") (Arith.symbol \"y\")) (Arith.symbol \"z\")\n\n/-!\n### Writing our own tactic\n\nLet's create a tactic that adds a new hypothesis to the context with a given\nname and postpones the need for its proof to the very end. It's similar to\nthe `suffices` tactic from Lean 3, except that we want to make sure that the new\ngoal goes to the bottom of the goal list.\n\nIt's going to be called `suppose` and is used like this:\n\n`suppose : `\n\nSo let's see the code:\n-/\n\nopen Lean Meta Elab Tactic Term in\nelab \"suppose \" n:ident \" : \" t:term : tactic => do\n let n : Name := n.getId\n let mvarId ← getMainGoal\n mvarId.withContext do\n let t ← elabType t\n let p ← mkFreshExprMVar t MetavarKind.syntheticOpaque n\n let (_, mvarIdNew) ← intro1P $ ← mvarId.assert n t p\n replaceMainGoal [p.mvarId!, mvarIdNew]\n evalTactic $ ← `(tactic|rotate_left)\n\nexample : 0 + a = a := by\n suppose add_comm : 0 + a = a + 0\n rw [add_comm]; rfl -- closes the initial main goal\n rw [Nat.zero_add]; rfl -- proves `add_comm`\n\n/-! We start by storing the main goal in `mvarId` and using it as a parameter of\n`withMVarContext` to make sure that our elaborations will work with types that\ndepend on other variables in the context.\n\nThis time we're using `mkFreshExprMVar` to create a metavariable expression for\nthe proof of `t`, which we can introduce to the context using `intro1P` and\n`assert`.\n\nTo require the proof of the new hypothesis as a goal, we call `replaceMainGoal`\npassing a list with `p.mvarId!` in the head. And then we can use the\n`rotate_left` tactic to move the recently added top goal to the bottom.\n\n## Printing Messages\n\nIn the `#assertType` example, we used `logInfo` to make our command print\nsomething. If, instead, we just want to perform a quick debug, we can use\n`dbg_trace`.\n\nThey behave a bit differently though, as we can see below:\n-/\n\nelab \"traces\" : tactic => do\n let array := List.replicate 2 (List.range 3)\n Lean.logInfo m!\"logInfo: {array}\"\n dbg_trace f!\"dbg_trace: {array}\"\n\nexample : True := by -- `example` is underlined in blue, outputting:\n -- dbg_trace: [[0, 1, 2], [0, 1, 2]]\n traces -- now `traces` is underlined in blue, outputting\n -- logInfo: [[0, 1, 2], [0, 1, 2]]\n trivial\n", "meta": {"author": "leanprover-community", "repo": "lean4-metaprogramming-book", "sha": "0b2e7e2c0cacac530ed947df878088c5d9715412", "save_path": "github-repos/lean/leanprover-community-lean4-metaprogramming-book", "path": "github-repos/lean/leanprover-community-lean4-metaprogramming-book/lean4-metaprogramming-book-0b2e7e2c0cacac530ed947df878088c5d9715412/lean/main/intro.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.24798742624020276, "lm_q2_score": 0.08632347541098986, "lm_q1q2_score": 0.021407136491280804}} {"text": "/-\nCopyright (c) 2021-2023 by the authors listed in the file AUTHORS and their\ninstitutional affiliations. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Abdalrhman Mohamed\n-/\n\nimport Smt.Reconstruction.Rewrites.Simp\n\nnamespace Smt.Reconstruction.Rewrites.Builtin\n\n-- Equality\n\n@[smt_simp] theorem eq_refl : (t = t) = True := eq_self t\n@[smt_simp] theorem eq_symm : (t = s) = (s = t) := propext ⟨(· ▸ rfl), (· ▸ rfl)⟩\n\n-- ITE\n\n@[smt_simp] theorem ite_true_cond : ite True x y = x := rfl\n@[smt_simp] theorem ite_false_cond : ite False x y = y := rfl\n@[smt_simp] theorem ite_not_cond [h : Decidable c] : ite (Not c) x y = ite c y x :=\n h.byCases (fun hc => if_pos hc ▸ if_neg (not_not_intro hc) ▸ rfl)\n (fun hnc => if_pos hnc ▸ if_neg hnc ▸ rfl)\n@[smt_simp] theorem ite_eq_branch [h : Decidable c] : ite c x x = x :=\n h.byCases (if_pos · ▸ rfl) (if_neg · ▸ rfl)\n\nend Smt.Reconstruction.Rewrites.Builtin\n", "meta": {"author": "ufmg-smite", "repo": "lean-smt", "sha": "6de0c4b216a918a14cf7a47d9a6faccaf8c8a209", "save_path": "github-repos/lean/ufmg-smite-lean-smt", "path": "github-repos/lean/ufmg-smite-lean-smt/lean-smt-6de0c4b216a918a14cf7a47d9a6faccaf8c8a209/Smt/Reconstruction/Rewrites/Builtin.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3208212878370535, "lm_q2_score": 0.06656918572976649, "lm_q1q2_score": 0.021356811896087687}} {"text": "-- lemmas about free variables and environments\n\nimport .definitions3\n\nlemma free_in_term.value.inv {x: var} {v: value}: ¬ free_in_term x v :=\n assume x_free_in_v: free_in_term x v,\n show «false», by cases x_free_in_v\n\nlemma free_in_term.var.inv {x y: var}: free_in_term x y → (x = y) :=\n assume x_free_in_y: free_in_term x y,\n begin\n cases x_free_in_y,\n case free_in_term.var { exact rfl }\n end\n\nlemma free_in_term.unop.inv {x: var} {op: unop} {t: term}: free_in_term x (term.unop op t) → free_in_term x t :=\n assume x_free_in_unop: free_in_term x (term.unop op t),\n begin\n cases x_free_in_unop,\n case free_in_term.unop x_free_in_t { from x_free_in_t }\n end\n\nlemma free_in_term.binop.inv {x: var} {op: binop} {t₁ t₂: term}:\n free_in_term x (term.binop op t₁ t₂) → free_in_term x t₁ ∨ free_in_term x t₂ :=\n assume x_free_in_binop: free_in_term x (term.binop op t₁ t₂),\n begin\n cases x_free_in_binop,\n case free_in_term.binop₁ x_free_in_t₁ { from or.inl x_free_in_t₁ },\n case free_in_term.binop₂ x_free_in_t₂ { from or.inr x_free_in_t₂ }\n end\n\nlemma free_in_term.app.inv {x: var} {t₁ t₂: term}:\n free_in_term x (term.app t₁ t₂) → free_in_term x t₁ ∨ free_in_term x t₂ :=\n assume x_free_in_app: free_in_term x (term.app t₁ t₂),\n begin\n cases x_free_in_app,\n case free_in_term.app₁ x_free_in_t₁ { from or.inl x_free_in_t₁ },\n case free_in_term.app₂ x_free_in_t₂ { from or.inr x_free_in_t₂ }\n end\n\nlemma free_in_prop.term.inv {t: term} {x: var}: free_in_prop x t → free_in_term x t :=\n assume x_free_in_t: free_in_prop x t,\n begin\n cases x_free_in_t,\n case free_in_prop.term free_in_t { from free_in_t }\n end\n\nlemma free_in_prop.not.inv {P: prop} {x: var}: free_in_prop x P.not → free_in_prop x P :=\n assume x_free_in_not: free_in_prop x P.not,\n begin\n cases x_free_in_not,\n case free_in_prop.not free_in_P { from free_in_P }\n end\n\nlemma free_in_prop.and.inv {P₁ P₂: prop} {x: var}: free_in_prop x (P₁ ⋀ P₂) → free_in_prop x P₁ ∨ free_in_prop x P₂ :=\n assume x_free_in_and: free_in_prop x (P₁ ⋀ P₂),\n begin\n cases x_free_in_and,\n case free_in_prop.and₁ free_in_P₁ {\n show free_in_prop x P₁ ∨ free_in_prop x P₂, from or.inl free_in_P₁\n },\n case free_in_prop.and₂ free_in_P₂ {\n show free_in_prop x P₁ ∨ free_in_prop x P₂, from or.inr free_in_P₂\n }\n end\n\nlemma free_in_prop.or.inv {P₁ P₂: prop} {x: var}: free_in_prop x (P₁ ⋁ P₂) → free_in_prop x P₁ ∨ free_in_prop x P₂ :=\n assume x_free_in_or: free_in_prop x (P₁ ⋁ P₂),\n begin\n cases x_free_in_or,\n case free_in_prop.or₁ free_in_P₁ {\n show free_in_prop x P₁ ∨ free_in_prop x P₂, from or.inl free_in_P₁\n },\n case free_in_prop.or₂ free_in_P₂ {\n show free_in_prop x P₁ ∨ free_in_prop x P₂, from or.inr free_in_P₂\n }\n end\n\nlemma free_in_prop.pre.inv {t₁ t₂: term} {x: var}:\n free_in_prop x (prop.pre t₁ t₂) → free_in_term x t₁ ∨ free_in_term x t₂ :=\n assume x_free_in_pre: free_in_prop x (prop.pre t₁ t₂),\n begin\n cases x_free_in_pre,\n case free_in_prop.pre₁ free_in_t₁ { from or.inl free_in_t₁ },\n case free_in_prop.pre₂ free_in_t₂ { from or.inr free_in_t₂ } \n end\n\nlemma free_in_prop.pre₁.inv {t: term} {op: unop} {x: var}:\n free_in_prop x (prop.pre₁ op t) → free_in_term x t :=\n assume x_free_in_pre: free_in_prop x (prop.pre₁ op t),\n begin\n cases x_free_in_pre,\n case free_in_prop.preop free_in_t { from free_in_t }\n end\n\nlemma free_in_prop.pre₂.inv {t₁ t₂: term} {op: binop} {x: var}:\n free_in_prop x (prop.pre₂ op t₁ t₂) → free_in_term x t₁ ∨ free_in_term x t₂ :=\n assume x_free_in_pre: free_in_prop x (prop.pre₂ op t₁ t₂),\n begin\n cases x_free_in_pre,\n case free_in_prop.preop₁ free_in_t₁ { from or.inl free_in_t₁ },\n case free_in_prop.preop₂ free_in_t₂ { from or.inr free_in_t₂ } \n end\n\nlemma free_in_prop.post.inv {t₁ t₂: term} {x: var}:\n free_in_prop x (prop.post t₁ t₂) → free_in_term x t₁ ∨ free_in_term x t₂ :=\n assume x_free_in_post: free_in_prop x (prop.post t₁ t₂),\n begin\n cases x_free_in_post,\n case free_in_prop.post₁ free_in_t₁ { from or.inl free_in_t₁ },\n case free_in_prop.post₂ free_in_t₂ { from or.inr free_in_t₂ } \n end\n\nlemma free_in_prop.call.inv {t: term} {x: var}:\n free_in_prop x (prop.call t) → free_in_term x t :=\n assume x_free_in_call: free_in_prop x (prop.call t),\n begin\n cases x_free_in_call,\n case free_in_prop.call free_in_t { from free_in_t }\n end\n\nlemma free_in_prop.forallc.inv {P: prop} {x fx: var}:\n free_in_prop x (prop.forallc fx P) → (x ≠ fx) ∧ free_in_prop x P :=\n assume x_free_in_forallc: free_in_prop x (prop.forallc fx P),\n begin\n cases x_free_in_forallc,\n case free_in_prop.forallc x_neq_fx free_in_P {\n from ⟨x_neq_fx, free_in_P⟩ \n }\n end\n\nlemma free_in_prop.forallc.same.inv {P: prop} {x: var}: ¬ free_in_prop x (prop.forallc x P) :=\n assume x_free: free_in_prop x (prop.forallc x P),\n begin\n cases x_free,\n case free_in_prop.forallc x_neq_y free_in_P {\n contradiction\n }\n end\n\nlemma free_in_prop.exis.inv {P: prop} {x fx: var}:\n free_in_prop x (prop.exis fx P) → (x ≠ fx) ∧ (free_in_prop x P) :=\n assume x_free_in_exis: free_in_prop x (prop.exis fx P),\n begin\n cases x_free_in_exis,\n case free_in_prop.exis x_neq_fx free_in_P {\n from ⟨x_neq_fx, free_in_P⟩ \n }\n end\n\nlemma free_in_prop.implies.inv {P₁ P₂: prop} {x: var}: free_in_prop x (prop.implies P₁ P₂) → free_in_prop x P₁ ∨ free_in_prop x P₂ :=\n assume x_free_in_implies: free_in_prop x (prop.or P₁.not P₂),\n begin\n cases x_free_in_implies,\n case free_in_prop.or₁ x_free_in_not_P₁ {\n cases x_free_in_not_P₁,\n case free_in_prop.not free_in_P₁ {\n show free_in_prop x P₁ ∨ free_in_prop x P₂, from or.inl free_in_P₁\n }\n },\n case free_in_prop.or₂ free_in_P₂ {\n show free_in_prop x P₁ ∨ free_in_prop x P₂, from or.inr free_in_P₂\n }\n end\n\nlemma free_in_prop.func.inv {P₁ P₂: prop} {t: term} {x y: var}:\n free_in_prop x (prop.func t y P₁ P₂) → free_in_term x t ∨ (x ≠ y ∧ (free_in_prop x P₁ ∨ free_in_prop x P₂)) :=\n assume : free_in_prop x (prop.func t y P₁ P₂),\n have free_in_prop x (term.unop unop.isFunc t ⋀\n (prop.forallc y (prop.implies P₁ (prop.pre t y) ⋀\n prop.implies (prop.post t y) P₂))),\n from this,\n begin\n cases this,\n case free_in_prop.and₁ x_free_in_unopfunc {\n cases x_free_in_unopfunc,\n case free_in_prop.term x_free_in_unopfuncterm {\n cases x_free_in_unopfuncterm,\n case free_in_term.unop x_free_in_func {\n left,\n from x_free_in_func\n }\n }\n },\n case free_in_prop.and₂ x_free_in_forallc {\n cases x_free_in_forallc,\n case free_in_prop.forallc x_neq_y x_free_in_forallp {\n cases x_free_in_forallp,\n case free_in_prop.and₁ x_free_Rpre {\n cases x_free_Rpre,\n case free_in_prop.or₁ x_free_in_Pnot {\n cases x_free_in_Pnot,\n case free_in_prop.not x_free_in_P₁ {\n right,\n split,\n from x_neq_y,\n left,\n from x_free_in_P₁\n }\n },\n case free_in_prop.or₂ x_free_in_pre {\n cases x_free_in_pre,\n case free_in_prop.pre₁ x_free_in_t {\n left,\n from x_free_in_t\n },\n case free_in_prop.pre₂ x_free_in_y {\n cases x_free_in_y,\n case free_in_term.var {\n contradiction\n }\n }\n }\n },\n case free_in_prop.and₂ x_free_postS {\n cases x_free_postS,\n case free_in_prop.or₁ x_free_in_postnot {\n cases x_free_in_postnot,\n case free_in_prop.not x_free_in_post {\n cases x_free_in_post,\n case free_in_prop.post₁ x_free_in_t {\n left,\n from x_free_in_t\n },\n case free_in_prop.post₂ x_free_in_y {\n cases x_free_in_y,\n case free_in_term.var {\n contradiction\n }\n }\n }\n },\n case free_in_prop.or₂ x_free_in_S {\n right,\n split,\n from x_neq_y,\n right,\n from x_free_in_S\n }\n }\n }\n }\n end\n\nlemma free_in_vc.term.inv {t: term} {x: var}: free_in_vc x t → free_in_term x t :=\n assume x_free_in_t: free_in_vc x t,\n begin\n cases x_free_in_t,\n case free_in_vc.term free_in_t { from free_in_t }\n end\n\nlemma free_in_vc.not.inv {P: vc} {x: var}: free_in_vc x P.not → free_in_vc x P :=\n assume x_free_in_not: free_in_vc x P.not,\n begin\n cases x_free_in_not,\n case free_in_vc.not free_in_P { from free_in_P }\n end\n\nlemma free_in_vc.and.inv {P₁ P₂: vc} {x: var}: free_in_vc x (P₁ ⋀ P₂) → free_in_vc x P₁ ∨ free_in_vc x P₂ :=\n assume x_free_in_and: free_in_vc x (P₁ ⋀ P₂),\n begin\n cases x_free_in_and,\n case free_in_vc.and₁ free_in_P₁ {\n show free_in_vc x P₁ ∨ free_in_vc x P₂, from or.inl free_in_P₁\n },\n case free_in_vc.and₂ free_in_P₂ {\n show free_in_vc x P₁ ∨ free_in_vc x P₂, from or.inr free_in_P₂\n }\n end\n\nlemma free_in_vc.or.inv {P₁ P₂: vc} {x: var}: free_in_vc x (P₁ ⋁ P₂) → free_in_vc x P₁ ∨ free_in_vc x P₂ :=\n assume x_free_in_or: free_in_vc x (P₁ ⋁ P₂),\n begin\n cases x_free_in_or,\n case free_in_vc.or₁ free_in_P₁ {\n show free_in_vc x P₁ ∨ free_in_vc x P₂, from or.inl free_in_P₁\n },\n case free_in_vc.or₂ free_in_P₂ {\n show free_in_vc x P₁ ∨ free_in_vc x P₂, from or.inr free_in_P₂\n }\n end\n\nlemma free_in_vc.pre.inv {t₁ t₂: term} {x: var}:\n free_in_vc x (vc.pre t₁ t₂) → free_in_term x t₁ ∨ free_in_term x t₂ :=\n assume x_free_in_pre: free_in_vc x (vc.pre t₁ t₂),\n begin\n cases x_free_in_pre,\n case free_in_vc.pre₁ free_in_t₁ { from or.inl free_in_t₁ },\n case free_in_vc.pre₂ free_in_t₂ { from or.inr free_in_t₂ } \n end\n\nlemma free_in_vc.pre₁.inv {t: term} {op: unop} {x: var}:\n free_in_vc x (vc.pre₁ op t) → free_in_term x t :=\n assume x_free_in_pre: free_in_vc x (vc.pre₁ op t),\n begin\n cases x_free_in_pre,\n case free_in_vc.preop free_in_t { from free_in_t }\n end\n\nlemma free_in_vc.pre₂.inv {t₁ t₂: term} {op: binop} {x: var}:\n free_in_vc x (vc.pre₂ op t₁ t₂) → free_in_term x t₁ ∨ free_in_term x t₂ :=\n assume x_free_in_pre: free_in_vc x (vc.pre₂ op t₁ t₂),\n begin\n cases x_free_in_pre,\n case free_in_vc.preop₁ free_in_t₁ { from or.inl free_in_t₁ },\n case free_in_vc.preop₂ free_in_t₂ { from or.inr free_in_t₂ } \n end\n\nlemma free_in_vc.post.inv {t₁ t₂: term} {x: var}:\n free_in_vc x (vc.post t₁ t₂) → free_in_term x t₁ ∨ free_in_term x t₂ :=\n assume x_free_in_post: free_in_vc x (vc.post t₁ t₂),\n begin\n cases x_free_in_post,\n case free_in_vc.post₁ free_in_t₁ { from or.inl free_in_t₁ },\n case free_in_vc.post₂ free_in_t₂ { from or.inr free_in_t₂ } \n end\n\nlemma free_in_vc.univ.inv {P: vc} {x y: var}:\n free_in_vc x (vc.univ y P) → (x ≠ y) ∧ free_in_vc x P :=\n assume x_free: free_in_vc x (vc.univ y P),\n begin\n cases x_free,\n case free_in_vc.univ x_neq_y free_in_P {\n from ⟨x_neq_y, free_in_P⟩ \n }\n end\n\nlemma free_in_vc.univ.same.inv {P: vc} {x: var}: ¬ free_in_vc x (vc.univ x P) :=\n assume x_free: free_in_vc x (vc.univ x P),\n begin\n cases x_free,\n case free_in_vc.univ x_neq_y free_in_P {\n contradiction\n }\n end\n\nlemma free_in_termctx.hole.inv {x: var} {t: term}:\n x ∈ FV (• t) → x ∈ FV t :=\n assume x_free_in_t: x ∈ FV (• t),\n have (termctx.apply • t) = t, by unfold termctx.apply,\n show x ∈ FV t, from this ▸ x_free_in_t\n\nlemma free_in_termctx.binop.inv {x: var} {op: binop} {t₁ t₂: termctx} {t': term}:\n x ∈ FV ((termctx.binop op t₁ t₂) t') → x ∈ FV (t₁ t') ∨ x ∈ FV (t₂ t') :=\n assume x_free_in_t: x ∈ FV ((termctx.binop op t₁ t₂) t'),\n have (termctx.apply (termctx.binop op t₁ t₂) t') = term.binop op (t₁.apply t') (t₂.apply t'),\n by unfold termctx.apply,\n have x ∈ FV (term.binop op (t₁.apply t') (t₂.apply t')), from this ▸ x_free_in_t,\n show x ∈ FV (t₁ t') ∨ x ∈ FV (t₂ t'), from free_in_term.binop.inv this\n\nlemma free_in_termctx.term.inv {x: var} {t t': term}:\n x ∈ FV (t.to_termctx t') → x ∈ FV t :=\n assume x_free_in_t: x ∈ FV (t.to_termctx t'),\n begin\n induction t with v y unop t₁ ih₁ binop t₂ t₃ ih₂ ih₃ t₄ t₅ ih₄ ih₅,\n\n show x ∈ FV (term.value v), from (\n have term.to_termctx (term.value v) = (termctx.value v), by unfold term.to_termctx,\n have h: x ∈ FV ((termctx.value v) t'), from this ▸ x_free_in_t,\n have termctx.apply (termctx.value v) t' = (term.value v), by unfold termctx.apply,\n show x ∈ FV (term.value v), from this.symm ▸ h\n ),\n\n show x ∈ FV (term.var y), from (\n have term.to_termctx (term.var y) = termctx.var y, by unfold term.to_termctx,\n have h: x ∈ FV ((termctx.var y) t'), from this ▸ x_free_in_t,\n have termctx.apply (termctx.var y) t' = term.var y, by unfold termctx.apply,\n show x ∈ FV (term.var y), from this.symm ▸ h\n ),\n\n show x ∈ FV (term.unop unop t₁), from (\n have term.to_termctx (term.unop unop t₁) = termctx.unop unop t₁.to_termctx, by unfold term.to_termctx,\n have h: x ∈ FV ((termctx.unop unop t₁.to_termctx) t'), from this ▸ x_free_in_t,\n have termctx.apply (termctx.unop unop t₁.to_termctx) t' = term.unop unop (t₁.to_termctx.apply t'),\n by unfold termctx.apply,\n have x ∈ FV (term.unop unop (t₁.to_termctx.apply t')), from this ▸ h,\n have x ∈ FV (t₁.to_termctx.apply t'), from free_in_term.unop.inv this,\n have x ∈ FV t₁, from ih₁ this,\n show x ∈ FV (term.unop unop t₁), from free_in_term.unop this\n ),\n\n show x ∈ FV (term.binop binop t₂ t₃), from (\n have term.to_termctx (term.binop binop t₂ t₃) = termctx.binop binop t₂.to_termctx t₃.to_termctx,\n by unfold term.to_termctx,\n have h: x ∈ FV ((termctx.binop binop t₂.to_termctx t₃.to_termctx) t'), from this ▸ x_free_in_t,\n have termctx.apply (termctx.binop binop t₂.to_termctx t₃.to_termctx) t'\n = term.binop binop (t₂.to_termctx.apply t') (t₃.to_termctx.apply t'),\n by unfold termctx.apply,\n have x ∈ FV (term.binop binop (t₂.to_termctx.apply t') (t₃.to_termctx.apply t')), from this ▸ h,\n have x ∈ FV (t₂.to_termctx.apply t') ∨ x ∈ FV (t₃.to_termctx.apply t'), from free_in_term.binop.inv this,\n or.elim this (\n assume : x ∈ FV (t₂.to_termctx.apply t'),\n have x ∈ FV t₂, from ih₂ this,\n show x ∈ FV (term.binop binop t₂ t₃), from free_in_term.binop₁ this\n ) (\n assume : x ∈ FV (t₃.to_termctx.apply t'),\n have x ∈ FV t₃, from ih₃ this,\n show x ∈ FV (term.binop binop t₂ t₃), from free_in_term.binop₂ this\n )\n ),\n\n show x ∈ FV (term.app t₄ t₅), from (\n have term.to_termctx (term.app t₄ t₅) = termctx.app t₄.to_termctx t₅.to_termctx,\n by unfold term.to_termctx,\n have h: x ∈ FV ((termctx.app t₄.to_termctx t₅.to_termctx) t'), from this ▸ x_free_in_t,\n have termctx.apply (termctx.app t₄.to_termctx t₅.to_termctx) t'\n = term.app (t₄.to_termctx.apply t') (t₅.to_termctx.apply t'),\n by unfold termctx.apply,\n have x ∈ FV (term.app (t₄.to_termctx.apply t') (t₅.to_termctx.apply t')), from this ▸ h,\n have x ∈ FV (t₄.to_termctx.apply t') ∨ x ∈ FV (t₅.to_termctx.apply t'), from free_in_term.app.inv this,\n or.elim this (\n assume : x ∈ FV (t₄.to_termctx.apply t'),\n have x ∈ FV t₄, from ih₄ this,\n show x ∈ FV (term.app t₄ t₅), from free_in_term.app₁ this\n ) (\n assume : x ∈ FV (t₅.to_termctx.apply t'),\n have x ∈ FV t₅, from ih₅ this,\n show x ∈ FV (term.app t₄ t₅), from free_in_term.app₂ this\n )\n )\n end\n\nlemma free_in_propctx.prop.inv {x: var} {P: prop} {t': term}:\n x ∈ FV (P.to_propctx t') → x ∈ FV P :=\n assume x_free_in_P: x ∈ FV (P.to_propctx t'),\n begin\n induction P,\n case prop.term t { from (\n have prop.to_propctx (prop.term t) = (propctx.term t), by unfold prop.to_propctx,\n have h: x ∈ FV ((propctx.term t) t'), from this ▸ x_free_in_P,\n have propctx.apply (propctx.term t.to_termctx) t' = t.to_termctx t', by unfold propctx.apply,\n have x ∈ FV (prop.term (t.to_termctx t')), from this.symm ▸ h,\n have x ∈ FV (t.to_termctx t'), from free_in_prop.term.inv this,\n have x ∈ FV t, from free_in_termctx.term.inv this,\n show x ∈ FV (prop.term t), from free_in_prop.term this\n )},\n case prop.not P₁ ih { from (\n have prop.to_propctx (prop.not P₁) = (propctx.not P₁.to_propctx), by unfold prop.to_propctx,\n have h: x ∈ FV ((propctx.not P₁.to_propctx) t'), from this ▸ x_free_in_P,\n have propctx.apply (propctx.not P₁.to_propctx) t' = prop.not (P₁.to_propctx.apply t'), by unfold propctx.apply,\n have x ∈ FV (prop.not (P₁.to_propctx.apply t')), from this.symm ▸ h,\n have x ∈ FV (P₁.to_propctx.apply t'), from free_in_prop.not.inv this,\n have x ∈ FV P₁, from ih this,\n show x ∈ FV P₁.not, from free_in_prop.not this\n )},\n case prop.and P₁ P₂ ih₁ ih₂ { from (\n have prop.to_propctx (prop.and P₁ P₂) = (P₁.to_propctx ⋀ P₂.to_propctx), by unfold prop.to_propctx,\n have h: x ∈ FV ((P₁.to_propctx ⋀ P₂.to_propctx) t'), from this ▸ x_free_in_P,\n have propctx.apply (propctx.and P₁.to_propctx P₂.to_propctx) t'\n = (P₁.to_propctx.apply t' ⋀ P₂.to_propctx.apply t'), by unfold propctx.apply,\n have x ∈ FV ((P₁.to_propctx.apply t') ⋀ (P₂.to_propctx.apply t')), from this.symm ▸ h,\n have x ∈ FV (P₁.to_propctx.apply t') ∨ x ∈ FV (P₂.to_propctx.apply t'), from free_in_prop.and.inv this,\n or.elim this (\n assume : x ∈ FV (P₁.to_propctx.apply t'),\n have x ∈ FV P₁, from ih₁ this,\n show x ∈ FV (P₁ ⋀ P₂), from free_in_prop.and₁ this\n ) (\n assume : x ∈ FV (P₂.to_propctx.apply t'),\n have x ∈ FV P₂, from ih₂ this,\n show x ∈ FV (P₁ ⋀ P₂), from free_in_prop.and₂ this\n )\n )},\n case prop.or P₁ P₂ ih₁ ih₂ { from (\n have prop.to_propctx (prop.or P₁ P₂) = (P₁.to_propctx ⋁ P₂.to_propctx), by unfold prop.to_propctx,\n have h: x ∈ FV ((P₁.to_propctx ⋁ P₂.to_propctx) t'), from this ▸ x_free_in_P,\n have propctx.apply (propctx.or P₁.to_propctx P₂.to_propctx) t'\n = (P₁.to_propctx.apply t' ⋁ P₂.to_propctx.apply t'), by unfold propctx.apply,\n have x ∈ FV ((P₁.to_propctx.apply t') ⋁ (P₂.to_propctx.apply t')), from this.symm ▸ h,\n have x ∈ FV (P₁.to_propctx.apply t') ∨ x ∈ FV (P₂.to_propctx.apply t'), from free_in_prop.or.inv this,\n or.elim this (\n assume : x ∈ FV (P₁.to_propctx.apply t'),\n have x ∈ FV P₁, from ih₁ this,\n show x ∈ FV (P₁ ⋁ P₂), from free_in_prop.or₁ this\n ) (\n assume : x ∈ FV (P₂.to_propctx.apply t'),\n have x ∈ FV P₂, from ih₂ this,\n show x ∈ FV (P₁ ⋁ P₂), from free_in_prop.or₂ this\n )\n )},\n case prop.pre t₁ t₂ { from (\n have prop.to_propctx (prop.pre t₁ t₂) = propctx.pre t₁ t₂, by unfold prop.to_propctx,\n have h: x ∈ FV ((propctx.pre t₁ t₂) t'), from this ▸ x_free_in_P,\n have propctx.apply (propctx.pre t₁.to_termctx t₂.to_termctx) t' = prop.pre (t₁.to_termctx t') (t₂.to_termctx t'),\n by unfold propctx.apply,\n have x ∈ FV (prop.pre (t₁.to_termctx t') (t₂.to_termctx t')), from this.symm ▸ h,\n have x ∈ FV (t₁.to_termctx t') ∨ x ∈ FV (t₂.to_termctx t'), from free_in_prop.pre.inv this,\n or.elim this (\n assume : x ∈ FV (t₁.to_termctx t'),\n have x ∈ FV t₁, from free_in_termctx.term.inv this,\n show x ∈ FV (prop.pre t₁ t₂), from free_in_prop.pre₁ this\n ) (\n assume : x ∈ FV (t₂.to_termctx t'),\n have x ∈ FV t₂, from free_in_termctx.term.inv this,\n show x ∈ FV (prop.pre t₁ t₂), from free_in_prop.pre₂ this\n )\n )},\n case prop.pre₁ op t { from (\n have prop.to_propctx (prop.pre₁ op t) = propctx.pre₁ op t, by unfold prop.to_propctx,\n have h: x ∈ FV ((propctx.pre₁ op t) t'), from this ▸ x_free_in_P,\n have propctx.apply (propctx.pre₁ op t.to_termctx) t' = prop.pre₁ op (t.to_termctx t'),\n by unfold propctx.apply,\n have x ∈ FV (prop.pre₁ op (t.to_termctx t')), from this.symm ▸ h,\n have x ∈ FV (t.to_termctx t'), from free_in_prop.pre₁.inv this,\n have x ∈ FV t, from free_in_termctx.term.inv this,\n show x ∈ FV (prop.pre₁ op t), from free_in_prop.preop this\n )},\n case prop.pre₂ op t₁ t₂ { from (\n have prop.to_propctx (prop.pre₂ op t₁ t₂) = propctx.pre₂ op t₁ t₂, by unfold prop.to_propctx,\n have h: x ∈ FV ((propctx.pre₂ op t₁ t₂) t'), from this ▸ x_free_in_P,\n have propctx.apply (propctx.pre₂ op t₁.to_termctx t₂.to_termctx) t'\n = prop.pre₂ op (t₁.to_termctx t') (t₂.to_termctx t'),\n by unfold propctx.apply,\n have x ∈ FV (prop.pre₂ op (t₁.to_termctx t') (t₂.to_termctx t')), from this.symm ▸ h,\n have x ∈ FV (t₁.to_termctx t') ∨ x ∈ FV (t₂.to_termctx t'), from free_in_prop.pre₂.inv this,\n or.elim this (\n assume : x ∈ FV (t₁.to_termctx t'),\n have x ∈ FV t₁, from free_in_termctx.term.inv this,\n show x ∈ FV (prop.pre₂ op t₁ t₂), from free_in_prop.preop₁ this\n ) (\n assume : x ∈ FV (t₂.to_termctx t'),\n have x ∈ FV t₂, from free_in_termctx.term.inv this,\n show x ∈ FV (prop.pre₂ op t₁ t₂), from free_in_prop.preop₂ this\n )\n )},\n case prop.post t₁ t₂ { from (\n have prop.to_propctx (prop.post t₁ t₂) = propctx.post t₁ t₂, by unfold prop.to_propctx,\n have h: x ∈ FV ((propctx.post t₁ t₂) t'), from this ▸ x_free_in_P,\n have propctx.apply (propctx.post t₁.to_termctx t₂.to_termctx) t' = prop.post (t₁.to_termctx t') (t₂.to_termctx t'),\n by unfold propctx.apply,\n have x ∈ FV (prop.post (t₁.to_termctx t') (t₂.to_termctx t')), from this.symm ▸ h,\n have x ∈ FV (t₁.to_termctx t') ∨ x ∈ FV (t₂.to_termctx t'), from free_in_prop.post.inv this,\n or.elim this (\n assume : x ∈ FV (t₁.to_termctx t'),\n have x ∈ FV t₁, from free_in_termctx.term.inv this,\n show x ∈ FV (prop.post t₁ t₂), from free_in_prop.post₁ this\n ) (\n assume : x ∈ FV (t₂.to_termctx t'),\n have x ∈ FV t₂, from free_in_termctx.term.inv this,\n show x ∈ FV (prop.post t₁ t₂), from free_in_prop.post₂ this\n )\n )},\n case prop.call t { from (\n have prop.to_propctx (prop.call t) = propctx.call t, by unfold prop.to_propctx,\n have h: x ∈ FV ((propctx.call t) t'), from this ▸ x_free_in_P,\n have propctx.apply (propctx.call t.to_termctx) t' = prop.call (t.to_termctx t'),\n by unfold propctx.apply,\n have x ∈ FV (prop.call (t.to_termctx t')), from this.symm ▸ h,\n have x ∈ FV (t.to_termctx t'), from free_in_prop.call.inv this,\n have x ∈ FV t, from free_in_termctx.term.inv this,\n show x ∈ FV (prop.call t), from free_in_prop.call this\n )},\n case prop.forallc y P₁ ih { from (\n have prop.to_propctx (prop.forallc y P₁) = propctx.forallc y P₁.to_propctx, by unfold prop.to_propctx,\n have h: x ∈ FV ((propctx.forallc y P₁.to_propctx) t'), from this ▸ x_free_in_P,\n have propctx.apply (propctx.forallc y P₁.to_propctx) t'\n = prop.forallc y (P₁.to_propctx.apply t'), by unfold propctx.apply,\n have x ∈ FV (prop.forallc y (P₁.to_propctx.apply t')), from this.symm ▸ h,\n have x_neq_y: x ≠ y, from (free_in_prop.forallc.inv this).left,\n have x ∈ FV (P₁.to_propctx.apply t'), from (free_in_prop.forallc.inv this).right,\n have x ∈ FV P₁, from ih this,\n show x ∈ FV (prop.forallc y P₁), from free_in_prop.forallc x_neq_y this\n )},\n case prop.exis y P₁ ih { from (\n have prop.to_propctx (prop.exis y P₁) = (propctx.exis y P₁.to_propctx), by unfold prop.to_propctx,\n have h: x ∈ FV ((propctx.exis y P₁.to_propctx) t'), from this ▸ x_free_in_P,\n have propctx.apply (propctx.exis y P₁.to_propctx) t' = prop.exis y (P₁.to_propctx.apply t'), by unfold propctx.apply,\n have x ∈ FV (prop.exis y (P₁.to_propctx.apply t')), from this.symm ▸ h,\n have x_neq_y: x ≠ y, from (free_in_prop.exis.inv this).left,\n have x ∈ FV (P₁.to_propctx.apply t'), from (free_in_prop.exis.inv this).right,\n have x ∈ FV P₁, from ih this,\n show x ∈ FV (prop.exis y P₁), from free_in_prop.exis x_neq_y this\n )}\n end\n\nlemma free_in_propctx.term.inv {x: var} {t: termctx} {t': term}:\n x ∈ FV ((propctx.term t) t') → x ∈ FV (t t') :=\n assume x_free_in_t: x ∈ FV (propctx.apply (propctx.term t) t'),\n have (propctx.apply (propctx.term t) t') = t t', by unfold propctx.apply,\n have x ∈ FV (prop.term (t t')), from this ▸ x_free_in_t,\n show x ∈ FV (t t'), from free_in_prop.term.inv this\n\nlemma free_in_propctx.not.inv {x: var} {Q: propctx} {t: term}:\n x ∈ FV (Q.not t) → x ∈ FV (Q t) :=\n assume x_free_in_Qn: x ∈ FV (Q.not t),\n have (propctx.apply (propctx.not Q) t) = prop.not (Q.apply t), by unfold propctx.apply,\n have x ∈ FV (prop.not (Q.apply t)), from this ▸ x_free_in_Qn,\n show x ∈ FV (Q t), from free_in_prop.not.inv this\n\nlemma free_in_propctx.and.inv {x: var} {Q₁ Q₂: propctx} {t: term}:\n x ∈ FV ((Q₁ ⋀ Q₂) t) → x ∈ FV (Q₁ t) ∨ x ∈ FV (Q₂ t) :=\n assume x_free_in_Q12: x ∈ FV ((Q₁ ⋀ Q₂) t),\n have (propctx.apply (propctx.and Q₁ Q₂) t) = (Q₁.apply t ⋀ Q₂.apply t), by unfold propctx.apply,\n have x ∈ FV (Q₁.apply t ⋀ Q₂.apply t), from this ▸ x_free_in_Q12,\n show x ∈ FV (Q₁ t) ∨ x ∈ FV (Q₂ t), from free_in_prop.and.inv this\n\nlemma free_in_propctx.or.inv {x: var} {Q₁ Q₂: propctx} {t: term}:\n x ∈ FV ((Q₁ ⋁ Q₂) t) → x ∈ FV (Q₁ t) ∨ x ∈ FV (Q₂ t) :=\n assume x_free_in_Q12: x ∈ FV ((Q₁ ⋁ Q₂) t),\n have (propctx.apply (propctx.or Q₁ Q₂) t) = (Q₁.apply t ⋁ Q₂.apply t), by unfold propctx.apply,\n have x ∈ FV (Q₁.apply t ⋁ Q₂.apply t), from this ▸ x_free_in_Q12,\n show x ∈ FV (Q₁ t) ∨ x ∈ FV (Q₂ t), from free_in_prop.or.inv this\n\nlemma free_in_propctx.implies.inv {x: var} {Q₁ Q₂: propctx} {t: term}:\n x ∈ FV ((propctx.implies Q₁ Q₂) t) → x ∈ FV (Q₁ t) ∨ x ∈ FV (Q₂ t) :=\n assume : x ∈ FV ((propctx.implies Q₁ Q₂) t),\n have x ∈ FV (Q₁.not t) ∨ x ∈ FV (Q₂ t), from free_in_propctx.or.inv this,\n or.elim this (\n assume : x ∈ FV (Q₁.not t),\n have x ∈ FV (Q₁ t), from free_in_propctx.not.inv this,\n show x ∈ FV (Q₁ t) ∨ x ∈ FV (Q₂ t), from or.inl this\n ) (\n assume : x ∈ FV (Q₂ t),\n show x ∈ FV (Q₁ t) ∨ x ∈ FV (Q₂ t), from or.inr this\n )\n\nlemma free_in_propctx.exis.inv {x fx: var} {Q: propctx} {t: term}:\n x ∈ FV ((propctx.exis fx Q) t) → x ≠ fx ∧ x ∈ FV (Q t) :=\n assume x_free_in_eQt: x ∈ FV ((propctx.exis fx Q) t),\n have (propctx.apply (propctx.exis fx Q) t) = prop.exis fx (Q.apply t), by unfold propctx.apply,\n have x ∈ FV (prop.exis fx (Q.apply t)), from this ▸ x_free_in_eQt,\n show x ≠ fx ∧ x ∈ FV (Q t), from free_in_prop.exis.inv this\n\nlemma free_in_prop.and_left_subset {P₁ P₂: prop}: FV P₁ ⊆ FV (P₁ ⋀ P₂) :=\n assume x: var,\n assume : x ∈ FV P₁,\n show x ∈ FV (P₁ ⋀ P₂), from free_in_prop.and₁ this\n\nlemma free_in_prop.and_elim {P₁ P₂: prop}:\n FV (P₁ ⋀ P₂) = FV P₁ ∪ FV P₂ :=\n set.eq_of_subset_of_subset (\n assume x: var,\n assume : x ∈ FV (P₁ ⋀ P₂),\n or.elim (free_in_prop.and.inv this) (\n assume : x ∈ FV P₁,\n show x ∈ FV P₁ ∪ FV P₂, from set.mem_union_left (FV P₂) this\n ) (\n assume : x ∈ FV P₂,\n show x ∈ FV P₁ ∪ FV P₂, from set.mem_union_right (FV P₁) this\n )\n ) (\n assume x: var,\n assume : x ∈ FV P₁ ∪ FV P₂,\n or.elim (set.mem_or_mem_of_mem_union this) (\n assume : x ∈ FV P₁,\n show x ∈ FV (P₁ ⋀ P₂), from free_in_prop.and₁ this\n ) (\n assume : x ∈ FV P₂,\n show x ∈ FV (P₁ ⋀ P₂), from free_in_prop.and₂ this\n )\n )\n\nlemma free_in_prop.and_assoc {P₁ P₂ P₃: prop}:\n FV (P₁ ⋀ P₂ ⋀ P₃) = FV ((P₁ ⋀ P₂) ⋀ P₃) :=\n set.eq_of_subset_of_subset (\n assume x: var,\n assume : x ∈ FV (P₁ ⋀ P₂ ⋀ P₃),\n or.elim (free_in_prop.and.inv this) (\n assume : x ∈ FV P₁,\n have x ∈ FV (P₁ ⋀ P₂), from free_in_prop.and₁ this,\n show x ∈ FV ((P₁ ⋀ P₂) ⋀ P₃), from free_in_prop.and₁ this\n ) (\n assume : x ∈ FV (P₂ ⋀ P₃),\n or.elim (free_in_prop.and.inv this) (\n assume : x ∈ FV P₂,\n have x ∈ FV (P₁ ⋀ P₂), from free_in_prop.and₂ this,\n show x ∈ FV ((P₁ ⋀ P₂) ⋀ P₃), from free_in_prop.and₁ this\n ) (\n assume : x ∈ FV P₃,\n show x ∈ FV ((P₁ ⋀ P₂) ⋀ P₃), from free_in_prop.and₂ this\n )\n )\n ) (\n assume x: var,\n assume : x ∈ FV ((P₁ ⋀ P₂) ⋀ P₃),\n or.elim (free_in_prop.and.inv this) (\n assume : x ∈ FV (P₁ ⋀ P₂),\n or.elim (free_in_prop.and.inv this) (\n assume : x ∈ FV P₁,\n show x ∈ FV (P₁ ⋀ P₂ ⋀ P₃), from free_in_prop.and₁ this\n ) (\n assume : x ∈ FV P₂,\n have x ∈ FV (P₂ ⋀ P₃), from free_in_prop.and₁ this,\n show x ∈ FV (P₁ ⋀ P₂ ⋀ P₃), from free_in_prop.and₂ this\n )\n ) (\n assume : x ∈ FV P₃,\n have x ∈ FV (P₂ ⋀ P₃), from free_in_prop.and₂ this,\n show x ∈ FV (P₁ ⋀ P₂ ⋀ P₃), from free_in_prop.and₂ this\n )\n )\n\nlemma free_in_prop.and_symm {P₁ P₂: prop}:\n FV (P₁ ⋀ P₂) = FV (P₂ ⋀ P₁) :=\n set.eq_of_subset_of_subset (\n assume x: var,\n assume : x ∈ FV (P₁ ⋀ P₂),\n or.elim (free_in_prop.and.inv this) (\n assume : x ∈ FV P₁,\n show x ∈ FV (P₂ ⋀ P₁), from free_in_prop.and₂ this\n ) (\n assume : x ∈ FV P₂,\n show x ∈ FV (P₂ ⋀ P₁), from free_in_prop.and₁ this\n )\n ) (\n assume x: var,\n assume : x ∈ FV (P₂ ⋀ P₁),\n or.elim (free_in_prop.and.inv this) (\n assume : x ∈ FV P₂,\n show x ∈ FV (P₁ ⋀ P₂), from free_in_prop.and₂ this\n ) (\n assume : x ∈ FV P₁,\n show x ∈ FV (P₁ ⋀ P₂), from free_in_prop.and₁ this\n )\n )\n\nlemma free_in_prop.same_left {P₁ P₂ P₃: prop}:\n (FV P₂ = FV P₃) → (FV (P₁ ⋀ P₂) = FV (P₁ ⋀ P₃)) :=\n assume h1: FV P₂ = FV P₃,\n set.eq_of_subset_of_subset (\n assume x: var,\n assume : x ∈ FV (P₁ ⋀ P₂),\n or.elim (free_in_prop.and.inv this) (\n assume : x ∈ FV P₁,\n show x ∈ FV (P₁ ⋀ P₃), from free_in_prop.and₁ this\n ) (\n assume : x ∈ FV P₂,\n have x ∈ FV P₃, from h1 ▸ this,\n show x ∈ FV (P₁ ⋀ P₃), from free_in_prop.and₂ this\n )\n ) (\n assume x: var,\n assume : x ∈ FV (P₁ ⋀ P₃),\n or.elim (free_in_prop.and.inv this) (\n assume : x ∈ FV P₁,\n show x ∈ FV (P₁ ⋀ P₂), from free_in_prop.and₁ this\n ) (\n assume : x ∈ FV P₃,\n have x ∈ FV P₂, from h1.symm ▸ this,\n show x ∈ FV (P₁ ⋀ P₂), from free_in_prop.and₂ this\n )\n )\n\nlemma free_in_prop.same_right {P₁ P₂ P₃: prop}:\n (FV P₁ = FV P₂) → (FV (P₁ ⋀ P₃) = FV (P₂ ⋀ P₃)) :=\n assume h1: FV P₁ = FV P₂,\n set.eq_of_subset_of_subset (\n assume x: var,\n assume : x ∈ FV (P₁ ⋀ P₃),\n or.elim (free_in_prop.and.inv this) (\n assume : x ∈ FV P₁,\n have x ∈ FV P₂, from h1 ▸ this,\n show x ∈ FV (P₂ ⋀ P₃), from free_in_prop.and₁ this\n ) (\n assume : x ∈ FV P₃,\n show x ∈ FV (P₂ ⋀ P₃), from free_in_prop.and₂ this\n )\n ) (\n assume x: var,\n assume : x ∈ FV (P₂ ⋀ P₃),\n or.elim (free_in_prop.and.inv this) (\n assume : x ∈ FV P₂,\n have x ∈ FV P₁, from h1.symm ▸ this,\n show x ∈ FV (P₁ ⋀ P₃), from free_in_prop.and₁ this\n ) (\n assume : x ∈ FV P₃,\n show x ∈ FV (P₁ ⋀ P₃), from free_in_prop.and₂ this\n )\n )\n\nlemma free_in_prop.shuffle {P Q R S: prop}:\n FV (P ⋀ Q ⋀ R ⋀ S) = FV ((P ⋀ Q ⋀ R) ⋀ S):=\n have h1: FV (P ⋀ Q ⋀ R ⋀ S) = FV ((Q ⋀ R ⋀ S) ⋀ P), from free_in_prop.and_symm,\n have h2: FV ((Q ⋀ R ⋀ S) ⋀ P) = FV (((Q ⋀ R) ⋀ S) ⋀ P),\n from free_in_prop.same_right free_in_prop.and_assoc,\n have h3: FV (((Q ⋀ R) ⋀ S) ⋀ P) = FV ((Q ⋀ R) ⋀ S ⋀ P), from free_in_prop.and_assoc.symm,\n have h4: FV ((Q ⋀ R) ⋀ S ⋀ P) = FV ((S ⋀ P) ⋀ Q ⋀ R), from free_in_prop.and_symm,\n have h5: FV ((S ⋀ P) ⋀ Q ⋀ R) = FV (S ⋀ P ⋀ Q ⋀ R), from free_in_prop.and_assoc.symm,\n have h6: FV (S ⋀ P ⋀ Q ⋀ R) = FV ((P ⋀ Q ⋀ R) ⋀ S), from free_in_prop.and_symm,\n show FV (P ⋀ Q ⋀ R ⋀ S) = FV ((P ⋀ Q ⋀ R) ⋀ S),\n from eq.trans h1 (eq.trans h2 (eq.trans h3 (eq.trans h4 (eq.trans h5 h6))))\n\nlemma free_in_prop.sub_same_left {P₁ P₂ P₃: prop}:\n (FV P₂ ⊆ FV P₃) → (FV (P₁ ⋀ P₂) ⊆ FV (P₁ ⋀ P₃)) :=\n assume h1: FV P₂ ⊆ FV P₃,\n assume x: var,\n assume : x ∈ FV (P₁ ⋀ P₂),\n or.elim (free_in_prop.and.inv this) (\n assume : x ∈ FV P₁,\n show x ∈ FV (P₁ ⋀ P₃), from free_in_prop.and₁ this\n ) (\n assume : x ∈ FV P₂,\n have x ∈ FV P₃, from set.mem_of_subset_of_mem h1 this,\n show x ∈ FV (P₁ ⋀ P₃), from free_in_prop.and₂ this\n )\n\nlemma free_in_prop.sub_same_right {P₁ P₂ P₃: prop}:\n (FV P₁ ⊆ FV P₂) → (FV (P₁ ⋀ P₃) ⊆ FV (P₂ ⋀ P₃)) :=\n assume h1: FV P₁ ⊆ FV P₂,\n assume x: var,\n assume : x ∈ FV (P₁ ⋀ P₃),\n or.elim (free_in_prop.and.inv this) (\n assume : x ∈ FV P₁,\n have x ∈ FV P₂, from set.mem_of_subset_of_mem h1 this,\n show x ∈ FV (P₂ ⋀ P₃), from free_in_prop.and₁ this\n ) (\n assume : x ∈ FV P₃,\n show x ∈ FV (P₂ ⋀ P₃), from free_in_prop.and₂ this\n )\n\nlemma prop.closed.and {P Q: prop}: closed P → closed Q → closed (P ⋀ Q) :=\n assume P_closed: closed P,\n assume Q_closed: closed Q,\n show closed (P ⋀ Q), from (\n assume x: var,\n assume : x ∈ FV (P ⋀ Q),\n or.elim (free_in_prop.and.inv this) (\n assume : x ∈ FV P,\n show «false», from P_closed x this\n ) (\n assume : x ∈ FV Q,\n show «false», from Q_closed x this\n )\n )\n\nlemma prop.closed.or {P Q: prop}: closed P → closed Q → closed (P ⋁ Q) :=\n assume P_closed: closed P,\n assume Q_closed: closed Q,\n show closed (P ⋁ Q), from (\n assume x: var,\n assume : x ∈ FV (P ⋁ Q),\n or.elim (free_in_prop.or.inv this) (\n assume : x ∈ FV P,\n show «false», from P_closed x this\n ) (\n assume : x ∈ FV Q,\n show «false», from Q_closed x this\n )\n )\n\nlemma prop.closed.not {P: prop}: closed P → closed P.not :=\n assume P_closed: closed P,\n show closed P.not, from (\n assume x: var,\n assume : x ∈ FV P.not,\n have x ∈ FV P, from free_in_prop.not.inv this,\n show «false», from P_closed x this\n )\n\nlemma prop.closed.implies {P Q: prop}: closed P → closed Q → closed (prop.implies P Q) :=\n assume P_closed: closed P,\n have P_not_closed: closed P.not, from prop.closed.not P_closed,\n assume Q_closed: closed Q,\n show closed (P.not ⋁ Q), from prop.closed.or P_not_closed Q_closed\n\nlemma prop.closed.and.inv {P Q: prop}: closed (P ⋀ Q) → (closed P ∧ closed Q) :=\n assume P_and_Q_closed: closed (P ⋀ Q),\n have P_closed: closed P, from (\n assume x: var,\n assume : x ∈ FV P,\n have x ∈ FV (P ⋀ Q), from free_in_prop.and₁ this,\n show «false», from P_and_Q_closed x this\n ),\n have Q_closed: closed Q, from (\n assume x: var,\n assume : x ∈ FV Q,\n have x ∈ FV (P ⋀ Q), from free_in_prop.and₂ this,\n show «false», from P_and_Q_closed x this\n ),\n ⟨P_closed, Q_closed⟩\n\nlemma prop.closed.or.inv {P Q: prop}: closed (P ⋁ Q) → (closed P ∧ closed Q) :=\n assume P_or_Q_closed: closed (P ⋁ Q),\n have P_closed: closed P, from (\n assume x: var,\n assume : x ∈ FV P,\n have x ∈ FV (P ⋁ Q), from free_in_prop.or₁ this,\n show «false», from P_or_Q_closed x this\n ),\n have Q_closed: closed Q, from (\n assume x: var,\n assume : x ∈ FV Q,\n have x ∈ FV (P ⋁ Q), from free_in_prop.or₂ this,\n show «false», from P_or_Q_closed x this\n ),\n ⟨P_closed, Q_closed⟩\n\nlemma prop.closed.not.inv {P: prop}: closed P.not → closed P :=\n assume P_not_closed: closed P.not,\n show closed P, from (\n assume x: var,\n assume : x ∈ FV P,\n have x ∈ FV P.not, from free_in_prop.not this,\n show «false», from P_not_closed x this\n )\n\nlemma prop.closed.implies.inv {P Q: prop}: closed (prop.implies P Q) → closed P ∧ closed Q :=\n assume P_not_or_Q_closed: closed (P.not ⋁ Q),\n have P_not_closed: closed P.not, from (prop.closed.or.inv P_not_or_Q_closed).left,\n have P_closed: closed P, from prop.closed.not.inv P_not_closed,\n have Q_closed: closed Q, from (prop.closed.or.inv P_not_or_Q_closed).right,\n ⟨P_closed, Q_closed⟩\n\nlemma vc.closed.and {P Q: vc}: closed P → closed Q → closed (P ⋀ Q) :=\n assume P_closed: closed P,\n assume Q_closed: closed Q,\n show closed (P ⋀ Q), from (\n assume x: var,\n assume : x ∈ FV (P ⋀ Q),\n or.elim (free_in_vc.and.inv this) (\n assume : x ∈ FV P,\n show «false», from P_closed x this\n ) (\n assume : x ∈ FV Q,\n show «false», from Q_closed x this\n )\n )\n\nlemma vc.closed.or {P Q: vc}: closed P → closed Q → closed (P ⋁ Q) :=\n assume P_closed: closed P,\n assume Q_closed: closed Q,\n show closed (P ⋁ Q), from (\n assume x: var,\n assume : x ∈ FV (P ⋁ Q),\n or.elim (free_in_vc.or.inv this) (\n assume : x ∈ FV P,\n show «false», from P_closed x this\n ) (\n assume : x ∈ FV Q,\n show «false», from Q_closed x this\n )\n )\n\nlemma vc.closed.not {P: vc}: closed P → closed P.not :=\n assume P_closed: closed P,\n show closed P.not, from (\n assume x: var,\n assume : x ∈ FV P.not,\n have x ∈ FV P, from free_in_vc.not.inv this,\n show «false», from P_closed x this\n )\n\nlemma vc.closed.implies {P Q: vc}: closed P → closed Q → closed (vc.implies P Q) :=\n assume P_closed: closed P,\n have P_not_closed: closed P.not, from vc.closed.not P_closed,\n assume Q_closed: closed Q,\n show closed (P.not ⋁ Q), from vc.closed.or P_not_closed Q_closed\n\nlemma vc.closed.term.inv {t: term}: closed (vc.term t) → closed t :=\n assume h: closed (vc.term t),\n assume x: var,\n assume : x ∈ FV t,\n have x ∈ FV (vc.term t), from free_in_vc.term this,\n show «false», from h x this\n\nlemma vc.closed.and.inv {P Q: vc}: closed (P ⋀ Q) → (closed P ∧ closed Q) :=\n assume P_and_Q_closed: closed (P ⋀ Q),\n have P_closed: closed P, from (\n assume x: var,\n assume : x ∈ FV P,\n have x ∈ FV (P ⋀ Q), from free_in_vc.and₁ this,\n show «false», from P_and_Q_closed x this\n ),\n have Q_closed: closed Q, from (\n assume x: var,\n assume : x ∈ FV Q,\n have x ∈ FV (P ⋀ Q), from free_in_vc.and₂ this,\n show «false», from P_and_Q_closed x this\n ),\n ⟨P_closed, Q_closed⟩\n\nlemma vc.closed.or.inv {P Q: vc}: closed (P ⋁ Q) → (closed P ∧ closed Q) :=\n assume P_or_Q_closed: closed (P ⋁ Q),\n have P_closed: closed P, from (\n assume x: var,\n assume : x ∈ FV P,\n have x ∈ FV (P ⋁ Q), from free_in_vc.or₁ this,\n show «false», from P_or_Q_closed x this\n ),\n have Q_closed: closed Q, from (\n assume x: var,\n assume : x ∈ FV Q,\n have x ∈ FV (P ⋁ Q), from free_in_vc.or₂ this,\n show «false», from P_or_Q_closed x this\n ),\n ⟨P_closed, Q_closed⟩\n\nlemma vc.closed.not.inv {P: vc}: closed P.not → closed P :=\n assume P_not_closed: closed P.not,\n show closed P, from (\n assume x: var,\n assume : x ∈ FV P,\n have x ∈ FV P.not, from free_in_vc.not this,\n show «false», from P_not_closed x this\n )\n\nlemma vc.closed.implies.inv {P Q: vc}: closed (vc.implies P Q) → closed P ∧ closed Q :=\n assume P_not_or_Q_closed: closed (P.not ⋁ Q),\n have P_not_closed: closed P.not, from (vc.closed.or.inv P_not_or_Q_closed).left,\n have P_closed: closed P, from vc.closed.not.inv P_not_closed,\n have Q_closed: closed Q, from (vc.closed.or.inv P_not_or_Q_closed).right,\n ⟨P_closed, Q_closed⟩\n\nlemma free_in_prop_of_free_in_to_vc {P: prop}: FV P.to_vc ⊆ FV P :=\n begin\n assume x: var,\n assume x_free: x ∈ FV P.to_vc,\n induction P,\n case prop.term t {\n unfold prop.to_vc at x_free,\n apply free_in_prop.term,\n from free_in_vc.term.inv x_free\n },\n case prop.not P₁ ih {\n unfold prop.to_vc at x_free,\n apply free_in_prop.not,\n have h1, from free_in_vc.not.inv x_free,\n from ih h1\n },\n case prop.and P₁ P₂ P₁_ih P₂_ih {\n unfold prop.to_vc at x_free,\n cases (free_in_vc.and.inv x_free),\n\n apply free_in_prop.and₁,\n from P₁_ih a,\n\n apply free_in_prop.and₂,\n from P₂_ih a\n },\n case prop.or P₁ P₂ P₁_ih P₂_ih {\n unfold prop.to_vc at x_free,\n cases (free_in_vc.or.inv x_free),\n\n apply free_in_prop.or₁,\n from P₁_ih a,\n\n apply free_in_prop.or₂,\n from P₂_ih a\n },\n case prop.pre t₁ t₂ {\n unfold prop.to_vc at x_free,\n cases (free_in_vc.pre.inv x_free),\n\n apply free_in_prop.pre₁,\n from a,\n\n apply free_in_prop.pre₂,\n from a\n },\n case prop.pre₁ op t {\n unfold prop.to_vc at x_free,\n apply free_in_prop.preop,\n from free_in_vc.pre₁.inv x_free\n },\n case prop.pre₂ op t₁ t₂ {\n unfold prop.to_vc at x_free,\n cases (free_in_vc.pre₂.inv x_free),\n\n apply free_in_prop.preop₁,\n from a,\n\n apply free_in_prop.preop₂,\n from a\n },\n case prop.call t {\n unfold prop.to_vc at x_free,\n have h2, from free_in_vc.term.inv x_free,\n show x ∈ FV (prop.call t), from absurd h2 free_in_term.value.inv\n },\n case prop.post t₁ t₂ {\n unfold prop.to_vc at x_free,\n cases (free_in_vc.post.inv x_free),\n\n apply free_in_prop.post₁,\n from a,\n\n apply free_in_prop.post₂,\n from a\n },\n case prop.forallc y P₁ P₁_ih {\n unfold prop.to_vc at x_free,\n have h1, from free_in_vc.univ.inv x_free,\n apply free_in_prop.forallc,\n from h1.left,\n from P₁_ih h1.right\n },\n case prop.exis y P₁ P₁_ih {\n unfold prop.to_vc at x_free,\n have h1, from free_in_vc.not.inv x_free,\n have h2, from free_in_vc.univ.inv h1,\n apply free_in_prop.exis,\n from h2.left,\n have h3, from free_in_vc.not.inv h2.right,\n from P₁_ih h3\n }\n end\n\nlemma free_in_prop_of_free_in_erased {P: prop}:\n FV P.erased_p ⊆ FV P ∧ FV P.erased_n ⊆ FV P :=\n begin\n induction P,\n\n case prop.term t {\n split,\n\n assume x: var,\n assume x_free: x ∈ FV (prop.term t).erased_p,\n unfold prop.erased_p at x_free,\n apply free_in_prop.term,\n from free_in_vc.term.inv x_free,\n\n assume x: var,\n assume x_free: x ∈ FV (prop.term t).erased_n,\n unfold prop.erased_n at x_free,\n apply free_in_prop.term,\n from free_in_vc.term.inv x_free\n },\n case prop.not P₁ ih {\n split,\n\n assume x: var,\n assume x_free: x ∈ FV P₁.not.erased_p,\n unfold prop.erased_p at x_free,\n apply free_in_prop.not,\n have h1, from free_in_vc.not.inv x_free,\n from ih.right h1,\n\n assume x: var,\n assume x_free: x ∈ FV P₁.not.erased_n,\n unfold prop.erased_n at x_free,\n apply free_in_prop.not,\n have h1, from free_in_vc.not.inv x_free,\n from ih.left h1\n },\n case prop.and P₁ P₂ P₁_ih P₂_ih {\n split,\n\n assume x: var,\n assume x_free: x ∈ FV (P₁ ⋀ P₂).erased_p,\n unfold prop.erased_p at x_free,\n cases (free_in_vc.and.inv x_free),\n apply free_in_prop.and₁,\n from P₁_ih.left a,\n apply free_in_prop.and₂,\n from P₂_ih.left a,\n\n assume x: var,\n assume x_free: x ∈ FV (P₁ ⋀ P₂).erased_n,\n unfold prop.erased_n at x_free,\n cases (free_in_vc.and.inv x_free),\n apply free_in_prop.and₁,\n from P₁_ih.right a,\n apply free_in_prop.and₂,\n from P₂_ih.right a\n },\n case prop.or P₁ P₂ P₁_ih P₂_ih {\n split,\n\n assume x: var,\n assume x_free: x ∈ FV (P₁ ⋁ P₂).erased_p,\n unfold prop.erased_p at x_free,\n cases (free_in_vc.or.inv x_free),\n apply free_in_prop.or₁,\n from P₁_ih.left a,\n apply free_in_prop.or₂,\n from P₂_ih.left a,\n\n assume x: var,\n assume x_free: x ∈ FV (P₁ ⋁ P₂).erased_n,\n unfold prop.erased_n at x_free,\n cases (free_in_vc.or.inv x_free),\n apply free_in_prop.or₁,\n from P₁_ih.right a,\n apply free_in_prop.or₂,\n from P₂_ih.right a\n },\n case prop.pre t₁ t₂ {\n split,\n\n assume x: var,\n assume x_free: x ∈ FV (prop.pre t₁ t₂).erased_p,\n unfold prop.erased_p at x_free,\n cases (free_in_vc.pre.inv x_free),\n\n apply free_in_prop.pre₁,\n from a,\n\n apply free_in_prop.pre₂,\n from a,\n\n assume x: var,\n assume x_free: x ∈ FV (prop.pre t₁ t₂).erased_n,\n unfold prop.erased_n at x_free,\n cases (free_in_vc.pre.inv x_free),\n\n apply free_in_prop.pre₁,\n from a,\n\n apply free_in_prop.pre₂,\n from a\n },\n case prop.pre₁ op t {\n split,\n\n assume x: var,\n assume x_free: x ∈ FV (prop.pre₁ op t).erased_p,\n unfold prop.erased_p at x_free,\n apply free_in_prop.preop,\n from free_in_vc.pre₁.inv x_free,\n\n assume x: var,\n assume x_free: x ∈ FV (prop.pre₁ op t).erased_n,\n unfold prop.erased_n at x_free,\n apply free_in_prop.preop,\n from free_in_vc.pre₁.inv x_free\n },\n case prop.pre₂ op t₁ t₂ {\n split,\n\n assume x: var,\n assume x_free: x ∈ FV (prop.pre₂ op t₁ t₂).erased_p,\n unfold prop.erased_p at x_free,\n cases (free_in_vc.pre₂.inv x_free),\n\n apply free_in_prop.preop₁,\n from a,\n\n apply free_in_prop.preop₂,\n from a,\n\n assume x: var,\n assume x_free: x ∈ FV (prop.pre₂ op t₁ t₂).erased_n,\n unfold prop.erased_n at x_free,\n cases (free_in_vc.pre₂.inv x_free),\n\n apply free_in_prop.preop₁,\n from a,\n\n apply free_in_prop.preop₂,\n from a\n },\n case prop.call t {\n split,\n\n assume x: var,\n assume x_free: x ∈ FV (prop.call t).erased_p,\n unfold prop.erased_p at x_free,\n have h2, from free_in_vc.term.inv x_free,\n show x ∈ FV (prop.call t), from absurd h2 free_in_term.value.inv,\n\n assume x: var,\n assume x_free: x ∈ FV (prop.call t).erased_n,\n unfold prop.erased_n at x_free,\n have h2, from free_in_vc.term.inv x_free,\n show x ∈ FV (prop.call t), from absurd h2 free_in_term.value.inv\n },\n case prop.post t₁ t₂ {\n split,\n\n assume x: var,\n assume x_free: x ∈ FV (prop.post t₁ t₂).erased_p,\n unfold prop.erased_p at x_free,\n cases (free_in_vc.post.inv x_free),\n\n apply free_in_prop.post₁,\n from a,\n\n apply free_in_prop.post₂,\n from a,\n\n assume x: var,\n assume x_free: x ∈ FV (prop.post t₁ t₂).erased_n,\n unfold prop.erased_n at x_free,\n cases (free_in_vc.post.inv x_free),\n\n apply free_in_prop.post₁,\n from a,\n\n apply free_in_prop.post₂,\n from a\n },\n case prop.forallc y P₁ P₁_ih {\n split,\n\n assume x: var,\n assume x_free: x ∈ FV (prop.forallc y P₁).erased_p,\n unfold prop.erased_p at x_free,\n have h2, from free_in_vc.term.inv x_free,\n show x ∈ FV (prop.forallc y P₁), from absurd h2 free_in_term.value.inv,\n\n assume x: var,\n assume x_free: x ∈ FV (prop.forallc y P₁).erased_n,\n unfold prop.erased_n at x_free,\n have h1, from free_in_vc.univ.inv x_free,\n apply free_in_prop.forallc,\n from h1.left,\n from P₁_ih.right h1.right\n },\n case prop.exis y P₁ P₁_ih {\n split,\n\n assume x: var,\n assume x_free: x ∈ FV (prop.exis y P₁).erased_p,\n unfold prop.erased_p at x_free,\n have h1, from free_in_vc.not.inv x_free,\n have h2, from free_in_vc.univ.inv h1,\n apply free_in_prop.exis,\n from h2.left,\n have h3, from free_in_vc.not.inv h2.right,\n from P₁_ih.left h3,\n\n assume x: var,\n assume x_free: x ∈ FV (prop.exis y P₁).erased_n,\n unfold prop.erased_n at x_free,\n have h1, from free_in_vc.not.inv x_free,\n have h2, from free_in_vc.univ.inv h1,\n apply free_in_prop.exis,\n from h2.left,\n have h3, from free_in_vc.not.inv h2.right,\n from P₁_ih.right h3\n }\n end\n\nlemma free_in_instantiate_to_vc_of_free_in_to_vc {P: prop} {t: calltrigger}:\n FV P.to_vc ⊆ FV (P.instantiate_with_p t).to_vc ∧\n FV P.to_vc ⊆ FV (P.instantiate_with_n t).to_vc :=\n begin\n induction P,\n\n case prop.term t {\n split,\n\n unfold prop.instantiate_with_p,\n from set.subset.refl (FV (prop.to_vc (prop.term t))),\n\n unfold prop.instantiate_with_n,\n from set.subset.refl (FV (prop.to_vc (prop.term t)))\n },\n case prop.not P₁ ih {\n split,\n\n unfold prop.instantiate_with_p,\n unfold prop.to_vc,\n\n assume x: var,\n assume x_free: x ∈ FV (vc.not (prop.to_vc P₁)),\n apply free_in_vc.not,\n have h1, from free_in_vc.not.inv x_free,\n change (x ∈ FV (prop.to_vc (prop.instantiate_with_n P₁ t))),\n from set.mem_of_mem_of_subset h1 ih.right,\n\n unfold prop.instantiate_with_n,\n unfold prop.to_vc,\n\n assume x: var,\n assume x_free: x ∈ FV (vc.not (prop.to_vc P₁)),\n apply free_in_vc.not,\n have h1, from free_in_vc.not.inv x_free,\n change (x ∈ FV (prop.to_vc (prop.instantiate_with_p P₁ t))),\n from set.mem_of_mem_of_subset h1 ih.left\n },\n case prop.and P₁ P₂ P₁_ih P₂_ih {\n split,\n\n assume x: var,\n assume x_free: x ∈ FV (P₁ ⋀ P₂).to_vc,\n unfold prop.to_vc at x_free,\n unfold prop.instantiate_with_p,\n change (x ∈ FV (prop.to_vc (prop.and (prop.instantiate_with_p P₁ t) (prop.instantiate_with_p P₂ t)))),\n unfold prop.to_vc,\n cases (free_in_vc.and.inv x_free),\n apply free_in_vc.and₁,\n from P₁_ih.left a,\n apply free_in_vc.and₂,\n from P₂_ih.left a,\n\n assume x: var,\n assume x_free: x ∈ FV (P₁ ⋀ P₂).to_vc,\n unfold prop.to_vc at x_free,\n unfold prop.instantiate_with_n,\n change (x ∈ FV (prop.to_vc (prop.and (prop.instantiate_with_n P₁ t) (prop.instantiate_with_n P₂ t)))),\n unfold prop.to_vc,\n cases (free_in_vc.and.inv x_free),\n apply free_in_vc.and₁,\n from P₁_ih.right a,\n apply free_in_vc.and₂,\n from P₂_ih.right a\n },\n case prop.or P₁ P₂ P₁_ih P₂_ih {\n split,\n\n assume x: var,\n assume x_free: x ∈ FV (P₁ ⋁ P₂).to_vc,\n unfold prop.to_vc at x_free,\n unfold prop.instantiate_with_p,\n change (x ∈ FV (prop.to_vc (prop.or (prop.instantiate_with_p P₁ t) (prop.instantiate_with_p P₂ t)))),\n unfold prop.to_vc,\n cases (free_in_vc.or.inv x_free),\n apply free_in_vc.or₁,\n from P₁_ih.left a,\n apply free_in_vc.or₂,\n from P₂_ih.left a,\n\n assume x: var,\n assume x_free: x ∈ FV (P₁ ⋁ P₂).to_vc,\n unfold prop.to_vc at x_free,\n unfold prop.instantiate_with_n,\n change (x ∈ FV (prop.to_vc (prop.or (prop.instantiate_with_n P₁ t) (prop.instantiate_with_n P₂ t)))),\n unfold prop.to_vc,\n cases (free_in_vc.or.inv x_free),\n apply free_in_vc.or₁,\n from P₁_ih.right a,\n apply free_in_vc.or₂,\n from P₂_ih.right a\n },\n case prop.pre t₁ t₂ {\n split,\n\n unfold prop.instantiate_with_p,\n from set.subset.refl (FV (prop.to_vc (prop.pre t₁ t₂))),\n\n unfold prop.instantiate_with_n,\n from set.subset.refl (FV (prop.to_vc (prop.pre t₁ t₂)))\n },\n case prop.pre₁ op t {\n split,\n\n unfold prop.instantiate_with_p,\n from set.subset.refl (FV (prop.to_vc (prop.pre₁ op t))),\n\n unfold prop.instantiate_with_n,\n from set.subset.refl (FV (prop.to_vc (prop.pre₁ op t)))\n },\n case prop.pre₂ op t₁ t₂ {\n split,\n\n unfold prop.instantiate_with_p,\n from set.subset.refl (FV (prop.to_vc (prop.pre₂ op t₁ t₂))),\n\n unfold prop.instantiate_with_n,\n from set.subset.refl (FV (prop.to_vc (prop.pre₂ op t₁ t₂)))\n },\n case prop.call t {\n split,\n\n unfold prop.instantiate_with_p,\n from set.subset.refl (FV (prop.to_vc (prop.call t))),\n\n unfold prop.instantiate_with_n,\n from set.subset.refl (FV (prop.to_vc (prop.call t)))\n },\n case prop.post t₁ t₂ {\n split,\n\n unfold prop.instantiate_with_p,\n from set.subset.refl (FV (prop.to_vc (prop.post t₁ t₂))),\n\n unfold prop.instantiate_with_n,\n from set.subset.refl (FV (prop.to_vc (prop.post t₁ t₂)))\n },\n case prop.forallc y P₁ P₁_ih {\n split,\n\n unfold prop.instantiate_with_p,\n assume x: var,\n assume x_free: x ∈ FV (prop.to_vc (prop.forallc y P₁)),\n change x ∈ FV (prop.to_vc (prop.and (prop.forallc y P₁) (prop.substt y (t.x) P₁))),\n unfold1 prop.to_vc,\n apply free_in_vc.and₁,\n from x_free,\n\n unfold prop.instantiate_with_n,\n from set.subset.refl (FV (prop.to_vc (prop.forallc y P₁)))\n },\n case prop.exis y P₁ P₁_ih {\n split,\n\n unfold prop.instantiate_with_p,\n from set.subset.refl (FV (prop.to_vc (prop.exis y P₁))),\n\n unfold prop.instantiate_with_n,\n from set.subset.refl (FV (prop.to_vc (prop.exis y P₁)))\n }\n end\n\nlemma free_in_instantiate_with_of_free_in_prop {P: prop} {t: calltrigger}:\n FV P ⊆ FV (P.instantiate_with_p t) ∧\n FV P ⊆ FV (P.instantiate_with_n t) :=\n begin\n induction P,\n\n case prop.term t {\n split,\n\n unfold prop.instantiate_with_p,\n from set.subset.refl (FV (prop.term t)),\n\n unfold prop.instantiate_with_n,\n from set.subset.refl (FV (prop.term t))\n },\n case prop.not P₁ ih {\n split,\n\n unfold prop.instantiate_with_p,\n\n assume x: var,\n assume x_free: x ∈ FV (prop.not P₁),\n apply free_in_prop.not,\n have h1, from free_in_prop.not.inv x_free,\n change (x ∈ FV (prop.instantiate_with_n P₁ t)),\n from set.mem_of_mem_of_subset h1 ih.right,\n\n unfold prop.instantiate_with_n,\n\n assume x: var,\n assume x_free: x ∈ FV (prop.not P₁),\n apply free_in_prop.not,\n have h1, from free_in_prop.not.inv x_free,\n change (x ∈ FV (prop.instantiate_with_p P₁ t)),\n from set.mem_of_mem_of_subset h1 ih.left\n },\n case prop.and P₁ P₂ P₁_ih P₂_ih {\n split,\n\n assume x: var,\n assume x_free: x ∈ FV (P₁ ⋀ P₂),\n unfold prop.instantiate_with_p,\n cases (free_in_prop.and.inv x_free),\n apply free_in_prop.and₁,\n from P₁_ih.left a,\n apply free_in_prop.and₂,\n from P₂_ih.left a,\n\n assume x: var,\n assume x_free: x ∈ FV (P₁ ⋀ P₂),\n unfold prop.instantiate_with_n,\n cases (free_in_prop.and.inv x_free),\n apply free_in_prop.and₁,\n from P₁_ih.right a,\n apply free_in_prop.and₂,\n from P₂_ih.right a\n },\n case prop.or P₁ P₂ P₁_ih P₂_ih {\n split,\n\n assume x: var,\n assume x_free: x ∈ FV (P₁ ⋁ P₂),\n unfold prop.instantiate_with_p,\n cases (free_in_prop.or.inv x_free),\n apply free_in_prop.or₁,\n from P₁_ih.left a,\n apply free_in_prop.or₂,\n from P₂_ih.left a,\n\n assume x: var,\n assume x_free: x ∈ FV (P₁ ⋁ P₂),\n unfold prop.instantiate_with_n,\n cases (free_in_prop.or.inv x_free),\n apply free_in_prop.or₁,\n from P₁_ih.right a,\n apply free_in_prop.or₂,\n from P₂_ih.right a\n },\n case prop.pre t₁ t₂ {\n split,\n\n unfold prop.instantiate_with_p,\n from set.subset.refl (FV (prop.pre t₁ t₂)),\n\n unfold prop.instantiate_with_n,\n from set.subset.refl (FV (prop.pre t₁ t₂))\n },\n case prop.pre₁ op t {\n split,\n\n unfold prop.instantiate_with_p,\n from set.subset.refl (FV (prop.pre₁ op t)),\n\n unfold prop.instantiate_with_n,\n from set.subset.refl (FV (prop.pre₁ op t))\n },\n case prop.pre₂ op t₁ t₂ {\n split,\n\n unfold prop.instantiate_with_p,\n from set.subset.refl (FV (prop.pre₂ op t₁ t₂)),\n\n unfold prop.instantiate_with_n,\n from set.subset.refl (FV (prop.pre₂ op t₁ t₂))\n },\n case prop.call t {\n split,\n\n unfold prop.instantiate_with_p,\n from set.subset.refl (FV (prop.call t)),\n\n unfold prop.instantiate_with_n,\n from set.subset.refl (FV (prop.call t))\n },\n case prop.post t₁ t₂ {\n split,\n\n unfold prop.instantiate_with_p,\n from set.subset.refl (FV (prop.post t₁ t₂)),\n\n unfold prop.instantiate_with_n,\n from set.subset.refl (FV (prop.post t₁ t₂))\n },\n case prop.forallc y P₁ P₁_ih {\n split,\n\n unfold prop.instantiate_with_p,\n\n assume x: var,\n assume x_free: x ∈ FV (prop.forallc y P₁),\n apply free_in_prop.and₁,\n from x_free,\n\n unfold prop.instantiate_with_n,\n from set.subset.refl (FV (prop.forallc y P₁))\n },\n case prop.exis y P₁ P₁_ih {\n split,\n\n unfold prop.instantiate_with_p,\n from set.subset.refl (FV (prop.exis y P₁)),\n\n unfold prop.instantiate_with_n,\n from set.subset.refl (FV (prop.exis y P₁))\n }\n end\n\ninstance {x: var} {t: term}: decidable (free_in_term x t) :=\n begin\n induction t with v y unop t₁ ih₁ binop t₂ t₃ ih₂ ih₃ t₄ t₅ ih₄ ih₅,\n\n show decidable (free_in_term x (term.value v)), by begin\n from is_false (free_in_term.value.inv)\n end,\n\n show decidable (free_in_term x (term.var y)), by begin\n by_cases (x = y) with h1,\n\n rw[h1],\n from is_true (free_in_term.var y),\n apply is_false, \n assume h2,\n have h3, from free_in_term.var.inv h2,\n contradiction\n end,\n\n show decidable (free_in_term x (term.unop unop t₁)), by begin\n by_cases (free_in_term x t₁) with h1,\n from is_true (free_in_term.unop h1),\n apply is_false,\n assume h2,\n have h3, from free_in_term.unop.inv h2,\n contradiction\n end,\n\n show decidable (free_in_term x (term.binop binop t₂ t₃)), by begin\n by_cases (free_in_term x t₂) with h1,\n from is_true (free_in_term.binop₁ h1),\n\n by_cases (free_in_term x t₃) with h2,\n from is_true (free_in_term.binop₂ h2),\n apply is_false,\n assume h3,\n have h4, from free_in_term.binop.inv h3,\n cases h4 with h5 h6,\n contradiction,\n contradiction\n end,\n\n show decidable (free_in_term x (term.app t₄ t₅)), by begin\n by_cases (free_in_term x t₄) with h1,\n from is_true (free_in_term.app₁ h1),\n\n by_cases (free_in_term x t₅) with h2,\n from is_true (free_in_term.app₂ h2),\n apply is_false,\n assume h3,\n have h4, from free_in_term.app.inv h3,\n cases h4 with h5 h6,\n contradiction,\n contradiction\n end\n end\n\ninstance {x: var} {P: prop}: decidable (free_in_prop x P) :=\n begin\n induction P,\n case prop.term t {\n by_cases (free_in_term x t) with h1,\n from is_true (free_in_prop.term h1),\n apply is_false,\n assume h2,\n have h3, from free_in_prop.term.inv h2,\n contradiction\n },\n case prop.not P₁ ih {\n by_cases (free_in_prop x P₁) with h1,\n from is_true (free_in_prop.not h1),\n apply is_false,\n assume h2,\n have h3, from free_in_prop.not.inv h2,\n contradiction\n },\n case prop.and P₁ P₂ P₁_ih P₂_ih {\n by_cases (free_in_prop x P₁) with h1,\n from is_true (free_in_prop.and₁ h1),\n\n by_cases (free_in_prop x P₂) with h2,\n from is_true (free_in_prop.and₂ h2),\n apply is_false,\n assume h3,\n have h4, from free_in_prop.and.inv h3,\n cases h4 with h5 h6,\n contradiction,\n contradiction\n },\n case prop.or P₁ P₂ P₁_ih P₂_ih {\n by_cases (free_in_prop x P₁) with h1,\n from is_true (free_in_prop.or₁ h1),\n\n by_cases (free_in_prop x P₂) with h2,\n from is_true (free_in_prop.or₂ h2),\n apply is_false,\n assume h3,\n have h4, from free_in_prop.or.inv h3,\n cases h4 with h5 h6,\n contradiction,\n contradiction\n },\n case prop.pre t₁ t₂ {\n by_cases (free_in_term x t₁) with h1,\n from is_true (free_in_prop.pre₁ h1),\n\n by_cases (free_in_term x t₂) with h2,\n from is_true (free_in_prop.pre₂ h2),\n apply is_false,\n assume h3,\n have h4, from free_in_prop.pre.inv h3,\n cases h4 with h5 h6,\n contradiction,\n contradiction\n },\n case prop.pre₁ op t {\n by_cases (free_in_term x t) with h1,\n from is_true (free_in_prop.preop h1),\n apply is_false,\n assume h2,\n have h3, from free_in_prop.pre₁.inv h2,\n contradiction\n },\n case prop.pre₂ op t₁ t₂ {\n by_cases (free_in_term x t₁) with h1,\n from is_true (free_in_prop.preop₁ h1),\n\n by_cases (free_in_term x t₂) with h2,\n from is_true (free_in_prop.preop₂ h2),\n apply is_false,\n assume h3,\n have h4, from free_in_prop.pre₂.inv h3,\n cases h4 with h5 h6,\n contradiction,\n contradiction\n },\n case prop.call t {\n by_cases (free_in_term x t) with h1,\n from is_true (free_in_prop.call h1),\n apply is_false,\n assume h2,\n have h3, from free_in_prop.call.inv h2,\n contradiction\n },\n case prop.post t₁ t₂ {\n by_cases (free_in_term x t₁) with h1,\n from is_true (free_in_prop.post₁ h1),\n\n by_cases (free_in_term x t₂) with h2,\n from is_true (free_in_prop.post₂ h2),\n apply is_false,\n assume h3,\n have h4, from free_in_prop.post.inv h3,\n cases h4 with h5 h6,\n contradiction,\n contradiction\n },\n case prop.forallc y P' P'_ih {\n by_cases (x = y) with h1,\n rw[h1],\n apply is_false,\n assume h2,\n have h3, from free_in_prop.forallc.inv h2,\n from h3.left rfl,\n\n by_cases (free_in_prop x P') with h2,\n from is_true (free_in_prop.forallc h1 h2),\n apply is_false,\n assume h3,\n have h4, from free_in_prop.forallc.inv h3,\n from h2 h4.right\n },\n case prop.exis y P' P'_ih {\n by_cases (x = y) with h1,\n rw[h1],\n apply is_false,\n assume h2,\n have h3, from free_in_prop.exis.inv h2,\n from h3.left rfl,\n\n by_cases (free_in_prop x P') with h2,\n from is_true (free_in_prop.exis h1 h2),\n apply is_false,\n assume h3,\n have h4, from free_in_prop.exis.inv h3,\n from h2 h4.right\n }\n end\n\ninstance {x: var} {P: vc}: decidable (free_in_vc x P) :=\n begin\n induction P,\n case vc.term t {\n by_cases (free_in_term x t) with h1,\n from is_true (free_in_vc.term h1),\n apply is_false,\n assume h2,\n have h3, from free_in_vc.term.inv h2,\n contradiction\n },\n case vc.not P₁ ih {\n by_cases (free_in_vc x P₁) with h1,\n from is_true (free_in_vc.not h1),\n apply is_false,\n assume h2,\n have h3, from free_in_vc.not.inv h2,\n contradiction\n },\n case vc.and P₁ P₂ P₁_ih P₂_ih {\n by_cases (free_in_vc x P₁) with h1,\n from is_true (free_in_vc.and₁ h1),\n\n by_cases (free_in_vc x P₂) with h2,\n from is_true (free_in_vc.and₂ h2),\n apply is_false,\n assume h3,\n have h4, from free_in_vc.and.inv h3,\n cases h4 with h5 h6,\n contradiction,\n contradiction\n },\n case vc.or P₁ P₂ P₁_ih P₂_ih {\n by_cases (free_in_vc x P₁) with h1,\n from is_true (free_in_vc.or₁ h1),\n\n by_cases (free_in_vc x P₂) with h2,\n from is_true (free_in_vc.or₂ h2),\n apply is_false,\n assume h3,\n have h4, from free_in_vc.or.inv h3,\n cases h4 with h5 h6,\n contradiction,\n contradiction\n },\n case vc.pre t₁ t₂ {\n by_cases (free_in_term x t₁) with h1,\n from is_true (free_in_vc.pre₁ h1),\n\n by_cases (free_in_term x t₂) with h2,\n from is_true (free_in_vc.pre₂ h2),\n apply is_false,\n assume h3,\n have h4, from free_in_vc.pre.inv h3,\n cases h4 with h5 h6,\n contradiction,\n contradiction\n },\n case vc.pre₁ op t {\n by_cases (free_in_term x t) with h1,\n from is_true (free_in_vc.preop h1),\n apply is_false,\n assume h2,\n have h3, from free_in_vc.pre₁.inv h2,\n contradiction\n },\n case vc.pre₂ op t₁ t₂ {\n by_cases (free_in_term x t₁) with h1,\n from is_true (free_in_vc.preop₁ h1),\n\n by_cases (free_in_term x t₂) with h2,\n from is_true (free_in_vc.preop₂ h2),\n apply is_false,\n assume h3,\n have h4, from free_in_vc.pre₂.inv h3,\n cases h4 with h5 h6,\n contradiction,\n contradiction\n },\n case vc.post t₁ t₂ {\n by_cases (free_in_term x t₁) with h1,\n from is_true (free_in_vc.post₁ h1),\n\n by_cases (free_in_term x t₂) with h2,\n from is_true (free_in_vc.post₂ h2),\n apply is_false,\n assume h3,\n have h4, from free_in_vc.post.inv h3,\n cases h4 with h5 h6,\n contradiction,\n contradiction\n },\n case vc.univ y P' P'_ih {\n by_cases (x = y) with h1,\n rw[h1],\n apply is_false,\n assume h2,\n have h3, from free_in_vc.univ.inv h2,\n from h3.left rfl,\n\n by_cases (free_in_vc x P') with h2,\n from is_true (free_in_vc.univ h1 h2),\n apply is_false,\n assume h3,\n have h4, from free_in_vc.univ.inv h3,\n from h2 h4.right\n }\n end\n\nlemma term.fresh_var_is_not_free {t: term}: ∀y, y ≥ t.fresh_var → y ∉ FV t :=\n begin\n induction t with v z unop t₁ t₁_ih binop t₂ t₃ t₂_ih t₃_ih t₄ t₅ t₄_ih t₅_ih,\n\n show ∀y : var, y ≥ term.fresh_var (term.value v) → y ∉ FV (term.value v), by begin\n assume y,\n assume h1,\n from free_in_term.value.inv\n end,\n\n show ∀y: var, y ≥ term.fresh_var (term.var z) → y ∉ FV (term.var z), by begin\n assume y,\n assume h1,\n assume h2,\n have h3: (y = z), from free_in_term.var.inv h2,\n rw[h3] at h1,\n unfold term.fresh_var at h1,\n have h3: z < z + 1, from lt_of_add_one,\n have h4, from not_lt_of_ge h1,\n contradiction\n end,\n\n show ∀y: var, y ≥ term.fresh_var (term.unop unop t₁) → y ∉ FV (term.unop unop t₁), by begin\n assume y,\n assume h1,\n assume h2,\n have h3, from free_in_term.unop.inv h2,\n unfold term.fresh_var at h1,\n from t₁_ih y h1 h3\n end,\n\n show ∀y: var, y ≥ term.fresh_var (term.binop binop t₂ t₃) → y ∉ FV (term.binop binop t₂ t₃), by begin\n assume y,\n assume h1,\n assume h2,\n unfold term.fresh_var at h1,\n cases (free_in_term.binop.inv h2) with h3 h3,\n\n have h4: (term.fresh_var t₂ ≤ max (term.fresh_var t₂) (term.fresh_var t₃)),\n from le_max_left (term.fresh_var t₂) (term.fresh_var t₃),\n have h5, from ge_trans h1 h4,\n from t₂_ih y h5 h3,\n\n have h4: (term.fresh_var t₃ ≤ max (term.fresh_var t₂) (term.fresh_var t₃)),\n from le_max_right (term.fresh_var t₂) (term.fresh_var t₃),\n have h5, from ge_trans h1 h4,\n from t₃_ih y h5 h3\n end,\n\n show ∀y: var, y ≥ term.fresh_var (term.app t₄ t₅) → y ∉ FV (term.app t₄ t₅), by begin\n assume y,\n assume h1,\n assume h2,\n unfold term.fresh_var at h1,\n cases (free_in_term.app.inv h2) with h3 h3,\n\n have h4: (term.fresh_var t₄ ≤ max (term.fresh_var t₄) (term.fresh_var t₅)),\n from le_max_left (term.fresh_var t₄) (term.fresh_var t₅),\n have h5, from ge_trans h1 h4,\n from t₄_ih y h5 h3,\n\n have h4: (term.fresh_var t₅ ≤ max (term.fresh_var t₄) (term.fresh_var t₅)),\n from le_max_right (term.fresh_var t₄) (term.fresh_var t₅),\n have h5, from ge_trans h1 h4,\n from t₅_ih y h5 h3\n end\n end\n\nlemma prop.fresh_var_is_unused {P: prop}: ∀x, x ≥ P.fresh_var → ¬ prop.uses_var x P :=\n begin\n induction P,\n\n case prop.term t {\n assume y,\n assume h1,\n assume h2,\n cases h2 with _ h3,\n unfold prop.fresh_var at h1,\n from term.fresh_var_is_not_free y h1 h3\n },\n\n case prop.not P₁ P₁_ih {\n assume y,\n assume h1,\n assume h2,\n cases h2 with _ _ _ h3,\n unfold prop.fresh_var at h1,\n from P₁_ih y h1 h3\n },\n\n case prop.and P₁ P₂ P₁_ih P₂_ih {\n assume y,\n assume h1,\n assume h2,\n unfold prop.fresh_var at h1,\n cases h2 with _ _ _ _ _ _ h3 _ _ h3,\n\n have h4: (prop.fresh_var P₁ ≤ max (prop.fresh_var P₁) (prop.fresh_var P₂)),\n from le_max_left (prop.fresh_var P₁) (prop.fresh_var P₂),\n have h5, from ge_trans h1 h4,\n from P₁_ih y h5 h3,\n\n have h4: (prop.fresh_var P₂ ≤ max (prop.fresh_var P₁) (prop.fresh_var P₂)),\n from le_max_right (prop.fresh_var P₁) (prop.fresh_var P₂),\n have h5, from ge_trans h1 h4,\n from P₂_ih y h5 h3\n },\n\n case prop.or P₁ P₂ P₁_ih P₂_ih {\n assume y,\n assume h1,\n assume h2,\n unfold prop.fresh_var at h1,\n cases h2 with _ _ _ _ _ _ _ _ _ _ _ _ h3 _ _ h3,\n\n have h4: (prop.fresh_var P₁ ≤ max (prop.fresh_var P₁) (prop.fresh_var P₂)),\n from le_max_left (prop.fresh_var P₁) (prop.fresh_var P₂),\n have h5, from ge_trans h1 h4,\n from P₁_ih y h5 h3,\n\n have h4: (prop.fresh_var P₂ ≤ max (prop.fresh_var P₁) (prop.fresh_var P₂)),\n from le_max_right (prop.fresh_var P₁) (prop.fresh_var P₂),\n have h5, from ge_trans h1 h4,\n from P₂_ih y h5 h3\n },\n\n case prop.pre t₁ t₂ {\n assume y,\n assume h1,\n assume h2,\n unfold prop.fresh_var at h1,\n cases h2 with _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ h3 _ _ h3,\n\n have h4: (term.fresh_var t₁ ≤ max (term.fresh_var t₁) (term.fresh_var t₂)),\n from le_max_left (term.fresh_var t₁) (term.fresh_var t₂),\n have h5, from ge_trans h1 h4,\n from term.fresh_var_is_not_free y h5 h3,\n\n have h4: (term.fresh_var t₂ ≤ max (term.fresh_var t₁) (term.fresh_var t₂)),\n from le_max_right (term.fresh_var t₁) (term.fresh_var t₂),\n have h5, from ge_trans h1 h4,\n from term.fresh_var_is_not_free y h5 h3\n },\n\n case prop.pre₁ op t {\n assume y,\n assume h1,\n assume h2,\n cases h2,\n unfold prop.fresh_var at h1,\n from term.fresh_var_is_not_free y h1 a\n },\n\n case prop.pre₂ op t₁ t₂ {\n assume y,\n assume h1,\n assume h2,\n unfold prop.fresh_var at h1,\n cases h2,\n\n have h4: (term.fresh_var t₁ ≤ max (term.fresh_var t₁) (term.fresh_var t₂)),\n from le_max_left (term.fresh_var t₁) (term.fresh_var t₂),\n have h5, from ge_trans h1 h4,\n from term.fresh_var_is_not_free y h5 a,\n\n have h4: (term.fresh_var t₂ ≤ max (term.fresh_var t₁) (term.fresh_var t₂)),\n from le_max_right (term.fresh_var t₁) (term.fresh_var t₂),\n have h5, from ge_trans h1 h4,\n from term.fresh_var_is_not_free y h5 a\n },\n\n case prop.call t {\n assume y,\n assume h1,\n assume h2,\n cases h2,\n unfold prop.fresh_var at h1,\n from term.fresh_var_is_not_free y h1 a\n },\n\n case prop.post t₁ t₂ {\n assume y,\n assume h1,\n assume h2,\n unfold prop.fresh_var at h1,\n cases h2,\n\n have h4: (term.fresh_var t₁ ≤ max (term.fresh_var t₁) (term.fresh_var t₂)),\n from le_max_left (term.fresh_var t₁) (term.fresh_var t₂),\n have h5, from ge_trans h1 h4,\n from term.fresh_var_is_not_free y h5 a,\n\n have h4: (term.fresh_var t₂ ≤ max (term.fresh_var t₁) (term.fresh_var t₂)),\n from le_max_right (term.fresh_var t₁) (term.fresh_var t₂),\n have h5, from ge_trans h1 h4,\n from term.fresh_var_is_not_free y h5 a\n },\n\n case prop.forallc z P₁ P₁_ih {\n assume y,\n assume h1,\n assume h2,\n unfold prop.fresh_var at h1,\n cases h2,\n \n have h4: (prop.fresh_var P₁ ≤ max (z + 1) (prop.fresh_var P₁)),\n from le_max_right (z + 1) (prop.fresh_var P₁),\n have h5, from ge_trans h1 h4,\n from P₁_ih y h5 a,\n\n have h4: (z + 1 ≤ max (z + 1) (prop.fresh_var P₁)),\n from le_max_left (z + 1) (prop.fresh_var P₁),\n have h5, from ge_trans h1 h4,\n have h3: z < z + 1, from lt_of_add_one,\n have h4, from not_lt_of_ge h1,\n contradiction\n },\n\n case prop.exis z P₁ P₁_ih {\n assume y,\n assume h1,\n assume h2,\n unfold prop.fresh_var at h1,\n cases h2,\n \n have h4: (prop.fresh_var P₁ ≤ max (z + 1) (prop.fresh_var P₁)),\n from le_max_right (z + 1) (prop.fresh_var P₁),\n have h5, from ge_trans h1 h4,\n from P₁_ih y h5 a,\n\n have h4: (z + 1 ≤ max (z + 1) (prop.fresh_var P₁)),\n from le_max_left (z + 1) (prop.fresh_var P₁),\n have h5, from ge_trans h1 h4,\n have h3: z < z + 1, from lt_of_add_one,\n have h4, from not_lt_of_ge h1,\n contradiction\n }\n end\n\nlemma vc.uses_var_of_free {x: var} {P: vc}: x ∈ FV P → vc.uses_var x P :=\n begin\n assume h1,\n induction P,\n case vc.term t {\n from vc.uses_var.term (free_in_vc.term.inv h1)\n },\n case vc.not P₁ P₁_ih {\n from vc.uses_var.not (P₁_ih (free_in_vc.not.inv h1))\n },\n case vc.and P₁ P₂ P₁_ih P₂_ih {\n cases (free_in_vc.and.inv h1) with h2 h3,\n\n from vc.uses_var.and₁ (P₁_ih h2),\n from vc.uses_var.and₂ (P₂_ih h3)\n },\n case vc.or P₁ P₂ P₁_ih P₂_ih {\n cases (free_in_vc.or.inv h1) with h2 h3,\n\n from vc.uses_var.or₁ (P₁_ih h2),\n from vc.uses_var.or₂ (P₂_ih h3)\n },\n case vc.pre t₁ t₂ {\n cases (free_in_vc.pre.inv h1) with h2 h3,\n\n from vc.uses_var.pre₁ h2,\n from vc.uses_var.pre₂ h3\n },\n case vc.pre₁ op t {\n from vc.uses_var.preop (free_in_vc.pre₁.inv h1)\n },\n case vc.pre₂ op t₁ t₂ {\n cases (free_in_vc.pre₂.inv h1) with h2 h3,\n\n from vc.uses_var.preop₁ h2,\n from vc.uses_var.preop₂ h3\n },\n case vc.post t₁ t₂ {\n cases (free_in_vc.post.inv h1) with h2 h3,\n\n from vc.uses_var.post₁ h2,\n from vc.uses_var.post₂ h3\n },\n case vc.univ y P' P'_ih {\n have h2, from free_in_vc.univ.inv h1,\n from vc.uses_var.univ (P'_ih h2.right)\n }\n end\n\nlemma vc.uses_var.term.inv {t: term} {x: var}: vc.uses_var x t → x ∈ FV t :=\n assume x_free_in_not: vc.uses_var x t,\n begin\n cases x_free_in_not,\n case vc.uses_var.term free_in_P { from free_in_P }\n end\n\nlemma vc.uses_var.not.inv {P: vc} {x: var}: vc.uses_var x P.not → vc.uses_var x P :=\n assume x_free_in_not: vc.uses_var x P.not,\n begin\n cases x_free_in_not,\n case vc.uses_var.not free_in_P { from free_in_P }\n end\n\nlemma vc.uses_var.and.inv {P₁ P₂: vc} {x: var}: vc.uses_var x (P₁ ⋀ P₂) → vc.uses_var x P₁ ∨ vc.uses_var x P₂ :=\n assume x_free_in_and: vc.uses_var x (P₁ ⋀ P₂),\n begin\n cases x_free_in_and,\n case vc.uses_var.and₁ free_in_P₁ {\n show vc.uses_var x P₁ ∨ vc.uses_var x P₂, from or.inl free_in_P₁\n },\n case vc.uses_var.and₂ free_in_P₂ {\n show vc.uses_var x P₁ ∨ vc.uses_var x P₂, from or.inr free_in_P₂\n }\n end\n\nlemma vc.uses_var.or.inv {P₁ P₂: vc} {x: var}: vc.uses_var x (P₁ ⋁ P₂) → vc.uses_var x P₁ ∨ vc.uses_var x P₂ :=\n assume x_free_in_or: vc.uses_var x (P₁ ⋁ P₂),\n begin\n cases x_free_in_or,\n case vc.uses_var.or₁ free_in_P₁ {\n show vc.uses_var x P₁ ∨ vc.uses_var x P₂, from or.inl free_in_P₁\n },\n case vc.uses_var.or₂ free_in_P₂ {\n show vc.uses_var x P₁ ∨ vc.uses_var x P₂, from or.inr free_in_P₂\n }\n end\n\nlemma vc.uses_var.univ.inv {P: vc} {x y: var}: vc.uses_var x (vc.univ y P) → (x = y) ∨ vc.uses_var x P :=\n assume x_free_in_univ: vc.uses_var x (vc.univ y P),\n begin\n cases x_free_in_univ,\n case vc.uses_var.univ h1 {\n from or.inr h1\n },\n case vc.uses_var.quantified h1 {\n from or.inl rfl\n }\n end\n\nlemma prop_uses_var_of_to_vc_uses_var {x: var} {P: prop}: vc.uses_var x P.to_vc → prop.uses_var x P :=\n begin\n assume h1,\n\n induction P,\n\n case prop.term t {\n unfold prop.to_vc at h1,\n cases h1,\n from prop.uses_var.term a\n },\n\n case prop.not P₁ P₁_ih {\n unfold prop.to_vc at h1,\n have h2, from vc.uses_var.not.inv h1,\n apply prop.uses_var.not,\n from P₁_ih h2\n },\n\n case prop.and P₁ P₂ P₁_ih P₂_ih {\n unfold prop.to_vc at h1,\n cases vc.uses_var.and.inv h1 with h2 h3,\n apply prop.uses_var.and₁,\n from P₁_ih h2,\n apply prop.uses_var.and₂,\n from P₂_ih h3\n },\n\n case prop.or P₁ P₂ P₁_ih P₂_ih {\n unfold prop.to_vc at h1,\n cases vc.uses_var.or.inv h1 with h2 h3,\n apply prop.uses_var.or₁,\n from P₁_ih h2,\n apply prop.uses_var.or₂,\n from P₂_ih h3\n },\n\n case prop.pre t₁ t₂ {\n unfold prop.to_vc at h1,\n cases h1,\n from prop.uses_var.pre₁ a,\n from prop.uses_var.pre₂ a\n },\n\n case prop.pre₁ op t {\n unfold prop.to_vc at h1,\n cases h1,\n from prop.uses_var.preop a\n },\n\n case prop.pre₂ op t₁ t₂ {\n unfold prop.to_vc at h1,\n cases h1,\n from prop.uses_var.preop₁ a,\n from prop.uses_var.preop₂ a\n },\n\n case prop.call t {\n unfold prop.to_vc at h1,\n have h2, from vc.uses_var.term.inv h1,\n have h3: ¬ free_in_term x value.true, from free_in_term.value.inv,\n contradiction\n },\n\n case prop.post t₁ t₂ {\n unfold prop.to_vc at h1,\n cases h1,\n from prop.uses_var.post₁ a,\n from prop.uses_var.post₂ a\n },\n\n case prop.forallc z P₁ P₁_ih {\n unfold prop.to_vc at h1,\n cases vc.uses_var.univ.inv h1 with h2 h3,\n\n rw[h2],\n from prop.uses_var.uquantified z,\n\n apply prop.uses_var.forallc,\n from P₁_ih h3\n },\n\n case prop.exis z P₁ P₁_ih {\n unfold prop.to_vc at h1,\n have h2, from vc.uses_var.not.inv h1,\n cases vc.uses_var.univ.inv h2 with h3 h4,\n\n rw[h3],\n from prop.uses_var.equantified z,\n\n apply prop.uses_var.exis,\n have h5, from vc.uses_var.not.inv h4,\n from P₁_ih h5\n }\n end\n\nlemma to_vc_closed_of_closed {P: prop}: closed P → closed P.to_vc :=\n assume P_closed: closed P,\n assume x: var,\n assume : x ∈ FV P.to_vc,\n have x ∈ FV P, from set.mem_of_mem_of_subset this free_in_prop_of_free_in_to_vc,\n show «false», from P_closed x this\n\nlemma free_in_prop.implies₁ {x: var} {P Q: prop}: free_in_prop x P → free_in_prop x (prop.implies P Q) :=\n begin\n assume h1,\n unfold prop.implies,\n apply free_in_prop.or₁,\n from free_in_prop.not h1\n end\n\nlemma free_in_prop.implies₂ {x: var} {P Q: prop}: free_in_prop x Q → free_in_prop x (prop.implies P Q) :=\n begin\n assume h1,\n unfold prop.implies,\n apply free_in_prop.or₂,\n from h1\n end\n", "meta": {"author": "levjj", "repo": "esverify-theory", "sha": "8565b123c87b0113f83553d7732cd6696c9b5807", "save_path": "github-repos/lean/levjj-esverify-theory", "path": "github-repos/lean/levjj-esverify-theory/esverify-theory-8565b123c87b0113f83553d7732cd6696c9b5807/src/freevars.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.044018646100611195, "lm_q1q2_score": 0.0213217555079728}} {"text": "/-\nBinaryTools: Utilities for displaying and manipulating Binary data.\n-/\nnamespace Neptune\n\n/-\nSimplification rules for proving that a ByteArray is of a particular size.\n-/\n@[simp] theorem ByteArray.size_empty : ByteArray.empty.size = 0 := rfl\n\n@[simp] theorem ByteArray.size_push (B : ByteArray) (a : UInt8) : (B.push a).size = B.size + 1 :=\nby { cases B; simp only [ByteArray.push, ByteArray.size, Array.size_push] }\n\n@[simp] theorem List.to_ByteArray_size : (L : List UInt8) → L.toByteArray.size = L.length\n| [] => rfl\n| a::l => by simp [List.toByteArray, to_ByteArray_loop_size]\nwhere to_ByteArray_loop_size :\n (L : List UInt8) → (B : ByteArray) → (List.toByteArray.loop L B).size = L.length + B.size\n| [], B => by simp [List.toByteArray.loop]\n| a::l, B => by\n simp [List.toByteArray.loop, to_ByteArray_loop_size]\n rw [Nat.add_succ, Nat.succ_add]\n\nuniverse u\nuniverse v\n\n/-\nType class for default conversion between two types.\n-/\nclass Into (Target: Type v) (Source: Type u) :=\n (into: Source → Target)\n\nexport Into (into)\n\ninstance (A: Type u) : Into A A := ⟨id⟩\n\ninstance (A: Type u) (h: A → Prop) : Into A (Subtype h) := ⟨Subtype.val⟩\n\n/-\nTransitivity\n-/\ninstance (A B C: Type u) [Into B C] [Into A B] : Into A C := ⟨fun c : C =>\n let b: B := Into.into c;\n Into.into b⟩\n\ninstance : Into ByteArray String := {\n into := String.toUTF8\n}\n\nnamespace Alphabet\ndef base2: String := \"01\"\ndef base8: String := \"01234567\"\ndef base10: String := \"0123456789\"\ndef base16: String := \"0123456789abcdef\"\ndef base16upper: String := \"0123456789ABCDEF\"\ndef base32: String := \"abcdefghijklmnopqrstuvwxyz234567\"\ndef base32upper: String := \"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567\"\ndef base32hex : String := \"0123456789abcdefghijklmnopqrstuv\"\ndef base32hexupper : String := \"0123456789ABCDEFGHIJKLMNOPQRSTUV\"\ndef base32z : String := \"ybndrfg8ejkmcpqxot1uwisza345h769\"\ndef base36 : String := \"0123456789abcdefghijklmnopqrstuvwxyz\"\ndef base36upper : String := \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\ndef base58flickr : String := \n \"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ\"\ndef base58btc : String := \n \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\"\ndef base64 : String := \n \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\"\ndef base64url : String := \n \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_\"\n\nend Alphabet\n\n/-\nEncode a ByteArray as a base64 String\n-/\ndef toBase64 {I: Type u} [Into ByteArray I] (input : I) (pad: Bool := true) : String := Id.run do\n let input : ByteArray := Into.into input\n let x := ByteArray.size input % 3\n let mut bytes := input\n let mut str := \"\"\n if x == 1 then bytes := bytes.append [0x00, 0x00].toByteArray\n if x == 2 then bytes := bytes.append [0x00].toByteArray\n for i in [:(bytes.size / 3)] do\n let b0 := bytes.data[3 * i]\n let b1 := bytes.data[3 * i + 1]\n let b2 := bytes.data[3 * i + 2]\n let s0 := b0.shiftRight 2\n let s1 := UInt8.xor\n ((b0.land 0b00000011).shiftLeft 4) \n ((b1.land 0b11110000).shiftRight 4)\n let s2 := UInt8.xor\n ((b1.land 0b00001111).shiftLeft 2) \n ((b2.land 0b11000000).shiftRight 6)\n let s3 := b2.land 0b00111111\n str := str.push (Alphabet.base64.get s0.toNat)\n str := str.push (Alphabet.base64.get s1.toNat)\n str := str.push (Alphabet.base64.get s2.toNat)\n str := str.push (Alphabet.base64.get s3.toNat)\n if pad then do\n if x == 1 then \n str := str.set (str.length - 1) '='\n str := str.set (str.length - 2) '='\n if x == 2 then \n str := str.set (str.length - 1) '='\n return str\n else \n if x == 1 then str := str.dropRight 2\n if x == 2 then str := str.dropRight 1\n return str\n", "meta": {"author": "lurk-lab", "repo": "Neptune.lean", "sha": "f6ae655926d2d0272f94e300fbb4854929ae13e2", "save_path": "github-repos/lean/lurk-lab-Neptune.lean", "path": "github-repos/lean/lurk-lab-Neptune.lean/Neptune.lean-f6ae655926d2d0272f94e300fbb4854929ae13e2/src/Neptune/BinaryTools.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38121956625615, "lm_q2_score": 0.05582313799303738, "lm_q1q2_score": 0.02128087245276292}} {"text": "/-\nCopyright (c) 2019 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Leonardo de Moura\n-/\nimport Lean.Expr\n\nnamespace Lean.Meta\n\n/-! See file `DiscrTree.lean` for the actual implementation and documentation. -/\n\nnamespace DiscrTree\n/--\nDiscrimination tree key. See `DiscrTree`\n-/\ninductive Key (simpleReduce : Bool) where\n | const : Name → Nat → Key simpleReduce\n | fvar : FVarId → Nat → Key simpleReduce\n | lit : Literal → Key simpleReduce\n | star : Key simpleReduce\n | other : Key simpleReduce\n | arrow : Key simpleReduce\n | proj : Name → Nat → Nat → Key simpleReduce\n deriving Inhabited, BEq, Repr\n\nprotected def Key.hash : Key s → UInt64\n | Key.const n a => mixHash 5237 $ mixHash (hash n) (hash a)\n | Key.fvar n a => mixHash 3541 $ mixHash (hash n) (hash a)\n | Key.lit v => mixHash 1879 $ hash v\n | Key.star => 7883\n | Key.other => 2411\n | Key.arrow => 17\n | Key.proj s i a => mixHash (hash a) $ mixHash (hash s) (hash i)\n\ninstance : Hashable (Key s) := ⟨Key.hash⟩\n\n/--\nDiscrimination tree trie. See `DiscrTree`.\n-/\ninductive Trie (α : Type) (simpleReduce : Bool) where\n | node (vs : Array α) (children : Array (Key simpleReduce × Trie α simpleReduce)) : Trie α simpleReduce\n\nend DiscrTree\n\nopen DiscrTree\n\n/--\nDiscrimination trees. It is an index from terms to values of type `α`.\n\nIf `simpleReduce := true`, then only simple reduction are performed while\nindexing/retrieving terms. For example, `iota` reduction is not performed.\n\nWe use `simpleReduce := false` in the type class resolution module,\nand `simpleReduce := true` in `simp`.\n\nMotivations:\n- In `simp`, we want to have `simp` theorem such as\n```\n@[simp] theorem liftOn_mk (a : α) (f : α → γ) (h : ∀ a₁ a₂, r a₁ a₂ → f a₁ = f a₂) :\n Quot.liftOn (Quot.mk r a) f h = f a := rfl\n```\nIf we enable `iota`, then the lhs is reduced to `f a`.\n\n- During type class resolution, we often want to reduce types using even `iota`.\nExample:\n```\ninductive Ty where\n | int\n | bool\n\n@[reducible] def Ty.interp (ty : Ty) : Type :=\n Ty.casesOn (motive := fun _ => Type) ty Int Bool\n\ndef test {a b c : Ty} (f : a.interp → b.interp → c.interp) (x : a.interp) (y : b.interp) : c.interp :=\n f x y\n\ndef f (a b : Ty.bool.interp) : Ty.bool.interp :=\n -- We want to synthesize `BEq Ty.bool.interp` here, and it will fail\n -- if we do not reduce `Ty.bool.interp` to `Bool`.\n test (.==.) a b\n```\n-/\nstructure DiscrTree (α : Type) (simpleReduce : Bool) where\n root : PersistentHashMap (Key simpleReduce) (Trie α simpleReduce) := {}\n\nend Lean.Meta\n", "meta": {"author": "leanprover", "repo": "lean4", "sha": "742d053a97bdd109a41a921facd1cd6a55e89bc7", "save_path": "github-repos/lean/leanprover-lean4", "path": "github-repos/lean/leanprover-lean4/lean4-742d053a97bdd109a41a921facd1cd6a55e89bc7/src/Lean/Meta/DiscrTreeTypes.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46101679412289653, "lm_q2_score": 0.04603390059969198, "lm_q1q2_score": 0.02122240127544208}} {"text": "/-\nCopyright (c) 2020 Anne Baanen. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Anne Baanen\n\nThe `simp_rw` tactic, a mix of `simp` and `rewrite`.\n-/\nimport tactic.core\n\n/-!\n# The `simp_rw` tactic\n\nThis module defines a tactic `simp_rw` which functions as a mix of `simp` and\n`rw`. Like `rw`, it applies each rewrite rule in the given order, but like\n`simp` it repeatedly applies these rules and also under binders like `∀ x, ...`,\n`∃ x, ...` and `λ x, ...`.\n\n## Implementation notes\n\nThe tactic works by taking each rewrite rule in turn and applying `simp only` to\nit. Arguments to `simp_rw` are of the format used by `rw` and are translated to\ntheir equivalents for `simp`.\n-/\n\nnamespace tactic.interactive\nopen interactive interactive.types tactic\n\n/--\n`simp_rw` functions as a mix of `simp` and `rw`. Like `rw`, it applies each\nrewrite rule in the given order, but like `simp` it repeatedly applies these\nrules and also under binders like `∀ x, ...`, `∃ x, ...` and `λ x, ...`.\n\nUsage:\n - `simp_rw [lemma_1, ..., lemma_n]` will rewrite the goal by applying the\n lemmas in that order. A lemma preceded by `←` is applied in the reverse direction.\n - `simp_rw [lemma_1, ..., lemma_n] at h₁ ... hₙ` will rewrite the given hypotheses.\n - `simp_rw [...] at ⊢ h₁ ... hₙ` rewrites the goal as well as the given hypotheses.\n - `simp_rw [...] at *` rewrites in the whole context: all hypotheses and the goal.\n\nLemmas passed to `simp_rw` must be expressions that are valid arguments to `simp`.\n\nFor example, neither `simp` nor `rw` can solve the following, but `simp_rw` can:\n```lean\nexample {α β : Type} {f : α → β} {t : set β} :\n (∀ s, f '' s ⊆ t) = ∀ s : set α, ∀ x ∈ s, x ∈ f ⁻¹' t :=\nby simp_rw [set.image_subset_iff, set.subset_def]\n```\n-/\nmeta def simp_rw (q : parse rw_rules) (l : parse location) : tactic unit :=\nq.rules.mmap' (λ rule, do\n let simp_arg := if rule.symm\n then simp_arg_type.symm_expr rule.rule\n else simp_arg_type.expr rule.rule,\n save_info rule.pos,\n simp none none tt [simp_arg] [] l) -- equivalent to `simp only [rule] at l`\n\nadd_tactic_doc\n{ name := \"simp_rw\",\n category := doc_category.tactic,\n decl_names := [`tactic.interactive.simp_rw],\n tags := [\"simplification\"] }\n\nend tactic.interactive\n", "meta": {"author": "JLimperg", "repo": "aesop3", "sha": "a4a116f650cc7403428e72bd2e2c4cda300fe03f", "save_path": "github-repos/lean/JLimperg-aesop3", "path": "github-repos/lean/JLimperg-aesop3/aesop3-a4a116f650cc7403428e72bd2e2c4cda300fe03f/src/tactic/simp_rw.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.22815650216092534, "lm_q2_score": 0.09268778553164236, "lm_q1q2_score": 0.021147320939941545}} {"text": "/-\nCopyright (c) 2022 Andrew Yang. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Andrew Yang\n-/\nimport morphisms.closed_immersion\nimport ring_theory.ring_hom.finite\nimport ring_theory.local_properties\nimport for_mathlib.epi_finite\n\n/-!\n\n# Finite morphisms\n\nA morphism of schemes is finite if it is affine and the component of the sheaf map on finite opens\nis finite.\nWe show that this property is local, and is stable under compositions and base-changes.\n\n-/\n\nnoncomputable theory\n\nopen category_theory category_theory.limits opposite topological_space\n\nuniverse u\n\nnamespace algebraic_geometry\n\nvariables {X Y : Scheme.{u}} (f : X ⟶ Y)\n\n/--\nA morphism is `finite` if the preimages of finite open sets are finite.\n-/\n@[mk_iff]\nclass finite (f : X ⟶ Y) extends affine f : Prop :=\n(is_finite_of_affine : ∀ U : opens Y.carrier, is_affine_open U → (f.1.c.app (op U)).finite)\n\ndef finite.affine_property : affine_target_morphism_property :=\naffine_and @ring_hom.finite\n\nlemma finite_eq_affine_property :\n @finite = target_affine_locally finite.affine_property :=\nby { ext, rw [finite_iff, finite.affine_property,\n affine_and_target_affine_locally_iff ring_hom.finite_respects_iso] }\n\nlemma finite.affine_property_is_local :\n finite.affine_property.is_local :=\nis_local_affine_and _ ring_hom.finite_respects_iso localization_finite finite_of_localization_span\n\nlemma finite_is_local_at_target :\n property_is_local_at_target @finite :=\nfinite_eq_affine_property.symm ▸ finite.affine_property_is_local.target_affine_locally_is_local\n\nlemma finite_respects_iso : morphism_property.respects_iso @finite :=\nfinite_is_local_at_target.respects_iso\n\nlemma finite_stable_under_composition : morphism_property.stable_under_composition @finite :=\nby { rw finite_eq_affine_property, exact affine_and_stable_under_composition @ring_hom.finite\n ring_hom.finite_stable_under_composition }\n\nlemma finite_stable_under_base_change : morphism_property.stable_under_base_change @finite :=\nby { rw finite_eq_affine_property, exact affine_and_stable_under_base_change _\n ring_hom.finite_respects_iso localization_finite finite_of_localization_span\n ring_hom.finite_stable_under_base_change }\n\nlemma finite_le_affine : @finite ≤ @affine :=\nby { rw finite_eq_affine_property, exact target_affine_locally_affine_and_le_affine _ }\n\n-- move me\nlemma _root_.category_theory.morphism_property.respects_iso.inf {C} [category C]\n {P₁ P₂ : morphism_property C} (h₁ : P₁.respects_iso) (h₂ : P₂.respects_iso) :\n (P₁ ⊓ P₂).respects_iso :=\n⟨λ _ _ _ _ _ ⟨H₁, H₂⟩, ⟨h₁.1 _ _ H₁, h₂.1 _ _ H₂⟩,\n λ _ _ _ _ _ ⟨H₁, H₂⟩, ⟨h₁.2 _ _ H₁, h₂.2 _ _ H₂⟩⟩\n\n-- move me\nlemma property_is_local_at_target.inf {P₁ P₂} (h₁ : property_is_local_at_target P₁)\n (h₂ : property_is_local_at_target P₂) : property_is_local_at_target (P₁ ⊓ P₂) :=\n⟨h₁.1.inf h₂.1, λ X Y f U H, ⟨h₁.2 _ _ H.1, h₂.2 _ _ H.2⟩, λ X Y f 𝒰 H,\n ⟨h₁.3 _ 𝒰 $ λ i, (H i).1, h₂.3 _ 𝒰 $ λ i, (H i).2⟩⟩\n\nlemma finite_Spec_iff {R S : CommRing} (f : R ⟶ S) :\n finite (Scheme.Spec.map f.op) ↔ ring_hom.finite f :=\nbegin\n rw [finite_eq_affine_property,\n finite.affine_property_is_local.affine_target_iff,\n finite.affine_property, affine_and_Spec_iff ring_hom.finite_respects_iso]\nend\n\nlemma is_closed_immersion_eq_finite_inf_mono :\n @is_closed_immersion = @finite ⊓ @mono Scheme _ :=\nbegin\n apply property_ext_of_le_affine is_closed_immersion_le_affine\n (inf_le_left.trans finite_le_affine) is_closed_immersion.is_local_at_target\n (finite_is_local_at_target.inf mono_is_local_at_target),\n intros R S f,\n simp_rw [is_closed_immersion_Spec_iff, pi.inf_apply, finite_Spec_iff],\n split,\n { rintro H,\n haveI := (is_closed_immersion_Spec_iff _).mpr H,\n exact ⟨ring_hom.finite.of_surjective _ H, infer_instance⟩ },\n { rintro ⟨h₁, h₂⟩,\n rw functor.mono_map_iff_mono at h₂,\n resetI,\n refine ring_hom.surjective_of_epi_of_finite _ _ h₁,\n convert @@category_theory.unop_epi_of_mono _ f.op h₂; exact CommRing.of_eq _ }\nend\n\n@[priority 100]\ninstance is_closed_immersion.to_finite {X Y : Scheme} (f : X ⟶ Y) [H : is_closed_immersion f] :\n finite f :=\nby { rw is_closed_immersion_eq_finite_inf_mono at H, exact H.1 }\n\ninstance finite_comp {X Y Z : Scheme} (f : X ⟶ Y) (g : Y ⟶ Z)\n [finite f] [finite g] : finite (f ≫ g) :=\nfinite_stable_under_composition _ _ infer_instance infer_instance\n\n-- lemma finite.affine_open_cover_tfae {X Y : Scheme.{u}} (f : X ⟶ Y) :\n-- tfae [finite f,\n-- ∃ (𝒰 : Scheme.open_cover.{u} Y) [∀ i, is_affine (𝒰.obj i)],\n-- ∀ (i : 𝒰.J), is_affine (pullback f (𝒰.map i)) ∧\n-- ring_hom.finite (Scheme.Γ.map (pullback.snd : pullback f (𝒰.map i) ⟶ _).op),\n-- ∀ (𝒰 : Scheme.open_cover.{u} Y) [∀ i, is_affine (𝒰.obj i)] (i : 𝒰.J),\n-- is_affine (pullback f (𝒰.map i)) ∧\n-- ring_hom.finite (Scheme.Γ.map (pullback.snd : pullback f (𝒰.map i) ⟶ _).op),\n-- ∀ {U : Scheme} (g : U ⟶ Y) [is_affine U] [is_open_immersion g],\n-- is_affine (pullback f g) ∧\n-- ring_hom.finite (Scheme.Γ.map (pullback.snd : pullback f g ⟶ _).op)] :=\n-- finite_eq_affine_property.symm ▸\n-- finite.affine_property_is_local.affine_open_cover_tfae f\n\n-- lemma finite.open_cover_tfae {X Y : Scheme.{u}} (f : X ⟶ Y) :\n-- tfae [finite f,\n-- ∃ (𝒰 : Scheme.open_cover.{u} Y), ∀ (i : 𝒰.J),\n-- finite (pullback.snd : (𝒰.pullback_cover f).obj i ⟶ 𝒰.obj i),\n-- ∀ (𝒰 : Scheme.open_cover.{u} Y) (i : 𝒰.J),\n-- finite (pullback.snd : (𝒰.pullback_cover f).obj i ⟶ 𝒰.obj i),\n-- ∀ (U : opens Y.carrier), finite (f ∣_ U),\n-- ∀ {U : Scheme} (g : U ⟶ Y) [is_open_immersion g],\n-- finite (pullback.snd : pullback f g ⟶ _)] :=\n-- affine_eq_affine_property.symm ▸\n-- affine_affine_property_is_local.open_cover_tfae f\n\nlemma finite_over_affine_iff [is_affine Y] :\n finite f ↔ is_affine X ∧ ring_hom.finite (Scheme.Γ.map f.op) :=\nfinite_eq_affine_property.symm ▸\n finite.affine_property_is_local.affine_target_iff f\n\nlemma finite.affine_open_cover_iff {X Y : Scheme.{u}} (𝒰 : Scheme.open_cover.{u} Y)\n [∀ i, is_affine (𝒰.obj i)] (f : X ⟶ Y) :\n finite f ↔ ∀ i, is_affine (pullback f (𝒰.map i)) ∧\n ring_hom.finite (Scheme.Γ.map (pullback.snd : pullback f (𝒰.map i) ⟶ _).op) :=\nfinite_eq_affine_property.symm ▸\n finite.affine_property_is_local.affine_open_cover_iff f 𝒰\n\nlemma finite.open_cover_iff {X Y : Scheme.{u}} (𝒰 : Scheme.open_cover.{u} Y)\n [∀ i, is_affine (𝒰.obj i)] (f : X ⟶ Y) :\n finite f ↔ ∀ i, finite (pullback.snd : pullback f (𝒰.map i) ⟶ _) :=\nfinite_eq_affine_property.symm ▸\n finite.affine_property_is_local.target_affine_locally_is_local.open_cover_iff f 𝒰\n\ninstance {X Y S : Scheme} (f : X ⟶ S) (g : Y ⟶ S) [finite g] :\n finite (pullback.fst : pullback f g ⟶ X) :=\nfinite_stable_under_base_change (is_pullback.of_has_pullback f g).flip infer_instance\n\ninstance {X Y S : Scheme} (f : X ⟶ S) (g : Y ⟶ S) [finite f] :\n finite (pullback.snd : pullback f g ⟶ Y) :=\nfinite_stable_under_base_change (is_pullback.of_has_pullback f g) infer_instance\n\nend algebraic_geometry", "meta": {"author": "erdOne", "repo": "lean-AG-morphisms", "sha": "bfb65e7d5c17f333abd7b1806717f12cd29427fd", "save_path": "github-repos/lean/erdOne-lean-AG-morphisms", "path": "github-repos/lean/erdOne-lean-AG-morphisms/lean-AG-morphisms-bfb65e7d5c17f333abd7b1806717f12cd29427fd/src/morphisms/finite.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4726834914771175, "lm_q2_score": 0.044680868523516944, "lm_q1q2_score": 0.02111990893592603}} {"text": "/-\n## Rewriting MLIR fragments with PDL\n\nThis file implements some framework support for PDL rewrites, which is used to\nformalize and prove rewrite operations. We interpret the matching section of\nPDL rewrites with the framework's basic pattern-matching tools, which allows us\nto unify (enrich) them with constraints specified by the dialect. This is\nimportant because we later need to reason on the semantics of matched programs,\nwhich are only defined if the constraints are met.\n\nThe end goal is to output a template theorem that looks like this:\n\n```lean4\n-- (unification variables)\n∀ (value_1: Value) (type_1: Type) (op_1: Operation),\n -- (non-unification-based constraints)\n is_float_type type_1 →\n\n semantics_of [mlir_bb|\n -- (symbolic pattern, almost verbatim from the `pdl.pattern` description)\n op_1 (value_1: type_1) 2\n ] =\n semantics_of [mlir_bb|\n -- (rewritten version of above)\n output_op_1 ...\n ]\n```\n\nFor readability/accessibility reasons, this statement would probably be\nsynthetized into Lean code rather than being a general theorem instantiated\nwith that particular PDL rewrite. The second option would require considering\n\"any matching basic block\" and then painstakingly proving that such a match has\nthe structure underlined by the PDL rewrite, which seems annoying.\n\nOperations of PDL that we support right now:\n\n* `pdl.operand`:\n Used as unification variable. Supports type requirement.\n* `pdl.operation`:\n Used as unification term.\n* `pdl.pattern`:\n Input operation for the whole rewriting workflow.\n* `pdl.result`:\n Utility to reference results from `pdl.operation` pointers\n* `pdl.type`:\n Used as unification variable.\n\nOperations of PDL that we should partially or totally express:\n\n* `pdl.attribute`:\n We don't have attributes yet\n* `pdl.erase`:\n We don't compute the target yet\n* `pdl.operation`:\n We should support attributes. And we don't handle the output either\n* `pdl.replace`:\n We don't compute the target yet\n* `pdl.rewrite`:\n One of the main components of the specification. We might not care about the\n root selection since we don't implement the pattern matching/search.\n\nOperations or features of PDL that we don't try to express (yet):\n\n* `pdl.operands`, `pdl.results`, `pdl.types`\n Anything related to ranges\n* `pdl.apply_native_constraint`, `pdl.apply_native_rewrite`:\n This is possible in principle, but requires the native constraints/rewrites\n to be rewritten in Lean, which is slightly inconvenient.\n* Use of native rewrite function in `pdl.rewrite`:\n Same as above\n* Using variadic arguments or matching operands with variadic arguments\n-/\n\nimport MLIR.Semantics.Types\nimport MLIR.Semantics.Matching\nimport MLIR.Semantics.Unification\nimport MLIR.AST\nimport MLIR.EDSL\nimport Lean.Exception\nimport Lean.Elab.Term\nopen Lean\n\nopen MLIR.AST\nopen MLIR.EDSL\n\n-- TODO: We updated to new matching but did not add regular type checks\n\n/- Utilities -/\n\nprivate def MLIR.AST.SSAVal.str: MLIR.AST.SSAVal → String\n | SSAVal.SSAVal s => s\n\n-- Get the n-th category of arguments from the specified variadic list by using\n-- the operand segment size attribute\nprivate def operandSegment (args: List SSAVal) (oss: TensorElem) (n: Nat) :=\n -- Flatten segment sizes\n let oss := match oss with\n | TensorElem.nested l => l.map (\n match · with | TensorElem.int i => i.toNat | _ => 0)\n | _ => []\n -- Accumulate\n let (oss, _) := oss.foldl\n (fun (segments, acc) size => (segments ++ [(acc, size)], acc + size))\n ([], 0)\n -- Get the segment for that argument\n let (start, size) := oss.getD n (0,0)\n (List.range size).filterMap (fun i => args.get? (i + start))\n\n\n/-\n### Monad for the analysis of PDL programs\n\nWhile PDL programs are mostly similar to match terms, the translation involves\nsome bookkeeping and fresh name generation. The Translation structure keeps\ntrack of this information, which is carried around in a state monad called\nTranslationM.\n-/\n\nstructure Translation (δ: Dialect α σ ε) where mk ::\n -- Unification problem\n u: Unification δ\n -- All variables defined so far (for fresh name generation)\n allvars: List String\n -- Typing judgements (to be inserted into operation terms)\n judgements: List (String × MTerm δ)\n -- List of operations that we want to collect after unification\n operations: List (MTerm δ)\n -- Names of results for each operation, and their types\n opresults: List (String × List (String × MTerm δ))\n -- Whether translation completed successfully\n success: Bool\n\ndef Translation.empty: Translation δ :=\n { u := Unification.empty,\n allvars := [],\n judgements := [],\n operations := [],\n opresults := [],\n success := false }\n\ninstance {δ: Dialect α σ ε} : Inhabited (Translation δ) := ⟨Translation.empty⟩\n\ndef Translation.str: Translation δ → String := fun tr =>\n \"Unification problem:\\n\" ++\n (toString tr.u) ++\n \"\\nAll variables:\\n \" ++\n (String.join $ tr.allvars.map (s!\" %{·}\")) ++\n \"\\nTyping judgements:\\n\" ++\n (String.join $ tr.judgements.map (fun (v,t) => s!\" %{v}: {t}\\n\")) ++\n \"Operation results:\\n\" ++\n (String.join $ tr.opresults.map (fun (n,l) => s!\" %{n}: {l}\\n\"))\n\nabbrev TranslationM (δ: Dialect α σ ε) := StateT (Translation δ) IO\n\ndef TranslationM.toIO {α} (tr: Translation δ) (x: TranslationM δ α): IO α :=\n Prod.fst <$> StateT.run x tr\n\ndef TranslationM.error {α} (s: String): TranslationM δ α :=\n throw <| IO.userError (s ++ \" o(x_x)o\")\n\n/-\n#### Name recording and name generation\n\nThe following monad functions are concerned with tracking variables,\nguaranteeing uniqueness, and generating fresh names.\n-/\n\n-- Record that [name] is now used in the problem, and check uniqueness\ndef TranslationM.addName (name: String): TranslationM δ Unit := do\n let tr ← get\n if name ∈ tr.allvars then\n error s!\"addName: {name} is already used!\"\n else\n set { tr with allvars := tr.allvars ++ [name] }\n\n-- Check that [name] is known\ndef TranslationM.checkNameDefined (name: String): TranslationM δ Unit := do\n let tr ← get\n if ! name ∈ tr.allvars then\n error s!\"checkNameDefined: {name} is undefined!\"\n\n-- Make up to [n] attempts at finding a fresh name by suffixing [s]\nprivate def TranslationM.freshNameAux (s: String) (n p: Nat):\n TranslationM δ String := do\n let tr ← get\n match n with\n | 0 =>\n return s\n | m+1 =>\n let s' := s!\"{s}{p}\"\n if tr.allvars.all (· != s') then\n set { tr with allvars := tr.allvars ++ [s'] }\n return s'\n else\n freshNameAux s m (p+1)\n\n-- Generate a new fresh name based on [name]; if not available, resort to\n-- adding numbered suffixes\ndef TranslationM.makeFreshName (name: String): TranslationM δ String := do\n let tr ← get\n if tr.allvars.all (· != name) then\n addName name\n return name\n else\n let f ← freshNameAux name (tr.allvars.length+1) 0\n addName f\n return f\n\n-- Generate [n] fresh names based on [name]\ndef TranslationM.makeFreshNames (name: String) (n: Nat):\n TranslationM δ (List String) :=\n (List.range n).mapM (fun idx => makeFreshName (name ++ toString idx))\n\n-- Generate a copy of the operation with the specified prefix and fresh names.\n-- Returns a pair with the new term and the list of all variables involved.\ndef TranslationM.makeFreshOp (prefix_: String) (op: MTerm δ) (priority: Nat):\n TranslationM δ (MTerm δ) := do\n let renameVars (done: List String) (vars: List (String × MSort)):\n TranslationM δ (List (String × MTerm δ) × List String) :=\n vars.foldlM\n (fun (repl, done) (var, sort) => do\n if var ∈ done then\n return (repl, done)\n else\n let var' ← makeFreshName (prefix_ ++ var)\n return (repl ++ [(var, MTerm.Var priority var' sort)], done ++ [var]))\n ([], done)\n\n let (repl, done) ← renameVars [] op.varsWithSorts\n return op.substVars repl\n\n\n/-\n#### Access to translation data\n\nThe following utilities query data recorded in the translation state.\n-/\n\ndef TranslationM.addEquation (equation: UEq δ): TranslationM δ Unit := do\n let tr ← get\n set { tr with u := { equations := tr.u.equations ++ [equation] } }\n\ndef TranslationM.addOperation (op: MTerm δ): TranslationM δ Unit := do\n let tr ← get\n set { tr with operations := tr.operations ++ [op] }\n\ndef TranslationM.addJudgement (s: String) (type: MTerm δ): TranslationM δ Unit := do\n let tr ← get\n set { tr with judgements := tr.judgements ++ [(s, type)] }\n\ndef TranslationM.addOpResults (name: String) (results: List (String × MTerm δ)):\n TranslationM δ Unit := do\n let tr ← get\n set { tr with opresults := tr.opresults ++ [(name, results)] }\n\n\ndef TranslationM.findJudgement? (s: String): TranslationM δ (Option (MTerm δ)) := do\n let cmpName := fun (name, type) => if name = s then some type else none\n return (← get).judgements.findSome? cmpName\n\ndef TranslationM.findJudgement (s: String): TranslationM δ (MTerm δ) := do\n match ← findJudgement? s with\n | some type => return type\n | none => error s!\"findJudgement: no type information for {s}!\"\n\ndef TranslationM.findJudgements (l: List String):\n TranslationM δ (List (String × MTerm δ)) :=\n l.mapM (fun var => do return (var, ← findJudgement var))\n\ndef TranslationM.findOpResult? (op: String) (idx: Nat):\n TranslationM δ (Option (String × MTerm δ)) := do\n let cmpName := fun (name, rets) => if name = op then rets.get? idx else none\n return (← get).opresults.findSome? cmpName\n\ndef TranslationM.findOpResult (op: String) (idx: Nat):\n TranslationM δ (String × MTerm δ) := do\n match ← findOpResult? op idx with\n | some info => return info\n | none => error s!\"findOpResultName: no return #{idx} for {op}!\"\n\n\n/-\n### Translation of PDL statements to match problems\n\nInterpretation PDL programs as match problems is fairly straightforward; most\nPDL operations simply add new names or equations to the. Most of the work is\nspent on parsing the input, adding new names and keeping track of information.\n\nPDL has a lot of restrictions on what you can write; you can't use the same\nvariable at two different places (implicit unification), you can't have a\ndeclaration operation (pdl.value, pdl.type, etc) without binding it to a\nvariable, etc. This allows us to make assumptions on the shape of the input.\n-/\n\nsection\nopen TranslationM\n\n-- TODO: Provide dialect data properly once implemented\nprivate def PDLToMatch.readStatement (operationMatchTerms: List (MTerm builtin))\n (op: Op builtin): TranslationM builtin Unit := do\n let tr ← get\n\n match op with\n -- %name = pdl.type\n | Op.mk \"pdl.type\" [⟨SSAVal.SSAVal name, .undefined \"pdl.type\"⟩]\n [] [] (AttrDict.mk []) => do\n IO.println s!\"Found new type variable: {name}\"\n addName name\n\n -- %name = pdl.type: TYPE\n | Op.mk \"pdl.type\" [⟨SSAVal.SSAVal name, .undefined \"pdl.type\"⟩]\n [] [] (AttrDict.mk [AttrEntry.mk \"type\" (AttrValue.type τ)]) => do\n IO.println s!\"Found new type variable: {name} (= {τ})\"\n addName name\n addEquation (.Var 1 name .MMLIRType, .ConstMLIRType τ)\n\n -- %name = pdl.operand\n | Op.mk \"pdl.operand\" [⟨SSAVal.SSAVal name, .undefined \"pdl.value\"⟩]\n [] [] (AttrDict.mk []) => do\n IO.println s!\"Found new variable: {name}\"\n addName name\n let typeName ← makeFreshName (name ++ \"_T\")\n IO.println s!\"→ Generated type name: {typeName}\"\n addJudgement name (.Var 1 typeName .MMLIRType)\n\n -- %name = pdl.operand: %typeName\n | Op.mk \"pdl.operand\" [⟨SSAVal.SSAVal name, .undefined \"pdl.value\"⟩]\n [⟨SSAVal.SSAVal typeName, .undefined \"pdl.type\"⟩] [] (AttrDict.mk []) => do\n IO.println s!\"Found new variable: {name} of type {typeName}\"\n addName name\n checkNameDefined typeName\n addJudgement name (.Var 0 typeName .MMLIRType)\n\n -- %name = pdl.operation \"OPNAME\"(ARGS) -> TYPE\n | Op.mk \"pdl.operation\" [⟨SSAVal.SSAVal name, _⟩] args [] attrs => do\n let (attributeNames, opname, operand_segment_sizes) :=\n (attrs.find \"attributeNames\",\n attrs.find \"name\",\n attrs.find \"operand_segment_sizes\")\n let argsVal := args.map Prod.fst\n\n match attributeNames, opname, operand_segment_sizes with\n | some (.list _),\n some (.str opname),\n some (builtin.dense_vector_attr oss _ _ _) =>\n let values := (operandSegment argsVal oss 0).map (·.str)\n let types := (operandSegment argsVal oss 2).map (·.str)\n IO.println s!\"Found new operation: {name} matching {opname}\"\n addName name\n\n IO.println s!\"→ Arguments: {values}, return types: {types}\"\n values.forM checkNameDefined\n types.forM checkNameDefined\n\n let valuesTypes ← findJudgements values\n let retNames ← makeFreshNames (name ++ \"_res\") types.length\n IO.println s!\"→ Arg types: {valuesTypes}, return names: {retNames}\"\n\n let insPattern := operationMatchTerms.find? fun\n | .App .OP [.ConstString n, _, _] => n = opname\n | _ => false\n if insPattern.isNone then\n error s!\"pdl.operation: no pattern known for {opname}!\"\n let insPattern := insPattern.get!\n\n IO.println s!\"→ Using match term: {insPattern}\"\n let ins ← makeFreshOp (name ++ \"_\") insPattern 2\n addOperation ins\n IO.println s!\"→ Instantiated match term: {ins}\"\n\n let operands_args: List (MTerm _) := valuesTypes.map (fun (v,t) =>\n .App .OPERAND [.Var 0 v .MSSAVal, t])\n let operands_rets: List (MTerm _) :=\n List.zip retNames types |>.map (fun (v, t) =>\n .App .OPERAND [.Var 1 v .MSSAVal, .Var 0 t .MMLIRType])\n let op_mterm :=\n .App .OP [\n .ConstString opname,\n .App (.LIST .MOperand) operands_args,\n .App (.LIST .MOperand) operands_rets\n ]\n addEquation (op_mterm, ins)\n\n let opResults := List.zip retNames (types.map (.Var 0 · .MMLIRType))\n addOpResults name opResults\n\n | _, _, _ =>\n error s!\"pdl.operation: unexpected attributes: {attrs}\"\n\n -- %name = pdl.result INDEX of %op\n | Op.mk \"pdl.result\" [⟨SSAVal.SSAVal name, .undefined \"pdl.value\"⟩]\n [⟨SSAVal.SSAVal opname, .undefined \"pdl.operation\"⟩] [] attrs => do\n match attrs.find \"index\" with\n | some (AttrValue.int index (MLIRType.int _ _)) =>\n IO.println\n s!\"Found new variable: {name} aliasing result {index} of {opname}\"\n checkNameDefined opname\n addName name\n\n let (resName, resType) ← findOpResult opname index.toNat\n addJudgement name resType\n addEquation (.Var 0 name .MSSAVal, .Var 1 resName .MSSAVal)\n\n | _ =>\n error s!\"pdl.result: unexpected attributes on {opname}: {attrs}\"\n\n | Op.mk \"pdl.rewrite\" [] args regions attrs =>\n return ()\n\n | _ => do\n error s!\"{op.name}: unrecognized PDL operation\"\n\ndef PDLToMatch.convert (PDLProgram: Op builtin)\n (operationMatchTerms: List (MTerm builtin)):\n TranslationM builtin Unit :=\n match PDLProgram with\n | Op.mk \"pdl.pattern\" _ [] [region] attrs =>\n match region with\n | Region.mk name [] stmts => do\n stmts.forM (readStatement operationMatchTerms)\n set { ← get with success := true }\n | Region.mk _ _ _ => do\n error (s!\"PDLToMatch.convert: expected only one BB with no \" ++\n \"arguments in the pattern region\")\n | Op.mk \"pdl.pattern\" _ _ _ _ => do\n error (s!\"PDLToMatch.convert: expected operation to have exactly one \" ++\n \"argument (a region):\\n{pattern}\")\n | _ => do\n error s!\"PDLToMatch.convert: not a PDL program: {PDLProgram}\"\n\ndef PDLToMatch.unify: TranslationM δ Unit := do\n let tr ← get\n if ! tr.success then\n error \"unify: translation did not complete successfully\"\n if let some u_unified ← tr.u.solve then\n set { tr with u := u_unified }\n else\n error \"unify: unification failed\"\n\ndef PDLToMatch.getOperationMatchTerms: TranslationM δ (List (MTerm δ)) := do\n let tr ← get\n return tr.operations.map tr.u.applyOnTerm\n\nend\n\n/-\n### Example PDL program\n-/\n\nprivate def ex_pdl: Op builtin := [mlir_op|\n \"pdl.pattern\"() ({\n -- %T0 = pdl.type\n %T0 = \"pdl.type\"() : () -> !\"pdl.type\"\n -- %T1 = pdl.type: i32\n %T1 = \"pdl.type\"() {type = i32} : () -> !\"pdl.type\"\n -- %v2 = pdl.operand\n %v2 = \"pdl.operand\"() : () -> !\"pdl.value\"\n -- %O3 = pdl.operation \"foo.op1\"(%v2) -> %T0\n %O3 = \"pdl.operation\"(%v2, %T0) {attributeNames = [], name = \"foo.op1\", operand_segment_sizes = dense<[1, 0, 1]> : vector<3×i32>} : (!\"pdl.value\", !\"pdl.type\") -> !\"pdl.operation\"\n -- %v4 = pdl.result 0 of %O3\n %v4 = \"pdl.result\"(%O3) {index = 0 : i32} : (!\"pdl.operation\") -> !\"pdl.value\"\n -- %v5 = pdl.operand: %T0\n %v5 = \"pdl.operand\"(%T0) : (!\"pdl.type\") -> !\"pdl.value\"\n -- %O6 = pdl.operation \"foo.op2\"(%v4, %v5) -> %T1\n %O6 = \"pdl.operation\"(%v4, %v5, %T1) {attributeNames = [], name = \"foo.op2\", operand_segment_sizes = dense<[2, 0, 1]> : vector<3×i32>} : (!\"pdl.value\", !\"pdl.value\", !\"pdl.type\") -> !\"pdl.operation\"\n\n -- TODO\n \"pdl.rewrite\"(%O6) ({\n \"pdl.replace\"(%O6, %v2) {operand_segment_sizes = dense<[1, 0, 1]> : vector<3×i32>} : (!\"pdl.operation\", !\"pdl.value\") -> ()\n }) {operand_segment_sizes = dense<[1, 0]> : vector<2×i32>} : (!\"pdl.operation\") -> ()\n }) {benefit = 1 : i16} : () -> ()\n]\n\n-- %res:!T = \"foo.op1\"(%x:!T)\nprivate def foo_op1_pattern: MTerm builtin :=\n .App .OP [\n .ConstString \"foo.op1\",\n .App (.LIST .MOperand) [\n .App .OPERAND [.Var 1 \"x\" .MSSAVal, .Var 1 \"T\" .MMLIRType]],\n .App (.LIST .MOperand) [\n .App .OPERAND [.Var 1 \"ret\" .MSSAVal, .Var 1 \"T\" .MMLIRType]]\n ]\n#eval foo_op1_pattern\n\n-- %res:!T = \"foo.op2\"(%x:!T, %y:i32)\nprivate def foo_op2_pattern: MTerm builtin :=\n .App .OP [\n .ConstString \"foo.op2\",\n .App (.LIST .MOperand) [\n .App .OPERAND [.Var 1 \"x\" .MSSAVal, .Var 1 \"T\" .MMLIRType],\n .App .OPERAND [.Var 1 \"y\" .MSSAVal, .ConstMLIRType .i32]],\n .App (.LIST .MOperand) [\n .App .OPERAND [.Var 1 \"ret\" .MSSAVal, .Var 1 \"T\" .MMLIRType]]\n ]\n#eval foo_op2_pattern\n\nprivate def foo_dialect := [foo_op1_pattern, foo_op2_pattern]\n\n#eval show IO Unit from do\n TranslationM.toIO Translation.empty do\n PDLToMatch.convert ex_pdl foo_dialect\n IO.println $ \"\\n## Translation result ##\\n\\n\" ++ (← get).str\n PDLToMatch.unify\n let matchTerms ← PDLToMatch.getOperationMatchTerms\n IO.println \"\\n## Final operation match terms ##\\n\"\n IO.println $ \"\\n\".intercalate (matchTerms.map toString)\n", "meta": {"author": "opencompl", "repo": "lean-mlir", "sha": "85fd61e38dec57e4d67d7af4d49a1ccc67828c1b", "save_path": "github-repos/lean/opencompl-lean-mlir", "path": "github-repos/lean/opencompl-lean-mlir/lean-mlir-85fd61e38dec57e4d67d7af4d49a1ccc67828c1b/MLIR/Dialects/PDLSemantics.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43782351378493656, "lm_q2_score": 0.04813677094594342, "lm_q1q2_score": 0.021075410197813595}} {"text": "def HList (αs : List (Type u)) : Type u := αs.foldr Prod.{u, u} PUnit\n\n@[match_pattern] def HList.nil : HList [] := ⟨⟩\n@[match_pattern] def HList.cons (a : α) (as : HList αs): HList (α :: αs) := (a, as)\n\ndef HList.set : {αs : _} → HList αs → (i : Fin αs.length) → αs.get i → HList αs\n | _ :: _, cons a as, ⟨0, h⟩, b => cons b as\n | _ :: _, cons a as, ⟨Nat.succ n, h⟩, b => cons a (set as ⟨n, Nat.le_of_succ_le_succ h⟩ b)\n | [], nil, _, _ => nil\n\ninstance : EmptyCollection (HList ∅) where\n emptyCollection := HList.nil\n\nnotation:30 Γ \" ⊢ \" α => HList Γ → α\n\n-- simplify well-founded recursion proofs by ignoring context sizes\nlocal instance : SizeOf (List α) := ⟨fun _ => 0⟩ in\n\n-- m: base monad\n-- ω: `return` type, `m ω` is the type of the entire `do` block\n-- Γ: `do`-local immutable context\n-- Δ: `do`-local mutable context\n-- b: `break` allowed\n-- c: `continue` allowed\n-- α: local result type, `m α` is the type of the statement\ninductive Stmt (m : Type u → Type _) (ω : Type u) : (Γ Δ : List (Type u)) → (b c : Bool) → (α : Type u) → Type _ where\n | expr (e : Γ ⊢ Δ ⊢ m α) : Stmt m ω Γ Δ b c α\n | bind (s₁ : Stmt m ω Γ Δ b c α) (s₂ : Stmt m ω (α :: Γ) Δ b c β) : Stmt m ω Γ Δ b c β\n | letmut (e : Γ ⊢ Δ ⊢ α) (s : Stmt m ω Γ (α :: Δ) b c β) : Stmt m ω Γ Δ b c β\n | ass (x : Fin Δ.length) (e : Γ ⊢ Δ ⊢ Δ.get x) : Stmt m ω Γ Δ b c PUnit\n | ite (e : Γ ⊢ Δ ⊢ Bool) (s₁ s₂ : Stmt m ω Γ Δ b c α) : Stmt m ω Γ Δ b c α\n | ret (e : Γ ⊢ Δ ⊢ ω) : Stmt m ω Γ Δ b c α\n --| sfor [ForM m γ α] (e : Σ Γ → γ) (body : α → Stmt m ω Γ Δ true PUnit) : Stmt m ω Γ Δ b c PUnit\n | sfor (e : Γ ⊢ Δ ⊢ List α) (body : Stmt m ω (α :: Γ) Δ true true PUnit) : Stmt m ω Γ Δ b c PUnit\n | sbreak : Stmt m ω Γ Δ true c α\n | scont : Stmt m ω Γ Δ b true α\n\n-- normal and abnormal result values\ninductive Res (ω α : Type _) : (b c : Bool) → Type _ where\n | val (a : α) : Res ω α b c\n | ret (o : ω) : Res ω α b c\n | rbreak : Res ω α true c\n | rcont : Res ω α b true\n\ninstance : Coe α (Res ω α b c) := ⟨Res.val⟩\ninstance : Coe (Id α) (Res ω α b c) := ⟨Res.val⟩\n\ndef Ctx.extendBot (x : α) : {Γ : _} → HList Γ → HList (Γ ++ [α])\n | [], _ => HList.cons x HList.nil\n | _ :: _, HList.cons a as => HList.cons a (extendBot x as)\n\ndef Ctx.extend (x : α) : HList Γ → HList (α :: Γ) :=\n fun σ => HList.cons x σ\n\ndef Ctx.drop : HList (α :: Γ) → HList Γ\n | HList.cons a as => as\n\n-- custom wf tactic\ntheorem Nat.le_add_right_of_le (n m : Nat) : n ≤ m → n ≤ m + k :=\n fun h => add_le_add h (Nat.zero_le _)\n\nmacro_rules\n| `(tactic| decreasing_tactic) =>\n `(tactic|\n (simp_wf\n repeat (first | apply PSigma.Lex.right | apply PSigma.Lex.left)\n simp [Nat.add_comm (n := 1), Nat.succ_add, Nat.mul_succ]\n try apply Nat.lt_succ_of_le\n repeat apply Nat.le_step\n first\n | repeat first | apply Nat.le_add_left | apply Nat.le_add_right_of_le\n | assumption\n all_goals apply Nat.le_refl\n))\n\n@[simp]\ndef Stmt.mapCtx (f : HList Γ' → HList Γ) : Stmt m ω Γ Δ b c β → Stmt m ω Γ' Δ b c β\n | expr e => expr (e ∘ f)\n | bind s₁ s₂ => bind (s₁.mapCtx f) (s₂.mapCtx (fun | HList.cons a as => HList.cons a (f as)))\n | letmut e s => letmut (e ∘ f) (s.mapCtx f)\n | ass x e => ass x (e ∘ f)\n | ite e s₁ s₂ => ite (e ∘ f) (s₁.mapCtx f) (s₂.mapCtx f)\n | ret e => ret (e ∘ f)\n | sfor e body => sfor (e ∘ f) (body.mapCtx (fun | HList.cons a as => HList.cons a (f as)))\n | sbreak => sbreak\n | scont => scont\ntermination_by mapCtx _ s => sizeOf s\n", "meta": {"author": "leanprover", "repo": "lean4", "sha": "742d053a97bdd109a41a921facd1cd6a55e89bc7", "save_path": "github-repos/lean/leanprover-lean4", "path": "github-repos/lean/leanprover-lean4/lean4-742d053a97bdd109a41a921facd1cd6a55e89bc7/tests/lean/run/wfEqnsIssue.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.04208772461143651, "lm_q1q2_score": 0.021043862305718256}} {"text": "/-\nCopyright (c) 2020 Scott Morrison. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Scott Morrison, Bhavik Mehta\n-/\nimport category_theory.limits.shapes.pullbacks\nimport category_theory.limits.shapes.strong_epi\nimport category_theory.limits.shapes.equalizers\n\n/-!\n# Definitions and basic properties of regular monomorphisms and epimorphisms.\n\nA regular monomorphism is a morphism that is the equalizer of some parallel pair.\n\nWe give the constructions\n* `split_mono → regular_mono` and\n* `regular_mono → mono`\nas well as the dual constructions for regular epimorphisms. Additionally, we give the construction\n* `regular_epi ⟶ strong_epi`.\n\nWe also define classes `regular_mono_category` and `regular_epi_category` for categories in which\nevery monomorphism or epimorphism is regular, and deduce that these categories are\n`strong_mono_category`s resp. `strong_epi_category`s.\n\n-/\n\nnoncomputable theory\n\nnamespace category_theory\nopen category_theory.limits\n\nuniverses v₁ u₁ u₂\n\nvariables {C : Type u₁} [category.{v₁} C]\n\nvariables {X Y : C}\n\n/-- A regular monomorphism is a morphism which is the equalizer of some parallel pair. -/\nclass regular_mono (f : X ⟶ Y) :=\n(Z : C)\n(left right : Y ⟶ Z)\n(w : f ≫ left = f ≫ right)\n(is_limit : is_limit (fork.of_ι f w))\n\nattribute [reassoc] regular_mono.w\n\n/-- Every regular monomorphism is a monomorphism. -/\n@[priority 100]\ninstance regular_mono.mono (f : X ⟶ Y) [regular_mono f] : mono f :=\nmono_of_is_limit_parallel_pair regular_mono.is_limit\n\ninstance equalizer_regular (g h : X ⟶ Y) [has_limit (parallel_pair g h)] :\n regular_mono (equalizer.ι g h) :=\n{ Z := Y,\n left := g,\n right := h,\n w := equalizer.condition g h,\n is_limit := fork.is_limit.mk _ (λ s, limit.lift _ s) (by simp) (λ s m w, by { ext1, simp [←w] }) }\n\n/-- Every split monomorphism is a regular monomorphism. -/\n@[priority 100]\ninstance regular_mono.of_split_mono (f : X ⟶ Y) [split_mono f] : regular_mono f :=\n{ Z := Y,\n left := 𝟙 Y,\n right := retraction f ≫ f,\n w := by tidy,\n is_limit := split_mono_equalizes f }\n\n/-- If `f` is a regular mono, then any map `k : W ⟶ Y` equalizing `regular_mono.left` and\n `regular_mono.right` induces a morphism `l : W ⟶ X` such that `l ≫ f = k`. -/\ndef regular_mono.lift' {W : C} (f : X ⟶ Y) [regular_mono f] (k : W ⟶ Y)\n (h : k ≫ (regular_mono.left : Y ⟶ @regular_mono.Z _ _ _ _ f _) = k ≫ regular_mono.right) :\n {l : W ⟶ X // l ≫ f = k} :=\nfork.is_limit.lift' regular_mono.is_limit _ h\n\n/--\nThe second leg of a pullback cone is a regular monomorphism if the right component is too.\n\nSee also `pullback.snd_of_mono` for the basic monomorphism version, and\n`regular_of_is_pullback_fst_of_regular` for the flipped version.\n-/\ndef regular_of_is_pullback_snd_of_regular {P Q R S : C} {f : P ⟶ Q} {g : P ⟶ R} {h : Q ⟶ S}\n {k : R ⟶ S} [hr : regular_mono h] (comm : f ≫ h = g ≫ k)\n (t : is_limit (pullback_cone.mk _ _ comm)) :\nregular_mono g :=\n{ Z := hr.Z,\n left := k ≫ hr.left,\n right := k ≫ hr.right,\n w := by rw [← reassoc_of comm, ← reassoc_of comm, hr.w],\n is_limit :=\n begin\n apply fork.is_limit.mk' _ _,\n intro s,\n have l₁ : (fork.ι s ≫ k) ≫ regular_mono.left = (fork.ι s ≫ k) ≫ regular_mono.right,\n rw [category.assoc, s.condition, category.assoc],\n obtain ⟨l, hl⟩ := fork.is_limit.lift' hr.is_limit _ l₁,\n obtain ⟨p, hp₁, hp₂⟩ := pullback_cone.is_limit.lift' t _ _ hl,\n refine ⟨p, hp₂, _⟩,\n intros m w,\n have z : m ≫ g = p ≫ g := w.trans hp₂.symm,\n apply t.hom_ext,\n apply (pullback_cone.mk f g comm).equalizer_ext,\n { erw [← cancel_mono h, category.assoc, category.assoc, comm, reassoc_of z] },\n { exact z },\n end }\n\n/--\nThe first leg of a pullback cone is a regular monomorphism if the left component is too.\n\nSee also `pullback.fst_of_mono` for the basic monomorphism version, and\n`regular_of_is_pullback_snd_of_regular` for the flipped version.\n-/\ndef regular_of_is_pullback_fst_of_regular {P Q R S : C} {f : P ⟶ Q} {g : P ⟶ R} {h : Q ⟶ S}\n {k : R ⟶ S} [hr : regular_mono k] (comm : f ≫ h = g ≫ k)\n (t : is_limit (pullback_cone.mk _ _ comm)) :\nregular_mono f :=\nregular_of_is_pullback_snd_of_regular comm.symm (pullback_cone.flip_is_limit t)\n\n@[priority 100]\ninstance strong_mono_of_regular_mono (f : X ⟶ Y) [regular_mono f] : strong_mono f :=\n{ mono := by apply_instance,\n has_lift :=\n begin\n introsI,\n have : v ≫ (regular_mono.left : Y ⟶ regular_mono.Z f) = v ≫ regular_mono.right,\n { apply (cancel_epi z).1,\n simp only [regular_mono.w, ← reassoc_of h] },\n obtain ⟨t, ht⟩ := regular_mono.lift' _ _ this,\n refine arrow.has_lift.mk ⟨t, (cancel_mono f).1 _, ht⟩,\n simp only [arrow.mk_hom, arrow.hom_mk'_left, category.assoc, ht, h]\n end }\n\n/-- A regular monomorphism is an isomorphism if it is an epimorphism. -/\nlemma is_iso_of_regular_mono_of_epi (f : X ⟶ Y) [regular_mono f] [e : epi f] : is_iso f :=\nis_iso_of_epi_of_strong_mono _\n\nsection\nvariables (C)\n\n/-- A regular mono category is a category in which every monomorphism is regular. -/\nclass regular_mono_category :=\n(regular_mono_of_mono : ∀ {X Y : C} (f : X ⟶ Y) [mono f], regular_mono f)\n\nend\n\n/-- In a category in which every monomorphism is regular, we can express every monomorphism as\n an equalizer. This is not an instance because it would create an instance loop. -/\ndef regular_mono_of_mono [regular_mono_category C] (f : X ⟶ Y) [mono f] : regular_mono f :=\nregular_mono_category.regular_mono_of_mono _\n\n@[priority 100]\ninstance regular_mono_category_of_split_mono_category [split_mono_category C] :\n regular_mono_category C :=\n{ regular_mono_of_mono := λ _ _ f _,\n by { haveI := by exactI split_mono_of_mono f, apply_instance } }\n\n@[priority 100]\ninstance strong_mono_category_of_regular_mono_category [regular_mono_category C] :\n strong_mono_category C :=\n{ strong_mono_of_mono := λ _ _ f _,\n by { haveI := by exactI regular_mono_of_mono f, apply_instance } }\n\n/-- A regular epimorphism is a morphism which is the coequalizer of some parallel pair. -/\nclass regular_epi (f : X ⟶ Y) :=\n(W : C)\n(left right : W ⟶ X)\n(w : left ≫ f = right ≫ f)\n(is_colimit : is_colimit (cofork.of_π f w))\n\nattribute [reassoc] regular_epi.w\n\n/-- Every regular epimorphism is an epimorphism. -/\n@[priority 100]\ninstance regular_epi.epi (f : X ⟶ Y) [regular_epi f] : epi f :=\nepi_of_is_colimit_parallel_pair regular_epi.is_colimit\n\ninstance coequalizer_regular (g h : X ⟶ Y) [has_colimit (parallel_pair g h)] :\n regular_epi (coequalizer.π g h) :=\n{ W := X,\n left := g,\n right := h,\n w := coequalizer.condition g h,\n is_colimit := cofork.is_colimit.mk _ (λ s, colimit.desc _ s) (by simp)\n (λ s m w, by { ext1, simp [←w] }) }\n\n/-- Every split epimorphism is a regular epimorphism. -/\n@[priority 100]\ninstance regular_epi.of_split_epi (f : X ⟶ Y) [split_epi f] : regular_epi f :=\n{ W := X,\n left := 𝟙 X,\n right := f ≫ section_ f,\n w := by tidy,\n is_colimit := split_epi_coequalizes f }\n\n/-- If `f` is a regular epi, then every morphism `k : X ⟶ W` coequalizing `regular_epi.left` and\n `regular_epi.right` induces `l : Y ⟶ W` such that `f ≫ l = k`. -/\ndef regular_epi.desc' {W : C} (f : X ⟶ Y) [regular_epi f] (k : X ⟶ W)\n (h : (regular_epi.left : regular_epi.W f ⟶ X) ≫ k = regular_epi.right ≫ k) :\n {l : Y ⟶ W // f ≫ l = k} :=\ncofork.is_colimit.desc' (regular_epi.is_colimit) _ h\n\n/--\nThe second leg of a pushout cocone is a regular epimorphism if the right component is too.\n\nSee also `pushout.snd_of_epi` for the basic epimorphism version, and\n`regular_of_is_pushout_fst_of_regular` for the flipped version.\n-/\ndef regular_of_is_pushout_snd_of_regular\n {P Q R S : C} {f : P ⟶ Q} {g : P ⟶ R} {h : Q ⟶ S} {k : R ⟶ S}\n [gr : regular_epi g] (comm : f ≫ h = g ≫ k) (t : is_colimit (pushout_cocone.mk _ _ comm)) :\nregular_epi h :=\n{ W := gr.W,\n left := gr.left ≫ f,\n right := gr.right ≫ f,\n w := by rw [category.assoc, category.assoc, comm, reassoc_of gr.w],\n is_colimit :=\n begin\n apply cofork.is_colimit.mk' _ _,\n intro s,\n have l₁ : gr.left ≫ f ≫ s.π = gr.right ≫ f ≫ s.π,\n rw [← category.assoc, ← category.assoc, s.condition],\n obtain ⟨l, hl⟩ := cofork.is_colimit.desc' gr.is_colimit (f ≫ cofork.π s) l₁,\n obtain ⟨p, hp₁, hp₂⟩ := pushout_cocone.is_colimit.desc' t _ _ hl.symm,\n refine ⟨p, hp₁, _⟩,\n intros m w,\n have z := w.trans hp₁.symm,\n apply t.hom_ext,\n apply (pushout_cocone.mk _ _ comm).coequalizer_ext,\n { exact z },\n { erw [← cancel_epi g, ← reassoc_of comm, ← reassoc_of comm, z], refl },\n end }\n\n/--\nThe first leg of a pushout cocone is a regular epimorphism if the left component is too.\n\nSee also `pushout.fst_of_epi` for the basic epimorphism version, and\n`regular_of_is_pushout_snd_of_regular` for the flipped version.\n-/\ndef regular_of_is_pushout_fst_of_regular\n {P Q R S : C} {f : P ⟶ Q} {g : P ⟶ R} {h : Q ⟶ S} {k : R ⟶ S}\n [fr : regular_epi f] (comm : f ≫ h = g ≫ k) (t : is_colimit (pushout_cocone.mk _ _ comm)) :\nregular_epi k :=\nregular_of_is_pushout_snd_of_regular comm.symm (pushout_cocone.flip_is_colimit t)\n\n@[priority 100]\ninstance strong_epi_of_regular_epi (f : X ⟶ Y) [regular_epi f] : strong_epi f :=\n{ epi := by apply_instance,\n has_lift :=\n begin\n introsI,\n have : (regular_epi.left : regular_epi.W f ⟶ X) ≫ u = regular_epi.right ≫ u,\n { apply (cancel_mono z).1,\n simp only [category.assoc, h, regular_epi.w_assoc] },\n obtain ⟨t, ht⟩ := regular_epi.desc' f u this,\n exact arrow.has_lift.mk ⟨t, ht, (cancel_epi f).1\n (by simp only [←category.assoc, ht, ←h, arrow.mk_hom, arrow.hom_mk'_right])⟩,\n end }\n\n/-- A regular epimorphism is an isomorphism if it is a monomorphism. -/\nlemma is_iso_of_regular_epi_of_mono (f : X ⟶ Y) [regular_epi f] [m : mono f] : is_iso f :=\nis_iso_of_mono_of_strong_epi _\n\nsection\nvariables (C)\n\n/-- A regular epi category is a category in which every epimorphism is regular. -/\nclass regular_epi_category :=\n(regular_epi_of_epi : ∀ {X Y : C} (f : X ⟶ Y) [epi f], regular_epi f)\n\nend\n\n/-- In a category in which every epimorphism is regular, we can express every epimorphism as\n a coequalizer. This is not an instance because it would create an instance loop. -/\ndef regular_epi_of_epi [regular_epi_category C] (f : X ⟶ Y) [epi f] : regular_epi f :=\nregular_epi_category.regular_epi_of_epi _\n\n@[priority 100]\ninstance regular_epi_category_of_split_epi_category [split_epi_category C] :\n regular_epi_category C :=\n{ regular_epi_of_epi := λ _ _ f _, by { haveI := by exactI split_epi_of_epi f, apply_instance } }\n\n@[priority 100]\ninstance strong_epi_category_of_regular_epi_category [regular_epi_category C] :\n strong_epi_category C :=\n{ strong_epi_of_epi := λ _ _ f _, by { haveI := by exactI regular_epi_of_epi f, apply_instance } }\n\nend category_theory\n", "meta": {"author": "saisurbehera", "repo": "mathProof", "sha": "57c6bfe75652e9d3312d8904441a32aff7d6a75e", "save_path": "github-repos/lean/saisurbehera-mathProof", "path": "github-repos/lean/saisurbehera-mathProof/mathProof-57c6bfe75652e9d3312d8904441a32aff7d6a75e/src/tertiary_packages/mathlib/src/category_theory/limits/shapes/regular_mono.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4571367168274948, "lm_q2_score": 0.04603390648912336, "lm_q1q2_score": 0.02104378887518176}} {"text": "import Lean\nopen List Lean\n\nexample (l : List α) (h : length l = length l) : length (a::l) = length (a::l) :=\n congrArg (·+1) h\n\nelab:max \"(\" tm:term \":)\" : term => Elab.Term.elabTerm tm none\n\nexample (l : List α) (h : length l = length l) : length (a::l) = length (a::l) :=\n (congrArg (·+1) h :)\n\nexample (l : List α) (h : length l = length l) : length (a::l) = length (a::l) :=\n have := congrArg (·+1) h; this\n\nexample (l : List α) (h : length l = length l) : length (a::l) = length (a::l) := by\n have := congrArg (·+1) h; exact this\n", "meta": {"author": "leanprover", "repo": "lean4", "sha": "742d053a97bdd109a41a921facd1cd6a55e89bc7", "save_path": "github-repos/lean/leanprover-lean4", "path": "github-repos/lean/leanprover-lean4/lean4-742d053a97bdd109a41a921facd1cd6a55e89bc7/tests/lean/run/1436.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.43398146480389854, "lm_q2_score": 0.04813676702004151, "lm_q1q2_score": 0.02089046466228161}} {"text": "/-\nCopyright (c) 2016 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Leonardo de Moura\n\n! This file was ported from Lean 3 source module init.meta.smt.smt_tactic\n! leanprover-community/mathlib commit 4a03bdeb31b3688c31d02d7ff8e0ff2e5d6174db\n! Please do not edit these lines, except to modify the commit id\n! if you have ported upstream changes.\n-/\nprelude\nimport Leanbin.Init.Control.Default\nimport Leanbin.Init.Meta.SimpTactic\nimport Leanbin.Init.Meta.Smt.CongruenceClosure\nimport Leanbin.Init.Meta.Smt.Ematch\n\nuniverse u\n\nrun_cmd\n mk_simp_attr `pre_smt\n\nrun_cmd\n mk_hinst_lemma_attr_set `ematch [] [`ematch_lhs]\n\n/-- Configuration for the smt tactic preprocessor. The preprocessor\n is applied whenever a new hypothesis is introduced.\n\n - simp_attr: is the attribute name for the simplification lemmas\n that are used during the preprocessing step.\n\n - max_steps: it is the maximum number of steps performed by the simplifier.\n\n - zeta: if tt, then zeta reduction (i.e., unfolding let-expressions)\n is used during preprocessing.\n-/\nstructure SmtPreConfig where\n simpAttr : Name := `pre_smt\n maxSteps : Nat := 1000000\n zeta : Bool := false\n#align smt_pre_config SmtPreConfig\n\n/-- Configuration for the smt_state object.\n\n- em_attr: is the attribute name for the hinst_lemmas\n that are used for ematching -/\nstructure SmtConfig where\n ccCfg : CcConfig := { }\n emCfg : EmatchConfig := { }\n preCfg : SmtPreConfig := { }\n emAttr : Name := `ematch\n#align smt_config SmtConfig\n\nunsafe def smt_config.set_classical (c : SmtConfig) (b : Bool) : SmtConfig :=\n { c with ccCfg := { c.ccCfg with em := b } }\n#align smt_config.set_classical smt_config.set_classical\n\nunsafe axiom smt_goal : Type\n#align smt_goal smt_goal\n\nunsafe def smt_state :=\n List smt_goal\n#align smt_state smt_state\n\nunsafe axiom smt_state.mk : SmtConfig → tactic smt_state\n#align smt_state.mk smt_state.mk\n\nunsafe axiom smt_state.to_format : smt_state → tactic_state → format\n#align smt_state.to_format smt_state.to_format\n\n/-- Return tt iff classical excluded middle was enabled at smt_state.mk -/\nunsafe axiom smt_state.classical : smt_state → Bool\n#align smt_state.classical smt_state.classical\n\nunsafe def smt_tactic :=\n StateT smt_state tactic\n#align smt_tactic smt_tactic\n\nunsafe instance : Append smt_state :=\n List.hasAppend\n\nsection\n\nattribute [local reducible] smt_tactic\n\nunsafe instance : Monad smt_tactic := by infer_instance\n\nunsafe instance : Alternative smt_tactic := by infer_instance\n\nunsafe instance : MonadState smt_state smt_tactic := by infer_instance\n\nend\n\n/- We don't use the default state_t lift operation because only\n tactics that do not change hypotheses can be automatically lifted to smt_tactic. -/\nunsafe axiom tactic_to_smt_tactic (α : Type) : tactic α → smt_tactic α\n#align tactic_to_smt_tactic tactic_to_smt_tactic\n\nunsafe instance : HasMonadLift tactic smt_tactic :=\n ⟨tactic_to_smt_tactic⟩\n\nunsafe instance (α : Type) : Coe (tactic α) (smt_tactic α) :=\n ⟨monadLift⟩\n\nunsafe instance : MonadFail smt_tactic :=\n { smt_tactic.monad with fail := fun α s => (tactic.fail (to_fmt s) : smt_tactic α) }\n\nnamespace SmtTactic\n\nopen Tactic (Transparency)\n\nunsafe axiom intros : smt_tactic Unit\n#align smt_tactic.intros smt_tactic.intros\n\nunsafe axiom intron : Nat → smt_tactic Unit\n#align smt_tactic.intron smt_tactic.intron\n\nunsafe axiom intro_lst : List Name → smt_tactic Unit\n#align smt_tactic.intro_lst smt_tactic.intro_lst\n\n/-- Try to close main goal by using equalities implied by the congruence\n closure module.\n-/\nunsafe axiom close : smt_tactic Unit\n#align smt_tactic.close smt_tactic.close\n\n/-- Produce new facts using heuristic lemma instantiation based on E-matching.\n This tactic tries to match patterns from lemmas in the main goal with terms\n in the main goal. The set of lemmas is populated with theorems\n tagged with the attribute specified at smt_config.em_attr, and lemmas\n added using tactics such as `smt_tactic.add_lemmas`.\n The current set of lemmas can be retrieved using the tactic `smt_tactic.get_lemmas`.\n\n Remark: the given predicate is applied to every new instance. The instance\n is only added to the state if the predicate returns tt.\n-/\nunsafe axiom ematch_core : (expr → Bool) → smt_tactic Unit\n#align smt_tactic.ematch_core smt_tactic.ematch_core\n\n/-- Produce new facts using heuristic lemma instantiation based on E-matching.\n This tactic tries to match patterns from the given lemmas with terms in\n the main goal.\n-/\nunsafe axiom ematch_using : hinst_lemmas → smt_tactic Unit\n#align smt_tactic.ematch_using smt_tactic.ematch_using\n\nunsafe axiom mk_ematch_eqn_lemmas_for_core : Transparency → Name → smt_tactic hinst_lemmas\n#align smt_tactic.mk_ematch_eqn_lemmas_for_core smt_tactic.mk_ematch_eqn_lemmas_for_core\n\nunsafe axiom to_cc_state : smt_tactic cc_state\n#align smt_tactic.to_cc_state smt_tactic.to_cc_state\n\nunsafe axiom to_em_state : smt_tactic ematch_state\n#align smt_tactic.to_em_state smt_tactic.to_em_state\n\nunsafe axiom get_config : smt_tactic SmtConfig\n#align smt_tactic.get_config smt_tactic.get_config\n\n/-- Preprocess the given term using the same simplifications rules used when\n we introduce a new hypothesis. The result is pair containing the resulting\n term and a proof that it is equal to the given one.\n-/\nunsafe axiom preprocess : expr → smt_tactic (expr × expr)\n#align smt_tactic.preprocess smt_tactic.preprocess\n\nunsafe axiom get_lemmas : smt_tactic hinst_lemmas\n#align smt_tactic.get_lemmas smt_tactic.get_lemmas\n\nunsafe axiom set_lemmas : hinst_lemmas → smt_tactic Unit\n#align smt_tactic.set_lemmas smt_tactic.set_lemmas\n\nunsafe axiom add_lemmas : hinst_lemmas → smt_tactic Unit\n#align smt_tactic.add_lemmas smt_tactic.add_lemmas\n\nunsafe def add_ematch_lemma_core (md : Transparency) (as_simp : Bool) (e : expr) :\n smt_tactic Unit := do\n let h ← hinst_lemma.mk_core md e as_simp\n add_lemmas (mk_hinst_singleton h)\n#align smt_tactic.add_ematch_lemma_core smt_tactic.add_ematch_lemma_core\n\nunsafe def add_ematch_lemma_from_decl_core (md : Transparency) (as_simp : Bool) (n : Name) :\n smt_tactic Unit := do\n let h ← hinst_lemma.mk_from_decl_core md n as_simp\n add_lemmas (mk_hinst_singleton h)\n#align smt_tactic.add_ematch_lemma_from_decl_core smt_tactic.add_ematch_lemma_from_decl_core\n\nunsafe def add_ematch_eqn_lemmas_for_core (md : Transparency) (n : Name) : smt_tactic Unit := do\n let hs ← mk_ematch_eqn_lemmas_for_core md n\n add_lemmas hs\n#align smt_tactic.add_ematch_eqn_lemmas_for_core smt_tactic.add_ematch_eqn_lemmas_for_core\n\nunsafe def ematch : smt_tactic Unit :=\n ematch_core fun _ => true\n#align smt_tactic.ematch smt_tactic.ematch\n\nunsafe def failed {α} : smt_tactic α :=\n tactic.failed\n#align smt_tactic.failed smt_tactic.failed\n\nunsafe def fail {α : Type} {β : Type u} [has_to_format β] (msg : β) : smt_tactic α :=\n tactic.fail msg\n#align smt_tactic.fail smt_tactic.fail\n\nunsafe def try {α : Type} (t : smt_tactic α) : smt_tactic Unit :=\n ⟨fun ss ts =>\n result.cases_on (t.run ss ts) (fun ⟨a, new_ss⟩ => result.success ((), new_ss)) fun e ref s' =>\n result.success ((), ss) ts⟩\n#align smt_tactic.try smt_tactic.try\n\n/-- `iterate_at_most n t`: repeat the given tactic at most n times or until t fails -/\nunsafe def iterate_at_most : Nat → smt_tactic Unit → smt_tactic Unit\n | 0, t => return ()\n | n + 1, t =>\n (do\n t\n iterate_at_most n t) <|>\n return ()\n#align smt_tactic.iterate_at_most smt_tactic.iterate_at_most\n\n/-- `iterate_exactly n t` : execute t n times -/\nunsafe def iterate_exactly : Nat → smt_tactic Unit → smt_tactic Unit\n | 0, t => return ()\n | n + 1, t => do\n t\n iterate_exactly n t\n#align smt_tactic.iterate_exactly smt_tactic.iterate_exactly\n\nunsafe def iterate : smt_tactic Unit → smt_tactic Unit :=\n iterate_at_most 100000\n#align smt_tactic.iterate smt_tactic.iterate\n\nunsafe def eblast : smt_tactic Unit :=\n iterate (ematch >> try close)\n#align smt_tactic.eblast smt_tactic.eblast\n\nopen Tactic\n\nprotected unsafe def read : smt_tactic (smt_state × tactic_state) := do\n let s₁ ← get\n let s₂ ← tactic.read\n return (s₁, s₂)\n#align smt_tactic.read smt_tactic.read\n\nprotected unsafe def write : smt_state × tactic_state → smt_tactic Unit := fun ⟨ss, ts⟩ =>\n ⟨fun _ _ => result.success ((), ss) ts⟩\n#align smt_tactic.write smt_tactic.write\n\nprivate unsafe def mk_smt_goals_for (cfg : SmtConfig) :\n List expr → List smt_goal → List expr → tactic (List smt_goal × List expr)\n | [], sr, tr => return (sr.reverse, tr.reverse)\n | tg :: tgs, sr, tr => do\n tactic.set_goals [tg]\n let [new_sg] ← smt_state.mk cfg |\n tactic.failed\n let [new_tg] ← get_goals |\n tactic.failed\n mk_smt_goals_for tgs (new_sg :: sr) (new_tg :: tr)\n#align smt_tactic.mk_smt_goals_for smt_tactic.mk_smt_goals_for\n\n/-- See slift -/\nunsafe def slift_aux {α : Type} (t : tactic α) (cfg : SmtConfig) : smt_tactic α :=\n ⟨fun ss => do\n let _ :: sgs ← return ss |\n tactic.fail \"slift tactic failed, there no smt goals to be solved\"\n let tg :: tgs ← tactic.get_goals |\n tactic.failed\n tactic.set_goals [tg]\n let a ← t\n let new_tgs ← tactic.get_goals\n let (new_sgs, new_tgs) ← mk_smt_goals_for cfg new_tgs [] []\n tactic.set_goals (new_tgs ++ tgs)\n return (a, new_sgs ++ sgs)⟩\n#align smt_tactic.slift_aux smt_tactic.slift_aux\n\n/-- This lift operation will restart the SMT state.\n It is useful for using tactics that change the set of hypotheses. -/\nunsafe def slift {α : Type} (t : tactic α) : smt_tactic α :=\n get_config >>= slift_aux t\n#align smt_tactic.slift smt_tactic.slift\n\nunsafe def trace_state : smt_tactic Unit := do\n let (s₁, s₂) ← smt_tactic.read\n trace (smt_state.to_format s₁ s₂)\n#align smt_tactic.trace_state smt_tactic.trace_state\n\nunsafe def trace {α : Type} [has_to_tactic_format α] (a : α) : smt_tactic Unit :=\n tactic.trace a\n#align smt_tactic.trace smt_tactic.trace\n\nunsafe def to_expr (q : pexpr) (allow_mvars := true) : smt_tactic expr :=\n tactic.to_expr q allow_mvars\n#align smt_tactic.to_expr smt_tactic.to_expr\n\nunsafe def classical : smt_tactic Bool := do\n let s ← get\n return s\n#align smt_tactic.classical smt_tactic.classical\n\nunsafe def num_goals : smt_tactic Nat :=\n List.length <$> get\n#align smt_tactic.num_goals smt_tactic.num_goals\n\n-- Low level primitives for managing set of goals\nunsafe def get_goals : smt_tactic (List smt_goal × List expr) := do\n let (g₁, _) ← smt_tactic.read\n let g₂ ← tactic.get_goals\n return (g₁, g₂)\n#align smt_tactic.get_goals smt_tactic.get_goals\n\nunsafe def set_goals : List smt_goal → List expr → smt_tactic Unit := fun g₁ g₂ =>\n ⟨fun ss => tactic.set_goals g₂ >> return ((), g₁)⟩\n#align smt_tactic.set_goals smt_tactic.set_goals\n\nprivate unsafe def all_goals_core (tac : smt_tactic Unit) :\n List smt_goal → List expr → List smt_goal → List expr → smt_tactic Unit\n | [], ts, acs, act => set_goals acs (ts ++ act)\n | s :: ss, [], acs, act => fail \"ill-formed smt_state\"\n | s :: ss, t :: ts, acs, act => do\n set_goals [s] [t]\n tac\n let (new_ss, new_ts) ← get_goals\n all_goals_core ss ts (acs ++ new_ss) (act ++ new_ts)\n#align smt_tactic.all_goals_core smt_tactic.all_goals_core\n\n/-- Apply the given tactic to all goals. -/\nunsafe def all_goals (tac : smt_tactic Unit) : smt_tactic Unit := do\n let (ss, ts) ← get_goals\n all_goals_core tac ss ts [] []\n#align smt_tactic.all_goals smt_tactic.all_goals\n\n/--\nLCF-style AND_THEN tactic. It applies tac1, and if succeed applies tac2 to each subgoal produced by tac1 -/\nunsafe def seq (tac1 : smt_tactic Unit) (tac2 : smt_tactic Unit) : smt_tactic Unit := do\n let (s :: ss, t :: ts) ← get_goals\n set_goals [s] [t]\n tac1\n all_goals tac2\n let (new_ss, new_ts) ← get_goals\n set_goals (new_ss ++ ss) (new_ts ++ ts)\n#align smt_tactic.seq smt_tactic.seq\n\nunsafe instance : AndThen' (smt_tactic Unit) (smt_tactic Unit) (smt_tactic Unit) :=\n ⟨seq⟩\n\nunsafe def focus1 {α} (tac : smt_tactic α) : smt_tactic α := do\n let (s :: ss, t :: ts) ← get_goals\n match ss with\n | [] => tac\n | _ => do\n set_goals [s] [t]\n let a ← tac\n let (ss', ts') ← get_goals\n set_goals (ss' ++ ss) (ts' ++ ts)\n return a\n#align smt_tactic.focus1 smt_tactic.focus1\n\nunsafe def solve1 (tac : smt_tactic Unit) : smt_tactic Unit := do\n let (ss, gs) ← get_goals\n match ss, gs with\n | [], _ => fail \"solve1 tactic failed, there isn't any goal left to focus\"\n | _, [] => fail \"solve1 tactic failed, there isn't any smt goal left to focus\"\n | s :: ss, g :: gs => do\n set_goals [s] [g]\n tac\n let (ss', gs') ← get_goals\n match ss', gs' with\n | [], [] => set_goals ss gs\n | _, _ => fail \"solve1 tactic failed, focused goal has not been solved\"\n#align smt_tactic.solve1 smt_tactic.solve1\n\nunsafe def swap : smt_tactic Unit := do\n let (ss, ts) ← get_goals\n match ss, ts with\n | s₁ :: s₂ :: ss, t₁ :: t₂ :: ts => set_goals (s₂ :: s₁ :: ss) (t₂ :: t₁ :: ts)\n | _, _ => failed\n#align smt_tactic.swap smt_tactic.swap\n\n/-- Add a new goal for t, and the hypothesis (h : t) in the current goal. -/\nunsafe def assert (h : Name) (t : expr) : smt_tactic Unit :=\n (((tactic.assert_core h t >> swap) >> intros) >> swap) >> try close\n#align smt_tactic.assert smt_tactic.assert\n\n/-- Add the hypothesis (h : t) in the current goal if v has type t. -/\nunsafe def assertv (h : Name) (t : expr) (v : expr) : smt_tactic Unit :=\n (tactic.assertv_core h t v >> intros) >> return ()\n#align smt_tactic.assertv smt_tactic.assertv\n\n/-- Add a new goal for t, and the hypothesis (h : t := ?M) in the current goal. -/\nunsafe def define (h : Name) (t : expr) : smt_tactic Unit :=\n (((tactic.define_core h t >> swap) >> intros) >> swap) >> try close\n#align smt_tactic.define smt_tactic.define\n\n/-- Add the hypothesis (h : t := v) in the current goal if v has type t. -/\nunsafe def definev (h : Name) (t : expr) (v : expr) : smt_tactic Unit :=\n (tactic.definev_core h t v >> intros) >> return ()\n#align smt_tactic.definev smt_tactic.definev\n\n/-- Add (h : t := pr) to the current goal -/\nunsafe def pose (h : Name) (t : Option expr := none) (pr : expr) : smt_tactic Unit :=\n match t with\n | none => do\n let t ← infer_type pr\n definev h t pr\n | some t => definev h t pr\n#align smt_tactic.pose smt_tactic.pose\n\n/-- Add (h : t) to the current goal, given a proof (pr : t) -/\nunsafe def note (h : Name) (t : Option expr := none) (pr : expr) : smt_tactic Unit :=\n match t with\n | none => do\n let t ← infer_type pr\n assertv h t pr\n | some t => assertv h t pr\n#align smt_tactic.note smt_tactic.note\n\nunsafe def destruct (e : expr) : smt_tactic Unit :=\n smt_tactic.seq (tactic.destruct e) smt_tactic.intros\n#align smt_tactic.destruct smt_tactic.destruct\n\nunsafe def by_cases (e : expr) : smt_tactic Unit := do\n let c ← classical\n if c then destruct (expr.app (expr.const `classical.em []) e)\n else do\n let dec_e ←\n mk_app `decidable [e] <|> fail \"by_cases smt_tactic failed, type is not a proposition\"\n let inst ←\n mk_instance dec_e <|>\n fail \"by_cases smt_tactic failed, type of given expression is not decidable\"\n let em ← mk_app `decidable.em [e, inst]\n destruct em\n#align smt_tactic.by_cases smt_tactic.by_cases\n\nunsafe def by_contradiction : smt_tactic Unit := do\n let t ← target\n let c ← classical\n if t then skip\n else\n if c then do\n apply (expr.app (expr.const `classical.by_contradiction []) t)\n intros\n else do\n let dec_t ←\n mk_app `decidable [t] <|>\n fail \"by_contradiction smt_tactic failed, target is not a proposition\"\n let inst ←\n mk_instance dec_t <|> fail \"by_contradiction smt_tactic failed, target is not decidable\"\n let a ← mk_mapp `decidable.by_contradiction [some t, some inst]\n apply a\n intros\n#align smt_tactic.by_contradiction smt_tactic.by_contradiction\n\n/-- Return a proof for e, if 'e' is a known fact in the main goal. -/\nunsafe def proof_for (e : expr) : smt_tactic expr := do\n let cc ← to_cc_state\n cc e\n#align smt_tactic.proof_for smt_tactic.proof_for\n\n/--\nReturn a refutation for e (i.e., a proof for (not e)), if 'e' has been refuted in the main goal. -/\nunsafe def refutation_for (e : expr) : smt_tactic expr := do\n let cc ← to_cc_state\n cc e\n#align smt_tactic.refutation_for smt_tactic.refutation_for\n\nunsafe def get_facts : smt_tactic (List expr) := do\n let cc ← to_cc_state\n return <| cc expr.mk_true\n#align smt_tactic.get_facts smt_tactic.get_facts\n\nunsafe def get_refuted_facts : smt_tactic (List expr) := do\n let cc ← to_cc_state\n return <| cc expr.mk_false\n#align smt_tactic.get_refuted_facts smt_tactic.get_refuted_facts\n\nunsafe def add_ematch_lemma : expr → smt_tactic Unit :=\n add_ematch_lemma_core reducible false\n#align smt_tactic.add_ematch_lemma smt_tactic.add_ematch_lemma\n\nunsafe def add_ematch_lhs_lemma : expr → smt_tactic Unit :=\n add_ematch_lemma_core reducible true\n#align smt_tactic.add_ematch_lhs_lemma smt_tactic.add_ematch_lhs_lemma\n\nunsafe def add_ematch_lemma_from_decl : Name → smt_tactic Unit :=\n add_ematch_lemma_from_decl_core reducible false\n#align smt_tactic.add_ematch_lemma_from_decl smt_tactic.add_ematch_lemma_from_decl\n\nunsafe def add_ematch_lhs_lemma_from_decl : Name → smt_tactic Unit :=\n add_ematch_lemma_from_decl_core reducible false\n#align smt_tactic.add_ematch_lhs_lemma_from_decl smt_tactic.add_ematch_lhs_lemma_from_decl\n\nunsafe def add_ematch_eqn_lemmas_for : Name → smt_tactic Unit :=\n add_ematch_eqn_lemmas_for_core reducible\n#align smt_tactic.add_ematch_eqn_lemmas_for smt_tactic.add_ematch_eqn_lemmas_for\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:207:4: warning: unsupported notation `f -/\nunsafe def add_lemmas_from_facts_core : List expr → smt_tactic Unit\n | [] => return ()\n | f :: fs => do\n try\n ((is_prop f >> guard (f && not (f f.is_arrow))) >> proof_for f >>=\n add_ematch_lemma_core reducible ff)\n add_lemmas_from_facts_core fs\n#align smt_tactic.add_lemmas_from_facts_core smt_tactic.add_lemmas_from_facts_core\n\nunsafe def add_lemmas_from_facts : smt_tactic Unit :=\n get_facts >>= add_lemmas_from_facts_core\n#align smt_tactic.add_lemmas_from_facts smt_tactic.add_lemmas_from_facts\n\nunsafe def induction (e : expr) (ids : List Name := []) (rec : Option Name := none) :\n smt_tactic Unit :=\n slift (tactic.induction e ids rec >> return ())\n#align smt_tactic.induction smt_tactic.induction\n\n-- pass on the information?\nunsafe def when (c : Prop) [Decidable c] (tac : smt_tactic Unit) : smt_tactic Unit :=\n if c then tac else skip\n#align smt_tactic.when smt_tactic.when\n\nunsafe def when_tracing (n : Name) (tac : smt_tactic Unit) : smt_tactic Unit :=\n when (is_trace_enabled_for n = true) tac\n#align smt_tactic.when_tracing smt_tactic.when_tracing\n\nend SmtTactic\n\nopen SmtTactic\n\nunsafe def using_smt {α} (t : smt_tactic α) (cfg : SmtConfig := { }) : tactic α := do\n let ss ← smt_state.mk cfg\n let (a, _) ←\n (do\n let a ← t\n iterate close\n return a).run\n ss\n return a\n#align using_smt using_smt\n\nunsafe def using_smt_with {α} (cfg : SmtConfig) (t : smt_tactic α) : tactic α :=\n using_smt t cfg\n#align using_smt_with using_smt_with\n\n", "meta": {"author": "leanprover-community", "repo": "lean3port", "sha": "9ed1898f23e4379865ee93d62cb6353e5ed6c270", "save_path": "github-repos/lean/leanprover-community-lean3port", "path": "github-repos/lean/leanprover-community-lean3port/lean3port-9ed1898f23e4379865ee93d62cb6353e5ed6c270/Leanbin/Init/Meta/Smt/SmtTactic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3276683139517237, "lm_q2_score": 0.06371498758495588, "lm_q1q2_score": 0.0208773825554175}} {"text": "import Lean\n\nnamespace SciLean.Meta.CustomSimp\n\nopen Lean Meta Elab Elab.Term\n\n\n-- Maybe add option to write logical formulas in simp guard\n-- something like @[simp_guard (n = 0) || (m = n)]\n\n/-- Prevent applying the theorem if the specified argument is equation to the specified value. \n\nWarning: It only works with custom simplifiers! Normal simplifier ignores this.\n\n\nExample:\n---\nAdding the following simp guard to the chain rule prevents appying it if `g` is an identity function.\n\n```\n @[simp_guard g (λ x => x)]\n theorem chain_rule {α β γ : Type}\n (f : β → γ) (g : α → β)\n : ∂ (λ x => f (g x)) = λ x dx => ∂ f (g x) (∂ g x dx) := ...\n```\n-/\nsyntax (name := simp_guard) \"simp_guard\" (ident term),+ : attr\n\ninitialize simpGuardAttr : ParametricAttribute (Array (Nat × Expr × Nat)) ←\n registerParametricAttribute {\n name := `simp_guard\n descr := \"Do not apply this simp theorem if the specified argument has the specified value.\"\n getParam := fun name => fun\n | `(attr| simp_guard $[$ids $vals],*) =>\n MetaM.run' <| TermElabM.run' <| (ids.zip vals).mapM λ (id, val) => do\n let info ← getConstInfo name\n\n let nth ← forallTelescope info.type λ args _ => do\n let i? ← args.findIdxM? \n (λ arg => do\n let argDecl ← getFVarLocalDecl arg\n pure (argDecl.userName = id.getId))\n match i? with\n | some i => pure i\n | none => throwError \"Theorem does not have an argument with the name `{id.getId}`\" \n\n -- `valueFun` is a function taking all theorem arguments [0,..,nth) and returning guard value\n let (valFun, numMVars) ← forallBoundedTelescope info.type nth λ args _ => do\n let value ← elabTerm val none\n let value ← abstractMVars value\n\n pure (← mkLambdaFVars args value.expr, value.numMVars)\n \n pure (nth, valFun, numMVars)\n | _ => Elab.throwUnsupportedSyntax\n }\n\n\ndef hasCustomSimpGuard (env : Environment) (n : Name) : Bool :=\n match simpGuardAttr.getParam? env n with\n | some _ => true\n | none => false\n", "meta": {"author": "lecopivo", "repo": "SciLean", "sha": "e4fe5962c862f9854a6c88a4082eb01bc1147086", "save_path": "github-repos/lean/lecopivo-SciLean", "path": "github-repos/lean/lecopivo-SciLean/SciLean-e4fe5962c862f9854a6c88a4082eb01bc1147086/SciLean/Tactic/CustomSimp/SimpGuard.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.32766830082071396, "lm_q2_score": 0.06371498758495588, "lm_q1q2_score": 0.020877381718775376}} {"text": "import data.pfun\nimport phase2.approximation\nimport phase2.complete_orbit\nimport phase2.reduction\n\nopen cardinal quiver set sum with_bot\nopen_locale cardinal classical pointwise\n\nuniverse u\n\nnamespace con_nf\nvariable [params.{u}]\n\n/-!\n# Weak approximations\n-/\n\n/-- Noncomputably eliminates a disjunction into a (possibly predicative) universe. -/\nnoncomputable def _root_.or.elim' {α : Sort*} {p q : Prop}\n (h : p ∨ q) (f : p → α) (g : q → α) : α :=\nif hp : p then f hp else g (h.resolve_left hp)\n\nlemma _root_.or.elim'_left {α : Sort*} {p q : Prop}\n (h : p ∨ q) (f : p → α) (g : q → α) (hp : p) : h.elim' f g = f hp :=\nby rw [or.elim', dif_pos hp]\n\nlemma _root_.or.elim'_right {α : Sort*} {p q : Prop}\n (h : p ∨ q) (f : p → α) (g : q → α) (hp : ¬p) : h.elim' f g = g (h.resolve_left hp) :=\nby rw [or.elim', dif_neg hp]\n\n/-- A *weak near-litter approximation* is a partial function from atoms to atoms and a partial\nfunction from litters to near-litters, both of which have small domain.\nThe image of a litter under the `litter_map` should be interpreted as the intended *precise* image\nof this litter under an allowable permutation.\nThe atom and litter maps should be injective (in suitable senses) and cohere in the sense that\nimages of atoms in litters are mapped to atoms inside the corresponding near-litters. -/\n@[ext] structure weak_near_litter_approx :=\n(atom_map : atom →. atom)\n(litter_map : litter →. near_litter)\n(atom_map_dom_small : small atom_map.dom)\n(litter_map_dom_small : small litter_map.dom)\n(atom_map_injective : ∀ ⦃a b⦄ ha hb, (atom_map a).get ha = (atom_map b).get hb → a = b)\n(litter_map_injective : ∀ ⦃L₁ L₂ : litter⦄ hL₁ hL₂,\n (((litter_map L₁).get hL₁ : set atom) ∩ (litter_map L₂).get hL₂).nonempty → L₁ = L₂)\n(atom_mem : ∀ (a : atom) ha L hL, a.1 = L ↔ (atom_map a).get ha ∈ (litter_map L).get hL)\n\n/-- A `β`-weak structural approximation is a product that assigns a weak near-litter approximation\nto each `β`-extended index. -/\ndef weak_struct_approx (β : type_index) := extended_index β → weak_near_litter_approx\n\nnamespace weak_near_litter_approx\n\nvariable (w : weak_near_litter_approx)\n\n/-- A litter that is not allowed to be used as a sandbox because it appears somewhere that\nwe need to preserve. -/\n@[mk_iff] inductive banned_litter : litter → Prop\n| atom_dom (a : atom) : (w.atom_map a).dom → banned_litter a.1\n| litter_dom (L : litter) : (w.litter_map L).dom → banned_litter L\n| atom_map (a : atom) (h) : banned_litter ((w.atom_map a).get h).1\n| litter_map (L : litter) (h) : banned_litter ((w.litter_map L).get h).1\n| diff (L : litter) (h) (a : atom) :\n a ∈ ((w.litter_map L).get h : set atom) \\ litter_set ((w.litter_map L).get h).1 →\n banned_litter a.1\n\nlemma banned_litter.mem_map (a : atom) (L : litter) (hL)\n (ha : a ∈ ((w.litter_map L).get hL : set atom)) : w.banned_litter a.1 :=\nbegin\n by_cases a.1 = ((w.litter_map L).get hL).1,\n { rw h,\n exact banned_litter.litter_map L hL, },\n { exact banned_litter.diff L hL a ⟨ha, h⟩, },\nend\n\n/-- There are only a small amount of banned litters. -/\nlemma banned_litter_small : small {L | w.banned_litter L} :=\nbegin\n simp only [banned_litter_iff, mem_diff, set_like.mem_coe, mem_litter_set],\n refine small.union _ (small.union _ (small.union _ (small.union _ _))),\n { refine lt_of_le_of_lt _ w.atom_map_dom_small,\n refine ⟨⟨λ a, ⟨_, a.prop.some_spec.1⟩, λ a₁ a₂ h, _⟩⟩,\n simp only [subtype.mk_eq_mk, prod.mk.inj_iff] at h,\n have := a₁.prop.some_spec.2,\n rw h at this,\n exact subtype.coe_injective (this.trans a₂.prop.some_spec.2.symm), },\n { refine lt_of_le_of_lt _ w.litter_map_dom_small,\n refine ⟨⟨λ L, ⟨_, L.prop⟩, λ L₁ L₂ h, _⟩⟩,\n simp only [subtype.mk_eq_mk, prod.mk.inj_iff] at h,\n exact subtype.coe_injective h, },\n { refine lt_of_le_of_lt _ w.atom_map_dom_small,\n refine ⟨⟨λ L, ⟨_, L.prop.some_spec.some⟩, λ L₁ L₂ h, _⟩⟩,\n simp only [subtype.mk_eq_mk, prod.mk.inj_iff] at h,\n have := L₁.prop.some_spec.some_spec,\n simp_rw h at this,\n exact subtype.coe_injective (this.trans L₂.prop.some_spec.some_spec.symm), },\n { refine lt_of_le_of_lt _ w.litter_map_dom_small,\n refine ⟨⟨λ L, ⟨_, L.prop.some_spec.some⟩, λ L₁ L₂ h, _⟩⟩,\n simp only [subtype.mk_eq_mk, prod.mk.inj_iff] at h,\n have := L₁.prop.some_spec.some_spec,\n simp_rw h at this,\n exact subtype.coe_injective (this.trans L₂.prop.some_spec.some_spec.symm), },\n { have : small ⋃ (L : litter) (h : (w.litter_map L).dom),\n ((w.litter_map L).get h : set atom) \\ litter_set ((w.litter_map L).get h).1,\n { refine small.bUnion _ _,\n { refine lt_of_le_of_lt _ w.litter_map_dom_small,\n refine ⟨⟨λ N, ⟨_, N.prop⟩, λ N₁ N₂ h, _⟩⟩,\n simp only [subtype.mk_eq_mk, prod.mk.inj_iff] at h,\n exact subtype.coe_inj.mp h, },\n { intros L hL,\n refine small.mono _ ((w.litter_map L).get hL).2.prop,\n exact λ x hx, or.inr hx, }, },\n refine lt_of_le_of_lt _ this,\n refine ⟨⟨λ L, ⟨L.prop.some_spec.some_spec.some, _⟩, λ L₁ L₂ h, _⟩⟩,\n { simp only [mem_Union],\n exact ⟨_, _, L.prop.some_spec.some_spec.some_spec.1⟩, },\n simp only [subtype.mk_eq_mk, prod.mk.inj_iff] at h,\n have := L₁.prop.some_spec.some_spec.some_spec.2,\n rw h at this,\n exact subtype.coe_injective\n (this.trans L₂.prop.some_spec.some_spec.some_spec.2.symm), },\nend\n\nlemma mk_not_banned_litter : #{L | ¬w.banned_litter L} = #μ :=\nbegin\n have := mk_sum_compl {L | w.banned_litter L},\n rw [compl_set_of, mk_litter] at this,\n rw [← this, add_eq_right],\n { by_contra' h,\n have h' := add_le_add (le_of_lt w.banned_litter_small) h.le,\n rw this at h',\n refine not_lt_of_le h' _,\n refine cardinal.add_lt_of_lt μ_strong_limit.is_limit.aleph_0_le κ_lt_μ _,\n exact lt_of_le_of_lt κ_regular.aleph_0_le κ_lt_μ, },\n { by_contra' h,\n have h' := add_le_add (le_of_lt w.banned_litter_small) h.le,\n rw this at h',\n refine not_lt_of_le h' _,\n refine cardinal.add_lt_of_lt μ_strong_limit.is_limit.aleph_0_le κ_lt_μ _,\n exact lt_trans w.banned_litter_small κ_lt_μ, },\nend\n\nlemma not_banned_litter_nonempty : nonempty {L | ¬w.banned_litter L} :=\nby simp only [← mk_ne_zero_iff, mk_not_banned_litter, ne.def, mk_ne_zero, not_false_iff]\n\n/-- The *sandbox litter* for a weak near-litter approximation is an arbitrarily chosen litter that\nisn't banned. -/\nnoncomputable def sandbox_litter : litter := w.not_banned_litter_nonempty.some\n\nlemma sandbox_litter_not_banned : ¬w.banned_litter w.sandbox_litter :=\nw.not_banned_litter_nonempty.some.prop\n\n/-- If `a` is in the domain, this is the atom map. Otherwise, this gives an arbitrary atom. -/\nnoncomputable def atom_map_or_else (a : atom) : atom := (w.atom_map a).get_or_else (arbitrary atom)\n\nlemma atom_map_or_else_of_dom {a : atom} (ha : (w.atom_map a).dom) :\n w.atom_map_or_else a = (w.atom_map a).get ha :=\nby rw [atom_map_or_else, part.get_or_else_of_dom]\n\nlemma mk_atom_map_image_le_mk_sandbox :\n #(w.atom_map.dom ∆ (w.atom_map_or_else '' w.atom_map.dom) : set atom) ≤\n #(litter_set w.sandbox_litter) :=\nbegin\n rw mk_litter_set,\n refine le_trans (mk_subtype_mono symm_diff_subset_union) (le_trans (mk_union_le _ _) _),\n refine add_le_of_le κ_regular.aleph_0_le _ _,\n exact le_of_lt w.atom_map_dom_small,\n exact le_trans mk_image_le (le_of_lt w.atom_map_dom_small),\nend\n\nlemma disjoint_sandbox :\n disjoint (w.atom_map.dom ∪ w.atom_map_or_else '' w.atom_map.dom) (litter_set w.sandbox_litter) :=\nbegin\n rw [disjoint_iff_inter_eq_empty, eq_empty_iff_forall_not_mem],\n rintros a ⟨ha₁, ha₂⟩,\n rw mem_litter_set at ha₂,\n have hnb := w.sandbox_litter_not_banned,\n rw ← ha₂ at hnb,\n cases ha₁,\n { exact hnb (banned_litter.atom_dom a ha₁), },\n { refine hnb _,\n simp only [mem_image, pfun.mem_dom] at ha₁,\n obtain ⟨b, ⟨_, hb, rfl⟩, rfl⟩ := ha₁,\n rw w.atom_map_or_else_of_dom hb,\n exact banned_litter.atom_map b hb, },\nend\n\nlemma atom_map_or_else_injective : inj_on w.atom_map_or_else w.atom_map.dom :=\nbegin\n intros a ha b hb h,\n rw [w.atom_map_or_else_of_dom ha, w.atom_map_or_else_of_dom hb] at h,\n exact w.atom_map_injective ha hb h,\nend\n\n/-- If `L` is in the domain, this is the litter map.\nOtherwise, this gives an arbitrary near-litter. -/\nnoncomputable def litter_map_or_else (L : litter) : near_litter :=\n(w.litter_map L).get_or_else (arbitrary near_litter)\n\nlemma litter_map_or_else_of_dom {L : litter} (hL : (w.litter_map L).dom) :\n w.litter_map_or_else L = (w.litter_map L).get hL :=\nby rw [litter_map_or_else, part.get_or_else_of_dom]\n\nnoncomputable def rough_litter_map_or_else (L : litter) : litter :=\n(w.litter_map_or_else L).1\n\nlemma rough_litter_map_or_else_of_dom {L : litter} (hL : (w.litter_map L).dom) :\n w.rough_litter_map_or_else L = ((w.litter_map L).get hL).1 :=\nby rw [rough_litter_map_or_else, litter_map_or_else_of_dom]\n\n/-- The induced action of this weak approximation on near-litters. -/\nnoncomputable def near_litter_map_or_else (N : near_litter) : near_litter :=\n⟨(w.litter_map_or_else N.fst).fst,\n w.litter_map_or_else N.fst ∆ (w.atom_map_or_else '' litter_set N.fst ∆ N),\n begin\n rw [is_near_litter, is_near, ← symm_diff_assoc],\n exact (w.litter_map_or_else N.fst).snd.prop.symm_diff (small.image N.2.prop),\n end⟩\n\n/-- A weak approximation is precise at a litter in its domain if all atoms in the symmetric\ndifference of its image are accounted for. -/\n@[mk_iff] structure precise_at {L : litter} (hL : (w.litter_map L).dom) : Prop :=\n(diff : ((w.litter_map L).get hL : set atom) ∆ litter_set ((w.litter_map L).get hL).1 ⊆\n w.atom_map.ran)\n(fwd : ∀ a ha, (w.atom_map a).get ha ∈ litter_set L → (w.atom_map ((w.atom_map a).get ha)).dom)\n(back : w.atom_map.dom ∩ (w.litter_map L).get hL ⊆ w.atom_map.ran)\n\n/-- A weak approximation is precise if it is precise at every litter in its domain. -/\ndef precise : Prop := ∀ ⦃L⦄ (hL : (w.litter_map L).dom), w.precise_at hL\n\n/-!\n## Induced litter permutation\n-/\n\nlemma mk_dom_symm_diff_le :\n #↥(w.litter_map.dom ∆ (w.rough_litter_map_or_else '' w.litter_map.dom)) ≤\n #{L : litter | ¬w.banned_litter L} :=\nbegin\n rw mk_not_banned_litter,\n refine le_trans (le_of_lt _) κ_le_μ,\n exact small.symm_diff w.litter_map_dom_small w.litter_map_dom_small.image,\nend\n\nlemma aleph_0_le_not_banned_litter : ℵ₀ ≤ #{L | ¬w.banned_litter L} :=\nbegin\n rw mk_not_banned_litter,\n exact μ_strong_limit.is_limit.aleph_0_le,\nend\n\nlemma disjoint_dom_not_banned_litter :\n disjoint (w.litter_map.dom ∪ w.rough_litter_map_or_else '' w.litter_map.dom)\n {L : litter | ¬w.banned_litter L} :=\nbegin\n simp only [set.disjoint_left, mem_union, pfun.mem_dom, mem_image, mem_set_of_eq, not_not],\n rintros _ (⟨_, hL, rfl⟩ | ⟨L, ⟨_, hL, rfl⟩, rfl⟩),\n { exact banned_litter.litter_dom _ hL, },\n { rw w.rough_litter_map_or_else_of_dom hL,\n exact banned_litter.litter_map _ hL, },\nend\n\nlemma rough_litter_map_or_else_inj_on : inj_on w.rough_litter_map_or_else w.litter_map.dom :=\nbegin\n intros L₁ hL₁ L₂ hL₂ h,\n rw [w.rough_litter_map_or_else_of_dom hL₁, w.rough_litter_map_or_else_of_dom hL₂] at h,\n exact w.litter_map_injective hL₁ hL₂ (near_litter.inter_nonempty_of_fst_eq_fst h),\nend\n\n/-- A local permutation on the set of litters that occur in the domain or range of `w`.\nThis permutes both flexible and inflexible litters. -/\nnoncomputable def litter_perm' : local_perm litter :=\nlocal_perm.complete\n w.rough_litter_map_or_else\n w.litter_map.dom\n {L | ¬w.banned_litter L}\n w.mk_dom_symm_diff_le\n w.aleph_0_le_not_banned_litter\n w.disjoint_dom_not_banned_litter\n w.rough_litter_map_or_else_inj_on\n\ndef id_on_banned (s : set litter) : local_perm litter := {\n to_fun := id,\n inv_fun := id,\n domain := {L | w.banned_litter L} \\ s,\n to_fun_domain' := λ L h, h,\n inv_fun_domain' := λ L h, h,\n left_inv' := λ L h, rfl,\n right_inv' := λ L h, rfl,\n}\n\nnoncomputable def litter_perm : local_perm litter :=\nlocal_perm.piecewise w.litter_perm' (w.id_on_banned w.litter_perm'.domain)\n (by rw ← set.subset_compl_iff_disjoint_left; exact λ L h, h.2)\n\nlemma litter_perm'_apply_eq (L : litter) (hL : L ∈ w.litter_map.dom) :\n w.litter_perm' L = w.rough_litter_map_or_else L :=\nlocal_perm.complete_apply_eq _ _ _ hL\n\nlemma litter_perm_apply_eq (L : litter) (hL : L ∈ w.litter_map.dom) :\n w.litter_perm L = w.rough_litter_map_or_else L :=\nbegin\n rw ← w.litter_perm'_apply_eq L hL,\n exact local_perm.piecewise_apply_eq_left (or.inl (or.inl hL)),\nend\n\nlemma litter_perm'_domain_small : small w.litter_perm'.domain :=\nbegin\n refine small.union (small.union w.litter_map_dom_small w.litter_map_dom_small.image) _,\n rw small,\n rw cardinal.mk_congr (local_perm.sandbox_subset_equiv _ _),\n simp only [mk_sum, mk_prod, mk_denumerable, lift_aleph_0, lift_uzero, lift_id],\n refine add_lt_of_lt κ_regular.aleph_0_le _ _;\n refine (mul_lt_of_lt κ_regular.aleph_0_le (lt_of_le_of_lt Λ_limit.aleph_0_le Λ_lt_κ) _);\n refine lt_of_le_of_lt (mk_subtype_mono (diff_subset _ _)) _,\n exact w.litter_map_dom_small,\n exact w.litter_map_dom_small.image,\nend\n\nlemma litter_perm_domain_small : small w.litter_perm.domain :=\nsmall.union w.litter_perm'_domain_small (small.mono (diff_subset _ _) w.banned_litter_small)\n\nvariables {α : Λ} [position_data.{}] [phase_2_assumptions α] {β : Iio α} {A : extended_index β}\n\nlemma mk_not_banned_litter_and_flexible : #{L | ¬w.banned_litter L ∧ flexible α L A} = #μ :=\nbegin\n refine le_antisymm ((mk_subtype_le _).trans mk_litter.le) _,\n by_contra,\n rw not_le at h,\n have h₁ := cardinal.le_mk_diff_add_mk {L | flexible α L A} {L | w.banned_litter L},\n rw [mk_flexible, diff_eq, inter_comm] at h₁,\n have h₂ := add_lt_of_lt μ_strong_limit.is_limit.aleph_0_le h\n (lt_trans w.banned_litter_small κ_lt_μ),\n exact h₁.not_lt h₂,\nend\n\nlemma mk_dom_inter_flexible_symm_diff_le :\n #↥((w.litter_map.dom ∩ {L | flexible α L A}) ∆\n (w.rough_litter_map_or_else '' (w.litter_map.dom ∩ {L | flexible α L A}))) ≤\n #{L : litter | ¬w.banned_litter L ∧ flexible α L A} :=\nbegin\n rw mk_not_banned_litter_and_flexible,\n refine le_trans (le_of_lt _) κ_le_μ,\n exact small.symm_diff\n (small.mono (inter_subset_left _ _) w.litter_map_dom_small)\n (small.mono (inter_subset_left _ _) w.litter_map_dom_small).image,\nend\n\nlemma aleph_0_le_not_banned_litter_and_flexible : ℵ₀ ≤ #{L | ¬w.banned_litter L ∧ flexible α L A} :=\nbegin\n rw mk_not_banned_litter_and_flexible,\n exact μ_strong_limit.is_limit.aleph_0_le,\nend\n\nlemma disjoint_dom_inter_flexible_not_banned_litter :\n disjoint ((w.litter_map.dom ∩ {L | flexible α L A})\n ∪ w.rough_litter_map_or_else '' (w.litter_map.dom ∩ {L | flexible α L A}))\n {L : litter | ¬w.banned_litter L ∧ flexible α L A} :=\nbegin\n refine disjoint_of_subset _ (inter_subset_left _ _) w.disjoint_dom_not_banned_litter,\n rintros a (ha | ⟨b, hb, rfl⟩),\n exact or.inl ha.1,\n exact or.inr ⟨b, hb.1, rfl⟩,\nend\n\nlemma rough_litter_map_or_else_inj_on_dom_inter_flexible :\n inj_on w.rough_litter_map_or_else (w.litter_map.dom ∩ {L | flexible α L A}) :=\nw.rough_litter_map_or_else_inj_on.mono (inter_subset_left _ _)\n\nnoncomputable def flexible_litter_perm (A : extended_index β) :\n local_perm litter :=\nlocal_perm.complete\n w.rough_litter_map_or_else\n (w.litter_map.dom ∩ {L | flexible α L A})\n {L | ¬w.banned_litter L ∧ flexible α L A}\n w.mk_dom_inter_flexible_symm_diff_le\n w.aleph_0_le_not_banned_litter_and_flexible\n w.disjoint_dom_inter_flexible_not_banned_litter\n w.rough_litter_map_or_else_inj_on_dom_inter_flexible\n\nlemma flexible_litter_perm_apply_eq (L : litter)\n (hL₁ : L ∈ w.litter_map.dom) (hL₂ : flexible α L A) :\n w.flexible_litter_perm A L = w.rough_litter_map_or_else L :=\nlocal_perm.complete_apply_eq _ _ _ ⟨hL₁, hL₂⟩\n\nlemma flexible_litter_perm_domain_small : small (w.flexible_litter_perm A).domain :=\nbegin\n refine small.union (small.union _ _) _,\n { exact w.litter_map_dom_small.mono (inter_subset_left _ _) },\n { exact (w.litter_map_dom_small.mono (inter_subset_left _ _)).image, },\n { rw small,\n rw cardinal.mk_congr (local_perm.sandbox_subset_equiv _ _),\n simp only [mk_sum, mk_prod, mk_denumerable, lift_aleph_0, lift_uzero, lift_id],\n refine add_lt_of_lt κ_regular.aleph_0_le _ _;\n refine (mul_lt_of_lt κ_regular.aleph_0_le (lt_of_le_of_lt Λ_limit.aleph_0_le Λ_lt_κ) _);\n refine lt_of_le_of_lt (mk_subtype_mono (diff_subset _ _)) _,\n exact w.litter_map_dom_small.mono (inter_subset_left _ _),\n exact (w.litter_map_dom_small.mono (inter_subset_left _ _)).image, },\nend\n\n/-!\n# Completed permutations\n-/\n\n/-- A local permutation induced by completing the orbits of atoms in a weak near-litter\napproximation. This function creates forward and backward images of atoms in the *sandbox litter*,\na litter which is away from the domain and range of the approximation in question, so it should\nnot interfere with other constructions. -/\nnoncomputable def complete_atom_perm : local_perm atom :=\nlocal_perm.complete\n w.atom_map_or_else\n w.atom_map.dom\n (litter_set w.sandbox_litter)\n w.mk_atom_map_image_le_mk_sandbox\n (by simpa only [mk_litter_set] using κ_regular.aleph_0_le)\n w.disjoint_sandbox\n w.atom_map_or_else_injective\n\nlemma sandbox_subset_small : small (local_perm.sandbox_subset\n w.mk_atom_map_image_le_mk_sandbox\n (by simpa only [mk_litter_set] using κ_regular.aleph_0_le)) :=\nbegin\n rw small,\n rw cardinal.mk_congr (local_perm.sandbox_subset_equiv _ _),\n simp only [mk_sum, mk_prod, mk_denumerable, lift_aleph_0, lift_uzero, lift_id],\n refine add_lt_of_lt κ_regular.aleph_0_le _ _;\n refine (mul_lt_of_lt κ_regular.aleph_0_le (lt_of_le_of_lt Λ_limit.aleph_0_le Λ_lt_κ) _);\n refine lt_of_le_of_lt (mk_subtype_mono (diff_subset _ _)) _,\n { exact w.atom_map_dom_small, },\n { exact lt_of_le_of_lt mk_image_le w.atom_map_dom_small, },\nend\n\nlemma complete_atom_perm_domain_small : small w.complete_atom_perm.domain :=\nsmall.union (small.union w.atom_map_dom_small\n (lt_of_le_of_lt mk_image_le w.atom_map_dom_small)) w.sandbox_subset_small\n\n/-- A near-litter approximation built from this weak near-litter approximation.\nIts action on atoms matches that of the weak approximation, and its rough action on litters\nmatches the given litter permutation. -/\nnoncomputable def complete (A : extended_index β) : near_litter_approx := {\n atom_perm := w.complete_atom_perm,\n litter_perm := w.flexible_litter_perm A,\n domain_small := λ L, small.mono (inter_subset_right _ _) w.complete_atom_perm_domain_small,\n}\n\nvariable {litter_perm : local_perm litter}\n\nlemma complete_atom_perm_apply_eq {a : atom} (ha : (w.atom_map a).dom) :\n w.complete_atom_perm a = (w.atom_map a).get ha :=\nby rwa [complete_atom_perm, local_perm.complete_apply_eq, atom_map_or_else_of_dom]\n\nlemma complete_smul_atom_eq {a : atom} (ha : (w.atom_map a).dom) :\n w.complete A • a = (w.atom_map a).get ha := w.complete_atom_perm_apply_eq ha\n\n@[simp] lemma complete_smul_litter_eq (L : litter) :\n w.complete A • L = w.flexible_litter_perm A L := rfl\n\nlemma smul_atom_eq\n {π : near_litter_perm} (hπ : (w.complete A).exactly_approximates π)\n {a : atom} (ha : (w.atom_map a).dom) :\n π • a = (w.atom_map a).get ha :=\nby rw [← hπ.map_atom a (or.inl (or.inl ha)), w.complete_smul_atom_eq ha]\n\nlemma smul_to_near_litter_eq_of_precise_at\n {π : near_litter_perm} (hπ : (w.complete A).exactly_approximates π)\n {L : litter} (hL : (w.litter_map L).dom) (hw : w.precise_at hL)\n (hπL : π • L = ((w.litter_map L).get hL).1) :\n π • L.to_near_litter = (w.litter_map L).get hL :=\nbegin\n refine set_like.coe_injective _,\n ext a : 1,\n simp only [mem_smul_set_iff_inv_smul_mem, near_litter_perm.coe_smul, litter.coe_to_near_litter,\n mem_litter_set, set_like.mem_coe],\n split,\n { intro ha,\n by_cases π.is_exception a,\n { suffices h' : π⁻¹ • a ∈ w.atom_map.dom,\n { rw w.atom_mem _ h' L hL at ha,\n have := hπ.map_atom _ (or.inl (or.inl h')),\n rw w.complete_smul_atom_eq h' at this,\n rw [this, smul_inv_smul] at ha,\n exact ha, },\n rw ← hπ.symm_map_atom a (hπ.exception_mem _ h) at ha ⊢,\n obtain ((hdom | hdom) | hdom) := (w.complete A).atom_perm.symm.map_domain\n (hπ.exception_mem _ h),\n { exact hdom, },\n { obtain ⟨c, hc₁, hc₂⟩ := hdom,\n rw w.atom_map_or_else_of_dom hc₁ at hc₂,\n have := hw.fwd c hc₁ (by rwa hc₂),\n rw hc₂ at this,\n exact this, },\n { cases w.sandbox_litter_not_banned _,\n rw ← eq_of_mem_litter_set_of_mem_litter_set ha\n (local_perm.sandbox_subset_subset _ _ hdom),\n exact banned_litter.litter_dom L hL, }, },\n { by_contradiction h',\n simp only [near_litter_perm.is_exception, mem_litter_set, not_or_distrib, not_not, ha] at h,\n obtain ⟨b, hb, rfl⟩ := hw.diff\n (or.inr ⟨by rw [← hπL, h.2, smul_inv_smul, mem_litter_set], h'⟩),\n refine h' ((w.atom_mem b hb L hL).mp _),\n have := hπ.map_atom b (or.inl (or.inl hb)),\n rw [w.complete_smul_atom_eq hb] at this,\n rw [this, inv_smul_smul] at ha,\n exact ha, }, },\n { intro ha,\n -- TODO: probably possible to clean up `by_cases` into a `suffices`\n by_cases π⁻¹ • a ∈ w.atom_map.dom,\n { rw w.atom_mem _ h L hL,\n have := hπ.map_atom _ (or.inl (or.inl h)),\n rw w.complete_smul_atom_eq h at this,\n rw [this, smul_inv_smul],\n exact ha, },\n have haL : a ∈ litter_set ((w.litter_map L).get hL).fst,\n { by_contradiction h',\n obtain ⟨b, hb, rfl⟩ := hw.diff (or.inl ⟨ha, h'⟩),\n have := hπ.map_atom b (or.inl (or.inl hb)),\n rw [w.complete_smul_atom_eq hb] at this,\n rw [this, inv_smul_smul] at h,\n exact h hb, },\n by_contradiction h',\n have hex : π.is_exception a,\n { refine or.inr (λ h'', h' (h''.trans _)),\n rw [inv_smul_eq_iff, hπL],\n exact haL, },\n obtain ((hdom | ⟨b, hb₁, hb₂⟩) | hdom) := hπ.exception_mem a hex,\n { obtain ⟨b, hb₁, hb₂⟩ := hw.back ⟨hdom, ha⟩,\n have := hπ.map_atom b (or.inl (or.inl hb₁)),\n rw [w.complete_smul_atom_eq hb₁] at this,\n rw [this, smul_eq_iff_eq_inv_smul] at hb₂,\n rw hb₂ at hb₁,\n exact h hb₁, },\n { rw w.atom_map_or_else_of_dom hb₁ at hb₂,\n have := hπ.map_atom b (or.inl (or.inl hb₁)),\n rw [w.complete_smul_atom_eq hb₁, hb₂, ← inv_smul_eq_iff] at this,\n rw this at h,\n exact h hb₁, },\n { refine w.sandbox_litter_not_banned _,\n rw eq_of_mem_litter_set_of_mem_litter_set (local_perm.sandbox_subset_subset _ _ hdom) haL,\n exact banned_litter.litter_map L hL, }, },\nend\n\nlemma smul_near_litter_eq_of_precise_at\n {π : near_litter_perm} (hπ : (w.complete A).exactly_approximates π)\n {N : near_litter} (hN : (w.litter_map N.1).dom) (hw : w.precise_at hN)\n (hπL : π • N.1 = ((w.litter_map N.1).get hN).1) :\n ((π • N : near_litter) : set atom) = (w.litter_map N.1).get hN ∆ (π • (litter_set N.1 ∆ N)) :=\nbegin\n refine (near_litter_perm.smul_near_litter_eq_smul_symm_diff_smul _ _).trans _,\n rw ← w.smul_to_near_litter_eq_of_precise_at hπ hN hw hπL,\n refl,\nend\n\nend weak_near_litter_approx\n\nnamespace weak_struct_approx\n\nsection\n\ndef precise {β : type_index} (w : weak_struct_approx β) : Prop := ∀ B, (w B).precise\n\nvariables {α : Λ} [position_data.{}] [phase_2_assumptions α] {β : Iio α} (w : weak_struct_approx β)\n\nnoncomputable def complete : struct_approx β :=\nλ B, (w B).complete B\n\nlemma smul_atom_eq\n {π : struct_perm β} (hπ : w.complete.exactly_approximates π)\n {a : atom} {B : extended_index β} (ha : ((w B).atom_map a).dom) :\n struct_perm.derivative B π • a = ((w B).atom_map a).get ha :=\nbegin\n have := (w B).smul_atom_eq (hπ B) ha,\n rw struct_perm.of_bot_smul at this,\n exact this,\nend\n\nlemma smul_to_near_litter_eq_of_precise (hw : w.precise)\n {π : struct_perm β} (hπ : w.complete.exactly_approximates π)\n {L : litter} {B : extended_index β} (hL : ((w B).litter_map L).dom)\n (hπL : struct_perm.derivative B π • L = (((w B).litter_map L).get hL).1) :\n struct_perm.derivative B π • L.to_near_litter = ((w B).litter_map L).get hL :=\nbegin\n have := (w B).smul_to_near_litter_eq_of_precise_at (hπ B) hL (hw B hL) _,\n { rw struct_perm.of_bot_smul at this,\n exact this, },\n { rw struct_perm.of_bot_smul,\n exact hπL, },\nend\n\nlemma smul_near_litter_eq_of_precise (hw : w.precise)\n {π : struct_perm β} (hπ : w.complete.exactly_approximates π)\n {N : near_litter} {B : extended_index β} (hN : ((w B).litter_map N.1).dom)\n (hπL : struct_perm.derivative B π • N.1 = (((w B).litter_map N.1).get hN).1) :\n ((struct_perm.derivative B π • N : near_litter) : set atom) =\n ((w B).litter_map N.1).get hN ∆ (struct_perm.derivative B π • (litter_set N.1 ∆ N)) :=\nbegin\n have := (w B).smul_near_litter_eq_of_precise_at (hπ B) hN (hw B hN) _,\n { rw struct_perm.of_bot_smul at this,\n exact this, },\n { rw struct_perm.of_bot_smul,\n exact hπL, },\nend\n\nend\n\nvariables {α : Λ} [position_data.{}] [phase_2_assumptions α] {β : Iio α}\n\n/-- A weak structural approximation *supports* a tangle if it defines an image for everything\nin the reduction of its designated support. -/\nstructure supports (w : weak_struct_approx β) (t : tangle β) : Prop :=\n(atom_mem : ∀ a B, (inl a, B) ∈ reduction α (designated_support t : set (support_condition β)) →\n ((w B).atom_map a).dom)\n(litter_mem : ∀ (L : litter) B,\n (inr L.to_near_litter, B) ∈ reduction α (designated_support t : set (support_condition β)) →\n ((w B).litter_map L).dom)\n\n/-- Two weak structural approximations are *compatible* for a tangle if they both support the\ntangle and agree on the reduction of its designated support. -/\nstructure compatible (w v : weak_struct_approx β) (t : tangle β) : Prop :=\n(w_supports : w.supports t)\n(v_supports : v.supports t)\n(atom_map : ∀ a B ha, ((w B).atom_map a).get (w_supports.atom_mem a B ha) =\n ((v B).atom_map a).get (v_supports.atom_mem a B ha))\n(litter_map : ∀ L B hL, ((w B).litter_map L).get (w_supports.litter_mem L B hL) =\n ((v B).litter_map L).get (v_supports.litter_mem L B hL))\n\n/-- The action of a weak structural approximation on support conditions. -/\nnoncomputable def support_condition_map_or_else (w : weak_struct_approx β) :\n support_condition β → support_condition β\n| (inl a, B) := (inl ((w B).atom_map_or_else a), B)\n| (inr N, B) := (inr ((w B).near_litter_map_or_else N), B)\n\ndef coherent_coe (w : weak_struct_approx β) (t : tangle β) : Prop :=\n∀ {π : allowable β} (hπ : w.complete.exactly_approximates π.to_struct_perm)\n (γ : Iic α) (δ ε : Iio α) (hδ : (δ : Λ) < γ) (hε : (ε : Λ) < γ) (hδε : δ ≠ ε)\n (C : path (β : type_index) γ) (t' : tangle δ) (hL)\n (hc₁ : ∃ (d : support_condition β), d ∈ (designated_support t).carrier ∧\n relation.refl_trans_gen (constrains α β)\n (inr (f_map (coe_ne_coe.mpr (coe_ne' hδε)) t').to_near_litter,\n (C.cons (coe_lt hε)).cons (bot_lt_coe _)) d)\n (hc₂ : ∀ (c : support_condition δ), c ∈ (designated_support t').carrier →\n π • (show support_condition β, from (c.fst, (C.cons (coe_lt hδ)).comp c.snd)) =\n w.support_condition_map_or_else (c.fst, (C.cons (coe_lt hδ)).comp c.snd)),\n f_map (subtype.coe_injective.ne (Iio.coe_injective.ne hδε))\n (show tangle δ, from\n (show allowable δ, from allowable_derivative (γ : Iic_index α) δ (coe_lt_coe.mpr hδ)\n (allowable.derivative\n (show path ((β : Iic_index α) : type_index) (γ : Iic_index α), from C) π)) • t') =\n (((w ((C.cons (coe_lt hε)).cons (bot_lt_coe _))).litter_map\n (f_map (subtype.coe_injective.ne (Iio.coe_injective.ne hδε)) t')).get hL).fst\n\ndef coherent_bot (w : weak_struct_approx β) : Prop :=\n∀ {π : allowable β} (hπ : w.complete.exactly_approximates π.to_struct_perm)\n (γ : Iic α) (ε : Iio α) (hε : (ε : Λ) < γ)\n (C : path (β : type_index) γ) (a : tangle ⊥) (hL)\n (hc : struct_perm.derivative (C.cons (bot_lt_coe _)) π.to_struct_perm • a =\n (w (C.cons (bot_lt_coe _))).atom_map_or_else a),\n f_map (show ((⊥ : Iio_index α) : type_index) ≠ (ε : Iio_index α),\n from subtype.coe_injective.ne Iio_index.bot_ne_coe)\n ((struct_perm.derivative (C.cons (bot_lt_coe _))) π.to_struct_perm • a) =\n (((w ((C.cons (coe_lt hε)).cons (bot_lt_coe _))).litter_map\n (f_map (show (⊥ : type_index) ≠ (ε : Λ), from bot_ne_coe) a)).get hL).fst\n\n@[mk_iff] structure coherent (w : weak_struct_approx β) (t : tangle β) : Prop :=\n(coe : w.coherent_coe t)\n(bot : w.coherent_bot)\n\nlemma smul_litter_eq_of_supports (w : weak_struct_approx β)\n {π : allowable β} (hπ : w.complete.exactly_approximates π.to_struct_perm)\n (t : tangle β) (hwc : w.coherent t) (hws : w.supports t)\n (d : support_condition β) (hd : d ∈ designated_support t)\n (B : extended_index β) (L : litter)\n (ih : ∀ (e : support_condition β),\n relation.trans_gen (constrains α β) e (inr L.to_near_litter, B) →\n π • e = w.support_condition_map_or_else e)\n (hc : relation.refl_trans_gen (constrains α β) (inr L.to_near_litter, B) d) :\n struct_perm.derivative B π.to_struct_perm • L =\n (((w B).litter_map L).get\n (hws.litter_mem L B ⟨⟨d, hd, refl_trans_gen_near_litter hc⟩, reduced.mk_litter _ _⟩)).fst :=\nbegin\n by_cases hflex : inflexible α L B,\n rw inflexible_iff at hflex,\n obtain (⟨γ, δ, ε, hδ, hε, hδε, C, t', rfl, rfl⟩ | ⟨γ, ε, hε, C, a, rfl, rfl⟩) := hflex,\n { have hc₂ := λ c hc, ih _ (relation.trans_gen.single $ constrains.f_map hδ hε hδε C t' c hc),\n have := smul_f_map (δ : Iio_index α) ε _ _ (Iio.coe_injective.ne hδε)\n (allowable.derivative\n (show path ((β : Iic_index α) : type_index) (γ : Iic_index α), from C) π) t',\n rw [← allowable.derivative_cons_apply, allowable.derivative_smul,\n ← struct_perm.derivative_bot_smul, ← struct_perm.derivative_cons] at this,\n exact this.trans (hwc.coe hπ γ δ ε hδ hε hδε C t' _ ⟨d, hd, hc⟩ hc₂), },\n { have hc : (_, _) = (_, _) := ih _ (relation.trans_gen.single $ constrains.f_map_bot hε C a),\n simp only [smul_inl, prod.mk.inj_iff, eq_self_iff_true, and_true] at hc,\n have := smul_f_map (⊥ : Iio_index α) ε _ _ _\n (allowable.derivative\n (show path ((β : Iic_index α) : type_index) (γ : Iic_index α), from C) π) a,\n rw [← allowable.derivative_cons_apply, allowable.derivative_smul,\n ← struct_perm.derivative_bot_smul, ← struct_perm.derivative_cons] at this,\n rw ← hwc.bot hπ γ ε hε C a _ hc,\n refine this.trans _,\n swap 3,\n refine congr_arg _ _,\n swap 3,\n { rw ← allowable.derivative_cons_apply,\n rw ← allowable.derivative_smul\n (show path ((β : Iic_index α) : type_index) ((⊥ : Iic_index α) : type_index),\n from C.cons (bot_lt_coe _)) π a,\n congr,\n sorry, },\n all_goals { sorry, }, },\n { have := hws.litter_mem L B ⟨⟨d, hd, refl_trans_gen_near_litter hc⟩, reduced.mk_litter _ _⟩,\n rw [← struct_perm.of_bot_smul, ← (hπ B).map_litter _ (or.inl (or.inl ⟨this, hflex⟩))],\n refine ((w B).complete_smul_litter_eq L).trans _,\n rw [(w B).flexible_litter_perm_apply_eq, (w B).rough_litter_map_or_else_of_dom],\n exact this,\n exact hflex, },\nend\n\nlemma smul_support_condition_eq (w : weak_struct_approx β) (hw : w.precise)\n {π : allowable β} (hπ : w.complete.exactly_approximates π.to_struct_perm)\n (t : tangle β) (hwc : w.coherent t) (hws : w.supports t)\n (c d : support_condition β)\n (hc : relation.refl_trans_gen (constrains α β) c d)\n (hd : d ∈ designated_support t) :\n π • c = w.support_condition_map_or_else c :=\nbegin\n revert d,\n refine (constrains_wf α β).trans_gen.induction c _,\n rintros c ih d hc hd,\n obtain ⟨a | N, B⟩ := c,\n { refine prod.ext _ rfl,\n change inl _ = inl _,\n refine congr_arg inl _,\n rw [w.smul_atom_eq hπ (hws.atom_mem a B ⟨⟨d, hd, hc⟩, reduced.mk_atom a B⟩),\n weak_near_litter_approx.atom_map_or_else_of_dom], },\n refine prod.ext _ rfl,\n change inr _ = inr _,\n refine congr_arg inr (set_like.coe_injective _),\n have ih' := λ e he, ih e (relation.trans_gen.single he) d\n (relation.refl_trans_gen.head he hc) hd,\n rw w.smul_near_litter_eq_of_precise hw hπ (hws.litter_mem N.1 B _) _,\n { simp only [weak_near_litter_approx.near_litter_map_or_else,\n near_litter.coe_mk, subtype.coe_mk],\n rw (w B).litter_map_or_else_of_dom (hws.litter_mem N.1 B _),\n congr' 1,\n ext a : 1,\n rw [mem_smul_set, mem_image],\n split,\n { rintro ⟨b, hb₁, hb₂⟩,\n have : (_, _) = (_, _) := ih' _ (constrains.symm_diff N _ hb₁ B),\n simp only [smul_inl, smul_inv_smul, prod.mk.inj_iff] at this,\n rw this.1 at hb₂,\n exact ⟨b, hb₁, hb₂⟩, },\n { rintro ⟨b, hb₁, hb₂⟩,\n have : (_, _) = (_, _) := ih' _ (constrains.symm_diff N _ hb₁ B),\n simp only [smul_inl, smul_inv_smul, prod.mk.inj_iff] at this,\n rw ← this.1 at hb₂,\n exact ⟨b, hb₁, hb₂⟩, },\n { exact ⟨⟨d, hd, refl_trans_gen_near_litter hc⟩, reduced.mk_litter _ _⟩, }, },\n refine w.smul_litter_eq_of_supports hπ t hwc hws d hd B N.1 _ (refl_trans_gen_near_litter hc),\n exact λ e he, ih e (trans_gen_near_litter he) d\n (relation.refl_trans_gen.trans he.to_refl (refl_trans_gen_near_litter hc)) hd,\nend\n\nlemma smul_eq_smul_tangle (w v : weak_struct_approx β)\n (hw : w.precise) (hv : v.precise)\n (t : tangle β) (h : compatible w v t)\n (hwc : w.coherent t) (hvc : v.coherent t)\n {πw πv : allowable β} (hπw : w.complete.exactly_approximates πw.to_struct_perm)\n (hπv : v.complete.exactly_approximates πv.to_struct_perm) :\n πw • t = πv • t :=\nbegin\n rw [smul_eq_iff_eq_inv_smul, smul_smul],\n symmetry,\n refine (designated_support t).supports _ _,\n intros c hc,\n rw [mul_smul, inv_smul_eq_iff],\n symmetry,\n rw smul_support_condition_eq w hw hπw t hwc h.w_supports c c relation.refl_trans_gen.refl hc,\n rw smul_support_condition_eq v hv hπv t hvc h.v_supports c c relation.refl_trans_gen.refl hc,\n obtain ⟨a | N, B⟩ := c,\n { simp only [support_condition_map_or_else, prod.mk.inj_iff, eq_self_iff_true, and_true],\n rw [(w B).atom_map_or_else_of_dom, (v B).atom_map_or_else_of_dom],\n refine h.atom_map a B _,\n exact ⟨⟨_, hc, relation.refl_trans_gen.refl⟩, reduced.mk_atom _ _⟩, },\n { simp only [support_condition_map_or_else, prod.mk.inj_iff, eq_self_iff_true, and_true,\n weak_near_litter_approx.near_litter_map_or_else],\n refine set_like.coe_injective _,\n simp only [near_litter.coe_mk, subtype.coe_mk],\n congr' 1,\n { rw [(w B).litter_map_or_else_of_dom, (v B).litter_map_or_else_of_dom, h.litter_map N.1 B _],\n exact ⟨⟨_, hc, refl_trans_gen_near_litter relation.refl_trans_gen.refl⟩,\n reduced.mk_litter _ _⟩, },\n { ext a : 1,\n rw [mem_image, mem_image],\n split;\n rintro ⟨b, hb₁, hb₂⟩;\n refine ⟨b, hb₁, _⟩;\n rw [← hb₂, (w B).atom_map_or_else_of_dom, (v B).atom_map_or_else_of_dom],\n { refine (h.atom_map b B _).symm,\n exact ⟨⟨_, hc, relation.refl_trans_gen.single (constrains.symm_diff N b hb₁ B)⟩,\n reduced.mk_atom _ _⟩, },\n { refine h.atom_map b B _,\n exact ⟨⟨_, hc, relation.refl_trans_gen.single (constrains.symm_diff N b hb₁ B)⟩,\n reduced.mk_atom _ _⟩, }, }, },\nend\n\nend weak_struct_approx\n\nend con_nf\n", "meta": {"author": "leanprover-community", "repo": "con-nf", "sha": "f0b66bd73ca5d3bd8b744985242c4c0b5464913f", "save_path": "github-repos/lean/leanprover-community-con-nf", "path": "github-repos/lean/leanprover-community-con-nf/con-nf-f0b66bd73ca5d3bd8b744985242c4c0b5464913f/src/phase2/weak_approx.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45326186278634367, "lm_q2_score": 0.046033905343956086, "lm_q1q2_score": 0.020865413687531757}} {"text": "/-\nCopyright (c) 2021 Gabriel Ebner. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Gabriel Ebner, Scott Morrison\n-/\nimport Std.Tactic.TryThis\nimport Mathlib.Lean.Expr.Basic\nimport Mathlib.Tactic.Cache\nimport Mathlib.Tactic.Core\nimport Mathlib.Tactic.SolveByElim\n\n/-!\n# Library search\n\nThis file defines a tactic `library_search`\nand a term elaborator `library_search%`\nthat tries to find a lemma\nsolving the current goal\n(subgoals are solved using `solveByElim`).\n\n```\nexample : x < x + 1 := library_search%\nexample : Nat := by library_search\n```\n-/\n\nnamespace Lean.Meta.DiscrTree\n\n/--\nInserts a new key into a discrimination tree,\nbut only if it is not of the form `#[*]` or `#[=, *, *, *]`.\n-/\ndef insertIfSpecific {α : Type} {s : Bool} [BEq α] (d : DiscrTree α s)\n (keys : Array (DiscrTree.Key s)) (v : α) : DiscrTree α s :=\n if keys == #[Key.star] || keys == #[Key.const `Eq 3, Key.star, Key.star, Key.star] then\n d\n else\n d.insertCore keys v\n\nend Lean.Meta.DiscrTree\n\nnamespace Mathlib.Tactic.LibrarySearch\n\nopen Lean Meta Std.Tactic.TryThis\n\ninitialize registerTraceClass `Tactic.librarySearch\n\n-- from Lean.Server.Completion\nprivate def isBlackListed (declName : Name) : MetaM Bool := do\n if declName == ``sorryAx then return true\n if declName matches .str _ \"inj\" then return true\n if declName matches .str _ \"noConfusionType\" then return true\n let env ← getEnv\n pure $ declName.isInternal'\n || isAuxRecursor env declName\n || isNoConfusion env declName\n <||> isRec declName <||> isMatcher declName\n\n/--\nA \"modifier\" for a declaration.\n* `none` indicates the original declaration,\n* `symm` indicates that (possibly after binders) the declaration is an `=`,\n and we want to consider the symmetric version,\n* `mp` indicates that (possibly after binders) the declaration is an `iff`,\n and we want to consider the forward direction,\n* `mpr` similarly, but for the backward direction.\n-/\ninductive DeclMod\n| none | symm | mp | mpr\nderiving DecidableEq\n\ninitialize librarySearchLemmas : DeclCache (DiscrTree (Name × DeclMod) true) ←\n DeclCache.mk \"librarySearch: init cache\" {} fun name constInfo lemmas => do\n if constInfo.isUnsafe then return lemmas\n if ← isBlackListed name then return lemmas\n withNewMCtxDepth do withReducible do\n let (_, _, type) ← forallMetaTelescopeReducing constInfo.type\n let keys ← DiscrTree.mkPath type\n let lemmas := lemmas.insertIfSpecific keys (name, .none)\n match type.getAppFnArgs with\n | (``Eq, #[_, lhs, rhs]) => do\n let keys_symm ← DiscrTree.mkPath (← mkEq rhs lhs)\n pure (lemmas.insertIfSpecific keys_symm (name, .symm))\n | (``Iff, #[lhs, rhs]) => do\n let keys_mp ← DiscrTree.mkPath rhs\n let keys_mpr ← DiscrTree.mkPath lhs\n pure <| (lemmas.insertIfSpecific keys_mp (name, .mp)).insertIfSpecific keys_mpr (name, .mpr)\n | _ => pure lemmas\n\n/-- Shortcut for calling `solveByElim`. -/\ndef solveByElim (goals : List MVarId) (required : List Expr) (depth) := do\n -- There is only a marginal decrease in performance for using the `symm` and `exfalso`\n -- options for `solveByElim`.\n -- (measured via `lake build && time lake env lean test/librarySearch.lean`).\n let cfg : SolveByElim.Config := { maxDepth := depth, exfalso := true, symm := true }\n let cfg := if !required.isEmpty then cfg.requireUsingAll required else cfg\n _ ← SolveByElim.solveByElim.processSyntax cfg false false [] [] #[] goals\n\n/--\nTry to solve the goal either by:\n* calling `solveByElim`\n* or applying a library lemma then calling `solveByElim` on the resulting goals.\n\nIf it successfully closes the goal, returns `none`.\nOtherwise, it returns `some a`, where `a : Array (MetavarContext × List MVarId)`,\nwith an entry for each library lemma which was successfully applied,\ncontaining the metavariable context after the application, and a list of the subsidiary goals.\n\n(Always succeeds, and the metavariable context stored in the monad is reverted,\nunless the goal was completely solved.)\n\n(Note that if `solveByElim` solves some but not all subsidiary goals,\nthis is not currently tracked.)\n-/\ndef librarySearch (goal : MVarId) (lemmas : DiscrTree (Name × DeclMod) s) (required : List Expr)\n (solveByElimDepth := 6) : MetaM <| Option (Array <| MetavarContext × List MVarId) := do\n profileitM Exception \"librarySearch\" (← getOptions) do\n let ty ← goal.getType\n withTraceNode `Tactic.librarySearch (return m!\"{exceptOptionEmoji ·} {ty}\") do\n\n let mut suggestions := #[]\n\n let state0 ← get\n\n try\n solveByElim [goal] required solveByElimDepth\n return none\n catch _ =>\n set state0\n\n for (lem, mod) in ← lemmas.getMatch ty do\n trace[Tactic.librarySearch] \"{lem}\"\n let result ← withTraceNode `Tactic.librarySearch (return m!\"{exceptOptionEmoji ·} trying {lem}\")\n try\n let lem ← mkConstWithFreshMVarLevels lem\n let lem ← match mod with\n | .none => pure lem\n | .symm => mapForallTelescope (fun e => mkAppM ``Eq.symm #[e]) lem\n | .mp => mapForallTelescope (fun e => mkAppM ``Iff.mp #[e]) lem\n | .mpr => mapForallTelescope (fun e => mkAppM ``Iff.mpr #[e]) lem\n let newGoals ← goal.apply lem\n (try\n for newGoal in newGoals do\n trace[Tactic.librarySearch] \"proving {← addMessageContextFull (mkMVar newGoal)}\"\n solveByElim newGoals required solveByElimDepth\n pure $ some $ Sum.inr ()\n catch _ =>\n let res := some $ Sum.inl (← getMCtx, newGoals)\n set state0\n return res)\n catch _ =>\n set state0\n pure none\n match result with\n | none => pure ()\n | some (Sum.inr ()) => return none\n | some (Sum.inl suggestion) => suggestions := suggestions.push suggestion\n\n pure $ some suggestions\n\ndef lines (ls : List MessageData) :=\n MessageData.joinSep ls (MessageData.ofFormat Format.line)\n\nopen Lean.Parser.Tactic\n\n-- TODO: implement the additional options for `library_search` from Lean 3,\n-- in particular including additional lemmas\n-- with `library_search [X, Y, Z]` or `library_search with attr`.\nsyntax (name := librarySearch') \"library_search\" (config)? (simpArgs)?\n (\" using \" (colGt term),+)? : tactic\nsyntax (name := librarySearch!) \"library_search!\" (config)? (simpArgs)?\n (\" using \" (colGt term),+)? : tactic\n\n-- For now we only implement the basic functionality.\n-- The full syntax is recognized, but will produce a \"Tactic has not been implemented\" error.\n\nopen Elab.Tactic Elab Tactic in\nelab_rules : tactic | `(tactic| library_search%$tk $[using $[$required:term],*]?) => do\n let mvar ← getMainGoal\n let (_, goal) ← (← getMainGoal).intros\n goal.withContext do\n let required := (← (required.getD #[]).mapM getFVarId).toList.map .fvar\n if let some suggestions ← librarySearch goal (← librarySearchLemmas.get) required then\n for suggestion in suggestions do\n withMCtx suggestion.1 do\n addExactSuggestion tk (← instantiateMVars (mkMVar mvar)).headBeta\n admitGoal goal\n else\n addExactSuggestion tk (← instantiateMVars (mkMVar mvar)).headBeta\n\nopen Elab Term in\nelab tk:\"library_search%\" : term <= expectedType => do\n let goal ← mkFreshExprMVar expectedType\n let (_, introdGoal) ← goal.mvarId!.intros\n introdGoal.withContext do\n if let some suggestions ← librarySearch introdGoal (← librarySearchLemmas.get) [] then\n for suggestion in suggestions do\n withMCtx suggestion.1 do\n addTermSuggestion tk (← instantiateMVars goal).headBeta\n mkSorry expectedType (synthetic := true)\n else\n addTermSuggestion tk (← instantiateMVars goal).headBeta\n instantiateMVars goal\n", "meta": {"author": "leanprover-community", "repo": "mathlib4", "sha": "b9a0a30342ca06e9817e22dbe46e75fc7f435500", "save_path": "github-repos/lean/leanprover-community-mathlib4", "path": "github-repos/lean/leanprover-community-mathlib4/mathlib4-b9a0a30342ca06e9817e22dbe46e75fc7f435500/Mathlib/Tactic/LibrarySearch.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38491214448393346, "lm_q2_score": 0.05419873211474107, "lm_q1q2_score": 0.02086175020659522}} {"text": "\nimport tactic\nimport tactic.monotonicity\nimport tactic.norm_num\nimport category.basic\nimport category.nursery\nimport data.equiv.nursery\nimport data.serial.medium\n\nuniverses u v w\n\nabbreviation put_m' := medium.put_m'.{u} unsigned\nabbreviation put_m := medium.put_m'.{u} unsigned punit\nabbreviation get_m := medium.get_m.{u} unsigned\n\ndef serial_inverse {α : Type u} (encode : α → put_m) (decode : get_m α) : Prop :=\n∀ w, decode -<< encode w = pure w\n\nclass serial (α : Type u) :=\n (encode : α → put_m)\n (decode : get_m α)\n (correctness : ∀ w, decode -<< encode w = pure w)\n\nclass serial1 (f : Type u → Type v) :=\n (encode : Π {α}, (α → put_m) → f α → put_m)\n (decode : Π {α}, get_m α → get_m (f α))\n (correctness : ∀ {α} put get, serial_inverse.{u} put get →\n ∀ (w : f α), decode get -<< encode put w = pure w)\n\ninstance serial.serial1 {f α} [serial1 f] [serial α] : serial (f α) :=\n{ encode := λ x, serial1.encode serial.encode x,\n decode := serial1.decode f (serial.decode α),\n correctness := serial1.correctness _ _ serial.correctness }\n\nclass serial2 (f : Type u → Type v → Type w) :=\n (encode : Π {α β}, (α → put_m.{u}) → (β → put_m.{v}) → f α β → put_m.{w})\n (decode : Π {α β}, get_m α → get_m β → get_m (f α β))\n (correctness : ∀ {α β} putα getα putβ getβ,\n serial_inverse putα getα →\n serial_inverse putβ getβ →\n ∀ (w : f α β), decode getα getβ -<< encode putα putβ w = pure w)\n\ninstance serial.serial2 {f α β} [serial2 f] [serial α] [serial β] : serial (f α β) :=\n{ encode := λ x, serial2.encode serial.encode serial.encode x,\n decode := serial2.decode f (serial.decode _) (serial.decode _),\n correctness := serial2.correctness _ _ _ _ serial.correctness serial.correctness }\n\ninstance serial1.serial2 {f α} [serial2 f] [serial α] : serial1 (f α) :=\n{ encode := λ β put x, serial2.encode serial.encode put x,\n decode := λ β get, serial2.decode f (serial.decode _) get,\n correctness := λ β get put, serial2.correctness _ _ _ _ serial.correctness }\n\nexport serial (encode decode)\n\nnamespace serial\n\nopen function\nexport medium (hiding put_m get_m put_m')\n\nvariables {α β σ γ : Type u} {ω : Type}\n\ndef serialize [serial α] (x : α) : list unsigned := (encode x).eval\ndef deserialize (α : Type u) [serial α] (bytes : list unsigned) : option α := (decode α).eval bytes\n\nlemma deserialize_serialize [serial α] (x : α) :\n deserialize _ (serialize x) = some x :=\nby simp [deserialize,serialize,eval_eval,serial.correctness]; refl\n\nlemma encode_decode_bind [serial α]\n (f : α → get_m β) (f' : punit → put_m) (w : α) :\n (decode α >>= f) -<< (encode w >>= f') = f w -<< f' punit.star :=\nby { rw [read_write_mono]; rw serial.correctness; refl }\n\nlemma encode_decode_bind' [serial α]\n (f : α → get_m β) (w : α) :\n (decode α >>= f) -<< (encode w) = f w -<< pure punit.star :=\nby { rw [read_write_mono_left]; rw serial.correctness; refl }\n\nlemma encode_decode_pure\n (w w' : α) (u : punit) :\n (pure w : get_m α) -<< (pure u) = pure w' ↔ w = w' :=\nby split; intro h; cases h; refl\n\nopen ulift\n\nprotected def ulift.encode [serial α] (w : ulift.{v} α) : put_m :=\n(liftable1.up _ equiv.punit_equiv_punit (encode (down w) : medium.put_m' unsigned _) : medium.put_m' unsigned _)\n\nprotected def ulift.decode [serial α] : get_m (ulift α) :=\nget_m.up ulift.up (decode α)\n\ninstance [serial α] : serial (ulift.{v u} α) :=\n{ encode := ulift.encode\n, decode := ulift.decode\n, correctness :=\n by { introv, simp [ulift.encode,ulift.decode],\n rw up_read_write' _ equiv.ulift.symm,\n rw [serial.correctness], cases w, refl,\n intro, refl } }\n\ninstance unsigned.serial : serial unsigned :=\n{ encode := λ w, put_m'.write w put_m'.pure\n, decode := get_m.read get_m.pure\n, correctness := by introv; refl }\n\n-- protected def write_word (w : unsigned) : put_m :=\n-- encode (up.{u} w)\n\n@[simp] lemma loop_read_write_word {α β γ : Type u}\n (w : unsigned) (x : α) (f : α → unsigned → get_m (β ⊕ α)) (g : β → get_m γ)\n (rest : punit → put_m) :\n get_m.loop f g x -<< (write_word w >>= rest) =\n (f x w >>= get_m.loop.rest f g) -<< rest punit.star := rfl\n\n@[simp] lemma loop_read_write_word' {α β γ : Type u}\n (w : unsigned) (x : α) (f : α → unsigned → get_m (β ⊕ α)) (g : β → get_m γ) :\n get_m.loop f g x -<< (write_word w) =\n (f x w >>= get_m.loop.rest f g) -<< pure punit.star := rfl\n\n-- protected def read_word : get_m.{u} (ulift unsigned) :=\n-- decode _\n\ndef select_tag' (tag : unsigned) : list (unsigned × get_m α) → get_m α\n| [] := get_m.fail\n| ((w,x) :: xs) := if w = tag then x else select_tag' xs\n\ndef select_tag (xs : list (unsigned × get_m α)) : get_m α :=\ndo w ← read_word,\n select_tag' (down w) xs\n\n@[simp]\nlemma read_write_tag_hit {w w' : unsigned} {x : get_m α}\n {xs : list (unsigned × get_m α)} {y : put_m}\n (h : w = w') :\n select_tag ( (w,x) :: xs ) -<< (write_word w' >> y) = x -<< y :=\nby subst w'; simp [select_tag,(>>),encode_decode_bind,select_tag']\n\nlemma read_write_tag_hit' {w w' : unsigned} {x : get_m α}\n {xs : list (unsigned × get_m α)}\n (h : w = w') :\n select_tag ( (w,x) :: xs ) -<< (write_word w') = x -<< pure punit.star :=\nby subst w'; simp [select_tag,(>>),encode_decode_bind',select_tag']\n\n@[simp]\nlemma read_write_tag_miss {w w' : unsigned} {x : get_m α}\n {xs : list (unsigned × get_m α)} {y : put_m}\n (h : w ≠ w') :\n select_tag ( (w,x) :: xs ) -<< (write_word w' >> y) = select_tag xs -<< (write_word w' >> y) :=\nby simp [select_tag,(>>),encode_decode_bind,select_tag',*]\n\ndef recursive_parser {α} : ℕ → (get_m α → get_m α) → get_m α\n| 0 _ := get_m.fail\n| (nat.succ n) rec_fn := rec_fn $ recursive_parser n rec_fn\n\nlemma recursive_parser_unfold {α} (n : ℕ) (f : get_m α → get_m α) (h : 1 ≤ n) :\n recursive_parser n f = f (recursive_parser (n-1) f) :=\nby cases n; [ cases h, refl ]\n\nattribute [simp] serial.correctness\n\nend serial\n\nstructure serializer (α : Type u) (β : Type u) :=\n(encoder : α → put_m.{u})\n(decoder : get_m β)\n\ndef serial.mk_serializer' (α) [serial α] : serializer α α :=\n{ encoder := encode,\n decoder := decode α }\n\nnamespace serializer\n\ndef valid_serializer {α} (x : serializer α α) :=\nserial_inverse\n (serializer.encoder x)\n (serializer.decoder x)\n\nlemma serializer.eq {α β} (x y : serializer α β)\n (h : x.encoder = y.encoder)\n (h' : x.decoder = y.decoder) :\n x = y :=\nby cases x; cases y; congr; assumption\n\nnamespace serializer.seq\n\nvariables {α : Type u} {i j : Type u}\nvariables (x : serializer α (i → j))\nvariables (y : serializer α i)\n\ndef encoder := λ (k : α), (x.encoder k >> y.encoder k : put_m' _)\ndef decoder := x.decoder <*> y.decoder\n\nend serializer.seq\n\ninstance {α : Type u} : applicative (serializer.{u} α) :=\n{ pure := λ i x, { encoder := λ _, (return punit.star : put_m' _), decoder := pure x }\n, seq := λ i j x y,\n { encoder := serializer.seq.encoder x y\n , decoder := serializer.seq.decoder x y } }\n\nsection lawful_applicative\n\nvariables {α β : Type u} {σ : Type u}\n\n@[simp]\nlemma decoder_pure (x : β) :\n (pure x : serializer σ β).decoder = pure x := rfl\n\n@[simp]\nlemma decoder_map (f : α → β) (x : serializer σ α) :\n (f <$> x).decoder = f <$> x.decoder := rfl\n\n@[simp]\nlemma decoder_seq (f : serializer σ (α → β)) (x : serializer σ α) :\n (f <*> x).decoder = f.decoder <*> x.decoder := rfl\n\n@[simp]\nlemma encoder_pure (x : β) (w : σ) :\n (pure x : serializer σ β).encoder w = (pure punit.star : put_m' _) := rfl\n\n@[simp]\nlemma encoder_map (f : α → β) (w : σ) (x : serializer σ α) :\n (f <$> x : serializer σ β).encoder w = x.encoder w := rfl\n\n@[simp]\nlemma encoder_seq (f : serializer σ (α → β)) (x : serializer σ α) (w : σ) :\n (f <*> x : serializer σ β).encoder w = (f.encoder w >> x.encoder w : put_m' _) := rfl\n\nend lawful_applicative\n\ninstance {α} : is_lawful_functor (serializer.{u} α) :=\nby refine { .. }; intros; apply serializer.eq; try { ext }; simp [map_map]\n\ninstance {α} : is_lawful_applicative (serializer.{u} α) :=\nby{ constructor; intros; apply serializer.eq; try { ext };\n simp [(>>),pure_seq_eq_map,seq_assoc,bind_assoc], }\n\nprotected def up {β} (ser : serializer β β) : serializer (ulift.{u v} β) (ulift.{u v} β) :=\n{ encoder := pliftable.up' _ ∘ ser.encoder ∘ ulift.down,\n decoder := medium.get_m.up ulift.up ser.decoder }\n\ndef ser_field_with {α β} (ser : serializer β β) (f : α → β) : serializer α β :=\n{ encoder := ser.encoder ∘ f,\n decoder := ser.decoder }\n\n@[simp]\ndef ser_field_with' {α β} (ser : serializer β β) (f : α → β) : serializer.{max u v} α (ulift.{v} β) :=\nser_field_with ser.up (ulift.up ∘ f)\n\n@[simp]\ndef ser_field {α β} [serial β] (f : α → β) : serializer α β :=\nser_field_with (serial.mk_serializer' β) f\n\n@[simp]\nlemma valid_mk_serializer (α) [serial α] :\n valid_serializer (serial.mk_serializer' α) :=\nserial.correctness\n\nvariables {α β σ γ : Type u} {ω : Type}\n\ndef there_and_back_again\n (y : serializer γ α) (w : γ) : option α :=\ny.decoder -<< y.encoder w\n\nopen medium (hiding put_m put_m' get_m)\n\nlemma there_and_back_again_seq {ser : serializer α α}\n {x : serializer γ (α → β)} {f : α → β} {y : γ → α} {w : γ} {w' : β}\n (h' : there_and_back_again x w = pure f)\n (h : w' = f (y w))\n (h₀ : valid_serializer ser) :\n there_and_back_again (x <*> ser_field_with ser y) w = pure w' :=\nby { simp [there_and_back_again,(>>),seq_eq_bind_map] at *,\n rw [read_write_mono h',map_read_write],\n rw [ser_field_with,h₀], subst w', refl }\n\nlemma there_and_back_again_map {ser : serializer α α}\n {f : α → β} {y : γ → α} {w : γ}\n (h₀ : valid_serializer ser) :\n there_and_back_again (f <$> ser_field_with ser y) w = pure (f $ y w) :=\nby rw [← pure_seq_eq_map,there_and_back_again_seq]; refl <|> assumption\n\nlemma there_and_back_again_pure (x : β) (w : γ) :\n there_and_back_again (pure x) w =\n pure x := rfl\n\nlemma valid_serializer_of_there_and_back_again\n {α : Type*} (y : serializer α α) :\n valid_serializer y ↔\n ∀ (w : α), there_and_back_again y w = pure w :=\nby { simp [valid_serializer,serial_inverse],\n repeat { rw forall_congr, intro }, refl }\n\n@[simp]\nlemma valid_serializer_up (x: serializer α α) :\n valid_serializer (serializer.up.{v} x) ↔ valid_serializer x :=\nby { cases x, simp [valid_serializer,serializer.up,serial_inverse,equiv.forall_iff_forall equiv.ulift],\n apply forall_congr, intro, dsimp [equiv.ulift,pliftable.up'],\n rw up_read_write' _ equiv.ulift.symm, split; intro h,\n { replace h := congr_arg (liftable1.down.{u} option (equiv.symm equiv.ulift)) h,\n simp [liftable1.down_up] at h, simp [h], refl },\n { simp [h], refl },\n { intro, refl, } }\n\nopen ulift\n\ndef ser_field' {α β} [serial β] (f : α → β) : serializer.{max u v} α (ulift.{v} β) :=\nser_field (up ∘ f)\n\ndef put₀ {α} (x : α) : put_m.{u} := (pure punit.star : put_m' _)\ndef get₀ {α} : get_m α := get_m.fail\n\ndef of_encoder {α} (x : α → put_m) : serializer α α :=\n⟨ x, get₀ ⟩\n\ndef of_decoder {α} (x : get_m α) : serializer α α :=\n⟨ put₀, x ⟩\n\nsection applicative\n\n@[simp]\nlemma encoder_ser_field (f : β → α) (x : serializer α α) (w : β) :\n (ser_field_with x f).encoder w = x.encoder (f w) := rfl\n\n@[simp]\nlemma encoder_up (x : serializer α α) (w : ulift α) :\n (serializer.up x).encoder w = pliftable.up' _ (x.encoder $ w.down) := rfl\n\n@[simp]\nlemma encoder_of_encoder (x : α → put_m) (w : α) :\n (of_encoder x).encoder w = x w := rfl\n\n@[simp]\nlemma decoder_ser_field (f : β → α) (x : serializer α α) :\n (ser_field_with x f).decoder = x.decoder := rfl\n\n@[simp]\nlemma decoder_up (x : serializer α α) :\n (serializer.up x).decoder = (x.decoder).up ulift.up := rfl\n\n@[simp]\nlemma decoder_of_decoder (x : get_m α) :\n (of_decoder x).decoder = x := rfl\n\nend applicative\nend serializer\n\nnamespace serial\n\nopen serializer\n\ndef of_serializer {α} (s : serializer α α)\n (h : ∀ w, there_and_back_again s w = pure w) : serial α :=\n{ encode := s.encoder\n, decode := s.decoder\n, correctness := @h }\n\ndef of_serializer₁ {f : Type u → Type v}\n (s : Π α, serializer α α → serializer (f α) (f α))\n (h : ∀ α ser, valid_serializer ser →\n ∀ w, there_and_back_again (s α ser) w = pure w)\n (h₀ : ∀ {α} ser w, (s α (of_encoder (encoder ser))).encoder w = (s α ser).encoder w)\n (h₁ : ∀ {α} ser, (s α (of_decoder (decoder ser))).decoder = (s α ser).decoder) : serial1 f :=\n{ encode := λ α put, (s α (of_encoder put)).encoder\n, decode := λ α get, (s α (of_decoder get)).decoder\n, correctness := by { introv hh, simp [h₀ ⟨put, get⟩,h₁ ⟨put,get⟩], apply h; assumption } }\n\ndef of_serializer₂ {f : Type u → Type v → Type w}\n (s : Π α β, serializer α α →\n serializer β β →\n serializer (f α β) (f α β))\n (h : ∀ α β serα serβ, valid_serializer serα → valid_serializer serβ →\n ∀ w, there_and_back_again (s α β serα serβ) w = pure w)\n (h₀ : ∀ {α β} serα serβ w, (s α β (of_encoder (encoder serα)) (of_encoder (encoder serβ))).encoder w = (s α β serα serβ).encoder w)\n (h₁ : ∀ {α β} serα serβ, (s α β (of_decoder (decoder serα)) (of_decoder (decoder serβ))).decoder = (s α β serα serβ).decoder) : serial2 f :=\n{ encode := λ α β putα putβ, (s α β (of_encoder putα) (of_encoder putβ)).encoder\n, decode := λ α β getα getβ, (s α β (of_decoder getα) (of_decoder getβ)).decoder\n, correctness := by { introv hα hβ, simp [h₀ ⟨putα,getα⟩ ⟨putβ,getβ⟩,h₁ ⟨putα,getα⟩ ⟨putβ,getβ⟩],\n apply h; assumption } }\n\nend serial\n\nnamespace tactic\nopen interactive\nopen interactive.types\nopen lean.parser\n\nmeta def interactive.mk_serializer (p : parse texpr) : tactic unit :=\ndo g ← mk_mvar,\n refine ``(serial.of_serializer %%p %%g) <|>\n refine ``(serial.of_serializer₁ (λ α ser, %%p) %%g _ _) <|>\n refine ``(serial.of_serializer₂ (λ α β ser_α ser_β, %%p) %%g _ _),\n gs ← get_goals,\n set_goals [g],\n vs ← intros,\n cases vs.ilast,\n iterate $\n applyc ``serializer.there_and_back_again_map <|>\n applyc ``serializer.there_and_back_again_pure <|>\n applyc ``serializer.there_and_back_again_seq,\n gs' ← get_goals,\n set_goals (gs ++ gs'),\n repeat $\n intros >>\n `[simp *] <|>\n reflexivity\n\nend tactic\n", "meta": {"author": "leanprover-community", "repo": "mathlib-nursery", "sha": "0479b31fa5b4d39f41e89b8584c9f5bf5271e8ec", "save_path": "github-repos/lean/leanprover-community-mathlib-nursery", "path": "github-repos/lean/leanprover-community-mathlib-nursery/mathlib-nursery-0479b31fa5b4d39f41e89b8584c9f5bf5271e8ec/src/data/serial/basic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828341018881344, "lm_q2_score": 0.04272219891766974, "lm_q1q2_score": 0.020860540978284617}} {"text": "\nsyntax:1021 term:1021 \"·\" term:1022 : term\nmacro_rules\n | `($a·$f $args*) => `($f $a $args*)\n | `($a·$f) => `($f $a)\n\nexample [Add a] (x y : a) (f : a → b) (g : b → c) (h : c → a) : a := y + x·f·g·h + x·id\n", "meta": {"author": "michelsol", "repo": "lean-playground", "sha": "0bfffb7bd41729fb9f95974e93f6ecbc0b6e59ca", "save_path": "github-repos/lean/michelsol-lean-playground", "path": "github-repos/lean/michelsol-lean-playground/lean-playground-0bfffb7bd41729fb9f95974e93f6ecbc0b6e59ca/Playground/Data/GeneralDotNotation.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.04146227019447842, "lm_q1q2_score": 0.02073113509723921}} {"text": "import Graph.Graph\nimport Graph.UndirectedGraph\nimport Std\n\n/-!\n## Traverse\n-/\n\nnamespace Graph\n\nvariable {α : Type} [Inhabited α] {β : Type}\n\nprivate def depthFirstTraverseAux (g : Graph α β) (visit : Nat -> γ -> γ × Bool) (leave : (Nat -> γ -> γ )) (state : γ) (sources : Array Nat) (visited : Array Bool) : Nat -> γ × Bool × Array Bool\n | 0 => (state, true, #[])\n | n + 1 => Id.run do\n let mut visited := visited\n let mut state := state\n for id in sources do\n if visited[id]! then continue else\n visited := visited.set! id true\n let (newState, terminate?) := visit id state;\n state := newState\n if terminate? then return (leave id state, true, #[]) else\n let adjacencyList := (g.vertices[id]!.adjacencyList.map (λ edge => edge.target)).filter (!visited[.]!)\n let (newState, terminate?, newVisited) := g.depthFirstTraverseAux visit leave state adjacencyList visited n\n visited := newVisited\n state := leave id newState\n if terminate? then return (state, true, #[])\n\n return (state, false, visited)\n\n/-- A depth-first traversal of the graph starting at `sources`. Nodes on the same \"level\" of the traversal are visited in order of the edges added.\n `visit` is a function executed at each vertex, its parameters are the vertex ID and the current state, it should return a new state and\n a boolean which terminates the traversal if true (but it will still leave the node). The optional parameter `leave` is executed when the node is left,\n when all its successors have been visited, uses the same state.\n Please provide a starting state. See example uses in `Graph.TraverseExample`. -/\ndef depthFirstTraverse (g : Graph α β) (sources : Array Nat) (startingState : γ ) (visit : Nat -> γ -> γ × Bool) (leave : Nat -> γ -> γ := (λ _ x => x)) : γ :=\n (g.depthFirstTraverseAux visit leave startingState sources (mkArray g.vertexCount false) (g.vertexCount)).1\n\n/-- A depth-first traversal started from all vertices in order. Each vertex is visited exactly once. See `depthFirstTraverse` for more info. -/\ndef depthFirstCompleteTraverse (g : Graph α β) (startingState : γ ) (visit : Nat -> γ -> γ × Bool) (leave : Nat -> γ -> γ := (λ _ x => x)) : γ :=\n g.depthFirstTraverse g.getAllVertexIDs startingState visit leave\n\nprivate def breadthFirstTraverseAux (g : Graph α β) (visit : Nat -> γ -> γ × Bool) (state : γ) (startingSources : Array Nat) (sources : Array Nat) (visited : Array Bool) : Nat -> γ\n | 0 => state\n | n + 1 => Id.run do\n let mut visited := visited\n let mut state := state\n let mut nextSources : Lean.HashSet Nat := Lean.HashSet.empty\n for id in sources do\n visited := visited.set! id true\n let (newState, terminate?) := visit id state;\n state := newState\n if terminate? then return state else\n let adjacencyList := (g.vertices[id]!.adjacencyList.map (λ edge => edge.target))\n for targetId in adjacencyList do nextSources := nextSources.insert targetId\n\n let sourcesArray : Array Nat := nextSources.fold (λ arr id => if visited[id]! then arr else arr.push id) #[]\n let startingSources := startingSources.filter (!visited[.]!)\n match (sourcesArray.isEmpty, startingSources.isEmpty) with\n | (false, _) => g.breadthFirstTraverseAux visit state startingSources sourcesArray visited n\n | (_, false) => g.breadthFirstTraverseAux visit state startingSources.pop #[startingSources.back] visited n\n | (true, true) => state\n\n/-- A breadth-first traversals of the graph starting at the `sources` in order, sources should not contain duplicates. Each vertex is only visited at most once.\n Nodes on the same \"level\" of the traversal will be visited in random order. If you need the order to be fixed then have a look at `breadthFirstTraverseDeprecated`.\n `visit` is a function executed at each vertex, its parameters are the vertex ID and the current state, it should return a new state and a boolean which terminates\n the traversal if true. Please provide a starting state. `maxDepth` is an optional parameter you can use to limit the depth of the traversal.\n See example uses in `Graph.TraverseExample`. -/\ndef breadthFirstTraverse (g : Graph α β) (sources : Array Nat) (startingState : γ ) (visit : Nat -> γ -> γ × Bool) (maxDepth : Nat := g.vertexCount + sources.size) : γ := Id.run do\n g.breadthFirstTraverseAux visit startingState sources.reverse #[] (mkArray g.vertexCount false) maxDepth\n\n/-- A breadth-first traversal started from all vertices in order. Each vertex is visited exactly once. See `breadthFirstTraverse` for more info. -/\ndef breadthFirstCompleteTraverse (g : Graph α β) (startingState : γ ) (visit : Nat -> γ -> γ × Bool) (maxDepth : Nat := g.vertexCount) : γ :=\n g.breadthFirstTraverse g.getAllVertexIDs startingState visit maxDepth\n\n\nnamespace UndirectedGraph\n\n/-- See directed graph. -/\ndef depthFirstTraverse (ug : UndirectedGraph α β) (sources : Array Nat) (startingState : γ ) (visit : Nat -> γ -> γ × Bool) (leave : Nat -> γ -> γ := (λ _ x => x)) : γ :=\n ug.graph.depthFirstTraverse sources startingState visit leave\n\n/-- See directed graph. -/\ndef depthFirstCompleteTraverse (ug : UndirectedGraph α β) (startingState : γ ) (visit : Nat -> γ -> γ × Bool) (leave : Nat -> γ -> γ := (λ _ x => x)) : γ :=\n ug.graph.depthFirstCompleteTraverse startingState visit leave\n\n/-- See directed graph. -/\ndef breadthFirstTraverse (ug : UndirectedGraph α β) (sources : Array Nat) (startingState : γ ) (visit : Nat -> γ -> γ × Bool) (maxDepth : Nat := ug.vertexCount) : γ :=\n ug.graph.breadthFirstTraverse sources startingState visit maxDepth\n\n/-- See directed graph. -/\ndef breadthFirstCompleteTraverse (ug : UndirectedGraph α β) (startingState : γ ) (visit : Nat -> γ -> γ × Bool) (maxDepth : Nat := ug.vertexCount) : γ :=\n ug.graph.breadthFirstCompleteTraverse startingState visit maxDepth\n\nend UndirectedGraph\nend Graph\n", "meta": {"author": "PeterKementzey", "repo": "graph-library-for-lean4", "sha": "414cdbe1603340a54133edf9b07985f94ceeb26a", "save_path": "github-repos/lean/PeterKementzey-graph-library-for-lean4", "path": "github-repos/lean/PeterKementzey-graph-library-for-lean4/graph-library-for-lean4-414cdbe1603340a54133edf9b07985f94ceeb26a/Graph/Traverse.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4921881357207955, "lm_q2_score": 0.042087729267329864, "lm_q1q2_score": 0.02071508100480865}} {"text": "import GeneralizedRewriting.Algorithm\nimport GeneralizedRewriting.Eauto\n\nsection Examples\n\nvariable (α β γ: Type)\nvariable (Rα: relation α) (Rβ: relation β) (Rγ: relation γ)\nvariable (Pα: α → Prop) (Pβ: β → Prop) (Pγ: γ → Prop)\nvariable (Pαβγ: α → β → Prop)\nvariable (fαβ: α → β) (fβγ: β → γ)\nvariable [Proper_fαβ: Proper (Rα ==> Rβ) fαβ]\nvariable [Proper_Pα: Proper (Rα ==> Iff) Pα]\nvariable [PER Rα] [PER Rβ]\n\nset_option trace.Meta.Tactic.grewrite true\nset_option trace.Meta.Tactic.eauto true\nset_option trace.Meta.Tactic.eauto.hints true\n\n-- Smallest example\nexample (h: Rα a a') (finish: Pα a') : Pα a := by\n grewrite h\n exact finish\n\n-- Rewrite a PER within itself\nexample (h: Rα a a') (finish: Rα a' x) : Rα a x := by\n grewrite h\n exact finish\nexample (h: Rα a a') (finish: Rα x a') : Rα x a := by\n grewrite h\n exact finish\n\n-- Nested function call\nexample (h: Rα a a') (finish: Rβ (fαβ a') x): Rβ (fαβ a) x := by\n grewrite h\n exact finish\n\n-- Multiple occurrences\nexample (h: Rα a a') (finish: Rα a' a'): Rα a a := by\n grewrite h\n exact finish\nexample (h: Rα a a') (finish: Rα a' a): Rα a a := by\n grewrite h at 1\n exact finish\nexample (h: Rα a a') (finish: Rα a a'): Rα a a := by\n grewrite h at 2\n exact finish\nexample (h: Rα a a') (finish: Rα a' a'): Rα a a := by\n grewrite h at -1\n grewrite h at 1\n exact finish\n\n-- More complex selection\nexample (h: Rα a a') (finish: Pα a'): Pα a ∧ Pα a ∧ Pα a ∧ Pα a ∧ Pα a ∧ Pα a := by\n grewrite h at 5\n grewrite h at - 2 4\n grewrite h\n repeat (constructor; assumption)\n assumption\n\nend Examples\n", "meta": {"author": "lephe", "repo": "lean4-rewriting", "sha": "8c66a9112e3114ed5b9ea3f40e978d2cf9548e4f", "save_path": "github-repos/lean/lephe-lean4-rewriting", "path": "github-repos/lean/lephe-lean4-rewriting/lean4-rewriting-8c66a9112e3114ed5b9ea3f40e978d2cf9548e4f/GeneralizedRewriting/TestsGrewrite.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4921881357207956, "lm_q2_score": 0.04208772686428808, "lm_q1q2_score": 0.020715079822059997}} {"text": "/-\nCopyright (c) 2018 Simon Hudon. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Simon Hudon, Patrick Massot\n-/\nimport algebra.group.pi\nimport group_theory.group_action.defs\n\n/-!\n# Pi instances for multiplicative actions\n\n> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.\n> Any changes to this file require a corresponding PR to mathlib4.\n\nThis file defines instances for mul_action and related structures on Pi types.\n\n## See also\n\n* `group_theory.group_action.option`\n* `group_theory.group_action.prod`\n* `group_theory.group_action.sigma`\n* `group_theory.group_action.sum`\n-/\n\nuniverses u v w\nvariable {I : Type u} -- The indexing type\nvariable {f : I → Type v} -- The family of types already equipped with instances\nvariables (x y : Π i, f i) (i : I)\n\nnamespace pi\n\n@[to_additive pi.has_vadd']\ninstance has_smul' {g : I → Type*} [Π i, has_smul (f i) (g i)] :\n has_smul (Π i, f i) (Π i : I, g i) :=\n⟨λ s x, λ i, (s i) • (x i)⟩\n\n@[simp, to_additive]\nlemma smul_apply' {g : I → Type*} [∀ i, has_smul (f i) (g i)] (s : Π i, f i) (x : Π i, g i) :\n (s • x) i = s i • x i :=\nrfl\n\n@[to_additive]\ninstance is_scalar_tower {α β : Type*}\n [has_smul α β] [Π i, has_smul β $ f i] [Π i, has_smul α $ f i]\n [Π i, is_scalar_tower α β (f i)] : is_scalar_tower α β (Π i : I, f i) :=\n⟨λ x y z, funext $ λ i, smul_assoc x y (z i)⟩\n\n@[to_additive]\ninstance is_scalar_tower' {g : I → Type*} {α : Type*}\n [Π i, has_smul α $ f i] [Π i, has_smul (f i) (g i)] [Π i, has_smul α $ g i]\n [Π i, is_scalar_tower α (f i) (g i)] : is_scalar_tower α (Π i : I, f i) (Π i : I, g i) :=\n⟨λ x y z, funext $ λ i, smul_assoc x (y i) (z i)⟩\n\n@[to_additive]\ninstance is_scalar_tower'' {g : I → Type*} {h : I → Type*}\n [Π i, has_smul (f i) (g i)] [Π i, has_smul (g i) (h i)] [Π i, has_smul (f i) (h i)]\n [Π i, is_scalar_tower (f i) (g i) (h i)] : is_scalar_tower (Π i, f i) (Π i, g i) (Π i, h i) :=\n⟨λ x y z, funext $ λ i, smul_assoc (x i) (y i) (z i)⟩\n\n@[to_additive]\ninstance smul_comm_class {α β : Type*}\n [Π i, has_smul α $ f i] [Π i, has_smul β $ f i] [∀ i, smul_comm_class α β (f i)] :\n smul_comm_class α β (Π i : I, f i) :=\n⟨λ x y z, funext $ λ i, smul_comm x y (z i)⟩\n\n@[to_additive]\ninstance smul_comm_class' {g : I → Type*} {α : Type*}\n [Π i, has_smul α $ g i] [Π i, has_smul (f i) (g i)] [∀ i, smul_comm_class α (f i) (g i)] :\n smul_comm_class α (Π i : I, f i) (Π i : I, g i) :=\n⟨λ x y z, funext $ λ i, smul_comm x (y i) (z i)⟩\n\n@[to_additive]\ninstance smul_comm_class'' {g : I → Type*} {h : I → Type*}\n [Π i, has_smul (g i) (h i)] [Π i, has_smul (f i) (h i)]\n [∀ i, smul_comm_class (f i) (g i) (h i)] : smul_comm_class (Π i, f i) (Π i, g i) (Π i, h i) :=\n⟨λ x y z, funext $ λ i, smul_comm (x i) (y i) (z i)⟩\n\n@[to_additive]\ninstance {α : Type*} [Π i, has_smul α $ f i] [Π i, has_smul αᵐᵒᵖ $ f i]\n [∀ i, is_central_scalar α (f i)] : is_central_scalar α (Π i, f i) :=\n⟨λ r m, funext $ λ i, op_smul_eq_smul _ _⟩\n\n/-- If `f i` has a faithful scalar action for a given `i`, then so does `Π i, f i`. This is\nnot an instance as `i` cannot be inferred. -/\n@[to_additive pi.has_faithful_vadd_at \"If `f i` has a faithful additive action for a given `i`, then\nso does `Π i, f i`. This is not an instance as `i` cannot be inferred\"]\nlemma has_faithful_smul_at {α : Type*}\n [Π i, has_smul α $ f i] [Π i, nonempty (f i)] (i : I) [has_faithful_smul α (f i)] :\n has_faithful_smul α (Π i, f i) :=\n⟨λ x y h, eq_of_smul_eq_smul $ λ a : f i, begin\n classical,\n have := congr_fun (h $ function.update (λ j, classical.choice (‹Π i, nonempty (f i)› j)) i a) i,\n simpa using this,\nend⟩\n\n@[to_additive pi.has_faithful_vadd]\ninstance has_faithful_smul {α : Type*}\n [nonempty I] [Π i, has_smul α $ f i] [Π i, nonempty (f i)] [Π i, has_faithful_smul α (f i)] :\n has_faithful_smul α (Π i, f i) :=\nlet ⟨i⟩ := ‹nonempty I› in has_faithful_smul_at i\n\n@[to_additive]\ninstance mul_action (α) {m : monoid α} [Π i, mul_action α $ f i] :\n @mul_action α (Π i : I, f i) m :=\n{ smul := (•),\n mul_smul := λ r s f, funext $ λ i, mul_smul _ _ _,\n one_smul := λ f, funext $ λ i, one_smul α _ }\n\n@[to_additive]\ninstance mul_action' {g : I → Type*} {m : Π i, monoid (f i)} [Π i, mul_action (f i) (g i)] :\n @mul_action (Π i, f i) (Π i : I, g i) (@pi.monoid I f m) :=\n{ smul := (•),\n mul_smul := λ r s f, funext $ λ i, mul_smul _ _ _,\n one_smul := λ f, funext $ λ i, one_smul _ _ }\n\ninstance smul_zero_class (α) {n : ∀ i, has_zero $ f i}\n [∀ i, smul_zero_class α $ f i] :\n @smul_zero_class α (Π i : I, f i) (@pi.has_zero I f n) :=\n{ smul_zero := λ c, funext $ λ i, smul_zero _ }\n\ninstance smul_zero_class' {g : I → Type*} {n : Π i, has_zero $ g i}\n [Π i, smul_zero_class (f i) (g i)] :\n @smul_zero_class (Π i, f i) (Π i : I, g i) (@pi.has_zero I g n) :=\n{ smul_zero := by { intros, ext x, apply smul_zero } }\n\ninstance distrib_smul (α) {n : ∀ i, add_zero_class $ f i} [∀ i, distrib_smul α $ f i] :\n @distrib_smul α (Π i : I, f i) (@pi.add_zero_class I f n) :=\n{ smul_add := λ c f g, funext $ λ i, smul_add _ _ _ }\n\ninstance distrib_smul' {g : I → Type*} {n : Π i, add_zero_class $ g i}\n [Π i, distrib_smul (f i) (g i)] :\n @distrib_smul (Π i, f i) (Π i : I, g i) (@pi.add_zero_class I g n) :=\n{ smul_add := by { intros, ext x, apply smul_add } }\n\ninstance distrib_mul_action (α) {m : monoid α} {n : ∀ i, add_monoid $ f i}\n [∀ i, distrib_mul_action α $ f i] :\n @distrib_mul_action α (Π i : I, f i) m (@pi.add_monoid I f n) :=\n{ ..pi.mul_action _,\n ..pi.distrib_smul _ }\n\ninstance distrib_mul_action' {g : I → Type*} {m : Π i, monoid (f i)} {n : Π i, add_monoid $ g i}\n [Π i, distrib_mul_action (f i) (g i)] :\n @distrib_mul_action (Π i, f i) (Π i : I, g i) (@pi.monoid I f m) (@pi.add_monoid I g n) :=\n{ .. pi.mul_action',\n .. pi.distrib_smul' }\n\nlemma single_smul {α} [monoid α] [Π i, add_monoid $ f i]\n [Π i, distrib_mul_action α $ f i] [decidable_eq I] (i : I) (r : α) (x : f i) :\n single i (r • x) = r • single i x :=\nsingle_op (λ i : I, ((•) r : f i → f i)) (λ j, smul_zero _) _ _\n\n/-- A version of `pi.single_smul` for non-dependent functions. It is useful in cases Lean fails\nto apply `pi.single_smul`. -/\nlemma single_smul' {α β} [monoid α] [add_monoid β]\n [distrib_mul_action α β] [decidable_eq I] (i : I) (r : α) (x : β) :\n single i (r • x) = r • single i x :=\nsingle_smul i r x\n\nlemma single_smul₀ {g : I → Type*} [Π i, monoid_with_zero (f i)] [Π i, add_monoid (g i)]\n [Π i, distrib_mul_action (f i) (g i)] [decidable_eq I] (i : I) (r : f i) (x : g i) :\n single i (r • x) = single i r • single i x :=\nsingle_op₂ (λ i : I, ((•) : f i → g i → g i)) (λ j, smul_zero _) _ _ _\n\ninstance mul_distrib_mul_action (α) {m : monoid α} {n : Π i, monoid $ f i}\n [Π i, mul_distrib_mul_action α $ f i] :\n @mul_distrib_mul_action α (Π i : I, f i) m (@pi.monoid I f n) :=\n{ smul_one := λ c, funext $ λ i, smul_one _,\n smul_mul := λ c f g, funext $ λ i, smul_mul' _ _ _,\n ..pi.mul_action _ }\n\ninstance mul_distrib_mul_action' {g : I → Type*} {m : Π i, monoid (f i)} {n : Π i, monoid $ g i}\n [Π i, mul_distrib_mul_action (f i) (g i)] :\n @mul_distrib_mul_action (Π i, f i) (Π i : I, g i) (@pi.monoid I f m) (@pi.monoid I g n) :=\n{ smul_mul := by { intros, ext x, apply smul_mul' },\n smul_one := by { intros, ext x, apply smul_one } }\n\nend pi\n\nnamespace function\n\n/-- Non-dependent version of `pi.has_smul`. Lean gets confused by the dependent instance if this\nis not present. -/\n@[to_additive \"Non-dependent version of `pi.has_vadd`. Lean gets confused by the dependent instance\nif this is not present.\"]\ninstance has_smul {ι R M : Type*} [has_smul R M] :\n has_smul R (ι → M) :=\npi.has_smul\n\n/-- Non-dependent version of `pi.smul_comm_class`. Lean gets confused by the dependent instance if\nthis is not present. -/\n@[to_additive \"Non-dependent version of `pi.vadd_comm_class`. Lean gets confused by the dependent\ninstance if this is not present.\"]\ninstance smul_comm_class {ι α β M : Type*}\n [has_smul α M] [has_smul β M] [smul_comm_class α β M] :\n smul_comm_class α β (ι → M) :=\npi.smul_comm_class\n\n@[to_additive]\nlemma update_smul {α : Type*} [Π i, has_smul α (f i)] [decidable_eq I]\n (c : α) (f₁ : Π i, f i) (i : I) (x₁ : f i) :\n update (c • f₁) i (c • x₁) = c • update f₁ i x₁ :=\nfunext $ λ j, (apply_update (λ i, (•) c) f₁ i x₁ j).symm\n\nend function\n\nnamespace set\n\n@[to_additive]\nlemma piecewise_smul {α : Type*} [Π i, has_smul α (f i)] (s : set I) [Π i, decidable (i ∈ s)]\n (c : α) (f₁ g₁ : Π i, f i) :\n s.piecewise (c • f₁) (c • g₁) = c • s.piecewise f₁ g₁ :=\ns.piecewise_op _ _ (λ _, (•) c)\n\nend set\n\nsection extend\n\n@[to_additive] lemma function.extend_smul {R α β γ : Type*} [has_smul R γ]\n (r : R) (f : α → β) (g : α → γ) (e : β → γ) :\n function.extend f (r • g) (r • e) = r • function.extend f g e :=\nfunext $ λ _, by convert (apply_dite ((•) r) _ _ _).symm\n\nend extend\n", "meta": {"author": "leanprover-community", "repo": "mathlib", "sha": "5e526d18cea33550268dcbbddcb822d5cde40654", "save_path": "github-repos/lean/leanprover-community-mathlib", "path": "github-repos/lean/leanprover-community-mathlib/mathlib-5e526d18cea33550268dcbbddcb822d5cde40654/src/group_theory/group_action/pi.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.04208772325972563, "lm_q1q2_score": 0.020715078047937124}} {"text": "/-\nCopyright (c) 2019 Jesse Michael Han. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthor(s): Jesse Michael Han \n\nMonadic parsing in Lean, following Hutton-Meijer's 'Monadic Parsing in Haskell` (doi: 10.1017/S0956796898003050).\n\nA related implementation for character buffers, due to Gabriel Ebner, is in data.buffer.\n-/\n\nimport tactic\n\nimport init.data.string\n\nsection miscellany\n\nlemma forall_iff_of_eq {α} {P Q : α → Prop} (h : P = Q) : (∀ x, P x ↔ Q x) :=\nλ _, h ▸ iff_of_eq rfl\n\nlemma mem_cons_iff {α} (xs : list α) (x y : α) : y ∈ (x::xs) ↔ y = x ∨ y ∈ xs :=\n(set.mem_union x (eq y) (λ (x : α), list.mem y xs))\n\nexample {α β} (xs : list α) {x : α} (f : α → β) (H_mem : x ∈ xs) : f x ∈ xs.map f := list.mem_map_of_mem f H_mem\n\nend miscellany\n\nnamespace char\n\nnotation `[]` := list.nil\nnotation h :: t := list.cons h t\nnotation `[` l:(foldr `, ` (h t, list.cons h t) list.nil `]`) := l\n\ninstance : has_zero string := ⟨\"\"⟩\n\nmeta def check_is_valid_char : tactic unit := `[norm_num[is_valid_char]]\n\n/-- char.mk' will automatically attempt to use `check_is_valid_char` to produce the validity certificate -/\ndef mk' (n : ℕ) (H : is_valid_char n . check_is_valid_char) : char :=\nchar.mk n H\n\ndef lower : list char := \"abcdefghijklmnopqrstuvwxyz\".data\n\ndef upper : list char := \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\".data\n\nlemma is_upper_of_mem_upper {c} (H : c ∈ upper) : is_upper c :=\nby {unfold is_upper upper, repeat{cases H, subst H, omega}, cases H }\n\nlemma to_lower_upper_eq_lower : upper.map to_lower = lower := dec_trivial\n\nlemma mem_lower_of_to_lower_upper {c} (H : c ∈ upper) : c.to_lower ∈ lower :=\nby {rw[<-to_lower_upper_eq_lower], exact list.mem_map_of_mem _ ‹_›}\n\ndef lowercase : {c // c ∈ upper} → {c // c ∈ lower} :=\nλ ⟨c,H⟩, ⟨char.to_lower c, mem_lower_of_to_lower_upper H⟩\n\ndef alpha : list char := lower ++ upper\n\ndef numeric : list char := \"0123456789\".data\n\ndef alphanumeric := alpha ++ numeric\n\nsection whitespace_chars\n\ndef cr := mk' 0x0D\n\ndef newline : char := mk' 0x0a\n\ndef space : char := ' '\n\ndef thin_space : char := ' '\n\ndef hair_space : char := ' '\n\ndef no_break_space : char := ' '\n\ndef medium_mathematical_space : char := ' '\n\ndef ideographic_space : char := ' '\n\ndef zero_width_no_break_space := ''\n\ndef zero_width_space := '​'\n\ndef punctuation_space := ' '\n\ndef figure_space := ' '\n\ndef six_per_em_space := ' '\n\ndef four_per_em_space := ' '\n\ndef three_per_em_space := ' '\n\ndef em_space := ' '\n\ndef en_space := ' '\n\ndef em_quad := ' '\n\ndef en_quad := ' '\n\ndef mongolian_vowel_separator := '᠎'\n\ndef ogham_space_mark := ' '\n\ndef tab := char.mk' 0x09\n\ndef narrow_no_break_space := ' '\n\ndef whitespace_chars : list char :=\n [cr,\n newline,\n space,\n thin_space,\n hair_space,\n tab,\n zero_width_space,\n zero_width_no_break_space,\n narrow_no_break_space,\n medium_mathematical_space,\n ideographic_space,\n punctuation_space,\n figure_space,\n six_per_em_space,\n four_per_em_space,\n three_per_em_space,\n em_quad,\n en_quad,\n en_space,\n em_space,\n mongolian_vowel_separator,\n no_break_space]\n\nend whitespace_chars\n\nend char\n\nnamespace string\n\ndef to_lower (arg : string) : string := ⟨arg.data.map char.to_lower⟩\n\ndef reverse (arg : string) : string :=\n⟨arg.data.reverse⟩\n\nend string\n\n@[reducible]meta def parser' := state_t string\n\nmeta def parser_tactic := parser' tactic\n\nnamespace parser_tactic\nsection parser_tactic\nvariables {α : Type}\n\nmeta def mk (run : string → tactic (α × string)) : parser_tactic α :=\nstate_t.mk run\n\nmeta def lift {α} (val : tactic α) : parser_tactic α := state_t.lift val\n\nmeta def run (p : parser_tactic α) : string → tactic (α × string) :=\nstate_t.run p\n\nmeta def result (p : parser_tactic α) (arg : string) : tactic α :=\np.run arg >>= return ∘ prod.fst\n\nmeta def get_result [has_reflect α] (p : parser_tactic α) (arg : string) : tactic unit :=\np.result arg >>= λ x, tactic.exact (reflect x)\n\n/--\n`run parser p arg` runs `p` as if `arg` were the current state.\n\nIt returns the result of p, leaving the actual state unchanged.\n-/\nmeta def run_parser (p : parser_tactic α) : string → parser_tactic α :=\nλ arg, lift (do (a,b) <- p.run arg, return a)\n\nmeta instance monad_parser_tactic : monad parser_tactic :=\nby change _root_.monad (state_t _ _); apply_instance\n\nmeta instance alternative_parser_tactic : alternative parser_tactic :=\nby change _root_.alternative (state_t _ _); apply_instance\n\nmeta instance : has_append (parser_tactic string) :=\n⟨λ p₁ p₂, do a <- p₁, b <- p₂, return $ a ++ b⟩ \n\nmeta def fail : parser_tactic α := parser_tactic.mk $ λ _, tactic.failed\n\nmeta def trace_state : parser_tactic unit :=\nparser_tactic.mk $ λ str, tactic.trace str >> return ((), str)\n\nmeta def get_state : parser_tactic string :=\nstate_t.get\n\nmeta def put_state : string -> parser_tactic unit :=\nλ arg, state_t.put arg\n\nmeta def modify_state : (string -> string) -> parser_tactic unit :=\nλ m, state_t.modify m\n\nmeta def prepend_state : string -> parser_tactic unit :=\nλ arg, modify_state (λ σ, arg ++ σ)\n\nmeta def append_state : string -> parser_tactic unit :=\nλ arg, modify_state (λ σ, σ ++ arg)\n\nmeta def run_parser' (p : parser_tactic α) : parser_tactic string → parser_tactic α :=\nλ q, q >>= run_parser p\n\nmeta def skip : parser_tactic unit :=\nparser_tactic.mk $ λ str, return ((), str)\n\nmeta def trace (msg : string) : parser_tactic unit :=\nparser_tactic.mk $ λ str, tactic.trace msg >> return ((), str)\n\nmeta def try_core (p : parser_tactic α) : parser_tactic (option α) :=\nmk $ (λ arg, do r <- tactic.try_core (p.run arg),\n match r with\n | none := return (none, arg)\n | (some x) := return (some x.1, x.2)\n end)\n\nmeta def try (p : parser_tactic α) : parser_tactic unit :=\ntry_core p >>= λ r, match r with\n | none := skip\n | some x := return ()\n end\n\nmeta def to_tactic (p : parser_tactic α) : string → tactic α :=\nλ arg, (p.run arg) >>= return ∘ prod.fst\n\nmeta instance : has_coe (parser_tactic α) (string → tactic α) :=\n⟨to_tactic⟩\n\nmeta def parser_tactic_format {α} [H : has_to_format α] : α × string → format :=\nλ ⟨r,σ⟩,\n format.line ++ (\"Result:\") ++\n format.line ++ format.line ++ (format.nest 5 $ to_fmt r) ++\n format.line ++ format.line ++\n \"──────────────────────────────────────\" ++\n format.line ++ format.line ++ (\"State:\") ++\n format.line ++ format.line ++ (format.nest 5 $ to_fmt σ)\n\n/-- For testing parsers on strings -/\nmeta def run' {α} [has_to_format α] (p : parser_tactic α) (arg : string) : tactic unit :=\n p.run arg >>= λ fmt, return $ _root_.trace_fmt (parser_tactic_format fmt) (λ _, ())\n\nend parser_tactic\nend parser_tactic\n\nopen parser_tactic\n\nnamespace parser_tactic\n\nmeta def item : parser_tactic char :=\nparser_tactic.mk $ λ str,\n match str with\n | ⟨[]⟩ := tactic.failed\n | ⟨(x::xs)⟩ := return (x, ⟨xs⟩)\n end\n\nmeta def eof : parser_tactic unit :=\nparser_tactic.mk $ λ str,\n match str with\n | ⟨[]⟩ := return ⟨(), str⟩\n | ⟨(x::xs)⟩ := tactic.failed\n end\n\n/--\n`item0` is like `item`, but does not consume anything (leaves the state unchanged).\n-/\nmeta def item0 : parser_tactic char :=\nparser_tactic.mk $ λ str,\n match str with\n | ⟨[]⟩ := tactic.failed\n | ⟨(x::xs)⟩ := return (x, ⟨x::xs⟩)\n end\n\nmeta def to_string : parser_tactic char → parser_tactic string :=\nλ p, do x <- p, return x.to_string\n\nmeta def to_string' : parser_tactic (list char) → parser_tactic string :=\nλ p, do x <- p, return $ string_imp.mk x\n\nmeta instance parser_to_string : has_coe (parser_tactic (char)) (parser_tactic string) :=\n⟨to_string⟩\n\nmeta instance list_char_coe : has_coe (parser_tactic (list char)) (parser_tactic string) :=\n⟨to_string'⟩\n\nmeta def sat (P : char → Prop) [decidable_pred P] : parser_tactic char :=\nitem >>= λ x, (if P x then return x else fail)\n\nsection eq_any\nvariables {α : Type*} [decidable_eq α]\n\ndef eq_any (cs : list α) : α → Prop :=\nλ c, cs.foldr (λ x, λ b, (= c) x ⊔ b) ⊥ \n\n@[simp]lemma eq_any_cons {c : α} {cs} : eq_any (c::cs) = λ x, c = x ∨ eq_any cs x := rfl\n\ninstance eq_any_decidable_pred : ∀ {cs : list α}, decidable_pred (eq_any cs) :=\nbegin\n intro cs, induction cs with c cs ih, unfold eq_any, tidy, apply_instance,\n intro x, haveI : decidable (eq_any cs x) := by apply ih,\n by_cases c = x,\n { exact decidable.is_true (by simp*) },\n { by_cases (eq_any cs x),\n { simp*, apply_instance },\n { simp*, apply_instance }}\nend\n\n/- note: we'll never need this, but it's basically free -/\ndef eq_all (cs : list α) : α → Prop :=\nλ c, cs.foldr (λ x, λ b, (= c) x ⊓ b) ⊤\n\n@[simp]lemma eq_all_cons {c : α} {cs} : eq_all (c::cs) = λ x, c = x ∧ eq_all cs x := rfl\n\ninstance eq_all_decidable_pred : ∀ {cs : list α}, decidable_pred (eq_all cs) :=\nbegin\n intro cs, induction cs with c cs ih, unfold eq_all, tidy, apply_instance,\n intro x, haveI : decidable (eq_all cs x) := by apply ih,\n by_cases c = x,\n { by_cases (eq_all cs x),\n { simp*, apply_instance },\n { simp*, apply_instance }},\n { exact decidable.is_false (by simp*) }\nend\n\nend eq_any\n\nmeta def ch (c : char) : parser_tactic char := sat (= c)\n\nmeta def chs (cs : list char) : parser_tactic char := sat (eq_any cs)\n\nmeta def not_chs (cs : list char) : parser_tactic char := sat (λ c, ¬ eq_any cs c)\n\nmeta def not_ch (c : char) : parser_tactic char := not_chs $ [c]\n\nmeta def str : string → parser_tactic string\n| ⟨[]⟩ := pure \"\"\n| ⟨x::xs⟩ := do y <- ch x,\n z <- str ⟨xs⟩,\n return $ y.to_string ++ z\n\nmeta def nil_if_fail {α} : parser_tactic α → parser_tactic (list α) := \nλ p, (p >>= return ∘ return) <|> return []\n\nmeta def fail_if_nil : parser_tactic string → parser_tactic string :=\nλ p, do x <- p, guard (x ≠ \"\"), return x\n\nmeta def fail_if_nil' {α} [decidable_eq α] : parser_tactic (list α) → parser_tactic (list α) :=\nλ p, do x <- p, guard (x ≠ []), return x\n\nmeta def fail_if_state_nil {α} (p : parser_tactic α) : parser_tactic α :=\n(get_state >>= λ arg, guard (arg ≠ \"\")) >> p\n\nmeta def list.mcons {m} [monad m] {α} (x : α) (xs : list α) : m (list α) :=\nreturn (x::xs)\n\nmeta def repeat {α} (p : parser_tactic α) : parser_tactic (list α) :=\n(do a <- p,\n as <- repeat,\n return (a::as)) <|> return []\n\nmeta def repeat1 {α : Type} : parser_tactic α → parser_tactic (list α) :=\nλ p, list.cons <$> p <*> repeat p\n\n/--\n`succeeds' p` runs p, but does not change the state even if p succeeds.\n-/\nmeta def succeeds' {α} (p : parser_tactic α) : parser_tactic bool :=\nsucceeds $ get_state >>= (run_parser p)\n\nmeta def fail_iff_succeeds {α} (p : parser_tactic α) : parser_tactic unit :=\nsucceeds' p >>= λ b, ite b fail skip\n\n/--\n`until p q` runs q until p succeeds, and returns the result of p and all the results of q\n-/\nmeta def until {α β} (p : parser_tactic α) (q : parser_tactic β) : parser_tactic (α × list β) :=\n repeat (fail_iff_succeeds p *> q) >>= λ _, prod.mk <$> p <*> return ‹_›\n\n/--\n`until' p q` runs q until p succeeds, and returns the result of p\n-/\nmeta def until' {α β} (p : parser_tactic α) (q : parser_tactic β) : parser_tactic α :=\nprod.fst <$> until p q\n\n/--\n`until'' p q` runs q until p succeeds, and returns all results of q\n-/ \nmeta def until'' {α β} (p : parser_tactic α) (q : parser_tactic β) : parser_tactic (list β) :=\nprod.snd <$> until p q\n\n/--\n`lookahead arg` succeeds if and only if `arg` is a substring of the current state\n-/\nmeta def lookahead (arg : string) : parser_tactic bool :=\nsucceeds' $ until' (str arg) item\n\nrun_cmd (lookahead \"foo\").run' \"abcfoode\"\n/--\n`not_str arg` consumes and returns the longest prefix which does not match `arg`.\n-/\nmeta def not_str : string → parser_tactic string := λ arg,\nuntil'' (str arg) item\n\nmeta def not_strs : list string → parser_tactic string := λ arg,\nrepeat $ succeeds (list.mfirst str arg) >>= (λ b, if b then fail else item)\n\nmeta def sepby_aux {α β} : parser_tactic α → parser_tactic β → parser_tactic (list α) :=\nλ p sep,\n list.cons <$> p <*> repeat (sep *> p)\n\nmeta def sepby {α β} : parser_tactic α → parser_tactic β → parser_tactic (list α) :=\nλ p sep,\n (sepby_aux p sep) <|> return []\n\n/-\nThe choice operator (++) from Hutton-Meijer does not have a direct analogue in this framework, since we use `tactic` as the monad instead of `list`.\n\nHowever, the deterministic choice operator (+++):\n1. fails iff both p and q fail\n2. if p succeeds, returns the result of p\n3. if p fails, runs q\n\nand therefore (+++) is emulated by the orelse (<|>) combinator.\n-/\n\n/-\nc.f. Hutton-Meijer:\n\nchainl :: Parser a -> Parser (a -> a -> a) -> a -> Parser a\nchainl p op a = (p ‘chainl1‘ op) +++ return a\n\nchainl1 :: Parser a -> Parser (a -> a -> a) -> Parser a\np ‘chainl1‘ op = do {a <- p; rest a}\n where\n rest a = (do f <- op\n b <- p\n rest (f a b))\n +++ return a\n-/\n\nmeta def chainl_rest {α} (p : parser_tactic α) (op : parser_tactic (α → α → α)) : α → parser_tactic α :=\nλ a,\n (do f <- op,\n b <- p,\n chainl_rest (f a b)) <|> return a\n\nmeta def chainl1 {α} (p : parser_tactic α) (op : parser_tactic (α → α → α)) : parser_tactic α :=\ndo a <- p, chainl_rest p op a\n\nmeta def chainl {α} : parser_tactic α → parser_tactic (α → α → α) → α → parser_tactic α :=\nλ p op a, (chainl1 p op) <|> return a\n\nmeta def chainr_rest {α} (p : parser_tactic α) (op : parser_tactic (α → α → α)) : α → parser_tactic α :=\nλ a,\n (do f <- op,\n b <- p,\n chainr_rest (f b a)) <|> return a\n\nmeta def chainr1 {α} (p : parser_tactic α) (op : parser_tactic (α → α → α)) : parser_tactic α :=\ndo a <- p, chainr_rest p op a\n\nmeta def chainr {α} : parser_tactic α → parser_tactic (α → α → α) → α → parser_tactic α :=\nλ p op a, (chainr1 p op) <|> return a\n\n/- Lexical combinators -/\n\nmeta def space : parser_tactic string := repeat (sat (= ' '))\n\nmeta def whitespace : parser_tactic string := repeat (chs char.whitespace_chars)\n\nmeta def not_whitespace : parser_tactic string := fail_if_nil $ repeat (not_chs char.whitespace_chars)\n\n/-- `token p` runs p, then consumes as many spaces as possible before discarding them. -/\nmeta def token {α} (p : parser_tactic α) : parser_tactic α := p <* space\n\n/-- `token' p runs p, then consumes as much whitespace as possible before discarding it. -/\nmeta def token' {α} (p : parser_tactic α) : parser_tactic α := p <* whitespace\n\nmeta def symb : string → parser_tactic string := token ∘ str\n\n/-- An alphanumeric token is a string of alphanumeric characters which must begin with an alpha character. -/\nmeta def alphanumeric_token : parser_tactic string :=\n(string.append <$> (sat char.is_alpha) <*> (repeat (sat char.is_alphanum))) <* whitespace\n\nmeta def digit : parser_tactic char := chs char.numeric\n\ndef from_base_10_aux : ℕ → list ℕ → ℕ\n| _ [] := 0\n| 0 (x::xs) := x\n| (n+1) (x::xs) := (10^n) * x + from_base_10_aux n xs\n\ndef from_base_10 : list ℕ → ℕ := λ xs, from_base_10_aux xs.length xs\n\nmeta def digit' : parser_tactic ℕ :=\ndo x <- digit,\n if (x = '0') then return 0 else\n if (x = '1') then return 1 else\n if (x = '2') then return 2 else\n if (x = '3') then return 3 else\n if (x = '4') then return 4 else\n if (x = '5') then return 5 else\n if (x = '6') then return 6 else\n if (x = '7') then return 7 else\n if (x = '8') then return 8 else\n if (x = '9') then return 9 else\n fail\n\nmeta def number' : parser_tactic ℕ := (repeat digit') >>= return ∘ from_base_10\n\nmeta def number : parser_tactic ℕ := (fail_if_nil' (repeat digit')) >>= return ∘ from_base_10\n\n/--\n`delimiter_aux arg_left arg_right k` believes that it has passed `k` copies of `arg_left`, and is expecting `k` copies of `arg_right`.\n\nUpon encountering a copy of `arg_right`, it calls itself, decrementing the counter by 1.\n\nIf it never encounters an opening `arg_left`, it returns the empty string.\n-/\n\n/-\nrunning delimiter on (foo (bar )) baz produces (foo (bar )).\n-/\n/-\nTODO(jesse) refactor this to consume extra characters to the right instead of left\n-/\nmeta def delimiter_aux (arg_left : string) (arg_right : string) : Π k : ℕ, parser_tactic string\n| 0 := (not_str arg_left ++ str arg_left ++ delimiter_aux 1)\n <|> return \"\"\n| (k + 1) := (not_str arg_left ++ str arg_left ++ delimiter_aux (k + 2))\n <|> ((not_str arg_right) ++ str arg_right) ++ delimiter_aux k\n\n/-- `delimiter arg_left arg_right parses the delimiters, then returns their interior as a string -/\nmeta def delimiter (arg_left arg_right : string) : parser_tactic string :=\ndelimiter_aux arg_left arg_right 0\n\n/--\n`delimiter' p arg_right arg_left` parses the delimiters, then runs p on their interior.\n-/\nmeta def delimiter' {α} (p : parser_tactic α) (arg_right) (arg_left) : parser_tactic α :=\ndelimiter arg_right arg_left >>= p.run_parser\n\nmeta def delimiter'' (arg_left arg_right : string) : parser_tactic string :=\ndo r <- (delimiter arg_left arg_right),\n r' <- run_parser (symb arg_left >> get_state) r,\n run_parser ((symb arg_right.reverse) >> get_state >>= return ∘ string.reverse) r'.reverse\n\nmeta def between (arg_left arg_right : string) : parser_tactic string :=\n (str arg_left ++ not_strs [arg_left, arg_right] ++ (between <|> return \"\") ++ not_strs [arg_left, arg_right] ++ str arg_right)\n\nmeta def apply {α} (p : parser_tactic α) : string → tactic (α × string) := (space *> p).run\n\n--TODO(jesse) fix this so it also consumes the corresponding prefix of the actual state\nmeta def case_insensitive (p : string → parser_tactic string) : string → parser_tactic string :=\nλ arg, do s <- get_state, run_parser (p arg.to_lower) s.to_lower\n\n-- section parse_fol\n-- open fol\n\n-- meta instance {k} : has_to_tactic_format (preformula L_empty k) :=\n-- ⟨begin intro f, have := (reflected.has_to_tactic_format f).1 ,\n-- apply this, apply_instance end⟩\n\n-- meta def parse_preformula_aux : parser_tactic (preformula L_empty 0) :=\n-- token' (str \"∀\") >> parse_preformula_aux >>= (λ x, return (preformula.all x)) <|>\n-- (repeat item) *> return (&0 ≃ &0)\n\n-- -- as vars are encountered, they are pushed onto the stack\n-- -- the de Bruijn index assigned to an encountered free variable is its position in the stack.\n-- -- a named variable is captured by the nearest quantifier with the same name\n\n-- meta structure formula_state (k : ℕ) :=\n-- (bound_var : list name)\n-- (free_var : list name)\n-- (result : preformula L_empty k)\n\n-- #check formula_state.mk\n\n-- -- meta def formula_state.var {k : ℕ} (σ : formula_state k) : tactic (list name) :=\n-- -- σ.bound_var >>= (λ x, (σ.free_var >>= (λ y, return (x ++ y))))\n\n-- meta def parse_preformula {k : ℕ} (σ : formula_state k) : parser_tactic (formula_state 0) :=\n-- do token' (str \"∀\"),\n-- v <- (alphanumeric_token),\n-- let foo := ℕ in\n-- return (formula_state.mk (σ.bound_var ++ [v]) (σ.free_var) foo )\n-- -- TODO(jesse) finish this\n\n-- -- @formula_state.mk 0 (σ.bound_var.append ([↑v] : list _)) σ.free_var (parse_preformula >>= _\n\n-- -- meta def parse_preformula : parser_tactic (Σk, preformula L_empty k) :=\n-- -- do token' (str \"∀\") >> (parse_preformula >>= λ x, return ⟨x.fst, x.2⟩)\n\n-- -- run_cmd run' parse_preformula_aux \"∀ ∀ ∀ ∀ foo\"\n\n-- -- fol.preterm.var : Π {L : Language}, ℕ → preterm L 0\n-- -- fol.preterm.func : Π {L : Language} {l : ℕ}, L.functions l → preterm L l\n-- -- fol.preterm.app : Π {L : Language} {l : ℕ}, preterm L (l + 1) → preterm L 0 → preterm L l\n\n-- -- fol.preformula.falsum : Π {L : Language}, preformula L 0\n-- -- fol.preformula.equal : Π {L : Language}, term L → term L → preformula L 0\n-- -- fol.preformula.rel : Π {L : Language} {l : ℕ}, L.relations l → preformula L l\n-- -- fol.preformula.apprel : Π {L : Language} {l : ℕ}, preformula L (l + 1) → term L → preformula L l\n-- -- fol.preformula.imp : Π {L : Language}, preformula L 0 → preformula L 0 → preformula L 0\n-- -- fol.preformula.all : Π {L : Language}, preformula L 0 → preformula L 0\n\n-- -- ∀ x, x = x ∧ (f x y = 3)\n\n-- meta def parse_eq : parser_tactic $ term L_empty → term L_empty → preformula L_empty 0 :=\n-- (token (ch '=' >> return preformula.equal))\n\n-- meta def parser_var : parser_tactic $ sorry := sorry\n\n-- meta def parse_preterm {k} : parser_tactic (preterm L_empty k) := sorry\n\n-- meta def parse_preformula {k} : parser_tactic (preformula L_empty k) := sorry\n\n-- end parse_fol\n\nsection tests\n\nrun_cmd (until' (str \"bar\") item : parser_tactic string).run' \"foo bar baz\"\n\nrun_cmd (str \"foobar\" <* eof).run' \"foobar\"\n\nrun_cmd (fail_if_nil $ str \"h\").run' \"hewwo\" -- succeeds as it should\n\n-- run_cmd (fail_if_nil $ str \"\").run' \"hewwo\" -- fails as it should\n\n-- run_cmd run' (fail_if_state_nil $ skip) \"\" -- fails as it should\n\nrun_cmd (sepby (str \"a\" <|> str \"b\") (str \",\")).run' \"a,b,c,d\"\n\nrun_cmd run' (fail_if_state_nil $ skip) \"foo\" -- succeeds as it should\n\nrun_cmd run' (delimiter \"(\" \")\") \"(1 + 2) + 3\"\n\nrun_cmd run' (delimiter \"[\" \"]\") \"[a + b + [c + d] + [e + [f]]] + 3\"\n\nrun_cmd run' (delimiter \"[\" \"]\") \"[]] + 3\"\n\nrun_cmd run' (delimiter \"[\" \"]\") \"[1 + 2 + 3\" -- returns nothing as it should\n\nrun_cmd run' (delimiter \"[\" \"]\") \"[a + b + [c + d] + [e + [f]]] + 3\"\n\nrun_cmd run' (not_str \"HEWWO\") \"DUH HEWWO\"\n\nrun_cmd run' (repeat alphanumeric_token) \"a1 a3 b3 b4 x12 xasd1\"\n\nrun_cmd run' (token $ (str \"foo\")) \"foo bar\"\n\nrun_cmd run' (sepby (str \"foo\") (str \" \")) \"foo foo foo foo\"\n\nrun_cmd run' (repeat (str \"foo\")) \"barfoofoobarbarbarfoo\"\n\n-- run_cmd run' (repeat1 (str \"foo\")) \"barfoofoobarbarbarfoo\" -- fails as it should\n\nrun_cmd run' (repeat1 (str \"foo\")) \"foofoofoobarbarbarfoo\" \n\nrun_cmd run' (str \"foo\") \"foobarbaz\" -- (foo, barbaz)\n\nrun_cmd run' (repeat1 $ fail_if_nil $ token $ not_whitespace) \"foo₁ foo₂ foo₃ foo₄ foo₅\"\n\nrun_cmd (repeat $ str \"a\" <|> str \"b\").run' \"bbababbaabaaaa\" -- if one branch fails, the state is unchanged and passed to the other branch\n\nend tests\n\nend parser_tactic\n\nopen parser_tactic\n\nnamespace arith_expr\n\nsection arith_expr\n\nopen arith_expr\n\nmeta def parse_number (arg : string) : tactic unit :=\ndo n <- number'.to_tactic arg,\n tactic.exact `(n)\n\nmutual inductive addop,mulop,digit,factor,term,expr\nwith addop : Type\n | plus : addop\n | minus : addop\nwith mulop : Type\n | mult : mulop\n | div : mulop\nwith digit : Type\n | zero : digit\n | one : digit\n | two : digit\n | three : digit\n | four : digit\n | five : digit\n | six : digit\n | seven : digit\n | eight : digit\n | nine : digit\nwith factor : Type\n | of_digit : digit → factor\n | of_expr : expr → factor\nwith term : Type\n | of_factor : factor → term\n | of_mulop : mulop → term → factor → term\nwith expr : Type\n | of_term : term → expr\n | of_addop : addop → expr → term → expr\n\ndef term.of_digit := term.of_factor ∘ factor.of_digit\n\ndef expr.of_digit := expr.of_term ∘ term.of_digit\n\nmeta mutual def eval_addop,eval_mulop,eval_digit,eval_factor,eval_term,eval_expr\nwith eval_addop : addop → ℕ → ℕ → ℕ\n | addop.plus := (nat.add)\n | addop.minus := (nat.sub)\nwith eval_mulop : mulop → ℕ → ℕ → ℕ\n | mulop.mult := (nat.mul)\n | mulop.div := (nat.div)\nwith eval_digit : digit → ℕ\n | digit.zero := 0\n | digit.one := 1\n | digit.two := 2\n | digit.three := 3\n | digit.four := 4\n | digit.five := 5\n | digit.six := 6\n | digit.seven := 7\n | digit.eight := 8\n | digit.nine := 9\nwith eval_factor : factor → ℕ\n | (factor.of_digit k) := eval_digit k \n | (factor.of_expr e) := eval_expr e\nwith eval_term : term → ℕ\n | (term.of_factor f) := eval_factor f\n | (term.of_mulop op t f) := (eval_mulop op) (eval_term t) (eval_factor f)\nwith eval_expr : expr → ℕ\n | (expr.of_term t) := eval_term t\n | (expr.of_addop op e t) := (eval_addop op) (eval_expr e) (eval_term t)\n\nmeta def nat.to_fmt : ℕ → format := nat.has_to_format.to_format\n\nmeta instance format_digit : has_to_format digit :=\n⟨λ x, nat.to_fmt (eval_digit x)⟩\n\nmeta instance format_factor : has_to_format factor :=\n⟨λ x, nat.to_fmt (eval_factor x)⟩\n\nmeta instance format_term : has_to_format term :=\n⟨λ x, nat.to_fmt (eval_term x)⟩\n\nmeta instance format_expr : has_to_format expr := \n⟨λ x, nat.to_fmt (eval_expr x)⟩\n\n\n\nmeta mutual def parse_addop,parse_mulop,parse_digit,parse_factor,parse_term,parse_expr\nwith parse_addop : string → tactic (addop × string)\n| arg := (token (str \"+\" >> return addop.plus <|> str \"-\" >> return addop.minus)).run arg\nwith parse_mulop : string → tactic (mulop × string)\n| arg := (token (str \"*\" >> return mulop.mult <|> str \"/\" >> return mulop.div)).run arg\nwith parse_digit : string → tactic (digit × string)\n| arg := (token $ trace \"HEWWO\" >> trace_state >> do x <- parser_tactic.digit,\n trace $ x.to_string ++ \" WAS THE DIGIT I PARSED\",\n if (x = '0') then return digit.zero else\n if (x = '1') then return digit.one else\n if (x = '2') then return digit.two else\n if (x = '3') then return digit.three else\n if (x = '4') then return digit.four else\n if (x = '5') then return digit.five else\n if (x = '6') then return digit.six else\n if (x = '7') then return digit.seven else\n if (x = '8') then return digit.eight else\n if (x = '9') then return digit.nine else\n fail).run arg\nwith parse_factor : string → tactic (factor × string)\n| arg := (fail_if_state_nil $ (trace \"hello\" >> (token $ (mk parse_digit) >>= return ∘ factor.of_digit <|> (mk parse_expr) >>= return ∘ factor.of_expr))).run arg\nwith parse_term : string → tactic (term × string)\n| arg := (token $\n (do\n trace \"hola\",\n b <- succeeds' (do not_str \"*\" >> str \"*\"),\n if b then (do t <- (mk parse_term),\n op <- (mk parse_mulop),\n f <- (mk parse_factor),\n return $ term.of_mulop op t f)\n else (mk parse_factor) >>= return ∘ term.of_factor\n -- e <- (mk parse_expr),\n -- op <- (mk parse_addop),\n -- t <- (mk parse_term),\n -- return $ expr.of_addop op e t\n )).run arg\nwith parse_expr : string → tactic (expr × string)\n| arg := (token $\n (do\n trace \"bonjour\",\n b <- succeeds' (do not_str \"+\" >> str \"+\"),\n if b then -- return (expr.of_digit digit.one)\n (do p <- not_str \"+\",\n e <- (mk parse_expr).run_parser p,\n op <- (mk parse_addop),\n t <- (mk parse_term),\n return $ expr.of_addop op e t)\n else (mk parse_term) >>= return ∘ expr.of_term\n -- e <- (mk parse_expr),\n -- op <- (mk parse_addop),\n -- t <- (mk parse_term),\n -- return $ expr.of_addop op e t\n )\n ).run arg\n\nmeta def parse_arith_expr : parser_tactic expr := mk parse_expr\n\nrun_cmd (mk parse_expr).run' \"9 + 1 + 1\"\n\n-- run_cmd (parse_arith_expr >> parse_arith_expr).run' \"1\"\n\n-- run_cmd (\n-- do b <- succeeds' (do not_str \"+\" >> str \"+\"),\n-- trace_state,\n-- if b then (do d₁ <- (mk parse_digit),\n-- op <- (mk parse_addop),\n-- d₂ <- (mk parse_digit),\n-- return $ expr.of_addop op (expr.of_digit d₁) (term.of_digit d₂)\n\n-- )\n-- else (mk parse_digit) >>= return ∘ expr.of_digit\n\n\n-- ).run' \"8 + 7\"\n\nend arith_expr\n\nend arith_expr\n\nnamespace calculator\n\n\nsection calculator\n\nopen calculator\n\ndef from_base_10_aux : ℕ → list ℤ → ℤ\n| _ [] := 0\n| 0 (x::xs) := x\n| (n+1) (x::xs) := (10^n) * x + from_base_10_aux n xs\n\ndef from_base_10 : list ℤ → ℤ := λ xs, from_base_10_aux xs.length xs\n\nmeta def digit' : parser_tactic ℤ :=\ndo x <- digit,\n if (x = '0') then return 0 else\n if (x = '1') then return 1 else\n if (x = '2') then return 2 else\n if (x = '3') then return 3 else\n if (x = '4') then return 4 else\n if (x = '5') then return 5 else\n if (x = '6') then return 6 else\n if (x = '7') then return 7 else\n if (x = '8') then return 8 else\n if (x = '9') then return 9 else\n fail\n\nmeta def number : parser_tactic ℤ := (repeat digit') >>= return ∘ from_base_10\n\nmeta def parse_number (arg : string) : tactic unit :=\ndo n <- number.to_tactic arg,\n tactic.exact `(n)\n\nmutual inductive addop,mulop,digit,factor,term,expr\nwith addop : Type\n | plus : addop\n | minus : addop\nwith mulop : Type\n | mult : mulop\n | div : mulop\nwith digit : Type\n | zero : digit\n | one : digit\n | two : digit\n | three : digit\n | four : digit\n | five : digit\n | six : digit\n | seven : digit\n | eight : digit\n | nine : digit\nwith factor : Type\n | of_digit : digit → factor\n | of_expr : expr → factor\nwith term : Type\n | of_factor : factor → term\n | of_mulop : mulop → term → factor → term\nwith expr : Type\n | of_term : term → expr\n | of_addop : addop → expr → term → expr\n\ndef term.of_digit := term.of_factor ∘ factor.of_digit\n\ndef expr.of_digit := expr.of_term ∘ term.of_digit\n\nmeta mutual def eval_addop,eval_mulop,eval_digit,eval_factor,eval_term,eval_expr\nwith eval_addop : addop → ℕ → ℕ → ℕ\n | addop.plus := (nat.add)\n | addop.minus := (nat.sub)\nwith eval_mulop : mulop → ℕ → ℕ → ℕ\n | mulop.mult := (nat.mul)\n | mulop.div := (nat.div)\nwith eval_digit : digit → ℕ\n | digit.zero := 0\n | digit.one := 1\n | digit.two := 2\n | digit.three := 3\n | digit.four := 4\n | digit.five := 5\n | digit.six := 6\n | digit.seven := 7\n | digit.eight := 8\n | digit.nine := 9\nwith eval_factor : factor → ℕ\n | (factor.of_digit k) := eval_digit k \n | (factor.of_expr e) := eval_expr e\nwith eval_term : term → ℕ\n | (term.of_factor f) := eval_factor f\n | (term.of_mulop op t f) := (eval_mulop op) (eval_term t) (eval_factor f)\nwith eval_expr : expr → ℕ\n | (expr.of_term t) := eval_term t\n | (expr.of_addop op e t) := (eval_addop op) (eval_expr e) (eval_term t)\n\nmeta def nat.to_fmt : ℕ → format := nat.has_to_format.to_format\n\nmeta instance format_digit : has_to_format digit :=\n⟨λ x, nat.to_fmt (eval_digit x)⟩\n\nmeta instance format_factor : has_to_format factor :=\n⟨λ x, nat.to_fmt (eval_factor x)⟩\n\nmeta instance format_term : has_to_format term :=\n⟨λ x, nat.to_fmt (eval_term x)⟩\n\nmeta instance format_expr : has_to_format expr := \n⟨λ x, nat.to_fmt (eval_expr x)⟩\n\n/-\nc.f. Hutton-Meijer:\n\nexpr :: Parser Int\naddop :: Parser (Int -> Int -> Int)\nmulop :: Parser (Int -> Int -> Int)\n\nexpr = chainl1 term addop\nterm = chainl1 factor mulop\nfactor = digit +++ (do symb \"(\"; n <- expr; symb \")\"; return n)\ndigit = (do <- token (sat isDigit); return(ord x - ord '0'))\naddop = (do symb \"+\"; return (+)) <|> (do symb \"-\"; return (-)))\nmultop = (do symb \"*\"; return (*)) <|> (do symb \"/\"; return (/)))\n\nSince mutual recursion in Lean seems to require use of the equation compiler,\nwe hack around this by exposing the underlying `parser_tactic.run` function,\nlater recovering the parser with `parser_tactic.mk`.\n-/\n\nmeta mutual def parse_addop,parse_mulop,parse_digit,parse_factor,parse_term,parse_expr\nwith parse_addop : string → tactic ((ℤ → ℤ → ℤ) × string)\n| arg := (symb \"+\" >> return (+) <|> symb \"-\" >> return (λ x y : ℤ, x - y)).run arg\nwith parse_mulop : string → tactic ((ℤ → ℤ → ℤ) × string)\n| arg := (symb \"*\" >> return (*) <|> symb \"/\" >> return (λ x y : ℤ, x / y)).run arg\nwith parse_digit : string → tactic (ℤ × string)\n| arg := (token $ digit').run arg\nwith parse_factor : string → tactic (ℤ × string)\n| arg := (mk parse_digit <|> do symb \"(\", e <- (mk parse_expr), symb \")\", return e).run arg\nwith parse_term : string → tactic (ℤ × string)\n| arg := (chainl1 (mk parse_factor) (mk parse_mulop)).run arg\nwith parse_expr : string → tactic (ℤ × string)\n| arg := (chainl1 (mk parse_term) (mk parse_addop)).run arg\n\nmeta def calculator : parser_tactic ℤ := mk parse_expr\n\nrun_cmd calculator.run' \"(2 * (3 + 5 + (2 * 2)))\"\n-- 24\n\nrun_cmd calculator.run' \"9 - 9 * 0 * 3 + 4 - 7\"\n-- 6\n\nend calculator\n\nend calculator\n\nsection parse_tree_from_list\n\ninductive my_tree\n| node : option string → my_tree\n| join : list my_tree → option string → my_tree\n\nopen my_tree\n\n-- def list.reflect {α} [has_reflect α] : has_reflect $ list α :=\n-- begin\n-- sorry\n-- end\n\n\n\n\nmeta instance my_tree.reflect : has_reflect my_tree\n| (node arg) := `(λ x, node x).subst `(arg)\n| (join xs arg) := (`(λ xs s, join xs s).subst (by haveI := my_tree.reflect; exact list.reflect xs)).subst `(arg)\n\nmeta def my_tree_format : my_tree → format\n| (node none) := \"• \"\n| (node $ some st) := sformat!\"{st} \"\n| (join xs none) := \"{• || \" ++ format.join ((xs.map my_tree_format).intersperse \" | \") ++ \"}\"\n| (join xs $ some st) := \"{\" ++ sformat!\"{st} || \" ++ \" || \" ++ format.join ((xs.map my_tree_format).intersperse \" | \") ++ \"}\"\n\nmeta instance : has_to_format my_tree := ⟨my_tree_format⟩\n\n/-\n(a, b, c, (d, e), f) should be parsed as\n\n none -------┐ \n / | \\ \\ | \na b c none f\n | \\\n d e\n-/\n\nmeta mutual def my_tree_parser₁,my_tree_parser₂\nwith my_tree_parser₁ : string → tactic (my_tree × string)\n| arg := ((do int <- (fail_if_nil $ delimiter'' \"(\" \")\"),\n ts <- (run_parser (mk my_tree_parser₂) int),\n return (my_tree.join ts none))\n <|>\n (do x <- not_str \",\",\n return $ my_tree.node x)).run arg\nwith my_tree_parser₂ : string → tactic (list my_tree × string)\n| arg := (sepby (mk my_tree_parser₁) (symb \",\")).run arg\n\nmeta def my_tree_parser : parser_tactic my_tree := mk my_tree_parser₁\n\ndef my_parse_tree : my_tree := by my_tree_parser.get_result \"(a,b,c)\"\n\n#print my_parse_tree\n\n#eval (to_fmt my_parse_tree).to_string\n/- {• || a | b | c } -/\nrun_cmd my_tree_parser.run' \"(a, b, c)\"\n/- {• || a | b | c } -/\nrun_cmd my_tree_parser.run' \"(a,(b,c))\"\n/- {• || a | {• || b | c }} -/\nrun_cmd my_tree_parser.run' \"((a,b),c)\"\n/- {• || {• || a | b } | c } -/\nrun_cmd my_tree_parser.run' \"(a, b, c, (d, e), f)\"\n/- {• || a | b | c | {• || d | e } | f } -/\n\nsection formatting_tests\n\nexample : my_tree := node none\ndef example_tree : my_tree := join [node none, node none, node none] \"foo\"\n\ndef example_tree2 : my_tree := join [join [node \"a\", node \"b\"] none, node \"foo\"] \"bar\"\n\nrun_cmd (return example_tree : parser_tactic my_tree).run' \"ab\"\nrun_cmd (return example_tree2 : parser_tactic my_tree).run' \"ab\"\n\nend formatting_tests\n\nend parse_tree_from_list\n\nnamespace tdop\nsection tdop1\n/- Top-down operator-precedence parsing, but with tokens hard-coded as their own inductive types -/\n\nstructure Tokens :=\n(tks : Type)\n(prec : tks → ℕ)\n\n@[derive has_reflect, derive decidable_eq]\ninductive arith_tks : Type\n| of_nat : ℕ → arith_tks\n| plus : arith_tks\n| mul : arith_tks\nexport arith_tks\n\nmeta def arith_tks.to_format : arith_tks → format := λ x, arith_tks.cases_on x (λ n, (to_fmt n)) (to_fmt \"+\") (to_fmt \"*\")\n\nmeta instance arith_tks.has_to_format : has_to_format arith_tks :=\n⟨arith_tks.to_format⟩\n\ninstance : has_coe ℕ arith_tks :=\n⟨of_nat⟩\n\ndef arith_Tokens : Tokens :=\n{ tks := arith_tks,\n prec := arith_tks.rec (λ _, 0) 10 15 }\n\ninstance arith_tks_Tokens_coe : has_coe arith_tks arith_Tokens.tks := ⟨id⟩\n\ninductive tdop_parse_tree (Tks : Tokens) : Type\n| node : Tks.tks → tdop_parse_tree\n| join : list tdop_parse_tree → Tks.tks → tdop_parse_tree\nexport tdop_parse_tree\n\nmeta instance arith_tree_reflect : Π τ : tdop_parse_tree arith_Tokens, reflected τ\n| (node l) := `(λ x, node x).subst `(l)\n| (join τs l) := (λ y, `(λ x, join x y).subst (by {haveI := arith_tree_reflect, exact (list.reflect τs)})) l\n\ndef tdop_parse_tree.make_branch {Tks : Tokens} (τ : tdop_parse_tree Tks) (τ₀ : tdop_parse_tree Tks) : tdop_parse_tree Tks :=\nbegin\n induction τ with n j label,\n { exact tdop_parse_tree.join ([τ₀]) n },\n { exact join (τ₀ :: j) label }\nend\n\ndef tdop_parse_tree.insert {Tks : Tokens} (τ : tdop_parse_tree Tks) (tk : Tks.tks) : tdop_parse_tree Tks :=\nτ.make_branch (node tk)\n\ndef my_tdop_parse_tree : tdop_parse_tree arith_Tokens :=\njoin [node (1 : ℕ), node (2 : ℕ)] plus\n\nmeta def of.mk {α : Type} [has_reflect α] {Tks : Tokens} (Tks_eval : (tdop_parse_tree Tks) → tactic α) (τ : tdop_parse_tree Tks) : tactic unit :=\ndo a <- (Tks_eval τ), tactic.exact `(a)\n\nsection arith_eval\n\ninstance : has_add $ option ℕ :=\n⟨λ k₁ k₂,\noption.cases_on k₁ (option.cases_on k₂ none (λ _, none)) (option.cases_on k₂ (λ _, none) (λ n₁ n₂, return $ n₁ + n₂))⟩\n\ninstance : has_mul $ option ℕ :=\n⟨λ k₁ k₂,\noption.cases_on k₁ (option.cases_on k₂ none (λ _, none)) (option.cases_on k₂ (λ _, none) (λ n₁ n₂, return $ n₁ * n₂))⟩\n\nmeta def arith_Tokens_eval : tdop_parse_tree arith_Tokens → option ℕ\n| (node arg) := arith_tks.cases_on arg pure none none\n| (join xs arg) := arith_tks.cases_on arg (λ _, none) ((xs.map arith_Tokens_eval).foldr (+) (some 0)) ((xs.map arith_Tokens_eval).foldr (*) (some 0))\n\nmeta def of_arith_Tokens : tdop_parse_tree arith_Tokens → tactic unit :=\nof.mk (λ x, arith_Tokens_eval x)\n\nmeta def my_three : ℕ := by of_arith_Tokens my_tdop_parse_tree\n\n#eval my_three -- 3\n\nend arith_eval\n\nmeta def arith_tks.parse : parser_tactic arith_tks := \n ((do n <- number, return n) <* whitespace)\n <|> (token (str \"+\") >> return plus)\n <|> (token (str \"*\") >> return mul)\n\n-- run_cmd (repeat $ arith_tks.parse).run' \"1 + 3 + 5 * 2\"\n\nmeta def parse_nat : Π (left : tdop_parse_tree arith_Tokens), string → tactic (tdop_parse_tree arith_Tokens × string)\n| left arg := (do n <- (token number), return (left.insert (of_nat n))).run arg\n\nmeta def parse_plus : Π (left : tdop_parse_tree arith_Tokens), string → tactic (tdop_parse_tree arith_Tokens × string)\n| left arg := (token (str \"+\") >> return ((node plus : tdop_parse_tree arith_Tokens).make_branch left)).run arg\n\nmeta def parse_mul : Π (left : tdop_parse_tree arith_Tokens), string → tactic (tdop_parse_tree arith_Tokens × string)\n| left arg := (token (str \"*\") >> return ((node mul : tdop_parse_tree arith_Tokens).make_branch left)).run arg\n\nmeta def arith_tdop_parser' : Π (left : tdop_parse_tree arith_Tokens), parser_tactic (tdop_parse_tree arith_Tokens)\n| left := (mk $ parse_nat left) <|> (mk $ parse_plus left) <|> (mk $ parse_mul left)\n\nmeta def arith_tdop_parser_aux : Π flag : bool, Π result : tdop_parse_tree arith_Tokens, parser_tactic (tdop_parse_tree arith_Tokens)\n| ff _ := arith_tdop_parser' (node $ of_nat 0) >>= arith_tdop_parser_aux tt\n| tt τ := (arith_tdop_parser' τ >>= arith_tdop_parser_aux tt) <|> return τ\n\nmeta def arith_tdop_parser : parser_tactic (tdop_parse_tree arith_Tokens)\n:= arith_tdop_parser_aux ff (node $ of_nat 0) \n\nmeta def tdop_arith.to_format : (tdop_parse_tree arith_Tokens) → format\n| (node l) := arith_tks.to_format l\n| (join τs l) := \"( \" ++ (tdop_arith.to_format $ node l) ++ \" || \" ++ (string.join (((τs.map tdop_arith.to_format).map format.to_string).intersperse \" ,\")) ++ \")\"\n\nmeta instance tdop_parse_to_format : has_to_format (tdop_parse_tree arith_Tokens) := ⟨tdop_arith.to_format⟩\n\nrun_cmd (do arith_tdop_parser' (node $ of_nat 0) >>= arith_tdop_parser' >>= arith_tdop_parser').run' \"1 + 2\"\n\n--TODO(jesse) fix this\nrun_cmd (arith_tdop_parser).run' \"1 + 2 + 3 * 4 + 5\"\n\nend tdop1\nend tdop\n", "meta": {"author": "jesse-michael-han", "repo": "lean-parser-combinators", "sha": "d0dff9149a85a150679aa2145c4ffe2ac1ae5c0b", "save_path": "github-repos/lean/jesse-michael-han-lean-parser-combinators", "path": "github-repos/lean/jesse-michael-han-lean-parser-combinators/lean-parser-combinators-d0dff9149a85a150679aa2145c4ffe2ac1ae5c0b/src/basic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3849121444839335, "lm_q2_score": 0.05340333017646163, "lm_q1q2_score": 0.020555590340805407}} {"text": "/-\nCopyright (c) 2019 Simon Hudon. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthor: Simon Hudon\n\nMonad encapsulating continuation passing programming style, similar to\nHaskell's `Cont`, `ContT` and `MonadCont`:\n\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.default\nimport Mathlib.control.monad.writer\nimport Mathlib.PostPort\n\nuniverses u v w l u_1 u_2 u₀ u₁ v₀ v₁ \n\nnamespace Mathlib\n\nstructure monad_cont.label (α : Type w) (m : Type u → Type v) (β : Type u) \nwhere\n apply : α → m β\n\ndef monad_cont.goto {α : Type u_1} {β : Type u} {m : Type u → Type v} (f : monad_cont.label α m β) (x : α) : m β :=\n monad_cont.label.apply f x\n\nclass monad_cont (m : Type u → Type v) \nwhere\n call_cc : {α β : Type u} → (monad_cont.label α m β → m α) → m α\n\nclass is_lawful_monad_cont (m : Type u → Type v) [Monad m] [monad_cont m] \nextends is_lawful_monad m\nwhere\n call_cc_bind_right : ∀ {α ω γ : Type u} (cmd : m α) (next : monad_cont.label ω m γ → α → m ω),\n (monad_cont.call_cc fun (f : monad_cont.label ω m γ) => cmd >>= next f) =\n do \n let x ← cmd \n monad_cont.call_cc fun (f : monad_cont.label ω m γ) => next f x\n call_cc_bind_left : ∀ {α : Type u} (β : Type u) (x : α) (dead : monad_cont.label α m β → β → m α),\n (monad_cont.call_cc fun (f : monad_cont.label α m β) => monad_cont.goto f x >>= dead f) = pure x\n call_cc_dummy : ∀ {α β : Type u} (dummy : m α), (monad_cont.call_cc fun (f : monad_cont.label α m β) => dummy) = dummy\n\ndef cont_t (r : Type u) (m : Type u → Type v) (α : Type w) :=\n (α → m r) → m r\n\ndef cont (r : Type u) (α : Type w) :=\n cont_t r id α\n\nnamespace cont_t\n\n\ndef run {r : Type u} {m : Type u → Type v} {α : Type w} : cont_t r m α → (α → m r) → m r :=\n id\n\ndef map {r : Type u} {m : Type u → Type v} {α : Type w} (f : m r → m r) (x : cont_t r m α) : cont_t r m α :=\n f ∘ x\n\ntheorem run_cont_t_map_cont_t {r : Type u} {m : Type u → Type v} {α : Type w} (f : m r → m r) (x : cont_t r m α) : run (map f x) = f ∘ run x :=\n rfl\n\ndef with_cont_t {r : Type u} {m : Type u → Type v} {α : Type w} {β : Type w} (f : (β → m r) → α → m r) (x : cont_t r m α) : cont_t r m β :=\n fun (g : β → m r) => x (f g)\n\ntheorem run_with_cont_t {r : Type u} {m : Type u → Type v} {α : Type w} {β : Type w} (f : (β → m r) → α → m r) (x : cont_t r m α) : run (with_cont_t f x) = run x ∘ f :=\n rfl\n\nprotected theorem ext {r : Type u} {m : Type u → Type v} {α : Type w} {x : cont_t r m α} {y : cont_t r m α} (h : ∀ (f : α → m r), run x f = run y f) : x = y :=\n funext fun (x_1 : α → m r) => h x_1\n\nprotected instance monad {r : Type u} {m : Type u → Type v} : Monad (cont_t r m) := sorry\n\nprotected instance is_lawful_monad {r : Type u} {m : Type u → Type v} : is_lawful_monad (cont_t r m) :=\n is_lawful_monad.mk\n (fun (α β : Type u_1) (x : α) (f : α → cont_t r m β) =>\n cont_t.ext fun (f_1 : β → m r) => Eq.refl (run (pure x >>= f) f_1))\n fun (α β γ : Type u_1) (x : cont_t r m α) (f : α → cont_t r m β) (g : β → cont_t r m γ) =>\n cont_t.ext fun (f_1 : γ → m r) => Eq.refl (run (x >>= f >>= g) f_1)\n\ndef monad_lift {r : Type u} {m : Type u → Type v} [Monad m] {α : Type u} : m α → cont_t r m α :=\n fun (x : m α) (f : α → m r) => x >>= f\n\nprotected instance has_monad_lift {r : Type u} {m : Type u → Type v} [Monad m] : has_monad_lift m (cont_t r m) :=\n has_monad_lift.mk fun (α : Type u) => monad_lift\n\ntheorem monad_lift_bind {r : Type u} {m : Type u → Type v} [Monad m] [is_lawful_monad m] {α : Type u} {β : Type u} (x : m α) (f : α → m β) : monad_lift (x >>= f) = monad_lift x >>= monad_lift ∘ f := sorry\n\nprotected instance monad_cont {r : Type u} {m : Type u → Type v} : monad_cont (cont_t r m) :=\n monad_cont.mk\n fun (α β : Type u_1) (f : label α (cont_t r m) β → cont_t r m α) (g : α → m r) =>\n f (monad_cont.label.mk fun (x : α) (h : β → m r) => g x) g\n\nprotected instance is_lawful_monad_cont {r : Type u} {m : Type u → Type v} : is_lawful_monad_cont (cont_t r m) :=\n is_lawful_monad_cont.mk sorry sorry sorry\n\nprotected instance monad_except {r : Type u} {m : Type u → Type v} (ε : outParam (Type u_1)) [monad_except ε m] : monad_except ε (cont_t r m) :=\n monad_except.mk (fun (x : Type u_2) (e : ε) (f : x → m r) => throw e)\n fun (α : Type u_2) (act : cont_t r m α) (h : ε → cont_t r m α) (f : α → m r) => catch (act f) fun (e : ε) => h e f\n\nprotected instance monad_run {r : Type u} {m : Type u → Type v} : monad_run (fun (α : Type u) => (α → m r) → ulift (m r)) (cont_t r m) :=\n monad_run.mk fun (α : Type u) (f : cont_t r m α) (x : α → m r) => ulift.up (f x)\n\nend cont_t\n\n\ndef except_t.mk_label {m : Type u → Type v} [Monad m] {α : Type u} {β : Type u} {ε : Type u} : label (except ε α) m β → label α (except_t ε m) β :=\n sorry\n\ntheorem except_t.goto_mk_label {m : Type u → Type v} [Monad m] {α : Type u} {β : Type u} {ε : Type u} (x : label (except ε α) m β) (i : α) : goto (except_t.mk_label x) i = except_t.mk (except.ok <$> goto x (except.ok i)) :=\n monad_cont.label.cases_on x fun (x : except ε α → m β) => Eq.refl (goto (except_t.mk_label (monad_cont.label.mk x)) i)\n\ndef except_t.call_cc {m : Type u → Type v} [Monad m] {ε : Type u} [monad_cont m] {α : Type u} {β : Type u} (f : label α (except_t ε m) β → except_t ε m α) : except_t ε m α :=\n except_t.mk (monad_cont.call_cc fun (x : label (except ε α) m β) => except_t.run (f (except_t.mk_label x)))\n\nprotected instance except_t.monad_cont {m : Type u → Type v} [Monad m] {ε : Type u} [monad_cont m] : monad_cont (except_t ε m) :=\n monad_cont.mk fun (α β : Type u) => except_t.call_cc\n\nprotected instance except_t.is_lawful_monad_cont {m : Type u → Type v} [Monad m] {ε : Type u} [monad_cont m] [is_lawful_monad_cont m] : is_lawful_monad_cont (except_t ε m) :=\n is_lawful_monad_cont.mk sorry sorry sorry\n\ndef option_t.mk_label {m : Type u → Type v} [Monad m] {α : Type u} {β : Type u} : label (Option α) m β → label α (option_t m) β :=\n sorry\n\ntheorem option_t.goto_mk_label {m : Type u → Type v} [Monad m] {α : Type u} {β : Type u} (x : label (Option α) m β) (i : α) : goto (option_t.mk_label x) i = option_t.mk (some <$> goto x (some i)) :=\n monad_cont.label.cases_on x fun (x : Option α → m β) => Eq.refl (goto (option_t.mk_label (monad_cont.label.mk x)) i)\n\ndef option_t.call_cc {m : Type u → Type v} [Monad m] [monad_cont m] {α : Type u} {β : Type u} (f : label α (option_t m) β → option_t m α) : option_t m α :=\n option_t.mk (monad_cont.call_cc fun (x : label (Option α) m β) => option_t.run (f (option_t.mk_label x)))\n\nprotected instance option_t.monad_cont {m : Type u → Type v} [Monad m] [monad_cont m] : monad_cont (option_t m) :=\n monad_cont.mk fun (α β : Type u) => option_t.call_cc\n\nprotected instance option_t.is_lawful_monad_cont {m : Type u → Type v} [Monad m] [monad_cont m] [is_lawful_monad_cont m] : is_lawful_monad_cont (option_t m) :=\n is_lawful_monad_cont.mk sorry sorry sorry\n\ndef writer_t.mk_label {m : Type u → Type v} [Monad m] {α : Type u_1} {β : Type u} {ω : Type u} [HasOne ω] : label (α × ω) m β → label α (writer_t ω m) β :=\n sorry\n\ntheorem writer_t.goto_mk_label {m : Type u → Type v} [Monad m] {α : Type u_1} {β : Type u} {ω : Type u} [HasOne ω] (x : label (α × ω) m β) (i : α) : goto (writer_t.mk_label x) i = monad_lift (goto x (i, 1)) :=\n monad_cont.label.cases_on x fun (x : α × ω → m β) => Eq.refl (goto (writer_t.mk_label (monad_cont.label.mk x)) i)\n\ndef writer_t.call_cc {m : Type u → Type v} [Monad m] [monad_cont m] {α : Type u} {β : Type u} {ω : Type u} [HasOne ω] (f : label α (writer_t ω m) β → writer_t ω m α) : writer_t ω m α :=\n writer_t.mk (monad_cont.call_cc (writer_t.run ∘ f ∘ writer_t.mk_label))\n\nprotected instance writer_t.monad_cont {m : Type u → Type v} [Monad m] (ω : Type u) [Monad m] [HasOne ω] [monad_cont m] : monad_cont (writer_t ω m) :=\n monad_cont.mk fun (α β : Type u) => writer_t.call_cc\n\ndef state_t.mk_label {m : Type u → Type v} [Monad m] {α : Type u} {β : Type u} {σ : Type u} : label (α × σ) m (β × σ) → label α (state_t σ m) β :=\n sorry\n\ntheorem state_t.goto_mk_label {m : Type u → Type v} [Monad m] {α : Type u} {β : Type u} {σ : Type u} (x : label (α × σ) m (β × σ)) (i : α) : goto (state_t.mk_label x) i = state_t.mk fun (s : σ) => goto x (i, s) :=\n monad_cont.label.cases_on x fun (x : α × σ → m (β × σ)) => Eq.refl (goto (state_t.mk_label (monad_cont.label.mk x)) i)\n\ndef state_t.call_cc {m : Type u → Type v} [Monad m] {σ : Type u} [monad_cont m] {α : Type u} {β : Type u} (f : label α (state_t σ m) β → state_t σ m α) : state_t σ m α :=\n state_t.mk\n fun (r : σ) => monad_cont.call_cc fun (f' : label (α × σ) m (β × σ)) => state_t.run (f (state_t.mk_label f')) r\n\nprotected instance state_t.monad_cont {m : Type u → Type v} [Monad m] {σ : Type u} [monad_cont m] : monad_cont (state_t σ m) :=\n monad_cont.mk fun (α β : Type u) => state_t.call_cc\n\nprotected instance state_t.is_lawful_monad_cont {m : Type u → Type v} [Monad m] {σ : Type u} [monad_cont m] [is_lawful_monad_cont m] : is_lawful_monad_cont (state_t σ m) :=\n is_lawful_monad_cont.mk sorry sorry sorry\n\ndef reader_t.mk_label {m : Type u → Type v} [Monad m] {α : Type u_1} {β : Type u} (ρ : Type u) : label α m β → label α (reader_t ρ m) β :=\n sorry\n\ntheorem reader_t.goto_mk_label {m : Type u → Type v} [Monad m] {α : Type u_1} {ρ : Type u} {β : Type u} (x : label α m β) (i : α) : goto (reader_t.mk_label ρ x) i = monad_lift (goto x i) :=\n monad_cont.label.cases_on x fun (x : α → m β) => Eq.refl (goto (reader_t.mk_label ρ (monad_cont.label.mk x)) i)\n\ndef reader_t.call_cc {m : Type u → Type v} [Monad m] {ε : Type u} [monad_cont m] {α : Type u} {β : Type u} (f : label α (reader_t ε m) β → reader_t ε m α) : reader_t ε m α :=\n reader_t.mk fun (r : ε) => monad_cont.call_cc fun (f' : label α m β) => reader_t.run (f (reader_t.mk_label ε f')) r\n\nprotected instance reader_t.monad_cont {m : Type u → Type v} [Monad m] {ρ : Type u} [monad_cont m] : monad_cont (reader_t ρ m) :=\n monad_cont.mk fun (α β : Type u) => reader_t.call_cc\n\nprotected instance reader_t.is_lawful_monad_cont {m : Type u → Type v} [Monad m] {ρ : Type u} [monad_cont m] [is_lawful_monad_cont m] : is_lawful_monad_cont (reader_t ρ m) :=\n is_lawful_monad_cont.mk sorry sorry sorry\n\n/-- reduce the equivalence between two continuation passing monads to the equivalence between\ntheir underlying monad -/\ndef cont_t.equiv {m₁ : Type u₀ → Type v₀} {m₂ : Type u₁ → Type v₁} {α₁ : Type u₀} {r₁ : Type u₀} {α₂ : Type u₁} {r₂ : Type u₁} (F : m₁ r₁ ≃ m₂ r₂) (G : α₁ ≃ α₂) : cont_t r₁ m₁ α₁ ≃ cont_t r₂ m₂ α₂ :=\n equiv.mk\n (fun (f : cont_t r₁ m₁ α₁) (r : α₂ → m₂ r₂) => coe_fn F (f fun (x : α₁) => coe_fn (equiv.symm F) (r (coe_fn G x))))\n (fun (f : cont_t r₂ m₂ α₂) (r : α₁ → m₁ r₁) =>\n coe_fn (equiv.symm F) (f fun (x : α₂) => coe_fn F (r (coe_fn (equiv.symm G) x))))\n sorry sorry\n\n", "meta": {"author": "AurelienSaue", "repo": "Mathlib4_auto", "sha": "590df64109b08190abe22358fabc3eae000943f2", "save_path": "github-repos/lean/AurelienSaue-Mathlib4_auto", "path": "github-repos/lean/AurelienSaue-Mathlib4_auto/Mathlib4_auto-590df64109b08190abe22358fabc3eae000943f2/Mathlib/control/monad/cont.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47268347662043286, "lm_q2_score": 0.043365796136651424, "lm_q1q2_score": 0.02049829528428533}} {"text": "import free_pfpng.epi\nimport free_pfpng.mono\n\nnoncomputable theory\n\nopen_locale classical big_operators\n\nopen category_theory\nopen opposite\nopen category_theory.grothendieck_topology\n\nuniverse u\n\nlemma Condensed.is_zero_of_is_zero_obj (A : Condensed.{u} Ab.{u+1})\n (hA : ∀ S : Profinite.{u}, limits.is_zero (A.val.obj (opposite.op S))) :\n limits.is_zero A :=\n{ unique_to := λ Y, nonempty.intro\n { default := 0,\n uniq := λ a, begin\n ext t : 3,\n apply (hA t.unop).eq_of_src,\n end },\n unique_from := λ Y, nonempty.intro\n { default := 0,\n uniq := λ a, begin\n ext t : 3,\n apply (hA t.unop).eq_of_tgt\n end } }\n\nlemma Profinite.free_pfpng_eq_zero_of_empty (S : Profinite.{u}) [is_empty S]\n (a : S.free_pfpng) : a = 0 :=\nbegin\n let E : limits.cone ((S.fintype_diagram ⋙ free_pfpng_functor)) :=\n ProFiltPseuNormGrp₁.bounded_cone ⟨Ab.explicit_limit_cone.{u u} _,\n Ab.explicit_limit_cone_is_limit _⟩,\n let hE : limits.is_limit E :=\n ProFiltPseuNormGrp₁.bounded_cone_is_limit _,\n let ee : S.free_pfpng ≅ E.X :=\n (limits.limit.is_limit _).cone_point_unique_up_to_iso hE,\n apply_fun ee.hom, swap,\n { intros x y h, apply_fun ee.inv at h, simpa using h },\n rw ee.hom.map_zero, ext T t,\n obtain ⟨s⟩ := t,\n apply is_empty.elim _ (s : S), assumption\nend\n\nlemma Profinite.is_zero_of_empty (S : Profinite.{u}) [is_empty S] :\n limits.is_zero S.condensed_free_pfpng :=\nbegin\n apply Condensed.is_zero_of_is_zero_obj,\n intros T,\n dsimp [Profinite.condensed_free_pfpng],\n dsimp [CompHausFiltPseuNormGrp.presheaf],\n apply is_zero_Ab,\n rintros ⟨⟨f,hf⟩⟩, ext t, change f t = 0,\n apply Profinite.free_pfpng_eq_zero_of_empty,\nend\n\nlemma category_theory.abelian.is_iso_of_mono_of_is_zero\n {A : Type*} [category A] [abelian A] {X Y : A} (f : X ⟶ Y) [mono f]\n (hY : limits.is_zero Y) : is_iso f :=\nbegin\n use 0, simp, split,\n rw ← cancel_mono f,\n apply hY.eq_of_tgt,\n apply hY.eq_of_tgt,\nend\n\ninstance Profinite.epi_free'_to_condensed_free_pfpng_of_empty\n (S : Profinite.{u}) [is_empty S] :\n epi S.free'_to_condensed_free_pfpng :=\nbegin\n suffices : is_iso S.free'_to_condensed_free_pfpng,\n { resetI, apply_instance },\n apply category_theory.abelian.is_iso_of_mono_of_is_zero,\n apply Profinite.is_zero_of_empty,\nend\n\n-- Do a case split on `[nonempty S]` here.\ninstance Profinite.epi_free'_to_condensed_free_pfpng (S : Profinite.{u}) :\n epi S.free'_to_condensed_free_pfpng :=\nbegin\n by_cases hS : nonempty S, { resetI, apply_instance },\n simp only [not_nonempty_iff] at hS,\n resetI, apply_instance\nend\n\ninstance Profinite.is_iso_free'_to_condensed_free_pfpng\n (S : Profinite.{u}) : is_iso S.free'_to_condensed_free_pfpng :=\nis_iso_of_mono_of_epi _\n\ndef Profinite.free_to_pfpng (S : Profinite.{u}) :\n CondensedSet_to_Condensed_Ab.obj S.to_Condensed ⟶\n S.condensed_free_pfpng :=\n(Condensed_Ab_CondensedSet_adjunction.hom_equiv _ _).symm S.to_condensed_free_pfpng\n\nattribute [simps hom_app] AddCommGroup.free_iso_free'\n\ninstance Profinite.is_iso_free_to_pfpng (S : Profinite.{u}) : is_iso S.free_to_pfpng :=\nbegin\n suffices : S.free_to_pfpng =\n (CondensedSet_to_Condensed_Ab_iso.app S.to_Condensed).hom ≫\n S.free'_to_condensed_free_pfpng,\n { rw this, apply_instance },\n rw [iso.app_hom],\n delta Profinite.free'_to_condensed_free_pfpng Profinite.free'_lift Profinite.free_to_pfpng\n CondensedSet_to_Condensed_Ab_iso Sheaf.adjunction\n Condensed_Ab_CondensedSet_adjunction Condensed_Ab_CondensedSet_adjunction',\n ext T : 4,\n dsimp only [adjunction.mk_of_hom_equiv_hom_equiv, functor.map_iso_hom, quiver.hom.forget_Ab,\n Sheaf.hom.comp_val, Condensed_Ab_to_CondensedSet_map, Sheaf.compose_equiv_symm_apply_val,\n presheaf_to_Sheaf_map_val, nat_trans.comp_app,\n iso_whisker_left_hom, iso_whisker_right_hom, whisker_left_app, whisker_right_app],\n rw [← nat_trans.comp_app, sheafify_map_sheafify_lift],\n congr' 4, clear T,\n ext T : 2,\n dsimp only [whiskering_right_map_app_app, whiskering_right_obj_map, nat_trans.comp_app,\n adjunction.whisker_right, adjunction.mk_of_unit_counit_hom_equiv_symm_apply,\n whisker_left_app, whisker_right_app,\n functor.associator_hom_app, functor.right_unitor_hom_app],\n erw [category.id_comp, category.id_comp, category.comp_id, category.comp_id],\n rw [← nat_trans.naturality_assoc],\n congr' 1,\n dsimp only [AddCommGroup.adj, AddCommGroup.adj', adjunction.mk_of_hom_equiv_hom_equiv,\n adjunction.of_nat_iso_left, adjunction.mk_of_hom_equiv_counit_app,\n equiv.inv_fun_as_coe, equiv.symm_trans_apply, iso.symm_hom,\n adjunction.equiv_homset_left_of_nat_iso_symm_apply],\n simp only [equiv.symm_symm],\n erw [← category.assoc, ← nat_trans.comp_app, iso.hom_inv_id, nat_trans.id_app,\n category.id_comp],\nend\n\nlemma free_pfpng_profinite_natural_map_aux (S T : Profinite.{u}) (f : S ⟶ T) :\n f ≫ T.to_free_pfpng = S.to_free_pfpng ≫\n (ProFiltPseuNormGrp₁.level.obj 1).map\n ((Profinite.extend free_pfpng_functor).map f) :=\nbegin\n apply (limits.is_limit_of_preserves (ProFiltPseuNormGrp₁.level.obj 1)\n (limits.limit.is_limit _)).hom_ext,\n intros W, dsimp [Profinite.to_free_pfpng,\n Profinite.free_pfpng_level_iso, limits.is_limit.cone_point_unique_up_to_iso,\n limits.is_limit.map],\n simp only [category.assoc],\n erw (limits.is_limit_of_preserves (ProFiltPseuNormGrp₁.level.obj 1)\n (limits.limit.is_limit (T.fintype_diagram ⋙ free_pfpng_functor))).fac,\n erw limits.limit.lift_π,\n swap, apply_instance,\n simp only [← functor.map_comp, limits.limit.lift_π],\n dsimp [Profinite.change_cone],\n simp only [functor.map_comp],\n erw (limits.is_limit_of_preserves (ProFiltPseuNormGrp₁.level.obj 1)\n (limits.limit.is_limit (S.fintype_diagram ⋙ free_pfpng_functor))).fac_assoc,\n erw limits.limit.lift_π_assoc,\n ext, dsimp [Profinite.as_limit_cone, Fintype.free_pfpng_unit, free_pfpng.map,\n ProFiltPseuNormGrp₁.level],\n rcases x with ⟨x⟩,\n simp only [finset.filter_congr_decidable],\n erw [finset.sum_filter, finset.sum_ite, finset.sum_ite],\n simp only [finset.filter_congr_decidable, finset.sum_const,\n nat.smul_one_eq_coe, finset.sum_const_zero, add_zero],\n rw finset.filter_filter,\n split_ifs,\n { symmetry, norm_cast, rw finset.card_eq_one,\n use (W.comap f.2).proj a,\n rw finset.eq_singleton_iff_nonempty_unique_mem,\n split,\n { rw finset.filter_nonempty_iff,\n use (W.comap f.2).proj a,\n refine ⟨finset.mem_univ _, h, rfl⟩ },\n { rintros ⟨q⟩ hq,\n simp only [finset.mem_filter, finset.mem_univ, true_and] at hq,\n erw hq.2 } },\n { symmetry, norm_cast,\n simp only [finset.card_eq_zero],\n rw finset.filter_eq_empty_iff,\n rintros ⟨q⟩ -, push_neg, intros hh,\n rw ← hh at h,\n erw discrete_quotient.map_proj_apply at h,\n contrapose! h,\n let e : (W.comap f.2) → W := discrete_quotient.map (le_refl _),\n apply_fun e at h, exact h },\nend\n\ndef free_pfpng_profinite_natural_map :\n Profinite_to_Condensed ⋙ CondensedSet_to_Condensed_Ab ⟶\n Profinite.extend free_pfpng_functor ⋙\n PFPNG₁_to_CHFPNG₁ₑₗ ⋙\n CHFPNG₁_to_CHFPNGₑₗ ⋙\n CompHausFiltPseuNormGrp.to_Condensed :=\n{ app := λ X, X.free_to_pfpng,\n naturality' := λ S T f, begin\n -- we should be able to precompose with the natural map `S.to_Condensed ⟶ S.free'`\n -- how do we do that?\n -- Answer: use `adjunction.hom_equiv`.\n dsimp only [functor.comp_map],\n dsimp only [Profinite.free_to_pfpng],\n apply_fun (Condensed_Ab_CondensedSet_adjunction.hom_equiv _ _),\n simp only [adjunction.hom_equiv_unit, adjunction.hom_equiv_counit, functor.map_comp],\n simp only [nat_trans.naturality, category.assoc, nat_trans.naturality_assoc],\n dsimp only [Profinite.condensed_free_pfpng],\n have := Condensed_Ab_CondensedSet_adjunction.unit.naturality\n (Profinite_to_Condensed.map f),\n dsimp only [functor.comp_map] at this,\n slice_lhs 1 2 { rw ← this }, clear this,\n dsimp only [functor.id_map], simp only [category.assoc],\n have := Condensed_Ab_CondensedSet_adjunction.unit.naturality\n S.to_condensed_free_pfpng,\n dsimp only [functor.comp_map] at this,\n slice_rhs 1 2 { erw ← this }, clear this,\n dsimp only [functor.id_map], simp only [category.assoc],\n have := Condensed_Ab_CondensedSet_adjunction.right_triangle_components,\n slice_rhs 2 3 { erw this }, clear this,\n erw category.id_comp,\n slice_lhs 2 3 { erw ← nat_trans.naturality },\n simp only [functor.id_map, category.assoc],\n have := Condensed_Ab_CondensedSet_adjunction.right_triangle_components,\n slice_lhs 3 4 { rw this }, clear this,\n erw category.comp_id,\n ext W ⟨t⟩ : 7, change W.unop ⟶ S at t,\n\n dsimp [Profinite.to_condensed_free_pfpng,\n CompHausFiltPseuNormGrp.level_Condensed_diagram_cocone,\n Ab.ulift, Profinite.to_free_pfpng_level],\n erw ← comp_apply,\n erw ← comp_apply,\n erw ← comp_apply,\n rw free_pfpng_profinite_natural_map_aux _ _ f, refl,\n end }\n\ninstance free_pfpng_profinite_natural_map_is_iso :\n is_iso free_pfpng_profinite_natural_map :=\nbegin\n apply_with nat_iso.is_iso_of_is_iso_app { instances := ff },\n intros X,\n apply X.is_iso_free_to_pfpng,\nend\n\ndef free_pfpng_profinite_iso_aux :\n condensify (free_pfpng_functor ⋙ PFPNG₁_to_CHFPNG₁ₑₗ) ≅\n ((Profinite.extend free_pfpng_functor ⋙ PFPNG₁_to_CHFPNG₁ₑₗ) ⋙\n CHFPNG₁_to_CHFPNGₑₗ) ⋙\n CompHausFiltPseuNormGrp.to_Condensed :=\niso_whisker_right\n (iso_whisker_right\n (Profinite.extend_commutes free_pfpng_functor PFPNG₁_to_CHFPNG₁ₑₗ).symm\n CHFPNG₁_to_CHFPNGₑₗ)\n CompHausFiltPseuNormGrp.to_Condensed\n\n/-- Prop 2.1 of Analytic.pdf -/\ndef free_pfpng_profinite_iso :\n condensify (free_pfpng_functor ⋙ PFPNG₁_to_CHFPNG₁ₑₗ) ≅\n Profinite_to_Condensed ⋙ CondensedSet_to_Condensed_Ab :=\nfree_pfpng_profinite_iso_aux ≪≫ (as_iso free_pfpng_profinite_natural_map).symm\n", "meta": {"author": "leanprover-community", "repo": "lean-liquid", "sha": "92f188bd17f34dbfefc92a83069577f708851aec", "save_path": "github-repos/lean/leanprover-community-lean-liquid", "path": "github-repos/lean/leanprover-community-lean-liquid/lean-liquid-92f188bd17f34dbfefc92a83069577f708851aec/src/free_pfpng/main.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.04146227611666972, "lm_q1q2_score": 0.020407240384604536}} {"text": "import tactic defs single height\n\nlemma branch_left : ∀ t, ⟨t⟩ → ⟨⟦t∣⟧⟩ :=\nbegin intros, apply is_branch.left_nl, assumption end\n\nlemma branch_left_leaf : ∀ t, ⟨t⟩ → ⟨⟦t,●⟧⟩ := \nbegin intros, apply is_branch.left_l, assumption end\n\nlemma branch_right : ∀ t, ⟨t⟩ → ⟨⟦∣t⟧⟩ :=\nbegin intros, apply is_branch.right_nl, assumption end\n\nlemma branch_right_leaf : ∀ t, ⟨t⟩ → ⟨⟦●,t⟧⟩ :=\nbegin intros, apply is_branch.right_l, assumption end \n \nmeta def auto_branch_core : tactic unit := \ndo\n h ← tactic.target,\n match h with \n | `(is_branch %%b):= \n match b with \n | `(●) := tactic.exact `(is_branch.single)\n | `(⟦%%t∣⟧) := do tactic.applyc `branch_left, auto_branch_core \n | `(⟦∣%%t⟧) := do tactic.applyc `branch_right, auto_branch_core\n | `(⟦%%t,●⟧):= do tactic.applyc `branch_left_leaf,\n auto_branch_core\n | `(⟦●,%%t⟧):= do tactic.applyc `branch_right_leaf,\n auto_branch_core\n | _ := tactic.try (tactic.assumption <|> tactic.tautology)\n end\n | _ := tactic.fail \"should not exists\"\n end\n\nmeta def reduce_trivial_tree_core : list expr → tactic unit \n| [] := tactic.skip\n| (h :: hs) := do t ← tactic.infer_type h, \n match t with \n | `(%%b ↣ ●) := tactic.replace h.to_string ``(single_grow %%b %%h)\n | `(height %%b ≤ 1) := tactic.replace h.to_string ``(height_le1_single %%b %%h)\n | _ := tactic.skip\n end,\n reduce_trivial_tree_core hs\n\nmeta def reduce_trivial_tree : tactic unit :=\ndo \n h ← tactic.local_context,\n reduce_trivial_tree_core h\n \nmeta def rewrite_ci_core : list expr → tactic unit\n| [] := tactic.skip\n| (h :: hs) := do t ← tactic.infer_type h,\n match t with\n | `(%%b = ●) := tactic.try (tactic.subst h)\n | _ := tactic.skip\n end,\n rewrite_ci_core hs\n\nmeta def rewrite_ci : tactic unit := \ndo\n reduce_trivial_tree,\n h ← tactic.local_context,\n rewrite_ci_core h\n\nmeta def auto_grow_core : tactic unit := \n do h ← tactic.target, \n match h with \n | `(grow %%t %%t') := \n match t, t' with \n | `(●), _ := tactic.applyc `grow.single_grow\n | `(⟦%%u∣⟧), `(⟦%%u'∣⟧) := \n do tactic.applyc `grow.left_grow, \n auto_grow_core\n | `(⟦∣%%v⟧), `(⟦∣%%v'⟧) := \n do tactic.applyc `grow.right_grow,\n auto_grow_core\n | `(⟦%%u, %%v⟧), `(⟦%%u', %%v'⟧) := \n do tactic.applyc `grow.full_grow,\n auto_grow_core, \n auto_grow_core\n | _, _ := tactic.try (tactic.assumption <|> tactic.tautology)\n end\n | _ := tactic.fail \"should not exists\"\n end\n\nmeta def auto_grow : tactic unit := \ndo\n rewrite_ci,\n auto_grow_core\n\n\nmeta def auto_branch : tactic unit := \ndo\n rewrite_ci,\n auto_branch_core\n", "meta": {"author": "ljt12138", "repo": "Proof-of-Surreal", "sha": "6b92baf2382ac23dd0d700f5c958aa910ad4b754", "save_path": "github-repos/lean/ljt12138-Proof-of-Surreal", "path": "github-repos/lean/ljt12138-Proof-of-Surreal/Proof-of-Surreal-6b92baf2382ac23dd0d700f5c958aa910ad4b754/src/tactics.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.04146227108280706, "lm_q1q2_score": 0.02040723790699706}} {"text": "/-\nCopyright (c) 2017 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Leonardo de Moura\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.default\nimport Mathlib.Lean3Lib.data.rbtree.default\n \n\nuniverses u v \n\nnamespace Mathlib\n\nnamespace rbmap\n\n\n/- Auxiliary instances -/\n\n/- Helper lemmas for reusing rbtree results. -/\n\ntheorem eq_some_of_to_value_eq_some {α : Type u} {β : Type v} {e : Option (α × β)} {v : β} : to_value e = some v → ∃ (k : α), e = some (k, v) := sorry\n\ntheorem eq_none_of_to_value_eq_none {α : Type u} {β : Type v} {e : Option (α × β)} : to_value e = none → e = none := sorry\n\n/- Lemmas -/\n\ntheorem not_mem_mk_rbmap {α : Type u} {β : Type v} {lt : α → α → Prop} (k : α) : ¬k ∈ mk_rbmap α β := sorry\n\ntheorem not_mem_of_empty {α : Type u} {β : Type v} {lt : α → α → Prop} {m : rbmap α β} (k : α) : empty m = tt → ¬k ∈ m := sorry\n\ntheorem not_mem_of_find_entry_none {α : Type u} {β : Type v} {lt : α → α → Prop} [DecidableRel lt] [is_strict_weak_order α lt] {k : α} {m : rbmap α β} : find_entry m k = none → ¬k ∈ m := sorry\n\ntheorem not_mem_of_find_none {α : Type u} {β : Type v} {lt : α → α → Prop} [DecidableRel lt] [is_strict_weak_order α lt] {k : α} {m : rbmap α β} : find m k = none → ¬k ∈ m := sorry\n\ntheorem mem_of_find_entry_some {α : Type u} {β : Type v} {lt : α → α → Prop} [DecidableRel lt] [is_strict_weak_order α lt] {k₁ : α} {e : α × β} {m : rbmap α β} : find_entry m k₁ = some e → k₁ ∈ m := sorry\n\ntheorem mem_of_find_some {α : Type u} {β : Type v} {lt : α → α → Prop} [DecidableRel lt] [is_strict_weak_order α lt] {k : α} {v : β} {m : rbmap α β} : find m k = some v → k ∈ m := sorry\n\ntheorem find_entry_eq_find_entry_of_eqv {α : Type u} {β : Type v} {lt : α → α → Prop} [DecidableRel lt] [is_strict_weak_order α lt] {m : rbmap α β} {k₁ : α} {k₂ : α} : strict_weak_order.equiv k₁ k₂ → find_entry m k₁ = find_entry m k₂ := sorry\n\ntheorem find_eq_find_of_eqv {α : Type u} {β : Type v} {lt : α → α → Prop} [DecidableRel lt] [is_strict_weak_order α lt] {k₁ : α} {k₂ : α} (m : rbmap α β) : strict_weak_order.equiv k₁ k₂ → find m k₁ = find m k₂ := sorry\n\ntheorem find_entry_correct {α : Type u} {β : Type v} {lt : α → α → Prop} [DecidableRel lt] [is_strict_weak_order α lt] (k : α) (m : rbmap α β) : k ∈ m ↔ ∃ (e : α × β), find_entry m k = some e ∧ strict_weak_order.equiv k (prod.fst e) := sorry\n\ntheorem eqv_of_find_entry_some {α : Type u} {β : Type v} {lt : α → α → Prop} [DecidableRel lt] [is_strict_weak_order α lt] {k₁ : α} {k₂ : α} {v : β} {m : rbmap α β} : find_entry m k₁ = some (k₂, v) → strict_weak_order.equiv k₁ k₂ := sorry\n\ntheorem eq_of_find_entry_some {α : Type u} {β : Type v} {lt : α → α → Prop} [DecidableRel lt] [is_strict_total_order α lt] {k₁ : α} {k₂ : α} {v : β} {m : rbmap α β} : find_entry m k₁ = some (k₂, v) → k₁ = k₂ :=\n fun (h : find_entry m k₁ = some (k₂, v)) =>\n (fun (this : strict_weak_order.equiv k₁ k₂) => eq_of_eqv_lt this) (eqv_of_find_entry_some h)\n\ntheorem find_correct {α : Type u} {β : Type v} {lt : α → α → Prop} [DecidableRel lt] [is_strict_weak_order α lt] (k : α) (m : rbmap α β) : k ∈ m ↔ ∃ (v : β), find m k = some v := sorry\n\ntheorem constains_correct {α : Type u} {β : Type v} {lt : α → α → Prop} [DecidableRel lt] [is_strict_weak_order α lt] (k : α) (m : rbmap α β) : k ∈ m ↔ contains m k = tt := sorry\n\ntheorem mem_of_mem_of_eqv {α : Type u} {β : Type v} {lt : α → α → Prop} [DecidableRel lt] [is_strict_weak_order α lt] {m : rbmap α β} {k₁ : α} {k₂ : α} : k₁ ∈ m → strict_weak_order.equiv k₁ k₂ → k₂ ∈ m := sorry\n\ntheorem mem_insert_of_incomp {α : Type u} {β : Type v} {lt : α → α → Prop} [DecidableRel lt] [is_strict_weak_order α lt] {k₁ : α} {k₂ : α} (m : rbmap α β) (v : β) : ¬lt k₁ k₂ ∧ ¬lt k₂ k₁ → k₁ ∈ insert m k₂ v :=\n fun (h : ¬lt k₁ k₂ ∧ ¬lt k₂ k₁) => to_rbmap_mem (rbtree.mem_insert_of_incomp m (eqv_entries_of_eqv_keys v v h))\n\ntheorem mem_insert {α : Type u} {β : Type v} {lt : α → α → Prop} [DecidableRel lt] [is_strict_weak_order α lt] (k : α) (m : rbmap α β) (v : β) : k ∈ insert m k v :=\n to_rbmap_mem (rbtree.mem_insert (k, v) m)\n\ntheorem mem_insert_of_equiv {α : Type u} {β : Type v} {lt : α → α → Prop} [DecidableRel lt] [is_strict_weak_order α lt] {k₁ : α} {k₂ : α} (m : rbmap α β) (v : β) : strict_weak_order.equiv k₁ k₂ → k₁ ∈ insert m k₂ v :=\n mem_insert_of_incomp m v\n\ntheorem mem_insert_of_mem {α : Type u} {β : Type v} {lt : α → α → Prop} [DecidableRel lt] [is_strict_weak_order α lt] {k₁ : α} {m : rbmap α β} (k₂ : α) (v : β) : k₁ ∈ m → k₁ ∈ insert m k₂ v :=\n fun (h : k₁ ∈ m) => to_rbmap_mem (rbtree.mem_insert_of_mem (k₂, v) (to_rbtree_mem' v h))\n\ntheorem equiv_or_mem_of_mem_insert {α : Type u} {β : Type v} {lt : α → α → Prop} [DecidableRel lt] [is_strict_weak_order α lt] {k₁ : α} {k₂ : α} {v : β} {m : rbmap α β} : k₁ ∈ insert m k₂ v → strict_weak_order.equiv k₁ k₂ ∨ k₁ ∈ m := sorry\n\ntheorem incomp_or_mem_of_mem_ins {α : Type u} {β : Type v} {lt : α → α → Prop} [DecidableRel lt] [is_strict_weak_order α lt] {k₁ : α} {k₂ : α} {v : β} {m : rbmap α β} : k₁ ∈ insert m k₂ v → ¬lt k₁ k₂ ∧ ¬lt k₂ k₁ ∨ k₁ ∈ m :=\n equiv_or_mem_of_mem_insert\n\ntheorem eq_or_mem_of_mem_ins {α : Type u} {β : Type v} {lt : α → α → Prop} [DecidableRel lt] [is_strict_total_order α lt] {k₁ : α} {k₂ : α} {v : β} {m : rbmap α β} : k₁ ∈ insert m k₂ v → k₁ = k₂ ∨ k₁ ∈ m := sorry\n\ntheorem find_entry_insert_of_eqv {α : Type u} {β : Type v} {lt : α → α → Prop} [DecidableRel lt] [is_strict_weak_order α lt] (m : rbmap α β) {k₁ : α} {k₂ : α} (v : β) : strict_weak_order.equiv k₁ k₂ → find_entry (insert m k₁ v) k₂ = some (k₁, v) := sorry\n\ntheorem find_entry_insert {α : Type u} {β : Type v} {lt : α → α → Prop} [DecidableRel lt] [is_strict_weak_order α lt] (m : rbmap α β) (k : α) (v : β) : find_entry (insert m k v) k = some (k, v) :=\n find_entry_insert_of_eqv m v (refl k)\n\ntheorem find_insert_of_eqv {α : Type u} {β : Type v} {lt : α → α → Prop} [DecidableRel lt] [is_strict_weak_order α lt] (m : rbmap α β) {k₁ : α} {k₂ : α} (v : β) : strict_weak_order.equiv k₁ k₂ → find (insert m k₁ v) k₂ = some v := sorry\n\ntheorem find_insert {α : Type u} {β : Type v} {lt : α → α → Prop} [DecidableRel lt] [is_strict_weak_order α lt] (m : rbmap α β) (k : α) (v : β) : find (insert m k v) k = some v :=\n find_insert_of_eqv m v (refl k)\n\ntheorem find_entry_insert_of_disj {α : Type u} {β : Type v} {lt : α → α → Prop} [DecidableRel lt] [is_strict_weak_order α lt] {k₁ : α} {k₂ : α} (m : rbmap α β) (v : β) : lt k₁ k₂ ∨ lt k₂ k₁ → find_entry (insert m k₁ v) k₂ = find_entry m k₂ := sorry\n\ntheorem find_entry_insert_of_not_eqv {α : Type u} {β : Type v} {lt : α → α → Prop} [DecidableRel lt] [is_strict_weak_order α lt] {k₁ : α} {k₂ : α} (m : rbmap α β) (v : β) : ¬strict_weak_order.equiv k₁ k₂ → find_entry (insert m k₁ v) k₂ = find_entry m k₂ := sorry\n\ntheorem find_entry_insert_of_ne {α : Type u} {β : Type v} {lt : α → α → Prop} [DecidableRel lt] [is_strict_total_order α lt] {k₁ : α} {k₂ : α} (m : rbmap α β) (v : β) : k₁ ≠ k₂ → find_entry (insert m k₁ v) k₂ = find_entry m k₂ :=\n fun (h : k₁ ≠ k₂) => find_entry_insert_of_not_eqv m v fun (h' : strict_weak_order.equiv k₁ k₂) => h (eq_of_eqv_lt h')\n\ntheorem find_insert_of_disj {α : Type u} {β : Type v} {lt : α → α → Prop} [DecidableRel lt] [is_strict_weak_order α lt] {k₁ : α} {k₂ : α} (m : rbmap α β) (v : β) : lt k₁ k₂ ∨ lt k₂ k₁ → find (insert m k₁ v) k₂ = find m k₂ := sorry\n\ntheorem find_insert_of_not_eqv {α : Type u} {β : Type v} {lt : α → α → Prop} [DecidableRel lt] [is_strict_weak_order α lt] {k₁ : α} {k₂ : α} (m : rbmap α β) (v : β) : ¬strict_weak_order.equiv k₁ k₂ → find (insert m k₁ v) k₂ = find m k₂ := sorry\n\ntheorem find_insert_of_ne {α : Type u} {β : Type v} {lt : α → α → Prop} [DecidableRel lt] [is_strict_total_order α lt] {k₁ : α} {k₂ : α} (m : rbmap α β) (v : β) : k₁ ≠ k₂ → find (insert m k₁ v) k₂ = find m k₂ := sorry\n\ntheorem mem_of_min_eq {α : Type u} {β : Type v} {lt : α → α → Prop} [DecidableRel lt] [is_strict_total_order α lt] {k : α} {v : β} {m : rbmap α β} : min m = some (k, v) → k ∈ m :=\n fun (h : min m = some (k, v)) => to_rbmap_mem (rbtree.mem_of_min_eq h)\n\ntheorem mem_of_max_eq {α : Type u} {β : Type v} {lt : α → α → Prop} [DecidableRel lt] [is_strict_total_order α lt] {k : α} {v : β} {m : rbmap α β} : max m = some (k, v) → k ∈ m :=\n fun (h : max m = some (k, v)) => to_rbmap_mem (rbtree.mem_of_max_eq h)\n\ntheorem eq_leaf_of_min_eq_none {α : Type u} {β : Type v} {lt : α → α → Prop} [DecidableRel lt] [is_strict_weak_order α lt] {m : rbmap α β} : min m = none → m = mk_rbmap α β :=\n rbtree.eq_leaf_of_min_eq_none\n\ntheorem eq_leaf_of_max_eq_none {α : Type u} {β : Type v} {lt : α → α → Prop} [DecidableRel lt] [is_strict_weak_order α lt] {m : rbmap α β} : max m = none → m = mk_rbmap α β :=\n rbtree.eq_leaf_of_max_eq_none\n\ntheorem min_is_minimal {α : Type u} {β : Type v} {lt : α → α → Prop} [DecidableRel lt] [is_strict_weak_order α lt] {k : α} {v : β} {m : rbmap α β} : min m = some (k, v) → ∀ {k' : α}, k' ∈ m → strict_weak_order.equiv k k' ∨ lt k k' := sorry\n\ntheorem max_is_maximal {α : Type u} {β : Type v} {lt : α → α → Prop} [DecidableRel lt] [is_strict_weak_order α lt] {k : α} {v : β} {m : rbmap α β} : max m = some (k, v) → ∀ {k' : α}, k' ∈ m → strict_weak_order.equiv k k' ∨ lt k' k := sorry\n\ntheorem min_is_minimal_of_total {α : Type u} {β : Type v} {lt : α → α → Prop} [DecidableRel lt] [is_strict_total_order α lt] {k : α} {v : β} {m : rbmap α β} : min m = some (k, v) → ∀ {k' : α}, k' ∈ m → k = k' ∨ lt k k' := sorry\n\ntheorem max_is_maximal_of_total {α : Type u} {β : Type v} {lt : α → α → Prop} [DecidableRel lt] [is_strict_total_order α lt] {k : α} {v : β} {m : rbmap α β} : max m = some (k, v) → ∀ {k' : α}, k' ∈ m → k = k' ∨ lt k' k := sorry\n\n", "meta": {"author": "AurelienSaue", "repo": "Mathlib4_auto", "sha": "590df64109b08190abe22358fabc3eae000943f2", "save_path": "github-repos/lean/AurelienSaue-Mathlib4_auto", "path": "github-repos/lean/AurelienSaue-Mathlib4_auto/Mathlib4_auto-590df64109b08190abe22358fabc3eae000943f2/Mathlib/Lean3Lib/data/rbmap/default.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.04146227063864274, "lm_q1q2_score": 0.02040723768838465}} {"text": "/-\nCopyright (c) 2017 Mario Carneiro. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Mario Carneiro, Yury Kudryashov\n-/\nimport tactic.transform_decl\nimport tactic.algebra\n\n/-!\n# Transport multiplicative to additive\n\nThis file defines an attribute `to_additive` that can be used to\nautomatically transport theorems and definitions (but not inductive\ntypes and structures) from a multiplicative theory to an additive theory.\n\nUsage information is contained in the doc string of `to_additive.attr`.\n\n### Missing features\n\n* Automatically transport structures and other inductive types.\n\n* For structures, automatically generate theorems like `group α ↔\n add_group (additive α)`.\n\n* Rewrite rules for the last part of the name that work in more\n cases. E.g., we can replace `monoid` with `add_monoid` etc.\n-/\n\nnamespace to_additive\nopen tactic exceptional\n\nsection performance_hack -- see Note [user attribute parameters]\n\nlocal attribute [semireducible] reflected\n\nlocal attribute [instance, priority 9000]\nprivate meta def hacky_name_reflect : has_reflect name :=\nλ n, `(id %%(expr.const n []) : name)\n\n/-- An auxiliary attribute used to store the names of the additive versions of declarations\nthat have been processed by `to_additive`. -/\n@[user_attribute]\nprivate meta def aux_attr : user_attribute (name_map name) name :=\n{ name := `to_additive_aux,\n descr := \"Auxiliary attribute for `to_additive`. DON'T USE IT\",\n cache_cfg := ⟨λ ns,\n ns.mfoldl\n (λ dict n', do\n let n := match n' with\n | name.mk_string s pre := if s = \"_to_additive\" then pre else n'\n | _ := n'\n end,\n param ← aux_attr.get_param_untyped n',\n pure $ dict.insert n param.app_arg.const_name)\n mk_name_map, []⟩,\n parser := lean.parser.ident }\n\nend performance_hack\n\n/-- A command that can be used to have future uses of `to_additive` change the `src` namespace\nto the `tgt` namespace.\n\nFor example:\n```\nrun_cmd to_additive.map_namespace `quotient_group `quotient_add_group\n```\n\nLater uses of `to_additive` on declarations in the `quotient_group` namespace will be created\nin the `quotient_add_group` namespaces.\n-/\nmeta def map_namespace (src tgt : name) : command :=\ndo let n := src.mk_string \"_to_additive\",\n let decl := declaration.thm n [] `(unit) (pure (reflect ())),\n add_decl decl,\n aux_attr.set n tgt tt\n\n/-- `value_type` is the type of the arguments that can be provided to `to_additive`.\n`to_additive.parser` parses the provided arguments into `name` for the target and an\noptional doc string. -/\n@[derive has_reflect, derive inhabited]\nstructure value_type : Type := (tgt : name) (doc : option string)\n\n/-- `add_comm_prefix x s` returns `\"comm_\" ++ s` if `x = tt` and `s` otherwise. -/\nmeta def add_comm_prefix : bool → string → string\n| tt s := (\"comm_\" ++ s)\n| ff s := s\n\n/-- Dictionary used by `to_additive.guess_name` to autogenerate names. -/\nmeta def tr : bool → list string → list string\n| is_comm (\"one\" :: \"le\" :: s) := add_comm_prefix is_comm \"nonneg\" :: tr ff s\n| is_comm (\"one\" :: \"lt\" :: s) := add_comm_prefix is_comm \"pos\" :: tr ff s\n| is_comm (\"le\" :: \"one\" :: s) := add_comm_prefix is_comm \"nonpos\" :: tr ff s\n| is_comm (\"lt\" :: \"one\" :: s) := add_comm_prefix is_comm \"neg\" :: tr ff s\n| is_comm (\"mul\" :: \"support\" :: s) := add_comm_prefix is_comm \"support\" :: tr ff s\n| is_comm (\"mul\" :: \"indicator\" :: s) := add_comm_prefix is_comm \"indicator\" :: tr ff s\n| is_comm (\"mul\" :: s) := add_comm_prefix is_comm \"add\" :: tr ff s\n| is_comm (\"smul\" :: s) := add_comm_prefix is_comm \"vadd\" :: tr ff s\n| is_comm (\"inv\" :: s) := add_comm_prefix is_comm \"neg\" :: tr ff s\n| is_comm (\"div\" :: s) := add_comm_prefix is_comm \"sub\" :: tr ff s\n| is_comm (\"one\" :: s) := add_comm_prefix is_comm \"zero\" :: tr ff s\n| is_comm (\"prod\" :: s) := add_comm_prefix is_comm \"sum\" :: tr ff s\n| is_comm (\"finprod\" :: s) := add_comm_prefix is_comm \"finsum\" :: tr ff s\n| is_comm (\"npow\" :: s) := add_comm_prefix is_comm \"nsmul\" :: tr ff s\n| is_comm (\"gpow\" :: s) := add_comm_prefix is_comm \"gsmul\" :: tr ff s\n| is_comm (\"monoid\" :: s) := (\"add_\" ++ add_comm_prefix is_comm \"monoid\") :: tr ff s\n| is_comm (\"submonoid\" :: s) := (\"add_\" ++ add_comm_prefix is_comm \"submonoid\") :: tr ff s\n| is_comm (\"group\" :: s) := (\"add_\" ++ add_comm_prefix is_comm \"group\") :: tr ff s\n| is_comm (\"subgroup\" :: s) := (\"add_\" ++ add_comm_prefix is_comm \"subgroup\") :: tr ff s\n| is_comm (\"semigroup\" :: s) := (\"add_\" ++ add_comm_prefix is_comm \"semigroup\") :: tr ff s\n| is_comm (\"magma\" :: s) := (\"add_\" ++ add_comm_prefix is_comm \"magma\") :: tr ff s\n| is_comm (\"comm\" :: s) := tr tt s\n| is_comm (x :: s) := (add_comm_prefix is_comm x :: tr ff s)\n| tt [] := [\"comm\"]\n| ff [] := []\n\n/-- Autogenerate target name for `to_additive`. -/\nmeta def guess_name : string → string :=\nstring.map_tokens ''' $\nλ s, string.intercalate (string.singleton '_') $\ntr ff (s.split_on '_')\n\n/-- Return the provided target name or autogenerate one if one was not provided. -/\nmeta def target_name (src tgt : name) (dict : name_map name) : tactic name :=\n(if tgt.get_prefix ≠ name.anonymous -- `tgt` is a full name\n then pure tgt\n else match src with\n | (name.mk_string s pre) :=\n do let tgt_auto := guess_name s,\n guard (tgt.to_string ≠ tgt_auto)\n <|> trace (\"`to_additive \" ++ src.to_string ++ \"`: correctly autogenerated target \" ++\n \"name, you may remove the explicit \" ++ tgt_auto ++ \" argument.\"),\n pure $ name.mk_string\n (if tgt = name.anonymous then tgt_auto else tgt.to_string)\n (pre.map_prefix dict.find)\n | _ := fail (\"to_additive: can't transport \" ++ src.to_string)\n end) >>=\n(λ res,\n if res = src\n then fail (\"to_additive: can't transport \" ++ src.to_string ++ \" to itself\")\n else pure res)\n\n/-- the parser for the arguments to `to_additive` -/\nmeta def parser : lean.parser value_type :=\ndo\n tgt ← optional lean.parser.ident,\n e ← optional interactive.types.texpr,\n doc ← match e with\n | some pe := some <$> ((to_expr pe >>= eval_expr string) : tactic string)\n | none := pure none\n end,\n return ⟨tgt.get_or_else name.anonymous, doc⟩\n\nprivate meta def proceed_fields_aux (src tgt : name) (prio : ℕ) (f : name → tactic (list string)) :\n command :=\ndo\n src_fields ← f src,\n tgt_fields ← f tgt,\n guard (src_fields.length = tgt_fields.length) <|>\n fail (\"Failed to map fields of \" ++ src.to_string),\n (src_fields.zip tgt_fields).mmap' $\n λ names, guard (names.fst = names.snd) <|>\n aux_attr.set (src.append names.fst) (tgt.append names.snd) tt prio\n\n/-- Add the `aux_attr` attribute to the structure fields of `src`\nso that future uses of `to_additive` will map them to the corresponding `tgt` fields. -/\nmeta def proceed_fields (env : environment) (src tgt : name) (prio : ℕ) : command :=\nlet aux := proceed_fields_aux src tgt prio in\ndo\naux (λ n, pure $ list.map name.to_string $ (env.structure_fields n).get_or_else []) >>\naux (λ n, (list.map (λ (x : name), \"to_\" ++ x.to_string) <$> get_tagged_ancestors n)) >>\naux (λ n, (env.constructors_of n).mmap $\n λ cs, match cs with\n | (name.mk_string s pre) :=\n (guard (pre = n) <|> fail \"Bad constructor name\") >>\n pure s\n | _ := fail \"Bad constructor name\"\n end)\n\n/--\nThe attribute `to_additive` can be used to automatically transport theorems\nand definitions (but not inductive types and structures) from a multiplicative\ntheory to an additive theory.\n\nTo use this attribute, just write:\n\n```\n@[to_additive]\ntheorem mul_comm' {α} [comm_semigroup α] (x y : α) : x * y = y * x := comm_semigroup.mul_comm\n```\n\nThis code will generate a theorem named `add_comm'`. It is also\npossible to manually specify the name of the new declaration, and\nprovide a documentation string:\n\n```\n@[to_additive add_foo \"add_foo doc string\"]\n/-- foo doc string -/\ntheorem foo := sorry\n```\n\nThe transport tries to do the right thing in most cases using several\nheuristics described below. However, in some cases it fails, and\nrequires manual intervention.\n\nIf the declaration to be transported has attributes which need to be\ncopied to the additive version, then `to_additive` should come last:\n\n```\n@[simp, to_additive] lemma mul_one' {G : Type*} [group G] (x : G) : x * 1 = x := mul_one x\n```\n\nThe exception to this rule is the `simps` attribute, which should come after `to_additive`:\n\n```\n@[to_additive, simps]\ninstance {M N} [has_mul M] [has_mul N] : has_mul (M × N) := ⟨λ p q, ⟨p.1 * q.1, p.2 * q.2⟩⟩\n```\n\n## Implementation notes\n\nThe transport process generally works by taking all the names of\nidentifiers appearing in the name, type, and body of a declaration and\ncreating a new declaration by mapping those names to additive versions\nusing a simple string-based dictionary and also using all declarations\nthat have previously been labeled with `to_additive`.\n\nIn the `mul_comm'` example above, `to_additive` maps:\n* `mul_comm'` to `add_comm'`,\n* `comm_semigroup` to `add_comm_semigroup`,\n* `x * y` to `x + y` and `y * x` to `y + x`, and\n* `comm_semigroup.mul_comm'` to `add_comm_semigroup.add_comm'`.\n\nEven when `to_additive` is unable to automatically generate the additive\nversion of a declaration, it can be useful to apply the attribute manually:\n\n```\nattribute [to_additive foo_add_bar] foo_bar\n```\n\nThis will allow future uses of `to_additive` to recognize that\n`foo_bar` should be replaced with `foo_add_bar`.\n\n### Handling of hidden definitions\n\nBefore transporting the “main” declaration `src`, `to_additive` first\nscans its type and value for names starting with `src`, and transports\nthem. This includes auxiliary definitions like `src._match_1`,\n`src._proof_1`.\n\nAfter transporting the “main” declaration, `to_additive` transports\nits equational lemmas.\n\n### Structure fields and constructors\n\nIf `src` is a structure, then `to_additive` automatically adds\nstructure fields to its mapping, and similarly for constructors of\ninductive types.\n\nFor new structures this means that `to_additive` automatically handles\ncoercions, and for old structures it does the same, if ancestry\ninformation is present in `@[ancestor]` attributes. The `ancestor`\nattribute must come before the `to_additive` attribute, and it is\nessential that the order of the base structures passed to `ancestor` matches\nbetween the multiplicative and additive versions of the structure.\n\n### Name generation\n\n* If `@[to_additive]` is called without a `name` argument, then the\n new name is autogenerated. First, it takes the longest prefix of\n the source name that is already known to `to_additive`, and replaces\n this prefix with its additive counterpart. Second, it takes the last\n part of the name (i.e., after the last dot), and replaces common\n name parts (“mul”, “one”, “inv”, “prod”) with their additive versions.\n\n* Namespaces can be transformed using `map_namespace`. For example:\n ```\n run_cmd to_additive.map_namespace `quotient_group `quotient_add_group\n ```\n\n Later uses of `to_additive` on declarations in the `quotient_group`\n namespace will be created in the `quotient_add_group` namespaces.\n\n* If `@[to_additive]` is called with a `name` argument `new_name`\n /without a dot/, then `to_additive` updates the prefix as described\n above, then replaces the last part of the name with `new_name`.\n\n* If `@[to_additive]` is called with a `name` argument\n `new_namespace.new_name` /with a dot/, then `to_additive` uses this\n new name as is.\n\nAs a safety check, in the first two cases `to_additive` double checks\nthat the new name differs from the original one.\n\n-/\n@[user_attribute]\nprotected meta def attr : user_attribute unit value_type :=\n{ name := `to_additive,\n descr := \"Transport multiplicative to additive\",\n parser := parser,\n after_set := some $ λ src prio persistent, do\n guard persistent <|> fail \"`to_additive` can't be used as a local attribute\",\n env ← get_env,\n val ← attr.get_param src,\n dict ← aux_attr.get_cache,\n tgt ← target_name src val.tgt dict,\n aux_attr.set src tgt tt,\n let dict := dict.insert src tgt,\n if env.contains tgt\n then proceed_fields env src tgt prio\n else do\n transform_decl_with_prefix_dict dict src tgt\n [`reducible, `_refl_lemma, `simp, `instance, `refl, `symm, `trans, `elab_as_eliminator,\n `no_rsimp],\n mwhen (has_attribute' `simps src)\n (trace \"Apply the simps attribute after the to_additive attribute\"),\n match val.doc with\n | some doc := add_doc_string tgt doc\n | none := skip\n end }\n\nadd_tactic_doc\n{ name := \"to_additive\",\n category := doc_category.attr,\n decl_names := [`to_additive.attr],\n tags := [\"transport\", \"environment\", \"lemma derivation\"] }\n\nend to_additive\n\n/- map operations -/\nattribute [to_additive] has_mul has_one has_inv has_div\n", "meta": {"author": "JLimperg", "repo": "aesop3", "sha": "a4a116f650cc7403428e72bd2e2c4cda300fe03f", "save_path": "github-repos/lean/JLimperg-aesop3", "path": "github-repos/lean/JLimperg-aesop3/aesop3-a4a116f650cc7403428e72bd2e2c4cda300fe03f/src/algebra/group/to_additive.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.411110869232168, "lm_q2_score": 0.04958902403746827, "lm_q1q2_score": 0.020386586776418452}} {"text": "namespace List\n\n@[simp] theorem filter_nil {p : α → Bool} : filter p [] = [] := by\n simp!\n\ntheorem cons_eq_append (a : α) (as : List α) : a :: as = [a] ++ as := rfl\n\ntheorem filter_cons (a : α) (as : List α) :\n filter p (a :: as) = if p a then a :: filter p as else filter p as :=\n sorry\n\n@[simp] theorem filter_append {as bs : List α} {p : α → Bool} :\n filter p (as ++ bs) = filter p as ++ filter p bs :=\n match as with\n | [] => by simp\n | a :: as => by\n rw [filter_cons, cons_append, filter_cons]\n cases p a\n simp [filter_append]\n simp [filter_append]\n\n-- the previous contains a more complicated version of\ndef f : Nat → Nat\n | 0 => 1\n | i+1 => (fun x => f x) i\n", "meta": {"author": "leanprover", "repo": "lean4", "sha": "742d053a97bdd109a41a921facd1cd6a55e89bc7", "save_path": "github-repos/lean/leanprover-lean4", "path": "github-repos/lean/leanprover-lean4/lean4-742d053a97bdd109a41a921facd1cd6a55e89bc7/tests/lean/run/structuralIssue2.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.44939263446475963, "lm_q2_score": 0.04535257539305419, "lm_q1q2_score": 0.020381113335646257}} {"text": "\nimport heap.lemmas heap.tactic misc prop\nimport data.nat.basic\n\nuniverses u\n\nnamespace separation\nopen memory finmap\n\nvariables (value : Type)\n\n@[reducible]\ndef ST (α : Type) := state_t (heap value) set α\n\nopen state_t\nvariables {value} {α : Type}\ninclude value\nlocal notation `ST` := ST value\n\ndef read (p : ptr) : ST value :=\ndo m ← get,\n match m.lookup p with\n | none := @monad_lift set _ _ _ ∅\n | (some x) := pure x\n end\n\ndef assign (p : ptr) (v : value) : ST punit :=\nmodify (finmap.insert p v)\n\ndef assign_vals (p : ptr) (vs : list value) : ST punit :=\nmodify $ (∪ heap.mk (vs.enum_from p))\n\ndef choice (p : α → Prop) : ST α :=\n@monad_lift set (state_t _ set) _ _ (p : set α)\n\ndef alloc (vs : list value) : ST ptr :=\ndo m ← get,\n p ← choice $ λ p : ptr, ∀ i < vs.length, (p + i) ∉ m,\n assign_vals p vs,\n pure p\n\nsection\n\nvariable value\n\ndef alloc' (n : ℕ) : ST ptr :=\nchoice (λ v : list value, v.length = n) >>= alloc\n\ndef dealloc (p : ptr) (n : ℕ) : ST unit :=\ndo m ← get,\n modify $ erase_all p n\n\nend\n\ndef for' : Π (k : ℕ) (n : ℕ) (f : ℕ → ST punit), ST punit\n| _ 0 f := pure punit.star\n| k (nat.succ n) f := f k >> for' k.succ n f\n\ndef for : Π (n : ℕ) (f : ℕ → ST punit), ST punit\n| 0 f := pure punit.star\n| (nat.succ n) f := for n f >> f n\n\n-- def clone (p : tptr (list value)) (n : ℕ) : ST ptr :=\n-- do q ← alloc' value n,\n-- for n (λ i,\n-- do v ← read (p + i),\n-- assign (q + i) v),\n-- pure q\n\n-- def map (p : ptr) (f : ℕ → value → value) (n : ℕ) : ST punit :=\n-- for n (λ i,\n-- do v ← read (p + i),\n-- assign (p + i) (f i v) )\n\nsection talloc\n\n-- open\n\nvariables (value) (α) [fixed_storable value α] (n : ℕ)\n-- local notation `ST` := ST value\nlocal notation `tptr` := tptr value\n\ndef malloc : ST (tptr (list value)) :=\ntptr.mk _ _ <$> alloc' value n\n\ndef ralloc : ST (tptr (list α)) :=\ntptr.mk _ _ <$> alloc' value (n * fixed_size value α)\n\ndef ralloc1 : ST (tptr α) :=\ntptr.mk _ _ <$> alloc' value (fixed_size value α)\n\nvariables {α}\n\nvariables {value}\n\ndef free (p : tptr (list α)) (n : ℕ) : ST unit :=\ndealloc value p.get (n * fixed_size value α)\n\nend talloc\n\n@[simp]\nlemma mem_run_modify (x : punit) (h h' : heap value) (g : heap value → heap value) :\n (x,h') ∈ (modify g : ST punit).run h ↔ h' = g h :=\nby simp only [modify,state_t.modify,pure,state_t.run,punit.punit_eq_iff, true_and, id.def, iff_self, set.mem_singleton_iff, prod.mk.inj_iff, prod.map]\n\n@[simp]\nlemma mem_bind_run {β} (x' : β) (h h' : heap value) (f : ST α) (g : α → ST β) :\n (x',h') ∈ (f >>= g).run h ↔ (∃ x'' h'', (x'',h'') ∈ f.run h ∧ (x',h') ∈ (g x'').run h'') :=\nby simp only [exists_prop, state_t.run_bind, set.mem_Union, set.bind_def, iff_self, prod.exists]\n\n@[simp]\nlemma mem_choice_run (x' : α) (h h' : heap value) (p : α → Prop) :\n (x',h') ∈ (choice p : ST α).run h ↔ p x' ∧ h' = h :=\nby simp only [choice, set.mem_Union, set.bind_def, set.mem_singleton_iff, prod.mk.inj_iff, run_monad_lift, set.pure_def];\n split; simp only [and_imp, exists_imp_distrib]; intros; try { subst x' }; repeat { split }; assumption\n\n@[simp]\nlemma mem_run_pure (x x' : α) (h h' : heap value) :\n (x',h') ∈ (pure x : ST α).run h ↔ x' = x ∧ h' = h :=\nby simp only [iff_self, set.mem_singleton_iff, prod.mk.inj_iff, set.pure_def, state_t.run_pure]\n\n@[simp]\nlemma mem_run_get (x' : heap value) (h h' : heap value) :\n (x',h') ∈ (get : ST _).run h ↔ x' = h ∧ h' = h :=\nby simp only [get, monad_state.lift, pure, set.mem_singleton_iff, prod.mk.inj_iff, id.def, state_t.run_get]\n\n@[simp]\nlemma mem_run_read (x' : value) (p : ptr) (h h' : heap value) :\n (x',h') ∈ (read p : ST _).run h ↔ h.lookup p = some x' ∧ h' = h :=\nbegin\n simp only [read, monad_state.lift, pure, exists_prop, set.mem_Union, set.bind_def, mem_run_get, prod.mk.inj_iff, run_bind, prod.exists], split,\n { rintro ⟨a,b,⟨h'',H⟩,H'⟩, cases h : (lookup p b); subst_vars; rw h at H'; simp [read] at H', cases H', casesm* _ ∧ _,\n subst_vars, rw h, exact ⟨rfl,rfl⟩ },\n { rintro ⟨h,⟨⟩,⟨⟩⟩, refine ⟨_,_,⟨rfl,rfl⟩,_⟩, simp [h,read] }\nend\n\nsection tactic\n\nopen tactic\nomit value\n\nmeta def sane_names : tactic unit :=\ndo ls ← local_context,\n ls.reverse.mmap' $ λ l,\n when (l.local_pp_name.to_string.length > 5) $ do\n t ← infer_type l,\n n ← revert l,\n let fn := t.get_app_fn,\n let v := if fn.is_constant\n then fn.const_name.update_prefix name.anonymous\n else if fn.is_local_constant\n then fn.local_pp_name\n else `h,\n v ← get_unused_name v,\n intro $ mk_simple_name $ (v.to_string.to_list.take 1).as_string,\n intron (n - 1),\n skip\n\nend tactic\n\nopen list\n\n@[simp]\nlemma mem_run_alloc_cons (v : value) (vs : list value) (h h' : heap value) (p : ptr) :\n (p, h') ∈ (alloc (v :: vs)).run h ↔ ∃ h'', some h' = some h'' ⊗ some (maplet p v) ∧ p ∉ h ∧ (p+1, h'') ∈ (alloc vs).run h :=\nbegin\n simp [alloc,assign_vals,enum_from], split; intro h; casesm * [Exists _, _ ∧ _]; subst_vars;\n constructor_matching* [_ ∧ _, Exists _]; try { assumption <|> refl <|> sane_names },\n { have : disjoint (maplet p v) (heap.mk (enum_from (p + 1) vs)) := disjoint_maplet_heap_mk_add_one _ _,\n rw [← union_eq_add_of_disjoint,union_comm_of_disjoint this,union_assoc],\n rw disjoint_union_left, refine ⟨_,this.symm⟩,\n symmetry, simp [disjoint_maplet], apply h_1 0 (nat.zero_lt_one_add _) },\n { apply h_1 0, linarith },\n { introv hi, specialize h_1 (1 + i) (nat.add_lt_add_left hi _),\n rw ← nat.add_assoc at h_1, exact h_1, },\n { introv hi, cases i, { exact n },\n specialize h_1 i, rw [← nat.succ_eq_add_one,nat.succ_add_eq_succ_add] at h_1,\n rw [nat.add_comm,nat.succ_eq_add_one] at hi,\n apply h_1 (nat.lt_of_add_lt_add_right hi) },\n { have : disjoint (maplet p v) (heap.mk (enum_from (p + 1) vs)),\n { simp },\n rw [union_comm_of_disjoint this, ← union_assoc],\n apply eq_union_of_eq_add e }\nend\n\n@[simp]\nlemma mem_run_alloc (vs : list value) (h h' : heap value) (p : ptr) :\n (p, h') ∈ (alloc vs).run h ↔ some h' = some h ⊗ some (heap.mk $ vs.enum_from p) :=\nbegin\n induction vs generalizing p h',\n { simp [alloc,assign_vals,list.enum_from], },\n { simp only [some_mk_enum_from_cons, mem_run_alloc_cons, vs_ih, add_zero], split,\n { simp only [and_imp, exists_imp_distrib], intros h'' H₀ H₁ H₂,\n simp only [*, memory.add_assoc, and_true, eq_self_iff_true], congr' 1,\n rw memory.add_comm, },\n { rintro H₀, existsi h ∪ heap.mk (enum_from (p + 1) vs_tl),\n rw [H₀,union_eq_add_of_disjoint,memory.add_assoc], split,\n { clear_except, congr' 1, apply memory.add_comm },\n split, {\n have : disjoint (maplet p vs_hd) h, prove_disjoint,\n apply this, simp },\n { exact rfl },\n prove_disjoint } }\nend\n\nend separation\n", "meta": {"author": "cipher1024", "repo": "lean-pl", "sha": "829680605ac17e91038d793c0188e9614353ca25", "save_path": "github-repos/lean/cipher1024-lean-pl", "path": "github-repos/lean/cipher1024-lean-pl/lean-pl-829680605ac17e91038d793c0188e9614353ca25/src/program.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.476579651063676, "lm_q2_score": 0.042722200593555464, "lm_q1q2_score": 0.020360531451549035}} {"text": "import tactic data.vector.basic data.vector.zip algebra.big_operators.basic algebra.big_operators.norm_num\n vorspiel lencodable\n\nopen_locale big_operators\n\nuniverses u v\n\nnamespace turing_machine\n\ninductive language (Γ : Type u)\n| blank : language\n| start : language\n| chr : Γ → language\n\nnotation `␣` := language.blank \nnotation `␤` := language.start\n\nnamespace language\nvariables {Γ : Type u}\n\ninstance : inhabited (language Γ) := ⟨␣⟩\n\ndef language_equiv_option_sum_bool : language Γ ≃ bool ⊕ Γ :=\n{ to_fun := λ l, match l with | ␣ := sum.inl ff | ␤ := sum.inl tt | chr x := sum.inr x end,\n inv_fun := λ l, match l with | (sum.inl ff) := ␣ | (sum.inl tt) := ␤ | sum.inr x := chr x end,\n left_inv := λ l, by rcases l; simp; refl,\n right_inv := λ l, by { rcases l; simp, { rcases l; refl }, refl } }\n\ninstance [fintype Γ] : fintype (language Γ) := fintype.of_equiv (bool ⊕ Γ) language_equiv_option_sum_bool.symm\n\nend language\n\nclass state_lang (Q : Type u) :=\n(start : Q)\n(halt : Q)\n\ninstance {Q R} [state_lang Q] [state_lang R] : state_lang (Q ⊕ R) := ⟨sum.inl state_lang.start, sum.inr state_lang.halt⟩\n\nend turing_machine\n\nnamespace turing_machine\nopen state_lang\n\nvariables\n (Γ : Type u) -- 言語\n (Q : Type v) [state_lang Q] -- 状態\n (ι : ℕ) -- テープの数\n\ninductive instruction\n| stay : instruction\n| right : instruction\n| left : instruction\n\nnamespace instruction\n\ninstance : inhabited instruction := ⟨stay⟩\n\n@[simp] def apply : instruction → ℕ → ℕ\n| stay ι := ι\n| right ι := ι + 1\n| left ι := ι - 1\n\n@[simp] lemma apply_default (n) : apply default n = n := rfl\n\n@[simp] lemma default_nth (ι : ℕ) (i) : (default : vector instruction ι).nth i = stay :=\nby { unfold default, simp }\n\ndef equiv_unit_sums : instruction ≃ unit ⊕ unit ⊕ unit :=\n{ to_fun := λ i, match i with | stay := sum.inl () | right := sum.inr (sum.inl ()) | left := sum.inr (sum.inr ()) end,\n inv_fun := λ i, match i with | sum.inl () := stay | sum.inr (sum.inl ()) := right | sum.inr (sum.inr ()) := left end,\n left_inv := λ i, by rcases i; refl,\n right_inv := λ i, by { rcases i; simp, rcases i, refl, rcases i; rcases i; refl } }\n\ninstance : fintype instruction := fintype.of_equiv (unit ⊕ unit ⊕ unit) equiv_unit_sums.symm\n\n@[simp] lemma card : fintype.card instruction = 3 := by simpa using fintype.card_congr equiv_unit_sums\n\nvariables {ι}\n\ndef Stay : vector instruction ι := vector.repeat stay ι\n\n@[simp] lemma Stay_nth (i : fin ι) : Stay.nth i = stay := by simp[Stay]\n\ndef Right : vector instruction ι := vector.repeat right ι\n\n@[simp] lemma Right_nth (i : fin ι) : Right.nth i = right := by simp[Right]\n\ndef Left : vector instruction ι := vector.repeat left ι\n\n@[simp] lemma Left_nth (i : fin ι) : Left.nth i = left := by simp[Left]\n\nend instruction\n\nstructure word :=\n(c : Q)\n(z : vector Γ ι)\n(u : vector instruction ι)\n(q : Q)\n(x : vector Γ ι)\n\nnotation `⟮` c `, ` z `; ` u ` | ` q `, ` x `⟯`:80 := word.mk c z u q x\n\nnamespace word\n\ndef equiv_prod : word Γ Q ι ≃ Q × vector Γ ι × vector instruction ι × Q × vector Γ ι :=\n{ to_fun := λ w, match w with ⟮c, z; u | q, x⟯ := (c, z, u, q, x) end,\n inv_fun := λ w, match w with (c, z, u, q, x) := ⟮c, z; u | q, x⟯ end,\n left_inv := λ w, by rcases w; refl,\n right_inv := λ w, by rcases w with ⟨_, w⟩; rcases w with ⟨_, w⟩; rcases w with ⟨_, w⟩; rcases w with ⟨_, w⟩; refl }\n\nopen fintype\n\ninstance [fintype Γ] [fintype Q] : fintype (word Γ Q ι) :=\nfintype.of_equiv (Q × vector Γ ι × vector instruction ι × Q × vector Γ ι) (equiv_prod _ _ _).symm\n\nlemma card [fintype Γ] [fintype Q] : card (word Γ Q ι) = card Q^2 * (3 * card Γ^2)^ι :=\ncalc card (word Γ Q ι) = card Q * card Γ^ι * 3^ι * card Q * card Γ^ι\n : by simpa[mul_assoc] using fintype.card_congr (equiv_prod Γ Q ι)\n ... = card Q * card Q * 3^ι * card Γ^ι * card Γ^ι\n : by ring\n ... = card Q^2 * (3 * card Γ^2)^ι\n : by simp[pow_two, mul_pow]; ring\n\nend word\n\nstructure model :=\n(state : Q) \n(tape : vector (ℕ → Γ) ι)\n(head : vector ℕ ι)\n\nnotation `⟦` q `, ` T `, ` H `⟧` := model.mk q T H\n\nstructure sentence :=\n(carrier : set (word Γ Q ι))\n(proper' : ∀ c z u q x, ⟮c, z; u | q, x⟯ ∈ carrier → q ≠ state_lang.halt ∧ c ≠ state_lang.start)\n\nnamespace sentence\nvariables {Γ Q ι}\nvariables (σ : sentence Γ Q ι)\n\ninstance : set_like (sentence Γ Q ι) (word Γ Q ι) := ⟨sentence.carrier, λ ⟨_, _⟩ ⟨_, _⟩, by simp⟩\n\nlemma mem_def (w : word Γ Q ι) : w ∈ σ ↔ w ∈ σ.carrier := iff.rfl\n\nlemma proper {c z u q x} : ⟮c, z; u | q, x⟯ ∈ σ → q ≠ state_lang.halt ∧ c ≠ state_lang.start := σ.proper' _ _ _ _ _\n\n@[simp] lemma start_notin (c z u x) : ⟮c, z; u | halt, x⟯ ∉ σ := λ A, by simpa using σ.proper A\n\n@[simp] lemma halt_notin (z u q x) : ⟮start, z; u | q, x⟯ ∉ σ := λ A, by simpa using σ.proper A \n\nlemma carrier_finite [fintype Γ] [fintype Q] : σ.carrier.finite := set.to_finite _\n\nnoncomputable instance [fintype Γ] [fintype Q] : fintype (sentence Γ Q ι) := fintype.of_injective carrier (λ ⟨_, _⟩ ⟨_, _⟩, by simp)\n\ndef is_halt (q : Q) : Prop := ∀ ⦃c z u x⦄, ⟮c, z; u | q, x⟯ ∉ σ\n\ndef is_start (c : Q) : Prop := ∀ ⦃z u x q⦄, ⟮c, z; u | q, x⟯ ∉ σ\n\nlemma coe_carrier : (σ : set (word Γ Q ι)) = σ.carrier := by refl\n\nend sentence\n\nvariables {Γ Q ι}\n\nnamespace model\nvariables (σ : sentence Γ Q ι)\n\n\n@[ext] lemma ext : ∀ {m₁ m₂ : model Γ Q ι}\n (hs : m₁.state = m₂.state)\n (ht : m₁.tape = m₂.tape)\n (hh : m₁.head = m₂.head), m₁ = m₂\n| ⟦q₁, T₁, H₁⟧ ⟦q₂, T₂, H₂⟧ hs ht hh :=\n by { simp at hs ht hh, simp[hs, ht, hh] }\n\ndef read (T : vector (ℕ → Γ) ι) (H : vector ℕ ι) : vector Γ ι := @vector.zip_with (ℕ → Γ) ℕ Γ ι (λ t h, t h) T H\n\n@[simp] lemma read_nth (T : vector (ℕ → Γ) ι) (H : vector ℕ ι) (i) : (read T H).nth i = (T.nth i) (H.nth i) :=\nby simp[read]\n\n@[irreducible] def reduct_tape (T H) (x : vector Γ ι) : vector (ℕ → Γ) ι :=\n @vector.zip_with3 (ℕ → Γ) ℕ Γ (ℕ → Γ) ι (λ t h x, λ n, if n = h then x else t n) T H x\n\n@[irreducible] def reduct_head (H) (u : vector instruction ι) : vector ℕ ι :=\n vector.zip_with instruction.apply u H\n\n@[simp] lemma reduct_tape_nth (T H) (x : vector Γ ι) (i) :\n (reduct_tape T H x).nth i = (λ n, if n = H.nth i then x.nth i else T.nth i n) :=\nby simp[reduct_tape]\n\n@[simp] lemma reduct_head_nth (H) (u : vector instruction ι) (i) :\n (reduct_head H u).nth i = (u.nth i).apply (H.nth i) :=\nby simp[reduct_head]\n\ninductive reduction : model Γ Q ι → model Γ Q ι → Prop\n| intro : ∀ (q : Q) (T : vector (ℕ → Γ) ι) (H : vector ℕ ι) (c : Q) (z : vector Γ ι) (u : vector instruction ι),\n ⟮c, z; u | q, read T H⟯ ∈ σ → reduction ⟦q, T, H⟧ ⟦c, reduct_tape T H z, reduct_head H u⟧\n\nnotation m₀ ` ⟶¹[`:60 σ `] ` :0 m₁ := reduction σ m₀ m₁ \n\ndef is_halt (m : model Γ Q ι) : Prop := ∀ m', ¬m ⟶¹[σ] m'\n\ndef time_reductions : ℕ → model Γ Q ι → model Γ Q ι → Prop := relation.power (reduction σ) \n\nnotation m₀ ` ⟶^(`:80 s `)[` σ `] ` :80 m₁ := time_reductions σ s m₀ m₁ \n\ndef time_bounded_reductions : ℕ → model Γ Q ι → model Γ Q ι → Prop := relation.power_le (reduction σ)\n\nnotation m₀ ` ⟶^(≤ `:80 s `)[` σ `] ` :80 m₁ := time_bounded_reductions σ s m₀ m₁ \n\ndef time_bounded_reductions_halt (s : ℕ) (m m' : model Γ Q ι) : Prop := is_halt σ m' ∧ m ⟶^(≤ s)[σ] m'\n\nnotation m₀ ` ⟶^(≤ `:80 s `)[` σ `]↓ ` :80 m₁ := time_bounded_reductions_halt σ s m₀ m₁ \n\ndef is_halt_in_step (s : ℕ) (m : model Γ Q ι) : Prop := ∀ (m') (s' > s), ¬ m ⟶^(s')[σ] m' \n\ndef reductions : model Γ Q ι → model Γ Q ι → Prop := relation.trans_gen (reduction σ) \n\nnotation m₀ ` ⟶*[`:80 σ `] ` :0 m₁ := reductions σ m₀ m₁ \n\nend model\n\nvariables {Γ Q ι} \ndef sentence.deterministic (σ : sentence Γ Q ι) : Prop :=\n∀ ⦃q x c₁ c₂ z₁ z₂ u₁ u₂⦄, ⟮c₁, z₁; u₁ | q, x⟯ ∈ σ → ⟮c₂, z₂; u₂ | q, x⟯ ∈ σ → c₁ = c₂ ∧ z₁ = z₂ ∧ u₁ = u₂\n\nnamespace sentence\n\ninductive of_fun_aux (δ : Q → vector Γ ι → option (Q × vector Γ ι × vector instruction ι)) : set (word Γ Q ι)\n| intro : ∀ {q x c z u}, δ q x = some ⟨c, z, u⟩ → of_fun_aux ⟮c, z; u | q, x⟯\n\ndef of_fun (δ : Q → vector Γ ι → option (Q × vector Γ ι × vector instruction ι))\n (H : ∀ {q x c z u}, δ q x = some ⟨c, z, u⟩ → q ≠ halt ∧ c ≠ start) : sentence Γ Q ι :=\n{ carrier := of_fun_aux δ,\n proper' := λ c z u q x, by { rintro ⟨_, _, _, _, _, h⟩, exact H h } }\n\nnamespace of_fun\nvariables (δ : Q → vector Γ ι → option (Q × vector Γ ι × vector instruction ι))\n\nlemma carrier_eq {H} : (of_fun δ H).carrier = of_fun_aux δ := rfl\n\n@[simp] lemma mem_iff {H} {c z u q x} : ⟮c, z; u | q, x⟯ ∈ of_fun δ H ↔ δ q x = some ⟨c, z, u⟩ :=\nby { simp[sentence.mem_def], split,\n { rintros ⟨_, _, _, _, _, h⟩, exact h }, { intros h, exact of_fun_aux.intro h } }\n\nlemma none_is_halt {q H} : (of_fun δ H).is_halt q ↔ ∀ x, δ q x = none :=\nby { simp [is_halt, mem_iff, option.eq_none_iff_forall_not_mem], split,\n { rintros h x c ⟨z, u⟩ eqn, exact h eqn }, { rintros h c z u x, exact h x c (z, u) } }\n\nlemma of_fn.deterministic {H} : deterministic (of_fun δ H) :=\nλ _ _ _ _ _ _ _ _, by { simp, intros h₁ h₂, simpa[h₁] using h₂ }\n\nend of_fun\n\nnamespace deterministic\nvariables {σ : sentence Γ Q ι} {m₁ m₂ : model Γ Q ι}\n\nlemma reduction (d : deterministic σ) : relation.deterministic (model.reduction σ) := λ m m₁ m₂ h₁ h₂,\nbegin\n rcases h₁ with ⟨q₁, T₁, H₁, c₁, z₁, u₁, mem₁⟩,\n rcases h₂ with ⟨q₂, T₂, H₂, c₂, z₂, u₂, mem₂⟩,\n rcases d mem₁ mem₂ with ⟨rfl, rfl, rfl⟩,\n refl\nend\n\nlemma time_reductions (d : deterministic σ) {n} : relation.deterministic (model.time_reductions σ n) :=\nrelation.power.deterministic (reduction @d)\n\nend deterministic\n\nend sentence\n\nsection TM\n\ndef tape_of (x : list Γ) : ℕ → language Γ\n| 0 := ␤\n| (n + 1) := if h : n < x.length then language.chr (x.nth_le n h) else ␣\n\n-- ␤ x₁ x₂ ... xₙ ␣ ␣ ␣ ...\n\n@[simp] lemma tape_of_of_zero {x : list Γ} : tape_of x 0 = ␤ := by simp[tape_of]\n\n@[simp] lemma tape_of_of_lt {n} {x : list Γ} (gt : n > 0) (le : n ≤ x.length) :\n tape_of x n = language.chr (x.nth_le (n - 1) (by { cases n, { simp at gt, contradiction }, { simpa using nat.succ_le_iff.mp le} })) :=\nby { cases n, { simp at gt, contradiction },\n { simp[tape_of, show n < x.length, from nat.succ_le_iff.mp le] } }\n\n@[simp] lemma tape_of_list_of_ge {n} {x : list Γ} (h : n ≥ x.length + 1) : tape_of x n = ␣ :=\nby { cases n, { simp at h, contradiction },\n { simp[tape_of], have : n ≥ x.length, exact nat.succ_le_succ_iff.mp h, exact nat.le_lt_antisymm this } }\n\nstructure fun_time_bounded_computable_by_NDTM (f : vector (list Γ) ι → vector (list Γ) ι) (T : ℕ → ℕ) :=\n(Q : Type*)\n(Q_fin : finite Q)\n(Q_state : state_lang Q)\n(σ : sentence (language Γ) Q ι)\n(reduction : ∀ (X : vector (list Γ) ι), \n model.is_halt_in_step σ (T X.length) (⟦start, X.map tape_of, default⟧) ∧\n ⟦start, X.map tape_of, default⟧ ⟶^(≤ T X.length)[σ]↓ ⟦halt, (f X).map tape_of, default⟧)\n\nstructure fun_time_bounded_computable_by_TM (f : vector (list Γ) ι → vector (list Γ) ι) (T : ℕ → ℕ)\n extends fun_time_bounded_computable_by_NDTM f T :=\n(deterministic : σ.deterministic)\n\nend TM\n\nnamespace sentence\nopen model sentence.deterministic relation\nvariables {R : Type*} [state_lang R] (f : Q → R) {σ : sentence Γ Q ι}\n\n@[simp] def word.map_q : word Γ Q ι → word Γ R ι\n| ⟮c, z; u | q, x⟯ := ⟮f c, z; u | f q, x⟯\n\n@[simp] def map_q (σ : sentence Γ Q ι) (f : Q → R) (H : ∀ c z u q x, ⟮c, z; u | q, x⟯ ∈ σ → f q ≠ halt ∧ f c ≠ start) :\n sentence Γ R ι :=\n{ carrier := word.map_q f '' σ,\n proper' := by { rintros c z u q x ⟨⟨c', z', u', q', x'⟩, h, eqn⟩,\n simp at eqn, rcases eqn with ⟨rfl, rfl, rfl, rfl, rfl⟩, exact H _ _ _ _ _ h } }\n\nend sentence\n\nnamespace model\nopen sentence sentence.deterministic relation\nvariables {m₁ m₂ m₃ : model Γ Q ι} {σ : sentence Γ Q ι}\n\n@[simp] lemma reduct_tape_read {T : vector (ℕ → Γ) ι} {H : vector ℕ ι} : reduct_tape T H (read T H) = T :=\nby { ext, simp, rintros rfl, refl }\n\n@[simp] lemma reduct_head_Stay {H : vector ℕ ι} : reduct_head H instruction.Stay = H :=\nby { ext, simp, }\n\nlemma reduction.iff {q₁ q₂ : Q} {T₁ T₂ : vector (ℕ → Γ) ι} {H₁ H₂ : vector ℕ ι} :\n (⟦q₁, T₁, H₁⟧ ⟶¹[σ] ⟦q₂, T₂, H₂⟧) ↔\n (∃ (z : vector Γ ι) (u : vector instruction ι), ⟮q₂, z; u | q₁, read T₁ H₁⟯ ∈ σ ∧ T₂ = reduct_tape T₁ H₁ z ∧ H₂ = reduct_head H₁ u) :=\n⟨by { rintros ⟨_, _, _, _, z, u, mem⟩, refine ⟨z, u, mem, rfl, rfl⟩ },\n by { rintros ⟨z, u, mem, rfl, rfl⟩, refine ⟨_, _, _, _, z, u, mem⟩ }⟩\n\n@[simp] lemma time_bounded_reductions.refl {s} : m₁ ⟶^(≤ s)[σ] m₁ := power_le.refl\n\nlemma time_reductions.refl : m₁ ⟶^(0)[σ] m₁ := power.zero _\n\n@[simp] lemma time_reductions_zero_iff : (m₁ ⟶^(0)[σ] m₂) ↔ m₁ = m₂ := power.zero_iff\n\nlemma time_bounded_reductions.of_le {s₁ s₂} (le : s₁ ≤ s₂) (h : m₁ ⟶^(≤ s₁)[σ] m₂) :\n m₁ ⟶^(≤ s₂)[σ] m₂ := power_le.of_le le h\n\nlemma time_reductions.add {s₁ s₂} (h₁ : m₁ ⟶^(s₁)[σ] m₂) (h₂ : m₂ ⟶^(s₂)[σ] m₃) :\n m₁ ⟶^(s₁ + s₂)[σ] m₃ := power.add h₁ h₂\n\nlemma time_bounded_reductions.add {s₁ s₂} (h₁ : m₁ ⟶^(≤ s₁)[σ] m₂) (h₂ : m₂ ⟶^(≤ s₂)[σ] m₃) :\n m₁ ⟶^(≤ s₁ + s₂)[σ] m₃ := power_le.add h₁ h₂\n\nlemma time_bounded_reductions.sum {m : ℕ → model Γ Q ι} {s : ℕ → ℕ}\n (h : ∀ k, m k ⟶^(≤ s k)[σ] m (k + 1)) (k : ℕ) : (m 0) ⟶^(≤ ∑ i in finset.range k, s i)[σ] (m k) :=\nby { induction k with k IH, { simp }, { simpa[finset.sum_range_succ] using IH.add (h k) } }\n\nlemma reduction.of_ss (r : m₁ ⟶¹[σ] m₂) {τ : sentence Γ Q ι} (ss : σ ≤ τ) : m₁ ⟶¹[τ] m₂ :=\nby { rcases r with ⟨q, T, H, c, z, u, mem⟩, refine ⟨_, _, _, _, _, _, ss mem⟩ }\n\nlemma time_reductions.of_ss {n} (r : m₁ ⟶^(n)[σ] m₂) {τ : sentence Γ Q ι} (ss : σ ≤ τ) : m₁ ⟶^(n)[τ] m₂ :=\nby { induction n with n IH generalizing m₂, { rcases r, simp },\n { rcases r with (_ | ⟨_, _, m₁₁, _, r₁_₁₁, r₁₁_₂⟩), exact (IH r₁_₁₁).succ (r₁₁_₂.of_ss ss) } }\n\nlemma time_bounded_reductions.of_ss {k} (r : m₁ ⟶^(≤ k)[σ] m₂) {τ : sentence Γ Q ι} (ss : σ ≤ τ) : m₁ ⟶^(≤ k)[τ] m₂ :=\nby { rcases r with ⟨n, le, r⟩, refine ⟨n, le, time_reductions.of_ss r ss⟩ }\n\nsection\nvariables {R : Type*} [state_lang R] (f : Q → R)\n\n@[simp] def map_q : model Γ Q ι → model Γ R ι\n| ⟦q, T, H⟧ := ⟦f q, T, H⟧\n\ninstance [has_coe Q R] : has_coe (model Γ Q ι) (model Γ R ι) := ⟨λ m, m.map_q coe⟩ \n\nvariables (m m' : model Γ Q ι) {f}\n\n@[simp] lemma map_q_tape (m : model Γ Q ι) : (m.map_q f).tape = m.tape := by cases m; simp\n\n@[simp] lemma map_q_head (m : model Γ Q ι) : (m.map_q f).head = m.head := by cases m; simp\n\n@[simp] lemma map_q_state (m : model Γ Q ι) : (m.map_q f).state = f m.state := by cases m; simp\n\nvariables (f)\n\nlemma reduction.map_q {H} (h : m₁ ⟶¹[σ] m₂) : m₁.map_q f ⟶¹[σ.map_q f H] m₂.map_q f :=\nby { rcases h with ⟨q, T, H, c, z, u, mem⟩, simp, refine ⟨_, _, _, _, _, _, _⟩, simp[sentence.mem_def], refine ⟨_, mem, by simp⟩ }\n\nlemma time_reductions.map_q {H} {n} (h : m₁ ⟶^(n)[σ] m₂) : m₁.map_q f ⟶^(n)[σ.map_q f H] m₂.map_q f :=\nby { induction n with n IH generalizing m₂, { rcases h, simp },\n { rcases h with (_ | ⟨_, _, m₁₁, _, r₁_₁₁, r₁₁_₂⟩), refine (IH r₁_₁₁).succ (r₁₁_₂.map_q f) } }\n\nlemma time_bounded_reduction.map_q {H} {k} (h : m₁ ⟶^(≤ k)[σ] m₂) : m₁.map_q f ⟶^(≤ k)[σ.map_q f H] m₂.map_q f :=\nby { rcases h with ⟨n, le, r⟩, refine ⟨n, le, time_reductions.map_q f r⟩ }\n\nvariables {f}\n\nlemma deterministic.map_q {H} (inj : function.injective f) (d : deterministic σ) : deterministic (σ.map_q f H) :=\nbegin\n rintros r x d₁ d₂ z₁ z₂ u₁ u₂ h₁ h₂,\n rcases h₁ with ⟨⟨c₁, z₁', u₁', q₁, x₁'⟩, mem₁, eq₁⟩,\n have : f c₁ = d₁ ∧ z₁ = z₁' ∧ u₁ = u₁' ∧ f q₁ = r ∧ x = x₁', { simp at eq₁, simp[eq₁] },\n rcases this with ⟨rfl, rfl, rfl, rfl, rfl⟩,\n rcases h₂ with ⟨⟨c₂, z₂', u₂', q₂, x₂'⟩, mem₂, eq₂⟩,\n have : f c₂ = d₂ ∧ z₂ = z₂' ∧ u₂ = u₂' ∧ f q₁ = f q₂ ∧ x = x₂', { simp at eq₂, simp[eq₂] },\n rcases this with ⟨rfl, rfl, rfl, eqn, rfl⟩,\n have : q₁ = q₂, from (inj eqn), rcases this with rfl,\n simp [d mem₁ mem₂]\nend\n\nend\n\nvariables {R : Type v} [state_lang R]\n\nnamespace sentence\nvariables {Q R} (q c : Q) (h : q ≠ halt ∧ c ≠ start) \n\ninductive fix_q_aux : word Γ Q ι → Prop\n| intro : ∀ (z : vector Γ ι), fix_q_aux ⟮c, z; instruction.Stay | q, z⟯\n\ndef fix_q (q c : Q) (h : q ≠ halt ∧ c ≠ start) : sentence Γ Q ι :=\n{ carrier := fix_q_aux q c,\n proper' := λ c' z u q' x, by { rintros ⟨⟩, exact h } } \n\n@[simp] lemma fix_q_mem (z : vector Γ ι) :\n ⟮c, z; instruction.Stay | q, z⟯ ∈ (fix_q q c h : sentence Γ Q ι) :=\nfix_q_aux.intro _\n\nlemma fix_q_mem_iff {c z u q x q₁ q₂ h} :\n ⟮c, z; u| q, x⟯ ∈ (fix_q q₁ q₂ h : sentence Γ Q ι) ↔ c = q₂ ∧ z = x ∧ q = q₁ ∧ u = instruction.Stay :=\n⟨by { rintros ⟨⟩, simp; refl }, by { rintros ⟨rfl, rfl, rfl, rfl⟩, exact fix_q_aux.intro _ }⟩\n\nlemma fix_q.deterministic : deterministic (fix_q q c h : sentence Γ Q ι) :=\nby { rintros q' x c₁ c₂ z₁ z₂ u₁ u₂ h₁ h₂, rcases h₁, rcases h₂, simp }\n\n@[simp] lemma fix_q_reduction (T : vector (ℕ → Γ) ι) (H : vector ℕ ι) : ⟦q, T, H⟧ ⟶¹[fix_q q c h] ⟦c, T, H⟧ :=\nreduction.iff.mpr ⟨read T H, instruction.Stay, by simp, by simp⟩\n\ninstance : has_union (sentence Γ Q ι) := ⟨λ σ τ,\n{ carrier := σ ∪ τ,\n proper' := by { rintros c z u q x (h | h), { exact σ.proper h }, { exact τ.proper h } } }⟩\n\ndef deterministic.union {σ τ : sentence Γ Q ι} (d₁ : deterministic σ) (d₂ : deterministic τ) \n (h : ∀ {q x c₁ c₂ z₁ z₂ u₁ u₂}, ⟮c₁, z₁; u₁ | q, x⟯ ∈ σ → ⟮c₂, z₂; u₂ | q, x⟯ ∈ τ → c₁ = c₂ ∧ z₁ = z₂ ∧ u₁ = u₂) :\n deterministic (σ ∪ τ) :=\nbegin\n rintros q x c₁ c₂ z₁ z₂ u₁ u₂ (h₁ | h₁) (h₂ | h₂),\n { exact d₁ h₁ h₂ }, { exact h h₁ h₂ }, { simp [h h₂ h₁] }, { exact d₂ h₁ h₂ }\nend\n\ninstance : has_Sup (sentence Γ Q ι) := ⟨λ s, \n{ carrier := ⋃₀ (carrier '' s),\n proper' := λ c z u q x h, by { simp at h, rcases h with ⟨σ, _, hσ⟩, exact σ.proper hσ } }⟩\n\nlemma Sup_carrier (s : set (sentence Γ Q ι)) : ↑(Sup s) = ⋃₀ (carrier '' s) := by refl\n\nlemma coe_supr {α : Sort*} {f : α → sentence Γ Q ι} : (↑(⨆ i, f i) : set (word Γ Q ι)) = ⋃ i, (f i) :=\nby { unfold supr, rw [Sup_carrier], simp, refl }\n\ndef deterministic.Sup {s : set (sentence Γ Q ι)} (d : ∀ σ ∈ s, deterministic σ) \n (h : ∀ (σ ∈ s) (τ ∈ s) {q x c₁ c₂ z₁ z₂ u₁ u₂},\n ⟮c₁, z₁; u₁ | q, x⟯ ∈ σ → ⟮c₂, z₂; u₂ | q, x⟯ ∈ τ → c₁ = c₂ ∧ z₁ = z₂ ∧ u₁ = u₂) :\n deterministic (Sup s) :=\nbegin\n rintros q x c₁ c₂ z₁ z₂ u₁ u₂ ⟨_, ⟨σ, hσs, rfl⟩, hσ⟩ ⟨_, ⟨τ, hτs, rfl⟩, hτ⟩, \n refine h _ hσs _ hτs hσ hτ\nend\n\ndef comp_suml (σ : sentence Γ Q ι) : sentence Γ (Q ⊕ R) ι := σ.map_q sum.inl (by { intros _ _ _ _ _ h, unfold halt start, simp[σ.proper h] })\n\ndef comp_sumr (τ : sentence Γ R ι) : sentence Γ (Q ⊕ R) ι := τ.map_q sum.inr (by { intros _ _ _ _ _ h, unfold halt start, simp[τ.proper h] })\n\ndef comp (σ : sentence Γ Q ι) (τ : sentence Γ R ι) : sentence Γ (Q ⊕ R) ι :=\n(σ.map_q sum.inl (by { intros _ _ _ _ _ h, unfold halt start, simp[σ.proper h] })) ∪\n(τ.map_q sum.inr (by { intros _ _ _ _ _ h, unfold halt start, simp[τ.proper h] })) ∪\n(fix_q (sum.inl (halt : Q)) (sum.inr (start : R)) (by unfold halt start; simp))\n\ninfix ` ▷ `:80 := comp\n\nlemma comp.deterministic {σ : sentence Γ Q ι} {τ : sentence Γ R ι}\n (d₁ : deterministic σ) (d₂ : deterministic τ) : deterministic (σ ▷ τ) :=\nbegin\n refine (deterministic.union (deterministic.union (deterministic.map_q sum.inl_injective d₁) (deterministic.map_q sum.inr_injective d₂) _)\n (fix_q.deterministic _ _ _) _),\n { rintros (q | r) _ _ _ _ _ _ _ ⟨⟨c₁, z₁, u₁, q, x⟩, mem₁, eqn₁⟩ ⟨⟨c₂, z₂, u₂, q', x'⟩, mem₂, eqn₂⟩,\n { simp at eqn₂, contradiction },\n { simp at eqn₁, contradiction } },\n { rintros _ _ _ _ _ _ _ _ (⟨⟨c, z, u, q, x⟩, mem, eqn⟩ | ⟨⟨c, z, u, q, x⟩, mem, eqn⟩) ⟨⟩,\n { simp at eqn, rcases eqn with ⟨rfl, rfl, rfl, rfl, rfl⟩, exfalso, simpa using mem },\n { simp at eqn, contradiction } }\nend\n\ndef dsum (σ : sentence Γ Q ι) (τ : sentence Γ R ι) (c : Q → R → Prop) : sentence Γ (Q ⊕ R) ι :=\n(σ.map_q sum.inl (by { intros _ _ _ _ _ h, unfold halt start, simp[σ.proper h] })) ∪\n(τ.map_q sum.inr (by { intros _ _ _ _ _ h, unfold halt start, simp[τ.proper h] })) ∪\n(⨆ (q : Q) (r : R) (h : c q r), (fix_q (sum.inl q) (sum.inr r) (by unfold halt start; simp)))\n\nlemma dsum.deterministic {σ : sentence Γ Q ι} {τ : sentence Γ R ι}\n (d₁ : deterministic σ) (d₂ : deterministic τ) (c : Q → R → Prop)\n (dc : ∀ q r₁ r₂, c q r₁ → c q r₂ → r₁ = r₂)\n (hc : ∀ q r, c q r → σ.is_halt q) : deterministic (dsum σ τ c) :=\nbegin\n refine (deterministic.union\n (deterministic.union (deterministic.map_q sum.inl_injective d₁) (deterministic.map_q sum.inr_injective d₂) _)\n (deterministic.Sup _ _) _),\n { rintros (q | r) _ _ _ _ _ _ _ ⟨⟨c₁, z₁, u₁, q, x⟩, mem₁, eqn₁⟩ ⟨⟨c₂, z₂, u₂, q', x'⟩, mem₂, eqn₂⟩,\n { simp at eqn₂, contradiction },\n { simp at eqn₁, contradiction } },\n { rintros σ ⟨q, rfl⟩, show (⨆ r (h : c q r), fix_q (sum.inl q) (sum.inr r) _).deterministic,\n refine deterministic.Sup _ _,\n { rintros _ ⟨r, rfl⟩, refine deterministic.Sup (by simpa using λ _, fix_q.deterministic _ _ _) _,\n { rintros _ ⟨_, rfl⟩ _ ⟨_, rfl⟩ (q | r); { intros _ _ _ _ _ _ _ h₁ h₂, exact fix_q.deterministic _ _ _ h₁ h₂ } } },\n { rintros _ ⟨r₁, rfl⟩ _ ⟨r₂, rfl⟩ (q' | r');\n { rintros _ _ _ _ _ _ _ ⟨_, ⟨_, ⟨hc₁, rfl⟩, rfl⟩, h₁⟩ ⟨_, ⟨_, ⟨hc₂, rfl⟩, rfl⟩, h₂⟩,\n have : r₁ = r₂, from dc _ _ _ hc₁ hc₂, rcases this with rfl,\n exact fix_q.deterministic _ _ (by unfold halt start; simp) h₁ h₂ } } },\n { rintros _ ⟨q₁, rfl⟩ _ ⟨q₂, rfl⟩ (q | r),\n { rintros _ _ _ _ _ _ _\n ⟨_, ⟨_, ⟨r₁, rfl⟩, rfl⟩, ⟨_, ⟨_, ⟨hc₁, rfl⟩, rfl⟩, h₁⟩⟩\n ⟨_, ⟨_, ⟨r₂, rfl⟩, rfl⟩, ⟨_, ⟨_, ⟨hc₂, rfl⟩, rfl⟩, h₂⟩⟩,\n simp at h₁ h₂,\n have : c₁ = sum.inr r₁ ∧ z₁ = x ∧ q = q₁ ∧ u₁ = instruction.Stay,\n { simpa using fix_q_mem_iff.mp h₁, unfold halt start; simp },\n rcases this with ⟨rfl, rfl, rfl, rfl⟩,\n have : c₂ = sum.inr r₂ ∧ z₂ = z₁ ∧ q = q₂ ∧ u₂ = instruction.Stay,\n { simpa using fix_q_mem_iff.mp h₂, unfold halt start; simp },\n rcases this with ⟨rfl, rfl, rfl, rfl⟩,\n have : r₁ = r₂, from dc _ _ _ hc₁ hc₂, rcases this with rfl,\n simp },\n { simp, rintros _ _ _ _ _ _ _\n ⟨_, ⟨_, ⟨r₁, rfl⟩, rfl⟩, ⟨_, ⟨_, ⟨hc₁, rfl⟩, rfl⟩, h₁⟩⟩ _,\n have : false, { simpa using (fix_q_mem_iff.mp h₁), unfold start halt; simp },\n contradiction } },\n { rintros (q | r),\n { rintros x _ _ _ _ _ _ (⟨⟨c₁, z₁, u₁, q₁, x₁⟩, wmem, hw⟩ | ⟨⟨c₁, z₁, u₁, q₁, x₁⟩, wmem, hw⟩),\n { simp at hw, rcases hw with ⟨rfl, rfl, rfl, rfl, rfl⟩,\n rintros ⟨_, ⟨_, ⟨q', rfl⟩, rfl⟩, ⟨_, ⟨_, ⟨r', rfl⟩, rfl⟩, H, ⟨_, ⟨hc', rfl⟩, rfl⟩, h₁⟩⟩,\n have : q₁ = q',\n { have := fix_q_mem_iff.mp h₁, simp at this, rcases this with ⟨rfl, rfl, rfl, rfl⟩; refl,\n unfold start halt; simp },\n rcases this with rfl,\n have : false := hc _ _ hc' wmem, contradiction },\n { simp at hw, contradiction } },\n { rintros x _ _ _ _ _ _ (⟨⟨c₁, z₁, u₁, q₁, x₁⟩, wmem, hw⟩ | ⟨⟨c₁, z₁, u₁, q₁, x₁⟩, wmem, hw⟩), \n { simp at hw, contradiction },\n { simp at hw, rcases hw with ⟨rfl, rfl, rfl, rfl, rfl⟩,\n rintros ⟨_, ⟨_, ⟨q', rfl⟩, rfl⟩, ⟨_, ⟨_, ⟨r', rfl⟩, rfl⟩, H, ⟨_, ⟨hc', rfl⟩, rfl⟩, h₁⟩⟩,\n have : false, { have := fix_q_mem_iff.mp h₁, simpa using this, unfold start halt; simp },\n contradiction } } }\nend\n\nend sentence\n\nlemma time_reductions.comp_aux {σ : sentence Γ Q ι} {τ : sentence Γ R ι} {n₁ n₂} {q r T₁ T₂ T₃ H₁ H₂ H₃}\n (h₁ : ⟦q, T₁, H₁⟧ ⟶^(n₁)[σ] ⟦halt, T₂, H₂⟧) (h₂ : ⟦start, T₂, H₂⟧ ⟶^(n₂)[τ] ⟦r, T₃, H₃⟧) :\n ⟦sum.inl q, T₁, H₁⟧ ⟶^(n₁ + n₂ + 1)[σ ▷ τ] ⟦sum.inr r, T₃, H₃⟧ :=\nbegin\n have h₁ : ⟦sum.inl q, T₁, H₁⟧ ⟶^(n₁)[σ ▷ τ] ⟦sum.inl halt, T₂, H₂⟧,\n from time_reductions.of_ss (time_reductions.map_q sum.inl h₁)\n (by { simp[(▷)], refine set.subset_union_of_subset_left (set.subset_union_left _ _) _,\n { intros _ _ _ _ _ h, unfold halt start, simp[σ.proper h] } }),\n have h : ⟦sum.inl halt, T₂, H₂⟧ ⟶¹[σ ▷ τ] ⟦sum.inr start, T₂, H₂⟧,\n from reduction.of_ss (sentence.fix_q_reduction _ _ _ _ _)\n (by { simp[(▷)], refine set.subset_union_right _ _, { unfold halt start; simp } }),\n have h₂ : ⟦sum.inr start, T₂, H₂⟧ ⟶^(n₂)[σ ▷ τ] ⟦sum.inr r, T₃, H₃⟧,\n from time_reductions.of_ss (time_reductions.map_q sum.inr h₂)\n (by { simp[(▷)], refine set.subset_union_of_subset_left (set.subset_union_right _ _) _,\n { intros _ _ _ _ _ h, unfold halt start, simp[τ.proper h] } }),\n simpa[show n₁.succ + n₂ = n₁ + n₂ + 1, by omega] using (h₁.succ h).add h₂\nend\n\nlemma time_reductions.comp {σ : sentence Γ Q ι} {τ : sentence Γ R ι} {n₁ n₂ : ℕ} {T₁ T₂ T₃ H₁ H₂ H₃}\n (h₁ : ⟦start, T₁, H₁⟧ ⟶^(n₁)[σ] ⟦halt, T₂, H₂⟧) (h₂ : ⟦start, T₂, H₂⟧ ⟶^(n₂)[τ] ⟦halt, T₃, H₃⟧) :\n ⟦start, T₁, H₁⟧ ⟶^(n₁ + n₂ + 1)[σ ▷ τ] ⟦halt, T₃, H₃⟧ :=\ntime_reductions.comp_aux h₁ h₂\n\nlemma time_bounded_reductions.comp {σ : sentence Γ Q ι} {τ : sentence Γ R ι} {k₁ k₂ : ℕ} {T₁ T₂ T₃ H₁ H₂ H₃}\n (h₁ : ⟦start, T₁, H₁⟧ ⟶^(≤ k₁)[σ] ⟦halt, T₂, H₂⟧) (h₂ : ⟦start, T₂, H₂⟧ ⟶^(≤ k₂)[τ] ⟦halt, T₃, H₃⟧) :\n ⟦start, T₁, H₁⟧ ⟶^(≤ k₁ + k₂ + 1)[σ ▷ τ] ⟦halt, T₃, H₃⟧ :=\nby { rcases h₁ with ⟨n₁, le₁, h₁⟩, rcases h₂ with ⟨n₂, le₂, h₂⟩, refine ⟨n₁ + n₂ + 1, by linarith, time_reductions.comp h₁ h₂⟩ }\n\nlemma time_reductions.dsum_left {σ : sentence Γ Q ι} {τ : sentence Γ R ι} {q₁ q₂ T₁ T₂ H₁ H₂} {n}\n (h : ⟦q₁, T₁, H₁⟧ ⟶^(n)[σ] ⟦q₂, T₂, H₂⟧) (φ : Q → R → Prop) :\n ⟦sum.inl q₁, T₁, H₁⟧ ⟶^(n)[sentence.dsum σ τ φ] ⟦sum.inl q₂, T₂, H₂⟧ :=\nby exact time_reductions.of_ss (time_reductions.map_q sum.inl h)\n (by { simp, refine set.subset_union_of_subset_left (set.subset_union_left _ _) _,\n { intros _ _ _ _ _ h, unfold halt start, simp[σ.proper h] } })\n\nlemma time_reductions.dsum_right {σ : sentence Γ Q ι} {τ : sentence Γ R ι} {r₁ r₂ T₁ T₂ H₁ H₂} {n}\n (h : ⟦r₁, T₁, H₁⟧ ⟶^(n)[τ] ⟦r₂, T₂, H₂⟧) (φ : Q → R → Prop) :\n ⟦sum.inr r₁, T₁, H₁⟧ ⟶^(n)[sentence.dsum σ τ φ] ⟦sum.inr r₂, T₂, H₂⟧ :=\nby exact time_reductions.of_ss (time_reductions.map_q sum.inr h)\n (by { simp, refine set.subset_union_of_subset_left (set.subset_union_right _ _) _,\n { intros _ _ _ _ _ h, unfold halt start, simp[τ.proper h] } })\n\nlemma time_reductions.dsum {σ : sentence Γ Q ι} {τ : sentence Γ R ι} {n₁ n₂} {q₁ q₂ r₂ r₃ T₁ T₂ T₃ H₁ H₂ H₃}\n (φ : Q → R → Prop) (h : φ q₂ r₂)\n (h₁ : ⟦q₁, T₁, H₁⟧ ⟶^(n₁)[σ] ⟦q₂, T₂, H₂⟧) (h₂ : ⟦r₂, T₂, H₂⟧ ⟶^(n₂)[τ] ⟦r₃, T₃, H₃⟧) :\n ⟦sum.inl q₁, T₁, H₁⟧ ⟶^(n₁ + n₂ + 1)[sentence.dsum σ τ φ] ⟦sum.inr r₃, T₃, H₃⟧ :=\nbegin\n have h₁ : ⟦sum.inl q₁, T₁, H₁⟧ ⟶^(n₁)[sentence.dsum σ τ φ] ⟦sum.inl q₂, T₂, H₂⟧,\n from time_reductions.dsum_left h₁ φ,\n have h : ⟦sum.inl q₂, T₂, H₂⟧ ⟶¹[sentence.dsum σ τ φ] ⟦sum.inr r₂, T₂, H₂⟧,\n from reduction.of_ss (sentence.fix_q_reduction _ _ _ _ _)\n (by { refine set.subset_union_of_subset_right _ _, { unfold halt start; simp },\n simp[sentence.coe_supr], refine set.subset_Union₃ q₂ r₂ h }),\n have h₂ : ⟦sum.inr r₂, T₂, H₂⟧ ⟶^(n₂)[sentence.dsum σ τ φ] ⟦sum.inr r₃, T₃, H₃⟧,\n from time_reductions.dsum_right h₂ φ,\n simpa[show n₁.succ + n₂ = n₁ + n₂ + 1, by omega] using (h₁.succ h).add h₂\nend\n\nlemma time_bounded_reductions.dsum {σ : sentence Γ Q ι} {τ : sentence Γ R ι} {n₁ n₂} {q₁ q₂ r₂ r₃ T₁ T₂ T₃ H₁ H₂ H₃}\n (φ : Q → R → Prop) (h : φ q₂ r₂)\n (h₁ : ⟦q₁, T₁, H₁⟧ ⟶^(≤ n₁)[σ] ⟦q₂, T₂, H₂⟧) (h₂ : ⟦r₂, T₂, H₂⟧ ⟶^(≤ n₂)[τ] ⟦r₃, T₃, H₃⟧) :\n ⟦sum.inl q₁, T₁, H₁⟧ ⟶^(≤ n₁ + n₂ + 1)[sentence.dsum σ τ φ] ⟦sum.inr r₃, T₃, H₃⟧ :=\nby{ rcases h₁ with ⟨n₁, le₁, h₁⟩, rcases h₂ with ⟨n₂, le₂, h₂⟩,\n refine ⟨n₁ + n₂ + 1, by linarith, time_reductions.dsum φ h h₁ h₂⟩ }\n\nend model\n\nnamespace blang\nopen instruction model\nvariables (Γ Q ι) [inhabited Γ] [bfin Γ]\n\ndef list_less_than (k : ℕ) := {l : list (option bool) // l.length ≤ k}\n\ninstance (k : ℕ) : inhabited (list_less_than k) := ⟨⟨[], by simp⟩⟩\n\nnamespace read\n\ninductive state\n| intro (q : Q) (i : fin (bentropy Γ).succ) (v : vector (vector bool (bentropy Γ)) ι) : state\n\nvariables {Γ Q ι}\n\ninstance [state_lang Q] : state_lang (state Γ Q ι) :=\n⟨state.intro start 0 default, state.intro halt ⊤ default⟩\n\ndef δ : state Γ Q ι → vector bool ι → option (state Γ Q ι × vector bool ι × vector instruction ι)\n| ⟨q, i, v⟩ x := if h : i < ⊤ then \n let newstate : state Γ Q ι :=\n ⟨q, ⟨i + 1, nat.succ_lt_succ (fin.lt_top_iff.mp h)⟩, (v.sim_update_nth (vector.rep ⟨i, fin.lt_top_iff.mp h⟩) x)⟩ in \n some ⟨newstate, x, Right⟩ else none\n\n@[simp] lemma δ_top {q v x} : δ (⟨q, ⊤, v⟩ : state Γ Q ι) x = none := by simp[δ]\n\ndef σ : sentence bool (state Γ Q ι) ι := sentence.of_fun δ\n(by { unfold start halt,\n intros q x c z u eqn, split; rintros rfl,\n { simpa using eqn },\n { rcases q with ⟨q, i, v⟩, by_cases C : i < ⊤; simp[C, δ, fin.ext_iff] at eqn; contradiction } })\n\nsection\nvariables (v : vector (vector bool (bentropy Γ)) ι) (T : vector (ℕ → bool) ι) (H : vector ℕ ι)\n\nlemma σ_reduction (q : Q) (i : fin (bentropy Γ).succ) (h : i < ⊤) :\n ⟦⟨q, i, v⟩, T, H⟧ ⟶¹[σ]\n ⟦⟨q, ⟨i + 1, nat.succ_lt_succ (fin.lt_top_iff.mp h)⟩, \n v.sim_update_nth (vector.rep ⟨i, fin.lt_top_iff.mp h⟩) (read T H)⟩, T, H.map nat.succ⟧ :=\nreduction.iff.mpr (⟨read T H, Right, by simp[σ, δ, h], by simp, by ext; simp⟩)\n\n@[simp] lemma σ_is_halt (q : Q) (v : vector (vector bool (bentropy Γ)) ι) : σ.is_halt ⟨q, ⊤, v⟩ :=\nby intros c z u x; simp[σ]\n\ndef memory :\n fin (bentropy Γ).succ → vector (vector bool (bentropy Γ)) ι\n| ⟨0, _⟩ := v\n| ⟨s + 1, hn⟩ := (memory ⟨s, by omega⟩).sim_update_nth (vector.rep ⟨s, by omega⟩) (read T (H.map ((+) s)))\n\n@[simp] lemma memory_0 : memory v T H 0 = v := by unfold has_zero.zero; rw [memory]\n\nlemma σ_time_reductions (q : Q) :\n ∀ (s : fin (bentropy Γ).succ), ⟦⟨q, 0, v⟩, T, H⟧ ⟶^(s)[σ] ⟦⟨q, s, memory v T H s⟩, T, H.map ((+) s)⟧\n| ⟨0, _⟩ := by { simp, ext, simp, }\n| ⟨s + 1, hs⟩ := by { \n let s' : fin (bentropy Γ).succ := ⟨s, by omega⟩,\n have r : ⟦⟨q, 0, v⟩, T, H⟧ ⟶^(s)[σ] ⟦⟨q, ⟨s, _⟩, memory v T H ⟨s, _⟩⟩, T, H.map ((+) s)⟧,\n from σ_time_reductions ⟨s, by omega⟩,\n have : ⟦⟨q, ⟨s, _⟩, memory v T H ⟨s, _⟩⟩, T, H.map ((+) s)⟧ ⟶¹[σ] ⟦⟨q, ⟨s + 1, _⟩, memory v T H ⟨s + 1, _⟩⟩, T, _⟧,\n by simpa[memory] using\n σ_reduction (memory v T H s') T (H.map ((+) s)) q s' (by simp[fin.lt_top_iff]; exact nat.succ_lt_succ_iff.mp hs),\n rw [show (H.map ((+) s)).map nat.succ = H.map ((+) s.succ), by ext; simp[nat.succ_add]] at this,\n exact r.succ this }\n\nlemma memory_nth_nth_of_lt : ∀ (s : fin (bentropy Γ).succ) k i (h : ↑i < s), \n ((memory v T H s).nth k).nth i = T.nth k (i + H.nth k)\n| ⟨0, _⟩ k i hi := by simp at hi; contradiction\n| ⟨s + 1, hs⟩ k ⟨i, hi⟩ h := by { \n have : i = s ∨ i < s, from eq_or_lt_of_le (nat.lt_succ_iff.mp (by simpa using h)),\n rcases this with (rfl | lt); simp[memory, vector.nth_sim_update_nth_if],\n { have : s ≠ i, from ne_of_gt lt,\n simp[this],\n simpa using memory_nth_nth_of_lt ⟨s, lt_trans (lt_add_one s) hs⟩ k ⟨i, hi⟩ (by simpa using lt) } }\n\nlemma σ_time_reductions_top (q : Q) : ⟦⟨q, 0, v⟩, T, H⟧ ⟶^(bentropy Γ)[σ] ⟦⟨q, ⊤, memory v T H ⊤⟩, T, H.map ((+) (bentropy Γ))⟧ :=\nσ_time_reductions v T H q ⊤\n\nlemma memory_nth_nth (k i) : ((memory v T H ⊤).nth k).nth i = T.nth k (i + H.nth k) :=\nmemory_nth_nth_of_lt v T H ⊤ k i (by simp[fin.lt_top_iff]; exact fin.is_lt i)\n\nend\n\nend read\n\nnamespace write\n\ninductive state\n| intro (q : Q) (i : fin (bentropy Γ).succ) (v : vector (vector bool (bentropy Γ)) ι) (u : vector instruction ι) : state\n\nvariables {Γ Q ι}\n\ninstance [state_lang Q] : state_lang (state Γ Q ι) :=\n⟨state.intro start ⊤ default Stay, state.intro halt 0 default Stay⟩\n\ndef δ : state Γ Q ι → vector bool ι → option (state Γ Q ι × vector bool ι × vector instruction ι)\n| ⟨q, ⟨0, _⟩, v, u⟩ x := none\n| ⟨q, ⟨i + 1, hi⟩, v, u⟩ x := \n let newstate : state Γ Q ι := ⟨q, ⟨i, by omega⟩, v, u⟩,\n i' : fin (bentropy Γ) := ⟨i, nat.succ_lt_succ_iff.mp hi⟩ in \n some ⟨newstate, v.map (λ x, x.nth i'), Left⟩\n\n@[simp] lemma δ_top {q v x u} : δ (⟨q, 0, v, u⟩ : state Γ Q ι) x = none := by unfold has_zero.zero; rw [δ]\n\ndef σ : sentence bool (state Γ Q ι) ι := sentence.of_fun δ\n(by { unfold start halt,\n intros q x c z u eqn, split; rintros rfl,\n { simpa using eqn },\n { rcases q with ⟨q, ⟨i, hi⟩, v, u⟩, rcases i; simp[δ] at eqn,\n { contradiction },\n { have lt : i < bentropy Γ, from nat.succ_lt_succ_iff.mp hi,\n have eq : i = bentropy Γ, by simpa[fin.coe_top] using (fin.eq_iff_veq _ _).mp eqn.1.2.1,\n simp[eq] at lt, contradiction } } })\n\nsection\nvariables (v : vector (vector bool (bentropy Γ)) ι) (u : vector instruction ι) (T : vector (ℕ → bool) ι) (H : vector ℕ ι)\n\ndef σ_tape_reduct (i) :=\nvector.zip_with3 (λ (t : ℕ → bool) h (x : vector bool (bentropy Γ)) n, if n = h then x.nth i else t n) T H v\n\nlemma σ_reduction (q : Q) (i : ℕ) (hi) :\n ⟦⟨q, ⟨i + 1, hi⟩, v, u⟩, T, H⟧ ⟶¹[σ]\n ⟦⟨q, ⟨i, by omega⟩, v, u⟩, σ_tape_reduct v T H ⟨i, nat.succ_lt_succ_iff.mp hi⟩, H.map nat.pred⟧ :=\nreduction.iff.mpr (⟨v.map (λ x, x.nth ⟨i, (by omega)⟩), Left, by simp[σ, δ]; refl,\n by { simp[reduct_tape, σ_tape_reduct], ext, simp }, by { ext, simp, exact nat.pred_eq_sub_one _ }⟩)\n\n@[simp] lemma σ_is_halt (q : Q) : σ.is_halt ⟨q, 0, v, u⟩ :=\nλ c z u x, by simp[σ]\n\ndef Tape : fin (bentropy Γ).succ → vector (vector bool (bentropy Γ)) ι → vector (ℕ → bool) ι → vector ℕ ι → vector (ℕ → bool) ι\n| ⟨0, _⟩ v T H := T\n| ⟨s + 1, hn⟩ v T H := Tape ⟨s, by omega⟩ v (σ_tape_reduct v T H ⟨s, nat.succ_lt_succ_iff.mp hn⟩) (H.map nat.pred)\n\n@[simp] lemma Tape_0 : Tape 0 v T H = T := by unfold has_zero.zero; rw [Tape]\n\nlemma σ_time_reductions (q : Q) :\n ∀ (s : fin (bentropy Γ).succ) (T H), ⟦⟨q, s, v, u⟩, T, H⟧ ⟶^(s)[σ] ⟦⟨q, 0, v, u⟩, Tape s v T H, (H.map (λ h, h - s))⟧\n| ⟨0, _⟩ T H := by { simp, ext, simp }\n| ⟨s + 1, hs⟩ T H := by { \n let s' : fin (bentropy Γ).succ := ⟨s, by omega⟩,\n let s'' : fin (bentropy Γ) := ⟨s, by { exact nat.succ_lt_succ_iff.mp hs}⟩,\n have r : ⟦⟨q, ⟨s, _⟩, v, u⟩, _, H.map nat.pred⟧ ⟶^(s)[σ] ⟦⟨q, 0, v, u⟩, _, H.map (λ h, h - (s + 1))⟧,\n { have := σ_time_reductions ⟨s, by omega⟩ (σ_tape_reduct v T H ⟨s, by omega⟩) (H.map nat.pred), simp at this, \n rw[show (H.map nat.pred).map (λ h, h - s) = H.map (λ h, h - (s + 1)),\n by { ext; simp; rw[nat.pred_sub, nat.pred_eq_sub_one, tsub_tsub] }] at this,\n exact this },\n have : ⟦⟨q, ⟨s + 1, _⟩, v, u⟩, T, H⟧ ⟶¹[σ] ⟦⟨q, ⟨s, _⟩, v, u⟩, _, H.map nat.pred⟧,\n from σ_reduction v u T H q s hs,\n have : ⟦⟨q, ⟨s + 1, _⟩, v, u⟩, T, H⟧ ⟶^(s+1)[σ] ⟦⟨q, 0, v, u⟩, _, H.map (λ h, h - (s + 1))⟧,\n from relation.power.succ_inv this r,\n simpa[Tape, @sub_add_eq_sub_sub ℕ] using this }\n\nend\n\nend write\n\nend blang\n\n\nnamespace universal_tm\nvariables {Γ Q ι}\n\nabbreviation lang := word Γ Q ι ⊕ vector Γ ι\n\n\n\nend universal_tm\n\nend turing_machine", "meta": {"author": "iehality", "repo": "lean-computable-complexity", "sha": "deee56eddd42eba1ceb05e8a9d8a2cc354138f65", "save_path": "github-repos/lean/iehality-lean-computable-complexity", "path": "github-repos/lean/iehality-lean-computable-complexity/lean-computable-complexity-deee56eddd42eba1ceb05e8a9d8a2cc354138f65/src/tm.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46879062662624377, "lm_q2_score": 0.04336580293660674, "lm_q1q2_score": 0.020329481932802075}} {"text": "/-\n# Message Fields\n\nBuilding on the basic data definitions in [Core](Core.md), this module defines the message\nfields that group together related information, and which in turn are combined to\ndefine the messages.\n\nFor each field example text from an ATS message is provided, together with the corresponding\nLean value. Lean has a variety of ways to populate structure values, and all variants are\ndemonstrated.\n-/\n\nimport LeanSpec.FPL.Core\nimport LeanSpec.lib.Temporal\n\nopen Core Temporal\n\nnamespace FPL.Field\n\n/-\n## Field 7: Aircraft identification and SSR mode and code\n\nField 7 is concerned with how a flight is identified for communication with air traffic control.\n-/\nstructure Field7 where\n f7a : AircraftIdentification\n f7bc : Option SsrCode\n\n/-\n### Field 7 Example\n\n`-SAS912/A5100`\n-/\nexample := Field7.mk ⟨\"SAS912\", by simp⟩ (some ⟨\"5100\", by simp⟩)\n\n/-\n## Field 8: Flight rules and type of flight\n\nField 8 provides information that determines how a flight is handled.\n-/\nstructure Field8 where\n f8a : FlightRules\n f8b : Option TypeOfFlight\n\n/-\n### Field 8 Example\n\n`-IS`\n-/\nexample := Field8.mk .i (some .s)\n\n/-\n## Field 9: Number and type of aircraft and wake turbulence category\n\nField 9 provides information about the aircraft that will be used to conduct the flight.\n-/\nstructure Field9 where\n f9a : Option NumberOfAircraft -- only included for formation flights\n f9b : Option Doc8643.Designator -- `none` indicates ZZZZ (refer field 18 TYP)\n f9c : WakeTurbulenceCategory\n\n/-\n`-2FK27/M`\n-/\nexample := Field9.mk (some ⟨2, by simp⟩) (some ⟨\"FK27\", by simp⟩) .m\n\n/-\n### Field 9 Example\n\n`-ZZZZ/L`\n-/\nexample := Field9.mk none none .l\n\n/-\n## Field 10: Equipment and capabilities\n\nField 10 documents what equipment and capabilities the flight/aircraft has.\nThese items communicate what air traffic control can expect of the flight,\nand limitations placed on the flight.\n-/\n\nstructure Field10 where\n f10a : List CommNavAppCode -- empty list indicates `N`\n f10b : List SurveillanceCode -- empty list indicates `N`\n -- Exclude invalid combinations.\n inv : ¬ (.b1 ∈ f10b ∧ .b2 ∈ f10b) ∧\n ¬ (.u1 ∈ f10b ∧ .u2 ∈ f10b) ∧\n ¬ (.v1 ∈ f10b ∧ .v2 ∈ f10b)\n\n/-\n### Field 10 Example\n\n`-SAFR/SV1`\n-/\nexample := (⟨[.s, .a, .f, .r], [.s, .v1], by simp⟩ : Field10)\n\n/-\n## Field 13: Departure aerodrome and time\n\nField 13 concerns the departure point and departure time of the flight.\n\nA flight plan can be filed in the air, in which case AFIL is specified in the\ndeparture point field.\n-/\ninductive ADep\n | adep (_ : Doc7910.Designator)\n | afil\nderiving DecidableEq\n\ndef Field13a := Option ADep -- `none` indicates ZZZZ (refer field 18 DEP)\n\nstructure Field13 where\n f13a : Field13a\n f13b : DTG\n\n/-\n### Field 13 Examples\n\n`-EHAM0730`\n-/\nexample := Field13.mk (some (.adep ⟨\"EHAM\", by simp⟩)) 63072027000\n\n/-\n`-AFIL1625`\n-/\nexample : Field13 := ⟨some .afil, 63072059100⟩\n\n/-\nThe designator in Field 13, if there is one.\n-/\ndef Field13.desigOf : Field13 → Option Doc7910.Designator\n | ⟨some (.adep desig), _⟩ => desig\n | _ => none\n\n/-\n## Field 15: Route\n\nField 15 describes the route the aircraft will follow to go from departure to destination.\nThis includes the level/altitude the flight operates at, and the speed of the aircraft.\n\nClimbing between two levels, the upper limit can be specified, or _PLUS_ used to\nindicate there is no nominated upper level.\n-/\ninductive UpperLevel\n | level (_ : VerticalPositionOfAircraft)\n | plus\n\n/-\nIndication of the change in speed and level.\n-/\nstructure SpeedLevelChange where\n speed : TrueAirspeed\n level : VerticalPositionOfAircraft\n upper : Option UpperLevel\n\n/-\n### Speed/Level Change Example\n\n`N0540A055PLUS`\n-/\nexample : SpeedLevelChange where\n speed := ⟨⟨⟨540, sorry⟩, .kt, .ias, by simp⟩, sorry⟩\n level := ⟨5500, .feet, .altitude⟩\n upper := some .plus\n\n/-\nA specific point along the route, together with changes to speed, level and flight rules\nplanned to occur at the point.\n-/\nstructure RoutePoint where\n pos : Position\n chg : Option SpeedLevelChange\n frul : Option FlightRule\n\n/-\nBetween two points on a route, the aircraft can follow a documented ATS route, or\nproceed directly.\n-/\ninductive Connector\n | rte (_ :RouteDesignator)\n | dct\n\n/-\nA route element is a point (and associated data) followed by the path to\nthe next element. Either, but not both, may be omitted.\n-/\nstructure RouteElement where\n point : Option RoutePoint\n rte : Option Connector\n -- At least one of point or connecting route must be populated.\n inv : ¬ (point.isNone ∧ rte.isNone)\n\n/-\nThe named waypoint in a route element, if there is one.\n-/\ndef RouteElement.waypointOf : RouteElement → Option Waypoint\n | ⟨some rp, _, _⟩ => rp.pos.waypointOf\n | _ => none \n\n/-\nThe ATS route designator in a route element, if there is one.\n-/\ndef RouteElement.atsRteOf : RouteElement → Option RouteDesignator\n | ⟨_, some (.rte rd), _⟩ => rd\n | _ => none \n\n/-\nDoes the route element indicate _direct_ to the next point?\n-/\ndef RouteElement.isDct : RouteElement → Bool\n | ⟨_, some .dct, _⟩ => true\n | _ => false \n\n/-\nThe flight rules change in a route element, if there is one.\n-/\ndef RouteElement.ruleOf : RouteElement → Option FlightRule\n | ⟨some rp, _, _⟩ => rp.frul\n | _ => none \n\n/-\nIndicator the route description has been truncated.\n-/\ninductive Truncate | t\n\n/-\nThe route consists of:\n- optional standard instrument departure (SID);\n- the non-empty list of elements;\n- optional standard arrival route (STAR) or truncation indicator.\n-/\nstructure Route where\n sid : Option RouteDesignator\n elements : List RouteElement\n starOrTruncate : Option (RouteDesignator ⊕ Truncate)\n -- Must be at least one route element.\n inv : elements ≠ ∅ ∧\n -- Consecutive flight rules changes must be distinct.\n let rules := (elements.map RouteElement.ruleOf).reduceOption\n rules.Chain' (· ≠ ·) ∧\n -- DCT must be followed by an explicit point.\n elements.Chain' (·.isDct → ·.point.isSome) ∧\n -- An ATS route designator must connect to another designator or a named point.\n elements.Chain'\n (fun re₁ re₂ ↦ re₁.atsRteOf.isSome →\n re₂.waypointOf.isSome ∨ (re₂.point.isNone ∧ re₂.atsRteOf.isSome))\n\n/-\nThe list of named waypoints in a route.\n-/\ndef Route.waypoints (rte : Route) : List Waypoint :=\n (rte.elements.map RouteElement.waypointOf).reduceOption\n\n/-\nField 15 consists of:\n- the initial requested cruising speed;\n- the initial requested cruising level;\n- the route description.\n-/\nstructure Field15 where\n f15a : TrueAirspeed\n f15b : Option VerticalPositionOfAircraft -- `none` indicates VFR\n f15c : Route\n\n/-\n### Field 15 Example\n\n`-M079F380 DCT WOL H65 RAZZI Q29 LIZZI DCT`\n-/\ndef exElems := [\n RouteElement.mk none (some .dct) (by simp),\n RouteElement.mk (mkWpt ⟨\"WOL\", by simp⟩) (some (.rte ⟨\"H65\", by simp⟩)) (by simp),\n RouteElement.mk (mkWpt ⟨\"RAZZI\", by simp⟩) (some (.rte ⟨\"Q29\", by simp⟩)) (by simp),\n RouteElement.mk (mkWpt ⟨\"LIZZI\", by simp⟩) (some .dct) (by simp)\n]\nwhere mkWpt (wpt : Waypoint) : Option RoutePoint :=\n some ⟨.wpt wpt, none, none⟩\n\nexample := {\n f15a := ⟨⟨⟨0.79, sorry⟩, .mach, .tas, by simp⟩, by simp⟩, -- M079\n f15b := some ⟨380, .feet, .flightLevel⟩, -- F380\n f15c := ⟨none, exElems, none, sorry⟩ : Field15 -- DCT WOL H65 RAZZI Q29 LIZZI DCT\n}\n\n/-\n## Field 16: Destination aerodrome and total estimated elapsed time, destination alternate aerodrome(s)\n\nField 16 concerns the destination aerodrome, the flight time, and alternate destinations in the event\ndiversion is required.\n-/\ndef Field16a := Option Doc7910.Designator -- `none` indicates ZZZZ (refer field 18 DEST)\n\n/-\nUp to two alternates are allowed.\n-/\ndef maxAlternateDestinations := 2\n\n/-\nField 16 consists of:\n- the planned destination aerodrome;\n- the total estimated elapsed time (TEET) - i.e. the estimated flight duration;\n- alternate destination aerodromes in case of a diversion.\n-/\nstructure Field16 where\n f16a : Field16a\n f16b : Duration\n f16c : List Field16a\n -- TEET must be less than one day.\n inv : f16b < Duration.oneDay ∧\n -- Upper limit on number of alternate aerodromes.\n f16c.length ≤ maxAlternateDestinations\n\n/-\n### Field 16 Example\n\n`-EHAM0645 EBBR ZZZZ`\n-/\nexample := Field16.mk (some ⟨\"EHAM\", by simp⟩) 24300 [some ⟨\"EBBR\", by simp⟩, none] (by simp)\n\n/-\nAre a departure and destination aerodrome the same?\n-/\ndef adepIsAdes : Field13a → Field16a → Bool\n | none, none => True\n | some (.adep desig₁), some desig₂ => desig₁ = desig₂\n | _, _ => False\n\n/-\n## Field 17: Arrival aerodrome and time\n\nField 17 concerns the actual arrival point and time, which will differ from the\nplanned destination in the event of a diversion.\n\nField 17 consists of:\n- the actual arrival aerodrome designator;\n- the actual arrival time;\n- the name of the arrival aerodrome, if it has no designator.\n-/\n\nstructure Field17 where\n f17a : Option Doc7910.Designator -- `none` indicates ZZZZ\n f17b : DTG\n f17c : Option FreeText\n -- Exactly one of designator and aerodrome name must be populated.\n inv : f17a.isNone ↔ f17c.isSome\n\n/-\n### Field 17 Example\n\n`-ZZZZ1620 DEN HELDER`\n-/\nexample := Field17.mk none 63072058800 (some ⟨\"DEN HELDER\", by simp⟩)\n\n/-\n## Field 18: Other information\n\nField 18 contains diverse other information about the flight.\n\nThe flight plan framework is presently undergoing major revision to benefit from the latest\ninformation management best practices. The extant flight plan format has largely remained\nunchanged for over 50 years. Allowed changes are limited by the the need for backwards\ncompatibility. As a result, additional information has typically been added as extra\ndata in field 18, with the result it is a rather disparate collection. It also means\nthat related information is recorded in separate parts of the message. For example, codes\nthat indicate navigation capability are presented in field 10a, but more recent Performance\nBased Navigation (PBN) codes appears in item _PBN_ of field 18.\n\nUp to 8 PBN codes may be specified.\n-/\ndef maxPbnCodes := 8\n\n/-\nThe elapsed time from departure to a point en-route. Usually a point where control is passed\nbetween ATS providers.\n-/\nstructure ElapsedTimePoint where\n point : Doc7910.FIRDesignator ⊕ Position\n duration : Duration\n\n/-\nThe `<` order relation on EET points. Ordered by the duration.\n-/\ninstance : LT ElapsedTimePoint where\n lt et₁ et₂ := LT.lt et₁.duration et₂.duration\n\n/-\nThe `<` relation is decidable.\n-/\ninstance (x y : ElapsedTimePoint) : Decidable (x < y) :=\n inferInstanceAs (Decidable (x.duration < y.duration))\n\n/-\nA point on the route where a delay occurs. The flight goes _off plan_ for\nthe duration. An example is a law enforcement flight that intends to conduct\ncovert operations and does not want to provide details of where it is flying.\n-/\nstructure DelayPoint where\n point : Waypoint\n duration : Duration\n\n/-\nThe route to an alternate destination if the flight decides to divert en-route.\n-/\nstructure RouteToRevisedDestination where\n destination : Doc7910.Designator\n route : FreeText\n\n/-\nThe various items that make up field 18.\n-/\nstructure Field18 where\n sts : List SpecialHandling\n pbn : List PBNCode\n nav : Option FreeText\n com : Option FreeText\n dat : Option FreeText\n sur : Option FreeText\n dep : Option (NameAndPosition ⊕ ATSUnit)\n dest : Option NameAndPosition\n reg : List Registration\n eet : List ElapsedTimePoint\n sel : Option SelcalCode\n typ : List (Option NumberOfAircraft × AircraftType)\n code : Option AircraftAddress\n dle : List DelayPoint\n opr : Option FreeText\n orgn : Option FreeText\n per : Option AircraftPerformance\n altn : List NameAndPosition\n ralt : List LandingSite\n talt : List LandingSite\n rif : Option RouteToRevisedDestination\n rmk : Option FreeText\n -- Upper limit on number of PBN codes.\n inv : pbn.length ≤ maxPbnCodes ∧\n -- Upper limit on number of alternate aerodromes.\n altn.length ≤ maxAlternateDestinations ∧\n -- EETs must be presented in ascending order.\n eet.ascendingStrict\n\n/-\n### Field 18 Example\n\n`-PBN/A1B1C1D1O2S2T1 NAV/RNP2 REG/VHXYZ SEL/AFPQ CODE/7C6DDF OPR/FLYOU ORGN/YSSYABCO PER/C`\n-/\nexample : Field18 := {\n sts := [],\n pbn := [.a1, .b1, .c1, .d1, .o2, .s2, .t1],\n nav := some ⟨\"RNP2\", by simp⟩,\n com := none,\n dat := none,\n sur := none,\n dep := none,\n dest := none,\n reg := [⟨\"VHXYZ\", by simp⟩]\n eet := [],\n sel := some ⟨\"AFPQ\", by simp⟩,\n typ := [],\n code := some ⟨\"7C6DDF\", by simp⟩,\n dle := [],\n opr := some ⟨\"FLYOU\", by simp⟩,\n orgn := some ⟨\"YSSYABCO\", by simp⟩,\n per := some .c,\n altn := [],\n ralt := [],\n talt := [],\n rif := none,\n rmk := none,\n inv := sorry\n}\n\n\n/-\n## Field 22: Amendment\n\nField 22 specifies changes to an existing flight plan.\nIf any part of a field changes, the entire content of the new field\nmust be included in field 22, not just the sub-item that is changing.\n-/\nstructure Field22 where\n f7 : Option Field7\n f8 : Option Field8\n f9 : Option Field9\n f10 : Option Field10\n f13 : Option Field13\n f15 : Option Field15\n f16 : Option Field16\n f18 : Option Field18\n -- At least one amendment must be specified.\n inv : ¬ (f7.isNone ∧f8.isNone ∧ f9.isNone ∧ f10.isNone ∧ f13.isNone ∧ f15.isNone ∧ f16.isNone ∧ f18.isNone)\n\n/-\n### Field 22 Example\n\n`-8/IX-13/EDDN1230`\n-/\nexample : Field22 where\n f7 := none\n f8 := some ⟨.i, some .x⟩\n f9 := none\n f10 := none\n f13 := some ⟨some (.adep ⟨\"EDDN\", by simp⟩), 63072027000⟩\n f15 := none\n f16 := none\n f18 := none\n inv := by simp\n\n\n/-\n## Consistency checks between fields\n\nAs noted earlier, the legacy nature of the flight planning messages means related information\nis spread across disparate fields. As a result a number of constraints are required to ensure\nconsistency between fields. The majority of these relate to the relationship between field 18\nother fields.\n\n### Fields 8 and 15 (requested level)\n\n - If initial requested cruising level is VFR, initial flight rules must be V or Z.\n-/\ndef F8F15Level : Field8 → Field15 → Prop\n | f8, ⟨_, none, _⟩ => f8.f8a ∈ [.v, .z]\n | _, _ => True\n\n/-\n### Fields 8 and 15 (flight rules)\n\n- Rule changes only allowed if initial rules is Y or Z.\n- If initial rules is Y (IFR first), first change must be to VFR.\n- If initial rules is Z (VFR first), first change must be to IFR.\n-/\ndef F8F15Rule (f8 : Field8) (f15 : Field15) : Prop :=\n match (f15.f15c.elements.map RouteElement.ruleOf).reduceOption with\n | [] => f8.f8a ∈ [.i, .v]\n | .vfr :: _ => f8.f8a = .y\n | .ifr :: _ => f8.f8a = .z\n\n/-\n### Fields 9 and 18 (TYP)\n\n- If designator in field 9b, field 18 TYP not populated.\n- If ZZZZ in field 9b, aircraft type in field 18 TYP.\n-/\ndef F9F18Typ : Field9 → Option Field18 → Prop\n | -- If designator in 9b, 18 TYP not populated.\n {f9b := some _, ..}, none\n | {f9b := some _, ..}, some {typ := [], ..}\n | -- If ZZZZ in 9b, must have aircraft type in 18 TYP.\n {f9b := none, ..}, some {typ := _::_, ..} => True\n | -- Any other combination is invalid.\n _, _ => False\n\n/-\n### Fields 10 and 18 (STS)\n\n- Can't specify W (RVSM capable) in Field 10a and NONRVSM on Field 18 STS.\n-/\ndef F10F18Sts : Field10 → Option Field18 → Prop\n | f10, some f18 => ¬ (.w ∈ f10.f10a ∧ .nonrvsm ∈ f18.sts)\n | _, _ => True\n\n/-\n### Fields 10 and 18 (PBN)\n\n- If R specified in field 10a, PBN capability must be provided in Field 18 PBN.\n-/\ndef F10F18Pbn : Field10 → Option Field18 → Prop\n | f10, none => .r ∉ f10.f10a\n | f10, some f18 => .r ∈ f10.f10a ↔ f18.pbn ≠ ∅ \n\n/-\n### Fields 10 and 18 (COM/NAV/DAT)\n\n- If Z specified in field 10a, other information must be provided in at least one of COM,\nNAV or DAT in Field 18.\n-/\ndef F10F18Z : Field10 → Option Field18 → Prop\n | f10, none => .z ∉ f10.f10a\n | f10, some f18 => .z ∈ f10.f10a ↔ f18.com.isSome ∨ f18.nav.isSome ∨ f18.dat.isSome\n\n/-\n### Fields 13 and 18 (DEP)\n\n- If designator in field 13a, field 18 DEP not populated.\n- If ZZZZ in field 13a, departure point in field 18 DEP.\n- If AFIL in field 13a, ATS unit in field 18 DEP.\n-/\ndef F13F18Dep : Field13 → Option Field18 → Prop\n | -- If designator in 13a, 18 DEP not populated.\n ⟨(some (.adep _)), _⟩, none\n | ⟨some (.adep _), _⟩, some {dep := none, ..}\n | -- If ZZZZ in 13a, must have departure point in 18 DEP.\n ⟨none, _⟩, some {dep := some (.inl _), ..}\n | -- If AFIL in 13a, must have ATS unit in 18 DEP.\n ⟨some .afil, _⟩, some {dep := some (.inr _), ..} => True\n | -- Any other combination is invalid.\n _, _ => False\n\n/-\n### Fields 15 and 18 (DLE)\n\n- A delay point must be explicitly named in the route.\n-/\ndef F15F18Dle : Field15 → Option Field18 → Prop\n | f15, some f18 => f18.dle.map (·.point) ⊆ f15.f15c.waypoints\n | _, _ => True\n\n/-\n### Fields 16 and 18 (DEST)\n\n- If designator in field 16a, field 18 DEST not populated.\n- If ZZZZ in field 16a, destination point in field 18 DEST.\n-/\ndef F16F18Dest : Field16 → Option Field18 → Prop\n | -- If designator in 16a, 18 DEST not populated.\n {f16a := some _, ..}, none\n | {f16a := some _, ..}, some {dest := none, ..}\n | -- If ZZZZ in 16a, must have destination point in 18 DEST.\n {f16a := none, ..}, some {dest := some _, ..} => True\n | -- Any other combination is invalid.\n _, _ => False\n\n/-\n### Fields 16 and 18 (EET)\n\n- All EETs must be less than the flight duration.\n-/\ndef F16F18Eet : Field16 → Option Field18 → Prop\n | {f16b := teet, ..}, some f18 => f18.eet.all (·.duration < teet)\n | _, _ => True\n\n/-\n### Fields 16 and 18 (DLE)\n\n- The sum of the delays at the route points must be less than the flight duration.\n-/\ndef F16F18Dle : Field16 → Option Field18 → Prop\n | {f16b := teet, ..}, some f18 => (f18.dle.map (·.duration)).add 0 < teet\n | _, _ => True\n\n/-\n### Fields 16 and 18 (ALTN)\n\n- For each ZZZZ entry in Field 16c, there must be a corresponding entry in Field 18 ALTN.\n-/\ndef F16F18Altn : Field16 → Option Field18 → Prop\n | {f16c := [], ..}, none => True\n | {f16c := altn16, ..}, some {altn := altn18, ..}\n => (altn16.filter (·.isNone)).length = altn18.length\n | _, _ => False\n\n/-\n### Fields 16 and 17 (destination and arrival)\n\n- Destination, if provided, must differ from actual arrival aerodrome.\n-/\ndef F16F17Dest : Field16a → Option Field17 → Prop\n | some dest, some {f17a := some arr, ..} => dest ≠ arr\n | _, _ => True\n\nend FPL.Field", "meta": {"author": "paulch42", "repo": "lean-spec", "sha": "4755a25caf719f935bcc4d54bd8a86462c9aceb9", "save_path": "github-repos/lean/paulch42-lean-spec", "path": "github-repos/lean/paulch42-lean-spec/lean-spec-4755a25caf719f935bcc4d54bd8a86462c9aceb9/LeanSpec/FPL/Field.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4148988457967689, "lm_q2_score": 0.04885777412113743, "lm_q1q2_score": 0.020271034091059164}} {"text": "/-\nCopyright (c) 2017 Johannes Hölzl. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Johannes Hölzl, Jeremy Avigad\n\nTheory of filters on sets.\n-/\nimport order.galois_connection order.zorn\nimport data.set.finite data.list data.pfun\nimport algebra.pi_instances\nimport category.applicative\nopen lattice set\n\nuniverses u v w x y\n\nlocal attribute [instance] classical.prop_decidable\n\nnamespace lattice\nvariables {α : Type u} {ι : Sort v}\n\ndef complete_lattice.copy (c : complete_lattice α)\n (le : α → α → Prop) (eq_le : le = @complete_lattice.le α c)\n (top : α) (eq_top : top = @complete_lattice.top α c)\n (bot : α) (eq_bot : bot = @complete_lattice.bot α c)\n (sup : α → α → α) (eq_sup : sup = @complete_lattice.sup α c)\n (inf : α → α → α) (eq_inf : inf = @complete_lattice.inf α c)\n (Sup : set α → α) (eq_Sup : Sup = @complete_lattice.Sup α c)\n (Inf : set α → α) (eq_Inf : Inf = @complete_lattice.Inf α c) :\n complete_lattice α :=\nbegin\n refine { le := le, top := top, bot := bot, sup := sup, inf := inf, Sup := Sup, Inf := Inf, ..};\n subst_vars,\n exact @complete_lattice.le_refl α c,\n exact @complete_lattice.le_trans α c,\n exact @complete_lattice.le_antisymm α c,\n exact @complete_lattice.le_sup_left α c,\n exact @complete_lattice.le_sup_right α c,\n exact @complete_lattice.sup_le α c,\n exact @complete_lattice.inf_le_left α c,\n exact @complete_lattice.inf_le_right α c,\n exact @complete_lattice.le_inf α c,\n exact @complete_lattice.le_top α c,\n exact @complete_lattice.bot_le α c,\n exact @complete_lattice.le_Sup α c,\n exact @complete_lattice.Sup_le α c,\n exact @complete_lattice.Inf_le α c,\n exact @complete_lattice.le_Inf α c\nend\n\nend lattice\n\nopen set lattice\n\nsection order\nvariables {α : Type u} (r : α → α → Prop)\nlocal infix `≼` : 50 := r\n\nlemma directed_on_Union {r} {ι : Sort v} {f : ι → set α} (hd : directed (⊆) f)\n (h : ∀x, directed_on r (f x)) : directed_on r (⋃x, f x) :=\nby simp only [directed_on, exists_prop, mem_Union, exists_imp_distrib]; exact\nassume a₁ b₁ fb₁ a₂ b₂ fb₂,\nlet ⟨z, zb₁, zb₂⟩ := hd b₁ b₂,\n ⟨x, xf, xa₁, xa₂⟩ := h z a₁ (zb₁ fb₁) a₂ (zb₂ fb₂) in\n⟨x, ⟨z, xf⟩, xa₁, xa₂⟩\n\nend order\n\ntheorem directed_of_chain {α β r} [is_refl β r] {f : α → β} {c : set α}\n (h : zorn.chain (f ⁻¹'o r) c) :\n directed r (λx:{a:α // a ∈ c}, f (x.val)) :=\nassume ⟨a, ha⟩ ⟨b, hb⟩, classical.by_cases\n (assume : a = b, by simp only [this, exists_prop, and_self, subtype.exists];\n exact ⟨b, hb, refl _⟩)\n (assume : a ≠ b, (h a ha b hb this).elim\n (λ h : r (f a) (f b), ⟨⟨b, hb⟩, h, refl _⟩)\n (λ h : r (f b) (f a), ⟨⟨a, ha⟩, refl _, h⟩))\n\nstructure filter (α : Type*) :=\n(sets : set (set α))\n(univ_sets : set.univ ∈ sets)\n(sets_of_superset {x y} : x ∈ sets → x ⊆ y → y ∈ sets)\n(inter_sets {x y} : x ∈ sets → y ∈ sets → x ∩ y ∈ sets)\n\n/-- If `F` is a filter on `α`, and `U` a subset of `α` then we can write `U ∈ F` as on paper. -/\n@[reducible]\ninstance {α : Type*}: has_mem (set α) (filter α) := ⟨λ U F, U ∈ F.sets⟩\n\nnamespace filter\nvariables {α : Type u} {f g : filter α} {s t : set α}\n\nlemma filter_eq : ∀{f g : filter α}, f.sets = g.sets → f = g\n| ⟨a, _, _, _⟩ ⟨._, _, _, _⟩ rfl := rfl\n\nlemma filter_eq_iff : f = g ↔ f.sets = g.sets :=\n⟨congr_arg _, filter_eq⟩\n\nprotected lemma ext_iff : f = g ↔ ∀ s, s ∈ f ↔ s ∈ g :=\nby rw [filter_eq_iff, ext_iff]\n\n@[extensionality]\nprotected lemma ext : (∀ s, s ∈ f ↔ s ∈ g) → f = g :=\nfilter.ext_iff.2\n\nlemma univ_mem_sets : univ ∈ f :=\nf.univ_sets\n\nlemma mem_sets_of_superset : ∀{x y : set α}, x ∈ f → x ⊆ y → y ∈ f :=\nf.sets_of_superset\n\nlemma inter_mem_sets : ∀{s t}, s ∈ f → t ∈ f → s ∩ t ∈ f :=\nf.inter_sets\n\nlemma univ_mem_sets' (h : ∀ a, a ∈ s): s ∈ f :=\nmem_sets_of_superset univ_mem_sets (assume x _, h x)\n\nlemma mp_sets (hs : s ∈ f) (h : {x | x ∈ s → x ∈ t} ∈ f) : t ∈ f :=\nmem_sets_of_superset (inter_mem_sets hs h) $ assume x ⟨h₁, h₂⟩, h₂ h₁\n\nlemma congr_sets (h : {x | x ∈ s ↔ x ∈ t} ∈ f) : s ∈ f ↔ t ∈ f :=\n⟨λ hs, mp_sets hs (mem_sets_of_superset h (λ x, iff.mp)),\n λ hs, mp_sets hs (mem_sets_of_superset h (λ x, iff.mpr))⟩\n\nlemma Inter_mem_sets {β : Type v} {s : β → set α} {is : set β} (hf : finite is) :\n (∀i∈is, s i ∈ f) → (⋂i∈is, s i) ∈ f :=\nfinite.induction_on hf\n (assume hs, by simp only [univ_mem_sets, mem_empty_eq, Inter_neg, Inter_univ, not_false_iff])\n (assume i is _ hf hi hs,\n have h₁ : s i ∈ f, from hs i (by simp),\n have h₂ : (⋂x∈is, s x) ∈ f, from hi $ assume a ha, hs _ $ by simp only [ha, mem_insert_iff, or_true],\n by simp [inter_mem_sets h₁ h₂])\n\nlemma exists_sets_subset_iff : (∃t ∈ f, t ⊆ s) ↔ s ∈ f :=\n⟨assume ⟨t, ht, ts⟩, mem_sets_of_superset ht ts, assume hs, ⟨s, hs, subset.refl _⟩⟩\n\nlemma monotone_mem_sets {f : filter α} : monotone (λs, s ∈ f) :=\nassume s t hst h, mem_sets_of_superset h hst\n\nend filter\n\nnamespace tactic.interactive\nopen tactic interactive\n\n/-- `filter_upwards [h1, ⋯, hn]` replaces a goal of the form `s ∈ f`\nand terms `h1 : t1 ∈ f, ⋯, hn : tn ∈ f` with `∀x, x ∈ t1 → ⋯ → x ∈ tn → x ∈ s`.\n\n`filter_upwards [h1, ⋯, hn] e` is a short form for `{ filter_upwards [h1, ⋯, hn], exact e }`.\n-/\nmeta def filter_upwards\n (s : parse types.pexpr_list)\n (e' : parse $ optional types.texpr) : tactic unit :=\ndo\n s.reverse.mmap (λ e, eapplyc `filter.mp_sets >> eapply e),\n eapplyc `filter.univ_mem_sets',\n match e' with\n | some e := interactive.exact e\n | none := skip\n end\n\nend tactic.interactive\n\nnamespace filter\nvariables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x}\n\nsection principal\n\n/-- The principal filter of `s` is the collection of all supersets of `s`. -/\ndef principal (s : set α) : filter α :=\n{ sets := {t | s ⊆ t},\n univ_sets := subset_univ s,\n sets_of_superset := assume x y hx hy, subset.trans hx hy,\n inter_sets := assume x y, subset_inter }\n\ninstance : inhabited (filter α) :=\n⟨principal ∅⟩\n\n@[simp] lemma mem_principal_sets {s t : set α} : s ∈ principal t ↔ t ⊆ s := iff.rfl\n\nlemma mem_principal_self (s : set α) : s ∈ principal s := subset.refl _\n\nend principal\n\nsection join\n\n/-- The join of a filter of filters is defined by the relation `s ∈ join f ↔ {t | s ∈ t} ∈ f`. -/\ndef join (f : filter (filter α)) : filter α :=\n{ sets := {s | {t : filter α | s ∈ t} ∈ f},\n univ_sets := by simp only [univ_mem_sets, mem_set_of_eq]; exact univ_mem_sets,\n sets_of_superset := assume x y hx xy,\n mem_sets_of_superset hx $ assume f h, mem_sets_of_superset h xy,\n inter_sets := assume x y hx hy,\n mem_sets_of_superset (inter_mem_sets hx hy) $ assume f ⟨h₁, h₂⟩, inter_mem_sets h₁ h₂ }\n\n@[simp] lemma mem_join_sets {s : set α} {f : filter (filter α)} :\n s ∈ join f ↔ {t | s ∈ filter.sets t} ∈ f := iff.rfl\n\nend join\n\nsection lattice\n\ninstance : partial_order (filter α) :=\n{ le := λf g, g.sets ⊆ f.sets,\n le_antisymm := assume a b h₁ h₂, filter_eq $ subset.antisymm h₂ h₁,\n le_refl := assume a, subset.refl _,\n le_trans := assume a b c h₁ h₂, subset.trans h₂ h₁ }\n\ntheorem le_def {f g : filter α} : f ≤ g ↔ ∀ x ∈ g, x ∈ f := iff.rfl\n\n/-- `generate_sets g s`: `s` is in the filter closure of `g`. -/\ninductive generate_sets (g : set (set α)) : set α → Prop\n| basic {s : set α} : s ∈ g → generate_sets s\n| univ {} : generate_sets univ\n| superset {s t : set α} : generate_sets s → s ⊆ t → generate_sets t\n| inter {s t : set α} : generate_sets s → generate_sets t → generate_sets (s ∩ t)\n\n/-- `generate g` is the smallest filter containing the sets `g`. -/\ndef generate (g : set (set α)) : filter α :=\n{ sets := {s | generate_sets g s},\n univ_sets := generate_sets.univ,\n sets_of_superset := assume x y, generate_sets.superset,\n inter_sets := assume s t, generate_sets.inter }\n\nlemma sets_iff_generate {s : set (set α)} {f : filter α} : f ≤ filter.generate s ↔ s ⊆ f.sets :=\niff.intro\n (assume h u hu, h $ generate_sets.basic $ hu)\n (assume h u hu, hu.rec_on h univ_mem_sets\n (assume x y _ hxy hx, mem_sets_of_superset hx hxy)\n (assume x y _ _ hx hy, inter_mem_sets hx hy))\n\nprotected def mk_of_closure (s : set (set α)) (hs : (generate s).sets = s) : filter α :=\n{ sets := s,\n univ_sets := hs ▸ (univ_mem_sets : univ ∈ generate s),\n sets_of_superset := assume x y, hs ▸ (mem_sets_of_superset : x ∈ generate s → x ⊆ y → y ∈ generate s),\n inter_sets := assume x y, hs ▸ (inter_mem_sets : x ∈ generate s → y ∈ generate s → x ∩ y ∈ generate s) }\n\nlemma mk_of_closure_sets {s : set (set α)} {hs : (generate s).sets = s} :\n filter.mk_of_closure s hs = generate s :=\nfilter.ext $ assume u,\nshow u ∈ (filter.mk_of_closure s hs).sets ↔ u ∈ (generate s).sets, from hs.symm ▸ iff.refl _\n\n/- Galois insertion from sets of sets into a filters. -/\ndef gi_generate (α : Type*) :\n @galois_insertion (set (set α)) (order_dual (filter α)) _ _ filter.generate filter.sets :=\n{ gc := assume s f, sets_iff_generate,\n le_l_u := assume f u, generate_sets.basic,\n choice := λs hs, filter.mk_of_closure s (le_antisymm hs $ sets_iff_generate.1 $ le_refl _),\n choice_eq := assume s hs, mk_of_closure_sets }\n\n/-- The infimum of filters is the filter generated by intersections\n of elements of the two filters. -/\ninstance : has_inf (filter α) := ⟨λf g : filter α,\n{ sets := {s | ∃ (a ∈ f) (b ∈ g), a ∩ b ⊆ s },\n univ_sets := ⟨_, univ_mem_sets, _, univ_mem_sets, inter_subset_left _ _⟩,\n sets_of_superset := assume x y ⟨a, ha, b, hb, h⟩ xy, ⟨a, ha, b, hb, subset.trans h xy⟩,\n inter_sets := assume x y ⟨a, ha, b, hb, hx⟩ ⟨c, hc, d, hd, hy⟩,\n ⟨_, inter_mem_sets ha hc, _, inter_mem_sets hb hd,\n calc a ∩ c ∩ (b ∩ d) = (a ∩ b) ∩ (c ∩ d) : by ac_refl\n ... ⊆ x ∩ y : inter_subset_inter hx hy⟩ }⟩\n\n@[simp] lemma mem_inf_sets {f g : filter α} {s : set α} :\n s ∈ f ⊓ g ↔ ∃t₁∈f.sets, ∃t₂∈g.sets, t₁ ∩ t₂ ⊆ s := iff.rfl\n\nlemma mem_inf_sets_of_left {f g : filter α} {s : set α} (h : s ∈ f) : s ∈ f ⊓ g :=\n⟨s, h, univ, univ_mem_sets, inter_subset_left _ _⟩\n\nlemma mem_inf_sets_of_right {f g : filter α} {s : set α} (h : s ∈ g) : s ∈ f ⊓ g :=\n⟨univ, univ_mem_sets, s, h, inter_subset_right _ _⟩\n\nlemma inter_mem_inf_sets {α : Type u} {f g : filter α} {s t : set α}\n (hs : s ∈ f) (ht : t ∈ g) : s ∩ t ∈ f ⊓ g :=\ninter_mem_sets (mem_inf_sets_of_left hs) (mem_inf_sets_of_right ht)\n\ninstance : has_top (filter α) :=\n⟨{ sets := {s | ∀x, x ∈ s},\n univ_sets := assume x, mem_univ x,\n sets_of_superset := assume x y hx hxy a, hxy (hx a),\n inter_sets := assume x y hx hy a, mem_inter (hx _) (hy _) }⟩\n\nlemma mem_top_sets_iff_forall {s : set α} : s ∈ (⊤ : filter α) ↔ (∀x, x ∈ s) :=\niff.refl _\n\n@[simp] lemma mem_top_sets {s : set α} : s ∈ (⊤ : filter α) ↔ s = univ :=\nby rw [mem_top_sets_iff_forall, eq_univ_iff_forall]\n\nsection complete_lattice\n\n/- We lift the complete lattice along the Galois connection `generate` / `sets`. Unfortunately,\n we want to have different definitional equalities for the lattice operations. So we define them\n upfront and change the lattice operations for the complete lattice instance. -/\n\nprivate def original_complete_lattice : complete_lattice (filter α) :=\n@order_dual.lattice.complete_lattice _ (gi_generate α).lift_complete_lattice\n\nlocal attribute [instance] original_complete_lattice\n\ninstance : complete_lattice (filter α) := original_complete_lattice.copy\n /- le -/ filter.partial_order.le rfl\n /- top -/ (filter.lattice.has_top).1\n (top_unique $ assume s hs, by have := univ_mem_sets ; finish)\n /- bot -/ _ rfl\n /- sup -/ _ rfl\n /- inf -/ (filter.lattice.has_inf).1\n begin\n ext f g : 2,\n exact le_antisymm\n (le_inf (assume s, mem_inf_sets_of_left) (assume s, mem_inf_sets_of_right))\n (assume s ⟨a, ha, b, hb, hs⟩, show s ∈ complete_lattice.inf f g, from\n mem_sets_of_superset (inter_mem_sets\n (@inf_le_left (filter α) _ _ _ _ ha)\n (@inf_le_right (filter α) _ _ _ _ hb)) hs)\n end\n /- Sup -/ (join ∘ principal) (by ext s x; exact (@mem_bInter_iff _ _ s filter.sets x).symm)\n /- Inf -/ _ rfl\n\nend complete_lattice\n\nlemma bot_sets_eq : (⊥ : filter α).sets = univ := rfl\n\nlemma sup_sets_eq {f g : filter α} : (f ⊔ g).sets = f.sets ∩ g.sets :=\n(gi_generate α).gc.u_inf\n\nlemma Sup_sets_eq {s : set (filter α)} : (Sup s).sets = (⋂f∈s, (f:filter α).sets) :=\n(gi_generate α).gc.u_Inf\n\nlemma supr_sets_eq {f : ι → filter α} : (supr f).sets = (⋂i, (f i).sets) :=\n(gi_generate α).gc.u_infi\n\nlemma generate_empty : filter.generate ∅ = (⊤ : filter α) :=\n(gi_generate α).gc.l_bot\n\nlemma generate_univ : filter.generate univ = (⊥ : filter α) :=\nmk_of_closure_sets.symm\n\nlemma generate_union {s t : set (set α)} :\n filter.generate (s ∪ t) = filter.generate s ⊓ filter.generate t :=\n(gi_generate α).gc.l_sup\n\nlemma generate_Union {s : ι → set (set α)} :\n filter.generate (⋃ i, s i) = (⨅ i, filter.generate (s i)) :=\n(gi_generate α).gc.l_supr\n\n@[simp] lemma mem_bot_sets {s : set α} : s ∈ (⊥ : filter α) :=\ntrivial\n\n@[simp] lemma mem_sup_sets {f g : filter α} {s : set α} :\n s ∈ f ⊔ g ↔ s ∈ f ∧ s ∈ g :=\niff.rfl\n\n@[simp] lemma mem_Sup_sets {x : set α} {s : set (filter α)} :\n x ∈ Sup s ↔ (∀f∈s, x ∈ (f:filter α)) :=\niff.rfl\n\n@[simp] lemma mem_supr_sets {x : set α} {f : ι → filter α} :\n x ∈ supr f ↔ (∀i, x ∈ f i) :=\nby simp only [supr_sets_eq, iff_self, mem_Inter]\n\n@[simp] lemma le_principal_iff {s : set α} {f : filter α} : f ≤ principal s ↔ s ∈ f :=\nshow (∀{t}, s ⊆ t → t ∈ f) ↔ s ∈ f,\n from ⟨assume h, h (subset.refl s), assume hs t ht, mem_sets_of_superset hs ht⟩\n\nlemma principal_mono {s t : set α} : principal s ≤ principal t ↔ s ⊆ t :=\nby simp only [le_principal_iff, iff_self, mem_principal_sets]\n\nlemma monotone_principal : monotone (principal : set α → filter α) :=\nby simp only [monotone, principal_mono]; exact assume a b h, h\n\n@[simp] lemma principal_eq_iff_eq {s t : set α} : principal s = principal t ↔ s = t :=\nby simp only [le_antisymm_iff, le_principal_iff, mem_principal_sets]; refl\n\n@[simp] lemma join_principal_eq_Sup {s : set (filter α)} : join (principal s) = Sup s := rfl\n\n/- lattice equations -/\n\nlemma empty_in_sets_eq_bot {f : filter α} : ∅ ∈ f ↔ f = ⊥ :=\n⟨assume h, bot_unique $ assume s _, mem_sets_of_superset h (empty_subset s),\n assume : f = ⊥, this.symm ▸ mem_bot_sets⟩\n\nlemma inhabited_of_mem_sets {f : filter α} {s : set α} (hf : f ≠ ⊥) (hs : s ∈ f) :\n ∃x, x ∈ s :=\nhave ∅ ∉ f.sets, from assume h, hf $ empty_in_sets_eq_bot.mp h,\nhave s ≠ ∅, from assume h, this (h ▸ hs),\nexists_mem_of_ne_empty this\n\nlemma filter_eq_bot_of_not_nonempty {f : filter α} (ne : ¬ nonempty α) : f = ⊥ :=\nempty_in_sets_eq_bot.mp $ univ_mem_sets' $ assume x, false.elim (ne ⟨x⟩)\n\nlemma forall_sets_neq_empty_iff_neq_bot {f : filter α} :\n (∀ (s : set α), s ∈ f → s ≠ ∅) ↔ f ≠ ⊥ :=\nby\n simp only [(@empty_in_sets_eq_bot α f).symm, ne.def];\n exact ⟨assume h hs, h _ hs rfl, assume h s hs eq, h $ eq ▸ hs⟩\n\nlemma mem_sets_of_neq_bot {f : filter α} {s : set α} (h : f ⊓ principal (-s) = ⊥) : s ∈ f :=\nhave ∅ ∈ f ⊓ principal (- s), from h.symm ▸ mem_bot_sets,\nlet ⟨s₁, hs₁, s₂, (hs₂ : -s ⊆ s₂), (hs : s₁ ∩ s₂ ⊆ ∅)⟩ := this in\nby filter_upwards [hs₁] assume a ha, classical.by_contradiction $ assume ha', hs ⟨ha, hs₂ ha'⟩\n\nlemma infi_sets_eq {f : ι → filter α} (h : directed (≥) f) (ne : nonempty ι) :\n (infi f).sets = (⋃ i, (f i).sets) :=\nlet ⟨i⟩ := ne, u := { filter .\n sets := (⋃ i, (f i).sets),\n univ_sets := by simp only [mem_Union]; exact ⟨i, univ_mem_sets⟩,\n sets_of_superset := by simp only [mem_Union, exists_imp_distrib];\n intros x y i hx hxy; exact ⟨i, mem_sets_of_superset hx hxy⟩,\n inter_sets :=\n begin\n simp only [mem_Union, exists_imp_distrib],\n assume x y a hx b hy,\n rcases h a b with ⟨c, ha, hb⟩,\n exact ⟨c, inter_mem_sets (ha hx) (hb hy)⟩\n end } in\nsubset.antisymm\n (show u ≤ infi f, from le_infi $ assume i, le_supr (λi, (f i).sets) i)\n (Union_subset $ assume i, infi_le f i)\n\nlemma mem_infi {f : ι → filter α} (h : directed (≥) f) (ne : nonempty ι) (s):\n s ∈ infi f ↔ s ∈ ⋃ i, (f i).sets :=\nshow s ∈ (infi f).sets ↔ s ∈ ⋃ i, (f i).sets, by rw infi_sets_eq h ne\n\nlemma infi_sets_eq' {f : β → filter α} {s : set β}\n (h : directed_on (f ⁻¹'o (≥)) s) (ne : ∃i, i ∈ s) :\n (⨅ i∈s, f i).sets = (⋃ i ∈ s, (f i).sets) :=\nlet ⟨i, hi⟩ := ne in\ncalc (⨅ i ∈ s, f i).sets = (⨅ t : {t // t ∈ s}, (f t.val)).sets : by rw [infi_subtype]; refl\n ... = (⨆ t : {t // t ∈ s}, (f t.val).sets) : infi_sets_eq\n (assume ⟨x, hx⟩ ⟨y, hy⟩, match h x hx y hy with ⟨z, h₁, h₂, h₃⟩ := ⟨⟨z, h₁⟩, h₂, h₃⟩ end)\n ⟨⟨i, hi⟩⟩\n ... = (⨆ t ∈ {t | t ∈ s}, (f t).sets) : by rw [supr_subtype]; refl\n\nlemma infi_sets_eq_finite (f : ι → filter α) :\n (⨅i, f i).sets = (⋃t:finset (plift ι), (⨅i∈t, f (plift.down i)).sets) :=\nbegin\n rw [infi_eq_infi_finset, infi_sets_eq],\n exact (directed_of_sup $ λs₁ s₂ hs, infi_le_infi $ λi, infi_le_infi_const $ λh, hs h),\n apply_instance\nend\n\nlemma mem_infi_finite {f : ι → filter α} (s):\n s ∈ infi f ↔ s ∈ ⋃t:finset (plift ι), (⨅i∈t, f (plift.down i)).sets :=\nshow s ∈ (infi f).sets ↔ s ∈ ⋃t:finset (plift ι), (⨅i∈t, f (plift.down i)).sets,\nby rw infi_sets_eq_finite\n\n@[simp] lemma sup_join {f₁ f₂ : filter (filter α)} : (join f₁ ⊔ join f₂) = join (f₁ ⊔ f₂) :=\nfilter_eq $ set.ext $ assume x,\n by simp only [supr_sets_eq, join, mem_sup_sets, iff_self, mem_set_of_eq]\n\n@[simp] lemma supr_join {ι : Sort w} {f : ι → filter (filter α)} :\n (⨆x, join (f x)) = join (⨆x, f x) :=\nfilter_eq $ set.ext $ assume x,\n by simp only [supr_sets_eq, join, iff_self, mem_Inter, mem_set_of_eq]\n\ninstance : bounded_distrib_lattice (filter α) :=\n{ le_sup_inf :=\n begin\n assume x y z s,\n simp only [and_assoc, mem_inf_sets, mem_sup_sets, exists_prop, exists_imp_distrib, and_imp],\n intros hs t₁ ht₁ t₂ ht₂ hts,\n exact ⟨s ∪ t₁,\n x.sets_of_superset hs $ subset_union_left _ _,\n y.sets_of_superset ht₁ $ subset_union_right _ _,\n s ∪ t₂,\n x.sets_of_superset hs $ subset_union_left _ _,\n z.sets_of_superset ht₂ $ subset_union_right _ _,\n subset.trans (@le_sup_inf (set α) _ _ _ _) (union_subset (subset.refl _) hts)⟩\n end,\n ..filter.lattice.complete_lattice }\n\n/- the complementary version with ⨆i, f ⊓ g i does not hold! -/\nlemma infi_sup_eq {f : filter α} {g : ι → filter α} : (⨅ x, f ⊔ g x) = f ⊔ infi g :=\nbegin\n refine le_antisymm _ (le_infi $ assume i, sup_le_sup (le_refl f) $ infi_le _ _),\n rintros t ⟨h₁, h₂⟩,\n rw [infi_sets_eq_finite] at h₂,\n simp only [mem_Union, (finset.inf_eq_infi _ _).symm] at h₂,\n rcases h₂ with ⟨s, hs⟩,\n suffices : (⨅i, f ⊔ g i) ≤ f ⊔ s.inf (λi, g i.down), { exact this ⟨h₁, hs⟩ },\n refine finset.induction_on s _ _,\n { exact le_sup_right_of_le le_top },\n { rintros ⟨i⟩ s his ih,\n rw [finset.inf_insert, sup_inf_left],\n exact le_inf (infi_le _ _) ih }\nend\n\nlemma mem_infi_sets_finset {s : finset α} {f : α → filter β} :\n ∀t, t ∈ (⨅a∈s, f a) ↔ (∃p:α → set β, (∀a∈s, p a ∈ f a) ∧ (⋂a∈s, p a) ⊆ t) :=\nshow ∀t, t ∈ (⨅a∈s, f a) ↔ (∃p:α → set β, (∀a∈s, p a ∈ f a) ∧ (⨅a∈s, p a) ≤ t),\nbegin\n simp only [(finset.inf_eq_infi _ _).symm],\n refine finset.induction_on s _ _,\n { simp only [finset.not_mem_empty, false_implies_iff, finset.inf_empty, top_le_iff,\n imp_true_iff, mem_top_sets, true_and, exists_const],\n intros; refl },\n { intros a s has ih t,\n simp only [ih, finset.forall_mem_insert, finset.inf_insert, mem_inf_sets,\n exists_prop, iff_iff_implies_and_implies, exists_imp_distrib, and_imp, and_assoc] {contextual := tt},\n split,\n { intros t₁ ht₁ t₂ p hp ht₂ ht,\n existsi function.update p a t₁,\n have : ∀a'∈s, function.update p a t₁ a' = p a',\n from assume a' ha',\n have a' ≠ a, from assume h, has $ h ▸ ha',\n function.update_noteq this,\n have eq : s.inf (λj, function.update p a t₁ j) = s.inf (λj, p j) :=\n finset.inf_congr rfl this,\n simp only [this, ht₁, hp, function.update_same, true_and, imp_true_iff, eq] {contextual := tt},\n exact subset.trans (inter_subset_inter (subset.refl _) ht₂) ht },\n assume p hpa hp ht,\n exact ⟨p a, hpa, (s.inf p), ⟨⟨p, hp, le_refl _⟩, ht⟩⟩ }\nend\n\n/- principal equations -/\n\n@[simp] lemma inf_principal {s t : set α} : principal s ⊓ principal t = principal (s ∩ t) :=\nle_antisymm\n (by simp; exact ⟨s, subset.refl s, t, subset.refl t, by simp⟩)\n (by simp [le_inf_iff, inter_subset_left, inter_subset_right])\n\n@[simp] lemma sup_principal {s t : set α} : principal s ⊔ principal t = principal (s ∪ t) :=\nfilter_eq $ set.ext $\n by simp only [union_subset_iff, union_subset_iff, mem_sup_sets, forall_const, iff_self, mem_principal_sets]\n\n@[simp] lemma supr_principal {ι : Sort w} {s : ι → set α} : (⨆x, principal (s x)) = principal (⋃i, s i) :=\nfilter_eq $ set.ext $ assume x, by simp only [supr_sets_eq, mem_principal_sets, mem_Inter];\nexact (@supr_le_iff (set α) _ _ _ _).symm\n\nlemma principal_univ : principal (univ : set α) = ⊤ :=\ntop_unique $ by simp only [le_principal_iff, mem_top_sets, eq_self_iff_true]\n\nlemma principal_empty : principal (∅ : set α) = ⊥ :=\nbot_unique $ assume s _, empty_subset _\n\n@[simp] lemma principal_eq_bot_iff {s : set α} : principal s = ⊥ ↔ s = ∅ :=\n⟨assume h, principal_eq_iff_eq.mp $ by simp only [principal_empty, h, eq_self_iff_true],\n assume h, by simp only [h, principal_empty, eq_self_iff_true]⟩\n\nlemma inf_principal_eq_bot {f : filter α} {s : set α} (hs : -s ∈ f) : f ⊓ principal s = ⊥ :=\nempty_in_sets_eq_bot.mp ⟨_, hs, s, mem_principal_self s, assume x ⟨h₁, h₂⟩, h₁ h₂⟩\n\ntheorem mem_inf_principal (f : filter α) (s t : set α) :\n s ∈ f ⊓ principal t ↔ { x | x ∈ t → x ∈ s } ∈ f :=\nbegin\n simp only [mem_inf_sets, mem_principal_sets, exists_prop], split,\n { rintros ⟨u, ul, v, tsubv, uvinter⟩,\n apply filter.mem_sets_of_superset ul,\n intros x xu xt, exact uvinter ⟨xu, tsubv xt⟩ },\n intro h, refine ⟨_, h, t, set.subset.refl t, _⟩,\n rintros x ⟨hx, xt⟩,\n exact hx xt\nend\n\nend lattice\n\nsection map\n\n/-- The forward map of a filter -/\ndef map (m : α → β) (f : filter α) : filter β :=\n{ sets := preimage m ⁻¹' f.sets,\n univ_sets := univ_mem_sets,\n sets_of_superset := assume s t hs st, mem_sets_of_superset hs $ preimage_mono st,\n inter_sets := assume s t hs ht, inter_mem_sets hs ht }\n\n@[simp] lemma map_principal {s : set α} {f : α → β} :\n map f (principal s) = principal (set.image f s) :=\nfilter_eq $ set.ext $ assume a, image_subset_iff.symm\n\nvariables {f : filter α} {m : α → β} {m' : β → γ} {s : set α} {t : set β}\n\n@[simp] lemma mem_map : t ∈ map m f ↔ {x | m x ∈ t} ∈ f := iff.rfl\n\nlemma image_mem_map (hs : s ∈ f) : m '' s ∈ map m f :=\nf.sets_of_superset hs $ subset_preimage_image m s\n\nlemma range_mem_map : range m ∈ map m f :=\nby rw ←image_univ; exact image_mem_map univ_mem_sets\n\nlemma mem_map_sets_iff : t ∈ map m f ↔ (∃s∈f, m '' s ⊆ t) :=\niff.intro\n (assume ht, ⟨set.preimage m t, ht, image_preimage_subset _ _⟩)\n (assume ⟨s, hs, ht⟩, mem_sets_of_superset (image_mem_map hs) ht)\n\n@[simp] lemma map_id : filter.map id f = f :=\nfilter_eq $ rfl\n\n@[simp] lemma map_compose : filter.map m' ∘ filter.map m = filter.map (m' ∘ m) :=\nfunext $ assume _, filter_eq $ rfl\n\n@[simp] lemma map_map : filter.map m' (filter.map m f) = filter.map (m' ∘ m) f :=\ncongr_fun (@@filter.map_compose m m') f\n\nend map\n\nsection comap\n\n/-- The inverse map of a filter -/\ndef comap (m : α → β) (f : filter β) : filter α :=\n{ sets := { s | ∃t∈ f, m ⁻¹' t ⊆ s },\n univ_sets := ⟨univ, univ_mem_sets, by simp only [subset_univ, preimage_univ]⟩,\n sets_of_superset := assume a b ⟨a', ha', ma'a⟩ ab,\n ⟨a', ha', subset.trans ma'a ab⟩,\n inter_sets := assume a b ⟨a', ha₁, ha₂⟩ ⟨b', hb₁, hb₂⟩,\n ⟨a' ∩ b', inter_mem_sets ha₁ hb₁, inter_subset_inter ha₂ hb₂⟩ }\n\nend comap\n\n/-- The cofinite filter is the filter of subsets whose complements are finite. -/\ndef cofinite : filter α :=\n{ sets := {s | finite (- s)},\n univ_sets := by simp only [compl_univ, finite_empty, mem_set_of_eq],\n sets_of_superset := assume s t (hs : finite (-s)) (st: s ⊆ t),\n finite_subset hs $ @lattice.neg_le_neg (set α) _ _ _ st,\n inter_sets := assume s t (hs : finite (-s)) (ht : finite (-t)),\n by simp only [compl_inter, finite_union, ht, hs, mem_set_of_eq] }\n\nlemma cofinite_ne_bot (hi : set.infinite (@set.univ α)) : @cofinite α ≠ ⊥ :=\nforall_sets_neq_empty_iff_neq_bot.mp \n $ λ s hs hn, by change set.finite _ at hs; \n rw [hn, set.compl_empty] at hs; exact hi hs\n\n/-- The monadic bind operation on filter is defined the usual way in terms of `map` and `join`.\n\nUnfortunately, this `bind` does not result in the expected applicative. See `filter.seq` for the\napplicative instance. -/\ndef bind (f : filter α) (m : α → filter β) : filter β := join (map m f)\n\n/-- The applicative sequentiation operation. This is not induced by the bind operation. -/\ndef seq (f : filter (α → β)) (g : filter α) : filter β :=\n⟨{ s | ∃u∈ f, ∃t∈ g, (∀m∈u, ∀x∈t, (m : α → β) x ∈ s) },\n ⟨univ, univ_mem_sets, univ, univ_mem_sets, by simp only [forall_prop_of_true, mem_univ, forall_true_iff]⟩,\n assume s₀ s₁ ⟨t₀, t₁, h₀, h₁, h⟩ hst, ⟨t₀, t₁, h₀, h₁, assume x hx y hy, hst $ h _ hx _ hy⟩,\n assume s₀ s₁ ⟨t₀, ht₀, t₁, ht₁, ht⟩ ⟨u₀, hu₀, u₁, hu₁, hu⟩,\n ⟨t₀ ∩ u₀, inter_mem_sets ht₀ hu₀, t₁ ∩ u₁, inter_mem_sets ht₁ hu₁,\n assume x ⟨hx₀, hx₁⟩ x ⟨hy₀, hy₁⟩, ⟨ht _ hx₀ _ hy₀, hu _ hx₁ _ hy₁⟩⟩⟩\n\ninstance : has_pure filter := ⟨λ(α : Type u) x, principal {x}⟩\n\ninstance : has_bind filter := ⟨@filter.bind⟩\n\ninstance : has_seq filter := ⟨@filter.seq⟩\n\ninstance : functor filter := { map := @filter.map }\n\nsection\n-- this section needs to be before applicative, otherwise the wrong instance will be chosen\nprotected def monad : monad filter := { map := @filter.map }\n\nlocal attribute [instance] filter.monad\nprotected def is_lawful_monad : is_lawful_monad filter :=\n{ id_map := assume α f, filter_eq rfl,\n pure_bind := assume α β a f, by simp only [bind, Sup_image, image_singleton,\n join_principal_eq_Sup, lattice.Sup_singleton, map_principal, eq_self_iff_true],\n bind_assoc := assume α β γ f m₁ m₂, filter_eq rfl,\n bind_pure_comp_eq_map := assume α β f x, filter_eq $\n by simp only [bind, join, map, preimage, principal, set.subset_univ, eq_self_iff_true,\n function.comp_app, mem_set_of_eq, singleton_subset_iff] }\nend\n\ninstance : applicative filter := { map := @filter.map, seq := @filter.seq }\n\ninstance : alternative filter :=\n{ failure := λα, ⊥,\n orelse := λα x y, x ⊔ y }\n\n@[simp] lemma pure_def (x : α) : pure x = principal {x} := rfl\n\n@[simp] lemma mem_pure {a : α} {s : set α} : a ∈ s → s ∈ (pure a : filter α) :=\nby simp only [imp_self, pure_def, mem_principal_sets, singleton_subset_iff]; exact id\n\n@[simp] lemma mem_pure_iff {a : α} {s : set α} : s ∈ (pure a : filter α) ↔ a ∈ s :=\nby rw [pure_def, mem_principal_sets, set.singleton_subset_iff]\n\n@[simp] lemma map_def {α β} (m : α → β) (f : filter α) : m <$> f = map m f := rfl\n\n@[simp] lemma bind_def {α β} (f : filter α) (m : α → filter β) : f >>= m = bind f m := rfl\n\n/- map and comap equations -/\nsection map\nvariables {f f₁ f₂ : filter α} {g g₁ g₂ : filter β} {m : α → β} {m' : β → γ} {s : set α} {t : set β}\n\n@[simp] theorem mem_comap_sets : s ∈ comap m g ↔ ∃t∈ g, m ⁻¹' t ⊆ s := iff.rfl\n\ntheorem preimage_mem_comap (ht : t ∈ g) : m ⁻¹' t ∈ comap m g :=\n⟨t, ht, subset.refl _⟩\n\nlemma comap_id : comap id f = f :=\nle_antisymm (assume s, preimage_mem_comap) (assume s ⟨t, ht, hst⟩, mem_sets_of_superset ht hst)\n\nlemma comap_comap_comp {m : γ → β} {n : β → α} : comap m (comap n f) = comap (n ∘ m) f :=\nle_antisymm\n (assume c ⟨b, hb, (h : preimage (n ∘ m) b ⊆ c)⟩, ⟨preimage n b, preimage_mem_comap hb, h⟩)\n (assume c ⟨b, ⟨a, ha, (h₁ : preimage n a ⊆ b)⟩, (h₂ : preimage m b ⊆ c)⟩,\n ⟨a, ha, show preimage m (preimage n a) ⊆ c, from subset.trans (preimage_mono h₁) h₂⟩)\n\n@[simp] theorem comap_principal {t : set β} : comap m (principal t) = principal (m ⁻¹' t) :=\nfilter_eq $ set.ext $ assume s,\n ⟨assume ⟨u, (hu : t ⊆ u), (b : preimage m u ⊆ s)⟩, subset.trans (preimage_mono hu) b,\n assume : preimage m t ⊆ s, ⟨t, subset.refl t, this⟩⟩\n\nlemma map_le_iff_le_comap : map m f ≤ g ↔ f ≤ comap m g :=\n⟨assume h s ⟨t, ht, hts⟩, mem_sets_of_superset (h ht) hts, assume h s ht, h ⟨_, ht, subset.refl _⟩⟩\n\nlemma gc_map_comap (m : α → β) : galois_connection (map m) (comap m) :=\nassume f g, map_le_iff_le_comap\n\nlemma map_mono (h : f₁ ≤ f₂) : map m f₁ ≤ map m f₂ := (gc_map_comap m).monotone_l h\nlemma monotone_map : monotone (map m) | a b := map_mono\nlemma comap_mono (h : g₁ ≤ g₂) : comap m g₁ ≤ comap m g₂ := (gc_map_comap m).monotone_u h\nlemma monotone_comap : monotone (comap m) | a b := comap_mono\n\n@[simp] lemma map_bot : map m ⊥ = ⊥ := (gc_map_comap m).l_bot\n@[simp] lemma map_sup : map m (f₁ ⊔ f₂) = map m f₁ ⊔ map m f₂ := (gc_map_comap m).l_sup\n@[simp] lemma map_supr {f : ι → filter α} : map m (⨆i, f i) = (⨆i, map m (f i)) :=\n(gc_map_comap m).l_supr\n\n@[simp] lemma comap_top : comap m ⊤ = ⊤ := (gc_map_comap m).u_top\n@[simp] lemma comap_inf : comap m (g₁ ⊓ g₂) = comap m g₁ ⊓ comap m g₂ := (gc_map_comap m).u_inf\n@[simp] lemma comap_infi {f : ι → filter β} : comap m (⨅i, f i) = (⨅i, comap m (f i)) :=\n(gc_map_comap m).u_infi\n\nlemma le_comap_top (f : α → β) (l : filter α) : l ≤ comap f ⊤ :=\nby rw [comap_top]; exact le_top\n\nlemma map_comap_le : map m (comap m g) ≤ g := (gc_map_comap m).l_u_le _\nlemma le_comap_map : f ≤ comap m (map m f) := (gc_map_comap m).le_u_l _\n\n@[simp] lemma comap_bot : comap m ⊥ = ⊥ :=\nbot_unique $ assume s _, ⟨∅, by simp only [mem_bot_sets], by simp only [empty_subset, preimage_empty]⟩\n\nlemma comap_supr {ι} {f : ι → filter β} {m : α → β} :\n comap m (supr f) = (⨆i, comap m (f i)) :=\nle_antisymm\n (assume s hs,\n have ∀i, ∃t, t ∈ f i ∧ m ⁻¹' t ⊆ s, by simpa only [mem_comap_sets, exists_prop, mem_supr_sets] using mem_supr_sets.1 hs,\n let ⟨t, ht⟩ := classical.axiom_of_choice this in\n ⟨⋃i, t i, mem_supr_sets.2 $ assume i, (f i).sets_of_superset (ht i).1 (subset_Union _ _),\n begin\n rw [preimage_Union, Union_subset_iff],\n assume i,\n exact (ht i).2\n end⟩)\n (supr_le $ assume i, monotone_comap $ le_supr _ _)\n\nlemma comap_Sup {s : set (filter β)} {m : α → β} : comap m (Sup s) = (⨆f∈s, comap m f) :=\nby simp only [Sup_eq_supr, comap_supr, eq_self_iff_true]\n\nlemma comap_sup : comap m (g₁ ⊔ g₂) = comap m g₁ ⊔ comap m g₂ :=\nle_antisymm\n (assume s ⟨⟨t₁, ht₁, hs₁⟩, ⟨t₂, ht₂, hs₂⟩⟩,\n ⟨t₁ ∪ t₂,\n ⟨g₁.sets_of_superset ht₁ (subset_union_left _ _), g₂.sets_of_superset ht₂ (subset_union_right _ _)⟩,\n union_subset hs₁ hs₂⟩)\n (sup_le (comap_mono le_sup_left) (comap_mono le_sup_right))\n\nlemma map_comap {f : filter β} {m : α → β} (hf : range m ∈ f) : (f.comap m).map m = f :=\nle_antisymm\n map_comap_le\n (assume t' ⟨t, ht, sub⟩, by filter_upwards [ht, hf]; rintros x hxt ⟨y, rfl⟩; exact sub hxt)\n\nlemma comap_map {f : filter α} {m : α → β} (h : ∀ x y, m x = m y → x = y) :\n comap m (map m f) = f :=\nhave ∀s, preimage m (image m s) = s,\n from assume s, preimage_image_eq s h,\nle_antisymm\n (assume s hs, ⟨\n image m s,\n f.sets_of_superset hs $ by simp only [this, subset.refl],\n by simp only [this, subset.refl]⟩)\n le_comap_map\n\nlemma le_of_map_le_map_inj' {f g : filter α} {m : α → β} {s : set α}\n (hsf : s ∈ f) (hsg : s ∈ g) (hm : ∀x∈s, ∀y∈s, m x = m y → x = y)\n (h : map m f ≤ map m g) : f ≤ g :=\nassume t ht, by filter_upwards [hsf, h $ image_mem_map (inter_mem_sets hsg ht)]\nassume a has ⟨b, ⟨hbs, hb⟩, h⟩,\nhave b = a, from hm _ hbs _ has h,\nthis ▸ hb\n\nlemma le_of_map_le_map_inj_iff {f g : filter α} {m : α → β} {s : set α}\n (hsf : s ∈ f) (hsg : s ∈ g) (hm : ∀x∈s, ∀y∈s, m x = m y → x = y) :\n map m f ≤ map m g ↔ f ≤ g :=\niff.intro (le_of_map_le_map_inj' hsf hsg hm) map_mono\n\nlemma eq_of_map_eq_map_inj' {f g : filter α} {m : α → β} {s : set α}\n (hsf : s ∈ f) (hsg : s ∈ g) (hm : ∀x∈s, ∀y∈s, m x = m y → x = y)\n (h : map m f = map m g) : f = g :=\nle_antisymm\n (le_of_map_le_map_inj' hsf hsg hm $ le_of_eq h)\n (le_of_map_le_map_inj' hsg hsf hm $ le_of_eq h.symm)\n\nlemma map_inj {f g : filter α} {m : α → β} (hm : ∀ x y, m x = m y → x = y) (h : map m f = map m g) :\n f = g :=\nhave comap m (map m f) = comap m (map m g), by rw h,\nby rwa [comap_map hm, comap_map hm] at this\n\ntheorem le_map_comap_of_surjective' {f : α → β} {l : filter β} {u : set β} (ul : u ∈ l)\n (hf : ∀ y ∈ u, ∃ x, f x = y) :\n l ≤ map f (comap f l) :=\nassume s ⟨t, tl, ht⟩,\nhave t ∩ u ⊆ s, from\n assume x ⟨xt, xu⟩,\n exists.elim (hf x xu) $ λ a faeq,\n by { rw ←faeq, apply ht, change f a ∈ t, rw faeq, exact xt },\nmem_sets_of_superset (inter_mem_sets tl ul) this\n\ntheorem map_comap_of_surjective' {f : α → β} {l : filter β} {u : set β} (ul : u ∈ l)\n (hf : ∀ y ∈ u, ∃ x, f x = y) :\n map f (comap f l) = l :=\nle_antisymm map_comap_le (le_map_comap_of_surjective' ul hf)\n\ntheorem le_map_comap_of_surjective {f : α → β} (hf : function.surjective f) (l : filter β) :\n l ≤ map f (comap f l) :=\nle_map_comap_of_surjective' univ_mem_sets (λ y _, hf y)\n\ntheorem map_comap_of_surjective {f : α → β} (hf : function.surjective f) (l : filter β) :\n map f (comap f l) = l :=\nle_antisymm map_comap_le (le_map_comap_of_surjective hf l)\n\nlemma comap_neq_bot {f : filter β} {m : α → β}\n (hm : ∀t∈ f, ∃a, m a ∈ t) : comap m f ≠ ⊥ :=\nforall_sets_neq_empty_iff_neq_bot.mp $ assume s ⟨t, ht, t_s⟩,\n let ⟨a, (ha : a ∈ preimage m t)⟩ := hm t ht in\n neq_bot_of_le_neq_bot (ne_empty_of_mem ha) t_s\n\nlemma comap_neq_bot_of_surj {f : filter β} {m : α → β}\n (hf : f ≠ ⊥) (hm : ∀b, ∃a, m a = b) : comap m f ≠ ⊥ :=\ncomap_neq_bot $ assume t ht,\n let\n ⟨b, (hx : b ∈ t)⟩ := inhabited_of_mem_sets hf ht,\n ⟨a, (ha : m a = b)⟩ := hm b\n in ⟨a, ha.symm ▸ hx⟩\n\n@[simp] lemma map_eq_bot_iff : map m f = ⊥ ↔ f = ⊥ :=\n⟨by rw [←empty_in_sets_eq_bot, ←empty_in_sets_eq_bot]; exact id,\n assume h, by simp only [h, eq_self_iff_true, map_bot]⟩\n\nlemma map_ne_bot (hf : f ≠ ⊥) : map m f ≠ ⊥ :=\nassume h, hf $ by rwa [map_eq_bot_iff] at h\n\nlemma sInter_comap_sets (f : α → β) (F : filter β) :\n ⋂₀(comap f F).sets = ⋂ U ∈ F, f ⁻¹' U :=\nbegin\n ext x,\n suffices : (∀ (A : set α) (B : set β), B ∈ F → f ⁻¹' B ⊆ A → x ∈ A) ↔\n ∀ (B : set β), B ∈ F → f x ∈ B,\n by simp only [mem_sInter, mem_Inter, mem_comap_sets, this, and_imp, mem_comap_sets, exists_prop, mem_sInter,\n iff_self, mem_Inter, mem_preimage_eq, exists_imp_distrib],\n split,\n { intros h U U_in,\n simpa only [set.subset.refl, forall_prop_of_true, mem_preimage_eq] using h (f ⁻¹' U) U U_in },\n { intros h V U U_in f_U_V,\n exact f_U_V (h U U_in) },\nend\nend map\n\nlemma map_cong {m₁ m₂ : α → β} {f : filter α} (h : {x | m₁ x = m₂ x} ∈ f) :\n map m₁ f = map m₂ f :=\nhave ∀(m₁ m₂ : α → β) (h : {x | m₁ x = m₂ x} ∈ f), map m₁ f ≤ map m₂ f,\nbegin\n intros m₁ m₂ h s hs,\n show {x | m₁ x ∈ s} ∈ f,\n filter_upwards [h, hs],\n simp only [subset_def, mem_preimage_eq, mem_set_of_eq, forall_true_iff] {contextual := tt}\nend,\nle_antisymm (this m₁ m₂ h) (this m₂ m₁ $ mem_sets_of_superset h $ assume x, eq.symm)\n\n-- this is a generic rule for monotone functions:\nlemma map_infi_le {f : ι → filter α} {m : α → β} :\n map m (infi f) ≤ (⨅ i, map m (f i)) :=\nle_infi $ assume i, map_mono $ infi_le _ _\n\nlemma map_infi_eq {f : ι → filter α} {m : α → β} (hf : directed (≥) f) (hι : nonempty ι) :\n map m (infi f) = (⨅ i, map m (f i)) :=\nle_antisymm\n map_infi_le\n (assume s (hs : preimage m s ∈ infi f),\n have ∃i, preimage m s ∈ f i,\n by simp only [infi_sets_eq hf hι, mem_Union] at hs; assumption,\n let ⟨i, hi⟩ := this in\n have (⨅ i, map m (f i)) ≤ principal s, from\n infi_le_of_le i $ by simp only [le_principal_iff, mem_map]; assumption,\n by simp only [filter.le_principal_iff] at this; assumption)\n\nlemma map_binfi_eq {ι : Type w} {f : ι → filter α} {m : α → β} {p : ι → Prop}\n (h : directed_on (f ⁻¹'o (≥)) {x | p x}) (ne : ∃i, p i) :\n map m (⨅i (h : p i), f i) = (⨅i (h: p i), map m (f i)) :=\nlet ⟨i, hi⟩ := ne in\ncalc map m (⨅i (h : p i), f i) = map m (⨅i:subtype p, f i.val) : by simp only [infi_subtype, eq_self_iff_true]\n ... = (⨅i:subtype p, map m (f i.val)) : map_infi_eq\n (assume ⟨x, hx⟩ ⟨y, hy⟩, match h x hx y hy with ⟨z, h₁, h₂, h₃⟩ := ⟨⟨z, h₁⟩, h₂, h₃⟩ end)\n ⟨⟨i, hi⟩⟩\n ... = (⨅i (h : p i), map m (f i)) : by simp only [infi_subtype, eq_self_iff_true]\n\nlemma map_inf' {f g : filter α} {m : α → β} {t : set α} (htf : t ∈ f) (htg : t ∈ g)\n (h : ∀x∈t, ∀y∈t, m x = m y → x = y) : map m (f ⊓ g) = map m f ⊓ map m g :=\nbegin\n refine le_antisymm\n (le_inf (map_mono inf_le_left) (map_mono inf_le_right))\n (assume s hs, _),\n simp only [map, mem_inf_sets, exists_prop, mem_map, mem_preimage_eq, mem_inf_sets] at hs ⊢,\n rcases hs with ⟨t₁, h₁, t₂, h₂, hs⟩,\n refine ⟨m '' (t₁ ∩ t), _, m '' (t₂ ∩ t), _, _⟩,\n { filter_upwards [h₁, htf] assume a h₁ h₂, mem_image_of_mem _ ⟨h₁, h₂⟩ },\n { filter_upwards [h₂, htg] assume a h₁ h₂, mem_image_of_mem _ ⟨h₁, h₂⟩ },\n { rw [image_inter_on],\n { refine image_subset_iff.2 _,\n exact λ x ⟨⟨h₁, _⟩, h₂, _⟩, hs ⟨h₁, h₂⟩ },\n { exact λ x ⟨_, hx⟩ y ⟨_, hy⟩, h x hx y hy } }\nend\n\nlemma map_inf {f g : filter α} {m : α → β} (h : ∀ x y, m x = m y → x = y) :\n map m (f ⊓ g) = map m f ⊓ map m g :=\nmap_inf' univ_mem_sets univ_mem_sets (assume x _ y _, h x y)\n\nlemma map_eq_comap_of_inverse {f : filter α} {m : α → β} {n : β → α}\n (h₁ : m ∘ n = id) (h₂ : n ∘ m = id) : map m f = comap n f :=\nle_antisymm\n (assume b ⟨a, ha, (h : preimage n a ⊆ b)⟩, f.sets_of_superset ha $\n calc a = preimage (n ∘ m) a : by simp only [h₂, preimage_id, eq_self_iff_true]\n ... ⊆ preimage m b : preimage_mono h)\n (assume b (hb : preimage m b ∈ f),\n ⟨preimage m b, hb, show preimage (m ∘ n) b ⊆ b, by simp only [h₁]; apply subset.refl⟩)\n\nlemma map_swap_eq_comap_swap {f : filter (α × β)} : prod.swap <$> f = comap prod.swap f :=\nmap_eq_comap_of_inverse prod.swap_swap_eq prod.swap_swap_eq\n\nlemma le_map {f : filter α} {m : α → β} {g : filter β} (h : ∀s∈ f, m '' s ∈ g) :\n g ≤ f.map m :=\nassume s hs, mem_sets_of_superset (h _ hs) $ image_preimage_subset _ _\n\nsection applicative\n\n@[simp] lemma mem_pure_sets {a : α} {s : set α} :\n s ∈ (pure a : filter α) ↔ a ∈ s :=\nby simp only [iff_self, pure_def, mem_principal_sets, singleton_subset_iff]\n\nlemma singleton_mem_pure_sets {a : α} : {a} ∈ (pure a : filter α) :=\nby simp only [mem_singleton, pure_def, mem_principal_sets, singleton_subset_iff]\n\n@[simp] lemma pure_neq_bot {α : Type u} {a : α} : pure a ≠ (⊥ : filter α) :=\nby simp only [pure, has_pure.pure, ne.def, not_false_iff, singleton_ne_empty, principal_eq_bot_iff]\n\nlemma mem_seq_sets_def {f : filter (α → β)} {g : filter α} {s : set β} :\n s ∈ f.seq g ↔ (∃u ∈ f, ∃t ∈ g, ∀x∈u, ∀y∈t, (x : α → β) y ∈ s) :=\niff.refl _\n\nlemma mem_seq_sets_iff {f : filter (α → β)} {g : filter α} {s : set β} :\n s ∈ f.seq g ↔ (∃u ∈ f, ∃t ∈ g, set.seq u t ⊆ s) :=\nby simp only [mem_seq_sets_def, seq_subset, exists_prop, iff_self]\n\nlemma mem_map_seq_iff {f : filter α} {g : filter β} {m : α → β → γ} {s : set γ} :\n s ∈ (f.map m).seq g ↔ (∃t u, t ∈ g ∧ u ∈ f ∧ ∀x∈u, ∀y∈t, m x y ∈ s) :=\niff.intro\n (assume ⟨t, ht, s, hs, hts⟩, ⟨s, m ⁻¹' t, hs, ht, assume a, hts _⟩)\n (assume ⟨t, s, ht, hs, hts⟩, ⟨m '' s, image_mem_map hs, t, ht, assume f ⟨a, has, eq⟩, eq ▸ hts _ has⟩)\n\nlemma seq_mem_seq_sets {f : filter (α → β)} {g : filter α} {s : set (α → β)} {t : set α}\n (hs : s ∈ f) (ht : t ∈ g): s.seq t ∈ f.seq g :=\n⟨s, hs, t, ht, assume f hf a ha, ⟨f, hf, a, ha, rfl⟩⟩\n\nlemma le_seq {f : filter (α → β)} {g : filter α} {h : filter β}\n (hh : ∀t ∈ f, ∀u ∈ g, set.seq t u ∈ h) : h ≤ seq f g :=\nassume s ⟨t, ht, u, hu, hs⟩, mem_sets_of_superset (hh _ ht _ hu) $\n assume b ⟨m, hm, a, ha, eq⟩, eq ▸ hs _ hm _ ha\n\nlemma seq_mono {f₁ f₂ : filter (α → β)} {g₁ g₂ : filter α}\n (hf : f₁ ≤ f₂) (hg : g₁ ≤ g₂) : f₁.seq g₁ ≤ f₂.seq g₂ :=\nle_seq $ assume s hs t ht, seq_mem_seq_sets (hf hs) (hg ht)\n\n@[simp] lemma pure_seq_eq_map (g : α → β) (f : filter α) : seq (pure g) f = f.map g :=\nbegin\n refine le_antisymm (le_map $ assume s hs, _) (le_seq $ assume s hs t ht, _),\n { rw ← singleton_seq, apply seq_mem_seq_sets _ hs,\n simp only [mem_singleton, pure_def, mem_principal_sets, singleton_subset_iff] },\n { rw mem_pure_sets at hs,\n refine sets_of_superset (map g f) (image_mem_map ht) _,\n rintros b ⟨a, ha, rfl⟩, exact ⟨g, hs, a, ha, rfl⟩ }\nend\n\n@[simp] lemma map_pure (f : α → β) (a : α) : map f (pure a) = pure (f a) :=\nle_antisymm\n (le_principal_iff.2 $ sets_of_superset (map f (pure a)) (image_mem_map singleton_mem_pure_sets) $\n by simp only [image_singleton, mem_singleton, singleton_subset_iff])\n (le_map $ assume s, begin\n simp only [mem_image, pure_def, mem_principal_sets, singleton_subset_iff],\n exact assume has, ⟨a, has, rfl⟩\n end)\n\n@[simp] lemma seq_pure (f : filter (α → β)) (a : α) : seq f (pure a) = map (λg:α → β, g a) f :=\nbegin\n refine le_antisymm (le_map $ assume s hs, _) (le_seq $ assume s hs t ht, _),\n { rw ← seq_singleton, exact seq_mem_seq_sets hs\n (by simp only [mem_singleton, pure_def, mem_principal_sets, singleton_subset_iff]) },\n { rw mem_pure_sets at ht,\n refine sets_of_superset (map (λg:α→β, g a) f) (image_mem_map hs) _,\n rintros b ⟨g, hg, rfl⟩, exact ⟨g, hg, a, ht, rfl⟩ }\nend\n\n@[simp] lemma seq_assoc (x : filter α) (g : filter (α → β)) (h : filter (β → γ)) :\n seq h (seq g x) = seq (seq (map (∘) h) g) x :=\nbegin\n refine le_antisymm (le_seq $ assume s hs t ht, _) (le_seq $ assume s hs t ht, _),\n { rcases mem_seq_sets_iff.1 hs with ⟨u, hu, v, hv, hs⟩,\n rcases mem_map_sets_iff.1 hu with ⟨w, hw, hu⟩,\n refine mem_sets_of_superset _\n (set.seq_mono (subset.trans (set.seq_mono hu (subset.refl _)) hs) (subset.refl _)),\n rw ← set.seq_seq,\n exact seq_mem_seq_sets hw (seq_mem_seq_sets hv ht) },\n { rcases mem_seq_sets_iff.1 ht with ⟨u, hu, v, hv, ht⟩,\n refine mem_sets_of_superset _ (set.seq_mono (subset.refl _) ht),\n rw set.seq_seq,\n exact seq_mem_seq_sets (seq_mem_seq_sets (image_mem_map hs) hu) hv }\nend\n\nlemma prod_map_seq_comm (f : filter α) (g : filter β) :\n (map prod.mk f).seq g = seq (map (λb a, (a, b)) g) f :=\nbegin\n refine le_antisymm (le_seq $ assume s hs t ht, _) (le_seq $ assume s hs t ht, _),\n { rcases mem_map_sets_iff.1 hs with ⟨u, hu, hs⟩,\n refine mem_sets_of_superset _ (set.seq_mono hs (subset.refl _)),\n rw ← set.prod_image_seq_comm,\n exact seq_mem_seq_sets (image_mem_map ht) hu },\n { rcases mem_map_sets_iff.1 hs with ⟨u, hu, hs⟩,\n refine mem_sets_of_superset _ (set.seq_mono hs (subset.refl _)),\n rw set.prod_image_seq_comm,\n exact seq_mem_seq_sets (image_mem_map ht) hu }\nend\n\ninstance : is_lawful_functor (filter : Type u → Type u) :=\n{ id_map := assume α f, map_id,\n comp_map := assume α β γ f g a, map_map.symm }\n\ninstance : is_lawful_applicative (filter : Type u → Type u) :=\n{ pure_seq_eq_map := assume α β, pure_seq_eq_map,\n map_pure := assume α β, map_pure,\n seq_pure := assume α β, seq_pure,\n seq_assoc := assume α β γ, seq_assoc }\n\ninstance : is_comm_applicative (filter : Type u → Type u) :=\n⟨assume α β f g, prod_map_seq_comm f g⟩\n\nlemma {l} seq_eq_filter_seq {α β : Type l} (f : filter (α → β)) (g : filter α) :\n f <*> g = seq f g := rfl\n\nend applicative\n\n/- bind equations -/\nsection bind\n@[simp] lemma mem_bind_sets {s : set β} {f : filter α} {m : α → filter β} :\n s ∈ bind f m ↔ ∃t ∈ f, ∀x ∈ t, s ∈ m x :=\ncalc s ∈ bind f m ↔ {a | s ∈ m a} ∈ f : by simp only [bind, mem_map, iff_self, mem_join_sets, mem_set_of_eq]\n ... ↔ (∃t ∈ f, t ⊆ {a | s ∈ m a}) : exists_sets_subset_iff.symm\n ... ↔ (∃t ∈ f, ∀x ∈ t, s ∈ m x) : iff.refl _\n\nlemma bind_mono {f : filter α} {g h : α → filter β} (h₁ : {a | g a ≤ h a} ∈ f) :\n bind f g ≤ bind f h :=\nassume x h₂, show (_ ∈ f), by filter_upwards [h₁, h₂] assume s gh' h', gh' h'\n\nlemma bind_sup {f g : filter α} {h : α → filter β} :\n bind (f ⊔ g) h = bind f h ⊔ bind g h :=\nby simp only [bind, sup_join, map_sup, eq_self_iff_true]\n\nlemma bind_mono2 {f g : filter α} {h : α → filter β} (h₁ : f ≤ g) :\n bind f h ≤ bind g h :=\nassume s h', h₁ h'\n\nlemma principal_bind {s : set α} {f : α → filter β} :\n (bind (principal s) f) = (⨆x ∈ s, f x) :=\nshow join (map f (principal s)) = (⨆x ∈ s, f x),\n by simp only [Sup_image, join_principal_eq_Sup, map_principal, eq_self_iff_true]\n\nend bind\n\nlemma infi_neq_bot_of_directed {f : ι → filter α}\n (hn : nonempty α) (hd : directed (≥) f) (hb : ∀i, f i ≠ ⊥) : (infi f) ≠ ⊥ :=\nlet ⟨x⟩ := hn in\nassume h, have he: ∅ ∈ (infi f), from h.symm ▸ (mem_bot_sets : ∅ ∈ (⊥ : filter α)),\nclassical.by_cases\n (assume : nonempty ι,\n have ∃i, ∅ ∈ f i,\n by rw [mem_infi hd this] at he; simp only [mem_Union] at he; assumption,\n let ⟨i, hi⟩ := this in\n hb i $ bot_unique $\n assume s _, (f i).sets_of_superset hi $ empty_subset _)\n (assume : ¬ nonempty ι,\n have univ ⊆ (∅ : set α),\n begin\n rw [←principal_mono, principal_univ, principal_empty, ←h],\n exact (le_infi $ assume i, false.elim $ this ⟨i⟩)\n end,\n this $ mem_univ x)\n\nlemma infi_neq_bot_iff_of_directed {f : ι → filter α}\n (hn : nonempty α) (hd : directed (≥) f) : (infi f) ≠ ⊥ ↔ (∀i, f i ≠ ⊥) :=\n⟨assume neq_bot i eq_bot, neq_bot $ bot_unique $ infi_le_of_le i $ eq_bot ▸ le_refl _,\n infi_neq_bot_of_directed hn hd⟩\n\nlemma mem_infi_sets {f : ι → filter α} (i : ι) : ∀{s}, s ∈ f i → s ∈ ⨅i, f i :=\nshow (⨅i, f i) ≤ f i, from infi_le _ _\n\n@[elab_as_eliminator]\nlemma infi_sets_induct {f : ι → filter α} {s : set α} (hs : s ∈ infi f) {p : set α → Prop}\n (uni : p univ)\n (ins : ∀{i s₁ s₂}, s₁ ∈ f i → p s₂ → p (s₁ ∩ s₂))\n (upw : ∀{s₁ s₂}, s₁ ⊆ s₂ → p s₁ → p s₂) : p s :=\nbegin\n rw [mem_infi_finite] at hs,\n simp only [mem_Union, (finset.inf_eq_infi _ _).symm] at hs,\n rcases hs with ⟨is, his⟩,\n revert s,\n refine finset.induction_on is _ _,\n { assume s hs, rwa [mem_top_sets.1 hs] },\n { rintros ⟨i⟩ js his ih s hs,\n rw [finset.inf_insert, mem_inf_sets] at hs,\n rcases hs with ⟨s₁, hs₁, s₂, hs₂, hs⟩,\n exact upw hs (ins hs₁ (ih hs₂)) }\nend\n\n/- tendsto -/\n\n/-- `tendsto` is the generic \"limit of a function\" predicate.\n `tendsto f l₁ l₂` asserts that for every `l₂` neighborhood `a`,\n the `f`-preimage of `a` is an `l₁` neighborhood. -/\ndef tendsto (f : α → β) (l₁ : filter α) (l₂ : filter β) := l₁.map f ≤ l₂\n\nlemma tendsto_def {f : α → β} {l₁ : filter α} {l₂ : filter β} :\n tendsto f l₁ l₂ ↔ ∀ s ∈ l₂, f ⁻¹' s ∈ l₁ := iff.rfl\n\nlemma tendsto_iff_comap {f : α → β} {l₁ : filter α} {l₂ : filter β} :\n tendsto f l₁ l₂ ↔ l₁ ≤ l₂.comap f :=\nmap_le_iff_le_comap\n\nlemma tendsto.congr' {f₁ f₂ : α → β} {l₁ : filter α} {l₂ : filter β}\n (hl : {x | f₁ x = f₂ x} ∈ l₁) (h : tendsto f₁ l₁ l₂) : tendsto f₂ l₁ l₂ :=\nby rwa [tendsto, ←map_cong hl]\n\ntheorem tendsto.congr'r {f₁ f₂ : α → β} {l₁ : filter α} {l₂ : filter β}\n (h : ∀ x, f₁ x = f₂ x) : tendsto f₁ l₁ l₂ ↔ tendsto f₂ l₁ l₂ :=\niff_of_eq (by congr'; exact funext h)\n\ntheorem tendsto.congr {f₁ f₂ : α → β} {l₁ : filter α} {l₂ : filter β}\n (h : ∀ x, f₁ x = f₂ x) : tendsto f₁ l₁ l₂ → tendsto f₂ l₁ l₂ :=\n(tendsto.congr'r h).1\n\nlemma tendsto_id' {x y : filter α} : x ≤ y → tendsto id x y :=\nby simp only [tendsto, map_id, forall_true_iff] {contextual := tt}\n\nlemma tendsto_id {x : filter α} : tendsto id x x := tendsto_id' $ le_refl x\n\nlemma tendsto.comp {f : α → β} {g : β → γ} {x : filter α} {y : filter β} {z : filter γ}\n (hf : tendsto f x y) (hg : tendsto g y z) : tendsto (g ∘ f) x z :=\ncalc map (g ∘ f) x = map g (map f x) : by rw [map_map]\n ... ≤ map g y : map_mono hf\n ... ≤ z : hg\n\nlemma tendsto_le_left {f : α → β} {x y : filter α} {z : filter β}\n (h : y ≤ x) : tendsto f x z → tendsto f y z :=\nle_trans (map_mono h)\n\nlemma tendsto_le_right {f : α → β} {x : filter α} {y z : filter β}\n (h₁ : y ≤ z) (h₂ : tendsto f x y) : tendsto f x z :=\nle_trans h₂ h₁\n\nlemma tendsto_map {f : α → β} {x : filter α} : tendsto f x (map f x) := le_refl (map f x)\n\nlemma tendsto_map' {f : β → γ} {g : α → β} {x : filter α} {y : filter γ}\n (h : tendsto (f ∘ g) x y) : tendsto f (map g x) y :=\nby rwa [tendsto, map_map]\n\nlemma tendsto_map'_iff {f : β → γ} {g : α → β} {x : filter α} {y : filter γ} :\n tendsto f (map g x) y ↔ tendsto (f ∘ g) x y :=\nby rw [tendsto, map_map]; refl\n\nlemma tendsto_comap {f : α → β} {x : filter β} : tendsto f (comap f x) x :=\nmap_comap_le\n\nlemma tendsto_comap_iff {f : α → β} {g : β → γ} {a : filter α} {c : filter γ} :\n tendsto f a (c.comap g) ↔ tendsto (g ∘ f) a c :=\n⟨assume h, h.comp tendsto_comap, assume h, map_le_iff_le_comap.mp $ by rwa [map_map]⟩\n\nlemma tendsto_comap'_iff {m : α → β} {f : filter α} {g : filter β} {i : γ → α}\n (h : range i ∈ f) : tendsto (m ∘ i) (comap i f) g ↔ tendsto m f g :=\nby rw [tendsto, ← map_compose]; simp only [(∘), map_comap h, tendsto]\n\nlemma comap_eq_of_inverse {f : filter α} {g : filter β} {φ : α → β} (ψ : β → α)\n (eq : ψ ∘ φ = id) (hφ : tendsto φ f g) (hψ : tendsto ψ g f) : comap φ g = f :=\nbegin\n refine le_antisymm (le_trans (comap_mono $ map_le_iff_le_comap.1 hψ) _) (map_le_iff_le_comap.1 hφ),\n rw [comap_comap_comp, eq, comap_id],\n exact le_refl _\nend\n\nlemma map_eq_of_inverse {f : filter α} {g : filter β} {φ : α → β} (ψ : β → α)\n (eq : φ ∘ ψ = id) (hφ : tendsto φ f g) (hψ : tendsto ψ g f) : map φ f = g :=\nbegin\n refine le_antisymm hφ (le_trans _ (map_mono hψ)),\n rw [map_map, eq, map_id],\n exact le_refl _\nend\n\nlemma tendsto_inf {f : α → β} {x : filter α} {y₁ y₂ : filter β} :\n tendsto f x (y₁ ⊓ y₂) ↔ tendsto f x y₁ ∧ tendsto f x y₂ :=\nby simp only [tendsto, lattice.le_inf_iff, iff_self]\n\nlemma tendsto_inf_left {f : α → β} {x₁ x₂ : filter α} {y : filter β}\n (h : tendsto f x₁ y) : tendsto f (x₁ ⊓ x₂) y :=\nle_trans (map_mono inf_le_left) h\n\nlemma tendsto_inf_right {f : α → β} {x₁ x₂ : filter α} {y : filter β}\n (h : tendsto f x₂ y) : tendsto f (x₁ ⊓ x₂) y :=\nle_trans (map_mono inf_le_right) h\n\nlemma tendsto_infi {f : α → β} {x : filter α} {y : ι → filter β} :\n tendsto f x (⨅i, y i) ↔ ∀i, tendsto f x (y i) :=\nby simp only [tendsto, iff_self, lattice.le_infi_iff]\n\nlemma tendsto_infi' {f : α → β} {x : ι → filter α} {y : filter β} (i : ι) :\n tendsto f (x i) y → tendsto f (⨅i, x i) y :=\ntendsto_le_left (infi_le _ _)\n\nlemma tendsto_principal {f : α → β} {a : filter α} {s : set β} :\n tendsto f a (principal s) ↔ {a | f a ∈ s} ∈ a :=\nby simp only [tendsto, le_principal_iff, mem_map, iff_self]\n\nlemma tendsto_principal_principal {f : α → β} {s : set α} {t : set β} :\n tendsto f (principal s) (principal t) ↔ ∀a∈s, f a ∈ t :=\nby simp only [tendsto, image_subset_iff, le_principal_iff, map_principal, mem_principal_sets]; refl\n\nlemma tendsto_pure_pure (f : α → β) (a : α) :\n tendsto f (pure a) (pure (f a)) :=\nshow filter.map f (pure a) ≤ pure (f a),\n by rw [filter.map_pure]; exact le_refl _\n\nlemma tendsto_const_pure {a : filter α} {b : β} : tendsto (λa, b) a (pure b) :=\nby simp [tendsto]; exact univ_mem_sets\n\nlemma tendsto_if {l₁ : filter α} {l₂ : filter β}\n {f g : α → β} {p : α → Prop} [decidable_pred p]\n (h₀ : tendsto f (l₁ ⊓ principal p) l₂)\n (h₁ : tendsto g (l₁ ⊓ principal { x | ¬ p x }) l₂) :\n tendsto (λ x, if p x then f x else g x) l₁ l₂ :=\nbegin\n revert h₀ h₁, simp only [tendsto_def, mem_inf_principal],\n intros h₀ h₁ s hs,\n apply mem_sets_of_superset (inter_mem_sets (h₀ s hs) (h₁ s hs)),\n rintros x ⟨hp₀, hp₁⟩, dsimp,\n by_cases h : p x,\n { rw if_pos h, exact hp₀ h },\n rw if_neg h, exact hp₁ h\nend\n\n\nsection prod\nvariables {s : set α} {t : set β} {f : filter α} {g : filter β}\n/- The product filter cannot be defined using the monad structure on filters. For example:\n\n F := do {x <- seq, y <- top, return (x, y)}\n hence:\n s ∈ F <-> ∃n, [n..∞] × univ ⊆ s\n\n G := do {y <- top, x <- seq, return (x, y)}\n hence:\n s ∈ G <-> ∀i:ℕ, ∃n, [n..∞] × {i} ⊆ s\n\n Now ⋃i, [i..∞] × {i} is in G but not in F.\n\n As product filter we want to have F as result.\n-/\n\n/-- Product of filters. This is the filter generated by cartesian products\n of elements of the component filters. -/\nprotected def prod (f : filter α) (g : filter β) : filter (α × β) :=\nf.comap prod.fst ⊓ g.comap prod.snd\n\nlemma prod_mem_prod {s : set α} {t : set β} {f : filter α} {g : filter β}\n (hs : s ∈ f) (ht : t ∈ g) : set.prod s t ∈ filter.prod f g :=\ninter_mem_inf_sets (preimage_mem_comap hs) (preimage_mem_comap ht)\n\nlemma mem_prod_iff {s : set (α×β)} {f : filter α} {g : filter β} :\n s ∈ filter.prod f g ↔ (∃ t₁ ∈ f, ∃ t₂ ∈ g, set.prod t₁ t₂ ⊆ s) :=\nbegin\n simp only [filter.prod],\n split,\n exact assume ⟨t₁, ⟨s₁, hs₁, hts₁⟩, t₂, ⟨s₂, hs₂, hts₂⟩, h⟩,\n ⟨s₁, hs₁, s₂, hs₂, subset.trans (inter_subset_inter hts₁ hts₂) h⟩,\n exact assume ⟨t₁, ht₁, t₂, ht₂, h⟩,\n ⟨prod.fst ⁻¹' t₁, ⟨t₁, ht₁, subset.refl _⟩, prod.snd ⁻¹' t₂, ⟨t₂, ht₂, subset.refl _⟩, h⟩\nend\n\nlemma tendsto_fst {f : filter α} {g : filter β} : tendsto prod.fst (filter.prod f g) f :=\ntendsto_inf_left tendsto_comap\n\nlemma tendsto_snd {f : filter α} {g : filter β} : tendsto prod.snd (filter.prod f g) g :=\ntendsto_inf_right tendsto_comap\n\nlemma tendsto.prod_mk {f : filter α} {g : filter β} {h : filter γ} {m₁ : α → β} {m₂ : α → γ}\n (h₁ : tendsto m₁ f g) (h₂ : tendsto m₂ f h) : tendsto (λx, (m₁ x, m₂ x)) f (filter.prod g h) :=\ntendsto_inf.2 ⟨tendsto_comap_iff.2 h₁, tendsto_comap_iff.2 h₂⟩\n\nlemma prod_infi_left {f : ι → filter α} {g : filter β} (i : ι) :\n filter.prod (⨅i, f i) g = (⨅i, filter.prod (f i) g) :=\nby rw [filter.prod, comap_infi, infi_inf i]; simp only [filter.prod, eq_self_iff_true]\n\nlemma prod_infi_right {f : filter α} {g : ι → filter β} (i : ι) :\n filter.prod f (⨅i, g i) = (⨅i, filter.prod f (g i)) :=\nby rw [filter.prod, comap_infi, inf_infi i]; simp only [filter.prod, eq_self_iff_true]\n\nlemma prod_mono {f₁ f₂ : filter α} {g₁ g₂ : filter β} (hf : f₁ ≤ f₂) (hg : g₁ ≤ g₂) :\n filter.prod f₁ g₁ ≤ filter.prod f₂ g₂ :=\ninf_le_inf (comap_mono hf) (comap_mono hg)\n\nlemma prod_comap_comap_eq {α₁ : Type u} {α₂ : Type v} {β₁ : Type w} {β₂ : Type x}\n {f₁ : filter α₁} {f₂ : filter α₂} {m₁ : β₁ → α₁} {m₂ : β₂ → α₂} :\n filter.prod (comap m₁ f₁) (comap m₂ f₂) = comap (λp:β₁×β₂, (m₁ p.1, m₂ p.2)) (filter.prod f₁ f₂) :=\nby simp only [filter.prod, comap_comap_comp, eq_self_iff_true, comap_inf]\n\nlemma prod_comm' : filter.prod f g = comap (prod.swap) (filter.prod g f) :=\nby simp only [filter.prod, comap_comap_comp, (∘), inf_comm, prod.fst_swap,\n eq_self_iff_true, prod.snd_swap, comap_inf]\n\nlemma prod_comm : filter.prod f g = map (λp:β×α, (p.2, p.1)) (filter.prod g f) :=\nby rw [prod_comm', ← map_swap_eq_comap_swap]; refl\n\nlemma prod_map_map_eq {α₁ : Type u} {α₂ : Type v} {β₁ : Type w} {β₂ : Type x}\n {f₁ : filter α₁} {f₂ : filter α₂} {m₁ : α₁ → β₁} {m₂ : α₂ → β₂} :\n filter.prod (map m₁ f₁) (map m₂ f₂) = map (λp:α₁×α₂, (m₁ p.1, m₂ p.2)) (filter.prod f₁ f₂) :=\nle_antisymm\n (assume s hs,\n let ⟨s₁, hs₁, s₂, hs₂, h⟩ := mem_prod_iff.mp hs in\n filter.sets_of_superset _ (prod_mem_prod (image_mem_map hs₁) (image_mem_map hs₂)) $\n calc set.prod (m₁ '' s₁) (m₂ '' s₂) = (λp:α₁×α₂, (m₁ p.1, m₂ p.2)) '' set.prod s₁ s₂ :\n set.prod_image_image_eq\n ... ⊆ _ : by rwa [image_subset_iff])\n ((tendsto_fst.comp (le_refl _)).prod_mk (tendsto_snd.comp (le_refl _)))\n\nlemma map_prod (m : α × β → γ) (f : filter α) (g : filter β) :\n map m (f.prod g) = (f.map (λa b, m (a, b))).seq g :=\nbegin\n simp [filter.ext_iff, mem_prod_iff, mem_map_seq_iff],\n assume s,\n split,\n exact assume ⟨t, ht, s, hs, h⟩, ⟨s, hs, t, ht, assume x hx y hy, @h ⟨x, y⟩ ⟨hx, hy⟩⟩,\n exact assume ⟨s, hs, t, ht, h⟩, ⟨t, ht, s, hs, assume ⟨x, y⟩ ⟨hx, hy⟩, h x hx y hy⟩\nend\n\nlemma prod_eq {f : filter α} {g : filter β} : f.prod g = (f.map prod.mk).seq g :=\nhave h : _ := map_prod id f g, by rwa [map_id] at h\n\nlemma prod_inf_prod {f₁ f₂ : filter α} {g₁ g₂ : filter β} :\n filter.prod f₁ g₁ ⊓ filter.prod f₂ g₂ = filter.prod (f₁ ⊓ f₂) (g₁ ⊓ g₂) :=\nby simp only [filter.prod, comap_inf, inf_comm, inf_assoc, lattice.inf_left_comm]\n\n@[simp] lemma prod_bot {f : filter α} : filter.prod f (⊥ : filter β) = ⊥ := by simp [filter.prod]\n@[simp] lemma bot_prod {g : filter β} : filter.prod (⊥ : filter α) g = ⊥ := by simp [filter.prod]\n\n@[simp] lemma prod_principal_principal {s : set α} {t : set β} :\n filter.prod (principal s) (principal t) = principal (set.prod s t) :=\nby simp only [filter.prod, comap_principal, principal_eq_iff_eq, comap_principal, inf_principal]; refl\n\n@[simp] lemma prod_pure_pure {a : α} {b : β} : filter.prod (pure a) (pure b) = pure (a, b) :=\nby simp\n\nlemma prod_eq_bot {f : filter α} {g : filter β} : filter.prod f g = ⊥ ↔ (f = ⊥ ∨ g = ⊥) :=\nbegin\n split,\n { assume h,\n rcases mem_prod_iff.1 (empty_in_sets_eq_bot.2 h) with ⟨s, hs, t, ht, hst⟩,\n rw [subset_empty_iff, set.prod_eq_empty_iff] at hst,\n cases hst with s_eq t_eq,\n { left, exact empty_in_sets_eq_bot.1 (s_eq ▸ hs) },\n { right, exact empty_in_sets_eq_bot.1 (t_eq ▸ ht) } },\n { rintros (rfl | rfl),\n exact bot_prod,\n exact prod_bot }\nend\n\nlemma prod_neq_bot {f : filter α} {g : filter β} : filter.prod f g ≠ ⊥ ↔ (f ≠ ⊥ ∧ g ≠ ⊥) :=\nby rw [(≠), prod_eq_bot, not_or_distrib]\n\nlemma tendsto_prod_iff {f : α × β → γ} {x : filter α} {y : filter β} {z : filter γ} :\n filter.tendsto f (filter.prod x y) z ↔\n ∀ W ∈ z, ∃ U ∈ x, ∃ V ∈ y, ∀ x y, x ∈ U → y ∈ V → f (x, y) ∈ W :=\nby simp only [tendsto_def, mem_prod_iff, prod_sub_preimage_iff, exists_prop, iff_self]\n\nend prod\n\n/- at_top and at_bot -/\n\n/-- `at_top` is the filter representing the limit `→ ∞` on an ordered set.\n It is generated by the collection of up-sets `{b | a ≤ b}`.\n (The preorder need not have a top element for this to be well defined,\n and indeed is trivial when a top element exists.) -/\ndef at_top [preorder α] : filter α := ⨅ a, principal {b | a ≤ b}\n\n/-- `at_bot` is the filter representing the limit `→ -∞` on an ordered set.\n It is generated by the collection of down-sets `{b | b ≤ a}`.\n (The preorder need not have a bottom element for this to be well defined,\n and indeed is trivial when a bottom element exists.) -/\ndef at_bot [preorder α] : filter α := ⨅ a, principal {b | b ≤ a}\n\nlemma mem_at_top [preorder α] (a : α) : {b : α | a ≤ b} ∈ @at_top α _ :=\nmem_infi_sets a $ subset.refl _\n\n@[simp] lemma at_top_ne_bot [nonempty α] [semilattice_sup α] : (at_top : filter α) ≠ ⊥ :=\ninfi_neq_bot_of_directed (by apply_instance)\n (assume a b, ⟨a ⊔ b, by simp only [ge, le_principal_iff, forall_const, set_of_subset_set_of,\n mem_principal_sets, and_self, sup_le_iff, forall_true_iff] {contextual := tt}⟩)\n (assume a, by simp only [principal_eq_bot_iff, ne.def, principal_eq_bot_iff]; exact ne_empty_of_mem (le_refl a))\n\n@[simp] lemma mem_at_top_sets [nonempty α] [semilattice_sup α] {s : set α} :\n s ∈ (at_top : filter α) ↔ ∃a:α, ∀b≥a, b ∈ s :=\nlet ⟨a⟩ := ‹nonempty α› in\niff.intro\n (assume h, infi_sets_induct h ⟨a, by simp only [forall_const, mem_univ, forall_true_iff]⟩\n (assume a s₁ s₂ ha ⟨b, hb⟩, ⟨a ⊔ b,\n assume c hc, ⟨ha $ le_trans le_sup_left hc, hb _ $ le_trans le_sup_right hc⟩⟩)\n (assume s₁ s₂ h ⟨a, ha⟩, ⟨a, assume b hb, h $ ha _ hb⟩))\n (assume ⟨a, h⟩, mem_infi_sets a $ assume x, h x)\n\nlemma map_at_top_eq [nonempty α] [semilattice_sup α] {f : α → β} :\n at_top.map f = (⨅a, principal $ f '' {a' | a ≤ a'}) :=\ncalc map f (⨅a, principal {a' | a ≤ a'}) = (⨅a, map f $ principal {a' | a ≤ a'}) :\n map_infi_eq (assume a b, ⟨a ⊔ b, by simp only [ge, le_principal_iff, forall_const, set_of_subset_set_of,\n mem_principal_sets, and_self, sup_le_iff, forall_true_iff] {contextual := tt}⟩)\n (by apply_instance)\n ... = (⨅a, principal $ f '' {a' | a ≤ a'}) : by simp only [map_principal, eq_self_iff_true]\n\nlemma tendsto_at_top [preorder β] (m : α → β) (f : filter α) :\n tendsto m f at_top ↔ (∀b, {a | b ≤ m a} ∈ f) :=\nby simp only [at_top, tendsto_infi, tendsto_principal]; refl\n\nlemma tendsto_at_top' [nonempty α] [semilattice_sup α] (f : α → β) (l : filter β) :\n tendsto f at_top l ↔ (∀s ∈ l, ∃a, ∀b≥a, f b ∈ s) :=\nby simp only [tendsto_def, mem_at_top_sets]; refl\n\ntheorem tendsto_at_top_principal [nonempty β] [semilattice_sup β] {f : β → α} {s : set α} :\n tendsto f at_top (principal s) ↔ ∃N, ∀n≥N, f n ∈ s :=\nby rw [tendsto_iff_comap, comap_principal, le_principal_iff, mem_at_top_sets]; refl\n\n/-- A function `f` grows to infinity independent of an order-preserving embedding `e`. -/\nlemma tendsto_at_top_embedding {α β γ : Type*} [preorder β] [preorder γ]\n {f : α → β} {e : β → γ} {l : filter α}\n (hm : ∀b₁ b₂, e b₁ ≤ e b₂ ↔ b₁ ≤ b₂) (hu : ∀c, ∃b, c ≤ e b) :\n tendsto (e ∘ f) l at_top ↔ tendsto f l at_top :=\nbegin\n rw [tendsto_at_top, tendsto_at_top],\n split,\n { assume hc b,\n filter_upwards [hc (e b)] assume a, (hm b (f a)).1 },\n { assume hb c,\n rcases hu c with ⟨b, hc⟩,\n filter_upwards [hb b] assume a ha, le_trans hc ((hm b (f a)).2 ha) }\nend\n\nlemma tendsto_at_top_at_top [nonempty α] [semilattice_sup α] [preorder β] (f : α → β) :\n tendsto f at_top at_top ↔ ∀ b : β, ∃ i : α, ∀ a : α, i ≤ a → b ≤ f a :=\niff.trans tendsto_infi $ forall_congr $ assume b, tendsto_at_top_principal\n\nlemma tendsto_finset_image_at_top_at_top {i : β → γ} {j : γ → β} (h : ∀x, j (i x) = x) :\n tendsto (λs:finset γ, s.image j) at_top at_top :=\ntendsto_infi.2 $ assume s, tendsto_infi' (s.image i) $ tendsto_principal_principal.2 $\n assume t (ht : s.image i ⊆ t),\n calc s = (s.image i).image j :\n by simp only [finset.image_image, (∘), h]; exact finset.image_id.symm\n ... ⊆ t.image j : finset.image_subset_image ht\n\nlemma prod_at_top_at_top_eq {β₁ β₂ : Type*} [inhabited β₁] [inhabited β₂] [semilattice_sup β₁]\n [semilattice_sup β₂] : filter.prod (@at_top β₁ _) (@at_top β₂ _) = @at_top (β₁ × β₂) _ :=\nby simp [at_top, prod_infi_left (default β₁), prod_infi_right (default β₂), infi_prod];\n exact infi_comm\n\nlemma prod_map_at_top_eq {α₁ α₂ β₁ β₂ : Type*} [inhabited β₁] [inhabited β₂]\n [semilattice_sup β₁] [semilattice_sup β₂] (u₁ : β₁ → α₁) (u₂ : β₂ → α₂) :\n filter.prod (map u₁ at_top) (map u₂ at_top) = map (prod.map u₁ u₂) at_top :=\nby rw [prod_map_map_eq, prod_at_top_at_top_eq, prod.map_def]\n\n/-- A function `f` maps upwards closed sets (at_top sets) to upwards closed sets when it is a\nGalois insertion. The Galois \"insertion\" and \"connection\" is weakened to only require it to be an\ninsertion and a connetion above `b'`. -/\nlemma map_at_top_eq_of_gc [semilattice_sup α] [semilattice_sup β] {f : α → β} (g : β → α) (b' : β)(hf : monotone f) (gc : ∀a, ∀b≥b', f a ≤ b ↔ a ≤ g b) (hgi : ∀b≥b', b ≤ f (g b)) :\n map f at_top = at_top :=\nbegin\n rw [@map_at_top_eq α _ ⟨g b'⟩],\n refine le_antisymm\n (le_infi $ assume b, infi_le_of_le (g (b ⊔ b')) $ principal_mono.2 $ image_subset_iff.2 _)\n (le_infi $ assume a, infi_le_of_le (f a ⊔ b') $ principal_mono.2 _),\n { assume a ha, exact (le_trans le_sup_left $ le_trans (hgi _ le_sup_right) $ hf ha) },\n { assume b hb,\n have hb' : b' ≤ b := le_trans le_sup_right hb,\n exact ⟨g b, (gc _ _ hb').1 (le_trans le_sup_left hb),\n le_antisymm ((gc _ _ hb').2 (le_refl _)) (hgi _ hb')⟩ }\nend\n\nlemma map_add_at_top_eq_nat (k : ℕ) : map (λa, a + k) at_top = at_top :=\nmap_at_top_eq_of_gc (λa, a - k) k\n (assume a b h, add_le_add_right h k)\n (assume a b h, (nat.le_sub_right_iff_add_le h).symm)\n (assume a h, by rw [nat.sub_add_cancel h])\n\nlemma map_sub_at_top_eq_nat (k : ℕ) : map (λa, a - k) at_top = at_top :=\nmap_at_top_eq_of_gc (λa, a + k) 0\n (assume a b h, nat.sub_le_sub_right h _)\n (assume a b _, nat.sub_le_right_iff_le_add)\n (assume b _, by rw [nat.add_sub_cancel])\n\nlemma tendso_add_at_top_nat (k : ℕ) : tendsto (λa, a + k) at_top at_top :=\nle_of_eq (map_add_at_top_eq_nat k)\n\nlemma tendso_sub_at_top_nat (k : ℕ) : tendsto (λa, a - k) at_top at_top :=\nle_of_eq (map_sub_at_top_eq_nat k)\n\nlemma tendsto_add_at_top_iff_nat {f : ℕ → α} {l : filter α} (k : ℕ) :\n tendsto (λn, f (n + k)) at_top l ↔ tendsto f at_top l :=\nshow tendsto (f ∘ (λn, n + k)) at_top l ↔ tendsto f at_top l,\n by rw [← tendsto_map'_iff, map_add_at_top_eq_nat]\n\nlemma map_div_at_top_eq_nat (k : ℕ) (hk : k > 0) : map (λa, a / k) at_top = at_top :=\nmap_at_top_eq_of_gc (λb, b * k + (k - 1)) 1\n (assume a b h, nat.div_le_div_right h)\n (assume a b _,\n calc a / k ≤ b ↔ a / k < b + 1 : by rw [← nat.succ_eq_add_one, nat.lt_succ_iff]\n ... ↔ a < (b + 1) * k : nat.div_lt_iff_lt_mul _ _ hk\n ... ↔ _ :\n begin\n cases k,\n exact (lt_irrefl _ hk).elim,\n simp [mul_add, add_mul, nat.succ_add, nat.lt_succ_iff]\n end)\n (assume b _,\n calc b = (b * k) / k : by rw [nat.mul_div_cancel b hk]\n ... ≤ (b * k + (k - 1)) / k : nat.div_le_div_right $ nat.le_add_right _ _)\n\n/- ultrafilter -/\n\nsection ultrafilter\nopen zorn\n\nvariables {f g : filter α}\n\n/-- An ultrafilter is a minimal (maximal in the set order) proper filter. -/\ndef is_ultrafilter (f : filter α) := f ≠ ⊥ ∧ ∀g, g ≠ ⊥ → g ≤ f → f ≤ g\n\nlemma ultrafilter_unique (hg : is_ultrafilter g) (hf : f ≠ ⊥) (h : f ≤ g) : f = g :=\nle_antisymm h (hg.right _ hf h)\n\nlemma le_of_ultrafilter {g : filter α} (hf : is_ultrafilter f) (h : f ⊓ g ≠ ⊥) :\n f ≤ g :=\nle_of_inf_eq $ ultrafilter_unique hf h inf_le_left\n\n/-- Equivalent characterization of ultrafilters:\n A filter f is an ultrafilter if and only if for each set s,\n -s belongs to f if and only if s does not belong to f. -/\nlemma ultrafilter_iff_compl_mem_iff_not_mem :\n is_ultrafilter f ↔ (∀ s, -s ∈ f ↔ s ∉ f) :=\n⟨assume hf s,\n ⟨assume hns hs,\n hf.1 $ empty_in_sets_eq_bot.mp $ by convert f.inter_sets hs hns; rw [inter_compl_self],\n assume hs,\n have f ≤ principal (-s), from\n le_of_ultrafilter hf $ assume h, hs $ mem_sets_of_neq_bot $\n by simp only [h, eq_self_iff_true, lattice.neg_neg],\n by simp only [le_principal_iff] at this; assumption⟩,\n assume hf,\n ⟨mt empty_in_sets_eq_bot.mpr ((hf ∅).mp (by convert f.univ_sets; rw [compl_empty])),\n assume g hg g_le s hs, classical.by_contradiction $ mt (hf s).mpr $\n assume : - s ∈ f,\n have s ∩ -s ∈ g, from inter_mem_sets hs (g_le this),\n by simp only [empty_in_sets_eq_bot, hg, inter_compl_self] at this; contradiction⟩⟩\n\nlemma mem_or_compl_mem_of_ultrafilter (hf : is_ultrafilter f) (s : set α) :\n s ∈ f ∨ - s ∈ f :=\nclassical.or_iff_not_imp_left.2 (ultrafilter_iff_compl_mem_iff_not_mem.mp hf s).mpr\n\nlemma mem_or_mem_of_ultrafilter {s t : set α} (hf : is_ultrafilter f) (h : s ∪ t ∈ f) :\n s ∈ f ∨ t ∈ f :=\n(mem_or_compl_mem_of_ultrafilter hf s).imp_right\n (assume : -s ∈ f, by filter_upwards [this, h] assume x hnx hx, hx.resolve_left hnx)\n\nlemma mem_of_finite_sUnion_ultrafilter {s : set (set α)} (hf : is_ultrafilter f) (hs : finite s)\n : ⋃₀ s ∈ f → ∃t∈s, t ∈ f :=\nfinite.induction_on hs (by simp only [empty_in_sets_eq_bot, hf.left, mem_empty_eq, sUnion_empty,\n forall_prop_of_false, exists_false, not_false_iff, exists_prop_of_false]) $\nλ t s' ht' hs' ih, by simp only [exists_prop, mem_insert_iff, set.sUnion_insert]; exact\nassume h, (mem_or_mem_of_ultrafilter hf h).elim\n (assume : t ∈ f, ⟨t, or.inl rfl, this⟩)\n (assume h, let ⟨t, hts', ht⟩ := ih h in ⟨t, or.inr hts', ht⟩)\n\nlemma mem_of_finite_Union_ultrafilter {is : set β} {s : β → set α}\n (hf : is_ultrafilter f) (his : finite is) (h : (⋃i∈is, s i) ∈ f) : ∃i∈is, s i ∈ f :=\nhave his : finite (image s is), from finite_image s his,\nhave h : (⋃₀ image s is) ∈ f, from by simp only [sUnion_image, set.sUnion_image]; assumption,\nlet ⟨t, ⟨i, hi, h_eq⟩, (ht : t ∈ f)⟩ := mem_of_finite_sUnion_ultrafilter hf his h in\n⟨i, hi, h_eq.symm ▸ ht⟩\n\nlemma ultrafilter_map {f : filter α} {m : α → β} (h : is_ultrafilter f) : is_ultrafilter (map m f) :=\nby rw ultrafilter_iff_compl_mem_iff_not_mem at ⊢ h; exact assume s, h (m ⁻¹' s)\n\nlemma ultrafilter_pure {a : α} : is_ultrafilter (pure a) :=\nbegin\n rw ultrafilter_iff_compl_mem_iff_not_mem, intro s,\n rw [mem_pure_sets, mem_pure_sets], exact iff.rfl\nend\n\nlemma ultrafilter_bind {f : filter α} (hf : is_ultrafilter f) {m : α → filter β}\n (hm : ∀ a, is_ultrafilter (m a)) : is_ultrafilter (f.bind m) :=\nbegin\n simp only [ultrafilter_iff_compl_mem_iff_not_mem] at ⊢ hf hm, intro s,\n dsimp [bind, join, map],\n simp only [hm], apply hf\nend\n\n/-- The ultrafilter lemma: Any proper filter is contained in an ultrafilter. -/\nlemma exists_ultrafilter (h : f ≠ ⊥) : ∃u, u ≤ f ∧ is_ultrafilter u :=\nlet\n τ := {f' // f' ≠ ⊥ ∧ f' ≤ f},\n r : τ → τ → Prop := λt₁ t₂, t₂.val ≤ t₁.val,\n ⟨a, ha⟩ := inhabited_of_mem_sets h univ_mem_sets,\n top : τ := ⟨f, h, le_refl f⟩,\n sup : Π(c:set τ), chain r c → τ :=\n λc hc, ⟨⨅a:{a:τ // a ∈ insert top c}, a.val.val,\n infi_neq_bot_of_directed ⟨a⟩\n (directed_of_chain $ chain_insert hc $ assume ⟨b, _, hb⟩ _ _, or.inl hb)\n (assume ⟨⟨a, ha, _⟩, _⟩, ha),\n infi_le_of_le ⟨top, mem_insert _ _⟩ (le_refl _)⟩\nin\nhave ∀c (hc: chain r c) a (ha : a ∈ c), r a (sup c hc),\n from assume c hc a ha, infi_le_of_le ⟨a, mem_insert_of_mem _ ha⟩ (le_refl _),\nhave (∃ (u : τ), ∀ (a : τ), r u a → r a u),\n from zorn (assume c hc, ⟨sup c hc, this c hc⟩) (assume f₁ f₂ f₃ h₁ h₂, le_trans h₂ h₁),\nlet ⟨uτ, hmin⟩ := this in\n⟨uτ.val, uτ.property.right, uτ.property.left, assume g hg₁ hg₂,\n hmin ⟨g, hg₁, le_trans hg₂ uτ.property.right⟩ hg₂⟩\n\n/-- Construct an ultrafilter extending a given filter.\n The ultrafilter lemma is the assertion that such a filter exists;\n we use the axiom of choice to pick one. -/\nnoncomputable def ultrafilter_of (f : filter α) : filter α :=\nif h : f = ⊥ then ⊥ else classical.epsilon (λu, u ≤ f ∧ is_ultrafilter u)\n\nlemma ultrafilter_of_spec (h : f ≠ ⊥) : ultrafilter_of f ≤ f ∧ is_ultrafilter (ultrafilter_of f) :=\nbegin\n have h' := classical.epsilon_spec (exists_ultrafilter h),\n simp only [ultrafilter_of, dif_neg, h, dif_neg, not_false_iff],\n simp only at h',\n assumption\nend\n\nlemma ultrafilter_of_le : ultrafilter_of f ≤ f :=\nif h : f = ⊥ then by simp only [ultrafilter_of, dif_pos, h, dif_pos, eq_self_iff_true, le_bot_iff]; exact le_refl _\n else (ultrafilter_of_spec h).left\n\nlemma ultrafilter_ultrafilter_of (h : f ≠ ⊥) : is_ultrafilter (ultrafilter_of f) :=\n(ultrafilter_of_spec h).right\n\nlemma ultrafilter_of_ultrafilter (h : is_ultrafilter f) : ultrafilter_of f = f :=\nultrafilter_unique h (ultrafilter_ultrafilter_of h.left).left ultrafilter_of_le\n\n/-- A filter equals the intersection of all the ultrafilters which contain it. -/\nlemma sup_of_ultrafilters (f : filter α) : f = ⨆ (g) (u : is_ultrafilter g) (H : g ≤ f), g :=\nbegin\n refine le_antisymm _ (supr_le $ λ g, supr_le $ λ u, supr_le $ λ H, H),\n intros s hs,\n -- If s ∉ f.sets, we'll apply the ultrafilter lemma to the restriction of f to -s.\n by_contradiction hs',\n let j : (-s) → α := subtype.val,\n have j_inv_s : j ⁻¹' s = ∅, by\n erw [←preimage_inter_range, subtype.val_range, inter_compl_self, preimage_empty],\n let f' := comap j f,\n have : f' ≠ ⊥,\n { apply mt empty_in_sets_eq_bot.mpr,\n rintro ⟨t, htf, ht⟩,\n suffices : t ⊆ s, from absurd (f.sets_of_superset htf this) hs',\n rw [subset_empty_iff] at ht,\n have : j '' (j ⁻¹' t) = ∅, by rw [ht, image_empty],\n erw [image_preimage_eq_inter_range, subtype.val_range, ←subset_compl_iff_disjoint,\n set.compl_compl] at this,\n exact this },\n rcases exists_ultrafilter this with ⟨g', g'f', u'⟩,\n simp only [supr_sets_eq, mem_Inter] at hs,\n have := hs (g'.map subtype.val) (ultrafilter_map u') (map_le_iff_le_comap.mpr g'f'),\n rw [←le_principal_iff, map_le_iff_le_comap, comap_principal, j_inv_s, principal_empty,\n le_bot_iff] at this,\n exact absurd this u'.1\nend\n\n/-- The `tendsto` relation can be checked on ultrafilters. -/\nlemma tendsto_iff_ultrafilter (f : α → β) (l₁ : filter α) (l₂ : filter β) :\n tendsto f l₁ l₂ ↔ ∀ g, is_ultrafilter g → g ≤ l₁ → g.map f ≤ l₂ :=\n⟨assume h g u gx, le_trans (map_mono gx) h,\n assume h, by rw [sup_of_ultrafilters l₁]; simpa only [tendsto, map_supr, supr_le_iff]⟩\n\n/- The ultrafilter monad. The monad structure on ultrafilters is the\n restriction of the one on filters. -/\n\ndef ultrafilter (α : Type u) : Type u := {f : filter α // is_ultrafilter f}\n\ndef ultrafilter.map (m : α → β) (u : ultrafilter α) : ultrafilter β :=\n⟨u.val.map m, ultrafilter_map u.property⟩\n\ndef ultrafilter.pure (x : α) : ultrafilter α := ⟨pure x, ultrafilter_pure⟩\n\ndef ultrafilter.bind (u : ultrafilter α) (m : α → ultrafilter β) : ultrafilter β :=\n⟨u.val.bind (λ a, (m a).val), ultrafilter_bind u.property (λ a, (m a).property)⟩\n\ninstance ultrafilter.has_pure : has_pure ultrafilter := ⟨@ultrafilter.pure⟩\ninstance ultrafilter.has_bind : has_bind ultrafilter := ⟨@ultrafilter.bind⟩\ninstance ultrafilter.functor : functor ultrafilter := { map := @ultrafilter.map }\ninstance ultrafilter.monad : monad ultrafilter := { map := @ultrafilter.map }\n\nnoncomputable def hyperfilter : filter α := ultrafilter_of cofinite\n\nlemma hyperfilter_le_cofinite (hi : set.infinite (@set.univ α)) : @hyperfilter α ≤ cofinite := \n(ultrafilter_of_spec (cofinite_ne_bot hi)).1\n\nlemma is_ultrafilter_hyperfilter (hi : set.infinite (@set.univ α)) : is_ultrafilter (@hyperfilter α) := \n(ultrafilter_of_spec (cofinite_ne_bot hi)).2\n\ntheorem nmem_hyperfilter_of_finite (hi : set.infinite (@set.univ α)) {s : set α} (hf : set.finite s) :\n s ∉ @hyperfilter α :=\nλ hy, \nhave hx : -s ∉ hyperfilter := \n λ hs, (ultrafilter_iff_compl_mem_iff_not_mem.mp (is_ultrafilter_hyperfilter hi) s).mp hs hy,\nhave ht : -s ∈ cofinite.sets := by show -s ∈ {s | _}; rwa [set.mem_set_of_eq, lattice.neg_neg],\nhx $ hyperfilter_le_cofinite hi ht\n\ntheorem compl_mem_hyperfilter_of_finite (hi : set.infinite (@set.univ α)) {s : set α} (hf : set.finite s) :\n -s ∈ @hyperfilter α :=\n(ultrafilter_iff_compl_mem_iff_not_mem.mp (is_ultrafilter_hyperfilter hi) s).mpr $ \nnmem_hyperfilter_of_finite hi hf\n\ntheorem mem_hyperfilter_of_finite_compl (hi : set.infinite (@set.univ α)) {s : set α} (hf : set.finite (-s)) :\n s ∈ @hyperfilter α := \nhave h : _ := compl_mem_hyperfilter_of_finite hi hf,\nby rwa [lattice.neg_neg] at h\n\nsection\n\nlocal attribute [instance] filter.monad filter.is_lawful_monad\n\ninstance ultrafilter.is_lawful_monad : is_lawful_monad ultrafilter :=\n{ id_map := assume α f, subtype.eq (id_map f.val),\n pure_bind := assume α β a f, subtype.eq (pure_bind a (subtype.val ∘ f)),\n bind_assoc := assume α β γ f m₁ m₂, subtype.eq (filter_eq rfl),\n bind_pure_comp_eq_map := assume α β f x, subtype.eq (bind_pure_comp_eq_map _ f x.val) }\n\nend\n\nlemma ultrafilter.eq_iff_val_le_val {u v : ultrafilter α} : u = v ↔ u.val ≤ v.val :=\n⟨assume h, by rw h; exact le_refl _,\n assume h, by rw subtype.ext; apply ultrafilter_unique v.property u.property.1 h⟩\n\nlemma exists_ultrafilter_iff (f : filter α) : (∃ (u : ultrafilter α), u.val ≤ f) ↔ f ≠ ⊥ :=\n⟨assume ⟨u, uf⟩, lattice.neq_bot_of_le_neq_bot u.property.1 uf,\n assume h, let ⟨u, uf, hu⟩ := exists_ultrafilter h in ⟨⟨u, hu⟩, uf⟩⟩\n\nend ultrafilter\n\nend filter\n\nnamespace filter\nvariables {α β γ : Type u} {f : β → filter α} {s : γ → set α}\nopen list\n\nlemma mem_traverse_sets :\n ∀(fs : list β) (us : list γ),\n forall₂ (λb c, s c ∈ f b) fs us → traverse s us ∈ traverse f fs\n| [] [] forall₂.nil := mem_pure_sets.2 $ mem_singleton _\n| (f::fs) (u::us) (forall₂.cons h hs) := seq_mem_seq_sets (image_mem_map h) (mem_traverse_sets fs us hs)\n\nlemma mem_traverse_sets_iff (fs : list β) (t : set (list α)) :\n t ∈ traverse f fs ↔\n (∃us:list (set α), forall₂ (λb (s : set α), s ∈ f b) fs us ∧ sequence us ⊆ t) :=\nbegin\n split,\n { induction fs generalizing t,\n case nil { simp only [sequence, pure_def, imp_self, forall₂_nil_left_iff, pure_def,\n exists_eq_left, mem_principal_sets, set.pure_def, singleton_subset_iff, traverse_nil] },\n case cons : b fs ih t {\n assume ht,\n rcases mem_seq_sets_iff.1 ht with ⟨u, hu, v, hv, ht⟩,\n rcases mem_map_sets_iff.1 hu with ⟨w, hw, hwu⟩,\n rcases ih v hv with ⟨us, hus, hu⟩,\n exact ⟨w :: us, forall₂.cons hw hus, subset.trans (set.seq_mono hwu hu) ht⟩ } },\n { rintros ⟨us, hus, hs⟩,\n exact mem_sets_of_superset (mem_traverse_sets _ _ hus) hs }\nend\n\nlemma sequence_mono :\n ∀(as bs : list (filter α)), forall₂ (≤) as bs → sequence as ≤ sequence bs\n| [] [] forall₂.nil := le_refl _\n| (a::as) (b::bs) (forall₂.cons h hs) := seq_mono (map_mono h) (sequence_mono as bs hs)\n\nend filter\n", "meta": {"author": "digama0", "repo": "mathlib-ITP2019", "sha": "5cbd0362e04e671ef5db1284870592af6950197c", "save_path": "github-repos/lean/digama0-mathlib-ITP2019", "path": "github-repos/lean/digama0-mathlib-ITP2019/mathlib-ITP2019-5cbd0362e04e671ef5db1284870592af6950197c/src/order/filter/basic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.04084572058025284, "lm_q1q2_score": 0.02026330994015678}} {"text": "/-\nCopyright (c) 2019 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Leonardo de Moura\n-/\nimport Lean.Compiler.IR.Basic\nimport Lean.Compiler.IR.LiveVars\nimport Lean.Compiler.IR.Format\n\nnamespace Lean.IR.ResetReuse\n/- Remark: the insertResetReuse transformation is applied before we have\n inserted `inc/dec` instructions, and perfomed lower level optimizations\n that introduce the instructions `release` and `set`. -/\n\n/- Remark: the functions `S`, `D` and `R` defined here implement the\n corresponding functions in the paper \"Counting Immutable Beans\"\n\n Here are the main differences:\n - We use the State monad to manage the generation of fresh variable names.\n - Support for join points, and `uset` and `sset` instructions for unboxed data.\n - `D` uses the auxiliary function `Dmain`.\n - `Dmain` returns a pair `(b, found)` to avoid quadratic behavior when checking\n the last occurrence of the variable `x`.\n - Because we have join points in the actual implementation, a variable may be live even if it\n does not occur in a function body. See example at `livevars.lean`.\n-/\n\nprivate def mayReuse (c₁ c₂ : CtorInfo) : Bool :=\n c₁.size == c₂.size && c₁.usize == c₂.usize && c₁.ssize == c₂.ssize &&\n /- The following condition is a heuristic.\n We don't want to reuse cells from different types even when they are compatible\n because it produces counterintuitive behavior. -/\n c₁.name.getPrefix == c₂.name.getPrefix\n\nprivate partial def S (w : VarId) (c : CtorInfo) : FnBody → FnBody\n | FnBody.vdecl x t v@(Expr.ctor c' ys) b =>\n if mayReuse c c' then\n let updtCidx := c.cidx != c'.cidx\n FnBody.vdecl x t (Expr.reuse w c' updtCidx ys) b\n else\n FnBody.vdecl x t v (S w c b)\n | FnBody.jdecl j ys v b =>\n let v' := S w c v\n if v == v' then FnBody.jdecl j ys v (S w c b)\n else FnBody.jdecl j ys v' b\n | FnBody.case tid x xType alts => FnBody.case tid x xType $ alts.map $ fun alt => alt.modifyBody (S w c)\n | b =>\n if b.isTerminal then b\n else let\n (instr, b) := b.split\n instr.setBody (S w c b)\n\n/- We use `Context` to track join points in scope. -/\nabbrev M := ReaderT LocalContext (StateT Index Id)\n\nprivate def mkFresh : M VarId := do\n let idx ← getModify (fun n => n + 1)\n pure { idx := idx }\n\nprivate def tryS (x : VarId) (c : CtorInfo) (b : FnBody) : M FnBody := do\n let w ← mkFresh\n let b' := S w c b\n if b == b' then pure b\n else pure $ FnBody.vdecl w IRType.object (Expr.reset c.size x) b'\n\nprivate def Dfinalize (x : VarId) (c : CtorInfo) : FnBody × Bool → M FnBody\n | (b, true) => pure b\n | (b, false) => tryS x c b\n\nprivate def argsContainsVar (ys : Array Arg) (x : VarId) : Bool :=\n ys.any fun arg => match arg with\n | Arg.var y => x == y\n | _ => false\n\nprivate def isCtorUsing (b : FnBody) (x : VarId) : Bool :=\n match b with\n | (FnBody.vdecl _ _ (Expr.ctor _ ys) _) => argsContainsVar ys x\n | _ => false\n\n/- Given `Dmain b`, the resulting pair `(new_b, flag)` contains the new body `new_b`,\n and `flag == true` if `x` is live in `b`.\n\n Note that, in the function `D` defined in the paper, for each `let x := e; F`,\n `D` checks whether `x` is live in `F` or not. This is great for clarity but it\n is expensive: `O(n^2)` where `n` is the size of the function body. -/\nprivate partial def Dmain (x : VarId) (c : CtorInfo) : FnBody → M (FnBody × Bool)\n | e@(FnBody.case tid y yType alts) => do\n let ctx ← read\n if e.hasLiveVar ctx x then do\n /- If `x` is live in `e`, we recursively process each branch. -/\n let alts ← alts.mapM fun alt => alt.mmodifyBody fun b => Dmain x c b >>= Dfinalize x c\n pure (FnBody.case tid y yType alts, true)\n else pure (e, false)\n | FnBody.jdecl j ys v b => do\n let (b, found) ← withReader (fun ctx => ctx.addJP j ys v) (Dmain x c b)\n let (v, _ /- found' -/) ← Dmain x c v\n /- If `found' == true`, then `Dmain b` must also have returned `(b, true)` since\n we assume the IR does not have dead join points. So, if `x` is live in `j` (i.e., `v`),\n then it must also live in `b` since `j` is reachable from `b` with a `jmp`.\n On the other hand, `x` may be live in `b` but dead in `j` (i.e., `v`). -/\n pure (FnBody.jdecl j ys v b, found)\n | e => do\n let ctx ← read\n if e.isTerminal then\n pure (e, e.hasLiveVar ctx x)\n else do\n let (instr, b) := e.split\n if isCtorUsing instr x then\n /- If the scrutinee `x` (the one that is providing memory) is being\n stored in a constructor, then reuse will probably not be able to reuse memory at runtime.\n It may work only if the new cell is consumed, but we ignore this case. -/\n pure (e, true)\n else\n let (b, found) ← Dmain x c b\n /- Remark: it is fine to use `hasFreeVar` instead of `hasLiveVar`\n since `instr` is not a `FnBody.jmp` (it is not a terminal) nor it is a `FnBody.jdecl`. -/\n if found || !instr.hasFreeVar x then\n pure (instr.setBody b, found)\n else\n let b ← tryS x c b\n pure (instr.setBody b, true)\n\nprivate def D (x : VarId) (c : CtorInfo) (b : FnBody) : M FnBody :=\n Dmain x c b >>= Dfinalize x c\n\npartial def R : FnBody → M FnBody\n | FnBody.case tid x xType alts => do\n let alts ← alts.mapM fun alt => do\n let alt ← alt.mmodifyBody R\n match alt with\n | Alt.ctor c b =>\n if c.isScalar then pure alt\n else Alt.ctor c <$> D x c b\n | _ => pure alt\n pure $ FnBody.case tid x xType alts\n | FnBody.jdecl j ys v b => do\n let v ← R v\n let b ← withReader (fun ctx => ctx.addJP j ys v) (R b)\n pure $ FnBody.jdecl j ys v b\n | e => do\n if e.isTerminal then pure e\n else do\n let (instr, b) := e.split\n let b ← R b\n pure (instr.setBody b)\n\nend ResetReuse\n\nopen ResetReuse\n\ndef Decl.insertResetReuse (d : Decl) : Decl :=\n match d with\n | Decl.fdecl (body := b) ..=>\n let nextIndex := d.maxIndex + 1\n let bNew := (R b {}).run' nextIndex\n d.updateBody! bNew\n | other => other\n\nend Lean.IR\n", "meta": {"author": "gebner", "repo": "lean4-old", "sha": "ee51cdfaf63ee313c914d83264f91f414a0e3b6e", "save_path": "github-repos/lean/gebner-lean4-old", "path": "github-repos/lean/gebner-lean4-old/lean4-old-ee51cdfaf63ee313c914d83264f91f414a0e3b6e/stage0/src/Lean/Compiler/IR/ResetReuse.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.26588047309981694, "lm_q2_score": 0.07585818158818373, "lm_q1q2_score": 0.020169209209158115}} {"text": "/-\nCopyright (c) 2017 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Leonardo de Moura, Mario Carneiro\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.data.nat.default\nimport Mathlib.Lean3Lib.init.data.bool.default\nimport Mathlib.Lean3Lib.init.ite_simp\n \n\nuniverses u l u_1 w v \n\nnamespace Mathlib\n\n/-- In the VM, d_array is implemented as a persistent array. -/\nstructure d_array (n : ℕ) (α : fin n → Type u) \nwhere\n data : (i : fin n) → α i\n\nnamespace d_array\n\n\n/-- The empty array. -/\ndef nil {α : fin 0 → Type u_1} : d_array 0 α :=\n mk fun (_x : fin 0) => sorry\n\n/-- `read a i` reads the `i`th member of `a`. Has builtin VM implementation. -/\ndef read {n : ℕ} {α : fin n → Type u} (a : d_array n α) (i : fin n) : α i :=\n data a i\n\n/-- `write a i v` sets the `i`th member of `a` to be `v`. Has builtin VM implementation. -/\ndef write {n : ℕ} {α : fin n → Type u} (a : d_array n α) (i : fin n) (v : α i) : d_array n α :=\n mk fun (j : fin n) => dite (i = j) (fun (h : i = j) => eq.rec_on h v) fun (h : ¬i = j) => read a j\n\ndef iterate_aux {n : ℕ} {α : fin n → Type u} {β : Type w} (a : d_array n α) (f : (i : fin n) → α i → β → β) (i : ℕ) : i ≤ n → β → β :=\n sorry\n\n/-- Fold over the elements of the given array in ascending order. Has builtin VM implementation. -/\ndef iterate {n : ℕ} {α : fin n → Type u} {β : Type w} (a : d_array n α) (b : β) (f : (i : fin n) → α i → β → β) : β :=\n iterate_aux a f n sorry b\n\n/-- Map the array. Has builtin VM implementation. -/\ndef foreach {n : ℕ} {α : fin n → Type u} {α' : fin n → Type v} (a : d_array n α) (f : (i : fin n) → α i → α' i) : d_array n α' :=\n mk fun (i : fin n) => f i (read a i)\n\ndef map {n : ℕ} {α : fin n → Type u} {α' : fin n → Type v} (f : (i : fin n) → α i → α' i) (a : d_array n α) : d_array n α' :=\n foreach a f\n\ndef map₂ {n : ℕ} {α : fin n → Type u} {α' : fin n → Type v} {α'' : fin n → Type w} (f : (i : fin n) → α i → α' i → α'' i) (a : d_array n α) (b : d_array n α') : d_array n α'' :=\n foreach b fun (i : fin n) => f i (read a i)\n\ndef foldl {n : ℕ} {α : fin n → Type u} {β : Type w} (a : d_array n α) (b : β) (f : (i : fin n) → α i → β → β) : β :=\n iterate a b f\n\ndef rev_iterate_aux {n : ℕ} {α : fin n → Type u} {β : Type w} (a : d_array n α) (f : (i : fin n) → α i → β → β) (i : ℕ) : i ≤ n → β → β :=\n sorry\n\ndef rev_iterate {n : ℕ} {α : fin n → Type u} {β : Type w} (a : d_array n α) (b : β) (f : (i : fin n) → α i → β → β) : β :=\n rev_iterate_aux a f n sorry b\n\n@[simp] theorem read_write {n : ℕ} {α : fin n → Type u} (a : d_array n α) (i : fin n) (v : α i) : read (write a i v) i = v := sorry\n\n@[simp] theorem read_write_of_ne {n : ℕ} {α : fin n → Type u} (a : d_array n α) {i : fin n} {j : fin n} (v : α i) : i ≠ j → read (write a i v) j = read a j := sorry\n\nprotected theorem ext {n : ℕ} {α : fin n → Type u} {a : d_array n α} {b : d_array n α} (h : ∀ (i : fin n), read a i = read b i) : a = b := sorry\n\nprotected theorem ext' {n : ℕ} {α : fin n → Type u} {a : d_array n α} {b : d_array n α} (h : ∀ (i : ℕ) (h : i < n), read a { val := i, property := h } = read b { val := i, property := h }) : a = b := sorry\n\nprotected def beq_aux {n : ℕ} {α : fin n → Type u} [(i : fin n) → DecidableEq (α i)] (a : d_array n α) (b : d_array n α) (i : ℕ) : i ≤ n → Bool :=\n sorry\n\n/-- Boolean element-wise equality check. -/\nprotected def beq {n : ℕ} {α : fin n → Type u} [(i : fin n) → DecidableEq (α i)] (a : d_array n α) (b : d_array n α) : Bool :=\n d_array.beq_aux a b n sorry\n\ntheorem of_beq_aux_eq_tt {n : ℕ} {α : fin n → Type u} [(i : fin n) → DecidableEq (α i)] {a : d_array n α} {b : d_array n α} (i : ℕ) (h : i ≤ n) : d_array.beq_aux a b i h = tt →\n ∀ (j : ℕ) (h' : j < i),\n read a { val := j, property := lt_of_lt_of_le h' h } = read b { val := j, property := lt_of_lt_of_le h' h } := sorry\n\ntheorem of_beq_eq_tt {n : ℕ} {α : fin n → Type u} [(i : fin n) → DecidableEq (α i)] {a : d_array n α} {b : d_array n α} : d_array.beq a b = tt → a = b := sorry\n\ntheorem of_beq_aux_eq_ff {n : ℕ} {α : fin n → Type u} [(i : fin n) → DecidableEq (α i)] {a : d_array n α} {b : d_array n α} (i : ℕ) (h : i ≤ n) : d_array.beq_aux a b i h = false →\n ∃ (j : ℕ),\n ∃ (h' : j < i),\n read a { val := j, property := lt_of_lt_of_le h' h } ≠ read b { val := j, property := lt_of_lt_of_le h' h } := sorry\n\ntheorem of_beq_eq_ff {n : ℕ} {α : fin n → Type u} [(i : fin n) → DecidableEq (α i)] {a : d_array n α} {b : d_array n α} : d_array.beq a b = false → a ≠ b := sorry\n\nprotected instance decidable_eq {n : ℕ} {α : fin n → Type u} [(i : fin n) → DecidableEq (α i)] : DecidableEq (d_array n α) :=\n fun (a b : d_array n α) =>\n dite (d_array.beq a b = tt) (fun (h : d_array.beq a b = tt) => is_true sorry)\n fun (h : ¬d_array.beq a b = tt) => isFalse sorry\n\nend d_array\n\n\n/-- A non-dependent array (see `d_array`). Implemented in the VM as a persistent array. -/\ndef array (n : ℕ) (α : Type u) :=\n d_array n fun (_x : fin n) => α\n\n/-- `mk_array n v` creates a new array of length `n` where each element is `v`. Has builtin VM implementation. -/\ndef mk_array {α : Type u_1} (n : ℕ) (v : α) : array n α :=\n d_array.mk fun (_x : fin n) => v\n\nnamespace array\n\n\ndef nil {α : Type u_1} : array 0 α :=\n d_array.nil\n\ndef read {n : ℕ} {α : Type u} (a : array n α) (i : fin n) : α :=\n d_array.read a i\n\ndef write {n : ℕ} {α : Type u} (a : array n α) (i : fin n) (v : α) : array n α :=\n d_array.write a i v\n\n/-- Fold array starting from 0, folder function includes an index argument. -/\ndef iterate {n : ℕ} {α : Type u} {β : Type v} (a : array n α) (b : β) (f : fin n → α → β → β) : β :=\n d_array.iterate a b f\n\n/-- Map each element of the given array with an index argument. -/\ndef foreach {n : ℕ} {α : Type u} {β : Type v} (a : array n α) (f : fin n → α → β) : array n β :=\n d_array.foreach a f\n\ndef map₂ {n : ℕ} {α : Type u} (f : α → α → α) (a : array n α) (b : array n α) : array n α :=\n foreach b fun (i : fin n) => f (read a i)\n\ndef foldl {n : ℕ} {α : Type u} {β : Type v} (a : array n α) (b : β) (f : α → β → β) : β :=\n iterate a b fun (_x : fin n) => f\n\ndef rev_list {n : ℕ} {α : Type u} (a : array n α) : List α :=\n foldl a [] fun (_x : α) (_y : List α) => _x :: _y\n\ndef rev_iterate {n : ℕ} {α : Type u} {β : Type v} (a : array n α) (b : β) (f : fin n → α → β → β) : β :=\n d_array.rev_iterate a b f\n\ndef rev_foldl {n : ℕ} {α : Type u} {β : Type v} (a : array n α) (b : β) (f : α → β → β) : β :=\n rev_iterate a b fun (_x : fin n) => f\n\ndef to_list {n : ℕ} {α : Type u} (a : array n α) : List α :=\n rev_foldl a [] fun (_x : α) (_y : List α) => _x :: _y\n\ntheorem push_back_idx {j : ℕ} {n : ℕ} (h₁ : j < n + 1) (h₂ : j ≠ n) : j < n :=\n nat.lt_of_le_and_ne (nat.le_of_lt_succ h₁) h₂\n\n/-- `push_back a v` pushes value `v` to the end of the array. Has builtin VM implementation. -/\ndef push_back {n : ℕ} {α : Type u} (a : array n α) (v : α) : array (n + 1) α :=\n d_array.mk fun (_x : fin (n + 1)) => sorry\n\ntheorem pop_back_idx {j : ℕ} {n : ℕ} (h : j < n) : j < n + 1 :=\n nat.lt.step h\n\n/-- Discard _last_ element in the array. Has builtin VM implementation. -/\ndef pop_back {n : ℕ} {α : Type u} (a : array (n + 1) α) : array n α :=\n d_array.mk fun (_x : fin n) => sorry\n\n/-- Auxilliary function for monadically mapping a function over an array. -/\ndef mmap_core {n : ℕ} {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (a : array n α) (f : α → m β) (i : ℕ) (H : i ≤ n) : m (array i β) :=\n sorry\n\n/-- Monadically map a function over the array. -/\ndef mmap {n : ℕ} {α : Type u} {β : Type v} {m : Type v → Type u_1} [Monad m] (a : array n α) (f : α → m β) : m (array n β) :=\n mmap_core a f n sorry\n\n/-- Map a function over the array. -/\ndef map {n : ℕ} {α : Type u} {β : Type v} (a : array n α) (f : α → β) : array n β :=\n d_array.map (fun (_x : fin n) => f) a\n\nprotected def mem {n : ℕ} {α : Type u} (v : α) (a : array n α) :=\n ∃ (i : fin n), read a i = v\n\nprotected instance has_mem {n : ℕ} {α : Type u} : has_mem α (array n α) :=\n has_mem.mk array.mem\n\ntheorem read_mem {n : ℕ} {α : Type u} (a : array n α) (i : fin n) : read a i ∈ a :=\n exists.intro i rfl\n\nprotected instance has_repr {n : ℕ} {α : Type u} [has_repr α] : has_repr (array n α) :=\n has_repr.mk (repr ∘ to_list)\n\n@[simp] theorem read_write {n : ℕ} {α : Type u} (a : array n α) (i : fin n) (v : α) : read (write a i v) i = v :=\n d_array.read_write a i v\n\n@[simp] theorem read_write_of_ne {n : ℕ} {α : Type u} (a : array n α) {i : fin n} {j : fin n} (v : α) : i ≠ j → read (write a i v) j = read a j :=\n d_array.read_write_of_ne a v\n\ndef read' {n : ℕ} {β : Type v} [Inhabited β] (a : array n β) (i : ℕ) : β :=\n dite (i < n) (fun (h : i < n) => read a { val := i, property := h }) fun (h : ¬i < n) => Inhabited.default\n\ndef write' {n : ℕ} {α : Type u} (a : array n α) (i : ℕ) (v : α) : array n α :=\n dite (i < n) (fun (h : i < n) => write a { val := i, property := h } v) fun (h : ¬i < n) => a\n\ntheorem read_eq_read' {n : ℕ} {α : Type u} [Inhabited α] (a : array n α) {i : ℕ} (h : i < n) : read a { val := i, property := h } = read' a i := sorry\n\ntheorem write_eq_write' {n : ℕ} {α : Type u} (a : array n α) {i : ℕ} (h : i < n) (v : α) : write a { val := i, property := h } v = write' a i v := sorry\n\nprotected theorem ext {n : ℕ} {α : Type u} {a : array n α} {b : array n α} (h : ∀ (i : fin n), read a i = read b i) : a = b :=\n d_array.ext h\n\nprotected theorem ext' {n : ℕ} {α : Type u} {a : array n α} {b : array n α} (h : ∀ (i : ℕ) (h : i < n), read a { val := i, property := h } = read b { val := i, property := h }) : a = b :=\n d_array.ext' h\n\nprotected instance decidable_eq {n : ℕ} {α : Type u} [DecidableEq α] : DecidableEq (array n α) :=\n eq.mpr sorry fun (a b : d_array n fun (_x : fin n) => α) => d_array.decidable_eq a b\n\n", "meta": {"author": "AurelienSaue", "repo": "Mathlib4_auto", "sha": "590df64109b08190abe22358fabc3eae000943f2", "save_path": "github-repos/lean/AurelienSaue-Mathlib4_auto", "path": "github-repos/lean/AurelienSaue-Mathlib4_auto/Mathlib4_auto-590df64109b08190abe22358fabc3eae000943f2/Mathlib/Lean3Lib/init/data/array/basic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.29746993014852224, "lm_q2_score": 0.0675466977093867, "lm_q1q2_score": 0.02009311144937461}} {"text": "/-\nCopyright (c) 2022 Andrew Yang. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Andrew Yang\n-/\nimport morphisms.quasi_separated\nimport morphisms.isomorphism\n\n/-!\n\n# Affine morphisms\n\nA morphism of schemes is affine if the preimages of affine open sets are affine.\n\n-/\n\nnoncomputable theory\n\nopen category_theory category_theory.limits opposite topological_space\n\nuniverse u\n\nnamespace algebraic_geometry\n\nvariables {X Y : Scheme.{u}} (f : X ⟶ Y)\n\n/-- A morphism is `affine` if the preimages of affine open sets are affine. -/\n@[mk_iff]\nclass affine (f : X ⟶ Y) : Prop :=\n(is_affine_preimage : ∀ U : opens Y.carrier,\n is_affine_open U → is_affine_open ((opens.map f.1.base).obj U))\n\n/-- The `affine_target_morphism_property` corresponding to affine morphisms. -/\ndef affine.affine_property : affine_target_morphism_property :=\nλ X Y f hf, is_affine X\n\n@[simp] lemma affine_affine_property_to_property {X Y : Scheme} (f : X ⟶ Y) :\n affine_target_morphism_property.to_property affine.affine_property f ↔\n is_affine Y ∧ is_affine X :=\nby { delta affine_target_morphism_property.to_property affine.affine_property, simp }\n\n@[priority 900]\ninstance affine_of_is_iso {X Y : Scheme} (f : X ⟶ Y) [is_iso f] : affine f :=\n⟨λ U hU, hU.map_is_iso f⟩\n\n@[priority 100]\ninstance affine.to_quasi_compact [affine f] : quasi_compact f :=\n(quasi_compact_iff_forall_affine f).mpr (λ U hU, (affine.is_affine_preimage U hU).is_compact)\n\ninstance affine_comp {X Y Z : Scheme} (f : X ⟶ Y) (g : Y ⟶ Z)\n [affine f] [affine g] : affine (f ≫ g) :=\nbegin\n constructor,\n intros U hU,\n rw [Scheme.comp_val_base, opens.map_comp_obj],\n apply affine.is_affine_preimage,\n apply affine.is_affine_preimage,\n exact hU\nend\n\nlemma affine_iff_affine_property :\n affine f ↔ target_affine_locally affine.affine_property f :=\n(affine_iff f).trans ⟨λ H U, H U U.prop, λ H U hU, H ⟨U, hU⟩⟩\n\nlemma affine_eq_affine_property :\n @affine = target_affine_locally affine.affine_property :=\nby { ext, exact affine_iff_affine_property _ }\n\ninstance {X : Scheme} (r : X.presheaf.obj (op ⊤)) :\n affine (X.of_restrict (X.basic_open r).open_embedding) :=\nbegin\n constructor,\n intros U hU,\n fapply (is_affine_open_iff_of_is_open_immersion (X.of_restrict _) _).mp,\n swap,\n { apply_instance },\n convert hU.basic_open_is_affine (X.presheaf.map (hom_of_le le_top).op r),\n rw X.basic_open_res,\n ext1,\n refine set.image_preimage_eq_inter_range.trans _,\n erw subtype.range_coe,\n refl\nend\n\n/-- The preimage of an affine open as an `Scheme.affine_opens`. -/\n@[simps]\ndef affine_preimage {X Y : Scheme} (f : X ⟶ Y) [affine f] (U : Y.affine_opens) :\n X.affine_opens :=\n⟨(opens.map f.1.base).obj (U : opens Y.carrier), affine.is_affine_preimage _ U.prop⟩\n\nlemma is_affine_of_span_top_of_is_affine_open (X : Scheme) (s : set (X.presheaf.obj $ op ⊤))\n (h₁ : ideal.span s = ⊤) (h₂ : ∀ r : s, is_affine_open (X.basic_open r.1)) : is_affine X :=\nbegin\n haveI hX' : quasi_separated_space X.carrier,\n { obtain ⟨s', hs', e⟩ := (ideal.span_eq_top_iff_finite _).mp h₁,\n rw quasi_separated_space_iff_affine,\n intros U V,\n rw [← set.inter_univ (U ∩ V : set X.carrier), ← (show _ = set.univ, from\n (congr_arg subtype.val $ supr_basic_open_eq_top_of_span_eq_top _ _ e : _)), opens.supr_def,\n subtype.val_eq_coe, subtype.coe_mk, set.inter_Union],\n apply is_compact_Union,\n intro i,\n convert_to is_compact ((U.1 ⊓ (X.basic_open i.val)) ⊓ (V.1 ⊓ (X.basic_open i.val))).1,\n { conv_rhs { rw [inf_assoc, ← @inf_assoc _ _ (X.basic_open i.1),\n @inf_comm _ _ (X.basic_open i.1), inf_assoc, inf_idem, ← inf_assoc] },\n refl },\n have : ∀ (S : opens X.carrier), S ⊓ X.basic_open i.1 = X.basic_open\n (X.presheaf.map (hom_of_le le_top : S ⟶ _).op i.1) := λ S, (X.basic_open_res _ _).symm,\n apply (h₂ ⟨i.1, hs' i.2⟩).is_quasi_separated,\n { exact @inf_le_right _ _ U.1 _ },\n { exact (U.val ⊓ X.basic_open i.val).2 },\n { rw this, exact (U.prop.basic_open_is_affine _).is_compact },\n { exact @inf_le_right _ _ V.1 _ },\n { exact (V.val ⊓ X.basic_open i.val).2 },\n { rw this, exact (V.prop.basic_open_is_affine _).is_compact } },\n have hX : compact_space X.carrier,\n { obtain ⟨s', hs', e⟩ := (ideal.span_eq_top_iff_finite _).mp h₁,\n rw [← is_compact_univ_iff, ← (show _ = set.univ, from\n (congr_arg subtype.val $ supr_basic_open_eq_top_of_span_eq_top _ _ e : _)), opens.supr_def],\n apply is_compact_Union,\n intro i, exact (h₂ ⟨i.1, hs' i.2⟩).is_compact },\n constructor,\n rw (is_iso.open_cover_tfae (Γ_Spec.adjunction.unit.app X)).out 0 5,\n refine ⟨s, λ i, prime_spectrum.basic_open i.1, _, _⟩,\n { rw prime_spectrum.Union_basic_open_eq_top_iff, convert h₁, simp },\n { intro r,\n apply_with is_iso_of_is_affine_is_iso { instances := ff },\n { change is_affine_open _,\n rw preimage_adjunction_unit_basic_open,\n exact h₂ r },\n { change is_affine_open _,\n rw ← basic_open_eq_of_affine,\n apply is_affine_open.basic_open_is_affine,\n apply_with top_is_affine_open { instances := ff },\n exact algebraic_geometry.Spec_is_affine _ },\n { suffices : ∀ (U = prime_spectrum.basic_open r.val),\n is_iso ((Γ_Spec.adjunction.unit.app X).val.c.app (op $ U)),\n { rw morphism_restrict_c_app,\n apply_with is_iso.comp_is_iso { instances := ff },\n { apply this, rw opens.open_embedding_obj_top },\n { apply_instance } },\n rintros _ rfl,\n rw CommRing.is_iso_iff_bijective,\n fapply bijective_of_is_localization (submonoid.powers r.1),\n rotate,\n { apply structure_sheaf.open_algebra },\n { apply ring_hom.to_algebra,\n exact X.presheaf.map (hom_of_le le_top :\n (opens.map (Γ_Spec.adjunction.unit.app X).val.base).obj _ ⟶ _).op },\n { apply structure_sheaf.is_localization.to_basic_open },\n { dsimp,\n rw ← is_compact_univ_iff at hX,\n rw ← is_quasi_separated_univ_iff at hX',\n convert is_localization_basic_open_of_qcqs\n (show is_compact (⊤ : opens _).1, from hX) hX' r.1;\n apply Γ_Spec.adjunction.unit_app_map_basic_open },\n { rw [ring_hom.algebra_map_to_algebra, ring_hom.algebra_map_to_algebra,\n Γ_Spec.adjunction_unit_app],\n exact X.1.to_Γ_Spec_SheafedSpace_app_spec r.1 } } }\nend\n\nlemma affine_affine_property_is_local :\n affine_target_morphism_property.is_local affine.affine_property :=\nbegin\n split,\n { apply affine_target_morphism_property.respects_iso_mk,\n all_goals { rintros X Y Z _ _ _ (H : is_affine _), resetI },\n exacts [is_affine_of_iso e.hom, H] },\n { introv H,\n change is_affine_open _,\n rw Scheme.preimage_basic_open f r,\n exact (@@top_is_affine_open X H).basic_open_is_affine _ },\n { rintros X Y H f S hS hS',\n resetI,\n apply_fun ideal.map (f.1.c.app (op ⊤)) at hS,\n rw [ideal.map_span, ideal.map_top] at hS,\n delta affine.affine_property,\n unfreezingI { change ∀ (i : S), is_affine_open _ at hS',\n simp_rw Scheme.preimage_basic_open at hS' },\n apply is_affine_of_span_top_of_is_affine_open X _ hS,\n rintro ⟨_, r, hr, rfl⟩,\n exact hS' ⟨r, hr⟩ }\nend\n\nlemma affine_is_local_at_target :\n property_is_local_at_target @affine :=\naffine_eq_affine_property.symm ▸\n affine_affine_property_is_local.target_affine_locally_is_local\n\n\nlemma affine_affine_property_stable_under_base_change :\n affine_target_morphism_property.stable_under_base_change affine.affine_property :=\nbegin\n introv X H,\n delta affine.affine_property at H ⊢,\n resetI,\n apply_instance\nend\n\nlemma affine_stable_under_base_change :\n morphism_property.stable_under_base_change @affine :=\naffine_eq_affine_property.symm ▸\n affine_affine_property_is_local.stable_under_base_change \n affine_affine_property_stable_under_base_change\n\nlemma affine_stable_under_composition :\n morphism_property.stable_under_composition @affine :=\nλ X Y Z f g hf hg, by exactI infer_instance\n \nlemma affine_over_affine_iff {X Y : Scheme} (f : X ⟶ Y) [is_affine Y] :\n affine f ↔ is_affine X :=\naffine_eq_affine_property.symm ▸\n affine_affine_property_is_local.affine_target_iff f\n\n@[priority 100]\ninstance affine_of_is_affine [is_affine X] [is_affine Y] : affine f :=\nbegin\n rw affine_over_affine_iff,\n apply_instance\nend\n\nlemma is_affine_of_affine [affine f] [is_affine Y] : is_affine X :=\nbegin\n rw ← affine_over_affine_iff f,\n apply_instance\nend\n\nend algebraic_geometry\n", "meta": {"author": "erdOne", "repo": "lean-AG-morphisms", "sha": "bfb65e7d5c17f333abd7b1806717f12cd29427fd", "save_path": "github-repos/lean/erdOne-lean-AG-morphisms", "path": "github-repos/lean/erdOne-lean-AG-morphisms/lean-AG-morphisms-bfb65e7d5c17f333abd7b1806717f12cd29427fd/src/morphisms/affine.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.39233683016710835, "lm_q2_score": 0.05108273190089447, "lm_q1q2_score": 0.020041637110273163}} {"text": "/-\nCopyright (c) 2017 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Leonardo de Moura, Mario Carneiro\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.data.nat.default\nimport Mathlib.Lean3Lib.init.data.bool.default\nimport Mathlib.Lean3Lib.init.ite_simp\n\nuniverses u l u_1 w v \n\nnamespace Mathlib\n\n/-- In the VM, d_array is implemented as a persistent array. -/\nstructure d_array (n : ℕ) (α : fin n → Type u) where\n data : (i : fin n) → α i\n\nnamespace d_array\n\n\n/-- The empty array. -/\ndef nil {α : fin 0 → Type u_1} : d_array 0 α := mk fun (_x : fin 0) => sorry\n\n/-- `read a i` reads the `i`th member of `a`. Has builtin VM implementation. -/\ndef read {n : ℕ} {α : fin n → Type u} (a : d_array n α) (i : fin n) : α i := data a i\n\n/-- `write a i v` sets the `i`th member of `a` to be `v`. Has builtin VM implementation. -/\ndef write {n : ℕ} {α : fin n → Type u} (a : d_array n α) (i : fin n) (v : α i) : d_array n α :=\n mk fun (j : fin n) => dite (i = j) (fun (h : i = j) => eq.rec_on h v) fun (h : ¬i = j) => read a j\n\ndef iterate_aux {n : ℕ} {α : fin n → Type u} {β : Type w} (a : d_array n α)\n (f : (i : fin n) → α i → β → β) (i : ℕ) : i ≤ n → β → β :=\n sorry\n\n/-- Fold over the elements of the given array in ascending order. Has builtin VM implementation. -/\ndef iterate {n : ℕ} {α : fin n → Type u} {β : Type w} (a : d_array n α) (b : β)\n (f : (i : fin n) → α i → β → β) : β :=\n iterate_aux a f n sorry b\n\n/-- Map the array. Has builtin VM implementation. -/\ndef foreach {n : ℕ} {α : fin n → Type u} {α' : fin n → Type v} (a : d_array n α)\n (f : (i : fin n) → α i → α' i) : d_array n α' :=\n mk fun (i : fin n) => f i (read a i)\n\ndef map {n : ℕ} {α : fin n → Type u} {α' : fin n → Type v} (f : (i : fin n) → α i → α' i)\n (a : d_array n α) : d_array n α' :=\n foreach a f\n\ndef map₂ {n : ℕ} {α : fin n → Type u} {α' : fin n → Type v} {α'' : fin n → Type w}\n (f : (i : fin n) → α i → α' i → α'' i) (a : d_array n α) (b : d_array n α') : d_array n α'' :=\n foreach b fun (i : fin n) => f i (read a i)\n\ndef foldl {n : ℕ} {α : fin n → Type u} {β : Type w} (a : d_array n α) (b : β)\n (f : (i : fin n) → α i → β → β) : β :=\n iterate a b f\n\ndef rev_iterate_aux {n : ℕ} {α : fin n → Type u} {β : Type w} (a : d_array n α)\n (f : (i : fin n) → α i → β → β) (i : ℕ) : i ≤ n → β → β :=\n sorry\n\ndef rev_iterate {n : ℕ} {α : fin n → Type u} {β : Type w} (a : d_array n α) (b : β)\n (f : (i : fin n) → α i → β → β) : β :=\n rev_iterate_aux a f n sorry b\n\n@[simp] theorem read_write {n : ℕ} {α : fin n → Type u} (a : d_array n α) (i : fin n) (v : α i) :\n read (write a i v) i = v :=\n sorry\n\n@[simp] theorem read_write_of_ne {n : ℕ} {α : fin n → Type u} (a : d_array n α) {i : fin n}\n {j : fin n} (v : α i) : i ≠ j → read (write a i v) j = read a j :=\n sorry\n\nprotected theorem ext {n : ℕ} {α : fin n → Type u} {a : d_array n α} {b : d_array n α}\n (h : ∀ (i : fin n), read a i = read b i) : a = b :=\n sorry\n\nprotected theorem ext' {n : ℕ} {α : fin n → Type u} {a : d_array n α} {b : d_array n α}\n (h :\n ∀ (i : ℕ) (h : i < n),\n read a { val := i, property := h } = read b { val := i, property := h }) :\n a = b :=\n sorry\n\nprotected def beq_aux {n : ℕ} {α : fin n → Type u} [(i : fin n) → DecidableEq (α i)]\n (a : d_array n α) (b : d_array n α) (i : ℕ) : i ≤ n → Bool :=\n sorry\n\n/-- Boolean element-wise equality check. -/\nprotected def beq {n : ℕ} {α : fin n → Type u} [(i : fin n) → DecidableEq (α i)] (a : d_array n α)\n (b : d_array n α) : Bool :=\n d_array.beq_aux a b n sorry\n\ntheorem of_beq_aux_eq_tt {n : ℕ} {α : fin n → Type u} [(i : fin n) → DecidableEq (α i)]\n {a : d_array n α} {b : d_array n α} (i : ℕ) (h : i ≤ n) :\n d_array.beq_aux a b i h = tt →\n ∀ (j : ℕ) (h' : j < i),\n read a { val := j, property := lt_of_lt_of_le h' h } =\n read b { val := j, property := lt_of_lt_of_le h' h } :=\n sorry\n\ntheorem of_beq_eq_tt {n : ℕ} {α : fin n → Type u} [(i : fin n) → DecidableEq (α i)]\n {a : d_array n α} {b : d_array n α} : d_array.beq a b = tt → a = b :=\n sorry\n\ntheorem of_beq_aux_eq_ff {n : ℕ} {α : fin n → Type u} [(i : fin n) → DecidableEq (α i)]\n {a : d_array n α} {b : d_array n α} (i : ℕ) (h : i ≤ n) :\n d_array.beq_aux a b i h = false →\n ∃ (j : ℕ),\n ∃ (h' : j < i),\n read a { val := j, property := lt_of_lt_of_le h' h } ≠\n read b { val := j, property := lt_of_lt_of_le h' h } :=\n sorry\n\ntheorem of_beq_eq_ff {n : ℕ} {α : fin n → Type u} [(i : fin n) → DecidableEq (α i)]\n {a : d_array n α} {b : d_array n α} : d_array.beq a b = false → a ≠ b :=\n sorry\n\nprotected instance decidable_eq {n : ℕ} {α : fin n → Type u} [(i : fin n) → DecidableEq (α i)] :\n DecidableEq (d_array n α) :=\n fun (a b : d_array n α) =>\n dite (d_array.beq a b = tt) (fun (h : d_array.beq a b = tt) => is_true sorry)\n fun (h : ¬d_array.beq a b = tt) => isFalse sorry\n\nend d_array\n\n\n/-- A non-dependent array (see `d_array`). Implemented in the VM as a persistent array. -/\ndef array (n : ℕ) (α : Type u) := d_array n fun (_x : fin n) => α\n\n/-- `mk_array n v` creates a new array of length `n` where each element is `v`. Has builtin VM implementation. -/\ndef mk_array {α : Type u_1} (n : ℕ) (v : α) : array n α := d_array.mk fun (_x : fin n) => v\n\nnamespace array\n\n\ndef nil {α : Type u_1} : array 0 α := d_array.nil\n\ndef read {n : ℕ} {α : Type u} (a : array n α) (i : fin n) : α := d_array.read a i\n\ndef write {n : ℕ} {α : Type u} (a : array n α) (i : fin n) (v : α) : array n α :=\n d_array.write a i v\n\n/-- Fold array starting from 0, folder function includes an index argument. -/\ndef iterate {n : ℕ} {α : Type u} {β : Type v} (a : array n α) (b : β) (f : fin n → α → β → β) : β :=\n d_array.iterate a b f\n\n/-- Map each element of the given array with an index argument. -/\ndef foreach {n : ℕ} {α : Type u} {β : Type v} (a : array n α) (f : fin n → α → β) : array n β :=\n d_array.foreach a f\n\ndef map₂ {n : ℕ} {α : Type u} (f : α → α → α) (a : array n α) (b : array n α) : array n α :=\n foreach b fun (i : fin n) => f (read a i)\n\ndef foldl {n : ℕ} {α : Type u} {β : Type v} (a : array n α) (b : β) (f : α → β → β) : β :=\n iterate a b fun (_x : fin n) => f\n\ndef rev_list {n : ℕ} {α : Type u} (a : array n α) : List α :=\n foldl a [] fun (_x : α) (_y : List α) => _x :: _y\n\ndef rev_iterate {n : ℕ} {α : Type u} {β : Type v} (a : array n α) (b : β) (f : fin n → α → β → β) :\n β :=\n d_array.rev_iterate a b f\n\ndef rev_foldl {n : ℕ} {α : Type u} {β : Type v} (a : array n α) (b : β) (f : α → β → β) : β :=\n rev_iterate a b fun (_x : fin n) => f\n\ndef to_list {n : ℕ} {α : Type u} (a : array n α) : List α :=\n rev_foldl a [] fun (_x : α) (_y : List α) => _x :: _y\n\ntheorem push_back_idx {j : ℕ} {n : ℕ} (h₁ : j < n + 1) (h₂ : j ≠ n) : j < n :=\n nat.lt_of_le_and_ne (nat.le_of_lt_succ h₁) h₂\n\n/-- `push_back a v` pushes value `v` to the end of the array. Has builtin VM implementation. -/\ndef push_back {n : ℕ} {α : Type u} (a : array n α) (v : α) : array (n + 1) α :=\n d_array.mk fun (_x : fin (n + 1)) => sorry\n\ntheorem pop_back_idx {j : ℕ} {n : ℕ} (h : j < n) : j < n + 1 := nat.lt.step h\n\n/-- Discard _last_ element in the array. Has builtin VM implementation. -/\ndef pop_back {n : ℕ} {α : Type u} (a : array (n + 1) α) : array n α :=\n d_array.mk fun (_x : fin n) => sorry\n\n/-- Auxilliary function for monadically mapping a function over an array. -/\ndef mmap_core {n : ℕ} {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (a : array n α)\n (f : α → m β) (i : ℕ) (H : i ≤ n) : m (array i β) :=\n sorry\n\n/-- Monadically map a function over the array. -/\ndef mmap {n : ℕ} {α : Type u} {β : Type v} {m : Type v → Type u_1} [Monad m] (a : array n α)\n (f : α → m β) : m (array n β) :=\n mmap_core a f n sorry\n\n/-- Map a function over the array. -/\ndef map {n : ℕ} {α : Type u} {β : Type v} (a : array n α) (f : α → β) : array n β :=\n d_array.map (fun (_x : fin n) => f) a\n\nprotected def mem {n : ℕ} {α : Type u} (v : α) (a : array n α) := ∃ (i : fin n), read a i = v\n\nprotected instance has_mem {n : ℕ} {α : Type u} : has_mem α (array n α) := has_mem.mk array.mem\n\ntheorem read_mem {n : ℕ} {α : Type u} (a : array n α) (i : fin n) : read a i ∈ a :=\n exists.intro i rfl\n\nprotected instance has_repr {n : ℕ} {α : Type u} [has_repr α] : has_repr (array n α) :=\n has_repr.mk (repr ∘ to_list)\n\n@[simp] theorem read_write {n : ℕ} {α : Type u} (a : array n α) (i : fin n) (v : α) :\n read (write a i v) i = v :=\n d_array.read_write a i v\n\n@[simp] theorem read_write_of_ne {n : ℕ} {α : Type u} (a : array n α) {i : fin n} {j : fin n}\n (v : α) : i ≠ j → read (write a i v) j = read a j :=\n d_array.read_write_of_ne a v\n\ndef read' {n : ℕ} {β : Type v} [Inhabited β] (a : array n β) (i : ℕ) : β :=\n dite (i < n) (fun (h : i < n) => read a { val := i, property := h })\n fun (h : ¬i < n) => Inhabited.default\n\ndef write' {n : ℕ} {α : Type u} (a : array n α) (i : ℕ) (v : α) : array n α :=\n dite (i < n) (fun (h : i < n) => write a { val := i, property := h } v) fun (h : ¬i < n) => a\n\ntheorem read_eq_read' {n : ℕ} {α : Type u} [Inhabited α] (a : array n α) {i : ℕ} (h : i < n) :\n read a { val := i, property := h } = read' a i :=\n sorry\n\ntheorem write_eq_write' {n : ℕ} {α : Type u} (a : array n α) {i : ℕ} (h : i < n) (v : α) :\n write a { val := i, property := h } v = write' a i v :=\n sorry\n\nprotected theorem ext {n : ℕ} {α : Type u} {a : array n α} {b : array n α}\n (h : ∀ (i : fin n), read a i = read b i) : a = b :=\n d_array.ext h\n\nprotected theorem ext' {n : ℕ} {α : Type u} {a : array n α} {b : array n α}\n (h :\n ∀ (i : ℕ) (h : i < n),\n read a { val := i, property := h } = read b { val := i, property := h }) :\n a = b :=\n d_array.ext' h\n\nprotected instance decidable_eq {n : ℕ} {α : Type u} [DecidableEq α] : DecidableEq (array n α) :=\n eq.mpr sorry fun (a b : d_array n fun (_x : fin n) => α) => d_array.decidable_eq a b\n\nend Mathlib", "meta": {"author": "AurelienSaue", "repo": "Mathlib4_auto", "sha": "590df64109b08190abe22358fabc3eae000943f2", "save_path": "github-repos/lean/AurelienSaue-Mathlib4_auto", "path": "github-repos/lean/AurelienSaue-Mathlib4_auto/Mathlib4_auto-590df64109b08190abe22358fabc3eae000943f2/Mathlib/Lean3Lib/init/data/array/basic_auto.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.33807712415000585, "lm_q2_score": 0.05921024659098507, "lm_q1q2_score": 0.020017629887692918}} {"text": "example (h : x ≠ true) : (x && y) = false := by\n simp [h]\n\nexample (h : ¬ (x = true)) : (x && y) = false := by\n simp [h]\n\nexample (h : x ≠ false) : (x && y) = y := by\n simp [h]\n\nexample (h : ¬ (x = false)) : (x && y) = y := by\n simp [h]\n", "meta": {"author": "leanprover", "repo": "lean4", "sha": "742d053a97bdd109a41a921facd1cd6a55e89bc7", "save_path": "github-repos/lean/leanprover-lean4", "path": "github-repos/lean/leanprover-lean4/lean4-742d053a97bdd109a41a921facd1cd6a55e89bc7/tests/lean/run/simpBool.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3849121444839335, "lm_q2_score": 0.05184546097287379, "lm_q1q2_score": 0.019955947564826933}} {"text": "import Lean.Meta\nimport Lean.Elab\nopen Lean.Core\nopen Lean.Meta\nopen Lean.Elab.Term\nopen Lean\nopen Nat\n\ndef lower (n : MetaM Nat) : CoreM Nat :=\n n.run' {}\n\ndef raise (n: CoreM Nat) : MetaM Nat :=\n do \n let i <- n\n return i\n\n-- copied from source\n\nsyntax (name := fooKind) \"foo!\" term : term\n\n@[termElab fooKind] def elabFoo : TermElab :=\nfun stx expectedType? => elabTerm (stx.getArg 1) expectedType?\n\n#check foo! 10\n\ndef eg1 : Bool := foo! true\n\n-- example of how to use the elaborator\n\nsyntax (name := addone) \"addone!\" (term)? : term\n\ndef addoneMeta (expr0 : Expr) : MetaM Expr := \n do\n let name2 : Name := `Nat.succ\n let expr : Expr ← \n mkAppM name2 #[expr0] \n -- the expression returned by a function\n return expr\n\n\n@[termElab addone] def addoneImpl : TermElab :=\nfun stx expectedType? =>\n match stx with\n | `(addone! $s) => \n do\n let s0 ← s\n let expr0 ← elabTerm s0 (some (Lean.mkConst `Nat)) \n let name2 : Name := `Nat.succ\n let expr : Expr ← \n mkAppM name2 #[expr0] \n -- the expression returned by a function\n return expr\n | _ =>\n do\n let name : Name := `Nat.zero\n let name2 : Name := `Nat.succ\n let expr : Expr := \n mkApp (Lean.mkConst name2) (Lean.mkConst name) \n -- the expression returned by a function\n return expr\n\ndef eg2 := addone! 10\n\n#eval eg2\n#eval 3 + addone!\n\n\n\ndef metaAddOne (n: MetaM Expr) : MetaM Expr :=\n do\n let i <- n\n let env ← getEnv\n IO.println s!\"{env.contains ``succ}\"\n IO.println s!\"{env.contains `succ}\"\n let decls ← getOpenDecls\n IO.println s!\"{decls}\"\n return mkApp (Lean.mkConst ``succ) i\n\ndef addOne(n: Nat) : Nat := addone! n\n \n#print addOne\n#eval addOne 7\n#eval metaAddOne (mkConst `zero)\n#eval ``succ\n\n#check Elab.resolveGlobalConstNoOverloadWithInfo \n\ndef egNameM : TermElabM Name := do\n let stx : Syntax ← `(succ)\n IO.println s!\"syntax : {stx}\"\n match stx with\n | stx@(Syntax.ident _ _ n pre) => IO.println (s!\"n: {n}; pre :{pre}\")\n | _ => IO.println \"Error\"\n let ns : List Name ← Lean.resolveGlobalConst stx \n return ns.head! \n\n#eval egNameM\n\n#check open List Nat in fun n => cons n\n\nsyntax (name := tryapp) term \">>>>>\" term : term\n\n@[termElab tryapp] def tryappImpl : TermElab :=\nfun stx expectedType? =>\n match stx with\n | `($s >>>>> $t) =>\n do\n let f <- elabTerm s none\n let x <- elabTerm t none\n let expr : Expr := mkApp f x\n let c ← isTypeCorrect expr\n -- let cc ← hasType expr \n if c then\n return expr\n else\n return (Lean.mkConst `Nat.zero)\n -- return (Lean.mkConst `Nat.zero)\n | _ => \n do \n return (Lean.mkConst `Nat) \n\n#check Nat.succ >>>>> Nat.zero\ndef one := Nat.succ >>>>> Nat.zero\n#eval one\n\n#check Eq >>>>> 2\n#check (@Eq Nat) >>>>> 2\n\ndef shiftnat (n: Nat)(e : Expr) : MetaM Expr :=\n match n with\n | Nat.zero => return e\n | Nat.succ n => do\n let prev ← shiftnat n e\n return ← mkApp (mkConst `Nat.succ) prev \n\nsyntax (name := natshift) term \">>+>>\" term : term\n\n@[termElab natshift] def natshiftImpl : TermElab :=\nfun stx expectedType? =>\n match stx with\n | `($s >>+>> $t) =>\n do\n let e <- elabTerm s (some (Lean.mkConst `Nat))\n let n : Nat <- t.isNatLit?.getD 0\n return ← shiftnat n e\n | _ => \n do \n return (Lean.mkConst `Nat) \n\n#check 3 >>+>> 2\n#eval 3 >>+>> 12\n\n#check Lean.Syntax.mkScientificLit (Float.toString 3.14)\n\n\ninductive Someterm where\n | something : {α : Type} → (a: α ) → Someterm\n | nothing : Someterm\n\ndef Someterm.isEmpty : Someterm → Bool \n | Someterm.something _ => false\n | Someterm.nothing => true\n\nsyntax (name := tryapp2) term \" >>>> \" term : term\n\n@[termElab tryapp2] def tryappImpl2 : TermElab :=\n let nt := Lean.mkConst `Someterm.nothing\n let st := Lean.mkConst `Someterm.something\n \n fun stx expectedType? =>\n match stx with\n | `($s >>>> $t) =>\n do\n let f <- elabTerm s none\n let x <- elabTerm t none\n let expr : Expr ← mkApp f x\n let c ← isTypeCorrect expr\n -- let cc := !expr.hasExprMVar\n if c then\n return Lean.mkApp st expr\n else\n return nt\n | _ => \n do \n return nt\n\n#check Nat.succ >>>> 3\n#check Nat.succ >>>> true\n\n\n#check (Eq.trans >>>> (rfl : Nat.zero = Nat.zero)) \n\ndef optApp {α β γ : Type} (f : α → β) (x : γ) :=\n f >>>> x\n\n#print optApp\n\ndef eg3 := optApp Nat.succ 3\n\ndef eg4 := optApp Nat.succ true\n\n#eval eg3.isEmpty -- this fails, the lambda body does not type check\n#eval eg4.isEmpty\n\n#print eg3\n\ndef exprApp (e1 e1t e2 : Expr) : MetaM Expr :=\n let n := Name.mkSimple \"unsafe-name\"\n withLetDecl n e1t e1 fun x => do\n let b ← (mkAppM n #[e2])\n return ← (mkLetFVars #[x] b)\n\nsyntax (name := unapp) term \" :: \" term \" |< \" term : term\n\n@[termElab unapp] def unappImpl : TermElab :=\n let nt := Lean.mkConst `Someterm.nothing\n let st := Lean.mkConst `Someterm.something \n let n := Name.mkSimple \"unsafe-name\"\n fun stx expectedType? =>\n match stx with\n | `($s :: $t |< $u) =>\n do\n let f <- elabTerm s none\n let type ← elabTerm t none\n let z <- elabTerm u none\n let expr : Expr ← withLetDecl n type f fun x => do\n let b ← (mkAppM n #[z])\n return ← (mkLetFVars #[x] b)\n let c <- isTypeCorrect expr\n if c then\n return Lean.mkApp st expr\n else\n return nt\n | _ => \n do \n return nt\n\n-- #check Nat.succ :: (Nat → Nat) |< 3\n\n\n\n#print unappImpl\n#print exprApp\n\nsyntax (name := minlet) \"minlet!\" : term\n\n@[termElab minlet] def minletImpl : TermElab :=\n fun stx expectedType? =>\n let n := Name.mkSimple \"n\"\n let z := Lean.mkConst `Nat.zero\n let ty := Lean.mkConst `Nat\n withLetDecl n ty z fun x => do\n let e <- mkLetFVars #[x] x\n return e\n\n#print minletImpl \n#check minlet!\n\ndef eglit := minletImpl (Syntax.mkStrLit \"minlet!\") none\n\n#check eglit\n#eval eglit\n\ndef blahh := Meta.isExprDefEqAux\n\ndef nameLess (name: Name) := 1\n\nsyntax (name := ignorename) \"ignore!\" ident : term\n\nmacro_rules\n | `(ignore! $s) => `(Nat.zero)\n\n#check nameLess ``Nat.succ\n\n#check ignore! Nat.succ\n\ninductive WrapTerm where\n | wrap : {α : Type} → (a: α ) → WrapTerm\n | wrapName : Name → WrapTerm\n | wrapExpr : Array Expr → WrapTerm\n\n#check WrapTerm\n\ndef makeTypeFamily := Eq 1\n \n#check makeTypeFamily\n#check Eq\n\ndef makeProp : Prop := by\n apply Eq\n focus\n exact 1\n exact 2 \n\ndef makeType : Type := by\n apply Option\n exact Nat\n \ndef makeIndFam : Nat → Type := by\n intro n\n induction n with\n | zero => \n exact Nat\n | succ k ih =>\n exact Nat × ih\n\n#check Eq.trans\n\n\ndef eqStatement: Prop := by\n apply Eq\n focus\n apply 1\n focus\n apply 2\n\ndef asFunc {α β : Type} (a: α) : (α → β) → β := \n fun f => f a\n\ndef asPi {α : Type}{motive : α → Type} (a: α) : \n ((x : α) → motive x) → motive a :=\n fun f => f a \n\ndef natGen : Nat := by\n apply (asFunc 3)\n exact Nat.succ\n\ndef piFactorizer (α : Type)(motive : α → Type) : Type :=\n (a: α ) → motive a\n\ndef island : Type := by\n apply piFactorizer\n focus\n exact fun _ => Nat\n focus\n exact Nat\n \n\ndef island2: Type := by\n apply piFactorizer Nat\n intro n\n induction n with\n | zero => exact Nat\n | succ k ih => exact Nat × ih\n\ndef egT := island2 \n\nopen Nat\n\ndef egEgt : island2 := fun n =>\n match n with\n | zero => Nat.zero\n | succ k => (k, egEgt k)\n\ndef WithType := Σ A : Type, A\n\ndef WithType.mk (α : Type) (a : α) : WithType := ⟨α , a⟩\n\ndef WithType.getType (w : WithType) : Type := w.1\ndef WithType.getVal (w : WithType) : w.1 := w.2\n\ndef metaWithType(e: Expr) : MetaM Expr := do\n let tp <- inferType e\n let pair ← mkAppM ``WithType.mk #[tp, e]\n return pair\n\nsyntax (name := withtype) \"withType! \" term : term\n\n@[termElab withtype] def metaWithTypeStx : TermElab := \n fun stx expectedType? =>\n match stx with\n | `(withType! $s) =>\n do \n let e <- elabTerm s none\n let pair ← metaWithType e\n return pair\n | _ => Elab.throwIllFormedSyntax\n\ndef egName := ``Nat\n\n#check egName\n\ndef egTyped := withType! 3\n\n#check egTyped\n#check egTyped.getType\n\ndef elem : Nat := egTyped.getVal\n\n#eval elem\n\ndef infEg : Inhabited Nat := inferInstance\n\n#print infEg\n\n#check @inferInstance (ToString Nat)\n\ndef viewExp : ToString Expr := inferInstance\n\ndef explicitToString (α : Type)(a: α)(ts: ToString α) : String :=\n ts.toString a\n\ndef exprToString (e: Expr) : String := viewExp.toString e\n\ndef exprView(e: Expr) : MetaM Expr := \n do\n let tp ← inferType e\n let tst ← mkAppM ``ToString #[tp]\n let ts ← synthInstance? tst\n match ts with\n | none => \n do\n let viewExp : ToString Expr := inferInstance\n let litStr := Literal.strVal (viewExp.toString e)\n let strExp := mkLit litStr\n return strExp\n | some t => do\n -- let tts ← mkAppM ``ToString.toString #[t] \n let v ← -- mkAppN tts #[e]\n mkAppM ``explicitToString #[tp, e, t]\n return ← whnf v\n\n\nsyntax (name := showexpr) \"show! \" term : term\n\n@[termElab showexpr] def showexprImpl : TermElab := \n fun stx expectedType? =>\n match stx with\n | `(show! $s) =>\n do \n let e <- elabTerm s none\n let s ← exprView e\n return s\n | _ => Elab.throwIllFormedSyntax\n\ndef egShow : String := show! (3 : Nat) \n\n#eval egShow\n\ndef egShow2 : String := show! (fun n : Nat => 2 + n)\n\n#eval egShow2\n\ndef hashExpr : Hashable Expr := inferInstance\n\n#check hashExpr\n\ntheorem constfunc{α : Type}{f: Nat → α}:\n (∀ n: Nat, f n = f (succ n)) → (∀ n: Nat, f n = f zero) := by\n intro hyp\n intro n \n induction n with\n | zero => rfl\n | succ k ih =>\n rw [← ih]\n apply Eq.symm\n apply hyp\n\ntheorem constfuncGen{α : Type}{f: Nat → α}:\n (∀ n: Nat, f n = f (succ n)) → \n (∃ c : α, ∀ n: Nat, f n = c) := by\n intro hyp\n apply Exists.intro\n intro n\n induction n with\n | zero => rfl\n | succ k ih =>\n rw [← ih]\n apply Eq.symm\n apply hyp \n\ndef mvarMeta : MetaM Expr := do\n let mvar ← mkFreshExprMVar (some (mkConst ``Nat))\n let mvarId := mvar.mvarId!\n let mvar2 ← mkFreshExprMVar (some (mkConst ``Nat)) -- none works too\n let mvarId2 := mvar2.mvarId!\n assignExprMVar mvarId2 mvar\n assignExprMVar mvarId (mkConst ``Nat.zero)\n let mvarUnused := mkFreshExprMVar (some (mkConst ``Nat))\n return mvar2\n\nsyntax (name := minass) \"minass!\" : term\n\n@[termElab minass] def minAssImpl : TermElab :=\n fun stx expectedType? =>\n do\n let e ← mvarMeta\n return mkApp (mkConst ``Nat.succ) e\n\ndef chkMinAss := minass!\n\n#eval chkMinAss\n\nvariable {m n: Nat}\n\nconstant k : Nat\n\nconstant l: Nat\n\ndef kl := k * l\n\ndef cname := `k\n\n#print kl\n\n#print cname\n\ndef mn := m * n\n\ndef names := [`n, ``mn]\n\ndef nPlusOne := addone! n\n\n#check nPlusOne\n#print nPlusOne\n#print mn\n\n#eval @nPlusOne 3\n\n#check ignore! n\n#check ignore! pqrst\n\ndef useName (fn: Nat → Nat) (arg: Name) : MetaM Expr := \n do\n let lctx ← getLCtx\n match (← getLCtx).findFromUserName? arg with\n | some d => return d.value\n | none => return mkConst `Nat.zero \n\ndef useFVar (z: Bool) (arg: Expr) : MetaM Expr := \n do\n let lctx ← getLCtx\n let e ← lctx.getFVar! arg\n return mkApp (mkConst `Nat.succ) e.value\n\nsyntax (name := minname) \"minname! \" term : term\n\n@[termElab minname] def minNameImpl : TermElab :=\n fun stx expectedType? =>\n match stx with\n | `(minname! $s) => \n do\n let n := Name.mkSimple \"n\"\n let z := Lean.mkConst `Nat.zero\n let ty := Lean.mkConst `Nat\n withLetDecl n ty z fun x =>\n let e := useFVar true x\n return ← e\n | _ => Elab.throwIllFormedSyntax\n\n#eval minname! true\n", "meta": {"author": "siddhartha-gadgil", "repo": "lean4-scratch", "sha": "680b7073f791706faf248d1d0ad21095012ae01b", "save_path": "github-repos/lean/siddhartha-gadgil-lean4-scratch", "path": "github-repos/lean/siddhartha-gadgil-lean4-scratch/lean4-scratch-680b7073f791706faf248d1d0ad21095012ae01b/Scratch/Egs.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45326183324442865, "lm_q2_score": 0.04401864719795893, "lm_q1q2_score": 0.019951972725886596}} {"text": "/-\nCopyright (c) 2019 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Leonardo de Moura\n-/\nimport Lean.Compiler.IR.Basic\nimport Lean.Compiler.IR.LiveVars\nimport Lean.Compiler.IR.Format\n\nnamespace Lean.IR.ResetReuse\n/-! Remark: the insertResetReuse transformation is applied before we have\n inserted `inc/dec` instructions, and perfomed lower level optimizations\n that introduce the instructions `release` and `set`. -/\n\n/-! Remark: the functions `S`, `D` and `R` defined here implement the\n corresponding functions in the paper \"Counting Immutable Beans\"\n\n Here are the main differences:\n - We use the State monad to manage the generation of fresh variable names.\n - Support for join points, and `uset` and `sset` instructions for unboxed data.\n - `D` uses the auxiliary function `Dmain`.\n - `Dmain` returns a pair `(b, found)` to avoid quadratic behavior when checking\n the last occurrence of the variable `x`.\n - Because we have join points in the actual implementation, a variable may be live even if it\n does not occur in a function body. See example at `livevars.lean`.\n-/\n\nprivate def mayReuse (c₁ c₂ : CtorInfo) : Bool :=\n c₁.size == c₂.size && c₁.usize == c₂.usize && c₁.ssize == c₂.ssize &&\n /- The following condition is a heuristic.\n We don't want to reuse cells from different types even when they are compatible\n because it produces counterintuitive behavior. -/\n c₁.name.getPrefix == c₂.name.getPrefix\n\nprivate partial def S (w : VarId) (c : CtorInfo) : FnBody → FnBody\n | FnBody.vdecl x t v@(Expr.ctor c' ys) b =>\n if mayReuse c c' then\n let updtCidx := c.cidx != c'.cidx\n FnBody.vdecl x t (Expr.reuse w c' updtCidx ys) b\n else\n FnBody.vdecl x t v (S w c b)\n | FnBody.jdecl j ys v b =>\n let v' := S w c v\n if v == v' then FnBody.jdecl j ys v (S w c b)\n else FnBody.jdecl j ys v' b\n | FnBody.case tid x xType alts => FnBody.case tid x xType <| alts.map fun alt => alt.modifyBody (S w c)\n | b =>\n if b.isTerminal then b\n else let\n (instr, b) := b.split\n instr.setBody (S w c b)\n\n/-- We use `Context` to track join points in scope. -/\nabbrev M := ReaderT LocalContext (StateT Index Id)\n\nprivate def mkFresh : M VarId := do\n let idx ← getModify (fun n => n + 1)\n pure { idx := idx }\n\nprivate def tryS (x : VarId) (c : CtorInfo) (b : FnBody) : M FnBody := do\n let w ← mkFresh\n let b' := S w c b\n if b == b' then pure b\n else pure $ FnBody.vdecl w IRType.object (Expr.reset c.size x) b'\n\nprivate def Dfinalize (x : VarId) (c : CtorInfo) : FnBody × Bool → M FnBody\n | (b, true) => pure b\n | (b, false) => tryS x c b\n\nprivate def argsContainsVar (ys : Array Arg) (x : VarId) : Bool :=\n ys.any fun arg => match arg with\n | Arg.var y => x == y\n | _ => false\n\nprivate def isCtorUsing (b : FnBody) (x : VarId) : Bool :=\n match b with\n | (FnBody.vdecl _ _ (Expr.ctor _ ys) _) => argsContainsVar ys x\n | _ => false\n\n/-- Given `Dmain b`, the resulting pair `(new_b, flag)` contains the new body `new_b`,\n and `flag == true` if `x` is live in `b`.\n\n Note that, in the function `D` defined in the paper, for each `let x := e; F`,\n `D` checks whether `x` is live in `F` or not. This is great for clarity but it\n is expensive: `O(n^2)` where `n` is the size of the function body. -/\nprivate partial def Dmain (x : VarId) (c : CtorInfo) : FnBody → M (FnBody × Bool)\n | e@(FnBody.case tid y yType alts) => do\n let ctx ← read\n if e.hasLiveVar ctx x then do\n /- If `x` is live in `e`, we recursively process each branch. -/\n let alts ← alts.mapM fun alt => alt.mmodifyBody fun b => Dmain x c b >>= Dfinalize x c\n pure (FnBody.case tid y yType alts, true)\n else pure (e, false)\n | FnBody.jdecl j ys v b => do\n let (b, found) ← withReader (fun ctx => ctx.addJP j ys v) (Dmain x c b)\n let (v, _ /- found' -/) ← Dmain x c v\n /- If `found' == true`, then `Dmain b` must also have returned `(b, true)` since\n we assume the IR does not have dead join points. So, if `x` is live in `j` (i.e., `v`),\n then it must also live in `b` since `j` is reachable from `b` with a `jmp`.\n On the other hand, `x` may be live in `b` but dead in `j` (i.e., `v`). -/\n pure (FnBody.jdecl j ys v b, found)\n | e => do\n let ctx ← read\n if e.isTerminal then\n pure (e, e.hasLiveVar ctx x)\n else do\n let (instr, b) := e.split\n if isCtorUsing instr x then\n /- If the scrutinee `x` (the one that is providing memory) is being\n stored in a constructor, then reuse will probably not be able to reuse memory at runtime.\n It may work only if the new cell is consumed, but we ignore this case. -/\n pure (e, true)\n else\n let (b, found) ← Dmain x c b\n /- Remark: it is fine to use `hasFreeVar` instead of `hasLiveVar`\n since `instr` is not a `FnBody.jmp` (it is not a terminal) nor it is a `FnBody.jdecl`. -/\n if found || !instr.hasFreeVar x then\n pure (instr.setBody b, found)\n else\n let b ← tryS x c b\n pure (instr.setBody b, true)\n\nprivate def D (x : VarId) (c : CtorInfo) (b : FnBody) : M FnBody :=\n Dmain x c b >>= Dfinalize x c\n\npartial def R : FnBody → M FnBody\n | FnBody.case tid x xType alts => do\n let alts ← alts.mapM fun alt => do\n let alt ← alt.mmodifyBody R\n match alt with\n | Alt.ctor c b =>\n if c.isScalar then pure alt\n else Alt.ctor c <$> D x c b\n | _ => pure alt\n pure $ FnBody.case tid x xType alts\n | FnBody.jdecl j ys v b => do\n let v ← R v\n let b ← withReader (fun ctx => ctx.addJP j ys v) (R b)\n pure $ FnBody.jdecl j ys v b\n | e => do\n if e.isTerminal then pure e\n else do\n let (instr, b) := e.split\n let b ← R b\n pure (instr.setBody b)\n\nend ResetReuse\n\nopen ResetReuse\n\ndef Decl.insertResetReuse (d : Decl) : Decl :=\n match d with\n | .fdecl (body := b) ..=>\n let nextIndex := d.maxIndex + 1\n let bNew := (R b {}).run' nextIndex\n d.updateBody! bNew\n | other => other\n\nend Lean.IR\n", "meta": {"author": "leanprover", "repo": "lean4", "sha": "742d053a97bdd109a41a921facd1cd6a55e89bc7", "save_path": "github-repos/lean/leanprover-lean4", "path": "github-repos/lean/leanprover-lean4/lean4-742d053a97bdd109a41a921facd1cd6a55e89bc7/src/Lean/Compiler/IR/ResetReuse.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.29098086621490676, "lm_q2_score": 0.06853748875117772, "lm_q1q2_score": 0.019943097845012123}} {"text": "/-\nCopyright (c) 2020 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Leonardo de Moura\n-/\nimport Lean.ScopedEnvExtension\nimport Lean.Util.Recognizers\nimport Lean.Meta.LevelDefEq\nimport Lean.Meta.DiscrTree\nimport Lean.Meta.AppBuilder\nimport Lean.Meta.Tactic.AuxLemma\nnamespace Lean.Meta\n\n/--\n The fields `levelParams` and `proof` are used to encode the proof of the simp lemma.\n If the `proof` is a global declaration `c`, we store `Expr.const c []` at `proof` without the universe levels, and `levelParams` is set to `#[]`\n When using the lemma, we create fresh universe metavariables.\n Motivation: most simp lemmas are global declarations, and this approach is faster and saves memory.\n\n The field `levelParams` is not empty only when we elaborate an expression provided by the user, and it contains universe metavariables.\n Then, we use `abstractMVars` to abstract the universe metavariables and create new fresh universe parameters that are stored at the field `levelParams`.\n-/\nstructure SimpLemma where\n keys : Array DiscrTree.Key\n levelParams : Array Name -- non empty for local universe polymorhic proofs.\n proof : Expr\n priority : Nat\n post : Bool\n perm : Bool -- true is lhs and rhs are identical modulo permutation of variables\n name? : Option Name := none -- for debugging and tracing purposes\n deriving Inhabited\n\ndef SimpLemma.getName (s : SimpLemma) : Name :=\n match s.name? with\n | some n => n\n | none => \"\"\n\ninstance : ToFormat SimpLemma where\n format s :=\n let perm := if s.perm then \":perm\" else \"\"\n let name := fmt s.getName\n let prio := f!\":{s.priority}\"\n name ++ prio ++ perm\n\ninstance : ToMessageData SimpLemma where\n toMessageData s := fmt s\n\ninstance : BEq SimpLemma where\n beq e₁ e₂ := e₁.proof == e₂.proof\n\nstructure SimpLemmas where\n pre : DiscrTree SimpLemma := DiscrTree.empty\n post : DiscrTree SimpLemma := DiscrTree.empty\n lemmaNames : Std.PHashSet Name := {}\n toUnfold : Std.PHashSet Name := {}\n erased : Std.PHashSet Name := {}\n deriving Inhabited\n\ndef addSimpLemmaEntry (d : SimpLemmas) (e : SimpLemma) : SimpLemmas :=\n if e.post then\n { d with post := d.post.insertCore e.keys e, lemmaNames := updateLemmaNames d.lemmaNames }\n else\n { d with pre := d.pre.insertCore e.keys e, lemmaNames := updateLemmaNames d.lemmaNames }\nwhere\n updateLemmaNames (s : Std.PHashSet Name) : Std.PHashSet Name :=\n match e.name? with\n | none => s\n | some name => s.insert name\n\ndef SimpLemmas.addDeclToUnfold (d : SimpLemmas) (declName : Name) : SimpLemmas :=\n { d with toUnfold := d.toUnfold.insert declName }\n\ndef SimpLemmas.isDeclToUnfold (d : SimpLemmas) (declName : Name) : Bool :=\n d.toUnfold.contains declName\n\ndef SimpLemmas.isLemma (d : SimpLemmas) (declName : Name) : Bool :=\n d.lemmaNames.contains declName\n\ndef SimpLemmas.eraseCore [Monad m] [MonadError m] (d : SimpLemmas) (declName : Name) : m SimpLemmas := do\n return { d with erased := d.erased.insert declName, lemmaNames := d.lemmaNames.erase declName, toUnfold := d.toUnfold.erase declName }\n\ndef SimpLemmas.erase [Monad m] [MonadError m] (d : SimpLemmas) (declName : Name) : m SimpLemmas := do\n unless d.isLemma declName || d.isDeclToUnfold declName do\n throwError \"'{declName}' does not have [simp] attribute\"\n d.eraseCore declName\n\ninductive SimpEntry where\n | lemma : SimpLemma → SimpEntry\n | toUnfold : Name → SimpEntry\n deriving Inhabited\n\nbuiltin_initialize simpExtension : SimpleScopedEnvExtension SimpEntry SimpLemmas ←\n registerSimpleScopedEnvExtension {\n name := `simpExt\n initial := {}\n addEntry := fun d e =>\n match e with\n | SimpEntry.lemma e => addSimpLemmaEntry d e\n | SimpEntry.toUnfold n => d.addDeclToUnfold n\n }\n\nprivate partial def isPerm : Expr → Expr → MetaM Bool\n | Expr.app f₁ a₁ _, Expr.app f₂ a₂ _ => isPerm f₁ f₂ <&&> isPerm a₁ a₂\n | Expr.mdata _ s _, t => isPerm s t\n | s, Expr.mdata _ t _ => isPerm s t\n | s@(Expr.mvar ..), t@(Expr.mvar ..) => isDefEq s t\n | Expr.forallE n₁ d₁ b₁ _, Expr.forallE n₂ d₂ b₂ _ => isPerm d₁ d₂ <&&> withLocalDeclD n₁ d₁ fun x => isPerm (b₁.instantiate1 x) (b₂.instantiate1 x)\n | Expr.lam n₁ d₁ b₁ _, Expr.lam n₂ d₂ b₂ _ => isPerm d₁ d₂ <&&> withLocalDeclD n₁ d₁ fun x => isPerm (b₁.instantiate1 x) (b₂.instantiate1 x)\n | Expr.letE n₁ t₁ v₁ b₁ _, Expr.letE n₂ t₂ v₂ b₂ _ =>\n isPerm t₁ t₂ <&&> isPerm v₁ v₂ <&&> withLetDecl n₁ t₁ v₁ fun x => isPerm (b₁.instantiate1 x) (b₂.instantiate1 x)\n | Expr.proj _ i₁ b₁ _, Expr.proj _ i₂ b₂ _ => i₁ == i₂ <&&> isPerm b₁ b₂\n | s, t => s == t\n\nprivate partial def shouldPreprocess (type : Expr) : MetaM Bool :=\n forallTelescopeReducing type fun xs result => return !result.isEq\n\nprivate partial def preprocess (e type : Expr) : MetaM (List (Expr × Expr)) := do\n let type ← whnf type\n if type.isForall then\n forallTelescopeReducing type fun xs type => do\n let e := mkAppN e xs\n let ps ← preprocess e type\n ps.mapM fun (e, type) =>\n return (← mkLambdaFVars xs e, ← mkForallFVars xs type)\n else if type.isEq then\n return [(e, type)]\n else if let some (lhs, rhs) := type.iff? then\n let type ← mkEq lhs rhs\n let e ← mkPropExt e\n return [(e, type)]\n else if let some (_, lhs, rhs) := type.ne? then\n let type ← mkEq (← mkEq lhs rhs) (mkConst ``False)\n let e ← mkEqFalse e\n return [(e, type)]\n else if let some p := type.not? then\n let type ← mkEq p (mkConst ``False)\n let e ← mkEqFalse e\n return [(e, type)]\n else if let some (type₁, type₂) := type.and? then\n let e₁ := mkProj ``And 0 e\n let e₂ := mkProj ``And 1 e\n return (← preprocess e₁ type₁) ++ (← preprocess e₂ type₂)\n else\n let type ← mkEq type (mkConst ``True)\n let e ← mkEqTrue e\n return [(e, type)]\n\nprivate def checkTypeIsProp (type : Expr) : MetaM Unit :=\n unless (← isProp type) do\n throwError \"invalid 'simp', proposition expected{indentExpr type}\"\n\nprivate def mkSimpLemmaCore (e : Expr) (levelParams : Array Name) (proof : Expr) (post : Bool) (prio : Nat) (name? : Option Name) : MetaM SimpLemma := do\n let type ← instantiateMVars (← inferType e)\n withNewMCtxDepth do\n let (xs, _, type) ← withReducible <| forallMetaTelescopeReducing type\n let type ← whnfR type\n let (keys, perm) ←\n match type.eq? with\n | some (_, lhs, rhs) => pure (← DiscrTree.mkPath lhs, ← isPerm lhs rhs)\n | none => throwError \"unexpected kind of 'simp' theorem{indentExpr type}\"\n return { keys := keys, perm := perm, post := post, levelParams := levelParams, proof := proof, name? := name?, priority := prio }\n\nprivate def mkSimpLemmasFromConst (declName : Name) (post : Bool) (prio : Nat) : MetaM (Array SimpLemma) := do\n let cinfo ← getConstInfo declName\n let val := mkConst declName (cinfo.levelParams.map mkLevelParam)\n withReducible do\n let type ← inferType val\n checkTypeIsProp type\n if (← shouldPreprocess type) then\n let mut r := #[]\n for (val, type) in (← preprocess val type) do\n let auxName ← mkAuxLemma cinfo.levelParams type val\n r := r.push <| (← mkSimpLemmaCore (mkConst auxName (cinfo.levelParams.map mkLevelParam)) #[] (mkConst auxName) post prio declName)\n return r\n else\n #[← mkSimpLemmaCore (mkConst declName (cinfo.levelParams.map mkLevelParam)) #[] (mkConst declName) post prio declName]\n\ndef addSimpLemma (declName : Name) (post : Bool) (attrKind : AttributeKind) (prio : Nat) : MetaM Unit := do\n let simpLemmas ← mkSimpLemmasFromConst declName post prio\n for simpLemma in simpLemmas do\n simpExtension.add (SimpEntry.lemma simpLemma) attrKind\n\nbuiltin_initialize\n registerBuiltinAttribute {\n name := `simp\n descr := \"simplification theorem\"\n add := fun declName stx attrKind =>\n let go : MetaM Unit := do\n let info ← getConstInfo declName\n if (← isProp info.type) then\n let post :=\n if stx[1].isNone then true else stx[1][0].getKind == ``Lean.Parser.Tactic.simpPost\n let prio ← getAttrParamOptPrio stx[2]\n addSimpLemma declName post attrKind prio\n else if info.hasValue then\n simpExtension.add (SimpEntry.toUnfold declName) attrKind\n else\n throwError \"invalid 'simp', it is not a proposition nor a definition (to unfold)\"\n discard <| go.run {} {}\n erase := fun declName => do\n let s ← simpExtension.getState (← getEnv)\n let s ← s.erase declName\n modifyEnv fun env => simpExtension.modifyState env fun _ => s\n }\n\ndef getSimpLemmas : MetaM SimpLemmas :=\n return simpExtension.getState (← getEnv)\n\n/- Auxiliary method for adding a global declaration to a `SimpLemmas` datastructure. -/\ndef SimpLemmas.addConst (s : SimpLemmas) (declName : Name) (post : Bool := true) (prio : Nat := eval_prio default) : MetaM SimpLemmas := do\n let simpLemmas ← mkSimpLemmasFromConst declName post prio\n return simpLemmas.foldl addSimpLemmaEntry s\n\ndef SimpLemma.getValue (simpLemma : SimpLemma) : MetaM Expr := do\n if simpLemma.proof.isConst && simpLemma.levelParams.isEmpty then\n let info ← getConstInfo simpLemma.proof.constName!\n if info.levelParams.isEmpty then\n return simpLemma.proof\n else\n return simpLemma.proof.updateConst! (← info.levelParams.mapM (fun _ => mkFreshLevelMVar))\n else\n let us ← simpLemma.levelParams.mapM fun _ => mkFreshLevelMVar\n simpLemma.proof.instantiateLevelParamsArray simpLemma.levelParams us\n\nprivate def preprocessProof (val : Expr) : MetaM (Array Expr) := do\n let type ← inferType val\n checkTypeIsProp type\n let ps ← preprocess val type\n return ps.toArray.map fun (val, _) => val\n\n/- Auxiliary method for creating simp lemmas from a proof term `val`. -/\ndef mkSimpLemmas (levelParams : Array Name) (proof : Expr) (post : Bool := true) (prio : Nat := eval_prio default) (name? : Option Name := none): MetaM (Array SimpLemma) :=\n withReducible do\n (← preprocessProof proof).mapM fun val => mkSimpLemmaCore val levelParams val post prio name?\n\n/- Auxiliary method for adding a local simp lemma to a `SimpLemmas` datastructure. -/\ndef SimpLemmas.add (s : SimpLemmas) (levelParams : Array Name) (proof : Expr) (post : Bool := true) (prio : Nat := eval_prio default) (name? : Option Name := none): MetaM SimpLemmas := do\n if proof.isConst then\n s.addConst proof.constName! post prio\n else\n let simpLemmas ← mkSimpLemmas levelParams proof post prio (← getName? proof)\n return simpLemmas.foldl addSimpLemmaEntry s\nwhere\n getName? (e : Expr) : MetaM (Option Name) := do\n match name? with\n | some _ => return name?\n | none =>\n let f := e.getAppFn\n if f.isConst then\n return f.constName!\n else if f.isFVar then\n let localDecl ← getFVarLocalDecl f\n return localDecl.userName\n else\n return none\n\nend Lean.Meta\n", "meta": {"author": "gebner", "repo": "lean4-old", "sha": "ee51cdfaf63ee313c914d83264f91f414a0e3b6e", "save_path": "github-repos/lean/gebner-lean4-old", "path": "github-repos/lean/gebner-lean4-old/lean4-old-ee51cdfaf63ee313c914d83264f91f414a0e3b6e/stage0/src/Lean/Meta/Tactic/Simp/SimpLemmas.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3311197396289915, "lm_q2_score": 0.06008665017400762, "lm_q1q2_score": 0.0198958759607957}} {"text": "example (f : α → α) (a b : α) (h : HEq a b) : f a = f b := by\n subst h\n rfl\n", "meta": {"author": "leanprover", "repo": "lean4", "sha": "742d053a97bdd109a41a921facd1cd6a55e89bc7", "save_path": "github-repos/lean/leanprover-lean4", "path": "github-repos/lean/leanprover-lean4/lean4-742d053a97bdd109a41a921facd1cd6a55e89bc7/tests/lean/run/heqSubst.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.30735801686526387, "lm_q2_score": 0.06465348925734803, "lm_q1q2_score": 0.019871768241558133}} {"text": "/-\nCopyright (c) 2019 Paul-Nicolas Madelaine. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Paul-Nicolas Madelaine, Robert Y. Lewis\n\n! This file was ported from Lean 3 source module tactic.norm_cast\n! leanprover-community/mathlib commit 32b08ef840dd25ca2e47e035c5da03ce16d2dc3c\n! Please do not edit these lines, except to modify the commit id\n! if you have ported upstream changes.\n-/\nimport Mathbin.Tactic.Converter.Interactive\nimport Mathbin.Tactic.Hint\n\n/-!\n# A tactic for normalizing casts inside expressions\n\nThis tactic normalizes casts inside expressions.\nIt can be thought of as a call to the simplifier with a specific set of lemmas to\nmove casts upwards in the expression.\nIt has special handling of numerals and a simple heuristic to help moving\ncasts \"past\" binary operators.\nContrary to simp, it should be safe to use as a non-terminating tactic.\n\nThe algorithm implemented here is described in the paper\n.\n\n## Important definitions\n* `tactic.interactive.norm_cast`\n* `tactic.interactive.push_cast`\n* `tactic.interactive.exact_mod_cast`\n* `tactic.interactive.apply_mod_cast`\n* `tactic.interactive.rw_mod_cast`\n* `tactic.interactive.assumption_mod_cast`\n-/\n\n\n/- ./././Mathport/Syntax/Translate/Tactic/Mathlib/Core.lean:38:34: unsupported: setup_tactic_parser -/\nnamespace Tactic\n\n/-- Runs `mk_instance` with a time limit.\n\nThis is a work around to the fact that in some cases\nmk_instance times out instead of failing,\nfor example: `has_lift_t ℤ ℕ`\n\n`mk_instance_fast` is used when we assume the type class search\nshould end instantly.\n-/\nunsafe def mk_instance_fast (e : expr) (timeout := 1000) : tactic expr :=\n try_for timeout (mk_instance e)\n#align tactic.mk_instance_fast tactic.mk_instance_fast\n\nend Tactic\n\nnamespace NormCast\n\nopen Tactic Expr\n\ninitialize\n registerTraceClass.1 `norm_cast\n\n/-- Output a trace message if `trace.norm_cast` is enabled.\n-/\nunsafe def trace_norm_cast {α} [has_to_tactic_format α] (msg : String) (a : α) : tactic Unit :=\n when_tracing `norm_cast do\n let a ← pp a\n trace (\"[norm_cast] \" ++ msg ++ a : format)\n#align norm_cast.trace_norm_cast norm_cast.trace_norm_cast\n\n/- failed to parenthesize: unknown constant 'Lean.Meta._root_.Lean.Parser.Command.registerSimpAttr'\n[PrettyPrinter.parenthesize.input] (Lean.Meta._root_.Lean.Parser.Command.registerSimpAttr\n [(Command.docComment\n \"/--\"\n \"The `push_cast` simp attribute uses `norm_cast` lemmas\\nto move casts toward the leaf nodes of the expression. -/\")]\n \"register_simp_attr\"\n `push_cast)-/-- failed to format: unknown constant 'Lean.Meta._root_.Lean.Parser.Command.registerSimpAttr'\n/--\n The `push_cast` simp attribute uses `norm_cast` lemmas\n to move casts toward the leaf nodes of the expression. -/\n register_simp_attr\n push_cast\n\n/-- `label` is a type used to classify `norm_cast` lemmas.\n* elim lemma: LHS has 0 head coes and ≥ 1 internal coe\n* move lemma: LHS has 1 head coe and 0 internal coes, RHS has 0 head coes and ≥ 1 internal coes\n* squash lemma: LHS has ≥ 1 head coes and 0 internal coes, RHS has fewer head coes\n-/\ninductive Label\n | elim : label\n | move : label\n | squash : label\n deriving DecidableEq, has_reflect, Inhabited\n#align norm_cast.label NormCast.Label\n\nnamespace Label\n\n/-- Convert `label` into `string`. -/\nprotected def toString : Label → String\n | elim => \"elim\"\n | move => \"move\"\n | squash => \"squash\"\n#align norm_cast.label.to_string NormCast.Label.toString\n\ninstance : ToString Label :=\n ⟨Label.toString⟩\n\ninstance : Repr Label :=\n ⟨Label.toString⟩\n\nunsafe instance : has_to_format Label :=\n ⟨fun l => l.toString⟩\n\n/-- Convert `string` into `label`. -/\ndef ofString : String → Option Label\n | \"elim\" => some elim\n | \"move\" => some move\n | \"squash\" => some squash\n | _ => none\n#align norm_cast.label.of_string NormCast.Label.ofString\n\nend Label\n\nopen Label\n\n/-- Count how many coercions are at the top of the expression. -/\nunsafe def count_head_coes : expr → ℕ\n | q(coe $(e)) => count_head_coes e + 1\n | q(coeSort $(e)) => count_head_coes e + 1\n | q(coeFn $(e)) => count_head_coes e + 1\n | _ => 0\n#align norm_cast.count_head_coes norm_cast.count_head_coes\n\n/-- Count how many coercions are inside the expression, including the top ones. -/\nunsafe def count_coes : expr → tactic ℕ\n | q(coe $(e)) => (· + 1) <$> count_coes e\n | q(coeSort $(e)) => (· + 1) <$> count_coes e\n | q(coeFn $(e)) => (· + 1) <$> count_coes e\n | app q(coeFn $(e)) x => (· + ·) <$> count_coes x <*> (· + 1) <$> count_coes e\n | expr.lam n bi t e => do\n let l ← mk_local' n bi t\n count_coes <| e l\n | e => do\n let as ← e.get_simp_args\n List.sum <$> as count_coes\n#align norm_cast.count_coes norm_cast.count_coes\n\n/-- Count how many coercions are inside the expression, excluding the top ones. -/\nprivate unsafe def count_internal_coes (e : expr) : tactic ℕ := do\n let ncoes ← count_coes e\n pure <| ncoes - count_head_coes e\n#align norm_cast.count_internal_coes norm_cast.count_internal_coes\n\n-- failed to format: unknown constant 'term.pseudo.antiquot'\n/--\n Classifies a declaration of type `ty` as a `norm_cast` rule.\n -/\n unsafe\n def\n classify_type\n ( ty : expr ) : tactic Label\n :=\n do\n let ( _ , ty ) ← open_pis ty\n let\n ( lhs , rhs )\n ←\n match\n ty\n with\n | q( $ ( lhs ) = $ ( rhs ) ) => pure ( lhs , rhs )\n | q( $ ( lhs ) ↔ $ ( rhs ) ) => pure ( lhs , rhs )\n | _ => fail \"norm_cast: lemma must be = or ↔\"\n let lhs_coes ← count_coes lhs\n when ( lhs_coes = 0 )\n <|\n fail \"norm_cast: badly shaped lemma, lhs must contain at least one coe\"\n let lhs_head_coes := count_head_coes lhs\n let lhs_internal_coes ← count_internal_coes lhs\n let rhs_head_coes := count_head_coes rhs\n let rhs_internal_coes ← count_internal_coes rhs\n if\n lhs_head_coes = 0\n then\n return elim\n else\n if\n lhs_head_coes = 1\n then\n do\n when ( rhs_head_coes ≠ 0 )\n <|\n fail \"norm_cast: badly shaped lemma, rhs can't start with coe\"\n if rhs_internal_coes = 0 then return squash else return move\n else\n if\n rhs_head_coes < lhs_head_coes\n then\n do return squash\n else\n do\n fail\n \"norm_cast: badly shaped shaped squash lemma, rhs must have fewer head coes than lhs\"\n#align norm_cast.classify_type norm_cast.classify_type\n\n/-- The cache for `norm_cast` attribute stores three `simp_lemma` objects. -/\nunsafe structure norm_cast_cache where\n up : simp_lemmas\n down : simp_lemmas\n squash : simp_lemmas\n#align norm_cast.norm_cast_cache norm_cast.norm_cast_cache\n\n/-- Empty `norm_cast_cache`. -/\nunsafe def empty_cache : norm_cast_cache\n where\n up := simp_lemmas.mk\n down := simp_lemmas.mk\n squash := simp_lemmas.mk\n#align norm_cast.empty_cache norm_cast.empty_cache\n\nunsafe instance : Inhabited norm_cast_cache :=\n ⟨empty_cache⟩\n\n/-- `add_elim cache e` adds `e` as an `elim` lemma to `cache`. -/\nunsafe def add_elim (cache : norm_cast_cache) (e : expr) : tactic norm_cast_cache := do\n let new_up ← cache.up.add e\n return\n { up := new_up\n down := cache\n squash := cache }\n#align norm_cast.add_elim norm_cast.add_elim\n\n/-- `add_move cache e` adds `e` as a `move` lemma to `cache`. -/\nunsafe def add_move (cache : norm_cast_cache) (e : expr) : tactic norm_cast_cache := do\n let new_up ← cache.up.add e true\n let new_down ← cache.down.add e\n return\n { up := new_up\n down := new_down\n squash := cache }\n#align norm_cast.add_move norm_cast.add_move\n\n/-- `add_squash cache e` adds `e` as an `squash` lemma to `cache`. -/\nunsafe def add_squash (cache : norm_cast_cache) (e : expr) : tactic norm_cast_cache := do\n let new_squash ← cache.squash.add e\n let new_down ← cache.down.add e\n return\n { up := cache\n down := new_down\n squash := new_squash }\n#align norm_cast.add_squash norm_cast.add_squash\n\n/-- The type of the `norm_cast` attribute.\nThe optional label is used to overwrite the classifier.\n-/\nunsafe def norm_cast_attr_ty : Type :=\n user_attribute norm_cast_cache (Option Label)\n#align norm_cast.norm_cast_attr_ty norm_cast.norm_cast_attr_ty\n\n/-- Efficient getter for the `@[norm_cast]` attribute parameter that does not call `eval_expr`.\n\nSee Note [user attribute parameters].\n-/\nunsafe def get_label_param (attr : norm_cast_attr_ty) (decl : Name) : tactic (Option Label) := do\n let p ← attr.get_param_untyped decl\n match p with\n | q(none) => pure none\n | q(some Label.elim) => pure label.elim\n | q(some Label.move) => pure label.move\n | q(some Label.squash) => pure label.squash\n | _ => fail p\n#align norm_cast.get_label_param norm_cast.get_label_param\n\n/--\n`add_lemma cache decl` infers the proper `norm_cast` attribute for `decl` and adds it to `cache`.\n-/\nunsafe def add_lemma (attr : norm_cast_attr_ty) (cache : norm_cast_cache) (decl : Name) :\n tactic norm_cast_cache := do\n let e ← mk_const decl\n let param ← get_label_param attr decl\n let l ← param <|> infer_type e >>= classify_type\n match l with\n | elim => add_elim cache e\n | move => add_move cache e\n | squash => add_squash cache e\n#align norm_cast.add_lemma norm_cast.add_lemma\n\n-- special lemmas to handle the ≥, > and ≠ operators\nprivate theorem ge_from_le {α} [LE α] : ∀ x y : α, x ≥ y ↔ y ≤ x := fun _ _ => Iff.rfl\n#align norm_cast.ge_from_le norm_cast.ge_from_le\n\nprivate theorem gt_from_lt {α} [LT α] : ∀ x y : α, x > y ↔ y < x := fun _ _ => Iff.rfl\n#align norm_cast.gt_from_lt norm_cast.gt_from_lt\n\nprivate theorem ne_from_not_eq {α} : ∀ x y : α, x ≠ y ↔ ¬x = y := fun _ _ => Iff.rfl\n#align norm_cast.ne_from_not_eq norm_cast.ne_from_not_eq\n\n/-- `mk_cache names` creates a `norm_cast_cache`. It infers the proper `norm_cast` attributes\nfor names in `names`, and collects the lemmas attributed with specific `norm_cast` attributes.\n-/\nunsafe def mk_cache (attr : Thunk norm_cast_attr_ty) (names : List Name) : tactic norm_cast_cache :=\n do\n let cache\n ←-- names has the declarations in reverse order\n names.foldrM\n (fun name cache => add_lemma (attr ()) cache Name) empty_cache\n let--some special lemmas to handle binary relations\n up := cache.up\n let up ← up.add_simp `` ge_from_le\n let up ← up.add_simp `` gt_from_lt\n let up ← up.add_simp `` ne_from_not_eq\n let down := cache.down\n let down ← down.add_simp `` coe_coe\n pure {\n up\n down\n squash := cache }\n#align norm_cast.mk_cache norm_cast.mk_cache\n\n/-- The `norm_cast` attribute.\n-/\n@[user_attribute]\nunsafe def norm_cast_attr : user_attribute norm_cast_cache (Option Label)\n where\n Name := `norm_cast\n descr := \"attribute for norm_cast\"\n parser :=\n (do\n let some l ← (Label.ofString ∘ toString) <$> ident\n return l) <|>\n return none\n after_set :=\n some fun decl prio persistent => do\n let param ← get_label_param norm_cast_attr decl\n match param with\n | some l => when (l ≠ elim) <| simp_attr.push_cast decl () tt prio\n | none => do\n let e ← mk_const decl\n let ty ← infer_type e\n let l ← classify_type ty\n norm_cast_attr decl l persistent prio\n before_unset := some fun _ _ => tactic.skip\n cache_cfg :=\n { mk_cache := mk_cache norm_cast_attr\n dependencies := [] }\n#align norm_cast.norm_cast_attr norm_cast.norm_cast_attr\n\n/-- Classify a declaration as a `norm_cast` rule. -/\nunsafe def make_guess (decl : Name) : tactic Label := do\n let e ← mk_const decl\n let ty ← infer_type e\n classify_type ty\n#align norm_cast.make_guess norm_cast.make_guess\n\n/-- Gets the `norm_cast` classification label for a declaration. Applies the\noverride specified on the attribute, if necessary.\n-/\nunsafe def get_label (decl : Name) : tactic Label := do\n let param ← get_label_param norm_cast_attr decl\n param <|> make_guess decl\n#align norm_cast.get_label norm_cast.get_label\n\nend NormCast\n\nnamespace Tactic.Interactive\n\nopen NormCast\n\n/-- `push_cast` rewrites the expression to move casts toward the leaf nodes.\nFor example, `↑(a + b)` will be written to `↑a + ↑b`.\nEquivalent to `simp only with push_cast`.\nCan also be used at hypotheses.\n\n`push_cast` can also be used at hypotheses and with extra simp rules.\n\n```lean\nexample (a b : ℕ) (h1 : ((a + b : ℕ) : ℤ) = 10) (h2 : ((a + b + 0 : ℕ) : ℤ) = 10) :\n ((a + b : ℕ) : ℤ) = 10 :=\nbegin\n push_cast,\n push_cast at h1,\n push_cast [int.add_zero] at h2,\nend\n```\n-/\nunsafe def push_cast (hs : parse tactic.simp_arg_list) (l : parse location) : tactic Unit :=\n tactic.interactive.simp none none true hs [`push_cast] l { discharger := tactic.assumption }\n#align tactic.interactive.push_cast tactic.interactive.push_cast\n\nend Tactic.Interactive\n\nnamespace NormCast\n\nopen Tactic Expr\n\n-- failed to format: unknown constant 'term.pseudo.antiquot'\n/-- Prove `a = b` using the given simp set. -/ unsafe\n def\n prove_eq_using\n ( s : simp_lemmas ) ( a b : expr ) : tactic expr\n :=\n do\n let ( a' , a_a' , _ ) ← simplify s [ ] a { failIfUnchanged := false }\n let ( b' , b_b' , _ ) ← simplify s [ ] b { failIfUnchanged := false }\n on_exception ( trace_norm_cast \"failed: \" ( to_expr ` `( $ ( a' ) = $ ( b' ) ) >>= pp ) )\n <|\n is_def_eq a' b' reducible\n let b'_b ← mk_eq_symm b_b'\n mk_eq_trans a_a' b'_b\n#align norm_cast.prove_eq_using norm_cast.prove_eq_using\n\n-- failed to format: unknown constant 'term.pseudo.antiquot'\n/-- Prove `a = b` by simplifying using move and squash lemmas. -/ unsafe\n def\n prove_eq_using_down\n ( a b : expr ) : tactic expr\n :=\n do\n let cache ← norm_cast_attr . get_cache\n trace_norm_cast \"proving: \" ( to_expr ` `( $ ( a ) = $ ( b ) ) >>= pp )\n prove_eq_using cache a b\n#align norm_cast.prove_eq_using_down norm_cast.prove_eq_using_down\n\n/-- This is the main heuristic used alongside the elim and move lemmas.\nThe goal is to help casts move past operators by adding intermediate casts.\nAn expression of the shape: op (↑(x : α) : γ) (↑(y : β) : γ)\nis rewritten to: op (↑(↑(x : α) : β) : γ) (↑(y : β) : γ)\nwhen (↑(↑(x : α) : β) : γ) = (↑(x : α) : γ) can be proven with a squash lemma\n-/\nunsafe def splitting_procedure : expr → tactic (expr × expr)\n | app (app op x) y =>\n (do\n let q(@coe $(α) $(δ) $(coe1) $(xx)) ← return x\n let q(@coe $(β) $(γ) $(coe2) $(yy)) ← return y\n success_if_fail <| is_def_eq α β\n is_def_eq δ γ\n (do\n let coe3 ← mk_app `has_lift_t [α, β] >>= mk_instance_fast\n let new_x ← to_expr ``(@coe $(β) $(δ) $(coe2) (@coe $(α) $(β) $(coe3) $(xx)))\n let new_e := app (app op new_x) y\n let eq_x ← prove_eq_using_down x new_x\n let pr ← mk_congr_arg op eq_x\n let pr ← mk_congr_fun pr y\n return (new_e, pr)) <|>\n do\n let coe3 ← mk_app `has_lift_t [β, α] >>= mk_instance_fast\n let new_y ← to_expr ``(@coe $(α) $(δ) $(coe1) (@coe $(β) $(α) $(coe3) $(yy)))\n let new_e := app (app op x) new_y\n let eq_y ← prove_eq_using_down y new_y\n let pr ← mk_congr_arg (app op x) eq_y\n return (new_e, pr)) <|>\n (do\n let q(@coe $(α) $(β) $(coe1) $(xx)) ← return x\n let q(@One.one $(β) $(h1)) ← return y\n let h2 ← to_expr ``(One $(α)) >>= mk_instance_fast\n let new_y ← to_expr ``(@coe $(α) $(β) $(coe1) (@One.one $(α) $(h2)))\n let eq_y ← prove_eq_using_down y new_y\n let new_e := app (app op x) new_y\n let pr ← mk_congr_arg (app op x) eq_y\n return (new_e, pr)) <|>\n (do\n let q(@coe $(α) $(β) $(coe1) $(xx)) ← return x\n let q(@Zero.zero $(β) $(h1)) ← return y\n let h2 ← to_expr ``(Zero $(α)) >>= mk_instance_fast\n let new_y ← to_expr ``(@coe $(α) $(β) $(coe1) (@Zero.zero $(α) $(h2)))\n let eq_y ← prove_eq_using_down y new_y\n let new_e := app (app op x) new_y\n let pr ← mk_congr_arg (app op x) eq_y\n return (new_e, pr)) <|>\n (do\n let q(@One.one $(β) $(h1)) ← return x\n let q(@coe $(α) $(β) $(coe1) $(xx)) ← return y\n let h1 ← to_expr ``(One $(α)) >>= mk_instance_fast\n let new_x ← to_expr ``(@coe $(α) $(β) $(coe1) (@One.one $(α) $(h1)))\n let eq_x ← prove_eq_using_down x new_x\n let new_e := app (app op new_x) y\n let pr ← mk_congr_arg (lam `x BinderInfo.default β (app (app op (var 0)) y)) eq_x\n return (new_e, pr)) <|>\n do\n let q(@Zero.zero $(β) $(h1)) ← return x\n let q(@coe $(α) $(β) $(coe1) $(xx)) ← return y\n let h1 ← to_expr ``(Zero $(α)) >>= mk_instance_fast\n let new_x ← to_expr ``(@coe $(α) $(β) $(coe1) (@Zero.zero $(α) $(h1)))\n let eq_x ← prove_eq_using_down x new_x\n let new_e := app (app op new_x) y\n let pr ← mk_congr_arg (lam `x BinderInfo.default β (app (app op (var 0)) y)) eq_x\n return (new_e, pr)\n | _ => failed\n#align norm_cast.splitting_procedure norm_cast.splitting_procedure\n\n/-- Discharging function used during simplification in the \"squash\" step.\n\nTODO: norm_cast takes a list of expressions to use as lemmas for the discharger\nTODO: a tactic to print the results the discharger fails to proove\n-/\nprivate unsafe def prove : tactic Unit :=\n assumption\n#align norm_cast.prove norm_cast.prove\n\n/-- Core rewriting function used in the \"squash\" step, which moves casts upwards\nand eliminates them.\n\nIt tries to rewrite an expression using the elim and move lemmas.\nOn failure, it calls the splitting procedure heuristic.\n-/\nunsafe def upward_and_elim (s : simp_lemmas) (e : expr) : tactic (expr × expr) :=\n (do\n let r ← condM (is_prop e) (return `iff) (return `eq)\n let (new_e, pr) ← s.rewrite e prove r\n let pr ←\n match r with\n | `iff => mk_app `propext [pr]\n | _ => return pr\n return (new_e, pr)) <|>\n splitting_procedure e\n#align norm_cast.upward_and_elim norm_cast.upward_and_elim\n\n/-!\nThe following auxiliary functions are used to handle numerals.\n-/\n\n\n/-- If possible, rewrite `(n : α)` to `((n : ℕ) : α)` where `n` is a numeral and `α ≠ ℕ`.\nReturns a pair of the new expression and proof that they are equal.\n-/\nunsafe def numeral_to_coe (e : expr) : tactic (expr × expr) := do\n let α ← infer_type e\n success_if_fail <| is_def_eq α q(ℕ)\n let n ← e.toNat\n let h1 ← mk_app `has_lift_t [q(ℕ), α] >>= mk_instance_fast\n let new_e : expr := reflect n\n let new_e ← to_expr ``(@coe ℕ $(α) $(h1) $(new_e))\n let pr ← prove_eq_using_down e new_e\n return (new_e, pr)\n#align norm_cast.numeral_to_coe norm_cast.numeral_to_coe\n\n/-- If possible, rewrite `((n : ℕ) : α)` to `(n : α)` where `n` is a numeral.\nReturns a pair of the new expression and proof that they are equal.\n-/\nunsafe def coe_to_numeral (e : expr) : tactic (expr × expr) := do\n let q(@coe ℕ $(α) $(h1) $(e')) ← return e\n let n ← e'.toNat\n -- replace e' by normalized numeral\n is_def_eq\n (reflect n) e' reducible\n let e := e.app_fn (reflect n)\n let new_e ← expr.of_nat α n\n let pr ← prove_eq_using_down e new_e\n return (new_e, pr)\n#align norm_cast.coe_to_numeral norm_cast.coe_to_numeral\n\n/-- A local variant on `simplify_top_down`. -/\nprivate unsafe def simplify_top_down' {α} (a : α) (pre : α → expr → tactic (α × expr × expr))\n (e : expr) (cfg : SimpConfig := { }) : tactic (α × expr × expr) :=\n ext_simplify_core a cfg simp_lemmas.mk (fun _ => failed)\n (fun a _ _ _ e => do\n let (new_a, new_e, pr) ← pre a e\n guard ¬new_e == e\n return (new_a, new_e, some pr, ff))\n (fun _ _ _ _ _ => failed) `eq e\n#align norm_cast.simplify_top_down' norm_cast.simplify_top_down'\n\n/-- The core simplification routine of `norm_cast`.\n-/\nunsafe def derive (e : expr) : tactic (expr × expr) := do\n let cache ← norm_cast_attr.get_cache\n let e ← instantiate_mvars e\n let cfg : SimpConfig :=\n { zeta := false\n beta := false\n eta := false\n proj := false\n iota := false\n iotaEqn := false\n failIfUnchanged := false }\n let e0 := e\n let-- step 1: pre-processing of numerals\n ((), e1, pr1)\n ← simplify_top_down' () (fun _ e => Prod.mk () <$> numeral_to_coe e) e0 cfg\n trace_norm_cast \"after numeral_to_coe: \" e1\n let-- step 2: casts are moved upwards and eliminated\n ((), e2, pr2)\n ← simplify_bottom_up () (fun _ e => Prod.mk () <$> upward_and_elim cache.up e) e1 cfg\n trace_norm_cast \"after upward_and_elim: \" e2\n let-- step 3: casts are squashed\n (e3, pr3, _)\n ← simplify cache.squash [] e2 cfg\n trace_norm_cast \"after squashing: \" e3\n let-- step 4: post-processing of numerals\n ((), e4, pr4)\n ← simplify_top_down' () (fun _ e => Prod.mk () <$> coe_to_numeral e) e3 cfg\n trace_norm_cast \"after coe_to_numeral: \" e4\n let new_e := e4\n guard ¬new_e == e\n let pr ← mk_eq_trans pr1 pr2\n let pr ← mk_eq_trans pr pr3\n let pr ← mk_eq_trans pr pr4\n return (new_e, pr)\n#align norm_cast.derive norm_cast.derive\n\n/-- A small variant of `push_cast` suited for non-interactive use.\n\n`derive_push_cast extra_lems e` returns an expression `e'` and a proof that `e = e'`.\n-/\nunsafe def derive_push_cast (extra_lems : List simp_arg_type) (e : expr) : tactic (expr × expr) :=\n do\n let (s, _) ← mk_simp_set true [`push_cast] extra_lems\n let (e, prf, _) ←\n simplify (s.eraseₓ [`nat.cast_succ]) [] e { failIfUnchanged := false } `eq tactic.assumption\n return (e, prf)\n#align norm_cast.derive_push_cast norm_cast.derive_push_cast\n\nend NormCast\n\nnamespace Tactic\n\nopen Expr NormCast\n\n/-- `aux_mod_cast e` runs `norm_cast` on `e` and returns the result. If `include_goal` is true, it\nalso normalizes the goal. -/\nunsafe def aux_mod_cast (e : expr) (include_goal : Bool := true) : tactic expr :=\n match e with\n | local_const _ lc _ _ => do\n let e ← get_local lc\n replace_at derive [e] include_goal\n get_local lc\n | e => do\n let t ← infer_type e\n let e ← assertv `this t e\n replace_at derive [e] include_goal\n get_local `this\n#align tactic.aux_mod_cast tactic.aux_mod_cast\n\n/-- `exact_mod_cast e` runs `norm_cast` on the goal and `e`, and tries to use `e` to close the\ngoal. -/\nunsafe def exact_mod_cast (e : expr) : tactic Unit :=\n decorate_error \"exact_mod_cast failed:\" do\n let new_e ← aux_mod_cast e\n exact new_e\n#align tactic.exact_mod_cast tactic.exact_mod_cast\n\n/-- `apply_mod_cast e` runs `norm_cast` on the goal and `e`, and tries to apply `e`. -/\nunsafe def apply_mod_cast (e : expr) : tactic (List (Name × expr)) :=\n decorate_error \"apply_mod_cast failed:\" do\n let new_e ← aux_mod_cast e\n apply new_e\n#align tactic.apply_mod_cast tactic.apply_mod_cast\n\n/-- `assumption_mod_cast` runs `norm_cast` on the goal. For each local hypothesis `h`, it also\nnormalizes `h` and tries to use that to close the goal. -/\nunsafe def assumption_mod_cast : tactic Unit :=\n decorate_error \"assumption_mod_cast failed:\" do\n let cfg : SimpConfig :=\n { failIfUnchanged := false\n canonizeInstances := false\n canonizeProofs := false\n proj := false }\n replace_at derive [] tt\n let ctx ← local_context\n ctx fun h => aux_mod_cast h ff >>= tactic.exact\n#align tactic.assumption_mod_cast tactic.assumption_mod_cast\n\nend Tactic\n\nnamespace Tactic.Interactive\n\nopen Tactic NormCast\n\n/-- Normalize casts at the given locations by moving them \"upwards\".\nAs opposed to simp, norm_cast can be used without necessarily closing the goal.\n-/\nunsafe def norm_cast (loc : parse location) : tactic Unit := do\n let ns ← loc.get_locals\n let tt ← replace_at derive ns loc.include_goal |\n fail \"norm_cast failed to simplify\"\n when loc <| try tactic.reflexivity\n when loc <| try tactic.triv\n when ¬ns <| try tactic.contradiction\n#align tactic.interactive.norm_cast tactic.interactive.norm_cast\n\n/-- Rewrite with the given rules and normalize casts between steps.\n-/\nunsafe def rw_mod_cast (rs : parse rw_rules) (loc : parse location) : tactic Unit :=\n decorate_error \"rw_mod_cast failed:\" do\n let cfg_norm : SimpConfig := { }\n let cfg_rw : RewriteCfg := { }\n let ns ← loc.get_locals\n Monad.mapM'\n (fun r : rw_rule => do\n save_info r\n replace_at derive ns loc\n rw ⟨[r], none⟩ loc { })\n rs\n replace_at derive ns loc\n skip\n#align tactic.interactive.rw_mod_cast tactic.interactive.rw_mod_cast\n\n/-- Normalize the goal and the given expression, then close the goal with exact.\n-/\nunsafe def exact_mod_cast (e : parse texpr) : tactic Unit := do\n let e ←\n i_to_expr e <|> do\n let ty ← target\n let e ← i_to_expr_strict ``(($(e) : $(ty)))\n let pty ← pp ty\n let ptgt ← pp e\n fail\n (\"exact_mod_cast failed, expression type not directly \" ++\n \"inferrable. Try:\\n\\nexact_mod_cast ...\\nshow \" ++\n to_fmt pty ++\n \",\\nfrom \" ++\n ptgt :\n format)\n tactic.exact_mod_cast e\n#align tactic.interactive.exact_mod_cast tactic.interactive.exact_mod_cast\n\n/-- Normalize the goal and the given expression, then apply the expression to the goal.\n-/\nunsafe def apply_mod_cast (e : parse texpr) : tactic Unit := do\n let e ← i_to_expr_for_apply e\n concat_tags <| tactic.apply_mod_cast e\n#align tactic.interactive.apply_mod_cast tactic.interactive.apply_mod_cast\n\n/--\nNormalize the goal and every expression in the local context, then close the goal with assumption.\n-/\nunsafe def assumption_mod_cast : tactic Unit :=\n tactic.assumption_mod_cast\n#align tactic.interactive.assumption_mod_cast tactic.interactive.assumption_mod_cast\n\nend Tactic.Interactive\n\nnamespace Conv.Interactive\n\nopen Conv\n\nopen NormCast (derive)\n\n/-- the converter version of `norm_cast' -/\nunsafe def norm_cast : conv Unit :=\n replace_lhs derive\n#align conv.interactive.norm_cast conv.interactive.norm_cast\n\nend Conv.Interactive\n\n-- TODO: move this elsewhere?\n@[norm_cast]\ntheorem ite_cast {α β} [HasLiftT α β] {c : Prop} [Decidable c] {a b : α} :\n ↑(ite c a b) = ite c (↑a : β) (↑b : β) := by by_cases h : c <;> simp [h]\n#align ite_cast ite_cast\n\n@[norm_cast]\ntheorem dite_cast {α β} [HasLiftT α β] {c : Prop} [Decidable c] {a : c → α} {b : ¬c → α} :\n ↑(dite c a b) = dite c (fun h => (↑(a h) : β)) fun h => (↑(b h) : β) := by\n by_cases h : c <;> simp [h]\n#align dite_cast dite_cast\n\nadd_hint_tactic norm_cast at *\n\n/-- The `norm_cast` family of tactics is used to normalize casts inside expressions.\nIt is basically a simp tactic with a specific set of lemmas to move casts\nupwards in the expression.\nTherefore it can be used more safely as a non-terminating tactic.\nIt also has special handling of numerals.\n\nFor instance, given an assumption\n```lean\na b : ℤ\nh : ↑a + ↑b < (10 : ℚ)\n```\n\nwriting `norm_cast at h` will turn `h` into\n```lean\nh : a + b < 10\n```\n\nYou can also use `exact_mod_cast`, `apply_mod_cast`, `rw_mod_cast`\nor `assumption_mod_cast`.\nWriting `exact_mod_cast h` and `apply_mod_cast h` will normalize the goal and\n`h` before using `exact h` or `apply h`.\nWriting `assumption_mod_cast` will normalize the goal and for every\nexpression `h` in the context it will try to normalize `h` and use\n`exact h`.\n`rw_mod_cast` acts like the `rw` tactic but it applies `norm_cast` between steps.\n\n`push_cast` rewrites the expression to move casts toward the leaf nodes.\nThis uses `norm_cast` lemmas in the forward direction.\nFor example, `↑(a + b)` will be written to `↑a + ↑b`.\nIt is equivalent to `simp only with push_cast`.\nIt can also be used at hypotheses with `push_cast at h`\nand with extra simp lemmas with `push_cast [int.add_zero]`.\n\n```lean\nexample (a b : ℕ) (h1 : ((a + b : ℕ) : ℤ) = 10) (h2 : ((a + b + 0 : ℕ) : ℤ) = 10) :\n ((a + b : ℕ) : ℤ) = 10 :=\nbegin\n push_cast,\n push_cast at h1,\n push_cast [int.add_zero] at h2,\nend\n```\n\nThe implementation and behavior of the `norm_cast` family is described in detail at\n.\n-/\nadd_tactic_doc\n { Name := \"norm_cast\"\n category := DocCategory.tactic\n declNames :=\n [`` tactic.interactive.norm_cast, `` tactic.interactive.rw_mod_cast,\n `` tactic.interactive.apply_mod_cast, `` tactic.interactive.assumption_mod_cast,\n `` tactic.interactive.exact_mod_cast, `` tactic.interactive.push_cast]\n tags := [\"coercions\", \"simplification\"] }\n\n/-- The `norm_cast` attribute should be given to lemmas that describe the\nbehaviour of a coercion in regard to an operator, a relation, or a particular\nfunction.\n\nIt only concerns equality or iff lemmas involving `↑`, `⇑` and `↥`, describing the behavior of\nthe coercion functions.\nIt does not apply to the explicit functions that define the coercions.\n\nExamples:\n```lean\n@[norm_cast] theorem coe_nat_inj' {m n : ℕ} : (↑m : ℤ) = ↑n ↔ m = n\n\n@[norm_cast] theorem coe_int_denom (n : ℤ) : (n : ℚ).denom = 1\n\n@[norm_cast] theorem cast_id : ∀ n : ℚ, ↑n = n\n\n@[norm_cast] theorem coe_nat_add (m n : ℕ) : (↑(m + n) : ℤ) = ↑m + ↑n\n\n@[norm_cast] theorem cast_sub [add_group α] [has_one α] {m n} (h : m ≤ n) :\n ((n - m : ℕ) : α) = n - m\n\n@[norm_cast] theorem coe_nat_bit0 (n : ℕ) : (↑(bit0 n) : ℤ) = bit0 ↑n\n\n@[norm_cast] theorem cast_coe_nat (n : ℕ) : ((n : ℤ) : α) = n\n\n@[norm_cast] theorem cast_one : ((1 : ℚ) : α) = 1\n```\n\nLemmas tagged with `@[norm_cast]` are classified into three categories: `move`, `elim`, and\n`squash`. They are classified roughly as follows:\n\n* elim lemma: LHS has 0 head coes and ≥ 1 internal coe\n* move lemma: LHS has 1 head coe and 0 internal coes, RHS has 0 head coes and ≥ 1 internal coes\n* squash lemma: LHS has ≥ 1 head coes and 0 internal coes, RHS has fewer head coes\n\n`norm_cast` uses `move` and `elim` lemmas to factor coercions toward the root of an expression\nand to cancel them from both sides of an equation or relation. It uses `squash` lemmas to clean\nup the result.\n\nOccasionally you may want to override the automatic classification.\nYou can do this by giving an optional `elim`, `move`, or `squash` parameter to the attribute.\n\n```lean\n@[simp, norm_cast elim] lemma nat_cast_re (n : ℕ) : (n : ℂ).re = n :=\nby rw [← of_real_nat_cast, of_real_re]\n```\n\nDon't do this unless you understand what you are doing.\n\nA full description of the tactic, and the use of each lemma category, can be found at\n.\n-/\nadd_tactic_doc\n { Name := \"norm_cast attributes\"\n category := DocCategory.attr\n declNames := [`` norm_cast.norm_cast_attr]\n tags := [\"coercions\", \"simplification\"] }\n\n", "meta": {"author": "leanprover-community", "repo": "mathlib3port", "sha": "62505aa236c58c8559783b16d33e30df3daa54f4", "save_path": "github-repos/lean/leanprover-community-mathlib3port", "path": "github-repos/lean/leanprover-community-mathlib3port/mathlib3port-62505aa236c58c8559783b16d33e30df3daa54f4/Mathbin/Tactic/NormCast.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3522017956470284, "lm_q2_score": 0.05582314388349448, "lm_q1q2_score": 0.019661011514429186}} {"text": "import Lean\n\n\n\nstructure A :=\n(x : Nat := 10)\n\ndef f : A :=\n{ }\n\ntheorem ex : f = { x := 10 } :=\nrfl\n\n#check f\n\nsyntax (name := emptyS) \"⟨\" \"⟩\" : term -- overload `⟨ ⟩` notation\n\nopen Lean\nopen Lean.Elab\nopen Lean.Elab.Term\n\n@[termElab emptyS] def elabEmptyS : TermElab :=\nfun stx expectedType? => do\n tryPostponeIfNoneOrMVar expectedType?\n let stxNew ← `(Nat.zero)\n withMacroExpansion stx stxNew $\n elabTerm stxNew expectedType?\n\ndef foo (x : Unit) := x\n\ndef f1 : Unit :=\nlet x := ⟨ ⟩\nfoo x\n\ndef f2 : Unit :=\nlet x := ⟨ ⟩\nx\n\ndef f3 : Nat :=\nlet x := ⟨ ⟩\nx\n\ntheorem ex2 : f3 = 0 :=\nrfl\n", "meta": {"author": "gebner", "repo": "lean4-old", "sha": "ee51cdfaf63ee313c914d83264f91f414a0e3b6e", "save_path": "github-repos/lean/gebner-lean4-old", "path": "github-repos/lean/gebner-lean4-old/lean4-old-ee51cdfaf63ee313c914d83264f91f414a0e3b6e/tests/lean/run/choiceExpectedTypeBug.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.35220178204788966, "lm_q2_score": 0.055823144668888804, "lm_q1q2_score": 0.019661011031899787}} {"text": "/-\nCopyright (c) 2015 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthor: Mario Carneiro\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.default\nimport Mathlib.data.multiset.powerset\nimport Mathlib.data.multiset.range\nimport Mathlib.PostPort\n\nuniverses u_1 u_2 u_3 \n\nnamespace Mathlib\n\n/-!\n# The `nodup` predicate for multisets without duplicate elements.\n-/\n\nnamespace multiset\n\n\n/- nodup -/\n\n/-- `nodup s` means that `s` has no duplicates, i.e. the multiplicity of\n any element is at most 1. -/\ndef nodup {α : Type u_1} (s : multiset α) :=\n quot.lift_on s list.nodup sorry\n\n@[simp] theorem coe_nodup {α : Type u_1} {l : List α} : nodup ↑l ↔ list.nodup l :=\n iff.rfl\n\n@[simp] theorem nodup_zero {α : Type u_1} : nodup 0 :=\n list.pairwise.nil\n\n@[simp] theorem nodup_cons {α : Type u_1} {a : α} {s : multiset α} : nodup (a ::ₘ s) ↔ ¬a ∈ s ∧ nodup s :=\n quot.induction_on s fun (l : List α) => list.nodup_cons\n\ntheorem nodup_cons_of_nodup {α : Type u_1} {a : α} {s : multiset α} (m : ¬a ∈ s) (n : nodup s) : nodup (a ::ₘ s) :=\n iff.mpr nodup_cons { left := m, right := n }\n\ntheorem nodup_singleton {α : Type u_1} (a : α) : nodup (a ::ₘ 0) :=\n list.nodup_singleton\n\ntheorem nodup_of_nodup_cons {α : Type u_1} {a : α} {s : multiset α} (h : nodup (a ::ₘ s)) : nodup s :=\n and.right (iff.mp nodup_cons h)\n\ntheorem not_mem_of_nodup_cons {α : Type u_1} {a : α} {s : multiset α} (h : nodup (a ::ₘ s)) : ¬a ∈ s :=\n and.left (iff.mp nodup_cons h)\n\ntheorem nodup_of_le {α : Type u_1} {s : multiset α} {t : multiset α} (h : s ≤ t) : nodup t → nodup s :=\n le_induction_on h fun (l₁ l₂ : List α) => list.nodup_of_sublist\n\ntheorem not_nodup_pair {α : Type u_1} (a : α) : ¬nodup (a ::ₘ a ::ₘ 0) :=\n list.not_nodup_pair\n\ntheorem nodup_iff_le {α : Type u_1} {s : multiset α} : nodup s ↔ ∀ (a : α), ¬a ::ₘ a ::ₘ 0 ≤ s :=\n quot.induction_on s\n fun (l : List α) => iff.trans list.nodup_iff_sublist (forall_congr fun (a : α) => not_congr (iff.symm repeat_le_coe))\n\ntheorem nodup_iff_ne_cons_cons {α : Type u_1} {s : multiset α} : nodup s ↔ ∀ (a : α) (t : multiset α), s ≠ a ::ₘ a ::ₘ t := sorry\n\ntheorem nodup_iff_count_le_one {α : Type u_1} [DecidableEq α] {s : multiset α} : nodup s ↔ ∀ (a : α), count a s ≤ 1 :=\n quot.induction_on s fun (l : List α) => list.nodup_iff_count_le_one\n\n@[simp] theorem count_eq_one_of_mem {α : Type u_1} [DecidableEq α] {a : α} {s : multiset α} (d : nodup s) (h : a ∈ s) : count a s = 1 :=\n le_antisymm (iff.mp nodup_iff_count_le_one d a) (iff.mpr count_pos h)\n\ntheorem nodup_iff_pairwise {α : Type u_1} {s : multiset α} : nodup s ↔ pairwise ne s :=\n quotient.induction_on s fun (l : List α) => iff.symm (pairwise_coe_iff_pairwise fun (a b : α) => ne.symm)\n\ntheorem pairwise_of_nodup {α : Type u_1} {r : α → α → Prop} {s : multiset α} : (∀ (a : α), a ∈ s → ∀ (b : α), b ∈ s → a ≠ b → r a b) → nodup s → pairwise r s := sorry\n\ntheorem forall_of_pairwise {α : Type u_1} {r : α → α → Prop} (H : symmetric r) {s : multiset α} (hs : pairwise r s) (a : α) : a ∈ s → ∀ (b : α), b ∈ s → a ≠ b → r a b := sorry\n\ntheorem nodup_add {α : Type u_1} {s : multiset α} {t : multiset α} : nodup (s + t) ↔ nodup s ∧ nodup t ∧ disjoint s t :=\n quotient.induction_on₂ s t fun (l₁ l₂ : List α) => list.nodup_append\n\ntheorem disjoint_of_nodup_add {α : Type u_1} {s : multiset α} {t : multiset α} (d : nodup (s + t)) : disjoint s t :=\n and.right (and.right (iff.mp nodup_add d))\n\ntheorem nodup_add_of_nodup {α : Type u_1} {s : multiset α} {t : multiset α} (d₁ : nodup s) (d₂ : nodup t) : nodup (s + t) ↔ disjoint s t := sorry\n\ntheorem nodup_of_nodup_map {α : Type u_1} {β : Type u_2} (f : α → β) {s : multiset α} : nodup (map f s) → nodup s :=\n quot.induction_on s fun (l : List α) => list.nodup_of_nodup_map f\n\ntheorem nodup_map_on {α : Type u_1} {β : Type u_2} {f : α → β} {s : multiset α} : (∀ (x : α), x ∈ s → ∀ (y : α), y ∈ s → f x = f y → x = y) → nodup s → nodup (map f s) :=\n quot.induction_on s fun (l : List α) => list.nodup_map_on\n\ntheorem nodup_map {α : Type u_1} {β : Type u_2} {f : α → β} {s : multiset α} (hf : function.injective f) : nodup s → nodup (map f s) :=\n nodup_map_on fun (x : α) (_x : x ∈ s) (y : α) (_x : y ∈ s) (h : f x = f y) => hf h\n\ntheorem nodup_filter {α : Type u_1} (p : α → Prop) [decidable_pred p] {s : multiset α} : nodup s → nodup (filter p s) :=\n quot.induction_on s fun (l : List α) => list.nodup_filter p\n\n@[simp] theorem nodup_attach {α : Type u_1} {s : multiset α} : nodup (attach s) ↔ nodup s :=\n quot.induction_on s fun (l : List α) => list.nodup_attach\n\ntheorem nodup_pmap {α : Type u_1} {β : Type u_2} {p : α → Prop} {f : (a : α) → p a → β} {s : multiset α} {H : ∀ (a : α), a ∈ s → p a} (hf : ∀ (a : α) (ha : p a) (b : α) (hb : p b), f a ha = f b hb → a = b) : nodup s → nodup (pmap f s H) :=\n quot.induction_on s (fun (l : List α) (H : ∀ (a : α), a ∈ Quot.mk setoid.r l → p a) => list.nodup_pmap hf) H\n\nprotected instance nodup_decidable {α : Type u_1} [DecidableEq α] (s : multiset α) : Decidable (nodup s) :=\n quotient.rec_on_subsingleton s fun (l : List α) => list.nodup_decidable l\n\ntheorem nodup_erase_eq_filter {α : Type u_1} [DecidableEq α] (a : α) {s : multiset α} : nodup s → erase s a = filter (fun (_x : α) => _x ≠ a) s :=\n quot.induction_on s fun (l : List α) (d : nodup (Quot.mk setoid.r l)) => congr_arg coe (list.nodup_erase_eq_filter a d)\n\ntheorem nodup_erase_of_nodup {α : Type u_1} [DecidableEq α] (a : α) {l : multiset α} : nodup l → nodup (erase l a) :=\n nodup_of_le (erase_le a l)\n\ntheorem mem_erase_iff_of_nodup {α : Type u_1} [DecidableEq α] {a : α} {b : α} {l : multiset α} (d : nodup l) : a ∈ erase l b ↔ a ≠ b ∧ a ∈ l := sorry\n\ntheorem mem_erase_of_nodup {α : Type u_1} [DecidableEq α] {a : α} {l : multiset α} (h : nodup l) : ¬a ∈ erase l a := sorry\n\ntheorem nodup_product {α : Type u_1} {β : Type u_2} {s : multiset α} {t : multiset β} : nodup s → nodup t → nodup (product s t) := sorry\n\ntheorem nodup_sigma {α : Type u_1} {σ : α → Type u_2} {s : multiset α} {t : (a : α) → multiset (σ a)} : nodup s → (∀ (a : α), nodup (t a)) → nodup (multiset.sigma s t) := sorry\n\ntheorem nodup_filter_map {α : Type u_1} {β : Type u_2} (f : α → Option β) {s : multiset α} (H : ∀ (a a' : α) (b : β), b ∈ f a → b ∈ f a' → a = a') : nodup s → nodup (filter_map f s) :=\n quot.induction_on s fun (l : List α) => list.nodup_filter_map H\n\ntheorem nodup_range (n : ℕ) : nodup (range n) :=\n list.nodup_range n\n\ntheorem nodup_inter_left {α : Type u_1} [DecidableEq α] {s : multiset α} (t : multiset α) : nodup s → nodup (s ∩ t) :=\n nodup_of_le (inter_le_left s t)\n\ntheorem nodup_inter_right {α : Type u_1} [DecidableEq α] (s : multiset α) {t : multiset α} : nodup t → nodup (s ∩ t) :=\n nodup_of_le (inter_le_right s t)\n\n@[simp] theorem nodup_union {α : Type u_1} [DecidableEq α] {s : multiset α} {t : multiset α} : nodup (s ∪ t) ↔ nodup s ∧ nodup t := sorry\n\n@[simp] theorem nodup_powerset {α : Type u_1} {s : multiset α} : nodup (powerset s) ↔ nodup s := sorry\n\ntheorem nodup_powerset_len {α : Type u_1} {n : ℕ} {s : multiset α} (h : nodup s) : nodup (powerset_len n s) :=\n nodup_of_le (powerset_len_le_powerset n s) (iff.mpr nodup_powerset h)\n\n@[simp] theorem nodup_bind {α : Type u_1} {β : Type u_2} {s : multiset α} {t : α → multiset β} : nodup (bind s t) ↔ (∀ (a : α), a ∈ s → nodup (t a)) ∧ pairwise (fun (a b : α) => disjoint (t a) (t b)) s := sorry\n\ntheorem nodup_ext {α : Type u_1} {s : multiset α} {t : multiset α} : nodup s → nodup t → (s = t ↔ ∀ (a : α), a ∈ s ↔ a ∈ t) :=\n quotient.induction_on₂ s t\n fun (l₁ l₂ : List α) (d₁ : nodup (quotient.mk l₁)) (d₂ : nodup (quotient.mk l₂)) =>\n iff.trans quotient.eq (list.perm_ext d₁ d₂)\n\ntheorem le_iff_subset {α : Type u_1} {s : multiset α} {t : multiset α} : nodup s → (s ≤ t ↔ s ⊆ t) :=\n quotient.induction_on₂ s t\n fun (l₁ l₂ : List α) (d : nodup (quotient.mk l₁)) => { mp := subset_of_le, mpr := list.subperm_of_subset_nodup d }\n\ntheorem range_le {m : ℕ} {n : ℕ} : range m ≤ range n ↔ m ≤ n :=\n iff.trans (le_iff_subset (nodup_range m)) range_subset\n\ntheorem mem_sub_of_nodup {α : Type u_1} [DecidableEq α] {a : α} {s : multiset α} {t : multiset α} (d : nodup s) : a ∈ s - t ↔ a ∈ s ∧ ¬a ∈ t := sorry\n\ntheorem map_eq_map_of_bij_of_nodup {α : Type u_1} {β : Type u_2} {γ : Type u_3} (f : α → γ) (g : β → γ) {s : multiset α} {t : multiset β} (hs : nodup s) (ht : nodup t) (i : (a : α) → a ∈ s → β) (hi : ∀ (a : α) (ha : a ∈ s), i a ha ∈ t) (h : ∀ (a : α) (ha : a ∈ s), f a = g (i a ha)) (i_inj : ∀ (a₁ a₂ : α) (ha₁ : a₁ ∈ s) (ha₂ : a₂ ∈ s), i a₁ ha₁ = i a₂ ha₂ → a₁ = a₂) (i_surj : ∀ (b : β), b ∈ t → ∃ (a : α), ∃ (ha : a ∈ s), b = i a ha) : map f s = map g t := sorry\n\n", "meta": {"author": "AurelienSaue", "repo": "Mathlib4_auto", "sha": "590df64109b08190abe22358fabc3eae000943f2", "save_path": "github-repos/lean/AurelienSaue-Mathlib4_auto", "path": "github-repos/lean/AurelienSaue-Mathlib4_auto/Mathlib4_auto-590df64109b08190abe22358fabc3eae000943f2/Mathlib/data/multiset/nodup.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3960681520167196, "lm_q2_score": 0.04958902842678734, "lm_q1q2_score": 0.019640634849302237}} {"text": "import o_minimal.sheaf.tactic\n\nnamespace o_minimal\n\nvariables {R : Type*} {S : struc R}\nvariables {X Y Z : Type*} [definable_sheaf S X] [definable_sheaf S Y] [definable_sheaf S Z]\n\n-- TODO: consistent naming\n\nlemma definable.const : definable S (@function.const X Y) :=\nbegin [defin]\n intro x,\n intro y,\n var\nend\n\nlemma definable_comp : definable S (@function.comp X Y Z) :=\nbegin [defin]\n intro f,\n intro g,\n intro x,\n app, var,\n app, var, var\nend\n\nlemma definable.app {f : X → Y} (hf : definable S f) {x : X} (hx : definable S x) :\n definable S (f x) :=\nbegin [defin]\n app,\n exact hf.definable _,\n exact hx.definable _\nend\n\nlemma definable.comp {g : Y → Z} (hg : definable S g) {f : X → Y} (hf : definable S f) :\n definable S (g ∘ f) :=\n(definable_comp.app hg).app hf\n\nlemma definable.prod_mk : definable S (@prod.mk X Y) :=\nbegin [defin]\n intro x,\n intro y,\n exact ⟨x.definable, y.definable⟩\nend\n\nlemma definable.fst : definable S (prod.fst : X × Y → X) :=\nbegin [defin]\n intro p,\n exact p.definable.1\nend\n\nlemma definable.snd : definable S (prod.snd : X × Y → Y) :=\nbegin [defin]\n intro p,\n exact p.definable.2\nend\n\nlemma definable.curry : definable S (@function.curry X Y Z) :=\nbegin [defin]\n intro f,\n intro x,\n intro y,\n app, var,\n app, app, exact definable.prod_mk.definable _, var, var\nend\n\nlemma definable.uncurry : definable S (@function.uncurry X Y Z) :=\nbegin [defin]\n intro f,\n intro p,\n app, app, var,\n app, exact definable.fst.definable _, var,\n app, exact definable.snd.definable _, var\nend\n\ninstance punit.definable_sheaf : definable_sheaf S punit :=\n{ definable := λ K f, true,\n definable_precomp := λ L K φ f hf, trivial,\n definable_cover := λ K f 𝓛 h, trivial }\n\nlemma definable.star : definable S punit.star :=\nbegin [defin]\n exact trivial\nend\n\ninstance Prop.definable_sheaf : definable_sheaf S Prop :=\n{ definable := λ K f, def_set S f,\n definable_precomp := λ L K φ f hf, φ.is_definable.preimage hf,\n definable_cover := λ K f 𝓛 h, Def.set_subcanonical 𝓛 f h }\n\nlemma definable.and : definable S and :=\nbegin [defin]\n intro p,\n intro q,\n exact def_set.inter p.definable q.definable\nend\n\nlemma definable.or : definable S or :=\nbegin [defin]\n intro p,\n intro q,\n exact def_set.union p.definable q.definable\nend\n\nlemma definable.imp : definable S ((→) : Prop → Prop → Prop) :=\nbegin [defin]\n intro p,\n intro q,\n exact def_set.imp p.definable q.definable\nend\n\nlemma definable.not : definable S not :=\nbegin [defin]\n intro p,\n exact def_set.compl p.definable\nend\n\nlemma definable.iff : definable S iff :=\nbegin [defin]\n intro p,\n intro q,\n exact def_set.iff p.definable q.definable\nend\n\ninstance set.definable_sheaf : definable_sheaf S (set X) :=\nshow definable_sheaf S (X → Prop), by apply_instance\n\nlemma definable.mem : definable S ((∈) : X → set X → Prop) :=\nbegin [defin]\n intro x,\n intro s,\n app, var, var\nend\n\nlemma definable.inter : definable S ((∩) : set X → set X → set X) :=\nbegin [defin]\n intro s,\n intro t,\n intro x,\n app,\n app,\n exact definable.and.definable _,\n app, app, exact definable.mem.definable _, var, var,\n app, app, exact definable.mem.definable _, var, var\nend\n\nlemma definable.union : definable S ((∪) : set X → set X → set X) :=\nbegin [defin]\n intro s,\n intro t,\n intro x,\n app,\n app,\n exact definable.or.definable _,\n app, app, exact definable.mem.definable _, var, var,\n app, app, exact definable.mem.definable _, var, var\nend\n\nlemma definable.compl : definable S (set.compl : set X → set X) :=\nbegin [defin]\n intro s,\n intro x,\n app, exact definable.not.definable _,\n app, app, exact definable.mem.definable _, var, var\nend\n\nlemma definable.diff : definable S ((\\) : set X → set X → set X) :=\nbegin [defin]\n intro s,\n intro t,\n intro x,\n app, app, exact definable.and.definable _,\n app, app, exact definable.mem.definable _, var, var,\n -- unnecessarily complicated, but hey why not\n -- TODO: `change`\n app,\n intro a,\n app, exact definable.not.definable _,\n app, app, exact definable.mem.definable _, var, var,\n var\nend\n\n-- Quantification over X is not definable in general.\n-- Needs a special property of X: \"quasicompactness\"?\n-- See `quantifiers` (for now, just over representables)\n\ninstance set.coe.definable_sheaf {s : set X} : definable_sheaf S s :=\n{ definable := λ K f, definable_sheaf.definable (subtype.val ∘ f),\n definable_precomp := λ L K φ f hf,\n definable_sheaf.definable_precomp φ (subtype.val ∘ f) hf,\n definable_cover := λ K f 𝓛 hf,\n definable_sheaf.definable_cover (subtype.val ∘ f) 𝓛 hf }\n\ninstance subtype.definable_sheaf {p : X → Prop} : definable_sheaf S {x // p x} :=\nshow definable_sheaf S (set_of p), by apply_instance\n\n-- instance prop.definable_sheaf {p : Prop} : definable_sheaf S p := sorry\n\n-- TODO: With an instance for Pi types, can we state the definable dependence on `s`?\nlemma definable.subtype.val {s : set X} : definable S (subtype.val : s → X) :=\nbegin [defin]\n intro v,\n exact v.definable\nend\n\nlemma definable_of_subtype_val {s : set Y} {f : X → s}\n (hf : definable S (subtype.val ∘ f)) : definable S f :=\nbegin\n cases hf with hf,\n exact ⟨λ K, hf K⟩\nend\n\n-- How to state definable subtype.mk?\n/-\nlemma definable.subtype.mk {s : set X} :\n definable S (subtype.mk : Π (x : X), x ∈ s → s) :=\nbegin\nend\n-/\n\nlemma definable_subtype.map {s : set X} {t : set Y} {f : X → Y} (hf : definable S f)\n (h : ∀ x ∈ s, f x ∈ t) : definable S (subtype.map f h : s → t) :=\ndefinable_of_subtype_val $ hf.comp definable.subtype.val\n\nend o_minimal\n", "meta": {"author": "rwbarton", "repo": "lean-omin", "sha": "fd733c6d95ef6f4743aae97de5e15df79877c00e", "save_path": "github-repos/lean/rwbarton-lean-omin", "path": "github-repos/lean/rwbarton-lean-omin/lean-omin-fd733c6d95ef6f4743aae97de5e15df79877c00e/src/o_minimal/sheaf/constants.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4263215925474903, "lm_q2_score": 0.04603389961812015, "lm_q1q2_score": 0.01962524539636829}} {"text": "import Lean\n\n\n\nstructure A :=\n(x : Nat := 10)\n\ndef f : A :=\n{ }\n\ntheorem ex : f = { x := 10 } :=\nrfl\n\n#check f\n\nsyntax (name := emptyS) \"⟨\" \"⟩\" : term -- overload `⟨ ⟩` notation\n\nopen Lean\nopen Lean.Elab\nopen Lean.Elab.Term\n\n@[term_elab emptyS] def elabEmptyS : TermElab :=\nfun stx expectedType? => do\n tryPostponeIfNoneOrMVar expectedType?\n let stxNew ← `(Nat.zero)\n withMacroExpansion stx stxNew $\n elabTerm stxNew expectedType?\n\ndef foo (x : Unit) := x\n\ndef f1 : Unit :=\nlet x := ⟨ ⟩\nfoo x\n\ndef f2 : Unit :=\nlet x := ⟨ ⟩\nx\n\ndef f3 : Nat :=\nlet x := ⟨ ⟩\nx\n\ntheorem ex2 : f3 = 0 :=\nrfl\n", "meta": {"author": "leanprover", "repo": "lean4", "sha": "742d053a97bdd109a41a921facd1cd6a55e89bc7", "save_path": "github-repos/lean/leanprover-lean4", "path": "github-repos/lean/leanprover-lean4/lean4-742d053a97bdd109a41a921facd1cd6a55e89bc7/tests/lean/run/choiceExpectedTypeBug.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.35577489351363034, "lm_q2_score": 0.0550052828715485, "lm_q1q2_score": 0.019569498656312283}} {"text": "import C0deine.Utils.Symbol\n\nnamespace C0deine\n\ninductive Typ.Primitive\n| int\n| bool\nderiving DecidableEq, Inhabited, Hashable\n\nmutual\ninductive Typ\n| prim (p : Typ.Primitive)\n| mem (m : Typ.Memory)\nderiving Inhabited, Hashable\n\ninductive Typ.Memory\n| pointer (typ : Typ)\n| array (typ : Typ)\n| struct (sym : Symbol)\nderiving Inhabited, Hashable\nend\n\ninductive Typ.Check\n| type : Typ → Typ.Check\n| void\n| any\nderiving Inhabited\n\nnamespace Typ\n\ndef Primitive.toString : Typ.Primitive → String\n | .int => \"int\"\n | .bool => \"bool\"\ninstance : ToString Primitive where toString := Primitive.toString\n\nmutual\ndef Memory.toString : Typ.Memory → String\n | .pointer (typ : Typ) => s!\"{toString typ}*\"\n | .array (typ : Typ) => s!\"{toString typ}[]\"\n | .struct (sym : Symbol) => s!\"struct {sym}\"\n\ndef toString : Typ → String\n | .prim (p : Primitive) => Primitive.toString p\n | .mem (m : Typ.Memory) => Memory.toString m\nend\n\ndef Check.toString : Check → String\n | .type t => s!\"{Typ.toString t}\"\n | .void => \"`void\"\n | .any => \"`any\"\n\ninstance : ToString Memory where toString := Memory.toString\ninstance : ToString Typ where toString := Typ.toString\ninstance : ToString Typ.Check where toString := Typ.Check.toString\ninstance : ToString (Option Typ) where\n toString | none => \"void\" | some t => s!\"{t}\"\n\nmutual\n-- encoding structural equality\ndef structEq (a b : Typ) : Bool :=\n match a, b with\n | .prim p1, .prim p2 => p1 = p2\n | .mem m1, .mem m2 => Memory.structEq m1 m2\n | _, _ => false\n\ndef Memory.structEq (a b : Memory) : Bool :=\n match a, b with\n | .struct s1, .struct s2 => s1 = s2\n | .pointer t1, .pointer t2 => Typ.structEq t1 t2\n | .array t1, .array t2 => Typ.structEq t1 t2\n | _, _ => false\nend\n\nmutual\ntheorem deq {a b : Typ} : structEq a b = true ↔ a = b := by\n cases a <;> cases b <;>\n ( unfold structEq\n simp\n try apply Memory.deq\n )\n\ntheorem Memory.deq {a b : Memory} : Memory.structEq a b = true ↔ a = b := by\n cases a <;> cases b <;>\n ( unfold Memory.structEq\n simp\n try apply Typ.deq\n )\nend\n\ninstance : DecidableEq Typ := fun a b =>\n match Bool.decEq (Typ.structEq a b) true with\n | .isTrue h => .isTrue (Typ.deq.mp h)\n | .isFalse h => .isFalse (h ∘ Typ.deq.mpr)\ninstance : DecidableEq Memory := fun a b =>\n match Bool.decEq (Memory.structEq a b) true with\n | .isTrue h => .isTrue (Memory.deq.mp h)\n | .isFalse h => .isFalse (h ∘ Memory.deq.mpr)\n\nderiving instance DecidableEq for Typ.Check\n\nmutual\n def equiv (a b : Typ) : Bool :=\n match a, b with\n | .prim p1 , .prim p2 => p1 == p2\n | .mem m1 , .mem m2 => Memory.equiv m1 m2\n | _, _ => false\n\n def Memory.equiv (a b : Memory) : Bool :=\n match a, b with\n | .pointer t1, .pointer t2 => equiv t1 t2\n | .array t1 , .array t2 => equiv t1 t2\n | .struct s1 , .struct s2 => s1 == s2\n | _, _ => false\nend\n\ndef Check.equiv (a b : Check) : Bool :=\n match a, b with\n | .type t1, .type t2 => Typ.equiv t1 t2\n | .void, .void => true\n | .any, .type (.mem (.array _))\n | .type (.mem (.array _)), .any => false\n | .any, .type (.mem _) | .type (.mem _), .any => true\n | .any, .any => true\n | _, _ => false\n\ndef isScalar : Typ → Bool\n | .prim .int => true\n | .prim .bool => true\n | _ => false\ndef Check.isScalar : Typ.Check → Bool\n | .type t => t.isScalar\n | _ => false\n\ndef isSmall : Typ → Bool\n | .mem (.struct _) => false\n | _ => true\ndef Check.isSmall : Typ.Check → Bool\n | .type t => t.isSmall\n | _ => true\n\ndef sizeof : Typ → Option Nat\n | .prim .int => some 4\n | .prim .bool => some 1\n | .mem (.pointer _) => some 8\n | .mem (.array _) => some 8\n | .mem (.struct _) => none\ndef Check.sizeof : Typ.Check → Option Nat\n | .type t => t.sizeof\n | _ => none\nend Typ\n", "meta": {"author": "JamesGallicchio", "repo": "c0deine", "sha": "afe36eb72c126bf0cf6682aac2048341a38e6b0d", "save_path": "github-repos/lean/JamesGallicchio-c0deine", "path": "github-repos/lean/JamesGallicchio-c0deine/c0deine-afe36eb72c126bf0cf6682aac2048341a38e6b0d/C0deine/Type/Typ.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4378234991142019, "lm_q2_score": 0.04468086836450484, "lm_q1q2_score": 0.019562334130808556}} {"text": "import data.set\n\nnamespace probability_theory\n\n-- TODO subtype.restrict?\ndef pi_subtype {α : Type*} {β : α → Type*} (mv : set α) := λ (g : Π i, β i) (i : mv), g i\n\n@[reducible]\ndef pi_subtype_img {α : Type*} {β : α → Type*} (mv : set α) :=\n λ (g : set (Π i, β i)) , pi_subtype mv '' g\n\n@[reducible]\ndef pi_unsubtype_img {α : Type*} {β : α → Type*} (mv : set α) :=\n λ (g : set (Π i : mv, β i)), pi_subtype mv ⁻¹' g\n\nnotation `<[`S`]` := pi_subtype_img S\nnotation `>[`S`]` := pi_unsubtype_img S\n\nnotation `<[]` := pi_subtype_img _\nnotation `>[]` := pi_unsubtype_img _\n\ndef set_to_subtype {α : Type*} (A : set α) (B : set α) : set A := λ x : A, ↑x ∈ B\n\ndef pi_set_to_subtype {α : Type*} {β : α → Type*} (A : set α) (B : set α)\n (f : Π i : B, β i) : Π i : set_to_subtype A B, β i := λ ⟨i, hi⟩, f ⟨i, hi⟩\n\nlemma pi_set_to_subtype_def {α : Type*} {β : α → Type*} (A : set α) (B : set α)\n (f : Π i : B, β i) (i : α) (hi : i ∈ A) (hi' : i ∈ B) :\n pi_set_to_subtype A B f ⟨⟨i, hi⟩, hi'⟩ = f ⟨↑(⟨i, hi⟩ : A), hi'⟩ := rfl\n\nlemma pi_set_to_subtype_def' {α : Type*} {β : α → Type*} (A : set α) (B : set α)\n (f : Π i : B, β i) (i : set_to_subtype A B) :\n pi_set_to_subtype A B f i = f ⟨↑(⟨i.val.val, i.val.property⟩ : A), i.property⟩ :=\nbegin\n obtain ⟨⟨_, _⟩, _⟩ := i,\n rw pi_set_to_subtype_def,\nend\n\nlemma pi_set_to_subtype_bijective {α : Type*} {β : α → Type*} {A : set α} {B : set α} (hAB : B ⊆ A)\n : function.bijective (@pi_set_to_subtype _ β A B) :=\nbegin\n constructor,\n { intros f f' hff',\n have h := congr_fun hff',\n simp_rw pi_set_to_subtype_def' at h,\n ext i,\n specialize h ⟨⟨i, hAB i.property⟩, i.property⟩,\n convert h; exact subtype.eq rfl },\n { intro f,\n refine ⟨(λ i, f ⟨⟨i, hAB i.property⟩, i.property⟩), _⟩,\n ext i,\n rw pi_set_to_subtype_def',\n congr,\n refine subtype.eq _, refine subtype.eq rfl },\nend\n\nlemma pi_set_to_subtype_img_preimage_idx {α : Type*} {β : α → Type*} {A : set α} {B : set α} (hAB : B ⊆ A) {b : B} (bs : set (β b)) :\npi_set_to_subtype A B '' ((λ (g : Π (i : B), β i), g b) ⁻¹' bs)\n= (λ (g : Π (i : set_to_subtype A B), β i), g ⟨⟨b, hAB b.property⟩, b.property⟩) ⁻¹' bs :=\nbegin\n ext1 x,\n split,\n rintro ⟨bs', hbs', hbsx'⟩,\n change bs' _ ∈ bs at hbs',\n change _ ∈ bs,\n subst hbsx',\n change bs' ⟨_, _⟩ ∈ _,\n convert hbs',\n exact subtype.eq rfl,\n intro hx,\n refine ⟨λ b : B, x ⟨⟨b, hAB b.property⟩, b.property⟩, hx, _⟩, ext ⟨⟨_, _⟩, _⟩, refl\nend\n\n@[reducible]\ndef pi_unsubtype_set {α : Type*} {β : α → Type*} (A : set α) (B : set α) :\n set (Π i : B, β i) → set (Π i : A, β i)\n := λ g, >[set_to_subtype A B] (pi_set_to_subtype A B '' g)\n\nnotation `>>[`A`]` := pi_unsubtype_set A _\nnotation `>>[]` := pi_unsubtype_set _ _\n\ndef pi_unsubtype_set_same {α : Type*} {β : α → Type*} (A : set α) (a : set (Π i : A, β i)) :\n >>[A] a = a :=\nbegin\n rw pi_unsubtype_set,\n rw pi_unsubtype_img,\n change (_ ⁻¹' (_ '' a)) = a,\n -- TODO extract\n convert @set.preimage_image_eq _ _ (@pi_set_to_subtype _ β A A) a (pi_set_to_subtype_bijective rfl.subset).injective,\n ext f i,\n rw pi_set_to_subtype_def',\n change f _ = _,\n congr, refine subtype.eq rfl\nend\n\nlemma pi_subtype_ext {α : Type*} {β : α → Type*} {A : set α}\n{f : Π i, β i} {g : Π i : A, β i} : pi_subtype A f = g ↔ ∀ i : A, f i = g i :=\nby rw function.funext_iff; refl\n\n--lemma pi_subtype_ext' {α : Type*} {β : α → Type*} {A : set α} {f g : Π i, β i} :\n--pi_subtype A f = pi_subtype A g ↔ ∀ i ∈ A, f i = g i := sorry\n\nlemma pi_subtype_subtype {α : Type*} {β : α → Type*} (A : set α) (B : set α) \n (x : Π i : α, β i) :\n pi_subtype (set_to_subtype A B) (pi_subtype A x) = λ (i : set_to_subtype A B), x i := rfl\n\nlemma pi_unsubtype_union_img_def {α : Type*} {β : α → Type*} [∀ i : α, inhabited (β i)]\n (A : set α) (B : set α) (sb : set (Π i : B, β i)) : >>[A] sb = <[A] (>[B] sb) :=\nbegin\n simp_rw [pi_unsubtype_img, pi_subtype_img],\n refine set.subset.antisymm _ _; intros x h,\n { obtain ⟨x', h', h⟩ := h,\n classical,\n let y : Π i, β i := λ i, if h : i ∈ B then x' ⟨i, h⟩\n else if h : i ∈ A then x ⟨i, h⟩ else default,\n refine ⟨y, _, _⟩,\n change pi_subtype B y ∈ sb,\n convert h',\n all_goals {refine pi_subtype_ext.mpr _, rintro ⟨i, hi⟩},\n exact dif_pos hi,\n by_cases hi' : i ∈ B,\n convert dif_pos hi',\n exact (congr_fun h ⟨⟨_, hi⟩, hi'⟩).symm,\n exact (dif_neg hi').trans (dif_pos hi) },\n { obtain ⟨_, h', rfl⟩ := h,\n refine ⟨pi_subtype B _, h', _⟩,\n ext ⟨⟨_, _⟩, _⟩, refl }\nend\n\ndef pi_subtype_subtype_subset {α : Type*} {β : α → Type*} {A : set α} {B : set α}\n (hba : B ⊆ A) (sb : set (Π i : B, β i)) :\n >[B] sb = >[A] (>[set_to_subtype A B] (pi_set_to_subtype A B '' sb)) :=\nbegin\n simp_rw [pi_unsubtype_img, set.preimage_preimage],\n refine set.subset.antisymm _ _; intros x h,\n { refine ⟨pi_subtype B x, h, _⟩, ext ⟨⟨_, _⟩, _⟩, refl },\n { obtain ⟨_, h', h⟩ := h,\n change pi_subtype B x ∈ sb,\n convert h',\n refine pi_subtype_ext.mpr _,\n rintro ⟨_, hi⟩,\n exact (congr_fun h ⟨⟨_, hba hi⟩, _⟩).symm }\nend\n\nlemma pi_unsubtype_union_img_inter {α : Type*} {β : α → Type*} (A : set α) (B : set α)\n (a : set (Π i : A, β i)) (b : set (Π i : B, β i)) :\n >[] (>>[A ∪ B] a ∩ >>[A ∪ B] b) = >[] a ∩ >[] b :=\nbegin\n simp_rw pi_unsubtype_img,\n rw set.preimage_inter,\n refine congr (congr_arg has_inter.inter _) _,\n exact (pi_subtype_subtype_subset (set.subset_union_left A B) _).symm,\n exact (pi_subtype_subtype_subset (set.subset_union_right A B) _).symm\nend\n\nend probability_theory\n", "meta": {"author": "rish987", "repo": "lean-bayes", "sha": "b334cc4f9b4d81551b8513854c44d5ed007c2373", "save_path": "github-repos/lean/rish987-lean-bayes", "path": "github-repos/lean/rish987-lean-bayes/lean-bayes-b334cc4f9b4d81551b8513854c44d5ed007c2373/src/probability_theory/pi_subtype.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958347, "lm_q2_score": 0.0396388400936601, "lm_q1q2_score": 0.019354987426521017}} {"text": "\n\nnamespace ForIn\n\ninductive Step.{u} (α : Type u)\n| done : α → Step α\n| yield : α → Step α\n\nclass Fold.{u, v, w, z} (m : Type w → Type z) [Monad m] (α : outParam (Type u)) (s : Type v) : Type (max v u z (w+1)):=\n(fold {β : Type w} (as : s) (init : β) (f : α → β → m (Step β)) : m β)\n\nexport Fold (fold)\n\nclass FoldMap.{u, w} (m : Type u → Type w) [Monad m] (s : Type u → Type u) : Type (max (u+1) w):=\n(foldMap {α β : Type u} (as : s α) (init : β) (f : α → β → m (Step (α × β))) : m (s α × β))\n\nexport FoldMap (foldMap)\n\n@[inline] instance {m} {α} [Monad m] : Fold m α (List α) :=\n{ fold := fun as init f =>\n let rec @[specialize] loop\n | [], b => pure b\n | a::as, b => do\n let s ← f a b\n (match s with\n | Step.done b => pure b\n | Step.yield b => loop as b)\n loop as init }\n\n@[inline] instance {m} [Monad m] : FoldMap m List :=\n{ foldMap := fun as init f =>\n let rec @[specialize] loop\n | [], rs, b => pure (rs.reverse, b)\n | a::as, rs, b => do\n let s ← f a b\n (match s with\n | Step.done (a, b) => pure ((a :: rs).reverse ++ as, b)\n | Step.yield (a, b) => loop as (a::rs) b)\n loop as [] init }\n\ndef tst1 : IO Nat :=\nfold [1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12, 14] 0 fun a b =>\n if a % 2 == 0 then do\n IO.println (\">> \" ++ toString a ++ \" \" ++ toString b)\n (if b > 20 then return Step.done b\n else return Step.yield (a+b))\n else\n return Step.yield b\n\n#eval tst1\n\ndef tst1' : IO Unit := do\nlet (as, b) ← foldMap [1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12, 14] 0 fun a b =>\n if a % 2 == 0 then do\n IO.println (\">> \" ++ toString a ++ \" \" ++ toString b)\n (if b > 20 then return Step.done (a, b)\n else return Step.yield (a/2, a+b))\n else\n return Step.yield (a, b)\nIO.println as\nIO.println b\npure ()\n\n#eval tst1'\n\ninstance Prod.fold {m α β γ δ} [Monad m] [i₁ : Fold m α γ] [i₂ : Fold m β δ] : Fold m (α × β) (γ × δ) :=\n{ fold := fun s init f =>\n Fold.fold s.1 init fun a x => do\n Fold.fold s.2 (Step.yield x) fun b x =>\n match x with\n | Step.done _ => return Step.done x\n | Step.yield x => do\n let s ← f (a, b) x\n (match s with\n | Step.done _ => return Step.done s\n | Step.yield _ => return Step.yield s) }\n\ndef tst2 (threshold : Nat) : IO Nat :=\nfold ([1, 2, 3, 4, 5, 10], [10, 20, 30, 40, 50]) 0 fun (a, b) s => do\n IO.println (\">> \" ++ toString a ++ \", \" ++ toString b ++ \", \" ++ toString s)\n (if s > threshold then return Step.done s\n else return Step.yield (s+a+b))\n\n#eval tst2 170\n#eval tst2 800\n\nstructure Range :=\n(lower upper : Nat)\n\n@[inline] instance Range.fold {m} [Monad m] : Fold m Nat Range :=\n{ fold := fun s init f =>\n let base := s.lower + s.upper - 2\n let rec @[specialize] loop : Nat → _ → _\n | 0, b => pure b\n | i+1, b =>\n let j := base - i\n if j >= s.upper then return b\n else do\n let s ← f j b\n (match s with\n | Step.done b => return b\n | Step.yield b => loop i b)\n loop (s.upper - 1) init }\n\n@[inline] def range (a : Nat) (b : Option Nat := none) : Range :=\nmatch b with\n| none => ⟨0, a⟩\n| some b => ⟨a, b⟩\n\ninstance : OfNat (Option Nat) :=\n⟨fun n => some n⟩\n\ndef tst3 : IO Nat :=\nfold (range 5 10) 0 fun i s => do\n IO.println (\">> \" ++ toString i)\n return Step.yield (s+i)\n\n#eval tst3\n\ntheorem zeroLtOfLt : {a b : Nat} → a < b → 0 < b\n| 0, _, h => h\n| a+1, b, h =>\n have a < b from Nat.ltTrans (Nat.ltSuccSelf _) h\n zeroLtOfLt this\n\n@[inline] instance {m} {α} [Monad m] : Fold m α (Array α) :=\n{ fold := fun as init f =>\n let rec @[specialize] loop : (i : Nat) → i ≤ as.size → _\n | 0, h, b => pure b\n | i+1, h, b =>\n have h' : i < as.size from Nat.ltOfLtOfLe (Nat.ltSuccSelf i) h\n have as.size - 1 < as.size from Nat.subLt (zeroLtOfLt h') (decide! (0 < 1))\n have as.size - 1 - i < as.size from Nat.ltOfLeOfLt (Nat.subLe (as.size - 1) i) this; do\n let s ← f (as.get ⟨as.size - 1 - i, this⟩) b\n (match s with\n | Step.done b => pure b\n | Step.yield b => loop i (Nat.leOfLt h') b)\n loop as.size (Nat.leRefl _) init }\n\n-- set_option trace.compiler.ir.result true\n\ndef tst4 : IO Nat :=\nfold (#[1, 2, 3, 4, 5] : Array Nat) 0 fun a b => do\n IO.println (\">> \" ++ toString a ++ \" \" ++ toString b)\n return Step.yield (a+b)\n\n#eval tst4\n\nend ForIn\n", "meta": {"author": "leanprover", "repo": "lean4", "sha": "742d053a97bdd109a41a921facd1cd6a55e89bc7", "save_path": "github-repos/lean/leanprover-lean4", "path": "github-repos/lean/leanprover-lean4/lean4-742d053a97bdd109a41a921facd1cd6a55e89bc7/tests/playground/forIn.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40733340004593027, "lm_q2_score": 0.04742587267267827, "lm_q1q2_score": 0.01931814196590741}} {"text": "/-\nCopyright (c) 2022 Mario Carneiro. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Mario Carneiro\n-/\n\nnamespace Option\n\n/-!\n# Bootstrapping theorems for Option\n\nThese are theorems used in the definitions of `Std.Data.List.Basic`.\nNew theorems should be added to `Std.Data.Option.Lemmas` if they are not needed by the bootstrap.\n-/\n\n@[simp] theorem getD_none : getD none a = a := rfl\n@[simp] theorem getD_some : getD (some a) b = a := rfl\n\n@[simp] theorem map_none' (f : α → β) : none.map f = none := rfl\n@[simp] theorem map_some' (a) (f : α → β) : (some a).map f = some (f a) := rfl\n\n@[simp] theorem none_bind (f : α → Option β) : none.bind f = none := rfl\n@[simp] theorem some_bind (a) (f : α → Option β) : (some a).bind f = f a := rfl\n", "meta": {"author": "leanprover", "repo": "std4", "sha": "5507f9d8409f93b984ce04eccf4914d534e6fca2", "save_path": "github-repos/lean/leanprover-std4", "path": "github-repos/lean/leanprover-std4/std4-5507f9d8409f93b984ce04eccf4914d534e6fca2/Std/Data/Option/Init/Lemmas.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.41869690935568665, "lm_q2_score": 0.046033903544407576, "lm_q1q2_score": 0.01927425313962124}} {"text": "/-\nBinaryTools: Utilities for displaying and manipulating Binary data.\n-/\n\n/-\nSimplification rules for ensuring type safety of Blake3Hash\n-/\n@[simp] theorem ByteArray.size_empty : ByteArray.empty.size = 0 :=\nrfl\n\n@[simp] theorem ByteArray.size_push (B : ByteArray) (a : UInt8) : (B.push a).size = B.size + 1 :=\nby { cases B; simp only [ByteArray.push, ByteArray.size, Array.size_push] }\n\n@[simp] theorem List.to_ByteArray_size : (L : List UInt8) → L.toByteArray.size = L.length\n| [] => rfl\n| a::l => by simp [List.toByteArray, to_ByteArray_loop_size]\nwhere to_ByteArray_loop_size :\n (L : List UInt8) → (B : ByteArray) → (List.toByteArray.loop L B).size = L.length + B.size\n| [], B => by simp [List.toByteArray.loop]\n| a::l, B => by\n simp [List.toByteArray.loop, to_ByteArray_loop_size]\n rw [Nat.add_succ, Nat.succ_add]\n\nuniverse u\nuniverse v\n\n/-\nType class for default conversion between two types.\n-/\nclass Into (Target: Type v) (Source: Type u) :=\n (into: Source → Target)\n\nexport Into (into)\n\ninstance (A: Type u) : Into A A := ⟨id⟩\n\ndef String.toByteArray (s : String) : ByteArray :=\n (List.map\n (fun c : Char => c.toNat.toUInt8) s.toList).toByteArray\n\ninstance : Into ByteArray String := {\n into := String.toByteArray\n}\n\nnamespace Alphabet\ndef base2: String := \"01\"\ndef base8: String := \"01234567\"\ndef base10: String := \"0123456789\"\ndef base16: String := \"0123456789abcdef\"\ndef base16upper: String := \"0123456789ABCDEF\"\ndef base32: String := \"abcdefghijklmnopqrstuvwxyz234567\"\ndef base32upper: String := \"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567\"\ndef base32hex : String := \"0123456789abcdefghijklmnopqrstuv\"\ndef base32hexupper : String := \"0123456789ABCDEFGHIJKLMNOPQRSTUV\"\ndef base32z : String := \"ybndrfg8ejkmcpqxot1uwisza345h769\"\ndef base36 : String := \"0123456789abcdefghijklmnopqrstuvwxyz\"\ndef base36upper : String := \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\ndef base58flickr : String := \n \"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ\"\ndef base58btc : String := \n \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\"\ndef base64 : String := \n \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\"\ndef base64url : String := \n \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_\"\n\nend Alphabet\n\n/-\nEncode a ByteArray as a base64 String\n-/\ndef toBase64 {I: Type u} [Into ByteArray I] (input : I) (pad: Bool := true) : String := do\n let input : ByteArray := Into.into input\n let x := ByteArray.size input % 3\n let mut bytes := input\n let mut str := \"\"\n if x == 1 then bytes := bytes.append [0x00, 0x00].toByteArray\n if x == 2 then bytes := bytes.append [0x00].toByteArray\n for i in [:(bytes.size / 3)] do\n let b0 := bytes.data[3 * i]\n let b1 := bytes.data[3 * i + 1]\n let b2 := bytes.data[3 * i + 2]\n let s0 := b0.shiftRight 2\n let s1 := UInt8.xor\n ((b0.land 0b00000011).shiftLeft 4) \n ((b1.land 0b11110000).shiftRight 4)\n let s2 := UInt8.xor\n ((b1.land 0b00001111).shiftLeft 2) \n ((b2.land 0b11000000).shiftRight 6)\n let s3 := b2.land 0b00111111\n str := str.push (Alphabet.base64.get s0.toNat)\n str := str.push (Alphabet.base64.get s1.toNat)\n str := str.push (Alphabet.base64.get s2.toNat)\n str := str.push (Alphabet.base64.get s3.toNat)\n if pad then do\n if x == 1 then \n str := str.set (str.length - 1) '='\n str := str.set (str.length - 2) '='\n if x == 2 then \n str := str.set (str.length - 1) '='\n return str\n else \n if x == 1 then str := str.dropRight 2\n if x == 2 then str := str.dropRight 1\n return str\n", "meta": {"author": "Anderssorby", "repo": "Neptune.lean", "sha": "378317a3e4383c7874d01907efb84b1e39180cf3", "save_path": "github-repos/lean/Anderssorby-Neptune.lean", "path": "github-repos/lean/Anderssorby-Neptune.lean/Neptune.lean-378317a3e4383c7874d01907efb84b1e39180cf3/src/BinaryTools.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4378234991142018, "lm_q2_score": 0.04401864813854272, "lm_q1q2_score": 0.01927239855429362}} {"text": "namespace util.data.nonempty_list\n\nuniverse u\nvariable {α : Type u}\n\n-- structure nonempty_list (α : Type u) :=\n-- (head : α)\n-- (tail : list α)\n\ninductive nonempty_list (α : Type u)\n| singleton : α → nonempty_list\n| cons : α → nonempty_list → nonempty_list\n\nnamespace nonempty_list\n\n-- def singleton : α → nonempty_list α := λ x, { head := x, tail := [] }\n\n@[reducible] def head : nonempty_list α → α\n| (nonempty_list.singleton x) := x\n| (nonempty_list.cons x _) := x\n\n@[reducible] def to_list : nonempty_list α → list α\n| (singleton x) := [x]\n| (cons x xs) := x :: to_list xs\n\n@[reducible] def tail : nonempty_list α → list α\n| (singleton _) := []\n| (cons _ xs) := to_list xs\n\n-- def append (xs : nonempty_list α) (ys : nonempty_list α) : nonempty_list α := {\n-- head := xs.head,\n-- tail := xs.tail ++ ys.to_list\n-- }\n\ndef append : nonempty_list α → nonempty_list α → nonempty_list α\n| (singleton x) ys := cons x ys\n| (cons x xs) ys := cons x (append xs ys)\n\ninstance : has_append (nonempty_list α) := ⟨ append ⟩\n\n-- lemma append_assoc : Π (xs ys zs : nonempty_list α), append (append xs ys) zs = append xs (append ys zs) :=\n-- begin\n-- intros,\n-- unfold append,\n-- simp\n-- end\n\n@[simp] lemma singleton_append (x : α) (xs : nonempty_list α) : singleton x ++ xs = cons x xs :=\nrfl\n\n@[simp] lemma cons_append (x : α) (xs : nonempty_list α) (ys : nonempty_list α) : cons x xs ++ ys = cons x (xs ++ ys) :=\nrfl\n\nlemma append_assoc (xs ys zs : nonempty_list α) : (xs ++ ys) ++ zs = xs ++ (ys ++ zs) :=\nbegin\n induction xs,\n simp *,\n simp *\nend\n\nend nonempty_list\n\nend util.data.nonempty_list", "meta": {"author": "semorrison", "repo": "lean-monoidal-categories", "sha": "81f43e1e0d623a96695aa8938951d7422d6d7ba6", "save_path": "github-repos/lean/semorrison-lean-monoidal-categories", "path": "github-repos/lean/semorrison-lean-monoidal-categories/lean-monoidal-categories-81f43e1e0d623a96695aa8938951d7422d6d7ba6/src/monoidal_categories/util/data/nonempty_list.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45326184801538616, "lm_q2_score": 0.04208772521219692, "lm_q1q2_score": 0.019076760108444137}} {"text": "/-\nCopyright (c) 2021 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Sebastian Ullrich, Leonardo de Moura\n-/\nprelude\nimport Init.SimpLemmas\nimport Init.Control.Except\nimport Init.Control.StateRef\n\nopen Function\n\n@[simp] theorem monadLift_self [Monad m] (x : m α) : monadLift x = x :=\n rfl\n\nclass LawfulFunctor (f : Type u → Type v) [Functor f] : Prop where\n map_const : (Functor.mapConst : α → f β → f α) = Functor.map ∘ const β\n id_map (x : f α) : id <$> x = x\n comp_map (g : α → β) (h : β → γ) (x : f α) : (h ∘ g) <$> x = h <$> g <$> x\n\nexport LawfulFunctor (map_const id_map comp_map)\n\nattribute [simp] id_map\n\n@[simp] theorem id_map' [Functor m] [LawfulFunctor m] (x : m α) : (fun a => a) <$> x = x :=\n id_map x\n\nclass LawfulApplicative (f : Type u → Type v) [Applicative f] extends LawfulFunctor f : Prop where\n seqLeft_eq (x : f α) (y : f β) : x <* y = const β <$> x <*> y\n seqRight_eq (x : f α) (y : f β) : x *> y = const α id <$> x <*> y\n pure_seq (g : α → β) (x : f α) : pure g <*> x = g <$> x\n map_pure (g : α → β) (x : α) : g <$> (pure x : f α) = pure (g x)\n seq_pure {α β : Type u} (g : f (α → β)) (x : α) : g <*> pure x = (fun h => h x) <$> g\n seq_assoc {α β γ : Type u} (x : f α) (g : f (α → β)) (h : f (β → γ)) : h <*> (g <*> x) = ((@comp α β γ) <$> h) <*> g <*> x\n comp_map g h x := (by\n repeat rw [← pure_seq]\n simp [seq_assoc, map_pure, seq_pure])\n\nexport LawfulApplicative (seqLeft_eq seqRight_eq pure_seq map_pure seq_pure seq_assoc)\n\nattribute [simp] map_pure seq_pure\n\n@[simp] theorem pure_id_seq [Applicative f] [LawfulApplicative f] (x : f α) : pure id <*> x = x := by\n simp [pure_seq]\n\nclass LawfulMonad (m : Type u → Type v) [Monad m] extends LawfulApplicative m : Prop where\n bind_pure_comp (f : α → β) (x : m α) : x >>= (fun a => pure (f a)) = f <$> x\n bind_map {α β : Type u} (f : m (α → β)) (x : m α) : f >>= (. <$> x) = f <*> x\n pure_bind (x : α) (f : α → m β) : pure x >>= f = f x\n bind_assoc (x : m α) (f : α → m β) (g : β → m γ) : x >>= f >>= g = x >>= fun x => f x >>= g\n map_pure g x := (by rw [← bind_pure_comp, pure_bind])\n seq_pure g x := (by rw [← bind_map]; simp [map_pure, bind_pure_comp])\n seq_assoc x g h := (by simp [← bind_pure_comp, ← bind_map, bind_assoc, pure_bind])\n\nexport LawfulMonad (bind_pure_comp bind_map pure_bind bind_assoc)\nattribute [simp] pure_bind bind_assoc\n\n@[simp] theorem bind_pure [Monad m] [LawfulMonad m] (x : m α) : x >>= pure = x := by\n show x >>= (fun a => pure (id a)) = x\n rw [bind_pure_comp, id_map]\n\ntheorem map_eq_pure_bind [Monad m] [LawfulMonad m] (f : α → β) (x : m α) : f <$> x = x >>= fun a => pure (f a) := by\n rw [← bind_pure_comp]\n\ntheorem seq_eq_bind_map {α β : Type u} [Monad m] [LawfulMonad m] (f : m (α → β)) (x : m α) : f <*> x = f >>= (. <$> x) := by\n rw [← bind_map]\n\ntheorem bind_congr [Bind m] {x : m α} {f g : α → m β} (h : ∀ a, f a = g a) : x >>= f = x >>= g := by\n simp [funext h]\n\n@[simp] theorem bind_pure_unit [Monad m] [LawfulMonad m] {x : m PUnit} : (x >>= fun _ => pure ⟨⟩) = x := by\n rw [bind_pure]\n\ntheorem map_congr [Functor m] {x : m α} {f g : α → β} (h : ∀ a, f a = g a) : (f <$> x : m β) = g <$> x := by\n simp [funext h]\n\ntheorem seq_eq_bind {α β : Type u} [Monad m] [LawfulMonad m] (mf : m (α → β)) (x : m α) : mf <*> x = mf >>= fun f => f <$> x := by\n rw [bind_map]\n\ntheorem seqRight_eq_bind [Monad m] [LawfulMonad m] (x : m α) (y : m β) : x *> y = x >>= fun _ => y := by\n rw [seqRight_eq]\n simp [map_eq_pure_bind, seq_eq_bind_map, const]\n\ntheorem seqLeft_eq_bind [Monad m] [LawfulMonad m] (x : m α) (y : m β) : x <* y = x >>= fun a => y >>= fun _ => pure a := by\n rw [seqLeft_eq]; simp [map_eq_pure_bind, seq_eq_bind_map]\n\n/-! # Id -/\n\nnamespace Id\n\n@[simp] theorem map_eq (x : Id α) (f : α → β) : f <$> x = f x := rfl\n@[simp] theorem bind_eq (x : Id α) (f : α → id β) : x >>= f = f x := rfl\n@[simp] theorem pure_eq (a : α) : (pure a : Id α) = a := rfl\n\ninstance : LawfulMonad Id := by\n refine' { .. } <;> intros <;> rfl\n\nend Id\n\n/-! # ExceptT -/\n\nnamespace ExceptT\n\ntheorem ext [Monad m] {x y : ExceptT ε m α} (h : x.run = y.run) : x = y := by\n simp [run] at h\n assumption\n\n@[simp] theorem run_pure [Monad m] (x : α) : run (pure x : ExceptT ε m α) = pure (Except.ok x) := rfl\n\n@[simp] theorem run_lift [Monad.{u, v} m] (x : m α) : run (ExceptT.lift x : ExceptT ε m α) = (Except.ok <$> x : m (Except ε α)) := rfl\n\n@[simp] theorem run_throw [Monad m] : run (throw e : ExceptT ε m β) = pure (Except.error e) := rfl\n\n@[simp] theorem run_bind_lift [Monad m] [LawfulMonad m] (x : m α) (f : α → ExceptT ε m β) : run (ExceptT.lift x >>= f : ExceptT ε m β) = x >>= fun a => run (f a) := by\n simp[ExceptT.run, ExceptT.lift, bind, ExceptT.bind, ExceptT.mk, ExceptT.bindCont, map_eq_pure_bind]\n\n@[simp] theorem bind_throw [Monad m] [LawfulMonad m] (f : α → ExceptT ε m β) : (throw e >>= f) = throw e := by\n simp [throw, throwThe, MonadExceptOf.throw, bind, ExceptT.bind, ExceptT.bindCont, ExceptT.mk]\n\ntheorem run_bind [Monad m] (x : ExceptT ε m α)\n : run (x >>= f : ExceptT ε m β)\n =\n run x >>= fun\n | Except.ok x => run (f x)\n | Except.error e => pure (Except.error e) :=\n rfl\n\n@[simp] theorem lift_pure [Monad m] [LawfulMonad m] (a : α) : ExceptT.lift (pure a) = (pure a : ExceptT ε m α) := by\n simp [ExceptT.lift, pure, ExceptT.pure]\n\n@[simp] theorem run_map [Monad m] [LawfulMonad m] (f : α → β) (x : ExceptT ε m α)\n : (f <$> x).run = Except.map f <$> x.run := by\n simp [Functor.map, ExceptT.map, map_eq_pure_bind]\n apply bind_congr\n intro a; cases a <;> simp [Except.map]\n\nprotected theorem seq_eq {α β ε : Type u} [Monad m] (mf : ExceptT ε m (α → β)) (x : ExceptT ε m α) : mf <*> x = mf >>= fun f => f <$> x :=\n rfl\n\nprotected theorem bind_pure_comp [Monad m] [LawfulMonad m] (f : α → β) (x : ExceptT ε m α) : x >>= pure ∘ f = f <$> x := by\n intros; rfl\n\nprotected theorem seqLeft_eq {α β ε : Type u} {m : Type u → Type v} [Monad m] [LawfulMonad m] (x : ExceptT ε m α) (y : ExceptT ε m β) : x <* y = const β <$> x <*> y := by\n show (x >>= fun a => y >>= fun _ => pure a) = (const (α := α) β <$> x) >>= fun f => f <$> y\n rw [← ExceptT.bind_pure_comp]\n apply ext\n simp [run_bind]\n apply bind_congr\n intro\n | Except.error _ => simp\n | Except.ok _ =>\n simp [map_eq_pure_bind]; apply bind_congr; intro b;\n cases b <;> simp [comp, Except.map, const]\n\nprotected theorem seqRight_eq [Monad m] [LawfulMonad m] (x : ExceptT ε m α) (y : ExceptT ε m β) : x *> y = const α id <$> x <*> y := by\n show (x >>= fun _ => y) = (const α id <$> x) >>= fun f => f <$> y\n rw [← ExceptT.bind_pure_comp]\n apply ext\n simp [run_bind]\n apply bind_congr\n intro a; cases a <;> simp\n\ninstance [Monad m] [LawfulMonad m] : LawfulMonad (ExceptT ε m) where\n id_map := by intros; apply ext; simp\n map_const := by intros; rfl\n seqLeft_eq := ExceptT.seqLeft_eq\n seqRight_eq := ExceptT.seqRight_eq\n pure_seq := by intros; apply ext; simp [ExceptT.seq_eq, run_bind]\n bind_pure_comp := ExceptT.bind_pure_comp\n bind_map := by intros; rfl\n pure_bind := by intros; apply ext; simp [run_bind]\n bind_assoc := by intros; apply ext; simp [run_bind]; apply bind_congr; intro a; cases a <;> simp\n\nend ExceptT\n\n/-! # ReaderT -/\n\nnamespace ReaderT\n\ntheorem ext {x y : ReaderT ρ m α} (h : ∀ ctx, x.run ctx = y.run ctx) : x = y := by\n simp [run] at h\n exact funext h\n\n@[simp] theorem run_pure [Monad m] (a : α) (ctx : ρ) : (pure a : ReaderT ρ m α).run ctx = pure a := rfl\n\n@[simp] theorem run_bind [Monad m] (x : ReaderT ρ m α) (f : α → ReaderT ρ m β) (ctx : ρ)\n : (x >>= f).run ctx = x.run ctx >>= λ a => (f a).run ctx := rfl\n\n@[simp] theorem run_mapConst [Monad m] (a : α) (x : ReaderT ρ m β) (ctx : ρ)\n : (Functor.mapConst a x).run ctx = Functor.mapConst a (x.run ctx) := rfl\n\n@[simp] theorem run_map [Monad m] (f : α → β) (x : ReaderT ρ m α) (ctx : ρ)\n : (f <$> x).run ctx = f <$> x.run ctx := rfl\n\n@[simp] theorem run_monadLift [MonadLiftT n m] (x : n α) (ctx : ρ)\n : (monadLift x : ReaderT ρ m α).run ctx = (monadLift x : m α) := rfl\n\n@[simp] theorem run_monadMap [MonadFunctor n m] (f : {β : Type u} → n β → n β) (x : ReaderT ρ m α) (ctx : ρ)\n : (monadMap @f x : ReaderT ρ m α).run ctx = monadMap @f (x.run ctx) := rfl\n\n@[simp] theorem run_read [Monad m] (ctx : ρ) : (ReaderT.read : ReaderT ρ m ρ).run ctx = pure ctx := rfl\n\n@[simp] theorem run_seq {α β : Type u} [Monad m] (f : ReaderT ρ m (α → β)) (x : ReaderT ρ m α) (ctx : ρ)\n : (f <*> x).run ctx = (f.run ctx <*> x.run ctx) := rfl\n\n@[simp] theorem run_seqRight [Monad m] (x : ReaderT ρ m α) (y : ReaderT ρ m β) (ctx : ρ)\n : (x *> y).run ctx = (x.run ctx *> y.run ctx) := rfl\n\n@[simp] theorem run_seqLeft [Monad m] (x : ReaderT ρ m α) (y : ReaderT ρ m β) (ctx : ρ)\n : (x <* y).run ctx = (x.run ctx <* y.run ctx) := rfl\n\ninstance [Monad m] [LawfulFunctor m] : LawfulFunctor (ReaderT ρ m) where\n id_map := by intros; apply ext; simp\n map_const := by intros; funext a b; apply ext; intros; simp [map_const]\n comp_map := by intros; apply ext; intros; simp [comp_map]\n\ninstance [Monad m] [LawfulApplicative m] : LawfulApplicative (ReaderT ρ m) where\n seqLeft_eq := by intros; apply ext; intros; simp [seqLeft_eq]\n seqRight_eq := by intros; apply ext; intros; simp [seqRight_eq]\n pure_seq := by intros; apply ext; intros; simp [pure_seq]\n map_pure := by intros; apply ext; intros; simp [map_pure]\n seq_pure := by intros; apply ext; intros; simp [seq_pure]\n seq_assoc := by intros; apply ext; intros; simp [seq_assoc]\n\ninstance [Monad m] [LawfulMonad m] : LawfulMonad (ReaderT ρ m) where\n bind_pure_comp := by intros; apply ext; intros; simp [LawfulMonad.bind_pure_comp]\n bind_map := by intros; apply ext; intros; simp [bind_map]\n pure_bind := by intros; apply ext; intros; simp\n bind_assoc := by intros; apply ext; intros; simp\n\nend ReaderT\n\n/-! # StateRefT -/\n\ninstance [Monad m] [LawfulMonad m] : LawfulMonad (StateRefT' ω σ m) :=\n inferInstanceAs (LawfulMonad (ReaderT (ST.Ref ω σ) m))\n\n/-! # StateT -/\n\nnamespace StateT\n\ntheorem ext {x y : StateT σ m α} (h : ∀ s, x.run s = y.run s) : x = y :=\n funext h\n\n@[simp] theorem run'_eq [Monad m] (x : StateT σ m α) (s : σ) : run' x s = (·.1) <$> run x s :=\n rfl\n\n@[simp] theorem run_pure [Monad m] (a : α) (s : σ) : (pure a : StateT σ m α).run s = pure (a, s) := rfl\n\n@[simp] theorem run_bind [Monad m] (x : StateT σ m α) (f : α → StateT σ m β) (s : σ)\n : (x >>= f).run s = x.run s >>= λ p => (f p.1).run p.2 := by\n simp [bind, StateT.bind, run]\n\n@[simp] theorem run_map {α β σ : Type u} [Monad m] [LawfulMonad m] (f : α → β) (x : StateT σ m α) (s : σ) : (f <$> x).run s = (fun (p : α × σ) => (f p.1, p.2)) <$> x.run s := by\n simp [Functor.map, StateT.map, run, map_eq_pure_bind]\n\n@[simp] theorem run_get [Monad m] (s : σ) : (get : StateT σ m σ).run s = pure (s, s) := rfl\n\n@[simp] theorem run_set [Monad m] (s s' : σ) : (set s' : StateT σ m PUnit).run s = pure (⟨⟩, s') := rfl\n\n@[simp] theorem run_modify [Monad m] (f : σ → σ) (s : σ) : (modify f : StateT σ m PUnit).run s = pure (⟨⟩, f s) := rfl\n\n@[simp] theorem run_modifyGet [Monad m] (f : σ → α × σ) (s : σ) : (modifyGet f : StateT σ m α).run s = pure ((f s).1, (f s).2) := by\n simp [modifyGet, MonadStateOf.modifyGet, StateT.modifyGet, run]\n\n@[simp] theorem run_lift {α σ : Type u} [Monad m] (x : m α) (s : σ) : (StateT.lift x : StateT σ m α).run s = x >>= fun a => pure (a, s) := rfl\n\n@[simp] theorem run_bind_lift {α σ : Type u} [Monad m] [LawfulMonad m] (x : m α) (f : α → StateT σ m β) (s : σ) : (StateT.lift x >>= f).run s = x >>= fun a => (f a).run s := by\n simp [StateT.lift, StateT.run, bind, StateT.bind]\n\n@[simp] theorem run_monadLift {α σ : Type u} [Monad m] [MonadLiftT n m] (x : n α) (s : σ) : (monadLift x : StateT σ m α).run s = (monadLift x : m α) >>= fun a => pure (a, s) := rfl\n\n@[simp] theorem run_monadMap [Monad m] [MonadFunctor n m] (f : {β : Type u} → n β → n β) (x : StateT σ m α) (s : σ)\n : (monadMap @f x : StateT σ m α).run s = monadMap @f (x.run s) := rfl\n\n@[simp] theorem run_seq {α β σ : Type u} [Monad m] [LawfulMonad m] (f : StateT σ m (α → β)) (x : StateT σ m α) (s : σ) : (f <*> x).run s = (f.run s >>= fun fs => (fun (p : α × σ) => (fs.1 p.1, p.2)) <$> x.run fs.2) := by\n show (f >>= fun g => g <$> x).run s = _\n simp\n\n@[simp] theorem run_seqRight [Monad m] [LawfulMonad m] (x : StateT σ m α) (y : StateT σ m β) (s : σ) : (x *> y).run s = (x.run s >>= fun p => y.run p.2) := by\n show (x >>= fun _ => y).run s = _\n simp\n\n@[simp] theorem run_seqLeft {α β σ : Type u} [Monad m] [LawfulMonad m] (x : StateT σ m α) (y : StateT σ m β) (s : σ) : (x <* y).run s = (x.run s >>= fun p => y.run p.2 >>= fun p' => pure (p.1, p'.2)) := by\n show (x >>= fun a => y >>= fun _ => pure a).run s = _\n simp\n\ntheorem seqRight_eq [Monad m] [LawfulMonad m] (x : StateT σ m α) (y : StateT σ m β) : x *> y = const α id <$> x <*> y := by\n apply ext; intro s\n simp [map_eq_pure_bind, const]\n apply bind_congr; intro p; cases p\n simp [Prod.eta]\n\ntheorem seqLeft_eq [Monad m] [LawfulMonad m] (x : StateT σ m α) (y : StateT σ m β) : x <* y = const β <$> x <*> y := by\n apply ext; intro s\n simp [map_eq_pure_bind]\n\ninstance [Monad m] [LawfulMonad m] : LawfulMonad (StateT σ m) where\n id_map := by intros; apply ext; intros; simp[Prod.eta]\n map_const := by intros; rfl\n seqLeft_eq := seqLeft_eq\n seqRight_eq := seqRight_eq\n pure_seq := by intros; apply ext; intros; simp\n bind_pure_comp := by intros; apply ext; intros; simp; apply LawfulMonad.bind_pure_comp\n bind_map := by intros; rfl\n pure_bind := by intros; apply ext; intros; simp\n bind_assoc := by intros; apply ext; intros; simp\n\nend StateT\n", "meta": {"author": "leanprover", "repo": "lean4", "sha": "742d053a97bdd109a41a921facd1cd6a55e89bc7", "save_path": "github-repos/lean/leanprover-lean4", "path": "github-repos/lean/leanprover-lean4/lean4-742d053a97bdd109a41a921facd1cd6a55e89bc7/src/Init/Control/Lawful.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4073334000459302, "lm_q2_score": 0.04672495613712898, "lm_q1q2_score": 0.0190326352503337}} {"text": "/-\nCopyright (c) 2022 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Leonardo de Moura\n-/\nimport Lean.Meta.InferType\n\nnamespace Lean.Compiler\n\nscoped notation:max \"◾\" => lcErased\n\nnamespace LCNF\n\ndef erasedExpr := mkConst ``lcErased\n\ndef _root_.Lean.Expr.isErased (e : Expr) :=\n e.isAppOf ``lcErased\n\ndef isPropFormerTypeQuick : Expr → Bool\n | .forallE _ _ b _ => isPropFormerTypeQuick b\n | .sort .zero => true\n | _ => false\n\n/--\nReturn true iff `type` is `Prop` or `As → Prop`.\n-/\npartial def isPropFormerType (type : Expr) : MetaM Bool := do\n match isPropFormerTypeQuick type with\n | true => return true\n | false => go type #[]\nwhere\n go (type : Expr) (xs : Array Expr) : MetaM Bool := do\n match type with\n | .sort .zero => return true\n | .forallE n d b c => Meta.withLocalDecl n c (d.instantiateRev xs) fun x => go b (xs.push x)\n | _ =>\n let type ← Meta.whnfD (type.instantiateRev xs)\n match type with\n | .sort .zero => return true\n | .forallE .. => go type #[]\n | _ => return false\n\n/--\nReturn true iff `e : Prop` or `e : As → Prop`.\n-/\ndef isPropFormer (e : Expr) : MetaM Bool := do\n isPropFormerType (← Meta.inferType e)\n\n/-!\nThe code generator uses a format based on A-normal form.\nThis normal form uses many let-expressions and it is very convenient for\napplying compiler transformations. However, it creates a few issues\nin a dependently typed programming language.\n\n- Many casts are needed.\n- It is too expensive to ensure we are not losing typeability when creating join points\n and simplifying let-values\n- It may not be possible to create a join point because the resulting expression is\n not type correct. For example, suppose we are trying to create a join point for\n making the following `match` terminal.\n ```\n let x := match a with | true => b | false => c;\n k[x]\n ```\n and want to transform this code into\n ```\n let jp := fun x => k[x]\n match a with\n | true => jp b\n | false => jp c\n ```\n where `jp` is a new join point (i.e., a local function that is always fully applied and\n tail recursive). In many examples in the Lean code-base, we have to skip this transformation\n because it produces a type-incorrect term. Recall that types/propositions in `k[x]` may rely on\n the fact that `x` is definitionally equal to `match a with ...` before the creation of\n the join point.\n\nThus, in the first code generator pass, we convert types into a `LCNFType` (Lean Compiler Normal Form Type).\nThe method `toLCNFType` produces a type with the following properties:\n\n- All constants occurring in the result type are inductive datatypes.\n- The arguments of type formers are type formers, or `◾`. We use `◾` to denote erased information.\n- All type definitions are expanded. If reduction gets stuck, it is replaced with `◾`.\n\nRemark: you can view `◾` occurring in a type position as the \"any type\".\nRemark: in our runtime, `◾` is represented as `box(0)`.\n\nThe goal is to preserve as much information as possible and avoid the problems described above.\nThen, we don't have `let x := v; ...` in LCNF code when `x` is a type former.\nIf the user provides a `let x := v; ...` where x is a type former, we can always expand it when\nconverting into LCNF.\nThus, given a `let x := v, ...` in occurring in LCNF, we know `x` cannot occur in any type since it is\nnot a type former.\n\nWe try to preserve type information because they unlock new optimizations, and we can type check\nthe result produced by each code generator step.\n\n\nBelow, we provide some example programs and their erased variants:\n-- 1. Source type: `f: (n: Nat) -> (tupleN Nat n)`.\n LCNF type: `f: Nat -> ◾`.\n We convert the return type `(tupleN Nat n) to `◾`, since we cannot reduce\n `(tupleN Nat n)` to a term of the form `(InductiveTy ...)`.\n\n-- 2. Source type: `f: (n: Nat) (fin: Fin n) -> (tupleN Nat fin)`.\n LCNF type: `f: Nat -> Fin ◾ -> ◾`.\n Since `(Fin n)` has dependency on `n`, we erase the `n` to get the\n type `(Fin ◾)`.\n-/\n\nopen Meta in\n/--\nConvert a Lean type into a LCNF type used by the code generator.\n-/\npartial def toLCNFType (type : Expr) : MetaM Expr := do\n if (← isProp type) then\n return erasedExpr\n let type ← whnfEta type\n match type with\n | .sort u => return .sort u\n | .const .. => visitApp type #[]\n | .lam n d b bi =>\n withLocalDecl n bi d fun x => do\n let d ← toLCNFType d\n let b ← toLCNFType (b.instantiate1 x)\n if b.isErased then\n return b\n else\n return Expr.lam n d (b.abstract #[x]) bi\n | .forallE .. => visitForall type #[]\n | .app .. => type.withApp visitApp\n | .fvar .. => visitApp type #[]\n | _ => return erasedExpr\nwhere\n whnfEta (type : Expr) : MetaM Expr := do\n let type ← whnf type\n let type' := type.eta\n if type' != type then\n whnfEta type'\n else\n return type\n\n visitForall (e : Expr) (xs : Array Expr) : MetaM Expr := do\n match e with\n | .forallE n d b bi =>\n let d := d.instantiateRev xs\n withLocalDecl n bi d fun x => do\n let d := (← toLCNFType d).abstract xs\n return .forallE n d (← visitForall b (xs.push x)) bi\n | _ =>\n let e ← toLCNFType (e.instantiateRev xs)\n return e.abstract xs\n\n visitApp (f : Expr) (args : Array Expr) := do\n let fNew ← match f with\n | .const declName us =>\n let .inductInfo _ ← getConstInfo declName | return erasedExpr\n pure <| .const declName us\n | .fvar .. => pure f\n | _ => return erasedExpr\n let mut result := fNew\n for arg in args do\n if (← isProp arg) then\n result := mkApp result erasedExpr\n else if (← isPropFormer arg) then\n result := mkApp result erasedExpr\n else if (← isTypeFormer arg) then\n result := mkApp result (← toLCNFType arg)\n else\n result := mkApp result erasedExpr\n return result\n\nmutual\n\npartial def joinTypes (a b : Expr) : Expr :=\n joinTypes? a b |>.getD erasedExpr\n\npartial def joinTypes? (a b : Expr) : Option Expr := do\n if a.isErased || b.isErased then\n return erasedExpr -- See comment at `compatibleTypes`.\n else if a == b then\n return a\n else\n let a' := a.headBeta\n let b' := b.headBeta\n if a != a' || b != b' then\n joinTypes? a' b'\n else\n match a, b with\n | .mdata _ a, b => joinTypes? a b\n | a, .mdata _ b => joinTypes? a b\n | .app f a, .app g b =>\n (do return .app (← joinTypes? f g) (← joinTypes? a b))\n <|>\n return erasedExpr\n | .forallE n d₁ b₁ _, .forallE _ d₂ b₂ _ =>\n (do return .forallE n (← joinTypes? d₁ d₂) (joinTypes b₁ b₂) .default)\n <|>\n return erasedExpr\n | .lam n d₁ b₁ _, .lam _ d₂ b₂ _ =>\n (do return .lam n (← joinTypes? d₁ d₂) (joinTypes b₁ b₂) .default)\n <|>\n return erasedExpr\n | _, _ => return erasedExpr\n\nend\n\n/--\nReturn `true` if `type` is a LCNF type former type.\n\nRemark: This is faster than `Lean.Meta.isTypeFormer`, as this\n assumes that the input `type` is an LCNF type.\n-/\npartial def isTypeFormerType (type : Expr) : Bool :=\n match type.headBeta with\n | .sort .. => true\n | .forallE _ _ b _ => isTypeFormerType b\n | _ => false\n\n/--\nGiven a LCNF `type` of the form `forall (a_1 : A_1) ... (a_n : A_n), B[a_1, ..., a_n]` and `p_1 : A_1, ... p_n : A_n`,\nreturn `B[p_1, ..., p_n]`.\n\nRemark: similar to `Meta.instantiateForall`, buf for LCNF types.\n-/\ndef instantiateForall (type : Expr) (ps : Array Expr) : CoreM Expr :=\n go 0 type\nwhere\n go (i : Nat) (type : Expr) : CoreM Expr :=\n if h : i < ps.size then\n if let .forallE _ _ b _ := type.headBeta then\n go (i+1) (b.instantiate1 ps[i])\n else\n throwError \"invalid instantiateForall, too many parameters\"\n else\n return type\ntermination_by go i _ => ps.size - i\n\n/--\nReturn `true` if `type` is a predicate.\nExamples: `Nat → Prop`, `Prop`, `Int → Bool → Prop`.\n-/\npartial def isPredicateType (type : Expr) : Bool :=\n match type.headBeta with\n | .sort .zero => true\n | .forallE _ _ b _ => isPredicateType b\n | _ => false\n\n/--\nReturn `true` if `type` is a LCNF type former type or it is an \"any\" type.\nThis function is similar to `isTypeFormerType`, but more liberal.\nFor example, `isTypeFormerType` returns false for `◾` and `Nat → ◾`, but\nthis function returns true.\n-/\npartial def maybeTypeFormerType (type : Expr) : Bool :=\n match type.headBeta with\n | .sort .. => true\n | .forallE _ _ b _ => maybeTypeFormerType b\n | _ => type.isErased\n\n/--\n`isClass? type` return `some ClsName` if the LCNF `type` is an instance of the class `ClsName`.\n-/\ndef isClass? (type : Expr) : CoreM (Option Name) := do\n let .const declName _ := type.getAppFn | return none\n if isClass (← getEnv) declName then\n return declName\n else\n return none\n\n/--\n`isArrowClass? type` return `some ClsName` if the LCNF `type` is an instance of the class `ClsName`, or\nif it is arrow producing an instance of the class `ClsName`.\n-/\npartial def isArrowClass? (type : Expr) : CoreM (Option Name) := do\n match type.headBeta with\n | .forallE _ _ b _ => isArrowClass? b\n | _ => isClass? type\n\npartial def getArrowArity (e : Expr) :=\n match e.headBeta with\n | .forallE _ _ b _ => getArrowArity b + 1\n | _ => 0\n\n/-- Return `true` if `type` is an inductive datatype with 0 constructors. -/\ndef isInductiveWithNoCtors (type : Expr) : CoreM Bool := do\n let .const declName _ := type.getAppFn | return false\n let some (.inductInfo info) := (← getEnv).find? declName | return false\n return info.numCtors == 0\n\nend Lean.Compiler.LCNF\n", "meta": {"author": "leanprover", "repo": "lean4", "sha": "742d053a97bdd109a41a921facd1cd6a55e89bc7", "save_path": "github-repos/lean/leanprover-lean4", "path": "github-repos/lean/leanprover-lean4/lean4-742d053a97bdd109a41a921facd1cd6a55e89bc7/src/Lean/Compiler/LCNF/Types.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.36658973632215985, "lm_q2_score": 0.051845472509812494, "lm_q1q2_score": 0.01900601809686995}} {"text": "import Lean\n\n-- This is a copy of Lean's DiscrTree, but with all definitional equality checks removed.\n\nnamespace CvxLean\n\nopen Lean\nopen Meta\n\ninductive Key where\n | const : Name → Nat → Key\n | fvar : FVarId → Nat → Key\n | lit : Literal → Key\n | star : Key\n | other : Key\n | arrow : Key\n | proj : Name → Nat → Key\n deriving Inhabited, BEq, Repr\n\nprotected def Key.hash : Key → UInt64\n | Key.const n a => mixHash 5237 $ mixHash (hash n) (hash a)\n | Key.fvar n a => mixHash 3541 $ mixHash (hash n) (hash a)\n | Key.lit v => mixHash 1879 $ hash v\n | Key.star => 7883\n | Key.other => 2411\n | Key.arrow => 17\n | Key.proj s i => mixHash 11 $ mixHash (hash s) (hash i)\n\ninstance : Hashable Key := ⟨Key.hash⟩\n\ninductive Trie (α : Type) where\n | node (vs : Array α) (children : Array (Key × Trie α)) : Trie α\n\nstructure DiscrTree (α : Type) where\n root : Std.PersistentHashMap Key (Trie α) := {}\n\ndef Key.ctorIdx : Key → Nat\n | Key.star => 0\n | Key.other => 1\n | Key.lit .. => 2\n | Key.fvar .. => 3\n | Key.const .. => 4\n | Key.arrow => 5\n | Key.proj .. => 6\n\ndef Key.lt : Key → Key → Bool\n | Key.lit v₁, Key.lit v₂ => v₁ < v₂\n | Key.fvar n₁ a₁, Key.fvar n₂ a₂ => Name.quickLt n₁.name n₂.name || (n₁ == n₂ && a₁ < a₂)\n | Key.const n₁ a₁, Key.const n₂ a₂ => Name.quickLt n₁ n₂ || (n₁ == n₂ && a₁ < a₂)\n | Key.proj s₁ i₁, Key.proj s₂ i₂ => Name.quickLt s₁ s₂ || (s₁ == s₂ && i₁ < i₂)\n | k₁, k₂ => k₁.ctorIdx < k₂.ctorIdx\n\ninstance : LT Key := ⟨fun a b => Key.lt a b⟩\ninstance (a b : Key) : Decidable (a < b) := inferInstanceAs (Decidable (Key.lt a b))\n\ndef Key.format : Key → Format\n | Key.star => \"*\"\n | Key.other => \"◾\"\n | Key.lit (Literal.natVal v) => Std.format v\n | Key.lit (Literal.strVal v) => repr v\n | Key.const k _ => Std.format k\n | Key.proj s i => Std.format s ++ \".\" ++ Std.format i\n | Key.fvar k _ => Std.format k.name\n | Key.arrow => \"→\"\n\ninstance : ToFormat Key := ⟨Key.format⟩\n\ndef Key.arity : Key → Nat\n | Key.const _ a => a\n | Key.fvar _ a => a\n | Key.arrow => 2\n | Key.proj .. => 1\n | _ => 0\n\ninstance : Inhabited (Trie α) := ⟨Trie.node #[] #[]⟩\n\n\nnamespace DiscrTree\n\ndef empty : DiscrTree α := { root := {} }\n\npartial def Trie.format [ToMessageData α] : Trie α → MessageData\n | Trie.node vs cs => MessageData.group $ MessageData.paren $\n \"node\" ++ (if vs.isEmpty then MessageData.nil else \" \" ++ toMessageData vs)\n ++ MessageData.joinSep (cs.toList.map $ fun ⟨k, c⟩ => MessageData.paren (toMessageData k ++ \" => \" ++ format c)) \",\"\n\ninstance [ToMessageData α] : ToMessageData (Trie α) := ⟨Trie.format⟩\n\npartial def format [ToMessageData α] (d : DiscrTree α) : MessageData :=\n let (_, r) := d.root.foldl\n (fun (p : Bool × MessageData) k c =>\n (false, p.2 ++ MessageData.paren (toMessageData k ++ \" => \" ++ toMessageData c)))\n (true, Format.nil)\n MessageData.group r\n\ninstance [ToMessageData α] : ToMessageData (DiscrTree α) := ⟨fun dt => format dt⟩\n\n/- The discrimination tree ignores some implicit arguments and proofs.\n We use the following auxiliary id as a \"mark\". -/\nprivate def tmpMVarId : MVarId := { name := `_discr_tree_tmp }\nprivate def tmpStar := mkMVar tmpMVarId\n\ninstance : Inhabited (DiscrTree α) where\n default := {}\n\n/--\n Return true iff the argument should be treated as a \"wildcard\" by the discrimination tree.\n - We ignore proofs because of proof irrelevance. It doesn't make sense to try to\n index their structure.\n - We ignore instance implicit arguments (e.g., `[Add α]`) because they are \"morally\" canonical.\n Moreover, we may have many definitionally equal terms floating around.\n Example: `Ring.hasAdd Int Int.isRing` and `Int.hasAdd`.\n - We considered ignoring implicit arguments (e.g., `{α : Type}`) since users don't \"see\" them,\n and may not even understand why some simplification rule is not firing.\n However, in type class resolution, we have instance such as `Decidable (@Eq Nat x y)`,\n where `Nat` is an implicit argument. Thus, we would add the path\n ```\n Decidable -> Eq -> * -> * -> * -> [Nat.decEq]\n ```\n to the discrimination tree IF we ignored the implict `Nat` argument.\n This would be BAD since **ALL** decidable equality instances would be in the same path.\n So, we index implicit arguments if they are types.\n This setting seems sensible for simplification lemmas such as:\n ```\n forall (x y : Unit), (@Eq Unit x y) = true\n ```\n If we ignore the implicit argument `Unit`, the `DiscrTree` will say it is a candidate\n simplification lemma for any equality in our goal.\n Remark: if users have problems with the solution above, we may provide a `noIndexing` annotation,\n and `ignoreArg` would return true for any term of the form `noIndexing t`.\n-/\nprivate def ignoreArg (a : Expr) (i : Nat) (infos : Array Meta.ParamInfo) : MetaM Bool := do\n if h : i < infos.size then\n let info := infos.get ⟨i, h⟩\n if info.isInstImplicit then\n return true\n else if info.isImplicit || info.isStrictImplicit then\n return not (← isType a)\n else\n isProof a\n else\n isProof a\n\nprivate partial def pushArgsAux (infos : Array Meta.ParamInfo) : Nat → Expr → Array Expr → MetaM (Array Expr)\n | i, Expr.app f a, todo => do\n if (← ignoreArg a i infos) then\n pushArgsAux infos (i-1) f (todo.push tmpStar)\n else\n pushArgsAux infos (i-1) f (todo.push a)\n | _, _, todo => return todo\n\ndef mkNoindexAnnotation (e : Expr) : Expr :=\n mkAnnotation `noindex e\n\ndef hasNoindexAnnotation (e : Expr) : Bool :=\n annotation? `noindex e |>.isSome\n\nprivate def pushArgs (root : Bool) (todo : Array Expr) (e : Expr) : MetaM (Key × Array Expr) := do\n if hasNoindexAnnotation e then\n return (Key.star, todo)\n else\n let fn := e.getAppFn\n let push (k : Key) (nargs : Nat) : MetaM (Key × Array Expr) := do\n let info ← getFunInfoNArgs fn nargs\n let todo ← pushArgsAux info.paramInfo (nargs-1) e todo\n return (k, todo)\n match fn with\n | Expr.lit v => return (Key.lit v, todo)\n | Expr.const c _ =>\n let nargs := e.getAppNumArgs\n push (Key.const c nargs) nargs\n | Expr.proj s i a .. =>\n return (Key.proj s i, todo.push a)\n | Expr.fvar fvarId =>\n let nargs := e.getAppNumArgs\n push (Key.fvar fvarId nargs) nargs\n | Expr.mvar mvarId =>\n if mvarId == tmpMVarId then\n -- We use `tmp to mark some implicit arguments and proofs\n return (Key.star, todo)\n else\n return (Key.star, todo)\n | Expr.forallE _ d b _ =>\n if b.hasLooseBVars then\n return (Key.other, todo)\n else\n return (Key.arrow, todo.push d |>.push b)\n | _ =>\n return (Key.other, todo)\n\npartial def mkPathAux (root : Bool) (todo : Array Expr) (keys : Array Key) : MetaM (Array Key) := do\n if todo.isEmpty then\n return keys\n else\n let e := todo.back\n let todo := todo.pop\n let (k, todo) ← pushArgs root todo e\n mkPathAux false todo (keys.push k)\n\nprivate def initCapacity := 8\n\ndef mkPath (e : Expr) : MetaM (Array Key) := do\n let todo : Array Expr := Array.mkEmpty initCapacity\n let keys : Array Key := Array.mkEmpty initCapacity\n mkPathAux (root := true) (todo.push e) keys\n\nprivate partial def createNodes (keys : Array Key) (v : α) (i : Nat) : Trie α :=\n if h : i < keys.size then\n let k := keys.get ⟨i, h⟩\n let c := createNodes keys v (i+1)\n Trie.node #[] #[(k, c)]\n else\n Trie.node #[v] #[]\n\nprivate def insertVal [BEq α] (vs : Array α) (v : α) : Array α :=\n if vs.contains v then vs else vs.push v\n\nprivate partial def insertAux [BEq α] (keys : Array Key) (v : α) : Nat → Trie α → Trie α\n | i, Trie.node vs cs =>\n if h : i < keys.size then\n let k := keys.get ⟨i, h⟩\n let c := Id.run $ cs.binInsertM\n (fun a b => a.1 < b.1)\n (fun ⟨_, s⟩ => let c := insertAux keys v (i+1) s; (k, c)) -- merge with existing\n (fun _ => let c := createNodes keys v (i+1); (k, c))\n (k, default)\n Trie.node vs c\n else\n Trie.node (insertVal vs v) cs\n\ndef insertCore [BEq α] (d : DiscrTree α) (keys : Array Key) (v : α) : DiscrTree α :=\n if keys.isEmpty then panic! \"invalid key sequence\"\n else\n let k := keys[0]!\n match d.root.find? k with\n | none =>\n let c := createNodes keys v 1\n { root := d.root.insert k c }\n | some c =>\n let c := insertAux keys v 1 c\n { root := d.root.insert k c }\n\ndef insert [BEq α] (d : DiscrTree α) (e : Expr) (v : α) : MetaM (DiscrTree α) := do\n let keys ← mkPath e\n return d.insertCore keys v\n\nprivate def getKeyArgs (e : Expr) (isMatch root : Bool) : MetaM (Key × Array Expr) := do\n match e.getAppFn with\n | Expr.lit v => return (Key.lit v, #[])\n | Expr.const c _ =>\n let nargs := e.getAppNumArgs\n return (Key.const c nargs, e.getAppRevArgs)\n | Expr.fvar fvarId =>\n let nargs := e.getAppNumArgs\n return (Key.fvar fvarId nargs, e.getAppRevArgs)\n | Expr.mvar mvarId =>\n if isMatch then\n return (Key.other, #[])\n else do\n return (Key.star, #[])\n | Expr.proj s i a .. =>\n return (Key.proj s i, #[a])\n | Expr.forallE _ d b _ =>\n if b.hasLooseBVars then\n return (Key.other, #[])\n else\n return (Key.arrow, #[d, b])\n | _ =>\n return (Key.other, #[])\n\nprivate abbrev getMatchKeyArgs (e : Expr) (root : Bool) : MetaM (Key × Array Expr) :=\n getKeyArgs e (isMatch := true) (root := root)\n\nprivate abbrev getUnifyKeyArgs (e : Expr) (root : Bool) : MetaM (Key × Array Expr) :=\n getKeyArgs e (isMatch := false) (root := root)\n\nprivate def getStarResult (d : DiscrTree α) : Array α :=\n let result : Array α := Array.mkEmpty initCapacity\n match d.root.find? Key.star with\n | none => result\n | some (Trie.node vs _) => result ++ vs\n\nprivate abbrev findKey (cs : Array (Key × Trie α)) (k : Key) : Option (Key × Trie α) :=\n cs.binSearch (k, default) (fun a b => a.1 < b.1)\n\nprivate partial def getMatchLoop (todo : Array Expr) (c : Trie α) (result : Array α) : MetaM (Array α) := do\n match c with\n | Trie.node vs cs =>\n if todo.isEmpty then\n return result ++ vs\n else if cs.isEmpty then\n return result\n else\n let e := todo.back\n let todo := todo.pop\n let first := cs[0]! /- Recall that `Key.star` is the minimal key -/\n let (k, args) ← getMatchKeyArgs e (root := false)\n /- We must always visit `Key.star` edges since they are wildcards.\n Thus, `todo` is not used linearly when there is `Key.star` edge\n and there is an edge for `k` and `k != Key.star`. -/\n let visitStar (result : Array α) : MetaM (Array α) :=\n if first.1 == Key.star then\n getMatchLoop todo first.2 result\n else\n return result\n let visitNonStar (k : Key) (args : Array Expr) (result : Array α) : MetaM (Array α) :=\n match findKey cs k with\n | none => pure result\n | some c => getMatchLoop (todo ++ args) c.2 result\n let result ← visitStar result\n match k with\n | Key.star => pure result\n /-\n Recall that dependent arrows are `(Key.other, #[])`, and non-dependent arrows are `(Key.arrow, #[a, b])`.\n A non-dependent arrow may be an instance of a dependent arrow (stored at `DiscrTree`). Thus, we also visit the `Key.other` child.\n -/\n | Key.arrow => visitNonStar Key.other #[] (← visitNonStar k args result)\n | _ => visitNonStar k args result\n\nprivate def getMatchRoot (d : DiscrTree α) (k : Key) (args : Array Expr) (result : Array α) : MetaM (Array α) :=\n match d.root.find? k with\n | none => return result\n | some c => getMatchLoop args c result\n\n/--\n Find values that match `e` in `d`.\n-/\npartial def getMatch (d : DiscrTree α) (e : Expr) : MetaM (Array α) := do\n Core.checkMaxHeartbeats \"getMatch\"\n let result := getStarResult d\n let (k, args) ← getMatchKeyArgs e (root := true)\n match k with\n | Key.star => return result\n | _ => getMatchRoot d k args result\n\npartial def getUnify (d : DiscrTree α) (e : Expr) : MetaM (Array α) := do\n Core.checkMaxHeartbeats \"getUnify\"\n let (k, args) ← getUnifyKeyArgs e (root := true)\n match k with\n | Key.star => d.root.foldlM (init := #[]) fun result k c => process k.arity #[] c result\n | _ =>\n let result := getStarResult d\n match d.root.find? k with\n | none => return result\n | some c => process 0 args c result\nwhere\n process (skip : Nat) (todo : Array Expr) (c : Trie α) (result : Array α) : MetaM (Array α) := do\n match skip, c with\n | skip+1, Trie.node vs cs =>\n if cs.isEmpty then\n return result\n else\n cs.foldlM (init := result) fun result ⟨k, c⟩ => process (skip + k.arity) todo c result\n | 0, Trie.node vs cs => do\n if todo.isEmpty then\n return result ++ vs\n else if cs.isEmpty then\n return result\n else\n let e := todo.back\n let todo := todo.pop\n let (k, args) ← getUnifyKeyArgs e (root := false)\n let visitStar (result : Array α) : MetaM (Array α) :=\n let first := cs[0]!\n if first.1 == Key.star then\n process 0 todo first.2 result\n else\n return result\n let visitNonStar (k : Key) (args : Array Expr) (result : Array α) : MetaM (Array α) :=\n match findKey cs k with\n | none => pure result\n | some c => process 0 (todo ++ args) c.2 result\n match k with\n | Key.star => cs.foldlM (init := result) fun result ⟨k, c⟩ => process k.arity todo c result\n -- See comment a `getMatch` regarding non-dependent arrows vs dependent arrows\n | Key.arrow => visitNonStar Key.other #[] (← visitNonStar k args (← visitStar result))\n | _ => visitNonStar k args (← visitStar result)\n\nend DiscrTree\n\n-- From AESOP:\nnamespace Trie\n\nunsafe def foldMUnsafe [Monad m] (initialKeys : Array Key)\n (f : σ → Array Key → α → m σ) (init : σ) : Trie α → m σ\n | Trie.node vs children => do\n let s ← vs.foldlM (init := init) λ s v => f s initialKeys v\n children.foldlM (init := s) λ s (k, t) =>\n t.foldMUnsafe (initialKeys.push k) f s\n\n@[implementedBy foldMUnsafe]\nopaque foldM [Monad m] (initalKeys : Array Key)\n (f : σ → Array Key → α → m σ) (init : σ) (t : Trie α) : m σ :=\n pure init\n\n@[inline]\ndef fold (initialKeys : Array Key) (f : σ → Array Key → α → σ) (init : σ)\n (t : Trie α) : σ :=\n Id.run $ t.foldM initialKeys (init := init) λ s k a => return f s k a\n\nend Trie\n\nnamespace DiscrTree\n\n@[inline]\ndef foldM [Monad m] (f : σ → Array Key → α → m σ) (init : σ) (t : DiscrTree α) :\n m σ :=\n t.root.foldlM (init := init) λ s k t => t.foldM #[k] (init := s) f\n\n@[inline]\ndef fold (f : σ → Array Key → α → σ) (init : σ) (t : DiscrTree α) : σ :=\n Id.run $ t.foldM (init := init) λ s keys a => return f s keys a\n\n-- TODO inefficient since it doesn't take advantage of the Trie structure at all\n@[inline]\ndef merge [BEq α] (t u : DiscrTree α) : DiscrTree α :=\n if t.root.size < u.root.size then loop t u else loop u t\n where\n @[inline]\n loop t u := t.fold (init := u) DiscrTree.insertCore\n\ndef values (t : DiscrTree α) : Array α :=\n t.fold (init := #[]) λ as _ a => as.push a\n\ndef toArray (t : DiscrTree α) : Array (Array Key × α) :=\n t.fold (init := #[]) λ as keys a => as.push (keys, a)\n\nend DiscrTree\n\nend CvxLean", "meta": {"author": "verified-optimization", "repo": "CvxLean", "sha": "fc2996519f0fca96f5ab48a5a1479c6a8024f733", "save_path": "github-repos/lean/verified-optimization-CvxLean", "path": "github-repos/lean/verified-optimization-CvxLean/CvxLean-fc2996519f0fca96f5ab48a5a1479c6a8024f733/CvxLean/Tactic/DCP/DiscrTree.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.3775406828054583, "lm_q2_score": 0.05033063117300159, "lm_q1q2_score": 0.01900186085908471}} {"text": "import Std.Tactic.Basic\nimport Std.Tactic.GuardExpr\nimport Std.Tactic.RCases\n\nset_option linter.missingDocs false\n\nexample (x : α × β × γ) : True := by\n rcases x with ⟨a, b, c⟩\n guard_hyp a : α\n guard_hyp b : β\n guard_hyp c : γ\n trivial\n\nexample (x : α × β × γ) : True := by\n rcases x with ⟨(a : α) : id α, -, c : id γ⟩\n guard_hyp a : α\n fail_if_success have : β := by assumption\n guard_hyp c : id γ\n trivial\n\nexample (x : (α × β) × γ) : True := by\n fail_if_success rcases x with ⟨_a, b, c⟩\n fail_if_success rcases x with ⟨⟨a:β, b⟩, c⟩\n rcases x with ⟨⟨a:α, b⟩, c⟩\n guard_hyp a : α\n guard_hyp b : β\n guard_hyp c : γ\n trivial\n\nexample : @Inhabited.{1} α × Option β ⊕ γ → True := by\n rintro (⟨⟨a⟩, _ | b⟩ | c)\n · guard_hyp a : α; trivial\n · guard_hyp a : α; guard_hyp b : β; trivial\n · guard_hyp c : γ; trivial\n\nexample : cond false Nat Int → cond true Int Nat → Nat ⊕ Unit → True := by\n rintro (x y : Int) (z | u)\n · guard_hyp x : Int; guard_hyp y : Int; guard_hyp z : Nat; trivial\n · guard_hyp x : Int; guard_hyp y : Int; guard_hyp u : Unit; trivial\n\nexample (x y : Nat) (h : x = y) : True := by\n rcases x with _|⟨⟩|z\n · guard_hyp h : Nat.zero = y; trivial\n · guard_hyp h : Nat.succ Nat.zero = y; trivial\n · guard_hyp z : Nat\n guard_hyp h : Nat.succ (Nat.succ z) = y; trivial\n\nexample (h : x = 3) (h₂ : x < 4) : x < 4 := by\n rcases h with ⟨⟩\n guard_hyp h₂ : 3 < 4; guard_target = 3 < 4; exact h₂\n\nexample (h : x = 3) (h₂ : x < 4) : x < 4 := by\n rcases h with rfl\n guard_hyp h₂ : 3 < 4; guard_target = 3 < 4; exact h₂\n\nexample (h : 3 = x) (h₂ : x < 4) : x < 4 := by\n rcases h with ⟨⟩\n guard_hyp h₂ : 3 < 4; guard_target = 3 < 4; exact h₂\n\nexample (h : 3 = x) (h₂ : x < 4) : x < 4 := by\n rcases h with rfl\n guard_hyp h₂ : 3 < 4; guard_target = 3 < 4; exact h₂\n\nexample (s : α ⊕ Empty) : True := by\n rcases s with s|⟨⟨⟩⟩\n guard_hyp s : α; trivial\n\nexample : True := by\n obtain ⟨n : Nat, _h : n = n, -⟩ : ∃ n : Nat, n = n ∧ True\n · exact ⟨0, rfl, trivial⟩\n trivial\n\nexample : True := by\n obtain (h : True) | ⟨⟨⟩⟩ : True ∨ False\n · exact Or.inl trivial\n guard_hyp h : True; trivial\n\nexample : True := by\n obtain h | ⟨⟨⟩⟩ : True ∨ False := Or.inl trivial\n guard_hyp h : True; trivial\n\nexample : True := by\n obtain ⟨h, h2⟩ := And.intro trivial trivial\n guard_hyp h : True; guard_hyp h2 : True; trivial\n\nexample : True := by\n fail_if_success obtain ⟨h, h2⟩\n trivial\n\nexample (x y : α × β) : True := by\n rcases x, y with ⟨⟨a, b⟩, c, d⟩\n guard_hyp a : α; guard_hyp b : β\n guard_hyp c : α; guard_hyp d : β\n trivial\n\nexample (x y : α ⊕ β) : True := by\n rcases x, y with ⟨a|b, c|d⟩\n · guard_hyp a : α; guard_hyp c : α; trivial\n · guard_hyp a : α; guard_hyp d : β; trivial\n · guard_hyp b : β; guard_hyp c : α; trivial\n · guard_hyp b : β; guard_hyp d : β; trivial\n\nexample (i j : Nat) : (Σ' x, i ≤ x ∧ x ≤ j) → i ≤ j := by\n intro h\n rcases h' : h with ⟨x, h₀, h₁⟩\n guard_hyp h' : h = ⟨x, h₀, h₁⟩\n apply Nat.le_trans h₀ h₁\n\nexample (x : Quot fun _ _ : α => True) (h : x = x): x = x := by\n rcases x with ⟨z⟩\n guard_hyp z : α\n guard_hyp h : Quot.mk (fun _ _ => True) z = Quot.mk (fun _ _ => True) z\n guard_target = Quot.mk (fun _ _ => True) z = Quot.mk (fun _ _ => True) z\n exact h\n\nexample (n : Nat) : True := by\n obtain _one_lt_n | _n_le_one : 1 < n + 1 ∨ n + 1 ≤ 1 := Nat.lt_or_ge 1 (n + 1)\n {trivial}; trivial\n\nexample (n : Nat) : True := by\n obtain _one_lt_n | (_n_le_one : n + 1 ≤ 1) := Nat.lt_or_ge 1 (n + 1)\n {trivial}; trivial\n\nopen Lean Elab Tactic in\n/-- Asserts that the goal has `n` hypotheses. Used for testing. -/\nelab \"check_num_hyps \" n:num : tactic => liftMetaMAtMain fun _ => do\n -- +1 because the _example recursion decl is in the list\n guard $ (← getLCtx).foldl (fun i _ => i+1) 0 = n.1.toNat + 1\n\nexample (h : ∃ x : Nat, x = x ∧ 1 = 1) : True := by\n rcases h with ⟨-, _⟩\n check_num_hyps 0\n trivial\n\nexample (h : ∃ x : Nat, x = x ∧ 1 = 1) : True := by\n rcases h with ⟨-, _, h⟩\n check_num_hyps 1\n guard_hyp h : 1 = 1\n trivial\n\nexample (h : True ∨ True ∨ True) : True := by\n rcases h with - | - | -\n iterate 3 · check_num_hyps 0; trivial\n\nexample : Bool → False → True\n| false => by rintro ⟨⟩\n| true => by rintro ⟨⟩\n\nexample : (b : Bool) → cond b False False → True := by\n rintro ⟨⟩ ⟨⟩\n\nstructure Baz {α : Type _} (f : α → α) : Prop where\n [inst : Nonempty α]\n h : f ∘ f = id\n\nexample {α} (f : α → α) (h : Baz f) : True := by rcases h with ⟨_⟩; trivial\n\nexample {α} (f : α → α) (h : Baz f) : True := by rcases h with @⟨_, _⟩; trivial\n\ninductive Test : Nat → Prop\n | a (n) : Test (2 + n)\n | b {n} : n > 5 → Test (n * n)\n\nexample {n} (h : Test n) : n = n := by\n have : True := by\n rcases h with (a | b)\n · guard_hyp a : Nat\n trivial\n · guard_hyp b : ‹Nat› > 5\n trivial\n · rcases h with (a | @⟨n, b⟩)\n · guard_hyp a : Nat\n trivial\n · guard_hyp b : n > 5\n trivial\n\nexample (h : a ≤ 2 ∨ 2 < a) : True := by\n obtain ha1 | ha2 : a ≤ 2 ∨ 3 ≤ a := h\n · guard_hyp ha1 : a ≤ 2; trivial\n · guard_hyp ha2 : 3 ≤ a; trivial\n\nexample (h : a ≤ 2 ∨ 2 < a) : True := by\n obtain ha1 | ha2 : a ≤ 2 ∨ 3 ≤ a := id h\n · guard_hyp ha1 : a ≤ 2; trivial\n · guard_hyp ha2 : 3 ≤ a; trivial\n\ninductive BaseType : Type where\n | one\n\ninductive BaseTypeHom : BaseType → BaseType → Type where\n | loop : BaseTypeHom one one\n | id (X : BaseType) : BaseTypeHom X X\n\nexample : BaseTypeHom one one → Unit := by rintro ⟨_⟩ <;> constructor\n", "meta": {"author": "leanprover", "repo": "std4", "sha": "5507f9d8409f93b984ce04eccf4914d534e6fca2", "save_path": "github-repos/lean/leanprover-std4", "path": "github-repos/lean/leanprover-std4/std4-5507f9d8409f93b984ce04eccf4914d534e6fca2/test/rcases.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35577489351363034, "lm_q2_score": 0.053403327163362595, "lm_q1q2_score": 0.01899956303481889}} {"text": "\nimport tactic.default\n\nuniverses u v\n-- #check @option.elim\n-- def option.elim {α β} (x : β) (f : α → β) : option α → β\n-- | none := x\n-- | (some y) := f y\n-- #exit\nnamespace list\n\ndef mfilter_map {m} [applicative m] {α β} (f : α → m (option β)) : list α → m (list.{v} β)\n| [] := pure []\n| (x :: xs) :=\n (λ a, option.elim a id (::)) <$> f x <*> mfilter_map xs\n\ndef mfilter_map' {m} [applicative m] [alternative m] {α β} (f : α → m β) : list α → m (list.{v} β)\n| [] := pure []\n| (x :: xs) :=\n ((::) <$> f x <|> pure id) <*> mfilter_map' xs\n\nend list\n\n\nnamespace tactic\n\nopen native\n\nmeta def rename_many' (renames : name_map name) (strict := tt) (use_unique_names := ff)\n: tactic (list (name × expr)) :=\ndo let hyp_name : expr → name :=\n if use_unique_names then expr.local_uniq_name else expr.local_pp_name,\n ctx ← revertible_local_context,\n -- The part of the context after (but including) the first hypthesis that\n -- must be renamed.\n let ctx_suffix := ctx.drop_while (λ h, (renames.find $ hyp_name h).is_none),\n when strict $ do {\n let ctx_names := rb_map.set_of_list (ctx_suffix.map hyp_name),\n let invalid_renames :=\n (renames.to_list.map prod.fst).filter (λ h, ¬ ctx_names.contains h),\n when ¬ invalid_renames.empty $ fail $ format.join\n [ \"Cannot rename these hypotheses:\\n\"\n , format.join $ (invalid_renames.map to_fmt).intersperse \", \"\n , format.line\n , \"This is because these hypotheses either do not occur in the\\n\"\n , \"context or they occur before a frozen local instance.\\n\"\n , \"In the latter case, try `tactic.unfreeze_local_instances`.\"\n ]\n },\n -- The new names for all hypotheses in ctx_suffix.\n let new_names :=\n ctx_suffix.map $ λ h,\n (renames.find $ hyp_name h).get_or_else h.local_pp_name,\n revert_lst ctx_suffix,\n -- trace_state,\n xs ← intro_lst new_names,\n xs' ← xs.mmap infer_type,\n -- trace $ ctx_suffix.zip $ xs.zip xs',\n pure $ (ctx_suffix.map expr.local_uniq_name).zip xs\n\nmeta def find_hyp (pat : pexpr) (f : expr → tactic unit) : tactic unit := do\nls ← local_context,\npat ← pexpr_to_pattern pat,\nls.mfirst $ λ h, do\n t ← infer_type h,\n match_pattern pat t,\n f h\n\nmeta def find_all_hyps (pat : pexpr) (f : expr → tactic unit) : tactic unit := do\nls ← local_context,\npat ← pexpr_to_pattern pat,\nls.mmap' $ λ h, try $ do\n t ← infer_type h,\n match_pattern pat t,\n f h\n\nnamespace interactive\nsetup_tactic_parser\n\nmeta def find_hyp (id : parse ident) (_ : parse (tk \":=\")) (pat : parse texpr)\n (_ : parse (tk \"then\")) (tac : itactic) : tactic unit := do\nls ← local_context,\npat ← pexpr_to_pattern pat,\nls.mfirst $ λ h, do\n t ← infer_type h,\n match_pattern pat t,\n rename_many (native.rb_map.of_list [(h.local_uniq_name, id)]) tt tt,\n tac,\n rename_many $ native.rb_map.of_list [(id, h.local_pp_name)]\n-- #exit\n\nmeta def find_all_hyps (id : parse ident) (_ : parse (tk \":=\")) (pat : parse texpr)\n (_ : parse (tk \"then\")) (tac : itactic) : tactic unit := do\nls ← local_context,\npat ← pexpr_to_pattern pat,\nls.reverse.mmap' (λ h,\n -- trace σ,\n -- let h := h.instantiate_locals $ list.reverse σ,\n try_or_report_error $ do {\n t ← infer_type h,\n match_pattern pat t,\n -- trace!\"{h} : {t}\",\n n ← tactic.revert h,\n intro id,\n intron $ n-1,\n -- xs ← rename_many' (native.rb_map.of_list [(h.local_uniq_name, id)]) tt tt,\n tac,\n h' ← get_local id,\n n ← tactic.revert h',\n intro h.local_pp_name,\n intron $ n-1,\n skip }),\nskip\n\nmeta def match_le_or_lt : expr → option (expr × expr)\n| `(%%x < %%y) := pure (x, y)\n| `(%%x ≤ %%y) := pure (x, y)\n| `(%%x > %%y) := pure (y, x)\n| `(%%x ≥ %%y) := pure (y, x)\n| _ := none\n\nmeta def match_le : expr → option (expr × expr)\n| `(%%x ≤ %%y) := pure (x, y)\n| `(%%x ≥ %%y) := pure (y, x)\n| _ := none\n\nmeta def match_lt : expr → option (expr × expr)\n| `(%%x < %%y) := pure (x, y)\n| `(%%x > %%y) := pure (y, x)\n| _ := none\n\n#print list.filter_map\n\ninductive edge\n| lt | le\n\ninstance : has_to_string edge :=\n⟨ λ e, match e with\n | edge.lt := \"lt\"\n | edge.le := \"le\"\n end ⟩\n\nmeta instance edge.has_to_format : has_to_format edge :=\n⟨ λ e, to_fmt $ to_string e ⟩\n\nmeta instance rb_lmap.has_to_format {α β} [has_to_tactic_format α] [has_to_tactic_format β] : has_to_tactic_format (native.rb_lmap α β) :=\nby delta native.rb_lmap; apply_instance\n\nopen native\n\nmeta def graph := (native.rb_lmap expr (expr × edge × expr))\n\nmeta instance graph.has_to_format : has_to_tactic_format graph :=\nby delta graph; apply_instance\n\nmeta def dfs_trans' (g : graph) (r : ref expr_set) (v : expr) : edge → expr → expr → tactic expr\n| e x h := do\n x ← instantiate_mvars x,\n -- trace!\"visit {x}, going to {v}\",\n vs ← read_ref r,\n -- trace!\"seen: {vs}\",\n if vs.contains x then failed\n else if v = x then pure h\n else do\n write_ref r $ vs.insert x,\n -- trace (g.find x),\n (g.find x).mfirst $ λ ⟨h',e',y⟩, do\n -- trace!\"try: {x}, {y}\",\n (e,h) ← match e, e' with\n | edge.lt, edge.lt := prod.mk edge.lt <$> mk_app ``lt_trans [h, h']\n | edge.lt, edge.le := prod.mk edge.lt <$> mk_app ``lt_of_lt_of_le [h, h']\n | edge.le, edge.lt := prod.mk edge.lt <$> mk_app ``lt_of_le_of_lt [h, h']\n | edge.le, edge.le := prod.mk edge.le <$> mk_app ``le_trans [h, h']\n end,\n -- trace\"ok\",\n dfs_trans' e y h\n\nmeta def dfs_trans (g : graph) (v v' : expr) : tactic expr :=\nusing_new_ref mk_expr_set $ λ r, do\n h ← mk_mapp ``le_refl [none, none, v],\n dfs_trans' g r v' edge.le v h\n\n#check cc_state\n\nlemma lt_of_eq_of_lt_of_eq {α} {R : α → α → Prop} {x x' y' y : α} (h₀ : x = x') (h₁ : R x' y') (h₂ : y' = y) :\n R x y := by subst_vars; exact h₁\n\n-- lemma t_of_eq_of_lt_of_eq {α} [has_lt α] {x x' y' y : α} (h₀ : x = x') (h₁ : x' < y') (h₂ : y' = y) :\n-- x < y := by subst_vars; exact h₁\n\nmeta def chain_trans : tactic unit := do\ntgt ← target,\n(x, y) ← match_le_or_lt tgt,\nα ← infer_type x,\ns ← cc_state.mk_using_hs,\nls ← local_context >>= list.mfilter_map'\n (λ h, do t ← infer_type h,\n do { (e, x, y) ← prod.mk edge.le <$> match_le t <|>\n prod.mk edge.lt <$> match_lt t,\n let x' := s.root x,\n let y' := s.root y,\n x_pr ← s.eqv_proof x' x,\n y_pr ← s.eqv_proof y y',\n h' ← mk_app ``lt_of_eq_of_lt_of_eq [x_pr, h, y_pr],\n -- trace!\"h : {infer_type h}\",\n -- trace!\"h' : {infer_type h'}\",\n infer_type x >>= is_def_eq α,\n pure [(h', e, x', y')] }),\n -- <|>\n -- do { (x, y) ← match_eq t,\n -- infer_type x >>= is_def_eq α,\n -- h₀ ← mk_eq_symm h >>= mk_app ``le_of_eq ∘ list.ret,\n -- h₁ ← mk_app ``le_of_eq [h],\n -- pure [(h₀, edge.le, y, x), (h₁, edge.le, x, y)] }),\nlet m := list.foldl (λ (m : graph) (e : _ × _ × _ × _),\n let ⟨pr,e,x,y⟩ := e in\n m.insert x (pr,e,y)) (native.rb_lmap.mk expr (expr × edge × expr)) ls.join,\nx ← whnf x,\ny ← whnf y,\npr ← dfs_trans m x y,\ntactic.apply pr <|>\n mk_app ``le_of_lt [pr] >>= tactic.apply,\nskip\n\nend interactive\n\nsetup_tactic_parser\nprecedence `=?`:0\n\nimport_private set_cases_tags\nimport_private cases_postprocess\n\nmeta def interactive.trichotomy (x : parse texpr) (_ : parse $ tk \"=?\") (y : parse texpr) (hyp : parse $ tk \"with\" *> ident <|> pure `h) : tactic unit := do\nx ← to_expr x,\ny ← to_expr y,\nα ← infer_type x,\ninst ← mk_app ``linear_order [α] >>= mk_instance,\nh' ← mk_mapp ``cmp_compares [α, inst, x, y] >>= note hyp none,\n\ne ← mk_app ``cmp [x, y],\nn ← revert_kdependencies e,\nx ← get_unused_name,\ntactic.generalize e x,\n\nh ← tactic.intro1,\ns ← simp_lemmas.mk.add_simp ``ordering.compares,\nin_tag ← get_main_tag,\nfocus1 $ do\n hs ← cases_core h,\n set_cases_tags in_tag $ cases_postprocess hs,\n gs ← get_goals,\n gs ← (gs.zip hs).mmap $ λ ⟨g,h,_,σ⟩, do\n { set_goals [g],\n interactive.propagate_tags $ do\n { dsimp_target (some s) [] { fail_if_unchanged := ff },\n intron_no_renames (n) },\n get_goals },\n set_goals gs.join\n\nend tactic\n\nexample {x y : ℤ} (h : x ≤ y) (h : x < y) : true :=\nbegin\n find_hyp hh := x ≤ _ then { replace hh : x = y, admit },\n trivial\nend\n\nexample {x y z w u v : ℕ} {a b : ℤ} (h₀ : x ≤ y) (h₁ : y < z) (h : y < u) (h₂ : z < w) (h₃ : w = u) (h₄ : u < v) : x ≤ u :=\nbegin\n chain_trans,\nend\n", "meta": {"author": "cipher1024", "repo": "search-trees", "sha": "0e0ea0ee59f0b0499ebad1ef6f34f09ec9666cde", "save_path": "github-repos/lean/cipher1024-search-trees", "path": "github-repos/lean/cipher1024-search-trees/search-trees-0e0ea0ee59f0b0499ebad1ef6f34f09ec9666cde/src/tactic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4687906266262437, "lm_q2_score": 0.040237939602421106, "lm_q1q2_score": 0.018863168920367938}} {"text": "import data.finset.basic\nimport data.finset.sort\nimport data.finset.fold\nimport data.finmap\nimport data.fintype.basic\nimport tactic.linarith\n\n/-\n - Model of Golang.\n - This version explores a strategy for putting the full field information\n - of a struct within its own type declaration. This would allow one to ensure\n - the struct is correct (and initiate instances of it) without refering to a\n - global context.\n - The downside to this approach is that you cannot have self-referential\n - structs, e.g. Linked List.\n -/\n\n inductive TypeDecl: Type\n | gInt: TypeDecl\n | gStr: TypeDecl\n | gErr: TypeDecl\n | gBool: TypeDecl\n | gPtr: TypeDecl → TypeDecl\n | gArr: ℕ → TypeDecl → TypeDecl\n | gStruct (name: string) (fields: finset string)\n (vals: ∀ s ∈ fields, TypeDecl) : TypeDecl\n\n instance : decidable_eq TypeDecl :=\n begin\n intros a b, induction a generalizing b; cases b;\n try {{ apply decidable.is_false, rintro ⟨⟩ }},\n { simp [], exact decidable.true },\n { simp [], exact decidable.true },\n { simp [], exact decidable.true },\n { simp [], exact decidable.true },\n {simp, exact (a_ih b), },\n { simp, apply @and.decidable (a_a=b_a) (a_a_1= b_a_1)\n (nat.decidable_eq a_a b_a) (a_ih b_a_1)},\n {refine if h: a_name = b_name then _ else decidable.is_false (by simp [h]),\n refine if h': a_fields = b_fields then _ else decidable.is_false (by simp [h']),\n subst h, subst h', simp, resetI,\n refine decidable_of_iff (∀ x h, (a_vals x h = b_vals x h))\n (by {intros, split,\n {intros, simp [function.funext_iff],exact a,},\n {intros, simp [function.funext_iff] at a, exact a x h} }),},\n end\n\n open TypeDecl\n instance: inhabited TypeDecl := ⟨gInt⟩\n\n inductive PrimType: TypeDecl → Type\n | pInt: ℤ → PrimType gInt\n | pStr: string → PrimType gStr\n | pErr: string → PrimType gErr\n | pBool: bool → PrimType gBool\n | pPtr (t: TypeDecl): ℤ → PrimType (gPtr t)\n | pArr (t: TypeDecl) (n:ℕ): (∀ s: fin n, PrimType t)\n → PrimType (gArr n t)\n | pStruct (name: string) (fields: finset string)\n (valtypes: ∀ s ∈ fields, TypeDecl)\n (vals: ∀ s ∈ fields, PrimType (valtypes s H))\n : PrimType (@gStruct name fields valtypes)\n open PrimType\n instance : ∀ t, decidable_eq (PrimType t) :=\n begin\n intros t a b, induction a generalizing b; cases b;\n try {{ apply decidable.is_false, rintro ⟨⟩ }},\n { exact decidable_of_iff (a = b_1) (by simp) },\n { exact decidable_of_iff (a = b_1) (by simp) },\n { exact decidable_of_iff (a = b_1) (by simp) },\n { exact decidable_of_iff (a = b_1) (by simp) },\n { exact decidable_of_iff (a_a = b_a) (by simp) },\n {resetI,\n refine decidable_of_iff (∀ x , a_a x = b_a x) ( by {intros, split,\n {intros, simp [function.funext_iff], exact a},\n {intros, simp [function.funext_iff] at a, exact a x}})},\n { resetI, refine decidable_of_iff (∀ x h, a_vals x h = b_vals x h)\n (by {intros, split,\n {intros, simp [function.funext_iff], exact a},\n {intros, simp [function.funext_iff] at a, exact a x h}}),},\n end\n\n def inh: ∀ t, (PrimType t)\n | gInt := pInt 0\n | gStr := pStr \"\"\n | gErr := pErr \"\"\n | gBool := pBool ff\n | (gPtr x) := @pPtr x 0\n | (gArr n t) := @pArr t n (λ _, inh t)\n | (@gStruct name fs vs) := @pStruct _ _ _\n (λ x h, (have H: (vs x h).sizeof <\n 1 + name.length + finset.sizeof string fs := sorry,\n inh (vs x h)))\n\n instance: ∀ t, inhabited (PrimType t):= λ t, ⟨inh t⟩\n\n @[derive decidable_eq]\n structure Ptr (t: TypeDecl) := (val: ℤ)\n @[derive decidable_eq]\n structure Arr (n: ℕ) (t: TypeDecl) := (vals: (∀ s: fin n, PrimType t))\n\n structure Struct (name: string) (fields: finset string)\n (valtypes: ∀ s ∈ fields, TypeDecl)\n :=\n (vals: ∀ s ∈ fields, PrimType (valtypes s H))\n\nlemma strext {name} {fields} {valtypes} (a b: Struct name fields valtypes)\n (h : a.vals=b.vals) : a = b := begin\n cases a, cases b, simp at h, simp, exact h\n end\n\n def type_dict: TypeDecl → Type\n | gStr := string\n | gErr := string\n | gInt := ℤ\n | gBool := bool\n | (gPtr t):= Ptr t\n | (gArr n t):= Arr n t\n | (gStruct name fs vs):= Struct name fs vs\n\n @[simp]\n def to_td: ∀ t, (PrimType t) → (type_dict t)\n | gInt (pInt x) := x\n | gStr (pStr x) := x\n | gErr (pErr x) := x\n | gBool (pBool x) := x\n | (gPtr _) (pPtr _ x) := Ptr.mk x\n | (gArr _ t) (pArr _ _ xs) := Arr.mk xs\n | (gStruct _ _ _) (pStruct _ _ _ xs) := ⟨xs⟩\n\n @[simp]\n def from_td: ∀ t, (type_dict t) → (PrimType t)\n | gInt x := pInt x\n | gStr x := pStr x\n | gErr x := pErr x\n | gBool x := pBool x\n | (gPtr t) x := pPtr t x.val\n | (gArr n t) x := pArr t n x.vals\n | (gStruct n fs vs) x := pStruct n fs vs x.vals\n\n /-\n - Bijection between the PrimType representation and Lean types\n -/\n def td_bij: ∀ t:TypeDecl, equiv (PrimType t) (type_dict t) := λ t,\n { to_fun := to_td t,\n inv_fun := from_td t,\n left_inv := by {rintro ⟨n⟩; refl},\n right_inv := by {induction t;\n {unfold function.right_inverse,unfold function.left_inverse, intros x,\n cases x; simp },\n }}\n\n\n\n def PrimType.to_typedecl {t} (x: PrimType t): TypeDecl := t\n\n /-\n - Sometimes we don't know ahead of time if the type β that we're expecting\n - is actually equal to the type 'type_dict x' we are giving, so these as_type\n - functions handle this in a safe way.\n -/\n @[simp]\n def as_type {dt: TypeDecl}\n (t: type_dict dt) (dt':TypeDecl): option (type_dict dt') :=\n if h: dt = dt' then some (by rw ← h; exact t) else none\n\n @[simp]\n def as_type_opt {dt: TypeDecl} (t: option (type_dict dt))\n (dt': TypeDecl): option (type_dict dt') :=\n t >>= λ somet, @as_type dt somet dt'\n\nsection language_operators\n\n /-\n - Defining operators in Go\n -/\n @[derive decidable_eq]\n inductive Relop: Type | EQ | NEQ | LE\n\n @[derive decidable_eq]\n inductive Binop: Type | PLUS | MINUS | OR | AND\n\n @[derive decidable_eq]\n inductive Unop: Type | NOT | NEG\n\nend language_operators\n\nsection gostructs\n open PrimType open nat\n\n\n lemma ltsucc : ∀ n, n < n+1 :=\n by simp only [nat.succ_pos', forall_const, lt_add_iff_pos_right]\n\n def to_fin (n) (i:ℕ) : option (fin n) :=\n if h: i < n then some ⟨i,h⟩ else none\n\n def shrink' (f:finset string) (h1: f.nonempty) (ts : ∀ s ∈ f, TypeDecl):\n ∀ s ∈ (f.erase (f.min' h1)), TypeDecl := by {\n intros s h,\n rw finset.mem_erase at h,\n exact ts s h.2}\n\n /-\n - Some analogue to structural recursion for linear ordered finsets\n -/\n def shrink (f : finset string) (ts : ∀ s ∈ f, TypeDecl)\n (vals: ∀ s ∈ f, PrimType (ts s H))\n : (Σ (f': finset string) (ts': ∀ s ∈ f', TypeDecl),\n ∀ s ∈ f', PrimType (ts' s H)) :=\n if h0: f = ∅ then ⟨f, ts, λ a b, inh (ts a b)⟩\n else\n have h1: f.nonempty := finset.nonempty_of_ne_empty h0,\n have h2: ∃ a, a ∈ f.min := finset.min_of_nonempty h1,\n have mxmem: f.min' h1 ∈ f := finset.min'_mem f h1,\n have mxtyp: TypeDecl := ts (f.min' h1) mxmem,\n\n have newvals: ∀ s ∈ (f.erase (f.min' h1)), PrimType ((shrink' f h1 ts) s H), by {\n intros s h',\n rw finset.mem_erase at h', dedup,\n exact vals s h'_1.2},\n\n ⟨f.erase (f.min' h1), shrink' f h1 ts, newvals⟩\n /-\n - Add a field, value pair to an existing Struct (helper for add_key)\n -/\n def add_key' (k: string) (t: TypeDecl) (val: PrimType t)\n (f: finset string) (ts: ∀ s ∈ f, TypeDecl)\n (v : ∀ s ∈ f, PrimType (ts s H))\n : Σ(fields: finset string) (typs:∀ s ∈ fields, TypeDecl ),\n ∀ s ∈ fields, PrimType (typs s H) :=\n ⟨insert k f, λ s mem, if h: s = k then t else begin\n apply ts s, -- changes goal to needing to prove s is in old fields\n rw finset.mem_insert at mem, -- mem of insert means s=k or s ∈ f\n simp only [h, false_or] at mem, -- rule out poss. of s=k with ¬h\n exact mem end\n , λ s mem,\n if h: s=k then by {subst h, simp, exact val} else begin\n rw finset.mem_insert at mem, -- mem of insert means s=k or s ∈ f\n simp only [h, false_or] at mem, -- rule out poss. of s=k with ¬h\n have Q : (dite (s = k) (λ (h : s = k), t) (λ (h : ¬s = k), ts s mem)\n = ts s _), by { simp [h]},\n rw Q, exact v s mem\n end⟩\n\n def add_key: Π (s) (t), PrimType t → string\n → (Σ f v, Struct s f v) → (Σ f v, Struct s f v)\n | s t pt key ⟨f', ts', ⟨vs'⟩⟩ :=\n match add_key' key t pt f' ts' vs' with\n | ⟨f, ts, vs⟩ := ⟨f, ts, ⟨vs⟩⟩\n end\n\n /-\n - Convenience constructor for GoStruct\n - An arbitrary value can be used for the image of a map with an empty domain\n -/\n def GoStruct.from_list: Π(s) , list (string × (Σ t, PrimType t))\n → Σ (f) (v), Struct s f v\n | s [] := ⟨∅, (λ _ _, gBool), ⟨λ _ _, pBool ff⟩⟩ -- impossible\n | n ((k,⟨t,v⟩)::tl) := add_key n t v k (GoStruct.from_list n tl)\n\n\nend gostructs\n\nsection to_strings\n\nopen nat\n def str_typeddecl: TypeDecl → string\n | gInt := \"Int\"\n | gStr := \"Str\"\n | gErr := \"Error\"\n | gBool := \"Bool\"\n | (gPtr t) := \"*\" ++ str_typeddecl t\n | (gArr n t) := \"[\"++to_string n ++\"]\" ++ str_typeddecl t\n | (gStruct s _ _) := s\n instance: has_to_string TypeDecl := ⟨str_typeddecl⟩\n instance: has_repr TypeDecl := ⟨str_typeddecl⟩\n\n /-\n - Rendering GoPrimTypes works but relies on sorry in two places to show that\n - it terminates. The struct's fields are printed in alphabetical order.\n -/\n meta mutual def str_ptype, str_arr, str_fields\n with str_ptype: ∀ t, PrimType t → string\n | _ (pInt p) := to_string p\n | _ (pStr p) := to_string p\n | _ (pErr p) := to_string p\n | _ (pBool p) := to_string p\n | _ (pPtr t v) := \"*\" ++ to_string t ++ \"@\" ++ to_string v\n | (gArr n t) (pArr _ _ v) := \"[\" ++ str_arr n v ++ \"]\"\n | _ (@pStruct name f t v) := name ++\"{\"++ str_fields f t v ++\"}\"\n\n with str_arr: Π{n} {t}, ℕ → (fin n → PrimType t) → string\n | _ _ 0 _ := \"\"\n | n t (succ i) a := (to_fin n i).elim \"\" (λ x, str_ptype t $ a x)\n ++ str_arr i a\n with str_fields: Π(f:finset string) (ts: (∀ s ∈ f, TypeDecl)),\n (∀ s ∈ f, PrimType (ts s H)) → string\n | f ts v :=\n begin\n have e: decidable (f = ∅) := finset.has_decidable_eq f ∅,\n cases e with hf ht,\n {have h1: f.nonempty := finset.nonempty_of_ne_empty hf,\n have head: string := f.min' h1 ++ \": \" ++ (\n str_ptype (ts (f.min' h1) (finset.min'_mem f h1))\n (v (f.min' h1) (finset.min'_mem f h1)))\n ++ if f.card > 1 then \", \" else \"\",\n exact head ++ (\n match shrink f ts v with\n | ⟨a,b,c⟩ := str_fields a b c\n end )},\n {exact \"\"}\n end\n\n meta def str_gstruct (s) (f) (v) (x: Struct s f v): string :=\n str_ptype _ (pStruct s f v x.vals)\n\n meta instance :∀ t, has_to_string (PrimType t):= λ t, ⟨str_ptype t⟩\n meta instance :∀ t, has_to_string (Ptr t):=\n λ t, ⟨λ ⟨z⟩, str_ptype (gPtr t) (pPtr t z)⟩\n meta instance :∀ n t, has_to_string (Arr n t):=\n λ n t, ⟨λ ⟨z⟩, str_ptype (gArr n t) (pArr t n z)⟩\n\n meta instance: Π(s) (f) (v), has_repr (Struct s f v)\n | s f v := ⟨str_gstruct s f v⟩.\n meta instance: Π(s) (f) (v), has_to_string (Struct s f v)\n | s f v := ⟨str_gstruct s f v⟩\n\n meta instance type_dict_to_string: Π(x:TypeDecl), has_to_string (type_dict x)\n | gStr := string.has_to_string\n | gErr := string.has_to_string\n | gInt := int.has_to_string\n | gBool := bool.has_to_string\n | (gPtr t) := (Ptr.has_to_string t)\n | (gArr n t) := (Arr.has_to_string n t)\n | (gStruct n f v) := (Struct.has_to_string n f v)\n\nend to_strings\n\nsection other_instances\n\n open TypeDecl\n\n instance int_le: has_le (type_dict gInt) := int.has_le\n instance int_add: has_add (type_dict gInt) := int.has_add\n instance int_lt: has_lt (type_dict gInt) := int.has_lt\n instance int_zero: has_zero (type_dict gInt) := int.has_zero\n instance int_one: has_one (type_dict gInt) := int.has_one\n instance int_neg: has_neg (type_dict gInt) := int.has_neg\n instance int_sub: has_sub (type_dict gInt) := int.has_sub\n instance str_le: has_le (type_dict gStr) := string.has_le\n instance str_append: has_append (type_dict gStr) := string.has_append\n\nend other_instances\n\n\n/-\n\n-- /-\n-- - Two lemmas about fieldlist which help prove define GoStruct.index\n-- -/\n-- lemma fl_len_eq {s} (x: GoStruct s): x.fieldlist.length = x.len := begin\n-- induction x,\n-- simp, unfold GoStruct.fieldlist, simp,\n-- end\n\n-- lemma fl_mem {s} {x: GoStruct s} {key: string}:\n-- key ∈ x.fieldlist → key ∈ x.fields := begin\n-- intros H, induction x,\n-- unfold GoStruct.fieldlist at H, simp at H, simp, exact H\n-- end\n\n-- /-\n-- - Alternative of nth_le that also returns a proof that the return element is a\n-- - member of the original list being indexed.\n-- -/\n-- @[simp]\n-- def nth_le_mem : Π {α: Type} (l : list α) (n),\n-- n < l.length → psigma (λ a:α, a ∈ l)\n-- | _ [] n h := absurd h (nat.not_lt_zero n)\n-- | _ (a :: l) 0 h := ⟨a, by {simp}⟩\n-- | _ (a :: l) (n+1) h :=\n-- match (nth_le_mem l n (nat.le_of_succ_le_succ h)) with\n-- | ⟨q, r⟩ := ⟨q, list.mem_cons_of_mem a r⟩\n-- end\n\n-- lemma ltsucc : ∀ n, n < n+1 :=\n-- by simp only [nat.succ_pos', forall_const, lt_add_iff_pos_right]\n\n-- /-\n-- - Given an index into the (sorted) fields, return a string and a proof that it\n-- - is a member of the finset.\n-- -/\n-- def GoStruct.index {name} {n:ℕ} (x: GoStruct name)\n-- (H: n < x.len) : psigma (λ f, f ∈ x.fields) := begin\n-- have z := nth_le_mem x.fieldlist n\n-- (by {rw fl_len_eq x, exact H}),\n-- exact ⟨z.1, fl_mem z.2⟩\n-- end\n\n-- /-\n-- - Helper function from GoStruct.structvals\n-- -/\n-- def structvals': Π {n:ℕ} {s: string} {x:GoStruct s},\n-- n < x.len → list (string × GoPrimType)\n-- | 0 _ _ _ := []\n-- | (n+1) _ x h := match x.index h with\n-- | ⟨u,v ⟩ := (u, x.vals u v) ::\n-- structvals' (lt.trans (ltsucc n) h)\n-- end\n\n-- /-\n-- - key sorted list of values\n-- -/\n-- def GoStruct.pairs {s} (x: GoStruct s) : list (string × GoPrimType) :=\n-- begin\n-- cases h : x.len with n,\n-- {exact []},\n-- {have H: x.len -1 < x.len, by {rw h, simp, exact ltsucc n},\n-- exact structvals' H}\n-- end\n\n-- /-\n-- - Access a field of a struct instance with an expected type\n-- -/\n-- def check_member_fields : Π(α: GoTypeDecl) {s: string},\n-- option (GoStruct s) → string → option (type_dict α)\n-- | _ _ none _ := none\n-- | α _ (some s) field := GoStruct.get s field >>=\n-- λx, as_type (x.to_gotype.2) α\n\n\n-/", "meta": {"author": "google", "repo": "soong_verification", "sha": "a6311e81a9d099e00c1cc37aa790fc45c45ff51f", "save_path": "github-repos/lean/google-soong_verification", "path": "github-repos/lean/google-soong_verification/soong_verification-a6311e81a9d099e00c1cc37aa790fc45c45ff51f/src/seplog/_a_lang_infostruct.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41489884579676883, "lm_q2_score": 0.04535257555434333, "lm_q1q2_score": 0.0188167312514078}} {"text": "/-\nCopyright (c) 2017 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Gabriel Ebner\n\n! This file was ported from Lean 3 source module data.buffer.parser\n! leanprover-community/mathlib commit 549e2fed50b361d0d49a3dd1e7ccb6de9440059b\n! Please do not edit these lines, except to modify the commit id\n! if you have ported upstream changes.\n-/\nimport Leanbin.Data.Buffer\nimport Leanbin.Data.Dlist\n\ninductive ParseResult (α : Type)\n | done (pos : ℕ) (result : α) : ParseResult\n | fail (pos : ℕ) (expected : Dlist String) : ParseResult\n#align parse_result ParseResult\n\n/--\nThe parser monad. If you are familiar with the Parsec library in Haskell, you will understand this. -/\ndef Parser (α : Type) :=\n ∀ (input : CharBuffer) (start : ℕ), ParseResult α\n#align parser Parser\n\nnamespace Parser\n\nvariable {α β γ : Type}\n\nprotected def bind (p : Parser α) (f : α → Parser β) : Parser β := fun input pos =>\n match p input Pos with\n | ParseResult.done Pos a => f a input Pos\n | ParseResult.fail Pos expected => ParseResult.fail Pos expected\n#align parser.bind Parser.bind\n\nprotected def pure (a : α) : Parser α := fun input pos => ParseResult.done Pos a\n#align parser.pure Parser.pure\n\nprivate theorem parser.id_map (p : Parser α) : Parser.bind p Parser.pure = p :=\n by\n apply funext; intro input\n apply funext; intro pos\n dsimp only [Parser.bind]\n cases p input Pos <;> exact rfl\n#align parser.parser.id_map parser.parser.id_map\n\nprivate theorem parser.bind_assoc (p : Parser α) (q : α → Parser β) (r : β → Parser γ) :\n Parser.bind (Parser.bind p q) r = Parser.bind p fun a => Parser.bind (q a) r :=\n by\n apply funext; intro input\n apply funext; intro pos\n dsimp only [Parser.bind]\n cases p input Pos <;> try dsimp only [bind]\n cases q result input pos_1 <;> try dsimp only [bind]\n all_goals rfl\n#align parser.parser.bind_assoc parser.parser.bind_assoc\n\nprotected def fail (msg : String) : Parser α := fun _ pos =>\n ParseResult.fail Pos (Dlist.singleton msg)\n#align parser.fail Parser.fail\n\ninstance : Monad Parser where\n pure := @Parser.pure\n bind := @Parser.bind\n\ninstance : LawfulMonad Parser where\n id_map := @Parser.id_map\n pure_bind _ _ _ _ := rfl\n bind_assoc := @Parser.bind_assoc\n\ninstance : MonadFail Parser :=\n { Parser.monad with fail := @Parser.fail }\n\nprotected def failure : Parser α := fun _ pos => ParseResult.fail Pos Dlist.empty\n#align parser.failure Parser.failure\n\nprotected def orelse (p q : Parser α) : Parser α := fun input pos =>\n match p input Pos with\n | ParseResult.fail pos₁ expected₁ =>\n if pos₁ ≠ Pos then ParseResult.fail pos₁ expected₁\n else\n match q input Pos with\n | ParseResult.fail pos₂ expected₂ =>\n if pos₁ < pos₂ then ParseResult.fail pos₁ expected₁\n else\n if pos₂ < pos₁ then ParseResult.fail pos₂ expected₂\n else-- pos₁ = pos₂\n ParseResult.fail\n pos₁ (expected₁ ++ expected₂)\n | ok => ok\n | ok => ok\n#align parser.orelse Parser.orelse\n\ninstance : Alternative Parser where\n failure := @Parser.failure\n orelse := @Parser.orelse\n\ninstance : Inhabited (Parser α) :=\n ⟨Parser.failure⟩\n\n/-- Overrides the expected token name, and does not consume input on failure. -/\ndef decorateErrors (msgs : Thunk (List String)) (p : Parser α) : Parser α := fun input pos =>\n match p input Pos with\n | ParseResult.fail _ expected => ParseResult.fail Pos (Std.DList.lazy_ofList (msgs ()))\n | ok => ok\n#align parser.decorate_errors Parser.decorateErrors\n\n/-- Overrides the expected token name, and does not consume input on failure. -/\ndef decorateError (msg : Thunk String) (p : Parser α) : Parser α :=\n decorateErrors [msg ()] p\n#align parser.decorate_error Parser.decorateError\n\n/-- Matches a single character. Fails only if there is no more input. -/\ndef anyChar : Parser Char := fun input pos =>\n if h : Pos < input.size then\n let c := input.read ⟨Pos, h⟩\n ParseResult.done (Pos + 1) c\n else ParseResult.fail Pos Dlist.empty\n#align parser.any_char Parser.anyChar\n\n/-- Matches a single character satisfying the given predicate. -/\ndef sat (p : Char → Prop) [DecidablePred p] : Parser Char := fun input pos =>\n if h : Pos < input.size then\n let c := input.read ⟨Pos, h⟩\n if p c then ParseResult.done (Pos + 1) c else ParseResult.fail Pos Dlist.empty\n else ParseResult.fail Pos Dlist.empty\n#align parser.sat Parser.sat\n\n/-- Matches the empty word. -/\ndef eps : Parser Unit :=\n return ()\n#align parser.eps Parser.eps\n\n/-- Matches the given character. -/\ndef ch (c : Char) : Parser Unit :=\n decorateError c.toString <| sat (· = c) >> eps\n#align parser.ch Parser.ch\n\n/-- Matches a whole char_buffer. Does not consume input in case of failure. -/\ndef charBuf (s : CharBuffer) : Parser Unit :=\n decorateError s.toString <| s.toList.mapM' ch\n#align parser.char_buf Parser.charBuf\n\n/-- Matches one out of a list of characters. -/\ndef oneOf (cs : List Char) : Parser Char :=\n (decorateErrors do\n let c ← cs\n return c) <|\n sat (· ∈ cs)\n#align parser.one_of Parser.oneOf\n\ndef oneOf' (cs : List Char) : Parser Unit :=\n oneOf cs >> eps\n#align parser.one_of' Parser.oneOf'\n\n/-- Matches a string. Does not consume input in case of failure. -/\ndef str (s : String) : Parser Unit :=\n decorateError s <| s.toList.mapM' ch\n#align parser.str Parser.str\n\n/-- Number of remaining input characters. -/\ndef remaining : Parser ℕ := fun input pos => ParseResult.done Pos (input.size - Pos)\n#align parser.remaining Parser.remaining\n\n/-- Matches the end of the input. -/\ndef eof : Parser Unit :=\n decorateError \"\" do\n let rem ← remaining\n guard <| rem = 0\n#align parser.eof Parser.eof\n\ndef foldrCore (f : α → β → β) (p : Parser α) (b : β) : ∀ reps : ℕ, Parser β\n | 0 => failure\n | reps + 1 =>\n (do\n let x ← p\n let xs ← foldr_core reps\n return (f x xs)) <|>\n return b\n#align parser.foldr_core Parser.foldrCore\n\n/-- Matches zero or more occurrences of `p`, and folds the result. -/\ndef foldr (f : α → β → β) (p : Parser α) (b : β) : Parser β := fun input pos =>\n foldrCore f p b (input.size - Pos + 1) input Pos\n#align parser.foldr Parser.foldr\n\ndef foldlCore (f : α → β → α) : ∀ (a : α) (p : Parser β) (reps : ℕ), Parser α\n | a, p, 0 => failure\n | a, p, reps + 1 =>\n (do\n let x ← p\n foldl_core (f a x) p reps) <|>\n return a\n#align parser.foldl_core Parser.foldlCore\n\n/-- Matches zero or more occurrences of `p`, and folds the result. -/\ndef foldl (f : α → β → α) (a : α) (p : Parser β) : Parser α := fun input pos =>\n foldlCore f a p (input.size - Pos + 1) input Pos\n#align parser.foldl Parser.foldl\n\n/-- Matches zero or more occurrences of `p`. -/\ndef many (p : Parser α) : Parser (List α) :=\n foldr List.cons p []\n#align parser.many Parser.many\n\ndef manyChar (p : Parser Char) : Parser String :=\n List.asString <$> many p\n#align parser.many_char Parser.manyChar\n\n/-- Matches zero or more occurrences of `p`. -/\ndef many' (p : Parser α) : Parser Unit :=\n many p >> eps\n#align parser.many' Parser.many'\n\n/-- Matches one or more occurrences of `p`. -/\ndef many1 (p : Parser α) : Parser (List α) :=\n List.cons <$> p <*> many p\n#align parser.many1 Parser.many1\n\n/-- Matches one or more occurences of the char parser `p` and implodes them into a string. -/\ndef manyChar1 (p : Parser Char) : Parser String :=\n List.asString <$> many1 p\n#align parser.many_char1 Parser.manyChar1\n\n/-- Matches one or more occurrences of `p`, separated by `sep`. -/\ndef sepBy1 (sep : Parser Unit) (p : Parser α) : Parser (List α) :=\n List.cons <$> p <*> many (sep >> p)\n#align parser.sep_by1 Parser.sepBy1\n\n/-- Matches zero or more occurrences of `p`, separated by `sep`. -/\ndef sepBy (sep : Parser Unit) (p : Parser α) : Parser (List α) :=\n sepBy1 sep p <|> return []\n#align parser.sep_by Parser.sepBy\n\ndef fixCore (F : Parser α → Parser α) : ∀ max_depth : ℕ, Parser α\n | 0 => failure\n | max_depth + 1 => F (fix_core max_depth)\n#align parser.fix_core Parser.fixCore\n\n/-- Matches a digit (0-9). -/\ndef digit : Parser Nat :=\n decorateError \"\" do\n let c ← sat fun c => '0' ≤ c ∧ c ≤ '9'\n pure <| c - '0'.toNat\n#align parser.digit Parser.digit\n\n/-- Matches a natural number. Large numbers may cause performance issues, so\ndon't run this parser on untrusted input. -/\ndef nat : Parser Nat :=\n decorateError \"\" do\n let digits ← many1 digit\n pure <|\n Prod.fst <|\n digits (fun digit ⟨Sum, magnitude⟩ => ⟨Sum + digit * magnitude, magnitude * 10⟩) ⟨0, 1⟩\n#align parser.nat Parser.nat\n\n/-- Fixpoint combinator satisfying `fix F = F (fix F)`. -/\ndef fix (F : Parser α → Parser α) : Parser α := fun input pos =>\n fixCore F (input.size - Pos + 1) input Pos\n#align parser.fix Parser.fix\n\nprivate def make_monospaced : Char → Char\n | '\\n' => ' '\n | '\\t' => ' '\n | '\\x0d' => ' '\n | c => c\n#align parser.make_monospaced parser.make_monospaced\n\ndef mkErrorMsg (input : CharBuffer) (pos : ℕ) (expected : Dlist String) : CharBuffer :=\n let left_ctx := (input.take Pos).takeRight 10\n let right_ctx := (input.drop Pos).take 10\n (left_ctx.map makeMonospaced ++ right_ctx.map makeMonospaced ++ \"\\n\".toCharBuffer ++\n left_ctx.map fun _ => ' ') ++\n \"^\\n\".toCharBuffer ++\n \"\\n\".toCharBuffer ++\n \"expected: \".toCharBuffer ++\n String.toCharBuffer (\" | \".intercalate expected.toList) ++\n \"\\n\".toCharBuffer\n#align parser.mk_error_msg Parser.mkErrorMsg\n\n/-- Runs a parser on the given input. The parser needs to match the complete input. -/\ndef run (p : Parser α) (input : CharBuffer) : Sum String α :=\n match (p <* eof) input 0 with\n | ParseResult.done Pos res => Sum.inr res\n | ParseResult.fail Pos expected => Sum.inl <| Buffer.toString <| mkErrorMsg input Pos expected\n#align parser.run Parser.run\n\n/-- Runs a parser on the given input. The parser needs to match the complete input. -/\ndef runString (p : Parser α) (input : String) : Sum String α :=\n run p input.toCharBuffer\n#align parser.run_string Parser.runString\n\nend Parser\n\n", "meta": {"author": "leanprover-community", "repo": "lean3port", "sha": "9ed1898f23e4379865ee93d62cb6353e5ed6c270", "save_path": "github-repos/lean/leanprover-community-lean3port", "path": "github-repos/lean/leanprover-community-lean3port/lean3port-9ed1898f23e4379865ee93d62cb6353e5ed6c270/Leanbin/Data/Buffer/Parser.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35220178204788966, "lm_q2_score": 0.05340332678672523, "lm_q1q2_score": 0.018808746861570427}} {"text": "/-\nCopyright (c) 2019 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Leonardo de Moura\n-/\nimport Lean.Compiler.IR.Basic\nimport Lean.Compiler.IR.LiveVars\nimport Lean.Compiler.IR.Format\n\nnamespace Lean.IR.ResetReuse\n/- Remark: the insertResetReuse transformation is applied before we have\n inserted `inc/dec` instructions, and perfomed lower level optimizations\n that introduce the instructions `release` and `set`. -/\n\n/- Remark: the functions `S`, `D` and `R` defined here implement the\n corresponding functions in the paper \"Counting Immutable Beans\"\n\n Here are the main differences:\n - We use the State monad to manage the generation of fresh variable names.\n - Support for join points, and `uset` and `sset` instructions for unboxed data.\n - `D` uses the auxiliary function `Dmain`.\n - `Dmain` returns a pair `(b, found)` to avoid quadratic behavior when checking\n the last occurrence of the variable `x`.\n - Because we have join points in the actual implementation, a variable may be live even if it\n does not occur in a function body. See example at `livevars.lean`.\n-/\n\nprivate def mayReuse (c₁ c₂ : CtorInfo) : Bool :=\n c₁.size == c₂.size && c₁.usize == c₂.usize && c₁.ssize == c₂.ssize &&\n /- The following condition is a heuristic.\n We don't want to reuse cells from different types even when they are compatible\n because it produces counterintuitive behavior. -/\n c₁.name.getPrefix == c₂.name.getPrefix\n\nprivate partial def S (w : VarId) (c : CtorInfo) : FnBody → FnBody\n | FnBody.vdecl x t v@(Expr.ctor c' ys) b =>\n if mayReuse c c' then\n let updtCidx := c.cidx != c'.cidx\n FnBody.vdecl x t (Expr.reuse w c' updtCidx ys) b\n else\n FnBody.vdecl x t v (S w c b)\n | FnBody.jdecl j ys v b =>\n let v' := S w c v\n if v == v' then FnBody.jdecl j ys v (S w c b)\n else FnBody.jdecl j ys v' b\n | FnBody.case tid x xType alts => FnBody.case tid x xType <| alts.map fun alt => alt.modifyBody (S w c)\n | b =>\n if b.isTerminal then b\n else let\n (instr, b) := b.split\n instr.setBody (S w c b)\n\n/- We use `Context` to track join points in scope. -/\nabbrev M := ReaderT LocalContext (StateT Index Id)\n\nprivate def mkFresh : M VarId := do\n let idx ← getModify (fun n => n + 1)\n pure { idx := idx }\n\nprivate def tryS (x : VarId) (c : CtorInfo) (b : FnBody) : M FnBody := do\n let w ← mkFresh\n let b' := S w c b\n if b == b' then pure b\n else pure $ FnBody.vdecl w IRType.object (Expr.reset c.size x) b'\n\nprivate def Dfinalize (x : VarId) (c : CtorInfo) : FnBody × Bool → M FnBody\n | (b, true) => pure b\n | (b, false) => tryS x c b\n\nprivate def argsContainsVar (ys : Array Arg) (x : VarId) : Bool :=\n ys.any fun arg => match arg with\n | Arg.var y => x == y\n | _ => false\n\nprivate def isCtorUsing (b : FnBody) (x : VarId) : Bool :=\n match b with\n | (FnBody.vdecl _ _ (Expr.ctor _ ys) _) => argsContainsVar ys x\n | _ => false\n\n/- Given `Dmain b`, the resulting pair `(new_b, flag)` contains the new body `new_b`,\n and `flag == true` if `x` is live in `b`.\n\n Note that, in the function `D` defined in the paper, for each `let x := e; F`,\n `D` checks whether `x` is live in `F` or not. This is great for clarity but it\n is expensive: `O(n^2)` where `n` is the size of the function body. -/\nprivate partial def Dmain (x : VarId) (c : CtorInfo) : FnBody → M (FnBody × Bool)\n | e@(FnBody.case tid y yType alts) => do\n let ctx ← read\n if e.hasLiveVar ctx x then do\n /- If `x` is live in `e`, we recursively process each branch. -/\n let alts ← alts.mapM fun alt => alt.mmodifyBody fun b => Dmain x c b >>= Dfinalize x c\n pure (FnBody.case tid y yType alts, true)\n else pure (e, false)\n | FnBody.jdecl j ys v b => do\n let (b, found) ← withReader (fun ctx => ctx.addJP j ys v) (Dmain x c b)\n let (v, _ /- found' -/) ← Dmain x c v\n /- If `found' == true`, then `Dmain b` must also have returned `(b, true)` since\n we assume the IR does not have dead join points. So, if `x` is live in `j` (i.e., `v`),\n then it must also live in `b` since `j` is reachable from `b` with a `jmp`.\n On the other hand, `x` may be live in `b` but dead in `j` (i.e., `v`). -/\n pure (FnBody.jdecl j ys v b, found)\n | e => do\n let ctx ← read\n if e.isTerminal then\n pure (e, e.hasLiveVar ctx x)\n else do\n let (instr, b) := e.split\n if isCtorUsing instr x then\n /- If the scrutinee `x` (the one that is providing memory) is being\n stored in a constructor, then reuse will probably not be able to reuse memory at runtime.\n It may work only if the new cell is consumed, but we ignore this case. -/\n pure (e, true)\n else\n let (b, found) ← Dmain x c b\n /- Remark: it is fine to use `hasFreeVar` instead of `hasLiveVar`\n since `instr` is not a `FnBody.jmp` (it is not a terminal) nor it is a `FnBody.jdecl`. -/\n if found || !instr.hasFreeVar x then\n pure (instr.setBody b, found)\n else\n let b ← tryS x c b\n pure (instr.setBody b, true)\n\nprivate def D (x : VarId) (c : CtorInfo) (b : FnBody) : M FnBody :=\n Dmain x c b >>= Dfinalize x c\n\npartial def R : FnBody → M FnBody\n | FnBody.case tid x xType alts => do\n let alts ← alts.mapM fun alt => do\n let alt ← alt.mmodifyBody R\n match alt with\n | Alt.ctor c b =>\n if c.isScalar then pure alt\n else Alt.ctor c <$> D x c b\n | _ => pure alt\n pure $ FnBody.case tid x xType alts\n | FnBody.jdecl j ys v b => do\n let v ← R v\n let b ← withReader (fun ctx => ctx.addJP j ys v) (R b)\n pure $ FnBody.jdecl j ys v b\n | e => do\n if e.isTerminal then pure e\n else do\n let (instr, b) := e.split\n let b ← R b\n pure (instr.setBody b)\n\nend ResetReuse\n\nopen ResetReuse\n\ndef Decl.insertResetReuse (d : Decl) : Decl :=\n match d with\n | Decl.fdecl (body := b) ..=>\n let nextIndex := d.maxIndex + 1\n let bNew := (R b {}).run' nextIndex\n d.updateBody! bNew\n | other => other\n\nend Lean.IR\n", "meta": {"author": "Kha", "repo": "lean4-nightly", "sha": "b4c92de57090e6c47b29d3575df53d86fce52752", "save_path": "github-repos/lean/Kha-lean4-nightly", "path": "github-repos/lean/Kha-lean4-nightly/lean4-nightly-b4c92de57090e6c47b29d3575df53d86fce52752/stage0/src/Lean/Compiler/IR/ResetReuse.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2782567937024021, "lm_q2_score": 0.06754668973182397, "lm_q1q2_score": 0.018795325309988304}} {"text": "import data.list.basic -- basic operations on `list`\nimport data.option.basic -- basic operations on `option`\nimport data.set.basic\nimport data.vector\nimport data.vector2\nimport logic.function -- function update and inverses\nimport aux\n\nnamespace parlang\nvariables {n : ℕ} {σ : Type} {ι : Type} {τ : ι → Type} [decidable_eq ι]\n\n/-\nWe use the following conventions for type variables:\n\n `σ` -- thread internal states\n `ι` -- shared memory index\n `τ` -- shared memory type map\n\n-/\n\n/-- Kernel of a parallel program.\n\nThe general idea is to not have explicit expressions, but use Lean functions to compute values. What\nwe are explicit shared loads and stores.\n\nΣ is constructor where the second argument may depend on the type of the first (in this case i). Can be constructed using ⟨...⟩\n-/\ninductive kernel {ι : Type} (σ : Type) (τ : ι → Type) : Type\n| load : (σ → (Σi:ι, (τ i → σ))) → kernel\n| store : (σ → (Σi:ι, τ i)) → kernel\n| compute {} : (σ → σ) → kernel\n| seq : kernel → kernel → kernel\n| ite : (σ → bool) → kernel → kernel → kernel\n| loop : (σ → bool) → kernel → kernel\n| sync {} : kernel\n\ninfixr ` ;; `:90 := kernel.seq\nopen kernel\n\n/-- Memory view -/\ndef memory {ι : Type} (τ : ι → Type) := Π (i : ι), τ i\n\nnamespace memory\n\ndef get (m : memory τ) (i : ι) : τ i := m i\n\ndef update (m : memory τ) (i : ι) (v : τ i) : memory τ := function.update m i v\n\nend memory\n\n/-- Thread state inclusing a shared memory *view*, the list of loads and stores tells what should\ndiffer between differnet threads. -/\nstructure thread_state {ι : Type} (σ : Type) (τ : ι → Type) : Type :=\n(tlocal : σ)\n(shared : memory τ)\n(loads : set ι := ∅)\n(stores : set ι := ∅)\n\nnamespace thread_state\n\ndef load (f : σ → (Σi:ι, (τ i → σ))) (t : thread_state σ τ) : thread_state σ τ :=\nlet ⟨i, tr⟩ := f t.tlocal in\n{ tlocal := tr (t.shared.get i),\n loads := insert i t.loads,\n .. t }\n\ndef store (f : σ → (Σi:ι, τ i)) (t : thread_state σ τ) : thread_state σ τ :=\nlet ⟨i, v⟩ := f t.tlocal in\n{ shared := t.shared.update i v,\n stores := insert i t.stores,\n .. t}\n\ndef compute (f : σ → σ) (t : thread_state σ τ) : thread_state σ τ :=\n{ tlocal := f t.tlocal,\n .. t}\n\ndef sync (g : memory τ) (t : thread_state σ τ) : thread_state σ τ :=\n{ shared := g,\n loads := ∅,\n stores := ∅,\n .. t}\n\ndef accesses (t : thread_state σ τ) : set ι := t.stores ∪ t.loads\n\nend thread_state\n\ndef no_thread_active (ac : vector bool n) : bool := ¬ac.to_list.any id\ndef any_thread_active (ac : vector bool n) : bool := ac.to_list.any id\ndef all_threads_active (ac : vector bool n) : bool := ac.to_list.all id\n/-- thread can only be active either in ac₁ or ac₂ -/\ndef ac_distinct (ac₁ ac₂ : vector bool n) : Prop := ∀ (i : fin n), ac₁.nth i = ff ∨ ac₂.nth i = ff\n\ndef ac_ge (ac' : vector bool n) (ac : vector bool n) : Prop := ∀ (t : fin n), ¬ (ac.nth t) → ¬ (ac'.nth t)\ninstance : has_le (vector bool n) := ⟨ac_ge⟩\n\n/-- shared program state -/\nstructure state {ι : Type} (n : ℕ) (σ : Type) (τ : ι → Type) : Type :=\n(threads : vector (thread_state σ τ) n)\n\nnamespace state\n\ndef map_threads (f : thread_state σ τ → thread_state σ τ) (s : state n σ τ) : state n σ τ :=\n{ threads := s.threads.map f, ..s }\n\n-- we generally don't want to unfold this if possible\n-- this would for example happen when you do cases in (exec_state (compute f) ...) \n-- TODO: rename this to mat? It would shorten a lot of names\n@[irreducible]\ndef map_active_threads (ac : vector bool n) (f : thread_state σ τ → thread_state σ τ) (s : state n σ τ) : state n σ τ :=\n{ threads := (s.threads.map₂ (λ t (a : bool), if a then f t else t) ac), ..s }\n\ndef active_threads (ac : vector bool n) (s : state n σ τ) : list (thread_state σ τ) :=\n((s.threads.map₂ prod.mk ac).to_list.filter (λ c : (thread_state σ τ × bool), c.2)).map (λ ⟨t, a⟩, t)\n\n-- case 1: no thread changed ι and shadows must be equal at ι\n-- case 2: thread t changed ι and all other threads must not access ι\ndef syncable (s : state n σ τ) (m : memory τ) : Prop :=\n∀i:ι,\n (∀ tid, i ∉ (s.threads.nth tid).stores ∧ m i = (s.threads.nth tid).shared i) ∨\n (∃ tid, i ∈ (s.threads.nth tid).stores ∧ m i = (s.threads.nth tid).shared i ∧\n (∀ tid', tid ≠ tid' → i ∉ (s.threads.nth tid').accesses))\n\ndef precedes (s u : state n σ τ) : Prop :=\n∀ (t : thread_state σ τ × thread_state σ τ), t ∈ (s.threads.map₂ prod.mk u.threads) → t.1.stores ⊆ t.2.stores ∧ t.1.loads ⊆ t.2.loads\n\nend state\n\n/-- If condition *f* evaluates to *tt*, the thread is deactivated -/\n@[irreducible]\ndef deactivate_threads (f : σ → bool) (ac : vector bool n) (s : state n σ τ) : vector bool n := \nac.map₂ (λ a (ts : thread_state σ τ), (bnot ∘ f) ts.tlocal && a) s.threads\n\ndef subkernel (q : kernel σ τ) : kernel σ τ → Prop\n| (seq k₁ k₂) := k₁ = q ∨ k₂ = q ∨ subkernel k₁ ∨ subkernel k₂\n| (ite c th el) := th = q ∨ el = q ∨ subkernel th ∨ subkernel el\n| (loop c body) := body = q ∨ subkernel body\n| k := k = q\n\n/-- Execute a kernel on a shared state, i.e. a list of threads -/\ninductive exec_state {n : ℕ} : kernel σ τ → vector bool n → state n σ τ → state n σ τ → Prop\n| load (f) (s : state n σ τ) (ac : vector bool n) :\n exec_state (load f) ac s (s.map_active_threads ac $ thread_state.load f)\n| store (f) (s : state n σ τ) (ac : vector bool n) :\n exec_state (store f) ac s (s.map_active_threads ac $ thread_state.store f)\n| compute (f : σ → σ) (s : state n σ τ) (ac : vector bool n) :\n exec_state (compute f) ac s (s.map_active_threads ac $ thread_state.compute f)\n| sync_all (s : state n σ τ) (ac : vector bool n) (m : memory τ) (hs : s.syncable m)\n (ha : all_threads_active ac) :\n exec_state sync ac s (s.map_threads $ thread_state.sync m)\n| sync_none (s : state n σ τ) (ac : vector bool n) (h : no_thread_active ac) :\n exec_state sync ac s s\n| seq (s t u : state n σ τ) (ac : vector bool n) (k₁ k₂ : kernel σ τ) :\n exec_state k₁ ac s t → exec_state k₂ ac t u → exec_state (seq k₁ k₂) ac s u\n -- in the then-branch we deactivate the threads where the condition is false and similar for else\n| ite (s t u : state n σ τ) (ac : vector bool n) (f : σ → bool) (k₁ k₂ : kernel σ τ) :\n exec_state k₁ (deactivate_threads (bnot ∘ f) ac s) s t →\n exec_state k₂ (deactivate_threads f ac s) t u →\n exec_state (ite f k₁ k₂) ac s u\n| loop_stop (s : state n σ τ) (ac : vector bool n) (f : σ → bool) (k : kernel σ τ) :\n no_thread_active (deactivate_threads (bnot ∘ f) ac s) →\n exec_state (loop f k) ac s s\n| loop_step (s t u : state n σ τ) (ac : vector bool n) (f : σ → bool) (k : kernel σ τ) :\n any_thread_active (deactivate_threads (bnot ∘ f) ac s) →\n exec_state k (deactivate_threads (bnot ∘ f) ac s) s t →\n exec_state (loop f k) (deactivate_threads (bnot ∘ f) ac s) t u →\n exec_state (loop f k) ac s u\n\ndef kernel_transform_func (k) (f) (n) (ac) : Prop := ∀ (s u : state n σ τ), exec_state k ac s u ↔ (u = s.map_active_threads ac f)\n\ndef contains_sync : kernel σ τ → Prop\n| (sync) := true\n| (seq k₁ k₂) := contains_sync k₁ ∨ contains_sync k₂\n| (load _) := false\n| (store _) := false\n| (compute _) := false\n| (ite c k₁ k₂) := contains_sync k₁ ∨ contains_sync k₂\n| (loop c k) := contains_sync k\n\ninductive program {ι : Type} (σ : Type) (τ : ι → Type)\n| intro (f : memory τ → ℕ) (k : kernel σ τ) : program\n\ndef state_initializer := ℕ → σ\n\n@[reducible]\ndef init_state (init : ℕ → σ) (f : memory τ → ℕ) (m : memory τ) : state (f m) σ τ := \n{ threads := (vector.range (f m)).map (λ n, { tlocal := init n, shared := m, loads := ∅, stores := ∅ })}\n\ninductive exec_prog : (ℕ → σ) → program σ τ → memory τ → memory τ → Prop\n| intro (k : kernel σ τ) (f : memory τ → ℕ) (a b : memory τ) (init : ℕ → σ) (s' : state (f a) σ τ) (hsync : s'.syncable b)\n (he : exec_state k (vector.repeat tt (f a)) (init_state init f a) s') : \n exec_prog init (program.intro f k) a b\n\ndef list_to_kernel_seq (ks : list (kernel σ τ)) : kernel σ τ := ks.foldl (λ k₁ k₂, k₁ ;; k₂) (kernel.compute id)\n\nend parlang", "meta": {"author": "fischerman", "repo": "GPU-transformation-verifier", "sha": "75a5016f05382738ff93ce5859c4cfa47ccb63c1", "save_path": "github-repos/lean/fischerman-GPU-transformation-verifier", "path": "github-repos/lean/fischerman-GPU-transformation-verifier/GPU-transformation-verifier-75a5016f05382738ff93ce5859c4cfa47ccb63c1/src/parlang/defs.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4726834617637482, "lm_q2_score": 0.039638836264712776, "lm_q1q2_score": 0.018736622345890838}} {"text": "/-\nCopyright (c) 2016 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Leonardo de Moura\n-/\nprelude\nimport init.meta.declaration init.meta.exceptional init.data.option.basic\nimport init.meta.rb_map\n\n/-- An __environment__ contains all of the declarations and notation that have been defined so far. -/\nmeta constant environment : Type\n\nnamespace environment\n/--\nConsider a type `ψ` which is an inductive datatype using a single constructor `mk (a : α) (b : β) : ψ`.\nLean will automatically make two projection functions `a : ψ → α`, `b : ψ → β`.\nLean tags these declarations as __projections__.\nThis helps the simplifier / rewriter not have to expand projectors.\nEg `a (mk x y)` will automatically reduce to `x`.\nIf you `extend` a structure, all of the projections on the parent will also be created for the child.\nProjections are also treated differently in the VM for efficiency.\n\nNote that projections have nothing to do with the dot `mylist.map` syntax.\n\nYou can find out if a declaration is a projection using `environment.is_projection` which returns `projection_info`.\n\nData for a projection declaration:\n- `cname` is the name of the constructor associated with the projection.\n- `nparams` is the number of constructor parameters. Eg `and.intro` has two type parameters.\n- `idx` is the parameter being projected by this projection.\n- `is_class` is tt iff this is a typeclass projection.\n\n### Examples:\n\n- `and.right` is a projection with ``{cname := `and.intro, nparams := 2, idx := 1, is_class := ff}``\n- `ordered_ring.neg` is a projection with ``{cname := `ordered_ring.mk, nparams := 1, idx := 5, is_class := tt}``.\n\n-/\nstructure projection_info :=\n(cname : name)\n(nparams : nat)\n(idx : nat)\n(is_class : bool)\n\n/-- A marking on the binders of structures and inductives indicating\n how this constructor should mark its parameters.\n\n inductive foo\n | one {} : foo -> foo -- relaxed_implicit\n | two ( ) : foo -> foo -- explicit\n | two [] : foo -> foo -- implicit\n | three : foo -> foo -- relaxed implicit (default)\n-/\ninductive implicit_infer_kind | implicit | relaxed_implicit | none\ninstance implicit_infer_kind.inhabited : inhabited implicit_infer_kind := ⟨implicit_infer_kind.implicit⟩\n\n/-- One introduction rule in an inductive declaration -/\nmeta structure intro_rule :=\n(constr : name)\n(type : expr)\n(infer : implicit_infer_kind := implicit_infer_kind.implicit)\n\n/-- Create a standard environment using the given trust level -/\nmeta constant mk_std : nat → environment\n/-- Return the trust level of the given environment -/\nmeta constant trust_lvl : environment → nat\n/-- Add a new declaration to the environment -/\nmeta constant add : environment → declaration → exceptional environment\n/-- make declaration `n` protected -/\nmeta constant mk_protected : environment → name → environment\n\n/-- add declaration `d` and make it protected -/\nmeta def add_protected (env : environment) (d : declaration) : exceptional environment := do\nenv ← env.add d,\npure $ env.mk_protected d.to_name\n\n/-- check if `n` is the name of a protected declaration -/\nmeta constant is_protected : environment → name → bool\n/-- Retrieve a declaration from the environment -/\nmeta constant get : environment → name → exceptional declaration\nmeta def contains (env : environment) (d : name) : bool :=\nmatch env.get d with\n| exceptional.success _ := tt\n| exceptional.exception _ := ff\nend\n\nmeta constant add_defn_eqns (env : environment) (opt : options)\n (lp_params : list name) (params : list expr) (sig : expr)\n (eqns : list (list (expr ff) × expr)) (is_meta : bool) : exceptional environment\n\n/-- Register the given name as a namespace, making it available to the `open` command -/\nmeta constant add_namespace : environment → name → environment\n/-- Mark a namespace as open -/\nmeta constant mark_namespace_as_open : environment -> name -> environment\n/-- Modify the environment as if `open %%name` had been parsed -/\nmeta constant execute_open : environment -> name -> environment\n/-- Retrieve all registered namespaces -/\nmeta constant get_namespaces : environment -> list name\n/-- Return tt iff the given name is a namespace -/\nmeta constant is_namespace : environment → name → bool\n/-- Add a new inductive datatype to the environment\n name, universe parameters, number of parameters, type, constructors (name and type), is_meta -/\nmeta constant add_inductive (env : environment)\n (n : name) (levels : list name) (num_params : nat) (type : expr)\n (intros : list (name × expr)) (is_meta : bool) : exceptional environment\n/-- Add a new general inductive declaration to the environment.\n This has the same effect as a `inductive` in the file, including generating\n all the auxiliary definitions, as well as triggering mutual/nested inductive\n compilation, by contrast to `environment.add_inductive` which only adds the\n core axioms supported by the kernel.\n\n The `inds` argument should be a list of inductives in the mutual family.\n The first argument is a pair of the name of the type being constructed\n and the type of this inductive family (not including the params).\n The second argument is a list of intro rules, specified by a name, an\n `implicit_infer_kind` giving the implicitness of the params for this constructor,\n and an expression with the type of the constructor (not including the params).\n-/\nmeta constant add_ginductive (env : environment) (opt : options)\n (levels : list name) (params : list expr)\n (inds : list ((name × expr) × list intro_rule))\n (is_meta : bool) : exceptional environment\n/-- Return tt iff the given name is an inductive datatype -/\nmeta constant is_inductive : environment → name → bool\n/-- Return tt iff the given name is a constructor -/\nmeta constant is_constructor : environment → name → bool\n/-- Return tt iff the given name is a recursor -/\nmeta constant is_recursor : environment → name → bool\n/-- Return tt iff the given name is a recursive inductive datatype -/\nmeta constant is_recursive : environment → name → bool\n/-- Return the name of the inductive datatype of the given constructor. -/\nmeta constant inductive_type_of : environment → name → option name\n/-- Return the constructors of the inductive datatype with the given name -/\nmeta constant constructors_of : environment → name → list name\n/-- Return the recursor of the given inductive datatype -/\nmeta constant recursor_of : environment → name → option name\n/-- Return the number of parameters of the inductive datatype -/\nmeta constant inductive_num_params : environment → name → nat\n/-- Return the number of indices of the inductive datatype -/\nmeta constant inductive_num_indices : environment → name → nat\n/-- Return tt iff the inductive datatype recursor supports dependent elimination -/\nmeta constant inductive_dep_elim : environment → name → bool\n/-- Functionally equivalent to `is_inductive`.\n\nTechnically, this works by checking if the name is in the ginductive environment\nextension which is outside the kernel, whereas `is_inductive` works by looking at the kernel extension.\nBut there are no `is_inductive`s which are not `is_ginductive`.\n -/\nmeta constant is_ginductive : environment → name → bool\n/-- See the docstring for `projection_info`. -/\nmeta constant is_projection : environment → name → option projection_info\n/-- Fold over declarations in the environment. -/\nmeta constant fold {α :Type} : environment → α → (declaration → α → α) → α\n/-- `relation_info env n` returns some value if n is marked as a relation in the given environment.\n the tuple contains: total number of arguments of the relation, lhs position and rhs position. -/\nmeta constant relation_info : environment → name → option (nat × nat × nat)\n/-- `refl_for env R` returns the name of the reflexivity theorem for the relation R -/\nmeta constant refl_for : environment → name → option name\n/-- `symm_for env R` returns the name of the symmetry theorem for the relation R -/\nmeta constant symm_for : environment → name → option name\n/-- `trans_for env R` returns the name of the transitivity theorem for the relation R -/\nmeta constant trans_for : environment → name → option name\n/-- `decl_olean env d` returns the name of the .olean file where d was defined.\n The result is none if d was not defined in an imported file. -/\nmeta constant decl_olean : environment → name → option string\n/-- `decl_pos env d` returns the source location of d if available. -/\nmeta constant decl_pos : environment → name → option pos\n/-- `decl_pos env d` returns the name of a declaration that d inherits\nnoncomputability from, or `none` if it is computable.\n\nNote that this also returns `none` on `axiom`s and `constant`s. These can be detected by using\n`environment.get_decl` and `declaration.is_axiom` and `declaration.is_constant`. -/\nmeta constant decl_noncomputable_reason : environment → name → option name\n/-- Return the fields of the structure with the given name, or `none` if it is not a structure -/\nmeta constant structure_fields : environment → name → option (list name)\n/-- `get_class_attribute_symbols env attr_name` return symbols\n occurring in instances of type classes tagged with the attribute `attr_name`.\n Example: [algebra] -/\nmeta constant get_class_attribute_symbols : environment → name → name_set\n/-- The fingerprint of the environment is a hash formed from all of the declarations in the environment. -/\nmeta constant fingerprint : environment → nat\n\n/-- Gets the equation lemmas for the declaration `n`. -/\nmeta constant get_eqn_lemmas_for (env : environment) (n : name) : list name\n/-- Gets the equation lemmas for the declaration `n`, including lemmas for match statements, etc. -/\nmeta constant get_ext_eqn_lemmas_for (env : environment) (n : name) : list name\n/--\nAdds the equation lemma `n`.\nIt is added for the declaration `t.pi_codomain.get_app_fn.const_name` where `t` is the type of the equation lemma.\n-/\nmeta constant add_eqn_lemma (env : environment) (n : name) : environment\n\nopen expr\n\nmeta constant unfold_untrusted_macros : environment → expr → expr\nmeta constant unfold_all_macros : environment → expr → expr\n\nmeta def is_constructor_app (env : environment) (e : expr) : bool :=\nis_constant (get_app_fn e) && is_constructor env (const_name (get_app_fn e))\n\nmeta def is_refl_app (env : environment) (e : expr) : option (name × expr × expr) :=\nmatch (refl_for env (const_name (get_app_fn e))) with\n| (some n) :=\n if get_app_num_args e ≥ 2\n then some (n, app_arg (app_fn e), app_arg e)\n else none\n| none := none\nend\n\n/-- Return true if 'n' has been declared in the current file -/\nmeta def in_current_file (env : environment) (n : name) : bool :=\n(env.decl_olean n).is_none && env.contains n && (n ∉ [``quot, ``quot.mk, ``quot.lift, ``quot.ind])\n\nmeta def is_definition (env : environment) (n : name) : bool :=\nmatch env.get n with\n| exceptional.success (declaration.defn _ _ _ _ _ _) := tt\n| _ := ff\nend\n\nend environment\n\nmeta instance : has_repr environment :=\n⟨λ e, \"[environment]\"⟩\n\nmeta instance : inhabited environment :=\n⟨environment.mk_std 0⟩\n", "meta": {"author": "subfish-zhou", "repo": "N2Lean", "sha": "8e858cc5b01f1ad921094dc355db3cb9473a42fd", "save_path": "github-repos/lean/subfish-zhou-N2Lean", "path": "github-repos/lean/subfish-zhou-N2Lean/N2Lean-8e858cc5b01f1ad921094dc355db3cb9473a42fd/library/init/meta/environment.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38861802670584894, "lm_q2_score": 0.04813677316493159, "lm_q1q2_score": 0.018706817799342777}} {"text": "import category_theory.limits.shapes.binary_products\nimport category_theory.limits.preserves.shapes.binary_products\nimport category_theory.adjunction\nimport category_theory.monad.adjunction\nimport category_theory.adjunction.fully_faithful\nimport category_theory.closed.cartesian\nimport category.adjunction\n\nuniverses v₁ v₂ u₁ u₂\n\nnamespace category_theory\n\nopen limits category\n\nvariables {C : Type u₁} {D : Type u₂} [category.{v₁} C] [category.{v₁} D] (i : D ⥤ C)\n\ndef coyoneda.ext {X Y : C} (p : Π {Z : C}, (X ⟶ Z) ≃ (Y ⟶ Z))\n (n : Π {Z Z' : C} (f : Z ⟶ Z') (g : X ⟶ Z), p (g ≫ f) = p g ≫ f) : X ≅ Y :=\n{ hom := p.symm (𝟙 Y),\n inv := p (𝟙 X),\n hom_inv_id' := by rw [← p.injective.eq_iff, n, p.apply_symm_apply, id_comp],\n inv_hom_id' := by rw [← n, id_comp, equiv.apply_symm_apply] }\n\nclass in_subcategory (A : C) :=\n(witness : D)\n(iso : i.obj witness ≅ A)\n\ndef witness_in (A : C) [in_subcategory i A] : D := in_subcategory.witness.{v₁} i A\ndef witness_iso (A : C) [in_subcategory i A] : i.obj (witness_in i A) ≅ A := in_subcategory.iso.\n\nclass in_subcategory' [ir : is_right_adjoint i] (A : C) :=\n( returning : is_iso (ir.adj.unit.app A) )\n\ndef containment_iso (A : C) [ir : is_right_adjoint i] [h : in_subcategory' i A] : A ≅ i.obj ((left_adjoint i).obj A) :=\nbegin\n haveI := h.returning,\n exact as_iso (ir.adj.unit.app A),\nend\nvariable {i}\n\ninstance inclusion_is_in (B : D) : in_subcategory i (i.obj B) :=\n{ witness := B,\n iso := iso.refl _ }\n\nnoncomputable\ninstance inclusion_is_in' (B : D) [ir : reflective i] : in_subcategory' i (i.obj B) :=\n{ returning :=\n begin\n haveI := nat_iso.is_iso_app_of_is_iso ir.adj.counit B,\n have : ir.adj.unit.app (i.obj B) ≫ i.map (ir.adj.counit.app B) = 𝟙 (i.obj B) := ir.adj.right_triangle_components,\n refine ⟨i.map (ir.adj.counit.app B), ir.adj.right_triangle_components, _⟩,\n dsimp,\n rw [← cancel_mono (i.map (is_right_adjoint.adj.counit.app B)), assoc, this, comp_id, id_comp],\n apply is_iso.mono_of_iso,\n end }\n\ndef unit_iso_of_split_mono [ir : reflective i] (A : C) [split_mono (ir.adj.unit.app A)] : is_iso (ir.adj.unit.app A) :=\nbegin\n let h : i.obj (ir.left.obj A) ⟶ A := retraction (ir.adj.unit.app A),\n haveI : is_iso (ir.adj.unit.app (i.obj (ir.left.obj A))) := in_subcategory'.returning,\n haveI : split_epi h := ⟨ir.adj.unit.app A, split_mono.id (ir.adj.unit.app A)⟩,\n suffices : epi (ir.adj.unit.app A),\n refine ⟨h, split_mono.id (ir.adj.unit.app A), _⟩,\n resetI,\n dsimp,\n erw [← cancel_epi (ir.adj.unit.app A), split_mono.id_assoc (ir.adj.unit.app A), comp_id],\n suffices : epi (ir.adj.unit.app _ ≫ i.map (ir.left.map h)),\n erw [← ir.adj.unit.naturality h, functor.id_map] at this,\n resetI,\n apply epi_of_epi h,\n apply epi_comp,\nend\n\n-- Some of the stuff here doesn't need reflectiveness, need to untangle what assumptions are actually used\nnoncomputable\ndef in_subcategory_of_has_iso [ir : reflective i] (A : C) (B : D) (h : i.obj B ≅ A) : in_subcategory' i A :=\n{ returning :=\n begin\n apply unit_iso_of_split_mono _,\n refine ⟨i.map ((ir.adj.hom_equiv _ _).symm h.inv) ≫ h.hom, _⟩,\n simp,\n end }\n\n@[reducible]\ndef equiv_homset_left_of_iso\n {X X' : C} (Y : C) (i : X ≅ X') :\n (X ⟶ Y) ≃ (X' ⟶ Y) :=\n{ to_fun := λ f, i.inv ≫ f,\n inv_fun := λ f, i.hom ≫ f,\n left_inv := λ f, by simp,\n right_inv := λ f, by simp }.\n\n@[reducible]\ndef equiv_homset_right_of_iso\n (X : C) {Y Y' : C} (i : Y ≅ Y') :\n (X ⟶ Y) ≃ (X ⟶ Y') :=\n{ to_fun := λ f, f ≫ i.hom,\n inv_fun := λ f, f ≫ i.inv,\n left_inv := λ f, by simp,\n right_inv := λ f, by simp }.\n\nvariable (i)\nnoncomputable\ndef biject_inclusion [ir : reflective i] {A B : C} [in_subcategory' i B] : (A ⟶ B) ≃ (i.obj ((left_adjoint i).obj A) ⟶ B) :=\ncalc (A ⟶ B) ≃ (A ⟶ i.obj ((left_adjoint i).obj B)) : equiv_homset_right_of_iso _ (containment_iso _ _)\n ... ≃ ((left_adjoint i).obj A ⟶ (left_adjoint i).obj B) : (ir.adj.hom_equiv _ _).symm\n ... ≃ (i.obj ((left_adjoint i).obj A) ⟶ i.obj ((left_adjoint i).obj B)) : equiv_of_fully_faithful i\n ... ≃ (i.obj ((left_adjoint i).obj A) ⟶ B) : equiv_homset_right_of_iso _ (containment_iso _ _).symm\nvariable {i}\n\nlemma biject_inclusion_natural [ir : reflective i] {A B B' : C} [h : in_subcategory' i B] [h' : in_subcategory' i B'] (f : A ⟶ B) (g : B ⟶ B') :\n biject_inclusion i (f ≫ g) = biject_inclusion i f ≫ g :=\nbegin\n dsimp [biject_inclusion, containment_iso],\n haveI := h'.returning,\n haveI := h.returning,\n have : i.map\n (((is_right_adjoint.adj.hom_equiv A ((left_adjoint i).obj B')).symm)\n ((f ≫ g) ≫ is_right_adjoint.adj.unit.app B')) ≫\n inv (is_right_adjoint.adj.unit.app B') = (i.map\n (((is_right_adjoint.adj.hom_equiv A ((left_adjoint i).obj B)).symm)\n (f ≫ is_right_adjoint.adj.unit.app B)) ≫\n inv (is_right_adjoint.adj.unit.app B)) ≫\n g ↔ _ = _ := (as_iso (ir.adj.unit.app B')).comp_inv_eq,\n convert this.2 _, -- this should not be necessary\n clear this,\n dsimp [as_iso_hom],\n erw [assoc, assoc, ir.adj.unit.naturality, assoc, (as_iso _).inv_hom_id_assoc, functor.comp_map, ← functor.map_comp],\n rw [← ir.adj.hom_equiv_naturality_right_symm, assoc], refl,\nend .\n\nlemma biject_inclusion_natural_left [ir : reflective i] {A A' B : C} [h : in_subcategory' i B] (f : A ⟶ A') (g : A' ⟶ B) :\n biject_inclusion i (f ≫ g) = i.map ((left_adjoint i).map f) ≫ biject_inclusion i g :=\nbegin\n dsimp [biject_inclusion],\n erw [← i.map_comp_assoc, ← ir.adj.hom_equiv_naturality_left_symm, assoc],\nend\n\nlemma biject_inclusion_symm_id_eq [ir : reflective i] (A : C) :\n (biject_inclusion i).symm (𝟙 (i.obj ((left_adjoint i).obj A))) = ir.adj.unit.app A :=\nbegin\n rw equiv.symm_apply_eq,\n dsimp [biject_inclusion, containment_iso],\n rw [ir.adj.hom_equiv_counit],\n let η := ir.adj.unit,\n let ε := ir.adj.counit,\n let L := left_adjoint i,\n have : 𝟙 (i.obj ((left_adjoint i).obj A)) = _ ≫ inv (is_right_adjoint.adj.unit.app (i.obj ((left_adjoint i).obj A))) ↔ _ = _ := (as_iso (is_right_adjoint.adj.unit.app (i.obj ((left_adjoint i).obj A)))).eq_comp_inv,\n rw this, clear this,\n rw [id_comp, as_iso_hom],\n change η.app (i.obj (L.obj A)) = i.map (L.map (η.app A ≫ η.app (i.obj (L.obj A))) ≫ ε.app (L.obj (i.obj (L.obj A)))),\n rw [L.map_comp, assoc],\n haveI := nat_iso.is_iso_app_of_is_iso ε (L.obj A),\n erw [ir.adj.left_triangle_components, comp_id, ← cancel_mono (i.map (ε.app (L.obj A))), ir.adj.right_triangle_components,\n ← i.map_comp, ir.adj.left_triangle_components, i.map_id],\nend\n\nlemma biject_inclusion_is_comp_unit [ir : reflective i] {A B : C} [h : in_subcategory' i B] (f : i.obj ((left_adjoint i).obj A) ⟶ B) :\n (biject_inclusion i).symm f = ir.adj.unit.app _ ≫ f :=\nby rw [← biject_inclusion_symm_id_eq A, (biject_inclusion i).symm_apply_eq,\n biject_inclusion_natural _ _, equiv.apply_symm_apply, id_comp]\n\nvariables [has_finite_products.{v₁} C] [has_finite_products.{v₁} D] [cartesian_closed C] (i)\n\nclass exponential_ideal extends reflective i :=\n[ strength (A) {B} [in_subcategory' i B] : in_subcategory' i (A ⟹ B) ]\n\nnoncomputable def exponential_ideal_of [z : reflective i]\n (h : ∀ (A : C) (B : D), in_subcategory' i (A ⟹ i.obj B)) : exponential_ideal i :=\n{ strength := λ A B inst,\n begin\n resetI,\n let ir : is_right_adjoint i := by apply_instance,\n let L := ir.left,\n let η := ir.adj.unit,\n haveI := h A (L.obj B),\n let i₁ : B ≅ i.obj (L.obj B) := containment_iso i B,\n let i₂ : A ⟹ i.obj (L.obj B) ≅ i.obj (L.obj (A ⟹ (i.obj (L.obj B)))) := containment_iso i (A ⟹ i.obj (L.obj B)),\n let : A ⟹ B ≅ i.obj (L.obj (A ⟹ B)),\n apply (exp A).map_iso i₁ ≪≫ i₂ ≪≫ (exp A ⋙ L ⋙ i).map_iso i₁.symm,\n refine ⟨_⟩,\n convert is_iso.of_iso this,\n change η.app (A ⟹ B) =\n (exp _).map (containment_iso _ _).hom ≫ η.app _ ≫ i.map (L.map ((exp _).map (containment_iso _ _).inv)),\n erw η.naturality_assoc,\n change η.app (A ⟹ B) = η.app (A ⟹ B) ≫ (exp A ⋙ L ⋙ _).map _ ≫ (exp A ⋙ L ⋙ _).map _,\n rw [← (exp A ⋙ L ⋙ _).map_comp, iso.hom_inv_id, functor.map_id],\n erw comp_id,\n end,\n ..z }\n\nvariables [exponential_ideal i]\n\nnoncomputable\ndef bijection (A B : C) (C' : D) : ((left_adjoint i).obj (A ⨯ B) ⟶ C') ≃ ((left_adjoint i).obj A ⨯ (left_adjoint i).obj B ⟶ C') :=\ncalc _ ≃ (A ⨯ B ⟶ i.obj C') : _inst_6.to_reflective.adj.hom_equiv _ _\n... ≃ (B ⨯ A ⟶ i.obj C') : equiv_homset_left_of_iso _ (limits.prod.braiding _ _)\n... ≃ (A ⟶ B ⟹ i.obj C') : (exp.adjunction _).hom_equiv _ _\n... ≃ (i.obj ((left_adjoint i).obj A) ⟶ B ⟹ i.obj C') :\n begin\n apply biject_inclusion i,\n apply exponential_ideal.strength,\n end\n... ≃ (B ⨯ i.obj ((left_adjoint i).obj A) ⟶ i.obj C') : ((exp.adjunction _).hom_equiv _ _).symm\n... ≃ (i.obj ((left_adjoint i).obj A) ⨯ B ⟶ i.obj C') : equiv_homset_left_of_iso _ (limits.prod.braiding _ _)\n... ≃ (B ⟶ i.obj ((left_adjoint i).obj A) ⟹ i.obj C') : (exp.adjunction _).hom_equiv _ _\n... ≃ (i.obj ((left_adjoint i).obj B) ⟶ i.obj ((left_adjoint i).obj A) ⟹ i.obj C') :\n begin\n apply biject_inclusion _,\n apply exponential_ideal.strength,\n end\n... ≃ (i.obj ((left_adjoint i).obj A) ⨯ i.obj ((left_adjoint i).obj B) ⟶ i.obj C') : ((exp.adjunction _).hom_equiv _ _).symm\n... ≃ (i.obj ((left_adjoint i).obj A ⨯ (left_adjoint i).obj B) ⟶ i.obj C') : equiv_homset_left_of_iso _\n begin\n apply (as_iso (prod_comparison _ _ _)).symm,\n haveI : preserves_limits i := _inst_6.to_reflective.adj.right_adjoint_preserves_limits,\n apply_instance,\n end\n... ≃ ((left_adjoint i).obj A ⨯ (left_adjoint i).obj B ⟶ C') : (equiv_of_fully_faithful _).symm\n\nvariables {i}\n\nlemma comp_inv_eq {X Y Z : C} (f : X ⟶ Y) (g : Z ⟶ Y) (h : Z ⟶ X) [is_iso f] :\n g ≫ inv f = h ↔ g = h ≫ f :=\n(as_iso f).comp_inv_eq.\n\n-- @[reassoc] lemma prod_comparison_natural (F : C ⥤ D) {A A' B B' : C} (f : A ⟶ A') (g : B ⟶ B') :\n-- F.map (prod.map f g) ≫ prod_comparison F A' B' = prod_comparison F A B ≫ prod.map (F.map f) (F.map g) :=\n\nlemma bijection_id (A B : C) : (bijection i A B _).symm (𝟙 _) = prod_comparison _ _ _ :=\nbegin\n dsimp [bijection],\n -- rw [equiv.symm_symm, equiv.symm_symm, equiv.symm_symm],\n -- dsimp [equiv_of_fully_faithful],\n rw [i.map_id, comp_id, biject_inclusion_is_comp_unit, biject_inclusion_is_comp_unit],\n let ir : is_right_adjoint i := by apply_instance,\n let L := ir.left,\n let adj : L ⊣ i := ir.adj,\n let η : _ ⟶ L ⋙ i := adj.unit,\n let ε : i ⋙ L ⟶ _ := adj.counit,\n change ((adj.hom_equiv (A ⨯ B) (L.obj A ⨯ L.obj B)).symm)\n (prod.lift limits.prod.snd limits.prod.fst ≫\n cartesian_closed.uncurry (η.app A ≫\n cartesian_closed.curry (prod.lift limits.prod.snd limits.prod.fst ≫\n cartesian_closed.uncurry (η.app B ≫ cartesian_closed.curry _)))) =\n prod_comparison L A B,\n rw [uncurry_natural_left, uncurry_curry, uncurry_natural_left, uncurry_curry,\n ← adjunction.eq_hom_equiv_apply, prod.lift_map_assoc, prod.lift_map_assoc,\n comp_id, comp_id, ← assoc, comp_inv_eq, adjunction.hom_equiv_unit, assoc],\n apply prod.hom_ext,\n rw [assoc, prod.lift_fst, prod.lift_snd, assoc, assoc, prod_comparison, prod_comparison,\n prod.lift_fst, ← i.map_comp, prod.lift_fst],\n apply η.naturality,\n rw [assoc, prod.lift_snd, prod.lift_fst_assoc, assoc, assoc, prod_comparison,\n prod_comparison, prod.lift_snd, ← i.map_comp, prod.lift_snd],\n apply η.naturality,\nend .\n\nlemma bijection_natural (A B : C) (C' C'' : D) (f : ((left_adjoint i).obj (A ⨯ B) ⟶ C')) (g : C' ⟶ C'') : bijection i _ _ _ (f ≫ g) = bijection i _ _ _ f ≫ g :=\nbegin\n have : i.preimage (i.map g) = g := preimage_map g,\n conv_rhs {congr, skip, rw ← this},\n dsimp [bijection],\n rw [← preimage_comp, assoc, ← adjunction.hom_equiv_naturality_right_symm,\n is_right_adjoint.adj.hom_equiv_naturality_right, ← assoc,\n (exp.adjunction B).hom_equiv_naturality_right, ← biject_inclusion_natural _ _,\n ← (exp.adjunction (i.obj _)).hom_equiv_naturality_right, assoc,\n ← (exp.adjunction B).hom_equiv_naturality_right_symm, ← biject_inclusion_natural _ _],\nend\n\nopen limits.prod\n\nnoncomputable\ndef preserves_pair_of_exponential_ideal (A B : C) : preserves_limit (pair.{v₁} A B) (is_right_adjoint.left i) :=\nbegin\n let ir : is_right_adjoint i := by apply_instance,\n let L := ir.left,\n let : L.obj (A ⨯ B) ≅ L.obj A ⨯ L.obj B := coyoneda.ext (λ Z, bijection i A B _) (λ _ _ _ _, bijection_natural _ _ _ _ _ _),\n have equate : prod_comparison L A B = this.hom := (bijection_id A B).symm,\n have : is_iso (prod_comparison L A B),\n rw equate, apply_instance,\n exactI preserves_pair.of_iso_comparison _ _ _,\nend\n\nvariable (i)\nnoncomputable\ndef preserves_binary_products_of_exponential_ideal : preserves_limits_of_shape (discrete walking_pair) (is_right_adjoint.left i) :=\n{ preserves_limit := λ K,\n begin\n apply preserves_limit_of_iso_diagram _ (diagram_iso_pair K).symm,\n apply preserves_pair_of_exponential_ideal,\n end }\nend category_theory\n", "meta": {"author": "b-mehta", "repo": "topos", "sha": "c9032b11789e36038bc841a1e2b486972421b983", "save_path": "github-repos/lean/b-mehta-topos", "path": "github-repos/lean/b-mehta-topos/topos-c9032b11789e36038bc841a1e2b486972421b983/src/construction.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4571367168274948, "lm_q2_score": 0.040845718536994986, "lm_q1q2_score": 0.018672077668461833}} {"text": "/-\nCopyright (c) 2021 Adam Topaz. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Adam Topaz\n-/\nimport category_theory.adjunction.fully_faithful\nimport category_theory.sites.plus\nimport category_theory.limits.concrete_category\nimport category_theory.concrete_category.elementwise\n\n/-!\n\n# Sheafification\n\nWe construct the sheafification of a presheaf over a site `C` with values in `D` whenever\n`D` is a concrete category for which the forgetful functor preserves the appropriate (co)limits\nand reflects isomorphisms.\n\nWe generally follow the approach of https://stacks.math.columbia.edu/tag/00W1\n\n-/\n\nnamespace category_theory\n\nopen category_theory.limits opposite\n\nuniverses w v u\nvariables {C : Type u} [category.{v} C] {J : grothendieck_topology C}\nvariables {D : Type w} [category.{max v u} D]\n\nsection\nvariables [concrete_category.{max v u} D]\n\nlocal attribute [instance]\n concrete_category.has_coe_to_sort\n concrete_category.has_coe_to_fun\n\n/-- A concrete version of the multiequalizer, to be used below. -/\n@[nolint has_nonempty_instance]\ndef meq {X : C} (P : Cᵒᵖ ⥤ D) (S : J.cover X) :=\n{ x : Π (I : S.arrow), P.obj (op I.Y) //\n ∀ (I : S.relation), P.map I.g₁.op (x I.fst) = P.map I.g₂.op (x I.snd) }\nend\n\nnamespace meq\n\nvariables [concrete_category.{max v u} D]\n\nlocal attribute [instance]\n concrete_category.has_coe_to_sort\n concrete_category.has_coe_to_fun\n\n\ninstance {X} (P : Cᵒᵖ ⥤ D) (S : J.cover X) : has_coe_to_fun (meq P S)\n (λ x, Π (I : S.arrow), P.obj (op I.Y)) := ⟨λ x, x.1⟩\n\n@[ext]\nlemma ext {X} {P : Cᵒᵖ ⥤ D} {S : J.cover X} (x y : meq P S)\n (h : ∀ I : S.arrow, x I = y I) : x = y := subtype.ext $ funext $ h\n\nlemma condition {X} {P : Cᵒᵖ ⥤ D} {S : J.cover X} (x : meq P S) (I : S.relation) :\n P.map I.g₁.op (x ((S.index P).fst_to I)) = P.map I.g₂.op (x ((S.index P).snd_to I)) := x.2 _\n\n/-- Refine a term of `meq P T` with respect to a refinement `S ⟶ T` of covers. -/\ndef refine {X : C} {P : Cᵒᵖ ⥤ D} {S T : J.cover X} (x : meq P T) (e : S ⟶ T) :\n meq P S :=\n⟨λ I, x ⟨I.Y, I.f, (le_of_hom e) _ I.hf⟩,\n λ I, x.condition ⟨I.Y₁, I.Y₂, I.Z, I.g₁, I.g₂, I.f₁, I.f₂,\n (le_of_hom e) _ I.h₁, (le_of_hom e) _ I.h₂, I.w⟩⟩\n\n@[simp]\nlemma refine_apply {X : C} {P : Cᵒᵖ ⥤ D} {S T : J.cover X} (x : meq P T) (e : S ⟶ T)\n (I : S.arrow) : x.refine e I = x ⟨I.Y, I.f, (le_of_hom e) _ I.hf⟩ := rfl\n\n/-- Pull back a term of `meq P S` with respect to a morphism `f : Y ⟶ X` in `C`. -/\ndef pullback {Y X : C} {P : Cᵒᵖ ⥤ D} {S : J.cover X} (x : meq P S) (f : Y ⟶ X) :\n meq P ((J.pullback f).obj S) :=\n⟨λ I, x ⟨_,I.f ≫ f, I.hf⟩, λ I, x.condition\n ⟨I.Y₁, I.Y₂, I.Z, I.g₁, I.g₂, I.f₁ ≫ f, I.f₂ ≫ f, I.h₁, I.h₂, by simp [reassoc_of I.w]⟩ ⟩\n\n@[simp]\nlemma pullback_apply {Y X : C} {P : Cᵒᵖ ⥤ D} {S : J.cover X} (x : meq P S) (f : Y ⟶ X)\n (I : ((J.pullback f).obj S).arrow) : x.pullback f I = x ⟨_, I.f ≫ f, I.hf⟩ := rfl\n\n@[simp]\nlemma pullback_refine {Y X : C} {P : Cᵒᵖ ⥤ D} {S T : J.cover X} (h : S ⟶ T)\n (f : Y ⟶ X) (x : meq P T) : (x.pullback f).refine\n ((J.pullback f).map h) = (refine x h).pullback _ := rfl\n\n/-- Make a term of `meq P S`. -/\ndef mk {X : C} {P : Cᵒᵖ ⥤ D} (S : J.cover X) (x : P.obj (op X)) : meq P S :=\n⟨λ I, P.map I.f.op x, λ I, by { dsimp, simp only [← comp_apply, ← P.map_comp, ← op_comp, I.w] }⟩\n\nlemma mk_apply {X : C} {P : Cᵒᵖ ⥤ D} (S : J.cover X) (x : P.obj (op X)) (I : S.arrow) :\n mk S x I = P.map I.f.op x := rfl\n\nvariable [preserves_limits (forget D)]\n\n/-- The equivalence between the type associated to `multiequalizer (S.index P)` and `meq P S`. -/\nnoncomputable\ndef equiv {X : C} (P : Cᵒᵖ ⥤ D) (S : J.cover X) [has_multiequalizer (S.index P)] :\n (multiequalizer (S.index P) : D) ≃ meq P S :=\nlimits.concrete.multiequalizer_equiv _\n\n@[simp]\nlemma equiv_apply {X : C} {P : Cᵒᵖ ⥤ D} {S : J.cover X} [has_multiequalizer (S.index P)]\n (x : multiequalizer (S.index P)) (I : S.arrow) :\nequiv P S x I = multiequalizer.ι (S.index P) I x := rfl\n\n@[simp]\nlemma equiv_symm_eq_apply {X : C} {P : Cᵒᵖ ⥤ D} {S : J.cover X} [has_multiequalizer (S.index P)]\n (x : meq P S) (I : S.arrow) : multiequalizer.ι (S.index P) I ((meq.equiv P S).symm x) = x I :=\nbegin\n let z := (meq.equiv P S).symm x,\n rw ← equiv_apply,\n simp,\nend\n\nend meq\n\nnamespace grothendieck_topology\n\nnamespace plus\n\nvariables [concrete_category.{max v u} D]\n\nlocal attribute [instance]\n concrete_category.has_coe_to_sort\n concrete_category.has_coe_to_fun\n\nvariable [preserves_limits (forget D)]\nvariables [∀ (X : C), has_colimits_of_shape (J.cover X)ᵒᵖ D]\nvariables [∀ (P : Cᵒᵖ ⥤ D) (X : C) (S : J.cover X), has_multiequalizer (S.index P)]\n\nnoncomputable theory\n\n/-- Make a term of `(J.plus_obj P).obj (op X)` from `x : meq P S`. -/\ndef mk {X : C} {P : Cᵒᵖ ⥤ D} {S : J.cover X} (x : meq P S) : (J.plus_obj P).obj (op X) :=\ncolimit.ι (J.diagram P X) (op S) ((meq.equiv P S).symm x)\n\nlemma res_mk_eq_mk_pullback {Y X : C} {P : Cᵒᵖ ⥤ D} {S : J.cover X} (x : meq P S) (f : Y ⟶ X) :\n (J.plus_obj P).map f.op (mk x) = mk (x.pullback f) :=\nbegin\n dsimp [mk, plus_obj],\n simp only [← comp_apply, colimit.ι_pre, ι_colim_map_assoc],\n simp_rw [comp_apply],\n congr' 1,\n apply_fun meq.equiv P _,\n erw equiv.apply_symm_apply,\n ext i,\n simp only [diagram_pullback_app,\n meq.pullback_apply, meq.equiv_apply, ← comp_apply],\n erw [multiequalizer.lift_ι, meq.equiv_symm_eq_apply],\n cases i, refl,\nend\n\nlemma to_plus_mk {X : C} {P : Cᵒᵖ ⥤ D} (S : J.cover X) (x : P.obj (op X)) :\n (J.to_plus P).app _ x = mk (meq.mk S x) :=\nbegin\n dsimp [mk, to_plus],\n let e : S ⟶ ⊤ := hom_of_le (order_top.le_top _),\n rw ← colimit.w _ e.op,\n delta cover.to_multiequalizer,\n simp only [comp_apply],\n congr' 1,\n dsimp [diagram],\n apply concrete.multiequalizer_ext,\n intros i,\n simpa only [← comp_apply, category.assoc, multiequalizer.lift_ι,\n category.comp_id, meq.equiv_symm_eq_apply],\nend\n\nlemma to_plus_apply {X : C} {P : Cᵒᵖ ⥤ D} (S : J.cover X) (x : meq P S) (I : S.arrow) :\n (J.to_plus P).app _ (x I) = (J.plus_obj P).map I.f.op (mk x) :=\nbegin\n dsimp only [to_plus, plus_obj],\n delta cover.to_multiequalizer,\n dsimp [mk],\n simp only [← comp_apply, colimit.ι_pre, ι_colim_map_assoc],\n simp only [comp_apply],\n dsimp only [functor.op],\n let e : (J.pullback I.f).obj (unop (op S)) ⟶ ⊤ := hom_of_le (order_top.le_top _),\n rw ← colimit.w _ e.op,\n simp only [comp_apply],\n congr' 1,\n apply concrete.multiequalizer_ext,\n intros i,\n dsimp [diagram],\n simp only [← comp_apply, category.assoc, multiequalizer.lift_ι,\n category.comp_id, meq.equiv_symm_eq_apply],\n let RR : S.relation :=\n ⟨_, _, _, i.f, 𝟙 _, I.f, i.f ≫ I.f, I.hf, sieve.downward_closed _ I.hf _, by simp⟩,\n cases I,\n erw x.condition RR,\n simpa [RR],\nend\n\nlemma to_plus_eq_mk {X : C} {P : Cᵒᵖ ⥤ D} (x : P.obj (op X)) :\n (J.to_plus P).app _ x = mk (meq.mk ⊤ x) :=\nbegin\n dsimp [mk, to_plus],\n delta cover.to_multiequalizer,\n simp only [comp_apply],\n congr' 1,\n apply_fun (meq.equiv P ⊤),\n ext i,\n simpa,\nend\n\nvariables [∀ (X : C), preserves_colimits_of_shape (J.cover X)ᵒᵖ (forget D)]\n\nlemma exists_rep {X : C} {P : Cᵒᵖ ⥤ D} (x : (J.plus_obj P).obj (op X)) :\n ∃ (S : J.cover X) (y : meq P S), x = mk y :=\nbegin\n obtain ⟨S,y,h⟩ := concrete.colimit_exists_rep (J.diagram P X) x,\n use [S.unop, meq.equiv _ _ y],\n rw ← h,\n dsimp [mk],\n simp,\nend\n\nlemma eq_mk_iff_exists {X : C} {P : Cᵒᵖ ⥤ D} {S T : J.cover X}\n (x : meq P S) (y : meq P T) : mk x = mk y ↔ (∃ (W : J.cover X) (h1 : W ⟶ S) (h2 : W ⟶ T),\n x.refine h1 = y.refine h2) :=\nbegin\n split,\n { intros h,\n obtain ⟨W, h1, h2, hh⟩ := concrete.colimit_exists_of_rep_eq _ _ _ h,\n use [W.unop, h1.unop, h2.unop],\n ext I,\n apply_fun (multiequalizer.ι (W.unop.index P) I) at hh,\n convert hh,\n all_goals\n { dsimp [diagram],\n simp only [← comp_apply, multiequalizer.lift_ι, category.comp_id, meq.equiv_symm_eq_apply],\n cases I, refl } },\n { rintros ⟨S,h1,h2,e⟩,\n apply concrete.colimit_rep_eq_of_exists,\n use [(op S), h1.op, h2.op],\n apply concrete.multiequalizer_ext,\n intros i,\n apply_fun (λ ee, ee i) at e,\n convert e,\n all_goals\n { dsimp [diagram],\n simp only [← comp_apply, multiequalizer.lift_ι, meq.equiv_symm_eq_apply],\n cases i, refl } },\nend\n\n/-- `P⁺` is always separated. -/\ntheorem sep {X : C} (P : Cᵒᵖ ⥤ D) (S : J.cover X) (x y : (J.plus_obj P).obj (op X))\n (h : ∀ (I : S.arrow), (J.plus_obj P).map I.f.op x = (J.plus_obj P).map I.f.op y) :\n x = y :=\nbegin\n -- First, we choose representatives for x and y.\n obtain ⟨Sx,x,rfl⟩ := exists_rep x,\n obtain ⟨Sy,y,rfl⟩ := exists_rep y,\n simp only [res_mk_eq_mk_pullback] at h,\n\n -- Next, using our assumption,\n -- choose covers over which the pullbacks of these representatives become equal.\n choose W h1 h2 hh using λ (I : S.arrow), (eq_mk_iff_exists _ _).mp (h I),\n\n -- To prove equality, it suffices to prove that there exists a cover over which\n -- the representatives become equal.\n rw eq_mk_iff_exists,\n\n -- Construct the cover over which the representatives become equal by combining the various\n -- covers chosen above.\n let B : J.cover X := S.bind W,\n use B,\n\n -- Prove that this cover refines the two covers over which our representatives are defined\n -- and use these proofs.\n let ex : B ⟶ Sx := hom_of_le begin\n rintros Y f ⟨Z,e1,e2,he2,he1,hee⟩,\n rw ← hee,\n apply le_of_hom (h1 ⟨_, _, he2⟩),\n exact he1,\n end,\n let ey : B ⟶ Sy := hom_of_le begin\n rintros Y f ⟨Z,e1,e2,he2,he1,hee⟩,\n rw ← hee,\n apply le_of_hom (h2 ⟨_, _, he2⟩),\n exact he1,\n end,\n use [ex, ey],\n\n -- Now prove that indeed the representatives become equal over `B`.\n -- This will follow by using the fact that our representatives become\n -- equal over the chosen covers.\n ext1 I,\n let IS : S.arrow := I.from_middle,\n specialize hh IS,\n let IW : (W IS).arrow := I.to_middle,\n apply_fun (λ e, e IW) at hh,\n convert hh,\n { let Rx : Sx.relation := ⟨I.Y, I.Y, I.Y, 𝟙 _, 𝟙 _, I.f,\n I.to_middle_hom ≫ I.from_middle_hom, _, _, by simp [I.middle_spec]⟩,\n have := x.condition Rx,\n simpa using this },\n { let Ry : Sy.relation := ⟨I.Y, I.Y, I.Y, 𝟙 _, 𝟙 _, I.f,\n I.to_middle_hom ≫ I.from_middle_hom, _, _, by simp [I.middle_spec]⟩,\n have := y.condition Ry,\n simpa using this },\nend\n\nlemma inj_of_sep (P : Cᵒᵖ ⥤ D) (hsep : ∀ (X : C) (S : J.cover X) (x y : P.obj (op X)),\n (∀ I : S.arrow, P.map I.f.op x = P.map I.f.op y) → x = y) (X : C) :\n function.injective ((J.to_plus P).app (op X)) :=\nbegin\n intros x y h,\n simp only [to_plus_eq_mk] at h,\n rw eq_mk_iff_exists at h,\n obtain ⟨W, h1, h2, hh⟩ := h,\n apply hsep X W,\n intros I,\n apply_fun (λ e, e I) at hh,\n exact hh\nend\n\n/-- An auxiliary definition to be used in the proof of `exists_of_sep` below.\n Given a compatible family of local sections for `P⁺`, and representatives of said sections,\n construct a compatible family of local sections of `P` over the combination of the covers\n associated to the representatives.\n The separatedness condition is used to prove compatibility among these local sections of `P`. -/\ndef meq_of_sep (P : Cᵒᵖ ⥤ D)\n (hsep : ∀ (X : C) (S : J.cover X) (x y : P.obj (op X)),\n (∀ I : S.arrow, P.map I.f.op x = P.map I.f.op y) → x = y)\n (X : C) (S : J.cover X)\n (s : meq (J.plus_obj P) S)\n (T : Π (I : S.arrow), J.cover I.Y)\n (t : Π (I : S.arrow), meq P (T I))\n (ht : ∀ (I : S.arrow), s I = mk (t I)) : meq P (S.bind T) :=\n{ val := λ I, t I.from_middle I.to_middle,\n property := begin\n intros II,\n apply inj_of_sep P hsep,\n rw [← comp_apply, ← comp_apply, (J.to_plus P).naturality, (J.to_plus P).naturality,\n comp_apply, comp_apply],\n erw [to_plus_apply (T II.fst.from_middle) (t II.fst.from_middle) II.fst.to_middle,\n to_plus_apply (T II.snd.from_middle) (t II.snd.from_middle) II.snd.to_middle,\n ← ht, ← ht, ← comp_apply, ← comp_apply, ← (J.plus_obj P).map_comp,\n ← (J.plus_obj P).map_comp],\n rw [← op_comp, ← op_comp],\n let IR : S.relation :=\n ⟨_, _, _, II.g₁ ≫ II.fst.to_middle_hom, II.g₂ ≫ II.snd.to_middle_hom,\n II.fst.from_middle_hom, II.snd.from_middle_hom, II.fst.from_middle_condition,\n II.snd.from_middle_condition, _⟩,\n swap, { simp only [category.assoc, II.fst.middle_spec, II.snd.middle_spec], apply II.w },\n exact s.condition IR,\n end }\n\ntheorem exists_of_sep (P : Cᵒᵖ ⥤ D)\n (hsep : ∀ (X : C) (S : J.cover X) (x y : P.obj (op X)),\n (∀ I : S.arrow, P.map I.f.op x = P.map I.f.op y) → x = y)\n (X : C) (S : J.cover X)\n (s : meq (J.plus_obj P) S) :\n ∃ t : (J.plus_obj P).obj (op X), meq.mk S t = s :=\nbegin\n have inj : ∀ (X : C), function.injective ((J.to_plus P).app (op X)) := inj_of_sep _ hsep,\n\n -- Choose representatives for the given local sections.\n choose T t ht using λ I, exists_rep (s I),\n\n -- Construct a large cover over which we will define a representative that will\n -- provide the gluing of the given local sections.\n let B : J.cover X := S.bind T,\n choose Z e1 e2 he2 he1 hee using λ I : B.arrow, I.hf,\n\n -- Construct a compatible system of local sections over this large cover, using the chosen\n -- representatives of our local sections.\n -- The compatilibity here follows from the separatedness assumption.\n let w : meq P B := meq_of_sep P hsep X S s T t ht,\n\n -- The associated gluing will be the candidate section.\n use mk w,\n ext I,\n erw [ht, res_mk_eq_mk_pullback],\n\n -- Use the separatedness of `P⁺` to prove that this is indeed a gluing of our\n -- original local sections.\n apply sep P (T I),\n intros II,\n simp only [res_mk_eq_mk_pullback, eq_mk_iff_exists],\n\n -- It suffices to prove equality for representatives over a\n -- convenient sufficiently large cover...\n use (J.pullback II.f).obj (T I),\n let e0 : (J.pullback II.f).obj (T I) ⟶ (J.pullback II.f).obj ((J.pullback I.f).obj B) :=\n hom_of_le begin\n intros Y f hf,\n apply sieve.le_pullback_bind _ _ _ I.hf,\n { cases I,\n exact hf },\n end,\n use [e0, 𝟙 _],\n ext IV,\n dsimp only [meq.refine_apply, meq.pullback_apply, w],\n let IA : B.arrow := ⟨_, (IV.f ≫ II.f) ≫ I.f, _⟩,\n swap,\n { refine ⟨I.Y, _, _, I.hf, _, rfl⟩,\n apply sieve.downward_closed,\n convert II.hf,\n cases I, refl },\n let IB : S.arrow := IA.from_middle,\n let IC : (T IB).arrow := IA.to_middle,\n let ID : (T I).arrow := ⟨IV.Y, IV.f ≫ II.f, sieve.downward_closed (T I) II.hf IV.f⟩,\n change t IB IC = t I ID,\n apply inj IV.Y,\n erw [to_plus_apply (T I) (t I) ID, to_plus_apply (T IB) (t IB) IC, ← ht, ← ht],\n\n -- Conclude by constructing the relation showing equality...\n let IR : S.relation := ⟨_, _, IV.Y, IC.f, ID.f, IB.f, I.f, _, I.hf, IA.middle_spec⟩,\n convert s.condition IR,\n cases I, refl,\nend\n\nvariable [reflects_isomorphisms (forget D)]\n\n/-- If `P` is separated, then `P⁺` is a sheaf. -/\ntheorem is_sheaf_of_sep (P : Cᵒᵖ ⥤ D)\n (hsep : ∀ (X : C) (S : J.cover X) (x y : P.obj (op X)),\n (∀ I : S.arrow, P.map I.f.op x = P.map I.f.op y) → x = y) :\n presheaf.is_sheaf J (J.plus_obj P) :=\nbegin\n rw presheaf.is_sheaf_iff_multiequalizer,\n intros X S,\n apply is_iso_of_reflects_iso _ (forget D),\n rw is_iso_iff_bijective,\n split,\n { intros x y h,\n apply sep P S _ _,\n intros I,\n apply_fun (meq.equiv _ _) at h,\n apply_fun (λ e, e I) at h,\n convert h,\n { erw [meq.equiv_apply, ← comp_apply, multiequalizer.lift_ι] },\n { erw [meq.equiv_apply, ← comp_apply, multiequalizer.lift_ι] } },\n { rintros (x : (multiequalizer (S.index _) : D)),\n obtain ⟨t,ht⟩ := exists_of_sep P hsep X S (meq.equiv _ _ x),\n use t,\n apply_fun meq.equiv _ _,\n swap, { apply_instance },\n rw ← ht,\n ext i,\n dsimp,\n rw [← comp_apply, multiequalizer.lift_ι],\n refl }\nend\n\nvariable (J)\n\n/-- `P⁺⁺` is always a sheaf. -/\ntheorem is_sheaf_plus_plus (P : Cᵒᵖ ⥤ D) :\n presheaf.is_sheaf J (J.plus_obj (J.plus_obj P)) :=\nbegin\n apply is_sheaf_of_sep,\n intros X S x y,\n apply sep,\nend\n\nend plus\n\nvariables (J)\nvariables\n [∀ (P : Cᵒᵖ ⥤ D) (X : C) (S : J.cover X), has_multiequalizer (S.index P)]\n [∀ (X : C), has_colimits_of_shape (J.cover X)ᵒᵖ D]\n\n/-- The sheafification of a presheaf `P`.\n*NOTE:* Additional hypotheses are needed to obtain a proof that this is a sheaf! -/\ndef sheafify (P : Cᵒᵖ ⥤ D) : Cᵒᵖ ⥤ D := J.plus_obj (J.plus_obj P)\n\n/-- The canonical map from `P` to its sheafification. -/\ndef to_sheafify (P : Cᵒᵖ ⥤ D) : P ⟶ J.sheafify P :=\nJ.to_plus P ≫ J.plus_map (J.to_plus P)\n\n/-- The canonical map on sheafifications induced by a morphism. -/\ndef sheafify_map {P Q : Cᵒᵖ ⥤ D} (η : P ⟶ Q) : J.sheafify P ⟶ J.sheafify Q :=\nJ.plus_map $ J.plus_map η\n\n@[simp]\nlemma sheafify_map_id (P : Cᵒᵖ ⥤ D) : J.sheafify_map (𝟙 P) = 𝟙 (J.sheafify P) :=\nby { dsimp [sheafify_map, sheafify], simp }\n\n@[simp]\nlemma sheafify_map_comp {P Q R : Cᵒᵖ ⥤ D} (η : P ⟶ Q) (γ : Q ⟶ R) :\n J.sheafify_map (η ≫ γ) = J.sheafify_map η ≫ J.sheafify_map γ :=\nby { dsimp [sheafify_map, sheafify], simp }\n\n@[simp, reassoc]\nlemma to_sheafify_naturality {P Q : Cᵒᵖ ⥤ D} (η : P ⟶ Q) :\n η ≫ J.to_sheafify _ = J.to_sheafify _ ≫ J.sheafify_map η :=\nby { dsimp [sheafify_map, sheafify, to_sheafify], simp }\n\nvariable (D)\n\n/-- The sheafification of a presheaf `P`, as a functor.\n*NOTE:* Additional hypotheses are needed to obtain a proof that this is a sheaf! -/\ndef sheafification : (Cᵒᵖ ⥤ D) ⥤ Cᵒᵖ ⥤ D := (J.plus_functor D ⋙ J.plus_functor D)\n\n@[simp]\nlemma sheafification_obj (P : Cᵒᵖ ⥤ D) : (J.sheafification D).obj P = J.sheafify P := rfl\n\n@[simp]\nlemma sheafification_map {P Q : Cᵒᵖ ⥤ D} (η : P ⟶ Q) : (J.sheafification D).map η =\n J.sheafify_map η := rfl\n\n/-- The canonical map from `P` to its sheafification, as a natural transformation.\n*Note:* We only show this is a sheaf under additional hypotheses on `D`. -/\ndef to_sheafification : 𝟭 _ ⟶ sheafification J D :=\nJ.to_plus_nat_trans D ≫ whisker_right (J.to_plus_nat_trans D) (J.plus_functor D)\n\n@[simp]\nlemma to_sheafification_app (P : Cᵒᵖ ⥤ D) : (J.to_sheafification D).app P = J.to_sheafify P := rfl\n\nvariable {D}\n\nlemma is_iso_to_sheafify {P : Cᵒᵖ ⥤ D} (hP : presheaf.is_sheaf J P) :\n is_iso (J.to_sheafify P) :=\nbegin\n dsimp [to_sheafify],\n haveI : is_iso (J.to_plus P) := by { apply is_iso_to_plus_of_is_sheaf J P hP },\n haveI : is_iso ((J.plus_functor D).map (J.to_plus P)) := by { apply functor.map_is_iso },\n exact @is_iso.comp_is_iso _ _ _ _ _ (J.to_plus P)\n ((J.plus_functor D).map (J.to_plus P)) _ _,\nend\n\n/-- If `P` is a sheaf, then `P` is isomorphic to `J.sheafify P`. -/\ndef iso_sheafify {P : Cᵒᵖ ⥤ D} (hP : presheaf.is_sheaf J P) :\n P ≅ J.sheafify P :=\nby letI := is_iso_to_sheafify J hP; exactI as_iso (J.to_sheafify P)\n\n@[simp]\nlemma iso_sheafify_hom {P : Cᵒᵖ ⥤ D} (hP : presheaf.is_sheaf J P) :\n (J.iso_sheafify hP).hom = J.to_sheafify P := rfl\n\n/-- Given a sheaf `Q` and a morphism `P ⟶ Q`, construct a morphism from\n`J.sheafifcation P` to `Q`. -/\ndef sheafify_lift {P Q : Cᵒᵖ ⥤ D} (η : P ⟶ Q) (hQ : presheaf.is_sheaf J Q) :\n J.sheafify P ⟶ Q := J.plus_lift (J.plus_lift η hQ) hQ\n\n@[simp, reassoc]\nlemma to_sheafify_sheafify_lift {P Q : Cᵒᵖ ⥤ D} (η : P ⟶ Q) (hQ : presheaf.is_sheaf J Q) :\n J.to_sheafify P ≫ sheafify_lift J η hQ = η :=\nby { dsimp only [sheafify_lift, to_sheafify], simp }\n\nlemma sheafify_lift_unique {P Q : Cᵒᵖ ⥤ D} (η : P ⟶ Q) (hQ : presheaf.is_sheaf J Q)\n (γ : J.sheafify P ⟶ Q) :\n J.to_sheafify P ≫ γ = η → γ = sheafify_lift J η hQ :=\nbegin\n intros h,\n apply plus_lift_unique,\n apply plus_lift_unique,\n rw [← category.assoc, ← plus_map_to_plus],\n exact h,\nend\n\n@[simp]\nlemma iso_sheafify_inv {P : Cᵒᵖ ⥤ D} (hP : presheaf.is_sheaf J P) :\n (J.iso_sheafify hP).inv = J.sheafify_lift (𝟙 _) hP :=\nbegin\n apply J.sheafify_lift_unique,\n simp [iso.comp_inv_eq],\nend\n\nlemma sheafify_hom_ext {P Q : Cᵒᵖ ⥤ D} (η γ : J.sheafify P ⟶ Q) (hQ : presheaf.is_sheaf J Q)\n (h : J.to_sheafify P ≫ η = J.to_sheafify P ≫ γ) : η = γ :=\nbegin\n apply J.plus_hom_ext _ _ hQ,\n apply J.plus_hom_ext _ _ hQ,\n rw [← category.assoc, ← category.assoc, ← plus_map_to_plus],\n exact h,\nend\n\n@[simp, reassoc]\nlemma sheafify_map_sheafify_lift {P Q R : Cᵒᵖ ⥤ D} (η : P ⟶ Q) (γ : Q ⟶ R)\n (hR : presheaf.is_sheaf J R) :\n J.sheafify_map η ≫ J.sheafify_lift γ hR = J.sheafify_lift (η ≫ γ) hR :=\nbegin\n apply J.sheafify_lift_unique,\n rw [← category.assoc, ← J.to_sheafify_naturality,\n category.assoc, to_sheafify_sheafify_lift],\nend\n\nend grothendieck_topology\n\nvariables (J)\nvariables\n [concrete_category.{max v u} D]\n [preserves_limits (forget D)]\n [∀ (P : Cᵒᵖ ⥤ D) (X : C) (S : J.cover X), has_multiequalizer (S.index P)]\n [∀ (X : C), has_colimits_of_shape (J.cover X)ᵒᵖ D]\n [∀ (X : C), preserves_colimits_of_shape (J.cover X)ᵒᵖ (forget D)]\n [reflects_isomorphisms (forget D)]\n\nlemma grothendieck_topology.sheafify_is_sheaf (P : Cᵒᵖ ⥤ D) :\n presheaf.is_sheaf J (J.sheafify P) :=\ngrothendieck_topology.plus.is_sheaf_plus_plus _ _\n\nvariables (D)\n\n/-- The sheafification functor, as a functor taking values in `Sheaf`. -/\n@[simps]\ndef presheaf_to_Sheaf : (Cᵒᵖ ⥤ D) ⥤ Sheaf J D :=\n{ obj := λ P, ⟨J.sheafify P, J.sheafify_is_sheaf P⟩,\n map := λ P Q η, ⟨J.sheafify_map η⟩,\n map_id' := λ P, Sheaf.hom.ext _ _ $ J.sheafify_map_id _,\n map_comp' := λ P Q R f g, Sheaf.hom.ext _ _ $ J.sheafify_map_comp _ _ }\n\ninstance presheaf_to_Sheaf_preserves_zero_morphisms [preadditive D] :\n (presheaf_to_Sheaf J D).preserves_zero_morphisms :=\n{ map_zero' := λ F G, by { ext, erw [colimit.ι_map, comp_zero, J.plus_map_zero,\n J.diagram_nat_trans_zero, zero_comp] } }\n\n/-- The sheafification functor is left adjoint to the forgetful functor. -/\n@[simps unit_app counit_app_val]\ndef sheafification_adjunction : presheaf_to_Sheaf J D ⊣ Sheaf_to_presheaf J D :=\nadjunction.mk_of_hom_equiv\n{ hom_equiv := λ P Q,\n { to_fun := λ e, J.to_sheafify P ≫ e.val,\n inv_fun := λ e, ⟨J.sheafify_lift e Q.2⟩,\n left_inv := λ e, Sheaf.hom.ext _ _ $ (J.sheafify_lift_unique _ _ _ rfl).symm,\n right_inv := λ e, J.to_sheafify_sheafify_lift _ _ },\n hom_equiv_naturality_left_symm' := begin\n intros P Q R η γ, ext1, dsimp, symmetry,\n apply J.sheafify_map_sheafify_lift,\n end,\n hom_equiv_naturality_right' := λ P Q R η γ, by { dsimp, rw category.assoc } }\n\ninstance Sheaf_to_presheaf_is_right_adjoint : is_right_adjoint (Sheaf_to_presheaf J D) :=\n⟨_, sheafification_adjunction J D⟩\n\ninstance presheaf_mono_of_mono {F G : Sheaf J D} (f : F ⟶ G) [mono f] : mono f.1 :=\n(Sheaf_to_presheaf J D).map_mono _\n\nlemma Sheaf.hom.mono_iff_presheaf_mono {F G : Sheaf J D} (f : F ⟶ G) : mono f ↔ mono f.1 :=\n⟨λ m, by { resetI, apply_instance },\n λ m, by { resetI, exact Sheaf.hom.mono_of_presheaf_mono J D f }⟩\n\nvariables {J D}\n/-- A sheaf `P` is isomorphic to its own sheafification. -/\n@[simps]\ndef sheafification_iso (P : Sheaf J D) :\n P ≅ (presheaf_to_Sheaf J D).obj P.val :=\n{ hom := ⟨(J.iso_sheafify P.2).hom⟩,\n inv := ⟨(J.iso_sheafify P.2).inv⟩,\n hom_inv_id' := by { ext1, apply (J.iso_sheafify P.2).hom_inv_id },\n inv_hom_id' := by { ext1, apply (J.iso_sheafify P.2).inv_hom_id } }\n\ninstance is_iso_sheafification_adjunction_counit (P : Sheaf J D) :\n is_iso ((sheafification_adjunction J D).counit.app P) :=\nis_iso_of_fully_faithful (Sheaf_to_presheaf J D) _\n\ninstance sheafification_reflective : is_iso (sheafification_adjunction J D).counit :=\nnat_iso.is_iso_of_is_iso_app _\n\nend category_theory\n", "meta": {"author": "leanprover-community", "repo": "mathlib", "sha": "5e526d18cea33550268dcbbddcb822d5cde40654", "save_path": "github-repos/lean/leanprover-community-mathlib", "path": "github-repos/lean/leanprover-community-mathlib/mathlib-5e526d18cea33550268dcbbddcb822d5cde40654/src/category_theory/sites/sheafification.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.03732689055684297, "lm_q1q2_score": 0.018663445278421485}} {"text": "/-\nCopyright (c) 2020 Robert Y. Lewis. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Robert Y. Lewis\n\n! This file was ported from Lean 3 source module tactic.doc_commands\n! leanprover-community/mathlib commit bc40b44c260045cc3e7ea7e29a9080cd8e92bd57\n! Please do not edit these lines, except to modify the commit id\n! if you have ported upstream changes.\n-/\n\n/-!\n# Documentation commands\n\nWe generate html documentation from mathlib. It is convenient to collect lists of tactics, commands,\nnotes, etc. To facilitate this, we declare these documentation entries in the library\nusing special commands.\n\n* `library_note` adds a note describing a certain feature or design decision. These can be\n referenced in doc strings with the text `note [name of note]`.\n* `add_tactic_doc` adds an entry documenting an interactive tactic, command, hole command, or\n attribute.\n\nSince these commands are used in files imported by `tactic.core`, this file has no imports.\n\n## Implementation details\n\n`library_note note_id note_msg` creates a declaration `` `library_note.i `` for some `i`.\nThis declaration is a pair of strings `note_id` and `note_msg`, and it gets tagged with the\n`library_note` attribute.\n\nSimilarly, `add_tactic_doc` creates a declaration `` `tactic_doc.i `` that stores the provided\ninformation.\n-/\n\n\n/- warning: string.hash -> String.hash is a dubious translation:\nlean 3 declaration is\n String -> Nat\nbut is expected to have type\n ([mdata borrowed:1 String]) -> UInt64\nCase conversion may be inaccurate. Consider using '#align string.hash String.hashₓ'. -/\n/-- A rudimentary hash function on strings. -/\ndef String.hash (s : String) : ℕ :=\n s.fold 1 fun h c => (33 * h + c.val) % unsignedSz\n#align string.hash String.hash\n\n/-- Get the last component of a name, and convert it to a string. -/\nunsafe def name.last : Name → String\n | Name.mk_string s _ => s\n | Name.mk_numeral n _ => repr n\n | anonymous => \"[anonymous]\"\n#align name.last name.last\n\nopen Tactic\n\n/-- `copy_doc_string fr to` copies the docstring from the declaration named `fr`\nto each declaration named in the list `to`. -/\nunsafe def tactic.copy_doc_string (fr : Name) (to : List Name) : tactic Unit := do\n let fr_ds ← doc_string fr\n to fun tgt => add_doc_string tgt fr_ds\n#align tactic.copy_doc_string tactic.copy_doc_string\n\nopen Lean Lean.Parser Interactive\n\n/-- `copy_doc_string source → target_1 target_2 ... target_n` copies the doc string of the\ndeclaration named `source` to each of `target_1`, `target_2`, ..., `target_n`.\n -/\n@[user_command]\nunsafe def copy_doc_string_cmd (_ : parse (tk \"copy_doc_string\")) : parser Unit := do\n let fr ← parser.ident\n tk \"->\"\n let to ← parser.many parser.ident\n let expr.const fr _ ← resolve_name fr\n let to ← parser.of_tactic (to.mapM fun n => expr.const_name <$> resolve_name n)\n tactic.copy_doc_string fr to\n#align copy_doc_string_cmd copy_doc_string_cmd\n\n/-! ### The `library_note` command -/\n\n\n/-- A user attribute `library_note` for tagging decls of type `string × string` for use in note\noutput. -/\n@[user_attribute]\nunsafe def library_note_attr : user_attribute\n where\n Name := `library_note\n descr := \"Notes about library features to be included in documentation\"\n parser := failed\n#align library_note_attr library_note_attr\n\n/-- `mk_reflected_definition name val` constructs a definition declaration by reflection.\n\nExample: ``mk_reflected_definition `foo 17`` constructs the definition\ndeclaration corresponding to `def foo : ℕ := 17`\n-/\nunsafe def mk_reflected_definition (decl_name : Name) {type} [reflected _ type] (body : type)\n [reflected _ body] : declaration :=\n mk_definition decl_name (reflect type).collect_univ_params (reflect type) (reflect body)\n#align mk_reflected_definition mk_reflected_definition\n\n/--\nIf `note_name` and `note` are strings, `add_library_note note_name note` adds a declaration named\n`library_note.` with `note` as the docstring and tags it with the `library_note`\nattribute.\n-/\nunsafe def tactic.add_library_note (note_name note : String) : tactic Unit := do\n let decl_name := .str `library_note note_name\n add_decl <| mk_reflected_definition decl_name ()\n add_doc_string decl_name note\n library_note_attr decl_name () tt none\n#align tactic.add_library_note tactic.add_library_note\n\nopen Tactic\n\n/-- A command to add library notes. Syntax:\n```\n/--\nnote message\n-/\nlibrary_note \"note id\"\n```\n-/\n@[user_command]\nunsafe def library_note (mi : interactive.decl_meta_info) (_ : parse (tk \"library_note\")) :\n parser Unit := do\n let note_name ← parser.pexpr\n let note_name ← eval_pexpr String note_name\n let some doc_string ← pure mi.doc_string |\n fail \"library_note requires a doc string\"\n add_library_note note_name doc_string\n#align library_note library_note\n\n/-- Collects all notes in the current environment.\nReturns a list of pairs `(note_id, note_content)` -/\nunsafe def tactic.get_library_notes : tactic (List (String × String)) :=\n attribute.get_instances `library_note >>=\n List.mapM fun dcl => Prod.mk dcl.getLast <$> doc_string dcl\n#align tactic.get_library_notes tactic.get_library_notes\n\n/-! ### The `add_tactic_doc_entry` command -/\n\n\n/-- The categories of tactic doc entry. -/\ninductive DocCategory\n | tactic\n | cmd\n | hole_cmd\n | attr\n deriving DecidableEq, has_reflect\n#align doc_category DocCategory\n\n/-- Format a `doc_category` -/\nunsafe def doc_category.to_string : DocCategory → String\n | DocCategory.tactic => \"tactic\"\n | DocCategory.cmd => \"command\"\n | DocCategory.hole_cmd => \"hole_command\"\n | DocCategory.attr => \"attribute\"\n#align doc_category.to_string doc_category.to_string\n\nunsafe instance : has_to_format DocCategory :=\n ⟨↑doc_category.to_string⟩\n\n/-- The information used to generate a tactic doc entry -/\nstructure TacticDocEntry where\n Name : String\n category : DocCategory\n declNames : List Name\n tags : List String := []\n inheritDescriptionFrom : Option Name := none\n deriving has_reflect\n#align tactic_doc_entry TacticDocEntry\n\n/-- Turns a `tactic_doc_entry` into a JSON representation. -/\nunsafe def tactic_doc_entry.to_json (d : TacticDocEntry) (desc : String) : json :=\n json.object\n [(\"name\", d.Name), (\"category\", d.category.toString),\n (\"decl_names\", d.declNames.map (json.of_string ∘ toString)),\n (\"tags\", d.tags.map json.of_string), (\"description\", desc)]\n#align tactic_doc_entry.to_json tactic_doc_entry.to_json\n\nunsafe instance tactic_doc_entry.has_to_string : ToString (TacticDocEntry × String) :=\n ⟨fun ⟨doc, desc⟩ => json.unparse (doc.to_json desc)⟩\n#align tactic_doc_entry.has_to_string tactic_doc_entry.has_to_string\n\n/-- A user attribute `tactic_doc` for tagging decls of type `tactic_doc_entry`\nfor use in doc output -/\n@[user_attribute]\nunsafe def tactic_doc_entry_attr : user_attribute\n where\n Name := `tactic_doc\n descr := \"Information about a tactic to be included in documentation\"\n parser := failed\n#align tactic_doc_entry_attr tactic_doc_entry_attr\n\n/-- Collects everything in the environment tagged with the attribute `tactic_doc`. -/\nunsafe def tactic.get_tactic_doc_entries : tactic (List (TacticDocEntry × String)) :=\n attribute.get_instances `tactic_doc >>=\n List.mapM fun dcl => Prod.mk <$> (mk_const dcl >>= eval_expr TacticDocEntry) <*> doc_string dcl\n#align tactic.get_tactic_doc_entries tactic.get_tactic_doc_entries\n\n/-- `add_tactic_doc tde` adds a declaration to the environment\nwith `tde` as its body and tags it with the `tactic_doc`\nattribute. If `tde.decl_names` has exactly one entry `` `decl`` and\nif `tde.description` is the empty string, `add_tactic_doc` uses the doc\nstring of `decl` as the description. -/\nunsafe def tactic.add_tactic_doc (tde : TacticDocEntry) (doc : Option String) : tactic Unit := do\n let desc ←\n doc <|> do\n let inh_id ←\n match tde.inheritDescriptionFrom, tde.declNames with\n | some inh_id, _ => pure inh_id\n | none, [inh_id] => pure inh_id\n | none, _ =>\n fail\n \"A tactic doc entry must either:\\n 1. have a description written as a doc-string for the `add_tactic_doc` invocation, or\\n 2. have a single declaration in the `decl_names` field, to inherit a description from, or\\n 3. explicitly indicate the declaration to inherit the description from using\\n `inherit_description_from`.\"\n doc_string inh_id <|> fail (toString inh_id ++ \" has no doc string\")\n let decl_name := .str (.str `tactic_doc tde.category.toString) tde.Name\n add_decl <| mk_definition decl_name [] q(TacticDocEntry) (reflect tde)\n add_doc_string decl_name desc\n tactic_doc_entry_attr decl_name () tt none\n#align tactic.add_tactic_doc tactic.add_tactic_doc\n\n/-- A command used to add documentation for a tactic, command, hole command, or attribute.\n\nUsage: after defining an interactive tactic, command, or attribute,\nadd its documentation as follows.\n```lean\n/--\ndescribe what the command does here\n-/\nadd_tactic_doc\n{ name := \"display name of the tactic\",\n category := cat,\n decl_names := [`dcl_1, `dcl_2],\n tags := [\"tag_1\", \"tag_2\"] }\n```\n\nThe argument to `add_tactic_doc` is a structure of type `tactic_doc_entry`.\n* `name` refers to the display name of the tactic; it is used as the header of the doc entry.\n* `cat` refers to the category of doc entry.\n Options: `doc_category.tactic`, `doc_category.cmd`, `doc_category.hole_cmd`, `doc_category.attr`\n* `decl_names` is a list of the declarations associated with this doc. For instance,\n the entry for `linarith` would set ``decl_names := [`tactic.interactive.linarith]``.\n Some entries may cover multiple declarations.\n It is only necessary to list the interactive versions of tactics.\n* `tags` is an optional list of strings used to categorize entries.\n* The doc string is the body of the entry. It can be formatted with markdown.\n What you are reading now is the description of `add_tactic_doc`.\n\nIf only one related declaration is listed in `decl_names` and if this\ninvocation of `add_tactic_doc` does not have a doc string, the doc string of\nthat declaration will become the body of the tactic doc entry. If there are\nmultiple declarations, you can select the one to be used by passing a name to\nthe `inherit_description_from` field.\n\nIf you prefer a tactic to have a doc string that is different then the doc entry,\nyou should write the doc entry as a doc string for the `add_tactic_doc` invocation.\n\nNote that providing a badly formed `tactic_doc_entry` to the command can result in strange error\nmessages.\n\n-/\n@[user_command]\nunsafe def add_tactic_doc_command (mi : interactive.decl_meta_info)\n (_ : parse <| tk \"add_tactic_doc\") : parser Unit := do\n let pe ← parser.pexpr\n let e ← eval_pexpr TacticDocEntry pe\n tactic.add_tactic_doc e mi\n#align add_tactic_doc_command add_tactic_doc_command\n\n/-- At various places in mathlib, we leave implementation notes that are referenced from many other\nfiles. To keep track of these notes, we use the command `library_note`. This makes it easy to\nretrieve a list of all notes, e.g. for documentation output.\n\nThese notes can be referenced in mathlib with the syntax `Note [note id]`.\nOften, these references will be made in code comments (`--`) that won't be displayed in docs.\nIf such a reference is made in a doc string or module doc, it will be linked to the corresponding\nnote in the doc display.\n\nSyntax:\n```\n/--\nnote message\n-/\nlibrary_note \"note id\"\n```\n\nAn example from `meta.expr`:\n\n```\n/--\nSome declarations work with open expressions, i.e. an expr that has free variables.\nTerms will free variables are not well-typed, and one should not use them in tactics like\n`infer_type` or `unify`. You can still do syntactic analysis/manipulation on them.\nThe reason for working with open types is for performance: instantiating variables requires\niterating through the expression. In one performance test `pi_binders` was more than 6x\nquicker than `mk_local_pis` (when applied to the type of all imported declarations 100x).\n-/\nlibrary_note \"open expressions\"\n```\n\nThis note can be referenced near a usage of `pi_binders`:\n\n\n```\n-- See Note [open expressions]\n/-- behavior of f -/\ndef f := pi_binders ...\n```\n-/\nadd_tactic_doc\n { Name := \"library_note\"\n category := DocCategory.cmd\n declNames := [`library_note, `tactic.add_library_note]\n tags := [\"documentation\"]\n inheritDescriptionFrom := `library_note }\n\nadd_tactic_doc\n { Name := \"add_tactic_doc\"\n category := DocCategory.cmd\n declNames := [`add_tactic_doc_command, `tactic.add_tactic_doc]\n tags := [\"documentation\"]\n inheritDescriptionFrom := `add_tactic_doc_command }\n\nadd_tactic_doc\n { Name := \"copy_doc_string\"\n category := DocCategory.cmd\n declNames := [`copy_doc_string_cmd, `tactic.copy_doc_string]\n tags := [\"documentation\"]\n inheritDescriptionFrom := `copy_doc_string_cmd }\n\n-- add docs to core tactics\n/-- The congruence closure tactic `cc` tries to solve the goal by chaining\nequalities from context and applying congruence (i.e. if `a = b`, then `f a = f b`).\nIt is a finishing tactic, i.e. it is meant to close\nthe current goal, not to make some inconclusive progress.\nA mostly trivial example would be:\n\n```lean\nexample (a b c : ℕ) (f : ℕ → ℕ) (h: a = b) (h' : b = c) : f a = f c := by cc\n```\n\nAs an example requiring some thinking to do by hand, consider:\n\n```lean\nexample (f : ℕ → ℕ) (x : ℕ)\n (H1 : f (f (f x)) = x) (H2 : f (f (f (f (f x)))) = x) :\n f x = x :=\nby cc\n```\n\nThe tactic works by building an equality matching graph. It's a graph where\nthe vertices are terms and they are linked by edges if they are known to\nbe equal. Once you've added all the equalities in your context, you take\nthe transitive closure of the graph and, for each connected component\n(i.e. equivalence class) you can elect a term that will represent the\nwhole class and store proofs that the other elements are equal to it.\nYou then take the transitive closure of these equalities under the\ncongruence lemmas.\n\nThe `cc` implementation in Lean does a few more tricks: for example it\nderives `a=b` from `nat.succ a = nat.succ b`, and `nat.succ a !=\nnat.zero` for any `a`.\n\n* The starting reference point is Nelson, Oppen, [Fast decision procedures based on congruence\nclosure](http://www.cs.colorado.edu/~bec/courses/csci5535-s09/reading/nelson-oppen-congruence.pdf),\nJournal of the ACM (1980)\n\n* The congruence lemmas for dependent type theory as used in Lean are described in\n[Congruence closure in intensional type theory](https://leanprover.github.io/papers/congr.pdf)\n(de Moura, Selsam IJCAR 2016).\n-/\nadd_tactic_doc\n { Name := \"cc (congruence closure)\"\n category := DocCategory.tactic\n declNames := [`tactic.interactive.cc]\n tags := [\"core\", \"finishing\"] }\n\n/-- `conv {...}` allows the user to perform targeted rewriting on a goal or hypothesis,\nby focusing on particular subexpressions.\n\nSee for more details.\n\nInside `conv` blocks, mathlib currently additionally provides\n* `erw`,\n* `ring`, `ring2` and `ring_exp`,\n* `norm_num`,\n* `norm_cast`,\n* `apply_congr`, and\n* `conv` (within another `conv`).\n\n`apply_congr` applies congruence lemmas to step further inside expressions,\nand sometimes gives better results than the automatically generated\ncongruence lemmas used by `congr`.\n\nUsing `conv` inside a `conv` block allows the user to return to the previous\nstate of the outer `conv` block after it is finished. Thus you can continue\nediting an expression without having to start a new `conv` block and re-scoping\neverything. For example:\n```lean\nexample (a b c d : ℕ) (h₁ : b = c) (h₂ : a + c = a + d) : a + b = a + d :=\nby conv\n{ to_lhs,\n conv\n { congr, skip,\n rw h₁ },\n rw h₂, }\n```\nWithout `conv`, the above example would need to be proved using two successive\n`conv` blocks, each beginning with `to_lhs`.\n\nAlso, as a shorthand, `conv_lhs` and `conv_rhs` are provided, so that\n```lean\nexample : 0 + 0 = 0 :=\nbegin\n conv_lhs { simp }\nend\n```\njust means\n```lean\nexample : 0 + 0 = 0 :=\nbegin\n conv { to_lhs, simp }\nend\n```\nand likewise for `to_rhs`.\n-/\nadd_tactic_doc\n { Name := \"conv\"\n category := DocCategory.tactic\n declNames := [`tactic.interactive.conv]\n tags := [\"core\"] }\n\nadd_tactic_doc\n { Name := \"simp\"\n category := DocCategory.tactic\n declNames := [`tactic.interactive.simp]\n tags := [\"core\", \"simplification\"] }\n\n/-- Accepts terms with the type `component tactic_state string` or `html empty` and\nrenders them interactively.\nRequires a compatible version of the vscode extension to view the resulting widget.\n\n### Example:\n\n```lean\n/-- A simple counter that can be incremented or decremented with some buttons. -/\nmeta def counter_widget {π α : Type} : component π α :=\ncomponent.ignore_props $ component.mk_simple int int 0 (λ _ x y, (x + y, none)) (λ _ s,\n h \"div\" [] [\n button \"+\" (1 : int),\n html.of_string $ to_string $ s,\n button \"-\" (-1)\n ]\n)\n\n#html counter_widget\n```\n-/\nadd_tactic_doc\n { Name := \"#html\"\n category := DocCategory.cmd\n declNames := [`show_widget_cmd]\n tags := [\"core\", \"widgets\"] }\n\n/-- The `add_decl_doc` command is used to add a doc string to an existing declaration.\n\n```lean\ndef foo := 5\n\n/--\nDoc string for foo.\n-/\nadd_decl_doc foo\n```\n-/\n@[user_command]\nunsafe def add_decl_doc_command (mi : interactive.decl_meta_info) (_ : parse <| tk \"add_decl_doc\") :\n parser Unit := do\n let n ← parser.ident\n let n ← resolve_constant n\n let some doc ← pure mi.doc_string |\n fail \"add_decl_doc requires a doc string\"\n add_doc_string n doc\n#align add_decl_doc_command add_decl_doc_command\n\nadd_tactic_doc\n { Name := \"add_decl_doc\"\n category := DocCategory.cmd\n declNames := [`` add_decl_doc_command]\n tags := [\"documentation\"] }\n\n", "meta": {"author": "leanprover-community", "repo": "mathlib3port", "sha": "62505aa236c58c8559783b16d33e30df3daa54f4", "save_path": "github-repos/lean/leanprover-community-mathlib3port", "path": "github-repos/lean/leanprover-community-mathlib3port/mathlib3port-62505aa236c58c8559783b16d33e30df3daa54f4/Mathbin/Tactic/DocCommands.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2720245510940225, "lm_q2_score": 0.06853749160505271, "lm_q1q2_score": 0.0186438803869748}} {"text": "/-\nCopyright (c) 2018 Simon Hudon. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthor: Simon Hudon\n\nInstances of `traversable` for types from the core library\n-/\n\nimport category.traversable.basic category.basic category.functor category.applicative\nimport data.list.basic data.set.lattice\n\nuniverses u v\n\nopen function\n\ninstance : traversable id := ⟨λ _ _ _ _, id⟩\ninstance : is_lawful_traversable id := by refine {..}; intros; refl\n\nsection option\n\nopen function functor\n\nsection inst\n\nvariables {F : Type u → Type v} [applicative F]\n\ninstance : traversable option := ⟨@option.traverse⟩\n\nend inst\n\nvariables {F G : Type u → Type u}\nvariables [applicative F] [applicative G]\nvariables [is_lawful_applicative F] [is_lawful_applicative G]\n\nlemma option.id_traverse {α} (x : option α) : option.traverse id.mk x = x :=\nby cases x; refl\n\nlemma option.comp_traverse {α β γ} (f : β → F γ) (g : α → G β) (x : option α) :\n option.traverse (comp.mk ∘ (<$>) f ∘ g) x =\n comp.mk (option.traverse f <$> option.traverse g x) :=\nby cases x; simp! with functor_norm; refl\n\nlemma option.traverse_eq_map_id {α β} (f : α → β) (x : option α) :\n traverse (id.mk ∘ f) x = id.mk (f <$> x) :=\nby cases x; refl\n\nvariable (η : applicative_transformation F G)\n\nlemma option.naturality {α β} (f : α → F β) (x : option α) :\n η (option.traverse f x) = option.traverse (@η _ ∘ f) x :=\nby cases x with x; simp! [*] with functor_norm\n\nend option\n\ninstance : is_lawful_traversable option :=\n{ id_traverse := @option.id_traverse,\n comp_traverse := @option.comp_traverse,\n traverse_eq_map_id := @option.traverse_eq_map_id,\n naturality := @option.naturality }\n\nnamespace list\n\nvariables {F G : Type u → Type u}\nvariables [applicative F] [applicative G]\nvariables [is_lawful_applicative F] [is_lawful_applicative G]\n\nopen applicative functor\nopen list (cons)\n\nprotected lemma id_traverse {α} (xs : list α) :\n list.traverse id.mk xs = xs :=\nby induction xs; simp! * with functor_norm; refl\n\nprotected lemma comp_traverse {α β γ} (f : β → F γ) (g : α → G β) (x : list α) :\n list.traverse (comp.mk ∘ (<$>) f ∘ g) x =\n comp.mk (list.traverse f <$> list.traverse g x) :=\nby induction x; simp! * with functor_norm; refl\n\nprotected lemma traverse_eq_map_id {α β} (f : α → β) (x : list α) :\n list.traverse (id.mk ∘ f) x = id.mk (f <$> x) :=\nby induction x; simp! * with functor_norm; refl\n\nvariable (η : applicative_transformation F G)\n\nprotected lemma naturality {α β} (f : α → F β) (x : list α) :\n η (list.traverse f x) = list.traverse (@η _ ∘ f) x :=\nby induction x; simp! * with functor_norm\nopen nat\n\ninstance : traversable list := ⟨@list.traverse⟩\n\ninstance : is_lawful_traversable list :=\n{ id_traverse := @list.id_traverse,\n comp_traverse := @list.comp_traverse,\n traverse_eq_map_id := @list.traverse_eq_map_id,\n naturality := @list.naturality }\n\nsection traverse\nvariables {α' β' : Type u} (f : α' → F β')\n\n@[simp] lemma traverse_nil : traverse f ([] : list α') = (pure [] : F (list β')) := rfl\n\n@[simp] lemma traverse_cons (a : α') (l : list α') :\n traverse f (a :: l) = (::) <$> f a <*> traverse f l := rfl\n\nvariables [is_lawful_applicative F]\n\n@[simp] lemma traverse_append :\n ∀ (as bs : list α'), traverse f (as ++ bs) = (++) <$> traverse f as <*> traverse f bs\n| [] bs :=\n have has_append.append ([] : list β') = id, by funext; refl,\n by simp [this] with functor_norm\n| (a :: as) bs := by simp [traverse_append as bs] with functor_norm; congr\n\nlemma mem_traverse {f : α' → set β'} :\n ∀(l : list α') (n : list β'), n ∈ traverse f l ↔ forall₂ (λb a, b ∈ f a) n l\n| [] [] := by simp\n| (a::as) [] := by simp; exact assume h, match h with end\n| [] (b::bs) := by simp\n| (a::as) (b::bs) :=\n suffices (b :: bs : list β') ∈ traverse f (a :: as) ↔ b ∈ f a ∧ bs ∈ traverse f as,\n by simpa [mem_traverse as bs],\n iff.intro\n (assume ⟨_, ⟨b, hb, rfl⟩, _, hl, rfl⟩, ⟨hb, hl⟩)\n (assume ⟨hb, hl⟩, ⟨_, ⟨b, hb, rfl⟩, _, hl, rfl⟩)\n\nend traverse\n\nend list\n\nnamespace sum\n\nsection traverse\nvariables {σ : Type u}\nvariables {F G : Type u → Type u}\nvariables [applicative F] [applicative G]\n\nopen applicative functor\nopen list (cons)\n\nprotected def traverse {α β} (f : α → F β) : σ ⊕ α → F (σ ⊕ β)\n| (sum.inl x) := pure (sum.inl x)\n| (sum.inr x) := sum.inr <$> f x\n\nvariables [is_lawful_applicative F] [is_lawful_applicative G]\n\nprotected lemma id_traverse {σ α} (x : σ ⊕ α) : sum.traverse id.mk x = x :=\nby cases x; refl\n\nprotected lemma comp_traverse {α β γ} (f : β → F γ) (g : α → G β) (x : σ ⊕ α) :\n sum.traverse (comp.mk ∘ (<$>) f ∘ g) x =\n comp.mk (sum.traverse f <$> sum.traverse g x) :=\nby cases x; simp! [sum.traverse,map_id] with functor_norm; refl\n\nprotected lemma traverse_eq_map_id {α β} (f : α → β) (x : σ ⊕ α) :\n sum.traverse (id.mk ∘ f) x = id.mk (f <$> x) :=\nby induction x; simp! * with functor_norm; refl\n\nprotected lemma map_traverse {α β γ} (g : α → G β) (f : β → γ) (x : σ ⊕ α) :\n (<$>) f <$> sum.traverse g x = sum.traverse ((<$>) f ∘ g) x :=\nby cases x; simp [(<$>), sum.mapr, sum.traverse, id_map] with functor_norm; congr\n\nprotected lemma traverse_map {α β γ : Type u} (g : α → β) (f : β → G γ) (x : σ ⊕ α) :\n sum.traverse f (g <$> x) = sum.traverse (f ∘ g) x :=\nby cases x; simp [(<$>), sum.mapr, sum.traverse, id_map] with functor_norm\n\nvariable (η : applicative_transformation F G)\n\nprotected lemma naturality {α β} (f : α → F β) (x : σ ⊕ α) :\n η (sum.traverse f x) = sum.traverse (@η _ ∘ f) x :=\nby cases x; simp! [sum.traverse] with functor_norm\n\nend traverse\n\ninstance {σ : Type u} : traversable.{u} (sum σ) := ⟨@sum.traverse _⟩\n\ninstance {σ : Type u} : is_lawful_traversable.{u} (sum σ) :=\n{ id_traverse := @sum.id_traverse σ,\n comp_traverse := @sum.comp_traverse σ,\n traverse_eq_map_id := @sum.traverse_eq_map_id σ,\n naturality := @sum.naturality σ }\n\nend sum\n", "meta": {"author": "khoek", "repo": "mathlib-tidy", "sha": "866afa6ab597c47f1b72e8fe2b82b97fff5b980f", "save_path": "github-repos/lean/khoek-mathlib-tidy", "path": "github-repos/lean/khoek-mathlib-tidy/mathlib-tidy-866afa6ab597c47f1b72e8fe2b82b97fff5b980f/category/traversable/instances.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2751297238231752, "lm_q2_score": 0.0675466977093867, "lm_q1q2_score": 0.018584104285951066}} {"text": "/-\nHere is an example where temporary metavariables from typeclass resolution\ncould spill into nested typeclass resolution, for which the outer TC succeeds\niff:\n\n1. the inner TC is still called, even with the leaked tmp mvars\n2. the inner TC is allowed to assign the leaked tmp mvars\n\nThis example will *NOT* work in Lean4.\n\nAlthough it would be easy to allow inner TC to set the outer TC tmp mvars,\nthe issue is that the solution to the inner TC problem may not be unique,\nand it would be extremely difficult to allow backtracking from the outer TC\nthrough to the inner TC.\n\nIn Lean4, inner TC can be called with leaked temporary mvars from the outer TC,\nbut they are treated as opaque, just as regular mvars are treated in the outer TC.\nSo, this example will fail.\n-/\n\nclass Foo (α : Type) : Type := (x : Unit)\nclass Zoo (α : Type) : Type := (x : Unit)\nclass Bar (α : Type) : Type := (x : Unit)\nclass HasParam (α : Type) [Bar α] : Type := (x : Unit)\n\ninstance FooToBar (α : Type) [f : Foo α] : Bar α :=\nmatch f.x with\n| () => {x:=()}\n\ninstance ZooToBar (α : Type) [z : Zoo α] : Bar α :=\nmatch z.x with\n| () => {x:=()}\n\ninstance HasParamInst (α : Type) [h : Foo α] : HasParam α := {x:=()}\n\nclass Top : Type := (x : Unit)\n\ninstance FooInt : Foo Int := {x:=()}\ninstance AllZoo (α : Type) : Zoo α := {x:=()}\n\ninstance Bad (α : Type) [HasParam α] : Top := Top.mk ()\n\nset_option pp.all true\nset_option trace.class_instances true\nset_option trace.type_context.complete_instance true\n\ndef foo [Top] : Unit := ()\n#check @foo _\n\n/-\n[class_instances] class-instance resolution trace\n[class_instances] (0) ?x_0 : Top := @Bad ?x_1 ?x_2\n[class_instances] (1) ?x_2 : @HasParam ?x_1 (@ZooToBar ?x_1 (AllZoo ?x_1)) := @HasParamInst ?x_3 ?x_4\n[type_context.complete_instance] would have synthed: Foo ?x_3\n[type_context.complete_instance] would have synthed: Foo ?x_3\nfailed is_def_eq\n-/\n\ndef couldWork : Top :=\n@Bad Int (@HasParamInst Int FooInt)\n\n#print couldWork\n/-\ndef couldWork : Top :=\n@Bad Int (@HasParamInst Int FooInt)\n-/\n", "meta": {"author": "leanprover", "repo": "lean4", "sha": "742d053a97bdd109a41a921facd1cd6a55e89bc7", "save_path": "github-repos/lean/leanprover-lean4", "path": "github-repos/lean/leanprover-lean4/lean4-742d053a97bdd109a41a921facd1cd6a55e89bc7/tests/elabissues/leaky_tmp_metavars2.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167645017354, "lm_q2_score": 0.04023794535707827, "lm_q1q2_score": 0.01855036737871785}} {"text": "import tactic.find\n\n#find (ff = _)\n\nconstants \n(f : nat → nat)\n(f₀ : f 0 = 0)\n(f₁ : f 1 = 1)\n(f₂ : f 2 = 1)\n(f_next : ∀ n : nat, f (n + 3) = f (n + 2) + f (n + 1) ∨ f (n + 3) = f (n + 1) + f n)\n\nnamespace evaluation\n\nmeta def hasElement : list nat → nat → bool\n| [] _ := ff\n| (x :: xs) e := if e = x then tt else hasElement xs e\n\n#eval hasElement [1,2,3] 1 -- tt\n#eval hasElement [1,2,3] 4 -- ff\n\n#reduce hasElement [1,2,3] 1 -- tt\n\n-- def union (lx ly : list nat) : list nat :=\n-- match lx, ly with\n-- | [], listy := listy\n-- | listx, [] := listx\n-- | (x :: xs), listy := if hasElem listy x then union xs listy else union xs (x :: listy)\n-- end\n-- @[reducible]\nmeta def union : list nat → list nat → list nat\n| [] ys := ys\n| (x :: xs) ys := if hasElement ys x then union xs ys else union xs (x :: ys)\n\n#print union._main\n\n#eval union [1,2,3,4,5] [1] -- [5, 4, 3, 2, 1]\n#eval union [1,2,3] [4,5,6] -- [3, 2, 1, 4, 5, 6]\n\n#eval union [1,2,3] [] -- [3, 2, 1]\n#reduce union [1,2,3] [] -- [union._main] [2, 3] [1], why reduce doesn't return the same result as eval?\n\nend evaluation\n\nnamespace lemmas\n\nset_option trace.simplify.rewrite true\n\nconstant hasElement : list nat → nat → bool\n\nnamespace hasElement\n\naxiom base (n : nat) : hasElement [] n = ff\naxiom step (x : nat) (xs : list nat) : hasElement (x :: xs) x = tt\naxiom step_not_eq (x y : nat) (xs : list nat) (h : x ≠ y) :\n hasElement (x :: xs) y = hasElement xs y\n\nlemma empty_not_contains_any (x : nat) : ¬ hasElement [] x = tt :=\nbegin\n rw hasElement.base _,\n -- change ¬ false = true, -- fail\n -- rw not.elim, -- fail\n -- rw not_false_iff, -- fail\n apply not.intro,\n exact bool.ff_ne_tt,\nend\n\nlemma single {x : nat} : hasElement [x] x := \n hasElement.step x []\n\nlemma two (x y : nat) : hasElement [x, y] y :=\nbegin\n -- if x = y => tt\n -- if x ≠ y => hasElement [y] y => tt [by single]\n by_cases (x = y),\n {\n rw ←h,\n exact hasElement.step x [x],\n },\n {\n change x ≠ y at h,\n -- rw hasElement.step_not_eq _ _ _ h, -- OK\n rw hasElement.step_not_eq,\n { exact @single y },\n { exact h },\n },\nend\n\nexample : ¬ hasElement [0] 1 :=\nbegin\n rw hasElement.step_not_eq,\n apply empty_not_contains_any,\n exact zero_ne_one,\nend\n\n#print two\n\n\nend hasElement\n\nvariables {x : ℕ} {xs ys : list ℕ}\n\nconstant union : list nat → list nat → list nat\n\naxiom union_base (xs : list nat) :\n union [] xs = xs\n\naxiom union_step₁ (h : hasElement ys x) :\n union (x :: xs) ys = union xs ys\n\naxiom union_step₂ (h : hasElement ys x → false) :\n union (x :: xs) ys = union xs (x :: ys)\n\n\nlemma union_single : union [x] [x] = [x] :=\nbegin\n have h₁ : union [] [x] = [x] := union_base [x],\n have h₂ : hasElement [x] x → union [x] [x] = union [] [x] := union_step₁,\n have h₃ : union [x] [x] = union [] [x] := h₂ hasElement.single,\n apply eq.trans h₃,\n exact h₁,\nend\n\nlemma union_single' : union [x] [x] = [x] :=\nbegin\n rw union_step₁,\n rw union_base,\n apply hasElement.single,\nend\n\n#print notation >>=\n\nopen tactic\nmeta def trace_all : tactic unit :=\n do n ← num_goals\n , trace \"num_goals =\"\n , trace n\n , trace_state\n , trace \"---------------------------------------------\"\n , trace_result\n\nlemma union_single'' : union [x] [x] = [x] := by { \n apply eq.trans (union_step₁ hasElement.single),\n trace_all,\n sorry\n}\n\nmeta def test_tactic : tactic unit :=\ndo \n define `x (expr.const `nat [])\n, trace \"-- after assert --\"\n, trace_state\n, n ← get_local `n\n, trace (infer_type n)\n\nexample (n : nat) : n = n := by { test_tactic, sorry }\n\nexample : (1 = 2) → (2 = 3) → (3 = 1) := begin\n assume h1 h2,\n apply eq.symm,\n apply eq.subst h2,\n apply eq.subst h1,\n apply eq.refl,\n trace_result,\n trace_call_stack,\nend\n\nexample (a : nat) (b : bool) (c : int) : true := by {\n do \n a ← get_local `a\n , b ← get_local `b\n , c ← get_local `c\n , infer_type a >>= trace\n , infer_type b >>= trace\n , infer_type c >>= trace\n , interactive.sorry\n}\n\nset_option trace.app_builder true\n-- set_option pp.all true\n\nexample (a b c : ℕ) : true := by {\n do\n a ← get_local `a\n , x ← mk_app `nat.succ [a] -- x : expr\n , r ← to_expr ```(%%x + b * c + (λ n, n) 100) -- to_expr : pexpr → tactic expr\n , trace r -- a.succ + b * c + (λ (n : ℕ), n) 100\n , infer_type r >>= trace -- ℕ\n , interactive.trivial -- or exact_dec_trivial\n}\n\n\nexample (a b c : nat) (H1 : a = b) (H2 : b = c) : a = c :=\nby do\n -- refine ```(eq.trans H1 _),\n interactive.refine ```(eq.trans H1 _),\n trace_state,\n assumption\n\nend lemmas\n\n\n\nmeta def solve (n : nat) (f : nat → nat) :=\nmatch n, f with\n| 0, f := 0\n| _, _ := 1\nend\n\n-- solve n = [f 0, f 1, f 2, ... f (n-1)]\n-- solve 0 = [[]]\n-- solve 1 = [[0]]\n-- solve 2 = [[0], [1]]\n-- solve 3 = [[0], [1], [1]]\n-- solve 4 = [[0], [1], [1], [1, 2]]\n-- solve 5 = [[0], [1], [1], [1, 2], X], \n-- where X = (1 + [1, 2]) ∪ (1 + 1) = [2, 3] ∪ [2] = [2, 3]\n\n#print add_lt_add_of_le_of_lt -- a ≤ b → c < d → a + c < b + d\n\n#print add_pos_of_nonneg_of_pos -- 0 ≤ a → 0 < b → 0 < a + b\n-- (ha : 0 ≤ a) (hb : 0 < b),\n -- zero_add 0 ▸ add_lt_add_of_le_of_lt ha hb\n\n#print notation ▸ -- eq.subst #1 #0\n#print notation + -- has_add.add #1 #0\n#print eq.subst", "meta": {"author": "mathprocessing", "repo": "lean_mathlib_examples", "sha": "743c6456c0a3219dd1722efdd31ee6f3a113818a", "save_path": "github-repos/lean/mathprocessing-lean_mathlib_examples", "path": "github-repos/lean/mathprocessing-lean_mathlib_examples/lean_mathlib_examples-743c6456c0a3219dd1722efdd31ee6f3a113818a/src/functional_equations/example1.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41489884579676883, "lm_q2_score": 0.04468086725142008, "lm_q1q2_score": 0.018538040251812837}} {"text": "import for_mathlib.open_embeddings\n\nimport sheaves.sheaf_of_topological_rings\nimport sheaves.stalk_of_rings\n\nuniverse variable u\n\nopen topological_space\n\nvariables {X : Type u} {Y : Type u} {Z : Type u}\nvariables [topological_space X] [topological_space Y] [topological_space Z]\n\nnamespace presheaf_of_rings\nvariables {F : presheaf_of_rings X} {G : presheaf_of_rings Y} {H : presheaf_of_rings Z}\n\nstructure f_map\n (F : presheaf_of_rings X) (G : presheaf_of_rings Y) :=\n(f : X → Y)\n(hf : continuous f)\n(f_flat : ∀ V : opens Y, G V → F (hf.comap V))\n(f_flat_is_ring_hom : ∀ V : opens Y, is_ring_hom (f_flat V))\n(presheaf_f_flat : ∀ V W : opens Y, ∀ (hWV : W ⊆ V),\n ∀ s : G V, F.res _ _ (hf.comap_mono hWV) (f_flat V s) = f_flat W (G.res V W hWV s))\n\nattribute [instance] f_map.f_flat_is_ring_hom\n\ndef f_map_id (F : presheaf_of_rings X) : presheaf_of_rings.f_map F F :=\n{ f := λ x, x,\n hf := continuous_id,\n f_flat := λ U, F.res _ _ (λ _ hx, hx),\n f_flat_is_ring_hom := λ U, presheaf_of_rings.res_is_ring_hom _ _ _ _,\n presheaf_f_flat := λ U V hVU s, begin\n rw ←F.to_presheaf.Hcomp',\n rw ←F.to_presheaf.Hcomp',\n end }\n\ndef f_map.comp (a : presheaf_of_rings.f_map F G) (b : presheaf_of_rings.f_map G H) :\npresheaf_of_rings.f_map F H :=\n{ f := λ x, b.f (a.f x),\n hf := b.hf.comp a.hf,\n f_flat := λ V s, (a.f_flat (b.hf.comap V)) ((b.f_flat V) s),\n f_flat_is_ring_hom := λ V, show (is_ring_hom ((a.f_flat (b.hf.comap V)) ∘ (b.f_flat V))), from is_ring_hom.comp _ _,\n presheaf_f_flat := λ V W hWV s,\n begin\n rw ←b.presheaf_f_flat V W hWV s,\n rw ←a.presheaf_f_flat (b.hf.comap V) (b.hf.comap W) (b.hf.comap_mono hWV),\n refl,\n end }\n\n@[simp] lemma f_map.id_comp (a : presheaf_of_rings.f_map F G) :\n (presheaf_of_rings.f_map_id F).comp a = a :=\nbegin\n cases a, delta presheaf_of_rings.f_map_id presheaf_of_rings.f_map.comp,\n congr, funext V s, dsimp,\n show _ = id _, apply congr_fun, exact F.to_presheaf.Hid _,\nend\n\n@[simp] lemma f_map.comp_id (a : presheaf_of_rings.f_map F G) :\n a.comp (presheaf_of_rings.f_map_id G) = a :=\nbegin\n cases a with f hf f_flat f_flat_is_ring_hom presheaf_f_flat,\n delta presheaf_of_rings.f_map_id presheaf_of_rings.f_map.comp,\n congr, funext V s, dsimp,\n rw ← presheaf_f_flat,\n show _ = id _, apply congr_fun, exact F.to_presheaf.Hid _,\nend\n\nend presheaf_of_rings\n\nnamespace presheaf_of_topological_rings\nvariables {F : presheaf_of_topological_rings X} {G : presheaf_of_topological_rings Y} {H : presheaf_of_topological_rings Z}\n\nstructure f_map (F : presheaf_of_topological_rings X) (G : presheaf_of_topological_rings Y) :=\n(f : X → Y)\n(hf : continuous f)\n(f_flat : ∀ V : opens Y, G V → F (hf.comap V))\n[f_flat_is_ring_hom : ∀ V : opens Y, is_ring_hom (f_flat V)]\n(cont_f_flat : ∀ V : opens Y, continuous (f_flat V))\n(presheaf_f_flat : ∀ V W : opens Y, ∀ (hWV : W ⊆ V),\n ∀ s : G V, F.res _ _ (hf.comap_mono hWV) (f_flat V s) = f_flat W (G.res V W hWV s))\n\ninstance f_map_flat.is_ring_hom (f : presheaf_of_topological_rings.f_map F G) (V : opens Y) :\n is_ring_hom (f.f_flat V) := f.f_flat_is_ring_hom V\n\nattribute [instance] presheaf_of_topological_rings.f_map.f_flat_is_ring_hom\n\ndef f_map.to_presheaf_of_rings_f_map\n {X : Type u} [topological_space X] {Y : Type u} [topological_space Y]\n {F : presheaf_of_topological_rings X} {G : presheaf_of_topological_rings Y}\n (f : presheaf_of_topological_rings.f_map F G) :\n presheaf_of_rings.f_map F.to_presheaf_of_rings G.to_presheaf_of_rings :=\n{ ..f}\n\n@[ext]\nlemma presheaf_of_topological_rings.f_map.ext\n {X : Type u} [topological_space X] {Y : Type u} [topological_space Y]\n {F : presheaf_of_topological_rings X} {G : presheaf_of_topological_rings Y}\n (a b : F.f_map G) (h : a.to_presheaf_of_rings_f_map = b.to_presheaf_of_rings_f_map) :\n a = b :=\nbegin\n cases a, cases b,\n dsimp [f_map.to_presheaf_of_rings_f_map] at h,\n injections,\n simp [*]\nend\n\n@[simp] lemma f_map.to_presheaf_of_rings_f_map_f (f : presheaf_of_topological_rings.f_map F G) :\n f.to_presheaf_of_rings_f_map.f = f.f := rfl\n\ndef f_map_id (F : presheaf_of_topological_rings X) :\n presheaf_of_topological_rings.f_map F F :=\n{ cont_f_flat := λ U, begin\n show continuous (((F.to_presheaf_of_rings).to_presheaf).res U (continuous.comap continuous_id U) _),\n convert continuous_id,\n { simp [continuous.comap_id U] },\n { simp [continuous.comap_id U] },\n convert heq_of_eq (F.Hid U),\n rw continuous.comap_id U,\n exact continuous.comap_id U,\n end,\n ..presheaf_of_rings.f_map_id F.to_presheaf_of_rings }\n\n@[simp] lemma f_map.to_presheaf_of_rings_f_map_id (F : presheaf_of_topological_rings X) :\n (presheaf_of_topological_rings.f_map_id F).to_presheaf_of_rings_f_map =\n presheaf_of_rings.f_map_id F.to_presheaf_of_rings := rfl\n\n@[simp] lemma f_map_id_apply (F : presheaf_of_topological_rings X) (x : X) :\n (presheaf_of_topological_rings.f_map_id F).f x = x := rfl\n\ndef f_map.comp (a : presheaf_of_topological_rings.f_map F G) (b : presheaf_of_topological_rings.f_map G H) :\n presheaf_of_topological_rings.f_map F H :=\n{ cont_f_flat := λ V, (a.cont_f_flat _).comp (b.cont_f_flat _),\n .. a.to_presheaf_of_rings_f_map.comp b.to_presheaf_of_rings_f_map }\n\n@[simp] lemma f_map.comp_f (a : presheaf_of_topological_rings.f_map F G) (b : presheaf_of_topological_rings.f_map G H) :\n (a.comp b).f = b.f ∘ a.f := rfl\n\n@[simp] lemma f_map.comp_to_presheaf_of_rings_f_map\n (a : presheaf_of_topological_rings.f_map F G) (b : presheaf_of_topological_rings.f_map G H) :\n (a.comp b).to_presheaf_of_rings_f_map =\n a.to_presheaf_of_rings_f_map.comp b.to_presheaf_of_rings_f_map := rfl\n\n@[simp] lemma f_map.id_comp (a : presheaf_of_topological_rings.f_map F G) :\n (presheaf_of_topological_rings.f_map_id F).comp a = a :=\nby ext; simp\n\n@[simp] lemma f_map.comp_id (a : presheaf_of_topological_rings.f_map F G) :\n a.comp (presheaf_of_topological_rings.f_map_id G) = a :=\nby ext; simp\n\nend presheaf_of_topological_rings\n\nopen_locale classical\n\n/-- The map on stalks induced from an f-map -/\nnoncomputable def stalk_map {F : presheaf_of_rings X} {G : presheaf_of_rings Y}\n (f : F.f_map G) (x : X) :\n stalk_of_rings G (f.f x) → stalk_of_rings F x :=\nto_stalk.rec G (f.f x) (stalk_of_rings F x)\n (λ V hfx s, ⟦⟨f.hf.comap V, hfx, f.f_flat V s⟩⟧)\n (λ V W H r hfx, quotient.sound begin\n use [f.hf.comap V, hfx, set.subset.refl _, f.hf.comap_mono H],\n erw F.to_presheaf.Hid,\n symmetry,\n apply f.presheaf_f_flat\n end )\n\nnamespace stalk_map\nvariables {F : presheaf_of_rings X} {G : presheaf_of_rings Y} {H : presheaf_of_rings Z}\nvariables (f : F.f_map G) (g : G.f_map H)\n\ninstance (F : presheaf_of_rings X) (x : X) :\n comm_ring (quotient (stalk.setoid (F.to_presheaf) x)) :=\nstalk_of_rings_is_comm_ring F x\n\ninstance f_flat_is_ring_hom (x : X) (V : opens Y) (hfx : f.f x ∈ V) :\n is_ring_hom (λ (s : G.F V), (⟦⟨f.hf.comap V, hfx, f.f_flat V s⟩⟧ : stalk_of_rings F x)) :=\nbegin\n show is_ring_hom ((to_stalk F x (f.hf.comap V) hfx) ∘ (f.f_flat V)),\n refine is_ring_hom.comp _ _,\nend\n\ninstance (x : X) : is_ring_hom (stalk_map f x) := to_stalk.rec_is_ring_hom _ _ _ _ _\n\n@[simp] lemma stalk_map_id (F : presheaf_of_rings X) (x : X) (s : stalk_of_rings F x) :\n stalk_map (presheaf_of_rings.f_map_id F) x s = s :=\nbegin\n induction s,\n apply quotient.sound,\n use s.U,\n use s.HxU,\n use (le_refl s.U),\n use (le_refl s.U),\n symmetry,\n convert (F.to_presheaf.Hcomp' _ _ _ _ _ s.s),\n refl,\nend\n\n@[simp] lemma stalk_map_id' (F : presheaf_of_rings X) (x : X) :\n stalk_map (presheaf_of_rings.f_map_id F) x = id := by ext; apply stalk_map_id\n\nlemma stalk_map_comp (x : X) (s : stalk_of_rings H (g.f (f.f x))) :\n stalk_map (f.comp g) x s = stalk_map f x (stalk_map g (f.f x) s) :=\nbegin\n induction s,\n apply quotient.sound,\n use f.hf.comap (g.hf.comap s.U),\n use s.HxU,\n existsi _, swap, intros t ht, exact ht,\n existsi _, swap, intros t ht, exact ht,\n refl,\n refl,\nend\n\n@[simp] lemma stalk_map_comp' (x : X) :\n stalk_map (f.comp g) x = (stalk_map f x) ∘ (stalk_map g (f.f x)) :=\nby ext; apply stalk_map_comp\n\nend stalk_map\n\nnamespace presheaf_of_rings\n\ndef restrict (U : opens X) (G : presheaf_of_rings X) :\n presheaf_of_rings U :=\n{ F := λ V, G.F (topological_space.opens.map U V),\n res := λ V W HWV, G.res _ _ (topological_space.opens.map_mono HWV),\n Hid := λ V, G.Hid (topological_space.opens.map U V),\n Hcomp := λ V₁ V₂ V₃ H12 H23, G.Hcomp (topological_space.opens.map U V₁)\n (topological_space.opens.map U V₂) (topological_space.opens.map U V₃)\n (topological_space.opens.map_mono H12) (topological_space.opens.map_mono H23),\n Fring := λ V, G.Fring (topological_space.opens.map U V),\n res_is_ring_hom := λ V W HWV, G.res_is_ring_hom (topological_space.opens.map U V)\n (topological_space.opens.map U W) (topological_space.opens.map_mono HWV) }\n\nvariables {U : opens X} (G : presheaf_of_rings X) (u : U)\n\nnoncomputable def restrict_stalk_map :\n stalk_of_rings (G.restrict U) u → stalk_of_rings G u :=\nto_stalk.rec (G.restrict U) u (stalk_of_rings G u)\n (λ V hu, to_stalk G u (topological_space.opens.map U V) ( opens.map_mem_of_mem hu))\n (λ W V HWV s huW, quotient.sound (begin\n use [(topological_space.opens.map U W), opens.map_mem_of_mem huW],\n use [(set.subset.refl (topological_space.opens.map U W)), topological_space.opens.map_mono HWV],\n rw G.Hid (topological_space.opens.map U W),\n refl,\n end))\n\ninstance : is_ring_hom (G.restrict_stalk_map u) :=\nby delta restrict_stalk_map; apply_instance\n\nend presheaf_of_rings\n\ndef presheaf_of_topological_rings.restrict (U : opens X) (G : presheaf_of_topological_rings X) :\n presheaf_of_topological_rings U :=\n{ Ftop := λ V, G.Ftop (topological_space.opens.map U V),\n Ftop_ring := λ V, G.Ftop_ring (topological_space.opens.map U V),\n res_continuous := λ V W HWV, G.res_continuous (topological_space.opens.map U V)\n (topological_space.opens.map U W) (topological_space.opens.map_mono HWV),\n..presheaf_of_rings.restrict U G.to_presheaf_of_rings }\n", "meta": {"author": "leanprover-community", "repo": "lean-perfectoid-spaces", "sha": "95a6520ce578b30a80b4c36e36ab2d559a842690", "save_path": "github-repos/lean/leanprover-community-lean-perfectoid-spaces", "path": "github-repos/lean/leanprover-community-lean-perfectoid-spaces/lean-perfectoid-spaces-95a6520ce578b30a80b4c36e36ab2d559a842690/src/sheaves/f_map.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49609382947091946, "lm_q2_score": 0.037326890690706035, "lm_q1q2_score": 0.01851764014499477}} {"text": "/-\nCopyright (c) 2020 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Leonardo de Moura\n-/\nimport Lean.ScopedEnvExtension\nimport Lean.Util.Recognizers\nimport Lean.Meta.LevelDefEq\nimport Lean.Meta.DiscrTree\nimport Lean.Meta.AppBuilder\nimport Lean.Meta.Tactic.AuxLemma\nnamespace Lean.Meta\n\n/--\n The fields `levelParams` and `proof` are used to encode the proof of the simp lemma.\n If the `proof` is a global declaration `c`, we store `Expr.const c []` at `proof` without the universe levels, and `levelParams` is set to `#[]`\n When using the lemma, we create fresh universe metavariables.\n Motivation: most simp lemmas are global declarations, and this approach is faster and saves memory.\n\n The field `levelParams` is not empty only when we elaborate an expression provided by the user, and it contains universe metavariables.\n Then, we use `abstractMVars` to abstract the universe metavariables and create new fresh universe parameters that are stored at the field `levelParams`.\n-/\nstructure SimpLemma where\n keys : Array DiscrTree.Key := #[]\n levelParams : Array Name := #[] -- non empty for local universe polymorhic proofs.\n proof : Expr\n priority : Nat := eval_prio default\n post : Bool := true\n perm : Bool := false -- true is lhs and rhs are identical modulo permutation of variables\n name? : Option Name := none -- for debugging and tracing purposes\n deriving Inhabited\n\ndef SimpLemma.getName (s : SimpLemma) : Name :=\n match s.name? with\n | some n => n\n | none => \"\"\n\ninstance : ToFormat SimpLemma where\n format s :=\n let perm := if s.perm then \":perm\" else \"\"\n let name := format s.getName\n let prio := f!\":{s.priority}\"\n name ++ prio ++ perm\n\ninstance : ToMessageData SimpLemma where\n toMessageData s := format s\n\ninstance : BEq SimpLemma where\n beq e₁ e₂ := e₁.proof == e₂.proof\n\nstructure SimpLemmas where\n pre : DiscrTree SimpLemma := DiscrTree.empty\n post : DiscrTree SimpLemma := DiscrTree.empty\n lemmaNames : Std.PHashSet Name := {}\n toUnfold : Std.PHashSet Name := {}\n erased : Std.PHashSet Name := {}\n deriving Inhabited\n\ndef addSimpLemmaEntry (d : SimpLemmas) (e : SimpLemma) : SimpLemmas :=\n if e.post then\n { d with post := d.post.insertCore e.keys e, lemmaNames := updateLemmaNames d.lemmaNames }\n else\n { d with pre := d.pre.insertCore e.keys e, lemmaNames := updateLemmaNames d.lemmaNames }\nwhere\n updateLemmaNames (s : Std.PHashSet Name) : Std.PHashSet Name :=\n match e.name? with\n | none => s\n | some name => s.insert name\n\ndef SimpLemmas.addDeclToUnfold (d : SimpLemmas) (declName : Name) : SimpLemmas :=\n { d with toUnfold := d.toUnfold.insert declName }\n\ndef SimpLemmas.isDeclToUnfold (d : SimpLemmas) (declName : Name) : Bool :=\n d.toUnfold.contains declName\n\ndef SimpLemmas.isLemma (d : SimpLemmas) (declName : Name) : Bool :=\n d.lemmaNames.contains declName\n\ndef SimpLemmas.eraseCore [Monad m] [MonadError m] (d : SimpLemmas) (declName : Name) : m SimpLemmas := do\n return { d with erased := d.erased.insert declName, lemmaNames := d.lemmaNames.erase declName, toUnfold := d.toUnfold.erase declName }\n\ndef SimpLemmas.erase [Monad m] [MonadError m] (d : SimpLemmas) (declName : Name) : m SimpLemmas := do\n unless d.isLemma declName || d.isDeclToUnfold declName do\n throwError \"'{declName}' does not have [simp] attribute\"\n d.eraseCore declName\n\nprivate partial def isPerm : Expr → Expr → MetaM Bool\n | Expr.app f₁ a₁ _, Expr.app f₂ a₂ _ => isPerm f₁ f₂ <&&> isPerm a₁ a₂\n | Expr.mdata _ s _, t => isPerm s t\n | s, Expr.mdata _ t _ => isPerm s t\n | s@(Expr.mvar ..), t@(Expr.mvar ..) => isDefEq s t\n | Expr.forallE n₁ d₁ b₁ _, Expr.forallE n₂ d₂ b₂ _ => isPerm d₁ d₂ <&&> withLocalDeclD n₁ d₁ fun x => isPerm (b₁.instantiate1 x) (b₂.instantiate1 x)\n | Expr.lam n₁ d₁ b₁ _, Expr.lam n₂ d₂ b₂ _ => isPerm d₁ d₂ <&&> withLocalDeclD n₁ d₁ fun x => isPerm (b₁.instantiate1 x) (b₂.instantiate1 x)\n | Expr.letE n₁ t₁ v₁ b₁ _, Expr.letE n₂ t₂ v₂ b₂ _ =>\n isPerm t₁ t₂ <&&> isPerm v₁ v₂ <&&> withLetDecl n₁ t₁ v₁ fun x => isPerm (b₁.instantiate1 x) (b₂.instantiate1 x)\n | Expr.proj _ i₁ b₁ _, Expr.proj _ i₂ b₂ _ => i₁ == i₂ <&&> isPerm b₁ b₂\n | s, t => s == t\n\nprivate partial def shouldPreprocess (type : Expr) : MetaM Bool :=\n forallTelescopeReducing type fun xs result => return !result.isEq\n\nprivate partial def preprocess (e type : Expr) (inv : Bool) : MetaM (List (Expr × Expr)) := do\n let type ← whnf type\n if type.isForall then\n forallTelescopeReducing type fun xs type => do\n let e := mkAppN e xs\n let ps ← preprocess e type inv\n ps.mapM fun (e, type) =>\n return (← mkLambdaFVars xs e, ← mkForallFVars xs type)\n else if let some (_, lhs, rhs) := type.eq? then\n if inv then\n let type ← mkEq rhs lhs\n let e ← mkEqSymm e\n return [(e, type)]\n else\n return [(e, type)]\n else if let some (lhs, rhs) := type.iff? then\n if inv then\n let type ← mkEq rhs lhs\n let e ← mkEqSymm (← mkPropExt e)\n return [(e, type)]\n else\n let type ← mkEq lhs rhs\n let e ← mkPropExt e\n return [(e, type)]\n else if let some (_, lhs, rhs) := type.ne? then\n if inv then\n throwError \"invalid '←' modifier in rewrite rule to 'False'\"\n let type ← mkEq (← mkEq lhs rhs) (mkConst ``False)\n let e ← mkEqFalse e\n return [(e, type)]\n else if let some p := type.not? then\n if inv then\n throwError \"invalid '←' modifier in rewrite rule to 'False'\"\n let type ← mkEq p (mkConst ``False)\n let e ← mkEqFalse e\n return [(e, type)]\n else if let some (type₁, type₂) := type.and? then\n let e₁ := mkProj ``And 0 e\n let e₂ := mkProj ``And 1 e\n return (← preprocess e₁ type₁ inv) ++ (← preprocess e₂ type₂ inv)\n else\n if inv then\n throwError \"invalid '←' modifier in rewrite rule to 'True'\"\n let type ← mkEq type (mkConst ``True)\n let e ← mkEqTrue e\n return [(e, type)]\n\nprivate def checkTypeIsProp (type : Expr) : MetaM Unit :=\n unless (← isProp type) do\n throwError \"invalid 'simp', proposition expected{indentExpr type}\"\n\nprivate def mkSimpLemmaCore (e : Expr) (levelParams : Array Name) (proof : Expr) (post : Bool) (prio : Nat) (name? : Option Name) : MetaM SimpLemma := do\n let type ← instantiateMVars (← inferType e)\n withNewMCtxDepth do\n let (xs, _, type) ← withReducible <| forallMetaTelescopeReducing type\n let type ← whnfR type\n let (keys, perm) ←\n match type.eq? with\n | some (_, lhs, rhs) => pure (← DiscrTree.mkPath lhs, ← isPerm lhs rhs)\n | none => throwError \"unexpected kind of 'simp' theorem{indentExpr type}\"\n return { keys := keys, perm := perm, post := post, levelParams := levelParams, proof := proof, name? := name?, priority := prio }\n\nprivate def mkSimpLemmasFromConst (declName : Name) (post : Bool) (inv : Bool) (prio : Nat) : MetaM (Array SimpLemma) := do\n let cinfo ← getConstInfo declName\n let val := mkConst declName (cinfo.levelParams.map mkLevelParam)\n withReducible do\n let type ← inferType val\n checkTypeIsProp type\n if inv || (← shouldPreprocess type) then\n let mut r := #[]\n for (val, type) in (← preprocess val type inv) do\n let auxName ← mkAuxLemma cinfo.levelParams type val\n r := r.push <| (← mkSimpLemmaCore (mkConst auxName (cinfo.levelParams.map mkLevelParam)) #[] (mkConst auxName) post prio declName)\n return r\n else\n #[← mkSimpLemmaCore (mkConst declName (cinfo.levelParams.map mkLevelParam)) #[] (mkConst declName) post prio declName]\n\ninductive SimpEntry where\n | lemma : SimpLemma → SimpEntry\n | toUnfold : Name → SimpEntry\n deriving Inhabited\n\nabbrev SimpExtension := SimpleScopedEnvExtension SimpEntry SimpLemmas\n\ndef SimpExtension.getLemmas (ext : SimpExtension) : CoreM SimpLemmas :=\n return ext.getState (← getEnv)\n\ndef addSimpLemma (ext : SimpExtension) (declName : Name) (post : Bool) (inv : Bool) (attrKind : AttributeKind) (prio : Nat) : MetaM Unit := do\n let simpLemmas ← mkSimpLemmasFromConst declName post inv prio\n for simpLemma in simpLemmas do\n ext.add (SimpEntry.lemma simpLemma) attrKind\n\ndef mkSimpAttr (attrName : Name) (attrDescr : String) (ext : SimpExtension) : IO Unit :=\n registerBuiltinAttribute {\n name := attrName\n descr := attrDescr\n add := fun declName stx attrKind =>\n let go : MetaM Unit := do\n let info ← getConstInfo declName\n if (← isProp info.type) then\n let post :=\n if stx[1].isNone then true else stx[1][0].getKind == ``Lean.Parser.Tactic.simpPost\n let prio ← getAttrParamOptPrio stx[2]\n addSimpLemma ext declName post (inv := false) attrKind prio\n else if info.hasValue then\n ext.add (SimpEntry.toUnfold declName) attrKind\n else\n throwError \"invalid 'simp', it is not a proposition nor a definition (to unfold)\"\n discard <| go.run {} {}\n erase := fun declName => do\n let s ← ext.getState (← getEnv)\n let s ← s.erase declName\n modifyEnv fun env => ext.modifyState env fun _ => s\n }\n\ndef mkSimpExt (extName : Name) : IO SimpExtension :=\n registerSimpleScopedEnvExtension {\n name := extName\n initial := {}\n addEntry := fun d e =>\n match e with\n | SimpEntry.lemma e => addSimpLemmaEntry d e\n | SimpEntry.toUnfold n => d.addDeclToUnfold n\n }\n\ndef registerSimpAttr (attrName : Name) (attrDescr : String) (extName : Name := attrName.appendAfter \"Ext\") : IO SimpExtension := do\n let ext ← mkSimpExt extName\n mkSimpAttr attrName attrDescr ext\n return ext\n\nbuiltin_initialize simpExtension : SimpExtension ← registerSimpAttr `simp \"simplification theorem\"\n\ndef getSimpLemmas : CoreM SimpLemmas :=\n simpExtension.getLemmas\n\n/- Auxiliary method for adding a global declaration to a `SimpLemmas` datastructure. -/\ndef SimpLemmas.addConst (s : SimpLemmas) (declName : Name) (post : Bool := true) (inv : Bool := false) (prio : Nat := eval_prio default) : MetaM SimpLemmas := do\n let simpLemmas ← mkSimpLemmasFromConst declName post inv prio\n return simpLemmas.foldl addSimpLemmaEntry s\n\ndef SimpLemma.getValue (simpLemma : SimpLemma) : MetaM Expr := do\n if simpLemma.proof.isConst && simpLemma.levelParams.isEmpty then\n let info ← getConstInfo simpLemma.proof.constName!\n if info.levelParams.isEmpty then\n return simpLemma.proof\n else\n return simpLemma.proof.updateConst! (← info.levelParams.mapM (fun _ => mkFreshLevelMVar))\n else\n let us ← simpLemma.levelParams.mapM fun _ => mkFreshLevelMVar\n simpLemma.proof.instantiateLevelParamsArray simpLemma.levelParams us\n\nprivate def preprocessProof (val : Expr) (inv : Bool) : MetaM (Array Expr) := do\n let type ← inferType val\n checkTypeIsProp type\n let ps ← preprocess val type inv\n return ps.toArray.map fun (val, _) => val\n\n/- Auxiliary method for creating simp lemmas from a proof term `val`. -/\ndef mkSimpLemmas (levelParams : Array Name) (proof : Expr) (post : Bool := true) (inv : Bool := false) (prio : Nat := eval_prio default) (name? : Option Name := none): MetaM (Array SimpLemma) :=\n withReducible do\n (← preprocessProof proof inv).mapM fun val => mkSimpLemmaCore val levelParams val post prio name?\n\n/- Auxiliary method for adding a local simp lemma to a `SimpLemmas` datastructure. -/\ndef SimpLemmas.add (s : SimpLemmas) (levelParams : Array Name) (proof : Expr) (inv : Bool := false) (post : Bool := true) (prio : Nat := eval_prio default) (name? : Option Name := none): MetaM SimpLemmas := do\n if proof.isConst then\n s.addConst proof.constName! post inv prio\n else\n let simpLemmas ← mkSimpLemmas levelParams proof post inv prio (← getName? proof)\n return simpLemmas.foldl addSimpLemmaEntry s\nwhere\n getName? (e : Expr) : MetaM (Option Name) := do\n match name? with\n | some _ => return name?\n | none =>\n let f := e.getAppFn\n if f.isConst then\n return f.constName!\n else if f.isFVar then\n let localDecl ← getFVarLocalDecl f\n return localDecl.userName\n else\n return none\n\nend Lean.Meta\n", "meta": {"author": "subfish-zhou", "repo": "leanprover-zh_CN.github.io", "sha": "8b2985d4a3d458ceda9361ac454c28168d920d3f", "save_path": "github-repos/lean/subfish-zhou-leanprover-zh_CN.github.io", "path": "github-repos/lean/subfish-zhou-leanprover-zh_CN.github.io/leanprover-zh_CN.github.io-8b2985d4a3d458ceda9361ac454c28168d920d3f/stage0/src/Lean/Meta/Tactic/Simp/SimpLemmas.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34158251284363395, "lm_q2_score": 0.054198726767778406, "lm_q1q2_score": 0.018513337282263273}} {"text": "import .expr_zipper\nopen tactic\nuniverse u\n/-- ltb is the same as lt but it goes to a bool rather than a prop to make deriving decidability easier. -/\nclass has_ltb (α : Type u) := (ltb : α → α → bool)\ninstance lt_of_ltb (α : Type u) [has_ltb α] : has_lt α := ⟨λ x y, has_ltb.ltb x y⟩\ninstance dec_lt_of_ltb (α : Type u) [has_ltb α] : decidable_rel ((<) : α → α → Prop) := by apply_instance\ninstance le_of_ltb (α : Type u) [has_ltb α] : has_le α := ⟨λ x y, x < y ∨ x = y⟩\ninstance dec_le_of_ltb (α : Type u) [has_ltb α] [decidable_eq α] : decidable_rel ((≤) : α → α → Prop) := by apply_instance\n\nnamespace derivations\n/-- An 'inductive argument' is either just a normal argument or a recursive argument.\nSo for example `@list.cons {α}` is a constructor with two arguments,\none being a normal with type α and the second being recursive.\n-/\nmeta inductive ind_arg\n| normal : expr → ind_arg\n| recursive (arg : expr) (rr : expr) : ind_arg\n\nmeta def map_ind_arg (f : pexpr → pexpr): ind_arg → pexpr\n| (ind_arg.normal e) := f $ to_pexpr e\n| (ind_arg.recursive _ rr) := to_pexpr rr\n\nmeta def ind_arg.pp : ind_arg → tactic format\n| (ind_arg.normal a) := pp a >>= pure ∘ (++ \"normal \")\n| (ind_arg.recursive a b) := pure (λ a b, \"rec \" ++ a ++ \" \" ++ b) <*> pp a <*> pp b\n\nmeta instance : has_to_tactic_format ind_arg := ⟨ind_arg.pp⟩\n\n/-- Induction but the induction hypotheses are bundled with their respective arguments.\nContrast this with the result of `induction` where all of the arguments are given, followed by the induction hyps\nand you don't know immediately whether you are looking at an ind hyp, a normal arg or a recursive arg.\n -/\nmeta def induction_but_the_recursors_are_kept_with_the_arguments (x : expr)\n : tactic $ list (name × list ind_arg × list (name × expr) ) := do\n xT ← infer_type x,\n cs ← induction x,\n gs ← get_goals,\n es ← (list.zip cs gs).mmap (λ c, do\n ⟨⟨n,ls, ss⟩, g⟩ ← pure c,\n set_goals [g],\n e ← resolve_name n >>= pure ∘ pexpr.mk_explicit >>= to_expr,\n T ← infer_type e,\n (ctx,b) ← pure $ telescope.of_pis T,\n args ← pure $ ls.take $ ctx.length,\n indos ← pure $ ls.drop $ ctx.length,\n ⟨[], acc⟩ ← args.mfoldl (λ p a, do\n ⟨indos, acc⟩ ← pure (p : (list expr) × (list ind_arg)),\n T ← infer_type a,\n if expr.get_app_fn xT = expr.get_app_fn T then do\n h::indos ← pure indos,\n pure (indos, ind_arg.recursive a h :: acc) else\n pure (indos, ind_arg.normal a :: acc)\n ) (indos, []),\n acc ← pure $ acc.reverse,\n pure (n, acc, ss)\n ),\n set_goals gs,\n pure es\n\n/-- Automatically derive `has_to_string` for an inductive datatype. -/\n@[derive_handler] meta def to_string_handler :=\ninstance_derive_handler ``has_to_string $\n do\n e ← get_env,\n split,\n x ← intro `x,\n cs ← induction_but_the_recursors_are_kept_with_the_arguments x,\n cs.mmap (λ c, do\n ⟨n,ls,ss⟩ ← pure c,\n constructor_name ← pure $ reflect $ n.components.ilast,\n if ls.empty then refine $ ```(to_string %%constructor_name) else do\n str ← pure $ list.foldl (λ x y, ```(%%x ++ %%y)) ```(\"\") $ list.intersperse ```( \" \" ) $ list.map (λ x, ```( \"(\" ++ %%x ++ \")\" )) $ ls.map (map_ind_arg (λ x, ```( to_string %%x))),\n refine $ ```(to_string %%constructor_name ++ \" \" ++ %%str)\n ),\n pure ()\n\n/-- Helper method for has_to_tactic_format_handler -/\nprivate meta def pp_cases : ind_arg → tactic unit\n|(ind_arg.normal x) :=\n refine ```(tactic.pp %%x)\n <|> refine ```(pure $ to_fmt %%x)\n <|> refine ```(pure $ format.of_string $ to_string %%x)\n <|> (do\n ppx ← tactic.pp x,\n T ← tactic.infer_type x,\n ppT ← tactic.pp T,\n msg : format ← pure $ to_fmt \"Couldn't find a way of showing \" ++ ppx ++ \" : \" ++ ppT,\n tactic.fail $ msg)\n|(ind_arg.recursive x r) := refine ```(%%r)\n\n@[derive_handler] meta def has_to_tactic_format_handler :=\ninstance_derive_handler ``has_to_tactic_format $ do\n split,\n x ← intro `x,\n cs ← induction_but_the_recursors_are_kept_with_the_arguments x,\n cs.mmap (λ x, do\n ⟨n,ls,ss⟩ ← pure x,\n constructor_name ← pure $ reflect $ n.components.ilast,\n cnp ← pure $ ```(tactic.pp %%constructor_name), -- : tactic format\n if ls.empty then refine cnp else do\n pps ← ls.mmap (λ x, do\n g ← mk_meta_var `(tactic format),\n gs ← get_goals,\n set_goals [g],\n pp_cases x,\n set_goals gs,\n instantiate_mvars g),\n ppl ← pure $ pps.foldr (λ x acc, ```(%%x :: %%acc)) ```([]),\n ppl ← pure $ ```(list.mmap id %%ppl), -- : tactic (list format)\n refine ```(pure (λ cnp ppl, cnp ++ (to_fmt \"{\")++ (format.group $ format.nest 1 $ format.join $ list.intersperse (\",\" ++ format.line) ppl) ++ \"}\") <*> %%cnp <*> %%ppl)\n ),\n pure ()\n\nprivate meta def lt_cases : (ind_arg × ind_arg) → pexpr → pexpr\n| (ind_arg.normal a_h, ind_arg.normal b_h) acc :=\n ```((%%a_h < %%b_h) ∨ ((%%a_h = %%b_h) ∧ %%acc))\n| (ind_arg.recursive a_h ai, ind_arg.recursive b_h bi) acc :=\n ```((%%ai %%b_h) ∨ ((%%a_h = %%b_h) ∧ %%acc))\n| _ acc := acc\n\n/-- Derive a total ordering for a given inductive datatype. This just puts an ordering on the constructor names and then\ncompares two terms with the same ctor lexically on their arguments. Useful for enabling the datatype to be\nstored in rtrees and other structures which require some total ordering on data.\nYou should only use this if you don't care about the semantics of `<`.\n-/\n@[derive_handler] meta def lt_derive_handler :=\ninstance_derive_handler ``has_lt $ do\n split,\n a ← intro `a,\n a_cs ← induction_but_the_recursors_are_kept_with_the_arguments a,\n a_goals ← get_goals,\n (list.zip a_cs a_goals).mmap (λ c, do\n ⟨⟨a_cn,a_hs,a_subs⟩,g⟩ ← pure c,\n b ← intro `b,\n b_cs ← induction_but_the_recursors_are_kept_with_the_arguments b,\n b_goals ← get_goals,\n bz ← pure $ list.zip b_cs b_goals,\n bz.mmap(λ c, do\n ⟨⟨b_cn,b_hs,b_subs⟩,g⟩ ← pure c,\n if a_cn < b_cn then exact `(true) else\n if a_cn > b_cn then exact `(false) else do\n r ← pure $ list.foldr lt_cases ```(false) $ list.zip a_hs b_hs,\n r ← to_expr r,\n exact r\n )\n ),\n set_goals a_goals,\n pure ()\n\nprivate meta def ltb_cases : (ind_arg × ind_arg) → pexpr → pexpr\n| (ind_arg.normal a_h, ind_arg.normal b_h) acc :=\n ```(bor (%%a_h < %%b_h) (band (to_bool $ %%a_h = %%b_h) %%acc))\n| (ind_arg.recursive a_h ai, ind_arg.recursive b_h bi) acc :=\n ```(bor (%%ai %%b_h) (band (to_bool $ %%a_h = %%b_h) %%acc))\n| _ acc := acc\n\n@[derive_handler] meta def mk_ltb_instance := instance_derive_handler ``has_ltb $ do\n split,\n a ← intro `a,\n (expr.const typename _) ← infer_type a >>= pure ∘ expr.get_app_fn,\n e ← get_env,\n all_cases ← pure $ environment.constructors_of e typename,\n a_cs ← induction_but_the_recursors_are_kept_with_the_arguments a,\n a_goals ← get_goals,\n (list.zip a_cs a_goals).mmap (λ c, do\n ⟨⟨a_cn,a_hs,a_subs⟩,g⟩ ← pure c,\n a_idx ← pure $ list.find_index (= a_cn) all_cases,\n b ← intro `b,\n b_cs ← induction_but_the_recursors_are_kept_with_the_arguments b,\n b_goals ← get_goals,\n bz ← pure $ list.zip b_cs b_goals,\n bz.mmap(λ c, do\n ⟨⟨b_cn,b_hs,b_subs⟩,g⟩ ← pure c,\n b_idx ← pure $ list.find_index (= b_cn) all_cases,\n if a_idx < b_idx then exact `(tt) else\n if a_idx > b_idx then exact `(ff) else do\n r ← pure $ list.foldr ltb_cases ```(ff) $ list.zip a_hs b_hs,\n r ← to_expr r,\n exact r\n )\n ),\n set_goals a_goals,\n pure ()\n\n/-!\n# An example:\n\n```\n@[derive decidable_eq, derive has_ltb, derive has_to_tactic_format]\ninductive qwerty\n| nil : qwerty\n| asdf (n : nat) : qwerty\n| br (x: qwerty) (n : nat) (y : qwerty) : qwerty\n| s : qwerty → qwerty\n\nopen qwerty\n#eval to_bool $ nil < (asdf 3)\n#eval to_bool $ s (asdf 3) < s (asdf 4)\n#eval to_bool (br (asdf 3) 2 nil < br (asdf 3) 2 nil)\n#eval to_bool $ ((asdf 3) < (asdf 4))\nrun_cmd (trace $ br (asdf 3) 2 nil)\n```\n-/\nend derivations\n", "meta": {"author": "EdAyers", "repo": "lean-humanproof-thesis", "sha": "ce8331df1883f286ab8cc7b61a328afdc006a059", "save_path": "github-repos/lean/EdAyers-lean-humanproof-thesis", "path": "github-repos/lean/EdAyers-lean-humanproof-thesis/lean-humanproof-thesis-ce8331df1883f286ab8cc7b61a328afdc006a059/src/basic/derive.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4073334000459302, "lm_q2_score": 0.04535258378008934, "lm_q1q2_score": 0.018473622152011697}} {"text": "/-\nCopyright (c) 2019 Paul-Nicolas Madelaine. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Paul-Nicolas Madelaine, Robert Y. Lewis\n\nNormalizing casts inside expressions.\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.default\nimport Mathlib.tactic.converter.interactive\nimport Mathlib.tactic.hint\nimport Mathlib.PostPort\n\nuniverses l u_1 u_2 \n\nnamespace Mathlib\n\n/-!\n# A tactic for normalizing casts inside expressions\n\nThis tactic normalizes casts inside expressions.\nIt can be thought of as a call to the simplifier with a specific set of lemmas to\nmove casts upwards in the expression.\nIt has special handling of numerals and a simple heuristic to help moving\ncasts \"past\" binary operators.\nContrary to simp, it should be safe to use as a non-terminating tactic.\n\nThe algorithm implemented here is described in the paper\n.\n\n## Important definitions\n* `tactic.interactive.norm_cast`\n* `tactic.interactive.push_cast`\n* `tactic.interactive.exact_mod_cast`\n* `tactic.interactive.apply_mod_cast`\n* `tactic.interactive.rw_mod_cast`\n* `tactic.interactive.assumption_mod_cast`\n-/\n\nnamespace tactic\n\n\n/--\nRuns `mk_instance` with a time limit.\n\nThis is a work around to the fact that in some cases\nmk_instance times out instead of failing,\nfor example: `has_lift_t ℤ ℕ`\n\n`mk_instance_fast` is used when we assume the type class search\nshould end instantly.\n-/\nend tactic\n\n\nnamespace norm_cast\n\n\n/--\nOutput a trace message if `trace.norm_cast` is enabled.\n-/\n/--\n`label` is a type used to classify `norm_cast` lemmas.\n* elim lemma: LHS has 0 head coes and ≥ 1 internal coe\n* move lemma: LHS has 1 head coe and 0 internal coes, RHS has 0 head coes and ≥ 1 internal coes\n* squash lemma: LHS has ≥ 1 head coes and 0 internal coes, RHS has fewer head coes\n-/\ninductive label \nwhere\n| elim : label\n| move : label\n| squash : label\n\nnamespace label\n\n\n/-- Convert `label` into `string`. -/\nprotected def to_string : label → string :=\n sorry\n\nprotected instance has_to_string : has_to_string label :=\n has_to_string.mk label.to_string\n\nprotected instance has_repr : has_repr label :=\n has_repr.mk label.to_string\n\n/-- Convert `string` into `label`. -/\ndef of_string : string → Option label :=\n sorry\n\nend label\n\n\n/-- Count how many coercions are at the top of the expression. -/\n/-- Count how many coercions are inside the expression, including the top ones. -/\n/-- Count how many coercions are inside the expression, excluding the top ones. -/\n/--\nClassifies a declaration of type `ty` as a `norm_cast` rule.\n-/\n/-- The cache for `norm_cast` attribute stores three `simp_lemma` objects. -/\n/-- Empty `norm_cast_cache`. -/\n/-- `add_elim cache e` adds `e` as an `elim` lemma to `cache`. -/\n/-- `add_move cache e` adds `e` as a `move` lemma to `cache`. -/\n/-- `add_squash cache e` adds `e` as an `squash` lemma to `cache`. -/\n/--\nThe type of the `norm_cast` attribute.\nThe optional label is used to overwrite the classifier.\n-/\n/--\nEfficient getter for the `@[norm_cast]` attribute parameter that does not call `eval_expr`.\n\nSee Note [user attribute parameters].\n-/\n/--\n`add_lemma cache decl` infers the proper `norm_cast` attribute for `decl` and adds it to `cache`.\n-/\n-- special lemmas to handle the ≥, > and ≠ operators\n\n/--\n`mk_cache names` creates a `norm_cast_cache`. It infers the proper `norm_cast` attributes\nfor names in `names`, and collects the lemmas attributed with specific `norm_cast` attributes.\n-/\n-- names has the declarations in reverse order\n\n--some special lemmas to handle binary relations\n\n/--\nThe `norm_cast` attribute.\n-/\n/-- Classify a declaration as a `norm_cast` rule. -/\n/--\nGets the `norm_cast` classification label for a declaration. Applies the\noverride specified on the attribute, if necessary.\n-/\nend norm_cast\n\n\nnamespace tactic.interactive\n\n\n/--\n`push_cast` rewrites the expression to move casts toward the leaf nodes.\nFor example, `↑(a + b)` will be written to `↑a + ↑b`.\nEquivalent to `simp only with push_cast`.\nCan also be used at hypotheses.\n\n`push_cast` can also be used at hypotheses and with extra simp rules.\n\n```lean\nexample (a b : ℕ) (h1 : ((a + b : ℕ) : ℤ) = 10) (h2 : ((a + b + 0 : ℕ) : ℤ) = 10) :\n ((a + b : ℕ) : ℤ) = 10 :=\nbegin\n push_cast,\n push_cast at h1,\n push_cast [int.add_zero] at h2,\nend\n```\n-/\nend tactic.interactive\n\n\nnamespace norm_cast\n\n\n/-- Prove `a = b` using the given simp set. -/\n/-- Prove `a = b` by simplifying using move and squash lemmas. -/\n/--\nThis is the main heuristic used alongside the elim and move lemmas.\nThe goal is to help casts move past operators by adding intermediate casts.\nAn expression of the shape: op (↑(x : α) : γ) (↑(y : β) : γ)\nis rewritten to: op (↑(↑(x : α) : β) : γ) (↑(y : β) : γ)\nwhen (↑(↑(x : α) : β) : γ) = (↑(x : α) : γ) can be proven with a squash lemma\n-/\n/--\nDischarging function used during simplification in the \"squash\" step.\n\nTODO: norm_cast takes a list of expressions to use as lemmas for the discharger\nTODO: a tactic to print the results the discharger fails to proove\n-/\n/--\nCore rewriting function used in the \"squash\" step, which moves casts upwards\nand eliminates them.\n\nIt tries to rewrite an expression using the elim and move lemmas.\nOn failure, it calls the splitting procedure heuristic.\n-/\n/-!\nThe following auxiliary functions are used to handle numerals.\n-/\n\n/--\nIf possible, rewrite `(n : α)` to `((n : ℕ) : α)` where `n` is a numeral and `α ≠ ℕ`.\nReturns a pair of the new expression and proof that they are equal.\n-/\n/--\nIf possible, rewrite `((n : ℕ) : α)` to `(n : α)` where `n` is a numeral.\nReturns a pair of the new expression and proof that they are equal.\n-/\n/-- A local variant on `simplify_top_down`. -/\n/--\nThe core simplification routine of `norm_cast`.\n-/\n/--\nA small variant of `push_cast` suited for non-interactive use.\n\n`derive_push_cast extra_lems e` returns an expression `e'` and a proof that `e = e'`.\n-/\nend norm_cast\n\n\nnamespace tactic\n\n\n/-- `aux_mod_cast e` runs `norm_cast` on `e` and returns the result. If `include_goal` is true, it\nalso normalizes the goal. -/\n/-- `exact_mod_cast e` runs `norm_cast` on the goal and `e`, and tries to use `e` to close the goal. -/\n/-- `apply_mod_cast e` runs `norm_cast` on the goal and `e`, and tries to apply `e`. -/\n/-- `assumption_mod_cast` runs `norm_cast` on the goal. For each local hypothesis `h`, it also\nnormalizes `h` and tries to use that to close the goal. -/\nend tactic\n\n\nnamespace tactic.interactive\n\n\n/--\nNormalize casts at the given locations by moving them \"upwards\".\nAs opposed to simp, norm_cast can be used without necessarily closing the goal.\n-/\n/--\nRewrite with the given rules and normalize casts between steps.\n-/\n/--\nNormalize the goal and the given expression, then close the goal with exact.\n-/\n/--\nNormalize the goal and the given expression, then apply the expression to the goal.\n-/\n/--\nNormalize the goal and every expression in the local context, then close the goal with assumption.\n-/\nend tactic.interactive\n\n\nnamespace conv.interactive\n\n\n/-- the converter version of `norm_cast' -/\nend conv.interactive\n\n\n-- TODO: move this elsewhere?\n\ntheorem ite_cast {α : Sort u_1} {β : Sort u_2} [has_lift_t α β] {c : Prop} [Decidable c] {a : α} {b : α} : ↑(ite c a b) = ite c ↑a ↑b := sorry\n\n/--\nThe `norm_cast` family of tactics is used to normalize casts inside expressions.\nIt is basically a simp tactic with a specific set of lemmas to move casts\nupwards in the expression.\nTherefore it can be used more safely as a non-terminating tactic.\nIt also has special handling of numerals.\n\nFor instance, given an assumption\n```lean\na b : ℤ\nh : ↑a + ↑b < (10 : ℚ)\n```\n\nwriting `norm_cast at h` will turn `h` into\n```lean\nh : a + b < 10\n```\n\nYou can also use `exact_mod_cast`, `apply_mod_cast`, `rw_mod_cast`\nor `assumption_mod_cast`.\nWriting `exact_mod_cast h` and `apply_mod_cast h` will normalize the goal and\n`h` before using `exact h` or `apply h`.\nWriting `assumption_mod_cast` will normalize the goal and for every\nexpression `h` in the context it will try to normalize `h` and use\n`exact h`.\n`rw_mod_cast` acts like the `rw` tactic but it applies `norm_cast` between steps.\n\n`push_cast` rewrites the expression to move casts toward the leaf nodes.\nThis uses `norm_cast` lemmas in the forward direction.\nFor example, `↑(a + b)` will be written to `↑a + ↑b`.\nIt is equivalent to `simp only with push_cast`.\nIt can also be used at hypotheses with `push_cast at h`\nand with extra simp lemmas with `push_cast [int.add_zero]`.\n\n```lean\nexample (a b : ℕ) (h1 : ((a + b : ℕ) : ℤ) = 10) (h2 : ((a + b + 0 : ℕ) : ℤ) = 10) :\n ((a + b : ℕ) : ℤ) = 10 :=\nbegin\n push_cast,\n push_cast at h1,\n push_cast [int.add_zero] at h2,\nend\n```\n\nThe implementation and behavior of the `norm_cast` family is described in detail at\n.\n-/\n/--\nThe `norm_cast` attribute should be given to lemmas that describe the\n", "meta": {"author": "AurelienSaue", "repo": "Mathlib4_auto", "sha": "590df64109b08190abe22358fabc3eae000943f2", "save_path": "github-repos/lean/AurelienSaue-Mathlib4_auto", "path": "github-repos/lean/AurelienSaue-Mathlib4_auto/Mathlib4_auto-590df64109b08190abe22358fabc3eae000943f2/Mathlib/tactic/norm_cast.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.30735801686526387, "lm_q2_score": 0.06008664554541885, "lm_q1q2_score": 0.018468112214925978}} {"text": "import Structure.Generic.Axioms.Universes\n\nimport mathlib4_experiments.Data.Equiv.Basic\n\n\n\nset_option autoBoundImplicitLocal false\n--set_option pp.universes true\n\nuniverses u v w\n\n\n\n-- We additionally want \"sort-like\" types to have some concept of \"functors\" that map instances. Here, we\n-- need to reconcile two conflicting requirements:\n--\n-- * We want a functor `F : α ⟶ β` with `α β : V` to be an instance of `V`, so that we can chain functors\n-- as in `α ⟶ β ⟶ γ`.\n--\n-- * We axiomatically assert the existence of certain functors such as identity and composition, which we\n-- assume to map instances in a specific way. We want this mapping to be a definitional equality so that\n-- e.g. applying the identity functor is a trivial operation.\n-- This implies that \"functoriality\" should be extra structure on functions, so that we can say that a\n-- given function \"is functorial\".\n--\n-- In order to meet both requirements, we define both kinds of functors, and write `α ⟶ β` for the first\n-- kind and `α ⟶' β` for a bundled version of the second kind, i.e. a function that is functorial. We\n-- assert the equivalence of these two kinds of functors as an axiom.\n--\n-- In the case of `Bundled C`, we can make sure that `α ⟶' β` is actually an instance of the type class\n-- `C`, so we can define `α ⟶ β` to be the same as `α ⟶' β`. However, in the case of `Sort u`, `α ⟶' β`\n-- is not an instance of `Sort u` if `u = 0` (i.e. `Sort u` is actually `Prop`).\n--\n-- Moreover, `α ⟶' β` is defined so that `α` and `β` can live in different universes.\n\nclass HasExternalFunctors (U : Universe.{u}) (V : Universe.{v}) : Type (max u v) where\n(IsFun {α : U} {β : V} : (α → β) → Sort (max u v))\n\nstructure BundledFunctor {U : Universe.{u}} {V : Universe.{v}} [h : HasExternalFunctors U V]\n (α : U) (β : V) : Sort (max 1 u v) where\n(f : α → β)\n(isFun : h.IsFun f)\n\nnamespace BundledFunctor\n\n infixr:20 \" ⟶' \" => BundledFunctor\n\n variable {U V : Universe} [h : HasExternalFunctors U V]\n\n instance coeFun (α : U) (β : V) : CoeFun (α ⟶' β) (λ _ => α → β) := ⟨BundledFunctor.f⟩\n\n def mkFun {α : U} {β : V} {f : α → β} (hf : h.IsFun f) : α ⟶' β := ⟨f, hf⟩\n\nend BundledFunctor\n\nclass HasInternalFunctors (U : Universe.{u}) extends HasExternalFunctors U U : Type u where\n(Fun : U → U → U)\n(funEquiv (α β : U) : ⌈Fun α β⌉ ≃ (α ⟶' β))\n\nnamespace HasInternalFunctors\n\n infixr:20 \" ⟶ \" => HasInternalFunctors.Fun\n\n variable {U : Universe} [h : HasInternalFunctors U]\n\n def toBundled {α β : U} (F : α ⟶ β) : α ⟶' β := (h.funEquiv α β).toFun F\n def fromBundled {α β : U} (F : α ⟶' β) : α ⟶ β := (h.funEquiv α β).invFun F\n\n @[simp] theorem fromToBundled {α β : U} (F : α ⟶ β) : fromBundled (toBundled F) = F := (h.funEquiv α β).leftInv F\n @[simp] theorem toFromBundled {α β : U} (F : α ⟶' β) : toBundled (fromBundled F) = F := (h.funEquiv α β).rightInv F\n\n def funCoe {α β : U} (F : α ⟶ β) : α → β := (toBundled F).f\n instance (α β : U) : CoeFun ⌈α ⟶ β⌉ (λ _ => α → β) := ⟨funCoe⟩\n\n -- Workaround for cases where `coeFun` doesn't work.\n notation:max F:max \"⟮\" x:0 \"⟯\" => HasInternalFunctors.funCoe F x\n\n def isFun {α β : U} (F : α ⟶ β) : h.IsFun (funCoe F) := (toBundled F).isFun\n\n theorem toBundled.eff {α β : U} (F : α ⟶ β) (a : α) : (toBundled F) a = F a := rfl\n\n @[simp] theorem fromBundled.coe {α β : U} (F : α ⟶' β) : funCoe (fromBundled F) = F.f :=\n congrArg BundledFunctor.f (toFromBundled F)\n @[simp] theorem fromBundled.eff {α β : U} (F : α ⟶' β) (a : α) : (fromBundled F) a = F a :=\n congrFun (fromBundled.coe F) a\n\n def mkFun {α β : U} {f : α → β} (hf : h.IsFun f) : α ⟶ β := fromBundled (BundledFunctor.mkFun hf)\n\n @[simp] theorem mkFun.eff {α β : U} {f : α → β} (hf : h.IsFun f) (a : α) :\n (mkFun hf) a = f a :=\n fromBundled.eff (BundledFunctor.mkFun hf) a\n\nend HasInternalFunctors\n\n\n\n@[simp] theorem elimRec {α : Sort u} {a a' : α} {ha : a = a'}\n {T : α → Sort v} {x : T a}\n {β : Sort w} {f : {a : α} → T a → β} :\n @f a' (ha ▸ x) = f x :=\nby subst ha; rfl\n\n\n\n-- The following axioms are equivalent to asserting the existence of five functors with specified behavior:\n-- id : `α ⟶ α, a ↦ a`\n-- const : `β ⟶ (α ⟶ β), c ↦ (a ↦ c)`\n-- app : `α ⟶ (α ⟶ β) ⟶ β, a ↦ (F ↦ F a)`\n-- dup : `(α ⟶ α ⟶ β) ⟶ (α ⟶ β), F ↦ (a ↦ F a a)`\n-- comp : `(α ⟶ β) ⟶ (β ⟶ γ) ⟶ (α ⟶ γ), F ↦ (G ↦ (a ↦ G (F a)))`\n--\n-- In `DerivedFunctors.lean`, we construct several other functors such as\n-- swap : `(α ⟶ β ⟶ γ) ⟶ (β ⟶ α ⟶ γ), F ↦ (b ↦ (a ↦ F a b))`\n-- subst : `(α ⟶ β ⟶ γ) ⟶ (α ⟶ β) ⟶ (α ⟶ γ), F ↦ (G ↦ (a ↦ F a (G a)))`\n-- Using these, we can give a general algorithm for proving that a function is functorial.\n\nclass HasIdFun (U : Universe) [h : HasExternalFunctors U U] where\n(idIsFun (α : U) : h.IsFun (λ a : α => a))\n\nnamespace HasIdFun\n\n variable {U : Universe} [HasExternalFunctors U U] [h : HasIdFun U]\n\n def idFun' (α : U) : α ⟶' α := BundledFunctor.mkFun (h.idIsFun α)\n\nend HasIdFun\n\nclass HasConstFun (U V : Universe) [h : HasExternalFunctors U V] where\n(constIsFun (α : U) {β : V} (c : β) : h.IsFun (λ a : α => c))\n\nnamespace HasConstFun\n\n variable {U V : Universe} [HasExternalFunctors U V] [h : HasConstFun U V]\n\n def constFun' (α : U) {β : V} (c : β) : α ⟶' β := BundledFunctor.mkFun (h.constIsFun α c)\n\nend HasConstFun\n\nclass HasCompFun (U V W : Universe) [HasExternalFunctors U V] [HasExternalFunctors V W] [h : HasExternalFunctors U W] where\n(compIsFun {α : U} {β : V} {γ : W} (F : α ⟶' β) (G : β ⟶' γ) : h.IsFun (λ a : α => G (F a)))\n\nnamespace HasCompFun\n\n variable {U V W : Universe} [HasExternalFunctors U V] [HasExternalFunctors V W] [HasExternalFunctors U W] [h : HasCompFun U V W]\n\n def compFun' {α : U} {β : V} {γ : W} (F : α ⟶' β) (G : β ⟶' γ) : α ⟶' γ := BundledFunctor.mkFun (h.compIsFun F G)\n\n def revCompFun' {α : U} {β : V} {γ : W} (G : β ⟶' γ) (F : α ⟶' β) : α ⟶' γ := compFun' F G\n infixr:90 \" ⊙' \" => HasCompFun.revCompFun'\n\nend HasCompFun\n\n\n\nclass HasLinearFunOp (U : Universe) [h : HasInternalFunctors U] extends HasIdFun U, HasCompFun U U U where\n(appIsFun {α : U} (a : α) (β : U) : h.IsFun (λ F : α ⟶ β => F a))\n(appFunIsFun (α β : U) : h.IsFun (λ a : α => HasInternalFunctors.mkFun (appIsFun a β)))\n(compFunIsFun {α β : U} (F : α ⟶' β) (γ : U) : h.IsFun (λ G : β ⟶ γ => HasInternalFunctors.mkFun (compIsFun F (HasInternalFunctors.toBundled G))))\n(compFunFunIsFun (α β γ : U) : h.IsFun (λ F : α ⟶ β => HasInternalFunctors.mkFun (compFunIsFun (HasInternalFunctors.toBundled F) γ)))\n\nnamespace HasLinearFunOp\n\n variable {U : Universe} [HasInternalFunctors U] [h : HasLinearFunOp U]\n\n def idFun' (α : U) : α ⟶' α := HasIdFun.idFun' α\n def idFun (α : U) : α ⟶ α := HasInternalFunctors.fromBundled (idFun' α)\n\n @[simp] theorem idFun.eff (α : U) (a : α) : (idFun α) a = a :=\n by apply HasInternalFunctors.fromBundled.eff\n\n def appFun' {α : U} (a : α) (β : U) : (α ⟶ β) ⟶' β := BundledFunctor.mkFun (h.appIsFun a β)\n def appFun {α : U} (a : α) (β : U) : (α ⟶ β) ⟶ β := HasInternalFunctors.fromBundled (appFun' a β)\n\n @[simp] theorem appFun.eff {α : U} (a : α) (β : U) (F : α ⟶ β) : (appFun a β) F = F a :=\n by apply HasInternalFunctors.fromBundled.eff\n\n def appFunFun' (α β : U) : α ⟶' (α ⟶ β) ⟶ β := BundledFunctor.mkFun (h.appFunIsFun α β)\n def appFunFun (α β : U) : α ⟶ (α ⟶ β) ⟶ β := HasInternalFunctors.fromBundled (appFunFun' α β)\n\n @[simp] theorem appFunFun.eff (α β : U) (a : α) : (appFunFun α β) a = appFun a β :=\n by apply HasInternalFunctors.fromBundled.eff\n @[simp] theorem appFunFun.effEff (α β : U) (a : α) (F : α ⟶ β) : ((appFunFun α β) a) F = F a :=\n by simp\n\n def compFun' {α β γ : U} (F : α ⟶' β) (G : β ⟶' γ) : α ⟶' γ := HasCompFun.compFun' F G\n def compFun {α β γ : U} (F : α ⟶ β) (G : β ⟶ γ) : α ⟶ γ :=\n HasInternalFunctors.fromBundled (compFun' (HasInternalFunctors.toBundled F) (HasInternalFunctors.toBundled G))\n\n @[simp] theorem compFun.eff {α β γ : U} (F : α ⟶ β) (G : β ⟶ γ) (a : α) : (compFun F G) a = G (F a) :=\n by apply HasInternalFunctors.fromBundled.eff\n\n def compFunFun' {α β : U} (F : α ⟶' β) (γ : U) : (β ⟶ γ) ⟶' (α ⟶ γ) := BundledFunctor.mkFun (h.compFunIsFun F γ)\n def compFunFun {α β : U} (F : α ⟶ β) (γ : U) : (β ⟶ γ) ⟶ (α ⟶ γ) :=\n HasInternalFunctors.fromBundled (compFunFun' (HasInternalFunctors.toBundled F) γ)\n\n @[simp] theorem compFunFun.eff {α β : U} (F : α ⟶ β) (γ : U) (G : β ⟶ γ) : (compFunFun F γ) G = compFun F G :=\n by apply HasInternalFunctors.fromBundled.eff\n @[simp] theorem compFunFun.effEff {α β : U} (F : α ⟶ β) (γ : U) (G : β ⟶ γ) (a : α) : ((compFunFun F γ) G) a = G (F a) :=\n by simp\n\n def compFunFunFun' (α β γ : U) : (α ⟶ β) ⟶' (β ⟶ γ) ⟶ (α ⟶ γ) := BundledFunctor.mkFun (h.compFunFunIsFun α β γ)\n def compFunFunFun (α β γ : U) : (α ⟶ β) ⟶ (β ⟶ γ) ⟶ (α ⟶ γ) := HasInternalFunctors.fromBundled (compFunFunFun' α β γ)\n \n @[simp] theorem compFunFunFun.eff (α β γ : U) (F : α ⟶ β) : (compFunFunFun α β γ) F = compFunFun F γ :=\n by apply HasInternalFunctors.fromBundled.eff\n @[simp] theorem compFunFunFun.effEff (α β γ : U) (F : α ⟶ β) (G : β ⟶ γ) : ((compFunFunFun α β γ) F) G = compFun F G :=\n by simp\n @[simp] theorem compFunFunFun.effEffEff (α β γ : U) (F : α ⟶ β) (G : β ⟶ γ) (a : α) : (((compFunFunFun α β γ) F) G) a = G (F a) :=\n by simp\n\nend HasLinearFunOp\n\n\n\nclass HasSubLinearFunOp (U : Universe) [h : HasInternalFunctors U] extends HasConstFun U U where\n(constFunIsFun (α β : U) : h.IsFun (λ c : β => HasInternalFunctors.mkFun (constIsFun α c)))\n\nnamespace HasSubLinearFunOp\n\n variable {U : Universe} [HasInternalFunctors U] [h : HasSubLinearFunOp U]\n\n def constFun' (α : U) {β : U} (c : β) : α ⟶' β := HasConstFun.constFun' α c\n def constFun (α : U) {β : U} (c : β) : α ⟶ β := HasInternalFunctors.fromBundled (constFun' α c)\n\n @[simp] theorem constFun.eff (α : U) {β : U} (c : β) (a : α) : (constFun α c) a = c :=\n by apply HasInternalFunctors.fromBundled.eff\n\n def constFunFun' (α β : U) : β ⟶' (α ⟶ β) := BundledFunctor.mkFun (h.constFunIsFun α β)\n def constFunFun (α β : U) : β ⟶ (α ⟶ β) := HasInternalFunctors.fromBundled (constFunFun' α β)\n\n @[simp] theorem constFunFun.eff (α β : U) (c : β) : (constFunFun α β) c = constFun α c :=\n by apply HasInternalFunctors.fromBundled.eff\n @[simp] theorem constFunFun.effEff (α β : U) (c : β) (a : α) : ((constFunFun α β) c) a = c :=\n by simp\n\nend HasSubLinearFunOp\n\nclass HasAffineFunOp (U : Universe) [h : HasInternalFunctors U] extends HasLinearFunOp U, HasSubLinearFunOp U\n\n\n\nclass HasNonLinearFunOp (U : Universe) [h : HasInternalFunctors U] where\n(dupIsFun {α β : U} (F : α ⟶' α ⟶ β) : h.IsFun (λ a : α => F a a))\n(dupFunIsFun (α β : U) : h.IsFun (λ F : α ⟶ α ⟶ β => HasInternalFunctors.mkFun (dupIsFun (HasInternalFunctors.toBundled F))))\n\nnamespace HasNonLinearFunOp\n\n variable {U : Universe} [HasInternalFunctors U] [h : HasNonLinearFunOp U]\n\n def dupFun' {α β : U} (F : α ⟶' α ⟶ β) : α ⟶' β := BundledFunctor.mkFun (h.dupIsFun F)\n def dupFun {α β : U} (F : α ⟶ α ⟶ β) : α ⟶ β :=\n HasInternalFunctors.fromBundled (dupFun' (HasInternalFunctors.toBundled F))\n\n @[simp] theorem dupFun.eff {α β : U} (F : α ⟶ α ⟶ β) (a : α) : (dupFun F) a = F a a :=\n by apply HasInternalFunctors.fromBundled.eff\n\n def dupFunFun' (α β : U) : (α ⟶ α ⟶ β) ⟶' (α ⟶ β) := BundledFunctor.mkFun (h.dupFunIsFun α β)\n def dupFunFun (α β : U) : (α ⟶ α ⟶ β) ⟶ (α ⟶ β) := HasInternalFunctors.fromBundled (dupFunFun' α β)\n\n @[simp] theorem dupFunFun.eff (α β : U) (F : α ⟶ α ⟶ β) : (dupFunFun α β) F = dupFun F :=\n by apply HasInternalFunctors.fromBundled.eff\n @[simp] theorem dupFunFun.effEff (α β : U) (F : α ⟶ α ⟶ β) (a : α) : ((dupFunFun α β) F) a = F a a :=\n by simp\n\nend HasNonLinearFunOp\n\nclass HasFullFunOp (U : Universe) [h : HasInternalFunctors U] extends HasAffineFunOp U, HasNonLinearFunOp U\n\n\n\nclass HasFunOp (U : Universe.{u}) extends HasInternalFunctors U, HasFullFunOp U : Type u\n", "meta": {"author": "SReichelt", "repo": "lean4-experiments", "sha": "ff55357a01a34a91bf670d712637480089085ee4", "save_path": "github-repos/lean/SReichelt-lean4-experiments", "path": "github-repos/lean/SReichelt-lean4-experiments/lean4-experiments-ff55357a01a34a91bf670d712637480089085ee4/Structure/Generic/Axioms/AbstractFunctors.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4186969093556867, "lm_q2_score": 0.04401864672766704, "lm_q1q2_score": 0.018430471338894}} {"text": "/-\nCopyright (c) 2018 Johannes Hölzl. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthor: Johannes Hölzl\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.default\nimport Mathlib.data.finset.basic\nimport Mathlib.data.multiset.pi\nimport Mathlib.PostPort\n\nuniverses u_1 u_2 \n\nnamespace Mathlib\n\n/-!\n# The cartesian product of finsets\n-/\n\nnamespace finset\n\n\n/-! ### pi -/\n\n/-- The empty dependent product function, defined on the empty set. The assumption `a ∈ ∅` is never\nsatisfied. -/\ndef pi.empty {α : Type u_1} (β : α → Type u_2) (a : α) (h : a ∈ ∅) : β a := multiset.pi.empty β a h\n\n/-- Given a finset `s` of `α` and for all `a : α` a finset `t a` of `δ a`, then one can define the\nfinset `s.pi t` of all functions defined on elements of `s` taking values in `t a` for `a ∈ s`.\nNote that the elements of `s.pi t` are only partially defined, on `s`. -/\ndef pi {α : Type u_1} {δ : α → Type u_2} [DecidableEq α] (s : finset α)\n (t : (a : α) → finset (δ a)) : finset ((a : α) → a ∈ s → δ a) :=\n mk (multiset.pi (val s) fun (a : α) => val (t a)) sorry\n\n@[simp] theorem pi_val {α : Type u_1} {δ : α → Type u_2} [DecidableEq α] (s : finset α)\n (t : (a : α) → finset (δ a)) : val (pi s t) = multiset.pi (val s) fun (a : α) => val (t a) :=\n rfl\n\n@[simp] theorem mem_pi {α : Type u_1} {δ : α → Type u_2} [DecidableEq α] {s : finset α}\n {t : (a : α) → finset (δ a)} {f : (a : α) → a ∈ s → δ a} :\n f ∈ pi s t ↔ ∀ (a : α) (h : a ∈ s), f a h ∈ t a :=\n multiset.mem_pi (val s) (fun (a : α) => (fun (a : α) => val (t a)) a) f\n\n/-- Given a function `f` defined on a finset `s`, define a new function on the finset `s ∪ {a}`,\nequal to `f` on `s` and sending `a` to a given value `b`. This function is denoted\n`s.pi.cons a b f`. If `a` already belongs to `s`, the new function takes the value `b` at `a`\nanyway. -/\ndef pi.cons {α : Type u_1} {δ : α → Type u_2} [DecidableEq α] (s : finset α) (a : α) (b : δ a)\n (f : (a : α) → a ∈ s → δ a) (a' : α) (h : a' ∈ insert a s) : δ a' :=\n multiset.pi.cons (val s) a b f a' sorry\n\n@[simp] theorem pi.cons_same {α : Type u_1} {δ : α → Type u_2} [DecidableEq α] (s : finset α)\n (a : α) (b : δ a) (f : (a : α) → a ∈ s → δ a) (h : a ∈ insert a s) : pi.cons s a b f a h = b :=\n multiset.pi.cons_same (pi.cons._proof_1 s a a h)\n\ntheorem pi.cons_ne {α : Type u_1} {δ : α → Type u_2} [DecidableEq α] {s : finset α} {a : α} {a' : α}\n {b : δ a} {f : (a : α) → a ∈ s → δ a} {h : a' ∈ insert a s} (ha : a ≠ a') :\n pi.cons s a b f a' h = f a' (or.resolve_left (iff.mp mem_insert h) (ne.symm ha)) :=\n multiset.pi.cons_ne (pi.cons._proof_1 s a a' h) (ne.symm ha)\n\ntheorem pi_cons_injective {α : Type u_1} {δ : α → Type u_2} [DecidableEq α] {a : α} {b : δ a}\n {s : finset α} (hs : ¬a ∈ s) : function.injective (pi.cons s a b) :=\n sorry\n\n@[simp] theorem pi_empty {α : Type u_1} {δ : α → Type u_2} [DecidableEq α]\n {t : (a : α) → finset (δ a)} : pi ∅ t = singleton (pi.empty δ) :=\n rfl\n\n@[simp] theorem pi_insert {α : Type u_1} {δ : α → Type u_2} [DecidableEq α]\n [(a : α) → DecidableEq (δ a)] {s : finset α} {t : (a : α) → finset (δ a)} {a : α}\n (ha : ¬a ∈ s) :\n pi (insert a s) t = finset.bUnion (t a) fun (b : δ a) => image (pi.cons s a b) (pi s t) :=\n sorry\n\ntheorem pi_singletons {α : Type u_1} [DecidableEq α] {β : Type u_2} (s : finset α) (f : α → β) :\n (pi s fun (a : α) => singleton (f a)) = singleton fun (a : α) (_x : a ∈ s) => f a :=\n sorry\n\ntheorem pi_const_singleton {α : Type u_1} [DecidableEq α] {β : Type u_2} (s : finset α) (i : β) :\n (pi s fun (_x : α) => singleton i) = singleton fun (_x : α) (_x : _x ∈ s) => i :=\n pi_singletons s fun (_x : α) => i\n\ntheorem pi_subset {α : Type u_1} {δ : α → Type u_2} [DecidableEq α] {s : finset α}\n (t₁ : (a : α) → finset (δ a)) (t₂ : (a : α) → finset (δ a))\n (h : ∀ (a : α), a ∈ s → t₁ a ⊆ t₂ a) : pi s t₁ ⊆ pi s t₂ :=\n fun (g : (a : α) → a ∈ s → δ a) (hg : g ∈ pi s t₁) =>\n iff.mpr mem_pi fun (a : α) (ha : a ∈ s) => h a ha (iff.mp mem_pi hg a ha)\n\ntheorem pi_disjoint_of_disjoint {α : Type u_1} [DecidableEq α] {δ : α → Type u_2}\n [(a : α) → DecidableEq (δ a)] {s : finset α} [DecidableEq ((a : α) → a ∈ s → δ a)]\n (t₁ : (a : α) → finset (δ a)) (t₂ : (a : α) → finset (δ a)) {a : α} (ha : a ∈ s)\n (h : disjoint (t₁ a) (t₂ a)) : disjoint (pi s t₁) (pi s t₂) :=\n sorry\n\nend Mathlib", "meta": {"author": "AurelienSaue", "repo": "Mathlib4_auto", "sha": "590df64109b08190abe22358fabc3eae000943f2", "save_path": "github-repos/lean/AurelienSaue-Mathlib4_auto", "path": "github-repos/lean/AurelienSaue-Mathlib4_auto/Mathlib4_auto-590df64109b08190abe22358fabc3eae000943f2/Mathlib/data/finset/pi_auto.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44939263446475963, "lm_q2_score": 0.04084571153154023, "lm_q1q2_score": 0.018355761911746475}} {"text": "import classes.unrestricted.basics.toolbox\nimport utilities.list_utils\n\n\nsection functions_lift_sink\n\nvariables {T N₀ N : Type}\n\ndef lift_symbol_ (lift_N : N₀ → N) : symbol T N₀ → symbol T N\n| (symbol.terminal t) := symbol.terminal t\n| (symbol.nonterminal n) := symbol.nonterminal (lift_N n)\n\ndef sink_symbol_ (sink_N : N → option N₀) : symbol T N → option (symbol T N₀)\n| (symbol.terminal t) := some (symbol.terminal t)\n| (symbol.nonterminal n) := option.map symbol.nonterminal (sink_N n)\n\ndef lift_string_ (lift_N : N₀ → N) : list (symbol T N₀) → list (symbol T N) :=\nlist.map (lift_symbol_ lift_N)\n\ndef sink_string_ (sink_N : N → option N₀) : list (symbol T N) → list (symbol T N₀) :=\nlist.filter_map (sink_symbol_ sink_N)\n\ndef lift_rule_ (lift_N : N₀ → N) : grule T N₀ → grule T N :=\nλ r : grule T N₀, grule.mk\n (lift_string_ lift_N r.input_L)\n (lift_N r.input_N)\n (lift_string_ lift_N r.input_R)\n (lift_string_ lift_N r.output_string)\n\nend functions_lift_sink\n\n\nsection lifting_conditions\n\nstructure lifted_grammar_ (T : Type) :=\n(g₀ g : grammar T)\n(lift_nt : g₀.nt → g.nt)\n(sink_nt : g.nt → option g₀.nt)\n(lift_inj : function.injective lift_nt)\n(sink_inj : ∀ x y, sink_nt x = sink_nt y →\n x = y ∨ sink_nt x = none\n)\n(lift_nt_sink : ∀ n₀ : g₀.nt, sink_nt (lift_nt n₀) = some n₀)\n(corresponding_rules : ∀ r : grule T g₀.nt,\n r ∈ g₀.rules →\n lift_rule_ lift_nt r ∈ g.rules\n)\n(preimage_of_rules : ∀ r : grule T g.nt,\n (r ∈ g.rules ∧ ∃ n₀ : g₀.nt, lift_nt n₀ = r.input_N) →\n (∃ r₀ ∈ g₀.rules, lift_rule_ lift_nt r₀ = r)\n)\n\nprivate lemma lifted_grammar_inverse {T : Type} (lg : lifted_grammar_ T) :\n ∀ x : lg.g.nt,\n (∃ val, lg.sink_nt x = some val) →\n option.map lg.lift_nt (lg.sink_nt x) = x :=\nbegin\n intros x h,\n cases h with valu ass,\n rw ass,\n rw option.map_some',\n apply congr_arg,\n symmetry,\n by_contradiction,\n have inje := lg.sink_inj x (lg.lift_nt valu),\n rw lg.lift_nt_sink at inje,\n cases inje ass with case_valu case_none,\n {\n exact h case_valu,\n },\n rw ass at case_none,\n exact option.no_confusion case_none,\nend\n\nend lifting_conditions\n\n\nsection translating_derivations\n\nvariables {T : Type}\n\nprivate lemma lift_tran_ {lg : lifted_grammar_ T} {w₁ w₂ : list (symbol T lg.g₀.nt)}\n (hyp : grammar_transforms lg.g₀ w₁ w₂) :\n grammar_transforms lg.g (lift_string_ lg.lift_nt w₁) (lift_string_ lg.lift_nt w₂) :=\nbegin\n rcases hyp with ⟨r, rin, u, v, bef, aft⟩,\n use lift_rule_ lg.lift_nt r,\n split,\n {\n exact lg.corresponding_rules r rin,\n },\n use lift_string_ lg.lift_nt u,\n use lift_string_ lg.lift_nt v,\n split,\n {\n have lift_bef := congr_arg (lift_string_ lg.lift_nt) bef,\n unfold lift_string_ at *,\n rw list.map_append_append at lift_bef,\n rw list.map_append_append at lift_bef,\n exact lift_bef,\n },\n {\n have lift_aft := congr_arg (lift_string_ lg.lift_nt) aft,\n unfold lift_string_ at *,\n rw list.map_append_append at lift_aft,\n exact lift_aft,\n },\nend\n\nlemma lift_deri_ (lg : lifted_grammar_ T) {w₁ w₂ : list (symbol T lg.g₀.nt)}\n (hyp : grammar_derives lg.g₀ w₁ w₂) :\n grammar_derives lg.g (lift_string_ lg.lift_nt w₁) (lift_string_ lg.lift_nt w₂) :=\nbegin\n induction hyp with u v trash orig ih,\n {\n apply grammar_deri_self,\n },\n apply grammar_deri_of_deri_tran,\n {\n exact ih,\n },\n exact lift_tran_ orig,\nend\n\n\ndef good_letter_ {lg : lifted_grammar_ T} : symbol T lg.g.nt → Prop\n| (symbol.terminal t) := true\n| (symbol.nonterminal n) := (∃ n₀ : lg.g₀.nt, lg.sink_nt n = n₀)\n\ndef good_string_ {lg : lifted_grammar_ T} (s : list (symbol T lg.g.nt)) :=\n∀ a ∈ s, good_letter_ a\n\nprivate lemma sink_tran_ {lg : lifted_grammar_ T} {w₁ w₂ : list (symbol T lg.g.nt)}\n (hyp : grammar_transforms lg.g w₁ w₂)\n (ok_input : good_string_ w₁) :\n grammar_transforms lg.g₀ (sink_string_ lg.sink_nt w₁) (sink_string_ lg.sink_nt w₂)\n ∧ good_string_ w₂ :=\nbegin\n rcases hyp with ⟨r, rin, u, v, bef, aft⟩,\n\n rcases lg.preimage_of_rules r (by {\n split,\n {\n exact rin,\n },\n rw bef at ok_input,\n have good_matched_nonterminal : good_letter_ (symbol.nonterminal r.input_N),\n {\n apply ok_input (symbol.nonterminal r.input_N),\n apply list.mem_append_left,\n apply list.mem_append_left,\n apply list.mem_append_right,\n rw list.mem_singleton,\n },\n change ∃ n₀ : lg.g₀.nt, lg.sink_nt r.input_N = some n₀ at good_matched_nonterminal,\n cases good_matched_nonterminal with n₀ hn₀,\n use n₀,\n have almost := congr_arg (option.map lg.lift_nt) hn₀,\n rw lifted_grammar_inverse lg r.input_N ⟨n₀, hn₀⟩ at almost,\n rw option.map_some' at almost,\n apply option.some_injective,\n exact almost.symm,\n }) with ⟨r₀, pre_in, preimage⟩,\n\n split, swap,\n {\n rw bef at ok_input,\n rw aft,\n unfold good_string_ at ok_input ⊢,\n rw ←preimage,\n clear_except ok_input,\n rw list.forall_mem_append_append at ok_input ⊢,\n rw list.forall_mem_append_append at ok_input,\n split,\n {\n exact ok_input.1.1,\n },\n split, swap,\n {\n exact ok_input.2.2,\n },\n intros a a_in_ros,\n cases a,\n {\n clear_except,\n unfold good_letter_,\n },\n unfold lift_rule_ at a_in_ros,\n dsimp only at a_in_ros,\n unfold lift_string_ at a_in_ros,\n rw list.mem_map at a_in_ros,\n rcases a_in_ros with ⟨s, trash, a_from_s⟩,\n rw ←a_from_s,\n cases s,\n {\n exfalso,\n clear_except a_from_s,\n unfold lift_symbol_ at a_from_s,\n exact symbol.no_confusion a_from_s,\n },\n unfold lift_symbol_,\n unfold good_letter_,\n use s,\n exact lg.lift_nt_sink s,\n },\n use r₀,\n split,\n {\n exact pre_in,\n },\n use sink_string_ lg.sink_nt u,\n use sink_string_ lg.sink_nt v,\n have correct_inverse : sink_symbol_ lg.sink_nt ∘ lift_symbol_ lg.lift_nt = option.some,\n {\n ext1,\n cases x,\n {\n refl,\n },\n rw function.comp_app,\n unfold lift_symbol_,\n unfold sink_symbol_,\n rw lg.lift_nt_sink,\n apply option.map_some',\n },\n split,\n {\n have sink_bef := congr_arg (sink_string_ lg.sink_nt) bef,\n unfold sink_string_ at *,\n rw list.filter_map_append_append at sink_bef,\n rw list.filter_map_append_append at sink_bef,\n convert sink_bef;\n rw ←preimage;\n unfold lift_rule_;\n dsimp only;\n clear_except correct_inverse,\n {\n unfold lift_string_,\n rw list.filter_map_map,\n rw correct_inverse,\n rw list.filter_map_some,\n },\n {\n change\n [symbol.nonterminal r₀.input_N] =\n list.filter_map (sink_symbol_ lg.sink_nt)\n (list.map (lift_symbol_ lg.lift_nt) [symbol.nonterminal r₀.input_N]),\n rw list.filter_map_map,\n rw correct_inverse,\n rw list.filter_map_some,\n },\n {\n unfold lift_string_,\n rw list.filter_map_map,\n rw correct_inverse,\n rw list.filter_map_some,\n },\n },\n {\n have sink_aft := congr_arg (sink_string_ lg.sink_nt) aft,\n unfold sink_string_ at *,\n rw list.filter_map_append_append at sink_aft,\n convert sink_aft,\n rw ←preimage,\n clear_except correct_inverse,\n unfold lift_rule_,\n dsimp only,\n unfold lift_string_,\n rw list.filter_map_map,\n rw correct_inverse,\n rw list.filter_map_some,\n },\nend\n\nprivate lemma sink_deri_aux {lg : lifted_grammar_ T} {w₁ w₂ : list (symbol T lg.g.nt)}\n (hyp : grammar_derives lg.g w₁ w₂)\n (ok_input : good_string_ w₁) :\n grammar_derives lg.g₀ (sink_string_ lg.sink_nt w₁) (sink_string_ lg.sink_nt w₂)\n ∧ good_string_ w₂ :=\nbegin\n induction hyp with u v trash orig ih,\n {\n split,\n {\n apply grammar_deri_self,\n },\n {\n exact ok_input,\n },\n },\n have both := sink_tran_ orig ih.2,\n\n split, swap,\n {\n exact both.2,\n },\n apply grammar_deri_of_deri_tran,\n {\n exact ih.1,\n },\n {\n exact both.1,\n },\nend\n\nlemma sink_deri_ (lg : lifted_grammar_ T) {w₁ w₂ : list (symbol T lg.g.nt)}\n (hyp : grammar_derives lg.g w₁ w₂)\n (ok_input : good_string_ w₁) :\n grammar_derives lg.g₀ (sink_string_ lg.sink_nt w₁) (sink_string_ lg.sink_nt w₂) :=\nbegin\n exact (sink_deri_aux hyp ok_input).1\nend\n\nend translating_derivations\n", "meta": {"author": "madvorak", "repo": "grammars", "sha": "5ab26130eb76d5f7cde0f6c2f9c6f3107ff8d34f", "save_path": "github-repos/lean/madvorak-grammars", "path": "github-repos/lean/madvorak-grammars/grammars-5ab26130eb76d5f7cde0f6c2f9c6f3107ff8d34f/src/classes/unrestricted/basics/lifting.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4804786780479071, "lm_q2_score": 0.037892427580287096, "lm_q1q2_score": 0.018206503511802398}} {"text": "import data.cpi.name\nimport data.list.witness\n\nnamespace cpi\n\n/-- A telescope may extend a context by 0 or 1 levels. This is effectively a\n function on contexts, but having it be inductive allows us to case split on\n it, simplifying some proofs. -/\n@[derive decidable_eq, nolint has_inhabited_instance]\ninductive telescope : Type\n| extend : ℕ → telescope\n| preserve : telescope\n\n/-- Apply a telescope to a context. -/\ndef telescope.apply : telescope → context → context\n| (telescope.extend n) Γ := context.extend n Γ\n| telescope.preserve Γ := Γ\n\n/-- A prefix expression. This can either be one of:\n\n - A communication prefix (send a series of variables on a channel, and then\n recieve, binding $n$ variables).\n\n - A spontaneous or silent prefix: a spontaneous reaction with some rate $k$.\n Used to model when a molecule may decompose into a simpler one.\n\n The prefix is parameterised by two types: the context it exists in, a function\n which augments an arbitrary context with variables bound by this prefix.\n\n While it is possible to do without the second parameter, this introduces many\n complexities to the proof when renaming, as you need to\n `augment (rename π) = augment π', while preserving type safety.\n-/\n@[derive decidable_eq, nolint has_inhabited_instance]\ninductive prefix_expr (ℍ : Type) : context → telescope → Type\n| communicate {} {Γ} (a : name Γ) (b : list (name Γ)) (y : ℕ) : prefix_expr Γ (telescope.extend y)\n| spontaneous {} {Γ} (k : ℍ) : prefix_expr Γ telescope.preserve\n\nvariables {ℍ : Type}\n\n-- Define some additional notation, and sugar\nnotation a `#(` b ` ; ` y `)` := prefix_expr.communicate a b y\nnotation a `#(` y `)` := prefix_expr.communicate a [] y\nnotation a `#⟨` b `⟩` := prefix_expr.communicate a b 0\nnotation a `#` := prefix_expr.communicate a [] 0\n\nnotation `τ@`:max k:max := prefix_expr.spontaneous k\n\nnamespace prefix_expr\n /-- Convert a prefix expression to a string. Can use `repr` normally. -/\n protected def to_string [has_repr ℍ] {Γ} : ∀ {f}, prefix_expr ℍ Γ f → string\n | ._ (a #( []; 0)) := repr a ++ \"#\"\n | ._ (a #( b; 0)) := repr a ++ \"#< \" ++ repr b ++ \"⟩\"\n | ._ (a #( []; y)) := repr a ++ \"#(\" ++ repr y ++ \")\"\n | ._ (a #( b; y)) := repr a ++ \"#(\" ++ repr b ++ \";\" ++ repr y ++ \")\"\n | ._ (τ@ k) := \"τ@\" ++ repr k\n\n instance [has_repr ℍ] {Γ f} : has_repr (prefix_expr ℍ Γ f) := ⟨ prefix_expr.to_string ⟩\n\n /-- A wrapper for prefixed expressions, which hides the extension function.\n\n This is suitable for comparing prefixes. -/\n @[nolint has_inhabited_instance]\n inductive wrap (ℍ : Type) : context → Type\n | intro {} {Γ} {f} (π : prefix_expr ℍ Γ f) : wrap Γ\n\n section free\n /-- Determine if any variable with a given level occurs within this prefix.\n -/\n def free_in : ∀ {Γ} {f}, level Γ → prefix_expr ℍ Γ f → Prop\n | ._ ._ l (a#(b; y)) := l ∈ a ∨ ∃ x ∈ b, l ∈ x\n | ._ ._ l τ@_ := false\n\n instance {Γ} {f} : has_mem (level Γ) (prefix_expr ℍ Γ f) := ⟨ free_in ⟩\n\n private def free_in_decide : ∀ {Γ} {f}\n (l : level Γ) (π : prefix_expr ℍ Γ f), decidable (free_in l π)\n | Γ ._ l (a#(b; y)) := if h : l ∈ a ∨ ∃ x ∈ b, l ∈ x then is_true h else is_false h\n | ._ ._ l τ@_ := decidable.false\n\n instance free_in.decidable {Γ} {f} {l} {π : prefix_expr ℍ Γ f}\n : decidable (free_in l π)\n := free_in_decide l π\n end free\n\n /- Renaming and extension.\n\n The extension sections are largely similar to that in data.cpi.name - see\n there for an explanation of some of the decisions made. -/\n section rename\n /-- Raise a level according to this prefix's context extension function. -/\n def raise :\n ∀ {Γ η} {f} (π : prefix_expr ℍ η f)\n , level Γ → level (f.apply Γ)\n | Γ ._ ._ (a#(b; y)) l := level.extend l\n | Γ ._ ._ τ@_ l := l\n\n /-- Rename all names within a prefix expression, providing some witness that\n this variable is free within it. -/\n def rename_with {Γ Δ} :\n Π {f} (π : prefix_expr ℍ Γ f)\n , (Π (a : name Γ), name.to_level a ∈ π → name Δ) → prefix_expr ℍ Δ f\n | f (a#(b; y)) ρ :=\n let a' := ρ a (or.inl (name.to_level_at a)) in\n let b' := list.map_witness b\n (λ x mem, ρ x (or.inr ⟨ x, mem, name.to_level_at x ⟩))\n in\n a'#( b' ; y)\n | f τ@k ρ := τ@k\n\n /-- Simple renaming function, not taking any witness. -/\n @[reducible]\n def rename {Γ Δ} {f} (ρ : name Γ → name Δ) (π : prefix_expr ℍ Γ f)\n : prefix_expr ℍ Δ f\n := rename_with π (λ a _, ρ a)\n\n /-- Renaming with the identity function does nothing. -/\n lemma rename_with_id {Γ} : ∀ {f} (π : prefix_expr ℍ Γ f)\n , rename_with π (λ a _, a) = π\n | ._ (a#(b; y)) := by simp [rename_with]\n | ._ τ@k := rfl\n\n /-- Renaming with the identity function is the identity. -/\n lemma rename_id {Γ} {f} (π : prefix_expr ℍ Γ f) : rename id π = π\n := rename_with_id π\n\n /-- Renaming twice is the same as renaming with a composed function. -/\n lemma rename_with_compose {Γ Δ η} :\n ∀ {f} (π : prefix_expr ℍ Γ f)\n (ρ : Π (a : name Γ), name.to_level a ∈ π → name Δ)\n (σ : name Δ → name η)\n , rename σ (rename_with π ρ) = rename_with π (λ a free, σ (ρ a free))\n | f (a#(b; y)) ρ σ := by simp [rename_with, rename, list.map_witness_to_map]\n | f (τ@_) ρ σ := rfl\n\n /-- Renaming twice is the same as renaming with a composed function. -/\n lemma rename_compose {Γ Δ η} {f}\n (π : prefix_expr ℍ Γ f) (ρ : name Γ → name Δ) (σ : name Δ → name η)\n : rename σ (rename ρ π) = rename (σ ∘ ρ) π\n := rename_with_compose π _ _\n\n /-- Wrap a renaming function, making it suitable for a nested context. -/\n def ext_with {Γ Δ η} :\n ∀ {f} (π : prefix_expr ℍ η f)\n (P : level (f.apply Γ) → Prop)\n (ρ : Π (x : name Γ), P (prefix_expr.raise π (name.to_level x)) → name Δ)\n , Π (x : name (f.apply Γ)), P (name.to_level x) → name (f.apply Δ)\n | f (_#(_; y)) P ρ a p := name.ext_with P ρ a p\n | f τ@_ P ρ a p := ρ a p\n\n /-- Extending with the identity does nothing. -/\n lemma ext_with_identity :\n ∀ {Γ η} {f} (π : prefix_expr ℍ η f)\n (P : level (f.apply Γ) → Prop)\n (a : name (f.apply Γ)) (p : P (name.to_level a))\n , ext_with π P (λ x _, x) a p = a\n | Γ η ._ (_#(_; _)) P a p := name.ext_with_identity P a p\n | Γ η ._ τ@k P a p := rfl\n\n /-- Extending with the identity does nothing. -/\n lemma ext_with_id {Γ η} {f}\n (π : prefix_expr ℍ η f) (P : level (f.apply Γ) → Prop)\n : ext_with π P (λ x _, x) = λ x _, x\n := funext $ λ a, funext (ext_with_identity π P a)\n\n /-- Wrap a simple renaming function, making it suitable for a nested context. -/\n def ext {Γ Δ η} {f} (π : prefix_expr ℍ η f) (ρ : name Γ → name Δ)\n : name (f.apply Γ) → name (f.apply Δ)\n | a := ext_with π (λ _, true) (λ x _, ρ x) a true.intro\n\n /-- Extending with the identity does nothing. -/\n lemma ext_identity {Γ η} {f} (π : prefix_expr ℍ η f) (a : name (f.apply Γ))\n : ext π id a = a := ext_with_identity π _ a _\n\n /-- Extending with the identity yields the identity function. -/\n lemma ext_id : ∀ {Γ η} {f} (π : prefix_expr ℍ η f), @ext ℍ Γ Γ η f π id = id\n | Γ η f π := funext (ext_identity π)\n\n /-- Composing extensions is equivalent extending a composition. -/\n lemma ext_with_compose :\n ∀ {Γ Δ η φ} {f} (π : prefix_expr ℍ φ f)\n (P : level (f.apply Γ) → Prop)\n (ρ : Π (x : name Γ), P (raise π (name.to_level x)) → name Δ)\n (σ : name Δ → name η)\n (a : name (f.apply Γ)) (p : P (name.to_level a))\n , ext π σ (ext_with π P ρ a p) = ext_with π P (λ a p, σ (ρ a p)) a p\n | Γ Δ η φ f (_#(_;_)) P ρ σ a p := name.ext_with_compose P ρ σ a p\n | Γ Δ η φ f τ@_ P ρ σ _ _ := rfl\n\n /-- Composing extensions is equivalent extending a composition. -/\n lemma ext_with_comp {Γ Δ η φ} {f} (π : prefix_expr ℍ φ f)\n (P : level (f.apply Γ) → Prop)\n (ρ : Π (x : name Γ), P (raise π (name.to_level x)) → name Δ)\n (σ : name Δ → name η)\n : (λ a p, ext π σ (ext_with π P ρ a p)) = ext_with π P (λ a p, σ (ρ a p))\n := funext $ λ a, funext (ext_with_compose π P ρ σ a)\n\n /-- Composing extensions is equivalent extending a composition. -/\n lemma ext_compose :\n ∀ {Γ Δ η φ} {f} (ρ : name Γ → name Δ) (σ : name Δ → name η)\n (π : prefix_expr ℍ φ f) (α : name (f.apply Γ))\n , ext π σ (ext π ρ α) = ext π (σ ∘ ρ) α\n | Γ Δ η φ f ρ σ (a#(b; y)) α := name.ext_compose ρ σ α\n | Γ Δ η φ f ρ σ τ@k α := rfl\n\n /-- Composing extensions is equivalent extending a composition. -/\n lemma ext_comp :\n ∀ {Γ Δ η φ} {f} (ρ : name Γ → name Δ) (σ : name Δ → name η)\n (π : prefix_expr ℍ φ f)\n , (ext π σ ∘ ext π ρ) = ext π (σ ∘ ρ)\n | Γ Δ η φ f ρ σ π := funext (ext_compose ρ σ π)\n\n /-- Rewrite one ext_with to another -/\n lemma ext_with_discard :\n ∀ {Γ Δ η} {f} (π : prefix_expr ℍ η f)\n (P : level (f.apply Γ) → Prop)\n (ρ : name Γ → name Δ)\n , (ext_with π P (λ a _, ρ a))\n = (λ a _, ext_with π (λ _x, true) (λ x _, ρ x) a true.intro)\n | Γ Δ η f (a'#(b; y)) P ρ := funext $ λ a, funext $ λ free, begin\n have : (λ (a : name Γ) (_x : P (@raise ℍ _ _ _ (a'#(b ; y)) (name.to_level a))), ρ a)\n = (λ (a : name Γ) (_x : P (level.extend (name.to_level a))), ρ a)\n := rfl,\n unfold ext_with,\n rw [this, name.ext_with_discard P],\n from rfl,\n end\n | Γ Δ η f τ@_ P ρ := funext $ λ a, funext $ λ free, rfl\n\n /-- Raising with a renamed prefix has the same effect as the original one. -/\n lemma rename_with_raise\n {Γ Δ η} {f} (π : prefix_expr ℍ Γ f)\n (ρ : Π (x : name Γ), name.to_level x ∈ π → name Δ)\n (l : level η)\n : raise π l = raise (rename_with π ρ) l\n := by { cases π; from rfl }\n\n /-- Extending with a renamed prefix has the same effect as the original one. -/\n lemma rename_with_ext_with\n {Γ Δ η φ} {f} (π : prefix_expr ℍ η f)\n (P : level (f.apply Γ) → Prop)\n (ρ : name Γ → name Δ)\n (σ : Π (x : name η), name.to_level x ∈ π → name φ)\n : ext_with (rename_with π σ) P (λ a _, ρ a) = ext_with π P (λ a _, ρ a)\n := funext $ λ a, funext $ λ free, by { cases π; from rfl }\n\n /-- Extending with a renamed prefix has the same effect as the original one. -/\n lemma rename_ext\n {Γ Δ η φ} {f} (ρ : name Γ → name Δ) (σ : name η → name φ)\n (π : prefix_expr ℍ Γ f)\n : @ext ℍ η φ Γ f π σ = (ext (rename ρ π) σ)\n := funext $ λ a, by { cases π; from rfl }\n end rename\n\n section rename_equations\n variables {Γ Δ : context} {ρ : name Γ → name Δ}\n\n @[simp]\n lemma rename_communicate (a : name Γ) (b : list (name Γ)) (y : ℕ)\n : rename ρ (a#(b; y) : prefix_expr ℍ _ _) = ((ρ a)#(list.map ρ b; y))\n := by simp [rename, rename_with, list.map_witness_to_map]\n\n @[simp]\n lemma rename_spontaneous (k : ℍ)\n : rename ρ τ@k = τ@k\n := by simp only [rename, rename_with]\n\n @[simp]\n lemma ext_communicate {η} (a : name η) (b : list (name η)) (y : ℕ)\n : ext (a#(b; y) : prefix_expr ℍ _ _) ρ = name.ext ρ\n := funext $ λ x, by { unfold ext ext_with, from rfl }\n\n @[simp]\n lemma ext_spontaneous {η} (k : ℍ)\n : ext (@spontaneous ℍ η k) ρ = ρ\n := funext $ λ x, by unfold ext ext_with\n\n private lemma rename_inj {Γ Δ} {ρ : name Γ → name Δ} (inj : function.injective ρ)\n : ∀ {f₁ f₂} {π₁ : prefix_expr ℍ Γ f₁} {π₂ : prefix_expr ℍ Γ f₂}\n , wrap.intro (rename ρ π₁) = wrap.intro (rename ρ π₂)\n → π₁ == π₂\n | _ _ (a#(b; y)) (a'#(b'; y')) eq := begin\n simp only [rename_communicate] at eq,\n rcases eq with ⟨ ⟨ _ ⟩, eqπ ⟩,\n simp only [heq_iff_eq] at eqπ ⊢,\n from ⟨ inj eqπ.left, list.injective_map_iff.mpr inj eqπ.right ⟩,\n end\n | _ _ (a#(b; y)) τ@k eq := begin\n simp only [rename_communicate, rename_spontaneous] at eq,\n exfalso, from eq.1,\n end\n | _ _ τ@k (a#(b; y)) eq := begin\n simp only [rename_communicate, rename_spontaneous] at eq,\n exfalso, from eq.1,\n end\n | _ _ τ@k τ@k' eq := begin\n simp only [rename_spontaneous] at eq,\n rcases eq with ⟨ eqC, eqπ ⟩,\n cases eqπ, from heq.refl _,\n end\n\n lemma rename.inj {Γ Δ} {ρ : name Γ → name Δ} (inj : function.injective ρ)\n : ∀ {f}, function.injective (@rename ℍ Γ Δ f ρ)\n | f π₁ π₂ eq := eq_of_heq (rename_inj inj (congr_arg wrap.intro eq))\n\n lemma ext.inj {Γ Δ η} {ρ : name Γ → name Δ}\n : ∀ {f} (π : prefix_expr ℍ η f), function.injective ρ → function.injective (ext π ρ)\n | ._ (_#(_; y)) inj a b eq := begin\n simp only [ext_communicate] at eq,\n from name.ext.inj inj eq,\n end\n | ._ (τ@_) inj a b eq := by { simp only [ext_spontaneous] at eq, from inj eq, }\n end rename_equations\nend prefix_expr\n\nend cpi\n\n#lint-\n", "meta": {"author": "continuouspi", "repo": "lean-cpi", "sha": "443bf2cb236feadc45a01387099c236ab2b78237", "save_path": "github-repos/lean/continuouspi-lean-cpi", "path": "github-repos/lean/continuouspi-lean-cpi/lean-cpi-443bf2cb236feadc45a01387099c236ab2b78237/src/data/cpi/prefix_expr.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.0362200557349317, "lm_q1q2_score": 0.01811002786746585}} {"text": "/-\nCopyright (c) 2016 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Leonardo de Moura\n-/\nprelude\nimport init.control\nimport init.meta.simp_tactic\nimport init.meta.smt.congruence_closure\nimport init.meta.smt.ematch\n\nuniverse u\n\nrun_cmd mk_simp_attr `pre_smt\nrun_cmd mk_hinst_lemma_attr_set `ematch [] [`ematch_lhs]\n\n/--\n Configuration for the smt tactic preprocessor. The preprocessor\n is applied whenever a new hypothesis is introduced.\n\n - simp_attr: is the attribute name for the simplification lemmas\n that are used during the preprocessing step.\n\n - max_steps: it is the maximum number of steps performed by the simplifier.\n\n - zeta: if tt, then zeta reduction (i.e., unfolding let-expressions)\n is used during preprocessing.\n-/\nstructure smt_pre_config :=\n(simp_attr : name := `pre_smt)\n(max_steps : nat := 1000000)\n(zeta : bool := ff)\n\n/--\nConfiguration for the smt_state object.\n\n- em_attr: is the attribute name for the hinst_lemmas\n that are used for ematching -/\nstructure smt_config :=\n(cc_cfg : cc_config := {})\n(em_cfg : ematch_config := {})\n(pre_cfg : smt_pre_config := {})\n(em_attr : name := `ematch)\n\nmeta def smt_config.set_classical (c : smt_config) (b : bool) : smt_config :=\n{ cc_cfg := { em := b, ..c.cc_cfg }, ..c }\n\nmeta constant smt_goal : Type\nmeta def smt_state :=\nlist smt_goal\nmeta constant smt_state.mk : smt_config → tactic smt_state\nmeta constant smt_state.to_format : smt_state → tactic_state → format\n/-- Return tt iff classical excluded middle was enabled at smt_state.mk -/\nmeta constant smt_state.classical : smt_state → bool\n\nmeta def smt_tactic :=\nstate_t smt_state tactic\n\nmeta instance : has_append smt_state :=\nlist.has_append\n\nsection\nlocal attribute [reducible] smt_tactic\nmeta instance : monad smt_tactic := by apply_instance\nmeta instance : alternative smt_tactic := by apply_instance\nmeta instance : monad_state smt_state smt_tactic := by apply_instance\nend\n\n/- We don't use the default state_t lift operation because only\n tactics that do not change hypotheses can be automatically lifted to smt_tactic. -/\nmeta constant tactic_to_smt_tactic (α : Type) : tactic α → smt_tactic α\n\nmeta instance : has_monad_lift tactic smt_tactic :=\n⟨tactic_to_smt_tactic⟩\n\nmeta instance (α : Type) : has_coe (tactic α) (smt_tactic α) :=\n⟨monad_lift⟩\n\nmeta instance : monad_fail smt_tactic :=\n{ fail := λ α s, (tactic.fail (to_fmt s) : smt_tactic α), ..smt_tactic.monad }\n\nnamespace smt_tactic\nopen tactic (transparency)\nmeta constant intros : smt_tactic unit\nmeta constant intron : nat → smt_tactic unit\nmeta constant intro_lst : list name → smt_tactic unit\n/--\n Try to close main goal by using equalities implied by the congruence\n closure module.\n-/\nmeta constant close : smt_tactic unit\n/--\n Produce new facts using heuristic lemma instantiation based on E-matching.\n This tactic tries to match patterns from lemmas in the main goal with terms\n in the main goal. The set of lemmas is populated with theorems\n tagged with the attribute specified at smt_config.em_attr, and lemmas\n added using tactics such as `smt_tactic.add_lemmas`.\n The current set of lemmas can be retrieved using the tactic `smt_tactic.get_lemmas`.\n\n Remark: the given predicate is applied to every new instance. The instance\n is only added to the state if the predicate returns tt.\n-/\nmeta constant ematch_core : (expr → bool) → smt_tactic unit\n/--\n Produce new facts using heuristic lemma instantiation based on E-matching.\n This tactic tries to match patterns from the given lemmas with terms in\n the main goal.\n-/\nmeta constant ematch_using : hinst_lemmas → smt_tactic unit\nmeta constant mk_ematch_eqn_lemmas_for_core : transparency → name → smt_tactic hinst_lemmas\nmeta constant to_cc_state : smt_tactic cc_state\nmeta constant to_em_state : smt_tactic ematch_state\nmeta constant get_config : smt_tactic smt_config\n/--\n Preprocess the given term using the same simplifications rules used when\n we introduce a new hypothesis. The result is pair containing the resulting\n term and a proof that it is equal to the given one.\n-/\nmeta constant preprocess : expr → smt_tactic (expr × expr)\nmeta constant get_lemmas : smt_tactic hinst_lemmas\nmeta constant set_lemmas : hinst_lemmas → smt_tactic unit\nmeta constant add_lemmas : hinst_lemmas → smt_tactic unit\n\nmeta def add_ematch_lemma_core (md : transparency) (as_simp : bool) (e : expr) : smt_tactic unit :=\ndo h ← hinst_lemma.mk_core md e as_simp,\n add_lemmas (mk_hinst_singleton h)\n\nmeta def add_ematch_lemma_from_decl_core (md : transparency) (as_simp : bool) (n : name) : smt_tactic unit :=\ndo h ← hinst_lemma.mk_from_decl_core md n as_simp,\n add_lemmas (mk_hinst_singleton h)\n\nmeta def add_ematch_eqn_lemmas_for_core (md : transparency) (n : name) : smt_tactic unit :=\ndo hs ← mk_ematch_eqn_lemmas_for_core md n,\n add_lemmas hs\n\nmeta def ematch : smt_tactic unit :=\nematch_core (λ _, tt)\n\nmeta def failed {α} : smt_tactic α :=\ntactic.failed\n\nmeta def fail {α : Type} {β : Type u} [has_to_format β] (msg : β) : smt_tactic α :=\ntactic.fail msg\n\nmeta def try {α : Type} (t : smt_tactic α) : smt_tactic unit :=\n⟨λ ss ts, result.cases_on (t.run ss ts)\n (λ ⟨a, new_ss⟩, result.success ((), new_ss))\n (λ e ref s', result.success ((), ss) ts)⟩\n\n/-- `iterate_at_most n t`: repeat the given tactic at most n times or until t fails -/\nmeta def iterate_at_most : nat → smt_tactic unit → smt_tactic unit\n| 0 t := return ()\n| (n+1) t := (do t, iterate_at_most n t) <|> return ()\n\n/-- `iterate_exactly n t` : execute t n times -/\nmeta def iterate_exactly : nat → smt_tactic unit → smt_tactic unit\n| 0 t := return ()\n| (n+1) t := do t, iterate_exactly n t\n\nmeta def iterate : smt_tactic unit → smt_tactic unit :=\niterate_at_most 100000\n\nmeta def eblast : smt_tactic unit :=\niterate (ematch >> try close)\n\nopen tactic\n\nprotected meta def read : smt_tactic (smt_state × tactic_state) :=\ndo s₁ ← get,\n s₂ ← tactic.read,\n return (s₁, s₂)\n\nprotected meta def write : smt_state × tactic_state → smt_tactic unit :=\nλ ⟨ss, ts⟩, ⟨λ _ _, result.success ((), ss) ts⟩\n\nprivate meta def mk_smt_goals_for (cfg : smt_config) : list expr → list smt_goal → list expr\n → tactic (list smt_goal × list expr)\n| [] sr tr := return (sr.reverse, tr.reverse)\n| (tg::tgs) sr tr := do\n tactic.set_goals [tg],\n [new_sg] ← smt_state.mk cfg | tactic.failed,\n [new_tg] ← get_goals | tactic.failed,\n mk_smt_goals_for tgs (new_sg::sr) (new_tg::tr)\n\n/- See slift -/\nmeta def slift_aux {α : Type} (t : tactic α) (cfg : smt_config) : smt_tactic α :=\n⟨λ ss, do\n _::sgs ← return ss | tactic.fail \"slift tactic failed, there no smt goals to be solved\",\n tg::tgs ← tactic.get_goals | tactic.failed,\n tactic.set_goals [tg], a ← t,\n new_tgs ← tactic.get_goals,\n (new_sgs, new_tgs) ← mk_smt_goals_for cfg new_tgs [] [],\n tactic.set_goals (new_tgs ++ tgs),\n return (a, new_sgs ++ sgs)⟩\n\n/--\n This lift operation will restart the SMT state.\n It is useful for using tactics that change the set of hypotheses. -/\nmeta def slift {α : Type} (t : tactic α) : smt_tactic α :=\nget_config >>= slift_aux t\n\nmeta def trace_state : smt_tactic unit :=\ndo (s₁, s₂) ← smt_tactic.read,\n trace (smt_state.to_format s₁ s₂)\n\nmeta def trace {α : Type} [has_to_tactic_format α] (a : α) : smt_tactic unit :=\ntactic.trace a\n\nmeta def to_expr (q : pexpr) (allow_mvars := tt) : smt_tactic expr :=\ntactic.to_expr q allow_mvars\n\nmeta def classical : smt_tactic bool :=\ndo s ← get,\n return s.classical\n\nmeta def num_goals : smt_tactic nat :=\nlist.length <$> get\n\n/- Low level primitives for managing set of goals -/\nmeta def get_goals : smt_tactic (list smt_goal × list expr) :=\ndo (g₁, _) ← smt_tactic.read,\n g₂ ← tactic.get_goals,\n return (g₁, g₂)\n\nmeta def set_goals : list smt_goal → list expr → smt_tactic unit :=\nλ g₁ g₂, ⟨λ ss, tactic.set_goals g₂ >> return ((), g₁)⟩\n\nprivate meta def all_goals_core (tac : smt_tactic unit) : list smt_goal → list expr → list smt_goal → list expr → smt_tactic unit\n| [] ts acs act := set_goals acs (ts ++ act)\n| (s :: ss) [] acs act := fail \"ill-formed smt_state\"\n| (s :: ss) (t :: ts) acs act :=\n do set_goals [s] [t],\n tac,\n (new_ss, new_ts) ← get_goals,\n all_goals_core ss ts (acs ++ new_ss) (act ++ new_ts)\n\n/-- Apply the given tactic to all goals. -/\nmeta def all_goals (tac : smt_tactic unit) : smt_tactic unit :=\ndo (ss, ts) ← get_goals,\n all_goals_core tac ss ts [] []\n\n/-- LCF-style AND_THEN tactic. It applies tac1, and if succeed applies tac2 to each subgoal produced by tac1 -/\nmeta def seq (tac1 : smt_tactic unit) (tac2 : smt_tactic unit) : smt_tactic unit :=\ndo (s::ss, t::ts) ← get_goals,\n set_goals [s] [t],\n tac1, all_goals tac2,\n (new_ss, new_ts) ← get_goals,\n set_goals (new_ss ++ ss) (new_ts ++ ts)\n\nmeta instance : has_andthen (smt_tactic unit) (smt_tactic unit) (smt_tactic unit) :=\n⟨seq⟩\n\nmeta def focus1 {α} (tac : smt_tactic α) : smt_tactic α :=\ndo (s::ss, t::ts) ← get_goals,\n match ss with\n | [] := tac\n | _ := do\n set_goals [s] [t],\n a ← tac,\n (ss', ts') ← get_goals,\n set_goals (ss' ++ ss) (ts' ++ ts),\n return a\n end\n\nmeta def solve1 (tac : smt_tactic unit) : smt_tactic unit :=\ndo (ss, gs) ← get_goals,\n match ss, gs with\n | [], _ := fail \"solve1 tactic failed, there isn't any goal left to focus\"\n | _, [] := fail \"solve1 tactic failed, there isn't any smt goal left to focus\"\n | s::ss, g::gs :=\n do set_goals [s] [g],\n tac,\n (ss', gs') ← get_goals,\n match ss', gs' with\n | [], [] := set_goals ss gs\n | _, _ := fail \"solve1 tactic failed, focused goal has not been solved\"\n end\n end\n\nmeta def swap : smt_tactic unit :=\ndo (ss, ts) ← get_goals,\n match ss, ts with\n | (s₁ :: s₂ :: ss), (t₁ :: t₂ :: ts) := set_goals (s₂ :: s₁ :: ss) (t₂ :: t₁ :: ts)\n | _, _ := failed\n end\n\n/-- Add a new goal for t, and the hypothesis (h : t) in the current goal. -/\nmeta def assert (h : name) (t : expr) : smt_tactic unit :=\ntactic.assert_core h t >> swap >> intros >> swap >> try close\n\n/-- Add the hypothesis (h : t) in the current goal if v has type t. -/\nmeta def assertv (h : name) (t : expr) (v : expr) : smt_tactic unit :=\ntactic.assertv_core h t v >> intros >> return ()\n\n/-- Add a new goal for t, and the hypothesis (h : t := ?M) in the current goal. -/\nmeta def define (h : name) (t : expr) : smt_tactic unit :=\ntactic.define_core h t >> swap >> intros >> swap >> try close\n\n/-- Add the hypothesis (h : t := v) in the current goal if v has type t. -/\nmeta def definev (h : name) (t : expr) (v : expr) : smt_tactic unit :=\ntactic.definev_core h t v >> intros >> return ()\n\n/-- Add (h : t := pr) to the current goal -/\nmeta def pose (h : name) (t : option expr := none) (pr : expr) : smt_tactic unit :=\nmatch t with\n| none := do t ← infer_type pr, definev h t pr\n| some t := definev h t pr\nend\n\n/-- Add (h : t) to the current goal, given a proof (pr : t) -/\nmeta def note (h : name) (t : option expr := none) (pr : expr) : smt_tactic unit :=\nmatch t with\n| none := do t ← infer_type pr, assertv h t pr\n| some t := assertv h t pr\nend\n\nmeta def destruct (e : expr) : smt_tactic unit :=\nsmt_tactic.seq (tactic.destruct e) smt_tactic.intros\n\nmeta def by_cases (e : expr) : smt_tactic unit :=\ndo c ← classical,\n if c then\n destruct (expr.app (expr.const `classical.em []) e)\n else do\n dec_e ← (mk_app `decidable [e] <|> fail \"by_cases smt_tactic failed, type is not a proposition\"),\n inst ← (mk_instance dec_e <|> fail \"by_cases smt_tactic failed, type of given expression is not decidable\"),\n em ← mk_app `decidable.em [e, inst],\n destruct em\n\nmeta def by_contradiction : smt_tactic unit :=\ndo t ← target,\n c ← classical,\n if t.is_false then skip\n else if c then do\n apply (expr.app (expr.const `classical.by_contradiction []) t),\n intros\n else do\n dec_t ← (mk_app `decidable [t] <|> fail \"by_contradiction smt_tactic failed, target is not a proposition\"),\n inst ← (mk_instance dec_t <|> fail \"by_contradiction smt_tactic failed, target is not decidable\"),\n a ← mk_mapp `decidable.by_contradiction [some t, some inst],\n apply a,\n intros\n\n/-- Return a proof for e, if 'e' is a known fact in the main goal. -/\nmeta def proof_for (e : expr) : smt_tactic expr :=\ndo cc ← to_cc_state, cc.proof_for e\n\n/-- Return a refutation for e (i.e., a proof for (not e)), if 'e' has been refuted in the main goal. -/\nmeta def refutation_for (e : expr) : smt_tactic expr :=\ndo cc ← to_cc_state, cc.refutation_for e\n\nmeta def get_facts : smt_tactic (list expr) :=\ndo cc ← to_cc_state,\n return $ cc.eqc_of expr.mk_true\n\nmeta def get_refuted_facts : smt_tactic (list expr) :=\ndo cc ← to_cc_state,\n return $ cc.eqc_of expr.mk_false\n\nmeta def add_ematch_lemma : expr → smt_tactic unit :=\nadd_ematch_lemma_core reducible ff\n\nmeta def add_ematch_lhs_lemma : expr → smt_tactic unit :=\nadd_ematch_lemma_core reducible tt\n\nmeta def add_ematch_lemma_from_decl : name → smt_tactic unit :=\nadd_ematch_lemma_from_decl_core reducible ff\n\nmeta def add_ematch_lhs_lemma_from_decl : name → smt_tactic unit :=\nadd_ematch_lemma_from_decl_core reducible ff\n\nmeta def add_ematch_eqn_lemmas_for : name → smt_tactic unit :=\nadd_ematch_eqn_lemmas_for_core reducible\n\nmeta def add_lemmas_from_facts_core : list expr → smt_tactic unit\n| [] := return ()\n| (f::fs) := do\n try (is_prop f >> guard (f.is_pi && bnot (f.is_arrow)) >> proof_for f >>= add_ematch_lemma_core reducible ff),\n add_lemmas_from_facts_core fs\n\nmeta def add_lemmas_from_facts : smt_tactic unit :=\nget_facts >>= add_lemmas_from_facts_core\n\nmeta def induction (e : expr) (ids : list name := []) (rec : option name := none) : smt_tactic unit :=\nslift (tactic.induction e ids rec >> return ()) -- pass on the information?\n\nmeta def when (c : Prop) [decidable c] (tac : smt_tactic unit) : smt_tactic unit :=\nif c then tac else skip\n\nmeta def when_tracing (n : name) (tac : smt_tactic unit) : smt_tactic unit :=\nwhen (is_trace_enabled_for n = tt) tac\n\nend smt_tactic\n\nopen smt_tactic\n\nmeta def using_smt {α} (t : smt_tactic α) (cfg : smt_config := {}) : tactic α :=\ndo ss ← smt_state.mk cfg,\n (a, _) ← (do a ← t, iterate close, return a).run ss,\n return a\n\nmeta def using_smt_with {α} (cfg : smt_config) (t : smt_tactic α) : tactic α :=\nusing_smt t cfg\n", "meta": {"author": "subfish-zhou", "repo": "N2Lean", "sha": "8e858cc5b01f1ad921094dc355db3cb9473a42fd", "save_path": "github-repos/lean/subfish-zhou-N2Lean", "path": "github-repos/lean/subfish-zhou-N2Lean/N2Lean-8e858cc5b01f1ad921094dc355db3cb9473a42fd/library/init/meta/smt/smt_tactic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3276683008207139, "lm_q2_score": 0.055005289455291144, "lm_q1q2_score": 0.018023489731966783}} {"text": "-- Copyright (c) 2017 Scott Morrison. All rights reserved.\n-- Released under Apache 2.0 license as described in the file LICENSE.\n-- Authors: Scott Morrison\n\n/- The Yoneda embedding, as a functor `yoneda : C ⥤ ((Cᵒᵖ) ⥤ (Type v₁))`,\n along with instances that it is `full` and `faithful`.\n \n Also the Yoneda lemma, `yoneda_lemma : (yoneda_pairing C) ≅ (yoneda_evaluation C)`. -/\n\nimport category_theory.natural_transformation\nimport category_theory.opposites\nimport category_theory.types\nimport category_theory.embedding\nimport category_theory.natural_isomorphism\n\nnamespace category_theory\n\nuniverses u₁ v₁ u₂\n\nvariables (C : Type u₁) [𝒞 : category.{u₁ v₁} C]\ninclude 𝒞\n\ndef yoneda : C ⥤ ((Cᵒᵖ) ⥤ (Type v₁)) := \n{ obj := λ X,\n { obj := λ Y : C, Y ⟶ X,\n map' := λ Y Y' f g, f ≫ g,\n map_comp' := begin intros X_1 Y Z f g, ext1, dsimp at *, erw [category.assoc] end,\n map_id' := begin intros X_1, ext1, dsimp at *, erw [category.id_comp] end },\n map' := λ X X' f, { app := λ Y g, g ≫ f } }\n\nnamespace yoneda\n@[simp] lemma obj_obj (X Y : C) : ((yoneda C) X) Y = (Y ⟶ X) := rfl\n@[simp] lemma obj_map (X : C) {Y Y' : C} (f : Y ⟶ Y') : ((yoneda C) X).map f = λ g, f ≫ g := rfl\n@[simp] lemma map_app {X X' : C} (f : X ⟶ X') (Y : C) : ((yoneda C).map f) Y = λ g, g ≫ f := rfl\n\nlemma obj_map_id {X Y : Cᵒᵖ} (f : X ⟶ Y) : ((yoneda C) X).map f (𝟙 X) = ((yoneda C).map f) Y (𝟙 Y) := \nby obviously\n\n@[simp] lemma naturality {X Y : C} (α : (yoneda C) X ⟶ (yoneda C) Y) \n {Z Z' : C} (f : Z ⟶ Z') (h : Z' ⟶ X) : f ≫ α Z' h = α Z (f ≫ h) :=\nbegin erw [functor_to_types.naturality], refl end\n\ninstance full : full (yoneda C) := \n{ preimage := λ X Y f, (f X) (𝟙 X) }.\n\ninstance faithful : faithful (yoneda C) := \nbegin\n fsplit, \n intros X Y f g p, \n injection p with h,\n convert (congr_fun (congr_fun h X) (𝟙 X)) ; simp\nend\n\n/-- Extensionality via Yoneda. The typical usage would be\n```\n-- Goal is `X ≅ Y`\napply yoneda.ext,\n-- Goals are now functions `(Z ⟶ X) → (Z ⟶ Y)`, `(Z ⟶ Y) → (Z ⟶ X)`, and the fact that these\nfunctions are inverses and natural in `Z`.\n```\n-/\ndef ext (X Y : C)\n (p : Π {Z : C}, (Z ⟶ X) → (Z ⟶ Y)) (q : Π {Z : C}, (Z ⟶ Y) → (Z ⟶ X))\n (h₁ : Π {Z : C} (f : Z ⟶ X), q (p f) = f) (h₂ : Π {Z : C} (f : Z ⟶ Y), p (q f) = f) \n (n : Π {Z Z' : C} (f : Z' ⟶ Z) (g : Z ⟶ X), p (f ≫ g) = f ≫ p g) : X ≅ Y := \n@preimage_iso _ _ _ _ (yoneda C) _ _ _ _ \n (nat_iso.of_components (λ Z, { hom := p, inv := q, }) (by tidy))\n\n-- We need to help typeclass inference with some awkward universe levels here.\ninstance prod_category_instance_1 : category (((Cᵒᵖ) ⥤ Type v₁) × (Cᵒᵖ)) := \ncategory_theory.prod.{(max u₁ (v₁+1)) (max u₁ v₁) u₁ v₁} (Cᵒᵖ ⥤ Type v₁) (Cᵒᵖ)\n\ninstance prod_category_instance_2 : category ((Cᵒᵖ) × ((Cᵒᵖ) ⥤ Type v₁)) := \ncategory_theory.prod.{u₁ v₁ (max u₁ (v₁+1)) (max u₁ v₁)} (Cᵒᵖ) (Cᵒᵖ ⥤ Type v₁) \n\nend yoneda\n\nopen yoneda\n\ndef yoneda_evaluation : (((Cᵒᵖ) ⥤ (Type v₁)) × (Cᵒᵖ)) ⥤ (Type (max u₁ v₁)) := \n(evaluation (Cᵒᵖ) (Type v₁)) ⋙ ulift_functor.{v₁ u₁}\n\n@[simp] lemma yoneda_evaluation_map_down\n (P Q : (Cᵒᵖ ⥤ Type v₁) × (Cᵒᵖ)) (α : P ⟶ Q) (x : (yoneda_evaluation C) P) : \n ((yoneda_evaluation C).map α x).down = (α.1) (Q.2) ((P.1).map (α.2) (x.down)) := rfl\n\ndef yoneda_pairing : (((Cᵒᵖ) ⥤ (Type v₁)) × (Cᵒᵖ)) ⥤ (Type (max u₁ v₁)) := \nlet F := (category_theory.prod.swap ((Cᵒᵖ) ⥤ (Type v₁)) (Cᵒᵖ)) in\nlet G := (functor.prod ((yoneda C).op) (functor.id ((Cᵒᵖ) ⥤ (Type v₁)))) in\nlet H := (functor.hom ((Cᵒᵖ) ⥤ (Type v₁))) in\n (F ⋙ G ⋙ H) \n\n@[simp] lemma yoneda_pairing_map\n (P Q : (Cᵒᵖ ⥤ Type v₁) × (Cᵒᵖ)) (α : P ⟶ Q) (β : (yoneda_pairing C) (P.1, P.2)) : \n (yoneda_pairing C).map α β = (yoneda C).map (α.snd) ≫ β ≫ α.fst := rfl\n\ndef yoneda_lemma : (yoneda_pairing C) ≅ (yoneda_evaluation C) := \n{ hom := \n { app := λ F x, ulift.up ((x.app F.2) (𝟙 F.2)),\n naturality' := begin intros X Y f, ext1, ext1, cases f, cases Y, cases X, dsimp at *, simp at *, \n erw [←functor_to_types.naturality, obj_map_id, functor_to_types.naturality, functor_to_types.map_id] end },\n inv := \n { app := λ F x, \n { app := λ X a, (F.1.map a) x.down,\n naturality' := begin intros X Y f, ext1, cases x, cases F, dsimp at *, erw [functor_to_types.map_comp], refl end },\n naturality' := begin intros X Y f, ext1, ext1, ext1, cases x, cases f, cases Y, cases X, \n dsimp at *, simp at *, erw [←functor_to_types.naturality, functor_to_types.map_comp] end },\n hom_inv_id' := begin ext1, ext1, ext1, ext1, cases X, dsimp at *, simp at *, \n erw [←functor_to_types.naturality, obj_map_id, functor_to_types.naturality, functor_to_types.map_id] end,\n inv_hom_id' := begin ext1, ext1, ext1, cases x, cases X, dsimp at *, erw [functor_to_types.map_id] end }.\n\nend category_theory", "meta": {"author": "khoek", "repo": "mathlib-tidy", "sha": "866afa6ab597c47f1b72e8fe2b82b97fff5b980f", "save_path": "github-repos/lean/khoek-mathlib-tidy", "path": "github-repos/lean/khoek-mathlib-tidy/mathlib-tidy-866afa6ab597c47f1b72e8fe2b82b97fff5b980f/category_theory/yoneda.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3960681520167195, "lm_q2_score": 0.04535258555427004, "lm_q1q2_score": 0.017962714749659905}} {"text": "/-\nFile: signature_recover_public_key_assert_nn_le_soundness.lean\n\nAutogenerated file.\n-/\nimport starkware.cairo.lean.semantics.soundness.hoare\nimport .signature_recover_public_key_code\nimport ..signature_recover_public_key_spec\nimport .signature_recover_public_key_assert_le_soundness\nopen tactic\n\nopen starkware.cairo.common.math\n\nvariables {F : Type} [field F] [decidable_eq F] [prelude_hyps F]\nvariable mem : F → F\nvariable σ : register_state F\n\n/- starkware.cairo.common.math.assert_nn_le autogenerated soundness theorem -/\n\ntheorem auto_sound_assert_nn_le\n -- arguments\n (range_check_ptr a b : F)\n -- code is in memory at σ.pc\n (h_mem : mem_at mem code_assert_nn_le σ.pc)\n -- all dependencies are in memory\n (h_mem_0 : mem_at mem code_assert_nn (σ.pc - 9))\n (h_mem_1 : mem_at mem code_assert_le (σ.pc - 5))\n -- input arguments on the stack\n (hin_range_check_ptr : range_check_ptr = mem (σ.fp - 5))\n (hin_a : a = mem (σ.fp - 4))\n (hin_b : b = mem (σ.fp - 3))\n -- conclusion\n : ensures_ret mem σ (λ κ τ,\n τ.ap = σ.ap + 14 ∧\n ∃ μ ≤ κ, rc_ensures mem (rc_bound F) μ (mem (σ.fp - 5)) (mem $ τ.ap - 1)\n (spec_assert_nn_le mem κ range_check_ptr a b (mem (τ.ap - 1)))) :=\nbegin\n apply ensures_of_ensuresb, intro νbound,\n have h_mem_rec := h_mem,\n unpack_memory code_assert_nn_le at h_mem with ⟨hpc0, hpc1, hpc2, hpc3, hpc4, hpc5, hpc6, hpc7, hpc8⟩,\n -- function call\n step_assert_eq hpc0 with arg0,\n step_assert_eq hpc1 with arg1,\n step_sub hpc2 (auto_sound_assert_nn mem _ range_check_ptr a _ _ _),\n { rw hpc3, norm_num2, exact h_mem_0 },\n { try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_a, hin_b] },\n try { arith_simps }, try { simp only [arg0, arg1] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } }, },\n { try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_a, hin_b] },\n try { arith_simps }, try { simp only [arg0, arg1] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } }, },\n intros κ_call4 ap4 h_call4,\n rcases h_call4 with ⟨h_call4_ap_offset, h_call4⟩,\n rcases h_call4 with ⟨rc_m4, rc_mle4, hl_range_check_ptr₁, h_call4⟩,\n generalize' hr_rev_range_check_ptr₁: mem (ap4 - 1) = range_check_ptr₁,\n have htv_range_check_ptr₁ := hr_rev_range_check_ptr₁.symm, clear hr_rev_range_check_ptr₁,\n try { simp only [arg0 ,arg1] at hl_range_check_ptr₁ },\n rw [←htv_range_check_ptr₁, ←hin_range_check_ptr] at hl_range_check_ptr₁,\n try { simp only [arg0 ,arg1] at h_call4 },\n rw [hin_range_check_ptr] at h_call4,\n clear arg0 arg1,\n -- function call\n step_assert_eq hpc4 with arg0,\n step_assert_eq hpc5 with arg1,\n step_sub hpc6 (auto_sound_assert_le mem _ range_check_ptr₁ a b _ _ _ _ _),\n { rw hpc7, norm_num2, exact h_mem_1 },\n { rw hpc7, norm_num2, exact h_mem_0 },\n { try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_a, hin_b, htv_range_check_ptr₁] },\n try { arith_simps }, try { simp only [arg0, arg1] },\n try { simp only [h_call4_ap_offset] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } }, },\n { try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_a, hin_b, htv_range_check_ptr₁] },\n try { arith_simps }, try { simp only [arg0, arg1] },\n try { simp only [h_call4_ap_offset] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } }, },\n { try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_a, hin_b, htv_range_check_ptr₁] },\n try { arith_simps }, try { simp only [arg0, arg1] },\n try { simp only [h_call4_ap_offset] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } }, },\n intros κ_call8 ap8 h_call8,\n rcases h_call8 with ⟨h_call8_ap_offset, h_call8⟩,\n rcases h_call8 with ⟨rc_m8, rc_mle8, hl_range_check_ptr₂, h_call8⟩,\n generalize' hr_rev_range_check_ptr₂: mem (ap8 - 1) = range_check_ptr₂,\n have htv_range_check_ptr₂ := hr_rev_range_check_ptr₂.symm, clear hr_rev_range_check_ptr₂,\n try { simp only [arg0 ,arg1] at hl_range_check_ptr₂ },\n rw [←htv_range_check_ptr₂, ←htv_range_check_ptr₁] at hl_range_check_ptr₂,\n try { simp only [arg0 ,arg1] at h_call8 },\n rw [←htv_range_check_ptr₁, hl_range_check_ptr₁, hin_range_check_ptr] at h_call8,\n clear arg0 arg1,\n -- return\n step_ret hpc8,\n -- finish\n step_done, use_only [rfl, rfl],\n split,\n { try { simp only [h_call4_ap_offset ,h_call8_ap_offset] },\n try { arith_simps }, try { refl } },\n -- range check condition\n use_only (rc_m4+rc_m8+0+0), split,\n linarith [rc_mle4, rc_mle8],\n split,\n { arith_simps,\n rw [←htv_range_check_ptr₂, hl_range_check_ptr₂, hl_range_check_ptr₁, hin_range_check_ptr],\n try { arith_simps, refl <|> norm_cast }, try { refl } },\n intro rc_h_range_check_ptr, repeat { rw [add_assoc] at rc_h_range_check_ptr },\n have rc_h_range_check_ptr' := range_checked_add_right rc_h_range_check_ptr,\n -- Final Proof\n -- user-provided reduction\n suffices auto_spec: auto_spec_assert_nn_le mem _ range_check_ptr a b _,\n { apply sound_assert_nn_le, apply auto_spec },\n -- prove the auto generated assertion\n dsimp [auto_spec_assert_nn_le],\n try { norm_num1 }, try { arith_simps },\n use_only [κ_call4],\n use_only [range_check_ptr₁],\n have rc_h_range_check_ptr₁ := range_checked_offset' rc_h_range_check_ptr,\n have rc_h_range_check_ptr₁' := range_checked_add_right rc_h_range_check_ptr₁, try { norm_cast at rc_h_range_check_ptr₁' },\n have spec4 := h_call4 rc_h_range_check_ptr',\n rw [←hin_range_check_ptr, ←htv_range_check_ptr₁] at spec4,\n try { dsimp at spec4, arith_simps at spec4 },\n use_only [spec4],\n use_only [κ_call8],\n use_only [range_check_ptr₂],\n have rc_h_range_check_ptr₂ := range_checked_offset' rc_h_range_check_ptr₁,\n have rc_h_range_check_ptr₂' := range_checked_add_right rc_h_range_check_ptr₂, try { norm_cast at rc_h_range_check_ptr₂' },\n have spec8 := h_call8 rc_h_range_check_ptr₁',\n rw [←hin_range_check_ptr, ←hl_range_check_ptr₁, ←htv_range_check_ptr₂] at spec8,\n try { dsimp at spec8, arith_simps at spec8 },\n use_only [spec8],\n try { split, linarith },\n try { ensures_simps; try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_a, hin_b, htv_range_check_ptr₁, htv_range_check_ptr₂] }, },\n try { simp only [h_call4_ap_offset, h_call8_ap_offset] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },\nend\n\n", "meta": {"author": "starkware-libs", "repo": "formal-proofs", "sha": "35613c65b6715601bbc0a550d52754f8e7d93e30", "save_path": "github-repos/lean/starkware-libs-formal-proofs", "path": "github-repos/lean/starkware-libs-formal-proofs/formal-proofs-35613c65b6715601bbc0a550d52754f8e7d93e30/src/starkware/cairo/common/cairo_secp/verification/verification/signature_recover_public_key_assert_nn_le_soundness.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4882833952958347, "lm_q2_score": 0.036769466207539105, "lm_q1q2_score": 0.017953919803032653}} {"text": "import .yul_ast\nimport .aux\n\nimport tactic.linarith\n\nimport data.finset.basic\nimport data.vector\nimport init.data.fin.ops\nimport init.data.list.basic\n\n\nset_option class.instance_max_depth 100\n\ndef FTContext := Identifier → option (ℕ × ℕ)\ndef empΓ : FTContext := λ_, none \n\ndef VarStore (vars : finset Identifier) := ∀ i : Identifier, (i ∈ vars) → Literal\ndef empStore : VarStore ∅\n | i i_in_emp := absurd i_in_emp (finset.not_mem_empty i)\n\nnamespace YulCommands\n\nvariable Γ : FTContext\n\ninductive IsInFor : Type\n| NestedInFor : IsInFor\n| NotNestedInFor : IsInFor\n\ninductive IsInFunc : Type\n| InFunc : IsInFunc\n| NotInFunc : IsInFunc\n\ninductive TermType : Type\n| BlockList : finset Identifier → finset Identifier → IsInFor → IsInFunc → TermType\n| CBlock : finset Identifier → IsInFor → IsInFunc → TermType\n| SwitchBody : finset Identifier → IsInFor → IsInFunc → TermType\n| CExpr : finset Identifier → ℕ → TermType\n| CStatement : finset Identifier → finset Identifier → IsInFor → IsInFunc → TermType\n\nopen IsInFor\nopen IsInFunc\nopen TermType\n\ninductive YulTerm : TermType → Type\n| EmpCBlock : \n ∀{vars : finset Identifier} {b : IsInFor} {b' : IsInFunc}, \n YulTerm (BlockList vars vars b b')\n| SeqCBlock : \n ∀ {vars : finset Identifier} (vars' : finset Identifier) \n {vars'' : finset Identifier} {b : IsInFor} {b' : IsInFunc}, \n YulTerm (CStatement vars vars' b b') -> \n YulTerm (BlockList vars' vars'' b b') → \n YulTerm (BlockList vars vars'' b b')\n\n| NestedScope : \n ∀ {vars : finset Identifier} (inner_vars inner_vars' : finset Identifier) \n {b : IsInFor} {b' : IsInFunc}, \n VarStore inner_vars → \n YulTerm (BlockList (inner_vars ∪ vars) (inner_vars' ∪ vars) b b') → \n YulTerm (CBlock vars b b')\n\n| CCase : \n ∀ {vars : finset Identifier} {b : IsInFor} {b' : IsInFunc},\n Literal → YulTerm (CBlock vars b b') → YulTerm (SwitchBody vars b b') → \n YulTerm (SwitchBody vars b b')\n| CDefault : \n ∀ {vars : finset Identifier} {b : IsInFor} {b' : IsInFunc},\n YulTerm (CBlock vars b b') → YulTerm (SwitchBody vars b b')\n| CNone : \n ∀ {vars : finset Identifier} {b : IsInFor} {b' : IsInFunc},\n YulTerm (SwitchBody vars b b')\n\n| CFunctionCall : \n ∀ {vars : finset Identifier} \n (f_id : Identifier) (n : ℕ) {m : ℕ}, \n (Γ f_id = some (n,m)) → \n (fin n → YulTerm (CExpr vars 1)) →\n YulTerm (CExpr vars m)\n| CId : \n ∀ {vars : finset Identifier} (id : Identifier), \n id ∈ vars → YulTerm (CExpr vars 1)\n| CLit : \n ∀ {vars : finset Identifier}, \n Literal → YulTerm (CExpr vars 1)\n| Scope : ∀ {vars_outer : finset Identifier} (vars_inner vars_fin : finset Identifier) \n {n : ℕ} (ret_vars : vector Identifier n), \n VarStore (vars_inner ∪ (tofinset' ret_vars)) →\n YulTerm (BlockList (vars_inner ∪ (tofinset' ret_vars)) (vars_fin ∪ (tofinset' ret_vars)) NotNestedInFor InFunc) → \n YulTerm (CExpr vars_outer n)\n| Result : \n ∀ {vars : finset Identifier} {n : ℕ},\n vector Literal n → YulTerm (CExpr vars n)\n \n| CBlock : \n ∀ {vars : finset Identifier} {b : IsInFor} {b' : IsInFunc}, \n YulTerm (CBlock vars b b') → YulTerm (CStatement vars vars b b')\n -- Function definitions already parsed into FTContext.\n| CVariableDeclarationAss : \n ∀ {vars : finset Identifier} (n : ℕ) \n (new_vars : fin n -> Identifier) {b : IsInFor} {b' : IsInFunc},\n YulTerm (CExpr vars n) → \n YulTerm (CStatement vars (vars ∪ (tofinset new_vars)) b b')\n| CVariableDeclaration : \n ∀ {vars : finset Identifier} (n : ℕ) \n (new_vars : fin n -> Identifier) {b : IsInFor} {b' : IsInFunc},\n YulTerm (CStatement vars (vars ∪ (tofinset new_vars)) b b')\n| CAssignment :\n ∀ {vars : finset Identifier} (n : ℕ) \n (ids : fin n -> Identifier) {b : IsInFor} {b' : IsInFunc},\n tofinset ids ⊆ vars → YulTerm (CExpr vars n) → \n YulTerm (CStatement vars vars b b')\n| CIf : \n ∀ {vars : finset Identifier} {b : IsInFor} {b' : IsInFunc}, \n YulTerm (CExpr vars 1) → YulTerm (CBlock vars b b') → \n YulTerm (CStatement vars vars b b')\n| CExpressionStatement : \n ∀ {vars : finset Identifier} {b : IsInFor} {b' : IsInFunc}, \n YulTerm (CExpr vars 0) -> YulTerm (CStatement vars vars b b')\n| CSwitch : ∀ {vars : finset Identifier} {b : IsInFor} {b' : IsInFunc}, \n YulTerm (CExpr vars 1) → \n YulTerm (SwitchBody vars b b') → \n YulTerm (CStatement vars vars b b')\n| CFor : \n ∀ {vars : finset Identifier} (inner_vars inner_vars' inner_vars'' : finset Identifier)\n {b : IsInFor} {b' : IsInFunc}, \n YulTerm (BlockList vars (vars ∪ inner_vars) NotNestedInFor b') → \n YulTerm (CExpr (vars ∪ inner_vars) 1) → \n YulTerm (BlockList (vars ∪ inner_vars) (vars ∪ inner_vars') NestedInFor b') → \n YulTerm (BlockList (vars ∪ inner_vars') (vars ∪ inner_vars'') NotNestedInFor b') → \n YulTerm (CStatement vars vars b b')\n| CBreak : \n ∀ {vars : finset Identifier} {b' : IsInFunc}, \n YulTerm (CStatement vars vars NestedInFor b')\n| CContinue : \n ∀ {vars : finset Identifier} {b' : IsInFunc}, \n YulTerm (CStatement vars vars NestedInFor b')\n| CLeave : \n ∀ {vars : finset Identifier} {b : IsInFor}, \n YulTerm (CStatement vars vars b InFunc)\n| ForExecInit :\n ∀ {vars : finset Identifier} (curr_inner_vars inner_vars inner_vars' inner_vars'' : finset Identifier) \n {b : IsInFor} {b' : IsInFunc}, \n VarStore curr_inner_vars →\n YulTerm (CExpr (vars ∪ inner_vars) 1) → \n YulTerm (BlockList (vars ∪ inner_vars) (vars ∪ inner_vars') NestedInFor b') → \n YulTerm (BlockList (vars ∪ inner_vars') (vars ∪ inner_vars'') NotNestedInFor b') →\n YulTerm (BlockList (vars ∪ curr_inner_vars) (vars ∪ inner_vars) NotNestedInFor b') →\n YulTerm (CStatement vars vars b b')\n| ForCheckCond : \n ∀ {vars : finset Identifier} (inner_vars inner_vars' inner_vars'' : finset Identifier) \n {b : IsInFor} {b' : IsInFunc}, \n VarStore inner_vars →\n YulTerm (CExpr (vars ∪ inner_vars) 1) → \n YulTerm (BlockList (vars ∪ inner_vars) (vars ∪ inner_vars') NestedInFor b') → \n YulTerm (BlockList (vars ∪ inner_vars') (vars ∪ inner_vars'') NotNestedInFor b') →\n YulTerm (CExpr (vars ∪ inner_vars) 1) →\n YulTerm (CStatement vars vars b b')\n| ForExecBody : \n ∀ {vars : finset Identifier} (curr_inner_vars inner_vars inner_vars' inner_vars'' : finset Identifier) \n {b : IsInFor} {b' : IsInFunc}, \n VarStore curr_inner_vars →\n vars ∪ inner_vars ⊆ vars ∪ curr_inner_vars →\n YulTerm (CExpr (vars ∪ inner_vars) 1) → \n YulTerm (BlockList (vars ∪ inner_vars) (vars ∪ inner_vars') NestedInFor b') → \n YulTerm (BlockList (vars ∪ inner_vars') (vars ∪ inner_vars'') NotNestedInFor b') →\n YulTerm (BlockList (vars ∪ curr_inner_vars) (vars ∪ inner_vars') NestedInFor b') →\n YulTerm (CStatement vars vars b b')\n| ForExecPost : \n ∀ {vars : finset Identifier} (curr_inner_vars inner_vars inner_vars' inner_vars'' : finset Identifier) \n {b : IsInFor} {b' : IsInFunc}, \n VarStore curr_inner_vars →\n YulTerm (CExpr (vars ∪ inner_vars) 1) → \n YulTerm (BlockList (vars ∪ inner_vars) (vars ∪ inner_vars') NestedInFor b') → \n YulTerm (BlockList (vars ∪ inner_vars') (vars ∪ inner_vars'') NotNestedInFor b') →\n YulTerm (BlockList (vars ∪ curr_inner_vars) (vars ∪ inner_vars'') NotNestedInFor b') →\n YulTerm (CStatement vars vars b b')\n| Skip : \n ∀ {vars : finset Identifier} {b : IsInFor} {b' : IsInFunc}, \n YulTerm (CStatement vars vars b b')\n -- ForCheckCond, ForExecbody and Skip not in Yul specification, added for small step semantics.\n\nopen YulTerm\n\ndef getVariableUpdate : ∀ {t : TermType} , YulTerm Γ t → option (finset Identifier × finset Identifier)\n| (BlockList vars vars' _ _) _ := some (vars, vars') \n| (CBlock _ _ _) _ := none\n| (SwitchBody _ _ _) _ := none\n| (CExpr _ _) _ := none\n| (CStatement vars vars' _ _) _ := some (vars, vars')\n\nlemma term_scope_monotonic : \n ∀ {t : TermType} (term : YulTerm Γ t) (vars vars' : finset Identifier),\n getVariableUpdate Γ term = some (vars, vars') → vars ⊆ vars' :=\n begin\n intros ttype t,\n induction t,\n\n -- EmpCBlock\n intros vars vars' is_var_update i,\n intro i_in_vars,\n rw getVariableUpdate at is_var_update,\n injection is_var_update with is_var_update,\n injection is_var_update with vars_eq_tvars tvars_eq_tvars,\n rw [←tvars_eq_tvars, vars_eq_tvars],\n exact i_in_vars,\n\n -- SeqCBlock\n intros vars vars' is_var_update i,\n intro i_in_vars,\n rw getVariableUpdate at is_var_update,\n injection is_var_update with is_var_update,\n injection is_var_update with vars_eq_tvars tvars''_eq_vars',\n rw vars_eq_tvars at t_ᾰ,\n have int₁ := t_ih_ᾰ vars t_vars' _ i_in_vars,\n rw tvars''_eq_vars' at t_ᾰ_1,\n have int₂ := t_ih_ᾰ_1 t_vars' vars' _ int₁,\n exact int₂,\n rw getVariableUpdate,\n injection is_var_update with _ tvars''_eq_vars',\n rw tvars''_eq_vars',\n rw getVariableUpdate,\n rw vars_eq_tvars,\n\n -- Block, SwitchBody & Expr\n repeat {\n intros vars vars',\n intro f,\n rw getVariableUpdate at f,\n exfalso,\n exact option.some_ne_none (vars, vars') (eq.symm f),\n },\n\n -- CStatements that do not bring new variables into scope.\n repeat {\n intros vars vars',\n intro is_var_update,\n rw getVariableUpdate at is_var_update,\n injection is_var_update with is_var_update,\n injection is_var_update with vars_eq_tvars tvars_eq_vars',\n rw [←tvars_eq_vars', vars_eq_tvars],\n exact finset.subset.refl vars,\n },\n\n -- CVariableDeclaration, CVariableDeclarationAss\n repeat {\n intros vars vars',\n intro is_var_update,\n rw getVariableUpdate at is_var_update,\n injection is_var_update with is_var_update,\n injection is_var_update with vars_eq eq_vars',\n rw [←vars_eq,←eq_vars'],\n exact finset.subset_union_left _ _,\n },\n\n end \n\ndef frame_TermType : TermType → finset Identifier → TermType\n| (BlockList vars vars' b b') fvars := \n BlockList (vars ∪ fvars) (vars' ∪ fvars) b b'\n| (CBlock vars b b') fvars := CBlock (vars ∪ fvars) b b'\n| (SwitchBody vars b b') fvars := SwitchBody (vars ∪ fvars) b b'\n| (CExpr vars n) fvars := CExpr (vars ∪ fvars) n\n| (CStatement vars vars' b b') fvars := \n CStatement (vars ∪ fvars) (vars' ∪ fvars) b b'\n\nlemma frame_lemma : \n ∀ s₁ s₂ s₃ : finset Identifier, \n s₁ ∪ s₂ ∪ s₃ = s₁ ∪ s₃ ∪ s₂ :=\n begin\n intros s₁ s₂ s₃,\n rw (finset.union_assoc s₁ s₂ s₃),\n rw (finset.union_assoc s₁ s₃ s₂),\n rw (finset.union_comm s₂ s₃),\n end\n\ndef frame : \n ∀ {t : TermType} (fvars : finset Identifier), \n YulTerm Γ t → YulTerm Γ (frame_TermType t fvars)\n| (BlockList _ _ _ _) fvars EmpCBlock := EmpCBlock\n| (BlockList _ _ _ _) fvars (SeqCBlock vars' cstmnt cblklst') :=\n SeqCBlock (vars' ∪ fvars) (frame fvars cstmnt) (frame fvars cblklst')\n| (CBlock vars b b') fvars (NestedScope inner_vars inner_vars' σ blklst) :=\n let inner_vars_eq:= finset.union_assoc inner_vars vars fvars,\n inner_vars'_eq := finset.union_assoc inner_vars' vars fvars,\n cast (cblklst : YulTerm Γ (BlockList((inner_vars ∪ vars) ∪ fvars) ((inner_vars' ∪ vars) ∪ fvars) b b')) : \n YulTerm Γ (BlockList (inner_vars ∪ (vars ∪ fvars)) (inner_vars' ∪ (vars ∪ fvars)) b b') :=\n eq.rec (eq.rec cblklst inner_vars_eq) inner_vars'_eq\n in NestedScope inner_vars inner_vars' σ (cast $ frame fvars blklst)\n| (SwitchBody _ _ _) fvars (CCase lit blk swtchbody) := \n CCase lit (frame fvars blk) (frame fvars swtchbody)\n| (SwitchBody _ _ _) fvars (CDefault blk) :=\n CDefault (frame fvars blk)\n| (SwitchBody _ _ _) fvars CNone :=\n CNone\n| (CExpr vars m) fvars (CFunctionCall f_id n p args) :=\n CFunctionCall f_id n p (λi, frame fvars (args i))\n| (CExpr vars 1) fvars (CId i i_in_vars) :=\n CId i (finset.mem_of_subset (finset.subset_union_left vars fvars) i_in_vars)\n| (CExpr _ 1) fvars (CLit lit) := CLit lit\n| (CExpr _ _) fvars (Scope vars_inner vars_inner' ret_vars σ stmnt) :=\n Scope vars_inner vars_inner' ret_vars σ stmnt\n| (CExpr _ _) fvars (Result res_vec) :=\n Result res_vec\n| (CStatement _ _ _ _) fvars (CBlock blk) := \n CBlock (frame fvars blk)\n| (CStatement vars _ b b') fvars (CVariableDeclarationAss n new_vars cexpr) := \n let cast (cstmnt : YulTerm Γ (CStatement (vars ∪ fvars) (vars ∪ fvars ∪ tofinset new_vars) b b'))\n : YulTerm Γ (CStatement (vars ∪ fvars) (vars ∪ tofinset new_vars ∪ fvars) b b') := \n eq.rec cstmnt (finset.union_right_comm vars fvars (tofinset new_vars))\n in cast $ CVariableDeclarationAss n new_vars (frame fvars cexpr)\n| (CStatement vars _ b b') fvars (CVariableDeclaration n new_vars) :=\n let cast (cstmnt : YulTerm Γ (CStatement (vars ∪ fvars) (vars ∪ fvars ∪ tofinset new_vars) b b'))\n : YulTerm Γ (CStatement (vars ∪ fvars) (vars ∪ tofinset new_vars ∪ fvars) b b') := \n eq.rec cstmnt (finset.union_right_comm vars fvars (tofinset new_vars))\n in cast $ CVariableDeclaration n new_vars\n| (CStatement vars _ b b') fvars (CAssignment n ids in_scope cexpr) :=\n CAssignment n ids\n (has_subset.subset.trans in_scope (finset.subset_union_left vars fvars)) \n (frame fvars cexpr)\n| (CStatement vars _ b b') fvars (CIf cexpr blk) :=\n CIf (frame fvars cexpr) (frame fvars blk)\n| (CStatement vars _ b b') fvars (CExpressionStatement cexpr) :=\n CExpressionStatement (frame fvars cexpr)\n| (CStatement vars _ b b') fvars (CSwitch cexpr swtchbody) :=\n CSwitch (frame fvars cexpr) (frame fvars swtchbody)\n| (CStatement vars _ b b') fvars (CFor inner_vars inner_vars' inner_vars'' init cond body post) :=\n let init_framed : YulTerm Γ (BlockList (vars ∪ fvars) (vars ∪ fvars ∪ inner_vars) NotNestedInFor b') := \n begin\n have init_framed := frame fvars init,\n rw frame_TermType at init_framed,\n apply eq.rec init_framed,\n rw frame_lemma,\n end,\n cond_framed : YulTerm Γ (CExpr (vars ∪ fvars ∪ inner_vars) 1) := \n begin\n have cond_framed := frame fvars cond,\n rw frame_TermType at cond_framed,\n apply eq.rec cond_framed,\n rw frame_lemma,\n end,\n body_framed : YulTerm Γ (BlockList (vars ∪ fvars ∪ inner_vars) (vars ∪ fvars ∪ inner_vars') NestedInFor b') :=\n begin\n have body_framed := frame fvars body,\n rw frame_TermType at body_framed,\n apply eq.rec body_framed,\n rw (frame_lemma vars inner_vars fvars),\n rw (frame_lemma vars inner_vars' fvars),\n end,\n post_framed : YulTerm Γ (BlockList (vars ∪ fvars ∪ inner_vars') (vars ∪ fvars ∪ inner_vars'') NotNestedInFor b') := \n begin\n have post_framed := frame fvars post,\n rw frame_TermType at post_framed,\n apply eq.rec post_framed,\n rw (frame_lemma vars inner_vars' fvars),\n rw (frame_lemma vars inner_vars'' fvars),\n end\n in CFor inner_vars inner_vars' inner_vars''\n init_framed cond_framed body_framed post_framed\n| (CStatement vars _ b b') fvars CBreak := CBreak\n| (CStatement vars _ b b') fvars CContinue := CContinue\n| (CStatement vars _ b b') fvars CLeave := CLeave\n| (CStatement vars _ b b') fvars \n (ForExecInit curr_inner_vars inner_vars inner_vars' inner_vars'' σ cond loop post eval_init) :=\n let cond_framed : YulTerm Γ (CExpr (vars ∪ fvars ∪ inner_vars) 1) := \n begin\n have cond_framed := frame fvars cond,\n rw frame_TermType at cond_framed,\n apply eq.rec cond_framed,\n rw frame_lemma,\n end,\n loop_framed : YulTerm Γ (BlockList (vars ∪ fvars ∪ inner_vars) (vars ∪ fvars ∪ inner_vars') NestedInFor b') := \n begin\n have loop_framed := frame fvars loop,\n rw frame_TermType at loop_framed,\n apply eq.rec loop_framed,\n rw (frame_lemma vars inner_vars fvars),\n rw (frame_lemma vars inner_vars' fvars),\n end,\n post_framed : YulTerm Γ (BlockList (vars ∪ fvars ∪ inner_vars') (vars ∪ fvars ∪ inner_vars'') NotNestedInFor b') := \n begin\n have post_framed := frame fvars post,\n rw frame_TermType at post_framed,\n apply eq.rec post_framed,\n rw (frame_lemma vars inner_vars' fvars),\n rw (frame_lemma vars inner_vars'' fvars),\n end,\n eval_init_framed : YulTerm Γ (BlockList (vars ∪ fvars ∪ curr_inner_vars) (vars ∪ fvars ∪ inner_vars) NotNestedInFor b') :=\n begin\n have eval_init_framed := frame fvars eval_init,\n rw frame_TermType at eval_init_framed,\n apply eq.rec eval_init_framed,\n rw (frame_lemma vars curr_inner_vars fvars),\n rw (frame_lemma vars inner_vars fvars),\n end\n in ForExecInit curr_inner_vars inner_vars inner_vars' inner_vars'' σ\n cond_framed loop_framed post_framed eval_init_framed\n| (CStatement vars _ b b') fvars \n (ForCheckCond inner_vars inner_vars' inner_vars'' σ cond loop post eval_cond) :=\n let cond_framed : YulTerm Γ (CExpr (vars ∪ fvars ∪ inner_vars) 1) := \n begin\n have cond_framed := frame fvars cond,\n rw frame_TermType at cond_framed,\n apply eq.rec cond_framed,\n rw frame_lemma,\n end,\n loop_framed : YulTerm Γ (BlockList (vars ∪ fvars ∪ inner_vars) (vars ∪ fvars ∪ inner_vars') NestedInFor b') := \n begin\n have loop_framed := frame fvars loop,\n rw frame_TermType at loop_framed,\n apply eq.rec loop_framed,\n rw (frame_lemma vars inner_vars fvars),\n rw (frame_lemma vars inner_vars' fvars),\n end,\n post_framed : YulTerm Γ (BlockList (vars ∪ fvars ∪ inner_vars') (vars ∪ fvars ∪ inner_vars'') NotNestedInFor b') := \n begin\n have post_framed := frame fvars post,\n rw frame_TermType at post_framed,\n apply eq.rec post_framed,\n rw (frame_lemma vars inner_vars' fvars),\n rw (frame_lemma vars inner_vars'' fvars),\n end,\n eval_cond_framed : YulTerm Γ (CExpr (vars ∪ fvars ∪ inner_vars) 1) :=\n begin\n have eval_cond_framed := frame fvars eval_cond,\n rw frame_TermType at eval_cond_framed,\n apply eq.rec eval_cond_framed,\n rw (frame_lemma vars inner_vars fvars),\n end\n in ForCheckCond inner_vars inner_vars' inner_vars'' σ\n cond_framed loop_framed post_framed eval_cond_framed\n| (CStatement vars _ b b') fvars \n (ForExecBody curr_inner_vars inner_vars inner_vars' inner_vars'' σ p cond loop post eval_loop) :=\n let cond_framed : YulTerm Γ (CExpr (vars ∪ fvars ∪ inner_vars) 1) := \n begin\n have cond_framed := frame fvars cond,\n rw frame_TermType at cond_framed,\n apply eq.rec cond_framed,\n rw frame_lemma,\n end,\n loop_framed : YulTerm Γ (BlockList (vars ∪ fvars ∪ inner_vars) (vars ∪ fvars ∪ inner_vars') NestedInFor b') := \n begin\n have loop_framed := frame fvars loop,\n rw frame_TermType at loop_framed,\n apply eq.rec loop_framed,\n rw (frame_lemma vars inner_vars fvars),\n rw (frame_lemma vars inner_vars' fvars),\n end,\n post_framed : YulTerm Γ (BlockList (vars ∪ fvars ∪ inner_vars') (vars ∪ fvars ∪ inner_vars'') NotNestedInFor b') := \n begin\n have post_framed := frame fvars post,\n rw frame_TermType at post_framed,\n apply eq.rec post_framed,\n rw (frame_lemma vars inner_vars' fvars),\n rw (frame_lemma vars inner_vars'' fvars),\n end,\n eval_loop_framed :YulTerm Γ (BlockList (vars ∪ fvars ∪ curr_inner_vars) (vars ∪ fvars ∪ inner_vars') NestedInFor b') :=\n begin\n have eval_loop_framed := frame fvars eval_loop,\n rw frame_TermType at eval_loop_framed,\n apply eq.rec eval_loop_framed,\n rw (frame_lemma vars inner_vars' fvars),\n rw (frame_lemma vars curr_inner_vars fvars),\n end,\n p' : vars ∪ fvars ∪ inner_vars ⊆ vars ∪ fvars ∪ curr_inner_vars :=\n begin\n intros i i_in,\n repeat {\n rw finset.mem_union at i_in,\n },\n repeat {\n rw finset.mem_union,\n },\n cases i_in with x y,\n exact or.inl x,\n cases finset.mem_union.1 (p (finset.mem_union_right vars y)) with h,\n exact or.inl (or.inl h),\n exact or.inr h,\n end\n in ForExecBody curr_inner_vars inner_vars inner_vars' inner_vars'' σ p'\n cond_framed loop_framed post_framed eval_loop_framed\n| (CStatement vars _ b b') fvars \n (ForExecPost curr_inner_vars inner_vars inner_vars' inner_vars'' σ cond loop post eval_post) :=\n let cond_framed : YulTerm Γ (CExpr (vars ∪ fvars ∪ inner_vars) 1) := \n begin\n have cond_framed := frame fvars cond,\n rw frame_TermType at cond_framed,\n apply eq.rec cond_framed,\n rw frame_lemma,\n end,\n loop_framed : YulTerm Γ (BlockList (vars ∪ fvars ∪ inner_vars) (vars ∪ fvars ∪ inner_vars') NestedInFor b') := \n begin\n have loop_framed := frame fvars loop,\n rw frame_TermType at loop_framed,\n apply eq.rec loop_framed,\n rw (frame_lemma vars inner_vars fvars),\n rw (frame_lemma vars inner_vars' fvars),\n end,\n post_framed : YulTerm Γ (BlockList (vars ∪ fvars ∪ inner_vars') (vars ∪ fvars ∪ inner_vars'') NotNestedInFor b') := \n begin\n have post_framed := frame fvars post,\n rw frame_TermType at post_framed,\n apply eq.rec post_framed,\n rw (frame_lemma vars inner_vars' fvars),\n rw (frame_lemma vars inner_vars'' fvars),\n end,\n eval_post_framed : YulTerm Γ (BlockList (vars ∪ fvars ∪ curr_inner_vars) (vars ∪ fvars ∪ inner_vars'') NotNestedInFor b') :=\n begin\n have eval_post_framed := frame fvars eval_post,\n rw frame_TermType at eval_post_framed,\n apply eq.rec eval_post_framed,\n rw (frame_lemma vars inner_vars'' fvars),\n rw (frame_lemma vars curr_inner_vars fvars),\n end\n in ForExecPost curr_inner_vars inner_vars inner_vars' inner_vars'' σ\n cond_framed loop_framed post_framed eval_post_framed\n| (CStatement vars _ b b') fvars Skip := Skip \n\ndef are_args_reduced : \n ∀ {vars : finset Identifier} {n : ℕ}, \n vector (YulTerm Γ (CExpr vars 1)) n → Prop\n| _ 0 _ := true\n| vars (nat.succ n) ⟨ (Result _) :: cexprs, p ⟩ := \n are_args_reduced \n (⟨ \n cexprs, \n by {\n rw list.length at p,\n exact (nat.add_right_cancel p),\n }\n ⟩ : vector (YulTerm Γ (CExpr vars 1)) n)\n| _ (nat.succ n) ⟨ _ :: _, _ ⟩ := false\n\ninstance (vars : finset Identifier) (n : ℕ) \n (cexprs : vector (YulTerm Γ (CExpr vars 1)) n) : \n decidable (are_args_reduced Γ cexprs) :=\n begin\n induction n,\n rw are_args_reduced,\n apply decidable.is_true,\n trivial,\n cases cexprs,\n cases cexprs_val,\n exfalso,\n exact list.ne_nil_of_length_eq_succ cexprs_property (eq.refl list.nil),\n cases cexprs_val_hd,\n repeat {\n rw are_args_reduced,\n apply decidable.is_false,\n trivial,\n },\n rw are_args_reduced,\n exact n_ih ⟨ cexprs_val_tl, _ ⟩,\n end\n\nlemma nil_reduced : \n ∀ {Γ : FTContext} {vars : finset Identifier}, \n @are_args_reduced Γ vars 0 vector.nil :=\n begin\n intros Γ vars,\n rw are_args_reduced,\n trivial,\n end \n\ndef is_result : \n ∀ {vars : finset Identifier} {n : ℕ}, \n YulTerm Γ (CExpr vars n) -> Prop\n| _ _ (Result _) := true\n| _ _ (CLit _) := false\n| _ _ (CId _ _) := false\n| _ _ (CFunctionCall _ _ _ _) := false\n| _ _ (Scope _ _ _ _ _) := false\n\ninstance \n (vars : finset Identifier) (n : ℕ) \n (cexpr : YulTerm Γ (CExpr vars n)) : decidable (is_result Γ cexpr) :=\n begin\n cases cexpr,\n repeat {\n rw is_result,\n apply decidable.is_false,\n trivial,\n },\n rw is_result,\n apply decidable.is_true,\n trivial,\n end\n\ndef is_skip : \n ∀ {vars vars': finset Identifier} {b : IsInFor} {b' : IsInFunc}, \n YulTerm Γ (CStatement vars vars' b b') -> Prop\n| _ _ _ _ Skip := true\n| _ _ _ _ (CBlock _) := false\n| _ _ _ _ (CVariableDeclarationAss _ _ _) := false\n| _ _ _ _ (CVariableDeclaration _ _) := false\n| _ _ _ _ (CAssignment _ _ _ _) := false\n| _ _ _ _ (CIf _ _) := false\n| _ _ _ _ (CExpressionStatement _) := false\n| _ _ _ _ (CSwitch _ _) := false\n| _ _ _ _ (CFor _ _ _ _ _ _ _) := false\n| _ _ _ _ CBreak := false\n| _ _ _ _ CContinue := false\n| _ _ _ _ CLeave := false\n| _ _ _ _ (ForExecInit _ _ _ _ _ _ _ _ _) := false\n| _ _ _ _ (ForCheckCond _ _ _ _ _ _ _ _) := false\n| _ _ _ _ (ForExecBody _ _ _ _ _ _ _ _ _ _) := false\n| _ _ _ _ (ForExecPost _ _ _ _ _ _ _ _ _) := false\n\nlemma is_skip_imp_vars_eq_vars' :\n ∀ {vars vars' : finset Identifier} {b : IsInFor} {b' : IsInFunc} \n {cstmnt : YulTerm Γ (CStatement vars vars' b b')},\n is_skip Γ cstmnt → vars' = vars :=\n begin\n intros vars vars' b b' cstmnt cstmnt_is_skip,\n cases cstmnt,\n repeat {\n rw is_skip at cstmnt_is_skip,\n },\n repeat {\n exfalso,\n exact cstmnt_is_skip,\n },\n end\n\ninstance is_skip_decidable {vars vars' : finset Identifier} {b : IsInFor} {b' : IsInFunc}\n {stmnt : YulTerm Γ (CStatement vars vars' b b')} : decidable (is_skip Γ stmnt) :=\n begin\n cases stmnt,\n repeat{\n rw is_skip,\n apply decidable.is_false,\n trivial,\n },\n rw is_skip,\n apply decidable.is_true,\n trivial,\n end\n\ndef is_empcblock : \n ∀ {vars vars' : finset Identifier} {b : IsInFor} {b' : IsInFunc}, \n YulTerm Γ (BlockList vars vars' b b') → Prop \n| _ _ _ _ EmpCBlock := true\n| _ _ _ _ _ := false\n\ninstance empcblock_decidable \n {vars vars' : finset Identifier} {b : IsInFor} {b' : IsInFunc}\n {blklst : YulTerm Γ (BlockList vars vars' b b')} : \n decidable (is_empcblock Γ blklst) :=\n begin\n cases blklst,\n rw is_empcblock,\n apply decidable.is_true,\n trivial,\n rw is_empcblock,\n apply decidable.is_false,\n trivial,\n end\n\nlemma is_empcblock_imp_vars_eq_vars' : \n ∀ {vars vars' : finset Identifier} {b : IsInFor} \n {b' : IsInFunc} {cblk : YulTerm Γ (BlockList vars vars' b b')},\n is_empcblock Γ cblk → vars = vars' :=\n begin\n intros vars vars' b b' cblk cblk_is_empcblock,\n cases cblk,\n refl,\n exfalso,\n rw is_empcblock at cblk_is_empcblock,\n exact cblk_is_empcblock,\n end \n\n\n\ndef is_empblock : \n ∀ {vars : finset Identifier} {b : IsInFor} {b' : IsInFunc}, \n YulTerm Γ (CBlock vars b b') → Prop\n| _ _ _ (NestedScope _ _ _ blklst) := is_empcblock Γ blklst\n\ninstance (vars : finset Identifier) (b : IsInFor) (b' : IsInFunc)\n (blk : YulTerm Γ (CBlock vars b b')) : decidable (is_empblock Γ blk) :=\n begin\n cases blk,\n rw is_empblock,\n exact YulCommands.empcblock_decidable Γ,\n end\n\ndef to_literal : ∀ {vars : finset Identifier} {n : ℕ}\n (cexpr : YulTerm Γ (CExpr vars n)), is_result Γ cexpr → vector Literal n\n | _ _ cexpr@(CFunctionCall _ _ _ _) cexpr_is_res := \n let cexpr_n_is_res : ¬ is_result Γ cexpr :=\n begin\n rw is_result,\n intro f,\n exact f,\n end\n in absurd cexpr_is_res cexpr_n_is_res\n | _ _ cexpr@(CId _ _) cexpr_is_res := \n let cexpr_n_is_res : ¬ is_result Γ cexpr :=\n begin\n rw is_result,\n intro f,\n exact f,\n end\n in absurd cexpr_is_res cexpr_n_is_res\n | _ _ cexpr@(CLit l) cexpr_is_res := \n let cexpr_n_is_res : ¬ is_result Γ cexpr :=\n begin\n rw is_result,\n intro f,\n exact f,\n end\n in absurd cexpr_is_res cexpr_n_is_res\n | _ _ cexpr@(Scope _ _ _ _ _) cexpr_is_res := \n let cexpr_n_is_res : ¬ is_result Γ cexpr :=\n begin\n rw is_result,\n intro f,\n exact f,\n end\n in absurd cexpr_is_res cexpr_n_is_res\n | _ _ cexpr@(Result res_vec) _ := res_vec\n\ndef getCase : \n ∀ {vars : finset Identifier} {b : IsInFor} {b' : IsInFunc}, \n Literal -> YulTerm Γ (SwitchBody vars b b') → YulTerm Γ (CBlock vars b b')\n| _ _ _ _ CNone := NestedScope ∅ ∅ empStore EmpCBlock\n| _ _ _ _ (CDefault blk) := blk\n| _ _ _ l (CCase lit blk swtchbody') :=\n if l = lit \n then blk\n else getCase l swtchbody'\n\nlemma reduced_and_n_tail_reduced_imp_n_lit\n {vars : finset Identifier}\n (cexpr : YulTerm Γ (CExpr vars 1))\n {n : ℕ}\n (cexprs : vector (YulTerm Γ (CExpr vars 1)) n) :\n ¬ (are_args_reduced Γ (vector.cons cexpr cexprs)) → are_args_reduced Γ cexprs → \n ¬ is_result Γ cexpr :=\n begin\n intros full_not_red tail_red,\n cases cexpr,\n repeat {\n rw is_result,\n intro f,\n exact f,\n },\n cases cexprs,\n exfalso,\n rw vector.cons at full_not_red,\n rw are_args_reduced at full_not_red,\n exact full_not_red(tail_red),\n end \n\ndef get_lits : \n ∀ {vars : finset Identifier} {n : ℕ} \n (arg_cexprs : vector (YulTerm Γ (CExpr vars 1)) n),\n are_args_reduced Γ arg_cexprs → vector Literal n \n| _ 0 _ _ := vector.nil\n| vars (nat.succ n) ⟨(Result lit) :: lit_cexprs, len_p⟩ p :=\n let lit_cexprs_vec' : vector (YulTerm Γ (CExpr vars 1)) n := \n ⟨ lit_cexprs, \n by {\n rw list.length at len_p,\n exact (nat.add_right_cancel len_p),\n }\n ⟩\n in vector.cons lit.head $ \n get_lits lit_cexprs_vec' $\n by {\n rw are_args_reduced at p,\n exact p,\n }\n\nend YulCommands", "meta": {"author": "NethermindEth", "repo": "Yul-Specification", "sha": "35b8620b920758684f13810859ec48c55544a8fe", "save_path": "github-repos/lean/NethermindEth-Yul-Specification", "path": "github-repos/lean/NethermindEth-Yul-Specification/Yul-Specification-35b8620b920758684f13810859ec48c55544a8fe/yul_cmd.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48047867804790706, "lm_q2_score": 0.03732688613936197, "lm_q1q2_score": 0.017934772907885383}} {"text": "/-\nCopyright (c) 2018 Simon Hudon. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Simon Hudon, Patrick Massot\n-/\nimport algebra.group.pi\nimport group_theory.group_action.defs\n\n/-!\n# Pi instances for multiplicative actions\n\nThis file defines instances for mul_action and related structures on Pi types.\n\n## See also\n\n* `group_theory.group_action.prod`\n* `group_theory.group_action.sigma`\n* `group_theory.group_action.sum`\n-/\n\nuniverses u v w\nvariable {I : Type u} -- The indexing type\nvariable {f : I → Type v} -- The family of types already equipped with instances\nvariables (x y : Π i, f i) (i : I)\n\nnamespace pi\n\n@[to_additive pi.has_vadd]\ninstance has_scalar {α : Type*} [Π i, has_scalar α $ f i] :\n has_scalar α (Π i : I, f i) :=\n⟨λ s x, λ i, s • (x i)⟩\n\n@[to_additive]\nlemma smul_def {α : Type*} [Π i, has_scalar α $ f i] (s : α) : s • x = λ i, s • x i := rfl\n@[simp, to_additive]\nlemma smul_apply {α : Type*} [Π i, has_scalar α $ f i] (s : α) : (s • x) i = s • x i := rfl\n\n@[to_additive pi.has_vadd']\ninstance has_scalar' {g : I → Type*} [Π i, has_scalar (f i) (g i)] :\n has_scalar (Π i, f i) (Π i : I, g i) :=\n⟨λ s x, λ i, (s i) • (x i)⟩\n\n@[simp, to_additive]\nlemma smul_apply' {g : I → Type*} [∀ i, has_scalar (f i) (g i)] (s : Π i, f i) (x : Π i, g i) :\n (s • x) i = s i • x i :=\nrfl\ninstance is_scalar_tower {α β : Type*}\n [has_scalar α β] [Π i, has_scalar β $ f i] [Π i, has_scalar α $ f i]\n [Π i, is_scalar_tower α β (f i)] : is_scalar_tower α β (Π i : I, f i) :=\n⟨λ x y z, funext $ λ i, smul_assoc x y (z i)⟩\n\ninstance is_scalar_tower' {g : I → Type*} {α : Type*}\n [Π i, has_scalar α $ f i] [Π i, has_scalar (f i) (g i)] [Π i, has_scalar α $ g i]\n [Π i, is_scalar_tower α (f i) (g i)] : is_scalar_tower α (Π i : I, f i) (Π i : I, g i) :=\n⟨λ x y z, funext $ λ i, smul_assoc x (y i) (z i)⟩\n\ninstance is_scalar_tower'' {g : I → Type*} {h : I → Type*}\n [Π i, has_scalar (f i) (g i)] [Π i, has_scalar (g i) (h i)] [Π i, has_scalar (f i) (h i)]\n [Π i, is_scalar_tower (f i) (g i) (h i)] : is_scalar_tower (Π i, f i) (Π i, g i) (Π i, h i) :=\n⟨λ x y z, funext $ λ i, smul_assoc (x i) (y i) (z i)⟩\n\n@[to_additive]\ninstance smul_comm_class {α β : Type*}\n [Π i, has_scalar α $ f i] [Π i, has_scalar β $ f i] [∀ i, smul_comm_class α β (f i)] :\n smul_comm_class α β (Π i : I, f i) :=\n⟨λ x y z, funext $ λ i, smul_comm x y (z i)⟩\n\n@[to_additive]\ninstance smul_comm_class' {g : I → Type*} {α : Type*}\n [Π i, has_scalar α $ g i] [Π i, has_scalar (f i) (g i)] [∀ i, smul_comm_class α (f i) (g i)] :\n smul_comm_class α (Π i : I, f i) (Π i : I, g i) :=\n⟨λ x y z, funext $ λ i, smul_comm x (y i) (z i)⟩\n\n@[to_additive]\ninstance smul_comm_class'' {g : I → Type*} {h : I → Type*}\n [Π i, has_scalar (g i) (h i)] [Π i, has_scalar (f i) (h i)]\n [∀ i, smul_comm_class (f i) (g i) (h i)] : smul_comm_class (Π i, f i) (Π i, g i) (Π i, h i) :=\n⟨λ x y z, funext $ λ i, smul_comm (x i) (y i) (z i)⟩\n\ninstance {α : Type*} [Π i, has_scalar α $ f i] [Π i, has_scalar αᵐᵒᵖ $ f i]\n [∀ i, is_central_scalar α (f i)] : is_central_scalar α (Π i, f i) :=\n⟨λ r m, funext $ λ i, op_smul_eq_smul _ _⟩\n\n/-- If `f i` has a faithful scalar action for a given `i`, then so does `Π i, f i`. This is\nnot an instance as `i` cannot be inferred. -/\n@[to_additive pi.has_faithful_vadd_at]\nlemma has_faithful_smul_at {α : Type*}\n [Π i, has_scalar α $ f i] [Π i, nonempty (f i)] (i : I) [has_faithful_smul α (f i)] :\n has_faithful_smul α (Π i, f i) :=\n⟨λ x y h, eq_of_smul_eq_smul $ λ a : f i, begin\n classical,\n have := congr_fun (h $ function.update (λ j, classical.choice (‹Π i, nonempty (f i)› j)) i a) i,\n simpa using this,\nend⟩\n\n@[to_additive pi.has_faithful_vadd]\ninstance has_faithful_smul {α : Type*}\n [nonempty I] [Π i, has_scalar α $ f i] [Π i, nonempty (f i)] [Π i, has_faithful_smul α (f i)] :\n has_faithful_smul α (Π i, f i) :=\nlet ⟨i⟩ := ‹nonempty I› in has_faithful_smul_at i\n\n@[to_additive]\ninstance mul_action (α) {m : monoid α} [Π i, mul_action α $ f i] :\n @mul_action α (Π i : I, f i) m :=\n{ smul := (•),\n mul_smul := λ r s f, funext $ λ i, mul_smul _ _ _,\n one_smul := λ f, funext $ λ i, one_smul α _ }\n\n@[to_additive]\ninstance mul_action' {g : I → Type*} {m : Π i, monoid (f i)} [Π i, mul_action (f i) (g i)] :\n @mul_action (Π i, f i) (Π i : I, g i) (@pi.monoid I f m) :=\n{ smul := (•),\n mul_smul := λ r s f, funext $ λ i, mul_smul _ _ _,\n one_smul := λ f, funext $ λ i, one_smul _ _ }\n\ninstance distrib_mul_action (α) {m : monoid α} {n : ∀ i, add_monoid $ f i}\n [∀ i, distrib_mul_action α $ f i] :\n @distrib_mul_action α (Π i : I, f i) m (@pi.add_monoid I f n) :=\n{ smul_zero := λ c, funext $ λ i, smul_zero _,\n smul_add := λ c f g, funext $ λ i, smul_add _ _ _,\n ..pi.mul_action _ }\n\ninstance distrib_mul_action' {g : I → Type*} {m : Π i, monoid (f i)} {n : Π i, add_monoid $ g i}\n [Π i, distrib_mul_action (f i) (g i)] :\n @distrib_mul_action (Π i, f i) (Π i : I, g i) (@pi.monoid I f m) (@pi.add_monoid I g n) :=\n{ smul_add := by { intros, ext x, apply smul_add },\n smul_zero := by { intros, ext x, apply smul_zero } }\n\nlemma single_smul {α} [monoid α] [Π i, add_monoid $ f i]\n [Π i, distrib_mul_action α $ f i] [decidable_eq I] (i : I) (r : α) (x : f i) :\n single i (r • x) = r • single i x :=\nsingle_op (λ i : I, ((•) r : f i → f i)) (λ j, smul_zero _) _ _\n\n/-- A version of `pi.single_smul` for non-dependent functions. It is useful in cases Lean fails\nto apply `pi.single_smul`. -/\nlemma single_smul' {α β} [monoid α] [add_monoid β]\n [distrib_mul_action α β] [decidable_eq I] (i : I) (r : α) (x : β) :\n single i (r • x) = r • single i x :=\nsingle_smul i r x\n\nlemma single_smul₀ {g : I → Type*} [Π i, monoid_with_zero (f i)] [Π i, add_monoid (g i)]\n [Π i, distrib_mul_action (f i) (g i)] [decidable_eq I] (i : I) (r : f i) (x : g i) :\n single i (r • x) = single i r • single i x :=\nsingle_op₂ (λ i : I, ((•) : f i → g i → g i)) (λ j, smul_zero _) _ _ _\n\ninstance mul_distrib_mul_action (α) {m : monoid α} {n : Π i, monoid $ f i}\n [Π i, mul_distrib_mul_action α $ f i] :\n @mul_distrib_mul_action α (Π i : I, f i) m (@pi.monoid I f n) :=\n{ smul_one := λ c, funext $ λ i, smul_one _,\n smul_mul := λ c f g, funext $ λ i, smul_mul' _ _ _,\n ..pi.mul_action _ }\n\ninstance mul_distrib_mul_action' {g : I → Type*} {m : Π i, monoid (f i)} {n : Π i, monoid $ g i}\n [Π i, mul_distrib_mul_action (f i) (g i)] :\n @mul_distrib_mul_action (Π i, f i) (Π i : I, g i) (@pi.monoid I f m) (@pi.monoid I g n) :=\n{ smul_mul := by { intros, ext x, apply smul_mul' },\n smul_one := by { intros, ext x, apply smul_one } }\n\nend pi\n\nnamespace function\n\n/-- Non-dependent version of `pi.has_scalar`. Lean gets confused by the dependent instance if this\nis not present. -/\n@[to_additive has_vadd]\ninstance has_scalar {ι R M : Type*} [has_scalar R M] :\n has_scalar R (ι → M) :=\npi.has_scalar\n\n/-- Non-dependent version of `pi.smul_comm_class`. Lean gets confused by the dependent instance if\nthis is not present. -/\n@[to_additive]\ninstance smul_comm_class {ι α β M : Type*}\n [has_scalar α M] [has_scalar β M] [smul_comm_class α β M] :\n smul_comm_class α β (ι → M) :=\npi.smul_comm_class\n\n@[to_additive]\nlemma update_smul {α : Type*} [Π i, has_scalar α (f i)] [decidable_eq I]\n (c : α) (f₁ : Π i, f i) (i : I) (x₁ : f i) :\n update (c • f₁) i (c • x₁) = c • update f₁ i x₁ :=\nfunext $ λ j, (apply_update (λ i, (•) c) f₁ i x₁ j).symm\n\nend function\n\nnamespace set\n\n@[to_additive]\nlemma piecewise_smul {α : Type*} [Π i, has_scalar α (f i)] (s : set I) [Π i, decidable (i ∈ s)]\n (c : α) (f₁ g₁ : Π i, f i) :\n s.piecewise (c • f₁) (c • g₁) = c • s.piecewise f₁ g₁ :=\ns.piecewise_op _ _ (λ _, (•) c)\n\nend set\n\nsection extend\n\n@[to_additive] lemma function.extend_smul {R α β γ : Type*} [has_scalar R γ]\n (r : R) (f : α → β) (g : α → γ) (e : β → γ) :\n function.extend f (r • g) (r • e) = r • function.extend f g e :=\nfunext $ λ _, by convert (apply_dite ((•) r) _ _ _).symm\n\nend extend\n", "meta": {"author": "nick-kuhn", "repo": "leantools", "sha": "567a98c031fffe3f270b7b8dea48389bc70d7abb", "save_path": "github-repos/lean/nick-kuhn-leantools", "path": "github-repos/lean/nick-kuhn-leantools/leantools-567a98c031fffe3f270b7b8dea48389bc70d7abb/src/group_theory/group_action/pi.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4186969093556867, "lm_q2_score": 0.0427221935853065, "lm_q1q2_score": 0.017887650415063176}} {"text": "import tactic\nimport .direction\nimport .boolset2d\nimport .listdec\nimport .sokostate\nimport .sokowidget\n\nstructure sokolevel :=\n(avail : bset2d)\n(ini : sokostate)\n(goal : boxes_only)\n\ninstance : inhabited sokolevel\n:= ⟨{ avail := [[tt]], ini := {boxes := [], storekeeper := (0,0)}, goal := ⟨[]⟩ }⟩\n\nnamespace sokolevel\n\ndef valid (level : sokolevel) := level.ini.valid level.avail\ninstance {level : sokolevel} : decidable level.valid\n := sokostate.valid.decidable\n\nlemma default.valid : (default sokolevel).valid := dec_trivial\n\ndef move (level : sokolevel) (d : direction) : sokolevel\n:= {ini := (level.ini.move level.avail d) ..level}\n\ndef solvable (level : sokolevel) :=\n exists goal_state : sokostate, goal_state ∈ level.goal ∧\n goal_state.reachable level.avail level.ini\n\nlemma solvable.triv (level : sokolevel)\n: level.ini ∈ level.goal → level.solvable\n:= λ Hin, ⟨level.ini, ⟨Hin, sokostate.reachable.triv⟩⟩\n\nlemma solvable.move (d : direction) (level : sokolevel)\n: (level.move d).solvable → level.solvable\n:= λ Hsol, exists.elim Hsol (λ goal Hsol,\n ⟨goal, ⟨Hsol.1, sokostate.reachable.move d Hsol.2⟩⟩ )\n\n-- _ _ \n-- (_)_ __ ___ _ __ ___ _ __| |_ \n-- | | '_ ` _ \\| '_ \\ / _ \\| '__| __|\n-- | | | | | | | |_) | (_) | | | |_ \n-- |_|_| |_| |_| .__/ \\___/|_| \\__|\n-- |_| \n\ndef add_newline (s : sokolevel) : sokolevel := {\n avail := []::s.avail,\n ini := {\n boxes := []::s.ini.boxes,\n storekeeper := match s.ini.storekeeper with (x,y) := (x,y+1) end\n },\n goal := { boxes := []::s.goal.boxes },\n}\ndef add_newsquare (av box stor sk : bool) (s : sokolevel) : sokolevel := {\n avail := list2d.add_to_line1 av s.avail,\n ini := {\n boxes := list2d.add_to_line1 box s.ini.boxes,\n storekeeper := if sk then (0, 0) else match s.ini.storekeeper with\n | (x,0) := (x+1,0)\n | xy := xy\n end\n },\n goal := { boxes := list2d.add_to_line1 stor s.goal.boxes, }\n}\n\ndef from_string_aux : list char → option (sokolevel × bool)\n| [] := some ( ⟨ [], ⟨[], (0,0)⟩, ⟨[]⟩⟩ , ff)\n| (c::str) := match (from_string_aux str), c with\n | none, _ := none\n | (some (s, sk_set)), '\\n' := some (s.add_newline, sk_set)\n | (some (s, sk_set)), ' ' := some (s.add_newsquare tt ff ff ff, sk_set)\n | (some (s, sk_set)), '#' := some (s.add_newsquare ff ff ff ff, sk_set)\n | (some (s, sk_set)), '.' := some (s.add_newsquare tt ff tt ff, sk_set)\n | (some (s, sk_set)), '$' := some (s.add_newsquare tt tt ff ff, sk_set)\n | (some (s, sk_set)), '*' := some (s.add_newsquare tt tt tt ff, sk_set)\n | (some (s, ff)), '@' := some (s.add_newsquare tt ff ff tt, tt)\n | (some (s, ff)), '+' := some (s.add_newsquare tt ff tt tt, tt)\n | (some _), _ := none\n end\n\ndef from_string (str : string) : sokolevel :=\n match (from_string_aux str.to_list) with\n | none := default sokolevel\n | some (_, ff) := default sokolevel\n | some (level, tt) := level\n end\n\n-- _ \n-- _____ ___ __ ___ _ __| |_ \n-- / _ \\ \\/ / '_ \\ / _ \\| '__| __|\n-- | __/> <| |_) | (_) | | | |_ \n-- \\___/_/\\_\\ .__/ \\___/|_| \\__|\n-- |_| \n\ndef square_to_char : bool → bool → bool → bool → char\n| tt ff ff ff := ' '\n| ff ff ff ff := '#'\n| tt ff tt ff := '.'\n| tt tt ff ff := '$'\n| tt tt tt ff := '*'\n| tt ff ff tt := '@'\n| tt ff tt tt := '+'\n| _ _ _ _ := '?'\n\ndef to_string_aux1 (str : list char) : list (bool × bool × bool × bool) → list char\n| [] := str\n| ((av,box,stor,sk)::t) := (square_to_char av box stor sk)::(to_string_aux1 t)\n\ndef to_string_aux2 : list2d (bool × bool × bool × bool) → list char\n| [] := []\n| (h::t) := to_string_aux1 ('\\n'::(to_string_aux2 t)) h\n\ninstance : has_to_string sokolevel := ⟨λ s,\n list.as_string (to_string_aux2\n (s.avail.dfzip2d (s.ini.boxes.dfzip2d (s.goal.boxes.dfzip2d (list2d.set2d true [] s.ini.storekeeper)))))\n⟩\n\ninstance : has_repr sokolevel\n:= ⟨λ lev, (string.append (string.append \"from_string \\\"\" (to_string lev)) \"\\\"\")⟩\n\nmeta def to_html (lev : sokolevel) : widget.html empty\n := sokowidget.build_table lev.avail lev.avail lev.ini.boxes lev.goal.boxes (bset2d.from_index lev.ini.storekeeper)\n\n-- _ _ _ __ _ _ _ \n-- ___(_)_ __ ___ _ __ | (_)/ _(_) ___ __ _| |_(_) ___ _ __ \n-- / __| | '_ ` _ \\| '_ \\| | | |_| |/ __/ _` | __| |/ _ \\| '_ \\ \n-- \\__ \\ | | | | | | |_) | | | _| | (_| (_| | |_| | (_) | | | |\n-- |___/_|_| |_| |_| .__/|_|_|_| |_|\\___\\__,_|\\__|_|\\___/|_| |_|\n-- |_| \n\nmeta def soko_show : tactic unit :=\ndo\n `(sokolevel.solvable %%lev_e) ← tactic.target,\n lev ← tactic.eval_expr sokolevel lev_e,\n tactic.trace (to_string lev)\n\nmeta def soko_simp_root (e : expr) : tactic unit :=\ndo\n soko ← tactic.eval_expr sokolevel e,\n tactic.trace (to_string soko),\n let p : pexpr := ``(%%e = sokolevel.mk\n %%soko.avail (sokostate.mk %%soko.ini.boxes %%soko.ini.storekeeper) (boxes_only.mk %%soko.goal.boxes)),\n eq ← tactic.to_expr p,\n name ← tactic.get_unused_name,\n H ← tactic.assert name eq,\n tactic.reflexivity,\n tactic.rewrite_target H,\n tactic.clear H\n\nmeta def soko_simp : tactic unit :=\ndo\n `(sokolevel.solvable %%lev) ← tactic.target,\n soko_simp_root lev\n\nmeta def soko_check_depth : expr → ℕ → tactic unit\n| _ 0 := return ()\n| e (n+1) := do\n `(sokolevel.move %%lev _) ← return e,\n soko_check_depth lev n\n\nmeta def soko_simp_if_deep : tactic unit :=\ndo\n `(sokolevel.solvable %%lev) ← tactic.target,\n tactic.try ((soko_check_depth lev 20) >> (soko_simp_root lev))\n\nmeta def solve_up : tactic unit\n:= tactic.apply `(solvable.move direction.up) >> soko_simp_if_deep\nmeta def solve_down : tactic unit\n:= tactic.apply `(solvable.move direction.down) >> soko_simp_if_deep\nmeta def solve_left : tactic unit\n:= tactic.apply `(solvable.move direction.left) >> soko_simp_if_deep\nmeta def solve_right : tactic unit\n:= tactic.apply `(solvable.move direction.right) >> soko_simp_if_deep\nmeta def solve_finish : tactic unit\n:= tactic.apply `(solvable.triv) >> tactic.apply `(@of_as_true) >> tactic.triv\n\nend sokolevel\n", "meta": {"author": "mirefek", "repo": "sokoban.lean", "sha": "451c92308afb4d3f8e566594b9751286f93b899b", "save_path": "github-repos/lean/mirefek-sokoban.lean", "path": "github-repos/lean/mirefek-sokoban.lean/sokoban.lean-451c92308afb4d3f8e566594b9751286f93b899b/src/sokolevel.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4649015862011227, "lm_q2_score": 0.038466194360679794, "lm_q1q2_score": 0.017882994773400718}} {"text": "-- Copyright (c) Microsoft Corporation. All rights reserved.\n-- Licensed under the MIT license.\n\nimport ..smtexpr\nimport ..smtcompile\nimport ..bitvector\nimport ..verifyopt\nimport .spec\nimport .lemmas\nimport .irstate\nimport .freevar\nimport .equiv\nimport .openprog\nimport ..irsem_exec\nimport smt2.syntax\nimport system.io\nimport init.meta.tactic\nimport init.meta.interactive\n\nnamespace spec\n\nopen opt\nopen irsem\n\nset_option pp.proofs true\nlemma check_val_exec_spec_prf : check_val_exec_spec\n:= begin\n unfold check_val_exec_spec,\n intros,\n cases vsrc with szsrc vsrc psrc,\n cases vtgt with sztgt vtgt ptgt,\n unfold check_val at H,\n have HSZ:decidable (sztgt = szsrc), apply_instance,\n cases HSZ,\n { rw dif_neg at H, cases H, apply neq_symm, assumption },\n {\n rw dif_pos at H,\n rw valty_rwsize_exec sztgt szsrc,\n injection H with H,\n generalize H0: (vsrc =_{irsem_exec.boolty}\n cast (check_val._match_1._proof_1\n irsem_exec szsrc sztgt (eq.symm HSZ)) vtgt) = t,\n rw H0 at H,\n unfold has_not.not at H,\n unfold has_or.or at H,\n unfold has_and.and at H,\n\n cases psrc,\n {\n apply val_refines.poison_intty, refl\n },\n {\n apply val_refines.concrete_intty,\n { refl },\n { cases ptgt,\n {\n cases t, cases H, cases H\n },\n refl },\n {\n cases t,\n { cases ptgt, cases H, cases H },\n {\n unfold has_eq.eq at H0,\n unfold has_comp.eq at H0,\n unfold bitvector.eq at H0,\n simp at H0, rw H0\n }\n }\n },\n any_goals { assumption }\n }\nend\n\n\n\nset_option pp.proofs true\nlemma check_val_replace: ∀ vssrc vstgt (η:freevar.env),\n η⟦opt.check_val irsem_smt vssrc vstgt⟧' = opt.check_val irsem_smt (η⟦vssrc⟧) (η⟦vstgt⟧)\n:= begin\n intros,\n cases vssrc, cases vstgt,\n unfold opt.check_val,\n unfold freevar.env.replace_valty,\n have HSZ: decidable (vssrc_sz = vstgt_sz), apply_instance,\n cases HSZ,\n {\n unfold check_val._match_1,\n rw dif_neg HSZ,\n rw dif_neg HSZ\n },\n {\n unfold check_val._match_1,\n rw dif_pos HSZ,\n rw dif_pos HSZ,\n unfold apply,\n unfold_coes,\n unfold id,\n rw env.replace_sb_or,\n rw env.replace_sb_not,\n rw env.replace_sb_and,\n unfold has_eq.eq, unfold has_comp.eq,\n rw env.replace_sb_eqbv,\n rw env.replace_sbv_cast, rw HSZ\n }\nend\n\nlemma check_val_some: ∀ {vssrc vstgt vesrc vetgt sres eres}\n (HEQS:equals_size vssrc vesrc = tt)\n (HEQT:equals_size vstgt vetgt = tt)\n (HS:sres = opt.check_val irsem_smt vssrc vstgt)\n (HE:eres = opt.check_val irsem_exec vesrc vetgt),\n none_or_some sres eres (λ s e, true)\n:= begin\n intros,\n cases vssrc, cases vesrc, cases vstgt, cases vetgt,\n unfold equals_size at HEQS, simp at HEQS,\n unfold equals_size at HEQT, simp at HEQT,\n unfold check_val at HS,\n unfold check_val at HE,\n\n have HSZ': decidable (vssrc_sz = vstgt_sz), apply_instance,\n cases HSZ',\n {\n have HSZ'': vesrc_sz ≠ vetgt_sz,\n { rw ← HEQS, rw ← HEQT, assumption },\n rw dif_neg HSZ' at HS,\n rw dif_neg HSZ'' at HE,\n unfold none_or_some, left, split; assumption\n },\n {\n have HSZ'': vesrc_sz = vetgt_sz,\n { rw ← HEQS, rw ← HEQT, assumption },\n rw dif_pos HSZ' at HS,\n rw dif_pos HSZ'' at HE,\n cases sres, cases HS, injection HS,\n cases eres, cases HE, injection HE,\n unfold none_or_some, right, apply exists.intro,\n apply exists.intro, split, refl, split, refl, constructor\n }\nend\n\nlemma check_val_equiv: ∀ {vssrc vstgt vesrc vetgt sres eres}\n (HEQS:val_equiv vssrc vesrc)\n (HEQT:val_equiv vstgt vetgt)\n (HS:sres = opt.check_val irsem_smt vssrc vstgt)\n (HE:eres = opt.check_val irsem_exec vesrc vetgt),\n none_or_some sres eres (λ s e, b_equiv s e)\n:= begin\n intros,\n cases vssrc, cases vstgt,\n cases vesrc, cases vetgt, -- make ivals\n have HSSZEQ := val_equiv_eqsize HEQS,\n have HTSZEQ := val_equiv_eqsize HEQT,\n unfold opt.check_val at *,\n\n have HSZ': decidable (vssrc_sz = vstgt_sz), apply_instance,\n cases HSZ',\n {\n have HSZ'': vesrc_sz ≠ vetgt_sz,\n {\n rw ← HSSZEQ, rw ← HTSZEQ, assumption\n },\n rw dif_neg HSZ' at HS,\n rw dif_neg HSZ'' at HE,\n rw HS, rw HE, unfold none_or_some, left, split;refl\n },\n {\n have HSZ'': vesrc_sz = vetgt_sz,\n { rw [← HSSZEQ, ← HTSZEQ], rw HSZ' },\n rw dif_pos HSZ' at HS,\n rw dif_pos HSZ'' at HE,\n cases sres, cases HS,\n cases eres, cases HE,\n injection HS with HS, injection HE with HE,\n unfold none_or_some,\n right,\n existsi sres, existsi eres,\n split, refl, split, refl,\n rw [HS, HE],\n\n cases HEQS,\n { -- source is poison.\n cases HEQS_a with HEQS_a,\n apply b_equiv.or1,\n { apply b_equiv.not, unfold_coes, unfold id, assumption },\n { intros H, rw HEQS_a_2 at H, cases H }\n },\n { -- source is concrete value,\n cases HEQS_a,\n cases HEQT,\n { -- target is poison\n apply b_equiv.or1, apply b_equiv.not, assumption,\n intros, apply b_equiv.and1, cases HEQT_a, assumption,\n intros, rw HEQT_a_2 at a_1, cases a_1\n },\n {\n cases HEQT_a,\n apply b_equiv.or1,\n { apply b_equiv.not, assumption },\n { intros, apply b_equiv.and1, assumption, intros,\n apply b_equiv.eq, assumption, --apply HEQT_a_1, apply bv_equiv.cast,\n apply bv_equiv_cast, assumption, rw HSZ''\n }\n }\n }\n }\nend\n\n\nuniverse u\nlemma check_single_reg0_replace: ∀ psrc ptgt root ss0 (η:freevar.env),\n η⟦opt.check_single_reg0 irsem_smt psrc ptgt root ss0⟧' =\n opt.check_single_reg0 irsem_smt psrc ptgt root (η⟦ss0⟧)\n:= begin\n intros,\n unfold opt.check_single_reg0,\n generalize HSS: irsem.bigstep irsem_smt ss0 psrc = oss,\n generalize HSS': irsem.bigstep irsem_smt ss0 ptgt = oss',\n rw ← bigstep_replace,\n rw ← bigstep_replace,\n rw HSS, rw HSS',\n unfold has_bind.bind,\n cases oss; cases oss';unfold option.bind,\n generalize HSV: irstate.getreg irsem_smt oss root = ovs,\n generalize HSV': irstate.getreg irsem_smt oss' root = ovs',\n rw getreg_replace HSV,\n rw getreg_replace HSV',\n cases ovs; cases ovs'; unfold option.bind,\n rw ← check_val_replace,\n generalize HCV: check_val irsem_smt ovs ovs' = ocv,\n cases ocv;unfold option.bind,\n unfold return, unfold pure,\n unfold apply,\n rw env.replace_sb_or,\n rw env.replace_sb_not,\n rw replace_getub,\n rw env.replace_sb_and,\n rw replace_getub\nend\n\nlemma check_single_reg0_equiv: ∀ psrc ptgt root ss0 se0 sres eres\n (HEQ:irstate_equiv ss0 se0)\n (HS:sres = opt.check_single_reg0 irsem_smt psrc ptgt root ss0)\n (HE:eres = opt.check_single_reg0 irsem_exec psrc ptgt root se0)\n (HEQS:irstate_equiv ss0 se0),\n none_or_some sres eres (λ s e, b_equiv s e)\n:= begin\n intros,\n unfold opt.check_single_reg0 at *,\n unfold has_bind.bind at HS,\n unfold has_bind.bind at HE,\n generalize HSS: irsem.bigstep irsem_smt ss0 psrc = oss,\n generalize HSS': irsem.bigstep irsem_smt ss0 ptgt = oss',\n generalize HSE: irsem.bigstep irsem_exec se0 psrc = ose,\n generalize HSE': irsem.bigstep irsem_exec se0 ptgt = ose',\n rw [HSS, HSS'] at HS,\n rw [HSE, HSE'] at HE,\n have HPTGT_ENTANGLED: none_or_some oss' ose' (λ ss' se', irstate_equiv ss' se'),\n {\n apply bigstep_both_equiv,\n assumption, rw HSS', rw HSE'\n },\n have HPSRC_ENTANGLED: none_or_some oss ose (λ ss' se', irstate_equiv ss' se'),\n {\n apply bigstep_both_equiv,\n assumption, rw HSS, rw HSE\n },\n cases oss; cases oss';\n cases ose; cases ose',\n any_goals { unfold option.bind at HS, unfold option.bind at HE,\n rw HS, rw HE, unfold none_or_some, left, split; refl },\n any_goals {\n exfalso, apply none_or_some_false2, apply HPSRC_ENTANGLED\n },\n any_goals {\n exfalso, apply none_or_some_false1, apply HPSRC_ENTANGLED\n },\n any_goals {\n exfalso, apply none_or_some_false2, apply HPTGT_ENTANGLED\n },\n any_goals {\n exfalso, apply none_or_some_false1, apply HPTGT_ENTANGLED\n },\n rw none_or_some_apply at HPSRC_ENTANGLED,\n rw none_or_some_apply at HPTGT_ENTANGLED,\n unfold option.bind at HS,\n unfold option.bind at HE,\n generalize HSV: irstate.getreg irsem_smt oss root = ovs,\n generalize HSV': irstate.getreg irsem_smt oss' root = ovs',\n generalize HEV: irstate.getreg irsem_exec ose root = ove,\n generalize HEV': irstate.getreg irsem_exec ose' root = ove',\n have HSRCVEQ := irstate.getreg_equiv HPSRC_ENTANGLED (eq.symm HSV) (eq.symm HEV),\n have HTGTVEQ := irstate.getreg_equiv HPTGT_ENTANGLED (eq.symm HSV') (eq.symm HEV'),\n rw [HSV, HSV'] at HS,\n rw [HEV, HEV'] at HE,\n cases ovs; cases ovs'; cases ove; cases ove',\n any_goals { unfold option.bind at HS, unfold option.bind at HE,\n rw HS, rw HE, unfold none_or_some, left, split; refl },\n any_goals {\n exfalso, apply none_or_some_false2, apply HSRCVEQ\n },\n any_goals {\n exfalso, apply none_or_some_false1, apply HSRCVEQ\n },\n any_goals {\n exfalso, apply none_or_some_false2, apply HTGTVEQ\n },\n any_goals {\n exfalso, apply none_or_some_false1, apply HTGTVEQ\n },\n rw none_or_some_apply at HSRCVEQ,\n rw none_or_some_apply at HTGTVEQ,\n unfold option.bind at HS,\n unfold option.bind at HE,\n cases HSRCVEQ with HSRCSZEQ HSRCVEQ,\n cases HTGTVEQ with HTGTSZEQ HTGTVEQ,\n generalize HSCV: check_val irsem_smt ovs ovs' = scv,\n generalize HECV: check_val irsem_exec ove ove' = ecv,\n rw HSCV at HS, rw HECV at HE,\n have HCVRET := check_val_some HSRCSZEQ HTGTSZEQ (eq.symm HSCV) (eq.symm HECV),\n cases scv ; cases ecv,\n { unfold option.bind at HS, unfold option.bind at HE,\n rw HS, rw HE, unfold none_or_some, left, split; refl },\n {\n unfold option.bind at HS,\n unfold option.bind at HE,\n exfalso, apply none_or_some_false2,\n assumption\n },\n {\n unfold option.bind at HS,\n unfold option.bind at HE,\n exfalso, apply none_or_some_false1,\n assumption\n },\n unfold option.bind at HS,\n unfold option.bind at HE,\n unfold return at *, unfold pure at *,\n unfold none_or_some, right,\n apply exists.intro,\n apply exists.intro,\n split, assumption,\n split, assumption,\n generalize HUB: (~irstate.getub irsem_exec ose) = ub,\n cases ub,\n {\n apply b_equiv.or1,\n {\n rw ← HUB, apply b_equiv.not,\n apply irstate.getub_equiv,\n apply HPSRC_ENTANGLED,\n refl, refl\n },\n {\n generalize HUB': irstate.getub irsem_exec ose' = ub',\n cases ub',\n {\n intros, apply b_equiv.and1,\n rw ← HUB',\n apply irstate.getub_equiv,\n apply HPTGT_ENTANGLED, refl, rw HUB', intros Q, cases Q\n },\n {\n intros, apply b_equiv.and1,\n apply irstate.getub_equiv,\n apply HPTGT_ENTANGLED, refl, rw HUB',\n have HNOUB: has_no_ub ose = tt,\n {\n cases ose, unfold irstate.getub at HUB,\n simp at HUB, unfold has_not.not at HUB,\n cases ose_fst, cases HUB, refl\n },\n have HNOUB': has_no_ub ose' = tt,\n {\n cases ose', unfold irstate.getub at HUB',\n simp at HUB',\n cases ose'_fst, cases HUB', refl\n },\n have HV := HSRCVEQ HNOUB,\n have HV' := HTGTVEQ HNOUB',\n have HCVRET := check_val_equiv HV HV' (eq.symm HSCV) (eq.symm HECV),\n rw none_or_some_apply at HCVRET,\n intros, assumption\n }\n }\n },\n {\n apply b_equiv.or1,\n {\n rw ← HUB, apply b_equiv.not, apply irstate.getub_equiv, apply HPSRC_ENTANGLED,\n refl, refl\n },\n {\n intros Q, cases Q\n }\n }\nend\n\n\ntheorem refines_single_reg_correct_prf: refines_single_reg_correct\n:= begin\n unfold refines_single_reg_correct,\n intros,\n unfold root_refines_smt,\n intros,\n unfold root_refines_finalstate,\n intros,\n generalize HEREF: check_single_reg0 irsem_exec psrc ptgt root se0 = oeb,\n have HSREF': some (η⟦sb⟧) = check_single_reg0 irsem_smt psrc ptgt root (η⟦ss0⟧),\n {\n rw ← check_single_reg0_replace,\n rw ← HSREF\n },\n have HCHKEQ: none_or_some (some (η⟦sb⟧)) oeb (λ s e, b_equiv s e),\n {\n apply check_single_reg0_equiv,\n unfold encode at a, apply a,\n rw HSREF', rw HEREF, unfold encode at a, apply a\n },\n cases oeb with eb,\n { exfalso, apply none_or_some_false1, assumption },\n rw none_or_some_apply at HCHKEQ,\n have HCHKTT := HEQ η eb HCHKEQ,\n \n unfold root_refines,\n unfold check_single_reg0 at HEREF,\n rw [← a_1, ← a_2] at HEREF,\n unfold has_bind.bind at HEREF,\n unfold option.bind at HEREF,\n generalize HV: (irstate.getreg irsem_exec se root) = ov,\n generalize HV': (irstate.getreg irsem_exec se' root) = ov',\n rw [HV, HV'] at HEREF,\n cases ov with v; cases ov' with v',\n any_goals { unfold option.bind at HEREF, cases HEREF, done },\n unfold option.bind at HEREF,\n\n generalize HCV: check_val irsem_exec v v' = ocv,\n rw HCV at HEREF,\n cases ocv with cv,\n any_goals { unfold option.bind at HEREF, cases HEREF, done },\n unfold option.bind at HEREF,\n injection HEREF with HEREF,\n subst HCHKTT,\n split,\n {\n generalize HUBSRC : irstate.getub irsem_exec se = ubsrc,\n generalize HUBTGT : irstate.getub irsem_exec se' = ubtgt,\n rw HUBSRC at HEREF,\n rw HUBTGT at HEREF,\n cases ubsrc,\n {\n apply ub_refines.ub,\n rw HUBSRC, refl\n },\n {\n apply ub_refines.noub, rw HUBSRC, refl,\n cases ubtgt,\n { cases cv; cases HEREF },\n { rw HUBTGT, refl }\n }\n },\n {\n intros HUBTRUE,\n existsi v, existsi v',\n split, refl, split, refl,\n apply check_val_exec_spec_prf,\n rw HUBTRUE at HEREF,\n cases (irstate.getub irsem_exec se'); cases cv,\n any_goals { cases HEREF, done },\n assumption\n }\nend\n\nend spec", "meta": {"author": "microsoft", "repo": "AliveInLean", "sha": "34370c2c15aa69f010d97b8d38e9e1955e9e387d", "save_path": "github-repos/lean/microsoft-AliveInLean", "path": "github-repos/lean/microsoft-AliveInLean/AliveInLean-34370c2c15aa69f010d97b8d38e9e1955e9e387d/src/spec/refinement.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.46490157137338844, "lm_q2_score": 0.03846619119161061, "lm_q1q2_score": 0.01788299272972897}} {"text": "import LeanCodePrompts.Premises\nopen Lean Meta Elab Term Syntax PrettyPrinter Parser\n\nnamespace LeanAide.Meta\n\nclass Reprint(a : Type) where\n reprSyn : a → String\n\ninstance reprintString : Reprint String where\n reprSyn := id\n\ninstance reprintName : Reprint Name where\n reprSyn := toString\n\ninstance reprintNat : Reprint Nat where\n reprSyn := toString\n\ninstance reprintBool : Reprint Bool where\n reprSyn := toString\n\ninstance reprintArray {a : Type} [Reprint a] : Reprint (Array a) where\n reprSyn := fun xs => xs.toList.map Reprint.reprSyn |>.toString\n\ninstance reprintList {a : Type} [Reprint a] : Reprint (List a) where\n reprSyn := fun xs => xs.map Reprint.reprSyn |>.toString\n\ninstance reprintOption {a : Type} [Reprint a] : Reprint (Option a) where\n reprSyn := fun xs => xs.map Reprint.reprSyn |>.getD \"\"\n\ninstance reprintSyntax : Reprint Syntax where\n reprSyn := fun xs => xs.reprint.get!\n\ndef reprint {a : Type}[Reprint a] (x : a) : String := Reprint.reprSyn x\n\ninstance reprintTermData : Reprint TermData where\n reprSyn := fun x => s!\"context: {Reprint.reprSyn x.context}; term: {Reprint.reprSyn x.value}\"\n\ninstance reprintProofData : Reprint PropProofData where\n reprSyn := fun x => s!\"context: {Reprint.reprSyn x.context}; prop: {Reprint.reprSyn x.prop}; proof : {Reprint.reprSyn x.proof}\"\n\n\ndef viewSyntax (s: String) : MetaM <| Syntax × String := do\n let c := runParserCategory (← getEnv) `term s\n match c with\n | Except.error e => throwError e\n | Except.ok s => pure (s, s.reprint.get!)\n\n\ndef nameDefTypeSyntax (name: Name) : MetaM <| Syntax × Syntax := do\n let info? := ((← getEnv).find? name)\n let info := info?.get!\n let exp := info.value?.get!\n let type := info.type\n let (stx, _) ← delabCore exp {} (delabVerbose)\n let (tstx, _) ← delabCore type {} (delabVerbose)\n return (stx, tstx)\n\ndef nameDefSyntax (name: Name) : MetaM <| Option Syntax := do\n let exp? ← nameExpr? name\n match exp? with\n | none => pure none\n | some exp => do\n let stx ← delab exp\n pure (some stx)\n\ndef premisesFromName (name : Name) : MetaM (List PremiseData) := do\n let (pf, prop) ← nameDefTypeSyntax name\n Lean.Syntax.premiseDataM #[] pf prop true name name\n\ndef _root_.PremiseData.view : PremiseData → MetaM String := fun data => do\n return s!\"context: {reprint data.context}; name?: {data.name?}; defnName: {data.defnName}; type: {reprint data.type}; type-group: {reprint data.typeGroup}; sub-terms: {reprint data.terms}; sub-proofs : {reprint data.propProofs} identifiers: {data.ids}\"\n\n\ndef premisesViewFromName (name: Name) : MetaM <| List String := do\n let premises ← premisesFromName name\n premises.mapM (fun p => p.view)\n\n\ndef premisesJsonFromName (name: Name) : MetaM <| Json := do\n let premises ← premisesFromName name\n return toJson premises\n\n\n#eval premisesViewFromName ``Nat.pred_le_pred\n\n-- #eval premisesJsonFromName ``Nat.pred_le_pred\n\n-- #eval premisesViewFromName ``Nat.le_of_succ_le_succ\n\n\ndef boundedDef (bound: Nat)(name: Name) : MetaM Bool := do\n let exp? ← nameExpr? name\n match exp? with\n | none => pure false\n | some exp => do\n pure (exp.approxDepth.toNat < bound)\n\ndef nameDefView (name: Name) : MetaM String := do\n let stx? ← nameDefSyntax name\n return (stx?.get!.reprint.get!)\n\ndef nameDefCleanView (name: Name) : MetaM String := do\n let stx? ← nameDefSyntax name\n return ((stx?.get!.purge).reprint.get!)\n\ndef nameDefSyntaxVerbose (name: Name) : MetaM <| Option Syntax := do\n let exp? ← nameExpr? name\n match exp? with\n | none => pure none\n | some exp => do\n let (stx, _) ← delabCore exp {} (delabVerbose)\n pure (some stx)\n\ndef nameDefViewVerbose (name: Name) : MetaM String := do\n let stx? ← nameDefSyntaxVerbose name\n return (stx?.get!.reprint.get!)\n\n-- #eval nameDefSyntax ``List.join\n\n-- #eval nameDefSyntax ``Nat.le_of_succ_le_succ\n\n\n\n-- #eval nameDefView ``Nat.gcd_eq_zero_iff\n\n-- #eval nameDefCleanView ``Nat.gcd_eq_zero_iff\n\n-- def egSplit : MetaM <| Option (Syntax × Array Syntax) := do\n-- let stx? ← nameDefSyntax ``Nat.gcd_eq_zero_iff\n-- lambdaStx? stx?.get!\n\n-- #eval egSplit\n\n-- def egSplitView : MetaM <| Option (String × Array String) := do\n-- let stx? ← nameDefSyntax ``Nat.gcd_eq_zero_iff\n-- let pair? ← lambdaStx? stx?.get!\n-- let (stx, args) := pair?.get!\n-- pure (stx.reprint.get!, args.map (fun s => s.reprint.get!))\n\n-- #eval egSplitView\n\n-- set_option pp.proofs false in \n-- #eval nameDefView ``Nat.gcd_eq_zero_iff\n\n-- set_option pp.proofs.withType true in \n-- #eval nameDefView ``Nat.gcd_eq_zero_iff\n\n-- #eval nameDefViewVerbose ``Nat.gcd_eq_zero_iff\n\n-- #eval nameDefSyntaxVerbose ``Nat.gcd_eq_zero_iff\n\n-- #eval nameDefViewVerbose ``Nat.gcd_eq_gcd_ab\n\n-- set_option pp.proofs false in\n-- #eval nameDefView ``Nat.gcd_eq_gcd_ab\n\n-- #eval setDelabBound 200\n\n-- #eval nameDefViewVerbose ``Nat.xgcd_aux_P\n\n-- set_option pp.proofs false in\n-- #eval nameDefView ``Nat.xgcd_aux_P\n\n-- theorem oddExample : ∀ (n : Nat), ∃ m, m > n ∧ m % 2 = 1 := by\n-- intro n -- introduce a variable n\n-- use 2 * n + 1 -- use `m = 2 * n + 1`\n-- apply And.intro -- apply the constructor of `∧` to split goals\n-- · linarith -- solve the first goal using `linarith` \n-- · simp [Nat.add_mod] -- solve the second goal using `simp` with the lemma `Nat.add_mod`\n\n-- -- #eval premisesViewFromName ``oddExample\n\nend LeanAide.Meta\n\nopen LeanAide.Meta\n\n\nstructure ConstsData where\n definitions : HashMap Name Syntax\n theorems : HashMap Name Syntax\n\ndef constsData : MetaM ConstsData := do\n let consts ← constantNameTypes\n let mut definitions := HashMap.empty\n let mut theorems := HashMap.empty\n for (c, type) in consts do\n let tstx ← delab type\n let tstx := tstx.raw.purge\n if ← Meta.isProp type then\n theorems := theorems.insert c tstx\n else\n definitions := definitions.insert c tstx\n return { definitions := definitions, theorems := theorems }\n\npartial def Lean.Syntax.identsM (stx: Syntax)(context: Array Syntax)(maxDepth? : Option Nat := none) : MetaM <| List <| Name × Nat := do\n if maxDepth? = some 0 then\n pure []\n else\n match ← namedArgument? stx with\n | some (arg, _) =>\n -- IO.println s!\"Named: {arg}\"\n let prev ← identsM arg context (maxDepth?.map (· -1))\n return prev.map (fun (s, m) => (s, m + 1))\n | none =>\n match ← proofWithProp? stx with\n | some (proof, _) =>\n -- IO.println s!\"Proof: {proof}\"\n let prev ← identsM proof context (maxDepth?.map (· -1))\n return prev.map (fun (s, m) => (s, m + 1))\n | none =>\n match ← lambdaStx? stx with\n | some (body, args) =>\n -- IO.println s!\"Lambda: {args}\"\n let prev ← identsM body (context ++ args) (maxDepth?.map (· -1))\n return prev.map (fun (s, m) => (s, m + args.size))\n | none =>\n match stx with\n | Syntax.node _ _ args => \n let prev ← args.mapM (identsM · context (maxDepth?.map (· -1))) \n return prev.toList.join.map (fun (s, m) => (s, m + 1))\n | Syntax.ident _ _ name .. => \n let contextVars := context.filterMap getVar\n -- IO.println s!\"Context: {contextVars} from {context}\"\n if !(contextVars.contains name) &&\n !(excludePrefixes.any (fun pfx => pfx.isPrefixOf name)) && !(excludeSuffixes.any (fun pfx => pfx.isSuffixOf name)) then \n pure [(name, 0)]\n else pure []\n | _ => pure []\n\n\n-- -- #eval termKindList\n\n\npartial def Lean.Syntax.termsM (context : Array Syntax)(stx: Syntax)(maxDepth? : Option Nat := none) : MetaM <| List <| TermData := do\n let tks ← termKindList\n let tks := tks.map (·.1)\n if maxDepth? = some 0 then\n pure []\n else\n match ← namedArgument? stx with\n | some (arg, _) =>\n -- IO.println s!\"Named: {arg}\"\n let prev ← termsM context arg (maxDepth?.map (· -1))\n return prev.map (fun s => s.increaseDepth 1 )\n | none =>\n match ← proofWithProp? stx with\n | some (proof, _) =>\n -- IO.println s!\"Proof: {proof}\"\n let prev ← termsM context proof (maxDepth?.map (· -1))\n return prev.map (fun s => s.increaseDepth 1)\n | none =>\n match ← lambdaStx? stx with\n | some (body, args) =>\n -- IO.println s!\"Lambda: {args}\"\n let prev ← termsM (context ++ args) body (maxDepth?.map (· -1))\n return prev.map (fun s => s.increaseDepth args.size)\n | none =>\n match stx with\n | Syntax.node _ k args => \n -- IO.println s!\"Node: {k}\"\n let prev ← args.mapM (termsM context · (maxDepth?.map (· -1)))\n let head : TermData := ⟨context, stx.purge, stx.purge.size, 0⟩\n if tks.contains k then \n return (head) :: prev.toList.join.map (fun s => s.increaseDepth 1)\n else \n return prev.toList.join.map (fun s => s.increaseDepth 1)\n | Syntax.ident .. => \n pure []\n | _ => pure []\n\n\n\npartial def Lean.Syntax.proofsM (context : Array Syntax)(stx: Syntax)(maxDepth? : Option Nat := none) : MetaM <| List <| PropProofData := do\n if maxDepth? = some 0 then\n pure []\n else\n match ← namedArgument? stx with\n | some (arg, _) =>\n -- IO.println s!\"Named: {arg}\"\n let prev ← proofsM context arg (maxDepth?.map (· -1))\n return prev.map (fun s => s.increaseDepth 1)\n | none =>\n match ← proofWithProp? stx with\n | some (proof, prop) =>\n -- IO.println s!\"Proof: {proof}\"\n let prev ← proofsM context proof (maxDepth?.map (· -1))\n let head : PropProofData := \n ⟨context, prop, proof, prop.size, proof.size, 0⟩\n return (head) :: prev.map (fun s => s.increaseDepth 1)\n | none =>\n match ← lambdaStx? stx with\n | some (body, args) =>\n -- IO.println s!\"Lambda: {args}\"\n let prev ← proofsM (context ++ args) body (maxDepth?.map (· -1))\n return prev.map (fun s => s.increaseDepth args.size)\n | none =>\n match stx with\n | Syntax.node _ _ args => \n -- IO.println s!\"Node: {k}\"\n let prev ← args.mapM (proofsM context · (maxDepth?.map (· -1)))\n return prev.toList.join.map (fun s => s.increaseDepth 1)\n | Syntax.ident .. => \n pure []\n | _ => pure []\n\n\ndef PremiseData.get(ctx : Array Syntax)(name: Name)(prop pf : Syntax) : MetaM PremiseData := do\n let subProofs: List (PropProofData) ← pf.proofsM ctx\n let subTerms : List (TermData) ← Syntax.termsM ctx pf\n let ids : List (Name × Nat) ← pf.identsM ctx \n return ⟨ctx, some name, name, prop.purge, prop.purge, pf.purge, prop.purge.size, pf.purge.size, subTerms.toArray, subProofs.toArray, ids.toArray⟩\n\ndef viewData (name: Name) : MetaM <| String := do\n let (stx, tstx) ← nameDefTypeSyntax name\n -- IO.println s!\"{stx.reprint.get!}\"\n -- IO.println s!\"{← proofWithProp? stx}\"\n let data ← PremiseData.get #[] name tstx stx \n data.view\n\n-- #eval viewData ``Nat.succ_le_succ\n\npartial def Lean.Syntax.kinds (stx: Syntax)(maxDepth?: Option Nat := none) : List String :=\n if maxDepth? = some 0 then\n []\n else\n match stx with\n | Syntax.node _ k args => \n let head? : Option String := \n k.components.head?.map (· |>.toString)\n match head? with\n | some head => head :: (args.map (kinds · (maxDepth?.map (· -1))) |>.toList.join)\n | none => args.map (kinds · (maxDepth?.map (· -1))) |>.toList.join\n | _ => []\n\npartial def Lean.Syntax.idents (stx: Syntax)(maxDepth? : Option Nat := none) : List <| Name × Nat :=\n if maxDepth? = some 0 then\n []\n else\n match stx with\n | Syntax.node _ _ args => \n args.map (idents · (maxDepth?.map (· -1))) \n |>.toList.join.map (fun (s, m) => (s, m + 1))\n | Syntax.ident _ _ name .. => \n if !(excludePrefixes.any (fun pfx => pfx.isPrefixOf name)) && !(excludeSuffixes.any (fun pfx => pfx.isSuffixOf name)) then \n [(name, 0)]\n else []\n | _ => []\n\n\npartial def Lean.Syntax.terms (stx: Syntax)(maxDepth?: Option Nat := none) : \n MetaM <| List <| String × Nat × List Name := do\n let tks ← termKindList\n let tks := tks.map (·.1)\n if maxDepth? = some 0 then\n pure []\n else\n match stx with\n | Syntax.node _ k args => \n match stx with \n | `(proved_prop| ($pf:term =: $_:term )) => \n pf.raw.terms\n | _ =>\n let head? : Option String := do \n if \n k ∈ tks \n then\n ← stx.reprint\n else\n none\n let argTerms ← args.mapM (terms · (maxDepth?.map (· -1))) \n let argTerms := argTerms.toList.join\n match head? with\n | some head => \n return (head.trim, 0, stx.idents.map (·.1)) ::\n (argTerms.map (fun (s, m, l) => (s, m + 1, l)))\n | none => \n return (argTerms.map (fun (s, m, l) => (s, m + 1, l)))\n \n | _ => pure []\n\nstructure Premises where\n type : String\n defTerms : List <| String × Nat × List Name\n defIdents : List <| Name × Nat\n typeTerms : List <| String × Nat × List Name\n typeIdents : List <| Name × Nat \nderiving Repr, Inhabited\n\ndef Premises.defMainTerms (p: Premises) : List <| String × Nat × List Name :=\n p.defTerms.filter (\n fun (s, _) => s.1.length < 20)\n\ndef Premises.typeMainTerms (p: Premises) : List <| String × Nat × List Name :=\n p.typeTerms.filter (fun (s, _) => (s.splitOn \"=>\").length == 1 \n && (s.splitOn \"↦\").length == 1)\n\n\n\ndef getPremises (name: Name)(maxDepth? : Option Nat := none ) : MetaM <| Premises := do\n let termStx? ← nameDefSyntaxVerbose name\n let term ← mkConstWithLevelParams name\n let type ← inferType term\n let typeView ← Meta.ppExpr type\n let typeStx ← delab type\n let defTerms ← match termStx? with\n | none => pure []\n | some stx => stx.terms maxDepth?\n let defTerms := defTerms.filter (fun (s, _) => s.1.length < 10000\n && !s.contains '\\n')\n let defIdents := match termStx? with\n | none => []\n | some stx => stx.idents maxDepth?\n pure {type := typeView.pretty 10000, defTerms := defTerms, defIdents := defIdents, typeTerms := ← typeStx.raw |>.terms maxDepth?, typeIdents := typeStx.raw |>.idents maxDepth?}\n\n\n-- Testing\n\n\n\ndef showTerms (s: String) : MetaM <| List <| String × Nat × List Name := do\n let c := runParserCategory (← getEnv) `term s\n match c with\n | Except.error e => throwError e\n | Except.ok s => (s.terms)\n\ndef showIdents (s: String) : MetaM <| List <| Name × Nat := do\n let c := runParserCategory (← getEnv) `term s\n match c with\n | Except.error e => throwError e\n | Except.ok s => pure (s.idents)\n\ndef showKinds (s: String) : MetaM <| List String := do\n let c := runParserCategory (← getEnv) `term s\n match c with\n | Except.error e => throwError e\n | Except.ok s => pure (s.kinds)\n\ndef nameDefTerms (name: Name)(maxDepth? : Option Nat := none ) : MetaM <| \n List <| String × Nat × List Name := do\n let stx? ← nameDefSyntax name\n match stx? with\n | none => pure []\n | some stx => (stx.terms maxDepth?)\n\ndef nameDefIdents (name: Name)(maxDepth? : Option Nat := none ) : MetaM <| List <| Name × Nat := do\n let stx? ← nameDefSyntax name\n match stx? with\n | none => pure []\n | some stx => pure (stx.idents maxDepth?)\n\n#check List.join\n\n-- #eval showTerms \"fun n ↦ Nat.succ n\"\n\n-- #eval showIdents \"fun n ↦ Nat.succ n\"\n\n-- #eval showTerms \"fun n ↦ Nat.succ n = n + 1\"\n\n#eval viewSyntax \"match n + 2 with | 0 => 0 | _ => 1\"\n\n-- #eval viewSyntax \"f (n := m)\"\n\ndef zeroOrOne : Nat → Nat\n| 0 => 0\n| _ => 1\n\n#eval nameDefSyntax ``zeroOrOne\n\n-- #eval nameDefSyntax ``Nat.succ_le_succ\n\n#check Lean.Parser.Term.namedArgument\n#check Lean.Parser.Term.matchAlt\n\n\n-- #eval showKinds \"n = n + 1\"\n\n-- def egTerms : MetaM <| List <| String × Nat × List Name := do\n-- let p ← getPremises ``oddExample (some 30) \n-- return p.defMainTerms\n\n-- #eval egTerms\n\n-- def egIdents : MetaM <| List <| Name × Nat:= do\n-- let p ← getPremises ``oddExample (some 50) \n-- return p.defIdents\n\n-- #eval egIdents\n\n-- def egGpIdents : MetaM NameGroups := do\n-- let nd ← egIdents\n-- return groupedNames nd.toArray\n\n-- #eval egGpIdents\n\n-- #check Linarith.lt_irrefl\n\n-- -- #eval nameDefSyntax ``oddExample\n\ndef dataSize : MetaM Nat := do\n let names ← constantNames\n return names.size \n\n-- #eval dataSize\n\ndef boundedDataSize (n: Nat) : MetaM Nat := do\n let names ← constantNames\n let names ← names.filterM (boundedDef n)\n return names.size\n\n-- #eval boundedDataSize 50\n\ndef sampleExtract (n: Nat := 100) : MetaM <|\n List (Name × (List <| String × Nat × List Name) ×\n (List <| Name × Nat)) := do\n let names ← constantNames\n let names := names.toList.take n\n names.mapM (fun n => do \n let p ← nameDefTerms n\n let q ← nameDefIdents n\n pure (n, p, q)\n )\n\ndef batchPremiseExtractM (start stop: Nat) : MetaM Nat := do\n let names ← constantNames\n let premisesFile := System.mkFilePath [\"rawdata\",\n s!\"outer-premises.jsonl\"]\n let h ← IO.FS.Handle.mk premisesFile IO.FS.Mode.append Bool.false\n let names := names.toList.drop start |>.take (stop - start)\n let mut cursor := start\n IO.println s!\"start: {start}, stop: {stop}\"\n for name in names do\n IO.println <| s!\"starting: {cursor} {name}\"\n let premises ← getPremises name (some 30)\n let p := premises.defMainTerms\n let pJson := p.map \n (fun (s, n, l) => \n Json.mkObj [\n (\"term\", s),\n (\"depth\", n),\n (\"local-idents\", Json.arr (\n l.toArray\n |>.filter (fun name => !names.contains name)\n |>.map (fun name : Name =>\n name.toString)))\n ]\n )\n let q:= premises.defIdents\n let q := q.filter (fun (name, _) => names.contains name)\n let qJson := q.map \n (fun (name, n) => \n Json.mkObj [\n (\"name\", name.toString),\n (\"depth\", n)\n ]\n )\n let js := Json.mkObj [\n (\"name\", name.toString),\n (\"type\", premises.type),\n (\"terms\", Json.arr \n pJson.toArray),\n (\"idents\", Json.arr \n qJson.toArray)\n ]\n let out := js.pretty 10000\n if out.length < 9000 then \n h.putStrLn <| out\n IO.println <| s!\"{cursor}. {name} : {premises.type} ({p.length}, {q.length}, {out.length})\"\n cursor := cursor + 1\n return cursor\n\ndef batchPremiseExtractCore (start stop: Nat) : CoreM Nat := \n (batchPremiseExtractM start stop).run'\n\n-- -- #eval sampleExtract\n\n-- theorem imo_1964_q1b : ∀ (n : Nat), (2 ^ n + 1) % 7 ≠ 0\n-- | 0 | 1 | 2 => by decide\n-- | n + 3 => by\n-- rw [pow_add, Nat.add_mod, Nat.mul_mod, show 2 ^ 3 % 7 = 1 from by rfl]\n-- simp [imo_1964_q1b n]\n\n\n-- set_option pp.proofs.withType true in\n-- -- #eval nameDefView ``imo_1964_q1b\n\n-- #eval nameDefView ``imo_1964_q1b\n\n-- -- #eval nameDefViewVerbose ``imo_1964_q1b", "meta": {"author": "siddhartha-gadgil", "repo": "LeanAide", "sha": "7862af73ee2f0be08b20fd3e4148e20bf4a81054", "save_path": "github-repos/lean/siddhartha-gadgil-LeanAide", "path": "github-repos/lean/siddhartha-gadgil-LeanAide/LeanAide-7862af73ee2f0be08b20fd3e4148e20bf4a81054/LeanCodePrompts/ExtrasPremises.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.36296921930155557, "lm_q2_score": 0.04885778295009592, "lm_q1q2_score": 0.01773387133420117}} {"text": "/-\nCopyright (c) 2019 Scott Morrison. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Scott Morrison, Bhavik Mehta\n-/\nimport category_theory.monad.adjunction\nimport category_theory.adjunction.limits\nimport category_theory.limits.preserves.shapes.terminal\n\nnamespace category_theory\nopen category\nopen category_theory.limits\n\nuniverses v₁ v₂ u₁ u₂ -- morphism levels before object levels. See note [category_theory universes].\n\nnamespace monad\n\nvariables {C : Type u₁} [category.{v₁} C]\nvariables {T : monad C}\n\nvariables {J : Type v₁} [small_category J]\n\nnamespace forget_creates_limits\n\nvariables (D : J ⥤ algebra T) (c : cone (D ⋙ forget T)) (t : is_limit c)\n\n/-- (Impl) The natural transformation used to define the new cone -/\n@[simps] def γ : (D ⋙ forget T ⋙ ↑T) ⟶ (D ⋙ forget T) := { app := λ j, (D.obj j).a }\n\n/-- (Impl) This new cone is used to construct the algebra structure -/\n@[simps] def new_cone : cone (D ⋙ forget T) :=\n{ X := T.obj c.X,\n π := (functor.const_comp _ _ ↑T).inv ≫ whisker_right c.π T ≫ (γ D) }\n\n/-- The algebra structure which will be the apex of the new limit cone for `D`. -/\n@[simps] def cone_point : algebra T :=\n{ A := c.X,\n a := t.lift (new_cone D c),\n unit' :=\n begin\n apply t.hom_ext,\n intro j,\n erw [category.assoc, t.fac (new_cone D c), id_comp],\n dsimp,\n erw [id_comp, ← category.assoc, ← T.η.naturality, functor.id_map, category.assoc,\n (D.obj j).unit, comp_id],\n end,\n assoc' :=\n begin\n apply t.hom_ext,\n intro j,\n rw [category.assoc, category.assoc, t.fac (new_cone D c)],\n dsimp,\n erw id_comp,\n slice_lhs 1 2 {rw ← T.μ.naturality},\n slice_lhs 2 3 {rw (D.obj j).assoc},\n slice_rhs 1 2 {rw ← (T : C ⥤ C).map_comp},\n rw t.fac (new_cone D c),\n dsimp,\n erw [id_comp, functor.map_comp, category.assoc]\n end }\n\n/-- (Impl) Construct the lifted cone in `algebra T` which will be limiting. -/\n@[simps] def lifted_cone : cone D :=\n{ X := cone_point D c t,\n π := { app := λ j, { f := c.π.app j },\n naturality' := λ X Y f, by { ext1, dsimp, erw c.w f, simp } } }\n\n/-- (Impl) Prove that the lifted cone is limiting. -/\n@[simps]\ndef lifted_cone_is_limit : is_limit (lifted_cone D c t) :=\n{ lift := λ s,\n { f := t.lift ((forget T).map_cone s),\n h' :=\n begin\n apply t.hom_ext, intro j,\n slice_rhs 2 3 {rw t.fac ((forget T).map_cone s) j},\n dsimp,\n slice_lhs 2 3 {rw t.fac (new_cone D c) j},\n dsimp,\n rw category.id_comp,\n slice_lhs 1 2 {rw ← (T : C ⥤ C).map_comp},\n rw t.fac ((forget T).map_cone s) j,\n exact (s.π.app j).h\n end },\n uniq' := λ s m J,\n begin\n ext1,\n apply t.hom_ext,\n intro j,\n simpa [t.fac (functor.map_cone (forget T) s) j] using congr_arg algebra.hom.f (J j),\n end }\n\nend forget_creates_limits\n\n-- Theorem 5.6.5 from [Riehl][riehl2017]\n/-- The forgetful functor from the Eilenberg-Moore category creates limits. -/\nnoncomputable\ninstance forget_creates_limits : creates_limits (forget T) :=\n{ creates_limits_of_shape := λ J 𝒥, by exactI\n { creates_limit := λ D,\n creates_limit_of_reflects_iso (λ c t,\n { lifted_cone := forget_creates_limits.lifted_cone D c t,\n valid_lift := cones.ext (iso.refl _) (λ j, (id_comp _).symm),\n makes_limit := forget_creates_limits.lifted_cone_is_limit _ _ _ } ) } }\n\n/-- `D ⋙ forget T` has a limit, then `D` has a limit. -/\nlemma has_limit_of_comp_forget_has_limit (D : J ⥤ algebra T) [has_limit (D ⋙ forget T)] :\n has_limit D :=\nhas_limit_of_created D (forget T)\n\nnamespace forget_creates_colimits\n\n-- Let's hide the implementation details in a namespace\nvariables {D : J ⥤ algebra T} (c : cocone (D ⋙ forget T)) (t : is_colimit c)\n\n-- We have a diagram D of shape J in the category of algebras, and we assume that we are given a\n-- colimit for its image D ⋙ forget T under the forgetful functor, say its apex is L.\n\n-- We'll construct a colimiting coalgebra for D, whose carrier will also be L.\n-- To do this, we must find a map TL ⟶ L. Since T preserves colimits, TL is also a colimit.\n-- In particular, it is a colimit for the diagram `(D ⋙ forget T) ⋙ T`\n-- so to construct a map TL ⟶ L it suffices to show that L is the apex of a cocone for this diagram.\n-- In other words, we need a natural transformation from const L to `(D ⋙ forget T) ⋙ T`.\n-- But we already know that L is the apex of a cocone for the diagram `D ⋙ forget T`, so it\n-- suffices to give a natural transformation `((D ⋙ forget T) ⋙ T) ⟶ (D ⋙ forget T)`:\n\n/--\n(Impl)\nThe natural transformation given by the algebra structure maps, used to construct a cocone `c` with\napex `colimit (D ⋙ forget T)`.\n -/\n@[simps] def γ : ((D ⋙ forget T) ⋙ ↑T) ⟶ (D ⋙ forget T) := { app := λ j, (D.obj j).a }\n\n/--\n(Impl)\nA cocone for the diagram `(D ⋙ forget T) ⋙ T` found by composing the natural transformation `γ`\nwith the colimiting cocone for `D ⋙ forget T`.\n-/\n@[simps]\ndef new_cocone : cocone ((D ⋙ forget T) ⋙ ↑T) :=\n{ X := c.X,\n ι := γ ≫ c.ι }\n\nvariables [preserves_colimit (D ⋙ forget T) (T : C ⥤ C)]\n\n/--\n(Impl)\nDefine the map `λ : TL ⟶ L`, which will serve as the structure of the coalgebra on `L`, and\nwe will show is the colimiting object. We use the cocone constructed by `c` and the fact that\n`T` preserves colimits to produce this morphism.\n-/\n@[reducible]\ndef lambda : ((T : C ⥤ C).map_cocone c).X ⟶ c.X :=\n(preserves_colimit.preserves t).desc (new_cocone c)\n\n/-- (Impl) The key property defining the map `λ : TL ⟶ L`. -/\nlemma commuting (j : J) :\nT.map (c.ι.app j) ≫ lambda c t = (D.obj j).a ≫ c.ι.app j :=\nis_colimit.fac (preserves_colimit.preserves t) (new_cocone c) j\n\nvariables [preserves_colimit ((D ⋙ forget T) ⋙ ↑T) (T : C ⥤ C)]\n\n/--\n(Impl)\nConstruct the colimiting algebra from the map `λ : TL ⟶ L` given by `lambda`. We are required to\nshow it satisfies the two algebra laws, which follow from the algebra laws for the image of `D` and\nour `commuting` lemma.\n-/\n@[simps] def cocone_point :\nalgebra T :=\n{ A := c.X,\n a := lambda c t,\n unit' :=\n begin\n apply t.hom_ext,\n intro j,\n erw [comp_id, ← category.assoc, T.η.naturality, category.assoc, commuting, ← category.assoc],\n erw algebra.unit, apply id_comp\n end,\n assoc' :=\n begin\n apply is_colimit.hom_ext (preserves_colimit.preserves (preserves_colimit.preserves t)),\n intro j,\n erw [← category.assoc, T.μ.naturality, ← functor.map_cocone_ι_app, category.assoc,\n is_colimit.fac _ (new_cocone c) j],\n rw ← category.assoc,\n erw [← functor.map_comp, commuting],\n dsimp,\n erw [← category.assoc, algebra.assoc, category.assoc, functor.map_comp, category.assoc,\n commuting],\n apply_instance, apply_instance\n end }\n\n/-- (Impl) Construct the lifted cocone in `algebra T` which will be colimiting. -/\n@[simps] def lifted_cocone : cocone D :=\n{ X := cocone_point c t,\n ι := { app := λ j, { f := c.ι.app j, h' := commuting _ _ _ },\n naturality' := λ A B f, by { ext1, dsimp, erw [comp_id, c.w] } } }\n\n/-- (Impl) Prove that the lifted cocone is colimiting. -/\n@[simps]\ndef lifted_cocone_is_colimit : is_colimit (lifted_cocone c t) :=\n{ desc := λ s,\n { f := t.desc ((forget T).map_cocone s),\n h' :=\n begin\n dsimp,\n apply is_colimit.hom_ext (preserves_colimit.preserves t),\n intro j,\n rw ← category.assoc, erw ← functor.map_comp,\n erw t.fac',\n rw ← category.assoc, erw forget_creates_colimits.commuting,\n rw category.assoc, rw t.fac',\n apply algebra.hom.h,\n apply_instance\n end },\n uniq' := λ s m J,\n by { ext1, apply t.hom_ext, intro j, simpa using congr_arg algebra.hom.f (J j) } }\n\nend forget_creates_colimits\n\nopen forget_creates_colimits\n\n-- TODO: the converse of this is true as well\n/--\nThe forgetful functor from the Eilenberg-Moore category for a monad creates any colimit\nwhich the monad itself preserves.\n-/\nnoncomputable\ninstance forget_creates_colimit (D : J ⥤ algebra T)\n [preserves_colimit (D ⋙ forget T) (T : C ⥤ C)]\n [preserves_colimit ((D ⋙ forget T) ⋙ ↑T) (T : C ⥤ C)] :\n creates_colimit D (forget T) :=\ncreates_colimit_of_reflects_iso $ λ c t,\n{ lifted_cocone :=\n { X := cocone_point c t,\n ι :=\n { app := λ j, { f := c.ι.app j, h' := commuting _ _ _ },\n naturality' := λ A B f, by { ext1, dsimp, erw [comp_id, c.w] } } },\n valid_lift := cocones.ext (iso.refl _) (by tidy),\n makes_colimit := lifted_cocone_is_colimit _ _ }\n\nnoncomputable\ninstance forget_creates_colimits_of_shape\n [preserves_colimits_of_shape J (T : C ⥤ C)] :\n creates_colimits_of_shape J (forget T) :=\n{ creates_colimit := λ K, by apply_instance }\n\nnoncomputable\ninstance forget_creates_colimits\n [preserves_colimits (T : C ⥤ C)] :\n creates_colimits (forget T) :=\n{ creates_colimits_of_shape := λ J 𝒥₁, by apply_instance }\n\n/--\nFor `D : J ⥤ algebra T`, `D ⋙ forget T` has a colimit, then `D` has a colimit provided colimits\nof shape `J` are preserved by `T`.\n-/\nlemma forget_creates_colimits_of_monad_preserves\n [preserves_colimits_of_shape J (T : C ⥤ C)] (D : J ⥤ algebra T) [has_colimit (D ⋙ forget T)] :\nhas_colimit D :=\nhas_colimit_of_created D (forget T)\n\nend monad\n\nvariables {C : Type u₁} [category.{v₁} C] {D : Type u₂} [category.{v₁} D]\nvariables {J : Type v₁} [small_category J]\n\ninstance comp_comparison_forget_has_limit\n (F : J ⥤ D) (R : D ⥤ C) [monadic_right_adjoint R] [has_limit (F ⋙ R)] :\n has_limit ((F ⋙ monad.comparison (adjunction.of_right_adjoint R)) ⋙ monad.forget _) :=\n@has_limit_of_iso _ _ _ _ (F ⋙ R) _ _\n (iso_whisker_left F (monad.comparison_forget (adjunction.of_right_adjoint R)).symm)\n\ninstance comp_comparison_has_limit\n (F : J ⥤ D) (R : D ⥤ C) [monadic_right_adjoint R] [has_limit (F ⋙ R)] :\n has_limit (F ⋙ monad.comparison (adjunction.of_right_adjoint R)) :=\nmonad.has_limit_of_comp_forget_has_limit (F ⋙ monad.comparison (adjunction.of_right_adjoint R))\n\n/-- Any monadic functor creates limits. -/\nnoncomputable\ndef monadic_creates_limits (R : D ⥤ C) [monadic_right_adjoint R] :\n creates_limits R :=\ncreates_limits_of_nat_iso (monad.comparison_forget (adjunction.of_right_adjoint R))\n\n/--\nThe forgetful functor from the Eilenberg-Moore category for a monad creates any colimit\nwhich the monad itself preserves.\n-/\nnoncomputable\ndef monadic_creates_colimit_of_preserves_colimit (R : D ⥤ C) (K : J ⥤ D)\n [monadic_right_adjoint R]\n [preserves_colimit (K ⋙ R) (left_adjoint R ⋙ R)]\n [preserves_colimit ((K ⋙ R) ⋙ left_adjoint R ⋙ R) (left_adjoint R ⋙ R)] :\n creates_colimit K R :=\nbegin\n apply creates_colimit_of_nat_iso (monad.comparison_forget (adjunction.of_right_adjoint R)),\n apply category_theory.comp_creates_colimit _ _,\n apply_instance,\n let i : ((K ⋙ monad.comparison (adjunction.of_right_adjoint R)) ⋙ monad.forget _) ≅ K ⋙ R :=\n functor.associator _ _ _ ≪≫\n iso_whisker_left K (monad.comparison_forget (adjunction.of_right_adjoint R)),\n apply category_theory.monad.forget_creates_colimit _,\n { dsimp,\n refine preserves_colimit_of_iso_diagram _ i.symm },\n { dsimp,\n refine preserves_colimit_of_iso_diagram _ (iso_whisker_right i (left_adjoint R ⋙ R)).symm },\nend\n\n/-- A monadic functor creates any colimits of shapes it preserves. -/\nnoncomputable\ndef monadic_creates_colimits_of_shape_of_preserves_colimits_of_shape (R : D ⥤ C)\n [monadic_right_adjoint R] [preserves_colimits_of_shape J R] : creates_colimits_of_shape J R :=\nbegin\n have : preserves_colimits_of_shape J (left_adjoint R ⋙ R),\n { apply category_theory.limits.comp_preserves_colimits_of_shape _ _,\n { haveI := adjunction.left_adjoint_preserves_colimits (adjunction.of_right_adjoint R),\n apply_instance },\n apply_instance },\n exactI ⟨λ K, monadic_creates_colimit_of_preserves_colimit _ _⟩,\nend\n\n/-- A monadic functor creates colimits if it preserves colimits. -/\nnoncomputable\ndef monadic_creates_colimits_of_preserves_colimits (R : D ⥤ C) [monadic_right_adjoint R]\n [preserves_colimits R] : creates_colimits R :=\n{ creates_colimits_of_shape := λ J 𝒥₁,\n by exactI monadic_creates_colimits_of_shape_of_preserves_colimits_of_shape _ }\n\nsection\n\nlemma has_limit_of_reflective (F : J ⥤ D) (R : D ⥤ C) [has_limit (F ⋙ R)] [reflective R] :\n has_limit F :=\nby { haveI := monadic_creates_limits R, exact has_limit_of_created F R }\n\n/-- If `C` has limits of shape `J` then any reflective subcategory has limits of shape `J`. -/\nlemma has_limits_of_shape_of_reflective [has_limits_of_shape J C] (R : D ⥤ C) [reflective R] :\n has_limits_of_shape J D :=\n{ has_limit := λ F, has_limit_of_reflective F R }\n\n/-- If `C` has limits then any reflective subcategory has limits. -/\nlemma has_limits_of_reflective (R : D ⥤ C) [has_limits C] [reflective R] : has_limits D :=\n{ has_limits_of_shape := λ J 𝒥₁, by exactI has_limits_of_shape_of_reflective R }\n\n/-- If `C` has colimits of shape `J` then any reflective subcategory has colimits of shape `J`. -/\nlemma has_colimits_of_shape_of_reflective (R : D ⥤ C)\n [reflective R] [has_colimits_of_shape J C] : has_colimits_of_shape J D :=\n{ has_colimit := λ F,\nbegin\n let c := (left_adjoint R).map_cocone (colimit.cocone (F ⋙ R)),\n letI := (adjunction.of_right_adjoint R).left_adjoint_preserves_colimits,\n let t : is_colimit c := is_colimit_of_preserves (left_adjoint R) (colimit.is_colimit _),\n apply has_colimit.mk ⟨_, (is_colimit.precompose_inv_equiv _ _).symm t⟩,\n apply (iso_whisker_left F (as_iso (adjunction.of_right_adjoint R).counit) : _) ≪≫ F.right_unitor,\nend }\n\n/-- If `C` has colimits then any reflective subcategory has colimits. -/\nlemma has_colimits_of_reflective (R : D ⥤ C) [reflective R] [has_colimits C] :\n has_colimits D :=\n{ has_colimits_of_shape := λ J 𝒥, by exactI has_colimits_of_shape_of_reflective R }\n\n/--\nThe reflector always preserves terminal objects. Note this in general doesn't apply to any other\nlimit.\n-/\nnoncomputable def left_adjoint_preserves_terminal_of_reflective\n (R : D ⥤ C) [reflective R] [has_terminal C] :\n preserves_limits_of_shape (discrete pempty) (left_adjoint R) :=\n{ preserves_limit := λ K,\n begin\n letI : has_terminal D := has_limits_of_shape_of_reflective R,\n letI := monadic_creates_limits R,\n letI := category_theory.preserves_limit_of_creates_limit_and_has_limit (functor.empty _) R,\n letI : preserves_limit (functor.empty _) (left_adjoint R),\n { apply preserves_terminal_of_iso,\n apply _ ≪≫ as_iso ((adjunction.of_right_adjoint R).counit.app (⊤_ D)),\n apply (left_adjoint R).map_iso (preserves_terminal.iso R).symm },\n apply preserves_limit_of_iso_diagram (left_adjoint R) (functor.unique_from_empty _).symm,\n end }\n\nend\nend category_theory\n", "meta": {"author": "JLimperg", "repo": "aesop3", "sha": "a4a116f650cc7403428e72bd2e2c4cda300fe03f", "save_path": "github-repos/lean/JLimperg-aesop3", "path": "github-repos/lean/JLimperg-aesop3/aesop3-a4a116f650cc7403428e72bd2e2c4cda300fe03f/src/category_theory/monad/limits.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.03622005222376973, "lm_q1q2_score": 0.017685650077614728}} {"text": "/-\nCopyright (c) 2018 Chris Hughes. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Chris Hughes, Abhimanyu Pallavi Sudhir\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.default\nimport Mathlib.algebra.geom_sum\nimport Mathlib.data.nat.choose.sum\nimport Mathlib.data.complex.basic\nimport Mathlib.PostPort\n\nuniverses u_1 u_2 u_3 \n\nnamespace Mathlib\n\n/-!\n# Exponential, trigonometric and hyperbolic trigonometric functions\n\nThis file contains the definitions of the real and complex exponential, sine, cosine, tangent,\nhyperbolic sine, hyperbolic cosine, and hyperbolic tangent functions.\n\n-/\n\ntheorem forall_ge_le_of_forall_le_succ {α : Type u_1} [preorder α] (f : ℕ → α) {m : ℕ}\n (h : ∀ (n : ℕ), n ≥ m → f (Nat.succ n) ≤ f n) {l : ℕ} (k : ℕ) (H : k ≥ m) : k ≤ l → f l ≤ f k :=\n sorry\n\ntheorem is_cau_of_decreasing_bounded {α : Type u_1} [linear_ordered_field α] [archimedean α]\n (f : ℕ → α) {a : α} {m : ℕ} (ham : ∀ (n : ℕ), n ≥ m → abs (f n) ≤ a)\n (hnm : ∀ (n : ℕ), n ≥ m → f (Nat.succ n) ≤ f n) : is_cau_seq abs f :=\n sorry\n\ntheorem is_cau_of_mono_bounded {α : Type u_1} [linear_ordered_field α] [archimedean α] (f : ℕ → α)\n {a : α} {m : ℕ} (ham : ∀ (n : ℕ), n ≥ m → abs (f n) ≤ a)\n (hnm : ∀ (n : ℕ), n ≥ m → f n ≤ f (Nat.succ n)) : is_cau_seq abs f :=\n sorry\n\ntheorem is_cau_series_of_abv_le_cau {α : Type u_1} {β : Type u_2} [ring β] [linear_ordered_field α]\n {abv : β → α} [is_absolute_value abv] {f : ℕ → β} {g : ℕ → α} (n : ℕ) :\n (∀ (m : ℕ), n ≤ m → abv (f m) ≤ g m) →\n (is_cau_seq abs fun (n : ℕ) => finset.sum (finset.range n) fun (i : ℕ) => g i) →\n is_cau_seq abv fun (n : ℕ) => finset.sum (finset.range n) fun (i : ℕ) => f i :=\n sorry\n\ntheorem is_cau_series_of_abv_cau {α : Type u_1} {β : Type u_2} [ring β] [linear_ordered_field α]\n {abv : β → α} [is_absolute_value abv] {f : ℕ → β} :\n (is_cau_seq abs fun (m : ℕ) => finset.sum (finset.range m) fun (n : ℕ) => abv (f n)) →\n is_cau_seq abv fun (m : ℕ) => finset.sum (finset.range m) fun (n : ℕ) => f n :=\n is_cau_series_of_abv_le_cau 0 fun (n : ℕ) (h : 0 ≤ n) => le_refl (abv (f n))\n\ntheorem is_cau_geo_series {α : Type u_1} [linear_ordered_field α] [archimedean α] {β : Type u_2}\n [field β] {abv : β → α} [is_absolute_value abv] (x : β) (hx1 : abv x < 1) :\n is_cau_seq abv fun (n : ℕ) => finset.sum (finset.range n) fun (m : ℕ) => x ^ m :=\n sorry\n\ntheorem is_cau_geo_series_const {α : Type u_1} [linear_ordered_field α] [archimedean α] (a : α)\n {x : α} (hx1 : abs x < 1) :\n is_cau_seq abs fun (m : ℕ) => finset.sum (finset.range m) fun (n : ℕ) => a * x ^ n :=\n sorry\n\ntheorem series_ratio_test {α : Type u_1} {β : Type u_2} [ring β] [linear_ordered_field α]\n [archimedean α] {abv : β → α} [is_absolute_value abv] {f : ℕ → β} (n : ℕ) (r : α) (hr0 : 0 ≤ r)\n (hr1 : r < 1) (h : ∀ (m : ℕ), n ≤ m → abv (f (Nat.succ m)) ≤ r * abv (f m)) :\n is_cau_seq abv fun (m : ℕ) => finset.sum (finset.range m) fun (n : ℕ) => f n :=\n sorry\n\ntheorem sum_range_diag_flip {α : Type u_1} [add_comm_monoid α] (n : ℕ) (f : ℕ → ℕ → α) :\n (finset.sum (finset.range n)\n fun (m : ℕ) => finset.sum (finset.range (m + 1)) fun (k : ℕ) => f k (m - k)) =\n finset.sum (finset.range n)\n fun (m : ℕ) => finset.sum (finset.range (n - m)) fun (k : ℕ) => f m k :=\n sorry\n\ntheorem sum_range_sub_sum_range {α : Type u_1} [add_comm_group α] {f : ℕ → α} {n : ℕ} {m : ℕ}\n (hnm : n ≤ m) :\n ((finset.sum (finset.range m) fun (k : ℕ) => f k) -\n finset.sum (finset.range n) fun (k : ℕ) => f k) =\n finset.sum (finset.filter (fun (k : ℕ) => n ≤ k) (finset.range m)) fun (k : ℕ) => f k :=\n sorry\n\ntheorem abv_sum_le_sum_abv {α : Type u_1} {β : Type u_2} [ring β] [linear_ordered_field α]\n {abv : β → α} [is_absolute_value abv] {γ : Type u_3} (f : γ → β) (s : finset γ) :\n abv (finset.sum s fun (k : γ) => f k) ≤ finset.sum s fun (k : γ) => abv (f k) :=\n sorry\n\ntheorem cauchy_product {α : Type u_1} {β : Type u_2} [ring β] [linear_ordered_field α] {abv : β → α}\n [is_absolute_value abv] {a : ℕ → β} {b : ℕ → β}\n (ha : is_cau_seq abs fun (m : ℕ) => finset.sum (finset.range m) fun (n : ℕ) => abv (a n))\n (hb : is_cau_seq abv fun (m : ℕ) => finset.sum (finset.range m) fun (n : ℕ) => b n) (ε : α)\n (ε0 : 0 < ε) :\n ∃ (i : ℕ),\n ∀ (j : ℕ),\n j ≥ i →\n abv\n (((finset.sum (finset.range j) fun (k : ℕ) => a k) *\n finset.sum (finset.range j) fun (n : ℕ) => b n) -\n finset.sum (finset.range j)\n fun (n : ℕ) =>\n finset.sum (finset.range (n + 1)) fun (m : ℕ) => a m * b (n - m)) <\n ε :=\n sorry\n\nnamespace complex\n\n\ntheorem is_cau_abs_exp (z : ℂ) :\n is_cau_seq abs\n fun (n : ℕ) =>\n finset.sum (finset.range n) fun (m : ℕ) => abs (z ^ m / ↑(nat.factorial m)) :=\n sorry\n\ntheorem is_cau_exp (z : ℂ) :\n is_cau_seq abs\n fun (n : ℕ) => finset.sum (finset.range n) fun (m : ℕ) => z ^ m / ↑(nat.factorial m) :=\n is_cau_series_of_abv_cau (is_cau_abs_exp z)\n\n/-- The Cauchy sequence consisting of partial sums of the Taylor series of\nthe complex exponential function -/\ndef exp' (z : ℂ) : cau_seq ℂ abs :=\n { val := fun (n : ℕ) => finset.sum (finset.range n) fun (m : ℕ) => z ^ m / ↑(nat.factorial m),\n property := is_cau_exp z }\n\n/-- The complex exponential function, defined via its Taylor series -/\ndef exp (z : ℂ) : ℂ := cau_seq.lim (exp' z)\n\n/-- The complex sine function, defined via `exp` -/\ndef sin (z : ℂ) : ℂ := (exp (-z * I) - exp (z * I)) * I / bit0 1\n\n/-- The complex cosine function, defined via `exp` -/\ndef cos (z : ℂ) : ℂ := (exp (z * I) + exp (-z * I)) / bit0 1\n\n/-- The complex tangent function, defined as `sin z / cos z` -/\ndef tan (z : ℂ) : ℂ := sin z / cos z\n\n/-- The complex hyperbolic sine function, defined via `exp` -/\ndef sinh (z : ℂ) : ℂ := (exp z - exp (-z)) / bit0 1\n\n/-- The complex hyperbolic cosine function, defined via `exp` -/\ndef cosh (z : ℂ) : ℂ := (exp z + exp (-z)) / bit0 1\n\n/-- The complex hyperbolic tangent function, defined as `sinh z / cosh z` -/\ndef tanh (z : ℂ) : ℂ := sinh z / cosh z\n\nend complex\n\n\nnamespace real\n\n\n/-- The real exponential function, defined as the real part of the complex exponential -/\ndef exp (x : ℝ) : ℝ := complex.re (complex.exp ↑x)\n\n/-- The real sine function, defined as the real part of the complex sine -/\ndef sin (x : ℝ) : ℝ := complex.re (complex.sin ↑x)\n\n/-- The real cosine function, defined as the real part of the complex cosine -/\ndef cos (x : ℝ) : ℝ := complex.re (complex.cos ↑x)\n\n/-- The real tangent function, defined as the real part of the complex tangent -/\ndef tan (x : ℝ) : ℝ := complex.re (complex.tan ↑x)\n\n/-- The real hypebolic sine function, defined as the real part of the complex hyperbolic sine -/\ndef sinh (x : ℝ) : ℝ := complex.re (complex.sinh ↑x)\n\n/-- The real hypebolic cosine function, defined as the real part of the complex hyperbolic cosine -/\ndef cosh (x : ℝ) : ℝ := complex.re (complex.cosh ↑x)\n\n/-- The real hypebolic tangent function, defined as the real part of\nthe complex hyperbolic tangent -/\ndef tanh (x : ℝ) : ℝ := complex.re (complex.tanh ↑x)\n\nend real\n\n\nnamespace complex\n\n\n@[simp] theorem exp_zero : exp 0 = 1 := sorry\n\ntheorem exp_add (x : ℂ) (y : ℂ) : exp (x + y) = exp x * exp y := sorry\n\ntheorem exp_list_sum (l : List ℂ) : exp (list.sum l) = list.prod (list.map exp l) :=\n monoid_hom.map_list_prod (monoid_hom.mk exp exp_zero exp_add) l\n\ntheorem exp_multiset_sum (s : multiset ℂ) :\n exp (multiset.sum s) = multiset.prod (multiset.map exp s) :=\n monoid_hom.map_multiset_prod (monoid_hom.mk exp exp_zero exp_add) s\n\ntheorem exp_sum {α : Type u_1} (s : finset α) (f : α → ℂ) :\n exp (finset.sum s fun (x : α) => f x) = finset.prod s fun (x : α) => exp (f x) :=\n monoid_hom.map_prod (monoid_hom.mk exp exp_zero exp_add) f s\n\ntheorem exp_nat_mul (x : ℂ) (n : ℕ) : exp (↑n * x) = exp x ^ n := sorry\n\ntheorem exp_ne_zero (x : ℂ) : exp x ≠ 0 := sorry\n\ntheorem exp_neg (x : ℂ) : exp (-x) = (exp x⁻¹) := sorry\n\ntheorem exp_sub (x : ℂ) (y : ℂ) : exp (x - y) = exp x / exp y := sorry\n\n@[simp] theorem exp_conj (x : ℂ) : exp (coe_fn conj x) = coe_fn conj (exp x) := sorry\n\n@[simp] theorem of_real_exp_of_real_re (x : ℝ) : ↑(re (exp ↑x)) = exp ↑x :=\n iff.mp eq_conj_iff_re\n (eq.mpr (id (Eq._oldrec (Eq.refl (coe_fn conj (exp ↑x) = exp ↑x)) (Eq.symm (exp_conj ↑x))))\n (eq.mpr (id (Eq._oldrec (Eq.refl (exp (coe_fn conj ↑x) = exp ↑x)) (conj_of_real x)))\n (Eq.refl (exp ↑x))))\n\n@[simp] theorem of_real_exp (x : ℝ) : ↑(real.exp x) = exp ↑x := of_real_exp_of_real_re x\n\n@[simp] theorem exp_of_real_im (x : ℝ) : im (exp ↑x) = 0 :=\n eq.mpr (id (Eq._oldrec (Eq.refl (im (exp ↑x) = 0)) (Eq.symm (of_real_exp_of_real_re x))))\n (eq.mpr (id (Eq._oldrec (Eq.refl (im ↑(re (exp ↑x)) = 0)) (of_real_im (re (exp ↑x)))))\n (Eq.refl 0))\n\ntheorem exp_of_real_re (x : ℝ) : re (exp ↑x) = real.exp x := rfl\n\ntheorem two_sinh (x : ℂ) : bit0 1 * sinh x = exp x - exp (-x) :=\n mul_div_cancel' (exp x - exp (-x)) two_ne_zero'\n\ntheorem two_cosh (x : ℂ) : bit0 1 * cosh x = exp x + exp (-x) :=\n mul_div_cancel' (exp x + exp (-x)) two_ne_zero'\n\n@[simp] theorem sinh_zero : sinh 0 = 0 := sorry\n\n@[simp] theorem sinh_neg (x : ℂ) : sinh (-x) = -sinh x := sorry\n\ntheorem sinh_add (x : ℂ) (y : ℂ) : sinh (x + y) = sinh x * cosh y + cosh x * sinh y := sorry\n\n@[simp] theorem cosh_zero : cosh 0 = 1 := sorry\n\n@[simp] theorem cosh_neg (x : ℂ) : cosh (-x) = cosh x := sorry\n\ntheorem cosh_add (x : ℂ) (y : ℂ) : cosh (x + y) = cosh x * cosh y + sinh x * sinh y := sorry\n\ntheorem sinh_sub (x : ℂ) (y : ℂ) : sinh (x - y) = sinh x * cosh y - cosh x * sinh y := sorry\n\ntheorem cosh_sub (x : ℂ) (y : ℂ) : cosh (x - y) = cosh x * cosh y - sinh x * sinh y := sorry\n\ntheorem sinh_conj (x : ℂ) : sinh (coe_fn conj x) = coe_fn conj (sinh x) := sorry\n\n@[simp] theorem of_real_sinh_of_real_re (x : ℝ) : ↑(re (sinh ↑x)) = sinh ↑x :=\n iff.mp eq_conj_iff_re\n (eq.mpr (id (Eq._oldrec (Eq.refl (coe_fn conj (sinh ↑x) = sinh ↑x)) (Eq.symm (sinh_conj ↑x))))\n (eq.mpr (id (Eq._oldrec (Eq.refl (sinh (coe_fn conj ↑x) = sinh ↑x)) (conj_of_real x)))\n (Eq.refl (sinh ↑x))))\n\n@[simp] theorem of_real_sinh (x : ℝ) : ↑(real.sinh x) = sinh ↑x := of_real_sinh_of_real_re x\n\n@[simp] theorem sinh_of_real_im (x : ℝ) : im (sinh ↑x) = 0 :=\n eq.mpr (id (Eq._oldrec (Eq.refl (im (sinh ↑x) = 0)) (Eq.symm (of_real_sinh_of_real_re x))))\n (eq.mpr (id (Eq._oldrec (Eq.refl (im ↑(re (sinh ↑x)) = 0)) (of_real_im (re (sinh ↑x)))))\n (Eq.refl 0))\n\ntheorem sinh_of_real_re (x : ℝ) : re (sinh ↑x) = real.sinh x := rfl\n\ntheorem cosh_conj (x : ℂ) : cosh (coe_fn conj x) = coe_fn conj (cosh x) := sorry\n\n@[simp] theorem of_real_cosh_of_real_re (x : ℝ) : ↑(re (cosh ↑x)) = cosh ↑x :=\n iff.mp eq_conj_iff_re\n (eq.mpr (id (Eq._oldrec (Eq.refl (coe_fn conj (cosh ↑x) = cosh ↑x)) (Eq.symm (cosh_conj ↑x))))\n (eq.mpr (id (Eq._oldrec (Eq.refl (cosh (coe_fn conj ↑x) = cosh ↑x)) (conj_of_real x)))\n (Eq.refl (cosh ↑x))))\n\n@[simp] theorem of_real_cosh (x : ℝ) : ↑(real.cosh x) = cosh ↑x := of_real_cosh_of_real_re x\n\n@[simp] theorem cosh_of_real_im (x : ℝ) : im (cosh ↑x) = 0 :=\n eq.mpr (id (Eq._oldrec (Eq.refl (im (cosh ↑x) = 0)) (Eq.symm (of_real_cosh_of_real_re x))))\n (eq.mpr (id (Eq._oldrec (Eq.refl (im ↑(re (cosh ↑x)) = 0)) (of_real_im (re (cosh ↑x)))))\n (Eq.refl 0))\n\ntheorem cosh_of_real_re (x : ℝ) : re (cosh ↑x) = real.cosh x := rfl\n\ntheorem tanh_eq_sinh_div_cosh (x : ℂ) : tanh x = sinh x / cosh x := rfl\n\n@[simp] theorem tanh_zero : tanh 0 = 0 := sorry\n\n@[simp] theorem tanh_neg (x : ℂ) : tanh (-x) = -tanh x :=", "meta": {"author": "AurelienSaue", "repo": "Mathlib4_auto", "sha": "590df64109b08190abe22358fabc3eae000943f2", "save_path": "github-repos/lean/AurelienSaue-Mathlib4_auto", "path": "github-repos/lean/AurelienSaue-Mathlib4_auto/Mathlib4_auto-590df64109b08190abe22358fabc3eae000943f2/Mathlib/data/complex/exponential_auto.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42632159254749036, "lm_q2_score": 0.041462269158095026, "lm_q1q2_score": 0.017676260618111762}} {"text": "import topology.category.Profinite.cofiltered_limit\nimport topology.discrete_quotient\n\nimport for_mathlib.order\n\nnoncomputable theory\n\nopen_locale classical\n\nnamespace Profinite\n\nopen category_theory\nopen category_theory.limits\n\nuniverse u\n\nvariables {J : Type u} [semilattice_inf J] (F : J ⥤ Profinite.{u}) (C : cone F)\n\nlemma image_eq (hC : is_limit C) (i : J) :\n set.range (C.π.app i) = ⋂ (j : J) (h : j ≤ i), set.range (F.map (hom_of_le h)) :=\nbegin\n refine le_antisymm _ _,\n { apply set.subset_Inter,\n intros j,\n apply set.subset_Inter,\n intros hj,\n rw ← C.w (hom_of_le hj),\n apply set.range_comp_subset_range },\n { rintro x hx,\n have cond : ∀ (j : J) (hj : j ≤ i), ∃ y : F.obj j, (F.map (hom_of_le hj)) y = x,\n { intros j hj,\n exact hx _ ⟨j,rfl⟩ _ ⟨hj, rfl⟩ },\n let Js := Σ' (a b : J), a ≤ b,\n let P := Π (j : J), F.obj j,\n let Us : Js → set P := λ e, { p | F.map (hom_of_le e.2.2) (p (e.1)) = p (e.2.1) ∧ p i = x},\n have hP : (_root_.is_compact (set.univ : set P)) := compact_univ,\n have hh := hP.inter_Inter_nonempty Us _ _,\n { rcases hh with ⟨z,hz⟩,\n let IC : (limit_cone F) ≅ C := (limit_cone_is_limit F).unique_up_to_iso hC,\n let ICX : (limit_cone F).X ≅ C.X := (cones.forget _).map_iso IC,\n let z : (limit_cone F).X := ⟨z,_⟩,\n swap,\n { intros a b h,\n convert (hz.2 _ ⟨⟨a, b, le_of_hom h⟩, rfl⟩).1 },\n use ICX.hom z,\n change (hC.lift _ ≫ _) _ = _,\n rw hC.fac,\n exact (hz.2 _ ⟨⟨i,i,le_refl _⟩,rfl⟩).2 },\n { intros i,\n refine is_closed.inter (is_closed_eq _ _) (is_closed_eq _ _);\n continuity },\n { have : ∀ e : J, nonempty (F.obj e),\n { intros e,\n rcases cond (e ⊓ i) inf_le_right with ⟨y,rfl⟩,\n use F.map (hom_of_le inf_le_left) y },\n haveI : ∀ j : J, inhabited (F.obj j) :=\n by {intros j, refine ⟨nonempty.some (this j)⟩},\n intros G,\n let GG := G.image (λ e : Js, e.1),\n haveI : inhabited J := ⟨i⟩,\n have := exists_le_finset (insert i GG),\n obtain ⟨j0,hj0⟩ := this,\n obtain ⟨x0,rfl⟩ := cond j0 (hj0 _ (finset.mem_insert_self _ _)),\n let z : P := λ e, if h : j0 ≤ e then F.map (hom_of_le h) x0 else default,\n use z,\n refine ⟨trivial, _⟩,\n rintros S ⟨e,rfl⟩,\n rintro T ⟨k,rfl⟩,\n dsimp [z],\n refine ⟨_, by erw dif_pos⟩,\n have : j0 ≤ e.fst,\n { apply hj0,\n apply finset.mem_insert_of_mem,\n rw finset.mem_image,\n refine ⟨e,k,rfl⟩ },\n erw [dif_pos this, dif_pos (le_trans this e.2.2)],\n change (F.map _ ≫ F.map _) _ = _,\n rw ← F.map_comp,\n refl } }\nend\n\nset_option pp.proofs true\n\nlemma image_stabilizes [inhabited J] [∀ i, fintype (F.obj i)]\n (i : J) : ∃ (j : J) (hj : j ≤ i), ∀ (k : J) (hk : k ≤ j),\n set.range (F.map (hom_of_le $ le_trans hk hj)) =\n set.range (F.map (hom_of_le hj)) :=\nbegin\n have := eventually_constant i\n (λ e he, set.range (F.map (hom_of_le he))) _,\n swap,\n { intros a b ha hb h,\n dsimp,\n have : hom_of_le ha = (hom_of_le h) ≫ (hom_of_le hb) := rfl,\n rw [this, F.map_comp, Profinite.coe_comp],\n apply set.range_comp_subset_range },\n obtain ⟨j0,hj0,hh⟩ := this,\n use j0, use hj0,\n exact hh,\nend\n\n/-- The images of the transition maps stabilize, in which case they agree with\nthe image of the cone point. -/\ntheorem exists_image [inhabited J] [∀ i, fintype (F.obj i)]\n (hC : is_limit C) (i : J) : ∃ (j : J) (hj : j ≤ i),\n set.range (C.π.app i) = set.range (F.map $ hom_of_le $ hj) :=\nbegin\n have := Inter_eq i (λ e he, set.range (F.map (hom_of_le he))) _,\n swap,\n { intros a b ha hb hh,\n dsimp,\n have : hom_of_le ha = hom_of_le hh ≫ hom_of_le hb, refl,\n rw [this, F.map_comp, Profinite.coe_comp],\n apply set.range_comp_subset_range },\n obtain ⟨j0,hj0,hh⟩ := this,\n dsimp at hh,\n use j0, use hj0,\n rw [image_eq _ _ hC, ← hh],\nend\n\nend Profinite\n", "meta": {"author": "leanprover-community", "repo": "lean-liquid", "sha": "92f188bd17f34dbfefc92a83069577f708851aec", "save_path": "github-repos/lean/leanprover-community-lean-liquid", "path": "github-repos/lean/leanprover-community-lean-liquid/lean-liquid-92f188bd17f34dbfefc92a83069577f708851aec/src/for_mathlib/Profinite/clopen_limit.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4921881357207955, "lm_q2_score": 0.035678547673460216, "lm_q1q2_score": 0.01756055786462591}} {"text": "import Lean\n\nexample : True := by\n apply True.intro\n --^ textDocument/hover\n\nexample : True := by\n simp [True.intro]\n --^ textDocument/hover\n\nexample (n : Nat) : True := by\n match n with\n | Nat.zero => _\n --^ textDocument/hover\n | n + 1 => _\n\n\n/-- My tactic -/\nmacro \"mytac\" o:\"only\"? e:term : tactic => `(exact $e)\n\nexample : True := by\n mytac only True.intro\n--^ textDocument/hover\n --^ textDocument/hover\n --^ textDocument/hover\n\n/-- My way better tactic -/\nmacro_rules\n | `(tactic| mytac $[only]? $e) => `(apply $e)\n\nexample : True := by\n mytac only True.intro\n--^ textDocument/hover\n\n/-- My ultimate tactic -/\nelab_rules : tactic\n | `(tactic| mytac $[only]? $e) => `(tactic| refine $e) >>= Lean.Elab.Tactic.evalTactic\n\nexample : True := by\n mytac only True.intro\n--^ textDocument/hover\n\n\n/-- My notation -/\nmacro \"mynota\" e:term : term => e\n\n#check mynota 1\n --^ textDocument/hover\n\n/-- My way better notation -/\nmacro_rules\n | `(mynota $e) => `(2 * $e)\n\n#check mynota 1\n --^ textDocument/hover\n\n-- macro_rules take precedence over elab_rules for term/command, so use new syntax\nsyntax \"mynota'\" term : term\n\n/-- My ultimate notation -/\nelab_rules : term\n | `(mynota' $e) => `($e * $e) >>= (Lean.Elab.Term.elabTerm · none)\n\n#check mynota' 1\n --^ textDocument/hover\n\n\n/-- My command -/\nmacro \"mycmd\" e:term : command => `(def hi := $e)\n\nmycmd 1\n--^ textDocument/hover\n\n/-- My way better command -/\nmacro_rules\n | `(mycmd $e) => `(@[inline] def hi := $e)\n\nmycmd 1\n--^ textDocument/hover\n\nsyntax \"mycmd'\" term : command\n/-- My ultimate command -/\nelab_rules : command\n | `(mycmd' $e) => `(/-- hi -/ @[inline] def hi := $e) >>= Lean.Elab.Command.elabCommand\n\nmycmd' 1\n--^ textDocument/hover\n\n\n#check ({ a := }) -- should not show `sorry`\n --^ textDocument/hover\n\nexample : True := by\n simp [id True.intro]\n --^ textDocument/hover\n --^ textDocument/hover\n\n\nexample : Id Nat := do\n let mut n := 1\n n := 2\n--^ textDocument/hover\n n\n", "meta": {"author": "subfish-zhou", "repo": "leanprover-zh_CN.github.io", "sha": "8b2985d4a3d458ceda9361ac454c28168d920d3f", "save_path": "github-repos/lean/subfish-zhou-leanprover-zh_CN.github.io", "path": "github-repos/lean/subfish-zhou-leanprover-zh_CN.github.io/leanprover-zh_CN.github.io-8b2985d4a3d458ceda9361ac454c28168d920d3f/tests/lean/interactive/hover.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38121956625614994, "lm_q2_score": 0.046033905343956086, "lm_q1q2_score": 0.017549025428299603}} {"text": "/- Separate compilation and syntactic linking -/\n\nimport .ast .maps .lib\n\n/- This file follows \"approach A\" from the paper\n \"Lightweight Verification of Separate Compilation\"\n by Kang, Kim, Hur, Dreyer and Vafeiadis, POPL 2016. -/\n\n\nnamespace linking\nopen ast maps\n\n/- * Syntactic linking -/\n\n/- A syntactic element [A] supports syntactic linking if it is equipped with the following:\n- a partial binary operator [link] that produces the result of linking two elements,\n or fails if they cannot be linked (e.g. two definitions that are incompatible);\n- a preorder [linkorder] with the meaning that [linkorder a1 a2] holds\n if [a2] can be obtained by linking [a1] with some other syntactic element.\n-/\n\nclass linker (A : Type) :=\n(link : A → A → option A)\n(linkorder : A → A → Prop)\n(linkorder_refl : ∀ x, linkorder x x)\n(linkorder_trans : ∀ {x y z}, linkorder x y → linkorder y z → linkorder x z)\n(link_linkorder : ∀ {x y z}, link x y = some z → linkorder x z ∧ linkorder y z)\nexport linker (link linkorder)\n\n/- Linking variable initializers. We adopt the following conventions:\n- an \"extern\" variable has an empty initialization list;\n- a \"common\" variable has an initialization list of the form [Init_space sz];\n- all other initialization lists correspond to fully defined variables, neither \"common\" nor \"extern\".\n-/\n\ninductive init_class : list init_data → Type\n| extern : init_class []\n| common (sz) : init_class [init_data.space sz]\n| definitive (il) : init_class il\n\ndef classify_init : Π (i : list init_data), init_class i\n| [] := init_class.extern\n| (init_data.space sz :: []) := init_class.common sz\n| i := init_class.definitive i\n\ndef link_varinit (i1 i2 : list init_data) :=\nmatch i1, i2, classify_init i1, classify_init i2 with\n| ._, i2, init_class.extern, _ := some i2\n| i1, ._, _, init_class.extern := some i1\n| ._, i2, init_class.common sz1, _ := if sz1 = init_data.list_size i2 then some i2 else none\n| i1, ._, _, init_class.common sz2 := if sz2 = init_data.list_size i1 then some i1 else none\n| i1, i2, _, _ := none\nend.\n\ninductive linkorder_varinit : list init_data → list init_data → Prop\n| linkorder_varinit_refl (il) : linkorder_varinit il il\n| linkorder_varinit_extern (il) : linkorder_varinit [] il\n| linkorder_varinit_common {sz il} :\n il ≠ list.nil → init_data.list_size il = sz →\n linkorder_varinit [init_data.space sz] il.\n\ninstance Linker_varinit : linker (list init_data) :=\n{ link := link_varinit,\n linkorder := linkorder_varinit,\n linkorder_refl := sorry',\n linkorder_trans := sorry',\n link_linkorder := sorry' }\n\n/- Linking variable definitions. -/\n\ndef link_vardef {V} [linker V] (v1 v2 : globvar V) : option (globvar V) :=\n match link v1.info v2.info with\n | none := none\n | some info :=\n match link v1.init v2.init with\n | none := none\n | some init :=\n if v1.readonly = v2.readonly ∧\n v1.volatile = v2.volatile\n then some { info := info, init := init,\n readonly := v1.readonly,\n volatile := v1.volatile }\n else none\n end\n end.\n\ninductive linkorder_vardef {V} [linker V] : globvar V → globvar V → Prop\n| intro {info1 info2 i1 i2} {ro vo} :\n linkorder info1 info2 →\n linkorder i1 i2 →\n linkorder_vardef ⟨info1, i1, ro, vo⟩ ⟨info2, i2, ro, vo⟩\n\ninstance Linker_vardef {V} [linker V] : linker (globvar V) :=\n{ link := link_vardef,\n linkorder := linkorder_vardef,\n linkorder_refl := sorry',\n linkorder_trans := sorry',\n link_linkorder := sorry' }\n\n/- Linking global definitions -/\n\ndef link_def {F V} [linker F] [linker V] : globdef F V → globdef F V → option (globdef F V)\n| (Gfun f1) (Gfun f2) := Gfun <$> link f1 f2\n| (Gvar v1) (Gvar v2) := Gvar <$> link v1 v2\n| _ _ := none\n\ninductive linkorder_def {F V} [linker F] [linker V] : globdef F V → globdef F V → Prop\n| linkorder_def_fun (fd1 fd2) :\n linkorder fd1 fd2 →\n linkorder_def (Gfun fd1) (Gfun fd2)\n| linkorder_def_var (v1 v2) :\n linkorder v1 v2 →\n linkorder_def (Gvar v1) (Gvar v2).\n\ninstance Linker_def {F V} [linker F] [linker V] : linker (globdef F V) :=\n{ link := link_def,\n linkorder := linkorder_def,\n linkorder_refl := sorry',\n linkorder_trans := sorry',\n link_linkorder := sorry' }\n\n/- Linking two compilation units. Compilation units are represented like\n whole programs using the type [program F V]. If a name has\n a global definition in one unit but not in the other, this definition\n is left unchanged in the result of the link. If a name has\n global definitions in both units, and is public (not static) in both,\n the two definitions are linked as per [Linker_def] above. \n\n If one or both definitions are static (not public), we should ideally\n rename it so that it can be kept unchanged in the result of the link.\n This would require a general notion of renaming of global identifiers\n in programs that we do not have yet. Hence, as a first step, linking\n is undefined if static definitions with the same name appear in both\n compilation units. -/\n\nsection linker_prog\nparameters {F V : Type} [linker F] [linker V]\n\nsection\nparameters (p1 p2 : program F V)\n\ndef dm1 := prog_defmap p1\ndef dm2 := prog_defmap p2\n\ndef link_prog_check (x : ident) (gd1 : globdef F V) :=\nmatch dm2^!x with\n| none := tt\n| some gd2 := (x ∈ p1.public) && (x ∈ p2.public) && (link gd1 gd2).is_some\nend\n\ndef link_prog_merge : option (globdef F V) → option (globdef F V) → option (globdef F V)\n| none o2 := o2\n| o1 none := o1\n| (some gd1) (some gd2) := link gd1 gd2\n\ndef link_prog : option (program F V) :=\nif p1.main = p2.main ∧ PTree.for_all dm1 link_prog_check then\nsome { main := p1.main,\n public := p1.public ++ p2.public,\n defs := PTree.elements $ PTree.combine link_prog_merge dm1 dm2 }\nelse none\n\nlemma link_prog_inv (p) (h : link_prog = some p) :\n p1.main = p2.main\n ∧ (∀ (id : ident) gd1 gd2,\n (dm1^!id) = some gd1 → (dm2^!id) = some gd2 →\n id ∈ p1.public ∧ id ∈ p2.public ∧ ∃ gd, link gd1 gd2 = some gd)\n ∧ p = { main := p1.main,\n public := p1.public ++ p2.public,\n defs := PTree.elements (PTree.combine link_prog_merge dm1 dm2) } := sorry'\n\nlemma link_prog_succeeds (hp : p1.main = p2.main)\n (h : ∀ (id : ident) gd1 gd2,\n (dm1^!id) = some gd1 → (dm2^!id) = some gd2 →\n id ∈ p1.public ∧ id ∈ p2.public ∧ (link gd1 gd2).is_some) :\n link_prog = some {\n main := p1.main,\n public := p1.public ++ p2.public,\n defs := PTree.elements (PTree.combine link_prog_merge dm1 dm2) } := sorry'\n\nlemma prog_defmap_elements (m: PTree (globdef F V)) (pub mn x) :\n (prog_defmap ⟨PTree.elements m, pub, mn⟩ ^! x) = (m^!x) := sorry'\nend\n\ninstance linker_prog : linker (program F V) :=\n{ link := link_prog,\n linkorder := λp1 p2, p1.main = p2.main\n ∧ p1.public ⊆ p2.public\n ∧ ∀ (id : ident) gd1, (prog_defmap p1^!id) = some gd1 →\n ∃ gd2, (prog_defmap p2^!id) = some gd2 ∧\n linkorder gd1 gd2 ∧ (id ∉ p2.public → gd2 = gd1),\n linkorder_refl := sorry',\n linkorder_trans := sorry',\n link_linkorder := sorry' }\n\nlemma prog_defmap_linkorder {p1 p2 : program F V} {id gd1} :\n linkorder p1 p2 →\n (prog_defmap p1^!id) = some gd1 →\n ∃ gd2, (prog_defmap p2^!id) = some gd2 ∧ linkorder gd1 gd2 := sorry'\n\nend linker_prog\n\n/- * Matching between two programs -/\n\n/- The following is a relational presentation of program transformations,\n e.g. [transf_partial_program] from module [AST]. -/\n\n/- To capture the possibility of separate compilation, we parameterize\n the [match_fundef] relation between function definitions with\n a context, e.g. the compilation unit from which the function definition comes.\n This unit is characterized as any program that is in the [linkorder]\n relation with the final, whole program. -/\n\nsection match_program_generic\n\nparameters {C F1 V1 F2 V2 : Type} -- [linker F1] [linker V1]\nparameter match_fundef : C → F1 → F2 → Prop\nparameter match_varinfo : V1 → V2 → Prop\n\ninductive match_globvar : globvar V1 → globvar V2 → Prop\n| mk (i1 i2 init ro vo) :\n match_varinfo i1 i2 →\n match_globvar ⟨i1, init, ro, vo⟩ ⟨i2, init, ro, vo⟩\n\nvariable [linker C]\n\ninductive match_globdef (ctx : C) : globdef F1 V1 → globdef F2 V2 → Prop\n| func (ctx' f1 f2) :\n linkorder ctx' ctx →\n match_fundef ctx' f1 f2 →\n match_globdef (Gfun f1) (Gfun f2)\n| var {v1 v2} :\n match_globvar v1 v2 →\n match_globdef (Gvar v1) (Gvar v2).\n\ndef match_ident_globdef (ctx : C) : ident × globdef F1 V1 → ident × globdef F2 V2 → Prop\n| (i1, g1) (i2, g2) := i1 = i2 ∧ match_globdef ctx g1 g2\n\ndef match_program_gen (ctx : C) (p1 : program F1 V1) (p2 : program F2 V2) : Prop :=\nlist.forall2 (match_ident_globdef ctx) p1.defs p2.defs\n∧ p2.main = p1.main\n∧ p2.public = p1.public\n\ntheorem match_program_defmap {ctx p1 p2} (hm : match_program_gen ctx p1 p2) (id) :\n option.rel (match_globdef ctx) (prog_defmap p1^!id) (prog_defmap p2^!id) := sorry'\n\nlemma match_program_gen_main {ctx p1 p2} (hm : match_program_gen ctx p1 p2) :\n p2.main = p1.main := sorry'\n\nlemma match_program_public {ctx p1 p2} (hm : match_program_gen ctx p1 p2) :\n p2.public = p1.public := sorry'\n\nend match_program_generic\n\n/- In many cases, the context for [match_program_gen] is the source program or \n source compilation unit itself. We provide a specialized definition for this case. -/\n\ndef match_program {F1 V1 F2 V2} [linker F1] [linker V1]\n (match_fundef : program F1 V1 → F1 → F2 → Prop)\n (match_varinfo : V1 → V2 → Prop)\n (p1 : program F1 V1) (p2 : program F2 V2) : Prop :=\nmatch_program_gen match_fundef match_varinfo p1 p1 p2\n\nlemma match_program_main {F1 V1 F2 V2} [linker F1] [linker V1]\n {match_fundef : program F1 V1 → F1 → F2 → Prop}\n {match_varinfo : V1 → V2 → Prop}\n {p1 : program F1 V1} {p2 : program F2 V2}\n (hm : match_program match_fundef match_varinfo p1 p2) : p2.main = p1.main :=\nmatch_program_gen_main _ _ hm\n\nend linking", "meta": {"author": "digama0", "repo": "kremlin", "sha": "d4665929ce9012e93a0b05fc7063b96256bab86f", "save_path": "github-repos/lean/digama0-kremlin", "path": "github-repos/lean/digama0-kremlin/kremlin-d4665929ce9012e93a0b05fc7063b96256bab86f/linking.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4493926344647597, "lm_q2_score": 0.03904829356494251, "lm_q1q2_score": 0.017548015516502837}} {"text": "/-\nCopyright (c) 2016 Johannes Hölzl. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Johannes Hölzl, Mario Carneiro\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.default\nimport Mathlib.logic.basic\nimport Mathlib.data.option.defs\nimport Mathlib.PostPort\n\nuniverses u_1 u_2 u v w u_3 u_4 u_5 u_6 u_7 l \n\nnamespace Mathlib\n\n/-!\n# Miscellaneous function constructions and lemmas\n-/\n\nnamespace function\n\n\n/-- Evaluate a function at an argument. Useful if you want to talk about the partially applied\n `function.eval x : (Π x, β x) → β x`. -/\ndef eval {α : Sort u_1} {β : α → Sort u_2} (x : α) (f : (x : α) → β x) : β x := f x\n\n@[simp] theorem eval_apply {α : Sort u_1} {β : α → Sort u_2} (x : α) (f : (x : α) → β x) :\n eval x f = f x :=\n rfl\n\ntheorem comp_apply {α : Sort u} {β : Sort v} {φ : Sort w} (f : β → φ) (g : α → β) (a : α) :\n comp f g a = f (g a) :=\n rfl\n\ntheorem const_def {α : Sort u_1} {β : Sort u_2} {y : β} : (fun (x : α) => y) = const α y := rfl\n\n@[simp] theorem const_apply {α : Sort u_1} {β : Sort u_2} {y : β} {x : α} : const α y x = y := rfl\n\n@[simp] theorem const_comp {α : Sort u_1} {β : Sort u_2} {γ : Sort u_3} {f : α → β} {c : γ} :\n const β c ∘ f = const α c :=\n rfl\n\n@[simp] theorem comp_const {α : Sort u_1} {β : Sort u_2} {γ : Sort u_3} {f : β → γ} {b : β} :\n f ∘ const α b = const α (f b) :=\n rfl\n\ntheorem id_def {α : Sort u_1} : id = fun (x : α) => x := rfl\n\ntheorem hfunext {α : Sort u} {α' : Sort u} {β : α → Sort v} {β' : α' → Sort v} {f : (a : α) → β a}\n {f' : (a : α') → β' a} (hα : α = α') (h : ∀ (a : α) (a' : α'), a == a' → f a == f' a') :\n f == f' :=\n sorry\n\ntheorem funext_iff {α : Sort u_1} {β : α → Sort u_2} {f₁ : (x : α) → β x} {f₂ : (x : α) → β x} :\n f₁ = f₂ ↔ ∀ (a : α), f₁ a = f₂ a :=\n { mp := fun (h : f₁ = f₂) (a : α) => h ▸ rfl, mpr := funext }\n\n@[simp] theorem injective.eq_iff {α : Sort u_1} {β : Sort u_2} {f : α → β} (I : injective f) {a : α}\n {b : α} : f a = f b ↔ a = b :=\n { mp := I, mpr := congr_arg f }\n\ntheorem injective.eq_iff' {α : Sort u_1} {β : Sort u_2} {f : α → β} (I : injective f) {a : α}\n {b : α} {c : β} (h : f b = c) : f a = c ↔ a = b :=\n h ▸ injective.eq_iff I\n\ntheorem injective.ne {α : Sort u_1} {β : Sort u_2} {f : α → β} (hf : injective f) {a₁ : α}\n {a₂ : α} : a₁ ≠ a₂ → f a₁ ≠ f a₂ :=\n mt fun (h : f a₁ = f a₂) => hf h\n\ntheorem injective.ne_iff {α : Sort u_1} {β : Sort u_2} {f : α → β} (hf : injective f) {x : α}\n {y : α} : f x ≠ f y ↔ x ≠ y :=\n { mp := mt (congr_arg f), mpr := injective.ne hf }\n\ntheorem injective.ne_iff' {α : Sort u_1} {β : Sort u_2} {f : α → β} (hf : injective f) {x : α}\n {y : α} {z : β} (h : f y = z) : f x ≠ z ↔ x ≠ y :=\n h ▸ injective.ne_iff hf\n\n/-- If the co-domain `β` of an injective function `f : α → β` has decidable equality, then\nthe domain `α` also has decidable equality. -/\ndef injective.decidable_eq {α : Sort u_1} {β : Sort u_2} {f : α → β} [DecidableEq β]\n (I : injective f) : DecidableEq α :=\n fun (a b : α) => decidable_of_iff (f a = f b) (injective.eq_iff I)\n\ntheorem injective.of_comp {α : Sort u_1} {β : Sort u_2} {γ : Sort u_3} {f : α → β} {g : γ → α}\n (I : injective (f ∘ g)) : injective g :=\n fun (x y : γ) (h : g x = g y) => I ((fun (this : f (g x) = f (g y)) => this) (congr_arg f h))\n\ntheorem surjective.of_comp {α : Sort u_1} {β : Sort u_2} {γ : Sort u_3} {f : α → β} {g : γ → α}\n (S : surjective (f ∘ g)) : surjective f :=\n sorry\n\nprotected instance decidable_eq_pfun (p : Prop) [Decidable p] (α : p → Type u_1)\n [(hp : p) → DecidableEq (α hp)] : DecidableEq ((hp : p) → α hp) :=\n sorry\n\ntheorem surjective.forall {α : Sort u_1} {β : Sort u_2} {f : α → β} (hf : surjective f)\n {p : β → Prop} : (∀ (y : β), p y) ↔ ∀ (x : α), p (f x) :=\n sorry\n\ntheorem surjective.forall₂ {α : Sort u_1} {β : Sort u_2} {f : α → β} (hf : surjective f)\n {p : β → β → Prop} : (∀ (y₁ y₂ : β), p y₁ y₂) ↔ ∀ (x₁ x₂ : α), p (f x₁) (f x₂) :=\n iff.trans (surjective.forall hf) (forall_congr fun (x : α) => surjective.forall hf)\n\ntheorem surjective.forall₃ {α : Sort u_1} {β : Sort u_2} {f : α → β} (hf : surjective f)\n {p : β → β → β → Prop} :\n (∀ (y₁ y₂ y₃ : β), p y₁ y₂ y₃) ↔ ∀ (x₁ x₂ x₃ : α), p (f x₁) (f x₂) (f x₃) :=\n iff.trans (surjective.forall hf) (forall_congr fun (x : α) => surjective.forall₂ hf)\n\ntheorem surjective.exists {α : Sort u_1} {β : Sort u_2} {f : α → β} (hf : surjective f)\n {p : β → Prop} : (∃ (y : β), p y) ↔ ∃ (x : α), p (f x) :=\n sorry\n\ntheorem surjective.exists₂ {α : Sort u_1} {β : Sort u_2} {f : α → β} (hf : surjective f)\n {p : β → β → Prop} :\n (∃ (y₁ : β), ∃ (y₂ : β), p y₁ y₂) ↔ ∃ (x₁ : α), ∃ (x₂ : α), p (f x₁) (f x₂) :=\n iff.trans (surjective.exists hf) (exists_congr fun (x : α) => surjective.exists hf)\n\ntheorem surjective.exists₃ {α : Sort u_1} {β : Sort u_2} {f : α → β} (hf : surjective f)\n {p : β → β → β → Prop} :\n (∃ (y₁ : β), ∃ (y₂ : β), ∃ (y₃ : β), p y₁ y₂ y₃) ↔\n ∃ (x₁ : α), ∃ (x₂ : α), ∃ (x₃ : α), p (f x₁) (f x₂) (f x₃) :=\n iff.trans (surjective.exists hf) (exists_congr fun (x : α) => surjective.exists₂ hf)\n\n/-- Cantor's diagonal argument implies that there are no surjective functions from `α`\nto `set α`. -/\ntheorem cantor_surjective {α : Type u_1} (f : α → set α) : ¬surjective f := sorry\n\n/-- Cantor's diagonal argument implies that there are no injective functions from `set α` to `α`. -/\ntheorem cantor_injective {α : Type u_1} (f : set α → α) : ¬injective f := sorry\n\n/-- `g` is a partial inverse to `f` (an injective but not necessarily\n surjective function) if `g y = some x` implies `f x = y`, and `g y = none`\n implies that `y` is not in the range of `f`. -/\ndef is_partial_inv {α : Type u_1} {β : Sort u_2} (f : α → β) (g : β → Option α) :=\n ∀ (x : α) (y : β), g y = some x ↔ f x = y\n\ntheorem is_partial_inv_left {α : Type u_1} {β : Sort u_2} {f : α → β} {g : β → Option α}\n (H : is_partial_inv f g) (x : α) : g (f x) = some x :=\n iff.mpr (H x (f x)) rfl\n\ntheorem injective_of_partial_inv {α : Type u_1} {β : Sort u_2} {f : α → β} {g : β → Option α}\n (H : is_partial_inv f g) : injective f :=\n fun (a b : α) (h : f a = f b) =>\n option.some.inj (Eq.trans (Eq.symm (iff.mpr (H a (f b)) h)) (iff.mpr (H b (f b)) rfl))\n\ntheorem injective_of_partial_inv_right {α : Type u_1} {β : Sort u_2} {f : α → β} {g : β → Option α}\n (H : is_partial_inv f g) (x : β) (y : β) (b : α) (h₁ : b ∈ g x) (h₂ : b ∈ g y) : x = y :=\n Eq.trans (Eq.symm (iff.mp (H b x) h₁)) (iff.mp (H b y) h₂)\n\ntheorem left_inverse.comp_eq_id {α : Sort u_1} {β : Sort u_2} {f : α → β} {g : β → α}\n (h : left_inverse f g) : f ∘ g = id :=\n funext h\n\ntheorem left_inverse_iff_comp {α : Sort u_1} {β : Sort u_2} {f : α → β} {g : β → α} :\n left_inverse f g ↔ f ∘ g = id :=\n { mp := left_inverse.comp_eq_id, mpr := congr_fun }\n\ntheorem right_inverse.comp_eq_id {α : Sort u_1} {β : Sort u_2} {f : α → β} {g : β → α}\n (h : right_inverse f g) : g ∘ f = id :=\n funext h\n\ntheorem right_inverse_iff_comp {α : Sort u_1} {β : Sort u_2} {f : α → β} {g : β → α} :\n right_inverse f g ↔ g ∘ f = id :=\n { mp := right_inverse.comp_eq_id, mpr := congr_fun }\n\ntheorem left_inverse.comp {α : Sort u_1} {β : Sort u_2} {γ : Sort u_3} {f : α → β} {g : β → α}\n {h : β → γ} {i : γ → β} (hf : left_inverse f g) (hh : left_inverse h i) :\n left_inverse (h ∘ f) (g ∘ i) :=\n sorry\n\ntheorem right_inverse.comp {α : Sort u_1} {β : Sort u_2} {γ : Sort u_3} {f : α → β} {g : β → α}\n {h : β → γ} {i : γ → β} (hf : right_inverse f g) (hh : right_inverse h i) :\n right_inverse (h ∘ f) (g ∘ i) :=\n left_inverse.comp hh hf\n\ntheorem left_inverse.right_inverse {α : Sort u_1} {β : Sort u_2} {f : α → β} {g : β → α}\n (h : left_inverse g f) : right_inverse f g :=\n h\n\ntheorem right_inverse.left_inverse {α : Sort u_1} {β : Sort u_2} {f : α → β} {g : β → α}\n (h : right_inverse g f) : left_inverse f g :=\n h\n\ntheorem left_inverse.surjective {α : Sort u_1} {β : Sort u_2} {f : α → β} {g : β → α}\n (h : left_inverse f g) : surjective f :=\n right_inverse.surjective (left_inverse.right_inverse h)\n\ntheorem right_inverse.injective {α : Sort u_1} {β : Sort u_2} {f : α → β} {g : β → α}\n (h : right_inverse f g) : injective f :=\n left_inverse.injective (right_inverse.left_inverse h)\n\ntheorem left_inverse.eq_right_inverse {α : Sort u_1} {β : Sort u_2} {f : α → β} {g₁ : β → α}\n {g₂ : β → α} (h₁ : left_inverse g₁ f) (h₂ : right_inverse g₂ f) : g₁ = g₂ :=\n sorry\n\n/-- We can use choice to construct explicitly a partial inverse for\n a given injective function `f`. -/\ndef partial_inv {α : Type u_1} {β : Sort u_2} (f : α → β) (b : β) : Option α :=\n dite (∃ (a : α), f a = b) (fun (h : ∃ (a : α), f a = b) => some (classical.some h))\n fun (h : ¬∃ (a : α), f a = b) => none\n\ntheorem partial_inv_of_injective {α : Type u_1} {β : Sort u_2} {f : α → β} (I : injective f) :\n is_partial_inv f (partial_inv f) :=\n sorry\n\ntheorem partial_inv_left {α : Type u_1} {β : Sort u_2} {f : α → β} (I : injective f) (x : α) :\n partial_inv f (f x) = some x :=\n is_partial_inv_left (partial_inv_of_injective I)\n\n/-- Construct the inverse for a function `f` on domain `s`. This function is a right inverse of `f`\non `f '' s`. -/\ndef inv_fun_on {α : Type u} [n : Nonempty α] {β : Sort v} (f : α → β) (s : set α) (b : β) : α :=\n dite (∃ (a : α), a ∈ s ∧ f a = b) (fun (h : ∃ (a : α), a ∈ s ∧ f a = b) => classical.some h)\n fun (h : ¬∃ (a : α), a ∈ s ∧ f a = b) => Classical.choice n\n\ntheorem inv_fun_on_pos {α : Type u} [n : Nonempty α] {β : Sort v} {f : α → β} {s : set α} {b : β}\n (h : ∃ (a : α), ∃ (H : a ∈ s), f a = b) : inv_fun_on f s b ∈ s ∧ f (inv_fun_on f s b) = b :=\n sorry\n\ntheorem inv_fun_on_mem {α : Type u} [n : Nonempty α] {β : Sort v} {f : α → β} {s : set α} {b : β}\n (h : ∃ (a : α), ∃ (H : a ∈ s), f a = b) : inv_fun_on f s b ∈ s :=\n and.left (inv_fun_on_pos h)\n\ntheorem inv_fun_on_eq {α : Type u} [n : Nonempty α] {β : Sort v} {f : α → β} {s : set α} {b : β}\n (h : ∃ (a : α), ∃ (H : a ∈ s), f a = b) : f (inv_fun_on f s b) = b :=\n and.right (inv_fun_on_pos h)\n\ntheorem inv_fun_on_eq' {α : Type u} [n : Nonempty α] {β : Sort v} {f : α → β} {s : set α} {a : α}\n (h : ∀ (x : α), x ∈ s → ∀ (y : α), y ∈ s → f x = f y → x = y) (ha : a ∈ s) :\n inv_fun_on f s (f a) = a :=\n (fun (this : ∃ (a' : α), ∃ (H : a' ∈ s), f a' = f a) =>\n h (inv_fun_on (fun (a' : α) => f a') s (f a)) (inv_fun_on_mem this) a ha (inv_fun_on_eq this))\n (Exists.intro a (Exists.intro ha rfl))\n\ntheorem inv_fun_on_neg {α : Type u} [n : Nonempty α] {β : Sort v} {f : α → β} {s : set α} {b : β}\n (h : ¬∃ (a : α), ∃ (H : a ∈ s), f a = b) : inv_fun_on f s b = Classical.choice n :=\n sorry\n\n/-- The inverse of a function (which is a left inverse if `f` is injective\n and a right inverse if `f` is surjective). -/\ndef inv_fun {α : Type u} [n : Nonempty α] {β : Sort v} (f : α → β) : β → α := inv_fun_on f set.univ\n\ntheorem inv_fun_eq {α : Type u} [n : Nonempty α] {β : Sort v} {f : α → β} {b : β}\n (h : ∃ (a : α), f a = b) : f (inv_fun f b) = b :=\n sorry\n\ntheorem inv_fun_neg {α : Type u} [n : Nonempty α] {β : Sort v} {f : α → β} {b : β}\n (h : ¬∃ (a : α), f a = b) : inv_fun f b = Classical.choice n :=\n sorry\n\ntheorem inv_fun_eq_of_injective_of_right_inverse {α : Type u} [n : Nonempty α] {β : Sort v}\n {f : α → β} {g : β → α} (hf : injective f) (hg : right_inverse g f) : inv_fun f = g :=\n funext\n fun (b : β) =>\n hf\n (eq.mpr (id (Eq._oldrec (Eq.refl (f (inv_fun f b) = f (g b))) (hg b)))\n (inv_fun_eq (Exists.intro (g b) (hg b))))\n\ntheorem right_inverse_inv_fun {α : Type u} [n : Nonempty α] {β : Sort v} {f : α → β}\n (hf : surjective f) : right_inverse (inv_fun f) f :=\n fun (b : β) => inv_fun_eq (hf b)\n\ntheorem left_inverse_inv_fun {α : Type u} [n : Nonempty α] {β : Sort v} {f : α → β}\n (hf : injective f) : left_inverse (inv_fun f) f :=\n fun (b : α) =>\n (fun (this : f (inv_fun f (f b)) = f b) => hf this) (inv_fun_eq (Exists.intro b rfl))\n\ntheorem inv_fun_surjective {α : Type u} [n : Nonempty α] {β : Sort v} {f : α → β}\n (hf : injective f) : surjective (inv_fun f) :=\n left_inverse.surjective (left_inverse_inv_fun hf)\n\ntheorem inv_fun_comp {α : Type u} [n : Nonempty α] {β : Sort v} {f : α → β} (hf : injective f) :\n inv_fun f ∘ f = id :=\n funext (left_inverse_inv_fun hf)\n\ntheorem injective.has_left_inverse {α : Type u} [i : Nonempty α] {β : Sort v} {f : α → β}\n (hf : injective f) : has_left_inverse f :=\n Exists.intro (inv_fun f) (left_inverse_inv_fun hf)\n\ntheorem injective_iff_has_left_inverse {α : Type u} [i : Nonempty α] {β : Sort v} {f : α → β} :\n injective f ↔ has_left_inverse f :=\n { mp := injective.has_left_inverse, mpr := has_left_inverse.injective }\n\n/-- The inverse of a surjective function. (Unlike `inv_fun`, this does not require\n `α` to be inhabited.) -/\ndef surj_inv {α : Sort u} {β : Sort v} {f : α → β} (h : surjective f) (b : β) : α :=\n classical.some (h b)\n\ntheorem surj_inv_eq {α : Sort u} {β : Sort v} {f : α → β} (h : surjective f) (b : β) :\n f (surj_inv h b) = b :=\n classical.some_spec (h b)\n\ntheorem right_inverse_surj_inv {α : Sort u} {β : Sort v} {f : α → β} (hf : surjective f) :\n right_inverse (surj_inv hf) f :=\n surj_inv_eq hf\n\ntheorem left_inverse_surj_inv {α : Sort u} {β : Sort v} {f : α → β} (hf : bijective f) :\n left_inverse (surj_inv (and.right hf)) f :=\n right_inverse_of_injective_of_left_inverse (and.left hf) (right_inverse_surj_inv (and.right hf))\n\ntheorem surjective.has_right_inverse {α : Sort u} {β : Sort v} {f : α → β} (hf : surjective f) :\n has_right_inverse f :=\n Exists.intro (surj_inv hf) (right_inverse_surj_inv hf)\n\ntheorem surjective_iff_has_right_inverse {α : Sort u} {β : Sort v} {f : α → β} :\n surjective f ↔ has_right_inverse f :=\n { mp := surjective.has_right_inverse, mpr := has_right_inverse.surjective }\n\ntheorem bijective_iff_has_inverse {α : Sort u} {β : Sort v} {f : α → β} :\n bijective f ↔ ∃ (g : β → α), left_inverse g f ∧ right_inverse g f :=\n sorry\n\ntheorem injective_surj_inv {α : Sort u} {β : Sort v} {f : α → β} (h : surjective f) :\n injective (surj_inv h) :=\n right_inverse.injective (right_inverse_surj_inv h)\n\n/-- Replacing the value of a function at a given point by a given value. -/\ndef update {α : Sort u} {β : α → Sort v} [DecidableEq α] (f : (a : α) → β a) (a' : α) (v : β a')\n (a : α) : β a :=\n dite (a = a') (fun (h : a = a') => Eq._oldrec v (Eq.symm h)) fun (h : ¬a = a') => f a\n\n/-- On non-dependent functions, `function.update` can be expressed as an `ite` -/\ntheorem update_apply {α : Sort u} [DecidableEq α] {β : Sort u_1} (f : α → β) (a' : α) (b : β)\n (a : α) : update f a' b a = ite (a = a') b (f a) :=\n sorry\n\n@[simp] theorem update_same {α : Sort u} {β : α → Sort v} [DecidableEq α] (a : α) (v : β a)\n (f : (a : α) → β a) : update f a v a = v :=\n dif_pos rfl\n\ntheorem update_injective {α : Sort u} {β : α → Sort v} [DecidableEq α] (f : (a : α) → β a)\n (a' : α) : injective (update f a') :=\n sorry\n\n@[simp] theorem update_noteq {α : Sort u} {β : α → Sort v} [DecidableEq α] {a : α} {a' : α}\n (h : a ≠ a') (v : β a') (f : (a : α) → β a) : update f a' v a = f a :=\n dif_neg h\n\ntheorem forall_update_iff {α : Sort u} {β : α → Sort v} [DecidableEq α] (f : (a : α) → β a) {a : α}\n {b : β a} (p : (a : α) → β a → Prop) :\n (∀ (x : α), p x (update f a b x)) ↔ p a b ∧ ∀ (x : α), x ≠ a → p x (f x) :=\n sorry\n\ntheorem update_eq_iff {α : Sort u} {β : α → Sort v} [DecidableEq α] {a : α} {b : β a}\n {f : (a : α) → β a} {g : (a : α) → β a} :\n update f a b = g ↔ b = g a ∧ ∀ (x : α), x ≠ a → f x = g x :=\n iff.trans funext_iff (forall_update_iff f fun (x : α) (y : β x) => y = g x)\n\ntheorem eq_update_iff {α : Sort u} {β : α → Sort v} [DecidableEq α] {a : α} {b : β a}\n {f : (a : α) → β a} {g : (a : α) → β a} :\n g = update f a b ↔ g a = b ∧ ∀ (x : α), x ≠ a → g x = f x :=\n iff.trans funext_iff (forall_update_iff f fun (x : α) (y : β x) => g x = y)\n\n@[simp] theorem update_eq_self {α : Sort u} {β : α → Sort v} [DecidableEq α] (a : α)\n (f : (a : α) → β a) : update f a (f a) = f :=\n iff.mpr update_eq_iff { left := rfl, right := fun (_x : α) (_x_1 : _x ≠ a) => rfl }\n\ntheorem update_comp_eq_of_forall_ne' {α : Sort u} {β : α → Sort v} [DecidableEq α] {α' : Sort u_1}\n (g : (a : α) → β a) {f : α' → α} {i : α} (a : β i) (h : ∀ (x : α'), f x ≠ i) :\n (fun (j : α') => update g i a (f j)) = fun (j : α') => g (f j) :=\n funext fun (x : α') => update_noteq (h x) a g\n\n/-- Non-dependent version of `function.update_comp_eq_of_forall_ne'` -/\ntheorem update_comp_eq_of_forall_ne {α' : Sort w} [DecidableEq α'] {α : Sort u_1} {β : Sort u_2}\n (g : α' → β) {f : α → α'} {i : α'} (a : β) (h : ∀ (x : α), f x ≠ i) :\n update g i a ∘ f = g ∘ f :=\n update_comp_eq_of_forall_ne' g a h\n\ntheorem update_comp_eq_of_injective' {α : Sort u} {β : α → Sort v} {α' : Sort w} [DecidableEq α]\n [DecidableEq α'] (g : (a : α) → β a) {f : α' → α} (hf : injective f) (i : α') (a : β (f i)) :\n (fun (j : α') => update g (f i) a (f j)) = update (fun (i : α') => g (f i)) i a :=\n iff.mpr eq_update_iff\n { left := update_same (f i) a g,\n right := fun (j : α') (hj : j ≠ i) => update_noteq (injective.ne hf hj) a g }\n\n/-- Non-dependent version of `function.update_comp_eq_of_injective'` -/\ntheorem update_comp_eq_of_injective {α : Sort u} {α' : Sort w} [DecidableEq α] [DecidableEq α']\n {β : Sort u_1} (g : α' → β) {f : α → α'} (hf : injective f) (i : α) (a : β) :\n update g (f i) a ∘ f = update (g ∘ f) i a :=\n update_comp_eq_of_injective' g hf i a\n\ntheorem apply_update {ι : Sort u_1} [DecidableEq ι] {α : ι → Sort u_2} {β : ι → Sort u_3}\n (f : (i : ι) → α i → β i) (g : (i : ι) → α i) (i : ι) (v : α i) (j : ι) :\n f j (update g i v j) = update (fun (k : ι) => f k (g k)) i (f i v) j :=\n sorry\n\ntheorem comp_update {α : Sort u} [DecidableEq α] {α' : Sort u_1} {β : Sort u_2} (f : α' → β)\n (g : α → α') (i : α) (v : α') : f ∘ update g i v = update (f ∘ g) i (f v) :=\n funext (apply_update (fun (x : α) => f) g i v)\n\ntheorem update_comm {α : Sort u_1} [DecidableEq α] {β : α → Sort u_2} {a : α} {b : α} (h : a ≠ b)\n (v : β a) (w : β b) (f : (a : α) → β a) :\n update (update f a v) b w = update (update f b w) a v :=\n sorry\n\n@[simp] theorem update_idem {α : Sort u_1} [DecidableEq α] {β : α → Sort u_2} {a : α} (v : β a)\n (w : β a) (f : (a : α) → β a) : update (update f a v) a w = update f a w :=\n sorry\n\n/-- `extend f g e'` extends a function `g : α → γ`\nalong a function `f : α → β` to a function `β → γ`,\nby using the values of `g` on the range of `f`\nand the values of an auxiliary function `e' : β → γ` elsewhere.\n\nMostly useful when `f` is injective. -/\ndef extend {α : Type u_1} {β : Type u_2} {γ : Type u_3} (f : α → β) (g : α → γ) (e' : β → γ) :\n β → γ :=\n fun (b : β) =>\n dite (∃ (a : α), f a = b) (fun (h : ∃ (a : α), f a = b) => g (classical.some h))\n fun (h : ¬∃ (a : α), f a = b) => e' b\n\ntheorem extend_def {α : Type u_1} {β : Type u_2} {γ : Type u_3} (f : α → β) (g : α → γ) (e' : β → γ)\n (b : β) :\n extend f g e' b =\n dite (∃ (a : α), f a = b) (fun (h : ∃ (a : α), f a = b) => g (classical.some h))\n fun (h : ¬∃ (a : α), f a = b) => e' b :=\n rfl\n\n@[simp] theorem extend_apply {α : Type u_1} {β : Type u_2} {γ : Type u_3} {f : α → β}\n (hf : injective f) (g : α → γ) (e' : β → γ) (a : α) : extend f g e' (f a) = g a :=\n sorry\n\n@[simp] theorem extend_comp {α : Type u_1} {β : Type u_2} {γ : Type u_3} {f : α → β}\n (hf : injective f) (g : α → γ) (e' : β → γ) : extend f g e' ∘ f = g :=\n funext fun (a : α) => extend_apply hf g e' a\n\ntheorem uncurry_def {α : Type u_1} {β : Type u_2} {γ : Type u_3} (f : α → β → γ) :\n uncurry f = fun (p : α × β) => f (prod.fst p) (prod.snd p) :=\n rfl\n\n@[simp] theorem uncurry_apply_pair {α : Type u_1} {β : Type u_2} {γ : Type u_3} (f : α → β → γ)\n (x : α) (y : β) : uncurry f (x, y) = f x y :=\n rfl\n\n@[simp] theorem curry_apply {α : Type u_1} {β : Type u_2} {γ : Type u_3} (f : α × β → γ) (x : α)\n (y : β) : curry f x y = f (x, y) :=\n rfl\n\n/-- Compose a binary function `f` with a pair of unary functions `g` and `h`.\nIf both arguments of `f` have the same type and `g = h`, then `bicompl f g g = f on g`. -/\ndef bicompl {α : Type u_1} {β : Type u_2} {γ : Type u_3} {δ : Type u_4} {ε : Type u_5}\n (f : γ → δ → ε) (g : α → γ) (h : β → δ) (a : α) (b : β) : ε :=\n f (g a) (h b)\n\n/-- Compose an unary function `f` with a binary function `g`. -/\ndef bicompr {α : Type u_1} {β : Type u_2} {γ : Type u_3} {δ : Type u_4} (f : γ → δ) (g : α → β → γ)\n (a : α) (b : β) : δ :=\n f (g a b)\n\n-- Suggested local notation:\n\ntheorem uncurry_bicompr {α : Type u_1} {β : Type u_2} {γ : Type u_3} {δ : Type u_4} (f : α → β → γ)\n (g : γ → δ) : uncurry (bicompr g f) = g ∘ uncurry f :=\n rfl\n\ntheorem uncurry_bicompl {α : Type u_1} {β : Type u_2} {γ : Type u_3} {δ : Type u_4} {ε : Type u_5}\n (f : γ → δ → ε) (g : α → γ) (h : β → δ) : uncurry (bicompl f g h) = uncurry f ∘ prod.map g h :=\n rfl\n\n/-- Records a way to turn an element of `α` into a function from `β` to `γ`. The most generic use\nis to recursively uncurry. For instance `f : α → β → γ → δ` will be turned into\n`↿f : α × β × γ → δ`. One can also add instances for bundled maps. -/\nclass has_uncurry (α : Type u_5) (β : outParam (Type u_6)) (γ : outParam (Type u_7)) where\n uncurry : α → β → γ\n\nprefix:1024 \"↿\" => Mathlib.function.has_uncurry.uncurry\n\n/-- Uncurrying operator. The most generic use is to recursively uncurry. For instance\n`f : α → β → γ → δ` will be turned into `↿f : α × β × γ → δ`. One can also add instances\nfor bundled maps.-/\nprotected instance has_uncurry_base {α : Type u_1} {β : Type u_2} : has_uncurry (α → β) α β :=\n has_uncurry.mk id\n\nprotected instance has_uncurry_induction {α : Type u_1} {β : Type u_2} {γ : Type u_3} {δ : Type u_4}\n [has_uncurry β γ δ] : has_uncurry (α → β) (α × γ) δ :=\n has_uncurry.mk fun (f : α → β) (p : α × γ) => has_uncurry.uncurry (f (prod.fst p)) (prod.snd p)\n\n/-- A function is involutive, if `f ∘ f = id`. -/\ndef involutive {α : Sort u_1} (f : α → α) := ∀ (x : α), f (f x) = x\n\ntheorem involutive_iff_iter_2_eq_id {α : Sort u_1} {f : α → α} :\n involutive f ↔ nat.iterate f (bit0 1) = id :=\n iff.symm funext_iff\n\nnamespace involutive\n\n\n@[simp] theorem comp_self {α : Sort u} {f : α → α} (h : involutive f) : f ∘ f = id := funext h\n\nprotected theorem left_inverse {α : Sort u} {f : α → α} (h : involutive f) : left_inverse f f := h\n\nprotected theorem right_inverse {α : Sort u} {f : α → α} (h : involutive f) : right_inverse f f := h\n\nprotected theorem injective {α : Sort u} {f : α → α} (h : involutive f) : injective f :=\n left_inverse.injective (involutive.left_inverse h)\n\nprotected theorem surjective {α : Sort u} {f : α → α} (h : involutive f) : surjective f :=\n fun (x : α) => Exists.intro (f x) (h x)\n\nprotected theorem bijective {α : Sort u} {f : α → α} (h : involutive f) : bijective f :=\n { left := involutive.injective h, right := involutive.surjective h }\n\n/-- Involuting an `ite` of an involuted value `x : α` negates the `Prop` condition in the `ite`. -/\nprotected theorem ite_not {α : Sort u} {f : α → α} (h : involutive f) (P : Prop) [Decidable P]\n (x : α) : f (ite P x (f x)) = ite (¬P) x (f x) :=\n sorry\n\nend involutive\n\n\n/-- The property of a binary function `f : α → β → γ` being injective.\n Mathematically this should be thought of as the corresponding function `α × β → γ` being injective.\n-/\ndef injective2 {α : Sort u_1} {β : Sort u_2} {γ : Sort u_3} (f : α → β → γ) :=\n ∀ {a₁ a₂ : α} {b₁ b₂ : β}, f a₁ b₁ = f a₂ b₂ → a₁ = a₂ ∧ b₁ = b₂\n\nnamespace injective2\n\n\nprotected theorem left {α : Type u_1} {β : Type u_2} {γ : Type u_3} (f : α → β → γ)\n (hf : injective2 f) {a₁ : α} {a₂ : α} {b₁ : β} {b₂ : β} (h : f a₁ b₁ = f a₂ b₂) : a₁ = a₂ :=\n and.left (hf h)\n\nprotected theorem right {α : Type u_1} {β : Type u_2} {γ : Type u_3} (f : α → β → γ)\n (hf : injective2 f) {a₁ : α} {a₂ : α} {b₁ : β} {b₂ : β} (h : f a₁ b₁ = f a₂ b₂) : b₁ = b₂ :=\n and.right (hf h)\n\ntheorem eq_iff {α : Type u_1} {β : Type u_2} {γ : Type u_3} (f : α → β → γ) (hf : injective2 f)\n {a₁ : α} {a₂ : α} {b₁ : β} {b₂ : β} : f a₁ b₁ = f a₂ b₂ ↔ a₁ = a₂ ∧ b₁ = b₂ :=\n sorry\n\nend injective2\n\n\n/-- `sometimes f` evaluates to some value of `f`, if it exists. This function is especially\ninteresting in the case where `α` is a proposition, in which case `f` is necessarily a\nconstant function, so that `sometimes f = f a` for all `a`. -/\ndef sometimes {α : Sort u_1} {β : Sort u_2} [Nonempty β] (f : α → β) : β :=\n dite (Nonempty α) (fun (h : Nonempty α) => f (Classical.choice h))\n fun (h : ¬Nonempty α) => Classical.choice _inst_1\n\ntheorem sometimes_eq {p : Prop} {α : Sort u_1} [Nonempty α] (f : p → α) (a : p) :\n sometimes f = f a :=\n dif_pos (Nonempty.intro a)\n\ntheorem sometimes_spec {p : Prop} {α : Sort u_1} [Nonempty α] (P : α → Prop) (f : p → α) (a : p)\n (h : P (f a)) : P (sometimes f) :=\n eq.mpr (id (Eq._oldrec (Eq.refl (P (sometimes f))) (sometimes_eq f a))) h\n\nend function\n\n\n/-- `s.piecewise f g` is the function equal to `f` on the set `s`, and to `g` on its complement. -/\ndef set.piecewise {α : Type u} {β : α → Sort v} (s : set α) (f : (i : α) → β i) (g : (i : α) → β i)\n [(j : α) → Decidable (j ∈ s)] (i : α) : β i :=\n ite (i ∈ s) (f i) (g i)\n\nend Mathlib", "meta": {"author": "AurelienSaue", "repo": "Mathlib4_auto", "sha": "590df64109b08190abe22358fabc3eae000943f2", "save_path": "github-repos/lean/AurelienSaue-Mathlib4_auto", "path": "github-repos/lean/AurelienSaue-Mathlib4_auto/Mathlib4_auto-590df64109b08190abe22358fabc3eae000943f2/Mathlib/logic/function/basic_auto.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.31405055783200714, "lm_q2_score": 0.05582314034922016, "lm_q1q2_score": 0.017531288366607018}} {"text": "/-\nCopyright (c) 2020 Scott Morrison. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Scott Morrison\n-/\nimport algebra.group.ext\nimport category_theory.limits.shapes.biproducts\nimport category_theory.limits.preserves.shapes.binary_products\nimport category_theory.limits.preserves.shapes.biproducts\nimport category_theory.limits.preserves.shapes.products\nimport category_theory.preadditive.basic\nimport tactic.abel\n\n/-!\n# Basic facts about biproducts in preadditive categories.\n\n> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.\n> Any changes to this file require a corresponding PR to mathlib4.\n\nIn (or between) preadditive categories,\n\n* Any biproduct satisfies the equality\n `total : ∑ j : J, biproduct.π f j ≫ biproduct.ι f j = 𝟙 (⨁ f)`,\n or, in the binary case, `total : fst ≫ inl + snd ≫ inr = 𝟙 X`.\n\n* Any (binary) `product` or (binary) `coproduct` is a (binary) `biproduct`.\n\n* In any category (with zero morphisms), if `biprod.map f g` is an isomorphism,\n then both `f` and `g` are isomorphisms.\n\n* If `f` is a morphism `X₁ ⊞ X₂ ⟶ Y₁ ⊞ Y₂` whose `X₁ ⟶ Y₁` entry is an isomorphism,\n then we can construct isomorphisms `L : X₁ ⊞ X₂ ≅ X₁ ⊞ X₂` and `R : Y₁ ⊞ Y₂ ≅ Y₁ ⊞ Y₂`\n so that `L.hom ≫ g ≫ R.hom` is diagonal (with `X₁ ⟶ Y₁` component still `f`),\n via Gaussian elimination.\n\n* As a corollary of the previous two facts,\n if we have an isomorphism `X₁ ⊞ X₂ ≅ Y₁ ⊞ Y₂` whose `X₁ ⟶ Y₁` entry is an isomorphism,\n we can construct an isomorphism `X₂ ≅ Y₂`.\n\n* If `f : W ⊞ X ⟶ Y ⊞ Z` is an isomorphism, either `𝟙 W = 0`,\n or at least one of the component maps `W ⟶ Y` and `W ⟶ Z` is nonzero.\n\n* If `f : ⨁ S ⟶ ⨁ T` is an isomorphism,\n then every column (corresponding to a nonzero summand in the domain)\n has some nonzero matrix entry.\n\n* A functor preserves a biproduct if and only if it preserves\n the corresponding product if and only if it preserves the corresponding coproduct.\n-/\n\nopen category_theory\nopen category_theory.preadditive\nopen category_theory.limits\nopen category_theory.functor\nopen category_theory.preadditive\n\nopen_locale classical\nopen_locale big_operators\n\nuniverses v v' u u'\n\nnoncomputable theory\n\nnamespace category_theory\n\nvariables {C : Type u} [category.{v} C] [preadditive C]\n\nnamespace limits\n\nvariables {J : Type} [fintype J]\n\n/--\nIn a preadditive category, we can construct a biproduct for `f : J → C` from\nany bicone `b` for `f` satisfying `total : ∑ j : J, b.π j ≫ b.ι j = 𝟙 b.X`.\n\n(That is, such a bicone is a limit cone and a colimit cocone.)\n-/\ndef is_bilimit_of_total {f : J → C} (b : bicone f) (total : ∑ j : J, b.π j ≫ b.ι j = 𝟙 b.X) :\n b.is_bilimit :=\n{ is_limit :=\n { lift := λ s, ∑ (j : J), s.π.app ⟨j⟩ ≫ b.ι j,\n uniq' := λ s m h,\n begin\n erw [←category.comp_id m, ←total, comp_sum],\n apply finset.sum_congr rfl,\n intros j m,\n erw [reassoc_of (h ⟨j⟩)],\n end,\n fac' := λ s j,\n begin\n cases j,\n simp only [sum_comp, category.assoc, bicone.to_cone_π_app, b.ι_π, comp_dite],\n -- See note [dsimp, simp].\n dsimp, simp,\n end },\n is_colimit :=\n { desc := λ s, ∑ (j : J), b.π j ≫ s.ι.app ⟨j⟩,\n uniq' := λ s m h,\n begin\n erw [←category.id_comp m, ←total, sum_comp],\n apply finset.sum_congr rfl,\n intros j m,\n erw [category.assoc, h ⟨j⟩],\n end,\n fac' := λ s j,\n begin\n cases j,\n simp only [comp_sum, ←category.assoc, bicone.to_cocone_ι_app, b.ι_π, dite_comp],\n dsimp, simp,\n end } }\n\nlemma is_bilimit.total {f : J → C} {b : bicone f} (i : b.is_bilimit) :\n ∑ j : J, b.π j ≫ b.ι j = 𝟙 b.X :=\ni.is_limit.hom_ext (λ j, by { cases j, simp [sum_comp, b.ι_π, comp_dite] })\n\n/--\nIn a preadditive category, we can construct a biproduct for `f : J → C` from\nany bicone `b` for `f` satisfying `total : ∑ j : J, b.π j ≫ b.ι j = 𝟙 b.X`.\n\n(That is, such a bicone is a limit cone and a colimit cocone.)\n-/\nlemma has_biproduct_of_total {f : J → C} (b : bicone f) (total : ∑ j : J, b.π j ≫ b.ι j = 𝟙 b.X) :\n has_biproduct f :=\nhas_biproduct.mk\n{ bicone := b,\n is_bilimit := is_bilimit_of_total b total }\n\n/-- In a preadditive category, any finite bicone which is a limit cone is in fact a bilimit\n bicone. -/\ndef is_bilimit_of_is_limit {f : J → C} (t : bicone f) (ht : is_limit t.to_cone) : t.is_bilimit :=\nis_bilimit_of_total _ $ ht.hom_ext $\n λ j, by { cases j, simp [sum_comp, t.ι_π, dite_comp, comp_dite] }\n\n/-- We can turn any limit cone over a pair into a bilimit bicone. -/\ndef bicone_is_bilimit_of_limit_cone_of_is_limit {f : J → C} {t : cone (discrete.functor f)}\n (ht : is_limit t) : (bicone.of_limit_cone ht).is_bilimit :=\nis_bilimit_of_is_limit _ $\n is_limit.of_iso_limit ht $ cones.ext (iso.refl _) (by { rintro ⟨j⟩, tidy })\n\n/-- In a preadditive category, if the product over `f : J → C` exists,\n then the biproduct over `f` exists. -/\nlemma has_biproduct.of_has_product {J : Type} [finite J] (f : J → C) [has_product f] :\n has_biproduct f :=\nby casesI nonempty_fintype J; exact\nhas_biproduct.mk\n{ bicone := _,\n is_bilimit := bicone_is_bilimit_of_limit_cone_of_is_limit (limit.is_limit _) }\n\n/-- In a preadditive category, any finite bicone which is a colimit cocone is in fact a bilimit\n bicone. -/\ndef is_bilimit_of_is_colimit {f : J → C} (t : bicone f) (ht : is_colimit t.to_cocone) :\n t.is_bilimit :=\nis_bilimit_of_total _ $ ht.hom_ext $ λ j, begin\n cases j,\n simp_rw [bicone.to_cocone_ι_app, comp_sum, ← category.assoc, t.ι_π, dite_comp],\n tidy\nend\n\n/-- We can turn any limit cone over a pair into a bilimit bicone. -/\ndef bicone_is_bilimit_of_colimit_cocone_of_is_colimit {f : J → C} {t : cocone (discrete.functor f)}\n (ht : is_colimit t) : (bicone.of_colimit_cocone ht).is_bilimit :=\nis_bilimit_of_is_colimit _ $\n is_colimit.of_iso_colimit ht $ cocones.ext (iso.refl _) (by { rintro ⟨j⟩, tidy })\n\n/-- In a preadditive category, if the coproduct over `f : J → C` exists,\n then the biproduct over `f` exists. -/\nlemma has_biproduct.of_has_coproduct {J : Type} [finite J] (f : J → C) [has_coproduct f] :\n has_biproduct f :=\nby casesI nonempty_fintype J; exact\nhas_biproduct.mk\n{ bicone := _,\n is_bilimit := bicone_is_bilimit_of_colimit_cocone_of_is_colimit (colimit.is_colimit _) }\n\n/-- A preadditive category with finite products has finite biproducts. -/\nlemma has_finite_biproducts.of_has_finite_products [has_finite_products C] :\n has_finite_biproducts C :=\n⟨λ n, { has_biproduct := λ F, has_biproduct.of_has_product _ }⟩\n\n/-- A preadditive category with finite coproducts has finite biproducts. -/\nlemma has_finite_biproducts.of_has_finite_coproducts [has_finite_coproducts C] :\n has_finite_biproducts C :=\n⟨λ n, { has_biproduct := λ F, has_biproduct.of_has_coproduct _ }⟩\n\nsection\nvariables {f : J → C} [has_biproduct f]\n\n/--\nIn any preadditive category, any biproduct satsifies\n`∑ j : J, biproduct.π f j ≫ biproduct.ι f j = 𝟙 (⨁ f)`\n-/\n@[simp] lemma biproduct.total : ∑ j : J, biproduct.π f j ≫ biproduct.ι f j = 𝟙 (⨁ f) :=\nis_bilimit.total (biproduct.is_bilimit _)\n\nlemma biproduct.lift_eq {T : C} {g : Π j, T ⟶ f j} :\n biproduct.lift g = ∑ j, g j ≫ biproduct.ι f j :=\nbegin\n ext j,\n simp only [sum_comp, biproduct.ι_π, comp_dite, biproduct.lift_π, category.assoc, comp_zero,\n finset.sum_dite_eq', finset.mem_univ, eq_to_hom_refl, category.comp_id, if_true],\nend\n\nlemma biproduct.desc_eq {T : C} {g : Π j, f j ⟶ T} :\n biproduct.desc g = ∑ j, biproduct.π f j ≫ g j :=\nbegin\n ext j,\n simp [comp_sum, biproduct.ι_π_assoc, dite_comp],\nend\n\n@[simp, reassoc] lemma biproduct.lift_desc {T U : C} {g : Π j, T ⟶ f j} {h : Π j, f j ⟶ U} :\n biproduct.lift g ≫ biproduct.desc h = ∑ j : J, g j ≫ h j :=\nby simp [biproduct.lift_eq, biproduct.desc_eq, comp_sum, sum_comp, biproduct.ι_π_assoc,\n comp_dite, dite_comp]\n\nlemma biproduct.map_eq [has_finite_biproducts C] {f g : J → C} {h : Π j, f j ⟶ g j} :\n biproduct.map h = ∑ j : J, biproduct.π f j ≫ h j ≫ biproduct.ι g j :=\nbegin\n ext,\n simp [biproduct.ι_π, biproduct.ι_π_assoc, comp_sum, sum_comp, comp_dite, dite_comp],\nend\n\n@[simp, reassoc]\nlemma biproduct.matrix_desc\n {K : Type} [fintype K] [has_finite_biproducts C]\n {f : J → C} {g : K → C} (m : Π j k, f j ⟶ g k) {P} (x : Π k, g k ⟶ P) :\n biproduct.matrix m ≫ biproduct.desc x = biproduct.desc (λ j, ∑ k, m j k ≫ x k) :=\nby { ext, simp, }\n\n@[simp, reassoc]\nlemma biproduct.lift_matrix\n {K : Type} [fintype K] [has_finite_biproducts C]\n {f : J → C} {g : K → C} {P} (x : Π j, P ⟶ f j) (m : Π j k, f j ⟶ g k) :\n biproduct.lift x ≫ biproduct.matrix m = biproduct.lift (λ k, ∑ j, x j ≫ m j k) :=\nby { ext, simp, }\n\n@[reassoc]\nlemma biproduct.matrix_map\n {K : Type} [fintype K] [has_finite_biproducts C]\n {f : J → C} {g : K → C} {h : K → C} (m : Π j k, f j ⟶ g k) (n : Π k, g k ⟶ h k) :\n biproduct.matrix m ≫ biproduct.map n = biproduct.matrix (λ j k, m j k ≫ n k) :=\nby { ext, simp, }\n\n@[reassoc]\nlemma biproduct.map_matrix\n {K : Type} [fintype K] [has_finite_biproducts C]\n {f : J → C} {g : J → C} {h : K → C} (m : Π k, f k ⟶ g k) (n : Π j k, g j ⟶ h k) :\n biproduct.map m ≫ biproduct.matrix n = biproduct.matrix (λ j k, m j ≫ n j k) :=\nby { ext, simp, }\n\nend\n\n/-- Reindex a categorical biproduct via an equivalence of the index types. -/\n@[simps]\ndef biproduct.reindex {β γ : Type} [fintype β] [decidable_eq β] [decidable_eq γ]\n (ε : β ≃ γ) (f : γ → C) [has_biproduct f] [has_biproduct (f ∘ ε)] : (⨁ (f ∘ ε)) ≅ (⨁ f) :=\n{ hom := biproduct.desc (λ b, biproduct.ι f (ε b)),\n inv := biproduct.lift (λ b, biproduct.π f (ε b)),\n hom_inv_id' := by { ext b b', by_cases h : b = b', { subst h, simp, }, { simp [h], }, },\n inv_hom_id' := begin\n ext g g',\n by_cases h : g = g';\n simp [preadditive.sum_comp, preadditive.comp_sum, biproduct.ι_π, biproduct.ι_π_assoc, comp_dite,\n equiv.apply_eq_iff_eq_symm_apply, finset.sum_dite_eq' finset.univ (ε.symm g') _, h],\n end, }\n\n/--\nIn a preadditive category, we can construct a binary biproduct for `X Y : C` from\nany binary bicone `b` satisfying `total : b.fst ≫ b.inl + b.snd ≫ b.inr = 𝟙 b.X`.\n\n(That is, such a bicone is a limit cone and a colimit cocone.)\n-/\ndef is_binary_bilimit_of_total {X Y : C} (b : binary_bicone X Y)\n (total : b.fst ≫ b.inl + b.snd ≫ b.inr = 𝟙 b.X) : b.is_bilimit :=\n{ is_limit :=\n { lift := λ s, binary_fan.fst s ≫ b.inl +\n binary_fan.snd s ≫ b.inr,\n uniq' := λ s m h, by erw [←category.comp_id m, ←total,\n comp_add, reassoc_of (h ⟨walking_pair.left⟩), reassoc_of (h ⟨walking_pair.right⟩)],\n fac' := λ s j, by rcases j with ⟨⟨⟩⟩; simp, },\n is_colimit :=\n { desc := λ s, b.fst ≫ binary_cofan.inl s +\n b.snd ≫ binary_cofan.inr s,\n uniq' := λ s m h, by erw [←category.id_comp m, ←total,\n add_comp, category.assoc, category.assoc, h ⟨walking_pair.left⟩, h ⟨walking_pair.right⟩],\n fac' := λ s j, by rcases j with ⟨⟨⟩⟩; simp, } }\n\nlemma is_bilimit.binary_total {X Y : C} {b : binary_bicone X Y} (i : b.is_bilimit) :\n b.fst ≫ b.inl + b.snd ≫ b.inr = 𝟙 b.X :=\ni.is_limit.hom_ext (λ j, by { rcases j with ⟨⟨⟩⟩; simp, })\n\n/--\nIn a preadditive category, we can construct a binary biproduct for `X Y : C` from\nany binary bicone `b` satisfying `total : b.fst ≫ b.inl + b.snd ≫ b.inr = 𝟙 b.X`.\n\n(That is, such a bicone is a limit cone and a colimit cocone.)\n-/\nlemma has_binary_biproduct_of_total {X Y : C} (b : binary_bicone X Y)\n (total : b.fst ≫ b.inl + b.snd ≫ b.inr = 𝟙 b.X) : has_binary_biproduct X Y :=\nhas_binary_biproduct.mk\n{ bicone := b,\n is_bilimit := is_binary_bilimit_of_total b total }\n\n/-- We can turn any limit cone over a pair into a bicone. -/\n@[simps]\ndef binary_bicone.of_limit_cone {X Y : C} {t : cone (pair X Y)} (ht : is_limit t) :\n binary_bicone X Y :=\n{ X := t.X,\n fst := t.π.app ⟨walking_pair.left⟩,\n snd := t.π.app ⟨walking_pair.right⟩,\n inl := ht.lift (binary_fan.mk (𝟙 X) 0),\n inr := ht.lift (binary_fan.mk 0 (𝟙 Y)) }\n\nlemma inl_of_is_limit {X Y : C} {t : binary_bicone X Y} (ht : is_limit t.to_cone) :\n t.inl = ht.lift (binary_fan.mk (𝟙 X) 0) :=\nby apply ht.uniq (binary_fan.mk (𝟙 X) 0); rintro ⟨⟨⟩⟩; dsimp; simp\n\nlemma inr_of_is_limit {X Y : C} {t : binary_bicone X Y} (ht : is_limit t.to_cone) :\n t.inr = ht.lift (binary_fan.mk 0 (𝟙 Y)) :=\nby apply ht.uniq (binary_fan.mk 0 (𝟙 Y)); rintro ⟨⟨⟩⟩; dsimp; simp\n\n/-- In a preadditive category, any binary bicone which is a limit cone is in fact a bilimit\n bicone. -/\ndef is_binary_bilimit_of_is_limit {X Y : C} (t : binary_bicone X Y) (ht : is_limit t.to_cone) :\n t.is_bilimit :=\nis_binary_bilimit_of_total _ (by refine binary_fan.is_limit.hom_ext ht _ _; simp)\n\n/-- We can turn any limit cone over a pair into a bilimit bicone. -/\ndef binary_bicone_is_bilimit_of_limit_cone_of_is_limit {X Y : C} {t : cone (pair X Y)}\n (ht : is_limit t) : (binary_bicone.of_limit_cone ht).is_bilimit :=\nis_binary_bilimit_of_total _ $ binary_fan.is_limit.hom_ext ht (by simp) (by simp)\n\n/-- In a preadditive category, if the product of `X` and `Y` exists, then the\n binary biproduct of `X` and `Y` exists. -/\nlemma has_binary_biproduct.of_has_binary_product (X Y : C) [has_binary_product X Y] :\n has_binary_biproduct X Y :=\nhas_binary_biproduct.mk\n{ bicone := _,\n is_bilimit := binary_bicone_is_bilimit_of_limit_cone_of_is_limit (limit.is_limit _) }\n\n/-- In a preadditive category, if all binary products exist, then all binary biproducts exist. -/\nlemma has_binary_biproducts.of_has_binary_products [has_binary_products C] :\n has_binary_biproducts C :=\n{ has_binary_biproduct := λ X Y, has_binary_biproduct.of_has_binary_product X Y, }\n\n/-- We can turn any colimit cocone over a pair into a bicone. -/\n@[simps]\ndef binary_bicone.of_colimit_cocone {X Y : C} {t : cocone (pair X Y)} (ht : is_colimit t) :\n binary_bicone X Y :=\n{ X := t.X,\n fst := ht.desc (binary_cofan.mk (𝟙 X) 0),\n snd := ht.desc (binary_cofan.mk 0 (𝟙 Y)),\n inl := t.ι.app ⟨walking_pair.left⟩,\n inr := t.ι.app ⟨walking_pair.right⟩ }\n\nlemma fst_of_is_colimit {X Y : C} {t : binary_bicone X Y} (ht : is_colimit t.to_cocone) :\n t.fst = ht.desc (binary_cofan.mk (𝟙 X) 0) :=\nbegin\n apply ht.uniq (binary_cofan.mk (𝟙 X) 0),\n rintro ⟨⟨⟩⟩; dsimp; simp\nend\n\nlemma snd_of_is_colimit {X Y : C} {t : binary_bicone X Y} (ht : is_colimit t.to_cocone) :\n t.snd = ht.desc (binary_cofan.mk 0 (𝟙 Y)) :=\nbegin\n apply ht.uniq (binary_cofan.mk 0 (𝟙 Y)),\n rintro ⟨⟨⟩⟩; dsimp; simp\nend\n\n/-- In a preadditive category, any binary bicone which is a colimit cocone is in fact a\n bilimit bicone. -/\ndef is_binary_bilimit_of_is_colimit {X Y : C} (t : binary_bicone X Y)\n (ht : is_colimit t.to_cocone) : t.is_bilimit :=\nis_binary_bilimit_of_total _\nbegin\n refine binary_cofan.is_colimit.hom_ext ht _ _; simp,\n { rw [category.comp_id t.inl] },\n { rw [category.comp_id t.inr] }\nend\n\n/-- We can turn any colimit cocone over a pair into a bilimit bicone. -/\ndef binary_bicone_is_bilimit_of_colimit_cocone_of_is_colimit {X Y : C} {t : cocone (pair X Y)}\n (ht : is_colimit t) : (binary_bicone.of_colimit_cocone ht).is_bilimit :=\nis_binary_bilimit_of_is_colimit (binary_bicone.of_colimit_cocone ht) $\n is_colimit.of_iso_colimit ht $ cocones.ext (iso.refl _) $ λ j, by { rcases j with ⟨⟨⟩⟩, tidy }\n\n/-- In a preadditive category, if the coproduct of `X` and `Y` exists, then the\n binary biproduct of `X` and `Y` exists. -/\nlemma has_binary_biproduct.of_has_binary_coproduct (X Y : C) [has_binary_coproduct X Y] :\n has_binary_biproduct X Y :=\nhas_binary_biproduct.mk\n{ bicone := _,\n is_bilimit := binary_bicone_is_bilimit_of_colimit_cocone_of_is_colimit (colimit.is_colimit _) }\n\n/-- In a preadditive category, if all binary coproducts exist, then all binary biproducts exist. -/\nlemma has_binary_biproducts.of_has_binary_coproducts [has_binary_coproducts C] :\n has_binary_biproducts C :=\n{ has_binary_biproduct := λ X Y, has_binary_biproduct.of_has_binary_coproduct X Y, }\n\nsection\nvariables {X Y : C} [has_binary_biproduct X Y]\n\n/--\nIn any preadditive category, any binary biproduct satsifies\n`biprod.fst ≫ biprod.inl + biprod.snd ≫ biprod.inr = 𝟙 (X ⊞ Y)`.\n-/\n@[simp] lemma biprod.total : biprod.fst ≫ biprod.inl + biprod.snd ≫ biprod.inr = 𝟙 (X ⊞ Y) :=\nbegin\n ext; simp [add_comp],\nend\n\nlemma biprod.lift_eq {T : C} {f : T ⟶ X} {g : T ⟶ Y} :\n biprod.lift f g = f ≫ biprod.inl + g ≫ biprod.inr :=\nbegin\n ext; simp [add_comp],\nend\n\n\n\n@[simp, reassoc] lemma biprod.lift_desc {T U : C} {f : T ⟶ X} {g : T ⟶ Y} {h : X ⟶ U} {i : Y ⟶ U} :\n biprod.lift f g ≫ biprod.desc h i = f ≫ h + g ≫ i :=\nby simp [biprod.lift_eq, biprod.desc_eq]\n\nlemma biprod.map_eq [has_binary_biproducts C] {W X Y Z : C} {f : W ⟶ Y} {g : X ⟶ Z} :\n biprod.map f g = biprod.fst ≫ f ≫ biprod.inl + biprod.snd ≫ g ≫ biprod.inr :=\nby apply biprod.hom_ext; apply biprod.hom_ext'; simp\n\n/--\nEvery split mono `f` with a cokernel induces a binary bicone with `f` as its `inl` and\nthe cokernel map as its `snd`.\nWe will show in `is_bilimit_binary_bicone_of_split_mono_of_cokernel` that this binary bicone is in\nfact already a biproduct. -/\n@[simps]\ndef binary_bicone_of_is_split_mono_of_cokernel {X Y : C} {f : X ⟶ Y} [is_split_mono f]\n {c : cokernel_cofork f} (i : is_colimit c) : binary_bicone X c.X :=\n{ X := Y,\n fst := retraction f,\n snd := c.π,\n inl := f,\n inr :=\n let c' : cokernel_cofork (𝟙 Y - (𝟙 Y - retraction f ≫ f)) :=\n cokernel_cofork.of_π (cofork.π c) (by simp) in\n let i' : is_colimit c' := is_cokernel_epi_comp i (retraction f) (by simp) in\n let i'' := is_colimit_cofork_of_cokernel_cofork i' in\n (split_epi_of_idempotent_of_is_colimit_cofork C (by simp) i'').section_,\n inl_fst' := by simp,\n inl_snd' := by simp,\n inr_fst' :=\n begin\n dsimp only,\n rw [split_epi_of_idempotent_of_is_colimit_cofork_section_,\n is_colimit_cofork_of_cokernel_cofork_desc, is_cokernel_epi_comp_desc],\n dsimp only [cokernel_cofork_of_cofork_of_π],\n letI := epi_of_is_colimit_cofork i,\n apply zero_of_epi_comp c.π,\n simp only [sub_comp, comp_sub, category.comp_id, category.assoc, is_split_mono.id, sub_self,\n cofork.is_colimit.π_desc_assoc, cokernel_cofork.π_of_π, is_split_mono.id_assoc],\n apply sub_eq_zero_of_eq,\n apply category.id_comp\n end,\n inr_snd' := by apply split_epi.id }\n\n/-- The bicone constructed in `binary_bicone_of_split_mono_of_cokernel` is a bilimit.\nThis is a version of the splitting lemma that holds in all preadditive categories. -/\ndef is_bilimit_binary_bicone_of_is_split_mono_of_cokernel {X Y : C} {f : X ⟶ Y} [is_split_mono f]\n {c : cokernel_cofork f} (i : is_colimit c) :\n (binary_bicone_of_is_split_mono_of_cokernel i).is_bilimit :=\nis_binary_bilimit_of_total _\nbegin\n simp only [binary_bicone_of_is_split_mono_of_cokernel_fst,\n binary_bicone_of_is_split_mono_of_cokernel_inr, binary_bicone_of_is_split_mono_of_cokernel_snd,\n split_epi_of_idempotent_of_is_colimit_cofork_section_],\n dsimp only [binary_bicone_of_is_split_mono_of_cokernel_X],\n rw [is_colimit_cofork_of_cokernel_cofork_desc, is_cokernel_epi_comp_desc],\n simp only [binary_bicone_of_is_split_mono_of_cokernel_inl, cofork.is_colimit.π_desc,\n cokernel_cofork_of_cofork_π, cofork.π_of_π, add_sub_cancel'_right]\nend\n\n/-- If `b` is a binary bicone such that `b.inl` is a kernel of `b.snd`, then `b` is a bilimit\n bicone. -/\ndef binary_bicone.is_bilimit_of_kernel_inl {X Y : C} (b : binary_bicone X Y)\n (hb : is_limit b.snd_kernel_fork) : b.is_bilimit :=\nis_binary_bilimit_of_is_limit _ $ binary_fan.is_limit.mk _\n (λ T f g, f ≫ b.inl + g ≫ b.inr) (λ T f g, by simp) (λ T f g, by simp) $ λ T f g m h₁ h₂,\n begin\n have h₁' : (m - (f ≫ b.inl + g ≫ b.inr)) ≫ b.fst = 0 := by simpa using sub_eq_zero.2 h₁,\n have h₂' : (m - (f ≫ b.inl + g ≫ b.inr)) ≫ b.snd = 0 := by simpa using sub_eq_zero.2 h₂,\n obtain ⟨q : T ⟶ X, hq : q ≫ b.inl = m - (f ≫ b.inl + g ≫ b.inr)⟩ :=\n kernel_fork.is_limit.lift' hb _ h₂',\n rw [←sub_eq_zero, ←hq, ←category.comp_id q, ←b.inl_fst, ←category.assoc, hq, h₁', zero_comp]\n end\n\n/-- If `b` is a binary bicone such that `b.inr` is a kernel of `b.fst`, then `b` is a bilimit\n bicone. -/\ndef binary_bicone.is_bilimit_of_kernel_inr {X Y : C} (b : binary_bicone X Y)\n (hb : is_limit b.fst_kernel_fork) : b.is_bilimit :=\nis_binary_bilimit_of_is_limit _ $ binary_fan.is_limit.mk _\n (λ T f g, f ≫ b.inl + g ≫ b.inr) (λ t f g, by simp) (λ t f g, by simp) $ λ T f g m h₁ h₂,\n begin\n have h₁' : (m - (f ≫ b.inl + g ≫ b.inr)) ≫ b.fst = 0 := by simpa using sub_eq_zero.2 h₁,\n have h₂' : (m - (f ≫ b.inl + g ≫ b.inr)) ≫ b.snd = 0 := by simpa using sub_eq_zero.2 h₂,\n obtain ⟨q : T ⟶ Y, hq : q ≫ b.inr = m - (f ≫ b.inl + g ≫ b.inr)⟩ :=\n kernel_fork.is_limit.lift' hb _ h₁',\n rw [←sub_eq_zero, ←hq, ←category.comp_id q, ←b.inr_snd, ←category.assoc, hq, h₂', zero_comp]\n end\n\n/-- If `b` is a binary bicone such that `b.fst` is a cokernel of `b.inr`, then `b` is a bilimit\n bicone. -/\ndef binary_bicone.is_bilimit_of_cokernel_fst {X Y : C} (b : binary_bicone X Y)\n (hb : is_colimit b.inr_cokernel_cofork) : b.is_bilimit :=\nis_binary_bilimit_of_is_colimit _ $ binary_cofan.is_colimit.mk _\n (λ T f g, b.fst ≫ f + b.snd ≫ g) (λ T f g, by simp) (λ T f g, by simp) $ λ T f g m h₁ h₂,\n begin\n have h₁' : b.inl ≫ (m - (b.fst ≫ f + b.snd ≫ g)) = 0 := by simpa using sub_eq_zero.2 h₁,\n have h₂' : b.inr ≫ (m - (b.fst ≫ f + b.snd ≫ g)) = 0 := by simpa using sub_eq_zero.2 h₂,\n obtain ⟨q : X ⟶ T, hq : b.fst ≫ q = m - (b.fst ≫ f + b.snd ≫ g)⟩ :=\n cokernel_cofork.is_colimit.desc' hb _ h₂',\n rw [←sub_eq_zero, ←hq, ←category.id_comp q, ←b.inl_fst, category.assoc, hq, h₁', comp_zero]\n end\n\n/-- If `b` is a binary bicone such that `b.snd` is a cokernel of `b.inl`, then `b` is a bilimit\n bicone. -/\ndef binary_bicone.is_bilimit_of_cokernel_snd {X Y : C} (b : binary_bicone X Y)\n (hb : is_colimit b.inl_cokernel_cofork) : b.is_bilimit :=\nis_binary_bilimit_of_is_colimit _ $ binary_cofan.is_colimit.mk _\n (λ T f g, b.fst ≫ f + b.snd ≫ g) (λ T f g, by simp) (λ T f g, by simp) $ λ T f g m h₁ h₂,\n begin\n have h₁' : b.inl ≫ (m - (b.fst ≫ f + b.snd ≫ g)) = 0 := by simpa using sub_eq_zero.2 h₁,\n have h₂' : b.inr ≫ (m - (b.fst ≫ f + b.snd ≫ g)) = 0 := by simpa using sub_eq_zero.2 h₂,\n obtain ⟨q : Y ⟶ T, hq : b.snd ≫ q = m - (b.fst ≫ f + b.snd ≫ g)⟩ :=\n cokernel_cofork.is_colimit.desc' hb _ h₁',\n rw [←sub_eq_zero, ←hq, ←category.id_comp q, ←b.inr_snd, category.assoc, hq, h₂', comp_zero]\n end\n\n/--\nEvery split epi `f` with a kernel induces a binary bicone with `f` as its `snd` and\nthe kernel map as its `inl`.\nWe will show in `binary_bicone_of_is_split_mono_of_cokernel` that this binary bicone is in fact\nalready a biproduct. -/\n@[simps]\ndef binary_bicone_of_is_split_epi_of_kernel {X Y : C} {f : X ⟶ Y} [is_split_epi f]\n {c : kernel_fork f} (i : is_limit c) : binary_bicone c.X Y :=\n{ X := X,\n fst :=\n let c' : kernel_fork (𝟙 X - (𝟙 X - f ≫ section_ f)) :=\n kernel_fork.of_ι (fork.ι c) (by simp) in\n let i' : is_limit c' := is_kernel_comp_mono i (section_ f) (by simp) in\n let i'' := is_limit_fork_of_kernel_fork i' in\n (split_mono_of_idempotent_of_is_limit_fork C (by simp) i'').retraction,\n snd := f,\n inl := c.ι,\n inr := section_ f,\n inl_fst' := by apply split_mono.id,\n inl_snd' := by simp,\n inr_fst' :=\n begin\n dsimp only,\n rw [split_mono_of_idempotent_of_is_limit_fork_retraction,\n is_limit_fork_of_kernel_fork_lift, is_kernel_comp_mono_lift],\n dsimp only [kernel_fork_of_fork_ι],\n letI := mono_of_is_limit_fork i,\n apply zero_of_comp_mono c.ι,\n simp only [comp_sub, category.comp_id, category.assoc, sub_self, fork.is_limit.lift_ι,\n fork.ι_of_ι, is_split_epi.id_assoc]\n end,\n inr_snd' := by simp }\n\n/-- The bicone constructed in `binary_bicone_of_is_split_epi_of_kernel` is a bilimit.\nThis is a version of the splitting lemma that holds in all preadditive categories. -/\ndef is_bilimit_binary_bicone_of_is_split_epi_of_kernel {X Y : C} {f : X ⟶ Y} [is_split_epi f]\n {c : kernel_fork f} (i : is_limit c) :\n (binary_bicone_of_is_split_epi_of_kernel i).is_bilimit :=\nbinary_bicone.is_bilimit_of_kernel_inl _ $ i.of_iso_limit $ fork.ext (iso.refl _) (by simp)\n\nend\n\nsection\nvariables {X Y : C} (f g : X ⟶ Y)\n\n/-- The existence of binary biproducts implies that there is at most one preadditive structure. -/\nlemma biprod.add_eq_lift_id_desc [has_binary_biproduct X X] :\n f + g = biprod.lift (𝟙 X) (𝟙 X) ≫ biprod.desc f g :=\nby simp\n\n/-- The existence of binary biproducts implies that there is at most one preadditive structure. -/\nlemma biprod.add_eq_lift_desc_id [has_binary_biproduct Y Y] :\n f + g = biprod.lift f g ≫ biprod.desc (𝟙 Y) (𝟙 Y) :=\nby simp\n\nend\n\nend limits\n\nopen category_theory.limits\n\nsection\nlocal attribute [ext] preadditive\n\n/-- The existence of binary biproducts implies that there is at most one preadditive structure. -/\ninstance subsingleton_preadditive_of_has_binary_biproducts {C : Type u} [category.{v} C]\n [has_zero_morphisms C] [has_binary_biproducts C] : subsingleton (preadditive C) :=\nsubsingleton.intro $ λ a b,\nbegin\n ext X Y f g,\n have h₁ := @biprod.add_eq_lift_id_desc _ _ a _ _ f g\n (by convert (infer_instance : has_binary_biproduct X X)),\n have h₂ := @biprod.add_eq_lift_id_desc _ _ b _ _ f g\n (by convert (infer_instance : has_binary_biproduct X X)),\n refine h₁.trans (eq.trans _ h₂.symm),\n congr' 2;\n exact subsingleton.elim _ _\nend\nend\n\nsection\nvariables [has_binary_biproducts.{v} C]\n\nvariables {X₁ X₂ Y₁ Y₂ : C}\nvariables (f₁₁ : X₁ ⟶ Y₁) (f₁₂ : X₁ ⟶ Y₂) (f₂₁ : X₂ ⟶ Y₁) (f₂₂ : X₂ ⟶ Y₂)\n\n/--\nThe \"matrix\" morphism `X₁ ⊞ X₂ ⟶ Y₁ ⊞ Y₂` with specified components.\n-/\ndef biprod.of_components : X₁ ⊞ X₂ ⟶ Y₁ ⊞ Y₂ :=\nbiprod.fst ≫ f₁₁ ≫ biprod.inl +\nbiprod.fst ≫ f₁₂ ≫ biprod.inr +\nbiprod.snd ≫ f₂₁ ≫ biprod.inl +\nbiprod.snd ≫ f₂₂ ≫ biprod.inr\n\n@[simp]\nlemma biprod.inl_of_components :\n biprod.inl ≫ biprod.of_components f₁₁ f₁₂ f₂₁ f₂₂ =\n f₁₁ ≫ biprod.inl + f₁₂ ≫ biprod.inr :=\nby simp [biprod.of_components]\n\n@[simp]\nlemma biprod.inr_of_components :\n biprod.inr ≫ biprod.of_components f₁₁ f₁₂ f₂₁ f₂₂ =\n f₂₁ ≫ biprod.inl + f₂₂ ≫ biprod.inr :=\nby simp [biprod.of_components]\n\n@[simp]\nlemma biprod.of_components_fst :\n biprod.of_components f₁₁ f₁₂ f₂₁ f₂₂ ≫ biprod.fst =\n biprod.fst ≫ f₁₁ + biprod.snd ≫ f₂₁ :=\nby simp [biprod.of_components]\n\n@[simp]\nlemma biprod.of_components_snd :\n biprod.of_components f₁₁ f₁₂ f₂₁ f₂₂ ≫ biprod.snd =\n biprod.fst ≫ f₁₂ + biprod.snd ≫ f₂₂ :=\nby simp [biprod.of_components]\n\n@[simp]\nlemma biprod.of_components_eq (f : X₁ ⊞ X₂ ⟶ Y₁ ⊞ Y₂) :\n biprod.of_components (biprod.inl ≫ f ≫ biprod.fst) (biprod.inl ≫ f ≫ biprod.snd)\n (biprod.inr ≫ f ≫ biprod.fst) (biprod.inr ≫ f ≫ biprod.snd) = f :=\nbegin\n ext;\n simp only [category.comp_id, biprod.inr_fst, biprod.inr_snd, biprod.inl_snd, add_zero, zero_add,\n biprod.inl_of_components, biprod.inr_of_components, eq_self_iff_true, category.assoc, comp_zero,\n biprod.inl_fst, preadditive.add_comp],\nend\n\n@[simp]\nlemma biprod.of_components_comp {X₁ X₂ Y₁ Y₂ Z₁ Z₂ : C}\n (f₁₁ : X₁ ⟶ Y₁) (f₁₂ : X₁ ⟶ Y₂) (f₂₁ : X₂ ⟶ Y₁) (f₂₂ : X₂ ⟶ Y₂)\n (g₁₁ : Y₁ ⟶ Z₁) (g₁₂ : Y₁ ⟶ Z₂) (g₂₁ : Y₂ ⟶ Z₁) (g₂₂ : Y₂ ⟶ Z₂) :\n biprod.of_components f₁₁ f₁₂ f₂₁ f₂₂ ≫ biprod.of_components g₁₁ g₁₂ g₂₁ g₂₂ =\n biprod.of_components\n (f₁₁ ≫ g₁₁ + f₁₂ ≫ g₂₁) (f₁₁ ≫ g₁₂ + f₁₂ ≫ g₂₂)\n (f₂₁ ≫ g₁₁ + f₂₂ ≫ g₂₁) (f₂₁ ≫ g₁₂ + f₂₂ ≫ g₂₂) :=\nbegin\n dsimp [biprod.of_components],\n apply biprod.hom_ext; apply biprod.hom_ext';\n simp only [add_comp, comp_add, add_comp_assoc, add_zero, zero_add,\n biprod.inl_fst, biprod.inl_snd, biprod.inr_fst, biprod.inr_snd,\n biprod.inl_fst_assoc, biprod.inl_snd_assoc, biprod.inr_fst_assoc, biprod.inr_snd_assoc,\n comp_zero, zero_comp,\n category.comp_id, category.assoc],\nend\n\n/--\nThe unipotent upper triangular matrix\n```\n(1 r)\n(0 1)\n```\nas an isomorphism.\n-/\n@[simps]\ndef biprod.unipotent_upper {X₁ X₂ : C} (r : X₁ ⟶ X₂) : X₁ ⊞ X₂ ≅ X₁ ⊞ X₂ :=\n{ hom := biprod.of_components (𝟙 _) r 0 (𝟙 _),\n inv := biprod.of_components (𝟙 _) (-r) 0 (𝟙 _), }\n\n/--\nThe unipotent lower triangular matrix\n```\n(1 0)\n(r 1)\n```\nas an isomorphism.\n-/\n@[simps]\ndef biprod.unipotent_lower {X₁ X₂ : C} (r : X₂ ⟶ X₁) : X₁ ⊞ X₂ ≅ X₁ ⊞ X₂ :=\n{ hom := biprod.of_components (𝟙 _) 0 r (𝟙 _),\n inv := biprod.of_components (𝟙 _) 0 (-r) (𝟙 _), }\n\n/--\nIf `f` is a morphism `X₁ ⊞ X₂ ⟶ Y₁ ⊞ Y₂` whose `X₁ ⟶ Y₁` entry is an isomorphism,\nthen we can construct isomorphisms `L : X₁ ⊞ X₂ ≅ X₁ ⊞ X₂` and `R : Y₁ ⊞ Y₂ ≅ Y₁ ⊞ Y₂`\nso that `L.hom ≫ g ≫ R.hom` is diagonal (with `X₁ ⟶ Y₁` component still `f`),\nvia Gaussian elimination.\n\n(This is the version of `biprod.gaussian` written in terms of components.)\n-/\ndef biprod.gaussian' [is_iso f₁₁] :\n Σ' (L : X₁ ⊞ X₂ ≅ X₁ ⊞ X₂) (R : Y₁ ⊞ Y₂ ≅ Y₁ ⊞ Y₂) (g₂₂ : X₂ ⟶ Y₂),\n L.hom ≫ (biprod.of_components f₁₁ f₁₂ f₂₁ f₂₂) ≫ R.hom = biprod.map f₁₁ g₂₂ :=\n⟨biprod.unipotent_lower (-(f₂₁ ≫ inv f₁₁)),\n biprod.unipotent_upper (-(inv f₁₁ ≫ f₁₂)),\n f₂₂ - f₂₁ ≫ (inv f₁₁) ≫ f₁₂,\n by ext; simp; abel⟩\n\n/--\nIf `f` is a morphism `X₁ ⊞ X₂ ⟶ Y₁ ⊞ Y₂` whose `X₁ ⟶ Y₁` entry is an isomorphism,\nthen we can construct isomorphisms `L : X₁ ⊞ X₂ ≅ X₁ ⊞ X₂` and `R : Y₁ ⊞ Y₂ ≅ Y₁ ⊞ Y₂`\nso that `L.hom ≫ g ≫ R.hom` is diagonal (with `X₁ ⟶ Y₁` component still `f`),\nvia Gaussian elimination.\n-/\ndef biprod.gaussian (f : X₁ ⊞ X₂ ⟶ Y₁ ⊞ Y₂) [is_iso (biprod.inl ≫ f ≫ biprod.fst)] :\n Σ' (L : X₁ ⊞ X₂ ≅ X₁ ⊞ X₂) (R : Y₁ ⊞ Y₂ ≅ Y₁ ⊞ Y₂) (g₂₂ : X₂ ⟶ Y₂),\n L.hom ≫ f ≫ R.hom = biprod.map (biprod.inl ≫ f ≫ biprod.fst) g₂₂ :=\nbegin\n let := biprod.gaussian'\n (biprod.inl ≫ f ≫ biprod.fst) (biprod.inl ≫ f ≫ biprod.snd)\n (biprod.inr ≫ f ≫ biprod.fst) (biprod.inr ≫ f ≫ biprod.snd),\n simpa [biprod.of_components_eq],\nend\n\n/--\nIf `X₁ ⊞ X₂ ≅ Y₁ ⊞ Y₂` via a two-by-two matrix whose `X₁ ⟶ Y₁` entry is an isomorphism,\nthen we can construct an isomorphism `X₂ ≅ Y₂`, via Gaussian elimination.\n-/\ndef biprod.iso_elim' [is_iso f₁₁] [is_iso (biprod.of_components f₁₁ f₁₂ f₂₁ f₂₂)] : X₂ ≅ Y₂ :=\nbegin\n obtain ⟨L, R, g, w⟩ := biprod.gaussian' f₁₁ f₁₂ f₂₁ f₂₂,\n letI : is_iso (biprod.map f₁₁ g) := by { rw ←w, apply_instance, },\n letI : is_iso g := (is_iso_right_of_is_iso_biprod_map f₁₁ g),\n exact as_iso g,\nend\n\n/--\nIf `f` is an isomorphism `X₁ ⊞ X₂ ≅ Y₁ ⊞ Y₂` whose `X₁ ⟶ Y₁` entry is an isomorphism,\nthen we can construct an isomorphism `X₂ ≅ Y₂`, via Gaussian elimination.\n-/\ndef biprod.iso_elim (f : X₁ ⊞ X₂ ≅ Y₁ ⊞ Y₂) [is_iso (biprod.inl ≫ f.hom ≫ biprod.fst)] : X₂ ≅ Y₂ :=\nbegin\n letI : is_iso (biprod.of_components\n (biprod.inl ≫ f.hom ≫ biprod.fst)\n (biprod.inl ≫ f.hom ≫ biprod.snd)\n (biprod.inr ≫ f.hom ≫ biprod.fst)\n (biprod.inr ≫ f.hom ≫ biprod.snd)) :=\n by { simp only [biprod.of_components_eq], apply_instance, },\n exact biprod.iso_elim'\n (biprod.inl ≫ f.hom ≫ biprod.fst)\n (biprod.inl ≫ f.hom ≫ biprod.snd)\n (biprod.inr ≫ f.hom ≫ biprod.fst)\n (biprod.inr ≫ f.hom ≫ biprod.snd)\nend\n\nlemma biprod.column_nonzero_of_iso {W X Y Z : C}\n (f : W ⊞ X ⟶ Y ⊞ Z) [is_iso f] :\n 𝟙 W = 0 ∨ biprod.inl ≫ f ≫ biprod.fst ≠ 0 ∨ biprod.inl ≫ f ≫ biprod.snd ≠ 0 :=\nbegin\n by_contra' h,\n rcases h with ⟨nz, a₁, a₂⟩,\n set x := biprod.inl ≫ f ≫ inv f ≫ biprod.fst,\n have h₁ : x = 𝟙 W, by simp [x],\n have h₀ : x = 0,\n { dsimp [x],\n rw [←category.id_comp (inv f), category.assoc, ←biprod.total],\n conv_lhs { slice 2 3, rw [comp_add], },\n simp only [category.assoc],\n rw [comp_add_assoc, add_comp],\n conv_lhs { congr, skip, slice 1 3, rw a₂, },\n simp only [zero_comp, add_zero],\n conv_lhs { slice 1 3, rw a₁, },\n simp only [zero_comp], },\n exact nz (h₁.symm.trans h₀),\nend\n\nend\n\nlemma biproduct.column_nonzero_of_iso'\n {σ τ : Type} [finite τ]\n {S : σ → C} [has_biproduct S] {T : τ → C} [has_biproduct T]\n (s : σ) (f : ⨁ S ⟶ ⨁ T) [is_iso f] :\n (∀ t : τ, biproduct.ι S s ≫ f ≫ biproduct.π T t = 0) → 𝟙 (S s) = 0 :=\nbegin\n casesI nonempty_fintype τ,\n intro z,\n set x := biproduct.ι S s ≫ f ≫ inv f ≫ biproduct.π S s,\n have h₁ : x = 𝟙 (S s), by simp [x],\n have h₀ : x = 0,\n { dsimp [x],\n rw [←category.id_comp (inv f), category.assoc, ←biproduct.total],\n simp only [comp_sum_assoc],\n conv_lhs { congr, apply_congr, skip, simp only [reassoc_of z], },\n simp, },\n exact h₁.symm.trans h₀,\nend\n\n/--\nIf `f : ⨁ S ⟶ ⨁ T` is an isomorphism, and `s` is a non-trivial summand of the source,\nthen there is some `t` in the target so that the `s, t` matrix entry of `f` is nonzero.\n-/\ndef biproduct.column_nonzero_of_iso\n {σ τ : Type} [fintype τ]\n {S : σ → C} [has_biproduct S] {T : τ → C} [has_biproduct T]\n (s : σ) (nz : 𝟙 (S s) ≠ 0)\n (f : ⨁ S ⟶ ⨁ T) [is_iso f] :\n trunc (Σ' t : τ, biproduct.ι S s ≫ f ≫ biproduct.π T t ≠ 0) :=\nbegin\n classical,\n apply trunc_sigma_of_exists,\n have t := biproduct.column_nonzero_of_iso'.{v} s f,\n by_contradiction h,\n simp only [not_exists_not] at h,\n exact nz (t h)\nend\n\nsection preadditive\nvariables {D : Type.{u'}} [category.{v'} D] [preadditive.{v'} D]\nvariables (F : C ⥤ D) [preserves_zero_morphisms F]\n\nnamespace limits\n\nsection fintype\nvariables {J : Type} [fintype J]\n\nlocal attribute [tidy] tactic.discrete_cases\n\n/-- A functor between preadditive categories that preserves (zero morphisms and) finite biproducts\n preserves finite products. -/\ndef preserves_product_of_preserves_biproduct {f : J → C} [preserves_biproduct f F] :\n preserves_limit (discrete.functor f) F :=\n{ preserves := λ c hc, is_limit.of_iso_limit\n ((is_limit.postcompose_inv_equiv (discrete.comp_nat_iso_discrete _ _) _).symm\n (is_bilimit_of_preserves F (bicone_is_bilimit_of_limit_cone_of_is_limit hc)).is_limit) $\n cones.ext (iso.refl _) (by tidy) }\n\nsection\nlocal attribute [instance] preserves_product_of_preserves_biproduct\n\n/-- A functor between preadditive categories that preserves (zero morphisms and) finite biproducts\n preserves finite products. -/\ndef preserves_products_of_shape_of_preserves_biproducts_of_shape\n [preserves_biproducts_of_shape J F] : preserves_limits_of_shape (discrete J) F :=\n{ preserves_limit := λ f, preserves_limit_of_iso_diagram _ discrete.nat_iso_functor.symm }\n\nend\n\n/-- A functor between preadditive categories that preserves (zero morphisms and) finite products\n preserves finite biproducts. -/\ndef preserves_biproduct_of_preserves_product {f : J → C} [preserves_limit (discrete.functor f) F] :\n preserves_biproduct f F :=\n{ preserves := λ b hb, is_bilimit_of_is_limit _ $\n is_limit.of_iso_limit ((is_limit.postcompose_hom_equiv (discrete.comp_nat_iso_discrete _ _)\n (F.map_cone b.to_cone)).symm (is_limit_of_preserves F hb.is_limit)) $\n cones.ext (iso.refl _) (by tidy) }\n\n/-- If the (product-like) biproduct comparison for `F` and `f` is a monomorphism, then `F`\n preserves the biproduct of `f`. For the converse, see `map_biproduct`. -/\ndef preserves_biproduct_of_mono_biproduct_comparison {f : J → C} [has_biproduct f]\n [has_biproduct (F.obj ∘ f)] [mono (biproduct_comparison F f)] : preserves_biproduct f F :=\nbegin\n have : pi_comparison F f = (F.map_iso (biproduct.iso_product f)).inv ≫\n biproduct_comparison F f ≫ (biproduct.iso_product _).hom,\n { ext, convert pi_comparison_comp_π F f j.as; simp [← functor.map_comp] },\n haveI : is_iso (biproduct_comparison F f) := is_iso_of_mono_of_is_split_epi _,\n haveI : is_iso (pi_comparison F f) := by { rw this, apply_instance },\n haveI := preserves_product.of_iso_comparison F f,\n apply preserves_biproduct_of_preserves_product\nend\n\n/-- If the (coproduct-like) biproduct comparison for `F` and `f` is an epimorphism, then `F`\n preserves the biproduct of `F` and `f`. For the converse, see `map_biproduct`. -/\ndef preserves_biproduct_of_epi_biproduct_comparison' {f : J → C} [has_biproduct f]\n [has_biproduct (F.obj ∘ f)] [epi (biproduct_comparison' F f)] : preserves_biproduct f F :=\nbegin\n haveI : epi ((split_epi_biproduct_comparison F f).section_) := by simpa,\n haveI : is_iso (biproduct_comparison F f) := is_iso.of_epi_section'\n (split_epi_biproduct_comparison F f),\n apply preserves_biproduct_of_mono_biproduct_comparison\nend\n\n/-- A functor between preadditive categories that preserves (zero morphisms and) finite products\n preserves finite biproducts. -/\ndef preserves_biproducts_of_shape_of_preserves_products_of_shape\n [preserves_limits_of_shape (discrete J) F] : preserves_biproducts_of_shape J F :=\n{ preserves := λ f, preserves_biproduct_of_preserves_product F }\n\n/-- A functor between preadditive categories that preserves (zero morphisms and) finite biproducts\n preserves finite coproducts. -/\ndef preserves_coproduct_of_preserves_biproduct {f : J → C} [preserves_biproduct f F] :\n preserves_colimit (discrete.functor f) F :=\n{ preserves := λ c hc, is_colimit.of_iso_colimit\n ((is_colimit.precompose_hom_equiv (discrete.comp_nat_iso_discrete _ _) _).symm\n (is_bilimit_of_preserves F\n (bicone_is_bilimit_of_colimit_cocone_of_is_colimit hc)).is_colimit) $\n cocones.ext (iso.refl _) (by tidy) }\n\nsection\nlocal attribute [instance] preserves_coproduct_of_preserves_biproduct\n\n/-- A functor between preadditive categories that preserves (zero morphisms and) finite biproducts\n preserves finite coproducts. -/\ndef preserves_coproducts_of_shape_of_preserves_biproducts_of_shape\n [preserves_biproducts_of_shape J F] : preserves_colimits_of_shape (discrete J) F :=\n{ preserves_colimit := λ f, preserves_colimit_of_iso_diagram _ discrete.nat_iso_functor.symm }\n\nend\n\n/-- A functor between preadditive categories that preserves (zero morphisms and) finite coproducts\n preserves finite biproducts. -/\ndef preserves_biproduct_of_preserves_coproduct {f : J → C}\n [preserves_colimit (discrete.functor f) F] : preserves_biproduct f F :=\n{ preserves := λ b hb, is_bilimit_of_is_colimit _ $\n is_colimit.of_iso_colimit ((is_colimit.precompose_inv_equiv (discrete.comp_nat_iso_discrete _ _)\n (F.map_cocone b.to_cocone)).symm (is_colimit_of_preserves F hb.is_colimit)) $\n cocones.ext (iso.refl _) (by tidy) }\n\n/-- A functor between preadditive categories that preserves (zero morphisms and) finite coproducts\n preserves finite biproducts. -/\ndef preserves_biproducts_of_shape_of_preserves_coproducts_of_shape\n [preserves_colimits_of_shape (discrete J) F] : preserves_biproducts_of_shape J F :=\n{ preserves := λ f, preserves_biproduct_of_preserves_coproduct F }\n\nend fintype\n\n/-- A functor between preadditive categories that preserves (zero morphisms and) binary biproducts\n preserves binary products. -/\ndef preserves_binary_product_of_preserves_binary_biproduct {X Y : C}\n [preserves_binary_biproduct X Y F] : preserves_limit (pair X Y) F :=\n{ preserves := λ c hc, is_limit.of_iso_limit\n ((is_limit.postcompose_inv_equiv (by exact diagram_iso_pair _) _).symm\n (is_binary_bilimit_of_preserves F\n (binary_bicone_is_bilimit_of_limit_cone_of_is_limit hc)).is_limit) $\n cones.ext (iso.refl _) (λ j, by { rcases j with ⟨⟨⟩⟩, tidy }) }\n\nsection\nlocal attribute [instance] preserves_binary_product_of_preserves_binary_biproduct\n\n/-- A functor between preadditive categories that preserves (zero morphisms and) binary biproducts\n preserves binary products. -/\ndef preserves_binary_products_of_preserves_binary_biproducts\n [preserves_binary_biproducts F] : preserves_limits_of_shape (discrete walking_pair) F :=\n{ preserves_limit := λ K, preserves_limit_of_iso_diagram _ (diagram_iso_pair _).symm }\n\nend\n\n/-- A functor between preadditive categories that preserves (zero morphisms and) binary products\n preserves binary biproducts. -/\ndef preserves_binary_biproduct_of_preserves_binary_product {X Y : C}\n [preserves_limit (pair X Y) F] : preserves_binary_biproduct X Y F :=\n{ preserves := λ b hb, is_binary_bilimit_of_is_limit _ $\n is_limit.of_iso_limit ((is_limit.postcompose_hom_equiv (by exact diagram_iso_pair _)\n (F.map_cone b.to_cone)).symm (is_limit_of_preserves F hb.is_limit)) $\n cones.ext (iso.refl _) (λ j, by { rcases j with ⟨⟨⟩⟩, tidy }) }\n\n/-- If the (product-like) biproduct comparison for `F`, `X` and `Y` is a monomorphism, then\n `F` preserves the biproduct of `X` and `Y`. For the converse, see `map_biprod`. -/\ndef preserves_binary_biproduct_of_mono_biprod_comparison {X Y : C} [has_binary_biproduct X Y]\n [has_binary_biproduct (F.obj X) (F.obj Y)] [mono (biprod_comparison F X Y)] :\n preserves_binary_biproduct X Y F :=\nbegin\n have : prod_comparison F X Y = (F.map_iso (biprod.iso_prod X Y)).inv ≫\n biprod_comparison F X Y ≫ (biprod.iso_prod _ _).hom := by { ext; simp [← functor.map_comp] },\n haveI : is_iso (biprod_comparison F X Y) := is_iso_of_mono_of_is_split_epi _,\n haveI : is_iso (prod_comparison F X Y) := by { rw this, apply_instance },\n haveI := preserves_limit_pair.of_iso_prod_comparison F X Y,\n apply preserves_binary_biproduct_of_preserves_binary_product\nend\n\n/-- If the (coproduct-like) biproduct comparison for `F`, `X` and `Y` is an epimorphism, then\n `F` preserves the biproduct of `X` and `Y`. For the converse, see `map_biprod`. -/\ndef preserves_binary_biproduct_of_epi_biprod_comparison' {X Y : C} [has_binary_biproduct X Y]\n [has_binary_biproduct (F.obj X) (F.obj Y)] [epi (biprod_comparison' F X Y)] :\n preserves_binary_biproduct X Y F :=\nbegin\n haveI : epi ((split_epi_biprod_comparison F X Y).section_) := by simpa,\n haveI : is_iso (biprod_comparison F X Y) := is_iso.of_epi_section'\n (split_epi_biprod_comparison F X Y),\n apply preserves_binary_biproduct_of_mono_biprod_comparison\nend\n\n/-- A functor between preadditive categories that preserves (zero morphisms and) binary products\n preserves binary biproducts. -/\ndef preserves_binary_biproducts_of_preserves_binary_products\n [preserves_limits_of_shape (discrete walking_pair) F] : preserves_binary_biproducts F :=\n{ preserves := λ X Y, preserves_binary_biproduct_of_preserves_binary_product F }\n\n/-- A functor between preadditive categories that preserves (zero morphisms and) binary biproducts\n preserves binary coproducts. -/\ndef preserves_binary_coproduct_of_preserves_binary_biproduct {X Y : C}\n [preserves_binary_biproduct X Y F] : preserves_colimit (pair X Y) F :=\n{ preserves := λ c hc, is_colimit.of_iso_colimit\n ((is_colimit.precompose_hom_equiv (by exact diagram_iso_pair _) _).symm\n (is_binary_bilimit_of_preserves F\n (binary_bicone_is_bilimit_of_colimit_cocone_of_is_colimit hc)).is_colimit) $\n cocones.ext (iso.refl _) (λ j, by { rcases j with ⟨⟨⟩⟩, tidy }) }\n\nsection\nlocal attribute [instance] preserves_binary_coproduct_of_preserves_binary_biproduct\n\n/-- A functor between preadditive categories that preserves (zero morphisms and) binary biproducts\n preserves binary coproducts. -/\ndef preserves_binary_coproducts_of_preserves_binary_biproducts\n [preserves_binary_biproducts F] : preserves_colimits_of_shape (discrete walking_pair) F :=\n{ preserves_colimit := λ K, preserves_colimit_of_iso_diagram _ (diagram_iso_pair _).symm }\n\nend\n\n/-- A functor between preadditive categories that preserves (zero morphisms and) binary coproducts\n preserves binary biproducts. -/\ndef preserves_binary_biproduct_of_preserves_binary_coproduct {X Y : C}\n [preserves_colimit (pair X Y) F] : preserves_binary_biproduct X Y F :=\n{ preserves := λ b hb, is_binary_bilimit_of_is_colimit _ $\n is_colimit.of_iso_colimit ((is_colimit.precompose_inv_equiv (by exact diagram_iso_pair _)\n (F.map_cocone b.to_cocone)).symm (is_colimit_of_preserves F hb.is_colimit)) $\n cocones.ext (iso.refl _) (λ j, by { rcases j with ⟨⟨⟩⟩, tidy }) }\n\n/-- A functor between preadditive categories that preserves (zero morphisms and) binary coproducts\n preserves binary biproducts. -/\ndef preserves_binary_biproducts_of_preserves_binary_coproducts\n [preserves_colimits_of_shape (discrete walking_pair) F] : preserves_binary_biproducts F :=\n{ preserves := λ X Y, preserves_binary_biproduct_of_preserves_binary_coproduct F }\n\nend limits\n\nend preadditive\n\nend category_theory\n", "meta": {"author": "leanprover-community", "repo": "mathlib", "sha": "5e526d18cea33550268dcbbddcb822d5cde40654", "save_path": "github-repos/lean/leanprover-community-mathlib", "path": "github-repos/lean/leanprover-community-mathlib/mathlib-5e526d18cea33550268dcbbddcb822d5cde40654/src/category_theory/preadditive/biproducts.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43398146480389854, "lm_q2_score": 0.0402379439184139, "lm_q1q2_score": 0.017462521842410386}} {"text": "import for_mathlib.algebra.homology.hom_complex\nimport for_mathlib.algebra.homology.shift\n\nopen category_theory category_theory.category category_theory.limits\n\nvariables {C : Type*} [category C] [preadditive C]\n\nnamespace cochain_complex\n\nnamespace hom_complex\n\nnamespace cochain\n\nvariables {K L : cochain_complex C ℤ} {i : ℤ}\n (γ γ₂ : cochain K L i) (n : ℤ) (γ' γ'₂: cochain K (L⟦n⟧) i)\n\ndef right_shift (j : ℤ) (hj : i = j + n) : cochain K (L⟦n⟧) j :=\ncochain.mk (λ p q hpq, γ.v p (p+i) rfl ≫\n (L.shift_functor_obj_X_iso n q (p+i) (by linarith)).inv)\n\nlemma right_shift_v (j : ℤ) (hj : i = j + n) (p q : ℤ) (hpq : q = p + j)\n (p' : ℤ) (hp' : p' = p + i) :\n (γ.right_shift n j hj).v p q hpq = γ.v p p' hp' ≫\n (L.shift_functor_obj_X_iso n q p' (by rw [hp', hpq, hj, add_assoc])).inv :=\nby { subst hp', refl, }\n\n@[simp]\nlemma right_shift_zero (j : ℤ) (hj : i = j + n) :\n (0 : cochain K L i).right_shift n j hj = 0 :=\nby { dsimp [right_shift], tidy, }\n\n@[simp]\nlemma right_shift_smul (j : ℤ) (hj : i = j + n) (a : ℤ) :\n (a • γ).right_shift n j hj = a • γ.right_shift n j hj :=\nbegin\n ext p q hpq,\n simp only [right_shift_v _ n j hj p q hpq _ rfl, zsmul_v, linear.smul_comp],\nend\n\n@[simp]\nlemma right_shift_add (j : ℤ) (hj : i = j + n) :\n (γ + γ₂).right_shift n j hj = γ.right_shift n j hj + γ₂.right_shift n j hj :=\nbegin\n ext p q hpq,\n simp only [right_shift_v _ n j hj p q hpq _ rfl, add_v, preadditive.add_comp],\nend\n\nvariable {n}\n\ndef right_unshift (j : ℤ) (hj : j = i + n) : cochain K L j :=\ncochain.mk (λ p q hpq, γ'.v p (p+i) rfl ≫\n (L.shift_functor_obj_X_iso n (p+i) q (by linarith)).hom)\n\nlemma right_unshift_v (j : ℤ) (hj : j = i + n) (p q : ℤ) (hpq : q = p + j)\n (p' : ℤ) (hp' : p' = p + i):\n (γ'.right_unshift j hj).v p q hpq = γ'.v p p' hp' ≫\n (L.shift_functor_obj_X_iso n p' q (by rw [hp', hpq, hj, add_assoc])).hom :=\nby { subst hp', refl, }\n\n@[simp]\nlemma right_unshift_zero (j : ℤ) (hj : j = i + n) :\n (0 : cochain K (L⟦n⟧) i).right_unshift j hj = 0 :=\nby { dsimp [right_unshift], tidy, }\n\n@[simp]\nlemma right_unshift_smul (j : ℤ) (hj : j = i + n) (a : ℤ) :\n (a • γ').right_unshift j hj = a • γ'.right_unshift j hj :=\nbegin\n ext p q hpq,\n simp only [right_unshift_v _ j hj p q hpq _ rfl, zsmul_v, linear.smul_comp],\nend\n\n@[simp]\nlemma right_unshift_add (j : ℤ) (hj : j = i + n) :\n (γ' + γ'₂).right_unshift j hj = γ'.right_unshift j hj + γ'₂.right_unshift j hj :=\nbegin\n ext p q hpq,\n simp only [right_unshift_v _ j hj p q hpq _ rfl, add_v, preadditive.add_comp],\nend\n\n@[simp]\nlemma right_unshift_shift (j : ℤ) (hj : j = i + n) :\n (γ'.right_unshift j hj).right_shift n i hj = γ' :=\nbegin\n ext p q hpq,\n simp only [cochain.right_shift_v _ n i hj p q hpq _ rfl,\n cochain.right_unshift_v _ j hj p (p+j) rfl q hpq,\n shift_functor_obj_X_iso, assoc,\n homological_complex.X_iso_of_eq_hom_inv,\n homological_complex.X_iso_of_eq_refl, iso.refl_hom],\n erw category.comp_id,\nend\n\nvariable (n)\n\n@[simp]\nlemma right_shift_unshift (j : ℤ) (hj : i = j + n) :\n (γ.right_shift n j hj).right_unshift i hj = γ :=\nbegin\n ext p q hpq,\n simp only [cochain.right_unshift_v _ i hj p q hpq _ rfl,\n cochain.right_shift_v _ n j hj p (p+j) rfl q hpq,\n shift_functor_obj_X_iso, assoc,\n homological_complex.X_iso_of_eq_inv_hom,\n homological_complex.X_iso_of_eq_refl, iso.refl_hom, category.comp_id],\nend\n\nlemma δ_right_shift (i' j j' : ℤ) (hj : i = j + n) (hj' : i' = j' + n) :\n δ j j' (γ.right_shift n j hj) = ε n • (δ i i' γ).right_shift n j' hj' :=\nbegin\n by_cases h₁ : i+1 = i', swap,\n { have h₂ : j+1 ≠ j' := λ h₃, by { exfalso, apply h₁, linarith, },\n simp only [δ_shape _ _ h₁, δ_shape _ _ h₂, right_shift_zero, smul_zero], },\n { have h₂ : j' = j+1 := by linarith,\n substs h₁ h₂,\n ext p q hpq,\n simp only [δ_v j _ rfl _ p q hpq (p+j) (p+1) (by linarith) rfl,\n γ.right_shift_v n j hj p (p+j) rfl (p+j+n) (by linarith),\n γ.right_shift_v n j hj (p+1) q (by linarith) (p+1+i) rfl, zsmul_v,\n right_shift_v _ n (j+1) hj' p q hpq (p+1+i) (by linarith),\n δ_v i _ rfl _ p (p+1+i) (by linarith) (p+j+n) _ (by linarith) rfl,\n shift_functor_obj_X_iso, assoc, preadditive.add_comp,\n homological_complex.d_comp_X_iso_of_eq_inv, linear.smul_comp,\n smul_add, smul_smul, ← ε_add],\n congr' 1,\n { erw [shift_functor_obj_d,\n homological_complex.X_iso_of_eq_refl,\n iso.refl_inv, category.id_comp, linear.comp_smul], },\n { congr' 1,\n rw [ε_eq_iff],\n exact ⟨-n, by linarith⟩, }, },\nend\n\nvariable {n}\n\nlemma δ_right_unshift (i' j j' : ℤ) (hj : j = i + n) (hj' : j' = i' + n) :\n δ j j' (γ'.right_unshift j hj) = ε n • (δ i i' γ').right_unshift j' hj' :=\nbegin\n conv_rhs { rw ← γ'.right_unshift_shift j hj, },\n rw [(γ'.right_unshift j hj).δ_right_shift n j' i i' hj hj',\n right_unshift_smul, cochain.right_shift_unshift, smul_smul,\n ← ε_add, ε_even _ (even_add_self n), one_smul],\nend\n\n@[simps]\ndef right_shift_equiv (K L : cochain_complex C ℤ) (n i j : ℤ) (h : i = j + n) :\n cochain K L i ≃+ cochain K (L⟦n⟧) j :=\n{ to_fun := λ γ, γ.right_shift n j h,\n inv_fun := λ γ', γ'.right_unshift i h,\n left_inv := λ γ, γ.right_shift_unshift _ _ _,\n right_inv := λ γ', γ'.right_unshift_shift _ _,\n map_add' := λ γ₁ γ₂, cochain.right_shift_add γ₁ γ₂ _ _ _, }\n\nend cochain\n\nnamespace cocycle\n\nvariables {K L : cochain_complex C ℤ} {i : ℤ}\n (γ : cocycle K L i) (n : ℤ) (γ' : cocycle K (L⟦n⟧) i)\n\n@[simps]\ndef right_shift (j : ℤ) (hj : i = j + n) : cocycle K (L⟦n⟧) j :=\n⟨(γ : cochain K L i).right_shift n j hj, begin\n rw [cocycle.mem_iff j (j+1) rfl, cochain.δ_right_shift _ n (i+1) j (j+1) hj (by linarith)],\n simp only [subtype.val_eq_coe, δ_eq_zero, cochain.right_shift_zero, smul_zero],\nend⟩\n\nvariable {n}\n\n@[simps]\ndef right_unshift (j : ℤ) (hj : j = i + n) : cocycle K L j :=\n⟨(γ' : cochain K (L⟦n⟧) i).right_unshift j hj, begin\n rw [cocycle.mem_iff j (j+1) rfl, cochain.δ_right_unshift _ (i+1) j (j+1) hj (by linarith)],\n simp only [subtype.val_eq_coe, δ_eq_zero, cochain.right_unshift_zero, smul_zero],\nend⟩\n\n@[simps]\ndef right_shift_equiv (K L : cochain_complex C ℤ) (n i j : ℤ) (h : i = j + n) :\n cocycle K L i ≃+ cocycle K (L⟦n⟧) j :=\n{ to_fun := λ γ, right_shift γ n j h,\n inv_fun := λ γ', right_unshift γ' i h,\n left_inv := λ γ, by { ext1, exact γ.1.right_shift_unshift _ _ _, },\n right_inv := λ γ', by { ext1, exact γ'.1.right_unshift_shift _ _, },\n map_add' := λ γ₁ γ₂, by { ext1, exact cochain.right_shift_add γ₁.1 γ₂.1 _ _ _, }, }\n\nend cocycle\n\n@[simps]\ndef right_shift_iso (K L : cochain_complex C ℤ) (n : ℤ) :\n (hom_complex K L)⟦n⟧ ≅ hom_complex K (L⟦n⟧) :=\nhomological_complex.hom.iso_of_components\n (λ i, add_equiv.to_AddCommGroup_iso (cochain.right_shift_equiv K L n (i+n) i rfl))\n (λ i j hij, begin\n ext1 γ,\n simp only [comp_apply],\n dsimp [hom_complex, δ_hom],\n erw [γ.δ_right_shift n (j+n) i j rfl rfl, cochain.right_shift_smul],\n end)\n\nnamespace cochain\n\nvariables {K L : cochain_complex C ℤ} {i : ℤ}\n (γ γ₂ : cochain K L i) (n : ℤ) (γ' γ'₂: cochain (K⟦n⟧) L i)\n\ndef left_shift (j : ℤ) (hj : j = i + n) : cochain (K⟦n⟧) L j :=\ncochain.mk (λ p q hpq,\n ε (n*j + (n*(n-1)/2)) • (K.shift_functor_obj_X_iso n p (p+n) rfl).hom ≫ γ.v (p+n) q (by { dsimp, linarith, }))\n\nlemma left_shift_v (j : ℤ) (hj : j = i + n) (p q : ℤ) (hpq : q = p + j)\n (p' : ℤ) (hp' : p' = p + n) :\n (γ.left_shift n j hj).v p q hpq = ε (n*j + (n*(n-1)/2)) • (K.shift_functor_obj_X_iso n p p' hp').hom ≫\n γ.v p' q (by rw [hpq, hp', hj, add_assoc, add_comm i]) :=\nby { subst hp', refl, }\n\n@[simp]\nlemma left_shift_zero (j : ℤ) (hj : j = i + n) :\n (0 : cochain K L i).left_shift n j hj = 0 :=\nby { dsimp [left_shift], tidy, }\n\n@[simp]\nlemma left_shift_smul (j : ℤ) (hj : j = i + n) (a : ℤ) :\n (a • γ).left_shift n j hj = a • γ.left_shift n j hj :=\nbegin\n ext p q hpq,\n simp only [left_shift_v _ n j hj p q hpq _ rfl, zsmul_v, linear.comp_smul,\n ← mul_smul, mul_comm a],\nend\n\n@[simp]\nlemma left_shift_add (j : ℤ) (hj : j = i + n) :\n (γ + γ₂).left_shift n j hj = γ.left_shift n j hj + γ₂.left_shift n j hj :=\nbegin\n ext p q hpq,\n simp only [left_shift_v _ n j hj p q hpq _ rfl, add_v, preadditive.comp_add, smul_add],\nend\n\nvariable {n}\n\ndef left_unshift (j : ℤ) (hj : i = j + n) : cochain K L j :=\ncochain.mk (λ p q hpq,\n ε (n*i + (n*(n-1)/2)) • (K.shift_functor_obj_X_iso n (p-n) p (by linarith)).inv ≫\n γ'.v (p-n) q (by { change _ = _ - _ + _, linarith,}))\n\n\nlemma left_unshift_v (j : ℤ) (hj : i = j + n) (p q : ℤ) (hpq : q = p + j)\n (p' : ℤ) (hp' : p' = p - n):\n (γ'.left_unshift j hj).v p q hpq =\n ε (n*i + (n*(n-1)/2)) • (K.shift_functor_obj_X_iso n p' p (by rw [hp', sub_add_cancel])).inv ≫\n γ'.v p' q (by rw [hpq, hp', hj, sub_add_add_cancel]) :=\nby { subst hp', refl, }\n\n@[simp]\nlemma left_unshift_zero (j : ℤ) (hj : i = j + n) :\n (0 : cochain (K⟦n⟧) L i).left_unshift j hj = 0 :=\nby { dsimp [left_unshift], tidy, }\n\n@[simp]\nlemma left_unshift_smul (j : ℤ) (hj : i = j + n) (a : ℤ) :\n (a • γ').left_unshift j hj = a • γ'.left_unshift j hj :=\nbegin\n ext p q hpq,\n simp only [left_unshift_v _ j hj p q hpq _ rfl, zsmul_v, linear.smul_comp, linear.comp_smul,\n ← mul_smul, mul_comm a],\nend\n\n@[simp]\nlemma left_unshift_add (j : ℤ) (hj : i = j + n) :\n (γ' + γ'₂).left_unshift j hj = γ'.left_unshift j hj + γ'₂.left_unshift j hj :=\nbegin\n ext p q hpq,\n simp only [left_unshift_v _ j hj p q hpq _ rfl, add_v, preadditive.comp_add, smul_add],\nend\n\n@[simp]\nlemma left_unshift_shift (j : ℤ) (hj : i = j + n) :\n (γ'.left_unshift j hj).left_shift n i hj = γ' :=\nbegin\n ext p q hpq,\n simp only [cochain.left_shift_v _ n i hj p q hpq _ rfl,\n cochain.left_unshift_v _ j hj (p+n) q (by linarith) p (by linarith),\n ε_add, linear.comp_smul, iso.hom_inv_id_assoc, ← mul_smul],\n nth_rewrite 0 mul_comm (ε (n*i)),\n rw ← mul_assoc,\n nth_rewrite 1 mul_assoc,\n rw [← ε_add, ε_even _ (even_add_self _), mul_one],\n rw [← ε_add, ε_even _ (even_add_self _), one_smul],\nend\n\nvariable (n)\n\n@[simp]\nlemma left_shift_unshift (j : ℤ) (hj : j = i + n) :\n (γ.left_shift n j hj).left_unshift i hj = γ :=\nbegin\n ext p q hpq,\n simp only [cochain.left_unshift_v _ i hj p q hpq _ rfl,\n cochain.left_shift_v _ n j hj (p-n) q (by linarith) p (by linarith)],\n simp only [shift_functor_obj_X_iso, ε_add, linear.comp_smul,\n homological_complex.X_iso_of_eq_inv_hom_assoc,\n homological_complex.X_iso_of_eq_refl, iso.refl_hom, category.id_comp, ← mul_smul],\n nth_rewrite 0 mul_comm (ε (n*j)),\n rw ← mul_assoc,\n nth_rewrite 1 mul_assoc,\n rw [← ε_add, ε_even _ (even_add_self _), mul_one],\n rw [← ε_add, ε_even _ (even_add_self _), one_smul],\nend\n\n\nvariable (n)\n\nlemma δ_left_shift (i' j j' : ℤ) (hj : j = i + n) (hj' : j' = i' + n) :\n δ j j' (γ.left_shift n j hj) = ε (n) • (δ i i' γ).left_shift n j' hj' :=\nbegin\n by_cases h₁ : i+1 = i', swap,\n { have h₂ : j+1 ≠ j' := λ h₃, by { exfalso, apply h₁, linarith, },\n simp only [δ_shape _ _ h₁, δ_shape _ _ h₂, left_shift_zero, smul_zero], },\n { have h₂ : j' = j+1 := by linarith,\n substs h₁ h₂,\n ext p q hpq,\n rw δ_v j _ rfl _ p q hpq (p+j) (p+1) (by linarith) rfl,\n rw γ.left_shift_v n j hj p _ rfl _ rfl,\n rw γ.left_shift_v n j hj (p+1) q (by linarith) _ rfl,\n rw zsmul_v,\n rw left_shift_v _ n (j+1) hj' p q hpq _ rfl,\n rw δ_v i _ rfl _ (p+n) q (by linarith) (p+j) (p+1+n) (by linarith) (by linarith),\n simp only [shift_functor_obj_X_iso, homological_complex.X_iso_of_eq_refl,\n linear.smul_comp, assoc, ε_succ, linear.comp_smul, neg_smul, preadditive.comp_add,\n preadditive.comp_neg, smul_add, zsmul_neg', add_right_inj, neg_inj, ← mul_smul],\n dsimp [iso.refl],\n simp only [preadditive.zsmul_comp, ← mul_smul],\n erw [category.id_comp, category.id_comp, category.id_comp],\n congr' 2,\n { simp only [mul_add, ε_add, mul_one, mul_comm _ (ε n)],\n simp only [← mul_assoc, ← ε_add n n, ε_even _ (even_add_self n)],\n ring, },\n { rw [hj],\n simp only [ε_add, neg_mul, mul_neg, neg_inj, mul_add],\n ring_nf, }, },\nend\n\nvariable {n}\n\nlemma δ_left_unshift (i' j j' : ℤ) (hj : i = j + n) (hj' : i' = j' + n) :\n δ j j' (γ'.left_unshift j hj) = ε n • (δ i i' γ').left_unshift j' hj' :=\nbegin\n conv_rhs { rw ← γ'.left_unshift_shift j hj, },\n rw [(γ'.left_unshift j hj).δ_left_shift n j' i i' hj hj',\n left_unshift_smul, cochain.left_shift_unshift, smul_smul,\n ← ε_add, ε_even _ (even_add_self n), one_smul],\nend\n\n@[simps]\ndef left_shift_equiv (K L : cochain_complex C ℤ) (n i j : ℤ) (h : j = i + n) :\n cochain K L i ≃+ cochain (K⟦n⟧) L j :=\n{ to_fun := λ γ, γ.left_shift n j h,\n inv_fun := λ γ', γ'.left_unshift i h,\n left_inv := λ γ, γ.left_shift_unshift _ _ _,\n right_inv := λ γ', γ'.left_unshift_shift _ _,\n map_add' := λ γ₁ γ₂, cochain.left_shift_add γ₁ γ₂ _ _ _, }\n\nend cochain\n\nnamespace cocycle\n\nvariables {K L : cochain_complex C ℤ} {i : ℤ}\n (γ : cocycle K L i) (n : ℤ) (γ' : cocycle (K⟦n⟧) L i)\n\n@[simps]\ndef left_shift (j : ℤ) (hj : j = i + n) : cocycle (K⟦n⟧) L j :=\n⟨(γ : cochain K L i).left_shift n j hj, begin\n rw [cocycle.mem_iff j (j+1) rfl, cochain.δ_left_shift _ n (i+1) j (j+1) hj (by linarith)],\n simp only [subtype.val_eq_coe, δ_eq_zero, cochain.left_shift_zero, smul_zero],\nend⟩\n\nvariable {n}\n\n@[simps]\ndef left_unshift (j : ℤ) (hj : i = j + n) : cocycle K L j :=\n⟨(γ' : cochain (K⟦n⟧) L i).left_unshift j hj, begin\n rw [cocycle.mem_iff j (j+1) rfl, cochain.δ_left_unshift _ (i+1) j (j+1) hj (by linarith)],\n simp only [subtype.val_eq_coe, δ_eq_zero, cochain.left_unshift_zero, smul_zero],\nend⟩\n\nvariables (K L)\n\n@[simps]\ndef left_shift_equiv (n i j : ℤ) (h : j = i + n) :\n cocycle K L i ≃+ cocycle (K⟦n⟧) L j :=\n{ to_fun := λ γ, left_shift γ n j h,\n inv_fun := λ γ', left_unshift γ' i h,\n left_inv := λ γ, by { ext1, exact γ.1.left_shift_unshift _ _ _, },\n right_inv := λ γ', by { ext1, exact γ'.1.left_unshift_shift _ _, },\n map_add' := λ γ₁ γ₂, by { ext1, exact cochain.left_shift_add γ₁.1 γ₂.1 _ _ _, }, }\n\nend cocycle\n\n@[simps]\ndef left_shift_iso (K L : cochain_complex C ℤ) (n : ℤ) :\n (hom_complex K L) ≅ (hom_complex (K⟦n⟧) L)⟦n⟧ :=\nhomological_complex.hom.iso_of_components\n (λ i, add_equiv.to_AddCommGroup_iso (cochain.left_shift_equiv K L n i (i+n) rfl))\n (λ i j hij, begin\n ext1 γ,\n simp only [comp_apply],\n dsimp [hom_complex, δ_hom],\n rw [γ.δ_left_shift n j (i+n) (j+n) rfl rfl, ← mul_smul, ← ε_add,\n ε_even _ (even_add_self n), one_smul],\n end)\n\ndef shift_iso (K L : cochain_complex C ℤ) (n : ℤ) :\n hom_complex K L ≅ hom_complex (K⟦n⟧) (L⟦n⟧) :=\nleft_shift_iso K L n ≪≫ right_shift_iso (K⟦n⟧) L n\n\nlemma δ_shift_iso_hom_f {K L : cochain_complex C ℤ} (n i j : ℤ) (γ : cochain K L i) :\n δ i j ((shift_iso K L n).hom.f i γ) = (shift_iso K L n).hom.f j (δ i j γ) :=\ncongr_hom (((shift_iso K L n).hom.comm i j)) γ\n\nlemma even_mul_succ (n : ℤ) : even (n * (n+1)) :=\nbegin\n by_cases hn : even n,\n { obtain ⟨k, rfl⟩ := hn,\n exact ⟨k * (2*k+1), by ring⟩, },\n { rw ← int.odd_iff_not_even at hn,\n obtain ⟨k, rfl⟩ := hn,\n exact ⟨(2*k+1)*(k+1), by ring⟩, },\nend\n\nlemma even_mul_pred (n : ℤ) : even (n * (n-1)) :=\nbegin\n rw mul_comm,\n convert (even_mul_succ (n-1)),\n linarith,\nend\n\nlemma mul_pred_div_two_of_even (k : ℤ) : ((k+k)* ((k+k)-1))/2 = k*(2*k-1) :=\nby simp only [show k+k = 2*k, by ring, mul_assoc, int.mul_div_cancel_left, ne.def, bit0_eq_zero,\n one_ne_zero, not_false_iff]\n\nlemma mul_succ_div_two_of_even (k : ℤ) : ((k+k)* (k+k+1))/2 = k*(2*k+1) :=\nby simp only [show k+k = 2*k, by ring, mul_assoc, int.mul_div_cancel_left,\n int.mul_div_cancel_left, ne.def, bit0_eq_zero, one_ne_zero, not_false_iff]\n\nlemma mul_pred_div_two_of_odd (k : ℤ) : ((2*k+1)* ((2*k+1)-1))/2 = k*(2*k+1) :=\nby simp only [add_tsub_cancel_right, mul_comm _ (2*k), mul_assoc,\n int.mul_div_cancel_left, ne.def, bit0_eq_zero, one_ne_zero, not_false_iff]\n\nlemma mul_succ_div_two_of_odd (k : ℤ) : ((2*k+1)* ((2*k+1)+1))/2 = (k+1)*(2*k+1) :=\nby simp only [mul_comm (2*k+1), show 2*k+1+1 = 2*(k+1), by ring, mul_assoc,\n int.mul_div_cancel_left, ne.def, bit0_eq_zero, one_ne_zero, not_false_iff]\n\nlemma mul_succ_div_two (n : ℤ) : (n * (n+1))/2 = (n*(n-1))/2 + n :=\nbegin\n by_cases hn : even n,\n { obtain ⟨k, rfl⟩ := hn,\n rw [mul_pred_div_two_of_even, mul_succ_div_two_of_even],\n ring, },\n { rw ← int.odd_iff_not_even at hn,\n obtain ⟨k, rfl⟩ := hn,\n rw [mul_succ_div_two_of_odd, mul_pred_div_two_of_odd],\n ring, },\nend\n\nlemma shift_iso_hom_f_of_hom {K L : cochain_complex C ℤ} (f : K ⟶ L) (n : ℤ) :\n ((shift_iso K L n).hom.f 0) (cochain.of_hom f) = ε ((n * (n+1))/2) • cochain.of_hom (f⟦n⟧') :=\nbegin\n ext p,\n dsimp only [shift_iso],\n simp only [iso.trans_hom, homological_complex.comp_f, comp_apply,\n left_shift_iso_hom_f_apply, right_shift_iso_hom_f_apply],\n rw cochain.right_shift_v _ n 0 rfl p p (by linarith) (p+n) (by linarith),\n rw cochain.left_shift_v _ n (0+n) rfl p (p+n) (by linarith) _ rfl,\n simp only [zero_add, shift_functor_obj_X_iso,\n homological_complex.X_iso_of_eq_refl, cochain.of_hom_v, linear.smul_comp, assoc],\n dsimp [iso.refl],\n have eq : ε (n * n + n * (n - 1) / 2) = ε (( n * (n+1)/2)),\n { simp only [mul_succ_div_two, ε_add, mul_comm _ (ε n)],\n congr' 1,\n by_cases hn : even n,\n { rw [ε_even _ hn, ε_even],\n obtain ⟨k, rfl⟩ := hn,\n exact ⟨2*k*k, by ring⟩, },\n { rw ← int.odd_iff_not_even at hn,\n rw [ε_odd _ hn, ε_odd],\n obtain ⟨k, rfl⟩ := hn,\n exact ⟨2*k*k+2*k, by ring⟩, }, },\n erw [id_comp, comp_id, eq],\n simpa only [cochain.of_hom_v],\nend\n\nend hom_complex\n\nend cochain_complex\n\nopen cochain_complex.hom_complex\n\ndef homotopy.shift {K L : cochain_complex C ℤ} {f₁ f₂ : K ⟶ L} (h : homotopy f₁ f₂) (n : ℤ) :\n homotopy (f₁⟦n⟧') (f₂⟦n⟧') :=\n(cochain_complex.hom_complex.equiv_homotopy _ _).symm begin\n obtain ⟨γ, hγ⟩ := (cochain_complex.hom_complex.equiv_homotopy _ _) h,\n replace hγ := congr_arg ((shift_iso K L n).hom.f 0) hγ.symm,\n simp only [map_add, shift_iso_hom_f_of_hom, ← δ_shift_iso_hom_f] at hγ,\n refine ⟨ε ((n*(n+1)/2)) • (shift_iso K L n).hom.f (-1) γ, _⟩,\n simp only [δ_zsmul, eq_sub_of_add_eq hγ, zsmul_sub, ← mul_smul, ← ε_add,\n ε_even _ (even_add_self _), one_smul, sub_add_cancel],\nend\n\nnamespace homotopy_category\n\nnoncomputable instance : has_shift (homotopy_category C (complex_shape.up ℤ)) ℤ :=\nquotient.shift (λ n K L f₁ f₂, by { rintro ⟨h⟩, exact ⟨h.shift n⟩, })\n\nlemma quotient_map_shift {K L : cochain_complex C ℤ} (φ : K ⟶ L) (n : ℤ) :\n (homotopy_category.quotient _ _).map (φ⟦n⟧') = ((homotopy_category.quotient _ _).map φ)⟦n⟧' := rfl\n\nend homotopy_category\n", "meta": {"author": "joelriou", "repo": "homotopical_algebra", "sha": "697f49d6744b09c5ef463cfd3e35932bdf2c78a3", "save_path": "github-repos/lean/joelriou-homotopical_algebra", "path": "github-repos/lean/joelriou-homotopical_algebra/homotopical_algebra-697f49d6744b09c5ef463cfd3e35932bdf2c78a3/src/for_mathlib/algebra/homology/hom_complex_shift.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4804786780479071, "lm_q2_score": 0.036220057295448235, "lm_q1q2_score": 0.01740296524813642}} {"text": "/-\nCopyright (c) 2016 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Leonardo de Moura\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.meta.tactic\nimport Mathlib.Lean3Lib.init.meta.format\nimport Mathlib.Lean3Lib.init.function\n \n\nuniverses l \n\nnamespace Mathlib\n\n/-- This is a kind attached to an argument of a congruence lemma that tells the simplifier how to fill it in.\n- `fixed`: It is a parameter for the congruence lemma, the parameter occurs in the left and right hand sides.\n For example the α in the congruence generated from `f: Π {α : Type} α → α`.\n- `fixed_no_param`: It is not a parameter for the congruence lemma, the lemma was specialized for this parameter.\n This only happens if the parameter is a subsingleton/proposition, and other parameters depend on it.\n- `eq`: The lemma contains three parameters for this kind of argument `a_i`, `b_i` and `(eq_i : a_i = b_i)`.\n `a_i` and `b_i` represent the left and right hand sides, and `eq_i` is a proof for their equality.\n For example the second argument in `f: Π {α : Type}, α → α`.\n- `cast`: corresponds to arguments that are subsingletons/propositions.\n For example the `p` in the congruence generated from `f : Π (x y : ℕ) (p: x < y), ℕ`.\n- `heq` The lemma contains three parameters for this kind of argument `a_i`, `b_i` and `(eq_i : a_i == b_i)`.\n `a_i` and `b_i` represent the left and right hand sides, and eq_i is a proof for their heterogeneous equality.\n-/\ninductive congr_arg_kind \nwhere\n| fixed : congr_arg_kind\n| fixed_no_param : congr_arg_kind\n| eq : congr_arg_kind\n| cast : congr_arg_kind\n| heq : congr_arg_kind\n\nnamespace congr_arg_kind\n\n\ndef to_string : congr_arg_kind → string :=\n sorry\n\nprotected instance has_repr : has_repr congr_arg_kind :=\n has_repr.mk to_string\n\n", "meta": {"author": "AurelienSaue", "repo": "Mathlib4_auto", "sha": "590df64109b08190abe22358fabc3eae000943f2", "save_path": "github-repos/lean/AurelienSaue-Mathlib4_auto", "path": "github-repos/lean/AurelienSaue-Mathlib4_auto/Mathlib4_auto-590df64109b08190abe22358fabc3eae000943f2/Mathlib/Lean3Lib/init/meta/congr_lemma.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.43782348444346736, "lm_q2_score": 0.03963884193722745, "lm_q1q2_score": 0.017354815896260763}} {"text": "import data.finsupp.basic\nimport finsupp_lemmas\nimport algebra.big_operators.fin\nimport data.nat.succ_pred\nimport tactic.linarith\nimport dynamics.periodic_pts\n\nopen_locale classical\nnoncomputable theory\n\nuniverses u\n\nstructure Stream (ι : Type) (α : Type u) : Type (max 1 u) :=\n(σ : Type)\n(valid : σ → Prop)\n(ready : σ → Prop)\n(next : Π (x : σ), valid x → σ)\n(index : Π (x : σ), valid x → ι)\n(value : Π (x : σ), ready x → α)\n\n@[ext]\nlemma Stream.ext {ι α} {s₁ s₂ : Stream ι α} (h₀ : s₁.σ = s₂.σ)\n (h₁ : ∀ x y, x == y → (s₁.valid x ↔ s₂.valid y)) (h₂ : ∀ x y, x == y → (s₁.ready x ↔ s₂.ready y)) (h₃ : ∀ x y H₁ H₂, x == y → s₁.next x H₁ == s₂.next y H₂)\n (h₄ : ∀ x y H₁ H₂, x == y → s₁.index x H₁ == s₂.index y H₂) (h₅ : ∀ x y H₁ H₂, x == y → s₁.value x H₁ == s₂.value y H₂) :\n s₁ = s₂ :=\nbegin\n cases s₁ with σ₁ v₁ r₁ n₁ i₁ l₁, cases s₂ with σ₂ v₂ r₂ n₂ i₂ l₂, dsimp only at *,\n subst h₀, simp only [heq_iff_eq] at *,\n obtain rfl : v₁ = v₂ := funext (λ x, propext $ h₁ x x rfl), obtain rfl : r₁ = r₂ := funext (λ x, propext $ h₂ x x rfl),\n refine ⟨rfl, rfl, rfl, _, _, _⟩; simp only [heq_iff_eq] at *; ext, { apply h₃ x x _ _ rfl; assumption, }, { apply h₄ x x _ _ rfl; assumption, },\n { apply h₅ x x _ _ rfl; assumption, },\nend\n\nsection stream_defs\nvariables {ι : Type} {α : Type*}\n\ndef Stream.eval₀ [has_zero α] (s : Stream ι α) (σ₀ : s.σ) (h₁ : s.valid σ₀) : ι →₀ α :=\nif h₂ : s.ready σ₀ then finsupp.single (s.index _ h₁) (s.value _ h₂) else 0\n\n@[simp]\nnoncomputable def Stream.eval_steps [add_zero_class α] (s : Stream ι α) :\n ℕ → s.σ → ι →₀ α\n| 0 _ := 0\n| (n + 1) σ₀ := if h₁ : s.valid σ₀ then (Stream.eval_steps n (s.next σ₀ h₁)) + (s.eval₀ _ h₁) else 0\n\nlemma Stream.eval_invalid [add_zero_class α] {s : Stream ι α} {σ₀ : s.σ} (h : ¬s.valid σ₀) (n : ℕ) :\n s.eval_steps n σ₀ = 0 :=\nby cases n; simp [h]\n\ninductive Stream.bound_valid : ℕ → ∀ (s : Stream ι α), s.σ → Prop\n| start (n : ℕ) {s : Stream ι α} {σ₀ : s.σ} : ¬s.valid σ₀ → Stream.bound_valid n s σ₀\n| step {n : ℕ} {s : Stream ι α} {σ₀ : s.σ} : ∀ (h : s.valid σ₀), Stream.bound_valid n s (s.next σ₀ h) → Stream.bound_valid (n + 1) s σ₀\n\nend stream_defs\n\n@[ext]\nstructure StreamExec (ι : Type) (α : Type u) :=\n(stream : Stream ι α)\n(state : stream.σ)\n(bound : ℕ)\n(bound_valid : stream.bound_valid bound state)\n\n\nuniverses v w\nvariables {ι ι' ι'' : Type} {α : Type u} {β : Type v} {γ : Type w}\n\n/-- Solve as many goals as possible by definitional simplification, use heq/eq, and `refl` -/\nmeta def tactic.interactive.solve_refl : tactic unit :=\nlet tactics : list (tactic unit) :=\n[`[dsimp],\n `[simp only [heq_iff_eq]],\n `[intros],\n `[subst_vars],\n `[refl]] in \nsequence (tactics.map (λ t, tactic.try t)) >> tactic.skip\n\n@[simps]\ndef Stream.bimap (s : Stream ι α) (f : ι → ι') (g : α → β) : Stream ι' β :=\n{ s with value := λ x hx, g (s.value x hx), index := λ x hx, f (s.index x hx) }\n\n@[simp] lemma Stream.id_bimap (s : Stream ι α) : s.bimap id id = s :=\nby ext; solve_refl\n\n@[simp] lemma Stream.bimap_bimap (s : Stream ι α)\n (f : ι → ι') (f' : ι' → ι'') (g : α → β) (h : β → γ) :\n (s.bimap f g).bimap f' h = s.bimap (f' ∘ f) (h ∘ g) :=\nby ext; solve_refl\n\nnotation f ` <$₁> `:1 s := s.bimap f id\nnotation g ` <$₂> `:1 s := s.bimap id g\n\n@[reducible, inline]\ndef StreamExec.valid (s : StreamExec ι α) : Prop := s.stream.valid s.state\n\n@[reducible, inline]\ndef StreamExec.ready (s : StreamExec ι α) : Prop := s.stream.ready s.state\n\nopen Stream.bound_valid (start step)\n\n@[simp] lemma Stream.bound_valid_zero {s : Stream ι α} {σ₀ : s.σ} :\n s.bound_valid 0 σ₀ ↔ ¬s.valid σ₀ :=\n⟨λ h, by { cases h, assumption, }, λ h, start _ h⟩\n\nlemma Stream.bound_valid.mono {s : Stream ι α} {σ₀ : s.σ} {n m : ℕ} (h : s.bound_valid n σ₀) (n_le : n ≤ m) :\n s.bound_valid m σ₀ :=\nbegin\n induction h with _ _ _ _ _ _ _ hv _ ih generalizing m,\n { apply Stream.bound_valid.start, assumption, },\n cases m, { cases nat.not_succ_le_zero _ n_le, },\n exact Stream.bound_valid.step hv (ih (nat.le_of_succ_le_succ n_le)),\nend\n\nlemma Stream.eval_ge_bound [add_zero_class α] {s : Stream ι α} {σ₀ : s.σ} {n b : ℕ} (hb : s.bound_valid b σ₀) (hn : b ≤ n) :\n s.eval_steps n σ₀ = s.eval_steps b σ₀ :=\nbegin\n induction hb with _ _ _ _ n' σ₀' s' hv _ ih generalizing n,\n { simp [Stream.eval_invalid, *], },\n cases n, { cases nat.not_succ_le_zero _ hn, },\n simp [hv, ih (nat.le_of_succ_le_succ hn)],\nend\n\nlemma Stream.eval_min_bound [add_zero_class α] {s : Stream ι α} {σ₀ : s.σ} {n b : ℕ} (hb : s.bound_valid b σ₀) :\n s.eval_steps (min b n) σ₀ = s.eval_steps n σ₀ :=\nby { rw min_def, split_ifs, { rw Stream.eval_ge_bound hb h, }, refl, }\n\nlemma Stream.valid.bound_pos {s : Stream ι α} {σ₀ : s.σ} (h : s.valid σ₀) :\n ¬s.bound_valid 0 σ₀ := by simpa\n\nlemma Stream.eval₀_support [has_zero α] (s : Stream ι α) (x : s.σ) (h : s.valid x) :\n (s.eval₀ x h).support ⊆ {s.index x h} :=\nby { rw Stream.eval₀, split_ifs, { exact finsupp.support_single_subset, }, simp, }\n\n@[simp] lemma Stream.bound_valid_succ {s : Stream ι α} {n : ℕ} {σ₀ : s.σ} :\n s.bound_valid (n + 1) σ₀ ↔ (∀ (h : s.valid σ₀), s.bound_valid n (s.next σ₀ h)) :=\n⟨λ h, by { cases h, { intro, contradiction, }, intro, assumption, }, λ h, if H : s.valid σ₀ then step H (h H) else start _ H⟩\n\ndef StreamExec.eval [add_zero_class α] (s : StreamExec ι α) : ι →₀ α :=\ns.stream.eval_steps s.bound s.state\n\nsection defs\n\n@[simp] lemma imap_eval₀_spec [add_comm_monoid α] (f : ι → ι') (s : Stream ι α) (σ₀ : s.σ) (h : s.valid σ₀) :\n (f <$₁> s).eval₀ _ h = (s.eval₀ _ h).map_domain f :=\nby { simp only [Stream.eval₀], split_ifs; simp, }\n\n@[simp] lemma imap_eval_steps_spec [add_comm_monoid α] (f : ι → ι') (s : Stream ι α) (σ₀ : s.σ) (n : ℕ) :\n (f <$₁> s).eval_steps n σ₀ = (s.eval_steps n σ₀).map_domain f :=\nbegin\n induction n with n ih generalizing s σ₀; simp,\n split_ifs; simp [ih, finsupp.map_domain_add], refl,\nend\n\n@[simp] lemma bimap_bound_valid_iff (f : ι → ι') (g : α → β) (s : Stream ι α) (n : ℕ) (x : s.σ) :\n (s.bimap f g).bound_valid n x ↔ s.bound_valid n x :=\nby { induction n with n ih generalizing x; simp [*]; refl, }\n\ninstance bimap_σ.has_zero {f : ι → ι'} {g : α → β} {s : Stream ι α} [z : has_zero s.σ] :\nhas_zero (s.bimap f g).σ := z\n\n@[simp] lemma Stream.bifunctor_bimap_valid (s : Stream ι α) (f : ι → ι') (g : α → β) :\n (s.bimap f g).valid = s.valid := rfl\n\n@[simp] lemma Stream.bifunctor_bimap_valid_apply (s : Stream ι α) (f : ι → ι') (g : α → β) (x : s.σ) :\n (s.bimap f g).valid x ↔ s.valid x := iff.rfl\n\n@[simp] lemma Stream.bifunctor_bimap_ready (s : Stream ι α) (f : ι → ι') (g : α → β) :\n (s.bimap f g).ready = s.ready := rfl\n\n@[simp] lemma Stream.bifunctor_bimap_ready_apply (s : Stream ι α) (f : ι → ι') (g : α → β) (x : s.σ) :\n (s.bimap f g).ready x ↔ s.ready x := iff.rfl\n\n@[simps]\ndef StreamExec.bimap (s : StreamExec ι α) (f : ι → ι') (g : α → β) : StreamExec ι' β :=\n{ s with stream := s.stream.bimap f g, bound_valid := by simpa using s.bound_valid }\n\n@[simp] lemma StreamExec.id_bimap (s : StreamExec ι α) : s.bimap id id = s :=\nby ext; solve_refl\n\n@[simp] lemma StreamExec.bimap_bimap (s : StreamExec ι α)\n (f : ι → ι') (f' : ι' → ι'') (g : α → β) (h : β → γ) :\n (s.bimap f g).bimap f' h = s.bimap (f' ∘ f) (h ∘ g) :=\nby ext; solve_refl\n\n@[simp] lemma imap_stream (s : StreamExec ι α) (f : ι → ι') :\n (f <$₁> s).stream = (f <$₁> s.stream) := rfl\n\n@[simp] lemma imap_stream_eval [add_zero_class α] (s : StreamExec ι α) (f : ι → ι') (n : ℕ) :\n (f <$₁> s).stream.eval_steps n s.state = (f <$₁> s.stream).eval_steps n s.state := rfl\n\n@[simp] lemma StreamExec.bifunctor_bimap_valid (s : StreamExec ι α) (f : ι → ι') (g : α → β) :\n (s.bimap f g).valid ↔ s.valid := iff.rfl\n\n@[simp] lemma StreamExec.bifunctor_bimap_ready (s : StreamExec ι α) (f : ι → ι') (g : α → β) :\n (s.bimap f g).ready ↔ s.ready := iff.rfl\n\n@[simp] lemma StreamExec.bimap_eval [add_comm_monoid α] (s : StreamExec ι α) (f : ι → ι') :\n (f <$₁> s).eval = s.eval.map_domain f :=\nby simp [StreamExec.eval]\n\ndef contract_stream (s : StreamExec ι α) : StreamExec unit α :=\n(λ _, ()) <$₁> s\n\n@[simp] lemma contract_stream_spec_apply [add_comm_monoid α] (s : StreamExec ι α) :\n (contract_stream s).eval () = (finsupp.sum_range s.eval) :=\nby simp [finsupp.sum_range, contract_stream]\n\n@[simp] lemma contract_stream_spec [add_comm_monoid α] (s : StreamExec ι α) :\n (contract_stream s).eval = finsupp.single () (finsupp.sum_range s.eval) :=\nby { ext, simp, }\n\ndef Stream.index' (s : Stream ι α) (x : s.σ) : with_top ι :=\nif h : s.valid x then s.index x h else ⊤ \n\ndef Stream.value' [has_zero α] (s : Stream ι α) (x : s.σ) : α :=\nif h : s.ready x then s.value _ h else 0\n\ndef Stream.next' (s : Stream ι α) (x : s.σ) : s.σ :=\nif h : s.valid x then s.next x h else x\n\n@[simp] lemma Stream.index'_lt_top_iff [preorder ι] {s : Stream ι α} {x : s.σ} :\n s.index' x < ⊤ ↔ s.valid x :=\nby { rw Stream.index', split_ifs; simp [h], exact with_top.coe_lt_top _, }\n\nlemma Stream.eval₀_eq_single [has_zero α] (s : Stream ι α) (x : s.σ) (h : s.valid x) :\n s.eval₀ x h = finsupp.single (s.index _ h) (s.value' x) :=\nby { rw [Stream.eval₀, Stream.value'], split_ifs with hr; simp, }\n\nlemma Stream.index'_val {s : Stream ι α} {x : s.σ} (h : s.valid x) : s.index' x = s.index x h := dif_pos h\n\nlemma Stream.index'_invalid {s : Stream ι α} {x : s.σ} (h : ¬s.valid x) : s.index' x = ⊤ := dif_neg h\n\nlemma Stream.value'_val [has_zero α] {s : Stream ι α} {x : s.σ} (h : s.ready x) : s.value' x = s.value x h := dif_pos h\n\n@[simp] lemma Stream.next'_val {s : Stream ι α} {x : s.σ} (hx) : s.next' x = s.next x hx := dif_pos hx\n\n@[simp] lemma Stream.next'_val_invalid {s : Stream ι α} {x : s.σ} (hx : ¬s.valid x) : s.next' x = x := dif_neg hx\n\n@[simp] lemma Stream.next'_val_invalid' {s : Stream ι α} {x : s.σ} (hx : ¬s.valid x) (n : ℕ) :\n s.next'^[n] x = x := function.iterate_fixed (Stream.next'_val_invalid hx) n\n\n\nlemma bound_valid_iff_next'_iterate {s : Stream ι α} {x : s.σ} {n : ℕ} :\n s.bound_valid n x ↔ ¬s.valid (s.next'^[n] x) :=\nby { induction n with n ih generalizing x, { simp, }, by_cases H : s.valid x; simp [ih, H, Stream.next'_val, Stream.next'_val_invalid, Stream.next'_val_invalid'], }\n\nlemma Stream.next'_ge_bound {s : Stream ι α} {σ₀ : s.σ} {n b : ℕ} (hb : s.bound_valid b σ₀) (hn : b ≤ n) :\n (s.next'^[n] σ₀) = (s.next'^[b] σ₀) :=\nbegin\n obtain ⟨k, rfl⟩ := nat.exists_eq_add_of_le hn,\n rw add_comm b k,\n rw bound_valid_iff_next'_iterate at hb,\n simp [function.iterate_add_apply, Stream.next'_val_invalid' hb],\nend\n\nlemma Stream.next'_min_bound {s : Stream ι α} {σ₀ : s.σ} {n b : ℕ} (hb : s.bound_valid b σ₀) :\n (s.next'^[min b n] σ₀) = (s.next'^[n] σ₀) :=\nby { rw min_def, split_ifs, { rw Stream.next'_ge_bound hb h, }, refl, }\n\nlemma Stream.bound_valid.next'_iff {s : Stream ι α} {x : s.σ} {B : ℕ} (hB : s.bound_valid B x) :\n ¬s.valid x ↔ s.next'.is_fixed_pt x :=\n⟨Stream.next'_val_invalid, λ h₁, by simpa [bound_valid_iff_next'_iterate, function.iterate_fixed h₁] using hB⟩\n\nlemma Stream.bound_valid.iterate_is_fixed_point {s : Stream ι α} {x : s.σ} {B : ℕ} (hB : s.bound_valid B x) :\n s.next'.is_fixed_pt (s.next'^[B] x) :=\nby simpa [function.iterate_succ'] using Stream.next'_ge_bound hB B.le_succ\n\nlemma Stream.bound_valid.fixed_pt_iff_periodic_pt {s : Stream ι α} {x : s.σ} {B : ℕ} (hB : s.bound_valid B x) :\n s.next'.is_fixed_pt x ↔ x ∈ s.next'.periodic_pts :=\n⟨λ h, function.mk_mem_periodic_pts zero_lt_one h, λ h, begin\n have hB' := function.is_fixed_point_iff_minimal_period_eq_one.mpr hB.iterate_is_fixed_point,\n simpa [hB', function.is_fixed_point_iff_minimal_period_eq_one] using (function.minimal_period_apply_iterate h B).symm,\nend⟩\n\nlemma Stream.next'_valid {s : Stream ι α} {x : s.σ}\n (h : s.valid (s.next' x)) : s.valid x :=\nby { contrapose h, rwa [Stream.next'_val_invalid h] }\n\nlemma Stream.next'_valid' {s : Stream ι α} {x : s.σ} (n : ℕ)\n (h : s.valid (s.next'^[n] x)) : s.valid x :=\nbegin\n induction n with _ ih generalizing x,\n { simpa using h },\n { rw [function.iterate_succ_apply] at h,\n exact Stream.next'_valid (ih h) }\nend\n\ntheorem Stream.bound_valid.no_repeat' {s : Stream ι α} {x : s.σ} {B : ℕ}\n (bv : s.bound_valid B x) (h : s.valid x) (n : ℕ) : s.next'^[n.succ] x ≠ x :=\nλ h', bv.fixed_pt_iff_periodic_pt.not.mp (bv.next'_iff.not_right.mp h) ⟨n + 1, nat.zero_lt_succ _, h'⟩\n\ntheorem Stream.bound_valid.no_repeat {s : Stream ι α} {x : s.σ} {B : ℕ}\n (bv : s.bound_valid B x) (h : s.valid x) : s.next' x ≠ x := bv.no_repeat' h 0\n\nlemma Stream.bimap_value' [has_zero α] [has_zero β] (s : Stream ι α) (f : ι → ι') (g : α → β) (hg : g 0 = 0) :\n (s.bimap f g).value' = g ∘ s.value' :=\nby { ext x, simp [Stream.value', apply_dite g, hg], refl, }\n\nlemma Stream.bimap_value'_apply [has_zero α] [has_zero β] (s : Stream ι α) (f : ι → ι') (g : α → β) (hg : g 0 = 0) (x) :\n (s.bimap f g).value' x = g (s.value' x) :=\nby rwa Stream.bimap_value'\n\nlemma Stream.bimap_index'_eq_apply (s : Stream ι α) (f : ι → ι') (g : α → β) (x : s.σ) :\n (s.bimap f g).index' x = with_top.map f (s.index' x) :=\nby unfold Stream.index'; split_ifs; split; simp\n\nlemma Stream.bimap_index'_eq (s : Stream ι α) (f : ι → ι') (g : α → β) :\n (s.bimap f g).index' = with_top.map f ∘ s.index' :=\nby ext; rw function.comp_app; simp [Stream.bimap_index'_eq_apply]\n\nend defs\n\nopen_locale big_operators\n\nlemma Stream.eval_steps_add [add_comm_monoid α] (s : Stream ι α) (m n : ℕ) (q : s.σ) :\n s.eval_steps (m + n) q = s.eval_steps m q + s.eval_steps n (s.next'^[m] q) :=\nbegin\n induction m with m ih generalizing q, { simp, },\n by_cases H : s.valid q,\n { simp [nat.succ_add, ih, H, Stream.next'_val], abel, },\n { simp only [Stream.eval_invalid H, Stream.next'_val_invalid' H, add_zero], },\nend\n\nlemma Stream.spec_of_iterate [add_comm_monoid α] (s : Stream ι α)\n (B : ℕ) (σ₀ : s.σ) (h : ∀ i < B, s.valid (s.next'^[i] σ₀)) :\n s.eval_steps B σ₀ = ∑ i : fin B, finsupp.single (s.index (s.next'^[i] σ₀) (h i i.prop)) (s.value' (s.next'^[i] σ₀)) :=\nbegin\n induction B with B ih generalizing σ₀,\n { simp, },\n have hv : s.valid σ₀, { exact h 0 (nat.zero_lt_succ _), },\n specialize ih (s.next _ hv) (λ i hi, by simpa [Stream.next'_val hv] using h (i + 1) (nat.succ_lt_succ hi)),\n simp [hv, fin.sum_univ_succ, ih, Stream.eval₀_eq_single _ _ hv, Stream.next'_val hv],\n rw add_comm,\nend\n\nnamespace primitives\n\n@[simps]\ndef externSparseVec_stream {len : ℕ} (inds : vector ι len) (vals : vector α len) :\n Stream ι α :=\n{ σ := ℕ,\n valid := λ i, i < len,\n ready := λ i, i < len,\n next := λ i hi, i + 1,\n index := λ i hi, inds.nth ⟨i, hi⟩,\n value := λ i hi, vals.nth ⟨i, hi⟩ }\n\n@[simp] lemma externSparseVec_stream_value' [has_zero α] {len : ℕ} (inds : vector ι len) (vals : vector α len) (i : fin len) :\n (externSparseVec_stream inds vals).value' (i : ℕ) = vals.nth i := \nby { rw Stream.value'_val, swap, { exact i.prop, }, simp, }\n\n@[simp] lemma externSparseVec_next'_iterate {len : ℕ} (inds : vector ι len) (vals : vector α len) (i : ℕ) :\n ((externSparseVec_stream inds vals).next'^[i] 0 : ℕ) = min len i :=\nbegin\n induction i with i ih, { simp [externSparseVec_stream], },\n rw [function.iterate_succ_apply', ih],\n simp [Stream.next', min_def, nat.succ_eq_add_one], clear ih,\n split_ifs; linarith,\nend\n\n@[simps]\ndef externSparseVec {len : ℕ} (inds : vector ι len) (vals : vector α len) :\n StreamExec ι α :=\n{ stream := externSparseVec_stream inds vals,\n state := (0 : ℕ),\n bound := len,\n bound_valid := by simp [bound_valid_iff_next'_iterate] }\n\n@[simp] lemma externSparseVec.spec [add_comm_monoid α] {len : ℕ} (inds : vector ι len) (vals : vector α len) :\n (externSparseVec inds vals).eval = ∑ i : fin len, finsupp.single (inds.nth i) (vals.nth i) :=\nbegin\n rw [StreamExec.eval, Stream.spec_of_iterate], swap, { dsimp, simp, },\n dsimp, apply fintype.sum_congr,\n intro i,\n congr; { simp [min_eq_right i.prop.le], },\nend\n\n@[simps]\ndef range (n : ℕ) : Stream ℕ ℕ :=\n{ σ := ℕ,\n next := λ k _, k+1,\n index := λ k _, k,\n value := λ k _, k,\n ready := λ _, true,\n valid := λ k, k < n, }\n\n@[simp] lemma range_iterate {n : ℕ} (i : ℕ) :\n ((range n).next'^[i] 0 : ℕ) = min n i :=\nbegin\n induction i with i ih, { simp [range], },\n rw [function.iterate_succ_apply', ih],\n simp [Stream.next', min_def, nat.succ_eq_add_one], clear ih,\n split_ifs; linarith,\nend\n\n@[simps]\ndef range_exec (n : ℕ) : StreamExec ℕ ℕ :=\n{ stream := range n,\n state := (0 : ℕ),\n bound := n,\n bound_valid := by simp [bound_valid_iff_next'_iterate] }\n\nend primitives\n", "meta": {"author": "kovach", "repo": "etch", "sha": "26ef67eb83cf7c5cfd1667059e16c3873b9098ca", "save_path": "github-repos/lean/kovach-etch", "path": "github-repos/lean/kovach-etch/etch-26ef67eb83cf7c5cfd1667059e16c3873b9098ca/src/verification/semantics/stream.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.399811640739795, "lm_q2_score": 0.043365800463895605, "lm_q1q2_score": 0.017338151835464666}} {"text": "namespace Cached\n\nstructure Cached {α : Type u} {β : Type v} (f : α → β) (x : α) :=\n val : β\n isFX : f x = val\n deriving Repr\n\ninstance : EmptyCollection (Cached f x) where emptyCollection := ⟨f x, rfl⟩\ninstance : Inhabited (Cached f x) where default := {}\ninstance : Subsingleton (Cached f x) where\n allEq := fun ⟨b, hb⟩ ⟨c, hc⟩ => by subst hb; subst hc; rfl\ninstance : DecidableEq (Cached f x) := fun _ _ => isTrue (Subsingleton.allEq ..)\ninstance [ToString β] : ToString (@Cached α β f x) where\n toString c := toString c.val\n\n@[simp]\ntheorem eq_of_subsingleton [Subsingleton α] {a b : α} : (a = b) = True := by\n simp [Subsingleton.allEq a b]\n\nabbrev Cached' (a : α) := Cached id a\n\nend Cached\n", "meta": {"author": "lurk-lab", "repo": "YatimaStdLib.lean", "sha": "f39dca7a0815ee65e71776d46337f0240037ff6d", "save_path": "github-repos/lean/lurk-lab-YatimaStdLib.lean", "path": "github-repos/lean/lurk-lab-YatimaStdLib.lean/YatimaStdLib.lean-f39dca7a0815ee65e71776d46337f0240037ff6d/YatimaStdLib/Cached.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4111108548019597, "lm_q2_score": 0.04208772446124641, "lm_q1q2_score": 0.01730272037993236}} {"text": "import Iris.BI\nimport Iris.Proofmode.Classes\nimport Iris.Proofmode.Environments\nimport Iris.Std\n\nnamespace Iris.Proofmode\nopen Iris.BI Iris.Std\nopen BI\n\n/-- Introduce one or multiple let-bound variables. -/\nscoped macro \"intro_let \" names:(colGt Lean.binderIdent)* : tactic => `(\n intro _ ;\n split ;\n rename_i $[$names]*\n)\n\n-- proof mode\ntheorem tac_start [BI PROP] (P : PROP) :\n envs_entails ⟨.nil, .nil⟩ P →\n ⊢ P\n:= by\n simp only [envs_entails, of_envs, big_op]\n rw' [intuitionistically_True_emp, (left_id : emp ∗ _ ⊣⊢ _)]\n intro h\n exact h\n\ntheorem tac_stop [BI PROP] {Γₚ Γₛ : Env PROP} (P : PROP) :\n let Ps := match Γₚ, Γₛ with\n | .nil, .nil => `[iprop| emp]\n | _ , .nil => `[iprop| □ [∧] Γₚ]\n | .nil, _ => `[iprop| [∗] Γₛ]\n | _ , _ => `[iprop| □ [∧] Γₚ ∗ [∗] Γₛ]\n (Ps ⊢ P) →\n envs_entails ⟨Γₚ, Γₛ⟩ P\n:= by\n cases Γₚ\n <;> cases Γₛ\n all_goals\n simp [envs_entails, of_envs, big_op]\n intro Ps\n rw' [Ps]\n case cons.nil =>\n rw' [(right_id : _ ∗ emp ⊣⊢ _)]\n all_goals\n rw' [intuitionistically_True_emp, (left_id : emp ∗ _ ⊣⊢ _)]\n\ntheorem tac_clear [BI PROP] {Δ : Envs PROP} (i : EnvsIndex.of Δ) (Q : PROP) :\n let (p, P) := Δ.lookup i\n [TCIte p TCTrue (TCOr (Affine P) (Absorbing Q))] →\n envs_entails (Δ.delete true i) Q →\n envs_entails Δ Q\n:= by\n intro_let p P h_lookup\n intro inst_affine_absorbing\n cases p\n all_goals\n cases inst_affine_absorbing\n simp only [envs_entails]\n intro h_entails\n rw' [envs_lookup_delete_sound true h_lookup, h_entails]\n simp only [bi_intuitionistically_if, ite_true, ite_false]\n rw' [sep_elim_r]\n\n-- pure\ntheorem tac_pure_intro [BI PROP] {Δ : Envs PROP} {a : Bool} {φ : Prop} (Q : PROP) :\n [FromPure a Q φ] →\n [TCIte a (AffineEnv Δ.spatial) TCTrue] →\n φ →\n envs_entails Δ Q\n:= by\n simp only [envs_entails]\n intro _ inst_affine_env hφ\n rw' [← from_pure]\n cases a\n case false =>\n apply pure_intro\n exact hφ\n case true =>\n cases inst_affine_env\n simp only [of_envs, bi_affinely_if]\n rw' [\n affine,\n pure_True hφ,\n affinely_True_emp,\n affinely_emp]\n\n-- implication and wand\ntheorem tac_impl_intro [BI PROP] {Δ : Envs PROP} {P Q : PROP} (R : PROP) :\n [FromImpl R P Q] →\n [TCIte Δ.spatial.isEmpty TCTrue (Persistent P)] →\n [FromAffinely P' P] →\n envs_entails (Δ.append false P') Q →\n envs_entails Δ R\n:= by\n simp only [envs_entails]\n intro _ inst_pers _ h_entails\n rw' [← from_impl]\n cases h_empty : Δ.spatial.isEmpty\n <;> rw [h_empty] at inst_pers\n <;> cases inst_pers\n case false =>\n apply impl_intro_l\n rw' [\n envs_append_sound false P',\n (from_affinely : ?true P ⊢ _),\n persistent_and_affinely_sep_l_1,\n wand_elim_r,\n h_entails]\n case true =>\n rw' [envs_spatial_is_empty_intuitionistically h_empty]\n apply impl_intro_l\n rw' [\n envs_append_sound false P',\n (from_affinely : ?true P ⊢ _)]\n simp only [bi_intuitionistically]\n rw' [\n ← affinely_and_lr,\n persistently_and_intuitionistically_sep_r,\n intuitionistically_elim,\n wand_elim_r,\n h_entails]\n\ntheorem tac_impl_intro_intuitionistic [BI PROP] {Δ : Envs PROP} {P P' Q : PROP} (R : PROP) :\n [FromImpl R P Q] →\n [IntoPersistent false P P'] →\n envs_entails (Δ.append true P') Q →\n envs_entails Δ R\n:= by\n simp only [envs_entails]\n intro _ _ h_entails\n rw' [← from_impl, envs_append_sound true P'] ; simp only\n apply impl_intro_l\n rw' [\n persistently_if_intro_false P,\n into_persistent,\n persistently_and_intuitionistically_sep_l,\n wand_elim_r,\n h_entails]\n\ntheorem tac_impl_intro_drop [BI PROP] {Δ : Envs PROP} {P Q : PROP} (R : PROP) :\n [FromImpl R P Q] →\n envs_entails Δ Q →\n envs_entails Δ R\n:= by\n simp only [envs_entails]\n intro _ h_entails\n rw' [← from_impl]\n apply impl_intro_l\n rw' [and_elim_r, h_entails]\n\ntheorem tac_wand_intro [BI PROP] {Δ : Envs PROP} {P Q : PROP} (R : PROP) :\n [FromWand R P Q] →\n envs_entails (Δ.append false P) Q →\n envs_entails Δ R\n:= by\n simp only [envs_entails]\n intro _ h_entails\n rw' [\n ← from_wand,\n envs_append_sound false P,\n h_entails]\n\ntheorem tac_wand_intro_intuitionistic [BI PROP] {Δ : Envs PROP} {P P' Q : PROP} (R : PROP) :\n [FromWand R P Q] →\n [IntoPersistent false P P'] →\n [TCOr (Affine P) (Absorbing Q)] →\n envs_entails (Δ.append true P') Q →\n envs_entails Δ R\n:= by\n simp only [envs_entails]\n intro _ _ inst_affine_absorbing h_entails\n rw' [← from_wand, envs_append_sound true P'] ; simp only\n apply wand_intro_l\n cases inst_affine_absorbing\n case a.l =>\n rw' [\n ← affine_affinely P,\n persistently_if_intro_false P,\n into_persistent,\n wand_elim_r,\n h_entails]\n case a.r =>\n rw' [\n persistently_if_intro_false P,\n into_persistent,\n ← absorbingly_intuitionistically_into_persistently,\n absorbingly_sep_l,\n wand_elim_r,\n h_entails,\n absorbing]\n\n-- specialize\ntheorem tac_specialize [BI PROP] {Δ : Envs PROP} (rpPremise rpWand : Bool) (i j : EnvsIndex.of Δ) (h_ne : i.type = j.type → i.val ≠ j.val) {P2 : PROP} (R : PROP) :\n let (p, P1) := Δ.lookup i\n let Δ' := Δ.delete rpPremise i\n let j' := Δ.updateIndexAfterDelete rpPremise i j h_ne\n let (q, Q) := Δ'.lookup j'\n [IntoWand q p Q P1 P2] →\n envs_entails (Δ'.replace rpWand j' (p && q) P2) R →\n envs_entails Δ R\n:= by\n intro_let p P1 h_lookup_i\n intro Δ' j'\n intro_let q Q h_lookup_j'\n simp only [envs_entails]\n intro _ h_entails\n rw' [\n envs_lookup_delete_sound rpPremise h_lookup_i,\n envs_lookup_replace_sound rpWand (p && q) P2 h_lookup_j']\n cases p\n case false =>\n rw' [(IntoWand.into_wand : □?q Q ⊢ □?false P1 -∗ P2)]\n simp only [bi_intuitionistically_if, Bool.false_and, ite_false]\n rw' [(assoc : P1 ∗ _ ⊣⊢ _), !wand_elim_r, h_entails]\n case true =>\n simp only [Bool.true_and, ← intuitionistically_if_intro_true]\n rw' [\n ← intuitionistically_idemp,\n ← intuitionistically_if_idemp,\n intuitionistically_intuitionistically_if q,\n (IntoWand.into_wand : □?q Q ⊢ □?true P1 -∗ P2),\n (assoc : □?q □ P1 ∗ _ ⊣⊢ _),\n intuitionistically_if_sep_2,\n !wand_elim_r,\n h_entails]\n\ntheorem tac_specialize_forall [BI PROP] {Δ : Envs PROP} (rpWand : Bool) (i : EnvsIndex.of Δ) {Φ : α → PROP} (Q : PROP) :\n let (p, P) := Δ.lookup i\n [IntoForall P Φ] →\n (∃ x, envs_entails (Δ.replace rpWand i p (Φ x)) Q) →\n envs_entails Δ Q\n:= by\n intro_let p P h_lookup\n simp only [envs_entails]\n intro _ ⟨x, h_entails⟩\n rw' [\n envs_lookup_replace_sound rpWand p (Φ x) h_lookup,\n IntoForall.into_forall,\n forall_elim x,\n wand_elim_r,\n h_entails]\n\n-- forall\ntheorem tac_forall_intro [BI PROP] {Δ : Envs PROP} {Ψ : α → PROP} (Q : PROP) :\n [FromForall Q Ψ] →\n (∀ a, envs_entails Δ `[iprop| Ψ a]) →\n envs_entails Δ Q\n:= by\n simp only [envs_entails]\n intro _ h_entails\n rw' [← from_forall]\n apply forall_intro\n exact h_entails\n\n-- exist\ntheorem tac_exist [BI PROP] {Δ : Envs PROP} {Φ : α → PROP} (P : PROP) :\n [FromExist P Φ] →\n (∃ a, envs_entails Δ `[iprop| Φ a]) →\n envs_entails Δ P\n:= by\n simp only [envs_entails]\n intro _ ⟨a, h_entails⟩\n rw' [← from_exist, ← exist_intro a, h_entails]\n\ntheorem tac_exist_destruct [BI PROP] {Δ : Envs PROP} (i : EnvsIndex.of Δ) {Φ : α → PROP} (Q : PROP) :\n let (p, P) := Δ.lookup i\n [IntoExist P Φ] →\n (∀ a, envs_entails (Δ.replace true i p (Φ a)) Q) →\n envs_entails Δ Q\n:= by\n intro_let p P h_lookup\n simp only [envs_entails, Envs.replace]\n intro _ h_entails\n rw' [\n envs_lookup_delete_sound true h_lookup,\n into_exist,\n intuitionistically_if_exist,\n sep_exist_r] ; simp only\n apply exist_elim\n intro a\n rw' [\n envs_append_sound p (Φ a),\n wand_elim_r,\n h_entails a]\n\n-- emp\ntheorem tac_emp_intro [BI PROP] {Γₚ Γₛ : Env PROP} :\n [AffineEnv Γₛ] →\n envs_entails ⟨Γₚ, Γₛ⟩ `[iprop| emp]\n:= by\n intro _\n simp only [envs_entails, of_envs]\n rw' [\n affinely_elim_emp,\n (affine : [∗] Γₛ.toList ⊢ emp),\n (left_id : emp ∗ _ ⊣⊢ _)]\n\n-- assumptions\ntheorem tac_assumption_lean [BI PROP] {Δ : Envs PROP} {P : PROP} (Q : PROP) :\n (⊢ P) →\n [FromAssumption true P Q] →\n [TCIte Δ.spatial.isEmpty TCTrue (TCOr (Absorbing Q) (AffineEnv Δ.spatial))] →\n envs_entails Δ Q\n:= by\n simp only [envs_entails]\n intro h_P _ inst_absorbing_affine_env\n rw' [\n ← (left_id : emp ∗ of_envs Δ ⊣⊢ _),\n ← intuitionistically_emp,\n h_P,\n (from_assumption : □?true P ⊢ Q)]\n cases h_empty : Δ.spatial.isEmpty\n <;> rw [h_empty] at inst_absorbing_affine_env\n <;> cases inst_absorbing_affine_env\n case false.e inst_absorbing_affine_env =>\n cases inst_absorbing_affine_env\n <;> rw' [!sep_elim_l]\n case true.t =>\n rw' [envs_spatial_is_empty_intuitionistically h_empty, sep_elim_l]\n\ntheorem tac_assumption [BI PROP] {Δ : Envs PROP} (i : EnvsIndex.of Δ) (Q : PROP) :\n let (p, P) := Δ.lookup i\n [FromAssumption p P Q] →\n let Δ' := Δ.delete true i\n [TCIte Δ'.spatial.isEmpty TCTrue (TCOr (Absorbing Q) (AffineEnv Δ'.spatial))] →\n envs_entails Δ Q\n:= by\n intro_let p P h_lookup\n simp only [envs_entails]\n intro _ inst_absorbing_affine_env\n rw' [envs_lookup_delete_sound true h_lookup]\n cases h_empty : (Δ.delete true i).spatial.isEmpty\n <;> rw [h_empty] at inst_absorbing_affine_env\n <;> cases inst_absorbing_affine_env\n case false.e inst_absorbing_affine_env =>\n rw' [(from_assumption : □?p P ⊢ Q)]\n cases inst_absorbing_affine_env\n <;> rw' [!sep_elim_l]\n case true.t =>\n rw' [envs_spatial_is_empty_intuitionistically h_empty, sep_elim_l]\n exact from_assumption\n\n-- false\ntheorem tac_ex_falso [BI PROP] {Δ : Envs PROP} (Q : PROP) :\n envs_entails Δ `[iprop| False] →\n envs_entails Δ Q\n:= by\n simp only [envs_entails]\n intro h_entails\n rw' [h_entails]\n exact False_elim\n\ntheorem tac_false_destruct [BI PROP] {Δ : Envs PROP} (i : EnvsIndex.of Δ) (Q : PROP) :\n let (_, P) := Δ.lookup i\n P = `[iprop| False] →\n envs_entails Δ Q\n:= by\n intro_let p P h_lookup\n simp only [envs_entails]\n intro h_false\n rw' [\n envs_lookup_delete_sound true h_lookup,\n intuitionistically_if_elim,\n h_false,\n sep_elim_l]\n exact False_elim\n\n-- moving between contexts\ntheorem tac_pure [BI PROP] {Δ : Envs PROP} {φ : Prop} (i : EnvsIndex.of Δ) (Q : PROP) :\n let (p, P) := Δ.lookup i\n [IntoPure P φ] →\n [TCIte p TCTrue (TCOr (Affine P) (Absorbing Q))] →\n (φ → envs_entails (Δ.delete true i) Q) →\n envs_entails Δ Q\n:= by\n intro_let p P h_lookup\n simp only [envs_entails]\n intro _ inst_affine_absorbing h_entails\n rw' [envs_lookup_delete_sound true h_lookup]\n cases p\n <;> simp only [bi_intuitionistically_if, ite_true, ite_false]\n <;> cases inst_affine_absorbing\n case false.e inst_affine_absorbing =>\n cases inst_affine_absorbing\n case l =>\n rw' [\n ← affine_affinely P,\n into_pure,\n ← persistent_and_affinely_sep_l]\n apply pure_elim φ\n · exact and_elim_l\n · intro h_φ\n rw' [h_entails h_φ, and_elim_r]\n case r =>\n rw' [\n into_pure,\n persistent_absorbingly_affinely_2,\n absorbingly_sep_lr,\n ← persistent_and_affinely_sep_l]\n apply pure_elim_l\n intro h_φ\n rw' [h_entails h_φ, absorbing]\n case true.t =>\n rw' [\n into_pure,\n ← persistently_and_intuitionistically_sep_l,\n persistently_pure]\n apply pure_elim_l\n intro h_φ\n rw' [h_entails h_φ]\n\ntheorem tac_intuitionistic [BI PROP] {Δ : Envs PROP} {P' : PROP} (i : EnvsIndex.of Δ) (Q : PROP) :\n let (p, P) := Δ.lookup i\n [IntoPersistent p P P'] →\n [TCIte p TCTrue (TCOr (Affine P) (Absorbing Q))] →\n envs_entails (Δ.replace true i true P') Q →\n envs_entails Δ Q\n:= by\n intro_let p P h_lookup\n simp only [envs_entails]\n intro _ inst_affine_absorbing h_entails\n rw' [envs_lookup_replace_sound true true P' h_lookup]\n cases p\n <;> simp only [bi_intuitionistically_if, ite_true, ite_false, bi_intuitionistically]\n <;> cases inst_affine_absorbing\n case false inst_affine_absorbing =>\n cases inst_affine_absorbing\n case l =>\n rw' [\n ← affine_affinely P,\n persistently_if_intro_false P,\n into_persistent,\n wand_elim_r,\n h_entails]\n case r =>\n rw' [persistently_if_intro_false P, into_persistent]\n conv =>\n lhs\n lhs\n rw [← absorbingly_intuitionistically_into_persistently]\n rw' [\n absorbingly_sep_l,\n wand_elim_r,\n h_entails,\n absorbing]\n case true =>\n rw' [\n persistently_if_intro_true P,\n into_persistent,\n wand_elim_r,\n h_entails]\n\ntheorem tac_spatial [BI PROP] {Δ : Envs PROP} {P' : PROP} (i : EnvsIndex.of Δ) (Q : PROP) :\n let (p, P) := Δ.lookup i\n [FromAffinely P' P p] →\n envs_entails (Δ.replace true i false P') Q →\n envs_entails Δ Q\n:= by\n intro_let p P h_lookup\n simp only [envs_entails]\n intro _ h_entails\n rw' [envs_lookup_replace_sound true false P' h_lookup]\n cases p\n <;> simp only [bi_intuitionistically_if, ite_true, ite_false]\n case false =>\n rw' [\n affinely_if_intro_false P,\n from_affinely,\n wand_elim_r,\n h_entails]\n case true =>\n rw' [\n intuitionistically_affinely,\n affinely_if_intro_true P,\n from_affinely,\n wand_elim_r,\n h_entails]\n\n-- (separating) conjunction splitting\ntheorem tac_and_split [BI PROP] {Δ : Envs PROP} {Q1 Q2 : PROP} (P : PROP) :\n [FromAnd P Q1 Q2] →\n envs_entails Δ Q1 →\n envs_entails Δ Q2 →\n envs_entails Δ P\n:= by\n simp only [envs_entails]\n intro _ h_entails_1 h_entails_2\n rw' [← from_and]\n apply and_intro\n · exact h_entails_1\n · exact h_entails_2\n\ntheorem tac_sep_split [BI PROP] {Δ : Envs PROP} {Q1 Q2 : PROP} (mask : List Bool) (h : mask.length = Δ.spatial.length) (P : PROP) :\n let (Δ₁, Δ₂) := Δ.split mask h\n [FromSep P Q1 Q2] →\n envs_entails Δ₁ Q1 →\n envs_entails Δ₂ Q2 →\n envs_entails Δ P\n:= by\n intro_let Δ₁ Δ₂ h_split\n simp only [envs_entails]\n intro _ h_entails_1 h_entails_2\n rw' [\n envs_split_sound h_split,\n ← from_sep,\n h_entails_1,\n h_entails_2]\n\n-- disjunction selection\ntheorem tac_disjunction_l [BI PROP] {Δ : Envs PROP} {Q1 Q2 : PROP} (P : PROP) :\n [FromOr P Q1 Q2] →\n envs_entails Δ Q1 →\n envs_entails Δ P\n:= by\n simp only [envs_entails]\n intro _ h_entails\n rw' [← from_or]\n apply or_intro_l'\n exact h_entails\n\ntheorem tac_disjunction_r [BI PROP] {Δ : Envs PROP} {Q1 Q2 : PROP} (P : PROP) :\n [FromOr P Q1 Q2] →\n envs_entails Δ Q2 →\n envs_entails Δ P\n:= by\n simp only [envs_entails]\n intro _ h_entails\n rw' [← from_or]\n apply or_intro_r'\n exact h_entails\n\n-- destruction\nclass inductive IntoConjunction [BI PROP] (P : PROP) (P1 P2 : outParam PROP) : Bool → Type\n | and : [IntoAnd true P P1 P2] → IntoConjunction P P1 P2 true\n | sep : [IntoSep P P1 P2] → IntoConjunction P P1 P2 false\n\nattribute [instance] IntoConjunction.and\nattribute [instance] IntoConjunction.sep\n\ntheorem tac_conjunction_destruct [BI PROP] {Δ : Envs PROP} {P1 P2 : PROP} (i : EnvsIndex.of Δ) (Q : PROP) :\n let (p, P) := Δ.lookup i\n [IntoConjunction P P1 P2 p] →\n envs_entails (Δ |>.delete true i |>.append p P1 |>.append p P2) Q →\n envs_entails Δ Q\n:= by\n intro_let p P h_lookup\n simp only [envs_entails]\n intro inst_conjunction h_entails\n rw' [\n envs_lookup_delete_sound true h_lookup,\n envs_append_sound p P1,\n envs_append_sound p P2] ; simp only\n cases p\n <;> simp only [bi_intuitionistically_if, ite_true, ite_false]\n <;> cases inst_conjunction\n case false.sep =>\n rw' [\n into_sep,\n (comm : P1 ∗ P2 ⊣⊢ _),\n ← (assoc : _ ⊣⊢ (P2 ∗ P1) ∗ _),\n wand_elim_r,\n wand_elim_r,\n h_entails]\n case true.and =>\n rw' [intuitionistically_if_intro_true P, into_and]\n simp only [bi_intuitionistically_if, ite_true]\n rw' [\n intuitionistically_and,\n and_sep_intuitionistically,\n (comm : □ P1 ∗ □ P2 ⊣⊢ _),\n ← (assoc : _ ⊣⊢ (□ P2 ∗ □ P1) ∗ _),\n wand_elim_r,\n wand_elim_r,\n h_entails]\n\ntheorem tac_conjunction_destruct_choice [BI PROP] {Δ : Envs PROP} {P1 P2 : PROP} (i : EnvsIndex.of Δ) (d : Bool) (Q : PROP) :\n let (p, P) := Δ.lookup i\n [IntoAnd p P P1 P2] →\n envs_entails (if d then Δ.replace true i p P1 else Δ.replace true i p P2) Q →\n envs_entails Δ Q\n:= by\n intro_let p P h_lookup\n simp only [envs_entails]\n intro _ h_entails\n cases d\n case false =>\n rw' [\n envs_lookup_replace_sound true p P2 h_lookup,\n into_and,\n and_elim_r,\n wand_elim_r,\n h_entails]\n case true =>\n rw' [\n envs_lookup_replace_sound true p P1 h_lookup,\n into_and,\n and_elim_l,\n wand_elim_r,\n h_entails]\n\ntheorem tac_disjunction_destruct [BI PROP] {Δ : Envs PROP} {P1 P2 : PROP} (i : EnvsIndex.of Δ) (Q : PROP) :\n let (p, P) := Δ.lookup i\n [IntoOr P P1 P2] →\n envs_entails (Δ.replace true i p P1) Q →\n envs_entails (Δ.replace true i p P2) Q →\n envs_entails Δ Q\n:= by\n intro_let p P h_lookup\n simp only [envs_entails]\n intro _ h_entails_1 h_entails_2\n rw' [envs_lookup_delete_sound true h_lookup] ; simp only\n simp only [Envs.replace] at h_entails_1\n simp only [Envs.replace] at h_entails_2\n rw' [into_or, intuitionistically_if_or, sep_or_r]\n apply or_elim\n · rw' [envs_append_sound p P1, wand_elim_r, h_entails_1]\n · rw' [envs_append_sound p P2, wand_elim_r, h_entails_2]\n\nend Iris.Proofmode\n", "meta": {"author": "larsk21", "repo": "iris-lean", "sha": "730e644d0ffaad78aac76e2e5f2cd8af0f1d2310", "save_path": "github-repos/lean/larsk21-iris-lean", "path": "github-repos/lean/larsk21-iris-lean/iris-lean-730e644d0ffaad78aac76e2e5f2cd8af0f1d2310/src/Iris/Proofmode/Theorems.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.03567855215943872, "lm_q1q2_score": 0.01728198010186971}} {"text": "/- Tactic combinators -/\n\nexample : p → q → r → p ∧ ((p ∧ q) ∧ r) ∧ (q ∧ r ∧ p) := by\n intros\n repeat (any_goals constructor)\n all_goals assumption\n\nexample : p → q → r → p ∧ ((p ∧ q) ∧ r) ∧ (q ∧ r ∧ p) := by\n intros\n repeat (any_goals (first | assumption | constructor))\n", "meta": {"author": "leanprover", "repo": "lean4", "sha": "742d053a97bdd109a41a921facd1cd6a55e89bc7", "save_path": "github-repos/lean/leanprover-lean4", "path": "github-repos/lean/leanprover-lean4/lean4-742d053a97bdd109a41a921facd1cd6a55e89bc7/doc/examples/NFM2022/nfm19.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.31742626558767584, "lm_q2_score": 0.054198732496667, "lm_q1q2_score": 0.017204101256002417}} {"text": "example {a : α} {as bs : List α} (h : bs = a::as) : as.length + 1 = bs.length := by\n rw [← List.length]\n trace_state -- lhs was folded\n rw [h]\n\nexample {a : α} {as bs : List α} (h : as = bs) : (a::b::as).length = bs.length + 2 := by\n rw [List.length, List.length]\n trace_state -- lhs was unfolded\n rw [h]\n\nexample {a : α} {as bs : List α} (h : as = bs) : (a::b::as).length = (b::bs).length + 1 := by\n conv => lhs; rw [List.length, List.length]\n trace_state -- lhs was unfolded\n conv => rhs; rw [List.length]\n trace_state -- rhs was unfolded\n rw [h]\n\nexample {a : α} {as bs : List α} (h : as = bs) : id (id ((a::b::as).length)) = (b::bs).length + 1 := by\n rw [id]\n trace_state\n rw [id]\n trace_state\n rw [List.length, List.length, List.length]\n trace_state\n rw [h]\n", "meta": {"author": "leanprover", "repo": "lean4", "sha": "742d053a97bdd109a41a921facd1cd6a55e89bc7", "save_path": "github-repos/lean/leanprover-lean4", "path": "github-repos/lean/leanprover-lean4/lean4-742d053a97bdd109a41a921facd1cd6a55e89bc7/tests/lean/rwEqThms.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4339814794452761, "lm_q2_score": 0.03963883711558994, "lm_q1q2_score": 0.01720252117491404}} {"text": "/-\nCopyright (c) 2017 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Gabriel Ebner\n-/\nimport data.buffer data.dlist\n\ninductive parse_result (α : Type)\n| done (pos : ℕ) (result : α) : parse_result\n| fail (pos : ℕ) (expected : dlist string) : parse_result\n\n/-- The parser monad. If you are familiar with the Parsec library in Haskell, you will understand this. -/\ndef parser (α : Type) :=\n∀ (input : char_buffer) (start : ℕ), parse_result α\n\nnamespace parser\nvariables {α β γ : Type}\n\nprotected def bind (p : parser α) (f : α → parser β) : parser β :=\nλ input pos, match p input pos with\n| parse_result.done pos a := f a input pos\n| parse_result.fail pos expected := parse_result.fail pos expected\nend\n\nprotected def pure (a : α) : parser α :=\nλ input pos, parse_result.done pos a\n\nprivate lemma parser.id_map (p : parser α) : parser.bind p parser.pure = p :=\nbegin\napply funext, intro input,\napply funext, intro pos,\ndunfold parser.bind,\ncases (p input pos); exact rfl\nend\n\nprivate lemma parser.bind_assoc (p : parser α) (q : α → parser β) (r : β → parser γ) :\n parser.bind (parser.bind p q) r = parser.bind p (λ a, parser.bind (q a) r) :=\nbegin\napply funext, intro input,\napply funext, intro pos,\ndunfold parser.bind,\ncases (p input pos); try {dunfold bind},\ncases (q result input pos_1); try {dunfold bind},\nall_goals {refl}\nend\n\nprotected def fail (msg : string) : parser α :=\nλ _ pos, parse_result.fail pos (dlist.singleton msg)\n\ninstance : monad parser :=\n{ pure := @parser.pure, bind := @parser.bind }\n\ninstance : is_lawful_monad parser :=\n{ id_map := @parser.id_map,\n pure_bind := λ _ _ _ _, rfl,\n bind_assoc := @parser.bind_assoc }\n\ninstance : monad_fail parser :=\n{ fail := @parser.fail, ..parser.monad }\n\nprotected def failure : parser α :=\nλ _ pos, parse_result.fail pos dlist.empty\n\nprotected def orelse (p q : parser α) : parser α :=\nλ input pos, match p input pos with\n| parse_result.fail pos₁ expected₁ :=\n if pos₁ ≠ pos then parse_result.fail pos₁ expected₁ else\n match q input pos with\n | parse_result.fail pos₂ expected₂ :=\n if pos₁ < pos₂ then\n parse_result.fail pos₁ expected₁\n else if pos₂ < pos₁ then\n parse_result.fail pos₂ expected₂\n else -- pos₁ = pos₂\n parse_result.fail pos₁ (expected₁ ++ expected₂)\n | ok := ok\n end\n | ok := ok\nend\n\ninstance : alternative parser :=\n{ failure := @parser.failure,\n orelse := @parser.orelse }\n\ninstance : inhabited (parser α) :=\n⟨parser.failure⟩\n\n/-- Overrides the expected token name, and does not consume input on failure. -/\ndef decorate_errors (msgs : thunk (list string)) (p : parser α) : parser α :=\nλ input pos, match p input pos with\n| parse_result.fail _ expected :=\n parse_result.fail pos (dlist.lazy_of_list (msgs ()))\n| ok := ok\nend\n\n/-- Overrides the expected token name, and does not consume input on failure. -/\ndef decorate_error (msg : thunk string) (p : parser α) : parser α :=\ndecorate_errors [msg ()] p\n\n/-- Matches a single character. Fails only if there is no more input. -/\ndef any_char : parser char :=\nλ input pos,\nif h : pos < input.size\n then\n let c := input.read ⟨pos, h⟩ in\n parse_result.done (pos+1) c\n else\n parse_result.fail pos dlist.empty\n\n/-- Matches a single character satisfying the given predicate. -/\ndef sat (p : char → Prop) [decidable_pred p] : parser char :=\nλ input pos,\nif h : pos < input.size\n then\n let c := input.read ⟨pos, h⟩ in\n if p c then\n parse_result.done (pos+1) c\n else\n parse_result.fail pos dlist.empty\n else\n parse_result.fail pos dlist.empty\n\n/-- Matches the empty word. -/\ndef eps : parser unit := return ()\n\n/-- Matches the given character. -/\ndef ch (c : char) : parser unit :=\ndecorate_error c.to_string $ sat (= c) >> eps\n\n/-- Matches a whole char_buffer. Does not consume input in case of failure. -/\ndef char_buf (s : char_buffer) : parser unit :=\ndecorate_error s.to_string $ s.to_list.mmap' ch\n\n/-- Matches one out of a list of characters. -/\ndef one_of (cs : list char) : parser char :=\ndecorate_errors (do c ← cs, return c.to_string) $\nsat (∈ cs)\n\ndef one_of' (cs : list char) : parser unit :=\none_of cs >> eps\n\n/-- Matches a string. Does not consume input in case of failure. -/\ndef str (s : string) : parser unit :=\ndecorate_error s $ s.to_list.mmap' ch\n\n/-- Number of remaining input characters. -/\ndef remaining : parser ℕ :=\nλ input pos, parse_result.done pos (input.size - pos)\n\n/-- Matches the end of the input. -/\ndef eof : parser unit :=\ndecorate_error \"\" $\ndo rem ← remaining, guard $ rem = 0\n\ndef foldr_core (f : α → β → β) (p : parser α) (b : β) : ∀ (reps : ℕ), parser β\n| 0 := failure\n| (reps+1) := (do x ← p, xs ← foldr_core reps, return (f x xs)) <|> return b\n\n/-- Matches zero or more occurrences of `p`, and folds the result. -/\ndef foldr (f : α → β → β) (p : parser α) (b : β) : parser β :=\nλ input pos, foldr_core f p b (input.size - pos + 1) input pos\n\ndef foldl_core (f : α → β → α) : ∀ (a : α) (p : parser β) (reps : ℕ), parser α\n| a p 0 := failure\n| a p (reps+1) := (do x ← p, foldl_core (f a x) p reps) <|> return a\n\n/-- Matches zero or more occurrences of `p`, and folds the result. -/\ndef foldl (f : α → β → α) (a : α) (p : parser β) : parser α :=\nλ input pos, foldl_core f a p (input.size - pos + 1) input pos\n\n/-- Matches zero or more occurrences of `p`. -/\ndef many (p : parser α) : parser (list α) :=\nfoldr list.cons p []\n\ndef many_char (p : parser char) : parser string :=\nlist.as_string <$> many p\n\n/-- Matches zero or more occurrences of `p`. -/\ndef many' (p : parser α) : parser unit :=\nmany p >> eps\n\n/-- Matches one or more occurrences of `p`. -/\ndef many1 (p : parser α) : parser (list α) :=\nlist.cons <$> p <*> many p\n\n/-- Matches one or more occurences of the char parser `p` and implodes them into a string. -/\ndef many_char1 (p : parser char) : parser string :=\nlist.as_string <$> many1 p\n\n/-- Matches one or more occurrences of `p`, separated by `sep`. -/\ndef sep_by1 (sep : parser unit) (p : parser α) : parser (list α) :=\nlist.cons <$> p <*> many (sep >> p)\n\n/-- Matches zero or more occurrences of `p`, separated by `sep`. -/\ndef sep_by (sep : parser unit) (p : parser α) : parser (list α) :=\nsep_by1 sep p <|> return []\n\ndef fix_core (F : parser α → parser α) : ∀ (max_depth : ℕ), parser α\n| 0 := failure\n| (max_depth+1) := F (fix_core max_depth)\n\n/-- Matches a digit (0-9). -/\ndef digit : parser nat := decorate_error \"\" $ do\n c ← sat (λ c, '0' ≤ c ∧ c ≤ '9'),\n pure $ c.to_nat - '0'.to_nat\n\n/-- Matches a natural number. Large numbers may cause performance issues, so\ndon't run this parser on untrusted input. -/\ndef nat : parser nat := decorate_error \"\" $ do\n digits ← many1 digit,\n pure $ prod.fst $ digits.foldr\n (λ digit ⟨sum, magnitude⟩, ⟨sum + digit * magnitude, magnitude * 10⟩)\n ⟨0, 1⟩\n\n/-- Fixpoint combinator satisfying `fix F = F (fix F)`. -/\ndef fix (F : parser α → parser α) : parser α :=\nλ input pos, fix_core F (input.size - pos + 1) input pos\n\nprivate def make_monospaced : char → char\n| '\\n' := ' '\n| '\\t' := ' '\n| '\\x0d' := ' '\n| c := c\n\ndef mk_error_msg (input : char_buffer) (pos : ℕ) (expected : dlist string) : char_buffer :=\nlet left_ctx := (input.take pos).take_right 10,\n right_ctx := (input.drop pos).take 10 in\nleft_ctx.map make_monospaced ++ right_ctx.map make_monospaced ++ \"\\n\".to_char_buffer ++\nleft_ctx.map (λ _, ' ') ++ \"^\\n\".to_char_buffer ++\n\"\\n\".to_char_buffer ++\n\"expected: \".to_char_buffer\n ++ string.to_char_buffer (\" | \".intercalate expected.to_list)\n ++ \"\\n\".to_char_buffer\n\n/-- Runs a parser on the given input. The parser needs to match the complete input. -/\ndef run (p : parser α) (input : char_buffer) : sum string α :=\nmatch (p <* eof) input 0 with\n| parse_result.done pos res := sum.inr res\n| parse_result.fail pos expected :=\n sum.inl $ buffer.to_string $ mk_error_msg input pos expected\nend\n\n/-- Runs a parser on the given input. The parser needs to match the complete input. -/\ndef run_string (p : parser α) (input : string) : sum string α :=\nrun p input.to_char_buffer\n\nend parser\n", "meta": {"author": "subfish-zhou", "repo": "N2Lean", "sha": "8e858cc5b01f1ad921094dc355db3cb9473a42fd", "save_path": "github-repos/lean/subfish-zhou-N2Lean", "path": "github-repos/lean/subfish-zhou-N2Lean/N2Lean-8e858cc5b01f1ad921094dc355db3cb9473a42fd/library/data/buffer/parser.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38861804086755836, "lm_q2_score": 0.044018649549418434, "lm_q1q2_score": 0.017106441349530623}} {"text": "import category_theory.shift\nimport for_mathlib.category_theory.quotient_misc\nimport for_mathlib.category_theory.functor.shift\n\nimport for_mathlib.category_theory.functor.shift_compatibility\n\nnoncomputable theory\n\nnamespace category_theory\n\nopen category\n\nvariables {C A : Type*} [category C] (r : hom_rel C)\n\nlemma quotient.functor_map_eq {X Y : C} (f : X ⟶ Y) :\n (quotient.functor r).map f = quot.mk _ f := rfl\n\nvariables [add_monoid A] [has_shift C A]\n (h : ∀ (a : A) ⦃X Y : C⦄ (f₁ f₂ : X ⟶ Y), r f₁ f₂ → r (f₁⟦a⟧') (f₂⟦a⟧'))\n\nvariable {r}\n\nnamespace quotient\n\n@[protected]\ndef shift_functor (a : A) : quotient r ⥤ quotient r :=\nlift r (shift_functor C a ⋙ functor r) (λ X Y f₁ f₂ rel, quotient.sound r (h a f₁ f₂ rel))\n\ndef comm_shift (a : A) :\n shift_functor C a ⋙ functor r ≅ functor r ⋙ quotient.shift_functor h a :=\n(quotient.lift.is_lift _ _ _).symm\n\n@[simp]\nlemma comm_shift_hom_app (a : A) (X : C) :\n (comm_shift h a).hom.app X = 𝟙 _ := rfl\n\n@[simp]\nlemma comm_shift_inv_app (a : A) (X : C) :\n (comm_shift h a).inv.app X = 𝟙 _ := rfl\n\ndef shift_ε : 𝟭 _ ≅ quotient.shift_functor h 0 :=\nquotient.lift_nat_iso _ _ (functor.right_unitor _ ≪≫ (functor.left_unitor _).symm ≪≫\n iso_whisker_right (shift_functor_zero C A).symm _ ≪≫ comm_shift h 0)\n\n@[simp]\nlemma shift_ε_hom_app (X : C) :\n (shift_ε h).hom.app ((functor r).obj X) =\n (functor r).map ((shift_functor_zero C A).inv.app X) :=\nbegin\n dsimp [shift_ε],\n simp only [id_comp, comp_id],\nend\n\ndef shift_μ (a b : A) :\n quotient.shift_functor h a ⋙ quotient.shift_functor h b ≅\n quotient.shift_functor h (a + b) :=\nquotient.lift_nat_iso _ _ ((functor.associator _ _ _).symm ≪≫\n iso_whisker_right (comm_shift h a).symm _ ≪≫ functor.associator _ _ _ ≪≫\n iso_whisker_left _ (comm_shift h b).symm ≪≫ (functor.associator _ _ _).symm ≪≫\n iso_whisker_right (shift_functor_add C a b).symm _ ≪≫ comm_shift h (a + b))\n\n@[simp]\nlemma shift_μ_hom_app (a b : A) (X : C) :\n (shift_μ h a b).hom.app ((functor r).obj X) =\n (functor r).map ((shift_functor_add C a b).inv.app X) :=\nbegin\n dsimp [shift_μ],\n simpa only [functor.map_id, comp_id, id_comp],\nend\n\nlocal attribute [instance, reducible] endofunctor_monoidal_category\nlocal attribute [reducible] discrete.add_monoidal\n\nlemma associativity_compatibility (a b c : A) (X : C) :\n (shift_functor C c).map ((shift_functor_add C a b).inv.app X) ≫\n (shift_functor_add C (a + b) c).inv.app X =\n (shift_functor_add C b c).inv.app ((shift_functor C a).obj X) ≫\n (shift_functor_add C a (b + c)).inv.app X ≫ eq_to_hom (by rw add_assoc):=\nbegin\n dsimp,\n have eq := (congr_arg iso.hom (monoidal_functor.associativity_iso_eq\n (shift_monoidal_functor C A) (discrete.mk a) (discrete.mk b) (discrete.mk c))),\n replace eq := congr_app eq X,\n dsimp at eq,\n simp only [id_comp, functor.map_id, comp_id] at eq,\n erw ← reassoc_of eq, clear eq,\n simp only [eq_to_hom_map, eq_to_hom_app, eq_to_hom_trans, eq_to_hom_refl, comp_id],\nend\n\nlemma shift_associativity (a b c : A) :\n (shift_μ h a b).hom ◫ 𝟙 (quotient.shift_functor h c) ≫\n (shift_μ h (a + b) c).hom ≫ eq_to_hom (by rw add_assoc) =\n (functor.associator _ _ _).hom ≫ 𝟙 (quotient.shift_functor h a) ◫ (shift_μ h b c).hom ≫\n (shift_μ h a (b + c)).hom :=\nquotient.nat_trans_ext _ _ (λ X, begin\n dsimp only [functor.associator, nat_trans.comp_app, nat_trans.hcomp_app,\n nat_trans.id_app, quotient.shift_functor],\n erw [id_comp, id_comp, shift_μ_hom_app, shift_μ_hom_app, shift_μ_hom_app,\n shift_μ_hom_app, assoc, functor.map_id, id_comp, lift_map_functor_map],\n dsimp only ,\n simp only [functor.comp_map, ← functor.map_comp, ← functor.map_comp_assoc,\n associativity_compatibility],\n simpa only [assoc, functor.map_comp, eq_to_hom_app, eq_to_hom_map, eq_to_hom_trans,\n eq_to_hom_refl, comp_id],\nend)\n\nlemma shift_left_unitality (a : A) :\n (shift_ε h).hom ◫ 𝟙 (quotient.shift_functor h a) ≫ (shift_μ h 0 a).hom =\n eq_to_hom (congr_arg (quotient.shift_functor h) (zero_add a).symm) :=\nquotient.nat_trans_ext _ _ (λ X, begin\n dsimp [shift_ε, shift_μ, comm_shift],\n simp only [comp_id, id_comp, eq_to_hom_app],\n erw [functor.map_id, id_comp, id_comp],\n dsimp [quotient.shift_functor, lift_map],\n erw [← functor_map_eq, ← functor_map_eq, ← functor.map_comp],\n transitivity (functor r).map (eq_to_hom _), swap,\n { rw zero_add, },\n { congr' 1,\n simp only [obj_ε_app, eq_to_iso.inv, assoc, μ_inv_hom_app],\n erw [comp_id, eq_to_hom_map, eq_to_hom_app], },\n { apply eq_to_hom_map, },\nend)\n\nlemma shift_right_unitality (a : A) :\n 𝟙 (quotient.shift_functor h a) ◫ (shift_ε h).hom ≫ (shift_μ h a 0).hom =\n eq_to_hom (congr_arg (quotient.shift_functor h) (add_zero a).symm) :=\nquotient.nat_trans_ext _ _ (λ X, begin\n dsimp only [shift_ε, shift_μ, iso.trans, nat_trans.hcomp, nat_trans.comp_app,\n quotient.shift_functor, comm_shift, lift.is_lift],\n simp only [iso.symm_inv, assoc, iso.symm_hom, iso_whisker_right_hom, lift_nat_iso_hom,\n nat_trans.id_app, lift_nat_trans_app, nat_trans.comp_app, whisker_right_app, functor.map_id,\n nat_iso.of_components_hom_app, iso.refl_hom, nat_iso.of_components_inv_app, iso.refl_inv],\n dsimp,\n simp only [id_comp, comp_id, eq_to_hom_app],\n erw [← functor_map_eq, ← functor_map_eq, ← functor.map_comp],\n transitivity (functor r).map (eq_to_hom _), swap,\n { rw add_zero, },\n { congr' 1,\n simp only [ε_app_obj, eq_to_iso.inv, assoc, μ_inv_hom_app, comp_id,\n eq_to_hom_map, eq_to_hom_app], },\n { apply eq_to_hom_map, },\nend)\n\n@[protected]\ndef shift : has_shift (quotient r) A :=\nhas_shift_mk _ _\n{ F := quotient.shift_functor h,\n ε := shift_ε h,\n μ := shift_μ h,\n associativity := λ a b c X, by simpa using congr_app (shift_associativity h a b c) X,\n left_unitality := λ a X, by simpa using congr_app (shift_left_unitality h a) X,\n right_unitality := λ a X, by simpa using congr_app (shift_right_unitality h a) X, }\n\ndef functor_comm_shift :\n @functor.has_comm_shift _ _ _ _ (functor r) A _ _\n (quotient.shift h) :=\n{ iso := quotient.comm_shift h,\n iso_add := λ a b, begin\n ext K,\n dsimp,\n simp only [functor.comm_shift.add_hom_app, comm_shift_hom_app, id_comp],\n erw [functor.map_id, id_comp, id_comp],\n change _ ≫ (shift_μ h a b).hom.app ((functor r).obj K) = _,\n erw [shift_μ_hom_app, ← functor.map_comp, iso.inv_hom_id_app, functor.map_id],\n end,\n iso_zero := begin\n ext K,\n simp only [nat_trans.comp_app, lift.is_lift_hom, nat_trans.id_app],\n dsimp only [functor.comm_shift.unit, shift.compatibility.comm_shift.unit,\n iso.trans, iso.symm, nat_trans.comp_app, iso_whisker_right, whiskering_right,\n functor.map_iso, whisker_right, iso_whisker_left, functor.left_unitor,\n functor.right_unitor, whiskering_left, whisker_left],\n erw [id_comp, id_comp, id_comp, shift_ε_hom_app, ← functor.map_comp,\n iso.inv_hom_id_app, functor.map_id],\n refl,\n end, }\n\nsection\n\nvariables\n {D : Type*} [category D]\n {F : C ⥤ D} {F' : quotient r ⥤ D} (e : functor r ⋙ F' ≅ F)\n {B : Type*} [add_monoid B] [has_shift C B] [has_shift D B]\n [has_shift (quotient r) B] [(functor r).has_comm_shift B]\n [F.has_comm_shift B]\n\ndef comm_shift_iso_of_fac (a : B) :\n shift_functor (quotient r) a ⋙ F' ≅ F' ⋙ shift_functor D a :=\nlift_nat_iso _ _ ((functor.associator _ _ _).symm ≪≫\n iso_whisker_right ((functor r).comm_shift_iso a).symm F' ≪≫\n functor.associator _ _ _ ≪≫ iso_whisker_left _ e ≪≫\n F.comm_shift_iso a ≪≫ iso_whisker_right e.symm _ ≪≫ functor.associator _ _ _)\n\n@[simp]\nlemma comm_shift_iso_of_fac_hom_app (a : B) (X : C) :\n (comm_shift_iso_of_fac e a).hom.app ((functor r).obj X) =\n F'.map (((functor r).comm_shift_iso a).inv.app X) ≫\n e.hom.app ((shift_functor C a).obj X) ≫\n (F.comm_shift_iso a).hom.app X ≫\n (shift_functor D a).map (e.inv.app X) :=\nbegin\n dsimp only [comm_shift_iso_of_fac],\n simp only [lift_nat_iso_hom, iso.trans_hom, iso.symm_hom, iso_whisker_right_hom,\n iso_whisker_left_hom, lift_nat_trans_app, nat_trans.comp_app,\n functor.associator_inv_app, whisker_right_app, functor.associator_hom_app,\n whisker_left_app, comp_id, id_comp],\nend\n\n@[simp]\nlemma comm_shift_iso_of_fac_inv_app (a : B) (X : C) :\n (comm_shift_iso_of_fac e a).inv.app ((functor r).obj X) =\n (shift_functor D a).map (e.hom.app X) ≫\n (F.comm_shift_iso a).inv.app X ≫\n e.inv.app ((shift_functor C a).obj X) ≫\n F'.map (((functor r).comm_shift_iso a).hom.app X) :=\nbegin\n dsimp only [comm_shift_iso_of_fac],\n simp only [lift_nat_iso_inv, iso.trans_inv, iso_whisker_right_inv, iso.symm_inv, assoc,\n iso_whisker_left_inv, lift_nat_trans_app, nat_trans.comp_app,\n functor.associator_inv_app, whisker_right_app, whisker_left_app,\n functor.associator_hom_app, comp_id, id_comp],\nend\n\nvariable (B)\n\ndef has_comm_shift : F'.has_comm_shift B :=\n{ iso := λ a, comm_shift_iso_of_fac e a,\n iso_zero := begin\n ext1,\n refine nat_trans_ext _ _ (λ X, _),\n simp only [comm_shift_iso_of_fac_hom_app, functor.comm_shift.unit_hom_app,\n functor.comm_shift_iso_zero, functor.comm_shift.unit_inv_app,\n F'.map_comp, assoc, ← e.hom.naturality_assoc, functor.comp_map],\n nth_rewrite 1 ← functor.map_comp_assoc,\n erw [← functor.map_comp, iso.inv_hom_id_app, (functor r).map_id, F'.map_id, id_comp,\n ← nat_trans.naturality],\n dsimp only [functor.id],\n rw e.hom_inv_id_app_assoc,\n end,\n iso_add := λ a b, begin\n ext1,\n refine nat_trans_ext _ _ (λ X, _),\n simp only [functor.comm_shift.add_hom_app, assoc, functor.comm_shift_iso_add,\n comm_shift_iso_of_fac_hom_app, functor.map_comp, functor.comm_shift.add_inv_app],\n erw [← nat_trans.naturality_assoc, ← nat_trans.naturality_assoc,\n comm_shift_iso_of_fac_hom_app, assoc, assoc, assoc],\n dsimp only [functor.comp_map],\n nth_rewrite 3 ← functor.map_comp_assoc,\n erw [← functor.map_comp, iso.inv_hom_id_app, (functor r).map_id, F'.map_id, id_comp],\n nth_rewrite 4 ← functor.map_comp_assoc,\n erw [e.inv_hom_id_app, functor.map_id, id_comp, (shift_functor_add D a b).inv.naturality],\n refl,\n end, }\n\ninstance lift_has_comm_shift\n (hF : ∀ (x y : C) (f₁ f₂ : x ⟶ y), r f₁ f₂ → F.map f₁ = F.map f₂) :\n (lift r F hF).has_comm_shift B :=\nhas_comm_shift (lift.is_lift r F hF) B\n\nend\n\nend quotient\n\nend category_theory\n", "meta": {"author": "joelriou", "repo": "homotopical_algebra", "sha": "697f49d6744b09c5ef463cfd3e35932bdf2c78a3", "save_path": "github-repos/lean/joelriou-homotopical_algebra", "path": "github-repos/lean/joelriou-homotopical_algebra/homotopical_algebra-697f49d6744b09c5ef463cfd3e35932bdf2c78a3/src/for_mathlib/category_theory/quotient_shift.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.034618842076191536, "lm_q1q2_score": 0.017038983342293347}} {"text": "import .arrow\nimport .cofibration_category\nimport tactic.slice\n\n/- Brown factorization, aka \"Ken Brown's lemma\", and a relative version.\n Following Rădulescu-Banu, Cofibrations in Homotopy Theory, section 1.3. -/\n \nuniverses v u\n\nnamespace homotopy_theory.cofibrations\nopen category_theory\nopen category_theory.category\nopen precofibration_category\nopen cofibration_category\nopen homotopy_theory.weak_equivalences\n\nvariables {C : Type u} [category.{v} C] [cofibration_category.{v} C]\n [has_initial_object.{v} C]\n\nstructure brown_factorization {a b : C} (f : a ⟶ b) : Type (max u v) :=\n-- ab represents a coproduct of a and b, used to formulate the condition on f' + s\n(ab : pushout (! a) (! b))\n(b' : C)\n(f' : a ⟶ b') (r : b' ⟶ b) (s : b ⟶ b')\n(hf' : is_cof f')\n(hf's : is_cof (ab.is_pushout.induced f' s (initial.uniqueness _ _)))\n(hs : is_acof s)\n(hf'r : f' ≫ r = f)\n(hsr : s ≫ r = 𝟙 b)\n\nlemma brown_factorization.hr {a b : C} {f : a ⟶ b} (c : brown_factorization f) :\n is_weq c.r :=\nbegin\n convert category_with_weak_equivalences.weq_of_comp_weq_left c.hs.2 _,\n rw c.hsr,\n apply weq_id\nend\n\nlemma brown_factorization.weq_f' {a b : C} {f : a ⟶ b} (c : brown_factorization f) (hf : is_weq f) :\n is_weq c.f' :=\nbegin\n convert category_with_weak_equivalences.weq_of_comp_weq_right c.hr _,\n rw c.hf'r,\n exact hf\nend\n\n--- Any map between cofibrant objects admits a Brown factorization (R-B, Lemma 1.3.1).\nlemma exists_brown_factorization {a b : C} (ha : cofibrant a) (hb : cofibrant b) (f : a ⟶ b) :\n nonempty (brown_factorization f) :=\nlet ab := pushout_by_cof (! a) (! b) ha,\n ⟨b', j, g, hj, hg, hf⟩ :=\n factorization (ab.is_pushout.induced f (𝟙 b) (initial.uniqueness _ _)) in\n⟨⟨ab, b', ab.map₀ ≫ j, g, ab.map₁ ≫ j,\n cof_comp (pushout_is_cof ab.is_pushout.transpose hb) hj,\n by convert hj; apply ab.is_pushout.uniqueness; simp,\n begin\n split,\n { refine cof_comp (pushout_is_cof ab.is_pushout ha) hj },\n { convert category_with_weak_equivalences.weq_of_comp_weq_right hg _,\n rw [assoc, hf], simpa using weq_id _ }\n end,\n by rw [assoc, hf]; simp,\n by rw [assoc, hf]; simp⟩⟩\n\n--- R-B, Lemma 1.3.3\nlemma relative_factorization {a₁ a₁' b₁ a₂ b₂ : C}\n (ha₁ : cofibrant a₁) (ha₂ : cofibrant a₂)\n (f₁' : a₁ ⟶ a₁') (r₁ : a₁' ⟶ b₁) (hf₁' : is_cof f₁') (hr : is_weq r₁)\n (f₂ : a₂ ⟶ b₂) (a : a₁ ⟶ a₂) (b : b₁ ⟶ b₂) (s : (f₁' ≫ r₁) ≫ b = a ≫ f₂) :\n ∃ a₂' (a' : a₁' ⟶ a₂') (f₂' : a₂ ⟶ a₂') (r₂ : a₂' ⟶ b₂)\n (hf' : f₁' ≫ a' = a ≫ f₂'), r₁ ≫ b = a' ≫ r₂ ∧ f₂' ≫ r₂ = f₂ ∧ is_cof f₂' ∧ is_weq r₂ ∧\n is_cof ((pushout_by_cof f₁' a hf₁').is_pushout.induced a' f₂' hf') :=\nlet po := pushout_by_cof f₁' a hf₁',\n g := po.is_pushout.induced (r₁ ≫ b) f₂ (by rw [←s, assoc]),\n ⟨a₂', s, r₂, hs, hr₂, hg⟩ := factorization g in\n⟨a₂', po.map₀ ≫ s, po.map₁ ≫ s, r₂,\n by rw [←assoc, ←assoc, po.is_pushout.commutes],\n by rw [assoc, hg]; simp,\n by simp [hg],\n cof_comp (pushout_is_cof po.is_pushout hf₁') hs,\n hr₂,\n by convert hs; apply po.is_pushout.uniqueness; simp⟩\n\n/-- R-B, Lemma 1.3.4. The statement there is missing hypotheses on the maps a and b,\n needed for the last two conclusions. -/\nlemma exists_relative_brown_factorization {a₁ b₁ a₂ b₂ : C}\n (ha₁ : cofibrant a₁) (hb₁ : cofibrant b₁) (ha₂ : cofibrant a₂) (hb₂ : cofibrant b₂)\n (f₁ : a₁ ⟶ b₁) (f₂ : a₂ ⟶ b₂) (a : a₁ ⟶ a₂) (b : b₁ ⟶ b₂) (S : f₁ ≫ b = a ≫ f₂)\n (c₁ : brown_factorization f₁) : ∃ (c₂ : brown_factorization f₂) (b' : c₁.b' ⟶ c₂.b')\n (hf' : c₁.f' ≫ b' = a ≫ c₂.f') (hr : c₁.r ≫ b = b' ≫ c₂.r) (hs : c₁.s ≫ b' = b ≫ c₂.s),\n (is_cof b → is_cof ((pushout_by_cof c₁.f' a c₁.hf').is_pushout.induced b' c₂.f' hf')) ∧\n (is_cof a → is_acof ((pushout_by_cof c₁.s b c₁.hs.1).is_pushout.induced b' c₂.s hs)) :=\nlet po_a := pushout_by_cof c₁.f' a c₁.hf',\n a₃ := po_a.ob,\n f' := po_a.map₁,\n cof_f' : is_cof f' := pushout_is_cof po_a.is_pushout c₁.hf',\n po_b := pushout_by_cof c₁.s b c₁.hs.1,\n b₃ := po_b.ob,\n s := po_b.map₁,\n acof_s : is_acof s := pushout_is_acof po_b.is_pushout c₁.hs,\n r := po_b.is_pushout.induced (c₁.r ≫ b) (𝟙 _) (by rw [←assoc, c₁.hsr]; simp),\n f₃ : a₃ ⟶ b₃ := po_a.is_pushout.induced (c₁.r ≫ b ≫ s) (f₂ ≫ s) begin\n conv { to_rhs, rw [←assoc, ←S], rw [←c₁.hf'r, assoc] }, simp\n end,\n a₂b₂ := pushout_by_cof (! a₂) (! b₂) ha₂,\n -- TODO: lemma here?\n cof_a₃ : cofibrant a₃ := begin\n change is_cof _,\n convert cof_comp ha₂ (pushout_is_cof po_a.is_pushout c₁.hf'),\n apply initial.uniqueness\n end,\n cof_b₃ : cofibrant b₃ := begin\n change is_cof _,\n convert cof_comp hb₂ (pushout_is_cof po_b.is_pushout c₁.hs.1),\n apply initial.uniqueness\n end,\n a₃b₃ := pushout_by_cof (! a₃) (! b₃) cof_a₃,\n a₁_b₁ := c₁.ab.ob,\n cof_a₁_b₁ : cofibrant a₁_b₁ := begin\n change is_cof _,\n convert cof_comp hb₁ (pushout_is_cof c₁.ab.is_pushout ha₁),\n apply initial.uniqueness\n end,\n a₃_b₃ := a₃b₃.ob,\n cof_a₃_b₃ : cofibrant a₃_b₃ := begin\n change is_cof _,\n convert cof_comp cof_b₃ (pushout_is_cof a₃b₃.is_pushout cof_a₃),\n apply initial.uniqueness\n end,\n ⟨b₂', b', fs₃', r₃, hfs₃', hr₃, hf'sr, cof_fs₃', weq_r₃, cof_p⟩ := begin\n refine relative_factorization cof_a₁_b₁ cof_a₃_b₃ _ c₁.r c₁.hf's c₁.hr\n (a₃b₃.is_pushout.induced f₃ (𝟙 b₃) (initial.uniqueness _ _))\n (pushout_of_maps c₁.ab.is_pushout a₃b₃.is_pushout (𝟙 _) (a ≫ f') (b ≫ s)\n (initial.uniqueness _ _) (initial.uniqueness _ _))\n (b ≫ s) _,\n apply c₁.ab.is_pushout.uniqueness,\n { slice_lhs 1 2 { simp }, conv { to_lhs, rw [c₁.hf'r, S, assoc] },\n rw induced_pushout_of_maps, simp },\n { slice_lhs 1 2 { simp }, conv { to_lhs, rw [c₁.hsr, id_comp] },\n rw induced_pushout_of_maps, simp }\n end,\n f₃' := a₃b₃.map₀ ≫ fs₃',\n s₃ := a₃b₃.map₁ ≫ fs₃',\n f₂' := f' ≫ f₃',\n r₂ := r₃ ≫ r,\n s₂ := s ≫ s₃ in\nhave sr : s ≫ r = 𝟙 _, by simp,\nhave s₂r₂ : s₂ ≫ r₂ = 𝟙 _, begin\n slice_lhs 3 4 { rw hf'sr },\n slice_lhs 2 3 { rw Is_pushout.induced_commutes₁ },\n simp\nend,\nhave weq_r₂ : is_weq r₂, begin\n refine weq_comp weq_r₃ _,\n rw ←weq_iff_weq_inv sr,\n exact acof_s.2\nend,\n⟨⟨a₂b₂, b₂', f₂', r₂, s₂,\n cof_comp (pushout_is_cof po_a.is_pushout c₁.hf')\n (cof_comp (pushout_is_cof a₃b₃.is_pushout.transpose cof_b₃) cof_fs₃'),\n begin\n have := cof_pushout cof_f' acof_s.1 a₂b₂.is_pushout\n (by convert a₃b₃.is_pushout; apply initial.uniqueness) (by apply initial.uniqueness),\n convert cof_comp this cof_fs₃',\n apply a₂b₂.is_pushout.uniqueness; conv { to_rhs, rw ←assoc }; simp\n end,\n begin\n refine ⟨_, (weq_iff_weq_inv s₂r₂).mpr weq_r₂⟩,\n exact cof_comp acof_s.1 (cof_comp (pushout_is_cof a₃b₃.is_pushout cof_a₃) cof_fs₃')\n end,\n begin\n slice_lhs 3 4 { rw hf'sr },\n slice_lhs 2 3 { rw Is_pushout.induced_commutes₀ },\n slice_lhs 1 2 { rw Is_pushout.induced_commutes₁ },\n simp [sr]\n end,\n s₂r₂⟩,\n b',\n begin\n convert congr_arg (λ z, c₁.ab.map₀ ≫ z) hfs₃' using 1,\n { slice_rhs 1 2 { rw Is_pushout.induced_commutes₀ } },\n { slice_rhs 1 2 { dsimp [pushout_of_maps], rw Is_pushout.induced_commutes₀ }, simp }\n end,\n begin\n have : c₁.r ≫ b = c₁.r ≫ b ≫ (s ≫ r), by rw [sr]; simp,\n rw this,\n slice_lhs 1 3 { rw hr₃ },\n simp\n end,\n begin\n convert congr_arg (λ z, c₁.ab.map₁ ≫ z) hfs₃' using 1,\n { slice_rhs 1 2 { rw Is_pushout.induced_commutes₁ } },\n { slice_rhs 1 2 { dsimp [pushout_of_maps], rw Is_pushout.induced_commutes₁ }, simp }\n end,\n begin\n intro hb,\n let v := _,\n let S₂ : cof_square v b' := ⟨_, _, _, _, cof_p⟩,\n let S₁ : cof_square a v,\n { refine ⟨c₁.ab.map₀, f' ≫ a₃b₃.map₀,\n by simp [v, pushout_of_maps], pushout_is_cof c₁.ab.is_pushout.transpose hb₁, _⟩,\n let po : pushout _ _ := _,\n change is_cof (po.is_pushout.induced _ _ _),\n have : is_cof (b ≫ s) := cof_comp hb acof_s.1,\n convert cof_pushout this cof_f'\n (Is_pushout_of_Is_pushout_of_Is_pushout c₁.ab.is_pushout.transpose po.is_pushout)\n (by convert a₃b₃.is_pushout.transpose; apply initial.uniqueness)\n (by apply initial.uniqueness) using 1,\n symmetry,\n apply pushout_induced_eq_iff; simp },\n have : c₁.f' = S₁.f₁ ≫ S₂.f₁, by simp,\n have S : is_cof_square a b' c₁.f' _ :=\n is_cof_square_comp ⟨S₁, rfl, rfl⟩ ⟨S₂, rfl, rfl⟩ this rfl,\n convert S.corner_cof.snd.snd,\n simp\n end,\n begin\n intro ha,\n let G := _,\n change is_acof G,\n suffices : is_cof G,\n { refine ⟨this, _⟩,\n have sG : s ≫ G = s₂, by simp,\n have : is_acof s := pushout_is_acof po_b.is_pushout c₁.hs,\n refine category_with_weak_equivalences.weq_of_comp_weq_left this.2 _,\n rw sG,\n exact (weq_iff_weq_inv s₂r₂).mpr weq_r₂ },\n -- From here on, the proof resembles the previous one\n let v := _,\n let S₂ : cof_square v b' := ⟨_, _, _, _, cof_p⟩,\n let S₁ : cof_square b v,\n { refine ⟨c₁.ab.map₁, s ≫ a₃b₃.map₁,\n by simp [v, pushout_of_maps], pushout_is_cof c₁.ab.is_pushout ha₁, _⟩,\n let po : pushout _ _ := _,\n change is_cof (po.is_pushout.induced _ _ _),\n have : is_cof (a ≫ f') := cof_comp ha cof_f',\n convert cof_pushout this acof_s.1\n (Is_pushout_of_Is_pushout_of_Is_pushout c₁.ab.is_pushout po.is_pushout)\n (by convert a₃b₃.is_pushout; apply initial.uniqueness)\n (by apply initial.uniqueness) using 1,\n symmetry,\n apply pushout_induced_eq_iff; simp },\n have : c₁.s = S₁.f₁ ≫ S₂.f₁, by simp,\n have S : is_cof_square b b' c₁.s _ :=\n is_cof_square_comp ⟨S₁, rfl, rfl⟩ ⟨S₂, rfl, rfl⟩ this rfl,\n convert S.corner_cof.snd.snd,\n simp\n end⟩\n\nend homotopy_theory.cofibrations\n", "meta": {"author": "rwbarton", "repo": "lean-homotopy-theory", "sha": "39e1b4ea1ed1b0eca2f68bc64162dde6a6396dee", "save_path": "github-repos/lean/rwbarton-lean-homotopy-theory", "path": "github-repos/lean/rwbarton-lean-homotopy-theory/lean-homotopy-theory-39e1b4ea1ed1b0eca2f68bc64162dde6a6396dee/src/homotopy_theory/formal/cofibrations/brown.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438006939036565, "lm_q2_score": 0.03514484261109071, "lm_q1q2_score": 0.017023461302673598}} {"text": "-- Copyright (c) 2017 Scott Morrison. All rights reserved.\n-- Released under Apache 2.0 license as described in the file LICENSE.\n-- Authors: Stephen Morgan, Scott Morrison\nimport category_theory.tactics.obviously\nimport category_theory.equivalence\n\nnamespace category_theory\n\nuniverses v₁ v₂ u₁ u₂\n\nstructure idempotent (C : Sort u₁) [category.{v₁+1} C] :=\n(X : C)\n(idem : X ⟶ X)\n(w' : idem ≫ idem = idem . obviously)\n\nrestate_axiom idempotent.w'\nattribute [simp] idempotent.w -- search\n\nvariables {C : Sort u₁} [𝒞 : category.{v₁+1} C]\ninclude 𝒞\n\nnamespace idempotent\n\nstructure morphism (P Q : idempotent.{v₁} C) :=\n(hom : P.X ⟶ Q.X)\n(left' : P.idem ≫ hom = hom . obviously)\n(right' : hom ≫ Q.idem = hom . obviously)\n\nrestate_axiom morphism.left'\nrestate_axiom morphism.right'\nattribute [simp] morphism.left morphism.right -- search\n\n@[extensionality] lemma ext {P Q : idempotent C} (f g : morphism P Q) (w : f.hom = g.hom) : f = g :=\nbegin\n induction f,\n induction g,\n tidy\nend\n\nend idempotent\n\ninstance idempotent_completion : category.{v₁+1} (idempotent C) :=\n{ hom := idempotent.morphism,\n id := λ P, ⟨ P.idem ⟩,\n comp := λ _ _ _ f g,\n { hom := f.hom ≫ g.hom,\n left' := by rw [←category.assoc, idempotent.morphism.left],\n right' := by rw [category.assoc, idempotent.morphism.right] } }\n\nnamespace idempotent_completion\n\n@[simp] lemma id_hom (P : idempotent C) : ((𝟙 P) : idempotent.morphism P P).hom = P.idem := rfl\n@[simp] lemma comp_hom {P Q R : idempotent C} (f : P ⟶ Q) (g : Q ⟶ R) : (f ≫ g).hom = f.hom ≫ g.hom := rfl\n\ndef to_completion (C : Type u₁) [𝒞 : category.{v₁+1} C] : C ⥤ (idempotent.{v₁} C) :=\n{ obj := λ P, { X := P, idem := 𝟙 P },\n map := λ _ _ f, { hom := f } }\n\n@[simp] private lemma double_idempotent_morphism_left (P Q : idempotent (idempotent C)) (f : P ⟶ Q)\n : (P.idem).hom ≫ (f.hom).hom = (f.hom).hom := congr_arg idempotent.morphism.hom f.left\n@[simp] private lemma double_idempotent_morphism_right (P Q : idempotent (idempotent C)) (f : P ⟶ Q)\n : (f.hom).hom ≫ (Q.idem).hom = (f.hom).hom := congr_arg idempotent.morphism.hom f.right\n\n@[simp] private def idempotent_functor : (idempotent (idempotent C)) ⥤ (idempotent C) :=\n{ obj := λ P, ⟨ P.X.X, P.idem.hom, congr_arg idempotent.morphism.hom P.w ⟩,\n map := λ _ _ f, ⟨ f.hom.hom, by obviously ⟩ }.\n@[simp] private def idempotent_inverse : (idempotent C) ⥤ (idempotent (idempotent C)) :=\n{ obj := λ P, ⟨ P, ⟨ P.idem, by obviously ⟩, by obviously ⟩,\n map := λ _ _ f, ⟨ f, by obviously ⟩ }.\n\n@[simp] lemma idem_hom_idempotent (X : idempotent (idempotent C)) : X.idem.hom ≫ X.idem.hom = X.idem.hom :=\nbegin\n rw ←comp_hom,\n simp,\nend\n\nlemma idempotent_idempotent :\n equivalence (idempotent (idempotent C)) (idempotent C) :=\nequivalence.mk idempotent_functor idempotent_inverse\n { hom := { app := λ X, { hom := { hom := X.idem.hom } } },\n inv := { app := λ X, { hom := { hom := X.idem.hom } } } }\n { hom := { app := λ X, { hom := X.idem } },\n inv := { app := λ X, { hom := X.idem } } }\n\nvariable {D : Type u₂}\nvariable [𝒟 : category.{v₂+1} D]\ninclude 𝒟\n\nattribute [search] idempotent.w idempotent.morphism.left idempotent.morphism.right\n idem_hom_idempotent comp_hom id_hom\n\ndef extend_to_completion (F : C ⥤ (idempotent D)) : (idempotent C) ⥤ (idempotent D) :=\n{ obj := λ P,\n { X := (F.obj P.X).X,\n idem := (F.map P.idem).hom,\n w' := begin rw [←comp_hom, ←functor.map_comp, idempotent.w], end },\n map := λ X Y f, { hom := (F.map f.hom).hom } }\n\nend idempotent_completion\nend category_theory\n", "meta": {"author": "semorrison", "repo": "lean-category-theory", "sha": "a27b4ae5eac978e9188d2e867c3d11d9a5b87a9e", "save_path": "github-repos/lean/semorrison-lean-category-theory", "path": "github-repos/lean/semorrison-lean-category-theory/lean-category-theory-a27b4ae5eac978e9188d2e867c3d11d9a5b87a9e/src/category_theory/idempotent_completion.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47657965106367595, "lm_q2_score": 0.035678553056634484, "lm_q1q2_score": 0.01700367236618771}} {"text": "/-\nCopyright (c) 2021 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Leonardo de Moura\n-/\nimport Lean.Meta.AppBuilder\n\nnamespace Lean.Meta\n\ninductive CongrArgKind where\n | /-- It is a parameter for the congruence theorem, the parameter occurs in the left and right hand sides. -/\n fixed\n | /--\n It is not a parameter for the congruence theorem, the lemma was specialized for this parameter.\n This only happens if the parameter is a subsingleton/proposition, and other parameters depend on it. -/\n fixedNoParam\n | /--\n The lemma contains three parameters for this kind of argument `a_i`, `b_i` and `eq_i : a_i = b_i`.\n `a_i` and `b_i` represent the left and right hand sides, and `eq_i` is a proof for their equality. -/\n eq\n | /--\n The congr-simp theorems contains only one parameter for this kind of argument, and congr theorems contains two.\n They correspond to arguments that are subsingletons/propositions. -/\n cast\n | /--\n The lemma contains three parameters for this kind of argument `a_i`, `b_i` and `eq_i : HEq a_i b_i`.\n `a_i` and `b_i` represent the left and right hand sides, and `eq_i` is a proof for their heterogeneous equality. -/\n heq\n\nstructure CongrTheorem where\n type : Expr\n proof : Expr\n argKinds : Array CongrArgKind\n\nprivate def addPrimeToFVarUserNames (ys : Array Expr) (lctx : LocalContext) : LocalContext := do\n let mut lctx := lctx\n for y in ys do\n let decl := lctx.getFVar! y\n lctx := lctx.setUserName decl.fvarId (decl.userName.appendAfter \"'\")\n return lctx\n\nprivate def setBinderInfosD (ys : Array Expr) (lctx : LocalContext) : LocalContext := do\n let mut lctx := lctx\n for y in ys do\n let decl := lctx.getFVar! y\n lctx := lctx.setBinderInfo decl.fvarId BinderInfo.default\n return lctx\n\npartial def mkHCongrWithArity (f : Expr) (numArgs : Nat) : MetaM CongrTheorem := do\n let fType ← inferType f\n forallBoundedTelescope fType numArgs fun xs xType =>\n forallBoundedTelescope fType numArgs fun ys yType => do\n if xs.size != numArgs then\n throwError \"failed to generate hcongr theorem, insufficient number of arguments\"\n else\n let lctx := addPrimeToFVarUserNames ys (← getLCtx) |> setBinderInfosD ys |> setBinderInfosD xs\n withLCtx lctx (← getLocalInstances) do\n withNewEqs xs ys fun eqs argKinds => do\n let mut hs := #[]\n for x in xs, y in ys, eq in eqs do\n hs := hs.push x |>.push y |>.push eq\n let xType := xType.consumeAutoOptParam\n let yType := yType.consumeAutoOptParam\n let resultType ← if xType == yType then mkEq xType yType else mkHEq xType yType\n let congrType ← mkForallFVars hs resultType\n return {\n type := congrType\n proof := (← mkProof congrType)\n argKinds\n }\nwhere\n withNewEqs {α} (xs ys : Array Expr) (k : Array Expr → Array CongrArgKind → MetaM α) : MetaM α :=\n let rec loop (i : Nat) (eqs : Array Expr) (kinds : Array CongrArgKind) := do\n if i < xs.size then\n let x := xs[i]\n let y := ys[i]\n let xType := (← inferType x).consumeAutoOptParam\n let yType := (← inferType y).consumeAutoOptParam\n if xType == yType then\n withLocalDeclD ((`e).appendIndexAfter (i+1)) (← mkEq x y) fun h =>\n loop (i+1) (eqs.push h) (kinds.push CongrArgKind.eq)\n else\n withLocalDeclD ((`e).appendIndexAfter (i+1)) (← mkHEq x y) fun h =>\n loop (i+1) (eqs.push h) (kinds.push CongrArgKind.heq)\n else\n k eqs kinds\n loop 0 #[] #[]\n\n mkProof (type : Expr) : MetaM Expr := do\n if let some (_, lhs, _) := type.eq? then\n mkEqRefl lhs\n else if let some (_, lhs, _, _) := type.heq? then\n mkHEqRefl lhs\n else\n forallBoundedTelescope type (some 1) fun a type =>\n let a := a[0]\n forallBoundedTelescope type (some 1) fun b motive =>\n let b := b[0]\n let type := type.bindingBody!.instantiate1 a\n withLocalDeclD motive.bindingName! motive.bindingDomain! fun eqPr => do\n let type := type.bindingBody!\n let motive := motive.bindingBody!\n let minor ← mkProof type\n let mut major := eqPr\n if (← whnf (← inferType eqPr)).isHEq then\n major ← mkEqOfHEq major\n let motive ← mkLambdaFVars #[b] motive\n mkLambdaFVars #[a, b, eqPr] (← mkEqNDRec motive minor major)\n\ndef mkHCongr (f : Expr) : MetaM CongrTheorem := do\n mkHCongrWithArity f (← getFunInfo f).getArity\n\nend Lean.Meta\n", "meta": {"author": "subfish-zhou", "repo": "leanprover-zh_CN.github.io", "sha": "8b2985d4a3d458ceda9361ac454c28168d920d3f", "save_path": "github-repos/lean/subfish-zhou-leanprover-zh_CN.github.io", "path": "github-repos/lean/subfish-zhou-leanprover-zh_CN.github.io/leanprover-zh_CN.github.io-8b2985d4a3d458ceda9361ac454c28168d920d3f/stage0/src/Lean/Meta/CongrTheorems.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4765796361952087, "lm_q2_score": 0.0356785472889478, "lm_q1q2_score": 0.017003669086940294}} {"text": "/-\nCopyright (c) 2022 Andrew Yang. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Andrew Yang\n-/\nimport ring_theory.ideal.cotangent\nimport ring_theory.dedekind_domain.basic\nimport ring_theory.valuation.valuation_ring\nimport ring_theory.nakayama\n/-!\n\n# Equivalent conditions for DVR\n\nIn `discrete_valuation_ring.tfae`, we show that the following are equivalent for a\nnoetherian local domain `(R, m, k)`:\n- `R` is a discrete valuation ring\n- `R` is a valuation ring\n- `R` is a dedekind domain\n- `R` is integrally closed with a unique prime ideal\n- `m` is principal\n- `dimₖ m/m² = 1`\n- Every nonzero ideal is a power of `m`.\n\n-/\n\n\nvariables (R : Type*) [comm_ring R] (K : Type*) [field K] [algebra R K] [is_fraction_ring R K]\n\nopen_locale discrete_valuation\nopen local_ring\n\nopen_locale big_operators\n\nlemma exists_maximal_ideal_pow_eq_of_principal [is_noetherian_ring R] [local_ring R] [is_domain R]\n (h : ¬ is_field R) (h' : (maximal_ideal R).is_principal) (I : ideal R) (hI : I ≠ ⊥) :\n ∃ n : ℕ, I = (maximal_ideal R) ^ n :=\nbegin\n classical,\n unfreezingI { obtain ⟨x, hx : _ = ideal.span _⟩ := h' },\n by_cases hI' : I = ⊤, { use 0, rw [pow_zero, hI', ideal.one_eq_top] },\n have H : ∀ r : R, ¬ (is_unit r) ↔ x ∣ r :=\n λ r, (set_like.ext_iff.mp hx r).trans ideal.mem_span_singleton,\n have : x ≠ 0,\n { rintro rfl,\n apply ring.ne_bot_of_is_maximal_of_not_is_field (maximal_ideal.is_maximal R) h,\n simp [hx] },\n have hx' := discrete_valuation_ring.irreducible_of_span_eq_maximal_ideal x this hx,\n have H' : ∀ r : R, r ≠ 0 → r ∈ nonunits R → ∃ (n : ℕ), associated (x ^ n) r,\n { intros r hr₁ hr₂,\n obtain ⟨f, hf₁, rfl, hf₂⟩ := (wf_dvd_monoid.not_unit_iff_exists_factors_eq r hr₁).mp hr₂,\n have : ∀ b ∈ f, associated x b,\n { intros b hb,\n exact irreducible.associated_of_dvd hx' (hf₁ b hb) ((H b).mp (hf₁ b hb).1) },\n clear hr₁ hr₂ hf₁,\n induction f using multiset.induction with fa fs fh,\n { exact (hf₂ rfl).elim },\n rcases eq_or_ne fs ∅ with rfl|hf',\n { use 1,\n rw [pow_one, multiset.prod_cons, multiset.empty_eq_zero, multiset.prod_zero, mul_one],\n exact this _ (multiset.mem_cons_self _ _) },\n { obtain ⟨n, hn⟩ := fh hf' (λ b hb, this _ (multiset.mem_cons_of_mem hb)),\n use n + 1,\n rw [pow_add, multiset.prod_cons, mul_comm, pow_one],\n exact associated.mul_mul (this _ (multiset.mem_cons_self _ _)) hn } },\n have : ∃ n : ℕ, x ^ n ∈ I,\n { obtain ⟨r, hr₁, hr₂⟩ : ∃ r : R, r ∈ I ∧ r ≠ 0,\n { by_contra h, push_neg at h, apply hI, rw eq_bot_iff, exact h },\n obtain ⟨n, u, rfl⟩ := H' r hr₂ (le_maximal_ideal hI' hr₁),\n use n,\n rwa [← I.unit_mul_mem_iff_mem u.is_unit, mul_comm] },\n use nat.find this,\n apply le_antisymm,\n { change ∀ s ∈ I, s ∈ _,\n by_contra hI'',\n push_neg at hI'',\n obtain ⟨s, hs₁, hs₂⟩ := hI'',\n apply hs₂,\n by_cases hs₃ : s = 0, { rw hs₃, exact zero_mem _ },\n obtain ⟨n, u, rfl⟩ := H' s hs₃ (le_maximal_ideal hI' hs₁),\n rw [mul_comm, ideal.unit_mul_mem_iff_mem _ u.is_unit] at ⊢ hs₁,\n apply ideal.pow_le_pow (nat.find_min' this hs₁),\n apply ideal.pow_mem_pow,\n exact (H _).mpr (dvd_refl _) },\n { rw [hx, ideal.span_singleton_pow, ideal.span_le, set.singleton_subset_iff],\n exact nat.find_spec this }\nend\n\nlemma maximal_ideal_is_principal_of_is_dedekind_domain\n [local_ring R] [is_domain R] [is_dedekind_domain R] : (maximal_ideal R).is_principal :=\nbegin\n classical,\n by_cases ne_bot : maximal_ideal R = ⊥,\n { rw ne_bot, apply_instance },\n obtain ⟨a, ha₁, ha₂⟩ : ∃ a ∈ maximal_ideal R, a ≠ (0 : R),\n { by_contra h', push_neg at h', apply ne_bot, rwa eq_bot_iff },\n have hle : ideal.span {a} ≤ maximal_ideal R,\n { rwa [ideal.span_le, set.singleton_subset_iff] },\n have : (ideal.span {a}).radical = maximal_ideal R,\n { rw ideal.radical_eq_Inf,\n apply le_antisymm,\n { exact Inf_le ⟨hle, infer_instance⟩ },\n { refine le_Inf (λ I hI, (eq_maximal_ideal $\n is_dedekind_domain.dimension_le_one _ (λ e, ha₂ _) hI.2).ge),\n rw [← ideal.span_singleton_eq_bot, eq_bot_iff, ← e], exact hI.1 } },\n have : ∃ n, maximal_ideal R ^ n ≤ ideal.span {a},\n { rw ← this, apply ideal.exists_radical_pow_le_of_fg, exact is_noetherian.noetherian _ },\n cases hn : nat.find this,\n { have := nat.find_spec this,\n rw [hn, pow_zero, ideal.one_eq_top] at this,\n exact (ideal.is_maximal.ne_top infer_instance (eq_top_iff.mpr $ this.trans hle)).elim },\n obtain ⟨b, hb₁, hb₂⟩ : ∃ b ∈ maximal_ideal R ^ n, ¬ b ∈ ideal.span {a},\n { by_contra h', push_neg at h', rw nat.find_eq_iff at hn,\n exact hn.2 n n.lt_succ_self (λ x hx, not_not.mp (h' x hx)) },\n have hb₃ : ∀ m ∈ maximal_ideal R, ∃ k : R, k * a = b * m,\n { intros m hm, rw ← ideal.mem_span_singleton', apply nat.find_spec this,\n rw [hn, pow_succ'], exact ideal.mul_mem_mul hb₁ hm },\n have hb₄ : b ≠ 0,\n { rintro rfl, apply hb₂, exact zero_mem _ },\n let K := fraction_ring R,\n let x : K := algebra_map R K b / algebra_map R K a,\n let M := submodule.map (algebra.of_id R K).to_linear_map (maximal_ideal R),\n have ha₃ : algebra_map R K a ≠ 0 := is_fraction_ring.to_map_eq_zero_iff.not.mpr ha₂,\n by_cases hx : ∀ y ∈ M, x * y ∈ M,\n { have := is_integral_of_smul_mem_submodule M _ _ x hx,\n { obtain ⟨y, e⟩ := is_integrally_closed.algebra_map_eq_of_integral this,\n refine (hb₂ (ideal.mem_span_singleton'.mpr ⟨y, _⟩)).elim,\n apply is_fraction_ring.injective R K,\n rw [map_mul, e, div_mul_cancel _ ha₃] },\n { rw submodule.ne_bot_iff, refine ⟨_, ⟨a, ha₁, rfl⟩, _⟩,\n exact is_fraction_ring.to_map_eq_zero_iff.not.mpr ha₂ },\n { apply submodule.fg.map, exact is_noetherian.noetherian _ } },\n { have : (M.map (distrib_mul_action.to_linear_map R K x)).comap\n (algebra.of_id R K).to_linear_map = ⊤,\n { by_contra h, apply hx,\n rintros m' ⟨m, hm, (rfl : algebra_map R K m = m')⟩,\n obtain ⟨k, hk⟩ := hb₃ m hm,\n have hk' : x * algebra_map R K m = algebra_map R K k,\n { rw [← mul_div_right_comm, ← map_mul, ← hk, map_mul, mul_div_cancel _ ha₃] },\n exact ⟨k, le_maximal_ideal h ⟨_, ⟨_, hm, rfl⟩, hk'⟩, hk'.symm⟩ },\n obtain ⟨y, hy₁, hy₂⟩ : ∃ y ∈ maximal_ideal R, b * y = a,\n { rw [ideal.eq_top_iff_one, submodule.mem_comap] at this,\n obtain ⟨_, ⟨y, hy, rfl⟩, hy' : x * algebra_map R K y = algebra_map R K 1⟩ := this,\n rw [map_one, ← mul_div_right_comm, div_eq_one_iff_eq ha₃, ← map_mul] at hy',\n exact ⟨y, hy, is_fraction_ring.injective R K hy'⟩ },\n refine ⟨⟨y, _⟩⟩,\n apply le_antisymm,\n { intros m hm, obtain ⟨k, hk⟩ := hb₃ m hm, rw [← hy₂, mul_comm, mul_assoc] at hk,\n rw [← mul_left_cancel₀ hb₄ hk, mul_comm], exact ideal.mem_span_singleton'.mpr ⟨_, rfl⟩ },\n { rwa [submodule.span_le, set.singleton_subset_iff] } }\nend\n\nlemma discrete_valuation_ring.tfae [is_noetherian_ring R] [local_ring R] [is_domain R]\n (h : ¬ is_field R) :\n tfae [discrete_valuation_ring R,\n valuation_ring R,\n is_dedekind_domain R,\n is_integrally_closed R ∧ ∃! P : ideal R, P ≠ ⊥ ∧ P.is_prime,\n (maximal_ideal R).is_principal,\n finite_dimensional.finrank (residue_field R) (cotangent_space R) = 1,\n ∀ I ≠ ⊥, ∃ n : ℕ, I = (maximal_ideal R) ^ n] :=\nbegin\n have ne_bot := ring.ne_bot_of_is_maximal_of_not_is_field (maximal_ideal.is_maximal R) h,\n classical,\n rw finrank_eq_one_iff',\n tfae_have : 1 → 2,\n { introI _, apply_instance },\n tfae_have : 2 → 1,\n { introI _,\n haveI := is_bezout.to_gcd_domain R,\n haveI : unique_factorization_monoid R := ufm_of_gcd_of_wf_dvd_monoid,\n apply discrete_valuation_ring.of_ufd_of_unique_irreducible,\n { obtain ⟨x, hx₁, hx₂⟩ := ring.exists_not_is_unit_of_not_is_field h,\n obtain ⟨p, hp₁, hp₂⟩ := wf_dvd_monoid.exists_irreducible_factor hx₂ hx₁,\n exact ⟨p, hp₁⟩ },\n { exact valuation_ring.unique_irreducible } },\n tfae_have : 1 → 4,\n { introI H,\n exact ⟨infer_instance, ((discrete_valuation_ring.iff_pid_with_one_nonzero_prime R).mp H).2⟩ },\n tfae_have : 4 → 3,\n { rintros ⟨h₁, h₂⟩, exact ⟨infer_instance, λ I hI hI', unique_of_exists_unique h₂\n ⟨ne_bot, infer_instance⟩ ⟨hI, hI'⟩ ▸ maximal_ideal.is_maximal R, h₁⟩ },\n tfae_have : 3 → 5,\n { introI h, exact maximal_ideal_is_principal_of_is_dedekind_domain R },\n tfae_have : 5 → 6,\n { rintro ⟨x, hx⟩,\n have : x ∈ maximal_ideal R := by { rw hx, exact submodule.subset_span (set.mem_singleton x) },\n let x' : maximal_ideal R := ⟨x, this⟩,\n use submodule.quotient.mk x',\n split,\n { intro e,\n rw submodule.quotient.mk_eq_zero at e,\n apply ring.ne_bot_of_is_maximal_of_not_is_field (maximal_ideal.is_maximal R) h,\n apply submodule.eq_bot_of_le_smul_of_le_jacobson_bot (maximal_ideal R),\n { exact ⟨{x}, (finset.coe_singleton x).symm ▸ hx.symm⟩ },\n { conv_lhs { rw hx },\n rw submodule.mem_smul_top_iff at e,\n rwa [submodule.span_le, set.singleton_subset_iff] },\n { rw local_ring.jacobson_eq_maximal_ideal (⊥ : ideal R) bot_ne_top, exact le_refl _ } },\n { refine λ w, quotient.induction_on' w $ λ y, _,\n obtain ⟨y, hy⟩ := y,\n rw [hx, submodule.mem_span_singleton] at hy,\n obtain ⟨a, rfl⟩ := hy,\n exact ⟨ideal.quotient.mk _ a, rfl⟩ } },\n tfae_have : 6 → 5,\n { rintro ⟨x, hx, hx'⟩,\n induction x using quotient.induction_on',\n use x,\n apply le_antisymm,\n swap, { rw [submodule.span_le, set.singleton_subset_iff], exact x.prop },\n have h₁ : (ideal.span {x} : ideal R) ⊔ maximal_ideal R ≤\n ideal.span {x} ⊔ (maximal_ideal R) • (maximal_ideal R),\n { refine sup_le le_sup_left _,\n rintros m hm,\n obtain ⟨c, hc⟩ := hx' (submodule.quotient.mk ⟨m, hm⟩),\n induction c using quotient.induction_on',\n rw ← sub_sub_cancel (c * x) m,\n apply sub_mem _ _,\n { apply_instance },\n { refine ideal.mem_sup_left (ideal.mem_span_singleton'.mpr ⟨c, rfl⟩) },\n { have := (submodule.quotient.eq _).mp hc,\n rw [submodule.mem_smul_top_iff] at this,\n exact ideal.mem_sup_right this } },\n have h₂ : maximal_ideal R ≤ (⊥ : ideal R).jacobson,\n { rw local_ring.jacobson_eq_maximal_ideal, exacts [le_refl _, bot_ne_top] },\n have := submodule.smul_sup_eq_smul_sup_of_le_smul_of_le_jacobson\n (is_noetherian.noetherian _) h₂ h₁,\n rw [submodule.bot_smul, sup_bot_eq] at this,\n rw [← sup_eq_left, eq_comm],\n exact le_sup_left.antisymm (h₁.trans $ le_of_eq this) },\n tfae_have : 5 → 7,\n { exact exists_maximal_ideal_pow_eq_of_principal R h },\n tfae_have : 7 → 2,\n { rw valuation_ring.iff_ideal_total,\n intro H,\n constructor,\n intros I J,\n by_cases hI : I = ⊥, { subst hI, left, exact bot_le },\n by_cases hJ : J = ⊥, { subst hJ, right, exact bot_le },\n obtain ⟨n, rfl⟩ := H I hI,\n obtain ⟨m, rfl⟩ := H J hJ,\n cases le_total m n with h' h',\n { left, exact ideal.pow_le_pow h' },\n { right, exact ideal.pow_le_pow h' } },\n tfae_finish,\nend\n", "meta": {"author": "leanprover-community", "repo": "mathlib", "sha": "5e526d18cea33550268dcbbddcb822d5cde40654", "save_path": "github-repos/lean/leanprover-community-mathlib", "path": "github-repos/lean/leanprover-community-mathlib/mathlib-5e526d18cea33550268dcbbddcb822d5cde40654/src/ring_theory/valuation/tfae.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4225046202709847, "lm_q2_score": 0.04023794708347557, "lm_q1q2_score": 0.01700071855298782}} {"text": "/-\nCopyright (c) 2021 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Leonardo de Moura\n-/\nimport Lean.Meta.Transform\nimport Lean.Meta.Tactic.Injection\nimport Lean.Meta.Tactic.Apply\nimport Lean.Meta.Tactic.Refl\nimport Lean.Meta.Tactic.Cases\nimport Lean.Meta.Tactic.Subst\nimport Lean.Meta.Tactic.Simp.Types\nimport Lean.Meta.Tactic.Assumption\n\nnamespace Lean.Meta\n\nprivate def mkAnd? (args : Array Expr) : Option Expr := Id.run do\n if args.isEmpty then\n return none\n else\n let mut result := args.back\n for arg in args.reverse[1:] do\n result := mkApp2 (mkConst ``And) arg result\n return result\n\ndef elimOptParam (type : Expr) : CoreM Expr := do\n Core.transform type fun e =>\n if e.isAppOfArity ``optParam 2 then\n return TransformStep.visit (e.getArg! 0)\n else\n return .continue\n\nprivate partial def mkInjectiveTheoremTypeCore? (ctorVal : ConstructorVal) (useEq : Bool) : MetaM (Option Expr) := do\n let us := ctorVal.levelParams.map mkLevelParam\n let type ← elimOptParam ctorVal.type\n forallBoundedTelescope type ctorVal.numParams fun params type =>\n forallTelescope type fun args1 resultType => do\n let jp (args2 args2New : Array Expr) : MetaM (Option Expr) := do\n let lhs := mkAppN (mkAppN (mkConst ctorVal.name us) params) args1\n let rhs := mkAppN (mkAppN (mkConst ctorVal.name us) params) args2\n let eq ← mkEq lhs rhs\n let mut eqs := #[]\n for arg1 in args1, arg2 in args2 do\n let arg1Type ← inferType arg1\n if !(← isProp arg1Type) && arg1 != arg2 then\n eqs := eqs.push (← mkEqHEq arg1 arg2)\n if let some andEqs := mkAnd? eqs then\n let result ← if useEq then\n mkEq eq andEqs\n else\n mkArrow eq andEqs\n mkForallFVars params (← mkForallFVars args1 (← mkForallFVars args2New result))\n else\n return none\n let rec mkArgs2 (i : Nat) (type : Expr) (args2 args2New : Array Expr) : MetaM (Option Expr) := do\n if h : i < args1.size then\n match (← whnf type) with\n | Expr.forallE n d b _ =>\n let arg1 := args1.get ⟨i, h⟩\n if arg1.occurs resultType then\n mkArgs2 (i + 1) (b.instantiate1 arg1) (args2.push arg1) args2New\n else\n withLocalDecl n (if useEq then BinderInfo.default else BinderInfo.implicit) d fun arg2 =>\n mkArgs2 (i + 1) (b.instantiate1 arg2) (args2.push arg2) (args2New.push arg2)\n | _ => throwError \"unexpected constructor type for '{ctorVal.name}'\"\n else\n jp args2 args2New\n if useEq then\n mkArgs2 0 type #[] #[]\n else\n withNewBinderInfos (params.map fun param => (param.fvarId!, BinderInfo.implicit)) <|\n withNewBinderInfos (args1.map fun arg1 => (arg1.fvarId!, BinderInfo.implicit)) <|\n mkArgs2 0 type #[] #[]\n\nprivate def mkInjectiveTheoremType? (ctorVal : ConstructorVal) : MetaM (Option Expr) :=\n mkInjectiveTheoremTypeCore? ctorVal false\n\nprivate def injTheoremFailureHeader (ctorName : Name) : MessageData :=\n m!\"failed to prove injectivity theorem for constructor '{ctorName}', use 'set_option genInjectivity false' to disable the generation\"\n\nprivate def throwInjectiveTheoremFailure {α} (ctorName : Name) (mvarId : MVarId) : MetaM α :=\n throwError \"{injTheoremFailureHeader ctorName}{indentD <| MessageData.ofGoal mvarId}\"\n\nprivate def solveEqOfCtorEq (ctorName : Name) (mvarId : MVarId) (h : FVarId) : MetaM Unit := do\n match (← injection mvarId h) with\n | InjectionResult.solved => unreachable!\n | InjectionResult.subgoal mvarId .. =>\n (← mvarId.splitAnd).forM fun mvarId =>\n unless (← mvarId.assumptionCore) do\n throwInjectiveTheoremFailure ctorName mvarId\n\nprivate def mkInjectiveTheoremValue (ctorName : Name) (targetType : Expr) : MetaM Expr :=\n forallTelescopeReducing targetType fun xs type => do\n let mvar ← mkFreshExprSyntheticOpaqueMVar type\n solveEqOfCtorEq ctorName mvar.mvarId! xs.back.fvarId!\n mkLambdaFVars xs mvar\n\ndef mkInjectiveTheoremNameFor (ctorName : Name) : Name :=\n ctorName ++ `inj\n\nprivate def mkInjectiveTheorem (ctorVal : ConstructorVal) : MetaM Unit := do\n let some type ← mkInjectiveTheoremType? ctorVal\n | return ()\n let value ← mkInjectiveTheoremValue ctorVal.name type\n let name := mkInjectiveTheoremNameFor ctorVal.name\n addDecl <| Declaration.thmDecl {\n name\n levelParams := ctorVal.levelParams\n type := (← instantiateMVars type)\n value := (← instantiateMVars value)\n }\n\ndef mkInjectiveEqTheoremNameFor (ctorName : Name) : Name :=\n ctorName ++ `injEq\n\nprivate def mkInjectiveEqTheoremType? (ctorVal : ConstructorVal) : MetaM (Option Expr) :=\n mkInjectiveTheoremTypeCore? ctorVal true\n\nprivate def mkInjectiveEqTheoremValue (ctorName : Name) (targetType : Expr) : MetaM Expr := do\n forallTelescopeReducing targetType fun xs type => do\n let mvar ← mkFreshExprSyntheticOpaqueMVar type\n let [mvarId₁, mvarId₂] ← mvar.mvarId!.apply (mkConst ``Eq.propIntro)\n | throwError \"unexpected number of subgoals when proving injective theorem for constructor '{ctorName}'\"\n let (h, mvarId₁) ← mvarId₁.intro1\n let (_, mvarId₂) ← mvarId₂.intro1\n solveEqOfCtorEq ctorName mvarId₁ h\n let mvarId₂ ← mvarId₂.casesAnd\n if let some mvarId₂ ← mvarId₂.substEqs then\n try mvarId₂.refl catch _ => throwError (injTheoremFailureHeader ctorName)\n mkLambdaFVars xs mvar\n\nprivate def mkInjectiveEqTheorem (ctorVal : ConstructorVal) : MetaM Unit := do\n let some type ← mkInjectiveEqTheoremType? ctorVal\n | return ()\n let value ← mkInjectiveEqTheoremValue ctorVal.name type\n let name := mkInjectiveEqTheoremNameFor ctorVal.name\n addDecl <| Declaration.thmDecl {\n name\n levelParams := ctorVal.levelParams\n type := (← instantiateMVars type)\n value := (← instantiateMVars value)\n }\n addSimpTheorem (ext := simpExtension) name (post := true) (inv := false) AttributeKind.global (prio := eval_prio default)\n\nregister_builtin_option genInjectivity : Bool := {\n defValue := true\n descr := \"generate injectivity theorems for inductive datatype constructors\"\n}\n\ndef mkInjectiveTheorems (declName : Name) : MetaM Unit := do\n if (← getEnv).contains ``Eq.propIntro && genInjectivity.get (← getOptions) && !(← isInductivePredicate declName) then\n let info ← getConstInfoInduct declName\n unless info.isUnsafe do\n for ctor in info.ctors do\n let ctorVal ← getConstInfoCtor ctor\n if ctorVal.numFields > 0 then\n mkInjectiveTheorem ctorVal\n mkInjectiveEqTheorem ctorVal\n\nend Lean.Meta\n", "meta": {"author": "leanprover", "repo": "lean4", "sha": "742d053a97bdd109a41a921facd1cd6a55e89bc7", "save_path": "github-repos/lean/leanprover-lean4", "path": "github-repos/lean/leanprover-lean4/lean4-742d053a97bdd109a41a921facd1cd6a55e89bc7/src/Lean/Meta/Injective.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.03410042436258875, "lm_q1q2_score": 0.016917010108620092}} {"text": "\nimport tactic.basic data.list.defs data.prod data.sum tactic.rcases\nuniverses u₁ u₂\n\nopen interactive interactive.types\nopen lean.parser nat tactic\n\nmeta def get_ext_subject : expr → tactic name\n| (expr.pi n bi d b) :=\n do v ← mk_local' n bi d,\n b' ← whnf $ b.instantiate_var v,\n get_ext_subject b'\n| (expr.app _ e) :=\n do t ← infer_type e >>= instantiate_mvars >>= head_beta,\n if t.get_app_fn.is_constant then\n pure $ t.get_app_fn.const_name\n else if t.is_pi then\n pure $ name.mk_numeral 0 name.anonymous\n else if t.is_sort then\n pure $ name.mk_numeral 1 name.anonymous\n else do\n t ← pp t,\n fail format!\"only constants and Pi types are supported: {t}\"\n| e := fail format!\"Only expressions of the form `_ → _ → ... → R ... e are supported: {e}\"\n\nopen native\n\n@[reducible] def ext_param_type := option name ⊕ option name\n\nmeta def opt_minus : lean.parser (option name → ext_param_type) :=\nsum.inl <$ tk \"-\" <|> pure sum.inr\n\nmeta def ext_param :=\nopt_minus <*> ( name.mk_numeral 0 name.anonymous <$ brackets \"(\" \")\" (tk \"→\" <|> tk \"->\") <|>\n none <$ tk \"*\" <|>\n some <$> ident )\n\nmeta def saturate_fun : name → tactic expr\n| (name.mk_numeral 0 name.anonymous) :=\ndo v₀ ← mk_mvar,\n v₁ ← mk_mvar,\n return $ v₀.imp v₁\n| (name.mk_numeral 1 name.anonymous) :=\ndo u ← mk_meta_univ,\n pure $ expr.sort u\n| n :=\ndo e ← resolve_constant n >>= mk_const,\n a ← get_arity e,\n e.mk_app <$> (list.iota a).mmap (λ _, mk_mvar)\n\nmeta def equiv_type_constr (n n' : name) : tactic unit :=\ndo e ← saturate_fun n,\n e' ← saturate_fun n',\n unify e e' <|> fail format!\"{n} and {n'} are not definitionally equal types\"\n\n/--\n Tag lemmas of the form:\n\n ```\n @[extensionality]\n lemma my_collection.ext (a b : my_collection)\n (h : ∀ x, a.lookup x = b.lookup y) :\n a = b := ...\n ```\n\n The attribute indexes extensionality lemma using the type of the\n objects (i.e. `my_collection`) which it gets from the statement of\n the lemma. In some cases, the same lemma can be used to state the\n extensionality of multiple types that are definitionally equivalent.\n\n ```\n attribute [extensionality [(→),thunk,stream]] funext\n ```\n\n Those parameters are cumulative. The following are equivalent:\n\n ```\n attribute [extensionality [(→),thunk]] funext\n attribute [extensionality [stream]] funext\n ```\n and\n ```\n attribute [extensionality [(→),thunk,stream]] funext\n ```\n\n One removes type names from the list for one lemma with:\n ```\n attribute [extensionality [-stream,-thunk]] funext\n ```\n\n Finally, the following:\n\n ```\n @[extensionality]\n lemma my_collection.ext (a b : my_collection)\n (h : ∀ x, a.lookup x = b.lookup y) :\n a = b := ...\n ```\n\n is equivalent to\n\n ```\n @[extensionality *]\n lemma my_collection.ext (a b : my_collection)\n (h : ∀ x, a.lookup x = b.lookup y) :\n a = b := ...\n ```\n\n This allows us specify type synonyms along with the type\n that referred to in the lemma statement.\n\n ```\n @[extensionality [*,my_type_synonym]]\n lemma my_collection.ext (a b : my_collection)\n (h : ∀ x, a.lookup x = b.lookup y) :\n a = b := ...\n ```\n -/\n@[user_attribute]\nmeta def extensional_attribute : user_attribute (name_map name) (bool × list ext_param_type × list name × list (name × name)) :=\n{ name := `extensionality,\n descr := \"lemmas usable by `ext` tactic\",\n cache_cfg := { mk_cache := λ ls,\n do { attrs ← ls.mmap $ λ l,\n do { ⟨_,_,ls,_⟩ ← extensional_attribute.get_param l,\n pure $ prod.mk <$> ls <*> pure l },\n pure $ rb_map.of_list $ attrs.join },\n dependencies := [] },\n parser :=\n do { ls ← pure <$> ext_param <|> list_of ext_param <|> pure [],\n m ← extensional_attribute.get_cache,\n pure $ (ff,ls,[],m.to_list) },\n after_set := some $ λ n _ b,\n do (ff,ls,_,ls') ← extensional_attribute.get_param n | pure (),\n s ← mk_const n >>= infer_type >>= get_ext_subject,\n let (rs,ls'') := if ls.empty\n then ([],[s])\n else ls.partition_map (sum.map (flip option.get_or_else s) (flip option.get_or_else s)),\n ls''.mmap' (equiv_type_constr s),\n let l := ls'' ∪ (ls'.filter $ λ l, prod.snd l = n).map prod.fst \\ rs,\n extensional_attribute.set n (tt,[],l,[]) b }\n\nattribute [extensionality] array.ext propext prod.ext\nattribute [extensionality [(→),thunk]] _root_.funext\n\nnamespace ulift\n@[extensionality] lemma ext {α : Type u₁} (X Y : ulift.{u₂} α) (w : X.down = Y.down) : X = Y :=\nbegin\n cases X, cases Y, dsimp at w, rw w,\nend\nend ulift\n\nnamespace plift\n@[extensionality] lemma ext {P : Prop} (a b : plift P) : a = b :=\nbegin\n cases a, cases b, refl\nend\nend plift\n\nnamespace tactic\n\nmeta def try_intros : ext_patt → tactic ext_patt\n| [] := try intros $> []\n| (x::xs) :=\ndo tgt ← target >>= whnf,\n if tgt.is_pi\n then rintro [x] >> try_intros xs\n else pure (x :: xs)\n\nmeta def ext1 (xs : ext_patt) (cfg : apply_cfg := {}): tactic ext_patt :=\ndo subject ← target >>= get_ext_subject,\n m ← extensional_attribute.get_cache,\n do { rule ← m.find subject,\n applyc rule cfg } <|>\n do { ls ← attribute.get_instances `extensionality,\n ls.any_of (λ n, applyc n cfg) } <|>\n fail format!\"no applicable extensionality rule found for {subject}\",\n try_intros xs\n\nmeta def ext : ext_patt → option ℕ → tactic unit\n| _ (some 0) := skip\n| xs n := focus1 $ do\n ys ← ext1 xs, try (ext ys (nat.pred <$> n))\n\n\nlocal postfix `?`:9001 := optional\nlocal postfix *:9001 := many\n\n/--\n `ext1 id` selects and apply one extensionality lemma (with attribute\n `extensionality`), using `id`, if provided, to name a local constant\n introduced by the lemma. If `id` is omitted, the local constant is\n named automatically, as per `intro`.\n -/\nmeta def interactive.ext1 (xs : parse ext_parse) : tactic unit :=\next1 xs $> ()\n\n/--\n - `ext` applies as many extensionality lemmas as possible;\n - `ext ids`, with `ids` a list of identifiers, finds extentionality and applies them\n until it runs out of identifiers in `ids` to name the local constants.\n\n When trying to prove:\n\n ```\n α β : Type,\n f g : α → set β\n ⊢ f = g\n ```\n\n applying `ext x y` yields:\n\n ```\n α β : Type,\n f g : α → set β,\n x : α,\n y : β\n ⊢ y ∈ f x ↔ y ∈ f x\n ```\n\n by applying functional extensionality and set extensionality.\n\n A maximum depth can be provided with `ext x y z : 3`.\n -/\nmeta def interactive.ext : parse ext_parse → parse (tk \":\" *> small_nat)? → tactic unit\n | [] (some n) := iterate_range 1 n (ext1 [] $> ())\n | [] none := repeat1 (ext1 [] $> ())\n | xs n := tactic.ext xs n\n\nend tactic\n", "meta": {"author": "digama0", "repo": "mathlib-ITP2019", "sha": "5cbd0362e04e671ef5db1284870592af6950197c", "save_path": "github-repos/lean/digama0-mathlib-ITP2019", "path": "github-repos/lean/digama0-mathlib-ITP2019/mathlib-ITP2019-5cbd0362e04e671ef5db1284870592af6950197c/src/tactic/ext.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.034618842698694585, "lm_q1q2_score": 0.016903806054131006}} {"text": "import classes.unrestricted.basics.lifting\nimport classes.unrestricted.closure_properties.concatenation\nimport utilities.written_by_others.trim_assoc\n\n\n-- new nonterminal type\nprivate def nn (N : Type) : Type :=\nN ⊕ fin 3\n\n-- new symbol type\nprivate def ns (T N : Type) : Type :=\nsymbol T (nn N)\n\nvariables {T : Type}\n\n\nsection specific_symbols\n\nprivate def Z {N : Type} : ns T N := symbol.nonterminal (sum.inr 0)\nprivate def H {N : Type} : ns T N := symbol.nonterminal (sum.inr 1) -- denoted by `#` in the pdf\nprivate def R {N : Type} : ns T N := symbol.nonterminal (sum.inr 2)\n\nprivate def S {g : grammar T} : ns T g.nt := symbol.nonterminal (sum.inl g.initial)\n\nprivate lemma Z_neq_H {N : Type} : Z ≠ @H T N :=\nbegin\n intro ass,\n have imposs := sum.inr.inj (symbol.nonterminal.inj ass),\n exact fin.zero_ne_one imposs,\nend\n\nprivate lemma Z_neq_R {N : Type} : Z ≠ @R T N :=\nbegin\n intro ass,\n have imposs := sum.inr.inj (symbol.nonterminal.inj ass),\n have zero_ne_two : (0 : fin 3) ≠ (2 : fin 3), dec_trivial,\n exact zero_ne_two imposs,\nend\n\nprivate lemma H_neq_R {N : Type} : H ≠ @R T N :=\nbegin\n intro ass,\n have imposs := sum.inr.inj (symbol.nonterminal.inj ass),\n have one_ne_two : (1 : fin 3) ≠ (2 : fin 3), dec_trivial,\n exact one_ne_two imposs,\nend\n\nend specific_symbols\n\n\nsection construction\n\nprivate def wrap_sym {N : Type} : symbol T N → ns T N\n| (symbol.terminal t) := symbol.terminal t\n| (symbol.nonterminal n) := symbol.nonterminal (sum.inl n)\n\nprivate def wrap_gr {N : Type} (r : grule T N) : grule T (nn N) :=\ngrule.mk\n (list.map wrap_sym r.input_L)\n (sum.inl r.input_N)\n (list.map wrap_sym r.input_R)\n (list.map wrap_sym r.output_string)\n\nprivate def rules_that_scan_terminals (g : grammar T) : list (grule T (nn g.nt)) :=\nlist.map (λ t, grule.mk\n [] (sum.inr 2) [symbol.terminal t] [symbol.terminal t, R]\n ) (all_used_terminals g)\n\n-- based on `/informal/KleeneStar.pdf`\nprivate def star_grammar (g : grammar T) : grammar T :=\ngrammar.mk (nn g.nt) (sum.inr 0) (\n grule.mk [] (sum.inr 0) [] [Z, S, H] ::\n grule.mk [] (sum.inr 0) [] [R, H] ::\n grule.mk [] (sum.inr 2) [H] [R] ::\n grule.mk [] (sum.inr 2) [H] [] ::\n list.map wrap_gr g.rules ++\n rules_that_scan_terminals g\n)\n\nend construction\n\n\nsection easy_direction\n\nprivate lemma short_induction {g : grammar T} {w : list (list T)}\n (ass : ∀ wᵢ ∈ w.reverse, grammar_generates g wᵢ) :\n grammar_derives (star_grammar g) [Z] (Z ::\n list.join (list.map (++ [H]) (list.map (list.map symbol.terminal) w.reverse))\n ) ∧\n ∀ p ∈ w, ∀ t ∈ p, symbol.terminal t ∈ list.join (list.map grule.output_string g.rules) :=\nbegin\n induction w with v x ih,\n {\n split,\n {\n apply grammar_deri_self,\n },\n {\n intros p pin,\n exfalso,\n exact list.not_mem_nil p pin,\n },\n },\n have vx_reverse : (v :: x).reverse = x.reverse ++ [v],\n {\n apply list.reverse_cons,\n },\n rw vx_reverse at *,\n specialize ih (by {\n intros wᵢ in_reversed,\n apply ass,\n apply list.mem_append_left,\n exact in_reversed,\n }),\n specialize ass v (by {\n apply list.mem_append_right,\n apply list.mem_singleton_self,\n }),\n unfold grammar_generates at ass,\n split,\n {\n apply grammar_deri_of_tran_deri,\n {\n use (star_grammar g).rules.nth_le 0 (by dec_trivial),\n split,\n {\n apply list.nth_le_mem,\n },\n use [[], []],\n split;\n refl,\n },\n rw [list.nil_append, list.append_nil, list.map_append, list.map_append],\n change grammar_derives (star_grammar g) [Z, S, H] _,\n have ih_plus := grammar_deri_with_postfix ([S, H] : list (symbol T (star_grammar g).nt)) ih.left,\n apply grammar_deri_of_deri_deri ih_plus,\n have ass_lifted : grammar_derives (star_grammar g) [S] (list.map symbol.terminal v),\n {\n clear_except ass,\n have wrap_eq_lift : @wrap_sym T g.nt = lift_symbol_ sum.inl,\n {\n ext,\n cases x;\n refl,\n },\n let lifted_g : lifted_grammar_ T :=\n lifted_grammar_.mk g (star_grammar g) sum.inl sum.get_left (by {\n intros x y hyp,\n exact sum.inl.inj hyp,\n }) (by {\n intros x y hyp,\n cases x,\n {\n cases y,\n {\n simp only [sum.get_left] at hyp,\n left,\n congr,\n exact hyp,\n },\n {\n simp only [sum.get_left] at hyp,\n exfalso,\n exact hyp,\n },\n },\n {\n cases y,\n {\n simp only [sum.get_left] at hyp,\n exfalso,\n exact hyp,\n },\n {\n right,\n refl,\n },\n },\n }) (by {\n intro x,\n refl,\n }) (by {\n intros r rin,\n apply list.mem_cons_of_mem,\n apply list.mem_cons_of_mem,\n apply list.mem_cons_of_mem,\n apply list.mem_cons_of_mem,\n apply list.mem_append_left,\n rw list.mem_map,\n use r,\n split,\n {\n exact rin,\n },\n unfold wrap_gr,\n unfold lift_rule_,\n unfold lift_string_,\n rw wrap_eq_lift,\n }) (by {\n rintros r ⟨rin, n, nrn⟩,\n iterate 4 {\n cases rin,\n {\n exfalso,\n rw rin at nrn,\n exact sum.no_confusion nrn,\n },\n },\n change r ∈ list.map wrap_gr g.rules ++ rules_that_scan_terminals g at rin,\n rw list.mem_append at rin,\n cases rin,\n {\n clear_except rin wrap_eq_lift,\n rw list.mem_map at rin,\n rcases rin with ⟨r₀, rin₀, r_of_r₀⟩,\n use r₀,\n split,\n {\n exact rin₀,\n },\n convert r_of_r₀,\n unfold lift_rule_,\n unfold wrap_gr,\n unfold lift_string_,\n rw wrap_eq_lift,\n },\n {\n exfalso,\n unfold rules_that_scan_terminals at rin,\n rw list.mem_map at rin,\n rcases rin with ⟨t, tin, r_of_tg⟩,\n rw ←r_of_tg at nrn,\n exact sum.no_confusion nrn,\n },\n }),\n convert_to\n grammar_derives lifted_g.g\n [symbol.nonterminal (sum.inl g.initial)]\n (lift_string_ lifted_g.lift_nt (list.map symbol.terminal v)),\n {\n unfold lift_string_,\n rw list.map_map,\n congr,\n },\n exact lift_deri_ lifted_g ass,\n },\n have ass_postf := grammar_deri_with_postfix ([H] : list (symbol T (star_grammar g).nt)) ass_lifted,\n rw list.join_append,\n rw ←list.cons_append,\n apply grammar_deri_with_prefix,\n rw list.map_map,\n rw list.map_singleton,\n rw list.join_singleton,\n change grammar_derives (star_grammar g) [S, H] (list.map symbol.terminal v ++ [H]),\n convert ass_postf,\n },\n {\n intros p pin t tin,\n cases pin,\n {\n rw pin at tin,\n clear pin,\n have stin : symbol.terminal t ∈ list.map symbol.terminal v,\n {\n rw list.mem_map,\n use t,\n split,\n {\n exact tin,\n },\n {\n refl,\n },\n },\n cases grammar_generates_only_legit_terminals ass stin with rule_exists imposs,\n {\n rcases rule_exists with ⟨r, rin, stirn⟩,\n rw list.mem_join,\n use r.output_string,\n split,\n {\n rw list.mem_map,\n use r,\n split,\n {\n exact rin,\n },\n {\n refl,\n },\n },\n {\n exact stirn,\n },\n },\n {\n exfalso,\n exact symbol.no_confusion imposs,\n }\n },\n {\n exact ih.right p pin t tin,\n }\n },\nend\n\nprivate lemma terminal_scan_ind {g : grammar T} {w : list (list T)} (n : ℕ) (n_lt_wl : n ≤ w.length)\n (terminals : ∀ v ∈ w, ∀ t ∈ v, symbol.terminal t ∈ list.join (list.map grule.output_string g.rules)) :\n grammar_derives (star_grammar g)\n ((list.map (λ u, list.map symbol.terminal u) (list.take (w.length - n) w)).join ++ [R] ++\n (list.map (λ v, [H] ++ list.map symbol.terminal v) (list.drop (w.length - n) w)).join ++ [H])\n (list.map symbol.terminal w.join ++ [R, H]) :=\nbegin\n induction n with k ih,\n {\n rw nat.sub_zero,\n rw list.drop_length,\n rw list.map_nil,\n rw list.join,\n rw list.append_nil,\n rw list.take_length,\n rw list.map_join,\n rw list.append_assoc,\n apply grammar_deri_self,\n },\n specialize ih (nat.le_of_succ_le n_lt_wl),\n apply grammar_deri_of_deri_deri _ ih,\n clear ih,\n\n have wlk_succ : w.length - k = (w.length - k.succ).succ,\n {\n omega,\n },\n have lt_wl : w.length - k.succ < w.length,\n {\n omega,\n },\n have split_ldw :\n list.drop (w.length - k.succ) w =\n (w.nth (w.length - k.succ)).to_list ++ list.drop (w.length - k) w,\n {\n rw wlk_succ,\n generalize substit : w.length - k.succ = q,\n rw substit at lt_wl,\n rw ←list.take_append_drop q w,\n rw list.nth_append_right,\n swap, {\n apply list.length_take_le,\n },\n have eq_q : (list.take q w).length = q,\n {\n rw list.length_take,\n exact min_eq_left_of_lt lt_wl,\n },\n rw eq_q,\n rw nat.sub_self,\n have drop_q_succ :\n list.drop q.succ (list.take q w ++ list.drop q w) = list.drop 1 (list.drop q w),\n {\n rw list.drop_drop,\n rw list.take_append_drop,\n rw add_comm,\n },\n rw [drop_q_succ, list.drop_left' eq_q, list.drop_drop],\n rw ←list.take_append_drop (1 + q) w,\n have q_lt : q < (list.take (1 + q) w).length,\n {\n rw list.length_take,\n exact lt_min (lt_one_add q) lt_wl,\n },\n rw list.drop_append_of_le_length (le_of_lt q_lt),\n apply congr_arg2,\n {\n rw list.nth_append,\n swap, {\n rw list.length_drop,\n exact nat.sub_pos_of_lt q_lt,\n },\n rw list.nth_drop,\n rw add_zero,\n rw list.nth_take (lt_one_add q),\n rw add_comm,\n rw list_drop_take_succ lt_wl,\n rw list.nth_le_nth lt_wl,\n refl,\n },\n {\n rw list.take_append_drop,\n },\n },\n apply grammar_deri_with_postfix,\n rw [split_ldw, list.map_append, list.join_append, ←list.append_assoc],\n apply grammar_deri_with_postfix,\n rw [wlk_succ, list.take_succ, list.map_append, list.join_append, list.append_assoc, list.append_assoc],\n apply grammar_deri_with_prefix,\n clear_except terminals lt_wl,\n specialize terminals (w.nth_le (w.length - k.succ) lt_wl) (list.nth_le_mem w (w.length - k.succ) lt_wl),\n rw list.nth_le_nth lt_wl,\n unfold option.to_list,\n rw [list.map_singleton, list.join_singleton, ←list.map_join, list.join_singleton],\n apply grammar_deri_of_tran_deri,\n {\n use (star_grammar g).rules.nth_le 2 (by dec_trivial),\n split_ile,\n use [[], list.map symbol.terminal (w.nth_le (w.length - k.succ) lt_wl)],\n split;\n refl,\n },\n rw list.nil_append,\n\n have scan_segment : ∀ m : ℕ, m ≤ (w.nth_le (w.length - k.succ) lt_wl).length →\n grammar_derives (star_grammar g)\n ([R] ++ list.map symbol.terminal (w.nth_le (w.length - k.succ) lt_wl))\n (list.map symbol.terminal (list.take m (w.nth_le (w.length - k.succ) lt_wl)) ++\n ([R] ++ list.map symbol.terminal (list.drop m (w.nth_le (w.length - k.succ) lt_wl)))),\n {\n intros m small,\n induction m with n ih,\n {\n rw ←list.append_assoc,\n convert grammar_deri_self,\n },\n apply grammar_deri_of_deri_tran (ih (nat.le_of_succ_le small)),\n rw nat.succ_le_iff at small,\n use ⟨[], (sum.inr 2), [symbol.terminal (list.nth_le (w.nth_le (w.length - k.succ) lt_wl) n small)],\n [symbol.terminal (list.nth_le (w.nth_le (w.length - k.succ) lt_wl) n small), R]⟩,\n split,\n {\n iterate 4 {\n apply list.mem_cons_of_mem,\n },\n apply list.mem_append_right,\n unfold rules_that_scan_terminals,\n rw list.mem_map,\n use list.nth_le (w.nth_le (w.length - k.succ) lt_wl) n small,\n split,\n {\n unfold all_used_terminals,\n rw list.mem_filter_map,\n use (w.nth_le (w.length - k.succ) lt_wl).nth_le n small,\n split,\n {\n apply terminals,\n apply list.nth_le_mem,\n },\n {\n refl,\n },\n },\n {\n refl,\n },\n },\n use list.map symbol.terminal (list.take n (w.nth_le (w.length - k.succ) lt_wl)),\n use list.map symbol.terminal (list.drop n.succ (w.nth_le (w.length - k.succ) lt_wl)),\n dsimp only,\n split,\n {\n trim,\n rw list.nil_append,\n rw list.append_assoc,\n apply congr_arg2,\n {\n refl,\n },\n rw ←list.take_append_drop 1 (list.map symbol.terminal (list.drop n (w.nth_le (w.length - k.succ) lt_wl))),\n apply congr_arg2,\n {\n rw ←list.map_take,\n rw list_take_one_drop,\n rw list.map_singleton,\n },\n {\n rw ←list.map_drop,\n rw list.drop_drop,\n rw add_comm,\n },\n },\n {\n rw list.take_succ,\n rw list.map_append,\n trim,\n rw list.nth_le_nth small,\n refl,\n },\n },\n convert scan_segment (w.nth_le (w.length - k.succ) lt_wl).length (by refl),\n {\n rw list.take_length,\n },\n {\n rw list.drop_length,\n rw list.map_nil,\n refl,\n },\nend\n\nprivate lemma terminal_scan_aux {g : grammar T} {w : list (list T)}\n (terminals : ∀ v ∈ w, ∀ t ∈ v, symbol.terminal t ∈ list.join (list.map grule.output_string g.rules)) :\n grammar_derives (star_grammar g)\n ([R] ++ (list.map (λ v, [H] ++ v) (list.map (list.map symbol.terminal) w)).join ++ [H])\n (list.map symbol.terminal w.join ++ [R, H]) :=\nbegin\n rw list.map_map,\n convert terminal_scan_ind w.length (by refl) terminals,\n {\n rw nat.sub_self,\n rw list.take_zero,\n refl,\n },\n {\n rw nat.sub_self,\n refl,\n },\nend\n\nend easy_direction\n\n\nsection hard_direction\n\nlemma zero_of_not_ge_one {n : ℕ} (not_pos : ¬ (n ≥ 1)) : n = 0 :=\nbegin\n push_neg at not_pos,\n rwa nat.lt_one_iff at not_pos,\nend\n\nlemma length_ge_one_of_not_nil {α : Type*} {l : list α} (lnn : l ≠ []) : l.length ≥ 1 :=\nbegin\n by_contradiction contra,\n have llz := zero_of_not_ge_one contra,\n rw list.length_eq_zero at llz,\n exact lnn llz,\nend\n\nprivate lemma nat_eq_tech {a b c : ℕ} (b_lt_c : b < c) (ass : c = a.succ + c - b.succ) :\n a = b :=\nbegin\n omega,\nend\n\nprivate lemma wrap_never_outputs_nt_inr {N : Type} {a : symbol T N} (i : fin 3) :\n wrap_sym a ≠ symbol.nonterminal (sum.inr i) :=\nbegin\n cases a;\n unfold wrap_sym,\n {\n apply symbol.no_confusion,\n },\n intro contr,\n have inl_eq_inr := symbol.nonterminal.inj contr,\n exact sum.no_confusion inl_eq_inr,\nend\n\nprivate lemma wrap_never_outputs_Z {N : Type} {a : symbol T N} :\n wrap_sym a ≠ Z :=\nbegin\n exact wrap_never_outputs_nt_inr 0,\nend\n\nprivate lemma wrap_never_outputs_H {N : Type} {a : symbol T N} :\n wrap_sym a ≠ H :=\nbegin\n exact wrap_never_outputs_nt_inr 1,\nend\n\nprivate lemma wrap_never_outputs_R {N : Type} {a : symbol T N} :\n wrap_sym a ≠ R :=\nbegin\n exact wrap_never_outputs_nt_inr 2,\nend\n\nprivate lemma map_wrap_never_contains_nt_inr {N : Type} {l : list (symbol T N)} (i : fin 3) :\n symbol.nonterminal (sum.inr i) ∉ list.map wrap_sym l :=\nbegin\n intro contra,\n rw list.mem_map at contra,\n rcases contra with ⟨s, -, imposs⟩,\n exact wrap_never_outputs_nt_inr i imposs,\nend\n\nprivate lemma map_wrap_never_contains_Z {N : Type} {l : list (symbol T N)} :\n Z ∉ list.map wrap_sym l :=\nbegin\n exact map_wrap_never_contains_nt_inr 0,\nend\n\nprivate lemma map_wrap_never_contains_H {N : Type} {l : list (symbol T N)} :\n H ∉ list.map wrap_sym l :=\nbegin\n exact map_wrap_never_contains_nt_inr 1,\nend\n\nprivate lemma map_wrap_never_contains_R {N : Type} {l : list (symbol T N)} :\n R ∉ list.map wrap_sym l :=\nbegin\n exact map_wrap_never_contains_nt_inr 2,\nend\n\nprivate lemma wrap_sym_inj {N : Type} {a b : symbol T N} (wrap_eq : wrap_sym a = wrap_sym b) :\n a = b :=\nbegin\n cases a,\n {\n cases b,\n {\n congr,\n exact symbol.terminal.inj wrap_eq,\n },\n {\n exfalso,\n exact symbol.no_confusion wrap_eq,\n },\n },\n {\n cases b,\n {\n exfalso,\n exact symbol.no_confusion wrap_eq,\n },\n {\n congr,\n unfold wrap_sym at wrap_eq,\n exact sum.inl.inj (symbol.nonterminal.inj wrap_eq),\n },\n },\nend\n\nprivate lemma wrap_str_inj {N : Type} {x y : list (symbol T N)}\n (wrap_eqs : list.map wrap_sym x = list.map wrap_sym y) :\n x = y :=\nbegin\n ext1,\n have eqnth := congr_arg (λ l, list.nth l n) wrap_eqs,\n dsimp only at eqnth,\n rw list.nth_map at eqnth,\n rw list.nth_map at eqnth,\n\n cases x.nth n with xₙ,\n {\n cases y.nth n with yₙ,\n {\n refl,\n },\n {\n exfalso,\n exact option.no_confusion eqnth,\n },\n },\n {\n cases y.nth n with yₙ,\n {\n exfalso,\n exact option.no_confusion eqnth,\n },\n {\n congr,\n apply wrap_sym_inj,\n rw option.map_some' at eqnth,\n rw option.map_some' at eqnth,\n exact option.some.inj eqnth,\n },\n },\nend\n\nprivate lemma H_not_in_rule_input {g : grammar T} {r : grule T g.nt} :\n H ∉ list.map wrap_sym r.input_L ++ [symbol.nonterminal (sum.inl r.input_N)] ++\n list.map wrap_sym r.input_R :=\nbegin\n intro contra,\n rw list.mem_append at contra,\n cases contra,\n swap, {\n exact map_wrap_never_contains_H contra,\n },\n rw list.mem_append at contra,\n cases contra,\n {\n exact map_wrap_never_contains_H contra,\n },\n {\n rw list.mem_singleton at contra,\n have imposs := symbol.nonterminal.inj contra,\n exact sum.no_confusion imposs,\n },\nend\n\nprivate lemma snsri_not_in_join_mpHmmw {g : grammar T} {x : list (list (symbol T g.nt))} {i : fin 3}\n (snsri_neq_H : symbol.nonterminal (sum.inr i) ≠ @H T g.nt) :\n symbol.nonterminal (sum.inr i) ∉ list.join (list.map (++ [H]) (list.map (list.map wrap_sym) x)) :=\nbegin\n intro contra,\n rw list.mem_join at contra,\n rw list.map_map at contra,\n rcases contra with ⟨l, l_in, in_l⟩,\n rw list.mem_map at l_in,\n rcases l_in with ⟨y, -, eq_l⟩,\n rw ←eq_l at in_l,\n rw function.comp_app at in_l,\n rw list.mem_append at in_l,\n cases in_l,\n {\n exact map_wrap_never_contains_nt_inr i in_l,\n },\n {\n rw list.mem_singleton at in_l,\n exact snsri_neq_H in_l,\n },\nend\n\nprivate lemma Z_not_in_join_mpHmmw {g : grammar T} {x : list (list (symbol T g.nt))} :\n Z ∉ list.join (list.map (++ [H]) (list.map (list.map wrap_sym) x)) :=\nbegin\n exact snsri_not_in_join_mpHmmw Z_neq_H,\nend\n\nprivate lemma R_not_in_join_mpHmmw {g : grammar T} {x : list (list (symbol T g.nt))} :\n R ∉ list.join (list.map (++ [H]) (list.map (list.map wrap_sym) x)) :=\nbegin\n exact snsri_not_in_join_mpHmmw H_neq_R.symm,\nend\n\nprivate lemma zero_Rs_in_the_long_part {g : grammar T} {x : list (list (symbol T g.nt))} [decidable_eq (ns T g.nt)] :\n list.count_in (list.map (++ [H]) (list.map (list.map wrap_sym) x)).join R = 0 :=\nbegin\n exact list.count_in_zero_of_notin R_not_in_join_mpHmmw,\nend\n\nprivate lemma cases_1_and_2_and_3a_match_aux {g : grammar T} {r₀ : grule T g.nt}\n {x : list (list (symbol T g.nt))} {u v : list (ns T g.nt)} (xnn : x ≠ [])\n (hyp : (list.join (list.map (++ [H]) (list.map (list.map wrap_sym) x))) =\n u ++ list.map wrap_sym r₀.input_L ++ [symbol.nonterminal (sum.inl r₀.input_N)] ++\n list.map wrap_sym r₀.input_R ++ v) :\n ∃ m : ℕ, ∃ u₁ v₁ : list (symbol T g.nt),\n u = list.join (list.map (++ [H]) (list.take m (list.map (list.map wrap_sym) x))) ++ list.map wrap_sym u₁\n ∧ list.nth x m = some (u₁ ++ r₀.input_L ++ [symbol.nonterminal r₀.input_N] ++ r₀.input_R ++ v₁) ∧\n v = list.map wrap_sym v₁ ++ [H] ++\n list.join (list.map (++ [H]) (list.drop m.succ (list.map (list.map wrap_sym) x))) :=\nbegin\n have hypp :\n (list.map (++ [H]) (list.map (list.map wrap_sym) x)).join =\n u ++ (\n list.map wrap_sym r₀.input_L ++ [symbol.nonterminal (sum.inl r₀.input_N)] ++ list.map wrap_sym r₀.input_R\n ) ++ v,\n {\n simpa [list.append_assoc] using hyp,\n },\n have mid_brack : ∀ u', ∀ v',\n u' ++ r₀.input_L ++ [symbol.nonterminal r₀.input_N] ++ r₀.input_R ++ v' =\n u' ++ (r₀.input_L ++ [symbol.nonterminal r₀.input_N] ++ r₀.input_R) ++ v',\n {\n intros,\n simp only [list.append_assoc],\n },\n simp_rw mid_brack,\n clear hyp mid_brack,\n\n classical,\n have count_Hs := congr_arg (λ l, list.count_in l H) hypp,\n dsimp only at count_Hs,\n rw list.count_in_append at count_Hs,\n rw list.count_in_append at count_Hs,\n rw list.count_in_zero_of_notin H_not_in_rule_input at count_Hs,\n rw add_zero at count_Hs,\n rw [list.count_in_join, list.map_map, list.map_map] at count_Hs,\n\n have lens := congr_arg list.length hypp,\n rw list.length_append_append at lens,\n rw list.length_append_append at lens,\n rw list.length_singleton at lens,\n\n have ul_lt : u.length < list.length (list.join (list.map (++ [H]) (list.map (list.map wrap_sym) x))),\n {\n clear_except lens,\n linarith,\n },\n rcases list.take_join_of_lt ul_lt with ⟨m, k, mlt, klt, init_ul⟩,\n\n have vnn : v ≠ [],\n {\n by_contradiction v_nil,\n rw [v_nil, list.append_nil] at hypp,\n clear_except hypp xnn,\n have hlast := congr_arg (λ l : list (ns T g.nt), l.reverse.nth 0) hypp,\n dsimp only at hlast,\n rw [list.reverse_join, list.reverse_append, list.reverse_append_append, list.reverse_singleton] at hlast,\n have hhh : some H = ((list.map wrap_sym r₀.input_R).reverse ++ [symbol.nonterminal (sum.inl r₀.input_N)] ++ (list.map wrap_sym r₀.input_L).reverse ++ u.reverse).nth 0,\n {\n convert hlast,\n rw list.map_map,\n change some H = (list.map (λ l, list.reverse (l ++ [H])) (list.map (list.map wrap_sym) x)).reverse.join.nth 0,\n simp_rw list.reverse_append,\n rw list.map_map,\n change some H = (list.map (λ l, [H].reverse ++ (list.map wrap_sym l).reverse) x).reverse.join.nth 0,\n rw ←list.map_reverse,\n have xrnn : x.reverse ≠ [],\n {\n intro xr_nil,\n rw list.reverse_eq_iff at xr_nil,\n exact xnn xr_nil,\n },\n cases x.reverse with d l,\n {\n exfalso,\n exact xrnn rfl,\n },\n rw [list.map_cons, list.join, list.append_assoc],\n rw list.nth_append,\n swap, {\n rw list.length_reverse,\n rw list.length_singleton,\n exact one_pos,\n },\n rw list.reverse_singleton,\n refl,\n },\n rw ←list.map_reverse at hhh,\n cases r₀.input_R.reverse,\n {\n rw [list.map_nil, list.nil_append] at hhh,\n simp only [list.nth, list.cons_append] at hhh,\n exact sum.no_confusion (symbol.nonterminal.inj hhh),\n },\n {\n simp only [list.nth, list.map_cons, list.cons_append] at hhh,\n exact wrap_never_outputs_H hhh.symm,\n },\n },\n have urrrl_lt :\n list.length (u ++ (\n list.map wrap_sym r₀.input_L ++ [symbol.nonterminal (sum.inl r₀.input_N)] ++ list.map wrap_sym r₀.input_R\n )) <\n list.length (list.join (list.map (++ [H]) (list.map (list.map wrap_sym) x))),\n {\n have vl_pos : v.length > 0,\n {\n exact list.length_pos_of_ne_nil vnn,\n },\n clear_except lens vl_pos,\n rw list.length_append,\n rw list.length_append_append,\n rw list.length_singleton,\n linarith,\n },\n rcases list.drop_join_of_lt urrrl_lt with ⟨m', k', mlt', klt', last_vl⟩,\n\n have mxl : m < x.length,\n {\n rw list.length_map at mlt,\n rw list.length_map at mlt,\n exact mlt,\n },\n have mxl' : m' < x.length,\n {\n rw list.length_map at mlt',\n rw list.length_map at mlt',\n exact mlt',\n },\n have mxlmm : m < (list.map (list.map wrap_sym) x).length,\n {\n rwa list.length_map,\n },\n have mxlmm' : m' < (list.map (list.map wrap_sym) x).length,\n {\n rwa list.length_map,\n },\n use [m, list.take k (x.nth_le m mxl), list.drop k' (x.nth_le m' mxl')],\n\n have hyp_u := congr_arg (list.take u.length) hypp,\n rw list.append_assoc at hyp_u,\n rw list.take_left at hyp_u,\n rw init_ul at hyp_u,\n rw list.nth_le_map at hyp_u,\n swap, {\n exact mxlmm,\n },\n rw list.take_append_of_le_length at hyp_u,\n swap, {\n rw list.nth_le_map at klt,\n swap, {\n exact mxlmm,\n },\n rw list.length_append at klt,\n rw list.length_singleton at klt,\n rw list.nth_le_map at klt ⊢,\n iterate 2 {\n swap, {\n exact mxl,\n },\n },\n rw list.length_map at klt ⊢,\n rw nat.lt_succ_iff at klt,\n exact klt,\n },\n rw ←hyp_u at count_Hs,\n\n have hyp_v :=\n congr_arg (list.drop (list.length (u ++ (\n list.map wrap_sym r₀.input_L ++ [symbol.nonterminal (sum.inl r₀.input_N)] ++ list.map wrap_sym r₀.input_R\n )))) hypp,\n rw list.drop_left at hyp_v,\n rw last_vl at hyp_v,\n rw list.nth_le_map at hyp_v,\n swap, {\n exact mxlmm',\n },\n rw list.drop_append_of_le_length at hyp_v,\n swap, {\n rw list.nth_le_map at klt',\n swap, {\n exact mxlmm',\n },\n rw list.length_append at klt',\n rw list.length_singleton at klt',\n rw list.nth_le_map at klt' ⊢,\n iterate 2 {\n swap, {\n exact mxl',\n },\n },\n rw list.length_map at klt' ⊢,\n rw nat.lt_succ_iff at klt',\n exact klt',\n },\n rw ←hyp_v at count_Hs,\n\n have mm : m = m',\n {\n clear_except count_Hs mxl mxl' klt klt',\n rw [\n list.count_in_append, list.count_in_append, list.map_map,\n list.count_in_join, ←list.map_take, list.map_map,\n list.count_in_join, ←list.map_drop, list.map_map\n ] at count_Hs,\n change\n (list.map (λ w, list.count_in (list.map wrap_sym w ++ [H]) H) x).sum =\n (list.map (λ w, list.count_in (list.map wrap_sym w ++ [H]) H) (list.take m x)).sum + _ +\n (_ + (list.map (λ w, list.count_in (list.map wrap_sym w ++ [H]) H) (list.drop m'.succ x)).sum)\n at count_Hs,\n simp_rw list.count_in_append at count_Hs,\n\n have inside_wrap : ∀ y : list (symbol T g.nt), (list.map wrap_sym y).count_in H = 0,\n {\n intro,\n rw list.count_in_zero_of_notin,\n apply map_wrap_never_contains_H,\n },\n have inside_one : ∀ z : list (symbol T g.nt),\n (list.map wrap_sym z).count_in (@H T g.nt) + [@H T g.nt].count_in (@H T g.nt) = 1,\n {\n intro,\n rw list.count_in_singleton_eq H,\n rw inside_wrap,\n },\n simp_rw inside_one at count_Hs,\n repeat {\n rw [list.map_const, list.sum_const_nat, one_mul] at count_Hs,\n },\n rw [list.length_take, list.length_drop, list.nth_le_map', list.nth_le_map'] at count_Hs,\n rw min_eq_left (le_of_lt mxl) at count_Hs,\n have inside_take : (list.take k (list.map wrap_sym (x.nth_le m mxl))).count_in H = 0,\n {\n rw ←list.map_take,\n rw inside_wrap,\n },\n have inside_drop : (list.drop k' (list.map wrap_sym (x.nth_le m' mxl'))).count_in H + [H].count_in H = 1,\n {\n rw ←list.map_drop,\n rw inside_wrap,\n rw list.count_in_singleton_eq (@H T g.nt),\n },\n rw [inside_take, inside_drop] at count_Hs,\n rw [add_zero, ←add_assoc, ←nat.add_sub_assoc] at count_Hs,\n swap, {\n rwa nat.succ_le_iff,\n },\n exact nat_eq_tech mxl' count_Hs,\n },\n rw ←mm at *,\n\n split,\n {\n symmetry,\n convert hyp_u,\n {\n rw list.map_take,\n },\n {\n rw list.map_take,\n rw list.nth_le_map,\n },\n },\n split,\n swap, {\n symmetry,\n convert hyp_v,\n {\n rw list.map_drop,\n rw list.nth_le_map,\n },\n {\n rw list.map_drop,\n rw mm,\n },\n },\n rw [←hyp_u, ←hyp_v] at hypp,\n\n have mltx : m < x.length,\n {\n rw list.length_map at mlt,\n rw list.length_map at mlt,\n exact mlt,\n },\n have xxx : x = x.take m ++ [x.nth_le m mltx] ++ x.drop m.succ,\n {\n rw list.append_assoc,\n rw list.singleton_append,\n rw list.cons_nth_le_drop_succ,\n rw list.take_append_drop,\n },\n have hyppp :\n (list.map (++ [H]) (list.map (list.map wrap_sym) (x.take m ++ [x.nth_le m mltx] ++ x.drop m.succ))).join =\n (list.take m (list.map (++ [H]) (list.map (list.map wrap_sym) x))).join ++\n list.take k ((list.map (list.map wrap_sym) x).nth_le m mxlmm) ++\n (list.map wrap_sym r₀.input_L ++ [symbol.nonterminal (sum.inl r₀.input_N)] ++ list.map wrap_sym r₀.input_R) ++\n (list.drop k' ((list.map (list.map wrap_sym) x).nth_le m mxlmm) ++ [H] ++\n (list.drop m.succ (list.map (++ [H]) (list.map (list.map wrap_sym) x))).join),\n {\n convert hypp,\n exact xxx.symm,\n },\n clear_except hyppp mm,\n rw [\n list.map_append_append, list.map_append_append,\n list.join_append_append,\n list.append_assoc, list.append_assoc, list.append_assoc, list.append_assoc, list.append_assoc, list.append_assoc,\n list.map_take, list.map_take,\n list.append_right_inj,\n ←list.append_assoc, ←list.append_assoc, ←list.append_assoc, ←list.append_assoc, ←list.append_assoc,\n list.map_drop, list.map_drop,\n list.append_left_inj,\n list.map_singleton, list.map_singleton, list.join_singleton,\n list.append_left_inj\n ] at hyppp,\n rw list.nth_le_nth mltx,\n apply congr_arg,\n apply wrap_str_inj,\n rw hyppp,\n rw list.map_append_append,\n rw list.map_take,\n rw list.nth_le_map,\n swap, {\n exact mltx,\n },\n rw list.map_drop,\n rw list.map_append_append,\n rw list.map_singleton,\n rw ←list.append_assoc,\n rw ←list.append_assoc,\n apply congr_arg2,\n {\n refl,\n },\n congr,\n exact mm,\nend\n\nprivate lemma case_1_match_rule {g : grammar T} {r₀ : grule T g.nt}\n {x : list (list (symbol T g.nt))} {u v : list (ns T g.nt)}\n (hyp : Z :: (list.join (list.map (++ [H]) (list.map (list.map wrap_sym) x))) =\n u ++ list.map wrap_sym r₀.input_L ++ [symbol.nonterminal (sum.inl r₀.input_N)] ++\n list.map wrap_sym r₀.input_R ++ v) :\n ∃ m : ℕ, ∃ u₁ v₁ : list (symbol T g.nt),\n u = Z :: list.join (list.map (++ [H]) (list.take m (list.map (list.map wrap_sym) x))) ++ list.map wrap_sym u₁\n ∧ list.nth x m = some (u₁ ++ r₀.input_L ++ [symbol.nonterminal r₀.input_N] ++ r₀.input_R ++ v₁) ∧\n v = list.map wrap_sym v₁ ++ [H] ++\n list.join (list.map (++ [H]) (list.drop m.succ (list.map (list.map wrap_sym) x))) :=\nbegin\n by_cases is_x_nil : x = [],\n {\n exfalso,\n rw [is_x_nil, list.map_nil, list.map_nil, list.join] at hyp,\n have hyp_len := congr_arg list.length hyp,\n rw list.length_singleton at hyp_len,\n repeat {\n rw list.length_append at hyp_len,\n },\n rw list.length_singleton at hyp_len,\n have left_nil : u ++ list.map wrap_sym r₀.input_L = [],\n {\n rw ←list.length_eq_zero,\n rw list.length_append,\n omega,\n },\n have right_nil : list.map wrap_sym r₀.input_R ++ v = [],\n {\n rw ←list.length_eq_zero,\n rw list.length_append,\n omega,\n },\n rw [left_nil, list.nil_append, list.append_assoc, right_nil, list.append_nil] at hyp,\n have imposs := list.head_eq_of_cons_eq hyp,\n unfold Z at imposs,\n rw symbol.nonterminal.inj_eq at imposs,\n exact sum.no_confusion imposs,\n },\n have unn : u ≠ [],\n {\n by_contradiction u_nil,\n rw [u_nil, list.nil_append] at hyp,\n cases r₀.input_L with d l,\n {\n rw [list.map_nil, list.nil_append] at hyp,\n have imposs := list.head_eq_of_cons_eq hyp,\n have inr_eq_inl := symbol.nonterminal.inj imposs,\n exact sum.no_confusion inr_eq_inl,\n },\n {\n rw list.map_cons at hyp,\n have imposs := list.head_eq_of_cons_eq hyp,\n cases d,\n {\n unfold wrap_sym at imposs,\n exact symbol.no_confusion imposs,\n },\n {\n unfold wrap_sym at imposs,\n have inr_eq_inl := symbol.nonterminal.inj imposs,\n exact sum.no_confusion inr_eq_inl,\n },\n },\n },\n have hypr := congr_arg list.tail hyp,\n rw list.tail at hypr,\n repeat {\n rw list.append_assoc at hypr,\n },\n rw list.tail_append_of_ne_nil _ _ unn at hypr,\n repeat {\n rw ←list.append_assoc at hypr,\n },\n rcases cases_1_and_2_and_3a_match_aux is_x_nil hypr with ⟨m, u₁, v₁, u_eq, xm_eq, v_eq⟩,\n use [m, u₁, v₁],\n split,\n {\n cases u with d l,\n {\n exfalso,\n exact unn rfl,\n },\n have headZ : d = Z,\n {\n repeat {\n rw list.cons_append at hyp,\n },\n exact list.head_eq_of_cons_eq hyp.symm,\n },\n rw headZ,\n rw list.tail at u_eq,\n rw u_eq,\n apply list.cons_append,\n },\n split,\n {\n exact xm_eq,\n },\n {\n exact v_eq,\n },\nend\n\nprivate lemma star_case_1 {g : grammar T} {α α' : list (ns T g.nt)}\n (orig : grammar_transforms (star_grammar g) α α')\n (hyp : ∃ x : list (list (symbol T g.nt)),\n (∀ xᵢ ∈ x, grammar_derives g [symbol.nonterminal g.initial] xᵢ) ∧\n (α = [Z] ++ list.join (list.map (++ [H]) (list.map (list.map wrap_sym) x)))) :\n (∃ x : list (list (symbol T g.nt)),\n (∀ xᵢ ∈ x, grammar_derives g [symbol.nonterminal g.initial] xᵢ) ∧\n (α' = [Z] ++ list.join (list.map (++ [H]) (list.map (list.map wrap_sym) x)))) ∨\n (∃ x : list (list (symbol T g.nt)),\n (∀ xᵢ ∈ x, grammar_derives g [symbol.nonterminal g.initial] xᵢ) ∧\n (α' = [R, H] ++ list.join (list.map (++ [H]) (list.map (list.map wrap_sym) x)))) :=\nbegin\n rcases hyp with ⟨x, valid, cat⟩,\n have no_R_in_alpha : R ∉ α,\n {\n intro contr,\n rw cat at contr,\n clear_except contr,\n rw list.mem_append at contr,\n cases contr,\n {\n rw list.mem_singleton at contr,\n exact Z_neq_R.symm contr,\n },\n {\n exact R_not_in_join_mpHmmw contr,\n },\n },\n rw cat at *,\n clear cat,\n rcases orig with ⟨r, rin, u, v, bef, aft⟩,\n\n cases rin,\n {\n left,\n rw rin at *,\n clear rin,\n dsimp only at *,\n rw [list.append_nil, list.append_nil] at bef,\n use ([symbol.nonterminal g.initial] :: x),\n split,\n {\n intros xᵢ xin,\n cases xin,\n {\n rw xin,\n apply grammar_deri_self,\n },\n {\n exact valid xᵢ xin,\n },\n },\n have u_nil : u = [],\n {\n clear_except bef,\n rw ←list.length_eq_zero,\n by_contradiction,\n have ul_pos : 0 < u.length,\n {\n rwa pos_iff_ne_zero,\n },\n clear h,\n have bef_tail := congr_arg list.tail bef,\n cases u with d l,\n {\n rw list.length at ul_pos,\n exact nat.lt_irrefl 0 ul_pos,\n },\n {\n have Z_in_tail : Z ∈ l ++ [symbol.nonterminal (sum.inr 0)] ++ v,\n {\n apply list.mem_append_left,\n apply list.mem_append_right,\n apply list.mem_singleton_self,\n },\n rw [list.singleton_append, list.tail_cons, list.cons_append, list.cons_append, list.tail_cons] at bef_tail,\n rw ←bef_tail at Z_in_tail,\n exact Z_not_in_join_mpHmmw Z_in_tail,\n },\n },\n have v_rest : v = list.join (list.map (++ [H]) (list.map (list.map wrap_sym) x)),\n {\n rw u_nil at bef,\n convert congr_arg list.tail bef.symm,\n },\n rw aft,\n rw [u_nil, v_rest],\n rw [list.nil_append, list.map_cons],\n refl,\n },\n cases rin,\n {\n right,\n rw rin at *,\n clear rin,\n dsimp only at *,\n rw [list.append_nil, list.append_nil] at bef,\n use x,\n split,\n {\n exact valid,\n },\n have u_nil : u = [],\n {\n clear_except bef,\n rw ←list.length_eq_zero,\n by_contradiction,\n have ul_pos : 0 < u.length,\n {\n rwa pos_iff_ne_zero,\n },\n clear h,\n have bef_tail := congr_arg list.tail bef,\n cases u with d l,\n {\n rw list.length at ul_pos,\n exact nat.lt_irrefl 0 ul_pos,\n },\n {\n have Z_in_tail : Z ∈ l ++ [symbol.nonterminal (sum.inr 0)] ++ v,\n {\n apply list.mem_append_left,\n apply list.mem_append_right,\n apply list.mem_singleton_self,\n },\n rw [list.singleton_append, list.tail_cons, list.cons_append, list.cons_append, list.tail_cons] at bef_tail,\n rw ←bef_tail at Z_in_tail,\n exact Z_not_in_join_mpHmmw Z_in_tail,\n },\n },\n have v_rest : v = list.join (list.map (++ [H]) (list.map (list.map wrap_sym) x)),\n {\n rw u_nil at bef,\n convert congr_arg list.tail bef.symm,\n },\n rw aft,\n rw [u_nil, v_rest],\n refl,\n },\n iterate 2 {\n cases rin,\n {\n exfalso,\n apply no_R_in_alpha,\n rw bef,\n apply list.mem_append_left,\n apply list.mem_append_left,\n apply list.mem_append_right,\n rw list.mem_singleton,\n rw rin,\n refl,\n },\n },\n have rin' : r ∈ rules_that_scan_terminals g ∨ r ∈ list.map wrap_gr g.rules,\n {\n rw or_comm,\n rwa ←list.mem_append,\n },\n clear rin,\n cases rin',\n {\n exfalso,\n apply no_R_in_alpha,\n rw bef,\n apply list.mem_append_left,\n apply list.mem_append_left,\n apply list.mem_append_right,\n rw list.mem_singleton,\n unfold rules_that_scan_terminals at rin',\n rw list.mem_map at rin',\n rcases rin' with ⟨t, -, form⟩,\n rw ←form,\n refl,\n },\n left,\n rw list.mem_map at rin',\n rcases rin' with ⟨r₀, orig_in, wrap_orig⟩,\n unfold wrap_gr at wrap_orig,\n rw ←wrap_orig at *,\n clear wrap_orig,\n dsimp only at *,\n rcases case_1_match_rule bef with ⟨m, u₁, v₁, u_eq, xm_eq, v_eq⟩,\n clear bef,\n rw [u_eq, v_eq] at aft,\n use (list.take m x ++ [u₁ ++ r₀.output_string ++ v₁] ++ list.drop m.succ x),\n split,\n {\n intros xᵢ xiin,\n rw list.mem_append_append at xiin,\n cases xiin,\n {\n apply valid,\n exact list.mem_of_mem_take xiin,\n },\n cases xiin,\n swap, {\n apply valid,\n exact list.mem_of_mem_drop xiin,\n },\n rw list.mem_singleton at xiin,\n rw xiin,\n have last_step :\n grammar_transforms g\n (u₁ ++ r₀.input_L ++ [symbol.nonterminal r₀.input_N] ++ r₀.input_R ++ v₁)\n (u₁ ++ r₀.output_string ++ v₁),\n {\n use r₀,\n split,\n {\n exact orig_in,\n },\n use [u₁, v₁],\n split;\n refl,\n },\n apply grammar_deri_of_deri_tran _ last_step,\n apply valid (u₁ ++ r₀.input_L ++ [symbol.nonterminal r₀.input_N] ++ r₀.input_R ++ v₁),\n exact list.nth_mem xm_eq,\n },\n rw list.singleton_append,\n rw aft,\n repeat {\n rw list.cons_append,\n },\n apply congr_arg2,\n {\n refl,\n },\n repeat {\n rw list.map_append,\n },\n rw list.join_append_append,\n repeat {\n rw list.append_assoc,\n },\n apply congr_arg2,\n {\n rw ←list.map_take,\n },\n repeat {\n rw ←list.append_assoc,\n },\n apply congr_arg2,\n swap, {\n rw ←list.map_drop,\n },\n rw [\n list.map_singleton, list.map_singleton, list.join_singleton,\n list.map_append, list.map_append\n ],\nend\n\nprivate lemma uv_nil_of_RH_eq {g : grammar T} {u v : list (ns T g.nt)}\n (ass : [R, H] = u ++ [] ++ [symbol.nonterminal (sum.inr 2)] ++ [H] ++ v) :\n u = [] ∧ v = [] :=\nbegin\n rw list.append_nil at ass,\n have lens := congr_arg list.length ass,\n simp only [list.length_append, list.length, zero_add] at lens,\n split;\n {\n rw ←list.length_eq_zero,\n omega,\n },\nend\n\nprivate lemma u_nil_when_RH {g : grammar T} {x : list (list (symbol T g.nt))} {u v : list (ns T g.nt)}\n (ass :\n [R, H] ++ (list.map (++ [H]) (list.map (list.map wrap_sym) x)).join =\n u ++ [] ++ [symbol.nonterminal (sum.inr 2)] ++ [H] ++ v\n ) :\n u = [] :=\nbegin\n cases u with d l,\n {\n refl,\n },\n rw list.append_nil at ass,\n exfalso,\n by_cases d = R,\n {\n rw h at ass,\n clear h,\n classical,\n have imposs, { dsimp_result { exact congr_arg (λ c : list (ns T g.nt), list.count_in c R) ass } },\n repeat {\n rw list.count_in_append at imposs,\n },\n repeat {\n rw list.count_in_cons at imposs,\n },\n repeat {\n rw list.count_in_nil at imposs,\n },\n have one_imposs : 1 + (0 + 0) + 0 = 1 + list.count_in l R + (1 + 0) + (0 + 0) + list.count_in v R,\n {\n convert imposs,\n {\n norm_num,\n },\n {\n simp [H_neq_R],\n },\n {\n symmetry,\n apply zero_Rs_in_the_long_part,\n },\n {\n norm_num,\n },\n {\n simp [R],\n },\n {\n simp [H_neq_R],\n },\n },\n clear_except one_imposs,\n repeat {\n rw add_zero at one_imposs,\n },\n linarith,\n },\n {\n apply h,\n clear h,\n have impos := congr_fun (congr_arg list.nth ass) 0,\n iterate 4 {\n rw list.nth_append at impos,\n swap, {\n norm_num,\n },\n },\n rw list.nth at impos,\n rw list.nth at impos,\n exact (option.some.inj impos).symm,\n },\nend\n\nprivate lemma case_2_match_rule {g : grammar T} {r₀ : grule T g.nt}\n {x : list (list (symbol T g.nt))} {u v : list (ns T g.nt)}\n (hyp : R :: H :: (list.join (list.map (++ [H]) (list.map (list.map wrap_sym) x))) =\n u ++ list.map wrap_sym r₀.input_L ++ [symbol.nonterminal (sum.inl r₀.input_N)] ++\n list.map wrap_sym r₀.input_R ++ v) :\n ∃ m : ℕ, ∃ u₁ v₁ : list (symbol T g.nt),\n u = R :: H :: list.join (list.map (++ [H]) (list.take m (list.map (list.map wrap_sym) x))) ++ list.map wrap_sym u₁\n ∧ list.nth x m = some (u₁ ++ r₀.input_L ++ [symbol.nonterminal r₀.input_N] ++ r₀.input_R ++ v₁) ∧\n v = list.map wrap_sym v₁ ++ [H] ++\n list.join (list.map (++ [H]) (list.drop m.succ (list.map (list.map wrap_sym) x))) :=\nbegin\n by_cases is_x_nil : x = [],\n {\n exfalso,\n rw [is_x_nil, list.map_nil, list.map_nil, list.join] at hyp,\n have imposs : symbol.nonterminal (sum.inl r₀.input_N) = R ∨ symbol.nonterminal (sum.inl r₀.input_N) = H,\n {\n simpa using congr_arg (λ l, symbol.nonterminal (sum.inl r₀.input_N) ∈ l) hyp,\n },\n cases imposs;\n exact sum.no_confusion (symbol.nonterminal.inj imposs),\n },\n have unn : u ≠ [],\n {\n by_contradiction u_nil,\n rw [u_nil, list.nil_append] at hyp,\n cases r₀.input_L with d l,\n {\n rw [list.map_nil, list.nil_append] at hyp,\n have imposs := list.head_eq_of_cons_eq hyp,\n have inr_eq_inl := symbol.nonterminal.inj imposs,\n exact sum.no_confusion inr_eq_inl,\n },\n {\n rw list.map_cons at hyp,\n have imposs := list.head_eq_of_cons_eq hyp,\n cases d,\n {\n unfold wrap_sym at imposs,\n exact symbol.no_confusion imposs,\n },\n {\n unfold wrap_sym at imposs,\n have inr_eq_inl := symbol.nonterminal.inj imposs,\n exact sum.no_confusion inr_eq_inl,\n },\n },\n },\n have hypt := congr_arg list.tail hyp,\n rw list.tail at hypt,\n repeat {\n rw list.append_assoc at hypt,\n },\n rw list.tail_append_of_ne_nil _ _ unn at hypt,\n have utnn : u.tail ≠ [],\n {\n by_contradiction ut_nil,\n rw [ut_nil, list.nil_append] at hypt,\n cases r₀.input_L with d l,\n {\n rw [list.map_nil, list.nil_append] at hypt,\n have imposs := list.head_eq_of_cons_eq hypt,\n have inr_eq_inl := symbol.nonterminal.inj imposs,\n exact sum.no_confusion inr_eq_inl,\n },\n {\n rw list.map_cons at hypt,\n have imposs := list.head_eq_of_cons_eq hypt,\n cases d,\n {\n unfold wrap_sym at imposs,\n exact symbol.no_confusion imposs,\n },\n {\n unfold wrap_sym at imposs,\n have inr_eq_inl := symbol.nonterminal.inj imposs,\n exact sum.no_confusion inr_eq_inl,\n },\n },\n },\n have hyptt := congr_arg list.tail hypt,\n rw list.tail at hyptt,\n rw list.tail_append_of_ne_nil _ _ utnn at hyptt,\n repeat {\n rw ←list.append_assoc at hyptt,\n },\n rcases cases_1_and_2_and_3a_match_aux is_x_nil hyptt with ⟨m, u₁, v₁, u_eq, xm_eq, v_eq⟩,\n use [m, u₁, v₁],\n split,\n {\n cases u with d l,\n {\n exfalso,\n exact unn rfl,\n },\n have headR : d = R,\n {\n repeat {\n rw list.cons_append at hyp,\n },\n exact list.head_eq_of_cons_eq hyp.symm,\n },\n rw list.tail at u_eq,\n rw list.tail at hypt,\n cases l with d' l',\n {\n exfalso,\n exact utnn rfl,\n },\n have tailHead : d' = H,\n {\n repeat {\n rw list.cons_append at hypt,\n },\n exact list.head_eq_of_cons_eq hypt.symm,\n },\n rw list.tail at u_eq,\n rw [headR, tailHead, u_eq, list.cons_append, list.cons_append],\n },\n split,\n {\n exact xm_eq,\n },\n {\n exact v_eq,\n },\nend\n\nprivate lemma star_case_2 {g : grammar T} {α α' : list (symbol T (star_grammar g).nt)}\n (orig : grammar_transforms (star_grammar g) α α')\n (hyp : ∃ x : list (list (symbol T g.nt)),\n (∀ xᵢ ∈ x, grammar_derives g [symbol.nonterminal g.initial] xᵢ) ∧\n (α = [R, H] ++ list.join (list.map (++ [H]) (list.map (list.map wrap_sym) x)))) :\n (∃ x : list (list (symbol T g.nt)),\n (∀ xᵢ ∈ x, grammar_derives g [symbol.nonterminal g.initial] xᵢ) ∧\n (α' = [R, H] ++ list.join (list.map (++ [H]) (list.map (list.map wrap_sym) x)))) ∨\n (∃ w : list (list T), ∃ β : list T, ∃ γ : list (symbol T g.nt), ∃ x : list (list (symbol T g.nt)),\n (∀ wᵢ ∈ w, grammar_generates g wᵢ) ∧\n (grammar_derives g [symbol.nonterminal g.initial] (list.map symbol.terminal β ++ γ)) ∧\n (∀ xᵢ ∈ x, grammar_derives g [symbol.nonterminal g.initial] xᵢ) ∧\n (α' = list.map symbol.terminal (list.join w) ++ list.map symbol.terminal β ++ [R] ++\n list.map wrap_sym γ ++ [H] ++ list.join (list.map (++ [H]) (list.map (list.map wrap_sym) x)))) ∨\n (∃ u : list T, u ∈ language.star (grammar_language g) ∧ α' = list.map symbol.terminal u) ∨\n (∃ σ : list (symbol T g.nt), α' = list.map wrap_sym σ ++ [R]) ∨\n (∃ ω : list (ns T g.nt), α' = ω ++ [H]) ∧ Z ∉ α' ∧ R ∉ α' :=\nbegin\n rcases hyp with ⟨x, valid, cat⟩,\n have no_Z_in_alpha : Z ∉ α,\n {\n intro contr,\n rw cat at contr,\n clear_except contr,\n rw list.mem_append at contr,\n cases contr,\n {\n cases contr,\n {\n exact Z_neq_R contr,\n },\n {\n apply Z_neq_H,\n rw ←list.mem_singleton,\n exact contr,\n },\n },\n {\n exact Z_not_in_join_mpHmmw contr,\n },\n },\n rw cat at *,\n clear cat,\n rcases orig with ⟨r, rin, u, v, bef, aft⟩,\n\n iterate 2 {\n cases rin,\n {\n exfalso,\n apply no_Z_in_alpha,\n rw bef,\n apply list.mem_append_left,\n apply list.mem_append_left,\n apply list.mem_append_right,\n rw list.mem_singleton,\n rw rin,\n refl,\n },\n },\n cases rin,\n {\n cases x with x₀ L,\n {\n right, right, right,\n rw [list.map_nil, list.map_nil, list.join, list.append_nil] at bef,\n have empty_string : u = [] ∧ v = [],\n {\n rw rin at bef,\n exact uv_nil_of_RH_eq bef,\n },\n rw [empty_string.left, list.nil_append, empty_string.right, list.append_nil] at aft,\n use list.nil,\n rw aft,\n rw [list.map_nil, list.nil_append],\n rw rin,\n },\n {\n right, left,\n use [[], [], x₀, L],\n split,\n {\n intros wᵢ wiin,\n exfalso,\n rw list.mem_nil_iff at wiin,\n exact wiin,\n },\n split,\n {\n rw [list.map_nil, list.nil_append],\n exact valid x₀ (list.mem_cons_self x₀ L),\n },\n split,\n {\n intros xᵢ xiin,\n exact valid xᵢ (list.mem_cons_of_mem x₀ xiin),\n },\n rw aft,\n rw [list.map_nil, list.append_nil, list.join, list.map_nil, list.nil_append],\n rw rin at bef ⊢,\n dsimp only at bef ⊢,\n have u_nil := u_nil_when_RH bef,\n rw [u_nil, list.nil_append] at bef ⊢,\n have eq_v := list.append_inj_right bef (by refl),\n rw ←eq_v,\n rw [list.map_cons, list.map_cons, list.join],\n rw [←list.append_assoc, ←list.append_assoc],\n },\n },\n cases rin,\n {\n cases x with x₀ L,\n {\n right, right, left,\n rw [list.map_nil, list.map_nil, list.join, list.append_nil] at bef,\n have empty_string : u = [] ∧ v = [],\n {\n rw rin at bef,\n exact uv_nil_of_RH_eq bef,\n },\n rw [empty_string.left, list.nil_append, empty_string.right, list.append_nil] at aft,\n use list.nil,\n split,\n {\n use list.nil,\n split,\n {\n refl,\n },\n {\n intros y imposs,\n exfalso,\n exact list.not_mem_nil y imposs,\n },\n },\n {\n rw aft,\n rw list.map_nil,\n rw rin,\n },\n },\n {\n right, right, right, right,\n rw rin at bef,\n dsimp only at bef,\n have u_nil := u_nil_when_RH bef,\n rw [u_nil, list.nil_append] at bef,\n have v_eq := eq.symm (list.append_inj_right bef (by refl)),\n rw [\n u_nil, list.nil_append, v_eq, rin, list.nil_append,\n list.map_cons, list.map_cons, list.join,\n list.append_assoc, list.append_join_append, ←list.append_assoc\n ] at aft,\n split,\n {\n use list.map wrap_sym x₀ ++ (list.map (λ l, [H] ++ l) (list.map (list.map wrap_sym) L)).join,\n rw aft,\n trim,\n },\n rw [list.append_assoc, ←list.append_join_append] at aft,\n rw aft,\n split;\n intro contra;\n rw list.mem_append at contra,\n {\n cases contra,\n {\n exact map_wrap_never_contains_Z contra,\n },\n cases contra,\n {\n exact Z_neq_H contra,\n },\n {\n exact Z_not_in_join_mpHmmw contra,\n },\n },\n {\n cases contra,\n {\n exact map_wrap_never_contains_R contra,\n },\n cases contra,\n {\n exact H_neq_R contra.symm,\n },\n {\n exact R_not_in_join_mpHmmw contra,\n },\n },\n },\n },\n have rin' : r ∈ rules_that_scan_terminals g ∨ r ∈ list.map wrap_gr g.rules,\n {\n rw or_comm,\n rwa ←list.mem_append,\n },\n clear rin,\n cases rin',\n {\n exfalso,\n unfold rules_that_scan_terminals at rin',\n rw list.mem_map at rin',\n rcases rin' with ⟨t, -, form⟩,\n rw ←form at bef,\n dsimp only at bef,\n rw list.append_nil at bef,\n have u_nil : u = [],\n {\n cases u with d l,\n {\n refl,\n },\n exfalso,\n repeat {\n rw list.cons_append at bef,\n },\n rw list.nil_append at bef,\n have btail := list.tail_eq_of_cons_eq bef,\n have imposs := congr_arg (λ l, R ∈ l) btail,\n dsimp only at imposs,\n apply false_of_true_eq_false,\n convert imposs.symm,\n {\n rw [eq_iff_iff, true_iff],\n apply list.mem_append_left,\n apply list.mem_append_left,\n apply list.mem_append_right,\n apply list.mem_singleton_self,\n },\n {\n rw [eq_iff_iff, false_iff],\n intro hyp,\n rw list.mem_cons_iff at hyp,\n cases hyp,\n {\n exact H_neq_R hyp.symm,\n },\n rw list.mem_join at hyp,\n rcases hyp with ⟨p, pin, Rinp⟩,\n rw list.mem_map at pin,\n rcases pin with ⟨q, qin, eq_p⟩,\n rw ←eq_p at Rinp,\n rw list.mem_append at Rinp,\n cases Rinp,\n {\n rw list.mem_map at qin,\n rcases qin with ⟨p', -, eq_q⟩,\n rw ←eq_q at Rinp,\n exact map_wrap_never_contains_R Rinp,\n },\n {\n rw list.mem_singleton at Rinp,\n exact H_neq_R Rinp.symm,\n },\n },\n },\n rw [u_nil, list.nil_append] at bef,\n have second_symbol := congr_fun (congr_arg list.nth bef) 1,\n rw list.nth_append at second_symbol,\n swap, {\n rw [list.length_cons, list.length_singleton],\n exact lt_add_one 1,\n },\n rw list.nth_append at second_symbol,\n swap, {\n rw [list.length_append, list.length_singleton, list.length_singleton],\n exact lt_add_one 1,\n },\n rw list.singleton_append at second_symbol,\n repeat {\n rw list.nth at second_symbol,\n },\n exact symbol.no_confusion (option.some.inj second_symbol),\n },\n left,\n rw list.mem_map at rin',\n rcases rin' with ⟨r₀, orig_in, wrap_orig⟩,\n unfold wrap_gr at wrap_orig,\n rw ←wrap_orig at *,\n clear wrap_orig,\n dsimp only at bef,\n rcases case_2_match_rule bef with ⟨m, u₁, v₁, u_eq, xm_eq, v_eq⟩,\n clear bef,\n rw [u_eq, v_eq] at aft,\n use (list.take m x ++ [u₁ ++ r₀.output_string ++ v₁] ++ list.drop m.succ x),\n split,\n {\n intros xᵢ xiin,\n rw list.mem_append_append at xiin,\n cases xiin,\n {\n apply valid,\n exact list.mem_of_mem_take xiin,\n },\n cases xiin,\n swap, {\n apply valid,\n exact list.mem_of_mem_drop xiin,\n },\n rw list.mem_singleton at xiin,\n rw xiin,\n have last_step :\n grammar_transforms g\n (u₁ ++ r₀.input_L ++ [symbol.nonterminal r₀.input_N] ++ r₀.input_R ++ v₁)\n (u₁ ++ r₀.output_string ++ v₁),\n {\n use r₀,\n split,\n {\n exact orig_in,\n },\n use [u₁, v₁],\n split;\n refl,\n },\n apply grammar_deri_of_deri_tran _ last_step,\n apply valid (u₁ ++ r₀.input_L ++ [symbol.nonterminal r₀.input_N] ++ r₀.input_R ++ v₁),\n exact list.nth_mem xm_eq,\n },\n rw aft,\n repeat {\n rw list.cons_append,\n },\n apply congr_arg2,\n {\n refl,\n },\n repeat {\n rw list.map_append,\n },\n rw list.join_append_append,\n repeat {\n rw list.append_assoc,\n },\n apply congr_arg2,\n {\n refl,\n },\n rw list.nil_append,\n apply congr_arg2,\n {\n rw ←list.map_take,\n refl,\n },\n simp [list.map, list.join, list.singleton_append, list.map_append, list.append_assoc, list.map_map, list.map_drop],\nend\n\nprivate lemma case_3_ni_wb {g : grammar T} {w : list (list T)} {β : list T} {i : fin 3} :\n @symbol.nonterminal T (nn g.nt) (sum.inr i) ∉\n list.map (@symbol.terminal T (nn g.nt)) w.join ++ list.map (@symbol.terminal T (nn g.nt)) β :=\nbegin\n intro contra,\n rw list.mem_append at contra,\n cases contra;\n {\n rw list.mem_map at contra,\n rcases contra with ⟨t, -, imposs⟩,\n exact symbol.no_confusion imposs,\n },\nend\n\nprivate lemma case_3_ni_u {g : grammar T}\n {w : list (list T)} {β : list T} {γ : list (symbol T g.nt)}\n {x : list (list (symbol T g.nt))} {u v : list (ns T g.nt)} {s : ns T g.nt}\n (ass :\n list.map symbol.terminal w.join ++ list.map symbol.terminal β ++ [R] ++ list.map wrap_sym γ ++ [H] ++\n (list.map (++ [H]) (list.map (list.map wrap_sym) x)).join =\n u ++ [R] ++ [s] ++ v\n ) :\n R ∉ u :=\nbegin\n intro R_in_u,\n classical,\n have count_R := congr_arg (λ l, list.count_in l R) ass,\n dsimp only at count_R,\n repeat {\n rw list.count_in_append at count_R,\n },\n have R_ni_wb : R ∉ list.map symbol.terminal w.join ++ list.map symbol.terminal β,\n {\n apply @case_3_ni_wb T g,\n },\n rw list.count_in_singleton_eq at count_R,\n rw [list.count_in_singleton_neq H_neq_R, add_zero] at count_R,\n rw ←list.count_in_append at count_R,\n rw [list.count_in_zero_of_notin R_ni_wb, zero_add] at count_R,\n rw [list.count_in_zero_of_notin map_wrap_never_contains_R, add_zero] at count_R,\n rw [zero_Rs_in_the_long_part, add_zero] at count_R,\n have ucR_pos := list.count_in_pos_of_in R_in_u,\n clear_except count_R ucR_pos,\n linarith,\nend\n\nprivate lemma case_3_u_eq_left_side {g : grammar T}\n {w : list (list T)} {β : list T} {γ : list (symbol T g.nt)}\n {x : list (list (symbol T g.nt))} {u v : list (ns T g.nt)} {s : ns T g.nt}\n (ass :\n list.map symbol.terminal w.join ++ list.map symbol.terminal β ++ [R] ++ list.map wrap_sym γ ++ [H] ++\n list.join (list.map (++ [H]) (list.map (list.map wrap_sym) x)) =\n u ++ [symbol.nonterminal (sum.inr 2)] ++ [s] ++ v\n ) :\n u = list.map symbol.terminal w.join ++ list.map (@symbol.terminal T (nn g.nt)) β :=\nbegin\n have R_ni_u : R ∉ u,\n {\n exact case_3_ni_u ass,\n },\n have R_ni_wb : R ∉ list.map symbol.terminal w.join ++ list.map symbol.terminal β,\n {\n apply @case_3_ni_wb T g,\n },\n repeat {\n rw list.append_assoc at ass,\n },\n convert congr_arg (list.take u.length) ass.symm,\n {\n rw list.take_left,\n },\n rw ←list.append_assoc,\n rw list.take_left',\n {\n classical,\n have index_of_first_R := congr_arg (list.index_of R) ass,\n rw list.index_of_append_of_notin R_ni_u at index_of_first_R,\n rw @list.singleton_append _ _ ([s] ++ v) at index_of_first_R,\n rw [←R, list.index_of_cons_self, add_zero] at index_of_first_R,\n rw [←list.append_assoc, list.index_of_append_of_notin R_ni_wb] at index_of_first_R,\n rw [list.singleton_append, list.index_of_cons_self, add_zero] at index_of_first_R,\n exact index_of_first_R,\n },\nend\n\nprivate lemma case_3_gamma_nil {g : grammar T}\n {w : list (list T)} {β : list T} {γ : list (symbol T g.nt)}\n {x : list (list (symbol T g.nt))} {u v : list (ns T g.nt)}\n (ass :\n list.map symbol.terminal w.join ++ list.map symbol.terminal β ++ [symbol.nonterminal (sum.inr 2)] ++\n list.map wrap_sym γ ++ [H] ++ list.join (list.map (++ [H]) (list.map (list.map wrap_sym) x)) =\n u ++ [symbol.nonterminal (sum.inr 2)] ++ [H] ++ v\n ) :\n γ = [] :=\nbegin\n have R_ni_wb : R ∉ list.map symbol.terminal w.join ++ list.map symbol.terminal β,\n {\n apply @case_3_ni_wb T g,\n },\n have H_ni_wb : H ∉ list.map symbol.terminal w.join ++ list.map symbol.terminal β,\n {\n apply @case_3_ni_wb T g,\n },\n have H_ni_wbrg : H ∉\n list.map (@symbol.terminal T (nn g.nt)) w.join ++ list.map symbol.terminal β ++\n [symbol.nonterminal (sum.inr 2)] ++ list.map wrap_sym γ,\n {\n intro contra,\n rw list.mem_append at contra,\n cases contra,\n swap, {\n exact map_wrap_never_contains_H contra,\n },\n rw list.mem_append at contra,\n cases contra,\n {\n exact H_ni_wb contra,\n },\n {\n rw list.mem_singleton at contra,\n exact H_neq_R contra,\n },\n },\n have R_ni_u : @symbol.nonterminal T (nn g.nt) (sum.inr 2) ∉ u,\n {\n exact case_3_ni_u ass,\n },\n have H_ni_u : H ∉ u,\n {\n rw case_3_u_eq_left_side ass,\n exact H_ni_wb,\n },\n classical,\n have first_R := congr_arg (list.index_of R) ass,\n have first_H := congr_arg (list.index_of H) ass,\n repeat {\n rw list.append_assoc (list.map symbol.terminal w.join ++ list.map symbol.terminal β) at first_R,\n },\n rw list.append_assoc\n (list.map symbol.terminal w.join ++ list.map symbol.terminal β ++\n [symbol.nonterminal (sum.inr 2)] ++ list.map wrap_sym γ)\n at first_H,\n rw list.index_of_append_of_notin R_ni_wb at first_R,\n rw list.index_of_append_of_notin H_ni_wbrg at first_H,\n rw [list.cons_append, list.cons_append, list.cons_append, R, list.index_of_cons_self, add_zero] at first_R,\n rw [list.cons_append, list.index_of_cons_self, add_zero] at first_H,\n rw [list.append_assoc u, list.append_assoc u] at first_R first_H,\n rw list.index_of_append_of_notin R_ni_u at first_R,\n rw list.index_of_append_of_notin H_ni_u at first_H,\n rw [list.append_assoc _ [H], list.singleton_append, list.index_of_cons_self, add_zero] at first_R,\n rw [list.append_assoc _ [H], list.singleton_append, ←R, list.index_of_cons_ne _ H_neq_R] at first_H,\n rw [list.singleton_append, H, list.index_of_cons_self] at first_H,\n rw ←first_R at first_H,\n clear_except first_H,\n repeat {\n rw list.length_append at first_H,\n },\n rw list.length_singleton at first_H,\n rw ←add_zero ((list.map symbol.terminal w.join).length + (list.map symbol.terminal β).length + 1) at first_H,\n rw add_right_inj at first_H,\n rw list.length_map at first_H,\n rw list.length_eq_zero at first_H,\n exact first_H,\nend\n\nprivate lemma case_3_v_nil {g : grammar T}\n {w : list (list T)} {β : list T} {u v : list (ns T g.nt)}\n (ass :\n list.map symbol.terminal w.join ++ list.map symbol.terminal β ++ [R] ++ [H] =\n u ++ [symbol.nonterminal (sum.inr 2)] ++ [H] ++ v\n ) :\n v = [] :=\nbegin\n have rev := congr_arg list.reverse ass,\n repeat {\n rw list.reverse_append at rev,\n },\n repeat {\n rw list.reverse_singleton at rev,\n },\n rw ←list.reverse_eq_nil,\n cases v.reverse with d l,\n {\n refl,\n },\n exfalso,\n rw list.singleton_append at rev,\n have brt := list.tail_eq_of_cons_eq rev,\n have brtt := congr_arg list.tail brt,\n rw list.singleton_append at brtt,\n rw list.tail_cons at brtt,\n cases l with e l',\n {\n change\n (list.map symbol.terminal β).reverse ++ (list.map symbol.terminal w.join).reverse =\n [symbol.nonterminal (sum.inr 2)] ++ u.reverse\n at brtt,\n have imposs := congr_arg (λ a, R ∈ a) brtt,\n dsimp only at imposs,\n apply false_of_true_eq_false,\n convert imposs.symm,\n {\n rw [eq_iff_iff, true_iff],\n apply list.mem_append_left,\n apply list.mem_singleton_self,\n },\n {\n rw [eq_iff_iff, false_iff],\n rw list.mem_append,\n push_neg,\n split;\n {\n rw list.mem_reverse,\n rw list.mem_map,\n push_neg,\n intros t trash,\n apply symbol.no_confusion,\n },\n },\n },\n {\n change _ = _ ++ _ at brtt,\n have imposs := congr_arg (λ a, H ∈ a) brtt,\n dsimp only at imposs,\n apply false_of_true_eq_false,\n convert imposs.symm,\n {\n rw [eq_iff_iff, true_iff],\n apply list.mem_append_right,\n apply list.mem_append_left,\n apply list.mem_singleton_self,\n },\n {\n rw [eq_iff_iff, false_iff],\n rw list.mem_append,\n push_neg,\n split;\n {\n rw list.mem_reverse,\n rw list.mem_map,\n push_neg,\n intros t trash,\n apply symbol.no_confusion,\n },\n },\n },\nend\n\nprivate lemma case_3_false_of_wbr_eq_urz {g : grammar T} {r₀ : grule T g.nt}\n {w : list (list T)} {β : list T} {u z : list (ns T g.nt)}\n (contradictory_equality :\n list.map symbol.terminal w.join ++ list.map symbol.terminal β ++ [R] =\n u ++ list.map wrap_sym r₀.input_L ++ [symbol.nonterminal (sum.inl r₀.input_N)] ++ z) :\n false :=\nbegin\n apply false_of_true_eq_false,\n convert congr_arg ((∈) (symbol.nonterminal (sum.inl r₀.input_N))) contradictory_equality.symm,\n {\n rw [eq_iff_iff, true_iff],\n apply list.mem_append_left,\n apply list.mem_append_right,\n apply list.mem_singleton_self,\n },\n {\n rw [eq_iff_iff, false_iff],\n intro hyp_N_in,\n rw list.mem_append at hyp_N_in,\n cases hyp_N_in,\n swap, {\n rw list.mem_singleton at hyp_N_in,\n exact sum.no_confusion (symbol.nonterminal.inj hyp_N_in),\n },\n rw list.mem_append at hyp_N_in,\n cases hyp_N_in;\n {\n rw list.mem_map at hyp_N_in,\n rcases hyp_N_in with ⟨t, -, impos⟩,\n exact symbol.no_confusion impos,\n },\n },\nend\n\nprivate lemma case_3_match_rule {g : grammar T} {r₀ : grule T g.nt}\n {x : list (list (symbol T g.nt))} {u v : list (ns T g.nt)}\n {w : list (list T)} {β : list T} {γ : list (symbol T g.nt)}\n (hyp :\n list.map symbol.terminal (list.join w) ++ list.map symbol.terminal β ++ [R] ++\n list.map wrap_sym γ ++ [H] ++ list.join (list.map (++ [H]) (list.map (list.map wrap_sym) x)) =\n u ++ list.map wrap_sym r₀.input_L ++ [symbol.nonterminal (sum.inl r₀.input_N)] ++\n list.map wrap_sym r₀.input_R ++ v) :\n (∃ m : ℕ, ∃ u₁ v₁ : list (symbol T g.nt),\n u = list.map symbol.terminal (list.join w) ++ list.map symbol.terminal β ++\n [R] ++ list.map wrap_sym γ ++ [H] ++\n list.join (list.map (++ [H]) (list.take m (list.map (list.map wrap_sym) x))) ++ list.map wrap_sym u₁\n ∧ list.nth x m = some (u₁ ++ r₀.input_L ++ [symbol.nonterminal r₀.input_N] ++ r₀.input_R ++ v₁) ∧\n v = list.map wrap_sym v₁ ++ [H] ++\n list.join (list.map (++ [H]) (list.drop m.succ (list.map (list.map wrap_sym) x)))) ∨\n (∃ u₁ v₁ : list (symbol T g.nt),\n u = list.map symbol.terminal (list.join w) ++ list.map symbol.terminal β ++ [R] ++ list.map wrap_sym u₁\n ∧ γ = u₁ ++ r₀.input_L ++ [symbol.nonterminal r₀.input_N] ++ r₀.input_R ++ v₁ ∧\n v = list.map wrap_sym v₁ ++ [H] ++ list.join (list.map (++ [H]) (list.map (list.map wrap_sym) x))) :=\nbegin\n repeat {\n rw list.append_assoc u at hyp,\n },\n rw list.append_eq_append_iff at hyp,\n cases hyp,\n {\n rcases hyp with ⟨u', u_eq, xj_eq⟩,\n left,\n repeat {\n rw ←list.append_assoc at xj_eq,\n },\n by_cases is_x_nil : x = [],\n {\n exfalso,\n rw [is_x_nil, list.map_nil, list.map_nil, list.join] at xj_eq,\n have imposs := congr_arg list.length xj_eq,\n rw list.length at imposs,\n rw list.length_append_append at imposs,\n rw list.length_append_append at imposs,\n rw list.length_singleton at imposs,\n clear_except imposs,\n linarith,\n },\n rcases cases_1_and_2_and_3a_match_aux is_x_nil xj_eq with ⟨m, u₁, v₁, u'_eq, xm_eq, v_eq⟩,\n use [m, u₁, v₁],\n split,\n {\n rw u_eq,\n rw u'_eq,\n rw ←list.append_assoc,\n },\n split,\n {\n exact xm_eq,\n },\n {\n exact v_eq,\n },\n },\n {\n rcases hyp with ⟨v', left_half, right_half⟩,\n have very_middle :\n [symbol.nonterminal (sum.inl r₀.input_N)] = list.map wrap_sym [symbol.nonterminal r₀.input_N],\n {\n rw list.map_singleton,\n refl,\n },\n cases x with x₀ xₗ,\n {\n rw [list.map_nil, list.map_nil, list.join, list.append_nil] at right_half,\n rw ←right_half at left_half,\n have backwards := congr_arg list.reverse left_half,\n clear right_half left_half,\n right,\n repeat {\n rw list.reverse_append at backwards,\n },\n rw [list.reverse_singleton, list.singleton_append] at backwards,\n rw ←list.reverse_reverse v,\n cases v.reverse with e z,\n {\n exfalso,\n rw list.nil_append at backwards,\n rw ←list.map_reverse _ r₀.input_R at backwards,\n cases r₀.input_R.reverse with d l,\n {\n rw [list.map_nil, list.nil_append] at backwards,\n rw list.reverse_singleton (symbol.nonterminal (sum.inl r₀.input_N)) at backwards,\n rw list.singleton_append at backwards,\n have imposs := list.head_eq_of_cons_eq backwards,\n exact sum.no_confusion (symbol.nonterminal.inj imposs),\n },\n {\n rw [list.map_cons, list.cons_append, list.cons_append] at backwards,\n have imposs := list.head_eq_of_cons_eq backwards,\n exact wrap_never_outputs_H imposs.symm,\n },\n },\n rw [list.cons_append, list.cons_append, list.cons.inj_eq] at backwards,\n cases backwards with He backward,\n rw ←He at *,\n clear He e,\n have forward := congr_arg list.reverse backward,\n clear backward,\n repeat {\n rw list.reverse_append at forward,\n },\n repeat {\n rw list.reverse_reverse at forward,\n },\n rw ←list.append_assoc at forward,\n rw list.append_eq_append_iff at forward,\n cases forward,\n swap, {\n exfalso,\n rcases forward with ⟨a, imposs, -⟩,\n rw list.append_assoc u at imposs,\n rw list.append_assoc _ (list.map wrap_sym r₀.input_R) at imposs,\n rw ←list.append_assoc u at imposs,\n rw ←list.append_assoc u at imposs,\n exact case_3_false_of_wbr_eq_urz imposs,\n },\n rcases forward with ⟨a', left_side, gamma_is⟩,\n repeat {\n rw ←list.append_assoc at left_side,\n },\n rw list.append_eq_append_iff at left_side,\n cases left_side,\n {\n exfalso,\n rcases left_side with ⟨a, imposs, -⟩,\n exact case_3_false_of_wbr_eq_urz imposs,\n },\n rcases left_side with ⟨c', the_left, the_a'⟩,\n rw the_a' at gamma_is,\n clear the_a' a',\n rw list.append_assoc at the_left,\n rw list.append_assoc at the_left,\n rw list.append_eq_append_iff at the_left,\n cases the_left,\n {\n exfalso,\n rcases the_left with ⟨a, -, imposs⟩,\n apply false_of_true_eq_false,\n convert congr_arg ((∈) R) imposs.symm,\n {\n rw [eq_iff_iff, true_iff],\n apply list.mem_append_right,\n apply list.mem_append_left,\n apply list.mem_singleton_self,\n },\n {\n rw [eq_iff_iff, false_iff],\n rw list.mem_append,\n push_neg,\n split,\n {\n rw list.mem_map,\n push_neg,\n intros,\n apply wrap_never_outputs_R,\n },\n {\n rw list.mem_singleton,\n intro impos,\n exact sum.no_confusion (symbol.nonterminal.inj impos),\n },\n },\n },\n rcases the_left with ⟨u₀, u_eq, rule_side⟩,\n rw u_eq at *,\n clear u_eq u,\n have zr_eq : z.reverse = list.drop (c' ++ list.map wrap_sym r₀.input_R).length (list.map wrap_sym γ),\n {\n have gamma_suffix := congr_arg (list.drop (c' ++ list.map wrap_sym r₀.input_R).length) gamma_is,\n rw list.drop_left at gamma_suffix,\n exact gamma_suffix.symm,\n },\n cases u₀ with d l,\n {\n exfalso,\n rw list.nil_append at rule_side,\n cases r₀.input_L with d l,\n {\n rw [list.map_nil, list.nil_append] at rule_side,\n have imposs := list.head_eq_of_cons_eq rule_side,\n exact sum.no_confusion (symbol.nonterminal.inj imposs),\n },\n {\n rw [list.map_cons, list.cons_append] at rule_side,\n have imposs := list.head_eq_of_cons_eq rule_side,\n exact wrap_never_outputs_R imposs.symm,\n },\n },\n rw [list.singleton_append, list.cons_append, list.cons.inj_eq] at rule_side,\n cases rule_side with Rd c'_eq,\n rw ←Rd at *,\n clear Rd d,\n rw c'_eq at gamma_is,\n use [list.take l.length γ, list.drop (c' ++ list.map wrap_sym r₀.input_R).length γ],\n split,\n {\n rw ←list.singleton_append,\n have l_from_gamma := congr_arg (list.take l.length) gamma_is,\n repeat {\n rw list.append_assoc at l_from_gamma,\n },\n rw list.take_left at l_from_gamma,\n rw list.map_take,\n rw l_from_gamma,\n rw ←list.append_assoc,\n },\n split,\n {\n rw c'_eq,\n convert_to list.take l.length γ ++ list.drop l.length γ = _,\n {\n symmetry,\n apply list.take_append_drop,\n },\n trim,\n rw zr_eq at gamma_is,\n rw c'_eq at gamma_is,\n repeat {\n rw list.append_assoc at gamma_is,\n },\n have gamma_minus_initial_l := congr_arg (list.drop l.length) gamma_is,\n rw [list.drop_left, very_middle, ←list.map_drop, ←list.map_drop] at gamma_minus_initial_l,\n repeat {\n rw ←list.map_append at gamma_minus_initial_l,\n },\n rw wrap_str_inj gamma_minus_initial_l,\n trim,\n repeat {\n rw list.length_append,\n },\n repeat {\n rw list.length_map,\n },\n repeat {\n rw list.length_append,\n },\n repeat {\n rw list.length_singleton,\n },\n repeat {\n rw add_assoc,\n },\n },\n {\n rw [list.map_nil, list.map_nil, list.join, list.append_nil],\n rw [list.reverse_cons, zr_eq],\n rw list.map_drop,\n },\n },\n by_cases is_v'_nil : v' = [],\n {\n rw [is_v'_nil, list.nil_append] at right_half,\n rw [is_v'_nil, list.append_nil] at left_half,\n left,\n use [0, [], list.drop (r₀.input_L ++ [symbol.nonterminal r₀.input_N] ++ r₀.input_R).length x₀],\n rw [list.map_cons, list.map_cons, list.join] at right_half,\n split,\n {\n rw [list.map_nil, list.append_nil],\n rw [list.take_zero, list.map_nil, list.join, list.append_nil],\n exact left_half.symm,\n },\n have lengths_trivi :\n list.length (\n list.map wrap_sym r₀.input_L ++ [symbol.nonterminal (sum.inl r₀.input_N)] ++ list.map wrap_sym r₀.input_R\n ) =\n list.length (r₀.input_L ++ [symbol.nonterminal r₀.input_N] ++ r₀.input_R),\n {\n rw [very_middle, ←list.map_append_append],\n apply list.length_map,\n },\n have len_rᵢ_le_len_x₀ :\n (r₀.input_L ++ [symbol.nonterminal r₀.input_N] ++ r₀.input_R).length ≤ (list.map wrap_sym x₀).length,\n {\n classical,\n have first_H := congr_arg (list.index_of H) right_half,\n rw [list.append_assoc _ [H], list.index_of_append_of_notin map_wrap_never_contains_H] at first_H,\n rw [list.singleton_append, list.index_of_cons_self, add_zero] at first_H,\n rw [very_middle, ←list.map_append_append, list.index_of_append_of_notin map_wrap_never_contains_H] at first_H,\n rw list.length_map at first_H,\n exact nat.le.intro first_H,\n },\n split,\n {\n rw list.nth,\n apply congr_arg,\n rw list.nil_append,\n convert_to x₀ =\n list.take (r₀.input_L ++ [symbol.nonterminal r₀.input_N] ++ r₀.input_R).length x₀ ++\n list.drop (r₀.input_L ++ [symbol.nonterminal r₀.input_N] ++ r₀.input_R).length x₀,\n {\n trim,\n apply wrap_str_inj,\n rw list.map_append_append,\n have right_left :=\n congr_arg (list.take (r₀.input_L ++ [symbol.nonterminal r₀.input_N] ++ r₀.input_R).length) right_half,\n rw list.take_left' lengths_trivi at right_left,\n rw [←very_middle, right_left],\n rw list.append_assoc _ [H],\n rw list.take_append_of_le_length len_rᵢ_le_len_x₀,\n rw list.map_take,\n },\n rw list.take_append_drop,\n },\n {\n rw [list.map_cons, list.drop_one, list.tail_cons],\n have right_right :=\n congr_arg (list.drop (r₀.input_L ++ [symbol.nonterminal r₀.input_N] ++ r₀.input_R).length) right_half,\n rw list.drop_left' lengths_trivi at right_right,\n rw right_right,\n rw list.append_assoc _ [H],\n rw list.drop_append_of_le_length len_rᵢ_le_len_x₀,\n rw list.map_drop,\n rw list.append_assoc _ [H],\n refl,\n },\n },\n right,\n obtain ⟨z, v'_eq⟩ : ∃ z, v' =\n list.map wrap_sym r₀.input_L ++ [symbol.nonterminal (sum.inl r₀.input_N)] ++ list.map wrap_sym r₀.input_R ++ z,\n {\n obtain ⟨v'', without_final_H⟩ : ∃ v'', v' = v'' ++ [H],\n {\n rw list.append_eq_append_iff at left_half,\n cases left_half,\n {\n rcases left_half with ⟨a', -, matters⟩,\n use list.nil,\n cases a' with d l,\n {\n rw list.nil_append at matters ⊢,\n exact matters.symm,\n },\n {\n exfalso,\n have imposs := congr_arg list.length matters,\n rw [list.length_singleton, list.length_append, list.length_cons] at imposs,\n have right_pos := length_ge_one_of_not_nil is_v'_nil,\n clear_except imposs right_pos,\n linarith,\n },\n },\n {\n rcases left_half with ⟨c', -, v_c'⟩,\n exact ⟨c', v_c'⟩,\n },\n },\n rw without_final_H at right_half,\n rw list.append_assoc v'' at right_half,\n have key_prop :\n list.length (\n list.map wrap_sym r₀.input_L ++ [symbol.nonterminal (sum.inl r₀.input_N)] ++ list.map wrap_sym r₀.input_R\n ) ≤\n v''.length,\n {\n classical,\n have first_H := congr_arg (list.index_of H) right_half,\n rw [very_middle, ←list.map_append_append, list.index_of_append_of_notin map_wrap_never_contains_H] at first_H,\n have H_not_in_v'' : H ∉ v'',\n {\n rw [without_final_H, ←list.append_assoc] at left_half,\n intro contra,\n apply false_of_true_eq_false,\n convert congr_arg ((∈) H) (list.append_right_cancel left_half).symm,\n {\n rw [eq_iff_iff, true_iff],\n exact list.mem_append_right _ contra,\n },\n {\n clear_except,\n rw [eq_iff_iff, false_iff],\n intro contr,\n iterate 3 {\n rw list.mem_append at contr,\n cases contr,\n },\n iterate 2 {\n rw list.mem_map at contr,\n rcases contr with ⟨t, -, impos⟩,\n exact symbol.no_confusion impos,\n },\n {\n rw list.mem_singleton at contr,\n exact H_neq_R contr,\n },\n {\n rw list.mem_map at contr,\n rcases contr with ⟨s, -, imposs⟩,\n exact wrap_never_outputs_H imposs,\n },\n },\n },\n rw list.index_of_append_of_notin H_not_in_v'' at first_H,\n rw [list.singleton_append, list.index_of_cons_self, add_zero] at first_H,\n rw [very_middle, ←list.map_append_append],\n exact nat.le.intro first_H,\n },\n obtain ⟨n, key_prop'⟩ := nat.le.dest key_prop,\n have right_take := congr_arg (list.take v''.length) right_half,\n rw list.take_left at right_take,\n rw ←key_prop' at right_take,\n rw list.take_append at right_take,\n use list.take n v ++ [H],\n rw without_final_H,\n rw ←right_take,\n repeat {\n rw ←list.append_assoc,\n },\n },\n rw v'_eq at right_half,\n rw list.append_assoc _ z at right_half,\n rw list.append_right_inj at right_half,\n rw v'_eq at left_half,\n obtain ⟨u₁, v₁, gamma_parts, z_eq⟩ : ∃ u₁, ∃ v₁,\n list.map wrap_sym γ =\n list.map wrap_sym u₁ ++ (\n list.map wrap_sym r₀.input_L ++ [symbol.nonterminal (sum.inl r₀.input_N)] ++ list.map wrap_sym r₀.input_R\n ) ++ list.map wrap_sym v₁ ∧\n z = list.map wrap_sym v₁ ++ [H],\n {\n repeat {\n rw ←list.append_assoc at left_half,\n },\n rw list.append_assoc _ (list.map wrap_sym γ) at left_half,\n rw list.append_assoc _ _ z at left_half,\n rw list.append_eq_append_iff at left_half,\n cases left_half,\n swap, {\n exfalso,\n rcases left_half with ⟨c', imposs, -⟩,\n exact case_3_false_of_wbr_eq_urz imposs,\n },\n rcases left_half with ⟨a', lhl, lhr⟩,\n have lhl' := congr_arg list.reverse lhl,\n repeat {\n rw list.reverse_append at lhl',\n },\n rw list.reverse_singleton at lhl',\n rw ←list.reverse_reverse a' at lhr,\n cases a'.reverse with d' l',\n {\n exfalso,\n rw list.nil_append at lhl',\n rw [list.singleton_append, list.reverse_singleton, list.singleton_append] at lhl',\n have imposs := list.head_eq_of_cons_eq lhl',\n exact sum.no_confusion (symbol.nonterminal.inj imposs),\n },\n rw list.singleton_append at lhl',\n rw list.cons_append at lhl',\n rw list.cons.inj_eq at lhl',\n cases lhl' with eq_d' lhl'',\n rw ←eq_d' at lhr,\n clear eq_d' d',\n rw ←list.append_assoc l' at lhl'',\n rw list.append_eq_append_iff at lhl'',\n cases lhl'',\n swap, {\n exfalso,\n rcases lhl'' with ⟨c'', imposs, -⟩,\n rw list.reverse_singleton at imposs,\n apply false_of_true_eq_false,\n convert congr_arg ((∈) R) imposs.symm,\n {\n rw [eq_iff_iff, true_iff],\n apply list.mem_append_left,\n apply list.mem_append_right,\n apply list.mem_singleton_self,\n },\n {\n rw [eq_iff_iff, false_iff],\n rw list.mem_reverse,\n apply map_wrap_never_contains_R,\n },\n },\n rcases lhl'' with ⟨b', lhlr', lhll'⟩,\n rw list.reverse_singleton at lhlr',\n have lhlr := congr_arg list.reverse lhlr',\n rw [list.reverse_append, list.reverse_append, list.reverse_reverse] at lhlr,\n rw [list.reverse_singleton, list.singleton_append] at lhlr,\n rw ←list.reverse_reverse b' at lhll',\n cases b'.reverse with d'' l'',\n {\n exfalso,\n rw list.nil_append at lhlr,\n cases r₀.input_L with d l,\n {\n rw list.map_nil at lhlr,\n exact list.no_confusion lhlr,\n },\n rw list.map_cons at lhlr,\n have imposs := list.head_eq_of_cons_eq lhlr,\n exact wrap_never_outputs_R imposs.symm,\n },\n rw list.cons_append at lhlr,\n rw list.cons.inj_eq at lhlr,\n cases lhlr with eq_d'' lve,\n rw ←eq_d'' at lhll',\n clear eq_d'' d'',\n have lhll := congr_arg list.reverse lhll',\n rw [list.reverse_reverse, list.reverse_append, list.reverse_reverse, list.reverse_append,\n list.reverse_reverse, list.reverse_reverse] at lhll,\n rw lhll at *,\n clear lhll u,\n rw list.reverse_cons at lhr,\n rw lve at lhr,\n use list.take l''.length γ,\n use list.drop (l''\n ++ list.map wrap_sym r₀.input_L\n ++ [symbol.nonterminal (sum.inl r₀.input_N)]\n ++ list.map wrap_sym r₀.input_R\n ).length γ,\n have z_expr : z =\n list.map wrap_sym (\n list.drop (l''\n ++ list.map wrap_sym r₀.input_L\n ++ [symbol.nonterminal (sum.inl r₀.input_N)]\n ++ list.map wrap_sym r₀.input_R\n ).length γ\n ) ++ [H],\n {\n have lhdr :=\n congr_arg\n (list.drop (l''\n ++ list.map wrap_sym r₀.input_L\n ++ [symbol.nonterminal (sum.inl r₀.input_N)]\n ++ list.map wrap_sym r₀.input_R\n ).length) lhr,\n rw list.drop_append_of_le_length at lhdr,\n {\n rw [list.map_drop, lhdr, ←list.append_assoc, list.drop_left],\n },\n have lhr' := congr_arg list.reverse lhr,\n repeat {\n rw list.reverse_append at lhr',\n },\n rw list.reverse_singleton at lhr',\n cases z.reverse with d l,\n {\n exfalso,\n rw [list.nil_append, list.singleton_append] at lhr',\n rw ←list.map_reverse _ r₀.input_R at lhr',\n cases r₀.input_R.reverse with dᵣ lᵣ,\n {\n rw [list.map_nil, list.nil_append, list.reverse_singleton, list.singleton_append] at lhr',\n have imposs := list.head_eq_of_cons_eq lhr',\n exact sum.no_confusion (symbol.nonterminal.inj imposs),\n },\n {\n rw [list.map_cons, list.cons_append] at lhr',\n have imposs := list.head_eq_of_cons_eq lhr',\n exact wrap_never_outputs_H imposs.symm,\n },\n },\n repeat {\n rw list.length_append,\n },\n have contra_len := congr_arg list.length lhr',\n repeat {\n rw list.length_append at contra_len,\n },\n repeat {\n rw list.length_reverse at contra_len,\n },\n repeat {\n rw list.length_singleton at contra_len,\n },\n rw list.length_cons at contra_len,\n rw list.length_singleton,\n clear_except contra_len,\n linarith,\n },\n split,\n swap, {\n exact z_expr,\n },\n rw z_expr at lhr,\n have gamma_expr : list.map wrap_sym γ =\n l'' ++ list.map wrap_sym r₀.input_L ++ [symbol.nonterminal (sum.inl r₀.input_N)] ++\n (list.map wrap_sym r₀.input_R ++\n (list.map wrap_sym\n (list.drop (l''\n ++ list.map wrap_sym r₀.input_L\n ++ [symbol.nonterminal (sum.inl r₀.input_N)]\n ++ list.map wrap_sym r₀.input_R\n ).length γ))),\n {\n repeat {\n rw ←list.append_assoc at lhr,\n },\n repeat {\n rw ←list.append_assoc,\n },\n exact list.append_right_cancel lhr,\n },\n rw gamma_expr,\n trim,\n have almost := congr_arg (list.take l''.length) gamma_expr.symm,\n repeat {\n rw list.append_assoc at almost,\n },\n rw list.take_left at almost,\n rw list.map_take,\n exact almost,\n },\n use [u₁, v₁],\n split, swap, split,\n {\n apply wrap_str_inj,\n rwa [\n very_middle, ←list.map_append_append, ←list.map_append_append,\n ←list.append_assoc, ←list.append_assoc\n ] at gamma_parts,\n },\n {\n rwa z_eq at right_half,\n },\n rw gamma_parts at left_half,\n rw list.append_assoc (list.map wrap_sym u₁) at left_half,\n rw ←list.append_assoc _ (list.map wrap_sym u₁) at left_half,\n rw list.append_assoc _ _ [H] at left_half,\n have left_left := congr_arg (list.take u.length) left_half,\n rw list.take_left at left_left,\n rw list.take_left' at left_left,\n {\n exact left_left.symm,\n },\n have lh_len := congr_arg list.length left_half,\n repeat {\n rw list.length_append at lh_len,\n },\n repeat {\n rw list.length_singleton at lh_len,\n },\n have cut_off_end : z.length = (list.map wrap_sym v₁).length + 1,\n {\n simpa using congr_arg list.length z_eq,\n },\n rw cut_off_end at lh_len,\n repeat {\n rw list.length_append,\n },\n rw list.length_singleton,\n repeat {\n rw add_assoc at lh_len,\n },\n iterate 3 {\n rw ←add_assoc at lh_len,\n },\n rwa add_left_inj at lh_len,\n },\nend\n\nprivate lemma star_case_3 {g : grammar T} {α α' : list (ns T g.nt)}\n (orig : grammar_transforms (star_grammar g) α α')\n (hyp : ∃ w : list (list T), ∃ β : list T, ∃ γ : list (symbol T g.nt), ∃ x : list (list (symbol T g.nt)),\n (∀ wᵢ ∈ w, grammar_generates g wᵢ) ∧\n (grammar_derives g [symbol.nonterminal g.initial] (list.map symbol.terminal β ++ γ)) ∧\n (∀ xᵢ ∈ x, grammar_derives g [symbol.nonterminal g.initial] xᵢ) ∧\n (α = list.map symbol.terminal (list.join w) ++ list.map symbol.terminal β ++ [R] ++\n list.map wrap_sym γ ++ [H] ++ list.join (list.map (++ [H]) (list.map (list.map wrap_sym) x)))) :\n (∃ w : list (list T), ∃ β : list T, ∃ γ : list (symbol T g.nt), ∃ x : list (list (symbol T g.nt)),\n (∀ wᵢ ∈ w, grammar_generates g wᵢ) ∧\n (grammar_derives g [symbol.nonterminal g.initial] (list.map symbol.terminal β ++ γ)) ∧\n (∀ xᵢ ∈ x, grammar_derives g [symbol.nonterminal g.initial] xᵢ) ∧\n (α' = list.map symbol.terminal (list.join w) ++ list.map symbol.terminal β ++ [R] ++\n list.map wrap_sym γ ++ [H] ++ list.join (list.map (++ [H]) (list.map (list.map wrap_sym) x)))) ∨\n (∃ u : list T, u ∈ language.star (grammar_language g) ∧ α' = list.map symbol.terminal u) ∨\n (∃ σ : list (symbol T g.nt), α' = list.map wrap_sym σ ++ [R]) ∨\n (∃ ω : list (ns T g.nt), α' = ω ++ [H]) ∧ Z ∉ α' ∧ R ∉ α' :=\nbegin\n rcases hyp with ⟨w, β, γ, x, valid_w, valid_middle, valid_x, cat⟩,\n have no_Z_in_alpha : Z ∉ α,\n {\n intro contr,\n rw cat at contr,\n clear_except contr,\n repeat {\n rw list.mem_append at contr,\n },\n iterate 5 {\n cases contr,\n },\n any_goals {\n rw list.mem_map at contr,\n rcases contr with ⟨s, -, imposs⟩,\n },\n {\n exact symbol.no_confusion imposs,\n },\n {\n exact symbol.no_confusion imposs,\n },\n {\n rw list.mem_singleton at contr,\n exact Z_neq_R contr,\n },\n {\n exact wrap_never_outputs_Z imposs,\n },\n {\n rw list.mem_singleton at contr,\n exact Z_neq_H contr,\n },\n {\n exact Z_not_in_join_mpHmmw contr,\n },\n },\n rw cat at *,\n clear cat,\n rcases orig with ⟨r, rin, u, v, bef, aft⟩,\n\n iterate 2 {\n cases rin,\n {\n exfalso,\n apply no_Z_in_alpha,\n rw bef,\n apply list.mem_append_left,\n apply list.mem_append_left,\n apply list.mem_append_right,\n rw list.mem_singleton,\n rw rin,\n refl,\n },\n },\n cases rin,\n {\n rw rin at bef aft,\n dsimp only at bef aft,\n rw list.append_nil at bef,\n have gamma_nil_here := case_3_gamma_nil bef,\n cases x with x₀ L,\n {\n right, right, left,\n rw [gamma_nil_here, list.map_nil, list.append_nil] at bef,\n rw [list.map_nil, list.map_nil, list.join, list.append_nil] at bef,\n have v_nil := case_3_v_nil bef,\n rw [v_nil, list.append_nil] at bef aft,\n use list.map symbol.terminal w.join ++ list.map symbol.terminal β,\n rw aft,\n have bef_minus_H := list.append_right_cancel bef,\n have bef_minus_RH := list.append_right_cancel bef_minus_H,\n rw ←bef_minus_RH,\n rw [list.map_append, list.map_map, list.map_map],\n refl,\n },\n {\n left,\n use [w ++ [β], x₀, L],\n split,\n {\n intros wᵢ wiin,\n rw list.mem_append at wiin,\n cases wiin,\n {\n exact valid_w wᵢ wiin,\n },\n {\n rw list.mem_singleton at wiin,\n rw wiin,\n rw [gamma_nil_here, list.append_nil] at valid_middle,\n exact valid_middle,\n },\n },\n split,\n {\n rw [list.map_nil, list.nil_append],\n exact valid_x x₀ (list.mem_cons_self x₀ L),\n },\n split,\n {\n intros xᵢ xiin,\n exact valid_x xᵢ (list.mem_cons_of_mem x₀ xiin),\n },\n rw [list.map_nil, list.append_nil],\n rw aft,\n have u_eq : u = list.map (@symbol.terminal T (nn g.nt)) w.join ++ list.map (@symbol.terminal T (nn g.nt)) β,\n {\n exact case_3_u_eq_left_side bef,\n },\n have v_eq : v = list.join (list.map (++ [H]) (list.map (list.map wrap_sym) (x₀ :: L))),\n {\n rw u_eq at bef,\n rw [gamma_nil_here, list.map_nil, list.append_nil] at bef,\n exact (list.append_left_cancel bef).symm,\n },\n rw [u_eq, v_eq],\n rw [list.join_append, list.map_append, list.join_singleton],\n rw [list.map_cons, list.map_cons, list.join],\n rw [←list.append_assoc, ←list.append_assoc],\n refl,\n },\n },\n cases rin,\n {\n rw rin at bef aft,\n dsimp only at bef aft,\n rw list.append_nil at bef aft,\n have gamma_nil_here := case_3_gamma_nil bef,\n rw ←list.reverse_reverse x at *,\n cases x.reverse with xₘ L,\n {\n right, left,\n rw [gamma_nil_here, list.map_nil, list.append_nil] at bef,\n rw [list.reverse_nil, list.map_nil, list.map_nil, list.join, list.append_nil] at bef,\n have v_nil := case_3_v_nil bef,\n rw [v_nil, list.append_nil] at bef aft,\n use list.join w ++ β,\n split,\n {\n use w ++ [β],\n split,\n {\n rw list.join_append,\n rw list.join_singleton,\n },\n {\n intros y y_in,\n rw list.mem_append at y_in,\n cases y_in,\n {\n exact valid_w y y_in,\n },\n {\n rw list.mem_singleton at y_in,\n rw y_in,\n rw [gamma_nil_here, list.append_nil] at valid_middle,\n exact valid_middle,\n },\n },\n },\n {\n rw aft,\n have bef_minus_H := list.append_right_cancel bef,\n have bef_minus_RH := list.append_right_cancel bef_minus_H,\n rw ←bef_minus_RH,\n rw list.map_append,\n },\n },\n {\n right, right, right,\n rw list.reverse_cons at bef,\n rw aft,\n have Z_ni_wb : Z ∉ list.map (@symbol.terminal T (nn g.nt)) w.join ++ list.map symbol.terminal β,\n {\n apply case_3_ni_wb,\n },\n have R_ni_wb : R ∉ list.map (@symbol.terminal T (nn g.nt)) w.join ++ list.map symbol.terminal β,\n {\n apply case_3_ni_wb,\n },\n have u_eq : u = list.map (@symbol.terminal T (nn g.nt)) w.join ++ list.map symbol.terminal β,\n {\n exact case_3_u_eq_left_side bef,\n },\n have v_eq : v = list.join (list.map (++ [H]) (list.map (list.map wrap_sym) (L.reverse ++ [xₘ]))),\n {\n rw u_eq at bef,\n rw [gamma_nil_here, list.map_nil, list.append_nil] at bef,\n exact (list.append_left_cancel bef).symm,\n },\n rw [u_eq, v_eq],\n split,\n {\n use list.map symbol.terminal w.join ++ list.map symbol.terminal β ++\n list.join (list.map (++ [H]) (list.map (list.map wrap_sym) L.reverse)) ++ list.map wrap_sym xₘ,\n rw [\n list.map_append, list.map_append, list.join_append,\n list.map_singleton, list.map_singleton, list.join_singleton,\n ←list.append_assoc, ←list.append_assoc\n ], refl,\n },\n split,\n {\n intro contra,\n rw list.mem_append at contra,\n cases contra,\n {\n exact Z_ni_wb contra,\n },\n {\n exact Z_not_in_join_mpHmmw contra,\n },\n },\n {\n intro contra,\n rw list.mem_append at contra,\n cases contra,\n {\n exact R_ni_wb contra,\n },\n {\n exact R_not_in_join_mpHmmw contra,\n },\n },\n },\n },\n have rin' : r ∈ rules_that_scan_terminals g ∨ r ∈ list.map wrap_gr g.rules,\n {\n rw or_comm,\n rwa ←list.mem_append,\n },\n clear rin,\n cases rin',\n {\n left,\n unfold rules_that_scan_terminals at rin',\n rw list.mem_map at rin',\n rcases rin' with ⟨t, -, r_is⟩,\n rw ←r_is at bef aft,\n dsimp only at bef aft,\n rw list.append_nil at bef,\n have u_matches : u = list.map (@symbol.terminal T (nn g.nt)) w.join ++ list.map symbol.terminal β,\n {\n exact case_3_u_eq_left_side bef,\n },\n have tv_matches :\n [symbol.terminal t] ++ v =\n list.map wrap_sym γ ++ [H] ++ list.join (list.map (++ [H]) (list.map (list.map wrap_sym) x)),\n {\n rw u_matches at bef,\n repeat {\n rw list.append_assoc at bef,\n },\n have almost := list.append_left_cancel (list.append_left_cancel (list.append_left_cancel bef)),\n rw ←list.append_assoc at almost,\n exact almost.symm,\n },\n cases γ with a δ,\n {\n exfalso,\n rw [list.map_nil, list.nil_append, list.singleton_append, list.singleton_append] at tv_matches,\n have t_matches := list.head_eq_of_cons_eq tv_matches,\n exact symbol.no_confusion t_matches,\n },\n rw [list.singleton_append, list.map_cons, list.cons_append, list.cons_append] at tv_matches,\n use [w, β ++ [t], δ, x],\n split,\n {\n exact valid_w,\n },\n split,\n {\n have t_matches' := list.head_eq_of_cons_eq tv_matches,\n cases a;\n unfold wrap_sym at t_matches',\n {\n have t_eq_a := symbol.terminal.inj t_matches',\n rw [t_eq_a, list.map_append, list.map_singleton, list.append_assoc, list.singleton_append],\n exact valid_middle,\n },\n {\n exfalso,\n exact symbol.no_confusion t_matches',\n },\n },\n split,\n {\n exact valid_x,\n },\n rw aft,\n rw u_matches,\n rw [list.map_append, list.map_singleton],\n have v_matches := list.tail_eq_of_cons_eq tv_matches,\n rw v_matches,\n simp [list.append_assoc],\n },\n left,\n rw list.mem_map at rin',\n rcases rin' with ⟨r₀, orig_in, wrap_orig⟩,\n unfold wrap_gr at wrap_orig,\n rw ←wrap_orig at *,\n clear wrap_orig,\n cases case_3_match_rule bef,\n {\n rcases h with ⟨m, u₁, v₁, u_eq, xm_eq, v_eq⟩,\n clear bef,\n dsimp only at aft,\n rw [u_eq, v_eq] at aft,\n use w,\n use β,\n use γ,\n use (list.take m x ++ [u₁ ++ r₀.output_string ++ v₁] ++ list.drop m.succ x),\n split,\n {\n exact valid_w,\n },\n split,\n {\n exact valid_middle,\n },\n split,\n {\n intros xᵢ xiin,\n rw list.mem_append_append at xiin,\n cases xiin,\n {\n apply valid_x,\n exact list.mem_of_mem_take xiin,\n },\n cases xiin,\n swap, {\n apply valid_x,\n exact list.mem_of_mem_drop xiin,\n },\n {\n rw list.mem_singleton at xiin,\n rw xiin,\n have last_step :\n grammar_transforms g\n (u₁ ++ r₀.input_L ++ [symbol.nonterminal r₀.input_N] ++ r₀.input_R ++ v₁)\n (u₁ ++ r₀.output_string ++ v₁),\n {\n use r₀,\n split,\n {\n exact orig_in,\n },\n use [u₁, v₁],\n split;\n refl,\n },\n apply grammar_deri_of_deri_tran _ last_step,\n apply valid_x (u₁ ++ r₀.input_L ++ [symbol.nonterminal r₀.input_N] ++ r₀.input_R ++ v₁),\n exact list.nth_mem xm_eq,\n },\n },\n {\n rw aft,\n trim,\n rw [\n list.map_append_append,\n list.map_append_append,\n list.join_append_append,\n ←list.map_take,\n ←list.map_drop,\n list.map_singleton,\n list.map_singleton,\n list.join_singleton,\n list.map_append_append,\n ←list.append_assoc,\n ←list.append_assoc,\n ←list.append_assoc\n ],\n },\n },\n {\n rcases h with ⟨u₁, v₁, u_eq, γ_eq, v_eq⟩,\n clear bef,\n dsimp only at aft,\n rw [u_eq, v_eq] at aft,\n use w,\n use β,\n use u₁ ++ r₀.output_string ++ v₁,\n use x,\n split,\n {\n exact valid_w,\n },\n split,\n {\n apply grammar_deri_of_deri_tran valid_middle,\n rw γ_eq,\n use r₀,\n split,\n {\n exact orig_in,\n },\n use [list.map symbol.terminal β ++ u₁, v₁],\n split,\n repeat {\n rw ←list.append_assoc,\n },\n },\n split,\n {\n exact valid_x,\n },\n {\n rw aft,\n trim,\n rw list.map_append_append,\n },\n },\nend\n\nprivate lemma star_case_4 {g : grammar T} {α α' : list (ns T g.nt)}\n (orig : grammar_transforms (star_grammar g) α α')\n (hyp : ∃ u : list T, u ∈ (grammar_language g).star ∧ α = list.map symbol.terminal u) :\n false :=\nbegin\n rcases hyp with ⟨w, -, alpha_of_w⟩,\n rw alpha_of_w at orig,\n rcases orig with ⟨r, -, u, v, bef, -⟩,\n simpa using congr_arg (λ l, symbol.nonterminal r.input_N ∈ l) bef,\nend\n\nprivate lemma star_case_5 {g : grammar T} {α α' : list (ns T g.nt)}\n (orig : grammar_transforms (star_grammar g) α α')\n (hyp : ∃ σ : list (symbol T g.nt), α = list.map wrap_sym σ ++ [R]) :\n (∃ σ : list (symbol T g.nt), α' = list.map wrap_sym σ ++ [R]) :=\nbegin\n rcases hyp with ⟨w, ends_with_R⟩,\n rcases orig with ⟨r, rin, u, v, bef, aft⟩,\n rw ends_with_R at bef,\n clear ends_with_R,\n iterate 2 {\n cases rin,\n {\n exfalso,\n rw rin at bef,\n simp only [list.append_nil] at bef,\n have imposs := congr_arg (λ l, Z ∈ l) bef,\n simp only [list.mem_append] at imposs,\n rw list.mem_singleton at imposs,\n rw list.mem_singleton at imposs,\n apply false_of_true_eq_false,\n convert imposs.symm,\n {\n unfold Z,\n rw [eq_self_iff_true, or_true, true_or],\n },\n {\n rw [eq_iff_iff, false_iff],\n push_neg,\n split,\n {\n apply map_wrap_never_contains_Z,\n },\n {\n exact Z_neq_R,\n },\n },\n },\n },\n iterate 2 {\n cases rin,\n {\n exfalso,\n rw rin at bef,\n dsimp only at bef,\n rw list.append_nil at bef,\n have rev := congr_arg list.reverse bef,\n repeat {\n rw list.reverse_append at rev,\n },\n repeat {\n rw list.reverse_singleton at rev,\n },\n rw list.singleton_append at rev,\n cases v.reverse with d l,\n {\n rw list.nil_append at rev,\n rw list.singleton_append at rev,\n have tails := list.tail_eq_of_cons_eq rev,\n rw ←list.map_reverse at tails,\n cases w.reverse with d' l',\n {\n rw list.map_nil at tails,\n have imposs := congr_arg list.length tails,\n rw [list.length, list.length_append, list.length_singleton] at imposs,\n clear_except imposs,\n linarith,\n },\n {\n rw list.map_cons at tails,\n rw list.singleton_append at tails,\n have heads := list.head_eq_of_cons_eq tails,\n exact wrap_never_outputs_R heads,\n },\n },\n {\n have tails := list.tail_eq_of_cons_eq rev,\n have H_in_tails := congr_arg (λ l, H ∈ l) tails,\n dsimp only at H_in_tails,\n rw list.mem_reverse at H_in_tails,\n apply false_of_true_eq_false,\n convert H_in_tails.symm,\n {\n rw [eq_iff_iff, true_iff],\n apply list.mem_append_right,\n apply list.mem_append_left,\n apply list.mem_singleton_self,\n },\n {\n rw [eq_iff_iff, false_iff],\n intro hyp_H_in,\n exact map_wrap_never_contains_H hyp_H_in,\n },\n },\n },\n },\n change r ∈ list.map wrap_gr g.rules ++ rules_that_scan_terminals g at rin,\n rw list.mem_append at rin,\n cases rin,\n {\n rw list.mem_map at rin,\n rcases rin with ⟨r₀, -, r_of_r₀⟩,\n rw list.append_eq_append_iff at bef,\n cases bef,\n {\n rcases bef with ⟨x, ur_eq, singleR⟩,\n by_cases is_x_nil : x = [],\n {\n have v_is_R : v = [R],\n {\n rw [is_x_nil, list.nil_append] at singleR,\n exact singleR.symm,\n },\n rw v_is_R at aft,\n rw [is_x_nil, list.append_nil] at ur_eq,\n have u_from_w : u = list.take u.length (list.map wrap_sym w),\n { -- do not extract out of `cases bef`\n repeat {\n rw list.append_assoc at ur_eq,\n },\n have tak := congr_arg (list.take u.length) ur_eq,\n rw list.take_left at tak,\n exact tak,\n },\n rw ←list.map_take at u_from_w,\n rw u_from_w at aft,\n rw ←r_of_r₀ at aft,\n dsimp only [wrap_gr] at aft,\n use list.take u.length w ++ r₀.output_string,\n rw list.map_append,\n exact aft,\n },\n {\n exfalso,\n have x_is_R : x = [R],\n {\n by_cases is_v_nil : v = [],\n {\n rw [is_v_nil, list.append_nil] at singleR,\n exact singleR.symm,\n },\n {\n exfalso,\n have imposs := congr_arg list.length singleR,\n rw list.length_singleton at imposs,\n rw list.length_append at imposs,\n have xl_ge_one := length_ge_one_of_not_nil is_x_nil,\n have vl_ge_one := length_ge_one_of_not_nil is_v_nil,\n clear_except imposs xl_ge_one vl_ge_one,\n linarith,\n },\n },\n rw x_is_R at ur_eq,\n have ru_eq := congr_arg list.reverse ur_eq,\n repeat {\n rw list.reverse_append at ru_eq,\n },\n repeat {\n rw list.reverse_singleton at ru_eq,\n rw list.singleton_append at ru_eq,\n },\n rw ←r_of_r₀ at ru_eq,\n dsimp only [wrap_gr, R] at ru_eq,\n rw ←list.map_reverse at ru_eq,\n cases r₀.input_R.reverse with d l,\n {\n rw [list.map_nil, list.nil_append] at ru_eq,\n have imposs := list.head_eq_of_cons_eq ru_eq,\n exact sum.no_confusion (symbol.nonterminal.inj imposs),\n },\n {\n have imposs := list.head_eq_of_cons_eq ru_eq,\n cases d;\n unfold wrap_sym at imposs,\n {\n exact symbol.no_confusion imposs,\n },\n {\n exact sum.no_confusion (symbol.nonterminal.inj imposs),\n },\n },\n },\n },\n {\n rcases bef with ⟨y, w_eq, v_eq⟩,\n have u_from_w : u = list.take u.length (list.map wrap_sym w),\n { -- do not extract out of `cases bef`\n repeat {\n rw list.append_assoc at w_eq,\n },\n have tak := congr_arg (list.take u.length) w_eq,\n rw list.take_left at tak,\n exact tak.symm,\n },\n have y_from_w :\n y = list.drop (u ++ r.input_L ++ [symbol.nonterminal r.input_N] ++ r.input_R).length (list.map wrap_sym w),\n {\n have drp := congr_arg (list.drop (u ++ r.input_L ++ [symbol.nonterminal r.input_N] ++ r.input_R).length) w_eq,\n rw list.drop_left at drp,\n exact drp.symm,\n },\n -- weird that `u_from_w` and `y_from_w` did not unify their type parameters in the same way\n rw u_from_w at aft,\n rw y_from_w at v_eq,\n rw v_eq at aft,\n use list.take u.length w ++ r₀.output_string ++\n list.drop (u ++ r.input_L ++ [symbol.nonterminal r.input_N] ++ r.input_R).length w,\n rw list.map_append_append,\n rw list.map_take,\n rw list.map_drop,\n rw aft,\n trim, -- fails to identify `list.take u.length (list.map wrap_sym w)` of defin-equal type parameters\n rw ←r_of_r₀,\n dsimp only [wrap_gr],\n refl, -- outside level `(symbol T (star_grammar g).nt) = (ns T g.nt) = (symbol T (nn g.nt))`\n },\n },\n {\n exfalso,\n unfold rules_that_scan_terminals at rin,\n rw list.mem_map at rin,\n rcases rin with ⟨t, -, eq_r⟩,\n rw ←eq_r at bef,\n clear eq_r,\n dsimp only at bef,\n rw list.append_nil at bef,\n have rev := congr_arg list.reverse bef,\n repeat {\n rw list.reverse_append at rev,\n },\n repeat {\n rw list.reverse_singleton at rev,\n },\n rw list.singleton_append at rev,\n cases v.reverse with d l,\n {\n rw list.nil_append at rev,\n rw list.singleton_append at rev,\n have tails := list.tail_eq_of_cons_eq rev,\n rw ←list.map_reverse at tails,\n cases w.reverse with d' l',\n {\n rw list.map_nil at tails,\n have imposs := congr_arg list.length tails,\n rw [list.length, list.length_append, list.length_singleton] at imposs,\n clear_except imposs,\n linarith,\n },\n {\n rw list.map_cons at tails,\n rw list.singleton_append at tails,\n have heads := list.head_eq_of_cons_eq tails,\n exact wrap_never_outputs_R heads,\n },\n },\n {\n have tails := list.tail_eq_of_cons_eq rev,\n have R_in_tails := congr_arg (λ l, R ∈ l) tails,\n dsimp only at R_in_tails,\n rw list.mem_reverse at R_in_tails,\n apply false_of_true_eq_false,\n convert R_in_tails.symm,\n {\n rw [eq_iff_iff, true_iff],\n apply list.mem_append_right,\n apply list.mem_append_right,\n apply list.mem_append_left,\n apply list.mem_singleton_self,\n },\n {\n rw [eq_iff_iff, false_iff],\n intro hyp_R_in,\n exact map_wrap_never_contains_R hyp_R_in,\n },\n },\n },\nend\n\nprivate lemma star_case_6 {g : grammar T} {α α' : list (ns T g.nt)}\n (orig : grammar_transforms (star_grammar g) α α')\n (hyp : (∃ ω : list (ns T g.nt), α = ω ++ [H]) ∧ Z ∉ α ∧ R ∉ α) :\n (∃ ω : list (ns T g.nt), α' = ω ++ [H]) ∧ Z ∉ α' ∧ R ∉ α' :=\nbegin\n rcases hyp with ⟨⟨w, ends_with_H⟩, no_Z, no_R⟩,\n rcases orig with ⟨r, rin, u, v, bef, aft⟩,\n iterate 2 {\n cases rin,\n {\n exfalso,\n rw rin at bef,\n simp only [list.append_nil] at bef,\n rw bef at no_Z,\n apply no_Z,\n apply list.mem_append_left,\n apply list.mem_append_right,\n apply list.mem_singleton_self,\n },\n },\n iterate 2 {\n cases rin,\n {\n exfalso,\n rw rin at bef,\n dsimp only at bef,\n rw list.append_nil at bef,\n rw bef at no_R,\n apply no_R,\n apply list.mem_append_left,\n apply list.mem_append_left,\n apply list.mem_append_right,\n apply list.mem_singleton_self,\n },\n },\n change r ∈ list.map wrap_gr g.rules ++ rules_that_scan_terminals g at rin,\n rw list.mem_append at rin,\n cases rin,\n {\n rw ends_with_H at bef,\n rw list.mem_map at rin,\n rcases rin with ⟨r₀, -, r_of_r₀⟩,\n split,\n swap, {\n split,\n {\n rw aft,\n intro contra,\n rw list.mem_append at contra,\n rw list.mem_append at contra,\n cases contra,\n swap, {\n apply no_Z,\n rw ends_with_H,\n rw bef,\n rw list.mem_append,\n right,\n exact contra,\n },\n cases contra,\n {\n apply no_Z,\n rw ends_with_H,\n rw bef,\n repeat {\n rw list.append_assoc,\n },\n rw list.mem_append,\n left,\n exact contra,\n },\n rw ←r_of_r₀ at contra,\n unfold wrap_gr at contra,\n rw list.mem_map at contra,\n rcases contra with ⟨s, -, imposs⟩,\n cases s,\n {\n unfold wrap_sym at imposs,\n exact symbol.no_confusion imposs,\n },\n {\n unfold wrap_sym at imposs,\n unfold Z at imposs,\n rw symbol.nonterminal.inj_eq at imposs,\n exact sum.no_confusion imposs,\n },\n },\n {\n rw aft,\n intro contra,\n rw list.mem_append at contra,\n rw list.mem_append at contra,\n cases contra,\n swap, {\n apply no_R,\n rw ends_with_H,\n rw bef,\n rw list.mem_append,\n right,\n exact contra,\n },\n cases contra,\n {\n apply no_R,\n rw ends_with_H,\n rw bef,\n repeat {\n rw list.append_assoc,\n },\n rw list.mem_append,\n left,\n exact contra,\n },\n rw ←r_of_r₀ at contra,\n unfold wrap_gr at contra,\n rw list.mem_map at contra,\n rcases contra with ⟨s, -, imposs⟩,\n cases s,\n {\n unfold wrap_sym at imposs,\n exact symbol.no_confusion imposs,\n },\n {\n unfold wrap_sym at imposs,\n unfold R at imposs,\n rw symbol.nonterminal.inj_eq at imposs,\n exact sum.no_confusion imposs,\n },\n },\n },\n use u ++ r.output_string ++ v.take (v.length - 1),\n rw aft,\n trim,\n have vlnn : v.length ≥ 1,\n {\n by_contradiction contra,\n have v_nil := zero_of_not_ge_one contra,\n rw list.length_eq_zero at v_nil,\n rw v_nil at bef,\n rw ←r_of_r₀ at bef,\n rw list.append_nil at bef,\n unfold wrap_gr at bef,\n have rev := congr_arg list.reverse bef,\n clear_except rev,\n repeat {\n rw list.reverse_append at rev,\n },\n rw ←list.map_reverse _ r₀.input_R at rev,\n rw list.reverse_singleton at rev,\n cases r₀.input_R.reverse with d l,\n {\n have H_eq_N : H = symbol.nonterminal (sum.inl r₀.input_N),\n {\n rw [list.map_nil, list.nil_append,\n list.reverse_singleton, list.singleton_append, list.singleton_append,\n list.cons.inj_eq] at rev,\n exact rev.left,\n },\n unfold H at H_eq_N,\n have inr_eq_inl := symbol.nonterminal.inj H_eq_N,\n exact sum.no_confusion inr_eq_inl,\n },\n {\n rw list.map_cons at rev,\n have H_is : H = wrap_sym d,\n {\n rw [list.singleton_append, list.cons_append, list.cons.inj_eq] at rev,\n exact rev.left,\n },\n unfold H at H_is,\n cases d;\n unfold wrap_sym at H_is,\n {\n exact symbol.no_confusion H_is,\n },\n {\n rw symbol.nonterminal.inj_eq at H_is,\n exact sum.no_confusion H_is,\n },\n },\n },\n convert_to list.take (v.length - 1) v ++ list.drop (v.length - 1) v = list.take (v.length - 1) v ++ [H],\n {\n rw list.take_append_drop,\n },\n trim,\n have bef_rev := congr_arg list.reverse bef,\n repeat {\n rw list.reverse_append at bef_rev,\n },\n have bef_rev_tak := congr_arg (list.take 1) bef_rev,\n rw list.take_left' at bef_rev_tak,\n swap, {\n rw list.length_reverse,\n apply list.length_singleton,\n },\n rw list.take_append_of_le_length at bef_rev_tak,\n swap, {\n rw list.length_reverse,\n exact vlnn,\n },\n rw list.reverse_take _ vlnn at bef_rev_tak,\n rw list.reverse_eq_iff at bef_rev_tak,\n rw list.reverse_reverse at bef_rev_tak,\n exact bef_rev_tak.symm,\n },\n {\n exfalso,\n unfold rules_that_scan_terminals at rin,\n rw list.mem_map at rin,\n rcases rin with ⟨t, -, eq_r⟩,\n rw ←eq_r at bef,\n dsimp only at bef,\n rw list.append_nil at bef,\n rw bef at no_R,\n apply no_R,\n apply list.mem_append_left,\n apply list.mem_append_left,\n apply list.mem_append_right,\n apply list.mem_singleton_self,\n },\nend\n\nprivate lemma star_induction {g : grammar T} {α : list (ns T g.nt)}\n (ass : grammar_derives (star_grammar g) [Z] α) :\n (∃ x : list (list (symbol T g.nt)),\n (∀ xᵢ ∈ x, grammar_derives g [symbol.nonterminal g.initial] xᵢ) ∧\n (α = [Z] ++ list.join (list.map (++ [H]) (list.map (list.map wrap_sym) x)))) ∨\n (∃ x : list (list (symbol T g.nt)),\n (∀ xᵢ ∈ x, grammar_derives g [symbol.nonterminal g.initial] xᵢ) ∧\n (α = [R, H] ++ list.join (list.map (++ [H]) (list.map (list.map wrap_sym) x)))) ∨\n (∃ w : list (list T), ∃ β : list T, ∃ γ : list (symbol T g.nt), ∃ x : list (list (symbol T g.nt)),\n (∀ wᵢ ∈ w, grammar_generates g wᵢ) ∧\n (grammar_derives g [symbol.nonterminal g.initial] (list.map symbol.terminal β ++ γ)) ∧\n (∀ xᵢ ∈ x, grammar_derives g [symbol.nonterminal g.initial] xᵢ) ∧\n (α = list.map symbol.terminal (list.join w) ++ list.map symbol.terminal β ++ [R] ++\n list.map wrap_sym γ ++ [H] ++ list.join (list.map (++ [H]) (list.map (list.map wrap_sym) x)))) ∨\n (∃ u : list T, u ∈ language.star (grammar_language g) ∧ α = list.map symbol.terminal u) ∨\n (∃ σ : list (symbol T g.nt), α = list.map wrap_sym σ ++ [R]) ∨\n (∃ ω : list (ns T g.nt), α = ω ++ [H]) ∧ Z ∉ α ∧ R ∉ α :=\nbegin\n induction ass with a b trash orig ih,\n {\n left,\n use list.nil,\n split,\n {\n intros y imposs,\n exfalso,\n exact list.not_mem_nil y imposs,\n },\n {\n refl,\n },\n },\n cases ih,\n {\n rw ←or_assoc,\n left,\n exact star_case_1 orig ih,\n },\n cases ih,\n {\n right,\n exact star_case_2 orig ih,\n },\n cases ih,\n {\n right, right,\n exact star_case_3 orig ih,\n },\n cases ih,\n {\n exfalso,\n exact star_case_4 orig ih,\n },\n cases ih,\n {\n right, right, right, right, left,\n exact star_case_5 orig ih,\n },\n {\n right, right, right, right, right,\n exact star_case_6 orig ih,\n },\nend\n\nend hard_direction\n\n\n/-- The class of recursively-enumerable languages is closed under the Kleene star. -/\ntheorem RE_of_star_RE (L : language T) :\n is_RE L → is_RE L.star :=\nbegin\n rintro ⟨g, hg⟩,\n use star_grammar g,\n\n apply set.eq_of_subset_of_subset,\n {\n -- prove `L.star ⊇` here\n intros w hyp,\n unfold grammar_language at hyp,\n rw set.mem_set_of_eq at hyp,\n have result := star_induction hyp,\n clear hyp,\n cases result,\n {\n exfalso,\n rcases result with ⟨x, -, contr⟩,\n cases w with d l,\n {\n tauto,\n },\n rw list.map_cons at contr,\n have terminal_eq_Z : symbol.terminal d = Z,\n {\n exact list.head_eq_of_cons_eq contr,\n },\n exact symbol.no_confusion terminal_eq_Z,\n },\n cases result,\n {\n exfalso,\n rcases result with ⟨x, -, contr⟩,\n cases w with d l,\n {\n tauto,\n },\n rw list.map_cons at contr,\n have terminal_eq_R : symbol.terminal d = R,\n {\n exact list.head_eq_of_cons_eq contr,\n },\n exact symbol.no_confusion terminal_eq_R,\n },\n cases result,\n {\n exfalso,\n rcases result with ⟨α, β, γ, x, -, -, -, contr⟩,\n have output_contains_R : R ∈ list.map symbol.terminal w,\n {\n rw contr,\n apply list.mem_append_left,\n apply list.mem_append_left,\n apply list.mem_append_left,\n apply list.mem_append_right,\n apply list.mem_cons_self,\n },\n rw list.mem_map at output_contains_R,\n rcases output_contains_R with ⟨t, -, terminal_eq_R⟩,\n exact symbol.no_confusion terminal_eq_R,\n },\n cases result,\n {\n rcases result with ⟨u, win, map_eq_map⟩,\n have w_eq_u : w = u,\n {\n have st_inj : function.injective (@symbol.terminal T (star_grammar g).nt),\n {\n apply symbol.terminal.inj,\n },\n rw ←list.map_injective_iff at st_inj,\n exact st_inj map_eq_map,\n },\n rw [w_eq_u, ←hg],\n exact win,\n },\n cases result,\n {\n exfalso,\n cases result with σ contr,\n have last_symbols := congr_fun (congr_arg list.nth (congr_arg list.reverse contr)) 0,\n rw [\n ←list.map_reverse,\n list.reverse_append,\n list.reverse_singleton,\n list.singleton_append,\n list.nth,\n list.nth_map\n ] at last_symbols,\n cases w.reverse.nth 0,\n {\n rw option.map_none' at last_symbols,\n exact option.no_confusion last_symbols,\n },\n {\n rw option.map_some' at last_symbols,\n have terminal_eq_R := option.some.inj last_symbols,\n exact symbol.no_confusion terminal_eq_R,\n },\n },\n {\n exfalso,\n rcases result with ⟨⟨ω, contr⟩, -⟩,\n have last_symbols := congr_fun (congr_arg list.nth (congr_arg list.reverse contr)) 0,\n rw [\n ←list.map_reverse,\n list.reverse_append,\n list.reverse_singleton,\n list.singleton_append,\n list.nth,\n list.nth_map\n ] at last_symbols,\n cases w.reverse.nth 0,\n {\n rw option.map_none' at last_symbols,\n exact option.no_confusion last_symbols,\n },\n {\n rw option.map_some' at last_symbols,\n have terminal_eq_H := option.some.inj last_symbols,\n exact symbol.no_confusion terminal_eq_H,\n },\n },\n },\n {\n -- prove `L.star ⊆` here\n intros p ass,\n unfold grammar_language,\n rw language.star at ass,\n rw set.mem_set_of_eq at ⊢ ass,\n rcases ass with ⟨w, w_join, parts_in_L⟩,\n let v := w.reverse,\n have v_reverse : v.reverse = w,\n {\n apply list.reverse_reverse,\n },\n rw ←v_reverse at *,\n rw w_join,\n clear w_join p,\n unfold grammar_generates,\n rw ←hg at parts_in_L,\n cases short_induction parts_in_L with derived terminated,\n apply grammar_deri_of_deri_deri derived,\n apply grammar_deri_of_tran_deri,\n {\n use (star_grammar g).rules.nth_le 1 (by dec_trivial),\n split,\n {\n apply list.nth_le_mem,\n },\n use [[], (list.map (++ [H]) (list.map (list.map symbol.terminal) v.reverse)).join],\n split,\n {\n rw list.reverse_reverse,\n refl,\n },\n {\n refl, -- binds the implicit argument of `grammar_deri_of_tran_deri`\n },\n },\n rw list.nil_append,\n rw v_reverse,\n have final_step :\n grammar_transforms (star_grammar g)\n (list.map symbol.terminal w.join ++ [R, H])\n (list.map symbol.terminal w.join),\n {\n use (star_grammar g).rules.nth_le 3 (by dec_trivial),\n split_ile,\n use [list.map symbol.terminal w.join, list.nil],\n split,\n {\n trim,\n },\n {\n have out_nil : ((star_grammar g).rules.nth_le 3 _).output_string = [],\n {\n refl,\n },\n rw [list.append_nil, out_nil, list.append_nil],\n },\n },\n apply grammar_deri_of_deri_tran _ final_step,\n convert_to\n grammar_derives (star_grammar g)\n ([R] ++ ([H] ++ (list.map (++ [H]) (list.map (list.map symbol.terminal) w)).join))\n (list.map symbol.terminal w.join ++ [R, H]),\n have rebracket :\n [H] ++ (list.map (++ [H]) (list.map (list.map symbol.terminal) w)).join =\n (list.map (λ v, [H] ++ v) (list.map (list.map symbol.terminal) w)).join ++ [H],\n {\n apply list.append_join_append,\n },\n rw rebracket,\n apply terminal_scan_aux,\n intros v vin t tin,\n rw ←list.mem_reverse at vin,\n exact terminated v vin t tin,\n },\nend\n", "meta": {"author": "madvorak", "repo": "grammars", "sha": "5ab26130eb76d5f7cde0f6c2f9c6f3107ff8d34f", "save_path": "github-repos/lean/madvorak-grammars", "path": "github-repos/lean/madvorak-grammars/grammars-5ab26130eb76d5f7cde0f6c2f9c6f3107ff8d34f/src/classes/unrestricted/closure_properties/star.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.48047867804790706, "lm_q2_score": 0.03514484905358528, "lm_q1q2_score": 0.016886350613459892}} {"text": "import for_mathlib.algebra.homology.trunc\n\nnoncomputable theory\n\nopen category_theory category_theory.limits category_theory.category\nopen_locale zero_object\n\n@[simp]\nlemma category_theory.epi_comp_left_iff_epi {C : Type*} [category C]\n {X₁ X₂ X₃ : C} (f : X₁ ⟶ X₂) (g : X₂ ⟶ X₃) [epi f]:\n epi (f ≫ g) ↔ epi g :=\nbegin\n split,\n { apply epi_of_epi, },\n { introI,\n apply epi_comp, },\nend\n\n@[simp]\nlemma category_theory.epi_comp_right_iff_epi {C : Type*} [category C]\n {X₁ X₂ X₃ : C} (f : X₁ ⟶ X₂) (g : X₂ ⟶ X₃) [is_iso g] :\n epi (f ≫ g) ↔ epi f :=\nbegin\n split,\n { introI,\n exact ⟨λ Z h₁ h₂ eq, by simpa only [← cancel_epi (inv g), ← cancel_epi (f ≫ g),\n assoc, is_iso.hom_inv_id_assoc] using eq⟩, },\n { introI,\n apply epi_comp, },\nend\n\n@[simp]\nlemma category_theory.mono_comp_right_iff_mono {C : Type*} [category C]\n {X₁ X₂ X₃ : C} (f : X₁ ⟶ X₂) (g : X₂ ⟶ X₃) [mono g] :\n mono (f ≫ g) ↔ mono f :=\nbegin\n split,\n { apply mono_of_mono, },\n { introI,\n apply mono_comp, },\nend\n\n@[simp]\nlemma category_theory.mono_comp_left_iff_mono {C : Type*} [category C]\n {X₁ X₂ X₃ : C} (f : X₁ ⟶ X₂) (g : X₂ ⟶ X₃) [is_iso f] :\n mono (f ≫ g) ↔ mono g :=\nbegin\n split,\n { introI,\n exact ⟨λ Z h₁ h₂ eq, by simpa only [← cancel_mono (inv f), ← cancel_mono (f ≫ g),\n assoc, is_iso.inv_hom_id_assoc] using eq⟩, },\n { introI,\n apply mono_comp, },\nend\n\nopen category_theory category_theory.limits category_theory.category\n\nnamespace category_theory.short_complex\n\n@[simps]\ndef homology_map_data.of_zeros_of_limit_kernel_fork {C : Type*} [category C] [has_zero_morphisms C]\n {S₁ S₂ : short_complex C} (φ : S₁ ⟶ S₂) (hf₁ : S₁.f = 0) (hg₁ : S₁.g = 0) (hf₂ : S₂.f = 0)\n (c : kernel_fork S₂.g) (hc : is_limit c) :\n homology_map_data φ\n (homology_data.of_zeros S₁ hf₁ hg₁)\n (homology_data.of_limit_kernel_fork S₂ hf₂ c hc) :=\nbegin\n let α := hc.lift (kernel_fork.of_ι φ.τ₂ (by rw [φ.comm₂₃, hg₁, zero_comp])),\n have hα : α ≫ c.ι = φ.τ₂ := by simp only [fork.is_limit.lift_ι', kernel_fork.ι_of_ι],\n exact { left :=\n { φK := α,\n φH := α,\n commf'' := by { dsimp, simp only [hf₁, left_homology_data.of_zeros_f',\n zero_comp, left_homology_data.of_limit_kernel_fork_f', comp_zero], }, },\n right :=\n { φQ := φ.τ₂,\n φH := α,\n commg'' := by { dsimp, simp only [φ.comm₂₃, right_homology_data.of_zeros_g',\n right_homology_data.of_limit_kernel_fork_f'], }, }, }\nend\n\ninstance is_iso_cycles_map_of_is_iso_of_mono {C : Type*} [category C] [has_zero_morphisms C]\n {S₁ S₂ : short_complex C} (φ : S₁ ⟶ S₂) [S₁.has_left_homology] [S₂.has_left_homology]\n [is_iso φ.τ₂] [mono φ.τ₃] :\n is_iso (cycles_map φ) :=\nbegin\n refine ⟨⟨S₁.lift_cycles (S₂.cycles_i ≫ inv φ.τ₂) _, _, _⟩⟩,\n { simp only [← cancel_mono φ.τ₃, assoc, ← φ.comm₂₃, is_iso.inv_hom_id_assoc, lift_cycles_i,\n cycles_i_g, zero_comp], },\n { simp only [← cancel_mono S₁.cycles_i, assoc, lift_cycles_i, cycles_map_i_assoc,\n is_iso.hom_inv_id, comp_id, id_comp], },\n { simp only [← cancel_mono S₂.cycles_i, assoc, is_iso.inv_hom_id, comp_id,\n lift_cycles_comp_cycles_map, lift_cycles_i, id_comp], },\nend\n\ninstance is_iso_cycles_co_map_of_is_iso_of_epi {C : Type*} [category C] [has_zero_morphisms C]\n {S₁ S₂ : short_complex C} (φ : S₁ ⟶ S₂) [S₁.has_right_homology] [S₂.has_right_homology]\n [is_iso φ.τ₂] [epi φ.τ₁] :\n is_iso (cycles_co_map φ) :=\nbegin\n refine ⟨⟨S₂.desc_cycles_co (inv φ.τ₂ ≫ S₁.p_cycles_co) _, _ ,_⟩⟩,\n { simp only [← cancel_epi φ.τ₁, φ.comm₁₂_assoc, is_iso.hom_inv_id_assoc,\n f_cycles_co_p, comp_zero], },\n { simp only [←cancel_epi S₁.p_cycles_co, is_iso.hom_inv_id_assoc,\n p_cycles_co_map_assoc, p_desc_cycles_co, comp_id], },\n { simp only [←cancel_epi S₂.p_cycles_co, p_desc_cycles_co_assoc, assoc, p_cycles_co_map,\n is_iso.inv_hom_id_assoc, comp_id], },\nend\n\ninstance mono_cycles_map_of_mono_of_mono {C : Type*} [category C] [has_zero_morphisms C]\n {S₁ S₂ : short_complex C} (φ : S₁ ⟶ S₂) [S₁.has_homology] [S₂.has_homology]\n [mono φ.τ₂] [mono φ.τ₃] : mono (cycles_map φ) :=\nbegin\n simp only [← mono_comp_right_iff_mono _ S₂.cycles_i, cycles_map_i, mono_comp_right_iff_mono],\n apply_instance,\nend\n\ninstance epi_cycles_co_map_of_epi_of_epi {C : Type*} [category C] [has_zero_morphisms C]\n {S₁ S₂ : short_complex C} (φ : S₁ ⟶ S₂) [S₁.has_homology] [S₂.has_homology]\n [epi φ.τ₂] [epi φ.τ₁] : epi (cycles_co_map φ) :=\nbegin\n simp only [← epi_comp_left_iff_epi S₁.p_cycles_co, p_cycles_co_map, epi_comp_left_iff_epi],\n apply_instance,\nend\n\nlemma quasi_iso_iff_exact_and_mono {C : Type*} [category C] [abelian C]\n {S₁ S₂ : short_complex C}\n (φ : S₁ ⟶ S₂) (hf₁ : S₁.f = 0) (hg₁ : S₁.g = 0) (hf₂ : S₂.f = 0) :\n short_complex.quasi_iso φ ↔\n (mk φ.τ₂ S₂.g (by rw [φ.comm₂₃, hg₁, zero_comp])).exact ∧ mono φ.τ₂ :=\nbegin\n rw [exact_iff_epi_to_cycles,\n (homology_map_data.of_zeros_of_limit_kernel_fork φ hf₁ hg₁ hf₂\n _ S₂.cycles_is_kernel).left.quasi_iso_iff,\n homology_map_data.of_zeros_of_limit_kernel_fork_left_φH],\n have w : φ.τ₂ ≫ S₂.g = 0 := by rw [φ.comm₂₃, hg₁, zero_comp],\n let S := mk φ.τ₂ S₂.g w,\n change is_iso (S₂.lift_cycles φ.τ₂ w) ↔ epi S.to_cycles ∧ _,\n let γ : S₂ ⟶ S :=\n { τ₁ := 0,\n τ₂ := 𝟙 _,\n τ₃ := 𝟙 _,\n comm₁₂' := by simp only [hf₂, zero_comp], },\n have eq : S₂.lift_cycles φ.τ₂ w ≫ cycles_map γ = S.to_cycles,\n { simp only [← cancel_mono S.cycles_i, comp_id, lift_cycles_comp_cycles_map,\n lift_cycles_i, to_cycles_i], },\n conv_rhs { rw ← S₂.lift_cycles_i φ.τ₂ w, },\n simp only [is_iso_iff_mono_and_epi, ← eq, epi_comp_right_iff_epi,\n mono_comp_right_iff_mono],\n tauto,\nend\n\nend category_theory.short_complex\n\nopen category_theory category_theory.limits category_theory.category\n\nnamespace cochain_complex\n\nsection\n\nvariables {C : Type*} [category C] {a b : ℤ} (h : a+1=b)\n [has_zero_morphisms C] [has_zero_object C] {A B : C} (φ : A ⟶ B)\n\nnamespace double\n\ninclude h φ\n@[nolint unused_arguments]\ndef X (n : ℤ) : C := if n = a then A else if n = b then B else 0\nomit h φ\n\ndef X_iso₁ {n : ℤ} (hn : n = a) :\n X h φ n ≅ A :=\neq_to_iso (by { subst hn, dsimp [X], simp, })\n\ndef X_iso₂ {n : ℤ} (hn : n = b) :\n X h φ n ≅ B :=\neq_to_iso (begin\n subst hn,\n simp only [X, if_neg (show ¬n=a, by linarith), eq_self_iff_true, if_true, ite_eq_right_iff],\nend)\n\nlemma X_is_zero (n : ℤ) (hn₁ : n ≠ a) (hn₂ : n ≠ b) :\n is_zero (X h φ n) :=\nby simpa only [X, if_neg hn₁, if_neg hn₂] using is_zero_zero C\n\ndef d (i j : ℤ) :\n X h φ i ⟶ X h φ j :=\nbegin\n by_cases hi : i = a,\n { by_cases hj : j = b,\n { exact (X_iso₁ h φ hi).hom ≫ φ ≫ (X_iso₂ h φ hj).inv, },\n { exact 0, }, },\n { exact 0, },\nend\n\nlemma d_eq' {i j : ℤ} (hi : i = a) (hj : j = b) :\n double.d h φ i j = (X_iso₁ h φ hi).hom ≫ φ ≫ (X_iso₂ h φ hj).inv :=\nby simp only [d, dif_pos hi, dif_pos hj]\n\n@[simp]\nlemma d_eq :\n double.d h φ a b = (X_iso₁ h φ rfl).hom ≫ φ ≫ (X_iso₂ h φ rfl).inv :=\nd_eq' _ _ rfl rfl\n\nlemma d_eq_zero₁ {i j : ℤ} (hi : i ≠ a) :\n double.d h φ i j = 0 :=\nby simp only [d, dif_neg hi]\n\nlemma d_eq_zero₂ {i j : ℤ} (hj : j ≠ b) :\n double.d h φ i j = 0 :=\nbegin\n by_cases hi : i = a,\n { simp only [d, dif_pos hi, dif_neg hj], },\n { simp only [d_eq_zero₁ _ _ hi], },\nend\n\n@[simp, reassoc]\nlemma d_comp_d {i j k : ℤ} :\n double.d h φ i j ≫ double.d h φ j k = 0 :=\nbegin\n by_cases hi : i = a,\n { by_cases hj : j = b,\n { have hk : j ≠ a := by linarith,\n rw [d_eq_zero₁ _ _ hk, comp_zero], },\n { simp only [d_eq_zero₂ _ _ hj, zero_comp], }, },\n { simp only [d_eq_zero₁ _ _ hi, zero_comp], },\nend\n\nend double\n\n@[simps]\ndef double : cochain_complex C ℤ :=\n{ X := double.X h φ,\n d := λ i j, double.d h φ i j,\n shape' := λ i j hij, begin\n change i+1 ≠ j at hij,\n by_cases hi : i = a,\n { rw double.d_eq_zero₂,\n exact λ hj, hij (by linarith), },\n { rw double.d_eq_zero₁ _ _ hi, },\n end, }\n\nnamespace double\n\nsection desc\n\nvariables (K : cochain_complex C ℤ) (fa : A ⟶ K.X a) (fb : B ⟶ K.X b)\n (comm : fa ≫ K.d a b = φ ≫ fb) {c : ℤ} (hc : b+1 = c)\n (w : fb ≫ K.d b c = 0)\n\ninclude fa fb\n\ndef desc.f (n : ℤ) : (double h φ).X n ⟶ K.X n :=\nbegin\n by_cases ha : n = a,\n { exact (double.X_iso₁ h φ ha).hom ≫ fa ≫ eq_to_hom (by rw ha), },\n { by_cases hb : n = b,\n { exact (double.X_iso₂ h φ hb).hom ≫ fb ≫ eq_to_hom (by rw hb), },\n { exact 0, }, },\nend\n\n@[simp]\nlemma desc.f₁ : desc.f h φ K fa fb a = (double.X_iso₁ h φ rfl).hom ≫ fa :=\nby simp only [desc.f, dif_pos rfl, eq_to_hom_refl, comp_id]\n\n@[simp]\nlemma desc.f₂ : desc.f h φ K fa fb b = (double.X_iso₂ h φ rfl).hom ≫ fb :=\nby simp only [desc.f, dif_neg (show b ≠ a, by linarith), dif_pos rfl, eq_to_hom_refl, comp_id]\n\nlemma desc.f_eq_zero (n : ℤ) (ha : n ≠ a) (hb : n ≠ b) : desc.f h φ K fa fb n = 0 :=\nby simp only [desc.f, dif_neg ha, dif_neg hb]\n\ninclude comm w hc\n\n@[simps]\ndef desc : double h φ ⟶ K :=\n{ f := desc.f h φ K fa fb,\n comm' := λ i j hij, begin\n change i+1 = j at hij,\n by_cases ha : i = a,\n { have hb : j = b := by linarith,\n substs ha hb,\n simp only [desc.f₁, assoc, double_d, d_eq, desc.f₂, iso.inv_hom_id_assoc,\n iso.cancel_iso_hom_left, comm], },\n { simp only [double_d, d_eq_zero₁ h _ ha, zero_comp],\n by_cases hb : i = b,\n { have hc : j = c := by linarith,\n substs hc hb,\n simp only [desc.f₂, assoc, w, comp_zero], },\n { rw [desc.f_eq_zero _ _ _ _ _ _ ha hb, zero_comp], }, },\n end, }\n\nend desc\n\nsection lift\n\nvariables (K : cochain_complex C ℤ) (fa : K.X a ⟶ A) (fb : K.X b ⟶ B)\n (comm : fa ≫ φ = K.d a b ≫ fb) {c : ℤ} (hc : c+1 = a)\n (w : K.d c a ≫ fa = 0)\n\ninclude fa fb\n\ndef lift.f (n : ℤ) : K.X n ⟶ (double h φ).X n :=\nbegin\n by_cases ha : n = a,\n { exact eq_to_hom (by rw ha) ≫ fa ≫ (double.X_iso₁ h φ ha).inv, },\n { by_cases hb : n = b,\n { exact eq_to_hom (by rw hb) ≫ fb ≫ (double.X_iso₂ h φ hb).inv, },\n { exact 0, }, },\nend\n\n@[simp]\nlemma lift.f₁ : lift.f h φ K fa fb a = fa ≫ (double.X_iso₁ h φ rfl).inv :=\nby simp only [lift.f, dif_pos rfl, eq_to_hom_refl, id_comp]\n\n@[simp]\nlemma lift.f₂ : lift.f h φ K fa fb b = fb ≫ (double.X_iso₂ h φ rfl).inv :=\nby simp only [lift.f, dif_neg (show b ≠ a, by linarith), dif_pos rfl, eq_to_hom_refl, id_comp]\n\nlemma lift.f_eq_zero (n : ℤ) (ha : n ≠ a) (hb : n ≠ b) : lift.f h φ K fa fb n = 0 :=\nby simp only [lift.f, dif_neg ha, dif_neg hb]\n\ninclude comm w hc\n\n@[simps]\ndef lift : K ⟶ double h φ :=\n{ f := lift.f h φ K fa fb,\n comm' := λ i j hij, begin\n change i+1 = j at hij,\n by_cases hb : j = b,\n { have ha : i = a := by linarith,\n substs ha hb,\n simp only [lift.f₁, double_d, d_eq, assoc, iso.inv_hom_id_assoc, lift.f₂,\n iso.cancel_iso_inv_right_assoc, comm], },\n { simp only [double_d, d_eq_zero₂ h _ hb, comp_zero],\n by_cases ha : j = a,\n { have hc : i = c := by linarith,\n substs hc ha,\n simp only [lift.f₁, reassoc_of w, zero_comp], },\n { rw [lift.f_eq_zero _ _ _ _ _ _ ha hb, comp_zero], }, },\n end, }\n\nend lift\n\nsection map\n\nvariables (φ) {A' B' : C} (φ' : A' ⟶ B') (α : A ⟶ A') (β : B ⟶ B') (comm : φ ≫ β = α ≫ φ')\n\ninclude comm\n\ndef map : double h φ ⟶ double h φ' :=\ndouble.desc h φ _ (α ≫ (double.X_iso₁ h φ' rfl).inv)\n (β ≫ (double.X_iso₂ h φ' rfl).inv) (by tidy) rfl\n (is_zero.eq_of_tgt (double.X_is_zero h φ' (b+1) (by linarith) (by linarith)) _ _)\n\n@[simp]\nlemma map_f₁ :\n (map h φ φ' α β comm).f a = (double.X_iso₁ h φ rfl).hom ≫ α ≫ (double.X_iso₁ h φ' rfl).inv :=\nby simp only [map, desc_f, desc.f₁]\n\n@[simp]\nlemma map_f₂ :\n (map h φ φ' α β comm).f b = (double.X_iso₂ h φ rfl).hom ≫ β ≫ (double.X_iso₂ h φ' rfl).inv :=\nby simp only [map, desc_f, desc.f₂]\n\nend map\n\nvariables {h φ}\n\n@[ext]\nlemma ext {K : cochain_complex C ℤ} (f₁ f₂ : double h φ ⟶ K)\n (ha : f₁.f a = f₂.f a) (hb : f₁.f b = f₂.f b) : f₁ = f₂ :=\nbegin\n ext n,\n by_cases ha' : n = a,\n { subst ha',\n exact ha, },\n { by_cases hb' : n = b,\n { subst hb',\n exact hb, },\n { apply is_zero.eq_of_src,\n exact double.X_is_zero h φ _ ha' hb', }, },\nend\n\n@[ext]\nlemma ext' {K : cochain_complex C ℤ} (f₁ f₂ : K ⟶ double h φ)\n (ha : f₁.f a = f₂.f a) (hb : f₁.f b = f₂.f b) : f₁ = f₂ :=\nbegin\n ext n,\n by_cases ha' : n = a,\n { subst ha',\n exact ha, },\n { by_cases hb' : n = b,\n { subst hb',\n exact hb, },\n { apply is_zero.eq_of_tgt,\n exact double.X_is_zero h φ _ ha' hb', }, },\nend\n\n@[simp, reassoc]\nlemma w_from {K : cochain_complex C ℤ} (f : double h φ ⟶ K) (c : ℤ) :\n f.f b ≫ K.d b c = 0 :=\nbegin\n by_cases hc : b+1 = c,\n { rw [f.comm b c, double_d, d_eq_zero₁ h φ (show b ≠ a, by linarith), zero_comp], },\n { rw [K.shape _ _ hc, comp_zero], },\nend\n\n@[simp, reassoc]\nlemma w_to {K : cochain_complex C ℤ} (f : K ⟶ double h φ) (c : ℤ) :\n K.d c a ≫ f.f a = 0 :=\nbegin\n by_cases hc : c+1 = a,\n { rw [← f.comm c a, double_d, d_eq_zero₂ h φ (show a ≠ b, by linarith), comp_zero], },\n { rw [K.shape _ _ hc, zero_comp], },\nend\n\nvariables (h φ)\n\n@[simps]\ndef ι : (homological_complex.single _ _ b).obj B ⟶ double h φ :=\ndouble.lift h φ _ 0 (homological_complex.single_obj_X_self _ _ _ _).hom (by simp)\n (sub_add_cancel a 1) (by simp)\n\n@[simps]\ndef π : double h φ ⟶ (homological_complex.single _ _ a).obj A :=\ndouble.desc h φ _ (homological_complex.single_obj_X_self _ _ _ _).inv 0 (by simp) rfl (by simp)\n\n@[simp, reassoc]\nlemma ι_π : ι h φ ≫ π h φ = 0 :=\nbegin\n ext n,\n by_cases ha : n = a,\n { subst ha,\n simp only [homological_complex.comp_f, ι_f, lift.f₁, zero_comp,\n homological_complex.zero_apply], },\n { apply is_zero.eq_of_tgt,\n dsimp [homological_complex.single],\n rw [if_neg ha],\n exact is_zero_zero C, },\nend\n\nend double\n\nend\n\nsection preadditive\n\nnamespace double\n\nvariables {C : Type*} [category C] [preadditive C] [has_zero_object C]\n {a b : ℤ} (h : a+1=b) {A B A' B' : C} {φ : A ⟶ B} {φ' : A' ⟶ B'}\n\ndef homotopy_mk (f₁ f₂ : double h φ ⟶ double h φ') (γ : B ⟶ A')\n (hγ₁ : f₁.f a = (double h φ).d a b ≫ (X_iso₂ h φ rfl).hom ≫\n γ ≫ (X_iso₁ h φ' rfl).inv + f₂.f a)\n (hγ₂ : f₁.f b = ((X_iso₂ h φ rfl).hom ≫ γ ≫ (X_iso₁ h φ' rfl).inv) ≫\n (double h φ').d a b + f₂.f b) :\n homotopy f₁ f₂ :=\n{ hom := λ i j, begin\n by_cases hb : i = b,\n { by_cases ha : j = a,\n { exact (X_iso₂ h φ hb).hom ≫ γ ≫ (X_iso₁ h φ' ha).inv, },\n { exact 0,}, },\n { exact 0, },\n end,\n zero' := λ i j (hij : j+1 ≠ i), begin\n by_cases hb : i = b,\n { rw dif_pos hb,\n by_cases ha : j = a,\n { exfalso,\n apply hij,\n rw [ha, hb, h], },\n { rw dif_neg ha, }, },\n { rw dif_neg hb, },\n end,\n comm := λ i, begin\n have h' : (complex_shape.up ℤ).rel a b := h,\n by_cases ha : i = a,\n { subst ha,\n have h'' : (complex_shape.up ℤ).rel (i-1) i := sub_add_cancel i 1,\n simp only [d_next_eq _ h', prev_d_eq _ h'', dif_pos rfl,\n dif_neg (show i ≠ b, by linarith), zero_comp, add_zero, hγ₁], },\n { by_cases hb : i = b,\n { subst hb,\n have h'' : (complex_shape.up ℤ).rel i (i+1) := rfl,\n simp only [prev_d_eq _ h', d_next_eq _ h'', dif_neg (succ_ne_self i), dif_pos rfl,\n comp_zero, zero_add, hγ₂], },\n { exact is_zero.eq_of_src (X_is_zero h φ i ha hb) _ _, }, },\n end, }\n\n/-- should be moved -/\nlemma four_cases {a b : ℤ} (h : a+1=b) (n : ℤ) :\n (n < a ∨ b < n) ∨ n = a ∨ n = b :=\nbegin\n by_cases h₁ : n < a,\n { exact or.inl (or.inl h₁), },\n { by_cases h₂ : b < n,\n { exact or.inl (or.inr h₂), },\n { refine or.inr _,\n simp only [not_lt] at h₁ h₂,\n cases h₁.lt_or_eq with h₃ h₃,\n { cases h₂.lt_or_eq with h₄ h₄,\n { exfalso,\n linarith, },\n { exact or.inr h₄, }, },\n { exact or.inl h₃.symm, }, }, },\nend\n\nend double\n\nend preadditive\n\nsection abelian\n\nvariables {C : Type*} [category C] [abelian C] {a b : ℤ} (h : a+1=b) {A B E : C} (φ : A ⟶ B)\n {i : B ⟶ E} {p : E ⟶ A} (w : i ≫ p = 0)\n\ninstance double_strictly_le :\n (double h φ).is_strictly_le b :=\n⟨λ n hn, double.X_is_zero h φ n (by linarith) (by linarith)⟩\n\ninstance double_strictly_ge :\n (double h φ).is_strictly_ge a :=\n⟨λ n hn, double.X_is_zero h φ n (by linarith) (by linarith)⟩\n\ninclude h\n\nlemma double.is_le_iff_epi : (double h φ).is_le a ↔ epi φ :=\nbegin\n rw [is_le_iff_of_is_le_next (double h φ) h, ← short_complex.exact_iff_is_zero_homology,\n short_complex.exact_iff_epi],\n { have ha : a = (complex_shape.up ℤ).prev b := by { rw prev, linarith, },\n subst ha,\n change epi (double.d _ _ _ _) ↔ _,\n rw double.d_eq,\n split,\n { intro hφ,\n haveI := @epi_of_epi _ _ _ _ _ _ _ hφ,\n have eq := φ ≫= (double.X_iso₂ h φ rfl).inv_hom_id,\n rw [comp_id, ← assoc] at eq,\n rw ← eq,\n apply epi_comp, },\n { introI,\n haveI := epi_comp φ (double.X_iso₂ h φ rfl).inv,\n apply epi_comp, }, },\n { apply is_zero.eq_of_tgt,\n exact double.X_is_zero h φ _ (by { rw [next], linarith, })\n (by simpa only [next] using succ_ne_self b), },\nend\n\ninstance double_le [epi φ] :\n (double h φ).is_le a :=\nby { rw double.is_le_iff_epi, apply_instance, }\n\nlemma double.is_ge_iff_mono : (double h φ).is_ge b ↔ mono φ :=\nbegin\n rw [is_ge_iff_of_is_ge_prev (double h φ) h, ← short_complex.exact_iff_is_zero_homology,\n short_complex.exact_iff_mono],\n { have hb : b = (complex_shape.up ℤ).next a := by rw [next, h],\n subst hb,\n change mono (double.d _ _ _ _) ↔ _,\n rw double.d_eq,\n split,\n { intro hφ,\n rw ← assoc at hφ,\n haveI := @mono_of_mono _ _ _ _ _ _ _ hφ,\n have eq := (double.X_iso₁ h φ rfl).inv_hom_id =≫ φ,\n rw [id_comp, assoc] at eq,\n rw ← eq,\n apply mono_comp, },\n { introI,\n haveI := mono_comp φ (double.X_iso₂ h φ rfl).inv,\n apply mono_comp, }, },\n { apply is_zero.eq_of_src,\n exact double.X_is_zero h φ _ (by simpa only [prev] using pred_ne_self a)\n (by { rw [prev], linarith, }), },\nend\n\ninstance double_ge [mono φ] :\n (double h φ).is_ge b :=\nby { rw double.is_ge_iff_mono, apply_instance, }\n\ninclude w\n\ndef double.σ : (double h i) ⟶ (homological_complex.single _ (complex_shape.up ℤ) b).obj A :=\nlift_single _ _ ((double.X_iso₂ h i rfl).hom ≫ p ≫\n (homological_complex.single_obj_X_self _ _ _ A).inv) _ h\nbegin\n dsimp,\n simp only [double.d_eq, assoc, iso.inv_hom_id_assoc, preadditive.is_iso.comp_left_eq_zero,\n reassoc_of w, zero_comp],\nend\n\n@[simp]\nlemma double.σ_f₁ : (double.σ h w).f a = 0 :=\nbegin\n dsimp [double.σ, lift_single],\n rw dif_neg (show ¬ a=b, by linarith),\nend\n\n@[simp]\nlemma double.σ_f₂ :\n (double.σ h w).f b = (double.X_iso₂ h i rfl).hom ≫ p\n ≫ (homological_complex.single_obj_X_self C (complex_shape.up ℤ) b A).inv :=\nbegin\n dsimp only [double.σ, lift_single],\n rw dif_pos rfl,\nend\n\ndef double.σ' : (homological_complex.single _ (complex_shape.up ℤ) a).obj B ⟶\n double h p :=\nbegin\n refine desc_single _ _ ((homological_complex.single_obj_X_self _ _ _ B).hom ≫ i ≫\n (double.X_iso₁ h p rfl).inv) _ h _,\n { dsimp,\n simp only [double.d_eq, assoc, iso.inv_hom_id_assoc, preadditive.is_iso.comp_left_eq_zero,\n reassoc_of w, zero_comp], },\nend\n\nomit w\n\ndef double.homotopy_πσ'_σι : homotopy (double.π h i ≫ double.σ' h w)\n (-double.σ h w ≫ double.ι h p) :=\ndouble.homotopy_mk _ _ _ (𝟙 _)\n (by { dsimp, simp [double.π, double.σ', double.ι], })\n (by { dsimp, simp [double.π, double.σ, double.ι], })\n\nlemma double.quasi_iso_σ' (ex : (short_complex.mk _ _ w).short_exact) :\n quasi_iso (double.σ' h w) :=\nbegin\n have hb : b = (complex_shape.up ℤ).next a := by rw [next, h],\n subst hb,\n haveI := ex.mono_f,\n haveI := ex.epi_g,\n rw quasi_iso_iff_of_is_le_of_is_ge (double.σ' h w) a,\n apply short_complex.quasi_iso.of_kernel_fork _ _ _,\n { refine ⟨λ Z f₁ f₂ eq, is_zero.eq_of_src _ _ _⟩,\n refine double.X_is_zero h p _\n (by { rw prev, linarith, })\n (by { rw prev, linarith, }), },\n { refl, },\n { let e : parallel_pair p 0 ≅\n parallel_pair (((double h) p).sc' a).g 0 :=\n parallel_pair.ext (double.X_iso₁ h p rfl).symm\n ((double.X_iso₂ h p rfl).symm) (by tidy) (by tidy),\n equiv_rw (is_limit.postcompose_inv_equiv e _).symm,\n refine is_limit.of_iso_limit ex.exact.f_is_kernel _,\n refine fork.ext (homological_complex.single_obj_X_self _ (complex_shape.up ℤ) a B).symm _,\n dsimp only [cones.postcompose, fork.ι],\n dsimp [e, double.σ'],\n simp only [desc_single_f, assoc, iso.inv_hom_id, comp_id, eq_to_hom_trans_assoc,\n eq_to_hom_refl, id_comp], },\nend\n\nlemma double.quasi_iso_σ (ex : (short_complex.mk _ _ w).short_exact) :\n quasi_iso (double.σ h w) :=\nbegin\n have ha : a = (complex_shape.up ℤ).prev b := by { rw prev, linarith, },\n subst ha,\n haveI := ex.mono_f,\n haveI := ex.epi_g,\n rw quasi_iso_iff_of_is_le_of_is_ge (double.σ h w) b,\n apply short_complex.quasi_iso.of_cokernel_cofork _ _ _,\n { refine ⟨λ Z f₁ f₂ eq, is_zero.eq_of_tgt _ _ _⟩,\n refine double.X_is_zero h i _\n (by { rw [next, prev], linarith, })\n (by { rw [next], linarith, }), },\n { refl, },\n { dsimp [double.σ],\n let e : parallel_pair i 0 ≅\n parallel_pair (((double h) i).sc' b).f 0 :=\n parallel_pair.ext (double.X_iso₁ h i rfl).symm (double.X_iso₂ h i rfl).symm\n (by tidy) (by tidy),\n equiv_rw (is_colimit.precompose_hom_equiv e _).symm,\n refine is_colimit.of_iso_colimit ex.exact.g_is_cokernel _,\n refine cofork.ext (homological_complex.single_obj_X_self _ (complex_shape.up ℤ) b A).symm _,\n dsimp only [cocones.precompose, cofork.π],\n dsimp [e, double.σ],\n simp only [lift_single_f, iso.inv_hom_id_assoc], },\nend\n\nlemma double.is_iso_iff {K L : cochain_complex C ℤ} [K.is_strictly_le b] [K.is_strictly_ge a]\n [L.is_strictly_le b] [L.is_strictly_ge a] (φ : K ⟶ L) :\n is_iso φ ↔ (is_iso (φ.f a) ∧ is_iso (φ.f b)) :=\nbegin\n split,\n { introI,\n split; exact (infer_instance : is_iso ((homological_complex.eval _ _ _).map φ)), },\n { intro hφ,\n haveI : ∀ (n : ℤ), is_iso (φ.f n),\n { intro n,\n rcases double.four_cases h n with ⟨h' | h'⟩ | ⟨h' | h'⟩,\n { refine ⟨⟨0, (is_strictly_ge.is_zero K a _ h').eq_of_src _ _,\n (is_strictly_ge.is_zero L a _ h').eq_of_src _ _⟩⟩, },\n { refine ⟨⟨0, (is_strictly_le.is_zero K b _ h').eq_of_src _ _,\n (is_strictly_le.is_zero L b _ h').eq_of_src _ _⟩⟩, },\n all_goals { unfreezingI { subst h', }, tauto, }, },\n apply homological_complex.hom.is_iso_of_components, },\nend\n\nlemma exists_iso_double (K : cochain_complex C ℤ) [K.is_strictly_le b] [K.is_strictly_ge a] :\n ∃ (A B : C) (φ : A ⟶ B), nonempty (K ≅ double h φ) :=\nbegin\n let α := double.lift h (K.d a b) K (𝟙 _) (𝟙 _) (by simp) (show (a-1)+1=a, by linarith)\n ((is_strictly_ge.is_zero K a (a-1) (by linarith)).eq_of_src _ _),\n haveI : is_iso α,\n { simp only [double.is_iso_iff h α, id_comp, double.lift_f, double.lift.f₁, double.lift.f₂],\n split; apply_instance, },\n exact ⟨_, _, K.d a b, ⟨as_iso α⟩⟩,\nend\n\nvariables {X₁ X₂ X₃ : C}\n\n@[simp]\ndef single_to_double (i : X₁ ⟶ X₂) (p : X₂ ⟶ X₃) (w : i ≫ p = 0) :\n ((homological_complex.single C _ a).obj X₁) ⟶ double h p :=\ndesc_single _ _ ((homological_complex.single_obj_X_self C\n (complex_shape.up ℤ) a X₁).hom ≫ i ≫ (double.X_iso₁ h p rfl).inv) _ h\n (by simp [reassoc_of w])\n\n@[simp]\ndef single_to_double' (g : X₁ ⟶ X₃) (p : X₂ ⟶ X₃) :\n ((homological_complex.single C _ b).obj X₁) ⟶ double h p :=\n desc_single _ (double h p) ((homological_complex.single_obj_X_self C\n (complex_shape.up ℤ) b X₁).hom ≫ g ≫ (double.X_iso₂ h p rfl).inv) (b+1) rfl\n (is_zero.eq_of_tgt (double.X_is_zero h p (b+1) (by simp only [← h, add_assoc, ne.def,\n add_right_eq_self, add_self_eq_zero, one_ne_zero, not_false_iff]) (succ_ne_self b)) _ _)\n\nvariables {h φ}\n\nlemma eq_single_to_double {Z : C} (f : ((homological_complex.single C _ a).obj Z) ⟶ double h φ) :\n ∃ (g : Z ⟶ A) (hg : g ≫ φ = 0), f = single_to_double h g φ hg :=\n⟨(homological_complex.single_obj_X_self C\n (complex_shape.up ℤ) a Z).inv ≫ f.f a ≫ (double.X_iso₁ h φ rfl).hom,\n by simpa only [preadditive.is_iso.comp_left_eq_zero, double_d, double.d_eq,\n homological_complex.single_obj_d, zero_comp,\n iso.inv_hom_id, comp_id, assoc] using f.comm a b =≫ (double.X_iso₂ h φ rfl).hom,\n from_single_ext _ _ a (by simp)⟩\n\nlemma eq_single_to_double' {Z : C} (f : ((homological_complex.single C _ b).obj Z) ⟶ double h φ) :\n ∃ (g : Z ⟶ B), f = single_to_double' h g φ :=\n⟨(homological_complex.single_obj_X_self C\n (complex_shape.up ℤ) b Z).inv ≫ f.f b ≫ (double.X_iso₂ h φ rfl).hom,\n from_single_ext _ _ b (by simp)⟩\n\nvariables (h φ)\n\nlemma double.is_zero_homology₁_iff :\n is_zero ((double h φ).homology a) ↔ mono φ :=\nbegin\n have hb : b = (complex_shape.up ℤ).next a := by { rw next, linarith, },\n subst hb,\n rw [← short_complex.exact_iff_is_zero_homology, short_complex.exact_iff_mono],\n { dsimp [homological_complex.short_complex_functor],\n have eq : homological_complex.d_from (double h φ) a = _ := double.d_eq h φ,\n simp only [eq, mono_comp_left_iff_mono, mono_comp_right_iff_mono], },\n { exact double.d_eq_zero₂ h φ (by linarith), }\nend\n\nlemma double.is_zero_homology₂_iff :\n is_zero ((double h φ).homology b) ↔ epi φ :=\nbegin\n have ha : a = (complex_shape.up ℤ).prev b := by { rw prev, linarith, },\n subst ha,\n rw [← short_complex.exact_iff_is_zero_homology, short_complex.exact_iff_epi],\n { dsimp [homological_complex.short_complex_functor],\n have eq : homological_complex.d_to (double h φ) b = _ := double.d_eq h φ,\n simp only [eq, ← assoc, epi_comp_right_iff_epi, epi_comp_left_iff_epi], },\n { exact double.d_eq_zero₁ h φ (by linarith), },\nend\n\nlemma is_iso_homology_map₁_single_to_double_iff_exact_and_mono\n (i : X₁ ⟶ X₂) (p : X₂ ⟶ X₃) (w : i ≫ p = 0) :\nis_iso (homology_map (single_to_double h i p w) a) ↔\n (short_complex.mk _ _ w).exact ∧ mono i :=\nbegin\n erw is_iso_homology_map_iff_short_complex_quasi_iso,\n rw short_complex.quasi_iso_iff_exact_and_mono, rotate,\n { refl, },\n { refl, },\n { exact double.d_eq_zero₂ h p (by linarith), },\n apply iff.and,\n { apply short_complex.exact_iff_of_iso,\n have hb : (complex_shape.up ℤ).next a = b := by { rw next, linarith, },\n refine short_complex.mk_iso\n (homological_complex.single_obj_X_self _ (complex_shape.up ℤ) _ X₁)\n (double.X_iso₁ h p rfl) (double.X_iso₂ h p hb) _ _ ,\n { dsimp,\n simp only [desc_single_f, assoc, iso.inv_hom_id, comp_id], },\n { dsimp,\n simpa only [← cancel_mono (double.X_iso₂ h p hb).inv, assoc, iso.hom_inv_id, comp_id,\n (double.d_eq' h p rfl hb).symm], }, },\n { simp only [single_to_double, homological_complex.short_complex_functor_map_τ₂,\n desc_single_f, mono_comp_left_iff_mono, mono_comp_right_iff_mono], },\nend\n\nvariable {φ}\n\nlemma single_to_double_quasi_iso_iff (i : X₁ ⟶ X₂) (p : X₂ ⟶ X₃) (w : i ≫ p = 0) :\n quasi_iso (single_to_double h i p w) ↔ (short_complex.mk _ _ w).short_exact :=\nbegin\n split,\n { intro hw,\n have hw' := (is_iso_homology_map₁_single_to_double_iff_exact_and_mono h i p w).1 (hw.is_iso a),\n haveI : mono i := hw'.2,\n haveI : epi p,\n { simp only [← double.is_zero_homology₂_iff h],\n haveI := hw.is_iso b,\n exact is_zero.of_iso (is_le.is_zero _ a _ (by linarith))\n (as_iso (homology_map (single_to_double h i p w) b)).symm, },\n exact short_complex.short_exact.mk hw'.1, },\n { intro hw,\n haveI := hw.epi_g,\n refine ⟨λ n, _⟩,\n rcases double.four_cases h n with hn | ⟨hn | hn⟩,\n { refine ⟨⟨0, is_zero.eq_of_src _ _ _, is_zero.eq_of_src _ _ _⟩⟩,\n { cases hn,\n { exact is_ge.is_zero _ _ _ hn, },\n { exact is_le.is_zero _ a n (by linarith), }, },\n { cases hn,\n { exact is_ge.is_zero _ _ _ hn, },\n { exact is_le.is_zero _ _ _ hn, }, }, },\n { subst hn,\n exact (is_iso_homology_map₁_single_to_double_iff_exact_and_mono h i p w).2 ⟨hw.exact, hw.mono_f⟩, },\n { subst hn,\n exact ⟨⟨0, is_zero.eq_of_src (is_le.is_zero _ a _ (by linarith)) _ _,\n is_zero.eq_of_src\n (by simpa only [double.is_zero_homology₂_iff] using hw.epi_g) _ _⟩⟩, }, },\nend\n\nlemma from_double_ext {K L : cochain_complex C ℤ} [K.is_strictly_le b] [K.is_strictly_ge a]\n (f₁ f₂ : K ⟶ L) (h₁ : f₁.f a = f₂.f a) (h₂ : f₁.f b = f₂.f b) : f₁ = f₂ :=\nbegin\n ext n,\n rcases double.four_cases h n with h' | (h' | h'),\n { apply is_zero.eq_of_src,\n cases h',\n { exact is_strictly_ge.is_zero _ a _ h', },\n { exact is_strictly_le.is_zero _ b _ h', }, },\n { unfreezingI { subst h', },\n exact h₁, },\n { unfreezingI { subst h', },\n exact h₂, },\nend\n\nomit h\nvariable (φ)\n\ninstance mapping_cone_single_map_is_strictly_le :\n (mapping_cone ((homological_complex.single _ _ 0).map φ)).is_strictly_le 0 :=\n⟨λ n hn, begin\n rw mapping_cone.X_is_zero_iff,\n split; exact is_strictly_le.is_zero _ 0 _ (by linarith),\nend⟩\n\ninstance mapping_cone_single_map_is_strictly_ge :\n (mapping_cone ((homological_complex.single _ _ 0).map φ)).is_strictly_ge (-1) :=\n⟨λ n hn, begin\n rw mapping_cone.X_is_zero_iff,\n split; exact is_strictly_ge.is_zero _ 0 _ (by linarith),\nend⟩\n\n@[simps]\ndef double_iso_mapping_cone : double (neg_add_self 1) φ ≅\n mapping_cone ((homological_complex.single _ _ 0).map φ) :=\n{ hom := double.desc (neg_add_self 1) φ _\n ((homological_complex.single_obj_X_self _ _ 0 A).inv ≫\n (mapping_cone.inl _).v _ _ (zero_add (-1)).symm)\n ((homological_complex.single_obj_X_self _ _ 0 B).inv ≫\n (mapping_cone.inr ((homological_complex.single _ _ 0).map φ)).f 0)\n begin\n simp only [assoc],\n erw mapping_cone.inl_d _ (-1) 0 1 (by linarith) (by linarith),\n simp only [homological_complex.single_obj_X_self_inv, eq_to_hom_refl,\n homological_complex.single_map_f_self, homological_complex.single_obj_X_self_hom,\n comp_id, assoc, homological_complex.single_obj_d, zero_comp, sub_zero, id_comp],\n erw id_comp,\n end\n (zero_add 1) (is_zero.eq_of_tgt\n (by simp only [mapping_cone.X_is_zero_iff, homological_complex.single_obj_X,\n add_self_eq_zero, one_ne_zero, if_false, and_self, is_zero_zero]) _ _),\n inv := double.lift (neg_add_self 1) φ _\n ((mapping_cone.fst _).1.v (-1) 0 (neg_add_self 1).symm ≫\n (homological_complex.single_obj_X_self _ _ 0 A).hom)\n ((mapping_cone.snd _ ).v _ _ (zero_add 0).symm ≫\n (homological_complex.single_obj_X_self _ _ 0 B).hom)\n begin\n rw mapping_cone.from_ext_iff _ _ _ (neg_add_self 1).symm,\n split,\n { simp only [assoc],\n erw mapping_cone.inl_fst_assoc,\n simp only [mapping_cone.inl_d_assoc _ (-1) 0 1 (by linarith) (by linarith),\n preadditive.sub_comp, assoc],\n erw [mapping_cone.inl_snd_assoc, mapping_cone.inr_snd_assoc],\n dsimp,\n simp [zero_comp, zero_comp, sub_zero], },\n { simp only [assoc, mapping_cone.inr_d_assoc _ (-1) 0],\n erw [mapping_cone.inr_fst_assoc, mapping_cone.inr_snd_assoc],\n simp only [homological_complex.single_obj_d, zero_comp], },\n end\n (show (-2 : ℤ) +1 = -1, by linarith)\n (is_zero.eq_of_src begin\n rw mapping_cone.X_is_zero_iff,\n split; exact is_strictly_ge.is_zero _ 0 _ (by linarith),\n end _ _),\n hom_inv_id' := begin\n refine from_double_ext (neg_add_self 1) _ _ _ _,\n { simp only [assoc, homological_complex.single_obj_X_self_inv, eq_to_hom_refl,\n homological_complex.single_obj_X_self_hom, id_comp, subtype.val_eq_coe,\n homological_complex.comp_f, double.desc_f, double.desc.f₁, double.lift_f,\n double.lift.f₁, homological_complex.id_f],\n erw mapping_cone.inl_fst_assoc,\n dsimp,\n simp only [id_comp, iso.hom_inv_id], },\n { simp only [assoc, homological_complex.single_obj_X_self_inv, eq_to_hom_refl,\n homological_complex.single_obj_X_self_hom, id_comp, homological_complex.comp_f,\n double.desc_f, double.desc.f₂, double.lift_f, double.lift.f₂,\n homological_complex.id_f],\n erw mapping_cone.inr_snd_assoc,\n dsimp,\n simp only [id_comp, iso.hom_inv_id], },\n end,\n inv_hom_id' := begin\n refine from_double_ext (neg_add_self 1) _ _ _ _,\n { simp only [assoc, id_comp, homological_complex.single_obj_X_self_inv, eq_to_hom_refl,\n homological_complex.single_obj_X_self_hom, subtype.val_eq_coe,\n homological_complex.comp_f, double.lift_f, double.lift.f₁, double.desc_f,\n double.desc.f₁, iso.inv_hom_id_assoc, homological_complex.id_f,\n mapping_cone.from_ext_iff _ _ _ (neg_add_self 1).symm,\n mapping_cone.inl_fst_assoc, mapping_cone.inr_fst_assoc, comp_id],\n split,\n { apply id_comp, },\n { apply is_zero.eq_of_src,\n exact is_strictly_ge.is_zero _ 0 _ (by linarith), }, },\n { simp only [assoc, id_comp, homological_complex.single_obj_X_self_inv, eq_to_hom_refl,\n homological_complex.single_obj_X_self_hom, homological_complex.comp_f, double.lift_f,\n double.lift.f₂, double.desc_f, double.desc.f₂, iso.inv_hom_id_assoc,\n homological_complex.id_f],\n erw id_comp,\n erw mapping_cone.to_ext_iff _ _ _ (zero_add 1).symm,\n simp only [assoc, mapping_cone.inr_fst, mapping_cone.inr_snd, id_comp, comp_id],\n split,\n { apply is_zero.eq_of_tgt,\n exact is_strictly_le.is_zero _ 0 _ (by { dsimp, linarith, }), },\n { refl, }, },\n end, }\n\nend abelian\n\nend cochain_complex\n", "meta": {"author": "joelriou", "repo": "homotopical_algebra", "sha": "697f49d6744b09c5ef463cfd3e35932bdf2c78a3", "save_path": "github-repos/lean/joelriou-homotopical_algebra", "path": "github-repos/lean/joelriou-homotopical_algebra/homotopical_algebra-697f49d6744b09c5ef463cfd3e35932bdf2c78a3/src/for_mathlib/algebra/homology/double.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47268347662043286, "lm_q2_score": 0.035678553825659445, "lm_q1q2_score": 0.016864662863101954}} {"text": "/-\nCopyright (c) 2019 Simon Hudon. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Simon Hudon\n\n! This file was ported from Lean 3 source module tactic.monotonicity.interactive\n! leanprover-community/mathlib commit 69be6fe368f5617a607ebb6b356a7a71419cede3\n! Please do not edit these lines, except to modify the commit id\n! if you have ported upstream changes.\n-/\nimport Mathbin.Control.Traversable.Derive\nimport Mathbin.Control.Traversable.Lemmas\nimport Leanbin.Data.Dlist\nimport Mathbin.Tactic.Monotonicity.Basic\n\nvariable {a b c p : Prop}\n\nnamespace Tactic.Interactive\n\nopen Lean Lean.Parser Interactive\n\nopen Interactive.Types\n\nopen Tactic\n\n-- mathport name: parser.optional\nlocal postfix:1024 \"?\" => optional\n\n-- mathport name: parser.many\nlocal postfix:1024 \"*\" => many\n\nunsafe inductive mono_function (elab : Bool := true)\n | non_assoc : expr elab → List (expr elab) → List (expr elab) → mono_function\n | assoc : expr elab → Option (expr elab) → Option (expr elab) → mono_function\n | assoc_comm : expr elab → expr elab → mono_function\n#align tactic.interactive.mono_function tactic.interactive.mono_function\n\n/- ./././Mathport/Syntax/Translate/Tactic/Builtin.lean:69:18: unsupported non-interactive tactic tactic.mk_dec_eq_instance -/\nunsafe instance : DecidableEq mono_function := by\n run_tac\n mk_dec_eq_instance\n\nunsafe def mono_function.to_tactic_format : mono_function → tactic format\n | mono_function.non_assoc fn xs ys => do\n let fn' ← pp fn\n let xs' ← mapM pp xs\n let ys' ← mapM pp ys\n return f! \"{fn' } {xs' } _ {ys'}\"\n | mono_function.assoc fn xs ys => do\n let fn' ← pp fn\n let xs' ← pp xs\n let ys' ← pp ys\n return f! \"{fn' } {xs' } _ {ys'}\"\n | mono_function.assoc_comm fn xs => do\n let fn' ← pp fn\n let xs' ← pp xs\n return f! \"{fn' } _ {xs'}\"\n#align tactic.interactive.mono_function.to_tactic_format tactic.interactive.mono_function.to_tactic_format\n\nunsafe instance has_to_tactic_format_mono_function : has_to_tactic_format mono_function\n where to_tactic_format := mono_function.to_tactic_format\n#align tactic.interactive.has_to_tactic_format_mono_function tactic.interactive.has_to_tactic_format_mono_function\n\nunsafe structure ac_mono_ctx' (rel : Type) where\n to_rel : Rel\n function : mono_function\n (left right rel_def : expr)\n deriving Traversable\n#align tactic.interactive.ac_mono_ctx' tactic.interactive.ac_mono_ctx'\n\n@[reducible]\nunsafe def ac_mono_ctx :=\n ac_mono_ctx' (Option (expr → expr → expr))\n#align tactic.interactive.ac_mono_ctx tactic.interactive.ac_mono_ctx\n\n@[reducible]\nunsafe def ac_mono_ctx_ne :=\n ac_mono_ctx' (expr → expr → expr)\n#align tactic.interactive.ac_mono_ctx_ne tactic.interactive.ac_mono_ctx_ne\n\nunsafe def ac_mono_ctx.to_tactic_format (ctx : ac_mono_ctx) : tactic format := do\n let fn ← pp ctx.function\n let l ← pp ctx.left\n let r ← pp ctx.right\n let rel ← pp ctx.rel_def\n return\n f! \"\\{ function := {fn }\n , left := {l }\n , right := {r }\n , rel_def := {Rel} }}\"\n#align tactic.interactive.ac_mono_ctx.to_tactic_format tactic.interactive.ac_mono_ctx.to_tactic_format\n\nunsafe instance has_to_tactic_format_mono_ctx : has_to_tactic_format ac_mono_ctx\n where to_tactic_format := ac_mono_ctx.to_tactic_format\n#align tactic.interactive.has_to_tactic_format_mono_ctx tactic.interactive.has_to_tactic_format_mono_ctx\n\nunsafe def as_goal (e : expr) (tac : tactic Unit) : tactic Unit := do\n let gs ← get_goals\n set_goals [e]\n tac\n set_goals gs\n#align tactic.interactive.as_goal tactic.interactive.as_goal\n\nopen List hiding map\n\nopen Functor Dlist\n\nsection Config\n\nparameter (opt : MonoCfg)\n\nparameter (asms : List expr)\n\nunsafe def unify_with_instance (e : expr) : tactic Unit :=\n as_goal e <|\n apply_instance <|>\n apply_opt_param <|>\n apply_auto_param <|>\n tactic.solve_by_elim { lemmas := some asms } <|>\n reflexivity <|> applyc `` id <|> return ()\n#align tactic.interactive.unify_with_instance tactic.interactive.unify_with_instance\n\nprivate unsafe def match_rule_head (p : expr) : List expr → expr → expr → tactic expr\n | vs, e, t =>\n (unify t p >> mapM' unify_with_instance vs.reverse) >> instantiate_mvars e <|> do\n let expr.pi _ _ d b ← return t |\n failed\n let v ← mk_meta_var d\n match_rule_head (v :: vs) (expr.app e v) (b v)\n#align tactic.interactive.match_rule_head tactic.interactive.match_rule_head\n\nunsafe def pi_head : expr → tactic expr\n | expr.pi n _ t b => do\n let v ← mk_meta_var t\n pi_head (b v)\n | e => return e\n#align tactic.interactive.pi_head tactic.interactive.pi_head\n\nunsafe def delete_expr (e : expr) : List expr → tactic (Option (List expr))\n | [] => return none\n | x :: xs => compare opt e x >> return (some xs) <|> map (cons x) <$> delete_expr xs\n#align tactic.interactive.delete_expr tactic.interactive.delete_expr\n\nunsafe def match_ac' : List expr → List expr → tactic (List expr × List expr × List expr)\n | es, x :: xs => do\n let es' ← delete_expr x es\n match es' with\n | some es' => do\n let (c, l, r) ← match_ac' es' xs\n return (x :: c, l, r)\n | none => do\n let (c, l, r) ← match_ac' es xs\n return (c, l, x :: r)\n | es, [] => do\n return ([], es, [])\n#align tactic.interactive.match_ac' tactic.interactive.match_ac'\n\nunsafe def match_ac (l : List expr) (r : List expr) : tactic (List expr × List expr × List expr) :=\n do\n let (s', l', r') ← match_ac' l r\n let s' ← mapM instantiate_mvars s'\n let l' ← mapM instantiate_mvars l'\n let r' ← mapM instantiate_mvars r'\n return (s', l', r')\n#align tactic.interactive.match_ac tactic.interactive.match_ac\n\nunsafe def match_prefix : List expr → List expr → tactic (List expr × List expr × List expr)\n | x :: xs, y :: ys =>\n (do\n compare opt x y\n Prod.map ((· :: ·) x) id <$> match_prefix xs ys) <|>\n return ([], x :: xs, y :: ys)\n | xs, ys => return ([], xs, ys)\n#align tactic.interactive.match_prefix tactic.interactive.match_prefix\n\n/-- `(prefix,left,right,suffix) ← match_assoc unif l r` finds the\nlongest prefix and suffix common to `l` and `r` and\nreturns them along with the differences -/\nunsafe def match_assoc (l : List expr) (r : List expr) :\n tactic (List expr × List expr × List expr × List expr) := do\n let (pre, l₁, r₁) ← match_prefix l r\n let (suf, l₂, r₂) ← match_prefix (reverse l₁) (reverse r₁)\n return (pre, reverse l₂, reverse r₂, reverse suf)\n#align tactic.interactive.match_assoc tactic.interactive.match_assoc\n\nunsafe def check_ac : expr → tactic (Bool × Bool × Option (expr × expr × expr) × expr)\n | expr.app (expr.app f x) y => do\n let t ← infer_type x\n let a ← try_core <| to_expr ``(IsAssociative $(t) $(f)) >>= mk_instance\n let c ← try_core <| to_expr ``(IsCommutative $(t) $(f)) >>= mk_instance\n let i ←\n try_core do\n let v ← mk_meta_var t\n let l_inst_p ← to_expr ``(IsLeftId $(t) $(f) $(v))\n let r_inst_p ← to_expr ``(IsRightId $(t) $(f) $(v))\n let l_v ← mk_meta_var l_inst_p\n let r_v ← mk_meta_var r_inst_p\n let l_id ← mk_mapp `is_left_id.left_id [some t, f, v, some l_v]\n mk_instance l_inst_p >>= unify l_v\n let r_id ← mk_mapp `is_right_id.right_id [none, f, v, some r_v]\n mk_instance r_inst_p >>= unify r_v\n let v' ← instantiate_mvars v\n return (l_id, r_id, v')\n return (a, c, i, f)\n | _ => return (false, false, none, expr.var 1)\n#align tactic.interactive.check_ac tactic.interactive.check_ac\n\nunsafe def parse_assoc_chain' (f : expr) : expr → tactic (Dlist expr)\n | e =>\n (do\n let expr.app (expr.app f' x) y ← return e\n is_def_eq f f'\n (· ++ ·) <$> parse_assoc_chain' x <*> parse_assoc_chain' y) <|>\n return (singleton e)\n#align tactic.interactive.parse_assoc_chain' tactic.interactive.parse_assoc_chain'\n\nunsafe def parse_assoc_chain (f : expr) : expr → tactic (List expr) :=\n map Dlist.toList ∘ parse_assoc_chain' f\n#align tactic.interactive.parse_assoc_chain tactic.interactive.parse_assoc_chain\n\nunsafe def fold_assoc (op : expr) :\n Option (expr × expr × expr) → List expr → Option (expr × List expr)\n | _, x :: xs => some (foldl (expr.app ∘ expr.app op) x xs, [])\n | none, [] => none\n | some (l_id, r_id, x₀), [] => some (x₀, [l_id, r_id])\n#align tactic.interactive.fold_assoc tactic.interactive.fold_assoc\n\nunsafe def fold_assoc1 (op : expr) : List expr → Option expr\n | x :: xs => some <| foldl (expr.app ∘ expr.app op) x xs\n | [] => none\n#align tactic.interactive.fold_assoc1 tactic.interactive.fold_assoc1\n\nunsafe def same_function_aux :\n List expr → List expr → expr → expr → tactic (expr × List expr × List expr)\n | xs₀, xs₁, expr.app f₀ a₀, expr.app f₁ a₁ => same_function_aux (a₀ :: xs₀) (a₁ :: xs₁) f₀ f₁\n | xs₀, xs₁, e₀, e₁ => is_def_eq e₀ e₁ >> return (e₀, xs₀, xs₁)\n#align tactic.interactive.same_function_aux tactic.interactive.same_function_aux\n\nunsafe def same_function : expr → expr → tactic (expr × List expr × List expr) :=\n same_function_aux [] []\n#align tactic.interactive.same_function tactic.interactive.same_function\n\nunsafe def parse_ac_mono_function (l r : expr) : tactic (expr × expr × List expr × mono_function) :=\n do\n let (full_f, ls, rs) ← same_function l r\n let (a, c, i, f) ← check_ac l\n if a then\n if c then do\n let (s, ls, rs) ← Monad.join (match_ac <$> parse_assoc_chain f l <*> parse_assoc_chain f r)\n let (l', l_id) ← fold_assoc f i ls\n let (r', r_id) ← fold_assoc f i rs\n let s' ← fold_assoc1 f s\n return (l', r', l_id ++ r_id, mono_function.assoc_comm f s')\n else do\n let-- a ∧ ¬ c\n (pre, ls, rs, suff)\n ← Monad.join (match_assoc <$> parse_assoc_chain f l <*> parse_assoc_chain f r)\n let (l', l_id) ← fold_assoc f i ls\n let (r', r_id) ← fold_assoc f i rs\n let pre' := fold_assoc1 f pre\n let suff' := fold_assoc1 f suff\n return (l', r', l_id ++ r_id, mono_function.assoc f pre' suff')\n else do\n let-- ¬ a\n (xs₀, x₀, x₁, xs₁)\n ← find_one_difference opt ls rs\n return (x₀, x₁, [], mono_function.non_assoc full_f xs₀ xs₁)\n#align tactic.interactive.parse_ac_mono_function tactic.interactive.parse_ac_mono_function\n\nunsafe def parse_ac_mono_function' (l r : pexpr) := do\n let l' ← to_expr l\n let r' ← to_expr r\n parse_ac_mono_function l' r'\n#align tactic.interactive.parse_ac_mono_function' tactic.interactive.parse_ac_mono_function'\n\n-- failed to format: unknown constant 'term.pseudo.antiquot'\nunsafe\n def\n ac_monotonicity_goal\n : expr → tactic ( expr × expr × List expr × ac_mono_ctx )\n |\n q( $ ( e₀ ) → $ ( e₁ ) )\n =>\n do\n let ( l , r , id_rs , f ) ← parse_ac_mono_function e₀ e₁\n let t₀ ← infer_type e₀\n let t₁ ← infer_type e₁\n let rel_def ← to_expr ` `( fun x₀ x₁ => ( x₀ : $ ( t₀ ) ) → ( x₁ : $ ( t₁ ) ) )\n return\n (\n e₀\n ,\n e₁\n ,\n id_rs\n ,\n {\n function := f\n left := l\n right := r\n to_rel := some <| expr.pi `x BinderInfo.default\n rel_def\n }\n )\n |\n q( $ ( e₀ ) = $ ( e₁ ) )\n =>\n do\n let ( l , r , id_rs , f ) ← parse_ac_mono_function e₀ e₁\n let t₀ ← infer_type e₀\n let t₁ ← infer_type e₁\n let rel_def ← to_expr ` `( fun x₀ x₁ => ( x₀ : $ ( t₀ ) ) = ( x₁ : $ ( t₁ ) ) )\n return\n ( e₀ , e₁ , id_rs , { function := f left := l right := r to_rel := none rel_def } )\n |\n expr.app ( expr.app Rel e₀ ) e₁\n =>\n do\n let ( l , r , id_rs , f ) ← parse_ac_mono_function e₀ e₁\n return\n (\n e₀\n ,\n e₁\n ,\n id_rs\n ,\n {\n function := f\n left := l\n right := r\n to_rel := expr.app ∘ expr.app Rel\n rel_def := Rel\n }\n )\n | _ => fail \"invalid monotonicity goal\"\n#align tactic.interactive.ac_monotonicity_goal tactic.interactive.ac_monotonicity_goal\n\nunsafe def bin_op_left (f : expr) : Option expr → expr → expr\n | none, e => e\n | some e₀, e₁ => f.mk_app [e₀, e₁]\n#align tactic.interactive.bin_op_left tactic.interactive.bin_op_left\n\nunsafe def bin_op (f a b : expr) : expr :=\n f.mk_app [a, b]\n#align tactic.interactive.bin_op tactic.interactive.bin_op\n\nunsafe def bin_op_right (f : expr) : expr → Option expr → expr\n | e, none => e\n | e₀, some e₁ => f.mk_app [e₀, e₁]\n#align tactic.interactive.bin_op_right tactic.interactive.bin_op_right\n\nunsafe def mk_fun_app : mono_function → expr → expr\n | mono_function.non_assoc f x y, z => f.mk_app (x ++ z :: y)\n | mono_function.assoc f x y, z => bin_op_left f x (bin_op_right f z y)\n | mono_function.assoc_comm f x, z => f.mk_app [z, x]\n#align tactic.interactive.mk_fun_app tactic.interactive.mk_fun_app\n\nunsafe inductive mono_law/- `assoc (l₀,r₀) (r₁,l₁)` gives first how to find rules to prove\n x+(y₀+z) R x+(y₁+z);\n if that fails, helps prove (x+y₀)+z R (x+y₁)+z -/\n\n |\n assoc :\n expr × expr → expr × expr → mono_law-- `congr r` gives the rule to prove `x = y → f x = f y`\n\n | congr : expr → mono_law\n | other : expr → mono_law\n#align tactic.interactive.mono_law tactic.interactive.mono_law\n\nunsafe def mono_law.to_tactic_format : mono_law → tactic format\n | mono_law.other e => do\n let e ← pp e\n return f! \"other {e}\"\n | mono_law.congr r => do\n let e ← pp r\n return f! \"congr {e}\"\n | mono_law.assoc (x₀, x₁) (y₀, y₁) => do\n let x₀ ← pp x₀\n let x₁ ← pp x₁\n let y₀ ← pp y₀\n let y₁ ← pp y₁\n return f! \"assoc {x₀ }; {x₁ } | {y₀ }; {y₁}\"\n#align tactic.interactive.mono_law.to_tactic_format tactic.interactive.mono_law.to_tactic_format\n\nunsafe instance has_to_tactic_format_mono_law : has_to_tactic_format mono_law\n where to_tactic_format := mono_law.to_tactic_format\n#align tactic.interactive.has_to_tactic_format_mono_law tactic.interactive.has_to_tactic_format_mono_law\n\nunsafe def mk_rel (ctx : ac_mono_ctx_ne) (f : expr → expr) : expr :=\n ctx.to_rel (f ctx.left) (f ctx.right)\n#align tactic.interactive.mk_rel tactic.interactive.mk_rel\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:207:4: warning: unsupported notation `xs₁ -/\nunsafe def mk_congr_args (fn : expr) (xs₀ xs₁ : List expr) (l r : expr) : tactic expr := do\n let p ← mk_app `eq [fn.mk_app <| xs₀ ++ l :: xs₁, fn.mk_app <| xs₀ ++ r :: xs₁]\n Prod.snd <$>\n solve_aux p do\n iterate_exactly (xs₁ xs₁.length) (applyc `congr_fun)\n applyc `congr_arg\n#align tactic.interactive.mk_congr_args tactic.interactive.mk_congr_args\n\nunsafe def mk_congr_law (ctx : ac_mono_ctx) : tactic expr :=\n match ctx.function with\n | mono_function.assoc f x₀ x₁ =>\n if (x₀ <|> x₁).isSome then mk_congr_args f x₀.toMonad x₁.toMonad ctx.left ctx.right else failed\n | mono_function.assoc_comm f x₀ => mk_congr_args f [x₀] [] ctx.left ctx.right\n | mono_function.non_assoc f x₀ x₁ => mk_congr_args f x₀ x₁ ctx.left ctx.right\n#align tactic.interactive.mk_congr_law tactic.interactive.mk_congr_law\n\nunsafe def mk_pattern (ctx : ac_mono_ctx) : tactic mono_law :=\n match (sequence ctx : Option (ac_mono_ctx' _)) with\n | some ctx =>\n match ctx.function with\n | mono_function.assoc f (some x) (some y) =>\n return <|\n mono_law.assoc\n (mk_rel ctx fun i => bin_op f x (bin_op f i y), mk_rel ctx fun i => bin_op f i y)\n (mk_rel ctx fun i => bin_op f (bin_op f x i) y, mk_rel ctx fun i => bin_op f x i)\n | mono_function.assoc f (some x) none =>\n return <| mono_law.other <| mk_rel ctx fun e => mk_fun_app ctx.function e\n | mono_function.assoc f none (some y) =>\n return <| mono_law.other <| mk_rel ctx fun e => mk_fun_app ctx.function e\n | mono_function.assoc f none none => none\n | _ => return <| mono_law.other <| mk_rel ctx fun e => mk_fun_app ctx.function e\n | none => mono_law.congr <$> mk_congr_law ctx\n#align tactic.interactive.mk_pattern tactic.interactive.mk_pattern\n\nunsafe def match_rule (pat : expr) (r : Name) : tactic expr := do\n let r' ← mk_const r\n let t ← infer_type r'\n let t ←\n expr.dsimp t { failIfUnchanged := false } true []\n [simp_arg_type.expr ``(Monotone), simp_arg_type.expr ``(StrictMono)]\n match_rule_head pat [] r' t\n#align tactic.interactive.match_rule tactic.interactive.match_rule\n\nunsafe def find_lemma (pat : expr) : List Name → tactic (List expr)\n | [] => return []\n | r :: rs => do\n (cons <$> match_rule pat r <|> pure id) <*> find_lemma rs\n#align tactic.interactive.find_lemma tactic.interactive.find_lemma\n\n-- failed to format: unknown constant 'term.pseudo.antiquot'\nunsafe\n def\n match_chaining_rules\n ( ls : List Name ) ( x₀ x₁ : expr ) : tactic ( List expr )\n :=\n do\n let x' ← to_expr ` `( $ ( x₁ ) → $ ( x₀ ) )\n let r₀ ← find_lemma x' ls\n let r₁ ← find_lemma x₁ ls\n return ( expr.app <$> r₀ <*> r₁ )\n#align tactic.interactive.match_chaining_rules tactic.interactive.match_chaining_rules\n\nunsafe def find_rule (ls : List Name) : mono_law → tactic (List expr)\n | mono_law.assoc (x₀, x₁) (y₀, y₁) =>\n match_chaining_rules ls x₀ x₁ <|> match_chaining_rules ls y₀ y₁\n | mono_law.congr r => return [r]\n | mono_law.other p => find_lemma p ls\n#align tactic.interactive.find_rule tactic.interactive.find_rule\n\nuniverse u v\n\ndef applyRel {α : Sort u} (R : α → α → Sort v) {x y : α} (x' y' : α) (h : R x y) (hx : x = x')\n (hy : y = y') : R x' y' := by\n rw [← hx, ← hy]\n apply h\n#align tactic.interactive.apply_rel Tactic.Interactive.applyRel\n\nunsafe def ac_refine (e : expr) : tactic Unit :=\n andthen (refine ``(Eq.mp _ $(e))) ac_refl\n#align tactic.interactive.ac_refine tactic.interactive.ac_refine\n\nunsafe def one_line (e : expr) : tactic format := do\n let lbl ← pp e\n let asm ← infer_type e >>= pp\n return\n f! \"\t{asm}\n \"\n#align tactic.interactive.one_line tactic.interactive.one_line\n\nunsafe def side_conditions (e : expr) : tactic format := do\n let vs := e.list_meta_vars\n let ts ← mapM one_line vs.tail\n let r := e.get_app_fn.const_name\n return\n f! \"{r }:\n {format.join ts}\"\n#align tactic.interactive.side_conditions tactic.interactive.side_conditions\n\nopen Monad\n\n-- failed to format: unknown constant 'term.pseudo.antiquot'\n/--\n tactic-facing function, similar to `interactive.tactic.generalize` with the\n exception that meta variables -/\n private\n unsafe\n def\n monotonicity.generalize'\n ( h : Name ) ( v : expr ) ( x : Name ) : tactic ( expr × expr )\n :=\n do\n let tgt ← target\n let t ← infer_type v\n let\n tgt'\n ←\n (\n do\n let ⟨ tgt' , _ ⟩ ← solve_aux tgt ( tactic.generalize v x >> target )\n to_expr ` `( fun y : $ ( t ) => ∀ x , y = x → $ ( tgt' 0 1 ) )\n )\n <|>\n to_expr ` `( fun y : $ ( t ) => ∀ x , $ ( v ) = x → $ ( tgt ) )\n let t ← head_beta ( tgt' v ) >>= assert h\n swap\n let r ← mk_eq_refl v\n solve1 <| tactic.exact ( t v r )\n Prod.mk <$> tactic.intro x <*> tactic.intro h\n#align tactic.interactive.monotonicity.generalize' tactic.interactive.monotonicity.generalize'\n\nprivate unsafe def hide_meta_vars (tac : List expr → tactic Unit) : tactic Unit :=\n focus1 do\n let tgt ← target >>= instantiate_mvars\n tactic.change tgt\n let ctx ← local_context\n let vs := tgt.list_meta_vars\n let vs' ←\n mapM\n (fun v => do\n let h ← get_unused_name `h\n let x ← get_unused_name `x\n Prod.snd <$> monotonicity.generalize' h v x)\n vs\n andthen (tac ctx) (vs' (try ∘ tactic.subst))\n#align tactic.interactive.hide_meta_vars tactic.interactive.hide_meta_vars\n\nunsafe def hide_meta_vars' (tac : itactic) : itactic :=\n hide_meta_vars fun _ => tac\n#align tactic.interactive.hide_meta_vars' tactic.interactive.hide_meta_vars'\n\nend Config\n\nunsafe def solve_mvar (v : expr) (tac : tactic Unit) : tactic Unit := do\n let gs ← get_goals\n set_goals [v]\n target >>= instantiate_mvars >>= tactic.change\n tac\n done\n set_goals <| gs\n#align tactic.interactive.solve_mvar tactic.interactive.solve_mvar\n\ndef List.minimumOn {α β} [LinearOrder β] (f : α → β) : List α → List α\n | [] => []\n | x :: xs =>\n Prod.snd <|\n xs.foldl\n (fun ⟨k, a⟩ b =>\n let k' := f b\n if k < k' then (k, a) else if k' < k then (k', [b]) else (k, b :: a))\n (f x, [x])\n#align tactic.interactive.list.minimum_on Tactic.Interactive.List.minimumOn\n\nopen Format MonoSelection\n\nunsafe def best_match {β} (xs : List expr) (tac : expr → tactic β) : tactic Unit := do\n let t ← target\n let xs ← xs.mapM fun x => try_core <| Prod.mk x <$> solve_aux t (tac x >> get_goals)\n let xs := xs.filterMap id\n let r := List.minimumOn (List.length ∘ Prod.fst ∘ Prod.snd) xs\n match r with\n | [(_, gs, pr)] => tactic.exact pr >> set_goals gs\n | [] => fail \"no good match found\"\n | _ => do\n let lmms ←\n r fun ⟨l, gs, _⟩ => do\n let ts ← gs infer_type\n let msg ← ts pp\n pure <| foldl compose \"\\n\\n\" <| List.intersperse \"\\n\" <| to_fmt l :: msg\n let msg := foldl compose \"\" lmms\n fail\n f! \"ambiguous match: {msg}\n \n Tip: try asserting a side condition to distinguish between the lemmas\"\n#align tactic.interactive.best_match tactic.interactive.best_match\n\nunsafe def mono_aux (dir : parse side) : tactic Unit := do\n let t ← target >>= instantiate_mvars\n let ns ← get_monotonicity_lemmas t dir\n let asms ← local_context\n let rs ← find_lemma asms t ns\n focus1 <| () <$ best_match rs fun law => tactic.refine <| to_pexpr law\n#align tactic.interactive.mono_aux tactic.interactive.mono_aux\n\n/-- - `mono` applies a monotonicity rule.\n- `mono*` applies monotonicity rules repetitively.\n- `mono with x ≤ y` or `mono with [0 ≤ x,0 ≤ y]` creates an assertion for the listed\n propositions. Those help to select the right monotonicity rule.\n- `mono left` or `mono right` is useful when proving strict orderings:\n for `x + y < w + z` could be broken down into either\n - left: `x ≤ w` and `y < z` or\n - right: `x < w` and `y ≤ z`\n- `mono using [rule1,rule2]` calls `simp [rule1,rule2]` before applying mono.\n- The general syntax is\n `mono '*'? ('with' hyp | 'with' [hyp1,hyp2])? ('using' [hyp1,hyp2])? mono_cfg?`\n\nTo use it, first import `tactic.monotonicity`.\n\nHere is an example of mono:\n\n```lean\nexample (x y z k : ℤ)\n (h : 3 ≤ (4 : ℤ))\n (h' : z ≤ y) :\n (k + 3 + x) - y ≤ (k + 4 + x) - z :=\nbegin\n mono, -- unfold `(-)`, apply add_le_add\n { -- ⊢ k + 3 + x ≤ k + 4 + x\n mono, -- apply add_le_add, refl\n -- ⊢ k + 3 ≤ k + 4\n mono },\n { -- ⊢ -y ≤ -z\n mono /- apply neg_le_neg -/ }\nend\n```\n\nMore succinctly, we can prove the same goal as:\n\n```lean\nexample (x y z k : ℤ)\n (h : 3 ≤ (4 : ℤ))\n (h' : z ≤ y) :\n (k + 3 + x) - y ≤ (k + 4 + x) - z :=\nby mono*\n```\n\n-/\nunsafe def mono (many : parse (tk \"*\")?) (dir : parse side)\n (hyps : parse <| tk \"with\" *> pexpr_list_or_texpr <|> pure [])\n (simp_rules : parse <| tk \"using\" *> simp_arg_list <|> pure []) : tactic Unit := do\n let hyps ← hyps.mapM fun p => to_expr p >>= mk_meta_var\n hyps fun pr => do\n let h ← get_unused_name `h\n note h none pr\n when (¬simp_rules) (simp_core { } failed tt simp_rules [] (loc.ns [none]) >> skip)\n if many then repeat <| mono_aux dir else mono_aux dir\n let gs ← get_goals\n set_goals <| hyps ++ gs\n#align tactic.interactive.mono tactic.interactive.mono\n\nadd_tactic_doc\n { Name := \"mono\"\n category := DocCategory.tactic\n declNames := [`tactic.interactive.mono]\n tags := [\"monotonicity\"] }\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:330:4: warning: unsupported (TODO): `[tacs] -/\n/- ./././Mathport/Syntax/Translate/Expr.lean:207:4: warning: unsupported notation `g -/\n/- ./././Mathport/Syntax/Translate/Expr.lean:330:4: warning: unsupported (TODO): `[tacs] -/\n/- ./././Mathport/Syntax/Translate/Expr.lean:330:4: warning: unsupported (TODO): `[tacs] -/\n/-- transforms a goal of the form `f x ≼ f y` into `x ≤ y` using lemmas\nmarked as `monotonic`.\n\nSpecial care is taken when `f` is the repeated application of an\nassociative operator and if the operator is commutative\n-/\nunsafe def ac_mono_aux (cfg : MonoCfg := { }) : tactic Unit :=\n hide_meta_vars fun asms => do\n try sorry\n let tgt ← target >>= instantiate_mvars\n let (l, r, id_rs, g) ← ac_monotonicity_goal cfg tgt <|> fail \"monotonic context not found\"\n let ns ← get_monotonicity_lemmas tgt both\n let p ← mk_pattern g\n let rules ← find_rule asms ns p <|> fail \"no applicable rules found\"\n when (rules = []) (fail \"no applicable rules found\")\n let err ← format.join <$> mapM side_conditions rules\n focus1 <|\n best_match rules fun rule => do\n let t₀ ← mk_meta_var q(Prop)\n let v₀ ← mk_meta_var t₀\n let t₁ ← mk_meta_var q(Prop)\n let v₁ ← mk_meta_var t₁\n tactic.refine <| ``(applyRel (g $(g.rel_def)) $(l) $(r) $(rule) $(v₀) $(v₁))\n solve_mvar v₀ (try (any_of id_rs rewrite_target) >> (done <|> refl <|> ac_refl <|> sorry))\n solve_mvar v₁ (try (any_of id_rs rewrite_target) >> (done <|> refl <|> ac_refl <|> sorry))\n let n ← num_goals\n iterate_exactly (n - 1)\n (try <| solve1 <| apply_instance <|> tactic.solve_by_elim { lemmas := some asms })\n#align tactic.interactive.ac_mono_aux tactic.interactive.ac_mono_aux\n\nopen Sum Nat\n\n/-- (repeat_until_or_at_most n t u): repeat tactic `t` at most n times or until u succeeds -/\nunsafe def repeat_until_or_at_most : Nat → tactic Unit → tactic Unit → tactic Unit\n | 0, t, _ => fail \"too many applications\"\n | succ n, t, u => u <|> t >> repeat_until_or_at_most n t u\n#align tactic.interactive.repeat_until_or_at_most tactic.interactive.repeat_until_or_at_most\n\nunsafe def repeat_until : tactic Unit → tactic Unit → tactic Unit :=\n repeat_until_or_at_most 100000\n#align tactic.interactive.repeat_until tactic.interactive.repeat_until\n\ninductive RepArity : Type\n | one\n | exactly (n : ℕ)\n | many\n deriving _root_.has_reflect, Inhabited\n#align tactic.interactive.rep_arity Tactic.Interactive.RepArity\n\nunsafe def repeat_or_not : RepArity → tactic Unit → Option (tactic Unit) → tactic Unit\n | rep_arity.one, tac, none => tac\n | rep_arity.many, tac, none => repeat tac\n | rep_arity.exactly n, tac, none => iterate_exactly' n tac\n | rep_arity.one, tac, some until => tac >> until\n | rep_arity.many, tac, some until => repeat_until tac until\n | rep_arity.exactly n, tac, some until => iterate_exactly n tac >> until\n#align tactic.interactive.repeat_or_not tactic.interactive.repeat_or_not\n\nunsafe def assert_or_rule : lean.parser (Sum pexpr pexpr) :=\n tk \":=\" *> inl <$> texpr <|> tk \":\" *> inr <$> texpr\n#align tactic.interactive.assert_or_rule tactic.interactive.assert_or_rule\n\nunsafe def arity : lean.parser RepArity :=\n tk \"*\" *> pure RepArity.many <|> RepArity.exactly <$> (tk \"^\" *> small_nat) <|> pure RepArity.one\n#align tactic.interactive.arity tactic.interactive.arity\n\n/-- `ac_mono` reduces the `f x ⊑ f y`, for some relation `⊑` and a\nmonotonic function `f` to `x ≺ y`.\n\n`ac_mono*` unwraps monotonic functions until it can't.\n\n`ac_mono^k`, for some literal number `k` applies monotonicity `k`\ntimes.\n\n`ac_mono := h`, with `h` a hypothesis, unwraps monotonic functions and\nuses `h` to solve the remaining goal. Can be combined with `*` or `^k`:\n`ac_mono* := h`\n\n`ac_mono : p` asserts `p` and uses it to discharge the goal result\nunwrapping a series of monotonic functions. Can be combined with * or\n^k: `ac_mono* : p`\n\nIn the case where `f` is an associative or commutative operator,\n`ac_mono` will consider any possible permutation of its arguments and\nuse the one the minimizes the difference between the left-hand side\nand the right-hand side.\n\nTo use it, first import `tactic.monotonicity`.\n\n`ac_mono` can be used as follows:\n\n```lean\nexample (x y z k m n : ℕ)\n (h₀ : z ≥ 0)\n (h₁ : x ≤ y) :\n (m + x + n) * z + k ≤ z * (y + n + m) + k :=\nbegin\n ac_mono,\n -- ⊢ (m + x + n) * z ≤ z * (y + n + m)\n ac_mono,\n -- ⊢ m + x + n ≤ y + n + m\n ac_mono,\nend\n```\n\nAs with `mono*`, `ac_mono*` solves the goal in one go and so does\n`ac_mono* := h₁`. The latter syntax becomes especially interesting in the\nfollowing example:\n\n```lean\nexample (x y z k m n : ℕ)\n (h₀ : z ≥ 0)\n (h₁ : m + x + n ≤ y + n + m) :\n (m + x + n) * z + k ≤ z * (y + n + m) + k :=\nby ac_mono* := h₁.\n```\n\nBy giving `ac_mono` the assumption `h₁`, we are asking `ac_refl` to\nstop earlier than it would normally would.\n-/\nunsafe def ac_mono (rep : parse arity) : parse assert_or_rule ? → optParam MonoCfg { } → tactic Unit\n | none, opt => focus1 <| repeat_or_not rep (ac_mono_aux opt) none\n | some (inl h), opt => do\n focus1 <| repeat_or_not rep (ac_mono_aux opt) (some <| done <|> to_expr h >>= ac_refine)\n | some (inr t), opt => do\n let h ← i_to_expr t >>= assert `h\n tactic.swap\n focus1 <| repeat_or_not rep (ac_mono_aux opt) (some <| done <|> ac_refine h)\n#align tactic.interactive.ac_mono tactic.interactive.ac_mono\n\n/-\nTODO(Simon): with `ac_mono := h` and `ac_mono : p` split the remaining\n gaol if the provided rule does not solve it completely.\n-/\nadd_tactic_doc\n { Name := \"ac_mono\"\n category := DocCategory.tactic\n declNames := [`tactic.interactive.ac_mono]\n tags := [\"monotonicity\"] }\n\nattribute [mono] And.imp Or.imp\n\nend Tactic.Interactive\n\n", "meta": {"author": "leanprover-community", "repo": "mathlib3port", "sha": "62505aa236c58c8559783b16d33e30df3daa54f4", "save_path": "github-repos/lean/leanprover-community-mathlib3port", "path": "github-repos/lean/leanprover-community-mathlib3port/mathlib3port-62505aa236c58c8559783b16d33e30df3daa54f4/Mathbin/Tactic/Monotonicity/Interactive.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4571367168274948, "lm_q2_score": 0.036769466867240946, "lm_q1q2_score": 0.016808673363187875}} {"text": "import category_theory.quotient\nimport category_theory.limits.shapes.zero_morphisms\nimport category_theory.preadditive.additive_functor\nimport group_theory.subgroup.basic\n\nnamespace category_theory\n\nopen limits\n\nnamespace quotient\n\nvariables {C D : Type*} [category C] [category D] {r : hom_rel C}\n\nlemma functor_map_surjective (X Y : C) :\n function.surjective (λ (f : X ⟶ Y), (functor r).map f) := surjective_quot_mk _\n\nlemma nat_trans_ext {F G : quotient r ⥤ D} (τ₁ τ₂ : F ⟶ G)\n (h : ∀ (X : C), τ₁.app ((functor r).obj X) = τ₂.app ((functor r).obj X)) : τ₁ = τ₂ :=\nby { ext X, cases X, exact h X, }\n\ndef lift_nat_trans (F G : quotient r ⥤ D) (τ : functor _ ⋙ F ⟶ functor _ ⋙ G) :\n F ⟶ G :=\n{ app := by { rintro ⟨X⟩, exact τ.app X, },\n naturality' := by { rintros ⟨X⟩ ⟨Y⟩ ⟨f⟩, exact τ.naturality f, }, }\n\n@[simp]\nlemma lift_nat_trans_app (F G : quotient r ⥤ D) (τ : functor _ ⋙ F ⟶ functor _ ⋙ G) (X : C) :\n (lift_nat_trans F G τ).app ((functor r).obj X) = τ.app X := rfl\n\n@[simp]\nlemma lift_nat_trans_id (F : quotient r ⥤ D) :\n lift_nat_trans F F (𝟙 _) = 𝟙 _ :=\nnat_trans_ext _ _ (λ X, rfl)\n\n@[simp, reassoc]\nlemma lift_nat_trans_comp (F G H : quotient r ⥤ D) (τ : functor _ ⋙ F ⟶ functor _ ⋙ G)\n (τ' : functor _ ⋙ G ⟶ functor _ ⋙ H) :\n lift_nat_trans F G τ ≫ lift_nat_trans G H τ' = lift_nat_trans F H (τ ≫ τ') :=\nnat_trans_ext _ _ (λ X, by simp)\n\n@[simps]\ndef lift_nat_iso (F G : quotient r ⥤ D) (e : functor _ ⋙ F ≅ functor _ ⋙ G) :\n F ≅ G :=\n{ hom := lift_nat_trans _ _ e.hom,\n inv := lift_nat_trans _ _ e.inv, }\n\nvariable (r)\n\ndef lift_nat_trans' {F G : C ⥤ D} (τ : F ⟶ G)\n (hF : ∀ (X Y : C) (f₁ f₂ : X ⟶ Y) (h : r f₁ f₂), F.map f₁ = F.map f₂)\n (hG : ∀ (X Y : C) (f₁ f₂ : X ⟶ Y) (h : r f₁ f₂), G.map f₁ = G.map f₂) :\n lift r F hF ⟶ lift r G hG :=\nlift_nat_trans _ _\n ((quotient.lift.is_lift r F hF).hom ≫ τ ≫ (quotient.lift.is_lift r G hG).inv)\n\n@[simp]\nlemma lift_nat_trans'_app {F G : C ⥤ D} (τ : F ⟶ G)\n (hF : ∀ (X Y : C) (f₁ f₂ : X ⟶ Y) (h : r f₁ f₂), F.map f₁ = F.map f₂)\n (hG : ∀ (X Y : C) (f₁ f₂ : X ⟶ Y) (h : r f₁ f₂), G.map f₁ = G.map f₂) (X : C) :\n (lift_nat_trans' r τ hF hG).app ((functor r).obj X) = τ.app X :=\nbegin\n dsimp [lift_nat_trans'],\n simp,\nend\n\n@[simp]\nlemma lift_nat_trans'_id (F : C ⥤ D)\n (hF : ∀ (X Y : C) (f₁ f₂ : X ⟶ Y) (h : r f₁ f₂), F.map f₁ = F.map f₂) :\n lift_nat_trans' r (𝟙 F) hF hF = 𝟙 _ :=\nnat_trans_ext _ _ (λ X, by { dsimp, simp, })\n\n@[simp]\nlemma lift_nat_trans'_comp {F G H : C ⥤ D} (τ : F ⟶ G) (τ' : G ⟶ H)\n (hF : ∀ (X Y : C) (f₁ f₂ : X ⟶ Y) (h : r f₁ f₂), F.map f₁ = F.map f₂)\n (hG : ∀ (X Y : C) (f₁ f₂ : X ⟶ Y) (h : r f₁ f₂), G.map f₁ = G.map f₂)\n (hH : ∀ (X Y : C) (f₁ f₂ : X ⟶ Y) (h : r f₁ f₂), H.map f₁ = H.map f₂) :\n lift_nat_trans' r τ hF hG ≫ lift_nat_trans' r τ' hG hH =\n lift_nat_trans' r (τ ≫ τ') hF hH :=\nnat_trans_ext _ _ (λ X, by simp)\n\n@[simps]\ndef lift_nat_iso' {F G : C ⥤ D} (e : F ≅ G)\n (hF : ∀ (X Y : C) (f₁ f₂ : X ⟶ Y) (h : r f₁ f₂), F.map f₁ = F.map f₂)\n (hG : ∀ (X Y : C) (f₁ f₂ : X ⟶ Y) (h : r f₁ f₂), G.map f₁ = G.map f₂) :\n lift r F hF ≅ lift r G hG :=\n{ hom := lift_nat_trans' r e.hom hF hG,\n inv := lift_nat_trans' r e.inv hG hF, }\n\nlemma lift_map_eq (F : C ⥤ D)\n (hF : ∀ (X Y : C) (f₁ f₂ : X ⟶ Y) (h : r f₁ f₂), F.map f₁ = F.map f₂)\n {X Y : C} (f : X ⟶ Y) :\n (lift r F hF).map ((functor r).map f) = F.map f :=\nby rw [functor_map, lift_map]\n\nopen_locale zero_object\n\nlemma is_zero_of_is_zero {X : C} (hX : is_zero X) :\n is_zero ((functor r).obj X) :=\nbegin\n haveI : has_zero_object C := ⟨⟨_, hX⟩⟩,\n refine limits.is_zero.of_iso _ ((functor r).map_iso (is_zero.iso_zero hX)),\n split,\n { rintro ⟨Y⟩,\n haveI := (has_zero_object.unique_from Y),\n refine ⟨⟨⟨(functor r).map default⟩, _⟩⟩,\n intro f,\n obtain ⟨g, rfl⟩ := functor_map_surjective _ _ f,\n rw subsingleton.elim g default, },\n { rintro ⟨Y⟩,\n haveI := (has_zero_object.unique_to Y),\n refine ⟨⟨⟨(functor r).map default⟩, _⟩⟩,\n intro f,\n obtain ⟨g, rfl⟩ := functor_map_surjective _ _ f,\n rw subsingleton.elim g default, },\nend\n\ninstance [has_zero_object C] : has_zero_object (quotient r) :=\n⟨⟨_, is_zero_of_is_zero _ (is_zero_zero C)⟩⟩\n\nsection preadditive\n\nvariables [preadditive C] [congruence r]\n (add : ∀ ⦃X Y : C⦄ ⦃f₁ g₁ f₂ g₂ : X ⟶ Y⦄ (h₁ : r f₁ g₁) (h₂ : r f₂ g₂), (r (f₁ + f₂) (g₁ + g₂)))\n (neg : ∀ ⦃X Y : C⦄ ⦃f g : X ⟶ Y⦄ (h : r f g), r (-f) (-g))\n\nlemma comp_closure_eq_self : comp_closure r = r :=\nbegin\n ext X Y f₁ f₂,\n split,\n { intro h,\n simpa only [← functor_map_eq_iff r] using quot.sound h, },\n { exact comp_closure.of _ _ _, },\nend\n\nvariable {r}\n\ninclude add\n\ndef preadditive.add {X Y : quotient r} (φ φ' : X ⟶ Y) : X ⟶ Y :=\nbegin\n refine quot.lift₂ (λ x y, quot.mk _ (x+y)) _ _ φ φ',\n { intros x y₁ y₂ h,\n rw comp_closure_eq_self at h,\n change (functor r).map (x+y₁) = (functor r).map (x+y₂),\n rw functor_map_eq_iff,\n exact add (refl _) h, },\n { intros x₁ x₂ y h,\n rw comp_closure_eq_self at h,\n change (functor r).map (x₁+y) = (functor r).map (x₂+y),\n rw functor_map_eq_iff,\n exact add h (refl _), },\nend\n\nomit add\n\ninclude neg\n\ndef preadditive.neg {X Y : quotient r} (φ : X ⟶ Y) : X ⟶ Y :=\nbegin\n refine quot.lift (λ x, quot.mk _ (-x)) _ φ,\n intros x y h,\n rw comp_closure_eq_self at h,\n change (functor r).map (-x) = (functor r).map (-y),\n rw functor_map_eq_iff,\n exact neg h,\nend\n\ninclude add\nvariable (r)\n\ndef preadditive.hom_group (X Y : quotient r) : add_comm_group (X ⟶ Y) :=\n{ add := preadditive.add add,\n add_assoc := by { rintros ⟨x⟩ ⟨y⟩ ⟨z⟩, exact (functor r).congr_map (add_assoc x y z), },\n zero := (functor r).map 0,\n zero_add := by { rintro ⟨x⟩, exact (functor r).congr_map (zero_add x), },\n add_zero := by { rintro ⟨x⟩, exact (functor r).congr_map (add_zero x), },\n neg := preadditive.neg neg,\n add_left_neg := by { rintro ⟨x⟩, exact (functor r).congr_map (add_left_neg x), },\n add_comm := by { rintros ⟨x⟩ ⟨y⟩, exact (functor r).congr_map (add_comm x y), }, }\n\n@[protected]\ndef preadditive :\n preadditive (quotient r) :=\n{ hom_group := preadditive.hom_group r add neg,\n add_comp' := λ X Y Z, begin\n rintros ⟨x₁⟩ ⟨x₂⟩ ⟨y⟩,\n exact (functor r).congr_map (preadditive.add_comp _ _ _ x₁ x₂ y),\n end,\n comp_add' := λ X Y Z, begin\n rintros ⟨x⟩ ⟨y₁⟩ ⟨y₂⟩,\n exact (functor r).congr_map (preadditive.comp_add _ _ _ x y₁ y₂),\n end, }\n\nlemma functor_additive :\n @functor.additive C (quotient r) _ _ _ (quotient.preadditive r add neg) (functor r) := { }\n\nomit add neg\n\nlemma lift_additive {D : Type*} [category D] [preadditive D] [preadditive (quotient r)]\n [(functor r).additive] (F : C ⥤ D) [F.additive]\n (H : ∀ (x y : C) (f₁ f₂ : x ⟶ y), r f₁ f₂ → F.map f₁ = F.map f₂) :\n (lift r F H).additive :=\n⟨begin\n rintro ⟨X⟩ ⟨Y⟩ ⟨f₁ : X ⟶ Y⟩ ⟨f₂ : X ⟶ Y⟩,\n change (lift r F H).map ((functor r).map f₁ + (functor r).map f₂) = F.map f₁ + F.map f₂,\n simpa only [← functor.map_add],\nend⟩\n\nend preadditive\n\nend quotient\n\nend category_theory\n", "meta": {"author": "joelriou", "repo": "homotopical_algebra", "sha": "697f49d6744b09c5ef463cfd3e35932bdf2c78a3", "save_path": "github-repos/lean/joelriou-homotopical_algebra", "path": "github-repos/lean/joelriou-homotopical_algebra/homotopical_algebra-697f49d6744b09c5ef463cfd3e35932bdf2c78a3/src/for_mathlib/category_theory/quotient_misc.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.033589505045466074, "lm_q1q2_score": 0.016794752522733037}} {"text": "/-\nCopyright (c) 2019 Paul-Nicolas Madelaine. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Paul-Nicolas Madelaine, Robert Y. Lewis\n\nNormalizing casts inside expressions.\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.default\nimport Mathlib.tactic.converter.interactive\nimport Mathlib.tactic.hint\nimport Mathlib.PostPort\n\nuniverses l u_1 u_2 \n\nnamespace Mathlib\n\n/-!\n# A tactic for normalizing casts inside expressions\n\nThis tactic normalizes casts inside expressions.\nIt can be thought of as a call to the simplifier with a specific set of lemmas to\nmove casts upwards in the expression.\nIt has special handling of numerals and a simple heuristic to help moving\ncasts \"past\" binary operators.\nContrary to simp, it should be safe to use as a non-terminating tactic.\n\nThe algorithm implemented here is described in the paper\n.\n\n## Important definitions\n* `tactic.interactive.norm_cast`\n* `tactic.interactive.push_cast`\n* `tactic.interactive.exact_mod_cast`\n* `tactic.interactive.apply_mod_cast`\n* `tactic.interactive.rw_mod_cast`\n* `tactic.interactive.assumption_mod_cast`\n-/\n\nnamespace tactic\n\n\n/--\nRuns `mk_instance` with a time limit.\n\nThis is a work around to the fact that in some cases\nmk_instance times out instead of failing,\nfor example: `has_lift_t ℤ ℕ`\n\n`mk_instance_fast` is used when we assume the type class search\nshould end instantly.\n-/\nend tactic\n\n\nnamespace norm_cast\n\n\n/--\nOutput a trace message if `trace.norm_cast` is enabled.\n-/\n/--\n`label` is a type used to classify `norm_cast` lemmas.\n* elim lemma: LHS has 0 head coes and ≥ 1 internal coe\n* move lemma: LHS has 1 head coe and 0 internal coes, RHS has 0 head coes and ≥ 1 internal coes\n* squash lemma: LHS has ≥ 1 head coes and 0 internal coes, RHS has fewer head coes\n-/\ninductive label where\n| elim : label\n| move : label\n| squash : label\n\nnamespace label\n\n\n/-- Convert `label` into `string`. -/\nprotected def to_string : label → string := sorry\n\nprotected instance has_to_string : has_to_string label := has_to_string.mk label.to_string\n\nprotected instance has_repr : has_repr label := has_repr.mk label.to_string\n\n/-- Convert `string` into `label`. -/\ndef of_string : string → Option label := sorry\n\nend label\n\n\n/-- Count how many coercions are at the top of the expression. -/\n/-- Count how many coercions are inside the expression, including the top ones. -/\n/-- Count how many coercions are inside the expression, excluding the top ones. -/\n/--\nClassifies a declaration of type `ty` as a `norm_cast` rule.\n-/\n/-- The cache for `norm_cast` attribute stores three `simp_lemma` objects. -/\n/-- Empty `norm_cast_cache`. -/\n/-- `add_elim cache e` adds `e` as an `elim` lemma to `cache`. -/\n/-- `add_move cache e` adds `e` as a `move` lemma to `cache`. -/\n/-- `add_squash cache e` adds `e` as an `squash` lemma to `cache`. -/\n/--\nThe type of the `norm_cast` attribute.\nThe optional label is used to overwrite the classifier.\n-/\n/--\nEfficient getter for the `@[norm_cast]` attribute parameter that does not call `eval_expr`.\n\nSee Note [user attribute parameters].\n-/\n/--\n`add_lemma cache decl` infers the proper `norm_cast` attribute for `decl` and adds it to `cache`.\n-/\n-- special lemmas to handle the ≥, > and ≠ operators\n\n/--\n`mk_cache names` creates a `norm_cast_cache`. It infers the proper `norm_cast` attributes\nfor names in `names`, and collects the lemmas attributed with specific `norm_cast` attributes.\n-/\n-- names has the declarations in reverse order\n\n--some special lemmas to handle binary relations\n\n/--\nThe `norm_cast` attribute.\n-/\n/-- Classify a declaration as a `norm_cast` rule. -/\n/--\nGets the `norm_cast` classification label for a declaration. Applies the\noverride specified on the attribute, if necessary.\n-/\nend norm_cast\n\n\nnamespace tactic.interactive\n\n\n/--\n`push_cast` rewrites the expression to move casts toward the leaf nodes.\nFor example, `↑(a + b)` will be written to `↑a + ↑b`.\nEquivalent to `simp only with push_cast`.\nCan also be used at hypotheses.\n\n`push_cast` can also be used at hypotheses and with extra simp rules.\n\n```lean\nexample (a b : ℕ) (h1 : ((a + b : ℕ) : ℤ) = 10) (h2 : ((a + b + 0 : ℕ) : ℤ) = 10) :\n ((a + b : ℕ) : ℤ) = 10 :=\nbegin\n push_cast,\n push_cast at h1,\n push_cast [int.add_zero] at h2,\nend\n```\n-/\nend tactic.interactive\n\n\nnamespace norm_cast\n\n\n/-- Prove `a = b` using the given simp set. -/\n/-- Prove `a = b` by simplifying using move and squash lemmas. -/\n/--\nThis is the main heuristic used alongside the elim and move lemmas.\nThe goal is to help casts move past operators by adding intermediate casts.\nAn expression of the shape: op (↑(x : α) : γ) (↑(y : β) : γ)\nis rewritten to: op (↑(↑(x : α) : β) : γ) (↑(y : β) : γ)\nwhen (↑(↑(x : α) : β) : γ) = (↑(x : α) : γ) can be proven with a squash lemma\n-/\n/--\nDischarging function used during simplification in the \"squash\" step.\n\nTODO: norm_cast takes a list of expressions to use as lemmas for the discharger\nTODO: a tactic to print the results the discharger fails to proove\n-/\n/--\nCore rewriting function used in the \"squash\" step, which moves casts upwards\nand eliminates them.\n\nIt tries to rewrite an expression using the elim and move lemmas.\nOn failure, it calls the splitting procedure heuristic.\n-/\n/-!\nThe following auxiliary functions are used to handle numerals.\n-/\n\n/--\nIf possible, rewrite `(n : α)` to `((n : ℕ) : α)` where `n` is a numeral and `α ≠ ℕ`.\nReturns a pair of the new expression and proof that they are equal.\n-/\n/--\nIf possible, rewrite `((n : ℕ) : α)` to `(n : α)` where `n` is a numeral.\nReturns a pair of the new expression and proof that they are equal.\n-/\n/-- A local variant on `simplify_top_down`. -/\n/--\nThe core simplification routine of `norm_cast`.\n-/\n/--\nA small variant of `push_cast` suited for non-interactive use.\n\n`derive_push_cast extra_lems e` returns an expression `e'` and a proof that `e = e'`.\n-/\nend norm_cast\n\n\nnamespace tactic\n\n\n/-- `aux_mod_cast e` runs `norm_cast` on `e` and returns the result. If `include_goal` is true, it\nalso normalizes the goal. -/\n/-- `exact_mod_cast e` runs `norm_cast` on the goal and `e`, and tries to use `e` to close the goal. -/\n/-- `apply_mod_cast e` runs `norm_cast` on the goal and `e`, and tries to apply `e`. -/\n/-- `assumption_mod_cast` runs `norm_cast` on the goal. For each local hypothesis `h`, it also\nnormalizes `h` and tries to use that to close the goal. -/\nend tactic\n\n\nnamespace tactic.interactive\n\n\n/--\nNormalize casts at the given locations by moving them \"upwards\".\nAs opposed to simp, norm_cast can be used without necessarily closing the goal.\n-/\n/--\nRewrite with the given rules and normalize casts between steps.\n-/\n/--\nNormalize the goal and the given expression, then close the goal with exact.\n-/\n/--\nNormalize the goal and the given expression, then apply the expression to the goal.\n-/\n/--\nNormalize the goal and every expression in the local context, then close the goal with assumption.\n-/\nend tactic.interactive\n\n\nnamespace conv.interactive\n\n\n/-- the converter version of `norm_cast' -/\nend conv.interactive\n\n\n-- TODO: move this elsewhere?\n\ntheorem ite_cast {α : Sort u_1} {β : Sort u_2} [has_lift_t α β] {c : Prop} [Decidable c] {a : α}\n {b : α} : ↑(ite c a b) = ite c ↑a ↑b :=\n sorry\n\n/--\nThe `norm_cast` family of tactics is used to normalize casts inside expressions.\nIt is basically a simp tactic with a specific set of lemmas to move casts\nupwards in the expression.\nTherefore it can be used more safely as a non-terminating tactic.\nIt also has special handling of numerals.\n\nFor instance, given an assumption\n```lean\na b : ℤ\nh : ↑a + ↑b < (10 : ℚ)\n```\n\nwriting `norm_cast at h` will turn `h` into\n```lean\nh : a + b < 10\n```\n\nYou can also use `exact_mod_cast`, `apply_mod_cast`, `rw_mod_cast`\nor `assumption_mod_cast`.\nWriting `exact_mod_cast h` and `apply_mod_cast h` will normalize the goal and\n`h` before using `exact h` or `apply h`.\nWriting `assumption_mod_cast` will normalize the goal and for every\nexpression `h` in the context it will try to normalize `h` and use\n`exact h`.\n`rw_mod_cast` acts like the `rw` tactic but it applies `norm_cast` between steps.\n\n`push_cast` rewrites the expression to move casts toward the leaf nodes.\nThis uses `norm_cast` lemmas in the forward direction.\nFor example, `↑(a + b)` will be written to `↑a + ↑b`.\nIt is equivalent to `simp only with push_cast`.\nIt can also be used at hypotheses with `push_cast at h`\nand with extra simp lemmas with `push_cast [int.add_zero]`.\n\n```lean\nexample (a b : ℕ) (h1 : ((a + b : ℕ) : ℤ) = 10) (h2 : ((a + b + 0 : ℕ) : ℤ) = 10) :\n ((a + b : ℕ) : ℤ) = 10 :=\nbegin\n push_cast,\n push_cast at h1,\n push_cast [int.add_zero] at h2,\nend\n```\n\nThe implementation and behavior of the `norm_cast` family is described in detail at\n.\n-/\n/--\nThe `norm_cast` attribute should be given to lemmas that describe the\nend Mathlib", "meta": {"author": "AurelienSaue", "repo": "Mathlib4_auto", "sha": "590df64109b08190abe22358fabc3eae000943f2", "save_path": "github-repos/lean/AurelienSaue-Mathlib4_auto", "path": "github-repos/lean/AurelienSaue-Mathlib4_auto/Mathlib4_auto-590df64109b08190abe22358fabc3eae000943f2/Mathlib/tactic/norm_cast_auto.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3140505578320071, "lm_q2_score": 0.05340332697504391, "lm_q1q2_score": 0.01677134462659761}} {"text": "open tactic\n\nnamespace conj\n\nvariables a b : Prop\n\n-- example : a → b → a ∧ b := by _\n\n-- example : a → b → a ∧ b := by do\n-- eh1 ← intro `h1,\n-- eh2 ← intro `h2,\n-- target >>= trace\n\n-- example : a → b → a ∧ b := by do\n-- eh1 ← intro `h1,\n-- eh2 ← intro `h2,\n-- local_context >>= trace\n\n-- example : a → b → a ∧ b := by do\n-- intro `h1,\n-- intro `h2,\n-- ea ← get_local `a,\n-- eb ← get_local `b,\n-- trace (to_string ea ++ \", \" ++ to_string eb),\n-- skip\n\nexample : a → b → a ∧ b := by do\n eh1 ← intro `h1,\n eh2 ← intro `h2,\n mk_const ``and.intro >>= apply,\n exact eh1,\n exact eh2\n\nexample : a → b → a ∧ b := by do\n eh1 ← intro `h1,\n eh2 ← intro `h2,\n applyc ``and.intro,\n exact eh1,\n exact eh2\n\nexample : a → b → a ∧ b :=\nby do eh1 ← intro `h1,\n eh2 ← intro `h2,\n e ← to_expr ```(and.intro h1 h2),\n exact e\n\nmeta def my_tactic : tactic unit :=\ndo eh1 ← intro `h1,\n eh2 ← intro `h2,\n e ← to_expr ``(and.intro %%eh1 %%eh2),\n exact e\n\nexample : a → b → a ∧ b :=\nby my_tactic\n\nexample (a b : Prop) (h : a ∧ b) : b ∧ a := by do\n split,\n to_expr ```(and.right h) >>= exact,\n to_expr ```(and.left h) >>= exact\n\nnamespace foo\n\ntheorem bar : true := trivial\n\nmeta def my_tac : tactic unit :=\nmk_const ``bar >>= exact\n\nexample : true := by my_tac\n\nend foo\n\nexample (a : Prop) : a → a :=\nby do n ← mk_fresh_name,\n intro n,\n hyp ← get_local n,\n exact hyp\n\nexample (a b : Prop) (h : a ∧ b) : b ∧ a :=\nby do split,\n eh ← get_local `h,\n mk_mapp ``and.right [none, none, some eh] >>= exact,\n mk_mapp ``and.left [none, none, some eh] >>= exact\n\nexample (a b : Prop) (h : a ∧ b) : b ∧ a :=\nby do split,\n ea ← get_local `a,\n eb ← get_local `b,\n eh ← get_local `h,\n mk_app ``and.right [ea, eb, eh] >>= exact,\n mk_app ``and.left [ea, eb, eh] >>= exact\n\nexample (a b : Prop) (h : a ∧ b) : b ∧ a :=\nby do split,\n eh ← get_local `h,\n mk_app ``and.right [eh] >>= exact,\n mk_app ``and.left [eh] >>= exact\n\nexample (a b : Prop) (h : a ∧ b) : b ∧ a :=\nby do split,\n eh ← get_local `h,\n mk_const ``and.right >>= apply,\n exact eh,\n mk_const ``and.left >>= apply,\n exact eh\n\n\nexample (a b : Prop) (h : a ∧ b) : b ∧ a := by do\n split,\n to_expr ```(and.right h) >>= exact,\n to_expr ```(and.left h) >>= exact\n\nexample (a b : Prop) (h : a ∧ b) : b ∧ a := by do\n split,\n eh ← get_local `h,\n to_expr ``(and.right %%eh) >>= exact,\n to_expr ``(and.left %%eh) >>= exact\n\nend conj\n\nnamespace hidden\n\nmeta def find_same_type : expr → list expr → tactic expr\n| e [] := failed\n| e (h :: hs) :=\n do t ← infer_type h,\n (unify e t >> return h) <|> find_same_type e hs\n\nmeta def assumption : tactic unit :=\ndo ctx ← local_context,\n t ← target,\n h ← find_same_type t ctx,\n exact h\n<|> fail \"assumption tactic failed\"\n\nmeta def first {α : Type} : list (tactic α) → tactic α\n| [] := fail \"first tactic failed, no more alternatives\"\n| (t::ts) := t <|> first ts\n\nend hidden\n\nmeta def destruct_conjunctions : tactic unit :=\nrepeat (do\n l ← local_context,\n first $ l.map (λ h, do\n ht ← infer_type h >>= whnf,\n match ht with\n | `(and %%a %%b) := do\n n ← get_unused_name `h none,\n mk_mapp ``and.left [none, none, some h] >>= assertv n a,\n n ← get_unused_name `h none,\n mk_mapp ``and.right [none, none, some h] >>= assertv n b,\n clear h\n | _ := failed\n end))\n\nnamespace hidden\n\nopen nat\n\nmeta def repeat_at_most : nat → tactic unit → tactic unit\n| 0 t := skip\n| (succ n) t := (do t, repeat_at_most n t) <|> skip\n\nmeta def repeat : tactic unit → tactic unit :=\nrepeat_at_most 100000\n\nend hidden\n\nset_option pp.beta false\n\nsection\n variables {α : Type} (a b : α)\n\n example : (λ x : α, a) b = a :=\n by do goal ← target,\n match expr.is_eq goal with\n | (some (e₁, e₂)) := do trace e₁,\n whnf e₁ >>= trace,\n reflexivity\n | none := failed\n end\n\n example : (λ x : α, a) b = a :=\n by do goal ← target,\n match expr.is_eq goal with\n | (some (e₁, e₂)) := do trace e₁,\n whnf e₁ transparency.none >>= trace,\n reflexivity\n | none := failed\n end\n\n attribute [reducible]\n definition foo (a b : α) : α := a\n\n example : foo a b = a :=\n by do goal ← target,\n match expr.is_eq goal with\n | (some (e₁, e₂)) := do trace e₁,\n whnf e₁ transparency.none >>= trace,\n reflexivity\n | none := failed\n end\n\n example : foo a b = a :=\n by do goal ← target,\n match expr.is_eq goal with\n | (some (e₁, e₂)) := do trace e₁,\n whnf e₁ transparency.reducible >>= trace,\n reflexivity\n | none := failed\n end\nend", "meta": {"author": "michens", "repo": "learn-lean", "sha": "f38fc342780ddff5a164a18e5482163dea506ccd", "save_path": "github-repos/lean/michens-learn-lean", "path": "github-repos/lean/michens-learn-lean/learn-lean-f38fc342780ddff5a164a18e5482163dea506ccd/pil/writing_tactics.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.39233683016710835, "lm_q2_score": 0.04272219419471942, "lm_q1q2_score": 0.016761490248139856}} {"text": "namespace Sexp\n\ninductive Sexp\n| atom (s : String)\n| slist (ss : List Sexp)\n\nnamespace Sexp\n\ndef atomToString (s : String) : String :=\n if s.isEmpty || s.any (\"\\\"() \".contains) then\n \"\\\"\" ++ String.replace s \"\\\"\" \"\\\\\\\"\" ++ \"\\\"\"\n else\n s\n\ntheorem atomToString_nonempty (s : String)\n : (atomToString s).isEmpty = false\n := by\n simp [atomToString]\n split\n case inl h =>\n generalize String.replace s _ _ = s\n simp [HAppend.hAppend, Append.append, String.append]\n simp [String.isEmpty, String.endPos, String.utf8ByteSize, String.utf8ByteSize.go]\n generalize String.utf8ByteSize.go _ = rest\n simp [BEq.beq]\n apply decide_eq_false\n intro h\n cases h\n case inr h =>\n apply Decidable.byCases id\n intro h'\n have := eq_true_of_ne_false h'\n simp [this] at h\n\nmutual\ndef toString : Sexp → String\n| atom s => atomToString s\n| slist ss => \"(\" ++ listToString ss ++ \")\"\n\ndef listToString : List Sexp → String\n| [] => \"\"\n| [s] => toString s\n| s :: ss => toString s ++ \" \" ++ listToString ss\nend\n\ninstance : ToString Sexp where\n toString := toString\n\n#eval (slist [\n (atom \"hi\"),\n (atom \"bye\"),\n (atom \"no \\\"really\"),\n (slist [(atom \"what\"), (atom \"oh\")])\n])", "meta": {"author": "JamesGallicchio", "repo": "lean-sexp", "sha": "c0e1ce7bdac4202382b2d5adc5ab12bd05179f62", "save_path": "github-repos/lean/JamesGallicchio-lean-sexp", "path": "github-repos/lean/JamesGallicchio-lean-sexp/lean-sexp-c0e1ce7bdac4202382b2d5adc5ab12bd05179f62/Sexp/Basic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3276682876897044, "lm_q2_score": 0.05108274002686294, "lm_q1q2_score": 0.016738193955100504}} {"text": "/-\n# Macros\n\n## What is a macro\nMacros in Lean are `Syntax → MacroM Syntax` functions. `MacroM` is the macro\nmonad which allows macros to have some static guarantees we will discuss in the\nnext section, you can mostly ignore it for now.\n\nMacros are registered as handlers for a specific syntax declaration using the\n`macro` attribute. The compiler will take care of applying these function\nto the syntax for us before performing actual analysis of the input. This\nmeans that the only thing we have to do is declare our syntax with a specific\nname and bind a function of type `Lean.Macro` to it. Let's try to reproduce\nthe `LXOR` notation from the `Syntax` chapter:\n-/\n\nimport Lean\n\nopen Lean\n\nsyntax:10 (name := lxor) term:10 \" LXOR \" term:11 : term\n\n@[macro lxor] def lxorImpl : Macro\n | `($l:term LXOR $r:term) => `(!$l && $r) -- we can use the quotation mechanism to create `Syntax` in macros\n | _ => Macro.throwUnsupported\n\n#eval true LXOR true -- false\n#eval true LXOR false -- false\n#eval false LXOR true -- true\n#eval false LXOR false -- false\n\n/-\nThat was quite easy! The `Macro.throwUnsupported` function can be used by a macro\nto indicate that \"it doesn't feel responsible for this syntax\". In this case\nit's merely used to fill a wildcard pattern that should never be reached anyways.\n\nHowever we can in fact register multiple macros for the same syntax this way\nif we desire, they will be tried one after another (the later registered ones have \nhigher priority) -- is \"higher\" correct?\nuntil one throws either a real error using `Macro.throwError` or succeeds, that\nis it does not `Macro.throwUnsupported`. Let's see this in action:\n-/\n\n@[macro lxor] def lxorImpl2 : Macro\n -- special case that changes behaviour of the case where the left and\n -- right hand side are these specific identifiers\n | `(true LXOR true) => `(true)\n | _ => Macro.throwUnsupported\n\n#eval true LXOR true -- true, handled by new macro\n#eval true LXOR false -- false, still handled by the old\n\n/-\nThis capability is obviously *very* powerful! It should not be used\nlightly and without careful thinking since it can introduce weird\nbehaviour while writing code later on. The following example illustrates\nthis weird behaviour:\n-/\n\n#eval true LXOR true -- true, handled by new macro\n\ndef foo := true\n#eval foo LXOR foo -- false, handled by old macro, after all the identifiers have a different name\n\n/-\nWithout knowing exactly how this macro is implemented this behaviour\nwill be very confusing to whoever might be debugging an issue based on this.\nThe rule of thumb for when to use a macro vs. other mechanisms like\nelaboration is that as soon as you are building real logic like in the 2nd\nmacro above, it should most likely not be a macro but an elaborator\n(explained in the elaboration chapter). This means ideally we want to\nuse macros for simple syntax to syntax translations, that a human could\neasily write out themselves as well but is too lazy to.\n\n## Simplifying macro declaration\nNow that we know the basics of what a macro is and how to register it\nwe can take a look at slightly more automated ways to do this (in fact\nall of the ways about to be presented are implemented as macros themselves).\n\nFirst things first there is `macro_rules` which basically desugars to\nfunctions like the ones we wrote above, for example:\n-/\n\nsyntax:10 term:10 \" RXOR \" term:11 : term\n\nmacro_rules\n | `($l:term RXOR $r:term) => `($l && !$r)\n\n/-\nAs you can see, it figures out lot's of things on its own for us:\n- the name of the syntax declaration\n- the `macro` attribute registration\n- the `throwUnsupported` wildcard\n\napart from this it just works like a function that is using pattern\nmatching syntax, we can in theory encode arbitrarily complex macro\nfunctions on the right hand side.\n\nIf this is still not short enough for you, there is a next step using the\n`macro` macro:\n-/\n\nmacro l:term:10 \" ⊕ \" r:term:11 : term => `((!$l && $r) || ($l && !$r))\n\n#eval true ⊕ true -- false\n#eval true ⊕ false -- true\n#eval false ⊕ true -- true\n#eval false ⊕ false -- false\n\n/-\nAs you can see, `macro` is quite close to `notation` already:\n- it performed syntax declaration for us\n- it automatically wrote a `macro_rules` style function to match on it\n\nThe are of course differences as well:\n- `notation` is limited to the `term` syntax category\n- `notation` cannot have arbitrary macro code on the right hand side\n\n## `Syntax` Quotations\n### The basics\nSo far we've handwaved the `` `(foo $bar) `` syntax to both create and\nmatch on `Syntax` objects but it's time for a full explanation since\nit will be essential to all non trivial things that are syntax related.\n\nFirst things first we call the `` `() `` syntax a `Syntax` quotation.\nWhen we plug variables into a syntax quotation like this: `` `($x) ``\nwe call the `$x` part an anti-quotation. When we insert `x` like this\nit is required that `x` is of type `TSyntax x` where `x` is some `Name`\nof a syntax category. The Lean compiler is actually smart enough to figure\nthe syntax categories that are allowed in this place out. Hence you might\nsometimes see errors of the form:\n```\napplication type mismatch\n x.raw\nargument\n x\nhas type\n TSyntax `a : Type\nbut is expected to have type\n TSyntax `b : Type\n```\nIf you are sure that your thing from the `a` syntax category can be\nused as a `b` here you can declare a coercion of the form:\n-/\n\ninstance : Coe (TSyntax `a) (TSyntax `b) where\n coe s := ⟨s.raw⟩\n\n/-!\nWhich will allow Lean to perform the type cast automatically. If you\nnotice that your `a` can not be used in place of the `b` here congrats,\nyou just discovered a bug in your `Syntax` function. Similar to the Lean\ncompiler you could can also declare functions that are specific to certain\n`TSynax` variants. For example as we have seen in the syntax chapter\nthere exists the function:\n-/\n#check TSyntax.getNat -- TSyntax.getNat : TSyntax numLitKind → Nat\n/-!\nWhich is guaranteed to not panic because we know that the `Syntax` that\nthe function is receiving is a numeric literal and can thus naturally\nbe converted to a `Nat`.\n\nIf we use the antiquotation syntax in pattern matching it will, as discussed\nin the syntax chapter, give us a a variable `x` of type `` TSyntax y `` where\n`y` is the `Name` of the syntax category that fits in the spot where we pattern matched.\nIf we wish to insert a literal `$x` into the `Syntax` for some reason,\nfor example macro creating macros, we can escape the anti quotation using: `` `($$x) ``.\n\nIf we want to specify the syntax kind we wish `x` to be interpreted as\nwe can make this explicit using: `` `($x:term) `` where `term` can be\nreplaced with any other valid syntax category (e.g. `command`) or parser\n(e.g. `ident`). \n\nSo far this is only a more formal explanation of the intuitive things\nwe've already seen in the syntax chapter and up to now in this chapter,\nnext we'll discuss some more advanced anti-quotations.\n\n### Advanced anti-quotations\nFor convenince we can also use anti-quotations in a way similar to\nformat strings: `` `($(mkIdent `c)) `` is the same as: `` let x := mkIdent `c; `($x) ``.\n\nFurthermore there are sometimes situations in which we are not working\nwith basic `Syntax` but `Syntax` wrapped in more complex datastructures,\nmost notably `Array (TSyntax c)` or `TSepArray c s`. Where `TSepArray c s`, is a\n`Syntax` specific type, it is what we get if we pattern match on some\n`Syntax` that users a separator `s` to separate things from the category `c`.\nFor example if we match using: `$xs,*`, `xs` will have type `TSepArray c \",\"`,.\nWith the special case of matching on no specific separator (i.e. whitespace):\n`$xs*` in which we will receive an `Array (TSyntax c)`.\n\nIf we are dealing with `xs : Array (TSyntax c)` and want to insert it into\na quotation we have two main ways to achieve this:\n1. Insert it using a separator, most commonly `,`: `` `($xs,*) ``.\n This is also the way to insert a `TSepArray c \",\"\"`\n2. Insert it point blank without a separator (TODO): `` `() ``\n\nFor example:\n-/\n\n-- syntactically cut away the first element of a tuple if possible\nsyntax \"cut_tuple \" \"(\" term \", \" term,+ \")\" : term \n\nmacro_rules\n -- cutting away one element of a pair isn't possible, it would not result in a tuple\n | `(cut_tuple ($x, $y)) => `(($x, $y)) \n | `(cut_tuple ($x, $y, $xs,*)) => `(($y, $xs,*))\n\n#check cut_tuple (1, 2) -- (1, 2) : Nat × Nat\n#check cut_tuple (1, 2, 3) -- (2, 3) : Nat × Nat\n\n/-!\nThe last thing for this section will be so called \"anti-quotation splices\".\nThere are two kinds of anti quotation splices, first the so called optional\nones. For example we might declare a syntax with an optional argument,\nsay our own `let` (in real projects this would most likely be a `let`\nin some functional language we are writing a theory about):\n-/\n\nsyntax \"mylet \" ident (\" : \" term)? \" := \" term \" in \" term : term\n\n/-!\nThere is this optional `(\" : \" term)?` argument involved which can let\nthe user define the type of the term to the left of it. With the methods\nwe know so far we'd have to write two `macro_rules` now, one for the case\nwith, one for the case without the optional argument. However the rest\nof the syntactic translation works exactly the same with and without\nthe optional argument so what we can do using a splice here is to essentially\ndefine both cases at once: \n-/\n\nmacro_rules\n | `(mylet $x $[: $ty]? := $val in $body) => `(let $x $[: $ty]? := $val; $body)\n\n/-!\nThe `$[...]?` part is the splice here, it basically says \"if this part of\nthe syntax isn't there, just ignore the parts on the right hand side that\ninvolve anti quotation variables involved here\". So now we can run\nthis syntax both with and without type ascription:\n-/\n\n#eval mylet x := 5 in x - 10 -- 0, due to subtraction behaviour of `Nat`\n#eval mylet x : Int := 5 in x - 10 -- -5, after all it is an `Int` now\n\n/-!\nThe second and last splice might remind readers of list comprehension\nas seen for example in Python. We will demonstrate it using an implementation\nof `map` as a macro:\n-/\n\n-- run the function given at the end for each element of the list\nsyntax \"foreach \" \"[\" term,* \"]\" term : term\n\nmacro_rules\n | `(foreach [ $[$x:term],* ] $func:term) => `(let f := $func; [ $[f $x],* ])\n\n#eval foreach [1,2,3,4] (Nat.add 2) -- [3, 4, 5, 6]\n\n/-!\nIn this case the `$[...],*` part is the splice. On the match side it tries\nto match the pattern we define inside of it repetetively (given the seperator\nwe tell it to). However unlike regular separator matching it does not\ngive us an `Array` or `SepArray`, instead it allows us to write another\nsplice on the right hand side that gets evaluated for each time the\npattern we specified matched, with the specific values from the match\nper iteration.\n-/\n\n/-!\n## Hygiene issues and how to solve them\nIf you are familiar with macro systems in other languages like C you\nprobably know about so called macro hygiene issues already.\nA hygiene issue is when a macro introduces an identifier that collides with an\nidentifier from some syntax that it is including. For example:\n-/\n\n-- Applying this macro produces a function that binds a new identifier `x`.\nmacro \"const\" e:term : term => `(fun x => $e)\n\n-- But `x` can also be defined by a user\ndef x : Nat := 42\n\n-- Which `x` should be used by the compiler in place of `$e`?\n#eval (const x) 10 -- 42\n\n/-\nGiven the fact that macros perform only syntactic translations one might\nexpect the above `eval` to return 10 instead of 42: after all, the resulting\nsyntax should be `(fun x => x) 10`. While this was of course not the intention\nof the author, this is what would happen in more primitive macro systems like\nthe one of C. So how does Lean avoid these hygiene issues? You can read\nabout this in detail in the excellent [Beyond Notations](https://lmcs.episciences.org/9362/pdf)\npaper which discusses the idea and implementation in Lean in detail.\nWe will merely give an overview of the topic, since the details are not\nthat interesting for practical uses. The idea described in Beyond Notations\ncomes down to a concept called \"macro scopes\". Whenever a new macro\nis invoked, a new macro scope (basically a unique number) is added to\na list of all the macro scopes that are active right now. When the current\nmacro introduces a new identifier what is actually getting added is an\nidentifier of the form:\n```\n._@.(.)*.._hyg.\n```\nFor example, if the module name is `Init.Data.List.Basic`, the name is\n`foo.bla`, and macros scopes are [2, 5] we get:\n```\nfoo.bla._@.Init.Data.List.Basic._hyg.2.5\n```\nSince macro scopes are unique numbers the list of macro scopes appended in the end\nof the name will always be unique across all macro invocations, hence macro hygiene\nissues like the ones above are not possible.\n\nIf you are wondering why there is more than just the macro scopes to this\nname generation, that is because we may have to combine scopes from different files/modules.\nThe main module being processed is always the right most one.\nThis situation may happen when we execute a macro generated in a file\nimported in the current file.\n```\nfoo.bla._@.Init.Data.List.Basic.2.1.Init.Lean.Expr_hyg.4\n```\nThe delimiter `_hyg` at the end is used just to improve performance of\nthe function `Lean.Name.hasMacroScopes` -- the format could also work without it.\n\nThis was a lot of technical details. You do not have to understand them\nin order to use macros, if you want you can just keep in mind that Lean\nwill not allow name clashes like the one in the `const` example.\n\nNote that this extends to *all* names that are introduced using syntax\nquotations, that is if you write a macro that produces:\n`` `(def foo := 1) ``, the user will not be able to access `foo`\nbecause the name will subject to hygienie. Luckily there is a way to\ncircumvent this. You can use `mkIdent` to generate a raw identifier,\nfor example: `` `(def $(mkIdent `foo) := 1) ``. In this case it won't\nbe subject to hygiene and accessible to the user.\n\n## `MonadQuotation` and `MonadRef`\nBased on this description of the hygiene mechanism one interesting\nquestion pops up, how do we know what the current list of macro scopes\nactually is? After all in the macro functions that were defined above\nthere is never any explicit passing around of the scopes happening.\nAs is quite common in functional programming, as soon as we start\nhaving some additional state that we need to bookkeep (like the macro scopes)\nthis is done with a monad, this is the case here as well with a slight twist.\n\nInstead of implementing this for only a single monad `MacroM` the general\nconcept of keeping track of macro scopes in monadic way is abstracted\naway using a type class called `MonadQuotation`. This allows any other\nmonad to also easily provide this hygienic `Syntax` creation mechanism\nby simply implementing this type class.\n\nThis is also the reason that while we are able to use pattern matching on syntax\nwith `` `(syntax) `` we cannot just create `Syntax` with the same\nsyntax in pure functions: there is no `Monad` implementing `MonadQuotation`\ninvolved in order to keep track of the macro scopes.\n\nNow let's take a brief look at the `MonadQuotation` type class:\n-/\n\nnamespace Playground\n\nclass MonadRef (m : Type → Type) where\n getRef : m Syntax\n withRef {α} : Syntax → m α → m α\n\nclass MonadQuotation (m : Type → Type) extends MonadRef m where\n getCurrMacroScope : m MacroScope\n getMainModule : m Name\n withFreshMacroScope {α : Type} : m α → m α\n\nend Playground\n\n/-\nSince `MonadQuotation` is based on `MonadRef`, let's take a look at `MonadRef`\nfirst. The idea here is quite simple: `MonadRef` is meant to be seen as an extension\nto the `Monad` typeclass which\n- gives us a reference to a `Syntax` value with `getRef`\n- can evaluate a certain monadic action `m α` with a new reference to a `Syntax`\n using `withRef`\n\nOn it's own `MonadRef` isn't exactly interesting, but once it is combined with\n`MonadQuotation` it makes sense.\n\nAs you can see `MonadQuotation` extends `MonadRef` and adds 3 new functions:\n- `getCurrMacroScope` which obtains the latest `MacroScope` that was created\n- `getMainModule` which (obviously) obtains the name of the main module,\n both of these are used to create these hygienic identifiers explained above\n- `withFreshMacroScope` which will compute the next macro scope and run\n some computation `m α` that performs syntax quotation with this new\n macro scope in order to avoid name clashes. While this is mostly meant\n to be used internally whenever a new macro invocation happens, it can sometimes\n make sense to use this in our own macros, for example when we are generating\n some syntax block repeatedly and want to avoid name clashes.\n\nHow `MonadRef` comes into play here is that Lean requires a way to indicate\nerrors at certain positions to the user. One thing that wasn't introduced\nin the `Syntax` chapter is that values of type `Syntax` actually carry their\nposition in the file around as well. When an error is detected, it is usually\nbound to a `Syntax` value which tells Lean where to indicate the error in the file.\nWhat Lean will do when using `withFreshMacroScope` is to apply the position of\nthe result of `getRef` to each introduced symbol, which then results in better\nerror positions than not applying any position.\n\nTo see error positioning in action, we can write a little macro that makes use of it:\n-/\n\nsyntax \"error_position\" ident : term\n\nmacro_rules\n | `(error_position all) => Macro.throwError \"Ahhh\"\n -- the `%$tk` syntax gives us the Syntax of the thing before the %,\n -- in this case `error_position`, giving it the name `tk`\n | `(error_position%$tk first) => withRef tk (Macro.throwError \"Ahhh\")\n\n#eval error_position all -- the error is indicated at `error_position all`\n#eval error_position first -- the error is only indicated at `error_position`\n\n/-\nObviously controlling the positions of errors in this way is quite important\nfor a good user experience.\n\n## Mini project\nAs a final mini project for this section we will re-build the arithmetic\nDSL from the syntax chapter in a slightly more advanced way, using a macro\nthis time so we can actually fully integrate it into the Lean syntax.\n-/\ndeclare_syntax_cat arith\n\nsyntax num : arith\nsyntax arith \"-\" arith : arith\nsyntax arith \"+\" arith : arith\nsyntax \"(\" arith \")\" : arith\nsyntax \"[Arith|\" arith \"]\" : term\n\nmacro_rules\n | `([Arith| $x:num]) => `($x)\n | `([Arith| $x:arith + $y:arith]) => `([Arith| $x] + [Arith| $y]) -- recursive macros are possible\n | `([Arith| $x:arith - $y:arith]) => `([Arith| $x] - [Arith| $y])\n | `([Arith| ($x:arith)]) => `([Arith| $x])\n\n#eval [Arith| (12 + 3) - 4] -- 11\n\n/-! Again feel free to play around with it. If you want to build more complex\nthings, like expressions with variables, maybe consider building an inductive type\nusing macros instead. Once you got your arithmetic expression term\nas an inductive, you could then write a function that takes some form of\nvariable assignment and evaluates the given expression for this\nassignment. You could also try to embed arbitrary `term`s into your\narith language using some special syntax or whatever else comes to your mind.\n-/\n\n/-!\n## More elaborate examples\n### Binders 2.0\nAs promised in the syntax chapter here is Binders 2.0. We'll start by\nreintroducing our theory of sets:\n-/\ndef Set (α : Type u) := α → Prop\ndef Set.mem (x : α) (X : Set α) : Prop := X x\n\n-- Integrate into the already existing typeclass for membership notation\ninstance : Membership α (Set α) where\n mem := Set.mem\n\ndef Set.empty : Set α := λ _ => False\n\n-- the basic \"all elements such that\" function for the notation\ndef setOf {α : Type} (p : α → Prop) : Set α := p\n\n/-!\nThe goal for this section will be to allow for both `{x : X | p x}`\nand `{x ∈ X, p x}` notations. In principle there are two ways to do this:\n1. Define a syntax and macro for each way to bind a variable we might think of\n2. Define a syntax cateogry of binders that we could reuse across other\n binder constructs such as `Σ` or `Π` as well and implement macros for\n the `{ | }` case\n\nIn this section we will use approach 2 because it is more easily reusable.\n-/\n\ndeclare_syntax_cat binder_construct\nsyntax \"{\" binder_construct \"|\" term \"}\" : term\n\n/-!\nNow let's define the two binders constructs we are interested in:\n-/\nsyntax ident \" : \" term : binder_construct\nsyntax ident \" ∈ \" term : binder_construct\n\n/-!\nAnd finally the macros to expand our syntax:\n-/\n\nmacro_rules\n | `({ $var:ident : $ty:term | $body:term }) => `(setOf (fun ($var : $ty) => $body))\n | `({ $var:ident ∈ $s:term | $body:term }) => `(setOf (fun $var => $var ∈ $s ∧ $body))\n\n-- Old examples with better syntax:\n#check { x : Nat | x ≤ 1 } -- setOf fun x => x ≤ 1 : Set Nat\n\nexample : 1 ∈ { y : Nat | y ≤ 1 } := by simp[Membership.mem, Set.mem, setOf]\nexample : 2 ∈ { y : Nat | y ≤ 3 ∧ 1 ≤ y } := by simp[Membership.mem, Set.mem, setOf]\n\n-- New examples:\ndef oneSet : Set Nat := λ x => x = 1\n#check { x ∈ oneSet | 10 ≤ x } -- setOf fun x => x ∈ oneSet ∧ 10 ≤ x : Set Nat\n\nexample : ∀ x, ¬(x ∈ { y ∈ oneSet | y ≠ 1 }) := by\n intro x h\n -- h : x ∈ setOf fun y => y ∈ oneSet ∧ y ≠ 1\n -- ⊢ False\n cases h\n -- : x ∈ oneSet\n -- : x ≠ 1\n contradiction\n\n\n/-!\n## Reading further\nIf you want to know more about macros you can read:\n- the API docs: TODO link\n- the source code: the lower parts of [Init.Prelude](https://github.com/leanprover/lean4/blob/master/src/Init/Prelude.lean)\n as you can see they are declared quite early in Lean because of their importance\n to building up syntax\n- the aforementioned [Beyond Notations](https://lmcs.episciences.org/9362/pdf) paper\n-/\n", "meta": {"author": "leanprover-community", "repo": "lean4-metaprogramming-book", "sha": "0b2e7e2c0cacac530ed947df878088c5d9715412", "save_path": "github-repos/lean/leanprover-community-lean4-metaprogramming-book", "path": "github-repos/lean/leanprover-community-lean4-metaprogramming-book/lean4-metaprogramming-book-0b2e7e2c0cacac530ed947df878088c5d9715412/lean/main/macros.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.14608723589515565, "lm_q2_score": 0.11436852316318395, "lm_q1q2_score": 0.016707781422320628}} {"text": "-- Author(s): Andrés Goens\n-- See Copyright Notice in LICENSE\n\nimport Pop.Util\nopen Util Std.HashMap\n\nnamespace Pop\n\ndef RequestId := Nat deriving ToString, BEq, Inhabited, Hashable\ndef Value := Option Nat deriving ToString, BEq, Inhabited\ndef Address := Nat deriving ToString, BEq, Inhabited\ndef ThreadId := Nat deriving Ord, LT, LE, ToString, Inhabited, Hashable, DecidableEq\ninductive ConditionalValue\n | const : Nat → ConditionalValue\n | tentative : Nat → ConditionalValue\n --| transaction : Nat → ConditionalValue\n | fetchAndAdd : ConditionalValue\n | failed : ConditionalValue\n deriving BEq, Inhabited\n\ndef ConditionalValue.update : ConditionalValue → Value → ConditionalValue\n | c@(.const v), some v' => if v == v' then c else .failed\n | c@(.tentative v), some v' => if v == v' then c else .failed\n | (.const _), none => .failed\n | (.tentative _), none => .failed\n | .failed , _ => .failed\n | .fetchAndAdd, some v => .tentative (v + 1)\n | .fetchAndAdd, none => .failed\n\ndef ConditionalValue.validate : ConditionalValue → ConditionalValue\n | .tentative v => .const v\n | c => c\n\ndef RequestId.toNat : RequestId → Nat := λ x => x\ndef ThreadId.toNat : ThreadId → Nat := λ x => x\ndef RequestId.ofNat : Nat → RequestId := λ x => x\ndef ThreadId.ofNat : Nat → ThreadId := λ x => x\ndef Address.ofNat : Nat → Address := λ x => x\ndef Value.ofNat : Nat → Value := λ x => some x\ndef Value.ofOptionNat : Option Nat → Value := λ x => x\n\ninstance : OfNat ThreadId n where ofNat := ThreadId.ofNat n\ninstance : OfNat RequestId n where ofNat := RequestId.ofNat n\ninstance : OfNat Address n where ofNat := Address.ofNat n\ninstance : OfNat Value n where ofNat := Value.ofNat n\ninstance : Coe RequestId Nat where coe := RequestId.toNat\n\ninstance : BEq ThreadId := @instBEq ThreadId instThreadIdDecidableEq\ninstance : Lean.Quote ThreadId where quote := λ n => Lean.quote (ThreadId.toNat n)\ninstance : ToString ConditionalValue where toString\n | .const n => s!\"{n}\"\n | .tentative n => s!\"{n}?\"\n | .fetchAndAdd => s!\"(n+1)\"\n | .failed => \"FAILED\"\n\ninstance : LawfulBEq ThreadId := inferInstance\ninstance : LawfulBEq (List ThreadId) := inferInstance\n\ndef Address.prettyPrint (addr : Address) : String :=\n match (OfNat.ofNat addr) with\n | 0 => s!\"x\"\n | 1 => s!\"y\"\n | 2 => s!\"z\"\n | 3 => s!\"w\"\n | addr => s!\"v{addr}\"\n\n\ninductive BlockingKinds\n | Read2ReadPred\n | Read2ReadNoPred\n | Read2WritePred\n | Read2WriteNoPred\n | Write2Read\n | Write2Write\n deriving BEq\n\nabbrev BlockingSemantics := List BlockingKinds\n\ndef BlockingKinds.toString : BlockingKinds → String\n | .Read2ReadPred => \"R → R (P)\"\n | .Read2ReadNoPred => \"R → R (NP)\"\n | .Read2WritePred => \"R → W (P)\"\n | .Read2WriteNoPred => \"R → W (NP)\"\n | .Write2Read => \"W → R\"\n | .Write2Write => \"W → W\"\n\ninstance : ToString BlockingKinds where toString := BlockingKinds.toString\n\nclass ArchReq where\n (type : Type 0)\n (instBEq : BEq type)\n (instInhabited : Inhabited type)\n (instToString : ToString type)\n (prettyPrint : type → String := instToString.toString)\n (isPermanentRead : type → Bool := λ _ => false)\n\nvariable [ArchReq]\n\ninductive Atomicity where\n | nonatomic : Atomicity\n | transactional : Atomicity\n | atomic : Atomicity\n deriving BEq, Inhabited\n\ninstance : ToString Atomicity where toString\n | .nonatomic => \"\"\n | .transactional => \"t\"\n | .atomic => \"a\"\n\nstructure ReadRequest where\n addr : Address\n reads_from : Option RequestId\n atomicity : Atomicity\n val : Value\n deriving BEq, Inhabited\n\nstructure WriteRequest where\n addr : Address\n val : ConditionalValue\n atomicity : Atomicity\n deriving BEq, Inhabited\n\ninstance : BEq ArchReq.type := ArchReq.instBEq\ninstance : Inhabited ArchReq.type := ArchReq.instInhabited\ninstance : ToString ArchReq.type := ArchReq.instToString\n\ninductive BasicRequest\n | read : ReadRequest → ArchReq.type → BasicRequest\n | write : WriteRequest → ArchReq.type → BasicRequest\n | fence : ArchReq.type → BasicRequest\n deriving BEq\n\ninstance : Inhabited BasicRequest where default := BasicRequest.fence default\n\ndef BasicRequest.atomicity : BasicRequest → Atomicity\n | .read rr _ => rr.atomicity\n | .write wr _ => wr.atomicity\n | .fence _ => .nonatomic\n\ndef BasicRequest.toString : BasicRequest → String\n | BasicRequest.read rr ty =>\n let tyStr := match s!\"{ty}\" with | \"\" => \"\" | str => s!\". {str}\"\n s!\"R{rr.atomicity}{tyStr} {rr.addr.prettyPrint}\" ++ match rr.val with | none => \"\" | some v => s!\" // {v}\"\n | BasicRequest.write wr ty =>\n let tyStr := match s!\"{ty}\" with | \"\" => \"\" | str => s!\". {str}\"\n s!\"W{wr.atomicity}{tyStr} {wr.addr.prettyPrint} {wr.val}\"\n | BasicRequest.fence ty =>\n let tyStr := match s!\"{ty}\" with | \"\" => \"\" | str => s!\". {str}\"\n s!\"Fence{tyStr}\"\n\ndef BasicRequest.prettyPrint : BasicRequest → String\n | BasicRequest.read rr ty =>\n let valStr := match rr.val with\n | none => \"\"\n | some val => s!\"({val})\"\n let tyStr := match s!\"{ArchReq.prettyPrint ty}\" with\n | \"\" => \"\"\n | str => s!\".{str}\"\n s!\"R{rr.atomicity}{tyStr} {rr.addr.prettyPrint}{valStr}\"\n | BasicRequest.write wr ty =>\n let tyStr := match s!\"{ArchReq.prettyPrint ty}\" with\n | \"\" => \"\"\n | str => s!\".{str}\"\n s!\"W{wr.atomicity}{tyStr} {wr.addr.prettyPrint}({wr.val})\"\n | BasicRequest.fence ty =>\n let tyStr := match s!\"{ArchReq.prettyPrint ty}\" with\n | \"\" => \"\"\n | str => s!\".{str}\"\n s!\"Fence{tyStr}\"\n\ninstance : ToString (BasicRequest) where toString := BasicRequest.toString\n\ndef BasicRequest.type : BasicRequest → ArchReq.type\n | BasicRequest.read _ t => t\n | BasicRequest.write _ t => t\n | BasicRequest.fence t => t\n\ndef BasicRequest.readRequest? : BasicRequest → Option ReadRequest\n | BasicRequest.read rr _ => some rr\n | BasicRequest.write _ _ => none\n | BasicRequest.fence _ => none\n\ndef BasicRequest.writeRequest? : BasicRequest → Option WriteRequest\n | BasicRequest.read _ _ => none\n | BasicRequest.write wr _ => some wr\n | BasicRequest.fence _ => none\n\ndef BasicRequest.updateType : BasicRequest → (ArchReq.type → ArchReq.type) → BasicRequest\n | .read rr t, f => .read rr (f t)\n | .write wr t, f => .write wr (f t)\n | .fence t, f => .fence (f t)\n\ndef BasicRequest.setValue : BasicRequest → Value → BasicRequest\n | BasicRequest.read rr rt, v => BasicRequest.read {rr with val := v} rt\n | br, _ => br\n\ndef BasicRequest.updateValue : BasicRequest → Value → BasicRequest\n | BasicRequest.write wr rt, v => BasicRequest.write {wr with val := wr.val.update v} rt\n | br, _ => br\n\ndef BasicRequest.validateWrite : BasicRequest → BasicRequest\n | BasicRequest.write wr rt => BasicRequest.write {wr with val := wr.val.validate} rt\n | br => br\n\ndef BasicRequest.value? : BasicRequest → Value\n | BasicRequest.read rr _ => rr.val\n | BasicRequest.write wr _ => match wr.val with\n | .const n => some n\n | .tentative n => some n\n | _ => none\n | _ => none\n\ndef BasicRequest.conditionalValue? : BasicRequest → Option ConditionalValue\n | .write wr _ => some wr.val\n | _ => none\n\nstructure ValidScopes where\n system_scope : List ThreadId\n scopes : ListTree ThreadId\n --scopes_consistent : ∀ s, scopes.elem s → s.sublist system_scope\n --system_scope_is_scope : system_scope ∈ scopes\n\ndef ValidScopes.default : ValidScopes :=\n { system_scope := [], scopes := ListTree.leaf [],\n -- scopes_consistent :=\n -- (by\n -- intros s h\n -- simp [ListTree.elem] at h\n -- rw [h]\n -- simp),\n -- system_scope_is_scope :=\n -- (by simp [ (· ∈ ·) ])\n }\n\ninstance : Inhabited ValidScopes where default := ValidScopes.default\n\ndef ValidScopes.toStringHet (threadType : Option (ThreadId → String)) (scopes : ValidScopes) : String :=\n let scopeFun := match threadType with\n | none => λ _ => \"\"\n | some f => λ ss =>\n let labs := removeDuplicates $ List.map f ss\n if labs == [\"default\"] || labs == [] then \"\" else\n if labs.length == 1 then labs.head! else\n String.intercalate \"+\" labs\n let scopeLab := λ s : List ThreadId => if s.isEmpty then \"\" else toString s ++ scopeFun s\n \"{\" ++ String.intercalate \", \" (scopes.scopes.toList.map scopeLab) ++ \"}\"\n\ndef ValidScopes.toString (scopes : ValidScopes) : String := scopes.toStringHet none\ninstance : ToString ValidScopes where toString := ValidScopes.toString\n\nopen Lean in\nprivate def quoteValidScopes : ValidScopes → Term\n | ValidScopes.mk system_scope scopes /-consistent system_is_scope-/ => Syntax.mkCApp ``ValidScopes.mk #[quote system_scope, quote scopes] -- , sorry, sorry]\ninstance : Lean.Quote ValidScopes where quote := quoteValidScopes\n\nstructure Scope {V : ValidScopes} where\n threads : List ThreadId\n valid : threads ∈ V.scopes\n\ninstance {V : ValidScopes} : ToString (@Scope V) where toString := λ ⟨threads,_⟩ => s!\"{threads}\"\n\ninstance {V : ValidScopes} : BEq (@Scope V) where\n beq := λ scope₁ scope₂ => scope₁.threads == scope₂.threads\n\ninstance {V : ValidScopes} : BEq (@Scope V) where\n beq := λ scope₁ scope₂ => scope₁.threads == scope₂.threads\n\ninstance {V : ValidScopes} : LE (@Scope V) where\n le := λ scope₁ scope₂ => List.sublist scope₁.threads scope₂.threads\n\nstructure Request where\n id : RequestId\n propagated_to : List ThreadId\n predecessor_at : List ThreadId\n thread : ThreadId\n basic_type : BasicRequest\n occurrence : Nat\n pairedRequest? : Option RequestId\n -- scope : Scope\n -- type : α\n deriving BEq\n\n\ndef Request.default : Request :=\n {id := 0, propagated_to := [], predecessor_at := [], thread := 0,\n occurrence := 0, basic_type := BasicRequest.fence Inhabited.default, pairedRequest? := none}\ninstance : Inhabited (Request) where default := Request.default\n\ndef Request.toString : Request → String\n | req => s!\" Request {req.id} {req.basic_type.prettyPrint} : [propagated to {req.propagated_to}, origin thread : {req.thread}, pred. at : {req.predecessor_at}]\"\ninstance : ToString (Request) where toString := Request.toString\n\ndef Request.toShortString : Request → String\n | req => s!\"{req.id}[{req.basic_type.toString}]\"\n\ndef BasicRequest.isRead (r : BasicRequest) : Bool := match r with | read _ _ => true | _ => false\ndef BasicRequest.isWrite (r : BasicRequest) : Bool := match r with | write _ _ => true | _ => false\ndef BasicRequest.isFence (r : BasicRequest) : Bool := match r with | fence _ => true | _ => false\n\ndef BasicRequest.isAtomic (r : BasicRequest) : Bool := match r with | .read rr _ => rr.atomicity == .atomic | .write wr _ => wr.atomicity == .atomic | .fence _ => false\ndef BasicRequest.isTransactional (r : BasicRequest) : Bool := match r with | .read rr _ => rr.atomicity == .transactional | .write wr _ => wr.atomicity == .transactional | .fence _ => false\ndef Request.isRead (r : Request) : Bool := r.basic_type.isRead\ndef Request.isWrite (r : Request) : Bool := r.basic_type.isWrite\ndef Request.isFence (r : Request) : Bool := r.basic_type.isFence\ndef Request.isMem (r : Request) : Bool := !r.basic_type.isFence\ndef Request.isPermanentRead (r : Request) : Bool := r.isRead && ArchReq.isPermanentRead r.basic_type.type\n\ndef Request.value? (r : Request) : Value := r.basic_type.value?\ndef Request.setValue (r : Request) (v : Value) : Request := { r with basic_type := r.basic_type.setValue v}\ndef Request.updateValue (r : Request) (v : Value) : Request :=\n { r with basic_type := r.basic_type.updateValue v}\ndef Request.validateWrite (r : Request) : Request := { r with basic_type := r.basic_type.validateWrite}\ndef Request.isSatisfied (r : Request) : Bool := match r.basic_type with\n | .read rr _ => rr.val.isSome\n | _ => false\n\ndef Request.isAtomic (r : Request) : Bool := r.basic_type.isAtomic\ndef Request.isTransactional (r : Request) : Bool := r.basic_type.isTransactional\n\ndef BasicRequest.address? (r : BasicRequest) : Option Address := match r with\n | read req _ => some req.addr\n | write req _ => some req.addr\n | _ => none\n\ndef Request.address? (r : Request) : Option Address := r.basic_type.address?\n\ndef Request.equivalent (r₁ r₂ : Request) : Bool :=\n if r₁.isFence then r₁.basic_type == r₂.basic_type\n else r₁.address? == r₂.address? && r₁.value? == r₂.value? && r₁.thread == r₂.thread &&\n ((r₁.isWrite && r₂.isWrite) || (r₁.isRead && r₂.isRead))\n\n-- Read, Write\ndef SatisfiedRead := RequestId × RequestId deriving ToString, BEq\n\n--instance [BEq α] : Membership (List α) (ListTree α) where\n-- mem lst tree := tree.elem lst = true\n\ndef decideThreadsValid (threads : List ThreadId) (V : ValidScopes) : Decidable (threads ∈ V.scopes) :=\n if h : V.scopes.elem threads then\n Decidable.isTrue h\n else\n Decidable.isFalse h\n\ninstance {threads : List ThreadId} {V : ValidScopes} : Decidable (threads ∈ V.scopes) := decideThreadsValid threads V\n\ndef ValidScopes.validate (V : ValidScopes) (threads : List ThreadId) : Option (@Scope V) :=\n if h : threads ∈ V.scopes then\n some { threads := threads, valid := h }\n else\n none\n\n-- Gives the subscopes of S, including S.\ndef ValidScopes.subscopes (V : ValidScopes) (S : @Scope V) : List (@Scope V) :=\n let children := V.scopes.nodesBelow S.threads\n filterNones $ children.map V.validate\n\ndef ValidScopes.containThread (V: ValidScopes) (t : ThreadId) : List (@Scope V) :=\n let containing := V.scopes.nodesAbove [t]\n filterNones $ containing.map V.validate\n\ndef ValidScopes.systemScope {V : ValidScopes } : @Scope V :=\n {threads := V.system_scope, valid := sorry} -- V.system_scope_is_scope}\n\ninstance {V : ValidScopes} : Inhabited (@Scope V) where\n default := V.systemScope\n\ndef ValidScopes.isUnscoped (V : ValidScopes) : Bool :=\n V.scopes == (ListTree.leaf V.system_scope)\n\ndef ValidScopes.jointScope : (V : ValidScopes) → ThreadId → ThreadId → (@Scope V)\n | valid, t₁, t₂ => match valid.scopes.meet t₁ t₂ with\n | some scope => {threads := scope, valid := sorry}\n | none => panic! s!\"can't find the joint scope of {t₁} and {t₂} in {valid.scopes}\"-- can we get rid of this case distinction?\n\ndef ValidScopes.reqThreadScope (V : ValidScopes ) (req : Request) : (@Scope V) :=\n V.jointScope req.thread req.thread\n\ndef ValidScopes.intersection : (V : ValidScopes) → @Scope V → @Scope V → Option (@Scope V)\n | V, s1, s2 => V.validate $ s1.threads.intersection s2.threads\n\ndef Request.propagatedTo (r : Request) (t : ThreadId) : Bool := r.propagated_to.elem t\n\ndef Request.fullyPropagated {V : ValidScopes} (r : Request) (s : optParam (@Scope V) V.systemScope) : Bool :=\n let propToList := s.threads.map (λ t => Request.propagatedTo r t)\n propToList.foldl (init:= true) (. && .)\n\ndef Request.isPredecessorAt (req : Request) (thId : ThreadId) : Bool :=\n req.predecessor_at.contains thId\n\ndef Request.makePredecessorAt (req : Request) (thId : ThreadId) : Request :=\n if req.isPredecessorAt thId then req else { req with predecessor_at := thId :: req.predecessor_at}\n\n/-\n We have scoped order constraints, i.e. a different set of order constraints\n for each scope. Order constraints specify a partial order on requests, and\n we represent them with a Bool value for a pair of (r₁,r₂) : RequestId × RequestId,\n which is true ↔ there is an order constraint r₁ →s r₂, for the scope s.\n\n However, we have a property (by construction) that if s' ≤ s and r₁ →s r₂, then\n also r₁ →s' r₂. Can we use this to find a more compact representation?\n-/\nstructure OrderConstraints {V : ValidScopes} where\n val : Std.HashMap (List ThreadId) (Std.HashMap (RequestId × RequestId) Bool)\n default : Bool\n\ndef OrderConstraints.empty {V : ValidScopes} (numReqs : optParam Nat 10) : @OrderConstraints V :=\n let scopes := V.scopes.toList\n { default := false, val :=\n Std.mkHashMap (capacity := scopes.length) |> scopes.foldl λ acc s => acc.insert s (Std.mkHashMap (capacity := numReqs))\n }\n\n-- TODO: make scope an optional parameter and just do the intersection by default?\n-- Would need to move around things in Arch typeclass...\ndef OrderConstraints.lookup {V : ValidScopes} (ordc : @OrderConstraints V)\n (S : @Scope V) (req₁ req₂ : RequestId) : Bool :=\n let sc_ordc := ordc.val.find? S.threads\n match sc_ordc with\n | none => ordc.default\n | some hashmap =>\n hashmap.findD (req₁, req₂) ordc.default\n\ndef OrderConstraints.predecessors {V : ValidScopes} (S : @Scope V) (req : RequestId)\n (reqs : List RequestId) (constraints : @OrderConstraints V) : List RequestId :=\n let sc_oc := constraints.lookup S -- hope this gets optimized accordingly...\n reqs.filter (λ x => sc_oc x req)\n\ndef OrderConstraints.successors {V : ValidScopes} (S : @Scope V) (req : RequestId)\n (reqs : List RequestId) (constraints : @OrderConstraints V) : List RequestId :=\n let sc_oc := constraints.lookup S -- hope this gets optimized accordingly...\n reqs.filter (λ x => sc_oc req x)\n\n def OrderConstraints.transitiveSuccessors {V : ValidScopes} (S : @Scope V) (req : RequestId)\n (reqs : List RequestId) (constraints : @OrderConstraints V) : List RequestId :=\n let sc_oc := constraints.lookup S\n Id.run do\n let mut succ := []\n let mut succ' := [req]\n while succ != succ' do\n succ := succ'\n succ' := reqs.filter\n λ x => succ'.any\n λ s => x == s || sc_oc s x\n return succ'\n\ndef OrderConstraints.between {V : ValidScopes} (S : @Scope V) (req₁ req₂ : RequestId)\n (reqs : List RequestId) (constraints : @OrderConstraints V) : List RequestId :=\n let preds₁ := constraints.predecessors S req₁ reqs\n let preds₂ := constraints.predecessors S req₂ reqs\n preds₂.removeAll (req₁::preds₁)\n\n-- TODO: is this really a quasi top sort?\ndef OrderConstraints.qtopSort {V : ValidScopes} (S : @Scope V)\n (reqs : List Request) (constraints : @OrderConstraints V) : List Request :=\n reqs.toArray.qsort (λ r₁ r₂ => constraints.lookup S r₁.id r₂.id) |>.toList\n\n/-\ndef SystemState.betweenRequests (state : SystemState) (req₁ req₂ : Request) : List Request :=\n let betweenIds := state.orderConstraints.between\n req₁.id req₂.id (reqIds state.requests)\n state.idsToReqs betweenIds\n -/\n\ndef OrderConstraints.compare {V₁ V₂ : ValidScopes} ( oc₁ : @OrderConstraints V₁) (oc₂ : @OrderConstraints V₂)\n (requests : List RequestId) : Bool :=\n if V₁.scopes.toList != V₂.scopes.toList\n then false\n else\n let scopes₁ := V₁.scopes.toList.map V₁.validate\n let scopes₂ := V₂.scopes.toList.map V₂.validate\n let scopes := scopes₁.zip scopes₂ -- pretty hacky: should get types to match\n let reqPairs := List.join $ requests.map λ r₁ => requests.foldl (init := []) λ reqs r₂ => (r₁,r₂)::reqs\n let keys := List.join $ scopes.map λ s => reqPairs.foldl (init := []) λ ks (r₁,r₂) => (s,r₁,r₂)::ks\n keys.all λ (s,r₁,r₂) => match s with\n | (some s₁, some s₂) => (oc₁.lookup s₁ r₁ r₂ == oc₂.lookup s₂ r₁ r₂)\n | _ => panic! s!\"invalid scopes {scopes₁} or {scopes₂}\"\n\ndef OrderConstraints.addSingleScope {V : ValidScopes} (constraints : @OrderConstraints V)\n (scope : @Scope V) (reqs : List (RequestId × RequestId)) (val := true) : @OrderConstraints V :=\n match constraints.val.find? scope.threads with\n | none => constraints\n | some sc_oc =>\n let sc_oc' := reqs.foldl (init := sc_oc) λ oc req => oc.insert req val\n let val' := constraints.val.insert scope.threads sc_oc'\n { constraints with val := val' }\n\n-- Updates `constraints` to add all pairs in `reqs` to the scope `scope` and each\n-- of its suscopes. The optional value `val` is what the constraint is updated to,\n-- and defaults to `true`.\ndef OrderConstraints.addSubscopes {V : ValidScopes} (constraints : @OrderConstraints V)\n(scope : @Scope V) (reqs : List (RequestId × RequestId)) (val := true) : @OrderConstraints V :=\n let subscopes := V.subscopes scope\n --dbg_trace s!\"{scope.threads}.subscopes: {subscopes.map λ s => s.threads}\"\n subscopes.foldl (init := constraints) λ oc sc => oc.addSingleScope sc reqs (val := val)\n\ndef OrderConstraints.swap {V : ValidScopes} (oc : @OrderConstraints V)\n (scope : @Scope V) (req₁ req₂ : RequestId) : @OrderConstraints V :=\n let c₁₂ := oc.lookup scope req₁ req₂\n let c₂₁ := oc.lookup scope req₂ req₁\n Id.run do\n if c₁₂ == c₂₁ then\n panic! \"cycle {req₁.id} ↔ {req₂.id} detected in order constraints.\"\n let mut add := []\n let mut remove := []\n if c₁₂ then\n add :=( req₂,req₁) :: add\n remove :=( req₁,req₂) :: remove\n if c₂₁ then\n add :=( req₁,req₂) :: add\n remove :=( req₂,req₁) :: remove\n let mut oc' := oc\n oc' := oc'.addSubscopes scope add\n oc' := oc'.addSubscopes scope remove (val := false)\n return oc'\n\ndef OrderConstraints.groupsToString : List Request → List Request → String\n | [],_ => \"\"\n | _,[] => \"\"\n | reqs₁, reqs₂ =>\n let vars₁ := removeDuplicates $ reqs₁ |>.map Request.address?\n let vars₂ := removeDuplicates $ reqs₂ |>.map Request.address?\n let vars := vars₁.filter vars₂.contains\n let colorFun := λ r => if vars.contains r.address? && r.address?.isSome then\n colorString Color.magenta r.toShortString else r.toShortString\n let (r₁strings, r₂strings) := (reqs₁.map colorFun, reqs₂.map colorFun)\n \"{\" ++ (String.intercalate \", \" $ r₁strings) ++\n \"} → {\" ++ (String.intercalate \", \" $ r₂strings) ++ \"}\"\n\ndef OrderConstraints.toString {V : ValidScopes} (constraints : @OrderConstraints V) (scope : @Scope V) (reqs : List Request) : String := Id.run do\n let reqsSorted := constraints.qtopSort scope reqs\n let mut pairs := []\n for req in reqsSorted do\n let deps := reqsSorted.filter λ req' => constraints.lookup scope req.id req'.id\n if deps.isEmpty then\n continue\n pairs := pairs ++ [ (req,deps) ]\n let mut res : List (List Request × List Request) := []\n for (req,deps) in pairs do\n if res.any λ (lhs,_) => lhs.contains req then\n continue\n let mut lhs := [req]\n for req' in reqsSorted do\n if req' == req then\n continue\n if pairs.lookup req' == some deps then\n lhs := req'::lhs\n res := res ++ [(lhs,deps)]\n String.intercalate \"; \" $ res.map λ (lhs,rhs) => OrderConstraints.groupsToString lhs rhs\n\nprivate def opReqId? : Option (Request) → Option RequestId := Option.map λ r => r.id\n\nprivate def valConsistent (vals : Array (Option (Request))) : Bool :=\n let valOpIds := vals.map opReqId?\n let valConsistent := λ idx opVal => match opVal with\n | none => true\n | some val => val == idx.val\n let consistentVals := valOpIds.mapIdx valConsistent\n consistentVals.foldl (. && .) true\n\nstructure RequestArray where\n val : Array (Option (Request))\n coherent : valConsistent val = true\n\ninstance : BEq (RequestArray) where beq := λ arr₁ arr₂ => arr₁.val == arr₂.val\n\ndef RequestArray.getReq? : RequestArray → RequestId → Option (Request)\n | arr, rId => match arr.val[rId.toNat]? with\n | some (some req) => some req\n | _ => none\n\ndef RequestArray.getReq! : RequestArray → RequestId → Request\n | arr, rId => arr.val[rId.toNat]?.get!.get!\n\ndef RequestArray.printReq : RequestArray → RequestId → String\n | arr, rId => match arr.getReq? rId with\n | none => \"\"\n | some r => r.toShortString\n\ndef RequestArray.seen : RequestArray → List RequestId\n | arr => List.range arr.val.size\n\ndef RequestArray.map {β : Type} : RequestArray → (Request → β) → Array β\n | rarr, f => filterNonesArr $ rarr.val.map λ opreq => Option.map f opreq\n-- instance : GetElem RequestArray RequestId (Option Request) where getElem\n\ntheorem emptyArrayCoherent : valConsistent (Array.mk ([] : List (Option (Request)))) := by\n sorry -- metavariable screws up simp\n\ndef RequestArray.empty : RequestArray :=\n { val := Array.mk [], coherent := emptyArrayCoherent }\n\ndef RequestArray.toString : RequestArray → String\n | arr => String.intercalate \",\\n\" $ List.map Request.toString $ filterNones arr.val.toList\n\ninstance : ToString (RequestArray) where toString := RequestArray.toString\n\ndef RequestArray.filter : RequestArray → (Request → Bool) → List Request\n | ra, f =>\n let fOp : Option Request → Bool\n | some r => f r\n | none => false\n filterNones $ Array.toList $ ra.val.filter fOp\n\ndef RequestArray.prettyPrint (arr : RequestArray) (numThreads : Nat) (order : @OrderConstraints V) (colWidth := 25) (highlight : optParam (Option $ ThreadId × RequestId) none) : String := Id.run do\n let mut threads := []\n let mut res := \"\"\n for thId in (List.range numThreads) do\n if thId != 0 then\n res := res ++ \"||\"\n res := res ++ s!\" T{thId}\" ++ (String.mk $ List.replicate (colWidth - 3) ' ')\n let mut thread := []\n for req in arr.filter (λ r => !(r.isWrite && r.value? == some 0)) do\n if highlight == some (thId, req.id) then\n thread := thread ++ [(Color.yellow, req)]\n else if req.thread == thId then\n thread := thread ++ [(Color.cyan, req)]\n else if req.propagatedTo thId then\n thread := thread ++ [(Color.black, req)]\n threads := threads ++ [thread]\n res := res ++ \"|\\n\" ++ (String.mk $ List.replicate (colWidth * numThreads + 2 * (numThreads - 1)) '-') ++ \"\\n\"\n threads := threads.map\n (λ th => th.toArray.qsort\n (λ r₁ r₂ => order.lookup (V.jointScope r₁.2.thread r₂.2.thread) r₁.2.id r₂.2.id)\n |>.toList)\n while threads.any (!·.isEmpty) do\n let mut sep := false\n for thread in threads do\n if sep then\n res := res ++ \"||\"\n else\n sep := true\n res := res ++ match thread.head? with\n | none => (String.mk $ List.replicate colWidth ' ')\n | some (color,r) => \" \" ++ (colorString color r.toShortString) ++ (String.mk $ List.replicate (colWidth - r.toShortString.length - 1) ' ')\n res := res ++ \"|\\n\"\n threads := threads.map List.tail\n return res\n\ndef reqIds : (RequestArray) → List RequestId\n | arr =>\n let opIds := Array.toList $ arr.val.map (Option.map Request.id)\n filterNones opIds\n\ndef growArray {α : Type} (a : Array (Option α)) (n : Nat) : Array (Option α) :=\n --dbg_trace s!\"growing array of size {a.size} by {n}\"\n a.append (Array.mkArray (a.size - n) none)\n\nprivate def RequestArray._insert : RequestArray → Request → Array (Option (Request))\n | arr, req =>\n --dbg_trace \"growing [{arr}] of size {arr.val.size} to {req.id.toNat + 1} for Request {req}\"\n let vals' := growArray arr.val (req.id.toNat + 1)\n let i := req.id.toNat.toUSize\n if h : i.toNat < vals'.size\n then vals'.uset i (some req) h\n -- If we use `i.toNat == vals'.size` then Lean won't unfold the typeclass\n -- instance of BEq.beq (which is Nat.beq) and we can't use Nat.beq_eq.\n -- Maybe ask on Zulip?\n else if h: (Nat.beq i.toNat vals'.size) then\n let hless : i.toNat < vals'.size + 1 := by\n {apply Nat.lt_of_succ_le\n apply Nat.le_of_eq\n rw [Nat.succ_eq_add_one]\n rw [Nat.beq_eq] at h\n rw [h]\n }\n let idfin := Fin.mk i.toNat hless\n vals'.insertAt idfin (some req)\n else unreachable! -- because of growArray before\n\n-- can't be proving these things right now\ntheorem RequestArrayInsertConsistent (arr : RequestArray) (req : Request) :\n valConsistent (arr._insert req) = true := by sorry\n -- unfold RequestArray._insert\n -- simp\n\ndef RequestArray.insertAtPosition : RequestArray → Option (Request) → USize → RequestArray\n | arr, opReq, i =>\n let val' := if h : i.toNat < arr.val.size\n then arr.val.uset i opReq h\n else match opReq with\n | some req => arr._insert req\n | none => arr.val\n -- RequestArrayInsertConsistent arr req\n { val := val', coherent := sorry}\n\n-- Inserst request at the position given by its id.\n-- Will overwrite another request with that same id.\ndef RequestArray.insert : RequestArray → Request → RequestArray\n | arr, req =>\n let i := req.id.toNat.toUSize\n arr.insertAtPosition (some req) i\n\ndef RequestArray.remove : RequestArray → RequestId → RequestArray\n | arr, reqId =>\n match arr.getReq? reqId with\n | none => arr\n | some req =>\n let i := req.id.toNat.toUSize\n arr.insertAtPosition none i\n\nstructure SystemState where\n requests : RequestArray\n removed : List (Request) -- TODO: remove, def. \"active\" to ignore satisfied reads\n scopes : ValidScopes\n satisfied : List SatisfiedRead\n threadTypes : ThreadId → String\n orderConstraints : @OrderConstraints scopes\n removedCoherent : ∀ id : RequestId, id ∈ (removed.map Request.id) → id ∈ reqIds requests\n\ndef SystemState.beq (state₁ state₂ : SystemState)\n -- (samesystem : state₁.system = state₂.system)\n : Bool :=\n state₁.requests == state₂.requests &&\n state₁.removed == state₂.removed &&\n state₁.satisfied == state₂.satisfied &&\n -- this will be expensive!\n state₁.orderConstraints.compare state₂.orderConstraints (reqIds state₁.requests)\n\ninstance : BEq (SystemState) where beq := SystemState.beq\n\ndef SystemState.findMaybeRemoved? (state : SystemState) (rId : RequestId) : Option Request :=\n match state.requests.getReq? rId with\n | some r => some r\n | none => state.removed.find? (·.id == rId)\n\ndef SystemState.oderConstraintsString (state : SystemState)\n(scope : optParam (@Scope state.scopes) state.scopes.systemScope) : String :=\n state.orderConstraints.toString scope $ filterNones $ state.requests.val.toList\n\ndef SystemState.threads : SystemState → List ThreadId\n | s => s.scopes.system_scope\n\ndef SystemState.prettyPrint (state : SystemState) (highlight : optParam (Option $ ThreadId × RequestId) none) : String :=\n let ocString := if state.scopes.scopes.toList.length == 1\n then s!\"constraints: {state.oderConstraintsString}\\n\"\n else String.intercalate \"\\n\" $ state.scopes.scopes.toList.map\n λ scope => s!\"constraints (scope {scope}) : {state.oderConstraintsString (state.scopes.validate scope).get!}\"\n let satisfiedStr := state.satisfied.map\n λ (r₁, r₂) => s!\"{(state.findMaybeRemoved? r₁).get!.toShortString} with {state.requests.printReq r₂}\"\n s!\"requests:\\n{state.requests.toString}\\n\\n\"++\n s!\"{state.requests.prettyPrint state.threads.length state.orderConstraints (highlight := highlight)}\\n\" ++\n s!\"removed: {state.removed.toString}\\n\" ++\n s!\"satisfied: {satisfiedStr}\\n\" ++\n ocString\n\ndef SystemState.toString : SystemState → String\n | state =>\n let ocString := if state.scopes.scopes.toList.length == 1\n then s!\"constraints: {state.oderConstraintsString}\\n\"\n else String.intercalate \"\\n\" $ state.scopes.scopes.toList.map\n λ scope => s!\"constraints (scope {scope}) : {state.oderConstraintsString (state.scopes.validate scope).get!}\"\n let satisfiedStr := state.satisfied.map\n λ (r₁, r₂) => s!\"{(state.findMaybeRemoved? r₁).get!.toShortString} with {state.requests.printReq r₂}\"\n s!\"requests:\\n{state.requests}\\n\" ++\n s!\"removed: {state.removed.toString}\\n\" ++\n s!\"satisfied: {satisfiedStr}\\n\" ++\n ocString\n\ndef SystemState.orderPredecessors (state : SystemState) (scope : @Scope state.scopes)\n (reqId : RequestId) : List RequestId :=\n state.orderConstraints.predecessors scope reqId (reqIds state.requests)\n\ninstance : ToString (SystemState) where toString := SystemState.toString\n\ntheorem emptyCoherent (requests : RequestArray) :\n ∀ id : RequestId, id ∈ [] → id ∈ reqIds requests := by\n intros id h\n contradiction\n\ntheorem empty2Coherent (seen : List RequestId) :\n ∀ id₁ id₂ : RequestId, (id₁,id₂) ∈ [] → id₁ ∈ seen ∧ id₂ ∈ seen := by\n intros\n contradiction\n\ndef SystemState.init (S : ValidScopes) (threadTypes : ThreadId → String): SystemState :=\n { requests := RequestArray.empty, removed := [],\n scopes := S, satisfied := [], orderConstraints := OrderConstraints.empty,\n removedCoherent := emptyCoherent RequestArray.empty, threadTypes\n }\n\ndef SystemState.default := SystemState.init ValidScopes.default (λ _ => \"default\")\ninstance : Inhabited (SystemState) where default := SystemState.default\n\ndef SystemState.seen : SystemState → List RequestId\n | state => state.requests.seen\n\ndef SystemState.idsToReqs : SystemState → List RequestId → List (Request)\n | state, ids => filterNones $ ids.map (λ id => state.requests.getReq? id)\n\ndef SystemState.isSatisfied : SystemState → RequestId → Bool\n | state, rid =>\n !(state.satisfied.filter λ (srd,_) => srd == rid).isEmpty\n\ndef SystemState.reqPropagatedTo : SystemState → RequestId → ThreadId → Bool\n | state, rid, tid => match state.requests.getReq? rid with\n | none => false\n | some req => req.propagatedTo tid\n\ndef SystemState.updateRequest : SystemState → Request → SystemState\n | state, request =>\n let requests' := state.requests.insert request\n SystemState.mk requests' state.removed state.scopes state.satisfied\n state.threadTypes state.orderConstraints sorry\n --{requests := requests', seen := state.seen, removed := state.removed,\n -- scopes := state.scopes, satisfied := state.satisfied,\n -- orderConstraints := state.orderConstraints,\n -- seenCoherent := state.seenCoherent, removedCoherent := state.removedCoherent,\n -- satisfiedCoherent := state.satisfiedCoherent}\ndef SystemState.allRequests (state : SystemState) : List Request := state.removed ++ filterNones state.requests.val.toList\n\nclass Arch where\n (req : ArchReq)\n (orderCondition : ValidScopes → Request → Request → Bool)\n (blockingSemantics : Request → BlockingSemantics)\n (scopeIntersection : (valid : ValidScopes) → Request → Request → @Scope valid := λ v _ _ => v.systemScope)\n (predecessorConstraints : SystemState → RequestId → RequestId → Bool := λ _ _ _ => true)\n (acceptConstraints : SystemState → BasicRequest → ThreadId → Bool := λ _ _ _ => true)\n (acceptEffects : SystemState → RequestId → ThreadId → SystemState := λ st _ _ => st)\n (propagateConstraints : SystemState → RequestId → ThreadId → Bool := λ _ _ _ => true)\n (propagateEffects : SystemState → RequestId → ThreadId → SystemState := λ st _ _ => st)\n (satisfyReadConstraints : SystemState → RequestId → RequestId → Bool := λ _ _ _ => true)\n (satisfyReadEffects : SystemState → RequestId → RequestId → SystemState := λ st _ _ => st)\n\ndef Request.blockingSemantics [inst : Arch] (req : @Request inst.req) : BlockingSemantics := Arch.blockingSemantics req\n\nend Pop\n", "meta": {"author": "goens", "repo": "lost-pop-lean", "sha": "5bfa5515609a3892ed7ba22dbe70bb5dd31d74c5", "save_path": "github-repos/lean/goens-lost-pop-lean", "path": "github-repos/lean/goens-lost-pop-lean/lost-pop-lean-5bfa5515609a3892ed7ba22dbe70bb5dd31d74c5/Pop/States.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.03410042362637635, "lm_q1q2_score": 0.016650670629313344}} {"text": "import tactic.lint\nimport algebra.continued_fractions.computation.approximations\n--set_option pp.all true\n-- set_option profiler true\nlemma another (g : 1000 = 2*500): 1000 = 2*500 ∧ 1000 = 2*500 :=\nbegin\n let h :ℕ :=1,\n exact ⟨rfl, rfl⟩\nend\n#print another\n#lint\n\nlemma foo (p : Prop) : p → p :=\nassume hp : p,\nhave hp2 : p, from hp,\nshow p, from hp\n#print foo\n\nlemma fun_problem (p : Prop) : ¬ (p ↔ ¬ p) :=\nassume hpnp,\nhave hnp : ¬ p, from\n assume hp : p,\n have hnp : ¬ p, from hpnp.mp hp,\n show false, from hnp hp,\nhave hp : p, from\n have unnecessary : ¬ p, from hnp,\n show p, from hpnp.mpr hnp,\nshow false, from hnp hp\n\n\nopen tactic declaration expr\n\nmeta def find_unused_have_macro : expr → tactic (list name)\n| (app a a_1) := (++) <$> find_unused_have_macro a <*> find_unused_have_macro a_1\n| (lam var_name bi var_type body) := find_unused_have_macro body\n| (pi var_name bi var_type body) := find_unused_have_macro body\n| (elet var_name type assignment body) := find_unused_have_macro body\n| (macro md [lam ppnm _ _ bd]) := do\n (++) (if bd.has_zero_var then [] else [ppnm]) <$>\n find_unused_have_macro bd\n| (macro md l) := do ls ← l.mmap find_unused_have_macro, return ls.join\n| _ := return []\n\nmeta def find_unused_let_macro : expr → tactic (list name)\n| (app a a_1) := (++) <$> find_unused_let_macro a <*> find_unused_let_macro a_1\n| (lam var_name bi var_type body) := find_unused_let_macro body\n| (pi var_name bi var_type body) := find_unused_let_macro body\n| (elet var_name type assignment body) := do\n --trace body,\n (++) (if body.has_zero_var then [] else [var_name]) <$>\n find_unused_let_macro body\n\n| (macro md [lam ppnm _ _ bd]) :=find_unused_let_macro bd\n| (macro md l) := do ls ← l.mmap find_unused_let_macro, return ls.join\n| _ := return []\n\nmeta def unused_of_decl : declaration → tactic (list name)\n| (defn a a_1 a_2 bd a_4 a_5) := find_unused_let_macro bd\n| (thm a a_1 a_2 bd) := find_unused_let_macro bd.get\n| _ := return []\n\nrun_cmd\ndo d ← get_decl `generalized_continued_fraction.le_of_succ_succ_nth_continuants_aux_b,\nunused_of_decl d\n\n@[linter] meta def linter.unused_lets : linter :=\n{ test := λ d,\n (do\n --trace d.to_name,\n ns ← unused_of_decl d,\n if ns.length = 0 then return none else return (\", \".intercalate (ns.map to_string))),\n no_errors_found := \"all good\",\n errors_found := \"DECLS HAVE UNNEEDED LETS\",\n is_fast := tt,\n auto_decls := ff }\nlemma tmp : ∃ n, n = 1 :=\nlet a := 1, b:=1 in\nbegin\n set t := 2,\n use a,\nend\n#print tmp\n#lint only unused_lets\n", "meta": {"author": "alexjbest", "repo": "lean-generalisation", "sha": "400060b425574cc751b7df6c5673b9792457e68f", "save_path": "github-repos/lean/alexjbest-lean-generalisation", "path": "github-repos/lean/alexjbest-lean-generalisation/lean-generalisation-400060b425574cc751b7df6c5673b9792457e68f/src/unused_lets.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41111086923216794, "lm_q2_score": 0.04023794665187623, "lm_q1q2_score": 0.01654225722417044}} {"text": "/-\nCopyright (c) 2017 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Leonardo de Moura\n\n! This file was ported from Lean 3 source module data.rbtree.basic\n! leanprover-community/mathlib commit 5cb17dd1617d2dc55eb17777c3dcded3306fadb5\n! Please do not edit these lines, except to modify the commit id\n! if you have ported upstream changes.\n-/\nimport Mathbin.Data.Rbtree.Init\nimport Mathbin.Logic.IsEmpty\nimport Mathbin.Tactic.Interactive\n\nuniverse u\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:330:4: warning: unsupported (TODO): `[tacs] -/\nunsafe def tactic.interactive.blast_disjs : tactic Unit :=\n sorry\n#align tactic.interactive.blast_disjs tactic.interactive.blast_disjs\n\nnamespace Rbnode\n\nvariable {α : Type u}\n\nopen Color Nat\n\ninductive IsNodeOf : Rbnode α → Rbnode α → α → Rbnode α → Prop\n | of_red (l v r) : is_node_of (red_node l v r) l v r\n | of_black (l v r) : is_node_of (black_node l v r) l v r\n#align rbnode.is_node_of Rbnode.IsNodeOf\n\ndef Lift (lt : α → α → Prop) : Option α → Option α → Prop\n | some a, some b => lt a b\n | _, _ => True\n#align rbnode.lift Rbnode.Lift\n\ninductive IsSearchable (lt : α → α → Prop) : Rbnode α → Option α → Option α → Prop\n | leaf_s {lo hi} (hlt : Lift lt lo hi) : is_searchable leaf lo hi\n |\n red_s {l r v lo hi} (hs₁ : is_searchable l lo (some v)) (hs₂ : is_searchable r (some v) hi) :\n is_searchable (red_node l v r) lo hi\n |\n black_s {l r v lo hi} (hs₁ : is_searchable l lo (some v)) (hs₂ : is_searchable r (some v) hi) :\n is_searchable (black_node l v r) lo hi\n#align rbnode.is_searchable Rbnode.IsSearchable\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:330:4: warning: unsupported (TODO): `[tacs] -/\nunsafe def is_searchable_tactic : tactic Unit :=\n sorry\n#align rbnode.is_searchable_tactic rbnode.is_searchable_tactic\n\nopen Rbnode (Mem)\n\nopen IsSearchable\n\nsection IsSearchableLemmas\n\nvariable {lt : α → α → Prop}\n\ntheorem lo_lt_hi {t : Rbnode α} {lt} [IsTrans α lt] :\n ∀ {lo hi}, IsSearchable lt t lo hi → Lift lt lo hi :=\n by\n induction t <;> intro lo hi hs\n case leaf => cases hs; assumption\n all_goals\n cases hs\n have h₁ := t_ih_lchild hs_hs₁\n have h₂ := t_ih_rchild hs_hs₂\n cases lo <;> cases hi <;> simp [lift] at *\n apply trans_of lt h₁ h₂\n#align rbnode.lo_lt_hi Rbnode.lo_lt_hi\n\n/- ./././Mathport/Syntax/Translate/Tactic/Builtin.lean:69:18: unsupported non-interactive tactic rbnode.is_searchable_tactic -/\ntheorem isSearchable_of_isSearchable_of_incomp [IsStrictWeakOrder α lt] {t} :\n ∀ {lo hi hi'} (hc : ¬lt hi' hi ∧ ¬lt hi hi') (hs : IsSearchable lt t lo (some hi)),\n IsSearchable lt t lo (some hi') :=\n by\n classical\n induction t <;> intros <;>\n run_tac\n is_searchable_tactic\n · cases lo <;> simp_all [lift]\n apply lt_of_lt_of_incomp\n assumption\n exact ⟨hc.2, hc.1⟩\n all_goals apply t_ih_rchild hc hs_hs₂\n#align rbnode.is_searchable_of_is_searchable_of_incomp Rbnode.isSearchable_of_isSearchable_of_incomp\n\n/- ./././Mathport/Syntax/Translate/Tactic/Builtin.lean:69:18: unsupported non-interactive tactic rbnode.is_searchable_tactic -/\ntheorem isSearchable_of_incomp_of_isSearchable [IsStrictWeakOrder α lt] {t} :\n ∀ {lo lo' hi} (hc : ¬lt lo' lo ∧ ¬lt lo lo') (hs : IsSearchable lt t (some lo) hi),\n IsSearchable lt t (some lo') hi :=\n by\n classical\n induction t <;> intros <;>\n run_tac\n is_searchable_tactic\n · cases hi <;> simp_all [lift]\n apply lt_of_incomp_of_lt\n assumption\n assumption\n all_goals apply t_ih_lchild hc hs_hs₁\n#align rbnode.is_searchable_of_incomp_of_is_searchable Rbnode.isSearchable_of_incomp_of_isSearchable\n\n/- ./././Mathport/Syntax/Translate/Tactic/Builtin.lean:69:18: unsupported non-interactive tactic rbnode.is_searchable_tactic -/\ntheorem isSearchable_some_low_of_isSearchable_of_lt {t} [IsTrans α lt] :\n ∀ {lo hi lo'} (hlt : lt lo' lo) (hs : IsSearchable lt t (some lo) hi),\n IsSearchable lt t (some lo') hi :=\n by\n induction t <;> intros <;>\n run_tac\n is_searchable_tactic\n · cases hi <;> simp_all [lift]\n apply trans_of lt hlt\n assumption\n all_goals apply t_ih_lchild hlt hs_hs₁\n#align rbnode.is_searchable_some_low_of_is_searchable_of_lt Rbnode.isSearchable_some_low_of_isSearchable_of_lt\n\n/- ./././Mathport/Syntax/Translate/Tactic/Builtin.lean:69:18: unsupported non-interactive tactic rbnode.is_searchable_tactic -/\ntheorem isSearchable_none_low_of_isSearchable_some_low {t} :\n ∀ {y hi} (hlt : IsSearchable lt t (some y) hi), IsSearchable lt t none hi :=\n by\n induction t <;> intros <;>\n run_tac\n is_searchable_tactic\n · simp [lift]\n all_goals apply t_ih_lchild hlt_hs₁\n#align rbnode.is_searchable_none_low_of_is_searchable_some_low Rbnode.isSearchable_none_low_of_isSearchable_some_low\n\n/- ./././Mathport/Syntax/Translate/Tactic/Builtin.lean:69:18: unsupported non-interactive tactic rbnode.is_searchable_tactic -/\ntheorem isSearchable_some_high_of_isSearchable_of_lt {t} [IsTrans α lt] :\n ∀ {lo hi hi'} (hlt : lt hi hi') (hs : IsSearchable lt t lo (some hi)),\n IsSearchable lt t lo (some hi') :=\n by\n induction t <;> intros <;>\n run_tac\n is_searchable_tactic\n · cases lo <;> simp_all [lift]\n apply trans_of lt\n assumption\n assumption\n all_goals apply t_ih_rchild hlt hs_hs₂\n#align rbnode.is_searchable_some_high_of_is_searchable_of_lt Rbnode.isSearchable_some_high_of_isSearchable_of_lt\n\n/- ./././Mathport/Syntax/Translate/Tactic/Builtin.lean:69:18: unsupported non-interactive tactic rbnode.is_searchable_tactic -/\ntheorem isSearchable_none_high_of_isSearchable_some_high {t} :\n ∀ {lo y} (hlt : IsSearchable lt t lo (some y)), IsSearchable lt t lo none :=\n by\n induction t <;> intros <;>\n run_tac\n is_searchable_tactic\n · cases lo <;> simp [lift]\n all_goals apply t_ih_rchild hlt_hs₂\n#align rbnode.is_searchable_none_high_of_is_searchable_some_high Rbnode.isSearchable_none_high_of_isSearchable_some_high\n\ntheorem range [IsStrictWeakOrder α lt] {t : Rbnode α} {x} :\n ∀ {lo hi}, IsSearchable lt t lo hi → Mem lt x t → Lift lt lo (some x) ∧ Lift lt (some x) hi :=\n by\n classical\n induction t\n case leaf => simp [mem]\n all_goals\n -- red_node and black_node are identical\n intro lo hi h₁ h₂\n cases h₁\n simp only [mem] at h₂\n have val_hi : lift lt (some t_val) hi :=\n by\n apply lo_lt_hi\n assumption\n have lo_val : lift lt lo (some t_val) :=\n by\n apply lo_lt_hi\n assumption\n cases_type*or.1\n · have h₃ : lift lt lo (some x) ∧ lift lt (some x) (some t_val) :=\n by\n apply t_ih_lchild\n assumption\n assumption\n cases' h₃ with lo_x x_val\n constructor\n show lift lt lo (some x)\n · assumption\n show lift lt (some x) hi\n · cases' hi with hi <;> simp [lift] at *\n apply trans_of lt x_val val_hi\n · cases h₂\n cases' lo with lo <;> cases' hi with hi <;> simp [lift] at *\n · apply lt_of_incomp_of_lt _ val_hi\n simp [*]\n · apply lt_of_lt_of_incomp lo_val\n simp [*]\n constructor\n · apply lt_of_lt_of_incomp lo_val\n simp [*]\n · apply lt_of_incomp_of_lt _ val_hi\n simp [*]\n · have h₃ : lift lt (some t_val) (some x) ∧ lift lt (some x) hi :=\n by\n apply t_ih_rchild\n assumption\n assumption\n cases' h₃ with val_x x_hi\n cases' lo with lo <;> cases' hi with hi <;> simp [lift] at *\n · assumption\n · apply trans_of lt lo_val val_x\n constructor\n · apply trans_of lt lo_val val_x\n · assumption\n#align rbnode.range Rbnode.range\n\ntheorem lt_of_mem_left [IsStrictWeakOrder α lt] {y : α} {t l r : Rbnode α} :\n ∀ {lo hi}, IsSearchable lt t lo hi → IsNodeOf t l y r → ∀ {x}, Mem lt x l → lt x y :=\n by\n intro _ _ hs hn x hm; cases hn <;> cases hs\n all_goals exact (range hs_hs₁ hm).2\n#align rbnode.lt_of_mem_left Rbnode.lt_of_mem_left\n\ntheorem lt_of_mem_right [IsStrictWeakOrder α lt] {y : α} {t l r : Rbnode α} :\n ∀ {lo hi}, IsSearchable lt t lo hi → IsNodeOf t l y r → ∀ {z}, Mem lt z r → lt y z :=\n by\n intro _ _ hs hn z hm; cases hn <;> cases hs\n all_goals exact (range hs_hs₂ hm).1\n#align rbnode.lt_of_mem_right Rbnode.lt_of_mem_right\n\ntheorem lt_of_mem_left_right [IsStrictWeakOrder α lt] {y : α} {t l r : Rbnode α} :\n ∀ {lo hi},\n IsSearchable lt t lo hi → IsNodeOf t l y r → ∀ {x z}, Mem lt x l → Mem lt z r → lt x z :=\n by\n intro _ _ hs hn x z hm₁ hm₂; cases hn <;> cases hs\n all_goals\n have h₁ := range hs_hs₁ hm₁\n have h₂ := range hs_hs₂ hm₂\n exact trans_of lt h₁.2 h₂.1\n#align rbnode.lt_of_mem_left_right Rbnode.lt_of_mem_left_right\n\nend IsSearchableLemmas\n\ninductive IsRedBlack : Rbnode α → Color → Nat → Prop\n | leaf_rb : is_red_black leaf black 0\n |\n red_rb {v l r n} (rb_l : is_red_black l black n) (rb_r : is_red_black r black n) :\n is_red_black (red_node l v r) red n\n |\n black_rb {v l r n c₁ c₂} (rb_l : is_red_black l c₁ n) (rb_r : is_red_black r c₂ n) :\n is_red_black (black_node l v r) black (succ n)\n#align rbnode.is_red_black Rbnode.IsRedBlack\n\nopen IsRedBlack\n\ntheorem depth_min : ∀ {c n} {t : Rbnode α}, IsRedBlack t c n → n ≤ depth min t :=\n by\n intro c n' t h\n induction h\n case leaf_rb => exact le_refl _\n case red_rb =>\n simp [depth]\n have : min (depth min h_l) (depth min h_r) ≥ h_n := by apply le_min <;> assumption\n apply le_succ_of_le\n assumption\n case black_rb =>\n simp [depth]\n apply succ_le_succ\n apply le_min <;> assumption\n#align rbnode.depth_min Rbnode.depth_min\n\nprivate def upper : Color → Nat → Nat\n | red, n => 2 * n + 1\n | black, n => 2 * n\n#align rbnode.upper rbnode.upper\n\nprivate theorem upper_le : ∀ c n, upper c n ≤ 2 * n + 1\n | red, n => le_refl _\n | black, n => by apply le_succ\n#align rbnode.upper_le rbnode.upper_le\n\ntheorem depth_max' : ∀ {c n} {t : Rbnode α}, IsRedBlack t c n → depth max t ≤ upper c n :=\n by\n intro c n' t h\n induction h\n case leaf_rb => simp [max, depth, upper, Nat.mul_zero]\n case\n red_rb =>\n suffices succ (max (depth max h_l) (depth max h_r)) ≤ 2 * h_n + 1 by simp_all [depth, upper]\n apply succ_le_succ\n apply max_le <;> assumption\n case\n black_rb =>\n have : depth max h_l ≤ 2 * h_n + 1 := le_trans h_ih_rb_l (upper_le _ _)\n have : depth max h_r ≤ 2 * h_n + 1 := le_trans h_ih_rb_r (upper_le _ _)\n suffices new : max (depth max h_l) (depth max h_r) + 1 ≤ 2 * h_n + 2 * 1\n · simp_all [depth, upper, succ_eq_add_one, Nat.left_distrib]\n apply succ_le_succ\n apply max_le <;> assumption\n#align rbnode.depth_max' Rbnode.depth_max'\n\ntheorem depth_max {c n} {t : Rbnode α} (h : IsRedBlack t c n) : depth max t ≤ 2 * n + 1 :=\n le_trans (depth_max' h) (upper_le _ _)\n#align rbnode.depth_max Rbnode.depth_max\n\ntheorem balanced {c n} {t : Rbnode α} (h : IsRedBlack t c n) : depth max t ≤ 2 * depth min t + 1 :=\n by\n have : 2 * depth min t + 1 ≥ 2 * n + 1 :=\n by\n apply succ_le_succ\n apply Nat.mul_le_mul_left\n apply depth_min h\n apply le_trans\n apply depth_max h\n apply this\n#align rbnode.balanced Rbnode.balanced\n\nend Rbnode\n\n", "meta": {"author": "leanprover-community", "repo": "mathlib3port", "sha": "62505aa236c58c8559783b16d33e30df3daa54f4", "save_path": "github-repos/lean/leanprover-community-mathlib3port", "path": "github-repos/lean/leanprover-community-mathlib3port/mathlib3port-62505aa236c58c8559783b16d33e30df3daa54f4/Mathbin/Data/Rbtree/Basic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4339814501625211, "lm_q2_score": 0.03789243056813771, "lm_q1q2_score": 0.016444611968143046}} {"text": "import Lean.Data.HashMap\n\ninductive NEList (α : Type)\n | uno : α → NEList α\n | cons : α → NEList α → NEList α\n\ndef NEList.contains [BEq α] : NEList α → α → Bool\n | uno a, x => a == x\n | cons a as, x => a == x || as.contains x\n\ndef NEList.noDup [BEq α] : NEList α → Bool\n | uno a => true\n | cons a as => ¬as.contains a && as.noDup\n\n@[specialize]\ndef NEList.foldl (f : α → β → α) : (init : α) → NEList β → α\n | a, uno b => f a b\n | a, cons b l => foldl f (f a b) l\n\n@[specialize]\ndef NEList.map (f : α → β) : NEList α → NEList β\n | uno a => uno (f a)\n | cons a as => cons (f a) (map f as)\n\ninductive Literal\n | bool : Bool → Literal\n | int : Int → Literal\n | float : Float → Literal\n | str : String → Literal\n\ninductive BinOp\n | add | mul | eq | ne | lt | le | gt | ge\n\ninductive UnOp\n | not\n\nmutual\n\n inductive Lambda\n | mk : (l : NEList String) → l.noDup → Program → Lambda\n\n inductive Expression\n | lit : Literal → Expression\n | var : String → Expression\n | lam : Lambda → Expression\n | list : List Literal → Expression\n | app : Expression → NEList Expression → Expression\n | unOp : UnOp → Expression → Expression\n | binOp : BinOp → Expression → Expression → Expression\n\n inductive Program\n | skip : Program\n | eval : Expression → Program\n | decl : String → Program → Program\n | seq : Program → Program → Program\n | fork : Expression → Program → Program → Program\n | loop : Expression → Program → Program\n | print : Expression → Program\n deriving Inhabited\n\nend\n\ninductive Value\n | nil : Value\n | lit : Literal → Value\n | list : List Literal → Value\n | lam : Lambda → Value\n deriving Inhabited\n\nabbrev Context := Lean.HashMap String Value\n\ninductive ErrorType\n | name | type | runTime\n\ndef Literal.typeStr : Literal → String\n | bool _ => \"bool\"\n | int _ => \"int\"\n | float _ => \"float\"\n | str _ => \"str\"\n\ndef removeRightmostZeros (s : String) : String :=\n let rec aux (buff res : List Char) : List Char → List Char\n | [] => res.reverse\n | a :: as =>\n if a != '0'\n then aux [] (a :: (buff ++ res)) as\n else aux (a :: buff) res as\n ⟨aux [] [] s.data⟩\n\nprotected def Literal.toString : Literal → String\n | bool b => toString b\n | int i => toString i\n | float f => removeRightmostZeros $ toString f\n | str s => s\n\ndef Lambda.typeStr : Lambda → String\n | mk l .. => (l.foldl (init := \"\") fun acc _ => acc ++ \"_ → \") ++ \"_\"\n\ndef Value.typeStr : Value → String\n | nil => \"nil\"\n | lit l => l.typeStr\n | list _ => \"list\"\n | lam l => l.typeStr\n\ndef Literal.eq : Literal → Literal → Bool\n | bool bₗ, bool bᵣ => bₗ == bᵣ\n | int iₗ, int iᵣ => iₗ == iᵣ\n | float fₗ, float fᵣ => fₗ == fᵣ\n | int iₗ, float fᵣ => (.ofInt iₗ) == fᵣ\n | float fₗ, int iᵣ => fₗ == (.ofInt iᵣ)\n | str sₗ, str sᵣ => sₗ == sᵣ\n | _ , _ => false\n\ndef listLiteralEq : List Literal → List Literal → Bool\n | [], [] => true\n | a :: a' :: as, b :: b' :: bs =>\n a.eq b && listLiteralEq (a' :: as) (b' :: bs)\n | _, _ => false\n\ndef opError (app l r : String) : String :=\n s!\"I can't perform a '{app}' operation between '{l}' and '{r}'\"\n\ndef opError1 (app v : String) : String :=\n s!\"I can't perform a '{app}' operation on '{v}'\"\n\ndef Value.not : Value → Except String Value\n | lit $ .bool b => return lit $ .bool !b\n | v => throw $ opError1 \"!\" v.typeStr\n\ndef Value.add : Value → Value → Except String Value\n | lit $ .bool bₗ, lit $ .bool bᵣ => return lit $ .bool $ bₗ || bᵣ\n | lit $ .int iₗ, lit $ .int iᵣ => return lit $ .int $ iₗ + iᵣ\n | lit $ .float fₗ, lit $ .float fᵣ => return lit $ .float $ fₗ + fᵣ\n | lit $ .int iₗ, lit $ .float fᵣ => return lit $ .float $ (.ofInt iₗ) + fᵣ\n | lit $ .float fₗ, lit $ .int iᵣ => return lit $ .float $ fₗ + (.ofInt iᵣ)\n | lit $ .str sₗ, lit $ .str sᵣ => return lit $ .str $ sₗ ++ sᵣ\n | list lₗ, list lᵣ => return list $ lₗ ++ lᵣ\n | list l, lit r => return list $ l.concat r\n | l, r => throw $ opError \"+\" l.typeStr r.typeStr\n\ndef Value.mul : Value → Value → Except String Value\n | lit $ .bool bₗ, lit $ .bool bᵣ => return .lit $ .bool $ bₗ && bᵣ\n | lit $ .int iₗ, lit $ .int iᵣ => return .lit $ .int $ iₗ * iᵣ\n | lit $ .float fₗ, lit $ .float fᵣ => return .lit $ .float $ fₗ * fᵣ\n | lit $ .int iₗ, lit $ .float fᵣ => return .lit $ .float $ (.ofInt iₗ) * fᵣ\n | lit $ .float fₗ, lit $ .int iᵣ => return .lit $ .float $ fₗ * (.ofInt iᵣ)\n | l, r => throw $ opError \"*\" l.typeStr r.typeStr\n\ndef Bool.toNat : Bool → Nat\n | false => 0\n | true => 1\n\ndef Value.lt : Value → Value → Except String Value\n | lit $ .bool bₗ, lit $ .bool bᵣ => return lit $ .bool $ bₗ.toNat < bᵣ.toNat\n | lit $ .int iₗ, lit $ .int iᵣ => return lit $ .bool $ iₗ < iᵣ\n | lit $ .float fₗ, lit $ .float fᵣ => return lit $ .bool $ fₗ < fᵣ\n | lit $ .int iₗ, lit $ .float fᵣ => return lit $ .bool $ (.ofInt iₗ) < fᵣ\n | lit $ .float fₗ, lit $ .int iᵣ => return lit $ .bool $ fₗ < (.ofInt iᵣ)\n | lit $ .str sₗ, lit $ .str sᵣ => return lit $ .bool $ sₗ < sᵣ\n | list lₗ, list lᵣ => return lit $ .bool $ lₗ.length < lᵣ.length\n | l, r => throw $ opError \"<\" l.typeStr r.typeStr\n\ndef Value.le : Value → Value → Except String Value\n | lit $ .bool bₗ, lit $ .bool bᵣ => return lit $ .bool $ bₗ.toNat ≤ bᵣ.toNat\n | lit $ .int iₗ, lit $ .int iᵣ => return lit $ .bool $ iₗ ≤ iᵣ\n | lit $ .float fₗ, lit $ .float fᵣ => return lit $ .bool $ fₗ ≤ fᵣ\n | lit $ .int iₗ, lit $ .float fᵣ => return lit $ .bool $ (.ofInt iₗ) ≤ fᵣ\n | lit $ .float fₗ, lit $ .int iᵣ => return lit $ .bool $ fₗ ≤ (.ofInt iᵣ)\n | lit $ .str sₗ, lit $ .str sᵣ => return lit $ .bool $ sₗ < sᵣ || sₗ == sᵣ\n | list lₗ, list lᵣ => return lit $ .bool $ lₗ.length ≤ lᵣ.length\n | l, r => throw $ opError \"<=\" l.typeStr r.typeStr\n\ndef Value.gt : Value → Value → Except String Value\n | lit $ .bool bₗ, lit $ .bool bᵣ => return lit $ .bool $ bₗ.toNat > bᵣ.toNat\n | lit $ .int iₗ, lit $ .int iᵣ => return lit $ .bool $ iₗ > iᵣ\n | lit $ .float fₗ, lit $ .float fᵣ => return lit $ .bool $ fₗ > fᵣ\n | lit $ .int iₗ, lit $ .float fᵣ => return lit $ .bool $ (.ofInt iₗ) > fᵣ\n | lit $ .float fₗ, lit $ .int iᵣ => return lit $ .bool $ fₗ > (.ofInt iᵣ)\n | lit $ .str sₗ, lit $ .str sᵣ => return lit $ .bool $ sₗ > sᵣ\n | list lₗ, list lᵣ => return lit $ .bool $ lₗ.length > lᵣ.length\n | l, r => throw $ opError \">\" l.typeStr r.typeStr\n\ndef Value.ge : Value → Value → Except String Value\n | lit $ .bool bₗ, lit $ .bool bᵣ => return lit $ .bool $ bₗ.toNat ≥ bᵣ.toNat\n | lit $ .int iₗ, lit $ .int iᵣ => return lit $ .bool $ iₗ ≥ iᵣ\n | lit $ .float fₗ, lit $ .float fᵣ => return lit $ .bool $ fₗ ≥ fᵣ\n | lit $ .int iₗ, lit $ .float fᵣ => return lit $ .bool $ (.ofInt iₗ) ≥ fᵣ\n | lit $ .float fₗ, lit $ .int iᵣ => return lit $ .bool $ fₗ ≥ (.ofInt iᵣ)\n | lit $ .str sₗ, lit $ .str sᵣ => return lit $ .bool $ sₗ > sᵣ || sₗ == sᵣ\n | list lₗ, list lᵣ => return lit $ .bool $ lₗ.length ≥ lᵣ.length\n | l, r => throw $ opError \">=\" l.typeStr r.typeStr\n\ndef Value.eq : Value → Value → Except String Value\n | nil, nil => return lit $ .bool true\n | lit lₗ, lit lᵣ => return lit $ .bool $ lₗ.eq lᵣ\n | list lₗ, list lᵣ => return lit $ .bool (listLiteralEq lₗ lᵣ)\n | lam .. , lam .. => throw \"I can't compare functions\"\n | _, _ => return lit $ .bool false\n\ndef Value.ne : Value → Value → Except String Value\n | nil, nil => return lit $ .bool false\n | lit lₗ, lit lᵣ => return lit $ .bool $ !(lₗ.eq lᵣ)\n | list lₗ, list lᵣ => return lit $ .bool !(listLiteralEq lₗ lᵣ)\n | lam .., lam .. => throw \"I can't compare functions\"\n | _, _ => return lit $ .bool true\n\ndef Value.unOp : Value → UnOp → Except String Value\n | v, .not => v.not\n\ndef Value.binOp : Value → Value → BinOp → Except String Value\n | l, r, .add => l.add r\n | l, r, .mul => l.mul r\n | l, r, .lt => l.lt r\n | l, r, .le => l.le r\n | l, r, .gt => l.gt r\n | l, r, .ge => l.ge r\n | l, r, .eq => l.eq r\n | l, r, .ne => l.ne r\n\ndef NEList.unfoldStrings (l : NEList String) : String :=\n l.foldl (init := \"\") $ fun acc a => acc ++ s!\" {a}\" |>.trimLeft\n\nmutual\n\n partial def unfoldExpressions (es : NEList Expression) : String :=\n (es.map exprToString).unfoldStrings\n\n partial def exprToString : Expression → String\n | .var n => n\n | .lit l => l.toString\n | .list l => toString $ l.map Literal.toString\n | .lam _ => \"«function»\"\n | .app e es => s!\"({exprToString e} {unfoldExpressions es})\"\n | .unOp .not e => s!\"!{exprToString e}\"\n | .binOp .add l r => s!\"({exprToString l} + {exprToString r})\"\n | .binOp .mul l r => s!\"({exprToString l} * {exprToString r})\"\n | .binOp .eq l r => s!\"({exprToString l} = {exprToString r})\"\n | .binOp .ne l r => s!\"({exprToString l} != {exprToString r})\"\n | .binOp .lt l r => s!\"({exprToString l} < {exprToString r})\"\n | .binOp .le l r => s!\"({exprToString l} <= {exprToString r})\"\n | .binOp .gt l r => s!\"({exprToString l} > {exprToString r})\"\n | .binOp .ge l r => s!\"({exprToString l} >= {exprToString r})\"\n\nend\n\ninstance : ToString Expression := ⟨exprToString⟩\n\ndef valToString : Value → String\n | .nil => \"«nil»\"\n | .lit l => l.toString\n | .list l => toString $ l.map Literal.toString\n | .lam _ => \"«function»\"\n\ninstance : ToString Value := ⟨valToString⟩\n\ndef consume (p : Program) :\n NEList String → NEList Expression →\n Option ((Option (NEList String)) × Program)\n | .cons n ns, .cons e es => consume (.seq (.decl n (.eval e)) p) ns es\n | .cons n ns, .uno e => some (some ns, .seq (.decl n (.eval e)) p)\n | .uno n, .uno e => some (none, .seq (.decl n (.eval e)) p)\n | .uno _, .cons .. => none\n\ntheorem noDupOfConsumeNoDup\n (h : ns.noDup) (h' : consume p' ns es = some (some l, p)) :\n l.noDup = true := by\n induction ns generalizing p' es with\n | uno _ => cases es <;> cases h'\n | cons _ _ hi =>\n simp [NEList.noDup] at h\n cases es with\n | uno _ => simp [consume] at h'; simp only [h.2, ← h'.1]\n | cons _ _ => exact hi h.2 h'\n\ninductive Continuation\n | exit : Continuation\n | seq : Program → Continuation → Continuation\n | decl : String → Continuation → Continuation\n | fork : Expression → Program → Program → Continuation → Continuation\n | loop : Expression → Program → Continuation → Continuation\n | unOp : UnOp → Expression → Continuation → Continuation\n | binOp₁ : BinOp → Expression → Continuation → Continuation\n | binOp₂ : BinOp → Value → Continuation → Continuation\n | app : Expression → NEList Expression → Continuation → Continuation\n | block : Context → Continuation → Continuation\n | print : Continuation → Continuation\n\ninductive State\n | ret : Value → Context → Continuation → State\n | prog : Program → Context → Continuation → State\n | expr : Expression → Context → Continuation → State\n | error : ErrorType → Context → String → State\n | done : Value → Context → State\n\ndef cantEvalAsBool (e : Expression) (v : Value) : String :=\n s!\"I can't evaluate '{e}' as a 'bool' because it reduces to '{v}', of \" ++\n s!\"type '{v.typeStr}'\"\n\ndef notFound (n : String) : String :=\n s!\"I can't find the definition of '{n}'\"\n\ndef notAFunction (e : Expression) (v : Value) : String :=\n s!\"I can't apply arguments to '{e}' because it evaluates to '{v}', of \" ++\n s!\"type '{v.typeStr}'\"\n\ndef wrongNParameters (e : Expression) (allowed provided : Nat) : String :=\n s!\"I can't apply {provided} arguments to '{e}' because the maximum \" ++\n s!\"allowed is {allowed}\"\n\ndef NEList.length : NEList α → Nat\n | uno _ => 1\n | cons _ l => 1 + l.length\n\ndef State.step : State → State\n | prog .skip c k => ret .nil c k\n | prog (.eval e) c k => expr e c k\n | prog (.seq p₁ p₂) c k => prog p₁ c (.seq p₂ k)\n | prog (.decl n p) c k => prog p c $ .block c (.decl n k)\n | prog (.fork e pT pF) c k => expr e c (.fork e pT pF k)\n | prog (.loop e p) c k => expr e c (.loop e p k)\n | prog (.print e) c k => expr e c (.print k)\n\n | expr (.lit l) c k => ret (.lit l) c k\n | expr (.list l) c k => ret (.list l) c k\n | expr (.var n) c k => match c[n] with\n | none => error .name c $ notFound n\n | some v => ret v c k\n | expr (.lam l) c k => ret (.lam l) c k\n | expr (.app e es) c k => expr e c (.app e es k)\n | expr (.unOp o e) c k => expr e c (.unOp o e k)\n | expr (.binOp o e₁ e₂) c k => expr e₁ c (.binOp₁ o e₂ k)\n\n | ret v c .exit => done v c\n | ret v c (.print k) => dbg_trace v; ret .nil c k\n | ret _ c (.seq p k) => prog p c k\n\n | ret v _ (.block c k) => ret v c k\n\n | ret v c (.app e es k) => match v with\n | .lam $ .mk ns h p => match h' : consume p ns es with\n | some (some l, p) =>\n ret (.lam $ .mk l (noDupOfConsumeNoDup h h') p) c k\n | some (none, p) => prog p c (.block c k)\n | none => error .runTime c $ wrongNParameters e ns.length es.length\n | v => error .type c $ notAFunction e v\n\n | ret (.lit $ .bool true) c (.fork _ pT _ k) => prog pT c k\n | ret (.lit $ .bool false) c (.fork _ _ pF k) => prog pF c k\n | ret v c (.fork e ..) => error .type c $ cantEvalAsBool e v\n\n | ret (.lit $ .bool true) c (.loop e p k) => prog (.seq p (.loop e p)) c k\n | ret (.lit $ .bool false) c (.loop _ _ k) => ret .nil c k\n | ret v c (.loop e ..) => error .type c $ cantEvalAsBool e v\n\n | ret v c (.decl n k) => ret .nil (c.insert n v) k\n\n | ret v c (.unOp o e k) => match v.unOp o with\n | .error m => error .type c m\n | .ok v => ret v c k\n | ret v₁ c (.binOp₁ o e₂ k) => expr e₂ c (.binOp₂ o v₁ k)\n | ret v₂ c (.binOp₂ o v₁ k) => match v₁.binOp v₂ o with\n | .error m => error .type c m\n | .ok v => ret v c k\n\n | s@(error ..) => s\n | s@(done ..) => s\n\ndef State.isProg : State → Bool\n | prog .. => true\n | _ => false\n\ndef State.isEnd : State → Bool\n | done .. => true\n | error .. => true\n | _ => false\n\ndef State.stepN : State → Nat → State\n | s, 0 => s\n | s, n + 1 => s.step.stepN n\n\nnotation s \"^\" \"[\" n \"]\" => State.stepN s n\n\ntheorem State.retProgression :\n ∃ n, (ret v c k^[n]).isEnd ∨ (ret v c k^[n]).isProg := by\n induction k generalizing v c with\n | app e es k hi =>\n cases v with\n | lam lm =>\n cases lm with\n | mk ns h p =>\n exists 1\n simp [stepN, step] -- doesn't seem to use `\n split\n next l p' h' => simp!; sorry\n next => simp!\n next => simp!\n | _ => exact ⟨1, by simp [stepN, step, isEnd]⟩\n | _ => sorry\n\n#check @State.step.match_2.eq_1\n#check @State.step.match_2.eq_2\n#check @State.step.match_2.eq_3\n#check @State.step.match_2.splitter\n", "meta": {"author": "leanprover", "repo": "lean4", "sha": "742d053a97bdd109a41a921facd1cd6a55e89bc7", "save_path": "github-repos/lean/leanprover-lean4", "path": "github-repos/lean/leanprover-lean4/lean4-742d053a97bdd109a41a921facd1cd6a55e89bc7/tests/lean/run/arthur2.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44552953503957277, "lm_q2_score": 0.03676946528395655, "lm_q1q2_score": 0.016381882771614873}} {"text": "#exit\n\nimport Structure.Generic.Axioms\n\nopen GeneralizedRelation\n\n\n\nset_option autoBoundImplicitLocal false\n\nuniverses u v w\n\n\n\n@[reducible] def mapOperation {α : Sort u} {β : Sort v} (op : α → α → β) {ω : Sort w} (m : ω → α) :\n ω → ω → β :=\nλ a b => op (m a) (m b)\n\n\n\nnamespace GeneralizedProperty\n\n variable {α : Sort u} {V : Universe} (P : GeneralizedProperty α V)\n {ω : Sort w} (m : ω → α)\n\n instance mapInst [h : HasInst P] : HasInst (P ∘ m) := ⟨λ a => h.inst (m a)⟩\n\nend GeneralizedProperty\n\n\n\nnamespace GeneralizedRelation\n\n variable {α : Sort u} {V : Universe} (R : GeneralizedRelation α V)\n\n section Mapping\n\n variable {ω : Sort w} (m : ω → α)\n\n instance mapRefl [h : HasRefl R] : HasRefl (mapOperation R m) := ⟨λ a => h.refl (m a)⟩\n\n variable [HasInternalFunctors V]\n\n instance mapSymm [h : HasSymm R] : HasSymm (mapOperation R m) := ⟨h.symm⟩\n instance mapTrans [h : HasTrans R] : HasTrans (mapOperation R m) := ⟨h.trans⟩\n\n instance mapPreorder [IsPreorder R] : IsPreorder (mapOperation R m) := ⟨⟩\n instance mapEquivalence [IsEquivalence R] : IsEquivalence (mapOperation R m) := ⟨⟩\n\n end Mapping\n\n section Identity\n\n @[simp] theorem mapRefl.id [h : HasRefl R] : mapRefl R id = h := match h with | ⟨_⟩ => rfl\n\n variable [HasInternalFunctors V]\n\n @[simp] theorem mapSymm.id [h : HasSymm R] : mapSymm R id = h := match h with | ⟨_⟩ => rfl\n @[simp] theorem mapTrans.id [h : HasTrans R] : mapTrans R id = h := match h with | ⟨_⟩ => rfl\n\n @[simp] theorem mapPreorder.id [h : IsPreorder R] : mapPreorder R id = h := match h with | { refl := _, trans := _ } => rfl\n @[simp] theorem mapEquivalence.id [h : IsEquivalence R] : mapEquivalence R id = h := match h with | { refl := _, symm := _, trans := _ } => rfl\n\n end Identity\n\nend GeneralizedRelation\n\n\n\nsection Morphisms\n\n variable {α : Sort u} {V : Universe} [HasInternalFunctors V] [HasInstanceArrows V]\n (R : GeneralizedRelation α V)\n {ω : Sort w} (m : ω → α)\n\n instance mapComposition [HasTrans R] [h : IsCompositionRelation R] :\n IsCompositionRelation (mapOperation R m) :=\n { assocLR := h.assocLR,\n assocRL := h.assocRL }\n\n instance mapMorphisms [IsPreorder R] [h : IsMorphismRelation R] :\n IsMorphismRelation (mapOperation R m) :=\n { leftId := h.leftId,\n rightId := h.rightId }\n\n instance mapIsomorphisms [IsEquivalence R] [h : IsIsomorphismRelation R] :\n IsIsomorphismRelation (mapOperation R m) :=\n { leftInv := h.leftInv,\n rightInv := h.rightInv,\n invInv := h.invInv,\n compInv := h.compInv,\n idInv := λ a => h.idInv (m a) }\n\nend Morphisms\n\n\n\nsection Functors\n\n variable {α : Sort u} {V W : Universe} [HasInstanceArrows W] [HasExternalFunctors V W]\n (R : GeneralizedRelation α V) (S : GeneralizedRelation α W)\n (F : BaseFunctor R S)\n {ω : Sort w} (m : ω → α)\n\n instance mapReflFunctor [HasRefl R] [HasRefl S] [h : IsReflFunctor R S F] :\n IsReflFunctor (mapOperation R m) (mapOperation S m) F :=\n ⟨λ a => h.respectsRefl (m a)⟩\n\n variable [HasInternalFunctors V] [HasInternalFunctors W]\n\n instance mapSymmFunctor [HasSymm R] [HasSymm S] [h : IsSymmFunctor R S F] :\n IsSymmFunctor (mapOperation R m) (mapOperation S m) F :=\n ⟨h.respectsSymm⟩\n\n instance mapTransFunctor [HasTrans R] [HasTrans S] [h : IsTransFunctor R S F] :\n IsTransFunctor (mapOperation R m) (mapOperation S m) F :=\n ⟨h.respectsTrans⟩\n\n instance mapPreorderFunctor [IsPreorder R] [IsPreorder S] [IsPreorderFunctor R S F] :\n IsPreorderFunctor (mapOperation R m) (mapOperation S m) F := ⟨⟩\n instance mapEquivalenceFunctor [IsEquivalence R] [IsEquivalence S] [IsEquivalenceFunctor R S F] :\n IsEquivalenceFunctor (mapOperation R m) (mapOperation S m) F := ⟨⟩\n\nend Functors\n\n\n\nsection NaturalTransformations\n\n variable {α : Sort u} {β : Sort v} {V W : Universe} [HasInternalFunctors W] [HasInstanceEquivalences W] [HasExternalFunctors V W]\n (R : GeneralizedRelation α V) (S : GeneralizedRelation β W) [h : HasTrans S]\n {mF mG : α → β} (F : ∀ {a b}, R a b ⟶' S (mF a) (mF b)) (G : ∀ {a b}, R a b ⟶' S (mG a) (mG b))\n (n : ∀ a, S (mF a) (mG a))\n {ω : Sort w} (m : ω → α)\n \n instance mapNaturality [h : IsNatural R S F G n] :\n IsNatural (mapOperation R m) S F G (λ a => n (m a)) :=\n ⟨h.nat⟩\n\nend NaturalTransformations\n", "meta": {"author": "SReichelt", "repo": "lean4-experiments", "sha": "ff55357a01a34a91bf670d712637480089085ee4", "save_path": "github-repos/lean/SReichelt-lean4-experiments", "path": "github-repos/lean/SReichelt-lean4-experiments/lean4-experiments-ff55357a01a34a91bf670d712637480089085ee4/Structure/Generic/Mapped.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44552954976388504, "lm_q2_score": 0.036769461985447595, "lm_q1q2_score": 0.016381881843436752}} {"text": "import morphisms.isomorphism\nimport algebraic_geometry.pullback_carrier\n\nopen opposite category_theory category_theory.limits topological_space\n\nnoncomputable theory\n\nnamespace algebraic_geometry\n\nlemma injective_of_surjective_diagonal {X Y : Scheme} (f : X ⟶ Y)\n (h : function.surjective (pullback.diagonal f).1.base) : function.injective f.1.base :=\nbegin\n intros x y e,\n let T : pullback.triplet f f := ⟨x, y, _, e, rfl⟩,\n obtain ⟨z, hz, hz'⟩ := T.exists_preimage,\n obtain ⟨z', rfl⟩ := h z,\n simp only [← Scheme.comp_val_base_apply, pullback.diagonal_fst, pullback.diagonal_snd] at hz hz',\n exact hz.symm.trans hz'\nend\n\nlemma surjective_diagonal_of_universally_injective {X Y : Scheme} (f : X ⟶ Y)\n (h : function.surjective (pullback.diagonal f).1.base) : function.injective f.1.base :=\nbegin\n intros x y e,\n let T : pullback.triplet f f := ⟨x, y, _, e, rfl⟩,\n obtain ⟨z, hz, hz'⟩ := T.exists_preimage,\n obtain ⟨z', rfl⟩ := h z,\n simp only [← Scheme.comp_val_base_apply, pullback.diagonal_fst, pullback.diagonal_snd] at hz hz',\n exact hz.symm.trans hz'\nend\n\nlemma injective_of_mono {X Y : Scheme} (f : X ⟶ Y) [mono f] : \n function.injective f.1.base :=\nbegin\n apply injective_of_surjective_diagonal,\n exact (as_iso $ (Scheme.forget_to_Top ⋙ forget Top).map\n (pullback.diagonal f)).to_equiv.surjective,\nend\n\n-- move me \nlemma mono_eq_diagonal : \n @mono Scheme _ = morphism_property.diagonal (@is_iso Scheme _) :=\nbegin\n ext X Y f,\n split,\n { introI _, show is_iso _, apply_instance },\n { rintro (H : is_iso _),\n resetI,\n haveI : is_iso (pullback.fst : pullback f f ⟶ X),\n { rw (is_iso.inv_eq_of_hom_inv_id (pullback.diagonal_fst f)).symm, apply_instance },\n exact is_kernel_pair.mono_of_is_iso_fst (is_pullback.of_has_pullback f f) }\nend\n\nlemma mono_is_local_at_target : \n property_is_local_at_target (@mono _ _) :=\nbegin\n rw mono_eq_diagonal,\n exact is_iso_is_local_at_target.diagonal\nend\n\nend algebraic_geometry", "meta": {"author": "erdOne", "repo": "lean-AG-morphisms", "sha": "bfb65e7d5c17f333abd7b1806717f12cd29427fd", "save_path": "github-repos/lean/erdOne-lean-AG-morphisms", "path": "github-repos/lean/erdOne-lean-AG-morphisms/lean-AG-morphisms-bfb65e7d5c17f333abd7b1806717f12cd29427fd/src/morphisms/monomorphism.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41869690935568665, "lm_q2_score": 0.039048289091790075, "lm_q1q2_score": 0.016349397958359876}} {"text": "macro \"foo!\" x:term:max : term => `($x - 1)\n\ntheorem ex1 : foo! 10 = 9 := rfl\n\nmacro (priority := high) \"foo! \" x:term:max : term => `($x + 1)\n\ntheorem ex2 : foo! 10 = 11 := rfl\n\nmacro (priority := low) \"foo! \" x:term:max : term => `($x * 2)\n\ntheorem ex3 : foo! 10 = 11 := rfl\n\nmacro (priority := high+1) \"foo! \" x:term:max : term => `($x * 2)\n\ntheorem ex4 : foo! 10 = 20 := rfl\n\nmacro (priority := high+4-2) \"foo! \" x:term:max : term => `($x * 3)\n\ntheorem ex5 : foo! 10 = 30 := rfl\n", "meta": {"author": "leanprover", "repo": "lean4", "sha": "742d053a97bdd109a41a921facd1cd6a55e89bc7", "save_path": "github-repos/lean/leanprover-lean4", "path": "github-repos/lean/leanprover-lean4/lean4-742d053a97bdd109a41a921facd1cd6a55e89bc7/tests/lean/run/prioDSL.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41869690935568665, "lm_q2_score": 0.039048288812218064, "lm_q1q2_score": 0.01634939784130394}} {"text": "example : n.succ = 1 → n = 0 := by\n intros h; injection h\n\nexample (h : n.succ = 1) : n = 0 := by\n injection h\n\nopaque T : Type\nopaque T.Pred : T → T → Prop\n\nexample {ρ} (hρ : ρ.Pred σ) : T.Pred ρ ρ := sorry\n", "meta": {"author": "leanprover", "repo": "lean4", "sha": "742d053a97bdd109a41a921facd1cd6a55e89bc7", "save_path": "github-repos/lean/leanprover-lean4", "path": "github-repos/lean/leanprover-lean4/lean4-742d053a97bdd109a41a921facd1cd6a55e89bc7/tests/lean/run/autoboundIssues.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.33807712415000585, "lm_q2_score": 0.048136770604560626, "lm_q1q2_score": 0.016273940971858396}} {"text": "/-\nCopyright (c) 2020 Markus Himmel. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Markus Himmel\n-/\n\nimport category_theory.category\nimport pseudoelements\nimport tactic.combinators\nimport tactic.chase_tactic\n\nopen category_theory\nopen category_theory.abelian\nopen category_theory.abelian.pseudoelements\nopen tactic\n\nnamespace tactic.chase\n\nsection lemmas\nuniverses v u\nvariables {C : Type u} [𝒞 : category.{v} C] [abelian.{v} C]\ninclude 𝒞\n\nlocal attribute [instance] object_to_sort\nlocal attribute [instance] hom_to_fun\n\nlemma pseudo_congr {X Y : C} {f g : X ⟶ Y} (h : f = g) (x : X) : f x = g x :=\nby rw h\n\nend lemmas\n\nmeta def try_apply_comm_lemma_at_aux (l : commutativity_lemma) :\n ℕ → diagram_term → option (diagram_term)\n| 0 ⟨ms, elem⟩ :=\n match list.is_prefix_of l.lhs ms with\n | ff := none\n | tt := some ⟨list.append l.rhs (list.drop l.lhs.length ms), elem⟩\n end\n| (n + 1) ⟨[], e⟩ := none\n| (n + 1) ⟨t::ts, e⟩ :=\n match try_apply_comm_lemma_at_aux n ⟨ts, e⟩ with\n | none := none\n | some ⟨nt, ne⟩ := some ⟨t::nt, ne⟩\n end\n\nmeta def try_apply_element_lemma_at_aux (l : element_lemma) :\n ℕ → diagram_term → option (diagram_term)\n| 0 ⟨ms, elem⟩ := if l.lhs = ⟨ms, elem⟩ then some l.rhs else none\n| (n + 1) ⟨[], e⟩ := none\n| (n + 1) ⟨t :: ts, e⟩ :=\n match try_apply_element_lemma_at_aux n ⟨ts, e⟩ with\n | none := none\n | some ⟨nt, ne⟩ := some ⟨t::nt, ne⟩\n end\n\nmeta inductive lemma_app\n| comm : commutativity_lemma → ℕ → diagram_term → lemma_app\n| elem : element_lemma → ℕ → diagram_term → lemma_app\n\nmeta instance format_lemma_app : has_to_format lemma_app :=\n{ to_format := λ a,\n match a with\n | lemma_app.comm a b c := format!\"comm: lemma ({a}) at {b} gives {c}\"\n | lemma_app.elem a b c := format!\"elem: lemma ({a}) at {b} gives {c}\"\n end }\n\nmeta def next_term : lemma_app → diagram_term\n| (lemma_app.comm _ _ t) := t\n| (lemma_app.elem _ _ t) := t\n\nmeta def apply_comm_lemma_at_aux : ℕ → diagram_term → tactic (option expr)\n| 0 t := some <$> (mk_eq_refl $ as_expr t)\n| 1 ⟨t::[], e⟩ := some <$> (mk_eq_refl $ as_expr ⟨[t], e⟩)\n| (n + 1) ⟨[], _⟩ := return none\n| (n + 1) ⟨t::[], e⟩ := return none\n| (n + 1) ⟨t::(u::ts), e⟩ :=\ndo\n some x ← i_to_expr ``(%%(u.ex) ≫ %%(t.ex)) >>= as_morphism,\n lhs ← mk_app `category_theory.abelian.pseudoelements.comp_apply [u.ex, t.ex, as_expr ⟨ts, e⟩] >>= mk_eq_symm,\n some rhs ← apply_comm_lemma_at_aux n ⟨x::ts, e⟩,\n some <$> mk_eq_trans lhs rhs\n\nmeta def apply_comm_lemma_at (l : commutativity_lemma) :\n ℕ → diagram_term → diagram_term → tactic (option expr)\n| 0 ⟨ms, elem⟩ goal :=\ndo\n some one ← apply_comm_lemma_at_aux (l.lhs.length - 1) ⟨ms, elem⟩,\n let inner := as_expr ⟨list.drop (l.lhs.length) ms, elem⟩,\n two ← mk_app `tactic.chase.pseudo_congr [l.ex, inner],\n some three ← apply_comm_lemma_at_aux (l.rhs.length - 1) goal,\n three' ← mk_eq_symm three,\n onetwo ← mk_eq_trans one two,\n some <$> mk_eq_trans onetwo three'\n| (n + 1) ⟨[], e⟩ goal := none\n| (n + 1) fr ⟨[], e⟩ := none\n| (n + 1) ⟨t::ts, e⟩ ⟨u::us, f⟩ :=\ndo\n some inner ← apply_comm_lemma_at n ⟨ts, e⟩ ⟨us, f⟩,\n some <$> mk_app `congr_arg [t.app, inner]\n\nmeta def apply_elem_lemma_at (l : element_lemma) :\n ℕ → diagram_term → tactic (option expr)\n| 0 ⟨ms, elem⟩ := return $ some l.ex\n| (n + 1) ⟨[], _⟩ := none\n| (n + 1) ⟨t::ts, e⟩ :=\ndo\n some inner ← apply_elem_lemma_at n ⟨ts, e⟩,\n some <$> mk_app `congr_arg [t.app, inner]\n\nmeta def build_proof (t : diagram_term) : lemma_app → tactic expr\n| (lemma_app.comm x y z) :=\ndo\n some u ← apply_comm_lemma_at x y t z,\n return u\n| (lemma_app.elem x y z) :=\ndo\n some u ← apply_elem_lemma_at x y t,\n return u\n\nmeta def try_apply_comm_lemma_at (l : commutativity_lemma) (n : ℕ) (t : diagram_term) :\n option (lemma_app) :=\nmatch try_apply_comm_lemma_at_aux l n t with\n| none := none\n| some t := lemma_app.comm l n t\nend\n\nmeta def try_apply_elem_lemma_at (l : element_lemma) (n : ℕ) (t : diagram_term) :\n option lemma_app :=\nmatch try_apply_element_lemma_at_aux l n t with\n| none := none\n| some t := lemma_app.elem l n t\nend\n\nmeta def iota : ℕ → list ℕ\n| 0 := [0]\n| (n + 1) := (n + 1) :: iota n\n\nmeta def try_apply_comm_lemma (l : commutativity_lemma) (t : diagram_term) : list lemma_app :=\nlist.filter_map (λ n, try_apply_comm_lemma_at l n t) $ iota t.ms.length\n\nmeta def try_apply_elem_lemma (l : element_lemma) (t : diagram_term) : list lemma_app :=\nlist.filter_map (λ n, try_apply_elem_lemma_at l n t) $ iota t.ms.length\n\nmeta def try_all_comm (t : diagram_term) : chase_tactic (list lemma_app) :=\ndo\n l ← get,\n return $ list.join $ list.map (λ l, try_apply_comm_lemma l t) l.comm_lemmas\n\nmeta def try_all_elem (t : diagram_term) : chase_tactic (list lemma_app) :=\ndo\n l ← get,\n return $ list.join $ list.map (λ l, try_apply_elem_lemma l t) l.elem_lemmas\n\nmeta mutual def show_via_zero, find_proof_dfs\nwith show_via_zero : diagram_term → diagram_term → chase_tactic (option expr)\n| cur goal := do\n l ← diagram_term.to_zero cur,\n match l with\n | none := return none\n | some e := do\n zer ← goal.zero,\n r ← find_proof_dfs goal zer [],\n match r with\n | none := return none\n | some f := (mk_eq_symm f) >>= (λ g, some <$> mk_eq_trans e g)\n end\n end\nwith find_proof_dfs :\ndiagram_term → diagram_term → list diagram_term → chase_tactic (option expr)\n| cur goal seen := if cur = goal then some <$> mk_eq_refl (as_expr cur) else\ndo\n via_zero ← show_via_zero cur goal,\n match via_zero with\n | some e := return $ some e\n | none := do\n cands_comm ← try_all_comm cur,\n cands_elem ← try_all_elem cur,\n let cands := list.append cands_comm cands_elem,\n\n list.mfoldl (λ r s,\n match r with\n | some q := return $ some q\n | none :=\n ite (list.any seen (λ e, to_bool $ e = (next_term s))) (return none) $\n do\n --trace format!\"trying {s}...\",\n l ← find_proof_dfs (next_term s) goal (cur::seen),\n match l with\n | none := none\n | some q := do\n f ← build_proof cur s,\n t ← mk_eq_trans f q,\n return $ some t\n end\n end) none cands\n end\n\nmeta def find_direct_proof (cur goal : diagram_term) : chase_tactic (option expr) :=\nfind_proof_dfs cur goal []\n\nmeta def find_proof : diagram_term → diagram_term → chase_tactic (option expr)\n| ⟨t, e⟩ ⟨t', e'⟩ := do\n mm ← diagram_term.type ⟨t, e⟩ >>= mono_with_domain,\n match mm with\n | none := find_direct_proof ⟨t, e⟩ ⟨t', e'⟩\n | some m := do\n ii ← find_proof ⟨m::t, e⟩ ⟨m::t', e'⟩,\n match ii with\n | none := none\n | some i := some <$> mk_app `category_theory.abelian.pseudoelements.pseudo_injective_of_mono [i]\n end\n end\n\nmeta def commutativity : chase_tactic unit :=\ndo\n (_, l, r) ← target_lhs_rhs,\n some lhs ← as_diagram_term l,\n some rhs ← as_diagram_term r,\n some p ← find_proof lhs rhs,\n tactic.exact p\n\nend tactic.chase\n\nnamespace tactic.interactive\nopen interactive (parse)\nopen lean.parser (tk pexpr)\n\nmeta def commutativity (loc : parse ((tk \"at\" *> some <$> pexpr) <|> return none)) : tactic unit :=\ndo\n l ← match loc with\n | none := return none\n | some m := some <$> to_expr m\n end,\n chase.run_chase_tactic l tactic.chase.commutativity\n\nend tactic.interactive\n", "meta": {"author": "TwoFX", "repo": "lean-homological-algebra", "sha": "e3a8e4ecaf49bec6c7b38b34c0b8f9749e941aa8", "save_path": "github-repos/lean/TwoFX-lean-homological-algebra", "path": "github-repos/lean/TwoFX-lean-homological-algebra/lean-homological-algebra-e3a8e4ecaf49bec6c7b38b34c0b8f9749e941aa8/src/tactic/commutativity.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4843800842769844, "lm_q2_score": 0.033589506012886725, "lm_q1q2_score": 0.016270087753344348}} {"text": "-- Copyright (c) 2018 Scott Morrison. All rights reserved.\n-- Released under Apache 2.0 license as described in the file LICENSE.\n-- Authors: Scott Morrison\n\nimport category_theory.isomorphism\nimport category_theory.functor_category\n\nnamespace category_theory\n\nuniverses u₁ v₁ u₂ v₂ u₃ v₃ u₄ v₄\n\nsection\nvariables (C : Type u₁) [𝒞 : category.{v₁} C]\n (D : Type u₂) [𝒟 : category.{v₂} D]\n (E : Type u₃) [ℰ : category.{v₃} E]\ninclude 𝒞 𝒟 ℰ\n\ndef whiskering_left : (C ⥤ D) ⥤ ((D ⥤ E) ⥤ (C ⥤ E)) :=\n{ obj := λ F,\n { obj := λ G, F ⋙ G,\n map := λ G H α,\n { app := λ c, α.app (F.obj c),\n naturality' := by intros X Y f; rw [functor.comp_map, functor.comp_map, α.naturality] } },\n map := λ F G τ,\n { app := λ H,\n { app := λ c, H.map (τ.app c),\n naturality' := λ X Y f, begin dsimp at *, rw [←H.map_comp, ←H.map_comp, ←τ.naturality] end },\n naturality' := λ X Y f, begin ext1, dsimp at *, rw [←nat_trans.naturality] end } }\n\ndef whiskering_right : (D ⥤ E) ⥤ ((C ⥤ D) ⥤ (C ⥤ E)) :=\n{ obj := λ H,\n { obj := λ F, F ⋙ H,\n map := λ _ _ α,\n { app := λ c, H.map (α.app c),\n naturality' := by intros X Y f;\n rw [functor.comp_map, functor.comp_map, ←H.map_comp, ←H.map_comp, α.naturality] } },\n map := λ G H τ,\n { app := λ F,\n { app := λ c, τ.app (F.obj c),\n naturality' := λ X Y f, begin dsimp at *, rw [τ.naturality] end },\n naturality' := λ X Y f, begin ext1, dsimp at *, rw [←nat_trans.naturality] end } }\n\nvariables {C} {D} {E}\n\ndef whisker_left (F : C ⥤ D) {G H : D ⥤ E} (α : G ⟹ H) : (F ⋙ G) ⟹ (F ⋙ H) :=\n((whiskering_left C D E).obj F).map α\n\n@[simp] lemma whisker_left.app (F : C ⥤ D) {G H : D ⥤ E} (α : G ⟹ H) (X : C) :\n (whisker_left F α).app X = α.app (F.obj X) :=\nrfl\n\ndef whisker_right {G H : C ⥤ D} (α : G ⟹ H) (F : D ⥤ E) : (G ⋙ F) ⟹ (H ⋙ F) :=\n((whiskering_right C D E).obj F).map α\n\n@[simp] lemma whisker_right.app {G H : C ⥤ D} (α : G ⟹ H) (F : D ⥤ E) (X : C) :\n (whisker_right α F).app X = F.map (α.app X) :=\nrfl\n\n@[simp] lemma whisker_left_id (F : C ⥤ D) {G : D ⥤ E} :\n whisker_left F (nat_trans.id G) = nat_trans.id (F.comp G) :=\nrfl\n\n@[simp] lemma whisker_right_id {G : C ⥤ D} (F : D ⥤ E) :\n whisker_right (nat_trans.id G) F = nat_trans.id (G.comp F) :=\n((whiskering_right C D E).obj F).map_id _\n\n@[simp] lemma whisker_left_vcomp (F : C ⥤ D) {G H K : D ⥤ E} (α : G ⟹ H) (β : H ⟹ K) :\n whisker_left F (α ⊟ β) = (whisker_left F α) ⊟ (whisker_left F β) :=\nrfl\n\n@[simp] lemma whisker_right_vcomp {G H K : C ⥤ D} (α : G ⟹ H) (β : H ⟹ K) (F : D ⥤ E) :\n whisker_right (α ⊟ β) F = (whisker_right α F) ⊟ (whisker_right β F) :=\n((whiskering_right C D E).obj F).map_comp α β\n\nvariables {B : Type u₄} [ℬ : category.{v₄} B]\ninclude ℬ\n\nlocal attribute [elab_simple] whisker_left whisker_right\n\n@[simp] lemma whisker_left_twice (F : B ⥤ C) (G : C ⥤ D) {H K : D ⥤ E} (α : H ⟹ K) :\n whisker_left F (whisker_left G α) = whisker_left (F ⋙ G) α :=\nrfl\n\n@[simp] lemma whisker_right_twice {H K : B ⥤ C} (F : C ⥤ D) (G : D ⥤ E) (α : H ⟹ K) :\n whisker_right (whisker_right α F) G = whisker_right α (F ⋙ G) :=\nrfl\n\nlemma whisker_right_left (F : B ⥤ C) {G H : C ⥤ D} (α : G ⟹ H) (K : D ⥤ E) :\n whisker_right (whisker_left F α) K = whisker_left F (whisker_right α K) :=\nrfl\nend\n\nnamespace functor\n\nuniverses u₅ v₅\n\nvariables {A : Type u₁} [𝒜 : category.{v₁} A]\nvariables {B : Type u₂} [ℬ : category.{v₂} B]\ninclude 𝒜 ℬ\n\ndef left_unitor (F : A ⥤ B) : ((functor.id _) ⋙ F) ≅ F :=\n{ hom := { app := λ X, 𝟙 (F.obj X) },\n inv := { app := λ X, 𝟙 (F.obj X) } }\n\n@[simp] lemma left_unitor_hom_app {F : A ⥤ B} {X} : F.left_unitor.hom.app X = 𝟙 _ := rfl\n@[simp] lemma left_unitor_inv_app {F : A ⥤ B} {X} : F.left_unitor.inv.app X = 𝟙 _ := rfl\n\ndef right_unitor (F : A ⥤ B) : (F ⋙ (functor.id _)) ≅ F :=\n{ hom := { app := λ X, 𝟙 (F.obj X) },\n inv := { app := λ X, 𝟙 (F.obj X) } }\n\n@[simp] lemma right_unitor_hom_app {F : A ⥤ B} {X} : F.right_unitor.hom.app X = 𝟙 _ := rfl\n@[simp] lemma right_unitor_inv_app {F : A ⥤ B} {X} : F.right_unitor.inv.app X = 𝟙 _ := rfl\n\nvariables {C : Type u₃} [𝒞 : category.{v₃} C]\nvariables {D : Type u₄} [𝒟 : category.{v₄} D]\ninclude 𝒞 𝒟\n\ndef associator (F : A ⥤ B) (G : B ⥤ C) (H : C ⥤ D) : ((F ⋙ G) ⋙ H) ≅ (F ⋙ (G ⋙ H)) :=\n{ hom := { app := λ _, 𝟙 _ },\n inv := { app := λ _, 𝟙 _ } }\n\n@[simp] lemma associator_hom_app {F : A ⥤ B} {G : B ⥤ C} {H : C ⥤ D} {X} :\n(associator F G H).hom.app X = 𝟙 _ := rfl\n@[simp] lemma associator_inv_app {F : A ⥤ B} {G : B ⥤ C} {H : C ⥤ D} {X} :\n(associator F G H).inv.app X = 𝟙 _ := rfl\n\nomit 𝒟\n\nlemma triangle (F : A ⥤ B) (G : B ⥤ C) :\n (associator F (functor.id B) G).hom ⊟ (whisker_left F (left_unitor G).hom) =\n (whisker_right (right_unitor F).hom G) :=\nbegin\n ext1,\n dsimp [associator, left_unitor, right_unitor],\n simp\nend\n\nvariables {E : Type u₅} [ℰ : category.{v₅} E]\ninclude 𝒟 ℰ\n\nvariables (F : A ⥤ B) (G : B ⥤ C) (H : C ⥤ D) (K : D ⥤ E)\n\nlemma pentagon :\n (whisker_right (associator F G H).hom K) ⊟ (associator F (G ⋙ H) K).hom ⊟ (whisker_left F (associator G H K).hom) =\n ((associator (F ⋙ G) H K).hom ⊟ (associator F G (H ⋙ K)).hom) :=\nbegin\n ext1,\n dsimp [associator],\n simp,\nend\n\nend functor\n\nend category_theory\n", "meta": {"author": "digama0", "repo": "mathlib-ITP2019", "sha": "5cbd0362e04e671ef5db1284870592af6950197c", "save_path": "github-repos/lean/digama0-mathlib-ITP2019", "path": "github-repos/lean/digama0-mathlib-ITP2019/mathlib-ITP2019-5cbd0362e04e671ef5db1284870592af6950197c/src/category_theory/whiskering.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4416730056646256, "lm_q2_score": 0.03676946924216767, "lm_q1q2_score": 0.016240081996881196}} {"text": "example (p q : Prop) : p ∧ q → p := by\n refine fun ⟨a, b⟩ => a\n\nexample (p q : Prop) : p ∧ q → p := by\n refine fun a => ?hp\n trace_state\n exact a.1\n\nexample (p q : Prop) : p ∧ q → p := by\n refine fun ⟨a, b⟩ => a\n\nexample (p q : Prop) : p ∧ q → p := by\n refine fun ⟨a, b⟩ => ?hp\n trace_state\n exact a\n\nexample (p q : Prop) : p ∧ q → p := by\n refine fun a => ?hp\n case hp => exact a.1\n\nexample (p q : Prop) : p ∧ q → p := by\n refine fun ⟨a, b⟩ => ?hp\n case hp => exact a\n\nexample (p q : Prop) : p ∧ q → p := by\n refine λ ⟨a, b⟩ => ?hp\n trace_state\n exact a\n", "meta": {"author": "leanprover", "repo": "lean4", "sha": "742d053a97bdd109a41a921facd1cd6a55e89bc7", "save_path": "github-repos/lean/leanprover-lean4", "path": "github-repos/lean/leanprover-lean4/lean4-742d053a97bdd109a41a921facd1cd6a55e89bc7/tests/lean/lean3RefineBug.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.31742627850202554, "lm_q2_score": 0.051082731900894476, "lm_q1q2_score": 0.016215001483017636}} {"text": "-- Copyright © 2019 François G. Dorais. All rights reserved.\n-- Released under Apache 2.0 license as described in the file LICENSE.\n\nimport .meta.ind_utils\n\n/-\n\nstructure {u_0 u_1 ... u_{n-1} v_0 v_1 ... v_{n-1}} multi_function_n \n(α_0 : Sort u_0) (α_1 : Sort u_1) ... (α_{n-1} : Sort u_{n-1})\n(β_0 : Sort v_0) (β_1 : Sort v_1) ... (β_{n-1} : Sort v_{n-1}) :=\nmk :: (fn_0 : α_0 → β_0) (fn_1 : α_1 → β_1) ... (fn_{n-1} : α_{n-1} → β_{n-1})\n\ntheorem multi_function_n.mk.eta {α_0 α_1 ... α_{n-1} β_0 β_1 ... β_{n-1}} (f : multi_function_n α_0 α_1 ... α_{n-1} β_0 β_1 ... β_{n-1}),\nmulti_function_n.mk (multi_function_n.fn_0 f) (multi_function_n.fn_1 f) ... (multi_function_n.fn_{n-1} f) = f\n\ndefinition multi_function_n.id {α_0 α_1 ... α_{n-1}} :\nmulti_function_n α_0 α_1 ... α_{n-1} α_0 α_1 ... α_{n-1}\n\ndefinition multi_function_n.comp {α_0 α_1 ... α_{n-1} β_0 β_1 ... β_{n-1} γ_0 γ_1 ... γ_{n-1}} :\nmulti_function_n β_0 β_1 ... β_{n-1} γ_0 γ_1 ... γ_{n-1} → \nmulti_function_n α_0 α_1 ... α_{n-1} β_0 β_1 ... β_{n-1} → \nmulti_function_n α_0 α_1 ... α_{n-1} γ_0 γ_1 ... γ_{n-1}\n\ntheorem multi_function_n.comp.assoc {α_0 α_1 ... α_{n-1} β_0 β_1 ... β_{n-1} γ_0 γ_1 ... γ_{n-1} δ_0 δ_1 ... δ_{n-1}} \n(f : multi_function_n γ_0 γ_1 ... γ_{n-1} δ_0 δ_1 ... δ_{n-1})\n(g : multi_function_n β_0 β_1 ... β_{n-1} γ_0 γ_1 ... γ_{n-1})\n(h : multi_function_n α_0 α_1 ... α_{n-1} β_0 β_1 ... β_{n-1}) : \nmulti_function_n.comp (multi_function_n.comp f g) h = multi_function_n.comp f (multi_function_n.comp g h)\n\ntheorem multi_function_n.comp.left_id {α_0 α_1 ... α_{n-1} β_0 β_1 ... β_{n-1}}\n(f : multi_function_n α_0 α_1 ... α_{n-1} β_0 β_1 ... β_{n-1}) : \nmulti_function_n.comp multi_function_n.id f = f\n\ntheorem multi_function_n.comp.right_id {α_0 α_1 ... α_{n-1} β_0 β_1 ... β_{n-1}}\n(f : multi_function_n α_0 α_1 ... α_{n-1} β_0 β_1 ... β_{n-1}) : \nmulti_function_n.comp f multi_function_n.id = f\n\n-/\n\nnamespace multi_function\n\ndef to_name (n : nat) : name := mk_sub_name `multi_function n\n\ndef mk_name (n : nat) : name := to_name n ++ `mk\n\ndef fn_name (n i : nat) : name := to_name n ++ mk_sub_name `fn i\n\nmeta def mk_decl (n : nat) : inductive_declaration :=\nlet nm := to_name n in\nlet dus := mk_sub_names `u n in\nlet dls := dus.map level.param in\nlet dns := mk_sub_names `α n in\nlet cus := mk_sub_names `v n in\nlet cls := cus.map level.param in\nlet cns := mk_sub_names `β n in\nlet ctx : expr_ctx :=\n (dns ++ cns).reverse.zip $\n (dls ++ cls).reverse.map $\n λ l, (expr.sort l, binder_info.default) in\nlet lt := level.list_max (level.one :: dls ++ cls) in\nlet type : expr := ctx.pi (expr.sort lt) in\nlet inst : expr := ctx.app (expr.const nm (dls ++ cls)) in\nlet ctx : expr_ctx := ctx.map (λ ⟨n, t, _⟩, (n, t, binder_info.implicit)) in\nlet ctx : expr_ctx := (mk_sub_names `fn n).reverse.enum.foldr (λ ⟨k, fn⟩ ctx,\n ctx.add fn (expr.pi `_ binder_info.default (expr.var (2 * n - 1)) (expr.var n))\n) ctx in\nlet cons : expr := ctx.pi (inst.lift_vars 0 n) in\n{ to_name := nm\n, univ_params := dus ++ cus\n, type := type\n, recursor := some (nm ++ `rec)\n, constructors := [(mk_name n, cons)]\n, num_params := 2 * n\n, num_indices := 0\n, is_trusted := tt \n}\n\nmeta def mk_proj (n : nat) : list declaration :=\nlet nm := to_name n in\nlet dus := mk_sub_names `u n in\nlet dls := dus.map level.param in\nlet dns := mk_sub_names `α n in\nlet cus := mk_sub_names `v n in\nlet cls := cus.map level.param in\nlet cns := mk_sub_names `β n in\nlet ctx : expr_ctx :=\n (dns ++ cns).reverse.zip $\n (dls ++ cls).reverse.map $\n λ l, (expr.sort l, binder_info.implicit) in\nlet inst : expr := ctx.app (expr.const nm (dls ++ cls)) in\nlet tctx : expr_ctx := ctx.add `f inst in\nlet types : list expr := (list.range' n).map (λ k,\n tctx.pi (expr.pi `_ binder_info.default (expr.var (2 * n - k)) (expr.var (n + 1 - k)))\n) in\nlet fctx : expr_ctx := (mk_sub_names `fn n).reverse.map (λ fn,\n (fn, (expr.pi `_ binder_info.default (expr.var (2 * n - 1)) (expr.var n)), binder_info.default)\n) in\nlet values : list expr := (list.range' n).map (λ k,\n let l := level.imax (level.param $ mk_sub_name `u k) (level.param $ mk_sub_name `v k) in\n let mot : expr := expr.pi `_ binder_info.default (expr.var (2 * n - k)) (expr.var (n + 1 - k)) in\n let mot : expr := expr.lam `H binder_info.default inst mot in\n let val : expr := fctx.lam (expr.var (n - k - 1)) in\n let rec : expr := ctx.app (expr.const (nm ++ `rec) (l :: dls ++ cls)) in\n let rec : expr := rec.app mot in\n let rec : expr := rec.app val in\n ctx.lam rec\n) in\n(list.zip types values).enum.map (λ ⟨k, t, v⟩,\n declaration.defn (fn_name n k) (dus ++ cus) t v reducibility_hints.abbrev tt\n)\n\nmeta def mk_eta (n : nat) : declaration :=\nlet nm := to_name n in\nlet dus := mk_sub_names `u n in\nlet dls := dus.map level.param in\nlet dns := mk_sub_names `α n in\nlet cus := mk_sub_names `v n in\nlet cls := cus.map level.param in\nlet cns := mk_sub_names `β n in\nlet lvl := level.list_max (level.one :: dls ++ cls) in\nlet ctx : expr_ctx :=\n (dns ++ cns).reverse.zip $\n (dls ++ cls).reverse.map $\n λ l, (expr.sort l, binder_info.implicit) in\nlet inst : expr := ctx.app (expr.const nm (dls ++ cls)) in\nlet cons : expr := ctx.app (expr.const (mk_name n) (dls ++ cls)) in\nlet tctx : expr_ctx := ctx.add `f inst in\nlet fns : list expr := (list.range n).map (λ k,\n let e : expr := expr.const (fn_name n k) (dls ++ cls) in\n tctx.app e\n) in\nlet lhs : expr := expr.mk_app (cons.lift_vars 0 1) fns in\nlet eqn : expr := expr.mk_app (expr.const `eq [lvl]) [inst.lift_vars 0 1, lhs, expr.var 0] in\nlet type : expr := tctx.pi $ eqn in\nlet rec : expr := ctx.app $ expr.const (nm ++ `rec_on) (level.zero :: dls ++ cls) in\nlet rec : expr := rec.app (expr.lam `f binder_info.default inst eqn) in\nlet rec : expr := expr.app (rec.lift_vars 0 1) (expr.var 0) in\nlet fctx : expr_ctx := (list.range n).map (λ k,\n (mk_sub_name `fn (n-k-1), expr.pi `_ binder_info.default (expr.var (2 * n)) (expr.var (n+1)), binder_info.default)\n) in\nlet fobj : expr := fctx.app (cons.lift_vars 0 (n+1)) in\nlet prf : expr := expr.const `eq.refl [lvl] in\nlet prf : expr := prf.mk_app [inst.lift_vars 0 (n+1), fobj] in\nlet value : expr := tctx.lam (rec.app $ fctx.lam prf) in\ndeclaration.thm (mk_name n ++ `eta) (dus ++ cus) type (pure value)\n\n/-\nmeta def mk_eq (n : nat) : declaration :=\nlet nm := to_name n in\nlet dus := mk_sub_names `u n in\nlet dls := dus.map level.param in\nlet dns := mk_sub_names `α n in\nlet cus := mk_sub_names `v n in\nlet cls := cus.map level.param in\nlet cns := mk_sub_names `β n in\nlet lvl := level.list_max (level.one :: dls ++ cls) in\nlet ctx : expr_ctx :=\n (dns ++ cns).reverse.zip $\n (dls ++ cls).reverse.map $\n λ l, (expr.sort l, binder_info.implicit) in\nlet inst : expr := ctx.app (expr.const nm (dls ++ cls)) in\nlet tctx : expr_ctx :=\n[ (mk_sub_name `f 2, inst.lift_vars 0 1, binder_info.default)\n, (mk_sub_name `f 1, inst, binder_info.default)\n] ++ ctx in\nlet tctx : expr_ctx := (list.zip dls cls).indexed.foldl (λ tctx ⟨k, dl, cl⟩,\n let typ : expr := expr.pi `_ binder_info.default (expr.var (2 * n + 1)) (expr.var (n + 2)) in\n let lhs : expr := expr.const (nm ++ mk_sub_name `fn k) (dls ++ cls) in\n let lhs : expr := lhs.app (expr.var (k+1)) in\n let rhs : expr := expr.const (nm ++ mk_sub_name `fn k) (dls ++ cls) in\n let rhs : expr := rhs.app (expr.var k) in\n let eqn : expr := expr.const `eq [level.imax dl cl] in\n let eqn : expr := eqn.mk_app [typ, lhs, rhs] in\n tctx.add (mk_sub_name `h k) eqn\n) tctx in\nlet type : expr := tctx.pi $ expr.mk_app (expr.const `eq [lvl]) [inst.lift_vars 0 (n+2), expr.var (n+1), expr.var n]\nin \nlet value : expr := inhabited.default expr in\ndeclaration.thm (nm ++ `eq) (dus ++ cus) type (pure value)\n-/\n\nmeta def mk_id (n : nat) : declaration :=\nlet nm := to_name n in\nlet us := mk_sub_names `u n in\nlet ls := us.map level.param in\nlet ts := mk_sub_names `α n in\nlet ctx : expr_ctx := ts.reverse.zip $ ls.reverse.map (λ l, (expr.sort l, binder_info.implicit)) in\nlet type : expr := expr.const nm (ls ++ ls) in\nlet type : expr := type.mk_app (expr.mk_num_vars n ++ expr.mk_num_vars n).reverse in\nlet type : expr := ctx.pi type in\nlet value : expr := expr.const (nm ++ `mk) (ls ++ ls) in\nlet value : expr := value.mk_app (expr.mk_num_vars n ++ expr.mk_num_vars n).reverse in\nlet value : expr := value.mk_app $ (list.range' n).map (λ k,\n let e : expr := expr.const `id [level.param $ mk_sub_name `u k] in\n e.app (expr.var (n - k - 1))\n) in\nlet value : expr := ctx.lam value in\ndeclaration.defn (nm ++ `id) us type value reducibility_hints.abbrev tt\n\nmeta def mk_comp (n : nat) : declaration :=\nlet nm := to_name n in\nlet nus := mk_sub_names `u n in\nlet nvs := mk_sub_names `v n in\nlet nws := mk_sub_names `w n in\nlet lus := nus.map level.param in\nlet lvs := nvs.map level.param in\nlet lws := nws.map level.param in\nlet tus := mk_sub_names `α n in\nlet tvs := mk_sub_names `β n in\nlet tws := mk_sub_names `γ n in\nlet ctx : expr_ctx := \n (tus ++ tvs ++ tws).reverse.zip $\n (lus ++ lvs ++ lws).reverse.map $\n λ l, (expr.sort l, binder_info.implicit) in\nlet typeuv : expr := expr.const nm (lus ++ lvs) in\nlet typevw : expr := expr.const nm (lvs ++ lws) in\nlet typeuw : expr := expr.const nm (lus ++ lws) in\nlet typeuv : expr := typeuv.mk_app (expr.mk_num_vars n (2 * n)).reverse in\nlet typeuv : expr := typeuv.mk_app (expr.mk_num_vars n (1 * n)).reverse in\nlet typeuw : expr := typeuw.mk_app (expr.mk_num_vars n (2 * n)).reverse in\nlet typeuw : expr := typeuw.mk_app (expr.mk_num_vars n (0 * n)).reverse in\nlet typevw : expr := typevw.mk_app (expr.mk_num_vars n (1 * n)).reverse in\nlet typevw : expr := typevw.mk_app (expr.mk_num_vars n (0 * n)).reverse in\nlet ctx : expr_ctx := ctx.add `f typevw in\nlet ctx : expr_ctx := ctx.add `g (typeuv.lift_vars 0 1) in\nlet type : expr := ctx.pi (typeuw.lift_vars 0 2) in\nlet pruv : list expr := (list.range n).map (λ k, \n let e : expr := expr.const (nm ++ mk_sub_name `fn k) (lus ++ lvs) in\n let e : expr := e.mk_app (expr.mk_num_vars n (2 * n + 2)).reverse in\n let e : expr := e.mk_app (expr.mk_num_vars n (1 * n + 2)).reverse in\n e.app (expr.var 0)\n) in\nlet prvw : list expr := (list.range n).map (λ k, \n let e : expr := expr.const (nm ++ mk_sub_name `fn k) (lvs ++ lws) in\n let e : expr := e.mk_app (expr.mk_num_vars n (1 * n + 2)).reverse in\n let e : expr := e.mk_app (expr.mk_num_vars n (0 * n + 2)).reverse in\n e.app (expr.var 1)\n) in\nlet args : list expr := (list.zip pruv prvw).reverse.enum.map (λ ⟨k, fuv, fvw⟩,\n let u := [mk_sub_name `u (n-k-1), mk_sub_name `v (n-k-1), mk_sub_name `w (n-k-1)] in\n let e : expr := expr.const `function.comp (u.map level.param) in\n e.mk_app [expr.var (2*n+2+k), expr.var (1*n+2+k), expr.var (0*n+2+k), fvw, fuv]\n) in\nlet value : expr := expr.const (nm ++ `mk) (lus ++ lws) in\nlet value : expr := value.mk_app (expr.mk_num_vars n (2 * n + 2)).reverse in\nlet value : expr := value.mk_app (expr.mk_num_vars n (0 * n + 2)).reverse in\nlet value : expr := value.mk_app args.reverse in\nlet value : expr := ctx.lam value in\ndeclaration.defn (nm ++ `comp) (nus ++ nvs ++ nws) type value reducibility_hints.abbrev tt\n\nmeta def mk_comp_assoc (n : nat) : declaration :=\nlet nm := to_name n in\nlet nts := mk_sub_names `t n in\nlet nus := mk_sub_names `u n in\nlet nvs := mk_sub_names `v n in\nlet nws := mk_sub_names `w n in\nlet lts := nts.map level.param in\nlet lus := nus.map level.param in\nlet lvs := nvs.map level.param in\nlet lws := nws.map level.param in\nlet tts := mk_sub_names `α n in\nlet tus := mk_sub_names `β n in\nlet tvs := mk_sub_names `γ n in\nlet tws := mk_sub_names `δ n in\nlet ctx : expr_ctx := \n (tts ++ tus ++ tvs ++ tws).reverse.zip $\n (lts ++ lus ++ lvs ++ lws).reverse.map $\n λ l, (expr.sort l, binder_info.implicit) in\nlet typetu : expr := expr.const nm (lts ++ lus) in\nlet typetu : expr := typetu.mk_app (expr.mk_num_vars n (3 * n)).reverse in\nlet typetu : expr := typetu.mk_app (expr.mk_num_vars n (2 * n)).reverse in\nlet typeuv : expr := expr.const nm (lus ++ lvs) in\nlet typeuv : expr := typeuv.mk_app (expr.mk_num_vars n (2 * n)).reverse in\nlet typeuv : expr := typeuv.mk_app (expr.mk_num_vars n (1 * n)).reverse in\nlet typevw : expr := expr.const nm (lvs ++ lws) in\nlet typevw : expr := typevw.mk_app (expr.mk_num_vars n (1 * n)).reverse in\nlet typevw : expr := typevw.mk_app (expr.mk_num_vars n (0 * n)).reverse in\nlet typetw : expr := expr.const nm (lts ++ lws) in\nlet typetw : expr := typetw.mk_app (expr.mk_num_vars n (3 * n)).reverse in\nlet typetw : expr := typetw.mk_app (expr.mk_num_vars n (0 * n)).reverse in\nlet ctx : expr_ctx := ctx.add `f typevw in\nlet ctx : expr_ctx := ctx.add `g (typeuv.lift_vars 0 1) in\nlet ctx : expr_ctx := ctx.add `h (typetu.lift_vars 0 2) in\nlet lhsl : expr := expr.const (nm ++ `comp) (lus ++ lvs ++ lws) in\nlet lhsl : expr := lhsl.mk_app (expr.mk_num_vars n (2 * n + 3)).reverse in\nlet lhsl : expr := lhsl.mk_app (expr.mk_num_vars n (1 * n + 3)).reverse in\nlet lhsl : expr := lhsl.mk_app (expr.mk_num_vars n (0 * n + 3)).reverse in\nlet lhsl : expr := lhsl.mk_app [expr.var 2, expr.var 1] in\nlet lhs : expr := expr.const (nm ++ `comp) (lts ++ lus ++ lws) in\nlet lhs : expr := lhs.mk_app (expr.mk_num_vars n (3 * n + 3)).reverse in\nlet lhs : expr := lhs.mk_app (expr.mk_num_vars n (2 * n + 3)).reverse in\nlet lhs : expr := lhs.mk_app (expr.mk_num_vars n (0 * n + 3)).reverse in\nlet lhs : expr := lhs.mk_app [lhsl, expr.var 0] in\nlet rhsr : expr := expr.const (nm ++ `comp) (lts ++ lus ++ lvs) in\nlet rhsr : expr := rhsr.mk_app (expr.mk_num_vars n (3 * n + 3)).reverse in\nlet rhsr : expr := rhsr.mk_app (expr.mk_num_vars n (2 * n + 3)).reverse in\nlet rhsr : expr := rhsr.mk_app (expr.mk_num_vars n (1 * n + 3)).reverse in\nlet rhsr : expr := rhsr.mk_app [expr.var 1, expr.var 0] in\nlet rhs : expr := expr.const (nm ++ `comp) (lts ++ lvs ++ lws) in\nlet rhs : expr := rhs.mk_app (expr.mk_num_vars n (3 * n + 3)).reverse in\nlet rhs : expr := rhs.mk_app (expr.mk_num_vars n (1 * n + 3)).reverse in\nlet rhs : expr := rhs.mk_app (expr.mk_num_vars n (0 * n + 3)).reverse in\nlet rhs : expr := rhs.mk_app [expr.var 2, rhsr] in\nlet lvl : level := level.list_max (level.one :: lts ++ lws) in\nlet eqn : expr := expr.const `eq [lvl] in\nlet eqn : expr := eqn.mk_app [typetw.lift_vars 0 3, lhs, rhs] in\nlet type : expr := ctx.pi eqn in\nlet proof : expr := expr.const `eq.refl [lvl] in\nlet proof : expr := proof.mk_app [typetw.lift_vars 0 3, lhs] in\nlet proof : expr := ctx.lam proof in\ndeclaration.thm (nm ++ `comp ++ `assoc) (nts ++ nus ++ nvs ++ nws) type (pure proof)\n\nmeta def mk_comp_left_id (n : nat) : declaration :=\nlet nm := to_name n in\nlet nus := mk_sub_names `u n in\nlet nvs := mk_sub_names `v n in\nlet lus := nus.map level.param in\nlet lvs := nvs.map level.param in\nlet tus := mk_sub_names `α n in\nlet tvs := mk_sub_names `β n in\nlet ctx : expr_ctx := (list.zip (tus ++ tvs) (lus ++ lvs)).reverse.map (λ ⟨n, l⟩,\n (n, expr.sort l, binder_info.implicit)\n) in\nlet typeuv : expr := ctx.app (expr.const nm (lus ++ lvs)) in\nlet ctx : expr_ctx := ctx.add `f typeuv in\nlet compuvv : expr := expr.const (nm ++ `comp) (lus ++ lvs ++ lvs) in\nlet compuvv : expr := compuvv.mk_app (expr.mk_num_vars n n).reverse in\nlet compuvv : expr := compuvv.mk_app (expr.mk_num_vars n 0).reverse in\nlet compuvv : expr := compuvv.mk_app (expr.mk_num_vars n 0).reverse in\nlet idv : expr := expr.const (nm ++ `id) lvs in\nlet idv : expr := idv.mk_app (expr.mk_num_vars n 0).reverse in\nlet lvl : level := level.list_max (level.one :: lus ++ lvs) in\nlet lhs : expr := expr.mk_app (compuvv.lift_vars 0 1) [idv.lift_vars 0 1, expr.var 0] in\nlet type : expr := expr.const `eq [lvl] in\nlet type : expr := type.mk_app [typeuv.lift_vars 0 1, lhs, expr.var 0] in\nlet type : expr := ctx.pi type in\nlet proof : expr := ctx.app $ expr.const (mk_name n ++ `eta) (lus ++ lvs) in\nlet proof : expr := ctx.lam proof in\ndeclaration.thm (nm ++ `comp ++ `left_id) (nus ++ nvs) type (pure proof)\n\nmeta def mk_comp_right_id (n : nat) : declaration :=\nlet nm := to_name n in\nlet nus := mk_sub_names `u n in\nlet nvs := mk_sub_names `v n in\nlet lus := nus.map level.param in\nlet lvs := nvs.map level.param in\nlet tus := mk_sub_names `α n in\nlet tvs := mk_sub_names `β n in\nlet ctx : expr_ctx := (list.zip (tus ++ tvs) (lus ++ lvs)).reverse.map (λ ⟨n, l⟩,\n (n, expr.sort l, binder_info.implicit)\n) in\nlet typeuv : expr := ctx.app (expr.const nm (lus ++ lvs)) in\nlet ctx : expr_ctx := ctx.add `f typeuv in\nlet compuuv : expr := expr.const (nm ++ `comp) (lus ++ lus ++ lvs) in\nlet compuuv : expr := compuuv.mk_app (expr.mk_num_vars n n).reverse in\nlet compuuv : expr := compuuv.mk_app (expr.mk_num_vars n n).reverse in\nlet compuuv : expr := compuuv.mk_app (expr.mk_num_vars n 0).reverse in\nlet idu : expr := expr.const (nm ++ `id) lus in\nlet idu : expr := idu.mk_app (expr.mk_num_vars n n).reverse in\nlet lvl : level := level.list_max (level.one :: lus ++ lvs) in\nlet lhs : expr := expr.mk_app (compuuv.lift_vars 0 1) [expr.var 0, idu.lift_vars 0 1] in\nlet type : expr := expr.const `eq [lvl] in\nlet type : expr := type.mk_app [typeuv.lift_vars 0 1, lhs, expr.var 0] in\nlet type : expr := ctx.pi type in\nlet proof : expr := ctx.app $ expr.const (mk_name n ++ `eta) (lus ++ lvs) in\nlet proof : expr := ctx.lam proof in\ndeclaration.thm (nm ++ `comp ++ `right_id) (nus ++ nvs) type (pure proof)\n\nend multi_function\n\nmeta def environment.add_multi_function (env : environment) (n : nat) : exceptional environment :=\nenv.add_ind (multi_function.mk_decl n) tt >>= λ env, list.mfoldl environment.add env $\nmulti_function.mk_proj n ++\n[ multi_function.mk_eta n\n, multi_function.mk_id n\n, multi_function.mk_comp n\n, multi_function.mk_comp_assoc n\n, multi_function.mk_comp_left_id n\n, multi_function.mk_comp_right_id n\n]\n\nnamespace tactic\n\nmeta def add_multi_function (n : nat) : tactic unit :=\ndo {\n let mfn := multi_function.to_name n,\n updateex_env $ λ env, env.add_multi_function n,\n -- vm needs code for cases_on ...\n ron ← get_decl (mfn ++ `rec_on),\n add_decl (ron.update_name $ mfn ++ `cases_on),\n -- set attributes\n (list.range n).mmap (λ k,\n set_basic_attribute `reducible (mfn ++ mk_sub_name `fn k) tt >>\n set_basic_attribute `inline (mfn ++ mk_sub_name `fn k) tt\n ),\n set_basic_attribute `reducible (mfn ++ `id) tt,\n set_basic_attribute `reducible (mfn ++ `comp) tt,\n guard (n = 0) <|> set_basic_attribute `simp (mfn ++ `mk.eta) tt,\n guard (n = 0) <|> set_basic_attribute `simp (mfn ++ `comp.left_id) tt,\n guard (n = 0) <|> set_basic_attribute `simp (mfn ++ `comp.right_id) tt,\n skip\n}\n\nmeta def ensure_multi_function (n : nat) : tactic unit :=\nget_decl (multi_function.to_name n) >> skip <|> add_multi_function n\n\nend tactic\n\nrun_cmd tactic.add_multi_function 1\nrun_cmd tactic.add_multi_function 2\n\ninstance {α} {β} : has_coe_to_fun (multi_function_1 α β) := ⟨_, multi_function_1.fn_0⟩\n\ntheorem multi_function_1.eq {α} {β} {f g : multi_function_1 α β} : f.fn_0 = g.fn_0 → f = g :=\nλ h,\neq.subst (multi_function_1.mk.eta f) $\neq.subst (multi_function_1.mk.eta g) $\ncongr rfl h\n\ntheorem multi_function_2.eq {α_0} {α_1} {β_0} {β_1} {f g : multi_function_2 α_0 α_1 β_0 β_1} : f.fn_0 = g.fn_0 → f.fn_1 = g.fn_1 → f = g :=\nλ h_0 h_1, \neq.subst (multi_function_2.mk.eta f) $\neq.subst (multi_function_2.mk.eta g) $\ncongr (congr rfl h_0) h_1\n", "meta": {"author": "fgdorais", "repo": "lean-universal", "sha": "9259b0f7fb3aa83a9e0a7a3eaa44c262e42cc9b1", "save_path": "github-repos/lean/fgdorais-lean-universal", "path": "github-repos/lean/fgdorais-lean-universal/lean-universal-9259b0f7fb3aa83a9e0a7a3eaa44c262e42cc9b1/src/util/multi_function.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4148988457967688, "lm_q2_score": 0.03904829636066302, "lm_q1q2_score": 0.016201093090369257}} {"text": "import polycodable_init\nimport polytime_tac\n\nvariables {α β γ : Type*} [polycodable α] [polycodable β] [polycodable γ]\nopen ptree.pencodable (encode decode)\n\nsection bool\n\ninstance : polycodable bool :=\n{ polytime_decode := ⟨_, \n (polytime_ite polytime_id polytime_nil (polytime_const ptree.non_nil)), λ x, by cases x; simp [ptree.of_option, encode, decode]⟩ }\n\n@[polyfun]\nlemma polytime_fun.ite' {f : α → bool} {g h : α → β} : polytime_fun f → polytime_fun g → polytime_fun h → polytime_fun (λ x, cond (f x) (g x) (h x))\n| ⟨cf, pf, sf⟩ ⟨cg, pg, sg⟩ ⟨ch, ph, sh⟩ :=\n⟨_, polytime_ite pf pg ph, λ x, by cases H : (f x); simp [sf, sg, sh, ← apply_ite part.some, ← apply_ite encode, encode, H]⟩ \n\n@[polyfun]\nlemma polytime_fun.ite {P : α → Prop} [decidable_pred P] {g h : α → β} (hP : polytime_fun (λ x, (P x : bool))) (hg : polytime_fun g) (hh : polytime_fun h) :\n polytime_fun (λ x, if P x then g x else h x) :=\nbegin\n convert_to polytime_fun (λ x, cond (P x) (g x) (h x)),\n { ext x, by_cases P x; simp, }, polyfun,\nend\n\n\nprivate lemma polytime_fun.eq_nil_aux : polytime_fun (λ x', (x' = ptree.nil : bool)) :=\n⟨_, polytime_ite polytime_id polytime_nil (polytime_const ptree.non_nil), λ x, by cases x; simp [encode]⟩\n\nlocal attribute [polyfun] polytime_fun.eq_nil_aux\n\n@[polyfun]\nlemma polytime_fun.band : polytime_fun₂ (&&) :=\nbegin\n convert_to polytime_fun₂ (λ b₁ b₂ : bool, cond b₁ b₂ ff),\n { ext b₁, cases b₁; simp, }, polyfun,\nend\n\n@[polyfun]\nlemma polytime_fun.bor : polytime_fun₂ (||) :=\nbegin\n convert_to polytime_fun₂ (λ b₁ b₂ : bool, cond b₁ tt b₂),\n { ext b₁, cases b₁; simp, }, polyfun,\nend\n\n@[polyfun]\nlemma polytime_fun.bnot : polytime_fun bnot :=\nby { convert_to polytime_fun (λ b, cond b ff tt), { ext b, cases b; refl, }, polyfun, }\n\nlemma ptree_children {f g : ptree → bool} (hf : polytime_fun f) (hg : polytime_fun g) :\n polytime_fun (λ x : ptree, (x ≠ ptree.nil) && (f x.left && g x.right)) :=\nby polyfun\n\nprivate lemma polytime_fun.eq_const_aux : ∀ (x : ptree), polytime_fun (λ x', (x' = x : bool))\n| ptree.nil := polytime_fun.eq_nil_aux\n| (ptree.node a b) :=\nbegin\n convert ptree_children (polytime_fun.eq_const_aux a) (polytime_fun.eq_const_aux b),\n ext x, cases x; simp,\nend\n\n@[polyfun]\nlemma polytime_fun.eq_const {f : α → β} [decidable_eq β] (hf : polytime_fun f) (x : β) : polytime_fun (λ x', (f x' = x : bool)) :=\nbegin\n convert_to polytime_fun (λ x', (encode (f x') = encode x : bool)), { simp, },\n exact polytime_fun.comp (polytime_fun.eq_const_aux (encode x)) hf,\nend\n\nend bool\n\nsection option\n\ninstance : polycodable (option α) :=\n{ polytime_decode :=\nbegin\n convert_to polytime_fun (λ x : ptree, if x = ptree.nil then ptree.nil else ptree.of_option (some (encode (decode x.right : α)))),\n { ext x, cases x; simp [ptree.to_option, ptree.of_option, encode, decode], },\n simp only [ptree.of_option], polyfun,\nend }\n\n@[polyfun]\nlemma polytime_fun.some : polytime_fun (@some α) :=\nby { apply polytime_fun.decode, simp [encode, function.comp, ptree.of_option], polyfun, }\n\n@[polyfun]\nlemma polytime_fun.iget [inhabited α] : polytime_fun (@option.iget α _) :=\n⟨code.ite code.id (code.const (encode (default : α))) code.right, polytime_ite polytime_id (polytime_const _) polytime_right, λ x,\nby { cases x; simp [encode, ptree.of_option], }⟩\n\n@[polyfun]\nlemma polytime_fun.is_none : polytime_fun (@option.is_none α) :=\n⟨code.ite code.id (code.const $ encode tt) (code.const $ encode ff), polytime_ite polytime_id (polytime_const _) (polytime_const _), λ x,\nby { cases x; simp [encode, ptree.of_option], }⟩\n\n@[polyfun]\nlemma polytime_fun.option_elim {f : α → option β} {g : α → γ} {h : α → β → γ} (hf : polytime_fun f) (hg : polytime_fun g) (hh : polytime_fun₂ h) :\n polytime_fun (λ x, (f x).elim (g x) (h x)) :=\nbegin\n apply polytime_fun.decode,\n haveI : inhabited β := ⟨decode ptree.nil⟩,\n convert_to polytime_fun (λ x : α, if (f x).is_none then encode (g x) else encode (h x (f x).iget)),\n { ext x, cases H : (f x); simp [H], },\n polyfun,\nend\n\n@[polyfun]\nlemma polytime_fun.option_map {f : α → option β} {g : α → β → γ} (hf : polytime_fun f) (hg : polytime_fun₂ g) :\n polytime_fun (λ x, (f x).map (g x)) :=\nbegin\n convert_to polytime_fun (λ x, (f x).elim none (λ r, some (g x r))),\n { ext x : 1, cases (f x); simp, },\n polyfun,\nend\n\n@[polyfun]\nlemma polytime_fun.get_or_else : polytime_fun₂ (@option.get_or_else α) :=\nbegin\n convert_to polytime_fun₂ (λ (a : option α) (b : α), a.elim b id),\n { ext a b, cases a; simp, }, polyfun,\nend\n\n@[polyfun]\nlemma polytime_fun.is_some : polytime_fun (@option.is_some α) :=\nbegin\n convert_to polytime_fun (λ (a : option α), a.elim ff (λ _, tt)),\n { ext x, cases x; simp, }, polyfun,\nend\n\nend option\n\nsection mk\n\ndef polycodable.mk' {δ : Type*} (encode : δ → α) (decode : α → δ) (encode_decode : ∀ x, decode (encode x) = x)\n (polytime_decode : polytime_fun (encode ∘ decode)) : polycodable δ :=\n{ polytime_decode :=\nby { apply polytime_fun.comp polytime_decode, polyfun, },\n ..ptree.pencodable.mk' encode decode encode_decode, }\n\nlemma polycodable.mk_encode {δ : Type*} (encode : δ → α) (decode : α → δ) (encode_decode : ∀ x, decode (encode x) = x) :\n @polytime_fun δ α (ptree.pencodable.mk' encode decode encode_decode) _ encode :=\nby { apply polytime_fun.id, }\n\nlemma polycodable.mk_decode' {δ : Type*} (encode : δ → α) (decode : α → δ) (encode_decode : ∀ x, decode (encode x) = x)\n (polytime_decode : polytime_fun (encode ∘ decode)) :\n @polytime_fun α δ _ (polycodable.mk' encode decode encode_decode polytime_decode).to_pencodable decode :=\npolytime_decode\n\nlemma polycodable.mk_decode {δ : Type*} (encode : δ → α) (decode : α → δ) (encode_decode : ∀ x, decode (encode x) = x)\n (f : β → δ) (hf : polytime_fun (encode ∘ f)) :\n @polytime_fun β δ _ (ptree.pencodable.mk' encode decode encode_decode) f :=\nhf\n\ndef polycodable.of_equiv {δ : Type*} (eqv : δ ≃ α) : polycodable δ :=\npolycodable.mk'\n(λ x, eqv x)\n(λ y, eqv.symm y)\n(by simp)\n(by simpa using polytime_fun.id)\n\n@[polyfun]\nlemma polycodable.of_equiv_polytime {δ : Type*} (eqv : δ ≃ α) :\n @polytime_fun δ α (ptree.pencodable.of_equiv eqv) _ eqv :=\nby { apply polytime_fun.id, }\n\n@[polyfun]\nlemma polycodable.of_equiv_polytime_symm {δ : Type*} (eqv : δ ≃ α) :\n @polytime_fun α δ _ (polycodable.of_equiv eqv).to_pencodable eqv.symm :=\nby { apply polycodable.mk_decode', }\n\nend mk\n\nsection unit\n\ninstance : polycodable unit := \n{ polytime_decode := polytime_fun.const ptree.nil }\n\nend unit\n\nsection sum\n\nend sum\n", "meta": {"author": "prakol16", "repo": "lean_complexity_theory_polytime_trees", "sha": "4f478b752a2061cd829bf83a68c77180d1318b62", "save_path": "github-repos/lean/prakol16-lean_complexity_theory_polytime_trees", "path": "github-repos/lean/prakol16-lean_complexity_theory_polytime_trees/lean_complexity_theory_polytime_trees-4f478b752a2061cd829bf83a68c77180d1318b62/src/polycodable.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40733340004593027, "lm_q2_score": 0.039638836690151356, "lm_q1q2_score": 0.01614622212286472}} {"text": "/-\nFile: signature_recover_public_key_is_zero_soundness.lean\n\nAutogenerated file.\n-/\nimport starkware.cairo.lean.semantics.soundness.hoare\nimport .signature_recover_public_key_code\nimport ..signature_recover_public_key_spec\nimport .signature_recover_public_key_verify_zero_soundness\nimport .signature_recover_public_key_unreduced_mul_soundness\nimport .signature_recover_public_key_nondet_bigint3_soundness\nopen tactic\n\nopen starkware.cairo.common.cairo_secp.field\nopen starkware.cairo.common.cairo_secp.bigint\n\nvariables {F : Type} [field F] [decidable_eq F] [prelude_hyps F]\nvariable mem : F → F\nvariable σ : register_state F\n\n/- starkware.cairo.common.cairo_secp.field.is_zero autogenerated soundness theorem -/\n\ntheorem auto_sound_is_zero\n -- arguments\n (range_check_ptr : F) (x : BigInt3 F)\n -- code is in memory at σ.pc\n (h_mem : mem_at mem code_is_zero σ.pc)\n -- all dependencies are in memory\n (h_mem_4 : mem_at mem code_nondet_bigint3 (σ.pc - 71))\n (h_mem_5 : mem_at mem code_unreduced_mul (σ.pc - 59))\n (h_mem_7 : mem_at mem code_verify_zero (σ.pc - 23))\n -- input arguments on the stack\n (hin_range_check_ptr : range_check_ptr = mem (σ.fp - 6))\n (hin_x : x = cast_BigInt3 mem (σ.fp - 5))\n -- conclusion\n : ensures_ret mem σ (λ κ τ,\n ∃ μ ≤ κ, rc_ensures mem (rc_bound F) μ (mem (σ.fp - 6)) (mem $ τ.ap - 2)\n (spec_is_zero mem κ range_check_ptr x (mem (τ.ap - 2)) (mem (τ.ap - 1)))) :=\nbegin\n apply ensures_of_ensuresb, intro νbound,\n have h_mem_rec := h_mem,\n unpack_memory code_is_zero at h_mem with ⟨hpc0, hpc1, hpc2, hpc3, hpc4, hpc5, hpc6, hpc7, hpc8, hpc9, hpc10, hpc11, hpc12, hpc13, hpc14, hpc15, hpc16, hpc17, hpc18, hpc19, hpc20, hpc21, hpc22, hpc23, hpc24, hpc25, hpc26, hpc27, hpc28, hpc29, hpc30, hpc31, hpc32, hpc33, hpc34, hpc35⟩,\n -- if statement\n -- tempvar\n apply of_register_state,\n intros regstate_ιχ__temp40 regstateeq_ιχ__temp40,\n generalize' hl_rev_ιχ__temp40: mem regstate_ιχ__temp40.ap = ιχ__temp40,\n have hl_ιχ__temp40 := hl_rev_ιχ__temp40.symm,\n rw [regstateeq_ιχ__temp40] at hl_ιχ__temp40, try { dsimp at hl_ιχ__temp40 },\n -- ap += 1\n step_advance_ap hpc0 hpc1,\n step_jnz hpc2 hpc3 with hcond hcond,\n {\n -- if: positive branch\n have a0 : ιχ__temp40 = 0, {\n try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_x, hl_ιχ__temp40] },\n try { dsimp [cast_BigInt3] },\n try { arith_simps }, try { simp only [hcond] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },\n },\n try { dsimp at a0 }, try { arith_simps at a0 },\n clear hcond,\n -- jump statement\n step_jump_imm hpc4 hpc5,\n -- function call\n step_assert_eq hpc15 with arg0,\n step_sub hpc16 (auto_sound_nondet_bigint3 mem _ range_check_ptr _ _),\n { rw hpc17, norm_num2, exact h_mem_4 },\n { try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_x, hl_ιχ__temp40] },\n try { dsimp [cast_BigInt3] },\n try { arith_simps }, try { simp only [arg0] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } }, },\n intros κ_call18 ap18 h_call18,\n rcases h_call18 with ⟨h_call18_ap_offset, h_call18⟩,\n rcases h_call18 with ⟨rc_m18, rc_mle18, hl_range_check_ptr₁, h_call18⟩,\n generalize' hr_rev_range_check_ptr₁: mem (ap18 - 4) = range_check_ptr₁,\n have htv_range_check_ptr₁ := hr_rev_range_check_ptr₁.symm, clear hr_rev_range_check_ptr₁,\n generalize' hr_rev_x_inv: cast_BigInt3 mem (ap18 - 3) = x_inv,\n simp only [hr_rev_x_inv] at h_call18,\n have htv_x_inv := hr_rev_x_inv.symm, clear hr_rev_x_inv,\n try { simp only [arg0] at hl_range_check_ptr₁ },\n rw [←htv_range_check_ptr₁, ←hin_range_check_ptr] at hl_range_check_ptr₁,\n try { simp only [arg0] at h_call18 },\n rw [hin_range_check_ptr] at h_call18,\n clear arg0,\n -- function call\n step_assert_eq hpc18 with arg0,\n step_assert_eq hpc19 with arg1,\n step_assert_eq hpc20 with arg2,\n step_assert_eq hpc21 with arg3,\n step_assert_eq hpc22 with arg4,\n step_assert_eq hpc23 with arg5,\n step_sub hpc24 (auto_sound_unreduced_mul mem _ x x_inv _ _ _),\n { rw hpc25, norm_num2, exact h_mem_5 },\n { try { ext } ; {\n try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_x, hl_ιχ__temp40, htv_range_check_ptr₁, htv_x_inv] },\n try { dsimp [cast_BigInt3] },\n try { arith_simps }, try { simp only [arg0, arg1, arg2, arg3, arg4, arg5] },\n try { simp only [h_call18_ap_offset] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },}, },\n { try { ext } ; {\n try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_x, hl_ιχ__temp40, htv_range_check_ptr₁, htv_x_inv] },\n try { dsimp [cast_BigInt3] },\n try { arith_simps }, try { simp only [arg0, arg1, arg2, arg3, arg4, arg5] },\n try { simp only [h_call18_ap_offset] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },}, },\n intros κ_call26 ap26 h_call26,\n rcases h_call26 with ⟨h_call26_ap_offset, h_call26⟩,\n generalize' hr_rev_x_x_inv: cast_UnreducedBigInt3 mem (ap26 - 3) = x_x_inv,\n simp only [hr_rev_x_x_inv] at h_call26,\n have htv_x_x_inv := hr_rev_x_x_inv.symm, clear hr_rev_x_x_inv,\n clear arg0 arg1 arg2 arg3 arg4 arg5,\n -- function call\n step_assert_eq hpc26 with arg0,\n step_assert_eq hpc27 hpc28 with arg1,\n step_assert_eq hpc29 with arg2,\n step_assert_eq hpc30 with arg3,\n step_sub hpc31 (auto_sound_verify_zero mem _ range_check_ptr₁ {\n d0 := x_x_inv.d0 - 1,\n d1 := x_x_inv.d1,\n d2 := x_x_inv.d2\n } _ _ _),\n { rw hpc32, norm_num2, exact h_mem_7 },\n { try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_x, hl_ιχ__temp40, htv_range_check_ptr₁, htv_x_inv, htv_x_x_inv] },\n try { dsimp [cast_BigInt3, cast_UnreducedBigInt3] },\n try { arith_simps }, try { simp only [arg0, arg1, arg2, arg3] },\n try { simp only [h_call18_ap_offset, h_call26_ap_offset] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } }, },\n { try { ext } ; {\n try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_x, hl_ιχ__temp40, htv_range_check_ptr₁, htv_x_inv, htv_x_x_inv] },\n try { dsimp [cast_BigInt3, cast_UnreducedBigInt3] },\n try { arith_simps }, try { simp only [arg0, arg1, arg2, arg3] },\n try { simp only [h_call18_ap_offset, h_call26_ap_offset] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },}, },\n intros κ_call33 ap33 h_call33,\n rcases h_call33 with ⟨h_call33_ap_offset, h_call33⟩,\n rcases h_call33 with ⟨rc_m33, rc_mle33, hl_range_check_ptr₂, h_call33⟩,\n generalize' hr_rev_range_check_ptr₂: mem (ap33 - 1) = range_check_ptr₂,\n have htv_range_check_ptr₂ := hr_rev_range_check_ptr₂.symm, clear hr_rev_range_check_ptr₂,\n try { simp only [arg0 ,arg1 ,arg2 ,arg3] at hl_range_check_ptr₂ },\n try { rw [h_call26_ap_offset] at hl_range_check_ptr₂ }, try { arith_simps at hl_range_check_ptr₂ },\n rw [←htv_range_check_ptr₂, ←htv_range_check_ptr₁] at hl_range_check_ptr₂,\n try { simp only [arg0 ,arg1 ,arg2 ,arg3] at h_call33 },\n try { rw [h_call26_ap_offset] at h_call33 }, try { arith_simps at h_call33 },\n rw [←htv_range_check_ptr₁, hl_range_check_ptr₁, hin_range_check_ptr] at h_call33,\n clear arg0 arg1 arg2 arg3,\n -- return\n step_assert_eq hpc33 hpc34 with hret0,\n step_ret hpc35,\n -- finish\n step_done, use_only [rfl, rfl],\n -- range check condition\n use_only (rc_m18+rc_m33+0+0), split,\n linarith [rc_mle18, rc_mle33],\n split,\n { arith_simps, try { simp only [hret0] },\n rw [←htv_range_check_ptr₂, hl_range_check_ptr₂, hl_range_check_ptr₁, hin_range_check_ptr],\n try { arith_simps, refl <|> norm_cast }, try { refl } },\n intro rc_h_range_check_ptr, repeat { rw [add_assoc] at rc_h_range_check_ptr },\n have rc_h_range_check_ptr' := range_checked_add_right rc_h_range_check_ptr,\n -- Final Proof\n -- user-provided reduction\n suffices auto_spec: auto_spec_is_zero mem _ range_check_ptr x _ _,\n { apply sound_is_zero, apply auto_spec },\n -- prove the auto generated assertion\n dsimp [auto_spec_is_zero],\n try { norm_num1 }, try { arith_simps },\n use_only [ιχ__temp40],\n right,\n use_only [a0],\n use_only [κ_call18],\n use_only [range_check_ptr₁],\n use_only [x_inv],\n have rc_h_range_check_ptr₁ := range_checked_offset' rc_h_range_check_ptr,\n have rc_h_range_check_ptr₁' := range_checked_add_right rc_h_range_check_ptr₁, try { norm_cast at rc_h_range_check_ptr₁' },\n have spec18 := h_call18 rc_h_range_check_ptr',\n rw [←hin_range_check_ptr, ←htv_range_check_ptr₁] at spec18,\n try { dsimp at spec18, arith_simps at spec18 },\n use_only [spec18],\n use_only [κ_call26],\n use_only [x_x_inv],\n try { dsimp at h_call26, arith_simps at h_call26 },\n try { use_only [h_call26] },\n use_only [κ_call33],\n use_only [range_check_ptr₂],\n have rc_h_range_check_ptr₂ := range_checked_offset' rc_h_range_check_ptr₁,\n have rc_h_range_check_ptr₂' := range_checked_add_right rc_h_range_check_ptr₂, try { norm_cast at rc_h_range_check_ptr₂' },\n have spec33 := h_call33 rc_h_range_check_ptr₁',\n rw [←hin_range_check_ptr, ←hl_range_check_ptr₁, ←htv_range_check_ptr₂] at spec33,\n try { dsimp at spec33, arith_simps at spec33 },\n use_only [spec33],\n try { split, linarith },\n try { ensures_simps; try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_x, hl_ιχ__temp40, htv_range_check_ptr₁, htv_x_inv, htv_x_x_inv, htv_range_check_ptr₂] }, },\n try { dsimp [cast_BigInt3, cast_UnreducedBigInt3] },\n try { arith_simps }, try { simp only [hret0] },\n try { simp only [h_call18_ap_offset, h_call26_ap_offset, h_call33_ap_offset] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },\n },\n {\n -- if: negative branch\n have a0 : ιχ__temp40 ≠ 0, {\n try { simp only [ne.def] },\n try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_x, hl_ιχ__temp40] },\n try { dsimp [cast_BigInt3] },\n try { arith_simps }, try { simp only [hcond] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },\n },\n try { dsimp at a0 }, try { arith_simps at a0 },\n clear hcond,\n -- function call\n step_assert_eq hpc6 with arg0,\n step_assert_eq hpc7 with arg1,\n step_assert_eq hpc8 with arg2,\n step_assert_eq hpc9 with arg3,\n step_sub hpc10 (auto_sound_verify_zero mem _ range_check_ptr {\n d0 := x.d0,\n d1 := x.d1,\n d2 := x.d2\n } _ _ _),\n { rw hpc11, norm_num2, exact h_mem_7 },\n { try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_x, hl_ιχ__temp40] },\n try { dsimp [cast_BigInt3] },\n try { arith_simps }, try { simp only [arg0, arg1, arg2, arg3] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } }, },\n { try { ext } ; {\n try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_x, hl_ιχ__temp40] },\n try { dsimp [cast_BigInt3] },\n try { arith_simps }, try { simp only [arg0, arg1, arg2, arg3] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },}, },\n intros κ_call12 ap12 h_call12,\n rcases h_call12 with ⟨h_call12_ap_offset, h_call12⟩,\n rcases h_call12 with ⟨rc_m12, rc_mle12, hl_range_check_ptr₁, h_call12⟩,\n generalize' hr_rev_range_check_ptr₁: mem (ap12 - 1) = range_check_ptr₁,\n have htv_range_check_ptr₁ := hr_rev_range_check_ptr₁.symm, clear hr_rev_range_check_ptr₁,\n try { simp only [arg0 ,arg1 ,arg2 ,arg3] at hl_range_check_ptr₁ },\n rw [←htv_range_check_ptr₁, ←hin_range_check_ptr] at hl_range_check_ptr₁,\n try { simp only [arg0 ,arg1 ,arg2 ,arg3] at h_call12 },\n rw [hin_range_check_ptr] at h_call12,\n clear arg0 arg1 arg2 arg3,\n -- return\n step_assert_eq hpc12 hpc13 with hret0,\n step_ret hpc14,\n -- finish\n step_done, use_only [rfl, rfl],\n -- range check condition\n use_only (rc_m12+0+0), split,\n linarith [rc_mle12],\n split,\n { arith_simps, try { simp only [hret0] },\n rw [←htv_range_check_ptr₁, hl_range_check_ptr₁, hin_range_check_ptr],\n try { arith_simps, refl <|> norm_cast }, try { refl } },\n intro rc_h_range_check_ptr, repeat { rw [add_assoc] at rc_h_range_check_ptr },\n have rc_h_range_check_ptr' := range_checked_add_right rc_h_range_check_ptr,\n -- Final Proof\n -- user-provided reduction\n suffices auto_spec: auto_spec_is_zero mem _ range_check_ptr x _ _,\n { apply sound_is_zero, apply auto_spec },\n -- prove the auto generated assertion\n dsimp [auto_spec_is_zero],\n try { norm_num1 }, try { arith_simps },\n use_only [ιχ__temp40],\n left,\n use_only [a0],\n use_only [κ_call12],\n use_only [range_check_ptr₁],\n have rc_h_range_check_ptr₁ := range_checked_offset' rc_h_range_check_ptr,\n have rc_h_range_check_ptr₁' := range_checked_add_right rc_h_range_check_ptr₁, try { norm_cast at rc_h_range_check_ptr₁' },\n have spec12 := h_call12 rc_h_range_check_ptr',\n rw [←hin_range_check_ptr, ←htv_range_check_ptr₁] at spec12,\n try { dsimp at spec12, arith_simps at spec12 },\n use_only [spec12],\n try { split, linarith },\n try { ensures_simps; try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_x, hl_ιχ__temp40, htv_range_check_ptr₁] }, },\n try { dsimp [cast_BigInt3] },\n try { arith_simps }, try { simp only [hret0] },\n try { simp only [h_call12_ap_offset] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },\n }\nend\n\n", "meta": {"author": "starkware-libs", "repo": "formal-proofs", "sha": "35613c65b6715601bbc0a550d52754f8e7d93e30", "save_path": "github-repos/lean/starkware-libs-formal-proofs", "path": "github-repos/lean/starkware-libs-formal-proofs/formal-proofs-35613c65b6715601bbc0a550d52754f8e7d93e30/src/starkware/cairo/common/cairo_secp/verification/verification/signature_recover_public_key_is_zero_soundness.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4455295203152604, "lm_q2_score": 0.0362200520937267, "lm_q1q2_score": 0.0161371024351118}} {"text": "/-\nDefine the semantics of core Linalg operations.\n-/\nimport MLIR.Semantics.Fitree\nimport MLIR.Semantics.Semantics\nimport MLIR.Semantics.SSAEnv\nimport MLIR.Semantics.UB\nimport MLIR.Util.Metagen\nimport MLIR.AST\nimport MLIR.EDSL\nopen MLIR.AST\n\n\n/-\nConsider the following MWE:\n\n```lean\nstructure DepProof where\n val: Nat\n H: val = 0\n\ndef MonadicDepProof [Mon: Monad M]: M DepProof := do\n let v ← pure 0\n return {\n val := v\n H := by {\n /-\n M: Type → Type ?u.380\n Mon: Monad M\n v: ℕ\n ⊢ v = 0\n -/\n sorry\n }\n }\n```\n\nHow to see in the proof mode that `v` originated from `pure 0`?\n-/\n\ninstance linalg: Dialect Void Void (fun x => Unit) where\n name := \"linalg\"\n iα := inferInstance\n iε := inferInstance\n\n\n-- We assume that we only run regions that behave purely (otherwise most of the\n-- theorems on generic don't work).\ndef validGenericRegion {Δ: Dialect α σ ε} (r: Region Δ) (f: Int → FinInt 32 → FinInt 32) :=\n forall (i: Int) (v: FinInt 32),\n OpM.denoteRegion r 0 [⟨.index, i⟩, ⟨.i32, v⟩] = return [⟨.i32, f i v⟩]\n\n\ndef OpM.findIndex (d: AttrDict δ) (key: String): OpM Δ Nat :=\n match d.find_int key with\n | .some ⟨v, MLIRType.index⟩ => return v.toNat\n | _ => OpM.Error s!\"{d}.lookup {key} failed to find int\"\n\ndef OpM.findI32 (d: AttrDict δ) (key: String): OpM Δ (FinInt 32) :=\n match d.find_int key with\n | .some (v, _) => return (FinInt.ofInt 32 v)\n | _ => OpM.Error s!\"{d}.lookup {key} failed to find int\"\n\n\n-- in general, xtract slice has offset, size, stride.\n-- We ignore the stride and offset for now, just use size.\ndef linalg_semantics_op {Δ: Dialect α σ ε}: IOp Δ → OpM Δ (TypedArgs Δ)\n | IOp.mk \"linalg.extractslice1d\" _ [⟨.tensor1d, t⟩] [] dict => do\n let len ← OpM.findIndex dict \"len\"\n let t' := t.extract len\n return [⟨.tensor1d, t'⟩]\n | IOp.mk \"linalg.fill1d\" _ [⟨.tensor1d, t⟩] [] dict => do\n let cst ← OpM.findI32 dict \"cst\"\n let t' := t.fill cst\n return [⟨.tensor1d, t'⟩]\n | IOp.mk \"linalg.generic1d'\" _ [⟨.tensor1d, t⟩] [r] _ => do -- generic1d without array index.\n let t' <- t.mapM (fun val => do\n let rets ← r [⟨.i32, val⟩]\n match rets with\n | [⟨.i32, v⟩] => pure v\n | _ => OpM.Error s!\"linalg.generic1d: unknown return value '{rets}'\")\n return [⟨.tensor1d, t'⟩]\n | IOp.mk \"linalg.generic1d\" _ [⟨.tensor1d, t⟩] [r] _ => do\n let t' <- t.mapMWithFlatIndex (fun idx val => do\n let rets ← r [⟨.index, idx.ix⟩, ⟨.i32, val⟩]\n match rets with\n | [⟨.i32, v⟩] => pure v\n | _ => OpM.Error s!\"linalg.generic1d: unknown return value '{rets}'\")\n return [⟨.tensor1d, t'⟩]\n | IOp.mk \"linalg.extractslice2d\" _ [⟨.tensor2d, t⟩] [r] dict => do\n let len0 ← OpM.findIndex dict \"len0\"\n let len1 ← OpM.findIndex dict \"len1\"\n dite (α := OpM Δ (TypedArgs Δ))\n (len0 <= t.size0)\n (fun LEQ0 =>\n dite (len1 <= t.size1)\n (fun LEQ1 => do\n let subview : TensorSubview2D t.size0 t.size1\n := { size0 := len0, size1 := len1, IX0 := LEQ0, IX1 := LEQ1}\n let t' := t.extractslice' subview\n return [⟨.tensor2d, t'⟩])\n (fun GT0 => OpM.Error \"expected index inbounds\"))\n (fun GT1 => OpM.Error \"expected index inbounds\")\n | IOp.mk \"linalg.fill2d\" _ [⟨.tensor2d, t⟩] [r] dict => do\n let cst ← OpM.findI32 dict \"cst\"\n let t' := t.fill (FinInt.toSint cst)\n return [⟨.tensor2d, t'⟩]\n | IOp.mk \"linalg.transpose2d\" _ [⟨.tensor2d, t⟩] [r] dict => do\n let t' := t.transpose\n return [⟨.tensor2d, t'⟩]\n | IOp.mk \"linalg.insertslice2d\" _ [⟨.tensor1d, t⟩] [r] dict => sorry\n | IOp.mk \"linalg.generic2d\" _ [⟨.tensor1d, t⟩] [r] dict => sorry\n | IOp.mk \"linalg.parallel2d\" _ [⟨.tensor1d, t⟩] [r] dict => do\n return []\n | IOp.mk name .. => OpM.Unhandled s!\"unhandled {name}\"\n\n-- TODO: timeout! with maxHeartbeats, all RAM is consumed.\n/-\nset_option maxHeartbeats 10000 in\ntheorem linalg_semantics_generic1d {Δ: Dialect α σ ε} {r: Region Δ} {rSpec types attrs}:\n validGenericRegion r rSpec →\n linalg_semantics_op (Δ := Δ)\n (IOp.mk \"linalg.generic1d\"\n types [⟨.tensor1d, t⟩]\n [OpM.denoteRegion r 0]\n attrs) =\n return [⟨.tensor1d, t.mapWithFlatIndex (fun idx val => rSpec idx.ix val)⟩] := by\n intros h\n simp [linalg_semantics_op]\n simp [validGenericRegion] at h\n simp [h]\n rw [Tensor1D.mapM_map]\n . rfl\n . intros; rfl\n-/\ninstance : Semantics linalg where\n semantics_op := linalg_semantics_op\n\nnamespace BubbleUpExtractSlice\n/-\nconvert extract slice (linalg.generic x) -> linalg.generic (extract slice x)\n-/\n\n#check mapM\ntheorem bubble_up_extract_slice [MM: Monad M] [LM: LawfulMonad M]\n (t: Tensor1D)\n (f : FinInt 32 -> M (FinInt 32)):\n (fun s => s.extract len) <$> (t.mapM f) = (t.extract len).mapM f := by {\n cases t;\n sorry\n}\n\n/- TODO -/\nend BubbleUpExtractSlice\n\nnamespace SwapExtractSlice\n/- TODO -/\nend SwapExtractSlice\n\nnamespace DecomposeLinalgOps\n/- TODO -/\nend DecomposeLinalgOps\n\nnamespace Fusion\n/- TODO -/\nend Fusion\n\nnamespace FusionOnTensors\n/- TODO -/\nend FusionOnTensors\n\n/-\nFor each transformation, we implement\n1) a theorem that proves correctness\n2) a test in Test/SemanticTests.lean which tests\n both versions of the program.\n-/\nnamespace ExtractSliceFillCommuteOneD\n\n-- TODO: timeout!\ntheorem extract_fill_commute:\n Tensor1D.fill (Tensor1D.extract t extractlen) fillval =\n Tensor1D.extract (Tensor1D.fill t fillval) extractlen := by {\n simp [Tensor1D.fill, Tensor1D.extract];\n apply List.extF\n intros n h; simp; simp at h\n sorry\n sorry\n /-\n repeat rw [List.getF_replicate]\n . apply Nat.lt_min_left; apply h\n . simp\n . assumption\n -/\n }\n-- https://mlir.llvm.org/doxygen/BubbleUpExtractSlice_8cpp_source.html\ndef LHS : Region linalg := [mlir_region| {\n %x = \"linalg.extractslice1d\" (%t) { len = 10 : index }: (tensor1d) -> (tensor1d)\n %out = \"linalg.fill1d\" (%x) { cst = 42 : index }: (tensor1d) -> (tensor1d)\n}]\ndef RHS : Region linalg := [mlir_region| {\n %x = \"linalg.fill1d\" (%t) { cst = 42 : index }: (tensor1d) -> (tensor1d)\n %out = \"linalg.extractslice1d\" (%x) { len = 10 : index }: (tensor1d) -> (tensor1d)\n}]\n/-\nTODO: Create a predicate to say that the programs agree on output value `out`.\n-/\n/-\ntheorem equiv (t: Tensor1D):\n run ⟦LHS⟧ (SSAEnv.One [ (\"t\", ⟨.tensor1d, t⟩) ]) =\n run ⟦RHS⟧ (SSAEnv.One [ (\"t\", ⟨.tensor1d, t⟩) ]) := by {\n simp[LHS, RHS];\n simp_all[denoteRegion, run, StateT.run, denoteTypedArgs, pure, StateT.pure, Except.pure,\n StateT.run, Except.ok, bind, Except.bind, denoteOps, denoteOps\n , StateT.bind, denoteOp, List.mapM, List.mapM.loop, TopM.get,\n StateT.get, OpM.toTopM, TopM.raiseUB, liftM, TopM.set,\n StateT.set, cast];\n\n }\n-/\n\nend ExtractSliceFillCommuteOneD\n\n\n\nnamespace ExtractSliceGenericCommute1D\nvariable (r : Region linalg)\n\n\n-- https://mlir.llvm.org/doxygen/BubbleUpExtractSlice_8cpp_source.html\ndef LHS: Region linalg := [mlir_region| {\n %x = \"linalg.generic1d\" (%t) ($(r)) { len = 10 : index }: (tensor1d) -> (tensor1d)\n %out = \"linalg.fill1d\" (%x) { cst = 42 : index }: (tensor1d) -> (tensor1d)\n}]\ndef RHS : Region linalg := [mlir_region| {\n %x = \"linalg.generic1d\" (%t) ($(r)) { cst = 42 : index }: (tensor1d) -> (tensor1d)\n %out = \"linalg.extractslice1d\" (%x) { len = 10 : index }: (tensor1d) -> (tensor1d)\n}]\n\n@[simp]\ntheorem OpM.bind_ret {Δ: Dialect α σ ε} (a: α) (k: α → OpM Δ β):\n bind (OpM.Ret a) k = k a := rfl\n\n@[simp]\ntheorem OpM.toTopM_pure {r: TypedArgs Δ}:\n OpM.toTopM rs (pure r) env = Except.ok (r, env) := rfl\n\ntheorem equiv (t: Tensor1D) r rSpec:\n validGenericRegion r rSpec →\n run ⟦LHS r⟧ (SSAEnv.One [ (\"t\", ⟨.tensor1d, t⟩) ]) =\n run ⟦RHS r⟧ (SSAEnv.One [ (\"t\", ⟨.tensor1d, t⟩) ]) := by {\n intros valid_r;\n simp[LHS, RHS];\n -- tactic bug: (kernel) constant has already been declared '_private.MLIR.Dialects.LinalgSemantics.0.linalg_semantics_op.match_2.eq_1'\n /-\n simp_all[denoteRegion, run, StateT.run, List.map, denoteTypedArgs, pure, StateT.pure, Except.pure,\n StateT.run, Except.ok, bind, Except.bind, denoteOps, denoteOps\n , StateT.bind, denoteOp, List.mapM, List.mapM.loop, TopM.get,\n StateT.get, OpM.toTopM, TopM.raiseUB, liftM, TopM.set,\n StateT.set, cast, OpM.denoteRegions, TopM.mapDenoteRegion,\n OpM.toTopM, denoteRegion, denoteOpArgs, SSAEnv.get, SSAEnv.getT, Semantics.semantics_op, linalg_semantics_op];\n -/\n sorry\n }\nend ExtractSliceGenericCommute1D\n\nnamespace mapMCommute\ndef fish [Monad m] (f: a -> m b) (g: b -> m c): a -> m c := fun a => (f a) >>= g\n\ntheorem mapM_cons [M: Monad m] [LM: LawfulMonad m] (x: a) (xs: List a) (f: a -> m b):\n List.mapM f (x :: xs) = f x >>= (fun b => do let bs <- List.mapM f xs; pure (b :: bs)) := by {\n simp[List.mapM, List.mapM.loop];\n sorry;\n}\ntheorem commute_implies_mapM_commute [Monad m] [LawfulMonad m]\n (f g : a -> m a ) (k: List a -> a -> m b)\n (COMMUTE: forall {b: Type} (x y : a) (k: a -> a -> m b), f x >>= (fun r1 => (g y >>= fun r2 => k r1 r2 )) =\n g y >>= fun r2 => f x >>= fun r1 => k r1 r2):\n List.mapM f xs >>= (fun r1 => (g y >>= fun r2 => k r1 r2 )) =\n g y >>= fun r2 => List.mapM f xs >>= fun r1 => k r1 r2 := by sorry\n\ntheorem mapM_commute [M: Monad m] [LM: LawfulMonad m]\n (f g: a -> m a) (COMMUTE: forall {b : Type} (x y : a) (k: a -> a -> m b), f x >>= (fun r1 => (g y >>= fun r2 => k r1 r2 )) =\n g y >>= fun r2 => f x >>= fun r1 => k r1 r2)\n : fish (List.mapM f) (List.mapM g) = List.mapM (fish f g) := by {\n\n funext x;\n induction x;\n case nil => {\n simp[fish, List.mapM, List.mapM.loop];\n }\n case cons head tail IH => {\n -- simp[fish];\n rewrite [mapM_cons];\n simp[fish];\n -- rewrite [mapM_cons];\n\n simp [bind_assoc]\n simp[mapM_cons];\n congr; -- remove the head\n funext x';\n rewrite [commute_implies_mapM_commute];\n congr;\n funext x';\n simp [fish] at IH;\n rewrite [<- IH];\n simp[bind_assoc];\n apply COMMUTE;\n\n }\n\n}\nend mapMCommute\n\nnamespace Generic1DFusion\n\n\nvariable (r s : Region linalg)\n\n-- See section MapMCommute.\n-- See section MapMCommute\n-- fmap f . fmap g == fmap (f . g)\n-- true iff f commutes with g?\n-- mapM f >=> mapM g == mapM (f >=> g)\n-- naive proof: induction on size of %t.\n-- god's proof in the book: show that the computation of y[i] looks like\n-- as what's written below. (need some notion of funext on the array).\ndef LHS: Region linalg := [mlir_region| {\n %x = \"linalg.generic1d\" (%t) ($(r)): (tensor1d) -> (tensor1d) -- fmap r | x[i] <- r(t(i))\n %y = \"linalg.generic1d\" (%x) ($(s)): (tensor1d) -> (tensor1d) -- fmap s | y[i] <- s(x[i]) = s(r(t(i)))\n}]\ndef RHS : Region linalg := [mlir_region| {\n %y = \"linalg.generic1d\" (%t) ({\n ^entry(%x: i32):\n %v1 = \"region.run\" (%x) ($(r)) {} : (index) -> (index)\n %v2 = \"region.run\" (%v1) ($(s)) {} : (index) -> (index)\n \"scf.yield\"(%v2): (i32) -> (i32)\n }): (tensor1d) -> (tensor1d)\n}]\nend Generic1DFusion\n\nnamespace Generic1DTiling\nvariable (r: Region linalg)\n-- Need a precondition that the width is divisible by 4.\n\ndef LHS: Region linalg := [mlir_region| {\n %y = \"linalg.generic1d\" (%x) ($(r)): (tensor1d) -> (tensor1d)\n}]\ndef RHS : Region linalg := [mlir_region| {\n %width = \"linalg.dim\" (%x) { \"index\" = 0 : index } : (tensor1d) -> (index)\n %four = \"arith.constant\" () { \"value\" = 4 : index } : () -> (index)\n %num_tiles = \"arith.div\"(%width , %four) : (index, index) -> (index)\n %y = \"scf.for_iter\" (%zero, %num_tiles, %x) ({ -- begin, end, loop variable.\n ^entry(%i: index):\n %xchunk = \"linalg.extractindex\"(%x, %i_times_four, %four) : (tensor1d, index, index) -> (tensor1d)\n %ychunk = \"linalg.generic1d\" (%xchunk) ($(r)): (tensor1d) -> (tensor1d)\n %yout = \"linalg.insertindex\"(%x, %i_times_four, %ychunk) : (tensor1d, index, tensor1d) -> (tensor1d)\n \"scf.yield\"(%yout) : (tensor1d) -> (tensor1d)\n }): (tensor1d) -> (tensor1d)\n}]\nend Generic1DTiling\n\nnamespace Transpose2D\n\n\ndef LHS: Region linalg := [mlir_region| {\n %x = \"linalg.transpsose2d\" (%t) : (tensor2d) -> (tensor2d)\n %y = \"linalg.transpose2d\" (%x) : (tensor2d) -> (tensor2d)\n}]\ndef RHS : Region linalg := [mlir_region| {\n %y = \"scf.id\"(%x) : (tensor2d) -> (tensor2d)\n}]\n\n-- Done in the tensor, we have the proof that 2d transpose is id.\n\nend Transpose2D\n", "meta": {"author": "opencompl", "repo": "lean-mlir", "sha": "85fd61e38dec57e4d67d7af4d49a1ccc67828c1b", "save_path": "github-repos/lean/opencompl-lean-mlir", "path": "github-repos/lean/opencompl-lean-mlir/lean-mlir-85fd61e38dec57e4d67d7af4d49a1ccc67828c1b/MLIR/Dialects/LinalgSemantics.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38861804086755836, "lm_q2_score": 0.04146227093475229, "lm_q1q2_score": 0.016112986500583345}} {"text": "/-\nCopyright (c) 2018 Johannes Hölzl. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthor: Johannes Hölzl\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.default\nimport Mathlib.data.finset.basic\nimport Mathlib.data.multiset.pi\nimport Mathlib.PostPort\n\nuniverses u_1 u_2 \n\nnamespace Mathlib\n\n/-!\n# The cartesian product of finsets\n-/\n\nnamespace finset\n\n\n/-! ### pi -/\n\n/-- The empty dependent product function, defined on the empty set. The assumption `a ∈ ∅` is never\nsatisfied. -/\ndef pi.empty {α : Type u_1} (β : α → Type u_2) (a : α) (h : a ∈ ∅) : β a :=\n multiset.pi.empty β a h\n\n/-- Given a finset `s` of `α` and for all `a : α` a finset `t a` of `δ a`, then one can define the\nfinset `s.pi t` of all functions defined on elements of `s` taking values in `t a` for `a ∈ s`.\nNote that the elements of `s.pi t` are only partially defined, on `s`. -/\ndef pi {α : Type u_1} {δ : α → Type u_2} [DecidableEq α] (s : finset α) (t : (a : α) → finset (δ a)) : finset ((a : α) → a ∈ s → δ a) :=\n mk (multiset.pi (val s) fun (a : α) => val (t a)) sorry\n\n@[simp] theorem pi_val {α : Type u_1} {δ : α → Type u_2} [DecidableEq α] (s : finset α) (t : (a : α) → finset (δ a)) : val (pi s t) = multiset.pi (val s) fun (a : α) => val (t a) :=\n rfl\n\n@[simp] theorem mem_pi {α : Type u_1} {δ : α → Type u_2} [DecidableEq α] {s : finset α} {t : (a : α) → finset (δ a)} {f : (a : α) → a ∈ s → δ a} : f ∈ pi s t ↔ ∀ (a : α) (h : a ∈ s), f a h ∈ t a :=\n multiset.mem_pi (val s) (fun (a : α) => (fun (a : α) => val (t a)) a) f\n\n/-- Given a function `f` defined on a finset `s`, define a new function on the finset `s ∪ {a}`,\nequal to `f` on `s` and sending `a` to a given value `b`. This function is denoted\n`s.pi.cons a b f`. If `a` already belongs to `s`, the new function takes the value `b` at `a`\nanyway. -/\ndef pi.cons {α : Type u_1} {δ : α → Type u_2} [DecidableEq α] (s : finset α) (a : α) (b : δ a) (f : (a : α) → a ∈ s → δ a) (a' : α) (h : a' ∈ insert a s) : δ a' :=\n multiset.pi.cons (val s) a b f a' sorry\n\n@[simp] theorem pi.cons_same {α : Type u_1} {δ : α → Type u_2} [DecidableEq α] (s : finset α) (a : α) (b : δ a) (f : (a : α) → a ∈ s → δ a) (h : a ∈ insert a s) : pi.cons s a b f a h = b :=\n multiset.pi.cons_same (pi.cons._proof_1 s a a h)\n\ntheorem pi.cons_ne {α : Type u_1} {δ : α → Type u_2} [DecidableEq α] {s : finset α} {a : α} {a' : α} {b : δ a} {f : (a : α) → a ∈ s → δ a} {h : a' ∈ insert a s} (ha : a ≠ a') : pi.cons s a b f a' h = f a' (or.resolve_left (iff.mp mem_insert h) (ne.symm ha)) :=\n multiset.pi.cons_ne (pi.cons._proof_1 s a a' h) (ne.symm ha)\n\ntheorem pi_cons_injective {α : Type u_1} {δ : α → Type u_2} [DecidableEq α] {a : α} {b : δ a} {s : finset α} (hs : ¬a ∈ s) : function.injective (pi.cons s a b) := sorry\n\n@[simp] theorem pi_empty {α : Type u_1} {δ : α → Type u_2} [DecidableEq α] {t : (a : α) → finset (δ a)} : pi ∅ t = singleton (pi.empty δ) :=\n rfl\n\n@[simp] theorem pi_insert {α : Type u_1} {δ : α → Type u_2} [DecidableEq α] [(a : α) → DecidableEq (δ a)] {s : finset α} {t : (a : α) → finset (δ a)} {a : α} (ha : ¬a ∈ s) : pi (insert a s) t = finset.bUnion (t a) fun (b : δ a) => image (pi.cons s a b) (pi s t) := sorry\n\ntheorem pi_singletons {α : Type u_1} [DecidableEq α] {β : Type u_2} (s : finset α) (f : α → β) : (pi s fun (a : α) => singleton (f a)) = singleton fun (a : α) (_x : a ∈ s) => f a := sorry\n\ntheorem pi_const_singleton {α : Type u_1} [DecidableEq α] {β : Type u_2} (s : finset α) (i : β) : (pi s fun (_x : α) => singleton i) = singleton fun (_x : α) (_x : _x ∈ s) => i :=\n pi_singletons s fun (_x : α) => i\n\ntheorem pi_subset {α : Type u_1} {δ : α → Type u_2} [DecidableEq α] {s : finset α} (t₁ : (a : α) → finset (δ a)) (t₂ : (a : α) → finset (δ a)) (h : ∀ (a : α), a ∈ s → t₁ a ⊆ t₂ a) : pi s t₁ ⊆ pi s t₂ :=\n fun (g : (a : α) → a ∈ s → δ a) (hg : g ∈ pi s t₁) =>\n iff.mpr mem_pi fun (a : α) (ha : a ∈ s) => h a ha (iff.mp mem_pi hg a ha)\n\ntheorem pi_disjoint_of_disjoint {α : Type u_1} [DecidableEq α] {δ : α → Type u_2} [(a : α) → DecidableEq (δ a)] {s : finset α} [DecidableEq ((a : α) → a ∈ s → δ a)] (t₁ : (a : α) → finset (δ a)) (t₂ : (a : α) → finset (δ a)) {a : α} (ha : a ∈ s) (h : disjoint (t₁ a) (t₂ a)) : disjoint (pi s t₁) (pi s t₂) := sorry\n\n", "meta": {"author": "AurelienSaue", "repo": "Mathlib4_auto", "sha": "590df64109b08190abe22358fabc3eae000943f2", "save_path": "github-repos/lean/AurelienSaue-Mathlib4_auto", "path": "github-repos/lean/AurelienSaue-Mathlib4_auto/Mathlib4_auto-590df64109b08190abe22358fabc3eae000943f2/Mathlib/data/finset/pi.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.403566839388498, "lm_q2_score": 0.039638839668221494, "lm_q1q2_score": 0.01599692124193157}} {"text": "import tactic\nimport category_theory.limits.shapes.pullbacks\n\nnamespace category_theory\nopen category_theory.limits\n\nvariables {C D : Type*} [category C] [category D] (e : C ≌ D)\n {X Y B : D} (f : X ⟶ B) (g : Y ⟶ B) [has_pullback (e.inverse.map f) (e.inverse.map g)]\n\nlemma equivalence.hom_eq_map {X Y : C} (f : e.functor.obj X ⟶ e.functor.obj Y)\n (g : X ⟶ Y) : e.inverse.map f = e.symm.counit.app _ ≫ g ≫ e.unit.app _ →\n f = e.functor.map g :=\nbegin\n intros h,\n change _ = (e.unit_iso.app _).inv ≫ g ≫ (e.unit_iso.app _).hom at h,\n rw iso.eq_inv_comp at h,\n replace h := h.symm,\n rw ← iso.eq_comp_inv at h,\n rw h,\n simp,\n nth_rewrite 0 ← category.id_comp f,\n simp_rw ← category.assoc,\n congr' 1,\n simp,\nend\n\n\nnoncomputable theory\n\n/-\nI would like to do something for more general shapes, but universes make this difficult\n(as usual...)\n-/\n\n@[simps]\ndef equivalence.pullback_cone : cone (cospan f g) :=\n{ X := e.functor.obj $ pullback (e.inverse.map f) (e.inverse.map g),\n π :=\n { app := λ i,\n match i with\n | none := e.functor.map pullback.fst ≫ e.counit.app X ≫ f\n | walking_cospan.left := e.functor.map pullback.fst ≫ e.counit.app X\n | walking_cospan.right := e.functor.map pullback.snd ≫ e.counit.app Y\n end,\n naturality' := begin\n rintro (i|i|i) (j|j|j) (h|h),\n { dsimp, simp only [category.id_comp, functor.map_id], dsimp, simp only [category.comp_id], },\n { dsimp, simp only [category.id_comp], dsimp [equivalence.pullback_cone._match_1],\n simp only [category.assoc], },\n { dsimp, simp only [category.id_comp, functor.map_id], dsimp, simp only [category.comp_id], },\n { unfold_aux,\n dsimp, simp, delta id_rhs,\n have : e.counit.app X ≫ f = e.functor.map (e.inverse.map f) ≫ e.counit.app B, by tidy,\n rw this, clear this,\n have : e.counit.app Y ≫ g = e.functor.map (e.inverse.map g) ≫ e.counit.app B, by tidy,\n rw this, clear this,\n simp_rw [← category.assoc, ← e.functor.map_comp, limits.pullback.condition] },\n { tidy }\n end } } .\n\nattribute [reassoc] equivalence.unit_inverse_comp\n\n-- This is a mess :-(\n-- Please fix before moving this file to mathlib!\ndef equivalence.is_limit_pullback_cone : limits.is_limit (e.pullback_cone f g) :=\n{ lift := λ S, e.symm.unit.app S.X ≫\n e.functor.map (pullback.lift (e.inverse.map (S.π.app walking_cospan.left))\n (e.inverse.map (S.π.app walking_cospan.right)) begin\n simp_rw ← e.inverse.map_comp,\n change e.inverse.map (_ ≫ (cospan f g).map walking_cospan.hom.inl) =\n e.inverse.map (_ ≫ (cospan f g).map walking_cospan.hom.inr),\n rw [S.w, S.w],\n end),\n fac' := begin\n rintros S (j|j|j),\n { dsimp [equivalence.pullback_cone._match_1],\n simp only [category.assoc],\n have : e.counit.app X ≫ f = e.functor.map (e.inverse.map f) ≫ e.counit.app B,\n { dsimp, simp only [equivalence.fun_inv_map, category.assoc, iso.inv_hom_id_app,\n nat_iso.cancel_nat_iso_hom_left], erw category.comp_id, },\n rw this, clear this,\n simp_rw [← category.assoc _ _ (e.counit.app B), ← e.functor.map_comp],\n simp only [functor.map_comp, pullback.lift_fst_assoc, equivalence.fun_inv_map,\n category.assoc, iso.inv_hom_id_app_assoc, iso.inv_hom_id_app],\n dsimp,\n simp only [category.comp_id],\n change _ ≫ (cospan f g).map walking_cospan.hom.inl = _,\n rw S.w },\n { dsimp [equivalence.pullback_cone._match_1],\n simp only [category.assoc],\n simp_rw [← category.assoc _ _ (e.counit.app X), ← e.functor.map_comp],\n simp only [pullback.lift_fst, equivalence.fun_inv_map, iso.inv_hom_id_app_assoc,\n category.assoc, iso.inv_hom_id_app],\n dsimp,\n rw [category.comp_id] },\n { dsimp [equivalence.pullback_cone._match_1],\n simp only [category.assoc],\n simp_rw [← category.assoc _ _ (e.counit.app Y), ← e.functor.map_comp],\n simp only [pullback.lift_snd, equivalence.fun_inv_map, iso.inv_hom_id_app_assoc,\n category.assoc, iso.inv_hom_id_app],\n dsimp,\n rw [category.comp_id] }\n end,\n uniq' := begin\n intros S m h,\n --dsimp at *,\n change m = (e.counit_iso.app S.X).inv ≫ _,\n rw iso.eq_inv_comp,\n apply equivalence.hom_eq_map,\n change _ = (e.unit_iso.app _).inv ≫ _ ≫ (e.unit_iso.app _).hom,\n rw iso.eq_inv_comp,\n symmetry,\n rw ← iso.eq_comp_inv,\n simp only [category.assoc],\n apply pullback.hom_ext,\n { simp only [functor.map_comp, pullback.lift_fst, iso.app_hom, iso.app_inv, category.assoc],\n specialize h walking_cospan.left,\n rw ← h,\n simp only [functor.map_comp, equivalence.inv_fun_map, category.assoc,\n equivalence.unit_inverse_comp_assoc, category.comp_id,\n equivalence.pullback_cone, equivalence.pullback_cone_π_app, functor.map_comp,\n equivalence.unit_inverse_comp], },\n { simp only [functor.map_comp, pullback.lift_snd, iso.app_hom, iso.app_inv, category.assoc],\n specialize h walking_cospan.right,\n rw ← h,\n simp only [functor.map_comp, equivalence.inv_fun_map, category.assoc,\n equivalence.unit_inverse_comp_assoc, category.comp_id,\n equivalence.pullback_cone, equivalence.pullback_cone_π_app, functor.map_comp,\n equivalence.unit_inverse_comp], }\n end } .\n\ninclude e\n\nlemma equivalence.has_pullback {X Y B : D} (f : X ⟶ B) (g : Y ⟶ B)\n [has_pullback (e.inverse.map f) (e.inverse.map g)] : has_pullback f g :=\nlimits.has_limit.mk ⟨e.pullback_cone _ _, e.is_limit_pullback_cone _ _⟩\n\nlemma equivalence.has_pullbacks [has_pullbacks C] : has_pullbacks D :=\nbegin\n apply has_pullbacks_of_has_limit_cospan _,\n intros X Y B f g,\n apply e.has_pullback,\nend\n\nend category_theory\n", "meta": {"author": "leanprover-community", "repo": "lean-liquid", "sha": "92f188bd17f34dbfefc92a83069577f708851aec", "save_path": "github-repos/lean/leanprover-community-lean-liquid", "path": "github-repos/lean/leanprover-community-lean-liquid/lean-liquid-92f188bd17f34dbfefc92a83069577f708851aec/src/for_mathlib/pullbacks.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4263215925474903, "lm_q2_score": 0.037326886273225016, "lm_q1q2_score": 0.015913257600840343}} {"text": "/- -----------------------------------------------------------------------\nThe topos of trees.\n----------------------------------------------------------------------- -/\n\nimport ..c1_basic\nimport ..c2_limits\n\nnamespace qp\n\nopen stdaux\n\nuniverse variables ℓobjx ℓhomx\n\n/-! #brief The topos of trees.\n-/\ndefinition TreeTopos : Cat\n:= PreShCat NatCat\n\n/-! #brief Action of the later endofunctor on objects.\n-/\ndefinition LaterObj.obj\n (F : TreeTopos^.obj)\n : ∀ (n : ℕ), Type\n| 0 := punit\n| (nat.succ n) := F^.obj n\n\n/-! #brief Action of the later endofunctor on objects.\n-/\ndefinition LaterObj.hom\n (F : TreeTopos^.obj)\n : ∀ (n₂ n₁ : ℕ) (ωn : n₁ ≤ n₂)\n , LaterObj.obj F n₂ → LaterObj.obj F n₁\n| n₂ 0 ωn x := punit.star\n| 0 (nat.succ n₁) ωn x := false.rec _ (by cases ωn)\n| (nat.succ n₂) (nat.succ n₁) ωn x := F^.hom (nat.le_of_succ_le_succ ωn) x\n\n/-! #brief Action of the later endofunctor on objects.\n-/\ntheorem LaterObj.hom.id\n (F : TreeTopos^.obj)\n : ∀ (n : ℕ)\n , LaterObj.hom F n n (nat.le_refl n) = @id (LaterObj.obj F n)\n| 0 := begin apply funext, intro u, cases u, trivial end\n| (nat.succ n) := F^.hom_id\n\n/-! #brief Action of the later endofunctor on objects.\n-/\ntheorem LaterObj.hom.circ\n (F : TreeTopos^.obj)\n : ∀ (n₃ n₂ n₁ : ℕ) (ωn₁₂ : n₁ ≤ n₂) (ωn₂₃ : n₂ ≤ n₃)\n , LaterObj.hom F n₃ n₁ (nat.le_trans ωn₁₂ ωn₂₃)\n = λ x, LaterObj.hom F n₂ n₁ ωn₁₂ (LaterObj.hom F n₃ n₂ ωn₂₃ x)\n| 0 0 0 ωn₁₂ ωn₂₃ := rfl\n| 0 0 (nat.succ n₁) ωn₁₂ ωn₂₃ := rfl\n| 0 (nat.succ n₂) 0 ωn₁₂ ωn₂₃ := rfl\n| (nat.succ n₃) 0 0 ωn₁₂ ωn₂₃ := rfl\n| 0 (nat.succ n₂) (nat.succ n₁) ωn₁₂ ωn₂₃ := by cases ωn₂₃\n| (nat.succ n₃) 0 (nat.succ n₁) ωn₁₂ ωn₂₃ := by cases ωn₁₂\n| (nat.succ n₃) (nat.succ n₂) 0 ωn₁₂ ωn₂₃ := rfl\n| (nat.succ n₃) (nat.succ n₂) (nat.succ n₁) ωn₁₂ ωn₂₃ := F^.hom_circ\n\n/-! #brief Action of the later endofunctor on objects.\n-/\ndefinition LaterObj\n (F : TreeTopos^.obj)\n : TreeTopos^.obj\n:= { obj := LaterObj.obj F\n , hom := LaterObj.hom F\n , hom_id := LaterObj.hom.id F\n , hom_circ := LaterObj.hom.circ F\n }\n\n/-! #brief Action of the later endofunctor on homs.\n-/\ndefinition LaterHom.com\n {F₁ F₂ : TreeTopos^.obj}\n (η : TreeTopos^.hom F₁ F₂)\n : ∀ (n : ℕ)\n , LaterObj.obj F₁ n → LaterObj.obj F₂ n\n| 0 := id\n| (nat.succ n) := η^.com n\n\n/-! #brief Action of the later endofunctor on homs.\n-/\ntheorem LaterHom.natural\n {F₁ F₂ : TreeTopos^.obj}\n (η : TreeTopos^.hom F₁ F₂)\n : ∀ (n₂ n₁ : ℕ) (ωn : n₁ ≤ n₂)\n , (λ x, LaterHom.com η n₁ (LaterObj.hom F₁ n₂ n₁ ωn x))\n = λ x, LaterObj.hom F₂ n₂ n₁ ωn (LaterHom.com η n₂ x)\n| 0 0 ωn := rfl\n| 0 (nat.succ n₁) ωn := by cases ωn\n| (nat.succ n₂) 0 ωn := rfl\n| (nat.succ n₂) (nat.succ n₁) ωn := η^.natural _\n\n\n/-! #brief Action of the later endofunctor on homs.\n-/\ndefinition LaterHom\n (F₁ F₂ : TreeTopos^.obj)\n (η : TreeTopos^.hom F₁ F₂)\n : TreeTopos^.hom (LaterObj F₁) (LaterObj F₂)\n:= { com := LaterHom.com η\n , natural := LaterHom.natural η\n }\n\n/-! #brief The later endofunctor.\n-/\ndefinition LaterFun : Fun TreeTopos TreeTopos\n:= { obj := LaterObj\n , hom := LaterHom\n , hom_id\n := λ F\n , begin\n apply NatTrans.eq,\n apply funext, intro n, cases n,\n { trivial },\n { trivial }\n end\n , hom_circ\n := λ F₁ F₂ F₃ η₂₃ η₁₂\n , begin\n apply NatTrans.eq,\n apply funext, intro n, cases n,\n { trivial },\n { trivial }\n end\n }\n\n/-! #brief The left adjoint of the later endofunctor.\n-/\ndefinition SoonerFun\n : Fun TreeTopos TreeTopos\n:= { obj := λ F, { obj := λ n, F^.obj (nat.succ n)\n , hom := λ n₂ n₁ ωn, F^.hom (nat.succ_le_succ ωn)\n , hom_id := λ n, F^.hom_id\n , hom_circ := λ n₃ n₂ n₁ ωn₁₂ ωn₂₃, F^.hom_circ\n }\n , hom := λ F₁ F₂ η, { com := λ n, η^.com (nat.succ n)\n , natural := λ n₂ n₁ ωn, η^.natural _\n }\n , hom_id\n := λ F\n , begin\n apply NatTrans.eq,\n apply funext, intro n,\n trivial\n end\n , hom_circ\n := λ F₁ F₂ F₃ η₂₃ η₁₂\n , begin\n apply NatTrans.eq,\n apply funext, intro n,\n trivial\n end\n }\n\n/-! #brief SoonerFun and LaterFun are adjoint.\n-/\ndefinition SoonerFun_LaterFun.adj\n : Adj SoonerFun LaterFun\n:= { counit\n := { com := λ F, { com := λ n x, x\n , natural := λ n₂ n₁ f, funext (λ x, rfl)\n }\n , natural := λ F₁ F₂ η, NatTrans.eq (funext (λ n, funext (λ x, rfl)))\n }\n , unit\n := { com := λ F, { com := λ n x, cast sorry x\n , natural := λ n₂ n₁ f, funext (λ x, sorry)\n }\n , natural := λ F₁ F₂ η, NatTrans.eq (funext (λ n, funext (λ x, sorry)))\n }\n , id_left := λ F, NatTrans.eq sorry\n , id_right := λ F, NatTrans.eq sorry\n }\n\n/-! #brief LaterFun preserves all limits.\n-/\ndefinition LaterFun.PresLimit\n {X : Cat.{ℓobjx ℓhomx}} (F : Fun X TreeTopos)\n : PresLimit F LaterFun\n:= Adj.right.PresLimit SoonerFun_LaterFun.adj F\n\n/-! #brief The next natural transformation.\n-/\ndefinition NextTrans.com (X : TreeTopos^.obj)\n : ∀ (n : ℕ)\n , X^.obj n → LaterObj.obj X n\n| 0 := λ u, punit.star\n| (nat.succ n) := X^.hom (nat.le_succ n)\n\n/-! #brief The next natural transformation.\n-/\ntheorem NextTrans.natural (X : TreeTopos^.obj)\n : ∀ (n₂ n₁ : ℕ) (ωn : n₁ ≤ n₂)\n , Cat.circ LeanCat (NextTrans.com X n₁) (X^.hom ωn)\n = Cat.circ LeanCat (LaterObj.hom X n₂ n₁ ωn) (NextTrans.com X n₂)\n| 0 0 ωn := rfl\n| 0 (nat.succ n₁) ωn := by cases ωn\n| (nat.succ n₂) 0 ωn := rfl\n| (nat.succ n₂) (nat.succ n₁) ωn\n:= begin\n refine eq.trans (eq.symm X^.hom_circ) _,\n refine eq.trans _ X^.hom_circ,\n trivial\n end\n\n/-! #brief The next natural transformation.\n-/\ndefinition NextTrans (X : TreeTopos^.obj)\n : TreeTopos^.hom X (LaterFun^.obj X)\n:= { com := NextTrans.com X\n , natural := NextTrans.natural X\n }\n\nend qp\n", "meta": {"author": "intoverflow", "repo": "qvr", "sha": "0cfcd33fe4bf8d93851a00cec5bfd21e77105d74", "save_path": "github-repos/lean/intoverflow-qvr", "path": "github-repos/lean/intoverflow-qvr/qvr-0cfcd33fe4bf8d93851a00cec5bfd21e77105d74/qp/p1_categories/c6_topos_of_trees/s1_topos_of_trees.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47268346176374826, "lm_q2_score": 0.033589503957117864, "lm_q1q2_score": 0.015877203009377592}} {"text": "import for_mathlib.ab4\nimport algebra.category.Module.colimits\nimport for_mathlib.AddCommGroup.ab4\n\nopen category_theory\nopen category_theory.limits\n\nlocal attribute [instance] category_theory.limits.has_zero_object.has_zero\n\nuniverses v'' v' v u'' u' u \n\nopen_locale classical\n\ninstance Module.forget₂_AddCommGroup_preserves_zero_morphisms {R : Type*} [ring R]\n : (forget₂ (Module R) AddCommGroup).preserves_zero_morphisms := ⟨⟩\n\ninstance Module.forget₂_AddCommGroup_faithful {R : Type*} [ring R]\n : faithful (forget₂ (Module R) AddCommGroup) :=\nbegin\n refine ⟨_⟩,\n intros X Y f g H,\n ext x, \n rw [← linear_map.to_add_monoid_hom_coe, ← linear_map.to_add_monoid_hom_coe],\n exact congr_arg2 _ H (refl x)\nend.\n\nnoncomputable\ninstance Module.forget₂_AddCommGroup_reflects_exact_sequences {R : Type*} [ring R]\n : functor.reflects_exact_sequences (forget₂ (Module R) AddCommGroup) := \nbegin\n apply functor.reflects_exact_sequences_of_preserves_zero_morphisms_of_faithful\nend\n\ninstance Module.forget₂_AddCommGroup_reflects_mono {R : Type*} [ring R]\n : functor.reflects_monomorphisms (forget₂ (Module R) AddCommGroup) := by apply_instance\n\ninstance Module.forget₂_AddCommGroup_preserves_mono {R : Type*} [ring R]\n : functor.preserves_monomorphisms (forget₂ (Module R) AddCommGroup) := by apply_instance\n\ninstance coextension.module_structure (R : Type*) [ring R] (G : Type*) [add_comm_group G]\n : module R (R →+ G) := {\n smul := λ r f, ⟨(λ x, f (x * r)), (by simp), (by { intros, simp [add_mul] })⟩,\n one_smul := by { intros, simp },\n mul_smul := by { intros, ext, simp [mul_assoc] },\n smul_add := by { intros, ext, simp },\n smul_zero := by { intros, ext, simp },\n add_smul := by { intros, ext, simp [mul_add] },\n zero_smul := by { intros, ext, simp }\n }.\n\ndef coextension.map' (R : Type*) [ring R] {G H : Type*} [add_comm_group G] [add_comm_group H]\n (ϕ : G →+ H) : (R →+ G) →ₗ[R] (R →+ H) := {\n to_fun := λ f, ⟨ϕ.comp f, by simp, by { intros, simp }⟩,\n map_add' := by { intros, ext, simp },\n map_smul' := by { intros, ext, simp, refl }\n }.\n\ndef Module.coextension (R : Type*) [ring R] : AddCommGroup ⥤ Module R := {\n obj := λ G, Module.of R (R →+ G),\n map := λ G H ϕ, Module.of_hom (coextension.map' R ϕ)\n}.\n\ndef Module.restriction_coextension_adj_unit (R : Type*) [ring R]\n (M : Type*) [add_comm_group M] [module R M] : M →ₗ[R] (R →+ M) := {\n to_fun := λ x, ⟨(λ r, r • x), zero_smul R x, (λ r s, add_smul r s x)⟩,\n map_add' := by { intros, ext, simp },\n map_smul' := by { intros, ext, simp, symmetry, apply mul_smul }\n }.\n\ndef Module.restriction_coextension_adj_counit (R : Type*) [ring R]\n (G : Type*) [add_comm_group G] : (R →+ G) →+ G := {\n to_fun := λ f, f 1,\n map_zero' := rfl,\n map_add' := λ x y, rfl\n }.\n\ndef Module.restriction_coextension_adj (R : Type*) [ring R]\n : forget₂ (Module R) AddCommGroup ⊣ Module.coextension R := \n adjunction.mk_of_unit_counit {\n unit := {\n app := λ M, Module.restriction_coextension_adj_unit R M,\n naturality' := by { intros, ext, symmetry, apply map_smul f }\n },\n counit := {\n app := λ G, Module.restriction_coextension_adj_counit R G,\n naturality' := by { intros, ext, refl }\n },\n left_triangle' := by { ext, exact one_smul _ _ },\n right_triangle' := by { ext M f r, exact congr_arg f.to_fun (one_mul r) } \n }.\n\ninstance Module.forget₂_AddCommGroup_preserves_coproduct {R : Type*} [ring R]\n {J : Type*} (f : J → Module R)\n : limits.preserves_colimit (discrete.functor f) (forget₂ (Module R) AddCommGroup) :=\n @preserves_colimits_of_shape.preserves_colimit _ _ _ _ _ _ _\n (@preserves_colimits_of_size.preserves_colimits_of_shape _ _ _ _ _\n (@preserves_colimits_of_size_shrink _ _ _ _ _\n (Module.restriction_coextension_adj R).left_adjoint_preserves_colimits) _ _) _\n\nlemma sigma_comparison_naturality {β : Type*} {C : Type*} [category C] {D : Type*} [category D]\n (G : C ⥤ D) {f g : β → C} (η : Π (b : β), f b ⟶ g b) [has_coproduct f] [has_coproduct g]\n [has_coproduct (λ (b : β), G.obj (f b))] [has_coproduct (λ (b : β), G.obj (g b))] \n : sigma_comparison G f\n ≫ G.map (colim_map (discrete.nat_trans (λ b', η b'.as) : discrete.functor f ⟶ discrete.functor g))\n = colim_map (discrete.nat_trans (λ b', G.map (η b'.as)) : discrete.functor (λ (b : β), G.obj (f b)) ⟶ discrete.functor (λ (b : β), G.obj (g b)))\n ≫ sigma_comparison G g :=\nbegin\n ext,\n simp [sigma_comparison],\n rw [← G.map_comp, ← G.map_comp],\n refine congr_arg _ _,\n delta sigma.ι,\n simp\nend\n\n-- not sure about the universes here\nlemma AB4_of_preserves_coproduct_and_reflects_and_preserves_mono {V W : Type u}\n [category.{v} V] [category.{v} W] [abelian V] [abelian W]\n [i : has_coproducts V] [i' : has_coproducts W]\n (F : V ⥤ W) [F.reflects_monomorphisms] [F.preserves_monomorphisms]\n [∀ (J : Type v) (f : J → V), limits.preserves_colimit (discrete.functor f) F]\n [h : @AB4 W _ i'] : @AB4 V _ i := \nbegin\n constructor,\n introsI,\n apply F.mono_of_mono_map,\n suffices : mono (F.map (colim_map (discrete.nat_trans (λ a', f a'.as) : discrete.functor X ⟶ discrete.functor Y))),\n { convert this,\n delta sigma.desc cofan.mk colim_map is_colimit.map cocones.precompose,\n congr,\n ext a, cases a, refl },\n have H := sigma_comparison_naturality F f,\n rw ← is_iso.eq_inv_comp at H,\n rw H,\n apply_with mono_comp {instances:=ff},\n { apply_instance },\n { apply_with mono_comp {instances:=ff},\n { convert AB4.cond (F.obj ∘ X) (F.obj ∘ Y) (λ a, F.map (f a)) (λ a, F.map_mono (f a)),\n delta sigma.desc cofan.mk colim_map is_colimit.map cocones.precompose, dsimp,\n congr,\n ext a, cases a, refl },\n { apply_instance } }\nend\n\ninstance AB4 {R : Type u} [ring R] : AB4 (Module.{(max v u) u} R) :=\n @AB4_of_preserves_coproduct_and_reflects_and_preserves_mono _ _ _ _ _ _ _ _\n (forget₂ (Module.{(max v u) u} R) AddCommGroup.{max v u})\n _ _ \n (λ J f, @preserves_colimits_of_shape.preserves_colimit _ _ _ _ _ _ _\n (@preserves_colimits_of_size.preserves_colimits_of_shape _ _ _ _ _ \n (Module.restriction_coextension_adj.{u v} R).left_adjoint_preserves_colimits\n (discrete J) _) (discrete.functor f)) _.", "meta": {"author": "Shamrock-Frost", "repo": "BrouwerFixedPoint", "sha": "52f48d25068df0eadf3df5b2ede7bcb087d30527", "save_path": "github-repos/lean/Shamrock-Frost-BrouwerFixedPoint", "path": "github-repos/lean/Shamrock-Frost-BrouwerFixedPoint/BrouwerFixedPoint-52f48d25068df0eadf3df5b2ede7bcb087d30527/src/Module_AB4.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4726834617637482, "lm_q2_score": 0.03358950347340756, "lm_q1q2_score": 0.01587720278073573}} {"text": "import Lean.Elab\nopen Lean.Elab.Tactic\nopen Lean.Elab\n\nsyntax (name := poyo) \"foo\" : tactic\n@[tactic poyo]\ndef evalpoyo : Tactic := fun stx => do\n logInfo m!\"

{1}

\"\n\ndef Set (α : Type u) := α → Prop\ndef Set.in (s : Set α) (a : α) := s a\n\nnotation:50 a \" ∈ \" s:50 => Set.in s a\n\ndef Set.pred (p : α → Prop) : Set α := p\n\nnotation \"{\" a \"|\" p \"}\" => Set.pred (fun a => p)\n\ndef Set.union (s₁ s₂ : Set α) : Set α :=\n { a | a ∈ s₁ ∨ a ∈ s₂ }\n\ninfix:65 \" ∪ \" => Set.union\n\ndef Set.inter (s₁ s₂ : Set α) : Set α :=\n { a | a ∈ s₁ ∧ a ∈ s₂ }\n\ninfix:70 \" ∩ \" => Set.inter\n\ninstance (s : Set α) [h : Decidable (s a)] : Decidable (a ∈ Set.pred s) := h\n\ninstance (s₁ s₂ : Set α) [Decidable (a ∈ s₁)] [Decidable (a ∈ s₂)] : Decidable (a ∈ s₁ ∩ s₂) :=\n inferInstanceAs (Decidable (_ ∧ _))\n\ninstance (s₁ s₂ : Set α) [Decidable (a ∈ s₁)] [Decidable (a ∈ s₂)] : Decidable (a ∈ s₁ ∪ s₂) :=\n inferInstanceAs (Decidable (_ ∨ _))\n\ndef main : IO Unit :=\n IO.println \"Hello, world!\"\n\nabbrev ℕ := Nat\n\ndef a := 1\n\n#check ℕ\n#check evalpoyo\n#check (1,2,3)\n#check 3 * 3 = 9\n#check (⟨9, ⟨3, rfl⟩⟩:{m: ℕ // ∃r, r * r = m})\n\n\ntheorem test1 {α} (a b : α) (as bs : List α) (h : a::as = b::bs) : a = b :=\nby {\n foo;\n skip;\n trace_state;\n injection h;\n assumption;\n}\n\n\n\ndef b:{ll: List (List ℕ) //∃m r, ll.length = m ∧ r * r = m ∧ m > 0} :=\n ⟨[[0,3,2,1], [2,1,0,3], [3,0,1,2], [1,2,3,0]],\n by {\n let m := 4; let r := 2;\n exists m;\n exists r;\n simp;\n }⟩\n\nmacro \"inductionFinTerm \" term:term \" with \" v:ident lt:ident t:tacticSeq : tactic => `(induction $term with | mk $v $lt => $t)\nsyntax \"repeatWithNat \" term \" => \" tacticSeq : tactic\nmacro_rules\n | `(tactic| repeatWithNat $num => $seq) => `(tactic| first | let trialNum := $num; ($seq); repeatWithNat (Nat.succ $num) => $seq | skip)\n\n\ndef h: ∃x, x = 0 := Subtype.existsOfSubtype ⟨0, by rfl⟩\nnoncomputable def aaaa: Nat := sorry\n#check Classical.choice\nnoncomputable def indefiniteDescription {α : Sort u} {p : α → Prop} (h : ∃ x, p x) : {x // p x} :=\n Classical.choice <| let ⟨x, px⟩ := h; ⟨⟨x, px⟩⟩\nnoncomputable def hoge {α : Sort u} {p : α → Prop} (h : ∃ x, p x) : Nonempty {x // p x} :=\nlet ⟨w, prop⟩ := h; ⟨w, prop⟩\n--てすと,カタカナ,漢字.123bcs\n\nconstant magic (h : ∃ n : ℕ, n > 0) : ℕ\naxiom magic_extract (n h) : magic ⟨n, h⟩ = n\n\nexample : false :=\nhave h1 : magic ⟨1, sorry⟩ = 1 := magic_extract _ _;\nhave h2 : magic ⟨2, sorry⟩ = 2 := magic_extract _ _;\nhave proof_irrel : magic ⟨1, sorry⟩ = magic ⟨2, sorry⟩ := rfl;\nabsurd (h1.symm.trans $ proof_irrel.trans h2) sorry", "meta": {"author": "amamama", "repo": "fuzzy-octo-palm-tree", "sha": "12685c23ab4a5bcf3187fe87594a629dbb1d1288", "save_path": "github-repos/lean/amamama-fuzzy-octo-palm-tree", "path": "github-repos/lean/amamama-fuzzy-octo-palm-tree/fuzzy-octo-palm-tree-12685c23ab4a5bcf3187fe87594a629dbb1d1288/lean4.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43014733397551624, "lm_q2_score": 0.03676947003380994, "lm_q1q2_score": 0.01581628950673598}} {"text": "import coding function\nimport computability.reduce\nopen encodable denumerable part\n\nuniverses u v\n\nlocal attribute [simp] set.set_of_app_iff\n\nlemma bool.to_bool_ext (p : Prop) (D0 D1 : decidable p) :\n @to_bool p D0 = @to_bool p D1 := \nby { cases (@decidable.em p D0) with h,\n simp[to_bool_tt h], exact h, simp[to_bool_ff h], exact h, }\n\nlemma bool.to_bool_ext_iff {p q : Prop} (r : p ↔ q) (D0 : decidable p) (D1 : decidable q) :\n @to_bool _ D0 = @to_bool _ D1 := \nby { cases (@decidable.em p D0) with h, simp[to_bool_tt h],\n exact r.mp h, simp[to_bool_ff h], exact (not_congr r).mp h, }\n\nlemma bool.to_bool_ext_bnot (p : Prop) (D0 : decidable p) (D1 : decidable ¬p) :\n @to_bool _ D1 = !@to_bool _ D0 := \nby { cases (@decidable.em p D0) with h,\n simp[to_bool_tt h], exact h, simp[to_bool_ff h], exact h, }\n\nlemma encode_to_bool_eq {α} {A : set α} (D0 D1 : decidable_pred A) :\n (λ n, (@to_bool (A n) (D0 n))) = (λ n, (@to_bool (A n) (D1 n))) := funext (λ x, by rw bool.to_bool_ext)\n\nlemma decidable_pred.compl {α} {A : set α} :\n decidable_pred A → decidable_pred Aᶜ := λ h x, @not.decidable _ (h x)\n\nnoncomputable def chr {α} (p : set α) : α → bool := λ x : α,\ndecidable.cases_on (classical.dec (p x)) (λ h₁, bool.ff) (λ h₂, bool.tt)\n\n@[simp] theorem chr_tt_iff {α} (A : set α) (x : α) : chr A x = tt ↔ A x :=\nby simp[chr]; cases (classical.dec (A x)); simp[h]\n\n@[simp] theorem chr_tt_iff_r {α} (A : set α) (x : α) : tt = chr A x ↔ A x :=\nby simp[chr]; cases (classical.dec (A x)); simp[h]\n\n@[simp] theorem chr_ff_iff {α} (A : set α) (x : α) : chr A x = ff ↔ ¬A x :=\nby simp[chr]; cases (classical.dec (A x)); simp[h]\n\n@[simp] theorem chr_ff_iff_r {α} (A : set α) (x : α) : ff = chr A x ↔ ¬A x :=\nby simp[chr]; cases (classical.dec (A x)); simp[h]\n\ntheorem chr_iff {α} (A : set α) (x : α) (b : bool) : chr A x = b ↔ (A x ↔ b = tt) :=\nby cases b; simp\n\n@[simp] theorem chr_app_iff {α} (A : set α) (x : α) : chr A x ↔ A x :=\nby simp[chr]; cases (classical.dec (A x)); simp[h]\n\ntheorem chr_eq_to_bool {α} (A : set α) (x : α) [decidable (A x)] : chr A x = to_bool (A x) :=\nby simp[chr_iff]\n\ntheorem to_bool_chr_eq {α} (A : set α) (x : α) (D : decidable (A x)) :\n to_bool (A x) = chr A x :=\nby { cases (@decidable.em (A x) D) with h,\n simp[to_bool_tt h, (chr_tt_iff _ _).2 h],\n simp[to_bool_ff h, (chr_ff_iff _ _).2 h] }\n\ntheorem chr_ext {α β} {A : set α} {B : set β} {x y} : chr A x = chr B y ↔ (A x ↔ B y) :=\nbegin\n split,\n { assume h,\n cases e : chr A x, \n have ax := (chr_ff_iff _ _).mp e,\n have bx := (chr_ff_iff B y).mp (by simp[←h, e]), simp[ax,bx],\n have ax := (chr_tt_iff _ _).mp e,\n have bx := (chr_tt_iff B y).mp (by simp[←h, e]), simp[ax,bx] },\n { assume h, \n cases e : chr B y,\n have bx := (chr_ff_iff _ _).mp e,\n exact (chr_ff_iff A x).mpr (by simp [h, bx]),\n have bx := (chr_tt_iff _ _).mp e,\n exact (chr_tt_iff A x).mpr (by simp [h, bx]) }\nend\n\n@[simp] lemma chr_coe_bool {α} (f : α → bool) : chr {x | f x = tt} = f :=\nby funext a; cases C : f a; simp; exact C\n\ndef rre_pred {α β σ} [primcodable α] [primcodable β] [primcodable σ]\n (p : set α) (f : β →. σ) : Prop :=\n(λ a, part.assert (p a) (λ _, part.some ())) partrec_in f\n\ninfix ` re_in `:80 := rre_pred\nprefix `r.e. `:80 := re_pred\n\ndef rre_pred_tot {α β σ} [primcodable α] [primcodable β] [primcodable σ]\n (p : set α) (f : β → σ) : Prop := p re_in ↑ᵣf\n\ninfix ` re_in! `:80 := rre_pred_tot\n\ntheorem rre_pred.re {α β σ} [primcodable α] [primcodable β] [primcodable σ]\n {A : set α} {f : β →. σ} (hA : A re_in f) (hf : partrec f) : r.e. A :=\nhA.le_part_part hf\n\ntheorem rre_pred.re0 {α} [primcodable α]\n {A : set α} (hA : A re_in! chr (∅ : set ℕ)) : r.e. A :=\nby { have : partrec ↑ᵣ(chr ∅ : ℕ → bool),\n { exact ((computable.const ff).of_eq $ λ x,\n by { symmetry, simp [chr_ff_iff], exact not_false }) },\n exact hA.re this }\n\ntheorem rre_in_0_iff_re {α} [primcodable α] {A : set α} :\n A re_in! chr (∅ : set ℕ) ↔ r.e. A :=\n⟨rre_pred.re0, partrec.to_rpart⟩\n\ndef rcomputable_pred {α β γ} [primcodable α] [primcodable β] [primcodable γ] (A : set α) (o : β →. γ) : Prop := \n∃ [D0 : decidable_pred A],\nby exactI (λ x, to_bool (A x)) computable_in o\n\ndef t_reducible {α β} [primcodable α] [primcodable β] (A : set α) (B : set β) : Prop := \n∃ [D0 : decidable_pred A] [D1 : decidable_pred B],\nby exactI (λ x, to_bool (A x)) computable_in! (λ x, to_bool (B x)) \n\ninfix ` ≤ₜ `:50 := t_reducible\n\n@[reducible] def t_irreducible {α β} [primcodable α] [primcodable β] (A : set α) (B : set β) : Prop := ¬A ≤ₜ B\n\ninfix ` ≰ₜ ` :50 := t_irreducible\n\n@[reducible] def t_reducible_lt {α β} [primcodable α] [primcodable β] (A : set α) (B : set β) : Prop :=\nA ≤ₜ B ∧ ¬B ≤ₜ A\n\ninfix ` <ₜ `:50 := t_reducible_lt\n\ndef t_reducible_equiv {α β} [primcodable α] [primcodable β] (A : set α) (B : set β) : Prop :=\nA ≤ₜ B ∧ B ≤ₜ A\n\ninfix ` ≡ₜ `:50 := t_reducible_equiv\n\ndef productive (A : set ℕ) : Prop :=\n∃ φ : ℕ →. ℕ, partrec φ ∧ ∀ i : ℕ, W⟦i⟧ₙ⁰ ⊆ A → ∃ z, z ∈ φ i ∧ z ∈ A ∧ z ∉ W⟦i⟧ₙ⁰\n\ndef creative (A : set ℕ) : Prop := r.e. A ∧ productive Aᶜ\n\ndef immune (A : set ℕ) : Prop := infinite A ∧ ∀ e, infinite W⟦e⟧ₙ⁰ → W⟦e⟧ₙ⁰ ∩ Aᶜ ≠ ∅\n\ndef simple (A : set ℕ) : Prop := r.e. A ∧ immune Aᶜ \n\nvariables {α : Type*} {β : Type*} {γ : Type*} {σ : Type*} {τ : Type*} {μ : Type*}\nvariables [primcodable α] [primcodable β] [primcodable γ] [primcodable σ] [primcodable τ] [primcodable μ]\n\ntheorem classical_iff {A : set α} {B : set β} :\n A ≤ₜ B ↔ chr A computable_in! (chr B) :=\nby simp[t_reducible, to_bool_chr_eq]; exact\n ⟨λ ⟨_, _, h⟩, h, λ h, ⟨classical.dec_pred _, classical.dec_pred _, h⟩⟩\n\ntheorem t_reducible.of_eq {A B : set α} {C : set β} (hA : A ≤ₜ C) (H : ∀ n, A n ↔ B n) : B ≤ₜ C :=\n(set.ext H : A = B) ▸ hA\n\n@[refl] theorem t_reducible.refl (A : set α) [D : decidable_pred A] : A ≤ₜ A := ⟨D, D, nat.rpartrec.refl⟩\n\n@[trans] theorem t_reducible.trans {A : set α} {B : set β} {C : set γ} :\n A ≤ₜ B → B ≤ₜ C → A ≤ₜ C :=\nλ ⟨Da, Db, hab⟩ ⟨Db0, Dc, hbc⟩,\n⟨Da, Dc, by simp only [encode_to_bool_eq Db Db0] at hab; exact nat.rpartrec.trans hab hbc⟩\n\n@[refl] theorem t_reducible_equiv.refl\n (A : set α) [D : decidable_pred A] :\n A ≡ₜ A :=\n⟨t_reducible.refl A, t_reducible.refl A⟩\n\n@[symm] theorem t_reducible_equiv.symm\n {A : set α} {B : set β} :\n A ≡ₜ B → B ≡ₜ A :=\nand.swap\n\n@[trans] theorem t_reducible_equiv.trans \n {A : set α} {B : set β} {C : set γ} :\n A ≡ₜ B → B ≡ₜ C → A ≡ₜ C :=\nλ ⟨ab, ba⟩ ⟨bc, cb⟩, ⟨t_reducible.trans ab bc, t_reducible.trans cb ba⟩\n\ntheorem many_one_reducible.to_turing {A : set α} {B : set β} [DA : decidable_pred A] [DB : decidable_pred B] :\n A ≤₀ B → A ≤ₜ B := λ h,\n⟨DA, DB, by { rcases h with ⟨f, cf, hf⟩,\n exact ((rcomputable.refl.comp (cf.to_rcomp)).of_eq $ λ n, by simp [hf]) }⟩\n\ntheorem one_one_reducible.to_turing {A : set α} {B : set β} [DA : decidable_pred A] [DB : decidable_pred B] :\n A ≤₁ B → A ≤ₜ B := λ h, h.to_many_one.to_turing\n\ntheorem reducible_compl (A : set α) [D : decidable_pred A] : Aᶜ ≤ₜ A :=\nhave Dc : decidable_pred Aᶜ, from D.compl,\nhave e0 : ∀ x, @to_bool (Aᶜ x) (Dc x) = !to_bool (A x), from λ x, bool.to_bool_ext_bnot _ _ _,\nhave cb : computable bnot, from (primrec.dom_bool _).to_comp,\n⟨Dc, D, (cb.to_rpart.comp rcomputable.refl).of_eq $ λ x, by simp[e0]⟩\n\ntheorem equiv_compl (A : set α) [D : decidable_pred A] : Aᶜ ≡ₜ A :=\nhave cc : Aᶜᶜ = A, from compl_compl A,\n⟨reducible_compl A, by { \n suffices : Aᶜᶜ ≤ₜ Aᶜ, rw cc at this, exact this, exact @reducible_compl _ _ Aᶜ D.compl, }⟩ \n\ntheorem computable_le {A : set α} (B : set β) [D : decidable_pred B] :\n computable_pred A → A ≤ₜ B :=\nλ ⟨D0, hA⟩, ⟨D0, D, nat.rpartrec.of_partrec _ hA⟩\n\ntheorem le_computable_computable {A : set α} {B : set β} :\n B ≤ₜ A → computable_pred A → computable_pred B := λ ⟨Db, Da, h⟩ ⟨Da0, hA⟩,\n⟨Db, by { simp only [computable, partrec, encode_to_bool_eq Da0 Da] at hA,\n exact rpartrec.le_part_part h hA}⟩\n\ntheorem computable_equiv {A : set α} {B : set β} :\n computable_pred A → computable_pred B → A ≡ₜ B :=\nλ ⟨Da, ca⟩ ⟨Db, cb⟩, ⟨@computable_le _ _ _ _ A B Db ⟨Da, ca⟩, @computable_le _ _ _ _ B A Da ⟨Db, cb⟩⟩\n\ntheorem computable_0 : computable_pred (∅ : set α) := \n⟨λ x, decidable.false, ((computable.const ff).of_eq $ λ x, rfl)⟩\n\ntheorem re_pred_0 : r.e. (∅ : set α) := \npartrec.none.of_eq (λ x, by {rw[show (∅ : set α) x = false, by refl], symmetry, simp[part.eq_none_iff] })\n\ntheorem degree0 (A : set α) :\n computable_pred A ↔ A ≡ₜ (∅ : set β) := \n⟨λ ⟨D, h⟩, ⟨computable_le _ ⟨D, h⟩, @computable_le _ _ _ _ _ _ D computable_0⟩,\n λ ⟨h, _⟩, le_computable_computable h computable_0⟩\n\n theorem computable_pred_iff_le {A : set α} :\n computable_pred A ↔ A ≤ₜ (∅ : set ℕ) := \n⟨λ ⟨D, h⟩, computable_le _ ⟨D, h⟩,\n λ h, le_computable_computable h computable_0⟩\n\ntheorem degree0' (A : set α) : computable_pred A ↔ A ≡ₜ (∅ : set ℕ) := degree0 A\n\ndef Join (A : ℕ → set ℕ) : set ℕ := {x | x.unpair.1 ∈ A x.unpair.2}\n\nprefix `⨁`:90 := Join\n\ntheorem Join_one_one_reducible (A : ℕ → set ℕ) [D : ∀ n, decidable_pred (A n)] (n) : A n ≤₁ ⨁A :=\nbegin\n let f := (λ m : ℕ, m.mkpair n),\n have cf : computable f := (primrec₂.mkpair.comp primrec.id (primrec.const n)).to_comp,\n refine ⟨f, cf, _, _⟩,\n { intros x y h, simp[f] at h, have : x = (x.mkpair n).unpair.1, simp,\n rw this, rw h, simp },\n { intros x, simp [Join], refl }\nend\n\ntheorem Join_le (A : ℕ → set ℕ) [DA : ∀ n, decidable_pred (A n)] \n (B : set ℕ) [DB : decidable_pred B] (hA : (λ x y, to_bool (A x y)) computable₂_in! λ x, to_bool (B x)) : ⨁A ≤ₜ B :=\n⟨λ a, DA (nat.unpair a).2 (nat.unpair a).1, DB, by { simp[Join],\n refine hA.comp (rcomputable.snd.comp rcomputable.nat_unpaired) (rcomputable.fst.comp rcomputable.nat_unpaired) }⟩\n\ndef Join₂ (A B : set ℕ) := ⨁(λ n, if n = 0 then A else if n = 1 then B else {})\n\ntheorem le_Join₂_left (A B : set ℕ) [DA : decidable_pred A] [DB : decidable_pred B] : A ≤₁ Join₂ A B :=\n@Join_one_one_reducible (λ n, if n = 0 then A else if n = 1 then B else {})\n (λ n a, by { cases n; simp, { exact DA a }, cases n; simp, { exact DB a }, { exact decidable.false } }) 0\n\ntheorem le_Join₂_right (A B : set ℕ) [DA : decidable_pred A] [DB : decidable_pred B] : B ≤₁ Join₂ A B :=\n@Join_one_one_reducible (λ n, if n = 0 then A else if n = 1 then B else {})\n (λ n a, by { cases n; simp, { exact DA a }, cases n; simp, { exact DB a }, { exact decidable.false } }) 1\n\ntheorem Join₂_le (A B C : set ℕ) [DA : decidable_pred A] [DB : decidable_pred B] [DC : decidable_pred C]\n (hA : A ≤ₜ C) (hB : B ≤ₜ C) : Join₂ A B ≤ₜ C :=\n@Join_le (λ n, if n = 0 then A else if n = 1 then B else {})\n (λ n a, by { cases n; simp, { exact DA a }, cases n; simp, { exact DB a }, { exact decidable.false } })\n C DC (by { rcases hA with ⟨_, _, cA⟩, rcases hB with ⟨_, _, cB⟩,\n simp,\n suffices : (λ (x y : ℕ), if x = 0 then (to_bool (A y)) else if x = 1 then to_bool (B y) else ff) computable₂_in! λ x, to_bool (C x),\n exact this.of_eq (λ n m, by { cases n; simp, cases n; simp[has_emptyc.emptyc] }),\n refine rcomputable.ite (rcomputable.to_bool_eq ℕ rcomputable.fst (rcomputable.const 0)) _ _,\n exact cast (by { congr, funext x, \n exact (@bool.to_bool_eq (A x.snd) (A x.snd) (hA_w x.snd) (DA x.snd)).mpr (by refl), \n funext x, simp }) (cA.comp rcomputable.snd),\n refine rcomputable.ite (rcomputable.to_bool_eq ℕ rcomputable.fst (rcomputable.const 1)) _ (rcomputable.const ff),\n exact cast (by { congr, funext x, \n exact (@bool.to_bool_eq (B x.snd) (B x.snd) (hB_w x.snd) (DB x.snd)).mpr (by refl), \n funext x, simp }) (cB.comp rcomputable.snd) })\n\nsection classical\nlocal attribute [instance, priority 0] classical.prop_decidable\nopen rpartrec\n\ntheorem cond_if_eq {α β} (p : set α) (x) (a b : β) :\n cond (chr p x) a b = if p x then a else b :=\nby {by_cases h : p x; simp [h], simp [(chr_tt_iff p x).mpr h], simp [(chr_ff_iff p x).mpr h] }\n\ndef Jump (A : set ℕ) : set ℕ := {x | (⟦x.unpair.1⟧ₙ^(chr A) x.unpair.2).dom}\n\nnotation A`′`:1200 := Jump A\n\n@[simp] def Jump_itr : ℕ → set ℕ → set ℕ\n| 0 A := A\n| (n+1) A := (Jump_itr n A)′\n\ntheorem lt_Jump (A : set ℕ) : A <ₜ A′ := \n⟨classical_iff.mpr\n begin\n show chr A computable_in! chr A′,\n have : ∃ e, ∀ x, (⟦e⟧ₙ^(chr A) x).dom ↔ A x,\n { have : ∃ e, ⟦e⟧ₙ^(chr A) = λ a, cond (chr A a) (some 0) none :=\n exists_index.mp (bool_to_part (chr A)),\n rcases this with ⟨e, he⟩,\n refine ⟨e, λ x, _⟩,\n show (⟦e⟧ₙ^(chr A) x).dom ↔ A x,\n simp [he],\n cases e : chr A x,\n simp[(chr_ff_iff _ _).1 e], rintros ⟨f, _⟩, \n simp[(chr_tt_iff _ _).1 e] },\n rcases this with ⟨e, he⟩,\n let f := λ x, chr A′ (e.mkpair x),\n have lmm_f : f computable_in! chr A′ :=\n (rcomputable.refl.comp (primrec₂.mkpair.comp (primrec.const e) primrec.id).to_rcomp),\n have : f = chr A,\n { funext x, simp[f, Jump, chr_ext, set.set_of_app_iff, he], },\n simp [←this], exact lmm_f,\n end,\n λ h : A′ ≤ₜ A,\n begin\n have l0 : chr A′ computable_in! chr A := classical_iff.mp h,\n have : ∃ e, ∀ x : ℕ, (⟦e⟧ₙ^(chr A) x).dom ↔ (x.mkpair x) ∉ A′,\n { let f : ℕ →. ℕ := (λ a, cond (chr A′ (a.mkpair a)) none (some 0)),\n have : f partrec_in! chr A := \n ((rpartrec.cond (rpartrec.refl_in $ (chr A′ : ℕ →. bool))\n partrec.none.to_rpart (rcomputable.const 0)).comp\n (primrec₂.mkpair.comp primrec.id primrec.id).to_rcomp).trans l0,\n have : ∃ e, ⟦e⟧ₙ^(chr A) = f := exists_index.mp this,\n rcases this with ⟨e, he⟩,\n refine ⟨e, λ x, _⟩,\n simp[he, set.mem_def, f],\n cases e : chr A′ (x.mkpair x),\n simp[(chr_ff_iff _ _).1 e],\n simp[(chr_tt_iff _ _).1 e], rintros ⟨_, _⟩ },\n rcases this with ⟨e, he⟩,\n have : (e.mkpair e) ∉ A′ ↔ (e.mkpair e) ∈ A′,\n calc\n (e.mkpair e) ∉ A′ ↔ ¬(⟦e⟧ₙ^(chr A) e).dom : by simp[Jump]\n ... ↔ (e.mkpair e) ∈ A′ : by simp[he],\n show false, from (not_iff_self _).mp this\n end⟩\n\ntheorem le_le_Jump {A B : set ℕ} : A ≤ₜ B → A′ ≤₁ B′ := λ h,\nbegin\n have h' := classical_iff.mp h,\n let f := (λ x : ℕ, ⟦x.unpair.1⟧ₙ^(chr A) x.unpair.2),\n have : ∃ e, ⟦e⟧ₙ^(chr B) = f,\n { have := (rpartrec.univ_tot ℕ ℕ (primrec.fst.comp primrec.unpair).to_rcomp h'\n (primrec.snd.comp primrec.unpair).to_rcomp), \n exact exists_index.mp this },\n rcases this with ⟨e, lmm_e⟩,\n have iff : ∀ x, A′ x ↔ B′ (e.mkpair x),\n { simp [Jump, lmm_e] },\n have pi : primrec e.mkpair := primrec₂.mkpair.comp (primrec.const e) (primrec.id),\n have inj : function.injective e.mkpair,\n { intros x y, intros h,\n have : x = (e.mkpair x).unpair.2, simp,\n rw this, rw h, simp }, \n refine ⟨e.mkpair, pi.to_comp, inj, iff⟩,\nend\n\ntheorem le_compl_of_le {A B : set ℕ} : A ≤₁ B → Aᶜ ≤₁ Bᶜ := λ ⟨f, comp, inj, h⟩,\n⟨f, comp, inj, λ x, ⟨λ h₁ h₂, h₁ ((h x).mpr h₂), λ h₁ h₂, h₁ ((h x).mp h₂)⟩⟩\n\ntheorem le1_compl_iff {A B : set ℕ} : Aᶜ ≤₁ Bᶜ ↔ A ≤₁ B :=\n⟨λ h, by { have := le_compl_of_le h, simp at this, exact this }, le_compl_of_le⟩\n\nopen primrec\n\nlemma rre_pred_iff {p : set α} {f : β →. σ} :\n p re_in f ↔ ∃ q : ℕ →. ℕ, q partrec_in f ∧ (∀ x, p x ↔ (q $ encode x).dom) :=\nbegin\n split; assume h,\n { let q : ℕ →. ℕ := \n λ n, part.bind (decode α n) (λ a, part.assert (p a) (λ (_ : p a), some 0)),\n have c : q partrec_in f :=\n (computable.decode.of_option.to_rpart).bind (h.comp rcomputable.snd),\n refine ⟨q, c, λ x, _⟩, \n simp [q, part.some, part.assert, encodek] },\n { rcases h with ⟨q, pq, hq⟩,\n let g : α →. unit := (λ x, (q (encode x)).map (λ x, ())),\n have : g partrec_in f :=\n (pq.comp computable.encode.to_rpart).map (rcomputable.const ()),\n exact (this.of_eq $ λ x, by {\n simp[g], apply part.ext, intros u, simp[hq, dom_iff_mem] }) }\nend\n\nlemma rre_pred_iff' {A : set α} {f : β →. σ} :\n A re_in f ↔ ∃ q : α →. ℕ, q partrec_in f ∧ (∀ x, A x ↔ (q x).dom) :=\nbegin\n split; assume h,\n { let q : α →. ℕ := (λ a, part.assert (A a) (λ (_ : A a), some 0)),\n refine ⟨q, h, λ x, _⟩, \n simp [q, part.some, part.assert, encodek] },\n { rcases h with ⟨q, pq, hq⟩,\n let g : α →. unit := (λ x, (q x).map (λ x, ())),\n have : g partrec_in f :=\n (pq.comp computable.encode.to_rpart).map (rcomputable.const ()),\n exact (this.of_eq $ λ x, by {\n simp[g], apply part.ext, intros u, simp[hq, dom_iff_mem] }) }\nend\n\nlemma rre_pred_iff_exists_index {A : set α} {f : β → σ} :\n A re_in! f ↔ ∃ e : ℕ, A = re_set α ℕ ↑ₒf e :=\n⟨λ h, begin\n rcases rre_pred_iff'.mp h with ⟨q, partrec, h⟩,\n rcases exists_index.mp partrec with ⟨e, rfl⟩,\n refine ⟨e, set.ext h⟩ \n end,\n by {rintros ⟨e, rfl⟩, refine rre_pred_iff'.mpr ⟨⟦e⟧^f, univ_partrec_in, λ x, by simp[re_set]⟩ }⟩\n\nlemma rre_pred.rre {f : α →. σ} {g : β →. τ} {A : set γ} :\n A re_in f → f partrec_in g → A re_in g :=\nby simp [rre_pred_iff]; exact λ q pq h pf, ⟨q, pq.trans pf, h⟩\n\nlemma rre_pred.rre' {A : set α} {B : set β} {C : set γ} :\n A re_in! chr B → B ≤ₜ C → A re_in! chr C :=\nby simp[classical_iff]; exact rre_pred.rre\n\ntheorem t_reducible.rre {A : set α} {B : set β} :\n A ≤ₜ B → A re_in! chr B := λ h,\nbegin\n have : (λ a, cond (chr A a) (some ()) none) partrec_in! chr B,\n { refine rpartrec.cond (classical_iff.mp h) (rcomputable.const _) rpartrec.none },\n exact (this.of_eq $ λ a,\n by { apply part.ext, simp, intros u, cases C : chr A a; simp at C ⊢; exact C })\nend\n\ntheorem t_reducible.compl_rre {A : set α} {B : set β} :\n A ≤ₜ B → Aᶜ re_in! chr B := λ h,\nbegin\n have : (λ a, cond (chr A a) none (some ())) partrec_in! chr B,\n { refine rpartrec.cond (classical_iff.mp h) rpartrec.none (rcomputable.const _) },\n exact (this.of_eq $ λ a, by {\n apply part.ext, simp, intros u, cases C : chr A a; simp at C ⊢, exact C,\n exact not_not.mpr C })\nend\n\ntheorem t_reducible_iff_rre {A : set α} {B : set β} :\n A ≤ₜ B ↔ A re_in! chr B ∧ Aᶜ re_in! chr B :=\n⟨λ h, ⟨h.rre, h.compl_rre⟩, begin\n rintros ⟨h₁, h₂⟩, apply classical_iff.mpr,\n show chr A computable_in! chr B,\n rcases rre_pred_iff'.mp h₁ with ⟨χ, pA, hA⟩,\n rcases rre_pred_iff'.mp h₂ with ⟨χc, pAc, hAc⟩,\n rcases exists_index.mp pA with ⟨e₁, rfl⟩,\n rcases exists_index.mp pAc with ⟨e₂, rfl⟩,\n let f₀ : α → ℕ → option bool :=\n λ x s, ((⟦e₁⟧^(chr B) [s] x : option ℕ).map (λ _, tt)) <|> ((⟦e₂⟧^(chr B) [s] x : option ℕ).map (λ _, ff)),\n let f : α →. bool := λ x, nat.rfind_opt (f₀ x),\n have total : ∀ x, (f x).dom,\n { intros x, simp[f, f₀, nat.rfind_opt_dom], by_cases C : A x,\n { rcases univn_dom_complete.mp ((hA x).mp C) with ⟨n, h_n⟩,\n refine ⟨n, or.inr _⟩,\n rw ←option.some_get h_n, simp only [option.map, option.bind, option.some_orelse] },\n { rcases univn_dom_complete.mp ((hAc x).mp C) with ⟨n, h_n⟩, refine ⟨n, _⟩,\n rw ←option.some_get h_n,\n cases ⟦e₁⟧^(chr B) [n] x with v;\n simp only [option.map, option.bind, option.some_orelse, option.none_orelse], simp, right, refl } },\n let f' : α → bool := λ x, (f x).get (total x),\n have : chr A = f',\n { sorry },\n have mono : ∀ {x : α} {a} {m n : ℕ}, m ≤ n → a ∈ f₀ x m → a ∈ f₀ x n,\n { sorry },\n sorry\n end⟩\n\ntheorem rre_Jumpcomputable {A : set α} {B : set ℕ} : A re_in! chr B → A ≤ₜ B′ := \nλ h, classical_iff.mpr \nbegin\n show chr A computable_in! chr B′,\n rcases rre_pred_iff.mp h with ⟨a, pa, ha⟩,\n rcases exists_index.mp pa with ⟨e, he⟩,\n let f : α → bool := (λ x, chr B′ (e.mkpair (encode x))),\n have l0 : f computable_in (chr B′ : ℕ →. bool) :=\n rcomputable.refl.comp (primrec₂.mkpair.comp\n (primrec.const e) primrec.encode).to_rcomp,\n have l1 : f = chr A,\n { funext x, simp[f, Jump, chr_ext, set.set_of_app_iff, he, ha], },\n show chr A computable_in! chr B′, from (l0.of_eq $ by simp[l1])\nend\n\ntheorem rre_iff_one_one_reducible {A B : set ℕ} : A re_in! chr B ↔ A ≤₁ B′ := \n⟨ begin\n assume h, show A ≤₁ B′,\n rcases rre_pred_iff.mp h with ⟨a, pa, ha⟩,\n rcases exists_index.mp pa with ⟨e, eqn_e⟩,\n have lmm1 : primrec e.mkpair := primrec₂.mkpair.comp (primrec.const _) primrec.id,\n have lmm2 : function.injective e.mkpair,\n { intros x y h,\n have : x = (e.mkpair x).unpair.2, simp,\n rw this, rw h, simp }, \n have lmm3 : ∀ n, A n ↔ B′ (e.mkpair n),\n { simp[Jump, chr_ext, set.set_of_app_iff, eqn_e, ha], }, \n refine ⟨e.mkpair, lmm1.to_comp, lmm2, lmm3⟩,\n end,\n begin\n assume h, show A re_in! chr B,\n rcases h with ⟨i, ci, inj, hi⟩,\n apply rre_pred_iff.mpr,\n let q : ℕ →. ℕ := (λ x, ⟦(i x).unpair.1⟧ₙ^(chr B) (i x).unpair.2),\n have lmm : q partrec_in! chr B,\n { refine rpartrec.univ_tot _ _\n (computable.fst.comp (primrec.unpair.to_comp.comp ci)).to_rcomp\n rcomputable.refl\n (computable.snd.comp (primrec.unpair.to_comp.comp ci)).to_rcomp },\n have lmm1 : ∀ n, A n ↔ (q n).dom,\n { intros x, simp [hi, q, Jump] },\n refine ⟨q, lmm, lmm1⟩,\n end⟩\n\ntheorem re_many_one_reducible_to_0' {A : set ℕ} : r.e. A ↔ A ≤₁ ∅′ :=\n⟨λ h, rre_iff_one_one_reducible.mp (h.to_rpart),\n λ h, (rre_iff_one_one_reducible.mpr h).re0 ⟩\n\ntheorem re_pred_Jump_0 : r.e. ∅′ :=\nre_many_one_reducible_to_0'.mpr (by refl)\n\nlemma dom_rre (f : α →. σ) : {x | (f x).dom} re_in f :=\nbegin\n let g := (λ a, (f a).map (λ x, ())),\n have := rpartrec.refl.map ((computable.const ()).comp computable.snd).to_rcomp.to₂,\n exact (this.of_eq $ λ x, by { rw set.set_of_app_iff, simp, \n apply part.ext, intros a, simp [dom_iff_mem] })\nend\n\ntheorem exists_rre [inhabited β] {p : α → β → Prop} {g : γ → τ} :\n {x : α × β | p x.1 x.2} re_in! g → {x | ∃ y, p x y} re_in! g := λ h,\nbegin\n have := rpartrec.exists_index.mp h,\n rcases this with ⟨e, eqn_e⟩,\n have eqn_e1 : ∀ x y, p x y ↔ (⟦e⟧^g (x, y) : part unit).dom,\n { simp [eqn_e, part.assert, part.some] },\n let p' := (λ x : α, nat.rfind (λ u, (⟦e⟧^g [u.unpair.2]\n (x, (decode β u.unpair.1).get_or_else (default β)) : option unit).is_some)),\n have lmm : ∀ x, (∃ y, p x y) ↔ (p' x).dom,\n { intros x, simp only [p'], split,\n { rintros ⟨y, hb⟩, rw eqn_e1 at hb,\n apply rfind_dom_total,\n simp [part.dom_iff_mem, part.some] at hb ⊢, rcases hb with ⟨z, hz⟩,\n rcases univn_complete.mp hz with ⟨s, hs⟩,\n use (encode y).mkpair s,\n simp [hs] },\n { simp, intros u h0 h1, \n use (decode β u.unpair.fst).get_or_else (default β),\n cases e : (⟦e⟧^g [u.unpair.snd] (x, \n (decode β u.unpair.fst).get_or_else (default β)) : option unit) with v,\n { exfalso, simp [e] at h0, exact h0 },\n have := univn_sound e, simp [eqn_e1, this] } },\n have eqn : {x | ∃ y, p x y} = {x | (p' x).dom},\n { apply set.ext, simp [lmm] },\n have : p' partrec_in! g,\n { apply rpartrec.rfind,\n refine primrec.option_is_some.to_rcomp.comp\n (rcomputable.univn_tot _ _ \n (primrec.const _).to_rcomp\n rcomputable.refl (snd.comp $ primrec.unpair.comp snd).to_rcomp _),\n have := ((fst.pair (option_get_or_else.comp \n (primrec.decode.comp $ fst.comp $ unpair.comp snd)\n (const (default β))))), exact this.to_rcomp },\n rw eqn,\n show {x | (p' x).dom} re_in! g,\n from (dom_rre p').rre this\nend\n\ntheorem rre_compl_of_rre {A B : set ℕ} :\n A re_in! chr B → Aᶜ re_in! chr B′ := λ h,\nbegin\n have lmm₁ : Aᶜ ≤₁ B′ᶜ,\n { simp[le1_compl_iff], exact rre_iff_one_one_reducible.mp h },\n have lmm₂ : B′ᶜ ≤₁ B′′, from rre_iff_one_one_reducible.mp (t_reducible.rre (reducible_compl B′)),\n exact rre_iff_one_one_reducible.mpr (lmm₁.trans lmm₂)\nend\n\nlemma rre_pred.rre_of_le {A : set α} {B : set β} {C : set γ} :\n A re_in! chr B → C ≤₀ A → C re_in! chr B := λ h ⟨f, comp, fh⟩,\nbegin\n rcases rre_pred_iff'.mp h with ⟨q, partrec, qh⟩,\n refine rre_pred_iff'.mpr ⟨q ∘ f, partrec.comp comp.to_rcomp, λ x, by simp[fh, qh]⟩,\nend\n\ntheorem exists_reducible [inhabited β] {p : α → β → Prop} {A : set ℕ} :\n {x : α × β | p x.1 x.2} ≤ₜ A → {x | ∃ y, p x y} ≤ₜ A′ :=\nλ h, rre_Jumpcomputable (exists_rre h.rre)\n\ntheorem forall_reducible [inhabited β] {p : α → β → Prop} {A : set ℕ} :\n {x : α × β | p x.1 x.2} ≤ₜ A → {x | ∀ y, p x y} ≤ₜ A′ := λ h,\nbegin\n have : {x | ∀ y, p x y}ᶜ ≤ₜ A′,\n { have : {x | ∃ y, ¬p x y} ≤ₜ A′,\n { apply exists_reducible, \n have := (equiv_compl {x : α × β | p x.1 x.2}).1.trans (h.of_eq $ by { intros a, simp }),\n exact (this.of_eq $ λ a, by refl) },\n exact (this.of_eq $ λ a, by { simp, exact not_forall.symm }) },\n apply (equiv_compl {x | ∀ y, p x y}).2.trans this\nend\n\ndef Kleene (A : set ℕ) : set ℕ := {x | (⟦x⟧ₙ^(chr A) x).dom}\n\ndef Tot (A : set ℕ) : set ℕ := {e | ∀ x, (⟦e⟧ₙ^(chr A) x).dom}\n\ndef Unbound (A : set ℕ) : set ℕ := {e | ∀ x, ∃ y, x ≤ y ∧ (⟦e⟧ₙ^(chr A) y).dom}\n\ndef Rec (A : set ℕ) : set ℕ := {e | W⟦e⟧ₙ^(chr A) ≤ₜ A}\n\ntheorem Kleene_equiv_Jump (A : set ℕ) : Kleene A ≡ₜ A′ :=\n⟨classical_iff.mpr \n begin\n show chr (Kleene A) computable_in! chr A′,\n let f := (λ n : ℕ, chr A′ (n.mkpair n)),\n have : chr (Kleene A) = f,\n { funext n, apply chr_ext.mpr,\n simp [Kleene, f, Jump] },\n rw this,\n have := rcomputable.refl.comp\n (primrec₂.mkpair.comp primrec.id primrec.id).to_rcomp,\n exact this\n end, classical_iff.mpr\n begin\n show chr A′ computable_in! chr (Kleene A),\n let t := (λ x : ℕ × (ℕ × ℕ), ⟦x.1⟧ₙ^(chr A) x.2.1),\n have : ∃ e, ⟦e⟧^(chr A) = t,\n { have : t partrec_in! chr A :=\n (rpartrec.univ_tot ℕ ℕ rcomputable.fst rcomputable.refl (fst.comp snd).to_rcomp),\n exact exists_index.mp this },\n rcases this with ⟨e, eqn_e⟩,\n let k := (λ n m : ℕ, curry (curry e n) m),\n have eqn_k : ∀ z i x, ⟦k i x⟧ₙ^(chr A) z = ⟦i⟧ₙ^(chr A) x,\n { intros z i x, simp [k, eqn_e] },\n let f := (λ x : ℕ, chr (Kleene A) (k x.unpair.1 x.unpair.2)),\n have : chr A′ = f,\n { funext n, apply chr_ext.mpr,\n simp [Kleene, f, Jump, eqn_k, eqn_e] },\n rw this,\n have : primrec₂ k := curry_prim.comp\n (curry_prim.comp (const e) fst) snd,\n have := rcomputable.refl.comp\n (this.comp (fst.comp primrec.unpair)\n (snd.comp primrec.unpair)).to_rcomp,\n exact this\n end⟩\n\ntheorem Tot_equiv_Jump2 (A : set ℕ) : Tot A ≤ₜ A′′ :=\nbegin\n have : Tot A = {e | ∀ x, ∃ s, (⟦e⟧ₙ^(chr A) [s] x).is_some},\n { simp[Tot, rpartrec.univn_dom_complete] },\n rw this,\n refine forall_reducible (exists_reducible $ classical_iff.mpr _),\n simp, \n refine option_is_some.to_rcomp.comp (rcomputable.univn_tot _ _\n (fst.comp fst).to_rcomp rcomputable.refl snd.to_rcomp (snd.comp fst).to_rcomp),\nend\n\ntheorem Unbound_equiv_Jump2 (A : set ℕ) : Unbound A ≤ₜ A′′ :=\nbegin\n have : Unbound A = {e | ∀ x, ∃ y : ℕ × ℕ, x ≤ y.2 ∧ (⟦e⟧ₙ^(chr A) [y.1] y.2).is_some},\n { simp[Unbound, rpartrec.univn_dom_complete], funext n,\n simp, refine forall_congr (λ x, _), split,\n { rintros ⟨y, eqn, s, h⟩, refine ⟨s, y, eqn, h⟩ },\n { rintros ⟨s, y, eqn, h⟩, refine ⟨y, eqn, s, h⟩ } },\n rw this,\n refine forall_reducible (exists_reducible $ classical_iff.mpr _),\n let f := (λ x : (ℕ × ℕ) × ℕ × ℕ, to_bool (x.fst.snd ≤ x.snd.snd) &&\n (⟦x.fst.fst⟧ₙ^(chr A) [x.snd.fst] x.snd.snd).is_some),\n have : f computable_in! chr A,\n { refine (primrec.dom_bool₂ (&&)).to_rcomp.comp₂'\n (primrec₂.comp primrec.nat_le (snd.comp fst) (snd.comp snd)).to_rcomp\n (primrec.option_is_some.to_rcomp.comp (rcomputable.univn_tot _ _\n (fst.comp fst).to_rcomp rcomputable.refl (fst.comp snd).to_rcomp (snd.comp snd).to_rcomp)) },\n exact (this.of_eq $ λ x, by symmetry; simp[f, chr_iff])\nend\n\ntheorem Rec_equiv_Jump3 (A : set ℕ) : Rec A ≤ₜ A′′′ :=\nbegin\n have : Rec A = {e : ℕ | ∃ i, ∀ x, ∃ s, (⟦i⟧ᵪ^(chr A) [s] x = some tt ↔ (⟦e⟧ₙ^(chr A) [s] x).is_some)},\n { simp[Rec, re_set], ext e, simp, sorry }, sorry\nend\n\nlemma rre_enumeration_iff {A : set α} {f : β → σ} (h : ∃ a, a ∈ A) :\n A re_in! f → (∃ e : ℕ → α, e computable_in! f ∧ (∀ x, x ∈ A ↔ ∃ n, e n = x)) :=\nbegin\n rcases h with ⟨a₀, hyp_a₀⟩,\n { intros hyp,\n rcases rre_pred_iff.mp hyp with ⟨q, hyp_q, hyp_q1⟩,\n let q' := (λ x : α, q (encode x)),\n have hyp_q' : q' partrec_in! f := hyp_q.comp primrec.encode.to_rcomp,\n rcases exists_index.mp hyp_q' with ⟨i, eqn_i⟩,\n let e := (λ n : ℕ, cond (⟦i⟧^f [n.unpair.1] \n ((decode α n.unpair.2).get_or_else a₀) : option ℕ).is_some\n ((decode α n.unpair.2).get_or_else a₀) a₀),\n have lmm1 : e computable_in! f,\n { refine rcomputable.cond\n (option_is_some.to_rcomp.comp (rcomputable.univn_tot _ _\n (rcomputable.const _)\n rcomputable.refl\n (fst.comp unpair).to_rcomp\n (option_get_or_else.comp (primrec.decode.comp $ snd.comp unpair) (const _)).to_rcomp))\n (option_get_or_else.comp (primrec.decode.comp $ snd.comp unpair)\n (const _)).to_rcomp (const _).to_rcomp },\n have lmm2 : ∀ x, x ∈ A ↔ ∃ n, e n = x,\n { simp [e], intros a, split,\n { intros hyp_a,\n have : ∃ y : ℕ, y ∈ (⟦i⟧^f a : part ℕ),\n { simp [←part.dom_iff_mem, eqn_i, q', ←hyp_q1], exact hyp_a },\n rcases this with ⟨y, lmm_y⟩,\n have := univn_complete.mp lmm_y, rcases this with ⟨s, lmm_s⟩,\n refine ⟨s.mkpair (encode a), _⟩, simp, simp[lmm_s] },\n { rintros ⟨n, hyp_n⟩,\n cases C : (⟦i⟧^f [n.unpair.fst] ((decode α n.unpair.snd).get_or_else a₀) : option ℕ) with v;\n simp[C] at hyp_n, simp[←hyp_n], exact hyp_a₀,\n suffices : (⟦i⟧^f a : part ℕ).dom,\n { simp[eqn_i, q', ←hyp_q1] at this, exact this },\n have := univn_sound C,\n simp[←hyp_n, this] } },\n refine ⟨e, lmm1, lmm2⟩ }\nend\n\nlemma re_enumeration_iff {A : set α} {f : β → σ} (h : ∃ a, a ∈ A) :\n r.e. A → ∃ e : ℕ → α, computable e ∧ (∀ x, x ∈ A ↔ ∃ n, e n = x) := λ hyp,\nby { rcases rre_enumeration_iff h (hyp.to_rpart_in ↑ᵣ(@id ℕ)) with ⟨e, lmm1, lmm2⟩,\n refine ⟨e, rcomputable.le_comp_comp lmm1 computable.id, lmm2⟩ }\n\nmutual def pie_pred, sigma_pred\nwith pie_pred : ℕ → set ℕ → Prop\n| 0 A := computable_pred A\n| (n + 1) A := ∃ B : set ℕ, sigma_pred n B ∧ A = {x | ∀ y, (x.mkpair y) ∈ B}\nwith sigma_pred : ℕ → set ℕ → Prop\n| 0 A := computable_pred A\n| (n + 1) A := ∃ B : set ℕ, pie_pred n B ∧ A = {x | ∃ y, (x.mkpair y) ∈ B}\n\nprefix `𝚷⁰`:max := pie_pred\n\nprefix `𝚺⁰`:max := sigma_pred\n\ndef delta_pred (n : ℕ) (A : set ℕ) : Prop := 𝚷⁰n A ∧ 𝚺⁰n A\n\nprefix `𝚫⁰`:max := delta_pred\n\n@[simp] lemma pie_pred0_iff {A : set ℕ} : 𝚷⁰0 A ↔ computable_pred A := by simp[pie_pred]\n\n@[simp] lemma sigma_pred0_iff {A : set ℕ} : 𝚺⁰0 A ↔ computable_pred A := by simp[sigma_pred]\n\nlemma pie_pred2_iff {A : set ℕ} {n : ℕ} :\n 𝚷⁰(n + 2) A ↔ ∃ B : set ℕ, 𝚷⁰n B ∧ A = {x | ∀ y, ∃ z, (x.mkpair y).mkpair z ∈ B} :=\nby { simp[sigma_pred, pie_pred], split,\n { rintros ⟨B₁, ⟨B₂, sigma, rfl⟩, rfl⟩, refine ⟨B₂, sigma, by refl⟩ },\n { rintros ⟨B₁, sigma, rfl⟩, refine ⟨_, ⟨B₁, sigma, rfl⟩, by refl⟩ } }\n\nlemma sigma_pred2_iff {A : set ℕ} {n : ℕ} :\n 𝚺⁰(n + 2) A ↔ ∃ B : set ℕ, 𝚺⁰n B ∧ A = {x | ∃ y, ∀ z, (x.mkpair y).mkpair z ∈ B} :=\nby { simp[sigma_pred, pie_pred], split,\n { rintros ⟨B₁, ⟨B₂, sigma, rfl⟩, rfl⟩, refine ⟨B₂, sigma, by refl⟩ },\n { rintros ⟨B₁, sigma, rfl⟩, refine ⟨_, ⟨B₁, sigma, rfl⟩, by refl⟩ } }\n\nlemma arith_hie_compl : ∀ {n : ℕ} {A : set ℕ},\n 𝚷⁰n A ↔ 𝚺⁰n Aᶜ\n| 0 A := by { simp[degree0'], exactI ⟨λ h, (equiv_compl A).trans h, λ h, (equiv_compl A).symm.trans h⟩ }\n| (n + 1) A := by { simp[sigma_pred, pie_pred], split,\n { rintros ⟨B, sigma, rfl⟩,\n refine ⟨Bᶜ, (@arith_hie_compl n Bᶜ).mpr (by simp[sigma]), by simp[set.compl_set_of]⟩ },\n { rintros ⟨B, pie, eqn⟩,\n refine ⟨Bᶜ, (@arith_hie_compl n B).mp pie, \n by rw ←(compl_compl A); rw eqn; simp[set.compl_set_of]⟩ } }\n\nlemma pie_pred.many_one : ∀ {n : ℕ} {A B : set ℕ} (pie : 𝚷⁰n B) (le : A ≤₀ B), 𝚷⁰n A\n| 0 A B pie le := by { simp at*, exact le_computable_computable le.to_turing pie }\n| 1 A B pie ⟨f, f_comp, le⟩ := by { simp[pie_pred] at pie,\n rcases pie with ⟨B', sigma, rfl⟩,\n let C : set ℕ := {x | (f x.unpair.1).mkpair x.unpair.2 ∈ B'},\n have : C ≤₀ B',\n { refine ⟨λ x, (f x.unpair.1).mkpair x.unpair.2, _, λ x, by simp[C]; refl⟩,\n refine primrec₂.mkpair.to_comp.comp (f_comp.comp (fst.comp unpair).to_comp) (snd.comp unpair).to_comp },\n have sigma' : computable_pred C, from le_computable_computable this.to_turing sigma,\n have : A = {x | ∀ y, x.mkpair y ∈ C}, { simp[C], exact set.ext le },\n simp [pie_pred], refine ⟨C, sigma', this⟩ }\n| (n + 2) A B pie ⟨f, f_comp, le⟩ := by {\n rcases pie_pred2_iff.mp pie with ⟨B', pie', rfl⟩,\n let C : set ℕ := {x | ((f x.unpair.1.unpair.1).mkpair x.unpair.1.unpair.2).mkpair x.unpair.2 ∈ B'},\n have : C ≤₀ B',\n { refine ⟨λ x, ((f x.unpair.1.unpair.1).mkpair x.unpair.1.unpair.2).mkpair x.unpair.2,\n _, λ x, by simp[C]; refl⟩,\n refine primrec₂.mkpair.to_comp.comp\n (primrec₂.mkpair.to_comp.comp (f_comp.comp (fst.comp $ unpair.comp $ fst.comp unpair).to_comp)\n (snd.comp $ unpair.comp $ fst.comp unpair).to_comp) (snd.comp unpair).to_comp }, \n have IH : 𝚷⁰n C, from pie_pred.many_one pie' this,\n have : A = {x | ∀ y, ∃ z, (x.mkpair y).mkpair z ∈ C},\n { simp[C], exact set.ext le },\n refine pie_pred2_iff.mpr ⟨C, IH, this⟩ }\n\nlemma sigma_pred.many_one : ∀ {n : ℕ} {A B : set ℕ} (sigma : 𝚺⁰n B) (le : A ≤₀ B), 𝚺⁰n A\n| 0 A B sigma le := by { simp at*, exact le_computable_computable le.to_turing sigma }\n| 1 A B sigma ⟨f, f_comp, le⟩ := by { simp[sigma_pred] at sigma,\n rcases sigma with ⟨B', pie, rfl⟩,\n let C : set ℕ := {x | (f x.unpair.1).mkpair x.unpair.2 ∈ B'},\n have : C ≤₀ B',\n { refine ⟨λ x, (f x.unpair.1).mkpair x.unpair.2, _, λ x, by simp[C]; refl⟩,\n refine primrec₂.mkpair.to_comp.comp (f_comp.comp (fst.comp unpair).to_comp) (snd.comp unpair).to_comp },\n have pie' : computable_pred C, from le_computable_computable this.to_turing pie,\n have : A = {x | ∃ y, x.mkpair y ∈ C}, { simp[C], exact set.ext le },\n simp[sigma_pred], refine ⟨C, pie', this⟩ }\n| (n + 2) A B sigma ⟨f, f_comp, le⟩ := by {\n rcases sigma_pred2_iff.mp sigma with ⟨B', sigma', rfl⟩,\n let C : set ℕ := {x | ((f x.unpair.1.unpair.1).mkpair x.unpair.1.unpair.2).mkpair x.unpair.2 ∈ B'},\n have : C ≤₀ B',\n { refine ⟨λ x, ((f x.unpair.1.unpair.1).mkpair x.unpair.1.unpair.2).mkpair x.unpair.2,\n _, λ x, by simp[C]; refl⟩,\n refine primrec₂.mkpair.to_comp.comp\n (primrec₂.mkpair.to_comp.comp (f_comp.comp (fst.comp $ unpair.comp $ fst.comp unpair).to_comp)\n (snd.comp $ unpair.comp $ fst.comp unpair).to_comp) (snd.comp unpair).to_comp }, \n have IH : 𝚺⁰n C, from sigma_pred.many_one sigma' this,\n have : A = {x : ℕ | ∃ (y : ℕ), ∀ (z : ℕ), (x.mkpair y).mkpair z ∈ C},\n { simp[C], exact set.ext le },\n refine sigma_pred2_iff.mpr ⟨C, IH, this⟩ }\n\nlemma pie_pred_iff {p : ℕ → ℕ → Prop} {n : ℕ}\n (h : 𝚺⁰n {x | p x.unpair.1 x.unpair.2}) : 𝚷⁰(n + 1) {x | ∀ y, p x y} :=\n by simp[pie_pred]; refine ⟨{x : ℕ | p (nat.unpair x).fst (nat.unpair x).snd}, h, by simp⟩\n\nlemma sigma_pred_iff {p : ℕ → ℕ → Prop} {n : ℕ}\n (h : 𝚷⁰n {x | p x.unpair.1 x.unpair.2}) : 𝚺⁰(n + 1) {x | ∃ y, p x y} :=\n by simp[sigma_pred]; refine ⟨{x : ℕ | p (nat.unpair x).fst (nat.unpair x).snd}, h, by simp⟩\n\nlemma pie_pred_bforall {p : ℕ → ℕ → Prop} {n : ℕ} {b : ℕ}\n (h : 𝚺⁰n {x | p x.unpair.1 x.unpair.2}) : 𝚺⁰n {x | ∀ y < b, p x y} :=\n by { }\n\nlemma sigma_pred.exists {n : ℕ} {A : set ℕ} (h : 𝚺⁰(n + 1) A) :\n 𝚺⁰(n + 1) {x | ∃ y, (x.mkpair y) ∈ A} :=\nbegin\n simp[sigma_pred] at h ⊢,\n rcases (h) with ⟨B, pie, rfl⟩,\n simp,\n let B' : set ℕ := {x | (x.unpair.1.mkpair x.unpair.2.unpair.1).mkpair x.unpair.2.unpair.2 ∈ B},\n have eqn : {x : ℕ | ∃ y n, ((x.mkpair y).mkpair n) ∈ B} = {x | ∃ y : ℕ, (x.mkpair y) ∈ B' },\n { apply set.ext, intros x, simp[B'], split,\n { rintros ⟨y, n, mem⟩, refine ⟨y.mkpair n, _⟩, simp[mem] },\n { rintros ⟨y, mem⟩, refine ⟨y.unpair.1, y.unpair.2, mem⟩ } },\n have le : B' ≤₀ B,\n { refine ⟨λ x, (x.unpair.1.mkpair x.unpair.2.unpair.1).mkpair x.unpair.2.unpair.2, _, λ x, by simp[B']; refl⟩,\n refine (primrec₂.mkpair.comp\n (primrec₂.mkpair.comp (fst.comp unpair) $ fst.comp $ unpair.comp $ snd.comp unpair)\n (snd.comp $ unpair.comp $ snd.comp unpair)).to_comp },\n refine ⟨B', pie.many_one le, eqn⟩\nend\n\nlemma sigma_pred.exists' {n : ℕ} {p : ℕ → ℕ → Prop} (h : 𝚺⁰(n + 1) {x | p x.unpair.1 x.unpair.2}) :\n 𝚺⁰(n + 1) {x | ∃ y, p x y} :=\nby have := h.exists; simp at this; exact this\n\nlemma sigma_pred.exists'' [inhabited α] {n : ℕ} {p : ℕ → α → Prop}\n (h : 𝚺⁰(n + 1) {x | p x.unpair.1 ((encodable.decode α x.unpair.2 ).get_or_else (default α))}) :\n 𝚺⁰(n + 1) {x | ∃ y, p x y} :=\nby { have := h.exists, simp at this, sorry }\n\nlemma pie_pred.forall {n : ℕ} {A : set ℕ} (h : 𝚷⁰(n + 1) A) :\n 𝚷⁰(n + 1) {x | ∀ y, (x.mkpair y) ∈ A} :=\nby simp[arith_hie_compl, set.compl_set_of] at h ⊢; exact h.exists\n\nlemma pie_pred.forall' {n : ℕ} {p : ℕ → ℕ → Prop} (h : 𝚷⁰(n + 1) {x | p x.unpair.1 x.unpair.2}) :\n 𝚷⁰(n + 1) {x | ∀ y, p x y} :=\nby have := h.forall; simp at this; exact this\n\nlemma sigma_pred1_iff_re {A : set ℕ} : 𝚺⁰1 A ↔ r.e. A :=\nbegin\n simp[sigma_pred, ←rre_in_0_iff_re], split,\n { rintros ⟨B, comp, rfl⟩, refine exists_rre (t_reducible.rre _),\n have : {x : ℕ × ℕ | x.1.mkpair x.2 ∈ B} ≤ₜ B,\n from classical_iff.mpr (rcomputable.refl.comp (primrec₂.mkpair.comp fst snd).to_rcomp),\n exact this.trans ((degree0' B).mp comp).1 },\n { intros h,\n rcases rre_pred_iff_exists_index.mp h with ⟨e, rfl⟩,\n let B : set ℕ := {x | (⟦e⟧ₙ^(chr ∅ : ℕ → bool) [x.unpair.2] x.unpair.1).is_some},\n have lmm₁ : computable_pred B,\n { refine computable_pred_iff_le.mpr (classical_iff.mpr _),\n have : (λ x : ℕ, (⟦e⟧ₙ^(chr ∅ : ℕ → bool) [x.unpair.2] x.unpair.1).is_some) computable_in! chr (∅ : set ℕ),\n from primrec.option_is_some.to_rcomp.comp\n (rcomputable.univn_tot _ _ (rcomputable.const _) rcomputable.refl (snd.comp unpair).to_rcomp (fst.comp unpair).to_rcomp ),\n exact this.of_eq (λ x, by simp[B]) },\n have lmm₂ : W⟦e⟧ₙ^(chr (∅ : set ℕ)) = {x | ∃ y, x.mkpair y ∈ B},\n { refine set.ext (λ x, _), simp[B], exact univn_dom_complete },\n exact ⟨B, lmm₁, lmm₂⟩ }\nend\n\nlemma pie_pred1_iff_co_re {A : set ℕ} : 𝚷⁰1 A ↔ r.e. Aᶜ :=\nby simp[arith_hie_compl, sigma_pred1_iff_re]\n\nlemma sigma_Jump_of_pie {n : ℕ} {A : set ℕ} (sigma : 𝚺⁰ n A) : 𝚺⁰ (n + 1) A′ :=\nbegin\n simp[Jump], sorry\nend\n\ntheorem sigma_complete : ∀ {n : ℕ} {A : set ℕ},\n 𝚺⁰(n + 1) A ↔ A re_in! chr (Jump_itr n ∅)\n| 0 A := by simp[rre_in_0_iff_re]; exact sigma_pred1_iff_re\n| (n + 1) A := begin\n have IH_sigma : ∀ {A}, 𝚺⁰(n + 1) A ↔ A re_in! chr (Jump_itr n ∅), from @sigma_complete n,\n have IH_pie : ∀ {A}, 𝚷⁰(n + 1) A ↔ Aᶜ re_in! chr (Jump_itr n ∅),\n { intros A, simp[arith_hie_compl, IH_sigma] },\n split, \n { simp[sigma_pred], rintros B pie rfl, refine exists_rre _,\n have lmm₁ : B re_in! chr (Jump_itr n ∅)′,\n { have := rre_compl_of_rre (IH_pie.mp pie), simp at this, exact this },\n have lmm₂ : {x : ℕ × ℕ | nat.mkpair x.fst x.snd ∈ B} ≤₀ B,\n from ⟨λ x, nat.mkpair x.fst x.snd, (primrec₂.mkpair.comp fst snd).to_comp, by simp[set.mem_def]⟩,\n exact rre_pred.rre_of_le lmm₁ lmm₂ },\n { intros h, simp at h,\n have : 𝚺⁰(n + 1) (Jump_itr n ∅)′, from IH_sigma.mpr (rre_iff_one_one_reducible.mpr (by refl)),\n refine (sigma_Jump_of_pie this).many_one (rre_iff_one_one_reducible.mp h).to_many_one }\n end\n\n\nlemma computable_pred_iff_chr_computable {A : set ℕ} : computable_pred A ↔ computable (chr A) :=\nbegin\n simp[computable_pred_iff_le, classical_iff],\n split; intros h, { refine rcomputable.le_comp_comp h ((computable.const ff).of_eq (by { simp[has_emptyc.emptyc] })), },\n { exact h.to_rcomp }\nend\n\nlemma re_Join_of_re_re {A B : set ℕ} (hA : r.e. A) (hB : r.e. B) : r.e. Join₂ A B :=\nbegin\n simp[Join₂, Join, ←sigma_pred1_iff_re, sigma_pred, computable_pred_iff_chr_computable] at *,\n rcases hA with ⟨A, hA, rfl⟩,\n rcases hB with ⟨B, hB, rfl⟩,\n let C : set ℕ := {n : ℕ |\n if (nat.unpair n).1.unpair.2 = 0 then nat.mkpair n.unpair.1.unpair.1 n.unpair.2 ∈ A else\n if (nat.unpair n).1.unpair.2 = 1 then nat.mkpair n.unpair.1.unpair.1 n.unpair.2 ∈ B else false },\n refine ⟨C, by { simp[C],\n suffices :\n computable\n (λ n, if (nat.unpair n).1.unpair.2 = 0 then chr A (nat.mkpair n.unpair.1.unpair.1 n.unpair.2) else\n if (nat.unpair n).1.unpair.2 = 1 then chr B (nat.mkpair n.unpair.1.unpair.1 n.unpair.2) else ff),\n exact this.of_eq (λ n, by { by_cases C₁ : (nat.unpair (nat.unpair n).fst).snd = 0; simp[C₁, set.mem_def, chr_eq_to_bool],\n by_cases C₂ : (nat.unpair (nat.unpair n).fst).snd = 1; simp[C₂] }),\n refine rcomputable.computable_of_rcomp (rcomputable.ite\n (rcomputable.to_bool_eq ℕ\n (rcomputable.snd.comp (rcomputable.nat_unpaired.comp (rcomputable.fst.comp rcomputable.nat_unpaired)))\n (rcomputable.const 0))\n (hA.to_rcomp.comp (rcomputable₂.comp rpartrec.some\n (rcomputable.fst.comp (rcomputable.nat_unpaired.comp (rcomputable.fst.comp rcomputable.nat_unpaired)))\n (rcomputable.snd.comp rcomputable.nat_unpaired))) _),\n refine rcomputable.ite\n (rcomputable.to_bool_eq ℕ\n (rcomputable.snd.comp (rcomputable.nat_unpaired.comp (rcomputable.fst.comp rcomputable.nat_unpaired)))\n (rcomputable.const 1)) (hB.to_rcomp.comp\n (rcomputable₂.comp rpartrec.some\n (rcomputable.fst.comp (rcomputable.nat_unpaired.comp (rcomputable.fst.comp rcomputable.nat_unpaired)))\n (rcomputable.snd.comp rcomputable.nat_unpaired))) (rcomputable.const ff) },\n by { ext x, simp, cases (nat.unpair x).snd with n; simp,\n { cases n with n; simp }}⟩,\nend\n\nend classical", "meta": {"author": "iehality", "repo": "lean-reducibility", "sha": "82a7e3ec0fcedfb0d69c25e77bcd24c9b29626b7", "save_path": "github-repos/lean/iehality-lean-reducibility", "path": "github-repos/lean/iehality-lean-reducibility/lean-reducibility-82a7e3ec0fcedfb0d69c25e77bcd24c9b29626b7/src/reducibility.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.03161876589986862, "lm_q1q2_score": 0.01580938294993431}} {"text": "import model_theory.substructures\nimport model_theory.bundled\n\n\n--OUTPUT 1\ntheorem overflow {L : first_order.language} {F : L.Theory} (h : ∀ n : ℕ, ∃ (m : F.Model) [mfin : fintype m], n ≤ @fintype.card m mfin) : ∃ (M : F.Model), infinite M :=\nbegin\n let A : ℕ → L.Theory,\n have h1 : ∀ n : ℕ, ∃ (m : F.Model) [mfin : fintype m], n ≤ @fintype.card m mfin, from h,\n have h2 : ∀ n : ℕ, ∃ (m : F.Model) [mfin : fintype m], n ≤ @fintype.card m mfin, from h,\n have h3 : ∀ n : ℕ, ∃ (m : F.Model) [mfin : fintype m], n ≤ @fintype.card m mfin, from h,\n have h4 : ∀ n : ℕ, ∃ (m : F.Model) [mfin : fintype m], n ≤ @fintype.card m mfin, from h,\n have h5 : ∀ n : ℕ, ∃ (m : F.Model) [mfin : fintype m], n ≤ @fintype.card m mfin, from h,\n have h6 : ∀ n : ℕ, ∃ (m : F.Model) [mfin : fintype m], n ≤ @fintype.card m mfin, from h,\n have h7 : ∀ n : ℕ, ∃ (m : F.Model) [mfin : fintype m], n ≤ @fintype.card m mfin, from h,\n have h8 : ∀ n : ℕ, ∃ (m : F.Model) [mfin : fintype m], n ≤ @fintype.card m mfin, from h,\n have h9 : ∀ n : ℕ, ∃ (m : F.Model) [mfin : fintype m], n ≤ @fintype.card m mfin, from h,\n have h10 : ∀ n : ℕ, ∃ (m : F.Model) [mfin : fintype m], n ≤ @fintype.card m mfin, from h,\n have h11 : ∀ n : ℕ, ∃ (m : F.Model) [mfin : fintype m], n ≤ @fintype.card m mfin, from h,\n have h12 : ∀ n : ℕ, ∃ (m : F.Model) [mfin : fintype m], n ≤ @fintype.card m mfin, from h,\n have h13 : ∀ n : ℕ, ∃ (m : F.Model) [mfin : fintype m], n ≤ @fintype.card m mfin, from h,\n have h14 : ∀ n : ℕ, ∃ (m : F.Model) [mfin : fintype m], n ≤ @fintype.card m mfin, from h,\n have h15 : ∀ n : ℕ, ∃ (m : F.Model) [mfin : fintype m], n ≤ @fintype.card m mfin, from h,\n have h16 : ∀ n : ℕ, ∃ (m : F.Model) [mfin : fintype m], n ≤ @fintype.card m mfin, from h,\n have h17 : ∀ n : ℕ, ∃ (m : F.Model) [mfin : fintype m], n ≤ @fintype.card m mfin, from h,\n have h18 : ∀ n : ℕ, ∃ (m : F.Model) [mfin : fintype m], n ≤ @fintype.card m mfin, from h,\n have h19 : ∀ n : ℕ, ∃ (m : F.Model) [mfin : fintype m], n ≤ @fintype.card m mfin, from h,\n have h20 : ∀ n : ℕ, ∃ (m : F.Model) [mfin : fintype m], n ≤ @fintype.card m mfin, from h,\n have h21 : ∀ n : ℕ, ∃ (m : F.Model) [mfin : fintype m], n ≤ @fintype.card m mfin, from h,\n have h22 : ∀ n : ℕ, ∃ (m : F.Model) [mfin : fintype m], n ≤ @fintype.card m mfin, from h,\n have h23 : ∀ n : ℕ, ∃ (m : F.Model) [mfin : fintype m], n ≤ @fintype.card m mfin, from h,\n have h24 : ∀ n : ℕ, ∃ (m : F.Model) [mfin : fintype m], n ≤ @fintype.card m mfin, from h,\n have h25 : ∀ n : ℕ, ∃ (m : F.Model) [mfin : fintype m], n ≤ @fintype.card m mfin, from h,\n have h26 : ∀ n : ℕ, ∃ (m : F.Model) [mfin : fintype m], n ≤ @fintype.card m mfin, from h,\n have h27 : ∀ n : ℕ, ∃ (m : F.Model) [mfin : fintype m], n ≤ @fintype.card m mfin, from h,\n have h28 : ∀ n : ℕ, ∃ (m : F.Model) [mfin : fintype m], n ≤ @fintype.card m mfin, from h,\n have h29 : ∀ n : ℕ, ∃ (m : F.Model) [mfin : fintype m], n ≤ @fintype.card m mfin, from h,\n have h30 : ∀ n : ℕ, ∃ (m : F.Model) [mfin : fintype m], n ≤ @fintype.card m mfin, from h,\n have h31 : ∀ n : ℕ, ∃ (m : F.Model) [mfin : fintype m], n ≤ @fintype.card m mfin, from h,\n have h32 : ∀ n : ℕ, ∃ (m : F.Model) [mfin : fintype m], n ≤ @fintype.card m mfin, from h,\n have h33 : ∀ n : ℕ, ∃ (m : F.Model) [mfin : fintype m], n ≤ @fintype.card m mfin, from h,\n have h34 : ∀ n : ℕ, ∃ (m : F.Model) [mfin : fintype m], n ≤ @fintype.card m mfin, from h,\n have h35 : ∀ n : ℕ, ∃ (m : F.Model) [mfin : fintype m], n ≤ @fintype.card m mfin, from h,\n have h36 : ∀ n : ℕ, ∃ (m : F.Model) [mfin : fintype m], n ≤ @fintype.card m mfin, from h,\n have h37 : ∀ n : ℕ, ∃ (m : F.Model) [mfin : fintype m], n ≤ @fintype.card m mfin, from h,\n have h38 : ∀ n : ℕ, ∃ (m : F.Model) [mfin : fintype m], n ≤ @fintype.card m mfin, from h,\n have h39 : ∀ n : ℕ, ∃ (m : F.Model) [mfin : fintype m], n ≤ @fintype.card m mfin, from h,\n have h40 : ∀ n : ℕ, ∃ (m : F.Model) [mfin : fintype m], n ≤ @fintype.card m mfin, from h,\n have h41 : ∀ n : ℕ, ∃ (m : F.Model) [mfin : fintype m], n ≤ @fintype.card m mfin, from h,\n have h42 : ∀ n : ℕ, ∃ (m : F.Model) [mfin : fintype m], n ≤ @fintype.card m mfin, from h,\n have h43 : ∀ n :\nend --Needs more than 2000 tokens!\n\n/- FEW SHOT PROMPTS TO CODEX(START)\n/--`theorem`\nPower Set is Closed under Intersection\nLet $S$ be a set.\n\nLet $\\powerset S$ be the power set of $S$.\n\n\nThen:\n:$\\forall A, B \\in \\powerset S: A \\cap B \\in \\powerset S$\n`proof`\nLet $A, B \\in \\powerset S$.\n\nThen by the definition of power set, $A \\subseteq S$ and $B \\subseteq S$.\n\nFrom Intersection is Subset we have that $A \\cap B \\subseteq A$.\n\nIt follows from Subset Relation is Transitive that $A \\cap B \\subseteq S$.\n\nThus $A \\cap B \\in \\powerset S$ and closure is proved.\n{{qed}}\n-/\ntheorem power_set_intersection_closed {α : Type*} (S : set α) : ∀ A B ∈ 𝒫 S, (A ∩ B) ∈ 𝒫 S :=\nbegin\n assume (A : set α) (hA : A ∈ 𝒫 S) (B : set α) (hB : B ∈ 𝒫 S),\n have h1 : (A ⊆ S) ∧ (B ⊆ S), from by {split,apply set.subset_of_mem_powerset,exact hA,apply set.subset_of_mem_powerset,exact hB},\n have h2 : (A ∩ B) ⊆ A, from by apply set.inter_subset_left,\n have h3 : (A ∩ B) ⊆ S, from by {apply set.subset.trans h2 h1.left},\n show (A ∩ B) ∈ 𝒫 S, from by {apply set.mem_powerset h3},\nend\n\n/--`theorem`\nSquare of Sum\n :$\\forall x, y \\in \\R: \\paren {x + y}^2 = x^2 + 2 x y + y^2$\n`proof`\nFollows from the distribution of multiplication over addition:\n\n{{begin-eqn}}\n{{eqn | l = \\left({x + y}\\right)^2\n | r = \\left({x + y}\\right) \\cdot \\left({x + y}\\right)\n}}\n{{eqn | r = x \\cdot \\left({x + y}\\right) + y \\cdot \\left({x + y}\\right)\n | c = Real Multiplication Distributes over Addition\n}}\n{{eqn | r = x \\cdot x + x \\cdot y + y \\cdot x + y \\cdot y\n | c = Real Multiplication Distributes over Addition\n}}\n{{eqn | r = x^2 + 2xy + y^2\n | c = \n}}\n{{end-eqn}}\n{{qed}}\n-/\ntheorem square_of_sum (x y : ℝ) : (x + y)^2 = (x^2 + 2*x*y + y^2) := \nbegin\n calc (x + y)^2 = (x+y)*(x+y) : by rw sq\n ... = x*(x+y) + y*(x+y) : by rw add_mul\n ... = x*x + x*y + y*x + y*y : by {rw [mul_comm x (x+y),mul_comm y (x+y)], rw [add_mul,add_mul], ring}\n ... = x^2 + 2*x*y + y^2 : by {repeat {rw ← sq}, rw mul_comm y x, ring}\nend\n\n\n/--`theorem`\nIdentity of Group is Unique\nLet $\\struct {G, \\circ}$ be a group. Then there is a unique identity element $e \\in G$.\n`proof`\nFrom Group has Latin Square Property, there exists a unique $x \\in G$ such that:\n:$a x = b$\n\nand there exists a unique $y \\in G$ such that:\n:$y a = b$\n\nSetting $b = a$, this becomes:\n\nThere exists a unique $x \\in G$ such that:\n:$a x = a$\n\nand there exists a unique $y \\in G$ such that:\n:$y a = a$\n\nThese $x$ and $y$ are both $e$, by definition of identity element.\n{{qed}}\n-/\ntheorem group_identity_unique {G : Type*} [group G] : ∃! e : G, ∀ a : G, e * a = a ∧ a * e = a :=\nbegin\n have h1 : ∀ a b : G, ∃! x : G, a * x = b, from by {\n assume a b : G, use a⁻¹ * b, obviously, },\n have h2 : ∀ a b : G, ∃! y : G, y * a = b, from by {\n assume a b : G, use b * a⁻¹, obviously, }, \n\n have h3 : ∀ a : G, ∃! x : G, a * x = a, from \n assume a : G, h1 a a,\n have h4 : ∀ a : G, ∃! y : G, y * a = a, from\n assume a : G, h2 a a,\n\n have h5 : ∀ a : G, classical.some (h3 a).exists = (1 : G), from assume a :G,\n exists_unique.unique (h3 a) (classical.some_spec (exists_unique.exists (h3 a)))\n (mul_one a),\n have h6 : ∀ a : G, classical.some (h4 a).exists = (1 : G), from assume a : G,\n exists_unique.unique (h4 a) (classical.some_spec (exists_unique.exists (h4 a))) (one_mul a), \n\n show ∃! e : G, ∀ a : G, e * a = a ∧ a * e = a, from by {\n use (1 : G),\n have h7 : ∀ e : G, (∀ a : G, e * a = a ∧ a * e = a) → e = 1, from by {\n assume (e : G) (hident : ∀ a : G, e * a = a ∧ a * e = a),\n have h8 : ∀ a : G, e = classical.some (h3 a).exists, from assume (a : G),\n exists_unique.unique (h3 a) (hident a).right\n (classical.some_spec (exists_unique.exists (h3 a))), \n have h9 : ∀ a : G, e = classical.some (h4 a).exists, from assume (a : G),\n exists_unique.unique (h4 a) (hident a).left\n (classical.some_spec (exists_unique.exists (h4 a))),\n show e = (1 : G), from eq.trans (h9 e) (h6 _), \n },\n exact ⟨by obviously, h7⟩,\n }\nend\n\n/--`theorem`\nOverflow theorem\nLet $F$ be a set of first-order formulas which has finite models of arbitrarily large size. Then $F$ has an infinite model.\n`proof`\nFor each $n$, let $\\mathbf A_n$ be the formula:\n\n$\\exists x_1 \\exists x_2 \\ldots \\exists x_n: \\{x_1 \\ne x_2 \\land x_1 \\ne x_3 \\land \\ldots \\land x_{n - 1} \\ne x_n\\}$\n\nThen $\\mathbf A_i$ is true in a structure $\\AA$ iff $\\AA$ has at least $n$ elements.\n\nTake:\n$$ \\Gamma := F \\cup \\bigcup_{i \\mathop = 1}^\\infty A_i $$\n\nSince $F$ has models of arbitrarily large size, every finite subset of $\\Gamma$ is satisfiable.\n\nFrom the Compactness Theorem, $\\Gamma$ is satisfiable in some model $\\mathbf{M}$.\n\nBut since $\\mathbf{M} \\models A_i$ for each $i$, $\\mathbf{M}$ must be infinite.\n\nSo $F$ has an infinite model.\n\nQED\n-/\ntheorem overflow {L : first_order.language} {F : L.Theory} (h : ∀ n : ℕ, ∃ (m : F.Model) [mfin : fintype m], n ≤ @fintype.card m mfin) : ∃ (M : F.Model), infinite M :=\nFEW SHOT PROMPTS TO CODEX(END)-/\n", "meta": {"author": "ayush1801", "repo": "Autoformalisation_benchmarks", "sha": "51e1e942a0314a46684f2521b95b6b091c536051", "save_path": "github-repos/lean/ayush1801-Autoformalisation_benchmarks", "path": "github-repos/lean/ayush1801-Autoformalisation_benchmarks/Autoformalisation_benchmarks-51e1e942a0314a46684f2521b95b6b091c536051/proof/lean_proof-Natural-Language-Proof-Translation/Correct_statement-lean_proof-3_few_shot_temperature_0_max_tokens_2000_n_1/clean_files/Overflow theorem.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.031618763960768154, "lm_q1q2_score": 0.015685873696434573}} {"text": "import for_mathlib.category_theory.triangulated.pretriangulated_misc\nimport algebra.homology.short_complex.exact\nimport for_mathlib.category_theory.localization.triangulated_subcategory\nimport for_mathlib.category_theory.shift_misc\nimport for_mathlib.category_theory.preadditive.misc\nimport category_theory.limits.preserves.shapes.zero\nimport for_mathlib.category_theory.shift_compatibility_minus\n\nnoncomputable theory\n\nnamespace category_theory\n\nopen limits category pretriangulated\nopen_locale zero_object\n\nlemma limits.exists_discrete_walking_pair_exists_iso_pair\n {C : Type*} [category C] (F : discrete walking_pair ⥤ C) :\n ∃ (X₁ X₂ : C), nonempty (F ≅ pair X₁ X₂) :=\n⟨F.obj (discrete.mk walking_pair.left), F.obj (discrete.mk walking_pair.right),\n ⟨discrete.nat_iso_functor ≪≫ eq_to_iso (by { congr' 1, ext j, cases j, tidy, })⟩⟩\n\nsection\n\nvariables {C D : Type*} [category C] [category D] [has_zero_morphisms C] [has_zero_morphisms D]\n\ninstance preserves_limit_functor_empty (F : C ⥤ D) [F.preserves_zero_morphisms]\n [has_zero_object C] : preserves_limit (functor.empty.{0} C) F :=\nbegin\n let c : cone (functor.empty.{0} C) := cone.mk 0 { app := λ X, 0, },\n have hc : is_limit c :=\n { lift := λ s, 0,\n fac' := by rintro s ⟨⟨⟩⟩,\n uniq' := λ s m hm, subsingleton.elim _ _, },\n refine preserves_limit_of_preserves_limit_cone hc\n { lift := λ s, 0,\n fac' := by rintro s ⟨⟨⟩⟩,\n uniq' := λ s m hm, begin\n refine is_zero.eq_of_tgt _ _ _,\n dsimp [functor.map_cone],\n rw [limits.is_zero.iff_id_eq_zero, ← F.map_id,\n subsingleton.elim (𝟙 (0 : C)) 0, F.map_zero],\n end, },\nend\n\nend\n\nsection\n/-- should be moved to short_complex.exact -/\n\nvariables {C : Type*} [category C]\n\nlemma short_complex.exact.is_zero_of_both_zeros [has_zero_morphisms C]\n {S : short_complex C} (ex : S.exact)\n (h₁ : S.f = 0) (h₂ : S.g = 0) : is_zero S.X₂ :=\n(short_complex.homology_data.of_zeros S h₁ h₂).exact_iff.1 ex\n\nlemma short_complex.exact.epi_f_iff_g_eq_zero [preadditive C] {S : short_complex C}\n (ex : S.exact) : epi S.f ↔ S.g = 0 :=\nbegin\n split,\n { introI,\n simp only [← cancel_epi S.f, S.zero, comp_zero], },\n { intro hg,\n haveI := ex.has_homology,\n haveI := S.is_iso_cycles_i_of hg,\n rw preadditive.epi_iff_cancel_zero,\n intros Z h eq,\n rw [← S.p_desc_cycles_co _ eq, ← cancel_epi (S.cycles_i),\n reassoc_of (S.exact_iff_cycles_i_p_cycles_co_zero.1 ex), comp_zero, zero_comp], },\nend\n\nlemma short_complex.exact.mono_g_iff_f_eq_zero [preadditive C] {S : short_complex C}\n (ex : S.exact) : mono S.g ↔ S.f = 0 :=\nbegin\n split,\n { introI,\n simp only [← cancel_mono S.g, S.zero, zero_comp], },\n { intro hf,\n haveI := ex.has_homology,\n haveI := S.is_iso_p_cycles_co_of hf,\n rw preadditive.mono_iff_cancel_zero,\n intros Z h eq,\n rw [← S.lift_cycles_i _ eq, ← cancel_mono (S.p_cycles_co), assoc,\n S.exact_iff_cycles_i_p_cycles_co_zero.1 ex, comp_zero, zero_comp], },\nend\n\nend\n\nvariables {C D A : Type*} [category C] [has_zero_object C] [has_shift C ℤ]\n [preadditive C] [∀ (n : ℤ), (shift_functor C n).additive] [pretriangulated C]\n [category D] [has_zero_object D] [has_shift D ℤ]\n [preadditive D] [∀ (n : ℤ), (shift_functor D n).additive] [pretriangulated D]\n [category A] [abelian A] (F : C ⥤ A) [functor.preserves_zero_morphisms F]\n\n@[simps]\ndef pretriangulated.triangle.short_complex (T : pretriangulated.triangle C)\n (hT : T ∈ dist_triang C) : short_complex C :=\n (candidate_triangle.of_distinguished T hT).short_complex\n\nnamespace functor\n\n@[protected]\nclass is_homological : Prop :=\n(map_distinguished [] : ∀ (T : pretriangulated.triangle C) (hT : T ∈ dist_triang C),\n ((T.short_complex hT).map F).exact)\n\nnamespace is_homological\n\nlemma mk' (hF : ∀ (T : pretriangulated.triangle C) (hT : T ∈ dist_triang C),\n ∃ (T' : pretriangulated.triangle C) (hT' : T' ∈ dist_triang C) (e : T ≅ T'),\n ((T'.short_complex hT').map F).exact) :\n F.is_homological :=\n⟨λ T hT, begin\n obtain ⟨T', hT', e, ex'⟩ := hF T hT,\n refine (short_complex.exact_iff_of_iso (F.map_short_complex.map_iso\n ((candidate_triangle.to_short_complex_functor C).map_iso _))).2 ex',\n exact preimage_iso (full_subcategory_inclusion _ : candidate_triangle C ⥤ _) e,\nend⟩\n\nvariable {F}\n\nlemma of_iso {G : C ⥤ A} [G.preserves_zero_morphisms] (e : G ≅ F) [F.is_homological] :\n G.is_homological :=\nis_homological.mk (λ T hT, (short_complex.exact_iff_of_iso\n (short_complex.map_nat_iso _ e)).2 (is_homological.map_distinguished F T hT))\n\nend is_homological\n\nsection\n\nopen triangulated\n\nvariable [F.is_homological]\n\ndef kernel_of_is_homological : set C :=\nλ K, ∀ (n : ℤ), limits.is_zero (F.obj (K⟦n⟧))\n\ninstance : is_triangulated_subcategory F.kernel_of_is_homological :=\n{ zero := λ n, limits.is_zero.of_iso (is_zero_zero A)\n (F.map_iso (shift_functor C n).map_zero_object ≪≫ F.map_zero_object),\n shift := λ K m hK n, limits.is_zero.of_iso (hK (m+n))\n (F.map_iso ((shift_functor_add C m n).app K).symm),\n ext₂ := λ T hT h₁ h₃ n, (is_homological.map_distinguished F _\n (triangle.shift_distinguished _ T hT n)).is_zero_of_both_zeros\n (is_zero.eq_of_src (h₁ _) _ _) (is_zero.eq_of_tgt (h₃ _) _ _), }\n\ninstance kernel_of_is_homological_saturated :\n saturated F.kernel_of_is_homological :=\n⟨λ L K i, begin\n introI,\n intros hL n,\n replace hL := hL n,\n rw limits.is_zero.iff_id_eq_zero at ⊢ hL,\n have eq : 𝟙 _ = i ≫ 𝟙 _ ≫ retraction i := by simp only [id_comp, is_split_mono.id],\n replace eq := (shift_functor C n ⋙ F).congr_map eq,\n dsimp only [functor.comp_map] at eq,\n simpa only [functor.map_comp, functor.map_id, hL, zero_comp, comp_zero] using eq,\nend⟩\n\ndef W_of_is_homological : morphism_property C :=\nλ X Y f, ∀ (n : ℤ), is_iso (F.map (f⟦n⟧'))\n\ninstance : preserves_limits_of_shape (discrete walking_pair) F :=\nbegin\n suffices : ∀ (X₁ X₂ : C), preserves_limit (pair X₁ X₂) F,\n { haveI := this,\n exact ⟨λ X, preserves_limit_of_iso_diagram F\n (category_theory.limits.exists_discrete_walking_pair_exists_iso_pair X)\n .some_spec.some_spec.some.symm⟩, },\n intros X₁ X₂,\n haveI : mono (F.biprod_comparison X₁ X₂),\n { rw preadditive.mono_iff_cancel_zero,\n intros Z f hf,\n have h₂ : f ≫ F.map biprod.snd = 0,\n { simpa only [assoc, biprod_comparison_snd, zero_comp] using hf =≫ biprod.snd, },\n have ex := is_homological.map_distinguished F _\n (binary_biproduct_triangle_distinguished X₁ X₂),\n let S := short_complex.mk (F.map (biprod.inl : X₁ ⟶ _)) (F.map (biprod.snd : _ ⟶ X₂))\n (by { rw ← F.map_comp, simp only [biprod.inl_snd, functor.map_zero]}),\n have ex : S.short_exact := short_complex.short_exact.mk\n (is_homological.map_distinguished F _ (binary_biproduct_triangle_distinguished X₁ X₂)),\n have hf' : ∃ (f₁ : Z ⟶ F.obj X₁), f₁ ≫ F.map biprod.inl = f := ⟨_, ex.lift_f f h₂⟩,\n obtain ⟨f₁, rfl⟩ := hf',\n replace hf := hf =≫ biprod.fst,\n simp only [assoc, biprod_comparison_fst, zero_comp, ← F.map_comp,\n biprod.inl_fst, F.map_id, comp_id] at hf,\n rw [hf, zero_comp], },\n haveI : preserves_binary_biproduct X₁ X₂ F :=\n limits.preserves_binary_biproduct_of_mono_biprod_comparison F,\n apply limits.preserves_binary_product_of_preserves_binary_biproduct,\nend\n\n\n@[priority 100]\ninstance is_homological.additive : F.additive :=\nfunctor.additive_of_preserves_binary_products _\n\nlemma kernel_of_is_homological_W :\n triangulated.subcategory.W F.kernel_of_is_homological = F.W_of_is_homological :=\nbegin\n ext X Y f,\n split,\n { intros hf n,\n let f' := f⟦n⟧',\n change is_iso (F.map f'),\n have hf' : triangulated.subcategory.W F.kernel_of_is_homological f' :=\n (morphism_property.compatible_with_shift.iff _ f n).2 hf,\n obtain ⟨Z, g', h', dist, mem⟩ := hf',\n rw is_iso_iff_mono_and_epi,\n split,\n { exact (functor.is_homological.map_distinguished F _\n (inv_rot_of_dist_triangle _ _ dist)).mono_g_iff_f_eq_zero.2\n (limits.is_zero.eq_of_src (mem (-1)) _ _), },\n { exact (functor.is_homological.map_distinguished F _ dist).epi_f_iff_g_eq_zero.2\n (limits.is_zero.eq_of_tgt\n (limits.is_zero.of_iso (mem 0) (F.map_iso ((shift_functor_zero C ℤ).symm.app _))) _ _), }, },\n { intro hf,\n obtain ⟨Z, g, h, mem⟩ := pretriangulated.distinguished_cocone_triangle _ _ f,\n have w : f ≫ g = 0 := pretriangulated.triangle.comp_zero₁₂ _ mem,\n refine ⟨Z, g, h, mem, λ n, _⟩,\n refine short_complex.exact.is_zero_of_both_zeros\n (functor.is_homological.map_distinguished F _\n (rot_of_dist_triangle _ _ (triangle.shift_distinguished _ _ mem n))) _ _,\n { dsimp [pretriangulated.triangle.short_complex],\n haveI := hf n,\n rw ← cancel_epi (F.map (f⟦n⟧')),\n simp only [F.map_zsmul, comp_zero, preadditive.comp_zsmul, ← functor.map_comp, w,\n functor.map_zero, zsmul_zero], },\n { haveI : is_iso (F.map (f⟦n⟧'⟦(1 : ℤ)⟧')) :=\n (nat_iso.is_iso_map_iff (iso_whisker_right (shift_functor_add _ n 1) F) f).1 (hf (n+1)),\n rw ← cancel_mono (F.map (f⟦n⟧'⟦(1 : ℤ)⟧')),\n have w' := F.congr_map (pretriangulated.triangle.comp_zero₂₃ _\n (rot_of_dist_triangle _ _ (triangle.shift_distinguished _ _ mem n))),\n dsimp [pretriangulated.triangle.short_complex] at ⊢ w',\n simp only [preadditive.comp_neg, functor.map_zsmul, assoc, preadditive.comp_zsmul,\n preadditive.zsmul_comp, functor.map_neg, F.map_zero, smul_neg, neg_eq_zero,\n smul_smul, ← units.coe_mul, ← mul_zpow, mul_neg, neg_mul, neg_neg, one_mul, one_smul,\n one_zpow, units.coe_one] at w',\n simp only [← F.map_comp, zero_comp, assoc, preadditive.zsmul_comp, F.map_zsmul, w',\n smul_zero], }, },\nend\n\ninstance shift_is_homological (n : ℤ) :\n (shift_functor C n ⋙ F).is_homological :=\n⟨λ T hT, begin\n refine (short_complex.exact_iff_of_iso _).1\n (functor.is_homological.map_distinguished F _ (triangle.shift_distinguished _ _ hT n)),\n refine short_complex.mk_iso (preadditive.mul_iso ((-1 : units ℤ)^n) (iso.refl _))\n (iso.refl _) (preadditive.mul_iso ((-1 : units ℤ)^n) (iso.refl _)) _ _,\n { dsimp, simp only [preadditive.zsmul_comp, id_comp, comp_id, F.map_zsmul], },\n { dsimp, simp only [preadditive.comp_zsmul, id_comp, comp_id, F.map_zsmul, smul_smul,\n ← units.coe_mul, ← mul_zpow, mul_neg, neg_mul, neg_neg, one_mul, one_smul, one_zpow,\n units.coe_one], },\nend⟩\n\nend\n\n@[priority 100]\ninstance triangulated_functor_preserves_zero_morphisms\n (F : C ⥤ D) [F.has_comm_shift ℤ] [F.is_triangulated] :\n F.preserves_zero_morphisms :=\n⟨λ X₁ X₂, begin\n have h := triangle.comp_zero₁₂ _ (F.map_distinguished _\n (binary_product_triangle_distinguished X₁ X₂)),\n dsimp at h,\n simpa only [← F.map_comp, prod.lift_snd] using h,\nend⟩\n\ninstance triangulated_functor_preserves_binary_products\n (F : C ⥤ D) [F.has_comm_shift ℤ] [F.is_triangulated] :\n preserves_limits_of_shape (discrete walking_pair) F :=\nbegin\n suffices : ∀ (X₁ X₂ : C), preserves_limit (pair X₁ X₂) F,\n { haveI := this,\n exact ⟨λ X, preserves_limit_of_iso_diagram F\n (category_theory.limits.exists_discrete_walking_pair_exists_iso_pair X)\n .some_spec.some_spec.some.symm⟩, },\n intros X₁ X₂,\n haveI : mono (F.biprod_comparison X₁ X₂),\n { rw preadditive.mono_iff_cancel_zero,\n intros Z f hf,\n have h₂ : f ≫ F.map biprod.snd = 0,\n { simpa only [assoc, biprod_comparison_snd, zero_comp] using hf =≫ biprod.snd, },\n obtain ⟨f₁, rfl⟩ := covariant_yoneda_exact₂ _\n (F.map_distinguished _ (binary_biproduct_triangle_distinguished X₁ X₂)) f h₂,\n replace hf := hf =≫ biprod.fst,\n dsimp [triangulated_functor.map_triangle] at hf,\n simp only [assoc, biprod_comparison_fst, zero_comp, ← F.map_comp, biprod.inl_fst,\n F.map_id, comp_id] at hf,\n rw [hf, zero_comp], },\n haveI : preserves_binary_biproduct X₁ X₂ F :=\n limits.preserves_binary_biproduct_of_mono_biprod_comparison _,\n apply limits.preserves_binary_product_of_preserves_binary_biproduct,\nend\n\n@[priority 100]\ninstance triangulated_functor_additive (F : C ⥤ D) [F.has_comm_shift ℤ] [F.is_triangulated ] :\n F.additive :=\nfunctor.additive_of_preserves_binary_products _\n\n@[priority 100]\ninstance is_homological.of_comp (F : C ⥤ D) (G : D ⥤ A) [F.has_comm_shift ℤ]\n [F.is_triangulated] [G.preserves_zero_morphisms]\n [G.is_homological] : (F ⋙ G).is_homological :=\n⟨λ T hT, begin\n have h := is_homological.map_distinguished G _ (F.map_distinguished _ hT),\n exact h,\nend⟩\n\nnamespace is_homological\n\nvariables (F) (T : pretriangulated.triangle C) (hT : T ∈ dist_triang C)\n (n₀ n₁ : ℤ) (h : n₁ = n₀+1)\n\ninclude h\n\ndef δ : F.obj (T.obj₃⟦n₀⟧) ⟶ F.obj (T.obj₁⟦n₁⟧) :=\nF.map (T.mor₃⟦n₀⟧' ≫ (shift_functor_add' C (1 : ℤ) n₀ n₁ (by rw [h, add_comm])).inv.app T.obj₁)\n\nomit h\n\ninclude hT\n\nlemma δ_comp : δ F T n₀ n₁ h ≫ F.map (T.mor₁⟦n₁⟧') = 0 :=\nbegin\n dsimp only [δ],\n rw [← F.map_comp, assoc, ← nat_trans.naturality],\n erw [← functor.map_comp_assoc, pretriangulated.triangle.comp_zero₃₁ _ hT],\n simp only [functor.map_zero, zero_comp],\nend\n\nlemma comp_δ : F.map (T.mor₂⟦n₀⟧') ≫ δ F T n₀ n₁ h = 0 :=\nbegin\n dsimp only [δ],\n rw [← F.map_comp, ← functor.map_comp_assoc, pretriangulated.triangle.comp_zero₂₃ _ hT],\n simp only [functor.map_zero, zero_comp],\nend\n\nvariable [hF : F.is_homological]\n\ninclude hF\n\nlemma ex₂ (n : ℤ) :\n (short_complex.mk (F.map (T.mor₁⟦n⟧')) (F.map (T.mor₂⟦n⟧'))\n (by rw [← F.map_comp, ← functor.map_comp, pretriangulated.triangle.comp_zero₁₂ _ hT,\n functor.map_zero, F.map_zero])).exact :=\nbegin\n refine (short_complex.exact_iff_of_iso _).1\n (is_homological.map_distinguished F _ (pretriangulated.triangle.shift_distinguished C T hT n)),\n refine short_complex.mk_iso (iso.refl _) (preadditive.mul_iso ((-1 : units ℤ)^n) (iso.refl _))\n (iso.refl _) _ _,\n { dsimp,\n simp only [id_comp, linear.comp_smul, comp_id, F.map_zsmul, smul_smul,\n int.units_coe_mul_self, one_zsmul], },\n { dsimp,\n simp only [linear.smul_comp, id_comp, comp_id, F.map_zsmul], },\nend\n\nlemma ex₃ :\n (short_complex.mk (F.map (T.mor₂⟦n₀⟧')) (δ F T n₀ n₁ h) (comp_δ F T hT n₀ n₁ h)).exact :=\nbegin\n refine (short_complex.exact_iff_of_iso _).1\n (is_homological.map_distinguished F _ ((rotate_distinguished_triangle _).1\n (pretriangulated.triangle.shift_distinguished C T hT n₀))),\n refine short_complex.mk_iso (iso.refl _) (preadditive.mul_iso ((-1 : units ℤ)^n₀) (iso.refl _))\n (F.map_iso ((shift_functor_add' C n₀ (1 : ℤ) n₁ h).symm.app T.obj₁)) _ _,\n { dsimp,\n simp only [id_comp, comp_id, F.map_zsmul, preadditive.comp_zsmul, smul_smul,\n int.units_coe_mul_self, one_zsmul], },\n { dsimp [δ],\n simp only [preadditive.zsmul_comp, id_comp, F.map_zsmul, ← F.map_comp, assoc],\n congr' 3,\n simp only [shift_functor_add_comm_hom_app],\n dsimp only [shift_functor_add', eq_to_iso, iso.trans],\n simp only [nat_trans.comp_app, eq_to_hom_app, assoc,\n iso.hom_inv_id_app_assoc, eq_to_hom_trans], },\nend\n\nlemma ex₁ :\n (short_complex.mk (δ F T n₀ n₁ h) (F.map (T.mor₁⟦n₁⟧')) (δ_comp F T hT n₀ n₁ h)).exact :=\nbegin\n refine (short_complex.exact_iff_of_iso _).1\n (is_homological.map_distinguished F _ ((inv_rotate_distinguished_triangle _).2\n (pretriangulated.triangle.shift_distinguished C T hT n₁))),\n refine short_complex.mk_iso\n (F.map_iso ((shift_functor_add' C n₁ (-1) n₀\n (by rw [h, int.add_neg_one, add_tsub_cancel_right])).symm.app T.obj₃))\n (preadditive.mul_iso ((-1 : units ℤ)^n₀) (iso.refl _))\n (preadditive.mul_iso ((-1 : units ℤ)) (iso.refl _)) _ _,\n { change F.map ((shift_functor_add' C n₁ (-1 : ℤ) n₀ _).inv.app T.obj₃) ≫\n F.map (T.mor₃⟦n₀⟧' ≫ (shift_functor_add' C 1 n₀ n₁ _).inv.app T.obj₁) =\n F.map (-(shift_functor C (-1 : ℤ)).map (((-1 : units ℤ)^n₁ • T.mor₃⟦n₁⟧') ≫ (shift_functor_add_comm C 1 n₁).hom.app _) ≫\n (shift_shift_neg (T.obj₁⟦n₁⟧) (1 : ℤ)).hom) ≫ ((-1 : units ℤ)^n₀ • 𝟙 _),\n rw functor.map_neg,\n erw preadditive.zsmul_comp,\n erw preadditive.comp_zsmul,\n rw functor.map_zsmul,\n rw preadditive.zsmul_comp,\n rw functor.map_zsmul,\n rw comp_id,\n rw smul_neg,\n rw smul_smul,\n simp only [h, zpow_add, zpow_one, mul_neg, units.coe_neg, neg_smul, neg_neg, mul_one,\n int.units_coe_mul_self, one_smul, ← F.map_comp],\n erw ← nat_trans.naturality_assoc,\n rw [(shift_functor C (-1 : ℤ)).map_comp, assoc],\n dsimp only [functor.comp_map],\n congr' 2,\n apply shift_compatibility_add_comm, },\n { dsimp,\n simp only [id_comp, comp_id, F.map_zsmul, preadditive.comp_zsmul, smul_smul, id_comp,\n preadditive.zsmul_comp, h, zpow_add, zpow_one, mul_neg, mul_one, units.coe_neg, neg_neg], },\nend\n\nend is_homological\n\nend functor\n\nend category_theory\n", "meta": {"author": "joelriou", "repo": "homotopical_algebra", "sha": "697f49d6744b09c5ef463cfd3e35932bdf2c78a3", "save_path": "github-repos/lean/joelriou-homotopical_algebra", "path": "github-repos/lean/joelriou-homotopical_algebra/homotopical_algebra-697f49d6744b09c5ef463cfd3e35932bdf2c78a3/src/for_mathlib/category_theory/triangulated/homological_functor.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48047867804790706, "lm_q2_score": 0.0325897412425357, "lm_q1q2_score": 0.015658675790136908}} {"text": "/-\nCopyright (c) 2016 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Leonardo de Moura\n-/\nprelude\nimport init.data.ordering.basic init.coe init.data.to_string\n\n/-- Reflect a C++ name object. The VM replaces it with the C++ implementation. -/\ninductive name\n| anonymous : name\n| mk_string : string → name → name\n| mk_numeral : unsigned → name → name\n\n/-- Gadget for automatic parameter support. This is similar to the opt_param gadget, but it uses\n the tactic declaration names tac_name to synthesize the argument.\n Like opt_param, this gadget only affects elaboration.\n For example, the tactic will *not* be invoked during type class resolution. -/\n@[reducible] def {u} auto_param (α : Sort u) (tac_name : name) : Sort u :=\nα\n\n@[simp] lemma {u} auto_param_eq (α : Sort u) (n : name) : auto_param α n = α :=\nrfl\n\ninstance : inhabited name :=\n⟨name.anonymous⟩\n\ndef mk_str_name (n : name) (s : string) : name :=\nname.mk_string s n\n\ndef mk_num_name (n : name) (v : nat) : name :=\nname.mk_numeral (unsigned.of_nat' v) n\n\ndef mk_simple_name (s : string) : name :=\nmk_str_name name.anonymous s\n\ninstance string_to_name : has_coe string name :=\n⟨mk_simple_name⟩\n\ninfix ` <.> `:65 := mk_str_name\n\nopen name\n\ndef name.get_prefix : name → name\n| anonymous := anonymous\n| (mk_string s p) := p\n| (mk_numeral s p) := p\n\ndef name.update_prefix : name → name → name\n| anonymous new_p := anonymous\n| (mk_string s p) new_p := mk_string s new_p\n| (mk_numeral s p) new_p := mk_numeral s new_p\n\n-- Without this option, we get errors when defining the following definitions.\nset_option eqn_compiler.ite false\n\ndef name.to_string_with_sep (sep : string) : name → string\n| anonymous := \"[anonymous]\"\n| (mk_string s anonymous) := s\n| (mk_numeral v anonymous) := repr v\n| (mk_string s n) := name.to_string_with_sep n ++ sep ++ s\n| (mk_numeral v n) := name.to_string_with_sep n ++ sep ++ repr v\n\nprivate def name.components' : name -> list name\n| anonymous := []\n| (mk_string s n) := mk_string s anonymous :: name.components' n\n| (mk_numeral v n) := mk_numeral v anonymous :: name.components' n\n\ndef name.components (n : name) : list name :=\n(name.components' n).reverse\n\nprotected def name.to_string : name → string :=\nname.to_string_with_sep \".\"\n\nprotected def name.repr (n : name) : string :=\n\"`\" ++ n.to_string\n\ninstance : has_to_string name :=\n⟨name.to_string⟩\n\ninstance : has_repr name :=\n⟨name.repr⟩\n\n/- TODO(Leo): provide a definition in Lean. -/\nmeta constant name.has_decidable_eq : decidable_eq name\n/- Both cmp and lex_cmp are total orders, but lex_cmp implements a lexicographical order. -/\nmeta constant name.cmp : name → name → ordering\nmeta constant name.lex_cmp : name → name → ordering\nmeta constant name.append : name → name → name\nmeta constant name.is_internal : name → bool\n\nprotected meta def name.lt (a b : name) : Prop :=\nname.cmp a b = ordering.lt\n\nmeta instance : decidable_rel name.lt :=\nλ a b, ordering.decidable_eq _ _\n\nmeta instance : has_lt name :=\n⟨name.lt⟩\n\nattribute [instance] name.has_decidable_eq\n\nmeta instance : has_append name :=\n⟨name.append⟩\n\n/-- `name.append_after n i` return a name of the form n_i -/\nmeta constant name.append_after : name → nat → name\n\nmeta def name.is_prefix_of : name → name → bool\n| p name.anonymous := ff\n| p n :=\n if p = n then tt else name.is_prefix_of p n.get_prefix\n\nmeta def name.is_suffix_of : name → name → bool\n| anonymous _ := tt\n| (mk_string s n) (mk_string s' n') := (s = s') && name.is_suffix_of n n'\n| (mk_numeral v n) (mk_numeral v' n') := (v = v') && name.is_suffix_of n n'\n| _ _ := ff\n\nmeta def name.replace_prefix : name → name → name → name\n| anonymous p p' := anonymous\n| (mk_string s c) p p' := if c = p then mk_string s p' else mk_string s (name.replace_prefix c p p')\n| (mk_numeral v c) p p' := if c = p then mk_numeral v p' else mk_numeral v (name.replace_prefix c p p')\n", "meta": {"author": "subfish-zhou", "repo": "N2Lean", "sha": "8e858cc5b01f1ad921094dc355db3cb9473a42fd", "save_path": "github-repos/lean/subfish-zhou-N2Lean", "path": "github-repos/lean/subfish-zhou-N2Lean/N2Lean-8e858cc5b01f1ad921094dc355db3cb9473a42fd/library/init/meta/name.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34510528442897664, "lm_q2_score": 0.04535257732852371, "lm_q1q2_score": 0.015651414098547332}} {"text": "import Machine.Parser\nimport Machine.Options\nimport Lean.Elab\n\nopen Lean Machine.Types\n\nnamespace List\n def forAll {α : Type u} (P : α → Prop) : List α → Prop\n | [] => True\n | x :: xs => P x ∧ forAll P xs\n\n def successively {α : Type u} (R : α → α → Prop) : List α → Prop\n | [] => True\n | [x] => True\n | x :: y :: ys => R x y ∧ successively R (y :: ys)\n\n def forLast {α : Type u} (P : α → Prop) : List α → Prop\n | [] => True\n | [x] => P x\n | x :: xs => forLast P xs\n\n def forFirst {α : Type u} (P : α → Prop) : List α → Prop\n | [] => True\n | x :: xs => P x\n\n def nonempty {α : Type u} : List α → Prop\n | [] => False\n | x :: xs => True\nend List\n\nnamespace Machine.Types\n def machine.next : machine → machine\n | ⟨stack, regs, flag, progc⟩ => ⟨stack, regs, flag, progc + 1⟩\n\n def machine.get (m : machine) (r : reg) : Int :=\n (m.regs.find? r).get!\nend Machine.Types\n\nnamespace Machine.Simulator\n def condjmp (M : machine) (cond : Ordering) (ptr : Nat) : machine :=\n ⟨M.stack, M.regs, M.flag, if M.flag == cond then ptr else M.progc + 1⟩\n\n def instr.eval (M : machine) : instr → machine\n | instr.push z => ⟨M.stack.push z, M.regs, M.flag, M.progc + 1⟩\n | instr.pushr r => ⟨M.stack.push (M.get r), M.regs, M.flag, M.progc + 1⟩\n | instr.popr r => ⟨M.stack.pop, M.regs.replace r M.stack.back, M.flag, M.progc + 1⟩\n | instr.dup => ⟨M.stack.push M.stack.back, M.regs, M.flag, M.progc + 1⟩\n | instr.add r₁ r₂ r₃ => ⟨M.stack, M.regs.replace r₃ (M.get r₁ + M.get r₂), M.flag, M.progc + 1⟩\n | instr.neg r₁ r₂ => ⟨M.stack, M.regs.replace r₂ (-M.get r₁), M.flag, M.progc + 1⟩\n | instr.mul r₁ r₂ r₃ => ⟨M.stack, M.regs.replace r₃ (M.get r₁ * M.get r₂), M.flag, M.progc + 1⟩\n | instr.cmp r₁ r₂ => ⟨M.stack, M.regs, compare (M.get r₁) (M.get r₂), M.progc + 1⟩\n | instr.jmp ptr => ⟨M.stack, M.regs, M.flag, ptr⟩\n | instr.je ptr => condjmp M Ordering.eq ptr\n | instr.jg ptr => condjmp M Ordering.gt ptr\n | instr.jl ptr => condjmp M Ordering.lt ptr\n | instr.dump => M.next\n\n def instr.effect (M : machine) : instr → IO Unit\n | instr.dump => do println! \"r1 = {M.get reg.r1}, r2 = {M.get reg.r2}, r3 = {M.get reg.r3}, r4 = {M.get reg.r4}\"\n | _ => return ()\n\n def tick (M : machine) (ρ : tape) : Option machine :=\n match ρ.get? M.progc with\n | none => none\n | some ε => some (instr.eval M ε)\n\n def effect (M : machine) (ρ : tape) : IO Unit :=\n match ρ.get? M.progc with\n | none => return ()\n | some ε => instr.effect M ε\n\n private def await (M₀ : machine) (ρ : tape) : Nat → IO Unit\n | 0 => throw (IO.userError \"execution depth was reached\")\n | n + 1 => do effect M₀ ρ; match tick M₀ ρ with\n | none => return ()\n | some M => await M ρ n\n\n private partial def unsafeAwait (M₀ : machine) (ρ : tape) : IO Unit :=\n do effect M₀ ρ; match tick M₀ ρ with\n | none => return ()\n | some M => unsafeAwait M ρ\n\n def simulate :=\n unsafeAwait machine.init\n\n elab \"asm \" label:ident xs:mnemonic* \" end\" : command => do\n let (ρ, M) ← Machine.Parser.expand xs\n let xs ← Array.mapM instr.restore ρ\n Elab.Command.elabDeclaration (← `(def $label : Array instr := #[$xs,*]))\n\n let opts ← getOptions\n\n if Machine.Options.debugAsm.get opts then\n do await M ρ (Machine.Options.executionDepth.get opts)\n else return ()\n\n def computes (ρ : tape) (M₁ M₂ : machine) :=\n tick M₁ ρ = some M₂\n\n def completed (ρ : tape) (M : machine) :=\n tick M ρ = none\n\n def clean (M : machine) :=\n M = machine.init\n\n def allowed (ρ : tape) (L : List machine) :=\n L.successively (computes ρ) ∧ L.forLast (completed ρ)\n\n def terminator (ρ : tape) (L : List machine) :=\n L.nonempty ∧ L.forFirst clean ∧ allowed ρ L\n\n def terminating (ρ : tape) :=\n ∃ L, terminator ρ L\n\n asm loop\n M: jmp M\n end\n\n theorem some_inj {α : Type u} {a b : α} (p : some a = some b) : a = b :=\n by { apply Option.noConfusion p; apply id }\n\n theorem loop.conservative : ∀ (M₁ M₂ : machine), tick M₁ loop = M₂ → M₁ = M₂ :=\n λ ⟨stack₁, regs₁, flags₁, progc₁⟩ ⟨stack₂, regs₂, flags₂, progc₂⟩ H => by {\n induction progc₁; apply some_inj H; cases H\n }\n\n theorem loopTerminator : ∀ (L : List machine), terminator loop L → False\n | [], ⟨p, _⟩ => p\n | [x], ⟨_, ⟨q, ⟨_, h⟩⟩⟩ => by { rw [q] at h; cases h }\n | x :: y :: ys, ⟨p, ⟨q, ⟨r, h⟩⟩⟩ => by {\n apply loopTerminator (y :: ys); apply And.intro;\n apply True.intro; apply And.intro; rw [←loop.conservative x y r.left];\n apply q; apply And.intro; apply r.right; apply h\n }\n\n theorem nonterminating : ¬terminating loop :=\n λ | Exists.intro L η => loopTerminator L η\nend Machine.Simulator", "meta": {"author": "forked-from-1kasper", "repo": "lean-vcpu", "sha": "7c6f4acc075bb2ff2dfdea28f6c685914a956819", "save_path": "github-repos/lean/forked-from-1kasper-lean-vcpu", "path": "github-repos/lean/forked-from-1kasper-lean-vcpu/lean-vcpu-7c6f4acc075bb2ff2dfdea28f6c685914a956819/Machine/Simulator.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.411110869232168, "lm_q2_score": 0.03789242459243669, "lm_q1q2_score": 0.015577987611511027}} {"text": "/-\nCopyright (c) 2022 Devon Tuma. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Devon Tuma\n-/\nimport computational_monads.simulation_semantics.simulate.support\nimport computational_monads.simulation_semantics.simulate.eval_dist\nimport computational_monads.simulation_semantics.simulate.subsingleton\nimport computational_monads.support.prod\n\n/-!\n# Tracking Simulation Oracle\n\nThis file defines a constructor for simulation oracles that use the internal state\nfor the purpose of tracking some value, in a way that doesn't affect the actual query result.\nFor example a logging oracle just tracks the queries, without actually affecting the return value.\n\nThe definition is in terms of a query function that responds to queries,\nand an indepdent update_state function that controls the internal state.\nFor simplicity the update state function rather than having oracle access.\n\nIn many cases this definition will be composed with an oracle with result depending on the state,\nbut this construction allows seperation of the components that affect state independently.\n-/\n\nvariables {α β γ : Type} {spec spec' spec'': oracle_spec}\n\nstructure tracking_sim_oracle (spec spec' : oracle_spec) (S : Type)\n extends sim_oracle spec spec' S :=\n(default_state := default_state)\n(answer_query : Π (i : spec.ι), spec.domain i → oracle_comp spec' (spec.range i))\n(update_state : Π (s : S) (i : spec.ι), spec.domain i → spec.range i → S)\n(o := λ i x, (λ u, (u, update_state x.2 i x.1 u)) <$> (answer_query i x.1))\n\nstructure stateless_sim_oracle (spec spec' : oracle_spec)\n extends tracking_sim_oracle spec spec' unit :=\n(default_state := ())\n(answer_query := answer_query)\n(update_state := λ _ _ _ _, ())\n(o := λ i x, (λ u, (u, ())) <$> (answer_query i x.1))\n\ndef identi_o (spec : oracle_spec) : stateless_sim_oracle spec spec :=\n{ answer_query := λ i t, oracle_comp.query i t }\n\n/-- Oracle where the query result is indepenent of the current oracle state,\nalthough the new state may depend upon the previous state.\nFor example a logging oracle that just tracks the input and output of queries.\n`o` is the way the oracle responds to queries, which doesn't have access to the state.\n`update_state` takes a query and internal state and returns the new internal state.\nNote that `update_state` is not a probabalistic function, and has no oracle access -/\ndef tracking_oracle {spec : oracle_spec} {S : Type}\n (o : Π (i : spec.ι), spec.domain i → oracle_comp spec' (spec.range i))\n (update_state : Π (s : S) (i : spec.ι), spec.domain i → spec.range i → S)\n (default_state : S) : sim_oracle spec spec' S :=\n{ default_state := default_state,\n o := λ i ⟨t, s⟩, (λ u, (u, update_state s i t u)) <$> (o i t) }\n\nnotation `⟪` o `|` update_state `,` default_state `⟫` :=\n tracking_oracle o update_state default_state\n\nnamespace tracking_oracle\n\nopen_locale big_operators ennreal\nopen oracle_comp oracle_spec\n\nvariables {S S' : Type} (o : Π (i : spec.ι), spec.domain i → oracle_comp spec' (spec.range i))\n (o' : Π (i : spec.ι), spec.domain i → oracle_comp spec'' (spec.range i))\n (update_state : Π (s : S) (i : spec.ι), spec.domain i → spec.range i → S)\n (update_state' : Π (s : S') (i : spec.ι), spec.domain i → spec.range i → S')\n (default_state : S) (default_state' : S') (a : α) (i : spec.ι) (t : spec.domain i)\n (oa : oracle_comp spec α) (ob : α → oracle_comp spec β) (s : S) (s' : S')\n (x : spec.domain i × S) (y : spec.range i × S)\n\n@[simp] lemma apply_eq : ⟪o | update_state, default_state⟫ i x =\n (λ u, (u, update_state x.2 i x.1 u)) <$> (o i x.1) := by {cases x, refl}\n\ninstance decidable [decidable_eq S] [∀ i x, (o i x).decidable] :\n (⟪o | update_state, default_state⟫ i x).decidable :=\nby { rw [apply_eq], exact oracle_comp.decidable_map _ _ }\n\nsection support\n\n@[simp] lemma support_apply : (⟪o | update_state, default_state⟫ i x).support =\n (λ u, (u, update_state x.2 i x.1 u)) '' (o i x.1).support :=\nset.ext (λ y, by rw [apply_eq, support_map])\n\nlemma fin_support_apply [∀ i t, (o i t).decidable] [decidable_eq S] :\n (⟪o | update_state, default_state⟫ i x).fin_support =\n (o i x.1).fin_support.image (λ u, (u, update_state x.2 i x.1 u)) :=\nby simp only [fin_support_eq_iff_support_eq_coe, apply_eq, support_map,\n finset.coe_image, coe_fin_support_eq_support]\n\nlemma mem_support_apply_iff {y : spec.range i × S} :\n y ∈ (⟪o | update_state, default_state⟫ i x).support ↔\n y.1 ∈ (o i x.1).support ∧ update_state x.2 i x.1 y.1 = y.2 :=\nby simp only [support_apply, prod.eq_iff_fst_eq_snd_eq, set.mem_image,\n and_comm (_ = y.fst), exists_eq_right_right]\n\n/-- If the oracle can take on any value then the first element of the support is unchanged -/\ntheorem support_simulate'_eq_support (h : ∀ i t, (o i t).support = ⊤) :\n (simulate' ⟪o | update_state, default_state⟫ oa s).support = oa.support :=\nsupport_simulate'_eq_support _ oa s (λ i t s, set.ext (λ x, by simp only\n [h, set.top_eq_univ, set.mem_univ, true_and, apply_eq, support_map, set.mem_image,\n prod.exists, prod.mk.inj_iff, exists_eq_left, exists_eq_left', exists_apply_eq_apply]))\n\n/-- Particular case of `support_simulate'_eq_support` for `query`.\nIn particular a tracking oracle that *only* does tracking doesn't affect the main output. -/\n@[simp] lemma support_simulate'_query_eq_support :\n (simulate' ⟪query | update_state, default_state⟫ oa s).support = oa.support :=\nsupport_simulate'_eq_support query update_state default_state oa s (λ _ _, rfl)\n\ntheorem support_simulate'_eq_support_simulate' (h : ∀ i t, (o i t).support = (o' i t).support) :\n (simulate' ⟪o | update_state, default_state⟫ oa s).support =\n (simulate' ⟪o' | update_state', default_state'⟫ oa s').support :=\nsupport_simulate'_eq_support_simulate' (λ i t s s', set.ext $ λ x,\n by simp only [mem_support_apply_iff, h, simulate'_query, support_map, support_apply,\n set.mem_image, set.mem_set_of_eq, prod.exists, exists_and_distrib_right, exists_eq_right,\n exists_eq_right', exists_eq_right_right, prod.eq_iff_fst_eq_snd_eq, and_comm (_ = x)]) oa s s'\n\n/-- The support of `simulate'` is independt of the tracking functions -/\ntheorem support_simulate'_eq_support_simulate'_of_oracle_eq :\n (simulate' ⟪o | update_state, default_state⟫ oa s).support =\n (simulate' ⟪o | update_state', default_state'⟫ oa s').support :=\nsupport_simulate'_eq_support_simulate' o o _ _ _ _ oa s s' (λ _ _, rfl)\n\nsection subsingleton\n\nvariables [subsingleton S]\n\n@[simp] lemma support_apply_of_subsingleton :\n (⟪o | update_state, default_state⟫ i x).support = prod.fst ⁻¹' (o i x.1).support :=\nset.ext (λ y, by erw [apply_eq, map_eq_bind_return_comp,\n support_bind_prod_mk_of_snd_subsingleton, set.image_id])\n\nlemma support_simulate_eq_preimage_support_of_subsingleton (h : ∀ i t, (o i t).support = ⊤) :\n (simulate ⟪o | update_state, default_state⟫ oa s).support = prod.fst ⁻¹' oa.support :=\nby rw [set.preimage, support_simulate_eq_support_simulate'_of_subsingleton,\n support_simulate'_eq_support o _ _ oa s h]\n\n@[simp] lemma support_simulate_query_eq_support_of_subsingleton :\n (simulate ⟪query | update_state, default_state⟫ oa s).support = prod.fst ⁻¹' oa.support :=\nsupport_simulate_eq_preimage_support_of_subsingleton query _ _ oa s (λ _ _, rfl)\n\nend subsingleton\n\nend support\n\nsection eval_dist\n\n@[simp] lemma eval_dist_apply :\n ⁅⟪o | update_state, default_state⟫ i (t, s)⁆ = ⁅o i t⁆.map (λ u, (u, update_state s i t u)) :=\nby rw [apply_eq, eval_dist_map]\n\n/-- If the oracle has uniform distribution, then the distribution under `simulate'` is unchanged -/\ntheorem eval_dist_simulate'_eq_eval_dist\n (h : ∀ i t, ⁅o i t⁆ = pmf.uniform_of_fintype (spec.range i)) :\n ⁅simulate' ⟪o | update_state, default_state⟫ oa s⁆ = ⁅oa⁆ :=\neval_dist_simulate'_eq_eval_dist _ oa s (λ i t s, trans\n (by simpa [eval_dist_apply, pmf.map_comp] using pmf.map_id ⁅o i t⁆) (h i t))\n\n/-- Specific case of `eval_dist_simulate'_eq_eval_dist` for query.\nIn particular if a tracking oracle *only* does tracking gives the same main output distribution. -/\n@[simp] lemma eval_dist_simulate'_query_eq_eval_dist :\n ⁅simulate' ⟪query | update_state, default_state⟫ oa s⁆ = ⁅oa⁆ :=\neval_dist_simulate'_eq_eval_dist query update_state default_state oa s (λ _ _, rfl)\n\nlemma eval_dist_simulate'_eq_eval_dist_simulate'\n (h : ∀ i t, o i t ≃ₚ o' i t) : ⁅simulate' ⟪o | update_state, default_state⟫ oa s⁆ =\n ⁅simulate' ⟪o' | update_state', default_state'⟫ oa s'⁆ :=\neval_dist_simulate'_eq_eval_dist_simulate' (λ i t s s',\n sorry) _ _ _ --by simp [pmf.map_comp, tracking_oracle.apply_eq, eval_dist_map, h]) oa s s'\n\n/-- The first output of simulation under different `tracking_oracle` with the same oracle\nis the same regardless of if the tracking functions are different. -/\ntheorem eval_dist_simulate'_eq_eval_dist_simulate'_of_oracle_eq :\n ⁅simulate' ⟪o | update_state, default_state⟫ oa s⁆ =\n ⁅simulate' ⟪o | update_state', default_state'⟫ oa s'⁆ :=\neval_dist_simulate'_eq_eval_dist_simulate' o o _ _ _ _ oa s s' (λ _ _, rfl)\n\nend eval_dist\n\nsection prob_event\n\nvariable (e : set α)\n\n@[simp] lemma prob_event_apply (e : set (spec.range i × S)) :\n ⁅e | ⟪o | update_state, default_state⟫ i (t, s)⁆ =\n ⁅λ u, (u, update_state s i t u) ∈ e | o i t⁆ :=\nby simpa only [apply_eq, prob_event_map]\n\nlemma prob_event_simulate'_eq_prob_event\n (h : ∀ i t, ⁅o i t⁆ = pmf.uniform_of_fintype (spec.range i)) :\n ⁅e | simulate' ⟪o | update_state, default_state⟫ oa s⁆ = ⁅e | oa⁆ :=\nprob_event_eq_of_eval_dist_eq (eval_dist_simulate'_eq_eval_dist _ _ _ _ _ h) e\n\n/-- Specific case of `eval_dist_simulate'_eq_eval_dist` for query.\nIn particular if a tracking oracle *only* does tracking gives the same main output distribution. -/\nlemma prob_event_simulate'_query_eq_prob_event :\n ⁅e | simulate' ⟪query | update_state, default_state⟫ oa s⁆ = ⁅e | oa⁆ :=\nprob_event_simulate'_eq_prob_event _ _ _ oa s e (λ _ _, rfl)\n\nlemma prob_event_simulate'_eq_prob_event_simulate'\n (h : ∀ i t, o i t ≃ₚ o' i t) : ⁅e | simulate' ⟪o | update_state, default_state⟫ oa s⁆ =\n ⁅e | simulate' ⟪o' | update_state', default_state'⟫ oa s'⁆ :=\nprob_event_eq_of_eval_dist_eq (eval_dist_simulate'_eq_eval_dist_simulate' _ _ _ _ _ _ _ _ _ h) e\n\n/-- The first output of simulation under different `tracking_oracle` with the same oracle\nis the same regardless of if the tracking functions are different. -/\ntheorem prob_event_simulate'_eq_eval_dist_simulate'_of_oracle_eq :\n ⁅e | simulate' ⟪o | update_state, default_state⟫ oa s⁆ =\n ⁅e | simulate' ⟪o | update_state', default_state'⟫ oa s'⁆ :=\nprob_event_simulate'_eq_prob_event_simulate' o o _ _ _ _ oa s s' e (λ _ _, rfl)\n\nend prob_event\n\nend tracking_oracle", "meta": {"author": "dtumad", "repo": "lean-crypto-formalization", "sha": "f975a9a9882120b509553a7ced9aa05b745ff154", "save_path": "github-repos/lean/dtumad-lean-crypto-formalization", "path": "github-repos/lean/dtumad-lean-crypto-formalization/lean-crypto-formalization-f975a9a9882120b509553a7ced9aa05b745ff154/src/computational_monads/simulation_semantics/constructions/tracking_oracle.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3140505449918075, "lm_q2_score": 0.04958902825121458, "lm_q1q2_score": 0.015573461347908078}} {"text": "import data.quot\nimport .homotopy_classes\n\nuniverses v u\n\nopen category_theory\nlocal notation f ` ∘ `:80 g:80 := g ≫ f\n\nnamespace homotopy_theory.cofibrations\n-- Homotopy equivalences as the weak equivalences of an I-category.\nopen homotopy_theory.weak_equivalences\n\nvariables {C : Type u} [category.{v} C]\n [has_initial_object.{v} C] [has_coproducts.{v} C] [I_category.{v} C]\n\ninstance homotopy_category.category_with_weak_equivalences :\n category_with_weak_equivalences (category_mod_congruence C homotopy_congruence) :=\nisomorphisms_as_weak_equivalences\n\ninstance I_category.category_with_weak_equivalences : category_with_weak_equivalences C :=\npreimage_with_weak_equivalences (quotient_functor C homotopy_congruence)\n\ndef homotopy_equivalence {x y : C} (f : x ⟶ y) : Prop := is_weq f\n\nlemma homotopic_iff_equal_in_ho {x y : C} {f g : x ⟶ y} : f ≃ g ↔ ⟦f⟧ = ⟦g⟧ :=\nby symmetry; apply quotient.eq\n\nlemma homotopy_equivalence_iff {x y : C} {f : x ⟶ y} :\n homotopy_equivalence f ↔ ∃ g, g ∘ f ≃ 𝟙 _ ∧ f ∘ g ≃ 𝟙 _ :=\nbegin\n split,\n { intro h, cases h with i hi,\n cases quotient.exists_rep i.inv with g hg,\n existsi g, split; rw homotopic_iff_equal_in_ho,\n { have := i.hom_inv_id',\n rw [hi, ←hg] at this, exact this },\n { have := i.inv_hom_id',\n rw [hi, ←hg] at this, exact this } },\n { intro h, rcases h with ⟨g, h₁, h₂⟩,\n refine ⟨iso.mk ⟦f⟧ ⟦g⟧ _ _, rfl⟩;\n { dsimp [auto_param], change ⟦_⟧ = ⟦_⟧, rw ←homotopic_iff_equal_in_ho,\n exact h₁ <|> exact h₂ } }\nend\n\nend homotopy_theory.cofibrations\n", "meta": {"author": "rwbarton", "repo": "lean-homotopy-theory", "sha": "39e1b4ea1ed1b0eca2f68bc64162dde6a6396dee", "save_path": "github-repos/lean/rwbarton-lean-homotopy-theory", "path": "github-repos/lean/rwbarton-lean-homotopy-theory/lean-homotopy-theory-39e1b4ea1ed1b0eca2f68bc64162dde6a6396dee/src/homotopy_theory/formal/i_category/homotopy_equivalences.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.031143832782908713, "lm_q1q2_score": 0.015571916391454357}} {"text": "import Lean\nopen Lean Elab Command Term Meta\n\n/- ## Elaboration: Solutions -/\n\n/- ### 1. -/\n\nelab n:term \"♥\" a:\"♥\"? b:\"♥\"? : term => do\n let nExpr : Expr ← elabTermEnsuringType n (mkConst `Nat)\n if let some a := a then\n if let some b := b then\n return Expr.app (Expr.app (Expr.const `Nat.add []) nExpr) (mkNatLit 3)\n else\n return Expr.app (Expr.app (Expr.const `Nat.add []) nExpr) (mkNatLit 2)\n else\n return Expr.app (Expr.app (Expr.const `Nat.add []) nExpr) (mkNatLit 1)\n\n#eval 7 ♥ -- 8\n#eval 7 ♥♥ -- 9\n#eval 7 ♥♥♥ -- 10\n\n/- ### 2. -/\n\n-- a) using `syntax` + `@[command_elab alias] def elabOurAlias : CommandElab`\nsyntax (name := aliasA) (docComment)? \"aliasA \" ident \" ← \" ident* : command\n\n@[command_elab «aliasA»]\ndef elabOurAlias : CommandElab := λ stx =>\n match stx with\n | `(aliasA $x:ident ← $ys:ident*) =>\n for y in ys do\n Lean.logInfo y\n | _ =>\n throwUnsupportedSyntax\n\naliasA hi.hello ← d.d w.w nnn\n\n-- b) using `syntax` + `elab_rules`.\nsyntax (name := aliasB) (docComment)? \"aliasB \" ident \" ← \" ident* : command\n\nelab_rules : command\n | `(command | aliasB $m:ident ← $ys:ident*) =>\n for y in ys do\n Lean.logInfo y\n\naliasB hi.hello ← d.d w.w nnn\n\n-- c) using `elab`\nelab \"aliasC \" x:ident \" ← \" ys:ident* : command =>\n for y in ys do\n Lean.logInfo y\n\naliasC hi.hello ← d.d w.w nnn\n\n/- ### 3. -/\n\nopen Parser.Tactic\n\n-- a) using `syntax` + `@[tactic nthRewrite] def elabNthRewrite : Lean.Elab.Tactic.Tactic`.\nsyntax (name := nthRewriteA) \"nth_rewriteA \" (config)? num rwRuleSeq (ppSpace location)? : tactic\n\n@[tactic nthRewriteA] def elabNthRewrite : Lean.Elab.Tactic.Tactic := fun stx => do\n match stx with\n | `(tactic| nth_rewriteA $[$cfg]? $n $rules $_loc) =>\n Lean.logInfo \"rewrite location!\"\n | `(tactic| nth_rewriteA $[$cfg]? $n $rules) =>\n Lean.logInfo \"rewrite target!\"\n | _ =>\n throwUnsupportedSyntax\n\n-- b) using `syntax` + `elab_rules`.\nsyntax (name := nthRewriteB) \"nth_rewriteB \" (config)? num rwRuleSeq (ppSpace location)? : tactic\n\nelab_rules (kind := nthRewriteB) : tactic\n | `(tactic| nth_rewriteB $[$cfg]? $n $rules $_loc) =>\n Lean.logInfo \"rewrite location!\"\n | `(tactic| nth_rewriteB $[$cfg]? $n $rules) =>\n Lean.logInfo \"rewrite target!\"\n\n-- c) using `elab`.\nelab \"nth_rewriteC \" (config)? num rwRuleSeq loc:(ppSpace location)? : tactic =>\n if let some loc := loc then\n Lean.logInfo \"rewrite location!\"\n else\n Lean.logInfo \"rewrite target!\"\n\nexample : 2 + 2 = 4 := by\n nth_rewriteC 2 [← add_zero] at h\n nth_rewriteC 2 [← add_zero]\n sorry\n", "meta": {"author": "leanprover-community", "repo": "lean4-metaprogramming-book", "sha": "0b2e7e2c0cacac530ed947df878088c5d9715412", "save_path": "github-repos/lean/leanprover-community-lean4-metaprogramming-book", "path": "github-repos/lean/leanprover-community-lean4-metaprogramming-book/lean4-metaprogramming-book-0b2e7e2c0cacac530ed947df878088c5d9715412/lean/solutions/elaboration.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4225046202709847, "lm_q2_score": 0.036769465415896915, "lm_q1q2_score": 0.01553526902311063}} {"text": "/-\nCopyright (c) 2022 Scott Morrison. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Scott Morrison, Gabriel Ebner, Floris van Doorn\n-/\nimport Lean\nimport Std.Tactic.OpenPrivate\n\n/-!\n# Helper functions for using the simplifier.\n\n[TODO] Needs documentation, cleanup, and possibly reunification of `mkSimpContext'` with core.\n-/\n\nopen Lean Elab.Tactic\n\ndef Lean.PHashSet.toList [BEq α] [Hashable α] (s : Lean.PHashSet α) : List α :=\n s.1.toList.map (·.1)\n\nnamespace Lean\n\nnamespace Meta.DiscrTree\n\npartial def Trie.getElements : Trie α s → Array α\n | Trie.node vs children =>\n vs ++ children.concatMap fun (_, child) ↦ child.getElements\n\ndef getElements (d : DiscrTree α s) : Array α :=\n d.1.toList.toArray.concatMap fun (_, child) => child.getElements\n\nend Meta.DiscrTree\n\nnamespace Meta.Simp\nopen Elab.Tactic\n\ninstance : ToFormat SimpTheorems where\n format s :=\nf!\"pre:\n{s.pre.getElements.toList}\npost:\n{s.post.getElements.toList}\nlemmaNames:\n{s.lemmaNames.toList.map (·.key)}\ntoUnfold: {s.toUnfold.toList}\nerased: {s.erased.toList.map (·.key)}\ntoUnfoldThms: {s.toUnfoldThms.toList}\"\n\ndef mkEqSymm (e : Expr) (r : Simp.Result) : MetaM Simp.Result :=\n ({ expr := e, proof? := · }) <$>\n match r.proof? with\n | none => pure none\n | some p => some <$> Meta.mkEqSymm p\n\ndef mkCast (r : Simp.Result) (e : Expr) : MetaM Expr := do\n mkAppM ``cast #[← r.getProof, e]\n\n/-- Return all propositions in the local context. -/\ndef getPropHyps : MetaM (Array FVarId) := do\n let mut result := #[]\n for localDecl in (← getLCtx) do\n unless localDecl.isAuxDecl do\n if (← isProp localDecl.type) then\n result := result.push localDecl.fvarId\n return result\n\nexport private mkDischargeWrapper from Lean.Elab.Tactic.Simp\n\n-- copied from core\n/--\nIf `ctx == false`, the config argument is assumed to have type `Meta.Simp.Config`,\nand `Meta.Simp.ConfigCtx` otherwise.\nIf `ctx == false`, the `discharge` option must be none\n-/\ndef mkSimpContext' (simpTheorems : SimpTheorems) (stx : Syntax) (eraseLocal : Bool)\n (kind := SimpKind.simp) (ctx := false) (ignoreStarArg : Bool := false) :\n TacticM MkSimpContextResult := do\n if ctx && !stx[2].isNone then\n if kind == SimpKind.simpAll then\n throwError \"'simp_all' tactic does not support 'discharger' option\"\n if kind == SimpKind.dsimp then\n throwError \"'dsimp' tactic does not support 'discharger' option\"\n let dischargeWrapper ← mkDischargeWrapper stx[2]\n let simpOnly := !stx[3].isNone\n let simpTheorems ← if simpOnly then\n simpOnlyBuiltins.foldlM (·.addConst ·) {}\n else\n pure simpTheorems\n let congrTheorems ← Meta.getSimpCongrTheorems\n let r ← elabSimpArgs stx[4] (eraseLocal := eraseLocal) (kind := kind) {\n config := (← elabSimpConfig stx[1] (kind := kind))\n simpTheorems := #[simpTheorems], congrTheorems\n }\n if !r.starArg || ignoreStarArg then\n return { r with dischargeWrapper }\n else\n let mut simpTheorems := r.ctx.simpTheorems\n let hs ← getPropHyps\n for h in hs do\n unless simpTheorems.isErased (.fvar h) do\n simpTheorems ← simpTheorems.addTheorem (.fvar h) (← h.getDecl).toExpr\n return { ctx := { r.ctx with simpTheorems }, dischargeWrapper }\n\nexport private checkTypeIsProp shouldPreprocess preprocess mkSimpTheoremCore\n from Lean.Meta.Tactic.Simp.SimpTheorems\n\n/-- Similar to `mkSimpTheoremsFromConst` except that it also returns the names of the generated\nlemmas.\nRemark: either the length of the arrays is the same,\nor the length of the first one is 0 and the length of the second one is 1. -/\ndef mkSimpTheoremsFromConst' (declName : Name) (post : Bool) (inv : Bool) (prio : Nat) :\n MetaM (Array Name × Array SimpTheorem) := do\n let cinfo ← getConstInfo declName\n let val := mkConst declName (cinfo.levelParams.map mkLevelParam)\n withReducible do\n let type ← inferType val\n checkTypeIsProp type\n if inv || (← shouldPreprocess type) then\n let mut r := #[]\n let mut auxNames := #[]\n for (val, type) in (← preprocess val type inv (isGlobal := true)) do\n let auxName ← mkAuxLemma cinfo.levelParams type val\n auxNames := auxNames.push auxName\n r := r.push <| ← mkSimpTheoremCore (.decl declName)\n (mkConst auxName (cinfo.levelParams.map mkLevelParam)) #[] (mkConst auxName) post prio\n return (auxNames, r)\n else\n return (#[], #[← mkSimpTheoremCore (.decl declName) (mkConst declName <|\n cinfo.levelParams.map mkLevelParam) #[] (mkConst declName) post prio])\n\n/-- Similar to `addSimpTheorem` except that it returns an array of all auto-generated\n simp-theorems. -/\ndef addSimpTheorem' (ext : SimpExtension) (declName : Name) (post : Bool) (inv : Bool)\n (attrKind : AttributeKind) (prio : Nat) : MetaM (Array Name) := do\n let (auxNames, simpThms) ← mkSimpTheoremsFromConst' declName post inv prio\n for simpThm in simpThms do\n ext.add (SimpEntry.thm simpThm) attrKind\n return auxNames\n\n/-- Similar to `AttributeImpl.add` in `mkSimpAttr` except that it doesn't require syntax,\n and returns an array of all auto-generated lemmas. -/\ndef addSimpAttr (declName : Name) (ext : SimpExtension) (attrKind : AttributeKind)\n (post : Bool) (prio : Nat) :\n MetaM (Array Name) := do\n let info ← getConstInfo declName\n if (← isProp info.type) then\n addSimpTheorem' ext declName post (inv := false) attrKind prio\n else if info.hasValue then\n if let some eqns ← getEqnsFor? declName then\n let mut auxNames := #[]\n for eqn in eqns do\n -- Is this list is always empty?\n let newAuxNames ← addSimpTheorem' ext eqn post (inv := false) attrKind prio\n auxNames := auxNames ++ newAuxNames\n ext.add (SimpEntry.toUnfoldThms declName eqns) attrKind\n if hasSmartUnfoldingDecl (← getEnv) declName then\n ext.add (SimpEntry.toUnfold declName) attrKind\n return auxNames\n else\n ext.add (SimpEntry.toUnfold declName) attrKind\n return #[]\n else\n throwError \"invalid 'simp', it is not a proposition nor a definition (to unfold)\"\n\n/-- Similar to `AttributeImpl.add` in `mkSimpAttr` except that it returns an array of all\n auto-generated lemmas. -/\ndef addSimpAttrFromSyntax (declName : Name) (ext : SimpExtension) (attrKind : AttributeKind)\n (stx : Syntax) : MetaM (Array Name) := do\n let post := if stx[1].isNone then true else stx[1][0].getKind == ``Lean.Parser.Tactic.simpPost\n let prio ← getAttrParamOptPrio stx[2]\n addSimpAttr declName ext attrKind post prio\n\nend Simp\n\n/-- Construct a `SimpTheorems` from a list of names. (i.e. as with `simp only`). -/\ndef simpTheoremsOfNames (lemmas : List Name) : MetaM SimpTheorems := do\n lemmas.foldlM (·.addConst ·) (← simpOnlyBuiltins.foldlM (·.addConst ·) {})\n\n/-- Simplify an expression using only a list of lemmas specified by name. -/\n-- TODO We need to write a `mkSimpContext` in `MetaM`\n-- that supports all the bells and whistles in `simp`.\n-- It should generalize this, and another partial implementation in `Tactic.Simps.Basic`.\ndef simpOnlyNames (lemmas : List Name) (e : Expr) (config : Simp.Config := {}) :\n MetaM Simp.Result := do\n (·.1) <$> simp e\n { simpTheorems := #[← simpTheoremsOfNames lemmas], congrTheorems := ← getSimpCongrTheorems,\n config := config }\n\n/--\nGiven a simplifier `S : Expr → MetaM Simp.Result`,\nand an expression `e : Expr`, run `S` on the type of `e`, and then\nconvert `e` into that simplified type, using a combination of type hints and `Eq.mp`.\n-/\ndef simpType (S : Expr → MetaM Simp.Result) (e : Expr) : MetaM Expr := do\n match (← S (← inferType e)) with\n | ⟨ty', none, _⟩ => mkExpectedTypeHint e ty'\n -- We use `mkExpectedTypeHint` in this branch as well, in order to preserve the binder types.\n | ⟨ty', some prf, _⟩ => mkExpectedTypeHint (← mkEqMP prf e) ty'\n\n/-- Independently simplify both the left-hand side and the right-hand side\nof an equality. The equality is allowed to be under binders.\nReturns the simplified equality and a proof of it. -/\ndef simpEq (S : Expr → MetaM Simp.Result) (type pf : Expr) : MetaM (Expr × Expr) := do\n forallTelescope type fun fvars type => do\n let .app (.app (.app (.const `Eq [u]) α) lhs) rhs := type | throwError \"simpEq expecting Eq\"\n let ⟨lhs', lhspf?, _⟩ ← S lhs\n let ⟨rhs', rhspf?, _⟩ ← S rhs\n let mut pf' := mkAppN pf fvars\n if let some lhspf := lhspf? then\n pf' ← mkEqTrans (← mkEqSymm lhspf) pf'\n if let some rhspf := rhspf? then\n pf' ← mkEqTrans pf' rhspf\n let type' := mkApp3 (mkConst ``Eq [u]) α lhs' rhs'\n return (← mkForallFVars fvars type', ← mkLambdaFVars fvars pf')\n\n/-- Checks whether `declName` is in `SimpTheorems` as either a lemma or definition to unfold. -/\ndef SimpTheorems.contains (d : SimpTheorems) (declName : Name) :=\n d.isLemma (.decl declName) || d.isDeclToUnfold declName\n\n/-- Tests whether `decl` has `simp`-attribute `simpAttr`. Returns `false` is `simpAttr` is not a\nvalid simp-attribute. -/\ndef isInSimpSet (simpAttr decl : Name) : CoreM Bool := do\n let .some simpDecl ← getSimpExtension? simpAttr | return false\n return (← simpDecl.getTheorems).contains decl\n\n/-- Returns all declarations with the `simp`-attribute `simpAttr`.\n Note: this also returns many auxiliary declarations. -/\ndef getAllSimpDecls (simpAttr : Name) : CoreM (List Name) := do\n let .some simpDecl ← getSimpExtension? simpAttr | return []\n let thms ← simpDecl.getTheorems\n return thms.toUnfold.toList ++ thms.lemmaNames.toList.filterMap fun\n | .decl decl => some decl\n | _ => none\n\n/-- Gets all simp-attributes given to declaration `decl`. -/\ndef getAllSimpAttrs (decl : Name) : CoreM (Array Name) := do\n let mut simpAttrs := #[]\n for (simpAttr, simpDecl) in (← simpExtensionMapRef.get).toList do\n if (← simpDecl.getTheorems).contains decl then\n simpAttrs := simpAttrs.push simpAttr\n return simpAttrs\n\nend Lean.Meta\n", "meta": {"author": "leanprover-community", "repo": "mathlib4", "sha": "b9a0a30342ca06e9817e22dbe46e75fc7f435500", "save_path": "github-repos/lean/leanprover-community-mathlib4", "path": "github-repos/lean/leanprover-community-mathlib4/mathlib4-b9a0a30342ca06e9817e22dbe46e75fc7f435500/Mathlib/Lean/Meta/Simp.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3522017956470284, "lm_q2_score": 0.044018652998225924, "lm_q1q2_score": 0.01550344862793862}} {"text": "/-\nCopyright (c) 2017 Johannes Hölzl. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthor: Johannes Hölzl\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.default\nimport Mathlib.tactic.lint.default\nimport Mathlib.tactic.ext\nimport Mathlib.tactic.simps\nimport Mathlib.PostPort\n\nuniverses u_1 u_2 u_3 \n\nnamespace Mathlib\n\nnamespace subtype\n\n\n/-- See Note [custom simps projection] -/\ndef simps.val {α : Sort u_1} {p : α → Prop} (x : Subtype p) : α := ↑x\n\n/-- A version of `x.property` or `x.2` where `p` is syntactically applied to the coercion of `x`\n instead of `x.1`. A similar result is `subtype.mem` in `data.set.basic`. -/\ntheorem prop {α : Sort u_1} {p : α → Prop} (x : Subtype p) : p ↑x := property x\n\n@[simp] theorem val_eq_coe {α : Sort u_1} {p : α → Prop} {x : Subtype p} : val x = ↑x := rfl\n\n@[simp] protected theorem forall {α : Sort u_1} {p : α → Prop}\n {q : (Subtype fun (a : α) => p a) → Prop} :\n (∀ (x : Subtype fun (a : α) => p a), q x) ↔\n ∀ (a : α) (b : p a), q { val := a, property := b } :=\n sorry\n\n/-- An alternative version of `subtype.forall`. This one is useful if Lean cannot figure out `q`\n when using `subtype.forall` from right to left. -/\nprotected theorem forall' {α : Sort u_1} {p : α → Prop} {q : (x : α) → p x → Prop} :\n (∀ (x : α) (h : p x), q x h) ↔ ∀ (x : Subtype fun (a : α) => p a), q (↑x) (property x) :=\n iff.symm subtype.forall\n\n@[simp] protected theorem exists {α : Sort u_1} {p : α → Prop}\n {q : (Subtype fun (a : α) => p a) → Prop} :\n (∃ (x : Subtype fun (a : α) => p a), q x) ↔\n ∃ (a : α), ∃ (b : p a), q { val := a, property := b } :=\n sorry\n\nprotected theorem ext {α : Sort u_1} {p : α → Prop} {a1 : Subtype fun (x : α) => p x}\n {a2 : Subtype fun (x : α) => p x} : ↑a1 = ↑a2 → a1 = a2 :=\n sorry\n\ntheorem ext_iff {α : Sort u_1} {p : α → Prop} {a1 : Subtype fun (x : α) => p x}\n {a2 : Subtype fun (x : α) => p x} : a1 = a2 ↔ ↑a1 = ↑a2 :=\n { mp := congr_arg fun {a1 : Subtype fun (x : α) => p x} => ↑a1, mpr := subtype.ext }\n\ntheorem heq_iff_coe_eq {α : Sort u_1} {p : α → Prop} {q : α → Prop} (h : ∀ (x : α), p x ↔ q x)\n {a1 : Subtype fun (x : α) => p x} {a2 : Subtype fun (x : α) => q x} : a1 == a2 ↔ ↑a1 = ↑a2 :=\n Eq._oldrec (fun (a2' : Subtype fun (x : α) => p x) => iff.trans heq_iff_eq ext_iff)\n (funext fun (x : α) => propext (h x)) a2\n\ntheorem ext_val {α : Sort u_1} {p : α → Prop} {a1 : Subtype fun (x : α) => p x}\n {a2 : Subtype fun (x : α) => p x} : val a1 = val a2 → a1 = a2 :=\n subtype.ext\n\ntheorem ext_iff_val {α : Sort u_1} {p : α → Prop} {a1 : Subtype fun (x : α) => p x}\n {a2 : Subtype fun (x : α) => p x} : a1 = a2 ↔ val a1 = val a2 :=\n ext_iff\n\n@[simp] theorem coe_eta {α : Sort u_1} {p : α → Prop} (a : Subtype fun (a : α) => p a) (h : p ↑a) :\n { val := ↑a, property := h } = a :=\n subtype.ext rfl\n\n@[simp] theorem coe_mk {α : Sort u_1} {p : α → Prop} (a : α) (h : p a) :\n ↑{ val := a, property := h } = a :=\n rfl\n\n@[simp] theorem mk_eq_mk {α : Sort u_1} {p : α → Prop} {a : α} {h : p a} {a' : α} {h' : p a'} :\n { val := a, property := h } = { val := a', property := h' } ↔ a = a' :=\n ext_iff\n\ntheorem coe_eq_iff {α : Sort u_1} {p : α → Prop} {a : Subtype fun (a : α) => p a} {b : α} :\n ↑a = b ↔ ∃ (h : p b), a = { val := b, property := h } :=\n sorry\n\ntheorem coe_injective {α : Sort u_1} {p : α → Prop} : function.injective coe :=\n fun (a b : Subtype p) => subtype.ext\n\ntheorem val_injective {α : Sort u_1} {p : α → Prop} : function.injective val := coe_injective\n\n/-- Restrict a (dependent) function to a subtype -/\ndef restrict {α : Sort u_1} {β : α → Type u_2} (f : (x : α) → β x) (p : α → Prop) (x : Subtype p) :\n β (val x) :=\n f ↑x\n\ntheorem restrict_apply {α : Sort u_1} {β : α → Type u_2} (f : (x : α) → β x) (p : α → Prop)\n (x : Subtype p) : restrict f p x = f (val x) :=\n Eq.refl (restrict f p x)\n\ntheorem restrict_def {α : Sort u_1} {β : Type u_2} (f : α → β) (p : α → Prop) :\n restrict f p = f ∘ coe :=\n Eq.refl (restrict f p)\n\ntheorem restrict_injective {α : Sort u_1} {β : Type u_2} {f : α → β} (p : α → Prop)\n (h : function.injective f) : function.injective (restrict f p) :=\n function.injective.comp h coe_injective\n\n/-- Defining a map into a subtype, this can be seen as an \"coinduction principle\" of `subtype`-/\ndef coind {α : Sort u_1} {β : Sort u_2} (f : α → β) {p : β → Prop} (h : ∀ (a : α), p (f a)) :\n α → Subtype p :=\n fun (a : α) => { val := f a, property := h a }\n\ntheorem coind_injective {α : Sort u_1} {β : Sort u_2} {f : α → β} {p : β → Prop}\n (h : ∀ (a : α), p (f a)) (hf : function.injective f) : function.injective (coind f h) :=\n fun (x y : α) (hxy : coind f h x = coind f h y) => hf (congr_arg val hxy)\n\ntheorem coind_surjective {α : Sort u_1} {β : Sort u_2} {f : α → β} {p : β → Prop}\n (h : ∀ (a : α), p (f a)) (hf : function.surjective f) : function.surjective (coind f h) :=\n sorry\n\ntheorem coind_bijective {α : Sort u_1} {β : Sort u_2} {f : α → β} {p : β → Prop}\n (h : ∀ (a : α), p (f a)) (hf : function.bijective f) : function.bijective (coind f h) :=\n { left := coind_injective h (and.left hf), right := coind_surjective h (and.right hf) }\n\n/-- Restriction of a function to a function on subtypes. -/\n@[simp] theorem map_coe {α : Sort u_1} {β : Sort u_2} {p : α → Prop} {q : β → Prop} (f : α → β)\n (h : ∀ (a : α), p a → q (f a)) : ∀ (ᾰ : Subtype p), ↑(map f h ᾰ) = f ↑ᾰ :=\n fun (ᾰ : Subtype p) => Eq.refl ↑(map f h ᾰ)\n\ntheorem map_comp {α : Sort u_1} {β : Sort u_2} {γ : Sort u_3} {p : α → Prop} {q : β → Prop}\n {r : γ → Prop} {x : Subtype p} (f : α → β) (h : ∀ (a : α), p a → q (f a)) (g : β → γ)\n (l : ∀ (a : β), q a → r (g a)) :\n map g l (map f h x) = map (g ∘ f) (fun (a : α) (ha : p a) => l (f a) (h a ha)) x :=\n rfl\n\ntheorem map_id {α : Sort u_1} {p : α → Prop} {h : ∀ (a : α), p a → p (id a)} : map id h = id :=\n sorry\n\ntheorem map_injective {α : Sort u_1} {β : Sort u_2} {p : α → Prop} {q : β → Prop} {f : α → β}\n (h : ∀ (a : α), p a → q (f a)) (hf : function.injective f) : function.injective (map f h) :=\n coind_injective (fun (x : Subtype fun (a : α) => p a) => map._proof_1 f h x)\n (function.injective.comp hf coe_injective)\n\ntheorem map_involutive {α : Sort u_1} {p : α → Prop} {f : α → α} (h : ∀ (a : α), p a → p (f a))\n (hf : function.involutive f) : function.involutive (map f h) :=\n fun (x : Subtype fun (a : α) => p a) => subtype.ext (hf ↑x)\n\nprotected instance has_equiv {α : Sort u_1} [has_equiv α] (p : α → Prop) : has_equiv (Subtype p) :=\n has_equiv.mk fun (s t : Subtype p) => ↑s ≈ ↑t\n\ntheorem equiv_iff {α : Sort u_1} [has_equiv α] {p : α → Prop} {s : Subtype p} {t : Subtype p} :\n s ≈ t ↔ ↑s ≈ ↑t :=\n iff.rfl\n\nprotected theorem refl {α : Sort u_1} {p : α → Prop} [setoid α] (s : Subtype p) : s ≈ s :=\n setoid.refl ↑s\n\nprotected theorem symm {α : Sort u_1} {p : α → Prop} [setoid α] {s : Subtype p} {t : Subtype p}\n (h : s ≈ t) : t ≈ s :=\n setoid.symm h\n\nprotected theorem trans {α : Sort u_1} {p : α → Prop} [setoid α] {s : Subtype p} {t : Subtype p}\n {u : Subtype p} (h₁ : s ≈ t) (h₂ : t ≈ u) : s ≈ u :=\n setoid.trans h₁ h₂\n\ntheorem equivalence {α : Sort u_1} [setoid α] (p : α → Prop) : equivalence has_equiv.equiv :=\n mk_equivalence has_equiv.equiv subtype.refl subtype.symm subtype.trans\n\nprotected instance setoid {α : Sort u_1} [setoid α] (p : α → Prop) : setoid (Subtype p) :=\n setoid.mk has_equiv.equiv (equivalence p)\n\nend subtype\n\n\nnamespace subtype\n\n\n/-! Some facts about sets, which require that `α` is a type. -/\n\n@[simp] theorem coe_prop {α : Type u_1} {S : set α} (a : Subtype fun (a : α) => a ∈ S) : ↑a ∈ S :=\n prop a\n\ntheorem val_prop {α : Type u_1} {S : set α} (a : Subtype fun (a : α) => a ∈ S) : val a ∈ S :=\n property a\n\nend Mathlib", "meta": {"author": "AurelienSaue", "repo": "Mathlib4_auto", "sha": "590df64109b08190abe22358fabc3eae000943f2", "save_path": "github-repos/lean/AurelienSaue-Mathlib4_auto", "path": "github-repos/lean/AurelienSaue-Mathlib4_auto/Mathlib4_auto-590df64109b08190abe22358fabc3eae000943f2/Mathlib/data/subtype_auto.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2974699426047947, "lm_q2_score": 0.05184546774853591, "lm_q1q2_score": 0.015422468315475713}} {"text": "/-\nCopyright (c) 2019 Simon Hudon. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Simon Hudon\n\nMonad encapsulating continuation passing programming style, similar to\nHaskell's `Cont`, `ContT` and `MonadCont`:\n\n-/\nimport control.monad.writer\n\nuniverses u v w u₀ u₁ v₀ v₁\n\nstructure monad_cont.label (α : Type w) (m : Type u → Type v) (β : Type u) :=\n(apply : α → m β)\n\ndef monad_cont.goto {α β} {m : Type u → Type v} (f : monad_cont.label α m β) (x : α) := f.apply x\n\nclass monad_cont (m : Type u → Type v) :=\n(call_cc : Π {α β}, ((monad_cont.label α m β) → m α) → m α)\n\nopen monad_cont\n\nclass is_lawful_monad_cont (m : Type u → Type v) [monad m] [monad_cont m]\nextends is_lawful_monad m :=\n(call_cc_bind_right {α ω γ} (cmd : m α) (next : (label ω m γ) → α → m ω) :\n call_cc (λ f, cmd >>= next f) = cmd >>= λ x, call_cc (λ f, next f x))\n(call_cc_bind_left {α} (β) (x : α) (dead : label α m β → β → m α) :\n call_cc (λ f : label α m β, goto f x >>= dead f) = pure x)\n(call_cc_dummy {α β} (dummy : m α) :\n call_cc (λ f : label α m β, dummy) = dummy)\n\nexport is_lawful_monad_cont\n\ndef cont_t (r : Type u) (m : Type u → Type v) (α : Type w) := (α → m r) → m r\n\n@[reducible] def cont (r : Type u) (α : Type w) := cont_t r id α\n\nnamespace cont_t\n\nexport monad_cont (label goto)\n\nvariables {r : Type u} {m : Type u → Type v} {α β γ ω : Type w}\n\ndef run : cont_t r m α → (α → m r) → m r := id\n\ndef map (f : m r → m r) (x : cont_t r m α) : cont_t r m α := f ∘ x\n\nlemma run_cont_t_map_cont_t (f : m r → m r) (x : cont_t r m α) :\n run (map f x) = f ∘ run x := rfl\n\ndef with_cont_t (f : (β → m r) → α → m r) (x : cont_t r m α) : cont_t r m β :=\nλ g, x $ f g\n\nlemma run_with_cont_t (f : (β → m r) → α → m r) (x : cont_t r m α) :\n run (with_cont_t f x) = run x ∘ f := rfl\n\n@[ext]\nprotected lemma ext {x y : cont_t r m α}\n (h : ∀ f, x.run f = y.run f) :\n x = y := by { ext; apply h }\n\ninstance : monad (cont_t r m) :=\n{ pure := λ α x f, f x,\n bind := λ α β x f g, x $ λ i, f i g }\n\ninstance : is_lawful_monad (cont_t r m) :=\n{ id_map := by { intros, refl },\n pure_bind := by { intros, ext, refl },\n bind_assoc := by { intros, ext, refl } }\n\ndef monad_lift [monad m] {α} : m α → cont_t r m α :=\nλ x f, x >>= f\n\ninstance [monad m] : has_monad_lift m (cont_t r m) :=\n{ monad_lift := λ α, cont_t.monad_lift }\n\nlemma monad_lift_bind [monad m] [is_lawful_monad m] {α β} (x : m α) (f : α → m β) :\n (monad_lift (x >>= f) : cont_t r m β) = monad_lift x >>= monad_lift ∘ f :=\nbegin\n ext,\n simp only [monad_lift,has_monad_lift.monad_lift,(∘),(>>=),bind_assoc,id.def,run,cont_t.monad_lift]\nend\n\ninstance : monad_cont (cont_t r m) :=\n{ call_cc := λ α β f g, f ⟨λ x h, g x⟩ g }\n\ninstance : is_lawful_monad_cont (cont_t r m) :=\n{ call_cc_bind_right := by intros; ext; refl,\n call_cc_bind_left := by intros; ext; refl,\n call_cc_dummy := by intros; ext; refl }\n\ninstance (ε) [monad_except ε m] : monad_except ε (cont_t r m) :=\n{ throw := λ x e f, throw e,\n catch := λ α act h f, catch (act f) (λ e, h e f) }\n\ninstance : monad_run (λ α, (α → m r) → ulift.{u v} (m r)) (cont_t.{u v u} r m) :=\n{ run := λ α f x, ⟨ f x ⟩ }\n\nend cont_t\n\nvariables {m : Type u → Type v} [monad m]\n\ndef except_t.mk_label {α β ε} : label (except.{u u} ε α) m β → label α (except_t ε m) β\n| ⟨ f ⟩ := ⟨ λ a, monad_lift $ f (except.ok a) ⟩\n\nlemma except_t.goto_mk_label {α β ε : Type*} (x : label (except.{u u} ε α) m β) (i : α) :\n goto (except_t.mk_label x) i = ⟨ except.ok <$> goto x (except.ok i) ⟩ := by cases x; refl\n\ndef except_t.call_cc\n {ε} [monad_cont m] {α β : Type*} (f : label α (except_t ε m) β → except_t ε m α) :\n except_t ε m α :=\nexcept_t.mk (call_cc $ λ x : label _ m β, except_t.run $ f (except_t.mk_label x) : m (except ε α))\n\ninstance {ε} [monad_cont m] : monad_cont (except_t ε m) :=\n{ call_cc := λ α β, except_t.call_cc }\n\ninstance {ε} [monad_cont m] [is_lawful_monad_cont m] : is_lawful_monad_cont (except_t ε m) :=\n{ call_cc_bind_right := by { intros, simp [call_cc,except_t.call_cc,call_cc_bind_right], ext, dsimp,\n congr' with ⟨ ⟩; simp [except_t.bind_cont,@call_cc_dummy m _], },\n call_cc_bind_left := by { intros,\n simp [call_cc,except_t.call_cc,call_cc_bind_right,except_t.goto_mk_label,map_eq_bind_pure_comp,\n bind_assoc,@call_cc_bind_left m _], ext, refl },\n call_cc_dummy := by { intros, simp [call_cc,except_t.call_cc,@call_cc_dummy m _], ext, refl }, }\n\ndef option_t.mk_label {α β} : label (option.{u} α) m β → label α (option_t m) β\n| ⟨ f ⟩ := ⟨ λ a, monad_lift $ f (some a) ⟩\n\nlemma option_t.goto_mk_label {α β : Type*} (x : label (option.{u} α) m β) (i : α) :\n goto (option_t.mk_label x) i = ⟨ some <$> goto x (some i) ⟩ := by cases x; refl\n\ndef option_t.call_cc [monad_cont m] {α β : Type*} (f : label α (option_t m) β → option_t m α) :\n option_t m α :=\noption_t.mk (call_cc $ λ x : label _ m β, option_t.run $ f (option_t.mk_label x) : m (option α))\n\ninstance [monad_cont m] : monad_cont (option_t m) :=\n{ call_cc := λ α β, option_t.call_cc }\n\ninstance [monad_cont m] [is_lawful_monad_cont m] : is_lawful_monad_cont (option_t m) :=\n{ call_cc_bind_right := by { intros, simp [call_cc,option_t.call_cc,call_cc_bind_right], ext, dsimp,\n congr' with ⟨ ⟩; simp [option_t.bind_cont,@call_cc_dummy m _], },\n call_cc_bind_left := by { intros, simp [call_cc,option_t.call_cc,call_cc_bind_right,\n option_t.goto_mk_label,map_eq_bind_pure_comp,bind_assoc,@call_cc_bind_left m _], ext, refl },\n call_cc_dummy := by { intros, simp [call_cc,option_t.call_cc,@call_cc_dummy m _], ext, refl }, }\n\ndef writer_t.mk_label {α β ω} [has_one ω] : label (α × ω) m β → label α (writer_t ω m) β\n| ⟨ f ⟩ := ⟨ λ a, monad_lift $ f (a,1) ⟩\n\nlemma writer_t.goto_mk_label {α β ω : Type*} [has_one ω] (x : label (α × ω) m β) (i : α) :\n goto (writer_t.mk_label x) i = monad_lift (goto x (i,1)) := by cases x; refl\n\ndef writer_t.call_cc [monad_cont m] {α β ω : Type*} [has_one ω]\n (f : label α (writer_t ω m) β → writer_t ω m α) : writer_t ω m α :=\n⟨ call_cc (writer_t.run ∘ f ∘ writer_t.mk_label : label (α × ω) m β → m (α × ω)) ⟩\n\ninstance (ω) [monad m] [has_one ω] [monad_cont m] : monad_cont (writer_t ω m) :=\n{ call_cc := λ α β, writer_t.call_cc }\n\ndef state_t.mk_label {α β σ : Type u} : label (α × σ) m (β × σ) → label α (state_t σ m) β\n| ⟨ f ⟩ := ⟨ λ a, ⟨ λ s, f (a,s) ⟩ ⟩\n\nlemma state_t.goto_mk_label {α β σ : Type u} (x : label (α × σ) m (β × σ)) (i : α) :\n goto (state_t.mk_label x) i = ⟨ λ s, (goto x (i,s)) ⟩ := by cases x; refl\n\ndef state_t.call_cc {σ} [monad_cont m] {α β : Type*}\n (f : label α (state_t σ m) β → state_t σ m α) : state_t σ m α :=\n⟨ λ r, call_cc (λ f', (f $ state_t.mk_label f').run r) ⟩\n\ninstance {σ} [monad_cont m] : monad_cont (state_t σ m) :=\n{ call_cc := λ α β, state_t.call_cc }\n\ninstance {σ} [monad_cont m] [is_lawful_monad_cont m] : is_lawful_monad_cont (state_t σ m) :=\n{ call_cc_bind_right := by { intros,\n simp [call_cc,state_t.call_cc,call_cc_bind_right,(>>=),state_t.bind], ext, dsimp,\n congr' with ⟨x₀,x₁⟩, refl },\n call_cc_bind_left := by { intros, simp [call_cc,state_t.call_cc,call_cc_bind_left,(>>=),\n state_t.bind,state_t.goto_mk_label], ext, refl },\n call_cc_dummy := by { intros, simp [call_cc,state_t.call_cc,call_cc_bind_right,(>>=),\n state_t.bind,@call_cc_dummy m _], ext, refl }, }\n\ndef reader_t.mk_label {α β} (ρ) : label α m β → label α (reader_t ρ m) β\n| ⟨ f ⟩ := ⟨ monad_lift ∘ f ⟩\n\nlemma reader_t.goto_mk_label {α ρ β} (x : label α m β) (i : α) :\n goto (reader_t.mk_label ρ x) i = monad_lift (goto x i) := by cases x; refl\n\ndef reader_t.call_cc {ε} [monad_cont m] {α β : Type*}\n (f : label α (reader_t ε m) β → reader_t ε m α) : reader_t ε m α :=\n⟨ λ r, call_cc (λ f', (f $ reader_t.mk_label _ f').run r) ⟩\n\ninstance {ρ} [monad_cont m] : monad_cont (reader_t ρ m) :=\n{ call_cc := λ α β, reader_t.call_cc }\n\ninstance {ρ} [monad_cont m] [is_lawful_monad_cont m] : is_lawful_monad_cont (reader_t ρ m) :=\n{ call_cc_bind_right :=\n by { intros, simp [call_cc,reader_t.call_cc,call_cc_bind_right], ext, refl },\n call_cc_bind_left := by { intros, simp [call_cc,reader_t.call_cc,call_cc_bind_left,\n reader_t.goto_mk_label], ext, refl },\n call_cc_dummy := by { intros, simp [call_cc,reader_t.call_cc,@call_cc_dummy m _], ext, refl } }\n\n/-- reduce the equivalence between two continuation passing monads to the equivalence between\ntheir underlying monad -/\ndef cont_t.equiv {m₁ : Type u₀ → Type v₀} {m₂ : Type u₁ → Type v₁}\n {α₁ r₁ : Type u₀} {α₂ r₂ : Type u₁} (F : m₁ r₁ ≃ m₂ r₂) (G : α₁ ≃ α₂) :\n cont_t r₁ m₁ α₁ ≃ cont_t r₂ m₂ α₂ :=\n{ to_fun := λ f r, F $ f $ λ x, F.symm $ r $ G x,\n inv_fun := λ f r, F.symm $ f $ λ x, F $ r $ G.symm x,\n left_inv := λ f, by funext r; simp,\n right_inv := λ f, by funext r; simp }\n", "meta": {"author": "JLimperg", "repo": "aesop3", "sha": "a4a116f650cc7403428e72bd2e2c4cda300fe03f", "save_path": "github-repos/lean/JLimperg-aesop3", "path": "github-repos/lean/JLimperg-aesop3/aesop3-a4a116f650cc7403428e72bd2e2c4cda300fe03f/src/control/monad/cont.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41489884579676883, "lm_q2_score": 0.03676946594365837, "lm_q1q2_score": 0.015255608980587457}} {"text": "import ReactorModel.Determinism.State\n\nopen Classical ReactorType Indexable\n\nnamespace Execution\nnamespace Instantaneous\nnamespace Step\n\nvariable [Indexable α] {s₁ s₂ : State α}\n\ntheorem rcn_not_mem_progress (e : s₁ ⇓ᵢ s₂) : e.rcn ∉ s₁.progress := \n sorry -- e.allows.unprocessed\n\ntheorem preserves_tag (e : s₁ ⇓ᵢ s₂) : s₁.tag = s₂.tag := \n sorry -- e.exec.preserves_tag\n \ntheorem mem_progress_iff :\n (e : s₁ ⇓ᵢ s₂) → (rcn' ∈ s₂.progress ↔ rcn' = e.rcn ∨ rcn' ∈ s₁.progress) := by\n intro h\n constructor\n case mp =>\n intro ho\n by_cases hc : rcn' = h.rcn\n case pos => exact .inl hc\n case neg => sorry\n -- rw [State.progress, h.exec.ctx_adds_rcn, ←rcn] at ho\n -- simp [Context.mem_record_progress_iff _ _ _ |>.mp ho]\n case mpr =>\n intro ho\n by_cases hc : rcn' = h.rcn\n case pos =>\n simp [hc]\n sorry\n -- exact Context.mem_record_progress_iff _ _ _ |>.mpr (.inl rfl)\n case neg =>\n sorry\n -- simp [State.progress, h.exec.ctx_adds_rcn, Context.mem_record_progress_iff _ _ _ |>.mpr (.inr $ ho.resolve_left hc)]\n\n-- Corollary of `InstStep.mem_progress_iff`.\ntheorem not_mem_progress :\n (e : s₁ ⇓ᵢ s₂) → (rcn' ≠ e.rcn) → rcn' ∉ s₁.progress → rcn' ∉ s₂.progress := \n sorry -- λ h hn hm => (mt h.mem_progress.mp) $ not_or.mpr ⟨hn, hm⟩\n\n-- Corollary of `InstStep.mem_progress`.\ntheorem monotonic_progress : (s₁ ⇓ᵢ s₂) → rcn' ∈ s₁.progress → rcn' ∈ s₂.progress := \n sorry -- (·.mem_progress_iff.mpr $ .inr ·)\n\n-- Corollary of `InstStep.mem_progress`.\ntheorem rcn_mem_progress : (e : s₁ ⇓ᵢ s₂) → e.rcn ∈ s₂.progress := \n (·.mem_progress_iff.mpr $ .inl rfl)\n\ntheorem Skip.equiv : (s₁ ⇓ₛ s₂) → s₁.rtr ≈ s₂.rtr\n | mk .. => .refl\n\ntheorem Skip.progress_eq : (e : s₁ ⇓ₛ s₂) → s₂.progress = s₁.progress.insert e.rcn\n | mk .. => rfl\n\ntheorem Skip.progress_mono (e : s₁ ⇓ₛ s₂) : s₁.progress ⊆ s₂.progress := by\n simp [e.progress_eq]\n apply Set.subset_insert\n\ntheorem Skip.triggers_iff (e : s₁ ⇓ₛ s₂) : (s₁.Triggers i) ↔ (s₂.Triggers i) := by \n cases e\n case mk rcn _ _ =>\n constructor\n all_goals\n intro h\n sorry -- exact h.progress_agnostic (s₁.record_preserves_rtr rcn) (s₁.record_preserves_tag rcn) |>.choose_spec\n\ntheorem Skip.mem_progress_iff (e : s₁ ⇓ₛ s₂) : \n (rcn' ∈ s₂.progress) ↔ (rcn' = e.rcn ∨ rcn' ∈ s₁.progress) := by\n sorry\n\ntheorem Skip.preserves_allows_indep (e₁ : s₁ ⇓ₛ s₂) (e₂ : s₂ ⇓ₛ s₃) (h : e₁.rcn ≮[s₁.rtr] e₂.rcn) : \n s₁.Allows e₂.rcn where\n mem := sorry\n unprocessed := Set.not_mem_subset e₁.progress_mono $ e₂.allows_rcn.unprocessed\n deps := by\n intro i hi\n have h' := equiv_eq_dependencies e₁.equiv |>.symm ▸ e₂.allows_rcn.deps\n refine e₁.mem_progress_iff.mp (h' hi) |>.resolve_left ?_\n intro hc; subst hc; contradiction\n\nset_option pp.proofs.withType false\ntheorem Skip.swap_indep_skip (e₁ : s₁ ⇓ₛ s₂) (e₂ : s₂ ⇓ₛ s₃) (h : e₁.rcn ≮[s₁.rtr] e₂.rcn) : \n ∃ (s₂' : _) (f₁ : s₁ ⇓ₛ s₂') (f₂ : s₂' ⇓ₛ s₃), (f₁.rcn = e₂.rcn) ∧ (f₂.rcn = e₁.rcn) := by \n have ha := e₁.preserves_allows_indep e₂ h\n have ht := e₁.triggers_iff.not.mpr e₂.not_triggers\n have e₁' := Skip.mk ha ht\n simp at e₁'\n exists _, e₁'\n sorry -- TODO: This is super annoying. Is there a better way to approach this?\n -- Do we need more preservation theorems for `Allows` and `Triggers` first?\n\ntheorem Skip.swap_indep_exec (e₁ : s₁ ⇓ₛ s₂) (e₂ : s₂ ⇓ₑ s₃) (h : e₁.rcn ≮[s₁.rtr] e₂.rcn) : \n ∃ (s₂' : _) (f₁ : s₁ ⇓ₑ s₂') (f₂ : s₂' ⇓ₛ s₃), (f₁.rcn = e₂.rcn) ∧ (f₂.rcn = e₁.rcn) := by \n sorry\n\ntheorem Skip.swap_indep (e₁ : s₁ ⇓ₛ s₂) (e₂ : s₂ ⇓ᵢ s₃) (h : e₁.rcn ≮[s₁.rtr] e₂.rcn) : \n ∃ (s₂' : _) (f₁ : s₁ ⇓ᵢ s₂') (f₂ : s₂' ⇓ₛ s₃), (f₁.rcn = e₂.rcn) ∧ (f₂.rcn = e₁.rcn) := by \n cases e₂\n case skip e₂ =>\n have ⟨_, e₁', e₂', _⟩ := e₁.swap_indep_skip e₂ h\n exists _, skip e₁', e₂'\n case exec e₂ =>\n have ⟨_, e₁', e₂', _⟩ := e₁.swap_indep_exec e₂ h\n exists _, exec e₁', e₂'\n\ntheorem Exec.equiv : (s₁ ⇓ₑ s₂) → s₁.rtr ≈ s₂.rtr\n | mk .. => by simp [State.record_preserves_rtr, s₁.exec_equiv]\n\ntheorem Exec.progress_eq : (e : s₁ ⇓ₑ s₂) → s₂.progress = s₁.progress.insert e.rcn\n | mk .. => rfl\n\ntheorem not_Closed (e : s₁ ⇓ᵢ s₂) : ¬s₁.Closed := by\n intro c\n have h := c ▸ e.allows_rcn.unprocessed\n simp [Partial.mem_iff] at h \n sorry -- have := h e.allows.mem.choose\n -- contradiction \n\ntheorem equiv : (s₁ ⇓ᵢ s₂) → s₁.rtr ≈ s₂.rtr\n | skip e | exec e => e.equiv\n\ntheorem deterministic (e₁ : s ⇓ᵢ s₁) (e₂ : s ⇓ᵢ s₂) (h : e₁.rcn = e₂.rcn) : s₁ = s₂ := by\n cases e₁ <;> cases e₂\n all_goals \n case _ e₁ e₂ => \n cases e₁; cases e₂\n simp [rcn] at h\n subst h\n first | rfl | contradiction\n\ntheorem acyclic (e : s₁ ⇓ᵢ s₂) : e.rcn ≮[s₁.rtr] e.rcn :=\n e.allows_rcn.acyclic\n\ntheorem progress_eq : (e : s₁ ⇓ᵢ s₂) → s₂.progress = s₁.progress.insert e.rcn\n | skip e | exec e => e.progress_eq \n\n/-\nBy cases on e₁ and e₂:\n(1) skip.skip:\n then both didn't trigger and nothing about the reactors changed, so it is easy to show that\n switching the order preserves non-triggering.\n\n(2)&(3) exec.skip and skip.exec:\n using `preserves_triggers` it should be easy\n\n(4) exec.exec: \n reduces to a theorem on State.exec?\n-/\ntheorem prepend_indep (e₁ : s₁ ⇓ᵢ s₂) (e₂ : s₂ ⇓ᵢ s₃) (h : e₁.rcn ≮[s₁.rtr] e₂.rcn) :\n ∃ (s₂' : _) (e₁' : s₁ ⇓ᵢ s₂') (e₂' : s₂' ⇓ᵢ s₃), e₁'.rcn = e₂.rcn ∧ e₂'.rcn = e₁.rcn := by\n cases e₁ \n case skip e₁ => \n have ⟨_, e₁', e₂', _⟩ := e₁.swap_indep e₂ h\n exists _, e₁', skip e₂'\n case exec e₁ =>\n sorry \n\nend Step\nend Instantaneous \nend Execution", "meta": {"author": "marcusrossel", "repo": "reactor-model", "sha": "f82fffb489b4352a0cc6bee964d44a142fee18ce", "save_path": "github-repos/lean/marcusrossel-reactor-model", "path": "github-repos/lean/marcusrossel-reactor-model/reactor-model-f82fffb489b4352a0cc6bee964d44a142fee18ce/src/ReactorModel/Determinism/InstantaneousStep.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42632159254749036, "lm_q2_score": 0.03567854895516831, "lm_q1q2_score": 0.015210535810350952}} {"text": "import polytime.lemmas\nimport complexity_class.dependent\n\nnamespace polytime\n\nopen_locale complexity_class\nopen tencodable function polysize\n\nvariables {α β γ δ ε η : Type} [tencodable α] [tencodable β] [tencodable γ]\n [tencodable δ] [tencodable ε] [tencodable η]\n\n@[complexity] lemma list_len : (@list.length α) ∈ₑ PTIME :=\nbegin\n complexity using λ x, (encode x).stack_rec (λ _ : unit, 0) (λ _ _ _, ()) (λ _ _ _, ())\n (λ _ ih _ _ _, ih + 1) (),\n induction x with hd tl ih, { refl, },\n simpa [encode_cons],\nend\n\n@[simp] def scanl_step {α β : Type*} (f : β → α → β) : list α × list β → list α × list β\n| ((x :: xs), (y :: ys)) := (xs, f y x :: y :: ys)\n| x := x\n\n@[complexity] theorem scanl_step_polytime {f : γ → β → α → β} {st : γ → list α × list β} (hf : f ∈ₑ PTIME) (hst : st ∈ₑ PTIME) :\n (λ x, scanl_step (f x) (st x)) ∈ₑ PTIME :=\nby { delta scanl_step, clean_target, complexity, }\n\ntheorem scanl_step_iterate' {α : Type*} (f : β → α → β) (l : list α) (x : β) (n : ℕ) :\n (scanl_step f)^[n] (l, [x]) = (l.drop n, ((l.scanl f x).take (n + 1)).reverse) :=\nbegin\n suffices : ∀ xs, (scanl_step f)^[n] (l, x :: xs) = (l.drop n, ((l.scanl f x).take (n + 1)).reverse ++ xs),\n { simpa using this [], },\n intro xs,\n induction l with hd tl ih generalizing x xs n, { rw iterate_fixed; simp, },\n cases n, { simp, }, { simp [ih], },\nend\n\ntheorem scanl_step_iterate {α : Type*} (f : β → α → β) (l : list α) (x : β) :\n (scanl_step f)^[l.length] (l, [x]) = ([], (l.scanl f x).reverse) :=\nby { rw [scanl_step_iterate', ← @list.length_scanl _ _ f x l], simp, }\n\nlemma list_scanl_rev' [polysize α] [polysize β] [polysize γ] {lst : γ → list α} {acc : γ → β} {f : γ → β → α → β}\n (hlst : lst ∈ₑ PTIME) (hacc : acc ∈ₑ PTIME) (hf : f ∈ₑ PTIME)\n (hf' : polysize_fun (λ (ls : list α) (x), ls.foldl (f x) (acc x))) :\n polytime.mem (λ x : γ, ((lst x).scanl (f x) (acc x)).reverse) :=\nbegin\n convert_to polytime.mem (λ x, ((scanl_step (f x))^[(lst x).length] (lst x, [acc x])).2),\n { simp [scanl_step_iterate], },\n refine complexity_class.mem.snd.comp _,\n apply iterate, complexity,\n cases hf' with pf hpf, cases polytime.size_le hlst with pl hpl,\n use pl + (pl + 1) * (pf.comp (pl + polynomial.X) + 1),\n intros x m _,\n simp [scanl_step_iterate'], apply add_le_add,\n { exact (list.size_le_of_sublist ((lst x).drop_sublist _)).trans (hpl _), },\n refine (list.size_le_of_sublist (list.take_sublist _ _)).trans _,\n apply list.size_le_mul_of_le,\n { rw [list.length_scanl, add_le_add_iff_right], exact (lst x).length_le_size.trans (hpl _), },\n simp_rw list.mem_iff_nth_le,\n rintros e ⟨n, hn, rfl⟩,\n rw list.scanl_nth_le_eq_foldl,\n exact (hpf ((lst x).take n, x)).trans (pf.eval_mono $ add_le_add_right ((list.size_le_of_sublist (list.take_sublist _ _)).trans (hpl _)) _),\nend\n\nlemma list_scanl_rev [polysize α] [polysize β] [polysize γ] {lst : γ → list α} {acc : γ → β} {f : γ → β → α → β}\n (hlst : lst ∈ₑ PTIME) (hacc : acc ∈ₑ PTIME) (hf : f ∈ₑ PTIME)\n (hf' : polysize_safe (λ (usf : γ × α) (sf : β), f usf.1 sf usf.2)) :\n polytime.mem (λ x : γ, ((lst x).scanl (f x) (acc x)).reverse) :=\nlist_scanl_rev' hlst hacc hf\n (polysize_safe.foldl polysize_fun.fst ((polytime.size_le hacc).comp polysize_fun.snd) \n (by { apply hf'.comp₃_1, complexity, }))\n\nlemma list_foldl' [polysize α] [polysize β] [polysize γ] {lst : γ → list α} {acc : γ → β} {f : γ → β → α → β}\n (hlst : lst ∈ₑ PTIME) (hacc : acc ∈ₑ PTIME) (hf : f ∈ₑ PTIME)\n (hf' : polysize_fun (λ (ls : list α) (x), ls.foldl (f x) (acc x))) :\n polytime.mem (λ x : γ, (lst x).foldl (f x) (acc x)) :=\nbegin\n rw complexity_class.of_some,\n convert complexity_class.head'.comp (list_scanl_rev' hlst hacc hf hf'),\n ext x : 1, simp [list.scanl_last_eq_foldl],\nend\n\n@[complexity] lemma list_foldl [polysize α] [polysize β] [polysize γ] {lst : γ → list α} {acc : γ → β} {f : γ → β → α → β}\n (hlst : lst ∈ₑ PTIME) (hacc : acc ∈ₑ PTIME) (hf : f ∈ₑ PTIME)\n (hf' : polysize_safe (λ (usf : γ × α) (sf : β), f usf.1 sf usf.2)) :\n polytime.mem (λ x : γ, (lst x).foldl (f x) (acc x)) :=\nbegin\n rw complexity_class.of_some,\n convert complexity_class.head'.comp (list_scanl_rev hlst hacc hf hf'),\n ext x : 1, simp [list.scanl_last_eq_foldl],\nend\n\n@[complexity] theorem list_reverse : (@list.reverse α) ∈ₑ PTIME :=\nbegin\n complexity using (λ l : list α, l.foldl (λ (acc : list α) (hd : α), hd :: acc) []),\n rw [← list.foldr_reverse, list.foldr_eta],\nend\n\n@[complexity] lemma list_scanl [polysize α] [polysize β] [polysize γ] {lst : γ → list α} {acc : γ → β} {f : γ → β → α → β}\n (hlst : lst ∈ₑ PTIME) (hacc : acc ∈ₑ PTIME) (hf : f ∈ₑ PTIME)\n (hf' : polysize_safe (λ (usf : γ × α) (sf : β), f usf.1 sf usf.2)) :\n polytime.mem (λ x : γ, ((lst x).scanl (f x) (acc x))) :=\nby simpa using list_reverse.comp (list_scanl_rev hlst hacc hf hf')\n\n@[complexity] theorem list_foldr [polysize α] [polysize β] [polysize γ] {lst : γ → list α} {acc : γ → β} {f : γ → α → β → β}\n (hlst : lst ∈ₑ PTIME) (hacc : acc ∈ₑ PTIME) (hf : f ∈ₑ PTIME)\n (hf' : polysize_safe (λ (usf : γ × α) (sf : β), f usf.1 usf.2 sf)) :\n polytime.mem (λ x : γ, (lst x).foldr (f x) (acc x)) :=\nby { simp_rw ← list.foldl_reverse, complexity, }\n\n@[complexity] theorem list_map {lst : γ → list α} {f : γ → α → β} (hlst : lst ∈ₑ PTIME) (hf : f ∈ₑ PTIME) :\n (λ x, (lst x).map (f x)) ∈ₑ PTIME :=\nby { complexity using (λ x, (lst x).foldr (λ hd acc, (f x hd) :: acc) []), induction lst x; simp [*], }\n\n\n@[complexity] theorem list_all_some : (@list.all_some α) ∈ₑ PTIME :=\nbegin\n complexity using λ l, l.foldr (λ hd' acc', hd'.bind (λ hd, acc'.map (λ acc, hd :: acc))) (some []),\n induction l with hd, { simp, }, cases hd; simp [*],\nend\n\ninstance {α : Type*} [polycodable α] : polycodable (list α) :=\n{ poly := by { dunfold decode, complexity, } }\n\n@[complexity] theorem list_tails : (@list.tails α) ∈ₑ PTIME :=\nby { complexity using λ ls, ls.scanl (λ l _, l.tail) ls, induction ls; simp [*], }\n\n@[complexity] theorem list_init : (@list.init α) ∈ₑ PTIME :=\nby { complexity using λ ls, ls.reverse.tail.reverse, induction ls using list.reverse_rec_on; simp [list.init], }\n\ntheorem stack_rec_eq [inhabited β] [inhabited γ] (ls : list γ) (base : α → β) (pre : γ → list γ → α → α)\n (post : β → γ → list γ → α → β) (arg : α) : ls.stack_rec base pre post arg =\n (ls.tails.init.scanl (λ (acc : list γ × α) (x : list γ), (x.tail, pre x.head x.tail acc.2)) (ls, arg))\n .foldr (λ ls_arg ih, if ls_arg.1.empty then base ls_arg.2 else post ih ls_arg.1.head ls_arg.1.tail ls_arg.2) (arbitrary _) :=\nbegin\n induction ls with hd tl ih generalizing arg, { simp [list.init], },\n simp [list.init_cons_of_ne_nil (list.ne_nil_of_length_eq_succ $ list.length_tails _), ih],\nend\n\n@[complexity] theorem list_stack_rec [polysize α] [polysize β] [polysize γ] [polysize δ] {ls : δ → list γ} {base : δ → α → β} {pre : δ → γ → list γ → α → α}\n {post : δ → β → γ → list γ → α → β} {arg : δ → α} (hls : ls ∈ₑ PTIME) (hb : base ∈ₑ PTIME)\n (hpre : pre ∈ₑ PTIME) (hpost : post ∈ₑ PTIME) (harg : arg ∈ₑ PTIME)\n (hpre' : polysize_safe (λ (usf : δ × γ × list γ) (sf : α), pre usf.1 usf.2.1 usf.2.2 sf))\n (hpost' : polysize_safe (λ (usf : δ × γ × list γ × α) (sf : β), post usf.1 sf usf.2.1 usf.2.2.1 usf.2.2.2)) :\n (λ x, (ls x).stack_rec (base x) (pre x) (post x) (arg x)) ∈ₑ PTIME :=\nbegin\n casesI is_empty_or_nonempty δ, { exact complexity_class.of_from_fintype' _, },\n casesI is_empty_or_nonempty γ, { complexity using (λ x, base x (arg x)), cases ls x with hd, { refl, }, exact is_empty.elim' infer_instance hd, },\n inhabit δ, inhabit γ, haveI : inhabited α := ⟨arg default⟩, haveI : inhabited β := ⟨base default default⟩,\n simp_rw stack_rec_eq,\n complexity, { apply polysize_safe.comp₄_3, complexity, },\n { apply polysize_safe.comp₅_1, complexity, },\nend\n\n@[complexity] lemma repeat : (@list.repeat α) ∈ₑ PTIME :=\nby { complexity using λ x n, (list.cons x)^[n] [], induction n; simp [iterate_succ', *], }\n\n@[complexity] lemma nat_stack_rec {n : γ → ℕ} {base : γ → α → β} {pre : γ → ℕ → α → α} {post : γ → β → ℕ → α → β}\n {arg : γ → α} (hn : n ∈ₑ PTIME) (hb : base ∈ₑ PTIME) (hpr : pre ∈ₑ PTIME) (hpo : post ∈ₑ PTIME)\n (harg : arg ∈ₑ PTIME) (hpr : polysize_safe (λ (usf : γ × ℕ) (sf : α), pre usf.1 usf.2 sf))\n (hpo' : polysize_safe (λ (usf : γ × ℕ × α) (sf : β), post usf.1 sf usf.2.1 usf.2.2)) : (λ x, (n x).stack_rec (base x) (pre x) (post x) (arg x)) ∈ₑ PTIME :=\nbegin\n complexity using λ x, (list.repeat () $ n x).stack_rec (base x) (λ _ tl y, pre x tl.length y)\n (λ ih _ tl y, post x ih tl.length y) (arg x),\n { apply polysize_safe.comp₃_2, complexity, },\n { apply polysize_safe.comp₄_1, complexity, },\n generalize : arg x = y, induction n x with n ih generalizing y,\n { simp, }, { simp [ih], },\nend\n\n@[complexity] lemma unary_nat_sum : (@list.sum ℕ _ _) ∈ₑ PTIME :=\nby { delta list.sum, complexity, }\n\n@[complexity] lemma list_ordered_insert {r : γ → α → α → Prop} [∀ x, decidable_rel (r x)] {a : γ → α} {ls : γ → list α} (hr : r ∈ₚ PTIME)\n (he : a ∈ₑ PTIME) (hls : ls ∈ₑ PTIME) : (λ x, (ls x).ordered_insert (r x) (a x)) ∈ₑ PTIME :=\nbegin\n complexity using λ x, (ls x).stack_rec (λ _ : unit, [a x]) (λ _ _ _, ())\n (λ ih b l _, if r x (a x) b then a x :: b :: l else b :: ih) (),\n induction ls x; simp [*],\nend\n\n@[complexity] lemma list_insertion_sort {r : γ → α → α → Prop} [∀ x, decidable_rel (r x)] {ls : γ → list α} (hr : r ∈ₚ PTIME)\n (hls : ls ∈ₑ PTIME) : (λ x, (ls x).insertion_sort (r x)) ∈ₑ PTIME :=\nby { complexity using λ x, (ls x).foldr (λ b ih, list.ordered_insert (r x) b ih) [], induction ls x; simp [*], }\n\n@[complexity] lemma list_append : ((++) : list α → list α → list α) ∈ₑ PTIME :=\nby { complexity using λ l₁ l₂, l₁.foldr (λ hd acc, hd :: acc) l₂, induction l₁; simp [*], }\n\n@[complexity] lemma list_drop : @list.drop α ∈ₑ PTIME :=\nby { complexity using λ n l, list.tail^[n] l, simp, }\n\n@[complexity] lemma list_any {l : α → list β} {p : α → β → bool} (hl : l ∈ₑ PTIME) (hp : p ∈ₑ PTIME) :\n (λ x, (l x).any (p x)) ∈ₑ PTIME :=\nby { delta list.any, complexity, use 0, simp, }\n\n@[complexity] lemma list_all {l : α → list β} {p : α → β → bool} (hl : l ∈ₑ PTIME) (hp : p ∈ₑ PTIME) :\n (λ x, (l x).all (p x)) ∈ₑ PTIME :=\nby { delta list.all, complexity, use 0, simp, }\n\n@[complexity] lemma list_bex {l : α → list β} {p : α → β → Prop} [∀ x y, decidable (p x y)] (hl : l ∈ₑ PTIME) (hp : p ∈ₚ PTIME) :\n (λ x, ∃ e ∈ l x, p x e) ∈ₚ PTIME :=\nby { simp_rw [← list.any_iff_exists_prop], complexity, }\n\n@[complexity] lemma list_ball {l : α → list β} {p : α → β → Prop} [∀ x y, decidable (p x y)] (hl : l ∈ₑ PTIME) (hp : p ∈ₚ PTIME) :\n (λ x, ∀ e ∈ l x, p x e) ∈ₚ PTIME :=\nby { simp_rw ← list.all_iff_forall_prop, complexity, }\n\n@[complexity] lemma list_mem : ((∈) : α → list α → Prop) ∈ₚ PTIME :=\nby { haveI : decidable_eq α := decidable_eq_of_encodable _, complexity using λ x l, ∃ z ∈ l, z = x, simp, }\n\n@[complexity] lemma pairwise {l : α → list β} {r : α → β → β → Prop} (hl : l ∈ₑ PTIME)\n (hr : r ∈ₚ PTIME) : (λ x, (l x).pairwise (r x)) ∈ₚ PTIME :=\nbegin\n classical, rw ← complexity_class.mem_iff_mem_pred,\n complexity using λ x, (l x).stack_rec (λ _ : unit, tt) (λ _ _ _, ())\n (λ ih hd tl _, (∀ a' ∈ tl, r x hd a') && ih) (), { use 0, simp, },\n induction l x; simp [*],\nend\n\n@[complexity] lemma list_nodup : (@list.nodup α) ∈ₚ PTIME :=\nby { dunfold list.nodup, complexity, }\n\n@[complexity] lemma list_nth {α : Type} [tencodable α] : @list.nth α ∈ₑ PTIME :=\nby { complexity using λ l n, (l.drop n).head', rw [← list.nth_zero, list.nth_drop], refl, }\n\nsection dep\nopen_locale tree\nvariables {σ τ : α → Type} [∀ i, tencodable (σ i)] [∀ i, tencodable (τ i)]\n\nlemma list_map_dep {f : ∀ x, list (σ x)} {g : ∀ x, σ x → τ x} (hf : f ∈ₐ PTIME) (hg : g ∈ₐ PTIME) :\n (λ x, @list.map _ (τ x) (g x) (f x)) ∈ₐ PTIME :=\npolytime.functor_map_dep list hf hg (@list_map _ _ _ _ _ _) \n\nend dep\n\nend polytime", "meta": {"author": "prakol16", "repo": "circuits", "sha": "cdf4ce1e019d6817e4abe0d082d8d379539fddca", "save_path": "github-repos/lean/prakol16-circuits", "path": "github-repos/lean/prakol16-circuits/circuits-cdf4ce1e019d6817e4abe0d082d8d379539fddca/src/polytime/data_structures/list.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46490157137338844, "lm_q2_score": 0.032589745588172986, "lm_q1q2_score": 0.015151023934600575}} {"text": "import defs.dynamics\nimport defs.fv\nimport defs.statics\nimport lemmas.cx\nimport lemmas.fv\n\ntheorem if_subst (ex: exp) (x: var) (fv_ex: fv ex = []) (e1 e2 e3: exp):\n subst ex x fv_ex (exp.if_ e1 e2 e3) =\n exp.if_\n (subst ex x fv_ex e1)\n (subst ex x fv_ex e2)\n (subst ex x fv_ex e3)\n := by simp [subst]\n\ntheorem app_subst (ex: exp) (x: var) (fv_ex: fv ex = []) (e1 e2: exp):\n subst ex x fv_ex (exp.app e1 e2) =\n exp.app\n (subst ex x fv_ex e1)\n (subst ex x fv_ex e2)\n := by simp [subst]\n\ntheorem fn_subst (ex: exp) (x: var) (fv_ex: fv ex = [])\n (y: var) (τ: typ) (e: exp):\n subst ex x fv_ex (exp.fn y τ e) =\n exp.fn y τ (if x = y then e else subst ex x fv_ex e) :=\nbegin\n simp [subst],\n -- super weird... at this point the lhs and rhs are equal so we should be\n -- done by refl but it doesn't work. but this does...?\n by_cases x = y,\n simp [h],\n simp [h],\nend\n\ntheorem pair_subst (ex: exp) (x: var) (fv_ex: fv ex = []) (e1 e2: exp):\n subst ex x fv_ex (exp.pair e1 e2) =\n exp.pair\n (subst ex x fv_ex e1)\n (subst ex x fv_ex e2)\n := by simp [subst]\n\ntheorem pair_left_subst (ex: exp) (x: var) (fv_ex: fv ex = []) (e: exp):\n subst ex x fv_ex (exp.pair_left e) = exp.pair_left (subst ex x fv_ex e)\n := by simp [subst]\n\ntheorem pair_right_subst (ex: exp) (x: var) (fv_ex: fv ex = []) (e: exp):\n subst ex x fv_ex (exp.pair_right e) = exp.pair_right (subst ex x fv_ex e)\n := by simp [subst]\n\ntheorem either_left_subst {τ: typ} (ex: exp) (x: var) (fv_ex: fv ex = []) (e: exp):\n subst ex x fv_ex (exp.either_left τ e) = exp.either_left τ (subst ex x fv_ex e)\n := by simp [subst]\n\ntheorem either_right_subst {τ: typ} (ex: exp) (x: var) (fv_ex: fv ex = []) (e: exp):\n subst ex x fv_ex (exp.either_right τ e) = exp.either_right τ (subst ex x fv_ex e)\n := by simp [subst]\n\ntheorem case_never_subst {τ: typ} (ex: exp) (x: var) (fv_ex: fv ex = []) (e: exp):\n subst ex x fv_ex (exp.case_never τ e) = exp.case_never τ (subst ex x fv_ex e)\n := by simp [subst]\n\ntheorem case_subst (ex: exp) (x: var) (fv_ex: fv ex = [])\n (eh e1 e2: exp) (x1 x2: var):\n subst ex x fv_ex (exp.case eh x1 e1 x2 e2) =\n exp.case\n (subst ex x fv_ex eh)\n x1 (if x = x1 then e1 else subst ex x fv_ex e1)\n x2 (if x = x2 then e2 else subst ex x fv_ex e2)\n :=\nbegin\n simp [subst],\n -- same as in fn_subst...?\n by_cases h1: x = x1,\n simp [h1],\n by_cases h2: x1 = x2,\n simp [h2],\n simp [h2],\n simp [h1],\n by_cases h2: x = x2,\n simp [h2],\n simp [h2],\nend\n\ntheorem weakening_var_helper {Γ: env} {x x': var} {τ1 τ2 τ: typ} {e: exp}:\n has_typ (env.insert_exp Γ x' τ1) e τ2 ->\n (x ∉ fv e -> has_typ (env.insert_exp (env.insert_exp Γ x' τ1) x τ) e τ2) ->\n x ∉ list.filter (ne x') (fv e) ->\n has_typ (env.insert_exp (env.insert_exp Γ x τ) x' τ1) e τ2 :=\nbegin\n intros et ih fv_e,\n by_cases x = x',\n let a := useless_insert_twice Γ.exps x τ1 τ,\n rw symm h at et ⊢,\n simp [env.insert_exp] at et,\n rw symm a at et,\n exact et,\n let b := ih (not_filter fv_e (fun a, h (symm a))),\n simp [env.insert_exp] at b,\n rw insert_comm Γ.exps x x' τ τ1 h at b,\n exact b,\nend\n\ntheorem weakening {Γ: env} {e: exp} {τ: typ} (x: var) (τx: typ):\n x ∉ fv e ->\n has_typ Γ e τ ->\n has_typ (env.insert_exp Γ x τx) e τ :=\nbegin\n intros fv_e et,\n induction et,\n exact has_typ.int,\n exact has_typ.true,\n exact has_typ.false,\n rw if_fv at fv_e,\n simp [list.append] at fv_e,\n let t_e1 := et_ih_a (fun a, fv_e (or.inl a)),\n let t_e2 := et_ih_a_1 (fun a, fv_e (or.inr (or.inl a))),\n let t_e3 := et_ih_a_2 (fun a, fv_e (or.inr (or.inr a))),\n exact has_typ.if_ t_e1 t_e2 t_e3,\n simp [fv] at fv_e,\n let var_ne := fun a, fv_e (symm a),\n exact has_typ.var (iff.elim_right (useless_insert_ne var_ne) et_a),\n rw fn_fv at fv_e,\n exact has_typ.fn (weakening_var_helper et_a et_ih fv_e),\n rw app_fv at fv_e,\n simp [list.append] at fv_e,\n let t_e1 := et_ih_a (fun a, fv_e (or.inl a)),\n let t_e2 := et_ih_a_1 (fun a, fv_e (or.inr a)),\n exact has_typ.app t_e1 t_e2,\n exact has_typ.unit,\n rw pair_fv at fv_e,\n simp [list.append] at fv_e,\n let t_e1 := et_ih_a (fun a, fv_e (or.inl a)),\n let t_e2 := et_ih_a_1 (fun a, fv_e (or.inr a)),\n exact has_typ.pair t_e1 t_e2,\n rw pair_left_fv at fv_e,\n exact has_typ.pair_left (et_ih fv_e),\n rw pair_right_fv at fv_e,\n exact has_typ.pair_right (et_ih fv_e),\n rw either_left_fv at fv_e,\n exact has_typ.either_left (et_ih fv_e),\n rw either_right_fv at fv_e,\n exact has_typ.either_right (et_ih fv_e),\n rw case_never_fv at fv_e,\n exact has_typ.case_never (et_ih fv_e),\n rw case_fv at fv_e,\n simp [list.append] at fv_e,\n let t_eh := et_ih_a (fun a, fv_e (or.inl a)),\n let fv_et_e1 := fun a, fv_e (or.inr (or.inl a)),\n let t_e1 := weakening_var_helper et_a_1 et_ih_a_1 fv_et_e1,\n let fv_et_e2 := fun a, fv_e (or.inr (or.inr a)),\n let t_e2 := weakening_var_helper et_a_2 et_ih_a_2 fv_et_e2,\n exact has_typ.case t_eh t_e1 t_e2,\nend\n\ntheorem subst_preservation_var_helper\n {Γ Γ': env} {x x': var} {τ1 τ2 τx: typ}\n {ex e: exp} (fv_ex: fv ex = []):\n Γ' = env.insert_exp Γ x τx ->\n has_typ (env.insert_exp Γ' x' τ1) e τ2 ->\n has_typ Γ ex τx ->\n (∀ {Γ : env},\n env.insert_exp Γ' x' τ1 = env.insert_exp Γ x τx →\n has_typ Γ ex τx → has_typ Γ (subst ex x fv_ex e) τ2) ->\n has_typ (env.insert_exp Γ x' τ1) (ite (x = x') e (subst ex x fv_ex e)) τ2 :=\nbegin\n intros Γ'_is et ext ih,\n by_cases x = x',\n simp [h],\n rw Γ'_is at et,\n rw h at et,\n simp [env.insert_exp] at et,\n rw useless_insert_twice Γ.exps x' τ1 τx at et,\n exact et,\n simp [h],\n rw Γ'_is at ih,\n let notin_fv_ex := list.not_mem_nil x',\n rw symm fv_ex at notin_fv_ex,\n let ext' := weakening x' τ1 notin_fv_ex ext,\n simp [env.insert_exp] at ih,\n let a := insert_comm Γ.exps x' x τ1 τx (fun a, h (symm a)),\n exact @ih (env.insert_exp Γ x' τ1) a ext',\nend\n\ntheorem subst_preservation\n {Γ Γ': env}\n {e ex: exp}\n {x: var}\n {τ τx: typ}\n (Γ'_is: Γ' = env.insert_exp Γ x τx)\n (fv_ex: fv ex = [])\n (et: has_typ Γ' e τ)\n (ext: has_typ Γ ex τx)\n : has_typ Γ (subst ex x fv_ex e) τ :=\nbegin\n induction et generalizing Γ,\n exact has_typ.int,\n exact has_typ.true,\n exact has_typ.false,\n let a := et_ih_a Γ'_is ext,\n let b := et_ih_a_1 Γ'_is ext,\n let c := et_ih_a_2 Γ'_is ext,\n exact has_typ.if_ a b c,\n rw Γ'_is at et_a,\n by_cases x = et_x,\n rw h at et_a ⊢,\n rw lookup_uniq (lookup_insert Γ.exps et_x τx) et_a at ext,\n simp [subst],\n exact ext,\n simp [subst, h],\n let h' := fun a, h (symm a),\n let hm := iff.elim_left (useless_insert_ne h') et_a,\n exact has_typ.var hm,\n rw fn_subst,\n let a := subst_preservation_var_helper fv_ex Γ'_is et_a ext @et_ih,\n exact has_typ.fn a,\n let a := et_ih_a Γ'_is ext,\n let b := et_ih_a_1 Γ'_is ext,\n exact has_typ.app a b,\n exact has_typ.unit,\n let a := et_ih_a Γ'_is ext,\n let b := et_ih_a_1 Γ'_is ext,\n exact has_typ.pair a b,\n exact has_typ.pair_left (et_ih Γ'_is ext),\n exact has_typ.pair_right (et_ih Γ'_is ext),\n exact has_typ.either_left (et_ih Γ'_is ext),\n exact has_typ.either_right (et_ih Γ'_is ext),\n exact has_typ.case_never (et_ih Γ'_is ext),\n rw case_subst,\n let t_e1 := subst_preservation_var_helper fv_ex Γ'_is et_a_1 ext @et_ih_a_1,\n let t_e2 := subst_preservation_var_helper fv_ex Γ'_is et_a_2 ext @et_ih_a_2,\n exact has_typ.case (et_ih_a Γ'_is ext) t_e1 t_e2,\nend\n\ntheorem subst_fv_var_helper {x x': var} {ex e: exp} (fv_ex: fv ex = []):\n fv (subst ex x fv_ex e) = list.filter (ne x) (fv e) ->\n list.filter (ne x') (fv (ite (x = x') e (subst ex x fv_ex e))) =\n list.filter (ne x) (list.filter (ne x') (fv e)) :=\nbegin\n intro ih,\n by_cases x = x',\n -- can't just `simp [h]` or else weird stuff happens with mismatched types\n rw h,\n simp,\n exact symm (filter_idempotent (ne x') (fv e)),\n simp [h],\n simp [ih],\n exact filter_comm (ne x') (ne x) (fv e),\nend\n\ntheorem subst_fv (ex: exp) (x: var) (fv_ex: fv ex = []) (e: exp):\n fv (subst ex x fv_ex e) = list.filter (ne x) (fv e) :=\nbegin\n let s := subst ex x fv_ex,\n induction e,\n simp [subst, fv],\n simp [subst, fv],\n simp [subst, fv],\n rw if_subst ex x fv_ex e_a e_a_1 e_a_2,\n rw if_fv (s e_a) (s e_a_1) (s e_a_2),\n rw e_ih_a,\n rw e_ih_a_1,\n rw e_ih_a_2,\n rw symm (list.filter_append (fv e_a_1) (fv e_a_2)),\n rw symm (list.filter_append (fv e_a) (fv e_a_1 ++ fv e_a_2)),\n simp [subst, fv],\n by_cases x = e,\n rw h,\n simp [subst, var_fv],\n exact fv_ex,\n simp [fv, subst, h],\n simp [fn_subst, fn_fv],\n exact subst_fv_var_helper fv_ex e_ih,\n rw app_subst ex x fv_ex e_a e_a_1,\n rw app_fv (s e_a) (s e_a_1),\n rw e_ih_a,\n rw e_ih_a_1,\n rw symm (list.filter_append (fv e_a) (fv e_a_1)),\n rw symm (app_fv e_a e_a_1),\n simp [subst, fv],\n simp [pair_subst],\n simp [pair_fv],\n rw e_ih_a,\n rw e_ih_a_1,\n simp [pair_left_subst, pair_left_fv],\n rw e_ih,\n simp [pair_right_subst, pair_right_fv],\n rw e_ih,\n simp [either_left_subst, either_left_fv],\n rw e_ih,\n simp [either_right_subst, either_right_fv],\n rw e_ih,\n simp [case_never_subst, case_never_fv],\n rw e_ih,\n simp [case_subst, case_fv],\n rw e_ih_a,\n rw subst_fv_var_helper fv_ex e_ih_a_1,\n rw subst_fv_var_helper fv_ex e_ih_a_2,\nend\n", "meta": {"author": "azdavis", "repo": "hatsugen", "sha": "a18f70f9ea4ce30c0baf0c40748aad5ccd176c60", "save_path": "github-repos/lean/azdavis-hatsugen", "path": "github-repos/lean/azdavis-hatsugen/hatsugen-a18f70f9ea4ce30c0baf0c40748aad5ccd176c60/src/lemmas/subst.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46490155654565424, "lm_q2_score": 0.032589743239179784, "lm_q1q2_score": 0.015151022359317893}} {"text": "import Lean\n\nmacro \"foo!\" x:term:max : term => `($x + 1)\n\n#check foo! 0\n\ntheorem ex1 : foo! 2 = 3 :=\n rfl\n\nmacro \"foo!\" x:term:max : term => `($x * 2)\n\n#check foo! 1 -- ambiguous\n\n-- macro with higher priority\nmacro (priority := high) \"foo!\" x:term:max : term => `($x - 2)\n\n#check foo! 2\n\ntheorem ex2 : foo! 2 = 0 :=\n rfl\n\n-- Define elaborator with even higher priority\nelab (priority := high+1) \"foo!\" x:term:max : term <= expectedType =>\n Lean.Elab.Term.elabTerm x expectedType\n\ntheorem ex3 : foo! 3 = 3 :=\n rfl\n", "meta": {"author": "leanprover", "repo": "lean4", "sha": "742d053a97bdd109a41a921facd1cd6a55e89bc7", "save_path": "github-repos/lean/leanprover-lean4", "path": "github-repos/lean/leanprover-lean4/lean4-742d053a97bdd109a41a921facd1cd6a55e89bc7/tests/lean/macroPrio.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.35936415888237616, "lm_q2_score": 0.04208773197075204, "lm_q1q2_score": 0.015124822398936198}} {"text": "import breen_deligne.constants\nimport breen_deligne.suitable\nimport pseudo_normed_group.FP\nimport system_of_complexes.rescale\n\nnoncomputable theory\n\nopen_locale classical nnreal big_operators\nlocal attribute [instance] type_pow\n\nuniverse variable u\n\nnamespace category_theory\nnamespace FreeAb\n\ndef of_functor (C : Type*) [category C] : C ⥤ FreeAb C :=\n{ obj := of,\n map := λ X Y f, free_abelian_group.of f,\n map_id' := λ X, rfl,\n map_comp' := λ X Y Z f g, rfl }\n\nend FreeAb\nend category_theory\n\nopen category_theory breen_deligne\n\nnamespace breen_deligne\n\nvariables (r' : ℝ≥0)\nvariables (BD : breen_deligne.data)\nvariables (M : ProFiltPseuNormGrpWithTinv r')\nvariables (c c₁ c₂ c₃ c₄ : ℝ≥0) (l m n : ℕ)\n\nopen category_theory breen_deligne\nopen Profinite pseudo_normed_group profinitely_filtered_pseudo_normed_group\n\n/-- The \"functor\" that sends `M` and `c` to `(filtration M c)^n` -/\ndef FP2 (r' : ℝ≥0) (c : ℝ≥0) (n : ℕ) :\n ProFiltPseuNormGrpWithTinv r' ⥤ FreeAb Profinite :=\nFiltrationPow r' c n ⋙ FreeAb.of_functor _\n\ntheorem FP2_def (r' : ℝ≥0) (c : ℝ≥0) (n : ℕ) :\n FP2 r' c n = FiltrationPow r' c n ⋙ FreeAb.of_functor _ := rfl\n\nnamespace FP2\n\n@[simps {fully_applied := ff}]\ndef res (r' : ℝ≥0) (c₁ c₂ : ℝ≥0) [fact (c₁ ≤ c₂)] (n : ℕ) : FP2 r' c₁ n ⟶ FP2 r' c₂ n :=\nwhisker_right (FiltrationPow.cast_le r' c₁ c₂ n) _\n\n@[simp] lemma res_refl : res r' c c n = 𝟙 _ :=\nby { simp [res, FiltrationPow.cast_le_refl], refl }\n\nlemma res_comp_res [h₁ : fact (c₁ ≤ c₂)] [h₂ : fact (c₂ ≤ c₃)] :\n res r' c₁ c₂ n ≫ res r' c₂ c₃ n = @res r' c₁ c₃ ⟨le_trans h₁.1 h₂.1⟩ n :=\nby simp only [res, ← whisker_right_comp, FiltrationPow.cast_le_comp]\n\nsection Tinv\nopen profinitely_filtered_pseudo_normed_group_with_Tinv\nvariables [fact (0 < r')]\n\n@[simps {fully_applied := ff}]\ndef Tinv [fact (c₁ ≤ r' * c₂)] : FP2 r' c₁ n ⟶ FP2 r' c₂ n :=\nwhisker_right (FiltrationPow.Tinv r' c₁ c₂ n) _\n\nlemma Tinv_def [fact (c₁ ≤ r' * c₂)] :\n Tinv r' c₁ c₂ n = whisker_right (FiltrationPow.Tinv r' c₁ c₂ n) _ := rfl\n\nlemma res_comp_Tinv\n [fact (c₁ ≤ c₂)] [fact (c₂ ≤ c₃)] [fact (c₁ ≤ r' * c₂)] [fact (c₂ ≤ r' * c₃)] :\n res r' c₁ c₂ n ≫ Tinv r' c₂ c₃ n = Tinv r' c₁ c₂ n ≫ res r' c₂ c₃ n :=\nby { simp only [Tinv, res, ← whisker_right_comp], refl }\n\nend Tinv\n\nend FP2\n\nopen FP2\n\nvariables {l m n}\n\nnamespace basic_universal_map\n\nopen basic_universal_map\n\nvariables (ϕ : basic_universal_map m n)\n\ndef eval_FP2 (c₁ c₂ : ℝ≥0) [ϕ.suitable c₁ c₂] : FP2 r' c₁ m ⟶ FP2 r' c₂ n :=\nwhisker_right (ϕ.eval_FP r' c₁ c₂) _\n\ndef eval_FP2' (c₁ c₂ : ℝ≥0) : FP2 r' c₁ m ⟶ FP2 r' c₂ n :=\nif H : ϕ.suitable c₁ c₂\nthen by exactI whisker_right (ϕ.eval_FP r' c₁ c₂) _\nelse 0\n\nlemma eval_FP2_eq_eval_FP2' (h : ϕ.suitable c₁ c₂) :\n eval_FP2 r' ϕ c₁ c₂ = eval_FP2' r' ϕ c₁ c₂ :=\nby { delta eval_FP2 eval_FP2', rw dif_pos h }\n\nlemma eval_FP2'_def [h : ϕ.suitable c₁ c₂] :\n eval_FP2' r' ϕ c₁ c₂ = whisker_right (ϕ.eval_FP r' c₁ c₂) _ :=\ndif_pos h\n\nlemma eval_FP2'_not_suitable (h : ¬ ϕ.suitable c₁ c₂) :\n eval_FP2' r' ϕ c₁ c₂ = 0 :=\ndif_neg h\n\nlemma eval_FP2'_comp (f : basic_universal_map l m) (g : basic_universal_map m n)\n [hf : f.suitable c₁ c₂] [hg : g.suitable c₂ c₃] :\n eval_FP2' r' (comp g f) c₁ c₃ = eval_FP2' r' f c₁ c₂ ≫ eval_FP2' r' g c₂ c₃ :=\nbegin\n haveI : (comp g f).suitable c₁ c₃ := suitable_comp c₂,\n simp only [eval_FP2'_def, eval_FP_comp r' _ c₂, whisker_right_comp]\nend\n\nlemma eval_FP2_comp (f : basic_universal_map l m) (g : basic_universal_map m n)\n [hf : f.suitable c₁ c₂] [hg : g.suitable c₂ c₃] :\n @eval_FP2 r' _ _ (comp g f) c₁ c₃ (suitable_comp c₂) =\n eval_FP2 r' f c₁ c₂ ≫ eval_FP2 r' g c₂ c₃ :=\nby { simp only [eval_FP2_eq_eval_FP2'], apply eval_FP2'_comp }\n\nlemma res_comp_eval_FP2\n [fact (c₁ ≤ c₂)] [fact (c₃ ≤ c₄)] [ϕ.suitable c₂ c₄] [ϕ.suitable c₁ c₃] :\n res r' c₁ c₂ m ≫ eval_FP2 r' ϕ c₂ c₄ = eval_FP2 r' ϕ c₁ c₃ ≫ res r' c₃ c₄ n :=\nby simp only [res, eval_FP2, ← whisker_right_comp,\n cast_le_comp_eval_FP _ c₁ c₂ c₃ c₄]\n\nlemma Tinv_comp_eval_FP2 [fact (0 < r')] [fact (c₁ ≤ r' * c₂)] [fact (c₃ ≤ r' * c₄)]\n [ϕ.suitable c₁ c₃] [ϕ.suitable c₂ c₄] :\n Tinv r' c₁ c₂ m ≫ eval_FP2 r' ϕ c₂ c₄ = eval_FP2 r' ϕ c₁ c₃ ≫ Tinv r' c₃ c₄ n :=\nby simp only [Tinv, eval_FP2, ← whisker_right_comp,\n Tinv_comp_eval_FP _ _ c₁ c₂ c₃ c₄]\n\nend basic_universal_map\n\nnamespace universal_map\n\nopen free_abelian_group\n\nvariables (ϕ : universal_map m n)\n\ndef eval_FP2 [ϕ.suitable c₁ c₂] : FP2 r' c₁ m ⟶ FP2 r' c₂ n :=\n∑ g : {g : basic_universal_map m n // g ∈ ϕ.support},\n begin\n haveI := suitable_of_mem_support ϕ c₁ c₂ g g.2,\n exact coeff (g : basic_universal_map m n) ϕ • (basic_universal_map.eval_FP2 r' g c₁ c₂)\n end\n\ndef eval_FP2' : FP2 r' c₁ m ⟶ FP2 r' c₂ n :=\n∑ g in ϕ.support, coeff g ϕ • (g.eval_FP2' r' c₁ c₂)\n\nlemma eval_FP2_eq_eval_FP2' (h : ϕ.suitable c₁ c₂) :\n eval_FP2 r' c₁ c₂ ϕ = eval_FP2' r' c₁ c₂ ϕ :=\nbegin\n simp only [eval_FP2, eval_FP2', basic_universal_map.eval_FP2_eq_eval_FP2',\n subtype.val_eq_coe],\n symmetry,\n apply finset.sum_subtype ϕ.support (λ _, iff.rfl),\nend\n\n@[simp] lemma eval_FP2'_of (f : basic_universal_map m n) :\n eval_FP2' r' c₁ c₂ (of f) = f.eval_FP2' r' c₁ c₂ :=\nby simp only [eval_FP2', support_of, coeff_of_self, one_smul, finset.sum_singleton]\n\n@[simp] lemma eval_FP2_of (f : basic_universal_map m n) [f.suitable c₁ c₂] :\n eval_FP2 r' c₁ c₂ (of f) = f.eval_FP2 r' c₁ c₂ :=\nby rw [eval_FP2_eq_eval_FP2', eval_FP2'_of, basic_universal_map.eval_FP2_eq_eval_FP2']\n\n@[simp] lemma eval_FP2'_zero :\n eval_FP2' r' c₁ c₂ (0 : universal_map m n) = 0 :=\nby rw [eval_FP2', support_zero, finset.sum_empty]\n\n@[simp] lemma eval_FP2_zero :\n eval_FP2 r' c₁ c₂ (0 : universal_map m n) = 0 :=\nby rw [eval_FP2_eq_eval_FP2', eval_FP2'_zero]\n\n@[simp] lemma eval_FP2'_neg (f : universal_map m n) :\n eval_FP2' r' c₁ c₂ (-f) = -eval_FP2' r' c₁ c₂ f :=\nby simp only [eval_FP2', add_monoid_hom.map_neg, finset.sum_neg_distrib, neg_smul, support_neg]\n\n@[simp] lemma eval_FP2_neg (f : universal_map m n) [f.suitable c₁ c₂] :\n eval_FP2 r' c₁ c₂ (-f) = -eval_FP2 r' c₁ c₂ f :=\nby simp only [eval_FP2_eq_eval_FP2', eval_FP2'_neg]\n\nlemma eval_FP2'_add (f g : universal_map m n) :\n eval_FP2' r' c₁ c₂ (f + g) = eval_FP2' r' c₁ c₂ f + eval_FP2' r' c₁ c₂ g :=\nbegin\n simp only [eval_FP2'],\n rw finset.sum_subset (support_add f g), -- two goals\n simp only [add_monoid_hom.map_add _ f g, add_smul],\n convert finset.sum_add_distrib using 2, -- three goals\n apply finset.sum_subset (finset.subset_union_left _ _), swap,\n apply finset.sum_subset (finset.subset_union_right _ _),\n all_goals { rintros x - h, rw not_mem_support_iff at h, simp [h] },\nend\n\nlemma eval_FP2_add (f g : universal_map m n) [f.suitable c₁ c₂] [g.suitable c₁ c₂] :\n eval_FP2 r' c₁ c₂ (f + g) = eval_FP2 r' c₁ c₂ f + eval_FP2 r' c₁ c₂ g :=\nby simp only [eval_FP2_eq_eval_FP2', eval_FP2'_add]\n\nlemma eval_FP2_sub (f g : universal_map m n) [f.suitable c₁ c₂] [g.suitable c₁ c₂] :\n eval_FP2 r' c₁ c₂ (f - g) = eval_FP2 r' c₁ c₂ f - eval_FP2 r' c₁ c₂ g :=\nby simp only [sub_eq_add_neg, eval_FP2_add, eval_FP2_neg]\n\nlemma eval_FP2'_comp_of (g : basic_universal_map m n) (f : basic_universal_map l m)\n [hf : f.suitable c₁ c₂] [hg : g.suitable c₂ c₃] :\n eval_FP2' r' c₁ c₃ ((universal_map.comp (of g)) (of f)) =\n eval_FP2' r' c₁ c₂ (of f) ≫ eval_FP2' r' c₂ c₃ (of g) :=\nbegin\n simp only [universal_map.comp_of, eval_FP2'_of],\n haveI hfg : (basic_universal_map.comp g f).suitable c₁ c₃ := basic_universal_map.suitable_comp c₂,\n rw ← basic_universal_map.eval_FP2'_comp,\nend\n\nopen category_theory category_theory.limits category_theory.preadditive\n\nlemma eval_FP2'_comp (g : universal_map m n) (f : universal_map l m)\n [hf : f.suitable c₁ c₂] [hg : g.suitable c₂ c₃] :\n eval_FP2' r' c₁ c₃ (universal_map.comp g f) = eval_FP2' r' c₁ c₂ f ≫ eval_FP2' r' c₂ c₃ g :=\nbegin\n unfreezingI { revert hg },\n apply free_abelian_group.induction_on_free_predicate\n (universal_map.suitable c₁ c₂) (universal_map.suitable_free_predicate c₁ c₂) f hf;\n unfreezingI { clear_dependent f },\n { intros h₂,\n simp only [eval_FP2'_zero, zero_comp, pi.zero_apply,\n add_monoid_hom.zero_apply, add_monoid_hom.map_zero] },\n { intros f hf hg,\n -- now do another nested induction on `f`\n apply free_abelian_group.induction_on_free_predicate\n (universal_map.suitable c₂ c₃) (universal_map.suitable_free_predicate c₂ c₃) g hg;\n unfreezingI { clear_dependent g },\n { simp only [universal_map.eval_FP2'_zero, comp_zero, add_monoid_hom.map_zero,\n add_monoid_hom.zero_apply] },\n { intros g hg,\n rw suitable_of_iff at hf hg,\n resetI,\n apply eval_FP2'_comp_of },\n { intros g hg IH,\n simp only [IH, eval_FP2'_neg, add_monoid_hom.map_neg, comp_neg,\n add_monoid_hom.neg_apply] },\n { rintros (g₁ : universal_map m n) (g₂ : universal_map m n) hg₁ hg₂ IH₁ IH₂, resetI,\n haveI Hg₁f : (universal_map.comp g₁ (of f)).suitable c₁ c₃ := suitable.comp c₂,\n haveI Hg₂f : (universal_map.comp g₂ (of f)).suitable c₁ c₃ := suitable.comp c₂,\n simp only [add_monoid_hom.map_add, eval_FP2'_add, IH₁, IH₂, comp_add,\n add_monoid_hom.add_apply] } },\n { intros f hf IH hg, resetI, specialize IH,\n simp only [IH, add_monoid_hom.map_neg, eval_FP2'_neg,\n add_monoid_hom.neg_apply, neg_inj, neg_comp] },\n { rintros (f₁ : universal_map l m) (f₂ : universal_map l m) hf₁ hf₂ IH₁ IH₂ hf, resetI,\n haveI Hgf₁ : (universal_map.comp g f₁).suitable c₁ c₃ := suitable.comp c₂,\n haveI Hgf₂ : (universal_map.comp g f₂).suitable c₁ c₃ := suitable.comp c₂,\n simp only [add_monoid_hom.map_add, add_monoid_hom.add_apply, eval_FP2'_add, IH₁, IH₂, add_comp] }\nend\n\nlemma eval_FP2_comp (g : universal_map m n) (f : universal_map l m)\n [hf : f.suitable c₁ c₂] [hg : g.suitable c₂ c₃] :\n @eval_FP2 r' c₁ c₃ _ _ (universal_map.comp g f) (universal_map.suitable.comp c₂) =\n eval_FP2 r' c₁ c₂ f ≫ eval_FP2 r' c₂ c₃ g :=\nby { simp only [eval_FP2_eq_eval_FP2'], apply eval_FP2'_comp }\n\nlemma res_comp_eval_FP2 [fact (c₁ ≤ c₂)] [fact (c₃ ≤ c₄)] [ϕ.suitable c₁ c₃] [ϕ.suitable c₂ c₄] :\n res r' c₁ c₂ m ≫ eval_FP2 r' c₂ c₄ ϕ = eval_FP2 r' c₁ c₃ ϕ ≫ res r' c₃ c₄ n :=\nbegin\n simp only [eval_FP2, comp_sum, sum_comp, comp_zsmul, zsmul_comp],\n apply finset.sum_congr rfl,\n rintros ⟨g, hg⟩ -,\n haveI : g.suitable c₁ c₃ := suitable_of_mem_support ϕ _ _ g hg,\n haveI : g.suitable c₂ c₄ := suitable_of_mem_support ϕ _ _ g hg,\n simp only [subtype.coe_mk, g.res_comp_eval_FP2 r' c₁ c₂ c₃ c₄],\nend\n\nlemma Tinv_comp_eval_FP2 [fact (0 < r')] [fact (c₁ ≤ r' * c₂)] [fact (c₃ ≤ r' * c₄)]\n [ϕ.suitable c₁ c₃] [ϕ.suitable c₂ c₄] :\n Tinv r' c₁ c₂ m ≫ eval_FP2 r' c₂ c₄ ϕ = eval_FP2 r' c₁ c₃ ϕ ≫ Tinv r' c₃ c₄ n :=\nbegin\n simp only [eval_FP2, comp_sum, sum_comp, comp_zsmul, zsmul_comp],\n apply finset.sum_congr rfl,\n rintros ⟨g, hg⟩ -,\n haveI : g.suitable c₁ c₃ := suitable_of_mem_support ϕ _ _ g hg,\n haveI : g.suitable c₂ c₄ := suitable_of_mem_support ϕ _ _ g hg,\n congr' 1, apply basic_universal_map.Tinv_comp_eval_FP2 r',\nend\n\nend universal_map\n\n\nvariables (κ : ℝ≥0 → ℕ → ℝ≥0) [∀ c, BD.suitable (κ c)]\n\ndef FPsystem.X (c : ℝ≥0) (n : ℕ) : FreeAb Profinite :=\nFreeAb.of $ (FiltrationPow r' (κ c n) $ BD.X n).obj M\n\ndef FPsystem.d (c : ℝ≥0) (n : ℕ) :\n FPsystem.X r' BD M κ c (n + 1) ⟶ FPsystem.X r' BD M κ c n :=\n(universal_map.eval_FP2 r' (κ c (n+1)) (κ c n) (BD.d (n+1) n)).app M\n\nlemma FPsystem.d_comp_d (c : ℝ≥0) (n : ℕ) :\n FPsystem.d r' BD M κ c (n + 1) ≫ FPsystem.d r' BD M κ c n = 0 :=\nbegin\n delta FPsystem.d,\n rw [← nat_trans.comp_app, ← universal_map.eval_FP2_comp],\n convert nat_trans.app_zero _, refl, refl,\n convert universal_map.eval_FP2_zero _ _ _,\n show BD.d _ _ ≫ BD.d _ _ = 0,\n rw homological_complex.d_comp_d,\nend\n\nopen opposite\n\ndef FPsystem [hκ : ∀ n, fact (monotone (function.swap κ n))] :\n ℝ≥0 ⥤ chain_complex (FreeAb Profinite) ℕ :=\n{ obj := λ c, chain_complex.of (FPsystem.X r' BD M κ c) (FPsystem.d r' BD M κ _) (FPsystem.d_comp_d _ _ _ _ _),\n map := λ c₁ c₂ h,\n { f := λ n, by { refine (@FP2.res r' _ _ (id _) (BD.X n)).app M,\n have := (hκ n).out, refine ⟨this h.le⟩, },\n comm' := begin\n rintro i j (rfl : j + 1 = i),\n rw [chain_complex.of_d, chain_complex.of_d],\n delta FPsystem.d, rw [← nat_trans.comp_app, ← nat_trans.comp_app],\n congr' 1,\n apply universal_map.res_comp_eval_FP2,\n end },\n map_id' := λ c, begin\n ext n, dsimp, rw [Filtration.cast_le_refl, (FreeAb.of_functor _).map_id], refl,\n end,\n map_comp' := λ c₁ c₂ c₃ h₁₂ h₂₃, begin\n ext n, dsimp, rw [← (FreeAb.of_functor _).map_comp, Filtration.cast_le_comp],\n end }\n.\n\ndef FPsystem.Tinv [fact (0 < r')]\n (κ₁ κ₂ : ℝ≥0 → ℕ → ℝ≥0)\n [∀ c, BD.suitable (κ₁ c)] [∀ c, BD.suitable (κ₂ c)]\n [hκ₁ : ∀ n, fact (monotone (function.swap κ₁ n))]\n [hκ₂ : ∀ n, fact (monotone (function.swap κ₂ n))]\n [∀ c n, fact (κ₁ c n ≤ r' * κ₂ c n)] :\n FPsystem r' BD M κ₁ ⟶ FPsystem r' BD M κ₂ :=\n{ app := λ c,\n { f := λ n, (FP2.Tinv r' _ _ _).app M,\n comm' := begin\n rintro i j (rfl : j + 1 = i),\n dsimp only [functor.comp_obj, FPsystem],\n rw [chain_complex.of_d, chain_complex.of_d],\n delta FPsystem.d,\n rw [← nat_trans.comp_app, ← nat_trans.comp_app],\n congr' 1,\n apply universal_map.Tinv_comp_eval_FP2\n end },\n naturality' := begin\n intros c₁ c₂ h,\n ext n,\n dsimp only [FPsystem, Tinv_app, homological_complex.comp_f, functor.comp_map, res_app],\n rw [← functor.map_comp, ← functor.map_comp],\n refl,\n end }\n\ndef FPsystem.res [fact (r' ≤ 1)]\n (κ₁ κ₂ : ℝ≥0 → ℕ → ℝ≥0)\n [∀ c, BD.suitable (κ₁ c)] [∀ c, BD.suitable (κ₂ c)]\n [hκ₁ : ∀ n, fact (monotone (function.swap κ₁ n))]\n [hκ₂ : ∀ n, fact (monotone (function.swap κ₂ n))]\n [∀ c n, fact (κ₁ c n ≤ κ₂ c n)] :\n FPsystem r' BD M κ₁ ⟶ FPsystem r' BD M κ₂ :=\n{ app := λ c,\n { f := λ n, (FP2.res r' _ _ _).app M,\n comm' := begin\n rintro i j (rfl : j + 1 = i),\n dsimp only [functor.comp_obj, FPsystem],\n rw [chain_complex.of_d, chain_complex.of_d],\n delta FPsystem.d,\n rw [← nat_trans.comp_app, ← nat_trans.comp_app],\n congr' 1,\n apply universal_map.res_comp_eval_FP2\n end },\n naturality' := begin\n intros c₁ c₂ h,\n ext n,\n dsimp only [FPsystem, res_app, homological_complex.comp_f, functor.comp_map],\n rw [← functor.map_comp, ← functor.map_comp],\n refl,\n end }\n\nend breen_deligne\n", "meta": {"author": "leanprover-community", "repo": "lean-liquid", "sha": "92f188bd17f34dbfefc92a83069577f708851aec", "save_path": "github-repos/lean/leanprover-community-lean-liquid", "path": "github-repos/lean/leanprover-community-lean-liquid/lean-liquid-92f188bd17f34dbfefc92a83069577f708851aec/src/pseudo_normed_group/FP2.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4571367316191468, "lm_q2_score": 0.03308597981882656, "lm_q1q2_score": 0.015124816676795423}} {"text": "/-\nCopyright (c) 2017 Mario Carneiro. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Mario Carneiro\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.default\nimport Mathlib.Lean3Lib.data.dlist\nimport Mathlib.tactic.core\nimport Mathlib.tactic.clear\nimport Mathlib.PostPort\n\nuniverses u_1 u_2 \n\nnamespace Mathlib\n\n/-!\n\n# Recursive cases (`rcases`) tactic and related tactics\n\n`rcases` is a tactic that will perform `cases` recursively, according to a pattern. It is used to\ndestructure hypotheses or expressions composed of inductive types like `h1 : a ∧ b ∧ c ∨ d` or\n`h2 : ∃ x y, trans_rel R x y`. Usual usage might be `rcases h1 with ⟨ha, hb, hc⟩ | hd` or\n`rcases h2 with ⟨x, y, _ | ⟨z, hxz, hzy⟩⟩` for these examples.\n\nEach element of an `rcases` pattern is matched against a particular local hypothesis (most of which\nare generated during the execution of `rcases` and represent individual elements destructured from\nthe input expression). An `rcases` pattern has the following grammar:\n\n* A name like `x`, which names the active hypothesis as `x`.\n* A blank `_`, which does nothing (letting the automatic naming system used by `cases` name the\n hypothesis).\n* A hyphen `-`, which clears the active hypothesis and any dependents.\n* The keyword `rfl`, which expects the hypothesis to be `h : a = b`, and calls `subst` on the\n hypothesis (which has the effect of replacing `b` with `a` everywhere or vice versa).\n* A type ascription `p : ty`, which sets the type of the hypothesis to `ty` and then matches it\n against `p`. (Of course, `ty` must unify with the actual type of `h` for this to work.)\n* A tuple pattern `⟨p1, p2, p3⟩`, which matches a constructor with many arguments, or a series\n of nested conjunctions or existentials. For example if the active hypothesis is `a ∧ b ∧ c`,\n then the conjunction will be destructured, and `p1` will be matched against `a`, `p2` against `b`\n and so on.\n* An alteration pattern `p1 | p2 | p3`, which matches an inductive type with multiple constructors,\n or a nested disjunction like `a ∨ b ∨ c`.\n\nThe patterns are fairly liberal about the exact shape of the constructors, and will insert\nadditional alternation branches and tuple arguments if there are not enough arguments provided, and\nreuse the tail for further matches if there are too many arguments provided to alternation and\ntuple patterns.\n\nThis file also contains the `obtain` and `rintro` tactics, which use the same syntax of `rcases`\npatterns but with a slightly different use case:\n\n* `rintro` (or `rintros`) is used like `rintro x ⟨y, z⟩` and is the same as `intros` followed by\n `rcases` on the newly introduced arguments.\n* `obtain` is the same as `rcases` but with a syntax styled after `have` rather than `cases`.\n `obtain ⟨hx, hy⟩ | hz := foo` is equivalent to `rcases foo with ⟨hx, hy⟩ | hz`. Unlike `rcases`,\n `obtain` also allows one to omit `:= foo`, although a type must be provided in this case,\n as in `obtain ⟨hx, hy⟩ | hz : a ∧ b ∨ c`, in which case it produces a subgoal for proving\n `a ∧ b ∨ c` in addition to the subgoals `hx : a, hy : b |- goal` and `hz : c |- goal`.\n\n## Tags\n\nrcases, rintro, obtain, destructuring, cases, pattern matching, match\n-/\n\nnamespace tactic\n\n\n/-!\nThese synonyms for `list` are used to clarify the meanings of the many\nusages of lists in this module.\n\n- `listΣ` is used where a list represents a disjunction, such as the\n list of possible constructors of an inductive type.\n\n- `listΠ` is used where a list represents a conjunction, such as the\n list of arguments of an individual constructor.\n\nThese are merely type synonyms, and so are not checked for consistency\nby the compiler.\n\nThe `def`/`local notation` combination makes Lean retain these\nannotations in reported types.\n-/\n\n/-- A list, with a disjunctive meaning (like a list of inductive constructors, or subgoals) -/\ndef list_Sigma (T : Type u_1) := List\n\n/-- A list, with a conjunctive meaning (like a list of constructor arguments, or hypotheses) -/\ndef list_Pi (T : Type u_1) := List\n\n/-- A metavariable representing a subgoal, together with a list of local constants to clear. -/\n/--\nAn `rcases` pattern can be one of the following, in a nested combination:\n\n* A name like `foo`\n* The special keyword `rfl` (for pattern matching on equality using `subst`)\n* A hyphen `-`, which clears the active hypothesis and any dependents.\n* A type ascription like `pat : ty` (parentheses are optional)\n* A tuple constructor like `⟨p1, p2, p3⟩`\n* An alternation / variant pattern `p1 | p2 | p3`\n\nParentheses can be used for grouping; alternation is higher precedence than type ascription, so\n`p1 | p2 | p3 : ty` means `(p1 | p2 | p3) : ty`.\n\nN-ary alternations are treated as a group, so `p1 | p2 | p3` is not the same as `p1 | (p2 | p3)`,\nand similarly for tuples. However, note that an n-ary alternation or tuple can match an n-ary\nconjunction or disjunction, because if the number of patterns exceeds the number of constructors in\nthe type being destructed, the extra patterns will match on the last element, meaning that\n`p1 | p2 | p3` will act like `p1 | (p2 | p3)` when matching `a1 ∨ a2 ∨ a3`. If matching against a\ntype with 3 constructors, `p1 | (p2 | p3)` will act like `p1 | (p2 | p3) | _` instead.\n-/\nnamespace rcases_patt\n\n\n/-- Get the name from a pattern, if provided -/\n/-- Interpret an rcases pattern as a tuple, where `p` becomes `⟨p⟩`\nif `p` is not already a tuple. -/\n/-- Interpret an rcases pattern as an alternation, where non-alternations are treated as one\nalternative. -/\n/-- Convert a list of patterns to a tuple pattern, but mapping `[p]` to `p` instead of `⟨p⟩`. -/\n/-- Convert a list of patterns to an alternation pattern, but mapping `[p]` to `p` instead of\na unary alternation `|p`. -/\n/-- This function is used for producing rcases patterns based on a case tree. Suppose that we have\na list of patterns `ps` that will match correctly against the branches of the case tree for one\nconstructor. This function will merge tuples at the end of the list, so that `[a, b, ⟨c, d⟩]`\nbecomes `⟨a, b, c, d⟩` instead of `⟨a, b, ⟨c, d⟩⟩`.\n\nWe must be careful to turn `[a, ⟨⟩]` into `⟨a, ⟨⟩⟩` instead of `⟨a⟩` (which will not perform the\nnested match). -/\n/-- This function is used for producing rcases patterns based on a case tree. This is like\n`tuple₁_core` but it produces a pattern instead of a tuple pattern list, converting `[n]` to `n`\ninstead of `⟨n⟩` and `[]` to `_`, and otherwise just converting `[a, b, c]` to `⟨a, b, c⟩`. -/\n/-- This function is used for producing rcases patterns based on a case tree. Here we are given\nthe list of patterns to apply to each argument of each constructor after the main case, and must\nproduce a list of alternatives with the same effect. This function calls `tuple₁` to make the\nindividual alternatives, and handles merging `[a, b, c | d]` to `a | b | c | d` instead of\n`a | b | (c | d)`. -/\n/-- This function is used for producing rcases patterns based on a case tree. This is like\n`alts₁_core`, but it produces a cases pattern directly instead of a list of alternatives. We\nspecially translate the empty alternation to `⟨⟩`, and translate `|(a | b)` to `⟨a | b⟩` (because we\ndon't have any syntax for unary alternation). Otherwise we can use the regular merging of\nalternations at the last argument so that `a | b | (c | d)` becomes `a | b | c | d`. -/\n/-- Formats an `rcases` pattern. If the `bracket` argument is true, then it will be\nprinted at high precedence, i.e. it will have parentheses around it if it is not already a tuple\nor atomic name. -/\nend rcases_patt\n\n\n/-- Takes the number of fields of a single constructor and patterns to match its fields against\n(not necessarily the same number). The returned lists each contain one element per field of the\nconstructor. The `name` is the name which will be used in the top-level `cases` tactic, and the\n`rcases_patt` is the pattern which the field will be matched against by subsequent `cases`\ntactics. -/\n-- The interesting case: we matched the last field against multiple\n\n-- patterns, so split off the remaining patterns into a subsequent\n\n-- match. This handles matching `α × β × γ` against `⟨a, b, c⟩`.\n\n/-- Takes a list of constructor names, and an (alternation) list of patterns, and matches each\npattern against its constructor. It returns the list of names that will be passed to `cases`,\nand the list of `(constructor name, patterns)` for each constructor, where `patterns` is the\n(conjunctive) list of patterns to apply to each constructor argument. -/\n/-- Like `zip`, but only elements satisfying a matching predicate `p` will go in the list,\nand elements of the first list that fail to match the second list will be skipped. -/\n/-- Given a local constant `e`, get its type. *But* if `e` does not exist, go find a hypothesis\nwith the same pretty name as `e` and get it instead. This is needed because we can sometimes lose\ntrack of the unique names of hypotheses when they are revert/intro'd by `change` and `cases`. (A\nbetter solution would be for these tactics to return a map of renamed hypotheses so that we don't\nlose track of them.) -/\n/--\n* `rcases_core p e` will match a pattern `p` against a local hypothesis `e`.\n It returns the list of subgoals that were produced.\n* `rcases.continue pes` will match a (conjunctive) list of `(p, e)` pairs which refer to\n patterns and local hypotheses to match against, and applies all of them. Note that this can\n involve matching later arguments multiple times given earlier arguments, for example\n `⟨a | b, ⟨c, d⟩⟩` performs the `⟨c, d⟩` match twice, once on the `a` branch and once on `b`.\n-/\n-- If the pattern is any other name, we already bound the name in the\n\n-- top-level `cases` tactic, so there is no more work to do for it.\n\n/-- Given a list of `uncleared_goal`s, each of which is a goal metavariable and\na list of variables to clear, actually perform the clear and set the goals with the result. -/\n/-- `rcases h e pat` performs case distinction on `e` using `pat` to\nname the arising new variables and assumptions. If `h` is `some` name,\na new assumption `h : e = pat` will relate the expression `e` with the\ncurrent pattern. See the module comment for the syntax of `pat`. -/\n/-- `rcases_many es pats` performs case distinction on the `es` using `pat` to\nname the arising new variables and assumptions.\nSee the module comment for the syntax of `pat`. -/\n/-- `rintro pat₁ pat₂ ... patₙ` introduces `n` arguments, then pattern matches on the `patᵢ` using\nthe same syntax as `rcases`. -/\n/-- Like `zip_with`, but if the lists don't match in length, the excess elements will be put at the\nend of the result. -/\ndef merge_list {α : Type u_1} (m : α → α → α) : List α → List α → List α := sorry\n\n/-- Merge two `rcases` patterns. This is used to underapproximate a case tree by an `rcases`\npattern. The two patterns come from cases in two branches, that due to the syntax of `rcases`\npatterns are forced to overlap. The rule here is that we take only the case splits that are in\ncommon between both branches. For example if one branch does `⟨a, b⟩` and the other does `c`,\nthen we return `c` because we don't know that a case on `c` would be safe to do. -/\n/--\n* `rcases_hint_core depth e` does the same as `rcases p e`, except the pattern `p` is an output\n instead of an input, controlled only by the case depth argument `depth`. We use `cases` to depth\n `depth` and then reconstruct an `rcases` pattern `p` that would, if passed to `rcases`, perform\n the same thing as the case tree we just constructed (or at least, the nearest expressible\n approximation to this.)\n* `rcases_hint.process_constructors depth cs l` takes a list of constructor names `cs` and a\n matching list `l` of elements `(g, c', hs, _)` where `c'` is a constructor name (used for\n alignment with `cs`), `g` is the subgoal, and `hs` is the list of local hypotheses created by\n `cases` in that subgoal. It matches on all of them, and then produces a `ΣΠ`-list of `rcases`\n patterns describing the result, and the list of generated subgoals.\n* `rcases_hint.continue depth es` does the same as `rcases.continue (ps.zip es)`, except the\n patterns `ps` are an output instead of an input, created by matching on everything to depth\n `depth` and recording the successful cases. It returns `ps`, and the list of generated subgoals.\n-/\n/--\n* `rcases? e` is like `rcases e with ...`, except it generates `...` by matching on everything it\ncan, and it outputs an `rcases` invocation that should have the same effect.\n* `rcases? e : n` can be used to control the depth of case splits (especially important for\nrecursive types like `nat`, which can be cased as many times as you like). -/\n/--\n* `rcases? ⟨e1, e2, e3⟩` is like `rcases ⟨e1, e2, e3⟩ with ...`, except it\n generates `...` by matching on everything it can, and it outputs an `rcases`\n invocation that should have the same effect.\n* `rcases? ⟨e1, e2, e3⟩ : n` can be used to control the depth of case splits\n (especially important for recursive types like `nat`, which can be cased as many\n times as you like). -/\n/--\n* `rintro?` is like `rintro ...`, except it generates `...` by introducing and matching on\neverything it can, and it outputs an `rintro` invocation that should have the same effect.\n* `rintro? : n` can be used to control the depth of case splits (especially important for\nrecursive types like `nat`, which can be cased as many times as you like). -/\n/--\n* `rcases_patt_parse tt` will parse a high precedence `rcases` pattern, `patt_hi`.\n This means only tuples and identifiers are allowed; alternations and type ascriptions\n require `(...)` instead, which switches to `patt`.\n* `rcases_patt_parse ff` will parse a low precedence `rcases` pattern, `patt`. This consists of a\n `patt_med` (which deals with alternations), optionally followed by a `: ty` type ascription. The\n expression `ty` is at `texpr` precedence because it can appear at the end of a tactic, for\n example in `rcases e with x : ty <|> skip`.\n* `rcases_patt_parse_list` will parse an alternation list, `patt_med`, one or more `patt`\n patterns separated by `|`. It does not parse a `:` at the end, so that `a | b : ty` parses as\n `(a | b) : ty` where `a | b` is the `patt_med` part.\n* `rcases_patt_parse_list_rest a` parses an alternation list after the initial pattern, `| b | c`.\n\n```lean\npatt ::= patt_med (\":\" expr)?\npatt_med ::= (patt_hi \"|\")* patt_hi\npatt_hi ::= id | \"rfl\" | \"_\" | \"⟨\" (patt \",\")* patt \"⟩\" | \"(\" patt \")\"\n```\n-/\n/-- Parse the optional depth argument `(: n)?` of `rcases?` and `rintro?`, with default depth 5. -/\n/-- The arguments to `rcases`, which in fact dispatch to several other tactics.\n* `rcases? expr (: n)?` or `rcases? ⟨expr, ...⟩ (: n)?` calls `rcases_hint`\n* `rcases? ⟨expr, ...⟩ (: n)?` calls `rcases_hint_many`\n* `rcases (h :)? expr (with patt)?` calls `rcases`\n* `rcases ⟨expr, ...⟩ (with patt)?` calls `rcases_many`\n-/\n/-- Syntax for a `rcases` pattern:\n* `rcases? expr (: n)?`\n* `rcases (h :)? expr (with patt_list (: expr)?)?`. -/\n/--\n`rintro_patt_parse_hi` and `rintro_patt_parse` are like `rcases_patt_parse`, but is used for\nparsing top level `rintro` patterns, which allow sequences like `(x y : t)` in addition to simple\n`rcases` patterns.\n\n* `rintro_patt_parse_hi` will parse a high precedence `rcases` pattern, `rintro_patt_hi` below.\n This means only tuples and identifiers are allowed; alternations and type ascriptions\n require `(...)` instead, which switches to `patt`.\n* `rintro_patt_parse tt` will parse a low precedence `rcases` pattern, `rintro_patt` below.\n This consists of either a sequence of patterns `p1 p2 p3` or an alternation list `p1 | p2 | p3`\n treated as a single pattern, optionally followed by a `: ty` type ascription, which applies to\n every pattern in the list.\n* `rintro_patt_parse ff` parses `rintro_patt_low`, which is the same as `rintro_patt_parse tt` but\n it does not permit an unparenthesized alternation list, it must have the form `p1 p2 p3 (: ty)?`.\n\n```lean\nrintro_patt ::= (rintro_patt_hi+ | patt_med) (\":\" expr)?\nrintro_patt_low ::= rintro_patt_hi* (\":\" expr)?\nrintro_patt_hi ::= patt_hi | \"(\" rintro_patt \")\"\n```\n-/\n/-- Syntax for a `rintro` pattern: `('?' (: n)?) | rintro_patt`. -/\nnamespace interactive\n\n\n/--\n`rcases` is a tactic that will perform `cases` recursively, according to a pattern. It is used to\ndestructure hypotheses or expressions composed of inductive types like `h1 : a ∧ b ∧ c ∨ d` or\n`h2 : ∃ x y, trans_rel R x y`. Usual usage might be `rcases h1 with ⟨ha, hb, hc⟩ | hd` or\n`rcases h2 with ⟨x, y, _ | ⟨z, hxz, hzy⟩⟩` for these examples.\n\nEach element of an `rcases` pattern is matched against a particular local hypothesis (most of which\nare generated during the execution of `rcases` and represent individual elements destructured from\nthe input expression). An `rcases` pattern has the following grammar:\n\n* A name like `x`, which names the active hypothesis as `x`.\n* A blank `_`, which does nothing (letting the automatic naming system used by `cases` name the\n hypothesis).\n* A hyphen `-`, which clears the active hypothesis and any dependents.\n* The keyword `rfl`, which expects the hypothesis to be `h : a = b`, and calls `subst` on the\n hypothesis (which has the effect of replacing `b` with `a` everywhere or vice versa).\n* A type ascription `p : ty`, which sets the type of the hypothesis to `ty` and then matches it\n against `p`. (Of course, `ty` must unify with the actual type of `h` for this to work.)\n* A tuple pattern `⟨p1, p2, p3⟩`, which matches a constructor with many arguments, or a series\n of nested conjunctions or existentials. For example if the active hypothesis is `a ∧ b ∧ c`,\n then the conjunction will be destructured, and `p1` will be matched against `a`, `p2` against `b`\n and so on.\n* An alteration pattern `p1 | p2 | p3`, which matches an inductive type with multiple constructors,\n or a nested disjunction like `a ∨ b ∨ c`.\n\nA pattern like `⟨a, b, c⟩ | ⟨d, e⟩` will do a split over the inductive datatype,\nnaming the first three parameters of the first constructor as `a,b,c` and the\nfirst two of the second constructor `d,e`. If the list is not as long as the\nnumber of arguments to the constructor or the number of constructors, the\nremaining variables will be automatically named. If there are nested brackets\nsuch as `⟨⟨a⟩, b | c⟩ | d` then these will cause more case splits as necessary.\nIf there are too many arguments, such as `⟨a, b, c⟩` for splitting on\n`∃ x, ∃ y, p x`, then it will be treated as `⟨a, ⟨b, c⟩⟩`, splitting the last\nparameter as necessary.\n\n`rcases` also has special support for quotient types: quotient induction into Prop works like\nmatching on the constructor `quot.mk`.\n\n`rcases h : e with PAT` will do the same as `rcases e with PAT` with the exception that an\nassumption `h : e = PAT` will be added to the context.\n\n`rcases? e` will perform case splits on `e` in the same way as `rcases e`,\nbut rather than accepting a pattern, it does a maximal cases and prints the\npattern that would produce this case splitting. The default maximum depth is 5,\nbut this can be modified with `rcases? e : n`.\n-/\n/--\nThe `rintro` tactic is a combination of the `intros` tactic with `rcases` to\nallow for destructuring patterns while introducing variables. See `rcases` for\na description of supported patterns. For example, `rintro (a | ⟨b, c⟩) ⟨d, e⟩`\nwill introduce two variables, and then do case splits on both of them producing\ntwo subgoals, one with variables `a d e` and the other with `b c d e`.\n\n`rintro`, unlike `rcases`, also supports the form `(x y : ty)` for introducing\nand type-ascripting multiple variables at once, similar to binders.\n\n`rintro?` will introduce and case split on variables in the same way as\n`rintro`, but will also print the `rintro` invocation that would have the same\nresult. Like `rcases?`, `rintro? : n` allows for modifying the\ndepth of splitting; the default is 5.\n\n`rintros` is an alias for `rintro`.\n-/\n/-- Alias for `rintro`. -/\n/-- Parses `patt? (: expr)? (:= expr)?`, the arguments for `obtain`.\n (This is almost the same as `rcases_patt_parse ff`,\nbut it allows the pattern part to be empty.) -/\n/--\nThe `obtain` tactic is a combination of `have` and `rcases`. See `rcases` for\na description of supported patterns.\n\n```lean\nobtain ⟨patt⟩ : type,\n{ ... }\n```\nis equivalent to\n```lean\nhave h : type,\n{ ... },\nrcases h with ⟨patt⟩\n```\n\nThe syntax `obtain ⟨patt⟩ : type := proof` is also supported.\n\nIf `⟨patt⟩` is omitted, `rcases` will try to infer the pattern.\n\nIf `type` is omitted, `:= proof` is required.\n-/\nend Mathlib", "meta": {"author": "AurelienSaue", "repo": "Mathlib4_auto", "sha": "590df64109b08190abe22358fabc3eae000943f2", "save_path": "github-repos/lean/AurelienSaue-Mathlib4_auto", "path": "github-repos/lean/AurelienSaue-Mathlib4_auto/Mathlib4_auto-590df64109b08190abe22358fabc3eae000943f2/Mathlib/tactic/rcases_auto.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.33807711081162, "lm_q2_score": 0.04468087408894116, "lm_q1q2_score": 0.015105580820527003}} {"text": "import ReactorModel.Objects.Reactor.Theorems.LawfulCoe\n\nnoncomputable section\nopen Classical\n\nnamespace ReactorType \n\ninductive Equivalent [ReactorType α] : α → α → Prop\n | intro\n (mem_cpt?_iff : ∀ cpt j, (j ∈ cpt? cpt rtr₁) ↔ (j ∈ cpt? cpt rtr₂)) \n (rcns_some_eq : ∀ {i r₁ r₂}, (rcns rtr₁ i = some r₁) → (rcns rtr₂ i = some r₂) → r₁ = r₂) \n (nest_equiv : ∀ {i n₁ n₂}, (nest rtr₁ i = some n₁) → (nest rtr₂ i = some n₂) → Equivalent n₁ n₂) \n : Equivalent rtr₁ rtr₂\n \nnamespace Equivalent\n\ninstance [ReactorType α] : HasEquiv α where \n Equiv := Equivalent\n\n@[refl]\nprotected theorem refl [ReactorType.WellFounded α] {rtr : α} : rtr ≈ rtr := by\n induction rtr using ReactorType.WellFounded.induction\n case nest hi =>\n constructor <;> (intros; simp_all)\n exact hi _ _ ‹_› \n\nvariable [ReactorType α] {rtr rtr₁ : α}\n\n@[symm]\nprotected theorem symm (e : rtr₁ ≈ rtr₂) : rtr₂ ≈ rtr₁ := by\n induction e\n case intro h₁ h₂ _ hi => \n constructor <;> intros\n · exact h₁ ‹_› ‹_› |>.symm\n · exact h₂ ‹_› ‹_› |>.symm\n · exact hi ‹_› ‹_›\n \n@[trans]\nprotected theorem trans (e₁ : rtr₁ ≈ rtr₂) (e₂ : rtr₂ ≈ rtr₃) : rtr₁ ≈ rtr₃ := by\n induction e₁ generalizing rtr₃; cases e₂\n case intro.intro h₁ h₂ _ hi h₁' h₂' h₃' => \n constructor\n · intros; exact h₁ ‹_› ‹_› |>.trans (h₁' ‹_› ‹_›)\n · intro _ _ _ h _\n have ⟨_, h⟩ := Partial.mem_iff.mp <| h₁ .rcn ‹_› |>.mp $ Partial.mem_iff.mpr ⟨_, h⟩\n exact h₂ ‹_› h |>.trans (h₂' h ‹_›)\n · intro _ _ _ h _\n have ⟨_, h⟩ := Partial.mem_iff.mp <| h₁ .rtr ‹_› |>.mp $ Partial.mem_iff.mpr ⟨_, h⟩ \n exact hi ‹_› h (h₃' h ‹_›)\n\ntheorem mem_cpt?_iff : (rtr₁ ≈ rtr₂) → (i ∈ cpt? cpt rtr₁ ↔ i ∈ cpt? cpt rtr₂)\n | intro h .. => h _ _\n\ntheorem rcns_some_eq : (rtr₁ ≈ rtr₂) → (rcns rtr₁ i = some r₁) → (rcns rtr₂ i = some r₂) → r₁ = r₂\n | intro _ h .. => h\n\ntheorem nest_equiv : (rtr₁ ≈ rtr₂) → (nest rtr₁ i = some n₁) → (nest rtr₂ i = some n₂) → n₁ ≈ n₂\n | intro _ _ h => h\n\ntheorem rcns_eq (e : rtr₁ ≈ rtr₂) : rcns rtr₂ = rcns rtr₁ := by\n funext i\n by_cases h₁ : i ∈ rcns rtr₁ \n case pos =>\n have ⟨_, h₂⟩ := Partial.mem_iff.mp $ mem_cpt?_iff e (cpt := .rcn) |>.mp h₁\n have ⟨_, h₁⟩ := Partial.mem_iff.mp h₁\n exact rcns_some_eq e h₁ h₂ ▸ h₁ |>.symm ▸ h₂\n case neg =>\n have h₂ := Partial.mem_iff.not.mp $ mem_cpt?_iff e (cpt := .rcn) |>.not.mp h₁\n have h₁ := Partial.mem_iff.not.mp h₁\n simp [cpt?] at h₁ h₂ \n simp [Option.eq_none_iff_forall_not_mem.mpr h₁, Option.eq_none_iff_forall_not_mem.mpr h₂]\n\ntheorem cpt?_some_iff (e : rtr₁ ≈ rtr₂) :\n (∃ o₁, cpt? cpt rtr₁ i = some o₁) ↔ (∃ o₂, cpt? cpt rtr₂ i = some o₂) := by\n simp [←Partial.mem_iff, mem_cpt?_iff e]\n\nvariable [Indexable α] {rtr₁ : α}\n\ntheorem obj?_rcn_eq (e : rtr₁ ≈ rtr₂) : rtr₁[.rcn] = rtr₂[.rcn] :=\n sorry\n\ntheorem mem_iff {i} (e : rtr₁ ≈ rtr₂) : (i ∈ rtr₁[cpt]) ↔ (i ∈ rtr₂[cpt]) := by\n sorry\n\ntheorem obj?_rtr_equiv (e : rtr₁ ≈ rtr₂) (h₁ : rtr₁[.rtr][i] = some n₁) (h₂ : rtr₂[.rtr][i] = some n₂) : \n n₁ ≈ n₂ := by\n sorry\n\ntheorem obj?_some_iff (e : rtr₁ ≈ rtr₂) :\n (∃ o₁, rtr₁[cpt][i] = some o₁) ↔ (∃ o₂, rtr₂[cpt][i] = some o₂) := \n sorry\n\nend Equivalent\n\ntheorem LawfulMemUpdate.equiv [ReactorType.WellFounded α] {rtr₁ : α}\n (u : LawfulMemUpdate cpt i f rtr₁ rtr₂) : rtr₁ ≈ rtr₂ := by\n induction u <;> constructor\n case final.mem_cpt?_iff e h₁ h₂ =>\n intro c j\n by_cases hc : c = cpt <;> try subst hc\n case neg => exact e.mem_iff (.inl hc)\n case pos =>\n by_cases hj : j = i <;> try subst hj\n case neg => exact e.mem_iff (.inr hj)\n case pos => simp [Partial.mem_iff, h₁, h₂]\n case final.rcns_some_eq e _ _ =>\n intro j _ _ h₁ h₂\n have h := e (c := .rcn) (j := j) (.inl $ by simp)\n simp_all [cpt?]\n case final.nest_equiv e _ _ =>\n intro j _ _ h₁ h₂\n have h := e (c := .rtr) (j := j) (.inl $ by simp)\n simp_all [cpt?]\n exact .refl\n case nest.mem_cpt?_iff j _ _ _ _ e h₁ h₂ _ _ =>\n intro c j'\n by_cases hc : c = .rtr <;> try subst hc\n case neg => exact e.mem_iff (.inl hc)\n case pos => \n by_cases hj : j' = j <;> try subst hj\n case neg => exact e.mem_iff (.inr hj)\n case pos => simp [Partial.mem_iff, h₁, h₂]\n case nest.rcns_some_eq e h₁ h₂ _ _ =>\n intro j _ _ h₁ h₂\n have h := e (c := .rcn) (j := j) (.inl $ by simp)\n simp_all [cpt?]\n case nest.nest_equiv j _ _ _ _ e _ _ _ hi =>\n intro j' n₁' n₂' h₁' h₂'\n by_cases hj : j' = j <;> try subst hj\n case pos => simp_all [cpt?]; assumption\n case neg => \n have := e (c := .rtr) (j := j') (.inr hj)\n simp_all [cpt?]\n exact .refl\n\ntheorem LawfulUpdate.equiv [ReactorType.WellFounded α] {rtr₁ : α} :\n (LawfulUpdate cpt i f rtr₁ rtr₂) → rtr₁ ≈ rtr₂\n | notMem _ h => h ▸ .refl\n | update u => u.equiv\n\ntheorem LawfulUpdatable.equiv [LawfulUpdatable α] {rtr : α} : \n (Updatable.update rtr cpt i f) ≈ rtr := \n Equivalent.symm (lawful rtr cpt i f).equiv\n\nnamespace Member\n\ninductive Equivalent [ReactorType α] [ReactorType β] : \n {rtr₁ : α} → {rtr₂ : β} → (Member cpt i rtr₁) → (Member cpt i rtr₂) → Prop \n | final : Equivalent (.final h₁) (.final h₂)\n | nest {n₁ : α} {n₂ : β} {m₁ : Member cpt i n₁} {m₂ : Member cpt i n₂} :\n (h₁ : ReactorType.nest rtr₁ j = some n₁) → (h₂ : ReactorType.nest rtr₂ j = some n₂) → \n (Equivalent m₁ m₂) → Equivalent (.nest h₁ m₁) (.nest h₂ m₂)\n\nnamespace Equivalent\n\n@[refl]\ntheorem refl [ReactorType.WellFounded α] {rtr : α} {m : Member cpt i rtr} : \n Equivalent m m := by\n induction rtr using ReactorType.WellFounded.induction\n case nest hi =>\n cases m\n case final => exact .final\n case nest h => exact .nest _ _ (hi _ ⟨_, h⟩)\n\nvariable [ReactorType α] [ReactorType β]\n\ntheorem symm {rtr₁ : α} {rtr₂ : β} {m₁ : Member cpt i rtr₁} {m₂ : Member cpt i rtr₂}\n (e : Equivalent m₁ m₂) : (Equivalent m₂ m₁) := by\n induction e <;> constructor; assumption\n\ntheorem trans \n [ReactorType γ] {rtr₁ : α} {rtr₂ : β} {rtr₃ : γ}\n {m₁ : Member cpt i rtr₁} {m₂ : Member cpt i rtr₂} {m₃ : Member cpt i rtr₃}\n (e₁ : Equivalent m₁ m₂) (e₂ : Equivalent m₂ m₃) : (Equivalent m₁ m₃) := by\n induction e₁ generalizing m₃ rtr₃ <;> cases e₂ <;> constructor\n case nest.nest hi₁ _ _ _ _ hi₂ => exact hi₁ hi₂\n\n-- Lemma for `to_eq`.\nprivate theorem to_eq' {rtr₁ rtr₂ : α} {m₁ : Member cpt i rtr₁} {m₂ : Member cpt i rtr₂} \n (h : rtr₁ = rtr₂) (e : Equivalent m₁ m₂) : m₁ = cast (by simp [h]) m₂ := by\n induction e <;> subst h\n case final => rfl\n case nest m₁ _ h₁ _ hi h₂ => \n injection h₁ ▸ h₂ with h\n simp [hi h, h]\n\ntheorem to_eq {rtr : α} {m₁ m₂ : Member cpt i rtr} (e : Equivalent m₁ m₂) : m₁ = m₂ := \n e.to_eq' rfl\n\ntheorem from_lawfulCoe [ReactorType α] [ReactorType β] [LawfulCoe α β] {rtr : α} \n (m : Member cpt i rtr) : Equivalent m (m : Member cpt i (rtr : β)) := by\n induction m\n case final => constructor\n case nest e => simp [fromLawfulCoe, Equivalent.nest _ _ e]\n\nend Equivalent\n\nvariable [ReactorType.WellFounded α] {rtr₁ : α}\n\ndef fromLawfulMemUpdate {rtr₁ : α} : \n (Member c j rtr₂) → (LawfulMemUpdate cpt i f rtr₁ rtr₂) → Member c j rtr₁\n | final h, u => final (Equivalent.mem_cpt?_iff u.equiv |>.mpr h)\n | nest h m (j := j), .final e _ _ => \n nest (m := m) $ by \n have h' := e (c := .rtr) (j := j) (.inl $ by simp)\n simp [cpt?] at h'\n exact h'.symm ▸ h\n | nest h m (j := j₂), .nest e h₁ h₂ u (j := j₁) =>\n if hj : j₂ = j₁ then\n let m' := (hj ▸ h |>.symm.trans h₂ |> Option.some_inj.mp) ▸ m \n nest h₁ $ fromLawfulMemUpdate m' u\n else\n nest (m := m) $ by \n have h' := e (c := .rtr) (.inr hj)\n simp [cpt?] at h'\n exact h'.symm ▸ h\n\ndef fromLawfulUpdate (m : Member c j rtr₂) : (LawfulUpdate cpt i f rtr₁ rtr₂) → Member c j rtr₁\n | .notMem _ h => h ▸ m\n | .update u => m.fromLawfulMemUpdate u\n\ntheorem Equivalent.from_lawfulMemUpdate (u : LawfulMemUpdate cpt i f rtr₁ rtr₂) \n (m : Member c j rtr₂) : Equivalent m (m.fromLawfulMemUpdate u) := by\n induction u <;> cases m <;> (simp [fromLawfulMemUpdate]; try exact .final)\n case final.nest e _ _ j _ _ hn => \n have h := e (c := .rtr) (j := j) (.inl $ by simp)\n simp [cpt?] at h\n exact .nest hn (h ▸ hn) .refl\n case nest.nest e h₁ h₂ _ hi _ _ m hn =>\n split\n case inl hj =>\n subst hj\n cases Option.some_inj.mp $ hn.symm.trans h₂\n exact .nest hn h₁ (hi m)\n case inr hj =>\n have h := e (c := .rtr) (.inr hj)\n simp [cpt?] at h\n exact .nest hn (h.symm ▸ hn) .refl\n\ntheorem Equivalent.from_lawfulUpdate (u : LawfulUpdate cpt i f rtr₁ rtr₂) \n (m : Member c j rtr₂) : Equivalent m (m.fromLawfulUpdate u) := by\n cases u\n case notMem _ h => cases h; rfl\n case update u => exact Equivalent.from_lawfulMemUpdate u m \n \nend Member\n\ntheorem UniqueIDs.lift [ReactorType α] [ReactorType β] [LawfulCoe α β] {rtr : α} \n (h : UniqueIDs (rtr : β)) : UniqueIDs rtr where\n allEq m₁ m₂ :=\n h.allEq (.fromLawfulCoe m₁) (.fromLawfulCoe m₂) ▸ Member.Equivalent.from_lawfulCoe m₁ \n |>.trans (Member.Equivalent.from_lawfulCoe m₂).symm \n |>.to_eq\n\ninstance [LawfulUpdatable α] [ind : Indexable β] [LawfulCoe α β] : Indexable α where\n unique_ids := UniqueIDs.lift ind.unique_ids \n\nopen Equivalent\nvariable [Indexable α] [Indexable β] {rtr rtr₁ : α}\n\nnamespace Dependency\n \ntheorem equiv (e : rtr₁ ≈ rtr₂) (d : j₁ <[rtr₂] j₂) : j₁ <[rtr₁] j₂ := by\n induction d with\n | prio h₁ h₂ h₃ => \n -- TODO: The next 2 lines are a common pattern in the `updated` proofs. Perhaps create a \n -- (unidirectional) derivative of `Equivalent.obj?_some_iff` that includes equivalence.\n have ⟨_, h₁'⟩ := obj?_some_iff e |>.mpr ⟨_, h₁⟩\n have e := Equivalent.obj?_rtr_equiv e h₁' h₁\n exact prio h₁' (rcns_eq e ▸ h₂) (rcns_eq e ▸ h₃) ‹_› ‹_›\n | mutNorm h₁ h₂ h₃ => \n have ⟨_, h₁'⟩ := obj?_some_iff e |>.mpr ⟨_, h₁⟩ \n have e := Equivalent.obj?_rtr_equiv e h₁' h₁\n exact mutNorm h₁' (rcns_eq e ▸ h₂) (rcns_eq e ▸ h₃) ‹_› ‹_›\n | depOverlap h₁ h₂ => \n exact depOverlap (e.obj?_rcn_eq.symm ▸ h₁) (e.obj?_rcn_eq.symm ▸ h₂) ‹_› ‹_› ‹_›\n | mutNest h₁ h₂ h₃ _ h₄ => \n have ⟨_, h₁'⟩ := e.obj?_some_iff.mpr ⟨_, h₁⟩ \n have e := Equivalent.obj?_rtr_equiv e h₁' h₁\n have ⟨_, h₂'⟩ := cpt?_some_iff e (cpt := .rtr) |>.mpr ⟨_, h₂⟩\n have h₄' := mem_cpt?_iff (Equivalent.nest_equiv e h₂' h₂) (cpt := .rcn) |>.mpr h₄\n exact mutNest h₁' h₂' (rcns_eq e ▸ h₃) ‹_› h₄'\n | trans _ _ d₁ d₂ => \n exact trans d₁ d₂\n\ntheorem Acyclic.equiv (e : rtr₁ ≈ rtr₂) (a : Acyclic rtr₁) : Acyclic rtr₂ :=\n fun i d => absurd (d.equiv e) (a i) \n\nend Dependency\n\nnamespace Wellformed\n\nset_option hygiene false in\nscoped macro \"equiv_nested_proof \" name:ident : term => `(\n fun hc hp => \n have e := Equivalent.obj?_rtr_equiv ‹_› h₁ h₂\n have ⟨_, hc'⟩ := Equivalent.cpt?_some_iff e (cpt := .rtr) |>.mp ⟨_, hc⟩ \n have e := Equivalent.nest_equiv e hc hc'\n $(Lean.mkIdentFrom name $ `ValidDependency ++ name.getId) hc' \n (Equivalent.mem_cpt?_iff e (cpt := .prt _) |>.mp hp)\n)\n\ntheorem ValidDependency.equiv \n (e : rtr₁ ≈ rtr₂) (h₁ : rtr₁[.rtr][j] = some con₁) (h₂ : rtr₂[.rtr][j] = some con₂) : \n (ValidDependency con₁ rk dk d) → ValidDependency con₂ rk dk d\n | stv h => stv $ mem_cpt?_iff (obj?_rtr_equiv e h₁ h₂) (cpt := .stv) |>.mp h\n | act h => act $ mem_cpt?_iff (obj?_rtr_equiv e h₁ h₂) (cpt := .act) |>.mp h\n | prt h => prt $ mem_cpt?_iff (obj?_rtr_equiv e h₁ h₂) (cpt := .prt _) |>.mp h\n | nestedIn hc hp => (equiv_nested_proof nestedIn) hc hp\n | nestedOut hc hp => (equiv_nested_proof nestedOut) hc hp\n\nset_option hygiene false in\nscoped macro \"equiv_prio_proof \" name:ident rtr₁:ident rtr₂:ident : term => `(\n fun h₁ h₂ h₃ => \n have ⟨_, h₁'⟩ := Equivalent.obj?_some_iff ‹$rtr₁ ≈ $rtr₂› |>.mpr ⟨_, h₁⟩ \n have e := Equivalent.obj?_rtr_equiv ‹_› h₁' h₁\n $(Lean.mkIdentFrom name $ `Wellformed ++ name.getId) \n ‹_› h₁' (Equivalent.rcns_eq e ▸ h₂) (Equivalent.rcns_eq e ▸ h₃)\n)\n\ntheorem equiv (e : rtr₁ ≈ rtr₂) (wf : Wellformed rtr₁) : Wellformed rtr₂ where\n overlap_prio := equiv_prio_proof overlap_prio rtr₁ rtr₂\n hazards_prio := equiv_prio_proof hazards_prio rtr₁ rtr₂\n mutation_prio := equiv_prio_proof mutation_prio rtr₁ rtr₂\n acyclic_deps := wf.acyclic_deps.equiv e\n valid_deps h₁ h₂ h₃ := \n have ⟨_, h₁'⟩ := Equivalent.obj?_some_iff e |>.mpr ⟨_, h₁⟩ \n have e := Equivalent.obj?_rtr_equiv e h₁' h₁\n have h₂' := Equivalent.rcns_eq e ▸ h₂\n wf.valid_deps h₁' h₂' h₃ |>.equiv ‹_› h₁' h₁\n unique_inputs h₁ h₂ _ h₃ := \n have h₃' := Equivalent.mem_iff e |>.mpr h₃\n wf.unique_inputs (e.obj?_rcn_eq.symm ▸ h₁) (e.obj?_rcn_eq.symm ▸ h₂) ‹_› h₃'\n\nend Wellformed\nend ReactorType\n", "meta": {"author": "marcusrossel", "repo": "reactor-model", "sha": "f82fffb489b4352a0cc6bee964d44a142fee18ce", "save_path": "github-repos/lean/marcusrossel-reactor-model", "path": "github-repos/lean/marcusrossel-reactor-model/reactor-model-f82fffb489b4352a0cc6bee964d44a142fee18ce/src/ReactorModel/Objects/Reactor/Theorems/Equivalent.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4843800842769843, "lm_q2_score": 0.031143833344941297, "lm_q1q2_score": 0.01508545262033102}} {"text": "import category_theory.preadditive.basic\nimport category_theory.abelian.projective\nimport category_theory.abelian.diagram_lemmas.four\n\nimport data.matrix.notation\n\nimport .abelian_category\nimport .fin_functor\nimport .split_exact\n\nnoncomputable theory\n\nopen category_theory\nopen category_theory.limits\nopen category_theory.preadditive\n\nuniverses v u\n\nnamespace category_theory\nvariables (𝒞 : Type u) [category.{v} 𝒞]\n\n@[ext]\nstructure short_exact_sequence [has_images 𝒞] [has_zero_morphisms 𝒞] [has_kernels 𝒞] :=\n(fst snd trd : 𝒞)\n(f : fst ⟶ snd)\n(g : snd ⟶ trd)\n[mono' : mono f]\n[epi' : epi g]\n(exact' : exact f g)\n\nnamespace short_exact_sequence\n\nattribute [instance] mono' epi'\n\nvariables {𝒞} [has_images 𝒞] [has_zero_morphisms 𝒞] [has_kernels 𝒞]\n\n@[simp, reassoc] lemma f_comp_g (A : short_exact_sequence 𝒞) : A.f ≫ A.g = 0 := A.exact'.w\n\n@[ext]\nstructure hom (A B : short_exact_sequence 𝒞) :=\n(fst : A.1 ⟶ B.1)\n(snd : A.2 ⟶ B.2)\n(trd : A.3 ⟶ B.3)\n(sq1' : fst ≫ B.f = A.f ≫ snd . obviously)\n(sq2' : snd ≫ B.g = A.g ≫ trd . obviously)\n\nnamespace hom\n\nrestate_axiom sq1' sq1\nrestate_axiom sq2' sq2\n\nattribute [reassoc] sq1 sq2\n\nend hom\n\ninstance : quiver (short_exact_sequence 𝒞) := ⟨hom⟩\n\ndef id (A : short_exact_sequence 𝒞) : A ⟶ A :=\n{ fst := 𝟙 _,\n snd := 𝟙 _,\n trd := 𝟙 _,\n sq1' := by simp only [category.id_comp, category.comp_id],\n sq2' := by simp only [category.id_comp, category.comp_id], }\n\ndef comp {A B C : short_exact_sequence 𝒞} (f : A ⟶ B) (g : B ⟶ C) : A ⟶ C :=\n{ fst := f.1 ≫ g.1,\n snd := f.2 ≫ g.2,\n trd := f.3 ≫ g.3,\n sq1' := by rw [category.assoc, hom.sq1, hom.sq1_assoc],\n sq2' := by rw [category.assoc, hom.sq2, hom.sq2_assoc], }\n\ninstance : category (short_exact_sequence 𝒞) :=\n{ id := id,\n comp := λ A B C f g, comp f g,\n id_comp' := by { intros, ext; dsimp; apply category.id_comp, },\n comp_id' := by { intros, ext; dsimp; apply category.comp_id, },\n assoc' := by { intros, ext; dsimp; apply category.assoc, },\n .. (infer_instance : quiver (short_exact_sequence 𝒞)) }\n\n@[simp] lemma id_fst (A : short_exact_sequence 𝒞) : hom.fst (𝟙 A) = 𝟙 A.1 := rfl\n@[simp] lemma id_snd (A : short_exact_sequence 𝒞) : hom.snd (𝟙 A) = 𝟙 A.2 := rfl\n@[simp] lemma id_trd (A : short_exact_sequence 𝒞) : hom.trd (𝟙 A) = 𝟙 A.3 := rfl\n\nvariables {A B C : short_exact_sequence 𝒞} (f : A ⟶ B) (g : B ⟶ C)\n\n@[simp, reassoc] lemma comp_fst : (f ≫ g).1 = f.1 ≫ g.1 := rfl\n@[simp, reassoc] lemma comp_snd : (f ≫ g).2 = f.2 ≫ g.2 := rfl\n@[simp, reassoc] lemma comp_trd : (f ≫ g).3 = f.3 ≫ g.3 := rfl\n\nvariables (𝒞)\n\n@[simps] def Fst : short_exact_sequence 𝒞 ⥤ 𝒞 :=\n{ obj := fst, map := λ A B f, f.1 }\n\n@[simps] def Snd : short_exact_sequence 𝒞 ⥤ 𝒞 :=\n{ obj := snd, map := λ A B f, f.2 }\n\n@[simps] def Trd : short_exact_sequence 𝒞 ⥤ 𝒞 :=\n{ obj := trd, map := λ A B f, f.3 }\n\n@[simps] def f_nat : Fst 𝒞 ⟶ Snd 𝒞 :=\n{ app := λ A, A.f,\n naturality' := λ A B f, f.sq1 }\n\n@[simps] def g_nat : Snd 𝒞 ⟶ Trd 𝒞 :=\n{ app := λ A, A.g,\n naturality' := λ A B f, f.sq2 }\n\ninstance : has_zero_morphisms (short_exact_sequence 𝒞) :=\n{ has_zero := λ A B, ⟨{ fst := 0, snd := 0, trd := 0 }⟩,\n comp_zero' := by { intros, ext; apply comp_zero },\n zero_comp' := by { intros, ext; apply zero_comp }, }\n.\n\n@[simp] lemma hom_zero_fst : (0 : A ⟶ B).1 = 0 := rfl\n\n@[simp] lemma hom_zero_snd : (0 : A ⟶ B).2 = 0 := rfl\n\n@[simp] lemma hom_zero_trd : (0 : A ⟶ B).3 = 0 := rfl\n\nvariables {𝒞}\n\nprotected def functor (A : short_exact_sequence 𝒞) : fin 3 ⥤ 𝒞 :=\nfin3_functor_mk ![A.1, A.2, A.3] A.f A.g\n\ndef functor_map {A B : short_exact_sequence 𝒞} (f : A ⟶ B) :\n Π i, A.functor.obj i ⟶ B.functor.obj i\n| ⟨0,h⟩ := f.1\n| ⟨1,h⟩ := f.2\n| ⟨2,h⟩ := f.3\n| ⟨i+3,hi⟩ := by { exfalso, revert hi, dec_trivial }\n\nmeta def aux_tac : tactic unit :=\n`[simp only [hom_of_le_refl, functor.map_id, category.id_comp, category.comp_id]]\n\nlemma functor_map_naturality {A B : short_exact_sequence 𝒞} (f : A ⟶ B) :\n ∀ (i j : fin 3) (hij : i ≤ j),\n functor_map f i ≫ B.functor.map hij.hom = A.functor.map hij.hom ≫ functor_map f j\n| ⟨0,hi⟩ ⟨0,hj⟩ hij := by aux_tac\n| ⟨1,hi⟩ ⟨1,hj⟩ hij := by aux_tac\n| ⟨2,hi⟩ ⟨2,hj⟩ hij := by aux_tac\n| ⟨0,hi⟩ ⟨1,hj⟩ hij := f.sq1\n| ⟨1,hi⟩ ⟨2,hj⟩ hij := f.sq2\n| ⟨i+3,hi⟩ _ _ := by { exfalso, revert hi, dec_trivial }\n| _ ⟨j+3,hj⟩ _ := by { exfalso, revert hj, dec_trivial }\n| ⟨i+1,hi⟩ ⟨0,hj⟩ H := by { exfalso, revert H, dec_trivial }\n| ⟨i+2,hi⟩ ⟨1,hj⟩ H := by { exfalso, revert H, dec_trivial }\n| ⟨0,hi⟩ ⟨2,hj⟩ hij :=\nbegin\n have h01 : (0 : fin 3) ⟶ 1 := hom_of_le dec_trivial,\n have h12 : (1 : fin 3) ⟶ 2 := hom_of_le dec_trivial,\n calc functor_map f ⟨0, hi⟩ ≫ B.functor.map hij.hom\n = functor_map f ⟨0, hi⟩ ≫ B.functor.map h01 ≫ B.functor.map h12 : _\n ... = (functor_map f ⟨0, hi⟩ ≫ B.functor.map h01) ≫ B.functor.map h12 : by rw category.assoc\n ... = (A.functor.map h01 ≫ functor_map f _) ≫ B.functor.map h12 : _\n ... = A.functor.map h01 ≫ functor_map f _ ≫ B.functor.map h12 : category.assoc _ _ _\n ... = A.functor.map h01 ≫ A.functor.map h12 ≫ functor_map f _ : _\n ... = A.functor.map hij.hom ≫ functor_map f ⟨2, hj⟩ : _,\n { rw [← functor.map_comp], congr, },\n { congr' 1, exact f.sq1 },\n { congr' 1, exact f.sq2 },\n { rw [← functor.map_comp_assoc], congr, },\nend\n\n@[simps] def Functor : short_exact_sequence 𝒞 ⥤ fin 3 ⥤ 𝒞 :=\n{ obj := short_exact_sequence.functor,\n map := λ A B f,\n { app := functor_map f,\n naturality' := λ i j hij, (functor_map_naturality f i j hij.le).symm },\n map_id' := λ A, by { ext i, fin_cases i; refl },\n map_comp' := λ A B C f g, by { ext i, fin_cases i; refl } }\n\nend short_exact_sequence\n\nnamespace short_exact_sequence\n\nvariables {𝒞} [abelian 𝒞]\nvariables {A B C : short_exact_sequence 𝒞} (f : A ⟶ B) (g : B ⟶ C)\n\nsection iso\n\nvariables {A B C} (f g)\n\nopen_locale zero_object\n\n/-- One form of the five lemma: if a morphism of short exact sequences has isomorphisms\nas first and third component, then the second component is also an isomorphism. -/\nlemma snd_is_iso (h1 : is_iso f.1) (h3 : is_iso f.3) : is_iso f.2 :=\n@abelian.is_iso_of_is_iso_of_is_iso_of_is_iso_of_is_iso 𝒞 _ _\n 0 A.1 A.2 A.3\n 0 B.1 B.2 B.3\n 0 A.f A.g\n 0 B.f B.g\n 0 f.1 f.2 f.3 (by rw [zero_comp, zero_comp]) f.sq1 f.sq2\n 0 0\n 0 0 0 (by rw [comp_zero, comp_zero])\n (exact_zero_left_of_mono _)\n A.exact'\n ((epi_iff_exact_zero_right _).mp infer_instance)\n (exact_zero_left_of_mono _)\n B.exact'\n ((epi_iff_exact_zero_right _).mp infer_instance) _ _ _ _\n\n/-- One form of the five lemma: if a morphism `f` of short exact sequences has isomorphisms\nas first and third component, then `f` itself is an isomorphism. -/\nlemma is_iso_of_fst_of_trd (h1 : is_iso f.1) (h3 : is_iso f.3) : is_iso f :=\n{ out :=\n begin\n haveI : is_iso f.2 := snd_is_iso f h1 h3,\n refine ⟨⟨inv f.1, inv f.2, inv f.3, _, _⟩, _, _⟩,\n { dsimp, simp only [is_iso.inv_comp_eq, f.sq1_assoc, category.comp_id, is_iso.hom_inv_id], },\n { dsimp, simp only [is_iso.inv_comp_eq, f.sq2_assoc, category.comp_id, is_iso.hom_inv_id], },\n { ext; dsimp; simp only [is_iso.hom_inv_id], },\n { ext; dsimp; simp only [is_iso.inv_hom_id], },\n end }\n\n@[simps] def iso_of_components (f₁ : A.1 ≅ B.1) (f₂ : A.2 ≅ B.2) (f₃ : A.3 ≅ B.3)\n (sq1 : f₁.hom ≫ B.f = A.f ≫ f₂.hom) (sq2 : f₂.hom ≫ B.g = A.g ≫ f₃.hom) :\n A ≅ B :=\n{ hom := ⟨f₁.hom, f₂.hom, f₃.hom, sq1, sq2⟩,\n inv :=\n begin\n refine ⟨f₁.inv, f₂.inv, f₃.inv, _, _⟩; dsimp,\n rw [iso.inv_comp_eq, ← category.assoc, iso.eq_comp_inv, sq1],\n rw [iso.inv_comp_eq, ← category.assoc, iso.eq_comp_inv, sq2],\n end,\n hom_inv_id' := by { ext; apply iso.hom_inv_id, },\n inv_hom_id' := by { ext; apply iso.inv_hom_id, } }\n\n@[simps] def iso_of_components' (f₁ : A.1 ≅ B.1) (f₂ : A.2 ⟶ B.2) (f₃ : A.3 ≅ B.3)\n (sq1 : f₁.hom ≫ B.f = A.f ≫ f₂) (sq2 : f₂ ≫ B.g = A.g ≫ f₃.hom) :\n A ≅ B :=\nlet F : A ⟶ B := ⟨f₁.hom, f₂, f₃.hom, sq1, sq2⟩ in\n{ hom := F,\n inv :=\n begin\n haveI : is_iso F.2 := snd_is_iso _ infer_instance infer_instance,\n refine ⟨f₁.inv, inv F.2, f₃.inv, _, _⟩; dsimp,\n rw [iso.inv_comp_eq, ← category.assoc, is_iso.eq_comp_inv, sq1],\n rw [is_iso.inv_comp_eq, ← category.assoc, iso.eq_comp_inv, sq2],\n end,\n hom_inv_id' := by { ext; try { apply iso.hom_inv_id, }, apply is_iso.hom_inv_id },\n inv_hom_id' := by { ext; try { apply iso.inv_hom_id, }, apply is_iso.inv_hom_id } }\n\nend iso\n\nsection split\n\n/-- A short exact sequence `0 ⟶ A₁ -f⟶ A₂ -g⟶ A₃ ⟶ 0` is *left split*\nif there exists a morphism `φ : A₂ ⟶ A₁` such that `f ≫ φ = 𝟙 A₁`. -/\ndef left_split (A : short_exact_sequence 𝒞) : Prop :=\n∃ φ : A.2 ⟶ A.1, A.f ≫ φ = 𝟙 A.1\n\n/-- A short exact sequence `0 ⟶ A₁ -f⟶ A₂ -g⟶ A₃ ⟶ 0` is *right split*\nif there exists a morphism `φ : A₂ ⟶ A₁` such that `f ≫ φ = 𝟙 A₁`. -/\ndef right_split (A : short_exact_sequence 𝒞) : Prop :=\n∃ χ : A.3 ⟶ A.2, χ ≫ A.g = 𝟙 A.3\n\nvariables {𝒜 : Type*} [category 𝒜] [abelian 𝒜]\n\nlemma exact_of_split {A B C : 𝒜} (f : A ⟶ B) (g : B ⟶ C) (χ : C ⟶ B) (φ : B ⟶ A)\n (hfg : f ≫ g = 0) (H : φ ≫ f + g ≫ χ = 𝟙 B) : exact f g :=\n{ w := hfg,\n epi :=\n begin\n let ψ : (kernel_subobject g : 𝒜) ⟶ image_subobject f :=\n subobject.arrow _ ≫ φ ≫ factor_thru_image_subobject f,\n suffices : ψ ≫ image_to_kernel f g hfg = 𝟙 _,\n { convert epi_of_epi ψ _, rw this, apply_instance },\n rw ← cancel_mono (subobject.arrow _), swap, { apply_instance },\n simp only [image_to_kernel_arrow, image_subobject_arrow_comp, category.id_comp, category.assoc],\n calc (kernel_subobject g).arrow ≫ φ ≫ f\n = (kernel_subobject g).arrow ≫ 𝟙 B : _\n ... = (kernel_subobject g).arrow : category.comp_id _,\n rw [← H, preadditive.comp_add],\n simp only [add_zero, zero_comp, kernel_subobject_arrow_comp_assoc],\n end }\n\n-- move this\nlemma exact_inl_snd (A B : 𝒜) : exact (biprod.inl : A ⟶ A ⊞ B) biprod.snd :=\nexact_of_split _ _ biprod.inr biprod.fst biprod.inl_snd biprod.total\n\ndef mk_of_split {A B C : 𝒜} (f : A ⟶ B) (g : B ⟶ C) (φ : B ⟶ A) (χ : C ⟶ B)\n (hfg : f ≫ g = 0) (hφ : f ≫ φ = 𝟙 A) (hχ : χ ≫ g = 𝟙 C) (H : φ ≫ f + g ≫ χ = 𝟙 B) :\n short_exact_sequence 𝒜 :=\n{ fst := A,\n snd := B,\n trd := C,\n f := f,\n g := g,\n mono' := by { haveI : mono (f ≫ φ), { rw hφ, apply_instance }, exact mono_of_mono f φ, },\n epi' := by { haveI : epi (χ ≫ g), { rw hχ, apply_instance }, exact epi_of_epi χ g, },\n exact' := exact_of_split f g χ φ hfg H }\n\ndef mk_of_split' {A B C : 𝒜} (f : A ⟶ B) (g : B ⟶ C)\n (H : ∃ (φ : B ⟶ A) (χ : C ⟶ B), f ≫ g = 0 ∧ f ≫ φ = 𝟙 A ∧ χ ≫ g = 𝟙 C ∧ φ ≫ f + g ≫ χ = 𝟙 B) :\n short_exact_sequence 𝒜 :=\nmk_of_split f g H.some H.some_spec.some H.some_spec.some_spec.1 H.some_spec.some_spec.2.1\n H.some_spec.some_spec.2.2.1 H.some_spec.some_spec.2.2.2\n\n@[simp] def mk_split (A B : 𝒜) : short_exact_sequence 𝒜 :=\n{ fst := A,\n snd := A ⊞ B,\n trd := B,\n f := biprod.inl,\n g := biprod.snd,\n exact' := exact_inl_snd _ _ }\n\n/-- A *splitting* of a short exact sequence `0 ⟶ A₁ -f⟶ A₂ -g⟶ A₃ ⟶ 0` is\nan isomorphism to the short exact sequence `0 ⟶ A₁ ⟶ A₁ ⊕ A₃ ⟶ A₃ ⟶ 0`,\nwhere the left and right components of the isomorphism are identity maps. -/\nstructure splitting (A : short_exact_sequence 𝒜) extends A ≅ (mk_split A.1 A.3) :=\n(fst_eq_id : hom.1 = 𝟙 A.1)\n(trd_eq_id : hom.3 = 𝟙 A.3)\n\n/-- A short exact sequence `0 ⟶ A₁ -f⟶ A₂ -g⟶ A₃ ⟶ 0` is *split* if there exist\n`φ : A₂ ⟶ A₁` and `χ : A₃ ⟶ A₂` such that:\n* `f ≫ φ = 𝟙 A₁`\n* `χ ≫ g = 𝟙 A₃`\n* `χ ≫ φ = 0`\n* `φ ≫ f + g ≫ χ = 𝟙 A₂`\n-/\ndef split (A : short_exact_sequence 𝒜) : Prop :=\n∃ (φ : A.2 ⟶ A.1) (χ : A.3 ⟶ A.2),\n A.f ≫ φ = 𝟙 A.1 ∧ χ ≫ A.g = 𝟙 A.3 ∧ χ ≫ φ = 0 ∧ φ ≫ A.f + A.g ≫ χ = 𝟙 A.2\n\nlemma mk_split_split (A B : 𝒜) : (mk_split A B).split :=\n⟨biprod.fst, biprod.inr, biprod.inl_fst, biprod.inr_snd, biprod.inr_fst, biprod.total⟩\n\nlemma splitting.split {A : short_exact_sequence 𝒜} (i : splitting A) : A.split :=\nbegin\n refine ⟨i.hom.2 ≫ biprod.fst ≫ i.inv.1, i.hom.3 ≫ biprod.inr ≫ i.inv.2, _⟩,\n simp only [category.assoc, ← hom.sq1_assoc, hom.sq2], dsimp,\n simp only [biprod.inl_fst_assoc, biprod.inr_snd_assoc, category.comp_id, category.assoc,\n ← comp_fst, ← comp_snd_assoc, ← comp_trd, i.to_iso.hom_inv_id, i.to_iso.inv_hom_id],\n dsimp,\n simp only [true_and, biprod.inr_fst_assoc, zero_comp, eq_self_iff_true, comp_zero,\n category.id_comp],\n simp only [hom.sq1, ← hom.sq2_assoc, ← comp_add],\n simp only [← category.assoc, ← add_comp, biprod.total,\n category.comp_id, ← comp_snd, i.to_iso.hom_inv_id], refl,\nend\n\ndef left_split.splitting {A : short_exact_sequence 𝒜} (h : A.left_split) : A.splitting :=\n{ to_iso := iso_of_components' (iso.refl _) (biprod.lift h.some A.g) (iso.refl _)\n (by { dsimp, simp only [category.id_comp], ext,\n { simpa only [biprod.inl_fst, biprod.lift_fst, category.assoc] using h.some_spec.symm, },\n { simp only [exact.w, f_comp_g, biprod.lift_snd, category.assoc, exact_inl_snd] } })\n (by { dsimp, simp only [category.comp_id, biprod.lift_snd], }),\n fst_eq_id := rfl,\n trd_eq_id := rfl }\n\ndef right_split.splitting {A : short_exact_sequence 𝒜} (h : A.right_split) : A.splitting :=\n{ to_iso := iso.symm $ iso_of_components' (iso.refl _) (biprod.desc A.f h.some) (iso.refl _)\n (by { dsimp, simp only [biprod.inl_desc, category.id_comp], })\n (by { dsimp, simp only [category.comp_id], ext,\n { simp only [exact.w, f_comp_g, biprod.inl_desc_assoc, exact_inl_snd] },\n { simpa only [biprod.inr_snd, biprod.inr_desc_assoc] using h.some_spec, } }),\n fst_eq_id := rfl,\n trd_eq_id := rfl }\n\nlemma tfae_split (A : short_exact_sequence 𝒜) :\n tfae [A.left_split, A.right_split, A.split, nonempty A.splitting] :=\nbegin\n tfae_have : 3 → 1, { rintro ⟨φ, χ, hφ, hχ, hχφ, H⟩, exact ⟨φ, hφ⟩ },\n tfae_have : 3 → 2, { rintro ⟨φ, χ, hφ, hχ, hχφ, H⟩, exact ⟨χ, hχ⟩ },\n tfae_have : 4 → 3, { rintro ⟨i⟩, exact i.split, },\n tfae_have : 1 → 4, { intro h, exact ⟨h.splitting⟩ },\n tfae_have : 2 → 4, { intro h, exact ⟨h.splitting⟩ },\n tfae_finish\nend\n\nend split\n\nend short_exact_sequence\n\nnamespace short_exact_sequence\n\nopen category_theory.preadditive\n\nvariables {𝒞} [preadditive 𝒞] [has_images 𝒞] [has_kernels 𝒞]\nvariables (A B : short_exact_sequence 𝒞)\n\nlocal notation `π₁` := congr_arg _root_.prod.fst\nlocal notation `π₂` := congr_arg _root_.prod.snd\n\nprotected def hom_inj (f : A ⟶ B) : (A.1 ⟶ B.1) × (A.2 ⟶ B.2) × (A.3 ⟶ B.3) := ⟨f.1, f.2, f.3⟩\n\nprotected lemma hom_inj_injective : function.injective (short_exact_sequence.hom_inj A B) :=\nλ f g h, let aux := π₂ h in\nby { ext; [have := π₁ h, have := π₁ aux, have := π₂ aux]; exact this, }\n\ninstance : has_add (A ⟶ B) :=\n{ add := λ f g,\n { fst := f.1 + g.1,\n snd := f.2 + g.2,\n trd := f.3 + g.3,\n sq1' := by { rw [add_comp, comp_add, f.sq1, g.sq1], },\n sq2' := by { rw [add_comp, comp_add, f.sq2, g.sq2], } } }\n\ninstance : has_neg (A ⟶ B) :=\n{ neg := λ f,\n { fst := -f.1,\n snd := -f.2,\n trd := -f.3,\n sq1' := by { rw [neg_comp, comp_neg, f.sq1], },\n sq2' := by { rw [neg_comp, comp_neg, f.sq2], } } }\n\ninstance : has_sub (A ⟶ B) :=\n{ sub := λ f g,\n { fst := f.1 - g.1,\n snd := f.2 - g.2,\n trd := f.3 - g.3,\n sq1' := by { rw [sub_comp, comp_sub, f.sq1, g.sq1], },\n sq2' := by { rw [sub_comp, comp_sub, f.sq2, g.sq2], } } }\n\ninstance has_nsmul : has_smul ℕ (A ⟶ B) :=\n{ smul := λ n f,\n { fst := n • f.1,\n snd := n • f.2,\n trd := n • f.3,\n sq1' := by rw [nsmul_comp, comp_nsmul, f.sq1],\n sq2' := by rw [nsmul_comp, comp_nsmul, f.sq2] } }\n\ninstance has_zsmul : has_smul ℤ (A ⟶ B) :=\n{ smul := λ n f,\n { fst := n • f.1,\n snd := n • f.2,\n trd := n • f.3,\n sq1' := by rw [zsmul_comp, comp_zsmul, f.sq1],\n sq2' := by rw [zsmul_comp, comp_zsmul, f.sq2] } }\n\nvariables (𝒞)\n\ninstance : preadditive (short_exact_sequence 𝒞) :=\n{ hom_group := λ A B, (short_exact_sequence.hom_inj_injective A B).add_comm_group _\n rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl),\n add_comp' := by { intros, ext; apply add_comp },\n comp_add' := by { intros, ext; apply comp_add }, }\n.\n\ninstance Fst_additive : (Fst 𝒞).additive := {}\ninstance Snd_additive : (Snd 𝒞).additive := {}\ninstance Trd_additive : (Trd 𝒞).additive := {}\n\nend short_exact_sequence\n\nend category_theory", "meta": {"author": "jjaassoonn", "repo": "flat", "sha": "bab2f5c18fdee0042680c31b0350c69d241e9a82", "save_path": "github-repos/lean/jjaassoonn-flat", "path": "github-repos/lean/jjaassoonn-flat/flat-bab2f5c18fdee0042680c31b0350c69d241e9a82/src/lte/for_mathlib/short_exact_sequence.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47657966593214324, "lm_q2_score": 0.031618766926451256, "lm_q1q2_score": 0.01506886137899444}} {"text": "import Mathlib.Tactic.Basic\nimport Mathlib.Tactic.Linarith\nimport Mathlib.Tactic.Ring\nimport Mathlib.Tactic.LibrarySearch\nimport Mathlib.Tactic.Cases\nimport Mathlib.Data.Quot\nimport Std.Data.Int.Basic\nimport SSA.Experiment.SSA2TreeNoProof\nimport SSA.Experiment.SSARgn2TreeNoProof\nimport SSA.Experiment.SSARgnVar2TreeNoProof\nimport SSA.Experiment.MLIRFlat\n\nopen Std\n\n#check RBMap\nnamespace AST\n\n/-\nKinds of values. We must have 'pair' to take multiple arguments.\nTODO: Does it make sense to make this a typeclass?\n-/\ninductive Kind where\n| int : Kind\n| nat : Kind\n| float : Kind\n| pair : Kind -> Kind -> Kind\n| unit: Kind\nderiving Inhabited, DecidableEq, BEq\n\ninstance : ToString Kind where\n toString k :=\n let rec go : Kind →String\n | .nat => \"nat\"\n | .int => \"int\"\n | .float => \"float\"\n | .unit => \"unit\"\n | .pair p q => s!\"({go p}, {go q})\"\n go k\n\n-- A binding of 'name' with kind 'Kind'\nstructure Var where\n name : String\n kind : Kind\nderiving Inhabited, DecidableEq, BEq\n\ninstance : ToString Var where\n toString x := \"%\" ++ x.name ++ \":\" ++ toString x.kind\n\nabbrev Var.unit : Var := { name := \"_\", kind := .unit }\n\n-- compile time constant values.\ninductive Const where\n| int: Int → Const\n| float: Float → Const\n| unit: Const\n| pair: Const → Const → Const\nderiving BEq\n\ninstance : ToString Const where\n toString :=\n let rec go : Const → String\n | .int i => toString i\n | .float f => toString f\n | .unit => \"()\"\n | .pair p q => s!\"({go p}, {go q})\"\n go\n\n-- Tag for variants of Op/Region hybrid\ninductive OR: Type\n| O -- Single Op\n| Os -- Multiple Ops\n| R -- Single Region\n| Rs -- Multiple Regions\n\ninductive OpName where\n| arith.constant\n| arith.add\n| arith.sub\n| arith.mul\n| scf.if\n| scf.for\n| scf.twice\n| scf.run\n| unknown\nderiving DecidableEq\n\ninstance : ToString OpName where\n toString\n | .arith.constant => \"arith.constant\"\n | .arith.add => \"arith.add\"\n | .arith.sub => \"arith.sub\"\n | .arith.mul => \"arith.mul\"\n | .scf.if => \"scf.if\"\n | .scf.for => \"scf.for\"\n | .scf.twice => \"scf.twice\"\n | .scf.run => \"scf.run\"\n | .unknown => \"\"\n\n@[simp]\ndef OpName.fromString : String -> OpName\n | \"arith.constant\" => OpName.arith.constant\n | \"arith.add\" => OpName.arith.add\n | \"arith.sub\" => OpName.arith.sub\n | \"arith.mul\" => OpName.arith.mul\n | \"scf.if\" => OpName.scf.if\n | \"scf.for\" => OpName.scf.for\n | \"scf.twice\" => OpName.scf.twice\n | \"scf.run\" => OpName.scf.run\n | _ => OpName.unknown\n\n-- Tagged expressiontrees\ninductive Expr: OR -> Type where\n| opsone: Expr .O -> Expr .Os -- terminator in a sequence of Ops\n| opscons: Expr .O -> Expr .Os -> Expr .Os -- cons cell 'op :: ops'\n| regionsnil : Expr .Rs -- empty sequence of regions\n| regionscons: Expr .R -> Expr .Rs -> Expr .Rs -- cons cell 'region :: regions'\n| op (ret : Var)\n (name : OpName)\n (arg : Var)\n (regions : Expr .Rs)\n (const: Const): Expr .O -- '%ret:retty = 'name'(%var:varty) [regions*] {const}'\n| tuple (ret: String) (a1 a2: Var): Expr .O -- %out = tuple (%v1, %v2)\n| region (arg : Var) (ops : Expr .Os): Expr .R -- '{ ^entry(arg:argty) ops* }'\n\nabbrev Op := Expr .O\nabbrev Region := Expr .R\nabbrev Regions := Expr .Rs\nabbrev Ops := Expr .Os\n\nabbrev Op.mk (ret: Var := Var.unit)\n (name: OpName)\n (arg: Var := Var.unit)\n (regions := Expr.regionsnil)\n (const := Const.unit): Op := Expr.op ret name arg regions const\n-- Append an 'Op' to the end of the 'Ops' list.\ndef Ops.snoc: Ops → Op → Ops\n| .opsone o, o' => .opscons o (.opsone o')\n| .opscons o os, o' => .opscons o (Ops.snoc os o')\n\n@[simp]\ndef Op.ret : Op → Var\n| .op ret _ _ _ _ => ret\n| .tuple retname arg1 arg2 =>\n { name := retname,\n kind := .pair arg1.kind arg2.kind : Var}\n\n\ndef Regions.isEmpty: Regions → Bool\n| .regionsnil => True\n| .regionscons _ _ => False\n\n\ndef Expr.format : Expr k → Format\n| .opsone o => o.format\n| .opscons o os => o.format ++ .line ++ os.format\n| .regionsnil => Format.nil\n| .regionscons r rs => r.format ++ .line ++ rs.format\n| .op ret name arg rs const =>\n let constfmt : Format :=\n if const == .unit then \"\"\n else \"{\" ++ toString const ++ \"}\"\n let argfmt : Format :=\n if arg == Var.unit then \"\"\n else \"(\" ++ toString arg ++ \")\"\n let rsfmt : Format :=\n if Regions.isEmpty rs then \"\"\n else (Format.nest 1 <| \"[\" ++ .line ++ Expr.format rs) ++ \"]\"\n .text (toString ret ++ \" = \" ++ toString name) ++\n argfmt ++ rsfmt ++ constfmt\n| .tuple ret a1 a2 =>\n .text <|\n \"%\" ++ toString ret ++ \" = \" ++\n \"(\" ++ toString a1 ++ \", \" ++ toString a2 ++ \")\"\n| .region arg ops =>\n let argfmt : Format :=\n if arg == Var.unit then \"\" else \"^(\" ++ toString arg ++ \")\"\n \"{\" ++ argfmt ++\n Format.nest 2 (.line ++ ops.format) ++ .line ++ \"}\"\ninstance ⦃k: OR⦄: ToFormat (Expr k) where\n format := Expr.format\n\ninstance : ToString (Expr k) where\n toString := Format.pretty ∘ format\n\n\n\n-- Lean type that corresponds to kind.\n@[reducible, simp]\ndef Kind.eval: Kind -> Type\n| .int => Int\n| .nat => Nat\n| .unit => Unit\n| .float => Float\n| .pair p q => p.eval × q.eval\n\ninstance Kind.bEqEval: (k : Kind) → BEq k.eval\n| .int => inferInstanceAs (BEq Int)\n| .nat => inferInstanceAs (BEq Nat)\n| .unit => inferInstanceAs (BEq Unit)\n| .float => inferInstanceAs (BEq Float)\n| .pair p q => by\n letI : BEq p.eval := Kind.bEqEval _\n letI : BEq q.eval := Kind.bEqEval _\n infer_instance\n\ndef Kind.default (k: Kind): k.eval :=\n match k with\n | .int => 0\n | .nat => 0\n | .unit => ()\n | .float => 0.0\n | .pair p q => (p.default, q.default)\n\ninstance KindDefault (k: Kind) : Inhabited (k.eval) where\n default := Kind.default _\n\n\nend AST\n\nsection Semantics\nopen AST\n\n-- A kind and a value of that kind.\nstructure Val where\n kind: Kind\n val: kind.eval\n\ninstance : BEq Val where\n beq a b :=\n let rec go a b :=\n match a, b with\n | {kind := .int, val := a}, {kind := .int, val := b} => a == b\n | {kind := .float, val := a}, {kind := .float, val := b} => a == b\n | {kind := .unit, val := a}, {kind := .unit, val := b} => a == b\n | {kind := .pair p q, val := ⟨a, a'⟩}, {kind := .pair r s, val := ⟨b, b'⟩ } =>\n go ⟨p, a⟩ ⟨r, b⟩ && go ⟨q, a'⟩ ⟨s, b'⟩\n | _, _ => False\n go a b\n\ndef Val.unit : Val := { kind := Kind.unit, val := () }\n\ndef Val.toString (v: Val): String :=\n match v with\n | {kind := .nat, val := val } =>\n let S : ToString Nat := inferInstance\n S.toString val\n | {kind := .int, val := val } =>\n let S : ToString Int := inferInstance\n S.toString val\n | {kind := .float, val := val } =>\n let S : ToString Float := inferInstance\n S.toString val\n | {kind := .unit, val := () } => \"()\"\n | {kind := .pair p q, val := (x, y) } =>\n let xstr := Val.toString ({ kind := p, val := x})\n let ystr := Val.toString { kind := q, val := y}\n s!\"({xstr}, {ystr})\"\n\ninstance : ToString Val where\n toString := Val.toString\n\n-- The retun value of an SSA operation, with a name, kind, and value of that kind.\nstructure NamedVal extends Val where\n name : String\nderiving BEq\n\ndef NamedVal.toString (nv: NamedVal): String :=\n s!\"{nv.name} := {Val.toString nv.toVal}\"\n\n\ninstance : ToString NamedVal where\n toString := NamedVal.toString\n\n-- Given a 'Var' of kind 'kind', and a value of type 〚kind⟧, build a 'Val'\n@[simp]\ndef AST.Var.toNamedVal (var: Var) (value: var.kind.eval): NamedVal :=\n { kind := var.kind, val := value, name := var.name }\n\n@[simp]\ndef NamedVal.var (nv: NamedVal): Var :=\n { name := nv.name, kind := nv.kind }\n\n-- Well typed environments; cons cells of\n-- bindings of variables to values of type ⟦var.kind⟧\nabbrev Env := (v: Var) → v.kind.eval\n\n\ninstance : Inhabited ((k: Kind) → Kind.eval k) where\n default :=\n let rec go := fun k =>\n match k with\n | .unit => ()\n | .pair p q => (go p, go q)\n | .float => 0\n | .int => 0\n | .nat => 0\n go\n\ndef Env.empty := fun (v : Var) =>\n let f : (k: Kind) → Kind.eval k := default\n f v.kind\n\n-- truncation of a type that smashes everything into a single equivalence class.\ninductive trunc (α: Type): α → α → Prop\n| trunc: trunc α a a' -- smash everthing.\n\ninstance EquivalenceTrunc : Equivalence (trunc α) where\n refl _ := .trunc\n symm _ := .trunc\n trans _ _ := .trunc\n\ninstance SetoidTrunc (α : Type) : Setoid α where\n r := trunc α\n iseqv := EquivalenceTrunc\n\n/-\nThe type of Error is computationally 'String', but logically just a point.\nthis allows us to ignore error states in proofs [they are all identified as equal],\nwhile still allowing computationally relevant errors.\n-/\nabbrev ErrorKind : Type := Trunc String\n\n/-\nCursed: We cast from 'ErrorKind' which is a quotient of 'String' into 'String'\nsince we know that these have the same RuntimeRep.\n-/\nunsafe def ErrorKind.toStringImpl (e: ErrorKind): String := unsafeCast e\n@[implemented_by ErrorKind.toStringImpl]\npartial def ErrorKind.toString (_: ErrorKind): String := \"<>\"\ninstance : ToString ErrorKind where\n toString := ErrorKind.toString\n\nabbrev ErrorKind.mk (s: String) : ErrorKind := Trunc.mk s\n\n-- Coerce from regular strings into errors.\ninstance : Coe String ErrorKind where\n coe := ErrorKind.mk\n\n@[simp]\ndef ErrorKind.subsingleton (e: ErrorKind) (e': ErrorKind): e = e' := by {\n apply Quotient.ind;\n intros a;\n apply Eq.symm;\n apply Quotient.ind;\n intros b;\n apply Quotient.sound;\n constructor;\n}\n\n\n-- Env → Except ErrorKind α\nabbrev TopM (α : Type) : Type := ReaderT Env Id α\n\nabbrev Env.set (var: Var) (val: var.kind.eval): Env → Env\n| env => fun v => if H : v = var then H ▸ val else env v\n\n-- We need to produce values of type '()' for eg. ops with zero agruments.\n-- Here, we ensure that Env.get for a var of type 'Unit' will always succeed and return '()',\n-- becuse there is not need not to. This allows us to use 'Unit' to signal zero arguments,\n-- wthout have to make up a fake name for a variable of type 'Unit'\nabbrev Env.get (var: Var) (e: Env): var.kind.eval := e var\n\nabbrev ReaderT.get [Monad m]: ReaderT ρ m ρ := fun x => pure x\nabbrev ReaderT.withEnv [Monad m] (f: ρ → ρ) (reader: ReaderT ρ m α): ReaderT ρ m α :=\n reader ∘ f\n\ndef TopM.get (var: Var): TopM var.kind.eval := ReaderT.get >>= (fun _ => (Env.get var))\n\n-- the unit type will always successfully return '()'\ntheorem TopM.get_unit (name: String) (env: Env): TopM.get ⟨name, .unit⟩ env = () := by {\n simp[get, ReaderT.get, bind, ReaderT.bind, Except.bind, pure, Except.pure];\n}\n\ntheorem TopM_get (name: String) (kind: Kind) (k: kind.eval → TopM β):\n (TopM.get ⟨name, kind⟩) >>= k = fun env => (k (env ⟨name, kind⟩)) env := rfl\n\ndef TopM.set (nv: NamedVal) (k: TopM α): TopM α :=\n ReaderT.withEnv (Env.set nv.var nv.val) k\n\ndef Val.cast (val: Val) (t: Kind): t.eval :=\n if H : val.kind = t\n then .(H ▸ val.val)\n else default\n-- Runtime values of arguments to an Op, This is the argument value,\n-- the evaluated regions, and the constant.\nstructure Op' where\n argval : Val := ⟨.unit, ()⟩\n regions: List (Val → TopM Val) := []\n const: Const := .unit\n retkind: Kind\n\n-- The single semantic unit, where the user provides the semantics\n-- of a single op of a given 'name'.\nstructure Semantic where\n name: OpName\n run: (o : Op') → TopM o.retkind.eval\n\n\n-- TODO: consider this design.\n-- partial finitely supported function.\n-- abbrev Semantics := (name: String) → Option (Semantic name)\n\nabbrev Semantics := OpName → (o: Op') → TopM o.retkind.eval\n\ninstance : ToString Op' where\n toString x := \"(\" ++ toString x.argval ++ \")\" ++\n \" [\" ++ \"#\" ++ toString x.regions.length ++ \"]\" ++\n \" {\" ++ toString x.const ++ \"}\" ++ \" → \" ++ toString x.retkind\n\n@[reducible]\ndef AST.OR.denoteType: OR -> Type\n| .O => TopM NamedVal\n| .Os => TopM NamedVal\n| .R => Val → TopM Val\n| .Rs => List (Val → TopM Val) -- TODO: is 'List' here correct?\n\n\ndef AST.Expr.denote {kind: OR}\n (sem: Semantics): Expr kind → kind.denoteType\n| .opsone o => AST.Expr.denote (kind := .O) sem o\n| .opscons o os => do\n let retv ← AST.Expr.denote (kind := .O) sem o\n TopM.set retv (os.denote sem)\n| .regionsnil => []\n| .regionscons r rs => r.denote sem :: (rs.denote sem)\n| .tuple ret arg1 arg2 => do\n let val1 ←TopM.get arg1\n let val2 ← TopM.get arg2\n return { name := ret,\n kind := .pair arg1.kind arg2.kind,\n val := (val1, val2)\n } -- build a pair\n| .op ret name arg rs const => do\n let val ← TopM.get arg\n let op' : Op' :=\n { argval := ⟨arg.kind, val⟩\n , regions := rs.denote sem\n , const := const\n , retkind := ret.kind }\n let out ← sem name op'\n return ret.toNamedVal out\n| .region arg ops => fun val => do\n -- TODO: improve dependent typing here\n let val' := val.cast arg.kind\n TopM.set (arg.toNamedVal val') (NamedVal.toVal <$> (ops.denote sem))\n\n\n-- Write this separately for defEq purposes.\ndef Op'.fromOp (sem: Semantics)\n (ret: Var) (arg: Var) (argval: arg.kind.eval) (rs: Regions) (const: Const) : Op' :=\n { argval := ⟨arg.kind, argval⟩\n , regions := rs.denote sem\n , const := const\n , retkind := ret.kind\n }\n\n\ndef runRegion (sem : Semantics) (expr: AST.Expr .R)\n(env : Env := fun e => default)\n(arg : Val := Val.unit) : Val :=\n (expr.denote sem arg).run env\n\n\ntheorem TopM_idempotent: ∀ (ma: TopM α) (k: α → α → TopM β),\n ma >>= (fun a => ma >>= (fun a' => k a a')) =\n ma >>= (fun a => k a a) := by {\n intros ma k;\n funext env;\n simp[ReaderT.bind];\n simp[bind];\n simp[ReaderT.bind];\n}\n\ntheorem TopM_commutative: ∀ (ma: TopM α) (mb: TopM β) (k: α → β → TopM γ),\n ma >>= (fun a => mb >>= (fun b => k a b)) =\n mb >>= (fun b => ma >>= (fun a => k a b)) := by {\n intros ma mb k;\n funext env;\n simp[ReaderT.bind];\n simp[bind];\n simp[ReaderT.bind];\n}\n\n-- unfold Expr.denote for opscons\ntheorem Expr.denote_opscons:\n (Expr.opscons o os).denote sem =\n (o.denote sem >>= fun retv => TopM.set retv (os.denote sem)) := by { rfl; }\n\n-- unfold Expr.denote for opsone\ntheorem Expr.denote_opsone:\n (Expr.opsone o).denote sem = o.denote sem := by { rfl; }\n\n\ntheorem Expr.denote_tuple:\n (Expr.tuple ret arg1 arg2).denote sem =\n do\n let val1 ←TopM.get arg1\n let val2 ← TopM.get arg2\n return { name := ret,\n kind := .pair arg1.kind arg2.kind,\n val := (val1, val2)\n } := by rfl\n\n-- unfold Expr.denote for op\ntheorem Expr.denote_op:\n (Op.mk ret name arg rs const ).denote sem =\n TopM.get arg >>= fun val =>\n let op' : Op' := -- TODO: use Op'.fromOp\n { argval := ⟨arg.kind, val⟩\n , regions := rs.denote sem\n , const := const\n , retkind := ret.kind }\n sem name op' >>= fun out => fun env => ret.toNamedVal out\n := by { rfl; }\n\n-- how to simply Expr.denote_op, assuming the environment lookup is correct.\ntheorem Expr.denote_op_success (ret: Var) (name: OpName) (arg: Var) (rs: Regions) (const: Const)\n (sem: Semantics)\n (env: Env)\n (argval: arg.kind.eval)\n (ARGVAL: env.get arg = argval)\n (outval : ret.kind.eval)\n (SEM: sem name (Op'.fromOp sem ret arg argval rs const) env = outval) :\n (Op.mk ret name arg rs const).denote sem env = (ret.toNamedVal outval)\n := by {\n rw[Expr.denote_op];\n simp[Op'.fromOp] at SEM;\n simp[Op'.fromOp, TopM.get, ReaderT.get, pure, bind, ReaderT.bind, Except.pure, Except.bind, ARGVAL, SEM];\n aesop\n }\n\n\n-- 'opscons o os' @ env is the same as 'os @ (env[o.ret = o.val])'.\n-- That is, if 'o' succeeds, the 'os' proceeds evaluation with 'env' which\n-- has been updated for 'o.ret' with 'o.val'.\ntheorem Expr.denote_opscons_success_op (o: Op) (outval: (Op.ret o).kind.eval)\n (sem : Semantics) (env: Env)\n (OVAL: o.denote sem env = (o.ret.toNamedVal outval)) :\n (Expr.opscons o os).denote sem env = os.denote sem (env.set o.ret outval) := by {\n rw[Expr.denote_opscons];\n simp[bind, ReaderT.bind, OVAL, Except.bind, TopM.set];\n sorry\n}\n\n\n-- If tuple succeeds, then:\n-- 1. The arguments exists in 'env'.\n-- 2. The value in 'env' is that of the tuple arguments, tupled up.\ntheorem Expr.denote_tuple_inv\n (SUCCESS: Expr.denote sem (Expr.tuple retname arg1 arg2) env = outval) :\n ∃ argval1, env.get arg1 = argval1 ∧\n ∃ argval2, env.get arg2 = argval2 ∧\n outval = { name := retname, kind := .pair arg1.kind arg2.kind, val := ⟨argval1, argval2 ⟩} := by {\n simp[Expr.denote, bind, ReaderT.bind, Except.bind] at SUCCESS;\n\n simp[TopM.get, bind, ReaderT.bind, Except.bind, ReaderT.get, pure, Except.pure] at SUCCESS ⊢;\n simp[pure, ReaderT.pure, Except.pure] at SUCCESS ⊢ ;\n aesop;\n}\n\n\n-- If op succeeds, then:\n-- 1. the arguments exists in 'env'.\n-- 2. 'sem' succeeded\n-- 3. The value returned by 'Expr.denote' is the boxed value in 'sem'.\ntheorem Expr.denote_op_assign_inv\n (SUCCESS: Expr.denote sem (Expr.op ret name arg regions const) env = outval) :\n ∃ argval, env.get arg = argval ∧\n ∃ (outval_val : ret.kind.eval),\n (sem name (Op'.fromOp sem ret arg argval regions const) env = pure outval_val /\\\n outval = ret.toNamedVal outval_val) := by {\n -- rw[Expr.denote_op] at SUCCESS; -- TODO: find out why 'rw' does not work here.\n\n simp[Expr.denote, bind, ReaderT.bind, Except.bind] at SUCCESS;\n simp[TopM.get, bind, ReaderT.bind, Except.bind] at SUCCESS ⊢;\n simp[ReaderT.get, pure, Except.pure] at SUCCESS ⊢;\n simp[SUCCESS];\n simp[pure, Except.pure];\n simp[pure, Except.pure, ReaderT.pure] at SUCCESS;\n simp[SUCCESS];\n aesop\n}\n\n-- What we can say about a op in general.\ntheorem Expr.denote_regionsnil: Expr.regionsnil.denote sem = [] := rfl\n\ntheorem Expr.denote_regionscons:\n Expr.denote sem (.regionscons r rs) = r.denote sem :: rs.denote sem := rfl\n\n\n\nend Semantics\n\nnamespace DSL\nopen AST\n\ndeclare_syntax_cat dsl_op\ndeclare_syntax_cat dsl_type\ndeclare_syntax_cat dsl_ops\ndeclare_syntax_cat dsl_region\ndeclare_syntax_cat dsl_var\ndeclare_syntax_cat dsl_var_name\ndeclare_syntax_cat dsl_const\ndeclare_syntax_cat dsl_kind\n\nsyntax sepBy1(ident, \"×\") :dsl_kind\nsyntax ident : dsl_var_name\nsyntax \"%\" dsl_var_name \":\" dsl_kind : dsl_var\nsyntax dsl_var \"=\"\n str\n (\"(\"dsl_var \")\")?\n (\"[\" dsl_region,* \"]\")?\n (\"{\" dsl_const \"}\")? \";\": dsl_op\nsyntax \"%\" dsl_var_name \"=\" \"tuple\" \"(\" dsl_var \",\" dsl_var \")\" \";\": dsl_op\nsyntax num : dsl_const\nsyntax \"{\" (\"^(\" dsl_var \")\" \":\")? dsl_op dsl_op* \"}\" : dsl_region\nsyntax \"[dsl_op|\" dsl_op \"]\" : term\nsyntax \"[dsl_ops|\" dsl_op dsl_op* \"]\" : term\nsyntax \"[dsl_region|\" dsl_region \"]\" : term\nsyntax \"[dsl_var|\" dsl_var \"]\" : term\nsyntax \"[dsl_kind|\" dsl_kind \"]\" : term\nsyntax \"[dsl_const|\" dsl_const \"]\" : term\nsyntax \"[dsl_var_name|\" dsl_var_name \"]\" : term\n\n\n@[simp]\ndef AST.Ops.fromList: Op → List Op → Ops\n| op, [] => .opsone op\n| op, op'::ops => .opscons op (AST.Ops.fromList op' ops)\n\n@[simp]\ndef AST.Regions.fromList: List Region → Regions\n| [] => .regionsnil\n| r :: rs => .regionscons r (AST.Regions.fromList rs)\n\nopen Lean Macro in\ndef parseKind (k: TSyntax `ident) : MacroM (TSyntax `term) :=\n match k.getId.toString with\n | \"int\" => `(AST.Kind.int)\n | \"nat\" => `(AST.Kind.nat)\n | unk => (Macro.throwErrorAt k s!\"unknown kind '{unk}'\")\n\n\nopen Lean Macro in\nmacro_rules\n| `([dsl_kind| $[ $ks ]×* ]) => do\n if ks.isEmpty\n then `(AST.Kind.unit)\n else\n let mut out ← parseKind ks[ks.size - 1]!\n for k in ks.pop.reverse do\n let cur ← parseKind k\n out ← `(AST.Kind.pair $cur $out)\n return out\n| `([dsl_kind| $$($q:term)]) => `(($q : Kind))\n\nopen Lean Macro in\nmacro_rules\n| `([dsl_var_name| $name:ident ]) =>\n return (Lean.quote name.getId.toString : TSyntax `term)\n| `([dsl_var_name| $$($q:term)]) => `(($q : String))\n\nmacro_rules\n| `([dsl_var| %$name:dsl_var_name : $kind:dsl_kind]) => do\n `({ name := [dsl_var_name| $name],\n kind := [dsl_kind| $kind] : Var})\n| `([dsl_var| $$($q:term)]) => `(($q : Var))\n\nmacro_rules\n| `([dsl_ops| $op $ops*]) => do\n let op_term ← `([dsl_op| $op])\n let ops_term ← ops.mapM (fun op => `([dsl_op| $op ]))\n `(AST.Ops.fromList $op_term [ $ops_term,* ])\n\nmacro_rules\n| `([dsl_ops| $$($q)]) => `(($q : Ops))\n\nmacro_rules\n| `([dsl_region| { $[ ^( $arg:dsl_var ): ]? $op $ops* } ]) => do\n let ops ← `([dsl_ops| $op $ops*])\n match arg with\n | .none => `(Expr.region Var.unit $ops)\n | .some arg => do\n let arg_term ← `([dsl_var| $arg ])\n `(Expr.region $arg_term $ops)\n| `([dsl_region| $$($q)]) => `(($q : Region))\n\nmacro_rules\n| `([dsl_const| $x:num ]) => `(Const.int $x)\n| `([dsl_const| $$($q)]) => `(($q : Const))\n\nopen Lean Syntax in\nmacro_rules\n| `([dsl_op| $res:dsl_var = $name:str\n $[ ( $arg:dsl_var ) ]?\n $[ [ $rgns,* ] ]?\n $[ { $const } ]?\n ;\n ]) => do\n let res_term ← `([dsl_var| $res])\n let arg_term ← match arg with\n | .some arg => `([dsl_var| $arg])\n | .none => `(AST.Var.unit)\n let name_term := name\n let rgns_term ← match rgns with\n | .none => `(.regionsnil)\n | .some rgns =>\n let rgns ← rgns.getElems.mapM (fun stx => `([dsl_region| $stx]))\n `(AST.Regions.fromList [ $rgns,* ])\n let const_term ←\n match const with\n | .none => `(Const.unit)\n | .some c => `([dsl_const| $c])\n `(Expr.op $res_term (OpName.fromString ($name_term : String)) $arg_term $rgns_term $const_term)\n| `([dsl_op| $$($q)]) => `(($q : Op))\n\nmacro_rules\n| `([dsl_op| %$res:dsl_var_name = tuple ( $arg1:dsl_var , $arg2:dsl_var) ; ]) => do\n let res_term ← `([dsl_var_name| $res])\n let arg1_term ← `([dsl_var| $arg1 ])\n let arg2_term ← `([dsl_var| $arg2 ])\n `(Expr.tuple $res_term $arg1_term $arg2_term)\n\ndef eg_kind_int := [dsl_kind| int]\n#reduce eg_kind_int\n\ndef eg_kind_int_times_nat := [dsl_kind| int × nat]\n#reduce eg_kind_int_times_nat\n\ndef eg_kind_int_times_nat_times_nat := [dsl_kind| int × nat × nat]\n#reduce eg_kind_int_times_nat_times_nat\n\n\n\ndef eg_var : AST.Var := [dsl_var| %y : int]\n#reduce eg_var\n\ndef eg_var_2 : AST.Var := [dsl_var| %$(\"y\") : int ]\n#reduce eg_var_2\n\ndef eg_var_3 : AST.Var :=\n let name := \"name\"; let ty := Kind.int; [dsl_var| %$(name) : $(ty) ]\n#reduce eg_var_3\n\ndef eg_op : AST.Op :=\n let name := \"name\"; let ty := Kind.int;\n [dsl_op| %res : int = \"arith.sub\" ( %$(name) : $(ty) ); ]\n#reduce eg_var_3\n\nsection Unexpander\n\n/-\nSupport for pretty printing our AST.Expr to make writing proofs easier.\n-/\n/-\n@[app_unexpander Var.mk] def unexpandVar: Lean.PrettyPrinter.Unexpander\n| `($_ $nm $kind) => `($nm $kind)\n| _ => throw ()\n\n@[app_unexpander Val.mk] def unexpandVal: Lean.PrettyPrinter.Unexpander\n| `($_ $kind $val) => `($val $kind)\n| _ => throw ()\n\n@[app_unexpander Kind.pair] def unexpandKindPair: Lean.PrettyPrinter.Unexpander\n| `($_ $l $r) => `($l × $r)\n| _ => throw ()\n\n@[app_unexpander Expr.tuple] def unexpandExprTuple: Lean.PrettyPrinter.Unexpander\n| `($_ $ret $l $r) => `($ret = \"tuple\" ( $l , $r ))\n| _ => throw ()\n\nopen Lean Macro PrettyPrinter in\n@[app_unexpander Expr.op] def unexpandExprOp: Lean.PrettyPrinter.Unexpander\n| `($_ $ret $name $arg regionsnil $const) => `($ret = \"op\" $name ( $arg ) $const)\n-- | `($_ $ret $name $arg $regions Const.unit) => `($ret = \"op\" $name ( $arg ) $regions)\n| `($_ $ret $name $arg $regions $const) => `($ret = \"op\" $name ( $arg ) $regions $const)\n| _ => sorry\n\n@[app_unexpander Expr.opscons] def unexpandExprOpscons: Lean.PrettyPrinter.Unexpander\n| `($_ $o $os) => `($o / $os)\n| _ => throw ()\n\n@[app_unexpander Expr.opsone] def unexpandExprOpsone: Lean.PrettyPrinter.Unexpander\n| `($_ $o) => `($o)\n| _ => throw ()\n\n@[app_unexpander Expr.regionscons] def unexpandRegionsnil : Lean.PrettyPrinter.Unexpander\n| `($_ ) => `(())\n\n\n@[app_unexpander Expr.regionscons] def unexpandRegionsCons : Lean.PrettyPrinter.Unexpander\n| `($_ $r Expr.regionsnil) => `($r)\n| _ => throw ()\n\n@[app_unexpander Const.unit] def unexpandConstUnit : Lean.PrettyPrinter.Unexpander\n| `($_) => `(())\n\n@[app_unexpander Const.int] def unexpandConstInt : Lean.PrettyPrinter.Unexpander\n| `($_ $i:num) => `($i)\n| _ => throw ()\n-/\nend Unexpander\n\n\nend DSL\n\nnamespace Arith\n\ndef const : Semantic := {\n name := .arith.constant\n run := fun o => match o with\n | { const := .int x, retkind := .int} => return x\n | _ => default\n}\n\ndef add : Semantic := {\n name := .arith.add\n run := fun o => match o with\n | { retkind := .int,\n argval := ⟨.pair .int .int, (x, y)⟩ } => return x + y\n | _ => default\n}\n\ndef sub : Semantic := {\n name := .arith.sub\n run := fun o => match o with\n | { retkind := .int,\n argval := ⟨.pair .int .int, (x, y)⟩ } => return x - y\n | _ => default\n}\n\ndef sem: Semantics :=\n fun name =>\n match name with\n | .arith.constant => const.run\n | .arith.add => add.run\n | .arith.sub => sub.run\n | _ => default\n\ndef eg_region_sub :=\n [dsl_region| {\n %one : int = \"arith.constant\" {1};\n %two : int = \"arith.constant\" {2};\n %t = tuple(%one : int , %two : int);\n %x : int = \"arith.sub\"(%t : int × int);\n }]\n#reduce eg_region_sub\n\n\nend Arith\n\nnamespace Scf -- 'structured control flow'\n\ndef repeatM (n: Nat) (f: Val → TopM Val) : Val → TopM Val :=\n n.repeat (f >=> .) pure\n\n\ntheorem repeatM.peel_left: ∀ (n: Nat) (f: Val → TopM Val),\n repeatM (n+1) f = f >=> repeatM n f := by {\n intros n f;\n simp[repeatM, Nat.repeat];\n}\n-- This theorem is now useless\n-- theorem repeatM.peel_left: repeatM (n+1) f = f >=> repeatM n f := rfl\n\n-- kleisli arrow is associative.\ntheorem kleisliRight.assoc {m: Type → Type}\n [M: Monad m] [LM: LawfulMonad m]\n {α β γ δ: Type}\n (f: α → m β) (g: β → m γ) (h: γ → m δ) :\n (f >=> g) >=> h = f >=> (g >=> h) := by {\n funext x;\n simp[Bind.kleisliRight];\n}\n\n-- pure is left identity\n@[simp]\ntheorem kleisliRight.pure_id_left {m: Type → Type}\n [M: Monad m] [LM: LawfulMonad m]\n {α β: Type}\n (f: α → m β) :\n pure >=> f = f := by {\n funext x;\n simp[Bind.kleisliRight];\n}\n\n-- pure is left identity\n@[simp]\ntheorem kleisliRight.pure_id_right {m: Type → Type}\n [M: Monad m] [LM: LawfulMonad m]\n {α β: Type}\n (f: α → m β) :\n f >=> pure = f:= by {\n funext x;\n simp[Bind.kleisliRight];\n}\n\n-- The above shows that (>=>, pure) forms a category.\n\n@[simp] theorem repeatM.zero: repeatM 0 f = pure := rfl\n@[simp] theorem repeatM.one: repeatM 1 f = f := by simp [repeatM, Nat.repeat]\n@[simp] theorem repeatM.succ: repeatM (Nat.succ n) f = f >=> repeatM n f := rfl\n\n-- composing repeatM is the same as adding the repeat\n-- counter.\ntheorem repeatM.compose: (repeatM n f) >=> (repeatM m f) = repeatM (n+m) f := by\n revert m\n induction n <;> intros m <;> simp\n case succ n' IH =>\n simp [Nat.succ_add, kleisliRight.assoc, IH]\n\ntheorem repeatM.peel_right: repeatM (n+1) f = repeatM n f >=> f := by\n induction n <;> simp at *\n case succ _ IH => rw [kleisliRight.assoc, IH]\n\ntheorem repeatM.commute_f: repeatM n f >=> f = f >=> repeatM n f := by\n simp [←peel_right]\n\n-- pull a function that commutes with f to the left of repeatM\n@[simp] -- pull simple stuff to the left.\ntheorem repeatM.commuting_pull_left\n {f g: Val → TopM Val} (COMMUTES: f >=> g = g >=> f) :\n (repeatM n f) >=> g = g >=> repeatM n f := by\n induction n <;> simp\n case succ n' IH =>\n simp [kleisliRight.assoc, IH]\n simp [←kleisliRight.assoc, COMMUTES]\n\ntheorem repeatM.commuting_pull_right\n {f g: Val → TopM Val} (COMMUTES: f >=> g = g >=> f) :\n g >=> repeatM n f = repeatM n f >=> g := (commuting_pull_left COMMUTES).symm\n\n-- TODO: decision procedure for free theory of\n-- commuting functions?\ntheorem repeatM.commuting_commute\n {f g: Val → TopM Val} (COMMUTES: f >=> g = g >=> f) :\n repeatM n f >=> repeatM m g = repeatM m g >=> repeatM n f := by\n induction n <;> simp\n case succ n' IH =>\n rw [kleisliRight.assoc, IH]\n simp [←kleisliRight.assoc]\n rw [commuting_pull_left COMMUTES.symm]\n\n-- to show (f >=> k) = (f >=> h), it suffices to show that k = h\ntheorem kleisli.cancel_left [M: Monad m] (f: α → m β) (k h : β → m γ) (H: k = h) :\n f >=> k = f >=> h := by {\n rw[H];\n}\n\ntheorem repeatM.commuting_compose\n {f g: Val → TopM Val} (COMMUTES: f >=> g = g >=> f) :\n (repeatM n f) >=> repeatM n g = repeatM n (f >=> g) := by\n induction n <;> simp\n case succ n' IH =>\n rw [←kleisliRight.assoc _ g _, kleisliRight.assoc _ _ g]\n rw [commuting_pull_left COMMUTES]\n rw [←kleisliRight.assoc f g _, kleisliRight.assoc (f >=> g) _ _, IH]\n\n\ndef if_ : Semantic := {\n name := .scf.if\n run := fun o => match o with\n | { argval := ⟨.int, cond⟩,\n regions := [rthen, relse],\n retkind := .int -- hack: we assume that we always return ints.\n } => do\n let rrun := if cond ≠ 0 then rthen else relse\n let v ← rrun Val.unit\n return v.cast .int\n | _ => default\n}\n\ndef twice : Semantic := {\n name := .scf.twice\n run := fun o => match o with\n | { regions := [r],\n retkind := .int\n } => do\n let v ← r Val.unit\n let w ← r Val.unit -- run a region twice, check that it is same as running once.\n return w.cast .int\n | _ => default\n}\n\ndef run : Semantic := {\n name := .scf.run\n run := fun o => match o with\n | { regions := [r],\n retkind := .int\n } => do\n let v ← r Val.unit\n return v.cast .int\n | _ => default\n}\n\ndef for_ : Semantic := {\n name := .scf.for\n run := fun o => match o with\n | { regions := [r],\n retkind := .int,\n argval := ⟨.pair .nat .int, ⟨niters, init⟩⟩\n } =>\n repeatM niters r ⟨.int, init⟩ >=> Val.cast (t := .int)\n | _ => default\n}\n\ndef sem : Semantics :=\n fun name =>\n match name with\n | .scf.if => if_.run\n | .scf.twice => twice.run\n | .scf.for => for_.run\n | _ => default\n\nend Scf\n\nnamespace Examples\nopen AST\ndef eg_arith_shadow : Region := [dsl_region| {\n %x : int = \"arith.constant\"{0};\n %x : int = \"arith.constant\"{1};\n %x : int = \"arith.constant\"{2};\n %x : int = \"arith.constant\"{3};\n %x : int = \"arith.constant\"{4};\n}]\n\ndef eg_scf_ite_true : Region := [dsl_region| {\n %cond : int = \"arith.constant\"{1};\n %out : int = \"scf.if\" (%cond : int) [{\n %out_then : int = \"arith.constant\"{42};\n }, {\n %out_else : int = \"arith.constant\"{0};\n }];\n}]\n\n\n\n-- f: Unit → a ∼ a\ndef eg_scf_ite_false : Region := [dsl_region| {\n %cond : int = \"arith.constant\"{0};\n %out : int = \"scf.if\" (%cond : int) [{\n %out_then : int = \"arith.constant\"{42};\n }, {\n %out_else : int = \"arith.constant\"{0};\n }];\n}]\n\n#print eg_scf_ite_false\n\ndef eg_scf_run_twice : Region := [dsl_region| {\n %x : int = \"arith.constant\"{41};\n %x : int = \"scf.twice\" [{\n %one : int = \"arith.constant\"{1};\n %xone = tuple(%x : int, %one : int);\n %x : int = \"arith.add\"(%xone : int × int);\n }];\n}]\n\ndef eg_scf_well_scoped : Region := [dsl_region| {\n %x : int = \"arith.constant\"{41};\n %one : int = \"arith.constant\"{1}; -- one is outside.\n %x : int = \"scf.twice\" [{\n %xone = tuple(%x : int, %one : int); -- one is accessed here.\n %x : int = \"arith.add\"(%xone : int × int);\n }];\n}]\n\ndef eg_scf_ill_scoped : Region := [dsl_region| {\n %x : int = \"arith.constant\"{41};\n %x : int = \"scf.twice\" [{\n %y : int = \"arith.constant\"{42};\n }];\n -- %y should NOT be accessible here\n %out = tuple(%y : int, %y : int);\n}]\n\ndef eg_scf_for: Region := [dsl_region| {\n %x : int = \"arith.constant\"{10}; -- 10 iterations\n %init : int = \"arith.constant\"{32}; -- start value\n %xinit = tuple(%x : int, %init : int);\n %out : int = \"scf.for\"(%xinit : int × int)[{\n ^(%xcur : int):\n %one : int = \"arith.constant\"{1};\n %xcur_one = tuple(%xcur : int, %one : int);\n %xnext : int = \"arith.add\"(%xcur_one : int × int);\n }];\n}]\n\n\n\nend Examples\n\nnamespace Rewriting\nopen AST\n\n/- Replace the final Op with the new seqence of Ops -/\ndef Ops.replaceOne (os: Ops) (new: Ops) : Ops :=\n match os with\n | .opsone o => new\n | .opscons o os => .opscons o (Ops.replaceOne os new)\n\nstructure Peephole where\n -- findbegin: TypingCtx -- free variables.\n find : Ops -- stuff in the pattern. The last op is to be replaced.\n replace : Ops -- replacement ops. can use 'findbegin'.\n sem: Semantics\n -- TODO: Once again, we need to reason 'upto error'.\n replaceCorrect: ∀ (env: Env),\n find.denote sem env = replace.denote sem env\n\n -- (FIND: find.denote sem env = origval),\n -- (replace.denote sem) env = origval\nend Rewriting\n\nnamespace RewritingHoare\nopen AST\nopen Rewriting\n/-\nA theory of rewriting, plus helper lemmas phrased along a hoare logic.\n-/\n-- https://softwarefoundations.cis.upenn.edu/plf-current/Hoare.html\ndef assertion (t: Type) : Type := t → Prop\ndef assertion.implies (P Q: assertion T) : Prop := ∀ (e: T), P e → Q e\n\n\nnotation P:80 \"->>\" Q:80 => assertion.implies P Q\n\nabbrev assertion.iff (P Q: assertion T) : Prop := P ->> Q ∧ Q ->> P\nnotation P:80 \"<<->>\" Q:80 => assertion.iff P Q\n\ndef assertion.and (P Q: assertion T) : assertion T := fun (v: T) => P v ∧ Q v\nnotation P:80 \"h∧\" Q:80 => assertion.and P Q -- how does this work?\n\ndef assertion.prop (p: Prop): assertion T := fun (_v: T) => p\n\ndef assertion.mapsto (v: Var) (val: v.kind.eval): assertion Env :=\n fun (e: Env) => e.get v = val\n\ndef assertion.maps (v: Var): assertion Env :=\n fun (e: Env) => ∃ (val: v.kind.eval), (e.get v) = val\n\nnotation \"h[\" v:80 \"↦\" val:80 \"]\" => assertion.mapsto v val\nnotation \"hprop(\" p:80 \")\" => assertion.prop p\nnotation \"h[\" v:80 \"↦\" \"?\" \"]\" => assertion.maps v\n-- def hoare_triple_region (P: assertion Env) (r: Expr .R) (Q: assertion (Except ErrorKind NamedVal)) : Prop :=\n-- ∀ (e: Env) (sem : (o : Op') → TopM o.retkind.eval) (v: Val), P e -> Q (r.denote sem v e)\n\n\n\n-- more conceptual proof, still does not use full hoare logic machinery, only a fragment.\nsection SubXXHoare\n-- x - x ~= 0\n\ntheorem Int.sub_n_n (n: Int) : n - n = 0 := by {\n linarith\n}\n\n\ndef sub_x_x_equals_zero (res: String) (arg: String) (pairname: String) : Peephole := {\n find := [dsl_ops|\n % $(pairname) = tuple( %$(arg) : int, %$(arg) : int);\n % $(res) : int = \"arith.sub\" ( %$(pairname) : int × int);\n ]\n replace := [dsl_ops|\n % $(res) : int = \"arith.constant\" {0};\n ]\n sem := Arith.sem,\n replaceCorrect := fun env => by {\n simp[Expr.denote, TopM.get, TopM.set, ReaderT.get, bind, Env.get, ReaderT.bind, pure, ReaderT.pure, Semantic.run,\n Arith.sem, Arith.sub, Arith.const, Env.set] at *;\n }\n }\n\n\nend SubXXHoare\n\n\nsection ForFusionHoare\n-- peel loop iterations out.\n\n\n-- e with x as subexpr\n-- (fun v => e' v) x = e\ndef pure_rewrite [M: Monad m] [LM: LawfulMonad m]\n (ma: m α)\n (maval: α)\n (MAVAL: ma = pure maval)\n (compute: α -> m β) :\n compute maval = ma >>= compute := by {\n simp[MAVAL];\n}\n\ndef for_fusion (r: Region) (n m : String)\n (n_plus_m n_m: String)\n (out1 out2: String)\n (n_init m_out1: String)\n (init n_plus_m_init: String) : Peephole := {\n find := [dsl_ops|\n % $(n_init) = tuple( %$(n) : nat, %$(init) : int);\n % $(out1) : int = \"scf.for\" ( %$(n_init) : nat × int) [$(r)];\n % $(m_out1) = tuple( %$(m) : nat, %$(out1) : int);\n % $(out2) : int = \"scf.for\" ( %$(m_out1) : nat × int) [$(r)];\n ]\n replace := [dsl_ops|\n % $(n_m) = tuple( %$(n) : nat, %$(m) : nat);\n % $(n_plus_m) : nat = \"arith.add\" ( %$(n_m) : nat × nat);\n % $(n_plus_m_init) = tuple( %$(n_plus_m) : nat, %$(init) : int);\n % $(out2) : int = \"scf.for\" ( %$(n_plus_m_init) : nat × int) [$(r)];\n ]\n sem :=\n fun name =>\n match name with\n | .arith.add => Arith.add.run\n | .scf.for => Scf.for_.run\n | _ => fun op env => return default\n\n replaceCorrect := fun env1 => by {\n simp;\n generalize SEM:((fun name =>\n match (motive := OpName → (o : Op') → TopM (Kind.eval o.retkind)) name with\n | OpName.arith.add => Arith.add.run\n | OpName.scf.for => Scf.for_.run\n | x => fun op env => default)) = sem;\n\n\n\n simp only[Expr.denote_opscons, Expr.denote_tuple, TopM_get];\n simp[TopM_get];\n simp[TopM_get];\n -- simp does not simplify 'TopM_get' again.\n sorry\n -- rw[Expr.denote_opscons];\n -- rw[Expr.denote_tuple];\n -- simp[Expr.denote];\n -- sorry\n\n -- simp[TopM.get, ReaderT.get, Env.get, bind, ReaderT.bind, TopM.set, pure, ReaderT.pure, Scf.for_, Env.set, Expr.denote];\n -- simp[Expr.denote, TopM.get, TopM.set, ReaderT.get, bind, Env.get, ReaderT.bind, pure, ReaderT.pure, Semantic.run];\n }\n}\nend ForFusionHoare\n\n\nend RewritingHoare\n\n\nnamespace Theorems\n\nend Theorems\n\nnamespace Test\ndef runRegionTest\n (sem: Semantics)\n (r: AST.Region)\n (expected: Val)\n (arg: Val := Val.unit )\n (env: Env := Env.empty) : IO Bool := do\n IO.println r\n let v : Val := (r.denote sem arg).run env\n if v == expected\n then\n IO.println s!\"{v}. OK\"; return True\n else\n IO.println s!\"ERROR: computed '{v}', expected '{expected}'.\"\n return False\n\n-- there is no notion of failure.\n-- def runRegionTestXfail :\n-- (sem: Semantics) →\n-- (r: AST.Region) →\n-- (arg: Val := Val.unit ) →\n-- (env: Env := Env.empty) → IO Bool :=\n-- fun sem r arg env => do\n-- IO.println r\n-- let v : Val := (r.denote sem arg).run env\n-- match v? with\n-- | .ok v =>\n-- IO.println s!\"ERROR: expected failure, but succeeded with '{v}'.\";\n-- return False\n-- | .error e =>\n-- IO.println s!\"OK: Succesfully xfailed '{e}'.\"\n-- return True\n\nend Test\n\n\nopen Arith Scf in\ndef arith_plus_scf.sem : Semantics := fun name =>\n match name with\n | .arith.constant => const.run\n | .arith.add => add.run\n | .arith.sub => sub.run\n | .scf.if => if_.run\n | .scf.for => for_.run\n | .scf.twice => twice.run\n | .scf.run => run.run\n | _ => default\n\nopen Arith Scf DSL Examples Test in\ndef main : IO UInt32 := do\n let tests :=\n [runRegionTest\n (sem := Arith.sem)\n (r := eg_region_sub)\n (expected := { kind := .int, val := -1}),\n runRegionTest\n (sem := Arith.sem)\n (r := eg_arith_shadow)\n (expected := { kind := .int, val := 4}),\n runRegionTest\n (sem := arith_plus_scf.sem)\n (r := eg_scf_ite_true)\n (expected := { kind := .int, val := 42}),\n runRegionTest\n (sem := arith_plus_scf.sem)\n (r := eg_scf_ite_false)\n (expected := { kind := .int, val := 0}),\n runRegionTest\n (sem := arith_plus_scf.sem)\n (r := eg_scf_run_twice)\n (expected := { kind := .int, val := 42}),\n runRegionTest\n (sem := arith_plus_scf.sem)\n (r := eg_scf_well_scoped)\n (expected := { kind := .int, val := 42}),\n runRegionTest\n (sem := arith_plus_scf.sem)\n (r := eg_scf_for)\n (expected := { kind := .int, val := 42})]\n let mut total := 0\n let mut correct := 0\n for t in tests do\n total := total + 1\n IO.println s!\"---Test {total}---\"\n let pass? ← t\n if pass? then correct := correct + 1\n IO.println \"---\"\n IO.println s!\"Tests: {correct} successful/{total}\"\n return (if correct == total then 0 else 1)\n", "meta": {"author": "bollu", "repo": "ssa", "sha": "19c73e48500bfe3f618c360423966677adb4673e", "save_path": "github-repos/lean/bollu-ssa", "path": "github-repos/lean/bollu-ssa/ssa-19c73e48500bfe3f618c360423966677adb4673e/SSA.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41489884579676883, "lm_q2_score": 0.03622005911605094, "lm_q1q2_score": 0.01502766072194027}} {"text": "import category_theory.preadditive\nimport category_theory.abelian.projective\nimport category_theory.abelian.diagram_lemmas.four\n\nimport data.matrix.notation\n\nimport for_mathlib.abelian_category\nimport for_mathlib.fin_functor\nimport for_mathlib.split_exact\n\nnoncomputable theory\n\nopen category_theory\nopen category_theory.limits\nopen category_theory.preadditive\n\nuniverses v u\n\nnamespace category_theory\nvariables (𝒞 : Type u) [category.{v} 𝒞]\n\n@[ext]\nstructure short_exact_sequence [has_images 𝒞] [has_zero_morphisms 𝒞] [has_kernels 𝒞] :=\n(fst snd trd : 𝒞)\n(f : fst ⟶ snd)\n(g : snd ⟶ trd)\n[mono' : mono f]\n[epi' : epi g]\n(exact' : exact f g)\n\nnamespace short_exact_sequence\n\nattribute [instance] mono' epi'\n\nvariables {𝒞} [has_images 𝒞] [has_zero_morphisms 𝒞] [has_kernels 𝒞]\n\n@[simp, reassoc] lemma f_comp_g (A : short_exact_sequence 𝒞) : A.f ≫ A.g = 0 := A.exact'.w\n\n@[ext]\nstructure hom (A B : short_exact_sequence 𝒞) :=\n(fst : A.1 ⟶ B.1)\n(snd : A.2 ⟶ B.2)\n(trd : A.3 ⟶ B.3)\n(sq1' : fst ≫ B.f = A.f ≫ snd . obviously)\n(sq2' : snd ≫ B.g = A.g ≫ trd . obviously)\n\nnamespace hom\n\nrestate_axiom sq1' sq1\nrestate_axiom sq2' sq2\n\nattribute [reassoc] sq1 sq2\n\nend hom\n\ninstance : quiver (short_exact_sequence 𝒞) := ⟨hom⟩\n\ndef id (A : short_exact_sequence 𝒞) : A ⟶ A :=\n{ fst := 𝟙 _,\n snd := 𝟙 _,\n trd := 𝟙 _,\n sq1' := by simp only [category.id_comp, category.comp_id],\n sq2' := by simp only [category.id_comp, category.comp_id], }\n\ndef comp {A B C : short_exact_sequence 𝒞} (f : A ⟶ B) (g : B ⟶ C) : A ⟶ C :=\n{ fst := f.1 ≫ g.1,\n snd := f.2 ≫ g.2,\n trd := f.3 ≫ g.3,\n sq1' := by rw [category.assoc, hom.sq1, hom.sq1_assoc],\n sq2' := by rw [category.assoc, hom.sq2, hom.sq2_assoc], }\n\ninstance : category (short_exact_sequence 𝒞) :=\n{ id := id,\n comp := λ A B C f g, comp f g,\n id_comp' := by { intros, ext; dsimp; apply category.id_comp, },\n comp_id' := by { intros, ext; dsimp; apply category.comp_id, },\n assoc' := by { intros, ext; dsimp; apply category.assoc, },\n .. (infer_instance : quiver (short_exact_sequence 𝒞)) }\n\n@[simp] lemma id_fst (A : short_exact_sequence 𝒞) : hom.fst (𝟙 A) = 𝟙 A.1 := rfl\n@[simp] lemma id_snd (A : short_exact_sequence 𝒞) : hom.snd (𝟙 A) = 𝟙 A.2 := rfl\n@[simp] lemma id_trd (A : short_exact_sequence 𝒞) : hom.trd (𝟙 A) = 𝟙 A.3 := rfl\n\nvariables {A B C : short_exact_sequence 𝒞} (f : A ⟶ B) (g : B ⟶ C)\n\n@[simp, reassoc] lemma comp_fst : (f ≫ g).1 = f.1 ≫ g.1 := rfl\n@[simp, reassoc] lemma comp_snd : (f ≫ g).2 = f.2 ≫ g.2 := rfl\n@[simp, reassoc] lemma comp_trd : (f ≫ g).3 = f.3 ≫ g.3 := rfl\n\nvariables (𝒞)\n\n@[simps] def Fst : short_exact_sequence 𝒞 ⥤ 𝒞 :=\n{ obj := fst, map := λ A B f, f.1 }\n\n@[simps] def Snd : short_exact_sequence 𝒞 ⥤ 𝒞 :=\n{ obj := snd, map := λ A B f, f.2 }\n\n@[simps] def Trd : short_exact_sequence 𝒞 ⥤ 𝒞 :=\n{ obj := trd, map := λ A B f, f.3 }\n\n@[simps] def f_nat : Fst 𝒞 ⟶ Snd 𝒞 :=\n{ app := λ A, A.f,\n naturality' := λ A B f, f.sq1 }\n\n@[simps] def g_nat : Snd 𝒞 ⟶ Trd 𝒞 :=\n{ app := λ A, A.g,\n naturality' := λ A B f, f.sq2 }\n\ninstance : has_zero_morphisms (short_exact_sequence 𝒞) :=\n{ has_zero := λ A B, ⟨{ fst := 0, snd := 0, trd := 0 }⟩,\n comp_zero' := by { intros, ext; apply comp_zero },\n zero_comp' := by { intros, ext; apply zero_comp }, }\n.\n\n@[simp] lemma hom_zero_fst : (0 : A ⟶ B).1 = 0 := rfl\n\n@[simp] lemma hom_zero_snd : (0 : A ⟶ B).2 = 0 := rfl\n\n@[simp] lemma hom_zero_trd : (0 : A ⟶ B).3 = 0 := rfl\n\nvariables {𝒞}\n\nprotected def functor (A : short_exact_sequence 𝒞) : fin 3 ⥤ 𝒞 :=\nfin3_functor_mk ![A.1, A.2, A.3] A.f A.g\n\ndef functor_map {A B : short_exact_sequence 𝒞} (f : A ⟶ B) :\n Π i, A.functor.obj i ⟶ B.functor.obj i\n| ⟨0,h⟩ := f.1\n| ⟨1,h⟩ := f.2\n| ⟨2,h⟩ := f.3\n| ⟨i+3,hi⟩ := by { exfalso, revert hi, dec_trivial }\n\nmeta def aux_tac : tactic unit :=\n`[simp only [hom_of_le_refl, functor.map_id, category.id_comp, category.comp_id]]\n\nlemma functor_map_naturality {A B : short_exact_sequence 𝒞} (f : A ⟶ B) :\n ∀ (i j : fin 3) (hij : i ≤ j),\n functor_map f i ≫ B.functor.map hij.hom = A.functor.map hij.hom ≫ functor_map f j\n| ⟨0,hi⟩ ⟨0,hj⟩ hij := by aux_tac\n| ⟨1,hi⟩ ⟨1,hj⟩ hij := by aux_tac\n| ⟨2,hi⟩ ⟨2,hj⟩ hij := by aux_tac\n| ⟨0,hi⟩ ⟨1,hj⟩ hij := f.sq1\n| ⟨1,hi⟩ ⟨2,hj⟩ hij := f.sq2\n| ⟨i+3,hi⟩ _ _ := by { exfalso, revert hi, dec_trivial }\n| _ ⟨j+3,hj⟩ _ := by { exfalso, revert hj, dec_trivial }\n| ⟨i+1,hi⟩ ⟨0,hj⟩ H := by { exfalso, revert H, dec_trivial }\n| ⟨i+2,hi⟩ ⟨1,hj⟩ H := by { exfalso, revert H, dec_trivial }\n| ⟨0,hi⟩ ⟨2,hj⟩ hij :=\nbegin\n have h01 : (0 : fin 3) ⟶ 1 := hom_of_le dec_trivial,\n have h12 : (1 : fin 3) ⟶ 2 := hom_of_le dec_trivial,\n calc functor_map f ⟨0, hi⟩ ≫ B.functor.map hij.hom\n = functor_map f ⟨0, hi⟩ ≫ B.functor.map h01 ≫ B.functor.map h12 : _\n ... = (functor_map f ⟨0, hi⟩ ≫ B.functor.map h01) ≫ B.functor.map h12 : by rw category.assoc\n ... = (A.functor.map h01 ≫ functor_map f _) ≫ B.functor.map h12 : _\n ... = A.functor.map h01 ≫ functor_map f _ ≫ B.functor.map h12 : category.assoc _ _ _\n ... = A.functor.map h01 ≫ A.functor.map h12 ≫ functor_map f _ : _\n ... = A.functor.map hij.hom ≫ functor_map f ⟨2, hj⟩ : _,\n { rw [← functor.map_comp], congr, },\n { congr' 1, exact f.sq1 },\n { congr' 1, exact f.sq2 },\n { rw [← functor.map_comp_assoc], congr, },\nend\n\n@[simps] def Functor : short_exact_sequence 𝒞 ⥤ fin 3 ⥤ 𝒞 :=\n{ obj := short_exact_sequence.functor,\n map := λ A B f,\n { app := functor_map f,\n naturality' := λ i j hij, (functor_map_naturality f i j hij.le).symm },\n map_id' := λ A, by { ext i, fin_cases i; refl },\n map_comp' := λ A B C f g, by { ext i, fin_cases i; refl } }\n\nend short_exact_sequence\n\nnamespace short_exact_sequence\n\nvariables {𝒞} [abelian 𝒞]\nvariables {A B C : short_exact_sequence 𝒞} (f : A ⟶ B) (g : B ⟶ C)\n\nsection iso\n\nvariables {A B C} (f g)\n\nopen_locale zero_object\n\n/-- One form of the five lemma: if a morphism of short exact sequences has isomorphisms\nas first and third component, then the second component is also an isomorphism. -/\nlemma snd_is_iso (h1 : is_iso f.1) (h3 : is_iso f.3) : is_iso f.2 :=\n@abelian.is_iso_of_is_iso_of_is_iso_of_is_iso_of_is_iso 𝒞 _ _\n 0 A.1 A.2 A.3\n 0 B.1 B.2 B.3\n 0 A.f A.g\n 0 B.f B.g\n 0 f.1 f.2 f.3 (by rw [zero_comp, zero_comp]) f.sq1 f.sq2\n 0 0\n 0 0 0 (by rw [comp_zero, comp_zero])\n (exact_zero_left_of_mono _)\n A.exact'\n ((epi_iff_exact_zero_right _).mp infer_instance)\n (exact_zero_left_of_mono _)\n B.exact'\n ((epi_iff_exact_zero_right _).mp infer_instance) _ _ _ _\n\n/-- One form of the five lemma: if a morphism `f` of short exact sequences has isomorphisms\nas first and third component, then `f` itself is an isomorphism. -/\nlemma is_iso_of_fst_of_trd (h1 : is_iso f.1) (h3 : is_iso f.3) : is_iso f :=\n{ out :=\n begin\n haveI : is_iso f.2 := snd_is_iso f h1 h3,\n refine ⟨⟨inv f.1, inv f.2, inv f.3, _, _⟩, _, _⟩,\n { dsimp, simp only [is_iso.inv_comp_eq, f.sq1_assoc, category.comp_id, is_iso.hom_inv_id], },\n { dsimp, simp only [is_iso.inv_comp_eq, f.sq2_assoc, category.comp_id, is_iso.hom_inv_id], },\n { ext; dsimp; simp only [is_iso.hom_inv_id], },\n { ext; dsimp; simp only [is_iso.inv_hom_id], },\n end }\n\n@[simps] def iso_of_components (f₁ : A.1 ≅ B.1) (f₂ : A.2 ≅ B.2) (f₃ : A.3 ≅ B.3)\n (sq1 : f₁.hom ≫ B.f = A.f ≫ f₂.hom) (sq2 : f₂.hom ≫ B.g = A.g ≫ f₃.hom) :\n A ≅ B :=\n{ hom := ⟨f₁.hom, f₂.hom, f₃.hom, sq1, sq2⟩,\n inv :=\n begin\n refine ⟨f₁.inv, f₂.inv, f₃.inv, _, _⟩; dsimp,\n rw [iso.inv_comp_eq, ← category.assoc, iso.eq_comp_inv, sq1],\n rw [iso.inv_comp_eq, ← category.assoc, iso.eq_comp_inv, sq2],\n end,\n hom_inv_id' := by { ext; apply iso.hom_inv_id, },\n inv_hom_id' := by { ext; apply iso.inv_hom_id, } }\n\n@[simps] def iso_of_components' (f₁ : A.1 ≅ B.1) (f₂ : A.2 ⟶ B.2) (f₃ : A.3 ≅ B.3)\n (sq1 : f₁.hom ≫ B.f = A.f ≫ f₂) (sq2 : f₂ ≫ B.g = A.g ≫ f₃.hom) :\n A ≅ B :=\nlet F : A ⟶ B := ⟨f₁.hom, f₂, f₃.hom, sq1, sq2⟩ in\n{ hom := F,\n inv :=\n begin\n haveI : is_iso F.2 := snd_is_iso _ infer_instance infer_instance,\n refine ⟨f₁.inv, inv F.2, f₃.inv, _, _⟩; dsimp,\n rw [iso.inv_comp_eq, ← category.assoc, is_iso.eq_comp_inv, sq1],\n rw [is_iso.inv_comp_eq, ← category.assoc, iso.eq_comp_inv, sq2],\n end,\n hom_inv_id' := by { ext; try { apply iso.hom_inv_id, }, apply is_iso.hom_inv_id },\n inv_hom_id' := by { ext; try { apply iso.inv_hom_id, }, apply is_iso.inv_hom_id } }\n\nend iso\n\nsection split\n\n/-- A short exact sequence `0 ⟶ A₁ -f⟶ A₂ -g⟶ A₃ ⟶ 0` is *left split*\nif there exists a morphism `φ : A₂ ⟶ A₁` such that `f ≫ φ = 𝟙 A₁`. -/\ndef left_split (A : short_exact_sequence 𝒞) : Prop :=\n∃ φ : A.2 ⟶ A.1, A.f ≫ φ = 𝟙 A.1\n\n/-- A short exact sequence `0 ⟶ A₁ -f⟶ A₂ -g⟶ A₃ ⟶ 0` is *right split*\nif there exists a morphism `φ : A₂ ⟶ A₁` such that `f ≫ φ = 𝟙 A₁`. -/\ndef right_split (A : short_exact_sequence 𝒞) : Prop :=\n∃ χ : A.3 ⟶ A.2, χ ≫ A.g = 𝟙 A.3\n\nvariables {𝒜 : Type*} [category 𝒜] [abelian 𝒜]\n\nlemma exact_of_split {A B C : 𝒜} (f : A ⟶ B) (g : B ⟶ C) (χ : C ⟶ B) (φ : B ⟶ A)\n (hfg : f ≫ g = 0) (H : φ ≫ f + g ≫ χ = 𝟙 B) : exact f g :=\n{ w := hfg,\n epi :=\n begin\n let ψ : (kernel_subobject g : 𝒜) ⟶ image_subobject f :=\n subobject.arrow _ ≫ φ ≫ factor_thru_image_subobject f,\n suffices : ψ ≫ image_to_kernel f g hfg = 𝟙 _,\n { convert epi_of_epi ψ _, rw this, apply_instance },\n rw ← cancel_mono (subobject.arrow _), swap, { apply_instance },\n simp only [image_to_kernel_arrow, image_subobject_arrow_comp, category.id_comp, category.assoc],\n calc (kernel_subobject g).arrow ≫ φ ≫ f\n = (kernel_subobject g).arrow ≫ 𝟙 B : _\n ... = (kernel_subobject g).arrow : category.comp_id _,\n rw [← H, preadditive.comp_add],\n simp only [add_zero, zero_comp, kernel_subobject_arrow_comp_assoc],\n end }\n\n-- move this\nlemma exact_inl_snd (A B : 𝒜) : exact (biprod.inl : A ⟶ A ⊞ B) biprod.snd :=\nexact_of_split _ _ biprod.inr biprod.fst biprod.inl_snd biprod.total\n\ndef mk_of_split {A B C : 𝒜} (f : A ⟶ B) (g : B ⟶ C) (φ : B ⟶ A) (χ : C ⟶ B)\n (hfg : f ≫ g = 0) (hφ : f ≫ φ = 𝟙 A) (hχ : χ ≫ g = 𝟙 C) (H : φ ≫ f + g ≫ χ = 𝟙 B) :\n short_exact_sequence 𝒜 :=\n{ fst := A,\n snd := B,\n trd := C,\n f := f,\n g := g,\n mono' := by { haveI : mono (f ≫ φ), { rw hφ, apply_instance }, exact mono_of_mono f φ, },\n epi' := by { haveI : epi (χ ≫ g), { rw hχ, apply_instance }, exact epi_of_epi χ g, },\n exact' := exact_of_split f g χ φ hfg H }\n\ndef mk_of_split' {A B C : 𝒜} (f : A ⟶ B) (g : B ⟶ C)\n (H : ∃ (φ : B ⟶ A) (χ : C ⟶ B), f ≫ g = 0 ∧ f ≫ φ = 𝟙 A ∧ χ ≫ g = 𝟙 C ∧ φ ≫ f + g ≫ χ = 𝟙 B) :\n short_exact_sequence 𝒜 :=\nmk_of_split f g H.some H.some_spec.some H.some_spec.some_spec.1 H.some_spec.some_spec.2.1\n H.some_spec.some_spec.2.2.1 H.some_spec.some_spec.2.2.2\n\n@[simp] def mk_split (A B : 𝒜) : short_exact_sequence 𝒜 :=\n{ fst := A,\n snd := A ⊞ B,\n trd := B,\n f := biprod.inl,\n g := biprod.snd,\n exact' := exact_inl_snd _ _ }\n\n/-- A *splitting* of a short exact sequence `0 ⟶ A₁ -f⟶ A₂ -g⟶ A₃ ⟶ 0` is\nan isomorphism to the short exact sequence `0 ⟶ A₁ ⟶ A₁ ⊕ A₃ ⟶ A₃ ⟶ 0`,\nwhere the left and right components of the isomorphism are identity maps. -/\nstructure splitting (A : short_exact_sequence 𝒜) extends A ≅ (mk_split A.1 A.3) :=\n(fst_eq_id : hom.1 = 𝟙 A.1)\n(trd_eq_id : hom.3 = 𝟙 A.3)\n\n/-- A short exact sequence `0 ⟶ A₁ -f⟶ A₂ -g⟶ A₃ ⟶ 0` is *split* if there exist\n`φ : A₂ ⟶ A₁` and `χ : A₃ ⟶ A₂` such that:\n* `f ≫ φ = 𝟙 A₁`\n* `χ ≫ g = 𝟙 A₃`\n* `χ ≫ φ = 0`\n* `φ ≫ f + g ≫ χ = 𝟙 A₂`\n-/\ndef split (A : short_exact_sequence 𝒜) : Prop :=\n∃ (φ : A.2 ⟶ A.1) (χ : A.3 ⟶ A.2),\n A.f ≫ φ = 𝟙 A.1 ∧ χ ≫ A.g = 𝟙 A.3 ∧ χ ≫ φ = 0 ∧ φ ≫ A.f + A.g ≫ χ = 𝟙 A.2\n\nlemma mk_split_split (A B : 𝒜) : (mk_split A B).split :=\n⟨biprod.fst, biprod.inr, biprod.inl_fst, biprod.inr_snd, biprod.inr_fst, biprod.total⟩\n\nlemma splitting.split {A : short_exact_sequence 𝒜} (i : splitting A) : A.split :=\nbegin\n refine ⟨i.hom.2 ≫ biprod.fst ≫ i.inv.1, i.hom.3 ≫ biprod.inr ≫ i.inv.2, _⟩,\n simp only [category.assoc, ← hom.sq1_assoc, hom.sq2], dsimp,\n simp only [biprod.inl_fst_assoc, biprod.inr_snd_assoc, category.comp_id, category.assoc,\n ← comp_fst, ← comp_snd_assoc, ← comp_trd, i.to_iso.hom_inv_id, i.to_iso.inv_hom_id],\n dsimp,\n simp only [true_and, biprod.inr_fst_assoc, zero_comp, eq_self_iff_true, comp_zero,\n category.id_comp],\n simp only [hom.sq1, ← hom.sq2_assoc, ← comp_add],\n simp only [← category.assoc, ← add_comp, biprod.total,\n category.comp_id, ← comp_snd, i.to_iso.hom_inv_id], refl,\nend\n\ndef left_split.splitting {A : short_exact_sequence 𝒜} (h : A.left_split) : A.splitting :=\n{ to_iso := iso_of_components' (iso.refl _) (biprod.lift h.some A.g) (iso.refl _)\n (by { dsimp, simp only [category.id_comp], ext,\n { simpa only [biprod.inl_fst, biprod.lift_fst, category.assoc] using h.some_spec.symm, },\n { simp only [exact.w, f_comp_g, biprod.lift_snd, category.assoc, exact_inl_snd] } })\n (by { dsimp, simp only [category.comp_id, biprod.lift_snd], }),\n fst_eq_id := rfl,\n trd_eq_id := rfl }\n\ndef right_split.splitting {A : short_exact_sequence 𝒜} (h : A.right_split) : A.splitting :=\n{ to_iso := iso.symm $ iso_of_components' (iso.refl _) (biprod.desc A.f h.some) (iso.refl _)\n (by { dsimp, simp only [biprod.inl_desc, category.id_comp], })\n (by { dsimp, simp only [category.comp_id], ext,\n { simp only [exact.w, f_comp_g, biprod.inl_desc_assoc, exact_inl_snd] },\n { simpa only [biprod.inr_snd, biprod.inr_desc_assoc] using h.some_spec, } }),\n fst_eq_id := rfl,\n trd_eq_id := rfl }\n\nlemma tfae_split (A : short_exact_sequence 𝒜) :\n tfae [A.left_split, A.right_split, A.split, nonempty A.splitting] :=\nbegin\n tfae_have : 3 → 1, { rintro ⟨φ, χ, hφ, hχ, hχφ, H⟩, exact ⟨φ, hφ⟩ },\n tfae_have : 3 → 2, { rintro ⟨φ, χ, hφ, hχ, hχφ, H⟩, exact ⟨χ, hχ⟩ },\n tfae_have : 4 → 3, { rintro ⟨i⟩, exact i.split, },\n tfae_have : 1 → 4, { intro h, exact ⟨h.splitting⟩ },\n tfae_have : 2 → 4, { intro h, exact ⟨h.splitting⟩ },\n tfae_finish\nend\n\nend split\n\nend short_exact_sequence\n\nnamespace short_exact_sequence\n\nopen category_theory.preadditive\n\nvariables {𝒞} [preadditive 𝒞] [has_images 𝒞] [has_kernels 𝒞]\nvariables (A B : short_exact_sequence 𝒞)\n\nlocal notation `π₁` := congr_arg _root_.prod.fst\nlocal notation `π₂` := congr_arg _root_.prod.snd\n\nprotected def hom_inj (f : A ⟶ B) : (A.1 ⟶ B.1) × (A.2 ⟶ B.2) × (A.3 ⟶ B.3) := ⟨f.1, f.2, f.3⟩\n\nprotected lemma hom_inj_injective : function.injective (short_exact_sequence.hom_inj A B) :=\nλ f g h, let aux := π₂ h in\nby { ext; [have := π₁ h, have := π₁ aux, have := π₂ aux]; exact this, }\n\ninstance : has_add (A ⟶ B) :=\n{ add := λ f g,\n { fst := f.1 + g.1,\n snd := f.2 + g.2,\n trd := f.3 + g.3,\n sq1' := by { rw [add_comp, comp_add, f.sq1, g.sq1], },\n sq2' := by { rw [add_comp, comp_add, f.sq2, g.sq2], } } }\n\ninstance : has_neg (A ⟶ B) :=\n{ neg := λ f,\n { fst := -f.1,\n snd := -f.2,\n trd := -f.3,\n sq1' := by { rw [neg_comp, comp_neg, f.sq1], },\n sq2' := by { rw [neg_comp, comp_neg, f.sq2], } } }\n\ninstance : has_sub (A ⟶ B) :=\n{ sub := λ f g,\n { fst := f.1 - g.1,\n snd := f.2 - g.2,\n trd := f.3 - g.3,\n sq1' := by { rw [sub_comp, comp_sub, f.sq1, g.sq1], },\n sq2' := by { rw [sub_comp, comp_sub, f.sq2, g.sq2], } } }\n\ninstance has_nsmul : has_smul ℕ (A ⟶ B) :=\n{ smul := λ n f,\n { fst := n • f.1,\n snd := n • f.2,\n trd := n • f.3,\n sq1' := by rw [nsmul_comp, comp_nsmul, f.sq1],\n sq2' := by rw [nsmul_comp, comp_nsmul, f.sq2] } }\n\ninstance has_zsmul : has_smul ℤ (A ⟶ B) :=\n{ smul := λ n f,\n { fst := n • f.1,\n snd := n • f.2,\n trd := n • f.3,\n sq1' := by rw [zsmul_comp, comp_zsmul, f.sq1],\n sq2' := by rw [zsmul_comp, comp_zsmul, f.sq2] } }\n\nvariables (𝒞)\n\ninstance : preadditive (short_exact_sequence 𝒞) :=\n{ hom_group := λ A B, (short_exact_sequence.hom_inj_injective A B).add_comm_group _\n rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl),\n add_comp' := by { intros, ext; apply add_comp },\n comp_add' := by { intros, ext; apply comp_add }, }\n.\n\ninstance Fst_additive : (Fst 𝒞).additive := {}\ninstance Snd_additive : (Snd 𝒞).additive := {}\ninstance Trd_additive : (Trd 𝒞).additive := {}\n\nend short_exact_sequence\n\nend category_theory\n", "meta": {"author": "leanprover-community", "repo": "lean-liquid", "sha": "92f188bd17f34dbfefc92a83069577f708851aec", "save_path": "github-repos/lean/leanprover-community-lean-liquid", "path": "github-repos/lean/leanprover-community-lean-liquid/lean-liquid-92f188bd17f34dbfefc92a83069577f708851aec/src/for_mathlib/short_exact_sequence.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41489884579676883, "lm_q2_score": 0.03622005716540519, "lm_q1q2_score": 0.0150276599126196}} {"text": "import category_theory.isomorphism\nimport homotopy_theory.formal.cylinder.hep\n\nimport .category\nimport .colimits\nimport .cylinder\nimport .interval_endpoints\nimport .pair\nimport .pushout_lemmas\n\nopen set\n\nopen category_theory\nopen category_theory.category\nlocal notation f ` ∘ `:80 g:80 := g ≫ f\n\nopen homotopy_theory.cylinder\n\nnamespace homotopy_theory.topological_spaces\nopen homotopy_theory.topological_spaces.Top\nlocal notation `Top` := Top.{0}\n\n-- The classical definition of a cofibration between topological\n-- spaces as a map which satisfies the homotopy extension property.\ndef cofibration {A X : Top} (j : A ⟶ X) : Prop := hep 0 j\n\n/-\n\n* A cofibration in Top is an embedding. [Strøm, Note on cofibrations,\n Theorem 1.] Proof: Suppose j : A → X is a cofibration. Form the\n mapping cylinder Z as the pushout shown below, with induced map\n k : Z → IX.\n\n j\n A → X = X\n i₀↓ ↓ ↓i₀\n IA → Z → IX → Z\n i₁↑ ↑ ↑i₁\n A = A → X\n j\n\n By the homotopy extension property, we can find a map r from IX back\n to Z. So Z → X is the inclusion of a retract, hence in particular an\n embedding. The map i₀ : A → IA has closed image, so IA → Z is a\n homeomorphism onto its image away from the image of i₀. Thus the\n composition\n\n i₁\n A → IA → Z → IX\n\n is an embedding; but it equals i₁ ∘ j : A → IX, so j : A → X is an\n embedding as well.\n\n-/\n\nvariables {A X : Top} {j : A ⟶ X}\nlocal notation `i` := i.{0}\n\nlemma embedding_i {ε} : embedding (i ε @> A) :=\nembedding_of_embedding_comp (p @> A) embedding_id\n\nlemma closed_i {ε} : is_closed (set.range (i ε @> A)) :=\nhave is_closed {p : Top.prod A I01 | p.snd ∈ ({I01_of_endpoint ε} : set I01)}, from\n continuous_iff_is_closed.mp continuous_snd _ is_closed_singleton,\nbegin\n convert this, ext p, cases p with a t,\n change (∃ a', (a', _) = (a, t)) ↔ _,\n simpa using eq_comm\nend\n\nlemma disjoint_i₀_i₁ : set.range (i 0 @> A) ∩ set.range (i 1 @> A) = ∅ :=\nbegin\n apply set.eq_empty_of_subset_empty, intros p hp,\n cases p with a t, rcases hp with ⟨⟨_, hp₀⟩, ⟨_, hp₁⟩⟩,\n have hp₀' : 0 = t := congr_arg prod.snd hp₀,\n have hp₁' : 1 = t := congr_arg prod.snd hp₁,\n have : (0 : I01) = 1 := hp₀'.trans hp₁'.symm,\n exact absurd (congr_arg subtype.val this)\n (show ¬(0 : ℝ) = 1, by norm_num)\nend\n\nlemma embedding_of_cofibration (h : cofibration j) : embedding j :=\nlet po := has_pushouts.pushout (i 0 @> A) j,\n Z := po.ob,\n k : Z ⟶ I.obj X :=\n po.is_pushout.induced (I &> j) (i 0 @> X) ((i 0).naturality j).symm,\n ⟨r, hr₀, hr₁⟩ := h Z po.map₁ po.map₀ po.is_pushout.commutes.symm in\nhave _ := hr₀.symm,\nhave hr : r ∘ k = 𝟙 _, by apply po.is_pushout.uniqueness; { rw ←assoc, simpa },\nhave e_z_ix : embedding k, from\n embedding_of_embedding_comp r (by rw hr; exact embedding_id),\nhave e_a_z : embedding (po.map₀ ∘ i 1 @> A), from\n comp_embedding_of_embedding_of_disjoint\n po.is_pushout (or.inl closed_i) embedding_i disjoint_i₀_i₁,\nhave embedding (k ∘ (po.map₀ ∘ i 1 @> A)), from e_z_ix.comp e_a_z,\nhave embedding (i 1 @> X ∘ j), begin\n convert this using 2,\n transitivity,\n exact (i 1).naturality j,\n simp\nend,\nembedding_of_embedding_comp _ this\n\nlemma cofibration_iff_cofibered_of_embedding (e : embedding j) :\n cofibration j ↔ (pair.mk X (range j)).cofibered :=\nlet j' := Top.factor_through_incl j (range j) (subset.refl _) in\nshow hep 0 j ↔ hep 0 _, from\nmem_iff_mem_of_isomorphic\n (homeomorphism_to_image_of_embedding e)\n (iso.refl X)\n (by ext p; refl)\n\nlemma cofibration_iff_cofibered :\n cofibration j ↔ embedding j ∧ (pair.mk X (range j)).cofibered :=\niff.intro\n (assume h,\n have e : embedding j := embedding_of_cofibration h,\n ⟨e, (cofibration_iff_cofibered_of_embedding e).mp h⟩)\n (assume h, (cofibration_iff_cofibered_of_embedding h.1).mpr h.2)\n\nsection relative_cylinder\nnoncomputable theory\n\nvariables (j) (ha : is_closed (range j))\nvariable (hj : cofibration j)\n\nlemma relative_cylinder' : ∃ Po : pushout (∂I &> j) (ii @> A),\n cofibration (Po.is_pushout.induced (ii @> X) (I &> j) (ii.naturality _)) ∧\n is_closed (range (Po.is_pushout.induced (ii @> X) (I &> j) (ii.naturality _))) :=\nlet P : pair := pair.mk X (range j) in\nlet j_ : homeomorphism A P.subspace :=\n homeomorphism_to_image_of_embedding (embedding_of_cofibration hj) in\nlet po := pair.po P I_01 ha I_01.is_closed in\nlet po' := Is_pushout_of_isomorphic po.transpose (∂I &> j) (ii @> A)\n ((∂I.map_iso j_).trans prod_doubleton) prod_doubleton (I.map_iso j_)\n (by apply coprod.uniqueness; refl)\n (by apply coprod.uniqueness; refl) in\nlet ind := po'.induced (ii @> X) (I &> j) (ii.naturality _) in\nhave ind = pair.incl _, begin\n dsimp [ind], apply po'.uniqueness,\n { apply coprod.uniqueness; simpa },\n { simpa },\nend,\n⟨⟨(P ⊗ I_01).subspace, _, _, po'⟩,\n begin\n change cofibration ind ∧ is_closed (range ind), rw this,\n refine ⟨prod_I_01_cofibered P ha (cofibration_iff_cofibered.mp hj).2, _⟩,\n convert @pair.prod.is_closed P I_01 ha I_01.is_closed using 1,\n apply subtype.range_val\n end⟩\n\nend relative_cylinder\n\nend homotopy_theory.topological_spaces\n", "meta": {"author": "rwbarton", "repo": "lean-homotopy-theory", "sha": "39e1b4ea1ed1b0eca2f68bc64162dde6a6396dee", "save_path": "github-repos/lean/rwbarton-lean-homotopy-theory", "path": "github-repos/lean/rwbarton-lean-homotopy-theory/lean-homotopy-theory-39e1b4ea1ed1b0eca2f68bc64162dde6a6396dee/src/homotopy_theory/topological_spaces/cofibrations.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46101677931231594, "lm_q2_score": 0.032589748054616015, "lm_q1q2_score": 0.01502442068673889}} {"text": "inductive Foo where\n | mk : Nat → Foo\n | boo : String → Foo\n\ninstance : ToString Foo where\n toString o := match o with\n | .mk n => aux1 n\n | .boo s => aux2 s\nwhere\n aux1 (n : Nat) : String :=\n s!\".mk {n}\"\n aux2 (s : String) : String :=\n s!\".boo {s}\"\n\nexample : toString (Foo.mk 10) = \".mk 10\" := rfl\n", "meta": {"author": "leanprover", "repo": "lean4", "sha": "742d053a97bdd109a41a921facd1cd6a55e89bc7", "save_path": "github-repos/lean/leanprover-lean4", "path": "github-repos/lean/leanprover-lean4/lean4-742d053a97bdd109a41a921facd1cd6a55e89bc7/tests/lean/run/instanceWhereDecls.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35577489351363034, "lm_q2_score": 0.042087724611436506, "lm_q1q2_score": 0.014973755741864821}} {"text": "-- Copyright (c) 2017 Scott Morrison. All rights reserved.\n-- Released under Apache 2.0 license as described in the file LICENSE.\n-- Authors: Scott Morrison\n\n/- The Yoneda embedding, as a functor `yoneda : C ⥤ (Cᵒᵖ ⥤ Type v₁)`,\n along with an instance that it is `fully_faithful`.\n\n Also the Yoneda lemma, `yoneda_lemma : (yoneda_pairing C) ≅ (yoneda_evaluation C)`. -/\n\nimport category_theory.natural_transformation\nimport category_theory.opposites\nimport category_theory.types\nimport category_theory.fully_faithful\nimport category_theory.natural_isomorphism\n\nnamespace category_theory\n\nuniverses v₁ u₁ u₂ -- declare the `v`'s first; see `category_theory.category` for an explanation\n\nvariables {C : Type u₁} [𝒞 : category.{v₁} C]\ninclude 𝒞\n\ndef yoneda : C ⥤ (Cᵒᵖ ⥤ Type v₁) :=\n{ obj := λ X,\n { obj := λ Y, unop Y ⟶ X,\n map := λ Y Y' f g, f.unop ≫ g,\n map_comp' := λ _ _ _ f g, begin ext1, dsimp at *, erw [category.assoc] end,\n map_id' := λ Y, begin ext1, dsimp at *, erw [category.id_comp] end },\n map := λ X X' f, { app := λ Y g, g ≫ f } }\n\ndef coyoneda : Cᵒᵖ ⥤ (C ⥤ Type v₁) :=\n{ obj := λ X,\n { obj := λ Y, unop X ⟶ Y,\n map := λ Y Y' f g, g ≫ f,\n map_comp' := λ _ _ _ f g, begin ext1, dsimp at *, erw [category.assoc] end,\n map_id' := λ Y, begin ext1, dsimp at *, erw [category.comp_id] end },\n map := λ X X' f, { app := λ Y g, f.unop ≫ g },\n map_comp' := λ _ _ _ f g, begin ext1, ext1, dsimp at *, erw [category.assoc] end,\n map_id' := λ X, begin ext1, ext1, dsimp at *, erw [category.id_comp] end }\n\nnamespace yoneda\n@[simp] lemma obj_obj (X : C) (Y : Cᵒᵖ) : (yoneda.obj X).obj Y = (unop Y ⟶ X) := rfl\n@[simp] lemma obj_map (X : C) {Y Y' : Cᵒᵖ} (f : Y ⟶ Y') :\n (yoneda.obj X).map f = λ g, f.unop ≫ g := rfl\n@[simp] lemma map_app {X X' : C} (f : X ⟶ X') (Y : Cᵒᵖ) :\n (yoneda.map f).app Y = λ g, g ≫ f := rfl\n\nlemma obj_map_id {X Y : C} (f : op X ⟶ op Y) :\n ((@yoneda C _).obj X).map f (𝟙 X) = ((@yoneda C _).map f.unop).app (op Y) (𝟙 Y) :=\nby obviously\n\n@[simp] lemma naturality {X Y : C} (α : yoneda.obj X ⟶ yoneda.obj Y)\n {Z Z' : C} (f : Z ⟶ Z') (h : Z' ⟶ X) : f ≫ α.app (op Z') h = α.app (op Z) (f ≫ h) :=\nbegin erw [functor_to_types.naturality], refl end\n\ninstance yoneda_fully_faithful : fully_faithful (@yoneda C _) :=\n{ preimage := λ X Y f, (f.app (op X)) (𝟙 X),\n injectivity' := λ X Y f g p,\n begin\n injection p with h,\n convert (congr_fun (congr_fun h (op X)) (𝟙 X)); dsimp; simp,\n end }\n\n/-- Extensionality via Yoneda. The typical usage would be\n```\n-- Goal is `X ≅ Y`\napply yoneda.ext,\n-- Goals are now functions `(Z ⟶ X) → (Z ⟶ Y)`, `(Z ⟶ Y) → (Z ⟶ X)`, and the fact that these\nfunctions are inverses and natural in `Z`.\n```\n-/\ndef ext (X Y : C)\n (p : Π {Z : C}, (Z ⟶ X) → (Z ⟶ Y)) (q : Π {Z : C}, (Z ⟶ Y) → (Z ⟶ X))\n (h₁ : Π {Z : C} (f : Z ⟶ X), q (p f) = f) (h₂ : Π {Z : C} (f : Z ⟶ Y), p (q f) = f)\n (n : Π {Z Z' : C} (f : Z' ⟶ Z) (g : Z ⟶ X), p (f ≫ g) = f ≫ p g) : X ≅ Y :=\n@preimage_iso _ _ _ _ yoneda _ _ _ _\n (nat_iso.of_components (λ Z, { hom := p, inv := q, }) (by tidy))\n\n-- We need to help typeclass inference with some awkward universe levels here.\ninstance prod_category_instance_1 : category ((Cᵒᵖ ⥤ Type v₁) × Cᵒᵖ) :=\ncategory_theory.prod.{(max u₁ v₁) v₁} (Cᵒᵖ ⥤ Type v₁) Cᵒᵖ\n\ninstance prod_category_instance_2 : category (Cᵒᵖ × (Cᵒᵖ ⥤ Type v₁)) :=\ncategory_theory.prod.{v₁ (max u₁ v₁)} Cᵒᵖ (Cᵒᵖ ⥤ Type v₁)\n\nend yoneda\n\nnamespace coyoneda\n@[simp] lemma obj_obj (X : Cᵒᵖ) (Y : C) : (coyoneda.obj X).obj Y = (unop X ⟶ Y) := rfl\n@[simp] lemma obj_map {X' X : C} (f : X' ⟶ X) (Y : Cᵒᵖ) :\n (coyoneda.obj Y).map f = λ g, g ≫ f := rfl\n@[simp] lemma map_app (X : C) {Y Y' : Cᵒᵖ} (f : Y ⟶ Y') :\n (coyoneda.map f).app X = λ g, f.unop ≫ g := rfl\nend coyoneda\n\nclass representable (F : Cᵒᵖ ⥤ Type v₁) :=\n(X : C)\n(w : yoneda.obj X ≅ F)\n\nvariables (C)\nopen yoneda\n\ndef yoneda_evaluation : Cᵒᵖ × (Cᵒᵖ ⥤ Type v₁) ⥤ Type (max u₁ v₁) :=\nevaluation_uncurried Cᵒᵖ (Type v₁) ⋙ ulift_functor.{u₁}\n\n@[simp] lemma yoneda_evaluation_map_down\n (P Q : Cᵒᵖ × (Cᵒᵖ ⥤ Type v₁)) (α : P ⟶ Q) (x : (yoneda_evaluation C).obj P) :\n ((yoneda_evaluation C).map α x).down = α.2.app Q.1 (P.2.map α.1 x.down) := rfl\n\ndef yoneda_pairing : Cᵒᵖ × (Cᵒᵖ ⥤ Type v₁) ⥤ Type (max u₁ v₁) :=\nfunctor.prod yoneda.op (functor.id (Cᵒᵖ ⥤ Type v₁)) ⋙ functor.hom (Cᵒᵖ ⥤ Type v₁)\n\n@[simp] lemma yoneda_pairing_map\n (P Q : Cᵒᵖ × (Cᵒᵖ ⥤ Type v₁)) (α : P ⟶ Q) (β : (yoneda_pairing C).obj P) :\n (yoneda_pairing C).map α β = yoneda.map α.1.unop ≫ β ≫ α.2 := rfl\n\ndef yoneda_lemma : yoneda_pairing C ≅ yoneda_evaluation C :=\n{ hom :=\n { app := λ F x, ulift.up ((x.app F.1) (𝟙 (unop F.1))),\n naturality' :=\n begin\n intros X Y f, ext1, ext1,\n cases f, cases Y, cases X,\n dsimp at *, simp at *,\n erw [←functor_to_types.naturality,\n obj_map_id,\n functor_to_types.naturality,\n functor_to_types.map_id]\n end },\n inv :=\n { app := λ F x,\n { app := λ X a, (F.2.map a.op) x.down,\n naturality' :=\n begin\n intros X Y f, ext1,\n cases x, cases F,\n dsimp at *,\n erw [functor_to_types.map_comp]\n end },\n naturality' :=\n begin\n intros X Y f, ext1, ext1, ext1,\n cases x, cases f, cases Y, cases X,\n dsimp at *,\n erw [←functor_to_types.naturality, functor_to_types.map_comp]\n end },\n hom_inv_id' :=\n begin\n ext1, ext1, ext1, ext1, cases X, dsimp at *,\n erw [←functor_to_types.naturality,\n obj_map_id,\n functor_to_types.naturality,\n functor_to_types.map_id], refl,\n end,\n inv_hom_id' :=\n begin\n ext1, ext1, ext1,\n cases x, cases X,\n dsimp at *,\n erw [functor_to_types.map_id]\n end }.\n\nvariables {C}\n\n@[simp] def yoneda_sections (X : C) (F : Cᵒᵖ ⥤ Type v₁) : (yoneda.obj X ⟹ F) ≅ ulift.{u₁} (F.obj (op X)) :=\nnat_iso.app (yoneda_lemma C) (op X, F)\n\nomit 𝒞\n@[simp] def yoneda_sections_small {C : Type u₁} [small_category C] (X : C) (F : Cᵒᵖ ⥤ Type u₁) : (yoneda.obj X ⟹ F) ≅ F.obj (op X) :=\nyoneda_sections X F ≪≫ ulift_trivial _\n\nend category_theory\n", "meta": {"author": "digama0", "repo": "mathlib-ITP2019", "sha": "5cbd0362e04e671ef5db1284870592af6950197c", "save_path": "github-repos/lean/digama0-mathlib-ITP2019", "path": "github-repos/lean/digama0-mathlib-ITP2019/mathlib-ITP2019-5cbd0362e04e671ef5db1284870592af6950197c/src/category_theory/yoneda.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46490158620112276, "lm_q2_score": 0.032100708105956687, "lm_q1q2_score": 0.014923670116638503}} {"text": "import tactic.core\n\nattribute [inline] or.decidable decidable.to_bool bool.decidable_eq and.decidable\n nat.decidable_eq ne.decidable decidable.false implies.decidable option.get_or_else\n option.map\n\nmeta def format.form (as : list format) : format :=\n(format.join (as.intersperse format.line)).paren.group\n\nopen native\n\nmeta def expr.meta_vars (e : expr) : rb_set expr :=\ne.fold mk_rb_set $ λ e i ms,\nmatch e with\n| expr.mvar _ _ _ := ms.insert e\n| _ := ms\nend\n\nmeta def list.dup_by_native {α β} [has_lt β] [decidable_rel ((<) : β → β → Prop)]\n (f : α → β) (xs : list α) : list α :=\nrb_map.values $ xs.foldl (λ m x, m.insert (f x) x) mk_rb_map\n\nmeta def level.mvar_name : level → name\n| (level.mvar n) := n\n| _ := name.anonymous\n\nprivate meta def level.meta_vars_core : level → name_set → name_set\n| level.zero := id\n| (level.param _) := id\n| (level.succ l) := l.meta_vars_core\n| (level.mvar n) := λ ms, ms.insert n\n| (level.max a b) := a.meta_vars_core ∘ b.meta_vars_core\n| (level.imax a b) := a.meta_vars_core ∘ b.meta_vars_core\n\nmeta def level.meta_vars (l : level) : name_set :=\nlevel.meta_vars_core l mk_name_set\n\nmeta def expr.univ_meta_vars (e : expr) : name_set :=\ne.fold mk_name_set $ λ e i ms,\nmatch e with\n| expr.sort l := level.meta_vars_core l ms\n| expr.const _ ls := ls.foldr level.meta_vars_core ms\n| _ := ms\nend\n\ndef list.index_of_core' {α} [decidable_eq α] (a : α) : ℕ → list α → option ℕ\n| i [] := none\n| i (x::xs) := if x = a then some i else xs.index_of_core' (i+1)\n\ndef list.index_of' {α} [decidable_eq α] (a : α) (xs : list α) : option ℕ :=\nxs.index_of_core' a 0\n\nmeta def expr.abstract_mvars (e : expr) (mvars : list name) : expr :=\ne.replace $ λ e i,\nmatch e with\n| e@(expr.mvar n _ _) :=\n (mvars.index_of' n).map (λ j, expr.var (i + j))\n| e := none\nend\n\nmeta def expr.meta_uniq_name : expr → name\n| (expr.mvar n _ _) := n\n| _ := name.anonymous\n\nmeta def expr.meta_type : expr → expr\n| (expr.mvar _ _ t) := t\n| _ := default _\n\nmeta def expr.abstract_mvars' (e : expr) (mvars : list expr) : expr :=\ne.abstract_mvars (mvars.map expr.meta_uniq_name)\n\nopen tactic\n\nprivate meta def sorted_mvars_core : list expr → list expr → tactic (list expr)\n| (e@(expr.mvar n pp_n _)::es) ctx :=\n if ∃ m ∈ ctx, (m : expr).meta_uniq_name = e.meta_uniq_name then\n sorted_mvars_core es ctx\n else do\n t ← infer_type e >>= instantiate_mvars,\n ctx ← sorted_mvars_core t.meta_vars.to_list ctx,\n sorted_mvars_core es (e :: ctx)\n| [] ctx := pure ctx\n| (e::es) ctx := sorted_mvars_core (e.meta_vars.to_list ++ es) ctx\n\nmeta def expr.sorted_mvars' (es : list expr) : tactic (list expr) :=\nsorted_mvars_core es []\n\nmeta def expr.sorted_mvars (e : expr) : tactic (list expr) :=\nexpr.sorted_mvars' [e]\n\nmeta def abstract_mvar_telescope : list expr → tactic (list expr)\n| [] := pure []\n| (m :: ms) := do\n t ← infer_type m >>= instantiate_mvars,\n ms' ← abstract_mvar_telescope ms,\n pure $ t.abstract_mvars' ms :: ms'\n\nmeta def level.instantiate_univ_mvars (subst : rb_map name level) : level → level\n| level.zero := level.zero\n| (level.succ a) := a.instantiate_univ_mvars.succ\n| (level.max a b) := level.max (a.instantiate_univ_mvars) (b.instantiate_univ_mvars)\n| (level.imax a b) := level.imax (a.instantiate_univ_mvars) (b.instantiate_univ_mvars)\n| l@(level.param _) := l\n| l@(level.mvar n) := (subst.find n).get_or_else l\n\nmeta def expr.instantiate_univ_mvars (subst : rb_map name level) (e : expr) : expr :=\ne.replace $ λ e i,\nmatch e with\n| (expr.const n ls) :=\n some $ expr.const n (ls.map (level.instantiate_univ_mvars subst))\n| (expr.sort l) :=\n some $ expr.sort (l.instantiate_univ_mvars subst)\n| _ := none\nend\n\nmeta def expr.mk_lambda (x e : expr) : expr :=\nexpr.lam x.local_pp_name x.local_binding_info x.local_type (e.abstract x)\n\nmeta def expr.mk_lambdas (xs : list expr) (e : expr) : expr :=\nxs.foldr expr.mk_lambda e\n\nmeta def expr.mk_pi (x e : expr) : expr :=\nexpr.pi x.local_pp_name x.local_binding_info x.local_type (e.abstract x)\n\nmeta def expr.mk_pis (xs : list expr) (e : expr) : expr :=\nxs.foldr expr.mk_pi e\n\nmeta def expr.app' : expr → expr → expr\n| (expr.lam _ _ _ a) b := a.instantiate_var b\n| a b := a b\n\nlemma or_imp_congr {p p' q q'} (hp : p → p') (hq : q → q') : p ∨ q → p' ∨ q'\n| (or.inl h) := or.inl (hp h)\n| (or.inr h) := or.inr (hq h)\n\nlemma or_imp_congr_left {p q r} (h : q → r) : q ∨ p → r ∨ p :=\nor_imp_congr h id\n\nlemma or_imp_congr_right {p q r} (h : q → r) : p ∨ q → p ∨ r :=\nor_imp_congr id h\n\nlemma or_imp_congr_right_strong {p q r} (h : ¬ p → q → r) : p ∨ q → p ∨ r :=\nmatch classical.prop_decidable p with\n| decidable.is_true hp := λ _, or.inl hp\n| decidable.is_false hp := or_imp_congr_right (h hp)\nend\n\nlemma imp_iff_or_not {p q : Prop} : (p → q) ↔ (¬ p ∨ q) :=\nby cases classical.prop_decidable p; simp *\n\nlemma not_imp_iff_or {p q : Prop} : (¬ p → q) ↔ (p ∨ q) :=\nby cases classical.prop_decidable p; simp *\n\ntheorem iff_imp {a b c} : ((a ↔ b) → c) ↔ ((a → b) → (b → a) → c) :=\niff.intro (λ h ha hb, h ⟨ha, hb⟩) (λ h ⟨ha, hb⟩, h ha hb)\n\nlemma classical.forall_imp_iff_exists_not_or {α} {p : α → Prop} {q : Prop} :\n ((∀ x, p x) → q) ↔ ((∃ x, ¬ p x) ∨ q) :=\nby simp [imp_iff_or_not]\n\ndef list.has_dups_core {α} [decidable_eq α] : list α → list α → bool\n| (x::xs) ys := x ∈ ys ∨ xs.has_dups_core (x::ys)\n| [] _ := ff\n\ndef list.has_dups {α} [decidable_eq α] (xs : list α) : bool :=\nxs.has_dups_core []\n\ndef list.zip_with_index_core {α} : ℕ → list α → list (α × ℕ)\n| _ [] := []\n| i (x::xs) := (x,i) :: list.zip_with_index_core (i+1) xs\n\ndef list.zip_with_index {α} : list α → list (α × ℕ) :=\nlist.zip_with_index_core 0\n\ndef list.filter_maximal {α} (gt : α → α → bool) (l : list α) : list α :=\nl.filter $ λ x, ∀ y ∈ l, ¬ gt y x\n\ndef list.m_any {α m} [monad m] (f : α → m bool) : list α → m bool\n| [] := pure ff\n| (x::xs) := do f_x ← f x, if f_x then pure tt else xs.m_any\n\nmeta def mk_metas_core : list expr → tactic (list expr)\n| [] := pure []\n| (t::ts) := do\n ms ← mk_metas_core ts,\n m ← mk_meta_var (t.instantiate_vars ms),\n pure (m::ms)\n\nmeta def expr.name_hint : expr → option name\n| (expr.const n _) := n\n| (expr.app a b) := a.name_hint <|> b.name_hint\n| (expr.pi pp_n _ a b) := b.name_hint <|> a.name_hint <|> pp_n\n| (expr.lam pp_n _ a b) := b.name_hint <|> pp_n\n| (expr.sort _) := `type\n| (expr.local_const _ pp_n _ _) := pp_n\n| _ := name.anonymous\n\nmeta def expr.hyp_name_hint (e : expr) : name :=\nmatch e.name_hint with\n| some (name.mk_string s _) := (\"h_\" ++ s : string)\n| _ := `h\nend\n\nmeta def mk_locals_core : list expr → tactic (list expr)\n| [] := pure []\n| (t::ts) := do\n lcs ← mk_locals_core ts,\n lc ← mk_local' t.hyp_name_hint binder_info.default (t.instantiate_vars lcs),\n pure (lc :: lcs)\n\nmeta def expr.const_levels : expr → list level\n| (expr.const n ls) := ls\n| _ := []\n\n@[inline] instance has_monad_lift.refl {m} [monad m] : has_monad_lift m m := ⟨λ _, id⟩\n\nmeta def tactic.unify_level (l1 l2 : level) : tactic unit :=\ntactic.unify (expr.sort l1) (expr.sort l2)\n\nnamespace tactic\n\nmeta def unify_with_type (a b : expr) (trnsp := transparency.semireducible) (approx := ff) :\n tactic unit := do\nta ← infer_type a,\ntb ← infer_type b,\nunify ta tb trnsp approx,\nunify a b trnsp approx\n\nmeta def minimal_tc_failure : expr → tactic expr | e := do\nff ← succeeds (type_check e),\nmatch e with\n| (expr.app a b) := minimal_tc_failure a <|> minimal_tc_failure b\n| (expr.lam n bi a b) :=\n minimal_tc_failure a <|> (do\n l ← mk_local' n bi a,\n minimal_tc_failure (b.instantiate_var a))\n| (expr.pi n bi a b) :=\n minimal_tc_failure a <|> (do\n l ← mk_local' n bi a,\n minimal_tc_failure (b.instantiate_var a))\n| (expr.elet n t v b) :=\n minimal_tc_failure t <|> minimal_tc_failure v <|>\n minimal_tc_failure (b.instantiate_var v)\n| e := pure e\nend <|> pure e\n\nend tactic\n\n-- decidable instance for bounded existence is not short-circuiting?!?\ndef list.existsb {α} (p : α → bool) : list α → bool\n| [] := ff\n| (x :: xs) := if p x then tt else xs.existsb\n\nmeta def infer_univ (type : expr) : tactic level := do\nsort_of_type ← infer_type type >>= whnf,\nmatch sort_of_type with\n| expr.sort lvl := pure lvl\n| not_sort := do\n fmt ← pp not_sort,\n fail $ (to_fmt \"cannot get universe level of sort:\" ++ format.line ++ fmt).group.nest 1\nend\n", "meta": {"author": "gebner", "repo": "super2", "sha": "9bc5256c31750021ab97d6b59b7387773e54b384", "save_path": "github-repos/lean/gebner-super2", "path": "github-repos/lean/gebner-super2/super2-9bc5256c31750021ab97d6b59b7387773e54b384/src/super/utils.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.28776780354463427, "lm_q2_score": 0.05184546848103997, "lm_q1q2_score": 0.014919456588531438}} {"text": "import tactic.derive_fintype\nimport logic.function.basic\nimport data.set.function\nimport data.fin.tuple\nimport data.finset.lattice\n\nsection vars\n@[derive decidable_eq, derive fintype, derive inhabited]\ninductive Vars\n| i | j | k | w | x | y | z | ind₀ | ind₁ | ind₂ | break | output | len | vals\n\nopen Vars\ninstance : has_to_string Vars :=\n⟨λ v, match v with\n-- S.split(\" | \").map(s => s + ' := \"' + s + '\"')\n| i := \"i\" | j := \"j\" | k := \"k\" | w := \"w\" | x := \"x\" | y := \"y\" | z := \"z\" | ind₀ := \"ind₀\" | ind₁ := \"ind₁\" | ind₂ := \"ind₂\" | break := \"break\" | output := \"output\" | len := \"len\" | vals := \"vals\"\nend⟩\nend vars\n\nsection NameSpace\n@[derive decidable_eq, derive inhabited, derive has_to_string, reducible]\ndef NameSpace := ℕ\n\ndef NameSpace.reserved : NameSpace := 0\n\ndef fresh (S : finset NameSpace) : NameSpace :=\nS.max.iget + 1\n\ntheorem not_fresh_mem (S : finset NameSpace) : fresh S ∉ S :=\nbegin\n simp only [fresh],\n cases hn : S.max,\n { rw finset.max_eq_bot.1 hn, exact finset.not_mem_empty _, },\n { refine finset.not_mem_of_max_lt _ hn, simp },\nend\n\ntheorem not_fresh_reserved (S : finset NameSpace) : fresh S ≠ NameSpace.reserved :=\nby simp [fresh, NameSpace.reserved]\n\nattribute [irreducible] NameSpace\nend NameSpace\n\n@[derive decidable_eq, derive fintype, derive inhabited]\ninductive Types\n| nn | rr | bb\n\nsection Ident\n\n@[derive decidable_eq]\nstructure Ident (b : Types) :=\n(ns : NameSpace)\n(name : Vars)\n\ninstance {b : Types} : has_to_string (Ident b) :=\n⟨λ i, \"n\" ++ (to_string i.ns) ++ \"_\" ++ (to_string i.name)⟩\n\nlemma Ident_ns_surjective {b : Types} : function.surjective (@Ident.ns b) :=\nby { intro x, use ⟨x, default⟩, }\n\n@[simp] lemma Ident_ns_range {b : Types} : set.range (@Ident.ns b) = set.univ :=\nby simpa [set.surjective_iff_surj_on_univ, set.surj_on, set.univ_subset_iff] using Ident_ns_surjective\n\ninfix `∷`:9000 := Ident.mk\ninfix `∷ₙ`:9000 := @Ident.mk Types.nn\ninfix `∷ᵣ`:9000 := @Ident.mk Types.rr\n\nend Ident\n\nsection frames\n-- TODO Fix\nvariables {α γ : Type*} {β : α → Type*} (f : (Π x, β x) → γ) (g : (Π x, β x) → (Π x, β x))\n\ndef function.has_dframe (S : set α) : Prop :=\n∀ ⦃c₁ c₂ : Π x, β x⦄, (∀ x ∈ S, c₁ x = c₂ x) → f c₁ = f c₂\n\nstructure function.has_dheap (S : set α) : Prop :=\n(local_frame : ∀ (c₁ c₂ : Π x, β x), (∀ x ∈ S, c₁ x = c₂ x) → ∀ {y}, y ∈ S → g c₁ y = g c₂ y)\n(global_id : ∀ (c y), y ∉ S → g c y = c y)\n\nvariables {f g}\ntheorem function.has_dframe.res {S} (h : function.has_dframe f S) (S') (hS' : S ⊆ S') :\n function.has_dframe f S' :=\nλ c₁ c₂ h', h (λ x hx, h' _ (hS' hx))\n\ntheorem function.has_dheap.res {S} (h : function.has_dheap g S) (S') (hS' : S ⊆ S') :\n function.has_dheap g S' :=\n{ local_frame := λ c₁ c₂ c_eq y hy,\nbegin\n by_cases H : y ∈ S,\n { exact h.local_frame c₁ c₂ (λ x hx, c_eq _ (hS' hx)) H, },\n { rw [h.global_id c₁ _ H, h.global_id c₂ _ H], exact c_eq _ hy, },\nend,\n global_id := λ c y hy, h.global_id c y (λ H, hy (hS' H)), }\n\ntheorem function.has_dframe.const (x : γ) (S : set α) : function.has_dframe (λ _ : Π x, β x, x) S :=\nλ _ _ _, rfl\n\ntheorem function.has_dheap.id (S : set α) : function.has_dheap (@id (Π x, β x)) S :=\n{ local_frame := λ c₁ c₂ h y hy, h y hy,\n global_id := λ _ _ _, rfl }\n\nexample {S : set α} {x₀ : α} {y₀ : β x₀} [∀ x, decidable_eq (β x)] (f : (Π x, β x) → (Π x, β x)) (g : (Π x, β x) → γ)\n (hf : function.has_dframe g S) (hg : function.has_dheap f (insert x₀ S)) :\n function.has_dframe (λ ctx, if ctx x₀ = y₀ then g (f ctx) else g ctx) (insert x₀ S) :=\nbegin\n intros c₁ c₂ c_eq, dsimp only,\n have := (hf.res _ _) c_eq,\n all_goals { sorry, },\nend\n\nend frames\n\ndef Context (val_type : Types → Type) : Type :=\n∀ ⦃b : Types⦄, Ident b → val_type b\n\nstructure HeapContext (val_type : Types → Type) : Type :=\n(store : Context val_type)\n(heap : Context (list ∘ val_type))\n\nnamespace Context\n\nvariable {val_type : Types → Type}\n\ninstance [∀ b, inhabited (val_type b)] : inhabited (Context val_type) :=\n⟨λ _ _, default⟩\n\ndef get (ctx : Context val_type) {b : Types} (x : Ident b) : val_type b := ctx x\n\ndef update (ctx : Context val_type) {b : Types} (x : Ident b) (v : val_type b) :\n Context val_type :=\nfunction.update ctx b (function.update (@ctx b) x v)\n\n/- Spec for context -/\n@[simp] lemma update_sound (ctx : Context val_type) {b : Types} (x : Ident b) (v : val_type b) :\n (ctx.update x v).get x = v := by simp [update, get]\n\n@[simp] lemma update_frame (ctx : Context val_type) {b : Types} (x y : Ident b) (vx : val_type b)\n (neq : y ≠ x) : (ctx.update x vx).get y = ctx.get y := by simp [get, update, function.update, neq]\n\n/- TODO: Add simp lemmas -/\n\n/- For some reason doesn't play well with equation compiler -/\n-- attribute [irreducible] Context\n\n-- @[simp]\n-- def try_modify (ctx : Context val_type) {b : Types} (x : Ident b) (f : val_type b → option (val_type b)) :\n-- option (Context val_type) :=\n-- (f (ctx.get x)).map (ctx.update x)\n\nend Context\n\nnamespace HeapContext\nvariable {val_type : Types → Type}\n\n@[simps] def update (ctx : HeapContext val_type) {b : Types} (x : Ident b) (v : val_type b) :\n HeapContext val_type :=\n{ store := ctx.store.update x v,\n heap := ctx.heap }\n\n@[simps] def update_arr (ctx : HeapContext val_type) {b : Types} (x : Ident b) \n (n : ℕ) (v : val_type b) : HeapContext val_type :=\n{ store := ctx.store,\n heap := ctx.heap.update x ((ctx.heap.get x).update_nth n v) }\n\nend HeapContext\n\nsection iterate\n\n@[simp]\ndef iterate_while {α : Type*} (f : α → option α) (cond : α → option bool) : ℕ → α → option α\n| 0 x := none\n| (n+1) x := (cond x).bind (λ b, if b then (f x).bind (iterate_while n) else some x)\n\n-- theorem iterate_while_tr {α β : Type*} {f₁ : α → option α} {cond₁ : α → option bool} {n : ℕ} {x : α}\n-- (tr : α → β) (f₂ : β → option β) (cond₂ : β → option bool) (y : β)\n-- (hf : ∀ x, )\n\n-- theorem iterate_while_eq_of_invariant {α : Type*} (inv : α → ℕ → Prop)\n-- (f : α → option α) (cond : α → option bool) (n : ℕ) (x : α)\n-- (hcond : ∀ {x i}, inv x i → (cond x).is_some)\n-- (h₀ : inv x 0) (hind : ∀ x i, cond x = some tt → inv x i → ∃ x' ∈ f x, inv x' (i + 1))\n-- (hₜ : ∀ {x}, inv x n → cond x = some ff) :\n-- ∃ r ∈ iterate_while f cond (n + 1) x, inv r n :=\n-- begin\n-- induction n with n ih generalizing x,\n-- { simpa [hₜ h₀], },\n-- obtain ⟨_|_, hc⟩ := option.is_some_iff_exists.mp (hcond h₀),\n-- { simp, }\n-- end\n\nend iterate\n\ntheorem imp_iff_distrib {a b c : Prop} : ((a → b) ↔ (a → c)) ↔ (a → (b ↔ c)) :=\n⟨λ h ha, ⟨λ hb, h.mp (λ _, hb) ha, λ hc, h.mpr (λ _, hc) ha⟩, λ h, ⟨λ hb ha, (h ha).mp (hb ha), λ hc ha, (h ha).mpr (hc ha)⟩⟩\n", "meta": {"author": "kovach", "repo": "etch", "sha": "26ef67eb83cf7c5cfd1667059e16c3873b9098ca", "save_path": "github-repos/lean/kovach-etch", "path": "github-repos/lean/kovach-etch/etch-26ef67eb83cf7c5cfd1667059e16c3873b9098ca/src/verification/code_generation/vars.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40356685373537454, "lm_q2_score": 0.03676946462425473, "lm_q1q2_score": 0.014838937151944639}} {"text": "partial def inf (u : Unit) : List Unit := u :: inf u\n\ntheorem aa : False :=\n nomatch (⟨inf._unsafe_rec (), rfl⟩ : ∃ l, l = () :: l)\n", "meta": {"author": "lurk-lab", "repo": "yatima", "sha": "f33b0bf1052d95f9acbbe61681b1b58c0b97121e", "save_path": "github-repos/lean/lurk-lab-yatima", "path": "github-repos/lean/lurk-lab-yatima/yatima-f33b0bf1052d95f9acbbe61681b1b58c0b97121e/Fixtures/Typechecker/RejectInfListFalse.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.3960681662740416, "lm_q2_score": 0.0373268896198015, "lm_q1q2_score": 0.014783992724428338}} {"text": "/-\nFile: signature_recover_public_key_div_mod_n_soundness.lean\n\nAutogenerated file.\n-/\nimport starkware.cairo.lean.semantics.soundness.hoare\nimport .signature_recover_public_key_code\nimport ..signature_recover_public_key_spec\nimport .signature_recover_public_key_bigint_mul_soundness\nimport .signature_recover_public_key_nondet_bigint3_soundness\nopen tactic\n\nopen starkware.cairo.common.cairo_secp.signature\nopen starkware.cairo.common.cairo_secp.bigint\nopen starkware.cairo.common.cairo_secp.constants\n\nvariables {F : Type} [field F] [decidable_eq F] [prelude_hyps F]\nvariable mem : F → F\nvariable σ : register_state F\n\n/- starkware.cairo.common.cairo_secp.signature.div_mod_n autogenerated soundness theorem -/\n\ntheorem auto_sound_div_mod_n\n -- arguments\n (range_check_ptr : F) (a b : BigInt3 F)\n -- code is in memory at σ.pc\n (h_mem : mem_at mem code_div_mod_n σ.pc)\n -- all dependencies are in memory\n (h_mem_3 : mem_at mem code_bigint_mul (σ.pc - 668))\n (h_mem_4 : mem_at mem code_nondet_bigint3 (σ.pc - 654))\n -- input arguments on the stack\n (hin_range_check_ptr : range_check_ptr = mem (σ.fp - 9))\n (hin_a : a = cast_BigInt3 mem (σ.fp - 8))\n (hin_b : b = cast_BigInt3 mem (σ.fp - 5))\n -- conclusion\n : ensures_ret mem σ (λ κ τ,\n τ.ap = σ.ap + 88 ∧\n ∃ μ ≤ κ, rc_ensures mem (rc_bound F) μ (mem (σ.fp - 9)) (mem $ τ.ap - 4)\n (spec_div_mod_n mem κ range_check_ptr a b (mem (τ.ap - 4)) (cast_BigInt3 mem (τ.ap - 3)))) :=\nbegin\n apply ensures_of_ensuresb, intro νbound,\n have h_mem_rec := h_mem,\n unpack_memory code_div_mod_n at h_mem with ⟨hpc0, hpc1, hpc2, hpc3, hpc4, hpc5, hpc6, hpc7, hpc8, hpc9, hpc10, hpc11, hpc12, hpc13, hpc14, hpc15, hpc16, hpc17, hpc18, hpc19, hpc20, hpc21, hpc22, hpc23, hpc24, hpc25, hpc26, hpc27, hpc28, hpc29, hpc30, hpc31, hpc32, hpc33, hpc34, hpc35, hpc36, hpc37, hpc38, hpc39, hpc40, hpc41, hpc42, hpc43, hpc44, hpc45, hpc46, hpc47, hpc48, hpc49, hpc50, hpc51, hpc52, hpc53, hpc54, hpc55, hpc56, hpc57, hpc58, hpc59, hpc60, hpc61, hpc62, hpc63, hpc64⟩,\n -- function call\n step_assert_eq hpc0 with arg0,\n step_sub hpc1 (auto_sound_nondet_bigint3 mem _ range_check_ptr _ _),\n { rw hpc2, norm_num2, exact h_mem_4 },\n { try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_a, hin_b] },\n try { dsimp [cast_BigInt3] },\n try { arith_simps }, try { simp only [arg0] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } }, },\n intros κ_call3 ap3 h_call3,\n rcases h_call3 with ⟨h_call3_ap_offset, h_call3⟩,\n rcases h_call3 with ⟨rc_m3, rc_mle3, hl_range_check_ptr₁, h_call3⟩,\n generalize' hr_rev_range_check_ptr₁: mem (ap3 - 4) = range_check_ptr₁,\n have htv_range_check_ptr₁ := hr_rev_range_check_ptr₁.symm, clear hr_rev_range_check_ptr₁,\n generalize' hr_rev_res: cast_BigInt3 mem (ap3 - 3) = res,\n simp only [hr_rev_res] at h_call3,\n have htv_res := hr_rev_res.symm, clear hr_rev_res,\n try { simp only [arg0] at hl_range_check_ptr₁ },\n rw [←htv_range_check_ptr₁, ←hin_range_check_ptr] at hl_range_check_ptr₁,\n try { simp only [arg0] at h_call3 },\n rw [hin_range_check_ptr] at h_call3,\n clear arg0,\n -- function call\n step_assert_eq hpc3 with arg0,\n step_sub hpc4 (auto_sound_nondet_bigint3 mem _ range_check_ptr₁ _ _),\n { rw hpc5, norm_num2, exact h_mem_4 },\n { try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_a, hin_b, htv_range_check_ptr₁, htv_res] },\n try { dsimp [cast_BigInt3] },\n try { arith_simps }, try { simp only [arg0] },\n try { simp only [h_call3_ap_offset] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } }, },\n intros κ_call6 ap6 h_call6,\n rcases h_call6 with ⟨h_call6_ap_offset, h_call6⟩,\n rcases h_call6 with ⟨rc_m6, rc_mle6, hl_range_check_ptr₂, h_call6⟩,\n generalize' hr_rev_range_check_ptr₂: mem (ap6 - 4) = range_check_ptr₂,\n have htv_range_check_ptr₂ := hr_rev_range_check_ptr₂.symm, clear hr_rev_range_check_ptr₂,\n generalize' hr_rev_k: cast_BigInt3 mem (ap6 - 3) = k,\n simp only [hr_rev_k] at h_call6,\n have htv_k := hr_rev_k.symm, clear hr_rev_k,\n try { simp only [arg0] at hl_range_check_ptr₂ },\n rw [←htv_range_check_ptr₂, ←htv_range_check_ptr₁] at hl_range_check_ptr₂,\n try { simp only [arg0] at h_call6 },\n rw [←htv_range_check_ptr₁, hl_range_check_ptr₁, hin_range_check_ptr] at h_call6,\n clear arg0,\n -- function call\n step_assert_eq hpc6 with arg0,\n step_assert_eq hpc7 with arg1,\n step_assert_eq hpc8 with arg2,\n step_assert_eq hpc9 with arg3,\n step_assert_eq hpc10 with arg4,\n step_assert_eq hpc11 with arg5,\n step_sub hpc12 (auto_sound_bigint_mul mem _ res b _ _ _),\n { rw hpc13, norm_num2, exact h_mem_3 },\n { try { ext } ; {\n try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_a, hin_b, htv_range_check_ptr₁, htv_res, htv_range_check_ptr₂, htv_k] },\n try { dsimp [cast_BigInt3] },\n try { arith_simps }, try { simp only [arg0, arg1, arg2, arg3, arg4, arg5] },\n try { simp only [h_call3_ap_offset, h_call6_ap_offset] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },}, },\n { try { ext } ; {\n try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_a, hin_b, htv_range_check_ptr₁, htv_res, htv_range_check_ptr₂, htv_k] },\n try { dsimp [cast_BigInt3] },\n try { arith_simps }, try { simp only [arg0, arg1, arg2, arg3, arg4, arg5] },\n try { simp only [h_call3_ap_offset, h_call6_ap_offset] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },}, },\n intros κ_call14 ap14 h_call14,\n rcases h_call14 with ⟨h_call14_ap_offset, h_call14⟩,\n generalize' hr_rev_res_b: cast_UnreducedBigInt5 mem (ap14 - 5) = res_b,\n simp only [hr_rev_res_b] at h_call14,\n have htv_res_b := hr_rev_res_b.symm, clear hr_rev_res_b,\n clear arg0 arg1 arg2 arg3 arg4 arg5,\n -- let\n generalize' hl_rev_n: ({\n d0 := N0,\n d1 := N1,\n d2 := N2\n } : BigInt3 F) = n,\n have hl_n := hl_rev_n.symm, clear hl_rev_n,\n try { dsimp at hl_n }, try { arith_simps at hl_n },\n -- function call\n step_assert_eq hpc14 with arg0,\n step_assert_eq hpc15 with arg1,\n step_assert_eq hpc16 with arg2,\n step_assert_eq hpc17 hpc18 with arg3,\n step_assert_eq hpc19 hpc20 with arg4,\n step_assert_eq hpc21 hpc22 with arg5,\n step_sub hpc23 (auto_sound_bigint_mul mem _ k n _ _ _),\n { rw hpc24, norm_num2, exact h_mem_3 },\n { try { ext } ; {\n try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_a, hin_b, htv_range_check_ptr₁, htv_res, htv_range_check_ptr₂, htv_k, htv_res_b, hl_n] },\n try { dsimp [cast_BigInt3, cast_UnreducedBigInt5] },\n try { arith_simps }, try { simp only [arg0, arg1, arg2, arg3, arg4, arg5] },\n try { simp only [h_call3_ap_offset, h_call6_ap_offset, h_call14_ap_offset] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },}, },\n { try { ext } ; {\n try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_a, hin_b, htv_range_check_ptr₁, htv_res, htv_range_check_ptr₂, htv_k, htv_res_b, hl_n] },\n try { dsimp [cast_BigInt3, cast_UnreducedBigInt5] },\n try { arith_simps }, try { simp only [arg0, arg1, arg2, arg3, arg4, arg5] },\n try { simp only [h_call3_ap_offset, h_call6_ap_offset, h_call14_ap_offset] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },}, },\n intros κ_call25 ap25 h_call25,\n rcases h_call25 with ⟨h_call25_ap_offset, h_call25⟩,\n generalize' hr_rev_k_n: cast_UnreducedBigInt5 mem (ap25 - 5) = k_n,\n simp only [hr_rev_k_n] at h_call25,\n have htv_k_n := hr_rev_k_n.symm, clear hr_rev_k_n,\n clear arg0 arg1 arg2 arg3 arg4 arg5,\n -- tempvar\n step_assert_eq hpc25 with tv_carry10,\n step_assert_eq hpc26 with tv_carry11,\n step_assert_eq hpc27 hpc28 with tv_carry12,\n generalize' hl_rev_carry1: ((res_b.d0 - k_n.d0 - a.d0) / (BASE : ℤ) : F) = carry1,\n have hl_carry1 := hl_rev_carry1.symm, clear hl_rev_carry1,\n have htv_carry1: carry1 = _, {\n have h_δ25_c0 : ∀ x : F, x / (BASE : ℤ) = x * (-46768052394588894761721767695234645457402928824320 : ℤ),\n { intro x, apply div_eq_mul_inv', apply PRIME.int_cast_mul_eq_one, rw [PRIME], try { simp_int_casts }, norm_num1 },\n apply eq.symm, apply eq.trans tv_carry12,\n try { simp only [h_δ25_c0] at hl_carry1 },\n try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_a, hin_b, htv_range_check_ptr₁, htv_res, htv_range_check_ptr₂, htv_k, htv_res_b, hl_n, htv_k_n, hl_carry1] },\n try { dsimp [cast_BigInt3, cast_UnreducedBigInt5] },\n try { arith_simps }, try { simp only [(eq_sub_of_eq_add tv_carry10), (eq_sub_of_eq_add tv_carry11)] },\n try { simp only [h_call3_ap_offset, h_call6_ap_offset, h_call14_ap_offset, h_call25_ap_offset] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } }, },\n clear tv_carry10 tv_carry11 tv_carry12,\n try { dsimp at hl_carry1 }, try { arith_simps at hl_carry1 },\n -- compound assert eq\n step_assert_eq hpc29 hpc30 with temp0,\n step_assert_eq hpc31 with temp1,\n have a29: mem (range_check_ptr₂ + 0) = carry1 + 2 ^ 127, {\n apply assert_eq_reduction temp1.symm,\n try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_a, hin_b, htv_range_check_ptr₁, htv_res, htv_range_check_ptr₂, htv_k, htv_res_b, hl_n, htv_k_n, hl_carry1, htv_carry1] },\n try { dsimp [cast_BigInt3, cast_UnreducedBigInt5] },\n try { arith_simps }, try { simp only [temp0] },\n try { simp only [h_call3_ap_offset, h_call6_ap_offset, h_call14_ap_offset, h_call25_ap_offset] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },\n },\n try { dsimp at a29 }, try { arith_simps at a29 },\n clear temp0 temp1,\n -- tempvar\n step_assert_eq hpc32 with tv_carry20,\n step_assert_eq hpc33 with tv_carry21,\n step_assert_eq hpc34 with tv_carry22,\n step_assert_eq hpc35 hpc36 with tv_carry23,\n generalize' hl_rev_carry2: ((res_b.d1 - k_n.d1 - a.d1 + carry1) / (BASE : ℤ) : F) = carry2,\n have hl_carry2 := hl_rev_carry2.symm, clear hl_rev_carry2,\n have htv_carry2: carry2 = _, {\n have h_δ32_c0 : ∀ x : F, x / (BASE : ℤ) = x * (-46768052394588894761721767695234645457402928824320 : ℤ),\n { intro x, apply div_eq_mul_inv', apply PRIME.int_cast_mul_eq_one, rw [PRIME], try { simp_int_casts }, norm_num1 },\n apply eq.symm, apply eq.trans tv_carry23,\n try { simp only [h_δ32_c0] at hl_carry2 },\n try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_a, hin_b, htv_range_check_ptr₁, htv_res, htv_range_check_ptr₂, htv_k, htv_res_b, hl_n, htv_k_n, hl_carry1, htv_carry1, hl_carry2] },\n try { dsimp [cast_BigInt3, cast_UnreducedBigInt5] },\n try { arith_simps }, try { simp only [(eq_sub_of_eq_add tv_carry20), (eq_sub_of_eq_add tv_carry21), tv_carry22] },\n try { simp only [h_call3_ap_offset, h_call6_ap_offset, h_call14_ap_offset, h_call25_ap_offset] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } }, },\n clear tv_carry20 tv_carry21 tv_carry22 tv_carry23,\n try { dsimp at hl_carry2 }, try { arith_simps at hl_carry2 },\n -- compound assert eq\n step_assert_eq hpc37 hpc38 with temp0,\n step_assert_eq hpc39 with temp1,\n have a37: mem (range_check_ptr₂ + 1) = carry2 + 2 ^ 127, {\n apply assert_eq_reduction temp1.symm,\n try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_a, hin_b, htv_range_check_ptr₁, htv_res, htv_range_check_ptr₂, htv_k, htv_res_b, hl_n, htv_k_n, hl_carry1, htv_carry1, hl_carry2, htv_carry2] },\n try { dsimp [cast_BigInt3, cast_UnreducedBigInt5] },\n try { arith_simps }, try { simp only [temp0] },\n try { simp only [h_call3_ap_offset, h_call6_ap_offset, h_call14_ap_offset, h_call25_ap_offset] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },\n },\n try { dsimp at a37 }, try { arith_simps at a37 },\n clear temp0 temp1,\n -- tempvar\n step_assert_eq hpc40 with tv_carry30,\n step_assert_eq hpc41 with tv_carry31,\n step_assert_eq hpc42 with tv_carry32,\n step_assert_eq hpc43 hpc44 with tv_carry33,\n generalize' hl_rev_carry3: ((res_b.d2 - k_n.d2 - a.d2 + carry2) / (BASE : ℤ) : F) = carry3,\n have hl_carry3 := hl_rev_carry3.symm, clear hl_rev_carry3,\n have htv_carry3: carry3 = _, {\n have h_δ40_c0 : ∀ x : F, x / (BASE : ℤ) = x * (-46768052394588894761721767695234645457402928824320 : ℤ),\n { intro x, apply div_eq_mul_inv', apply PRIME.int_cast_mul_eq_one, rw [PRIME], try { simp_int_casts }, norm_num1 },\n apply eq.symm, apply eq.trans tv_carry33,\n try { simp only [h_δ40_c0] at hl_carry3 },\n try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_a, hin_b, htv_range_check_ptr₁, htv_res, htv_range_check_ptr₂, htv_k, htv_res_b, hl_n, htv_k_n, hl_carry1, htv_carry1, hl_carry2, htv_carry2, hl_carry3] },\n try { dsimp [cast_BigInt3, cast_UnreducedBigInt5] },\n try { arith_simps }, try { simp only [(eq_sub_of_eq_add tv_carry30), (eq_sub_of_eq_add tv_carry31), tv_carry32] },\n try { simp only [h_call3_ap_offset, h_call6_ap_offset, h_call14_ap_offset, h_call25_ap_offset] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } }, },\n clear tv_carry30 tv_carry31 tv_carry32 tv_carry33,\n try { dsimp at hl_carry3 }, try { arith_simps at hl_carry3 },\n -- compound assert eq\n step_assert_eq hpc45 hpc46 with temp0,\n step_assert_eq hpc47 with temp1,\n have a45: mem (range_check_ptr₂ + 2) = carry3 + 2 ^ 127, {\n apply assert_eq_reduction temp1.symm,\n try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_a, hin_b, htv_range_check_ptr₁, htv_res, htv_range_check_ptr₂, htv_k, htv_res_b, hl_n, htv_k_n, hl_carry1, htv_carry1, hl_carry2, htv_carry2, hl_carry3, htv_carry3] },\n try { dsimp [cast_BigInt3, cast_UnreducedBigInt5] },\n try { arith_simps }, try { simp only [temp0] },\n try { simp only [h_call3_ap_offset, h_call6_ap_offset, h_call14_ap_offset, h_call25_ap_offset] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },\n },\n try { dsimp at a45 }, try { arith_simps at a45 },\n clear temp0 temp1,\n -- tempvar\n step_assert_eq hpc48 with tv_carry40,\n step_assert_eq hpc49 with tv_carry41,\n step_assert_eq hpc50 hpc51 with tv_carry42,\n generalize' hl_rev_carry4: ((res_b.d3 - k_n.d3 + carry3) / (BASE : ℤ) : F) = carry4,\n have hl_carry4 := hl_rev_carry4.symm, clear hl_rev_carry4,\n have htv_carry4: carry4 = _, {\n have h_δ48_c0 : ∀ x : F, x / (BASE : ℤ) = x * (-46768052394588894761721767695234645457402928824320 : ℤ),\n { intro x, apply div_eq_mul_inv', apply PRIME.int_cast_mul_eq_one, rw [PRIME], try { simp_int_casts }, norm_num1 },\n apply eq.symm, apply eq.trans tv_carry42,\n try { simp only [h_δ48_c0] at hl_carry4 },\n try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_a, hin_b, htv_range_check_ptr₁, htv_res, htv_range_check_ptr₂, htv_k, htv_res_b, hl_n, htv_k_n, hl_carry1, htv_carry1, hl_carry2, htv_carry2, hl_carry3, htv_carry3, hl_carry4] },\n try { dsimp [cast_BigInt3, cast_UnreducedBigInt5] },\n try { arith_simps }, try { simp only [(eq_sub_of_eq_add tv_carry40), tv_carry41] },\n try { simp only [h_call3_ap_offset, h_call6_ap_offset, h_call14_ap_offset, h_call25_ap_offset] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } }, },\n clear tv_carry40 tv_carry41 tv_carry42,\n try { dsimp at hl_carry4 }, try { arith_simps at hl_carry4 },\n -- compound assert eq\n step_assert_eq hpc52 hpc53 with temp0,\n step_assert_eq hpc54 with temp1,\n have a52: mem (range_check_ptr₂ + 3) = carry4 + 2 ^ 127, {\n apply assert_eq_reduction temp1.symm,\n try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_a, hin_b, htv_range_check_ptr₁, htv_res, htv_range_check_ptr₂, htv_k, htv_res_b, hl_n, htv_k_n, hl_carry1, htv_carry1, hl_carry2, htv_carry2, hl_carry3, htv_carry3, hl_carry4, htv_carry4] },\n try { dsimp [cast_BigInt3, cast_UnreducedBigInt5] },\n try { arith_simps }, try { simp only [temp0] },\n try { simp only [h_call3_ap_offset, h_call6_ap_offset, h_call14_ap_offset, h_call25_ap_offset] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },\n },\n try { dsimp at a52 }, try { arith_simps at a52 },\n clear temp0 temp1,\n -- compound assert eq\n step_assert_eq hpc55 with temp0,\n step_assert_eq hpc56 hpc57 with temp1,\n step_assert_eq hpc58 with temp2,\n have a55: res_b.d4 - k_n.d4 + carry4 = 0, {\n apply assert_eq_reduction temp2.symm,\n try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_a, hin_b, htv_range_check_ptr₁, htv_res, htv_range_check_ptr₂, htv_k, htv_res_b, hl_n, htv_k_n, hl_carry1, htv_carry1, hl_carry2, htv_carry2, hl_carry3, htv_carry3, hl_carry4, htv_carry4] },\n try { dsimp [cast_BigInt3, cast_UnreducedBigInt5] },\n try { arith_simps }, try { simp only [(eq_sub_of_eq_add temp0), temp1] },\n try { simp only [h_call3_ap_offset, h_call6_ap_offset, h_call14_ap_offset, h_call25_ap_offset] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },\n },\n try { dsimp at a55 }, try { arith_simps at a55 },\n clear temp0 temp1 temp2,\n -- let\n generalize' hl_rev_range_check_ptr₃: (range_check_ptr₂ + 4 : F) = range_check_ptr₃,\n have hl_range_check_ptr₃ := hl_rev_range_check_ptr₃.symm, clear hl_rev_range_check_ptr₃,\n try { dsimp at hl_range_check_ptr₃ }, try { arith_simps at hl_range_check_ptr₃ },\n -- return\n step_assert_eq hpc59 hpc60 with hret0,\n step_assert_eq hpc61 with hret1,\n step_assert_eq hpc62 with hret2,\n step_assert_eq hpc63 with hret3,\n step_ret hpc64,\n -- finish\n step_done, use_only [rfl, rfl],\n split,\n { try { simp only [h_call3_ap_offset ,h_call6_ap_offset ,h_call14_ap_offset ,h_call25_ap_offset] },\n try { arith_simps }, try { refl } },\n -- range check condition\n use_only (rc_m3+rc_m6+4+0+0), split,\n linarith [rc_mle3, rc_mle6],\n split,\n { arith_simps, try { simp only [hret0 ,hret1 ,hret2 ,hret3] },\n try { simp only [h_call25_ap_offset ,h_call14_ap_offset] }, try { arith_simps },\n rw [←htv_range_check_ptr₂, hl_range_check_ptr₂, hl_range_check_ptr₁, hin_range_check_ptr],\n try { arith_simps, refl <|> norm_cast }, try { refl } },\n intro rc_h_range_check_ptr, repeat { rw [add_assoc] at rc_h_range_check_ptr },\n have rc_h_range_check_ptr' := range_checked_add_right rc_h_range_check_ptr,\n -- Final Proof\n -- user-provided reduction\n suffices auto_spec: auto_spec_div_mod_n mem _ range_check_ptr a b _ _,\n { apply sound_div_mod_n, apply auto_spec },\n -- prove the auto generated assertion\n dsimp [auto_spec_div_mod_n],\n try { norm_num1 }, try { arith_simps },\n use_only [κ_call3],\n use_only [range_check_ptr₁],\n use_only [res],\n have rc_h_range_check_ptr₁ := range_checked_offset' rc_h_range_check_ptr,\n have rc_h_range_check_ptr₁' := range_checked_add_right rc_h_range_check_ptr₁, try { norm_cast at rc_h_range_check_ptr₁' },\n have spec3 := h_call3 rc_h_range_check_ptr',\n rw [←hin_range_check_ptr, ←htv_range_check_ptr₁] at spec3,\n try { dsimp at spec3, arith_simps at spec3 },\n use_only [spec3],\n use_only [κ_call6],\n use_only [range_check_ptr₂],\n use_only [k],\n have rc_h_range_check_ptr₂ := range_checked_offset' rc_h_range_check_ptr₁,\n have rc_h_range_check_ptr₂' := range_checked_add_right rc_h_range_check_ptr₂, try { norm_cast at rc_h_range_check_ptr₂' },\n have spec6 := h_call6 rc_h_range_check_ptr₁',\n rw [←hin_range_check_ptr, ←hl_range_check_ptr₁, ←htv_range_check_ptr₂] at spec6,\n try { dsimp at spec6, arith_simps at spec6 },\n use_only [spec6],\n use_only [κ_call14],\n use_only [res_b],\n try { dsimp at h_call14, arith_simps at h_call14 },\n try { use_only [h_call14] },\n use_only [n, hl_n],\n use_only [κ_call25],\n use_only [k_n],\n try { dsimp at h_call25, arith_simps at h_call25 },\n try { use_only [h_call25] },\n use_only [carry1, hl_carry1],\n use_only [a29],\n cases rc_h_range_check_ptr₂' (0) (by norm_num1) with n hn, arith_simps at hn,\n use_only [n], { simp only [a29.symm, hl_range_check_ptr₂, hl_range_check_ptr₁, hin_range_check_ptr], arith_simps, exact hn },\n use_only [carry2, hl_carry2],\n use_only [a37],\n cases rc_h_range_check_ptr₂' (1) (by norm_num1) with n hn, arith_simps at hn,\n use_only [n], { simp only [a37.symm, hl_range_check_ptr₂, hl_range_check_ptr₁, hin_range_check_ptr], arith_simps, exact hn },\n use_only [carry3, hl_carry3],\n use_only [a45],\n cases rc_h_range_check_ptr₂' (2) (by norm_num1) with n hn, arith_simps at hn,\n use_only [n], { simp only [a45.symm, hl_range_check_ptr₂, hl_range_check_ptr₁, hin_range_check_ptr], arith_simps, exact hn },\n use_only [carry4, hl_carry4],\n use_only [a52],\n cases rc_h_range_check_ptr₂' (3) (by norm_num1) with n hn, arith_simps at hn,\n use_only [n], { simp only [a52.symm, hl_range_check_ptr₂, hl_range_check_ptr₁, hin_range_check_ptr], arith_simps, exact hn },\n use_only [a55],\n have rc_h_range_check_ptr₃ := range_checked_offset' rc_h_range_check_ptr₂,\n have rc_h_range_check_ptr₃' := range_checked_add_right rc_h_range_check_ptr₃,try { norm_cast at rc_h_range_check_ptr₃' },\n use_only [range_check_ptr₃, hl_range_check_ptr₃],\n try { split, linarith },\n try { ensures_simps; try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_a, hin_b, htv_range_check_ptr₁, htv_res, htv_range_check_ptr₂, htv_k, htv_res_b, hl_n, htv_k_n, hl_carry1, htv_carry1, hl_carry2, htv_carry2, hl_carry3, htv_carry3, hl_carry4, htv_carry4, hl_range_check_ptr₃] }, },\n try { dsimp [cast_BigInt3, cast_UnreducedBigInt5] },\n try { arith_simps }, try { simp only [hret0, hret1, hret2, hret3] },\n try { simp only [h_call3_ap_offset, h_call6_ap_offset, h_call14_ap_offset, h_call25_ap_offset] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },\nend\n\n", "meta": {"author": "starkware-libs", "repo": "formal-proofs", "sha": "35613c65b6715601bbc0a550d52754f8e7d93e30", "save_path": "github-repos/lean/starkware-libs-formal-proofs", "path": "github-repos/lean/starkware-libs-formal-proofs/formal-proofs-35613c65b6715601bbc0a550d52754f8e7d93e30/src/starkware/cairo/common/cairo_secp/verification/verification/signature_recover_public_key_div_mod_n_soundness.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4921881357207956, "lm_q2_score": 0.02976009512918625, "lm_q1q2_score": 0.01464756574050771}} {"text": "import category_theory.isomorphism category_theory.concrete_category\nimport category_theory.limits.shapes.equalizers\nimport category_theory.endomorphism\nimport category_theory.category.preorder data.fin.basic\nimport category_theory.arrow\nimport category_theory.category.Cat\nimport category_theory.limits.presheaf\nimport category_theory.limits.comma\n\n-- Should not be here...\nlemma nat.iterate_succ {α : Type*} (f : α → α)\n : ∀ (n : ℕ) (x0 : α), f^[n + 1] x0 = f (f^[n] x0)\n| 0 x0 := rfl\n| (n + 1) x0 := nat.iterate_succ n (f x0)\n\nnamespace category_theory\n\nopen category_theory category_theory.limits\n\nlocal attribute [instance]\n category_theory.concrete_category.has_coe_to_sort\n category_theory.concrete_category.has_coe_to_fun\n\nlemma iso.eq_app_inv_of_app_hom_eq\n {C : Type*} [category C] [concrete_category C] {X Y : C} (f : X ≅ Y)\n {x : X} {y : Y} (H : f.hom x = y) : x = f.inv y := \nbegin\n transitivity f.inv (f.hom x),\n { rw [← comp_apply, iso.hom_inv_id, id_apply] },\n { rw H }\nend\n\nlemma is_iso.eq_app_inv_of_app_hom_eq\n {C : Type*} [category C] [concrete_category C] {X Y : C} (f : X ⟶ Y) [is_iso f]\n {x : X} {y : Y} : f x = y → x = inv f y :=\n iso.eq_app_inv_of_app_hom_eq (as_iso f)\n\ntheorem is_iso.cancel_iso_inv_left {C : Type*} [category C] {X Y Z : C}\n (f : Y ⟶ X) [is_iso f] : ∀ (g g' : Y ⟶ Z), inv f ≫ g = inv f ≫ g' ↔ g = g' :=\n iso.cancel_iso_inv_left (as_iso f)\n\nlemma parallel_pair_comp \n {C : Type*} {D : Type*} [category C] [category D] (F : C ⥤ D) {X Y : C} (f g : X ⟶ Y)\n : parallel_pair f g ⋙ F = parallel_pair (F.map f) (F.map g) :=\nbegin\n apply category_theory.functor.hext,\n { intro u, cases u; refl },\n { intros u v i, cases u; cases v; cases i, \n all_goals { simp },\n all_goals { refl } },\nend\n\ndef parallel_pair_comp.cocone_comp_to_cocone_pair\n {C : Type*} {D : Type*} [category C] [category D] (F : C ⥤ D) {X Y : C} (f g : X ⟶ Y)\n (c : cocone (parallel_pair f g ⋙ F)) : cocone (parallel_pair (F.map f) (F.map g)) := {\n X := c.X,\n ι := eq_to_hom (parallel_pair_comp F f g).symm ≫ c.ι\n }\n\ndef parallel_pair_comp.cocone_pair_to_cocone_comp\n {C : Type*} {D : Type*} [category C] [category D] (F : C ⥤ D) {X Y : C} (f g : X ⟶ Y)\n (c : cocone (parallel_pair (F.map f) (F.map g))) : cocone (parallel_pair f g ⋙ F) := {\n X := c.X,\n ι := eq_to_hom (parallel_pair_comp F f g) ≫ c.ι\n }\n\ndef parallel_pair_comp.is_colimit_comp_to_is_colimit_pair\n {C : Type*} {D : Type*} [category C] [category D] (F : C ⥤ D) {X Y : C} (f g : X ⟶ Y)\n (c : cocone (parallel_pair f g ⋙ F)) (hc : is_colimit c)\n : is_colimit (parallel_pair_comp.cocone_comp_to_cocone_pair F f g c) := {\n desc := λ s, hc.desc (parallel_pair_comp.cocone_pair_to_cocone_comp F f g s),\n fac' := by { intros, refine eq.trans (category.assoc _ _ _) _, rw hc.fac',\n refine eq.trans (category.assoc _ _ _).symm _, simp },\n uniq' := λ s m h, hc.uniq' (parallel_pair_comp.cocone_pair_to_cocone_comp F f g s) m\n (λ u, by { refine eq.trans _ (congr_arg (λ w, nat_trans.app (eq_to_hom (parallel_pair_comp F f g)) u ≫ w) (h u)),\n refine eq.trans _ (category.assoc _ _ _),\n refine congr_arg (λ w, w ≫ m) _,\n refine eq.trans _ (category.assoc _ _ _),\n simp }) }\n\ndef parallel_pair_comp.is_colimit_pair_to_is_colimit_comp\n {C : Type*} {D : Type*} [category C] [category D] (F : C ⥤ D) {X Y : C} (f g : X ⟶ Y)\n (c : cocone (parallel_pair (F.map f) (F.map g))) (hc : is_colimit c)\n : is_colimit (parallel_pair_comp.cocone_pair_to_cocone_comp F f g c) := {\n desc := λ s, hc.desc (parallel_pair_comp.cocone_comp_to_cocone_pair F f g s),\n fac' := by { intros, refine eq.trans (category.assoc _ _ _) _, rw hc.fac',\n refine eq.trans (category.assoc _ _ _).symm _, simp },\n uniq' := λ s m h, hc.uniq' (parallel_pair_comp.cocone_comp_to_cocone_pair F f g s) m\n (λ u, by { refine eq.trans _ (congr_arg (λ w, nat_trans.app (eq_to_hom (parallel_pair_comp F f g).symm) u ≫ w) (h u)),\n refine eq.trans _ (category.assoc _ _ _),\n refine congr_arg (λ w, w ≫ m) _,\n refine eq.trans _ (category.assoc _ _ _),\n simp }) }\n\nlemma concrete_category.pow_eq_iter {C : Type*} [category C] [concrete_category C] {X : C} (f : X ⟶ X)\n (k : ℕ) : @coe_fn _ _ concrete_category.has_coe_to_fun (f ^ k : End X) = (f^[k]) :=\nbegin\n ext x,\n induction k with k ih,\n { simp },\n { rw nat.iterate_succ, rw ← npow_eq_pow, dsimp [monoid.npow, npow_rec], simp, congr, exact ih }\nend\n\nuniverse u\ndef restricted_yoneda_functor {C : Type u} [small_category C] {ℰ : Type*} [category ℰ]\n : (C ⥤ ℰ)ᵒᵖ ⥤ ℰ ⥤ Cᵒᵖ ⥤ Type u := \n category_theory.functor.op_hom _ _\n ⋙ whiskering_left Cᵒᵖ ℰᵒᵖ (Type u)\n ⋙ (whiskering_left _ _ _).obj yoneda\n\nlemma restricted_yoneda_functor_obj {C : Type u} [small_category C] {ℰ : Type*} [category ℰ]\n (A : C ⥤ ℰ) : restricted_yoneda_functor.obj (opposite.op A) = colimit_adj.restricted_yoneda A := rfl\n\ndef functor.map_cone_comp {J C D E : Type*} [category J] [category C] [category D] [category E]\n (K : J ⥤ C) (F : C ⥤ D) (G : D ⥤ E)\n : cones.functoriality K (F ⋙ G)\n ≅ cones.functoriality K F\n ⋙ cones.functoriality (K ⋙ F) G\n ⋙ cones.postcompose (functor.associator K F G).hom :=\nbegin\n refine nat_iso.of_components _ _,\n { intro c, refine category_theory.limits.cones.ext (iso.refl _) _,\n intro j, symmetry, exact eq.trans (category.id_comp _) (category.comp_id _) },\n { intros c c' f, ext,\n exact eq.trans (category.comp_id _) (category.id_comp _).symm }\nend\n\ndef functor.map_cone_map_cone {J C D E : Type*} [category J] [category C] [category D] [category E]\n (K : J ⥤ C) (F : C ⥤ D) (G : D ⥤ E)\n : cones.functoriality K (F ⋙ G) ⋙ cones.postcompose (functor.associator K F G).inv\n ≅ cones.functoriality K F ⋙ cones.functoriality (K ⋙ F) G :=\n ((whiskering_right _ _ _).obj (cones.postcompose (functor.associator K F G).inv)).map_iso\n (functor.map_cone_comp K F G)\n ≪≫ ((whiskering_right _ _ _).obj (cones.postcompose (functor.associator K F G).inv)).map_iso\n (functor.associator (cones.functoriality K F) (cones.functoriality (K ⋙ F) G)\n (cones.postcompose (K.associator F G).hom)).symm\n \n ≪≫ (functor.associator _ _ _)\n ≪≫ ((whiskering_left _ _ _).obj _).map_iso\n ((limits.cones.postcompose_comp _ _).symm ≪≫\n by { rw (K.associator F G).hom_inv_id, exact limits.cones.postcompose_id })\n ≪≫ (functor.right_unitor _)\n\ndef functor.map_cone_comp' {J C D E : Type*} [category J] [category C] [category D] [category E]\n (K : J ⥤ C) (F : C ⥤ D) (G : D ⥤ E) (c : cone K)\n : (F ⋙ G).map_cone c\n ≅ (cones.postcompose (functor.associator K F G).hom).obj (G.map_cone (F.map_cone c)) :=\n ((evaluation _ _).obj c).map_iso (functor.map_cone_comp K F G)\n\ndef functor.map_cone_map_cone' {J C D E : Type*} [category J] [category C] [category D] [category E]\n (K : J ⥤ C) (F : C ⥤ D) (G : D ⥤ E) (c : cone K)\n : (cones.postcompose (functor.associator K F G).inv).obj ((F ⋙ G).map_cone c)\n ≅ G.map_cone (F.map_cone c) :=\n ((evaluation _ _).obj c).map_iso (functor.map_cone_map_cone K F G)\n\ndef functor.map_cocone_comp {J C D E : Type*} [category J] [category C] [category D] [category E]\n (K : J ⥤ C) (F : C ⥤ D) (G : D ⥤ E)\n : cocones.functoriality K (F ⋙ G)\n ≅ cocones.functoriality K F\n ⋙ cocones.functoriality (K ⋙ F) G\n ⋙ cocones.precompose (functor.associator K F G).hom :=\nbegin\n refine nat_iso.of_components _ _,\n { intro c, refine category_theory.limits.cocones.ext (iso.refl _) _,\n intro j,\n exact eq.trans (category.comp_id _) (category.id_comp _).symm },\n { intros c c' f, ext,\n exact eq.trans (category.comp_id _) (category.id_comp _).symm }\nend\n\ndef functor.map_cocone_map_cocone {J C D E : Type*} [category J] [category C] [category D] [category E]\n (K : J ⥤ C) (F : C ⥤ D) (G : D ⥤ E)\n : cocones.functoriality K (F ⋙ G) ⋙ cocones.precompose (functor.associator K F G).inv\n ≅ cocones.functoriality K F ⋙ cocones.functoriality (K ⋙ F) G :=\n ((whiskering_right _ _ _).obj (cocones.precompose (functor.associator K F G).inv)).map_iso\n (functor.map_cocone_comp K F G)\n ≪≫ ((whiskering_right _ _ _).obj (cocones.precompose (functor.associator K F G).inv)).map_iso\n (functor.associator (cocones.functoriality K F) (cocones.functoriality (K ⋙ F) G)\n (cocones.precompose (K.associator F G).hom)).symm\n \n ≪≫ (functor.associator _ _ _)\n ≪≫ ((whiskering_left _ _ _).obj _).map_iso\n ((limits.cocones.precompose_comp _ _).symm ≪≫\n by { rw (K.associator F G).inv_hom_id, exact limits.cocones.precompose_id })\n ≪≫ (functor.right_unitor _)\n\ndef functor.map_cocone_comp' {J C D E : Type*} [category J] [category C] [category D] [category E]\n (K : J ⥤ C) (F : C ⥤ D) (G : D ⥤ E) (c : cocone K)\n : (F ⋙ G).map_cocone c\n ≅ (cocones.precompose (functor.associator K F G).hom).obj (G.map_cocone (F.map_cocone c)) :=\n ((evaluation _ _).obj c).map_iso (functor.map_cocone_comp K F G)\n\ndef functor.map_cocone_map_cocone' {J C D E : Type*} [category J] [category C] [category D]\n [category E] (K : J ⥤ C) (F : C ⥤ D) (G : D ⥤ E) (c : cocone K)\n : (cocones.precompose (functor.associator K F G).inv).obj ((F ⋙ G).map_cocone c)\n ≅ G.map_cocone (F.map_cocone c) :=\n ((evaluation _ _).obj c).map_iso (functor.map_cocone_map_cocone K F G)\n\ndef category_theory.limits.preserves_limits_of_equiv_domain {C : Type*} [category C]\n {D : Type*} [category D] {J : Type*} [category J] {K : J ⥤ C}\n {C' : Type*} [category C'] (F : C ⥤ D) (e : C ≌ C')\n (h : preserves_limit (K ⋙ e.functor) (e.inverse ⋙ F))\n : preserves_limit K F :=\nbegin\n constructor, intros c hc,\n let α : K ⋙ F ≅ (K ⋙ e.functor) ⋙ (e.inverse ⋙ F) :=\n calc K ⋙ F ≅ K ⋙ (𝟭 C ⋙ F) : ((whiskering_left _ _ _).obj K).map_iso F.left_unitor.symm\n ... ≅ K ⋙ ((e.functor ⋙ e.inverse) ⋙ F) : ((whiskering_left _ _ _).obj K).map_iso\n (((whiskering_right _ _ _).obj F).map_iso\n e.unit_iso)\n ... ≅ K ⋙ (e.functor ⋙ (e.inverse ⋙ F)) : ((whiskering_left _ _ _).obj K).map_iso \n (functor.associator _ _ _)\n ... ≅ (K ⋙ e.functor) ⋙ (e.inverse ⋙ F) : functor.associator _ _ _,\n refine is_limit.equiv_of_nat_iso_of_iso α.symm\n ((e.inverse ⋙ F).map_cone (e.functor.map_cone c))\n (F.map_cone c) _ _,\n { ext, swap, { exact F.map_iso (e.unit_iso.app c.X).symm },\n { dsimp,\n refine eq.trans (congr_arg _ (category.id_comp _))\n (eq.trans (congr_arg _ (category.id_comp _))\n (eq.trans (congr_arg _ (category.comp_id _)) _)),\n rw [← F.map_comp, ← F.map_comp],\n refine congr_arg _ _,\n rw [← functor.comp_map],\n apply e.unit_iso.inv.naturality } },\n { destruct h, intros h' _, refine h' _,\n destruct adjunction.is_equivalence_preserves_limits e.functor, intros h'' _,\n destruct h'', intros h''' _, destruct @h''' K, intros H _,\n exact H hc, }\nend.\n\ndef category_theory.limits.preserves_colimits_of_equiv_domain {C : Type*} [category C]\n {D : Type*} [category D] {J : Type*} [category J] {K : J ⥤ C}\n {C' : Type*} [category C'] (F : C ⥤ D) (e : C ≌ C')\n (h : preserves_colimit (K ⋙ e.functor) (e.inverse ⋙ F))\n : preserves_colimit K F :=\nbegin\n constructor, intros c hc,\n let α : K ⋙ F ≅ (K ⋙ e.functor) ⋙ (e.inverse ⋙ F) :=\n calc K ⋙ F ≅ K ⋙ (𝟭 C ⋙ F) : ((whiskering_left _ _ _).obj K).map_iso F.left_unitor.symm\n ... ≅ K ⋙ ((e.functor ⋙ e.inverse) ⋙ F) : ((whiskering_left _ _ _).obj K).map_iso\n (((whiskering_right _ _ _).obj F).map_iso\n e.unit_iso)\n ... ≅ K ⋙ (e.functor ⋙ (e.inverse ⋙ F)) : ((whiskering_left _ _ _).obj K).map_iso \n (functor.associator _ _ _)\n ... ≅ (K ⋙ e.functor) ⋙ (e.inverse ⋙ F) : functor.associator _ _ _,\n refine is_colimit.equiv_of_nat_iso_of_iso α.symm\n ((e.inverse ⋙ F).map_cocone (e.functor.map_cocone c))\n (F.map_cocone c) _ _,\n { ext, swap, { exact F.map_iso (e.unit_iso.app c.X).symm },\n { dsimp,\n refine eq.trans (congr_arg2 _ (congr_arg2 _ (category.comp_id _) rfl) rfl) _,\n refine eq.trans (congr_arg2 _ (congr_arg2 _ (category.comp_id _) rfl) rfl) _,\n refine eq.trans (congr_arg2 _ (congr_arg2 _ (category.id_comp _) rfl) rfl) _,\n rw [← F.map_comp, ← F.map_comp],\n refine congr_arg _ _,\n rw [← functor.comp_map],\n rw ← e.unit_iso.hom.naturality, simp } },\n { destruct h, intros h' _, refine h' _,\n destruct adjunction.is_equivalence_preserves_colimits e.functor, intros h'' _,\n destruct h'', intros h''' _, destruct @h''' K, intros H _,\n exact H hc, }\nend.\n\ndef category_theory.limits.preserves_colimits_of_equiv_codomain {C : Type*} [category C]\n {D : Type*} [category D] {J : Type*} [category J] {K : J ⥤ C}\n {D' : Type*} [category D'] (F : C ⥤ D) (e : D ≌ D')\n (h : preserves_colimit K (F ⋙ e.functor))\n : preserves_colimit K F :=\n @limits.preserves_colimit_of_nat_iso _ _ _ _ _ _ _ _ _\n (functor.associator _ _ _ ≪≫ ((whiskering_left _ _ _).obj F).map_iso e.unit_iso.symm\n ≪≫ functor.right_unitor _)\n (@limits.comp_preserves_colimit C _ D' _ J _ K D _ (F ⋙ e.functor) e.inverse h _)\n\ndef category_theory.iso_to_equiv {C : Type*} [category C] {D : Type*} [category D]\n (F : Cat.of C ≅ Cat.of D) : C ≌ D :=\n ⟨F.hom, F.inv, eq_to_iso (F.hom_inv_id.symm), eq_to_iso (F.inv_hom_id),\n by { intro, simp, rw category_theory.eq_to_hom_map, simp, refl }⟩.\n\nlemma colimit_iso_colimit_cocone_desc {J C : Type*} [category J] [category C]\n (F : J ⥤ C) [has_colimit F] (c : colimit_cocone F) (c' : cocone F)\n : (colimit.iso_colimit_cocone c).inv ≫ colimit.desc F c' = c.is_colimit.desc c' :=\n by { apply c.is_colimit.hom_ext, intro j, simp }\n\n-- universes v₁ v₂ v₃ v₄ u₁ u₂ u₃ u₄ \n-- I think the universe levels are borked :(\n-- def comma.cocone_of_preserves_is_colimit'\n-- {J : Type u₁} [small_category.{u₁} J] {A : Type u₂}\n-- [category.{(max u₁ u₂) u₂} A] {B : Type u₃}\n-- [category.{(max u₁ u₃) u₃} B] {T : Type u₄}\n-- [category.{(max u₁ u₄) u₄} T] {L : A ⥤ T} {R : B ⥤ T}\n-- (F : J ⥤ comma L R)\n-- [preserves_colimit (F ⋙ comma.fst L R) L]\n-- {c₁ : cocone (F ⋙ comma.fst L R)} (t₁ : is_colimit c₁)\n-- {c₂ : cocone (F ⋙ comma.snd L R)} (t₂ : is_colimit c₂) :\n-- is_colimit (comma.cocone_of_preserves.{u₁} F t₁ c₂) :=\n-- { desc := λ s,\n-- { left := t₁.desc ((fst L R).map_cocone s),\n-- right := t₂.desc ((snd L R).map_cocone s),\n-- w' := (is_colimit_of_preserves L t₁).hom_ext $ λ j,\n-- begin\n-- rw [cocone_of_preserves_X_hom, (is_colimit_of_preserves L t₁).fac_assoc,\n-- colimit_auxiliary_cocone_ι_app, assoc, ←R.map_comp, t₂.fac, L.map_cocone_ι_app,\n-- ←L.map_comp_assoc, t₁.fac],\n-- exact (s.ι.app j).w,\n-- end },\n-- uniq' := λ s m w, comma_morphism.ext _ _\n-- (t₁.uniq ((fst L R).map_cocone s) _ (by simp [←w]))\n-- (t₂.uniq ((snd L R).map_cocone s) _ (by simp [←w])) }\n\nend category_theory", "meta": {"author": "Shamrock-Frost", "repo": "BrouwerFixedPoint", "sha": "52f48d25068df0eadf3df5b2ede7bcb087d30527", "save_path": "github-repos/lean/Shamrock-Frost-BrouwerFixedPoint", "path": "github-repos/lean/Shamrock-Frost-BrouwerFixedPoint/BrouwerFixedPoint-52f48d25068df0eadf3df5b2ede7bcb087d30527/src/category_theory.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.49218813572079556, "lm_q2_score": 0.029760093300570403, "lm_q1q2_score": 0.014647564840484684}} {"text": "\nimport tactic.basic core data.sum tactic.rcases\nuniverses u₁ u₂\n\nopen interactive interactive.types\nopen lean.parser nat tactic\n\nmeta def get_ext_subject : expr → tactic name\n| (expr.pi n bi d b) :=\n do v ← mk_local' n bi d,\n b' ← whnf $ b.instantiate_var v,\n get_ext_subject b'\n| (expr.app _ e) :=\n do t ← infer_type e >>= instantiate_mvars >>= head_beta,\n if t.get_app_fn.is_constant then\n pure $ t.get_app_fn.const_name\n else if t.is_pi then\n pure $ name.mk_numeral 0 name.anonymous\n else if t.is_sort then\n pure $ name.mk_numeral 1 name.anonymous\n else do\n t ← pp t,\n fail format!\"only constants and Pi types are supported: {t}\"\n| e := fail format!\"Only expressions of the form `_ → _ → ... → R ... e are supported: {e}\"\n\nopen native\n\n@[reducible] def ext_param_type := option name ⊕ option name\n\nmeta def opt_minus : lean.parser (option name → ext_param_type) :=\nsum.inl <$ tk \"-\" <|> pure sum.inr\n\nmeta def ext_param :=\nopt_minus <*> ( name.mk_numeral 0 name.anonymous <$ brackets \"(\" \")\" (tk \"→\" <|> tk \"->\") <|>\n none <$ tk \"*\" <|>\n some <$> ident )\n\nmeta def saturate_fun : name → tactic expr\n| (name.mk_numeral 0 name.anonymous) :=\ndo v₀ ← mk_mvar,\n v₁ ← mk_mvar,\n return $ v₀.imp v₁\n| (name.mk_numeral 1 name.anonymous) :=\ndo u ← mk_meta_univ,\n pure $ expr.sort u\n| n :=\ndo e ← resolve_constant n >>= mk_const,\n a ← get_arity e,\n e.mk_app <$> (list.iota a).mmap (λ _, mk_mvar)\n\nmeta def equiv_type_constr (n n' : name) : tactic unit :=\ndo e ← saturate_fun n,\n e' ← saturate_fun n',\n unify e e' <|> fail format!\"{n} and {n'} are not definitionally equal types\"\n\n/--\n Tag lemmas of the form:\n\n ```\n @[extensionality]\n lemma my_collection.ext (a b : my_collection)\n (h : ∀ x, a.lookup x = b.lookup y) :\n a = b := ...\n ```\n\n The attribute indexes extensionality lemma using the type of the\n objects (i.e. `my_collection`) which it gets from the statement of\n the lemma. In some cases, the same lemma can be used to state the\n extensionality of multiple types that are definitionally equivalent.\n\n ```\n attribute [extensionality [(→),thunk,stream]] funext\n ```\n\n Those parameters are cumulative. The following are equivalent:\n\n ```\n attribute [extensionality [(→),thunk]] funext\n attribute [extensionality [stream]] funext\n ```\n and\n ```\n attribute [extensionality [(→),thunk,stream]] funext\n ```\n\n One removes type names from the list for one lemma with:\n ```\n attribute [extensionality [-stream,-thunk]] funext\n ```\n\n Finally, the following:\n\n ```\n @[extensionality]\n lemma my_collection.ext (a b : my_collection)\n (h : ∀ x, a.lookup x = b.lookup y) :\n a = b := ...\n ```\n\n is equivalent to\n\n ```\n @[extensionality *]\n lemma my_collection.ext (a b : my_collection)\n (h : ∀ x, a.lookup x = b.lookup y) :\n a = b := ...\n ```\n\n This allows us specify type synonyms along with the type\n that referred to in the lemma statement.\n\n ```\n @[extensionality [*,my_type_synonym]]\n lemma my_collection.ext (a b : my_collection)\n (h : ∀ x, a.lookup x = b.lookup y) :\n a = b := ...\n ```\n -/\n@[user_attribute]\nmeta def extensional_attribute : user_attribute (name_map name) (bool × list ext_param_type × list name × list (name × name)) :=\n{ name := `extensionality,\n descr := \"lemmas usable by `ext` tactic\",\n cache_cfg := { mk_cache := λ ls,\n do { attrs ← ls.mmap $ λ l,\n do { ⟨_,_,ls,_⟩ ← extensional_attribute.get_param l,\n pure $ prod.mk <$> ls <*> pure l },\n pure $ rb_map.of_list $ attrs.join },\n dependencies := [] },\n parser :=\n do { ls ← pure <$> ext_param <|> list_of ext_param <|> pure [],\n m ← extensional_attribute.get_cache,\n pure $ (ff,ls,[],m.to_list) },\n after_set := some $ λ n _ b,\n do (ff,ls,_,ls') ← extensional_attribute.get_param n | pure (),\n s ← mk_const n >>= infer_type >>= get_ext_subject,\n let (rs,ls'') := if ls.empty\n then ([],[s])\n else ls.partition_map (sum.map (flip option.get_or_else s) (flip option.get_or_else s)),\n ls''.mmap' (equiv_type_constr s),\n let l := ls'' ∪ (ls'.filter $ λ l, prod.snd l = n).map prod.fst \\ rs,\n extensional_attribute.set n (tt,[],l,[]) b }\n\nattribute [extensionality] array.ext propext\nattribute [extensionality [(→),thunk]] _root_.funext\n\nnamespace ulift\n@[extensionality] lemma ext {α : Type u₁} (X Y : ulift.{u₂} α) (w : X.down = Y.down) : X = Y :=\nbegin\n cases X, cases Y, dsimp at w, rw w,\nend\nend ulift\n\nnamespace tactic\n\nmeta def try_intros : ext_patt → tactic ext_patt\n| [] := try intros $> []\n| (x::xs) :=\ndo tgt ← target >>= whnf,\n if tgt.is_pi\n then rintro [x] >> try_intros xs\n else pure (x :: xs)\n\nmeta def ext1 (xs : ext_patt) : tactic ext_patt :=\ndo subject ← target >>= get_ext_subject,\n m ← extensional_attribute.get_cache,\n do { rule ← m.find subject,\n applyc rule } <|>\n do { ls ← attribute.get_instances `extensionality,\n ls.any_of applyc } <|>\n fail format!\"no applicable extensionality rule found for {subject}\",\n try_intros xs\n\nmeta def ext : ext_patt → option ℕ → tactic unit\n| _ (some 0) := skip\n| xs n := focus1 $ do\n ys ← ext1 xs, try (ext ys (nat.pred <$> n))\n\n\nlocal postfix `?`:9001 := optional\nlocal postfix *:9001 := many\n\n/--\n `ext1 id` selects and apply one extensionality lemma (with attribute\n `extensionality`), using `id`, if provided, to name a local constant\n introduced by the lemma. If `id` is omitted, the local constant is\n named automatically, as per `intro`.\n -/\nmeta def interactive.ext1 (xs : parse ext_parse) : tactic unit :=\next1 xs $> ()\n\n/--\n - `ext` applies as many extensionality lemmas as possible;\n - `ext ids`, with `ids` a list of identifiers, finds extentionality and applies them\n until it runs out of identifiers in `ids` to name the local constants.\n\n When trying to prove:\n\n ```\n α β : Type,\n f g : α → set β\n ⊢ f = g\n ```\n\n applying `ext x y` yields:\n\n ```\n α β : Type,\n f g : α → set β,\n x : α,\n y : β\n ⊢ y ∈ f x ↔ y ∈ f x\n ```\n\n by applying functional extensionality and set extensionality.\n\n A maximum depth can be provided with `ext x y z : 3`.\n -/\nmeta def interactive.ext : parse ext_parse → parse (tk \":\" *> small_nat)? → tactic unit\n | [] (some n) := iterate_range 1 n (ext1 [] $> ())\n | [] none := repeat1 (ext1 [] $> ())\n | xs n := tactic.ext xs n\n\nend tactic\n", "meta": {"author": "khoek", "repo": "mathlib-tidy", "sha": "866afa6ab597c47f1b72e8fe2b82b97fff5b980f", "save_path": "github-repos/lean/khoek-mathlib-tidy", "path": "github-repos/lean/khoek-mathlib-tidy/mathlib-tidy-866afa6ab597c47f1b72e8fe2b82b97fff5b980f/tactic/ext.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4493926492132671, "lm_q2_score": 0.03258974241703221, "lm_q1q2_score": 0.014645590681968088}} {"text": "import Lean\nimport Lean.Parser.Term\n\nopen Lean Elab Command Term Meta \n\nnamespace SumMacro\n\n-- The Prismatic class lets you move between a sum type and its subtypes\n-- For instance if you had a sum type X := A | B then\n-- > inject goes from A → X or B → X\n-- > project goes from X → Option A or X → Option B\nclass Prismatic (e : Type → Type) (u : Type → Type v) where\n inject : e α → u α\n project : u α → Option (e α)\n\n-- Given a sum type we need a way to label each branch of the sum type.\n-- For example given X := A | B we need to generate contructors for A and B.\n-- For normal sum types these are usually Left and Right, but one reason to use\n-- macros is so that the names are a little more readable.\n-- Typically the subtype name is just the name of the subtype, assuming\n-- the subtype is just an identifier indicating some type. However, you can\n-- actually pass in an expression as a subtype. We need a way to generate\n-- an ID for that expression that is (mostly) unique and also repeatable\n-- for that expression (thus we can't just generate random names).\npartial\ndef compileSubId : Syntax → Name := fun subterm =>\n match subterm with\n | .missing => \"missing_\"\n | .node _ kind args =>\n if kind == strLitKind\n then compileSubId args[0]!\n -- ignore parenthesis\n else if kind == ``Lean.Parser.Term.paren\n then compileSubId args[1]!\n -- for parameterized types we merge the function and its argument\n else if kind == ``Lean.Parser.Term.app\n then\n let fName := compileSubId args[0]!\n let argNames := compileSubId args[1]!\n fName ++ argNames\n -- if we didn't handle the term already we just punt and try\n -- to fold together all the sub nodes, ignoring null or empty values\n else if args.size > 0\n then Array.foldl (fun x y => \n let y' := compileSubId y\n if x == \"\"\n then compileSubId y\n else if y' == \"null\"\n then x\n else x ++ y') \"\" args\n else if kind == `null\n then \"null\"\n else toString kind\n | .atom _ val => val\n | .ident _ _ val _ => val\n \n\ndef sumCtorName2 : Ident → Term → Name := fun sumid subterm => sumid.getId ++ Name.appendAfter (compileSubId subterm) \"select\"\n\n-- to generate the sum type we basically need to generate constructors for each subtype\n-- and then tie it all together with an inductive view.\ndef elabSumI (sumid : Ident) (subids : Syntax.TSepArray `term \",\") : CommandElabM Unit := do\n let subvals : Array (TSyntax `term) := subids\n let toCtor : Term → CommandElabM CtorView := \n fun subterm => do\n let ty ← `({x : Type} → $subterm x → $sumid x)\n pure { ref := default,\n modifiers := default,\n declName := sumCtorName2 sumid subterm,\n binders := Syntax.missing,\n type? := ty\n }\n let subCtors : Array CtorView ← Array.sequenceMap subvals toCtor\n let indView : InductiveView := {\n ref := default,\n modifiers := {docString? := \"argh\"},\n declId := sumid,\n shortDeclName := sumid.getId,\n declName := sumid.getId,\n levelNames := [],\n binders := Syntax.missing,\n type? := (← `(Type → Type 1)),\n ctors := subCtors,\n derivingClasses := #[],\n computedFields := #[]\n }\n elabInductiveViews #[indView]\n\n-- you can make the sum type directly using mkSumI but typically you use\n-- mkSumType which also generates prismatic instances\nelab \"mkSumI\" sumid:ident \" o: \" subids:term,+ \":o\" : command => elabSumI sumid subids\n\n\n\ndef elabPrismatic (sumid : Ident) (subterm: Term) : CommandElabM Unit := do\n let ctorName : Ident := Lean.mkIdent <| sumCtorName2 sumid subterm\n let instanceCmd ←\n `(instance : Prismatic $subterm ($sumid) where\n inject := fun sx => $ctorName sx\n project := fun bx => match bx with \n | $ctorName sx => Option.some sx\n | _ => Option.none)\n elabCommand instanceCmd\n\nelab \"mkPrismatic\" sumid:ident subid:term : command => elabPrismatic sumid subid\n\n\nelab \"mkSumType\" sumid:ident \" >| \" subids:term,+ \" |< \" : command => do\n elabSumI sumid subids\n let mkP := fun subterm => elabPrismatic sumid subterm\n Array.forM mkP (subids : Array Term)\n\n\n\ndef elabCollapse (collapsertarget : TSyntax `term) (sumid : Ident) (subids: Syntax.TSepArray `term sep) (collapsers : Syntax.TSepArray `term sep) : TermElabM Expr := do\n let evalBranch : (TSyntax `term × TSyntax `term) → TermElabM (TSyntax `Lean.Parser.Term.matchAlt) := fun ⟨subval, collapser⟩ => do\n let ctorName := Lean.mkIdent <| sumCtorName2 sumid subval\n `(Parser.Term.matchAltExpr| | $ctorName x => $collapser x)\n let subidsArray : Array (TSyntax `term) := subids\n let collapsersArray : Array (TSyntax `term) := collapsers\n let branches ← Array.sequenceMap (Array.zip subidsArray collapsersArray) evalBranch\n let collapserFunc ← `(fun {α : Type} (sumVal : $sumid α) => (match sumVal with $branches:matchAlt* : $collapsertarget α))\n elabTerm collapserFunc Option.none\n\nelab \"buildInterpreter\" commandtype:ident targetmonad:ident subids:term,+ \" [: \" collapsers:term,+ \" :] \" : term =>\n elabCollapse targetmonad commandtype subids collapsers\n\n/-\nnamespace x\n\ninductive OtherI (y : Type) where\n | A : y → OtherI y\n | C : y → y → OtherI y\n deriving Repr\n\ninductive EcksI (x : Type) (y : Type) where\n| X : x → y → EcksI x y\n-/\n/-\nmkSumI Argh o: (EcksI Nat),OtherI :o\nmkPrismatic Argh (EcksI Nat)\nmkPrismatic Argh OtherI\n\n\nmkSumType Argh >| EcksI Nat, OtherI |<\n\ndef collapserArgh := buildInterpreter Argh IO (EcksI Nat),OtherI\n [:\n (fun s => match s with \n | EcksI.X x y => pure y),\n (fun o => match o with\n | OtherI.A y => pure y\n | OtherI.C a b => pure b)\n :]\n\n\nopen Prismatic\n\ndef aVal : Argh Nat := inject <| EcksI.X 3 4\nend x\n\n-/\n\n/-#print Argh\n#check Argh.EcksI.Natselect (EcksI.X 3 4)\n#check @Prismatic.inject (EcksI Nat) Argh _ Nat (EcksI.X 3 5) \n#check (Prismatic.inject (EcksI.X 3 7) : Argh Nat)\n#check blargh aVal\n-/\n\nend SumMacro\n", "meta": {"author": "Izzimach", "repo": "qinglong", "sha": "d2f4e4656d86fdbace9bbbdc94f8e1de1a67f97f", "save_path": "github-repos/lean/Izzimach-qinglong", "path": "github-repos/lean/Izzimach-qinglong/qinglong-d2f4e4656d86fdbace9bbbdc94f8e1de1a67f97f/src/QingLong/Macro/SumMacro.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41489884579676883, "lm_q2_score": 0.03514484930623215, "lm_q1q2_score": 0.01458155741285709}} {"text": "import classes.unrestricted.basics.definition\n\nvariables {T : Type} {g : grammar T}\n\n\n/-- The relation `grammar_derives` is reflexive. -/\nlemma grammar_deri_self {w : list (symbol T g.nt)} :\n grammar_derives g w w :=\nrelation.refl_trans_gen.refl\n\nlemma grammar_deri_of_tran {v w : list (symbol T g.nt)} :\n grammar_transforms g v w → grammar_derives g v w :=\nrelation.refl_trans_gen.single\n\n/-- The relation `grammar_derives` is transitive. -/\nlemma grammar_deri_of_deri_deri {u v w : list (symbol T g.nt)}\n (huv : grammar_derives g u v) (hvw : grammar_derives g v w) :\n grammar_derives g u w :=\nrelation.refl_trans_gen.trans huv hvw\n\nlemma grammar_deri_of_deri_tran {u v w : list (symbol T g.nt)}\n (huv : grammar_derives g u v) (hvw : grammar_transforms g v w) :\n grammar_derives g u w :=\ngrammar_deri_of_deri_deri huv (grammar_deri_of_tran hvw)\n\nlemma grammar_deri_of_tran_deri {u v w : list (symbol T g.nt)}\n (huv : grammar_transforms g u v) (hvw : grammar_derives g v w) :\n grammar_derives g u w :=\ngrammar_deri_of_deri_deri (grammar_deri_of_tran huv) hvw\n\nlemma grammar_tran_or_id_of_deri {u w : list (symbol T g.nt)} (ass : grammar_derives g u w) :\n (u = w) ∨\n (∃ v : list (symbol T g.nt), (grammar_transforms g u v) ∧ (grammar_derives g v w)) :=\nrelation.refl_trans_gen.cases_head ass\n\n\nlemma grammar_deri_with_prefix {w₁ w₂ : list (symbol T g.nt)}\n (pᵣ : list (symbol T g.nt))\n (ass : grammar_derives g w₁ w₂) :\n grammar_derives g (pᵣ ++ w₁) (pᵣ ++ w₂) :=\nbegin\n induction ass with x y trash hyp ih,\n {\n apply grammar_deri_self,\n },\n apply grammar_deri_of_deri_tran,\n {\n exact ih,\n },\n rcases hyp with ⟨r, rin, u, v, h_bef, h_aft⟩,\n use r,\n split,\n {\n exact rin,\n },\n use pᵣ ++ u,\n use v,\n rw h_bef,\n rw h_aft,\n split;\n simp only [list.append_assoc],\nend\n\nlemma grammar_deri_with_postfix {w₁ w₂ : list (symbol T g.nt)}\n (pₒ : list (symbol T g.nt))\n (ass : grammar_derives g w₁ w₂) :\n grammar_derives g (w₁ ++ pₒ) (w₂ ++ pₒ) :=\nbegin\n induction ass with x y trash hyp ih,\n {\n apply grammar_deri_self,\n },\n apply grammar_deri_of_deri_tran,\n {\n exact ih,\n },\n rcases hyp with ⟨r, rin, u, v, h_bef, h_aft⟩,\n use r,\n split,\n {\n exact rin,\n },\n use u,\n use v ++ pₒ,\n rw h_bef,\n rw h_aft,\n split;\n simp only [list.append_assoc],\nend\n\n\ndef as_terminal {N : Type} : symbol T N → option T\n| (symbol.terminal t) := some t\n| (symbol.nonterminal _) := none\n\ndef all_used_terminals (g : grammar T) : list T :=\nlist.filter_map as_terminal (list.join (list.map grule.output_string g.rules))\n", "meta": {"author": "madvorak", "repo": "grammars", "sha": "5ab26130eb76d5f7cde0f6c2f9c6f3107ff8d34f", "save_path": "github-repos/lean/madvorak-grammars", "path": "github-repos/lean/madvorak-grammars/grammars-5ab26130eb76d5f7cde0f6c2f9c6f3107ff8d34f/src/classes/unrestricted/basics/toolbox.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48828339529583464, "lm_q2_score": 0.02976009319300477, "lm_q1q2_score": 0.014531359348600826}} {"text": "/-\nCopyright (c) 2017 Johannes Hölzl. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthor: Johannes Hölzl\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.default\nimport Mathlib.tactic.lint.default\nimport Mathlib.tactic.ext\nimport Mathlib.tactic.simps\nimport Mathlib.PostPort\n\nuniverses u_1 u_2 u_3 \n\nnamespace Mathlib\n\nnamespace subtype\n\n\n/-- See Note [custom simps projection] -/\ndef simps.val {α : Sort u_1} {p : α → Prop} (x : Subtype p) : α :=\n ↑x\n\n/-- A version of `x.property` or `x.2` where `p` is syntactically applied to the coercion of `x`\n instead of `x.1`. A similar result is `subtype.mem` in `data.set.basic`. -/\ntheorem prop {α : Sort u_1} {p : α → Prop} (x : Subtype p) : p ↑x :=\n property x\n\n@[simp] theorem val_eq_coe {α : Sort u_1} {p : α → Prop} {x : Subtype p} : val x = ↑x :=\n rfl\n\n@[simp] protected theorem forall {α : Sort u_1} {p : α → Prop} {q : (Subtype fun (a : α) => p a) → Prop} : (∀ (x : Subtype fun (a : α) => p a), q x) ↔ ∀ (a : α) (b : p a), q { val := a, property := b } := sorry\n\n/-- An alternative version of `subtype.forall`. This one is useful if Lean cannot figure out `q`\n when using `subtype.forall` from right to left. -/\nprotected theorem forall' {α : Sort u_1} {p : α → Prop} {q : (x : α) → p x → Prop} : (∀ (x : α) (h : p x), q x h) ↔ ∀ (x : Subtype fun (a : α) => p a), q (↑x) (property x) :=\n iff.symm subtype.forall\n\n@[simp] protected theorem exists {α : Sort u_1} {p : α → Prop} {q : (Subtype fun (a : α) => p a) → Prop} : (∃ (x : Subtype fun (a : α) => p a), q x) ↔ ∃ (a : α), ∃ (b : p a), q { val := a, property := b } := sorry\n\nprotected theorem ext {α : Sort u_1} {p : α → Prop} {a1 : Subtype fun (x : α) => p x} {a2 : Subtype fun (x : α) => p x} : ↑a1 = ↑a2 → a1 = a2 := sorry\n\ntheorem ext_iff {α : Sort u_1} {p : α → Prop} {a1 : Subtype fun (x : α) => p x} {a2 : Subtype fun (x : α) => p x} : a1 = a2 ↔ ↑a1 = ↑a2 :=\n { mp := congr_arg fun {a1 : Subtype fun (x : α) => p x} => ↑a1, mpr := subtype.ext }\n\ntheorem heq_iff_coe_eq {α : Sort u_1} {p : α → Prop} {q : α → Prop} (h : ∀ (x : α), p x ↔ q x) {a1 : Subtype fun (x : α) => p x} {a2 : Subtype fun (x : α) => q x} : a1 == a2 ↔ ↑a1 = ↑a2 :=\n Eq._oldrec (fun (a2' : Subtype fun (x : α) => p x) => iff.trans heq_iff_eq ext_iff)\n (funext fun (x : α) => propext (h x)) a2\n\ntheorem ext_val {α : Sort u_1} {p : α → Prop} {a1 : Subtype fun (x : α) => p x} {a2 : Subtype fun (x : α) => p x} : val a1 = val a2 → a1 = a2 :=\n subtype.ext\n\ntheorem ext_iff_val {α : Sort u_1} {p : α → Prop} {a1 : Subtype fun (x : α) => p x} {a2 : Subtype fun (x : α) => p x} : a1 = a2 ↔ val a1 = val a2 :=\n ext_iff\n\n@[simp] theorem coe_eta {α : Sort u_1} {p : α → Prop} (a : Subtype fun (a : α) => p a) (h : p ↑a) : { val := ↑a, property := h } = a :=\n subtype.ext rfl\n\n@[simp] theorem coe_mk {α : Sort u_1} {p : α → Prop} (a : α) (h : p a) : ↑{ val := a, property := h } = a :=\n rfl\n\n@[simp] theorem mk_eq_mk {α : Sort u_1} {p : α → Prop} {a : α} {h : p a} {a' : α} {h' : p a'} : { val := a, property := h } = { val := a', property := h' } ↔ a = a' :=\n ext_iff\n\ntheorem coe_eq_iff {α : Sort u_1} {p : α → Prop} {a : Subtype fun (a : α) => p a} {b : α} : ↑a = b ↔ ∃ (h : p b), a = { val := b, property := h } := sorry\n\ntheorem coe_injective {α : Sort u_1} {p : α → Prop} : function.injective coe :=\n fun (a b : Subtype p) => subtype.ext\n\ntheorem val_injective {α : Sort u_1} {p : α → Prop} : function.injective val :=\n coe_injective\n\n/-- Restrict a (dependent) function to a subtype -/\ndef restrict {α : Sort u_1} {β : α → Type u_2} (f : (x : α) → β x) (p : α → Prop) (x : Subtype p) : β (val x) :=\n f ↑x\n\ntheorem restrict_apply {α : Sort u_1} {β : α → Type u_2} (f : (x : α) → β x) (p : α → Prop) (x : Subtype p) : restrict f p x = f (val x) :=\n Eq.refl (restrict f p x)\n\ntheorem restrict_def {α : Sort u_1} {β : Type u_2} (f : α → β) (p : α → Prop) : restrict f p = f ∘ coe :=\n Eq.refl (restrict f p)\n\ntheorem restrict_injective {α : Sort u_1} {β : Type u_2} {f : α → β} (p : α → Prop) (h : function.injective f) : function.injective (restrict f p) :=\n function.injective.comp h coe_injective\n\n/-- Defining a map into a subtype, this can be seen as an \"coinduction principle\" of `subtype`-/\ndef coind {α : Sort u_1} {β : Sort u_2} (f : α → β) {p : β → Prop} (h : ∀ (a : α), p (f a)) : α → Subtype p :=\n fun (a : α) => { val := f a, property := h a }\n\ntheorem coind_injective {α : Sort u_1} {β : Sort u_2} {f : α → β} {p : β → Prop} (h : ∀ (a : α), p (f a)) (hf : function.injective f) : function.injective (coind f h) :=\n fun (x y : α) (hxy : coind f h x = coind f h y) => hf (congr_arg val hxy)\n\ntheorem coind_surjective {α : Sort u_1} {β : Sort u_2} {f : α → β} {p : β → Prop} (h : ∀ (a : α), p (f a)) (hf : function.surjective f) : function.surjective (coind f h) := sorry\n\ntheorem coind_bijective {α : Sort u_1} {β : Sort u_2} {f : α → β} {p : β → Prop} (h : ∀ (a : α), p (f a)) (hf : function.bijective f) : function.bijective (coind f h) :=\n { left := coind_injective h (and.left hf), right := coind_surjective h (and.right hf) }\n\n/-- Restriction of a function to a function on subtypes. -/\n@[simp] theorem map_coe {α : Sort u_1} {β : Sort u_2} {p : α → Prop} {q : β → Prop} (f : α → β) (h : ∀ (a : α), p a → q (f a)) : ∀ (ᾰ : Subtype p), ↑(map f h ᾰ) = f ↑ᾰ :=\n fun (ᾰ : Subtype p) => Eq.refl ↑(map f h ᾰ)\n\ntheorem map_comp {α : Sort u_1} {β : Sort u_2} {γ : Sort u_3} {p : α → Prop} {q : β → Prop} {r : γ → Prop} {x : Subtype p} (f : α → β) (h : ∀ (a : α), p a → q (f a)) (g : β → γ) (l : ∀ (a : β), q a → r (g a)) : map g l (map f h x) = map (g ∘ f) (fun (a : α) (ha : p a) => l (f a) (h a ha)) x :=\n rfl\n\ntheorem map_id {α : Sort u_1} {p : α → Prop} {h : ∀ (a : α), p a → p (id a)} : map id h = id := sorry\n\ntheorem map_injective {α : Sort u_1} {β : Sort u_2} {p : α → Prop} {q : β → Prop} {f : α → β} (h : ∀ (a : α), p a → q (f a)) (hf : function.injective f) : function.injective (map f h) :=\n coind_injective (fun (x : Subtype fun (a : α) => p a) => map._proof_1 f h x) (function.injective.comp hf coe_injective)\n\ntheorem map_involutive {α : Sort u_1} {p : α → Prop} {f : α → α} (h : ∀ (a : α), p a → p (f a)) (hf : function.involutive f) : function.involutive (map f h) :=\n fun (x : Subtype fun (a : α) => p a) => subtype.ext (hf ↑x)\n\nprotected instance has_equiv {α : Sort u_1} [has_equiv α] (p : α → Prop) : has_equiv (Subtype p) :=\n has_equiv.mk fun (s t : Subtype p) => ↑s ≈ ↑t\n\ntheorem equiv_iff {α : Sort u_1} [has_equiv α] {p : α → Prop} {s : Subtype p} {t : Subtype p} : s ≈ t ↔ ↑s ≈ ↑t :=\n iff.rfl\n\nprotected theorem refl {α : Sort u_1} {p : α → Prop} [setoid α] (s : Subtype p) : s ≈ s :=\n setoid.refl ↑s\n\nprotected theorem symm {α : Sort u_1} {p : α → Prop} [setoid α] {s : Subtype p} {t : Subtype p} (h : s ≈ t) : t ≈ s :=\n setoid.symm h\n\nprotected theorem trans {α : Sort u_1} {p : α → Prop} [setoid α] {s : Subtype p} {t : Subtype p} {u : Subtype p} (h₁ : s ≈ t) (h₂ : t ≈ u) : s ≈ u :=\n setoid.trans h₁ h₂\n\ntheorem equivalence {α : Sort u_1} [setoid α] (p : α → Prop) : equivalence has_equiv.equiv :=\n mk_equivalence has_equiv.equiv subtype.refl subtype.symm subtype.trans\n\nprotected instance setoid {α : Sort u_1} [setoid α] (p : α → Prop) : setoid (Subtype p) :=\n setoid.mk has_equiv.equiv (equivalence p)\n\nend subtype\n\n\nnamespace subtype\n\n\n/-! Some facts about sets, which require that `α` is a type. -/\n\n@[simp] theorem coe_prop {α : Type u_1} {S : set α} (a : Subtype fun (a : α) => a ∈ S) : ↑a ∈ S :=\n prop a\n\ntheorem val_prop {α : Type u_1} {S : set α} (a : Subtype fun (a : α) => a ∈ S) : val a ∈ S :=\n property a\n\n", "meta": {"author": "AurelienSaue", "repo": "Mathlib4_auto", "sha": "590df64109b08190abe22358fabc3eae000943f2", "save_path": "github-repos/lean/AurelienSaue-Mathlib4_auto", "path": "github-repos/lean/AurelienSaue-Mathlib4_auto/Mathlib4_auto-590df64109b08190abe22358fabc3eae000943f2/Mathlib/data/subtype.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.33458944125318596, "lm_q2_score": 0.043365797063917993, "lm_q1q2_score": 0.014509737809115374}} {"text": "-- Copyright (c) 2018 Scott Morrison. All rights reserved.\n-- Released under Apache 2.0 license as described in the file LICENSE.\n-- Authors: Reid Barton, Mario Carneiro, Scott Morrison\n\nimport category_theory.whiskering\nimport category_theory.yoneda\nimport category_theory.limits.cones\n\nopen category_theory category_theory.category category_theory.functor\n\nnamespace category_theory.limits\n\nuniverses v u u' u'' w -- declare the `v`'s first; see `category_theory.category` for an explanation\n\nvariables {J : Type v} [small_category J]\nvariables {C : Type u} [𝒞 : category.{v} C]\ninclude 𝒞\n\nvariables {F : J ⥤ C}\n\n/-- A cone `t` on `F` is a limit cone if each cone on `F` admits a unique\n cone morphism to `t`. -/\nstructure is_limit (t : cone F) :=\n(lift : Π (s : cone F), s.X ⟶ t.X)\n(fac' : ∀ (s : cone F) (j : J), lift s ≫ t.π.app j = s.π.app j . obviously)\n(uniq' : ∀ (s : cone F) (m : s.X ⟶ t.X) (w : ∀ j : J, m ≫ t.π.app j = s.π.app j),\n m = lift s . obviously)\n\nrestate_axiom is_limit.fac'\nattribute [simp] is_limit.fac\nrestate_axiom is_limit.uniq'\n\nnamespace is_limit\n\ninstance subsingleton {t : cone F} : subsingleton (is_limit t) :=\n⟨by intros P Q; cases P; cases Q; congr; ext; solve_by_elim⟩\n\n/- Repackaging the definition in terms of cone morphisms. -/\n\ndef lift_cone_morphism {t : cone F} (h : is_limit t) (s : cone F) : s ⟶ t :=\n{ hom := h.lift s }\n\nlemma uniq_cone_morphism {s t : cone F} (h : is_limit t) {f f' : s ⟶ t} :\n f = f' :=\nhave ∀ {g : s ⟶ t}, g = h.lift_cone_morphism s, by intro g; ext; exact h.uniq _ _ g.w,\nthis.trans this.symm\n\ndef mk_cone_morphism {t : cone F}\n (lift : Π (s : cone F), s ⟶ t)\n (uniq' : ∀ (s : cone F) (m : s ⟶ t), m = lift s) : is_limit t :=\n{ lift := λ s, (lift s).hom,\n uniq' := λ s m w,\n have cone_morphism.mk m w = lift s, by apply uniq',\n congr_arg cone_morphism.hom this }\n\n/-- Limit cones on `F` are unique up to isomorphism. -/\ndef unique {s t : cone F} (P : is_limit s) (Q : is_limit t) : s ≅ t :=\n{ hom := Q.lift_cone_morphism s,\n inv := P.lift_cone_morphism t,\n hom_inv_id' := P.uniq_cone_morphism,\n inv_hom_id' := Q.uniq_cone_morphism }\n\ndef of_iso_limit {r t : cone F} (P : is_limit r) (i : r ≅ t) : is_limit t :=\nis_limit.mk_cone_morphism\n (λ s, P.lift_cone_morphism s ≫ i.hom)\n (λ s m, by rw ←i.comp_inv_eq; apply P.uniq_cone_morphism)\n\nvariables {t : cone F}\n\nlemma hom_lift (h : is_limit t) {W : C} (m : W ⟶ t.X) :\n m = h.lift { X := W, π := { app := λ b, m ≫ t.π.app b } } :=\nh.uniq { X := W, π := { app := λ b, m ≫ t.π.app b } } m (λ b, rfl)\n\n/-- Two morphisms into a limit are equal if their compositions with\n each cone morphism are equal. -/\nlemma hom_ext (h : is_limit t) {W : C} {f f' : W ⟶ t.X}\n (w : ∀ j, f ≫ t.π.app j = f' ≫ t.π.app j) : f = f' :=\nby rw [h.hom_lift f, h.hom_lift f']; congr; exact funext w\n\n/-- The universal property of a limit cone: a map `W ⟶ X` is the same as\n a cone on `F` with vertex `W`. -/\ndef hom_iso (h : is_limit t) (W : C) : (W ⟶ t.X) ≅ ((const J).obj W ⟹ F) :=\n{ hom := λ f, (t.extend f).π,\n inv := λ π, h.lift { X := W, π := π },\n hom_inv_id' := by ext f; apply h.hom_ext; intro j; simp; dsimp; refl }\n\n@[simp] lemma hom_iso_hom (h : is_limit t) {W : C} (f : W ⟶ t.X) :\n (is_limit.hom_iso h W).hom f = (t.extend f).π := rfl\n\n/-- The limit of `F` represents the functor taking `W` to\n the set of cones on `F` with vertex `W`. -/\ndef nat_iso (h : is_limit t) : yoneda.obj t.X ≅ F.cones :=\nnat_iso.of_components (λ W, is_limit.hom_iso h (unop W)) (by tidy)\n\ndef hom_iso' (h : is_limit t) (W : C) :\n (W ⟶ t.X) ≅ { p : Π j, W ⟶ F.obj j // ∀ {j j'} (f : j ⟶ j'), p j ≫ F.map f = p j' } :=\nh.hom_iso W ≪≫\n{ hom := λ π,\n ⟨λ j, π.app j, λ j j' f,\n by convert ←(π.naturality f).symm; apply id_comp⟩,\n inv := λ p,\n { app := λ j, p.1 j,\n naturality' := λ j j' f, begin dsimp, rw [id_comp], exact (p.2 f).symm end } }\n\n/-- If G : C → D is a faithful functor which sends t to a limit cone,\n then it suffices to check that the induced maps for the image of t\n can be lifted to maps of C. -/\ndef of_faithful {t : cone F} {D : Type u'} [category.{v} D] (G : C ⥤ D) [faithful G]\n (ht : is_limit (G.map_cone t)) (lift : Π (s : cone F), s.X ⟶ t.X)\n (h : ∀ s, G.map (lift s) = ht.lift (G.map_cone s)) : is_limit t :=\n{ lift := lift,\n fac' := λ s j, by apply G.injectivity; rw [G.map_comp, h]; apply ht.fac,\n uniq' := λ s m w, begin\n apply G.injectivity, rw h,\n refine ht.uniq (G.map_cone s) _ (λ j, _),\n convert ←congr_arg (λ f, G.map f) (w j),\n apply G.map_comp\n end }\n\nend is_limit\n\ndef is_limit_iso_unique_cone_morphism {t : cone F} :\n is_limit t ≅ Π s, unique (s ⟶ t) :=\n{ hom := λ h s,\n { default := h.lift_cone_morphism s,\n uniq := λ _, h.uniq_cone_morphism },\n inv := λ h,\n { lift := λ s, (h s).default.hom,\n uniq' := λ s f w, congr_arg cone_morphism.hom ((h s).uniq ⟨f, w⟩) } }\n\n/-- A cocone `t` on `F` is a colimit cocone if each cocone on `F` admits a unique\n cocone morphism from `t`. -/\nstructure is_colimit (t : cocone F) :=\n(desc : Π (s : cocone F), t.X ⟶ s.X)\n(fac' : ∀ (s : cocone F) (j : J), t.ι.app j ≫ desc s = s.ι.app j . obviously)\n(uniq' : ∀ (s : cocone F) (m : t.X ⟶ s.X) (w : ∀ j : J, t.ι.app j ≫ m = s.ι.app j),\n m = desc s . obviously)\n\nrestate_axiom is_colimit.fac'\nattribute [simp] is_colimit.fac\nrestate_axiom is_colimit.uniq'\n\nnamespace is_colimit\n\ninstance subsingleton {t : cocone F} : subsingleton (is_colimit t) :=\n⟨by intros P Q; cases P; cases Q; congr; ext; solve_by_elim⟩\n\n/- Repackaging the definition in terms of cone morphisms. -/\n\ndef desc_cocone_morphism {t : cocone F} (h : is_colimit t) (s : cocone F) : t ⟶ s :=\n{ hom := h.desc s }\n\nlemma uniq_cocone_morphism {s t : cocone F} (h : is_colimit t) {f f' : t ⟶ s} :\n f = f' :=\nhave ∀ {g : t ⟶ s}, g = h.desc_cocone_morphism s, by intro g; ext; exact h.uniq _ _ g.w,\nthis.trans this.symm\n\ndef mk_cocone_morphism {t : cocone F}\n (desc : Π (s : cocone F), t ⟶ s)\n (uniq' : ∀ (s : cocone F) (m : t ⟶ s), m = desc s) : is_colimit t :=\n{ desc := λ s, (desc s).hom,\n uniq' := λ s m w,\n have cocone_morphism.mk m w = desc s, by apply uniq',\n congr_arg cocone_morphism.hom this }\n\n/-- Limit cones on `F` are unique up to isomorphism. -/\ndef unique {s t : cocone F} (P : is_colimit s) (Q : is_colimit t) : s ≅ t :=\n{ hom := P.desc_cocone_morphism t,\n inv := Q.desc_cocone_morphism s,\n hom_inv_id' := P.uniq_cocone_morphism,\n inv_hom_id' := Q.uniq_cocone_morphism }\n\ndef of_iso_colimit {r t : cocone F} (P : is_colimit r) (i : r ≅ t) : is_colimit t :=\nis_colimit.mk_cocone_morphism\n (λ s, i.inv ≫ P.desc_cocone_morphism s)\n (λ s m, by rw i.eq_inv_comp; apply P.uniq_cocone_morphism)\n\nvariables {t : cocone F}\n\nlemma hom_desc (h : is_colimit t) {W : C} (m : t.X ⟶ W) :\n m = h.desc { X := W, ι := { app := λ b, t.ι.app b ≫ m,\n naturality' := by intros; erw [←assoc, t.ι.naturality, comp_id, comp_id] } } :=\nh.uniq { X := W, ι := { app := λ b, t.ι.app b ≫ m, naturality' := _ } } m (λ b, rfl)\n\n/-- Two morphisms out of a colimit are equal if their compositions with\n each cocone morphism are equal. -/\nlemma hom_ext (h : is_colimit t) {W : C} {f f' : t.X ⟶ W}\n (w : ∀ j, t.ι.app j ≫ f = t.ι.app j ≫ f') : f = f' :=\nby rw [h.hom_desc f, h.hom_desc f']; congr; exact funext w\n\n/-- The universal property of a colimit cocone: a map `X ⟶ W` is the same as\n a cocone on `F` with vertex `W`. -/\ndef hom_iso (h : is_colimit t) (W : C) : (t.X ⟶ W) ≅ (F ⟹ (const J).obj W) :=\n{ hom := λ f, (t.extend f).ι,\n inv := λ ι, h.desc { X := W, ι := ι },\n hom_inv_id' := by ext f; apply h.hom_ext; intro j; simp; dsimp; refl }\n\n@[simp] lemma hom_iso_hom (h : is_colimit t) {W : C} (f : t.X ⟶ W) :\n (is_colimit.hom_iso h W).hom f = (t.extend f).ι := rfl\n\n/-- The colimit of `F` represents the functor taking `W` to\n the set of cocones on `F` with vertex `W`. -/\ndef nat_iso (h : is_colimit t) : coyoneda.obj (op t.X) ≅ F.cocones :=\nnat_iso.of_components (is_colimit.hom_iso h) (by intros; ext; dsimp; rw ←assoc; refl)\n\ndef hom_iso' (h : is_colimit t) (W : C) :\n (t.X ⟶ W) ≅ { p : Π j, F.obj j ⟶ W // ∀ {j j' : J} (f : j ⟶ j'), F.map f ≫ p j' = p j } :=\nh.hom_iso W ≪≫\n{ hom := λ ι,\n ⟨λ j, ι.app j, λ j j' f,\n by convert ←(ι.naturality f); apply comp_id⟩,\n inv := λ p,\n { app := λ j, p.1 j,\n naturality' := λ j j' f, begin dsimp, rw [comp_id], exact (p.2 f) end } }\n\n/-- If G : C → D is a faithful functor which sends t to a colimit cocone,\n then it suffices to check that the induced maps for the image of t\n can be lifted to maps of C. -/\ndef of_faithful {t : cocone F} {D : Type u'} [category.{v} D] (G : C ⥤ D) [faithful G]\n (ht : is_colimit (G.map_cocone t)) (desc : Π (s : cocone F), t.X ⟶ s.X)\n (h : ∀ s, G.map (desc s) = ht.desc (G.map_cocone s)) : is_colimit t :=\n{ desc := desc,\n fac' := λ s j, by apply G.injectivity; rw [G.map_comp, h]; apply ht.fac,\n uniq' := λ s m w, begin\n apply G.injectivity, rw h,\n refine ht.uniq (G.map_cocone s) _ (λ j, _),\n convert ←congr_arg (λ f, G.map f) (w j),\n apply G.map_comp\n end }\n\nend is_colimit\n\ndef is_colimit_iso_unique_cocone_morphism {t : cocone F} :\n is_colimit t ≅ Π s, unique (t ⟶ s) :=\n{ hom := λ h s,\n { default := h.desc_cocone_morphism s,\n uniq := λ _, h.uniq_cocone_morphism },\n inv := λ h,\n { desc := λ s, (h s).default.hom,\n uniq' := λ s f w, congr_arg cocone_morphism.hom ((h s).uniq ⟨f, w⟩) } }\n\nsection limit\n\n/-- `has_limit F` represents a particular chosen limit of the diagram `F`. -/\nclass has_limit (F : J ⥤ C) :=\n(cone : cone F)\n(is_limit : is_limit cone)\n\nvariables (J C)\n\n/-- `C` has limits of shape `J` if we have chosen a particular limit of\n every functor `F : J ⥤ C`. -/\n@[class] def has_limits_of_shape := Π F : J ⥤ C, has_limit F\n\n/-- `C` has all (small) limits if it has limits of every shape. -/\n@[class] def has_limits :=\nΠ {J : Type v} {𝒥 : small_category J}, by exactI has_limits_of_shape J C\n\nvariables {J C}\n\ninstance has_limit_of_has_limits_of_shape\n {J : Type v} [small_category J] [H : has_limits_of_shape J C] (F : J ⥤ C) : has_limit F :=\nH F\n\ninstance has_limits_of_shape_of_has_limits\n {J : Type v} [small_category J] [H : has_limits.{v} C] : has_limits_of_shape J C :=\nH\n\n/- Interface to the `has_limit` class. -/\n\ndef limit.cone (F : J ⥤ C) [has_limit F] : cone F := has_limit.cone F\n\ndef limit (F : J ⥤ C) [has_limit F] := (limit.cone F).X\n\ndef limit.π (F : J ⥤ C) [has_limit F] (j : J) : limit F ⟶ F.obj j :=\n(limit.cone F).π.app j\n\n@[simp] lemma limit.cone_π {F : J ⥤ C} [has_limit F] (j : J) :\n (limit.cone F).π.app j = limit.π _ j := rfl\n\n@[simp] lemma limit.w (F : J ⥤ C) [has_limit F] {j j' : J} (f : j ⟶ j') :\n limit.π F j ≫ F.map f = limit.π F j' := (limit.cone F).w f\n\ndef limit.is_limit (F : J ⥤ C) [has_limit F] : is_limit (limit.cone F) :=\nhas_limit.is_limit.{v} F\n\ndef limit.lift (F : J ⥤ C) [has_limit F] (c : cone F) : c.X ⟶ limit F :=\n(limit.is_limit F).lift c\n\n@[simp] lemma limit.is_limit_lift {F : J ⥤ C} [has_limit F] (c : cone F) :\n (limit.is_limit F).lift c = limit.lift F c := rfl\n\n@[simp] lemma limit.lift_π {F : J ⥤ C} [has_limit F] (c : cone F) (j : J) :\n limit.lift F c ≫ limit.π F j = c.π.app j :=\nis_limit.fac _ c j\n\ndef limit.cone_morphism {F : J ⥤ C} [has_limit F] (c : cone F) :\n cone_morphism c (limit.cone F) :=\n(limit.is_limit F).lift_cone_morphism c\n\n@[simp] lemma limit.cone_morphism_hom {F : J ⥤ C} [has_limit F] (c : cone F) :\n (limit.cone_morphism c).hom = limit.lift F c := rfl\n@[simp] lemma limit.cone_morphism_π {F : J ⥤ C} [has_limit F] (c : cone F) (j : J) :\n (limit.cone_morphism c).hom ≫ limit.π F j = c.π.app j :=\nby erw is_limit.fac\n\n@[extensionality] lemma limit.hom_ext {F : J ⥤ C} [has_limit F] {X : C} {f f' : X ⟶ limit F}\n (w : ∀ j, f ≫ limit.π F j = f' ≫ limit.π F j) : f = f' :=\n(limit.is_limit F).hom_ext w\n\ndef limit.hom_iso (F : J ⥤ C) [has_limit F] (W : C) : (W ⟶ limit F) ≅ (F.cones.obj (op W)) :=\n(limit.is_limit F).hom_iso W\n\n@[simp] lemma limit.hom_iso_hom (F : J ⥤ C) [has_limit F] {W : C} (f : W ⟶ limit F):\n (limit.hom_iso F W).hom f = (const J).map f ≫ (limit.cone F).π :=\n(limit.is_limit F).hom_iso_hom f\n\ndef limit.hom_iso' (F : J ⥤ C) [has_limit F] (W : C) :\n (W ⟶ limit F) ≅ { p : Π j, W ⟶ F.obj j // ∀ {j j' : J} (f : j ⟶ j'), p j ≫ F.map f = p j' } :=\n(limit.is_limit F).hom_iso' W\n\nlemma limit.lift_extend {F : J ⥤ C} [has_limit F] (c : cone F) {X : C} (f : X ⟶ c.X) :\n limit.lift F (c.extend f) = f ≫ limit.lift F c :=\nby obviously\n\nsection pre\nvariables {K : Type v} [small_category K]\nvariables (F) [has_limit F] (E : K ⥤ J) [has_limit (E ⋙ F)]\n\ndef limit.pre : limit F ⟶ limit (E ⋙ F) :=\nlimit.lift (E ⋙ F)\n { X := limit F,\n π := { app := λ k, limit.π F (E.obj k) } }\n\n@[simp] lemma limit.pre_π (k : K) : limit.pre F E ≫ limit.π (E ⋙ F) k = limit.π F (E.obj k) :=\nby erw is_limit.fac\n\n@[simp] lemma limit.lift_pre (c : cone F) :\n limit.lift F c ≫ limit.pre F E = limit.lift (E ⋙ F) (c.whisker E) :=\nby ext; simp\n\nvariables {L : Type v} [small_category L]\nvariables (D : L ⥤ K) [has_limit (D ⋙ E ⋙ F)]\n\n@[simp] lemma limit.pre_pre : limit.pre F E ≫ limit.pre (E ⋙ F) D = limit.pre F (D ⋙ E) :=\nby ext j; erw [assoc, limit.pre_π, limit.pre_π, limit.pre_π]; refl\n\nend pre\n\nsection post\nvariables {D : Type u'} [𝒟 : category.{v} D]\ninclude 𝒟\n\nvariables (F) [has_limit F] (G : C ⥤ D) [has_limit (F ⋙ G)]\n\ndef limit.post : G.obj (limit F) ⟶ limit (F ⋙ G) :=\nlimit.lift (F ⋙ G)\n{ X := G.obj (limit F),\n π :=\n { app := λ j, G.map (limit.π F j),\n naturality' :=\n by intros j j' f; erw [←G.map_comp, limits.cone.w, id_comp]; refl } }\n\n@[simp] lemma limit.post_π (j : J) : limit.post F G ≫ limit.π (F ⋙ G) j = G.map (limit.π F j) :=\nby erw is_limit.fac\n\n@[simp] lemma limit.lift_post (c : cone F) :\n G.map (limit.lift F c) ≫ limit.post F G = limit.lift (F ⋙ G) (G.map_cone c) :=\nby ext; rw [assoc, limit.post_π, ←G.map_comp, limit.lift_π, limit.lift_π]; refl\n\n@[simp] lemma limit.post_post\n {E : Type u''} [category.{v} E] (H : D ⥤ E) [has_limit ((F ⋙ G) ⋙ H)] :\n/- H G (limit F) ⟶ H (limit (F ⋙ G)) ⟶ limit ((F ⋙ G) ⋙ H) equals -/\n/- H G (limit F) ⟶ limit (F ⋙ (G ⋙ H)) -/\n H.map (limit.post F G) ≫ limit.post (F ⋙ G) H = limit.post F (G ⋙ H) :=\nby ext; erw [assoc, limit.post_π, ←H.map_comp, limit.post_π, limit.post_π]; refl\n\nend post\n\nlemma limit.pre_post {K : Type v} [small_category K] {D : Type u'} [category.{v} D]\n (E : K ⥤ J) (F : J ⥤ C) (G : C ⥤ D)\n [has_limit F] [has_limit (E ⋙ F)] [has_limit (F ⋙ G)] [has_limit ((E ⋙ F) ⋙ G)] :\n/- G (limit F) ⟶ G (limit (E ⋙ F)) ⟶ limit ((E ⋙ F) ⋙ G) vs -/\n/- G (limit F) ⟶ limit F ⋙ G ⟶ limit (E ⋙ (F ⋙ G)) or -/\n G.map (limit.pre F E) ≫ limit.post (E ⋙ F) G = limit.post F G ≫ limit.pre (F ⋙ G) E :=\nby ext; erw [assoc, limit.post_π, ←G.map_comp, limit.pre_π, assoc, limit.pre_π, limit.post_π]; refl\n\nsection lim_functor\n\nvariables [has_limits_of_shape J C]\n\n/-- `limit F` is functorial in `F`, when `C` has all limits of shape `J`. -/\ndef lim : (J ⥤ C) ⥤ C :=\n{ obj := λ F, limit F,\n map := λ F G α, limit.lift G\n { X := limit F,\n π :=\n { app := λ j, limit.π F j ≫ α.app j,\n naturality' := λ j j' f,\n by erw [id_comp, assoc, ←α.naturality, ←assoc, limit.w] } },\n map_comp' := λ F G H α β,\n by ext; erw [assoc, is_limit.fac, is_limit.fac, ←assoc, is_limit.fac, assoc]; refl }\n\nvariables {F} {G : J ⥤ C} (α : F ⟹ G)\n\n@[simp] lemma lim.map_π (j : J) : lim.map α ≫ limit.π G j = limit.π F j ≫ α.app j :=\nby apply is_limit.fac\n\n@[simp] lemma limit.lift_map (c : cone F) :\n limit.lift F c ≫ lim.map α = limit.lift G ((cones.postcompose α).obj c) :=\nby ext; rw [assoc, lim.map_π, ←assoc, limit.lift_π, limit.lift_π]; refl\n\nlemma limit.map_pre {K : Type v} [small_category K] [has_limits_of_shape K C] (E : K ⥤ J) :\n lim.map α ≫ limit.pre G E = limit.pre F E ≫ lim.map (whisker_left E α) :=\nby ext; rw [assoc, limit.pre_π, lim.map_π, assoc, lim.map_π, ←assoc, limit.pre_π]; refl\n\nlemma limit.map_pre' {K : Type v} [small_category K] [has_limits_of_shape.{v} K C]\n (F : J ⥤ C) {E₁ E₂ : K ⥤ J} (α : E₁ ⟹ E₂) :\n limit.pre F E₂ = limit.pre F E₁ ≫ lim.map (whisker_right α F) :=\nby ext1; simp [(category.assoc _ _ _ _).symm]\n\nlemma limit.id_pre (F : J ⥤ C) :\nlimit.pre F (functor.id _) = lim.map (functor.left_unitor F).inv := by tidy\n\nlemma limit.map_post {D : Type u'} [category.{v} D] [has_limits_of_shape J D] (H : C ⥤ D) :\n/- H (limit F) ⟶ H (limit G) ⟶ limit (G ⋙ H) vs\n H (limit F) ⟶ limit (F ⋙ H) ⟶ limit (G ⋙ H) -/\n H.map (lim.map α) ≫ limit.post G H = limit.post F H ≫ lim.map (whisker_right α H) :=\nbegin\n ext,\n rw [assoc, limit.post_π, ←H.map_comp, lim.map_π, H.map_comp],\n rw [assoc, lim.map_π, ←assoc, limit.post_π],\n refl\nend\n\ndef lim_yoneda : lim ⋙ yoneda ≅ category_theory.cones J C :=\nnat_iso.of_components (λ F, nat_iso.of_components (λ W, limit.hom_iso F (unop W)) (by tidy))\n (by tidy)\n\nend lim_functor\n\nend limit\n\n\nsection colimit\n\n/-- `has_colimit F` represents a particular chosen colimit of the diagram `F`. -/\nclass has_colimit (F : J ⥤ C) :=\n(cocone : cocone F)\n(is_colimit : is_colimit cocone)\n\nvariables (J C)\n\n/-- `C` has colimits of shape `J` if we have chosen a particular colimit of\n every functor `F : J ⥤ C`. -/\n@[class] def has_colimits_of_shape := Π F : J ⥤ C, has_colimit F\n\n/-- `C` has all (small) colimits if it has limits of every shape. -/\n@[class] def has_colimits :=\nΠ {J : Type v} {𝒥 : small_category J}, by exactI has_colimits_of_shape J C\n\nvariables {J C}\n\ninstance has_colimit_of_has_colimits_of_shape\n {J : Type v} [small_category J] [H : has_colimits_of_shape J C] (F : J ⥤ C) : has_colimit F :=\nH F\n\ninstance has_colimits_of_shape_of_has_colimits\n {J : Type v} [small_category J] [H : has_colimits.{v} C] : has_colimits_of_shape J C :=\nH\n\n/- Interface to the `has_colimit` class. -/\n\ndef colimit.cocone (F : J ⥤ C) [has_colimit F] : cocone F := has_colimit.cocone F\n\ndef colimit (F : J ⥤ C) [has_colimit F] := (colimit.cocone F).X\n\ndef colimit.ι (F : J ⥤ C) [has_colimit F] (j : J) : F.obj j ⟶ colimit F :=\n(colimit.cocone F).ι.app j\n\n@[simp] lemma colimit.cocone_ι {F : J ⥤ C} [has_colimit F] (j : J) :\n (colimit.cocone F).ι.app j = colimit.ι _ j := rfl\n\n@[simp] lemma colimit.w (F : J ⥤ C) [has_colimit F] {j j' : J} (f : j ⟶ j') :\n F.map f ≫ colimit.ι F j' = colimit.ι F j := (colimit.cocone F).w f\n\ndef colimit.is_colimit (F : J ⥤ C) [has_colimit F] : is_colimit (colimit.cocone F) :=\nhas_colimit.is_colimit.{v} F\n\ndef colimit.desc (F : J ⥤ C) [has_colimit F] (c : cocone F) : colimit F ⟶ c.X :=\n(colimit.is_colimit F).desc c\n\n@[simp] lemma colimit.is_colimit_desc {F : J ⥤ C} [has_colimit F] (c : cocone F) :\n (colimit.is_colimit F).desc c = colimit.desc F c := rfl\n\n@[simp] lemma colimit.ι_desc {F : J ⥤ C} [has_colimit F] (c : cocone F) (j : J) :\n colimit.ι F j ≫ colimit.desc F c = c.ι.app j :=\nis_colimit.fac _ c j\n\ndef colimit.cocone_morphism {F : J ⥤ C} [has_colimit F] (c : cocone F) :\n cocone_morphism (colimit.cocone F) c :=\n(colimit.is_colimit F).desc_cocone_morphism c\n\n@[simp] lemma colimit.cocone_morphism_hom {F : J ⥤ C} [has_colimit F] (c : cocone F) :\n (colimit.cocone_morphism c).hom = colimit.desc F c := rfl\n@[simp] lemma colimit.ι_cocone_morphism {F : J ⥤ C} [has_colimit F] (c : cocone F) (j : J) :\n colimit.ι F j ≫ (colimit.cocone_morphism c).hom = c.ι.app j :=\nby erw is_colimit.fac\n\n@[extensionality] lemma colimit.hom_ext {F : J ⥤ C} [has_colimit F] {X : C} {f f' : colimit F ⟶ X}\n (w : ∀ j, colimit.ι F j ≫ f = colimit.ι F j ≫ f') : f = f' :=\n(colimit.is_colimit F).hom_ext w\n\ndef colimit.hom_iso (F : J ⥤ C) [has_colimit F] (W : C) : (colimit F ⟶ W) ≅ (F.cocones.obj W) :=\n(colimit.is_colimit F).hom_iso W\n\n@[simp] lemma colimit.hom_iso_hom (F : J ⥤ C) [has_colimit F] {W : C} (f : colimit F ⟶ W):\n (colimit.hom_iso F W).hom f = (colimit.cocone F).ι ≫ (const J).map f :=\n(colimit.is_colimit F).hom_iso_hom f\n\ndef colimit.hom_iso' (F : J ⥤ C) [has_colimit F] (W : C) :\n (colimit F ⟶ W) ≅ { p : Π j, F.obj j ⟶ W // ∀ {j j'} (f : j ⟶ j'), F.map f ≫ p j' = p j } :=\n(colimit.is_colimit F).hom_iso' W\n\nlemma colimit.desc_extend (F : J ⥤ C) [has_colimit F] (c : cocone F) {X : C} (f : c.X ⟶ X) :\n colimit.desc F (c.extend f) = colimit.desc F c ≫ f :=\nbegin\n ext1, simp [category.assoc_symm], refl\nend\n\nsection pre\nvariables {K : Type v} [small_category K]\nvariables (F) [has_colimit F] (E : K ⥤ J) [has_colimit (E ⋙ F)]\n\ndef colimit.pre : colimit (E ⋙ F) ⟶ colimit F :=\ncolimit.desc (E ⋙ F)\n { X := colimit F,\n ι := { app := λ k, colimit.ι F (E.obj k) } }\n\n@[simp] lemma colimit.ι_pre (k : K) : colimit.ι (E ⋙ F) k ≫ colimit.pre F E = colimit.ι F (E.obj k) :=\nby erw is_colimit.fac\n\n@[simp] lemma colimit.pre_desc (c : cocone F) :\n colimit.pre F E ≫ colimit.desc F c = colimit.desc (E ⋙ F) (c.whisker E) :=\nby ext; rw [←assoc, colimit.ι_pre]; simp\n\nvariables {L : Type v} [small_category L]\nvariables (D : L ⥤ K) [has_colimit (D ⋙ E ⋙ F)]\n\n@[simp] lemma colimit.pre_pre : colimit.pre (E ⋙ F) D ≫ colimit.pre F E = colimit.pre F (D ⋙ E) :=\nbegin\n ext j,\n rw [←assoc, colimit.ι_pre, colimit.ι_pre],\n letI : has_colimit ((D ⋙ E) ⋙ F) := show has_colimit (D ⋙ E ⋙ F), by apply_instance,\n exact (colimit.ι_pre F (D ⋙ E) j).symm\nend\n\nend pre\n\nsection post\nvariables {D : Type u'} [𝒟 : category.{v} D]\ninclude 𝒟\n\nvariables (F) [has_colimit F] (G : C ⥤ D) [has_colimit (F ⋙ G)]\n\ndef colimit.post : colimit (F ⋙ G) ⟶ G.obj (colimit F) :=\ncolimit.desc (F ⋙ G)\n{ X := G.obj (colimit F),\n ι :=\n { app := λ j, G.map (colimit.ι F j),\n naturality' :=\n by intros j j' f; erw [←G.map_comp, limits.cocone.w, comp_id]; refl } }\n\n@[simp] lemma colimit.ι_post (j : J) : colimit.ι (F ⋙ G) j ≫ colimit.post F G = G.map (colimit.ι F j) :=\nby erw is_colimit.fac\n\n@[simp] lemma colimit.post_desc (c : cocone F) :\n colimit.post F G ≫ G.map (colimit.desc F c) = colimit.desc (F ⋙ G) (G.map_cocone c) :=\nby ext; rw [←assoc, colimit.ι_post, ←G.map_comp, colimit.ι_desc, colimit.ι_desc]; refl\n\n@[simp] lemma colimit.post_post\n {E : Type u''} [category.{v} E] (H : D ⥤ E) [has_colimit ((F ⋙ G) ⋙ H)] :\n/- H G (colimit F) ⟶ H (colimit (F ⋙ G)) ⟶ colimit ((F ⋙ G) ⋙ H) equals -/\n/- H G (colimit F) ⟶ colimit (F ⋙ (G ⋙ H)) -/\n colimit.post (F ⋙ G) H ≫ H.map (colimit.post F G) = colimit.post F (G ⋙ H) :=\nbegin\n ext,\n rw [←assoc, colimit.ι_post, ←H.map_comp, colimit.ι_post],\n exact (colimit.ι_post F (G ⋙ H) j).symm\nend\n\nend post\n\nlemma colimit.pre_post {K : Type v} [small_category K] {D : Type u'} [category.{v} D]\n (E : K ⥤ J) (F : J ⥤ C) (G : C ⥤ D)\n [has_colimit F] [has_colimit (E ⋙ F)] [has_colimit (F ⋙ G)] [has_colimit ((E ⋙ F) ⋙ G)] :\n/- G (colimit F) ⟶ G (colimit (E ⋙ F)) ⟶ colimit ((E ⋙ F) ⋙ G) vs -/\n/- G (colimit F) ⟶ colimit F ⋙ G ⟶ colimit (E ⋙ (F ⋙ G)) or -/\n colimit.post (E ⋙ F) G ≫ G.map (colimit.pre F E) = colimit.pre (F ⋙ G) E ≫ colimit.post F G :=\nbegin\n ext,\n rw [←assoc, colimit.ι_post, ←G.map_comp, colimit.ι_pre, ←assoc],\n letI : has_colimit (E ⋙ F ⋙ G) := show has_colimit ((E ⋙ F) ⋙ G), by apply_instance,\n erw [colimit.ι_pre (F ⋙ G) E j, colimit.ι_post]\nend\n\nsection colim_functor\n\nvariables [has_colimits_of_shape J C]\n\n/-- `colimit F` is functorial in `F`, when `C` has all colimits of shape `J`. -/\ndef colim : (J ⥤ C) ⥤ C :=\n{ obj := λ F, colimit F,\n map := λ F G α, colimit.desc F\n { X := colimit G,\n ι :=\n { app := λ j, α.app j ≫ colimit.ι G j,\n naturality' := λ j j' f,\n by erw [comp_id, ←assoc, α.naturality, assoc, colimit.w] } },\n map_comp' := λ F G H α β,\n by ext; erw [←assoc, is_colimit.fac, is_colimit.fac, assoc, is_colimit.fac, ←assoc]; refl }\n\nvariables {F} {G : J ⥤ C} (α : F ⟹ G)\n\n@[simp] lemma colim.ι_map (j : J) : colimit.ι F j ≫ colim.map α = α.app j ≫ colimit.ι G j :=\nby apply is_colimit.fac\n\n@[simp] lemma colimit.map_desc (c : cocone G) :\n colim.map α ≫ colimit.desc G c = colimit.desc F ((cocones.precompose α).obj c) :=\nby ext; rw [←assoc, colim.ι_map, assoc, colimit.ι_desc, colimit.ι_desc]; refl\n\nlemma colimit.pre_map {K : Type v} [small_category K] [has_colimits_of_shape K C] (E : K ⥤ J) :\n colimit.pre F E ≫ colim.map α = colim.map (whisker_left E α) ≫ colimit.pre G E :=\nby ext; rw [←assoc, colimit.ι_pre, colim.ι_map, ←assoc, colim.ι_map, assoc, colimit.ι_pre]; refl\n\nlemma colimit.pre_map' {K : Type v} [small_category K] [has_colimits_of_shape.{v} K C]\n (F : J ⥤ C) {E₁ E₂ : K ⥤ J} (α : E₁ ⟹ E₂) :\n colimit.pre F E₁ = colim.map (whisker_right α F) ≫ colimit.pre F E₂ :=\nby ext1; simp [(category.assoc _ _ _ _).symm]\n\nlemma colimit.pre_id (F : J ⥤ C) :\ncolimit.pre F (functor.id _) = colim.map (functor.left_unitor F).hom := by tidy\n\nlemma colimit.map_post {D : Type u'} [category.{v} D] [has_colimits_of_shape J D] (H : C ⥤ D) :\n/- H (colimit F) ⟶ H (colimit G) ⟶ colimit (G ⋙ H) vs\n H (colimit F) ⟶ colimit (F ⋙ H) ⟶ colimit (G ⋙ H) -/\n colimit.post F H ≫ H.map (colim.map α) = colim.map (whisker_right α H) ≫ colimit.post G H:=\nbegin\n ext,\n rw [←assoc, colimit.ι_post, ←H.map_comp, colim.ι_map, H.map_comp],\n rw [←assoc, colim.ι_map, assoc, colimit.ι_post],\n refl\nend\n\ndef colim_coyoneda : colim.op ⋙ coyoneda ≅ category_theory.cocones J C :=\nnat_iso.of_components (λ F, nat_iso.of_components (colimit.hom_iso (unop F)) (by tidy))\n (by {tidy, rw [← category.assoc,← category.assoc], tidy})\n\nend colim_functor\n\nend colimit\n\nend category_theory.limits\n", "meta": {"author": "digama0", "repo": "mathlib-ITP2019", "sha": "5cbd0362e04e671ef5db1284870592af6950197c", "save_path": "github-repos/lean/digama0-mathlib-ITP2019", "path": "github-repos/lean/digama0-mathlib-ITP2019/mathlib-ITP2019-5cbd0362e04e671ef5db1284870592af6950197c/src/category_theory/limits/limits.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4416730056646256, "lm_q2_score": 0.032589746057971644, "lm_q1q2_score": 0.01439401109527122}} {"text": "import operations\nimport params\nimport littleendian\n\nimport category_theory.category.basic\nimport category_theory.core\n\nopen operations\nopen params\nopen littleendian\n\nopen category_theory\n\nnamespace utils\n\nvariables [category (bitvec word_len)]\n\n/-!\n # Utilities\n-/\n\n\n-- A random input matrix to be used as `rowround` and `columnround` inputs. \nvariable M : matrixType\n\n/--\n Prepare the `rowround` matrix input.\n\n Any `rowround` input matrix is in the form:\n\n (y₀, y₁, y₂, y₃)\n (y₄, y₅, y₆, y₇)\n (y₈, y₉, y₁₀, y₁₁)\n (y₁₂, y₁₃, y₁₄, y₁₅)\n\n But we need this to be converted to:\n\n (y₀, y₁, y₂, y₃)\n (y₅, y₆, y₇, y₄)\n (y₁₀, y₁₁, y₈, y₉)\n (y₁₅, y₁₂, y₁₃, y₁₄) \n-/\n@[simp] def rowround_input : matrixType :=\n (\n ((M.fst).fst, (M.fst).snd.fst, (M.fst).snd.snd.fst, (M.fst).snd.snd.snd),\n ((M.snd.fst).snd.fst, (M.snd.fst).snd.snd.fst, (M.snd.fst).snd.snd.snd, (M.snd.fst).fst),\n ((M.snd.snd.fst).snd.snd.fst, (M.snd.snd.fst).snd.snd.snd, (M.snd.snd.fst).fst, (M.snd.snd.fst).snd.fst),\n ((M.snd.snd.snd).snd.snd.snd, (M.snd.snd.snd).fst, (M.snd.snd.snd).snd.fst, (M.snd.snd.snd).snd.snd.fst)\n )\n\n/--\n Prepare the `rowround` matrix output.\n\n Any `rowround` output matrix is of the form:\n\n (z₀, z₁, z₂, z₃)\n (z₅, z₆, z₇, z₄)\n (z₁₀, z₁₁, z₈, z₉)\n (z₁₅, z₁₂, z₁₃, z₁₄) \n\n But we need this to be converted to:\n\n (z₀, z₁, z₂, z₃)\n (z₄, z₅, z₆, z₇)\n (z₈, z₉, z₁₀, z₁₁)\n (z₁₂, z₁₃, z₁₄, z₁₅)\n-/\n@[simp] def rowround_output : matrixType :=\n (\n ((M.fst).fst, (M.fst).snd.fst, (M.fst).snd.snd.fst, (M.fst).snd.snd.snd),\n ((M.snd.fst).snd.snd.snd, (M.snd.fst).fst, (M.snd.fst).snd.fst, (M.snd.fst).snd.snd.fst),\n ((M.snd.snd.fst).snd.snd.fst, (M.snd.snd.fst).snd.snd.snd, (M.snd.snd.fst).fst, (M.snd.snd.fst).snd.fst),\n ((M.snd.snd.snd).snd.fst, (M.snd.snd.snd).snd.snd.fst, (M.snd.snd.snd).snd.snd.snd, (M.snd.snd.snd).fst)\n )\n\n/-- The `rowround_output` function is the inverse of the `rowround_input` function. -/\nlemma rowround_output_is_inv_of_input : rowround_output (rowround_input M) = M :=\nbegin\n unfold rowround_input,\n unfold rowround_output,\n simp only [prod.mk.eta],\nend\n\n/--\n Prepare the `columnround` matrix input.\n\n Any `columnround` input matrix is in the form:\n\n (x₀, x₁, x₂, x₃)\n (x₄, x₅, x₆, x₇)\n (x₈, x₉, x₁₀, x₁₁)\n (x₁₂, x₁₃, x₁₄, x₁₅)\n\n But we need this to be converted to:\n\n (x₀, x₄, x₈, x₁₂)\n (x₅, x₉, x₁₃, x₁)\n (x₁₀, x₁₄, x₂, x₆)\n (x₁₅, x₃, x₇, x₁₁)\n-/\n@[simp] def columnround_input : matrixType :=\n (\n ((M.fst).fst, (M.snd.fst).fst, (M.snd.snd.fst).fst, (M.snd.snd.snd).fst),\n ((M.snd.fst).snd.fst, (M.snd.snd.fst).snd.fst, (M.snd.snd.snd).snd.fst, (M.fst).snd.fst),\n ((M.snd.snd.fst).snd.snd.fst, (M.snd.snd.snd).snd.snd.fst, (M.fst).snd.snd.fst, (M.snd.fst).snd.snd.fst),\n ((M.snd.snd.snd).snd.snd.snd, (M.fst).snd.snd.snd, (M.snd.fst).snd.snd.snd, (M.snd.snd.fst).snd.snd.snd)\n )\n\n/--\n Prepare the `columnround` matrix output.\n\n Any `columnround` output matrix is in the form:\n\n (y₀, y₄, y₈, y₁₂)\n (y₅, y₉, y₁₃, y₁)\n (y₁₀, y₁₄, y₂, y₆)\n (y₁₅, y₃, y₇, y₁₁)\n\n But we need this to be converted to:\n\n (y₀, y₁, y₂, y₃)\n (y₄, y₅, y₆, y₇)\n (y₈, y₉, y₁₀, y₁₁)\n (y₁₂, y₁₃, y₁₄, y₁₅) \n-/\n@[simp] def columnround_output : matrixType :=\n (\n ((M.fst).fst, (M.snd.fst).snd.snd.snd, (M.snd.snd.fst).snd.snd.fst, (M.snd.snd.snd).snd.fst),\n ((M.fst).snd.fst, (M.snd.fst).fst, (M.snd.snd.fst).snd.snd.snd, (M.snd.snd.snd).snd.snd.fst),\n ((M.fst).snd.snd.fst, (M.snd.fst).snd.fst, (M.snd.snd.fst).fst, (M.snd.snd.snd).snd.snd.snd),\n ((M.fst).snd.snd.snd, (M.snd.fst).snd.snd.fst, (M.snd.snd.fst).snd.fst, (M.snd.snd.snd).fst)\n )\n\n/-- The `columnround_output` function is the inverse of the `columnround_input` function. -/\nlemma columnround_output_is_inv_of_input : columnround_output (columnround_input M) = M :=\nbegin\n unfold columnround_input,\n unfold columnround_output,\n simp only [prod.mk.eta],\nend\n\n-- A random input 64 bytes matrix that we can reduce using `littleendian` function.\nvariable X : matrix64Type\n\n-- A random input 16 bytes matrix that we can aument using the `littleendian_inv` function.\nvariable Y : matrixType\n\n/-- Reduce the 64 bytes sequence to a 16 bytes one by using little endian. -/\ndef reduce : matrixType :=\n (\n (\n littleendian (((X.fst).fst).fst, ((X.fst).fst).snd.fst, ((X.fst).fst).snd.snd.fst, ((X.fst).fst).snd.snd.snd), \n littleendian (((X.fst).snd.fst).fst, ((X.fst).snd.fst).snd.fst, ((X.fst).snd.fst).snd.snd.fst, ((X.fst).snd.fst).snd.snd.snd),\n littleendian (((X.fst).snd.snd.fst).fst, ((X.fst).snd.snd.fst).snd.fst, ((X.fst).snd.snd.fst).snd.snd.fst, ((X.fst).snd.snd.fst).snd.snd.snd),\n littleendian (((X.fst).snd.snd.snd).fst, ((X.fst).snd.snd.snd).snd.fst, ((X.fst).snd.snd.snd).snd.snd.fst, ((X.fst).snd.snd.snd).snd.snd.snd)\n ),\n (\n littleendian (((X.snd.fst).fst).fst, ((X.snd.fst).fst).snd.fst, ((X.snd.fst).fst).snd.snd.fst, ((X.snd.fst).fst).snd.snd.snd), \n littleendian (((X.snd.fst).snd.fst).fst, ((X.snd.fst).snd.fst).snd.fst, ((X.snd.fst).snd.fst).snd.snd.fst, ((X.snd.fst).snd.fst).snd.snd.snd),\n littleendian (((X.snd.fst).snd.snd.fst).fst, ((X.snd.fst).snd.snd.fst).snd.fst, ((X.snd.fst).snd.snd.fst).snd.snd.fst, ((X.snd.fst).snd.snd.fst).snd.snd.snd),\n littleendian (((X.snd.fst).snd.snd.snd).fst, ((X.snd.fst).snd.snd.snd).snd.fst, ((X.snd.fst).snd.snd.snd).snd.snd.fst, ((X.snd.fst).snd.snd.snd).snd.snd.snd)\n ),\n (\n littleendian (((X.snd.snd.fst).fst).fst, ((X.snd.snd.fst).fst).snd.fst, ((X.snd.snd.fst).fst).snd.snd.fst, ((X.snd.snd.fst).fst).snd.snd.snd), \n littleendian (((X.snd.snd.fst).snd.fst).fst, ((X.snd.snd.fst).snd.fst).snd.fst, ((X.snd.snd.fst).snd.fst).snd.snd.fst, ((X.snd.snd.fst).snd.fst).snd.snd.snd),\n littleendian (((X.snd.snd.fst).snd.snd.fst).fst, ((X.snd.snd.fst).snd.snd.fst).snd.fst, ((X.snd.snd.fst).snd.snd.fst).snd.snd.fst, ((X.snd.snd.fst).snd.snd.fst).snd.snd.snd),\n littleendian (((X.snd.snd.fst).snd.snd.snd).fst, ((X.snd.snd.fst).snd.snd.snd).snd.fst, ((X.snd.snd.fst).snd.snd.snd).snd.snd.fst, ((X.snd.snd.fst).snd.snd.snd).snd.snd.snd)\n ),\n (\n littleendian (((X.snd.snd.snd).fst).fst, ((X.snd.snd.snd).fst).snd.fst, ((X.snd.snd.snd).fst).snd.snd.fst, ((X.snd.snd.snd).fst).snd.snd.snd), \n littleendian (((X.snd.snd.snd).snd.fst).fst, ((X.snd.snd.snd).snd.fst).snd.fst, ((X.snd.snd.snd).snd.fst).snd.snd.fst, ((X.snd.snd.snd).snd.fst).snd.snd.snd),\n littleendian (((X.snd.snd.snd).snd.snd.fst).fst, ((X.snd.snd.snd).snd.snd.fst).snd.fst, ((X.snd.snd.snd).snd.snd.fst).snd.snd.fst, ((X.snd.snd.snd).snd.snd.fst).snd.snd.snd),\n littleendian (((X.snd.snd.snd).snd.snd.snd).fst, ((X.snd.snd.snd).snd.snd.snd).snd.fst, ((X.snd.snd.snd).snd.snd.snd).snd.snd.fst, ((X.snd.snd.snd).snd.snd.snd).snd.snd.snd)\n )\n )\n\n/-- Aument a given 16 bytes sequence to a 64 bytes one using `littleenedian_inv`. -/\ndef aument : matrix64Type := (\n (\n littleendian_inv Y.fst.fst,\n littleendian_inv Y.fst.snd.fst,\n littleendian_inv Y.fst.snd.snd.fst,\n littleendian_inv Y.fst.snd.snd.snd\n ),\n (\n littleendian_inv Y.snd.fst.fst,\n littleendian_inv Y.snd.fst.snd.fst,\n littleendian_inv Y.snd.fst.snd.snd.fst,\n littleendian_inv Y.snd.fst.snd.snd.snd\n ),\n (\n littleendian_inv Y.snd.snd.fst.fst,\n littleendian_inv Y.snd.snd.fst.snd.fst,\n littleendian_inv Y.snd.snd.fst.snd.snd.fst,\n littleendian_inv Y.snd.snd.fst.snd.snd.snd\n ),\n (\n littleendian_inv Y.snd.snd.snd.fst,\n littleendian_inv Y.snd.snd.snd.snd.fst,\n littleendian_inv Y.snd.snd.snd.snd.snd.fst,\n littleendian_inv Y.snd.snd.snd.snd.snd.snd\n )\n)\n\n/-- \nModular 2^32 addition of 4x4 matrices by doing Aᵢⱼ + Bᵢⱼ\n\nThe `MOD` operation (modulo 2^32 addition) is the key to make the salsa20 hash function irreversible.\nEverything is reversible except for this addition.\n-/\n@[simp] def mod_matrix (A B : matrixType) : matrixType := (\n (\n A.fst.fst MOD B.fst.fst,\n A.fst.snd.fst MOD B.fst.snd.fst,\n A.fst.snd.snd.fst MOD B.fst.snd.snd.fst,\n A.fst.snd.snd.snd MOD B.fst.snd.snd.snd\n ),\n (\n A.snd.fst.fst MOD B.snd.fst.fst,\n A.snd.fst.snd.fst MOD B.snd.fst.snd.fst,\n A.snd.fst.snd.snd.fst MOD B.snd.fst.snd.snd.fst,\n A.snd.fst.snd.snd.snd MOD B.snd.fst.snd.snd.snd\n ),\n (\n A.snd.snd.fst.fst MOD B.snd.snd.fst.fst,\n A.snd.snd.fst.snd.fst MOD B.snd.snd.fst.snd.fst,\n A.snd.snd.fst.snd.snd.fst MOD B.snd.snd.fst.snd.snd.fst,\n A.snd.snd.fst.snd.snd.snd MOD B.snd.snd.fst.snd.snd.snd\n ),\n (\n A.snd.snd.snd.fst MOD B.snd.snd.snd.fst,\n A.snd.snd.snd.snd.fst MOD B.snd.snd.snd.snd.fst,\n A.snd.snd.snd.snd.snd.fst MOD B.snd.snd.snd.snd.snd.fst,\n A.snd.snd.snd.snd.snd.snd MOD B.snd.snd.snd.snd.snd.snd\n )\n)\n\n/-\n/-- The inverse of a `mod_matrix` operation is not a function. -/\n@[simp] lemma inv_of_mod_matrix_is_not_a_function : ∃ (A B C D : matrixType), mod_matrix A B = mod_matrix C D :=\nbegin\n simp only [mod_matrix, prod.mk.inj_iff, prod.exists, exists_and_distrib_left, exists_and_distrib_right,\n inv_of_mod_is_not_a_function, and_true],\nend\n-/\n\n/-- We define the xor of a matrix to be the xor of each individual bitvector of matrix A and matrix B. -/\ndef xor_matrix (A B : matrixType) : matrixType := (\n (\n A.fst.fst XOR B.fst.fst,\n A.fst.snd.fst XOR B.fst.snd.fst,\n A.fst.snd.snd.fst XOR B.fst.snd.snd.fst,\n A.fst.snd.snd.snd XOR B.fst.snd.snd.snd\n ),\n (\n A.snd.fst.fst XOR B.snd.fst.fst,\n A.snd.fst.snd.fst XOR B.snd.fst.snd.fst,\n A.snd.fst.snd.snd.fst XOR B.snd.fst.snd.snd.fst,\n A.snd.fst.snd.snd.snd XOR B.snd.fst.snd.snd.snd\n ),\n (\n A.snd.snd.fst.fst XOR B.snd.snd.fst.fst,\n A.snd.snd.fst.snd.fst XOR B.snd.snd.fst.snd.fst,\n A.snd.snd.fst.snd.snd.fst XOR B.snd.snd.fst.snd.snd.fst,\n A.snd.snd.fst.snd.snd.snd XOR B.snd.snd.fst.snd.snd.snd\n ),\n (\n A.snd.snd.snd.fst XOR B.snd.snd.snd.fst,\n A.snd.snd.snd.snd.fst XOR B.snd.snd.snd.snd.fst,\n A.snd.snd.snd.snd.snd.fst XOR B.snd.snd.snd.snd.snd.fst,\n A.snd.snd.snd.snd.snd.snd XOR B.snd.snd.snd.snd.snd.snd\n )\n)\n\n-- Have 16 random numbers.\nvariables a₀ a₁ a₂ a₃ a₄ a₅ a₆ a₇ a₈ a₉ a₁₀ a₁₁ a₁₂ a₁₃ a₁₄ a₁₅ : bitvec word_len\n\n/-- Distribute 2 * Matrix. -/\n@[simp] lemma matrix_distribute_two :\n 2 * ((a₀, a₁, a₂, a₃), (a₄, a₅, a₆, a₇), (a₈, a₉, a₁₀, a₁₁), (a₁₂, a₁₃, a₁₄, a₁₅)) =\n (\n (2 * a₀, 2 * a₁, 2 * a₂, 2 * a₃),\n (2 * a₄, 2 * a₅, 2 * a₆, 2 * a₇),\n (2 * a₈, 2 * a₉, 2 * a₁₀, 2 * a₁₁),\n (2 * a₁₂, 2 * a₁₃, 2 * a₁₄, 2 * a₁₅)\n ) := rfl\n\n/-\n/-- The MOD sum of two equal matrices X is 2 times X. -/\n@[simp] lemma mod_matrix_double : mod_matrix M M = 2 * M :=\nbegin\n unfold mod_matrix,\n simp only [mod_self],\n\n rw ← matrix_distribute_two\n M.fst.fst M.fst.snd.fst M.fst.snd.snd.fst M.fst.snd.snd.snd\n M.snd.fst.fst M.snd.fst.snd.fst M.snd.fst.snd.snd.fst M.snd.fst.snd.snd.snd\n M.snd.snd.fst.fst M.snd.snd.fst.snd.fst M.snd.snd.fst.snd.snd.fst M.snd.snd.fst.snd.snd.snd\n M.snd.snd.snd.fst M.snd.snd.snd.snd.fst M.snd.snd.snd.snd.snd.fst M.snd.snd.snd.snd.snd.snd,\n refl,\nend\n-/\n\n/-- Convert a `matrixType` to a `list` as lists are easy to work sometimes than prods. -/\n@[simp] def matrix_to_list : matrixType → list (bitvec word_len)\n| m := [\n m.fst.fst, m.fst.snd.fst, m.fst.snd.snd.fst, m.fst.snd.snd.snd,\n m.snd.fst.fst, m.snd.fst.snd.fst, m.snd.fst.snd.snd.fst, m.snd.fst.snd.snd.snd,\n m.snd.snd.fst.fst, m.snd.snd.fst.snd.fst, m.snd.snd.fst.snd.snd.fst, m.snd.snd.fst.snd.snd.snd,\n m.snd.snd.snd.fst, m.snd.snd.snd.snd.fst, m.snd.snd.snd.snd.snd.fst, m.snd.snd.snd.snd.snd.snd\n]\n\n/-- Convert a list of bitvectors into a `matrixType`. Will panic if list size is < 16 -/\n@[simp] def list_to_matrix : list (bitvec word_len) → matrixType\n| l := (\n ((l.nth 0).iget, (l.nth 1).iget, (l.nth 2).iget, (l.nth 3).iget),\n ((l.nth 4).iget, (l.nth 5).iget, (l.nth 6).iget, (l.nth 7).iget),\n ((l.nth 8).iget, (l.nth 9).iget, (l.nth 10).iget, (l.nth 11).iget),\n ((l.nth 12).iget, (l.nth 13).iget, (l.nth 14).iget, (l.nth 15).iget)\n)\n\nend utils\n", "meta": {"author": "oxarbitrage", "repo": "salsa20", "sha": "12d0ebb3c27801931e61d470fb2ed548a5562578", "save_path": "github-repos/lean/oxarbitrage-salsa20", "path": "github-repos/lean/oxarbitrage-salsa20/salsa20-12d0ebb3c27801931e61d470fb2ed548a5562578/src/utils.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3886180267058489, "lm_q2_score": 0.036769467922763914, "lm_q1q2_score": 0.014289278067168521}} {"text": "/- Introduces evaluation contexts. -/\n\nimport sesh.term\nimport sesh.ren_sub\n\nopen term\nopen matrix\n\nuniverses u v w\n\n/- Oh no, additional axioms. -/\naxiom heq.congr {α γ : Sort u} {β δ : Sort v} {f₁ : α → β} {f₂ : γ → δ} {a₁ : α} {a₂ : γ} (h₁ : f₁ == f₂) (h₂ : a₁ == a₂) : f₁ a₁ == f₂ a₂\n\naxiom heq.dcongr {α β : Sort u} {γ δ : Sort v} {ε ζ : Sort w} {f₁ : Π α, γ → ε} {f₂ : Π β, δ → ζ} {a₁₁ : α} {a₁₂ : γ} {a₂₁ : β} {a₂₂ : δ} (h₁ : f₁ == f₂) (h₂ : a₁₁ == a₂₁) (h₃ : a₁₂ == a₂₂) : f₁ a₁₁ a₁₂ == f₂ a₂₁ a₂₂\n\n/- The context except the hole consumes Γₑ resources, while the\n hole can consume arbitrary resources Γ. The term plugged in\n for the hole must have type A' (hence the hole is \"typed\") and\n the resulting term has type A. In every evaluation context,\n the hole has the same precontext as the overall expression,\n since GV never evaluates under binders. Therefore I don't have\n to allow a fully general (i.e. arbitrary precontext) typing\n context for the hole. -/\n@[reducible]\ndef eval_ctx_fn {γ} (Γₑ: context γ) (A' A: tp): Type :=\n Π (Γ: context γ), term Γ A' → term (Γ + Γₑ) A\n\nnamespace eval_ctx_fn\n\n@[reducible]\ndef apply {γ} {Γₑ Γ': context γ} {A' A: tp}\n (f: eval_ctx_fn Γₑ A' A)\n (Γ: context γ)\n (M: term Γ' A')\n (h: auto_param (Γ = Γ'+Γₑ) ``solve_context)\n : term Γ A :=\ncast (by solve_context) $ f Γ' M\n\nend eval_ctx_fn\n\n/- A value of type (eval_ctx f) specifies that f is a valid function\n for an evaluation context. It's a Type rather than a Prop, because\n Prop can only eliminate into Prop but sometimes I need to extract\n the actual value of a constructor argument out of an eval_ctx. -/\ninductive eval_ctx\n : Π {γ} {A' A: tp} (Γₑ: context γ), eval_ctx_fn Γₑ A' A → Type\n| EHole:\n Π (γ: precontext) (A: tp),\n eval_ctx 0 (λ (Γ: context γ) (M: term Γ A), begin convert M, solve_context end)\n\n| EAppLeft:\n Π {γ} {Γ₁ Γ₂: context γ} {A B: tp}\n {C'}\n (Γₑ: context γ)\n (hΓ: Γₑ = Γ₁ + Γ₂)\n (N: term Γ₂ A)\n (E: eval_ctx_fn Γ₁ C' $ A⊸B),\n eval_ctx Γ₁ E\n -------------------------------\n→ eval_ctx Γₑ (λ Γ M, App _ (E Γ M) N)\n\n| EAppRight:\n Π {γ} {Γ₁ Γ₂: context γ} {A B: tp}\n {A'} {V: term Γ₁ $ A⊸B}\n (Γₑ: context γ)\n (hΓ: Γₑ = Γ₁ + Γ₂)\n (hV: value V)\n (E: eval_ctx_fn Γ₂ A' A),\n eval_ctx Γ₂ E\n -------------------------------\n→ eval_ctx Γₑ (λ Γ M, App _ V $ E Γ M)\n\n| ELetUnit:\n Π {γ} {Γ₁ Γ₂: context γ} {A: tp}\n {A'}\n (Γₑ: context γ)\n (hΓ: Γₑ = Γ₁ + Γ₂)\n (N: term Γ₂ A)\n (E: eval_ctx_fn Γ₁ A' tp.unit),\n eval_ctx Γ₁ E\n ---------------------------------\n→ eval_ctx Γₑ (λ Γ M, LetUnit _ (E Γ M) N)\n\n| EPairLeft:\n Π {γ} {Γ₁ Γ₂: context γ} {A B: tp}\n {A'}\n (Γₑ: context γ)\n (hΓ: Γₑ = Γ₁ + Γ₂)\n (N: term Γ₂ B)\n (E: eval_ctx_fn Γ₁ A' A),\n eval_ctx Γ₁ E\n ------------------------------\n→ eval_ctx Γₑ (λ Γ M, Pair _ (E Γ M) N)\n\n| EPairRight:\n Π {γ} {Γ₁ Γ₂: context γ} {A B: tp}\n {B'} {V: term Γ₁ A}\n (Γₑ: context γ)\n (hΓ: Γₑ = Γ₁ + Γ₂)\n (hV: value V)\n (E: eval_ctx_fn Γ₂ B' B),\n eval_ctx Γ₂ E\n ------------------------------\n→ eval_ctx Γₑ (λ Γ M, Pair _ V $ E Γ M)\n\n| ELetPair:\n Π {γ} {Γ₁ Γ₂: context γ} {A B C: tp}\n {C'}\n (Γₑ: context γ)\n (hΓ: Γₑ = Γ₁ + Γ₂)\n (N: term (⟦1⬝A⟧::⟦1⬝B⟧::Γ₂) C)\n (E: eval_ctx_fn Γ₁ C' $ tp.prod A B),\n eval_ctx Γ₁ E\n ----------------------------------\n→ eval_ctx Γₑ (λ Γ M, LetPair _ (E Γ M) N)\n\n| EInl:\n Π {γ} {Γₑ: context γ} {A: tp}\n {A'}\n (B: tp)\n (E: eval_ctx_fn Γₑ A' A),\n eval_ctx Γₑ E\n -----------------------------\n→ eval_ctx Γₑ (λ Γ M, Inl B $ E Γ M)\n\n| EInr:\n Π {γ} {Γₑ: context γ} {B: tp}\n {B'}\n (A: tp)\n (E: eval_ctx_fn Γₑ B' B),\n eval_ctx Γₑ E\n ---------------------------\n→ eval_ctx Γₑ (λ Γ M, Inr A $ E Γ M)\n\n| ECase:\n Π {γ} {Γ₁ Γ₂: context γ} {A B C: tp}\n {D'}\n (Γₑ: context γ)\n (hΓ: Γₑ = Γ₁ + Γ₂)\n (M: term (⟦1⬝A⟧::Γ₂) C)\n (N: term (⟦1⬝B⟧::Γ₂) C)\n (E: eval_ctx_fn Γ₁ D' $ tp.sum A B),\n eval_ctx Γ₁ E\n --------------------------------\n→ eval_ctx Γₑ (λ Γ L, Case _ (E Γ L) M N)\n\n| EFork:\n Π {γ} {Γₑ: context γ} {S: sesh_tp}\n {T'}\n (E: eval_ctx_fn Γₑ T' $ S⊸End!),\n eval_ctx Γₑ E\n --------------------------\n→ eval_ctx Γₑ (λ Γ x, Fork (E Γ x))\n\n| ESendLeft:\n Π {γ} {Γ₁ Γ₂: context γ} {A: tp} {S: sesh_tp}\n {A'}\n (Γₑ: context γ)\n (hΓ: Γₑ = Γ₁ + Γ₂)\n (N: term Γ₂ $ !A⬝S)\n (E: eval_ctx_fn Γ₁ A' A),\n eval_ctx Γ₁ E\n ------------------------------\n→ eval_ctx Γₑ (λ Γ M, Send _ (E Γ M) N)\n\n| ESendRight:\n Π {γ} {Γ₁ Γ₂: context γ} {A: tp} {S: sesh_tp}\n {T'} {V: term Γ₁ A}\n (Γₑ: context γ)\n (hΓ: Γₑ = Γ₁ + Γ₂)\n (hV: value V)\n (E: eval_ctx_fn Γ₂ T' $ !A⬝S),\n eval_ctx Γ₂ E\n ------------------------------\n→ eval_ctx Γₑ (λ Γ M, Send _ V $ E Γ M)\n\n| ERecv:\n Π {γ} {Γₑ: context γ} {A: tp} {S: sesh_tp}\n {T'}\n (E: eval_ctx_fn Γₑ T' ?A⬝S),\n eval_ctx Γₑ E\n --------------------------\n→ eval_ctx Γₑ (λ Γ M, Recv $ E Γ M)\n\n| EWait:\n Π {γ} {Γₑ: context γ}\n {T'}\n (E: eval_ctx_fn Γₑ T' End?),\n eval_ctx Γₑ E\n --------------------------\n→ eval_ctx Γₑ (λ Γ M, Wait $ E Γ M)\n\nnamespace eval_ctx\nopen matrix.vmul\n\n/- The new function we're defining takes a hole term defined over\n an extended environment (rename ρ Γ) and returns the same expression,\n but well-typed under the extended environment. -/\ndef ext:\n Π {γ δ: precontext} {A' A: tp}{Γ: context γ}\n {E: eval_ctx_fn Γ A' A}\n (ρ: ren_fn γ δ),\n eval_ctx Γ E\n -----------------------------------------------\n → Σ E': eval_ctx_fn (Γ ⊛ (λ B x, identity δ B $ ρ B x)) A' A,\n eval_ctx (Γ ⊛ (λ B x, identity δ B $ ρ B x)) E'\n/- In each case we define what happens when the resulting\n renamed evaluation context is _applied_ to a hole-filling\n argument, which is the last matched variable (usually M).\n\n Most cases proceed by renaming parts of the evaluation context\n to make sense in the extended typing context and proving that\n the contexts still make sense.\n\n The return value of this function also carries the proof\n that the returned function is, in fact, an evaluation context. -/\n| _ _ _ _ _ _ _ (EHole _ _) :=\nbegin\n rw [matrix.vmul.zero_vmul],\n exact ⟨_, EHole _ _⟩\nend\n| _ _ _ _ _ _ ρ (EAppLeft _ hΓ N _ E) :=\n let E' := ext ρ E in\n ⟨_, EAppLeft\n _\n (begin rw [hΓ, vmul_right_distrib] end)\n (rename ρ _ N)\n E'.fst\n E'.snd⟩\n| _ _ _ _ _ _ ρ (EAppRight _ hΓ hV _ E) :=\n let E' := ext ρ E in\n ⟨_, EAppRight\n _\n (begin rw [hΓ, vmul_right_distrib] end)\n (hV.rename ρ)\n E'.fst\n E'.snd⟩\n| _ _ _ _ _ _ ρ (ELetUnit _ hΓ N _ E) :=\n let E' := ext ρ E in\n ⟨_, ELetUnit\n _\n (begin rw [hΓ, vmul_right_distrib] end)\n (rename ρ _ N)\n E'.fst\n E'.snd⟩\n| _ _ _ _ _ _ ρ (EPairLeft _ hΓ N _ E) :=\n let E' := ext ρ E in\n ⟨_, EPairLeft\n _\n (begin rw [hΓ, vmul_right_distrib] end)\n (rename ρ _ N)\n E'.fst\n E'.snd⟩\n| _ _ _ _ _ _ ρ (EPairRight _ hΓ hV _ E) :=\n let E' := ext ρ E in\n ⟨_, EPairRight\n _\n (begin rw [hΓ, vmul_right_distrib] end)\n (hV.rename ρ)\n E'.fst\n E'.snd⟩\n| γ _ _ _ _ _ ρ (ELetPair _ hΓ N _ E) :=\n let E' := ext ρ E in\n ⟨_, ELetPair\n _\n (begin rw [hΓ, vmul_right_distrib] end)\n (rename ((ρ.ext _).ext _) _ N)\n E'.fst\n E'.snd⟩\n| _ _ _ _ _ _ ρ (EInl C _ E) :=\n let E' := ext ρ E in\n ⟨_, EInl\n C\n E'.fst\n E'.snd⟩\n| _ _ _ _ _ _ ρ (EInr C _ E) :=\n let E' := ext ρ E in\n ⟨_, EInr\n C\n E'.fst\n E'.snd⟩\n| γ _ _ _ _ _ ρ (ECase _ hΓ M N _ E) :=\n let E' := ext ρ E in\n ⟨_, ECase\n _\n (begin rw [hΓ, vmul_right_distrib] end)\n (rename (ρ.ext _) _ M)\n (rename (ρ.ext _) _ N)\n E'.fst\n E'.snd⟩\n| _ _ _ _ _ _ ρ (EFork _ E) :=\n let E' := ext ρ E in\n ⟨_, EFork\n E'.fst\n E'.snd⟩\n| _ _ _ _ _ _ ρ (ESendLeft _ hΓ N _ E) :=\n let E' := ext ρ E in\n ⟨_, ESendLeft\n _\n (begin rw [hΓ, vmul_right_distrib] end)\n (rename ρ _ N)\n E'.fst\n E'.snd⟩\n| _ _ _ _ _ _ ρ (ESendRight _ hΓ hV _ E) :=\n let E' := ext ρ E in\n ⟨_, ESendRight\n _\n (begin rw [hΓ, vmul_right_distrib] end)\n (hV.rename ρ)\n E'.fst\n E'.snd⟩\n| _ _ _ _ _ _ ρ (ERecv _ E) :=\n let E' := ext ρ E in\n ⟨_, ERecv\n E'.fst\n E'.snd⟩\n| _ _ _ _ _ _ ρ (EWait _ E) :=\n let E' := ext ρ E in\n ⟨_, EWait\n E'.fst\n E'.snd⟩\n\ndef wrap: Π {γ} {A'' A' A: tp} {Γₑ Γₑ': context γ}\n (E: eval_ctx_fn Γₑ A'' A')\n (hE: eval_ctx Γₑ E)\n (E': eval_ctx_fn Γₑ' A' A)\n (hE': eval_ctx Γₑ' E')\n (Γ: context γ)\n (hΓ: Γ = Γₑ+Γₑ'),\n Σ E': eval_ctx_fn Γ A'' A,\n eval_ctx Γ E'\n| _ _ _ _ _ _ E hE _ (EHole _ _) Γ hΓ :=\n cast (begin congr; simp [*, hΓ], congr' 1, simp [hΓ] end)\n (sigma.mk E hE)\n| _ _ _ _ _ _ E hE _ (EAppLeft _ _ N E' hE') Γ hΓ :=\n let EE' := wrap E hE E' hE' _ rfl in\n ⟨_, EAppLeft Γ (by solve_context) N EE'.fst EE'.snd⟩\n| _ _ _ _ _ _ E hE _ (EAppRight _ _ hV E' hE') Γ hΓ :=\n let EE' := wrap E hE E' hE' _ rfl in\n ⟨_, EAppRight Γ (by solve_context) hV EE'.fst EE'.snd⟩\n| _ _ _ _ _ _ E hE _ (ELetUnit _ _ N E' hE') Γ hΓ :=\n let EE' := wrap E hE E' hE' _ rfl in\n ⟨_, ELetUnit Γ (by solve_context) N EE'.fst EE'.snd⟩\n| _ _ _ _ _ _ E hE _ (EPairLeft _ _ N E' hE') Γ hΓ :=\n let EE' := wrap E hE E' hE' _ rfl in\n ⟨_, EPairLeft Γ (by solve_context) N EE'.fst EE'.snd⟩\n| _ _ _ _ _ _ E hE _ (EPairRight _ _ hV E' hE') Γ hΓ :=\n let EE' := wrap E hE E' hE' _ rfl in\n ⟨_, EPairRight Γ (by solve_context) hV EE'.fst EE'.snd⟩\n| _ _ _ _ _ _ E hE _ (ELetPair _ _ N E' hE') Γ hΓ :=\n let EE' := wrap E hE E' hE' _ rfl in\n ⟨_, ELetPair Γ (by solve_context) N EE'.fst EE'.snd⟩\n| _ _ _ _ _ _ E hE _ (EInl B E' hE') Γ hΓ :=\n let EE' := wrap E hE E' hE' _ rfl in\n ⟨_, EInl B (cast (by rw [hΓ]) EE'.fst) $ cast (begin\n congr' 1, exact hΓ.symm,\n h_generalize Hx: EE'.fst == x, exact Hx,\n end) EE'.snd⟩\n| _ _ _ _ _ _ E hE _ (EInr A E' hE') Γ hΓ :=\n let EE' := wrap E hE E' hE' _ rfl in\n ⟨_, EInr A (cast (by rw [hΓ]) EE'.fst) $ cast (begin\n congr' 1, exact hΓ.symm,\n h_generalize Hx: EE'.fst == x, exact Hx,\n end) EE'.snd⟩\n| _ _ _ _ _ _ E hE _ (ECase _ _ M N E' hE') Γ hΓ :=\n let EE' := wrap E hE E' hE' _ rfl in\n ⟨_, ECase Γ (by solve_context) M N EE'.fst EE'.snd⟩\n| _ _ _ _ _ _ E hE _ (EFork E' hE') Γ hΓ :=\n let EE' := wrap E hE E' hE' _ rfl in\n ⟨_, EFork (cast (by rw [hΓ]) EE'.fst) $ cast (begin\n congr' 1, exact hΓ.symm,\n h_generalize Hx: EE'.fst == x, exact Hx,\n end) EE'.snd⟩\n| _ _ _ _ _ _ E hE _ (ESendLeft _ _ M E' hE') Γ hΓ :=\n let EE' := wrap E hE E' hE' _ rfl in\n ⟨_, ESendLeft Γ (by solve_context) M EE'.fst EE'.snd⟩\n| _ _ _ _ _ _ E hE _ (ESendRight _ _ hV E' hE') Γ hΓ :=\n let EE' := wrap E hE E' hE' _ rfl in\n ⟨_, ESendRight Γ (by solve_context) hV EE'.fst EE'.snd⟩\n| _ _ _ _ _ _ E hE _ (ERecv E' hE') Γ hΓ :=\n let EE' := wrap E hE E' hE' _ rfl in\n ⟨_, ERecv (cast (by rw [hΓ]) EE'.fst) $ cast (begin\n congr' 1, exact hΓ.symm,\n h_generalize Hx: EE'.fst == x, exact Hx,\n end) EE'.snd⟩\n| _ _ _ _ _ _ E hE _ (EWait E' hE') Γ hΓ :=\n let EE' := wrap E hE E' hE' _ rfl in\n ⟨_, EWait (cast (by rw [hΓ]) EE'.fst) $ cast (begin\n congr' 1, exact hΓ.symm,\n h_generalize Hx: EE'.fst == x, exact Hx,\n end) EE'.snd⟩\n\nset_option pp.implicit true\n\nlemma wrap_composes {γ} {Γ Γₑ Γₑ': context γ} {A'' A' A: tp}\n {M: term Γ A''}\n {E': eval_ctx_fn Γₑ A'' A'}\n {hE': eval_ctx Γₑ E'}\n {E: eval_ctx_fn Γₑ' A' A}\n {hE: eval_ctx Γₑ' E}\n (Γ': context γ)\n (hΓ': Γ' = Γ+Γₑ)\n (EM: term Γ' A')\n (Γ'': context γ)\n (hΓ'': Γ'' = Γ'+Γₑ')\n (EM': term Γ'' A)\n (hEM: EM = E'.apply Γ' M)\n (hEM': EM' = E.apply Γ'' EM)\n : EM' = (wrap E' hE' E hE _ rfl).fst.apply Γ'' M :=\nbegin\n induction hE; simp [*, wrap, eval_ctx_fn.apply],\n case EHole {\n h_generalize Hx: (E' Γ M) == x,\n h_generalize Hy: x == y,\n h_generalize Hx': (⟨E', hE'⟩: Σ E': eval_ctx_fn Γₑ A'' hE_A, eval_ctx Γₑ E') == x',\n congr' 1, simp [hΓ'],\n apply heq.trans Hy.symm, apply heq.trans Hx.symm,\n apply heq.congr, unfold sigma.fst,\n sorry\n },\n sorry\nend\n\nend eval_ctx\n\n/- An evaluation context is a hole-replacing function\n together with a proof of its validity. -/\nstructure eval_ctx' {γ} (Γₑ: context γ) (A' A: tp) :=\n(f: eval_ctx_fn Γₑ A' A)\n(h: eval_ctx Γₑ f)\n\nnamespace eval_ctx'\n\ndef ext {γ δ: precontext} {Γ: context γ} {A' A: tp} (ρ: ren_fn γ δ) (E: eval_ctx' Γ A' A)\n : eval_ctx' (Γ ⊛ (λ B x, identity δ B $ ρ B x)) A' A :=\n let E' := eval_ctx.ext ρ E.h in\n ⟨E'.fst, E'.snd⟩\n\ndef wrap {γ} {Γₑ Γₑ': context γ} {A'' A' A: tp}\n (E: eval_ctx' Γₑ A'' A')\n (E': eval_ctx' Γₑ' A' A)\n (Γ: context γ)\n (hΓ: Γ = Γₑ+Γₑ')\n : eval_ctx' Γ A'' A :=\nlet EE' := eval_ctx.wrap E.f E.h E'.f E'.h Γ hΓ in\n⟨EE'.fst, EE'.snd⟩\n\nlemma wrap_composes {γ} {Γ Γₑ Γₑ': context γ} {A'' A' A: tp}\n {M: term Γ A''}\n {E': eval_ctx' Γₑ A'' A'}\n {E: eval_ctx' Γₑ' A' A}\n (Γ': context γ)\n (hΓ': Γ' = Γ+Γₑ)\n (EM: term Γ' A')\n (Γ'': context γ)\n (hΓ'': Γ'' = Γ'+Γₑ')\n (EM': term Γ'' A)\n (hE: EM = E'.f.apply Γ' M)\n (hE': EM' = E.f.apply Γ'' EM)\n : EM' = (E'.wrap E _ rfl).f.apply Γ'' M :=\nsorry\n\nend eval_ctx'\n\ninductive term_reduces\n : ∀ {γ} {Γ: context γ} {A: tp}, term Γ A → term Γ A → Prop\ninfix ` ⟶M `:55 := term_reduces\n| EvalLift:\n ∀ {γ} {Γ Γₑ: context γ} {A A': tp}\n {M M': term Γ A}\n (Γ': context γ)\n (E: eval_ctx' Γₑ A A')\n (EM EM': term Γ' A')\n (hΓ': Γ' = Γ+Γₑ)\n (hStep: M ⟶M M')\n (hEM: EM = E.f.apply Γ' M)\n (hEM': EM' = E.f.apply Γ' M'),\n -----------------------\n EM ⟶M EM'\n\n| EvalLam:\n ∀ {γ} {Γ₁ Γ₂: context γ} {A B: tp}\n {V: term Γ₂ A}\n (Γ: context γ)\n (M: term (⟦1⬝A⟧::Γ₁) B)\n (hV: value V)\n (_: auto_param (Γ = Γ₁ + Γ₂) ``solve_context),\n ----------------------------------------------\n (App Γ (Abs M) V) ⟶M ssubst _ M V\n\n| EvalUnit:\n ∀ {γ} {Γ: context γ} {A: tp}\n (M: term Γ A),\n ---------------------------------------\n (LetUnit Γ (Unit 0) M $ by simp) ⟶M M\n\n| EvalPair:\n ∀ {γ} {Γ₁₁ Γ₁₂ Γ₂: context γ} {A B C: tp}\n {V: term Γ₁₁ A} {W: term Γ₁₂ B}\n (Γ₁ Γ: context γ)\n (hV: value V)\n (hW: value W)\n (M: term (⟦1⬝A⟧::⟦1⬝B⟧::Γ₂) C)\n (_: auto_param (Γ = Γ₁ + Γ₂) ``solve_context)\n (_: auto_param (Γ₁ = Γ₁₁ + Γ₁₂) ``solve_context),\n -----------------------------------------------------------\n (LetPair Γ (Pair Γ₁ V W $ by assumption) M $ by assumption)\n ⟶M\n dsubst _ M V W\n\n| EvalInl:\n ∀ {γ} {Γ₁ Γ₂: context γ} {A B C: tp}\n {V: term Γ₁ A}\n (Γ: context γ)\n (hV: value V)\n (M: term (⟦1⬝A⟧::Γ₂) C)\n (N: term (⟦1⬝B⟧::Γ₂) C)\n (_: auto_param (Γ = Γ₁ + Γ₂) ``solve_context),\n ----------------------------------------------\n (Case Γ (Inl B V) M N) ⟶M ssubst _ M V\n\n| EvalInr:\n ∀ {γ} {Γ₁ Γ₂: context γ} {A B C: tp}\n {V: term Γ₁ B}\n (Γ: context γ)\n (hV: value V)\n (M: term (⟦1⬝A⟧::Γ₂) C)\n (N: term (⟦1⬝B⟧::Γ₂) C)\n (_: auto_param (Γ = Γ₁ + Γ₂) ``solve_context),\n ----------------------------------------------\n (Case Γ (Inr A V) M N) ⟶M ssubst _ N V\n\ninfix ` ⟶M `:55 := term_reduces\n\n/- This is what I thought initially (WRONG!):\n I _think_ there is barely any benefit to formalizing evaluation contexts\n because they would have to be defined for all kinds of terms anyway.\n\n Actually no, eval_ctx is _necessary_ to formalize configuration reduction\n without losing what's left of my sanity. -/\n", "meta": {"author": "Vtec234", "repo": "lean-sesh", "sha": "d11d7bb0599406e27d3a4d26242aec13d639ecf7", "save_path": "github-repos/lean/Vtec234-lean-sesh", "path": "github-repos/lean/Vtec234-lean-sesh/lean-sesh-d11d7bb0599406e27d3a4d26242aec13d639ecf7/src/sesh/eval.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47268347662043286, "lm_q2_score": 0.030214584447621012, "lm_q1q2_score": 0.014281934821343161}} {"text": "\nimport tactic\nimport tactic.monotonicity\nimport tactic.norm_num\nimport category.basic\nimport category.serial\nimport data.serial.medium\n\nuniverses u v w\n\ndef serial_inverse {α : Type u} (encode : α → put_m) (decode : get_m α) : Prop :=\n∀ w, decode -<< encode w = pure w\n\nclass serial (α : Type u) :=\n (encode : α → put_m.{u})\n (decode : get_m α)\n (correctness : ∀ w, decode -<< encode w = pure w)\n\nclass serial1 (f : Type u → Type v) :=\n (encode : Π {α} [serial α], f α → put_m.{v})\n (decode : Π {α} [serial α], get_m (f α))\n (correctness : ∀ {α} [serial α] (w : f α), decode -<< encode w = pure w)\n\ninstance serial.serial1 {f α} [serial1 f] [serial α] : serial (f α) :=\n{ encode := λ x, serial1.encode x,\n decode := serial1.decode f,\n correctness := serial1.correctness }\n\nclass serial2 (f : Type u → Type v → Type w) :=\n (encode : Π {α β} [serial α] [serial β], f α β → put_m.{w})\n (decode : Π {α β} [serial α] [serial β], get_m (f α β))\n (correctness : ∀ {α β} [serial α] [serial β] (w : f α β), decode -<< encode w = pure w)\n\ninstance serial.serial2 {f α β} [serial2 f] [serial α] [serial β] : serial (f α β) :=\n{ encode := λ x, serial2.encode x,\n decode := serial2.decode f,\n correctness := serial2.correctness }\n\ninstance serial1.serial2 {f α} [serial2 f] [serial α] : serial1 (f α) :=\n{ encode := λ β inst x, @serial2.encode _ _ α β _ inst x,\n decode := λ β inst, @serial2.decode f _ α β _ inst,\n correctness := λ β inst, @serial2.correctness _ _ α β _ inst }\n\nexport serial (encode decode)\n\nnamespace serial\n\nopen function\n\nvariables {α β σ γ : Type u} {ω : Type}\n\ndef serialize [serial α] (x : α) : list unsigned := (encode x).eval\ndef deserialize (α : Type u) [serial α] (bytes : list unsigned) : option α := (decode α).eval bytes\n\nlemma encode_decode_bind [serial α]\n (f : α → get_m β) (f' : punit → put_m) (w : α) :\n (decode α >>= f) -<< (encode w >>= f') = f w -<< f' punit.star :=\nby { rw [read_write_mono]; rw serial.correctness; refl }\n\nlemma encode_decode_bind' [serial α]\n (f : α → get_m β) (w : α) :\n (decode α >>= f) -<< (encode w) = f w -<< pure punit.star :=\nby { rw [read_write_mono_left]; rw serial.correctness; refl }\n\nlemma encode_decode_pure\n (w w' : α) (u : punit) :\n (pure w) -<< (pure u) = pure w' ↔ w = w' :=\nby split; intro h; cases h; refl\n\nopen ulift\n\nprotected def ulift.encode [serial α] (w : ulift.{v} α) : put_m :=\nliftable1.up equiv.punit_equiv_punit (encode (down w))\n\nprotected def ulift.decode [serial α] : get_m (ulift α) :=\nget_m.up ulift.up (decode α)\n\ninstance [serial α] : serial (ulift.{v u} α) :=\n{ encode := ulift.encode\n, decode := ulift.decode\n, correctness :=\n by { introv, simp [ulift.encode,ulift.decode],\n rw up_read_write' _ equiv.ulift.symm,\n rw [serial.correctness], cases w, refl,\n intro, refl } }\n\ninstance unsigned.serial : serial unsigned :=\n{ encode := λ w, put_m'.write w put_m'.pure\n, decode := get_m.read get_m.pure\n, correctness := by introv; refl }\n\ndef write_word (w : unsigned) : put_m.{u} :=\nencode (up.{u} w)\n\n@[simp] lemma loop_read_write_word {α β γ : Type u}\n (w : unsigned) (x : α) (f : α → unsigned → get_m (β ⊕ α)) (g : β → get_m γ)\n (rest : punit → put_m) :\n get_m.loop f g x -<< (write_word w >>= rest) =\n (f x w >>= @sum.rec _ _ (λ _, get_m γ) g (get_m.loop f g)) -<< rest punit.star := rfl\n\n@[simp] lemma loop_read_write_word' {α β γ : Type u}\n (w : unsigned) (x : α) (f : α → unsigned → get_m (β ⊕ α)) (g : β → get_m γ) :\n get_m.loop f g x -<< (write_word w) =\n (f x w >>= @sum.rec _ _ (λ _, get_m γ) g (get_m.loop f g)) -<< pure punit.star := rfl\n\ndef read_word : get_m.{u} (ulift unsigned) :=\ndecode _\n\ndef select_tag' (tag : unsigned) : list (unsigned × get_m α) → get_m α\n| [] := get_m.fail\n| ((w,x) :: xs) := if w = tag then x else select_tag' xs\n\ndef select_tag (xs : list (unsigned × get_m α)) : get_m α :=\ndo w ← read_word,\n select_tag' (down w) xs\n\n@[simp]\nlemma read_write_tag_hit {w w' : unsigned} {x : get_m α}\n {xs : list (unsigned × get_m α)} {y : put_m}\n (h : w = w') :\n select_tag ( (w,x) :: xs ) -<< (write_word w' >> y) = x -<< y :=\nby subst w'; simp [select_tag,(>>),read_word,write_word,encode_decode_bind,select_tag']\n\nlemma read_write_tag_hit' {w w' : unsigned} {x : get_m α}\n {xs : list (unsigned × get_m α)}\n (h : w = w') :\n select_tag ( (w,x) :: xs ) -<< (write_word w') = x -<< pure punit.star :=\nby subst w'; simp [select_tag,(>>),read_word,write_word,encode_decode_bind',select_tag']\n\n@[simp]\nlemma read_write_tag_miss {w w' : unsigned} {x : get_m α}\n {xs : list (unsigned × get_m α)} {y : put_m}\n (h : w ≠ w') :\n select_tag ( (w,x) :: xs ) -<< (write_word w' >> y) = select_tag xs -<< (write_word w' >> y) :=\nby simp [select_tag,(>>),read_word,write_word,encode_decode_bind,select_tag',*]\n\ndef recursive_parser {α} : ℕ → (get_m α → get_m α) → get_m α\n| 0 _ := get_m.fail\n| (nat.succ n) rec_fn := rec_fn $ recursive_parser n rec_fn\n\nlemma recursive_parser_unfold {α} (n : ℕ) (f : get_m α → get_m α) (h : 1 ≤ n) :\n recursive_parser n f = f (recursive_parser (n-1) f) :=\nby cases n; [ cases h, refl ]\n\nattribute [simp] serial.correctness\n\nend serial\n\nstructure serializer (α : Type u) (β : Type u) :=\n(encoder : α → put_m.{u})\n(decoder : get_m β)\n\nnamespace serializer\n\ndef valid_serializer {α} (x : serializer α α) :=\nserial_inverse\n (serializer.encoder x)\n (serializer.decoder x)\n\nlemma serializer.eq {α β} (x y : serializer α β)\n (h : x.encoder = y.encoder)\n (h' : x.decoder = y.decoder) :\n x = y :=\nby cases x; cases y; congr; assumption\n\nnamespace serializer.seq\n\nvariables {α : Type u} {i j : Type u}\nvariables (x : serializer α (i → j))\nvariables (y : serializer α i)\n\ndef encoder := λ (k : α), x.encoder k >> y.encoder k\ndef decoder := x.decoder <*> y.decoder\n\nend serializer.seq\n\ninstance {α : Type u} : applicative (serializer.{u} α) :=\n{ pure := λ i x, { encoder := λ _, return punit.star, decoder := pure x }\n, seq := λ i j x y,\n { encoder := serializer.seq.encoder x y\n , decoder := serializer.seq.decoder x y } }\n\nsection lawful_applicative\n\nvariables {α β : Type u} {σ : Type u}\n\n@[simp]\nlemma decoder_pure (x : β) :\n (pure x : serializer σ β).decoder = pure x := rfl\n\n@[simp]\nlemma decoder_map (f : α → β) (x : serializer σ α) :\n (f <$> x).decoder = f <$> x.decoder := rfl\n\n@[simp]\nlemma decoder_seq (f : serializer σ (α → β)) (x : serializer σ α) :\n (f <*> x).decoder = f.decoder <*> x.decoder := rfl\n\n@[simp]\nlemma encoder_pure (x : β) (w : σ) :\n (pure x : serializer σ β).encoder w = pure punit.star := rfl\n\n@[simp]\nlemma encoder_map (f : α → β) (w : σ) (x : serializer σ α) :\n (f <$> x : serializer σ β).encoder w = x.encoder w := rfl\n\n@[simp]\nlemma encoder_seq (f : serializer σ (α → β)) (x : serializer σ α) (w : σ) :\n (f <*> x : serializer σ β).encoder w = f.encoder w >> x.encoder w := rfl\n\nend lawful_applicative\n\ninstance {α} : is_lawful_functor (serializer.{u} α) :=\nby refine { .. }; intros; apply serializer.eq; try { ext }; simp [map_map]\n\ninstance {α} : is_lawful_applicative (serializer.{u} α) :=\nby{ constructor; intros; apply serializer.eq; try { ext };\n simp [(>>),pure_seq_eq_map,seq_assoc,bind_assoc], }\n\ndef ser_field {α β} [serial β] (f : α → β) : serializer α β :=\n{ encoder := λ x, encode (f x)\n, decoder := @decode _ _ }\n\nvariables {α β σ γ : Type u} {ω : Type}\n\ndef there_and_back_again\n (y : serializer γ α) (w : γ) : option α :=\ny.decoder -<< y.encoder w\n\nlemma there_and_back_again_seq [serial α]\n (x : serializer γ (α → β)) (f : α → β) (y : γ → α) (w : γ) (w' : β)\n (h' : there_and_back_again x w = pure f)\n (h : w' = f (y w)) :\n there_and_back_again (x <*> ser_field y) w = pure w' :=\nby { simp [there_and_back_again,(>>),seq_eq_bind_map] at *,\n rw [read_write_mono h',map_read_write],\n rw [ser_field,serial.correctness], subst w', refl }\n\n@[simp]\nlemma there_and_back_again_map [serial α]\n (f : α → β) (y : γ → α) (w : γ) :\n there_and_back_again (f <$> ser_field y) w = pure (f $ y w) :=\nby rw [← pure_seq_eq_map,there_and_back_again_seq]; refl\n\n@[simp]\nlemma there_and_back_again_pure (x : β) (w : γ) :\n there_and_back_again (pure x) w =\n pure x := rfl\n\nlemma valid_serializer_of_there_and_back_again\n {α : Type*} (y : serializer α α) :\n valid_serializer y ↔\n ∀ (w : α), there_and_back_again y w = pure w :=\nby { simp [valid_serializer,serial_inverse],\n repeat { rw forall_congr, intro }, refl }\n\nopen ulift\n\ndef ser_field' {α β} [serial β] (f : α → β) : serializer.{max u v} α (ulift.{v} β) :=\nser_field (up ∘ f)\n\ndef of_serializer {α} (s : serializer α α) (h : ∀ w, there_and_back_again s w = pure w) : serial α :=\n{ encode := s.encoder\n, decode := s.decoder\n, correctness := @h }\n\ndef of_serializer₁ {f : Type u → Type v}\n (s : Π α [serial α], serializer (f α) (f α))\n (h : ∀ α [serial α] w, there_and_back_again (s α) w = pure w) : serial1 f :=\n{ encode := λ α inst, (@s α inst).encoder\n, decode := λ α inst, (@s α inst).decoder\n, correctness := @h }\n\ndef of_serializer₂ {f : Type u → Type v → Type w}\n (s : Π α β [serial α] [serial β], serializer (f α β) (f α β))\n (h : ∀ α β [serial α] [serial β] w, there_and_back_again (s α β) w = pure w) : serial2 f :=\n{ encode := λ α β inst inst', (@s α β inst inst').encoder\n, decode := λ α β inst inst', (@s α β inst inst').decoder\n, correctness := @h }\n\nend serializer\n", "meta": {"author": "cipher1024", "repo": "serialean", "sha": "47881e4a6bc0a62cd68520564610b75f8a4fef2c", "save_path": "github-repos/lean/cipher1024-serialean", "path": "github-repos/lean/cipher1024-serialean/serialean-47881e4a6bc0a62cd68520564610b75f8a4fef2c/src/data/serial/basic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.399811640739795, "lm_q2_score": 0.03567855485102608, "lm_q1q2_score": 0.01426470155421351}} {"text": "import tactic.choose\n\n/- choice -/\nexample (h : ∀n m : ℕ, n < m → ∃i j, m = n + i ∨ m + j = n) : true :=\nbegin\n choose i j h using h,\n guard_hyp i : ∀n m : ℕ, n < m → ℕ,\n guard_hyp j : ∀n m : ℕ, n < m → ℕ,\n guard_hyp h : ∀ (n m : ℕ) (h : n < m), m = n + i n m h ∨ m + j n m h = n,\n trivial\nend\n\nexample (h : ∀n m : ℕ, n < m → ∃i j, m = n + i ∨ m + j = n) : true :=\nbegin\n choose! i j h using h,\n guard_hyp i : ℕ → ℕ → ℕ,\n guard_hyp j : ℕ → ℕ → ℕ,\n guard_hyp h : ∀ (n m : ℕ), n < m → m = n + i n m ∨ m + j n m = n,\n trivial\nend\n\nexample (h : ∀n m : ℕ, ∃i, ∀n:ℕ, ∃j, m = n + i ∨ m + j = n) : true :=\nbegin\n choose i j h using h,\n guard_hyp i : ℕ → ℕ → ℕ,\n guard_hyp j : ℕ → ℕ → ℕ → ℕ,\n guard_hyp h : ∀ (n m k : ℕ), m = k + i n m ∨ m + j n m k = k,\n trivial\nend\n\n-- Test `simp only [exists_prop]` gets applied after choosing.\n-- Because of this simp, we need a non-rfl goal\nexample (h : ∀ n, ∃ k ≥ 0, n = k) : ∀ x : ℕ, 1 = 1 :=\nbegin\n choose u hu using h,\n guard_hyp hu : ∀ n, u n ≥ 0 ∧ n = u n,\n intro, refl\nend\n\n-- test choose with conjunction\nexample (h : ∀ i : ℕ, ∃ j, i < j ∧ j < i+i) : true :=\nbegin\n choose f h h' using h,\n guard_hyp f : ℕ → ℕ,\n guard_hyp h : ∀ (i : ℕ), i < f i,\n guard_hyp h' : ∀ (i : ℕ), f i < i + i,\n trivial,\nend\n\n-- test choose with nonempty instances\nuniverse u\nexample {α : Type u} (p : α → Prop) (h : ∀ i : α, p i → ∃ j : α × α, p j.1) : true :=\nbegin\n choose! f h using h,\n guard_hyp f : α → α × α,\n guard_hyp h : ∀ (i : α), p i → p (f i).1,\n trivial,\nend\n", "meta": {"author": "leanprover-community", "repo": "mathlib", "sha": "5e526d18cea33550268dcbbddcb822d5cde40654", "save_path": "github-repos/lean/leanprover-community-mathlib", "path": "github-repos/lean/leanprover-community-mathlib/mathlib-5e526d18cea33550268dcbbddcb822d5cde40654/test/choose.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.25091278688527247, "lm_q2_score": 0.056652428891601526, "lm_q1q2_score": 0.014214818817011466}} {"text": "/-\nCopyright (c) 2020 Scott Morrison. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Scott Morrison, Bhavik Mehta\n-/\nimport category_theory.limits.shapes.pullbacks\nimport category_theory.limits.shapes.strong_epi\nimport category_theory.limits.shapes.equalizers\n\n/-!\n# Definitions and basic properties of regular monomorphisms and epimorphisms.\n\nA regular monomorphism is a morphism that is the equalizer of some parallel pair.\n\nWe give the constructions\n* `split_mono → regular_mono` and\n* `regular_mono → mono`\nas well as the dual constructions for regular epimorphisms. Additionally, we give the construction\n* `regular_epi ⟶ strong_epi`.\n\nWe also define classes `regular_mono_category` and `regular_epi_category` for categories in which\nevery monomorphism or epimorphism is regular, and deduce that these categories are\n`strong_mono_category`s resp. `strong_epi_category`s.\n\n-/\n\nnoncomputable theory\n\nnamespace category_theory\nopen category_theory.limits\n\nuniverses v₁ u₁ u₂\n\nvariables {C : Type u₁} [category.{v₁} C]\n\nvariables {X Y : C}\n\n/-- A regular monomorphism is a morphism which is the equalizer of some parallel pair. -/\nclass regular_mono (f : X ⟶ Y) :=\n(Z : C)\n(left right : Y ⟶ Z)\n(w : f ≫ left = f ≫ right)\n(is_limit : is_limit (fork.of_ι f w))\n\nattribute [reassoc] regular_mono.w\n\n/-- Every regular monomorphism is a monomorphism. -/\n@[priority 100]\ninstance regular_mono.mono (f : X ⟶ Y) [regular_mono f] : mono f :=\nmono_of_is_limit_fork regular_mono.is_limit\n\ninstance equalizer_regular (g h : X ⟶ Y) [has_limit (parallel_pair g h)] :\n regular_mono (equalizer.ι g h) :=\n{ Z := Y,\n left := g,\n right := h,\n w := equalizer.condition g h,\n is_limit := fork.is_limit.mk _ (λ s, limit.lift _ s) (by simp) (λ s m w, by { ext1, simp [←w] }) }\n\n/-- Every split monomorphism is a regular monomorphism. -/\n@[priority 100]\ninstance regular_mono.of_split_mono (f : X ⟶ Y) [split_mono f] : regular_mono f :=\n{ Z := Y,\n left := 𝟙 Y,\n right := retraction f ≫ f,\n w := by tidy,\n is_limit := split_mono_equalizes f }\n\n/-- If `f` is a regular mono, then any map `k : W ⟶ Y` equalizing `regular_mono.left` and\n `regular_mono.right` induces a morphism `l : W ⟶ X` such that `l ≫ f = k`. -/\ndef regular_mono.lift' {W : C} (f : X ⟶ Y) [regular_mono f] (k : W ⟶ Y)\n (h : k ≫ (regular_mono.left : Y ⟶ @regular_mono.Z _ _ _ _ f _) = k ≫ regular_mono.right) :\n {l : W ⟶ X // l ≫ f = k} :=\nfork.is_limit.lift' regular_mono.is_limit _ h\n\n/--\nThe second leg of a pullback cone is a regular monomorphism if the right component is too.\n\nSee also `pullback.snd_of_mono` for the basic monomorphism version, and\n`regular_of_is_pullback_fst_of_regular` for the flipped version.\n-/\ndef regular_of_is_pullback_snd_of_regular {P Q R S : C} {f : P ⟶ Q} {g : P ⟶ R} {h : Q ⟶ S}\n {k : R ⟶ S} [hr : regular_mono h] (comm : f ≫ h = g ≫ k)\n (t : is_limit (pullback_cone.mk _ _ comm)) :\nregular_mono g :=\n{ Z := hr.Z,\n left := k ≫ hr.left,\n right := k ≫ hr.right,\n w := by rw [← reassoc_of comm, ← reassoc_of comm, hr.w],\n is_limit :=\n begin\n apply fork.is_limit.mk' _ _,\n intro s,\n have l₁ : (fork.ι s ≫ k) ≫ regular_mono.left = (fork.ι s ≫ k) ≫ regular_mono.right,\n rw [category.assoc, s.condition, category.assoc],\n obtain ⟨l, hl⟩ := fork.is_limit.lift' hr.is_limit _ l₁,\n obtain ⟨p, hp₁, hp₂⟩ := pullback_cone.is_limit.lift' t _ _ hl,\n refine ⟨p, hp₂, _⟩,\n intros m w,\n have z : m ≫ g = p ≫ g := w.trans hp₂.symm,\n apply t.hom_ext,\n apply (pullback_cone.mk f g comm).equalizer_ext,\n { erw [← cancel_mono h, category.assoc, category.assoc, comm, reassoc_of z] },\n { exact z },\n end }\n\n/--\nThe first leg of a pullback cone is a regular monomorphism if the left component is too.\n\nSee also `pullback.fst_of_mono` for the basic monomorphism version, and\n`regular_of_is_pullback_snd_of_regular` for the flipped version.\n-/\ndef regular_of_is_pullback_fst_of_regular {P Q R S : C} {f : P ⟶ Q} {g : P ⟶ R} {h : Q ⟶ S}\n {k : R ⟶ S} [hr : regular_mono k] (comm : f ≫ h = g ≫ k)\n (t : is_limit (pullback_cone.mk _ _ comm)) :\nregular_mono f :=\nregular_of_is_pullback_snd_of_regular comm.symm (pullback_cone.flip_is_limit t)\n\n@[priority 100]\ninstance strong_mono_of_regular_mono (f : X ⟶ Y) [regular_mono f] : strong_mono f :=\n{ mono := by apply_instance,\n has_lift :=\n begin\n introsI,\n have : v ≫ (regular_mono.left : Y ⟶ regular_mono.Z f) = v ≫ regular_mono.right,\n { apply (cancel_epi z).1,\n simp only [regular_mono.w, ← reassoc_of h] },\n obtain ⟨t, ht⟩ := regular_mono.lift' _ _ this,\n refine arrow.has_lift.mk ⟨t, (cancel_mono f).1 _, ht⟩,\n simp only [arrow.mk_hom, arrow.hom_mk'_left, category.assoc, ht, h]\n end }\n\n/-- A regular monomorphism is an isomorphism if it is an epimorphism. -/\nlemma is_iso_of_regular_mono_of_epi (f : X ⟶ Y) [regular_mono f] [e : epi f] : is_iso f :=\nis_iso_of_epi_of_strong_mono _\n\nsection\nvariables (C)\n\n/-- A regular mono category is a category in which every monomorphism is regular. -/\nclass regular_mono_category :=\n(regular_mono_of_mono : ∀ {X Y : C} (f : X ⟶ Y) [mono f], regular_mono f)\n\nend\n\n/-- In a category in which every monomorphism is regular, we can express every monomorphism as\n an equalizer. This is not an instance because it would create an instance loop. -/\ndef regular_mono_of_mono [regular_mono_category C] (f : X ⟶ Y) [mono f] : regular_mono f :=\nregular_mono_category.regular_mono_of_mono _\n\n@[priority 100]\ninstance regular_mono_category_of_split_mono_category [split_mono_category C] :\n regular_mono_category C :=\n{ regular_mono_of_mono := λ _ _ f _,\n by { haveI := by exactI split_mono_of_mono f, apply_instance } }\n\n@[priority 100]\ninstance strong_mono_category_of_regular_mono_category [regular_mono_category C] :\n strong_mono_category C :=\n{ strong_mono_of_mono := λ _ _ f _,\n by { haveI := by exactI regular_mono_of_mono f, apply_instance } }\n\n/-- A regular epimorphism is a morphism which is the coequalizer of some parallel pair. -/\nclass regular_epi (f : X ⟶ Y) :=\n(W : C)\n(left right : W ⟶ X)\n(w : left ≫ f = right ≫ f)\n(is_colimit : is_colimit (cofork.of_π f w))\n\nattribute [reassoc] regular_epi.w\n\n/-- Every regular epimorphism is an epimorphism. -/\n@[priority 100]\ninstance regular_epi.epi (f : X ⟶ Y) [regular_epi f] : epi f :=\nepi_of_is_colimit_cofork regular_epi.is_colimit\n\ninstance coequalizer_regular (g h : X ⟶ Y) [has_colimit (parallel_pair g h)] :\n regular_epi (coequalizer.π g h) :=\n{ W := X,\n left := g,\n right := h,\n w := coequalizer.condition g h,\n is_colimit := cofork.is_colimit.mk _ (λ s, colimit.desc _ s) (by simp)\n (λ s m w, by { ext1, simp [←w] }) }\n\n/-- Every split epimorphism is a regular epimorphism. -/\n@[priority 100]\ninstance regular_epi.of_split_epi (f : X ⟶ Y) [split_epi f] : regular_epi f :=\n{ W := X,\n left := 𝟙 X,\n right := f ≫ section_ f,\n w := by tidy,\n is_colimit := split_epi_coequalizes f }\n\n/-- If `f` is a regular epi, then every morphism `k : X ⟶ W` coequalizing `regular_epi.left` and\n `regular_epi.right` induces `l : Y ⟶ W` such that `f ≫ l = k`. -/\ndef regular_epi.desc' {W : C} (f : X ⟶ Y) [regular_epi f] (k : X ⟶ W)\n (h : (regular_epi.left : regular_epi.W f ⟶ X) ≫ k = regular_epi.right ≫ k) :\n {l : Y ⟶ W // f ≫ l = k} :=\ncofork.is_colimit.desc' (regular_epi.is_colimit) _ h\n\n/--\nThe second leg of a pushout cocone is a regular epimorphism if the right component is too.\n\nSee also `pushout.snd_of_epi` for the basic epimorphism version, and\n`regular_of_is_pushout_fst_of_regular` for the flipped version.\n-/\ndef regular_of_is_pushout_snd_of_regular\n {P Q R S : C} {f : P ⟶ Q} {g : P ⟶ R} {h : Q ⟶ S} {k : R ⟶ S}\n [gr : regular_epi g] (comm : f ≫ h = g ≫ k) (t : is_colimit (pushout_cocone.mk _ _ comm)) :\nregular_epi h :=\n{ W := gr.W,\n left := gr.left ≫ f,\n right := gr.right ≫ f,\n w := by rw [category.assoc, category.assoc, comm, reassoc_of gr.w],\n is_colimit :=\n begin\n apply cofork.is_colimit.mk' _ _,\n intro s,\n have l₁ : gr.left ≫ f ≫ s.π = gr.right ≫ f ≫ s.π,\n rw [← category.assoc, ← category.assoc, s.condition],\n obtain ⟨l, hl⟩ := cofork.is_colimit.desc' gr.is_colimit (f ≫ cofork.π s) l₁,\n obtain ⟨p, hp₁, hp₂⟩ := pushout_cocone.is_colimit.desc' t _ _ hl.symm,\n refine ⟨p, hp₁, _⟩,\n intros m w,\n have z := w.trans hp₁.symm,\n apply t.hom_ext,\n apply (pushout_cocone.mk _ _ comm).coequalizer_ext,\n { exact z },\n { erw [← cancel_epi g, ← reassoc_of comm, ← reassoc_of comm, z], refl },\n end }\n\n/--\nThe first leg of a pushout cocone is a regular epimorphism if the left component is too.\n\nSee also `pushout.fst_of_epi` for the basic epimorphism version, and\n`regular_of_is_pushout_snd_of_regular` for the flipped version.\n-/\ndef regular_of_is_pushout_fst_of_regular\n {P Q R S : C} {f : P ⟶ Q} {g : P ⟶ R} {h : Q ⟶ S} {k : R ⟶ S}\n [fr : regular_epi f] (comm : f ≫ h = g ≫ k) (t : is_colimit (pushout_cocone.mk _ _ comm)) :\nregular_epi k :=\nregular_of_is_pushout_snd_of_regular comm.symm (pushout_cocone.flip_is_colimit t)\n\n@[priority 100]\ninstance strong_epi_of_regular_epi (f : X ⟶ Y) [regular_epi f] : strong_epi f :=\n{ epi := by apply_instance,\n has_lift :=\n begin\n introsI,\n have : (regular_epi.left : regular_epi.W f ⟶ X) ≫ u = regular_epi.right ≫ u,\n { apply (cancel_mono z).1,\n simp only [category.assoc, h, regular_epi.w_assoc] },\n obtain ⟨t, ht⟩ := regular_epi.desc' f u this,\n exact arrow.has_lift.mk ⟨t, ht, (cancel_epi f).1\n (by simp only [←category.assoc, ht, ←h, arrow.mk_hom, arrow.hom_mk'_right])⟩,\n end }\n\n/-- A regular epimorphism is an isomorphism if it is a monomorphism. -/\nlemma is_iso_of_regular_epi_of_mono (f : X ⟶ Y) [regular_epi f] [m : mono f] : is_iso f :=\nis_iso_of_mono_of_strong_epi _\n\nsection\nvariables (C)\n\n/-- A regular epi category is a category in which every epimorphism is regular. -/\nclass regular_epi_category :=\n(regular_epi_of_epi : ∀ {X Y : C} (f : X ⟶ Y) [epi f], regular_epi f)\n\nend\n\n/-- In a category in which every epimorphism is regular, we can express every epimorphism as\n a coequalizer. This is not an instance because it would create an instance loop. -/\ndef regular_epi_of_epi [regular_epi_category C] (f : X ⟶ Y) [epi f] : regular_epi f :=\nregular_epi_category.regular_epi_of_epi _\n\n@[priority 100]\ninstance regular_epi_category_of_split_epi_category [split_epi_category C] :\n regular_epi_category C :=\n{ regular_epi_of_epi := λ _ _ f _, by { haveI := by exactI split_epi_of_epi f, apply_instance } }\n\n@[priority 100]\ninstance strong_epi_category_of_regular_epi_category [regular_epi_category C] :\n strong_epi_category C :=\n{ strong_epi_of_epi := λ _ _ f _, by { haveI := by exactI regular_epi_of_epi f, apply_instance } }\n\nend category_theory\n", "meta": {"author": "nick-kuhn", "repo": "leantools", "sha": "567a98c031fffe3f270b7b8dea48389bc70d7abb", "save_path": "github-repos/lean/nick-kuhn-leantools", "path": "github-repos/lean/nick-kuhn-leantools/leantools-567a98c031fffe3f270b7b8dea48389bc70d7abb/src/category_theory/limits/shapes/regular_mono.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3738758227716966, "lm_q2_score": 0.0378924305681377, "lm_q1q2_score": 0.01416706365548187}} {"text": "import Mt.Reservation\n\nnamespace Mt.TaskM.impl\n\ninductive IterationResult (spec : Spec) (T : Type)\n| Done : spec.State -> T -> IterationResult spec T\n| Panic : spec.State -> String -> IterationResult spec T\n| Running : spec.State -> (spec.State -> Bool) ->\n (spec.State -> IterationResult spec T) ->\n IterationResult spec T\n\ndef TaskM (spec : Spec) (T : Type) :=spec.State -> IterationResult spec T\n\nnamespace TaskM\n\nvariable {spec : Spec}\n\ndef atomic_read_modify_read\n (f : spec.State -> T × spec.State)\n : TaskM spec T\n| s => match f s with\n | ⟨t, s'⟩ => IterationResult.Done s' t\n\ndef panic {T : Type} (msg : String) : TaskM spec T\n| s => IterationResult.Panic s msg\n\ndef atomic_assert\n (cond : spec.State -> Bool)\n : TaskM spec Unit\n| s => if cond s then\n IterationResult.Done s ⟨⟩\n else\n IterationResult.Panic s \"Assertion failed\"\n\ndef atomic_blocking_rmr\n (block_until : spec.State -> Bool)\n (f : spec.State -> T × spec.State) : TaskM spec T\n| s => IterationResult.Running s block_until (atomic_read_modify_read f)\n\ninductive is_direct_cont {T : Type} : TaskM spec T -> TaskM spec T -> Prop\n| running\n {p cont : TaskM spec T}\n {s s'}\n {block_until : spec.State -> Bool}\n (iteration : p s = IterationResult.Running s' block_until cont)\n : is_direct_cont cont p\n\ntheorem is_direct_cont.wf {T : Type} : WellFounded (@is_direct_cont spec T) :=by\n constructor\n intro p\n constructor\n intro cont is_cont\n cases is_cont\n rename_i s s' bu iteration\n exact helper (p s) cont iteration\n\nwhere\n helper (it : IterationResult spec T) (p : TaskM spec T) {s block_until} :\n it = IterationResult.Running s block_until p → Acc is_direct_cont p :=by\n revert p s block_until\n induction it\n . intros ; contradiction\n . intros ; contradiction\n . intro p s bu h\n rename_i s' bu' p' IH\n injection h ; rename_i h ; rw [h] at IH\n constructor\n intro cont is_cont ; cases is_cont ; rename_i h\n exact IH _ _ h\n\ninstance instWf {T : Type} : WellFoundedRelation (TaskM spec T) where\n rel :=is_direct_cont\n wf :=is_direct_cont.wf\n\ndef pure {T : Type} (t : T) : TaskM spec T :=\n λ s => IterationResult.Done s t\n\ndef bind {U V : Type} (mu : TaskM spec U) (f : U -> TaskM spec V) : TaskM spec V :=\n λ s => match h : mu s with\n | IterationResult.Done s' u => IterationResult.Running s' (λ _ => true) (f u)\n | IterationResult.Panic s' msg => IterationResult.Panic s' msg\n | IterationResult.Running s' block_until cont =>\n have : is_direct_cont cont mu :=⟨h⟩\n IterationResult.Running s' block_until (bind cont f)\ntermination_by bind => mu\n\ntheorem bind_def {U V spec}\n {mu : TaskM spec U} {f : U -> TaskM spec V}\n {s}\n : (bind mu f) s = match mu s with\n | IterationResult.Done s' u => IterationResult.Running s' (λ _ => true) (f u)\n | IterationResult.Panic s' msg => IterationResult.Panic s' msg\n | IterationResult.Running s' block_until cont =>\n IterationResult.Running s' block_until (bind cont f) :=by\n simp only [bind]\n cases mu s <;> rfl\n\ntheorem bind_assoc {U V W : Type}\n (mu : TaskM spec U)\n (f : U -> TaskM spec V)\n (g : V -> TaskM spec W) :\n mu.bind (fun u => (f u).bind g) = (mu.bind f).bind g :=by\n apply funext ; intro s0\n simp only [bind_def]\n induction mu s0 <;> try rfl\n rename_i s' block_until cont IH\n simp only []\n simp only [<- bind_def] at IH\n apply congrArg (IterationResult.Running _ _)\n apply funext ; intro s\n exact IH ..\n\nend TaskM\n\nend Mt.TaskM.impl", "meta": {"author": "mirkootter", "repo": "lean-mt", "sha": "027a16555d487e46a0a00611b8039655378dfdd5", "save_path": "github-repos/lean/mirkootter-lean-mt", "path": "github-repos/lean/mirkootter-lean-mt/lean-mt-027a16555d487e46a0a00611b8039655378dfdd5/Mt/Task/Impl.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3849121444839335, "lm_q2_score": 0.03676946647141984, "lm_q1q2_score": 0.014153014191044304}} {"text": "import vc0.basic\n\nnamespace c0\nopen ast\n\nnamespace value\n\ndef ts_sized (Γ : ast) : type ⊕ sdef → Prop\n| (sum.inl τ) := Γ.sized τ\n| (sum.inr sd) := ∀ τ ∈ sd.values, Γ.sized τ\n\ntheorem default_exists {Γ : ast} (ok : Γ.okind) :\n ∀ ts, ts_sized Γ ts → ∃ (v : value), default Γ ts v :=\nast.okind.induction' ok $ λ Γ ok IH, begin\n have : ∀ {τ}, Γ.sized τ → ∃ (v : value), default Γ (sum.inl τ) v,\n { intros τ sz, induction τ,\n { exact ⟨_, default.int⟩ },\n { exact ⟨_, default.bool⟩ },\n { exact ⟨_, default.ref⟩ },\n { exact ⟨_, default.arr⟩ },\n { cases sz with sd h,\n cases (get_sdef_ex_iff ok).1 ⟨_, h⟩ with xτs m,\n cases IH with d Γ ok' IH'; rcases m with rfl | m,\n { rcases sdecl_ok1 ok' with ⟨nd, sd', al, sz⟩,\n cases get_sdef_determ ok h ⟨or.inl rfl, al.imp $ λ _ _ _ h, h.weak⟩,\n rcases IH' (sum.inr sd) sz with ⟨v, h'⟩,\n exact ⟨_, default.struct h h'.weak⟩ },\n { cases ok,\n cases (get_sdef_ex_iff ok_a_1).2 ⟨_, m⟩ with sd' h₁,\n cases IH' (sum.inl (type.struct τ)) ⟨_, h₁⟩ with v h₂,\n exact ⟨v, h₂.weak⟩ } } },\n rintro (τ | sd) sz,\n { exact this sz },\n { refine alist.rec' (λ sz, ⟨_, default.nil⟩) (λ sd x τ h IH sz, _) sd sz,\n cases list.forall_mem_cons.1 sz with sz₁ sz₂,\n cases this sz₁ with v v0,\n cases IH sz₂ with vs vs0,\n exact ⟨_, default.cons v0 vs0⟩ }\nend\n\nend value\n\nnamespace addr\n\ntheorem update_at.progress {α β} (S : α → β → Prop) {b}\n {R : α → α → Prop} (hR : ∀ x, S x b → ∃ y, R x y) :\n ∀ {l₁ l₂}, list.forall₂ S l₁ l₂ → ∀ {n}, b ∈ list.nth l₂ n → ∃ l', list.update_at R n l₁ l'\n| _ _ (@list.forall₂.cons _ _ S a b' l₁ l₂ r h) 0 rfl :=\n let ⟨y, r⟩ := hR a r in ⟨_, list.update_at.one r⟩\n| _ _ (@list.forall₂.cons _ _ S a b' l₁ l₂ r h) (n+1) h' :=\n let ⟨l₂, r⟩ := update_at.progress h h' in\n ⟨_, list.update_at.cons r⟩\n\ntheorem at_head.progress {Γ E τ τs}\n {R : value → value → Prop} (hR : ∀ x, value.ok Γ E x τ → ∃ y, R x y)\n (x) (xok : value.ok Γ E x (vtype.cons τ τs)) :\n ∃ y, value.at_head R x y :=\nby cases xok; cases hR _ xok_a with v' h'; exact ⟨_, ⟨h'⟩⟩\n\ntheorem at_tail.progress {Γ E τ τs}\n {R : value → value → Prop} (hR : ∀ x, value.ok Γ E x τs → ∃ y, R x y)\n (x) (xok : value.ok Γ E x (vtype.cons τ τs)) :\n ∃ y, value.at_tail R x y :=\nby cases xok; cases hR _ xok_a_1 with v' h'; exact ⟨_, ⟨h'⟩⟩\n\ntheorem at_nth'.progress {Γ E τ}\n {R : value → value → Prop} (hR : ∀ x, value.ok Γ E x τ → ∃ y, R x y) :\n ∀ {i n}, i < n → ∀ x, value.ok Γ E x (vtype.arr' τ n) →\n ∃ y, value.at_nth' R i x y\n| 0 (n+1) h := at_head.progress hR\n| (i+1) (n+1) h := at_tail.progress (at_nth'.progress (nat.lt_of_succ_lt_succ h))\n\ntheorem at_nth.progress {Γ E τ}\n {R : value → value → Prop} (hR : ∀ x, value.ok Γ E x τ → ∃ y, R x y)\n {i n} (lt : i < n) (x) (xok : value.ok Γ E x (vtype.arr τ n)) :\n ∃ y, value.at_nth R i x y :=\nbegin\n cases xok,\n cases at_nth'.progress hR lt _ xok_a with y h,\n exact ⟨_, lt, h⟩\nend\n\ntheorem at_field.progress {Γ E τ}\n {R : value → value → Prop} (hR : ∀ x, value.ok Γ E x τ → ∃ y, R x y)\n {s sd f} (hd : Γ.get_sdef s sd)\n {t} (ht : t ∈ sd.lookup f) (tτ : vtype.of_ty (exp.type.reg t) τ)\n (x) (xok : value.ok Γ E x (vtype.struct s)) :\n ∃ y, value.at_field R f x y :=\nbegin\n rcases xok with _|_|_|_|_|_|_|_|⟨_, vs, rfl, al⟩,\n cases vtype.of_ty_alist sd with τs sτ,\n rcases value.of_map_ok.1 (al _ _ hd sτ) with ⟨vs', e, h⟩,\n cases value.of_map_inj e,\n rcases sτ.rel_of_lookup_right ht with ⟨τ', hτ, tτ'⟩,\n cases vtype.of_ty_determ tτ tτ',\n rcases h.flip.rel_of_lookup_right hτ with ⟨v, m, vok⟩,\n cases hR _ vok with y r,\n exact ⟨_, r, m, rfl, rfl⟩\nend\n\ntheorem update.progress {Γ E σ H η} (ok : ast.okind Γ)\n (Eok : heap.ok Γ H E) (ηok : vars.ok Γ E η σ)\n {a τ} (aok : addr.ok Γ E σ a τ)\n {R : value → value → Prop} (hR : ∀ x, value.ok Γ E x τ → ∃ y, R x y)\n (Rok : ∀ x, value.ok Γ E x τ → ∀ y, R x y → value.ok Γ E y τ) :\n ∃ H' η', update H η R a H' η' :=\nbegin\n induction a generalizing τ R; cases aok,\n { cases update_at.progress _ hR Eok aok_a with H' h,\n exact ⟨_, _, update.ref h⟩ },\n { rcases ηok _ _ aok_a with ⟨v, h, vok⟩,\n cases hR v vok with v' h',\n exact ⟨_, _, update.var h h' rfl⟩ },\n { rcases a_ih aok_a_1 (at_head.progress hR) (at_head.ok Rok) with ⟨H', η', h⟩,\n exact ⟨_, _, update.head h⟩ },\n { rcases a_ih aok_a_1 (at_tail.progress hR) (at_tail.ok Rok) with ⟨H', η', h⟩,\n exact ⟨_, _, update.tail h⟩ },\n { rcases a_ih aok_a_2 (at_nth.progress hR aok_a_1) (at_nth.ok Rok aok_a_1) with ⟨H', η', h⟩,\n exact ⟨_, _, update.nth h⟩ },\n { rcases a_ih aok_a_4 (at_field.progress hR aok_a_1 aok_a_2 aok_a_3)\n (at_field.ok ok Rok aok_a_1 aok_a_2 aok_a_3) with ⟨H', η', h⟩,\n exact ⟨_, _, update.field h⟩ }\nend\n\ntheorem get.progress {Γ E σ Δ H η a τ}\n (Eok : heap.ok Γ H E) (σok : vars_ty.ok Δ σ)\n (ηok : vars.ok Γ E η σ) (aok : addr.ok Γ E σ a τ) :\n ∃ v, get H η a v :=\nbegin\n induction aok,\n { rcases Eok.flip.nth_right aok_a with ⟨v, h, vok⟩,\n exact ⟨_, get.ref h⟩ },\n { rcases ηok _ _ aok_a with ⟨v, h, vok⟩,\n exact ⟨_, get.var h⟩ },\n { rcases aok_ih with ⟨v, h⟩,\n cases get.ok σok Eok ηok aok_a_1 h,\n exact ⟨_, get.head h⟩ },\n { rcases aok_ih with ⟨v, h⟩,\n cases get.ok σok Eok ηok aok_a_1 h,\n exact ⟨_, get.tail h⟩ },\n case c0.addr.ok.nth : a i n τ lt aok IH {\n rcases IH with ⟨_, h⟩,\n cases get.ok σok Eok ηok aok h,\n suffices : ∃ v', value.is_nth i v v',\n { cases this with v' h', exact ⟨v', get.nth h h'⟩ },\n clear h aok _x,\n induction i with i IH generalizing n v,\n { cases n, {cases lt},\n cases a_1, exact ⟨_, value.is_nth.zero⟩ },\n { cases n, {cases lt},\n cases a_1 with _ _ _ _ _ v vs _ _ vok vsok,\n cases IH (nat.lt_of_succ_lt_succ lt) vsok with v' h',\n exact ⟨_, value.is_nth.succ h'⟩ } },\n case c0.addr.ok.field : a s f t sd τ hd hf tτ aok IH {\n rcases IH with ⟨v, h⟩,\n cases get.ok σok Eok ηok aok h, subst v,\n cases vtype.of_ty_alist sd with τs sτ,\n rcases value.of_map_ok.1 (a_1 _ _ hd sτ) with ⟨vs', e, al⟩,\n cases value.of_map_inj e,\n rcases sτ.rel_of_lookup_right hf with ⟨τ', hτ, tτ'⟩,\n cases vtype.of_ty_determ tτ tτ',\n rcases al.flip.rel_of_lookup_right hτ with ⟨v', h', vok⟩,\n exact ⟨v', get.field h h'⟩ }\nend\n\ntheorem get_len.progress {Γ E σ Δ H η a τ n}\n (Eok : heap.ok Γ H E) (σok : vars_ty.ok Δ σ)\n (ηok : vars.ok Γ E η σ) (aok : addr.ok Γ E σ a (vtype.arr τ n)) :\n get_len H η a n :=\nbegin\n cases get.progress Eok σok ηok aok with v h,\n cases get.ok σok Eok ηok aok h, exact ⟨h⟩\nend\n\nend addr\n\ntheorem alloc_arr.progress (i:int32) :\n (∃ (j:ℕ), (i:ℤ) = j) ∨ i < 0 :=\nbegin\n cases lt_or_le (i:ℤ) 0 with h₁,\n { rw [← int32.coe_zero, int32.coe_lt] at h₁,\n exact or.inr h₁ },\n { cases e : (i:ℤ) with j,\n { exact or.inl ⟨_, rfl⟩ },\n { rw e at h, cases h } },\nend\n\ntheorem bounds.progress (n : ℕ) (i:int32) :\n (∃ (j:ℕ), (i:ℤ) = j ∧ j < n) ∨ i < 0 ∨ (n:ℤ) ≤ (i:ℤ) :=\nbegin\n rcases alloc_arr.progress i with ⟨j, e⟩ | h,\n { cases lt_or_le (i:ℤ) (n:ℤ) with h₂,\n { refine or.inl ⟨j, e, int.coe_nat_lt.1 _⟩,\n rw ← e, exact h₂ },\n { exact or.inr (or.inr h) } },\n { exact or.inr (or.inl h) }\nend\n\ntheorem step_binop.progress {Γ E op v₁ v₂ t₁ t₂ τ₁}\n (opok : binop.ok op t₁ t₂)\n (tτ₁ : vtype.of_ty (exp.type.reg t₁) τ₁)\n (vok₁ : value.ok Γ E v₁ τ₁)\n (vok₂ : value.ok Γ E v₂ τ₁) :\n ∃ v, value.step_binop op v₁ v₂ v :=\nbegin\n cases opok,\n case c0.binop.ok.comp {\n cases tτ₁, cases vok₁ with n₁, cases vok₂ with n₂,\n have : ∃ b, value.step_comp opok_1 (value.int n₁) (value.int n₂) b,\n { cases opok_1; exact ⟨_, by constructor⟩ },\n cases this with b h,\n exact ⟨_, value.step_binop.comp h⟩ },\n case c0.binop.ok.eq { exact ⟨_, by constructor; constructor⟩ },\n case c0.binop.ok.ne { exact ⟨_, by constructor; constructor⟩ },\n all_goals {\n cases tτ₁, cases vok₁, cases vok₂,\n exact ⟨_, by constructor⟩ }\nend\n\ntheorem step_unop.progress {Γ E op v t₁ t₂ τ₁}\n (opok : unop.ok op t₁ t₂)\n (tτ : vtype.of_ty (exp.type.reg t₁) τ₁)\n (vok : value.ok Γ E v τ₁) :\n ∃ v', value.step_unop op v v' :=\nby cases opok; {\n cases tτ, cases vok,\n exact ⟨_, by constructor⟩ }\n\ntheorem step_call.progress {Γ E Δ f vs ts τs t τ s}\n (ok : ast.ok Γ)\n (fd : get_fdef Γ f ⟨ts, t⟩)\n (hs : get_body Γ f τ Δ s)\n (tτ : vtype.of_ty (exp.type.ls ts) τs)\n (vsok : value.ok Γ E vs τs) :\n ∃ η, step_call Δ vs η :=\nbegin\n cases hs,\n have : list.forall₂ (λ (c : ident × ast.type), eval_ty Γ c.2) hs_xτs Δ.values,\n { rw [alist.values, list.forall₂_map_right_iff],\n unfold alist.forall₂ at hs_a_1,\n rw [alist.mk'_entries, list.forall₂_map_left_iff] at hs_a_1,\n refine hs_a_1.imp _, rintro _ _ ⟨i, t, τ, h⟩, exact h },\n cases ok.fdef_uniq fd (ast.get_fdef.mk hs_a this hs_a_2),\n clear _x this fd hs_a hs_a_1 hs_a_2 hs_nd,\n change Δ.entries.map sigma.snd with Δ.values,\n refine alist.rec' _ (λ Δ x t h IH, _) Δ vs τs vsok tτ; intros vs τs vsok tτ,\n { cases tτ, cases vsok,\n exact ⟨_, by constructor⟩ },\n { cases tτ, cases vsok,\n rcases IH _ _ vsok_a_1 tτ_a_1 with ⟨η, h⟩,\n exact ⟨_, step_call.cons _ h⟩ }\nend\n\ntheorem step_ret.progress {Γ E σs H S η τ v}\n (Sok : stack.ok Γ E σs S τ) (vok : value.ok Γ E v τ) :\n ∃ s', step_ret ⟨H, S, η⟩ v s' :=\nbegin\n cases Sok,\n { cases vok, exact ⟨_, step_ret.done⟩ },\n { exact ⟨_, step_ret.ret⟩ }\nend\n\ntheorem step_deref.progress {Γ E σ Δ H S η a τ K}\n (Eok : heap.ok Γ H E) (σok : vars_ty.ok Δ σ)\n (ηok : vars.ok Γ E η σ) (aok : addr_opt.ok Γ E σ a τ) :\n ∃ s', step_deref ⟨H, S, η⟩ a K s' :=\nbegin\n cases a,\n { exact ⟨_, step_deref.null⟩ },\n { cases addr.get.progress Eok σok ηok aok with v h,\n exact ⟨_, step_deref.deref h⟩ }\nend\n\ninductive progresses (Γ : ast) (s : state) : Prop\n| final {} : s.final → progresses\n| prog {s'} : step Γ s none s' → progresses\n| io {i} (f : heap × value → state) :\n (∀ o, step Γ s (some (i, o)) (f o)) → progresses\nopen progresses\n\ntheorem progress {Γ : ast} (ok : Γ.ok)\n {s} (stok : state.ok Γ s) : progresses Γ s :=\nbegin\n cases stok,\n case c0.state.ok.stmt : E σs σ Δ C τ δ s K t Cok tτ sok si Kok {\n cases Cok with _ _ _ H η S _ _ σok Eok ηok Sok,\n cases sok,\n { exact prog (step.decl sok_a) },\n { exact prog (step.decl_asgn sok_a) },\n { exact prog step.If₁ },\n { exact prog step.while },\n { cases e : lval.is_var sok_lv,\n { exact prog (step.asgn₁ e) },\n { exact prog (step.asgn_var₁ e) } },\n { exact prog step.asnop₁ },\n { exact prog step.eval₁ },\n { exact prog step.assert₁ },\n { cases sok_e,\n { cases sok_a, cases tτ,\n cases step_ret.progress Sok value.ok.nil with s' h,\n exact prog (step.ret_none h) },\n { exact prog step.ret₁ } },\n { cases K,\n { rcases Kok with ⟨⟨⟩⟩ | Kok,\n cases Kok.eq_none, cases tτ,\n cases step_ret.progress Sok value.ok.nil with s' h,\n exact prog (step.nop₁ h) },\n { exact prog step.nop₂ } },\n { exact prog step.seq } },\n case c0.state.ok.exp : E σs σ H η S Δ ret τ e α K Cok eu lok eok {\n cases Cok with _ _ _ H η S _ _ σok Eok ηok Sok,\n rcases eok with ⟨t, eok, tτ⟩,\n cases α,\n { cases eok,\n { exact prog step.int },\n { exact prog step.bool },\n { exact prog step.null },\n { rcases finmap.exists_mem_lookup_iff.2 (finmap.mem_keys.1 eu) with ⟨τ', iτ'⟩,\n rcases ηok _ _ iτ' with ⟨v, h, vok⟩,\n exact prog (step.var h) },\n { exact prog step.binop₁ },\n { exact prog step.unop₁ },\n { exact prog step.cond₁ },\n { exact prog step.nil },\n { exact prog step.cons₁ },\n { exact prog step.call₁ },\n { exact prog step.field },\n { exact prog step.deref },\n { exact prog step.index },\n { cases value.default_exists ok.ind (sum.inl _) eok_a_1 with v v0,\n exact prog (step.alloc_ref eok_a v0 ⟨⟩) },\n { exact prog (step.alloc_arr₁ eok_a) } },\n { cases lok,\n { exact prog step.addr_var },\n { exact prog step.addr_deref₁ },\n { exact prog step.addr_index₁ },\n { exact prog step.addr_field₁ } } },\n case c0.state.ok.ret : E σs σ H η S Δ ret τ α a K Cok aok Kok {\n cases Cok with _ _ _ H η S _ _ σok Eok ηok Sok,\n cases Kok,\n { cases aok,\n exact prog step.If₂ },\n { exact prog step.asgn₂ },\n { cases Kok_a,\n { exact prog step.asgn_err },\n { rcases addr.update.progress ok.ind Eok ηok\n Kok_a_1 (by exact λ _ _, ⟨a, rfl⟩)\n (addr.eq.ok aok) with ⟨H', η', h⟩,\n exact prog (step.asgn₃ h) } },\n { exact prog step.asgn_var₂ },\n { cases step_deref.progress Eok σok ηok aok with s' h,\n exact prog (step.asnop₂ h) },\n { exact prog step.eval₂ },\n { cases aok,\n exact prog step.assert₂ },\n { cases step_ret.progress Sok aok with s' h,\n exact prog (step.ret₂ h) },\n { cases aok;\n exact prog step.addr_deref₂ },\n { cases a,\n { exact prog step.addr_field_err },\n { exact prog step.addr_field₂ } },\n { cases aok;\n exact prog step.addr_index₂ },\n { cases aok, cases Kok_o,\n { exact prog step.addr_index_err₁ },\n { cases Kok_a _ rfl with n aok,\n have h := addr.get_len.progress Eok σok ηok aok,\n rcases bounds.progress n aok_1 with ⟨j, h₁, h₂⟩ | h',\n { exact prog (step.addr_index₃ h h₁ h₂) },\n { exact prog (step.addr_index_err₂ h h') } } },\n { exact prog step.binop₂ },\n { rcases step_binop.progress Kok_a Kok_a_1 Kok_a_3 aok with ⟨v|err, h⟩,\n { exact prog (step.binop₃ h) },\n { exact prog (step.binop_err h) } },\n { rcases step_unop.progress Kok_a Kok_a_1 aok with ⟨v, h⟩,\n exact prog (step.unop₂ h) },\n { cases aok,\n exact prog step.cond₂ },\n { exact prog step.cons₂ },\n { exact prog step.cons₃ },\n { cases Kok,\n rcases Kok_a_6 with ext | ⟨τ, Δ, s, h⟩,\n { exact progresses.io\n (λ o, state.ret cont_ty.V ⟨o.1, S, η⟩ o.2 Kok_K)\n (λ ⟨H', v⟩, step.call_extern ext) },\n { cases step_call.progress ok Kok_a_5 h Kok_a_8 aok with η h',\n exact prog (step.call₂ h h') } },\n { cases step_deref.progress Eok σok ηok aok with s' h,\n exact prog (step.deref' h) },\n { cases aok,\n rcases alloc_arr.progress aok_1 with ⟨j, h⟩ | h,\n { cases value.default_exists ok.ind (sum.inl _) Kok_a_1 with v v0,\n exact prog (step.alloc_arr₂ h v0 ⟨⟩) },\n { exact prog (step.alloc_arr_err h) } } },\n case c0.state.ok.err : err { exact final state.final.err },\n case c0.state.ok.done : n { exact final state.final.done },\nend\n\nend c0\n", "meta": {"author": "digama0", "repo": "vc0", "sha": "b8b192c8c139e0b5a25a7284b93ed53cdf7fd7a5", "save_path": "github-repos/lean/digama0-vc0", "path": "github-repos/lean/digama0-vc0/vc0-b8b192c8c139e0b5a25a7284b93ed53cdf7fd7a5/src/vc0/progress.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167793123159, "lm_q2_score": 0.030675801378361855, "lm_q1q2_score": 0.014142059154276682}} {"text": "/-\nCopyright (c) 2019 Simon Hudon. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Simon Hudon\n-/\nimport tactic.monotonicity.basic\nimport control.traversable\nimport control.traversable.derive\nimport data.dlist\n\nvariables {a b c p : Prop}\n\nnamespace tactic.interactive\n\nopen lean lean.parser interactive\nopen interactive.types\nopen tactic\n\nlocal postfix `?`:9001 := optional\nlocal postfix *:9001 := many\n\nmeta inductive mono_function (elab : bool := tt)\n | non_assoc : expr elab → list (expr elab) → list (expr elab) → mono_function\n | assoc : expr elab → option (expr elab) → option (expr elab) → mono_function\n | assoc_comm : expr elab → expr elab → mono_function\n\nmeta instance : decidable_eq mono_function :=\nby mk_dec_eq_instance\n\nmeta def mono_function.to_tactic_format : mono_function → tactic format\n | (mono_function.non_assoc fn xs ys) := do\n fn' ← pp fn,\n xs' ← mmap pp xs,\n ys' ← mmap pp ys,\n return format!\"{fn'} {xs'} _ {ys'}\"\n | (mono_function.assoc fn xs ys) := do\n fn' ← pp fn,\n xs' ← pp xs,\n ys' ← pp ys,\n return format!\"{fn'} {xs'} _ {ys'}\"\n | (mono_function.assoc_comm fn xs) := do\n fn' ← pp fn,\n xs' ← pp xs,\n return format!\"{fn'} _ {xs'}\"\n\nmeta instance has_to_tactic_format_mono_function : has_to_tactic_format mono_function :=\n{ to_tactic_format := mono_function.to_tactic_format }\n\n@[derive traversable]\nmeta structure ac_mono_ctx' (rel : Type) :=\n (to_rel : rel)\n (function : mono_function)\n (left right rel_def : expr)\n\n@[reducible]\nmeta def ac_mono_ctx := ac_mono_ctx' (option (expr → expr → expr))\n@[reducible]\nmeta def ac_mono_ctx_ne := ac_mono_ctx' (expr → expr → expr)\n\nmeta def ac_mono_ctx.to_tactic_format (ctx : ac_mono_ctx) : tactic format :=\ndo fn ← pp ctx.function,\n l ← pp ctx.left,\n r ← pp ctx.right,\n rel ← pp ctx.rel_def,\n return format!\"{{ function := {fn}\\n, left := {l}\\n, right := {r}\\n, rel_def := {rel} }\"\n\nmeta instance has_to_tactic_format_mono_ctx : has_to_tactic_format ac_mono_ctx :=\n{ to_tactic_format := ac_mono_ctx.to_tactic_format }\n\nmeta def as_goal (e : expr) (tac : tactic unit) : tactic unit :=\ndo gs ← get_goals,\n set_goals [e],\n tac,\n set_goals gs\n\nopen list (hiding map) functor dlist\n\nsection config\n\nparameter opt : mono_cfg\nparameter asms : list expr\n\nmeta def unify_with_instance (e : expr) : tactic unit :=\nas_goal e $\napply_instance\n<|>\napply_opt_param\n<|>\napply_auto_param\n<|>\ntactic.solve_by_elim { lemmas := some asms }\n<|>\nreflexivity\n<|>\napplyc ``id\n<|>\nreturn ()\n\nprivate meta def match_rule_head (p : expr)\n: list expr → expr → expr → tactic expr\n | vs e t :=\n(unify t p >> mmap' unify_with_instance vs >> instantiate_mvars e)\n<|>\ndo (expr.pi _ _ d b) ← return t | failed,\n v ← mk_meta_var d,\n match_rule_head (v::vs) (expr.app e v) (b.instantiate_var v)\n\nmeta def pi_head : expr → tactic expr\n| (expr.pi n _ t b) :=\ndo v ← mk_meta_var t,\n pi_head (b.instantiate_var v)\n| e := return e\n\nmeta def delete_expr (e : expr)\n: list expr → tactic (option (list expr))\n | [] := return none\n | (x :: xs) :=\n(compare opt e x >> return (some xs))\n<|>\n(map (cons x) <$> delete_expr xs)\n\nmeta def match_ac'\n: list expr → list expr → tactic (list expr × list expr × list expr)\n | es (x :: xs) := do\n es' ← delete_expr x es,\n match es' with\n | (some es') := do\n (c,l,r) ← match_ac' es' xs, return (x::c,l,r)\n | none := do\n (c,l,r) ← match_ac' es xs, return (c,l,x::r)\n end\n | es [] := do\nreturn ([],es,[])\n\nmeta def match_ac (l : list expr) (r : list expr)\n: tactic (list expr × list expr × list expr) :=\ndo (s',l',r') ← match_ac' l r,\n s' ← mmap instantiate_mvars s',\n l' ← mmap instantiate_mvars l',\n r' ← mmap instantiate_mvars r',\n return (s',l',r')\n\nmeta def match_prefix\n: list expr → list expr → tactic (list expr × list expr × list expr)\n| (x :: xs) (y :: ys) :=\n (do compare opt x y,\n prod.map ((::) x) id <$> match_prefix xs ys)\n<|> return ([],x :: xs,y :: ys)\n| xs ys := return ([],xs,ys)\n\n/--\n`(prefix,left,right,suffix) ← match_assoc unif l r` finds the\nlongest prefix and suffix common to `l` and `r` and\nreturns them along with the differences -/\nmeta def match_assoc (l : list expr) (r : list expr)\n: tactic (list expr × list expr × list expr × list expr) :=\ndo (pre,l₁,r₁) ← match_prefix l r,\n (suf,l₂,r₂) ← match_prefix (reverse l₁) (reverse r₁),\n return (pre,reverse l₂,reverse r₂,reverse suf)\n\nmeta def check_ac : expr → tactic (bool × bool × option (expr × expr × expr) × expr)\n | (expr.app (expr.app f x) y) :=\n do t ← infer_type x,\n a ← try_core $ to_expr ``(is_associative %%t %%f) >>= mk_instance,\n c ← try_core $ to_expr ``(is_commutative %%t %%f) >>= mk_instance,\n i ← try_core (do\n v ← mk_meta_var t,\n l_inst_p ← to_expr ``(is_left_id %%t %%f %%v),\n r_inst_p ← to_expr ``(is_right_id %%t %%f %%v),\n l_v ← mk_meta_var l_inst_p,\n r_v ← mk_meta_var r_inst_p ,\n l_id ← mk_mapp `is_left_id.left_id [some t,f,v,some l_v],\n mk_instance l_inst_p >>= unify l_v,\n r_id ← mk_mapp `is_right_id.right_id [none,f,v,some r_v],\n mk_instance r_inst_p >>= unify r_v,\n v' ← instantiate_mvars v,\n return (l_id,r_id,v')),\n return (a.is_some,c.is_some,i,f)\n | _ := return (ff,ff,none,expr.var 1)\n\nmeta def parse_assoc_chain' (f : expr) : expr → tactic (dlist expr)\n | e :=\n (do (expr.app (expr.app f' x) y) ← return e,\n is_def_eq f f',\n (++) <$> parse_assoc_chain' x <*> parse_assoc_chain' y)\n<|> return (singleton e)\n\nmeta def parse_assoc_chain (f : expr) : expr → tactic (list expr) :=\nmap dlist.to_list ∘ parse_assoc_chain' f\n\nmeta def fold_assoc (op : expr) : option (expr × expr × expr) → list expr → option (expr × list expr)\n| _ (x::xs) := some (foldl (expr.app ∘ expr.app op) x xs, [])\n| none [] := none\n| (some (l_id,r_id,x₀)) [] := some (x₀,[l_id,r_id])\n\nmeta def fold_assoc1 (op : expr) : list expr → option expr\n| (x::xs) := some $ foldl (expr.app ∘ expr.app op) x xs\n| [] := none\n\nmeta def same_function_aux\n: list expr → list expr → expr → expr → tactic (expr × list expr × list expr)\n | xs₀ xs₁ (expr.app f₀ a₀) (expr.app f₁ a₁) :=\n same_function_aux (a₀ :: xs₀) (a₁ :: xs₁) f₀ f₁\n | xs₀ xs₁ e₀ e₁ := is_def_eq e₀ e₁ >> return (e₀,xs₀,xs₁)\n\nmeta def same_function : expr → expr → tactic (expr × list expr × list expr) :=\nsame_function_aux [] []\n\nmeta def parse_ac_mono_function (l r : expr)\n: tactic (expr × expr × list expr × mono_function) :=\ndo (full_f,ls,rs) ← same_function l r,\n (a,c,i,f) ← check_ac l,\n if a\n then if c\n then do\n (s,ls,rs) ← monad.join (match_ac\n <$> parse_assoc_chain f l\n <*> parse_assoc_chain f r),\n (l',l_id) ← fold_assoc f i ls,\n (r',r_id) ← fold_assoc f i rs,\n s' ← fold_assoc1 f s,\n return (l',r',l_id ++ r_id,mono_function.assoc_comm f s')\n else do -- a ∧ ¬ c\n (pre,ls,rs,suff) ← monad.join (match_assoc\n <$> parse_assoc_chain f l\n <*> parse_assoc_chain f r),\n (l',l_id) ← fold_assoc f i ls,\n (r',r_id) ← fold_assoc f i rs,\n let pre' := fold_assoc1 f pre,\n let suff' := fold_assoc1 f suff,\n return (l',r',l_id ++ r_id,mono_function.assoc f pre' suff')\n else do -- ¬ a\n (xs₀,x₀,x₁,xs₁) ← find_one_difference opt ls rs,\n return (x₀,x₁,[],mono_function.non_assoc full_f xs₀ xs₁)\n\nmeta def parse_ac_mono_function' (l r : pexpr) :=\ndo l' ← to_expr l,\n r' ← to_expr r,\n parse_ac_mono_function l' r'\n\nmeta def ac_monotonicity_goal : expr → tactic (expr × expr × list expr × ac_mono_ctx)\n | `(%%e₀ → %%e₁) :=\n do (l,r,id_rs,f) ← parse_ac_mono_function e₀ e₁,\n t₀ ← infer_type e₀,\n t₁ ← infer_type e₁,\n rel_def ← to_expr ``(λ x₀ x₁, (x₀ : %%t₀) → (x₁ : %%t₁)),\n return (e₀, e₁, id_rs,\n { function := f\n , left := l, right := r\n , to_rel := some $ expr.pi `x binder_info.default\n , rel_def := rel_def })\n | `(%%e₀ = %%e₁) :=\n do (l,r,id_rs,f) ← parse_ac_mono_function e₀ e₁,\n t₀ ← infer_type e₀,\n t₁ ← infer_type e₁,\n rel_def ← to_expr ``(λ x₀ x₁, (x₀ : %%t₀) = (x₁ : %%t₁)),\n return (e₀, e₁, id_rs,\n { function := f\n , left := l, right := r\n , to_rel := none\n , rel_def := rel_def })\n | (expr.app (expr.app rel e₀) e₁) :=\n do (l,r,id_rs,f) ← parse_ac_mono_function e₀ e₁,\n return (e₀, e₁, id_rs,\n { function := f\n , left := l, right := r\n , to_rel := expr.app ∘ expr.app rel\n , rel_def := rel })\n | _ := fail \"invalid monotonicity goal\"\n\nmeta def bin_op_left (f : expr) : option expr → expr → expr\n| none e := e\n| (some e₀) e₁ := f.mk_app [e₀,e₁]\n\nmeta def bin_op (f a b : expr) : expr :=\nf.mk_app [a,b]\n\nmeta def bin_op_right (f : expr) : expr → option expr → expr\n| e none := e\n| e₀ (some e₁) := f.mk_app [e₀,e₁]\n\nmeta def mk_fun_app : mono_function → expr → expr\n | (mono_function.non_assoc f x y) z := f.mk_app (x ++ z :: y)\n | (mono_function.assoc f x y) z := bin_op_left f x (bin_op_right f z y)\n | (mono_function.assoc_comm f x) z := f.mk_app [z,x]\n\nmeta inductive mono_law\n /- `assoc (l₀,r₀) (r₁,l₁)` gives first how to find rules to prove\n x+(y₀+z) R x+(y₁+z);\n if that fails, helps prove (x+y₀)+z R (x+y₁)+z -/\n | assoc : expr × expr → expr × expr → mono_law\n /- `congr r` gives the rule to prove `x = y → f x = f y` -/\n | congr : expr → mono_law\n | other : expr → mono_law\n\nmeta def mono_law.to_tactic_format : mono_law → tactic format\n | (mono_law.other e) := do e ← pp e, return format!\"other {e}\"\n | (mono_law.congr r) := do e ← pp r, return format!\"congr {e}\"\n | (mono_law.assoc (x₀,x₁) (y₀,y₁)) :=\ndo x₀ ← pp x₀,\n x₁ ← pp x₁,\n y₀ ← pp y₀,\n y₁ ← pp y₁,\n return format!\"assoc {x₀}; {x₁} | {y₀}; {y₁}\"\n\nmeta instance has_to_tactic_format_mono_law : has_to_tactic_format mono_law :=\n{ to_tactic_format := mono_law.to_tactic_format }\n\nmeta def mk_rel (ctx : ac_mono_ctx_ne) (f : expr → expr) : expr :=\nctx.to_rel (f ctx.left) (f ctx.right)\n\nmeta def mk_congr_args (fn : expr) (xs₀ xs₁ : list expr) (l r : expr) : tactic expr :=\ndo p ← mk_app `eq [fn.mk_app $ xs₀ ++ l :: xs₁,fn.mk_app $ xs₀ ++ r :: xs₁],\n prod.snd <$> solve_aux p\n (do iterate_exactly (xs₁.length) (applyc `congr_fun),\n applyc `congr_arg)\n\nmeta def mk_congr_law (ctx : ac_mono_ctx) : tactic expr :=\nmatch ctx.function with\n | (mono_function.assoc f x₀ x₁) :=\n if (x₀ <|> x₁).is_some\n then mk_congr_args f x₀.to_monad x₁.to_monad ctx.left ctx.right\n else failed\n | (mono_function.assoc_comm f x₀) := mk_congr_args f [x₀] [] ctx.left ctx.right\n | (mono_function.non_assoc f x₀ x₁) := mk_congr_args f x₀ x₁ ctx.left ctx.right\nend\n\nmeta def mk_pattern (ctx : ac_mono_ctx) : tactic mono_law :=\nmatch (sequence ctx : option (ac_mono_ctx' _)) with\n | (some ctx) :=\n match ctx.function with\n | (mono_function.assoc f (some x) (some y)) :=\n return $ mono_law.assoc\n ( mk_rel ctx (λ i, bin_op f x (bin_op f i y))\n , mk_rel ctx (λ i, bin_op f i y))\n ( mk_rel ctx (λ i, bin_op f (bin_op f x i) y)\n , mk_rel ctx (λ i, bin_op f x i))\n | (mono_function.assoc f (some x) none) :=\n return $ mono_law.other $\n mk_rel ctx (λ e, mk_fun_app ctx.function e)\n | (mono_function.assoc f none (some y)) :=\n return $ mono_law.other $\n mk_rel ctx (λ e, mk_fun_app ctx.function e)\n | (mono_function.assoc f none none) :=\n none\n | _ :=\n return $ mono_law.other $\n mk_rel ctx (λ e, mk_fun_app ctx.function e)\n end\n | none := mono_law.congr <$> mk_congr_law ctx\nend\n\nmeta def match_rule (pat : expr) (r : name) : tactic expr :=\ndo r' ← mk_const r,\n t ← infer_type r',\n t ← expr.dsimp t { fail_if_unchanged := ff } tt [] [\n simp_arg_type.expr ``(monotone), simp_arg_type.expr ``(strict_mono)],\n match_rule_head pat [] r' t\n\nmeta def find_lemma (pat : expr) : list name → tactic (list expr)\n | [] := return []\n | (r :: rs) :=\n do (cons <$> match_rule pat r <|> pure id) <*> find_lemma rs\n\nmeta def match_chaining_rules (ls : list name) (x₀ x₁ : expr) : tactic (list expr) :=\ndo x' ← to_expr ``(%%x₁ → %%x₀),\n r₀ ← find_lemma x' ls,\n r₁ ← find_lemma x₁ ls,\n return (expr.app <$> r₀ <*> r₁)\n\nmeta def find_rule (ls : list name) : mono_law → tactic (list expr)\n | (mono_law.assoc (x₀,x₁) (y₀,y₁)) :=\n(match_chaining_rules ls x₀ x₁)\n<|> (match_chaining_rules ls y₀ y₁)\n | (mono_law.congr r) := return [r]\n | (mono_law.other p) := find_lemma p ls\n\nuniverses u v\n\ndef apply_rel {α : Sort u} (R : α → α → Sort v) {x y : α}\n (x' y' : α)\n (h : R x y)\n (hx : x = x')\n (hy : y = y')\n: R x' y' :=\nby { rw [← hx,← hy], apply h }\n\nmeta def ac_refine (e : expr) : tactic unit :=\nrefine ``(eq.mp _ %%e) ; ac_refl\n\nmeta def one_line (e : expr) : tactic format :=\ndo lbl ← pp e,\n asm ← infer_type e >>= pp,\n return format!\"\\t{asm}\\n\"\n\nmeta def side_conditions (e : expr) : tactic format :=\ndo let vs := e.list_meta_vars,\n ts ← mmap one_line vs.tail,\n let r := e.get_app_fn.const_name,\n return format!\"{r}:\\n{format.join ts}\"\n\nopen monad\n\n/-- tactic-facing function, similar to `interactive.tactic.generalize` with the\nexception that meta variables -/\nprivate meta def monotonicity.generalize' (h : name) (v : expr) (x : name) : tactic (expr × expr) :=\ndo tgt ← target,\n t ← infer_type v,\n tgt' ← do {\n ⟨tgt', _⟩ ← solve_aux tgt (tactic.generalize v x >> target),\n to_expr ``(λ y : %%t, Π x, y = x → %%(tgt'.binding_body.lift_vars 0 1))\n } <|> to_expr ``(λ y : %%t, Π x, %%v = x → %%tgt),\n t ← head_beta (tgt' v) >>= assert h,\n swap,\n r ← mk_eq_refl v,\n solve1 $ tactic.exact (t v r),\n prod.mk <$> tactic.intro x <*> tactic.intro h\n\nprivate meta def hide_meta_vars (tac : list expr → tactic unit) : tactic unit :=\nfocus1 $\ndo tgt ← target >>= instantiate_mvars,\n tactic.change tgt,\n ctx ← local_context,\n let vs := tgt.list_meta_vars,\n vs' ← mmap (λ v,\n do h ← get_unused_name `h,\n x ← get_unused_name `x,\n prod.snd <$> monotonicity.generalize' h v x) vs,\n tac ctx;\n vs'.mmap' (try ∘ tactic.subst)\n\nmeta def hide_meta_vars' (tac : itactic) : itactic :=\nhide_meta_vars $ λ _, tac\n\nend config\n\nmeta def solve_mvar (v : expr) (tac : tactic unit) : tactic unit :=\ndo gs ← get_goals,\n set_goals [v],\n target >>= instantiate_mvars >>= tactic.change,\n tac, done,\n set_goals $ gs\n\ndef list.minimum_on {α β} [linear_order β] (f : α → β) : list α → list α\n| [] := []\n| (x :: xs) := prod.snd $ xs.foldl (λ ⟨k,a⟩ b,\n let k' := f b in\n if k < k' then (k,a)\n else if k' < k then (k', [b])\n else (k,b :: a)) (f x, [x])\n\nopen format mono_selection\n\nmeta def best_match {β} (xs : list expr) (tac : expr → tactic β) : tactic unit :=\ndo t ← target,\n xs ← xs.mmap (λ x,\n try_core $ prod.mk x <$> solve_aux t (tac x >> get_goals)),\n let xs := xs.filter_map id,\n let r := list.minimum_on (list.length ∘ prod.fst ∘ prod.snd) xs,\n match r with\n | [(_,gs,pr)] := tactic.exact pr >> set_goals gs\n | [] := fail \"no good match found\"\n | _ :=\n do lmms ← r.mmap (λ ⟨l,gs,_⟩,\n do ts ← gs.mmap infer_type,\n msg ← ts.mmap pp,\n pure $ foldl compose \"\\n\\n\" (list.intersperse \"\\n\" $ to_fmt l.get_app_fn.const_name :: msg)),\n let msg := foldl compose \"\" lmms,\n fail format!\"ambiguous match: {msg}\\n\\nTip: try asserting a side condition to distinguish between the lemmas\"\n end\n\nmeta def mono_aux (dir : parse side) :\n tactic unit :=\ndo t ← target >>= instantiate_mvars,\n ns ← get_monotonicity_lemmas t dir,\n asms ← local_context,\n rs ← find_lemma asms t ns,\n focus1 $ () <$ best_match rs (λ law, tactic.refine $ to_pexpr law)\n\n/--\n- `mono` applies a monotonicity rule.\n- `mono*` applies monotonicity rules repetitively.\n- `mono with x ≤ y` or `mono with [0 ≤ x,0 ≤ y]` creates an assertion for the listed\n propositions. Those help to select the right monotonicity rule.\n- `mono left` or `mono right` is useful when proving strict orderings:\n for `x + y < w + z` could be broken down into either\n - left: `x ≤ w` and `y < z` or\n - right: `x < w` and `y ≤ z`\n- `mono using [rule1,rule2]` calls `simp [rule1,rule2]` before applying mono.\n- The general syntax is `mono '*'? ('with' hyp | 'with' [hyp1,hyp2])? ('using' [hyp1,hyp2])? mono_cfg?\n\nTo use it, first import `tactic.monotonicity`.\n\nHere is an example of mono:\n\n```lean\nexample (x y z k : ℤ)\n (h : 3 ≤ (4 : ℤ))\n (h' : z ≤ y) :\n (k + 3 + x) - y ≤ (k + 4 + x) - z :=\nbegin\n mono, -- unfold `(-)`, apply add_le_add\n { -- ⊢ k + 3 + x ≤ k + 4 + x\n mono, -- apply add_le_add, refl\n -- ⊢ k + 3 ≤ k + 4\n mono },\n { -- ⊢ -y ≤ -z\n mono /- apply neg_le_neg -/ }\nend\n```\n\nMore succinctly, we can prove the same goal as:\n\n```lean\nexample (x y z k : ℤ)\n (h : 3 ≤ (4 : ℤ))\n (h' : z ≤ y) :\n (k + 3 + x) - y ≤ (k + 4 + x) - z :=\nby mono*\n```\n\n-/\nmeta def mono (many : parse (tk \"*\")?)\n (dir : parse side)\n (hyps : parse $ tk \"with\" *> pexpr_list_or_texpr <|> pure [])\n (simp_rules : parse $ tk \"using\" *> simp_arg_list <|> pure []) :\n tactic unit :=\ndo hyps ← hyps.mmap (λ p, to_expr p >>= mk_meta_var),\n hyps.mmap' (λ pr, do h ← get_unused_name `h, note h none pr),\n when (¬ simp_rules.empty) (simp_core { } failed tt simp_rules [] (loc.ns [none]) >> skip),\n if many.is_some\n then repeat $ mono_aux dir\n else mono_aux dir,\n gs ← get_goals,\n set_goals $ hyps ++ gs\n\nadd_tactic_doc\n{ name := \"mono\",\n category := doc_category.tactic,\n decl_names := [`tactic.interactive.mono],\n tags := [\"monotonicity\"] }\n\n/--\ntransforms a goal of the form `f x ≼ f y` into `x ≤ y` using lemmas\nmarked as `monotonic`.\n\nSpecial care is taken when `f` is the repeated application of an\nassociative operator and if the operator is commutative\n-/\nmeta def ac_mono_aux (cfg : mono_cfg := { mono_cfg . }) :\n tactic unit :=\nhide_meta_vars $ λ asms,\ndo try `[simp only [sub_eq_add_neg]],\n tgt ← target >>= instantiate_mvars,\n (l,r,id_rs,g) ← ac_monotonicity_goal cfg tgt\n <|> fail \"monotonic context not found\",\n ns ← get_monotonicity_lemmas tgt both,\n p ← mk_pattern g,\n rules ← find_rule asms ns p <|> fail \"no applicable rules found\",\n when (rules = []) (fail \"no applicable rules found\"),\n err ← format.join <$> mmap side_conditions rules,\n focus1 $ best_match rules (λ rule, do\n t₀ ← mk_meta_var `(Prop),\n v₀ ← mk_meta_var t₀,\n t₁ ← mk_meta_var `(Prop),\n v₁ ← mk_meta_var t₁,\n tactic.refine $ ``(apply_rel %%(g.rel_def) %%l %%r %%rule %%v₀ %%v₁),\n solve_mvar v₀ (try (any_of id_rs rewrite_target) >>\n ( done <|>\n refl <|>\n ac_refl <|>\n `[simp only [is_associative.assoc]]) ),\n solve_mvar v₁ (try (any_of id_rs rewrite_target) >>\n ( done <|>\n refl <|>\n ac_refl <|>\n `[simp only [is_associative.assoc]]) ),\n n ← num_goals,\n iterate_exactly (n-1) (try $ solve1 $ apply_instance <|>\n tactic.solve_by_elim { lemmas := some asms }))\n\nopen sum nat\n\n/-- (repeat_until_or_at_most n t u): repeat tactic `t` at most n times or until u succeeds -/\nmeta def repeat_until_or_at_most : nat → tactic unit → tactic unit → tactic unit\n| 0 t _ := fail \"too many applications\"\n| (succ n) t u := u <|> (t >> repeat_until_or_at_most n t u)\n\nmeta def repeat_until : tactic unit → tactic unit → tactic unit :=\nrepeat_until_or_at_most 100000\n\n@[derive _root_.has_reflect, derive _root_.inhabited]\ninductive rep_arity : Type\n| one | exactly (n : ℕ) | many\n\nmeta def repeat_or_not : rep_arity → tactic unit → option (tactic unit) → tactic unit\n | rep_arity.one tac none := tac\n | rep_arity.many tac none := repeat tac\n | (rep_arity.exactly n) tac none := iterate_exactly' n tac\n | rep_arity.one tac (some until) := tac >> until\n | rep_arity.many tac (some until) := repeat_until tac until\n | (rep_arity.exactly n) tac (some until) := iterate_exactly n tac >> until\n\nmeta def assert_or_rule : lean.parser (pexpr ⊕ pexpr) :=\n(tk \":=\" *> inl <$> texpr <|> (tk \":\" *> inr <$> texpr))\n\nmeta def arity : lean.parser rep_arity :=\nrep_arity.many <$ tk \"*\" <|>\nrep_arity.exactly <$> (tk \"^\" *> small_nat) <|>\npure rep_arity.one\n\n/--\n\n`ac_mono` reduces the `f x ⊑ f y`, for some relation `⊑` and a\nmonotonic function `f` to `x ≺ y`.\n\n`ac_mono*` unwraps monotonic functions until it can't.\n\n`ac_mono^k`, for some literal number `k` applies monotonicity `k`\ntimes.\n\n`ac_mono h`, with `h` a hypothesis, unwraps monotonic functions and\nuses `h` to solve the remaining goal. Can be combined with `*` or `^k`:\n`ac_mono* h`\n\n`ac_mono : p` asserts `p` and uses it to discharge the goal result\nunwrapping a series of monotonic functions. Can be combined with * or\n^k: `ac_mono* : p`\n\nIn the case where `f` is an associative or commutative operator,\n`ac_mono` will consider any possible permutation of its arguments and\nuse the one the minimizes the difference between the left-hand side\nand the right-hand side.\n\nTo use it, first import `tactic.monotonicity`.\n\n`ac_mono` can be used as follows:\n\n```lean\nexample (x y z k m n : ℕ)\n (h₀ : z ≥ 0)\n (h₁ : x ≤ y) :\n (m + x + n) * z + k ≤ z * (y + n + m) + k :=\nbegin\n ac_mono,\n -- ⊢ (m + x + n) * z ≤ z * (y + n + m)\n ac_mono,\n -- ⊢ m + x + n ≤ y + n + m\n ac_mono,\nend\n```\n\nAs with `mono*`, `ac_mono*` solves the goal in one go and so does\n`ac_mono* h₁`. The latter syntax becomes especially interesting in the\nfollowing example:\n\n```lean\nexample (x y z k m n : ℕ)\n (h₀ : z ≥ 0)\n (h₁ : m + x + n ≤ y + n + m) :\n (m + x + n) * z + k ≤ z * (y + n + m) + k :=\nby ac_mono* h₁.\n```\n\nBy giving `ac_mono` the assumption `h₁`, we are asking `ac_refl` to\nstop earlier than it would normally would.\n-/\nmeta def ac_mono (rep : parse arity) :\n parse assert_or_rule? →\n opt_param mono_cfg { mono_cfg . } →\n tactic unit\n | none opt := focus1 $ repeat_or_not rep (ac_mono_aux opt) none\n | (some (inl h)) opt :=\ndo focus1 $ repeat_or_not rep (ac_mono_aux opt) (some $ done <|> to_expr h >>= ac_refine)\n | (some (inr t)) opt :=\ndo h ← i_to_expr t >>= assert `h,\n tactic.swap,\n focus1 $ repeat_or_not rep (ac_mono_aux opt) (some $ done <|> ac_refine h)\n/-\nTODO(Simon): with `ac_mono h` and `ac_mono : p` split the remaining\n gaol if the provided rule does not solve it completely.\n-/\n\nadd_tactic_doc\n{ name := \"ac_mono\",\n category := doc_category.tactic,\n decl_names := [`tactic.interactive.ac_mono],\n tags := [\"monotonicity\"] }\n\nattribute [mono] and.imp or.imp\n\nend tactic.interactive\n", "meta": {"author": "JLimperg", "repo": "aesop3", "sha": "a4a116f650cc7403428e72bd2e2c4cda300fe03f", "save_path": "github-repos/lean/JLimperg-aesop3", "path": "github-repos/lean/JLimperg-aesop3/aesop3-a4a116f650cc7403428e72bd2e2c4cda300fe03f/src/tactic/monotonicity/interactive.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.37754066879814546, "lm_q2_score": 0.0373268831943749, "lm_q1q2_score": 0.014092416445354557}} {"text": "import tactic\nimport .boolset2d\nimport .sokostate\nimport .boxint\nimport .sokolevel\nimport .sokowidget\n\ndef boxint.generate_from_list (avail : bset2d) (boxes blocks : list (ℕ × ℕ)) (sk : ℕ × ℕ) : boxint\n:=\nlet boxes2d := (bset2d.from_indexes boxes) in\nlet blocks2d := (bset2d.from_indexes blocks) in\nlet subboxes := boxes2d ∩ avail in\nlet supboxes := (avail \\ blocks2d) ∪ subboxes in\nboxint.generate avail subboxes supboxes sk\n\ndef list.pall {α : Type} (P : α → Prop) : list α → Prop\n| [] := true\n| (h::t) := P h ∧ list.pall t\ndef list.pall_iff {α : Type} {P : α → Prop} {l : list α}\n: list.pall P l ↔ (∀ a : α, a ∈ l → P a)\n:=\nbegin\n induction l with h t IH, {\n split,\n { intros H a Hin, exfalso,\n exact list.not_mem_nil a Hin, },\n { intro H, trivial, }\n }, {\n split, {\n intros H a Hin,\n cases H with Hh Ht,\n cases Hin,\n rw Hin, exact Hh,\n exact IH.mp Ht a Hin,\n }, {\n intro H, split,\n { apply H, simp, },\n { apply IH.mpr,\n intros a Hin,\n apply H, right, exact Hin,\n }\n }\n }\nend\nlemma list.pall_in {α : Type} (l : list α)\n: l.pall (λ a, a ∈ l) := list.pall_iff.mpr (λ a H, H)\n\nnamespace deadlocks\n\ntheorem boxint.generate_from_list_valid {avail : bset2d} {boxes blocks : list (ℕ × ℕ)} {sk : ℕ × ℕ}\n: (boxint.generate_from_list avail boxes blocks sk).valid avail\n:=\nbegin\n apply boxint.generate_valid, {\n exact bset2d.union_supset_right,\n }, {\n apply bset2d.union_subset,\n exact bset2d.sdiff_subset,\n exact bset2d.inter_subset_right,\n }\nend\n\ndef deadlock (avail : bset2d) (goal : boxes_only) (as : boxint) : Prop\n:= ∀ s1 s2 : sokostate, s1 ∈ as → s2 ∈ goal → s2.reachable avail s1 → false\n\nmeta def deadlock.to_html {avail : bset2d} {goal : boxes_only} {as : boxint}\n (H : deadlocks.deadlock avail goal as) : widget.html empty\n := sokowidget.build_table avail as.supboxes as.subboxes goal.boxes as.sk_comp\n\nlemma new_deadlocks {avail : bset2d} {goal : boxes_only} {new_dls : list boxint}\n: (∀ as : boxint, as ∈ new_dls →\n as.valid avail ∧ as.disjoint goal ∧\n (∀ as2 : boxint, as2 ∈ as.next_states avail →\n ∃ dl : boxint, as2.subset_g dl goal ∧ (dl ∈ new_dls ∨ deadlock avail goal dl))\n) → (∀ as : boxint, as ∈ new_dls → deadlock avail goal as)\n:=\nbegin\n intro H,\n intros as Has_in s1 sg Hs1 Hsg Hr,\n revert as,\n induction Hr with s1 d Hr IH,\n { \n assume as Has_in Hs,\n exact boxint.disjoint_correct as goal sg (H as Has_in).2.1 Hs Hsg,\n },\n {\n assume as Has_in Hs1,\n rcases H as Has_in with ⟨Hval, Hdisj, H⟩,\n cases boxint.next_of_real_move avail as Hval s1 d Hs1 with H1 H2,\n { exact IH as Has_in H1, }, -- no change in abstract state\n {\n rcases H2 with ⟨as2, Has2_next, Hin_as2⟩,\n rcases H as2 Has2_next with ⟨dl, Hdl_sup, Hdl⟩,\n let s2 := sokostate.move avail d s1,\n have : s2 ∈ dl\n := boxint.subset_g_correct Hdl_sup s2 sg Hin_as2 Hsg Hr,\n cases Hdl with Hdl_new Hdl_old,\n {\n clear H,\n exact IH dl Hdl_new this,\n },\n { apply Hdl_old s2 sg this Hsg Hr, }\n },\n }\nend\n\nlemma new_deadlock {avail : bset2d} {goal : boxes_only} {new_dl : boxint}\n: (\n new_dl.valid avail ∧ new_dl.disjoint goal ∧\n (∀ as2 : boxint, as2 ∈ new_dl.next_states avail →\n ∃ dl : boxint, as2.subset_g dl goal ∧ deadlock avail goal dl)\n) → deadlock avail goal new_dl\n:=\nbegin\n rintros ⟨Hval, Hdisj, H⟩,\n have : (∀ as, as ∈ [new_dl] → deadlock avail goal as), {\n apply new_deadlocks,\n refine list.pall_iff.mp ⟨_, trivial⟩,\n refine ⟨Hval, Hdisj, _⟩,\n intros as2 Has2,\n rcases H as2 Has2 with ⟨dl, Hsub, Hdl⟩,\n existsi dl,\n split, exact Hsub,\n right, exact Hdl,\n },\n exact (list.pall_iff.mpr this).1,\nend\n\n-- _ _ _ \n-- | |_ __ _ ___| |_(_) ___ ___ \n-- | __/ _` |/ __| __| |/ __/ __|\n-- | || (_| | (__| |_| | (__\\__ \\\n-- \\__\\__,_|\\___|\\__|_|\\___|___/\n-- \n\nmeta def and_placeholders : ℕ → pexpr\n| 0 := ``(trivial)\n| (n+1) := ``(and.intro %%(pexpr.mk_placeholder) %%(and_placeholders n))\n\nmeta def analyze_deadlock : tactic unit\n:=\ndo\n tactic.refine ``(and.intro boxint.generate_from_list_valid\n (and.intro dec_trivial (list.pall_iff.mp _))),\n `(list.pall %%_ %%steps_list) ← tactic.target,\n num_steps ← tactic.eval_expr nat `(@list.length boxint %%steps_list),\n tactic.refine (and_placeholders num_steps),\n return ()\n\nend deadlocks\n\nmeta def get_deadlock_of_step (t : expr) : tactic (expr × bool)\n:=\n(do\n `(deadlocks.deadlock %%e0 %%e1 %%e) ← tactic.whnf t reducible,\n return (e, ff)\n) <|> \n(do\n `(%%e ∈ %%e0) ← return t,\n return (e, tt)\n)\n\nmeta def tactic.deadlocked_step (e : expr) : tactic unit :=\ndo\n t ← tactic.infer_type e,\n (dl, is_rep) ← get_deadlock_of_step t,\n tactic.refine ``(exists.intro %%dl (and.intro dec_trivial _)),\n if is_rep then tactic.left >> tactic.exact e\n else tactic.try tactic.right >> tactic.exact e\n\nmeta def tactic.interactive.deadlocked_step (q : interactive.parse interactive.types.texpr) : tactic unit\n:= tactic.i_to_expr q >>= tactic.deadlocked_step\n", "meta": {"author": "mirefek", "repo": "sokoban.lean", "sha": "451c92308afb4d3f8e566594b9751286f93b899b", "save_path": "github-repos/lean/mirefek-sokoban.lean", "path": "github-repos/lean/mirefek-sokoban.lean/sokoban.lean-451c92308afb4d3f8e566594b9751286f93b899b/src/deadlocks.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4378234991142019, "lm_q2_score": 0.032100706601262484, "lm_q1q2_score": 0.0140544436882031}} {"text": "/-\nCopyright (c) 2019 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthor: Leonardo de Moura\n-/\nprelude\nimport Init.Control.Basic\nimport Init.Data.List.Basic\n\nnamespace List\nuniverse u v w u₁ u₂\n\n/-!\nRemark: we can define `mapM`, `mapM₂` and `forM` using `Applicative` instead of `Monad`.\nExample:\n```\ndef mapM {m : Type u → Type v} [Applicative m] {α : Type w} {β : Type u} (f : α → m β) : List α → m (List β)\n | [] => pure []\n | a::as => List.cons <$> (f a) <*> mapM as\n```\n\nHowever, we consider `f <$> a <*> b` an anti-idiom because the generated code\nmay produce unnecessary closure allocations.\nSuppose `m` is a `Monad`, and it uses the default implementation for `Applicative.seq`.\nThen, the compiler expands `f <$> a <*> b <*> c` into something equivalent to\n```\n(Functor.map f a >>= fun g_1 => Functor.map g_1 b) >>= fun g_2 => Functor.map g_2 c\n```\nIn an ideal world, the compiler may eliminate the temporary closures `g_1` and `g_2` after it inlines\n`Functor.map` and `Monad.bind`. However, this can easily fail. For example, suppose\n`Functor.map f a >>= fun g_1 => Functor.map g_1 b` expanded into a match-expression.\nThis is not unreasonable and can happen in many different ways, e.g., we are using a monad that\nmay throw exceptions. Then, the compiler has to decide whether it will create a join-point for\nthe continuation of the match or float it. If the compiler decides to float, then it will\nbe able to eliminate the closures, but it may not be feasible since floating match expressions\nmay produce exponential blowup in the code size.\n\nFinally, we rarely use `mapM` with something that is not a `Monad`.\n\nUsers that want to use `mapM` with `Applicative` should use `mapA` instead.\n-/\n\n@[inline]\ndef mapM {m : Type u → Type v} [Monad m] {α : Type w} {β : Type u} (f : α → m β) (as : List α) : m (List β) :=\n let rec @[specialize] loop\n | [], bs => pure bs.reverse\n | a :: as, bs => do loop as ((← f a)::bs)\n loop as []\n\n@[specialize]\ndef mapA {m : Type u → Type v} [Applicative m] {α : Type w} {β : Type u} (f : α → m β) : List α → m (List β)\n | [] => pure []\n | a::as => List.cons <$> f a <*> mapA f as\n\n@[specialize]\nprotected def forM {m : Type u → Type v} [Monad m] {α : Type w} (as : List α) (f : α → m PUnit) : m PUnit :=\n match as with\n | [] => pure ⟨⟩\n | a :: as => do f a; List.forM as f\n\n@[specialize]\ndef forA {m : Type u → Type v} [Applicative m] {α : Type w} (as : List α) (f : α → m PUnit) : m PUnit :=\n match as with\n | [] => pure ⟨⟩\n | a :: as => f a *> forA as f\n\n@[specialize]\ndef filterAuxM {m : Type → Type v} [Monad m] {α : Type} (f : α → m Bool) : List α → List α → m (List α)\n | [], acc => pure acc\n | h :: t, acc => do\n let b ← f h\n filterAuxM f t (cond b (h :: acc) acc)\n\n@[inline]\ndef filterM {m : Type → Type v} [Monad m] {α : Type} (f : α → m Bool) (as : List α) : m (List α) := do\n let as ← filterAuxM f as []\n pure as.reverse\n\n@[inline]\ndef filterRevM {m : Type → Type v} [Monad m] {α : Type} (f : α → m Bool) (as : List α) : m (List α) :=\n filterAuxM f as.reverse []\n\n@[inline]\ndef filterMapM {m : Type u → Type v} [Monad m] {α β : Type u} (f : α → m (Option β)) (as : List α) : m (List β) :=\n let rec @[specialize] loop\n | [], bs => pure bs\n | a :: as, bs => do\n match (← f a) with\n | none => loop as bs\n | some b => loop as (b::bs)\n loop as.reverse []\n\n@[specialize]\nprotected def foldlM {m : Type u → Type v} [Monad m] {s : Type u} {α : Type w} : (f : s → α → m s) → (init : s) → List α → m s\n | _, s, [] => pure s\n | f, s, a :: as => do\n let s' ← f s a\n List.foldlM f s' as\n\n@[inline]\ndef foldrM {m : Type u → Type v} [Monad m] {s : Type u} {α : Type w} (f : α → s → m s) (init : s) (l : List α) : m s :=\n l.reverse.foldlM (fun s a => f a s) init\n\n@[specialize]\ndef firstM {m : Type u → Type v} [Alternative m] {α : Type w} {β : Type u} (f : α → m β) : List α → m β\n | [] => failure\n | a::as => f a <|> firstM f as\n\n@[specialize]\ndef anyM {m : Type → Type u} [Monad m] {α : Type v} (f : α → m Bool) : List α → m Bool\n | [] => pure false\n | a::as => do\n match (← f a) with\n | true => pure true\n | false => anyM f as\n\n@[specialize]\ndef allM {m : Type → Type u} [Monad m] {α : Type v} (f : α → m Bool) : List α → m Bool\n | [] => pure true\n | a::as => do\n match (← f a) with\n | true => allM f as\n | false => pure false\n\n@[specialize]\ndef findM? {m : Type → Type u} [Monad m] {α : Type} (p : α → m Bool) : List α → m (Option α)\n | [] => pure none\n | a::as => do\n match (← p a) with\n | true => pure (some a)\n | false => findM? p as\n\n@[specialize]\ndef findSomeM? {m : Type u → Type v} [Monad m] {α : Type w} {β : Type u} (f : α → m (Option β)) : List α → m (Option β)\n | [] => pure none\n | a::as => do\n match (← f a) with\n | some b => pure (some b)\n | none => findSomeM? f as\n\n@[inline] protected def forIn {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (as : List α) (init : β) (f : α → β → m (ForInStep β)) : m β :=\n let rec @[specialize] loop\n | [], b => pure b\n | a::as, b => do\n match (← f a b) with\n | ForInStep.done b => pure b\n | ForInStep.yield b => loop as b\n loop as init\n\ninstance : ForIn m (List α) α where\n forIn := List.forIn\n\n@[simp] theorem forIn_nil [Monad m] (f : α → β → m (ForInStep β)) (b : β) : forIn [] b f = pure b :=\n rfl\n\n@[simp] theorem forIn_cons [Monad m] (f : α → β → m (ForInStep β)) (a : α) (as : List α) (b : β)\n : forIn (a::as) b f = f a b >>= fun | ForInStep.done b => pure b | ForInStep.yield b => forIn as b f :=\n rfl\n\n@[inline] protected def forIn' {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (as : List α) (init : β) (f : (a : α) → a ∈ as → β → m (ForInStep β)) : m β :=\n let rec @[specialize] loop : (as' : List α) → (b : β) → Exists (fun bs => bs ++ as' = as) → m β\n | [], b, _ => pure b\n | a::as', b, h => do\n have : a ∈ as := by\n have ⟨bs, h⟩ := h\n subst h\n exact mem_append_of_mem_right _ (Mem.head ..)\n match (← f a this b) with\n | ForInStep.done b => pure b\n | ForInStep.yield b =>\n have : Exists (fun bs => bs ++ as' = as) := have ⟨bs, h⟩ := h; ⟨bs ++ [a], by rw [← h, append_cons bs a as']⟩\n loop as' b this\n loop as init ⟨[], rfl⟩\n\ninstance : ForIn' m (List α) α inferInstance where\n forIn' := List.forIn'\n\n@[simp] theorem forIn'_eq_forIn {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (as : List α) (init : β) (f : α → β → m (ForInStep β)) : forIn' as init (fun a _ b => f a b) = forIn as init f := by\n simp [forIn', forIn, List.forIn, List.forIn']\n have : ∀ cs h, List.forIn'.loop cs (fun a _ b => f a b) as init h = List.forIn.loop f as init := by\n intro cs h\n induction as generalizing cs init with\n | nil => intros; rfl\n | cons a as ih => intros; simp [List.forIn.loop, List.forIn'.loop, ih]\n apply this\n\ninstance : ForM m (List α) α where\n forM := List.forM\n\n@[simp] theorem forM_nil [Monad m] (f : α → m PUnit) : forM [] f = pure ⟨⟩ :=\n rfl\n@[simp] theorem forM_cons [Monad m] (f : α → m PUnit) (a : α) (as : List α) : forM (a::as) f = f a >>= fun _ => forM as f :=\n rfl\n\ninstance : Functor List where\n map := List.map\n\nend List\n", "meta": {"author": "leanprover", "repo": "lean4", "sha": "742d053a97bdd109a41a921facd1cd6a55e89bc7", "save_path": "github-repos/lean/leanprover-lean4", "path": "github-repos/lean/leanprover-lean4/lean4-742d053a97bdd109a41a921facd1cd6a55e89bc7/src/Init/Data/List/Control.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.27825678173200435, "lm_q2_score": 0.050330629214348124, "lm_q1q2_score": 0.014004838907731307}} {"text": "-- quantifier instantiation\n\nimport .definitions3 .freevars .substitution .logic\n\nlemma prop.has_call_p.term.inv {c: calltrigger} {t: term}: c ∉ calls_p t :=\n assume t_has_call: prop.has_call_p c t,\n show «false», by cases t_has_call\n\nlemma prop.has_call_p.not.inv {c: calltrigger} {P: prop}: c ∈ calls_p P.not → c ∈ calls_n P :=\n assume not_has_call: c ∈ calls_p P.not,\n begin\n cases not_has_call,\n from a\n end\n\nlemma prop.has_call_p.and.inv {c: calltrigger} {P₁ P₂: prop}: c ∈ calls_p (P₁ ⋀ P₂) → c ∈ calls_p P₁ ∨ c ∈ calls_p P₂ :=\n assume and_has_call: c ∈ calls_p (P₁ ⋀ P₂),\n begin\n cases and_has_call,\n show c ∈ calls_p P₁ ∨ c ∈ calls_p P₂, from or.inl a,\n show c ∈ calls_p P₁ ∨ c ∈ calls_p P₂, from or.inr a\n end\n\nlemma prop.has_call_p.or.inv {c: calltrigger} {P₁ P₂: prop}: c ∈ calls_p (P₁ ⋁ P₂) → c ∈ calls_p P₁ ∨ c ∈ calls_p P₂ :=\n assume or_has_call: c ∈ calls_p (P₁ ⋁ P₂),\n begin\n cases or_has_call,\n show c ∈ calls_p P₁ ∨ c ∈ calls_p P₂, from or.inl a,\n show c ∈ calls_p P₁ ∨ c ∈ calls_p P₂, from or.inr a\n end\n\nlemma prop.has_call_p.pre₁.inv {c: calltrigger} {op: unop} {t: term}: c ∉ calls_p (prop.pre₁ op t) :=\n assume pre_has_call: c ∈ calls_p (prop.pre₁ op t),\n show «false», by cases pre_has_call\n\nlemma prop.has_call_p.pre₂.inv {c: calltrigger} {op: binop} {t₁ t₂: term}: c ∉ calls_p (prop.pre₂ op t₁ t₂) :=\n assume pre_has_call: c ∈ calls_p (prop.pre₂ op t₁ t₂),\n show «false», by cases pre_has_call\n\nlemma prop.has_call_p.pre.inv {c: calltrigger} {t₁ t₂: term}: c ∉ calls_p (prop.pre t₁ t₂) :=\n assume pre_has_call: c ∈ calls_p (prop.pre t₁ t₂),\n show «false», by cases pre_has_call\n\nlemma prop.has_call_p.post.inv {c: calltrigger} {t₁ t₂: term}: c ∉ calls_p (prop.post t₁ t₂) :=\n assume post_has_call: c ∈ calls_p (prop.post t₁ t₂),\n show «false», by cases post_has_call\n\nlemma prop.has_call_p.call.inv {c: calltrigger} {t: term}:\n c ∈ calls_p (prop.call t) → (c = calltrigger.mk t) :=\n assume call_has_call: c ∈ calls_p (prop.call t),\n show c = calltrigger.mk t, by { cases call_has_call, refl }\n\nlemma prop.has_call_p.forallc.inv {c: calltrigger} {x: var} {t: term} {P: prop}:\n c ∉ calls_p (prop.forallc x P) :=\n assume forall_has_call: c ∈ calls_p (prop.forallc x P),\n begin\n cases forall_has_call\n end\n\nlemma prop.has_call_p.exis.inv {c: calltrigger} {x: var} {P: prop}: c ∉ calls_p (prop.exis x P) :=\n assume exis_has_call: c ∈ calls_p (prop.exis x P),\n begin\n cases exis_has_call\n end\n\nlemma prop.has_call_n.term.inv {c: calltrigger} {t: term}: c ∉ calls_n t :=\n assume t_has_call_n: prop.has_call_n c t,\n show «false», by cases t_has_call_n\n\nlemma prop.has_call_n.not.inv {c: calltrigger} {P: prop}: c ∈ calls_n P.not → c ∈ calls_p P :=\n assume not_has_call_n: c ∈ calls_n P.not,\n begin\n cases not_has_call_n,\n from a\n end\n\nlemma prop.has_call_n.and.inv {c: calltrigger} {P₁ P₂: prop}: c ∈ calls_n (P₁ ⋀ P₂) → c ∈ calls_n P₁ ∨ c ∈ calls_n P₂ :=\n assume and_has_call_n: c ∈ calls_n (P₁ ⋀ P₂),\n begin\n cases and_has_call_n,\n show c ∈ calls_n P₁ ∨ c ∈ calls_n P₂, from or.inl a,\n show c ∈ calls_n P₁ ∨ c ∈ calls_n P₂, from or.inr a\n end\n\nlemma prop.has_call_n.or.inv {c: calltrigger} {P₁ P₂: prop}: c ∈ calls_n (P₁ ⋁ P₂) → c ∈ calls_n P₁ ∨ c ∈ calls_n P₂ :=\n assume or_has_call_n: c ∈ calls_n (P₁ ⋁ P₂),\n begin\n cases or_has_call_n,\n show c ∈ calls_n P₁ ∨ c ∈ calls_n P₂, from or.inl a,\n show c ∈ calls_n P₁ ∨ c ∈ calls_n P₂, from or.inr a\n end\n\nlemma prop.has_call_n.pre₁.inv {c: calltrigger} {op: unop} {t: term}: c ∉ calls_n (prop.pre₁ op t) :=\n assume pre_has_call_n: c ∈ calls_n (prop.pre₁ op t),\n show «false», by cases pre_has_call_n\n\nlemma prop.has_call_n.pre₂.inv {c: calltrigger} {op: binop} {t₁ t₂: term}: c ∉ calls_n (prop.pre₂ op t₁ t₂) :=\n assume pre_has_call_n: c ∈ calls_n (prop.pre₂ op t₁ t₂),\n show «false», by cases pre_has_call_n\n\nlemma prop.has_call_n.pre.inv {c: calltrigger} {t₁ t₂: term}: c ∉ calls_n (prop.pre t₁ t₂) :=\n assume pre_has_call_n: c ∈ calls_n (prop.pre t₁ t₂),\n show «false», by cases pre_has_call_n\n\nlemma prop.has_call_n.post.inv {c: calltrigger} {t₁ t₂: term}: c ∉ calls_n (prop.post t₁ t₂) :=\n assume post_has_call_n: c ∈ calls_n (prop.post t₁ t₂),\n show «false», by cases post_has_call_n\n\nlemma prop.has_call_n.call.inv {c: calltrigger} {t₁ t₂: term}: c ∉ calls_n (prop.call t₁ t₂) :=\n assume call_has_call_n: c ∈ calls_n (prop.call t₁ t₂),\n show «false», by cases call_has_call_n\n\nlemma prop.has_call_n.forallc.inv {c: calltrigger} {x: var} {t: term} {P: prop}:\n c ∉ calls_n (prop.forallc x P) :=\n assume forall_has_call_n: c ∈ calls_n (prop.forallc x P),\n begin\n cases forall_has_call_n\n end\n\nlemma prop.has_call_n.exis.inv {c: calltrigger} {x: var} {P: prop}: c ∉ calls_n (prop.exis x P) :=\n assume exis_has_call_n: c ∈ calls_n (prop.exis x P),\n begin\n cases exis_has_call_n\n end\n\nlemma prop.has_quantifier_p.term.inv {q: callquantifier} {t: term}: q ∉ quantifiers_p t :=\n assume t_has_quantifier_p: prop.has_quantifier_p q t,\n show «false», by cases t_has_quantifier_p\n\nlemma prop.has_quantifier_p.not.inv {q: callquantifier} {P: prop}: q ∈ quantifiers_p P.not → q ∈ quantifiers_n P :=\n assume not_has_quantifier_p: q ∈ quantifiers_p P.not,\n begin\n cases not_has_quantifier_p with a,\n from a\n end\n\nlemma prop.has_quantifier_p.and.inv {q: callquantifier} {P₁ P₂: prop}:\n q ∈ quantifiers_p (P₁ ⋀ P₂) → q ∈ quantifiers_p P₁ ∨ q ∈ quantifiers_p P₂ :=\n assume and_has_quantifier_p: q ∈ quantifiers_p (P₁ ⋀ P₂),\n begin\n cases and_has_quantifier_p,\n show q ∈ quantifiers_p P₁ ∨ q ∈ quantifiers_p P₂, from or.inl a,\n show q ∈ quantifiers_p P₁ ∨ q ∈ quantifiers_p P₂, from or.inr a\n end\n\nlemma prop.has_quantifier_p.or.inv {q: callquantifier} {P₁ P₂: prop}:\n q ∈ quantifiers_p (P₁ ⋁ P₂) → q ∈ quantifiers_p P₁ ∨ q ∈ quantifiers_p P₂ :=\n assume or_has_quantifier_p: q ∈ quantifiers_p (P₁ ⋁ P₂),\n begin\n cases or_has_quantifier_p,\n show q ∈ quantifiers_p P₁ ∨ q ∈ quantifiers_p P₂, from or.inl a,\n show q ∈ quantifiers_p P₁ ∨ q ∈ quantifiers_p P₂, from or.inr a\n end\n\nlemma prop.has_quantifier_p.pre₁.inv {q: callquantifier} {op: unop} {t: term}: q ∉ quantifiers_p (prop.pre₁ op t) :=\n assume pre_has_quantifier_p: q ∈ quantifiers_p (prop.pre₁ op t),\n show «false», by cases pre_has_quantifier_p\n\nlemma prop.has_quantifier_p.pre₂.inv {q: callquantifier} {op: binop} {t₁ t₂: term}: q ∉ quantifiers_p (prop.pre₂ op t₁ t₂) :=\n assume pre_has_quantifier_p: q ∈ quantifiers_p (prop.pre₂ op t₁ t₂),\n show «false», by cases pre_has_quantifier_p\n\nlemma prop.has_quantifier_p.pre.inv {q: callquantifier} {t₁ t₂: term}: q ∉ quantifiers_p (prop.pre t₁ t₂) :=\n assume pre_has_quantifier_p: q ∈ quantifiers_p (prop.pre t₁ t₂),\n show «false», by cases pre_has_quantifier_p\n\nlemma prop.has_quantifier_p.post.inv {q: callquantifier} {t₁ t₂: term}: q ∉ quantifiers_p (prop.post t₁ t₂) :=\n assume post_has_quantifier_p: q ∈ quantifiers_p (prop.post t₁ t₂),\n show «false», by cases post_has_quantifier_p\n\nlemma prop.has_quantifier_p.call.inv {q: callquantifier} {t₁ t₂: term}: q ∉ quantifiers_p (prop.call t₁ t₂) :=\n assume call_has_quantifier_p: q ∈ quantifiers_p (prop.call t₁ t₂),\n show «false», by cases call_has_quantifier_p\n\nlemma prop.has_quantifier_p.forallc.inv {q: callquantifier} {x: var} {P: prop}:\n q ∈ quantifiers_p (prop.forallc x P) → (q = ⟨x, P⟩) :=\n assume forall_has_quantifier_p: q ∈ quantifiers_p (prop.forallc x P),\n begin\n cases forall_has_quantifier_p,\n from rfl\n end\n\nlemma prop.has_quantifier_n.term.inv {q: callquantifier} {t: term}: q ∉ quantifiers_n t :=\n assume t_has_quantifier_n: prop.has_quantifier_n q t,\n show «false», by cases t_has_quantifier_n\n\nlemma prop.has_quantifier_n.not.inv {q: callquantifier} {P: prop}: q ∈ quantifiers_n P.not → q ∈ quantifiers_p P :=\n assume not_has_quantifier_n: q ∈ quantifiers_n P.not,\n begin\n cases not_has_quantifier_n,\n from a\n end\n\nlemma prop.has_quantifier_n.and.inv {q: callquantifier} {P₁ P₂: prop}:\n q ∈ quantifiers_n (P₁ ⋀ P₂) → q ∈ quantifiers_n P₁ ∨ q ∈ quantifiers_n P₂ :=\n assume and_has_quantifier_n: q ∈ quantifiers_n (P₁ ⋀ P₂),\n begin\n cases and_has_quantifier_n,\n show q ∈ quantifiers_n P₁ ∨ q ∈ quantifiers_n P₂, from or.inl a,\n show q ∈ quantifiers_n P₁ ∨ q ∈ quantifiers_n P₂, from or.inr a\n end\n\nlemma prop.has_quantifier_n.or.inv {q: callquantifier} {P₁ P₂: prop}:\n q ∈ quantifiers_n (P₁ ⋁ P₂) → q ∈ quantifiers_n P₁ ∨ q ∈ quantifiers_n P₂ :=\n assume or_has_quantifier_n: q ∈ quantifiers_n (P₁ ⋁ P₂),\n begin\n cases or_has_quantifier_n,\n show q ∈ quantifiers_n P₁ ∨ q ∈ quantifiers_n P₂, from or.inl a,\n show q ∈ quantifiers_n P₁ ∨ q ∈ quantifiers_n P₂, from or.inr a\n end\n\nlemma prop.has_quantifier_n.pre₁.inv {q: callquantifier} {op: unop} {t: term}: q ∉ quantifiers_n (prop.pre₁ op t) :=\n assume pre_has_quantifier_n: q ∈ quantifiers_n (prop.pre₁ op t),\n show «false», by cases pre_has_quantifier_n\n\nlemma prop.has_quantifier_n.pre₂.inv {q: callquantifier} {op: binop} {t₁ t₂: term}: q ∉ quantifiers_n (prop.pre₂ op t₁ t₂) :=\n assume pre_has_quantifier_n: q ∈ quantifiers_n (prop.pre₂ op t₁ t₂),\n show «false», by cases pre_has_quantifier_n\n\nlemma prop.has_quantifier_n.pre.inv {q: callquantifier} {t₁ t₂: term}: q ∉ quantifiers_n (prop.pre t₁ t₂) :=\n assume pre_has_quantifier_n: q ∈ quantifiers_n (prop.pre t₁ t₂),\n show «false», by cases pre_has_quantifier_n\n\nlemma prop.has_quantifier_n.post.inv {q: callquantifier} {t₁ t₂: term}: q ∉ quantifiers_n (prop.post t₁ t₂) :=\n assume post_has_quantifier_n: q ∈ quantifiers_n (prop.post t₁ t₂),\n show «false», by cases post_has_quantifier_n\n\nlemma prop.has_quantifier_n.call.inv {q: callquantifier} {t₁ t₂: term}: q ∉ quantifiers_n (prop.call t₁ t₂) :=\n assume call_has_quantifier_n: q ∈ quantifiers_n (prop.call t₁ t₂),\n show «false», by cases call_has_quantifier_n\n\nlemma prop.has_quantifier_n.forallc.inv {q: callquantifier} {x: var} {P: prop}:\n q ∉ quantifiers_n (prop.forallc x P) :=\n assume forall_has_quantifier_n: q ∈ quantifiers_n (prop.forallc x P),\n begin\n cases forall_has_quantifier_n\n end\n\nlemma prop.has_call_p_subst.term.inv {c: calltrigger} {t: term} {σ: env}:\n c ∉ calls_p_subst σ t :=\n assume : c ∈ calls_p_subst σ t,\n have c ∈ (calltrigger.subst σ) '' calls_p t, from this,\n @set.mem_image_elim_on calltrigger calltrigger (calltrigger.subst σ) (calls_p t)\n (λa, «false») c this (\n assume c': calltrigger,\n assume : c' ∈ calls_p t,\n show «false», from prop.has_call_p.term.inv this\n )\n\nlemma prop.has_call_p_subst.and₁ {c: calltrigger} {P₁ P₂: prop} {σ: env}:\n c ∈ calls_p_subst σ P₁ → c ∈ calls_p_subst σ (P₁ ⋀ P₂) :=\n assume : c ∈ calls_p_subst σ P₁,\n have c ∈ (calltrigger.subst σ) '' calls_p P₁, from this,\n @set.mem_image_elim_on calltrigger calltrigger (calltrigger.subst σ) (calls_p P₁)\n (λa, a ∈ calls_p_subst σ (P₁ ⋀ P₂)) c this (\n assume c': calltrigger,\n assume : c' ∈ calls_p P₁,\n have c' ∈ calls_p (P₁ ⋀ P₂), from prop.has_call_p.and₁ this,\n show calltrigger.subst σ c' ∈ calls_p_subst σ (P₁ ⋀ P₂), from set.mem_image this rfl\n )\n\nlemma prop.has_call_p_subst.and₂ {c: calltrigger} {P₁ P₂: prop} {σ: env}:\n c ∈ calls_p_subst σ P₂ → c ∈ calls_p_subst σ (P₁ ⋀ P₂) :=\n assume : c ∈ calls_p_subst σ P₂,\n have c ∈ (calltrigger.subst σ) '' calls_p P₂, from this,\n @set.mem_image_elim_on calltrigger calltrigger (calltrigger.subst σ) (calls_p P₂)\n (λa, a ∈ calls_p_subst σ (P₁ ⋀ P₂)) c this (\n assume c': calltrigger,\n assume : c' ∈ calls_p P₂,\n have c' ∈ calls_p (P₁ ⋀ P₂), from prop.has_call_p.and₂ this,\n show calltrigger.subst σ c' ∈ calls_p_subst σ (P₁ ⋀ P₂), from set.mem_image this rfl\n )\n\nlemma prop.has_call_p_subst.not {c: calltrigger} {P: prop} {σ: env}:\n c ∈ calls_p_subst σ P → c ∈ calls_n_subst σ P.not :=\n assume : c ∈ calls_p_subst σ P,\n have c ∈ (calltrigger.subst σ) '' calls_p P, from this,\n @set.mem_image_elim_on calltrigger calltrigger (calltrigger.subst σ) (calls_p P)\n (λa, a ∈ calls_n_subst σ P.not) c this (\n assume c': calltrigger,\n assume : c' ∈ calls_p P,\n have c' ∈ calls_n P.not, from prop.has_call_n.not this,\n show calltrigger.subst σ c' ∈ calls_n_subst σ P.not, from set.mem_image this rfl\n )\n\nlemma prop.has_call_n_subst.term.inv {c: calltrigger} {t: term} {σ: env}:\n c ∉ calls_n_subst σ t :=\n assume : c ∈ calls_n_subst σ t,\n have c ∈ (calltrigger.subst σ) '' calls_n t, from this,\n @set.mem_image_elim_on calltrigger calltrigger (calltrigger.subst σ) (calls_n t)\n (λa, «false») c this (\n assume c': calltrigger,\n assume : c' ∈ calls_n t,\n show «false», from prop.has_call_n.term.inv this\n )\n\nlemma prop.has_call_n_subst.not {c: calltrigger} {P: prop} {σ: env}:\n c ∈ calls_n_subst σ P → c ∈ calls_p_subst σ P.not :=\n assume : c ∈ calls_n_subst σ P,\n have c ∈ (calltrigger.subst σ) '' calls_n P, from this,\n @set.mem_image_elim_on calltrigger calltrigger (calltrigger.subst σ) (calls_n P)\n (λa, a ∈ calls_p_subst σ P.not) c this (\n assume c': calltrigger,\n assume : c' ∈ calls_n P,\n have c' ∈ calls_p P.not, from prop.has_call_p.not this,\n show calltrigger.subst σ c' ∈ calls_p_subst σ P.not, from set.mem_image this rfl\n )\n\nlemma prop.has_call_p_subst.not.inv {c: calltrigger} {P: prop} {σ: env}:\n c ∈ calls_p_subst σ P.not → c ∈ calls_n_subst σ P :=\n assume : c ∈ calls_p_subst σ P.not,\n have c ∈ (calltrigger.subst σ) '' calls_p P.not, from this,\n @set.mem_image_elim_on calltrigger calltrigger (calltrigger.subst σ) (calls_p P.not)\n (λa, a ∈ calls_n_subst σ P) c this (\n assume c': calltrigger,\n assume : c' ∈ calls_p P.not,\n have c' ∈ calls_n P, from prop.has_call_p.not.inv this,\n show calltrigger.subst σ c' ∈ calls_n_subst σ P, from set.mem_image this rfl\n )\n\nlemma prop.has_call_n_subst.not.inv {c: calltrigger} {P: prop} {σ: env}:\n c ∈ calls_n_subst σ P.not → c ∈ calls_p_subst σ P :=\n assume : c ∈ calls_n_subst σ P.not,\n have c ∈ (calltrigger.subst σ) '' calls_n P.not, from this,\n @set.mem_image_elim_on calltrigger calltrigger (calltrigger.subst σ) (calls_n P.not)\n (λa, a ∈ calls_p_subst σ P) c this (\n assume c': calltrigger,\n assume : c' ∈ calls_n P.not,\n have c' ∈ calls_p P, from prop.has_call_n.not.inv this,\n show calltrigger.subst σ c' ∈ calls_p_subst σ P, from set.mem_image this rfl\n )\n\nlemma prop.has_call_p_subst.and.inv {c: calltrigger} {P₁ P₂: prop} {σ: env}:\n c ∈ calls_p_subst σ (P₁ ⋀ P₂) → c ∈ calls_p_subst σ P₁ ∨ c ∈ calls_p_subst σ P₂ :=\n assume : c ∈ calls_p_subst σ (P₁ ⋀ P₂),\n have c ∈ (calltrigger.subst σ) '' calls_p (P₁ ⋀ P₂), from this,\n @set.mem_image_elim_on calltrigger calltrigger (calltrigger.subst σ) (calls_p (P₁ ⋀ P₂))\n (λa, a ∈ calls_p_subst σ P₁ ∨ a ∈ calls_p_subst σ P₂) c this (\n assume c': calltrigger,\n assume : c' ∈ calls_p (P₁ ⋀ P₂),\n or.elim (prop.has_call_p.and.inv this) (\n assume : c' ∈ calls_p P₁,\n have calltrigger.subst σ c' ∈ calls_p_subst σ P₁, from set.mem_image this rfl,\n show calltrigger.subst σ c' ∈ calls_p_subst σ P₁\n ∨ calltrigger.subst σ c' ∈ calls_p_subst σ P₂, from or.inl this\n ) (\n assume : c' ∈ calls_p P₂,\n have calltrigger.subst σ c' ∈ calls_p_subst σ P₂, from set.mem_image this rfl,\n show calltrigger.subst σ c' ∈ calls_p_subst σ P₁\n ∨ calltrigger.subst σ c' ∈ calls_p_subst σ P₂, from or.inr this\n )\n )\n\nlemma prop.has_call_p_subst.or.inv {c: calltrigger} {P₁ P₂: prop} {σ: env}:\n c ∈ calls_p_subst σ (P₁ ⋁ P₂) → c ∈ calls_p_subst σ P₁ ∨ c ∈ calls_p_subst σ P₂ :=\n assume : c ∈ calls_p_subst σ (P₁ ⋁ P₂),\n have c ∈ (calltrigger.subst σ) '' calls_p (P₁ ⋁ P₂), from this,\n @set.mem_image_elim_on calltrigger calltrigger (calltrigger.subst σ) (calls_p (P₁ ⋁ P₂))\n (λa, a ∈ calls_p_subst σ P₁ ∨ a ∈ calls_p_subst σ P₂) c this (\n assume c': calltrigger,\n assume : c' ∈ calls_p (P₁ ⋁ P₂),\n or.elim (prop.has_call_p.or.inv this) (\n assume : c' ∈ calls_p P₁,\n have calltrigger.subst σ c' ∈ calls_p_subst σ P₁, from set.mem_image this rfl,\n show calltrigger.subst σ c' ∈ calls_p_subst σ P₁\n ∨ calltrigger.subst σ c' ∈ calls_p_subst σ P₂, from or.inl this\n ) (\n assume : c' ∈ calls_p P₂,\n have calltrigger.subst σ c' ∈ calls_p_subst σ P₂, from set.mem_image this rfl,\n show calltrigger.subst σ c' ∈ calls_p_subst σ P₁\n ∨ calltrigger.subst σ c' ∈ calls_p_subst σ P₂, from or.inr this\n )\n )\n\nlemma prop.has_call_n_subst.and.inv {c: calltrigger} {P₁ P₂: prop} {σ: env}:\n c ∈ calls_n_subst σ (P₁ ⋀ P₂) → c ∈ calls_n_subst σ P₁ ∨ c ∈ calls_n_subst σ P₂ :=\n assume : c ∈ calls_n_subst σ (P₁ ⋀ P₂),\n have c ∈ (calltrigger.subst σ) '' calls_n (P₁ ⋀ P₂), from this,\n @set.mem_image_elim_on calltrigger calltrigger (calltrigger.subst σ) (calls_n (P₁ ⋀ P₂))\n (λa, a ∈ calls_n_subst σ P₁ ∨ a ∈ calls_n_subst σ P₂) c this (\n assume c': calltrigger,\n assume : c' ∈ calls_n (P₁ ⋀ P₂),\n or.elim (prop.has_call_n.and.inv this) (\n assume : c' ∈ calls_n P₁,\n have calltrigger.subst σ c' ∈ calls_n_subst σ P₁, from set.mem_image this rfl,\n show calltrigger.subst σ c' ∈ calls_n_subst σ P₁\n ∨ calltrigger.subst σ c' ∈ calls_n_subst σ P₂, from or.inl this\n ) (\n assume : c' ∈ calls_n P₂,\n have calltrigger.subst σ c' ∈ calls_n_subst σ P₂, from set.mem_image this rfl,\n show calltrigger.subst σ c' ∈ calls_n_subst σ P₁\n ∨ calltrigger.subst σ c' ∈ calls_n_subst σ P₂, from or.inr this\n )\n )\n\nlemma prop.has_call_n_subst.or.inv {c: calltrigger} {P₁ P₂: prop} {σ: env}:\n c ∈ calls_n_subst σ (P₁ ⋁ P₂) → c ∈ calls_n_subst σ P₁ ∨ c ∈ calls_n_subst σ P₂ :=\n assume : c ∈ calls_n_subst σ (P₁ ⋁ P₂),\n have c ∈ (calltrigger.subst σ) '' calls_n (P₁ ⋁ P₂), from this,\n @set.mem_image_elim_on calltrigger calltrigger (calltrigger.subst σ) (calls_n (P₁ ⋁ P₂))\n (λa, a ∈ calls_n_subst σ P₁ ∨ a ∈ calls_n_subst σ P₂) c this (\n assume c': calltrigger,\n assume : c' ∈ calls_n (P₁ ⋁ P₂),\n or.elim (prop.has_call_n.or.inv this) (\n assume : c' ∈ calls_n P₁,\n have calltrigger.subst σ c' ∈ calls_n_subst σ P₁, from set.mem_image this rfl,\n show calltrigger.subst σ c' ∈ calls_n_subst σ P₁\n ∨ calltrigger.subst σ c' ∈ calls_n_subst σ P₂, from or.inl this\n ) (\n assume : c' ∈ calls_n P₂,\n have calltrigger.subst σ c' ∈ calls_n_subst σ P₂, from set.mem_image this rfl,\n show calltrigger.subst σ c' ∈ calls_n_subst σ P₁\n ∨ calltrigger.subst σ c' ∈ calls_n_subst σ P₂, from or.inr this\n )\n )\n\nlemma no_instantiations.term {t: term}: no_instantiations t :=\n have h1: calls_p t = ∅, from set.eq_empty_of_forall_not_mem (\n assume c: calltrigger,\n assume : c ∈ calls_p t,\n show «false», from prop.has_call_p.term.inv this\n ),\n have h2: calls_n t = ∅, from set.eq_empty_of_forall_not_mem (\n assume c: calltrigger,\n assume : c ∈ calls_n t,\n show «false», from prop.has_call_n.term.inv this\n ),\n have h3: quantifiers_p t = ∅, from set.eq_empty_of_forall_not_mem (\n assume q: callquantifier,\n assume : q ∈ quantifiers_p t,\n show «false», from prop.has_quantifier_p.term.inv this\n ),\n have h4: quantifiers_n t = ∅, from set.eq_empty_of_forall_not_mem (\n assume q: callquantifier,\n assume : q ∈ quantifiers_n t,\n show «false», from prop.has_quantifier_n.term.inv this\n ),\n ⟨h1, ⟨h2, ⟨h3, h4⟩⟩⟩\n\nlemma no_instantiations.not {P: prop}: no_instantiations P → no_instantiations P.not :=\n assume ⟨no_calls_p_in_P, ⟨no_calls_n_in_P, ⟨no_quantifiers_p_in_P, no_quantifiers_n_in_P⟩⟩⟩,\n have h1: calls_p P.not = ∅, from set.eq_empty_of_forall_not_mem (\n assume c: calltrigger,\n assume : c ∈ calls_p P.not,\n have c_in_calls_p_P: c ∈ calls_n P, from prop.has_call_p.not.inv this,\n have c_not_in_calls_p_P: c ∉ calls_n P, from set.forall_not_mem_of_eq_empty no_calls_n_in_P c,\n show «false», from c_not_in_calls_p_P c_in_calls_p_P\n ),\n have h2: calls_n P.not = ∅, from set.eq_empty_of_forall_not_mem (\n assume c: calltrigger,\n assume : c ∈ calls_n P.not,\n have c_in_calls_p_P: c ∈ calls_p P, from prop.has_call_n.not.inv this,\n have c_not_in_calls_p_P: c ∉ calls_p P, from set.forall_not_mem_of_eq_empty no_calls_p_in_P c,\n show «false», from c_not_in_calls_p_P c_in_calls_p_P\n ),\n have h3: quantifiers_p P.not = ∅, from set.eq_empty_of_forall_not_mem (\n assume q: callquantifier,\n assume : q ∈ quantifiers_p P.not,\n have c_in_quantifiers_p_P: q ∈ quantifiers_n P, from prop.has_quantifier_p.not.inv this,\n have c_not_in_quantifiers_p_P: q ∉ quantifiers_n P, from set.forall_not_mem_of_eq_empty no_quantifiers_n_in_P q,\n show «false», from c_not_in_quantifiers_p_P c_in_quantifiers_p_P\n ),\n have h4: quantifiers_n P.not = ∅, from set.eq_empty_of_forall_not_mem (\n assume q: callquantifier,\n assume : q ∈ quantifiers_n P.not,\n have c_in_quantifiers_p_P: q ∈ quantifiers_p P, from prop.has_quantifier_n.not.inv this,\n have c_not_in_quantifiers_p_P: q ∉ quantifiers_p P, from set.forall_not_mem_of_eq_empty no_quantifiers_p_in_P q,\n show «false», from c_not_in_quantifiers_p_P c_in_quantifiers_p_P\n ),\n ⟨h1, ⟨h2, ⟨h3, h4⟩⟩⟩\n\nlemma no_instantiations.and {P₁ P₂: prop}:\n no_instantiations P₁ → no_instantiations P₂ → no_instantiations (prop.and P₁ P₂) :=\n assume ⟨no_calls_p_in_P₁, ⟨no_calls_n_in_P₁, ⟨no_quantifiers_p_in_P₁, no_quantifiers_n_in_P₁⟩⟩⟩,\n assume ⟨no_calls_p_in_P₂, ⟨no_calls_n_in_P₂, ⟨no_quantifiers_p_in_P₂, no_quantifiers_n_in_P₂⟩⟩⟩,\n have h1: calls_p (P₁ ⋀ P₂) = ∅, from set.eq_empty_of_forall_not_mem (\n assume c: calltrigger,\n assume : c ∈ calls_p (P₁ ⋀ P₂),\n have c ∈ calls_p P₁ ∨ c ∈ calls_p P₂, from prop.has_call_p.and.inv this,\n or.elim this (\n assume c_in_calls_p_P₁: c ∈ calls_p P₁,\n have c_not_in_calls_p_P₁: c ∉ calls_p P₁, from set.forall_not_mem_of_eq_empty no_calls_p_in_P₁ c,\n show «false», from c_not_in_calls_p_P₁ c_in_calls_p_P₁\n ) (\n assume c_in_calls_p_P₂: c ∈ calls_p P₂,\n have c_not_in_calls_p_P₂: c ∉ calls_p P₂, from set.forall_not_mem_of_eq_empty no_calls_p_in_P₂ c,\n show «false», from c_not_in_calls_p_P₂ c_in_calls_p_P₂\n )\n ),\n have h2: calls_n (P₁ ⋀ P₂) = ∅, from set.eq_empty_of_forall_not_mem (\n assume c: calltrigger,\n assume : c ∈ calls_n (P₁ ⋀ P₂),\n have c ∈ calls_n P₁ ∨ c ∈ calls_n P₂, from prop.has_call_n.and.inv this,\n or.elim this (\n assume c_in_calls_p_P₁: c ∈ calls_n P₁,\n have c_not_in_calls_p_P₁: c ∉ calls_n P₁, from set.forall_not_mem_of_eq_empty no_calls_n_in_P₁ c,\n show «false», from c_not_in_calls_p_P₁ c_in_calls_p_P₁\n ) (\n assume c_in_calls_p_P₂: c ∈ calls_n P₂,\n have c_not_in_calls_p_P₂: c ∉ calls_n P₂, from set.forall_not_mem_of_eq_empty no_calls_n_in_P₂ c,\n show «false», from c_not_in_calls_p_P₂ c_in_calls_p_P₂\n )\n ),\n have h3: quantifiers_p (P₁ ⋀ P₂) = ∅, from set.eq_empty_of_forall_not_mem (\n assume q: callquantifier,\n assume : q ∈ quantifiers_p (P₁ ⋀ P₂),\n have q ∈ quantifiers_p P₁ ∨ q ∈ quantifiers_p P₂, from prop.has_quantifier_p.and.inv this,\n or.elim this (\n assume q_in_quantifiers_p_P₁: q ∈ quantifiers_p P₁,\n have q_not_in_quantifiers_p_P₁: q ∉ quantifiers_p P₁, from set.forall_not_mem_of_eq_empty no_quantifiers_p_in_P₁ q,\n show «false», from q_not_in_quantifiers_p_P₁ q_in_quantifiers_p_P₁\n ) (\n assume q_in_quantifiers_p_P₂: q ∈ quantifiers_p P₂,\n have q_not_in_quantifiers_p_P₂: q ∉ quantifiers_p P₂, from set.forall_not_mem_of_eq_empty no_quantifiers_p_in_P₂ q,\n show «false», from q_not_in_quantifiers_p_P₂ q_in_quantifiers_p_P₂\n )\n ),\n have h4: quantifiers_n (P₁ ⋀ P₂) = ∅, from set.eq_empty_of_forall_not_mem (\n assume q: callquantifier,\n assume : q ∈ quantifiers_n (P₁ ⋀ P₂),\n have q ∈ quantifiers_n P₁ ∨ q ∈ quantifiers_n P₂, from prop.has_quantifier_n.and.inv this,\n or.elim this (\n assume q_in_quantifiers_p_P₁: q ∈ quantifiers_n P₁,\n have q_not_in_quantifiers_p_P₁: q ∉ quantifiers_n P₁, from set.forall_not_mem_of_eq_empty no_quantifiers_n_in_P₁ q,\n show «false», from q_not_in_quantifiers_p_P₁ q_in_quantifiers_p_P₁\n ) (\n assume q_in_quantifiers_p_P₂: q ∈ quantifiers_n P₂,\n have q_not_in_quantifiers_p_P₂: q ∉ quantifiers_n P₂, from set.forall_not_mem_of_eq_empty no_quantifiers_n_in_P₂ q,\n show «false», from q_not_in_quantifiers_p_P₂ q_in_quantifiers_p_P₂\n )\n ),\n ⟨h1, ⟨h2, ⟨h3, h4⟩⟩⟩\n\nlemma no_instantiations.or {P₁ P₂: prop}:\n no_instantiations P₁ → no_instantiations P₂ → no_instantiations (prop.or P₁ P₂) :=\n assume ⟨no_calls_p_in_P₁, ⟨no_calls_n_in_P₁, ⟨no_quantifiers_p_in_P₁, no_quantifiers_n_in_P₁⟩⟩⟩,\n assume ⟨no_calls_p_in_P₂, ⟨no_calls_n_in_P₂, ⟨no_quantifiers_p_in_P₂, no_quantifiers_n_in_P₂⟩⟩⟩,\n have h1: calls_p (P₁ ⋁ P₂) = ∅, from set.eq_empty_of_forall_not_mem (\n assume c: calltrigger,\n assume : c ∈ calls_p (P₁ ⋁ P₂),\n have c ∈ calls_p P₁ ∨ c ∈ calls_p P₂, from prop.has_call_p.or.inv this,\n or.elim this (\n assume c_in_calls_p_P₁: c ∈ calls_p P₁,\n have c_not_in_calls_p_P₁: c ∉ calls_p P₁, from set.forall_not_mem_of_eq_empty no_calls_p_in_P₁ c,\n show «false», from c_not_in_calls_p_P₁ c_in_calls_p_P₁\n ) (\n assume c_in_calls_p_P₂: c ∈ calls_p P₂,\n have c_not_in_calls_p_P₂: c ∉ calls_p P₂, from set.forall_not_mem_of_eq_empty no_calls_p_in_P₂ c,\n show «false», from c_not_in_calls_p_P₂ c_in_calls_p_P₂\n )\n ),\n have h2: calls_n (P₁ ⋁ P₂) = ∅, from set.eq_empty_of_forall_not_mem (\n assume c: calltrigger,\n assume : c ∈ calls_n (P₁ ⋁ P₂),\n have c ∈ calls_n P₁ ∨ c ∈ calls_n P₂, from prop.has_call_n.or.inv this,\n or.elim this (\n assume c_in_calls_p_P₁: c ∈ calls_n P₁,\n have c_not_in_calls_p_P₁: c ∉ calls_n P₁, from set.forall_not_mem_of_eq_empty no_calls_n_in_P₁ c,\n show «false», from c_not_in_calls_p_P₁ c_in_calls_p_P₁\n ) (\n assume c_in_calls_p_P₂: c ∈ calls_n P₂,\n have c_not_in_calls_p_P₂: c ∉ calls_n P₂, from set.forall_not_mem_of_eq_empty no_calls_n_in_P₂ c,\n show «false», from c_not_in_calls_p_P₂ c_in_calls_p_P₂\n )\n ),\n have h3: quantifiers_p (P₁ ⋁ P₂) = ∅, from set.eq_empty_of_forall_not_mem (\n assume q: callquantifier,\n assume : q ∈ quantifiers_p (P₁ ⋁ P₂),\n have q ∈ quantifiers_p P₁ ∨ q ∈ quantifiers_p P₂, from prop.has_quantifier_p.or.inv this,\n or.elim this (\n assume q_in_quantifiers_p_P₁: q ∈ quantifiers_p P₁,\n have q_not_in_quantifiers_p_P₁: q ∉ quantifiers_p P₁, from set.forall_not_mem_of_eq_empty no_quantifiers_p_in_P₁ q,\n show «false», from q_not_in_quantifiers_p_P₁ q_in_quantifiers_p_P₁\n ) (\n assume q_in_quantifiers_p_P₂: q ∈ quantifiers_p P₂,\n have q_not_in_quantifiers_p_P₂: q ∉ quantifiers_p P₂, from set.forall_not_mem_of_eq_empty no_quantifiers_p_in_P₂ q,\n show «false», from q_not_in_quantifiers_p_P₂ q_in_quantifiers_p_P₂\n )\n ),\n have h4: quantifiers_n (P₁ ⋁ P₂) = ∅, from set.eq_empty_of_forall_not_mem (\n assume q: callquantifier,\n assume : q ∈ quantifiers_n (P₁ ⋁ P₂),\n have q ∈ quantifiers_n P₁ ∨ q ∈ quantifiers_n P₂, from prop.has_quantifier_n.or.inv this,\n or.elim this (\n assume q_in_quantifiers_p_P₁: q ∈ quantifiers_n P₁,\n have q_not_in_quantifiers_p_P₁: q ∉ quantifiers_n P₁, from set.forall_not_mem_of_eq_empty no_quantifiers_n_in_P₁ q,\n show «false», from q_not_in_quantifiers_p_P₁ q_in_quantifiers_p_P₁\n ) (\n assume q_in_quantifiers_p_P₂: q ∈ quantifiers_n P₂,\n have q_not_in_quantifiers_p_P₂: q ∉ quantifiers_n P₂, from set.forall_not_mem_of_eq_empty no_quantifiers_n_in_P₂ q,\n show «false», from q_not_in_quantifiers_p_P₂ q_in_quantifiers_p_P₂\n )\n ),\n ⟨h1, ⟨h2, ⟨h3, h4⟩⟩⟩\n\nlemma no_instantiations.pre {t₁ t₂: term}: no_instantiations (prop.pre t₁ t₂) :=\n have h1: calls_p (prop.pre t₁ t₂) = ∅, from set.eq_empty_of_forall_not_mem (\n assume c: calltrigger,\n assume : c ∈ calls_p (prop.pre t₁ t₂),\n show «false», from prop.has_call_p.pre.inv this\n ),\n have h2: calls_n (prop.pre t₁ t₂) = ∅, from set.eq_empty_of_forall_not_mem (\n assume c: calltrigger,\n assume : c ∈ calls_n (prop.pre t₁ t₂),\n show «false», from prop.has_call_n.pre.inv this\n ),\n have h3: quantifiers_p (prop.pre t₁ t₂) = ∅, from set.eq_empty_of_forall_not_mem (\n assume q: callquantifier,\n assume : q ∈ quantifiers_p (prop.pre t₁ t₂),\n show «false», from prop.has_quantifier_p.pre.inv this\n ),\n have h4: quantifiers_n (prop.pre t₁ t₂) = ∅, from set.eq_empty_of_forall_not_mem (\n assume q: callquantifier,\n assume : q ∈ quantifiers_n (prop.pre t₁ t₂),\n show «false», from prop.has_quantifier_n.pre.inv this\n ),\n ⟨h1, ⟨h2, ⟨h3, h4⟩⟩⟩\n\nlemma no_instantiations.pre₁ {t: term} {op: unop}: no_instantiations (prop.pre₁ op t) :=\n have h1: calls_p (prop.pre₁ op t) = ∅, from set.eq_empty_of_forall_not_mem (\n assume c: calltrigger,\n assume : c ∈ calls_p (prop.pre₁ op t),\n show «false», from prop.has_call_p.pre₁.inv this\n ),\n have h2: calls_n (prop.pre₁ op t) = ∅, from set.eq_empty_of_forall_not_mem (\n assume c: calltrigger,\n assume : c ∈ calls_n (prop.pre₁ op t),\n show «false», from prop.has_call_n.pre₁.inv this\n ),\n have h3: quantifiers_p (prop.pre₁ op t) = ∅, from set.eq_empty_of_forall_not_mem (\n assume q: callquantifier,\n assume : q ∈ quantifiers_p (prop.pre₁ op t),\n show «false», from prop.has_quantifier_p.pre₁.inv this\n ),\n have h4: quantifiers_n (prop.pre₁ op t) = ∅, from set.eq_empty_of_forall_not_mem (\n assume q: callquantifier,\n assume : q ∈ quantifiers_n (prop.pre₁ op t),\n show «false», from prop.has_quantifier_n.pre₁.inv this\n ),\n ⟨h1, ⟨h2, ⟨h3, h4⟩⟩⟩\n\nlemma no_instantiations.pre₂ {t₁ t₂: term} {op: binop}: no_instantiations (prop.pre₂ op t₁ t₂) :=\n have h1: calls_p (prop.pre₂ op t₁ t₂) = ∅, from set.eq_empty_of_forall_not_mem (\n assume c: calltrigger,\n assume : c ∈ calls_p (prop.pre₂ op t₁ t₂),\n show «false», from prop.has_call_p.pre₂.inv this\n ),\n have h2: calls_n (prop.pre₂ op t₁ t₂) = ∅, from set.eq_empty_of_forall_not_mem (\n assume c: calltrigger,\n assume : c ∈ calls_n (prop.pre₂ op t₁ t₂),\n show «false», from prop.has_call_n.pre₂.inv this\n ),\n have h3: quantifiers_p (prop.pre₂ op t₁ t₂) = ∅, from set.eq_empty_of_forall_not_mem (\n assume q: callquantifier,\n assume : q ∈ quantifiers_p (prop.pre₂ op t₁ t₂),\n show «false», from prop.has_quantifier_p.pre₂.inv this\n ),\n have h4: quantifiers_n (prop.pre₂ op t₁ t₂) = ∅, from set.eq_empty_of_forall_not_mem (\n assume q: callquantifier,\n assume : q ∈ quantifiers_n (prop.pre₂ op t₁ t₂),\n show «false», from prop.has_quantifier_n.pre₂.inv this\n ),\n ⟨h1, ⟨h2, ⟨h3, h4⟩⟩⟩\n\nlemma no_instantiations.post {t₁ t₂: term}: no_instantiations (prop.post t₁ t₂) :=\n have h1: calls_p (prop.post t₁ t₂) = ∅, from set.eq_empty_of_forall_not_mem (\n assume c: calltrigger,\n assume : c ∈ calls_p (prop.post t₁ t₂),\n show «false», from prop.has_call_p.post.inv this\n ),\n have h2: calls_n (prop.post t₁ t₂) = ∅, from set.eq_empty_of_forall_not_mem (\n assume c: calltrigger,\n assume : c ∈ calls_n (prop.post t₁ t₂),\n show «false», from prop.has_call_n.post.inv this\n ),\n have h3: quantifiers_p (prop.post t₁ t₂) = ∅, from set.eq_empty_of_forall_not_mem (\n assume q: callquantifier,\n assume : q ∈ quantifiers_p (prop.post t₁ t₂),\n show «false», from prop.has_quantifier_p.post.inv this\n ),\n have h4: quantifiers_n (prop.post t₁ t₂) = ∅, from set.eq_empty_of_forall_not_mem (\n assume q: callquantifier,\n assume : q ∈ quantifiers_n (prop.post t₁ t₂),\n show «false», from prop.has_quantifier_n.post.inv this\n ),\n ⟨h1, ⟨h2, ⟨h3, h4⟩⟩⟩\n\nlemma prop.erased_n.implies {P Q: prop}:\n (prop.implies P Q).erased_n = vc.implies P.erased_p Q.erased_n :=\n by calc \n (prop.implies P Q).erased_n = (prop.or (prop.not P) Q).erased_n : rfl\n ... = ((prop.not P).erased_n ⋁ Q.erased_n) : by unfold prop.erased_n\n ... = ((vc.not P.erased_p) ⋁ Q.erased_n) : by unfold prop.erased_n\n\nlemma prop.erased_p.implies {P Q: prop}:\n (prop.implies P Q).erased_p = vc.implies P.erased_n Q.erased_p :=\n by calc \n (prop.implies P Q).erased_p = (prop.or (prop.not P) Q).erased_p : rfl\n ... = ((prop.not P).erased_p ⋁ Q.erased_p) : by unfold prop.erased_p\n ... = (vc.not P.erased_n ⋁ Q.erased_p) : by unfold prop.erased_p\n\nlemma free_of_erased_n_free {x: var} {P: prop}: (x ∈ FV P.erased_n ∨ x ∈ FV P.erased_p) → x ∈ FV P :=\n assume x_free_in_erased_n_or_erased_p,\n begin\n induction P,\n case prop.term t { from (\n or.elim x_free_in_erased_n_or_erased_p\n (\n assume x_free_in_t: free_in_vc x (prop.term t).erased_n,\n have (prop.term t).erased_n = vc.term t, by unfold prop.erased_n,\n have free_in_vc x (vc.term t), from this ▸ x_free_in_t,\n have free_in_term x t, from free_in_vc.term.inv this,\n show free_in_prop x (prop.term t), from free_in_prop.term this\n ) (\n assume x_free_in_t: free_in_vc x (prop.term t).erased_p,\n have (prop.term t).erased_p = vc.term t, by unfold prop.erased_p,\n have free_in_vc x (vc.term t), from this ▸ x_free_in_t,\n have free_in_term x t, from free_in_vc.term.inv this,\n show free_in_prop x (prop.term t), from free_in_prop.term this\n )\n )},\n case prop.not P₁ ih { from (\n or.elim x_free_in_erased_n_or_erased_p\n (\n assume x_free: x ∈ FV (prop.not P₁).erased_n,\n have (prop.not P₁).erased_n = vc.not P₁.erased_p, by unfold prop.erased_n,\n have x ∈ FV (vc.not P₁.erased_p), from this ▸ x_free,\n have x ∈ FV P₁.erased_p, from free_in_vc.not.inv this,\n have x ∈ FV P₁, from ih (or.inr this),\n show x ∈ FV P₁.not, from free_in_prop.not this\n ) (\n assume x_free: x ∈ FV (prop.not P₁).erased_p,\n have (prop.not P₁).erased_p = vc.not P₁.erased_n, by unfold prop.erased_p,\n have x ∈ FV (vc.not P₁.erased_n), from this ▸ x_free,\n have x ∈ FV P₁.erased_n, from free_in_vc.not.inv this,\n have x ∈ FV P₁, from ih (or.inl this),\n show x ∈ FV P₁.not, from free_in_prop.not this\n )\n )},\n case prop.and P₁ P₂ P₁_ih P₂_ih { from (\n or.elim x_free_in_erased_n_or_erased_p (\n assume x_free: x ∈ FV (P₁ ⋀ P₂).erased_n,\n have (prop.and P₁ P₂).erased_n = (P₁.erased_n ⋀ P₂.erased_n), by unfold prop.erased_n,\n have x ∈ FV (P₁.erased_n ⋀ P₂.erased_n), from this ▸ x_free,\n have x ∈ FV P₁.erased_n ∨ x ∈ FV P₂.erased_n, from free_in_vc.and.inv this,\n or.elim this (\n assume : x ∈ FV P₁.erased_n,\n have x ∈ FV P₁, from P₁_ih (or.inl this),\n show x ∈ FV (P₁ ⋀ P₂), from free_in_prop.and₁ this\n ) (\n assume : x ∈ FV P₂.erased_n,\n have x ∈ FV P₂, from P₂_ih (or.inl this),\n show x ∈ FV (P₁ ⋀ P₂), from free_in_prop.and₂ this\n )\n ) (\n assume x_free: x ∈ FV (P₁ ⋀ P₂).erased_p,\n have (prop.and P₁ P₂).erased_p = (P₁.erased_p ⋀ P₂.erased_p), by unfold prop.erased_p,\n have x ∈ FV (P₁.erased_p ⋀ P₂.erased_p), from this ▸ x_free,\n have x ∈ FV P₁.erased_p ∨ x ∈ FV P₂.erased_p, from free_in_vc.and.inv this,\n or.elim this (\n assume : x ∈ FV P₁.erased_p,\n have x ∈ FV P₁, from P₁_ih (or.inr this),\n show x ∈ FV (P₁ ⋀ P₂), from free_in_prop.and₁ this\n ) (\n assume : x ∈ FV P₂.erased_p,\n have x ∈ FV P₂, from P₂_ih (or.inr this),\n show x ∈ FV (P₁ ⋀ P₂), from free_in_prop.and₂ this\n )\n )\n )},\n case prop.or P₁ P₂ P₁_ih P₂_ih { from (\n or.elim x_free_in_erased_n_or_erased_p (\n assume x_free: x ∈ FV (P₁ ⋁ P₂).erased_n,\n have (prop.or P₁ P₂).erased_n = (P₁.erased_n ⋁ P₂.erased_n), by unfold prop.erased_n,\n have x ∈ FV (P₁.erased_n ⋁ P₂.erased_n), from this ▸ x_free,\n have x ∈ FV P₁.erased_n ∨ x ∈ FV P₂.erased_n, from free_in_vc.or.inv this,\n or.elim this (\n assume : x ∈ FV P₁.erased_n,\n have x ∈ FV P₁, from P₁_ih (or.inl this),\n show x ∈ FV (P₁ ⋁ P₂), from free_in_prop.or₁ this\n ) (\n assume : x ∈ FV P₂.erased_n,\n have x ∈ FV P₂, from P₂_ih (or.inl this),\n show x ∈ FV (P₁ ⋁ P₂), from free_in_prop.or₂ this\n )\n ) (\n assume x_free: x ∈ FV (P₁ ⋁ P₂).erased_p,\n have (prop.or P₁ P₂).erased_p = (P₁.erased_p ⋁ P₂.erased_p), by unfold prop.erased_p,\n have x ∈ FV (P₁.erased_p ⋁ P₂.erased_p), from this ▸ x_free,\n have x ∈ FV P₁.erased_p ∨ x ∈ FV P₂.erased_p, from free_in_vc.or.inv this,\n or.elim this (\n assume : x ∈ FV P₁.erased_p,\n have x ∈ FV P₁, from P₁_ih (or.inr this),\n show x ∈ FV (P₁ ⋁ P₂), from free_in_prop.or₁ this\n ) (\n assume : x ∈ FV P₂.erased_p,\n have x ∈ FV P₂, from P₂_ih (or.inr this),\n show x ∈ FV (P₁ ⋁ P₂), from free_in_prop.or₂ this\n )\n )\n )},\n case prop.pre t₁ t₂ { from (\n or.elim x_free_in_erased_n_or_erased_p (\n assume x_free: x ∈ FV (prop.pre t₁ t₂).erased_n,\n have (prop.pre t₁ t₂).erased_n = vc.pre t₁ t₂, by unfold prop.erased_n,\n have x ∈ FV (vc.pre t₁ t₂), from this ▸ x_free,\n have x ∈ FV t₁ ∨ x ∈ FV t₂, from free_in_vc.pre.inv this,\n or.elim this (\n assume : x ∈ FV t₁,\n show free_in_prop x (prop.pre t₁ t₂), from free_in_prop.pre₁ this\n ) (\n assume : x ∈ FV t₂,\n show free_in_prop x (prop.pre t₁ t₂), from free_in_prop.pre₂ this\n )\n ) (\n assume x_free: x ∈ FV (prop.pre t₁ t₂).erased_p,\n have (prop.pre t₁ t₂).erased_p = vc.pre t₁ t₂, by unfold prop.erased_p,\n have x ∈ FV (vc.pre t₁ t₂), from this ▸ x_free,\n have x ∈ FV t₁ ∨ x ∈ FV t₂, from free_in_vc.pre.inv this,\n or.elim this (\n assume : x ∈ FV t₁,\n show free_in_prop x (prop.pre t₁ t₂), from free_in_prop.pre₁ this\n ) (\n assume : x ∈ FV t₂,\n show free_in_prop x (prop.pre t₁ t₂), from free_in_prop.pre₂ this\n )\n )\n )},\n case prop.pre₁ op t { from (\n or.elim x_free_in_erased_n_or_erased_p (\n assume x_free_in_t: free_in_vc x (prop.pre₁ op t).erased_n,\n have (prop.pre₁ op t).erased_n = vc.pre₁ op t, by unfold prop.erased_n,\n have free_in_vc x (vc.pre₁ op t), from this ▸ x_free_in_t,\n have free_in_term x t, from free_in_vc.pre₁.inv this,\n show free_in_prop x (prop.pre₁ op t), from free_in_prop.preop this\n ) (\n assume x_free_in_t: free_in_vc x (prop.pre₁ op t).erased_p,\n have (prop.pre₁ op t).erased_p = vc.pre₁ op t, by unfold prop.erased_p,\n have free_in_vc x (vc.pre₁ op t), from this ▸ x_free_in_t,\n have free_in_term x t, from free_in_vc.pre₁.inv this,\n show free_in_prop x (prop.pre₁ op t), from free_in_prop.preop this\n )\n )},\n case prop.pre₂ op t₁ t₂ { from (\n or.elim x_free_in_erased_n_or_erased_p (\n assume x_free: x ∈ FV (prop.pre₂ op t₁ t₂).erased_n,\n have (prop.pre₂ op t₁ t₂).erased_n = vc.pre₂ op t₁ t₂, by unfold prop.erased_n,\n have x ∈ FV (vc.pre₂ op t₁ t₂), from this ▸ x_free,\n have x ∈ FV t₁ ∨ x ∈ FV t₂, from free_in_vc.pre₂.inv this,\n or.elim this (\n assume : x ∈ FV t₁,\n show free_in_prop x (prop.pre₂ op t₁ t₂), from free_in_prop.preop₁ this\n ) (\n assume : x ∈ FV t₂,\n show free_in_prop x (prop.pre₂ op t₁ t₂), from free_in_prop.preop₂ this\n )\n ) (\n assume x_free: x ∈ FV (prop.pre₂ op t₁ t₂).erased_p,\n have (prop.pre₂ op t₁ t₂).erased_p = vc.pre₂ op t₁ t₂, by unfold prop.erased_p,\n have x ∈ FV (vc.pre₂ op t₁ t₂), from this ▸ x_free,\n have x ∈ FV t₁ ∨ x ∈ FV t₂, from free_in_vc.pre₂.inv this,\n or.elim this (\n assume : x ∈ FV t₁,\n show free_in_prop x (prop.pre₂ op t₁ t₂), from free_in_prop.preop₁ this\n ) (\n assume : x ∈ FV t₂,\n show free_in_prop x (prop.pre₂ op t₁ t₂), from free_in_prop.preop₂ this\n )\n )\n )},\n case prop.post t₁ t₂ { from (\n or.elim x_free_in_erased_n_or_erased_p (\n assume x_free: x ∈ FV (prop.post t₁ t₂).erased_n,\n have (prop.post t₁ t₂).erased_n = vc.post t₁ t₂, by unfold prop.erased_n,\n have x ∈ FV (vc.post t₁ t₂), from this ▸ x_free,\n have x ∈ FV t₁ ∨ x ∈ FV t₂, from free_in_vc.post.inv this,\n or.elim this (\n assume : x ∈ FV t₁,\n\n show free_in_prop x (prop.post t₁ t₂), from free_in_prop.post₁ this\n ) (\n assume : x ∈ FV t₂,\n\n show free_in_prop x (prop.post t₁ t₂), from free_in_prop.post₂ this\n )\n ) (\n assume x_free: x ∈ FV (prop.post t₁ t₂).erased_p,\n have (prop.post t₁ t₂).erased_p = vc.post t₁ t₂, by unfold prop.erased_p,\n have x ∈ FV (vc.post t₁ t₂), from this ▸ x_free,\n have x ∈ FV t₁ ∨ x ∈ FV t₂, from free_in_vc.post.inv this,\n or.elim this (\n assume : x ∈ FV t₁,\n\n show free_in_prop x (prop.post t₁ t₂), from free_in_prop.post₁ this\n ) (\n assume : x ∈ FV t₂,\n\n show free_in_prop x (prop.post t₁ t₂), from free_in_prop.post₂ this\n )\n )\n )},\n case prop.call t { from (\n or.elim x_free_in_erased_n_or_erased_p (\n assume x_free: x ∈ FV (prop.call t).erased_n,\n have (prop.call t).erased_n = vc.term value.true, by unfold prop.erased_n,\n have x ∈ FV (vc.term value.true), from this ▸ x_free,\n have x ∈ FV (term.value value.true), from free_in_vc.term.inv this,\n absurd this (free_in_term.value.inv)\n ) (\n assume x_free: x ∈ FV (prop.call t).erased_p,\n have (prop.call t).erased_p = vc.term value.true, by unfold prop.erased_p,\n have x ∈ FV (vc.term value.true), from this ▸ x_free,\n have x ∈ FV (term.value value.true), from free_in_vc.term.inv this,\n absurd this (free_in_term.value.inv)\n )\n )},\n case prop.forallc y P₁ ih { from (\n or.elim x_free_in_erased_n_or_erased_p (\n assume x_free: x ∈ FV (prop.forallc y P₁).erased_n,\n have (prop.forallc y P₁).erased_n = vc.univ y P₁.erased_n, by unfold prop.erased_n,\n have x ∈ FV (vc.univ y P₁.erased_n), from this ▸ x_free,\n have h2: (x ≠ y) ∧ free_in_vc x P₁.erased_n, from free_in_vc.univ.inv this,\n have x ∈ FV P₁, from ih (or.inl h2.right),\n show x ∈ FV (prop.forallc y P₁), from free_in_prop.forallc h2.left this\n ) (\n assume x_free: x ∈ FV (prop.forallc y P₁).erased_p,\n have (prop.forallc y P₁).erased_p = vc.term value.true, by unfold prop.erased_p,\n have x ∈ FV (vc.term value.true), from this ▸ x_free,\n have x ∈ FV (term.value value.true), from free_in_vc.term.inv this,\n absurd this (free_in_term.value.inv)\n )\n )},\n case prop.exis y P₁ ih { from (\n or.elim x_free_in_erased_n_or_erased_p (\n assume x_free: x ∈ FV (prop.exis y P₁).erased_n,\n have (prop.exis y P₁).erased_n = vc.not (vc.univ y (vc.not P₁.erased_n)), by unfold prop.erased_n,\n have x ∈ FV (vc.not (vc.univ y (vc.not P₁.erased_n))), from this ▸ x_free,\n have x ∈ FV (vc.univ y (vc.not P₁.erased_n)), from free_in_vc.not.inv this,\n have h2: (x ≠ y) ∧ free_in_vc x (vc.not P₁.erased_n), from free_in_vc.univ.inv this,\n have h3: x ∈ FV P₁.erased_n, from free_in_vc.not.inv h2.right,\n have x ∈ FV P₁, from ih (or.inl h3),\n show x ∈ FV (prop.exis y P₁), from free_in_prop.exis h2.left this\n )\n (\n assume x_free: x ∈ FV (prop.exis y P₁).erased_p,\n have (prop.exis y P₁).erased_p = vc.not (vc.univ y (vc.not P₁.erased_p)), by unfold prop.erased_p,\n have x ∈ FV (vc.not (vc.univ y (vc.not P₁.erased_p))), from this ▸ x_free,\n have x ∈ FV (vc.univ y (vc.not P₁.erased_p)), from free_in_vc.not.inv this,\n have h2: (x ≠ y) ∧ free_in_vc x (vc.not P₁.erased_p), from free_in_vc.univ.inv this,\n have h3: x ∈ FV P₁.erased_p, from free_in_vc.not.inv h2.right,\n have x ∈ FV P₁, from ih (or.inr h3),\n show x ∈ FV (prop.exis y P₁), from free_in_prop.exis h2.left this\n )\n )}\n end\n\nlemma free_of_erased_free {x: var} {P: prop}: (x ∈ FV P.erased_p ∨ x ∈ FV P.erased_n) → x ∈ FV P :=\n assume : x ∈ FV P.erased_p ∨ x ∈ FV P.erased_n,\n have x ∈ FV P.erased_n ∨ x ∈ FV P.erased_p, from this.symm,\n show x ∈ FV P, from free_of_erased_n_free this\n\nlemma prop.has_call_p.and_union {P₁ P₂: prop}:\n calls_p (P₁ ⋀ P₂) = calls_p P₁ ∪ calls_p P₂ :=\n set.eq_of_subset_of_subset (\n assume c: calltrigger,\n assume : c ∈ calls_p (P₁ ⋀ P₂),\n or.elim (prop.has_call_p.and.inv this) (\n assume : c ∈ calls_p P₁,\n show c ∈ calls_p P₁ ∪ calls_p P₂, from set.mem_union_left (calls_p P₂) this\n ) (\n assume : c ∈ calls_p P₂,\n show c ∈ calls_p P₁ ∪ calls_p P₂, from set.mem_union_right (calls_p P₁) this\n )\n ) (\n assume c: calltrigger,\n assume : c ∈ calls_p P₁ ∪ calls_p P₂,\n or.elim (set.mem_or_mem_of_mem_union this) (\n assume : c ∈ calls_p P₁,\n show c ∈ calls_p (P₁ ⋀ P₂), from prop.has_call_p.and₁ this\n ) (\n assume : c ∈ calls_p P₂,\n show c ∈ calls_p (P₁ ⋀ P₂), from prop.has_call_p.and₂ this\n )\n )\n\nlemma prop.has_call_p.and.symm {P₁ P₂: prop}:\n calls_p (P₁ ⋀ P₂) = calls_p (P₂ ⋀ P₁) :=\n set.eq_of_subset_of_subset (\n assume c: calltrigger,\n assume : c ∈ calls_p (P₁ ⋀ P₂),\n or.elim (prop.has_call_p.and.inv this) (\n assume : c ∈ calls_p P₁,\n show c ∈ calls_p (P₂ ⋀ P₁), from prop.has_call_p.and₂ this\n ) (\n assume : c ∈ calls_p P₂,\n show c ∈ calls_p (P₂ ⋀ P₁), from prop.has_call_p.and₁ this\n )\n ) (\n assume c: calltrigger,\n assume : c ∈ calls_p (P₂ ⋀ P₁),\n or.elim (prop.has_call_p.and.inv this) (\n assume : c ∈ calls_p P₂,\n show c ∈ calls_p (P₁ ⋀ P₂), from prop.has_call_p.and₂ this\n ) (\n assume : c ∈ calls_p P₁,\n show c ∈ calls_p (P₁ ⋀ P₂), from prop.has_call_p.and₁ this\n )\n )\n\nlemma prop.has_quantifier_p.and.symm {P₁ P₂: prop}:\n quantifiers_p (P₁ ⋀ P₂) = quantifiers_p (P₂ ⋀ P₁) :=\n set.eq_of_subset_of_subset (\n assume q: callquantifier,\n assume : q ∈ quantifiers_p (P₁ ⋀ P₂),\n or.elim (prop.has_quantifier_p.and.inv this) (\n assume : q ∈ quantifiers_p P₁,\n show q ∈ quantifiers_p (P₂ ⋀ P₁), from prop.has_quantifier_p.and₂ this\n ) (\n assume : q ∈ quantifiers_p P₂,\n show q ∈ quantifiers_p (P₂ ⋀ P₁), from prop.has_quantifier_p.and₁ this\n )\n ) (\n assume q: callquantifier,\n assume : q ∈ quantifiers_p (P₂ ⋀ P₁),\n or.elim (prop.has_quantifier_p.and.inv this) (\n assume : q ∈ quantifiers_p P₂,\n show q ∈ quantifiers_p (P₁ ⋀ P₂), from prop.has_quantifier_p.and₂ this\n ) (\n assume : q ∈ quantifiers_p P₁,\n show q ∈ quantifiers_p (P₁ ⋀ P₂), from prop.has_quantifier_p.and₁ this\n )\n )\n\nlemma prop.has_call_p.and.comm {P₁ P₂ P₃: prop}:\n calls_p (P₁ ⋀ P₂ ⋀ P₃) = calls_p ((P₁ ⋀ P₂) ⋀ P₃) :=\n set.eq_of_subset_of_subset (\n assume c: calltrigger,\n assume : c ∈ calls_p (P₁ ⋀ P₂ ⋀ P₃),\n or.elim (prop.has_call_p.and.inv this) (\n assume : c ∈ calls_p P₁,\n have c ∈ calls_p (P₁ ⋀ P₂), from prop.has_call_p.and₁ this,\n show c ∈ calls_p ((P₁ ⋀ P₂) ⋀ P₃), from prop.has_call_p.and₁ this\n ) (\n assume : c ∈ calls_p (P₂ ⋀ P₃),\n or.elim (prop.has_call_p.and.inv this) (\n assume : c ∈ calls_p P₂,\n have c ∈ calls_p (P₁ ⋀ P₂), from prop.has_call_p.and₂ this,\n show c ∈ calls_p ((P₁ ⋀ P₂) ⋀ P₃), from prop.has_call_p.and₁ this\n ) (\n assume : c ∈ calls_p P₃,\n show c ∈ calls_p ((P₁ ⋀ P₂) ⋀ P₃), from prop.has_call_p.and₂ this\n )\n )\n ) (\n assume c: calltrigger,\n assume : c ∈ calls_p ((P₁ ⋀ P₂) ⋀ P₃),\n or.elim (prop.has_call_p.and.inv this) (\n assume : c ∈ calls_p (P₁ ⋀ P₂),\n or.elim (prop.has_call_p.and.inv this) (\n assume : c ∈ calls_p P₁,\n show c ∈ calls_p (P₁ ⋀ P₂ ⋀ P₃), from prop.has_call_p.and₁ this\n ) (\n assume : c ∈ calls_p P₂,\n have c ∈ calls_p (P₂ ⋀ P₃), from prop.has_call_p.and₁ this,\n show c ∈ calls_p (P₁ ⋀ P₂ ⋀ P₃), from prop.has_call_p.and₂ this\n )\n ) (\n assume : c ∈ calls_p P₃,\n have c ∈ calls_p (P₂ ⋀ P₃), from prop.has_call_p.and₂ this,\n show c ∈ calls_p (P₁ ⋀ P₂ ⋀ P₃), from prop.has_call_p.and₂ this\n )\n )\n\nlemma prop.has_quantifier_p.and.comm {P₁ P₂ P₃: prop}:\n quantifiers_p (P₁ ⋀ P₂ ⋀ P₃) = quantifiers_p ((P₁ ⋀ P₂) ⋀ P₃) :=\n set.eq_of_subset_of_subset (\n assume q: callquantifier,\n assume : q ∈ quantifiers_p (P₁ ⋀ P₂ ⋀ P₃),\n or.elim (prop.has_quantifier_p.and.inv this) (\n assume : q ∈ quantifiers_p P₁,\n have q ∈ quantifiers_p (P₁ ⋀ P₂), from prop.has_quantifier_p.and₁ this,\n show q ∈ quantifiers_p ((P₁ ⋀ P₂) ⋀ P₃), from prop.has_quantifier_p.and₁ this\n ) (\n assume : q ∈ quantifiers_p (P₂ ⋀ P₃),\n or.elim (prop.has_quantifier_p.and.inv this) (\n assume : q ∈ quantifiers_p P₂,\n have q ∈ quantifiers_p (P₁ ⋀ P₂), from prop.has_quantifier_p.and₂ this,\n show q ∈ quantifiers_p ((P₁ ⋀ P₂) ⋀ P₃), from prop.has_quantifier_p.and₁ this\n ) (\n assume : q ∈ quantifiers_p P₃,\n show q ∈ quantifiers_p ((P₁ ⋀ P₂) ⋀ P₃), from prop.has_quantifier_p.and₂ this\n )\n )\n ) (\n assume q: callquantifier,\n assume : q ∈ quantifiers_p ((P₁ ⋀ P₂) ⋀ P₃),\n or.elim (prop.has_quantifier_p.and.inv this) (\n assume : q ∈ quantifiers_p (P₁ ⋀ P₂),\n or.elim (prop.has_quantifier_p.and.inv this) (\n assume : q ∈ quantifiers_p P₁,\n show q ∈ quantifiers_p (P₁ ⋀ P₂ ⋀ P₃), from prop.has_quantifier_p.and₁ this\n ) (\n assume : q ∈ quantifiers_p P₂,\n have q ∈ quantifiers_p (P₂ ⋀ P₃), from prop.has_quantifier_p.and₁ this,\n show q ∈ quantifiers_p (P₁ ⋀ P₂ ⋀ P₃), from prop.has_quantifier_p.and₂ this\n )\n ) (\n assume : q ∈ quantifiers_p P₃,\n have q ∈ quantifiers_p (P₂ ⋀ P₃), from prop.has_quantifier_p.and₂ this,\n show q ∈ quantifiers_p (P₁ ⋀ P₂ ⋀ P₃), from prop.has_quantifier_p.and₂ this\n )\n )\n\nlemma same_calls_p_and_left {P P' Q: prop} {σ: env}:\n calls_p_subst σ P' ⊆ calls_p_subst σ P → (calls_p_subst σ (P' ⋀ Q) ⊆ calls_p_subst σ (P ⋀ Q)) :=\n assume calls_P'_P: calls_p_subst σ P' ⊆ calls_p_subst σ P,\n assume c: calltrigger,\n assume : c ∈ calls_p_subst σ (P' ⋀ Q),\n or.elim (prop.has_call_p_subst.and.inv this) (\n assume : c ∈ calls_p_subst σ P',\n have c ∈ calls_p_subst σ P, from set.mem_of_mem_of_subset this calls_P'_P,\n show c ∈ calls_p_subst σ (P ⋀ Q), from prop.has_call_p_subst.and₁ this\n )\n (\n assume : c ∈ calls_p_subst σ Q,\n show c ∈ calls_p_subst σ (P ⋀ Q), from prop.has_call_p_subst.and₂ this\n )\n\nlemma prop.has_call_of_subst_has_call {P: prop} {c: calltrigger} {y: var} {v: value}:\n (c ∈ calls_p (prop.subst y v P) → ∃c', c' ∈ calls_p P) ∧\n (c ∈ calls_n (prop.subst y v P) → ∃c', c' ∈ calls_n P) :=\n begin\n induction P,\n case prop.term t {\n split,\n\n intro h,\n unfold prop.subst at h,\n cases h,\n\n intro h,\n unfold prop.subst at h,\n cases h\n },\n case prop.not P₁ P₁_ih {\n split,\n\n intro h,\n unfold prop.subst at h,\n have h2, from prop.has_call_p.not.inv h,\n have h3, from P₁_ih.right h2,\n cases h3 with c' a,\n from ⟨c', prop.has_call_p.not a⟩,\n\n intro h,\n unfold prop.subst at h,\n have h2, from prop.has_call_n.not.inv h,\n have h3, from P₁_ih.left h2,\n cases h3 with c' h3,\n from ⟨c', prop.has_call_n.not h3⟩,\n },\n case prop.and P₂ P₃ P₂_ih P₃_ih {\n split,\n\n intro h,\n unfold prop.subst at h,\n have h2, from prop.has_call_p.and.inv h,\n cases h2,\n have h3, from P₂_ih.left a,\n cases h3 with c' h3,\n from ⟨c', prop.has_call_p.and₁ h3⟩,\n have h3, from P₃_ih.left a,\n cases h3 with c' h3,\n from ⟨c', prop.has_call_p.and₂ h3⟩,\n\n intro h,\n unfold prop.subst at h,\n have h2, from prop.has_call_n.and.inv h,\n cases h2,\n have h3, from P₂_ih.right a,\n cases h3 with c' h3,\n from ⟨c', prop.has_call_n.and₁ h3⟩,\n have h3, from P₃_ih.right a,\n cases h3 with c' h3,\n from ⟨c', prop.has_call_n.and₂ h3⟩,\n },\n case prop.or P₄ P₅ P₄_ih P₅_ih {\n split,\n\n intro h,\n unfold prop.subst at h,\n have h2, from prop.has_call_p.or.inv h,\n cases h2,\n have h3, from P₄_ih.left a,\n cases h3 with c' h3,\n from ⟨c', prop.has_call_p.or₁ h3⟩,\n have h3, from P₅_ih.left a,\n cases h3 with c' h3,\n from ⟨c', prop.has_call_p.or₂ h3⟩,\n\n intro h,\n unfold prop.subst at h,\n have h2, from prop.has_call_n.or.inv h,\n cases h2,\n have h3, from P₄_ih.right a,\n cases h3 with c' h3,\n from ⟨c', prop.has_call_n.or₁ h3⟩,\n have h3, from P₅_ih.right a,\n cases h3 with c' h3,\n from ⟨c', prop.has_call_n.or₂ h3⟩,\n },\n case prop.pre t₁ t₂ {\n split,\n\n intro h,\n unfold prop.subst at h,\n cases h,\n\n intro h,\n unfold prop.subst at h,\n cases h\n },\n case prop.pre₁ op t {\n split,\n\n intro h,\n unfold prop.subst at h,\n cases h,\n\n intro h,\n unfold prop.subst at h,\n cases h\n },\n case prop.pre₂ op t₁ t₂ {\n split,\n\n intro h,\n unfold prop.subst at h,\n cases h,\n\n intro h,\n unfold prop.subst at h,\n cases h\n },\n case prop.post t₁ t₂ {\n split,\n\n intro h,\n unfold prop.subst at h,\n cases h,\n\n intro h,\n unfold prop.subst at h,\n cases h\n },\n case prop.call t {\n split,\n\n intro h,\n existsi (calltrigger.mk t),\n apply prop.has_call_p.calltrigger,\n\n intro h,\n unfold prop.subst at h,\n cases h\n },\n case prop.forallc z t P ih {\n split,\n\n intro h,\n unfold prop.subst at h,\n cases h,\n\n intro h,\n unfold prop.subst at h,\n cases h\n },\n case prop.exis z P ih {\n split,\n\n intro h,\n unfold prop.subst at h,\n cases h,\n\n intro h,\n unfold prop.subst at h,\n cases h\n }\n end\n\nlemma prop.has_call_of_subst_env_has_call {P: prop} {σ: env}:\n (∀c, c ∈ calls_p (prop.subst_env σ P) → ∃c', c' ∈ calls_p P) ∧\n (∀c, c ∈ calls_n (prop.subst_env σ P) → ∃c', c' ∈ calls_n P) :=\n begin\n induction σ with σ' y v ih,\n\n split,\n\n intro c,\n intro h,\n unfold prop.subst_env at h,\n existsi c,\n from h,\n\n intro c,\n intro h,\n unfold prop.subst_env at h,\n existsi c,\n from h,\n\n split,\n\n intro c,\n intro h,\n unfold prop.subst_env at h,\n have h2, from prop.has_call_of_subst_has_call.left h,\n cases h2 with c' h3,\n from ih.left c' h3,\n\n intro c,\n intro h,\n unfold prop.subst_env at h,\n have h2, from prop.has_call_of_subst_has_call.right h,\n cases h2 with c' h3,\n from ih.right c' h3,\n end\n\nlemma find_calls_equiv_has_call {P: prop} {c: calltrigger}:\n (c ∈ calls_p P ↔ c ∈ P.find_calls_p) ∧ (c ∈ calls_n P ↔ c ∈ P.find_calls_n) :=\n begin\n induction P,\n case prop.term t {\n split,\n\n split,\n\n assume h1,\n cases h1,\n\n assume h1,\n unfold prop.find_calls_p at h1,\n cases h1,\n\n split,\n\n assume h1,\n cases h1,\n\n assume h1,\n unfold prop.find_calls_n at h1,\n cases h1\n },\n case prop.not P₁ ih {\n split,\n\n split,\n\n assume h1,\n cases h1,\n have h2: c ∈ calls_n P₁, from a,\n unfold prop.find_calls_p,\n from ih.right.mp h2,\n\n assume h1,\n unfold prop.find_calls_p at h1,\n have h2, from ih.right.mpr h1,\n unfold has_mem.mem at h2,\n unfold set.mem at h2,\n unfold calls_n at h2,\n unfold has_mem.mem,\n unfold set.mem,\n unfold calls_p,\n from prop.has_call_p.not h2,\n\n split,\n\n assume h1,\n cases h1,\n have h2: c ∈ calls_p P₁, from a,\n unfold prop.find_calls_n,\n from ih.left.mp h2,\n\n assume h1,\n unfold prop.find_calls_n at h1,\n have h2, from ih.left.mpr h1,\n unfold has_mem.mem at h2,\n unfold set.mem at h2,\n unfold calls_p at h2,\n unfold has_mem.mem,\n unfold set.mem,\n unfold calls_n,\n from prop.has_call_n.not h2\n },\n case prop.and P₁ P₂ P₁_ih P₂_ih {\n split,\n\n split,\n\n assume h1,\n cases h1,\n\n have h2: c ∈ calls_p P₁, from a,\n unfold prop.find_calls_p,\n apply list.mem_append.mpr,\n left,\n from P₁_ih.left.mp h2,\n\n have h2: c ∈ calls_p P₂, from a,\n unfold prop.find_calls_p,\n apply list.mem_append.mpr,\n right,\n from P₂_ih.left.mp h2,\n\n assume h1,\n change prop.has_call_p c (prop.and P₁ P₂),\n\n unfold prop.find_calls_p at h1,\n have h2, from list.mem_append.mp h1,\n cases h2,\n have h3, from P₁_ih.left.mpr a,\n have h4: prop.has_call_p c P₁, from h3,\n from prop.has_call_p.and₁ h4,\n\n have h3, from P₂_ih.left.mpr a,\n have h4: prop.has_call_p c P₂, from h3,\n from prop.has_call_p.and₂ h4,\n\n split,\n\n assume h1,\n cases h1,\n\n have h2: c ∈ calls_n P₁, from a,\n unfold prop.find_calls_n,\n apply list.mem_append.mpr,\n left,\n from P₁_ih.right.mp h2,\n\n have h2: c ∈ calls_n P₂, from a,\n unfold prop.find_calls_n,\n apply list.mem_append.mpr,\n right,\n from P₂_ih.right.mp h2,\n\n assume h1,\n change prop.has_call_n c (prop.and P₁ P₂),\n\n unfold prop.find_calls_n at h1,\n have h2, from list.mem_append.mp h1,\n cases h2,\n have h3, from P₁_ih.right.mpr a,\n have h4: prop.has_call_n c P₁, from h3,\n from prop.has_call_n.and₁ h4,\n\n have h3, from P₂_ih.right.mpr a,\n have h4: prop.has_call_n c P₂, from h3,\n from prop.has_call_n.and₂ h4\n },\n case prop.or P₁ P₂ P₁_ih P₂_ih {\n split,\n\n split,\n\n assume h1,\n cases h1,\n\n have h2: c ∈ calls_p P₁, from a,\n unfold prop.find_calls_p,\n apply list.mem_append.mpr,\n left,\n from P₁_ih.left.mp h2,\n\n have h2: c ∈ calls_p P₂, from a,\n unfold prop.find_calls_p,\n apply list.mem_append.mpr,\n right,\n from P₂_ih.left.mp h2,\n\n assume h1,\n change prop.has_call_p c (prop.or P₁ P₂),\n\n unfold prop.find_calls_p at h1,\n have h2, from list.mem_append.mp h1,\n cases h2,\n have h3, from P₁_ih.left.mpr a,\n have h4: prop.has_call_p c P₁, from h3,\n from prop.has_call_p.or₁ h4,\n\n have h3, from P₂_ih.left.mpr a,\n have h4: prop.has_call_p c P₂, from h3,\n from prop.has_call_p.or₂ h4,\n\n split,\n\n assume h1,\n cases h1,\n\n have h2: c ∈ calls_n P₁, from a,\n unfold prop.find_calls_n,\n apply list.mem_append.mpr,\n left,\n from P₁_ih.right.mp h2,\n\n have h2: c ∈ calls_n P₂, from a,\n unfold prop.find_calls_n,\n apply list.mem_append.mpr,\n right,\n from P₂_ih.right.mp h2,\n\n assume h1,\n change prop.has_call_n c (prop.or P₁ P₂),\n\n unfold prop.find_calls_n at h1,\n have h2, from list.mem_append.mp h1,\n cases h2,\n have h3, from P₁_ih.right.mpr a,\n have h4: prop.has_call_n c P₁, from h3,\n from prop.has_call_n.or₁ h4,\n\n have h3, from P₂_ih.right.mpr a,\n have h4: prop.has_call_n c P₂, from h3,\n from prop.has_call_n.or₂ h4\n },\n case prop.pre t₁ t₂ {\n split,\n\n split,\n\n assume h1,\n cases h1,\n\n assume h1,\n unfold prop.find_calls_p at h1,\n cases h1,\n\n split,\n\n assume h1,\n cases h1,\n\n assume h1,\n unfold prop.find_calls_n at h1,\n cases h1\n },\n case prop.pre₁ op t {\n split,\n\n split,\n\n assume h1,\n cases h1,\n\n assume h1,\n unfold prop.find_calls_p at h1,\n cases h1,\n\n split,\n\n assume h1,\n cases h1,\n\n assume h1,\n unfold prop.find_calls_n at h1,\n cases h1\n },\n case prop.pre₂ op t₁ t₂ {\n split,\n\n split,\n\n assume h1,\n cases h1,\n\n assume h1,\n unfold prop.find_calls_p at h1,\n cases h1,\n\n split,\n\n assume h1,\n cases h1,\n\n assume h1,\n unfold prop.find_calls_n at h1,\n cases h1\n },\n case prop.call t {\n split,\n\n split,\n\n assume h1,\n cases h1,\n unfold prop.find_calls_p,\n simp,\n\n assume h1,\n unfold prop.find_calls_p at h1,\n simp at h1,\n change prop.has_call_p c (prop.call t),\n rw[h1],\n from prop.has_call_p.calltrigger,\n\n split,\n\n assume h1,\n cases h1,\n\n assume h1,\n unfold prop.find_calls_n at h1,\n cases h1\n },\n case prop.post t₁ t₂ {\n split,\n\n split,\n\n assume h1,\n cases h1,\n\n assume h1,\n unfold prop.find_calls_p at h1,\n cases h1,\n\n split,\n\n assume h1,\n cases h1,\n\n assume h1,\n unfold prop.find_calls_n at h1,\n cases h1\n },\n case prop.forallc y P₁ P₁_ih {\n split,\n\n split,\n\n assume h1,\n cases h1,\n\n assume h1,\n unfold prop.find_calls_p at h1,\n cases h1,\n\n split,\n\n assume h1,\n cases h1,\n\n assume h1,\n unfold prop.find_calls_n at h1,\n cases h1\n },\n case prop.exis y P₁ P₁_ih {\n split,\n\n split,\n\n assume h1,\n cases h1,\n\n assume h1,\n unfold prop.find_calls_p at h1,\n cases h1,\n\n split,\n\n assume h1,\n cases h1,\n\n assume h1,\n unfold prop.find_calls_n at h1,\n cases h1\n }\n end\n\nlemma to_vc_valid_of_erased_n_valid:\n ∀P: prop, ((⊨ P.erased_n) → ⊨ P.to_vc) ∧ ((⊨ P.to_vc) → ⊨ P.erased_p)\n| (prop.term t) := begin\n split,\n\n unfold prop.erased_n,\n unfold prop.to_vc,\n from id,\n\n unfold prop.erased_p,\n unfold prop.to_vc,\n from id\n end\n| (prop.not P₁) :=\n have rec_wf: P₁.simplesize < (prop.not P₁).simplesize, from simplesize_prop_not,\n begin\n split,\n\n unfold prop.erased_n,\n unfold prop.to_vc,\n assume h1,\n have h2, from mt (to_vc_valid_of_erased_n_valid P₁).right,\n have h3, from valid.not.mpr h1,\n have h4, from h2 h3,\n from valid.not.mp h4,\n\n unfold prop.erased_p,\n unfold prop.to_vc,\n assume h1,\n have h2, from mt (to_vc_valid_of_erased_n_valid P₁).left,\n have h3, from valid.not.mpr h1,\n have h4, from h2 h3,\n from valid.not.mp h4\n end\n| (prop.and P₁ P₂) :=\n have rec_1: P₁.simplesize < (prop.and P₁ P₂).simplesize, from simplesize_prop_and₁,\n have rec_2: P₂.simplesize < (prop.and P₁ P₂).simplesize, from simplesize_prop_and₂,\n begin\n split,\n\n unfold prop.erased_n,\n unfold prop.to_vc,\n assume h1,\n\n apply valid.and.mp,\n split,\n show ⊨ prop.to_vc P₁, by begin\n have h2, from (valid.and.mpr h1).left,\n from (to_vc_valid_of_erased_n_valid P₁).left h2\n end,\n\n show ⊨ prop.to_vc P₂, by begin\n have h2, from (valid.and.mpr h1).right,\n from (to_vc_valid_of_erased_n_valid P₂).left h2\n end,\n\n unfold prop.erased_p,\n unfold prop.to_vc,\n assume h1,\n\n apply valid.and.mp,\n split,\n show ⊨prop.erased_p P₁, by begin\n have h2, from (valid.and.mpr h1).left,\n from (to_vc_valid_of_erased_n_valid P₁).right h2\n end,\n\n show ⊨prop.erased_p P₂, by begin\n have h2, from (valid.and.mpr h1).right,\n from (to_vc_valid_of_erased_n_valid P₂).right h2\n end\n end\n| (prop.or P₁ P₂) :=\n have rec_1: P₁.simplesize < (prop.or P₁ P₂).simplesize, from simplesize_prop_or₁,\n have rec_2: P₂.simplesize < (prop.or P₁ P₂).simplesize, from simplesize_prop_or₂,\n begin\n split,\n\n unfold prop.erased_n,\n unfold prop.to_vc,\n assume h2,\n\n cases (valid.or.elim h2),\n\n apply valid.or.left,\n from (to_vc_valid_of_erased_n_valid P₁).left a,\n\n apply valid.or.right,\n from (to_vc_valid_of_erased_n_valid P₂).left a,\n\n unfold prop.erased_p,\n unfold prop.to_vc,\n assume h2,\n\n cases (valid.or.elim h2),\n\n apply valid.or.left,\n from (to_vc_valid_of_erased_n_valid P₁).right a,\n\n apply valid.or.right,\n from (to_vc_valid_of_erased_n_valid P₂).right a\n end\n| (prop.pre t₁ t₂) := begin\n split,\n\n unfold prop.erased_n,\n unfold prop.to_vc,\n from id,\n\n unfold prop.erased_p,\n unfold prop.to_vc,\n from id\n end\n| (prop.pre₁ op t) := begin\n split,\n\n unfold prop.erased_n,\n unfold prop.to_vc,\n from id,\n\n unfold prop.erased_p,\n unfold prop.to_vc,\n from id\n end\n| (prop.pre₂ op t₁ t₂) := begin\n split,\n\n unfold prop.erased_n,\n unfold prop.to_vc,\n from id,\n\n unfold prop.erased_p,\n unfold prop.to_vc,\n from id\n end\n| (prop.call t) := begin\n split,\n\n unfold prop.erased_n,\n unfold prop.to_vc,\n from id,\n\n unfold prop.erased_p,\n unfold prop.to_vc,\n from id\n end\n| (prop.post t₁ t₂) := begin\n split,\n\n unfold prop.erased_n,\n unfold prop.to_vc,\n from id,\n\n unfold prop.erased_p,\n unfold prop.to_vc,\n from id\n end\n| (prop.forallc y P₁) :=\n begin\n split,\n\n unfold prop.erased_n,\n unfold prop.to_vc,\n assume h1,\n have h2, from valid.univ.mpr h1,\n apply valid.univ.mp,\n assume v,\n have h3, from h2 v,\n have h3b: (vc.substt y v (prop.erased_n P₁) = vc.subst y v (prop.erased_n P₁)),\n from vc.substt_value_eq_subst,\n have h3c: ⊨vc.subst y v (prop.erased_n P₁), from h3b ▸ h3,\n have h4: (vc.subst y v (prop.erased_n P₁) = prop.erased_n (prop.subst y v P₁)),\n from subst_distrib_erased.right,\n have h5: ⊨ prop.erased_n (prop.subst y v P₁), from h4 ▸ h3c,\n have h6: (vc.subst y v (prop.to_vc P₁) = prop.to_vc (prop.subst y v P₁)),\n from subst_distrib_to_vc,\n rw[h6],\n show ⊨prop.to_vc (prop.subst y v P₁), from (\n have ht1: P₁.simplesize = (prop.subst y v P₁).simplesize, from same_simplesize_after_subst,\n have ht2: P₁.simplesize < (prop.forallc y P₁).simplesize, from simplesize_prop_forall,\n have rec_wf: (prop.subst y v P₁).simplesize < (prop.forallc y P₁).simplesize, from ht1 ▸ ht2,\n (to_vc_valid_of_erased_n_valid (prop.subst y v P₁)).left h5\n ),\n\n assume h1,\n unfold prop.erased_p,\n from valid.tru\n end\n| (prop.exis y P₁) := begin\n split,\n\n unfold prop.erased_n,\n unfold prop.to_vc,\n assume h1,\n\n have h2, from valid.not.mpr h1,\n apply valid.not.mp,\n\n by_contradiction h3,\n have h4: ⊨vc.univ y (vc.not (prop.erased_n P₁)), by begin\n have h5, from valid.univ.mpr h3,\n apply valid.univ.mp,\n assume v: value,\n have h6, from h5 v,\n have h6b: (vc.substt y v (vc.not (prop.to_vc P₁)) = vc.subst y v (vc.not (prop.to_vc P₁))),\n from vc.substt_value_eq_subst,\n have h6c: ⊨vc.subst y v (vc.not (prop.to_vc P₁)), from h6b ▸ h6,\n have h7: (vc.subst y v (vc.not (prop.to_vc P₁)) = vc.not (vc.subst y v (prop.to_vc P₁))),\n by unfold vc.subst,\n rw[h7] at h6c,\n have h8: (vc.subst y v (vc.not (prop.erased_n P₁)) = vc.not (vc.subst y v (prop.erased_n P₁))),\n by unfold vc.subst,\n rw[h8],\n\n have h9, from valid.not.mpr h6,\n apply valid.not.mp,\n\n by_contradiction h10,\n have h11: ⊨vc.subst y v (prop.to_vc P₁), by begin\n\n have h12: (vc.subst y v (prop.erased_n P₁) = prop.erased_n (prop.subst y v P₁)),\n from subst_distrib_erased.right,\n have h13: ⊨ prop.erased_n (prop.subst y v P₁), from h12 ▸ h10,\n have h14: (vc.subst y v (prop.to_vc P₁) = prop.to_vc (prop.subst y v P₁)),\n from subst_distrib_to_vc,\n rw[h14],\n show ⊨prop.to_vc (prop.subst y v P₁), from (\n have ht1: P₁.simplesize = (prop.subst y v P₁).simplesize, from same_simplesize_after_subst,\n have ht2: P₁.simplesize < (prop.forallc y P₁).simplesize, from simplesize_prop_forall,\n have rec_wf: (prop.subst y v P₁).simplesize < (prop.forallc y P₁).simplesize, from ht1 ▸ ht2,\n (to_vc_valid_of_erased_n_valid (prop.subst y v P₁)).left h13\n )\n end,\n from h9 h11\n end,\n from h2 h4,\n\n unfold prop.erased_p,\n unfold prop.to_vc,\n assume h1,\n\n have h2, from valid.not.mpr h1,\n apply valid.not.mp,\n\n by_contradiction h3,\n have h4: ⊨vc.univ y (vc.not (prop.to_vc P₁)), by begin\n have h5, from valid.univ.mpr h3,\n apply valid.univ.mp,\n assume v: value,\n have h6, from h5 v,\n\n have h7: (vc.subst y v (vc.not (prop.erased_p P₁)) = vc.not (vc.subst y v (prop.erased_p P₁))),\n by unfold vc.subst,\n have h8: (vc.subst y v (vc.not (prop.to_vc P₁)) = vc.not (vc.subst y v (prop.to_vc P₁))),\n by unfold vc.subst,\n rw[h8],\n\n have h9, from valid.not.mpr h6,\n apply valid.not.mp,\n\n by_contradiction h10,\n have h11: ⊨vc.subst y v (prop.erased_p P₁), by begin\n\n have h12: (vc.subst y v (prop.to_vc P₁) = prop.to_vc (prop.subst y v P₁)),\n from subst_distrib_to_vc,\n have h13: ⊨ prop.to_vc (prop.subst y v P₁), from h12 ▸ h10,\n have h14: (vc.subst y v (prop.erased_p P₁) = prop.erased_p (prop.subst y v P₁)),\n from subst_distrib_erased.left,\n rw[h14],\n show ⊨prop.erased_p (prop.subst y v P₁), from (\n have ht1: P₁.simplesize = (prop.subst y v P₁).simplesize, from same_simplesize_after_subst,\n have ht2: P₁.simplesize < (prop.forallc y P₁).simplesize, from simplesize_prop_forall,\n have rec_wf: (prop.subst y v P₁).simplesize < (prop.forallc y P₁).simplesize, from ht1 ▸ ht2,\n (to_vc_valid_of_erased_n_valid (prop.subst y v P₁)).right h13\n )\n end,\n from h9 h11\n end,\n from h2 h4\n end\nusing_well_founded {\n rel_tac := λ _ _, `[exact ⟨_, measure_wf $ λ s, s.simplesize⟩],\n dec_tac := tactic.assumption\n}\n\nlemma and_lifted_p_is_some {P₁ P₂ Q: prop} {x: var}:\n prop.lift_p (prop.and P₁ P₂) x = some Q →\n (∃Q₁: prop, P₁.lift_p x = some Q₁ ∧ (Q = (Q₁ ⋀ P₂))) ∨ (∃Q₂: prop, P₂.lift_p x = some Q₂ ∧ (Q = (P₁ ⋀ Q₂))) :=\n begin\n assume h1,\n unfold prop.lift_p at h1,\n cases (prop.lift_p P₁ x) with Q₁ h2,\n\n unfold prop.lift_p._match_1 at h1,\n have h3, from eq_from_map_result_some h1,\n cases h3 with Q₂ h4,\n right,\n existsi Q₂,\n from h4,\n\n unfold prop.lift_p._match_1 at h1,\n have h2, from option.some.inj h1,\n left,\n existsi Q₁,\n split,\n from rfl,\n from h2.symm\n end\n\nlemma and_lifted_n_is_some {P₁ P₂ Q: prop} {x: var}:\n prop.lift_n (prop.and P₁ P₂) x = some Q →\n (∃Q₁: prop, P₁.lift_n x = some Q₁ ∧ (Q = (Q₁ ⋀ P₂))) ∨ (∃Q₂: prop, P₂.lift_n x = some Q₂ ∧ (Q = (P₁ ⋀ Q₂))) :=\n begin\n assume h1,\n unfold prop.lift_n at h1,\n cases (prop.lift_n P₁ x) with Q₁ h2,\n\n unfold prop.lift_n._match_1 at h1,\n have h3, from eq_from_map_result_some h1,\n cases h3 with Q₂ h4,\n right,\n existsi Q₂,\n from h4,\n\n unfold prop.lift_n._match_1 at h1,\n have h2, from option.some.inj h1,\n left,\n existsi Q₁,\n split,\n from rfl,\n from h2.symm\n end\n\nlemma or_lifted_p_is_some {P₁ P₂ Q: prop} {x: var}:\n prop.lift_p (prop.or P₁ P₂) x = some Q →\n (∃Q₁: prop, P₁.lift_p x = some Q₁ ∧ (Q = (Q₁ ⋁ P₂))) ∨ (∃Q₂: prop, P₂.lift_p x = some Q₂ ∧ (Q = (P₁ ⋁ Q₂))) :=\n begin\n assume h1,\n unfold prop.lift_p at h1,\n cases (prop.lift_p P₁ x) with Q₁ h2,\n\n unfold prop.lift_p._match_2 at h1,\n have h3, from eq_from_map_result_some h1,\n cases h3 with Q₂ h4,\n right,\n existsi Q₂,\n from h4,\n\n unfold prop.lift_p._match_2 at h1,\n have h2, from option.some.inj h1,\n left,\n existsi Q₁,\n split,\n from rfl,\n from h2.symm\n end\n\nlemma or_lifted_n_is_some {P₁ P₂ Q: prop} {x: var}:\n prop.lift_n (prop.or P₁ P₂) x = some Q →\n (∃Q₁: prop, P₁.lift_n x = some Q₁ ∧ (Q = (Q₁ ⋁ P₂))) ∨ (∃Q₂: prop, P₂.lift_n x = some Q₂ ∧ (Q = (P₁ ⋁ Q₂))) :=\n begin\n assume h1,\n unfold prop.lift_n at h1,\n cases (prop.lift_n P₁ x) with Q₁ h2,\n\n unfold prop.lift_n._match_2 at h1,\n have h3, from eq_from_map_result_some h1,\n cases h3 with Q₂ h4,\n right,\n existsi Q₂,\n from h4,\n\n unfold prop.lift_n._match_2 at h1,\n have h2, from option.some.inj h1,\n left,\n existsi Q₁,\n split,\n from rfl,\n from h2.symm\n end\n\nlemma to_vc_valid_of_lifted_to_vc_valid {x: var}:\n ∀P: prop, ∀Q: prop, ¬ prop.uses_var x P →\n (P.lift_p x = some Q → (⊨ Q.to_vc) → ⊨ P.to_vc) ∧\n (P.lift_n x = some Q → (⊨ P.to_vc) → ⊨ Q.to_vc)\n| (prop.term t) := begin\n assume Q,\n assume x_unused,\n split,\n\n assume h1,\n unfold prop.lift_p at h1,\n contradiction,\n\n assume h1,\n unfold prop.lift_n at h1,\n contradiction\n end\n| (prop.not P₁) :=\n have rec_wf: P₁.simplesize < (prop.not P₁).simplesize, from simplesize_prop_not,\n begin\n assume Q,\n assume x_unused,\n\n split,\n\n assume h1,\n unfold prop.lift_p at h1,\n have h2, from eq_from_map_result_some h1,\n cases h2 with Q₂ h3,\n assume h4,\n rw[h3.right] at h4,\n unfold prop.to_vc at h4,\n unfold prop.to_vc,\n apply valid.not.mp,\n have h5, from valid.not.mpr h4,\n by_contradiction h6,\n have h7: ⊨prop.to_vc Q₂, by begin\n have h8: ¬ prop.uses_var x P₁, by begin\n assume h9,\n have h10, from prop.uses_var.not h9,\n from x_unused h10\n end,\n from (to_vc_valid_of_lifted_to_vc_valid P₁ Q₂ h8).right h3.left h6\n end,\n from h5 h7,\n\n assume h1,\n unfold prop.lift_n at h1,\n have h2, from eq_from_map_result_some h1,\n cases h2 with Q₂ h3,\n assume h4,\n rw[h3.right],\n unfold prop.to_vc at h4,\n unfold prop.to_vc,\n apply valid.not.mp,\n have h5, from valid.not.mpr h4,\n by_contradiction h6,\n have h7: ⊨prop.to_vc P₁, by begin\n have h8: ¬ prop.uses_var x P₁, by begin\n assume h9,\n have h10, from prop.uses_var.not h9,\n from x_unused h10\n end,\n from (to_vc_valid_of_lifted_to_vc_valid P₁ Q₂ h8).left h3.left h6\n end,\n from h5 h7\n end\n| (prop.and P₁ P₂) :=\n have rec_1: P₁.simplesize < (prop.and P₁ P₂).simplesize, from simplesize_prop_and₁,\n have rec_2: P₂.simplesize < (prop.and P₁ P₂).simplesize, from simplesize_prop_and₂,\n begin\n assume Q,\n assume x_unused,\n\n split,\n\n assume h1,\n have h2, from and_lifted_p_is_some h1,\n cases h2 with h3 h4,\n cases h3 with Q₁ h4,\n assume h5,\n rw[h4.right] at h5,\n have h6: ⊨prop.to_vc (prop.and Q₁ P₂), from h5,\n unfold prop.to_vc at h6,\n unfold prop.to_vc,\n apply valid.and.mp,\n split,\n have h7, from (valid.and.mpr h6).left,\n have h8: ¬ prop.uses_var x P₁, by begin\n assume h9,\n have h10: prop.uses_var x (prop.and P₁ P₂), from prop.uses_var.and₁ h9,\n from x_unused h10\n end,\n from (to_vc_valid_of_lifted_to_vc_valid P₁ Q₁ h8).left h4.left h7,\n from (valid.and.mpr h6).right,\n\n cases h4 with Q₂ h5,\n assume h6,\n rw[h5.right] at h6,\n have h7: ⊨prop.to_vc (prop.and P₁ Q₂), from h6,\n unfold prop.to_vc at h7,\n have h8, from valid.and.mpr h7,\n unfold prop.to_vc,\n apply valid.and.mp,\n split,\n from h8.left,\n have h9: ¬ prop.uses_var x P₂, by begin\n assume h9,\n have h10: prop.uses_var x (prop.and P₁ P₂), from prop.uses_var.and₂ h9,\n from x_unused h10\n end,\n from (to_vc_valid_of_lifted_to_vc_valid P₂ Q₂ h9).left h5.left h8.right,\n\n assume h1,\n have h2, from and_lifted_n_is_some h1,\n cases h2 with h3 h4,\n cases h3 with Q₁ h4,\n assume h5,\n rw[h4.right],\n unfold prop.to_vc at h5,\n change ⊨prop.to_vc (prop.and Q₁ P₂),\n unfold prop.to_vc,\n apply valid.and.mp,\n split,\n have h7, from (valid.and.mpr h5).left,\n have h8: ¬ prop.uses_var x P₁, by begin\n assume h9,\n have h10: prop.uses_var x (prop.and P₁ P₂), from prop.uses_var.and₁ h9,\n from x_unused h10\n end,\n from (to_vc_valid_of_lifted_to_vc_valid P₁ Q₁ h8).right h4.left h7,\n from (valid.and.mpr h5).right,\n\n cases h4 with Q₂ h5,\n assume h6,\n rw[h5.right],\n change ⊨prop.to_vc (prop.and P₁ Q₂),\n unfold prop.to_vc,\n unfold prop.to_vc at h6,\n have h7, from valid.and.mpr h6,\n apply valid.and.mp,\n split,\n from h7.left,\n have h8: ¬ prop.uses_var x P₂, by begin\n assume h9,\n have h10: prop.uses_var x (prop.and P₁ P₂), from prop.uses_var.and₂ h9,\n from x_unused h10\n end,\n from (to_vc_valid_of_lifted_to_vc_valid P₂ Q₂ h8).right h5.left h7.right\n end\n| (prop.or P₁ P₂) :=\n have rec_1: P₁.simplesize < (prop.or P₁ P₂).simplesize, from simplesize_prop_or₁,\n have rec_2: P₂.simplesize < (prop.or P₁ P₂).simplesize, from simplesize_prop_or₂,\n begin\n assume Q,\n assume x_unused,\n\n split,\n\n assume h1,\n have h2, from or_lifted_p_is_some h1,\n cases h2 with h3 h4,\n cases h3 with Q₁ h4,\n assume h5,\n rw[h4.right] at h5,\n have h6: ⊨prop.to_vc (prop.or Q₁ P₂), from h5,\n unfold prop.to_vc at h6,\n unfold prop.to_vc,\n cases (valid.or.elim h6) with h7 h8,\n\n apply valid.or.left,\n have h8: ¬ prop.uses_var x P₁, by begin\n assume h9,\n have h10: prop.uses_var x (prop.or P₁ P₂), from prop.uses_var.or₁ h9,\n from x_unused h10\n end,\n from (to_vc_valid_of_lifted_to_vc_valid P₁ Q₁ h8).left h4.left h7,\n\n apply valid.or.right,\n from h8,\n\n assume h5,\n unfold prop.to_vc,\n cases h4 with Q₂ h6,\n rw[h6.right] at h5,\n have h7: ⊨prop.to_vc (prop.or P₁ Q₂), from h5,\n unfold prop.to_vc at h7,\n cases (valid.or.elim h7) with h8 h9,\n apply valid.or.left,\n from h8,\n apply valid.or.right,\n have h10: ¬ prop.uses_var x P₂, by begin\n assume h9,\n have h10: prop.uses_var x (prop.or P₁ P₂), from prop.uses_var.or₂ h9,\n from x_unused h10\n end,\n from (to_vc_valid_of_lifted_to_vc_valid P₂ Q₂ h10).left h6.left h9,\n\n assume h1,\n have h2, from or_lifted_n_is_some h1,\n cases h2 with h3 h4,\n cases h3 with Q₁ h4,\n assume h5,\n rw[h4.right],\n change ⊨prop.to_vc (prop.or Q₁ P₂),\n unfold prop.to_vc at h5,\n unfold prop.to_vc,\n cases (valid.or.elim h5) with h7 h8,\n\n apply valid.or.left,\n have h8: ¬ prop.uses_var x P₁, by begin\n assume h9,\n have h10: prop.uses_var x (prop.or P₁ P₂), from prop.uses_var.or₁ h9,\n from x_unused h10\n end,\n from (to_vc_valid_of_lifted_to_vc_valid P₁ Q₁ h8).right h4.left h7,\n\n apply valid.or.right,\n from h8,\n\n assume h5,\n unfold prop.to_vc at h5,\n cases h4 with Q₂ h6,\n rw[h6.right],\n change ⊨prop.to_vc (prop.or P₁ Q₂),\n unfold prop.to_vc,\n cases (valid.or.elim h5) with h8 h9,\n apply valid.or.left,\n from h8,\n apply valid.or.right,\n have h10: ¬ prop.uses_var x P₂, by begin\n assume h9,\n have h10: prop.uses_var x (prop.or P₁ P₂), from prop.uses_var.or₂ h9,\n from x_unused h10\n end,\n from (to_vc_valid_of_lifted_to_vc_valid P₂ Q₂ h10).right h6.left h9\n end\n| (prop.pre t₁ t₂) := begin\n assume Q,\n assume x_unused,\n split,\n\n assume h1,\n unfold prop.lift_p at h1,\n contradiction,\n\n assume h1,\n unfold prop.lift_n at h1,\n contradiction\n end\n| (prop.pre₁ op t) := begin\n assume Q,\n assume x_unused,\n split,\n\n assume h1,\n unfold prop.lift_p at h1,\n contradiction,\n\n assume h1,\n unfold prop.lift_n at h1,\n contradiction\n end\n| (prop.pre₂ op t₁ t₂) := begin\n assume Q,\n assume x_unused,\n split,\n\n assume h1,\n unfold prop.lift_p at h1,\n contradiction,\n\n assume h1,\n unfold prop.lift_n at h1,\n contradiction\n end\n| (prop.call t) := begin\n assume Q,\n assume x_unused,\n split,\n\n assume h1,\n unfold prop.lift_p at h1,\n contradiction,\n\n assume h1,\n unfold prop.lift_n at h1,\n contradiction\n end\n| (prop.post t₁ t₂) := begin\n assume Q,\n assume x_unused,\n split,\n\n assume h1,\n unfold prop.lift_p at h1,\n contradiction,\n\n assume h1,\n unfold prop.lift_n at h1,\n contradiction\n end\n| (prop.forallc y P₁) := begin\n assume Q,\n assume x_unused,\n\n split,\n\n assume h1,\n unfold prop.lift_p at h1,\n have h2, from option.some.inj h1,\n assume h3,\n rw[h2.symm] at h3,\n unfold prop.to_vc at h3,\n cases (valid.or.elim h3) with h4 h5,\n have h5, from valid.not.mpr h4,\n have h6: ⊨vc.term ↑value.true, from valid.tru,\n contradiction,\n\n unfold prop.to_vc,\n apply valid.univ.mp,\n assume v,\n have h6: (vc.substt y x (prop.to_vc P₁) = prop.to_vc (prop.substt y x P₁)),\n from substt_distrib_to_vc,\n rw[←h6] at h5,\n\n by_cases (free_in_vc y P₁.to_vc) with h7,\n\n have h8: ⊨ vc.substt x y (vc.substt y ↑x (prop.to_vc P₁)), from valid.alpha_equiv h5,\n have h9: ¬ vc.uses_var x (prop.to_vc P₁), by begin\n assume h10,\n have h11, from prop_uses_var_of_to_vc_uses_var h10,\n have h12: prop.uses_var x (prop.forallc y P₁), from prop.uses_var.forallc h11,\n contradiction\n end,\n have h10: (vc.substt x y (vc.substt y x (prop.to_vc P₁)) = (prop.to_vc P₁)),\n from vc.substt_var_cancel h9,\n rw[h10] at h8,\n have h11: ⊨ vc.univ y P₁.to_vc, from valid.univ.free ⟨h7, h8⟩,\n have h12: ⊨ vc.substt y v (prop.to_vc P₁),\n from valid.univ.mpr h11 v,\n have h13: (vc.substt y v (prop.to_vc P₁) = vc.subst y v (prop.to_vc P₁)),\n from vc.substt_value_eq_subst,\n rw[h13] at h12,\n from h12,\n\n have h8: (vc.subst y v (prop.to_vc P₁) = (prop.to_vc P₁)),\n from unchanged_of_subst_nonfree_vc h7,\n rw[h8],\n have h9: (vc.substt y x (prop.to_vc P₁) = (prop.to_vc P₁)),\n from unchanged_of_substt_nonfree_vc h7,\n rw[h9] at h5,\n from h5,\n\n assume h1,\n unfold prop.lift_n at h1,\n exfalso,\n from option.no_confusion h1\n end\n| (prop.exis y P₁) := begin\n assume Q,\n assume x_unused,\n\n split,\n\n assume h1,\n unfold prop.lift_p at h1,\n exfalso,\n from option.no_confusion h1,\n\n assume h1,\n unfold prop.lift_n at h1,\n exfalso,\n from option.no_confusion h1,\n end\nusing_well_founded {\n rel_tac := λ _ _, `[exact ⟨_, measure_wf $ λ s, s.simplesize⟩],\n dec_tac := tactic.assumption\n}\n\nlemma to_vc_valid_of_lift_all_to_vc_valid: ∀P:prop, (⊨ P.lift_all.to_vc) → ⊨ P.to_vc\n| P :=\n begin\n assume h1,\n unfold prop.lift_all at h1,\n by_cases (option.is_none_prop (prop.lift_p P (prop.fresh_var P))) with h2,\n\n have h3: (prop.lift_p P (prop.fresh_var P) = none), from option.is_none.inv.mpr h2,\n simp[h3] at h1,\n from h1,\n\n have h3, from option.some_iff_not_none.mpr h2,\n have h4: ∃Q, (prop.lift_p P (prop.fresh_var P) = some Q), from option.is_some_iff_exists.mp h3,\n cases h4 with Q h5,\n simp[h5] at h1,\n show ⊨ prop.to_vc P, from (\n have Q.num_quantifiers < P.num_quantifiers, from (lifted_prop_smaller Q).left h5,\n have h6: ⊨ Q.to_vc, from to_vc_valid_of_lift_all_to_vc_valid Q h1,\n have P.fresh_var ≤ P.fresh_var, from le_refl P.fresh_var,\n have ¬ prop.uses_var (prop.fresh_var P) P, from prop.fresh_var_is_unused P.fresh_var this,\n (to_vc_valid_of_lifted_to_vc_valid P Q this).left h5 h6\n )\n end\nusing_well_founded {\n rel_tac := λ _ _, `[exact ⟨_, measure_wf $ λ s, s.num_quantifiers ⟩],\n dec_tac := tactic.assumption\n}\n\nlemma erased_valid_of_instantiated_with_erased_valid {P: prop} {t: calltrigger}:\n ((⊨ (P.instantiate_with_n t).to_vc) → ⊨ P.to_vc) ∧\n ((⊨ P.to_vc) → ⊨ (P.instantiate_with_p t).to_vc) :=\n begin\n induction P,\n case prop.term t {\n split,\n\n unfold prop.instantiate_with_n,\n from id,\n\n unfold prop.instantiate_with_p,\n from id\n },\n case prop.not P₁ ih {\n split,\n\n unfold prop.instantiate_with_n,\n unfold prop.to_vc,\n assume h1,\n apply valid.not.mp,\n\n by_contradiction,\n\n have h4: ⊨ prop.to_vc (prop.instantiate_with_p P₁ t),\n from ih.right a,\n have h5, from valid.not.mpr h1,\n from h5 h4,\n\n unfold prop.instantiate_with_p,\n unfold prop.to_vc,\n assume h1,\n apply valid.not.mp,\n\n by_contradiction,\n have h2: ⊨ prop.to_vc P₁,\n from ih.left a,\n have h3, from valid.not.mpr h1,\n from h3 h2\n },\n case prop.and P₁ P₂ P₁_ih P₂_ih {\n split,\n\n unfold prop.instantiate_with_n,\n unfold prop.to_vc,\n assume h1,\n have h2: ⊨ prop.to_vc (prop.and (prop.instantiate_with_n P₁ t) (prop.instantiate_with_n P₂ t)), from h1,\n unfold prop.to_vc at h2,\n have h3, from valid.and.mpr h2,\n apply valid.and.mp,\n split,\n show ⊨ prop.to_vc P₁, from P₁_ih.left h3.left,\n show ⊨ prop.to_vc P₂, from P₂_ih.left h3.right,\n\n unfold prop.instantiate_with_p,\n unfold prop.to_vc,\n assume h1,\n have h2, from valid.and.mpr h1,\n change ⊨ prop.to_vc (prop.and (prop.instantiate_with_p P₁ t) (prop.instantiate_with_p P₂ t)),\n unfold prop.to_vc,\n apply valid.and.mp,\n split,\n show ⊨ prop.to_vc (prop.instantiate_with_p P₁ t), from P₁_ih.right h2.left,\n show ⊨ prop.to_vc (prop.instantiate_with_p P₂ t), from P₂_ih.right h2.right\n },\n case prop.or P₁ P₂ P₁_ih P₂_ih {\n split,\n\n unfold prop.instantiate_with_n,\n unfold prop.to_vc,\n assume h1,\n have h2: ⊨ prop.to_vc (prop.or (prop.instantiate_with_n P₁ t) (prop.instantiate_with_n P₂ t)), from h1,\n unfold prop.to_vc at h2,\n cases valid.or.elim h2 with h3 h4,\n\n apply valid.or.left,\n from P₁_ih.left h3,\n\n apply valid.or.right,\n from P₂_ih.left h4,\n\n unfold prop.instantiate_with_p,\n unfold prop.to_vc,\n assume h1,\n change ⊨ prop.to_vc (prop.or (prop.instantiate_with_p P₁ t) (prop.instantiate_with_p P₂ t)),\n unfold prop.to_vc,\n cases valid.or.elim h1 with h3 h4,\n\n apply valid.or.left,\n from P₁_ih.right h3,\n\n apply valid.or.right,\n from P₂_ih.right h4\n },\n case prop.pre t₁ t₂ {\n split,\n\n unfold prop.instantiate_with_n,\n from id,\n\n unfold prop.instantiate_with_p,\n from id\n },\n case prop.pre₁ op t {\n split,\n\n unfold prop.instantiate_with_n,\n from id,\n\n unfold prop.instantiate_with_p,\n from id\n },\n case prop.pre₂ op t₁ t₂ {\n split,\n\n unfold prop.instantiate_with_n,\n from id,\n\n unfold prop.instantiate_with_p,\n from id\n },\n case prop.call t {\n split,\n\n unfold prop.instantiate_with_n,\n from id,\n\n unfold prop.instantiate_with_p,\n from id\n },\n case prop.post t₁ t₂ {\n split,\n\n unfold prop.instantiate_with_n,\n from id,\n\n unfold prop.instantiate_with_p,\n from id\n },\n case prop.forallc y P₁ P₁_ih {\n split,\n\n unfold prop.instantiate_with_n,\n from id,\n\n unfold prop.instantiate_with_p,\n unfold prop.to_vc,\n assume h1,\n change ⊨ prop.to_vc (prop.and (prop.forallc y P₁) (prop.substt y (t.x) P₁)),\n unfold prop.to_vc,\n apply valid.and.mp,\n split,\n from h1,\n\n have h2: (vc.substt y (t.x) (prop.to_vc P₁) = prop.to_vc (prop.substt y (t.x) P₁)),\n from substt_distrib_to_vc,\n rw[←h2],\n from valid.univ.mpr h1 t.x\n },\n case prop.exis y P₁ P₁_ih {\n split,\n\n unfold prop.instantiate_with_n,\n from id,\n\n unfold prop.instantiate_with_p,\n from id\n }\n end\n\nlemma to_vc_valid_of_instantiate_with_all_lifted_to_vc_valid {T: list calltrigger}:\n ∀P: prop, (⊨ (P.instantiate_with_all T).lift_all.to_vc) → ⊨ P.to_vc :=\n begin\n induction T,\n\n case list.nil {\n assume P,\n assume h1,\n unfold prop.instantiate_with_all at h1,\n from to_vc_valid_of_lift_all_to_vc_valid P h1\n },\n\n case list.cons t T ih {\n assume P,\n assume h1,\n unfold prop.instantiate_with_all at h1,\n have h3, from ih (prop.instantiate_with_n P t),\n have h4, from h3 h1,\n from erased_valid_of_instantiated_with_erased_valid.left h4\n }\n end\n\nlemma lifted_all_to_vc_valid_of_instantiate_rep_valid {n: ℕ}:\n ∀P: prop, (⊨ P.instantiate_rep n) → ⊨ P.lift_all.to_vc :=\n begin\n induction n,\n\n case nat.zero {\n assume P,\n assume h1,\n unfold prop.instantiate_rep at h1,\n from (to_vc_valid_of_erased_n_valid (prop.lift_all P)).left h1\n },\n\n case nat.succ n ih {\n assume P,\n unfold prop.instantiate_rep,\n assume h1,\n have h2, from ih (prop.instantiate_with_all (prop.lift_all P) (prop.find_calls_n (prop.lift_all P))) h1,\n from to_vc_valid_of_instantiate_with_all_lifted_to_vc_valid P.lift_all h2\n }\n end\n\n-- inst_n(P) ⇒ inst_p(P)\n-- ⇘ ⇗ \n-- ⇑ P ⇓\n-- ⇗ ⇘ \n-- erased_n(P) ⇒ erased_p(P)\n\nlemma to_vc_valid_of_instantiated_n_valid {P: prop}:\n (⊨ P.instantiated_n) → ⊨ P.to_vc :=\n assume : ⊨ P.instantiated_n,\n have ⊨ P.instantiate_rep P.max_nesting_level, by { unfold prop.instantiated_n at this, from this },\n have ⊨ P.lift_all.to_vc, from lifted_all_to_vc_valid_of_instantiate_rep_valid P this,\n show ⊨ P.to_vc, from to_vc_valid_of_lift_all_to_vc_valid P this\n\nlemma vc_valid_from_inst_valid {P: prop}:\n ⟪ P ⟫ → ⦃ P ⦄ :=\n assume h1: ⟪ P ⟫,\n assume σ: env,\n assume h2: closed_subst σ P,\n have h3: ⊨ (prop.subst_env σ P).instantiated_n, from h1 σ h2,\n have h4: ⊨ (prop.subst_env σ P).to_vc, from to_vc_valid_of_instantiated_n_valid h3,\n have h5: (vc.subst_env σ (prop.to_vc P) = prop.to_vc (prop.subst_env σ P)),\n from subst_env_distrib_to_vc,\n show ⊨ vc.subst_env σ (prop.to_vc P), from h5.symm ▸ h4\n", "meta": {"author": "levjj", "repo": "esverify-theory", "sha": "8565b123c87b0113f83553d7732cd6696c9b5807", "save_path": "github-repos/lean/levjj-esverify-theory", "path": "github-repos/lean/levjj-esverify-theory/esverify-theory-8565b123c87b0113f83553d7732cd6696c9b5807/src/qi.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44939263446475963, "lm_q2_score": 0.031143829073493886, "lm_q1q2_score": 0.013995807394657592}} {"text": "/-\nCopyright (c) 2017 Mario Carneiro. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Mario Carneiro\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.default\nimport Mathlib.tactic.basic\nimport Mathlib.PostPort\n\nuniverses u_1 u_2 u_3 \n\nnamespace Mathlib\n\nnamespace option\n\n\ntheorem coe_def {α : Type u_1} : coe = some := rfl\n\ntheorem some_ne_none {α : Type u_1} (x : α) : some x ≠ none :=\n fun (h : some x = none) => option.no_confusion h\n\n@[simp] theorem get_mem {α : Type u_1} {o : Option α} (h : ↥(is_some o)) : get h ∈ o :=\n option.cases_on o\n (fun (h : ↥(is_some none)) =>\n eq.dcases_on h (fun (a : tt = false) => bool.no_confusion a) (Eq.refl tt) (HEq.refl h))\n (fun (o : α) (h : ↥(is_some (some o))) => idRhs (some o = some o) rfl) h\n\ntheorem get_of_mem {α : Type u_1} {a : α} {o : Option α} (h : ↥(is_some o)) : a ∈ o → get h = a :=\n sorry\n\n@[simp] theorem not_mem_none {α : Type u_1} (a : α) : ¬a ∈ none :=\n fun (h : a ∈ none) => option.no_confusion h\n\n@[simp] theorem some_get {α : Type u_1} {x : Option α} (h : ↥(is_some x)) : some (get h) = x :=\n option.cases_on x\n (fun (h : ↥(is_some none)) =>\n eq.dcases_on h (fun (a : tt = false) => bool.no_confusion a) (Eq.refl tt) (HEq.refl h))\n (fun (x : α) (h : ↥(is_some (some x))) => idRhs (some (get h) = some (get h)) rfl) h\n\n@[simp] theorem get_some {α : Type u_1} (x : α) (h : ↥(is_some (some x))) : get h = x := rfl\n\n@[simp] theorem get_or_else_some {α : Type u_1} (x : α) (y : α) : get_or_else (some x) y = x := rfl\n\n@[simp] theorem get_or_else_coe {α : Type u_1} (x : α) (y : α) : get_or_else (↑x) y = x := rfl\n\ntheorem get_or_else_of_ne_none {α : Type u_1} {x : Option α} (hx : x ≠ none) (y : α) :\n some (get_or_else x y) = x :=\n sorry\n\ntheorem mem_unique {α : Type u_1} {o : Option α} {a : α} {b : α} (ha : a ∈ o) (hb : b ∈ o) :\n a = b :=\n some.inj (Eq.trans (Eq.symm ha) hb)\n\ntheorem some_injective (α : Type u_1) : function.injective some :=\n fun (_x _x_1 : α) => iff.mp some_inj\n\n/-- `option.map f` is injective if `f` is injective. -/\ntheorem map_injective {α : Type u_1} {β : Type u_2} {f : α → β} (Hf : function.injective f) :\n function.injective (option.map f) :=\n sorry\n\ntheorem ext {α : Type u_1} {o₁ : Option α} {o₂ : Option α} :\n (∀ (a : α), a ∈ o₁ ↔ a ∈ o₂) → o₁ = o₂ :=\n sorry\n\ntheorem eq_none_iff_forall_not_mem {α : Type u_1} {o : Option α} : o = none ↔ ∀ (a : α), ¬a ∈ o :=\n sorry\n\n@[simp] theorem none_bind {α : Type u_1} {β : Type u_1} (f : α → Option β) : none >>= f = none :=\n rfl\n\n@[simp] theorem some_bind {α : Type u_1} {β : Type u_1} (a : α) (f : α → Option β) :\n some a >>= f = f a :=\n rfl\n\n@[simp] theorem none_bind' {α : Type u_1} {β : Type u_2} (f : α → Option β) :\n option.bind none f = none :=\n rfl\n\n@[simp] theorem some_bind' {α : Type u_1} {β : Type u_2} (a : α) (f : α → Option β) :\n option.bind (some a) f = f a :=\n rfl\n\n@[simp] theorem bind_some {α : Type u_1} (x : Option α) : x >>= some = x := bind_pure\n\n@[simp] theorem bind_eq_some {α : Type u_1} {β : Type u_1} {x : Option α} {f : α → Option β}\n {b : β} : x >>= f = some b ↔ ∃ (a : α), x = some a ∧ f a = some b :=\n sorry\n\n@[simp] theorem bind_eq_some' {α : Type u_1} {β : Type u_2} {x : Option α} {f : α → Option β}\n {b : β} : option.bind x f = some b ↔ ∃ (a : α), x = some a ∧ f a = some b :=\n sorry\n\n@[simp] theorem bind_eq_none' {α : Type u_1} {β : Type u_2} {o : Option α} {f : α → Option β} :\n option.bind o f = none ↔ ∀ (b : β) (a : α), a ∈ o → ¬b ∈ f a :=\n sorry\n\n@[simp] theorem bind_eq_none {α : Type u_1} {β : Type u_1} {o : Option α} {f : α → Option β} :\n o >>= f = none ↔ ∀ (b : β) (a : α), a ∈ o → ¬b ∈ f a :=\n bind_eq_none'\n\ntheorem bind_comm {α : Type u_1} {β : Type u_2} {γ : Type u_3} {f : α → β → Option γ} (a : Option α)\n (b : Option β) :\n (option.bind a fun (x : α) => option.bind b (f x)) =\n option.bind b fun (y : β) => option.bind a fun (x : α) => f x y :=\n sorry\n\ntheorem bind_assoc {α : Type u_1} {β : Type u_2} {γ : Type u_3} (x : Option α) (f : α → Option β)\n (g : β → Option γ) :\n option.bind (option.bind x f) g = option.bind x fun (y : α) => option.bind (f y) g :=\n option.cases_on x (Eq.refl (option.bind (option.bind none f) g))\n fun (x : α) => Eq.refl (option.bind (option.bind (some x) f) g)\n\ntheorem join_eq_some {α : Type u_1} {x : Option (Option α)} {a : α} :\n join x = some a ↔ x = some (some a) :=\n sorry\n\ntheorem join_ne_none {α : Type u_1} {x : Option (Option α)} :\n join x ≠ none ↔ ∃ (z : α), x = some (some z) :=\n sorry\n\ntheorem join_ne_none' {α : Type u_1} {x : Option (Option α)} :\n ¬join x = none ↔ ∃ (z : α), x = some (some z) :=\n sorry\n\ntheorem bind_id_eq_join {α : Type u_1} {x : Option (Option α)} : x >>= id = join x := sorry\n\ntheorem join_eq_join {α : Type u_1} : mjoin = join := sorry\n\ntheorem bind_eq_bind {α : Type u_1} {β : Type u_1} {f : α → Option β} {x : Option α} :\n x >>= f = option.bind x f :=\n rfl\n\n@[simp] theorem map_eq_map {α : Type u_1} {β : Type u_1} {f : α → β} :\n Functor.map f = option.map f :=\n rfl\n\ntheorem map_none {α : Type u_1} {β : Type u_1} {f : α → β} : f <$> none = none := rfl\n\ntheorem map_some {α : Type u_1} {β : Type u_1} {a : α} {f : α → β} : f <$> some a = some (f a) :=\n rfl\n\n@[simp] theorem map_none' {α : Type u_1} {β : Type u_2} {f : α → β} : option.map f none = none :=\n rfl\n\n@[simp] theorem map_some' {α : Type u_1} {β : Type u_2} {a : α} {f : α → β} :\n option.map f (some a) = some (f a) :=\n rfl\n\ntheorem map_eq_some {α : Type u_1} {β : Type u_1} {x : Option α} {f : α → β} {b : β} :\n f <$> x = some b ↔ ∃ (a : α), x = some a ∧ f a = b :=\n sorry\n\n@[simp] theorem map_eq_some' {α : Type u_1} {β : Type u_2} {x : Option α} {f : α → β} {b : β} :\n option.map f x = some b ↔ ∃ (a : α), x = some a ∧ f a = b :=\n sorry\n\ntheorem map_eq_none {α : Type u_1} {β : Type u_1} {x : Option α} {f : α → β} :\n f <$> x = none ↔ x = none :=\n sorry\n\n@[simp] theorem map_eq_none' {α : Type u_1} {β : Type u_2} {x : Option α} {f : α → β} :\n option.map f x = none ↔ x = none :=\n sorry\n\ntheorem map_congr {α : Type u_1} {β : Type u_2} {f : α → β} {g : α → β} {x : Option α}\n (h : ∀ (a : α), a ∈ x → f a = g a) : option.map f x = option.map g x :=\n sorry\n\n@[simp] theorem map_id' {α : Type u_1} : option.map id = id := map_id\n\n@[simp] theorem map_map {α : Type u_1} {β : Type u_2} {γ : Type u_3} (h : β → γ) (g : α → β)\n (x : Option α) : option.map h (option.map g x) = option.map (h ∘ g) x :=\n sorry\n\ntheorem comp_map {α : Type u_1} {β : Type u_2} {γ : Type u_3} (h : β → γ) (g : α → β)\n (x : Option α) : option.map (h ∘ g) x = option.map h (option.map g x) :=\n Eq.symm (map_map h g x)\n\n@[simp] theorem map_comp_map {α : Type u_1} {β : Type u_2} {γ : Type u_3} (f : α → β) (g : β → γ) :\n option.map g ∘ option.map f = option.map (g ∘ f) :=\n sorry\n\ntheorem mem_map_of_mem {α : Type u_1} {β : Type u_2} {a : α} {x : Option α} (g : α → β)\n (h : a ∈ x) : g a ∈ option.map g x :=\n iff.mpr mem_def (Eq.symm (iff.mp mem_def h) ▸ map_some')\n\ntheorem bind_map_comm {α : Type u_1} {β : Type u_1} {x : Option (Option α)} {f : α → β} :\n x >>= option.map f = option.map (option.map f) x >>= id :=\n sorry\n\ntheorem join_map_eq_map_join {α : Type u_1} {β : Type u_2} {f : α → β} {x : Option (Option α)} :\n join (option.map (option.map f) x) = option.map f (join x) :=\n sorry\n\ntheorem join_join {α : Type u_1} {x : Option (Option (Option α))} :\n join (join x) = join (option.map join x) :=\n sorry\n\ntheorem mem_of_mem_join {α : Type u_1} {a : α} {x : Option (Option α)} (h : a ∈ join x) :\n some a ∈ x :=\n iff.mpr mem_def (Eq.symm (iff.mp mem_def h) ▸ iff.mp join_eq_some h)\n\n@[simp] theorem pbind_eq_bind {α : Type u_1} {β : Type u_2} (f : α → Option β) (x : Option α) :\n (pbind x fun (a : α) (_x : a ∈ x) => f a) = option.bind x f :=\n sorry\n\ntheorem map_bind {α : Type u_1} {β : Type u_1} {γ : Type u_1} (f : β → γ) (x : Option α)\n (g : α → Option β) :\n option.map f (x >>= g) =\n do \n let a ← x \n option.map f (g a) :=\n sorry\n\ntheorem map_bind' {α : Type u_1} {β : Type u_2} {γ : Type u_3} (f : β → γ) (x : Option α)\n (g : α → Option β) :\n option.map f (option.bind x g) = option.bind x fun (a : α) => option.map f (g a) :=\n sorry\n\ntheorem map_pbind {α : Type u_1} {β : Type u_2} {γ : Type u_3} (f : β → γ) (x : Option α)\n (g : (a : α) → a ∈ x → Option β) :\n option.map f (pbind x g) = pbind x fun (a : α) (H : a ∈ x) => option.map f (g a H) :=\n sorry\n\ntheorem pbind_map {α : Type u_1} {β : Type u_2} {γ : Type u_3} (f : α → β) (x : Option α)\n (g : (b : β) → b ∈ option.map f x → Option γ) :\n pbind (option.map f x) g = pbind x fun (a : α) (h : a ∈ x) => g (f a) (mem_map_of_mem f h) :=\n option.cases_on x\n (fun (g : (b : β) → b ∈ option.map f none → Option γ) => Eq.refl (pbind (option.map f none) g))\n (fun (x : α) (g : (b : β) → b ∈ option.map f (some x) → Option γ) =>\n Eq.refl (pbind (option.map f (some x)) g))\n g\n\n@[simp] theorem pmap_none {α : Type u_1} {β : Type u_2} {p : α → Prop} (f : (a : α) → p a → β)\n {H : ∀ (a : α), a ∈ none → p a} : pmap f none H = none :=\n rfl\n\n@[simp] theorem pmap_some {α : Type u_1} {β : Type u_2} {p : α → Prop} (f : (a : α) → p a → β)\n {x : α} (h : p x) : pmap f (some x) = fun (_x : ∀ (a : α), a ∈ some x → p a) => some (f x h) :=\n rfl\n\ntheorem mem_pmem {α : Type u_1} {β : Type u_2} {p : α → Prop} (f : (a : α) → p a → β) (x : Option α)\n {a : α} (h : ∀ (a : α), a ∈ x → p a) (ha : a ∈ x) : f a (h a ha) ∈ pmap f x h :=\n eq.mpr (id (Eq._oldrec (Eq.refl (f a (h a ha) ∈ pmap f x h)) (propext mem_def)))\n (Eq._oldrec\n (fun (h : ∀ (a_1 : α), a_1 ∈ some a → p a_1) (ha : a ∈ some a) => Eq.refl (pmap f (some a) h))\n (Eq.symm (eq.mp (Eq._oldrec (Eq.refl (a ∈ x)) (propext mem_def)) ha)) h ha)\n\ntheorem pmap_map {α : Type u_1} {β : Type u_2} {γ : Type u_3} {p : α → Prop} (f : (a : α) → p a → β)\n (g : γ → α) (x : Option γ) (H : ∀ (a : α), a ∈ option.map g x → p a) :\n pmap f (option.map g x) H =\n pmap (fun (a : γ) (h : p (g a)) => f (g a) h) x\n fun (a : γ) (h : a ∈ x) => H (g a) (mem_map_of_mem g h) :=\n sorry\n\ntheorem map_pmap {α : Type u_1} {β : Type u_2} {γ : Type u_3} {p : α → Prop} (g : β → γ)\n (f : (a : α) → p a → β) (x : Option α) (H : ∀ (a : α), a ∈ x → p a) :\n option.map g (pmap f x H) = pmap (fun (a : α) (h : p a) => g (f a h)) x H :=\n sorry\n\n@[simp] theorem pmap_eq_map {α : Type u_1} {β : Type u_2} (p : α → Prop) (f : α → β) (x : Option α)\n (H : ∀ (a : α), a ∈ x → p a) : pmap (fun (a : α) (_x : p a) => f a) x H = option.map f x :=\n sorry\n\ntheorem pmap_bind {α : Type u_1} {β : Type u_1} {γ : Type u_1} {x : Option α} {g : α → Option β}\n {p : β → Prop} {f : (b : β) → p b → γ} (H : ∀ (a : β), a ∈ x >>= g → p a)\n (H' : ∀ (a : α) (b : β), b ∈ g a → b ∈ x >>= g) :\n pmap f (x >>= g) H =\n do \n let a ← x \n pmap f (g a) fun (b : β) (h : b ∈ g a) => H b (H' a b h) :=\n sorry\n\ntheorem bind_pmap {α : Type u_1} {β : Type u_2} {γ : Type u_2} {p : α → Prop}\n (f : (a : α) → p a → β) (x : Option α) (g : β → Option γ) (H : ∀ (a : α), a ∈ x → p a) :\n pmap f x H >>= g = pbind x fun (a : α) (h : a ∈ x) => g (f a (H a h)) :=\n sorry\n\ntheorem pbind_eq_none {α : Type u_1} {β : Type u_2} {x : Option α} {f : (a : α) → a ∈ x → Option β}\n (h' : ∀ (a : α) (H : a ∈ x), f a H = none → x = none) : pbind x f = none ↔ x = none :=\n sorry\n\ntheorem pbind_eq_some {α : Type u_1} {β : Type u_2} {x : Option α} {f : (a : α) → a ∈ x → Option β}\n {y : β} : pbind x f = some y ↔ ∃ (z : α), ∃ (H : z ∈ x), f z H = some y :=\n sorry\n\n@[simp] theorem pmap_eq_none_iff {α : Type u_1} {β : Type u_2} {p : α → Prop}\n {f : (a : α) → p a → β} {x : Option α} {h : ∀ (a : α), a ∈ x → p a} :\n pmap f x h = none ↔ x = none :=\n sorry\n\n@[simp] theorem pmap_eq_some_iff {α : Type u_1} {β : Type u_2} {p : α → Prop}\n {f : (a : α) → p a → β} {x : Option α} {hf : ∀ (a : α), a ∈ x → p a} {y : β} :\n pmap f x hf = some y ↔ ∃ (a : α), ∃ (H : x = some a), f a (hf a H) = y :=\n sorry\n\n@[simp] theorem join_pmap_eq_pmap_join {α : Type u_1} {β : Type u_2} {p : α → Prop}\n {f : (a : α) → p a → β} {x : Option (Option α)}\n (H : ∀ (a : Option α), a ∈ x → ∀ (a_1 : α), a_1 ∈ a → p a_1) :\n join (pmap (pmap f) x H) =\n pmap f (join x) fun (a : α) (h : a ∈ join x) => H (some a) (mem_of_mem_join h) a rfl :=\n sorry\n\n@[simp] theorem seq_some {α : Type u_1} {β : Type u_1} {a : α} {f : α → β} :\n some f <*> some a = some (f a) :=\n rfl\n\n@[simp] theorem some_orelse' {α : Type u_1} (a : α) (x : Option α) :\n option.orelse (some a) x = some a :=\n rfl\n\n@[simp] theorem some_orelse {α : Type u_1} (a : α) (x : Option α) : (some a <|> x) = some a := rfl\n\n@[simp] theorem none_orelse' {α : Type u_1} (x : Option α) : option.orelse none x = x :=\n option.cases_on x (Eq.refl (option.orelse none none))\n fun (x : α) => Eq.refl (option.orelse none (some x))\n\n@[simp] theorem none_orelse {α : Type u_1} (x : Option α) : (none <|> x) = x := none_orelse' x\n\n@[simp] theorem orelse_none' {α : Type u_1} (x : Option α) : option.orelse x none = x :=\n option.cases_on x (Eq.refl (option.orelse none none))\n fun (x : α) => Eq.refl (option.orelse (some x) none)\n\n@[simp] theorem orelse_none {α : Type u_1} (x : Option α) : (x <|> none) = x := orelse_none' x\n\n@[simp] theorem is_some_none {α : Type u_1} : is_some none = false := rfl\n\n@[simp] theorem is_some_some {α : Type u_1} {a : α} : is_some (some a) = tt := rfl\n\ntheorem is_some_iff_exists {α : Type u_1} {x : Option α} : ↥(is_some x) ↔ ∃ (a : α), x = some a :=\n sorry\n\n@[simp] theorem is_none_none {α : Type u_1} : is_none none = tt := rfl\n\n@[simp] theorem is_none_some {α : Type u_1} {a : α} : is_none (some a) = false := rfl\n\n@[simp] theorem not_is_some {α : Type u_1} {a : Option α} : is_some a = false ↔ is_none a = tt :=\n sorry\n\ntheorem eq_some_iff_get_eq {α : Type u_1} {o : Option α} {a : α} :\n o = some a ↔ ∃ (h : ↥(is_some o)), get h = a :=\n sorry\n\ntheorem not_is_some_iff_eq_none {α : Type u_1} {o : Option α} : ¬↥(is_some o) ↔ o = none := sorry\n\ntheorem ne_none_iff_is_some {α : Type u_1} {o : Option α} : o ≠ none ↔ ↥(is_some o) := sorry\n\ntheorem ne_none_iff_exists {α : Type u_1} {o : Option α} : o ≠ none ↔ ∃ (x : α), some x = o := sorry\n\ntheorem ne_none_iff_exists' {α : Type u_1} {o : Option α} : o ≠ none ↔ ∃ (x : α), o = some x :=\n iff.trans ne_none_iff_exists (exists_congr fun (_x : α) => eq_comm)\n\ntheorem bex_ne_none {α : Type u_1} {p : Option α → Prop} :\n (∃ (x : Option α), ∃ (H : x ≠ none), p x) ↔ ∃ (x : α), p (some x) :=\n sorry\n\ntheorem ball_ne_none {α : Type u_1} {p : Option α → Prop} :\n (∀ (x : Option α), x ≠ none → p x) ↔ ∀ (x : α), p (some x) :=\n sorry\n\ntheorem iget_mem {α : Type u_1} [Inhabited α] {o : Option α} : ↥(is_some o) → iget o ∈ o := sorry\n\ntheorem iget_of_mem {α : Type u_1} [Inhabited α] {a : α} {o : Option α} : a ∈ o → iget o = a :=\n sorry\n\n@[simp] theorem guard_eq_some {α : Type u_1} {p : α → Prop} [decidable_pred p] {a : α} {b : α} :\n guard p a = some b ↔ a = b ∧ p a :=\n sorry\n\n@[simp] theorem guard_eq_some' {p : Prop} [Decidable p] (u : Unit) : guard p = some u ↔ p := sorry\n\ntheorem lift_or_get_choice {α : Type u_1} {f : α → α → α} (h : ∀ (a b : α), f a b = a ∨ f a b = b)\n (o₁ : Option α) (o₂ : Option α) : lift_or_get f o₁ o₂ = o₁ ∨ lift_or_get f o₁ o₂ = o₂ :=\n sorry\n\n@[simp] theorem lift_or_get_none_left {α : Type u_1} {f : α → α → α} {b : Option α} :\n lift_or_get f none b = b :=\n option.cases_on b (Eq.refl (lift_or_get f none none))\n fun (b : α) => Eq.refl (lift_or_get f none (some b))\n\n@[simp] theorem lift_or_get_none_right {α : Type u_1} {f : α → α → α} {a : Option α} :\n lift_or_get f a none = a :=\n option.cases_on a (Eq.refl (lift_or_get f none none))\n fun (a : α) => Eq.refl (lift_or_get f (some a) none)\n\n@[simp] theorem lift_or_get_some_some {α : Type u_1} {f : α → α → α} {a : α} {b : α} :\n lift_or_get f (some a) (some b) = ↑(f a b) :=\n rfl\n\n/-- given an element of `a : option α`, a default element `b : β` and a function `α → β`, apply this\nfunction to `a` if it comes from `α`, and return `b` otherwise. -/\ndef cases_on' {α : Type u_1} {β : Type u_2} : Option α → β → (α → β) → β := sorry\n\n@[simp] theorem cases_on'_none {α : Type u_1} {β : Type u_2} (x : β) (f : α → β) :\n cases_on' none x f = x :=\n rfl\n\n@[simp] theorem cases_on'_some {α : Type u_1} {β : Type u_2} (x : β) (f : α → β) (a : α) :\n cases_on' (some a) x f = f a :=\n rfl\n\n@[simp] theorem cases_on'_coe {α : Type u_1} {β : Type u_2} (x : β) (f : α → β) (a : α) :\n cases_on' (↑a) x f = f a :=\n rfl\n\n@[simp] theorem cases_on'_none_coe {α : Type u_1} {β : Type u_2} (f : Option α → β) (o : Option α) :\n cases_on' o (f none) (f ∘ coe) = f o :=\n option.cases_on o (Eq.refl (cases_on' none (f none) (f ∘ coe)))\n fun (o : α) => Eq.refl (cases_on' (some o) (f none) (f ∘ coe))\n\nend Mathlib", "meta": {"author": "AurelienSaue", "repo": "Mathlib4_auto", "sha": "590df64109b08190abe22358fabc3eae000943f2", "save_path": "github-repos/lean/AurelienSaue-Mathlib4_auto", "path": "github-repos/lean/AurelienSaue-Mathlib4_auto/Mathlib4_auto-590df64109b08190abe22358fabc3eae000943f2/Mathlib/data/option/basic_auto.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3557749071749625, "lm_q2_score": 0.03904829650044906, "lm_q1q2_score": 0.013892404062787678}} {"text": "\nimport unitb.models.nondet\n\nimport util.data.option\nimport util.data.sum\nimport util.predicate\n\nimport tactic.finish\n\nuniverse variables u v\n\nopen nat predicate\n\nsection\n\nparameters (σ : Type) (lbl : Type)\n\n@[reducible]\ndef pred := σ → Prop\n\nparameters {σ}\n\ninductive code : pred → pred → Type\n | skip {} : ∀ p, code p p\n | action : ∀ p q, set lbl → lbl → code p q\n | seq : ∀ {p q r}, code p q → code q r → code p r\n | if_then_else : ∀ p {pa pb q}, set lbl → pred → code pa q → code pb q → code p q\n | while : ∀ {p inv} q, set lbl → pred → code p inv → code inv q\n\nparameters {σ lbl}\n\n@[pattern,reducible]\ndef if_then_else : ∀ p {pa pb q}, set lbl → pred → code pa q → code pb q → code p q :=\ncode.if_then_else\n\n@[pattern,reducible]\ndef while : ∀ {p inv} q, set lbl → pred → code p inv → code inv q :=\n@code.while\n\ninductive current : ∀ {p q}, code p q → Type\n | action : ∀ p q s l, current (code.action p q s l)\n | seq_left : ∀ p q r (c₀ : code p q) (c₁ : code q r), current c₀ → current (code.seq c₀ c₁)\n | seq_right : ∀ p q r (c₀ : code p q) (c₁ : code q r), current c₁ → current (code.seq c₀ c₁)\n | ite_cond : ∀ p t pa pb q s (c₀ : code pa q) (c₁ : code pb q),\n current (code.if_then_else p s t c₀ c₁)\n | ite_left : ∀ p t pa pb q s (c₀ : code pa q) (c₁ : code pb q),\n current c₀ → current (code.if_then_else p s t c₀ c₁)\n | ite_right : ∀ p t pa pb q s (c₀ : code pa q) (c₁ : code pb q),\n current c₁ → current (code.if_then_else p s t c₀ c₁)\n | while_cond : ∀ p inv q s w (c : code p inv),\n current (code.while q s w c)\n | while_body : ∀ p inv q s w (c : code p inv),\n current c → current (code.while q s w c)\n\n@[reducible]\ndef seq_left {p q r} {c₀ : code p q} (c₁ : code q r)\n (cur : current c₀)\n: current (code.seq c₀ c₁) :=\ncurrent.seq_left _ _ _ c₀ _ cur\n\n@[reducible]\ndef seq_right {p q r} (c₀ : code p q) {c₁ : code q r}\n (cur : current c₁)\n: current (code.seq c₀ c₁) :=\ncurrent.seq_right _ _ _ c₀ _ cur\n\n@[reducible]\ndef ite_cond (p t) {pa pb q} (s : set lbl) (c₀ : code pa q) (c₁ : code pb q)\n: current (if_then_else p s t c₀ c₁) :=\ncurrent.ite_cond p t _ _ _ s c₀ c₁\n\n@[reducible]\ndef ite_left (p t) {pa pb q} (s : set lbl) {c₀ : code pa q} (c₁ : code pb q) (cur₀ : current c₀)\n: current (if_then_else p s t c₀ c₁) :=\ncurrent.ite_left p t _ _ _ s c₀ c₁ cur₀\n\n@[reducible]\ndef ite_right (p t : pred) {pa pb q : pred} (s : set lbl)\n (c₀ : code pa q) {c₁ : code pb q}\n (cur₁ : current c₁)\n: current (if_then_else p s t c₀ c₁) :=\ncurrent.ite_right p t _ _ _ s c₀ c₁ cur₁\n\n@[reducible]\ndef while_cond {p inv} (q s w) (c : code p inv)\n: current (code.while q s w c) :=\ncurrent.while_cond p inv q s w c\n\n@[reducible]\ndef while_body {p inv} (q s w) {c : code p inv}\n (cur : current c)\n: current (code.while q s w c) :=\ncurrent.while_body p inv q s w c cur\n\ndef selects' : Π {p q} {c : code p q}, current c → lbl → Prop\n | ._ ._ ._ (current.action _ _ _ e') e := e = e'\n | ._ ._ ._ (current.seq_left _ _ _ s c p) e := selects' p e\n | ._ ._ ._ (current.seq_right _ _ _ _ _ p) e := selects' p e\n | ._ ._ ._ (current.ite_cond _ _ _ _ _ _ _ _) e := false\n | ._ ._ ._ (current.ite_left _ _ _ _ _ _ _ _ p) e := selects' p e\n | ._ ._ ._ (current.ite_right _ _ _ _ _ _ _ _ p) e := selects' p e\n | ._ ._ ._ (current.while_cond _ _ _ _ _ _) e := false\n | .(inv) .(q) ._ (current.while_body p inv q _ _ _ pc) e := selects' pc e\n\ndef selects {p q} {c : code p q} : option (current c) → lbl → Prop\n | (some c) := selects' c\n | none := False\n\ndef is_control' : Π {p q} {c : code p q}, current c → bool\n | ._ ._ ._ (current.action _ _ _ l) := ff\n | ._ ._ ._ (current.seq_left p q r _ _ pc) := is_control' pc\n | ._ ._ ._ (current.seq_right p q r _ _ pc) := is_control' pc\n | .(p) .(q) ._ (current.ite_cond p t pa pb q _ _ _) := tt\n | ._ ._ ._ (current.ite_left p t _ _ _ _ _ _ pc) := is_control' pc\n | ._ ._ ._ (current.ite_right p t _ _ _ _ _ _ pc) := is_control' pc\n | .(inv) .(q) ._ (current.while_cond p inv q _ t _) := tt\n | ._ ._ ._ (current.while_body _ _ _ _ _ _ pc) := is_control' pc\n\ndef is_control {p q} {c : code p q} : option (current c) → bool\n | (some pc) := is_control' pc\n | none := ff\n\n-- def control {p q} (c : code p q) := subtype (@is_control _ _ c)\n\n-- instance is_control_decidable\n-- : ∀ {p q} {c : code p q} (cur : current c), decidable (is_control cur)\n-- | ._ ._ ._ (current.action _ _ _) := decidable.false\n-- | ._ ._ ._ (current.seq_left p q r c₀ c₁ cur) := is_control_decidable cur\n-- | ._ ._ ._ (current.seq_right p q r c₀ c₁ cur) := is_control_decidable cur\n-- | ._ ._ ._ (current.ite_cond p t pa pb q c₀ c₁) := decidable.true\n-- | ._ ._ ._ (current.ite_left p t pa pb q c₀ c₁ cur) := is_control_decidable cur\n-- | ._ ._ ._ (current.ite_right p t pa pb q c₀ c₁ cur) := is_control_decidable cur\n-- | ._ ._ ._ (current.while_cond p t inv q c) := decidable.true\n-- | ._ ._ ._ (current.while_body p t inv q c cur) := is_control_decidable cur\n\ndef condition' : Π {p q} {c : code p q} (pc : current c), is_control' pc → σ → Prop\n | ._ ._ ._ (current.action _ _ _ _) h := by cases h\n | ._ ._ ._ (current.seq_left p q r c₀ c₁ pc) h := condition' pc h\n | ._ ._ ._ (current.seq_right p q r c₀ c₁ pc) h := condition' pc h\n | .(p) .(q) ._ (current.ite_cond p c pa pb q _ c₀ c₁) h := c\n | .(p) .(q) ._ (current.ite_left p c pa pb q _ c₀ c₁ pc) h := condition' pc h\n | .(p) .(q) ._ (current.ite_right p c pa pb q _ c₀ c₁ pc) h := condition' pc h\n | .(inv) .(q) ._ (current.while_cond p inv q _ c _) h := c\n | .(inv) .(q) ._ (current.while_body p inv q _ _ _ pc) h := condition' pc h\n\ndef condition {p q} {c : code p q} : ∀ pc : option $ current c, is_control pc → σ → Prop\n | (some pc) := condition' pc\n | none := assume h, by cases h\n\ndef action_of : Π {p q} {c : code p q} (cur : current c),\n{ p // ∃ P, condition (some cur) P = p } ⊕ subtype (selects (some cur))\n | ._ ._ ._ (current.action _ _ _ l) := sum.inr ⟨l,rfl⟩\n | ._ ._ ._ (current.seq_left p q r _ _ pc) := action_of pc\n | ._ ._ ._ (current.seq_right p q r _ _ pc) := action_of pc\n | .(p) .(q) ._ (current.ite_cond p t pa pb q _ _ _) := sum.inl ⟨t,rfl,rfl⟩\n | ._ ._ ._ (current.ite_left p t _ _ _ _ _ _ pc) := action_of pc\n | ._ ._ ._ (current.ite_right p t _ _ _ _ _ _ pc) := action_of pc\n | .(inv) .(q) ._ (current.while_cond p inv q _ t _) := sum.inl ⟨t,rfl,rfl⟩\n | ._ ._ ._ (current.while_body _ _ _ _ _ _ pc) := action_of pc\n\ndef assert_of' : Π {p q} {c : code p q}, current c → σ → Prop\n | .(p) ._ ._ (current.action p _ _ _) := p\n | ._ ._ ._ (current.seq_left _ _ _ _ _ pc) := assert_of' pc\n | ._ ._ ._ (current.seq_right _ _ _ _ _ pc) := assert_of' pc\n | .(p) ._ ._ (current.ite_cond p _ _ _ _ _ _ _) := p\n | ._ ._ ._ (current.ite_left _ _ _ _ _ _ _ _ pc) := assert_of' pc\n | ._ ._ ._ (current.ite_right _ _ _ _ _ _ _ _ pc) := assert_of' pc\n | .(inv) .(q) ._ (current.while_cond p inv q _ _ _) := inv\n | ._ ._ ._ (current.while_body _ _ _ _ _ _ pc) := assert_of' pc\n\ndef assert_of {p q} {c : code p q} : option (current c) → σ → Prop\n | none := q\n | (some pc) := assert_of' pc\n\nlocal attribute [instance] classical.prop_decidable\n\nnoncomputable def next_assert' : Π {p q} {c : code p q}, current c → σ → σ → Prop\n | ._ .(q) ._ (current.action _ q _ _) := λ _, q\n | ._ ._ ._ (current.seq_left _ _ _ _ _ pc) := next_assert' pc\n | ._ ._ ._ (current.seq_right _ _ _ _ _ pc) := next_assert' pc\n | .(p) .(q) ._ (current.ite_cond p t pa pb q _ _ _) := λ s, if t s then pa else pb\n | ._ ._ ._ (current.ite_left _ _ _ _ _ _ _ _ pc) := next_assert' pc\n | ._ ._ ._ (current.ite_right _ _ _ _ _ _ _ _ pc) := next_assert' pc\n | .(inv) .(q) ._ (current.while_cond p inv q _ t _) := λ s, if t s then p else q\n | ._ ._ ._ (current.while_body _ _ _ _ _ _ pc) := next_assert' pc\n\nnoncomputable def next_assert {p q} {c : code p q} : option (current c) → σ → σ → Prop\n | none := λ _, q\n | (some pc) := next_assert' pc\n\ndef first : Π {p q} (c : code p q), option (current c)\n | ._ ._ (code.skip p) := none\n | ._ ._ (code.action p _ _ l) := some $ current.action _ _ _ _\n | .(p) .(r) (@code.seq ._ ._ p q r c₀ c₁) :=\n seq_left c₁ <$> first _\n <|> seq_right _ <$> first _\n | ._ ._ (@if_then_else ._ ._ p _ _ _ _ c b₀ b₁) :=\n some $ ite_cond _ _ _ _ _\n | ._ ._ (@code.while ._ ._ _ _ _ _ c b) :=\n some $ while_cond _ _ _ _\n\nnoncomputable def next' (s : σ) : ∀ {p q} {c : code p q}, current c → option (current c)\n | ._ ._ ._ (current.action p q _ l) := none\n | ._ ._ ._ (current.seq_left _ _ _ c₀ c₁ cur₀) :=\n seq_left c₁ <$> next' cur₀\n <|> seq_right c₀ <$> first c₁\n | ._ ._ ._ (current.seq_right _ _ _ c₀ c₁ cur₁) :=\n seq_right _ <$> next' cur₁\n | .(p) .(q) ._ (current.ite_cond p c pa pb q _ b₀ b₁) :=\n if c s\n then ite_left _ _ _ _ <$> first b₀\n else ite_right _ _ _ _ <$> first b₁\n | ._ ._ ._ (current.ite_left _ _ _ _ _ _ b₀ b₁ cur₀) :=\n ite_left _ _ _ b₁ <$> next' cur₀\n | ._ ._ ._ (current.ite_right _ _ _ _ _ _ b₀ b₁ cur₁) :=\n ite_right _ _ _ _ <$> next' cur₁\n | .(inv) .(q) ._ (current.while_cond p inv q ds c b) :=\n if c s\n then while_body q ds c <$> first b <|> some (while_cond _ ds _ b)\n else none\n | ._ ._ ._ (current.while_body _ _ q _ c b cur) :=\n while_body q _ c <$> next' cur\n <|> some (while_cond _ _ _ b)\n\nnoncomputable def next (s : σ) {p q : pred} {c : code p q}\n: option (current c) → option (current c)\n | (some pc) := next' s pc\n | none := none\n\ninductive subtree {p q : pred} (c : code p q) : ∀ {p' q' : pred}, code p' q' → Type\n | rfl {} : subtree c\n | seq_left : ∀ (p' q' r) (c₀ : code p' q') (c₁ : code q' r),\n subtree c₀ →\n subtree (code.seq c₀ c₁)\n | seq_right : ∀ (p' q' r) (c₀ : code p' q') (c₁ : code q' r),\n subtree c₁ →\n subtree (code.seq c₀ c₁)\n | ite_left : ∀ (ds t p' pa pb q') (c₀ : code pa q') (c₁ : code pb q'),\n subtree c₀ →\n subtree (code.if_then_else p' ds t c₀ c₁)\n | ite_right : ∀ (ds t p' pa pb q') (c₀ : code pa q') (c₁ : code pb q'),\n subtree c₁ →\n subtree (code.if_then_else p' ds t c₀ c₁)\n | while : ∀ (ds t p' q' inv) (c' : code q' inv),\n subtree c' →\n subtree (code.while p' ds t c')\n\nset_option eqn_compiler.lemmas false\ndef within' {p q : pred} {c : code p q}\n: ∀ {p' q'} {c' : code p' q'} (P : subtree c c') (pc : current c'), bool\n | ._ ._ ._ subtree.rfl pc := tt\n | ._ ._ ._ (subtree.seq_left p' q' r' c₀ c₁ P)\n (current.seq_left ._ ._ ._ ._ ._ pc) := within' P pc\n | ._ ._ ._ (subtree.seq_left p' q' r' c₀ c₁ P)\n (current.seq_right ._ ._ ._ ._ ._ pc) := ff\n | ._ ._ ._ (subtree.seq_right p' q' r' c₀ c₁ P)\n (current.seq_left ._ ._ ._ ._ ._ pc) := ff\n | ._ ._ ._ (subtree.seq_right p' q' r' c₀ c₁ P)\n (current.seq_right ._ ._ ._ ._ ._ pc) := within' P pc\n | ._ ._ ._ (subtree.ite_left ds t p' pa pb q' c₀ c₁ P)\n (current.ite_left ._ ._ ._ ._ ._ ._ ._ ._ pc) := within' P pc\n | ._ ._ ._ (subtree.ite_left ds t p' pa pb q' c₀ c₁ P)\n (current.ite_right ._ ._ ._ ._ ._ ._ ._ ._ pc) := ff\n | ._ ._ ._ (subtree.ite_left ds t p' pa pb q' c₀ c₁ P)\n (current.ite_cond ._ ._ ._ ._ ._ ._ ._ ._) := ff\n | ._ ._ ._ (subtree.ite_right ds t p' pa pb q' c₀ c₁ P)\n (current.ite_left ._ ._ ._ ._ ._ ._ ._ ._ pc) := ff\n | ._ ._ ._ (subtree.ite_right ds t p' pa pb q' c₀ c₁ P)\n (current.ite_right ._ ._ ._ ._ ._ ._ ._ ._ pc) := within' P pc\n | ._ ._ ._ (subtree.ite_right ds t p' pa pb q' c₀ c₁ P)\n (current.ite_cond ._ ._ ._ ._ ._ ._ ._ ._) := ff\n | ._ ._ ._ (subtree.while ds t p' q' inv c' P)\n (current.while_body ._ ._ ._ ._ ._ ._ pc) := within' P pc\n | ._ ._ ._ (subtree.while ds t p' q' inv c' P)\n (current.while_cond .(q') .(inv) .(p') .(ds) .(t) .(c')) := ff\n\ndef exit' {p q : pred} {c : code p q}\n: ∀ {p' q'} {c' : code p' q'} (P : subtree c c'), option (current c')\n | ._ ._ ._ subtree.rfl := none\n | ._ ._ ._ (subtree.seq_left p' q' r' c₀ c₁ P) :=\n (seq_left c₁ <$> exit' P)\n <|> (seq_right c₀ <$> first c₁)\n | ._ ._ ._ (subtree.seq_right p' q' r' c₀ c₁ P) :=\n seq_right c₀ <$> exit' P\n | ._ ._ ._ (subtree.ite_left ds t p' pa pb q' c₀ c₁ P) :=\n ite_left p' t ds c₁ <$> exit' P\n | ._ ._ ._ (subtree.ite_right ds t p' pa pb q' c₀ c₁ P) :=\n ite_right p' t ds c₀ <$> exit' P\n | ._ ._ ._ (subtree.while ds t p' q' inv c' P) :=\n ( while_body _ ds _ <$> exit' P\n <|> some (current.while_cond _ _ _ _ _ _))\nset_option eqn_compiler.lemmas true\n\n@[simp]\nlemma exit'_rfl\n: ∀ {p' q'} {c' : code p' q'}, exit' (subtree.rfl : subtree c' c') = none :=\nby { intros, cases c' ; refl }\n\n@[simp]\nlemma exit'_seq_left {p' q' p q r : pred}\n {c : code p' q'} {c₀ : code p q} {c₁ : code q r}\n {P : subtree c c₀ }\n: exit' (subtree.seq_left p q r c₀ c₁ P) =\n ( (seq_left c₁ <$> exit' P)\n <|> (seq_right c₀ <$> first c₁) ) :=\nby refl\n\n@[simp]\nlemma exit'_seq_right {p' q' p q r : pred}\n {c : code p' q'} {c₀ : code p q} {c₁ : code q r}\n {P : subtree c c₁ }\n: exit' (subtree.seq_right p q r c₀ c₁ P) =\n (seq_right c₀ <$> exit' P) :=\nby refl\n\n@[simp]\nlemma exit'_ite_left {p' q' p pa pb q : pred}\n {ds} {t : pred}\n {c : code p' q'} {c₀ : code pa q} {c₁ : code pb q}\n {P : subtree c c₀ }\n: exit' (subtree.ite_left ds t p pa pb q c₀ c₁ P) =\n ite_left p t ds c₁ <$> exit' P :=\nby refl\n\n@[simp]\nlemma exit'_ite_right {p' q' p pa pb q : pred}\n {ds} {t : pred}\n {c : code p' q'} {c₀ : code pa q} {c₁ : code pb q}\n {P : subtree c c₁ }\n: exit' (subtree.ite_right ds t p pa pb q c₀ c₁ P) =\n ite_right p t ds c₀ <$> exit' P :=\nby refl\n\n@[simp]\nlemma exit'_while {p' q' p inv q : pred}\n {ds} {t : pred}\n {c : code p' q'} {c' : code p inv}\n {P : subtree c c' }\n: exit' (subtree.while ds q t p inv c' P) =\n ( while_body t ds q <$> exit' P\n <|> some (current.while_cond _ _ _ _ _ _)) :=\nby refl\n\n@[simp]\nlemma within'_rfl {p' q' : pred}\n {c : code p' q'}\n {pc : current c}\n: within' subtree.rfl pc\n ↔ true :=\nby { cases c ; change tt ↔ true ; simp ; exact rfl, }\n\n@[simp]\nlemma within'_seq_left {p' q' p q r : pred}\n {c : code p' q'} {c₀ : code p q} {c₁ : code q r}\n {P : subtree c c₀ }\n {pc : current (code.seq c₀ c₁)}\n: within' (subtree.seq_left p q r c₀ c₁ P) pc\n ↔ (∃ pc₀, within' P pc₀ ∧ pc = current.seq_left p q r c₀ c₁ pc₀) :=\nbegin\n cases pc with pc,\n { split ; intro h,\n { existsi a,\n split, apply h, refl },\n { cases h with pc₀ h, cases h with h₀ h₁,\n rw h₁, apply h₀ }, },\n { split ; intro h,\n { cases h },\n { cases h with pc₀ h, cases h with h₀ h₁,\n cases h₁, } }\nend\n\n@[simp]\nlemma within'_seq_right {p' q' p q r : pred}\n {c : code p' q'} {c₀ : code p q} {c₁ : code q r}\n {P : subtree c c₁ }\n {pc : current (code.seq c₀ c₁)}\n: within' (subtree.seq_right p q r c₀ c₁ P) pc\n ↔ (∃ pc₁, within' P pc₁ ∧ pc = current.seq_right p q r c₀ c₁ pc₁) :=\nbegin\n cases pc with pc,\n { split ; intro h,\n { cases h },\n { cases h with pc₀ h, cases h with h₀ h₁,\n cases h₁, } },\n { split ; intro h,\n { existsi a,\n split, apply h, refl },\n { cases h with pc₀ h, cases h with h₀ h₁,\n rw h₁, apply h₀ }, },\nend\n\n@[simp]\nlemma within'_ite_left {p' q' p pa pb q : pred}\n {ds} {t : pred}\n {c : code p' q'} {c₀ : code pa q} {c₁ : code pb q}\n {P : subtree c c₀ }\n {pc : current _}\n: within' (subtree.ite_left ds t p pa pb q c₀ c₁ P) pc\n ↔ ∃ pc₀, within' P pc₀ ∧ pc = current.ite_left _ _ _ _ _ _ c₀ c₁ pc₀ :=\nbegin\n cases pc with pc,\n { split ; intro h,\n { cases h },\n { cases h with pc₀ h, cases h with h₀ h₁,\n cases h₁, } },\n { split ; intro h,\n { existsi a,\n split, apply h, refl },\n { cases h with pc₀ h, cases h with h₀ h₁,\n rw h₁, apply h₀ }, },\n { split ; intro h,\n { cases h },\n { cases h with pc₀ h, cases h with h₀ h₁,\n cases h₁, } }\nend\n\n@[simp]\nlemma within'_ite_right {p' q' p pa pb q : pred}\n {ds} {t : pred}\n {c : code p' q'} {c₀ : code pa q} {c₁ : code pb q}\n {P : subtree c c₁ }\n {pc : current _}\n: within' (subtree.ite_right ds t p pa pb q c₀ c₁ P) pc\n ↔ ∃ pc₁, within' P pc₁ ∧ pc = current.ite_right _ _ _ _ _ _ c₀ c₁ pc₁ :=\nbegin\n cases pc with pc,\n { split ; intro h,\n { cases h },\n { cases h with pc₀ h, cases h with h₀ h₁,\n cases h₁, } },\n { split ; intro h,\n { cases h },\n { cases h with pc₀ h, cases h with h₀ h₁,\n cases h₁, } },\n { split ; intro h,\n { existsi a,\n split, apply h, refl },\n { cases h with pc₀ h, cases h with h₀ h₁,\n rw h₁, apply h₀ }, },\nend\n\n@[simp]\nlemma within'_while {p' q' p inv q : pred}\n {ds} {t : pred}\n {c : code p' q'} {c' : code p inv}\n {P : subtree c c' }\n {pc : current _}\n: within' (subtree.while ds q t p inv c' P) pc\n ↔ ∃ pc', within' P pc' ∧ pc = current.while_body _ _ _ _ _ c' pc' :=\nbegin\n split ; intro h,\n { cases pc,\n { cases h },\n { existsi a, split,\n { apply h },\n { refl } } },\n { cases h with pc' h, cases h with h₀ h₁,\n cases h₁, apply h₀ }\nend\n\ndef counter {p q ds l}\n: ∀ {p' q'} {c' : code p' q'}, subtree (code.action p q ds l) c' → current c'\n | ._ ._ ._ subtree.rfl := current.action _ _ _ _\n | ._ ._ ._ (subtree.seq_left p q r c₀ c₁ P) :=\n current.seq_left _ _ _ _ _ (counter P)\n | ._ ._ ._ (subtree.seq_right p q r c₀ c₁ P) :=\n current.seq_right _ _ _ _ _ (counter P)\n | ._ ._ ._ (subtree.ite_left ds p t pa pb q c₀ c₁ P) :=\n current.ite_left _ _ _ _ _ _ _ _ (counter P)\n | ._ ._ ._ (subtree.ite_right ds p t pa pb q c₀ c₁ P) :=\n current.ite_right _ _ _ _ _ _ _ _ (counter P)\n | ._ ._ ._ (subtree.while p t inv q c₀ c₁ P) :=\n current.while_body _ _ _ _ _ _ (counter P)\n\ndef within {p q : pred} {c : code p q} {p' q'} {c' : code p' q'} (P : subtree c c')\n: option (current c') → Prop\n | (some pc) := within' P pc ∨ exit' P = some pc\n | none := exit' P = none\n\ndef exits {p q : pred} {c : code p q} {p' q'} {c' : code p' q'} (P : subtree c c')\n (pc : option (current c')) : Prop :=\nexit' P = pc\n\n\nlemma within_rfl {p q : pred} {c : code p q}\n (pc : option (current c))\n: within subtree.rfl pc :=\nbegin\n cases pc with pc,\n { dunfold within,\n cases c ; refl },\n { dunfold within,\n left, cases c ; apply rfl }\nend\n\n@[simp]\nlemma within_seq_left {p' q' p q r : pred}\n {c : code p' q'} {c₀ : code p q} {c₁ : code q r}\n {P : subtree c c₀ }\n {pc : option $ current (code.seq c₀ c₁)}\n: within (subtree.seq_left p q r c₀ c₁ P) pc\n ↔ (∃ pc₀, within P pc₀ ∧ pc = current.seq_left p q r c₀ c₁ <$> pc₀) :=\nbegin\n cases pc with pc,\n { simp [within], split ; intro h,\n { existsi none, simp [within],\n cases h, assumption },\n { cases h with pc₀ h, cases h with h₀ h₁,\n rw [eq_comm,fmap_eq_none_iff] at h₁, subst pc₀,\n dunfold within at h₀, simp [h₀], admit } },\n { admit }\nend\n\nsection projections\n\nvariables {p q r : pred}\nvariables {c₀ : code p q}\nvariables {c₁ : code q r}\n\ndef subtree.left\n: ∀ {p' q'} {c : code p' q'}, subtree (code.seq c₀ c₁) c → subtree c₀ c\n | ._ ._ ._ subtree.rfl := subtree.seq_left _ _ _ _ _ subtree.rfl\n | ._ ._ ._ (subtree.seq_left p q r c₂ c₃ S) := subtree.seq_left _ _ _ _ _ (subtree.left S)\n | ._ ._ ._ (subtree.seq_right p q r c₂ c₃ S) := subtree.seq_right _ _ _ _ _ (subtree.left S)\n | ._ ._ ._ (subtree.ite_left p ds t pa pb r c₂ c₃ S) :=\n subtree.ite_left _ _ _ _ _ _ _ _ (subtree.left S)\n | ._ ._ ._ (subtree.ite_right p ds t pa pb r c₂ c₃ S) :=\n subtree.ite_right _ _ _ _ _ _ _ _ (subtree.left S)\n | ._ ._ ._ (subtree.while ds t p q c₂ c₃ S) :=\n subtree.while _ _ _ _ _ _ (subtree.left S)\n\ndef subtree.right\n: ∀ {p' q'} {c : code p' q'}, subtree (code.seq c₀ c₁) c → subtree c₁ c\n | ._ ._ ._ subtree.rfl := subtree.seq_right _ _ _ _ _ subtree.rfl\n | ._ ._ ._ (subtree.seq_left p q r c₂ c₃ S) := subtree.seq_left _ _ _ _ _ (subtree.right S)\n | ._ ._ ._ (subtree.seq_right p q r c₂ c₃ S) := subtree.seq_right _ _ _ _ _ (subtree.right S)\n | ._ ._ ._ (subtree.ite_left p ds t pa pb r c₂ c₃ S) :=\n subtree.ite_left _ _ _ _ _ _ _ _ (subtree.right S)\n | ._ ._ ._ (subtree.ite_right p ds t pa pb r c₂ c₃ S) :=\n subtree.ite_right _ _ _ _ _ _ _ _ (subtree.right S)\n | ._ ._ ._ (subtree.while ds t p q c₂ c₃ S) :=\n subtree.while _ _ _ _ _ _ (subtree.right S)\n\nvariables {p' q' : pred}\nvariables {c : code p' q'}\nvariables {pc : option $ current c}\n\nlemma within_left_or_within_right_iff_within_seq\n (H : subtree (code.seq c₀ c₁) c)\n: within H pc ↔ within H.left pc ∨ within H.right pc :=\nbegin\n induction H,\n { cases pc with pc,\n { dunfold within subtree.left subtree.right,\n simp, },\n dunfold within subtree.left subtree.right,\n have Hnone : none = some pc ↔ false, { admit },\n simp [Hnone],\n { cases pc,\n { left,\n existsi a, refl, },\n { right, left, existsi a, refl } } },\n { cases pc with pc,\n { dsimp [within,subtree.left], admit }, dsimp [within], admit },\n all_goals { admit }\nend\n\nlemma exits_iff_exits_right\n (H : subtree (code.seq c₀ c₁) c)\n: exits H pc ↔ exits H.right pc := sorry\n\nlemma exits_left_imp_within_right\n (H : subtree (code.seq c₀ c₁) c)\n: exits H.left pc → within H.right pc := sorry\n\nend projections\n\nend\n", "meta": {"author": "unitb", "repo": "unitb-semantics", "sha": "07607ddb2ced4044af121f1fd989e058e19c3c9c", "save_path": "github-repos/lean/unitb-unitb-semantics", "path": "github-repos/lean/unitb-unitb-semantics/unitb-semantics-07607ddb2ced4044af121f1fd989e058e19c3c9c/src/unitb/code/syntax.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48047867804790706, "lm_q2_score": 0.02887090736407739, "lm_q1q2_score": 0.01387185540433549}} {"text": "import galois.map.fmap_func\n galois.network.labels\n\nuniverses u v\n\n\nnamespace network\n\ninductive act (A : Type u) : Type u\n-- return a poll result and the amount of time elapsed\n| poll : Π (ports : list port) (sockets : list socket) (bound : time), \n (poll_result ports sockets bound → (list (socket × message_t) × A)) → act\n\nnamespace act\ndef just_send_messages {A : Type u} (ms : list (socket × message_t)) \n (x : A) := act.poll [] [] 0 (λ _, (ms, x))\n\ndef return {A : Type u} (x : A) : act A := just_send_messages [] x\nend act\n\n/-- Indicates that an agent is polling -/\ninductive polls_on_socket {A : Type u} (s : socket) : act A → Prop\n| mk : ∀ ports sockets bound cont, 0 < bound → s ∈ sockets \n → polls_on_socket (act.poll ports sockets bound cont)\n\ninstance polls_decidable {A : Type} (s : socket) : decidable_pred (@polls_on_socket A s)\n:= begin\nintros x, induction x,\napply (if H : 0 < bound ∧ s ∈ sockets then _ else _),\n{ apply decidable.is_true, induction H with H1 H2,\n constructor; assumption },\n{ apply decidable.is_false, intros contra, cases contra,\n apply H, split; assumption }\nend\n\n-- An agent is defined as a type for the internal state, an process that produces\n-- the state, and a looping process that will execute when the process is complete.\n--\n-- Semantically, think of the behavior as `next >>= forever loop` where\n-- `forever loop = loop >=> forever loop`.\nstructure agent : Type 1 :=\n (state_type : Type)\n (loop : state_type → act state_type)\n\n\ninductive dlabel {A : Type u} : act A → Type u\n| poll : ∀ (ports : list port) (sockets : list socket) (bound : time) cont\n (r : poll_result ports sockets bound),\n dlabel (act.poll ports sockets bound cont)\n\nnamespace dlabel\ndef cont_result {A : Type u} : ∀ {next : act A} (la : dlabel next), \n list (socket × message_t) × A\n| (act.poll ports sockets bound cont) (dlabel.poll ._ ._ ._ ._ r) := cont r\n\ndef messages {A : Type u} {next : act A} (la : dlabel next) : list (socket × message_t)\n := la.cont_result.fst\n\nlemma invert {A : Type u} \n {ports sockets bound cont} (l : @dlabel A (act.poll ports sockets bound cont))\n : ∃ r : poll_result ports sockets bound,\n l = dlabel.poll ports sockets bound cont r\n:= begin\ncases l, constructor, reflexivity\nend\nend dlabel\n\nend network", "meta": {"author": "GaloisInc", "repo": "lean-protocol-support", "sha": "cabfa3abedbdd6fdca6e2da6fbbf91a13ed48dda", "save_path": "github-repos/lean/GaloisInc-lean-protocol-support", "path": "github-repos/lean/GaloisInc-lean-protocol-support/lean-protocol-support-cabfa3abedbdd6fdca6e2da6fbbf91a13ed48dda/galois/network/action.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4186969093556867, "lm_q2_score": 0.03308598148730279, "lm_q1q2_score": 0.013852998191733145}} {"text": "/-\n Specifications file for bigint_spec.cairo\n\n Do not modify the constant definitions, structure definitions, or automatic specifications.\n Do not change the name or arguments of the user specifications and soundness theorems.\n\n You may freely move the definitions around in the file.\n You may add definitions and theorems wherever you wish in this file.\n-/\nimport starkware.cairo.lean.semantics.soundness.prelude\nimport starkware.cairo.common.cairo_secp.constants_spec\n\nopen starkware.cairo.common.cairo_secp.constants\n\nnamespace starkware.cairo.common.cairo_secp.bigint\n\nvariables {F : Type} [field F] [decidable_eq F] [prelude_hyps F]\n\n-- End of automatically generated prelude.\n\n-- Main scope definitions.\n\n@[ext] structure BigInt3 (F : Type) :=\n ( d0 : F ) ( d1 : F ) ( d2 : F )\nattribute [derive decidable_eq] BigInt3\n@[ext] structure π_BigInt3 (F : Type) :=\n ( σ_ptr : F ) ( d0 : F ) ( d1 : F ) ( d2 : F )\n@[reducible] def φ_BigInt3.d0 := 0\n@[reducible] def φ_BigInt3.d1 := 1\n@[reducible] def φ_BigInt3.d2 := 2\n@[reducible] def φ_BigInt3.SIZE := 3\n@[reducible] def cast_BigInt3 (mem : F → F) (p : F) : BigInt3 F := {\n d0 := mem (p + φ_BigInt3.d0),\n d1 := mem (p + φ_BigInt3.d1),\n d2 := mem (p + φ_BigInt3.d2)\n}\n@[reducible] def cast_π_BigInt3 (mem : F → F) (p : F) : π_BigInt3 F := {\n σ_ptr := mem p,\n d0 := mem ((mem p) + φ_BigInt3.d0),\n d1 := mem ((mem p) + φ_BigInt3.d1),\n d2 := mem ((mem p) + φ_BigInt3.d2)\n}\ninstance π_BigInt3_to_F : has_coe (π_BigInt3 F) F := ⟨λ s, s.σ_ptr⟩\n@[ext] structure UnreducedBigInt5 (F : Type) :=\n ( d0 : F ) ( d1 : F ) ( d2 : F ) ( d3 : F ) ( d4 : F )\n@[ext] structure π_UnreducedBigInt5 (F : Type) :=\n ( σ_ptr : F ) ( d0 : F ) ( d1 : F ) ( d2 : F ) ( d3 : F ) ( d4 : F )\n@[reducible] def φ_UnreducedBigInt5.d0 := 0\n@[reducible] def φ_UnreducedBigInt5.d1 := 1\n@[reducible] def φ_UnreducedBigInt5.d2 := 2\n@[reducible] def φ_UnreducedBigInt5.d3 := 3\n@[reducible] def φ_UnreducedBigInt5.d4 := 4\n@[reducible] def φ_UnreducedBigInt5.SIZE := 5\n@[reducible] def cast_UnreducedBigInt5 (mem : F → F) (p : F) : UnreducedBigInt5 F := {\n d0 := mem (p + φ_UnreducedBigInt5.d0),\n d1 := mem (p + φ_UnreducedBigInt5.d1),\n d2 := mem (p + φ_UnreducedBigInt5.d2),\n d3 := mem (p + φ_UnreducedBigInt5.d3),\n d4 := mem (p + φ_UnreducedBigInt5.d4)\n}\n@[reducible] def cast_π_UnreducedBigInt5 (mem : F → F) (p : F) : π_UnreducedBigInt5 F := {\n σ_ptr := mem p,\n d0 := mem ((mem p) + φ_UnreducedBigInt5.d0),\n d1 := mem ((mem p) + φ_UnreducedBigInt5.d1),\n d2 := mem ((mem p) + φ_UnreducedBigInt5.d2),\n d3 := mem ((mem p) + φ_UnreducedBigInt5.d3),\n d4 := mem ((mem p) + φ_UnreducedBigInt5.d4)\n}\ninstance π_UnreducedBigInt5_to_F : has_coe (π_UnreducedBigInt5 F) F := ⟨λ s, s.σ_ptr⟩\n@[ext] structure UnreducedBigInt3 (F : Type) :=\n ( d0 : F ) ( d1 : F ) ( d2 : F )\n@[ext] structure π_UnreducedBigInt3 (F : Type) :=\n ( σ_ptr : F ) ( d0 : F ) ( d1 : F ) ( d2 : F )\n@[reducible] def φ_UnreducedBigInt3.d0 := 0\n@[reducible] def φ_UnreducedBigInt3.d1 := 1\n@[reducible] def φ_UnreducedBigInt3.d2 := 2\n@[reducible] def φ_UnreducedBigInt3.SIZE := 3\n@[reducible] def cast_UnreducedBigInt3 (mem : F → F) (p : F) : UnreducedBigInt3 F := {\n d0 := mem (p + φ_UnreducedBigInt3.d0),\n d1 := mem (p + φ_UnreducedBigInt3.d1),\n d2 := mem (p + φ_UnreducedBigInt3.d2)\n}\n@[reducible] def cast_π_UnreducedBigInt3 (mem : F → F) (p : F) : π_UnreducedBigInt3 F := {\n σ_ptr := mem p,\n d0 := mem ((mem p) + φ_UnreducedBigInt3.d0),\n d1 := mem ((mem p) + φ_UnreducedBigInt3.d1),\n d2 := mem ((mem p) + φ_UnreducedBigInt3.d2)\n}\ninstance π_UnreducedBigInt3_to_F : has_coe (π_UnreducedBigInt3 F) F := ⟨λ s, s.σ_ptr⟩\n\n-- End of main scope definitions.\n\nnamespace nondet_bigint3\n\n@[reducible] def MAX_SUM := 3 * (BASE - 1)\n\nend nondet_bigint3\n\nnamespace BigInt3\n\ndef add (x y : BigInt3 F) : BigInt3 F :=\n{ d0 := x.d0 + y.d0, d1 := x.d1 + y.d1, d2 := x.d2 + y.d2 }\n\ndef sub (x y : BigInt3 F) : BigInt3 F :=\n{ d0 := x.d0 - y.d0, d1 := x.d1 - y.d1, d2 := x.d2 - y.d2 }\n\nend BigInt3\n\nnamespace UnreducedBigInt3\n\ndef add (x y : UnreducedBigInt3 F) : UnreducedBigInt3 F :=\n{ d0 := x.d0 + y.d0, d1 := x.d1 + y.d1, d2 := x.d2 + y.d2 }\n\ndef sub (x y : UnreducedBigInt3 F) : UnreducedBigInt3 F :=\n{ d0 := x.d0 - y.d0, d1 := x.d1 - y.d1, d2 := x.d2 - y.d2 }\n\nend UnreducedBigInt3\n\n@[ext]\nstructure bigint3 := (i0 i1 i2 : ℤ)\n\nnamespace bigint3\n\ndef val (x : bigint3) : int := x.i2 * ↑BASE^2 + x.i1 * ↑BASE + x.i0\n\ndef toBigInt3 (x : bigint3) : BigInt3 F := ⟨x.i0, x.i1, x.i2⟩\n\ndef toUnreducedBigInt3 (x : bigint3) : UnreducedBigInt3 F := ⟨x.i0, x.i1, x.i2⟩\n\ndef add (x y : bigint3) : bigint3 :=\n{ i0 := x.i0 + y.i0, i1 := x.i1 + y.i1, i2 := x.i2 + y.i2 }\n\ntheorem toBigInt3_add (x y : bigint3) : ((x.add y).toBigInt3 : BigInt3 F) =\n BigInt3.add (x.toBigInt3) (y.toBigInt3) :=\nby simp [BigInt3.add, toBigInt3, bigint3.add]\n\ntheorem toUnreducedBigInt3_add (x y : bigint3) :\n ((x.add y).toUnreducedBigInt3 : UnreducedBigInt3 F) =\n UnreducedBigInt3.add (x.toUnreducedBigInt3) (y.toUnreducedBigInt3) :=\nby simp [UnreducedBigInt3.add, toUnreducedBigInt3, bigint3.add]\n\ntheorem add_val (x y : bigint3) : (x.add y).val = x.val + y.val :=\nby { simp [val, add], ring }\n\ndef sub (x y : bigint3) : bigint3 :=\n{ i0 := x.i0 - y.i0, i1 := x.i1 - y.i1, i2 := x.i2 - y.i2 }\n\ntheorem toBigInt3_sub (x y : bigint3) : ((x.sub y).toBigInt3 : BigInt3 F) =\n BigInt3.sub (x.toBigInt3) (y.toBigInt3) :=\nby simp [BigInt3.sub, toBigInt3, bigint3.sub]\n\ntheorem toUnreducedBigInt3_sub (x y : bigint3) : ((x.sub y).toUnreducedBigInt3 : UnreducedBigInt3 F) =\n UnreducedBigInt3.sub (x.toUnreducedBigInt3) (y.toUnreducedBigInt3) :=\nby simp [UnreducedBigInt3.sub, toUnreducedBigInt3, bigint3.sub]\n\ntheorem sub_val (x y : bigint3) : (x.sub y).val = x.val - y.val :=\nby { simp [val, sub], ring }\n\ndef cmul (c : ℤ) (x : bigint3) : bigint3 :=\n{ i0 := c * x.i0, i1 := c * x.i1, i2 := c * x.i2}\n\ntheorem cmul_val (c : ℤ) (x : bigint3) : (x.cmul c).val = c * x.val :=\nby { simp [val, cmul], ring }\n\ndef mul (x y : bigint3) : bigint3 :=\n{ i0 := x.i0 * y.i0 + (x.i1 * y.i2 + x.i2 * y.i1) * (4 * SECP_REM),\n i1 := x.i0 * y.i1 + x.i1 * y.i0 + (x.i2 * y.i2) * (4 * SECP_REM),\n i2 := x.i0 * y.i2 + x.i1 * y.i1 + x.i2 * y.i0 }\n\ntheorem mul_val (x y : bigint3) : (x.mul y).val ≡ x.val * y.val [ZMOD ↑SECP_PRIME] :=\nbegin\n have aux : (4 : ℤ) ∣ ↑BASE ^ 3,\n { dsimp only [BASE], simp_int_casts, norm_num1 },\n rw [int.modeq_iff_dvd],\n use [4 * (x.i1 * y.i2 + x.i2 * y.i1 + BASE * (x.i2 * y.i2))],\n rw SECP_PRIME_eq,\n simp only [val, mul],\n conv { to_rhs, rw [←mul_assoc, sub_mul, int.div_mul_cancel aux] },\n generalize : SECP_REM = S,\n generalize : BASE = B,\n ring\nend\n\ndef sqr (x : bigint3) : bigint3 := x.mul x\n\ntheorem sqr_val (x : bigint3) : x.sqr.val ≡ x.val^2 [ZMOD ↑SECP_PRIME] :=\nby { rw pow_two, exact mul_val x x }\n\ndef bounded (x : bigint3) (b : ℤ) := abs x.i0 ≤ b ∧ abs x.i1 ≤ b ∧ abs x.i2 ≤ b\n\ntheorem bounded_of_bounded_of_le {x : bigint3} {b₁ b₂ : ℤ} (bddx : x.bounded b₁) (hle : b₁ ≤ b₂) :\n x.bounded b₂ :=\n⟨bddx.1.trans hle, bddx.2.1.trans hle, bddx.2.2.trans hle⟩\n\ntheorem bounded_add {x y : bigint3} {b₁ b₂ : int} (bddx : x.bounded b₁) (bddy : y.bounded b₂) :\n (x.add y).bounded (b₁ + b₂) :=\n⟨(abs_add _ _).trans (add_le_add bddx.1 bddy.1),\n (abs_add _ _).trans (add_le_add bddx.2.1 bddy.2.1),\n (abs_add _ _).trans (add_le_add bddx.2.2 bddy.2.2)⟩\n\ntheorem bounded_sub {x y : bigint3} {b₁ b₂ : int} (bddx : x.bounded b₁) (bddy : y.bounded b₂) :\n (x.sub y).bounded (b₁ + b₂) :=\n⟨(abs_sub _ _).trans (add_le_add bddx.1 bddy.1),\n (abs_sub _ _).trans (add_le_add bddx.2.1 bddy.2.1),\n (abs_sub _ _).trans (add_le_add bddx.2.2 bddy.2.2)⟩\n\ntheorem bounded_cmul {x : bigint3} {c b : int} (bddx : x.bounded b) :\n (x.cmul c).bounded (abs c * b) :=\nbegin\n simp [cmul, bigint3.bounded, abs_mul],\n exact ⟨mul_le_mul_of_nonneg_left bddx.1 (abs_nonneg _),\n mul_le_mul_of_nonneg_left bddx.2.1 (abs_nonneg _),\n mul_le_mul_of_nonneg_left bddx.2.2 (abs_nonneg _)⟩\nend\n\ntheorem bounded_cmul' {x : bigint3} {c b : int} (h : 0 ≤ c) (bddx : x.bounded b) :\n (x.cmul c).bounded (c * b) :=\nby { convert bounded_cmul bddx, rw abs_of_nonneg h }\n\ntheorem bounded_mul {x y : bigint3} {b : ℤ} (hx : x.bounded b) (hy : y.bounded b) :\n (x.mul y).bounded (b^2 * (8 * SECP_REM + 1)) :=\nbegin\n have bnonneg : 0 ≤ b := le_trans (abs_nonneg _) hx.1,\n have secp4nonneg : (0 : ℤ) ≤ 4 * ↑SECP_REM,\n { apply mul_nonneg, norm_num1, rw [SECP_REM], simp_int_casts, norm_num1 },\n have secp4ge1 : (1 : ℤ) ≤ 4 * ↑SECP_REM,\n { rw [SECP_REM], simp_int_casts, norm_num1 },\n simp only [bigint3.mul, bigint3.bounded],\n split,\n { transitivity b * b + (b * b + b * b) * (4 * ↑SECP_REM),\n { apply le_trans, apply abs_add,\n apply add_le_add, rw abs_mul,\n apply mul_le_mul hx.1 hy.1 (abs_nonneg _) bnonneg,\n rw [abs_mul, abs_of_nonneg secp4nonneg],\n apply mul_le_mul_of_nonneg_right _ secp4nonneg,\n apply le_trans, apply abs_add, rw [abs_mul, abs_mul],\n apply add_le_add, apply mul_le_mul hx.2.1 hy.2.2 (abs_nonneg _) bnonneg,\n apply mul_le_mul hx.2.2 hy.2.1 (abs_nonneg _) bnonneg },\n apply le_of_eq, ring },\n split,\n { transitivity b * b + b * (b * (4 * ↑SECP_REM)) + (b * b) * (4 * ↑SECP_REM),\n { apply le_trans, apply abs_add,\n apply add_le_add,\n apply le_trans, apply abs_add,\n rw [abs_mul, abs_mul], apply add_le_add,\n apply mul_le_mul hx.1 hy.2.1 (abs_nonneg _) bnonneg,\n apply mul_le_mul hx.2.1 _ (abs_nonneg _) bnonneg,\n rw [←mul_one(abs y.i0)],\n apply mul_le_mul hy.1 secp4ge1 zero_le_one bnonneg,\n rw [abs_mul, abs_mul, abs_of_nonneg secp4nonneg],\n apply mul_le_mul_of_nonneg_right _ secp4nonneg,\n apply mul_le_mul hx.2.2 hy.2.2 (abs_nonneg _) bnonneg,\n },\n apply le_of_eq, ring },\n transitivity (b * b + b * b + b * b),\n apply le_trans, apply abs_add, apply add_le_add,\n apply le_trans, apply abs_add, rw [abs_mul, abs_mul],\n apply add_le_add,\n apply mul_le_mul hx.1 hy.2.2 (abs_nonneg _) bnonneg,\n apply mul_le_mul hx.2.1 hy.2.1 (abs_nonneg _) bnonneg,\n rw abs_mul,\n apply mul_le_mul hx.2.2 hy.1 (abs_nonneg _) bnonneg,\n transitivity (b^2 * 3),\n apply le_of_eq, ring,\n apply mul_le_mul_of_nonneg_left _ (pow_two_nonneg b),\n rw [SECP_REM], simp_int_casts, norm_num1\nend\n\ntheorem bounded_sqr {x : bigint3} {b : ℤ} (hx : x.bounded b) :\n (x.sqr).bounded (b^2 * (8 * SECP_REM + 1)) :=\nbounded_mul hx hx\n\nend bigint3\n\ntheorem bigint3_eqs {x : BigInt3 F} {i0 i1 i2 : ℤ} (h : x = (bigint3.mk i0 i1 i2).toBigInt3) :\n x.d0 = i0 ∧ x.d1 = i1 ∧ x.d2 = i2 :=\nby { rwa BigInt3.ext_iff at h }\n\ntheorem unreduced_bigint3_eqs {x : UnreducedBigInt3 F} {i0 i1 i2 : ℤ} (h : x = (bigint3.mk i0 i1 i2).toUnreducedBigInt3) :\n x.d0 = i0 ∧ x.d1 = i1 ∧ x.d2 = i2 :=\nby { rwa UnreducedBigInt3.ext_iff at h }\n\ntheorem cast_int_eq_of_bdd_3BASE {i j : int}\n (heq : (i : F) = (j : F))\n (ibdd : abs i ≤ 3 * BASE - 1)\n (jbdd : abs j ≤ 3 * BASE - 1) :\n i = j :=\nbegin\n apply PRIME.int_coe_inj heq,\n apply lt_of_le_of_lt,\n apply abs_sub,\n apply lt_of_le_of_lt,\n apply add_le_add jbdd ibdd,\n dsimp only [BASE, PRIME],\n simp_int_casts,\n norm_num\nend\n\ntheorem toBigInt3_eq_toBigInt3_of_bounded_3BASE {a b : bigint3}\n (heq : (a.toBigInt3 : BigInt3 F) = b.toBigInt3)\n (abdd : a.bounded (3 * BASE - 1))\n (bbdd : b.bounded (3 * BASE - 1)) :\n a = b :=\nbegin\n simp [BigInt3.ext_iff, bigint3.toBigInt3] at heq,\n ext,\n { apply cast_int_eq_of_bdd_3BASE heq.1 abdd.1 bbdd.1 },\n { apply cast_int_eq_of_bdd_3BASE heq.2.1 abdd.2.1 bbdd.2.1 },\n { apply cast_int_eq_of_bdd_3BASE heq.2.2 abdd.2.2 bbdd.2.2 }\nend\n\ntheorem toBigInt3_eq_zero_of_bounded_3BASE {a : bigint3}\n (heq : (a.toBigInt3 : BigInt3 F) = ⟨0, 0, 0⟩)\n (abdd : a.bounded (3 * BASE - 1)) :\n a = ⟨0, 0, 0⟩ :=\nbegin\n have : (a.toBigInt3 : BigInt3 F) = bigint3.toBigInt3 ⟨0, 0, 0⟩,\n { rw heq, simp [bigint3.toBigInt3] },\n apply toBigInt3_eq_toBigInt3_of_bounded_3BASE this abdd,\n simp [bigint3.bounded],\n norm_num\nend\n\n@[ext] structure bigint5 := (i0 i1 i2 i3 i4 : ℤ)\n\ndef bigint3.bigint5_mul (ix iy : bigint3) : bigint5 :=\n{ i0 := ix.i0 * iy.i0,\n i1 := ix.i0 * iy.i1 + ix.i1 * iy.i0,\n i2 := ix.i0 * iy.i2 + ix.i1 * iy.i1 + ix.i2 * iy.i0,\n i3 := ix.i1 * iy.i2 + ix.i2 * iy.i1,\n i4 := ix.i2 * iy.i2 }\n\ndef BigInt3.UnreducedBigInt5_mul (x y : BigInt3 F) : UnreducedBigInt5 F :=\n{ d0 := x.d0 * y.d0,\n d1 := x.d0 * y.d1 + x.d1 * y.d0,\n d2 := x.d0 * y.d2 + x.d1 * y.d1 + x.d2 * y.d0,\n d3 := x.d1 * y.d2 + x.d2 * y.d1,\n d4 := x.d2 * y.d2 }\n\ndef bigint5.toUnreducedBigInt5 (x : bigint5) : UnreducedBigInt5 F := ⟨x.i0, x.i1, x.i2, x.i3, x.i4⟩\n\ntheorem bigint3.bigint5_mul_toUnreducedBigInt5 (ix iy : bigint3) :\n ((ix.bigint5_mul iy).toUnreducedBigInt5 : UnreducedBigInt5 F) =\n (ix.toBigInt3).UnreducedBigInt5_mul (iy.toBigInt3) :=\nby simp [bigint5.toUnreducedBigInt5, bigint3.toBigInt3, bigint3.bigint5_mul,\n BigInt3.UnreducedBigInt5_mul]\n\ndef bigint3.to_bigint5 (ix : bigint3) : bigint5 := ⟨ix.i0, ix.i1, ix.i2, 0, 0⟩\n\ndef BigInt3.toUnreducedBigInt5 {F : Type} [field F]\n (x : BigInt3 F) : UnreducedBigInt5 F := ⟨x.d0, x.d1, x.d2, 0, 0⟩\n\ntheorem bigint3.to_bigint5_to_Unreduced_BigInt5 (ix : bigint3) :\n (ix.to_bigint5.toUnreducedBigInt5 : UnreducedBigInt5 F) = ix.toBigInt3.toUnreducedBigInt5 :=\nbegin\n simp [bigint5.toUnreducedBigInt5, bigint3.to_bigint5, bigint3.toBigInt3,\n BigInt3.toUnreducedBigInt5]\nend\n\nnamespace UnreducedBigInt5\n\ndef add (x y : UnreducedBigInt5 F) : UnreducedBigInt5 F :=\n{ d0 := x.d0 + y.d0, d1 := x.d1 + y.d1, d2 := x.d2 + y.d2, d3 := x.d3 + y.d3, d4 := x.d4 + y.d4 }\n\ndef sub (x y : UnreducedBigInt5 F) : UnreducedBigInt5 F :=\n{ d0 := x.d0 - y.d0, d1 := x.d1 - y.d1, d2 := x.d2 - y.d2, d3 := x.d3 - y.d3, d4 := x.d4 - y.d4 }\n\nend UnreducedBigInt5\n\nnamespace bigint5\n\ndef val (x : bigint5) : int := x.i4 * ↑BASE^4 + x.i3 * ↑BASE^3 + x.i2 * ↑BASE^2 +\n x.i1 * ↑BASE + x.i0\n\ndef add (x y : bigint5) : bigint5 :=\n{ i0 := x.i0 + y.i0, i1 := x.i1 + y.i1, i2 := x.i2 + y.i2, i3 := x.i3 + y.i3, i4 := x.i4 + y.i4 }\n\ntheorem toUnreducedBigInt5_add (x y : bigint5) :\n ((x.add y).toUnreducedBigInt5 : UnreducedBigInt5 F) =\n UnreducedBigInt5.add (x.toUnreducedBigInt5) (y.toUnreducedBigInt5) :=\nby simp [UnreducedBigInt5.add, toUnreducedBigInt5, bigint5.add]\n\ntheorem add_val (x y : bigint5) : (x.add y).val = x.val + y.val :=\nby { simp [val, add], ring }\n\ndef sub (x y : bigint5) : bigint5 :=\n{ i0 := x.i0 - y.i0, i1 := x.i1 - y.i1, i2 := x.i2 - y.i2, i3 := x.i3 - y.i3, i4 := x.i4 - y.i4 }\n\ntheorem toUnreducedBigInt5_sub (x y : bigint5) :\n ((x.sub y).toUnreducedBigInt5 : UnreducedBigInt5 F) =\n UnreducedBigInt5.sub (x.toUnreducedBigInt5) (y.toUnreducedBigInt5) :=\nby simp [UnreducedBigInt5.sub, toUnreducedBigInt5, bigint5.sub]\n\ntheorem sub_val (x y : bigint5) : (x.sub y).val = x.val - y.val :=\nby { simp [val, sub], ring }\n\ndef cmul (c : ℤ) (x : bigint5) : bigint5 :=\n{ i0 := c * x.i0, i1 := c * x.i1, i2 := c * x.i2, i3 := c * x.i3, i4 := c * x.i4 }\n\ndef bounded (x : bigint5) (b : ℤ) := abs x.i0 ≤ b ∧ abs x.i1 ≤ b ∧ abs x.i2 ≤ b ∧\n abs x.i3 ≤ b ∧ abs x.i4 ≤ b\n\ntheorem bounded_of_bounded_of_le {x : bigint5} {b₁ b₂ : ℤ} (bddx : x.bounded b₁) (hle : b₁ ≤ b₂) :\n x.bounded b₂ :=\n⟨bddx.1.trans hle, bddx.2.1.trans hle, bddx.2.2.1.trans hle, bddx.2.2.2.1.trans hle,\n bddx.2.2.2.2.trans hle⟩\n\ntheorem bounded_add {x y : bigint5} {b₁ b₂ : int} (bddx : x.bounded b₁) (bddy : y.bounded b₂) :\n (x.add y).bounded (b₁ + b₂) :=\n⟨(abs_add _ _).trans (add_le_add bddx.1 bddy.1),\n (abs_add _ _).trans (add_le_add bddx.2.1 bddy.2.1),\n (abs_add _ _).trans (add_le_add bddx.2.2.1 bddy.2.2.1),\n (abs_add _ _).trans (add_le_add bddx.2.2.2.1 bddy.2.2.2.1),\n (abs_add _ _).trans (add_le_add bddx.2.2.2.2 bddy.2.2.2.2)⟩\n\ntheorem bounded_sub {x y : bigint5} {b₁ b₂ : int} (bddx : x.bounded b₁) (bddy : y.bounded b₂) :\n (x.sub y).bounded (b₁ + b₂) :=\n⟨(abs_sub _ _).trans (add_le_add bddx.1 bddy.1),\n (abs_sub _ _).trans (add_le_add bddx.2.1 bddy.2.1),\n (abs_sub _ _).trans (add_le_add bddx.2.2.1 bddy.2.2.1),\n (abs_sub _ _).trans (add_le_add bddx.2.2.2.1 bddy.2.2.2.1),\n (abs_sub _ _).trans (add_le_add bddx.2.2.2.2 bddy.2.2.2.2) ⟩\n\ntheorem bounded_cmul {x : bigint5} {c b : int} (bddx : x.bounded b) :\n (x.cmul c).bounded (abs c * b) :=\nbegin\n simp [cmul, bigint5.bounded, abs_mul],\n exact ⟨mul_le_mul_of_nonneg_left bddx.1 (abs_nonneg _),\n mul_le_mul_of_nonneg_left bddx.2.1 (abs_nonneg _),\n mul_le_mul_of_nonneg_left bddx.2.2.1 (abs_nonneg _),\n mul_le_mul_of_nonneg_left bddx.2.2.2.1 (abs_nonneg _),\n mul_le_mul_of_nonneg_left bddx.2.2.2.2 (abs_nonneg _)⟩\nend\n\ntheorem bounded_cmul' {x : bigint5} {c b : int} (h : 0 ≤ c) (bddx : x.bounded b) :\n (x.cmul c).bounded (c * b) :=\nby { convert bounded_cmul bddx, rw abs_of_nonneg h }\n\ntheorem toUnreducedBigInt5_eq_of_sub_bounded {a b : bigint5}\n (heq : (a.toUnreducedBigInt5 : UnreducedBigInt5 F) = b.toUnreducedBigInt5)\n (bdd : (b.sub a).bounded (PRIME - 1)) :\n a = b :=\nbegin\n simp [UnreducedBigInt5.ext_iff, bigint5.toUnreducedBigInt5] at heq,\n have h : (PRIME : ℤ) - 1 < PRIME, by norm_num,\n ext,\n exact PRIME.int_coe_inj heq.1 (lt_of_le_of_lt bdd.1 h),\n exact PRIME.int_coe_inj heq.2.1 (lt_of_le_of_lt bdd.2.1 h),\n exact PRIME.int_coe_inj heq.2.2.1 (lt_of_le_of_lt bdd.2.2.1 h),\n exact PRIME.int_coe_inj heq.2.2.2.1 (lt_of_le_of_lt bdd.2.2.2.1 h),\n exact PRIME.int_coe_inj heq.2.2.2.2 (lt_of_le_of_lt bdd.2.2.2.2 h),\nend\n\nend bigint5\n\ntheorem bigint3.bounded_bigint5_mul {x y : bigint3} {b : ℤ}\n (hx : x.bounded b) (hy : y.bounded b) :\n (x.bigint5_mul y).bounded (3 * b^2) :=\nbegin\n have bnn : 0 ≤ b := le_trans (abs_nonneg _) hx.1,\n have b2nn: 0 ≤ b^2 := sq_nonneg b,\n have b2le3b2 : b^2 ≤ 3 * b^2, by linarith,\n have b2b2le3b2 : b^2 + b^2 ≤ 3 * b^2, by linarith,\n have b23eq : 3 * b^2 = b^2 + b^2 + b^2, by linarith,\n simp [bigint3.bigint5_mul],\n split,\n { apply le_trans _ b2le3b2,\n rw [abs_mul, pow_two],\n exact mul_le_mul hx.1 hy.1 (abs_nonneg _) bnn },\n split,\n { apply le_trans _ b2b2le3b2,\n refine le_trans (abs_add _ _) _,\n simp_rw [abs_mul, pow_two],\n apply add_le_add,\n exact mul_le_mul hx.1 hy.2.1 (abs_nonneg _) bnn,\n exact mul_le_mul hx.2.1 hy.1 (abs_nonneg _) bnn },\n split,\n { rw [b23eq, pow_two],\n refine le_trans (abs_add _ _) _,\n apply add_le_add,\n refine le_trans (abs_add _ _) _,\n simp_rw abs_mul, apply add_le_add,\n exact mul_le_mul hx.1 hy.2.2 (abs_nonneg _) bnn,\n exact mul_le_mul hx.2.1 hy.2.1 (abs_nonneg _) bnn,\n rw abs_mul,\n exact mul_le_mul hx.2.2 hy.1 (abs_nonneg _) bnn },\n split,\n { apply le_trans _ b2b2le3b2,\n refine le_trans (abs_add _ _) _,\n simp_rw [abs_mul, pow_two],\n apply add_le_add,\n exact mul_le_mul hx.2.1 hy.2.2 (abs_nonneg _) bnn,\n exact mul_le_mul hx.2.2 hy.2.1 (abs_nonneg _) bnn },\n apply le_trans _ b2le3b2,\n rw [abs_mul, pow_two],\n exact mul_le_mul hx.2.2 hy.2.2 (abs_nonneg _) bnn\nend\n\ntheorem bigint3.to_bigint5_bounded {x : bigint3} {b : ℤ} (hx : x.bounded b) :\n x.to_bigint5.bounded b :=\nbegin\n use [hx.1, hx.2.1, hx.2.2],\n simp [bigint3.to_bigint5],\n apply le_trans (abs_nonneg _ ) hx.1\nend\n\n/-\n-- Function: bigint_mul\n-/\n\n/- bigint_mul autogenerated specification -/\n\n-- Do not change this definition.\ndef auto_spec_bigint_mul (mem : F → F) (κ : ℕ) (x y : BigInt3 F) (ρ_res : UnreducedBigInt5 F) : Prop :=\n 14 ≤ κ ∧\n ρ_res = {\n d0 := x.d0 * y.d0,\n d1 := x.d0 * y.d1 + x.d1 * y.d0,\n d2 := x.d0 * y.d2 + x.d1 * y.d1 + x.d2 * y.d0,\n d3 := x.d1 * y.d2 + x.d2 * y.d1,\n d4 := x.d2 * y.d2\n }\n\n-- You may change anything in this definition except the name and arguments.\ndef spec_bigint_mul (mem : F → F) (κ : ℕ) (x y : BigInt3 F) (ρ_res : UnreducedBigInt5 F) : Prop :=\n ρ_res = x.UnreducedBigInt5_mul y\n\n/- bigint_mul soundness theorem -/\n\n-- Do not change the statement of this theorem. You may change the proof.\ntheorem sound_bigint_mul\n {mem : F → F}\n (κ : ℕ)\n (x y : BigInt3 F) (ρ_res : UnreducedBigInt5 F)\n (h_auto : auto_spec_bigint_mul mem κ x y ρ_res) :\n spec_bigint_mul mem κ x y ρ_res :=\nbegin\n exact h_auto.2\nend\n\n/-\n-- Function: nondet_bigint3\n-/\n\n/- nondet_bigint3 autogenerated specification -/\n\n-- Do not change this definition.\ndef auto_spec_nondet_bigint3 (mem : F → F) (κ : ℕ) (range_check_ptr ρ_range_check_ptr : F) (ρ_res : BigInt3 F) : Prop :=\n ∃ res : BigInt3 F,\n ∃ MAX_SUM : F, MAX_SUM = 232113757366008801543585789 ∧\n mem (range_check_ptr) = MAX_SUM - (res.d0 + res.d1 + res.d2) ∧\n is_range_checked (rc_bound F) (MAX_SUM - (res.d0 + res.d1 + res.d2)) ∧\n ∃ range_check_ptr₁ : F, range_check_ptr₁ = range_check_ptr + 4 ∧\n mem (range_check_ptr₁ - 3) = res.d0 ∧\n is_range_checked (rc_bound F) (res.d0) ∧\n mem (range_check_ptr₁ - 2) = res.d1 ∧\n is_range_checked (rc_bound F) (res.d1) ∧\n mem (range_check_ptr₁ - 1) = res.d2 ∧\n is_range_checked (rc_bound F) (res.d2) ∧\n 10 ≤ κ ∧\n ρ_range_check_ptr = range_check_ptr₁ ∧\n ρ_res = res\n\n-- You may change anything in this definition except the name and arguments.\ndef spec_nondet_bigint3 (mem : F → F) (κ : ℕ) (range_check_ptr ρ_range_check_ptr : F) (ρ_res : BigInt3 F) : Prop :=\n ∃ nd0 nd1 nd2 slack : ℕ,\n nd0 < rc_bound F ∧\n nd1 < rc_bound F ∧\n nd2 < rc_bound F ∧\n slack < rc_bound F ∧\n ρ_res = bigint3.toBigInt3 { i0 := nd0, i1 := nd1, i2 := nd2 } ∧\n nd0 + nd1 + nd2 + slack = 3 * (BASE - 1)\n\ntheorem nondet_bigint3_corr {mem : F → F} {k : ℕ} {range_check_ptr : F} {ret0 : F} {x : BigInt3 F}\n (h : spec_nondet_bigint3 mem k range_check_ptr ret0 x) :\n ∃ ix : bigint3, x = ix.toBigInt3 ∧ ix.bounded (3 * (BASE - 1)) :=\nbegin\n have BASEge1: 1 ≤ BASE, by { unfold BASE, norm_num1 },\n rcases h with ⟨nd0, nd1, nd2, _, _, _, _, _, xeq, sumeq⟩,\n refine ⟨_, xeq, _⟩,\n simp only [bigint3.bounded],\n have : (3 : ℤ) * (↑BASE - 1) = ↑(3 * (BASE - 1)),\n { rw [int.coe_nat_mul, int.coe_nat_sub BASEge1], simp },\n rw [this, ←sumeq], norm_cast, simp only [add_assoc],\n split, apply nat.le_add_right,\n split, apply le_trans (nat.le_add_right _ _) (nat.le_add_left _ _),\n apply le_trans _ (nat.le_add_left _ _),\n apply le_trans (nat.le_add_right _ _) (nat.le_add_left _ _),\nend\n\n/- nondet_bigint3 soundness theorem -/\n\n-- Do not change the statement of this theorem. You may change the proof.\ntheorem sound_nondet_bigint3\n {mem : F → F}\n (κ : ℕ)\n (range_check_ptr ρ_range_check_ptr : F) (ρ_res : BigInt3 F)\n (h_auto : auto_spec_nondet_bigint3 mem κ range_check_ptr ρ_range_check_ptr ρ_res) :\n spec_nondet_bigint3 mem κ range_check_ptr ρ_range_check_ptr ρ_res :=\nbegin\n rcases h_auto with ⟨res, MAX_SUM, MAX_SUM_eq,\n _, ⟨slack, slack_lt, slack_eq⟩,\n rp1, rp1eq,\n resd0eq,\n ⟨nd0, nd0_lt, nd0_eq⟩,\n resd1eq,\n ⟨nd1, nd1_lt, nd1_eq⟩,\n resd2eq,\n ⟨nd2, nd2_lt, nd2_eq⟩,\n _,\n rp1eq',\n reseq⟩,\n use [nd0, nd1, nd2, slack, nd0_lt, nd1_lt, nd2_lt, slack_lt],\n split, { rw reseq, ext; simp [bigint3.toBigInt3]; assumption },\n rw BASE, norm_num1,\n apply @PRIME.nat_coe_field_inj F,\n transitivity 4 * rc_bound F, linarith,\n apply lt_of_le_of_lt (mul_le_mul_left' (rc_bound_hyp F) 4),\n rw PRIME, norm_num1,\n rw PRIME, norm_num1,\n simp only [nat.cast_add, ←slack_eq, ←nd0_eq, ←nd1_eq, ←nd2_eq, add_sub_cancel'_right, nat.cast_bit0, nat.cast_bit1, nat.cast_one],\n rw MAX_SUM_eq\nend\n\n\nend starkware.cairo.common.cairo_secp.bigint\n", "meta": {"author": "starkware-libs", "repo": "formal-proofs", "sha": "35613c65b6715601bbc0a550d52754f8e7d93e30", "save_path": "github-repos/lean/starkware-libs-formal-proofs", "path": "github-repos/lean/starkware-libs-formal-proofs/formal-proofs-35613c65b6715601bbc0a550d52754f8e7d93e30/src/starkware/cairo/common/cairo_secp/bigint_spec.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.399811640739795, "lm_q2_score": 0.034618836349163955, "lm_q1q2_score": 0.013841013761261697}} {"text": "import Lean\nimport Duper.RuleM\n\n/- This code is copied from Lean's Discrimination Trees, but the support for\ndefinitional equality has been removed. -/\n\nnamespace Duper\n\nopen Lean\nopen RuleM\n\ninitialize Lean.registerTraceClass `DiscrTree.debug\n\ninductive Key where\n | const : Name → Nat → Key\n | fvar : FVarId → Nat → Key\n | lit : Literal → Key\n | star : Key\n | other : Key\n | arrow : Key\n | proj : Name → Nat → Key\n deriving Inhabited, BEq, Repr\n\nprotected def Key.hash : Key → UInt64\n | Key.const n a => mixHash 5237 $ mixHash (hash n) (hash a)\n | Key.fvar n a => mixHash 3541 (hash a) --$ mixHash (hash n) (hash a)\n | Key.lit v => mixHash 1879 $ hash v\n | Key.star => 7883\n | Key.other => 2411\n | Key.arrow => 17\n | Key.proj s i => mixHash 11 $ mixHash (hash s) (hash i)\n\ninstance : Hashable Key := ⟨Key.hash⟩\n\ninductive Trie (α : Type) where\n | node (vs : Array α) (children : Array (Key × Trie α)) : Trie α\n\n/- The filterSet argument is a temporary hack to simulate deletions from the discrimination tree. If that turns\n out to be too slow though, I'll have to remove it and rewrite delete to actually remove elements from the tree -/\nstructure DiscrTree (α : Type) where\n root : PersistentHashMap Key (Trie α) := {}\n filterSet : HashSet Clause := {} -- Keeps track of the set of clauses that should be filtered out (i.e. \"removed\" clauses)\n\ndef Key.ctorIdx : Key → Nat\n | Key.star => 0\n | Key.other => 1\n | Key.lit .. => 2\n | Key.fvar .. => 3\n | Key.const .. => 4\n | Key.arrow => 5\n | Key.proj .. => 6\n\ndef Key.lt : Key → Key → Bool\n | Key.lit v₁, Key.lit v₂ => v₁ < v₂\n | Key.fvar n₁ a₁, Key.fvar n₂ a₂ => a₁ < a₂ -- Name.quickLt n₁.name n₂.name || (n₁ == n₂ && a₁ < a₂)\n | Key.const n₁ a₁, Key.const n₂ a₂ => Name.quickLt n₁ n₂ || (n₁ == n₂ && a₁ < a₂)\n | Key.proj s₁ i₁, Key.proj s₂ i₂ => Name.quickLt s₁ s₂ || (s₁ == s₂ && i₁ < i₂)\n | k₁, k₂ => k₁.ctorIdx < k₂.ctorIdx\n\ninstance : LT Key := ⟨fun a b => Key.lt a b⟩\ninstance (a b : Key) : Decidable (a < b) := inferInstanceAs (Decidable (Key.lt a b))\n\ndef Key.format : Key → Format\n | Key.star => \"*\"\n | Key.other => \"◾\"\n | Key.lit (Literal.natVal v) => Std.format v\n | Key.lit (Literal.strVal v) => repr v\n | Key.const k _ => Std.format k\n | Key.proj s i => Std.format s ++ \".\" ++ Std.format i\n | Key.fvar k _ => Std.format k.name\n | Key.arrow => \"→\"\n\ninstance : ToFormat Key := ⟨Key.format⟩\n\ndef Key.arity : Key → Nat\n | Key.const _ a => a\n | Key.fvar _ a => a\n | Key.arrow => 2\n | Key.proj .. => 1\n | _ => 0\n\ninstance : Inhabited (Trie α) := ⟨Trie.node #[] #[]⟩\n\nnamespace DiscrTree\n\ndef empty : DiscrTree α := { root := {} }\n\npartial def Trie.format [ToMessageData α] : Trie α → MessageData\n | Trie.node vs cs => MessageData.group $ MessageData.paren $\n \"node\" ++ (if vs.isEmpty then MessageData.nil else \" \" ++ toMessageData vs)\n ++ MessageData.joinSep (cs.toList.map $ fun ⟨k, c⟩ => MessageData.paren (toMessageData k ++ \" => \" ++ format c)) \",\"\n\npartial def Trie.formatClause : Trie (Clause × α) → MessageData\n | Trie.node vs cs => MessageData.group $ MessageData.paren $\n \"node\" ++ (if vs.isEmpty then MessageData.nil else \" \" ++ toMessageData (Array.map (fun x => x.1) vs))\n ++ MessageData.joinSep (cs.toList.map $ fun ⟨k, c⟩ => MessageData.paren (toMessageData k ++ \" => \" ++ formatClause c)) \",\"\n\ninstance [ToMessageData α] : ToMessageData (Trie α) := ⟨Trie.format⟩\ninstance : ToMessageData (Trie (Clause × α)) := ⟨Trie.formatClause⟩\n\npartial def format [ToMessageData α] (d : DiscrTree α) : MessageData :=\n let (_, r) := d.root.foldl\n (fun (p : Bool × MessageData) k c =>\n (false, p.2 ++ MessageData.paren (toMessageData k ++ \" => \" ++ toMessageData c)))\n (true, Format.nil)\n MessageData.group r\n\npartial def formatClauses (d : DiscrTree (Clause × α)) : MessageData :=\n let (_, r) := d.root.foldl\n (fun (p : Bool × MessageData) k c =>\n (false, p.2 ++ MessageData.paren (toMessageData k ++ \" => \" ++ toMessageData c)))\n (true, Format.nil)\n MessageData.group r\n\ninstance [ToMessageData α] : ToMessageData (DiscrTree α) := ⟨fun dt => format dt⟩\n\n/- The discrimination tree ignores some implicit arguments and proofs.\n We use the following auxiliary id as a \"mark\". -/\nprivate def tmpMVarId : MVarId := { name := `_discr_tree_tmp }\nprivate def tmpStar := mkMVar tmpMVarId\n\ninstance : Inhabited (DiscrTree α) where\n default := {}\n\n/--\n Return true iff the argument should be treated as a \"wildcard\" by the discrimination tree.\n\n - We ignore proofs because of proof irrelevance. It doesn't make sense to try to\n index their structure.\n\n - We ignore instance implicit arguments (e.g., `[Add α]`) because they are \"morally\" canonical.\n Moreover, we may have many definitionally equal terms floating around.\n Example: `Ring.hasAdd Int Int.isRing` and `Int.hasAdd`.\n\n - We considered ignoring implicit arguments (e.g., `{α : Type}`) since users don't \"see\" them,\n and may not even understand why some simplification rule is not firing.\n However, in type class resolution, we have instance such as `Decidable (@Eq Nat x y)`,\n where `Nat` is an implicit argument. Thus, we would add the path\n ```\n Decidable -> Eq -> * -> * -> * -> [Nat.decEq]\n ```\n to the discrimination tree IF we ignored the implict `Nat` argument.\n This would be BAD since **ALL** decidable equality instances would be in the same path.\n So, we index implicit arguments if they are types.\n This setting seems sensible for simplification lemmas such as:\n ```\n forall (x y : Unit), (@Eq Unit x y) = true\n ```\n If we ignore the implicit argument `Unit`, the `DiscrTree` will say it is a candidate\n simplification lemma for any equality in our goal.\n\n Remark: if users have problems with the solution above, we may provide a `noIndexing` annotation,\n and `ignoreArg` would return true for any term of the form `noIndexing t`.\n\n Duper modification remark: The check of isProof has been removed and replaced with return false under the\n assumption that proofs won't be collected by the `collectAssumptions` function in Tactic.lean to begin with\n (additionally, attempting to actually call isProof is problematic because duper can attempt to index\n expressions that have escaped bound variables, which will cause isProof to panic)\n-/\nprivate def ignoreArg (a : Expr) (i : Nat) (infos : Array Meta.ParamInfo) : RuleM Bool := do\n if h : i < infos.size then\n let info := infos.get ⟨i, h⟩\n if info.isInstImplicit then\n return true\n else if info.isImplicit || info.isStrictImplicit then\n return not (← Meta.isType a)\n else\n return false -- Previously: isProof a\n else\n return false -- Previously: isProof a\n\nprivate partial def pushArgsAux (infos : Array Meta.ParamInfo) : Nat → Expr → Array Expr → RuleM (Array Expr)\n | i, Expr.app f a, todo => do\n if (← ignoreArg a i infos) then\n pushArgsAux infos (i-1) f (todo.push tmpStar)\n else\n pushArgsAux infos (i-1) f (todo.push a)\n | _, _, todo => return todo\n\ndef mkNoindexAnnotation (e : Expr) : Expr :=\n mkAnnotation `noindex e\n\ndef hasNoindexAnnotation (e : Expr) : Bool :=\n annotation? `noindex e |>.isSome\n\nprivate def pushArgs (root : Bool) (todo : Array Expr) (e : Expr) : RuleM (Key × Array Expr) := do\n if hasNoindexAnnotation e then\n return (Key.star, todo)\n else\n let fn := e.getAppFn\n let push (k : Key) (nargs : Nat) : RuleM (Key × Array Expr) := do\n let info ← Meta.getFunInfoNArgs fn nargs\n let todo ← pushArgsAux info.paramInfo (nargs-1) e todo\n return (k, todo)\n match fn with\n | Expr.lit v => return (Key.lit v, todo)\n | Expr.const c _ =>\n let nargs := e.getAppNumArgs\n push (Key.const c nargs) nargs\n | Expr.proj s i a .. =>\n return (Key.proj s i, todo.push a)\n | Expr.fvar fvarId =>\n let nargs := e.getAppNumArgs\n push (Key.fvar fvarId nargs) nargs\n | Expr.mvar mvarId =>\n if mvarId == tmpMVarId then\n -- We use `tmp to mark some implicit arguments and proofs\n return (Key.star, todo)\n else\n return (Key.star, todo)\n | Expr.forallE _ d b _ =>\n if b.hasLooseBVars then\n return (Key.other, todo)\n else\n return (Key.arrow, todo.push d |>.push b)\n | _ =>\n return (Key.other, todo)\n\npartial def mkPathAux (root : Bool) (todo : Array Expr) (keys : Array Key) : RuleM (Array Key) := do\n if todo.isEmpty then\n return keys\n else\n let e := todo.back\n let todo := todo.pop\n let (k, todo) ← pushArgs root todo e\n mkPathAux false todo (keys.push k)\n\nprivate def initCapacity := 8\n\ndef mkPath (e : Expr) : RuleM (Array Key) := do\n let todo : Array Expr := Array.mkEmpty initCapacity\n let keys : Array Key := Array.mkEmpty initCapacity\n mkPathAux (root := true) (todo.push e) keys\n\nprivate partial def createNodes (keys : Array Key) (v : α) (i : Nat) : Trie α :=\n if h : i < keys.size then\n let k := keys.get ⟨i, h⟩\n let c := createNodes keys v (i+1)\n Trie.node #[] #[(k, c)]\n else\n Trie.node #[v] #[]\n\nprivate def insertVal [BEq α] (vs : Array α) (v : α) : Array α :=\n if vs.contains v then vs else vs.push v\n\nprivate partial def insertAux [BEq α] (keys : Array Key) (v : α) : Nat → Trie α → Trie α\n | i, Trie.node vs cs =>\n if h : i < keys.size then\n let k := keys.get ⟨i, h⟩\n let c := Id.run $ cs.binInsertM\n (fun a b => a.1 < b.1)\n (fun ⟨_, s⟩ => let c := insertAux keys v (i+1) s; (k, c)) -- merge with existing\n (fun _ => let c := createNodes keys v (i+1); (k, c))\n (k, default)\n Trie.node vs c\n else\n Trie.node (insertVal vs v) cs\n\ndef insertCore [BEq α] (d : DiscrTree α) (keys : Array Key) (v : α) : DiscrTree α :=\n if keys.isEmpty then panic! \"invalid key sequence\"\n else\n let k := keys[0]!\n match d.root.find? k with\n | none =>\n let c := createNodes keys v 1\n { d with root := d.root.insert k c }\n | some c =>\n let c := insertAux keys v 1 c\n { d with root := d.root.insert k c }\n\n/- Original, more general insert code for discrimination trees\ndef insert [BEq α] (d : DiscrTree α) (e : Expr) (v : α) : RuleM (DiscrTree α) := do\n let keys ← mkPath e\n return d.insertCore keys v\n-/\n\ndef insert [BEq α] (d : DiscrTree (Clause × α)) (e : Expr) (v : (Clause × α)) : RuleM (DiscrTree (Clause × α)) := do\n let keys ← mkPath e\n let d := {d with filterSet := d.filterSet.erase v.1} -- In case if v.1 was previously removed, erase v.1 from d.filterSet\n return d.insertCore keys v\n\nprivate def getKeyArgs (e : Expr) (isMatch root : Bool) : RuleM (Key × Array Expr) := do\n match e.getAppFn with\n | Expr.lit v => return (Key.lit v, #[])\n | Expr.const c _ =>\n let nargs := e.getAppNumArgs\n return (Key.const c nargs, e.getAppRevArgs)\n | Expr.fvar fvarId =>\n let nargs := e.getAppNumArgs\n return (Key.fvar fvarId nargs, e.getAppRevArgs)\n | Expr.mvar _ =>\n if isMatch then\n return (Key.other, #[])\n else do\n return (Key.star, #[])\n | Expr.proj s i a .. =>\n return (Key.proj s i, #[a])\n | Expr.forallE _ d b _ =>\n if b.hasLooseBVars then\n return (Key.other, #[])\n else\n return (Key.arrow, #[d, b])\n | _ =>\n return (Key.other, #[])\n\nprivate abbrev getMatchKeyArgs (e : Expr) (root : Bool) : RuleM (Key × Array Expr) :=\n getKeyArgs e (isMatch := true) (root := root)\n\nprivate abbrev getUnifyKeyArgs (e : Expr) (root : Bool) : RuleM (Key × Array Expr) :=\n getKeyArgs e (isMatch := false) (root := root)\n\nprivate def getStarResult (d : DiscrTree α) : Array α :=\n let result : Array α := Array.mkEmpty initCapacity\n match d.root.find? Key.star with\n | none => result\n | some (Trie.node vs _) => result ++ vs\n\nprivate abbrev findKey (cs : Array (Key × Trie α)) (k : Key) : Option (Key × Trie α) :=\n cs.binSearch (k, default) (fun a b => a.1 < b.1)\n\nprivate partial def getMatchLoop (todo : Array Expr) (c : Trie α) (result : Array α) : RuleM (Array α) := do\n match c with\n | Trie.node vs cs =>\n if todo.isEmpty then\n return result ++ vs\n else if cs.isEmpty then\n return result\n else\n let e := todo.back\n let todo := todo.pop\n let first := cs[0]! /- Recall that `Key.star` is the minimal key -/\n let (k, args) ← getMatchKeyArgs e (root := false)\n /- We must always visit `Key.star` edges since they are wildcards.\n Thus, `todo` is not used linearly when there is `Key.star` edge\n and there is an edge for `k` and `k != Key.star`. -/\n let visitStar (result : Array α) : RuleM (Array α) :=\n if first.1 == Key.star then\n getMatchLoop todo first.2 result\n else\n return result\n let visitNonStar (k : Key) (args : Array Expr) (result : Array α) : RuleM (Array α) :=\n match findKey cs k with\n | none => return result\n | some c => getMatchLoop (todo ++ args) c.2 result\n let result ← visitStar result\n match k with\n | Key.star => return result\n /-\n Recall that dependent arrows are `(Key.other, #[])`, and non-dependent arrows are `(Key.arrow, #[a, b])`.\n A non-dependent arrow may be an instance of a dependent arrow (stored at `DiscrTree`). Thus, we also visit the `Key.other` child.\n -/\n | Key.arrow => visitNonStar Key.other #[] (← visitNonStar k args result)\n | _ => visitNonStar k args result\n\nprivate def getMatchRoot (d : DiscrTree α) (k : Key) (args : Array Expr) (result : Array α) : RuleM (Array α) :=\n match d.root.find? k with\n | none => return result\n | some c => getMatchLoop args c result\n\nprivate partial def getMatch' (d : DiscrTree α) (e : Expr) : RuleM (Array α) := do\n Core.checkMaxHeartbeats \"getMatch\"\n let result := getStarResult d\n let (k, args) ← getMatchKeyArgs e (root := true)\n match k with\n | Key.star => return result\n | _ => getMatchRoot d k args result\n\n/-- Find values that match `e` in `d`. -/\npartial def getMatch (d : DiscrTree (Clause × α)) (e : Expr) : RuleM (Array (Clause × α)) := do\n let unfiltered_result ← getMatch' d e\n let filterSet := d.filterSet\n return Array.filter (fun c => not (filterSet.contains c.1)) unfiltered_result\n\nprivate partial def getUnify' (d : DiscrTree α) (e : Expr) : RuleM (Array α) := do\n Core.checkMaxHeartbeats \"getUnify\"\n let (k, args) ← getUnifyKeyArgs e (root := true)\n match k with\n | Key.star => d.root.foldlM (init := #[]) fun result k c => process k.arity #[] c result\n | _ =>\n let result := getStarResult d\n match d.root.find? k with\n | none => return result\n | some c => process 0 args c result\nwhere\n process (skip : Nat) (todo : Array Expr) (c : Trie α) (result : Array α) : RuleM (Array α) := do\n match skip, c with\n | skip+1, Trie.node vs cs =>\n if cs.isEmpty then\n return result\n else\n cs.foldlM (init := result) fun result ⟨k, c⟩ => process (skip + k.arity) todo c result\n | 0, Trie.node vs cs => do\n if todo.isEmpty then\n return result ++ vs\n else if cs.isEmpty then\n return result\n else\n let e := todo.back\n let todo := todo.pop\n let (k, args) ← getUnifyKeyArgs e (root := false)\n let visitStar (result : Array α) : RuleM (Array α) :=\n let first := cs[0]!\n if first.1 == Key.star then\n process 0 todo first.2 result\n else\n return result\n let visitNonStar (k : Key) (args : Array Expr) (result : Array α) : RuleM (Array α) :=\n match findKey cs k with\n | none => return result\n | some c => process 0 (todo ++ args) c.2 result\n match k with\n | Key.star => cs.foldlM (init := result) fun result ⟨k, c⟩ => process k.arity todo c result\n -- See comment a `getMatch` regarding non-dependent arrows vs dependent arrows\n | Key.arrow => visitNonStar Key.other #[] (← visitNonStar k args (← visitStar result))\n | _ => visitNonStar k args (← visitStar result)\n\npartial def getUnify (d : DiscrTree (Clause × α)) (e : Expr) : RuleM (Array (Clause × α)) := do\n let unfiltered_result ← getUnify' d e\n let filterSet := d.filterSet\n return Array.filter (fun c => not (filterSet.contains c.1)) unfiltered_result\n\ndef delete (d : DiscrTree α) (c : Clause) : RuleM (DiscrTree α) := do\n let root := d.root\n let filterSet := d.filterSet.insert c\n return { root := root, filterSet := filterSet }\n\nend DiscrTree\nend Duper\n\n\n\n", "meta": {"author": "leanprover-community", "repo": "duper", "sha": "96b8f8383363e800976b0fa99830c1b5e8c19b09", "save_path": "github-repos/lean/leanprover-community-duper", "path": "github-repos/lean/leanprover-community-duper/duper-96b8f8383363e800976b0fa99830c1b5e8c19b09/Duper/DiscrTree.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.35936414516010196, "lm_q2_score": 0.038466187746970484, "lm_q1q2_score": 0.013823368677258037}} {"text": "/-\nCopyright (c) 2016 Johannes Hölzl. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Johannes Hölzl, Mario Carneiro\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.default\nimport Mathlib.logic.basic\nimport Mathlib.data.option.defs\nimport Mathlib.PostPort\n\nuniverses u_1 u_2 u v w u_3 u_4 u_5 u_6 u_7 l \n\nnamespace Mathlib\n\n/-!\n# Miscellaneous function constructions and lemmas\n-/\n\nnamespace function\n\n\n/-- Evaluate a function at an argument. Useful if you want to talk about the partially applied\n `function.eval x : (Π x, β x) → β x`. -/\ndef eval {α : Sort u_1} {β : α → Sort u_2} (x : α) (f : (x : α) → β x) : β x :=\n f x\n\n@[simp] theorem eval_apply {α : Sort u_1} {β : α → Sort u_2} (x : α) (f : (x : α) → β x) : eval x f = f x :=\n rfl\n\ntheorem comp_apply {α : Sort u} {β : Sort v} {φ : Sort w} (f : β → φ) (g : α → β) (a : α) : comp f g a = f (g a) :=\n rfl\n\ntheorem const_def {α : Sort u_1} {β : Sort u_2} {y : β} : (fun (x : α) => y) = const α y :=\n rfl\n\n@[simp] theorem const_apply {α : Sort u_1} {β : Sort u_2} {y : β} {x : α} : const α y x = y :=\n rfl\n\n@[simp] theorem const_comp {α : Sort u_1} {β : Sort u_2} {γ : Sort u_3} {f : α → β} {c : γ} : const β c ∘ f = const α c :=\n rfl\n\n@[simp] theorem comp_const {α : Sort u_1} {β : Sort u_2} {γ : Sort u_3} {f : β → γ} {b : β} : f ∘ const α b = const α (f b) :=\n rfl\n\ntheorem id_def {α : Sort u_1} : id = fun (x : α) => x :=\n rfl\n\ntheorem hfunext {α : Sort u} {α' : Sort u} {β : α → Sort v} {β' : α' → Sort v} {f : (a : α) → β a} {f' : (a : α') → β' a} (hα : α = α') (h : ∀ (a : α) (a' : α'), a == a' → f a == f' a') : f == f' := sorry\n\ntheorem funext_iff {α : Sort u_1} {β : α → Sort u_2} {f₁ : (x : α) → β x} {f₂ : (x : α) → β x} : f₁ = f₂ ↔ ∀ (a : α), f₁ a = f₂ a :=\n { mp := fun (h : f₁ = f₂) (a : α) => h ▸ rfl, mpr := funext }\n\n@[simp] theorem injective.eq_iff {α : Sort u_1} {β : Sort u_2} {f : α → β} (I : injective f) {a : α} {b : α} : f a = f b ↔ a = b :=\n { mp := I, mpr := congr_arg f }\n\ntheorem injective.eq_iff' {α : Sort u_1} {β : Sort u_2} {f : α → β} (I : injective f) {a : α} {b : α} {c : β} (h : f b = c) : f a = c ↔ a = b :=\n h ▸ injective.eq_iff I\n\ntheorem injective.ne {α : Sort u_1} {β : Sort u_2} {f : α → β} (hf : injective f) {a₁ : α} {a₂ : α} : a₁ ≠ a₂ → f a₁ ≠ f a₂ :=\n mt fun (h : f a₁ = f a₂) => hf h\n\ntheorem injective.ne_iff {α : Sort u_1} {β : Sort u_2} {f : α → β} (hf : injective f) {x : α} {y : α} : f x ≠ f y ↔ x ≠ y :=\n { mp := mt (congr_arg f), mpr := injective.ne hf }\n\ntheorem injective.ne_iff' {α : Sort u_1} {β : Sort u_2} {f : α → β} (hf : injective f) {x : α} {y : α} {z : β} (h : f y = z) : f x ≠ z ↔ x ≠ y :=\n h ▸ injective.ne_iff hf\n\n/-- If the co-domain `β` of an injective function `f : α → β` has decidable equality, then\nthe domain `α` also has decidable equality. -/\ndef injective.decidable_eq {α : Sort u_1} {β : Sort u_2} {f : α → β} [DecidableEq β] (I : injective f) : DecidableEq α :=\n fun (a b : α) => decidable_of_iff (f a = f b) (injective.eq_iff I)\n\ntheorem injective.of_comp {α : Sort u_1} {β : Sort u_2} {γ : Sort u_3} {f : α → β} {g : γ → α} (I : injective (f ∘ g)) : injective g :=\n fun (x y : γ) (h : g x = g y) => I ((fun (this : f (g x) = f (g y)) => this) (congr_arg f h))\n\ntheorem surjective.of_comp {α : Sort u_1} {β : Sort u_2} {γ : Sort u_3} {f : α → β} {g : γ → α} (S : surjective (f ∘ g)) : surjective f := sorry\n\nprotected instance decidable_eq_pfun (p : Prop) [Decidable p] (α : p → Type u_1) [(hp : p) → DecidableEq (α hp)] : DecidableEq ((hp : p) → α hp) :=\n sorry\n\ntheorem surjective.forall {α : Sort u_1} {β : Sort u_2} {f : α → β} (hf : surjective f) {p : β → Prop} : (∀ (y : β), p y) ↔ ∀ (x : α), p (f x) := sorry\n\ntheorem surjective.forall₂ {α : Sort u_1} {β : Sort u_2} {f : α → β} (hf : surjective f) {p : β → β → Prop} : (∀ (y₁ y₂ : β), p y₁ y₂) ↔ ∀ (x₁ x₂ : α), p (f x₁) (f x₂) :=\n iff.trans (surjective.forall hf) (forall_congr fun (x : α) => surjective.forall hf)\n\ntheorem surjective.forall₃ {α : Sort u_1} {β : Sort u_2} {f : α → β} (hf : surjective f) {p : β → β → β → Prop} : (∀ (y₁ y₂ y₃ : β), p y₁ y₂ y₃) ↔ ∀ (x₁ x₂ x₃ : α), p (f x₁) (f x₂) (f x₃) :=\n iff.trans (surjective.forall hf) (forall_congr fun (x : α) => surjective.forall₂ hf)\n\ntheorem surjective.exists {α : Sort u_1} {β : Sort u_2} {f : α → β} (hf : surjective f) {p : β → Prop} : (∃ (y : β), p y) ↔ ∃ (x : α), p (f x) := sorry\n\ntheorem surjective.exists₂ {α : Sort u_1} {β : Sort u_2} {f : α → β} (hf : surjective f) {p : β → β → Prop} : (∃ (y₁ : β), ∃ (y₂ : β), p y₁ y₂) ↔ ∃ (x₁ : α), ∃ (x₂ : α), p (f x₁) (f x₂) :=\n iff.trans (surjective.exists hf) (exists_congr fun (x : α) => surjective.exists hf)\n\ntheorem surjective.exists₃ {α : Sort u_1} {β : Sort u_2} {f : α → β} (hf : surjective f) {p : β → β → β → Prop} : (∃ (y₁ : β), ∃ (y₂ : β), ∃ (y₃ : β), p y₁ y₂ y₃) ↔ ∃ (x₁ : α), ∃ (x₂ : α), ∃ (x₃ : α), p (f x₁) (f x₂) (f x₃) :=\n iff.trans (surjective.exists hf) (exists_congr fun (x : α) => surjective.exists₂ hf)\n\n/-- Cantor's diagonal argument implies that there are no surjective functions from `α`\nto `set α`. -/\ntheorem cantor_surjective {α : Type u_1} (f : α → set α) : ¬surjective f := sorry\n\n/-- Cantor's diagonal argument implies that there are no injective functions from `set α` to `α`. -/\ntheorem cantor_injective {α : Type u_1} (f : set α → α) : ¬injective f := sorry\n\n/-- `g` is a partial inverse to `f` (an injective but not necessarily\n surjective function) if `g y = some x` implies `f x = y`, and `g y = none`\n implies that `y` is not in the range of `f`. -/\ndef is_partial_inv {α : Type u_1} {β : Sort u_2} (f : α → β) (g : β → Option α) :=\n ∀ (x : α) (y : β), g y = some x ↔ f x = y\n\ntheorem is_partial_inv_left {α : Type u_1} {β : Sort u_2} {f : α → β} {g : β → Option α} (H : is_partial_inv f g) (x : α) : g (f x) = some x :=\n iff.mpr (H x (f x)) rfl\n\ntheorem injective_of_partial_inv {α : Type u_1} {β : Sort u_2} {f : α → β} {g : β → Option α} (H : is_partial_inv f g) : injective f :=\n fun (a b : α) (h : f a = f b) => option.some.inj (Eq.trans (Eq.symm (iff.mpr (H a (f b)) h)) (iff.mpr (H b (f b)) rfl))\n\ntheorem injective_of_partial_inv_right {α : Type u_1} {β : Sort u_2} {f : α → β} {g : β → Option α} (H : is_partial_inv f g) (x : β) (y : β) (b : α) (h₁ : b ∈ g x) (h₂ : b ∈ g y) : x = y :=\n Eq.trans (Eq.symm (iff.mp (H b x) h₁)) (iff.mp (H b y) h₂)\n\ntheorem left_inverse.comp_eq_id {α : Sort u_1} {β : Sort u_2} {f : α → β} {g : β → α} (h : left_inverse f g) : f ∘ g = id :=\n funext h\n\ntheorem left_inverse_iff_comp {α : Sort u_1} {β : Sort u_2} {f : α → β} {g : β → α} : left_inverse f g ↔ f ∘ g = id :=\n { mp := left_inverse.comp_eq_id, mpr := congr_fun }\n\ntheorem right_inverse.comp_eq_id {α : Sort u_1} {β : Sort u_2} {f : α → β} {g : β → α} (h : right_inverse f g) : g ∘ f = id :=\n funext h\n\ntheorem right_inverse_iff_comp {α : Sort u_1} {β : Sort u_2} {f : α → β} {g : β → α} : right_inverse f g ↔ g ∘ f = id :=\n { mp := right_inverse.comp_eq_id, mpr := congr_fun }\n\ntheorem left_inverse.comp {α : Sort u_1} {β : Sort u_2} {γ : Sort u_3} {f : α → β} {g : β → α} {h : β → γ} {i : γ → β} (hf : left_inverse f g) (hh : left_inverse h i) : left_inverse (h ∘ f) (g ∘ i) := sorry\n\ntheorem right_inverse.comp {α : Sort u_1} {β : Sort u_2} {γ : Sort u_3} {f : α → β} {g : β → α} {h : β → γ} {i : γ → β} (hf : right_inverse f g) (hh : right_inverse h i) : right_inverse (h ∘ f) (g ∘ i) :=\n left_inverse.comp hh hf\n\ntheorem left_inverse.right_inverse {α : Sort u_1} {β : Sort u_2} {f : α → β} {g : β → α} (h : left_inverse g f) : right_inverse f g :=\n h\n\ntheorem right_inverse.left_inverse {α : Sort u_1} {β : Sort u_2} {f : α → β} {g : β → α} (h : right_inverse g f) : left_inverse f g :=\n h\n\ntheorem left_inverse.surjective {α : Sort u_1} {β : Sort u_2} {f : α → β} {g : β → α} (h : left_inverse f g) : surjective f :=\n right_inverse.surjective (left_inverse.right_inverse h)\n\ntheorem right_inverse.injective {α : Sort u_1} {β : Sort u_2} {f : α → β} {g : β → α} (h : right_inverse f g) : injective f :=\n left_inverse.injective (right_inverse.left_inverse h)\n\ntheorem left_inverse.eq_right_inverse {α : Sort u_1} {β : Sort u_2} {f : α → β} {g₁ : β → α} {g₂ : β → α} (h₁ : left_inverse g₁ f) (h₂ : right_inverse g₂ f) : g₁ = g₂ := sorry\n\n/-- We can use choice to construct explicitly a partial inverse for\n a given injective function `f`. -/\ndef partial_inv {α : Type u_1} {β : Sort u_2} (f : α → β) (b : β) : Option α :=\n dite (∃ (a : α), f a = b) (fun (h : ∃ (a : α), f a = b) => some (classical.some h))\n fun (h : ¬∃ (a : α), f a = b) => none\n\ntheorem partial_inv_of_injective {α : Type u_1} {β : Sort u_2} {f : α → β} (I : injective f) : is_partial_inv f (partial_inv f) := sorry\n\ntheorem partial_inv_left {α : Type u_1} {β : Sort u_2} {f : α → β} (I : injective f) (x : α) : partial_inv f (f x) = some x :=\n is_partial_inv_left (partial_inv_of_injective I)\n\n/-- Construct the inverse for a function `f` on domain `s`. This function is a right inverse of `f`\non `f '' s`. -/\ndef inv_fun_on {α : Type u} [n : Nonempty α] {β : Sort v} (f : α → β) (s : set α) (b : β) : α :=\n dite (∃ (a : α), a ∈ s ∧ f a = b) (fun (h : ∃ (a : α), a ∈ s ∧ f a = b) => classical.some h)\n fun (h : ¬∃ (a : α), a ∈ s ∧ f a = b) => Classical.choice n\n\ntheorem inv_fun_on_pos {α : Type u} [n : Nonempty α] {β : Sort v} {f : α → β} {s : set α} {b : β} (h : ∃ (a : α), ∃ (H : a ∈ s), f a = b) : inv_fun_on f s b ∈ s ∧ f (inv_fun_on f s b) = b := sorry\n\ntheorem inv_fun_on_mem {α : Type u} [n : Nonempty α] {β : Sort v} {f : α → β} {s : set α} {b : β} (h : ∃ (a : α), ∃ (H : a ∈ s), f a = b) : inv_fun_on f s b ∈ s :=\n and.left (inv_fun_on_pos h)\n\ntheorem inv_fun_on_eq {α : Type u} [n : Nonempty α] {β : Sort v} {f : α → β} {s : set α} {b : β} (h : ∃ (a : α), ∃ (H : a ∈ s), f a = b) : f (inv_fun_on f s b) = b :=\n and.right (inv_fun_on_pos h)\n\ntheorem inv_fun_on_eq' {α : Type u} [n : Nonempty α] {β : Sort v} {f : α → β} {s : set α} {a : α} (h : ∀ (x : α), x ∈ s → ∀ (y : α), y ∈ s → f x = f y → x = y) (ha : a ∈ s) : inv_fun_on f s (f a) = a :=\n (fun (this : ∃ (a' : α), ∃ (H : a' ∈ s), f a' = f a) =>\n h (inv_fun_on (fun (a' : α) => f a') s (f a)) (inv_fun_on_mem this) a ha (inv_fun_on_eq this))\n (Exists.intro a (Exists.intro ha rfl))\n\ntheorem inv_fun_on_neg {α : Type u} [n : Nonempty α] {β : Sort v} {f : α → β} {s : set α} {b : β} (h : ¬∃ (a : α), ∃ (H : a ∈ s), f a = b) : inv_fun_on f s b = Classical.choice n := sorry\n\n/-- The inverse of a function (which is a left inverse if `f` is injective\n and a right inverse if `f` is surjective). -/\ndef inv_fun {α : Type u} [n : Nonempty α] {β : Sort v} (f : α → β) : β → α :=\n inv_fun_on f set.univ\n\ntheorem inv_fun_eq {α : Type u} [n : Nonempty α] {β : Sort v} {f : α → β} {b : β} (h : ∃ (a : α), f a = b) : f (inv_fun f b) = b := sorry\n\ntheorem inv_fun_neg {α : Type u} [n : Nonempty α] {β : Sort v} {f : α → β} {b : β} (h : ¬∃ (a : α), f a = b) : inv_fun f b = Classical.choice n := sorry\n\ntheorem inv_fun_eq_of_injective_of_right_inverse {α : Type u} [n : Nonempty α] {β : Sort v} {f : α → β} {g : β → α} (hf : injective f) (hg : right_inverse g f) : inv_fun f = g :=\n funext\n fun (b : β) =>\n hf (eq.mpr (id (Eq._oldrec (Eq.refl (f (inv_fun f b) = f (g b))) (hg b))) (inv_fun_eq (Exists.intro (g b) (hg b))))\n\ntheorem right_inverse_inv_fun {α : Type u} [n : Nonempty α] {β : Sort v} {f : α → β} (hf : surjective f) : right_inverse (inv_fun f) f :=\n fun (b : β) => inv_fun_eq (hf b)\n\ntheorem left_inverse_inv_fun {α : Type u} [n : Nonempty α] {β : Sort v} {f : α → β} (hf : injective f) : left_inverse (inv_fun f) f :=\n fun (b : α) => (fun (this : f (inv_fun f (f b)) = f b) => hf this) (inv_fun_eq (Exists.intro b rfl))\n\ntheorem inv_fun_surjective {α : Type u} [n : Nonempty α] {β : Sort v} {f : α → β} (hf : injective f) : surjective (inv_fun f) :=\n left_inverse.surjective (left_inverse_inv_fun hf)\n\ntheorem inv_fun_comp {α : Type u} [n : Nonempty α] {β : Sort v} {f : α → β} (hf : injective f) : inv_fun f ∘ f = id :=\n funext (left_inverse_inv_fun hf)\n\ntheorem injective.has_left_inverse {α : Type u} [i : Nonempty α] {β : Sort v} {f : α → β} (hf : injective f) : has_left_inverse f :=\n Exists.intro (inv_fun f) (left_inverse_inv_fun hf)\n\ntheorem injective_iff_has_left_inverse {α : Type u} [i : Nonempty α] {β : Sort v} {f : α → β} : injective f ↔ has_left_inverse f :=\n { mp := injective.has_left_inverse, mpr := has_left_inverse.injective }\n\n/-- The inverse of a surjective function. (Unlike `inv_fun`, this does not require\n `α` to be inhabited.) -/\ndef surj_inv {α : Sort u} {β : Sort v} {f : α → β} (h : surjective f) (b : β) : α :=\n classical.some (h b)\n\ntheorem surj_inv_eq {α : Sort u} {β : Sort v} {f : α → β} (h : surjective f) (b : β) : f (surj_inv h b) = b :=\n classical.some_spec (h b)\n\ntheorem right_inverse_surj_inv {α : Sort u} {β : Sort v} {f : α → β} (hf : surjective f) : right_inverse (surj_inv hf) f :=\n surj_inv_eq hf\n\ntheorem left_inverse_surj_inv {α : Sort u} {β : Sort v} {f : α → β} (hf : bijective f) : left_inverse (surj_inv (and.right hf)) f :=\n right_inverse_of_injective_of_left_inverse (and.left hf) (right_inverse_surj_inv (and.right hf))\n\ntheorem surjective.has_right_inverse {α : Sort u} {β : Sort v} {f : α → β} (hf : surjective f) : has_right_inverse f :=\n Exists.intro (surj_inv hf) (right_inverse_surj_inv hf)\n\ntheorem surjective_iff_has_right_inverse {α : Sort u} {β : Sort v} {f : α → β} : surjective f ↔ has_right_inverse f :=\n { mp := surjective.has_right_inverse, mpr := has_right_inverse.surjective }\n\ntheorem bijective_iff_has_inverse {α : Sort u} {β : Sort v} {f : α → β} : bijective f ↔ ∃ (g : β → α), left_inverse g f ∧ right_inverse g f := sorry\n\ntheorem injective_surj_inv {α : Sort u} {β : Sort v} {f : α → β} (h : surjective f) : injective (surj_inv h) :=\n right_inverse.injective (right_inverse_surj_inv h)\n\n/-- Replacing the value of a function at a given point by a given value. -/\ndef update {α : Sort u} {β : α → Sort v} [DecidableEq α] (f : (a : α) → β a) (a' : α) (v : β a') (a : α) : β a :=\n dite (a = a') (fun (h : a = a') => Eq._oldrec v (Eq.symm h)) fun (h : ¬a = a') => f a\n\n/-- On non-dependent functions, `function.update` can be expressed as an `ite` -/\ntheorem update_apply {α : Sort u} [DecidableEq α] {β : Sort u_1} (f : α → β) (a' : α) (b : β) (a : α) : update f a' b a = ite (a = a') b (f a) := sorry\n\n@[simp] theorem update_same {α : Sort u} {β : α → Sort v} [DecidableEq α] (a : α) (v : β a) (f : (a : α) → β a) : update f a v a = v :=\n dif_pos rfl\n\ntheorem update_injective {α : Sort u} {β : α → Sort v} [DecidableEq α] (f : (a : α) → β a) (a' : α) : injective (update f a') := sorry\n\n@[simp] theorem update_noteq {α : Sort u} {β : α → Sort v} [DecidableEq α] {a : α} {a' : α} (h : a ≠ a') (v : β a') (f : (a : α) → β a) : update f a' v a = f a :=\n dif_neg h\n\ntheorem forall_update_iff {α : Sort u} {β : α → Sort v} [DecidableEq α] (f : (a : α) → β a) {a : α} {b : β a} (p : (a : α) → β a → Prop) : (∀ (x : α), p x (update f a b x)) ↔ p a b ∧ ∀ (x : α), x ≠ a → p x (f x) := sorry\n\ntheorem update_eq_iff {α : Sort u} {β : α → Sort v} [DecidableEq α] {a : α} {b : β a} {f : (a : α) → β a} {g : (a : α) → β a} : update f a b = g ↔ b = g a ∧ ∀ (x : α), x ≠ a → f x = g x :=\n iff.trans funext_iff (forall_update_iff f fun (x : α) (y : β x) => y = g x)\n\ntheorem eq_update_iff {α : Sort u} {β : α → Sort v} [DecidableEq α] {a : α} {b : β a} {f : (a : α) → β a} {g : (a : α) → β a} : g = update f a b ↔ g a = b ∧ ∀ (x : α), x ≠ a → g x = f x :=\n iff.trans funext_iff (forall_update_iff f fun (x : α) (y : β x) => g x = y)\n\n@[simp] theorem update_eq_self {α : Sort u} {β : α → Sort v} [DecidableEq α] (a : α) (f : (a : α) → β a) : update f a (f a) = f :=\n iff.mpr update_eq_iff { left := rfl, right := fun (_x : α) (_x_1 : _x ≠ a) => rfl }\n\ntheorem update_comp_eq_of_forall_ne' {α : Sort u} {β : α → Sort v} [DecidableEq α] {α' : Sort u_1} (g : (a : α) → β a) {f : α' → α} {i : α} (a : β i) (h : ∀ (x : α'), f x ≠ i) : (fun (j : α') => update g i a (f j)) = fun (j : α') => g (f j) :=\n funext fun (x : α') => update_noteq (h x) a g\n\n/-- Non-dependent version of `function.update_comp_eq_of_forall_ne'` -/\ntheorem update_comp_eq_of_forall_ne {α' : Sort w} [DecidableEq α'] {α : Sort u_1} {β : Sort u_2} (g : α' → β) {f : α → α'} {i : α'} (a : β) (h : ∀ (x : α), f x ≠ i) : update g i a ∘ f = g ∘ f :=\n update_comp_eq_of_forall_ne' g a h\n\ntheorem update_comp_eq_of_injective' {α : Sort u} {β : α → Sort v} {α' : Sort w} [DecidableEq α] [DecidableEq α'] (g : (a : α) → β a) {f : α' → α} (hf : injective f) (i : α') (a : β (f i)) : (fun (j : α') => update g (f i) a (f j)) = update (fun (i : α') => g (f i)) i a :=\n iff.mpr eq_update_iff\n { left := update_same (f i) a g, right := fun (j : α') (hj : j ≠ i) => update_noteq (injective.ne hf hj) a g }\n\n/-- Non-dependent version of `function.update_comp_eq_of_injective'` -/\ntheorem update_comp_eq_of_injective {α : Sort u} {α' : Sort w} [DecidableEq α] [DecidableEq α'] {β : Sort u_1} (g : α' → β) {f : α → α'} (hf : injective f) (i : α) (a : β) : update g (f i) a ∘ f = update (g ∘ f) i a :=\n update_comp_eq_of_injective' g hf i a\n\ntheorem apply_update {ι : Sort u_1} [DecidableEq ι] {α : ι → Sort u_2} {β : ι → Sort u_3} (f : (i : ι) → α i → β i) (g : (i : ι) → α i) (i : ι) (v : α i) (j : ι) : f j (update g i v j) = update (fun (k : ι) => f k (g k)) i (f i v) j := sorry\n\ntheorem comp_update {α : Sort u} [DecidableEq α] {α' : Sort u_1} {β : Sort u_2} (f : α' → β) (g : α → α') (i : α) (v : α') : f ∘ update g i v = update (f ∘ g) i (f v) :=\n funext (apply_update (fun (x : α) => f) g i v)\n\ntheorem update_comm {α : Sort u_1} [DecidableEq α] {β : α → Sort u_2} {a : α} {b : α} (h : a ≠ b) (v : β a) (w : β b) (f : (a : α) → β a) : update (update f a v) b w = update (update f b w) a v := sorry\n\n@[simp] theorem update_idem {α : Sort u_1} [DecidableEq α] {β : α → Sort u_2} {a : α} (v : β a) (w : β a) (f : (a : α) → β a) : update (update f a v) a w = update f a w := sorry\n\n/-- `extend f g e'` extends a function `g : α → γ`\nalong a function `f : α → β` to a function `β → γ`,\nby using the values of `g` on the range of `f`\nand the values of an auxiliary function `e' : β → γ` elsewhere.\n\nMostly useful when `f` is injective. -/\ndef extend {α : Type u_1} {β : Type u_2} {γ : Type u_3} (f : α → β) (g : α → γ) (e' : β → γ) : β → γ :=\n fun (b : β) =>\n dite (∃ (a : α), f a = b) (fun (h : ∃ (a : α), f a = b) => g (classical.some h)) fun (h : ¬∃ (a : α), f a = b) => e' b\n\ntheorem extend_def {α : Type u_1} {β : Type u_2} {γ : Type u_3} (f : α → β) (g : α → γ) (e' : β → γ) (b : β) : extend f g e' b =\n dite (∃ (a : α), f a = b) (fun (h : ∃ (a : α), f a = b) => g (classical.some h)) fun (h : ¬∃ (a : α), f a = b) => e' b :=\n rfl\n\n@[simp] theorem extend_apply {α : Type u_1} {β : Type u_2} {γ : Type u_3} {f : α → β} (hf : injective f) (g : α → γ) (e' : β → γ) (a : α) : extend f g e' (f a) = g a := sorry\n\n@[simp] theorem extend_comp {α : Type u_1} {β : Type u_2} {γ : Type u_3} {f : α → β} (hf : injective f) (g : α → γ) (e' : β → γ) : extend f g e' ∘ f = g :=\n funext fun (a : α) => extend_apply hf g e' a\n\ntheorem uncurry_def {α : Type u_1} {β : Type u_2} {γ : Type u_3} (f : α → β → γ) : uncurry f = fun (p : α × β) => f (prod.fst p) (prod.snd p) :=\n rfl\n\n@[simp] theorem uncurry_apply_pair {α : Type u_1} {β : Type u_2} {γ : Type u_3} (f : α → β → γ) (x : α) (y : β) : uncurry f (x, y) = f x y :=\n rfl\n\n@[simp] theorem curry_apply {α : Type u_1} {β : Type u_2} {γ : Type u_3} (f : α × β → γ) (x : α) (y : β) : curry f x y = f (x, y) :=\n rfl\n\n/-- Compose a binary function `f` with a pair of unary functions `g` and `h`.\nIf both arguments of `f` have the same type and `g = h`, then `bicompl f g g = f on g`. -/\ndef bicompl {α : Type u_1} {β : Type u_2} {γ : Type u_3} {δ : Type u_4} {ε : Type u_5} (f : γ → δ → ε) (g : α → γ) (h : β → δ) (a : α) (b : β) : ε :=\n f (g a) (h b)\n\n/-- Compose an unary function `f` with a binary function `g`. -/\ndef bicompr {α : Type u_1} {β : Type u_2} {γ : Type u_3} {δ : Type u_4} (f : γ → δ) (g : α → β → γ) (a : α) (b : β) : δ :=\n f (g a b)\n\n-- Suggested local notation:\n\ntheorem uncurry_bicompr {α : Type u_1} {β : Type u_2} {γ : Type u_3} {δ : Type u_4} (f : α → β → γ) (g : γ → δ) : uncurry (bicompr g f) = g ∘ uncurry f :=\n rfl\n\ntheorem uncurry_bicompl {α : Type u_1} {β : Type u_2} {γ : Type u_3} {δ : Type u_4} {ε : Type u_5} (f : γ → δ → ε) (g : α → γ) (h : β → δ) : uncurry (bicompl f g h) = uncurry f ∘ prod.map g h :=\n rfl\n\n/-- Records a way to turn an element of `α` into a function from `β` to `γ`. The most generic use\nis to recursively uncurry. For instance `f : α → β → γ → δ` will be turned into\n`↿f : α × β × γ → δ`. One can also add instances for bundled maps. -/\nclass has_uncurry (α : Type u_5) (β : outParam (Type u_6)) (γ : outParam (Type u_7)) \nwhere\n uncurry : α → β → γ\n\nprefix:1024 \"↿\" => Mathlib.function.has_uncurry.uncurry\n\n/-- Uncurrying operator. The most generic use is to recursively uncurry. For instance\n`f : α → β → γ → δ` will be turned into `↿f : α × β × γ → δ`. One can also add instances\nfor bundled maps.-/\nprotected instance has_uncurry_base {α : Type u_1} {β : Type u_2} : has_uncurry (α → β) α β :=\n has_uncurry.mk id\n\nprotected instance has_uncurry_induction {α : Type u_1} {β : Type u_2} {γ : Type u_3} {δ : Type u_4} [has_uncurry β γ δ] : has_uncurry (α → β) (α × γ) δ :=\n has_uncurry.mk fun (f : α → β) (p : α × γ) => has_uncurry.uncurry (f (prod.fst p)) (prod.snd p)\n\n/-- A function is involutive, if `f ∘ f = id`. -/\ndef involutive {α : Sort u_1} (f : α → α) :=\n ∀ (x : α), f (f x) = x\n\ntheorem involutive_iff_iter_2_eq_id {α : Sort u_1} {f : α → α} : involutive f ↔ nat.iterate f (bit0 1) = id :=\n iff.symm funext_iff\n\nnamespace involutive\n\n\n@[simp] theorem comp_self {α : Sort u} {f : α → α} (h : involutive f) : f ∘ f = id :=\n funext h\n\nprotected theorem left_inverse {α : Sort u} {f : α → α} (h : involutive f) : left_inverse f f :=\n h\n\nprotected theorem right_inverse {α : Sort u} {f : α → α} (h : involutive f) : right_inverse f f :=\n h\n\nprotected theorem injective {α : Sort u} {f : α → α} (h : involutive f) : injective f :=\n left_inverse.injective (involutive.left_inverse h)\n\nprotected theorem surjective {α : Sort u} {f : α → α} (h : involutive f) : surjective f :=\n fun (x : α) => Exists.intro (f x) (h x)\n\nprotected theorem bijective {α : Sort u} {f : α → α} (h : involutive f) : bijective f :=\n { left := involutive.injective h, right := involutive.surjective h }\n\n/-- Involuting an `ite` of an involuted value `x : α` negates the `Prop` condition in the `ite`. -/\nprotected theorem ite_not {α : Sort u} {f : α → α} (h : involutive f) (P : Prop) [Decidable P] (x : α) : f (ite P x (f x)) = ite (¬P) x (f x) := sorry\n\nend involutive\n\n\n/-- The property of a binary function `f : α → β → γ` being injective.\n Mathematically this should be thought of as the corresponding function `α × β → γ` being injective.\n-/\ndef injective2 {α : Sort u_1} {β : Sort u_2} {γ : Sort u_3} (f : α → β → γ) :=\n ∀ {a₁ a₂ : α} {b₁ b₂ : β}, f a₁ b₁ = f a₂ b₂ → a₁ = a₂ ∧ b₁ = b₂\n\nnamespace injective2\n\n\nprotected theorem left {α : Type u_1} {β : Type u_2} {γ : Type u_3} (f : α → β → γ) (hf : injective2 f) {a₁ : α} {a₂ : α} {b₁ : β} {b₂ : β} (h : f a₁ b₁ = f a₂ b₂) : a₁ = a₂ :=\n and.left (hf h)\n\nprotected theorem right {α : Type u_1} {β : Type u_2} {γ : Type u_3} (f : α → β → γ) (hf : injective2 f) {a₁ : α} {a₂ : α} {b₁ : β} {b₂ : β} (h : f a₁ b₁ = f a₂ b₂) : b₁ = b₂ :=\n and.right (hf h)\n\ntheorem eq_iff {α : Type u_1} {β : Type u_2} {γ : Type u_3} (f : α → β → γ) (hf : injective2 f) {a₁ : α} {a₂ : α} {b₁ : β} {b₂ : β} : f a₁ b₁ = f a₂ b₂ ↔ a₁ = a₂ ∧ b₁ = b₂ := sorry\n\nend injective2\n\n\n/-- `sometimes f` evaluates to some value of `f`, if it exists. This function is especially\ninteresting in the case where `α` is a proposition, in which case `f` is necessarily a\nconstant function, so that `sometimes f = f a` for all `a`. -/\ndef sometimes {α : Sort u_1} {β : Sort u_2} [Nonempty β] (f : α → β) : β :=\n dite (Nonempty α) (fun (h : Nonempty α) => f (Classical.choice h)) fun (h : ¬Nonempty α) => Classical.choice _inst_1\n\ntheorem sometimes_eq {p : Prop} {α : Sort u_1} [Nonempty α] (f : p → α) (a : p) : sometimes f = f a :=\n dif_pos (Nonempty.intro a)\n\ntheorem sometimes_spec {p : Prop} {α : Sort u_1} [Nonempty α] (P : α → Prop) (f : p → α) (a : p) (h : P (f a)) : P (sometimes f) :=\n eq.mpr (id (Eq._oldrec (Eq.refl (P (sometimes f))) (sometimes_eq f a))) h\n\nend function\n\n\n/-- `s.piecewise f g` is the function equal to `f` on the set `s`, and to `g` on its complement. -/\ndef set.piecewise {α : Type u} {β : α → Sort v} (s : set α) (f : (i : α) → β i) (g : (i : α) → β i) [(j : α) → Decidable (j ∈ s)] (i : α) : β i :=\n ite (i ∈ s) (f i) (g i)\n\n", "meta": {"author": "AurelienSaue", "repo": "Mathlib4_auto", "sha": "590df64109b08190abe22358fabc3eae000943f2", "save_path": "github-repos/lean/AurelienSaue-Mathlib4_auto", "path": "github-repos/lean/AurelienSaue-Mathlib4_auto/Mathlib4_auto-590df64109b08190abe22358fabc3eae000943f2/Mathlib/logic/function/basic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.26588047309981694, "lm_q2_score": 0.051845464086015744, "lm_q1q2_score": 0.013784696519269434}} {"text": "import Std.Tactic.GuardExpr\nimport Mathlib.Tactic.Elementwise\n--import Mathlib.Algebra.Category.Mon.Basic\n\nnamespace ElementwiseTest\nopen CategoryTheory\n\nset_option linter.existingAttributeWarning false in\nattribute [simp] Iso.hom_inv_id Iso.inv_hom_id IsIso.hom_inv_id IsIso.inv_hom_id\n\nattribute [local instance] ConcreteCategory.hasCoeToFun ConcreteCategory.hasCoeToSort\n\n@[elementwise]\ntheorem ex1 [Category C] [ConcreteCategory C] (X : C) (f g h : X ⟶ X) (h' : g ≫ h = h ≫ g) :\n f ≫ g ≫ h = f ≫ h ≫ g := by rw [h']\n\n-- If there is already a `ConcreteCategory` instance, do not add a new argument.\nexample : ∀ C [Category C] [ConcreteCategory C] (X : C) (f g h : X ⟶ X) (_ : g ≫ h = h ≫ g)\n (x : X), h (g (f x)) = g (h (f x)) := @ex1_apply\n\n@[elementwise]\ntheorem ex2 [Category C] (X : C) (f g h : X ⟶ X) (h' : g ≫ h = h ≫ g) :\n f ≫ g ≫ h = f ≫ h ≫ g := by rw [h']\n\n-- If there is not already a `ConcreteCategory` instance, insert a new argument.\nexample : ∀ C [Category C] (X : C) (f g h : X ⟶ X) (_ : g ≫ h = h ≫ g) [ConcreteCategory C]\n (x : X), h (g (f x)) = g (h (f x)) := @ex2_apply\n\n-- Need nosimp on the following `elementwise` since the lemma can be proved by simp anyway.\n@[elementwise nosimp]\ntheorem ex3 [Category C] {X Y : C} (f : X ≅ Y) : f.hom ≫ f.inv = 𝟙 X :=\n Iso.hom_inv_id _\n\nexample : ∀ C [Category C] (X Y : C) (f : X ≅ Y) [ConcreteCategory C] (x : X),\n f.inv (f.hom x) = x := @ex3_apply\n\n-- Make sure there's no `id x` in there:\nexample : ∀ C [Category C] (X Y : C) (f : X ≅ Y) [ConcreteCategory C] (x : X),\n f.inv (f.hom x) = x := by intros; simp only [ex3_apply]\n\n@[elementwise]\nlemma foo [Category C]\n {M N K : C} {f : M ⟶ N} {g : N ⟶ K} {h : M ⟶ K} (w : f ≫ g = h) : f ≫ 𝟙 N ≫ g = h := by\n simp [w]\n\n@[elementwise]\nlemma foo' [Category C]\n {M N K : C} {f : M ⟶ N} {g : N ⟶ K} {h : M ⟶ K} (w : f ≫ g = h) : f ≫ 𝟙 N ≫ g = h := by\n simp [w]\n\nlemma bar [Category C] [ConcreteCategory C]\n {M N K : C} {f : M ⟶ N} {g : N ⟶ K} {h : M ⟶ K} (w : f ≫ g = h) (x : M) : g (f x) = h x := by\n apply foo_apply w\n\nexample {M N K : Type} {f : M ⟶ N} {g : N ⟶ K} {h : M ⟶ K} (w : f ≫ g = h) (x : M) :\n g (f x) = h x := by\n have := elementwise_of% w\n guard_hyp this : ∀ (x : M), g (f x) = h x\n exact this x\n\nexample {M N K : Type} {f : M ⟶ N} {g : N ⟶ K} {h : M ⟶ K} (w : f ≫ g = h) (x : M) :\n g (f x) = h x := (elementwise_of% w) x\n\nexample [Category C] [ConcreteCategory C]\n {M N K : C} {f : M ⟶ N} {g : N ⟶ K} {h : M ⟶ K} (w : f ≫ g = h) (x : M) :\n g (f x) = h x := by\n have := elementwise_of% w\n guard_hyp this : ∀ (x : M), g (f x) = h x\n exact this x\n\n-- `elementwise_of%` allows a level metavariable for its `ConcreteCategory` instance.\nexample [Category C] [ConcreteCategory C]\n (h : ∀ D [Category D] (X Y : D) (f : X ⟶ Y) (g : Y ⟶ X), f ≫ g = 𝟙 X)\n {M N : C} {f : M ⟶ N} {g : N ⟶ M} (x : M) : g (f x) = x := by\n have := elementwise_of% h\n guard_hyp this : ∀ D [Category D] (X Y : D) (f : X ⟶ Y) (g : Y ⟶ X)\n [ConcreteCategory D] (x : X), g (f x) = x\n rw [this]\n\nsection Mon\n-- TODO: switch to actual Mon when it is ported\nvariable (Mon : Type _) [Category Mon] [ConcreteCategory Mon]\n\nlemma bar' {M N K : Mon} {f : M ⟶ N} {g : N ⟶ K} {h : M ⟶ K} (w : f ≫ g = h) (x : M) :\n g (f x) = h x := by exact foo_apply w x\n\nlemma bar'' {M N K : Mon} {f : M ⟶ N} {g : N ⟶ K} {h : M ⟶ K} (w : f ≫ g = h) (x : M) :\n g (f x) = h x := by apply foo_apply w\n\nlemma bar''' {M N K : Mon} {f : M ⟶ N} {g : N ⟶ K} {h : M ⟶ K} (w : f ≫ g = h) (x : M) :\n g (f x) = h x := by apply foo_apply w\n\nexample (M N K : Mon) (f : M ⟶ N) (g : N ⟶ K) (h : M ⟶ K) (w : f ≫ g = h) (m : M) :\n g (f m) = h m := by rw [elementwise_of% w]\n\nexample (M N K : Mon) (f : M ⟶ N) (g : N ⟶ K) (h : M ⟶ K) (w : f ≫ g = h) (m : M) :\n g (f m) = h m := by\n -- porting note: did not port `elementwise!` tactic\n replace w := elementwise_of% w\n apply w\n\nend Mon\n\nexample {α β : Type} (f g : α ⟶ β) (w : f = g) (a : α) : f a = g a := by\n -- porting note: did not port `elementwise!` tactic\n replace w := elementwise_of% w\n guard_hyp w : ∀ (x : α), f x = g x\n rw [w]\n\n\nexample {α β : Type} (f g : α ⟶ β) (w : f ≫ 𝟙 β = g) (a : α) : f a = g a := by\n -- porting note: did not port `elementwise!` tactic\n replace w := elementwise_of% w\n guard_hyp w : ∀ (x : α), f x = g x\n rw [w]\n\nend ElementwiseTest\n", "meta": {"author": "leanprover-community", "repo": "mathlib4", "sha": "b9a0a30342ca06e9817e22dbe46e75fc7f435500", "save_path": "github-repos/lean/leanprover-community-mathlib4", "path": "github-repos/lean/leanprover-community-mathlib4/mathlib4-b9a0a30342ca06e9817e22dbe46e75fc7f435500/test/elementwise.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42250464935739196, "lm_q2_score": 0.032589741594884654, "lm_q1q2_score": 0.013769317345194753}} {"text": "import data_util.lean_step\nimport data_util.basic\nimport system.io\nimport all\n\nmeta def dummy_dp_handler : ℕ → ℕ → tactic.ref ℕ → ℕ → LeanStepDatapoint → tactic unit := λ _ _ _ _ dp, do {\n dp_fmt ← has_to_format.to_format <$> (to_tactic_json dp),\n tactic.trace format! \"DATAPOINT: \\n---\\n{dp_fmt}\\n---\\n\"\n}\n\nmeta def fp_dp_handler\n (fp : io.handle)\n (serialization_guard : LeanStepDatapoint → tactic bool)\n (decl_count : ℕ)\n (decl_total : ℕ)\n (dp_count : tactic.ref ℕ)\n (total : ℕ)\n : LeanStepDatapoint → tactic unit := λ dp, do {\n mcond (bnot <$> serialization_guard dp) (pure ()) $ do {\n msg ← (format.to_string ∘ format.flatten ∘ has_to_format.to_format) <$> to_tactic_json dp,\n tactic.unsafe_run_io $ io.fs.put_str_ln fp msg\n },\n tactic.modify_ref dp_count nat.succ,\n count ← tactic.read_ref dp_count,\n when (count % 100 = 0) $ \n tactic.trace format! \"DECL {decl_count}/{decl_total} || PROCESSED {count}/{total}\"\n}\n\nmeta def lean_step_serialization_guard\n (SERIALIZATION_DEPTH_LIMIT := 64)\n (SERIALIZATION_WEIGHT_LIMIT := 1500)\n : LeanStepDatapoint → tactic bool := λ dp, do {\n let validate_expr : expr → bool := λ e, (e.get_depth ≤ SERIALIZATION_DEPTH_LIMIT) && (e.get_weight ≤ SERIALIZATION_WEIGHT_LIMIT),\n option.is_some <$> match dp with\n | ⟨_, decl_tp, hyps, _, decl_premises, _, goal, proof_term, result, next_lemma, _⟩ := optional $ do {\n guard $ validate_expr decl_tp,\n guard $ all $ hyps.map (λ ⟨x₁, x₂⟩, validate_expr x₁ && validate_expr x₂),\n guard $ all $ decl_premises.map (λ ⟨x₁, x₂⟩, validate_expr x₁ && validate_expr x₂),\n guard $ validate_expr proof_term,\n guard $ validate_expr result,\n match next_lemma with\n | (some next_lemma) := guard $ (validate_expr next_lemma.1) && (validate_expr next_lemma.2)\n | _ := pure ()\n end\n }\n end\n}\n\nmeta def declaration.kind : declaration → string\n| (declaration.defn _ _ _ _ _ _) := \"definition\"\n| (declaration.thm _ _ _ _) := \"theorem\"\n| (declaration.cnst _ _ _ _) := \"constant\"\n| (declaration.ax _ _ _) := \"axiom\"\n\nmeta def lean_step_main\n (dp_handler : ℕ → ℕ → tactic.ref ℕ → ℕ → LeanStepDatapoint → tactic unit)\n (opts : LeanStepOpts)\n (decl_nm : name)\n (decl_count : ℕ) (decl_total : ℕ)\n : tactic unit := do {\n env ← tactic.get_env,\n decl ← env.get decl_nm | tactic.fail format! \"[lean_step_main] DECLARATION LOOKUP FAILED FOR {decl_nm}\",\n guard (decl.is_theorem) <|> tactic.fail format! \"[lean_step_main] PROOF LOOKUP FAILED FOR {decl_nm}, DECLARATION IS A {decl.kind}\",\n pf ← tactic.get_proof decl,\n decl_premises ← gather_used_premises pf >>= λ xs, xs.mmap mk_type_annotation,\n tactic.using_new_ref (0 : ℕ) $ λ dp_ref,\n lean_step_main_core decl_nm decl.type decl_premises pf (dp_handler decl_count decl_total dp_ref opts.rec_limit) opts pf\n}\n\nsection tests\n\n-- run_cmd lean_step_main dummy_dp_handler {} `peirce_identity 0 0\n\nexample : ∀ {P Q : Prop}, ((P → Q) → P) → P :=\nλ {P Q : Prop}, (em P).elim (λ (_x : P) (_x_1 : (P → Q) → P), _x) $ λ (_x : ¬P) (H : (P → Q) → P), H (λ (_x_1 : P), (@absurd P false _x_1 _x).elim)\n\nend tests\n\nsection main\n\nmeta def lean_step_from_decls_file (decls_file : string) (dest : string) (rec_limit : ℕ) (depth_limit : ℕ) (weight_limit : ℕ) : io unit := do {\n nm_strs ← io.mk_file_handle decls_file io.mode.read >>= readlines',\n (nms : list (name × list name)) ← (nm_strs.filter $ λ nm_str, string.length nm_str > 0).mmap $ λ nm_str, do {\n ((io.run_tactic' ∘ parse_decl_nm_and_open_ns) $ nm_str)\n },\n let total := nms.length,\n dest_handle ← io.mk_file_handle dest io.mode.write,\n io.run_tactic' $ tactic.using_new_ref (0 : ℕ) $ λ ref,\n for_ nms $ λ ⟨nm, _⟩, do {\n count ← tactic.read_ref ref,\n tactic.try_verbose $ lean_step_main (fp_dp_handler dest_handle (lean_step_serialization_guard depth_limit weight_limit)) {rec_limit := rec_limit} nm count total,\n tactic.modify_ref ref nat.succ,\n count ← tactic.read_ref ref,\n tactic.trace format!\"[lean_step_from_decls_file] PROGRESS: {count}/{total}\"\n }\n}\n\nmeta def list.nth_except_with_default {α} [has_to_format α] (xs : list α) (pos : ℕ) (msg : string) (default : option α := none) : io α :=\nmatch default with\n| some default := xs.nth_except pos msg <|> io.put_str_ln' format! \"WARNING: defaulting {msg} to {default}\" *> pure default\n| _ := xs.nth_except pos msg\nend\n\ndef nat.to_string : ℕ → string := repr\n\nmeta def main : io unit := do {\n args ← io.cmdline_args,\n decls_file ← args.nth_except 0 \"decls_file\",\n dest ← args.nth_except 1 \"dest\",\n rec_limit ← string.to_nat <$> args.nth_except_with_default 2 \"rec_limit\" (5000 : ℕ).to_string,\n serialization_depth_limit ← string.to_nat <$> (args.nth_except_with_default 3 \"serialization_depth_limit\" (100 : ℕ).to_string),\n serialization_weight_limit ← string.to_nat <$> (args.nth_except_with_default 4 \"serialization_weight_limit\" (2000 : ℕ).to_string),\n lean_step_from_decls_file decls_file dest rec_limit serialization_depth_limit serialization_weight_limit \n}\n\nend main\n", "meta": {"author": "jesse-michael-han", "repo": "lean-step-public", "sha": "1abd55d25fe01e581a040a815aceb379d8e1bee1", "save_path": "github-repos/lean/jesse-michael-han-lean-step-public", "path": "github-repos/lean/jesse-michael-han-lean-step-public/lean-step-public-1abd55d25fe01e581a040a815aceb379d8e1bee1/src/lean_step.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.30735802955444114, "lm_q2_score": 0.044680865820311146, "lm_q1q2_score": 0.013733022877317211}} {"text": "import rpartrec coding\n\nopen encodable denumerable part\n\ndef encode2 {α σ} [encodable α] [inhabited α] [encodable σ] (f : α →. σ) :=\n(λ n, (f $ (decode α n).get_or_else (default α)).map encode)\n\ndef encode2_total {α σ} [encodable α] [inhabited α] [encodable σ] (f : α → σ) :=\n(λ n, encode (f $ (decode α n).get_or_else (default α)))\n\n@[simp] lemma encode2_total_eq {α σ} [encodable α] [inhabited α] [encodable σ] (f : α → σ) : \n encode2 (f : α →. σ) = pfun.lift (encode2_total f) := funext (λ x, by simp[encode2, encode2_total])\n\ntheorem rpartrec.encode2_rpartrec_in {α σ} [primcodable α] [primcodable σ] [inhabited α] (f : α →. σ) :\n encode2 f partrec_in f :=\nbegin\n simp only [encode2],\n have c₀ : (λ n, f ((decode α n).get_or_else (default α))) partrec_in f :=\n rpartrec.refl.comp ((computable.decode.option_get_or_else $ computable.const $ default α).to_rpart),\n have c₁ : computable (λ x, encode x.2 : ℕ × σ → ℕ) := computable.encode.comp computable.snd,\n exact c₀.map c₁.to_rpart\nend\n\ntheorem rpartrec.rpartrec_in_encode2 {α σ} [primcodable α] [primcodable σ] [inhabited α] (f : α →. σ) :\n f partrec_in encode2 f :=\nbegin\n let f' : α →. σ := (λ a, (encode2 f (encode a)).bind (λ x, decode σ x)),\n have c₀ : (λ a, encode2 f (encode a) : α →. ℕ) partrec_in encode2 f :=\n rpartrec.refl.comp (partrec.to_rpart computable.encode),\n have c₁ : partrec₂ (λ x y, ↑(decode σ y) : α → ℕ →. σ) := computable.decode.of_option.comp computable.snd,\n exact ((c₀.bind c₁.to_rpart).of_eq $ λ a, by simp[encode2])\nend\n\ndef graph {α β} [decidable_eq β] (f : α → β) : α × β → bool :=\nλ x, to_bool (f x.1 = x.2)\n\ndef epsilon_r {β} [primcodable β] [inhabited β] (p : β →. bool) : part β := \n ((nat.rfind $ λ x, p ((decode β x).get_or_else (default β))).map \n (λ x, (decode β x).get_or_else (default β)))\n\ndef epsilon {β} [primcodable β] [inhabited β] (p : β → bool) : part β :=\nepsilon_r (p : β →. bool)\n\ntheorem epsilon_witness {β} [primcodable β] [inhabited β] {p : β → bool} {b : β} :\n b ∈ epsilon p → p b = tt :=\nby { simp[epsilon,epsilon_r], intros x h hl he, rw he at h, simp[←h] }\n\n@[simp] theorem exists_epsilon_iff {β} [primcodable β] [inhabited β] {p : β → bool} :\n (epsilon p).dom ↔ (∃ b, p b = tt) := by { split,\n{ intros w, use (epsilon p).get w, exact epsilon_witness ⟨w, rfl⟩ },\n{ rintros ⟨b, hb⟩, simp[epsilon,epsilon_r, part.map, part.some],\n use (encode b), simp[hb], use trivial} }\n\n@[simp] def initialpart {α σ} [denumerable α] (f : α → option σ) : ℕ → list (α × σ)\n| 0 := []\n| (n + 1) := option.cases_on (f (of_nat α n)) (initialpart n) (λ a, (of_nat α n, a) :: initialpart n)\n\ninfix `↾`:70 := initialpart\n\n@[simp] theorem nat.initialpart_length {α σ} [denumerable α] (f : α → option σ) (s) : (f↾s).length ≤ s :=\nby { induction s with m ih; simp,\n cases C : f (of_nat _ m); simp, { exact nat.le_succ_of_le ih},\n { exact nat.succ_le_succ ih } }\n\nlemma nat.initialpart_nth {α σ} [denumerable α] {f : α → option σ} {s n : ℕ} {a}\n (h : n < s) (hn : f (of_nat α n) = some a) :\n ∃ i, (f↾s).nth i = some (of_nat α n, a) ∧ ∀ j b, j < i → (f↾s).nth j ≠ some (of_nat α n, b) :=\nbegin\n induction s with s IH,\n { simp at h, contradiction },\n { simp[initialpart], cases C : f (of_nat α s) with v; simp,\n { have : n < s ∨ n = s, from nat.lt_succ_iff_lt_or_eq.mp h,\n cases this,\n { exact IH this },\n { exfalso, simp[this, C] at hn, exact hn } },\n { have eqn_n : n < s ∨ n = s, from nat.lt_succ_iff_lt_or_eq.mp h,\n cases eqn_n,\n { rcases IH eqn_n with ⟨i, eqn_na, hi⟩, use i + 1, simp, refine ⟨eqn_na, λ j b eqn_j, _⟩,\n cases j; simp, \n { intros e, exfalso, \n have : n = s, rw ←@denumerable.encode_of_nat α _ s,\n rw ←@denumerable.encode_of_nat α _ n, simp [e],\n simp[this] at eqn_n, exact eqn_n },\n { have : j < i, from nat.succ_lt_succ_iff.mp eqn_j,\n exact hi _ _ this } },\n { use 0, simp[eqn_n], rw eqn_n at hn, simp[C] at hn, exact hn } } }\nend\n\nlemma nat.initialpart_nth_none {α σ} [denumerable α] {f : α → option σ} (s) {n}\n (hn : f (of_nat α n) = none) : ∀ i a, (f↾s).nth i ≠ some (of_nat α n, a) :=\nbegin\n induction s with s IH generalizing n; simp[initialpart],\n { cases C : f (of_nat α s) with v; simp, exact IH hn,\n intros i, cases i; simp,\n { intros a e, exfalso, simp [e, hn] at C, exact C },\n { exact IH hn i } }\nend\n\nlemma nat.initialpart_to_fn {α σ} [decidable_eq α] [denumerable α] {f : α → option σ} {s a b}\n (h : encode a < s) (hn : f a = some b) : (f↾s).to_fn a = some b :=\nby simp; rw (show a = of_nat α (encode a), by simp) at hn ⊢; exact nat.initialpart_nth h hn\n\nlemma nat.initialpart_to_fn_none {α σ} [decidable_eq α] [denumerable α] {f : α → option σ} {a}\n (ha : f a = none) (s) : (f↾s).to_fn a = none :=\nby simp; rw (show a = of_nat α (encode a), by simp) at ha ⊢;\n intros m y; exact nat.initialpart_nth_none s ha m y\n\ndef list.subseq {α} [decidable_eq α] (f : ℕ → α) : list α → bool\n| [] := tt\n| (x::xs) := to_bool (x = f xs.length) && list.subseq xs\n\nnotation l` ⊂ₘ `f:80 := list.subseq f l\n\ndef list.subseq_t {σ} [primcodable σ] (f : ℕ → σ) :=\nlist.subseq (λ x, encode $ f x)\n\nnotation l` ⊂ₘ* `f:80 := list.subseq_t f l\n\ntheorem subseq_iff (l : list ℕ) (f : ℕ → ℕ) :\n l ⊂ₘ f ↔ (∀ n, n < l.length → l.rnth n = some (f n)) :=\nbegin\n induction l with n0 l0 ih; simp[list.subseq], split; assume h,\n { intros n h0,\n have ih0 : ∀ {n}, n < l0.length → l0.rnth n = option.some (f n), from ih.mp h.2,\n have e : n < l0.length ∨ n = l0.length, omega,\n cases e,\n simp[list.rnth, list.nth_append (show n < l0.reverse.length, by simp[list.length_reverse, e])],\n exact ih0 e,\n simp[e, list.rnth_concat_length, h.1] },\n have lm0 : n0 = f l0.length,\n { have h' := h l0.length (lt_add_one (list.length l0)),\n simp [list.rnth_concat_length] at h',\n exact option.some_inj.mp (by simp; exact h') },\n have lm1 : (l0 ⊂ₘ f) = tt,\n { apply ih.mpr, intros n ne,\n have h' := h n (nat.lt.step ne), rw ← h',\n simp[list.rnth], symmetry, exact list.nth_append (by simp[ne]) },\n exact ⟨lm0, lm1⟩\nend\n\ndef nat.rfind_fin0 (p : ℕ → bool) (m : ℕ) : ℕ → option ℕ\n| 0 := none\n| (n+1) := cond (p (m - n.succ)) (some (m - n.succ)) (nat.rfind_fin0 n)\n\ndef nat.rfind_fin (p : ℕ → bool) (m : ℕ) := nat.rfind_fin0 p m m\n\ntheorem rfind_fin0_iff (p : ℕ → bool) : ∀ (i m n : ℕ), i ≤ m → \n (nat.rfind_fin0 p m i = some n ↔ (m - i ≤ n ∧ n < m ∧ p n = tt ∧ ∀ l, m - i ≤ l → l < n → p l = ff)) :=\nbegin\n intros i, \n induction i with i0 ih,\n { intros m n, simp [nat.rfind_fin0], intros c c0, exfalso, exact nat.lt_le_antisymm c0 c },\n { intros m n i0e, simp[nat.rfind_fin0],\n cases ep : p (m - i0.succ), simp,\n { rw ih m n (show i0 ≤ m, by omega), split, \n { rintros ⟨e0, e1, e2, h0⟩,\n have l0 : ∀ (l : ℕ), m ≤ l + i0.succ → l < n → p l = ff,\n { intros l el0 el1,\n have le : m - i0.succ = l ∨ m - i0 ≤ l, omega,\n cases le, simp[←ep, le], simp at*, exact h0 _ le el1 },\n exact ⟨show m ≤ n + i0.succ, by omega, e1, e2, l0⟩ },\n { rintros ⟨e0, e1, e2, h0⟩, split,\n { have l0 : m - i0.succ = n ∨ m - i0 ≤ n, omega, cases l0,\n { exfalso, simp[l0, e2] at ep, exact ep },\n { exact l0 } },\n { have l0 : ∀ (l : ℕ), m - i0 ≤ l → l < n → p l = ff := λ _ _ el1, h0 _ (by omega) el1,\n exact ⟨e1, e2, l0⟩ } } },\n { simp, split,\n { assume e, rcases e with rfl,\n exact ⟨by omega, by omega, ep,\n by { intros k l0 l1, exfalso, \n have : m < m, from lt_of_le_of_lt l0 (lt_tsub_iff_right.mp l1), exact nat.lt_asymm this this }⟩ },\n { rintros ⟨e0, e1, e2, h0⟩,\n have l0 : m - i0.succ < n ∨ m - i0.succ = n, omega,\n cases l0,\n { exfalso, have c : p (m - i0.succ) = ff , exact h0 _ (by simp[nat.sub_add_cancel i0e]) l0,\n exact bool_iff_false.mpr c ep },\n { exact l0 } } } }\nend\n\n@[simp] theorem rfind_fin_iff {p : ℕ → bool} {m n : ℕ} :\n nat.rfind_fin p m = some n ↔ n < m ∧ p n = tt ∧ ∀ {l : ℕ}, l < n → p l = ff :=\nby { have h := rfind_fin0_iff p m m n (by refl), simp at h, exact h }\n\n@[simp] theorem rfind_fin_none {p : ℕ → bool} {m : ℕ} :\n nat.rfind_fin p m = none ↔ ∀ {l : ℕ}, l < m → p l = ff :=\nbegin\n rcases e : nat.rfind_fin p m,\n { simp, assume l el, cases epl : p l, refl,\n exfalso, rcases nat_bool_minimum' epl with ⟨m0, en, em0, hm0⟩,\n have l0 : ¬nat.rfind_fin p m = some m0, { rw e, intros c, exact option.not_mem_none _ c },\n have nc := λ n, not_congr (@rfind_fin_iff p m n), simp[-rfind_fin_iff] at nc, \n have l1 : ∃ (x : ℕ), x < m0 ∧ p x = tt := (nc _).mp l0 (by omega) em0,\n rcases l1 with ⟨n, hn, en⟩,\n have c : p n = ff := hm0 _ hn,\n exact bool_iff_false.mpr c en },\n { simp, use this,\n rw rfind_fin_iff at e, exact ⟨e.1, e.2.1⟩ }\nend\n\nnamespace primrec\n\nvariables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {σ : Type*} {τ : Type*} {μ : Type*}\n [primcodable α] [primcodable β] [primcodable γ] [primcodable δ] [primcodable σ] [primcodable τ] [primcodable μ]\n\ntheorem list_get_elem {f : α → list β} {p : α → β → Prop}\n [∀ a b, decidable (p a b)]\n (hf : primrec f) (hp : primrec_rel p) :\n primrec (λ a, (f a).get_elem (p a)) :=\nlist_nth.comp hf (list_find_index hf hp)\n\ntheorem list_rnth : primrec₂ (@list.rnth α) := \nprimrec.list_nth.comp (primrec.list_reverse.comp primrec.fst) primrec.snd\n\ndef subseq {α} (A B : ℕ → option α) := ∀ n b, A n = some b → B n = some b\n\ninfix ` ⊆* `:50 := subseq\n\nend primrec\n\nnamespace rpartrec\n\nvariables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {σ : Type*} {τ : Type*} {μ : Type*}\n [primcodable α] [primcodable β] [primcodable γ] [primcodable δ] [primcodable σ] [primcodable τ] [primcodable μ]\n\ntheorem epsilon_r_rpartrec [inhabited β] (p : α × β →. bool) :\n (λ a, epsilon_r (λ x, p (a, x))) partrec_in p :=\nbegin\n have c₀ : (λ x, p (x.1, (decode β x.2).get_or_else (default β)) : α × ℕ →. bool) partrec_in p :=\n (rpartrec.refl.comp $ (computable.pair computable.fst \n ((computable.decode.comp computable.snd).option_get_or_else (computable.const (default β))))\n .to_rpart),\n have c₁ : computable (λ x, (decode β x.2).get_or_else (default β) : α × ℕ → β) :=\n (computable.decode.comp computable.snd).option_get_or_else (computable.const (default β)),\n have c₂ : (λ a, nat.rfind $ λ x, p (a, (decode β x).get_or_else (default β))) partrec_in p, from rfind c₀,\n exact c₂.map c₁.to_rpart\nend\n\ntheorem epsilon_r_rpartrec_refl [inhabited β] {p : α → β →. bool} :\n (λ a, epsilon_r (p a)) partrec_in prod.unpaired p :=\nbegin\n have c₀ : (λ x, p x.1 ((decode β x.2).get_or_else (default β)) : α × ℕ →. bool) partrec_in prod.unpaired p :=\n (rpartrec.refl.comp $ (computable.pair computable.fst \n ((computable.decode.comp computable.snd).option_get_or_else (computable.const (default β))))\n .to_rpart),\n have c₁ : computable (λ x, (decode β x.2).get_or_else (default β) : α × ℕ → β) :=\n (computable.decode.comp computable.snd).option_get_or_else (computable.const (default β)),\n have c₂ : (λ a, nat.rfind $ λ x, p a ((decode β x).get_or_else (default β))) partrec_in prod.unpaired p, from rfind c₀,\n exact c₂.map c₁.to_rpart\nend\n\n@[rcomputability]\nprotected theorem epsilon_r [inhabited β] {p : α → β →. bool} {g : γ →. σ}\n (hp : p partrec₂_in g) : (λ a, epsilon_r (p a)) partrec_in g :=\nepsilon_r_rpartrec_refl.trans hp\n\n@[rcomputability]\nprotected theorem epsilon [inhabited β] {p : α → β → bool} {g : γ →. σ}\n (hp : p computable₂_in g) :\n (λ a, epsilon (p a)) partrec_in g :=\nepsilon_r_rpartrec_refl.trans hp\n\ntheorem epsilon_rpartrec [inhabited β] (p : α × β → bool) :\n (λ a, epsilon (λ x, p (a, x))) partrec_in (λ x, some $ p x) :=\nepsilon_r_rpartrec _ \n\nend rpartrec\n\nnamespace rcomputable\n\nvariables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {σ : Type*} {τ : Type*} {μ : Type*}\n [primcodable α] [primcodable β] [primcodable γ] [primcodable δ] [primcodable σ] [primcodable τ] [primcodable μ]\n\n@[rcomputability]\nprotected theorem epsilon [inhabited β] {p : α → β → bool} {g : γ →. σ} (hp : p computable₂_in g) :\n (λ a, epsilon (p a)) partrec_in g :=\nrpartrec.epsilon_r hp\n\n@[rcomputability]\ntheorem initialpart {α} [denumerable α] {f : α → option σ} {g : β →. τ}\n (hf : f computable_in g) : (↾) f computable_in g :=\nbegin\n let I : ℕ → list (α × σ) := (λ n : ℕ, n.elim []\n (λ m IH, option.cases_on (f (of_nat α m)) IH (λ a, (of_nat α m, a) :: IH))),\n have : I computable_in g,\n { refine rcomputable.nat_elim'\n rcomputable.id\n (rcomputable.const _) _, simp,\n refine rcomputable.option_cases\n (hf.comp ((primrec.of_nat _).to_rcomp.comp $ fst.comp snd))\n (snd.comp snd) _,\n refine (primrec.list_cons.comp (((primrec.of_nat _).comp $ primrec.fst.comp $\n primrec.snd.comp primrec.fst).pair primrec.snd) $ primrec.snd.comp $\n primrec.snd.comp primrec.fst).to_rcomp },\n exact (this.of_eq $ λ n, by induction n with n IH; simp[I]; simp[←IH])\nend\n\ntheorem initialpart_s {α β} [primcodable α] [denumerable β] {f : α → β → option γ} {g : α → ℕ} {o : σ →. τ}\n (hf : f computable₂_in o) (hg : g computable_in o) : (λ x, (f x)↾(g x)) computable_in o :=\nbegin\n let I : α → list (β × γ) := (λ a : α, (g a).elim []\n (λ m IH, option.cases_on (f a (of_nat β m)) IH (λ a, (of_nat β m, a) :: IH))),\n have : I computable_in o,\n { refine rcomputable.nat_elim' hg (const []) (by { \n simp,\n refine rcomputable.option_cases (hf.comp fst ((rcomputable.of_nat β).comp fst.to_unary₂)) snd.to_unary₂\n (rcomputable₂.list_cons.comp₂ (((rcomputable.of_nat β).comp fst.to_unary₂).to_unary₁.pair id'.to_unary₂)\n (to_unary₁ snd.to_unary₂)) }) },\n exact (this.of_eq $ λ n, by { simp[I], induction (g n) with n IH; simp[I]; simp[←IH]})\nend\n\nprivate lemma list.concat_induction {α} {C : list α → Sort*} :\n C [] → (Π l t, C l → C (l.concat t)) → Π l, C l :=\nbegin\n assume h0 ih,\n have l0 : Π l, C (list.reverse l),\n { intros l, induction l with hd tl tlih,\n simp, exact h0, \n rw (show (hd :: tl).reverse = tl.reverse.concat hd, by simp), exact ih _ _ tlih },\n intros l, rw (show l = l.reverse.reverse, by simp), exact l0 _\nend\n\ntheorem foldr' [inhabited α] (f : α × β → β) :\n (λ x, list.foldr (λ y z, f (y, z)) x.1 x.2 : β × list α → β) computable_in (f : α × β →. β) :=\n let foldr' := (λ x, nat.elim x.1 \n (λ y IH, f ((x.2.reverse.nth y).get_or_else (default α), IH))\n x.2.length : β × list α → β) in\n have c₀ : computable (λ x, x.2.length : β × list α → ℕ) :=\n computable.list_length.comp computable.snd,\n have c₁ : computable (λ x, x.1 : β × list α → β) := computable.fst,\n have c₂ : computable (λ x, (x.1.2.reverse.nth x.2.1).get_or_else (default α) :\n (β × list α) × ℕ × β → α) :=\n primrec.option_get_or_else.to_comp.comp\n (computable.list_nth.comp \n (computable.list_reverse.comp $ computable.snd.comp computable.fst)\n (computable.fst.comp computable.snd)) (computable.const $ default α),\n have c₃ : (λ x, f (((x.1.2.reverse.nth x.2.1).get_or_else (default α)), x.2.2) :\n (β × list α) × ℕ × β → β) computable_in (f : α × β →. β) :=\n refl.comp (pair c₂.to_rcomp (snd.comp snd)),\n have c₄ : foldr' computable_in (f : α × β →. β) := nat_elim c₀.to_rcomp c₁.to_rcomp c₃,\n have e : ∀ a (l m : list α), nat.elim a\n (λ y IH, f (((l ++ m).nth y).get_or_else (default α), IH)) l.length =\n nat.elim a (λ y IH, f ((l.nth y).get_or_else (default α), IH)) l.length,\n { intros a,\n apply @list.concat_induction _ (λ l, ∀ m, nat.elim a \n (λ y IH, f (((l ++ m).nth y).get_or_else (default α), IH)) l.length = \n nat.elim a (λ y IH, f ((l.nth y).get_or_else (default α), IH)) l.length); simp,\n intros ll ld lih m, apply congr, refl, apply congr,\n { rw (show ll ++ ld :: m = ll ++ [ld] ++ m, by simp),\n rw (list.nth_append (show ll.length < (ll ++ [ld]).length, by simp)),\n rw list.nth_concat_length, refl },\n { simp [lih] } },\n(c₄.of_eq $ by \n{ simp[foldr'], intros a l, induction l with ld ll lih; simp,\n rw (show ll.length = ll.reverse.length, by simp), congr,\n { rw list.nth_concat_length, refl },\n { rw e, simp[lih] } })\n\ntheorem foldr0 [inhabited α] (f : α × β → β) (b : β) :\n (λ x, list.foldr (λ y z, f (y, z)) b x : list α → β) computable_in (f : α × β →. β) := \n(foldr' f).comp (pair (const b) id)\n\n@[rcomputability]\ntheorem list_foldr' [inhabited α] {f : α → β → β} {o : σ →. τ} (hf : f computable₂_in o) :\n list.foldr f computable₂_in o :=\nrcomputable₂.trans₂ (foldr' (prod.unpaired f)).to₂ hf\n\n@[rcomputability]\ntheorem list_foldr [inhabited β] {f : α → β → γ → γ} {g : α → γ} {h : α → list β} {o : σ →. τ}\n (hf : (prod.unpaired3 f) computable_in o) (hg : g computable_in o) (hh : h computable_in o) :\n (λ x : α, list.foldr (f x) (g x) (h x)) computable_in o :=\nbegin\n have eqn: ∀ (a : α) (H₁ H₂ : list β),\n nat.elim (g a) (λ y IH, f a ((H₁.reverse ++ H₂).nth y).iget IH) H₁.length = \n nat.elim (g a) (λ y IH, f a (H₁.reverse.nth y).iget IH) H₁.length,\n { intros a H₁ H₂,\n induction H₁ with hd H₁ IH generalizing a H₂; simp,\n { have eq_hd : (H₁.reverse ++ [hd]).nth H₁.length = hd,\n { rw [show H₁.length = H₁.reverse.length, by simp, list.nth_concat_length H₁.reverse hd], refl },\n have eq_hd' : (H₁.reverse ++ hd :: H₂).nth H₁.length = hd,\n { rw [show H₁.reverse ++ hd :: H₂ = H₁.reverse ++ [hd] ++ H₂,by simp,\n list.nth_append (show H₁.length < (H₁.reverse ++ [hd]).length, by simp)], simp[eq_hd] },\n simp[eq_hd, eq_hd', IH] } },\n have : (λ a, nat.elim (g a) (λ y IH, f a ((h a).rnth y).iget IH) (h a).length) computable_in o,\n { refine rcomputable.nat_elim' (list_length.comp hh) hg\n (unpaired3 hf fst (option_iget.comp (rcomputable₂.list_rnth.comp (to_unary₁ hh) fst.to_unary₂)) snd.to_unary₂) },\n exact this.of_eq (by { \n intros a, induction (h a) with h H IH,\n { simp }, simp[←IH, list.rnth, eqn], congr,\n { rw [show H.length = H.reverse.length, by simp, list.nth_concat_length] } })\nend\n\n@[rcomputability]\nlemma list_map [inhabited β] {g : α → β → γ} {f : α → list β} {o : σ →. τ}\n (hg : g computable₂_in o) (hf : f computable_in o) :\n(λ a : α, list.map (g a) (f a)) computable_in o :=\nhave (λ a, list.foldr (λ b s, g a b :: s) [] (f a)) computable_in o,\n{ refine list_foldr\n (rcomputable₂.list_cons.comp (rcomputable₂.comp hg fst fst.to_unary₂) snd.to_unary₂) (const list.nil) hf },\nthis.of_eq (λ a, by simp[list.map_eq_foldr]) \n\n@[rcomputability]\nlemma list_filter [inhabited β] {p : α → β → Prop} [∀ x y, decidable (p x y)] {f : α → list β} {o : σ →. τ}\n (hp : (λ a b, to_bool (p a b)) computable₂_in o) (hf : f computable_in o) :\n(λ a : α, list.filter (p a) (f a)) computable_in o :=\nhave (λ a, list.foldr (λ b s, if (p a b) then (b :: s) else s) [] (f a)) computable_in o,\n{ refine list_foldr _ (by rcomputability) hf,\n { refine rcomputable.ite (hp.comp fst (fst.to_unary₂))\n (rcomputable₂.list_cons.comp fst.to_unary₂ snd.to_unary₂) snd.to_unary₂ } },\nthis.of_eq (λ a, by simp[list.filter_eq_foldr]) \n\n@[rcomputability]\nlemma list_rec [inhabited β] {f : α → list β} {g : α → γ} {h : α → β → list β → γ → γ} {o : σ →. τ}\n (hf : f computable_in o) (hg : g computable_in o) (hh : prod.unpaired4 h computable_in o) :\n @rcomputable _ _ γ _ _ _ _ _ (λ a : α, list.rec_on (f a) (g a) (h a)) o :=\nlet F (a : α) := (f a).foldr\n (λ (b : β) (s : list β × γ), (b :: s.1, h a b s.1 s.2)) ([], g a) in\nhave F computable_in o,\n from list_foldr ((rcomputable₂.list_cons.comp fst.to_unary₂ (fst.comp snd.to_unary₂)).pair hh)\n ((const list.nil).pair hg) hf,\n(snd.comp this).of_eq (λ a, by { \n suffices : F a = (f a, list.rec_on (f a) (g a) (λ b l IH, h a b l IH)), { rw this },\n simp[F], induction (f a); simp* })\n\n@[rcomputability]\nlemma omega_ordering_Min [inhabited α] (r : omega_ordering α) {o : σ →. τ}\n (hr : r.ordering computable_in o) :\n r.Min computable_in o :=\nbegin\n let F : list α → option α := list.foldr\n (λ (a : α) (IH : option α), option.cases_on IH a\n (λ ih, if omega_ordering.ordering a ≤ omega_ordering.ordering ih then a else ih)) none,\n have : F computable_in o,\n { simp[F],\n refine list_foldr (option_cases snd.to_unary₂ ((option_some.comp rpartrec.some).comp fst.to_unary₂) _) (const none) id',\n { refine rcomputable.ite _ _ _,\n { refine rcomputable₂.to_bool_nat_le.comp (comp hr (fst.comp snd.to_unary₁)) (to_unary₂ hr) },\n { exact option_some.comp (fst.comp snd.to_unary₁) },\n exact (option_some.comp rpartrec.some).to_unary₂ } },\n exact this.of_eq (λ l, by { induction l with x l IH, { simp[F, omega_ordering.Min] },\n { simp[F, omega_ordering.Min] at IH ⊢, rw[IH], cases C : r.Min l; simp,\n { simp[omega_ordering.min_iff],\n by_cases C : omega_ordering.ordering x ≤ omega_ordering.ordering val; simp[C] } } })\nend\n\n@[rcomputability]\nlemma omega_ordering_Min_le [inhabited α] (r : omega_ordering α) (f : β → list α) (h : ∀ x, (f x).length > 0) {o : σ →. τ}\n (hr : r.ordering computable_in o) (hf : f computable_in o) :\n (λ x, r.Min_le (f x) (h x)) computable_in o :=\nrcomputable.option_get ((omega_ordering_Min r hr).comp hf)\n\n@[rcomputability]\nlemma rcomputable.list_initial [inhabited α] {o : σ →. τ} : ((↾*) : list α → ℕ → list α) computable₂_in o :=\nbegin\n let lindex : list α → list (α × ℕ) := λ l, list.rec_on l [] (λ a l IH, (a, l.length) :: IH),\n let F : list α → ℕ → list α := λ l n, ((lindex l).filter (λ p : α × ℕ, p.2 < n)).map prod.fst,\n have : F computable₂_in o,\n { refine list_map (fst.to_unary₂)\n (list_filter (rcomputable₂.to_bool_nat_lt.comp (snd.to_unary₂) (snd.to_unary₁))\n (list_rec fst (const [])\n (rcomputable₂.list_cons.comp (pair fst.to_unary₂ (list_length.comp (fst.comp snd.to_unary₂)))\n (snd.comp snd.to_unary₂)))) },\n exact this.of_eq (λ l n, by { \n induction l with x l IH; simp[F, lindex, list.filter],\n { have : @list.rec α (λ _, list (α × ℕ)) [] (λ (a : α) (l : list α), list.cons (a, l.length)) (x :: l) = \n (x, l.length) :: lindex l, from rfl,\n simp[show @list.rec α (λ _, list (α × ℕ)) [] (λ (a : α) (l : list α), list.cons (a, l.length)) (x :: l) = \n (x, l.length) :: lindex l, from rfl, list.filter],\n by_cases C : l.length < n; simp[C],\n { simp[show (x :: l)↾*n = x :: l, from list.initial_elim (nat.succ_le_iff.mpr C),\n show l↾*n = l, from list.initial_elim (le_of_lt C),\n F, lindex] at IH ⊢, exact IH },\n { have : (x :: l)↾*n = l↾*n, from list.initial_cons (not_lt.mp C),\n rw this, exact IH } } })\nend\n\n@[rcomputability]\nlemma list_weight_of [inhabited α] {wt : α → ℕ} {o : σ →. τ}\n (h : wt computable_in o) : list.weight_of wt computable_in o :=\nbegin\n let F : list α → ℕ := λ l, list.rec_on l 0 (λ a l IH, nat.mkpair (wt a) IH + 1),\n have : F computable_in o,\n { refine rcomputable.list_rec id (const 0) _,\n exact rcomputable₂.nat_add.comp\n (rcomputable₂.comp rpartrec.some (comp h fst.to_unary₂) (snd.comp snd.to_unary₂))\n (const 1) },\n exact this.of_eq (λ l, by { induction l with x l IH; simp[F, list.weight_of], { simp[F] at IH, simp[IH] } })\nend\n\n@[rcomputability]\ntheorem list_chr [decidable_eq α] [inhabited α] {o : σ →. τ} :\n (list.chr : list α → α → bool) computable₂_in o :=\nbegin\n let F : list α → α → bool := λ l a, l.filter (λ x, x = a) ≠ [],\n have : F computable₂_in o,\n { simp[F],\n refine (dom_fintype bnot).comp₂\n ((rcomputable₂.to_bool_eq _).comp\n (rcomputable.list_filter ((rcomputable₂.to_bool_eq _).comp snd snd.to_unary₁) fst) (const [])) },\n exact this.of_eq (λ l a, by simp[F, list.filter_eq_nil, list.chr])\nend\n\n@[rcomputability]\ntheorem graph_rcomp [decidable_eq β] (f : α → β) : graph f computable_in (f : α →. β) :=\n have c₀ : (λ x, to_bool (x.1 = x.2) : β × β → bool) computable_in (f : α →. β) := primrec.eq.to_rcomp,\n have c₂ : (λ x, (f x.1, x.2) : α × β → β × β) computable_in (f : α →. β) := rcomputable.pair \n (rcomputable.refl.comp rcomputable.fst) rcomputable.snd,\nc₀.comp c₂\n\n@[rcomputability]\ntheorem subseq_rcomputable [decidable_eq α] [inhabited α] (f : ℕ → α) :\n list.subseq f computable_in! f :=\nbegin\n let g := (λ x, (x.2.1 + 1, x.2.2 && graph f (x.2.1, x.1)) : α × ℕ × bool → ℕ × bool),\n let subseq0 := (λ x, (list.foldr (λ y z, g (y, z)) (0, tt) x) : list α → ℕ × bool),\n let subseq1 := (λ x, (subseq0 x).2),\n have cg : g computable_in (f : ℕ →. α) := ((computable.succ.to_rcomp).comp (fst.comp snd)).pair \n ((primrec.to_rcomp (primrec.dom_bool₂ band)).comp $\n (snd.comp snd).pair $\n (rcomputable.graph_rcomp f).comp ((fst.comp snd).pair fst)),\n have cic : subseq1 computable_in (f : ℕ →. α) := rcomputable.snd.comp (\n list_foldr (cg.comp (pair fst.to_unary₂ snd.to_unary₂)) ((const 0).pair (const tt)) id),\n have e : ∀ l, subseq0 l = (l.length, list.subseq f l),\n { intros l, simp[subseq0], induction l with ld ll ihl; simp[list.subseq,graph],\n rw ihl, simp, rw bool.band_comm, simp [eq_comm], congr },\n exact (cic.of_eq $ λ l, by simp[subseq1,e])\nend\n\nprivate lemma rfind_fin0 {p : α → ℕ → bool} {f : α → ℕ} {g : α → ℕ} {h : β →. τ}\n (hp : prod.unpaired p computable_in h) (hf : f computable_in h) (hg : g computable_in h) :\n (λ a, nat.rfind_fin0 (p a) (f a) (g a) : α → option ℕ) computable_in h :=\nbegin\n let f₁ : α × ℕ × option ℕ → option ℕ :=\n (λ x, cond (p x.1 (f x.1 - x.2.1.succ)) (some $ f x.1 - x.2.1.succ) x.2.2),\n have c₁ : f₁ computable_in h,\n { refine rcomputable.cond\n (hp.comp (fst.pair ((primrec.to_rcomp primrec.nat_sub).comp $\n (hf.comp fst).pair (computable.succ.to_rcomp.comp $ fst.comp snd))))\n (primrec.option_some.to_rcomp.comp ((primrec.to_rcomp primrec.nat_sub).comp $\n (hf.comp fst).pair (computable.succ.to_rcomp.comp $ fst.comp snd))) (snd.comp snd) },\n have e : ∀ a b n, nat.elim option.none (λ y IH, cond (p a (b - y.succ)) (some $ b - y.succ) IH) n = \n nat.rfind_fin0 (p a) b n,\n { intros a b n, simp, induction n with n0 ih; simp[nat.rfind_fin0], rw ih },\n have c₂ := nat_elim hg (const option.none) c₁,\n exact (c₂.of_eq $ λ n, by simp[f₁]; simp; rw e)\nend\n\n@[rcomputability]\ntheorem rfind_fin {p : α → ℕ → bool} {f : α → ℕ} {g : β →. τ}\n (hp : p computable₂_in g) (hf : f computable_in g) :\n (λ a, nat.rfind_fin (p a) (f a)) computable_in g := \nrfind_fin0 hp hf hf\n\nend rcomputable\n\nopen nat.rpartrec primrec\nvariables {α : Type*} {σ : Type*} {β : Type*} {τ : Type*} {γ : Type*} {μ : Type*} {ν : Type*} {o_dom : Type*} {o_cod : Type*}\n [primcodable α] [primcodable σ] [primcodable β] [primcodable τ] [primcodable γ] [primcodable μ] [primcodable ν] [primcodable o_dom] [primcodable o_cod]\n {o : o_dom →. o_cod}\n\naxiom rcomputable.code_rec {f : α → code} {fo : α → σ} {fz : α → σ} {fs : α → σ} {fl : α → σ} {fr : α → σ}\n {fp : α → code → code → σ → σ → σ} {fc : α → code → code → σ → σ → σ} {fpr : α → code → code → σ → σ → σ} {frf : α → code → σ → σ}\n (hfo : fo computable_in o) (hfz : fz computable_in o) (hfs : fs computable_in o) (hfl : fl computable_in o) (hfr : fr computable_in o)\n (hfp : prod.unpaired5 fp computable_in o) (hfc : prod.unpaired5 fc computable_in o) (hfpr : prod.unpaired5 fpr computable_in o)\n (hfrf : prod.unpaired3 frf computable_in o) :\n @rcomputable α _ σ _ _ _ _ _ (λ a, code.rec_on (f a) (fo a) (fz a) (fs a) (fl a) (fr a) (fp a) (fc a) (fpr a) (frf a)) o\n\n-- !!!! AXIOM !!!!\naxiom primrec.evaln_to_fn :\n primrec (λ x : ℕ × list (ℕ × ℕ) × code × ℕ, code.evaln x.1 x.2.1.to_fn x.2.2.1 x.2.2.2)\n\ntheorem computable.evaln_to_fn\n {s : α → ℕ} {l : α → list (ℕ × ℕ)} {c : α → code} {n : α → ℕ}\n (hs : computable s) (hl : computable l) (hc : computable c) (hn : computable n) :\n computable (λ x, code.evaln (s x) (l x).to_fn (c x) (n x)) :=\nprimrec.evaln_to_fn.to_comp.comp (hs.pair $ hl.pair $ hc.pair hn)\n\ntheorem eval_eq_rfind (f : ℕ → option ℕ) (c n) :\n code.eval f c n = nat.rfind_opt (λ s, code.evaln s f c n) :=\npart.ext $ λ x, begin\n refine code.evaln_complete.trans (nat.rfind_opt_mono _).symm,\n intros a m n hl, apply code.evaln_mono hl,\nend\n\ntheorem partrec.eval_to_fn {α} [primcodable α]\n {l : α → list (ℕ × ℕ)} {c : α → code} {n : α → ℕ}\n (hl : computable l) (hc : computable c) (hn : computable n) :\n partrec (λ x, code.eval (l x).to_fn (c x) (n x)) :=\nbegin\n let f := (λ x, nat.rfind_opt (λ s, code.evaln s (l x).to_fn (c x) (n x))),\n have : partrec f := (partrec.rfind_opt $\n computable.evaln_to_fn computable.snd\n (hl.comp computable.fst) (hc.comp computable.fst) (hn.comp computable.fst)),\n exact (this.of_eq $ by simp[f, eval_eq_rfind])\nend\n\ntheorem list.to_fn_map [decidable_eq σ] [denumerable σ]\n (f : τ → option μ) (c : list (σ × τ)) (n) :\n (c.to_fn n).map f = (c.map (λ x : σ × τ, (x.1, f x.2))).to_fn n :=\nbegin\n cases C : c.to_fn n with v; simp; symmetry,\n { simp [list.to_fn_iff_none] at C ⊢, intros m o x y eqn_xy eqn_n,\n have := C m y, simp [eqn_n] at eqn_xy, contradiction },\n { simp [list.to_fn_iff] at C ⊢, rcases C with ⟨m, eqn_nv, hyp⟩,\n refine ⟨m, ⟨n, v, eqn_nv, rfl, rfl⟩, λ k p eqn_k x y eqn_xy eqn_n eqn_p, _⟩,\n have := hyp _ y eqn_k, rw [eqn_n] at eqn_xy, contradiction }\nend\n\ntheorem list.to_fn_encode_of_nat {σ} [decidable_eq σ] [denumerable σ]\n (c : list (σ × τ)) :\n (λ n, option.map encode (c.to_fn (of_nat σ n))) = \n (c.map (λ x : σ × τ, (encode x.1, encode x.2))).to_fn :=\nbegin\n funext n,\n cases C : c.to_fn (of_nat σ n) with v; simp; symmetry,\n { simp [list.to_fn_iff_none] at C ⊢, intros m k x y eqn_xy eqn_n eqn_k,\n have := C m y, rw ←eqn_n at this, simp at this, contradiction },\n { simp [list.to_fn_iff] at C ⊢, rcases C with ⟨m, eqn_nv, hyp⟩,\n refine ⟨m, ⟨_, _, eqn_nv, (by simp), rfl⟩, λ k z eqn_k x y eqn_xy eqn_n eqn_z, _⟩,\n have := hyp _ y eqn_k, rw ←eqn_n at this, simp at this, contradiction }\nend\n\ntheorem computable.univn_to_fn (α σ) [primcodable α] [primcodable σ] {β} [decidable_eq β] [denumerable β]\n {i : γ → ℕ} {l : γ → list (β × τ)} {s : γ → ℕ} {n : γ → α}\n (hi : computable i) (hl : computable l) (hs : computable s) (hn : computable n) :\n computable (λ x : γ, (⟦i x⟧*(l x).to_fn [s x] (n x) : option σ)) :=\nbegin\n simp [univn, list.to_fn_encode_of_nat],\n refine computable.option_bind (computable.evaln_to_fn hs\n ((list_map primrec.id ((primrec.encode.comp $ fst.comp snd).pair\n (primrec.encode.comp $ snd.comp snd)).to₂).to_comp.comp hl)\n ((primrec.of_nat _).to_comp.comp hi)\n (primrec.encode.to_comp.comp hn))\n (primrec.decode.comp snd).to_comp\nend\n\ntheorem partrec.univ_to_fn (α σ) [primcodable α] [decidable_eq σ] [denumerable σ]\n {i : γ → ℕ} {l : γ → list (σ × τ)} {n : γ → α}\n (hi : computable i) (hl : computable l) (hn : computable n) :\n partrec (λ x : γ, (⟦i x⟧*(l x).to_fn (n x) : part σ)) :=\nbegin\n simp [univ, list.to_fn_encode_of_nat],\n refine partrec.bind (partrec.eval_to_fn\n ((list_map primrec.id ((primrec.encode.comp $ fst.comp snd).pair\n (primrec.encode.comp $ snd.comp snd)).to₂).to_comp.comp hl)\n ((primrec.of_nat _).to_comp.comp hi)\n (primrec.encode.to_comp.comp hn))\n ((primrec.of_nat _).comp snd).to_comp\nend\n\ntheorem rcomputable.evaln_w {s : α → ℕ} {f : ℕ → option ℕ} {c : α → code} {n : α → ℕ} {o : β →. σ}\n (hs : s computable_in o) (hf : f computable_in o) (hc : c computable_in o) (hn : n computable_in o) : \n (λ x, code.evaln (s x) f (c x) (n x)) computable_in o :=\nbegin\n let u := (λ x, code.evaln (s x) (f↾(s x)).to_fn (c x) (n x)),\n have eqn_u : (λ x, code.evaln (s x) f (c x) (n x)) = u,\n { suffices :\n ∀ t d, code.evaln t (f↾t).to_fn d = code.evaln t f d,\n { funext, simp[u] at this ⊢, rw this },\n intros t d,\n apply code.evaln_use,\n intros u eqn_u,\n { cases C : f u,\n { exact nat.initialpart_to_fn_none C t },\n { exact nat.initialpart_to_fn (show encode u < t, from eqn_u) C } } },\n rw eqn_u,\n simp only [u],\n let m := (λ x, (s x, f↾s x, c x, n x)),\n have lmm_m : m computable_in o := (rcomputable.pair hs \n (((rcomputable.initialpart hf).comp hs).pair (rcomputable.pair hc hn))),\n have := computable.evaln_to_fn fst.to_comp (fst.comp snd).to_comp\n (fst.comp $ snd.comp snd).to_comp (snd.comp $ snd.comp snd).to_comp,\n have := this.to_rcomp.comp lmm_m,\n exact this\nend\n\ntheorem rcomputable.evaln_s {s : α → ℕ} {f : α → ℕ → option ℕ} {c : α → code} {n : α → ℕ} {o : β →. σ}\n (hs : s computable_in o) (hf : f computable₂_in o) (hc : c computable_in o) (hn : n computable_in o) : \n (λ x, code.evaln (s x) (f x) (c x) (n x)) computable_in o :=\nbegin\n let u := (λ x, code.evaln (s x) ((f x)↾(s x)).to_fn (c x) (n x)),\n have eqn_u : (λ x, code.evaln (s x) (f x) (c x) (n x)) = u,\n { suffices :\n ∀ x t d, code.evaln t ((f x)↾t).to_fn d = code.evaln t (f x) d,\n { funext, simp[u] at this ⊢, rw this }, \n intros x t d,\n apply code.evaln_use,\n intros u eqn_u,\n { cases C : f x u,\n { exact nat.initialpart_to_fn_none C t },\n { exact nat.initialpart_to_fn (show encode u < t, from eqn_u) C } } },\n rw eqn_u,\n simp only [u],\n let m := (λ x, (s x, (f x)↾s x, c x, n x)),\n have lmm_m : m computable_in o := (rcomputable.pair hs \n (rcomputable.pair (rcomputable.initialpart_s hf hs) (hc.pair hn))),\n have := computable.evaln_to_fn fst.to_comp (fst.comp snd).to_comp\n (fst.comp $ snd.comp snd).to_comp (snd.comp $ snd.comp snd).to_comp,\n have := this.to_rcomp.comp lmm_m,\n exact this\nend\n\ntheorem rcomputable.evaln_tot {s : α → ℕ} {f : ℕ → ℕ} {c : α → code} {n : α → ℕ} {o : β →. σ}\n (hs : s computable_in o) (hf : f computable_in o) (hc : c computable_in o) (hn : n computable_in o) : \n (λ x, code.evaln (s x) ↑ₒf (c x) (n x)) computable_in o := \nrcomputable.evaln_w hs (rcomputable.option_some_iff.mpr hf) hc hn\n\ntheorem rcomputable.evaln_tot_s {s : α → ℕ} {f : α → ℕ → ℕ} {c : α → code} {n : α → ℕ} {o : β →. σ}\n (hs : s computable_in o) (hf : f computable₂_in o) (hc : c computable_in o) (hn : n computable_in o) : \n (λ x, code.evaln (s x) ↑ₒ(f x) (c x) (n x)) computable_in o := \nrcomputable.evaln_s hs (rcomputable.option_some_iff.mpr hf) hc hn\n\ntheorem rpartrec.eval_w {f : ℕ → option ℕ} {c : α → code} {n : α → ℕ} {o : β →. σ}\n (hf : f computable_in o) (hc : c computable_in o) (hn : n computable_in o) :\n (λ x, code.eval f (c x) (n x)) partrec_in o :=\nbegin\n let p := (λ x, nat.rfind_opt (λ s, code.evaln s f (c x) (n x))),\n have : p partrec_in o,\n { apply rpartrec.rfind_opt, \n refine (rcomputable.evaln_w rcomputable.snd hf\n (hc.comp rcomputable.fst) (hn.comp rcomputable.fst)) },\n exact (this.of_eq $ λ a, by simp [p, eval_eq_rfind])\nend\n\ntheorem rpartrec.eval_s {f : α → ℕ → option ℕ} {c : α → code} {n : α → ℕ} {o : β →. σ}\n (hf : f computable₂_in o) (hc : c computable_in o) (hn : n computable_in o) :\n (λ x, code.eval (f x) (c x) (n x)) partrec_in o :=\nbegin \n let p := (λ x, nat.rfind_opt (λ s, code.evaln s (f x) (c x) (n x))),\n have : p partrec_in o,\n { apply rpartrec.rfind_opt, \n refine (rcomputable.evaln_s rcomputable.snd\n (rcomputable₂.comp₂ hf rcomputable.fst.to_unary₁ rcomputable.id'.to_unary₂)\n (hc.comp rcomputable.fst) (hn.comp rcomputable.fst)) },\n exact (this.of_eq $ λ a, by simp [p, eval_eq_rfind])\nend\n\ntheorem rpartrec.eval_tot {f : ℕ → ℕ} {c : α → code} {n : α → ℕ} {o : β →. σ}\n (hf : f computable_in o) (hc : c computable_in o) (hn : n computable_in o) :\n (λ x, code.eval (↑ₒf) (c x) (n x)) partrec_in o :=\nrpartrec.eval_w (rcomputable.option_some_iff.mpr hf) hc hn\n\ntheorem rpartrec.eval_tot_s {f : α → ℕ → ℕ} {c : α → code} {n : α → ℕ} {o : β →. σ}\n (hf : f computable₂_in o) (hc : c computable_in o) (hn : n computable_in o) :\n (λ x, code.eval (↑ₒ(f x)) (c x) (n x)) partrec_in o :=\nrpartrec.eval_s (rcomputable.option_some_iff.mpr hf) hc hn\n\ntheorem rcomputable.univn_w (α σ) [primcodable α] [primcodable σ]\n {i : γ → ℕ} {p : β → option τ} {s : γ → ℕ} {n : γ → α} {o : μ →. ν}\n (hi : i computable_in o) (hp : p computable_in o) (hs : s computable_in o) (hn : n computable_in o) :\n (λ x, ⟦i x⟧*p [s x] (n x) : γ → option σ) computable_in o :=\nbegin\n simp [univn],\n refine rcomputable.option_bind (rcomputable.evaln_w hs\n (rcomputable.option_bind primrec.decode.to_rcomp _)\n ((primrec.of_nat _).to_rcomp.comp hi)\n (primrec.encode.to_rcomp.comp hn)) _,\n { refine rcomputable.option_map _ _,\n { exact hp.comp rcomputable.snd },\n { exact (primrec.encode.comp snd).to_rcomp } },\n { exact (primrec.decode.comp snd).to_rcomp }\nend\n\ntheorem rpartrec.univ_w (α σ) [primcodable α] [primcodable σ]\n {i : γ → ℕ} {p : β → option τ} {n : γ → α} {o : μ →. ν}\n (hi : i computable_in o) (hp : p computable_in o) (hn : n computable_in o) :\n (λ x, ⟦i x⟧*p (n x) : γ →. σ) partrec_in o :=\nbegin\n simp [univ],\n refine rpartrec.bind (rpartrec.eval_w\n (rcomputable.option_bind primrec.decode.to_rcomp _)\n ((primrec.of_nat _).to_rcomp.comp hi)\n (primrec.encode.to_rcomp.comp hn)) _,\n { refine rcomputable.option_map (hp.comp rcomputable.snd) _,\n refine (primrec.encode.comp snd).to_rcomp },\n { refine (primrec.decode.comp snd).to_comp.of_option.to_rpart }\nend\n\n@[rcomputability]\ntheorem rcomputable.univn_tot (α σ) [primcodable α] [primcodable σ]\n {i : γ → ℕ} {f : β → τ} {s : γ → ℕ} {n : γ → α} {o : μ →. ν}\n (hi : i computable_in o) (hf : f computable_in o) (hs : s computable_in o) (hn : n computable_in o) :\n (λ x, ⟦i x⟧^f [s x] (n x) : γ → option σ) computable_in o :=\nrcomputable.univn_w _ _ hi (rcomputable.option_some_iff.mpr hf) hs hn\n\n@[rcomputability]\ntheorem rpartrec.univ_tot (α σ) [primcodable α] [primcodable σ]\n {i : γ → ℕ} {f : β → τ} {n : γ → α} {o : μ →. ν}\n (hi : i computable_in o) (hf : f computable_in o) (hn : n computable_in o) :\n (λ x, ⟦i x⟧^f (n x) : γ →. σ) partrec_in o :=\nrpartrec.univ_w _ _ hi (rcomputable.option_some_iff.mpr hf) hn\n\ntheorem rcomputable.univn_s (α σ) [primcodable α] [primcodable σ]\n {i : γ → ℕ} {p : γ → β → option τ} {s : γ → ℕ} {n : γ → α} {o : μ →. ν}\n (hi : i computable_in o) (hp : p computable₂_in o) (hs : s computable_in o) (hn : n computable_in o) :\n (λ x, ⟦i x⟧*(p x) [s x] (n x) : γ → option σ) computable_in o :=\nrcomputable.option_bind (rcomputable.evaln_s hs\n (rcomputable.option_bind (rcomputable.decode.to_unary₂)\n ((rcomputable.id'.option_map rcomputable.encode.to_unary₂).comp₂\n (rcomputable₂.comp₂ hp rcomputable.fst.to_unary₁ rcomputable.id'.to_unary₂)))\n ((primrec.of_nat _).to_rcomp.comp hi)\n (primrec.encode.to_rcomp.comp hn)) (rcomputable.decode.to_unary₂)\n\ntheorem rpartrec.univ_s (α σ) [primcodable α] [primcodable σ]\n {i : γ → ℕ} {p : γ → β → option τ} {n : γ → α} {o : μ →. ν}\n (hi : i computable_in o) (hp : p computable₂_in o) (hn : n computable_in o) :\n (λ x, ⟦i x⟧*(p x) (n x) : γ →. σ) partrec_in o :=\nrpartrec.bind (rpartrec.eval_s\n (rcomputable.option_bind (rcomputable.decode.to_unary₂)\n ((rcomputable.id'.option_map rcomputable.encode.to_unary₂).comp₂\n (rcomputable₂.comp₂ hp rcomputable.fst.to_unary₁ rcomputable.id'.to_unary₂)))\n ((primrec.of_nat _).to_rcomp.comp hi)\n (primrec.encode.to_rcomp.comp hn)) ((rpartrec.coe.comp rcomputable.decode).to_unary₂)\n\n@[rcomputability]\ntheorem rcomputable.univn_tot_s (α σ) [primcodable α] [primcodable σ]\n {i : γ → ℕ} {f : γ → β → τ} {s : γ → ℕ} {n : γ → α} {o : μ →. ν}\n (hi : i computable_in o) (hf : f computable₂_in o) (hs : s computable_in o) (hn : n computable_in o) :\n (λ x, ⟦i x⟧^(f x) [s x] (n x) : γ → option σ) computable_in o :=\nrcomputable.univn_s _ _ hi (rcomputable.option_some_iff.mpr hf) hs hn\n\n@[rcomputability]\ntheorem rpartrec.univ_tot_s (α σ) [primcodable α] [primcodable σ]\n {i : γ → ℕ} {f : γ → β → τ} {n : γ → α} {o : μ →. ν}\n (hi : i computable_in o) (hf : f computable₂_in o) (hn : n computable_in o) :\n (λ x, ⟦i x⟧^(f x) (n x) : γ →. σ) partrec_in o :=\nrpartrec.univ_s _ _ hi (rcomputable.option_some_iff.mpr hf) hn\n\ntheorem rpartrec.exists_index {f : α →. σ} {g : β → τ} :\n f partrec_in! g ↔ ∃ e, ⟦e⟧^g = f :=\nbegin\n split,\n { let g' := (λ n, (decode β n).bind (λ a, some $ encode (g a))),\n have : (λ (n : ℕ), (of_option (decode β n)).bind (λ (a : β), some (encode (g a)))) = ↑ʳg',\n { funext n, simp [g'], cases decode β n; simp [of_option] },\n simp[univ, rpartrec_tot, rpartrec, nat.rpartrec.reducible], unfold_coes, rw this,\n assume h, rcases code.exists_code_opt.mp h with ⟨c, eqn_c⟩,\n refine ⟨encode c, funext $ λ a, _⟩, simp [eqn_c, part.of_option] },\n { rintros ⟨e, rfl⟩, refine rpartrec.univ_tot _ _\n (primrec.const e).to_rcomp rcomputable.refl rcomputable.id }\nend\n\n@[rcomputability]\ntheorem univ_partrec_in {f : α → σ} {e} :\n (⟦e⟧^f : β →. τ) partrec_in! f :=\nrpartrec.univ_tot _ _ (primrec.const e).to_rcomp rcomputable.refl rcomputable.id\n\nnamespace rpartrec\n\nsection\n\nlemma in_complement (p : α →. β) [∀ a, decidable (p a).dom] : p partrec_in! p.complement :=\n(rpartrec.coe.comp rpartrec.refl).of_eq (λ a, by simp)\n\nend\n\n@[rcomputability]\nprotected theorem cond {c : α → bool} {f : α →. σ} {g : α →. σ} {h : β → τ}\n (hc : c computable_in! h) (hf : f partrec_in! h) (hg : g partrec_in! h) :\n (λ a, cond (c a) (f a) (g a)) partrec_in! h :=\nbegin\n rcases exists_index.1 hf with ⟨e, eqn_e⟩,\n rcases exists_index.1 hg with ⟨i, eqn_i⟩,\n have := rpartrec.univ_tot α σ (rcomputable.cond hc (rcomputable.const e) (rcomputable.const i))\n rcomputable.refl rcomputable.id,\n exact (this.of_eq $ λ a, by cases eqn : c a; simp[eqn, eqn_e, eqn_i])\nend\n\ntheorem bool_to_part (c : α → bool):\n (λ a, cond (c a) (some 0) part.none : α →. ℕ) partrec_in (c : α →. bool) :=\nrpartrec.cond rcomputable.refl (rcomputable.const 0) partrec.none.to_rpart\n\ntheorem universal_index {f : β → τ} : ∃ u, ∀ (x : ℕ) (y : α),\n (⟦u⟧^f (x, y) : part σ) = ⟦x⟧^f y :=\nby rcases exists_index.mp \n (rpartrec.univ_tot α σ rcomputable.fst (rcomputable.refl_in f) rcomputable.snd) with ⟨u, hu⟩;\n exact ⟨u, by simp[hu]⟩\n\ntheorem recursion (α σ) [primcodable α] [primcodable σ] (f : β → τ) :\n ∃ fixpoint : ℕ → ℕ, primrec fixpoint ∧\n ∀ {I : ℕ → ℕ} {i}, ⟦i⟧^f = ↑ᵣI →\n (⟦fixpoint i⟧^f : α →. σ) = ⟦I (fixpoint i)⟧^f :=\nbegin\n have : ∃ j, (⟦j⟧^f : ℕ × α →. σ) = λ a, (⟦a.1⟧^f a.1).bind (λ n : ℕ, ⟦n⟧^f a.2),\n { have this := (rpartrec.univ_tot ℕ ℕ rcomputable.fst rcomputable.refl rcomputable.fst).bind\n ((rpartrec.univ_tot α σ rcomputable.snd rcomputable.refl (snd.comp fst).to_rcomp)).to₂,\n exact exists_index.mp this },\n rcases this with ⟨j, lmm_j⟩,\n have : ∃ k, ⟦k⟧^f = λ (a : ℕ × ℕ), ⟦a.1⟧^f (curry j a.2),\n { have := rpartrec.curry_prim.to_comp.comp (computable.const j) computable.id,\n have := (rpartrec.univ_tot ℕ ℕ rcomputable.fst rcomputable.refl \n (this.to_rcomp.comp rcomputable.snd)),\n exact exists_index.mp this },\n rcases this with ⟨k, lmm_k⟩,\n let fixpoint : ℕ → ℕ := λ x, curry j (curry k x),\n have : primrec fixpoint := rpartrec.curry_prim.comp (primrec.const j)\n (rpartrec.curry_prim.comp (primrec.const k) primrec.id),\n refine ⟨fixpoint, this, _⟩,\n assume I i h, funext x,\n show ⟦fixpoint i⟧^f x = ⟦I (fixpoint i)⟧^f x,\n simp[fixpoint, lmm_j, lmm_k, h],\nend\n\ntheorem recursion1 (α σ) [primcodable α] [primcodable σ]\n {f : β → τ} {I : ℕ → ℕ} (h : I computable_in ↑ᵣf) :\n ∃ n, (⟦n⟧^f : α →. σ) = ⟦I n⟧^f :=\nby rcases recursion α σ f with ⟨fixpoint, cf, hfix⟩;\n rcases exists_index.mp h with ⟨i, hi⟩;\n exact ⟨fixpoint i, hfix hi⟩\n\nend rpartrec\n\nnoncomputable def bounded_computation (f : α →. σ) (h : β → τ) (s : ℕ) : α → option σ :=\n⟦classical.epsilon (λ e : ℕ, ⟦e⟧^h = f)⟧^h [s]\n\nnotation f`^`h` .[`s`]` := bounded_computation f h s\n \ntheorem bounded_computation_spec {f : α →. σ} {h : β → τ} (hf : f partrec_in! h)\n {x y} : y ∈ f x ↔ ∃ s, f^h.[s] x = some y :=\nbegin\n have : y ∈ ⟦classical.epsilon (λ (y : ℕ), ⟦y⟧^h = f)⟧^h x ↔\n ∃ (s : ℕ), ⟦classical.epsilon (λ e, ⟦e⟧^h = f)⟧^h [s] x = some y,\n from rpartrec.univn_complete,\n have eqn := classical.epsilon_spec (rpartrec.exists_index.mp hf), simp[eqn] at this,\n exact this\nend\n\ndef usen_pfun (σ) [primcodable σ] (p : β → option τ) (e : ℕ) (s : ℕ) (x : α) : part (option ℕ) :=\ncond ((⟦e⟧*p [s] x : option σ)).is_some\n ((nat.rfind $ λ u : ℕ, (⟦e⟧*p [u] x : option σ).is_some).map option.some)\n (some option.none)\n\nlemma usen_pfun_defined {p : β → option τ} {e : ℕ} {s : ℕ} {x : α} :\n (usen_pfun σ p e s x).dom :=\nbegin\n simp [usen_pfun],\n cases C : (⟦e⟧*p [s] x).is_some; simp [C, part.dom],\n refine ⟨s, _⟩, simp[C, part.some]\nend \n\ndef usen (σ) [primcodable σ] (f : β → option τ) (e : ℕ) (s : ℕ) (x : α) : option ℕ :=\n(usen_pfun σ f e s x).get usen_pfun_defined\n\ndef usen0 (σ) [primcodable σ] (e : ℕ) (s : ℕ) (x : α) : option ℕ := usen σ ↑ₒ(λ _, 0 : ℕ → ℕ) e s x\n\nnotation `Φ⟦` e `⟧^`f ` [` s `]` := usen _ ↑ₒf e s\n\nnotation `Φ⟦` e `⟧⁰` ` [` s `]` := usen0 _ e s\n\n@[rcomputability]\ntheorem rcomputable.usen_tot (σ) [primcodable σ]\n {f : β → τ} {i : γ → ℕ} {s : γ → ℕ} {a : γ → α} {o : μ → ν}\n (hf : f computable_in! o) (hi : i computable_in! o) (hs : s computable_in! o) (ha : a computable_in! o) :\n (λ x, usen σ ↑ₒf (i x) (s x) (a x)) computable_in! o :=\nbegin\n suffices :\n (λ x, usen_pfun σ ↑ₒf (i x) (s x) (a x)) partrec_in! o,\n from (this.of_eq $ λ n, by simp [usen]),\n refine rpartrec.cond _ _ _,\n { refine primrec.option_is_some.to_rcomp.comp (rcomputable.univn_tot _ _ hi hf hs ha) },\n { refine (rpartrec.rfind _).map _,\n { refine primrec.option_is_some.to_rcomp.comp\n (rcomputable.univn_tot _ _ (hi.comp rcomputable.fst) hf rcomputable.snd (ha.comp rcomputable.fst)) },\n { refine (primrec.succ.comp snd).to_rcomp } },\n { refine rcomputable.const _ }\nend\n\n@[rcomputability]\ntheorem computable.usen_to_fn (σ) [primcodable σ] {β} [decidable_eq β] [denumerable β]\n {l : γ → list (β × τ)} {i : γ → ℕ} {s : γ → ℕ} {a : γ → α} {o : μ → ν}\n (hl : computable l) (hi : computable i) (hs : computable s) (ha : computable a) :\n computable (λ x, usen σ (l x).to_fn (i x) (s x) (a x)) :=\nbegin\n suffices :\n partrec (λ x, usen_pfun σ (l x).to_fn (i x) (s x) (a x)),\n from (this.of_eq $ λ n, by simp [usen] ),\n refine partrec.cond _ _ _,\n { refine (option_is_some.to_comp.comp (computable.univn_to_fn α σ hi hl hs ha))},\n { refine (partrec.rfind _).map _,\n { refine primrec.option_is_some.to_comp.comp\n (computable.univn_to_fn _ _ (hi.comp computable.fst) (hl.comp computable.fst)\n computable.snd (ha.comp computable.fst)) },\n refine (primrec.succ.to_comp.comp computable.snd) },\n { refine (const _).to_comp }\nend\n\ntheorem usen_eq_tt {p : β → option τ} {e : ℕ} {s : ℕ} {x : α}\n (h : (⟦e⟧*p [s] x : option σ).is_some = tt) :\n usen σ p e s x = ((nat.rfind (λ u, (⟦e⟧*p [u] x).is_some)).get (rfind_dom_total ⟨s, h⟩)) :=\nby simp [usen, usen_pfun, h, map]\n\ntheorem usen_eq_ff {p : β → option τ} {e : ℕ} {s : ℕ} {x : α}\n (h : (⟦e⟧*p [s] x : option σ).is_some = ff) :\n usen σ p e s x = none :=\nby simp [usen, usen_pfun, h, map]\n\ntheorem usen_is_some_iff {p : β → option τ} {e : ℕ} {s : ℕ} {x : α} :\n (usen σ p e s x).is_some ↔ (⟦e⟧*p [s] x : option σ).is_some :=\nby { cases C : (⟦e⟧*p [s] x).is_some, { simp[usen_eq_ff C] }, { simp[usen_eq_tt C] } }\n\ntheorem usen_step_tt {p : β → option τ} {e : ℕ} {s : ℕ} {x : α}\n {u : ℕ} (hu : usen σ p e s x = u) :\n (⟦e⟧*p [u] x : option σ).is_some = tt :=\nbegin\n have : (⟦e⟧*p [s] x : option σ).is_some, { simp[←usen_is_some_iff, hu] },\n simp [usen_eq_tt this] at hu,\n have : u ∈ nat.rfind (λ u, (⟦e⟧*p [u] x).is_some), rw ←hu, from get_mem _,\n simp at this, simp [this.1]\nend\n\ntheorem usen_consumption_step {p : ℕ → option τ} {e : ℕ} {s : ℕ} {x : α} {y : σ}\n {u : ℕ} (hu : usen σ p e s x = u) :\n ⟦e⟧*p [s] x = some y → ∀ {q : ℕ → option τ}, (∀ n, n < u → q n = p n) →\n ⟦e⟧*q [u] x = some y := λ h q hq,\nbegin\n suffices : (⟦e⟧*q [u] : α → option σ) = ⟦e⟧*p [u],\n { simp [this], have := usen_step_tt hu,\n rcases option.is_some_iff_exists.mp this with ⟨z, hz⟩,\n simp [rpartrec.univn_mono_eq h hz, hz] },\n apply rpartrec.univn_use, exact hq\nend\n\ntheorem usen_le {p : β → option τ} {e : ℕ} {s : ℕ} {x : α}\n (u : ℕ) (hu : usen σ p e s x = u) : u ≤ s :=\nbegin\n cases h : (⟦e⟧*p [s] x : option σ).is_some,\n { exfalso, simp[usen_eq_ff h] at hu, contradiction },\n { simp [usen_eq_tt h] at hu, rcases hu with rfl,\n let u := (nat.rfind ↑(λ u, (⟦e⟧*p [u] x).is_some)).get (rfind_dom_total ⟨_, h⟩),\n suffices : u ≤ s, from this,\n have eqn : u ≤ s ∨ s < u, from le_or_lt u s, cases eqn, refine eqn,\n exfalso,\n have : u ∈ nat.rfind (λ u, (⟦e⟧*p [u] x).is_some), from get_mem _,\n simp at this,\n have := this.2 eqn, simp [h] at this, refine this }\nend\n\ndef usen_mono {p : β → option τ} {e : ℕ} {x : α}\n {m n u : ℕ} (le : u ≤ n) (hm : usen σ p e m x = u) : usen σ p e n x = u :=\nbegin\n have mdom : (⟦e⟧*p [m] x : option σ).is_some, from usen_is_some_iff.mp (by simp[hm]),\n have udom : (⟦e⟧*p [u] x : option σ).is_some, from usen_step_tt hm,\n have ndom : (⟦e⟧*p [n] x : option σ).is_some, from rpartrec.univn_dom_mono le udom, \n have : usen σ p e m x = (nat.rfind (λ u, (⟦e⟧*p [u] x).is_some)).get _, from usen_eq_tt mdom,\n have : usen σ p e n x = usen σ p e m x, simp[this], from usen_eq_tt ndom,\n simp[this, hm]\nend\n\ndef use (σ) [primcodable σ] (p : β → option τ) (e : ℕ) (x : α) : part ℕ :=\nnat.rfind_opt (λ s, usen σ p e s x)\n\n@[rcomputability]\ntheorem rcomputable.use_tot (σ) [primcodable σ]\n {f : β → τ} {i : γ → ℕ} {s : γ → ℕ} {a : γ → α} {o : μ → τ}\n (hf : f computable_in! o) (hi : i computable_in! o) (hs : s computable_in! o) (ha : a computable_in! o) :\n (λ x, use σ ↑ₒf (i x) (a x)) partrec_in! o :=\nrpartrec.rfind_opt\n (rcomputable.usen_tot _ hf (rcomputable.to_unary₁ hi)\n ((rpartrec.of_option' rcomputable.id').to_unary₂) (rcomputable.to_unary₁ ha))\n \ndef use0 (σ) [primcodable σ] (e : ℕ) (x : α) : part ℕ := use σ ↑ₒ(λ _, 0 : ℕ → ℕ) e x\n\nnotation `Φ⟦` e `⟧^`f := use _ ↑ₒf e\n\nnotation `Φ⟦` e `⟧⁰ ` x := use0 _ e x\n\ntheorem use_dom_iff {p : β → option τ} {e : ℕ} {x : α} :\n (use σ p e x).dom ↔ (⟦e⟧*p x : part σ).dom :=\ncalc (use σ p e x).dom ↔ ∃ s, (usen σ p e s x).is_some : by simp[use, nat.rfind_opt_dom, option.is_some_iff_exists]\n ... ↔ ∃ s, (⟦e⟧*p [s] x : option σ).is_some : by simp[usen_is_some_iff]\n ... ↔ (⟦e⟧*p x : part σ).dom : iff.symm rpartrec.univn_dom_complete\n\ntheorem use_eq_iff {p : β → option τ} {e : ℕ} {x : α} {u : ℕ} :\n u ∈ use σ p e x ↔ usen σ p e u x = u :=\ncalc u ∈ use σ p e x ↔ ∃ s, usen σ p e s x = u : nat.rfind_opt_mono (λ u m n le h, usen_mono ((usen_le u h).trans le) h)\n ... ↔ usen σ p e u x = u : ⟨λ ⟨s, eq_use⟩, usen_mono (by refl) eq_use, λ h, ⟨u, h⟩⟩\n", "meta": {"author": "iehality", "repo": "lean-reducibility", "sha": "82a7e3ec0fcedfb0d69c25e77bcd24c9b29626b7", "save_path": "github-repos/lean/iehality-lean-reducibility", "path": "github-repos/lean/iehality-lean-reducibility/lean-reducibility-82a7e3ec0fcedfb0d69c25e77bcd24c9b29626b7/src/function.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167793123159, "lm_q2_score": 0.02976009330057041, "lm_q1q2_score": 0.013719902365463}} {"text": "/-\nCopyright (c) 2020 Eric Wieser. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Eric Wieser\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.default\nimport Mathlib.PostPort\n\nuniverses u_1 u_2 \n\nnamespace Mathlib\n\n/-!\n# Extra facts about `pprod`\n-/\n\n@[simp] theorem pprod.mk.eta {α : Sort u_1} {β : Sort u_2} {p : PProd α β} : { fst := pprod.fst p, snd := pprod.snd p } = p :=\n pprod.cases_on p fun (a : α) (b : β) => rfl\n\n", "meta": {"author": "AurelienSaue", "repo": "Mathlib4_auto", "sha": "590df64109b08190abe22358fabc3eae000943f2", "save_path": "github-repos/lean/AurelienSaue-Mathlib4_auto", "path": "github-repos/lean/AurelienSaue-Mathlib4_auto/Mathlib4_auto-590df64109b08190abe22358fabc3eae000943f2/Mathlib/data/pprod.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.2720245392906821, "lm_q2_score": 0.05033062903628872, "lm_q1q2_score": 0.013691166175806666}} {"text": "import category_theory.lifting_properties.basic\nimport category_theory.adjunction.basic\n\nnamespace category_theory\n\nopen category\n\nvariables {C D : Type*} [category C] [category D]\n {G : C ⥤ D} {F : D ⥤ C}\n\n/-namespace comm_sq\n\nsection\nvariables {A B : C} {X Y : D} {i : A ⟶ B} {p : X ⟶ Y}\n {u : G.obj A ⟶ X} {v : G.obj B ⟶ Y}\n (sq : comm_sq u (G.map i) p v) (adj : G ⊣ F)\n\ninclude sq adj\n\ndef right_adjoint :\n comm_sq (adj.hom_equiv _ _ u) i (F.map p) (adj.hom_equiv _ _ v) :=\n⟨begin\n simp only [adjunction.hom_equiv_unit, assoc, ← F.map_comp, sq.w],\n rw [F.map_comp, adjunction.unit_naturality_assoc],\nend⟩\n\ndef right_adjoint_lift_struct_equiv :\n sq.lift_struct ≃ (sq.right_adjoint adj).lift_struct :=\n{ to_fun := λ l,\n { l := adj.hom_equiv _ _ l.l,\n fac_left' := by rw [← adj.hom_equiv_naturality_left, l.fac_left],\n fac_right' := by rw [← adjunction.hom_equiv_naturality_right, l.fac_right], },\n inv_fun := λ l,\n { l := (adj.hom_equiv _ _).symm l.l,\n fac_left' := begin\n rw [← adjunction.hom_equiv_naturality_left_symm, l.fac_left],\n apply (adj.hom_equiv _ _).left_inv,\n end,\n fac_right' := begin\n rw [← adjunction.hom_equiv_naturality_right_symm, l.fac_right],\n apply (adj.hom_equiv _ _).left_inv,\n end, },\n left_inv := by tidy,\n right_inv := by tidy, }\n\n@[simp]\nlemma right_adjoint_has_lift_iff :\n has_lift (sq.right_adjoint adj) ↔ has_lift sq :=\nbegin\n simp only [has_lift.iff],\n exact equiv.nonempty_congr (sq.right_adjoint_lift_struct_equiv adj).symm,\nend\n\ninstance [has_lift sq] : has_lift (sq.right_adjoint adj) :=\nby { rw right_adjoint_has_lift_iff, apply_instance, }\n\nend\nsection\nvariables {A B : C} {X Y : D} {i : A ⟶ B} {p : X ⟶ Y}\n {u : A ⟶ F.obj X} {v : B ⟶ F.obj Y}\n (sq : comm_sq u i (F.map p) v) (adj : G ⊣ F)\n\ninclude sq adj\n\ndef left_adjoint :\n comm_sq ((adj.hom_equiv _ _).symm u) (G.map i) p\n ((adj.hom_equiv _ _).symm v) :=\n⟨begin\n simp only [adjunction.hom_equiv_counit, assoc,\n ← G.map_comp_assoc, ← sq.w],\n rw [G.map_comp, assoc, adjunction.counit_naturality],\nend⟩\n\ndef left_adjoint_lift_struct_equiv :\n sq.lift_struct ≃ (sq.left_adjoint adj).lift_struct :=\n{ to_fun := λ l,\n { l := (adj.hom_equiv _ _).symm l.l,\n fac_left' := by rw [← adj.hom_equiv_naturality_left_symm, l.fac_left],\n fac_right' := by rw [← adj.hom_equiv_naturality_right_symm, l.fac_right], },\n inv_fun := λ l,\n { l := (adj.hom_equiv _ _) l.l,\n fac_left' := begin\n rw [← adj.hom_equiv_naturality_left, l.fac_left],\n apply (adj.hom_equiv _ _).right_inv,\n end,\n fac_right' := begin\n rw [← adj.hom_equiv_naturality_right, l.fac_right],\n apply (adj.hom_equiv _ _).right_inv,\n end, },\n left_inv := by tidy,\n right_inv := by tidy, }\n\n@[simp]\nlemma left_adjoint_has_lift_iff :\n has_lift (sq.left_adjoint adj) ↔ has_lift sq :=\nbegin\n simp only [has_lift.iff],\n exact equiv.nonempty_congr (sq.left_adjoint_lift_struct_equiv adj).symm,\nend\n\nend\n\nend comm_sq-/\n\nnamespace has_lifting_property\n\n/-lemma iff_of_adjunction (adj : G ⊣ F) {A B : C} {X Y : D} (i : A ⟶ B) (p : X ⟶ Y) :\n has_lifting_property (G.map i) p ↔ has_lifting_property i (F.map p) :=\nbegin\n split,\n { introI,\n constructor,\n intros f g sq,\n rw ← sq.left_adjoint_has_lift_iff adj,\n apply_instance, },\n { introI,\n constructor,\n intros f g sq,\n rw ← sq.right_adjoint_has_lift_iff adj,\n apply_instance, },\nend\n\nlemma of_arrow_iso_left {A B A' B' X Y : C} {i : A ⟶ B} {i' : A' ⟶ B'}\n (e : arrow.mk i ≅ arrow.mk i') (p : X ⟶ Y)\n [hip : has_lifting_property i p] : has_lifting_property i' p :=\nbegin\n have eq : i' = (arrow.left_func.map_iso e).inv ≫ i ≫ (arrow.right_func.map_iso e).hom,\n { simp only [functor.map_iso_inv, arrow.left_func_map, functor.map_iso_hom,\n arrow.right_func_map, arrow.w_mk_right_assoc, arrow.mk_hom],\n have eq' := arrow.hom.congr_right e.inv_hom_id,\n dsimp at eq' ⊢,\n rw [eq', category.comp_id], },\n rw eq,\n apply_instance,\nend\n\nlemma of_arrow_iso_right {A B X Y X' Y' : C} (i : A ⟶ B) {p : X ⟶ Y} {p' : X' ⟶ Y'}\n (e : arrow.mk p ≅ arrow.mk p')\n [hip : has_lifting_property i p] : has_lifting_property i p' :=\nbegin\n have eq : p' = (arrow.left_func.map_iso e).inv ≫ p ≫ (arrow.right_func.map_iso e).hom,\n { simp only [functor.map_iso_inv, arrow.left_func_map, functor.map_iso_hom,\n arrow.right_func_map, arrow.w_mk_right_assoc, arrow.mk_hom],\n have eq' := arrow.hom.congr_right e.inv_hom_id,\n dsimp at eq' ⊢,\n rw [eq', category.comp_id], },\n rw eq,\n apply_instance,\nend\n\nlemma iff_of_arrow_iso_left {A B A' B' X Y : C} {i : A ⟶ B} {i' : A' ⟶ B'}\n (e : arrow.mk i ≅ arrow.mk i') (p : X ⟶ Y) :\n has_lifting_property i p ↔ has_lifting_property i' p :=\nby { split; introI, exacts [of_arrow_iso_left e p, of_arrow_iso_left e.symm p], }\n\nlemma iff_of_arrow_iso_right {A B X Y X' Y' : C} (i : A ⟶ B) {p : X ⟶ Y} {p' : X' ⟶ Y'}\n (e : arrow.mk p ≅ arrow.mk p') :\n has_lifting_property i p ↔ has_lifting_property i p' :=\nby { split; introI, exacts [of_arrow_iso_right i e, of_arrow_iso_right i e.symm], }-/\n\nend has_lifting_property\n\nend category_theory\n", "meta": {"author": "joelriou", "repo": "dold-kan", "sha": "a083fe264275774ac49ac520caf25f2ee29debb1", "save_path": "github-repos/lean/joelriou-dold-kan", "path": "github-repos/lean/joelriou-dold-kan/dold-kan-a083fe264275774ac49ac520caf25f2ee29debb1/src/for_mathlib/lifting_properties_misc.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4921881357207955, "lm_q2_score": 0.0275852831261459, "lm_q1q2_score": 0.01357714907518807}} {"text": "import tactic\nimport category_theory.functor\nimport data.W.basic\nimport category_theory.closed.types\nimport algebra.category.CommRing.basic\nimport algebra.category.Module.basic\n\nuniverses w x u v \n\nopen category_theory\n\nvariables (𝒞 : Type u) [category.{v} 𝒞]\n\n@[protect_proj] structure struc : Type (max u v (w+1) (x+1)) :=\n( F : 𝒞 → Type w )\n[ cat : category.{x} (sigma F) ]\n( fst_map : Π {A B : sigma F} (f : A ⟶ B), A.1 ⟶ B.1 )\n( fst_map_id : ∀ (A : sigma F), fst_map (𝟙 A) = 𝟙 A.1 )\n( fst_map_comp : ∀ {A B C : sigma F} (f : A ⟶ B) (g : B ⟶ C),\n fst_map (f ≫ g) = fst_map f ≫ fst_map g )\n\nnamespace struc\n\ninstance : has_coe_to_fun (struc 𝒞) (λ _, 𝒞 → Type w) :=\n{ coe := struc.F }\n\nvariables {𝒞} {F : struc 𝒞}\n\ninstance : category (sigma F) := F.cat\n\ndef fst : sigma F ⥤ 𝒞 :=\n{ obj := sigma.fst,\n map := F.fst_map,\n map_id' := F.fst_map_id,\n map_comp' := F.fst_map_comp }\n\ninstance (X : 𝒞) : category_struct (F X) :=\n{ hom := λ A B, { f : sigma.mk X A ⟶ ⟨X, B⟩ // fst.map f = 𝟙 X },\n id := λ A, ⟨𝟙 _, by simp; refl⟩,\n comp := λ A B C f g, ⟨f.1 ≫ g.1, by erw [functor.map_comp, f.2, g.2, category.comp_id]⟩ }\n\ninstance (X : 𝒞) : category (F X) :=\n{ comp_id' := λ _ _ _, subtype.ext (category.comp_id _),\n id_comp' := λ _ _ _, subtype.ext (category.id_comp _),\n assoc' := λ _ _ _ _ _ _ _, subtype.ext (category.assoc _ _ _) }\n\nopen opposite\n\ndef of_functor (F : 𝒞 ⥤ Type w) : struc 𝒞 :=\n{ F := F.obj,\n cat := \n { hom := λ A B, {f : A.1 ⟶ B.1 // F.map f A.2 = B.2 },\n id := λ A, ⟨𝟙 A.1, by simp⟩,\n comp := λ A B C f g, ⟨f.1 ≫ g.1, by simp [f.prop, g.prop]⟩,\n comp_id' := λ _ _ _, subtype.ext (category.comp_id _),\n id_comp' := λ _ _ _, subtype.ext (category.id_comp _),\n assoc' := λ _ _ _ _ _ _ _, subtype.ext (category.assoc _ _ _) },\n fst_map := λ _ _, subtype.val,\n fst_map_id := by intros; refl,\n fst_map_comp := by intros; refl }\n\ndef Module₂ : struc Ring :=\n{ F := λ R, Module R,\n cat :=\n { hom := λ A B, Σ f : A.1 ⟶ B.1, A.2 →ₛₗ[f] B.2,\n id := λ A, ⟨𝟙 A.1, linear_map.id⟩,\n comp := λ A B C f g, ⟨f.1 ≫ g.1, \n @linear_map.comp _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ⟨rfl⟩ g.2 f.2⟩,\n comp_id' := by { intros, cases f, cases f_fst, cases f_snd, refl },\n id_comp' := by { intros, cases f, cases f_fst, cases f_snd, refl },\n assoc' := by { intros, refl } },\n fst_map := λ _ _ f, f.fst,\n fst_map_id := by intros; refl,\n fst_map_comp := by intros; refl }\n\n\ndef of_category (𝒟 : Type*) [category 𝒟] : struc 𝒞 :=\n{ F := λ _, 𝒟,\n cat := \n { hom := λ A B, (A.1 ⟶ B.1) × (A.2 ⟶ B.2),\n id := λ _, (𝟙 _, 𝟙 _),\n comp := λ A B C f g, (f.1 ≫ g.1, f.2 ≫ g.2),\n comp_id' := λ A B f, prod.ext (category.comp_id _) (category.comp_id _),\n id_comp' := λ A B f, prod.ext (category.id_comp _) (category.id_comp _),\n assoc' := λ A B C D f g h, prod.ext (category.assoc _ _ _) (category.assoc _ _ _) },\n fst_map := λ _ _, prod.fst,\n fst_map_id := λ _, rfl,\n fst_map_comp := by intros; refl }\n\nvariable (𝒞)\n\ndef type : struc 𝒞 := of_category (Type v)\n\ndef prop : struc 𝒞 := of_category Prop\n\nlemma hcongr {α α' : Sort*}\n {β : α → Sort*} {β' : α' → Sort*} {f : Π a, β a}\n {g : Π a, β' a} (hβ : β == β')\n (a a') (h : f == g) (ha : a == a') :\n f a == g a' :=\nbegin\n have := type_eq_of_heq ha,\n subst this,\n simp at *,\n substs hβ ha,\n simp at *,\n subst h\nend\n\n\ndef sigma_pi (F : 𝒞 ⥤ Type) (G : struc (sigma (of_functor F))) : struc 𝒞 :=\n{ F := λ X, Π a : F.obj X, G.F ⟨X, a⟩,\n cat := \n { hom := λ A B, Σ (f : A.1 ⟶ B.1), \n Π (a : of_functor F A.1) (b : of_functor F B.1) (hab : b = F.map f a), \n sigma.mk (sigma.mk A.1 a) (A.2 a) ⟶ sigma.mk (sigma.mk B.1 b) (B.2 b),\n id := λ X, ⟨𝟙 X.1, λ x y h, cast (by simp [F.map_id] at h; rw h) \n (𝟙 (sigma.mk (sigma.mk X.1 x) (X.2 x)))⟩,\n comp := λ X Y Z f g, ⟨f.1 ≫ g.1, \n λ a b h, cast (by simp) (f.2 a _ rfl ≫ g.2 (F.map f.1 a) b (by simp [h]))⟩,\n comp_id' := λ X Y f, begin \n cases f with f₁ f₂,\n ext,\n { simp },\n { refl },\n { intros a a' h,\n rw heq_iff_eq at h,\n subst a',\n dsimp,\n apply function.hfunext,\n { refl },\n { intros b b' h,\n rw [heq_iff_eq] at h,\n subst b',\n apply function.hfunext,\n simp,\n intros _ h _,\n subst h,\n simp } }\n end,\n id_comp' := λ X Y f, begin \n cases f with f₁ f₂,\n ext,\n { simp },\n { refl },\n { intros a a' h,\n dsimp,\n rw heq_iff_eq at h,\n subst a',\n apply function.hfunext,\n { refl },\n { intros b b' h,\n rw heq_iff_eq at h,\n subst b',\n apply function.hfunext,\n { simp * at * },\n { intros,\n simp * at *,\n convert category.id_comp (f₂ a b a'),\n { simp },\n { rw [F.map_id],\n refl },\n { simp },\n { simp } } } }\n end,\n assoc' := λ W X Y Z f g h, begin\n ext, simp [category.assoc],\n intros a a' h,\n rw [heq_iff_eq] at h,\n subst h,\n simp,\n apply function.hfunext,\n { refl },\n { intros b b' h,\n rw heq_iff_eq at h,\n subst b',\n apply function.hfunext,\n { simp [category.assoc] },\n { intros c c' h,\n simp,\n dsimp,\n congr,\n { simp },\n { rw F.map_comp, refl },\n { apply hcongr,\n apply function.hfunext,\n rw F.map_comp; refl,\n intros,\n rw [F.map_comp],\n refl,\n rw [F.map_comp],\n refl,\n exact proof_irrel_heq _ _ },\n { apply hcongr,\n apply function.hfunext,\n rw F.map_comp; refl,\n intros,\n rw [F.map_comp],\n refl,\n rw [F.map_comp],\n refl,\n exact proof_irrel_heq _ _ } } }\n end },\n fst_map := λ _ _ f, f.fst,\n fst_map_id := by intros; refl,\n fst_map_comp := by intros; refl }\n\nexample : 1 = 1 := rfl\n\ndef sigma_arrow (F : 𝒞 ⥤ Type) (G : struc 𝒞) : struc 𝒞 :=\n{ F := λ X, F.obj X → G X,\n cat := \n { hom := λ A B, Σ (f : A.1 ⟶ B.1), \n Π (a : of_functor F A.1) (b : of_functor F B.1) (h : b = F.map f a), \n { g : sigma.mk A.1 (A.2 a) ⟶ sigma.mk B.1 (B.2 b) // fst.map g = f } ,\n id := λ X, ⟨𝟙 X.1, λ x y h, ⟨cast (by simp [h]) (𝟙 (sigma.mk X.1 (X.2 x))), \n begin simp, end⟩⟩,\n comp := λ X Y Z f g, ⟨f.1 ≫ g.1, \n λ x z h, cast (by simp [h]) (f.2 x (F.map f.1 x) rfl ≫ g.2 (F.map f.1 x) z (by simp [h]))⟩,\n comp_id' := λ X Y f, \n begin \n cases f with f₁ f₂,\n ext,\n { simp },\n { refl },\n { intros a a' h,\n rw heq_iff_eq at h,\n subst a',\n apply function.hfunext,\n { refl },\n { intros b b' h,\n rw heq_iff_eq at h,\n subst b',\n dsimp,\n apply function.hfunext,\n { simp },\n { intros _ h _,\n subst h,\n simp } } }\n end,\n id_comp' := λ X Y f, begin \n cases f with f₁ f₂,\n ext,\n { simp },\n { refl },\n { intros a a' h,\n dsimp,\n rw heq_iff_eq at h,\n subst a',\n apply function.hfunext,\n { refl },\n { intros b b' h,\n rw heq_iff_eq at h,\n subst b',\n apply function.hfunext,\n { simp * at * },\n { intros,\n simp * at *,\n convert category.id_comp (f₂ a b a'),\n { simp },\n { simp },\n { simp } } } }\n end,\n assoc' := λ W X Y Z f g h, begin\n ext, simp [category.assoc],\n intros a a' h,\n rw [heq_iff_eq] at h,\n subst h,\n simp,\n apply function.hfunext,\n { refl },\n { intros b b' h,\n rw heq_iff_eq at h,\n subst b',\n apply function.hfunext,\n { simp [category.assoc] },\n { intros c c' h,\n simp,\n dsimp,\n congr,\n { simp },\n { apply hcongr,\n apply function.hfunext,\n rw F.map_comp; refl,\n intros,\n rw [F.map_comp],\n refl,\n rw [F.map_comp],\n refl,\n exact proof_irrel_heq _ _ },\n { apply hcongr,\n apply function.hfunext,\n rw F.map_comp; refl,\n intros,\n rw [F.map_comp],\n refl,\n rw [F.map_comp],\n refl,\n exact proof_irrel_heq _ _ } } }\n end },\n fst_map := λ _ _ f, f.fst,\n fst_map_id := by intros; refl,\n fst_map_comp := by intros; refl }\n\n-- def sigma_arrow (F : struc 𝒞) (G : struc 𝒞) : struc 𝒞 :=\n-- { F := λ X, Σ (i : F X → G X), \n-- (Π (a b : F X), (sigma.mk X a ⟶ ⟨X, b⟩) → \n-- { f : sigma.mk X (i a) ⟶ ⟨X, i b⟩ // fst.map f = 𝟙 X}),\n-- cat := \n-- { hom := λ A B, Σ (f : A.1 ⟶ B.1), Π (a : F A.1) (b : F B.1),\n-- (sigma.mk A.1 a ⟶ sigma.mk B.1 b) →\n-- { g : (sigma.mk A.1 (A.2.1 a)) ⟶ (sigma.mk B.1 (B.2.1 b)) // fst.map g = f },\n-- id := λ A, ⟨𝟙 _, λ a b f, A.2.2 a b f⟩,\n-- comp := λ A B C f g, ⟨f.1 ≫ g.1, λ a c h, \n-- begin\n-- have := sigma.snd f a,\n \n-- end⟩,\n-- comp_id' := sorry,\n-- id_comp' := sorry,\n-- assoc' := sorry },\n\n-- fst_map := λ _ _ f, f.fst,\n-- fst_map_id := by intros; refl,\n-- fst_map_comp := by intros; refl }\n\n\n-- def sigma_pi₂ (F : struc 𝒞) (G : struc (sigma F)) : struc 𝒞 :=\n-- { F := λ X, Σ (i : Π a : F X, G.F ⟨X, a⟩), \n-- (Π (a b : F X) (f : sigma.mk X a ⟶ sigma.mk X b), \n-- { g : sigma.mk (sigma.mk X a) (i a) ⟶ ⟨⟨X, b⟩, i b⟩ // fst.map g = f }),\n-- cat := \n-- { hom := λ A B, Σ (f : A.1 ⟶ B.1), (Π (a : F A.1) (b : F B.1), \n-- (sigma.mk A.1 a ⟶ sigma.mk B.1 b) → \n-- (sigma.mk (sigma.mk A.1 a) (A.2.1 a) ⟶ ⟨⟨B.1, b⟩, B.2.1 b⟩)),\n-- id := λ A, ⟨𝟙 _, λ a b f, (A.2.2 a b f).1⟩,\n-- comp := λ A B C f g, ⟨f.1 ≫ g.1, λ a c h, \n-- begin\n-- have := sigma.snd f a,\n \n-- end⟩,\n-- comp_id' := sorry,\n-- id_comp' := sorry,\n-- assoc' := sorry },\n\n-- fst_map := λ _ _ f, f.fst,\n-- fst_map_id := by intros; refl,\n-- fst_map_comp := by intros; refl }\n\nend struc", "meta": {"author": "ChrisHughes24", "repo": "coq-and-lean-playground", "sha": "7da672891e29c0434909abad315ca6efefcbb989", "save_path": "github-repos/lean/ChrisHughes24-coq-and-lean-playground", "path": "github-repos/lean/ChrisHughes24-coq-and-lean-playground/coq-and-lean-playground-7da672891e29c0434909abad315ca6efefcbb989/lean/parametricity/sigma_category/struc3.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4921881357207956, "lm_q2_score": 0.027585281127577247, "lm_q1q2_score": 0.013577148091516292}} {"text": "import algebra.homology.quasi_iso\nimport algebra.homology.short_complex.pseudoelements\nimport for_mathlib.algebra.homology.hom_complex_shift\nimport category_theory.triangulated.triangulated\nimport for_mathlib.algebra.homology.homological_complex_limits\n\nnoncomputable theory\nopen category_theory category_theory.category category_theory.limits\n category_theory.pretriangulated\n\n@[simp]\nlemma category_theory.limits.biprod.is_zero_iff {C : Type*} [category C]\n [has_zero_morphisms C] (A B : C)\n [has_binary_biproduct A B] : is_zero (biprod A B) ↔ is_zero A ∧ is_zero B :=\nbegin\n split,\n { intro h,\n simp only [is_zero.iff_id_eq_zero],\n split,\n { rw ← cancel_mono (biprod.inl : _ ⟶ A ⊞ B),\n apply h.eq_of_tgt, },\n { rw ← cancel_mono (biprod.inr : _ ⟶ A ⊞ B),\n apply h.eq_of_tgt, }, },\n { rintro ⟨h₁, h₂⟩,\n rw is_zero.iff_id_eq_zero,\n ext1,\n { apply h₁.eq_of_src, },\n { apply h₂.eq_of_src, }, },\nend\n\nopen category_theory category_theory.category category_theory.limits\n category_theory.pretriangulated\n\nnamespace cochain_complex\n\nvariables {C : Type*} [category C]\n\nsection preadditive\n\nvariables [preadditive C]\n {F G : cochain_complex C ℤ} [∀ p, has_binary_biproduct (F.X (p+1)) (G.X p)]\n (φ : F ⟶ G)\n\nopen hom_complex\n\ninclude φ\n\ndef mapping_cone : cochain_complex C ℤ :=\n{ X := λ i, F.X (i+1) ⊞ G.X i,\n d := λ i j, begin\n by_cases i+1 = j,\n { exact -biprod.fst ≫ F.d _ _ ≫ biprod.inl +\n biprod.fst ≫ (cochain.of_hom φ).v (i+1) j (by simpa only [add_zero, ← h]) ≫ biprod.inr +\n biprod.snd ≫ G.d _ _ ≫ biprod.inr,\n },\n { exact 0, },\n end,\n shape' := λ i j (hij : i+1 ≠ j), by rw dif_neg hij,\n d_comp_d' := λ i j k (hij : i+1=j) (hjk : j+1=k), begin\n simp only [dif_pos hij, hjk, dif_pos rfl],\n substs hij hjk,\n ext1,\n { dsimp,\n simp only [assoc, preadditive.comp_add, preadditive.add_comp, preadditive.neg_comp,\n preadditive.comp_neg, biprod.inl_fst_assoc, biprod.inl_snd_assoc, zero_comp,\n F.d_comp_d_assoc, neg_zero, zero_add, biprod.inr_fst_assoc, biprod.inr_snd_assoc,\n comp_zero, add_zero, cochain.of_hom_v, φ.comm_assoc, add_left_neg], },\n { simp only [assoc, preadditive.comp_add, preadditive.add_comp, preadditive.neg_comp,\n preadditive.comp_neg, biprod.inr_fst_assoc, biprod.inr_snd_assoc, zero_comp,\n comp_zero, neg_zero, zero_add, G.d_comp_d_assoc], },\n end, }\n\nomit φ\n\nnamespace mapping_cone\n\ninclude φ\n\nlemma X_is_zero_iff (n : ℤ) :\n is_zero ((mapping_cone φ).X n) ↔ is_zero (F.X (n+1)) ∧ is_zero (G.X n) :=\nbiprod.is_zero_iff _ _\n\ndef inl : cochain F (mapping_cone φ) (-1) :=\ncochain.mk (λ p q hpq, (cochain.of_hom (𝟙 F)).v p (q+1) (by linarith) ≫ biprod.inl)\n\ndef inr : G ⟶ mapping_cone φ :=\ncocycle.hom_of\n (cocycle.mk (cochain.mk (λ p q hpq,\n (cochain.of_hom (𝟙 G)).v p q hpq ≫ biprod.inr)) 1 (zero_add 1)\n begin\n ext1 p _ rfl,\n dsimp [mapping_cone],\n simp only [cochain.zero_v,\n δ_v 0 1 (zero_add 1) _ p _ rfl p (p+1) (by linarith) rfl,\n zero_add, cochain.mk_v, cochain.of_hom_v, homological_complex.id_f, id_comp,\n ε_1, neg_smul, one_zsmul, dif_pos rfl, preadditive.comp_add,\n preadditive.comp_neg, biprod.inr_fst_assoc, zero_comp, neg_zero,\n biprod.inr_snd_assoc, add_right_neg],\n end)\n\ndef fst : cocycle (mapping_cone φ) F 1 :=\ncocycle.mk (cochain.mk (λ p q hpq, biprod.fst ≫\n (cochain.of_hom (𝟙 F)).v (p+1) q (by simpa only [add_zero] using hpq))) 2 (by linarith)\n begin\n ext1 p q hpq,\n have hpq' : q = p + 1 + 1 := by linarith,\n subst hpq',\n dsimp [mapping_cone],\n simp only [δ_v 1 2 (by linarith) _ p (p+1+1) (by linarith) (p+1) (p+1) (by linarith) rfl,\n dif_pos rfl, ε_succ, ε_1, neg_neg, one_smul, cochain.mk_v, cochain.of_hom_v, id_comp,\n homological_complex.id_f, assoc, preadditive.add_comp, preadditive.comp_add, comp_id,\n preadditive.neg_comp, preadditive.comp_neg, biprod.inl_fst, biprod.inr_fst, comp_zero,\n add_zero, add_right_neg],\n end\n\ndef snd : cochain (mapping_cone φ) G 0 :=\ncochain.mk (λ p q hpq, biprod.snd ≫ (cochain.of_hom (𝟙 G)).v p q hpq)\n\n@[simp, reassoc]\nlemma inl_fst (p q : ℤ) (hpq : p = q+1) :\n (inl φ).v p q (by rw [hpq, int.add_neg_one, add_tsub_cancel_right]) ≫\n (fst φ : cochain (mapping_cone φ) F 1).v q p hpq = 𝟙 _ :=\nbegin\n subst hpq,\n dsimp [inl, fst],\n simp only [cochain.of_hom_v, homological_complex.id_f, id_comp, biprod.inl_fst_assoc],\n erw [cochain.of_hom_v, homological_complex.id_f],\nend\n\n@[simp, reassoc]\nlemma inl_snd (p q : ℤ) (hpq : q = p+(-1)) :\n (inl φ).v p q hpq ≫ (snd φ).v q q (add_zero q).symm = 0 :=\nbegin\n dsimp [inl, snd],\n simp only [assoc, biprod.inl_snd_assoc, zero_comp, comp_zero],\nend\n\n@[simp, reassoc]\nlemma inr_fst (p q : ℤ) (hpq : q = p+1) :\n (inr φ).f p ≫ (fst φ : cochain (mapping_cone φ) F 1).v p q hpq = 0 :=\nbegin\n subst hpq,\n dsimp [inr, fst],\n simp only [cochain.of_hom_v, homological_complex.id_f, id_comp, biprod.inr_fst_assoc, zero_comp],\nend\n\n@[simp, reassoc]\nlemma inr_snd (p : ℤ) :\n (inr φ).f p ≫ (snd φ).v p p (add_zero p).symm = 𝟙 _ :=\nbegin\n dsimp [inr, snd],\n simp only [assoc, biprod.inr_snd, cochain.of_hom_v, homological_complex.id_f, comp_id],\nend\n\nlemma id (p q : ℤ) (hpq : q = p+1) :\n (fst φ : cochain (mapping_cone φ) F 1).v p q hpq ≫\n (inl φ).v q p (by rw [hpq, int.add_neg_one, add_tsub_cancel_right]) +\n (snd φ).v p p (add_zero p).symm ≫ (inr φ).f p = 𝟙 _ :=\nbegin\n subst hpq,\n dsimp [inl, inr, fst, snd],\n simp only [cochain.of_hom_v, homological_complex.id_f, id_comp, assoc],\n erw [cochain.of_hom_v, homological_complex.id_f, id_comp],\n apply biprod.total,\nend\n\n@[reassoc]\nlemma inl_d (n₁ n₂ n₃ : ℤ) (h₁₂ : n₁ = n₂ + (-1)) (h₂₃ : n₂ = n₃ + (-1)) :\n (inl φ).v n₂ n₁ h₁₂ ≫ (mapping_cone φ).d n₁ n₂ =\n φ.f n₂ ≫ (inr φ).f n₂ - F.d n₂ n₃ ≫ (inl φ).v _ _ h₂₃ :=\nbegin\n have hn₂ : n₂ = n₁ + 1 := by linarith,\n have hn₃ : n₃ = n₁ + 1 + 1 := by linarith,\n substs hn₂ hn₃,\n dsimp [mapping_cone, inl, inr],\n simp only [dif_pos rfl, add_zero, cochain.of_hom_v, homological_complex.id_f, id_comp,\n preadditive.comp_add, preadditive.comp_neg, biprod.inl_fst_assoc,\n biprod.inl_snd_assoc, zero_comp],\n erw [cochain.of_hom_v, neg_add_eq_sub],\nend\n\n@[simp, reassoc]\nlemma inr_d (n n' : ℤ) :\n (inr φ).f n ≫ (mapping_cone φ).d n n' =\n G.d n n' ≫ (inr φ).f n' :=\nbegin\n by_cases h : n+1 = n',\n { subst h,\n dsimp [inr, mapping_cone],\n simp only [dif_pos rfl],\n simp only [cochain.of_hom_v, homological_complex.id_f, id_comp, preadditive.comp_add,\n preadditive.comp_neg, biprod.inr_fst_assoc, zero_comp, neg_zero,\n biprod.inr_snd_assoc, zero_add], },\n { change ¬ (complex_shape.up ℤ).rel n n' at h,\n simp only [homological_complex.shape _ _ _ h, zero_comp, comp_zero], },\nend\n\nattribute [irreducible] mapping_cone inl inr fst snd\n\n@[simps]\ndef X_iso (n i : ℤ) (hi : i = n+1) [has_binary_biproduct (F.X i) (G.X n)] :\n (mapping_cone φ).X n ≅ F.X i ⊞ G.X n :=\n{ hom := (fst φ : cochain (mapping_cone φ) F 1).v n i hi ≫ biprod.inl +\n (snd φ).v n n (add_zero n).symm ≫ biprod.inr,\n inv := biprod.fst ≫ (inl φ).v i n (by linarith) + biprod.snd ≫ (inr φ).f n,\n hom_inv_id' := by simp only [add_zero, zero_add, preadditive.comp_add,\n preadditive.add_comp_assoc, assoc, biprod.inl_fst, comp_id, biprod.inr_fst,\n comp_zero, biprod.inl_snd, biprod.inr_snd, id],\n inv_hom_id' := begin\n ext1,\n { simp only [assoc, preadditive.comp_add, preadditive.add_comp,\n biprod.inl_fst_assoc, biprod.inl_snd_assoc, zero_comp, add_zero, comp_id,\n inl_fst_assoc, inl_snd_assoc], },\n { simp only [assoc, preadditive.comp_add, preadditive.add_comp,\n biprod.inr_fst_assoc, biprod.inr_snd_assoc, zero_comp, zero_add, comp_id,\n inr_fst_assoc, inr_snd_assoc], },\n end, }\n\n@[simp]\nlemma inl_comp_fst :\n (inl φ).comp (fst φ : cochain (mapping_cone φ) F 1) (neg_add_self 1).symm =\n cochain.of_hom (𝟙 _) :=\nbegin\n ext n,\n simp only [cochain.comp_v _ _ (neg_add_self 1).symm n (n-1) n (by linarith) (by linarith),\n inl_fst, cochain.of_hom_v, homological_complex.id_f],\nend\n\n@[simp]\nlemma inl_comp_snd :\n (inl φ).comp (snd φ) (add_zero _).symm = 0 :=\nbegin\n ext n,\n simp only [cochain.comp_zero_cochain, inl_snd, cochain.zero_v],\nend\n\n@[simp]\nlemma inr_comp_fst :\n (cochain.of_hom (inr φ)).comp (fst φ : cochain (mapping_cone φ) F 1) (zero_add 1).symm = 0 :=\nby tidy\n\n@[simp]\nlemma inr_comp_snd :\n (cochain.of_hom (inr φ)).comp\n (snd φ : cochain (mapping_cone φ) G 0) (zero_add 0).symm = cochain.of_hom (𝟙 _) :=\nby tidy\n\n@[simps]\ndef δ_as_cocycle : cocycle (mapping_cone φ) F 1 :=\n-fst φ\n\ndef δ : mapping_cone φ ⟶ F⟦(1 : ℤ)⟧ :=\ncocycle.hom_of (cocycle.right_shift (δ_as_cocycle φ) 1 0 (zero_add 1).symm)\n\n@[simp, priority 1100]\nlemma inr_δ : inr φ ≫ δ φ = 0 :=\nbegin\n ext n,\n dsimp only [δ],\n simp only [homological_complex.comp_f, cocycle.hom_of_f, cochain.neg_v,\n cocycle.right_shift_coe, δ_as_cocycle_coe, homological_complex.zero_f_apply,\n hom_complex.cochain.right_shift_v _ 1 0 (zero_add 1).symm n n (by linarith) _ rfl,\n preadditive.neg_comp, preadditive.comp_neg, inr_fst_assoc, zero_comp, neg_zero],\nend\n\n@[simp]\nlemma inl_δ :\n (inl φ).comp (cochain.of_hom (δ φ)) (add_zero _).symm =\n -(cochain.of_hom (𝟙 F)).right_shift _ _ (add_neg_self 1).symm :=\nbegin\n /- TODO deduplicate the proof of this and the lemma above -/\n ext p q hpq,\n simp only [cochain.comp_zero_cochain, cochain.of_hom_v, δ,\n cocycle.hom_of_f, cocycle.right_shift_coe, δ_as_cocycle_coe,\n hom_complex.cochain.right_shift_v _ 1 0 (zero_add 1).symm q q (by linarith) p (by linarith),\n hom_complex.cochain.right_shift_v _ 1 (-1) (add_neg_self 1).symm p q hpq p (by linarith),\n cochain.neg_v, preadditive.comp_neg, preadditive.neg_comp, cochain.neg_v,\n inl_fst_assoc, homological_complex.id_f, id_comp],\nend\n\nvariable {φ}\n\nlemma to_ext_iff {A : C} {n : ℤ} (f g : A ⟶ (mapping_cone φ).X n) (n' : ℤ) (hn' : n' = n+1) :\n f = g ↔ f ≫ (fst φ : cochain (mapping_cone φ) F 1).v n n' hn' =\n g ≫ (fst φ : cochain (mapping_cone φ) F 1).v n n' hn' ∧\n f ≫ (snd φ).v n n (add_zero n).symm = g ≫ (snd φ).v n n (add_zero n).symm :=\nbegin\n split,\n { rintro rfl,\n tauto, },\n { intro hfg,\n rw [← cancel_mono (𝟙 ((mapping_cone φ).X n))],\n simp only [← id _ _ _ hn', preadditive.comp_add, reassoc_of hfg.1, reassoc_of hfg.2], },\nend\n\nlemma from_ext_iff {A : C} {n : ℤ} (f g : (mapping_cone φ).X n ⟶ A)\n (n' : ℤ) (h : n' = n+1) :\n f = g ↔ (inl φ).v n' n (by rw [h, int.add_neg_one, add_tsub_cancel_right]) ≫ f =\n (inl φ).v n' n (by rw [h, int.add_neg_one, add_tsub_cancel_right]) ≫ g ∧\n (inr φ).f n ≫ f = (inr φ).f n ≫ g :=\nbegin\n haveI : has_binary_biproduct (F.X n') (G.X n) := by { subst h, apply_instance, },\n split,\n { rintro rfl,\n tauto, },\n { intro hfg,\n rw [← cancel_epi (𝟙 ((mapping_cone φ).X n))],\n simp only [← id _ _ _ h, preadditive.add_comp, assoc, hfg.1, hfg.2], },\nend\n\nvariable (φ)\n\n@[reassoc]\nlemma d_fst (n₁ n₂ n₃ : ℤ) (h₁₂ : n₂ = n₁ + 1) (h₂₃ : n₃ = n₂ + 1) :\n (mapping_cone φ).d n₁ n₂ ≫ (fst φ : cochain (mapping_cone φ) F 1).v n₂ n₃ h₂₃ =\n -(fst φ : cochain (mapping_cone φ) F 1).v n₁ n₂ h₁₂ ≫ F.d n₂ n₃ :=\nby simp only [from_ext_iff _ _ _ h₁₂, inl_d_assoc _ n₁ n₂ n₃ (by linarith) (by linarith),\n assoc, preadditive.sub_comp, inr_fst, comp_zero, inl_fst, comp_id, zero_sub,\n preadditive.comp_neg, inl_fst_assoc, inr_d_assoc, inr_fst_assoc, zero_comp, neg_zero,\n eq_self_iff_true, and_self]\n\n@[reassoc]\nlemma d_snd (n₁ n₂ : ℤ) (h₁₂ : n₂ = n₁ + 1) :\n (mapping_cone φ).d n₁ n₂ ≫ (snd φ).v n₂ n₂ (add_zero n₂).symm =\n (fst φ : cochain (mapping_cone φ) F 1).v n₁ n₂ h₁₂ ≫ φ.f n₂ +\n (snd φ).v n₁ n₁ (add_zero n₁).symm ≫ G.d n₁ n₂ :=\nby simp only [from_ext_iff _ _ _ h₁₂, assoc,\n inl_d_assoc _ n₁ n₂ (n₂+1) (by linarith) (by linarith),\n preadditive.sub_comp, inl_snd, comp_zero, sub_zero, preadditive.comp_add,\n inl_snd_assoc, zero_comp, add_zero, inl_fst_assoc, inr_snd, comp_id,\n inr_d_assoc, inr_fst_assoc, zero_add, inr_snd_assoc,\n eq_self_iff_true, and_self]\n\n@[simp]\nlemma δ_inl :\n hom_complex.δ (-1) 0 (inl φ) = cochain.of_hom (φ ≫ inr φ) :=\nbegin\n ext p,\n simp only [δ_v (-1) 0 (neg_add_self 1) _ p p (add_zero p).symm _ _ rfl rfl,\n inl_d φ (p-1) p (p+1) (by linarith)( by linarith),\n add_left_neg, ε_0, one_zsmul, sub_add_cancel, cochain.of_hom_comp,\n cochain.comp_zero_cochain, cochain.of_hom_v],\nend\n\n@[simp]\nlemma δ_snd :\n hom_complex.δ 0 1 (snd φ) = -(fst φ : cochain (mapping_cone φ) F 1).comp\n (cochain.of_hom φ) (add_zero 1).symm :=\nbegin\n ext p q hpq,\n simp only [δ_v 0 1 (zero_add 1) _ p q hpq p q (by linarith) hpq, d_snd _ _ _ hpq,\n zero_add, add_zero, neg_neg, neg_zero, neg_eq_zero, add_tsub_cancel_right, ε_1,\n smul_add, neg_smul, one_zsmul, add_neg_cancel_comm_assoc, cochain.neg_v,\n cochain.comp_zero_cochain, cochain.of_hom_v],\n abel,\nend\n\nomit φ\nlemma _root_.int.two_eq_one_add_one : (2 : ℤ) = 1+1 := by linarith\nlemma _root_.int.one_eq_two_add_neg_one : (1 : ℤ) = 2+(-1) := by linarith\n\nlemma of_d_eq : cochain.of_d (mapping_cone φ) =\n -((fst φ : cochain (mapping_cone φ) F 1).comp (cochain.of_d F)\n int.two_eq_one_add_one).comp (inl φ) int.one_eq_two_add_neg_one +\n ((fst φ : cochain (mapping_cone φ) F 1).comp (cochain.of_hom φ) (add_zero 1).symm).comp\n (cochain.of_hom (inr φ)) (add_zero 1).symm +\n ((snd φ).comp (cochain.of_d G) (zero_add 1).symm).comp\n (cochain.of_hom (inr φ)) (add_zero 1).symm :=\nbegin\n ext p q hpq,\n simp only [from_ext_iff _ _ _ hpq,\n cochain.of_d_v, inl_d φ p q (q+1) (by linarith) (by linarith), cochain.add_v,\n preadditive.comp_add, cochain.comp_assoc_of_third_is_zero_cochain, cochain.comp_zero_cochain,\n cochain.of_hom_v, inl_fst_assoc, cochain.neg_v, inl_snd_assoc, zero_comp,\n cochain.comp_assoc_of_first_is_zero_cochain, cochain.zero_cochain_comp, preadditive.comp_neg,\n cochain.comp_v _ _ int.one_eq_two_add_neg_one p (q+1) q (by linarith) (by linarith),\n cochain.comp_v _ _ _root_.int.two_eq_one_add_one p q (q+1) hpq rfl, assoc, add_zero,\n inl_fst_assoc, inr_d, inr_fst_assoc, neg_zero, zero_add, inr_snd_assoc, sub_eq_neg_add,\n eq_self_iff_true, and_true],\nend\n\nvariable {φ}\n\nlemma to_decomposition {A : C} {n : ℤ} (f : A ⟶ (mapping_cone φ).X n)\n (n' : ℤ) (h : n' = n+1) :\n ∃ (x : A ⟶ F.X n') (y : A ⟶ G.X n), f = x ≫\n (inl φ : cochain F (mapping_cone φ) (-1)).v n' n (by rw [h, int.add_neg_one, add_tsub_cancel_right])\n + y ≫ (inr φ).f n :=\nbegin\n refine ⟨f ≫ (fst φ : cochain (mapping_cone φ) F 1).v _ _ (by linarith), f ≫ (snd φ).v n n (by linarith), _⟩,\n have h := f ≫= id φ n n' h,\n rw comp_id at h,\n nth_rewrite 0 ← h,\n simp only [preadditive.comp_add, assoc],\nend\n\nlemma cochain_ext {K : cochain_complex C ℤ} {m m' : ℤ}\n (y₁ y₂ : cochain (mapping_cone φ) K m) (hm' : m = m'+1) :\n y₁ = y₂ ↔ (inl φ).comp y₁ (show m' = -1+m, by rw [hm', neg_add_cancel_comm_assoc]) =\n (inl φ).comp y₂ (show m' = -1+m, by rw [hm', neg_add_cancel_comm_assoc]) ∧\n (cochain.of_hom (inr φ)).comp y₁ (zero_add m).symm =\n (cochain.of_hom (inr φ)).comp y₂ (zero_add m).symm :=\nbegin\n split,\n { rintro rfl,\n tauto, },\n { rintro ⟨h₁, h₂⟩,\n ext p q hpq,\n replace h₁ := cochain.congr_v h₁ (p+1) q (by linarith),\n replace h₂ := cochain.congr_v h₂ p q (by linarith),\n simp only [cochain.comp_v _ _ (show m' = -1+m, by linarith) (p+1) p q (by linarith) hpq] at h₁,\n simp only [cochain.zero_cochain_comp, cochain.of_hom_v] at h₂,\n rw [from_ext_iff _ _ (p+1) rfl, h₁, h₂],\n tauto, },\nend\n\nlemma cochain_ext' {K : cochain_complex C ℤ} {m m' : ℤ}\n (y₁ y₂ : cochain K (mapping_cone φ) m) (hm' : m' = m+1) :\n y₁ = y₂ ↔ y₁.comp (fst φ : cochain (mapping_cone φ) F 1) hm' =\n y₂.comp (fst φ : cochain (mapping_cone φ) F 1) hm' ∧\n y₁.comp (snd φ) (add_zero m).symm =\n y₂.comp (snd φ) (add_zero m).symm :=\nbegin\n split,\n { rintro rfl,\n tauto, },\n { rintro ⟨h₁, h₂⟩,\n ext p q hpq,\n replace h₁ := cochain.congr_v h₁ p (q+1) (by linarith),\n simp only [cochain.comp_v _ _ hm' p q (q+1) (by linarith) (by linarith)] at h₁,\n replace h₂ := cochain.congr_v h₂ p q (by linarith),\n simp only [cochain.comp_zero_cochain] at h₂,\n rw [to_ext_iff _ _ (q+1) rfl, h₂, h₁],\n tauto, },\nend\n\nvariable (φ)\n\n@[simp]\ndef ι' := (homotopy_category.quotient _ _).map (inr φ)\n\ndef δ' : (homotopy_category.quotient _ _).obj (mapping_cone φ) ⟶\n ((homotopy_category.quotient _ _).obj F)⟦(1 : ℤ)⟧ :=\n(homotopy_category.quotient _ _).map (δ φ)\n\ndef desc_cochain {K : cochain_complex C ℤ} {n m : ℤ} (α : cochain F K m) (β : cochain G K n)\n (h : m+1=n) :\n cochain (mapping_cone φ) K n :=\n(fst φ : cochain (mapping_cone φ) F 1).comp α (show n = 1+m, by rw [← h, add_comm])\n + (snd φ).comp β (zero_add n).symm\n\n@[simp, reassoc]\nlemma inl_desc_cochain_v {K : cochain_complex C ℤ} {n m : ℤ}\n (α : cochain F K m) (β : cochain G K n) (h : m+1=n) (p₁ p₂ p₃ : ℤ)\n (h₁₂ : p₂ = p₁ + (-1)) (h₂₃ : p₃ = p₂ + n) :\n (inl φ).v p₁ p₂ h₁₂ ≫ (desc_cochain φ α β h).v p₂ p₃ h₂₃ =\n α.v p₁ p₃ (by rw [h₂₃, h₁₂, ← h, int.add_neg_one, sub_add_add_cancel]) :=\nbegin\n dsimp [desc_cochain],\n simp only [add_zero, cochain.zero_cochain_comp, preadditive.comp_add, zero_comp,\n cochain.comp_v _ _ (show n = 1 + m, by linarith) p₂ p₁ p₃ (by linarith) (by linarith),\n inl_fst_assoc, inl_snd_assoc],\nend\n\n@[simp, reassoc]\nlemma inr_desc_cochain_v {K : cochain_complex C ℤ} {n m : ℤ}\n (α : cochain F K m) (β : cochain G K n) (h : m+1=n) (p₁ p₂ : ℤ)\n (h₁₂ : p₂ = p₁ + n) :\n (inr φ).f p₁ ≫ (desc_cochain φ α β h).v p₁ p₂ h₁₂ =\n β.v p₁ p₂ h₁₂ :=\nbegin\n dsimp [desc_cochain],\n simp only [cochain.zero_cochain_comp, preadditive.comp_add, inr_snd_assoc, add_left_eq_self,\n cochain.comp_v _ _ (show n = 1 + m, by linarith) p₁ (p₁ + 1) p₂ rfl (by linarith),\n inr_fst_assoc, zero_comp],\nend\n\n@[simp]\nlemma inl_desc_cochain {K : cochain_complex C ℤ} {n m : ℤ}\n (α : cochain F K m) (β : cochain G K n) (h : m+1=n) :\n (inl φ).comp (desc_cochain φ α β h)\n (show m = -1+n, by rw [← h, neg_add_cancel_comm_assoc]) = α :=\nbegin\n ext p q hpq,\n simp only [cochain.comp_v _ _ (show m = -1 + n, by linarith)\n p (p-1) q (by linarith) (by linarith), inl_desc_cochain_v],\nend\n\n@[simp]\nlemma inr_desc_cochain {K : cochain_complex C ℤ} {n m : ℤ}\n (α : cochain F K m) (β : cochain G K n) (h : m+1=n) :\n (cochain.of_hom (inr φ)).comp\n (desc_cochain φ α β h) (zero_add n).symm = β :=\nbegin\n ext p q hpq,\n simp only [cochain.comp_v _ _ (zero_add n).symm p p q (add_zero p).symm hpq,\n cochain.of_hom_v, inr_desc_cochain_v],\nend\n\nlemma δ_desc_cochain {K : cochain_complex C ℤ} {n m n' : ℤ} (α : cochain F K m) (β : cochain G K n)\n (h : m+1=n) (hn' : n+1 = n') : hom_complex.δ n n' (desc_cochain φ α β h) =\n (fst φ : cochain (mapping_cone φ) F 1).comp (hom_complex.δ m n α +\n ε (n+1) • (cochain.of_hom φ).comp β (zero_add n).symm) (by rw [← hn', add_comm]) +\n (snd φ).comp (hom_complex.δ n n' β) (zero_add n').symm :=\nbegin\n ext p q hpq,\n simp only [from_ext_iff _ _ (p+1) rfl,\n δ_v n n' hn' _ p q hpq (q-1) (p+1) rfl rfl, cochain.add_v,\n cochain.comp_v _ _ (show n' = 1+n, by linarith) p (p+1) q rfl (by linarith),\n zero_add, neg_zero, add_zero, ε_succ, neg_smul, preadditive.comp_add,\n inl_desc_cochain_v_assoc, preadditive.comp_neg, linear.comp_smul, cochain.neg_v,\n cochain.zsmul_v, cochain.zero_cochain_comp, cochain.of_hom_v, inl_fst_assoc,\n inl_snd_assoc, zero_comp, inr_desc_cochain_v_assoc, inr_d_assoc, inr_desc_cochain_v,\n inr_fst_assoc, smul_zero, inr_snd_assoc, smul_sub, show m = n-1, by linarith,\n inl_d_assoc φ p (p+1) (p+2) (by linarith) (by linarith),\n δ_v m n h _ (p+1) q (by linarith) (q-1) (p+2) rfl (by linarith),\n preadditive.sub_comp, assoc, inl_desc_cochain_v, ε_sub, ε_1, mul_neg, mul_one, neg_neg],\n exact ⟨by abel, rfl⟩,\nend\n\ndef desc_cocycle {K : cochain_complex C ℤ} {n m : ℤ} (α : cochain F K m) (β : cocycle G K n)\n (h : m+1=n) (eq : hom_complex.δ m n α =\n ε n • (cochain.of_hom φ).comp (β : cochain G K n) (zero_add n).symm) :\n cocycle (mapping_cone φ) K n :=\ncocycle.mk (desc_cochain φ α (β : cochain G K n) h) (n+1) rfl\n (by simp only [δ_desc_cochain φ α (β : cochain G K n) h rfl, ε_add, ε_1, mul_neg, mul_one, eq,\n neg_smul, ← sub_eq_add_neg, sub_self, cochain.comp_zero, zero_add,\n cocycle.δ_eq_zero, cochain.comp_zero])\n\n@[simp]\nlemma desc_cocycle_coe {K : cochain_complex C ℤ} {n m : ℤ} (α : cochain F K m) (β : cocycle G K n)\n (h : m+1=n) (eq : hom_complex.δ m n α = ε n • (cochain.of_hom φ).comp β.1 (zero_add n).symm) :\n(desc_cocycle φ α β h eq : cochain (mapping_cone φ) K n) =\n desc_cochain φ α β h := rfl\n\ndef desc {K : cochain_complex C ℤ} (α : cochain F K (-1)) (β : G ⟶ K)\n (eq : hom_complex.δ (-1) 0 α = cochain.of_hom (φ ≫ β)) :\n mapping_cone φ ⟶ K :=\ncocycle.hom_of (desc_cocycle φ α (cocycle.of_hom β) (neg_add_self 1)\n (by simp only [eq, ε_0, cochain.of_hom_comp, subtype.val_eq_coe, cocycle.of_hom_coe, one_zsmul]))\n\n@[simp, reassoc]\nlemma inl_desc_v {K : cochain_complex C ℤ} (α : cochain F K (-1)) (β : G ⟶ K)\n (eq : hom_complex.δ (-1) 0 α = cochain.of_hom (φ ≫ β)) (p q : ℤ) (hpq : q = p + (-1)) :\n (inl φ).v p q hpq ≫ (desc φ α β eq).f q = α.v p q hpq :=\nbegin\n dsimp only [desc],\n simp only [cocycle.hom_of_f, desc_cocycle_coe, inl_desc_cochain_v],\nend\n\n@[simp]\nlemma inl_desc {K : cochain_complex C ℤ} (α : cochain F K (-1)) (β : G ⟶ K)\n (eq : hom_complex.δ (-1) 0 α = cochain.of_hom (φ ≫ β)) :\n (inl φ).comp (cochain.of_hom (desc φ α β eq)) (add_zero _).symm = α :=\nby tidy\n\n@[simp, reassoc]\nlemma inr_desc_f {K : cochain_complex C ℤ} (α : cochain F K (-1)) (β : G ⟶ K)\n (eq : hom_complex.δ (-1) 0 α = cochain.of_hom (φ ≫ β)) (n : ℤ):\n (inr φ).f n ≫ (desc φ α β eq).f n = β.f n :=\nbegin\n dsimp only [desc],\n simp only [cocycle.hom_of_f, desc_cocycle_coe, cocycle.of_hom_coe,\n inr_desc_cochain_v, cochain.of_hom_v],\nend\n\n@[simp, reassoc]\nlemma inr_desc {K : cochain_complex C ℤ} (α : cochain F K (-1)) (β : G ⟶ K)\n (eq : hom_complex.δ (-1) 0 α = cochain.of_hom (φ ≫ β)) :\n inr φ ≫ desc φ α β eq = β :=\nbegin\n dsimp only [desc],\n ext n,\n simp only [homological_complex.comp_f, cocycle.hom_of_f, desc_cocycle_coe,\n cocycle.of_hom_coe, inr_desc_cochain_v, cochain.of_hom_v],\nend\n\nlemma desc_f {K : cochain_complex C ℤ} (α : cochain F K (-1)) (β : G ⟶ K)\n (eq : hom_complex.δ (-1) 0 α = cochain.of_hom (φ ≫ β)) (n n' : ℤ) (hn' : n' = n+1) :\n (desc φ α β eq).f n =\n (fst φ : cochain (mapping_cone φ) F 1).v n n' hn' ≫\n α.v n' n (by { rw [hn', int.add_neg_one, add_tsub_cancel_right]}) +\n (snd φ).v n n (add_zero n).symm ≫ β.f n :=\nby simp only [from_ext_iff _ _ _ hn', add_zero, inl_desc_v, preadditive.comp_add,\n inl_fst_assoc, inl_snd_assoc, zero_comp, eq_self_iff_true, inr_desc_f,\n inr_fst_assoc, inr_snd_assoc, zero_add, and_self]\n\ndef desc_homotopy {K : cochain_complex C ℤ} (f₁ f₂ : mapping_cone φ ⟶ K)\n (γ₁ : cochain F K (-2)) (γ₂ : cochain G K (-1))\n (h₁ : (inl φ).comp (cochain.of_hom f₁) (add_zero (-1)).symm =\n hom_complex.δ (-2) (-1) γ₁ + (cochain.of_hom φ).comp γ₂ (zero_add _).symm +\n (inl φ).comp (cochain.of_hom f₂) (add_zero (-1)).symm)\n (h₂ : cochain.of_hom (inr φ ≫ f₁) =\n hom_complex.δ (-1) 0 γ₂ + cochain.of_hom (inr φ ≫ f₂)) :\n homotopy f₁ f₂ :=\n(equiv_homotopy _ _).symm\nbegin\n refine ⟨desc_cochain _ γ₁ γ₂ (by linarith), _⟩,\n rw [δ_desc_cochain φ γ₁ γ₂ (by linarith) (neg_add_self 1),\n cochain_ext _ _ (show (0 : ℤ) = -1 +1 , by linarith)],\n split,\n { rw [cochain.comp_add, h₁],\n nth_rewrite 0 cochain.comp_add,\n simp only [← cochain.comp_assoc _ _ _ (neg_add_self 1).symm (add_neg_self 1).symm\n (show (-1 : ℤ) = (-1) +1 + (-1), by linarith), inl_comp_fst, cochain.id_comp,\n neg_add_self, ε_0, one_smul, ← cochain.comp_assoc_of_second_is_zero_cochain,\n inl_comp_snd, cochain.zero_comp, add_zero], },\n { rw [cochain.comp_add, ← cochain.of_hom_comp, ← cochain.of_hom_comp, h₂],\n nth_rewrite 0 cochain.comp_add,\n simp only [← hom_complex.cochain.comp_assoc_of_first_is_zero_cochain,\n inr_comp_fst, cochain.zero_comp, zero_add, inr_comp_snd,\n cochain.id_comp], },\nend\n\ndef lift_cochain {K : cochain_complex C ℤ}\n {n m : ℤ} (α : cochain K F m) (β : cochain K G n) (h : n+1=m) :\n cochain K (mapping_cone φ) n :=\nα.comp (inl φ) (by linarith) + β.comp (cochain.of_hom (inr φ)) (by linarith)\n\n@[simp, reassoc]\nlemma lift_cochain_fst_v {K : cochain_complex C ℤ}\n {n m : ℤ} (α : cochain K F m) (β : cochain K G n) (h : n+1=m) (p₁ p₂ p₃ : ℤ)\n (h₁₂ : p₂ = p₁ + n) (h₂₃ : p₃ = p₂ + 1) :\n (lift_cochain φ α β h).v p₁ p₂ h₁₂ ≫ (fst φ : cochain (mapping_cone φ) F 1).v p₂ p₃ h₂₃ =\n α.v p₁ p₃ (by rw [h₂₃, h₁₂, ← h, add_assoc]) :=\nbegin\n dsimp only [lift_cochain],\n simp only [cochain.add_v, add_zero, cochain.comp_zero_cochain, cochain.of_hom_v,\n subtype.val_eq_coe, preadditive.add_comp, assoc, inr_fst, comp_zero,\n cochain.comp_v _ _ (show n = m+(-1), by linarith) p₁ p₃ p₂ (by linarith) (by linarith),\n inl_fst, comp_id],\nend\n\n@[simp, reassoc]\nlemma lift_cochain_snd_v {K : cochain_complex C ℤ}\n {n m : ℤ} (α : cochain K F m) (β : cochain K G n) (h : n+1=m)\n (p₁ p₂ : ℤ) (h₁₂ : p₂ = p₁ + n) :\n (lift_cochain φ α β h).v p₁ p₂ h₁₂ ≫ (snd φ).v p₂ p₂ (add_zero p₂).symm =\n β.v p₁ p₂ h₁₂ :=\nbegin\n dsimp [lift_cochain],\n simp only [cochain.comp_zero_cochain, cochain.of_hom_v, preadditive.add_comp, assoc,\n cochain.comp_v _ _ (show n = m+(-1), by linarith) p₁ (p₁+m) p₂ rfl (by linarith),\n inr_snd, comp_id, add_left_eq_self, inl_snd, comp_zero],\nend\n\n@[simp]\nlemma lift_cochain_fst {K : cochain_complex C ℤ}\n {n m : ℤ} (α : cochain K F m) (β : cochain K G n) (h : n+1=m) :\n (lift_cochain φ α β h).comp (fst φ : cochain (mapping_cone φ) F 1) h.symm = α :=\nbegin\n ext p q hpq,\n simp only [cochain.comp_v _ _ h.symm p (p+n) q rfl (by linarith), lift_cochain_fst_v],\nend\n\n@[simp]\nlemma lift_cochain_snd {K : cochain_complex C ℤ}\n {n m : ℤ} (α : cochain K F m) (β : cochain K G n) (h : n+1=m) :\n (lift_cochain φ α β h).comp (snd φ) (add_zero n).symm = β :=\nbegin\n ext p q hpq,\n simp only [cochain.comp_zero_cochain, lift_cochain_snd_v],\nend\n\nlemma δ_lift_cochain {K : cochain_complex C ℤ}\n {n m : ℤ} (α : cochain K F m) (β : cochain K G n) (h : n+1=m) (m' : ℤ) (hm' : m = m'+(-1)) :\n hom_complex.δ n m (lift_cochain φ α β h) =\n -(hom_complex.δ m m' α).comp (inl φ) hm' +\n (hom_complex.δ n m β + α.comp (cochain.of_hom φ) (add_zero m).symm).comp\n (cochain.of_hom (inr φ)) (add_zero m).symm :=\nbegin\n ext p q hpq,\n simp only [to_ext_iff _ _ (q+1) rfl, δ_v n m h _ p q hpq _ _ rfl rfl, cochain.add_v,\n cochain.comp_v _ _ hm' p (q+1) q (by linarith) (by linarith),\n δ_v m m' (by linarith) _ p (q+1) (by linarith) q (p+1) (by linarith) rfl,\n cochain.neg_v, cochain.comp_zero_cochain, cochain.of_hom_v,\n preadditive.add_comp, assoc, preadditive.zsmul_comp, lift_cochain_fst_v, inl_fst, inr_fst,\n preadditive.neg_comp, preadditive.comp_neg, comp_zero, smul_zero, add_zero,\n d_fst φ (q-1) q (q+1) (by linarith) rfl, lift_cochain_fst_v_assoc, comp_id, neg_add, h,\n ε_succ, neg_smul, neg_neg, inl_snd, neg_zero, zero_add, d_snd φ (q-1) q (by linarith),\n preadditive.comp_add, lift_cochain_snd_v_assoc, inr_snd, lift_cochain_snd_v],\n refine ⟨rfl, _⟩,\n have : ∀ (x y z : K.X p ⟶ G.X q), x +y +z = y+z +x := λ x y z, by abel,\n apply this,\nend\n\ndef lift_cocycle {K : cochain_complex C ℤ}\n {n m : ℤ} (α : cocycle K F m) (β : cochain K G n) (h : n+1=m)\n (hαβ : hom_complex.δ n m β + (α : cochain K F m).comp (cochain.of_hom φ) (add_zero m).symm = 0) :\n cocycle K (mapping_cone φ) n :=\ncocycle.mk (lift_cochain φ (α : cochain K F m) β h) _ h\n (by simp only [δ_lift_cochain φ _ _ h (m+1) (by linarith), hαβ, cochain.zero_comp, add_zero,\n cocycle.δ_eq_zero, neg_zero])\n\n@[simp]\ndef lift_cocycle_coe {K : cochain_complex C ℤ}\n {n m : ℤ} (α : cocycle K F m) (β : cochain K G n) (h : n+1=m)\n (hαβ : hom_complex.δ n m β + (α : cochain K F m).comp (cochain.of_hom φ) (add_zero m).symm = 0) :\n (lift_cocycle φ α β h hαβ : cochain K (mapping_cone φ) n) =\n lift_cochain φ (α : cochain K F m) β h := rfl\n\ndef lift {K : cochain_complex C ℤ} (α : cocycle K F 1) (β : cochain K G 0)\n (hαβ : hom_complex.δ 0 1 β + (α : cochain K F 1).comp (cochain.of_hom φ) (add_zero 1).symm = 0) :\n K ⟶ mapping_cone φ :=\ncocycle.hom_of (lift_cocycle φ α β (zero_add 1) hαβ)\n\n@[simp, reassoc]\nlemma lift_fst_f {K : cochain_complex C ℤ} (α : cocycle K F 1) (β : cochain K G 0)\n (hαβ : hom_complex.δ 0 1 β + (α : cochain K F 1).comp (cochain.of_hom φ) (add_zero 1).symm = 0)\n (n n' : ℤ) (hnn' : n' = n+1) :\n (lift φ α β hαβ).f n ≫\n (fst φ : cochain (mapping_cone φ) F 1).v n n' hnn' = (α : cochain K F 1).v n n' hnn' :=\nbegin\n dsimp only [lift],\n simp only [cocycle.hom_of_f, lift_cocycle_coe, lift_cochain_fst_v],\nend\n\n@[simp]\nlemma lift_fst {K : cochain_complex C ℤ} (α : cocycle K F 1) (β : cochain K G 0)\n (hαβ : hom_complex.δ 0 1 β + (α : cochain K F 1).comp (cochain.of_hom φ) (add_zero 1).symm = 0) :\n (cochain.of_hom (lift φ α β hαβ)).comp\n (fst φ : cochain (mapping_cone φ) F 1) (zero_add 1).symm =\n (α : cochain K F 1) :=\nbegin\n ext p q hpq,\n simp only [cochain.zero_cochain_comp, cochain.of_hom_v, lift_fst_f],\nend\n\n@[simp, reassoc]\nlemma lift_snd_f {K : cochain_complex C ℤ} (α : cocycle K F 1) (β : cochain K G 0)\n (hαβ : hom_complex.δ 0 1 β + (α : cochain K F 1).comp (cochain.of_hom φ) (add_zero 1).symm = 0) (n : ℤ) :\n (lift φ α β hαβ).f n ≫ (snd φ).v n n (add_zero n).symm =\n β.v n n (add_zero n).symm :=\nbegin\n dsimp only [lift],\n simp only [cocycle.hom_of_f, lift_cocycle_coe, lift_cochain_snd_v],\nend\n\n@[simp]\nlemma lift_snd {K : cochain_complex C ℤ} (α : cocycle K F 1) (β : cochain K G 0)\n (hαβ : hom_complex.δ 0 1 β + (α : cochain K F 1).comp (cochain.of_hom φ) (add_zero 1).symm = 0) :\n (cochain.of_hom (lift φ α β hαβ)).comp\n (snd φ) (add_zero 0).symm = β :=\nbegin\n dsimp only [lift],\n simp only [cocycle.cochain_of_hom_hom_of_eq_coe, lift_cocycle_coe, lift_cochain_snd],\nend\n\nlemma lift_desc_f {K L : cochain_complex C ℤ} (α : cocycle K F 1) (β : cochain K G 0)\n (hαβ : hom_complex.δ 0 1 β + (α : cochain K F 1).comp (cochain.of_hom φ) (add_zero 1).symm = 0)\n (α' : cochain F L (-1)) (β' : G ⟶ L) (eq : hom_complex.δ (-1) 0 α' = cochain.of_hom (φ ≫ β'))\n (n n' : ℤ) (hnn' : n' = n+1) :\n (lift φ α β hαβ).f n ≫ (desc φ α' β' eq).f n =\n (α : cochain K F 1).v n n' hnn' ≫ α'.v n' n (by { rw [hnn', int.add_neg_one, add_tsub_cancel_right], }) +\n β.v n n (add_zero n).symm ≫ β'.f n :=\nbegin\n rw [← id_comp ((desc φ α' β' eq).f n), ← id φ _ _ hnn'],\n simp only [preadditive.add_comp, assoc, inl_desc_v, inr_desc_f, preadditive.comp_add,\n lift_fst_f_assoc, lift_snd_f_assoc],\nend\n\nlemma lift_f {K : cochain_complex C ℤ} (α : cocycle K F 1) (β : cochain K G 0)\n (hαβ : hom_complex.δ 0 1 β + (α : cochain K F 1).comp (cochain.of_hom φ) (add_zero 1).symm = 0) (n n' : ℤ)\n (hn' : n' = n+1) :\n (lift φ α β hαβ).f n = (α : cochain K F 1).v n n' hn' ≫\n (inl φ).v n' n (by rw [hn', int.add_neg_one, add_tsub_cancel_right]) +\n β.v n n (add_zero n).symm ≫ (inr φ).f n :=\nby simp only [to_ext_iff _ _ _ hn', add_zero, lift_fst_f, preadditive.add_comp, assoc,\n inl_fst, comp_id, inr_fst, comp_zero, eq_self_iff_true, lift_snd_f, inl_snd,\n inr_snd, zero_add, and_self]\n\ndef lift_homotopy {K : cochain_complex C ℤ} (f₁ f₂ : K ⟶ mapping_cone φ)\n (γ₁ : cochain K F 0) (γ₂ : cochain K G (-1))\n (h₁ : (cochain.of_hom f₁).comp (fst φ :\n cochain (mapping_cone φ) F 1) (zero_add 1).symm = -hom_complex.δ 0 1 γ₁ +\n (cochain.of_hom f₂).comp (fst φ : cochain (mapping_cone φ) F 1) (zero_add 1).symm)\n (h₂ : (cochain.of_hom f₁).comp (snd φ) (add_zero 0).symm =\n hom_complex.δ (-1) 0 γ₂ + γ₁.comp (cochain.of_hom φ) (zero_add 0).symm +\n (cochain.of_hom f₂).comp (snd φ) (add_zero 0).symm) :\n homotopy f₁ f₂ :=\n(equiv_homotopy _ _).symm\nbegin\n refine ⟨lift_cochain φ γ₁ γ₂ (neg_add_self 1), _⟩,\n simp only [δ_lift_cochain φ _ _ _ 1 (show (0 : ℤ) = 1 +(-1), by linarith),\n cochain_ext' _ _ (zero_add 1).symm],\n split,\n { simp only [add_zero, cochain.add_comp, cochain.neg_comp,\n cochain.comp_assoc_of_second_is_zero_cochain, inr_comp_fst,\n cochain.comp_zero,\n cochain.comp_assoc _ _ _ (add_neg_self 1).symm (neg_add_self 1).symm\n (show (1 : ℤ) = 1+(-1)+1, by linarith),\n inl_comp_fst, cochain.comp_id, h₁], },\n { simp only [zero_add, neg_zero, cochain.add_comp, cochain.comp_assoc_of_third_is_zero_cochain,\n cochain.neg_comp, inl_comp_snd, cochain.comp_zero, inr_comp_snd, cochain.comp_id, h₂], },\nend\n\nsection\n\nvariables {K₁ K₂ L₁ L₂ : cochain_complex C ℤ}\n [∀ p, has_binary_biproduct (K₁.X (p+1)) (L₁.X p)]\n [∀ p, has_binary_biproduct (K₂.X (p+1)) (L₂.X p)]\n (f₁ : K₁ ⟶ L₁) (f₂ : K₂ ⟶ L₂) (τ₁ : K₁ ⟶ K₂) (τ₂ : L₁ ⟶ L₂) (comm : f₁ ≫ τ₂ = τ₁ ≫ f₂)\n\ninclude comm\n\ndef map : mapping_cone f₁ ⟶ mapping_cone f₂ :=\ndesc f₁ ((cochain.of_hom τ₁).comp (inl f₂) (zero_add _).symm)\n (τ₂ ≫ inr f₂)\nbegin\n rw [δ_comp_of_first_is_zero_cochain _ _ _ (neg_add_self 1), δ_inl,\n cocycle.δ_cochain_of_hom, cochain.zero_comp, smul_zero, add_zero, cochain.of_hom_comp f₂,\n ← assoc f₁, ← cochain.of_hom_comp, ← cochain.of_hom_comp, ← assoc, comm],\nend\n\nlemma inr_comp_map :\n inr f₁ ≫ map _ _ _ _ comm =\n τ₂ ≫ inr f₂ :=\nbegin\n apply hom_complex.cochain.of_hom_injective,\n rw cochain_ext' _ _ (zero_add 1).symm,\n dsimp only [map],\n split,\n { simp only [inr_desc, cochain.of_hom_comp,\n cochain.comp_assoc_of_second_is_zero_cochain, inr_comp_fst,\n inr_fst], },\n { simp only [inr_desc, cochain.of_hom_comp, inr_snd,\n cochain.comp_assoc_of_third_is_zero_cochain, inr_comp_snd], },\nend\n\nlemma map_comp_δ :\n map _ _ _ _ comm ≫ δ f₂ =\n δ f₁ ≫ τ₁⟦1⟧' :=\nbegin\n apply hom_complex.cochain.of_hom_injective,\n rw cochain_ext _ _(neg_add_self 1).symm,\n dsimp only [map],\n split,\n { simp only [cochain.of_hom_comp, ← hom_complex.cochain.comp_assoc_of_second_is_zero_cochain,\n inl_desc, hom_complex.cochain.comp_assoc_of_first_is_zero_cochain,\n inl_δ, cochain.comp_neg, cochain.of_hom_comp],\n ext p q hpq,\n have hp : p = q+1 := by linarith,\n subst hp,\n simp only [cochain.neg_v, cochain.zero_cochain_comp, cochain.of_hom_v,\n cochain.neg_comp, cochain.comp_zero_cochain, shift_functor_map_f', neg_inj],\n erw cochain.right_shift_v (cochain.of_hom _) 1 (-1)\n (by linarith) (q+1) q (by linarith) (q+1) (by linarith),\n erw cochain.right_shift_v (cochain.of_hom _) 1 (-1)\n (by linarith) (q+1) q (by linarith) (q+1) (by linarith),\n simp only [shift_functor_obj_X_iso, cochain.of_hom_v, homological_complex.id_f,\n homological_complex.X_iso_of_eq_refl, id_comp],\n dsimp [iso.refl],\n rw [comp_id, id_comp], },\n { rw [cochain.of_hom_comp, ← hom_complex.cochain.comp_assoc_of_first_is_zero_cochain,\n ← cochain.of_hom_comp, inr_desc, ← cochain.of_hom_comp, assoc,\n inr_δ, comp_zero, cochain.of_hom_zero, ← cochain.of_hom_comp, ← assoc,\n inr_δ, zero_comp, cochain.of_hom_zero], },\nend\n\nend\n\nexample : ℕ := 42\n\nsection\n\nvariables {K L : cochain_complex C ℤ} (f : K ⟶ L) {D : Type*} [category D] [preadditive D]\n [∀ p, has_binary_biproduct (K.X (p+1)) (L.X p)] (Φ : C ⥤ D) [functor.additive Φ]\n [∀ p, has_binary_biproduct (((Φ.map_homological_complex (complex_shape.up ℤ)).obj K).X (p + 1))\n (((Φ.map_homological_complex (complex_shape.up ℤ)).obj L).X p)]\n\n@[simps]\ndef map_iso : (Φ.map_homological_complex _).obj (mapping_cone f) ≅\n mapping_cone ((Φ.map_homological_complex _).map f) :=\n{ hom := mapping_cone.lift _ (cocycle.map (mapping_cone.fst f) Φ)\n ((mapping_cone.snd f).map Φ) (by simp),\n inv := mapping_cone.desc _ ((mapping_cone.inl f).map Φ)\n ((Φ.map_homological_complex _).map (mapping_cone.inr f)) (by simp),\n hom_inv_id' := begin\n ext n,\n simpa only [homological_complex.comp_f, homological_complex.id_f,\n lift_desc_f _ _ _ _ _ _ _ n (n+1) rfl, cocycle.map_coe, cochain.map_v,\n functor.map_homological_complex_map_f, ← Φ.map_comp, ← Φ.map_add,\n mapping_cone.id, Φ.map_id],\n end,\n inv_hom_id' := hom_complex.cochain.of_hom_injective begin\n ext n,\n simp only [cochain.of_hom_comp, cochain.comp_zero_cochain, cochain.of_hom_v,\n homological_complex.id_f, from_ext_iff _ _ (n+1) rfl, to_ext_iff _ _ (n+1) rfl,\n assoc, lift_fst_f, cocycle.map_coe, cochain.map_v, inl_desc_v_assoc, id_comp,\n inl_fst, inr_desc_f_assoc, functor.map_homological_complex_map_f, inr_fst,\n lift_snd_f, inl_snd, inr_snd, ← Φ.map_comp, Φ.map_zero, Φ.map_id],\n tauto,\n end, }\n\nend\n\nend mapping_cone\n\nend preadditive\n\nsection abelian\n\nopen hom_complex\n\nvariables [abelian C] {S : short_complex (cochain_complex C ℤ)} (ex : S.short_exact)\n\ninclude ex\n\nlemma degreewise_exact (n : ℤ) :\n (S.map (homological_complex.eval C (complex_shape.up ℤ) n)).short_exact :=\nex.map_of_exact (homological_complex.eval C (complex_shape.up ℤ) n)\n\ndef from_mapping_cone_of_ses : mapping_cone S.f ⟶ S.X₃ :=\nmapping_cone.desc S.f 0 S.g (by simp)\n\n@[simp, reassoc]\nlemma inr_from_mapping_cone_of_ses (n : ℤ) :\n (mapping_cone.inr S.f).f n ≫ (from_mapping_cone_of_ses ex).f n = S.g.f n :=\nbegin\n dsimp only [from_mapping_cone_of_ses],\n simp only [mapping_cone.inr_desc_f],\nend\n\n@[simp, reassoc]\nlemma inl_from_mapping_cone_of_ses (p q : ℤ) (hpq : q = p + (-1)) :\n (mapping_cone.inl S.f).v p q hpq ≫ (from_mapping_cone_of_ses ex).f q = 0 :=\nbegin\n dsimp only [from_mapping_cone_of_ses],\n simp only [mapping_cone.inl_desc_v, cochain.zero_v],\nend\n\n@[simp, reassoc]\nlemma inr_mapping_cone_comp_from_mapping_cone_of_ses :\n mapping_cone.inr S.f ≫ from_mapping_cone_of_ses ex = S.g :=\nbegin\n ext n : 2,\n simp only [homological_complex.comp_f, inr_from_mapping_cone_of_ses],\nend\n\ninstance from_mapping_cone_of_ses_quasi_iso : quasi_iso (from_mapping_cone_of_ses ex) :=\n⟨λ n, begin\n rw is_iso_homology_map_iff_short_complex_quasi_iso'\n (from_mapping_cone_of_ses ex) (show (n-1)+1=n, by linarith) rfl,\n change is_iso _,\n haveI : ∀ (n : ℤ), mono (S.f.f n) :=\n λ n, (ex.map_of_exact (homological_complex.eval _ _ n)).mono_f,\n rw is_iso_iff_mono_and_epi,\n split,\n { rw short_complex.mono_homology_map_iff,\n dsimp,\n intros A x₂ hxy z hz,\n obtain ⟨x, y, rfl⟩ := mapping_cone.to_decomposition x₂ _ rfl,\n simp only [preadditive.add_comp, assoc, mapping_cone.inr_d, preadditive.comp_sub,\n mapping_cone.inl_d S.f n (n+1) (n+1+1) (by linarith) (by linarith)] at hxy,\n obtain ⟨hx, hy⟩ := (mapping_cone.to_ext_iff _ _ _ rfl).mp hxy,\n simp only [preadditive.add_comp, preadditive.sub_comp, assoc, mapping_cone.inr_fst,\n comp_zero, mapping_cone.inl_fst, comp_id, zero_sub, add_zero, zero_comp, neg_eq_zero] at hx,\n simp only [preadditive.add_comp, preadditive.sub_comp, assoc, mapping_cone.inr_snd, comp_id,\n mapping_cone.inl_snd, comp_zero, sub_zero, zero_comp, ← eq_neg_iff_add_eq_zero] at hy,\n clear hxy,\n simp only [preadditive.add_comp, assoc, inr_from_mapping_cone_of_ses,\n inl_from_mapping_cone_of_ses, comp_zero, zero_add] at hz,\n haveI : epi (S.g.f (n-1)) := (ex.map_of_exact (homological_complex.eval _ _ _)).epi_g,\n obtain ⟨A', π, hπ, z', hz'⟩ := abelian.pseudo_surjective_of_epi' (S.g.f (n-1)) z,\n have ex' := (ex.map_of_exact (homological_complex.eval _ _ n)),\n haveI := ex'.mono_f,\n let w : A' ⟶ S.X₁.X n := ex'.exact.lift (π ≫ y - z' ≫ S.X₂.d _ _) begin\n dsimp,\n simp only [preadditive.sub_comp, assoc, hz, reassoc_of hz',\n homological_complex.hom.comm, sub_self],\n end,\n have hw : w ≫ S.f.f n = _ := ex'.exact.lift_f _ _,\n refine ⟨A', π, hπ, w ≫ (mapping_cone.inl S.f).v n (n-1) (show n-1 = n+(-1), by refl) + z' ≫ (mapping_cone.inr S.f).f (n-1),\n (mapping_cone.to_ext_iff _ _ _ rfl).mpr ⟨_, _⟩⟩,\n { simp only [assoc, preadditive.add_comp, mapping_cone.inr_fst, comp_zero, add_zero,\n mapping_cone.inl_fst, comp_id, mapping_cone.inr_d_assoc,\n mapping_cone.inl_d_assoc S.f (n-1) n (n+1) (by refl) (by linarith),\n preadditive.sub_comp, preadditive.comp_sub, ← cancel_mono (S.f.f (n+1)), zero_comp],\n simp only [← S.f.comm, reassoc_of hw, preadditive.sub_comp, assoc, homological_complex.d_comp_d,\n comp_zero, sub_zero, zero_sub, hy, preadditive.comp_neg], },\n { simp only [assoc, preadditive.comp_add, preadditive.add_comp, mapping_cone.inl_snd, comp_zero,\n zero_add, mapping_cone.inr_snd, comp_id, mapping_cone.inr_d_assoc, preadditive.comp_sub,\n preadditive.sub_comp, hw,\n mapping_cone.inl_d S.f (n-1) n (n+1) (show n-1 = n+(-1), by refl) (by linarith)],\n abel, }, },\n { rw short_complex.epi_homology_map_iff,\n dsimp,\n intros A z hz,\n haveI : epi (S.g.f n) := (ex.map_of_exact (homological_complex.eval _ _ _)).epi_g,\n obtain ⟨A', π, hπ, y, hy⟩ := abelian.pseudo_surjective_of_epi' (S.g.f n) z,\n have ex' := (ex.map_of_exact (homological_complex.eval _ _ (n+1))),\n haveI := ex'.mono_f,\n let x : A' ⟶ S.X₁.X (n+1) := ex'.exact.lift (y ≫ S.X₂.d _ _) begin\n dsimp,\n simp only [assoc, ← S.g.comm, ← reassoc_of hy, hz, comp_zero],\n end,\n have hx : x ≫ S.f.f (n+1) = _ := ex'.exact.lift_f _ _,\n have hdx : x ≫ S.X₁.d (n+1) (n+1+1) = 0,\n { simp only [← cancel_mono (S.f.f (n+1+1)), assoc, zero_comp, ← S.f.comm, reassoc_of hx,\n homological_complex.d_comp_d, comp_zero], },\n refine ⟨A', π, hπ, y ≫ (mapping_cone.inr S.f).f n -\n x ≫ (mapping_cone.inl S.f).v (n+1) n (show n = (n+1)+(-1), by linarith), _, _⟩,\n { simp only [preadditive.sub_comp, assoc, mapping_cone.inr_d, ← reassoc_of hx,\n mapping_cone.inl_d S.f n (n+1) (n+1+1) (by linarith) (by linarith), preadditive.comp_sub,\n reassoc_of hdx, zero_comp, sub_zero, sub_self], },\n { exact ⟨0, by simp only [hy, preadditive.sub_comp, assoc, inr_from_mapping_cone_of_ses,\n inl_from_mapping_cone_of_ses, comp_zero, sub_zero, zero_comp, add_zero]⟩, }, },\nend⟩\n\nend abelian\n\nend cochain_complex\n", "meta": {"author": "joelriou", "repo": "homotopical_algebra", "sha": "697f49d6744b09c5ef463cfd3e35932bdf2c78a3", "save_path": "github-repos/lean/joelriou-homotopical_algebra", "path": "github-repos/lean/joelriou-homotopical_algebra/homotopical_algebra-697f49d6744b09c5ef463cfd3e35932bdf2c78a3/src/for_mathlib/algebra/homology/mapping_cone.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4687906266262437, "lm_q2_score": 0.028870905901814212, "lm_q1q2_score": 0.013534410068978802}} {"text": "import Architectural.proofObligations\nimport Architectural.lang\nimport tactic \n\nopen LANG PORTS tactic \n\nlocal infix ` OR `:50 := LANG.disj \nlocal infix ` & `:50 := LANG.conj \nvariables {Var : Type} [fintype Var] [decidable_eq Var] [reflected Var]\n\n\ntheorem asdff (x : Trace PORTS) {A : LANG} : x ∈ (@AssertionLang.sem LANG PORTS _ _ _ A) ↔ x ∈ LANG.sem A := by {refl,}\n\ntheorem fsadfdsa (x : Trace PORTS) (A B : LANG) : x ∈ LANG.sem (A & B).always ↔ x ∈ LANG.sem (A).always ∧ x ∈ LANG.sem (B).always := \nbegin\nsimp, rw forall_and_distrib, \nend \n\ntheorem disj_comm_guarded (x : Trace PORTS) (A B : LANG) : x ∈ LANG.sem (A OR B).always ↔ x ∈ LANG.sem (B OR A).always := \nbegin\nsimp,\nend \ntheorem conj_comm_guarded (x : Trace PORTS) (A B : LANG) : x ∈ LANG.sem (A & B).always ↔ x ∈ LANG.sem (B & A).always := \nbegin\nsplit, all_goals {intros h i, replace h := h i, cases h, split, assumption, assumption,},\nend \n\ntheorem fasdjbasdf {x : Trace PORTS} (A B : LANG) : x ∈ LANG.sem (A & B) ↔ x ∈ LANG.sem A ∧ x ∈ LANG.sem B := \nbegin\nrw conj_def, simp, \nend \n\ntheorem foobars {x : Trace PORTS} (A B C D : LANG) : \n x ∈ LANG.sem ((A & B & C).always & D.always) \n ↔ \n x ∈ LANG.sem (((A & B).always &C.always) & D.always) := \nbegin \nrepeat {rw fasdjbasdf, rw fsadfdsa,},\nend \n\ntheorem portation_left {x : Trace PORTS} (A B : LANG) : (x ∈ @AssertionLang.sem LANG PORTS _ _ _ (A & B).always) → x ∈ (A).always.sem := \nbegin \nintro h, intro i, rw forall_conj_distrib_mem at h, cases h with h1 h2, apply h1 i,\nend \n\ntheorem portation_right {x : Trace PORTS} (A B : LANG) : (x ∈ @AssertionLang.sem LANG PORTS _ _ _ (A & B).always) → x ∈ (B).always.sem := \nbegin \nintro h, intro i, rw forall_conj_distrib_mem at h, cases h with h1 h2, apply h2 i,\nend \n\n\n------\n\nmeta structure model_info := \n(del : list (expr × expr)) \n(comps : list expr)\n\n\nmeta def preprocess_rpo_fst : tactic (name × name) := do \n x ← tactic.get_unused_name `x,\n H ← tactic.get_unused_name `H,\n tactic.intro x,\n `[simp],\n `[rw AssertionLang.impl_def],\n tactic.intro H,\n `[rw [list_conj_iff, get_nfs] at H, simp at H, rw toMap at H],\n return ⟨x, H⟩\n\n\nmeta def decompose_conj : expr → expr → tactic (unit)\n| h `(and %%left %%right) := do \n left_nm ← get_unused_name,\n right_nm ← get_unused_name,\n cases_core h [left_nm, right_nm] transparency.semireducible,\n right_e ← get_local right_nm,\n decompose_conj right_e right\n| _ _ := do return ()\n\nmeta def decompose_conj_left : expr → expr → tactic (unit)\n| h `(and %%left %%right) := do \n left_nm ← get_unused_name,\n right_nm ← get_unused_name,\n cases_core h [left_nm, right_nm] transparency.semireducible,\n left_e ← get_local left_nm,\n decompose_conj left_e left\n| _ _ := do return ()\n\n\n\n\nmeta def collect_assertions : list expr → tactic (list expr) \n| (h::t ) := do \n τ ← infer_type h,\n match τ with \n | `(_ ∈ _) := do \n l ← collect_assertions t,\n return $ [h]++l\n | `(_ ∈ _ → _) := do \n l ← collect_assertions t,\n return $ [h]++l\n | _ := collect_assertions t\n end \n| [] := return []\n\n\ntheorem IFf_pos (c : Prop) (H : decidable c) : ∀ {α : Type} {t e :α}, c → ite c t e = t := by {intros a b c h, apply if_pos h,}\ntheorem IFf_neg : Π (c : Prop) [H : decidable c], ∀ {α : Type} {t e :α}, ¬c → (@ite _ c H t e) = e := by {intros a b c h a f, apply if_neg, exact f}\n\n\nmeta def get_conds_aux : expr → tactic (list expr)\n| `(@ite %%A %%B %%C %%D %%E) := do \n let cond := [B],\n r ← get_conds_aux E,\n return $ cond ++ r\n| _ := return []\n\n\n\nmeta def get_conds : expr → tactic (list expr)\n| `(%%x ∈ AssertionLang.sem (%%E)) :=\n match E with \n | `(Contract.nf (option.iget %%Y)) := get_conds_aux Y\n | `(Contract.A (option.iget %%Y)) := get_conds_aux Y\n | _ := return []\n end \n| `(_ → %%x ∈ AssertionLang.sem (%%E)) :=\n match E with \n | `(Contract.nf (option.iget %%Y)) := get_conds_aux Y\n | _ := return []\n end \n| x := return []\n\nmeta def GFSAUIHasd : list expr → tactic (list (list expr))\n| (h::t) := do \n -- tactic.trace \"here\",\n -- τ ← infer_type h,\n -- tactic.trace τ,\n l← get_conds h, t ← GFSAUIHasd t, return (l::t)\n| _ := do return []\n\n\nmeta def aiuhsfd : list expr → list (expr × bool) \n| [] := []\n| (h::t) := match h with \n | `(eq %%A %%B) := \n if B = A then ([(h,tt)]++(aiuhsfd t)) else ([(h,ff)]++(aiuhsfd t))\n | _ := []\n end \n\nmeta def sjdioaf (hyp : expr) : list (expr × bool) → tactic unit\n| [] := return ()\n| ((e, b)::t) := do \n if b then do \n let ef := expr.mk_app `(IFf_pos) [e],\n rewrite_hyp ef hyp, return () \n else do \n sjdioaf t\n\n\nmeta def suihfa : list (expr × list (expr × bool)) → tactic unit\n| [] := return ()\n| ((e, l)::xs) := do a ← sjdioaf e l,\n suihfa xs\n\nmeta def extract_contracts : expr → tactic unit := λ h, do \n infer_type h >>= decompose_conj h, dedup,\n tactic.repeat `[rw Map.find_val at *],\n xs ← local_context >>= collect_assertions,\n l ← xs.mmap infer_type >>= GFSAUIHasd,\n let ls := xs.zip (l.map aiuhsfd),\n suihfa ls,\n iterate `[rw if_neg at *],\n any_goals `[dec_trivial],\n `[rw nf_def at *, simp at *], \n return ()\n\n\nmeta def collect_consequents : list (expr × expr) → (list (expr × expr)) \n| [] := []\n| ((h, τ)::t) := match τ with \n | `(%%P → %%Q) := (collect_consequents t).cons (h,Q) \n | _ := collect_consequents t\n end \n\nmeta def collect_vars_aux : expr → list expr \n| `(LANG.atom %%a) := [a]\n| `(LANG.lt %%a %%v) := [a,v]\n| `(LANG.neg %%A) := collect_vars_aux A\n| `(LANG.conj %%A %%B) := collect_vars_aux A ++ collect_vars_aux B\n| `(LANG.disj %%A %%B) := collect_vars_aux A ++ collect_vars_aux B\n| `(LANG.always %%A) := collect_vars_aux A\n|_ := []\n\nmeta def collect_vars : expr → list expr \n| `(_ ∈ AssertionLang.sem %%P) := collect_vars_aux P \n| _ := []\n\nmeta def find_matches_aux : expr → list (expr × expr) → list (expr × expr) \n| h ((a,b)::l) := if h=a then [(b,h)] else if h=b then [(a,h)]else (find_matches_aux h l)\n| _ _ := []\n\nmeta def find_matches (del : list (expr × expr)) : list expr → list (expr × expr) \n| [] := []\n| (h::t) := find_matches_aux h del++(find_matches t )\n-- find_matches_aux es del \n\n\nopen tactic.interactive («have»)\n\nmeta def mk_sync_apply (x : expr) : (expr × expr) → tactic unit \n| (a,b) := do \n -- ((synchronize' x fault_PWMFlow_LACU fault_armFlow_armController) (atom fault_PWMFlow_LACU).neg.always).mpr\n `(_ ∈ AssertionLang.sem %%FOO) ← target,\n let e := expr.mk_app `(synchronize') [x, b, a, FOO],\n-- tactic.trace e,\n τ ← infer_type e,\n match τ with \n | `(%%GOAL → %%FOO) := do \n h ← get_unused_name `h,\n «have» h ``(%%GOAL) ``(by dec_trivial),\n h_e ← get_local h,\n let e' := expr.mk_app e [h_e],\n τ ← infer_type e',\n match τ with \n | `(%%l ↔ %%r) := do \n let e'' := `(@iff.mpr %%l %%r %%e'),\n apply e'',\n `[simp],\n clear h_e,\n return ()\n | _ := return ()\n end \n | _ := return ()\n end \n\nmeta def try_application : list expr → tactic unit \n| [] := return ()\n| (h::t) := (do apply h, return ()) <|> try_application t\n\n\nmeta def synchronize_ports (x : name) (Γ : model_info): tactic unit := do \n tgt ← target, \n let cs := collect_vars tgt,\n let ls := find_matches Γ.del cs, -- vars to sub will be on LEFT\n x ← get_local x,\n ls.mmap (mk_sync_apply x),\n return ()\n\nmeta def decompose_env_assumptions (x_nm : name) : tactic unit := do\n A ← get_unused_name `A,\n intro A,\n A_e ← get_local A, x ← get_local x_nm,\n let e := expr.mk_app `(asdff) [x],\n tactic.rewrite_hyp e A_e,\n let e' := expr.mk_app `(fsadfdsa) [x],\n tactic.repeat (do A_e ← get_local A,tactic.rewrite_hyp e' A_e, return ()),\n A_e ← get_local A,\n tactic.repeat (do A_e ← get_local A, cases_core A_e [A] transparency.semireducible, return ()),\n return ()\n\nmeta def try_rewrites : expr → tactic unit \n| `(_ ∈ AssertionLang.sem _) := do `[rw asdff], tactic.repeat (`[rw fsadfdsa]), return ()\n| _ := do tactic.repeat (`[rw fsadfdsa]), return ()\n\n\nmeta def check_for_portation_aux (e : expr) : list expr → tactic unit \n| (h::t) := match h with \n | `(_ → (_ ∈ AssertionLang.sem (%%A & %%B).always)) := \n if A = e then do `[apply portation_left], return () \n else if B = e then do `[apply portation_right], return ()\n else check_for_portation_aux t\n | _ := check_for_portation_aux t\n end \n| [] := return ()\n\nmeta def check_for_portation_aux' (e : expr) : list expr → tactic unit \n| (h::t) := match h with \n | `(_ → _ → (_ ∈ AssertionLang.sem (%%A & %%B).always)) := \n if A = e then do `[apply portation_left], return () \n else if B = e then do `[apply portation_right], return ()\n else check_for_portation_aux' t\n | _ := check_for_portation_aux' t\n end \n| [] := return ()\n\nmeta def check_for_portation : tactic unit := do \n`(_ ∈ LANG.sem (LANG.always %%FOO)) ← target,\nlocal_context >>= (list.mmap infer_type) >>= check_for_portation_aux FOO\n\nmeta def check_for_portation' : tactic unit := do \n`(_ ∈ LANG.sem (LANG.always %%FOO)) ← target,\nlocal_context >>= (list.mmap infer_type) >>= check_for_portation_aux' FOO\n\nmeta def find_assumption : list expr → tactic bool \n| [] := return ff \n| (h::t) := do apply h >> return tt <|> find_assumption t \n\nmeta def try_terminal_rws : tactic unit := do \n `[rwa disj_comm_guarded] <|> `[rwa conj_comm_guarded] <|> return () \n\nmeta def core_rpo_loop (x : name) (Γ : model_info) : tactic unit := do \ncheck_for_portation,\nlocal_context >>= try_application,\nsynchronize_ports x Γ, \ntarget >>= try_rewrites,\nb ← local_context >>= find_assumption,\nif !b then try_terminal_rws else return ()\n\nmeta def solve_rpo_fst_new (Γ : model_info) : tactic unit := do \n ⟨x, H⟩ ← preprocess_rpo_fst,\n get_local H >>= extract_contracts,\n decompose_env_assumptions x,\n synchronize_ports x Γ,\n local_context >>= try_application,\n synchronize_ports x Γ,\n target >>= try_rewrites,\n repeat `[split],\n all_goals $ core_rpo_loop x Γ,\n try (`[repeat {split}, repeat {assumption}]), -- can fix.\n return ()\n\nmeta def make_cases (H : name) : tactic unit := do \n H_e ← get_local H,\n τ ← infer_type H_e,\n match τ with \n |`(or _ _) := do cases_core H_e [] transparency.semireducible, \n all_goals (make_cases ),\n return ()\n | _ := return ()\n end \n\nmeta def find_this_component (Γ : model_info) : list expr → tactic expr \n| [] := return default \n| (h::t) := do \n τ ← infer_type h,\n match τ with \n | `(_ = %%FOO) := \n if FOO ∈ Γ.comps then return FOO else find_this_component t \n | _ := find_this_component t \n end \n\nmeta def get_comp_contract (H : expr) (comp : expr): tactic unit := do \n h ← get_unused_name,\n let e : expr := (expr.mk_app H [comp]),\n τ ← infer_type e,\n tactic.local_proof h (τ) (tactic.exact e),\n return ()\n\nmeta def get_other_comp_contracts (Γ : model_info) (H2 : expr) : tactic expr := do \n e ← local_context >>= find_this_component Γ,\n let l := Γ.comps.erase e,\n l.mmap (get_comp_contract H2),\n return e\n\nmeta def rewrite_this_comp (comp : expr ) : list expr → tactic unit \n| (h::t) := do \n τ ← infer_type h,\n match τ with \n | `(_ = %%FOO) := if FOO = comp then subst h else rewrite_this_comp t \n | _ := rewrite_this_comp t \n end\n| [] := return ()\n\nmeta def decompose_fst_hyp (Γ : model_info) : tactic unit := do \n Ha ← tactic.get_unused_name `Ha,\n `[rw AssertionLang.impl_def], \n tactic.intro Ha, \n `[rw AssertionLang.conj_def at *],\n H_e ← get_local Ha, \n H1 ← get_unused_name `H1,\n H2 ← get_unused_name `H2,\n cases_core H_e [H1,H2] transparency.semireducible,\n `[rw list_conj_iff at *, simp only [list.mem_map, forall_exists_index, and_imp, forall_apply_eq_imp_iff₂] at *], \n this_comp ← get_local H2 >>= get_other_comp_contracts Γ,\n local_context >>= rewrite_this_comp this_comp,\n H1_e ← get_local H1,\n tactic.rewrite_hyp `(asdff) H1_e,\n repeat `[rw fsadfdsa at *],\n tactic.iterate (do H1_e ← get_local H1, cases_core H1_e [H1] transparency.semireducible),\n return ()\n\nmeta def clear_goal_rewrites_aux : expr → tactic unit \n| `(ite (%%X = %%Y) %%B %%C) := if X = Y then do `[rw if_pos] else do `[rw if_neg], clear_goal_rewrites_aux C\n| _ := do return ()\n\nmeta def clear_goal_of_rewrites : tactic unit := do \n tgt ← target,\n match tgt with \n | `(_ ∈ AssertionLang.sem (Contract.A (option.iget (%%FOO)))) := clear_goal_rewrites_aux FOO \n | _ := do tactic.trace \"hmm\", return ()\n end \n\nmeta def rpo_snd_core : tactic unit := do \n repeat (`[rw Map.find_val at *]),\n clear_goal_of_rewrites,\n xs ← local_context >>= collect_assertions,\n l ← xs.mmap infer_type >>= GFSAUIHasd,\n let ls := xs.zip (l.map aiuhsfd),\n suihfa ls,\n clear_goal_of_rewrites,\n iterate `[rw if_neg at *],\n any_goals `[dec_trivial],\n `[rw nf_def at *, simp only [Map.find_val] at *],\n try (`[rw asdff, repeat {rw fsadfdsa}, rw ← asdff, repeat {split}]),\n return ()\n\nmeta def check_for_semantic_unfolding : expr → tactic unit \n| `(_ ∈ AssertionLang.sem _) := do return ()\n| _ := do try `[rw ← asdff] \n\nmeta def finish_conjunctions : tactic unit := do \n any_goals $ `[rw fsadfdsa],\n any_goals $ split,\n any_goals $ assumption,\n any_goals $ `[rw ← asdff], assumption,\n return ()\n\nmeta def new_tac_finisher (x : name) (Γ : model_info) : tactic unit := do \n synchronize_ports x Γ,\n `[rw asdff],\n try_terminal_rws,\n -- finish_conjunctions,\n -- `[rw fsadfdsa],\n -- split, -- copied from above\n -- assumption,rw ← asdff,assumption],\n return ()\n\nmeta def solve_rpo_snd_new (Γ : model_info) : tactic unit := do \n S ← tactic.get_unused_name `S,\n H ← tactic.get_unused_name `H,\n x ← tactic.get_unused_name `x,\n tactic.intro S, tactic.intro H, tactic.intro x,\n `[simp at *],\n make_cases H,\n all_goals $ decompose_fst_hyp Γ,\n all_goals $ rpo_snd_core, \n all_goals $ try $ `[rw ← asdff],\n all_goals (do x_e ← get_local x,synchronize_ports x Γ),\n all_goals $ `[rw asdff],\n all_goals $ local_context >>= try_application,\n any_goals `[dec_trivial],\n any_goals $ try_terminal_rws,\n all_goals $ try (check_for_portation'),\n all_goals $ local_context >>= try_application,\n any_goals $ `[dec_trivial],\n all_goals $ new_tac_finisher x Γ,\n all_goals $ (do `[rw fsadfdsa, split], assumption <|> `[rw ← asdff], assumption),\n return ()", "meta": {"author": "loganrjmurphy", "repo": "ForeMoSt", "sha": "c7affc7c8971562520d2775ac48fe4f188f84b02", "save_path": "github-repos/lean/loganrjmurphy-ForeMoSt", "path": "github-repos/lean/loganrjmurphy-ForeMoSt/ForeMoSt-c7affc7c8971562520d2775ac48fe4f188f84b02/src/rpo_fst_tactic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.414898860266261, "lm_q2_score": 0.03258974734991799, "lm_q1q2_score": 0.013521449031846374}} {"text": "/-\nCopyright (c) 2021 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Leonardo de Moura\n\nNotation for operators defined at Prelude.lean\n-/\nprelude\nimport Init.NotationExtra\n\nnamespace Lean.Parser.Tactic.Conv\n\n/-- `conv` is the syntax category for a \"conv tactic\", where \"conv\" is short\nfor conversion. A conv tactic is a program which receives a target, printed as\n`| a`, and is tasked with coming up with some term `b` and a proof of `a = b`.\nIt is mainly used for doing targeted term transformations, for example rewriting\nonly on the left side of an equality. -/\ndeclare_syntax_cat conv (behavior := both)\n\nsyntax convSeq1Indented := sepBy1IndentSemicolon(conv)\nsyntax convSeqBracketed := \"{\" withoutPosition(sepByIndentSemicolon(conv)) \"}\"\n-- Order is important: a missing `conv` proof should not be parsed as `{ }`,\n-- automatically closing goals\nsyntax convSeq := convSeqBracketed <|> convSeq1Indented\n\n/-- The `*` occurrence list means to apply to all occurrences of the pattern. -/\nsyntax occsWildcard := \"*\"\n\n/--\nA list `1 2 4` of occurrences means to apply to the first, second, and fourth\noccurrence of the pattern.\n-/\nsyntax occsIndexed := num+\n\n/-- An occurrence specification, either `*` or a list of numbers. The default is `[1]`. -/\nsyntax occs := atomic(\"(\" &\"occs\") \" := \" (occsWildcard <|> occsIndexed) \") \"\n\n/--\n`with_annotate_state stx t` annotates the lexical range of `stx : Syntax` with\nthe initial and final state of running tactic `t`.\n-/\nscoped syntax (name := withAnnotateState)\n \"with_annotate_state \" rawStx ppSpace conv : conv\n\n\n/-- `skip` does nothing. -/\nsyntax (name := skip) \"skip\" : conv\n\n/-- Traverses into the left subterm of a binary operator.\n(In general, for an `n`-ary operator, it traverses into the second to last argument.) -/\nsyntax (name := lhs) \"lhs\" : conv\n\n/-- Traverses into the right subterm of a binary operator.\n(In general, for an `n`-ary operator, it traverses into the last argument.) -/\nsyntax (name := rhs) \"rhs\" : conv\n\n/-- Reduces the target to Weak Head Normal Form. This reduces definitions\nin \"head position\" until a constructor is exposed. For example, `List.map f [a, b, c]`\nweak head normalizes to `f a :: List.map f [b, c]`. -/\nsyntax (name := whnf) \"whnf\" : conv\n\n/-- Expands let-declarations and let-variables. -/\nsyntax (name := zeta) \"zeta\" : conv\n\n/-- Puts term in normal form, this tactic is meant for debugging purposes only. -/\nsyntax (name := reduce) \"reduce\" : conv\n\n/-- Performs one step of \"congruence\", which takes a term and produces\nsubgoals for all the function arguments. For example, if the target is `f x y` then\n`congr` produces two subgoals, one for `x` and one for `y`. -/\nsyntax (name := congr) \"congr\" : conv\n\n/--\n* `arg i` traverses into the `i`'th argument of the target. For example if the\n target is `f a b c d` then `arg 1` traverses to `a` and `arg 3` traverses to `c`.\n* `arg @i` is the same as `arg i` but it counts all arguments instead of just the\n explicit arguments. -/\nsyntax (name := arg) \"arg \" \"@\"? num : conv\n\n/-- `ext x` traverses into a binder (a `fun x => e` or `∀ x, e` expression)\nto target `e`, introducing name `x` in the process. -/\nsyntax (name := ext) \"ext\" (colGt ident)* : conv\n\n/-- `change t'` replaces the target `t` with `t'`,\nassuming `t` and `t'` are definitionally equal. -/\nsyntax (name := change) \"change \" term : conv\n\n/-- `delta id1 id2 ...` unfolds all occurrences of `id1`, `id2`, ... in the target.\nLike the `delta` tactic, this ignores any definitional equations and uses\nprimitive delta-reduction instead, which may result in leaking implementation details.\nUsers should prefer `unfold` for unfolding definitions. -/\nsyntax (name := delta) \"delta \" (colGt ident)+ : conv\n\n/--\n* `unfold foo` unfolds all occurrences of `foo` in the target.\n* `unfold id1 id2 ...` is equivalent to `unfold id1; unfold id2; ...`.\nLike the `unfold` tactic, this uses equational lemmas for the chosen definition\nto rewrite the target. For recursive definitions,\nonly one layer of unfolding is performed. -/\nsyntax (name := unfold) \"unfold \" (colGt ident)+ : conv\n\n/--\n* `pattern pat` traverses to the first subterm of the target that matches `pat`.\n* `pattern (occs := *) pat` traverses to every subterm of the target that matches `pat`\n which is not contained in another match of `pat`. It generates one subgoal for each matching\n subterm.\n* `pattern (occs := 1 2 4) pat` matches occurrences `1, 2, 4` of `pat` and produces three subgoals.\n Occurrences are numbered left to right from the outside in.\n\nNote that skipping an occurrence of `pat` will traverse inside that subexpression, which means\nit may find more matches and this can affect the numbering of subsequent pattern matches.\nFor example, if we are searching for `f _` in `f (f a) = f b`:\n* `occs := 1 2` (and `occs := *`) returns `| f (f a)` and `| f b`\n* `occs := 2` returns `| f a`\n* `occs := 2 3` returns `| f a` and `| f b`\n* `occs := 1 3` is an error, because after skipping `f b` there is no third match.\n-/\nsyntax (name := pattern) \"pattern \" (occs)? term : conv\n\n/-- `rw [thm]` rewrites the target using `thm`. See the `rw` tactic for more information. -/\nsyntax (name := rewrite) \"rewrite\" (config)? rwRuleSeq : conv\n\n/-- `simp [thm]` performs simplification using `thm` and marked `@[simp]` lemmas.\nSee the `simp` tactic for more information. -/\nsyntax (name := simp) \"simp\" (config)? (discharger)? (&\" only\")?\n (\" [\" withoutPosition((simpStar <|> simpErase <|> simpLemma),*) \"]\")? : conv\n\n/--\n`dsimp` is the definitional simplifier in `conv`-mode. It differs from `simp` in that it only\napplies theorems that hold by reflexivity.\n\nExamples:\n\n```lean\nexample (a : Nat): (0 + 0) = a - a := by\n conv =>\n lhs\n dsimp\n rw [← Nat.sub_self a]\n```\n-/\nsyntax (name := dsimp) \"dsimp \" (config)? (discharger)? (&\"only \")?\n (\"[\" withoutPosition((simpErase <|> simpLemma),*) \"]\")? : conv\n\n/-- `simp_match` simplifies match expressions. For example,\n```\nmatch [a, b] with\n| [] => 0\n| hd :: tl => hd\n```\nsimplifies to `a`. -/\nsyntax (name := simpMatch) \"simp_match\" : conv\n\n\n/-- Executes the given tactic block without converting `conv` goal into a regular goal. -/\nsyntax (name := nestedTacticCore) \"tactic'\" \" => \" tacticSeq : conv\n\n/-- Focuses, converts the `conv` goal `⊢ lhs` into a regular goal `⊢ lhs = rhs`, and then executes the given tactic block. -/\nsyntax (name := nestedTactic) \"tactic\" \" => \" tacticSeq : conv\n\n/-- Executes the given conv block without converting regular goal into a `conv` goal. -/\nsyntax (name := convTactic) \"conv'\" \" => \" convSeq : tactic\n\n/-- `{ convs }` runs the list of `convs` on the current target, and any subgoals that\nremain are trivially closed by `skip`. -/\nsyntax (name := nestedConv) convSeqBracketed : conv\n\n/-- `(convs)` runs the `convs` in sequence on the current list of targets.\nThis is pure grouping with no added effects. -/\nsyntax (name := paren) \"(\" withoutPosition(convSeq) \")\" : conv\n\n/-- `rfl` closes one conv goal \"trivially\", by using reflexivity\n(that is, no rewriting). -/\nmacro \"rfl\" : conv => `(conv| tactic => rfl)\n\n/-- `done` succeeds iff there are no goals remaining. -/\nmacro \"done\" : conv => `(conv| tactic' => done)\n\n/-- `trace_state` prints the current goal state. -/\nmacro \"trace_state\" : conv => `(conv| tactic' => trace_state)\n\n/-- `all_goals tac` runs `tac` on each goal, concatenating the resulting goals, if any. -/\nmacro (name := allGoals) tk:\"all_goals \" s:convSeq : conv =>\n `(conv| tactic' => all_goals%$tk conv' => $s)\n\n/--\n`any_goals tac` applies the tactic `tac` to every goal, and succeeds if at\nleast one application succeeds.\n-/\nmacro (name := anyGoals) tk:\"any_goals \" s:convSeq : conv =>\n `(conv| tactic' => any_goals%$tk conv' => $s)\n\n/--\n* `case tag => tac` focuses on the goal with case name `tag` and solves it using `tac`,\n or else fails.\n* `case tag x₁ ... xₙ => tac` additionally renames the `n` most recent hypotheses\n with inaccessible names to the given names.\n* `case tag₁ | tag₂ => tac` is equivalent to `(case tag₁ => tac); (case tag₂ => tac)`.\n-/\nmacro (name := case) tk:\"case \" args:sepBy1(caseArg, \" | \") arr:\" => \" s:convSeq : conv =>\n `(conv| tactic' => case%$tk $args|* =>%$arr conv' => ($s); all_goals rfl)\n\n/--\n`case'` is similar to the `case tag => tac` tactic, but does not ensure the goal\nhas been solved after applying `tac`, nor admits the goal if `tac` failed.\nRecall that `case` closes the goal using `sorry` when `tac` fails, and\nthe tactic execution is not interrupted.\n-/\nmacro (name := case') tk:\"case' \" args:sepBy1(caseArg, \" | \") arr:\" => \" s:convSeq : conv =>\n `(conv| tactic' => case'%$tk $args|* =>%$arr conv' => $s)\n\n/--\n`next => tac` focuses on the next goal and solves it using `tac`, or else fails.\n`next x₁ ... xₙ => tac` additionally renames the `n` most recent hypotheses with\ninaccessible names to the given names.\n-/\nmacro \"next \" args:binderIdent* \" => \" tac:convSeq : conv => `(conv| case _ $args* => $tac)\n\n/--\n`focus tac` focuses on the main goal, suppressing all other goals, and runs `tac` on it.\nUsually `· tac`, which enforces that the goal is closed by `tac`, should be preferred.\n-/\nmacro (name := focus) tk:\"focus \" s:convSeq : conv => `(conv| tactic' => focus%$tk conv' => $s)\n\n/-- `conv => cs` runs `cs` in sequence on the target `t`,\nresulting in `t'`, which becomes the new target subgoal. -/\nsyntax (name := convConvSeq) \"conv\" \" => \" convSeq : conv\n\n/-- `· conv` focuses on the main conv goal and tries to solve it using `s`. -/\nmacro dot:patternIgnore(\"·\" <|> \".\") s:convSeq : conv => `(conv| {%$dot ($s) })\n\n\n/-- `fail_if_success t` fails if the tactic `t` succeeds. -/\nmacro (name := failIfSuccess) tk:\"fail_if_success \" s:convSeq : conv =>\n `(conv| tactic' => fail_if_success%$tk conv' => $s)\n\n/-- `rw [rules]` applies the given list of rewrite rules to the target.\nSee the `rw` tactic for more information. -/\nmacro \"rw\" c:(config)? s:rwRuleSeq : conv => `(conv| rewrite $[$c]? $s)\n\n/-- `erw [rules]` is a shorthand for `rw (config := { transparency := .default }) [rules]`.\nThis does rewriting up to unfolding of regular definitions (by comparison to regular `rw`\nwhich only unfolds `@[reducible]` definitions). -/\nmacro \"erw\" s:rwRuleSeq : conv => `(conv| rw (config := { transparency := .default }) $s)\n\n/-- `args` traverses into all arguments. Synonym for `congr`. -/\nmacro \"args\" : conv => `(conv| congr)\n/-- `left` traverses into the left argument. Synonym for `lhs`. -/\nmacro \"left\" : conv => `(conv| lhs)\n/-- `right` traverses into the right argument. Synonym for `rhs`. -/\nmacro \"right\" : conv => `(conv| rhs)\n/-- `intro` traverses into binders. Synonym for `ext`. -/\nmacro \"intro\" xs:(colGt ident)* : conv => `(conv| ext $xs*)\n\nsyntax enterArg := ident <|> (\"@\"? num)\n\n/-- `enter [arg, ...]` is a compact way to describe a path to a subterm.\nIt is a shorthand for other conv tactics as follows:\n* `enter [i]` is equivalent to `arg i`.\n* `enter [@i]` is equivalent to `arg @i`.\n* `enter [x]` (where `x` is an identifier) is equivalent to `ext x`.\nFor example, given the target `f (g a (fun x => x b))`, `enter [1, 2, x, 1]`\nwill traverse to the subterm `b`. -/\nsyntax \"enter\" \" [\" (colGt enterArg),+ \"]\": conv\nmacro_rules\n | `(conv| enter [$i:num]) => `(conv| arg $i)\n | `(conv| enter [@$i]) => `(conv| arg @$i)\n | `(conv| enter [$id:ident]) => `(conv| ext $id)\n | `(conv| enter [$arg, $args,*]) => `(conv| (enter [$arg]; enter [$args,*]))\n\n/-- The `apply thm` conv tactic is the same as `apply thm` the tactic.\nThere are no restrictions on `thm`, but strange results may occur if `thm`\ncannot be reasonably interpreted as proving one equality from a list of others. -/\n-- TODO: error if non-conv subgoals?\nmacro \"apply \" e:term : conv => `(conv| tactic => apply $e)\n\n/-- `first | conv | ...` runs each `conv` until one succeeds, or else fails. -/\nsyntax (name := first) \"first \" withPosition((colGe \"|\" convSeq)+) : conv\n\n/-- `try tac` runs `tac` and succeeds even if `tac` failed. -/\nmacro \"try \" t:convSeq : conv => `(conv| first | $t | skip)\n\nmacro:1 x:conv tk:\" <;> \" y:conv:0 : conv =>\n `(conv| tactic' => (conv' => $x:conv) <;>%$tk (conv' => $y:conv))\n\n/-- `repeat convs` runs the sequence `convs` repeatedly until it fails to apply. -/\nsyntax \"repeat\" convSeq : conv\nmacro_rules\n | `(conv| repeat $seq) => `(conv| first | ($seq); repeat $seq | rfl)\n\n/--\n`conv => ...` allows the user to perform targeted rewriting on a goal or hypothesis,\nby focusing on particular subexpressions.\n\nSee for more details.\n\nBasic forms:\n* `conv => cs` will rewrite the goal with conv tactics `cs`.\n* `conv at h => cs` will rewrite hypothesis `h`.\n* `conv in pat => cs` will rewrite the first subexpression matching `pat` (see `pattern`).\n-/\n-- HACK: put this at the end so that references to `conv` above\n-- refer to the syntax category instead of this syntax\nsyntax (name := conv) \"conv \" (\" at \" ident)? (\" in \" (occs)? term)? \" => \" convSeq : tactic\n\nend Lean.Parser.Tactic.Conv\n", "meta": {"author": "leanprover", "repo": "lean4", "sha": "742d053a97bdd109a41a921facd1cd6a55e89bc7", "save_path": "github-repos/lean/leanprover-lean4", "path": "github-repos/lean/leanprover-lean4/lean4-742d053a97bdd109a41a921facd1cd6a55e89bc7/src/Init/Conv.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2845760042165267, "lm_q2_score": 0.047425874019047645, "lm_q1q2_score": 0.013496265724816965}} {"text": "import Lean\nimport Mathlib.Tactic.Simps.Basic\nimport Mathlib.Tactic.PermuteGoals\nimport Mathlib.Tactic.Classical\n\nopen Lean Elab Parser Term Meta Tactic\n\nsyntax (name := seq) \"seq\" tacticSeq : tactic\n\nsection Source\n -- modified from `Lean.Elab.Tactic.Simp`\n def traceSimpCall' (stx : Syntax) (usedSimps : Simp.UsedSimps) : MetaM Syntax := do\n let mut stx := stx\n if stx[3].isNone then\n stx := stx.setArg 3 (mkNullNode #[mkAtom \"only\"])\n let mut args := #[]\n let mut localsOrStar := some #[]\n let lctx ← getLCtx\n let env ← getEnv\n for (thm, _) in usedSimps.toArray.qsort (·.2 < ·.2) do\n match thm with\n | .decl declName => -- global definitions in the environment\n if env.contains declName && !simpOnlyBuiltins.contains declName then\n args := args.push (← `(Parser.Tactic.simpLemma| $(mkIdent (← unresolveNameGlobal declName)):ident))\n | .fvar fvarId => -- local hypotheses in the context\n if let some ldecl := lctx.find? fvarId then\n localsOrStar := localsOrStar.bind fun locals =>\n if !ldecl.userName.isInaccessibleUserName &&\n (lctx.findFromUserName? ldecl.userName).get!.fvarId == ldecl.fvarId then\n some (locals.push ldecl.userName)\n else\n none\n -- Note: the `if let` can fail for `simp (config := {contextual := true})` when\n -- rewriting with a variable that was introduced in a scope. In that case we just ignore.\n | .stx _ thmStx => -- simp theorems provided in the local invocation\n args := args.push ⟨thmStx⟩ \n | .other _ => -- Ignore \"special\" simp lemmas such as constructed by `simp_all`.\n pure () -- We can't display them anyway.\n if let some locals := localsOrStar then\n args := args ++ (← locals.mapM fun id => `(Parser.Tactic.simpLemma| $(mkIdent id):ident))\n else\n args := args.push ⟨(← `(Parser.Tactic.simpStar| *))⟩ \n let argsStx := if args.isEmpty then #[] else #[mkAtom \"[\", (mkAtom \",\").mkSep args, mkAtom \"]\"]\n stx := stx.setArg 4 (mkNullNode argsStx)\n return stx\n\n def dsimpLocation' (ctx : Simp.Context) (loc : Location) : TacticM Syntax := do\n match loc with\n | Location.targets hyps simplifyTarget =>\n withMainContext do\n let fvarIds ← getFVarIds hyps\n go fvarIds simplifyTarget\n | Location.wildcard =>\n withMainContext do\n go (← (← getMainGoal).getNondepPropHyps) (simplifyTarget := true)\n where\n go (fvarIdsToSimp : Array FVarId) (simplifyTarget : Bool) : TacticM Syntax := do\n let mvarId ← getMainGoal\n let (result?, usedSimps) ← dsimpGoal mvarId ctx (simplifyTarget := simplifyTarget) (fvarIdsToSimp := fvarIdsToSimp)\n match result? with\n | none => replaceMainGoal []\n | some mvarId => replaceMainGoal [mvarId]\n traceSimpCall' (← getRef) usedSimps\n\n def getMainGoal' : TacticM (MVarId × List MVarId) := do\n loop (← getGoals)\n where\n loop : List MVarId → TacticM (MVarId × List MVarId)\n | [] => throwNoGoalsToBeSolved\n | mvarId :: mvarIds => do\n if (← mvarId.isAssigned) then\n loop mvarIds\n else\n setGoals (mvarId :: mvarIds)\n return (mvarId, mvarIds)\n\n/--\n Searches for a metavariable `g` s.t. `tag` is its exact name.\n If none then searches for a metavariable `g` s.t. `tag` is a suffix of its name.\n If none, then it searches for a metavariable `g` s.t. `tag` is a prefix of its name. -/\ndef findTag? (mvarIds : List MVarId) (tag : Name) : TacticM (Option MVarId) := do\n match (← mvarIds.findM? fun mvarId => return tag == (← mvarId.getDecl).userName) with\n | some mvarId => return mvarId\n | none =>\n match (← mvarIds.findM? fun mvarId => return tag.isSuffixOf (← mvarId.getDecl).userName) with\n | some mvarId => return mvarId\n | none => mvarIds.findM? fun mvarId => return tag.isPrefixOf (← mvarId.getDecl).userName\n\ndef getCaseGoals (tag : TSyntax `Lean.binderIdent) : TacticM (MVarId × List MVarId) := do\n let gs ← getUnsolvedGoals\n let g ← if let `(Lean.binderIdent| $tag:ident) := tag then\n let tag := tag.getId\n let some g ← findTag? gs tag | throwError \"tag not found\"\n pure g\n else\n getMainGoal\n return (g, gs.erase g)\n\ndef matchAltTac := Term.matchAlt (rhsParser := matchRhs)\n\nend Source\n\ndef traceGoalsAt (stx : TSyntax `tactic) : TacticM Unit := do\n let gs ← getUnsolvedGoals\n withRef stx <| addRawTrace (goalsToMessageData gs)\n\ndef traceTacticCallAt (stx : TSyntax `tactic) (tac : TSyntax `tactic) : TacticM Unit := do\n withRef stx <| addRawTrace m!\"[TACTIC] {tac}\"\n\n#check Split.applyMatchSplitter\n\npartial def evalTacticWithTrace : TSyntax `tactic → TacticM Unit\n /- Dealing with bracketing -/\n | `(tactic| { $[$tacs]* }) => do \n for tac in tacs do \n evalTacticWithTrace tac\n | `(tactic| ( $[$tacs]* )) => do \n for tac in tacs do \n evalTacticWithTrace tac\n /- Dealing with focused goals -/\n | `(tactic| · $[$tacs]*) => do\n let (mainGoal, otherGoals) ← getMainGoal'\n setGoals [mainGoal]\n for tac in tacs do\n evalTacticWithTrace tac\n setGoals otherGoals\n | `(tactic| focus $[$tacs]*) => do\n let (mainGoal, otherGoals) ← getMainGoal'\n setGoals [mainGoal]\n for tac in tacs do\n evalTacticWithTrace tac\n setGoals otherGoals\n /- Handle trace for the `classical` tactic -/\n | `(tactic| classical $[$tacs]*) => do\n modifyEnv Meta.instanceExtension.pushScope\n Meta.addInstance ``Classical.propDecidable .local 10\n try for tac in tacs do evalTacticWithTrace tac\n finally modifyEnv Meta.instanceExtension.popScope\n /- Trace `simp` calls with the complete list of theorems used -/\n | stx@`(tactic| simp%$tk $(config)? $(discharger)? $[only%$o]? $[[$args,*]]? $(loc)?) => do\n traceGoalsAt stx\n let { ctx, dischargeWrapper } ← withMainContext <| mkSimpContext stx (eraseLocal := false)\n let usedSimps ← dischargeWrapper.with fun discharge? =>\n simpLocation ctx discharge? (expandOptLocation stx.raw[5])\n traceTacticCallAt stx ⟨← traceSimpCall' stx usedSimps⟩\n traceGoalsAt stx\n | stx@`(tactic| simp_all%$tk $(config)? $(discharger)? $[only%$o]? $[[$args,*]]?) => do\n traceGoalsAt stx\n let { ctx, .. } ← mkSimpContext stx (eraseLocal := true) (kind := .simpAll) (ignoreStarArg := true)\n let (result?, usedSimps) ← simpAll (← getMainGoal) ctx\n match result? with\n | none => replaceMainGoal []\n | some mvarId => replaceMainGoal [mvarId]\n traceTacticCallAt stx ⟨← traceSimpCall' stx usedSimps⟩\n traceGoalsAt stx\n | stx@`(tactic| dsimp%$tk $(config)? $[only%$o]? $[[$args,*]]? $(loc)?) => do\n traceGoalsAt stx\n let { ctx, .. } ← withMainContext <| mkSimpContext stx (eraseLocal := false) (kind := .dsimp)\n traceTacticCallAt stx ⟨← dsimpLocation' ctx (expandOptLocation stx.raw[5])⟩\n traceGoalsAt stx\n /- Treat a rewrite sequence as a sequence of individual rewrites, with a trace provided at each step -/\n | `(tactic| rw $[$cfg]? [$rs,*] $[$loc]?) => do\n for r in (rs : TSyntaxArray `Lean.Parser.Tactic.rwRule) do\n traceGoalsAt ⟨r.raw⟩\n let rtac ← `(tactic| rw $[$cfg]? [$r] $[$loc]?) \n evalTactic rtac\n traceTacticCallAt ⟨r.raw⟩ rtac\n traceGoalsAt ⟨r.raw⟩\n | `(tactic| erw [$rs,*] $[$loc]?) => do\n for r in (rs : TSyntaxArray `Lean.Parser.Tactic.rwRule) do\n traceGoalsAt ⟨r.raw⟩\n let rtac ← `(tactic| erw [$r] $[$loc]?) \n evalTactic rtac\n traceTacticCallAt ⟨r.raw⟩ rtac\n traceGoalsAt ⟨r.raw⟩\n | `(tactic| rwa [$rs,*] $[$loc]?) => do\n for r in (rs : TSyntaxArray `Lean.Parser.Tactic.rwRule) do\n traceGoalsAt ⟨r.raw⟩\n let rtac ← `(tactic| rw [$r] $[$loc]?) \n evalTactic rtac\n traceTacticCallAt ⟨r.raw⟩ rtac\n traceGoalsAt ⟨r.raw⟩\n `(tactic| assumption) >>= evalTactic ∘ TSyntax.raw\n /- Annotate `apply` and `exact` applications with the type information -/\n | stx@`(tactic| apply $v) => do\n traceGoalsAt stx\n evalTactic stx\n let trm ← Tactic.elabTerm v none\n let typ ← inferType trm\n let (mainGoal, otherGoals) ← getMainGoal'\n let newGoals ← mainGoal.apply trm\n setGoals <| newGoals ++ otherGoals\n let typ ← instantiateMVars typ\n let typStx ← PrettyPrinter.delab typ\n `(tactic| apply ($v : $typStx)) >>= traceTacticCallAt stx\n traceGoalsAt stx\n | stx@`(tactic| exact $v) => do\n traceGoalsAt stx\n evalTactic stx\n let trm ← Tactic.elabTerm v none\n let typ ← inferType trm\n let typStx ← PrettyPrinter.delab typ\n `(tactic| exact ($v : $typStx)) >>= traceTacticCallAt stx\n traceGoalsAt stx\n /- Handling `match`, `induction` and `cases` -/\n | stx@`(tactic| case $[$tag $hs*]|* =>%$arr $tac:tacticSeq) => do\n for tag in tag, h in hs do\n traceGoalsAt ⟨arr⟩\n traceTacticCallAt ⟨arr⟩ stx -- TODO (unimportant) remove the `tacticSeq` from `stx`\n let (g, _) ← getCaseGoals tag\n withRef arr <| addRawTrace (goalsToMessageData [g])\n let stx ← `(tactic| case $[$tag $hs*]|* =>%$arr seq $tac:tacticSeq)\n evalTactic stx.raw\n | stx@`(tactic| case' $[$tag $hs*]|* =>%$arr $tac:tacticSeq) => do\n for tag in tag, h in hs do\n traceGoalsAt ⟨arr⟩\n traceTacticCallAt ⟨arr⟩ stx -- TODO (unimportant) remove the `tacticSeq` from `stx`\n let (g, _) ← getCaseGoals tag\n withRef arr <| addRawTrace (goalsToMessageData [g])\n let stx ← `(tactic| case' $[$tag $hs*]|* =>%$arr seq $tac:tacticSeq)\n | `(tactic| induction $[$ts],* $[using $id:ident]? $[generalizing $gs*]? with $[$tac]? $is*) => do\n let is' : TSyntaxArray ``inductionAlt ←\n is.mapM <|\n fun\n | `(inductionAlt| $il* => $ts:tacticSeq) => `(inductionAlt| $il* => seq $ts)\n | i => return ⟨i⟩\n let stx' ← `(tactic| induction $[$ts],* $[using $id:ident]? $[generalizing $gs*]? with $[$tac]? $is'*)\n evalTactic stx'\n | `(tactic| cases $[$cs],* $[using $id:ident]? with $[$tac]? $is*) => do\n let is' : TSyntaxArray ``inductionAlt ←\n is.mapM <|\n fun\n | `(inductionAlt| $il* => $ts:tacticSeq) => `(inductionAlt| $il* => seq $ts)\n | i => return ⟨i⟩\n let stx' ← `(tactic| cases $[$cs],* $[using $id:ident]? with $[$tac]? $is'*)\n evalTactic stx'\n | `(tactic| match $[$gen]? $[$motive]? $discrs,* with $alts:matchAlt*) => do\n let alts' : TSyntaxArray ``matchAlt ←\n alts.mapM <|\n fun\n | `(matchAltTac| | $[$pats,*]|* => $rhs:tacticSeq) => do\n let alt ← `(matchAltTac| | $[$pats,*]|* => seq $rhs)\n return ⟨alt⟩\n | alt => return ⟨alt⟩\n let stx' ← `(tactic| match $[$gen]? $[$motive]? $discrs,* with $alts':matchAlt*)\n evalTactic stx'\n /- Display the expected type in `have` and `let` statements -/\n | stx@`(tactic| have $[$x:ident]? := $prf) => do\n traceGoalsAt stx\n evalTactic stx\n let trm ← Tactic.elabTerm prf none\n let typ ← inferType trm\n let typStx ← PrettyPrinter.delab typ\n `(tactic| have $[$x:ident]? : $typStx := $prf) >>= traceTacticCallAt stx\n traceGoalsAt stx\n | stx@`(tactic| let $x:ident := $val) => do\n traceGoalsAt stx\n evalTactic stx\n let trm ← Tactic.elabTerm val none\n let typ ← inferType trm\n let typStx ← PrettyPrinter.delab typ\n `(tactic| let $x:ident : $typStx := $val) >>= traceTacticCallAt stx \n traceGoalsAt stx\n /- Otherwise, evaluate the tactic normally -/\n | stx@`(tactic| $tac) => do\n traceGoalsAt stx\n evalTactic tac\n traceTacticCallAt stx tac\n traceGoalsAt stx\n\n@[tactic seq]\ndef traceSequence : Tactic := fun s => do\n -- Leonardo de Moura's code for extracting the list of tactics\n match s with\n | `(tactic| seq $[$tacs]*) =>\n for tac in tacs do\n evalTacticWithTrace tac\n | _ => evalTactic <| ← `(tactic.sorry)\n\n-- an example of the `seq` tactic\nexample (h : x = y) : 0 + x = y ∧ 1 = 1 := by\n seq \n rw [Nat.zero_add, (h : x = y)]\n refine' ⟨_, _⟩\n focus\n rw [←h, h]\n · rfl\n\n-- a deep copy of Lean's `by` tactic, called `by'`\nsyntax (name := byTactic') \"by' \" tacticSeq : term\n\n@[term_elab byTactic'] def elabByTactic' : TermElab := fun stx expectedType? => do\n match expectedType? with\n | some expectedType =>\n let mvar ← mkFreshExprMVar expectedType MetavarKind.syntheticOpaque\n let mvarId := mvar.mvarId!\n let ref ← getRef\n registerSyntheticMVar ref mvarId <| SyntheticMVarKind.tactic stx (← saveContext)\n return mvar\n | none =>\n tryPostpone\n throwError (\"invalid 'by\\'' tactic, expected type has not been provided\")\n\nexample : 1 + 1 = 2 := by' -- the new `by'` syntax can be used to replace `by`\n focus\n rfl\n\n-- intercepting the `by` tactic to output intermediate trace data\n-- the `by'` clone is needed here to avoid infinite recursion\nmacro_rules\n | `(by $t) => `(by' seq $t) \n\nsection Test\n\nset_option linter.unreachableTactic false\n\n-- the `by` tactic now generates trace data by default\nexample (h : x = y) : x + 0 + x = x + y ∧ 1 = 1 := by\n have := (rfl : 1 = 1)\n let a := 5\n simp at this\n refine' ⟨_, _⟩\n · apply Eq.symm\n apply Eq.symm\n erw [h, ← h, h, ← h]\n simp_all\n · apply Eq.symm\n apply Eq.symm\n subst h\n rfl\n done\n\nexample : ∀ n : Nat, n = n := by\n intro n\n let x : ∀ m : ℕ, m = m := by\n intro a\n rfl\n match n with\n | .zero => rfl\n | .succ _ => rfl\n\nexample : P ∧ Q ↔ Q ∧ P := by\n constructor\n · intro ⟨x, y⟩\n constructor\n · assumption\n · assumption\n · intro ⟨_, _⟩\n constructor\n · assumption\n · assumption\n\nexample : ∀ n : Nat, n = n := by\n intro n\n induction n\n case zero => rfl\n case succ _ ih => simp\n\nexample : ∀ n : Nat, n + n = n + n := by\n intro n\n induction n with\n | zero => rfl\n | succ _ _ => rfl\n\nexample : ∀ n : Nat, n + n = n + n := by\n intro n\n cases n with\n | zero =>\n let h := (rfl : 1 = 1)\n rfl\n | succ _ => rfl\n\nexample : ∀ n : Nat, n + n = n + n := by\n intro n\n match n with\n | .zero => rfl\n | .succ _ => rfl\n\nend Test", "meta": {"author": "siddhartha-gadgil", "repo": "LeanAide", "sha": "7862af73ee2f0be08b20fd3e4148e20bf4a81054", "save_path": "github-repos/lean/siddhartha-gadgil-LeanAide", "path": "github-repos/lean/siddhartha-gadgil-LeanAide/LeanAide-7862af73ee2f0be08b20fd3e4148e20bf4a81054/LeanCodePrompts/TacticExtraction.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3665897363221598, "lm_q2_score": 0.03676946567977764, "lm_q1q2_score": 0.013479308728256388}} {"text": "import Lean\nimport Mathlib.Control.Writer\nimport PremiseSelection.Utils\nopen Lean\n/-!\n\n# Theorem feature extraction\n\nInput: the goal state\nOuput: the theorem statement as an expr\n\n -/\nopen Std\n\ndef Std.RBMap.modify' (k : κ) (fn : Option α → Option α) (r : RBMap κ α cmp) :=\n match fn <| r.find? k with\n | none => r.erase k\n | some v => r.insert k v\n\ndef Std.RBMap.mergeBy (fn : κ → α → α → α) (r1 r2 : RBMap κ α cmp) : RBMap κ α cmp :=\n r2.foldl (fun r1 k v2 => r1.modify' k (fun | none => some v2 | some v1 => some (fn k v1 v2))) r1\n\nnamespace PremiseSelection\n\ndef Multiset (α : Type) [Ord α] := Std.RBMap α Nat compare\n\nvariable {α : Type} [Ord α]\n\ndef Multiset.empty : Multiset α := mkRBMap _ _ _\n\ninstance : EmptyCollection (Multiset α) := ⟨Multiset.empty⟩\n\ninstance : Append (Multiset α) where\n append x y := x.mergeBy (fun _ => (·+·)) y\n\ndef Multiset.add : Multiset α → α → Multiset α\n | m, a => m.modify' a (fun | none => some 1 | some v => some (v + 1))\n\ndef Multiset.singleton : α → Multiset α\n | a => Multiset.empty |>.add a\n\ninstance : Ord Name := ⟨Name.quickCmp⟩\n\nstructure Bigram where\n fst : Name\n snd : Name\n deriving Ord\n\nstructure Trigram where\n fst : Name\n snd : Name\n trd : Name\n deriving Ord\n\ninstance : ToJson Bigram where\n toJson b := s!\"{b.fst}/{b.snd}\"\n\ninstance : ToString Bigram where\n toString b := s!\"{b.fst}/{b.snd}\"\n\ninstance : ToString Trigram where\n toString t := s!\"{t.fst}/{t.snd}/{t.trd}\"\n\ninstance : ToJson Trigram where\n toJson t := s!\"{t.fst}/{t.snd}/{t.trd}\"\n\nstructure StatementFeatures where\n /-- Just the constant's names and how frequently they arise. -/\n nameCounts : Multiset Name := ∅\n bigramCounts : Multiset Bigram := ∅\n trigramCounts : Multiset Trigram := ∅\n\ninstance : ForIn M (Multiset α) (α × Nat) :=\n show ForIn _ (Std.RBMap _ _ _) _ by infer_instance\n\ndef Multiset.toList (m : Multiset α) : List α :=\n m.foldl (fun l x _ => x :: l) []\n\ndef Multiset.toHFeatures [ToString α] (m : Multiset α) : Array String :=\n Array.mk <| m.toList.map (s!\"H:{·}\")\n\ndef Multiset.toTFeatures [ToString α] (m : Multiset α) : Array String :=\n Array.mk <| m.toList.map (s!\"T:{·}\")\n\ninstance [ToJson α] : ToJson (Multiset α) where\n toJson m := Json.arr (Array.mk (m.toList.map toJson))\n\ninstance : EmptyCollection StatementFeatures := ⟨{}⟩\ninstance : Append StatementFeatures where\n append x y := {\n nameCounts := x.nameCounts ++ y.nameCounts\n bigramCounts := x.bigramCounts ++ y.bigramCounts\n trigramCounts := x.trigramCounts ++ y.trigramCounts\n }\n\ninstance : ToJson StatementFeatures where\n toJson f := Json.mkObj [\n (\"nameCounts\", toJson f.nameCounts),\n (\"bigramCounts\", toJson f.bigramCounts),\n (\"trigramCounts\", toJson f.trigramCounts)\n ]\n\ndef StatementFeatures.mkName : Name → StatementFeatures\n | n => {nameCounts := Multiset.singleton n}\n\ndef StatementFeatures.mkBigram : Name → Name → StatementFeatures\n | n1, n2 => {bigramCounts := Multiset.singleton ⟨n1, n2⟩}\n\ndef StatementFeatures.mkTrigram : Name → Name → Name → StatementFeatures\n | n1, n2, n3 => {trigramCounts := Multiset.singleton ⟨n1, n2, n3⟩}\n\ndef StatementFeatures.toHFeatures (f : StatementFeatures) : Array String := \n f.nameCounts.toHFeatures ++\n f.bigramCounts.toHFeatures ++\n f.trigramCounts.toHFeatures\n\ndef StatementFeatures.toTFeatures (f : StatementFeatures) : Array String :=\n f.nameCounts.toTFeatures ++\n f.bigramCounts.toTFeatures ++\n f.trigramCounts.toTFeatures\n\ndef immediateName (e : Expr) : Option Name :=\n if let .const n _ := e then\n some n\n else if let some n := e.natLit? then\n some <| toString n\n else\n none\n\ndef getHeadName? (e : Expr) : Option Name := do\n immediateName <| e.getAppFn\n\ndef visitFeature (e : Expr) : WriterT StatementFeatures MetaM Unit := do\n --let ppe ← Lean.PrettyPrinter.ppExpr e\n if let some n := immediateName e then\n tell <| StatementFeatures.mkName n\n if e.isApp then\n e.withApp (fun f args => do\n if let some n1 := immediateName f then\n for arg in args do\n if let some n2 := getHeadName? arg then\n tell <| StatementFeatures.mkBigram n1 n2\n if arg.isApp then\n arg.withApp (fun f args => do\n if let some n2 := immediateName f then\n for arg in args do\n if let some n3 := getHeadName? arg then\n tell <| StatementFeatures.mkTrigram n1 n2 n3\n )\n for p in args.toList.allPairs do\n if let some n2 := getHeadName? p.1 then\n if let some n3 := getHeadName? p.2 then\n tell <| StatementFeatures.mkTrigram n1 n2 n3\n )\n return ()\n\ndef getStatementFeatures (e : Expr) : MetaM StatementFeatures := do\n let ((), features) ← WriterT.run <| forEachExpr visitFeature e\n return features\n\nopen Lean.Meta\n\ndef getArgsFeatures (args : List Expr) : MetaM (Array StatementFeatures) := do \n let mut argsFeats := #[]\n for arg in args do\n let argType ← inferType arg\n if (← inferType argType).isProp then\n let argFeats ← getStatementFeatures argType\n if ! argFeats.nameCounts.isEmpty then\n argsFeats := argsFeats ++ #[argFeats]\n return argsFeats\n\ndef getThmAndArgsFeatures (e : Expr) \n : MetaM (StatementFeatures × Array StatementFeatures) := do\n forallTelescope e <| fun args thm => do\n let thmFeats ← getStatementFeatures thm\n let argsFeats ← getArgsFeatures args.data\n return (thmFeats, argsFeats)\n\nend PremiseSelection\n", "meta": {"author": "BartoszPiotrowski", "repo": "lean-premise-selection", "sha": "f414bdd8f17e21b368b8ef69cbc47dd55a5cc032", "save_path": "github-repos/lean/BartoszPiotrowski-lean-premise-selection", "path": "github-repos/lean/BartoszPiotrowski-lean-premise-selection/lean-premise-selection-f414bdd8f17e21b368b8ef69cbc47dd55a5cc032/PremiseSelection/StatementFeatures.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.32423538592116924, "lm_q2_score": 0.04146227330362875, "lm_q1q2_score": 0.013443536185771059}} {"text": "/-\nCopyright (c) 2019 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Simon Hudon\n\nThe writer monad transformer for passing immutable state.\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.default\nimport Mathlib.control.monad.basic\nimport Mathlib.algebra.group.basic\nimport Mathlib.PostPort\n\nuniverses u v l u_1 u_2 u_3 u₀ u₁ v₀ v₁ \n\nnamespace Mathlib\n\nstructure writer_t (ω : Type u) (m : Type u → Type v) (α : Type u) \nwhere\n run : m (α × ω)\n\ndef writer (ω : Type u) (α : Type u) :=\n writer_t ω id\n\nnamespace writer_t\n\n\nprotected theorem ext {ω : Type u} {m : Type u → Type v} [Monad m] {α : Type u} (x : writer_t ω m α) (x' : writer_t ω m α) (h : run x = run x') : x = x' := sorry\n\nprotected def tell {ω : Type u} {m : Type u → Type v} [Monad m] (w : ω) : writer_t ω m PUnit :=\n mk (pure (PUnit.unit, w))\n\nprotected def listen {ω : Type u} {m : Type u → Type v} [Monad m] {α : Type u} : writer_t ω m α → writer_t ω m (α × ω) :=\n sorry\n\nprotected def pass {ω : Type u} {m : Type u → Type v} [Monad m] {α : Type u} : writer_t ω m (α × (ω → ω)) → writer_t ω m α :=\n sorry\n\nprotected def pure {ω : Type u} {m : Type u → Type v} [Monad m] {α : Type u} [HasOne ω] (a : α) : writer_t ω m α :=\n mk (pure (a, 1))\n\nprotected def bind {ω : Type u} {m : Type u → Type v} [Monad m] {α : Type u} {β : Type u} [Mul ω] (x : writer_t ω m α) (f : α → writer_t ω m β) : writer_t ω m β :=\n mk\n (do \n let x ← run x \n let x' ← run (f (prod.fst x))\n pure (prod.fst x', prod.snd x * prod.snd x'))\n\nprotected instance monad {ω : Type u} {m : Type u → Type v} [Monad m] [HasOne ω] [Mul ω] : Monad (writer_t ω m) := sorry\n\nprotected instance is_lawful_monad {ω : Type u} {m : Type u → Type v} [Monad m] [monoid ω] [is_lawful_monad m] : is_lawful_monad (writer_t ω m) := sorry\n\nprotected def lift {ω : Type u} {m : Type u → Type v} [Monad m] {α : Type u} [HasOne ω] (a : m α) : writer_t ω m α :=\n mk (flip Prod.mk 1 <$> a)\n\nprotected instance has_monad_lift {ω : Type u} (m : Type u → Type u_1) [Monad m] [HasOne ω] : has_monad_lift m (writer_t ω m) :=\n has_monad_lift.mk fun (α : Type u) => writer_t.lift\n\nprotected def monad_map {ω : Type u} {m : Type u → Type u_1} {m' : Type u → Type u_2} [Monad m] [Monad m'] {α : Type u} (f : {α : Type u} → m α → m' α) : writer_t ω m α → writer_t ω m' α :=\n fun (x : writer_t ω m α) => mk (f (run x))\n\nprotected instance monad_functor {ω : Type u} (m : Type u → Type u_1) (m' : Type u → Type u_1) [Monad m] [Monad m'] : monad_functor m m' (writer_t ω m) (writer_t ω m') :=\n monad_functor.mk writer_t.monad_map\n\nprotected def adapt {ω : Type u} {m : Type u → Type v} [Monad m] {ω' : Type u} {α : Type u} (f : ω → ω') : writer_t ω m α → writer_t ω' m α :=\n fun (x : writer_t ω m α) => mk (prod.map id f <$> run x)\n\nprotected instance monad_except {ω : Type u} {m : Type u → Type v} [Monad m] (ε : outParam (Type u_1)) [HasOne ω] [Monad m] [monad_except ε m] : monad_except ε (writer_t ω m) :=\n monad_except.mk (fun (α : Type u) => writer_t.lift ∘ throw)\n fun (α : Type u) (x : writer_t ω m α) (c : ε → writer_t ω m α) => mk (catch (run x) fun (e : ε) => run (c e))\n\nend writer_t\n\n\n/--\nAn implementation of [MonadReader](\nhttps://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-Reader-Class.html#t:MonadReader).\nIt does not contain `local` because this function cannot be lifted using `monad_lift`.\nInstead, the `monad_reader_adapter` class provides the more general `adapt_reader` function.\n\nNote: This class can be seen as a simplification of the more \"principled\" definition\n```\nclass monad_reader (ρ : out_param (Type u)) (n : Type u → Type u) :=\n(lift {α : Type u} : (∀ {m : Type u → Type u} [monad m], reader_t ρ m α) → n α)\n```\n-/\nclass monad_writer (ω : outParam (Type u)) (m : Type u → Type v) \nwhere\n tell : ω → m PUnit\n listen : {α : Type u} → m α → m (α × ω)\n pass : {α : Type u} → m (α × (ω → ω)) → m α\n\nprotected instance writer_t.monad_writer {ω : Type u} {m : Type u → Type v} [Monad m] : monad_writer ω (writer_t ω m) :=\n monad_writer.mk writer_t.tell (fun (α : Type u) => writer_t.listen) fun (α : Type u) => writer_t.pass\n\nprotected instance reader_t.monad_writer {ω : Type u} {ρ : Type u} {m : Type u → Type v} [Monad m] [monad_writer ω m] : monad_writer ω (reader_t ρ m) :=\n monad_writer.mk (fun (x : ω) => monad_lift (monad_writer.tell x)) (fun (α : Type u) (_x : reader_t ρ m α) => sorry)\n fun (α : Type u) (_x : reader_t ρ m (α × (ω → ω))) => sorry\n\ndef swap_right {α : Type u_1} {β : Type u_2} {γ : Type u_3} : (α × β) × γ → (α × γ) × β :=\n sorry\n\nprotected instance state_t.monad_writer {ω : Type u} {σ : Type u} {m : Type u → Type v} [Monad m] [monad_writer ω m] : monad_writer ω (state_t σ m) :=\n monad_writer.mk (fun (x : ω) => monad_lift (monad_writer.tell x)) (fun (α : Type u) (_x : state_t σ m α) => sorry)\n fun (α : Type u) (_x : state_t σ m (α × (ω → ω))) => sorry\n\ndef except_t.pass_aux {ε : Type u_1} {α : Type u_2} {ω : Type u_3} : except ε (α × (ω → ω)) → except ε α × (ω → ω) :=\n sorry\n\nprotected instance except_t.monad_writer {ω : Type u} {ε : Type u} {m : Type u → Type v} [Monad m] [monad_writer ω m] : monad_writer ω (except_t ε m) :=\n monad_writer.mk (fun (x : ω) => monad_lift (monad_writer.tell x)) (fun (α : Type u) (_x : except_t ε m α) => sorry)\n fun (α : Type u) (_x : except_t ε m (α × (ω → ω))) => sorry\n\ndef option_t.pass_aux {α : Type u_1} {ω : Type u_2} : Option (α × (ω → ω)) → Option α × (ω → ω) :=\n sorry\n\nprotected instance option_t.monad_writer {ω : Type u} {m : Type u → Type v} [Monad m] [monad_writer ω m] : monad_writer ω (option_t m) :=\n monad_writer.mk (fun (x : ω) => monad_lift (monad_writer.tell x)) (fun (α : Type u) (_x : option_t m α) => sorry)\n fun (α : Type u) (_x : option_t m (α × (ω → ω))) => sorry\n\n/-- Adapt a monad stack, changing the type of its top-most environment.\n\nThis class is comparable to\n[Control.Lens.Magnify](https://hackage.haskell.org/package/lens-4.15.4/docs/Control-Lens-Zoom.html#t:Magnify),\nbut does not use lenses (why would it), and is derived automatically for any transformer\nimplementing `monad_functor`.\n\nNote: This class can be seen as a simplification of the more \"principled\" definition\n```\nclass monad_reader_functor (ρ ρ' : out_param (Type u)) (n n' : Type u → Type u) :=\n(map {α : Type u} : (∀ {m : Type u → Type u} [monad m], reader_t ρ m α → reader_t ρ' m α) → n α → n' α)\n```\n-/\nclass monad_writer_adapter (ω : outParam (Type u)) (ω' : outParam (Type u)) (m : Type u → Type v) (m' : Type u → Type v) \nwhere\n adapt_writer : {α : Type u} → (ω → ω') → m α → m' α\n\n/-- Transitivity.\n\nThis instance generates the type-class problem with a metavariable argument (which is why this\nis marked as `[nolint dangerous_instance]`).\nCurrently that is not a problem, as there are almost no instances of `monad_functor` or\n`monad_writer_adapter`.\n\nsee Note [lower instance priority] -/\nprotected instance monad_writer_adapter_trans {ω : Type u} {ω' : Type u} {m : Type u → Type v} {m' : Type u → Type v} {n : Type u → Type v} {n' : Type u → Type v} [monad_writer_adapter ω ω' m m'] [monad_functor m m' n n'] : monad_writer_adapter ω ω' n n' :=\n monad_writer_adapter.mk fun (α : Type u) (f : ω → ω') => monad_map fun (α : Type u) => adapt_writer f\n\nprotected instance writer_t.monad_writer_adapter {ω : Type u} {ω' : Type u} {m : Type u → Type v} [Monad m] : monad_writer_adapter ω ω' (writer_t ω m) (writer_t ω' m) :=\n monad_writer_adapter.mk fun (α : Type u) => writer_t.adapt\n\nprotected instance writer_t.monad_run (ω : Type u) (m : Type u → Type (max u u_1)) (out : outParam (Type u → Type (max u u_1))) [monad_run out m] : monad_run (fun (α : Type u) => out (α × ω)) (writer_t ω m) :=\n monad_run.mk fun (α : Type u) (x : writer_t ω m α) => run (writer_t.run x)\n\n/-- reduce the equivalence between two writer monads to the equivalence between\ntheir underlying monad -/\ndef writer_t.equiv {m₁ : Type u₀ → Type v₀} {m₂ : Type u₁ → Type v₁} {α₁ : Type u₀} {ω₁ : Type u₀} {α₂ : Type u₁} {ω₂ : Type u₁} (F : m₁ (α₁ × ω₁) ≃ m₂ (α₂ × ω₂)) : writer_t ω₁ m₁ α₁ ≃ writer_t ω₂ m₂ α₂ :=\n equiv.mk (fun (_x : writer_t ω₁ m₁ α₁) => sorry) (fun (_x : writer_t ω₂ m₂ α₂) => sorry) sorry sorry\n\n", "meta": {"author": "AurelienSaue", "repo": "Mathlib4_auto", "sha": "590df64109b08190abe22358fabc3eae000943f2", "save_path": "github-repos/lean/AurelienSaue-Mathlib4_auto", "path": "github-repos/lean/AurelienSaue-Mathlib4_auto/Mathlib4_auto-590df64109b08190abe22358fabc3eae000943f2/Mathlib/control/monad/writer.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3276683008207139, "lm_q2_score": 0.040845712991009864, "lm_q1q2_score": 0.013383845371574762}} {"text": "/-\nCopyright (c) 2019 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthor: Leonardo de Moura\n-/\nprelude\nimport Init.Control.Basic\nimport Init.Data.List.Basic\n\nnamespace List\nuniverses u v w u₁ u₂\n\n/-\nRemark: we can define `mapM`, `mapM₂` and `forM` using `Applicative` instead of `Monad`.\nExample:\n```\ndef mapM {m : Type u → Type v} [Applicative m] {α : Type w} {β : Type u} (f : α → m β) : List α → m (List β)\n | [] => pure []\n | a::as => List.cons <$> (f a) <*> mapM as\n```\n\nHowever, we consider `f <$> a <*> b` an anti-idiom because the generated code\nmay produce unnecessary closure allocations.\nSuppose `m` is a `Monad`, and it uses the default implementation for `Applicative.seq`.\nThen, the compiler expands `f <$> a <*> b <*> c` into something equivalent to\n```\n(Functor.map f a >>= fun g_1 => Functor.map g_1 b) >>= fun g_2 => Functor.map g_2 c\n```\nIn an ideal world, the compiler may eliminate the temporary closures `g_1` and `g_2` after it inlines\n`Functor.map` and `Monad.bind`. However, this can easily fail. For example, suppose\n`Functor.map f a >>= fun g_1 => Functor.map g_1 b` expanded into a match-expression.\nThis is not unreasonable and can happen in many different ways, e.g., we are using a monad that\nmay throw exceptions. Then, the compiler has to decide whether it will create a join-point for\nthe continuation of the match or float it. If the compiler decides to float, then it will\nbe able to eliminate the closures, but it may not be feasible since floating match expressions\nmay produce exponential blowup in the code size.\n\nFinally, we rarely use `mapM` with something that is not a `Monad`.\n\nUsers that want to use `mapM` with `Applicative` should use `mapA` instead.\n-/\n\n@[specialize]\ndef mapM {m : Type u → Type v} [Monad m] {α : Type w} {β : Type u} (f : α → m β) : List α → m (List β)\n | [] => pure []\n | a::as => return (← f a) :: (← mapM f as)\n\n@[specialize]\ndef mapA {m : Type u → Type v} [Applicative m] {α : Type w} {β : Type u} (f : α → m β) : List α → m (List β)\n | [] => pure []\n | a::as => List.cons <$> f a <*> mapA f as\n\n@[specialize]\nprotected def forM {m : Type u → Type v} [Monad m] {α : Type w} (as : List α) (f : α → m PUnit) : m PUnit :=\n match as with\n | [] => pure ⟨⟩\n | a :: as => do f a; List.forM as f\n\n@[specialize]\ndef forA {m : Type u → Type v} [Applicative m] {α : Type w} (as : List α) (f : α → m PUnit) : m PUnit :=\n match as with\n | [] => pure ⟨⟩\n | a :: as => f a *> forA as f\n\n@[specialize]\ndef filterAuxM {m : Type → Type v} [Monad m] {α : Type} (f : α → m Bool) : List α → List α → m (List α)\n | [], acc => pure acc\n | h :: t, acc => do\n let b ← f h\n filterAuxM f t (cond b (h :: acc) acc)\n\n@[inline]\ndef filterM {m : Type → Type v} [Monad m] {α : Type} (f : α → m Bool) (as : List α) : m (List α) := do\n let as ← filterAuxM f as []\n pure as.reverse\n\n@[inline]\ndef filterRevM {m : Type → Type v} [Monad m] {α : Type} (f : α → m Bool) (as : List α) : m (List α) :=\n filterAuxM f as.reverse []\n\n@[inline]\ndef filterMapM {m : Type u → Type v} [Monad m] {α β : Type u} (f : α → m (Option β)) (as : List α) : m (List β) :=\n let rec @[specialize] loop\n | [], bs => pure bs\n | a :: as, bs => do\n match (← f a) with\n | none => loop as bs\n | some b => loop as (b::bs)\n loop as.reverse []\n\n@[specialize]\nprotected def foldlM {m : Type u → Type v} [Monad m] {s : Type u} {α : Type w} : (f : s → α → m s) → (init : s) → List α → m s\n | f, s, [] => pure s\n | f, s, a :: as => do\n let s' ← f s a\n List.foldlM f s' as\n\n@[specialize]\ndef foldrM {m : Type u → Type v} [Monad m] {s : Type u} {α : Type w} : (f : α → s → m s) → (init : s) → List α → m s\n | f, s, [] => pure s\n | f, s, a :: as => do\n let s' ← foldrM f s as\n f a s'\n\n@[specialize]\ndef firstM {m : Type u → Type v} [Monad m] [Alternative m] {α : Type w} {β : Type u} (f : α → m β) : List α → m β\n | [] => failure\n | a::as => f a <|> firstM f as\n\n@[specialize]\ndef anyM {m : Type → Type u} [Monad m] {α : Type v} (f : α → m Bool) : List α → m Bool\n | [] => pure false\n | a::as => do\n match (← f a) with\n | true => pure true\n | false => anyM f as\n\n@[specialize]\ndef allM {m : Type → Type u} [Monad m] {α : Type v} (f : α → m Bool) : List α → m Bool\n | [] => pure true\n | a::as => do\n match (← f a) with\n | true => allM f as\n | false => pure false\n\n@[specialize]\ndef findM? {m : Type → Type u} [Monad m] {α : Type} (p : α → m Bool) : List α → m (Option α)\n | [] => pure none\n | a::as => do\n match (← p a) with\n | true => pure (some a)\n | false => findM? p as\n\n@[specialize]\ndef findSomeM? {m : Type u → Type v} [Monad m] {α : Type w} {β : Type u} (f : α → m (Option β)) : List α → m (Option β)\n | [] => pure none\n | a::as => do\n match (← f a) with\n | some b => pure (some b)\n | none => findSomeM? f as\n\n@[inline] protected def forIn {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (as : List α) (init : β) (f : α → β → m (ForInStep β)) : m β :=\n let rec @[specialize] loop\n | [], b => pure b\n | a::as, b => do\n match (← f a b) with\n | ForInStep.done b => pure b\n | ForInStep.yield b => loop as b\n loop as init\n\ninstance : ForIn m (List α) α where\n forIn := List.forIn\n\n@[simp] theorem forIn_nil [Monad m] (f : α → β → m (ForInStep β)) (b : β) : forIn [] b f = pure b :=\n rfl\n\n@[simp] theorem forIn_cons [Monad m] (f : α → β → m (ForInStep β)) (a : α) (as : List α) (b : β)\n : forIn (a::as) b f = f a b >>= fun | ForInStep.done b => pure b | ForInStep.yield b => forIn as b f :=\n rfl\n\ninstance : ForM m (List α) α where\n forM := List.forM\n\n@[simp] theorem forM_nil [Monad m] (f : α → m PUnit) : forM [] f = pure ⟨⟩ :=\n rfl\n@[simp] theorem forM_cons [Monad m] (f : α → m PUnit) (a : α) (as : List α) : forM (a::as) f = f a >>= fun _ => forM as f :=\n rfl\n\nend List\n", "meta": {"author": "gebner", "repo": "lean4-old", "sha": "ee51cdfaf63ee313c914d83264f91f414a0e3b6e", "save_path": "github-repos/lean/gebner-lean4-old", "path": "github-repos/lean/gebner-lean4-old/lean4-old-ee51cdfaf63ee313c914d83264f91f414a0e3b6e/stage0/src/Init/Data/List/Control.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2538610069692489, "lm_q2_score": 0.052618951862062086, "lm_q1q2_score": 0.013357900105369516}} {"text": "import Lean\nimport Lean.Meta\nimport Lean.Elab\nimport Lean.Parser\nimport Lean.Parser.Extension\nimport LeanCodePrompts.Utils\nopen Lean Meta Elab Parser Tactic\n \n\ndef depsPrompt : IO (Array String) := do\n let file ← reroutePath <| System.mkFilePath [\"data/types.txt\"]\n IO.FS.lines file\n\ndeclare_syntax_cat typed_ident\nsyntax \"(\" ident \":\" term \")\" : typed_ident\nsyntax \"{\" ident \":\" term \"}\" : typed_ident\n\n#check Array.foldrM\n#check TSyntaxArray.rawImpl\n#check TSyntax.mk\n\ninstance : Coe (Syntax) (TSyntax n) where\n coe := TSyntax.mk\n\ninstance : Coe (Array Syntax) (Array (TSyntax n)) where\n coe := Array.map Coe.coe\n\n/-- check whether a string parses as a term -/\ndef checkTerm (s : String) : MetaM Bool := do\n let env ← getEnv\n let chk := Lean.Parser.runParserCategory env `term s\n match chk with\n | Except.ok _ => pure true\n | Except.error _ => pure false\n\n/-- split prompts into those that parse -/\ndef promptsSplit : MetaM ((Array String) × (Array String)) := do \n let deps ← depsPrompt\n let mut succ: Array String := Array.empty\n let mut fail: Array String := Array.empty\n for type in deps do\n let chk ← checkTerm type\n if chk then\n succ := succ.push type\n else\n fail := fail.push type\n return (succ, fail)\n\n\ndeclare_syntax_cat argument\nsyntax \"(\" ident+ \" : \" term \")\" : argument\nsyntax \"{\" ident+ \" : \" term \"}\" : argument\nsyntax \"[\" ident \" : \" term \"]\" : argument\nsyntax \"[\" term \"]\" : argument\n\ndeclare_syntax_cat thmStat\nsyntax argument* docComment \"theorem\" argument* \":\" term : thmStat\nsyntax \"theorem\" (ident)? argument* \":\" term : thmStat\nsyntax \"def\" ident argument* \":\" term : thmStat\nsyntax argument* \":\" term : thmStat\n\ndef thmsPrompt : IO (Array String) := do\n let file ← reroutePath <| System.mkFilePath [\"data/thms.txt\"]\n IO.FS.lines file\n\n/-- check whether a string parses as a theorem -/\ndef checkThm (s : String) : MetaM Bool := do\n let env ← getEnv\n let chk := Lean.Parser.runParserCategory env `thmStat s\n match chk with\n | Except.ok stx =>\n IO.println stx \n pure true\n | Except.error _ => pure false\n\n#check Syntax\npartial def tokens (s : Syntax) : Array String := \nmatch s with\n| .missing => Array.empty\n| .node _ _ args => args.foldl (fun acc x => acc ++ tokens x) Array.empty\n| .atom _ val => #[val]\n| .ident _ val .. => #[val.toString]\n\ndef getTokens (s: String) : MetaM <| Array String := do\n let env ← getEnv\n let chk := Lean.Parser.runParserCategory env `thmStat s\n match chk with\n | Except.ok stx =>\n pure <| tokens stx\n | Except.error _ => pure Array.empty\n\n-- #eval getTokens \"{α : Type u} [group α] [has_lt α] [covariant_class α α (function.swap has_mul.mul) has_lt.lt] {a : α} : 1 < a⁻¹ ↔ a < 1\"\n\n\n/-- split prompts into those that parse -/\ndef promptsThmSplit : MetaM ((Array String) × (Array String)) := do \n let deps ← thmsPrompt\n let mut succ: Array String := Array.empty\n let mut fail: Array String := Array.empty\n for type in deps do\n let chk ← checkThm type\n if chk then\n succ := succ.push type\n else\n fail := fail.push type\n return (succ, fail)\n\ndef promptsThmSplitCore : CoreM ((Array String) × (Array String)) :=\n promptsThmSplit.run'\n\ndef levelNames := \n [`u, `v, `u_1, `u_2, `u_3, `u_4, `u_5, `u_6, `u_7, `u_8, `u_9, `u_10, `u_11, `u₁, `u₂, `W₁, `W₂, `w₁, `w₂, `u', `v', `uu, `w, `wE]\n\npartial def idents : Syntax → List String\n| Syntax.ident _ s .. => [s.toString]\n| Syntax.node _ _ ss => ss.toList.bind idents\n| _ => []\n\ndef elabThm (s : String)(opens: List String := []) \n (levelNames : List Lean.Name := levelNames)\n : TermElabM <| Except String Expr := do\n let env ← getEnv\n let chk := Lean.Parser.runParserCategory env `thmStat s\n match chk with\n | Except.ok stx =>\n match stx with\n | `(thmStat| $_:docComment theorem $args:argument* : $type:term) =>\n elabAux type args\n | `(thmStat|theorem $_ $args:argument* : $type:term) =>\n elabAux type args\n | `(thmStat|theorem $args:argument* : $type:term) =>\n elabAux type args\n | `(thmStat|$vars:argument* $_:docComment theorem $args:argument* : $type:term ) =>\n elabAux type (vars ++ args)\n | `(thmStat|def $_ $args:argument* : $type:term) =>\n elabAux type args\n | `(thmStat|$args:argument* : $type:term) =>\n elabAux type args\n | _ => return Except.error s!\"parsed incorrectly to {stx}\"\n | Except.error e => return Except.error e\n where elabAux (type: Syntax)(args: Array Syntax) : \n TermElabM <| Except String Expr := do\n let header := if opens.isEmpty then \"\" else \n (opens.foldl (fun acc s => acc ++ \" \" ++ s) \"open \") ++ \" in \"\n let mut argS := \"\"\n for arg in args do\n argS := argS ++ (showSyntax arg) ++ \" -> \"\n let funStx := s!\"{header}{argS}{showSyntax type}\"\n match Lean.Parser.runParserCategory (← getEnv) `term funStx with\n | Except.ok termStx => Term.withLevelNames levelNames <|\n try \n let expr ← Term.withoutErrToSorry <| \n Term.elabTerm termStx none\n return Except.ok expr\n catch e => \n return Except.error s!\"{← e.toMessageData.toString} ; identifiers {idents termStx} (during elaboration)\"\n | Except.error e => \n return Except.error s!\"parsed to {funStx}; error while parsing as theorem: {e}\" \n\ndef elabThmCore (s : String)(opens: List String := []) \n (levelNames : List Lean.Name := levelNames)\n : CoreM <| Except String Expr := \n (elabThm s opens levelNames).run'.run'\n\ntheorem true_true_iff_True : true = true ↔ True := by\n apply Iff.intro\n intros\n exact True.intro\n intros\n rfl\n\n\ntheorem true_false_iff_false : false = true ↔ False := by\n apply Iff.intro \n intro hyp\n simp at hyp\n intro hyp\n contradiction\n\nsyntax \"lynx\" (\"at\" ident)? : tactic\nsyntax \"lynx\" \"at\" \"*\" : tactic\nmacro_rules \n| `(tactic| lynx) => \n `(tactic|try(repeat rw [true_true_iff_True]);try (repeat (rw [true_false_iff_false])))\n| `(tactic| lynx at $t:ident) => \n `(tactic| try(repeat rw [true_true_iff_True] at $t:ident);try (repeat (rw [true_false_iff_false] at $t:ident)))\n| `(tactic| lynx at *) => \n `(tactic|try(repeat rw [true_true_iff_True] at *);try (repeat (rw [true_false_iff_false] at *)))\n\n\ndef provedEqual (e₁ e₂ : Expr) : TermElabM Bool := do\n let type ← mkEq e₁ e₂\n let mvar ← mkFreshExprMVar <| some type\n let mvarId := mvar.mvarId!\n let stx ← `(tactic| lynx; try (rfl))\n let res ← runTactic mvarId stx\n let (remaining, _) := res\n return remaining.isEmpty\n\ndef provedEquiv (e₁ e₂ : Expr) : TermElabM Bool := do\n try\n let type ← mkAppM ``Iff #[e₁, e₂]\n let mvar ← mkFreshExprMVar <| some type\n let mvarId := mvar.mvarId!\n let stx ← `(tactic| intros; lynx at *<;> apply Iff.intro <;> intro hyp <;> (lynx at *) <;> (try assumption) <;> try (intros; apply Eq.symm; apply hyp))\n let res ← runTactic mvarId stx\n let (remaining, _) := res\n return remaining.isEmpty\n catch _ => pure false\n\n\ndef compareThms(s₁ s₂ : String)(opens: List String := []) \n (levelNames : List Lean.Name := levelNames)\n : TermElabM <| Except String Bool := do\n let e₁ ← elabThm s₁ opens levelNames\n let e₂ ← elabThm s₂ opens levelNames\n match e₁ with\n | Except.ok e₁ => match e₂ with\n | Except.ok e₂ => \n let p := (← provedEqual e₁ e₂) || \n (← provedEquiv e₁ e₂)\n return Except.ok p\n | Except.error e₂ => return Except.error e₂\n | Except.error e₁ => return Except.error e₁\n\ndef compareThmsCore(s₁ s₂ : String)(opens: List String := []) \n (levelNames : List Lean.Name := levelNames)\n : CoreM <| Except String Bool := \n (compareThms s₁ s₂ opens levelNames).run'.run'\n\ndef compareThmExps(e₁ e₂: Expr)\n : TermElabM <| Except String Bool := do\n let p := (← provedEqual e₁ e₂) || \n (← provedEquiv e₁ e₂)\n return Except.ok p\n\ndef compareThmExpsCore(e₁ e₂: Expr)\n : CoreM <| Except String Bool := do\n (compareThmExps e₁ e₂).run'.run'\n\ndef equalThms(s₁ s₂ : String)(opens: List String := []) \n (levelNames : List Lean.Name := levelNames)\n : TermElabM Bool := do\n match ← compareThms s₁ s₂ opens levelNames with\n | Except.ok p => return p\n | Except.error _ => return false\n\ndef groupThms(ss: Array String)(opens: List String := []) \n (levelNames : List Lean.Name := levelNames)\n : TermElabM (Array (Array String)) := do\n let mut groups: Array (Array String) := Array.empty\n for s in ss do\n match ← groups.findIdxM? (fun g => \n equalThms s g[0]! opens levelNames) with\n |none => \n groups := groups.push #[s]\n | some j => \n groups := groups.set! j (groups[j]!.push s)\n return groups\n\ndef groupTheoremsCore(ss: Array String)(opens: List String := []) \n (levelNames : List Lean.Name := levelNames)\n : CoreM (Array (Array String)) := \n (groupThms ss opens levelNames).run'.run'\n\ndef groupThmsSort(ss: Array String)(opens: List String := []) \n (levelNames : List Lean.Name := levelNames)\n : TermElabM (Array (Array String)) := do\n let gps ← groupThms ss opens levelNames\n return gps.qsort (fun xs ys => xs.size > ys.size)\n\ndef groupThmsSortCore(ss: Array String)(opens: List String := []) \n (levelNames : List Lean.Name := levelNames)\n : CoreM (Array (Array String)) := \n (groupThmsSort ss opens levelNames).run'.run'\n\n-- Tests\n\n-- #eval checkTerm \"(fun x : Nat => x + 1)\"\n\n-- #eval checkTerm \"a • s\"\n\n-- #eval checkTerm \"λ x : Nat, x + 1\"\n\n-- #eval checkTerm \"a - t = 0\"\n\n\ndef checkStatements : MetaM (List (String × Bool)) := do\n let prompts ← depsPrompt\n (prompts.toList.take 50).mapM fun s => \n do return (s, ← checkTerm s)\n\ndef tryParseThm (s : String) : MetaM String := do\n let env ← getEnv\n let chk := Lean.Parser.runParserCategory env `thmStat s\n match chk with\n | Except.ok stx =>\n match stx with\n | `(thmStat|theorem $_ $args:argument* : $type:term) =>\n let mut argS := \"\"\n for arg in args do\n argS := argS ++ (showSyntax arg) ++ \" -> \"\n let funStx := s!\"{argS}{showSyntax type}\"\n pure s!\"match: {funStx}\"\n | `(thmStat|$args:argument* : $type:term) =>\n let mut argS := \"\"\n for arg in args do\n argS := argS ++ (showSyntax arg) ++ \" -> \"\n let funStx := s!\"{argS}{showSyntax type}\"\n pure s!\"match: {funStx}\"\n | _ => pure s!\"parsed to mysterious {stx}\"\n | Except.error e => pure s!\"error: {e}\"\n\n-- #eval tryParseThm \"theorem blah (n : Nat) {m: Type} : n = n\"\n\n-- #eval elabThm \"(p: Nat)/-- blah test -/ theorem (n : Nat) {m: Type} : n = p\"\n\ndef eg :=\n\"section \nvariable (α : Type) {n : Nat}\n/-- A doc that should be ignored -/\ntheorem blah (m: Nat) : n = m \"\n\n-- #eval checkThm eg\n\n-- #eval checkThm \"(n : Nat) {m: Type} : n = n\"\n\n-- #eval tryParseThm \"theorem subfield.list_sum_mem {K : Type u} [field K] (s : subfield K) {l : list K} : (∀ (x : K), x ∈ l → x ∈ s) → l.sum ∈ s\"\n\ndef checkElabThm (s : String) : TermElabM String := do\n let env ← getEnv\n let chk := Lean.Parser.runParserCategory env `thmStat s\n match chk with\n | Except.ok stx =>\n match stx with\n | `(thmStat|theorem $_ $args:argument* : $type:term) =>\n let mut argS := \"\"\n for arg in args do\n argS := argS ++ (showSyntax arg) ++ \" -> \"\n let funStx := s!\"{argS}{showSyntax type}\"\n match Lean.Parser.runParserCategory env `term funStx with\n | Except.ok termStx => Term.withLevelNames levelNames <|\n try \n let expr ← Term.withoutErrToSorry <| \n Term.elabTerm termStx none\n pure s!\"elaborated: {← expr.view} from {funStx}\"\n catch e => \n pure s!\"{← e.toMessageData.toString} during elaboration\"\n | Except.error e => \n pure s!\"parsed to {funStx}; error while parsing: {e}\"\n | `(thmStat|$vars:argument* $_:docComment theorem $args:argument* : $type:term ) =>\n let mut argS := \"\"\n for arg in vars ++ args do\n argS := argS ++ (showSyntax arg) ++ \" -> \"\n let funStx := s!\"{argS}{showSyntax type}\"\n match Lean.Parser.runParserCategory env `term funStx with\n | Except.ok termStx => Term.withLevelNames levelNames <|\n try \n let expr ← Term.withoutErrToSorry <| \n Term.elabTerm termStx none\n pure s!\"elaborated: {← expr.view} from {funStx}\"\n catch e => \n pure s!\"{← e.toMessageData.toString} during elaboration\"\n | Except.error e => \n pure s!\"parsed to {funStx}; error while parsing: {e}\"\n | `(thmStat|$args:argument* : $type:term) =>\n let mut argS := \"\"\n for arg in args do\n argS := argS ++ (showSyntax arg) ++ \" -> \"\n let funStx := s!\"{argS}{showSyntax type}\"\n match Lean.Parser.runParserCategory env `term funStx with\n | Except.ok termStx => Term.withLevelNames levelNames <|\n try \n let expr ← Term.withoutErrToSorry <| \n Term.elabTerm termStx none\n pure s!\"elaborated: {← expr.view} from {funStx}\"\n catch e => \n pure s!\"{← e.toMessageData.toString} during elaboration\"\n | Except.error e => \n pure s!\"parsed to {funStx}; error while parsing: {e}\"\n | _ => pure s!\"parsed to mysterious {stx}\"\n | Except.error e => pure s!\"error: {e}\"\n\n-- #eval checkElabThm \"theorem blah (n : Nat) {m : Nat} : n = m\"\n\n-- #eval checkElabThm eg\n\n-- #eval checkElabThm \"theorem subfield.list_sum_mem {K : Type u} [field K] (s : subfield K) {l : list K} : (∀ (x : K), x ∈ l → x ∈ s) → l.sum ∈ s\"\n\n-- #eval elabThm \"theorem blah (n : Nat) {m : Nat} : n = m\" \n\n-- #eval elabThm \"theorem (n : Nat) {m : Nat} : n = m\"\n\n-- #eval elabThm \"theorem blah (n : Nat) {m : Nat} : n = succ n\" [\"Nat\"]\n\n-- #eval elabThm \"theorem blah (n : Nat) {m : Nat} : n = succ n\" [\"Nat\"]\n\n-- #eval elabThm \"(n : Nat) {m : Nat} : n = succ n\" [\"Nat\"]\n\n-- #eval elabThmCore \"(n : Nat) {m : Nat} : n = succ n\" [\"Nat\"]\n\n-- #eval elabThm \"theorem subfield.list_sum_mem {K : Type u} [field K] (s : subfield K) {l : list K} : (∀ (x : K), x ∈ l → x ∈ s) → l.sum ∈ s\"\n\n-- #eval compareThms \"theorem nonsense(n : Nat) (m : Nat) : n = m\" \"(p : Nat)(q: Nat) : p = q\"\n\n-- #eval compareThms \": True\" \": true = true\"\n\n-- #eval compareThms \"{A: Type} : A → True\" \"{A: Type}: A → true\"\n\n-- #eval compareThms \": False\" \": false = true\"\n\n-- #eval compareThms \"{A: Sort} : False → A\" \"{A: Sort} : false = true → A\"\n\nexample : (∀ {A: Sort}, False → A) ↔ (∀ {A: Sort}, false = true → A) := by\n intros; lynx at *<;> apply Iff.intro <;> intro hyp <;> (lynx at *) <;> (try assumption) <;> try (intros; apply Eq.symm; apply hyp)\n\n\nexample : (∀ (a b c: Nat), \n a + (b + c) = (a + b) + c) ↔ (∀ (a b c: Nat), (a + b) + c = a + (b + c)) := by \n intros; apply Iff.intro <;> intro hyp <;> (try assumption) <;> try (intros; apply Eq.symm; apply hyp)\n \n-- #eval compareThms \"(a b c: Nat): a + (b + c) = (a + b) + c\" \"(a b c: Nat): (a + b) + c = a + (b + c)\"\n", "meta": {"author": "siddhartha-gadgil", "repo": "LeanAide", "sha": "7862af73ee2f0be08b20fd3e4148e20bf4a81054", "save_path": "github-repos/lean/siddhartha-gadgil-LeanAide", "path": "github-repos/lean/siddhartha-gadgil-LeanAide/LeanAide-7862af73ee2f0be08b20fd3e4148e20bf4a81054/LeanCodePrompts/CheckParse.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.36658973632215985, "lm_q2_score": 0.03622005846583568, "lm_q1q2_score": 0.013277901682563917}} {"text": "/-\nCopyright (c) 2019 Simon Hudon. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Simon Hudon\n-/\nimport control.traversable.derive\nimport control.traversable.lemmas\nimport data.dlist\nimport tactic.monotonicity.basic\n\nvariables {a b c p : Prop}\n\nnamespace tactic.interactive\n\nopen lean lean.parser interactive\nopen interactive.types\nopen tactic\n\nlocal postfix `?`:9001 := optional\nlocal postfix *:9001 := many\n\nmeta inductive mono_function (elab : bool := tt)\n | non_assoc : expr elab → list (expr elab) → list (expr elab) → mono_function\n | assoc : expr elab → option (expr elab) → option (expr elab) → mono_function\n | assoc_comm : expr elab → expr elab → mono_function\n\nmeta instance : decidable_eq mono_function :=\nby mk_dec_eq_instance\n\nmeta def mono_function.to_tactic_format : mono_function → tactic format\n | (mono_function.non_assoc fn xs ys) := do\n fn' ← pp fn,\n xs' ← mmap pp xs,\n ys' ← mmap pp ys,\n return format!\"{fn'} {xs'} _ {ys'}\"\n | (mono_function.assoc fn xs ys) := do\n fn' ← pp fn,\n xs' ← pp xs,\n ys' ← pp ys,\n return format!\"{fn'} {xs'} _ {ys'}\"\n | (mono_function.assoc_comm fn xs) := do\n fn' ← pp fn,\n xs' ← pp xs,\n return format!\"{fn'} _ {xs'}\"\n\nmeta instance has_to_tactic_format_mono_function : has_to_tactic_format mono_function :=\n{ to_tactic_format := mono_function.to_tactic_format }\n\n@[derive traversable]\nmeta structure ac_mono_ctx' (rel : Type) :=\n (to_rel : rel)\n (function : mono_function)\n (left right rel_def : expr)\n\n@[reducible]\nmeta def ac_mono_ctx := ac_mono_ctx' (option (expr → expr → expr))\n@[reducible]\nmeta def ac_mono_ctx_ne := ac_mono_ctx' (expr → expr → expr)\n\nmeta def ac_mono_ctx.to_tactic_format (ctx : ac_mono_ctx) : tactic format :=\ndo fn ← pp ctx.function,\n l ← pp ctx.left,\n r ← pp ctx.right,\n rel ← pp ctx.rel_def,\n return format!\"{{ function := {fn}\\n, left := {l}\\n, right := {r}\\n, rel_def := {rel} }}\"\n\nmeta instance has_to_tactic_format_mono_ctx : has_to_tactic_format ac_mono_ctx :=\n{ to_tactic_format := ac_mono_ctx.to_tactic_format }\n\nmeta def as_goal (e : expr) (tac : tactic unit) : tactic unit :=\ndo gs ← get_goals,\n set_goals [e],\n tac,\n set_goals gs\n\nopen list (hiding map) functor dlist\n\nsection config\n\nparameter opt : mono_cfg\nparameter asms : list expr\n\nmeta def unify_with_instance (e : expr) : tactic unit :=\nas_goal e $\napply_instance\n<|>\napply_opt_param\n<|>\napply_auto_param\n<|>\ntactic.solve_by_elim { lemmas := some asms }\n<|>\nreflexivity\n<|>\napplyc ``id\n<|>\nreturn ()\n\nprivate meta def match_rule_head (p : expr)\n: list expr → expr → expr → tactic expr\n | vs e t :=\n(unify t p >> mmap' unify_with_instance vs >> instantiate_mvars e)\n<|>\ndo (expr.pi _ _ d b) ← return t | failed,\n v ← mk_meta_var d,\n match_rule_head (v::vs) (expr.app e v) (b.instantiate_var v)\n\nmeta def pi_head : expr → tactic expr\n| (expr.pi n _ t b) :=\ndo v ← mk_meta_var t,\n pi_head (b.instantiate_var v)\n| e := return e\n\nmeta def delete_expr (e : expr)\n: list expr → tactic (option (list expr))\n | [] := return none\n | (x :: xs) :=\n(compare opt e x >> return (some xs))\n<|>\n(map (cons x) <$> delete_expr xs)\n\nmeta def match_ac'\n: list expr → list expr → tactic (list expr × list expr × list expr)\n | es (x :: xs) := do\n es' ← delete_expr x es,\n match es' with\n | (some es') := do\n (c,l,r) ← match_ac' es' xs, return (x::c,l,r)\n | none := do\n (c,l,r) ← match_ac' es xs, return (c,l,x::r)\n end\n | es [] := do\nreturn ([],es,[])\n\nmeta def match_ac (l : list expr) (r : list expr)\n: tactic (list expr × list expr × list expr) :=\ndo (s',l',r') ← match_ac' l r,\n s' ← mmap instantiate_mvars s',\n l' ← mmap instantiate_mvars l',\n r' ← mmap instantiate_mvars r',\n return (s',l',r')\n\nmeta def match_prefix\n: list expr → list expr → tactic (list expr × list expr × list expr)\n| (x :: xs) (y :: ys) :=\n (do compare opt x y,\n prod.map ((::) x) id <$> match_prefix xs ys)\n<|> return ([],x :: xs,y :: ys)\n| xs ys := return ([],xs,ys)\n\n/--\n`(prefix,left,right,suffix) ← match_assoc unif l r` finds the\nlongest prefix and suffix common to `l` and `r` and\nreturns them along with the differences -/\nmeta def match_assoc (l : list expr) (r : list expr)\n: tactic (list expr × list expr × list expr × list expr) :=\ndo (pre,l₁,r₁) ← match_prefix l r,\n (suf,l₂,r₂) ← match_prefix (reverse l₁) (reverse r₁),\n return (pre,reverse l₂,reverse r₂,reverse suf)\n\nmeta def check_ac : expr → tactic (bool × bool × option (expr × expr × expr) × expr)\n | (expr.app (expr.app f x) y) :=\n do t ← infer_type x,\n a ← try_core $ to_expr ``(is_associative %%t %%f) >>= mk_instance,\n c ← try_core $ to_expr ``(is_commutative %%t %%f) >>= mk_instance,\n i ← try_core (do\n v ← mk_meta_var t,\n l_inst_p ← to_expr ``(is_left_id %%t %%f %%v),\n r_inst_p ← to_expr ``(is_right_id %%t %%f %%v),\n l_v ← mk_meta_var l_inst_p,\n r_v ← mk_meta_var r_inst_p ,\n l_id ← mk_mapp `is_left_id.left_id [some t,f,v,some l_v],\n mk_instance l_inst_p >>= unify l_v,\n r_id ← mk_mapp `is_right_id.right_id [none,f,v,some r_v],\n mk_instance r_inst_p >>= unify r_v,\n v' ← instantiate_mvars v,\n return (l_id,r_id,v')),\n return (a.is_some,c.is_some,i,f)\n | _ := return (ff,ff,none,expr.var 1)\n\nmeta def parse_assoc_chain' (f : expr) : expr → tactic (dlist expr)\n | e :=\n (do (expr.app (expr.app f' x) y) ← return e,\n is_def_eq f f',\n (++) <$> parse_assoc_chain' x <*> parse_assoc_chain' y)\n<|> return (singleton e)\n\nmeta def parse_assoc_chain (f : expr) : expr → tactic (list expr) :=\nmap dlist.to_list ∘ parse_assoc_chain' f\n\nmeta def fold_assoc (op : expr) :\n option (expr × expr × expr) → list expr → option (expr × list expr)\n| _ (x::xs) := some (foldl (expr.app ∘ expr.app op) x xs, [])\n| none [] := none\n| (some (l_id,r_id,x₀)) [] := some (x₀,[l_id,r_id])\n\nmeta def fold_assoc1 (op : expr) : list expr → option expr\n| (x::xs) := some $ foldl (expr.app ∘ expr.app op) x xs\n| [] := none\n\nmeta def same_function_aux\n: list expr → list expr → expr → expr → tactic (expr × list expr × list expr)\n | xs₀ xs₁ (expr.app f₀ a₀) (expr.app f₁ a₁) :=\n same_function_aux (a₀ :: xs₀) (a₁ :: xs₁) f₀ f₁\n | xs₀ xs₁ e₀ e₁ := is_def_eq e₀ e₁ >> return (e₀,xs₀,xs₁)\n\nmeta def same_function : expr → expr → tactic (expr × list expr × list expr) :=\nsame_function_aux [] []\n\nmeta def parse_ac_mono_function (l r : expr)\n: tactic (expr × expr × list expr × mono_function) :=\ndo (full_f,ls,rs) ← same_function l r,\n (a,c,i,f) ← check_ac l,\n if a\n then if c\n then do\n (s,ls,rs) ← monad.join (match_ac\n <$> parse_assoc_chain f l\n <*> parse_assoc_chain f r),\n (l',l_id) ← fold_assoc f i ls,\n (r',r_id) ← fold_assoc f i rs,\n s' ← fold_assoc1 f s,\n return (l',r',l_id ++ r_id,mono_function.assoc_comm f s')\n else do -- a ∧ ¬ c\n (pre,ls,rs,suff) ← monad.join (match_assoc\n <$> parse_assoc_chain f l\n <*> parse_assoc_chain f r),\n (l',l_id) ← fold_assoc f i ls,\n (r',r_id) ← fold_assoc f i rs,\n let pre' := fold_assoc1 f pre,\n let suff' := fold_assoc1 f suff,\n return (l',r',l_id ++ r_id,mono_function.assoc f pre' suff')\n else do -- ¬ a\n (xs₀,x₀,x₁,xs₁) ← find_one_difference opt ls rs,\n return (x₀,x₁,[],mono_function.non_assoc full_f xs₀ xs₁)\n\nmeta def parse_ac_mono_function' (l r : pexpr) :=\ndo l' ← to_expr l,\n r' ← to_expr r,\n parse_ac_mono_function l' r'\n\nmeta def ac_monotonicity_goal : expr → tactic (expr × expr × list expr × ac_mono_ctx)\n | `(%%e₀ → %%e₁) :=\n do (l,r,id_rs,f) ← parse_ac_mono_function e₀ e₁,\n t₀ ← infer_type e₀,\n t₁ ← infer_type e₁,\n rel_def ← to_expr ``(λ x₀ x₁, (x₀ : %%t₀) → (x₁ : %%t₁)),\n return (e₀, e₁, id_rs,\n { function := f\n , left := l, right := r\n , to_rel := some $ expr.pi `x binder_info.default\n , rel_def := rel_def })\n | `(%%e₀ = %%e₁) :=\n do (l,r,id_rs,f) ← parse_ac_mono_function e₀ e₁,\n t₀ ← infer_type e₀,\n t₁ ← infer_type e₁,\n rel_def ← to_expr ``(λ x₀ x₁, (x₀ : %%t₀) = (x₁ : %%t₁)),\n return (e₀, e₁, id_rs,\n { function := f\n , left := l, right := r\n , to_rel := none\n , rel_def := rel_def })\n | (expr.app (expr.app rel e₀) e₁) :=\n do (l,r,id_rs,f) ← parse_ac_mono_function e₀ e₁,\n return (e₀, e₁, id_rs,\n { function := f\n , left := l, right := r\n , to_rel := expr.app ∘ expr.app rel\n , rel_def := rel })\n | _ := fail \"invalid monotonicity goal\"\n\nmeta def bin_op_left (f : expr) : option expr → expr → expr\n| none e := e\n| (some e₀) e₁ := f.mk_app [e₀,e₁]\n\nmeta def bin_op (f a b : expr) : expr :=\nf.mk_app [a,b]\n\nmeta def bin_op_right (f : expr) : expr → option expr → expr\n| e none := e\n| e₀ (some e₁) := f.mk_app [e₀,e₁]\n\nmeta def mk_fun_app : mono_function → expr → expr\n | (mono_function.non_assoc f x y) z := f.mk_app (x ++ z :: y)\n | (mono_function.assoc f x y) z := bin_op_left f x (bin_op_right f z y)\n | (mono_function.assoc_comm f x) z := f.mk_app [z,x]\n\nmeta inductive mono_law\n /- `assoc (l₀,r₀) (r₁,l₁)` gives first how to find rules to prove\n x+(y₀+z) R x+(y₁+z);\n if that fails, helps prove (x+y₀)+z R (x+y₁)+z -/\n | assoc : expr × expr → expr × expr → mono_law\n /- `congr r` gives the rule to prove `x = y → f x = f y` -/\n | congr : expr → mono_law\n | other : expr → mono_law\n\nmeta def mono_law.to_tactic_format : mono_law → tactic format\n | (mono_law.other e) := do e ← pp e, return format!\"other {e}\"\n | (mono_law.congr r) := do e ← pp r, return format!\"congr {e}\"\n | (mono_law.assoc (x₀,x₁) (y₀,y₁)) :=\ndo x₀ ← pp x₀,\n x₁ ← pp x₁,\n y₀ ← pp y₀,\n y₁ ← pp y₁,\n return format!\"assoc {x₀}; {x₁} | {y₀}; {y₁}\"\n\nmeta instance has_to_tactic_format_mono_law : has_to_tactic_format mono_law :=\n{ to_tactic_format := mono_law.to_tactic_format }\n\nmeta def mk_rel (ctx : ac_mono_ctx_ne) (f : expr → expr) : expr :=\nctx.to_rel (f ctx.left) (f ctx.right)\n\nmeta def mk_congr_args (fn : expr) (xs₀ xs₁ : list expr) (l r : expr) : tactic expr :=\ndo p ← mk_app `eq [fn.mk_app $ xs₀ ++ l :: xs₁,fn.mk_app $ xs₀ ++ r :: xs₁],\n prod.snd <$> solve_aux p\n (do iterate_exactly (xs₁.length) (applyc `congr_fun),\n applyc `congr_arg)\n\nmeta def mk_congr_law (ctx : ac_mono_ctx) : tactic expr :=\nmatch ctx.function with\n | (mono_function.assoc f x₀ x₁) :=\n if (x₀ <|> x₁).is_some\n then mk_congr_args f x₀.to_monad x₁.to_monad ctx.left ctx.right\n else failed\n | (mono_function.assoc_comm f x₀) := mk_congr_args f [x₀] [] ctx.left ctx.right\n | (mono_function.non_assoc f x₀ x₁) := mk_congr_args f x₀ x₁ ctx.left ctx.right\nend\n\nmeta def mk_pattern (ctx : ac_mono_ctx) : tactic mono_law :=\nmatch (sequence ctx : option (ac_mono_ctx' _)) with\n | (some ctx) :=\n match ctx.function with\n | (mono_function.assoc f (some x) (some y)) :=\n return $ mono_law.assoc\n ( mk_rel ctx (λ i, bin_op f x (bin_op f i y))\n , mk_rel ctx (λ i, bin_op f i y))\n ( mk_rel ctx (λ i, bin_op f (bin_op f x i) y)\n , mk_rel ctx (λ i, bin_op f x i))\n | (mono_function.assoc f (some x) none) :=\n return $ mono_law.other $\n mk_rel ctx (λ e, mk_fun_app ctx.function e)\n | (mono_function.assoc f none (some y)) :=\n return $ mono_law.other $\n mk_rel ctx (λ e, mk_fun_app ctx.function e)\n | (mono_function.assoc f none none) :=\n none\n | _ :=\n return $ mono_law.other $\n mk_rel ctx (λ e, mk_fun_app ctx.function e)\n end\n | none := mono_law.congr <$> mk_congr_law ctx\nend\n\nmeta def match_rule (pat : expr) (r : name) : tactic expr :=\ndo r' ← mk_const r,\n t ← infer_type r',\n t ← expr.dsimp t { fail_if_unchanged := ff } tt [] [\n simp_arg_type.expr ``(monotone), simp_arg_type.expr ``(strict_mono)],\n match_rule_head pat [] r' t\n\nmeta def find_lemma (pat : expr) : list name → tactic (list expr)\n | [] := return []\n | (r :: rs) :=\n do (cons <$> match_rule pat r <|> pure id) <*> find_lemma rs\n\nmeta def match_chaining_rules (ls : list name) (x₀ x₁ : expr) : tactic (list expr) :=\ndo x' ← to_expr ``(%%x₁ → %%x₀),\n r₀ ← find_lemma x' ls,\n r₁ ← find_lemma x₁ ls,\n return (expr.app <$> r₀ <*> r₁)\n\nmeta def find_rule (ls : list name) : mono_law → tactic (list expr)\n | (mono_law.assoc (x₀,x₁) (y₀,y₁)) :=\n(match_chaining_rules ls x₀ x₁)\n<|> (match_chaining_rules ls y₀ y₁)\n | (mono_law.congr r) := return [r]\n | (mono_law.other p) := find_lemma p ls\n\nuniverses u v\n\ndef apply_rel {α : Sort u} (R : α → α → Sort v) {x y : α}\n (x' y' : α)\n (h : R x y)\n (hx : x = x')\n (hy : y = y')\n: R x' y' :=\nby { rw [← hx,← hy], apply h }\n\nmeta def ac_refine (e : expr) : tactic unit :=\nrefine ``(eq.mp _ %%e) ; ac_refl\n\nmeta def one_line (e : expr) : tactic format :=\ndo lbl ← pp e,\n asm ← infer_type e >>= pp,\n return format!\"\\t{asm}\\n\"\n\nmeta def side_conditions (e : expr) : tactic format :=\ndo let vs := e.list_meta_vars,\n ts ← mmap one_line vs.tail,\n let r := e.get_app_fn.const_name,\n return format!\"{r}:\\n{format.join ts}\"\n\nopen monad\n\n/-- tactic-facing function, similar to `interactive.tactic.generalize` with the\nexception that meta variables -/\nprivate meta def monotonicity.generalize' (h : name) (v : expr) (x : name) : tactic (expr × expr) :=\ndo tgt ← target,\n t ← infer_type v,\n tgt' ← do\n { ⟨tgt', _⟩ ← solve_aux tgt (tactic.generalize v x >> target),\n to_expr ``(λ y : %%t, Π x, y = x → %%(tgt'.binding_body.lift_vars 0 1)) }\n <|> to_expr ``(λ y : %%t, Π x, %%v = x → %%tgt),\n t ← head_beta (tgt' v) >>= assert h,\n swap,\n r ← mk_eq_refl v,\n solve1 $ tactic.exact (t v r),\n prod.mk <$> tactic.intro x <*> tactic.intro h\n\nprivate meta def hide_meta_vars (tac : list expr → tactic unit) : tactic unit :=\nfocus1 $\ndo tgt ← target >>= instantiate_mvars,\n tactic.change tgt,\n ctx ← local_context,\n let vs := tgt.list_meta_vars,\n vs' ← mmap (λ v,\n do h ← get_unused_name `h,\n x ← get_unused_name `x,\n prod.snd <$> monotonicity.generalize' h v x) vs,\n tac ctx;\n vs'.mmap' (try ∘ tactic.subst)\n\nmeta def hide_meta_vars' (tac : itactic) : itactic :=\nhide_meta_vars $ λ _, tac\n\nend config\n\nmeta def solve_mvar (v : expr) (tac : tactic unit) : tactic unit :=\ndo gs ← get_goals,\n set_goals [v],\n target >>= instantiate_mvars >>= tactic.change,\n tac, done,\n set_goals $ gs\n\ndef list.minimum_on {α β} [linear_order β] (f : α → β) : list α → list α\n| [] := []\n| (x :: xs) := prod.snd $ xs.foldl (λ ⟨k,a⟩ b,\n let k' := f b in\n if k < k' then (k,a)\n else if k' < k then (k', [b])\n else (k,b :: a)) (f x, [x])\n\nopen format mono_selection\n\nmeta def best_match {β} (xs : list expr) (tac : expr → tactic β) : tactic unit :=\ndo t ← target,\n xs ← xs.mmap (λ x,\n try_core $ prod.mk x <$> solve_aux t (tac x >> get_goals)),\n let xs := xs.filter_map id,\n let r := list.minimum_on (list.length ∘ prod.fst ∘ prod.snd) xs,\n match r with\n | [(_,gs,pr)] := tactic.exact pr >> set_goals gs\n | [] := fail \"no good match found\"\n | _ :=\n do lmms ← r.mmap (λ ⟨l,gs,_⟩,\n do ts ← gs.mmap infer_type,\n msg ← ts.mmap pp,\n pure $ foldl compose \"\\n\\n\" $\n list.intersperse \"\\n\" $ to_fmt l.get_app_fn.const_name :: msg),\n let msg := foldl compose \"\" lmms,\n fail format!(\"ambiguous match: {msg}\\n\\n\" ++\n \"Tip: try asserting a side condition to distinguish between the lemmas\")\n end\n\nmeta def mono_aux (dir : parse side) :\n tactic unit :=\ndo t ← target >>= instantiate_mvars,\n ns ← get_monotonicity_lemmas t dir,\n asms ← local_context,\n rs ← find_lemma asms t ns,\n focus1 $ () <$ best_match rs (λ law, tactic.refine $ to_pexpr law)\n\n/--\n- `mono` applies a monotonicity rule.\n- `mono*` applies monotonicity rules repetitively.\n- `mono with x ≤ y` or `mono with [0 ≤ x,0 ≤ y]` creates an assertion for the listed\n propositions. Those help to select the right monotonicity rule.\n- `mono left` or `mono right` is useful when proving strict orderings:\n for `x + y < w + z` could be broken down into either\n - left: `x ≤ w` and `y < z` or\n - right: `x < w` and `y ≤ z`\n- `mono using [rule1,rule2]` calls `simp [rule1,rule2]` before applying mono.\n- The general syntax is\n `mono '*'? ('with' hyp | 'with' [hyp1,hyp2])? ('using' [hyp1,hyp2])? mono_cfg?`\n\nTo use it, first import `tactic.monotonicity`.\n\nHere is an example of mono:\n\n```lean\nexample (x y z k : ℤ)\n (h : 3 ≤ (4 : ℤ))\n (h' : z ≤ y) :\n (k + 3 + x) - y ≤ (k + 4 + x) - z :=\nbegin\n mono, -- unfold `(-)`, apply add_le_add\n { -- ⊢ k + 3 + x ≤ k + 4 + x\n mono, -- apply add_le_add, refl\n -- ⊢ k + 3 ≤ k + 4\n mono },\n { -- ⊢ -y ≤ -z\n mono /- apply neg_le_neg -/ }\nend\n```\n\nMore succinctly, we can prove the same goal as:\n\n```lean\nexample (x y z k : ℤ)\n (h : 3 ≤ (4 : ℤ))\n (h' : z ≤ y) :\n (k + 3 + x) - y ≤ (k + 4 + x) - z :=\nby mono*\n```\n\n-/\nmeta def mono (many : parse (tk \"*\")?)\n (dir : parse side)\n (hyps : parse $ tk \"with\" *> pexpr_list_or_texpr <|> pure [])\n (simp_rules : parse $ tk \"using\" *> simp_arg_list <|> pure []) :\n tactic unit :=\ndo hyps ← hyps.mmap (λ p, to_expr p >>= mk_meta_var),\n hyps.mmap' (λ pr, do h ← get_unused_name `h, note h none pr),\n when (¬ simp_rules.empty) (simp_core { } failed tt simp_rules [] (loc.ns [none]) >> skip),\n if many.is_some\n then repeat $ mono_aux dir\n else mono_aux dir,\n gs ← get_goals,\n set_goals $ hyps ++ gs\n\nadd_tactic_doc\n{ name := \"mono\",\n category := doc_category.tactic,\n decl_names := [`tactic.interactive.mono],\n tags := [\"monotonicity\"] }\n\n/--\ntransforms a goal of the form `f x ≼ f y` into `x ≤ y` using lemmas\nmarked as `monotonic`.\n\nSpecial care is taken when `f` is the repeated application of an\nassociative operator and if the operator is commutative\n-/\nmeta def ac_mono_aux (cfg : mono_cfg := { mono_cfg . }) :\n tactic unit :=\nhide_meta_vars $ λ asms,\ndo try `[simp only [sub_eq_add_neg]],\n tgt ← target >>= instantiate_mvars,\n (l,r,id_rs,g) ← ac_monotonicity_goal cfg tgt\n <|> fail \"monotonic context not found\",\n ns ← get_monotonicity_lemmas tgt both,\n p ← mk_pattern g,\n rules ← find_rule asms ns p <|> fail \"no applicable rules found\",\n when (rules = []) (fail \"no applicable rules found\"),\n err ← format.join <$> mmap side_conditions rules,\n focus1 $ best_match rules (λ rule, do\n t₀ ← mk_meta_var `(Prop),\n v₀ ← mk_meta_var t₀,\n t₁ ← mk_meta_var `(Prop),\n v₁ ← mk_meta_var t₁,\n tactic.refine $ ``(apply_rel %%(g.rel_def) %%l %%r %%rule %%v₀ %%v₁),\n solve_mvar v₀ (try (any_of id_rs rewrite_target) >>\n ( done <|>\n refl <|>\n ac_refl <|>\n `[simp only [is_associative.assoc]]) ),\n solve_mvar v₁ (try (any_of id_rs rewrite_target) >>\n ( done <|>\n refl <|>\n ac_refl <|>\n `[simp only [is_associative.assoc]]) ),\n n ← num_goals,\n iterate_exactly (n-1) (try $ solve1 $ apply_instance <|>\n tactic.solve_by_elim { lemmas := some asms }))\n\nopen sum nat\n\n/-- (repeat_until_or_at_most n t u): repeat tactic `t` at most n times or until u succeeds -/\nmeta def repeat_until_or_at_most : nat → tactic unit → tactic unit → tactic unit\n| 0 t _ := fail \"too many applications\"\n| (succ n) t u := u <|> (t >> repeat_until_or_at_most n t u)\n\nmeta def repeat_until : tactic unit → tactic unit → tactic unit :=\nrepeat_until_or_at_most 100000\n\n@[derive _root_.has_reflect, derive _root_.inhabited]\ninductive rep_arity : Type\n| one | exactly (n : ℕ) | many\n\nmeta def repeat_or_not : rep_arity → tactic unit → option (tactic unit) → tactic unit\n | rep_arity.one tac none := tac\n | rep_arity.many tac none := repeat tac\n | (rep_arity.exactly n) tac none := iterate_exactly' n tac\n | rep_arity.one tac (some until) := tac >> until\n | rep_arity.many tac (some until) := repeat_until tac until\n | (rep_arity.exactly n) tac (some until) := iterate_exactly n tac >> until\n\nmeta def assert_or_rule : lean.parser (pexpr ⊕ pexpr) :=\n(tk \":=\" *> inl <$> texpr <|> (tk \":\" *> inr <$> texpr))\n\nmeta def arity : lean.parser rep_arity :=\nrep_arity.many <$ tk \"*\" <|>\nrep_arity.exactly <$> (tk \"^\" *> small_nat) <|>\npure rep_arity.one\n\n/--\n\n`ac_mono` reduces the `f x ⊑ f y`, for some relation `⊑` and a\nmonotonic function `f` to `x ≺ y`.\n\n`ac_mono*` unwraps monotonic functions until it can't.\n\n`ac_mono^k`, for some literal number `k` applies monotonicity `k`\ntimes.\n\n`ac_mono := h`, with `h` a hypothesis, unwraps monotonic functions and\nuses `h` to solve the remaining goal. Can be combined with `*` or `^k`:\n`ac_mono* := h`\n\n`ac_mono : p` asserts `p` and uses it to discharge the goal result\nunwrapping a series of monotonic functions. Can be combined with * or\n^k: `ac_mono* : p`\n\nIn the case where `f` is an associative or commutative operator,\n`ac_mono` will consider any possible permutation of its arguments and\nuse the one the minimizes the difference between the left-hand side\nand the right-hand side.\n\nTo use it, first import `tactic.monotonicity`.\n\n`ac_mono` can be used as follows:\n\n```lean\nexample (x y z k m n : ℕ)\n (h₀ : z ≥ 0)\n (h₁ : x ≤ y) :\n (m + x + n) * z + k ≤ z * (y + n + m) + k :=\nbegin\n ac_mono,\n -- ⊢ (m + x + n) * z ≤ z * (y + n + m)\n ac_mono,\n -- ⊢ m + x + n ≤ y + n + m\n ac_mono,\nend\n```\n\nAs with `mono*`, `ac_mono*` solves the goal in one go and so does\n`ac_mono* := h₁`. The latter syntax becomes especially interesting in the\nfollowing example:\n\n```lean\nexample (x y z k m n : ℕ)\n (h₀ : z ≥ 0)\n (h₁ : m + x + n ≤ y + n + m) :\n (m + x + n) * z + k ≤ z * (y + n + m) + k :=\nby ac_mono* := h₁.\n```\n\nBy giving `ac_mono` the assumption `h₁`, we are asking `ac_refl` to\nstop earlier than it would normally would.\n-/\nmeta def ac_mono (rep : parse arity) :\n parse assert_or_rule? →\n opt_param mono_cfg { mono_cfg . } →\n tactic unit\n | none opt := focus1 $ repeat_or_not rep (ac_mono_aux opt) none\n | (some (inl h)) opt :=\ndo focus1 $ repeat_or_not rep (ac_mono_aux opt) (some $ done <|> to_expr h >>= ac_refine)\n | (some (inr t)) opt :=\ndo h ← i_to_expr t >>= assert `h,\n tactic.swap,\n focus1 $ repeat_or_not rep (ac_mono_aux opt) (some $ done <|> ac_refine h)\n/-\nTODO(Simon): with `ac_mono := h` and `ac_mono : p` split the remaining\n gaol if the provided rule does not solve it completely.\n-/\n\nadd_tactic_doc\n{ name := \"ac_mono\",\n category := doc_category.tactic,\n decl_names := [`tactic.interactive.ac_mono],\n tags := [\"monotonicity\"] }\n\nattribute [mono] and.imp or.imp\n\nend tactic.interactive\n", "meta": {"author": "Mel-TunaRoll", "repo": "Lean-Mordell-Weil-Mel-Branch", "sha": "4db36f86423976aacd2c2968c4e45787fcd86b97", "save_path": "github-repos/lean/Mel-TunaRoll-Lean-Mordell-Weil-Mel-Branch", "path": "github-repos/lean/Mel-TunaRoll-Lean-Mordell-Weil-Mel-Branch/Lean-Mordell-Weil-Mel-Branch-4db36f86423976aacd2c2968c4e45787fcd86b97/src/tactic/monotonicity/interactive.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.334589441253186, "lm_q2_score": 0.03963883938459575, "lm_q1q2_score": 0.013262737121616677}} {"text": "import its reducibility\n\nopen encodable denumerable\n\nattribute [simp] set.set_of_app_iff\n\nvariables {α : Type*} {β : Type*} {γ : Type*} {σ : Type*} {τ : Type*} {μ : Type*}\n [primcodable α] [primcodable β] [primcodable γ] [primcodable σ] [primcodable τ] [primcodable μ]\n {o : σ →. τ}\nvariables {n : ℕ} (S : strategy n) {k : ℕ}\n\nopen strategy encodable\n\ndef ancestor.equiv_fin {k : ℕ} (η : Tree k) :\nancestor η ≃ fin η.length :=\n{ to_fun := (λ μ, ⟨μ.val.length, list.is_initial_length μ.property⟩),\n inv_fun := (λ n, ⟨η↾*n.val, list.is_initial_initial η n.val n.property⟩),\n left_inv := (λ ⟨μ, ⟨l, x, p⟩⟩,\n by { simp[←p], simp only [show l ++ x :: μ = (l ++ [x]) ++ μ, by simp, list.initial_append] }),\n right_inv := (λ ⟨n, lt⟩, by { simp, exact list.initial_length lt }) }\n\ninstance primcodable.ancestor_arrow {α : Type*} [primcodable α] {k} (η : Tree k) : primcodable (ancestor η → α) :=\nprimcodable.of_equiv (fin η.length → α) (equiv.arrow_congr (ancestor.equiv_fin η) (by refl))\n\n@[rcomputability]\nlemma rcomputable.is_pi {k} : @Tree'.is_pi k computable_in o :=\nbegin\n induction k with k IH,\n { exact rcomputable.id.of_eq (λ b, by cases b; simp) },\n { let F : Tree' (k + 1) → bool := λ μ, list.cases_on μ ff (λ η _, !@Tree'.is_pi k η),\n have : F computable_in o,\n { refine (rcomputable.list_rec (rcomputable.id') (rcomputable.const ff)\n ((rcomputable.dom_fintype bnot).comp (IH.comp (rcomputable.fst.comp rcomputable.snd)))) },\n exact this.of_eq (λ μ, by { induction μ with ν μ IH; simp[F, Tree'.is_sigma] }) }\nend\n\n@[rcomputability]\nlemma rcomputable.is_sigma {k} : @Tree'.is_sigma k computable_in o :=\n(rcomputable.dom_fintype bnot).comp rcomputable.is_pi\n\ndef ancestor.extend_fn'_enc (α : Type*) [inhabited α] [primcodable α] (η : Tree k) (x : Tree' k) (n : ℕ) : ℕ := \n let f := (decode (ancestor (x :: η) → α) n).iget in\nencode (ancestor.extend_fn f η (list.suffix_cons x η))\n\nnamespace strategy\n\nnamespace approx_enc\n\ndef derivative (η : Tree (k + 1)) (μ : Tree k) (υ : list (Tree (k + 1))) : list ℕ :=\n(list.range_r μ.length).filter (λ i, υ.nth i = η)\n\ndef pi_derivative\n (η : Tree (k + 1)) (μ : Tree k) (υ : list (Tree (k + 1))) : list ℕ :=\n(derivative η μ υ).filter (λ i, @Tree'.is_sigma (k + 1) (μ↾*(i + 1)))\n\ndef lambda : Π (μ : Tree k) (υ : list (Tree (k + 1))), Tree (k + 1)\n| [] _ := []\n| (x :: μ) υ := let ih := lambda μ υ in\n option.cases_on (υ.nth μ.length) []\n (λ uμ, if uμ = ih ∨ (x.is_pi ∧ pi_derivative uμ μ υ = [])\n then (x :: μ) :: uμ else ih)\n\ndef assignment (μ : Tree k) (υ : list (Tree (k + 1))) : Tree (k + 1) × ℕ :=\n(S.priority (k + 1)).Min_le\n ((lambda μ υ, 0) :: ((list.range_r (lambda μ υ).length).filter\n (λ i, @Tree'.is_sigma (k + 2) (lambda μ υ↾*(i + 1)))).map\n (λ i, ((lambda μ υ)↾*i, (derivative (lambda μ υ↾*i) μ υ).length))) (by simp)\n\ndef up (μ : Tree k) (υ : list (Tree (k + 1))) : Tree (k + 1) :=\n(assignment S μ υ).1\n\nlemma ancestors_eq_range (μ : Tree k) : μ.ancestors.map ancestor.index = list.range_r μ.length :=\nby { induction μ with ν μ IH; simp[ancestor.index, (∘)], exact IH }\n\nlemma derivative_eq {μ : Tree k} {υ : ancestor μ → Tree (k + 1)} {υ' : list (Tree (k + 1))}\n (h : ∀ ν : ancestor μ, υ'.nth ν.index = some (υ ν)) (η : Tree (k + 1)) : \n derivative η μ υ' = (approx.derivative η υ).map ancestor.index :=\nby { simp[derivative, approx.derivative, ←ancestors_eq_range, list.map_filter, (∘)],\n congr, funext ν, simp [h] }\n\nlemma pi_derivative_eq {μ : Tree k} {υ : ancestor μ → Tree (k + 1)} {υ' : list (Tree (k + 1))}\n (h : ∀ ν : ancestor μ, υ'.nth ν.index = some (υ ν)) (η : Tree (k + 1)) : \n pi_derivative η μ υ' = (approx.pi_derivative η υ).map ancestor.index :=\nby { simp[pi_derivative, approx.pi_derivative, derivative_eq h, list.map_filter, (∘)],\n congr, funext ν, simp[ancestor_initial_index_succ] }\n\nlemma lambda_eq {μ : Tree k} {υ : ancestor μ → Tree (k + 1)} {υ' : list (Tree (k + 1))}\n (h : ∀ ν : ancestor μ, υ'.nth ν.index = some (υ ν)) : \n lambda μ υ' = approx.lambda υ :=\nbegin\n induction μ with ν μ IH; simp[lambda, approx.lambda],\n rw [show υ'.nth μ.length = some (υ ⟨μ, by simp⟩), from h ⟨μ, by simp⟩], simp,\n have la_eq : lambda μ υ' = approx.lambda (ancestor.extend_fn υ μ _),\n from @IH (ancestor.extend_fn υ μ (by simp)) (λ σ, h (σ.extend (by simp))),\n have pider_eq : ∀ η,\n pi_derivative η μ υ' = list.map ancestor.index (approx.pi_derivative η (ancestor.extend_fn υ μ _)),\n from @pi_derivative_eq _ _ (ancestor.extend_fn υ μ (by simp)) υ'\n (λ σ, h (σ.extend (by simp))),\n simp[la_eq, pider_eq]\nend\n\nlemma assignment_eq {μ : Tree k} {υ : ancestor μ → Tree (k + 1)} {υ' : list (Tree (k + 1))}\n (h : ∀ ν : ancestor μ, υ'.nth ν.index = some (υ ν)) : \n assignment S μ υ' = approx.assignment S υ :=\nbegin\n simp[assignment, approx.assignment, lambda_eq h],\n refine omega_ordering.Min_le_eq _ _ _ _,\n simp,\n rw [←ancestors_eq_range],\n simp[list.map_filter, (∘)],\n congr,\n { funext ν, simp[ancestor_initial_index, derivative_eq h] },\n { ext ν, simp[ancestor_initial_index_succ] }\nend\n\nlemma up_eq {μ : Tree k} {υ : ancestor μ → Tree (k + 1)} {υ' : list (Tree (k + 1))}\n (h : ∀ ν : ancestor μ, υ'.nth ν.index = some (υ ν)) : \n up S μ υ' = approx.up S υ :=\ncongr_arg prod.fst (assignment_eq S h)\n\nvariables {S}\nopen rcomputable computable₂\n\nlemma rcomputable.derivative :\n (prod.unpaired3 (derivative : Tree (k + 1) → Tree k → list (Tree (k + 1)) → list ℕ)) computable_in o :=\nbegin\n refine rcomputable.list_filter _ _,\n { refine (rcomputable₂.to_bool_eq (option (Tree (k + 1)))).comp₂ _ _,\n { exact rcomputable₂.list_nth.comp₂ (rcomputable.to_unary₁ rcomputable.snd.to_unary₂) rcomputable.id'.to_unary₂ },\n { exact rcomputable.to_unary₁ rcomputable.option_some.to_unary₁ } },\n { exact rcomputable.list_range_r.comp (rcomputable.list_length.comp rcomputable.fst.to_unary₂) }\nend\n\nlemma rcomputable.pi_derivative : \n (prod.unpaired3 (pi_derivative : Tree (k + 1) → Tree k → list (Tree (k + 1)) → list ℕ)) computable_in o :=\nbegin\n refine rcomputable.list_filter _ rcomputable.derivative,\n { simp, exact rcomputable.is_sigma.comp₂\n (rcomputable.rcomputable.list_initial.comp₂ (rcomputable.to_unary₁ rcomputable.fst.to_unary₂)\n rcomputable.succ.to_unary₂) }\nend\n\nlemma rcomputable.lambda : \n (lambda : Tree k → list (Tree (k + 1)) → Tree (k + 1)) computable₂_in o :=\nbegin\n let F : Tree k → list (Tree (k + 1)) → Tree (k + 1) :=\n λ μ υ, list.rec_on μ []\n (λ x μ ih, option.cases_on (υ.nth μ.length) []\n (λ uμ, if uμ = ih ∨ (x.is_pi ∧ pi_derivative uμ μ υ = []) then (x :: μ) :: uμ else ih)),\n have : F computable₂_in o,\n { simp[F],\n refine rcomputable.list_rec (rpartrec.some.to_unary₁) (rcomputable.const list.nil)\n (rcomputable.option_rec\n (rcomputable₂.list_nth.comp snd.to_unary₁\n (rcomputable.list_length.comp (fst.comp snd.to_unary₂)))\n (rcomputable.const list.nil)\n (rcomputable.ite _ _ _)),\n { simp, refine rcomputable.bor.comp _\n (rcomputable.band.comp (rcomputable.is_pi.comp (fst.comp snd.to_unary₁)) _),\n { refine (rcomputable₂.to_bool_eq _).comp snd\n (snd.comp (snd.comp snd.to_unary₁)) },\n { refine (rcomputable₂.to_bool_eq _).comp\n (rcomputable.pi_derivative.unpaired3 snd\n (fst.comp (snd.comp snd.to_unary₁))\n (snd.comp fst.to_unary₁)) (rcomputable.const []) } },\n { exact rcomputable₂.list_cons.comp\n (rcomputable₂.list_cons.comp (fst.comp snd.to_unary₁)\n (fst.comp (snd.comp snd.to_unary₁)))\n snd },\n { exact snd.comp (snd.comp snd.to_unary₁) } },\n exact this.of_eq (λ μ υ, by {\n induction μ with x μ IH; simp[F, lambda],\n { cases C : υ.nth μ.length with ν; simp[C],\n { simp[F, lambda] at IH, simp[IH] } } })\nend\n\nlemma rcomputable.assignment_enc : \n (assignment S : Tree k → list (Tree (k + 1)) → Tree (k + 1) × ℕ) computable₂_in o :=\n(omega_ordering_Min_le (S.priority (k + 1)) _ _ (S.effective _).to_rcomp\n (rcomputable₂.list_cons.comp (pair (rcomputable.lambda.comp fst snd) (const 0))\n (list_map\n (pair (rcomputable.list_initial.comp (rcomputable.lambda.comp fst.to_unary₁ snd.to_unary₁) snd)\n (list_length.comp (rcomputable.derivative.unpaired3\n (rcomputable.list_initial.comp (rcomputable.lambda.comp fst.to_unary₁ snd.to_unary₁) snd)\n (fst.to_unary₁) (snd.to_unary₁))))\n (list_filter\n (by {simp, exact is_sigma.comp₂ \n (rcomputable.list_initial.comp₂ (rcomputable.lambda.comp fst snd).to_unary₁ succ.to_unary₂) })\n (list_range_r.comp (list_length.comp (rcomputable.lambda.comp fst snd)))))))\n\nlemma rcomputable.up_enc : \n (up S : Tree k → list (Tree (k + 1)) → Tree (k + 1)) computable₂_in o :=\nfst.comp rcomputable.assignment_enc\n\nend approx_enc\n\ndef up'_enc : Tree k → list (Tree (k + 1))\n| [] := []\n| (_ :: η) := up'_enc η ++ [approx_enc.up S η (up'_enc η)]\n\n@[simp] lemma up'_enc_length (μ : Tree k) : (up'_enc S μ).length = μ.length :=\nby induction μ with ν μ IH; simp[up'_enc]; exact IH\n\nvariables {S}\nopen rcomputable rcomputable₂\n\nlemma rcomputable.up'_enc : (up'_enc S : Tree k → list (Tree (k + 1))) computable_in o :=\nbegin\n let F : Tree k → list (Tree (k + 1)) := λ μ, list.rec_on μ [] (λ _ η IH, IH ++ [approx_enc.up S η IH]),\n have : F computable_in o,\n { simp[F],\n refine rcomputable.list_rec rcomputable.id' (const []) _,\n exact list_append.comp (snd.comp snd.to_unary₂)\n (list_cons.comp (approx_enc.rcomputable.up_enc.comp (fst.comp snd.to_unary₂) (snd.comp snd.to_unary₂))\n (const [])) },\n exact this.of_eq (λ μ, by { \n induction μ with ν μ IH; simp[F, up'_enc],\n { simp[F] at IH, simp[IH] } })\nend\n\nlemma up_enc_eq_up {μ : Tree k} : ∀ ν : ancestor μ, (S.up'_enc μ).nth ν.index = some (S.up' μ ν) :=\nbegin\n induction μ with ν μ IH; simp[up'_enc, up' S, -up'_up_consistent],\n { rintros ⟨σ, lt⟩,simp at lt, contradiction },\n { rintros ⟨σ, lt⟩, simp[up', -up'_up_consistent],\n have : σ = μ ∨ σ ⊂ᵢ μ, from list.is_initial_cons_iff.mp lt,\n rcases this with (rfl | lt),\n { simp[ancestor.index],\n rw [show σ.length = (S.up'_enc σ).length, by simp, list.nth_concat_length],\n simp, refine approx_enc.up_eq S IH },\n { simp[lt, ancestor.index],\n rw [list.nth_append (show list.length σ < (S.up'_enc μ).length, by simp[list.is_initial_length lt])],\n have := IH ⟨σ, lt⟩, simp[ancestor.index] at this, exact this } }\nend\n\n@[rcomputability]\ntheorem rcomputable.up : (up[S] : Tree k → Tree (k + 1)) computable_in o :=\n(approx_enc.rcomputable.up_enc.comp id' rcomputable.up'_enc).of_eq\n(λ μ, approx_enc.up_eq S up_enc_eq_up)\n\n\n@[rcomputability]\ntheorem rcomputable.lambda : (λ[S] : Tree k → Tree (k + 1)) computable_in o :=\nby { have : (λ μ : Tree k, approx_enc.lambda μ (S.up'_enc μ)) computable_in o,\n from approx_enc.rcomputable.lambda.comp id' rcomputable.up'_enc,\n exact this.of_eq (λ μ, approx_enc.lambda_eq up_enc_eq_up) }\n\nlemma rcomputable.Tree'_weight_aux {k : ℕ} :\n (Tree'.weight_aux : Tree' k → ℕ) computable_in o :=\nbegin\n induction k with k IH,\n { exact (id'.cond (const 1) (const 0)).of_eq (λ μ, by cases μ; simp[Tree'.weight_aux]) },\n { exact list_weight_of IH }\nend\n\n@[rcomputability]\nlemma rcomputable.Tree_weight {k : ℕ} :\n (Tree.weight : Tree k → ℕ) computable_in o :=\nbegin\n induction k with k IH,\n { exact rcomputable.Tree'_weight_aux },\n { let F : Tree (k + 1) → ℕ := λ μ, list.rec_on μ 0 (λ ν _ _, ν.weight_aux + 1),\n have : F computable_in o,\n { simp[F], refine rcomputable.list_rec id (const 0)\n (nat_add.comp (rcomputable.Tree'_weight_aux.comp fst.to_unary₂) (const 1)) },\n exact this.of_eq (λ μ, by cases μ; simp[F, Tree.weight]) }\nend\n\nend strategy", "meta": {"author": "iehality", "repo": "lean-reducibility", "sha": "82a7e3ec0fcedfb0d69c25e77bcd24c9b29626b7", "save_path": "github-repos/lean/iehality-lean-reducibility", "path": "github-repos/lean/iehality-lean-reducibility/lean-reducibility-82a7e3ec0fcedfb0d69c25e77bcd24c9b29626b7/src/its_computable.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47268347662043286, "lm_q2_score": 0.02800751766498379, "lm_q1q2_score": 0.013238690821392726}} {"text": "import Lean\nimport Crypto.Util\n\nopen Lean Elab Tactic Meta\n\nnamespace Crypto\n\n/-- Return true iff `constName` is the a non-recursive inductive datatype without indices\n that has only one constructor. If `includeProp` is false, we also check that the datatype is\n not `Prop` or `Sort*` -/\ndef isVeryStructureLike (env : Environment) (constName : Name) (includeProp := true) : Bool :=\n match env.find? constName with\n | some d@(ConstantInfo.inductInfo { isRec := false, ctors := [ctor], numIndices := 0, .. }) =>\n includeProp || d.toConstantVal.type.getForallBody.level!.isASucc\n | _ => false\n\n/-- Good names for new hypotheses when casing on a variable with name `nm` and type `constName`. -/\ndef giveNames (env : Environment) (constName nm : Name) : Array Name :=\n match getStructureInfo? env constName with\n | some p => p.fieldNames.map λ s => nm.appendAfter (\"_\" ++ s.toString)\n | _ => if constName == `Exists then #[nm.appendAfter \"_val\", nm.appendAfter \"_prop\"] else #[]\n\n\n/- the data we record for each field -/\nstructure FieldData where\n(decl : LocalDecl)\n(fvar : Expr)\n(type : Expr)\n(depends : NameSet)\n(isProp : Bool)\nderiving Inhabited\n\n/- additionally an expression that gives us the translation to another field -/\nstructure FieldMapping extends FieldData where\n(tgt : Option Expr)\nderiving Inhabited\n\nstructure Context where\n(target : Array FieldData)\nderiving Inhabited\n\nstructure State where\n(mapping : Array FieldMapping)\nderiving Inhabited\n\nopen Std.Format\n\ninstance : ToFormat NameSet :=\n⟨λ x => format x.toList⟩\n\ninstance : ToFormat FieldData :=\n⟨λ ⟨a, b, c, d, e⟩ => group (nest 1 (format \"⟨\" ++ format a ++ format \",\" ++ line ++ format b ++\nformat \",\" ++ line ++ format c ++ format \",\" ++ line ++ format d ++ format \",\" ++ line ++ format e\n++ format \"⟩\"))⟩\n\nnamespace FieldData\n\ndef name (fields : FieldData) : Name :=\nfields.decl.userName.head!\n\ndef toFieldMapping (fields : FieldData) : FieldMapping :=\n{ toFieldData := fields, tgt := none }\n\nend FieldData\n\nnamespace FieldMapping\ndef update (field : FieldMapping) (newM : Option Expr) : FieldMapping :=\nif field.tgt.isNone then { field with tgt := newM } else field\n\ndef updateM (field : FieldMapping) (tac : MetaM (Option Expr)) : MetaM FieldMapping :=\nif field.tgt.isNone then do\n let tgt ← tac\n return { field with tgt := tgt }\nelse\n return field\n\nend FieldMapping\n\ndef ppFieldData (x : FieldData) : MetaM Format :=\ndo return group (nest 1 (format \"⟨\" ++\nformat x.name ++ format \",\" ++ line ++\nformat (← Meta.ppExpr x.fvar) ++ format \",\" ++ line ++\nformat (← Meta.ppExpr x.type) ++ format \",\" ++ line ++\nformat (← x.depends.toList.mapM λ e => Meta.ppExpr (mkFVar ⟨e⟩)) ++ format \",\" ++ line ++\nformat x.isProp ++ format \"⟩\"))\n\n/-- make a field mapping with no connections. -/\ndef mkState (fields1 : Array FieldData) : State :=\n{ mapping := fields1.map (·.toFieldMapping) }\n\nnamespace State\n\ndef done (st : State) : Bool :=\nst.mapping.all (·.tgt.isSome)\n\ndef update (st : State) (f : FieldData → Option Expr) : State :=\n{ mapping := st.mapping.map λ info => info.update (f info.toFieldData) }\n\ndef updateM (st : State) (f : FieldData → MetaM (Option Expr)) : MetaM State := do\n let fieldMapping ← st.mapping.mapM λ info => info.updateM (f info.toFieldData)\n return { mapping := fieldMapping }\n\ndef getDataMapping (st : State) : Array (Expr × Expr) :=\nst.mapping.filterMap λ map => match map.tgt with\n | none => none\n | some e => if map.isProp then none else some (map.fvar, e)\n\ndef getMapping (st : State) : Array (Expr × Expr) :=\nst.mapping.filterMap λ map => match map.tgt with\n | none => none\n | some e => some (map.fvar, e)\n\ndef missing (st : State) : Array FieldData :=\nst.mapping.filterMap λ info => if info.tgt.isNone then some info.toFieldData else none\n\ndef missingData (st : State) : Array FieldData :=\nst.mapping.filterMap λ info =>\n if info.tgt.isNone && !info.isProp then some info.toFieldData else none\n\ndef traceMapping (st : State) : MetaM (Array Format) :=\nst.mapping.mapM λ info : FieldMapping =>\n if info.tgt.isSome then Meta.ppExpr info.tgt.get! else return Format.nil\n\n\nend State\n\nnamespace Meta\n\ndef fieldDataofCaseGoals (l : Array CasesSubgoal) : MetaM (MVarId × Array FieldData) := do\n let casegoal := l.get! 0\n let mvarId := casegoal.mvarId\n withMVarContext mvarId do\n let lctx ← getLCtx\n let fieldExprs := casegoal.fields\n let fields := fieldExprs.map Expr.fvarId!\n let ldecls := fields.map λ e => lctx.fvarIdToDecl.find! e\n let axiom_fields ← fieldExprs.mapM isProof\n let types ← fieldExprs.mapM inferType\n let depends := types.map λ tp => tp.ListFvarIds\n let fieldData := ldecls.zipWith5 FieldData.mk fieldExprs types depends axiom_fields\n return (mvarId, fieldData)\n\ndef updateFieldData (l : Array CasesSubgoal) (fields : Array FieldData) :\n MetaM (Array FieldData) := do\n let casegoal := l.get! 0\n let mvarId := casegoal.mvarId\n let fieldData ← withMVarContext mvarId $ fields.mapM λ info =>\n match casegoal.subst.find? info.fvar.fvarId! with\n | (some e) => do\n let lctx ← getLCtx\n let id := e.fvarId!\n let ldecl := lctx.fvarIdToDecl.find! id\n let t ← inferType e\n let depends := NameSet.empty -- todo\n return ⟨ldecl, e, t, depends, info.isProp⟩\n | none => return info\n return fieldData\n\ndef AddFieldsToContext (mvarId : MVarId) (nm : Name) (us : List Level) (args : Array Expr) :\n MetaM (MVarId × MVarId × Array FieldData) := do\n let env ← getEnv\n let d ← env.find? nm\n let true ← isStructureLike env nm\n let eStr ← mkAppN (mkConst nm us) args\n let (h, mvarId, m2) ← assertm mvarId `h eStr\n let l ← cases mvarId h\n let (mvarId, fieldData) ← fieldDataofCaseGoals l\n return (mvarId, m2, fieldData)\n\n/-- map the data fields to data fields of the same name. -/\ndef trivialMapping (st : State) (ctx : Context) : State :=\nst.update $ λ info =>\n if info.isProp then none else\n ctx.target.findSome? λ info' => if info.name == info'.name then some info'.fvar else none\n\n/-- map the data fields to data fields with the same type, if a unique such data field exists. -/\ndef uniqueMapping (st : State) (ctx : Context) : MetaM State :=\nst.updateM $ λ info => if info.isProp then return none else do\n let sources ← st.mapping.filterM λ info' => isDefEq info.type info'.type\n let targets ← ctx.target.filterM λ info' => isDefEq info.type info'.type\n return (if sources.size = 1 ∧ targets.size = 1 then some (targets.get! 0).fvar else none)\n\nset_option pp.all true\npartial def caseOnStructures (mvarId : MVarId) (st : Array FieldData) (ctx : Context)\n (includeProp := true) :\n MetaM (MVarId × Array FieldData) := do\n let env ← getEnv\n let info? := st.find? λ info =>\n info.type.getAppFn.constName?.any (isVeryStructureLike env · includeProp)\n match info? with\n | some info => do\n let rest := st.filter λ info' => info'.fvar.fvarId! != info.fvar.fvarId!\n let str := info.type.getAppFn.constName!\n -- todo: there seems to be a bug with the given names when transitively extending structures. Do we need to skip fields?\n -- IO.println (giveNames env str info.name)\n let l ← cases mvarId info.fvar.fvarId! #[⟨false, (giveNames env str info.name).toList⟩]\n let (mvarId, fieldData) ← fieldDataofCaseGoals l\n let rest ← updateFieldData l rest\n caseOnStructures mvarId (rest ++ fieldData) ctx includeProp\n | none =>\n return (mvarId, st)\n\n\n/-- Find which axioms of the first structure that occur in the second structure. -/\ndef matchingAxioms (st : State) (ctx : Context) : MetaM State := do\n let targetTypes : Array (Expr × Expr) := ctx.target.filterMap λ info =>\n if info.isProp then (info.fvar, info.type) else none\n st.updateM λ info => do\n let e := info.type.instantiateFVars st.getDataMapping\n match (← targetTypes.findM? λ (e', t) => isDefEq e t) with\n | some (e, t) => return (some e)\n | none => return none\n\n/-- some copy-pasted simp code -/\ndef getPropHyps : MetaM (Array FVarId) := do\n let mut result := #[]\n for localDecl in (← getLCtx) do\n unless localDecl.isAuxDecl do\n if (← isProp localDecl.type) then\n result := result.push localDecl.fvarId\n return result\n\n/-- some mostly copy-pasted simp code -/\ndef mkSimpContext (simpOnly := false) (starArg := true) : MetaM Simp.Context := do\n let ctx : Simp.Context :=\n { config := {}\n simpLemmas := if simpOnly then {} else (← getSimpLemmas)\n congrLemmas := (← getCongrLemmas) }\n if !starArg then\n return ctx\n else\n let hs ← getPropHyps\n let mut ctx := ctx\n for h in hs do\n let localDecl ← getLocalDecl h\n let fvarId := localDecl.fvarId\n let proof := localDecl.toExpr\n let id ← mkFreshUserName `h\n let simpLemmas ← ctx.simpLemmas.add #[] proof (name? := id)\n ctx := { ctx with simpLemmas }\n return ctx\n\n/-- The tactic we use to automatically prove axioms. -/\ndef currentAutomation (mvarId : MVarId) : MetaM Unit := do\nlet newgoal ← simpTarget mvarId (← mkSimpContext false)\n\n-- match (← simpTarget mvarId (← mkSimpContext false)) with\n-- | some x => IO.println \"failure!\"\n-- | none => IO.println \"success!\"\n\n/-- Tries to prove `e` in the local context, returns the proof if successful. -/\ndef tryToProve (mvarId : MVarId) (tac : MVarId → MetaM Unit) (e : Expr) : MetaM (Option Expr) :=\nwithoutModifyingState do\n let (fvar, mvarId, m2) ← assertm mvarId `h e\n try\n tac m2\n -- IO.println s!\"is assigned: {← isExprMVarAssigned m2}\"\n let some e ← getExprMVarAssignment? m2 | return none\n let e ← instantiateMVars e\n if (← e.hasExprMVar) then return none else return some e\n catch err =>\n return none\n\n/-- Tests whether nm1 is a subclass of nm1. Currently the data fields must have the same Name for\nthis tactic to work. -/\ndef isSubclass (mvarId : MVarId) (nm1 nm2 : Name) (trace := false) :\n MetaM (MVarId × MVarId × MVarId × State) := do\n let u := mkLevelParam `u\n let (M, mvarId) ← asserti mvarId `M (mkSort (mkLevelSucc u)) (mkConst `PUnit [mkLevelSucc u])\n let (mvarId, m2, fields2) ← AddFieldsToContext mvarId nm2 [u] #[mkFVar M]\n let (mvarId, fields2) ← caseOnStructures mvarId fields2 ⟨#[]⟩ false\n let ctx : Context := ⟨fields2⟩\n if trace then IO.println s!\"cases on fields class 2: {← ctx.target.map (·.name)}\"\n let (mvarId, m1, fields1) ← AddFieldsToContext mvarId nm1 [u] #[mkFVar M]\n let (mvarId, fields1) ← caseOnStructures mvarId fields1 ctx\n let st := mkState fields1\n withMVarContext mvarId do\n let st ← uniqueMapping st ctx\n let st := trivialMapping st ctx\n if trace then IO.println s!\"map of data: {← st.traceMapping}\"\n let (mvarId, fields2) ← caseOnStructures mvarId fields2 ⟨#[]⟩ -- is this dangerous?\n let ctx : Context := ⟨fields2⟩\n withMVarContext mvarId do\n let ctx : Context := ⟨fields2⟩\n let st ← matchingAxioms st ctx\n let st ← st.updateM λ info => if !info.isProp then return none else\n tryToProve mvarId currentAutomation (info.type.instantiateFVars st.getDataMapping)\n if trace then IO.println s!\"map: {← st.traceMapping}\"\n return (mvarId, m1, m2, st)\n\nend Meta\n\nsyntax (name := guardHyp) \"guardHyp \" (\" : \" term)? : tactic\n@[tactic guardHyp] def evalGuardHyp : Lean.Elab.Tactic.Tactic := fun stx =>\n match stx with\n | `(tactic| guardHyp $[: $ty]?) => do\n return ()\n | _ => throwUnsupportedSyntax\n\ndef isSubclassTac (nm1 nm2 : Name) (trace := false) : TacticM Unit := withMainContext do\nlet mvarId ← getMainGoal\nlet (mvarId, m1, m2, st) ← Meta.isSubclass mvarId nm1 nm2 trace\nif st.done then IO.println s!\"{nm1} is a subclass of {nm2}\"\nelse IO.println s!\"Cannot construct the following fields of {nm1} from {nm2}:\n{st.missing.map (·.name)}.\"\nlet l ← getUnsolvedGoals\nsetGoals (mvarId::m1::m2::l)\n\ndef cryptomorphicTac (nm1 nm2 : Name) (trace := false) : TacticM Unit := withMainContext do\nlet mvarId ← getMainGoal\nlet (mvarId, m1, m2, st1) ← Meta.isSubclass mvarId nm1 nm2 trace\nlet (mvarId, m3, m4, st2) ← Meta.isSubclass mvarId nm2 nm1 trace\nif st1.done && st2.done then IO.println s!\"{nm1} and {nm2} are cryptomorphic\"\nelse do\n IO.println s!\"Cannot prove that {nm1} and {nm2} are cryptomorphic\"\n if !st1.done then\n IO.println s!\"{nm2} → {nm1}: cannot construct {st1.missing.map (·.name)}\"\n if !st2.done then\n IO.println s!\"{nm1} → {nm2}: Cannot construct {st2.missing.map (·.name)}\"\nlet l ← getUnsolvedGoals\nsetGoals (mvarId::m1::m2::m3::m4::l)\n\nsyntax (name := isSubclass) \"isSubclass \" ident ident : tactic\nsyntax (name := isSubclassE) \"isSubclass! \" ident ident : tactic\n@[tactic «isSubclass»] def evalIsSubclass : Tactic := fun stx =>\n match stx with\n | `(tactic| isSubclass $nm1 $nm2) => withoutModifyingState $ isSubclassTac nm1.getId nm2.getId\n | _ => throwUnsupportedSyntax\n@[tactic «isSubclassE»] def evalIsSubclassE : Tactic := fun stx =>\n match stx with\n | `(tactic| isSubclass! $nm1 $nm2) => isSubclassTac nm1.getId nm2.getId true\n | _ => throwUnsupportedSyntax\n\n\nsyntax (name := cryptomorphic) \"cryptomorphic \" ident ident : tactic\n@[tactic «cryptomorphic»] def evalCryptomorphic : Tactic := fun stx =>\n match stx with\n | `(tactic| cryptomorphic $nm1 $nm2) => withoutModifyingState $ cryptomorphicTac nm1.getId nm2.getId\n | _ => throwUnsupportedSyntax\n\nend Crypto\nopen Crypto\n\n/-!\n## Demo and tests\n\nWe define some notions of commutative Monoids,\n(1) right-unital\n(2) right-unital, and then has a superfluous axiom `1 * 1 = 1`\n(3) both left-unital and right-unital.\n(4) denoted additively\n(5) with a unit given by an existential quantifier (`∃ one, ...`)\n(6) by extending a `Monoid` structure.\n-/\n\nclass Zero (α : Type u) where\n zero : α\n\ninstance [Zero α] : OfNat α (nat_lit 0) where\n ofNat := Zero.zero\n\nclass One (α : Type u) where\n one : α\n\ninstance [One α] : OfNat α (nat_lit 1) where\n ofNat := One.one\n\nclass CommMonoid1 (M : Type _) extends Mul M, One M :=\n(mul_assoc : ∀ x y z : M, (x * y) * z = x * (y * z))\n(mul_comm : ∀ x y : M, x * y = y * x)\n(mul_one : ∀ x : M, x * 1 = x)\n\nclass CommMonoid2 (M : Type _) extends Mul M, One M :=\n(mul_one : ∀ x : M, x * 1 = x)\n(one_mul_one : 1 * 1 = 1)\n(mul_assoc : ∀ x y z : M, (x * y) * z = x * (y * z))\n(mul_comm : ∀ x y : M, x * y = y * x)\n\nclass CommMonoid3 (M : Type _) extends Mul M, One M :=\n(one_mul : ∀ x : M, 1 * x = x)\n(mul_assoc : ∀ x y z : M, (x * y) * z = x * (y * z))\n(mul_comm : ∀ x y : M, x * y = y * x)\n\nclass CommMonoid4 (M : Type _) extends Add M, Zero M :=\n(add_assoc : ∀ x y z : M, (x + y) + z = x + (y + z))\n(add_comm : ∀ x y : M, x + y = y + x)\n(add_zero : ∀ x : M, x + 0 = x)\n\nclass CommMonoid5 (M : Type _) extends Mul M :=\n(mul_axioms : (∀ x y z : M, (x * y) * z = x * (y * z)) ∧ (∀ x y : M, x * y = y * x))\n(exists_one : ∃ one : M, ∀ x : M, x * one = x)\n\nclass Monoid (M : Type _) extends Mul M, One M :=\n(mul_assoc : ∀ x y z : M, (x * y) * z = x * (y * z))\n(mul_one : ∀ x : M, x * 1 = x)\n\nclass CommMonoid6 (M : Type _) extends Monoid M :=\n(mul_comm : ∀ x y : M, x * y = y * x)\n\nopen CommMonoid1\n\n-- example (M : Type _) [CommMonoid1 M] (x : M) : 1 * x = 1 := by\n-- simp [mul_comm]\n\n\n\nexample : True := by\n cryptomorphic CommMonoid1 CommMonoid2 -- yes\n cryptomorphic CommMonoid1 CommMonoid3 -- mul_one, one_mul [need better automation]\n cryptomorphic CommMonoid1 CommMonoid4 -- yes\n cryptomorphic CommMonoid1 CommMonoid5 -- one, mul_one [need support for existentials]\n cryptomorphic CommMonoid1 CommMonoid6 -- yes\n trivial\n\n/-! As a sanity check: we cannot prove commutativity on an arbitrary Monoid. -/\n\nclass MyMonoid (M : Type _) extends Mul M :=\n(mul_assoc : ∀ x y z : M, (x * y) * z = x * (y * z))\n(one : M)\n(mul_one : ∀ x : M, x * one = x)\n\nexample : True := by\n cryptomorphic MyMonoid CommMonoid1 -- missing (expected): mul_comm\n trivial\n\n/-!\nIf two data fields have the same type, we try to get the one with the same name.\nIn the future we could look at which choice will make more axioms overlap.\n-/\n\nclass MyAlmostRing (M : Type _) extends Mul M :=\n(add : M → M → M)\n(mul_assoc : ∀ x y z : M, (x * y) * z = x * (y * z))\n(mul_comm : ∀ x y : M, x * y = y * x)\n(one : M)\n(mul_one : ∀ x : M, x * one = x)\n\nexample : True := by\n cryptomorphic CommMonoid1 MyAlmostRing -- missing (expected): add\n trivial\n\n/-! Test which \"fields\" are missing when inside nested structures. -/\n\nclass CommMonoidBundled1 (M : Type _) extends Mul M :=\n(mul_assoc : ∀ x y z : M, (x * y) * z = x * (y * z))\n(mul_comm : ∀ x y : M, x * y = y * x)\n(one_axioms : ∃ one : M, (∀ x : M, x * one = x) ∧ (∀ x : M, x * x = one))\n\nclass CommMonoidBundled2 (M : Type _) :=\n(data : (M → M → M) × M)\n(mul_assoc : ∀ x y z : M, data.1 (data.1 x y) z = data.1 x (data.1 y z))\n(mul_comm : ∀ x y : M, data.1 x y = data.1 y x)\n(mul_one : ∀ x : M, data.1 x data.2 = x)\n\n\nexample : True := by\n cryptomorphic CommMonoidBundled1 CommMonoid1 -- missing (expected): one_axioms_prop_right\n -- missing: one, one_mul [need support for existentials]\n cryptomorphic CommMonoidBundled2 CommMonoid1 -- yesss\n trivial", "meta": {"author": "fpvandoorn", "repo": "cryptomorphism", "sha": "d486419ecced54de3db759dae81110be44b7c28b", "save_path": "github-repos/lean/fpvandoorn-cryptomorphism", "path": "github-repos/lean/fpvandoorn-cryptomorphism/cryptomorphism-d486419ecced54de3db759dae81110be44b7c28b/lean4/Crypto/Structure.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34864513533394575, "lm_q2_score": 0.037892430703949105, "lm_q1q2_score": 0.013211011630910497}} {"text": "import system.io\nimport utils\nopen tactic.unsafe\n\nuniverses u v w\n\n-- tools and help functions\n\n-- def option.mmap {m : Type u → Type v} [monad m] {α : Type w} {β : Type u} (f : α → m β) : option α → m (option β)\n-- | none := return none\n-- | (some x) := do x' ← f x, return (some x')\n\ndef list.last_option {α : Type u}: list α → option α\n| [] := none\n| [a] := some a\n| (a::b::l) := list.last_option (b::l)\n\nmeta def expr.local_uniq_name_option : expr → option name\n| (expr.local_const n m bi t) := some n\n| e := none\n\nmeta def expr.mvar_uniq_name_option : expr → option name\n| (expr.mvar n ppn t) := some n\n| e := none\n\n-- set the tactic state\nmeta def set_state (new_state: tactic_state): tactic unit :=\n -- this is in mathlib but easier to recreate\n λ _, interaction_monad.result.success () new_state\n\n-- types for encoding tactic state information\n\nmeta structure mvar_decl :=\n(unique_name : name)\n(pp_name : name)\n(expr_type : expr)\n(local_cxt : list expr)\n(type : option expr)\n(assignment : option expr)\n\n/- There already is a local_decl type, but \nthis is some more informtion for understanding \nthe type better.-/\nmeta structure local_decl2 :=\n(unique_name : name)\n(pp_name : name)\n(expr_type : expr)\n(bi : binder_info)\n(type : option expr)\n(prev : option name)\n(frozen : bool)\n(ld : option local_decl)\n\nmeta structure univ_mvar_decl :=\n(unique_name : name)\n(assignment : option level)\n\nmeta inductive context.decl\n| mvar_decl (mv : mvar_decl) : context.decl\n| univ_mvar_decl (mv : univ_mvar_decl) : context.decl\n| local_decl (loc : local_decl2) : context.decl\n\nmeta structure context :=\n-- in order of dependecies\n(decls : list context.decl)\n(names : name_set)\n\nmeta structure tactic_state_data :=\n(decls : list context.decl)\n(goals : list (name × tactic.tag))\n\n-- meta instance : has_to_format tactic.tag := sorry\n-- meta instance : has_to_format context.decl := sorry\n-- -- meta instance : has_to_tactic_format context.decl := sorry\n-- meta instance foo' : has_to_format $ list (name × tactic.tag) := by apply_instance\n-- meta instance foo : has_to_format (list decl) := by apply_instance\n\n-- meta instance : has_to_tactic_format tactic_state_data :=\n-- ⟨λ ⟨decls, goals⟩, pure $ format!\"tactic_state_data.mk \\n\\t decls := {decls} \\n\\t goals := {goals}\"⟩\n\nattribute [derive [has_to_format]] mvar_decl univ_mvar_decl binder_info\nattribute [derive [has_to_format]] local_decl\nattribute [derive [has_to_format]] local_decl2\nattribute [derive [has_to_format]] context.decl\nmeta instance : has_to_format tactic.tag := (by apply_instance : has_to_format (list name))\n\nattribute [derive [has_to_format]] tactic_state_data\n\nsection instances\n\nattribute [derive [has_to_tactic_json]] mvar_decl\nattribute [derive [has_to_tactic_json]] univ_mvar_decl\nattribute [derive [has_to_tactic_json]] local_decl\nattribute [derive [has_to_tactic_json]] local_decl\nattribute [derive [has_to_tactic_json]] local_decl2\n\nattribute [derive has_to_tactic_json] context.decl\n\nmeta instance : has_to_tactic_json tactic.tag :=\n⟨by mk_to_tactic_json name.anonymous⟩\n\nmeta instance : has_from_json tactic.tag :=\nhas_from_json_list\n\nattribute [derive has_to_tactic_json] tactic_state_data\n\nmeta instance : has_from_json mvar_decl :=\n⟨λ msg, match msg with\n | (json.array $ [c, json.array [un, pp, ety, cxt, ty, assn]]) := do\n (c_nm : name) ← has_from_json_name_aux c,\n if c_nm = `mvar_decl.mk then do\n mvar_decl.mk <$> (has_from_json.from_json un) <*> (has_from_json.from_json pp)\n <*> has_from_json.from_json ety <*> has_from_json.from_json cxt\n <*> has_from_json.from_json ty <*> has_from_json.from_json assn\n else\n tactic.fail format!\"[has_from_json_mvar_decl] unexpected: {msg}\"\n | exc := tactic.fail format!\"[has_from_json_mvar_decl] unexpected: {exc}\"\n end\n⟩\n\nmeta instance : has_from_json univ_mvar_decl :=\n⟨λ msg, match msg with\n | (json.array $ [c, json.array [un, pp]]) := do\n (c_nm : name) ← has_from_json_name_aux c,\n if c_nm = `univ_mvar_decl.mk then do\n univ_mvar_decl.mk <$> (has_from_json.from_json un) <*> (has_from_json.from_json pp)\n else\n tactic.fail format!\"[has_from_json_univ_mvar_decl] unexpected: {msg}\"\n | exc := tactic.fail format!\"[has_from_json_univ_mvar_decl] unexpected: {exc}\"\n end\n⟩\n\n-- meta instance : has_from_json univ_mvar_decl := sorry\n\n-- attribute [derive [has_to_tactic_json]] bool\n\nrun_cmd (has_to_tactic_json.to_tactic_json tt >>= (has_from_json.from_json : json → tactic bool))\n\nmeta instance : has_from_json local_decl := \n⟨λ msg, match msg with\n | (json.array $ [c, json.array [un, pp, ty, val, bi, idx]]) := do\n (c_nm : name) ← has_from_json_name_aux c,\n if c_nm = `local_decl.mk then do\n local_decl.mk <$>\n (has_from_json.from_json un) <*>\n (has_from_json.from_json pp) <*>\n has_from_json.from_json ty <*>\n has_from_json.from_json val <*>\n has_from_json.from_json bi <*>\n has_from_json.from_json idx\n else\n tactic.fail format!\"[has_from_json_local_decl] unexpected: {msg}\"\n | exc := tactic.fail format!\"[has_from_json_local_decl] unexpected: {exc}\"\n end\n⟩\n\nmeta instance : has_from_json local_decl2 :=\n⟨λ msg, match msg with\n | (json.array $ [c, json.array [un, pp, ety, bi, ty, prev, frozen, ld]]) := do\n (c_nm : name) ← has_from_json_name_aux c,\n if c_nm = `local_decl2.mk then do\n local_decl2.mk <$>\n (has_from_json.from_json un) <*>\n (has_from_json.from_json pp) <*>\n has_from_json.from_json ety <*>\n has_from_json.from_json bi <*>\n has_from_json.from_json ty <*>\n has_from_json.from_json prev <*>\n has_from_json.from_json frozen <*>\n has_from_json.from_json ld\n else\n tactic.fail format!\"[has_from_json_local_decl2] unexpected: {msg}\"\n | exc := tactic.fail format!\"[has_from_json_local_decl2] unexpected: {exc}\"\n end\n⟩\n\nmeta instance : has_from_json context.decl :=\nlet ⟨fn₁⟩ := (by apply_instance : has_from_json mvar_decl) in\nlet ⟨fn₂⟩ := (by apply_instance : has_from_json univ_mvar_decl) in\nlet ⟨fn₃⟩ := (by apply_instance : has_from_json local_decl2) in\n⟨λ msg, match msg with\n | (json.array $ [c, json.array args]) := do\n (c_nm : name) ← has_from_json_name_aux c,\n tactic.trace format!\"[has_from_json_context.decl] c_nm: {c_nm}\",\n if c_nm = `context.decl.mvar_decl then context.decl.mvar_decl <$> fn₁ args.head else\n if c_nm = `context.decl.univ_mvar_decl then context.decl.univ_mvar_decl <$> fn₂ args.head else\n if c_nm = `context.decl.local_decl then context.decl.local_decl <$> fn₃ args.head else\n tactic.fail format!\"[has_from_json_context.decl] unexpected: {msg}\"\n | exc := tactic.fail format!\"[has_from_json_context.decl] unexpected: {exc}\"\n end\n⟩\n\nmeta instance : has_from_json (list context.decl) := has_from_json_list\nmeta instance has_from_json_list_name_tactic_tag : has_from_json (list (name × tactic.tag)) := has_from_json_list\n\nmeta instance : has_from_json tactic_state_data :=\nlet ⟨fn₁⟩ := (by apply_instance : has_from_json (list context.decl)) in\nlet ⟨fn₂⟩ := (by apply_instance : has_from_json (list (name × tactic.tag))) in\n⟨λ msg, match msg with\n | (json.array $ [c, json.array [decls_msg, goals_msg]]) := do\n (c_nm : name) ← has_from_json_name_aux c,\n tactic.trace format!\"[has_from_json_tactic_state_data] c_nm: {c_nm}\",\n if c_nm = `tactic_state_data.mk then tactic_state_data.mk <$> fn₁ decls_msg <*> fn₂ goals_msg else\n tactic.fail format!\"[has_from_json_tactic_state_data] unexpected: {msg}\"\n | exc := tactic.fail format!\"[has_from_json_tactic_state_data] unexpected: {exc}\"\n end\n⟩\n\n\nend instances\n\n-- convience functions and instances\n\nmeta instance mvar_decl_has_to_string : has_to_format mvar_decl := \n⟨ λ d, format! \"{{mvar_decl .\\nunique_name := {d.unique_name},\\npp_name := {d.pp_name},\\nexpr_type := {d.expr_type},\\nlocal_cxt := {d.local_cxt},\\ntype := {d.type},\\nassignment := {d.assignment},\\n}\" ⟩ \n\nmeta instance univ_mvar_decl_has_to_string : has_to_format univ_mvar_decl := \n⟨ λ d, format! \"{{univ_mvar_decl .\\nunique_name := {d.unique_name},\\nassignment := {d.assignment},\\n}\" ⟩ \n\nmeta instance local_decl_has_to_string : has_to_format local_decl := \n⟨ λ d, format! \"{{local_decl .\\nunique_name := {d.unique_name},\\npp_name := {d.pp_name},\\ntype := {d.type},\\nvalue := {d.value},\\nbi := {repr d.bi},\\nidx := {d.idx},\\n}\" ⟩ \n\nmeta instance local_decl2_has_to_string : has_to_format local_decl2 := \n⟨ λ d, format! \"{{local_decl2 .\\nunique_name := {d.unique_name},\\npp_name := {d.pp_name},\\nexpr_type := {d.expr_type},\\nbi := {repr d.bi},\\ntype := {d.type},\\nprev := {d.prev}\\n},\\nfrozen := {d.frozen},\\nld := {d.ld}\" ⟩ \n\nmeta def context.decl.unique_name : context.decl -> name\n| (context.decl.mvar_decl d) := d.unique_name\n| (context.decl.univ_mvar_decl d) := d.unique_name\n| (context.decl.local_decl d) := d.unique_name\n\nmeta instance context_decl_has_to_string : has_to_format context.decl := \n⟨ λ d, match d with\n| context.decl.mvar_decl d := format! \"{d}\"\n| context.decl.univ_mvar_decl d := format! \"{d}\"\n| context.decl.local_decl d := format! \"{d}\"\nend ⟩\n\nmeta instance context_has_to_string : has_to_format context := \n⟨ λ cxt, format! \"{cxt.decls}\" ⟩\n\n\n-- constructors\n\nmeta def context.empty : context := \n{ decls := [], names := mk_name_set }\n\nmeta def context.mk1 (d : context.decl) : context :=\n{ decls := [d], names := name_set.of_list [d.unique_name]}\n\nmeta def context.append (cxt1 : context) (cxt2 : context) : context :=\n{ decls := cxt1.decls ++ (cxt2.decls.filter (λ d, ¬ (cxt1.names.contains d.unique_name))),\n names := cxt1.names.fold cxt2.names $ λ n ns, ns.insert n\n}\n\nmeta instance context.has_append : has_append context := ⟨ context.append ⟩\n\n/- Get univ metavariables level expression tree.-/\nmeta def context.process_level : level -> tactic context\n| level.zero := return context.empty\n| (level.succ lvl) := context.process_level lvl\n| (level.max lvl1 lvl2) := do\n cxt1 <- context.process_level lvl1,\n cxt2 <- context.process_level lvl2,\n return (cxt1 ++ cxt2)\n| (level.imax lvl1 lvl2) := do\n cxt1 <- context.process_level lvl1,\n cxt2 <- context.process_level lvl2,\n return (cxt1 ++ cxt2)\n| (level.param _) := return context.empty\n| lvl@(level.mvar nm) := do\n ass <- optional (tactic.get_univ_assignment lvl),\n let univ_decl := context.decl.univ_mvar_decl {\n unique_name := nm,\n assignment := ass\n },\n return (context.mk1 univ_decl)\n\ndef find_prev {α : Type} [decidable_eq α] (a : α) : list α -> option α\n| [] := none\n| [b] := none\n| (b :: c :: ls) := if c = a then some b else find_prev (c :: ls)\n\n/- Get metavariables and local constants inside an expression tree, follow recursively. -/\nmeta def context.process_expr : expr -> local_context -> tactic context\n| (expr.var _) _ := return context.empty\n| (expr.sort lvl) _ := context.process_level lvl\n| (expr.const _ lvls) _ := do\n cxts <- lvls.mmap context.process_level,\n let cxt := cxts.foldl context.append context.empty,\n return cxt\n| mv@(expr.mvar unique_nm pp_nm tp) _ := do\n lcxt <- type_context.run $ type_context.get_context mv,\n let local_cxt := lcxt.to_list,\n cxts <- local_cxt.mmap (λ e, e.unfold_macros >>= flip context.process_expr lcxt),\n let cxt := cxts.foldl context.append context.empty,\n tp_cxt <- tp.unfold_macros >>= flip context.process_expr lcxt,\n mv_type <- optional (tactic.infer_type mv),\n tp_cxt2 <- match mv_type with\n | (some e) := e.unfold_macros >>= flip context.process_expr lcxt\n | none := return context.empty\n end,\n assignment <- optional (tactic.get_assignment mv),\n ass_cxt <- match assignment with\n | (some e) := e.unfold_macros >>= flip context.process_expr lcxt\n | none := return context.empty\n end,\n let mv_dec := context.decl.mvar_decl {\n unique_name := unique_nm,\n pp_name := pp_nm,\n expr_type := tp,\n local_cxt := local_cxt,\n type := mv_type,\n assignment := assignment\n },\n return $ cxt ++ tp_cxt ++ tp_cxt2 ++ ass_cxt ++ (context.mk1 mv_dec)\n| lconst@(expr.local_const unique_nm pp_nm bi tp) lcxt := do\n tp_cxt <- tp.unfold_macros >>= flip context.process_expr lcxt,\n loc_type <- optional (tactic.infer_type lconst),\n tp_cxt2 <- match loc_type with\n | (some e) := e.unfold_macros >>= flip context.process_expr lcxt\n | none := return context.empty\n end,\n let ld := lcxt.get_local_decl unique_nm,\n tp_cxt3 <- match ld with\n | (some ld) := ld.type.unfold_macros >>= flip context.process_expr lcxt\n | none := return context.empty\n end,\n value_cxt <- match ld with\n | (some ld) := match ld.value with\n | (some e) := e.unfold_macros >>= flip context.process_expr lcxt\n | none := return context.empty\n end\n | none := return context.empty\n end,\n let (prev : option expr) := find_prev lconst lcxt.to_list,\n let prev_id := match prev with\n | some (expr.local_const id _ _ _) := some id\n | _ := none\n end,\n frozen_instances_opt <- tactic.frozen_local_instances,\n let frozen := match frozen_instances_opt with\n | none := ff\n | some frozen_instances := frozen_instances.any (λ e, e.local_uniq_name_option = some unique_nm)\n end,\n let loc_dec := context.decl.local_decl {\n unique_name := unique_nm,\n pp_name := pp_nm,\n expr_type := tp,\n bi := bi,\n type := loc_type,\n prev := prev_id,\n frozen := frozen,\n ld := lcxt.get_local_decl unique_nm,\n },\n return $ tp_cxt ++ tp_cxt2 ++ tp_cxt3 ++ value_cxt ++ (context.mk1 loc_dec)\n| (expr.app expr1 expr2) lcxt := do\n cxt1 <- expr1.unfold_macros >>= flip context.process_expr lcxt,\n cxt2 <- expr2.unfold_macros >>= flip context.process_expr lcxt,\n return (cxt1 ++ cxt2)\n| (expr.lam _ _ expr1 expr2) lcxt := do\n cxt1 <- expr1.unfold_macros >>= flip context.process_expr lcxt,\n cxt2 <- expr2.unfold_macros >>= flip context.process_expr lcxt,\n return (cxt1 ++ cxt2)\n| (expr.pi _ _ expr1 expr2) lcxt := do\n cxt1 <- expr1.unfold_macros >>= flip context.process_expr lcxt,\n cxt2 <- expr2.unfold_macros >>= flip context.process_expr lcxt,\n return (cxt1 ++ cxt2)\n| (expr.elet _ expr1 expr2 expr3) lcxt := do\n cxt1 <- expr1.unfold_macros >>= flip context.process_expr lcxt,\n cxt2 <- expr2.unfold_macros >>= flip context.process_expr lcxt,\n cxt3 <- expr3.unfold_macros >>= flip context.process_expr lcxt,\n return (cxt1 ++ cxt2 ++ cxt3)\n| (expr.macro md deps) _ := tactic.fail format!\"[process_expr] can't handle macro {expr.macro_def_name md}\"\n\nmeta def context.get : tactic context := do\n lcxt <- type_context.run $ type_context.get_local_context,\n mvs <- tactic.get_goals,\n cxts <- mvs.mmap (λ e, e.unfold_macros >>= flip context.process_expr lcxt),\n let cxt := cxts.foldl context.append context.empty,\n return cxt\n\nmeta def tactic_state_data.get : tactic tactic_state_data := do\n cxt <- context.get,\n gs <- tactic.get_goals,\n goals <- gs.mmap $ λ g, do {\n nm <- g.mvar_uniq_name_option,\n tag <- tactic.get_tag g,\n return (nm, tag)\n },\n return { \n decls := cxt.decls,\n goals := goals\n }\n\n-- tracing code for debugging\n\nmeta def trace_context : tactic unit := do\n -- cxt <- context.get,\n cxt ← tactic_state_data.get,\n has_to_tactic_json.to_tactic_json cxt >>= tactic.trace\n\n\n-- rebuilding the context\n\nmeta def swap_univ_mvs (nm_map : name_map context.decl) : level → tactic level\n| (level.mvar nm) := do {\n d <- nm_map.find nm,\n nm' <- match d with\n | (context.decl.univ_mvar_decl dd) := return dd.unique_name\n | _ := tactic.failed\n end,\n return $ level.mvar nm'\n}\n| (level.max lvl1 lvl2) := do {\n lvl1' <- swap_univ_mvs lvl1,\n lvl2' <- swap_univ_mvs lvl2,\n return $ level.max lvl1' lvl2'\n}\n| (level.imax lvl1 lvl2) := do {\n lvl1' <- swap_univ_mvs lvl1,\n lvl2' <- swap_univ_mvs lvl2,\n return $ level.imax lvl1' lvl2'\n}\n| (level.succ lvl) := do {\n lvl' <- swap_univ_mvs lvl,\n return $ level.succ lvl'\n}\n| lvl := return lvl --level.zero and level.param\n\nmeta def swap_mvs (nm_map : name_map context.decl) : expr -> tactic expr\n| (expr.mvar unique_nm pp_nm tp) := do {\n d <- nm_map.find unique_nm,\n (unique_nm', tp') <- match d with\n | (context.decl.mvar_decl dd) := return (dd.unique_name, dd.expr_type)\n | _ := tactic.failed\n end,\n return $ expr.mvar unique_nm pp_nm tp'\n}\n| (expr.local_const unique_nm pp_nm bi tp) := do {\n d <- nm_map.find unique_nm,\n (unique_nm', tp') <- match d with\n | (context.decl.local_decl dd) := return (dd.unique_name, dd.expr_type)\n | _ := tactic.failed\n end,\n return $ expr.local_const unique_nm' pp_nm bi tp'\n}\n| e@(expr.var _) := return e\n| (expr.sort lvl) := do {\n lvl' <- swap_univ_mvs nm_map lvl,\n return $ expr.sort lvl'\n}\n| (expr.const nm lvls) := do {\n lvls' <- lvls.mmap (swap_univ_mvs nm_map),\n return $ expr.const nm lvls'\n}\n| (expr.app expr1 expr2) := do {\n expr1' <- swap_mvs expr1.unfold_string_macros.erase_annotations,\n expr2' <- swap_mvs expr2.unfold_string_macros.erase_annotations,\n return $ expr.app expr1' expr2'\n}\n| (expr.lam nm bi expr1 expr2) := do {\n expr1' <- swap_mvs expr1.unfold_string_macros.erase_annotations,\n expr2' <- swap_mvs expr2.unfold_string_macros.erase_annotations,\n return $ expr.lam nm bi expr1' expr2'\n}\n| (expr.pi nm bi expr1 expr2) := do {\n expr1' <- swap_mvs expr1.unfold_string_macros.erase_annotations,\n expr2' <- swap_mvs expr2.unfold_string_macros.erase_annotations,\n return $ expr.pi nm bi expr1' expr2'\n}\n| (expr.elet nm expr1 expr2 expr3) := do {\n expr1' <- swap_mvs expr1.unfold_string_macros.erase_annotations,\n expr2' <- swap_mvs expr2.unfold_string_macros.erase_annotations,\n expr3' <- swap_mvs expr3.unfold_string_macros.erase_annotations,\n return $ expr.elet nm expr1' expr2' expr3'\n}\n| (expr.macro _ _) := tactic.fail \"[swap_mvs] can't handle macros yet\"\n\n/- A better constructor for locals which covers \nfrozen status and assignments. -/\nmeta def local_context.mk_local2 (pretty_name : name) (type : expr) (bi : binder_info) (frozen : bool) (assignment : option expr) (lcxt : local_context) : tactic (expr × local_context) := do\n-- capture state\ns <- tactic.read,\n-- there are a few ways to add to local context, \n-- the most direct being local_context.mk_local\n-- however that doesn't handle assignments or frozen locals,\n-- so we are setting the local context as the context of a goal\n-- and using intro to push a new hypothesis onto the stack\ntarget <- match (assignment, bi) with\n| (none, bi) := \npure $ expr.pi pretty_name bi type `(true)\n| (some ass, binder_info.default) :=\npure $ expr.elet pretty_name type ass `(true)\n| _ := tactic.fail \"Unreachable state reached\" \nend,\ngoal_mv <- type_context.run $ type_context.mk_mvar \"tmp_goal\" target lcxt,\ntactic.set_goals [goal_mv],\nnew_local <- tactic.intro_core pretty_name,\nif frozen then\n tactic.freeze_local_instances\nelse\n pure (),\nnew_lcxt <- type_context.run $ type_context.get_local_context,\n-- reset the state back to the beginning\n_root_.set_state s,\n\nreturn (new_local, new_lcxt)\n\nmeta def build_context_aux (nm_map : name_map context.decl) (loc_map : name_map local_context): context.decl -> tactic ((name_map context.decl) × (name_map local_context) × context.decl)\n| (context.decl.univ_mvar_decl d) := do\n -- update dependencies\n new_assignment <- d.assignment.mmap (swap_univ_mvs nm_map),\n -- create mvar\n new_univ_mvar <- tactic.mk_meta_univ,\n new_uid <- match new_univ_mvar with\n | level.mvar nm := return nm\n | _ := tactic.failed\n end,\n -- assign mvar\n match new_assignment with \n | some lvl := type_context.run $ type_context.level.assign new_univ_mvar lvl\n | none := return ()\n end,\n -- return new decl\n let new_decl := context.decl.univ_mvar_decl {\n unique_name := new_uid,\n assignment := new_assignment\n },\n let new_nmap := nm_map.insert d.unique_name new_decl,\n return (new_nmap, loc_map, new_decl)\n| (context.decl.local_decl d) := do\n -- update dependencies\n let pp_name := d.pp_name,\n new_type <- swap_mvs nm_map (d.type.get_or_else d.expr_type).unfold_string_macros.erase_annotations,\n let (new_lcxt_option : option local_context) := do {\n unique_name <- d.prev,\n loc_map.find unique_name\n },\n let new_lcxt := new_lcxt_option.get_or_else local_context.empty,\n ld <- d.ld,\n new_assignment <- ld.value.mmap ((swap_mvs nm_map) ∘ expr.unfold_string_macros ∘ expr.erase_annotations),\n -- create local \n (new_loc, new_lcxt) <- new_lcxt.mk_local2 pp_name new_type d.bi d.frozen new_assignment,\n (new_uid, new_tp) <- match new_loc with\n | expr.local_const nm _ bi tp := return (nm, tp)\n | _ := tactic.failed\n end,\n let (new_prev : option expr) := new_lcxt.fold (λ prev e, if e = new_loc then prev else some e) none,\n let new_prev_id := match new_prev with\n | some (expr.local_const id _ _ _) := some id\n | _ := none\n end,\n let new_decl := context.decl.local_decl {\n unique_name := new_uid,\n pp_name := pp_name,\n expr_type := new_tp,\n bi := d.bi,\n prev := new_prev_id,\n type := new_type,\n frozen := d.frozen,\n ld := new_lcxt.get_local_decl new_uid\n },\n let new_nmap := nm_map.insert d.unique_name new_decl,\n let new_loc_map := loc_map.insert d.unique_name new_lcxt,\n return (new_nmap, new_loc_map, new_decl)\n \n| (context.decl.mvar_decl d) := do\n -- update dependencies\n let pp_name := d.pp_name,\n new_type <- swap_mvs nm_map (d.type.get_or_else d.expr_type).unfold_string_macros.erase_annotations,\n let (new_lcxt_option : option local_context) := do {\n last <- d.local_cxt.last_option,\n unique_name <- last.local_uniq_name_option,\n loc_map.find unique_name\n },\n let new_lcxt := new_lcxt_option.get_or_else local_context.empty,\n new_assignment <- d.assignment.mmap ((swap_mvs nm_map) ∘ expr.unfold_string_macros ∘ expr.erase_annotations),\n -- create mvar\n new_mvar <- type_context.run $ type_context.mk_mvar pp_name new_type new_lcxt,\n (new_uid, new_tp) <- match new_mvar with\n | expr.mvar nm _ tp := return (nm, tp)\n | _ := tactic.failed\n end,\n -- assign mvar\n match new_assignment with \n | some e := type_context.run $ type_context.assign new_mvar e\n | none := return ()\n end,\n let new_decl := context.decl.mvar_decl {\n unique_name := new_uid,\n pp_name := pp_name,\n expr_type := new_tp,\n local_cxt := new_lcxt.to_list,\n type := new_type,\n assignment := new_assignment\n },\n let new_nmap := nm_map.insert d.unique_name new_decl,\n return (new_nmap, loc_map, new_decl)\n\nmeta def rebuild_context : (list context.decl) -> tactic ((name_map context.decl) × (name_map local_context))\n| [] := return (mk_name_map, mk_name_map)\n| (d :: ds) := do\n (nm_map, loc_map) <- rebuild_context ds,\n (nm_map, loc_map, _) <- build_context_aux nm_map loc_map d,\n return (nm_map, loc_map)\n\nmeta def mvar_id : expr -> tactic name\n| (expr.mvar uid _ _) := return uid\n| _ := tactic.fail \"Expecting mvar\"\n\nmeta def rebuild_tactic_state (ts : tactic_state_data) : tactic unit := do\n (nm_map, _) <- rebuild_context ts.decls.reverse,\n goals_and_tags <- ts.goals.mmap $ λ ⟨nm, tag⟩, do {\n d <- nm_map.find nm,\n nm' <- match d with\n | context.decl.mvar_decl dd := return dd.unique_name\n | _ := tactic.fail \"Expecting mvar_decl\"\n end,\n mvars <- type_context.run type_context.list_mvars,\n mv <- mvars.mfirst $ λ e, do {\n nm2 <- mvar_id e,\n if nm' = nm2 then return e else failure\n },\n return (mv, tag)\n },\n let goals := goals_and_tags.map prod.fst,\n tactic.set_goals goals,\n goals_and_tags.mmap $ λ ⟨g, tag⟩, do {\n tactic.enable_tags tt,\n tactic.set_tag g tag,\n tactic.enable_tags ff -- seems to be off by default\n },\n return ()\n\n-- for testing\n\nmeta def refresh_context : tactic unit := do\n cxt <- context.get,\n (nm_map, _) <- rebuild_context cxt.decls.reverse,\n gs <- tactic.get_goals,\n new_goals <- gs.mmap $ λ g, do {\n nm <- mvar_id g,\n d <- nm_map.find nm,\n tactic.trace (nm, d),\n nm' <- match d with\n | context.decl.mvar_decl dd := return dd.unique_name\n | _ := tactic.fail \"Expecting mvar_decl\"\n end,\n mvars <- type_context.run type_context.list_mvars,\n mv <- mvars.mfirst $ λ e, do {\n nm2 <- mvar_id e,\n if nm' = nm2 then return e else failure\n },\n return mv\n },\n tactic.set_goals new_goals\n\nmeta def refresh_tactic_state : tactic unit := do\n ts_data <- tactic_state_data.get,\n -- go into a clean tactic environment and build the tactic state\n ts <- tactic.unsafe_run_io $ io.run_tactic' $ do {\n rebuild_tactic_state ts_data,\n tactic.read -- return tactic state\n },\n -- set tactic state to new one\n _root_.set_state ts\n\n-- examples\n\nsection examples\n\n-- example (α : Type) (a : nat): a=a := begin\n-- trace_context,\n-- refresh_tactic_state,\n-- trace_context,\n-- induction a,\n-- trace_context,\n-- refresh_tactic_state, -- check that tags are still there\n-- trace_context,\n-- refl,\n-- refl,\n-- done,\n-- trace_context,\n-- end\n\n-- -- Debug\n-- example {α β γ : Type} --(f : α → β) (g : β → γ)\n-- : α :=\n-- begin\n-- trace_context,\n-- refresh_tactic_state,\n-- trace_context,\n-- end\n\n-- -- Frozen local instances\n-- def fish {α β γ} {m : Type → Type} [monad m] (f : m α → m β) (g : m β → m γ)\n-- : m α → m γ :=\n-- begin\n-- trace_context,\n-- refresh_tactic_state,\n-- trace_context,\n-- revert m, -- fails, `monad m` is a frozen instance\n-- revert f, -- succeeds\n-- revert α -- succeeds\n-- end\n\n-- example : let x := 0 in x=0 := begin\n-- intro,\n-- trace_context,\n-- refresh_tactic_state,\n-- trace_context,\n-- simp,\n-- done,\n-- end\n\nend examples\n", "meta": {"author": "jesse-michael-han", "repo": "lean-tpe-public", "sha": "87c7bb8dfb8271d8fcf917aae0e731600c4f4c6c", "save_path": "github-repos/lean/jesse-michael-han-lean-tpe-public", "path": "github-repos/lean/jesse-michael-han-lean-tpe-public/lean-tpe-public-87c7bb8dfb8271d8fcf917aae0e731600c4f4c6c/src/tactic_state.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41111086923216794, "lm_q2_score": 0.03210070405485706, "lm_q1q2_score": 0.013196948346956863}} {"text": "/-\nCopyright (c) 2017 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Mario Carneiro\n\nParallel computation of a computable sequence of computations by\na diagonal enumeration.\nThe important theorems of this operation are proven as\nterminates_parallel and exists_of_mem_parallel.\n(This operation is nondeterministic in the sense that it does not\nhonor sequence equivalence (irrelevance of computation time).)\n\n! This file was ported from Lean 3 source module data.seq.parallel\n! leanprover-community/mathlib commit a7e36e48519ab281320c4d192da6a7b348ce40ad\n! Please do not edit these lines, except to modify the commit id\n! if you have ported upstream changes.\n-/\nimport Mathbin.Data.Seq.Wseq\n\nuniverse u v\n\nnamespace Computation\n\n/- ./././Mathport/Syntax/Translate/Command.lean:224:11: unsupported: unusual advanced open style -/\n/- ./././Mathport/Syntax/Translate/Command.lean:224:11: unsupported: unusual advanced open style -/\nvariable {α : Type u} {β : Type v}\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\ndef Parallel.aux2 : List (Computation α) → Sum α (List (Computation α)) :=\n List.foldr\n (fun c o =>\n match o with\n | Sum.inl a => Sum.inl a\n | Sum.inr ls => rmap (fun c' => c'::ls) (destruct c))\n (Sum.inr [])\n#align computation.parallel.aux2 Computation.Parallel.aux2\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\ndef Parallel.aux1 :\n List (Computation α) × Wseq (Computation α) →\n Sum α (List (Computation α) × Wseq (Computation α))\n | (l, S) =>\n rmap\n (fun l' =>\n match Seq.destruct S with\n | none => (l', Seq.nil)\n | some (none, S') => (l', S')\n | some (some c, S') => (c::l', S'))\n (Parallel.aux2 l)\n#align computation.parallel.aux1 Computation.Parallel.aux1\n\n/-- Parallel computation of an infinite stream of computations,\n taking the first result -/\ndef parallel (S : Wseq (Computation α)) : Computation α :=\n corec Parallel.aux1 ([], S)\n#align computation.parallel Computation.parallel\n\ntheorem TerminatesParallel.aux :\n ∀ {l : List (Computation α)} {S c},\n c ∈ l → Terminates c → Terminates (corec Parallel.aux1 (l, S)) :=\n by\n have lem1 :\n ∀ l S, (∃ a : α, parallel.aux2 l = Sum.inl a) → terminates (corec parallel.aux1 (l, S)) :=\n by\n intro l S e\n cases' e with a e\n have : corec parallel.aux1 (l, S) = return a :=\n by\n apply destruct_eq_ret\n simp [parallel.aux1]\n rw [e]\n simp [rmap]\n rw [this]\n infer_instance\n intro l S c m T\n revert l S\n apply @terminates_rec_on _ _ c T _ _\n · intro a l S m\n apply lem1\n induction' l with c l IH generalizing m <;> simp at m\n · contradiction\n cases' m with e m\n · rw [← e]\n simp [parallel.aux2]\n cases' List.foldr parallel.aux2._match_1 (Sum.inr List.nil) l with a' ls\n exacts[⟨a', rfl⟩, ⟨a, rfl⟩]\n · cases' IH m with a' e\n simp [parallel.aux2]\n simp [parallel.aux2] at e\n rw [e]\n exact ⟨a', rfl⟩\n · intro s IH l S m\n have H1 : ∀ l', parallel.aux2 l = Sum.inr l' → s ∈ l' :=\n by\n induction' l with c l IH' generalizing m <;> intro l' e' <;> simp at m\n · contradiction\n cases' m with e m <;> simp [parallel.aux2] at e'\n · rw [← e] at e'\n cases' List.foldr parallel.aux2._match_1 (Sum.inr List.nil) l with a' ls <;>\n injection e' with e'\n rw [← e']\n simp\n · induction' e : List.foldr parallel.aux2._match_1 (Sum.inr List.nil) l with a' ls <;>\n rw [e] at e'\n · contradiction\n have := IH' m _ e\n simp [parallel.aux2] at e'\n cases destruct c <;> injection e' with h'\n rw [← h']\n simp [this]\n induction' h : parallel.aux2 l with a l'\n · exact lem1 _ _ ⟨a, h⟩\n · have H2 : corec parallel.aux1 (l, S) = think _ :=\n by\n apply destruct_eq_think\n simp [parallel.aux1]\n rw [h]\n simp [rmap]\n rw [H2]\n apply @Computation.think_terminates _ _ _\n have := H1 _ h\n rcases seq.destruct S with (_ | ⟨_ | c, S'⟩) <;> simp [parallel.aux1] <;> apply IH <;>\n simp [this]\n#align computation.terminates_parallel.aux Computation.TerminatesParallel.aux\n\ntheorem terminates_parallel {S : Wseq (Computation α)} {c} (h : c ∈ S) [T : Terminates c] :\n Terminates (parallel S) :=\n by\n suffices\n ∀ (n) (l : List (Computation α)) (S c),\n c ∈ l ∨ some (some c) = Seq.nth S n → Terminates c → Terminates (corec Parallel.aux1 (l, S))\n from\n let ⟨n, h⟩ := h\n this n [] S c (Or.inr h) T\n intro n; induction' n with n IH <;> intro l S c o T\n · cases' o with a a\n · exact terminates_parallel.aux a T\n have H : seq.destruct S = some (some c, _) :=\n by\n unfold seq.destruct Functor.map\n rw [← a]\n simp\n induction' h : parallel.aux2 l with a l' <;> have C : corec parallel.aux1 (l, S) = _\n · apply destruct_eq_ret\n simp [parallel.aux1]\n rw [h]\n simp [rmap]\n · rw [C]\n skip\n infer_instance\n · apply destruct_eq_think\n simp [parallel.aux1]\n rw [h, H]\n simp [rmap]\n · rw [C]\n apply @Computation.think_terminates _ _ _\n apply terminates_parallel.aux _ T\n simp\n · cases' o with a a\n · exact terminates_parallel.aux a T\n induction' h : parallel.aux2 l with a l' <;> have C : corec parallel.aux1 (l, S) = _\n · apply destruct_eq_ret\n simp [parallel.aux1]\n rw [h]\n simp [rmap]\n · rw [C]\n skip\n infer_instance\n · apply destruct_eq_think\n simp [parallel.aux1]\n rw [h]\n simp [rmap]\n · rw [C]\n apply @Computation.think_terminates _ _ _\n have TT : ∀ l', terminates (corec parallel.aux1 (l', S.tail)) :=\n by\n intro\n apply IH _ _ _ (Or.inr _) T\n rw [a]\n cases' S with f al\n rfl\n induction' e : seq.nth S 0 with o\n · have D : seq.destruct S = none := by\n dsimp [seq.destruct]\n rw [e]\n rfl\n rw [D]\n simp [parallel.aux1]\n have TT := TT l'\n rwa [seq.destruct_eq_nil D, seq.tail_nil] at TT\n · have D : seq.destruct S = some (o, S.tail) :=\n by\n dsimp [seq.destruct]\n rw [e]\n rfl\n rw [D]\n cases' o with c <;> simp [parallel.aux1, TT]\n#align computation.terminates_parallel Computation.terminates_parallel\n\ntheorem exists_of_mem_parallel {S : Wseq (Computation α)} {a} (h : a ∈ parallel S) :\n ∃ c ∈ S, a ∈ c :=\n by\n suffices\n ∀ C,\n a ∈ C →\n ∀ (l : List (Computation α)) (S),\n corec Parallel.aux1 (l, S) = C → ∃ c, (c ∈ l ∨ c ∈ S) ∧ a ∈ c\n from\n let ⟨c, h1, h2⟩ := this _ h [] S rfl\n ⟨c, h1.resolve_left id, h2⟩\n let F : List (Computation α) → Sum α (List (Computation α)) → Prop :=\n by\n intro l a\n cases' a with a l'\n exact ∃ c ∈ l, a ∈ c\n exact ∀ a', (∃ c ∈ l', a' ∈ c) → ∃ c ∈ l, a' ∈ c\n have lem1 : ∀ l : List (Computation α), F l (parallel.aux2 l) :=\n by\n intro l\n induction' l with c l IH <;> simp [parallel.aux2]\n · intro a h\n rcases h with ⟨c, hn, _⟩\n exact False.elim hn\n · simp [parallel.aux2] at IH\n cases' List.foldr parallel.aux2._match_1 (Sum.inr List.nil) l with a ls <;>\n simp [parallel.aux2]\n · rcases IH with ⟨c', cl, ac⟩\n refine' ⟨c', Or.inr cl, ac⟩\n · induction' h : destruct c with a c' <;> simp [rmap]\n · refine' ⟨c, List.mem_cons_self _ _, _⟩\n rw [destruct_eq_ret h]\n apply ret_mem\n · intro a' h\n rcases h with ⟨d, dm, ad⟩\n simp at dm\n cases' dm with e dl\n · rw [e] at ad\n refine' ⟨c, List.mem_cons_self _ _, _⟩\n rw [destruct_eq_think h]\n exact think_mem ad\n · cases' IH a' ⟨d, dl, ad⟩ with d dm\n cases' dm with dm ad\n exact ⟨d, Or.inr dm, ad⟩\n intro C aC\n refine' mem_rec_on aC _ fun C' IH => _ <;> intro l S e <;> have e' := congr_arg destruct e <;>\n have := lem1 l <;>\n simp [parallel.aux1] at e' <;>\n cases' parallel.aux2 l with a' l' <;>\n injection e' with h'\n · rw [h'] at this\n rcases this with ⟨c, cl, ac⟩\n exact ⟨c, Or.inl cl, ac⟩\n · induction' e : seq.destruct S with a <;> rw [e] at h'\n ·\n exact\n let ⟨d, o, ad⟩ := IH _ _ h'\n let ⟨c, cl, ac⟩ := this a ⟨d, o.resolve_right (wseq.not_mem_nil _), ad⟩\n ⟨c, Or.inl cl, ac⟩\n · cases' a with o S'\n cases' o with c <;> simp [parallel.aux1] at h' <;> rcases IH _ _ h' with ⟨d, dl | dS', ad⟩\n ·\n exact\n let ⟨c, cl, ac⟩ := this a ⟨d, dl, ad⟩\n ⟨c, Or.inl cl, ac⟩\n · refine' ⟨d, Or.inr _, ad⟩\n rw [seq.destruct_eq_cons e]\n exact seq.mem_cons_of_mem _ dS'\n · simp at dl\n cases' dl with dc dl\n · rw [dc] at ad\n refine' ⟨c, Or.inr _, ad⟩\n rw [seq.destruct_eq_cons e]\n apply seq.mem_cons\n ·\n exact\n let ⟨c, cl, ac⟩ := this a ⟨d, dl, ad⟩\n ⟨c, Or.inl cl, ac⟩\n · refine' ⟨d, Or.inr _, ad⟩\n rw [seq.destruct_eq_cons e]\n exact seq.mem_cons_of_mem _ dS'\n#align computation.exists_of_mem_parallel Computation.exists_of_mem_parallel\n\ntheorem map_parallel (f : α → β) (S) : map f (parallel S) = parallel (S.map (map f)) :=\n by\n refine'\n eq_of_bisim\n (fun c1 c2 =>\n ∃ l S,\n c1 = map f (corec parallel.aux1 (l, S)) ∧\n c2 = corec parallel.aux1 (l.map (map f), S.map (map f)))\n _ ⟨[], S, rfl, rfl⟩\n intro c1 c2 h;\n exact\n match c1, c2, h with\n | _, _, ⟨l, S, rfl, rfl⟩ => by\n clear _match\n have : parallel.aux2 (l.map (map f)) = lmap f (rmap (List.map (map f)) (parallel.aux2 l)) :=\n by\n simp [parallel.aux2]\n induction' l with c l IH <;> simp\n rw [IH]\n cases List.foldr parallel.aux2._match_1 (Sum.inr List.nil) l <;> simp [parallel.aux2]\n cases destruct c <;> simp\n simp [parallel.aux1]\n rw [this]\n cases' parallel.aux2 l with a l' <;> simp\n apply S.rec_on _ (fun c S => _) fun S => _ <;> simp <;> simp [parallel.aux1] <;>\n exact ⟨_, _, rfl, rfl⟩\n#align computation.map_parallel Computation.map_parallel\n\ntheorem parallel_empty (S : Wseq (Computation α)) (h : S.headI ~> none) : parallel S = empty _ :=\n eq_empty_of_not_terminates fun ⟨⟨a, m⟩⟩ =>\n by\n let ⟨c, cs, ac⟩ := exists_of_mem_parallel m\n let ⟨n, nm⟩ := Wseq.exists_nth_of_mem cs\n let ⟨c', h'⟩ := Wseq.head_some_of_nth_some nm\n injection h h'\n#align computation.parallel_empty Computation.parallel_empty\n\n-- The reason this isn't trivial from exists_of_mem_parallel is because it eliminates to Sort\ndef parallelRec {S : Wseq (Computation α)} (C : α → Sort v) (H : ∀ s ∈ S, ∀ a ∈ s, C a) {a}\n (h : a ∈ parallel S) : C a :=\n by\n let T : wseq (Computation (α × Computation α)) := S.map fun c => c.map fun a => (a, c)\n have : S = T.map (map fun c => c.1) :=\n by\n rw [← wseq.map_comp]\n refine' (wseq.map_id _).symm.trans (congr_arg (fun f => wseq.map f S) _)\n funext c\n dsimp [id, Function.comp]\n rw [← map_comp]\n exact (map_id _).symm\n have pe := congr_arg parallel this\n rw [← map_parallel] at pe\n have h' := h\n rw [pe] at h'\n haveI : terminates (parallel T) := (terminates_map_iff _ _).1 ⟨⟨_, h'⟩⟩\n induction' e : get (parallel T) with a' c\n have : a ∈ c ∧ c ∈ S := by\n rcases exists_of_mem_map h' with ⟨d, dT, cd⟩\n rw [get_eq_of_mem _ dT] at e\n cases e\n dsimp at cd\n cases cd\n rcases exists_of_mem_parallel dT with ⟨d', dT', ad'⟩\n rcases wseq.exists_of_mem_map dT' with ⟨c', cs', e'⟩\n rw [← e'] at ad'\n rcases exists_of_mem_map ad' with ⟨a', ac', e'⟩\n injection e' with i1 i2\n constructor\n rwa [i1, i2] at ac'\n rwa [i2] at cs'\n cases' this with ac cs\n apply H _ cs _ ac\n#align computation.parallel_rec Computation.parallelRec\n\ntheorem parallel_promises {S : Wseq (Computation α)} {a} (H : ∀ s ∈ S, s ~> a) : parallel S ~> a :=\n fun a' ma' =>\n let ⟨c, cs, ac⟩ := exists_of_mem_parallel ma'\n H _ cs ac\n#align computation.parallel_promises Computation.parallel_promises\n\ntheorem mem_parallel {S : Wseq (Computation α)} {a} (H : ∀ s ∈ S, s ~> a) {c} (cs : c ∈ S)\n (ac : a ∈ c) : a ∈ parallel S := by\n haveI := terminates_of_mem ac <;> haveI := terminates_parallel cs <;>\n exact mem_of_promises _ (parallel_promises H)\n#align computation.mem_parallel Computation.mem_parallel\n\ntheorem parallel_congr_lem {S T : Wseq (Computation α)} {a} (H : S.LiftRel Equiv T) :\n (∀ s ∈ S, s ~> a) ↔ ∀ t ∈ T, t ~> a :=\n ⟨fun h1 t tT =>\n let ⟨s, sS, se⟩ := Wseq.exists_of_liftRel_right H tT\n (promises_congr se _).1 (h1 _ sS),\n fun h2 s sS =>\n let ⟨t, tT, se⟩ := Wseq.exists_of_liftRel_left H sS\n (promises_congr se _).2 (h2 _ tT)⟩\n#align computation.parallel_congr_lem Computation.parallel_congr_lem\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\n-- The parallel operation is only deterministic when all computation paths lead to the same value\ntheorem parallel_congr_left {S T : Wseq (Computation α)} {a} (h1 : ∀ s ∈ S, s ~> a)\n (H : S.LiftRel Equiv T) : parallel S ~ parallel T :=\n let h2 := (parallel_congr_lem H).1 h1\n fun a' =>\n ⟨fun h => by\n have aa := parallel_promises h1 h <;> rw [← aa] <;> rw [← aa] at h <;>\n exact\n let ⟨s, sS, as⟩ := exists_of_mem_parallel h\n let ⟨t, tT, st⟩ := wseq.exists_of_lift_rel_left H sS\n let aT := (st _).1 as\n mem_parallel h2 tT aT,\n fun h => by\n have aa := parallel_promises h2 h <;> rw [← aa] <;> rw [← aa] at h <;>\n exact\n let ⟨s, sS, as⟩ := exists_of_mem_parallel h\n let ⟨t, tT, st⟩ := wseq.exists_of_lift_rel_right H sS\n let aT := (st _).2 as\n mem_parallel h1 tT aT⟩\n#align computation.parallel_congr_left Computation.parallel_congr_left\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\ntheorem parallel_congr_right {S T : Wseq (Computation α)} {a} (h2 : ∀ t ∈ T, t ~> a)\n (H : S.LiftRel Equiv T) : parallel S ~ parallel T :=\n parallel_congr_left ((parallel_congr_lem H).2 h2) H\n#align computation.parallel_congr_right Computation.parallel_congr_right\n\nend Computation\n\n", "meta": {"author": "leanprover-community", "repo": "mathlib3port", "sha": "62505aa236c58c8559783b16d33e30df3daa54f4", "save_path": "github-repos/lean/leanprover-community-mathlib3port", "path": "github-repos/lean/leanprover-community-mathlib3port/mathlib3port-62505aa236c58c8559783b16d33e30df3daa54f4/Mathbin/Data/Seq/Parallel.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3415824860330003, "lm_q2_score": 0.03846619022711134, "lm_q1q2_score": 0.013139376885994992}} {"text": "/-\nCopyright (c) 2018 Johannes Hölzl. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Johannes Hölzl\n\nMonotone version of 1-point elimination for ∃ (and ∀).\n\n `∃x, t[x, R x a] ~> t[a, rfl]`\n\nwith the (reflexive) relation `R`, and `t` is monotone in `R`:\n `∀x y, R x y → t x → t y`.\n\nThen\n (∃x, R x a ∧ p x) ↔ p a\nthen\n assume h : p a, ⟨a, h, R.refl a⟩\nand\n assume ⟨x, hx, hxa⟩, mono x a hxa hx\n\nOr with the following dependent monotonicity:\n `∀x y (h : R x y), t x h → t y R.refl`.\n\nThen\n (∃x, ∃h:R x a, p x h) ↔ p a R.refl\nthen\n assume h : p a R.refl, ⟨a, h, R.refl a⟩\nand\n assume ⟨x, hx, hxa⟩, mono x a hxa hx\n\n-/\nimport simp_loop.conv\n\ninductive bintree (α : Type*)\n| leaf (a : α) : bintree\n| node (l r : bintree) : bintree\n\ndef list.dedup {α : Type*} [decidable_eq α] : list α → list α\n| [] := []\n| (x :: xs) := (if x ∈ xs then xs.dedup else x :: xs.dedup)\n\nnamespace bintree\nvariables {α : Type*} {β : Type*}\n\ndef pos := list bool\n\ndef left : bintree α → bintree α\n| (leaf a) := leaf a\n| (node l r) := l\n\ndef right : bintree α → bintree α\n| (leaf a) := leaf a\n| (node l r) := r\n\ndef at_pos : pos → bintree α → bintree α\n| [] t := t\n| (ff :: p) t := at_pos p (left t)\n| (tt :: p) t := at_pos p (right t)\n\ndef map (f : α → β) : bintree α → bintree β\n| (leaf a) := leaf (f a)\n| (node l r) := node (map l) (map r)\n\ndef mmap {m : Type* → Type*} [monad m] (f : α → m β) : bintree α → m (bintree β)\n| (leaf a) := leaf <$> f a\n| (node l r) := node <$> mmap l <*> mmap r\n\nend bintree\n\n\ndef monotone {α : Sort*} (r : α → α → Prop) (p : α → Prop) : Prop :=\n∀x y, r x y → p x → p y\n\nlemma monotone_eq {α : Type*} (p : α → Prop) : monotone (=) p :=\nassume x y h, h ▸ id\n\n-- do we/want need a dependent version?\nlemma exists_elim_rel {α : Sort*} {r : α → α → Prop} {p : α → Prop} {a : α} [is_refl α r]\n (h : monotone r p) :\n (∃x, r x a ∧ p x) ↔ p a :=\n⟨assume ⟨x, hxa, hx⟩, h x a hxa hx, assume ha, ⟨a, is_refl.refl r a, ha⟩⟩\n\nlemma ex_extend {α : Type*} {p : α → Prop} : (∃a, p a) ↔ (∃a, p a ∧ true) :=\n⟨assume ⟨a, ha⟩, ⟨a, ha, ⟨⟩⟩, assume ⟨a, ha, ⟨⟩⟩, ⟨a, ha⟩⟩\n\nlemma l_eq {p E : Prop} : (p ∧ E) ↔ (E ∧ p) :=\nand_comm _ _\nlemma l_ex {p E : Prop} {r : E → Prop} : (p ∧ (∃h:E, r h)) ↔ (∃h:E, p ∧ r h) :=\n⟨λ⟨h, e, r⟩, ⟨e, h, r⟩, λ⟨e, h, r⟩, ⟨h, e, r⟩⟩\nlemma l_cn {p q E : Prop} : (p ∧ (E ∧ q)) ↔ (E ∧ (p ∧ q)) :=\n⟨λ⟨h, e, r⟩, ⟨e, h, r⟩, λ⟨e, h, r⟩, ⟨h, e, r⟩⟩\nlemma r_eq {p E : Prop} : (E ∧ p) ↔ (E ∧ p) :=\niff.refl _\nlemma r_ex {p E : Prop} {r : E → Prop} : ((∃h:E, r h) ∧ p) ↔ (∃h:E, r h ∧ p) :=\n⟨λ⟨⟨e, r⟩, h⟩, ⟨e, r, h⟩, λ⟨e, r, h⟩, ⟨⟨e, r⟩, h⟩⟩\nlemma r_cn {p q E : Prop} : ((E ∧ q) ∧ p) ↔ (E ∧ (q ∧ p)) :=\n⟨λ⟨⟨e, r⟩, h⟩, ⟨e, r, h⟩, λ⟨e, r, h⟩, ⟨⟨e, r⟩, h⟩⟩\nlemma e_eq_Prop {p E : Prop} : (∃a:p, E) ↔ (E ∧ p) :=\n⟨λ⟨a, h⟩, ⟨h, a⟩, λ⟨h, a⟩, ⟨a, h⟩⟩\nlemma e_eq {α : Sort*} {E : Prop} : (∃a:α, E) ↔ (E ∧ ∃a:α, true) :=\n⟨λ⟨a, h⟩, ⟨h, ⟨a, ⟨⟩⟩⟩, λ⟨h, ⟨a, _⟩⟩, ⟨a, h⟩⟩\nlemma e_ex {α : Sort*} {E : Prop} {s : E → α → Prop} : (∃a:α, ∃h:E, s h a) ↔ (∃h:E, ∃a:α, s h a) :=\n⟨λ⟨a, h, t⟩, ⟨h, a, t⟩, λ⟨a, h, t⟩, ⟨h, a, t⟩⟩\nlemma e_cn {α : Sort*} {E : Prop} {t : α → Prop} : (∃a:α, E ∧ t a) ↔ (E ∧ (∃a:α, t a)) :=\n⟨λ⟨a, e, t⟩, ⟨e, ⟨a, t⟩⟩, λ⟨e, ⟨a, t⟩⟩, ⟨a, e, t⟩⟩\n\nlemma l_congr {p q r : Prop} (h : q ↔ r) : p ∧ q ↔ p ∧ r :=\nand_congr (iff.refl p) h\nlemma r_congr {p q r : Prop} (h : q ↔ r) : q ∧ p ↔ r ∧ p :=\nand_congr h (iff.refl p)\nlemma ex_congr {α : Sort*} {p q : α → Prop} (h : ∀a, p a ↔ q a) : (∃a, p a) ↔ (∃a, q a) :=\nexists_congr h\n\nlemma comm_l {α : Sort*} {p : Prop} {q : α → Prop} : p ∧ (∃a, q a) ↔ ∃a, p ∧ q a :=\n⟨λ⟨a, hq, hp⟩, ⟨hq, ⟨a, hp⟩⟩, λ ⟨hq, ⟨a, hp⟩⟩, ⟨a, hq, hp⟩⟩\nlemma comm_r {α : Sort*} {p : Prop} {q : α → Prop} : (∃a, q a) ∧ p ↔ ∃a, q a ∧ p :=\n⟨λ ⟨⟨a, hp⟩, hq⟩, ⟨a, hp, hq⟩, λ⟨a, hp, hq⟩, ⟨⟨a, hp⟩, hq⟩⟩\nlemma comm_ex {α : Sort*} {β : Sort*} {p : α → β → Prop} : (∃a b, p a b) ↔ (∃b a, p a b) :=\n⟨λ⟨a, ⟨b, h⟩⟩, ⟨b, ⟨a, h⟩⟩, λ⟨a, ⟨b, h⟩⟩, ⟨b, ⟨a, h⟩⟩⟩\n\nnamespace simp_loop\nopen conv_t tactic expr\n\nmeta inductive info\n| binder (v : expr) (dependent : bool) | operator (side : bool)\n\nnamespace info\nopen format\nmeta instance : has_to_format info :=\n⟨λi, match i with\n| info.binder v d := to_fmt \"binder \" ++ to_fmt v ++ \" \" ++ to_fmt d\n| info.operator s := to_fmt \"operator \" ++ to_fmt s\nend⟩\nend info\n\nmeta inductive norm_form\n| eq | ex | cn\n\nnamespace norm_form\nopen format\nmeta instance : has_to_format norm_form :=\n⟨λi, match i with\n| norm_form.eq := to_fmt \"eq\"\n| norm_form.ex := to_fmt \"ex\"\n| norm_form.cn := to_fmt \"cn\"\nend⟩\nend norm_form\n\nmeta def congr_ex {α} (c : conv α) : conv α := congr_binder ``ex_congr (λ_, c)\n\nmeta def congr {α} (c : conv α) : info → conv α\n| (info.binder _ _) := congr_ex c\n| (info.operator tt) := congr_simple ``r_congr c\n| (info.operator ff) := congr_simple ``l_congr c\n\nmeta def apply_norm (n_eq n_ex n_cn : list name) : norm_form → conv norm_form\n| norm_form.eq := do n_eq.mfirst apply_const, return norm_form.cn\n| norm_form.ex := do n_ex.mfirst apply_const, return norm_form.ex\n| norm_form.cn := do n_cn.mfirst apply_const, return norm_form.cn\n\nmeta def analyse (chk : expr → list expr → expr → bool)\n (v : expr) (deps : list expr) : expr → tactic (option $ list $ info × expr)\n| `(@Exists %%α %%p) := if chk v deps α then\n return none\n else do\n (lam pp_n bi domain body) ← return p | return (some []),\n x ← mk_local' pp_n bi domain,\n return [(info.binder x (deps.any $ λv, v.occurs α), body.instantiate_var x)]\n| `(%%p ∧ %%q) := return [(info.operator tt, p), (info.operator ff, q)]\n| t := return $ if chk v deps t then none else some []\n\nmeta def find (chk : expr → list expr → expr → bool)\n (v : expr) : list expr → expr → tactic (list $ list info) | deps e := do\nsome is ← analyse chk v deps e | return [[]],\niss ← is.mmap (λ⟨i, t⟩, do\n deps ← return $ match i with (info.binder v tt) := v :: deps | _ := deps end,\n iss ← find deps t,\n return $ iss.map $ λis, i :: is),\nreturn iss.join\n\nsection reorder\n\nprivate meta def reorder_dependent : list info → conv norm_form\n| [] := (do -- trace \"reorder_equality []\", trace_lhs,\n `(_ = _) ← lhs, return norm_form.eq) <|> return norm_form.ex\n| (i::xs) := do\n n ← congr (reorder_dependent xs) i,\n match i with\n | info.binder _ _ := apply_norm [``e_eq_Prop, ``e_eq] [``e_ex] [``e_cn] n\n | info.operator tt := apply_norm [``r_eq] [``r_ex] [``r_cn] n\n | info.operator ff := apply_norm [``l_eq] [``l_ex] [``l_cn] n\n end\n\nprivate meta def reorder_non_dependent : list info → conv (option (list info))\n| [] := return none\n| (i::is) := (do info.binder _ ff ← return i, return is) <|> (do\n some is' ← congr (reorder_non_dependent is) i | return none,\n r ← return $ match i with\n | info.binder _ _ := ``comm_ex\n | info.operator tt := ``comm_r\n | info.operator ff := ``comm_l\n end,\n apply_const r,\n return (i :: is'))\n\nmeta def reorder {α} (elim : norm_form → conv α) : list info → conv α | l := do\n-- trace (to_fmt \"reorder_and_elim \" ++ to_fmt l),\nsome l' ← congr_ex (reorder_non_dependent l) |\n (congr_ex (reorder_dependent l) >>= elim),\napply_const ``comm_ex,\ncongr_ex (reorder l')\n\nend reorder\n\nsection term_focus\n\n/-\n\nMove a term on one side of a relation using Galois connections:\n\nSymmetric rules:\n f x R y ↔ x Q g z\n\n ⟹ f x R t ↔ x Q t'\n ⟹ t Q g x ↔ t' R x\n\nInjectivity rules:\n f x R g y ↔ x Q y\n\n ⟹ f x R t ↔ x Q t'\n ⟹ t R g x ↔ t' Q x\n\nSplitting rules:\n f x R t ↔ (C₁ ∧ x Q₁ t₁) ∨ (C₂ ∧ x Q₂ t₂)\n\nSetup:\n\n* allow symmetric relations\n* apply the rules symmetrically\n* should we add dischargers for conditional rules, ala:\n 0 < R → x / R ≤ S ↔ x ≤ S * R\n or:\n x / R ≤ S ↔ (0 < R ∧ x ≤ S * R) ∨ (R < 0 ∧ S * R ≤ x) ∨ (R = 0 ∧ 0 ≤ S)\n This one doesn't work for monotone elimination as we have x ≤ S * R and S * R ≤ x case.\n* conditionals:\n ∀x n i : ℕ, x + n = i ↔ (n ≤ i ∧ x = i - n)\n ∀x n i : ℕ, x - n = i ↔ ((i = 0 ∧ x ≤ n) ∨ x = i + n)\n ∀x n i : ℕ, n - x = i ↔ ((i = 0 ∧ n ≤ x) ∨ (i ≤ n ∧ x = i - n))\n\n-/\n\n\nmeta def connection_iff : user_attribute :=\n{ name := `connection_iff,\n descr := \"Connection rules of the form f x R y ↔ x Q g z, used for term focusing\" }\n\nsection analyse\n\nmeta def conjs : expr → tactic (list expr)\n| `(%%a ∧ %%b) := do\n as ← conjs a,\n bs ← conjs b,\n return (as ++ bs)\n| e := return [e]\n\nmeta def disjs_of_conjs : expr → tactic (list $ list expr)\n| `(%%a ∨ %%b) := do\n as ← disjs_of_conjs a,\n bs ← disjs_of_conjs b,\n return (as ++ bs)\n| e := do\n d ← conjs e,\n return [d]\n\n-- better `parse_rel`: this doesn't work with heq!\n-- idea: use relation manager\nmeta def parse_rel : expr → tactic (expr × expr × expr)\n| (expr.app (expr.app f a) b) := return (f, a, b)\n| _ := fail \"term is not a relation application\"\n\ndef peep {α} : list α → list (list α × α × list α)\n| [] := []\n| (a :: xs) := ([], a, xs) :: (peep xs).map (λ⟨p, a', s⟩, (a::p, a', s))\n\nprivate meta def analyse_connection_aux (ls : list level) (vs : list expr) (lhs rhs : expr) :\n tactic $ list pattern := do\ndisjs ← disjs_of_conjs rhs,\ncandidates ← disjs.mmap (λconjs, do\n candidates ← (peep conjs).mmap (λxs, (do\n (ps, e, ss) ← return xs,\n (rel, l, r) ← parse_rel e,\n return $\n (if l ∈ vs ∧ (r :: rel :: ps ++ ss).all (λe, ¬ l.occurs e) then [l] else []) ++\n (if r ∈ vs ∧ (l :: rel :: ps ++ ss).all (λe, ¬ r.occurs e) then [r] else []))\n <|> return []),\n return candidates.join),\nlet candidates := vs.filter $ λv, candidates.all $ λcs, v ∈ cs,\n\n(rel, l, r) ← parse_rel lhs,\nlet candidates := candidates.filter $ λc,\n ¬ c.occurs rel ∧ ((c.occurs l ∧ ¬ c.occurs r) ∨ c.occurs r ∧ ¬ c.occurs l),\nlet candidates := candidates.dedup,\nlet vs' := vs.filter (λv, v.occurs lhs),\ncandidates.mmap (λc, mk_pattern ls vs' lhs [] [c])\n\n/-- `analyse_connection ls r` a list of symm-flag and pattern. The pattern matches if the rule is\napplicable. In this case `tactic.match_pattern` returns one expression where the focused variable\nshould occur. The symm-flag indicates if the iff-rule should be applied in its symmetric variant. -/\nmeta def analyse_connection (n : name) : tactic $ list $ bool × pattern := do\ne ← get_env,\nd ← e.get n,\nlet ls := d.univ_params.map level.param,\n(vs, `(%%lhs ↔ %%rhs)) ← mk_local_pis d.type,\nl ← analyse_connection_aux ls vs lhs rhs,\nr ← analyse_connection_aux ls vs rhs lhs,\nreturn (l.map (λp, (ff, p)) ++ r.map (λp, (tt, p)))\n\nmeta def ors (c : conv unit) : conv unit := do\n`(_ ∨ _) ← lhs | c,\ncongr_core (congr_core skip ors) ors,\nskip\n\nmeta def ands (c : conv unit) : conv unit := do\n`(_ ∧ _) ← lhs | c,\ncongr_core (congr_core skip ands) ands,\nskip\n\nmeta def local_eq (v₀ v₁ : expr) : bool :=\nv₀.is_local_constant ∧ v₁.is_local_constant ∧ v₀.local_uniq_name = v₁.local_uniq_name\n\nmeta def term_focus (l : list (name × bool × pattern)) (v : expr) : conv unit :=\nl.mfirst $ assume ⟨n, symm, pat⟩, do\n ([], [t]) ← match_pattern pat,\n guard $ v.occurs t,\n (if symm then apply_const n else fail \"symmetric apply not supported yet\"),\n ors (ands $ (do\n l ← lhs,\n (_, l, r) ← lift_tactic $ parse_rel l,\n guard ((v.occurs l ∧ ¬ local_eq l v) ∨ (v.occurs r ∧ ¬ local_eq r v)),\n term_focus) <|> skip)\n\nend analyse\n\n/-\n\nLattices\n\n x ≤ y ⊓ z ↔ x ≤ y ∧ x ≤ z\n\n y ⊓ z ≤ x ↔ y \\ z ≤ x (Heyting algebra)\n\n a ⊔ b ≤ c ↔ a ≤ c ∧ b ≤ c\n\nCase: Focus on a\n (∃ x, x ⊔ b ≤ c ∧ p x) ↔ (∃x, x ≤ c ∧ b ≤ c ∧ p x)\n\n-/\n\n\nend term_focus\n\n#exit\n\nsection equality_elim\n\nmeta def check_eq (x : expr) (deps : list expr) : expr → bool\n| `(%%l = %%r) := (l = x ∧ deps.all (λx, ¬ x.occurs r)) ∨ (r = x ∧ deps.all (λx, ¬ x.occurs l))\n| _ := ff\n\nmeta def elim_equality (n : norm_form) : conv unit := do\n-- trace (to_fmt \"elim_equality [reordered] \" ++ to_fmt n), trace_lhs,\napply_norm [``elim_eq_left, ``elim_eq_right] [``elim_ex_left, ``elim_ex_right] [``elim_cn_left, ``elim_cn_right] n,\nskip\n\nmeta def run : conv unit := do\npss ← congr_binder ``ex_congr (λv, do t ← lhs, find check_eq v [v] t),\npss.mfirst (reorder elim_equality)\n\nend equality_elim\n\nend simp_loop", "meta": {"author": "johoelzl", "repo": "lean-simp-loop", "sha": "c1ad8c34be7c6fd323fc5eff5ce337fd23a72e04", "save_path": "github-repos/lean/johoelzl-lean-simp-loop", "path": "github-repos/lean/johoelzl-lean-simp-loop/lean-simp-loop-c1ad8c34be7c6fd323fc5eff5ce337fd23a72e04/src/simp_loop/monotone_elim.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3073580295544412, "lm_q2_score": 0.042722201050615215, "lm_q1q2_score": 0.01313101153314577}} {"text": "import ReactorModel.Determinism.InstantaneousExecution\n\nnamespace Execution\n\nopen ReactorType\nopen State (Closed)\n\nvariable [Indexable α] {s s₁ s₂ : State α} [State.Nontrivial s] [State.Nontrivial s₁]\n\nnamespace AdvanceTag\n\ntheorem not_Closed (a : s₁ ⇓- s₂) : ¬(Closed s₂) :=\n have := a.advance.preserves_Nontrivial -- TODO: Make this work via type class inference.\n (absurd a.advance.progress_empty ·.progress_Nonempty.ne_empty)\n\ntheorem nonrepeatable (a₁ : s₁ ⇓- s₂) (a₂ : s₂ ⇓- s₃) : False :=\n absurd a₂.closed a₁.not_Closed\n\ntheorem tag_lt (a : s₁ ⇓- s₂) : s₁.tag < s₂.tag :=\n a.advance.tag_lt\n\ntheorem tag_ne (a : s₁ ⇓- s₂) : s₁.tag ≠ s₂.tag :=\n ne_of_lt a.tag_lt\n\ntheorem determinisic (a₁ : s ⇓- s₁) (a₂ : s ⇓- s₂) : s₁ = s₂ :=\n a₁.advance.determinisic a₂.advance\n\ninstance preserves_Nontrivial [State.Nontrivial s₁] {e : s₁ ⇓- s₂} : State.Nontrivial s₂ :=\n e.advance.preserves_Nontrivial\n\nend AdvanceTag\n\nnamespace Instantaneous\nnamespace ClosedExecution\n\ntheorem not_Closed (e : s₁ ⇓| s₂) : ¬(Closed s₁) := by\n simp [Closed]\n have h := Partial.Nonempty.iff_ids_nonempty.mp $ State.Nontrivial.nontrivial (s := s₁)\n exact e.fresh ▸ h.ne_empty.symm \n\ntheorem preserves_tag (e : s₁ ⇓| s₂) : s₁.tag = s₂.tag :=\n e.exec.preserves_tag\n\ntheorem equiv (e : s₁ ⇓| s₂) : s₁.rtr ≈ s₂.rtr :=\n e.exec.equiv\n \ntheorem rcns_Nodup (e : s₁ ⇓| s₂) : e.rcns.Nodup := \n e.exec.rcns_nodup\n\ntheorem progress_def (e : s₁ ⇓| s₂) : s₂.progress = s₁.rtr[.rcn].ids :=\n Equivalent.obj?_rcn_eq e.equiv ▸ e.closed\n\ntheorem mem_rcns_iff (e : s₁ ⇓| s₂) : rcn ∈ e.rcns ↔ (rcn ∈ s₁.rtr[.rcn] ∧ rcn ∉ s₁.progress) := by\n simp [Partial.mem_def, e.progress_def ▸ e.exec.mem_rcns_iff (rcn := rcn)]\n\ntheorem rcns_perm (e₁ : s ⇓| s₁) (e₂ : s ⇓| s₂) : e₁.rcns ~ e₂.rcns := by\n simp [List.perm_ext e₁.rcns_Nodup e₂.rcns_Nodup, e₁.mem_rcns_iff, e₂.mem_rcns_iff]\n\ntheorem tag_eq (e₁ : s ⇓| s₁) (e₂ : s ⇓| s₂) : s₁.tag = s₂.tag :=\n e₁.exec.preserves_tag ▸ e₂.exec.preserves_tag\n\ntheorem progress_eq (e₁ : s ⇓| s₁) (e₂ : s ⇓| s₂) : s₁.progress = s₂.progress := by\n simp [e₁.progress_def, e₂.progress_def]\n\ntheorem deterministic (e₁ : s ⇓| s₁) (e₂ : s ⇓| s₂) : s₁ = s₂ :=\n e₁.exec.deterministic e₂.exec (e₁.tag_eq e₂) (e₁.progress_eq e₂)\n\ntheorem step_determined (e : s ⇓| s₁) (a : s ⇓- s₂) : False :=\n absurd a.closed e.not_Closed\n\ninstance preserves_Nontrivial [h : State.Nontrivial s₁] {e : s₁ ⇓| s₂} : State.Nontrivial s₂ where\n nontrivial := Equivalent.obj?_rcn_eq e.equiv ▸ h.nontrivial\n\ntheorem nonrepeatable (e₁ : s₁ ⇓| s₂) (e₂ : s₂ ⇓| s₃) : False :=\n have := e₁.preserves_Nontrivial -- TODO: Make this work via type class inference.\n absurd e₁.closed $ e₂.not_Closed\n\ntheorem progress_ssubset (e : s₁ ⇓| s₂) : s₁.progress ⊂ s₂.progress := by\n have := e.preserves_Nontrivial -- TODO: Make this work via type class inference.\n rw [e.fresh]\n exact e.closed.progress_Nonempty.empty_ssubset\n\nend ClosedExecution\nend Instantaneous\n\nnamespace Step\n\ntheorem tag_le : (s₁ ⇓ s₂) → s₁.tag ≤ s₂.tag\n | close e => le_of_eq e.preserves_tag\n | advance a => le_of_lt a.tag_lt\n\ntheorem deterministic : (s ⇓ s₁) → (s ⇓ s₂) → s₁ = s₂\n | close e₁, close e₂ => e₁.deterministic e₂\n | advance a₁, advance a₂ => a₁.determinisic a₂\n | close e, advance a | advance a, close e => e.step_determined a |>.elim\n\ntheorem seq_tag_lt : (s₁ ⇓ s₂) → (s₂ ⇓ s₃) → s₁.tag < s₃.tag\n | close e₁, close e₂ => e₁.nonrepeatable e₂ |>.elim\n | advance a₁, advance a₂ => a₁.nonrepeatable a₂ |>.elim\n | close e, advance a => e.preserves_tag ▸ a.tag_lt\n | advance a, close e => e.preserves_tag ▸ a.tag_lt\n\ninstance preserves_Nontrivial [State.Nontrivial s₁] : (s₁ ⇓ s₂) → State.Nontrivial s₂\n | close e => e.preserves_Nontrivial\n | advance a => a.preserves_Nontrivial\n\nend Step\n\nend Execution", "meta": {"author": "marcusrossel", "repo": "reactor-model", "sha": "f82fffb489b4352a0cc6bee964d44a142fee18ce", "save_path": "github-repos/lean/marcusrossel-reactor-model", "path": "github-repos/lean/marcusrossel-reactor-model/reactor-model-f82fffb489b4352a0cc6bee964d44a142fee18ce/src/ReactorModel/Determinism/ExecutionStep.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43398146480389854, "lm_q2_score": 0.030214586412450714, "lm_q1q2_score": 0.01311257046971933}} {"text": "import Qq\nopen Qq\n\nset_option linter.unusedVariables false in\ndef typeClassArgument (α : Q(Sort u)) (inst : Q(Inhabited $α)) : Q($α) :=\n q(Inhabited.default)\n\nexample : Q(Nat) :=\n typeClassArgument q(Nat) q(inferInstance)\n\nopen Lean in\n#eval show MetaM Q(Nat) from do\n let _ ← synthInstanceQ q(Inhabited Nat)\n return typeClassArgument (u := levelOne) q(Nat) q(inferInstance)\n", "meta": {"author": "gebner", "repo": "quote4", "sha": "c71f94e34c1cda52eef5c93dc9da409ab2727420", "save_path": "github-repos/lean/gebner-quote4", "path": "github-repos/lean/gebner-quote4/quote4-c71f94e34c1cda52eef5c93dc9da409ab2727420/examples/typeclass.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.4263215925474903, "lm_q2_score": 0.030214583792677812, "lm_q1q2_score": 0.012881129480653994}} {"text": "/-\nCopyright (c) 2018 Mario Carneiro. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Mario Carneiro, Kenny Lau\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.default\nimport Mathlib.data.list.basic\nimport Mathlib.PostPort\n\nuniverses u v w z u_1 u_2 u_3 \n\nnamespace Mathlib\n\nnamespace list\n\n\n/- zip & unzip -/\n\n@[simp] theorem zip_with_cons_cons {α : Type u} {β : Type v} {γ : Type w} (f : α → β → γ) (a : α)\n (b : β) (l₁ : List α) (l₂ : List β) :\n zip_with f (a :: l₁) (b :: l₂) = f a b :: zip_with f l₁ l₂ :=\n rfl\n\n@[simp] theorem zip_cons_cons {α : Type u} {β : Type v} (a : α) (b : β) (l₁ : List α)\n (l₂ : List β) : zip (a :: l₁) (b :: l₂) = (a, b) :: zip l₁ l₂ :=\n rfl\n\n@[simp] theorem zip_with_nil_left {α : Type u} {β : Type v} {γ : Type w} (f : α → β → γ)\n (l : List β) : zip_with f [] l = [] :=\n rfl\n\n@[simp] theorem zip_with_nil_right {α : Type u} {β : Type v} {γ : Type w} (f : α → β → γ)\n (l : List α) : zip_with f l [] = [] :=\n list.cases_on l (Eq.refl (zip_with f [] []))\n fun (l_hd : α) (l_tl : List α) => Eq.refl (zip_with f (l_hd :: l_tl) [])\n\n@[simp] theorem zip_nil_left {α : Type u} {β : Type v} (l : List α) : zip [] l = [] := rfl\n\n@[simp] theorem zip_nil_right {α : Type u} {β : Type v} (l : List α) : zip l [] = [] :=\n zip_with_nil_right Prod.mk l\n\n@[simp] theorem zip_swap {α : Type u} {β : Type v} (l₁ : List α) (l₂ : List β) :\n map prod.swap (zip l₁ l₂) = zip l₂ l₁ :=\n sorry\n\n@[simp] theorem length_zip_with {α : Type u} {β : Type v} {γ : Type w} (f : α → β → γ) (l₁ : List α)\n (l₂ : List β) : length (zip_with f l₁ l₂) = min (length l₁) (length l₂) :=\n sorry\n\n@[simp] theorem length_zip {α : Type u} {β : Type v} (l₁ : List α) (l₂ : List β) :\n length (zip l₁ l₂) = min (length l₁) (length l₂) :=\n length_zip_with Prod.mk\n\ntheorem lt_length_left_of_zip_with {α : Type u} {β : Type v} {γ : Type w} {f : α → β → γ} {i : ℕ}\n {l : List α} {l' : List β} (h : i < length (zip_with f l l')) : i < length l :=\n and.left\n (eq.mp (Eq._oldrec (Eq.refl (i < min (length l) (length l'))) (propext lt_min_iff))\n (eq.mp (Eq._oldrec (Eq.refl (i < length (zip_with f l l'))) (length_zip_with f l l')) h))\n\ntheorem lt_length_right_of_zip_with {α : Type u} {β : Type v} {γ : Type w} {f : α → β → γ} {i : ℕ}\n {l : List α} {l' : List β} (h : i < length (zip_with f l l')) : i < length l' :=\n and.right\n (eq.mp (Eq._oldrec (Eq.refl (i < min (length l) (length l'))) (propext lt_min_iff))\n (eq.mp (Eq._oldrec (Eq.refl (i < length (zip_with f l l'))) (length_zip_with f l l')) h))\n\ntheorem lt_length_left_of_zip {α : Type u} {β : Type v} {i : ℕ} {l : List α} {l' : List β}\n (h : i < length (zip l l')) : i < length l :=\n lt_length_left_of_zip_with h\n\ntheorem lt_length_right_of_zip {α : Type u} {β : Type v} {i : ℕ} {l : List α} {l' : List β}\n (h : i < length (zip l l')) : i < length l' :=\n lt_length_right_of_zip_with h\n\ntheorem zip_append {α : Type u} {β : Type v} {l₁ : List α} {r₁ : List α} {l₂ : List β} {r₂ : List β}\n (h : length l₁ = length l₂) : zip (l₁ ++ r₁) (l₂ ++ r₂) = zip l₁ l₂ ++ zip r₁ r₂ :=\n sorry\n\ntheorem zip_map {α : Type u} {β : Type v} {γ : Type w} {δ : Type z} (f : α → γ) (g : β → δ)\n (l₁ : List α) (l₂ : List β) : zip (map f l₁) (map g l₂) = map (prod.map f g) (zip l₁ l₂) :=\n sorry\n\ntheorem zip_map_left {α : Type u} {β : Type v} {γ : Type w} (f : α → γ) (l₁ : List α)\n (l₂ : List β) : zip (map f l₁) l₂ = map (prod.map f id) (zip l₁ l₂) :=\n eq.mpr\n (id\n (Eq._oldrec (Eq.refl (zip (map f l₁) l₂ = map (prod.map f id) (zip l₁ l₂)))\n (Eq.symm (zip_map f id l₁ l₂))))\n (eq.mpr (id (Eq._oldrec (Eq.refl (zip (map f l₁) l₂ = zip (map f l₁) (map id l₂))) (map_id l₂)))\n (Eq.refl (zip (map f l₁) l₂)))\n\ntheorem zip_map_right {α : Type u} {β : Type v} {γ : Type w} (f : β → γ) (l₁ : List α)\n (l₂ : List β) : zip l₁ (map f l₂) = map (prod.map id f) (zip l₁ l₂) :=\n eq.mpr\n (id\n (Eq._oldrec (Eq.refl (zip l₁ (map f l₂) = map (prod.map id f) (zip l₁ l₂)))\n (Eq.symm (zip_map id f l₁ l₂))))\n (eq.mpr (id (Eq._oldrec (Eq.refl (zip l₁ (map f l₂) = zip (map id l₁) (map f l₂))) (map_id l₁)))\n (Eq.refl (zip l₁ (map f l₂))))\n\ntheorem zip_map' {α : Type u} {β : Type v} {γ : Type w} (f : α → β) (g : α → γ) (l : List α) :\n zip (map f l) (map g l) = map (fun (a : α) => (f a, g a)) l :=\n sorry\n\ntheorem mem_zip {α : Type u} {β : Type v} {a : α} {b : β} {l₁ : List α} {l₂ : List β} :\n (a, b) ∈ zip l₁ l₂ → a ∈ l₁ ∧ b ∈ l₂ :=\n sorry\n\ntheorem map_fst_zip {α : Type u} {β : Type v} (l₁ : List α) (l₂ : List β) :\n length l₁ ≤ length l₂ → map prod.fst (zip l₁ l₂) = l₁ :=\n sorry\n\ntheorem map_snd_zip {α : Type u} {β : Type v} (l₁ : List α) (l₂ : List β) :\n length l₂ ≤ length l₁ → map prod.snd (zip l₁ l₂) = l₂ :=\n sorry\n\n@[simp] theorem unzip_nil {α : Type u} {β : Type v} : unzip [] = ([], []) := rfl\n\n@[simp] theorem unzip_cons {α : Type u} {β : Type v} (a : α) (b : β) (l : List (α × β)) :\n unzip ((a, b) :: l) = (a :: prod.fst (unzip l), b :: prod.snd (unzip l)) :=\n sorry\n\ntheorem unzip_eq_map {α : Type u} {β : Type v} (l : List (α × β)) :\n unzip l = (map prod.fst l, map prod.snd l) :=\n sorry\n\ntheorem unzip_left {α : Type u} {β : Type v} (l : List (α × β)) :\n prod.fst (unzip l) = map prod.fst l :=\n sorry\n\ntheorem unzip_right {α : Type u} {β : Type v} (l : List (α × β)) :\n prod.snd (unzip l) = map prod.snd l :=\n sorry\n\ntheorem unzip_swap {α : Type u} {β : Type v} (l : List (α × β)) :\n unzip (map prod.swap l) = prod.swap (unzip l) :=\n sorry\n\ntheorem zip_unzip {α : Type u} {β : Type v} (l : List (α × β)) :\n zip (prod.fst (unzip l)) (prod.snd (unzip l)) = l :=\n sorry\n\ntheorem unzip_zip_left {α : Type u} {β : Type v} {l₁ : List α} {l₂ : List β} :\n length l₁ ≤ length l₂ → prod.fst (unzip (zip l₁ l₂)) = l₁ :=\n sorry\n\ntheorem unzip_zip_right {α : Type u} {β : Type v} {l₁ : List α} {l₂ : List β}\n (h : length l₂ ≤ length l₁) : prod.snd (unzip (zip l₁ l₂)) = l₂ :=\n eq.mpr (id (Eq._oldrec (Eq.refl (prod.snd (unzip (zip l₁ l₂)) = l₂)) (Eq.symm (zip_swap l₂ l₁))))\n (eq.mpr\n (id\n (Eq._oldrec (Eq.refl (prod.snd (unzip (map prod.swap (zip l₂ l₁))) = l₂))\n (unzip_swap (zip l₂ l₁))))\n (unzip_zip_left h))\n\ntheorem unzip_zip {α : Type u} {β : Type v} {l₁ : List α} {l₂ : List β}\n (h : length l₁ = length l₂) : unzip (zip l₁ l₂) = (l₁, l₂) :=\n sorry\n\ntheorem zip_of_prod {α : Type u} {β : Type v} {l : List α} {l' : List β} {lp : List (α × β)}\n (hl : map prod.fst lp = l) (hr : map prod.snd lp = l') : lp = zip l l' :=\n sorry\n\ntheorem map_prod_left_eq_zip {α : Type u} {β : Type v} {l : List α} (f : α → β) :\n map (fun (x : α) => (x, f x)) l = zip l (map f l) :=\n sorry\n\ntheorem map_prod_right_eq_zip {α : Type u} {β : Type v} {l : List α} (f : α → β) :\n map (fun (x : α) => (f x, x)) l = zip (map f l) l :=\n sorry\n\n@[simp] theorem length_revzip {α : Type u} (l : List α) : length (revzip l) = length l := sorry\n\n@[simp] theorem unzip_revzip {α : Type u} (l : List α) : unzip (revzip l) = (l, reverse l) :=\n unzip_zip (Eq.symm (length_reverse l))\n\n@[simp] theorem revzip_map_fst {α : Type u} (l : List α) : map prod.fst (revzip l) = l :=\n eq.mpr (id (Eq._oldrec (Eq.refl (map prod.fst (revzip l) = l)) (Eq.symm (unzip_left (revzip l)))))\n (eq.mpr (id (Eq._oldrec (Eq.refl (prod.fst (unzip (revzip l)) = l)) (unzip_revzip l)))\n (Eq.refl (prod.fst (l, reverse l))))\n\n@[simp] theorem revzip_map_snd {α : Type u} (l : List α) : map prod.snd (revzip l) = reverse l :=\n eq.mpr\n (id\n (Eq._oldrec (Eq.refl (map prod.snd (revzip l) = reverse l))\n (Eq.symm (unzip_right (revzip l)))))\n (eq.mpr (id (Eq._oldrec (Eq.refl (prod.snd (unzip (revzip l)) = reverse l)) (unzip_revzip l)))\n (Eq.refl (prod.snd (l, reverse l))))\n\ntheorem reverse_revzip {α : Type u} (l : List α) : reverse (revzip l) = revzip (reverse l) := sorry\n\ntheorem revzip_swap {α : Type u} (l : List α) : map prod.swap (revzip l) = revzip (reverse l) :=\n sorry\n\ntheorem nth_zip_with {α : Type u_1} {β : Type u_1} {γ : Type u_1} (f : α → β → γ) (l₁ : List α)\n (l₂ : List β) (i : ℕ) : nth (zip_with f l₁ l₂) i = f <$> nth l₁ i <*> nth l₂ i :=\n sorry\n\ntheorem nth_zip_with_eq_some {α : Type u_1} {β : Type u_2} {γ : Type u_3} (f : α → β → γ)\n (l₁ : List α) (l₂ : List β) (z : γ) (i : ℕ) :\n nth (zip_with f l₁ l₂) i = some z ↔\n ∃ (x : α), ∃ (y : β), nth l₁ i = some x ∧ nth l₂ i = some y ∧ f x y = z :=\n sorry\n\ntheorem nth_zip_eq_some {α : Type u} {β : Type v} (l₁ : List α) (l₂ : List β) (z : α × β) (i : ℕ) :\n nth (zip l₁ l₂) i = some z ↔ nth l₁ i = some (prod.fst z) ∧ nth l₂ i = some (prod.snd z) :=\n sorry\n\n@[simp] theorem nth_le_zip_with {α : Type u} {β : Type v} {γ : Type w} {f : α → β → γ} {l : List α}\n {l' : List β} {i : ℕ} {h : i < length (zip_with f l l')} :\n nth_le (zip_with f l l') i h =\n f (nth_le l i (lt_length_left_of_zip_with h))\n (nth_le l' i (lt_length_right_of_zip_with h)) :=\n sorry\n\n@[simp] theorem nth_le_zip {α : Type u} {β : Type v} {l : List α} {l' : List β} {i : ℕ}\n {h : i < length (zip l l')} :\n nth_le (zip l l') i h =\n (nth_le l i (lt_length_left_of_zip h), nth_le l' i (lt_length_right_of_zip h)) :=\n nth_le_zip_with\n\ntheorem mem_zip_inits_tails {α : Type u} {l : List α} {init : List α} {tail : List α} :\n (init, tail) ∈ zip (inits l) (tails l) ↔ init ++ tail = l :=\n sorry\n\nend Mathlib", "meta": {"author": "AurelienSaue", "repo": "Mathlib4_auto", "sha": "590df64109b08190abe22358fabc3eae000943f2", "save_path": "github-repos/lean/AurelienSaue-Mathlib4_auto", "path": "github-repos/lean/AurelienSaue-Mathlib4_auto/Mathlib4_auto-590df64109b08190abe22358fabc3eae000943f2/Mathlib/data/list/zip_auto.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3775406547908328, "lm_q2_score": 0.034100429638778046, "lm_q1q2_score": 0.012874298534472986}} {"text": "import Lean\nimport Lean.Meta\nimport Lean.Parser\nimport LeanCodePrompts.CheckParse\nimport LeanCodePrompts.ParseJson\nimport LeanCodePrompts.Autocorrect\nimport LeanCodePrompts.KeywordSummary.KeywordExtraction\nimport LeanCodePrompts.EgsTranslate\nopen Lean Meta\n\nopen Lean Elab Parser Command\n\ndef fileName := \"data/safe_prompts.json\"\n\n/-- extract prompt pairs from JSON response to local server -/\ndef sentenceSimPairs\n (s: String)\n (theoremField : String := \"theorem\")\n : MetaM <| Except String (Array (String × String)) := do\n let json ← readJson s\n return do\n (← json.getArr?).mapM <| fun j => do\n let docstring ← j.getObjValAs? String \"doc_string\" \n let typeField := \n if fileName ∈ [\"data/mathlib4-prompts.json\"] then \"type\"\n else theoremField\n let thm ← j.getObjValAs? String typeField\n pure (docstring, thm) \n\n-- #eval sentenceSimPairs egSen\n\nnamespace GPT\n\ndef message (role content : String) : Json :=\n Json.mkObj [(\"role\", role), (\"content\", content)] \n\ndef prompt (sys: String) (egs : List <| String × String)(query : String) : Json :=\n let head := message \"system\" sys\n let egArr := \n egs.bind (fun (ds, thm) => [message \"user\" ds, message \"assistant\" thm])\n Json.arr <| head :: egArr ++ [message \"user\" query] |>.toArray\n\ndef sysPrompt := \"You are a coding assistant who translates from natural language to Lean Theorem Prover code following examples. Follow EXACTLY the examples given.\"\n\ndef makePrompt(query : String)(pairs: Array (String × String)) : Json:= prompt sysPrompt pairs.toList query \n\ndef makeFlipPrompt(query : String)(pairs: Array (String × String)) : Json:= prompt sysPrompt (pairs.toList.map (fun (x, y) => (y, x))) query\n\ndef jsonToExprStrArray (json: Json) : TermElabM (Array String) := do\n let outArr : Array String ← \n match json.getArr? with\n | Except.ok arr => \n let parsedArr : Array String ← \n arr.filterMapM <| fun js =>\n match js.getObjVal? \"message\" with\n | Except.ok jsobj => \n match jsobj.getObjVal? \"content\" with\n | Except.ok jsstr =>\n match jsstr.getStr? with\n | Except.ok str => pure (some str)\n | Except.error e => \n throwError m!\"json string expected but got {js}, error: {e}\"\n | Except.error _ =>\n throwError m!\"no content field in {jsobj}\"\n | Except.error _ =>\n throwError m!\"no message field in {js}\"\n \n pure parsedArr\n | Except.error e => throwError m!\"json parsing error: {e}\"\n\nend GPT\n\n/-- make prompt from prompt pairs -/\n@[deprecated GPT.makePrompt]\ndef makePrompt(prompt : String)(pairs: Array (String × String)) : String := \n pairs.foldr (fun (ds, thm) acc => \n -- acc ++ \"/-- \" ++ ds ++\" -/\\ntheorem\" ++ thm ++ \"\\n\" ++ \"\\n\"\ns!\"/-- {ds} -/\ntheorem {thm} :=\n\n{acc}\"\n ) s!\"/-- {prompt} -/\ntheorem \"\n\n\n/-- make prompt for reverse translation from prompt pairs -/\n@[deprecated GPT.makeFlipPrompt]\ndef makeFlipPrompt(statement : String)(pairs: Array (String × String)) : String := \n pairs.foldr (fun (ds, thm) acc => \ns!\"theorem {thm} := \n/- {ds} -/\n\n{acc}\"\n ) s!\"theorem {statement} := \n/- \"\n\n/-- make prompt for reverse translation from prompt pairs -/\ndef makeFlipStatementsPrompt(statement : String)(pairs: Array (String × String)) : String := \n pairs.foldr (fun (ds, thm) acc => \ns!\"{thm} := \n/- {ds} -/\n\n{acc}\"\n ) s!\"{statement} := \n/- \"\n\ndef openAIKey : IO (Option String) := IO.getEnv \"OPENAI_API_KEY\"\n\n/--query OpenAI Codex with given prompt and parameters -/\ndef codexQuery(prompt: String)(n: Nat := 1)\n (temp : JsonNumber := ⟨2, 1⟩)(stopTokens: Array String := #[\":=\", \"-/\"]) : MetaM Json := do\n let key? ← openAIKey\n let key := \n match key? with\n | some k => k\n | none => panic! \"OPENAI_API_KEY not set\"\n let dataJs := Json.mkObj [(\"model\", \"code-davinci-002\"), (\"prompt\", prompt), (\"temperature\", Json.num temp), (\"n\", n), (\"max_tokens\", 150), (\"stop\", Json.arr <| stopTokens |>.map Json.str)]\n let data := dataJs.pretty\n trace[Translate.info] \"OpenAI query: {data}\"\n let out ← IO.Process.output {\n cmd:= \"curl\", \n args:= #[\"https://api.openai.com/v1/completions\",\n \"-X\", \"POST\",\n \"-H\", \"Authorization: Bearer \" ++ key,\n \"-H\", \"Content-Type: application/json\",\n \"--data\", data]}\n readJson out.stdout\n\ndef gptQuery(messages: Json)(n: Nat := 1)\n (temp : JsonNumber := ⟨2, 1⟩)(stopTokens: Array String := #[\":=\", \"-/\"]) : MetaM Json := do\n let key? ← openAIKey\n let key := \n match key? with\n | some k => k\n | none => panic! \"OPENAI_API_KEY not set\"\n let dataJs := Json.mkObj [(\"model\", \"gpt-3.5-turbo\"), (\"messages\", messages)\n , (\"temperature\", Json.num temp), (\"n\", n), (\"max_tokens\", 150), (\"stop\", Json.arr <| stopTokens |>.map Json.str)\n ]\n let data := dataJs.pretty\n trace[Translate.info] \"OpenAI query: {data}\"\n let out ← IO.Process.output {\n cmd:= \"curl\", \n args:= #[\"https://api.openai.com/v1/chat/completions\",\n \"-X\", \"POST\",\n \"-H\", \"Authorization: Bearer \" ++ key,\n \"-H\", \"Content-Type: application/json\",\n \"--data\", data]}\n trace[Translate.info] \"OpenAI response: {out.stdout} (stderr: {out.stderr})\"\n readJson out.stdout\n\ndef openAIQuery(prompt: String)(n: Nat := 1)\n (temp : JsonNumber := ⟨2, 1⟩)(stopTokens: Array String := #[\":=\", \"-/\"]) : MetaM Json :=\n codexQuery prompt n temp stopTokens \n\n/-!\nCaching, polling etc to avoid repeatedly calling servers\n-/\n\ninitialize webCacheJson : IO.Ref (HashMap String Json) ← IO.mkRef (HashMap.empty)\n\ninitialize pendingJsonQueries : IO.Ref (HashSet String) \n ← IO.mkRef (HashSet.empty)\n\ninitialize logCache : IO.Ref (Array String) ← IO.mkRef (#[])\n\ndef mkLog{α : Type _}[ToString α](msg: α) : IO Unit := do\n let cache ← logCache.get\n logCache.set (cache.push (toString msg))\n\ndef logs (num: Nat) : IO (List String) := do\n let cache ← logCache.get\n return cache.reverse.toList.take num\n\ndef showLogs (num: Nat) : IO Unit := do\n let cache ← logCache.get\n let ls := cache.reverse.toList.take num\n for lines in ls do\n for l in lines.splitOn \"\\n\" do\n IO.println l\n\ndef getCachedJson? (s: String) : IO (Option Json) := do\n let cache ← webCacheJson.get\n return cache.find? s\n\ndef cacheJson (s: String)(js: Json) : IO Unit := do\n let cache ← webCacheJson.get\n webCacheJson.set (cache.insert s js)\n return ()\n\npartial def pollCacheJson (s : String) : IO Json := do\n let cache ← webCacheJson.get\n match cache.find? s with\n | some jsBlob => return jsBlob\n | none => do\n IO.sleep 200\n pollCacheJson s\n\n/-- check if there is a valid elaboration after translation, autocorrection -/\ndef hasElab (s: String)(limit : Option Nat := none) : TermElabM Bool := do\n -- (elabThmTrans s).map (fun e => e.toBool)\n let elab? ← polyElabThmTrans s limit\n match elab? with\n | Except.error _ => return Bool.false\n | Except.ok els => return !els.isEmpty\n\n/-- log to file -/\ndef elabLog (s: String) : IO Unit := do\n let logFile := System.mkFilePath [\"results/elab_logs.txt\"]\n let h ← IO.FS.Handle.mk logFile IO.FS.Mode.append Bool.false\n h.putStrLn s\n h.putStrLn \"\"\n\ndef fixedPrompts:= #[(\"If $z_1, \\\\dots, z_n$ are complex, then $|z_1 + z_2 + \\\\dots + z_n|\\\\leq |z_1| + |z_2| + \\\\dots + |z_n|$.\", \"(n : ℕ) (f : ℕ → ℂ) :\\n abs (∑ i in finset.range n, f i) ≤ ∑ i in finset.range n, abs (f i) :=\"), (\"If x and y are in $\\\\mathbb{R}^n$, then $|x+y|^2 + |x-y|^2 = 2|x|^2 + 2|y|^2$.\", \"(n : ℕ) (x y : euclidean_space ℝ (fin n)) :\\n ∥x + y∥^2 + ∥x - y∥^2 = 2*∥x∥^2 + 2*∥y∥^2 :=\"), (\"If $x$ is an element of infinite order in $G$, prove that the elements $x^n$, $n\\\\in\\\\mathbb{Z}$ are all distinct.\", \"(G : Type*) [group G] (x : G) (hx : x ≠ 1) (hx_inf : ∀ n : ℕ, x ^ n ≠ 1) : ∀ m n : ℤ, m ≠ n → x ^ m ≠ x ^ n :=\"), (\"Let $X$ be a topological space; let $A$ be a subset of $X$. Suppose that for each $x\\\\in A$ there is an open set $U$ containing $x$ such that $U\\\\subset A$. Show that $A$ is open in $X$.\", \"(X : Type*) [topological_space X]\\n (A : set X) (hA : ∀ x ∈ A, ∃ U : set X, is_open U ∧ x ∈ U ∧ U ⊆ A):\\n is_open A :=\")]\n\n/-- choosing pairs to build a prompt -/\ndef getPromptPairs(s: String)(numSim : Nat)(numKW: Nat)\n (scoreBound: Float)(matchBound: Nat)\n : TermElabM (Array (String × String) × IO.Process.Output) := do\n let jsData := Json.mkObj [\n (\"filename\", fileName),\n (\"field\", \"doc_string\"),\n (\"doc_string\", s),\n (\"n\", numSim),\n (\"model_name\", \"all-mpnet-base-v2\")\n ]\n let simJsonOut ← \n IO.Process.output {cmd:= \"curl\", args:= \n #[\"-X\", \"POST\", \"-H\", \"Content-type: application/json\", \"-d\", jsData.pretty, s!\"{← leanAideIP}/nearest_prompts\"]}\n let pairs? ← sentenceSimPairs simJsonOut.stdout \"theorem\"\n -- IO.println s!\"obtained sentence similarity; time : {← IO.monoMsNow}\"\n let allPairs : Array (String × String) ← \n match pairs? with\n | Except.error e =>\n throwError e \n | Except.ok pairs => pure pairs \n -- logInfo m!\"all pairs: {allPairs}\" \n let kwPairs :=\n if numKW >0 \n then ← keywordBasedPrompts docPair s numKW scoreBound matchBound\n else #[]\n -- IO.println s!\"obtained keyword pairs; time : {← IO.monoMsNow}\"\n let allPairs := (allPairs ++ kwPairs).toList.eraseDups.toArray\n let pairs -- := allPairs -- \n ← allPairs.filterM (fun (_, s) => do\n isElabPrompt s )\n let kwPairs ← keywordBasedPrompts docPair s\n return (\n (pairs ++ kwPairs).toList.eraseDups.toArray, simJsonOut)\n\n/-- choosing pairs to build a prompt -/\ndef getPromptPairsGeneral(s: String)(numSim : Nat)(field: String := \"doc_string\")\n (theoremField : String := \"theorem\")\n : TermElabM (Array (String × String) × IO.Process.Output) := do\n let jsData := Json.mkObj [\n (\"filename\", fileName),\n (\"field\", field),\n (field, s),\n (\"n\", numSim),\n (\"model_name\", \"all-mpnet-base-v2\")\n ]\n let simJsonOut ← \n IO.Process.output {cmd:= \"curl\", args:= \n #[\"-X\", \"POST\", \"-H\", \"Content-type: application/json\", \"-d\", jsData.pretty, s!\"{← leanAideIP}/nearest_prompts\"]}\n let pairs? ← sentenceSimPairs simJsonOut.stdout theoremField\n -- IO.println s!\"obtained sentence similarity; time : {← IO.monoMsNow}\"\n let allPairs : Array (String × String) ← \n match pairs? with\n | Except.error e =>\n throwError e\n \n | Except.ok pairs => pure pairs \n -- logInfo m!\"all pairs: {allPairs}\" \n return (\n allPairs.toList.eraseDups.toArray, simJsonOut)\n\n\n/-- given string to translate, build prompt and query OpenAI; returns JSON response\n-/\ndef getCodeJson (s: String)(numSim : Nat:= 8)(numKW: Nat := 0)(includeFixed: Bool := Bool.false)(queryNum: Nat := 5)(temp : JsonNumber := ⟨2, 1⟩)(scoreBound: Float := 0.2)(matchBound: Nat := 15) : TermElabM Json := do\n match ← getCachedJson? s with\n | some js => return js\n | none => \n let pending ← pendingJsonQueries.get\n if pending.contains s then pollCacheJson s \n else \n let pending ← pendingJsonQueries.get\n pendingJsonQueries.set (pending.insert s)\n -- work starts here; before this was caching, polling etc\n let (pairs, IOOut) ← \n if numSim > 0 then \n getPromptPairs s numSim numKW scoreBound matchBound \n else pure (#[], ⟨0, \"\", \"\"⟩)\n let pairs := if includeFixed then pairs ++ fixedPrompts else pairs\n let pairs := pairs.filter (fun (s, _) => s.length < 100) \n let prompt := GPT.makePrompt s pairs\n trace[Translate.info] m!\"prompt: \\n{prompt.pretty}\"\n -- mkLog prompt\n let fullJson ← \n gptQuery prompt queryNum temp \n let outJson := \n (fullJson.getObjVal? \"choices\").toOption.getD (Json.arr #[])\n let pending ← pendingJsonQueries.get\n pendingJsonQueries.set (pending.erase s)\n if IOOut.exitCode = 0 then cacheJson s outJson \n else throwError m!\"Web query error: {IOOut.stderr}\"\n return outJson\n\n/-- Given an array of outputs, tries to elaborate them with translation and autocorrection and returns the best choice, throwing an error if nothing elaborates. -/\ndef arrayToExpr (output: Array String) : TermElabM Expr := do\n let output := output.toList.eraseDups.toArray\n trace[Translate.info] m!\"output:\\n{output}\"\n -- mkLog output\n let mut elaborated : Array String := Array.empty\n -- translation, autocorrection and filtering by elaboration\n for out in output do\n let ployElab? ← polyElabThmTrans out\n match ployElab? with\n | Except.error _ => pure ()\n | Except.ok es =>\n for (_ , _, s) in es do\n elaborated := elaborated.push s \n if elaborated.isEmpty then do\n -- information with failed logs\n logWarning m!\"No valid output from Codex; outputs below\"\n for out in output do\n let polyOut ← polyStrThmTrans out\n for str in polyOut do\n logWarning m!\"{str}\"\n mkSyntheticSorry (mkSort levelZero)\n else \n -- grouping by trying to prove equality and selecting\n let groupSorted ← groupFuncStrs elaborated\n let topStr := groupSorted[0]![0]!\n let thmExc ← elabFuncTyp topStr\n match thmExc with\n | Except.ok (_, thm) => return thm\n | Except.error s => throwError s\n\n/-- Given an array of outputs, tries to elaborate them with translation and autocorrection and returns the best choice, throwing an error if nothing elaborates. -/\ndef arrayToStx (output: Array String) : TermElabM Syntax := do\n let output := output.toList.eraseDups.toArray\n trace[Translate.info] m!\"output:\\n{output}\"\n -- mkLog output\n let mut elaborated : Array String := Array.empty\n -- translation, autocorrection and filtering by elaboration\n for out in output do\n let ployElab? ← polyElabThmTrans out\n match ployElab? with\n | Except.error _ => pure ()\n | Except.ok es =>\n for (_ , _, s) in es do\n elaborated := elaborated.push s \n if elaborated.isEmpty then do\n -- information with failed logs\n logWarning m!\"No valid output from Codex; outputs below\"\n for out in output do\n let polyOut ← polyStrThmTrans out\n for str in polyOut do\n logWarning m!\"{str}\"\n pure Syntax.missing\n else \n -- grouping by trying to prove equality and selecting\n let groupSorted ← groupFuncStrs elaborated\n let topStr := groupSorted[0]![0]!\n let thmExc ← elabFuncTyp topStr\n match thmExc with\n | Except.ok (stx, _) => return stx\n | Except.error s => throwError s\n\n/-- Given an array of outputs, tries to elaborate them with translation and autocorrection and optionally returns the best choice as well as all elaborated terms (used for batch processing, interactive code uses `arrayToExpr` instead) -/\ndef arrayToExpr? (output: Array String) : TermElabM (Option (Expr× (Array String))) := do\n -- IO.println s!\"arrayToExpr? called with {output.size} outputs\"\n let mut elaborated : Array String := Array.empty\n let mut fullElaborated : Array String := Array.empty\n for out in output do\n -- IO.println s!\"elaboration called: {out}\"\n let ployElab? ← polyElabThmTrans out\n match ployElab? with\n | Except.error _ => pure ()\n | Except.ok es =>\n for (expr, _, s) in es do\n elaborated := elaborated.push s \n if !expr.hasExprMVar then\n fullElaborated := fullElaborated.push s\n if elaborated.isEmpty then \n elabLog \"No valid output from Codex; outputs below\"\n for out in output do\n let polyOut ← polyStrThmTrans out\n for str in polyOut do\n elabLog s!\"{str}\"\n return none\n else \n let priority := \n if fullElaborated.isEmpty then elaborated else fullElaborated\n let groupSorted ← groupFuncStrs priority\n let topStr := groupSorted[0]![0]!\n let thmExc ← elabFuncTyp topStr\n match thmExc with\n | Except.ok (_, thm) => return some (thm, elaborated)\n | Except.error s =>\n elabLog s!\"Second round error : {s}\"\n return none\n\ndef greedyArrayToExpr? (output: Array String) : TermElabM (Option Expr) := do\n output.findSomeM? <| fun out => do\n let t? ← elabThmTrans? out\n return t?.map fun (expr, _, _) => expr\n\n/-- reverse translation from `Lean` to natural language -/\ndef leanToPrompt (thm: String)(numSim : Nat:= 5)(numKW: Nat := 1)(temp : JsonNumber := 0)(scoreBound: Float := 0.2)(matchBound: Nat := 15)(textField : String := \"text\") : TermElabM String := do\n let (pairs, _) ← getPromptPairs thm numSim numKW scoreBound matchBound\n let prompt := GPT.makeFlipPrompt thm pairs\n -- elabLog prompt\n let fullJson ← gptQuery prompt 1 temp\n let outJson := \n (fullJson.getObjVal? \"choices\").toOption.getD (Json.arr #[])\n let out? := (outJson.getArrVal? 0).bind fun js => js.getObjVal? textField\n let outJson := \n match (out?) with\n | Except.error s => Json.str s!\"query for translation failed: {s}\" \n | Except.ok js => js\n return outJson.getStr!\n\n/-- reverse translation from `Lean` to natural language -/\n@[deprecated leanToPrompt]\ndef statementToDoc (thm: String)(numSim : Nat:= 5)(temp : JsonNumber := 0) : TermElabM String := do\n let (pairs, _) ← getPromptPairsGeneral thm numSim \"statement\"\n let prompt := makeFlipStatementsPrompt thm pairs\n -- elabLog prompt\n let fullJson ← openAIQuery prompt 1 temp\n let outJson := \n (fullJson.getObjVal? \"choices\").toOption.getD (Json.arr #[])\n let out? := (outJson.getArrVal? 0).bind fun js => js.getObjVal? \"text\"\n let outJson := \n match (out?) with\n | Except.error s => Json.str s!\"query for translation failed: {s}\" \n | Except.ok js => js\n return outJson.getStr!\n\ndef egThm := \"theorem eg_thm : ∀ n: Nat, ∃ m : Nat, m > n ∧ m % 2 = 0\"\n\ndef egPairs := getPromptPairsGeneral egThm 5 \"statement\" \"statement\"\n\ndef egPrompt := do\n let (pairs, _) ← egPairs\n return makeFlipStatementsPrompt egThm pairs\n\n-- #eval egPrompt\n\n-- #eval statementToDoc egThm 5 0\n\n-- #eval leanToPrompt \"∀ {p : ℕ} [inst : Fact (Nat.Prime p)], p = 2 ∨ p % 2 = 1\"\n\n-- #eval leanToPrompt \"∀ {α : Type u} {x : FreeGroup α}, x ≠ 1 → ¬IsOfFinOrder x\"\n\n-- #eval leanToPrompt \"{ n : ℕ } -> Even ( ( n + 1 ) * n )\"\n\n/-- array of outputs extracted from OpenAI Json -/\ndef jsonToExprStrArray (json: Json) : TermElabM (Array String) := do\n let outArr : Array String ← \n match json.getArr? with\n | Except.ok arr => \n let parsedArr : Array String ← \n arr.filterMapM <| fun js =>\n match js.getObjVal? \"text\" with\n | Except.ok jsstr =>\n match jsstr.getStr? with\n | Except.ok str => pure (some str)\n | Except.error e => \n throwError m!\"json string expected but got {js}, error: {e}\"\n | Except.error _ =>\n throwError m!\"no text field\"\n pure parsedArr\n | Except.error e => throwError m!\"json parsing error: {e}\"\n return outArr\n\n/-- array of outputs extracted from Json Array -/\ndef jsonStringToExprStrArray (jsString: String) : TermElabM (Array String) := do\n try\n let json ← readJson jsString\n let outArr : Array String ← \n match json.getArr? with\n | Except.ok arr => \n let parsedArr : Array String ← \n arr.filterMapM <| fun js =>\n match js.getStr? with\n | Except.ok str => pure (some str)\n | Except.error e => \n throwError m!\"json string expected but got {js}, error: {e}\"\n pure parsedArr\n | Except.error _ => pure #[jsString]\n return outArr\n catch _ =>\n pure #[jsString]\n\n-- #eval jsonStringToExprStrArray \"simple\"\n-- #eval jsonStringToExprStrArray \"[\\\"simple\\\", \\\"simple2\\\"]\"\n\n\n/-- given json returned by open-ai obtain the best translation -/\ndef jsonToExpr' (json: Json) : TermElabM Expr := do\n let output ← GPT.jsonToExprStrArray json\n arrayToExpr output\n\n/-- translation from a comment-like syntax to a theorem statement -/\nelab \"//-\" cb:commentBody : term => do\n let s := cb.raw.getAtomVal\n let s := (s.dropRight 2).trim \n -- querying codex\n let js ← getCodeJson s\n -- filtering, autocorrection and selection\n let e ← jsonToExpr' js\n trace[Translate.info] m!\"{e}\"\n return e\n\ndef uncurriedView(numArgs: Nat)(e: Expr) : MetaM String :=\n match numArgs with\n | 0 => do return \" : \" ++ (← e.view)\n | k +1 => \n match e with\n | Expr.forallE n t _ bi => do\n let core := s!\"{n.eraseMacroScopes} : {← t.view}\"\n let typeString :=s!\"{← t.view}\"\n let argString := match bi with\n | BinderInfo.implicit => \"{\"++ core ++ \"}\"\n | BinderInfo.strictImplicit => \"{{ \"++ core ++ \"}}\"\n | BinderInfo.instImplicit =>\n if (`inst).isPrefixOf n then s!\"[{typeString}]\"\n else s!\"[{core}]\"\n | BinderInfo.default => s!\"({core})\" \n let tail : String ← \n withLocalDecl `func BinderInfo.default e fun func =>\n withLocalDecl n bi t fun arg => do\n let fx := mkAppN func #[arg]\n let newType ← inferType fx\n uncurriedView k newType\n return \" \" ++ argString ++ tail\n | _ => do return \" : \" ++ (← e.view)\n\nelab \"uncurry2\" e:term : term => do\n let e ← Term.elabTerm e none\n let e ← uncurriedView 2 e\n return mkStrLit e\n\nuniverse u\n\n\ndef translateViewM (s: String) : TermElabM String := do\n let js ← getCodeJson s\n let output ← GPT.jsonToExprStrArray js\n trace[Translate.info] m!\"{output}\"\n let e? ← arrayToExpr? output\n match e? with\n | some (e, _) => do\n e.view\n | none => do\n let stx ← output.findSomeM? <| fun s => do\n let exp ← identMappedFunStx s \n return exp.toOption\n return stx.getD \"False\"\n\n\n/-- view of string in core; to be run with Snapshot.runCore\n-/\ndef translateViewCore (s: String) : CoreM String := \n (translateViewM s).run'.run'\n\n\n", "meta": {"author": "siddhartha-gadgil", "repo": "LeanAide", "sha": "7862af73ee2f0be08b20fd3e4148e20bf4a81054", "save_path": "github-repos/lean/siddhartha-gadgil-LeanAide", "path": "github-repos/lean/siddhartha-gadgil-LeanAide/LeanAide-7862af73ee2f0be08b20fd3e4148e20bf4a81054/LeanCodePrompts/Translate.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.22000710486009023, "lm_q2_score": 0.05834583692755956, "lm_q1q2_score": 0.012836498663071322}} {"text": "/-\nCopyright (c) 2018 Chris Hughes. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Chris Hughes, Abhimanyu Pallavi Sudhir\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.default\nimport Mathlib.algebra.geom_sum\nimport Mathlib.data.nat.choose.sum\nimport Mathlib.data.complex.basic\nimport Mathlib.PostPort\n\nuniverses u_1 u_2 u_3 \n\nnamespace Mathlib\n\n/-!\n# Exponential, trigonometric and hyperbolic trigonometric functions\n\nThis file contains the definitions of the real and complex exponential, sine, cosine, tangent,\nhyperbolic sine, hyperbolic cosine, and hyperbolic tangent functions.\n\n-/\n\ntheorem forall_ge_le_of_forall_le_succ {α : Type u_1} [preorder α] (f : ℕ → α) {m : ℕ} (h : ∀ (n : ℕ), n ≥ m → f (Nat.succ n) ≤ f n) {l : ℕ} (k : ℕ) (H : k ≥ m) : k ≤ l → f l ≤ f k := sorry\n\ntheorem is_cau_of_decreasing_bounded {α : Type u_1} [linear_ordered_field α] [archimedean α] (f : ℕ → α) {a : α} {m : ℕ} (ham : ∀ (n : ℕ), n ≥ m → abs (f n) ≤ a) (hnm : ∀ (n : ℕ), n ≥ m → f (Nat.succ n) ≤ f n) : is_cau_seq abs f := sorry\n\ntheorem is_cau_of_mono_bounded {α : Type u_1} [linear_ordered_field α] [archimedean α] (f : ℕ → α) {a : α} {m : ℕ} (ham : ∀ (n : ℕ), n ≥ m → abs (f n) ≤ a) (hnm : ∀ (n : ℕ), n ≥ m → f n ≤ f (Nat.succ n)) : is_cau_seq abs f := sorry\n\ntheorem is_cau_series_of_abv_le_cau {α : Type u_1} {β : Type u_2} [ring β] [linear_ordered_field α] {abv : β → α} [is_absolute_value abv] {f : ℕ → β} {g : ℕ → α} (n : ℕ) : (∀ (m : ℕ), n ≤ m → abv (f m) ≤ g m) →\n (is_cau_seq abs fun (n : ℕ) => finset.sum (finset.range n) fun (i : ℕ) => g i) →\n is_cau_seq abv fun (n : ℕ) => finset.sum (finset.range n) fun (i : ℕ) => f i := sorry\n\ntheorem is_cau_series_of_abv_cau {α : Type u_1} {β : Type u_2} [ring β] [linear_ordered_field α] {abv : β → α} [is_absolute_value abv] {f : ℕ → β} : (is_cau_seq abs fun (m : ℕ) => finset.sum (finset.range m) fun (n : ℕ) => abv (f n)) →\n is_cau_seq abv fun (m : ℕ) => finset.sum (finset.range m) fun (n : ℕ) => f n :=\n is_cau_series_of_abv_le_cau 0 fun (n : ℕ) (h : 0 ≤ n) => le_refl (abv (f n))\n\ntheorem is_cau_geo_series {α : Type u_1} [linear_ordered_field α] [archimedean α] {β : Type u_2} [field β] {abv : β → α} [is_absolute_value abv] (x : β) (hx1 : abv x < 1) : is_cau_seq abv fun (n : ℕ) => finset.sum (finset.range n) fun (m : ℕ) => x ^ m := sorry\n\ntheorem is_cau_geo_series_const {α : Type u_1} [linear_ordered_field α] [archimedean α] (a : α) {x : α} (hx1 : abs x < 1) : is_cau_seq abs fun (m : ℕ) => finset.sum (finset.range m) fun (n : ℕ) => a * x ^ n := sorry\n\ntheorem series_ratio_test {α : Type u_1} {β : Type u_2} [ring β] [linear_ordered_field α] [archimedean α] {abv : β → α} [is_absolute_value abv] {f : ℕ → β} (n : ℕ) (r : α) (hr0 : 0 ≤ r) (hr1 : r < 1) (h : ∀ (m : ℕ), n ≤ m → abv (f (Nat.succ m)) ≤ r * abv (f m)) : is_cau_seq abv fun (m : ℕ) => finset.sum (finset.range m) fun (n : ℕ) => f n := sorry\n\ntheorem sum_range_diag_flip {α : Type u_1} [add_comm_monoid α] (n : ℕ) (f : ℕ → ℕ → α) : (finset.sum (finset.range n) fun (m : ℕ) => finset.sum (finset.range (m + 1)) fun (k : ℕ) => f k (m - k)) =\n finset.sum (finset.range n) fun (m : ℕ) => finset.sum (finset.range (n - m)) fun (k : ℕ) => f m k := sorry\n\ntheorem sum_range_sub_sum_range {α : Type u_1} [add_comm_group α] {f : ℕ → α} {n : ℕ} {m : ℕ} (hnm : n ≤ m) : ((finset.sum (finset.range m) fun (k : ℕ) => f k) - finset.sum (finset.range n) fun (k : ℕ) => f k) =\n finset.sum (finset.filter (fun (k : ℕ) => n ≤ k) (finset.range m)) fun (k : ℕ) => f k := sorry\n\ntheorem abv_sum_le_sum_abv {α : Type u_1} {β : Type u_2} [ring β] [linear_ordered_field α] {abv : β → α} [is_absolute_value abv] {γ : Type u_3} (f : γ → β) (s : finset γ) : abv (finset.sum s fun (k : γ) => f k) ≤ finset.sum s fun (k : γ) => abv (f k) := sorry\n\ntheorem cauchy_product {α : Type u_1} {β : Type u_2} [ring β] [linear_ordered_field α] {abv : β → α} [is_absolute_value abv] {a : ℕ → β} {b : ℕ → β} (ha : is_cau_seq abs fun (m : ℕ) => finset.sum (finset.range m) fun (n : ℕ) => abv (a n)) (hb : is_cau_seq abv fun (m : ℕ) => finset.sum (finset.range m) fun (n : ℕ) => b n) (ε : α) (ε0 : 0 < ε) : ∃ (i : ℕ),\n ∀ (j : ℕ),\n j ≥ i →\n abv\n (((finset.sum (finset.range j) fun (k : ℕ) => a k) * finset.sum (finset.range j) fun (n : ℕ) => b n) -\n finset.sum (finset.range j)\n fun (n : ℕ) => finset.sum (finset.range (n + 1)) fun (m : ℕ) => a m * b (n - m)) <\n ε := sorry\n\nnamespace complex\n\n\ntheorem is_cau_abs_exp (z : ℂ) : is_cau_seq abs fun (n : ℕ) => finset.sum (finset.range n) fun (m : ℕ) => abs (z ^ m / ↑(nat.factorial m)) := sorry\n\ntheorem is_cau_exp (z : ℂ) : is_cau_seq abs fun (n : ℕ) => finset.sum (finset.range n) fun (m : ℕ) => z ^ m / ↑(nat.factorial m) :=\n is_cau_series_of_abv_cau (is_cau_abs_exp z)\n\n/-- The Cauchy sequence consisting of partial sums of the Taylor series of\nthe complex exponential function -/\ndef exp' (z : ℂ) : cau_seq ℂ abs :=\n { val := fun (n : ℕ) => finset.sum (finset.range n) fun (m : ℕ) => z ^ m / ↑(nat.factorial m),\n property := is_cau_exp z }\n\n/-- The complex exponential function, defined via its Taylor series -/\ndef exp (z : ℂ) : ℂ :=\n cau_seq.lim (exp' z)\n\n/-- The complex sine function, defined via `exp` -/\ndef sin (z : ℂ) : ℂ :=\n (exp (-z * I) - exp (z * I)) * I / bit0 1\n\n/-- The complex cosine function, defined via `exp` -/\ndef cos (z : ℂ) : ℂ :=\n (exp (z * I) + exp (-z * I)) / bit0 1\n\n/-- The complex tangent function, defined as `sin z / cos z` -/\ndef tan (z : ℂ) : ℂ :=\n sin z / cos z\n\n/-- The complex hyperbolic sine function, defined via `exp` -/\ndef sinh (z : ℂ) : ℂ :=\n (exp z - exp (-z)) / bit0 1\n\n/-- The complex hyperbolic cosine function, defined via `exp` -/\ndef cosh (z : ℂ) : ℂ :=\n (exp z + exp (-z)) / bit0 1\n\n/-- The complex hyperbolic tangent function, defined as `sinh z / cosh z` -/\ndef tanh (z : ℂ) : ℂ :=\n sinh z / cosh z\n\nend complex\n\n\nnamespace real\n\n\n/-- The real exponential function, defined as the real part of the complex exponential -/\ndef exp (x : ℝ) : ℝ :=\n complex.re (complex.exp ↑x)\n\n/-- The real sine function, defined as the real part of the complex sine -/\ndef sin (x : ℝ) : ℝ :=\n complex.re (complex.sin ↑x)\n\n/-- The real cosine function, defined as the real part of the complex cosine -/\ndef cos (x : ℝ) : ℝ :=\n complex.re (complex.cos ↑x)\n\n/-- The real tangent function, defined as the real part of the complex tangent -/\ndef tan (x : ℝ) : ℝ :=\n complex.re (complex.tan ↑x)\n\n/-- The real hypebolic sine function, defined as the real part of the complex hyperbolic sine -/\ndef sinh (x : ℝ) : ℝ :=\n complex.re (complex.sinh ↑x)\n\n/-- The real hypebolic cosine function, defined as the real part of the complex hyperbolic cosine -/\ndef cosh (x : ℝ) : ℝ :=\n complex.re (complex.cosh ↑x)\n\n/-- The real hypebolic tangent function, defined as the real part of\nthe complex hyperbolic tangent -/\ndef tanh (x : ℝ) : ℝ :=\n complex.re (complex.tanh ↑x)\n\nend real\n\n\nnamespace complex\n\n\n@[simp] theorem exp_zero : exp 0 = 1 := sorry\n\ntheorem exp_add (x : ℂ) (y : ℂ) : exp (x + y) = exp x * exp y := sorry\n\ntheorem exp_list_sum (l : List ℂ) : exp (list.sum l) = list.prod (list.map exp l) :=\n monoid_hom.map_list_prod (monoid_hom.mk exp exp_zero exp_add) l\n\ntheorem exp_multiset_sum (s : multiset ℂ) : exp (multiset.sum s) = multiset.prod (multiset.map exp s) :=\n monoid_hom.map_multiset_prod (monoid_hom.mk exp exp_zero exp_add) s\n\ntheorem exp_sum {α : Type u_1} (s : finset α) (f : α → ℂ) : exp (finset.sum s fun (x : α) => f x) = finset.prod s fun (x : α) => exp (f x) :=\n monoid_hom.map_prod (monoid_hom.mk exp exp_zero exp_add) f s\n\ntheorem exp_nat_mul (x : ℂ) (n : ℕ) : exp (↑n * x) = exp x ^ n := sorry\n\ntheorem exp_ne_zero (x : ℂ) : exp x ≠ 0 := sorry\n\ntheorem exp_neg (x : ℂ) : exp (-x) = (exp x⁻¹) := sorry\n\ntheorem exp_sub (x : ℂ) (y : ℂ) : exp (x - y) = exp x / exp y := sorry\n\n@[simp] theorem exp_conj (x : ℂ) : exp (coe_fn conj x) = coe_fn conj (exp x) := sorry\n\n@[simp] theorem of_real_exp_of_real_re (x : ℝ) : ↑(re (exp ↑x)) = exp ↑x :=\n iff.mp eq_conj_iff_re\n (eq.mpr (id (Eq._oldrec (Eq.refl (coe_fn conj (exp ↑x) = exp ↑x)) (Eq.symm (exp_conj ↑x))))\n (eq.mpr (id (Eq._oldrec (Eq.refl (exp (coe_fn conj ↑x) = exp ↑x)) (conj_of_real x))) (Eq.refl (exp ↑x))))\n\n@[simp] theorem of_real_exp (x : ℝ) : ↑(real.exp x) = exp ↑x :=\n of_real_exp_of_real_re x\n\n@[simp] theorem exp_of_real_im (x : ℝ) : im (exp ↑x) = 0 :=\n eq.mpr (id (Eq._oldrec (Eq.refl (im (exp ↑x) = 0)) (Eq.symm (of_real_exp_of_real_re x))))\n (eq.mpr (id (Eq._oldrec (Eq.refl (im ↑(re (exp ↑x)) = 0)) (of_real_im (re (exp ↑x))))) (Eq.refl 0))\n\ntheorem exp_of_real_re (x : ℝ) : re (exp ↑x) = real.exp x :=\n rfl\n\ntheorem two_sinh (x : ℂ) : bit0 1 * sinh x = exp x - exp (-x) :=\n mul_div_cancel' (exp x - exp (-x)) two_ne_zero'\n\ntheorem two_cosh (x : ℂ) : bit0 1 * cosh x = exp x + exp (-x) :=\n mul_div_cancel' (exp x + exp (-x)) two_ne_zero'\n\n@[simp] theorem sinh_zero : sinh 0 = 0 := sorry\n\n@[simp] theorem sinh_neg (x : ℂ) : sinh (-x) = -sinh x := sorry\n\ntheorem sinh_add (x : ℂ) (y : ℂ) : sinh (x + y) = sinh x * cosh y + cosh x * sinh y := sorry\n\n@[simp] theorem cosh_zero : cosh 0 = 1 := sorry\n\n@[simp] theorem cosh_neg (x : ℂ) : cosh (-x) = cosh x := sorry\n\ntheorem cosh_add (x : ℂ) (y : ℂ) : cosh (x + y) = cosh x * cosh y + sinh x * sinh y := sorry\n\ntheorem sinh_sub (x : ℂ) (y : ℂ) : sinh (x - y) = sinh x * cosh y - cosh x * sinh y := sorry\n\ntheorem cosh_sub (x : ℂ) (y : ℂ) : cosh (x - y) = cosh x * cosh y - sinh x * sinh y := sorry\n\ntheorem sinh_conj (x : ℂ) : sinh (coe_fn conj x) = coe_fn conj (sinh x) := sorry\n\n@[simp] theorem of_real_sinh_of_real_re (x : ℝ) : ↑(re (sinh ↑x)) = sinh ↑x :=\n iff.mp eq_conj_iff_re\n (eq.mpr (id (Eq._oldrec (Eq.refl (coe_fn conj (sinh ↑x) = sinh ↑x)) (Eq.symm (sinh_conj ↑x))))\n (eq.mpr (id (Eq._oldrec (Eq.refl (sinh (coe_fn conj ↑x) = sinh ↑x)) (conj_of_real x))) (Eq.refl (sinh ↑x))))\n\n@[simp] theorem of_real_sinh (x : ℝ) : ↑(real.sinh x) = sinh ↑x :=\n of_real_sinh_of_real_re x\n\n@[simp] theorem sinh_of_real_im (x : ℝ) : im (sinh ↑x) = 0 :=\n eq.mpr (id (Eq._oldrec (Eq.refl (im (sinh ↑x) = 0)) (Eq.symm (of_real_sinh_of_real_re x))))\n (eq.mpr (id (Eq._oldrec (Eq.refl (im ↑(re (sinh ↑x)) = 0)) (of_real_im (re (sinh ↑x))))) (Eq.refl 0))\n\ntheorem sinh_of_real_re (x : ℝ) : re (sinh ↑x) = real.sinh x :=\n rfl\n\ntheorem cosh_conj (x : ℂ) : cosh (coe_fn conj x) = coe_fn conj (cosh x) := sorry\n\n@[simp] theorem of_real_cosh_of_real_re (x : ℝ) : ↑(re (cosh ↑x)) = cosh ↑x :=\n iff.mp eq_conj_iff_re\n (eq.mpr (id (Eq._oldrec (Eq.refl (coe_fn conj (cosh ↑x) = cosh ↑x)) (Eq.symm (cosh_conj ↑x))))\n (eq.mpr (id (Eq._oldrec (Eq.refl (cosh (coe_fn conj ↑x) = cosh ↑x)) (conj_of_real x))) (Eq.refl (cosh ↑x))))\n\n@[simp] theorem of_real_cosh (x : ℝ) : ↑(real.cosh x) = cosh ↑x :=\n of_real_cosh_of_real_re x\n\n@[simp] theorem cosh_of_real_im (x : ℝ) : im (cosh ↑x) = 0 :=\n eq.mpr (id (Eq._oldrec (Eq.refl (im (cosh ↑x) = 0)) (Eq.symm (of_real_cosh_of_real_re x))))\n (eq.mpr (id (Eq._oldrec (Eq.refl (im ↑(re (cosh ↑x)) = 0)) (of_real_im (re (cosh ↑x))))) (Eq.refl 0))\n\ntheorem cosh_of_real_re (x : ℝ) : re (cosh ↑x) = real.cosh x :=\n rfl\n\ntheorem tanh_eq_sinh_div_cosh (x : ℂ) : tanh x = sinh x / cosh x :=\n rfl\n\n@[simp] theorem tanh_zero : tanh 0 = 0 := sorry\n\n@[simp] theorem tanh_neg (x : ℂ) : tanh (-x) = -tanh x := sorry\n\ntheorem tanh_conj (x : ℂ) : tanh (coe_fn conj x) = coe_fn conj (tanh x) := sorry\n\n@[simp] theorem of_real_tanh_of_real_re (x : ℝ) : ↑(re (tanh ↑x)) = tanh ↑x :=\n iff.mp eq_conj_iff_re\n (eq.mpr (id (Eq._oldrec (Eq.refl (coe_fn conj (tanh ↑x) = tanh ↑x)) (Eq.symm (tanh_conj ↑x))))\n (eq.mpr (id (Eq._oldrec (Eq.refl (tanh (coe_fn conj ↑x) = tanh ↑x)) (conj_of_real x))) (Eq.refl (tanh ↑x))))\n\n@[simp] theorem of_real_tanh (x : ℝ) : ↑(real.tanh x) = tanh ↑x :=\n of_real_tanh_of_real_re x\n\n@[simp] theorem tanh_of_real_im (x : ℝ) : im (tanh ↑x) = 0 :=\n eq.mpr (id (Eq._oldrec (Eq.refl (im (tanh ↑x) = 0)) (Eq.symm (of_real_tanh_of_real_re x))))\n (eq.mpr (id (Eq._oldrec (Eq.refl (im ↑(re (tanh ↑x)) = 0)) (of_real_im (re (tanh ↑x))))) (Eq.refl 0))\n\ntheorem tanh_of_real_re (x : ℝ) : re (tanh ↑x) = real.tanh x :=\n rfl\n\ntheorem cosh_add_sinh (x : ℂ) : cosh x + sinh x = exp x := sorry\n\ntheorem sinh_add_cosh (x : ℂ) : sinh x + cosh x = exp x :=\n eq.mpr (id (Eq._oldrec (Eq.refl (sinh x + cosh x = exp x)) (add_comm (sinh x) (cosh x))))\n (eq.mpr (id (Eq._oldrec (Eq.refl (cosh x + sinh x = exp x)) (cosh_add_sinh x))) (Eq.refl (exp x)))\n\ntheorem cosh_sub_sinh (x : ℂ) : cosh x - sinh x = exp (-x) := sorry\n\ntheorem cosh_sq_sub_sinh_sq (x : ℂ) : cosh x ^ bit0 1 - sinh x ^ bit0 1 = 1 := sorry\n\ntheorem cosh_square (x : ℂ) : cosh x ^ bit0 1 = sinh x ^ bit0 1 + 1 := sorry\n\ntheorem sinh_square (x : ℂ) : sinh x ^ bit0 1 = cosh x ^ bit0 1 - 1 := sorry\n\ntheorem cosh_two_mul (x : ℂ) : cosh (bit0 1 * x) = cosh x ^ bit0 1 + sinh x ^ bit0 1 := sorry\n\ntheorem sinh_two_mul (x : ℂ) : sinh (bit0 1 * x) = bit0 1 * sinh x * cosh x := sorry\n\ntheorem cosh_three_mul (x : ℂ) : cosh (bit1 1 * x) = bit0 (bit0 1) * cosh x ^ bit1 1 - bit1 1 * cosh x := sorry\n\ntheorem sinh_three_mul (x : ℂ) : sinh (bit1 1 * x) = bit0 (bit0 1) * sinh x ^ bit1 1 + bit1 1 * sinh x := sorry\n\n@[simp] theorem sin_zero : sin 0 = 0 := sorry\n\n@[simp] theorem sin_neg (x : ℂ) : sin (-x) = -sin x := sorry\n\ntheorem two_sin (x : ℂ) : bit0 1 * sin x = (exp (-x * I) - exp (x * I)) * I :=\n mul_div_cancel' ((exp (-x * I) - exp (x * I)) * I) two_ne_zero'\n\ntheorem two_cos (x : ℂ) : bit0 1 * cos x = exp (x * I) + exp (-x * I) :=\n mul_div_cancel' (exp (x * I) + exp (-x * I)) two_ne_zero'\n\ntheorem sinh_mul_I (x : ℂ) : sinh (x * I) = sin x * I := sorry\n\ntheorem cosh_mul_I (x : ℂ) : cosh (x * I) = cos x := sorry\n\ntheorem tanh_mul_I (x : ℂ) : tanh (x * I) = tan x * I := sorry\n\ntheorem cos_mul_I (x : ℂ) : cos (x * I) = cosh x := sorry\n\ntheorem sin_mul_I (x : ℂ) : sin (x * I) = sinh x * I := sorry\n\ntheorem tan_mul_I (x : ℂ) : tan (x * I) = tanh x * I := sorry\n\ntheorem sin_add (x : ℂ) (y : ℂ) : sin (x + y) = sin x * cos y + cos x * sin y := sorry\n\n@[simp] theorem cos_zero : cos 0 = 1 := sorry\n\n@[simp] theorem cos_neg (x : ℂ) : cos (-x) = cos x := sorry\n\ntheorem cos_add (x : ℂ) (y : ℂ) : cos (x + y) = cos x * cos y - sin x * sin y := sorry\n\ntheorem sin_sub (x : ℂ) (y : ℂ) : sin (x - y) = sin x * cos y - cos x * sin y := sorry\n\ntheorem cos_sub (x : ℂ) (y : ℂ) : cos (x - y) = cos x * cos y + sin x * sin y := sorry\n\ntheorem sin_add_mul_I (x : ℂ) (y : ℂ) : sin (x + y * I) = sin x * cosh y + cos x * sinh y * I := sorry\n\ntheorem sin_eq (z : ℂ) : sin z = sin ↑(re z) * cosh ↑(im z) + cos ↑(re z) * sinh ↑(im z) * I := sorry\n\ntheorem cos_add_mul_I (x : ℂ) (y : ℂ) : cos (x + y * I) = cos x * cosh y - sin x * sinh y * I := sorry\n\ntheorem cos_eq (z : ℂ) : cos z = cos ↑(re z) * cosh ↑(im z) - sin ↑(re z) * sinh ↑(im z) * I := sorry\n\ntheorem sin_sub_sin (x : ℂ) (y : ℂ) : sin x - sin y = bit0 1 * sin ((x - y) / bit0 1) * cos ((x + y) / bit0 1) := sorry\n\ntheorem cos_sub_cos (x : ℂ) (y : ℂ) : cos x - cos y = -bit0 1 * sin ((x + y) / bit0 1) * sin ((x - y) / bit0 1) := sorry\n\ntheorem cos_add_cos (x : ℂ) (y : ℂ) : cos x + cos y = bit0 1 * cos ((x + y) / bit0 1) * cos ((x - y) / bit0 1) := sorry\n\ntheorem sin_conj (x : ℂ) : sin (coe_fn conj x) = coe_fn conj (sin x) := sorry\n\n@[simp] theorem of_real_sin_of_real_re (x : ℝ) : ↑(re (sin ↑x)) = sin ↑x :=\n iff.mp eq_conj_iff_re\n (eq.mpr (id (Eq._oldrec (Eq.refl (coe_fn conj (sin ↑x) = sin ↑x)) (Eq.symm (sin_conj ↑x))))\n (eq.mpr (id (Eq._oldrec (Eq.refl (sin (coe_fn conj ↑x) = sin ↑x)) (conj_of_real x))) (Eq.refl (sin ↑x))))\n\n@[simp] theorem of_real_sin (x : ℝ) : ↑(real.sin x) = sin ↑x :=\n of_real_sin_of_real_re x\n\n@[simp] theorem sin_of_real_im (x : ℝ) : im (sin ↑x) = 0 :=\n eq.mpr (id (Eq._oldrec (Eq.refl (im (sin ↑x) = 0)) (Eq.symm (of_real_sin_of_real_re x))))\n (eq.mpr (id (Eq._oldrec (Eq.refl (im ↑(re (sin ↑x)) = 0)) (of_real_im (re (sin ↑x))))) (Eq.refl 0))\n\ntheorem sin_of_real_re (x : ℝ) : re (sin ↑x) = real.sin x :=\n rfl\n\ntheorem cos_conj (x : ℂ) : cos (coe_fn conj x) = coe_fn conj (cos x) := sorry\n\n@[simp] theorem of_real_cos_of_real_re (x : ℝ) : ↑(re (cos ↑x)) = cos ↑x :=\n iff.mp eq_conj_iff_re\n (eq.mpr (id (Eq._oldrec (Eq.refl (coe_fn conj (cos ↑x) = cos ↑x)) (Eq.symm (cos_conj ↑x))))\n (eq.mpr (id (Eq._oldrec (Eq.refl (cos (coe_fn conj ↑x) = cos ↑x)) (conj_of_real x))) (Eq.refl (cos ↑x))))\n\n@[simp] theorem of_real_cos (x : ℝ) : ↑(real.cos x) = cos ↑x :=\n of_real_cos_of_real_re x\n\n@[simp] theorem cos_of_real_im (x : ℝ) : im (cos ↑x) = 0 :=\n eq.mpr (id (Eq._oldrec (Eq.refl (im (cos ↑x) = 0)) (Eq.symm (of_real_cos_of_real_re x))))\n (eq.mpr (id (Eq._oldrec (Eq.refl (im ↑(re (cos ↑x)) = 0)) (of_real_im (re (cos ↑x))))) (Eq.refl 0))\n\ntheorem cos_of_real_re (x : ℝ) : re (cos ↑x) = real.cos x :=\n rfl\n\n@[simp] theorem tan_zero : tan 0 = 0 := sorry\n\ntheorem tan_eq_sin_div_cos (x : ℂ) : tan x = sin x / cos x :=\n rfl\n\ntheorem tan_mul_cos {x : ℂ} (hx : cos x ≠ 0) : tan x * cos x = sin x :=\n eq.mpr (id (Eq._oldrec (Eq.refl (tan x * cos x = sin x)) (tan_eq_sin_div_cos x)))\n (eq.mpr (id (Eq._oldrec (Eq.refl (sin x / cos x * cos x = sin x)) (div_mul_cancel (sin x) hx))) (Eq.refl (sin x)))\n\n@[simp] theorem tan_neg (x : ℂ) : tan (-x) = -tan x := sorry\n\ntheorem tan_conj (x : ℂ) : tan (coe_fn conj x) = coe_fn conj (tan x) := sorry\n\n@[simp] theorem of_real_tan_of_real_re (x : ℝ) : ↑(re (tan ↑x)) = tan ↑x :=\n iff.mp eq_conj_iff_re\n (eq.mpr (id (Eq._oldrec (Eq.refl (coe_fn conj (tan ↑x) = tan ↑x)) (Eq.symm (tan_conj ↑x))))\n (eq.mpr (id (Eq._oldrec (Eq.refl (tan (coe_fn conj ↑x) = tan ↑x)) (conj_of_real x))) (Eq.refl (tan ↑x))))\n\n@[simp] theorem of_real_tan (x : ℝ) : ↑(real.tan x) = tan ↑x :=\n of_real_tan_of_real_re x\n\n@[simp] theorem tan_of_real_im (x : ℝ) : im (tan ↑x) = 0 :=\n eq.mpr (id (Eq._oldrec (Eq.refl (im (tan ↑x) = 0)) (Eq.symm (of_real_tan_of_real_re x))))\n (eq.mpr (id (Eq._oldrec (Eq.refl (im ↑(re (tan ↑x)) = 0)) (of_real_im (re (tan ↑x))))) (Eq.refl 0))\n\ntheorem tan_of_real_re (x : ℝ) : re (tan ↑x) = real.tan x :=\n rfl\n\ntheorem cos_add_sin_I (x : ℂ) : cos x + sin x * I = exp (x * I) := sorry\n\ntheorem cos_sub_sin_I (x : ℂ) : cos x - sin x * I = exp (-x * I) := sorry\n\n@[simp] theorem sin_sq_add_cos_sq (x : ℂ) : sin x ^ bit0 1 + cos x ^ bit0 1 = 1 := sorry\n\n@[simp] theorem cos_sq_add_sin_sq (x : ℂ) : cos x ^ bit0 1 + sin x ^ bit0 1 = 1 :=\n eq.mpr (id (Eq._oldrec (Eq.refl (cos x ^ bit0 1 + sin x ^ bit0 1 = 1)) (add_comm (cos x ^ bit0 1) (sin x ^ bit0 1))))\n (eq.mpr (id (Eq._oldrec (Eq.refl (sin x ^ bit0 1 + cos x ^ bit0 1 = 1)) (sin_sq_add_cos_sq x))) (Eq.refl 1))\n\ntheorem cos_two_mul' (x : ℂ) : cos (bit0 1 * x) = cos x ^ bit0 1 - sin x ^ bit0 1 := sorry\n\ntheorem cos_two_mul (x : ℂ) : cos (bit0 1 * x) = bit0 1 * cos x ^ bit0 1 - 1 := sorry\n\ntheorem sin_two_mul (x : ℂ) : sin (bit0 1 * x) = bit0 1 * sin x * cos x := sorry\n\ntheorem cos_square (x : ℂ) : cos x ^ bit0 1 = 1 / bit0 1 + cos (bit0 1 * x) / bit0 1 := sorry\n\ntheorem cos_square' (x : ℂ) : cos x ^ bit0 1 = 1 - sin x ^ bit0 1 := sorry\n\ntheorem sin_square (x : ℂ) : sin x ^ bit0 1 = 1 - cos x ^ bit0 1 := sorry\n\ntheorem inv_one_add_tan_sq {x : ℂ} (hx : cos x ≠ 0) : 1 + tan x ^ bit0 1⁻¹ = cos x ^ bit0 1 := sorry\n\ntheorem tan_sq_div_one_add_tan_sq {x : ℂ} (hx : cos x ≠ 0) : tan x ^ bit0 1 / (1 + tan x ^ bit0 1) = sin x ^ bit0 1 := sorry\n\ntheorem cos_three_mul (x : ℂ) : cos (bit1 1 * x) = bit0 (bit0 1) * cos x ^ bit1 1 - bit1 1 * cos x := sorry\n\ntheorem sin_three_mul (x : ℂ) : sin (bit1 1 * x) = bit1 1 * sin x - bit0 (bit0 1) * sin x ^ bit1 1 := sorry\n\ntheorem exp_mul_I (x : ℂ) : exp (x * I) = cos x + sin x * I :=\n Eq.symm (cos_add_sin_I x)\n\ntheorem exp_add_mul_I (x : ℂ) (y : ℂ) : exp (x + y * I) = exp x * (cos y + sin y * I) :=\n eq.mpr (id (Eq._oldrec (Eq.refl (exp (x + y * I) = exp x * (cos y + sin y * I))) (exp_add x (y * I))))\n (eq.mpr (id (Eq._oldrec (Eq.refl (exp x * exp (y * I) = exp x * (cos y + sin y * I))) (exp_mul_I y)))\n (Eq.refl (exp x * (cos y + sin y * I))))\n\ntheorem exp_eq_exp_re_mul_sin_add_cos (x : ℂ) : exp x = exp ↑(re x) * (cos ↑(im x) + sin ↑(im x) * I) := sorry\n\n/-- De Moivre's formula -/\ntheorem cos_add_sin_mul_I_pow (n : ℕ) (z : ℂ) : (cos z + sin z * I) ^ n = cos (↑n * z) + sin (↑n * z) * I := sorry\n\nend complex\n\n\nnamespace real\n\n\n@[simp] theorem exp_zero : exp 0 = 1 := sorry\n\ntheorem exp_add (x : ℝ) (y : ℝ) : exp (x + y) = exp x * exp y := sorry\n\ntheorem exp_list_sum (l : List ℝ) : exp (list.sum l) = list.prod (list.map exp l) :=\n monoid_hom.map_list_prod (monoid_hom.mk exp exp_zero exp_add) l\n\ntheorem exp_multiset_sum (s : multiset ℝ) : exp (multiset.sum s) = multiset.prod (multiset.map exp s) :=\n monoid_hom.map_multiset_prod (monoid_hom.mk exp exp_zero exp_add) s\n\ntheorem exp_sum {α : Type u_1} (s : finset α) (f : α → ℝ) : exp (finset.sum s fun (x : α) => f x) = finset.prod s fun (x : α) => exp (f x) :=\n monoid_hom.map_prod (monoid_hom.mk exp exp_zero exp_add) f s\n\ntheorem exp_nat_mul (x : ℝ) (n : ℕ) : exp (↑n * x) = exp x ^ n := sorry\n\ntheorem exp_ne_zero (x : ℝ) : exp x ≠ 0 := sorry\n\ntheorem exp_neg (x : ℝ) : exp (-x) = (exp x⁻¹) := sorry\n\ntheorem exp_sub (x : ℝ) (y : ℝ) : exp (x - y) = exp x / exp y := sorry\n\n@[simp] theorem sin_zero : sin 0 = 0 := sorry\n\n@[simp] theorem sin_neg (x : ℝ) : sin (-x) = -sin x := sorry\n\ntheorem sin_add (x : ℝ) (y : ℝ) : sin (x + y) = sin x * cos y + cos x * sin y := sorry\n\n@[simp] theorem cos_zero : cos 0 = 1 := sorry\n\n@[simp] theorem cos_neg (x : ℝ) : cos (-x) = cos x := sorry\n\ntheorem cos_add (x : ℝ) (y : ℝ) : cos (x + y) = cos x * cos y - sin x * sin y := sorry\n\ntheorem sin_sub (x : ℝ) (y : ℝ) : sin (x - y) = sin x * cos y - cos x * sin y := sorry\n\ntheorem cos_sub (x : ℝ) (y : ℝ) : cos (x - y) = cos x * cos y + sin x * sin y := sorry\n\ntheorem sin_sub_sin (x : ℝ) (y : ℝ) : sin x - sin y = bit0 1 * sin ((x - y) / bit0 1) * cos ((x + y) / bit0 1) := sorry\n\ntheorem cos_sub_cos (x : ℝ) (y : ℝ) : cos x - cos y = -bit0 1 * sin ((x + y) / bit0 1) * sin ((x - y) / bit0 1) := sorry\n\ntheorem cos_add_cos (x : ℝ) (y : ℝ) : cos x + cos y = bit0 1 * cos ((x + y) / bit0 1) * cos ((x - y) / bit0 1) := sorry\n\ntheorem tan_eq_sin_div_cos (x : ℝ) : tan x = sin x / cos x := sorry\n\ntheorem tan_mul_cos {x : ℝ} (hx : cos x ≠ 0) : tan x * cos x = sin x :=\n eq.mpr (id (Eq._oldrec (Eq.refl (tan x * cos x = sin x)) (tan_eq_sin_div_cos x)))\n (eq.mpr (id (Eq._oldrec (Eq.refl (sin x / cos x * cos x = sin x)) (div_mul_cancel (sin x) hx))) (Eq.refl (sin x)))\n\n@[simp] theorem tan_zero : tan 0 = 0 := sorry\n\n@[simp] theorem tan_neg (x : ℝ) : tan (-x) = -tan x := sorry\n\n@[simp] theorem sin_sq_add_cos_sq (x : ℝ) : sin x ^ bit0 1 + cos x ^ bit0 1 = 1 := sorry\n\n@[simp] theorem cos_sq_add_sin_sq (x : ℝ) : cos x ^ bit0 1 + sin x ^ bit0 1 = 1 :=\n eq.mpr (id (Eq._oldrec (Eq.refl (cos x ^ bit0 1 + sin x ^ bit0 1 = 1)) (add_comm (cos x ^ bit0 1) (sin x ^ bit0 1))))\n (eq.mpr (id (Eq._oldrec (Eq.refl (sin x ^ bit0 1 + cos x ^ bit0 1 = 1)) (sin_sq_add_cos_sq x))) (Eq.refl 1))\n\ntheorem sin_sq_le_one (x : ℝ) : sin x ^ bit0 1 ≤ 1 :=\n eq.mpr (id (Eq._oldrec (Eq.refl (sin x ^ bit0 1 ≤ 1)) (Eq.symm (sin_sq_add_cos_sq x))))\n (le_add_of_nonneg_right (pow_two_nonneg (cos x)))\n\ntheorem cos_sq_le_one (x : ℝ) : cos x ^ bit0 1 ≤ 1 :=\n eq.mpr (id (Eq._oldrec (Eq.refl (cos x ^ bit0 1 ≤ 1)) (Eq.symm (sin_sq_add_cos_sq x))))\n (le_add_of_nonneg_left (pow_two_nonneg (sin x)))\n\ntheorem abs_sin_le_one (x : ℝ) : abs (sin x) ≤ 1 := sorry\n\ntheorem abs_cos_le_one (x : ℝ) : abs (cos x) ≤ 1 := sorry\n\ntheorem sin_le_one (x : ℝ) : sin x ≤ 1 :=\n and.right (iff.mp abs_le (abs_sin_le_one x))\n\ntheorem cos_le_one (x : ℝ) : cos x ≤ 1 :=\n and.right (iff.mp abs_le (abs_cos_le_one x))\n\ntheorem neg_one_le_sin (x : ℝ) : -1 ≤ sin x :=\n and.left (iff.mp abs_le (abs_sin_le_one x))\n\ntheorem neg_one_le_cos (x : ℝ) : -1 ≤ cos x :=\n and.left (iff.mp abs_le (abs_cos_le_one x))\n\ntheorem cos_two_mul (x : ℝ) : cos (bit0 1 * x) = bit0 1 * cos x ^ bit0 1 - 1 := sorry\n\ntheorem cos_two_mul' (x : ℝ) : cos (bit0 1 * x) = cos x ^ bit0 1 - sin x ^ bit0 1 := sorry\n\ntheorem sin_two_mul (x : ℝ) : sin (bit0 1 * x) = bit0 1 * sin x * cos x := sorry\n\ntheorem cos_square (x : ℝ) : cos x ^ bit0 1 = 1 / bit0 1 + cos (bit0 1 * x) / bit0 1 := sorry\n\ntheorem cos_square' (x : ℝ) : cos x ^ bit0 1 = 1 - sin x ^ bit0 1 := sorry\n\ntheorem sin_square (x : ℝ) : sin x ^ bit0 1 = 1 - cos x ^ bit0 1 :=\n iff.mpr eq_sub_iff_add_eq (sin_sq_add_cos_sq x)\n\ntheorem inv_one_add_tan_sq {x : ℝ} (hx : cos x ≠ 0) : 1 + tan x ^ bit0 1⁻¹ = cos x ^ bit0 1 := sorry\n\ntheorem tan_sq_div_one_add_tan_sq {x : ℝ} (hx : cos x ≠ 0) : tan x ^ bit0 1 / (1 + tan x ^ bit0 1) = sin x ^ bit0 1 := sorry\n\ntheorem inv_sqrt_one_add_tan_sq {x : ℝ} (hx : 0 < cos x) : sqrt (1 + tan x ^ bit0 1)⁻¹ = cos x := sorry\n\ntheorem tan_div_sqrt_one_add_tan_sq {x : ℝ} (hx : 0 < cos x) : tan x / sqrt (1 + tan x ^ bit0 1) = sin x := sorry\n\ntheorem cos_three_mul (x : ℝ) : cos (bit1 1 * x) = bit0 (bit0 1) * cos x ^ bit1 1 - bit1 1 * cos x := sorry\n\ntheorem sin_three_mul (x : ℝ) : sin (bit1 1 * x) = bit1 1 * sin x - bit0 (bit0 1) * sin x ^ bit1 1 := sorry\n\n/-- The definition of `sinh` in terms of `exp`. -/\ntheorem sinh_eq (x : ℝ) : sinh x = (exp x - exp (-x)) / bit0 1 := sorry\n\n@[simp] theorem sinh_zero : sinh 0 = 0 := sorry\n\n@[simp] theorem sinh_neg (x : ℝ) : sinh (-x) = -sinh x := sorry\n\ntheorem sinh_add (x : ℝ) (y : ℝ) : sinh (x + y) = sinh x * cosh y + cosh x * sinh y := sorry\n\n/-- The definition of `cosh` in terms of `exp`. -/\ntheorem cosh_eq (x : ℝ) : cosh x = (exp x + exp (-x)) / bit0 1 := sorry\n\n@[simp] theorem cosh_zero : cosh 0 = 1 := sorry\n\n@[simp] theorem cosh_neg (x : ℝ) : cosh (-x) = cosh x := sorry\n\ntheorem cosh_add (x : ℝ) (y : ℝ) : cosh (x + y) = cosh x * cosh y + sinh x * sinh y := sorry\n\ntheorem sinh_sub (x : ℝ) (y : ℝ) : sinh (x - y) = sinh x * cosh y - cosh x * sinh y := sorry\n\ntheorem cosh_sub (x : ℝ) (y : ℝ) : cosh (x - y) = cosh x * cosh y - sinh x * sinh y := sorry\n\ntheorem tanh_eq_sinh_div_cosh (x : ℝ) : tanh x = sinh x / cosh x := sorry\n\n@[simp] theorem tanh_zero : tanh 0 = 0 := sorry\n\n@[simp] theorem tanh_neg (x : ℝ) : tanh (-x) = -tanh x := sorry\n\ntheorem cosh_add_sinh (x : ℝ) : cosh x + sinh x = exp x := sorry\n\ntheorem sinh_add_cosh (x : ℝ) : sinh x + cosh x = exp x := sorry\n\ntheorem cosh_sq_sub_sinh_sq (x : ℝ) : cosh x ^ bit0 1 - sinh x ^ bit0 1 = 1 := sorry\n\ntheorem cosh_square (x : ℝ) : cosh x ^ bit0 1 = sinh x ^ bit0 1 + 1 := sorry\n\ntheorem sinh_square (x : ℝ) : sinh x ^ bit0 1 = cosh x ^ bit0 1 - 1 := sorry\n\ntheorem cosh_two_mul (x : ℝ) : cosh (bit0 1 * x) = cosh x ^ bit0 1 + sinh x ^ bit0 1 := sorry\n\ntheorem sinh_two_mul (x : ℝ) : sinh (bit0 1 * x) = bit0 1 * sinh x * cosh x := sorry\n\ntheorem cosh_three_mul (x : ℝ) : cosh (bit1 1 * x) = bit0 (bit0 1) * cosh x ^ bit1 1 - bit1 1 * cosh x := sorry\n\ntheorem sinh_three_mul (x : ℝ) : sinh (bit1 1 * x) = bit0 (bit0 1) * sinh x ^ bit1 1 + bit1 1 * sinh x := sorry\n\n/- TODO make this private and prove ∀ x -/\n\ntheorem add_one_le_exp_of_nonneg {x : ℝ} (hx : 0 ≤ x) : x + 1 ≤ exp x := sorry\n\ntheorem one_le_exp {x : ℝ} (hx : 0 ≤ x) : 1 ≤ exp x := sorry\n\ntheorem exp_pos (x : ℝ) : 0 < exp x := sorry\n\n@[simp] theorem abs_exp (x : ℝ) : abs (exp x) = exp x :=\n abs_of_pos (exp_pos x)\n\ntheorem exp_strict_mono : strict_mono exp := sorry\n\ntheorem exp_monotone {x : ℝ} {y : ℝ} : x ≤ y → exp x ≤ exp y :=\n strict_mono.monotone exp_strict_mono\n\n@[simp] theorem exp_lt_exp {x : ℝ} {y : ℝ} : exp x < exp y ↔ x < y :=\n strict_mono.lt_iff_lt exp_strict_mono\n\n@[simp] theorem exp_le_exp {x : ℝ} {y : ℝ} : exp x ≤ exp y ↔ x ≤ y :=\n strict_mono.le_iff_le exp_strict_mono\n\ntheorem exp_injective : function.injective exp :=\n strict_mono.injective exp_strict_mono\n\n@[simp] theorem exp_eq_exp {x : ℝ} {y : ℝ} : exp x = exp y ↔ x = y :=\n function.injective.eq_iff exp_injective\n\n@[simp] theorem exp_eq_one_iff (x : ℝ) : exp x = 1 ↔ x = 0 :=\n eq.mpr (id (Eq._oldrec (Eq.refl (exp x = 1 ↔ x = 0)) (Eq.symm exp_zero)))\n (eq.mpr (id (Eq._oldrec (Eq.refl (exp x = exp 0 ↔ x = 0)) (propext (function.injective.eq_iff exp_injective))))\n (iff.refl (x = 0)))\n\n@[simp] theorem one_lt_exp_iff {x : ℝ} : 1 < exp x ↔ 0 < x :=\n eq.mpr (id (Eq._oldrec (Eq.refl (1 < exp x ↔ 0 < x)) (Eq.symm exp_zero)))\n (eq.mpr (id (Eq._oldrec (Eq.refl (exp 0 < exp x ↔ 0 < x)) (propext exp_lt_exp))) (iff.refl (0 < x)))\n\n@[simp] theorem exp_lt_one_iff {x : ℝ} : exp x < 1 ↔ x < 0 :=\n eq.mpr (id (Eq._oldrec (Eq.refl (exp x < 1 ↔ x < 0)) (Eq.symm exp_zero)))\n (eq.mpr (id (Eq._oldrec (Eq.refl (exp x < exp 0 ↔ x < 0)) (propext exp_lt_exp))) (iff.refl (x < 0)))\n\n@[simp] theorem exp_le_one_iff {x : ℝ} : exp x ≤ 1 ↔ x ≤ 0 :=\n exp_zero ▸ exp_le_exp\n\n@[simp] theorem one_le_exp_iff {x : ℝ} : 1 ≤ exp x ↔ 0 ≤ x :=\n exp_zero ▸ exp_le_exp\n\n/-- `real.cosh` is always positive -/\ntheorem cosh_pos (x : ℝ) : 0 < cosh x :=\n Eq.symm (cosh_eq x) ▸ half_pos (add_pos (exp_pos x) (exp_pos (-x)))\n\nend real\n\n\nnamespace complex\n\n\ntheorem sum_div_factorial_le {α : Type u_1} [linear_ordered_field α] (n : ℕ) (j : ℕ) (hn : 0 < n) : (finset.sum (finset.filter (fun (k : ℕ) => n ≤ k) (finset.range j)) fun (m : ℕ) => 1 / ↑(nat.factorial m)) ≤\n ↑(Nat.succ n) * (↑(nat.factorial n) * ↑n⁻¹) := sorry\n\ntheorem exp_bound {x : ℂ} (hx : abs x ≤ 1) {n : ℕ} (hn : 0 < n) : abs (exp x - finset.sum (finset.range n) fun (m : ℕ) => x ^ m / ↑(nat.factorial m)) ≤\n abs x ^ n * (↑(Nat.succ n) * (↑(nat.factorial n) * ↑n⁻¹)) := sorry\n\ntheorem abs_exp_sub_one_le {x : ℂ} (hx : abs x ≤ 1) : abs (exp x - 1) ≤ bit0 1 * abs x := sorry\n\ntheorem abs_exp_sub_one_sub_id_le {x : ℂ} (hx : abs x ≤ 1) : abs (exp x - 1 - x) ≤ abs x ^ bit0 1 := sorry\n\nend complex\n\n\nnamespace real\n\n\ntheorem exp_bound {x : ℝ} (hx : abs x ≤ 1) {n : ℕ} (hn : 0 < n) : abs (exp x - finset.sum (finset.range n) fun (m : ℕ) => x ^ m / ↑(nat.factorial m)) ≤\n abs x ^ n * (↑(Nat.succ n) / (↑(nat.factorial n) * ↑n)) := sorry\n\n/-- A finite initial segment of the exponential series, followed by an arbitrary tail.\nFor fixed `n` this is just a linear map wrt `r`, and each map is a simple linear function\nof the previous (see `exp_near_succ`), with `exp_near n x r ⟶ exp x` as `n ⟶ ∞`,\nfor any `r`. -/\ndef exp_near (n : ℕ) (x : ℝ) (r : ℝ) : ℝ :=\n (finset.sum (finset.range n) fun (m : ℕ) => x ^ m / ↑(nat.factorial m)) + x ^ n / ↑(nat.factorial n) * r\n\n@[simp] theorem exp_near_zero (x : ℝ) (r : ℝ) : exp_near 0 x r = r := sorry\n\n@[simp] theorem exp_near_succ (n : ℕ) (x : ℝ) (r : ℝ) : exp_near (n + 1) x r = exp_near n x (1 + x / (↑n + 1) * r) := sorry\n\ntheorem exp_near_sub (n : ℕ) (x : ℝ) (r₁ : ℝ) (r₂ : ℝ) : exp_near n x r₁ - exp_near n x r₂ = x ^ n / ↑(nat.factorial n) * (r₁ - r₂) := sorry\n\ntheorem exp_approx_end (n : ℕ) (m : ℕ) (x : ℝ) (e₁ : n + 1 = m) (h : abs x ≤ 1) : abs (exp x - exp_near m x 0) ≤ abs x ^ m / ↑(nat.factorial m) * ((↑m + 1) / ↑m) := sorry\n\ntheorem exp_approx_succ {n : ℕ} {x : ℝ} {a₁ : ℝ} {b₁ : ℝ} (m : ℕ) (e₁ : n + 1 = m) (a₂ : ℝ) (b₂ : ℝ) (e : abs (1 + x / ↑m * a₂ - a₁) ≤ b₁ - abs x / ↑m * b₂) (h : abs (exp x - exp_near m x a₂) ≤ abs x ^ m / ↑(nat.factorial m) * b₂) : abs (exp x - exp_near n x a₁) ≤ abs x ^ n / ↑(nat.factorial n) * b₁ := sorry\n\ntheorem exp_approx_end' {n : ℕ} {x : ℝ} {a : ℝ} {b : ℝ} (m : ℕ) (e₁ : n + 1 = m) (rm : ℝ) (er : ↑m = rm) (h : abs x ≤ 1) (e : abs (1 - a) ≤ b - abs x / rm * ((rm + 1) / rm)) : abs (exp x - exp_near n x a) ≤ abs x ^ n / ↑(nat.factorial n) * b := sorry\n\ntheorem exp_1_approx_succ_eq {n : ℕ} {a₁ : ℝ} {b₁ : ℝ} {m : ℕ} (en : n + 1 = m) {rm : ℝ} (er : ↑m = rm) (h : abs (exp 1 - exp_near m 1 ((a₁ - 1) * rm)) ≤ abs 1 ^ m / ↑(nat.factorial m) * (b₁ * rm)) : abs (exp 1 - exp_near n 1 a₁) ≤ abs 1 ^ n / ↑(nat.factorial n) * b₁ := sorry\n\ntheorem exp_approx_start (x : ℝ) (a : ℝ) (b : ℝ) (h : abs (exp x - exp_near 0 x a) ≤ abs x ^ 0 / ↑(nat.factorial 0) * b) : abs (exp x - a) ≤ b := sorry\n\ntheorem cos_bound {x : ℝ} (hx : abs x ≤ 1) : abs (cos x - (1 - x ^ bit0 1 / bit0 1)) ≤\n abs x ^ bit0 (bit0 1) * (bit1 (bit0 1) / bit0 (bit0 (bit0 (bit0 (bit0 (bit1 1)))))) := sorry\n\ntheorem sin_bound {x : ℝ} (hx : abs x ≤ 1) : abs (sin x - (x - x ^ bit1 1 / bit0 (bit1 1))) ≤\n abs x ^ bit0 (bit0 1) * (bit1 (bit0 1) / bit0 (bit0 (bit0 (bit0 (bit0 (bit1 1)))))) := sorry\n\ntheorem cos_pos_of_le_one {x : ℝ} (hx : abs x ≤ 1) : 0 < cos x := sorry\n\ntheorem sin_pos_of_pos_of_le_one {x : ℝ} (hx0 : 0 < x) (hx : x ≤ 1) : 0 < sin x := sorry\n\ntheorem sin_pos_of_pos_of_le_two {x : ℝ} (hx0 : 0 < x) (hx : x ≤ bit0 1) : 0 < sin x := sorry\n\ntheorem cos_one_le : cos 1 ≤ bit0 1 / bit1 1 := sorry\n\ntheorem cos_one_pos : 0 < cos 1 := sorry\n\ntheorem cos_two_neg : cos (bit0 1) < 0 := sorry\n\nend real\n\n\nnamespace complex\n\n\ntheorem abs_cos_add_sin_mul_I (x : ℝ) : abs (cos ↑x + sin ↑x * I) = 1 := sorry\n\ntheorem abs_exp_eq_iff_re_eq {x : ℂ} {y : ℂ} : abs (exp x) = abs (exp y) ↔ re x = re y := sorry\n\n@[simp] theorem abs_exp_of_real (x : ℝ) : abs (exp ↑x) = real.exp x :=\n eq.mpr (id (Eq._oldrec (Eq.refl (abs (exp ↑x) = real.exp x)) (Eq.symm (of_real_exp x))))\n (abs_of_nonneg (le_of_lt (real.exp_pos x)))\n\n", "meta": {"author": "AurelienSaue", "repo": "Mathlib4_auto", "sha": "590df64109b08190abe22358fabc3eae000943f2", "save_path": "github-repos/lean/AurelienSaue-Mathlib4_auto", "path": "github-repos/lean/AurelienSaue-Mathlib4_auto/Mathlib4_auto-590df64109b08190abe22358fabc3eae000943f2/Mathlib/data/complex/exponential.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.39233684437737093, "lm_q2_score": 0.03258974453112602, "lm_q1q2_score": 0.012786157528406665}} {"text": "import pseudo_normed_group.category\nimport for_mathlib.AddCommGroup.explicit_limits\n\nimport topology.category.Compactum\n\nopen category_theory\nopen category_theory.limits\n\nuniverse u\nvariables {J : Type u} [small_category J]\n\nstructure PseuNormGrp₁ :=\n(carrier : Type u)\n[str : pseudo_normed_group carrier]\n(exhaustive' : ∀ x : carrier, ∃ c : nnreal,\n x ∈ pseudo_normed_group.filtration carrier c)\n\nnamespace PseuNormGrp₁\n\ninstance : has_coe_to_sort PseuNormGrp₁.{u} (Type u) := ⟨carrier⟩\ninstance (M : PseuNormGrp₁.{u}) : pseudo_normed_group M := M.str\n\nlemma exhaustive (M : PseuNormGrp₁) (x : M) :\n ∃ c, x ∈ pseudo_normed_group.filtration M c := M.exhaustive' x\n\ninstance : category PseuNormGrp₁.{u} :=\n{ hom := λ A B, strict_pseudo_normed_group_hom A B,\n id := λ A, strict_pseudo_normed_group_hom.id A,\n comp := λ A B C f g, f.comp g }\n\n@[simp]\nlemma id_apply (M : PseuNormGrp₁) (x : M) : (𝟙 M : M ⟶ M) x = x := rfl\n\n@[simp]\nlemma comp_apply {A B C : PseuNormGrp₁} (f : A ⟶ B) (g : B ⟶ C) (a : A) :\n (f ≫ g) a = g (f a) := rfl\n\ndef to_Ab : PseuNormGrp₁.{u} ⥤ Ab.{u} :=\n{ obj := λ M, AddCommGroup.of M,\n map := λ M N f, f.to_add_monoid_hom }\n\nvariable {K : J ⥤ PseuNormGrp₁.{u}}\nvariable (C : limits.limit_cone (K ⋙ to_Ab))\n\ndef bounded_elements : add_subgroup C.cone.X :=\n{ carrier := { x | ∃ c, ∀ j, C.cone.π.app j x ∈ pseudo_normed_group.filtration (K.obj j) c },\n zero_mem' := ⟨0, λ j, by { simp, apply pseudo_normed_group.zero_mem_filtration } ⟩,\n add_mem' := λ a b ha hb, begin\n obtain ⟨c,hc⟩ := ha,\n obtain ⟨d,hd⟩ := hb,\n use c + d,\n intros j,\n simp,\n apply pseudo_normed_group.add_mem_filtration,\n apply hc,\n apply hd,\n end,\n neg_mem' := λ a ha, begin\n obtain ⟨c,hc⟩ := ha,\n use c,\n intros j,\n simp,\n apply pseudo_normed_group.neg_mem_filtration,\n apply hc,\n end }\n\ndef bounded_elements.filt (c : nnreal) : set C.cone.X :=\n{ x | ∀ j, C.cone.π.app j x ∈ pseudo_normed_group.filtration (K.obj j) c }\n\ndef bounded_elements.filt_incl (c : nnreal) :\n bounded_elements.filt C c → bounded_elements C :=\nλ x, ⟨x, c, x.2⟩\n\ndef bounded_elements.filtration (c : nnreal) : set (bounded_elements C) :=\nset.range (bounded_elements.filt_incl _ c)\n\ndef bounded_cone_point : PseuNormGrp₁ :=\n{ carrier := bounded_elements C,\n str :=\n { filtration := bounded_elements.filtration _,\n filtration_mono := begin\n intros c₁ c₂ h x hx,\n obtain ⟨t,rfl⟩ := hx, refine ⟨⟨t,_⟩,rfl⟩, intros i,\n apply pseudo_normed_group.filtration_mono h, apply t.2,\n end,\n zero_mem_filtration := begin\n intros c, refine ⟨⟨0,λ i, _⟩,rfl⟩, simp,\n apply pseudo_normed_group.zero_mem_filtration\n end,\n neg_mem_filtration := begin\n intros c x hx,\n obtain ⟨t,rfl⟩ := hx, refine ⟨⟨-t, λ i, _⟩, rfl⟩, simp,\n apply pseudo_normed_group.neg_mem_filtration, apply t.2\n end,\n add_mem_filtration := begin\n intros c₁ c₂ x₁ x₂ h₁ h₂,\n obtain ⟨t₁,rfl⟩ := h₁, obtain ⟨t₂,rfl⟩ := h₂,\n refine ⟨⟨t₁ + t₂, λ i, _⟩, rfl⟩, simp,\n apply pseudo_normed_group.add_mem_filtration, apply t₁.2, apply t₂.2,\n end },\n exhaustive' := begin\n intros m,\n obtain ⟨c,hc⟩ := m.2,\n refine ⟨c,⟨m.1, hc⟩, by { ext, refl }⟩,\n end }\n\ndef bounded_cone : cone K :=\n{ X := bounded_cone_point C,\n π :=\n { app := λ j,\n { to_fun := λ x, C.cone.π.app _ x.1,\n map_zero' := by simp,\n map_add' := λ x y, by simp,\n strict' := begin\n rintros c x ⟨x,rfl⟩,\n apply x.2,\n end },\n naturality' := begin\n intros i j f,\n ext,\n dsimp,\n rw ← C.cone.w f,\n refl,\n end } }\n\ndef bounded_cone_lift (S : cone K) : S.X ⟶ bounded_cone_point C :=\n{ to_fun := λ x, ⟨C.2.lift (to_Ab.map_cone S) x, begin\n obtain ⟨c,hc⟩ := S.X.exhaustive x,\n use c,\n intros j,\n rw [← Ab.comp_apply, C.2.fac],\n apply (S.π.app j).strict,\n exact hc,\n end⟩,\n map_zero' := by { ext, simp },\n map_add' := λ x y, by { ext, simp },\n strict' := begin\n intros c x hx,\n refine ⟨⟨_, λ j, _⟩,rfl⟩,\n erw [← Ab.comp_apply, C.2.fac],\n apply (S.π.app j).strict,\n exact hx,\n end }\n\ndef bounded_cone_is_limit : is_limit (bounded_cone C) :=\n{ lift := λ S, bounded_cone_lift C S,\n fac' := begin\n intros S j,\n ext,\n dsimp [bounded_cone_lift, bounded_cone],\n rw [← Ab.comp_apply, C.2.fac],\n refl,\n end,\n uniq' := begin\n intros S m hm,\n ext,\n dsimp [bounded_cone_lift, bounded_cone],\n apply Ab.is_limit_ext,\n intros j,\n rw [← Ab.comp_apply, C.2.fac],\n dsimp,\n rw ← hm,\n refl,\n end }\n\ninstance : has_limits PseuNormGrp₁ :=\nbegin\n constructor, introsI J hJ, constructor, intros K,\n exact has_limit.mk ⟨_, bounded_cone_is_limit ⟨_,limit.is_limit _⟩⟩,\nend\n\nopen pseudo_normed_group\n\nlemma mem_filtration_iff_of_is_limit (C : cone K) (hC : is_limit C)\n (x : C.X) (c : nnreal) :\n x ∈ pseudo_normed_group.filtration C.X c ↔\n (∀ j : J, C.π.app j x ∈ pseudo_normed_group.filtration (K.obj j) c) :=\nbegin\n split,\n { intros h j,\n exact (C.π.app j).strict h },\n { intros h,\n let E := bounded_cone ⟨_, Ab.explicit_limit_cone_is_limit.{u u} _⟩,\n let e : C ≅ E := hC.unique_up_to_iso (bounded_cone_is_limit _),\n let eX : C.X ≅ E.X := (cones.forget _).map_iso e,\n let w := eX.hom x,\n have hw : ∀ j, E.π.app j w ∈ filtration (K.obj j) c,\n { intros j,\n dsimp only [w],\n change (eX.hom ≫ E.π.app _) _ ∈ _,\n dsimp only [eX, functor.map_iso, cones.forget],\n convert h j,\n simp },\n suffices : w ∈ filtration E.X c,\n { convert eX.inv.strict this,\n change _ = (eX.hom ≫ eX.inv) x,\n rw iso.hom_inv_id,\n refl },\n refine ⟨⟨_,hw⟩,rfl⟩ }\nend\n\n@[simps]\ndef _root_.strict_pseudo_normed_group_hom.level {M N : Type*}\n [pseudo_normed_group M] [pseudo_normed_group N]\n (f : strict_pseudo_normed_group_hom M N) (c) :\n filtration M c → filtration N c :=\nλ x, ⟨f x, f.strict x.2⟩\n\n@[simp]\nlemma _root_.strict_pseudo_normed_group_hom.level_id\n (M : Type*) [pseudo_normed_group M] (c) :\n (strict_pseudo_normed_group_hom.id M).level c = id := by { ext, refl }\n\n@[simp]\nlemma _root_.strict_pseudo_normed_group_hom.level_comp {M N L : Type*}\n [pseudo_normed_group M] [pseudo_normed_group N] [pseudo_normed_group L]\n (f : strict_pseudo_normed_group_hom M N) (g : strict_pseudo_normed_group_hom N L) (c) :\n (f.comp g).level c = g.level c ∘ f.level c := by { ext, refl }\n\n@[simps]\ndef level : nnreal ⥤ PseuNormGrp₁.{u} ⥤ Type u :=\n{ obj := λ c,\n { obj := λ M, filtration M c,\n map := λ X Y f, f.level _,\n map_id' := λ M, strict_pseudo_normed_group_hom.level_id M _,\n map_comp' := λ M N L f g, f.level_comp g c },\n map := λ c₁ c₂ h,\n { app := λ M, pseudo_normed_group.cast_le' h.le } } .\n\nlemma level_map {X Y : PseuNormGrp₁} (f : X ⟶ Y) (c) : (level.obj c).map f = f.level _ := rfl\n\nlemma level_map' {X Y : PseuNormGrp₁} (f : X ⟶ Y) (c) : (level.obj c).map f =\n pseudo_normed_group.level f f.strict c := rfl\n\ndef level_cone_iso_hom (c) (t : (level.obj c).obj (bounded_cone_point C)) :\n (K ⋙ level.obj c).sections :=\n{ val := λ j,\n { val := C.cone.π.app j t.1.1,\n property := begin\n obtain ⟨w,hw⟩ := t.2,\n apply_fun (λ e, e.val) at hw,\n rw ← hw,\n apply w.2\n end },\n property := begin\n intros i j f,\n ext,\n dsimp,\n rw ← C.cone.w f,\n refl,\n end }\n\ndef level_cone_iso_inv (c) (t : (K ⋙ level.obj c).sections) :\n (level.obj c).obj (bounded_cone_point C) :=\n{ val :=\n { val := C.2.lift (Ab.explicit_limit_cone.{u u} _) ⟨λ j, (t.1 j).1, begin\n intros i j f,\n dsimp,\n change _ = (t.val _).val,\n rw ← t.2 f,\n refl,\n end⟩,\n property := begin\n use c,\n intros j,\n rw [← Ab.comp_apply, C.2.fac],\n dsimp [Ab.explicit_limit_cone],\n apply (t.1 j).2,\n end },\n property := begin\n refine ⟨⟨_,_⟩,rfl⟩,\n intros j,\n dsimp,\n rw [← Ab.comp_apply, C.2.fac],\n dsimp [Ab.explicit_limit_cone],\n apply (t.1 j).2,\n end } .\n\ndef level_cone_iso (c) :\n (level.obj c).map_cone (bounded_cone C) ≅ types.limit_cone.{u u} _ :=\ncones.ext\n{ hom := level_cone_iso_hom _ _,\n inv := level_cone_iso_inv _ _,\n hom_inv_id' := begin\n ext,\n dsimp [level_cone_iso_inv, level_cone_iso_hom],\n apply Ab.is_limit_ext,\n intros j,\n rw [← Ab.comp_apply, C.2.fac],\n refl,\n end,\n inv_hom_id' := begin\n ext,\n dsimp [level_cone_iso_inv, level_cone_iso_hom],\n rw [← Ab.comp_apply, C.2.fac],\n refl,\n end }\nbegin\n intros j,\n ext,\n refl,\nend\n\ninstance preserves_limits_level_obj (c) : preserves_limits (level.obj c) :=\nbegin\n constructor, introsI J hJ, constructor, intros K,\n apply preserves_limit_of_preserves_limit_cone\n (bounded_cone_is_limit ⟨_, Ab.explicit_limit_cone_is_limit _⟩),\n apply is_limit.of_iso_limit (types.limit_cone_is_limit _) (level_cone_iso _ _).symm,\nend\n\ndef neg_nat_trans (c) : level.obj.{u} c ⟶ level.obj.{u} c :=\n{ app := λ X, pseudo_normed_group.neg',\n naturality' := begin\n intros A B f,\n ext,\n dsimp [level, neg'],\n simp,\n end }\n\nend PseuNormGrp₁\n\nnamespace CompHausFiltPseuNormGrp₁\n\n@[simp]\nlemma id_apply {A : CompHausFiltPseuNormGrp₁} (a : A) : (𝟙 A : A ⟶ A) a = a := rfl\n\n@[simp]\nlemma comp_apply {A B C : CompHausFiltPseuNormGrp₁} (f : A ⟶ B) (g : B ⟶ C) (a : A) :\n (f ≫ g) a = g (f a) := rfl\n\ndef to_PNG₁ :\n CompHausFiltPseuNormGrp₁.{u} ⥤ PseuNormGrp₁.{u} :=\n{ obj := λ M,\n { carrier := M,\n exhaustive' := M.exhaustive },\n map := λ X Y f, { strict' := λ c x h, f.strict h .. f.to_add_monoid_hom } }\n\ninstance : faithful to_PNG₁.{u} := faithful.mk $\nbegin\n intros X Y f g h,\n ext,\n apply_fun (λ e, e x) at h,\n exact h\nend\n\nvariable {K : J ⥤ CompHausFiltPseuNormGrp₁.{u}}\nvariable (C : limits.limit_cone ((K ⋙ to_PNG₁) ⋙ PseuNormGrp₁.to_Ab))\n\ndef filtration_equiv (c : nnreal) :\n pseudo_normed_group.filtration (PseuNormGrp₁.bounded_cone_point C) c\n ≃ (CompHaus.limit_cone.{u u} (K ⋙ level.obj c)).X :=\n((cones.forget _).map_iso (PseuNormGrp₁.level_cone_iso C c)).to_equiv\n\ninstance (c) :\n topological_space (pseudo_normed_group.filtration (PseuNormGrp₁.bounded_cone_point C) c) :=\ntopological_space.induced (filtration_equiv C c) infer_instance\n\ndef filtration_homeo (c : nnreal) :\n pseudo_normed_group.filtration (PseuNormGrp₁.bounded_cone_point C) c\n ≃ₜ (CompHaus.limit_cone.{u u} (K ⋙ level.obj c)).X :=\nhomeomorph.homeomorph_of_continuous_open (filtration_equiv _ _) continuous_induced_dom\nbegin\n intros U hU,\n have : inducing (filtration_equiv C c) := ⟨rfl⟩,\n rw this.is_open_iff at hU,\n obtain ⟨U,hU,rfl⟩ := hU,\n simpa,\nend\n\ninstance (c) : t2_space\n (pseudo_normed_group.filtration (PseuNormGrp₁.bounded_cone_point C) c) :=\n(filtration_homeo C c).symm.t2_space\n\ninstance (c) : compact_space\n (pseudo_normed_group.filtration (PseuNormGrp₁.bounded_cone_point C) c) :=\n(filtration_homeo C c).symm.compact_space\n\n/-\ninstance (c) : totally_disconnected_space\n (pseudo_normed_group.filtration (PseuNormGrp₁.bounded_cone_point C) c) :=\n(filtration_homeo C c).symm.totally_disconnected_space\n-/\n\ndef level_π (j c) : pseudo_normed_group.filtration (PseuNormGrp₁.bounded_cone_point C) c →\n pseudo_normed_group.filtration (K.obj j) c :=\n(PseuNormGrp₁.level.obj c).map ((PseuNormGrp₁.bounded_cone C).π.app j)\n\nlemma level_π_continuous (j c) : continuous (level_π C j c) :=\nbegin\n have : level_π C j c ∘ (filtration_homeo C c).symm =\n (CompHaus.limit_cone.{u u} _).π.app j,\n { ext,\n change (C.is_limit.lift _ ≫ C.cone.π.app j) _ = _,\n rw C.is_limit.fac,\n refl },\n suffices : continuous (level_π C j c ∘ (filtration_homeo C c).symm),\n by simpa using this,\n rw this,\n continuity,\nend\n\nlemma bounded_cone_point_continuous_add'_aux {J : Type u}\n [small_category J]\n {K : J ⥤ CompHausFiltPseuNormGrp₁}\n (C : category_theory.limits.limit_cone\n ((K ⋙ to_PNG₁) ⋙ PseuNormGrp₁.to_Ab)) :\n ∀ (c₁ c₂ : nnreal), continuous\n (pseudo_normed_group.add' :\n (pseudo_normed_group.filtration (PseuNormGrp₁.bounded_cone_point C) c₁) ×\n (pseudo_normed_group.filtration (PseuNormGrp₁.bounded_cone_point C) c₂) →\n (pseudo_normed_group.filtration (PseuNormGrp₁.bounded_cone_point C) (c₁ + c₂))) :=\nbegin\n intros c₁ c₂,\n let g : (pseudo_normed_group.filtration (PseuNormGrp₁.bounded_cone_point C) c₁) ×\n (pseudo_normed_group.filtration (PseuNormGrp₁.bounded_cone_point C) c₂) →\n (pseudo_normed_group.filtration (PseuNormGrp₁.bounded_cone_point C) (c₁ + c₂)) :=\n pseudo_normed_group.add',\n change continuous g,\n suffices : continuous ((filtration_homeo C _) ∘ g), by simpa using this,\n apply continuous.subtype_mk,\n apply continuous_pi,\n intros j,\n let e := pseudo_normed_group.add' ∘ (prod.map (level_π C j c₁) (level_π C j c₂)),\n have he : continuous e,\n { apply continuous.comp,\n apply comphaus_filtered_pseudo_normed_group.continuous_add',\n apply continuous.prod_map,\n apply level_π_continuous,\n apply level_π_continuous },\n convert he,\n ext,\n dsimp,\n simpa,\nend\n\nlemma bounded_cone_point_continuous_neg'_aux {J : Type u}\n [small_category J]\n {K : J ⥤ CompHausFiltPseuNormGrp₁}\n (C : category_theory.limits.limit_cone\n ((K ⋙ to_PNG₁) ⋙ PseuNormGrp₁.to_Ab)) :\n ∀ (c : nnreal), continuous\n (pseudo_normed_group.neg' :\n (pseudo_normed_group.filtration (PseuNormGrp₁.bounded_cone_point C) c) →\n (pseudo_normed_group.filtration (PseuNormGrp₁.bounded_cone_point C) c)) :=\nbegin\n intros c,\n let g : (pseudo_normed_group.filtration (PseuNormGrp₁.bounded_cone_point C) c) →\n (pseudo_normed_group.filtration (PseuNormGrp₁.bounded_cone_point C) c) :=\n pseudo_normed_group.neg',\n change continuous g,\n suffices : continuous ((filtration_homeo C c) ∘ g),\n by simpa using this,\n apply continuous.subtype_mk,\n apply continuous_pi,\n dsimp [g],\n intros j,\n let e := pseudo_normed_group.neg' ∘ level_π C j c,\n have he : continuous e,\n { apply continuous.comp,\n apply comphaus_filtered_pseudo_normed_group.continuous_neg',\n apply level_π_continuous },\n convert he,\n ext,\n dsimp,\n simpa,\nend\n\nlemma bounded_cone_point_continuous_cast_le_aux {J : Type u}\n [small_category J]\n {K : J ⥤ CompHausFiltPseuNormGrp₁}\n (C : category_theory.limits.limit_cone\n ((K ⋙ to_PNG₁) ⋙ PseuNormGrp₁.to_Ab)) :\n ∀ (c₁ c₂ : nnreal) (h : c₁ ≤ c₂), continuous\n (pseudo_normed_group.cast_le' h :\n (pseudo_normed_group.filtration (PseuNormGrp₁.bounded_cone_point C) c₁) →\n (pseudo_normed_group.filtration (PseuNormGrp₁.bounded_cone_point C) c₂)) :=\nbegin\n intros c₁ c₂ h,\n let g : (pseudo_normed_group.filtration (PseuNormGrp₁.bounded_cone_point C) c₁) →\n (pseudo_normed_group.filtration (PseuNormGrp₁.bounded_cone_point C) c₂) :=\n pseudo_normed_group.cast_le' h,\n change continuous g,\n suffices : continuous ((filtration_homeo C _) ∘ g), by simpa using this,\n apply continuous.subtype_mk,\n apply continuous_pi,\n intros j,\n dsimp [g],\n let e := pseudo_normed_group.cast_le' h ∘ level_π C j c₁,\n have he : continuous e,\n { apply continuous.comp,\n haveI : fact (c₁ ≤ c₂) := ⟨h⟩,\n apply comphaus_filtered_pseudo_normed_group.continuous_cast_le,\n apply level_π_continuous },\n exact he,\nend\n\ndef bounded_cone_point : CompHausFiltPseuNormGrp₁ :=\n{ M := PseuNormGrp₁.bounded_cone_point C,\n str :=\n { continuous_add' := bounded_cone_point_continuous_add'_aux _,\n continuous_neg' := bounded_cone_point_continuous_neg'_aux _,\n continuous_cast_le := λ _ _ h, bounded_cone_point_continuous_cast_le_aux _ _ _ h.out,\n ..(infer_instance : pseudo_normed_group (PseuNormGrp₁.bounded_cone_point C)) },\n exhaustive' := (PseuNormGrp₁.bounded_cone_point C).exhaustive }\n\ndef bounded_cone : cone K :=\n{ X := bounded_cone_point C,\n π :=\n { app := λ j,\n { continuous' := λ c, level_π_continuous _ _ _,\n ..((PseuNormGrp₁.bounded_cone C).π.app j) },\n naturality' := begin\n intros i j f,\n ext,\n dsimp,\n rw ← (PseuNormGrp₁.bounded_cone C).w f,\n refl,\n end } }\n\ndef bounded_cone_is_limit : is_limit (bounded_cone C) :=\n{ lift := λ S,\n { continuous' := begin\n intros c,\n let t : pseudo_normed_group.filtration S.X c →\n pseudo_normed_group.filtration (bounded_cone C).X c :=\n (((PseuNormGrp₁.bounded_cone_is_limit C).lift (to_PNG₁.map_cone S)).level _),\n change continuous t,\n suffices : continuous ((filtration_homeo C c) ∘ t), by simpa using this,\n have : ⇑(filtration_homeo C c) ∘ t =\n (CompHaus.limit_cone_is_limit.{u u} _).lift ((level.obj c).map_cone S),\n { ext,\n change (C.is_limit.lift _ ≫ C.cone.π.app _) _ = _,\n rw C.is_limit.fac, refl },\n rw this,\n continuity,\n end,\n ..((PseuNormGrp₁.bounded_cone_is_limit C).lift (to_PNG₁.map_cone S)) },\n fac' := begin\n intros S j,\n ext,\n dsimp [bounded_cone],\n change ((PseuNormGrp₁.bounded_cone_is_limit C).lift (to_PNG₁.map_cone S) ≫\n (PseuNormGrp₁.bounded_cone C).π.app j) _ = _,\n rw (PseuNormGrp₁.bounded_cone_is_limit C).fac,\n refl,\n end,\n uniq' := begin\n intros S m hm,\n ext,\n dsimp,\n have : to_PNG₁.map m =\n (PseuNormGrp₁.bounded_cone_is_limit C).lift (to_PNG₁.map_cone S),\n { apply (PseuNormGrp₁.bounded_cone_is_limit C).uniq (to_PNG₁.map_cone S),\n intros j,\n ext t,\n specialize hm j,\n apply_fun (λ e, e t) at hm,\n exact hm },\n rw ← this,\n refl,\n end }\n\ninstance : preserves_limit K to_PNG₁ :=\n\nbegin\n apply preserves_limit_of_preserves_limit_cone,\n rotate 2,\n exact bounded_cone ⟨_,Ab.explicit_limit_cone_is_limit.{u u} _⟩,\n exact bounded_cone_is_limit _,\n exact PseuNormGrp₁.bounded_cone_is_limit _,\nend\n\n/-\nRemark: This functor even creates limits, as can be shown using the fact that the forgetful\nfunctor from `Profinite` to `Type*` creates limits.\nI don't think we actually need that strong statement, so we only prove the following.\n-/\ninstance : preserves_limits to_PNG₁ :=\nbegin\n constructor, introsI J hJ, constructor\nend\n\nend CompHausFiltPseuNormGrp₁\n\nnamespace ProFiltPseuNormGrp₁\n\n@[simp]\nlemma id_apply {A : ProFiltPseuNormGrp₁} (a : A) : (𝟙 A : A ⟶ A) a = a := rfl\n\n@[simp]\nlemma comp_apply {A B C : ProFiltPseuNormGrp₁} (f : A ⟶ B) (g : B ⟶ C) (a : A) :\n (f ≫ g) a = g (f a) := rfl\n\ndef to_PNG₁ :\n ProFiltPseuNormGrp₁.{u} ⥤ PseuNormGrp₁.{u} :=\n{ obj := λ M,\n { carrier := M,\n exhaustive' := M.exhaustive },\n map := λ X Y f, { strict' := λ c x h, f.strict h .. f.to_add_monoid_hom } }\n\ninstance : faithful to_PNG₁.{u} := faithful.mk $\nbegin\n intros X Y f g h,\n ext,\n apply_fun (λ e, e x) at h,\n exact h\nend\n\nvariable {K : J ⥤ ProFiltPseuNormGrp₁.{u}}\nvariable (C : limits.limit_cone ((K ⋙ to_PNG₁) ⋙ PseuNormGrp₁.to_Ab))\n\ndef filtration_equiv (c : nnreal) :\n pseudo_normed_group.filtration (PseuNormGrp₁.bounded_cone_point C) c\n ≃ (Profinite.limit_cone (K ⋙ level.obj c)).X :=\n((cones.forget _).map_iso (PseuNormGrp₁.level_cone_iso C c)).to_equiv\n\ninstance (c) :\n topological_space (pseudo_normed_group.filtration (PseuNormGrp₁.bounded_cone_point C) c) :=\ntopological_space.induced (filtration_equiv C c) infer_instance\n\ndef filtration_homeo (c : nnreal) :\n pseudo_normed_group.filtration (PseuNormGrp₁.bounded_cone_point C) c\n ≃ₜ (Profinite.limit_cone (K ⋙ level.obj c)).X :=\nhomeomorph.homeomorph_of_continuous_open (filtration_equiv _ _) continuous_induced_dom\nbegin\n intros U hU,\n have : inducing (filtration_equiv C c) := ⟨rfl⟩,\n rw this.is_open_iff at hU,\n obtain ⟨U,hU,rfl⟩ := hU,\n simpa,\nend\n\ninstance (c) : t2_space\n (pseudo_normed_group.filtration (PseuNormGrp₁.bounded_cone_point C) c) :=\n(filtration_homeo C c).symm.t2_space\n\ninstance (c) : compact_space\n (pseudo_normed_group.filtration (PseuNormGrp₁.bounded_cone_point C) c) :=\n(filtration_homeo C c).symm.compact_space\n\ninstance (c) : totally_disconnected_space\n (pseudo_normed_group.filtration (PseuNormGrp₁.bounded_cone_point C) c) :=\n(filtration_homeo C c).symm.totally_disconnected_space\n\ndef level_π (j c) : pseudo_normed_group.filtration (PseuNormGrp₁.bounded_cone_point C) c →\n pseudo_normed_group.filtration (K.obj j) c :=\n(PseuNormGrp₁.level.obj c).map ((PseuNormGrp₁.bounded_cone C).π.app j)\n\nlemma level_π_continuous (j c) : continuous (level_π C j c) :=\nbegin\n have : level_π C j c ∘ (filtration_homeo C c).symm =\n (Profinite.limit_cone _).π.app j,\n { ext,\n change (C.is_limit.lift _ ≫ C.cone.π.app j) _ = _,\n rw C.is_limit.fac,\n refl },\n suffices : continuous (level_π C j c ∘ (filtration_homeo C c).symm),\n by simpa using this,\n rw this,\n continuity,\nend\n\nlemma bounded_cone_point_continuous_add'_aux {J : Type u}\n [small_category J]\n {K : J ⥤ ProFiltPseuNormGrp₁}\n (C : category_theory.limits.limit_cone\n ((K ⋙ to_PNG₁) ⋙ PseuNormGrp₁.to_Ab)) :\n ∀ (c₁ c₂ : nnreal), continuous\n (pseudo_normed_group.add' :\n (pseudo_normed_group.filtration (PseuNormGrp₁.bounded_cone_point C) c₁) ×\n (pseudo_normed_group.filtration (PseuNormGrp₁.bounded_cone_point C) c₂) →\n (pseudo_normed_group.filtration (PseuNormGrp₁.bounded_cone_point C) (c₁ + c₂))) :=\nbegin\n intros c₁ c₂,\n let g : (pseudo_normed_group.filtration (PseuNormGrp₁.bounded_cone_point C) c₁) ×\n (pseudo_normed_group.filtration (PseuNormGrp₁.bounded_cone_point C) c₂) →\n (pseudo_normed_group.filtration (PseuNormGrp₁.bounded_cone_point C) (c₁ + c₂)) :=\n pseudo_normed_group.add',\n change continuous g,\n suffices : continuous ((filtration_homeo C _) ∘ g), by simpa using this,\n apply continuous.subtype_mk,\n apply continuous_pi,\n intros j,\n let e := pseudo_normed_group.add' ∘ (prod.map (level_π C j c₁) (level_π C j c₂)),\n have he : continuous e,\n { apply continuous.comp,\n apply comphaus_filtered_pseudo_normed_group.continuous_add',\n apply continuous.prod_map,\n apply level_π_continuous,\n apply level_π_continuous },\n convert he,\n ext,\n dsimp,\n simpa,\nend\n\nlemma bounded_cone_point_continuous_neg'_aux {J : Type u}\n [small_category J]\n {K : J ⥤ ProFiltPseuNormGrp₁}\n (C : category_theory.limits.limit_cone\n ((K ⋙ to_PNG₁) ⋙ PseuNormGrp₁.to_Ab)) :\n ∀ (c : nnreal), continuous\n (pseudo_normed_group.neg' :\n (pseudo_normed_group.filtration (PseuNormGrp₁.bounded_cone_point C) c) →\n (pseudo_normed_group.filtration (PseuNormGrp₁.bounded_cone_point C) c)) :=\nbegin\n intros c,\n let g : (pseudo_normed_group.filtration (PseuNormGrp₁.bounded_cone_point C) c) →\n (pseudo_normed_group.filtration (PseuNormGrp₁.bounded_cone_point C) c) :=\n pseudo_normed_group.neg',\n change continuous g,\n suffices : continuous ((filtration_homeo C c) ∘ g),\n by simpa using this,\n apply continuous.subtype_mk,\n apply continuous_pi,\n dsimp [g],\n intros j,\n let e := pseudo_normed_group.neg' ∘ level_π C j c,\n have he : continuous e,\n { apply continuous.comp,\n apply comphaus_filtered_pseudo_normed_group.continuous_neg',\n apply level_π_continuous },\n convert he,\n ext,\n dsimp,\n simpa,\nend\n\nlemma bounded_cone_point_continuous_cast_le_aux {J : Type u}\n [small_category J]\n {K : J ⥤ ProFiltPseuNormGrp₁}\n (C : category_theory.limits.limit_cone\n ((K ⋙ to_PNG₁) ⋙ PseuNormGrp₁.to_Ab)) :\n ∀ (c₁ c₂ : nnreal) (h : c₁ ≤ c₂), continuous\n (pseudo_normed_group.cast_le' h :\n (pseudo_normed_group.filtration (PseuNormGrp₁.bounded_cone_point C) c₁) →\n (pseudo_normed_group.filtration (PseuNormGrp₁.bounded_cone_point C) c₂)) :=\nbegin\n intros c₁ c₂ h,\n let g : (pseudo_normed_group.filtration (PseuNormGrp₁.bounded_cone_point C) c₁) →\n (pseudo_normed_group.filtration (PseuNormGrp₁.bounded_cone_point C) c₂) :=\n pseudo_normed_group.cast_le' h,\n change continuous g,\n suffices : continuous ((filtration_homeo C _) ∘ g), by simpa using this,\n apply continuous.subtype_mk,\n apply continuous_pi,\n intros j,\n dsimp [g],\n let e := pseudo_normed_group.cast_le' h ∘ level_π C j c₁,\n have he : continuous e,\n { apply continuous.comp,\n haveI : fact (c₁ ≤ c₂) := ⟨h⟩,\n apply comphaus_filtered_pseudo_normed_group.continuous_cast_le,\n apply level_π_continuous },\n exact he,\nend\n\ndef bounded_cone_point : ProFiltPseuNormGrp₁ :=\n{ M := PseuNormGrp₁.bounded_cone_point C,\n str :=\n { continuous_add' := bounded_cone_point_continuous_add'_aux _,\n continuous_neg' := bounded_cone_point_continuous_neg'_aux _,\n continuous_cast_le := λ _ _ h, bounded_cone_point_continuous_cast_le_aux _ _ _ h.out,\n ..(infer_instance : pseudo_normed_group (PseuNormGrp₁.bounded_cone_point C)) },\n exhaustive' := (PseuNormGrp₁.bounded_cone_point C).exhaustive }\n\ndef bounded_cone : cone K :=\n{ X := bounded_cone_point C,\n π :=\n { app := λ j,\n { continuous' := λ c, level_π_continuous _ _ _,\n ..((PseuNormGrp₁.bounded_cone C).π.app j) },\n naturality' := begin\n intros i j f,\n ext,\n dsimp,\n rw ← (PseuNormGrp₁.bounded_cone C).w f,\n refl,\n end } }\n\ndef bounded_cone_is_limit : is_limit (bounded_cone C) :=\n{ lift := λ S,\n { continuous' := begin\n intros c,\n let t : pseudo_normed_group.filtration S.X c →\n pseudo_normed_group.filtration (bounded_cone C).X c :=\n (((PseuNormGrp₁.bounded_cone_is_limit C).lift (to_PNG₁.map_cone S)).level _),\n change continuous t,\n suffices : continuous ((filtration_homeo C c) ∘ t), by simpa using this,\n have : ⇑(filtration_homeo C c) ∘ t =\n (Profinite.limit_cone_is_limit _).lift ((level.obj c).map_cone S),\n { ext,\n change (C.is_limit.lift _ ≫ C.cone.π.app _) _ = _,\n rw C.is_limit.fac, refl },\n rw this,\n continuity,\n end,\n ..((PseuNormGrp₁.bounded_cone_is_limit C).lift (to_PNG₁.map_cone S)) },\n fac' := begin\n intros S j,\n ext,\n dsimp [bounded_cone],\n change ((PseuNormGrp₁.bounded_cone_is_limit C).lift (to_PNG₁.map_cone S) ≫\n (PseuNormGrp₁.bounded_cone C).π.app j) _ = _,\n rw (PseuNormGrp₁.bounded_cone_is_limit C).fac,\n refl,\n end,\n uniq' := begin\n intros S m hm,\n ext,\n dsimp,\n have : to_PNG₁.map m =\n (PseuNormGrp₁.bounded_cone_is_limit C).lift (to_PNG₁.map_cone S),\n { apply (PseuNormGrp₁.bounded_cone_is_limit C).uniq (to_PNG₁.map_cone S),\n intros j,\n ext t,\n specialize hm j,\n apply_fun (λ e, e t) at hm,\n exact hm },\n rw ← this,\n refl,\n end }\n\ninstance : preserves_limit K to_PNG₁ :=\n\nbegin\n apply preserves_limit_of_preserves_limit_cone,\n rotate 2,\n exact bounded_cone ⟨_,Ab.explicit_limit_cone_is_limit.{u u} _⟩,\n exact bounded_cone_is_limit _,\n exact PseuNormGrp₁.bounded_cone_is_limit _,\nend\n\n/-\nRemark: This functor even creates limits, as can be shown using the fact that the forgetful\nfunctor from `Profinite` to `Type*` creates limits.\nI don't think we actually need that strong statement, so we only prove the following.\n-/\ninstance : preserves_limits to_PNG₁ :=\nbegin\n constructor, introsI J hJ, constructor\nend\n\nend ProFiltPseuNormGrp₁\n", "meta": {"author": "leanprover-community", "repo": "lean-liquid", "sha": "92f188bd17f34dbfefc92a83069577f708851aec", "save_path": "github-repos/lean/leanprover-community-lean-liquid", "path": "github-repos/lean/leanprover-community-lean-liquid/lean-liquid-92f188bd17f34dbfefc92a83069577f708851aec/src/pseudo_normed_group/bounded_limits.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.5, "lm_q2_score": 0.025565213969671128, "lm_q1q2_score": 0.012782606984835564}} {"text": "/-\nCopyright (c) 2016 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Leonardo de Moura\n-/\nprelude\nimport init.meta.interactive_base init.meta.tactic init.meta.set_get_option_tactics\n\nstructure cc_config :=\n/- If tt, congruence closure will treat implicit instance arguments as constants. -/\n(ignore_instances : bool := tt)\n/- If tt, congruence closure modulo AC. -/\n(ac : bool := tt)\n/- If ho_fns is (some fns), then full (and more expensive) support for higher-order functions is\n *only* considered for the functions in fns and local functions. The performance overhead is described in the paper\n \"Congruence Closure in Intensional Type Theory\". If ho_fns is none, then full support is provided\n for *all* constants. -/\n(ho_fns : option (list name) := none)\n/- If true, then use excluded middle -/\n(em : bool := tt)\n\n/-- Congruence closure state.\nThis may be considered to be a set of expressions and an equivalence class over this set.\nThe equivalence class is generated by the equational rules that are added to the cc_state and congruence,\nthat is, if `a = b` then `f(a) = f(b)` and so on.\n -/\nmeta constant cc_state : Type\nmeta constant cc_state.mk_core : cc_config → cc_state\n/-- Create a congruence closure state object using the hypotheses in the current goal. -/\nmeta constant cc_state.mk_using_hs_core : cc_config → tactic cc_state\n/-- Get the next element in the equivalence class.\nNote that if the given expr e is not in the graph then it will just return e. -/\nmeta constant cc_state.next : cc_state → expr → expr\n/-- Returns the root expression for each equivalence class in the graph.\nIf the bool argument is set to true then it only returns roots of non-singleton classes. -/\nmeta constant cc_state.roots_core : cc_state → bool → list expr\n/-- Get the root representative of the given expression. -/\nmeta constant cc_state.root : cc_state → expr → expr\n/-- \"Modification Time\". The field m_mt is used to implement the mod-time optimization introduce by the Simplify theorem prover.\nThe basic idea is to introduce a counter gmt that records the number of heuristic instantiation that have\noccurred in the current branch. It is incremented after each round of heuristic instantiation.\nThe field m_mt records the last time any proper descendant of of thie entry was involved in a merge. -/\nmeta constant cc_state.mt : cc_state → expr → nat\n/-- \"Global Modification Time\". gmt is a number stored on the cc_state,\nit is compared with the modification time of a cc_entry in e-matching. See `cc_state.mt`. -/\nmeta constant cc_state.gmt : cc_state → nat\n/-- Increment the Global Modification time. -/\nmeta constant cc_state.inc_gmt : cc_state → cc_state\n/-- Check if `e` is the root of the congruence class. -/\nmeta constant cc_state.is_cg_root : cc_state → expr → bool\n/-- Pretty print the entry associated with the given expression. -/\nmeta constant cc_state.pp_eqc : cc_state → expr → tactic format\n/-- Pretty print the entire cc graph.\nIf the bool argument is set to true then singleton equivalence classes will be omitted. -/\nmeta constant cc_state.pp_core : cc_state → bool → tactic format\n/-- Add the given expression to the graph. -/\nmeta constant cc_state.internalize : cc_state → expr → tactic cc_state\n/-- Add the given proof term as a new rule.\nThe proof term p must be an `eq _ _`, `heq _ _`, `iff _ _`, or a negation of these. -/\nmeta constant cc_state.add : cc_state → expr → tactic cc_state\n/-- Check whether two expressions are in the same equivalence class. -/\nmeta constant cc_state.is_eqv : cc_state → expr → expr → tactic bool\n/-- Check whether two expressions are not in the same equivalence class. -/\nmeta constant cc_state.is_not_eqv : cc_state → expr → expr → tactic bool\n/-- Returns a proof term that the given terms are equivalent in the given cc_state-/\nmeta constant cc_state.eqv_proof : cc_state → expr → expr → tactic expr\n/-- Returns true if the cc_state is inconsistent. For example if it had both `a = b` and `a ≠ b` in it.-/\nmeta constant cc_state.inconsistent : cc_state → bool\n/-- `proof_for cc e` constructs a proof for e if it is equivalent to true in cc_state -/\nmeta constant cc_state.proof_for : cc_state → expr → tactic expr\n/-- `refutation_for cc e` constructs a proof for `not e` if it is equivalent to false in cc_state -/\nmeta constant cc_state.refutation_for : cc_state → expr → tactic expr\n/-- If the given state is inconsistent, return a proof for false. Otherwise fail. -/\nmeta constant cc_state.proof_for_false : cc_state → tactic expr\nnamespace cc_state\n\nmeta def mk : cc_state :=\ncc_state.mk_core {}\n\nmeta def mk_using_hs : tactic cc_state :=\ncc_state.mk_using_hs_core {}\n\nmeta def roots (s : cc_state) : list expr :=\ncc_state.roots_core s tt\n\nmeta instance : has_to_tactic_format cc_state :=\n⟨λ s, cc_state.pp_core s tt⟩\n\nmeta def eqc_of_core (s : cc_state) : expr → expr → list expr → list expr\n| e f r :=\n let n := s.next e in\n if n = f then e::r else eqc_of_core n f (e::r)\n\nmeta def eqc_of (s : cc_state) (e : expr) : list expr :=\ns.eqc_of_core e e []\n\nmeta def in_singlenton_eqc (s : cc_state) (e : expr) : bool :=\ns.next e = e\n\nmeta def eqc_size (s : cc_state) (e : expr) : nat :=\n(s.eqc_of e).length\n\nmeta def fold_eqc_core {α} (s : cc_state) (f : α → expr → α) (first : expr) : expr → α → α\n| c a :=\n let new_a := f a c,\n next := s.next c in\n if next =ₐ first then new_a\n else fold_eqc_core next new_a\n\nmeta def fold_eqc {α} (s : cc_state) (e : expr) (a : α) (f : α → expr → α) : α :=\nfold_eqc_core s f e e a\n\nmeta def mfold_eqc {α} {m : Type → Type} [monad m] (s : cc_state) (e : expr) (a : α) (f : α → expr → m α) : m α :=\nfold_eqc s e (return a) (λ act e, do a ← act, f a e)\nend cc_state\n\nopen tactic\nmeta def tactic.cc_core (cfg : cc_config) : tactic unit :=\ndo intros, s ← cc_state.mk_using_hs_core cfg, t ← target, s ← s.internalize t,\n if s.inconsistent then do {\n pr ← s.proof_for_false,\n mk_app `false.elim [t, pr] >>= exact}\n else do {\n tr ← return $ expr.const `true [],\n b ← s.is_eqv t tr,\n if b then do {\n pr ← s.eqv_proof t tr,\n mk_app `of_eq_true [pr] >>= exact\n } else do {\n dbg ← get_bool_option `trace.cc.failure ff,\n if dbg then do {\n ccf ← pp s,\n fail format!\"cc tactic failed, equivalence classes: \\n{ccf}\"\n } else do {\n fail \"cc tactic failed\"\n }\n }\n }\n\nmeta def tactic.cc : tactic unit :=\ntactic.cc_core {}\n\nmeta def tactic.cc_dbg_core (cfg : cc_config) : tactic unit :=\nsave_options $\n set_bool_option `trace.cc.failure tt\n >> tactic.cc_core cfg\n\nmeta def tactic.cc_dbg : tactic unit :=\ntactic.cc_dbg_core {}\n\nmeta def tactic.ac_refl : tactic unit :=\ndo (lhs, rhs) ← target >>= match_eq,\n s ← return $ cc_state.mk,\n s ← s.internalize lhs,\n s ← s.internalize rhs,\n b ← s.is_eqv lhs rhs,\n if b then do {\n s.eqv_proof lhs rhs >>= exact\n } else do {\n fail \"ac_refl failed\"\n }\n", "meta": {"author": "subfish-zhou", "repo": "N2Lean", "sha": "8e858cc5b01f1ad921094dc355db3cb9473a42fd", "save_path": "github-repos/lean/subfish-zhou-N2Lean", "path": "github-repos/lean/subfish-zhou-N2Lean/N2Lean-8e858cc5b01f1ad921094dc355db3cb9473a42fd/library/init/meta/smt/congruence_closure.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.46879062662624377, "lm_q2_score": 0.027169230551047186, "lm_q1q2_score": 0.012736680614978296}} {"text": "import \n -- data.real.basic\n -- topology.instances.real\n -- measure_theory.borel_space\n -- measure_theory.measure_space\n states\nuniverse u\nopen set topological_space classical\nlocal attribute [instance] prop_decidable\n\n\n-- ALL FILES IN THIS FOLDER ARE A WORK IN PROGRESS.\n-- THE TERMINOLOGY AND IDEAS DEFINED HERE ALSO DIFFER\n-- MARKEDLY FROM ONTOLOGY.LEAN. \n-- THIS FILE USED TO BE THE ROOT OF THE PROJECT.\n\n/-! # State Spaces\n\nHere we develop the higher order consequences of our theory,\nwhich are a consequence of the notion of state. We expand\nthe notion of state to define state spaces for substances,\nand prove associated lemmas.\n\nWe adopt the convention that all dependent types of a substance\nare to be upper cased, so for instance the type of states of a \nsubstance `s` is `s.State`.\n\n-/\n\n-- TODO: refactor so our naming convention is valid.\n-- TODO: refactor proofs so they are correct under the\n-- new definition of states (they worked before).\n\nnamespace ontology\n \n variables {ω : ontology} (s : ω.substance)\n include ω\n \n \n -- The type of states of a substance\n @[reducible]\n def substance.State := quotient s.State_setoid\n \n -- The quotient map from worlds to states,\n -- which ontologically grounds set of states as entities.\n-- @[reducible]\n-- def substance.f := @quotient.mk ω.world s.State_setoid\n \n @[reducible]\n def substance.State_at (w : ω.world) := @quotient.mk ω.world s.State_setoid w\n \n -- Recall that the quotient of a topological space\n -- is itself a topological space. Therefore the type\n -- of states of a substance is naturally endowed with \n -- topological structure. A set of states will be open \n -- if and only if the set of all worlds in which the substance is\n -- in one of the states is itself open, so any nonempty set of states\n -- can only be open if there is some entity which exists precisely in\n -- the worlds in which the entity has one of those states. \n -- Therefore any nonempty set of states is ontologically grounded,\n -- and so we can consider any such set to be an ontologically grounded\n -- property of the substance, and this we call a perfection.\n \n @[reducible]\n def substance.Event := set s.State\n \n structure substance.Perfection :=\n -- the event of the perfection existing in the substance\n (exist : s.Event)\n (is_open : is_open exist)\n (ne : exist.nonempty)\n (nuniv : exist ≠ univ)\n \n -- We added nuniv because the necessary s.Event should not really\n -- be considered an internal perfection of the substance, since it\n -- is grounded in the nb and is always necessary.\n \n -- Accidents of a substance are perfections of the same substance.\n -- The most important step in this proof is to show that they are open.\n lemma state_open_of_accident : ∀ (a: ω.accident), a.inheres s → is_open (s.State_at '' a.exists) := sorry\n-- begin\n-- intros a H,\n-- apply is_open_coinduced.2,\n-- simp [preimage],\n-- let α := {x : ω.world | ∃ (x_1 : ω.world), x_1 ∈ (a.val).exists ∧ substance.equiv s x_1 x},\n-- suffices c : is_open α,\n-- exact c,\n-- suffices c : α = a.val.exists,\n-- rw c,\n-- exact a.val.existential,\n-- ext, constructor; intro h; simp at *,\n-- obtain ⟨y, h₁, h₂⟩ := h,\n-- simp [substance.equiv, substance.state] at h₂,\n-- simp [ontology.world.entities, entity.subsistents] at h₂,\n \n-- -- have c : {a : ω.accident | a.inheres s} ∩ {a : ω.accident | y ∈ (a.val).exist} ⊆\n-- -- {a : ω.accident | a.inheres s} ∩ {a : ω.accident | x ∈ (a.val).exist},\n-- -- rw h₂,\n-- -- exact and.right (@c a ⟨H, h₁⟩),\n-- existsi x,\n-- constructor,\n-- assumption,\n-- obtain ⟨res, _, _⟩ := substance.equiv_sound s,\n-- exact res x,\n-- end\n \n -- It should then be easier to prove that it is not empty\n lemma state_ne_of_accident : ∀ (a: ω.accident), a.inheres s → (s.State_at '' a.exists).nonempty :=\n begin\n intros a H,\n simp [preimage],\n exact a.possible,\n end\n \n -- But it is a little bit harder to prove it is not univ\n lemma state_nuniv_of_accident : ∀ (a: ω.accident), a.inheres s → (s.State_at '' a.exists) ≠ univ := sorry\n-- begin\n-- intros a H,\n-- simp [preimage, image, quotient.mk],\n-- intro h,\n-- -- This is a trick\n-- -- let ψ := (@quotient.mk world ontology.substance.State_setoid),\n-- replace h : univ ⊆ {b : quotient s.State_setoid | ∃ (a_1 : ω.world), a_1 ∈ (a.val).exists ∧ s.State_at a_1 = b},\n-- rw ←h,\n-- -- refl,\n-- have c : s.val.exists = a.val.exists,\n-- ext, constructor; intro h₁,--; simp at *,\n-- have c := @h (s.State_at x) _,\n-- simp at c,\n-- obtain ⟨y, c₁, c₂⟩ := c,\n-- replace c₂ : s.equiv y x := c₂,\n-- simp [substance.equiv, substance.state] at c₂,\n-- simp [ontology.world.entities, entity.subsistents] at c₂,\n-- have c : {a : ω.accident | a.inheres s} ∩ {a : ω.accident | y ∈ (a.val).exist} ⊆\n-- {a : ω.accident | a.inheres s} ∩ {a : ω.accident | x ∈ (a.val).exist},\n-- rw c₂,\n-- exact and.right (@c a ⟨H, c₁⟩),\n-- trivial,\n-- revert x,\n-- apply sub_of_inheres,\n-- exact H,\n-- have c₁ : s.val.exists.dense := s.property,\n-- have c₂ : ¬ a.val.exists.dense := a.property,\n-- rw c at c₁,\n-- contradiction,\n-- end\n \n -- Finally we can construct the perfection.\n def substance.Perfection_of (a ∈ s.accidents) : s.Perfection :=\n ⟨ s.State_at '' a.exists\n , state_open_of_accident s a H\n , state_ne_of_accident s a H\n , state_nuniv_of_accident s a H\n ⟩\n \n -- perfections which come from accidents\n @[reducible]\n def substance.aperfections := {p : s.Perfection | ∃ a ∈ s.accidents, (s.Perfection_of a H) = p}\n \n -- events which come from accidents\n @[reducible]\n def substance.aevents := {p : s.Event | ∃ a ∈ s.accidents, (s.Perfection_of a H).exist = p}\n \n instance state_has_mem : has_mem s.Perfection s.State :=\n ⟨λ p s, s ∈ p.exist⟩\n @[reducible]\n def perfections (x : s.State) := {p : s.Perfection | p ∈ x}\n \n -- We can also build a neighborhood for any state\n -- which is an aperfection in case the substance has\n -- accidents in that state and the whole space otherwise.\n \n structure nhd {s : ω.substance} (x : s.State) :=\n (U : s.Event)\n (is_open : is_open U)\n (elem : x ∈ U)\n \n noncomputable def state.nhd_default {s : ω.substance} (x : s.State) : nhd x :=\n begin\n classical,\n set elab_help := s.State_setoid,\n -- lets build a world which maps to x\n -- and has some accident, the associated perfection of which\n -- will be our neighborhood. If no such world exists, we\n -- will just use univ.\n by_cases w : ∃w, ⟦w⟧ = x ∧ (∃a : ω.accident, a.inheres s ∧ a.up ∈ w),\n swap,\n exact ⟨univ, is_open_univ, by simp⟩,\n replace w := nonempty_subtype.2 w,\n replace w := classical.choice w,\n obtain ⟨w, hw, a⟩ := w,\n replace a := nonempty_subtype.2 a,\n replace a := classical.choice a,\n obtain ⟨a, ha₁, ha₂⟩ := a,\n -- a is now our wanted accident.\n let p := s.Perfection_of a ha₁,\n -- it is now easier to build the neighborhood.\n fconstructor,\n exact p.exist,\n exact p.is_open,\n rw ←hw,\n simp [p,substance.Perfection_of],\n existsi w,\n exact ⟨ha₂, rfl⟩,\n end\n \n -- Each contingent substance has a bottom state. For a contingent substance\n -- this is the \"state\" in which the substance does not exist.\n \n -- lemma aux : contingent s → ∀ w, \n \n -- def aux (h : contingent s) : nonempty (subtype s.val.exists.compl) := sorry\n \n -- @[reducible]\n -- noncomputable def state_bot (h : contingent s) : s.State :=\n -- have c : ¬ ∀ x, x ∈ s.val.exists,\n -- by {obtain ⟨⟨exist, is_open, nes⟩, perfect⟩ := s,\n -- intro h',\n -- replace h' := eq_univ_of_forall h',\n -- simp [contingent, nb, nbe] at h,\n -- simp at h',\n -- contradiction,\n -- },\n -- -- φ $\n -- -- classical.choice $\n -- -- nonempty_of_exists $\n -- -- not_forall.mp c\n -- -- have d : nonempty (subtype s.val.exists.compl),\n -- -- begin \n -- -- replace c := not_forall.mp c,\n -- -- obtain ⟨x, hx⟩ := c,\n -- -- constructor,\n -- -- exact ⟨x, hx⟩,\n -- -- end,\n -- φ $\n -- subtype.val $\n -- choice $\n -- aux h\n \n \n \n \n -- begin\n -- classical,\n -- obtain ⟨⟨exist, is_open, nes⟩, perfect⟩ := s,\n -- simp [contingent, nb, nbe] at h,\n -- set s : ω.substance := ⟨⟨exist, is_open, nes⟩, perfect⟩,\n -- have c : ¬ ∀ x, x ∈ exist,\n -- intro h',\n -- replace h' := eq_univ_of_forall h',\n -- contradiction,\n -- replace c := not_forall.mp c,\n -- replace c := nonempty_of_exists c,\n -- replace c := classical.choice c,\n -- exact φ s c,\n -- end\n \n -- set_option trace.elaborator_detail true\n -- lemma bot_no_accidents (h : contingent s) : (s.State_set (@quotient.out _ s.State_setoid (state_bot h))) = ∅ :=\n -- begin\n -- set elab_help := s.State_setoid,\n -- simp [substance.State_set],\n -- apply eq_empty_iff_forall_not_mem.2,\n -- intro x,\n -- simp,\n -- -- simp [state_bot, ontology.φ],\n -- intros h₂ h₃,\n -- -- simp at h₃,\n -- have d := sub_of_inheres x s h₂,\n -- replace h₃ := d h₃,\n -- -- simp [(choice (aux s h)).property] at h₃,\n -- -- set c := subtype.val (choice (aux s h),\n -- -- let c := quotient.mk_out ⟦(choice (aux s h)).val⟧,\n -- -- simp [quotient.out],\n -- end\n \n -- The bottom has no perfections.\n -- For the necessary being it is rather that\n -- we should consider it to have a single necessary\n -- informal \"perfection\" which is the set which \n -- contains only the unique state of the nb.\n -- lemma state_bot_empty : perfections ⊥ = ∅ :=\n -- begin\n -- classical,\n -- set elab_help := s.State_setoid,\n -- simp [perfections],\n -- apply eq_empty_of_subset_empty,\n -- intros p hp,\n -- simp at *,\n -- let e := quotient.mk⁻¹' p.exists,\n -- let state := p.ne.some,\n -- have c : is_open e ∧ e.nonempty,\n -- constructor,\n -- exact p.existential,\n -- simp [set.nonempty],\n -- use state.out,\n -- simp,\n -- exact p.ne.some_mem,\n -- let e₂ : entity := ⟨e, c.1, c.2⟩, \n -- -- apply mem_preimage.2,\n -- -- exact p.ne,\n -- -- focus {library_search},\n -- -- by_cases contingent s;\n -- -- simp [has_bot.bot, h, has_mem.mem] at hp,\n \n -- end\n \n -- Every state space is T0 but not T1, so that its specialization order\n -- has a botton element. For a contingent substance\n -- this is the \"state\" in which the substance does not exist.\n -- For the necessary being it is its unique state.\n -- instance state_order_bot : order_bot s.State :=\n -- begin\n -- classical,\n -- fconstructor,\n -- by_cases contingent s,\n -- obtain ⟨⟨exist, is_open, nes⟩, perfect⟩ := s,\n -- simp [contingent, nb, nbe] at h,\n -- set s : ω.substance := ⟨⟨exist, is_open, nes⟩, perfect⟩,\n -- have c : ¬ ∀ x, x ∈ exist,\n -- intro h',\n -- replace h' := eq_univ_of_forall h',\n -- contradiction,\n -- replace c := not_forall.mp c,\n -- replace c := nonempty_of_exists c,\n -- replace c := classical.choice c,\n -- exact φ s c,\n -- exact φ s (default world),\n -- intros x₁ x₂,\n -- exact ∀ p : s.Perfection, p ∈ x₁ → p ∈ x₂,\n -- intros x p h,\n -- exact h,\n -- intros x y z h₁ h₂ p hp,\n -- exact h₂ p (h₁ p hp),\n -- intros x y h₁ h₂,\n -- admit,\n -- intros x p hp,\n -- by_cases contingent s;\n -- simp [h] at hp,\n -- end\n \n \n -- Next we wish to show that the perfections which come from accidents\n -- form a basis.\n -- lemma accidents_nhds : ∀ (w : s.State) (U : set s.State), w ∈ U → is_open U → ∃ V ∈ s.aevents, w ∈ V ∧ V ⊆ U :=\n -- begin\n -- intros w U H op,\n -- end\n \n -- #check is_topological_basis_of_open_of_nhds\n \n -- Then we want to show that unions of accidents also map\n -- to perfections, and that all perfections are generated this way.\n \nend ontology", "meta": {"author": "maxd13", "repo": "topological_ontology", "sha": "68d21c9a00024fba3aed301e16c31e05733c1786", "save_path": "github-repos/lean/maxd13-topological_ontology", "path": "github-repos/lean/maxd13-topological_ontology/topological_ontology-68d21c9a00024fba3aed301e16c31e05733c1786/src/abstraction/statespaces.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41489886026626094, "lm_q2_score": 0.030675802264527863, "lm_q1q2_score": 0.012727355397305797}} {"text": "import Lean.Meta\nimport Lean.Elab\nopen Lean.Core\nopen Lean.Meta\nopen Lean.Elab.Term\nopen Lean\n\ndef mvarMeta4 : MetaM Expr := do\n let mvar ← mkFreshExprMVar (some (mkConst ``Nat))\n let mvarId := mvar.mvarId!\n let mvar2 ← mkFreshExprMVar (some (mkConst ``Nat)) -- none works too\n let mvarId2 := mvar2.mvarId!\n assignExprMVar mvarId2 (mkApp (mkConst `Nat.succ) mvar) -- eg tactic returns mvar seeking mvar2\n withLocalDecl Name.anonymous BinderInfo.default (mkConst ``Nat) $ fun x => \n do\n assignExprMVar mvarId x\n let q ← mkLambdaFVars #[x] mvar2\n return q\n\nsyntax (name := minass) \"minass!\" : term\n\n@[termElab minass] def minAssImpl4 : TermElab :=\n fun stx expectedType? =>\n do\n let e ← mvarMeta4\n return e\n\ndef chkMinAss4 := minass!\n\n#check chkMinAss4\n#eval chkMinAss4 2\n\ntheorem zero_add : (n : Nat) → 0 + n = n := by\n intro n\n induction n\n case zero => rfl\n case succ n ih => rw [Nat.add_succ, ih]\n\nopen Nat\n\ndef recFn : Nat → Nat := \n fun n =>\n match n with\n | zero => zero\n | succ n => succ (recFn n)\n /-\n Nat.brecOn n\n fun n f =>\n (match n : (n : Nat) → Nat.below n → Nat with \n | zero => fun x => zero\n | succ n => fun x => succ x.fst.fst)\n f\n-/\n/-by\n intro n\n match n with\n | zero => exact zero\n | succ n => exact succ (recFn n)\n-/\n#print recFn\n\n#check Nat.rec\n#check Nat.below\n\n\n#check Eq.mp\n#check congrArg\n\ndef rwPush (mvarId : MVarId) (e : Expr) (heq : Expr) \n (symm : Bool := false): TermElabM (Expr × Nat) :=\n do\n let t ← inferType e\n let rwr ← Meta.rewrite mvarId t heq symm\n let pf := rwr.eqProof\n let tt := rwr.eNew\n Elab.logInfo m!\"mvars : {rwr.mvarIds.length}\"\n let pushed ← mkAppM `Eq.mp #[pf, e]\n return (pushed, rwr.mvarIds.length)\n\nopen Lean.Elab.Tactic\n\nsyntax (name := rwPushTac) \"rwPushTac\" term \"on\" term : tactic\n@[tactic rwPushTac] def rwPushImpl : Tactic :=\n fun stx => \n match stx with\n | `(tactic|rwPushTac $t on $s) =>\n withMainContext $\n do\n let mvarId ← getMainGoal\n let e ← Elab.Tactic.elabTerm s none\n let heq ← Elab.Tactic.elabTerm t none\n let (rw, l) ← rwPush mvarId e heq\n Elab.logInfo m!\"obtained {rw}\"\n if ← isDefEq (← inferType rw) (← getMainTarget) \n then\n assignExprMVar mvarId rw\n replaceMainGoal [] \n else \n throwTacticEx `rwPushTac mvarId m!\"rwPush failed\" \n return ()\n | _ => Elab.throwIllFormedSyntax\n\ndef pushEg {α : Type}{P: α → Type}{a b : α}(heq : a = b)(x : P a) : P b := by\n rwPushTac heq on x\n\n#check @pushEg\n#reduce @pushEg\n\ndef transPf {α : Type}{a b c : α}(f: α → Nat) :\n a = b → b = c → a = c := by\n intros h1 h2\n rwPushTac h2 on h1\n\n\n#reduce transPf\n", "meta": {"author": "siddhartha-gadgil", "repo": "lean4-scratch", "sha": "680b7073f791706faf248d1d0ad21095012ae01b", "save_path": "github-repos/lean/siddhartha-gadgil-lean4-scratch", "path": "github-repos/lean/siddhartha-gadgil-lean4-scratch/lean4-scratch-680b7073f791706faf248d1d0ad21095012ae01b/Scratch/Eg4.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4455295203152604, "lm_q2_score": 0.02843603201565089, "lm_q1q2_score": 0.012669091703602328}} {"text": "import category_theory.shift\nimport tactic.linarith\nimport for_mathlib.category_theory.functor.shift_compatibility\nimport for_mathlib.category_theory.triangulated.shift_compatibility\nimport for_mathlib.category_theory.shift_misc\n\nnoncomputable theory\n\nopen category_theory category_theory.category\n\nnamespace category_theory\n\nnamespace functor\n\nvariables {C D E : Type*} [category C] [category D] [category E] (F : C ⥤ D)\n {A G : Type*} [add_monoid A] [add_group G]\n [has_shift C A] [has_shift D A] [has_shift E A]\n [hCℤ : has_shift C ℤ] [hDℤ : has_shift D ℤ]\n\nvariables (F A)\n\nnamespace comm_shift\n\ndef unit : shift_functor C (0 : A) ⋙ F ≅ F ⋙ shift_functor D (0 : A) :=\nshift.compatibility.comm_shift.unit _ _ F\n\n@[simp]\nlemma unit_hom_app (X : C) :\n (unit F A).hom.app X = F.map ((shift_functor_zero C A).hom.app X) ≫\n (shift_functor_zero D A).inv.app (F.obj X) :=\nbegin\n dsimp [unit, shift.compatibility.comm_shift.unit],\n erw [id_comp, id_comp],\nend\n\n@[simp]\nlemma unit_inv_app (X : C) :\n (unit F A).inv.app X = (shift_functor_zero D A).hom.app (F.obj X) ≫\n F.map ((shift_functor_zero C A).inv.app X) :=\nbegin\n dsimp [unit, shift.compatibility.comm_shift.unit],\n simp only [comp_id],\nend\n\nvariables {F A}\n\n@[simp]\ndef change {a b : A} (e : shift_functor C a ⋙ F ≅ F ⋙ shift_functor D a)\n (h : a = b) :\n shift_functor C b ⋙ F ≅ F ⋙ shift_functor D b :=\nshift.compatibility.comm_shift.change e (eq_to_iso (by subst h))\n\ndef add {a b : A} (e₁ : shift_functor C a ⋙ F ≅ F ⋙ shift_functor D a)\n (e₂ : shift_functor C b ⋙ F ≅ F ⋙ shift_functor D b) :\n shift_functor C (a + b) ⋙ F ≅ F ⋙ shift_functor D (a + b) :=\nshift.compatibility.comm_shift.comp e₁ e₂\n\n@[simp]\nlemma add_hom_app {a b : A} (e₁ : shift_functor C a ⋙ F ≅ F ⋙ shift_functor D a)\n (e₂ : shift_functor C b ⋙ F ≅ F ⋙ shift_functor D b) (X : C) :\n (add e₁ e₂).hom.app X = F.map ((shift_functor_add C a b).hom.app X) ≫\n e₂.hom.app (X⟦a⟧) ≫ (e₁.hom.app X)⟦b⟧' ≫ (shift_functor_add D a b).inv.app (F.obj X) :=\nbegin\n dsimp [add, shift.compatibility.comm_shift.comp],\n erw [id_comp, id_comp, id_comp],\nend\n\n@[simp]\nlemma add_inv_app {a b : A} (e₁ : shift_functor C a ⋙ F ≅ F ⋙ shift_functor D a)\n (e₂ : shift_functor C b ⋙ F ≅ F ⋙ shift_functor D b) (X : C) :\n (add e₁ e₂).inv.app X = (shift_functor_add D a b).hom.app (F.obj X) ≫\n (e₁.inv.app X)⟦b⟧' ≫ e₂.inv.app (X⟦a⟧) ≫ F.map ((shift_functor_add C a b).inv.app X) :=\nbegin\n dsimp [add, shift.compatibility.comm_shift.comp],\n erw [comp_id, comp_id, comp_id, assoc, assoc],\nend\n\n@[simp]\ndef add' {a b c : A} (h : a + b = c) (e₁ : shift_functor C a ⋙ F ≅ F ⋙ shift_functor D a)\n (e₂ : shift_functor C b ⋙ F ≅ F ⋙ shift_functor D b) :\n shift_functor C c ⋙ F ≅ F ⋙ shift_functor D c :=\n(shift.compatibility.comm_shift.comp e₁ e₂).change (eq_to_iso (by simpa only [← h]))\n\nlemma add'_eq_add {a b : A} (e₁ : shift_functor C a ⋙ F ≅ F ⋙ shift_functor D a)\n (e₂ : shift_functor C b ⋙ F ≅ F ⋙ shift_functor D b) :\n add' rfl e₁ e₂ = add e₁ e₂ :=\nby simp only [add', add, eq_to_iso_refl, shift.compatibility.comm_shift.change_refl]\n\ndef sub {a b : A} (e : shift_functor C (a + b) ⋙ F ≅ F ⋙ shift_functor D (a + b))\n (f : shift_functor C b ⋙ F ≅ F ⋙ shift_functor D b) [is_equivalence (shift_functor D b)] :\n shift_functor C a ⋙ F ≅ F ⋙ shift_functor D a :=\n@shift.compatibility.comm_shift.comp_cancel _ _ _ _ _ _ _ _ _ F (discrete.mk a) (discrete.mk b) e f _\n\ndef add_equiv {b : A} (f : shift_functor C b ⋙ F ≅ F ⋙ shift_functor D b)\n [is_equivalence (shift_functor D b)] (a : A) :\n (shift_functor C a ⋙ F ≅ F ⋙ shift_functor D a) ≃\n (shift_functor C (a + b) ⋙ F ≅ F ⋙ shift_functor D (a + b)) :=\n{ to_fun := λ e, add e f,\n inv_fun := λ e, sub e f,\n left_inv := (shift.compatibility.comm_shift.comp_equiv f (discrete.mk a)).left_inv,\n right_inv := (shift.compatibility.comm_shift.comp_equiv f (discrete.mk a)).right_inv, }\n\ndef sub' {a b c : A} (h : a + b = c) (e : shift_functor C c ⋙ F ≅ F ⋙ shift_functor D c)\n (f : shift_functor C b ⋙ F ≅ F ⋙ shift_functor D b) [is_equivalence (shift_functor D b)] :\n shift_functor C a ⋙ F ≅ F ⋙ shift_functor D a :=\nsub (change e h.symm) f\n\nlemma sub'_eq_sub {a b : A} (e : shift_functor C (a + b) ⋙ F ≅ F ⋙ shift_functor D (a + b))\n (f : shift_functor C b ⋙ F ≅ F ⋙ shift_functor D b) [is_equivalence (shift_functor D b)] :\n sub' rfl e f = sub e f :=\nbegin\n dsimp only [sub'],\n simp only [change, eq_to_iso_refl, shift.compatibility.comm_shift.change_refl],\nend\n\ndef add'_equiv {a b c : A} (h : a + b = c)\n (f : shift_functor C b ⋙ F ≅ F ⋙ shift_functor D b)\n [is_equivalence (shift_functor D b)] :\n (shift_functor C a ⋙ F ≅ F ⋙ shift_functor D a) ≃\n (shift_functor C c ⋙ F ≅ F ⋙ shift_functor D c) :=\n{ to_fun := λ e, add' h e f,\n inv_fun := λ e, sub' h e f,\n left_inv := begin\n subst h,\n simpa only [sub'_eq_sub, add'_eq_add] using (add_equiv f a).left_inv,\n end,\n right_inv := begin\n subst h,\n simpa only [sub'_eq_sub, add'_eq_add] using (add_equiv f a).right_inv,\n end, }\n\nlemma add_bijective {b : A} (f : shift_functor C b ⋙ F ≅ F ⋙ shift_functor D b)\n [is_equivalence (shift_functor D b)] (a : A) :\n function.bijective (λ (e : shift_functor C a ⋙ F ≅ F ⋙ shift_functor D a),\n add e f) :=\n(add_equiv f a).bijective\n\nlemma add'_bijective {a b c : A} (h : a + b = c)\n (f : shift_functor C b ⋙ F ≅ F ⋙ shift_functor D b)\n [is_equivalence (shift_functor D b)] :\n function.bijective (λ (e : shift_functor C a ⋙ F ≅ F ⋙ shift_functor D a),\n add' h e f) :=\n(add'_equiv h f).bijective\n\n@[simp]\nlemma add'_sub' {a b c : A} (h : a + b = c) (e : shift_functor C c ⋙ F ≅ F ⋙ shift_functor D c)\n (f : shift_functor C b ⋙ F ≅ F ⋙ shift_functor D b) [is_equivalence (shift_functor D b)] :\n add' h (sub' h e f) f = e :=\n(add'_equiv h f).right_inv e\n\nlemma add'_assoc (a b c ab bc abc : A) (hab : a + b = ab) (hbc : b + c = bc)\n (habc : a + b + c = abc)\n (e₁ : shift_functor C a ⋙ F ≅ F ⋙ shift_functor D a)\n (e₂ : shift_functor C b ⋙ F ≅ F ⋙ shift_functor D b)\n (e₃ : shift_functor C c ⋙ F ≅ F ⋙ shift_functor D c) :\n add' (show ab + c = abc, by rw [← hab, habc]) (add' hab e₁ e₂) e₃ =\n add' (show a + bc = abc, by rw [← hbc, ← add_assoc, habc]) e₁ (add' hbc e₂ e₃) :=\nbegin\n substs hab hbc habc,\n simp only [add'_eq_add],\n apply shift.compatibility.comm_shift.comp_assoc,\nend\n\n@[protected]\nlemma zero_add {a : A} (e : shift_functor C a ⋙ F ≅ F ⋙ shift_functor D a) :\n add (unit _ _) e = change e (zero_add a).symm :=\nshift.compatibility.comm_shift.unit_comp e\n\n@[protected]\nlemma add_zero {a : A} (e : shift_functor C a ⋙ F ≅ F ⋙ shift_functor D a) :\n add e (unit _ _) = change e (add_zero a).symm :=\nshift.compatibility.comm_shift.comp_unit e\n\n@[simp]\nlemma add'_zero {a : A} (e : shift_functor C a ⋙ F ≅ F ⋙ shift_functor D a) :\n add' (add_zero a) e (unit _ _) = e :=\nbegin\n change change (add e (unit _ _)) (add_zero a) = e,\n rw comm_shift.add_zero,\n simp only [change, shift.compatibility.comm_shift.change_comp, eq_to_iso_trans,\n eq_to_iso_refl, shift.compatibility.comm_shift.change_refl],\nend\n\nend comm_shift\n\nvariables (F A)\n\n@[ext, nolint has_nonempty_instance]\nclass has_comm_shift :=\n(iso : Π (a : A), shift_functor C a ⋙ F ≅ F ⋙ shift_functor D a)\n(iso_zero : iso 0 = comm_shift.unit F A)\n(iso_add : ∀ (a b : A), iso (a + b) = comm_shift.add (iso a) (iso b))\n\nvariable {A}\ndef comm_shift_iso [F.has_comm_shift A] (a : A) :\n shift_functor C a ⋙ F ≅ F ⋙ shift_functor D a :=\nhas_comm_shift.iso a\n\nlemma comm_shift_iso_add [F.has_comm_shift A] (a b : A) :\n F.comm_shift_iso (a + b) = comm_shift.add (F.comm_shift_iso a) (F.comm_shift_iso b) :=\nhas_comm_shift.iso_add _ _\n\nvariable (A)\n\nlemma comm_shift_iso_zero [F.has_comm_shift A] :\n F.comm_shift_iso (0 : A) = comm_shift.unit F A :=\nhas_comm_shift.iso_zero\n\nvariable {A}\nlemma comm_shift_congr_iso {a b : A} [F.has_comm_shift A] (h : a = b) (X : C) :\n (F.comm_shift_iso a).hom.app X = eq_to_hom (by rw h) ≫\n (F.comm_shift_iso b).hom.app X ≫ eq_to_hom (by rw h) :=\nby { subst h, simp only [eq_to_hom_refl, comp_id, id_comp], }\n\nnamespace comm_shift\n\nvariables {F A}\n\nlemma iso_add_eq_of_iso_eq (e₁ e₂ : F.has_comm_shift A) (a b : A)\n (ha : e₁.iso a = e₂.iso a) (hb : e₁.iso b = e₂.iso b) :\n e₁.iso (a + b) = e₂.iso (a + b) :=\nby rw [e₁.iso_add, e₂.iso_add, ha, hb]\n\nlemma iso_eq_of_iso_add_eq (e₁ e₂ : F.has_comm_shift A) (a b : A)\n (hb : e₁.iso b = e₂.iso b) (hab : e₁.iso (a + b) = e₂.iso (a+b))\n [is_equivalence (shift_functor D b)] : e₁.iso a = e₂.iso a :=\n(comm_shift.add_bijective (e₁.iso b) a).1\n (by { dsimp only, rw [← e₁.iso_add, hb, ← e₂.iso_add, hab], })\n\ninclude hCℤ hDℤ\n\n@[ext]\nlemma eq_of_iso_one_eq (e₁ e₂ : F.has_comm_shift ℤ)\n (h : e₁.iso (1 : ℤ) = e₂.iso (1 : ℤ)) : e₁ = e₂ :=\nbegin\n suffices : ∀ (n : ℕ), e₁.iso (n : ℤ) = e₂.iso (n : ℤ),\n { ext n : 2,\n cases n,\n { apply this, },\n { have eq : (-[1+n]+(1+n)) = 0,\n { simp only [int.neg_succ_of_nat_coe, nat.cast_add, nat.cast_one, neg_add_rev],\n linarith, },\n refine iso_eq_of_iso_add_eq e₁ e₂ (-[1+n]) (1+n) (this _) _,\n rw [eq, e₁.iso_zero, e₂.iso_zero], }, },\n intro n,\n induction n with n hn,\n { exact e₁.iso_zero.trans (e₂.iso_zero.symm), },\n { rw [nat.cast_succ, e₁.iso_add, e₂.iso_add, hn, h], },\nend\n\nvariable (e : shift_functor C (1 : ℤ) ⋙ F ≅ F ⋙ shift_functor D (1 : ℤ))\n\nnamespace mk_ℤ\n\nnoncomputable\ndef iso_ℕ : Π (n : ℕ), shift_functor C (int.of_nat n) ⋙ F ≅ F ⋙ shift_functor D (int.of_nat n)\n| 0 := unit _ _\n| 1 := e\n| (n+2) := add (iso_ℕ (n+1)) e\n\n@[simp]\nlemma iso_ℕ_zero : iso_ℕ e 0 = unit _ _ := rfl\n\n@[simp]\nlemma iso_ℕ_one : iso_ℕ e 1 = e := rfl\n\nlemma iso_ℕ_add_one (n : ℕ) : add (iso_ℕ e n) e = iso_ℕ e (n+1) :=\nbegin\n cases n,\n { unfold iso_ℕ,\n simp only [comm_shift.zero_add, change, eq_to_iso_refl, shift.compatibility.comm_shift.change_refl], },\n { unfold iso_ℕ, },\nend\n\nlemma iso_ℕ_add'_one (n₀ n₁ : ℕ) (h : n₀ + 1 = n₁) :\n add' (by { simp only [← h, int.of_nat_eq_coe], push_cast, })\n (iso_ℕ e n₀) e = iso_ℕ e n₁ :=\nbegin\n subst h,\n erw add'_eq_add,\n apply iso_ℕ_add_one,\nend\n\ndef iso_ℤ : Π (n : ℤ), shift_functor C (n : ℤ) ⋙ F ≅ F ⋙ shift_functor D (n : ℤ)\n| (int.of_nat n) := iso_ℕ e n\n| -[1+n] := sub' (by { rw int.of_nat_eq_coe, rw int.neg_succ_of_nat_coe', push_cast, linarith, })\n (unit F ℤ) (iso_ℕ e (1+n))\n\n@[simp]\nlemma iso_ℤ_zero : iso_ℤ e 0 = unit _ _ := rfl\n\n@[simp]\nlemma iso_ℤ_one : iso_ℤ e 1 = e := rfl\n\nlemma iso_ℕ_add' (n₁ n₂ n₃ : ℕ) (h : n₁ + n₂ = n₃) :\n add' (by simp only [← h, int.of_nat_eq_coe, nat.cast_add]) (iso_ℕ e n₁) (iso_ℕ e n₂) =\n iso_ℕ e n₃ :=\nbegin\n revert h n₃ n₁,\n induction n₂ with n₂ hn₂,\n { intros n₁ n₃ h,\n have h' : n₁ = n₃ := by simpa only [add_zero] using h,\n subst h',\n exact add'_zero (iso_ℕ e n₁), },\n { intros n₁ n₃ h,\n rw ← iso_ℕ_add_one,\n rw ← add'_eq_add,\n conv_lhs { congr, skip, congr, skip, rw ← iso_ℕ_one e, },\n erw ← add'_assoc (int.of_nat n₁) (int.of_nat n₂) 1 (int.of_nat (n₁ + n₂))\n (int.of_nat n₂ + 1) n₃ (by simp) (by simp) (by { rw ← h, push_cast, simp, rw add_assoc,}),\n rw hn₂ _ _ rfl,\n erw iso_ℕ_add'_one,\n rw [← h, nat.succ_eq_add_one, add_assoc], },\nend\n\nlemma iso_ℤ_add'_nonneg (n₁ n₂ n₃ : ℤ) (h : n₁ + n₂ = n₃) (hn₁ : 0 ≤ n₁) (hn₂ : 0 ≤ n₂) :\n add' h (iso_ℤ e n₁) (iso_ℤ e n₂) = iso_ℤ e n₃ :=\nbegin\n have h₁ : ∃ (m₁ : ℕ), n₁ = int.of_nat m₁ := int.eq_coe_of_zero_le hn₁,\n have h₂ : ∃ (m₂ : ℕ), n₂ = int.of_nat m₂ := int.eq_coe_of_zero_le hn₂,\n rcases h₁ with ⟨m₁, hm₁⟩,\n rcases h₂ with ⟨m₂, hm₂⟩,\n have h₃ : n₃ = int.of_nat (m₁ + m₂),\n { simp only [← h, hm₁, hm₂, int.of_nat_eq_coe, nat.cast_add], },\n substs hm₁ hm₂ h₃,\n unfold iso_ℤ,\n exact iso_ℕ_add' e _ _ _ rfl,\nend\n\nlemma iso_ℤ_add'_neg (n₁ n₂ : ℤ) (h : n₁ + n₂ = 0) (hn₂ : 0 ≤ n₂):\n add' h (iso_ℤ e n₁) (iso_ℤ e n₂) = unit F ℤ :=\nbegin\n cases n₁,\n { have hn₁ : 0 ≤ int.of_nat n₁ := int.of_nat_nonneg n₁,\n have h₂ : n₂ = 0 := by linarith,\n subst h₂,\n have h₁ : n₁ = 0 := by simpa only [int.of_nat_eq_coe, add_zero, nat.cast_eq_zero] using h,\n subst h₁,\n erw [iso_ℤ_zero, add'_zero], },\n { have h₂ : n₂ = int.of_nat (1 + n₁),\n { rw int.neg_succ_of_nat_coe' at h,\n rw int.of_nat_eq_coe,\n push_cast,\n linarith, },\n subst h₂,\n unfold iso_ℤ,\n apply add'_sub', },\nend\n\nlemma iso_ℤ_add'_one (n₀ n₁ : ℤ) (h : n₀ + 1 = n₁) : add' h (iso_ℤ e n₀) e = iso_ℤ e n₁ :=\nbegin\n cases n₀,\n { have h₁ : n₁ = int.of_nat (n₀ + 1),\n { rw ← h, simp, },\n subst h₁,\n unfold iso_ℤ,\n rw ← iso_ℕ_add_one e n₀,\n apply add'_eq_add, },\n { have h' := h,\n rw int.neg_succ_of_nat_coe' at h',\n apply (add'_bijective (show n₁ + int.of_nat n₀ = 0, by { rw int.of_nat_eq_coe, linarith, })\n (iso_ℤ e (int.of_nat n₀))).1 _,\n simp only,\n rw iso_ℤ_add'_neg e, swap, { apply int.of_nat_nonneg, },\n rw add'_assoc (-[1+n₀]) 1 (int.of_nat n₀) n₁ (int.of_nat (1+n₀)) 0 h\n (by simp) (by { rw int.neg_succ_of_nat_coe', simp,}),\n conv_lhs { congr, skip, congr, rw ← iso_ℤ_one e, },\n rw iso_ℤ_add'_nonneg e 1 (int.of_nat n₀) (int.of_nat (1+n₀)) (by simp) zero_le_one (int.of_nat_nonneg n₀),\n apply iso_ℤ_add'_neg,\n apply int.of_nat_nonneg, },\nend\n\nlemma iso_ℤ_add_one (n : ℤ) : add (iso_ℤ e n) (iso_ℤ e 1) = iso_ℤ e (n + 1) :=\nbegin\n rw ← add'_eq_add,\n apply iso_ℤ_add'_one,\nend\n\nend mk_ℤ\n\n@[simps]\ndef mk'_ℤ (iso : Π (a : ℤ), shift_functor C a ⋙ F ≅ F ⋙ shift_functor D a)\n (iso_zero : iso 0 = comm_shift.unit F ℤ)\n (iso_add_one : ∀ (a : ℤ), iso (a + 1) = comm_shift.add (iso a) (iso 1)) :\n has_comm_shift F ℤ :=\n{ iso := iso,\n iso_zero := iso_zero,\n iso_add := begin\n have iso_add_one' : ∀ (a b : ℤ) (h : a + 1 = b),\n iso b = comm_shift.add' h (iso a) (iso 1),\n { intros a b h,\n subst h,\n rw add'_eq_add,\n apply iso_add_one, },\n suffices : ∀ (a b c : ℤ) (h : a + b = c) (hb : 0 ≤ b),\n iso c = add' h (iso a) (iso b),\n { intros a b,\n by_cases hb : 0 ≤ b,\n { rw [this a b _ rfl hb, add'_eq_add], },\n { rw ← add'_eq_add,\n apply (add'_bijective (show (a+b)+(-b) = a, by linarith) (iso (-b))).1,\n simp only [← this (a+b) (-b) a (by linarith) (by linarith),\n add'_assoc a b (-b) (a+b) 0 a rfl (by linarith) (by linarith),\n ← this b (-b) 0 (by linarith) (by linarith), iso_zero, add'_zero], }, },\n intros a b c h hb,\n obtain ⟨b', hb'⟩ := int.eq_coe_of_zero_le hb,\n subst hb',\n clear hb,\n revert a c,\n induction b' with b hb,\n { intros a c h,\n have hc : c = a := by simp only [←h, nat.cast_zero, add_zero],\n subst hc,\n erw [iso_zero, add'_zero], },\n { intros a c h,\n rw iso_add_one' b b.succ (by push_cast),\n rw ← add'_assoc a b 1 _ b.succ c rfl (by push_cast)\n (by { rw ← h, push_cast, rw add_assoc, }),\n rw ← hb a _ rfl,\n apply iso_add_one', },\n end}\n\n@[simps]\ndef mk_ℤ (e : shift_functor C (1 : ℤ) ⋙ F ≅ F ⋙ shift_functor D (1 : ℤ)) :\n has_comm_shift F ℤ :=\nmk'_ℤ (mk_ℤ.iso_ℤ e) rfl (λ a, (mk_ℤ.iso_ℤ_add_one e a).symm)\n\nvariable (F)\n\n@[simps]\ndef equiv_ℤ : has_comm_shift F ℤ ≃\n (shift_functor C (1 : ℤ) ⋙ F ≅ F ⋙ shift_functor D (1 : ℤ)) :=\n{ to_fun := λ c, c.iso 1,\n inv_fun := λ e, mk_ℤ e,\n left_inv := λ c, by { ext, refl, },\n right_inv := λ e, rfl, }\n\nend comm_shift\n\nvariable {A}\n\nlemma iso_add_hom_app (F : C ⥤ D) [F.has_comm_shift A] (p q : A) (X : C) :\n (F.comm_shift_iso (p+q)).hom.app X = F.map ((shift_functor_add C p q).hom.app X) ≫\n (F.comm_shift_iso q).hom.app (X⟦p⟧) ≫ ((F.comm_shift_iso p).hom.app X)⟦q⟧' ≫\n (shift_functor_add D p q).inv.app (F.obj X) :=\nbegin\n simp only [comm_shift_iso_add, comm_shift.add, shift.compatibility.comm_shift.comp_hom_app,\n iso.symm_hom, iso.symm_inv, monoidal_functor.μ_iso_hom],\nend\n\nlemma map_shift_functor_add_comm {A : Type*} [add_comm_monoid A] (F : C ⥤ D)\n [has_shift C A] [has_shift D A] [F.has_comm_shift A] (p q : A) (X : C) :\n F.map ((shift_functor_add_comm C p q).hom.app X) ≫\n (F.comm_shift_iso p).hom.app (X⟦q⟧) ≫ ((F.comm_shift_iso q).hom.app X)⟦p⟧' =\n (F.comm_shift_iso q).hom.app (X⟦p⟧) ≫ ((F.comm_shift_iso p).hom.app X)⟦q⟧' ≫\n (shift_functor_add_comm D p q).hom.app (F.obj X) :=\nbegin\n have eq₁ := F.iso_add_hom_app p q X,\n simp only [← cancel_mono ((shift_functor_add D p q).hom.app (F.obj X)),\n assoc, iso.inv_hom_id_app] at eq₁,\n erw comp_id at eq₁,\n have eq₂ := F.iso_add_hom_app q p X,\n simp only [← cancel_epi (F.map ((shift_functor_add C q p).inv.app X)),\n ← F.map_comp_assoc, iso.inv_hom_id_app, F.map_id, id_comp] at eq₂,\n simp only [← cancel_epi (F.map ((shift_functor_add C p q).hom.app X)),\n ← cancel_mono ((shift_functor_add D q p).inv.app (F.obj X)), assoc],\n slice_rhs 1 3 { rw ← eq₁, },\n simp only [assoc, ← eq₂], clear eq₁ eq₂,\n dsimp only [shift_functor_add_comm, iso.symm, iso.trans, nat_trans.comp_app],\n simpa only [F.map_comp, ← F.map_comp_assoc, assoc, eq_to_iso, eq_to_hom_app, eq_to_hom_map,\n iso.hom_inv_id_app, iso.hom_inv_id_app_assoc, F.map_id, id_comp, comp_id,\n F.comm_shift_congr_iso (add_comm p q), assoc, eq_to_hom_trans, eq_to_hom_refl],\nend\n\n@[reassoc]\nlemma compatibility_composition (F₁ : C ⥤ D) (F₂ : D ⥤ E)\n [F₁.has_comm_shift A] [F₂.has_comm_shift A] (a b : A) (X : C) :\n F₂.map ((shift_functor D b).map ((F₁.comm_shift_iso a).hom.app X)) ≫\n (F₂.comm_shift_iso b).hom.app ((shift_functor D a).obj (F₁.obj X)) =\n (F₂.comm_shift_iso b).hom.app (F₁.obj ((shift_functor C a).obj X)) ≫\n (shift_functor E b).map (F₂.map ((F₁.comm_shift_iso a).hom.app X)) :=\nbegin\n let α := (F₁.comm_shift_iso a).hom,\n let β := (F₂.comm_shift_iso b).hom,\n have eq := nat_trans.exchange (F₁.comm_shift_iso a).hom (𝟙 _) (𝟙 _) (F₂.comm_shift_iso b).hom,\n simp only [id_comp, comp_id] at eq,\n replace eq := congr_app eq.symm X,\n dsimp at eq,\n simpa only [assoc, id_comp, functor.map_id, comp_id] using eq,\nend\n\ninstance has_comm_shift_comp (F₁ : C ⥤ D) (F₂ : D ⥤ E)\n [F₁.has_comm_shift A] [F₂.has_comm_shift A] : (F₁ ⋙ F₂).has_comm_shift A :=\n{ iso := λ a, comm_shift_comp (F₁.comm_shift_iso a) (F₂.comm_shift_iso a),\n iso_zero := begin\n ext X,\n simp only [comm_shift_comp_hom_app, F₁.comm_shift_iso_zero A,\n F₂.comm_shift_iso_zero A],\n dsimp only [comm_shift.unit, shift.compatibility.comm_shift.unit],\n simp only [iso.trans_hom, iso_whisker_right_hom, iso.symm_hom,\n iso_whisker_left_hom, monoidal_functor.ε_iso_hom,\n nat_trans.comp_app, whisker_right_app, left_unitor_hom_app, right_unitor_inv_app,\n whisker_left_app, id_comp, map_comp, assoc, comp_map],\n erw [functor.map_id, id_comp, id_comp],\n dsimp [monoidal_functor.ε_iso],\n nth_rewrite 1 ← F₂.map_comp_assoc,\n rw [← nat_trans.comp_app, is_iso.hom_inv_id],\n erw [F₂.map_id, id_comp],\n end,\n iso_add := λ a b, begin\n ext X,\n simp only [assoc, comm_shift_comp_hom_app, comm_shift.add_hom_app, comp_map,\n comm_shift_iso_add, functor.map_comp, comp],\n slice_lhs 4 5 { erw [← F₂.map_comp, iso.inv_hom_id_app, F₂.map_id], },\n simpa only [assoc, id_comp, compatibility_composition_assoc],\n end, }\n\nlemma shift_functor_add'_hom_app_obj [F.has_comm_shift A] (a b c : A) (h : c = a + b)\n (K : C) :\n ((shift_functor_add' D a b c) h).hom.app (F.obj K) =\n (F.comm_shift_iso c).inv.app K ≫\n F.map (((shift_functor_add' _ a b c) h).hom.app K) ≫\n (F.comm_shift_iso b).hom.app (K⟦a⟧) ≫\n (shift_functor D b).map ((F.comm_shift_iso a).hom.app K) :=\nbegin\n subst h,\n simp only [shift_functor_add'_eq_shift_functor_add, F.comm_shift_iso_add,\n comm_shift.add, iso.symm_hom, shift.compatibility.comm_shift.comp_inv_app, assoc,\n ← F.map_comp_assoc, μ_hom_inv_app],\n erw [F.map_id, id_comp, iso.inv_hom_id_app_assoc, ← functor.map_comp,\n iso.inv_hom_id_app, functor.map_id, comp_id],\nend\n\nvariable (A)\n\nlemma shift_functor_zero_hom_app_obj [F.has_comm_shift A] (K : C) :\n (shift_functor_zero D A).hom.app (F.obj K) =\n (F.comm_shift_iso 0).inv.app K ≫ F.map ((shift_functor_zero C A).hom.app K) :=\nbegin\n rw F.comm_shift_iso_zero,\n dsimp [comm_shift.unit, shift.compatibility.comm_shift.unit],\n erw [comp_id, comp_id, assoc, ← F.map_comp],\n simp only [ε_hom_inv_app, map_id, comp_id],\nend\n\ninstance id_has_comm_shift {C A : Type*} [category C]\n [add_monoid A] [has_shift C A] :\n (𝟭 C).has_comm_shift A :=\n{ iso := λ a, by refl,\n iso_add := λ a b, begin\n ext X,\n dsimp only [iso.refl, comm_shift.add],\n simp only [nat_trans.id_app, shift.compatibility.comm_shift.comp_hom_app, id_map],\n erw [id_comp, functor.map_id, id_comp, iso.inv_hom_id_app],\n refl,\n end,\n iso_zero := begin\n ext X,\n dsimp only [iso.refl, comm_shift.unit, shift.compatibility.comm_shift.unit,\n iso.trans, functor.left_unitor, iso_whisker_right, whiskering_right,\n functor.map_iso, whisker_right, nat_trans.id_app, nat_trans.comp_app,\n functor.id, functor.right_unitor, iso.symm, iso_whisker_left,\n whiskering_left, whisker_left],\n erw [id_comp, id_comp, iso.inv_hom_id_app],\n refl,\n end, }\n\n@[simp]\nlemma has_comm_shift.id_iso_hom_app {C A : Type*} [category C]\n [add_monoid A] [has_shift C A] (X : C) (a : A) :\n (comm_shift_iso (𝟭 C) a).hom.app X = 𝟙 _ := rfl\n\n@[simp]\nlemma has_comm_shift.id_iso_inv_app {C A : Type*} [category C]\n [add_monoid A] [has_shift C A] (X : C) (a : A) :\n (comm_shift_iso (𝟭 C) a).inv.app X = 𝟙 _ := rfl\n\n@[simp]\nlemma has_comm_shift.comp_hom_app (F₁ : C ⥤ D) (F₂ : D ⥤ E)\n [F₁.has_comm_shift A] [F₂.has_comm_shift A] (X : C) (a : A) :\n (comm_shift_iso (F₁ ⋙ F₂) a).hom.app X =\n F₂.map ((comm_shift_iso F₁ a).hom.app X) ≫\n (comm_shift_iso F₂ a).hom.app (F₁.obj X) :=\ncomm_shift_comp_hom_app _ _ _\n\n@[simp]\nlemma has_comm_shift.comp_inv_app (F₁ : C ⥤ D) (F₂ : D ⥤ E)\n [F₁.has_comm_shift A] [F₂.has_comm_shift A] (X : C) (a : A) :\n (comm_shift_iso (F₁ ⋙ F₂) a).inv.app X =\n (comm_shift_iso F₂ a).inv.app (F₁.obj X) ≫\n F₂.map ((comm_shift_iso F₁ a).inv.app X) :=\ncomm_shift_comp_inv_app _ _ _\n\nend functor\n\nnamespace shift\n\nsection\n\nvariables {C D : Type*} [category C] [category D] (F : C ⥤ D)\n {A : Type*} [add_monoid A] [has_shift D A] [full F] [faithful F]\n (s : A → C ⥤ C) (hs : Π (a : A), s a ⋙ F ≅ F ⋙ shift_functor D a)\n\nlocal attribute [instance] endofunctor_monoidal_category\n\nlemma has_shift_of_fully_faithful_map_ε_iso_hom_app (X : C) :\n F.map ((@shift_monoidal_functor C A _ _\n (has_shift_of_fully_faithful F s hs)).ε_iso.hom.app X) =\n (shift_zero A (F.obj X)).inv ≫ (hs 0).inv.app X :=\nbegin\n dsimp [shift_monoidal_functor],\n erw [id_comp, id_comp],\n simp only [functor.image_preimage],\nend\n\nlemma has_shift_of_fully_faithful_map_ε_iso_inv_app (X : C) :\n F.map ((@shift_monoidal_functor C A _ _\n (has_shift_of_fully_faithful F s hs)).ε_iso.inv.app X) =\n (hs 0).hom.app X ≫ (shift_zero A (F.obj X)).hom :=\nbegin\n rw [← cancel_mono (F.map ((@shift_monoidal_functor C A _ _\n (has_shift_of_fully_faithful F s hs)).ε_iso.hom.app X)), ← F.map_comp,\n iso.inv_hom_id_app, F.map_id, has_shift_of_fully_faithful_map_ε_iso_hom_app,\n assoc, iso.hom_inv_id_assoc, iso.hom_inv_id_app],\n refl,\nend\n\nlemma has_shift_of_fully_faithful_map_μ_iso_hom_app (a b : A) (X : C) :\n F.map (((@shift_monoidal_functor C A _ _\n (has_shift_of_fully_faithful F s hs)).μ_iso (discrete.mk a) (discrete.mk b)).hom.app X) =\n (hs b).hom.app ((s a).obj X) ≫ (shift_functor D b).map ((hs a).hom.app X) ≫\n (shift_functor_add D a b).inv.app (F.obj X) ≫ (hs (a + b)).inv.app X :=\nbegin\n dsimp [shift_monoidal_functor],\n erw [assoc, assoc, assoc, id_comp, comp_id, id_comp, functor.image_preimage],\nend\n\nlemma has_shift_of_fully_faithful_map_μ_iso_inv_app (a b : A) (X : C) :\n F.map (((@shift_monoidal_functor C A _ _\n (has_shift_of_fully_faithful F s hs)).μ_iso (discrete.mk a) (discrete.mk b)).inv.app X) =\n (hs (a + b)).hom.app X ≫\n (shift_functor_add D a b).hom.app (F.obj X) ≫\n (shift_functor D b).map ((hs a).inv.app X) ≫\n (hs b).inv.app ((s a).obj X) :=\nbegin\n erw [← cancel_mono (F.map (((@shift_monoidal_functor C A _ _\n (has_shift_of_fully_faithful F s hs)).μ_iso (discrete.mk a) (discrete.mk b)).hom.app X)),\n ← F.map_comp, iso.inv_hom_id_app, F.map_id, assoc, assoc, assoc,\n has_shift_of_fully_faithful_map_μ_iso_hom_app, iso.inv_hom_id_app_assoc,\n ← functor.map_comp_assoc, iso.inv_hom_id_app, functor.map_id, id_comp,\n iso.hom_inv_id_app_assoc, iso.hom_inv_id_app],\n refl,\nend\n\ndef has_comm_shift_of_fully_faithful :\n @functor.has_comm_shift _ _ _ _ F A _ (has_shift_of_fully_faithful F s hs) _ :=\n{ iso := hs,\n iso_add := λ a b, begin\n ext X,\n dsimp only [functor.comm_shift.add, compatibility.comm_shift.comp,\n iso.trans, iso.symm, nat_trans.comp_app, iso_whisker_right,\n whiskering_right, functor.map_iso, whisker_right, functor.associator,\n iso_whisker_left, whiskering_left, whisker_left],\n erw [id_comp, id_comp, id_comp, has_shift_of_fully_faithful_map_μ_iso_inv_app,\n assoc, assoc, assoc, iso.inv_hom_id_app_assoc, ← functor.map_comp_assoc,\n iso.inv_hom_id_app, functor.map_id, id_comp,\n iso.symm_hom, monoidal_functor.μ_iso_hom, μ_inv_hom_app, comp_id],\n end,\n iso_zero := begin\n ext X,\n dsimp only [functor.comm_shift.unit, compatibility.comm_shift.unit, iso.trans,\n iso_whisker_right, whiskering_right, functor.left_unitor, nat_trans.comp_app,\n functor.right_unitor, iso.symm, iso_whisker_left, whiskering_left,\n functor.map_iso, whisker_right, whisker_left],\n erw [id_comp, id_comp, has_shift_of_fully_faithful_map_ε_iso_inv_app],\n simp only [iso.app_hom, iso.symm_hom, monoidal_functor.ε_iso_hom, assoc, ε_inv_hom_app],\n erw comp_id,\n end, }\n\nend\n\nend shift\n\nend category_theory\n\nsection\n\nopen category_theory\n\nvariables {C : Type*} [category C]\n\nclass set.is_stable_by_shift (S : set C) (A : Type*) [add_monoid A] [has_shift C A] : Prop :=\n(condition [] : ∀ (a : A) (X : C) (hX : X ∈ S), X⟦a⟧ ∈ S)\n\nend\n\nnamespace category_theory\n\nnamespace shift\n\nsection\n\nvariables {C A : Type*} [category C] [add_monoid A] [has_shift C A]\n (S : set C) [S.is_stable_by_shift A]\n\ninstance has_shift_full_subcategory :\n has_shift (full_subcategory S) A :=\nhas_shift_of_fully_faithful (full_subcategory_inclusion S)\n (λ a, full_subcategory.lift _ (full_subcategory_inclusion S ⋙ shift_functor C a)\n (λ X, set.is_stable_by_shift.condition a X.1 X.2))\n (λ a, full_subcategory.lift_comp_inclusion _ _ _)\n\ninstance has_comm_shift_full_subcategory_inclusion :\n (full_subcategory_inclusion S).has_comm_shift A :=\nhas_comm_shift_of_fully_faithful _ _ _\n\nend\n\nend shift\n\nnamespace functor\n\nnamespace has_comm_shift\n\n@[simps]\ndef of_iso {C D : Type*} [category C] [category D]\n {F G : C ⥤ D} (e : F ≅ G) (A : Type*) [add_monoid A] [has_shift C A] [has_shift D A]\n [F.has_comm_shift A] : G.has_comm_shift A :=\n{ iso := λ a, iso_whisker_left _ e.symm ≪≫ comm_shift_iso F a ≪≫\n iso_whisker_right e _,\n iso_zero := begin\n ext X,\n simp only [iso.trans_hom, iso_whisker_left_hom, iso.symm_hom, iso_whisker_right_hom,\n nat_trans.comp_app, whisker_left_app, whisker_right_app, comm_shift.unit_hom_app,\n iso.symm_inv, monoidal_functor.ε_iso_hom, comm_shift_iso_zero, assoc,\n ← nat_trans.naturality_assoc, ← nat_trans.naturality],\n dsimp,\n simp only [iso.inv_hom_id_app_assoc],\n end,\n iso_add := λ a b, begin\n ext X,\n simp only [iso.trans_hom, iso_whisker_left_hom, iso.symm_hom, iso_whisker_right_hom,\n nat_trans.comp_app, whisker_left_app, whisker_right_app, comm_shift.add_hom_app,\n map_comp, iso.symm_inv, monoidal_functor.μ_iso_hom, assoc, μ_naturality,\n comm_shift_iso_add],\n erw nat_trans.naturality_assoc,\n rw [← functor.map_comp_assoc, iso.hom_inv_id_app, functor.map_id, id_comp],\n refl,\n end, }\n\nend has_comm_shift\n\nend functor\n\nnamespace nat_trans\n\nvariables {C D : Type*} [category C] [category D] {F G : C ⥤ D} (τ : F ⟶ G) (e : F ≅ G)\n (A : Type*) [add_monoid A] [has_shift C A] [has_shift D A] [F.has_comm_shift A]\n [G.has_comm_shift A]\n\nclass respects_comm_shift : Prop :=\n(comm [] : ∀ (a : A), (F.comm_shift_iso a).hom ≫ whisker_right τ _ =\n whisker_left _ τ ≫ (G.comm_shift_iso a).hom)\n\nvariable {A}\n\nnamespace respects_comm_shift\n\n@[reassoc]\nlemma comm_app (a : A) (X : C) [τ.respects_comm_shift A] :\n (F.comm_shift_iso a).hom.app X ≫ (τ.app X)⟦a⟧' =\n τ.app (X⟦a⟧) ≫ (G.comm_shift_iso a).hom.app X :=\ncongr_app (respects_comm_shift.comm τ a) X\n\nlemma app_shift (a : A) (X : C) [τ.respects_comm_shift A] :\n τ.app (X⟦a⟧) = (F.comm_shift_iso a).hom.app X ≫\n (τ.app X)⟦a⟧' ≫ (G.comm_shift_iso a).inv.app X :=\nby erw [comm_app_assoc, iso.hom_inv_id_app, comp_id]\n\nlemma of_iso {C D : Type*} [category C] [category D]\n {F G : C ⥤ D} (e : F ≅ G) (A : Type*) [add_monoid A] [has_shift C A] [has_shift D A]\n [F.has_comm_shift A] :\n @respects_comm_shift _ _ _ _ _ _ e.hom A _ _ _ _ (functor.has_comm_shift.of_iso e A) :=\nbegin\n letI := functor.has_comm_shift.of_iso e A,\n refine ⟨λ a, _⟩,\n conv_rhs { dsimp [functor.comm_shift_iso, functor.has_comm_shift.iso], },\n ext X,\n simpa only [comp_app, whisker_left_app, iso.hom_inv_id_app_assoc],\nend\n\ninstance nat_iso_inv [e.hom.respects_comm_shift A] : e.inv.respects_comm_shift A :=\n⟨λ a, begin\n ext X,\n simp only [comp_app, whisker_right_app, whisker_left_app,\n ← cancel_mono ((shift_functor D a).map (e.hom.app X)), assoc,\n respects_comm_shift.comm_app e.hom a X, e.inv_hom_id_app_assoc,\n ← functor.map_comp, e.inv_hom_id_app, functor.map_id],\n apply comp_id,\nend⟩\n\nlemma of_iso_hom : e.hom.respects_comm_shift A ↔ e.inv.respects_comm_shift A :=\nbegin\n split,\n { introI,\n apply_instance, },\n { intro h,\n haveI : e.symm.hom.respects_comm_shift A := h,\n change e.symm.inv.respects_comm_shift A,\n apply_instance, },\nend\n\ninstance of_comp {H : C ⥤ D} (τ' : G ⟶ H) [H.has_comm_shift A] [τ.respects_comm_shift A]\n [τ'.respects_comm_shift A] : (τ ≫ τ').respects_comm_shift A :=\n⟨λ a, begin\n ext X,\n simp only [whisker_right_comp, comp_app, whisker_right_app, whisker_left_comp, assoc,\n whisker_left_app, comm_app_assoc, comm_app],\nend⟩\n\ninstance associator {C₁ C₂ C₃ C₄ : Type*} [category C₁] [category C₂] [category C₃] [category C₄]\n [has_shift C₁ A] [has_shift C₂ A] [has_shift C₃ A] [has_shift C₄ A]\n (F₁ : C₁ ⥤ C₂) (F₂ : C₂ ⥤ C₃) (F₃ : C₃ ⥤ C₄)\n [F₁.has_comm_shift A] [F₂.has_comm_shift A][F₃.has_comm_shift A] :\n (functor.associator F₁ F₂ F₃).hom.respects_comm_shift A :=\n⟨λ a, begin\n ext X,\n simp only [comp_app, functor.has_comm_shift.comp_hom_app, functor.map_comp, assoc,\n whisker_right_app, functor.associator_hom_app, functor.map_id, whisker_left_app,\n functor.comp_map],\n dsimp,\n simp only [comp_id, id_comp],\nend⟩\n\ninstance whisker_left {C₁ C₂ C₃ : Type*} [category C₁] [category C₂] [category C₃]\n [has_shift C₁ A] [has_shift C₂ A] [has_shift C₃ A]\n (F : C₁ ⥤ C₂) {G G' : C₂ ⥤ C₃} [F.has_comm_shift A] [G.has_comm_shift A]\n [G'.has_comm_shift A] (τ : G ⟶ G') [τ.respects_comm_shift A] :\n (whisker_left F τ).respects_comm_shift A :=\n⟨λ a, begin\n ext X,\n simp only [comp_app, functor.has_comm_shift.comp_hom_app, whisker_right_app, whisker_left_app,\n assoc, whisker_left_twice, comm_app],\n apply nat_trans.naturality_assoc,\nend⟩\n\ninstance whisker_right {C₁ C₂ C₃ : Type*} [category C₁] [category C₂] [category C₃]\n [has_shift C₁ A] [has_shift C₂ A] [has_shift C₃ A]\n {F F' : C₁ ⥤ C₂} [F.has_comm_shift A] [F'.has_comm_shift A]\n (G : C₂ ⥤ C₃) [G.has_comm_shift A]\n (τ : F ⟶ F') [τ.respects_comm_shift A] :\n (whisker_right τ G).respects_comm_shift A :=\n⟨λ a, begin\n ext X,\n simp only [whisker_right_twice, comp_app, functor.has_comm_shift.comp_hom_app,\n whisker_right_app, functor.comp_map, assoc, whisker_left_app, ← G.map_comp_assoc,\n ← comm_app τ a X],\n erw [G.map_comp, assoc, ← nat_trans.naturality],\n refl,\nend⟩\n\ninstance id : respects_comm_shift (𝟙 F) A :=\n⟨λ a, by simp only [whisker_right_id', comp_id, whisker_left_id', id_comp]⟩\n\nend respects_comm_shift\n\nend nat_trans\n\nnamespace functor\n\nnamespace has_comm_shift\n\nsection\n\nvariables {C D E : Type*} [category C] [category D] [category E]\n {F : C ⥤ D} {G : D ⥤ E} {H : C ⥤ E} (e : F ⋙ G ≅ H)\n {A : Type*} [add_monoid A]\n [has_shift C A] [has_shift D A] [has_shift E A]\n [G.has_comm_shift A] [H.has_comm_shift A]\n [full G] [faithful G]\n\ninclude e\n\ndef of_fully_faithful.iso (a : A) :\n shift_functor C a ⋙ F ≅ F ⋙ shift_functor D a :=\nnat_iso_of_comp_fully_faithful G\n (functor.associator _ _ _ ≪≫ iso_whisker_left _ e ≪≫\n H.comm_shift_iso a ≪≫ iso_whisker_right e.symm _ ≪≫\n functor.associator _ _ _ ≪≫ iso_whisker_left _ (G.comm_shift_iso a).symm ≪≫\n (functor.associator _ _ _).symm)\n\n@[simp]\nlemma of_fully_faithful.map_iso_hom_app (a : A) (X : C) :\n G.map ((of_fully_faithful.iso e a).hom.app X) =\n e.hom.app ((shift_functor C a).obj X) ≫ (H.comm_shift_iso a).hom.app X ≫\n (shift_functor E a).map (e.inv.app X) ≫ (G.comm_shift_iso a).inv.app (F.obj X) :=\nbegin\n dsimp [of_fully_faithful.iso],\n simp only [category.comp_id, category.id_comp, image_preimage],\nend\n\n@[simp]\nlemma of_fully_faithful.map_iso_inv_app (a : A) (X : C) :\n G.map ((of_fully_faithful.iso e a).inv.app X) =\n (G.comm_shift_iso a).hom.app (F.obj X) ≫ (shift_functor E a).map (e.hom.app X) ≫\n (H.comm_shift_iso a).inv.app X ≫ e.inv.app ((shift_functor C a).obj X) :=\nbegin\n dsimp [of_fully_faithful.iso],\n simp only [category.id_comp, category.comp_id, category.assoc, image_preimage],\nend\n\nvariable (A)\n\n@[simps]\ndef of_fully_faithful : F.has_comm_shift A :=\n{ iso := of_fully_faithful.iso e,\n iso_zero := begin\n ext X,\n apply G.map_injective,\n simp only [of_fully_faithful.map_iso_hom_app, comm_shift.unit_hom_app,\n iso.symm_hom, iso.symm_inv, monoidal_functor.ε_iso_hom, map_comp,\n comm_shift_iso_zero, comm_shift.unit_inv_app, assoc],\n erw nat_trans.naturality_assoc,\n simp only [id_map, ε_hom_inv_app_assoc],\n erw nat_trans.naturality_assoc,\n simp only [comp_map, iso.hom_inv_id_app_assoc],\n end,\n iso_add := λ a b, begin\n ext X,\n apply G.map_injective,\n simp only [of_fully_faithful.map_iso_hom_app, comm_shift.add_hom_app, iso.symm_hom,\n iso.symm_inv, monoidal_functor.μ_iso_hom, map_comp, assoc, comm_shift_iso_add,\n comm_shift.add_inv_app],\n erw [← nat_trans.naturality_assoc, ← nat_trans.naturality_assoc, ← nat_trans.naturality_assoc],\n dsimp,\n simp only [μ_hom_inv_app_assoc, of_fully_faithful.map_iso_hom_app, map_comp, assoc],\n nth_rewrite 2 ← functor.map_comp_assoc,\n rw [iso.inv_hom_id_app, functor.map_id, id_comp],\n end, }\n\ninclude A\n\nlemma of_fully_faithful_iso_hom_respects_comm_shift :\n by { haveI := of_fully_faithful e A, exact e.hom.respects_comm_shift A } :=\nbegin\n constructor,\n intro a,\n ext X,\n simp only [nat_trans.comp_app, comp_hom_app, whisker_right_app, assoc, whisker_left_app],\n conv_lhs { congr, dsimp [functor.comm_shift_iso], },\n simp only [of_fully_faithful.map_iso_hom_app, assoc, iso.inv_hom_id_app_assoc,\n nat_iso.cancel_nat_iso_hom_left, ← functor.map_comp, iso.inv_hom_id_app, functor.map_id],\n apply comp_id,\nend\n\nend\n\nsection\n\ninstance of_full_subcategory_lift {C D : Type*} [category C] [category D]\n (F : C ⥤ D) (S : set D) (A : Type*) [add_monoid A]\n [has_shift C A] [has_shift D A] [S.is_stable_by_shift A]\n [F.has_comm_shift A] (hS : ∀ (X : C), S (F.obj X)) :\n (full_subcategory.lift S F hS).has_comm_shift A :=\nof_fully_faithful (full_subcategory.lift_comp_inclusion S F hS) A\n\ninstance of_full_subcategory_lift_iso_hom_respects_comm_shift\n {C D : Type*} [category C] [category D]\n (F : C ⥤ D) (S : set D) (A : Type*) [add_monoid A]\n [has_shift C A] [has_shift D A] [S.is_stable_by_shift A]\n [F.has_comm_shift A] (hS : ∀ (X : C), S (F.obj X)) :\n (full_subcategory.lift_comp_inclusion S F hS).hom.respects_comm_shift A :=\nof_fully_faithful_iso_hom_respects_comm_shift _ _\n\n\nend\n\nend has_comm_shift\n\nend functor\n\nend category_theory\n", "meta": {"author": "joelriou", "repo": "homotopical_algebra", "sha": "697f49d6744b09c5ef463cfd3e35932bdf2c78a3", "save_path": "github-repos/lean/joelriou-homotopical_algebra", "path": "github-repos/lean/joelriou-homotopical_algebra/homotopical_algebra-697f49d6744b09c5ef463cfd3e35932bdf2c78a3/src/for_mathlib/category_theory/functor/shift.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4921881357207955, "lm_q2_score": 0.02556521587213409, "lm_q1q2_score": 0.012582895939405368}} {"text": "import pseudo_normed_group.CLC\n/-!\n\n# V-hat((M_c)^n)^{T⁻¹}\n\nThis file defines a fundamental construction defined just above Definition 9.3\nin `analytic.pdf`: the subspac of V-hat(M_c^n) where the two actions of T⁻¹ coincide.\n\n## Main definition\n\nHere `M` is a profinitely filtered pseudo-normed group with `T⁻¹` scaling things by `r'`,\n`V` is a seminormed group with `T⁻¹` scaling norms by `r`, `c` is a real (a filtration coefficient)\nand `n` is a natural.\n\n- `CLCFPTinv r V r' c n M`: the seminormed group defined as the subgroup of `V-hat(M_c^n)` where\n the two actions of `T⁻¹` (one coming from the action on M, the other coming from the\n action on V) coincide.\n\n-/\nopen_locale classical nnreal\nnoncomputable theory\nlocal attribute [instance] type_pow\n\nnamespace category_theory\n\ntheorem comm_sq₂ {C} [category C] {A₁ A₂ A₃ B₁ B₂ B₃ : C}\n {f₁ : A₁ ⟶ B₁} {f₂ : A₂ ⟶ B₂} {f₃ : A₃ ⟶ B₃}\n {a : A₁ ⟶ A₂} {a' : A₂ ⟶ A₃} {b : B₁ ⟶ B₂} {b' : B₂ ⟶ B₃}\n (h₁ : a ≫ f₂ = f₁ ≫ b) (h₂ : a' ≫ f₃ = f₂ ≫ b') : (a ≫ a') ≫ f₃ = f₁ ≫ b ≫ b' :=\nby rw [category.assoc, h₂, ← category.assoc, h₁, ← category.assoc]\n\nend category_theory\n\nopen SemiNormedGroup opposite Profinite pseudo_normed_group category_theory breen_deligne\nopen profinitely_filtered_pseudo_normed_group category_theory.limits\nopen normed_add_group_hom\n\nnamespace SemiNormedGroup\n\ndef equalizer {V W : SemiNormedGroup} (f g : V ⟶ W) := of (f.equalizer g)\n\nnamespace equalizer\n\ndef ι {V W : SemiNormedGroup} (f g : V ⟶ W) :\n equalizer f g ⟶ V :=\nnormed_add_group_hom.equalizer.ι _ _\n\n@[reassoc] lemma condition {V W : SemiNormedGroup} (f g : V ⟶ W) :\n ι f g ≫ f = ι f g ≫ g :=\nnormed_add_group_hom.equalizer.comp_ι_eq _ _\n\nlemma ι_range {V W : SemiNormedGroup} (f g : V ⟶ W) :\n (ι f g).range = (f - g).ker :=\nbegin\n ext, rw [normed_add_group_hom.mem_range, normed_add_group_hom.mem_ker],\n split,\n { rintro ⟨x, rfl⟩, rw [normed_add_group_hom.sub_apply], exact x.2 },\n { intro h, refine ⟨⟨x, h⟩, rfl⟩, }\nend\n\nlemma ι_range' {V W : SemiNormedGroup} (f g : V ⟶ W) :\n (ι f g).range = (g - f).ker :=\nbegin\n rw ι_range, ext x,\n simp only [normed_add_group_hom.mem_ker, normed_add_group_hom.sub_apply, sub_eq_zero],\n rw eq_comm\nend\n\ndef map {V₁ V₂ W₁ W₂ : SemiNormedGroup} {f₁ f₂ g₁ g₂} (φ : V₁ ⟶ V₂) (ψ : W₁ ⟶ W₂)\n (hf : φ ≫ f₂ = f₁ ≫ ψ) (hg : φ ≫ g₂ = g₁ ≫ ψ) :\n equalizer f₁ g₁ ⟶ equalizer f₂ g₂ :=\nnormed_add_group_hom.equalizer.map _ _ hf.symm hg.symm\n\nlemma map_comp_ι {V₁ V₂ W₁ W₂ : SemiNormedGroup} {f₁ f₂ g₁ g₂} (φ : V₁ ⟶ V₂) (ψ : W₁ ⟶ W₂)\n (hf : φ ≫ f₂ = f₁ ≫ ψ) (hg : φ ≫ g₂ = g₁ ≫ ψ) :\n map φ ψ hf hg ≫ ι _ _ = ι _ _ ≫ φ :=\nrfl\n\ntheorem map_congr\n {V₁ V₂ W₁ W₂ : SemiNormedGroup} {f₁ f₂ g₁ g₂} {φ : V₁ ⟶ V₂} {ψ : W₁ ⟶ W₂}\n {V₁' V₂' W₁' W₂' : SemiNormedGroup} {f₁' f₂' g₁' g₂'} {φ' : V₁' ⟶ V₂'} {ψ' : W₁' ⟶ W₂'}\n {hf : φ ≫ f₂ = f₁ ≫ ψ} {hg : φ ≫ g₂ = g₁ ≫ ψ}\n {hf' : φ' ≫ f₂' = f₁' ≫ ψ'} {hg' : φ' ≫ g₂' = g₁' ≫ ψ'}\n (Hφ : arrow.mk φ = arrow.mk φ') (Hψ : arrow.mk ψ = arrow.mk ψ')\n (Hf₁ : arrow.mk f₁ = arrow.mk f₁') (Hf₂ : arrow.mk f₂ = arrow.mk f₂')\n (Hg₁ : arrow.mk g₁ = arrow.mk g₁') (Hg₂ : arrow.mk g₂ = arrow.mk g₂') :\n arrow.mk (map φ ψ hf hg) = arrow.mk (map φ' ψ' hf' hg') :=\nby { cases Hφ, cases Hψ, cases Hf₁, cases Hf₂, cases Hg₁, cases Hg₂, refl }\n\nlemma map_comp_map {V₁ V₂ V₃ W₁ W₂ W₃ : SemiNormedGroup} {f₁ f₂ f₃ g₁ g₂ g₃}\n {φ : V₁ ⟶ V₂} {ψ : W₁ ⟶ W₂} {φ' : V₂ ⟶ V₃} {ψ' : W₂ ⟶ W₃}\n (hf : φ ≫ f₂ = f₁ ≫ ψ) (hg : φ ≫ g₂ = g₁ ≫ ψ)\n (hf' : φ' ≫ f₃ = f₂ ≫ ψ') (hg' : φ' ≫ g₃ = g₂ ≫ ψ') :\n map φ ψ hf hg ≫ map φ' ψ' hf' hg' =\n map (φ ≫ φ') (ψ ≫ ψ') (comm_sq₂ hf hf') (comm_sq₂ hg hg') :=\nby { ext, refl }\n\nlemma map_id {J} [category J] {V W : SemiNormedGroup} (f g : V ⟶ W) :\n map (𝟙 V) (𝟙 W) (show 𝟙 V ≫ f = f ≫ 𝟙 W, by simp) (show 𝟙 V ≫ g = g ≫ 𝟙 W, by simp) = 𝟙 _ :=\nby { ext, refl }\n\nlemma norm_map_le {V₁ V₂ W₁ W₂ : SemiNormedGroup} {f₁ f₂ g₁ g₂} {φ : V₁ ⟶ V₂} {ψ : W₁ ⟶ W₂}\n (hf : φ ≫ f₂ = f₁ ≫ ψ) (hg : φ ≫ g₂ = g₁ ≫ ψ) (C : ℝ) (hφ : ∥ι f₁ g₁ ≫ φ∥ ≤ C) :\n ∥map φ ψ hf hg∥ ≤ C :=\nnormed_add_group_hom.equalizer.norm_map_le _ _ C hφ\n\n@[simps obj map]\nprotected def F {J} [category J] {V W : J ⥤ SemiNormedGroup} (f g : V ⟶ W) : J ⥤ SemiNormedGroup :=\n{ obj := λ X, of ((f.app X).equalizer (g.app X)),\n map := λ X Y φ, equalizer.map (V.map φ) (W.map φ) (f.naturality _) (g.naturality _),\n map_id' := λ X, by simp only [category_theory.functor.map_id]; exact normed_add_group_hom.equalizer.map_id,\n map_comp' := λ X Y Z φ ψ, begin\n simp only [functor.map_comp],\n exact (map_comp_map _ _ _ _).symm\n end }\n\n@[simps]\ndef map_nat {J} [category J] {V₁ V₂ W₁ W₂ : J ⥤ SemiNormedGroup}\n {f₁ f₂ g₁ g₂} (φ : V₁ ⟶ V₂) (ψ : W₁ ⟶ W₂)\n (hf : φ ≫ f₂ = f₁ ≫ ψ) (hg : φ ≫ g₂ = g₁ ≫ ψ) :\n equalizer.F f₁ g₁ ⟶ equalizer.F f₂ g₂ :=\n{ app := λ X, equalizer.map (φ.app X) (ψ.app X)\n (by rw [← nat_trans.comp_app, ← nat_trans.comp_app, hf])\n (by rw [← nat_trans.comp_app, ← nat_trans.comp_app, hg]),\n naturality' := λ X Y α, by simp only [equalizer.F_map, map_comp_map, nat_trans.naturality] }\n\nlemma map_nat_comp_map_nat {J} [category J] {V₁ V₂ V₃ W₁ W₂ W₃ : J ⥤ SemiNormedGroup}\n {f₁ f₂ f₃ g₁ g₂ g₃} {φ : V₁ ⟶ V₂} {ψ : W₁ ⟶ W₂} {φ' : V₂ ⟶ V₃} {ψ' : W₂ ⟶ W₃}\n (hf : φ ≫ f₂ = f₁ ≫ ψ) (hg : φ ≫ g₂ = g₁ ≫ ψ)\n (hf' : φ' ≫ f₃ = f₂ ≫ ψ') (hg' : φ' ≫ g₃ = g₂ ≫ ψ') :\n map_nat φ ψ hf hg ≫ map_nat φ' ψ' hf' hg' =\n map_nat (φ ≫ φ') (ψ ≫ ψ') (comm_sq₂ hf hf') (comm_sq₂ hg hg') :=\nby { ext, refl }\n\nlemma map_nat_id {J} [category J] {V W : J ⥤ SemiNormedGroup} (f g : V ⟶ W) :\n map_nat (𝟙 V) (𝟙 W) (show 𝟙 V ≫ f = f ≫ 𝟙 W, by simp) (show 𝟙 V ≫ g = g ≫ 𝟙 W, by simp) = 𝟙 _ :=\nby { ext, refl }\n\nend equalizer\nend SemiNormedGroup\n\nuniverse variable u\nvariables (r : ℝ≥0) (V : SemiNormedGroup) [normed_with_aut r V] [fact (0 < r)]\nvariables (r' : ℝ≥0) [fact (0 < r')] [fact (r' ≤ 1)]\nvariables (M M₁ M₂ M₃ : ProFiltPseuNormGrpWithTinv.{u} r')\nvariables (c c₁ c₂ c₃ c₄ c₅ c₆ c₇ c₈ : ℝ≥0) (l m n : ℕ)\nvariables (f : M₁ ⟶ M₂) (g : M₂ ⟶ M₃)\n\ndef CLCTinv (r : ℝ≥0) (V : SemiNormedGroup)\n [normed_with_aut r V] [fact (0 < r)] {A B : Profiniteᵒᵖ} (f g : A ⟶ B) :\n SemiNormedGroup :=\nSemiNormedGroup.of $ normed_add_group_hom.equalizer\n ((CLC V).map f)\n ((CLC V).map g ≫ (CLC.T_inv r V).app B)\n\nnamespace CLCTinv\n\ndef ι (r : ℝ≥0) (V : SemiNormedGroup)\n [normed_with_aut r V] [fact (0 < r)] {A B : Profiniteᵒᵖ} (f g : A ⟶ B) :\n CLCTinv r V f g ⟶ (CLC V).obj A :=\nSemiNormedGroup.equalizer.ι _ _\n\nlemma ι_range (r : ℝ≥0) (V : SemiNormedGroup)\n [normed_with_aut r V] [fact (0 < r)] {A B : Profiniteᵒᵖ} (f g : A ⟶ B) :\n (ι r V f g).range =\n normed_add_group_hom.ker ((CLC V).map f - ((CLC V).map g ≫ (CLC.T_inv r V).app B)) :=\nSemiNormedGroup.equalizer.ι_range _ _\n\nlemma ι_range' (r : ℝ≥0) (V : SemiNormedGroup)\n [normed_with_aut r V] [fact (0 < r)] {A B : Profiniteᵒᵖ} (f g : A ⟶ B) :\n (ι r V f g).range =\n normed_add_group_hom.ker (((CLC V).map g ≫ (CLC.T_inv r V).app B) - (CLC V).map f) :=\nSemiNormedGroup.equalizer.ι_range' _ _\n\ndef map {A₁ B₁ A₂ B₂ : Profiniteᵒᵖ} (f₁ g₁ : A₁ ⟶ B₁) (f₂ g₂ : A₂ ⟶ B₂)\n (ϕ : A₁ ⟶ A₂) (ψ : B₁ ⟶ B₂) (h₁ : ϕ ≫ f₂ = f₁ ≫ ψ) (h₂ : ϕ ≫ g₂ = g₁ ≫ ψ) :\n CLCTinv r V f₁ g₁ ⟶ CLCTinv r V f₂ g₂ :=\nSemiNormedGroup.equalizer.map ((CLC V).map ϕ) ((CLC V).map ψ)\n (by rw [← functor.map_comp, ← functor.map_comp, h₁]) $\nby rw [← category.assoc, ← functor.map_comp, h₂, functor.map_comp,\n category.assoc, (CLC.T_inv _ _).naturality, category.assoc]\n\nlemma map_comp_ι {A₁ B₁ A₂ B₂ : Profiniteᵒᵖ} (f₁ g₁ : A₁ ⟶ B₁) (f₂ g₂ : A₂ ⟶ B₂)\n (ϕ : A₁ ⟶ A₂) (ψ : B₁ ⟶ B₂) (h₁ : ϕ ≫ f₂ = f₁ ≫ ψ) (h₂ : ϕ ≫ g₂ = g₁ ≫ ψ) :\n map r V f₁ g₁ f₂ g₂ ϕ ψ h₁ h₂ ≫ ι r V _ _ = ι _ _ _ _ ≫ (CLC V).map ϕ :=\nnormed_add_group_hom.equalizer.ι_comp_map _ _\n\nlemma map_norm_noninc {A₁ B₁ A₂ B₂ : Profiniteᵒᵖ} (f₁ g₁ : A₁ ⟶ B₁) (f₂ g₂ : A₂ ⟶ B₂)\n (ϕ : A₁ ⟶ A₂) (ψ : B₁ ⟶ B₂) (h₁ h₂) :\n (CLCTinv.map r V f₁ g₁ f₂ g₂ ϕ ψ h₁ h₂).norm_noninc :=\nequalizer.map_norm_noninc _ _ $ CLC.map_norm_noninc _ _\n\nlemma norm_map_le {A₁ B₁ A₂ B₂ : Profiniteᵒᵖ} (f₁ g₁ : A₁ ⟶ B₁) (f₂ g₂ : A₂ ⟶ B₂)\n (ϕ : A₁ ⟶ A₂) (ψ : B₁ ⟶ B₂) (h₁ h₂) (C : ℝ≥0)\n (H : ∥SemiNormedGroup.equalizer.ι\n ((CLC V).map f₁)\n ((CLC V).map g₁ ≫ (CLC.T_inv r V).app B₁) ≫\n (CLC V).map ϕ∥ ≤ C) :\n ∥CLCTinv.map r V f₁ g₁ f₂ g₂ ϕ ψ h₁ h₂∥ ≤ C :=\nSemiNormedGroup.equalizer.norm_map_le _ _ C H\n\n@[simp] lemma map_id {A B : Profiniteᵒᵖ} (f g : A ⟶ B) :\n map r V f g f g (𝟙 A) (𝟙 B) rfl rfl = 𝟙 _ :=\nbegin\n simp only [map, SemiNormedGroup.equalizer.map, category_theory.functor.map_id],\n exact equalizer.map_id,\nend\n\nlemma map_comp {A₁ A₂ A₃ B₁ B₂ B₃ : Profiniteᵒᵖ}\n {f₁ g₁ : A₁ ⟶ B₁} {f₂ g₂ : A₂ ⟶ B₂} {f₃ g₃ : A₃ ⟶ B₃}\n (ϕ₁ : A₁ ⟶ A₂) (ϕ₂ : A₂ ⟶ A₃) (ψ₁ : B₁ ⟶ B₂) (ψ₂ : B₂ ⟶ B₃)\n (h1 h2 h3 h4 h5 h6) :\n CLCTinv.map r V f₁ g₁ f₃ g₃ (ϕ₁ ≫ ϕ₂) (ψ₁ ≫ ψ₂) h1 h2 =\n CLCTinv.map r V f₁ g₁ f₂ g₂ ϕ₁ ψ₁ h3 h4 ≫\n CLCTinv.map r V f₂ g₂ f₃ g₃ ϕ₂ ψ₂ h5 h6 :=\nbegin\n simp only [map, SemiNormedGroup.equalizer.map, category_theory.functor.map_comp],\n exact (equalizer.map_comp_map _ _ _ _).symm,\nend\n\nlemma map_comp_map {A₁ A₂ A₃ B₁ B₂ B₃ : Profiniteᵒᵖ}\n {f₁ g₁ : A₁ ⟶ B₁} {f₂ g₂ : A₂ ⟶ B₂} {f₃ g₃ : A₃ ⟶ B₃}\n (ϕ₁ : A₁ ⟶ A₂) (ϕ₂ : A₂ ⟶ A₃) (ψ₁ : B₁ ⟶ B₂) (ψ₂ : B₂ ⟶ B₃)\n (h₁ h₂ h₃ h₄) :\n CLCTinv.map r V f₁ g₁ f₂ g₂ ϕ₁ ψ₁ h₁ h₂ ≫\n CLCTinv.map r V f₂ g₂ f₃ g₃ ϕ₂ ψ₂ h₃ h₄ =\n CLCTinv.map r V f₁ g₁ f₃ g₃ (ϕ₁ ≫ ϕ₂) (ψ₁ ≫ ψ₂) (comm_sq₂ h₁ h₃) (comm_sq₂ h₂ h₄) :=\n(map_comp _ _ _ _ _ _ _ _ _ _ _ _).symm\n\n@[simps]\ndef map_iso {A₁ B₁ A₂ B₂ : Profiniteᵒᵖ} (f₁ g₁ : A₁ ⟶ B₁) (f₂ g₂ : A₂ ⟶ B₂)\n (ϕ : A₁ ≅ A₂) (ψ : B₁ ≅ B₂) (h₁ : ϕ.hom ≫ f₂ = f₁ ≫ ψ.hom) (h₂ : ϕ.hom ≫ g₂ = g₁ ≫ ψ.hom) :\n CLCTinv r V f₁ g₁ ≅ CLCTinv r V f₂ g₂ :=\n{ hom := map r V f₁ g₁ f₂ g₂ ϕ.hom ψ.hom h₁ h₂,\n inv := map r V f₂ g₂ f₁ g₁ ϕ.inv ψ.inv\n (by rw [iso.inv_comp_eq, ← category.assoc, iso.eq_comp_inv, h₁])\n (by rw [iso.inv_comp_eq, ← category.assoc, iso.eq_comp_inv, h₂]),\n hom_inv_id' := by { simp only [map_comp_map, iso.hom_inv_id], apply map_id },\n inv_hom_id' := by { simp only [map_comp_map, iso.inv_hom_id], apply map_id } }\n\nlemma map_iso_isometry {A₁ B₁ A₂ B₂ : Profiniteᵒᵖ} (f₁ g₁ : A₁ ⟶ B₁) (f₂ g₂ : A₂ ⟶ B₂)\n (ϕ : A₁ ≅ A₂) (ψ : B₁ ≅ B₂) (h₁ : ϕ.hom ≫ f₂ = f₁ ≫ ψ.hom) (h₂ : ϕ.hom ≫ g₂ = g₁ ≫ ψ.hom) :\n isometry (map_iso r V f₁ g₁ f₂ g₂ ϕ ψ h₁ h₂).hom :=\nbegin\n apply SemiNormedGroup.iso_isometry_of_norm_noninc;\n apply map_norm_noninc\nend\n\n@[simps]\nprotected def F {J} [category J] (r : ℝ≥0) (V : SemiNormedGroup)\n [normed_with_aut r V] [fact (0 < r)] {A B : J ⥤ Profiniteᵒᵖ} (f g : A ⟶ B) :\n J ⥤ SemiNormedGroup :=\n{ obj := λ X, CLCTinv r V (f.app X) (g.app X),\n map := λ X Y φ, map _ _ _ _ _ _ (A.map φ) (B.map φ) (f.naturality _) (g.naturality _),\n map_id' := λ X, by simp only [category_theory.functor.map_id]; apply map_id,\n map_comp' := λ X Y Z φ ψ, by simp only [functor.map_comp]; apply map_comp }\n\ntheorem F_def {J} [category J] (r : ℝ≥0) (V : SemiNormedGroup)\n [normed_with_aut r V] [fact (0 < r)] {A B : J ⥤ Profiniteᵒᵖ} (f g : A ⟶ B) :\n CLCTinv.F r V f g = SemiNormedGroup.equalizer.F\n (whisker_right f (CLC V))\n (whisker_right g (CLC V) ≫ whisker_left B (CLC.T_inv r V)) := rfl\n\n@[simps]\ndef map_nat {J} [category J] {A₁ B₁ A₂ B₂ : J ⥤ Profiniteᵒᵖ} (f₁ g₁ : A₁ ⟶ B₁) (f₂ g₂ : A₂ ⟶ B₂)\n (ϕ : A₁ ⟶ A₂) (ψ : B₁ ⟶ B₂) (h₁ : ϕ ≫ f₂ = f₁ ≫ ψ) (h₂ : ϕ ≫ g₂ = g₁ ≫ ψ) :\n CLCTinv.F r V f₁ g₁ ⟶ CLCTinv.F r V f₂ g₂ :=\n{ app := λ X, map _ _ _ _ _ _ (ϕ.app X) (ψ.app X)\n (by rw [← nat_trans.comp_app, h₁, nat_trans.comp_app])\n (by rw [← nat_trans.comp_app, h₂, nat_trans.comp_app]),\n naturality' := λ X Y α, by simp only [CLCTinv.F_map, map_comp_map, ϕ.naturality, ψ.naturality] }\n\ntheorem map_nat_def {J} [category J] {A₁ B₁ A₂ B₂ : J ⥤ Profiniteᵒᵖ} (f₁ g₁ : A₁ ⟶ B₁) (f₂ g₂ : A₂ ⟶ B₂)\n (ϕ : A₁ ⟶ A₂) (ψ : B₁ ⟶ B₂) (h₁ : ϕ ≫ f₂ = f₁ ≫ ψ) (h₂ : ϕ ≫ g₂ = g₁ ≫ ψ) :\n map_nat r V f₁ g₁ f₂ g₂ ϕ ψ h₁ h₂ = begin\n dsimp only [F_def],\n refine SemiNormedGroup.equalizer.map_nat\n (whisker_right ϕ (CLC V))\n (whisker_right ψ (CLC V))\n (by rw [← whisker_right_comp, ← whisker_right_comp, h₁])\n (comm_sq₂ _ _).symm,\n { exact whisker_right ψ _ },\n { rw [← whisker_right_comp, ← whisker_right_comp, h₂] },\n ext x : 2,\n simp only [nat_trans.comp_app, whisker_left_app, whisker_right_app,\n (CLC.T_inv _ _).naturality],\n end := rfl\n.\n\n-- @[simps]\ndef map_nat_iso {J} [category J] {A₁ B₁ A₂ B₂ : J ⥤ Profiniteᵒᵖ} (f₁ g₁ : A₁ ⟶ B₁) (f₂ g₂ : A₂ ⟶ B₂)\n (ϕ : A₁ ≅ A₂) (ψ : B₁ ≅ B₂) (h₁ : ϕ.hom ≫ f₂ = f₁ ≫ ψ.hom) (h₂ : ϕ.hom ≫ g₂ = g₁ ≫ ψ.hom) :\n CLCTinv.F r V f₁ g₁ ≅ CLCTinv.F r V f₂ g₂ :=\n{ hom := map_nat r V f₁ g₁ f₂ g₂ ϕ.hom ψ.hom h₁ h₂,\n inv := map_nat r V f₂ g₂ f₁ g₁ ϕ.inv ψ.inv\n (by rw [iso.inv_comp_eq, ← category.assoc, iso.eq_comp_inv, h₁])\n (by rw [iso.inv_comp_eq, ← category.assoc, iso.eq_comp_inv, h₂]),\n hom_inv_id' :=\n begin\n simp only [map_nat_def, _root_.id, SemiNormedGroup.equalizer.map_nat_comp_map_nat,\n ← whisker_right_comp, iso.hom_inv_id, whisker_right_id', SemiNormedGroup.equalizer.map_nat_id],\n refl\n end,\n inv_hom_id' :=\n begin\n simp only [map_nat_def, _root_.id, SemiNormedGroup.equalizer.map_nat_comp_map_nat,\n ← whisker_right_comp, iso.inv_hom_id, whisker_right_id', SemiNormedGroup.equalizer.map_nat_id],\n refl\n end, }\n\nend CLCTinv\n\nlemma aux (r' c c₂ : ℝ≥0) [r1 : fact (r' ≤ 1)] [h : fact (c₂ ≤ r' * c)] : fact (c₂ ≤ c) :=\n⟨h.1.trans $ (mul_le_mul' r1.1 le_rfl).trans (by simp)⟩\n\n@[simps obj]\ndef CLCFPTinv₂ (r : ℝ≥0) (V : SemiNormedGroup)\n (r' : ℝ≥0) [fact (0 < r)] [fact (0 < r')] [r1 : fact (r' ≤ 1)] [normed_with_aut r V]\n (c c₂ : ℝ≥0) [fact (c₂ ≤ r' * c)] (n : ℕ) : (ProFiltPseuNormGrpWithTinv r')ᵒᵖ ⥤ SemiNormedGroup :=\nby haveI : fact (c₂ ≤ c) := aux r' c c₂; exact\nCLCTinv.F r V\n (nat_trans.op (FiltrationPow.Tinv r' c₂ c n))\n (nat_trans.op (FiltrationPow.cast_le r' c₂ c n))\n\ntheorem CLCFPTinv₂_def (r : ℝ≥0) (V : SemiNormedGroup)\n (r' : ℝ≥0) [fact (0 < r)] [fact (0 < r')] [r1 : fact (r' ≤ 1)] [normed_with_aut r V]\n (c c₂ : ℝ≥0) [fact (c₂ ≤ r' * c)] (n : ℕ) :\n CLCFPTinv₂ r V r' c c₂ n = SemiNormedGroup.equalizer.F\n (CLCFP.Tinv V r' c c₂ n)\n (@CLCFP.res V r' c c₂ n (aux r' c c₂) ≫ CLCFP.T_inv r V r' c₂ n) := rfl\n\ninstance CLCFPTinv₂.separated_space [fact (c₂ ≤ r' * c₁)] (M) :\n separated_space ((CLCFPTinv₂ r V r' c₁ c₂ n).obj M) :=\nbegin\n rw separated_iff_t2,\n refine @subtype.t2_space _ _ (id _) (id _),\n rw ← separated_iff_t2,\n apply uniform_space.completion.separated_space\nend\n\ninstance CLCFPTinv₂.complete_space [fact (c₂ ≤ r' * c₁)] (M) :\n complete_space ((CLCFPTinv₂ r V r' c₁ c₂ n).obj M) :=\nbegin\n refine @is_closed.complete_space_coe _ (id _) (id _) _ _,\n { apply uniform_space.completion.complete_space },\n { refine is_closed_eq _ continuous_const,\n apply normed_add_group_hom.continuous }\nend\n\n/-- The functor that sends `M` and `c` to `V-hat((filtration M c)^n)^{T⁻¹}`,\ndefined by taking `T⁻¹`-invariants for two different actions by `T⁻¹`:\n\n* The first comes from the action of `T⁻¹` on `M`.\n* The second comes from the action of `T⁻¹` on `V`.\n\nWe take the equalizer of those two actions.\n\nSee the lines just above Definition 9.3 of [Analytic]. -/\ndef CLCFPTinv (r : ℝ≥0) (V : SemiNormedGroup) (r' : ℝ≥0)\n (c : ℝ≥0) (n : ℕ) [normed_with_aut r V] [fact (0 < r)] [fact (0 < r')] [fact (r' ≤ 1)] :\n (ProFiltPseuNormGrpWithTinv r')ᵒᵖ ⥤ SemiNormedGroup :=\nCLCFPTinv₂ r V r' c (r' * c) n\n\nnamespace CLCFPTinv₂\n\nlemma map_norm_noninc [fact (c₂ ≤ r' * c)] [fact (c₂ ≤ c)]\n {M₁ M₂} (f : M₁ ⟶ M₂) : ((CLCFPTinv₂ r V r' c c₂ n).map f).norm_noninc :=\nCLCTinv.map_norm_noninc _ _ _ _ _ _ _ _ _ _\n\ndef res [fact (c₂ ≤ r' * c₁)] [fact (c₂ ≤ c₁)] [fact (c₄ ≤ r' * c₃)] [fact (c₄ ≤ c₃)]\n [fact (c₃ ≤ c₁)] [fact (c₄ ≤ c₂)] : CLCFPTinv₂ r V r' c₁ c₂ n ⟶ CLCFPTinv₂ r V r' c₃ c₄ n :=\nCLCTinv.map_nat r V _ _ _ _\n (nat_trans.op (FiltrationPow.cast_le _ c₃ c₁ n))\n (nat_trans.op (FiltrationPow.cast_le _ c₄ c₂ n)) rfl rfl\n\n@[simp] lemma res_refl [fact (c₂ ≤ r' * c₁)] [fact (c₂ ≤ c₁)] : res r V r' c₁ c₂ c₁ c₂ n = 𝟙 _ :=\nby { simp only [res, FiltrationPow.cast_le_refl, nat_trans.op_id], ext x : 2, apply CLCTinv.map_id }\n\nlemma res_comp_res\n [fact (c₂ ≤ r' * c₁)] [fact (c₂ ≤ c₁)]\n [fact (c₄ ≤ r' * c₃)] [fact (c₄ ≤ c₃)]\n [fact (c₆ ≤ r' * c₅)] [fact (c₆ ≤ c₅)]\n [fact (c₃ ≤ c₁)] [fact (c₄ ≤ c₂)]\n [fact (c₅ ≤ c₃)] [fact (c₆ ≤ c₄)]\n [fact (c₅ ≤ c₁)] [fact (c₆ ≤ c₂)] :\n res r V r' c₁ c₂ c₃ c₄ n ≫ res r V r' c₃ c₄ c₅ c₆ n = res r V r' c₁ c₂ c₅ c₆ n :=\nbegin\n ext x : 2, simp only [res, nat_trans.comp_app],\n exact (CLCTinv.map_comp _ _ _ _ _ _ _ _ _ _ _ _).symm\nend\n\nlemma res_norm_noninc {_ : fact (c₂ ≤ r' * c₁)} {_ : fact (c₂ ≤ c₁)}\n {_ : fact (c₄ ≤ r' * c₃)} {_ : fact (c₄ ≤ c₃)} {_ : fact (c₃ ≤ c₁)} {_ : fact (c₄ ≤ c₂)} (M) :\n ((res r V r' c₁ c₂ c₃ c₄ n).app M).norm_noninc :=\nCLCTinv.map_norm_noninc _ _ _ _ _ _ _ _ _ _\n\nlemma norm_res_le [fact (c₂ ≤ r' * c₁)] [fact (c₂ ≤ c₁)] [fact (c₄ ≤ r' * c₃)] [fact (c₄ ≤ c₃)]\n [fact (c₃ ≤ c₁)] [fact (c₄ ≤ c₂)] (h₂₃ : c₂ = c₃) (M) :\n ∥(res r V r' c₁ c₂ c₃ c₄ n).app M∥ ≤ r :=\nbegin\n apply CLCTinv.norm_map_le,\n rw [← category.comp_id ((CLC V).map ((nat_trans.op (FiltrationPow.cast_le r' c₃ c₁ n)).app M))],\n have := nat_trans.congr_app (CLC.T r V).inv_hom_id ((FiltrationPow r' c₃ n).op.obj M),\n dsimp only [nat_trans.id_app] at this,\n rw [← this, CLC.T_inv_eq, nat_trans.comp_app, ← category.assoc ((CLC V).map _)],\n unfreezingI { subst c₃ },\n rw [← SemiNormedGroup.equalizer.condition_assoc, ← category.assoc],\n refine normed_add_group_hom.norm_comp_le_of_le' 1 r r (mul_one ↑r).symm _ _,\n { apply CLC.norm_T_le },\n { apply norm_noninc.norm_noninc_iff_norm_le_one.1,\n exact (CLC.map_norm_noninc V _).comp equalizer.ι_norm_noninc }\nend\n\nend CLCFPTinv₂\n\nnamespace CLCFPTinv\n\nlemma map_norm_noninc {M₁ M₂} (f : M₁ ⟶ M₂) : ((CLCFPTinv r V r' c n).map f).norm_noninc :=\nCLCFPTinv₂.map_norm_noninc _ _ _ _ _ _ _\n\ndef res [fact (c₂ ≤ c₁)] : CLCFPTinv r V r' c₁ n ⟶ CLCFPTinv r V r' c₂ n :=\nCLCFPTinv₂.res r V r' c₁ _ c₂ _ n\n\n@[simp] lemma res_refl : res r V r' c₁ c₁ n = 𝟙 _ :=\nCLCFPTinv₂.res_refl _ _ _ _ _ _\n\nlemma res_comp_res [fact (c₃ ≤ c₁)] [fact (c₅ ≤ c₃)] [fact (c₅ ≤ c₁)] :\n res r V r' c₁ c₃ n ≫ res r V r' c₃ c₅ n = res r V r' c₁ c₅ n :=\nCLCFPTinv₂.res_comp_res _ _ _ _ _ _ _ _ _ _\n\nlemma res_norm_noninc {_ : fact (c₂ ≤ c₁)} (M) :\n ((res r V r' c₁ c₂ n).app M).norm_noninc :=\nCLCFPTinv₂.res_norm_noninc r V r' _ _ _ _ _ _\n\nlemma norm_res_le [fact (c₂ ≤ c₁)] [fact (c₂ ≤ r' * c₁)] (M) :\n ∥(res r V r' c₁ c₂ n).app M∥ ≤ r :=\nbegin\n rw ← res_comp_res r V r' c₁ (r' * c₁) c₂,\n refine norm_comp_le_of_le' _ _ _ (one_mul ↑r).symm _ (CLCFPTinv₂.norm_res_le r V r' _ _ _ _ n rfl M),\n apply norm_noninc.norm_noninc_iff_norm_le_one.1,\n exact CLCTinv.map_norm_noninc r V _ _ _ _ _ _ _ _\nend\n\nlemma norm_res_le_pow (N : ℕ) [fact (c₂ ≤ c₁)] [h : fact (c₂ ≤ r' ^ N * c₁)] (M) :\n ∥(res r V r' c₁ c₂ n).app M∥ ≤ (r ^ N) :=\nbegin\n unfreezingI { induction N with N ih generalizing c₁ c₂ },\n { rw pow_zero,\n apply norm_noninc.norm_noninc_iff_norm_le_one.1,\n exact CLCTinv.map_norm_noninc r V _ _ _ _ _ _ _ _ },\n haveI : fact (c₂ ≤ r' ^ N * c₁) := nnreal.fact_le_pow_mul_of_le_pow_succ_mul _ _ _,\n rw [pow_succ, mul_assoc] at h, resetI,\n rw [← res_comp_res r V r' c₁ (r' ^ N * c₁) c₂],\n exact norm_comp_le_of_le' _ _ _ (pow_succ _ _) (norm_res_le r V r' _ _ n M) (ih _ _)\nend\n\nend CLCFPTinv\n\nnamespace breen_deligne\n\nopen CLCFPTinv\n\nvariables (M) {l m n}\n\nnamespace universal_map\n\nvariables (ϕ ψ : universal_map m n)\n\ndef eval_CLCFPTinv₂\n [fact (c₂ ≤ r' * c₁)] [fact (c₄ ≤ r' * c₃)]\n [ϕ.suitable c₃ c₁] [ϕ.suitable c₄ c₂] :\n CLCFPTinv₂ r V r' c₁ c₂ n ⟶ CLCFPTinv₂ r V r' c₃ c₄ m :=\nbegin\n dsimp only [CLCFPTinv₂_def],\n refine SemiNormedGroup.equalizer.map_nat (ϕ.eval_CLCFP _ _ _ _) (ϕ.eval_CLCFP _ _ _ _)\n (Tinv_comp_eval_CLCFP V r' c₁ c₂ c₃ c₄ ϕ).symm _,\n haveI : fact (c₂ ≤ c₁) := aux r' _ _, haveI : fact (c₄ ≤ c₃) := aux r' _ _,\n have h₁ := res_comp_eval_CLCFP V r' c₁ c₂ c₃ c₄ ϕ,\n have h₂ := T_inv_comp_eval_CLCFP r V r' c₂ c₄ ϕ,\n have := comm_sq₂ h₁ h₂,\n exact this.symm\nend\n\n@[simp] lemma eval_CLCFPTinv₂_zero\n [fact (c₂ ≤ r' * c₁)] [fact (c₄ ≤ r' * c₃)] :\n (0 : universal_map m n).eval_CLCFPTinv₂ r V r' c₁ c₂ c₃ c₄ = 0 :=\nby { simp only [eval_CLCFPTinv₂, eval_CLCFP_zero], ext, refl }\n\n@[simp] lemma eval_CLCFPTinv₂_add\n [fact (c₂ ≤ r' * c₁)] [fact (c₄ ≤ r' * c₃)]\n [ϕ.suitable c₃ c₁] [ϕ.suitable c₄ c₂]\n [ψ.suitable c₃ c₁] [ψ.suitable c₄ c₂] :\n (ϕ + ψ : universal_map m n).eval_CLCFPTinv₂ r V r' c₁ c₂ c₃ c₄ =\n ϕ.eval_CLCFPTinv₂ r V r' c₁ c₂ c₃ c₄ + ψ.eval_CLCFPTinv₂ r V r' c₁ c₂ c₃ c₄ :=\nby { simp only [eval_CLCFPTinv₂, eval_CLCFP_add], ext, refl }\n\n@[simp] lemma eval_CLCFPTinv₂_sub\n [fact (c₂ ≤ r' * c₁)] [fact (c₄ ≤ r' * c₃)]\n [ϕ.suitable c₃ c₁] [ϕ.suitable c₄ c₂]\n [ψ.suitable c₃ c₁] [ψ.suitable c₄ c₂] :\n (ϕ - ψ : universal_map m n).eval_CLCFPTinv₂ r V r' c₁ c₂ c₃ c₄ =\n ϕ.eval_CLCFPTinv₂ r V r' c₁ c₂ c₃ c₄ - ψ.eval_CLCFPTinv₂ r V r' c₁ c₂ c₃ c₄ :=\nby { simp only [eval_CLCFPTinv₂, eval_CLCFP_sub], ext, refl }\n\nlemma eval_CLCFPTinv₂_comp {l m n : FreeMat} (f : l ⟶ m) (g : m ⟶ n)\n [fact (c₂ ≤ r' * c₁)] [fact (c₄ ≤ r' * c₃)] [fact (c₆ ≤ r' * c₅)]\n [f.suitable c₅ c₃] [f.suitable c₆ c₄] [g.suitable c₃ c₁] [g.suitable c₄ c₂] :\n @eval_CLCFPTinv₂ r V _ _ r' _ _ c₁ c₂ c₅ c₆ _ _ (f ≫ g)\n _ _ (suitable.comp c₃) (suitable.comp c₄) =\n g.eval_CLCFPTinv₂ r V r' c₁ c₂ c₃ c₄ ≫ f.eval_CLCFPTinv₂ r V r' c₃ c₄ c₅ c₆ :=\nbegin\n dsimp only [eval_CLCFPTinv₂, CLCFPTinv₂_def], delta id,\n simp only [SemiNormedGroup.equalizer.map_nat_comp_map_nat],\n generalize_proofs h1 h2 h3 h4 h5 h6 h7 h8,\n revert h5 h6 h7 h8, resetI,\n have H1 : eval_CLCFP V r' c₁ c₅ (f ≫ g) = eval_CLCFP V r' c₁ c₃ g ≫ eval_CLCFP V r' c₃ c₅ f :=\n eval_CLCFP_comp V r' c₁ c₃ c₅ g f,\n have H2 : eval_CLCFP V r' c₂ c₆ (f ≫ g) = eval_CLCFP V r' c₂ c₄ g ≫ eval_CLCFP V r' c₄ c₆ f :=\n eval_CLCFP_comp V r' c₂ c₄ c₆ g f,\n rw [H1, H2],\n intros, refl,\nend\n\nlemma res_comp_eval_CLCFPTinv₂\n [fact (c₂ ≤ r' * c₁)] [fact (c₄ ≤ r' * c₃)]\n [fact (c₆ ≤ r' * c₅)] [fact (c₈ ≤ r' * c₇)]\n [fact (c₂ ≤ c₁)] [fact (c₃ ≤ c₁)] [fact (c₄ ≤ c₂)] [fact (c₄ ≤ c₃)]\n [fact (c₆ ≤ c₅)] [fact (c₇ ≤ c₅)] [fact (c₈ ≤ c₆)] [fact (c₈ ≤ c₇)]\n [ϕ.suitable c₅ c₁] [ϕ.suitable c₆ c₂]\n [ϕ.suitable c₇ c₃] [ϕ.suitable c₈ c₄] :\n CLCFPTinv₂.res r V r' c₁ c₂ c₃ c₄ n ≫ ϕ.eval_CLCFPTinv₂ r V r' c₃ c₄ c₇ c₈ =\n ϕ.eval_CLCFPTinv₂ r V r' c₁ c₂ c₅ c₆ ≫ CLCFPTinv₂.res r V r' c₅ c₆ c₇ c₈ m :=\nbegin\n dsimp only [CLCFPTinv₂.res, eval_CLCFPTinv₂, CLCFPTinv₂_def, CLCTinv.map_nat_def], delta id,\n simp only [SemiNormedGroup.equalizer.map_nat_comp_map_nat],\n congr' 1; { simp only [← CLCFP.res_def], apply res_comp_eval_CLCFP },\nend\n\nlemma norm_eval_CLCFPTinv₂_le [fact (c₂ ≤ r' * c₁)] [fact (c₄ ≤ r' * c₃)]\n [ϕ.suitable c₃ c₁] [ϕ.suitable c₄ c₂] (N : ℕ) (h : ϕ.bound_by N) (M) :\n ∥(ϕ.eval_CLCFPTinv₂ r V r' c₁ c₂ c₃ c₄).app M∥ ≤ N :=\nbegin\n apply SemiNormedGroup.equalizer.norm_map_le,\n refine normed_add_group_hom.norm_comp_le_of_le' _ _ _ (mul_one _).symm _ _,\n { apply norm_eval_CLCFP_le, exact h },\n { apply norm_noninc.norm_noninc_iff_norm_le_one.1,\n exact equalizer.ι_norm_noninc }\nend\n\ndef eval_CLCFPTinv [ϕ.suitable c₂ c₁] :\n CLCFPTinv r V r' c₁ n ⟶ CLCFPTinv r V r' c₂ m :=\nϕ.eval_CLCFPTinv₂ r V r' c₁ _ c₂ _\n\nlemma eval_CLCFPTinv_def [ϕ.suitable c₂ c₁] :\n ϕ.eval_CLCFPTinv r V r' c₁ c₂ = ϕ.eval_CLCFPTinv₂ r V r' c₁ _ c₂ _ := rfl\n\n@[simp] lemma eval_CLCFPTinv_zero :\n (0 : universal_map m n).eval_CLCFPTinv r V r' c₁ c₂ = 0 :=\nby apply eval_CLCFPTinv₂_zero\n\n@[simp] lemma eval_CLCFPTinv_add [ϕ.suitable c₂ c₁] [ψ.suitable c₂ c₁] :\n (ϕ + ψ : universal_map m n).eval_CLCFPTinv r V r' c₁ c₂ =\n ϕ.eval_CLCFPTinv r V r' c₁ c₂ + ψ.eval_CLCFPTinv r V r' c₁ c₂ :=\neval_CLCFPTinv₂_add _ _ _ _ _ _ _ _ _\n\n@[simp] lemma eval_CLCFPTinv_sub [ϕ.suitable c₂ c₁] [ψ.suitable c₂ c₁] :\n (ϕ - ψ : universal_map m n).eval_CLCFPTinv r V r' c₁ c₂ =\n ϕ.eval_CLCFPTinv r V r' c₁ c₂ - ψ.eval_CLCFPTinv r V r' c₁ c₂ :=\neval_CLCFPTinv₂_sub _ _ _ _ _ _ _ _ _\n\nlemma eval_CLCFPTinv_comp {l m n : FreeMat} (f : l ⟶ m) (g : m ⟶ n)\n [hg : g.suitable c₂ c₁] [hf : f.suitable c₃ c₂] :\n @eval_CLCFPTinv r V _ _ r' _ _ c₁ c₃ _ _ (f ≫ g) (suitable.comp c₂) =\n g.eval_CLCFPTinv r V r' c₁ c₂ ≫ f.eval_CLCFPTinv r V r' c₂ c₃ :=\nby apply eval_CLCFPTinv₂_comp\n\nlemma res_comp_eval_CLCFPTinv\n [fact (c₂ ≤ c₁)] [ϕ.suitable c₄ c₂] [ϕ.suitable c₃ c₁] [fact (c₄ ≤ c₃)] :\n res r V r' c₁ c₂ n ≫ ϕ.eval_CLCFPTinv r V r' c₂ c₄ =\n ϕ.eval_CLCFPTinv r V r' c₁ c₃ ≫ res r V r' c₃ c₄ m :=\nby apply res_comp_eval_CLCFPTinv₂\n\nlemma res_comp_eval_CLCFPTinv_absorb\n [fact (c₂ ≤ c₁)] [hϕ : ϕ.suitable c₃ c₂] :\n res r V r' c₁ c₂ n ≫ ϕ.eval_CLCFPTinv r V r' c₂ c₃ =\n @eval_CLCFPTinv r V _ _ r' _ _ c₁ c₃ _ _ ϕ (hϕ.le _ _ _ _ le_rfl (fact.out _)) :=\nby rw [@res_comp_eval_CLCFPTinv r V _ _ r' _ _ c₁ c₂ c₃ c₃ _ _ ϕ\n (_root_.id _) (_root_.id _) (_root_.id _) (_root_.id _),\n res_refl, category.comp_id]\n\nlemma eval_CLCFPTinv_comp_res_absorb\n {_: fact (c₃ ≤ c₂)} [hϕ : ϕ.suitable c₂ c₁] :\n ϕ.eval_CLCFPTinv r V r' c₁ c₂ ≫ res r V r' c₂ c₃ m =\n @eval_CLCFPTinv r V _ _ r' _ _ c₁ c₃ _ _ ϕ (hϕ.le _ _ _ _ (fact.out _) le_rfl) :=\nby rw [← @res_comp_eval_CLCFPTinv r V _ _ r' _ _ c₁ c₁ c₂ c₃ _ _ ϕ\n (_root_.id _) (_root_.id _) (_root_.id _) (_root_.id _),\n res_refl, category.id_comp]\n\nlemma norm_eval_CLCFPTinv_le [normed_with_aut r V] [fact (0 < r)] [ϕ.suitable c₂ c₁]\n (N : ℕ) (h : ϕ.bound_by N) (M) :\n ∥(ϕ.eval_CLCFPTinv r V r' c₁ c₂).app M∥ ≤ N :=\nnorm_eval_CLCFPTinv₂_le r V r' _ _ _ _ _ N h M\n\nlemma eval_CLCFPTinv_norm_noninc [normed_with_aut r V] [fact (0 < r)]\n [h : ϕ.very_suitable r r' c₂ c₁] (M) :\n ((ϕ.eval_CLCFPTinv r V r' c₁ c₂).app M).norm_noninc :=\nbegin\n apply norm_noninc.norm_noninc_iff_norm_le_one.2,\n have h' := h,\n unfreezingI { rcases h with ⟨N, k, c', hN, hϕ, hr, H⟩ },\n haveI : fact (c' ≤ c₁) := ⟨H.trans $ fact.out _⟩,\n have aux := res_comp_eval_CLCFPTinv r V r' c₁ c' c₂ c₂ ϕ,\n rw [res_refl, category.comp_id] at aux,\n rw ← aux,\n refine le_trans _ hr,\n rw mul_comm,\n apply normed_add_group_hom.norm_comp_le_of_le,\n { apply_mod_cast norm_eval_CLCFPTinv_le, exact hN },\n { haveI : fact (c' ≤ r' ^ k * c₁) := ⟨H⟩,\n rw nnreal.coe_pow,\n apply norm_res_le_pow },\nend\n\nend universal_map\n\nend breen_deligne\n\nattribute [irreducible] CLCFPTinv₂ CLCFPTinv₂.res\n breen_deligne.universal_map.eval_CLCFPTinv₂\n", "meta": {"author": "leanprover-community", "repo": "lean-liquid", "sha": "92f188bd17f34dbfefc92a83069577f708851aec", "save_path": "github-repos/lean/leanprover-community-lean-liquid", "path": "github-repos/lean/leanprover-community-lean-liquid/lean-liquid-92f188bd17f34dbfefc92a83069577f708851aec/src/pseudo_normed_group/Tinv.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4263215925474903, "lm_q2_score": 0.02931223149332675, "lm_q1q2_score": 0.01249643721135576}} {"text": "import Cdclt.Euf\n\nopen proof\nopen proof.sort proof.term\nopen rules eufRules\n\ndef U := atom 50\ndef a₁ := const 100 U\ndef a₂ := const 101 U\ndef a₃ := const 102 U\ndef a₄ := const 103 U\ndef b₁ := const 104 U\ndef b₂ := const 105 U\ndef f₁ := const 106 (mkArrowN [U, U, U])\ndef f₂ := const 107 (mkArrowN [U, U, U])\ndef f₃ := const 108 (mkArrowN [U, U])\n\ntheorem binCong :\n thHolds (mkEq a₁ a₂) → thHolds (mkEq b₁ b₂) → (thHolds (mkEq (mkApp (mkApp f₁ a₁) b₁) (mkApp (mkApp f₁ a₂) b₂))) :=\nλ s0 : thHolds (mkEq a₁ a₂) =>\nλ s1 : thHolds (mkEq b₁ b₂) =>\nhave s2 : thHolds (mkEq f₁ f₁) from refl\nshow (thHolds (mkEq (mkApp (mkApp f₁ a₁) b₁) (mkApp (mkApp f₁ a₂) b₂))) from cong (cong s2 s0) s1\n\n/-\n(SCOPE |:conclusion| (not (and (= a b) (or (not p3) (not (= (f a) (f b)))) p1 (or (not p1) (and p2 p3))))\n (EQ_RESOLVE |:conclusion| false\n (CHAIN_RESOLUTION |:conclusion| (not (= (f a) (f b)))\n (ASSUME |:conclusion| (or (not p3) (not (= (f a) (f b)))) |:args| ((or (not p3) (not (= (f a) (f b))))))\n (AND_ELIM |:conclusion| p3\n (CHAIN_RESOLUTION |:conclusion| (and p2 p3)\n (ASSUME |:conclusion| (or (not p1) (and p2 p3)) |:args| ((or (not p1) (and p2 p3))))\n (ASSUME |:conclusion| p1 |:args| (p1)) |:args| (false p1))\n |:args| (1))\n |:args| (false p3))\n (TRANS |:conclusion| (= (not (= (f a) (f b))) false)\n (CONG |:conclusion| (= (not (= (f a) (f b))) (not (= (f b) (f b))))\n (CONG |:conclusion| (= (= (f a) (f b)) (= (f b) (f b)))\n (CONG |:conclusion| (= (f a) (f b))\n (ASSUME |:conclusion| (= a b) |:args| ((= a b))) |:args| (23 f))\n (REFL |:conclusion| (= (f b) (f b)) |:args| ((f b))) |:args| (6))\n |:args| (17))\n (TRANS |:conclusion| (= (not (= (f b) (f b))) false)\n (CONG |:conclusion| (= (not (= (f b) (f b))) (not true))\n (THEORY_REWRITE |:conclusion| (= (= (f b) (f b)) true) |:args| ((= (= (f b) (f b)) true) 2 5))\n |:args| (17))\n (THEORY_REWRITE |:conclusion| (= (not true) false) |:args| ((= (not true) false) 1 6)))))\n |:args| ((= a b) (or (not p3) (not (= (f a) (f b)))) p1 (or (not p1) (and p2 p3))))\n-/\n\ndef a := const 1000 U\ndef b := const 1001 U\ndef p₁ := const 1002 boolSort\ndef p₂ := const 1003 boolSort\ndef p₃ := const 1004 boolSort\ndef f := const 1005 (mkArrowN [U, U])\ndef fa := mkApp f a\ndef fb := mkApp f b\n\ndef eqab := mkEq a b\ndef eqfafb := mkEq fa fb\ndef eqfbfb := mkEq fb fb\ndef eqfbfbtop := mkEq eqfbfb top\ndef neqfbfb := mkNot eqfbfb\ndef eqneqfbfbbot := mkEq neqfbfb bot\ndef eqeqfafbeqfbfb := mkEq eqfafb eqfbfb\ndef eqneqfafbneqfbfb := mkEq (mkNot eqfafb) (mkNot eqfbfb)\ndef neqfafb := mkNot eqfafb\ndef eqneqfafbbot := mkEq neqfafb bot\ndef np₁ := mkNot p₁\ndef np₃ := mkNot p₃\ndef andp₂p₃ := mkAnd p₂ p₃\ndef ornp₁andp₂p₃ := mkOr np₁ andp₂p₃\ndef ornp₃neqfafb := mkOr np₃ neqfafb\n\ntheorem simpleCongRw :\n thHolds eqab → thHolds ornp₃neqfafb → thHolds p₁ → thHolds ornp₁andp₂p₃ → thHolds bot :=\nλ s0 : thHolds eqab =>\nλ s1 : thHolds ornp₃neqfafb =>\nλ s2 : thHolds p₁ =>\nλ s3 : thHolds ornp₁andp₂p₃ =>\n\nhave s4 : thHolds andp₂p₃ from thAssume (R1 (clOr s3) (clAssume s2) p₁)\nhave s5 : thHolds p₃ from andElim s4 1\nhave s6 : thHolds neqfafb from thAssume (R1 (clOr s1) (clAssume s5) p₃)\n\nhave s7 : thHolds eqfafb from cong refl s0\nlet s8_1 := @refl eqConst\nlet s8_2 := (cong s8_1 s7)\nhave s8 : thHolds eqeqfafbeqfbfb from cong s8_2 (@refl fb)\nhave s9 : thHolds eqneqfafbneqfbfb from cong (@refl notConst) s8\nhave s10 : thHolds (mkEq (mkNot top) bot) from thTrustValid\nhave s11 : thHolds eqfbfbtop from thTrustValid\nhave s12 : thHolds ((mkEq neqfbfb) (mkNot top)) from cong (@refl notConst) s11\nhave s13 : thHolds (mkEq neqfbfb bot) from trans s12 s10\nhave s14 : thHolds eqneqfafbbot from trans s9 s13\nshow thHolds bot from eqResolve s6 s14\n\n/-\n(SCOPE |:conclusion| (not (and (= a b) (and p1 true) (or (not p1) (and p2 p3)) (or (not p3) (not (= (f a) (f b))))))\n (CHAIN_RESOLUTION |:conclusion| false\n (REORDERING |:conclusion| (or (= (f a) (f b)) (not (= a b)))\n (IMPLIES_ELIM |:conclusion| (or (not (= a b)) (= (f a) (f b)))\n (SCOPE |:conclusion| (=> (= a b) (= (f a) (f b)))\n (CONG |:conclusion| (= (f a) (f b))\n (SYMM |:conclusion| (= a b)\n (SYMM |:conclusion| (= b a)\n (ASSUME |:conclusion| (= a b) |:args| ((= a b))))) |:args| (23 f))\n |:args| ((= a b))))\n |:args| ((or (= (f a) (f b)) (not (= a b)))))\n (CHAIN_RESOLUTION |:conclusion| (not (= (f a) (f b)))\n (ASSUME |:conclusion| (or (not p3) (not (= (f a) (f b)))) |:args| ((or (not p3) (not (= (f a) (f b))))))\n (CHAIN_RESOLUTION |:conclusion| p3\n (REORDERING |:conclusion| (or p3 (not (and p2 p3)))\n (CNF_AND_POS |:conclusion| (or (not (and p2 p3)) p3) |:args| ((and p2 p3) 1)) |:args| ((or p3 (not (and p2 p3)))))\n (CHAIN_RESOLUTION |:conclusion| (and p2 p3)\n (ASSUME |:conclusion| (or (not p1) (and p2 p3)) |:args| ((or (not p1) (and p2 p3))))\n (EQ_RESOLVE |:conclusion| p1\n (ASSUME |:conclusion| (and p1 true) |:args| ((and p1 true)))\n (THEORY_REWRITE |:conclusion| (= (and p1 true) p1) |:args| ((= (and p1 true) p1) 1 5)))\n |:args| (false p1))\n |:args| (false (and p2 p3)))\n |:args| (false p3))\n (ASSUME |:conclusion| (= a b) |:args| ((= a b))) |:args| (true (= (f a) (f b)) false (= a b)))\n |:args| ((= a b) (and p1 true) (or (not p1) (and p2 p3)) (or (not p3) (not (= (f a) (f b))))))\n-/\n\ndef andp₁t := mkAnd p₁ (val (value.bool true) boolSort)\n\ntheorem simpleCong :\n thHolds eqab → thHolds andp₁t → thHolds ornp₃neqfafb → thHolds p₁ → thHolds ornp₁andp₂p₃ → holds [] :=\n -- thHolds eqab → thHolds andp₁t → thHolds ornp₃neqfafb → thHolds p₁ → thHolds ornp₁andp₂p₃ → thHolds (mkOr (mkNot eqab) eqfafb) :=\nfun a0 : thHolds eqab =>\nfun a1 : thHolds andp₁t =>\nfun a2 : thHolds ornp₃neqfafb =>\nfun a3 : thHolds p₁ =>\nfun a4 : thHolds ornp₁andp₂p₃ =>\n\nhave s0 : holds [mkNot eqab, eqfafb] from clOr (scope (\n fun a0 : thHolds eqab =>\n have s0 : thHolds (mkEq b a) from symm a0\n have s1 : thHolds eqab from symm s0\n show thHolds eqfafb from cong (@refl f) s1\n ))\nhave s1 : holds [eqfafb, mkNot eqab] from reorder s0 [1,0]\n\nhave s2 : holds [andp₂p₃] from R1 (clOr a4) (clAssume a3) p₁\nhave s3 : holds ([(mkNot (mkAndN [p₂, p₃])), p₃]) from @cnfAndPos ([p₂, p₃]) 1\nhave s4 : holds [p₃, mkNot andp₂p₃] from reorder s3 [1,0]\n\nhave s5 : thHolds (mkEq andp₁t p₁) from thTrustValid\nhave s6 : thHolds p₁ from eqResolve a1 s5\nhave s7 : holds [andp₂p₃] from R1 (clOr a4) (clAssume s6) p₁\nhave s8 : holds [p₃] from R1 s4 s7 andp₂p₃\n\nhave s9 : holds [neqfafb] from R1 (clOr a2) s8 p₃\n\nshow holds [] from R1 (R0 s1 s9 eqfafb) (clOr a0) eqab\n", "meta": {"author": "CVC4", "repo": "signatures", "sha": "c64ffc4421cd37773c444a9ecb68f5075c47842a", "save_path": "github-repos/lean/CVC4-signatures", "path": "github-repos/lean/CVC4-signatures/signatures-c64ffc4421cd37773c444a9ecb68f5075c47842a/lean4/Cdclt/examples/euf.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46490157137338844, "lm_q2_score": 0.02675928328246172, "lm_q1q2_score": 0.012440432846842098}} {"text": "/-\nCopyright (c) 2019 Simon Hudon. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Simon Hudon\n-/\nimport control.traversable.derive\nimport control.traversable.lemmas\nimport data.dlist\nimport tactic.monotonicity.basic\n\nvariables {a b c p : Prop}\n\nnamespace tactic.interactive\n\nopen lean lean.parser interactive\nopen interactive.types\nopen tactic\n\nlocal postfix `?`:9001 := optional\nlocal postfix *:9001 := many\n\nmeta inductive mono_function (elab : bool := tt)\n | non_assoc : expr elab → list (expr elab) → list (expr elab) → mono_function\n | assoc : expr elab → option (expr elab) → option (expr elab) → mono_function\n | assoc_comm : expr elab → expr elab → mono_function\n\nmeta instance : decidable_eq mono_function :=\nby mk_dec_eq_instance\n\nmeta def mono_function.to_tactic_format : mono_function → tactic format\n | (mono_function.non_assoc fn xs ys) := do\n fn' ← pp fn,\n xs' ← mmap pp xs,\n ys' ← mmap pp ys,\n return format!\"{fn'} {xs'} _ {ys'}\"\n | (mono_function.assoc fn xs ys) := do\n fn' ← pp fn,\n xs' ← pp xs,\n ys' ← pp ys,\n return format!\"{fn'} {xs'} _ {ys'}\"\n | (mono_function.assoc_comm fn xs) := do\n fn' ← pp fn,\n xs' ← pp xs,\n return format!\"{fn'} _ {xs'}\"\n\nmeta instance has_to_tactic_format_mono_function : has_to_tactic_format mono_function :=\n{ to_tactic_format := mono_function.to_tactic_format }\n\n@[derive traversable]\nmeta structure ac_mono_ctx' (rel : Type) :=\n (to_rel : rel)\n (function : mono_function)\n (left right rel_def : expr)\n\n@[reducible]\nmeta def ac_mono_ctx := ac_mono_ctx' (option (expr → expr → expr))\n@[reducible]\nmeta def ac_mono_ctx_ne := ac_mono_ctx' (expr → expr → expr)\n\nmeta def ac_mono_ctx.to_tactic_format (ctx : ac_mono_ctx) : tactic format :=\ndo fn ← pp ctx.function,\n l ← pp ctx.left,\n r ← pp ctx.right,\n rel ← pp ctx.rel_def,\n return format!\"{{ function := {fn}\\n, left := {l}\\n, right := {r}\\n, rel_def := {rel} }\"\n\nmeta instance has_to_tactic_format_mono_ctx : has_to_tactic_format ac_mono_ctx :=\n{ to_tactic_format := ac_mono_ctx.to_tactic_format }\n\nmeta def as_goal (e : expr) (tac : tactic unit) : tactic unit :=\ndo gs ← get_goals,\n set_goals [e],\n tac,\n set_goals gs\n\nopen list (hiding map) functor dlist\n\nsection config\n\nparameter opt : mono_cfg\nparameter asms : list expr\n\nmeta def unify_with_instance (e : expr) : tactic unit :=\nas_goal e $\napply_instance\n<|>\napply_opt_param\n<|>\napply_auto_param\n<|>\ntactic.solve_by_elim { lemmas := some asms }\n<|>\nreflexivity\n<|>\napplyc ``id\n<|>\nreturn ()\n\nprivate meta def match_rule_head (p : expr)\n: list expr → expr → expr → tactic expr\n | vs e t :=\n(unify t p >> mmap' unify_with_instance vs >> instantiate_mvars e)\n<|>\ndo (expr.pi _ _ d b) ← return t | failed,\n v ← mk_meta_var d,\n match_rule_head (v::vs) (expr.app e v) (b.instantiate_var v)\n\nmeta def pi_head : expr → tactic expr\n| (expr.pi n _ t b) :=\ndo v ← mk_meta_var t,\n pi_head (b.instantiate_var v)\n| e := return e\n\nmeta def delete_expr (e : expr)\n: list expr → tactic (option (list expr))\n | [] := return none\n | (x :: xs) :=\n(compare opt e x >> return (some xs))\n<|>\n(map (cons x) <$> delete_expr xs)\n\nmeta def match_ac'\n: list expr → list expr → tactic (list expr × list expr × list expr)\n | es (x :: xs) := do\n es' ← delete_expr x es,\n match es' with\n | (some es') := do\n (c,l,r) ← match_ac' es' xs, return (x::c,l,r)\n | none := do\n (c,l,r) ← match_ac' es xs, return (c,l,x::r)\n end\n | es [] := do\nreturn ([],es,[])\n\nmeta def match_ac (l : list expr) (r : list expr)\n: tactic (list expr × list expr × list expr) :=\ndo (s',l',r') ← match_ac' l r,\n s' ← mmap instantiate_mvars s',\n l' ← mmap instantiate_mvars l',\n r' ← mmap instantiate_mvars r',\n return (s',l',r')\n\nmeta def match_prefix\n: list expr → list expr → tactic (list expr × list expr × list expr)\n| (x :: xs) (y :: ys) :=\n (do compare opt x y,\n prod.map ((::) x) id <$> match_prefix xs ys)\n<|> return ([],x :: xs,y :: ys)\n| xs ys := return ([],xs,ys)\n\n/--\n`(prefix,left,right,suffix) ← match_assoc unif l r` finds the\nlongest prefix and suffix common to `l` and `r` and\nreturns them along with the differences -/\nmeta def match_assoc (l : list expr) (r : list expr)\n: tactic (list expr × list expr × list expr × list expr) :=\ndo (pre,l₁,r₁) ← match_prefix l r,\n (suf,l₂,r₂) ← match_prefix (reverse l₁) (reverse r₁),\n return (pre,reverse l₂,reverse r₂,reverse suf)\n\nmeta def check_ac : expr → tactic (bool × bool × option (expr × expr × expr) × expr)\n | (expr.app (expr.app f x) y) :=\n do t ← infer_type x,\n a ← try_core $ to_expr ``(is_associative %%t %%f) >>= mk_instance,\n c ← try_core $ to_expr ``(is_commutative %%t %%f) >>= mk_instance,\n i ← try_core (do\n v ← mk_meta_var t,\n l_inst_p ← to_expr ``(is_left_id %%t %%f %%v),\n r_inst_p ← to_expr ``(is_right_id %%t %%f %%v),\n l_v ← mk_meta_var l_inst_p,\n r_v ← mk_meta_var r_inst_p ,\n l_id ← mk_mapp `is_left_id.left_id [some t,f,v,some l_v],\n mk_instance l_inst_p >>= unify l_v,\n r_id ← mk_mapp `is_right_id.right_id [none,f,v,some r_v],\n mk_instance r_inst_p >>= unify r_v,\n v' ← instantiate_mvars v,\n return (l_id,r_id,v')),\n return (a.is_some,c.is_some,i,f)\n | _ := return (ff,ff,none,expr.var 1)\n\nmeta def parse_assoc_chain' (f : expr) : expr → tactic (dlist expr)\n | e :=\n (do (expr.app (expr.app f' x) y) ← return e,\n is_def_eq f f',\n (++) <$> parse_assoc_chain' x <*> parse_assoc_chain' y)\n<|> return (singleton e)\n\nmeta def parse_assoc_chain (f : expr) : expr → tactic (list expr) :=\nmap dlist.to_list ∘ parse_assoc_chain' f\n\nmeta def fold_assoc (op : expr) :\n option (expr × expr × expr) → list expr → option (expr × list expr)\n| _ (x::xs) := some (foldl (expr.app ∘ expr.app op) x xs, [])\n| none [] := none\n| (some (l_id,r_id,x₀)) [] := some (x₀,[l_id,r_id])\n\nmeta def fold_assoc1 (op : expr) : list expr → option expr\n| (x::xs) := some $ foldl (expr.app ∘ expr.app op) x xs\n| [] := none\n\nmeta def same_function_aux\n: list expr → list expr → expr → expr → tactic (expr × list expr × list expr)\n | xs₀ xs₁ (expr.app f₀ a₀) (expr.app f₁ a₁) :=\n same_function_aux (a₀ :: xs₀) (a₁ :: xs₁) f₀ f₁\n | xs₀ xs₁ e₀ e₁ := is_def_eq e₀ e₁ >> return (e₀,xs₀,xs₁)\n\nmeta def same_function : expr → expr → tactic (expr × list expr × list expr) :=\nsame_function_aux [] []\n\nmeta def parse_ac_mono_function (l r : expr)\n: tactic (expr × expr × list expr × mono_function) :=\ndo (full_f,ls,rs) ← same_function l r,\n (a,c,i,f) ← check_ac l,\n if a\n then if c\n then do\n (s,ls,rs) ← monad.join (match_ac\n <$> parse_assoc_chain f l\n <*> parse_assoc_chain f r),\n (l',l_id) ← fold_assoc f i ls,\n (r',r_id) ← fold_assoc f i rs,\n s' ← fold_assoc1 f s,\n return (l',r',l_id ++ r_id,mono_function.assoc_comm f s')\n else do -- a ∧ ¬ c\n (pre,ls,rs,suff) ← monad.join (match_assoc\n <$> parse_assoc_chain f l\n <*> parse_assoc_chain f r),\n (l',l_id) ← fold_assoc f i ls,\n (r',r_id) ← fold_assoc f i rs,\n let pre' := fold_assoc1 f pre,\n let suff' := fold_assoc1 f suff,\n return (l',r',l_id ++ r_id,mono_function.assoc f pre' suff')\n else do -- ¬ a\n (xs₀,x₀,x₁,xs₁) ← find_one_difference opt ls rs,\n return (x₀,x₁,[],mono_function.non_assoc full_f xs₀ xs₁)\n\nmeta def parse_ac_mono_function' (l r : pexpr) :=\ndo l' ← to_expr l,\n r' ← to_expr r,\n parse_ac_mono_function l' r'\n\nmeta def ac_monotonicity_goal : expr → tactic (expr × expr × list expr × ac_mono_ctx)\n | `(%%e₀ → %%e₁) :=\n do (l,r,id_rs,f) ← parse_ac_mono_function e₀ e₁,\n t₀ ← infer_type e₀,\n t₁ ← infer_type e₁,\n rel_def ← to_expr ``(λ x₀ x₁, (x₀ : %%t₀) → (x₁ : %%t₁)),\n return (e₀, e₁, id_rs,\n { function := f\n , left := l, right := r\n , to_rel := some $ expr.pi `x binder_info.default\n , rel_def := rel_def })\n | `(%%e₀ = %%e₁) :=\n do (l,r,id_rs,f) ← parse_ac_mono_function e₀ e₁,\n t₀ ← infer_type e₀,\n t₁ ← infer_type e₁,\n rel_def ← to_expr ``(λ x₀ x₁, (x₀ : %%t₀) = (x₁ : %%t₁)),\n return (e₀, e₁, id_rs,\n { function := f\n , left := l, right := r\n , to_rel := none\n , rel_def := rel_def })\n | (expr.app (expr.app rel e₀) e₁) :=\n do (l,r,id_rs,f) ← parse_ac_mono_function e₀ e₁,\n return (e₀, e₁, id_rs,\n { function := f\n , left := l, right := r\n , to_rel := expr.app ∘ expr.app rel\n , rel_def := rel })\n | _ := fail \"invalid monotonicity goal\"\n\nmeta def bin_op_left (f : expr) : option expr → expr → expr\n| none e := e\n| (some e₀) e₁ := f.mk_app [e₀,e₁]\n\nmeta def bin_op (f a b : expr) : expr :=\nf.mk_app [a,b]\n\nmeta def bin_op_right (f : expr) : expr → option expr → expr\n| e none := e\n| e₀ (some e₁) := f.mk_app [e₀,e₁]\n\nmeta def mk_fun_app : mono_function → expr → expr\n | (mono_function.non_assoc f x y) z := f.mk_app (x ++ z :: y)\n | (mono_function.assoc f x y) z := bin_op_left f x (bin_op_right f z y)\n | (mono_function.assoc_comm f x) z := f.mk_app [z,x]\n\nmeta inductive mono_law\n /- `assoc (l₀,r₀) (r₁,l₁)` gives first how to find rules to prove\n x+(y₀+z) R x+(y₁+z);\n if that fails, helps prove (x+y₀)+z R (x+y₁)+z -/\n | assoc : expr × expr → expr × expr → mono_law\n /- `congr r` gives the rule to prove `x = y → f x = f y` -/\n | congr : expr → mono_law\n | other : expr → mono_law\n\nmeta def mono_law.to_tactic_format : mono_law → tactic format\n | (mono_law.other e) := do e ← pp e, return format!\"other {e}\"\n | (mono_law.congr r) := do e ← pp r, return format!\"congr {e}\"\n | (mono_law.assoc (x₀,x₁) (y₀,y₁)) :=\ndo x₀ ← pp x₀,\n x₁ ← pp x₁,\n y₀ ← pp y₀,\n y₁ ← pp y₁,\n return format!\"assoc {x₀}; {x₁} | {y₀}; {y₁}\"\n\nmeta instance has_to_tactic_format_mono_law : has_to_tactic_format mono_law :=\n{ to_tactic_format := mono_law.to_tactic_format }\n\nmeta def mk_rel (ctx : ac_mono_ctx_ne) (f : expr → expr) : expr :=\nctx.to_rel (f ctx.left) (f ctx.right)\n\nmeta def mk_congr_args (fn : expr) (xs₀ xs₁ : list expr) (l r : expr) : tactic expr :=\ndo p ← mk_app `eq [fn.mk_app $ xs₀ ++ l :: xs₁,fn.mk_app $ xs₀ ++ r :: xs₁],\n prod.snd <$> solve_aux p\n (do iterate_exactly (xs₁.length) (applyc `congr_fun),\n applyc `congr_arg)\n\nmeta def mk_congr_law (ctx : ac_mono_ctx) : tactic expr :=\nmatch ctx.function with\n | (mono_function.assoc f x₀ x₁) :=\n if (x₀ <|> x₁).is_some\n then mk_congr_args f x₀.to_monad x₁.to_monad ctx.left ctx.right\n else failed\n | (mono_function.assoc_comm f x₀) := mk_congr_args f [x₀] [] ctx.left ctx.right\n | (mono_function.non_assoc f x₀ x₁) := mk_congr_args f x₀ x₁ ctx.left ctx.right\nend\n\nmeta def mk_pattern (ctx : ac_mono_ctx) : tactic mono_law :=\nmatch (sequence ctx : option (ac_mono_ctx' _)) with\n | (some ctx) :=\n match ctx.function with\n | (mono_function.assoc f (some x) (some y)) :=\n return $ mono_law.assoc\n ( mk_rel ctx (λ i, bin_op f x (bin_op f i y))\n , mk_rel ctx (λ i, bin_op f i y))\n ( mk_rel ctx (λ i, bin_op f (bin_op f x i) y)\n , mk_rel ctx (λ i, bin_op f x i))\n | (mono_function.assoc f (some x) none) :=\n return $ mono_law.other $\n mk_rel ctx (λ e, mk_fun_app ctx.function e)\n | (mono_function.assoc f none (some y)) :=\n return $ mono_law.other $\n mk_rel ctx (λ e, mk_fun_app ctx.function e)\n | (mono_function.assoc f none none) :=\n none\n | _ :=\n return $ mono_law.other $\n mk_rel ctx (λ e, mk_fun_app ctx.function e)\n end\n | none := mono_law.congr <$> mk_congr_law ctx\nend\n\nmeta def match_rule (pat : expr) (r : name) : tactic expr :=\ndo r' ← mk_const r,\n t ← infer_type r',\n t ← expr.dsimp t { fail_if_unchanged := ff } tt [] [\n simp_arg_type.expr ``(monotone), simp_arg_type.expr ``(strict_mono)],\n match_rule_head pat [] r' t\n\nmeta def find_lemma (pat : expr) : list name → tactic (list expr)\n | [] := return []\n | (r :: rs) :=\n do (cons <$> match_rule pat r <|> pure id) <*> find_lemma rs\n\nmeta def match_chaining_rules (ls : list name) (x₀ x₁ : expr) : tactic (list expr) :=\ndo x' ← to_expr ``(%%x₁ → %%x₀),\n r₀ ← find_lemma x' ls,\n r₁ ← find_lemma x₁ ls,\n return (expr.app <$> r₀ <*> r₁)\n\nmeta def find_rule (ls : list name) : mono_law → tactic (list expr)\n | (mono_law.assoc (x₀,x₁) (y₀,y₁)) :=\n(match_chaining_rules ls x₀ x₁)\n<|> (match_chaining_rules ls y₀ y₁)\n | (mono_law.congr r) := return [r]\n | (mono_law.other p) := find_lemma p ls\n\nuniverses u v\n\ndef apply_rel {α : Sort u} (R : α → α → Sort v) {x y : α}\n (x' y' : α)\n (h : R x y)\n (hx : x = x')\n (hy : y = y')\n: R x' y' :=\nby { rw [← hx,← hy], apply h }\n\nmeta def ac_refine (e : expr) : tactic unit :=\nrefine ``(eq.mp _ %%e) ; ac_refl\n\nmeta def one_line (e : expr) : tactic format :=\ndo lbl ← pp e,\n asm ← infer_type e >>= pp,\n return format!\"\\t{asm}\\n\"\n\nmeta def side_conditions (e : expr) : tactic format :=\ndo let vs := e.list_meta_vars,\n ts ← mmap one_line vs.tail,\n let r := e.get_app_fn.const_name,\n return format!\"{r}:\\n{format.join ts}\"\n\nopen monad\n\n/-- tactic-facing function, similar to `interactive.tactic.generalize` with the\nexception that meta variables -/\nprivate meta def monotonicity.generalize' (h : name) (v : expr) (x : name) : tactic (expr × expr) :=\ndo tgt ← target,\n t ← infer_type v,\n tgt' ← do\n { ⟨tgt', _⟩ ← solve_aux tgt (tactic.generalize v x >> target),\n to_expr ``(λ y : %%t, Π x, y = x → %%(tgt'.binding_body.lift_vars 0 1)) }\n <|> to_expr ``(λ y : %%t, Π x, %%v = x → %%tgt),\n t ← head_beta (tgt' v) >>= assert h,\n swap,\n r ← mk_eq_refl v,\n solve1 $ tactic.exact (t v r),\n prod.mk <$> tactic.intro x <*> tactic.intro h\n\nprivate meta def hide_meta_vars (tac : list expr → tactic unit) : tactic unit :=\nfocus1 $\ndo tgt ← target >>= instantiate_mvars,\n tactic.change tgt,\n ctx ← local_context,\n let vs := tgt.list_meta_vars,\n vs' ← mmap (λ v,\n do h ← get_unused_name `h,\n x ← get_unused_name `x,\n prod.snd <$> monotonicity.generalize' h v x) vs,\n tac ctx;\n vs'.mmap' (try ∘ tactic.subst)\n\nmeta def hide_meta_vars' (tac : itactic) : itactic :=\nhide_meta_vars $ λ _, tac\n\nend config\n\nmeta def solve_mvar (v : expr) (tac : tactic unit) : tactic unit :=\ndo gs ← get_goals,\n set_goals [v],\n target >>= instantiate_mvars >>= tactic.change,\n tac, done,\n set_goals $ gs\n\ndef list.minimum_on {α β} [linear_order β] (f : α → β) : list α → list α\n| [] := []\n| (x :: xs) := prod.snd $ xs.foldl (λ ⟨k,a⟩ b,\n let k' := f b in\n if k < k' then (k,a)\n else if k' < k then (k', [b])\n else (k,b :: a)) (f x, [x])\n\nopen format mono_selection\n\nmeta def best_match {β} (xs : list expr) (tac : expr → tactic β) : tactic unit :=\ndo t ← target,\n xs ← xs.mmap (λ x,\n try_core $ prod.mk x <$> solve_aux t (tac x >> get_goals)),\n let xs := xs.filter_map id,\n let r := list.minimum_on (list.length ∘ prod.fst ∘ prod.snd) xs,\n match r with\n | [(_,gs,pr)] := tactic.exact pr >> set_goals gs\n | [] := fail \"no good match found\"\n | _ :=\n do lmms ← r.mmap (λ ⟨l,gs,_⟩,\n do ts ← gs.mmap infer_type,\n msg ← ts.mmap pp,\n pure $ foldl compose \"\\n\\n\" $\n list.intersperse \"\\n\" $ to_fmt l.get_app_fn.const_name :: msg),\n let msg := foldl compose \"\" lmms,\n fail format!(\"ambiguous match: {msg}\\n\\n\" ++\n \"Tip: try asserting a side condition to distinguish between the lemmas\")\n end\n\nmeta def mono_aux (dir : parse side) :\n tactic unit :=\ndo t ← target >>= instantiate_mvars,\n ns ← get_monotonicity_lemmas t dir,\n asms ← local_context,\n rs ← find_lemma asms t ns,\n focus1 $ () <$ best_match rs (λ law, tactic.refine $ to_pexpr law)\n\n/--\n- `mono` applies a monotonicity rule.\n- `mono*` applies monotonicity rules repetitively.\n- `mono with x ≤ y` or `mono with [0 ≤ x,0 ≤ y]` creates an assertion for the listed\n propositions. Those help to select the right monotonicity rule.\n- `mono left` or `mono right` is useful when proving strict orderings:\n for `x + y < w + z` could be broken down into either\n - left: `x ≤ w` and `y < z` or\n - right: `x < w` and `y ≤ z`\n- `mono using [rule1,rule2]` calls `simp [rule1,rule2]` before applying mono.\n- The general syntax is\n `mono '*'? ('with' hyp | 'with' [hyp1,hyp2])? ('using' [hyp1,hyp2])? mono_cfg?`\n\nTo use it, first import `tactic.monotonicity`.\n\nHere is an example of mono:\n\n```lean\nexample (x y z k : ℤ)\n (h : 3 ≤ (4 : ℤ))\n (h' : z ≤ y) :\n (k + 3 + x) - y ≤ (k + 4 + x) - z :=\nbegin\n mono, -- unfold `(-)`, apply add_le_add\n { -- ⊢ k + 3 + x ≤ k + 4 + x\n mono, -- apply add_le_add, refl\n -- ⊢ k + 3 ≤ k + 4\n mono },\n { -- ⊢ -y ≤ -z\n mono /- apply neg_le_neg -/ }\nend\n```\n\nMore succinctly, we can prove the same goal as:\n\n```lean\nexample (x y z k : ℤ)\n (h : 3 ≤ (4 : ℤ))\n (h' : z ≤ y) :\n (k + 3 + x) - y ≤ (k + 4 + x) - z :=\nby mono*\n```\n\n-/\nmeta def mono (many : parse (tk \"*\")?)\n (dir : parse side)\n (hyps : parse $ tk \"with\" *> pexpr_list_or_texpr <|> pure [])\n (simp_rules : parse $ tk \"using\" *> simp_arg_list <|> pure []) :\n tactic unit :=\ndo hyps ← hyps.mmap (λ p, to_expr p >>= mk_meta_var),\n hyps.mmap' (λ pr, do h ← get_unused_name `h, note h none pr),\n when (¬ simp_rules.empty) (simp_core { } failed tt simp_rules [] (loc.ns [none]) >> skip),\n if many.is_some\n then repeat $ mono_aux dir\n else mono_aux dir,\n gs ← get_goals,\n set_goals $ hyps ++ gs\n\nadd_tactic_doc\n{ name := \"mono\",\n category := doc_category.tactic,\n decl_names := [`tactic.interactive.mono],\n tags := [\"monotonicity\"] }\n\n/--\ntransforms a goal of the form `f x ≼ f y` into `x ≤ y` using lemmas\nmarked as `monotonic`.\n\nSpecial care is taken when `f` is the repeated application of an\nassociative operator and if the operator is commutative\n-/\nmeta def ac_mono_aux (cfg : mono_cfg := { mono_cfg . }) :\n tactic unit :=\nhide_meta_vars $ λ asms,\ndo try `[simp only [sub_eq_add_neg]],\n tgt ← target >>= instantiate_mvars,\n (l,r,id_rs,g) ← ac_monotonicity_goal cfg tgt\n <|> fail \"monotonic context not found\",\n ns ← get_monotonicity_lemmas tgt both,\n p ← mk_pattern g,\n rules ← find_rule asms ns p <|> fail \"no applicable rules found\",\n when (rules = []) (fail \"no applicable rules found\"),\n err ← format.join <$> mmap side_conditions rules,\n focus1 $ best_match rules (λ rule, do\n t₀ ← mk_meta_var `(Prop),\n v₀ ← mk_meta_var t₀,\n t₁ ← mk_meta_var `(Prop),\n v₁ ← mk_meta_var t₁,\n tactic.refine $ ``(apply_rel %%(g.rel_def) %%l %%r %%rule %%v₀ %%v₁),\n solve_mvar v₀ (try (any_of id_rs rewrite_target) >>\n ( done <|>\n refl <|>\n ac_refl <|>\n `[simp only [is_associative.assoc]]) ),\n solve_mvar v₁ (try (any_of id_rs rewrite_target) >>\n ( done <|>\n refl <|>\n ac_refl <|>\n `[simp only [is_associative.assoc]]) ),\n n ← num_goals,\n iterate_exactly (n-1) (try $ solve1 $ apply_instance <|>\n tactic.solve_by_elim { lemmas := some asms }))\n\nopen sum nat\n\n/-- (repeat_until_or_at_most n t u): repeat tactic `t` at most n times or until u succeeds -/\nmeta def repeat_until_or_at_most : nat → tactic unit → tactic unit → tactic unit\n| 0 t _ := fail \"too many applications\"\n| (succ n) t u := u <|> (t >> repeat_until_or_at_most n t u)\n\nmeta def repeat_until : tactic unit → tactic unit → tactic unit :=\nrepeat_until_or_at_most 100000\n\n@[derive _root_.has_reflect, derive _root_.inhabited]\ninductive rep_arity : Type\n| one | exactly (n : ℕ) | many\n\nmeta def repeat_or_not : rep_arity → tactic unit → option (tactic unit) → tactic unit\n | rep_arity.one tac none := tac\n | rep_arity.many tac none := repeat tac\n | (rep_arity.exactly n) tac none := iterate_exactly' n tac\n | rep_arity.one tac (some until) := tac >> until\n | rep_arity.many tac (some until) := repeat_until tac until\n | (rep_arity.exactly n) tac (some until) := iterate_exactly n tac >> until\n\nmeta def assert_or_rule : lean.parser (pexpr ⊕ pexpr) :=\n(tk \":=\" *> inl <$> texpr <|> (tk \":\" *> inr <$> texpr))\n\nmeta def arity : lean.parser rep_arity :=\nrep_arity.many <$ tk \"*\" <|>\nrep_arity.exactly <$> (tk \"^\" *> small_nat) <|>\npure rep_arity.one\n\n/--\n\n`ac_mono` reduces the `f x ⊑ f y`, for some relation `⊑` and a\nmonotonic function `f` to `x ≺ y`.\n\n`ac_mono*` unwraps monotonic functions until it can't.\n\n`ac_mono^k`, for some literal number `k` applies monotonicity `k`\ntimes.\n\n`ac_mono := h`, with `h` a hypothesis, unwraps monotonic functions and\nuses `h` to solve the remaining goal. Can be combined with `*` or `^k`:\n`ac_mono* := h`\n\n`ac_mono : p` asserts `p` and uses it to discharge the goal result\nunwrapping a series of monotonic functions. Can be combined with * or\n^k: `ac_mono* : p`\n\nIn the case where `f` is an associative or commutative operator,\n`ac_mono` will consider any possible permutation of its arguments and\nuse the one the minimizes the difference between the left-hand side\nand the right-hand side.\n\nTo use it, first import `tactic.monotonicity`.\n\n`ac_mono` can be used as follows:\n\n```lean\nexample (x y z k m n : ℕ)\n (h₀ : z ≥ 0)\n (h₁ : x ≤ y) :\n (m + x + n) * z + k ≤ z * (y + n + m) + k :=\nbegin\n ac_mono,\n -- ⊢ (m + x + n) * z ≤ z * (y + n + m)\n ac_mono,\n -- ⊢ m + x + n ≤ y + n + m\n ac_mono,\nend\n```\n\nAs with `mono*`, `ac_mono*` solves the goal in one go and so does\n`ac_mono* := h₁`. The latter syntax becomes especially interesting in the\nfollowing example:\n\n```lean\nexample (x y z k m n : ℕ)\n (h₀ : z ≥ 0)\n (h₁ : m + x + n ≤ y + n + m) :\n (m + x + n) * z + k ≤ z * (y + n + m) + k :=\nby ac_mono* := h₁.\n```\n\nBy giving `ac_mono` the assumption `h₁`, we are asking `ac_refl` to\nstop earlier than it would normally would.\n-/\nmeta def ac_mono (rep : parse arity) :\n parse assert_or_rule? →\n opt_param mono_cfg { mono_cfg . } →\n tactic unit\n | none opt := focus1 $ repeat_or_not rep (ac_mono_aux opt) none\n | (some (inl h)) opt :=\ndo focus1 $ repeat_or_not rep (ac_mono_aux opt) (some $ done <|> to_expr h >>= ac_refine)\n | (some (inr t)) opt :=\ndo h ← i_to_expr t >>= assert `h,\n tactic.swap,\n focus1 $ repeat_or_not rep (ac_mono_aux opt) (some $ done <|> ac_refine h)\n/-\nTODO(Simon): with `ac_mono := h` and `ac_mono : p` split the remaining\n gaol if the provided rule does not solve it completely.\n-/\n\nadd_tactic_doc\n{ name := \"ac_mono\",\n category := doc_category.tactic,\n decl_names := [`tactic.interactive.ac_mono],\n tags := [\"monotonicity\"] }\n\nattribute [mono] and.imp or.imp\n\nend tactic.interactive\n", "meta": {"author": "jjaassoonn", "repo": "projective_space", "sha": "11fe19fe9d7991a272e7a40be4b6ad9b0c10c7ce", "save_path": "github-repos/lean/jjaassoonn-projective_space", "path": "github-repos/lean/jjaassoonn-projective_space/projective_space-11fe19fe9d7991a272e7a40be4b6ad9b0c10c7ce/src/tactic/monotonicity/interactive.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3380771374883919, "lm_q2_score": 0.036769468846346534, "lm_q1q2_score": 0.01243091677454144}} {"text": "import for_mathlib.homology_exact\nimport for_mathlib.split_exact\nimport for_mathlib.sum_str\n.\n\nnoncomputable theory\n\nopen category_theory category_theory.limits\n\nvariables {𝓐 : Type*} [category 𝓐] [abelian 𝓐]\n\nvariables {A₁₁ A₁₂ A₁₃ A₁₄ A₁₅ : 𝓐}\nvariables {A₂₁ A₂₂ A₂₃ A₂₄ A₂₅ : 𝓐}\nvariables {A₃₁ A₃₂ A₃₃ A₃₄ A₃₅ : 𝓐}\nvariables {A₄₁ A₄₂ A₄₃ A₄₄ A₄₅ : 𝓐}\nvariables {A₅₁ A₅₂ A₅₃ A₅₄ A₅₅ : 𝓐}\n\nvariables {f₁₁ : A₁₁ ⟶ A₁₂} {f₁₂ : A₁₂ ⟶ A₁₃} {f₁₃ : A₁₃ ⟶ A₁₄} {f₁₄ : A₁₄ ⟶ A₁₅}\nvariables {g₁₁ : A₁₁ ⟶ A₂₁} {g₁₂ : A₁₂ ⟶ A₂₂} {g₁₃ : A₁₃ ⟶ A₂₃} {g₁₄ : A₁₄ ⟶ A₂₄} {g₁₅ : A₁₅ ⟶ A₂₅}\nvariables {f₂₁ : A₂₁ ⟶ A₂₂} {f₂₂ : A₂₂ ⟶ A₂₃} {f₂₃ : A₂₃ ⟶ A₂₄} {f₂₄ : A₂₄ ⟶ A₂₅}\nvariables {g₂₁ : A₂₁ ⟶ A₃₁} {g₂₂ : A₂₂ ⟶ A₃₂} {g₂₃ : A₂₃ ⟶ A₃₃} {g₂₄ : A₂₄ ⟶ A₃₄} {g₂₅ : A₂₅ ⟶ A₃₅}\nvariables {f₃₁ : A₃₁ ⟶ A₃₂} {f₃₂ : A₃₂ ⟶ A₃₃} {f₃₃ : A₃₃ ⟶ A₃₄} {f₃₄ : A₃₄ ⟶ A₃₅}\nvariables {g₃₁ : A₃₁ ⟶ A₄₁} {g₃₂ : A₃₂ ⟶ A₄₂} {g₃₃ : A₃₃ ⟶ A₄₃} {g₃₄ : A₃₄ ⟶ A₄₄} {g₃₅ : A₃₅ ⟶ A₄₅}\nvariables {f₄₁ : A₄₁ ⟶ A₄₂} {f₄₂ : A₄₂ ⟶ A₄₃} {f₄₃ : A₄₃ ⟶ A₄₄} {f₄₄ : A₄₄ ⟶ A₄₅}\nvariables {g₄₁ : A₄₁ ⟶ A₅₁} {g₄₂ : A₄₂ ⟶ A₅₂} {g₄₃ : A₄₃ ⟶ A₅₃} {g₄₄ : A₄₄ ⟶ A₅₄} {g₄₅ : A₄₅ ⟶ A₅₅}\nvariables {f₅₁ : A₅₁ ⟶ A₅₂} {f₅₂ : A₅₂ ⟶ A₅₃} {f₅₃ : A₅₃ ⟶ A₅₄} {f₅₄ : A₅₄ ⟶ A₅₅}\n\nsection\n\nvariables (f₁₁ g₁₁ g₁₂ f₂₁)\n\n/-- A *commutative square* is a commutative diagram of the following shape:\n```\nA₁₁ --- f₁₁ --> A₁₂\n | |\ng₁₁ g₁₂\n | |\n v v\nA₂₁ --- f₂₁ --> A₂₂\n```\nThe order of (explicit) variables is: top-to-bottom, left-to-right,\nalternating between rows of horizontal maps and rows of vertical maps. -/\n@[ext] structure commsq :=\n(S : 𝓐)\n(ι : A₁₁ ⟶ S)\n(π : S ⟶ A₂₂)\n(diag : A₁₁ ⟶ A₂₂)\n(sum : sum_str A₁₂ A₂₁ S)\n(ι_fst : ι ≫ sum.fst = f₁₁)\n(ι_snd : ι ≫ sum.snd = g₁₁)\n(inl_π : sum.inl ≫ π = g₁₂)\n(inr_π : sum.inr ≫ π = f₂₁)\n(tr₁ : g₁₁ ≫ f₂₁ = diag)\n(tr₂ : f₁₁ ≫ g₁₂ = diag)\n\nend\n\nnamespace commsq\n\nattribute [simp, reassoc] ι_fst ι_snd inl_π inr_π\n\n@[reassoc] lemma w (sq : commsq f₁₁ g₁₁ g₁₂ f₂₁) : f₁₁ ≫ g₁₂ = g₁₁ ≫ f₂₁ :=\nby rw [sq.tr₁, sq.tr₂]\n\n@[reassoc] lemma w_inv [is_iso g₁₁] [is_iso g₁₂] (sq : commsq f₁₁ g₁₁ g₁₂ f₂₁) :\n inv g₁₁ ≫ f₁₁ = f₂₁ ≫ inv g₁₂ :=\nby rw [is_iso.eq_comp_inv, category.assoc, sq.w, is_iso.inv_hom_id_assoc]\n\ndef of_eq (w : f₁₁ ≫ g₁₂ = g₁₁ ≫ f₂₁) : commsq f₁₁ g₁₁ g₁₂ f₂₁ :=\n{ S := A₁₂ ⊞ A₂₁,\n ι := biprod.lift f₁₁ g₁₁,\n π := biprod.desc g₁₂ f₂₁,\n diag := g₁₁ ≫ f₂₁,\n sum := sum_str.biprod _ _,\n ι_fst := biprod.lift_fst _ _,\n ι_snd := biprod.lift_snd _ _,\n inl_π := biprod.inl_desc _ _,\n inr_π := biprod.inr_desc _ _,\n tr₁ := rfl,\n tr₂ := w }\n\ndef symm (sq : commsq f₁₁ g₁₁ g₁₂ f₂₁) : commsq g₁₁ f₁₁ f₂₁ g₁₂ :=\n{ sum := sq.sum.symm,\n ι_fst := sq.ι_snd,\n ι_snd := sq.ι_fst,\n inl_π := sq.inr_π,\n inr_π := sq.inl_π,\n tr₁ := sq.tr₂,\n tr₂ := sq.tr₁,\n .. sq }\n\nlemma ι_eq (sq : commsq f₁₁ g₁₁ g₁₂ f₂₁) :\n sq.ι = f₁₁ ≫ sq.sum.inl + g₁₁ ≫ sq.sum.inr :=\nbegin\n rw [← cancel_mono (𝟙 sq.S), ← sq.sum.total],\n simp only [preadditive.add_comp, category.assoc, ι_fst_assoc, ι_snd_assoc, preadditive.comp_add,\n preadditive.add_comp_assoc, sum_str.inl_fst, category.comp_id, sum_str.inr_fst, comp_zero,\n add_zero, sum_str.inl_snd, sum_str.inr_snd, zero_add],\nend\n\nlemma π_eq (sq : commsq f₁₁ g₁₁ g₁₂ f₂₁) :\n sq.π = sq.sum.fst ≫ g₁₂ + sq.sum.snd ≫ f₂₁ :=\nbegin\n rw [← cancel_epi (𝟙 sq.S), ← sq.sum.total],\n simp only [preadditive.add_comp, category.assoc, inl_π, inr_π, preadditive.comp_add,\n preadditive.add_comp_assoc, sum_str.inl_fst, category.comp_id, sum_str.inr_fst, comp_zero,\n add_zero, sum_str.inl_snd, sum_str.inr_snd, zero_add],\nend\n\nsection iso\nopen category_theory.preadditive\n\nlemma ι_iso_hom (sq₁ sq₂ : commsq f₁₁ g₁₁ g₁₂ f₂₁) :\n sq₁.ι ≫ (sq₁.sum.iso sq₂.sum).hom = sq₂.ι :=\nbegin\n simp only [sum_str.iso_hom, comp_add, ι_fst_assoc, ι_snd_assoc],\n simp only [← sq₂.ι_fst_assoc, ← sq₂.ι_snd_assoc, ← comp_add, sum_str.total, category.comp_id],\nend\n\nlemma iso_hom_π (sq₁ sq₂ : commsq f₁₁ g₁₁ g₁₂ f₂₁) :\n (sq₁.sum.iso sq₂.sum).hom ≫ sq₂.π = sq₁.π :=\nbegin\n simp only [sum_str.iso_hom, add_comp, category.assoc, inl_π, inr_π],\n simp only [← sq₁.inl_π, ← sq₁.inr_π],\n simp only [← category.assoc, ← add_comp, sum_str.total, category.id_comp],\nend\n\nlemma ι_iso_inv (sq₁ sq₂ : commsq f₁₁ g₁₁ g₁₂ f₂₁) :\n sq₂.ι ≫ (sq₁.sum.iso sq₂.sum).inv = sq₁.ι :=\nι_iso_hom _ _\n\nlemma iso_inv_π (sq₁ sq₂ : commsq f₁₁ g₁₁ g₁₂ f₂₁) :\n (sq₁.sum.iso sq₂.sum).inv ≫ sq₁.π = sq₂.π :=\niso_hom_π _ _\n\nend iso\n\nlemma of_iso (e₁₁ : A₁₁ ≅ A₃₃) (e₁₂ : A₁₂ ≅ A₃₄) (e₂₁ : A₂₁ ≅ A₄₃) (e₂₂ : A₂₂ ≅ A₄₄)\n (sqa : commsq f₁₁ e₁₁.hom e₁₂.hom f₃₃) (sqb : commsq g₁₁ e₁₁.hom e₂₁.hom g₃₃)\n (sqc : commsq g₁₂ e₁₂.hom e₂₂.hom g₃₄) (sqd : commsq f₂₁ e₂₁.hom e₂₂.hom f₄₃)\n (sq1 : commsq f₁₁ g₁₁ g₁₂ f₂₁) :\n commsq f₃₃ g₃₃ g₃₄ f₄₃ :=\nof_eq $ by rw [← cancel_epi e₁₁.hom, ← sqa.w_assoc, ← sqc.w, ← sqb.w_assoc, ← sqd.w, sq1.w_assoc]\n\ndef kernel (sq : commsq f₁₁ g₁₁ g₁₂ f₂₁) :\n commsq (kernel.ι f₁₁) (kernel.map _ _ _ _ sq.w) g₁₁ (kernel.ι f₂₁) :=\ncommsq.of_eq $ by simp only [kernel.lift_ι]\n\ndef cokernel (sq : commsq f₁₁ g₁₁ g₁₂ f₂₁) :\n commsq (cokernel.π f₁₁) g₁₂ (cokernel.map _ _ _ _ sq.w) (cokernel.π f₂₁) :=\ncommsq.of_eq $ by simp only [cokernel.π_desc]\n\ndef bicartesian (sq : commsq f₁₁ g₁₁ g₁₂ f₂₁) : Prop :=\nshort_exact (-f₁₁ ≫ sq.sum.inl + g₁₁ ≫ sq.sum.inr) sq.π\n\ndef bicartesian.is_limit {sq : commsq f₁₁ g₁₁ g₁₂ f₂₁} (h : sq.bicartesian) :\n is_limit (pullback_cone.mk f₁₁ g₁₁ sq.w) :=\npullback_cone.is_limit.mk sq.w\n (λ s, (@abelian.is_limit_of_exact_of_mono _ _ _ _ _ _ _ _ h.mono h.exact).lift\n (fork.of_ι (-s.fst ≫ sq.sum.inl + s.snd ≫ sq.sum.inr)\n (by simp only [s.condition, preadditive.add_comp, preadditive.neg_comp, category.assoc,\n inl_π, inr_π, add_left_neg, comp_zero])))\n (λ s,\n begin\n have : f₁₁ = -((-f₁₁ ≫ sq.sum.inl + g₁₁ ≫ sq.sum.inr) ≫ sq.sum.fst),\n { simp only [preadditive.add_comp, preadditive.neg_comp, category.assoc, sum_str.inl_fst,\n category.comp_id, sum_str.inr_fst, comp_zero, add_zero, neg_neg] },\n conv_lhs { congr, skip, rw this },\n rw [preadditive.comp_neg, ← category.assoc],\n erw (@abelian.is_limit_of_exact_of_mono _ _ _ _ _ _ _ _ h.mono h.exact).fac _\n walking_parallel_pair.zero,\n simp only [preadditive.add_comp, preadditive.neg_comp, category.assoc, comp_zero,\n fork.of_ι_π_app, sum_str.inl_fst, category.comp_id, sum_str.inr_fst, add_zero, neg_neg],\n end)\n (λ s,\n begin\n have : g₁₁ = (-f₁₁ ≫ sq.sum.inl + g₁₁ ≫ sq.sum.inr) ≫ sq.sum.snd,\n { simp only [preadditive.add_comp, preadditive.neg_comp, category.assoc, sum_str.inl_snd,\n comp_zero, neg_zero, sum_str.inr_snd, category.comp_id, zero_add] },\n conv_lhs { congr, skip, rw this },\n rw ← category.assoc,\n erw (@abelian.is_limit_of_exact_of_mono _ _ _ _ _ _ _ _ h.mono h.exact).fac _\n walking_parallel_pair.zero,\n simp only [preadditive.add_comp, preadditive.neg_comp, category.assoc, comp_zero,\n fork.of_ι_π_app, sum_str.inl_snd, neg_zero, sum_str.inr_snd, category.comp_id, zero_add],\n end)\n (λ s m h₁ h₂,\n begin\n apply fork.is_limit.hom_ext (@abelian.is_limit_of_exact_of_mono _ _ _ _ _ _ _ _ h.mono h.exact),\n erw [is_limit.fac],\n simp only [reassoc_of h₁, reassoc_of h₂, kernel_fork.ι_of_ι, preadditive.comp_add,\n preadditive.comp_neg, fork.of_ι_π_app],\n end)\n\ndef bicartesian.is_colimit {sq : commsq f₁₁ g₁₁ g₁₂ f₂₁} (h : sq.bicartesian) :\n is_colimit (pushout_cocone.mk g₁₂ f₂₁ sq.w) :=\npushout_cocone.is_colimit.mk sq.w\n (λ s, (@abelian.is_colimit_of_exact_of_epi _ _ _ _ _ _ _ _ h.epi h.exact).desc\n (cofork.of_π (sq.sum.fst ≫ s.inl + sq.sum.snd ≫ s.inr)\n (by simp only [s.condition, preadditive.comp_add, preadditive.add_comp_assoc,\n preadditive.neg_comp, category.assoc, sum_str.inl_fst, category.comp_id, sum_str.inr_fst,\n comp_zero, add_zero, sum_str.inl_snd, neg_zero, sum_str.inr_snd, zero_add, add_left_neg,\n zero_comp])))\n (λ s,\n begin\n conv_lhs { congr, rw [← sq.inl_π] },\n rw category.assoc,\n erw (@abelian.is_colimit_of_exact_of_epi _ _ _ _ _ _ _ _ h.epi h.exact).fac _\n walking_parallel_pair.one,\n simp only [preadditive.comp_add, add_zero, zero_comp, cofork.of_π_ι_app, sum_str.inl_fst_assoc,\n sum_str.inl_snd_assoc],\n end)\n (λ s,\n begin\n conv_lhs { congr, rw [← sq.inr_π] },\n rw category.assoc,\n erw (@abelian.is_colimit_of_exact_of_epi _ _ _ _ _ _ _ _ h.epi h.exact).fac _\n walking_parallel_pair.one,\n simp only [preadditive.comp_add, zero_add, zero_comp, cofork.of_π_ι_app, sum_str.inr_fst_assoc,\n sum_str.inr_snd_assoc]\n end)\n (λ s m h₁ h₂,\n begin\n apply cofork.is_colimit.hom_ext\n (@abelian.is_colimit_of_exact_of_epi _ _ _ _ _ _ _ _ h.epi h.exact),\n erw [is_colimit.fac],\n simp only [cokernel_cofork.π_of_π, cofork.of_π_ι_app],\n conv_lhs { congr, rw [← category.id_comp sq.π] },\n rw [← sq.sum.total],\n simp only [h₁, h₂, preadditive.add_comp, category.assoc, inl_π, inr_π]\n end)\n\nlemma bicartesian.of_is_limit_of_is_colimt {sq : commsq f₁₁ g₁₁ g₁₂ f₂₁}\n (hl : is_limit (pullback_cone.mk f₁₁ g₁₁ sq.w)) (hc : is_colimit (pushout_cocone.mk g₁₂ f₂₁ sq.w)) :\n sq.bicartesian :=\nbegin\n have h : (-f₁₁ ≫ sq.sum.inl + g₁₁ ≫ sq.sum.inr) ≫ sq.π = 0,\n { simp only [sq.w, preadditive.add_comp, preadditive.neg_comp, category.assoc, inl_π, inr_π,\n add_left_neg] },\n let hker : is_limit (kernel_fork.of_ι _ h),\n { fapply kernel_fork.is_limit.of_ι,\n { refine λ T g hg, hl.lift (pullback_cone.mk (-g ≫ sq.sum.fst) (g ≫ sq.sum.snd) _),\n rw [sq.π_eq, preadditive.comp_add] at hg,\n simp only [add_eq_zero_iff_eq_neg.1 hg, preadditive.neg_comp, category.assoc,\n neg_neg] },\n { intros T g hg,\n simp only [preadditive.comp_add, preadditive.comp_neg, ← category.assoc],\n erw [hl.fac _ walking_span.left, hl.fac _ walking_span.right],\n simp only [preadditive.neg_comp, category.assoc, neg_neg, pullback_cone.mk_π_app_left,\n pullback_cone.mk_π_app_right, ← preadditive.comp_add, sq.sum.total, category.comp_id] },\n { intros T g hg m hm,\n apply pullback_cone.is_limit.hom_ext hl,\n { erw [pullback_cone.mk_fst, hl.fac _ walking_span.left],\n simp only [← hm, preadditive.neg_comp, category.assoc, neg_neg, pullback_cone.mk_π_app_left,\n preadditive.comp_neg, preadditive.add_comp, sum_str.inl_fst, category.comp_id,\n sum_str.inr_fst, comp_zero, add_zero] },\n { erw [pullback_cone.mk_snd, hl.fac _ walking_span.right],\n simp only [← hm, preadditive.neg_comp, category.assoc, pullback_cone.mk_π_app_right,\n preadditive.add_comp, sum_str.inl_snd, comp_zero, neg_zero, sum_str.inr_snd,\n category.comp_id, zero_add] } } },\n let hcoker : is_colimit (cokernel_cofork.of_π _ h),\n { fapply cokernel_cofork.is_colimit.of_π,\n { refine λ T g hg, hc.desc (pushout_cocone.mk (sq.sum.inl ≫ g) (sq.sum.inr ≫ g) _),\n rwa [preadditive.add_comp, preadditive.neg_comp, add_eq_zero_iff_neg_eq, neg_neg,\n category.assoc, category.assoc] at hg },\n { intros T g hg,\n simp only [sq.π_eq, preadditive.add_comp, category.assoc],\n erw [hc.fac _ walking_cospan.left, hc.fac _ walking_cospan.right],\n simp only [pushout_cocone.mk_ι_app_left, pushout_cocone.mk_ι_app_right, ← category.assoc,\n ← preadditive.add_comp, sq.sum.total, category.id_comp] },\n { intros T g hg m hm,\n apply pushout_cocone.is_colimit.hom_ext hc,\n { erw [pushout_cocone.mk_inl, hc.fac _ walking_cospan.left],\n simp only [← hm, pushout_cocone.mk_ι_app_left, inl_π_assoc] },\n { erw [pushout_cocone.mk_inr, hc.fac _ walking_cospan.right],\n simp only [←hm, pushout_cocone.mk_ι_app_right, inr_π_assoc] } } },\n haveI : mono (-f₁₁ ≫ sq.sum.inl + g₁₁ ≫ sq.sum.inr) := mono_of_is_limit_fork hker,\n haveI : epi sq.π := epi_of_is_colimit_cofork hcoker,\n exact ⟨abelian.exact_of_is_kernel _ _ h hker⟩\nend\n\nopen category_theory.preadditive\n\nlemma bicartesian.congr {sq₁ : commsq f₁₁ g₁₁ g₁₂ f₂₁}\n (h : sq₁.bicartesian) (sq₂ : commsq f₁₁ g₁₁ g₁₂ f₂₁) :\n sq₂.bicartesian :=\nbegin\n have := h.mono, have := h.epi, resetI,\n have hm : mono (-f₁₁ ≫ sq₂.sum.inl + g₁₁ ≫ sq₂.sum.inr),\n { suffices : -f₁₁ ≫ sq₂.sum.inl + g₁₁ ≫ sq₂.sum.inr =\n (-f₁₁ ≫ sq₁.sum.inl + g₁₁ ≫ sq₁.sum.inr) ≫ (sq₁.sum.iso sq₂.sum).hom,\n { rw [this], apply mono_comp },\n simp only [sum_str.iso_hom, comp_add, add_comp_assoc, neg_comp, category.assoc,\n sum_str.inl_fst, category.comp_id, sum_str.inr_fst, comp_zero, add_zero,\n sum_str.inl_snd, neg_zero, sum_str.inr_snd, zero_add], },\n have he : epi sq₂.π, { rw [← sq₁.iso_inv_π sq₂], apply epi_comp },\n have H : exact (-f₁₁ ≫ sq₂.sum.inl + g₁₁ ≫ sq₂.sum.inr) sq₂.π,\n { apply exact_of_iso_of_exact' _ _ _ _\n (iso.refl _) (sq₁.sum.iso sq₂.sum) (iso.refl _) _ _ h.exact,\n { simp only [iso.refl_hom, comp_add, category.id_comp, sum_str.iso_hom, add_comp_assoc,\n neg_comp, category.assoc, sum_str.inl_fst, sum_str.inr_fst, comp_zero, add_zero,\n sum_str.inl_snd, neg_zero, sum_str.inr_snd, zero_add], },\n { simp only [iso.refl_hom, category.comp_id, iso_hom_π], }, },\n exactI ⟨H⟩\nend\n\nlemma bicartesian_iff (sq₁ sq₂ : commsq f₁₁ g₁₁ g₁₂ f₂₁) :\n sq₁.bicartesian ↔ sq₂.bicartesian :=\n⟨λ h, h.congr _, λ h, h.congr _⟩\n\n--move this (do we want this?)\ninstance {C : Type*} [category C] [preadditive C] {X Y : C} : has_neg (X ≅ Y) :=\n⟨λ e, ⟨-e.hom, -e.inv, by simp, by simp⟩⟩\n\n@[simp] lemma neg_iso_hom {C : Type*} [category C] [preadditive C] {X Y : C} {e : X ≅ Y} :\n (-e).hom = -(e.hom) := rfl\n\n@[simp] lemma neg_iso_inv {C : Type*} [category C] [preadditive C] {X Y : C} {e : X ≅ Y} :\n (-e).inv = -(e.inv) := rfl\n\n-- move me\n@[simp] lemma _root_.category_theory.short_exact.neg_left (h : short_exact f₁₁ f₁₂) :\n short_exact (-f₁₁) f₁₂ :=\nbegin\n haveI := h.mono, haveI := h.epi,\n refine ⟨_⟩,\n have : -f₁₁ = (-iso.refl _).hom ≫ f₁₁,\n { simp only [neg_iso_hom, iso.refl_hom, category.id_comp, neg_comp], },\n rw [this, exact_iso_comp],\n exact h.exact\nend\n\n-- move me\n@[simp] lemma _root_.category_theory.short_exact.neg_left_iff :\n short_exact (-f₁₁) f₁₂ ↔ short_exact f₁₁ f₁₂ :=\nbegin\n refine ⟨_, λ h, h.neg_left⟩,\n intro h, simpa only [neg_neg] using h.neg_left\nend\n\nlemma bicartesian.symm {sq : commsq f₁₁ g₁₁ g₁₂ f₂₁} (h : sq.bicartesian) :\n sq.symm.bicartesian :=\nbegin\n rw bicartesian at h ⊢,\n rw ← category_theory.short_exact.neg_left_iff,\n simp only [neg_add_rev, neg_neg],\n exact h\nend\n\nlemma bicartesian.symm_iff (sq : commsq f₁₁ g₁₁ g₁₂ f₂₁) :\n sq.symm.bicartesian ↔ sq.bicartesian :=\n⟨λ h, h.symm, λ h, h.symm⟩\n\nsection\nvariables (g₁₁ g₁₂ g₁₃)\n\n-- move me\nlemma short_exact.of_iso (h : short_exact f₁₁ f₁₂)\n (sq1 : commsq f₁₁ g₁₁ g₁₂ f₂₁) (sq2 : commsq f₁₂ g₁₂ g₁₃ f₂₂)\n [is_iso g₁₁] [is_iso g₁₂] [is_iso g₁₃] :\n short_exact f₂₁ f₂₂ :=\nbegin\n have := h.mono, have := h.epi, resetI,\n have : mono f₂₁,\n { suffices : mono (f₂₁ ≫ inv g₁₂), { resetI, apply mono_of_mono f₂₁ (inv g₁₂), },\n rw ← sq1.w_inv, apply_instance },\n have : epi f₂₂,\n { suffices : epi (g₁₂ ≫ f₂₂), { resetI, apply epi_of_epi g₁₂ f₂₂ },\n { rw ← sq2.w, apply epi_comp } },\n resetI, refine ⟨_⟩,\n apply exact_of_iso_of_exact' _ _ _ _ (as_iso g₁₁) (as_iso g₁₂) (as_iso g₁₃)\n sq1.symm.w sq2.symm.w h.exact,\nend\n\nend\n\nlemma bicartesian.of_iso (e₁₁ : A₁₁ ≅ A₃₃) (e₁₂ : A₁₂ ≅ A₃₄) (e₂₁ : A₂₁ ≅ A₄₃) (e₂₂ : A₂₂ ≅ A₄₄)\n {sq1 : commsq f₁₁ g₁₁ g₁₂ f₂₁} {sq2 : commsq f₃₃ g₃₃ g₃₄ f₄₃}\n (sqa : commsq f₁₁ e₁₁.hom e₁₂.hom f₃₃) (sqb : commsq g₁₁ e₁₁.hom e₂₁.hom g₃₃)\n (sqc : commsq g₁₂ e₁₂.hom e₂₂.hom g₃₄) (sqd : commsq f₂₁ e₂₁.hom e₂₂.hom f₄₃)\n (h : sq1.bicartesian) :\n sq2.bicartesian :=\nbegin\n let e : sq1.S ≅ sq2.S := _,\n apply short_exact.of_iso e₁₁.hom e.hom e₂₂.hom h,\n swap 3,\n { refine ⟨sq1.sum.fst ≫ e₁₂.hom ≫ sq2.sum.inl + sq1.sum.snd ≫ e₂₁.hom ≫ sq2.sum.inr,\n sq2.sum.fst ≫ e₁₂.inv ≫ sq1.sum.inl + sq2.sum.snd ≫ e₂₁.inv ≫ sq1.sum.inr,\n _, _⟩;\n { dsimp, simp only [comp_add, add_comp_assoc, category.assoc, sum_str.inl_fst,\n category.comp_id, sum_str.inr_fst, comp_zero, add_zero, iso.hom_inv_id_assoc,\n sum_str.inl_snd, sum_str.inr_snd, zero_add, sq1.sum.total, sq2.sum.total,\n iso.inv_hom_id_assoc], }, },\n { apply commsq.of_eq, dsimp,\n simp only [comp_add, add_comp_assoc, neg_comp, category.assoc, sum_str.inl_fst,\n category.comp_id, sum_str.inr_fst, comp_zero, add_zero, sum_str.inl_snd, neg_zero,\n sum_str.inr_snd, zero_add, comp_neg, sqa.w_assoc, sqb.w_assoc], },\n { apply commsq.of_eq, dsimp,\n simp only [add_comp, category.assoc, inl_π, inr_π, ← sqc.w, ← sqd.w, sq1.π_eq], }\nend\n\nend commsq\n", "meta": {"author": "leanprover-community", "repo": "lean-liquid", "sha": "92f188bd17f34dbfefc92a83069577f708851aec", "save_path": "github-repos/lean/leanprover-community-lean-liquid", "path": "github-repos/lean/leanprover-community-lean-liquid/lean-liquid-92f188bd17f34dbfefc92a83069577f708851aec/src/for_mathlib/commsq.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4921881357207956, "lm_q2_score": 0.025178838820344166, "lm_q1q2_score": 0.012392725738599591}} {"text": "import parlang.defs\nimport parlang.lemmas_active_map\nimport parlang.lemmas_thread_state\nimport parlang.lemmas_state\n\nnamespace parlang\nvariables {n : ℕ} {σ : Type} {ι : Type} {τ : ι → Type} [decidable_eq ι]\n\n@[simp]\nlemma exec_skip {n} {ac : vector bool n} {s} : exec_state (kernel.compute id : kernel σ τ) ac s s := begin\n rw [state.map_active_threads_id s ac] { occs := occurrences.pos [2] },\n apply exec_state.compute,\nend\n\nlemma exec_state_unique {s u t : state n σ τ} {ac : vector bool n} {k} (h₁ : exec_state k ac s u) (h₂ : exec_state k ac s t) : t = u := begin\n induction h₁ generalizing t,\n case exec_state.load {\n cases h₂, refl,\n },\n case exec_state.store {\n cases h₂, refl,\n },\n case exec_state.compute {\n cases h₂, refl,\n },\n case exec_state.sync_all {\n cases h₂,\n case parlang.exec_state.sync_all {\n by_cases hl : 0 < n,\n {\n have : h₁_m = h₂_m := by apply state.syncable_unique h₁_hs h₂_hs hl,\n subst this,\n refl,\n },\n {\n have : n = 0 := by simpa using hl,\n subst this,\n simp [state.map_threads],\n rw [vector.vector_0_eq h₁_s.threads, vector.map_nil, vector.map_nil],\n }\n },\n case parlang.exec_state.sync_none {\n by_cases hl : 0 < n,\n exact false.elim (no_threads_active_not_all_threads hl h₂_h h₁_ha),\n have : n = 0 := by simpa using hl,\n subst this,\n rw [state.map_threads, vector.vector_0_eq h₁_s.threads, vector.map_nil],\n sorry,\n },\n },\n case exec_state.sync_none {\n cases h₂,\n case parlang.exec_state.sync_all {\n by_cases hl : 0 < n,\n -- contradiction\n {apply false.elim (no_threads_active_not_all_threads hl h₁_h h₂_ha),},\n {\n by_cases h' : n = 0,\n swap,\n {\n sorry,\n }, {\n subst h',\n cases h₁_s,\n cases h₁_s,\n sorry,\n }\n }\n },\n case parlang.exec_state.sync_none {\n refl,\n }\n },\n case parlang.exec_state.seq {\n cases h₂,\n specialize h₁_ih_a h₂_a,\n subst h₁_ih_a,\n specialize h₁_ih_a_1 h₂_a_1,\n assumption,\n },\n case parlang.exec_state.ite {\n cases h₂,\n specialize h₁_ih_a h₂_a,\n subst h₁_ih_a,\n specialize h₁_ih_a_1 h₂_a_1,\n assumption,\n },\n case parlang.exec_state.loop_stop {\n cases h₂,\n case parlang.exec_state.loop_stop {\n refl,\n },\n case parlang.exec_state.loop_step {\n apply false.elim (no_threads_active_no_active_thread h₁_a h₂_a),\n }\n },\n case parlang.exec_state.loop_step {\n cases h₂,\n case parlang.exec_state.loop_stop {\n apply false.elim (no_threads_active_no_active_thread h₂_a h₁_a),\n },\n case parlang.exec_state.loop_step {\n specialize h₁_ih_a h₂_a_1,\n subst h₁_ih_a,\n specialize h₁_ih_a_1 h₂_a_2,\n assumption,\n }\n }\nend\n\nlemma exec_state_precedes {s u : state n σ τ} {ac : vector bool n} {k} : exec_state (k) ac s u → s.precedes u := begin\n intro he,\n cases he,\n case parlang.exec_state.load {\n unfold state.precedes,\n simp,\n intros a b,\n induction n,\n case nat.zero {\n exact match ac with\n | ⟨[], h⟩ := begin\n sorry,\n -- rw vector.map₂_nil',\n -- rw vector.map₂_nil,\n -- intro,\n -- have : (a, b) ∉ (@vector.nil (thread_state σ τ × thread_state σ τ)) := by apply vector.mem_nil,\n -- contradiction,\n end\n end,\n },\n case nat.succ {\n exact match ac, s.threads with\n | ⟨list.cons a ac_tl, h ⟩ := begin\n sorry\n end\n end,\n },\n },\n repeat { admit }\nend\n\nlemma exec_state_seq_left {s u : state n σ τ} {ac : vector bool n} {k₁ k₂} : exec_state (k₁ ;; k₂) ac s u → ∃t, exec_state k₁ ac s t ∧ t.precedes u := begin\n intro he,\n cases he,\n apply Exists.intro he_t,\n apply and.intro he_a _,\n apply exec_state_precedes he_a_1,\nend\n\nlemma exec_state_inactive_threads_untouched {s u : state n σ τ} {ac : vector bool n} {k} : exec_state k ac s u → ∀ i, ¬ ac.nth i → s.threads.nth i = u.threads.nth i := begin\n intros he i hna,\n induction he,\n case parlang.exec_state.load {\n apply state.map_active_threads_nth_inac hna,\n },\n case parlang.exec_state.store {\n apply state.map_active_threads_nth_inac hna,\n },\n case parlang.exec_state.compute {\n apply state.map_active_threads_nth_inac hna,\n },\n case parlang.exec_state.sync_all {\n have : ↥(vector.nth he_ac i) := by apply all_threads_active_nth he_ha,\n contradiction,\n },\n case parlang.exec_state.sync_none {\n refl,\n },\n case parlang.exec_state.seq {\n rw he_ih_a hna,\n rw he_ih_a_1 hna,\n },\n case parlang.exec_state.ite {\n rw he_ih_a (deactivate_threads_deactivate_inactive_thread hna),\n rw ← he_ih_a_1 (deactivate_threads_deactivate_inactive_thread hna),\n },\n case parlang.exec_state.loop_stop {\n refl,\n },\n case parlang.exec_state.loop_step {\n rw he_ih_a (deactivate_threads_deactivate_inactive_thread hna),\n rw ← he_ih_a_1 (deactivate_threads_deactivate_inactive_thread hna),\n }\nend\n\nlemma exec_skip_eq {n} {ac : vector bool n} {s t} : exec_state (kernel.compute id : kernel σ τ) ac s t → t = s := exec_state_unique exec_skip\n\nlemma kernel_transform_inhab {k : kernel σ τ} {n} {ac} {s u} : exec_state k ac s u → ¬contains_sync k → ∃ f, kernel_transform_func k f n ac := begin\n intros h hs,\n unfold kernel_transform_func,\n induction k generalizing s u,\n case parlang.kernel.load {\n apply exists.intro (thread_state.load k),\n intros s u,\n apply iff.intro,\n {\n intro he,\n cases he,\n simp [state.map_active_threads],\n }, {\n intro hm,\n subst hm,\n apply exec_state.load,\n }\n },\n case parlang.kernel.sync {\n apply hs.elim,\n rw contains_sync,\n apply true.intro,\n },\n case parlang.kernel.seq {\n rw contains_sync at hs,\n have h1 : ¬contains_sync k_a := sorry,\n have h2 : ¬contains_sync k_a_1 := sorry,\n cases h,\n specialize k_ih_a h1 h_a,\n specialize k_ih_a_1 h2 h_a_1,\n cases k_ih_a with f,\n cases k_ih_a_1 with g,\n apply exists.intro (g ∘ f),\n intros s' u',\n apply iff.intro,\n {\n intros he,\n cases he,\n have h3 : he_t = state.map_active_threads ac f s' := (k_ih_a_h _ _).mp he_a,\n have h4 : u' = state.map_active_threads ac g he_t := (k_ih_a_1_h _ _).mp he_a_1,\n rw ← state.map_map_active_threads,\n rw h3 at h4,\n exact h4,\n }, {\n intro hmac,\n subst hmac,\n apply exec_state.seq,\n repeat { sorry }\n }\n },\n repeat { sorry }\nend\n\n/-- order of exec_state can be changed if their ac's are distinct -/\nlemma exec_state_comm_distinct_ac {s t u : state n σ τ} {ac₁ ac₂ : vector bool n} {k₁ k₂} :\n ac_distinct ac₁ ac₂ →\n exec_state k₁ ac₁ s t →\n exec_state k₂ ac₂ t u →\n ∃ t', exec_state k₂ ac₂ s t' ∧ exec_state k₁ ac₁ t' u :=\nbegin\n intros hd hk₁ hk₂,\n have hf₁ : _ := kernel_transform_inhab hk₁ sorry,\n have hf₂ : _ := kernel_transform_inhab hk₂ sorry,\n cases hf₁ with f₁ hf₁,\n cases hf₂ with f₂ hf₂,\n have h : u = state.map_active_threads ac₂ f₂ (state.map_active_threads ac₁ f₁ s) := begin\n have hkst : t = state.map_active_threads ac₁ f₁ s := ((hf₁ s t).mp hk₁), -- an underscore as a type would break the rw below\n have hktu : _ := (hf₂ t u).mp hk₂,\n rw ← hkst,\n exact hktu,\n end,\n rw state.map_active_threads_comm hd at h,\n apply exists.intro (state.map_active_threads ac₂ f₂ s),\n apply and.intro, \n {\n apply (hf₂ _ _).mpr,\n refl,\n }, {\n apply (hf₁ _ _).mpr,\n exact h,\n }\nend\n\n@[simp]\nlemma init_state_syncable {init : ℕ → σ} {f : memory τ → ℕ} {m : memory τ} : (init_state init f m).syncable m := begin\n unfold state.syncable init_state,\n simp,\nend\n\nlemma kernel_foldr_skip {k : kernel σ τ} {n} {ks s u} {ac : vector bool n} : exec_state (list.foldr kernel.seq k ks) ac s u = exec_state (list.foldr kernel.seq (kernel.compute id) ks ;; k) ac s u := sorry\n\nlemma exec_no_threads_active {k : kernel σ τ} {n} {s} {ac : vector bool n} \n(h : no_thread_active ac = tt) :\nexec_state k ac s s := begin\n induction k,\n {\n rw [← state.map_active_threads_no_thread_active s ac _ h] { occs := occurrences.pos [2] },\n apply exec_state.load,\n }, {\n rw [← state.map_active_threads_no_thread_active s ac _ h] { occs := occurrences.pos [2] },\n apply exec_state.store,\n }, {\n rw [← state.map_active_threads_no_thread_active s ac _ h] { occs := occurrences.pos [2] },\n apply exec_state.compute,\n }, {\n apply exec_state.seq,\n repeat { assumption },\n }, {\n apply exec_state.ite,\n rw ac_deac_ge',\n exact k_ih_a,\n apply no_thread_active_ge,\n exact h,\n rw ac_deac_ge',\n exact k_ih_a_1,\n apply no_thread_active_ge,\n exact h,\n }, {\n apply exec_state.loop_stop,\n rw ac_deac_ge',\n exact h,\n apply no_thread_active_ge,\n exact h,\n }, {\n apply exec_state.sync_none,\n exact h,\n }\nend\n\nend parlang", "meta": {"author": "fischerman", "repo": "GPU-transformation-verifier", "sha": "75a5016f05382738ff93ce5859c4cfa47ccb63c1", "save_path": "github-repos/lean/fischerman-GPU-transformation-verifier", "path": "github-repos/lean/fischerman-GPU-transformation-verifier/GPU-transformation-verifier-75a5016f05382738ff93ce5859c4cfa47ccb63c1/src/parlang/lemmas_exec.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4843800842769843, "lm_q2_score": 0.025565216475354077, "lm_q1q2_score": 0.012383281710891356}} {"text": "/-\nCopyright (c) 2016 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Leonardo de Moura\n\n! This file was ported from Lean 3 source module init.meta.expr\n! leanprover-community/mathlib commit 569fa1a97c0a3d52ccd7286c659e42bbba8eb006\n! Please do not edit these lines, except to modify the commit id\n! if you have ported upstream changes.\n-/\nprelude\nimport Leanbin.Init.Meta.Level\nimport Leanbin.Init.Control.Monad\nimport Leanbin.Init.Meta.RbMap\n\nuniverse u v\n\nopen Native\n\n/-- Column and line position in a Lean source file. -/\nstructure Pos where\n line : Nat\n column : Nat\n#align pos Pos\n\ninstance : DecidableEq Pos\n | ⟨l₁, c₁⟩, ⟨l₂, c₂⟩ =>\n if h₁ : l₁ = l₂ then\n if h₂ : c₁ = c₂ then isTrue (Eq.recOn h₁ (Eq.recOn h₂ rfl))\n else isFalse fun contra => Pos.noConfusion contra fun e₁ e₂ => absurd e₂ h₂\n else isFalse fun contra => Pos.noConfusion contra fun e₁ e₂ => absurd e₁ h₁\n\nunsafe instance : has_to_format Pos :=\n ⟨fun ⟨l, c⟩ => \"⟨\" ++ l ++ \", \" ++ c ++ \"⟩\"⟩\n\n/-- Auxiliary annotation for binders (Lambda and Pi).\n This information is only used for elaboration.\n The difference between `{}` and `⦃⦄` is how implicit arguments are treated that are *not* followed by explicit arguments.\n `{}` arguments are applied eagerly, while `⦃⦄` arguments are left partially applied:\n```lean\ndef foo {x : ℕ} : ℕ := x\ndef bar ⦃x : ℕ⦄ : ℕ := x\n#check foo -- foo : ℕ\n#check bar -- bar : Π ⦃x : ℕ⦄, ℕ\n```\n -/\ninductive BinderInfo-- `(x : α)`\n\n | default-- `{x : α}`\n\n | implicit-- `⦃x:α⦄`\n\n | strict_implicit-- `[x : α]`. Should be inferred with typeclass resolution.\n\n |\n inst_implicit/- Auxiliary internal attribute used to mark local constants representing recursive functions\n in recursive equations and `match` statements. -/\n\n | aux_decl\n#align binder_info BinderInfo\n\ninstance : Repr BinderInfo :=\n ⟨fun bi =>\n match bi with\n | BinderInfo.default => \"default\"\n | BinderInfo.implicit => \"implicit\"\n | BinderInfo.strict_implicit => \"strict_implicit\"\n | BinderInfo.inst_implicit => \"inst_implicit\"\n | BinderInfo.aux_decl => \"aux_decl\"⟩\n\n/-- Macros are basically \"promises\" to build an expr by some C++ code, you can't build them in Lean.\n You can unfold a macro and force it to evaluate.\n They are used for\n - `sorry`.\n - Term placeholders (`_`) in `pexpr`s.\n - Expression annotations. See `expr.is_annotation`.\n - Meta-recursive calls. Eg:\n ```\n meta def Y : (α → α) → α | f := f (Y f)\n ```\n The `Y` that appears in `f (Y f)` is a macro.\n - Builtin projections:\n ```\n structure foo := (mynat : ℕ)\n #print foo.mynat\n -- @[reducible]\n -- def foo.mynat : foo → ℕ :=\n -- λ (c : foo), [foo.mynat c]\n ```\n The thing in square brackets is a macro.\n - Ephemeral structures inside certain specialised C++ implemented tactics.\n -/\nunsafe axiom macro_def : Type\n#align macro_def macro_def\n\n/-- An expression. eg ```(4+5)```.\n\n The `elab` flag is indicates whether the `expr` has been elaborated and doesn't contain any placeholder macros.\n For example the equality `x = x` is represented in `expr ff` as ``app (app (const `eq _) x) x`` while in `expr tt` it is represented as ``app (app (app (const `eq _) t) x) x`` (one more argument).\n The VM replaces instances of this datatype with the C++ implementation. -/\nunsafe inductive expr (elaborated : Bool := true)-- A bound variable with a de-Bruijn index.\n\n | var (i : Nat) : expr-- A type universe: `Sort u`\n\n |\n sort (l : level) :\n expr/- A global constant. These include definitions, constants and inductive type stuff present\nin the environment as well as hard-coded definitions. -/\n\n |\n const (name : Name) (ls : List level) :\n expr/- [WARNING] Do not trust the types for `mvar` and `local_const`,\nthey are sometimes dummy values. Use `tactic.infer_type` instead. -/\n-- An `mvar` is a 'hole' yet to be filled in by the elaborator or tactic state.\n\n |\n mvar (unique : Name) (pretty : Name) (type : expr) :\n expr-- A local constant. For example, if our tactic state was `h : P ⊢ Q`, `h` would be a local constant.\n\n |\n local_const (unique : Name) (pretty : Name) (bi : BinderInfo) (type : expr) :\n expr-- Function application.\n\n | app (f : expr) (x : expr) : expr-- Lambda abstraction. eg ```(λ a : α, x)``\n\n |\n lam (var_name : Name) (bi : BinderInfo) (var_type : expr) (body : expr) :\n expr-- Pi type constructor. eg ```(Π a : α, x)`` and ```(α → β)``\n\n |\n pi (var_name : Name) (bi : BinderInfo) (var_type : expr) (body : expr) :\n expr-- An explicit let binding.\n\n |\n elet (var_name : Name) (type : expr) (assignment : expr) (body : expr) :\n expr/- A macro, see the docstring for `macro_def`.\n The list of expressions are local constants and metavariables that the macro depends on.\n -/\n\n | macro (m : macro_def) (args : List expr) : expr\n#align expr expr\n\nvariable {elab : Bool}\n\nunsafe instance : Inhabited (expr elab) :=\n ⟨expr.sort level.zero⟩\n\n/-- Get the name of the macro definition. -/\nunsafe axiom expr.macro_def_name (d : macro_def) : Name\n#align expr.macro_def_name expr.macro_def_name\n\nunsafe def expr.mk_var (n : Nat) : expr :=\n expr.var n\n#align expr.mk_var expr.mk_var\n\n/-- Expressions can be annotated using an annotation macro during compilation.\nFor example, a `have x:X, from p, q` expression will be compiled to `(λ x:X,q)(p)`, but nested in an annotation macro with the name `\"have\"`.\nThese annotations have no real semantic meaning, but are useful for helping Lean's pretty printer. -/\nunsafe axiom expr.is_annotation : expr elab → Option (Name × expr elab)\n#align expr.is_annotation expr.is_annotation\n\nunsafe axiom expr.is_string_macro : expr elab → Option (expr elab)\n#align expr.is_string_macro expr.is_string_macro\n\n/-- Remove all macro annotations from the given `expr`. -/\nunsafe def expr.erase_annotations : expr elab → expr elab\n | e =>\n match e.is_annotation with\n | some (_, a) => expr.erase_annotations a\n | none => e\n#align expr.erase_annotations expr.erase_annotations\n\n/-- Compares expressions, including binder names. -/\nunsafe axiom expr.has_decidable_eq : DecidableEq expr\n#align expr.has_decidable_eq expr.has_decidable_eq\n\nattribute [instance] expr.has_decidable_eq\n\n/-- Compares expressions while ignoring binder names. -/\nunsafe axiom expr.alpha_eqv : expr → expr → Bool\n#align expr.alpha_eqv expr.alpha_eqv\n\nprotected unsafe axiom expr.to_string : expr elab → String\n#align expr.to_string expr.to_string\n\nunsafe instance : ToString (expr elab) :=\n ⟨expr.to_string⟩\n\nunsafe instance : has_to_format (expr elab) :=\n ⟨fun e => e.toString⟩\n\n/-- Coercion for letting users write (f a) instead of (expr.app f a) -/\nunsafe instance : CoeFun (expr elab) fun e => expr elab → expr elab :=\n ⟨fun e => expr.app e⟩\n\n/-- Each expression created by Lean carries a hash.\nThis is calculated upon creation of the expression.\nTwo structurally equal expressions will have the same hash. -/\nunsafe axiom expr.hash : expr → Nat\n#align expr.hash expr.hash\n\n/-- Compares expressions, ignoring binder names, and sorting by hash. -/\nunsafe axiom expr.lt : expr → expr → Bool\n#align expr.lt expr.lt\n\n/-- Compares expressions, ignoring binder names. -/\nunsafe axiom expr.lex_lt : expr → expr → Bool\n#align expr.lex_lt expr.lex_lt\n\n/--\n`expr.fold e a f`: Traverses each subexpression of `e`. The `nat` passed to the folder `f` is the binder depth. -/\nunsafe axiom expr.fold {α : Type} : expr → α → (expr → Nat → α → α) → α\n#align expr.fold expr.fold\n\n/-- `expr.replace e f`\n Traverse over an expr `e` with a function `f` which can decide to replace subexpressions or not.\n For each subexpression `s` in the expression tree, `f s n` is called where `n` is how many binders are present above the given subexpression `s`.\n If `f s n` returns `none`, the children of `s` will be traversed.\n Otherwise if `some s'` is returned, `s'` will replace `s` and this subexpression will not be traversed further.\n -/\nunsafe axiom expr.replace : expr → (expr → Nat → Option expr) → expr\n#align expr.replace expr.replace\n\n/--\n`abstract_local e n` replaces each instance of the local constant with unique (not pretty) name `n` in `e` with a de-Bruijn variable. -/\nunsafe axiom expr.abstract_local : expr → Name → expr\n#align expr.abstract_local expr.abstract_local\n\n/--\nMulti version of `abstract_local`. Note that the given expression will only be traversed once, so this is not the same as `list.foldl expr.abstract_local`.-/\nunsafe axiom expr.abstract_locals : expr → List Name → expr\n#align expr.abstract_locals expr.abstract_locals\n\n/-- `abstract e x` Abstracts the expression `e` over the local constant `x`. -/\nunsafe def expr.abstract : expr → expr → expr\n | e, expr.local_const n m bi t => e.abstract_local n\n | e, _ => e\n#align expr.abstract expr.abstract\n\n/-- Expressions depend on `level`s, and these may depend on universe parameters which have names.\n`instantiate_univ_params e [(n₁,l₁), ...]` will traverse `e` and replace any universe parameters with name `nᵢ` with the corresponding level `lᵢ`. -/\nunsafe axiom expr.instantiate_univ_params : expr → List (Name × level) → expr\n#align expr.instantiate_univ_params expr.instantiate_univ_params\n\n/--\n`instantiate_nth_var n a b` takes the `n`th de-Bruijn variable in `a` and replaces each occurrence with `b`. -/\nunsafe axiom expr.instantiate_nth_var : Nat → expr → expr → expr\n#align expr.instantiate_nth_var expr.instantiate_nth_var\n\n/--\n`instantiate_var a b` takes the 0th de-Bruijn variable in `a` and replaces each occurrence with `b`. -/\nunsafe axiom expr.instantiate_var : expr → expr → expr\n#align expr.instantiate_var expr.instantiate_var\n\n/-- ``instantiate_vars `(#0 #1 #2) [x,y,z] = `(%%x %%y %%z)`` -/\nunsafe axiom expr.instantiate_vars : expr → List expr → expr\n#align expr.instantiate_vars expr.instantiate_vars\n\n/-- Same as `instantiate_vars` except lifts and shifts the vars by the given amount.\n``instantiate_vars_core `(#0 #1 #2 #3) 0 [x,y] = `(x y #0 #1)``\n``instantiate_vars_core `(#0 #1 #2 #3) 1 [x,y] = `(#0 x y #1)``\n``instantiate_vars_core `(#0 #1 #2 #3) 2 [x,y] = `(#0 #1 x y)``\n-/\nunsafe axiom expr.instantiate_vars_core : expr → Nat → List expr → expr\n#align expr.instantiate_vars_core expr.instantiate_vars_core\n\n/--\nPerform beta-reduction if the left expression is a lambda, or construct an application otherwise.\nThat is: ``expr.subst `(λ x, %%Y) Z = Y[x/Z]``, and\n``expr.subst X Z = X.app Z`` otherwise -/\nprotected unsafe axiom expr.subst : expr elab → expr elab → expr elab\n#align expr.subst expr.subst\n\n/--\n`get_free_var_range e` returns one plus the maximum de-Bruijn value in `e`. Eg `get_free_var_range `(#1 #0)` yields `2` -/\nunsafe axiom expr.get_free_var_range : expr → Nat\n#align expr.get_free_var_range expr.get_free_var_range\n\n/-- `has_var e` returns true iff e has free variables. -/\nunsafe axiom expr.has_var : expr → Bool\n#align expr.has_var expr.has_var\n\n/-- `has_var_idx e n` returns true iff `e` has a free variable with de-Bruijn index `n`. -/\nunsafe axiom expr.has_var_idx : expr → Nat → Bool\n#align expr.has_var_idx expr.has_var_idx\n\n/-- `has_local e` returns true if `e` contains a local constant. -/\nunsafe axiom expr.has_local : expr → Bool\n#align expr.has_local expr.has_local\n\n/-- `has_meta_var e` returns true iff `e` contains a metavariable. -/\nunsafe axiom expr.has_meta_var : expr → Bool\n#align expr.has_meta_var expr.has_meta_var\n\n/--\n`lower_vars e s d` lowers the free variables >= s in `e` by `d`. Note that this can cause variable clashes.\n examples:\n - ``lower_vars `(#2 #1 #0) 1 1 = `(#1 #0 #0)``\n - ``lower_vars `(λ x, #2 #1 #0) 1 1 = `(λ x, #1 #1 #0 )``\n -/\nunsafe axiom expr.lower_vars : expr → Nat → Nat → expr\n#align expr.lower_vars expr.lower_vars\n\n/--\nLifts free variables. `lift_vars e s d` will lift all free variables with index `≥ s` in `e` by `d`. -/\nunsafe axiom expr.lift_vars : expr → Nat → Nat → expr\n#align expr.lift_vars expr.lift_vars\n\n/-- Get the position of the given expression in the Lean source file, if anywhere. -/\nprotected unsafe axiom expr.pos : expr elab → Option Pos\n#align expr.pos expr.pos\n\n/-- `copy_pos_info src tgt` copies position information from `src` to `tgt`. -/\nunsafe axiom expr.copy_pos_info : expr → expr → expr\n#align expr.copy_pos_info expr.copy_pos_info\n\n/-- Returns `some n` when the given expression is a constant with the name `..._cnstr.n`\n```\nis_internal_cnstr : expr → option unsigned\n|(const (mk_numeral n (mk_string \"_cnstr\" _)) _) := some n\n|_ := none\n```\n[NOTE] This is not used anywhere in core Lean.\n-/\nunsafe axiom expr.is_internal_cnstr : expr → Option Unsigned\n#align expr.is_internal_cnstr expr.is_internal_cnstr\n\n/--\nThere is a macro called a \"nat_value_macro\" holding a natural number which are used during compilation.\nThis function extracts that to a natural number. [NOTE] This is not used anywhere in Lean. -/\nunsafe axiom expr.get_nat_value : expr → Option Nat\n#align expr.get_nat_value expr.get_nat_value\n\n/-- Get a list of all of the universe parameters that the given expression depends on. -/\nunsafe axiom expr.collect_univ_params : expr → List Name\n#align expr.collect_univ_params expr.collect_univ_params\n\n/--\n`occurs e t` returns `tt` iff `e` occurs in `t` up to α-equivalence. Purely structural: no unification or definitional equality. -/\nunsafe axiom expr.occurs : expr → expr → Bool\n#align expr.occurs expr.occurs\n\n/-- Returns true if any of the names in the given `name_set` are present in the given `expr`. -/\nunsafe axiom expr.has_local_in : expr → name_set → Bool\n#align expr.has_local_in expr.has_local_in\n\n/-- Computes the number of sub-expressions (constant time). -/\nunsafe axiom expr.get_weight : expr → ℕ\n#align expr.get_weight expr.get_weight\n\n/-- Computes the maximum depth of the expression (constant time). -/\nunsafe axiom expr.get_depth : expr → ℕ\n#align expr.get_depth expr.get_depth\n\n/--\n`mk_delayed_abstraction m ls` creates a delayed abstraction on the metavariable `m` with the unique names of the local constants `ls`.\n If `m` is not a metavariable then this is equivalent to `abstract_locals`.\n -/\nunsafe axiom expr.mk_delayed_abstraction : expr → List Name → expr\n#align expr.mk_delayed_abstraction expr.mk_delayed_abstraction\n\n/-- If the given expression is a delayed abstraction macro, return `some ls`\nwhere `ls` is a list of unique names of locals that will be abstracted. -/\nunsafe axiom expr.get_delayed_abstraction_locals : expr → Option (List Name)\n#align expr.get_delayed_abstraction_locals expr.get_delayed_abstraction_locals\n\n/-- (reflected a) is a special opaque container for a closed `expr` representing `a`.\n It can only be obtained via type class inference, which will use the representation\n of `a` in the calling context. Local constants in the representation are replaced\n by nested inference of `reflected` instances.\n\n The quotation expression `` `(a) `` (outside of patterns) is equivalent to `reflect a`\n and thus can be used as an explicit way of inferring an instance of `reflected a`.\n \n Note that the `α` argument is explicit to prevent it being treated as reducible by typeclass\n inference, as this breaks `reflected` instances on type synonyms. -/\n@[class]\nunsafe def reflected (α : Sort u) : α → Type := fun _ => expr\n#align reflected reflected\n\n@[inline]\nunsafe def reflected.to_expr {α : Sort u} {a : α} : reflected _ a → expr :=\n id\n#align reflected.to_expr reflected.to_expr\n\n/-- This is a more strongly-typed version of `expr.subst` that keeps track of the value being\nreflected. To obtain a term of type `reflected _`, use `` (`(λ x y, foo x y).subst ex).subst ey`` instead of\nusing `` `(foo %%ex %%ey) `` (which returns an `expr`). -/\n@[inline]\nunsafe def reflected.subst {α : Sort v} {β : α → Sort u} {f : ∀ a : α, β a} {a : α} :\n reflected _ f → reflected _ a → reflected _ (f a) :=\n expr.subst\n#align reflected.subst reflected.subst\n\n@[instance]\nprotected unsafe axiom expr.reflect (e : expr elab) : reflected _ e\n#align expr.reflect expr.reflect\n\n@[instance]\nprotected unsafe axiom string.reflect (s : String) : reflected _ s\n#align string.reflect string.reflect\n\n@[inline]\nunsafe instance {α : Sort u} (a : α) : Coe (reflected _ a) expr :=\n ⟨reflected.to_expr⟩\n\nprotected unsafe def reflect {α : Sort u} (a : α) [h : reflected _ a] : reflected _ a :=\n h\n#align reflect reflect\n\nunsafe instance {α} (a : α) : has_to_format (reflected _ a) :=\n ⟨fun h => to_fmt h.to_expr⟩\n\nnamespace Expr\n\nopen Decidable\n\nunsafe def lt_prop (a b : expr) : Prop :=\n expr.lt a b = true\n#align expr.lt_prop expr.lt_prop\n\nunsafe instance : DecidableRel expr.lt_prop := fun a b => Bool.decidableEq _ _\n\n/-- Compares expressions, ignoring binder names, and sorting by hash. -/\nunsafe instance : LT expr :=\n ⟨expr.lt_prop⟩\n\nunsafe def mk_true : expr :=\n const `true []\n#align expr.mk_true expr.mk_true\n\nunsafe def mk_false : expr :=\n const `false []\n#align expr.mk_false expr.mk_false\n\n/-- Returns the sorry macro with the given type. -/\nunsafe axiom mk_sorry (type : expr) : expr\n#align expr.mk_sorry expr.mk_sorry\n\n/-- Checks whether e is sorry, and returns its type. -/\nunsafe axiom is_sorry (e : expr) : Option expr\n#align expr.is_sorry expr.is_sorry\n\n/-- Replace each instance of the local constant with name `n` by the expression `s` in `e`. -/\nunsafe def instantiate_local (n : Name) (s : expr) (e : expr) : expr :=\n instantiate_var (abstract_local e n) s\n#align expr.instantiate_local expr.instantiate_local\n\nunsafe def instantiate_locals (s : List (Name × expr)) (e : expr) : expr :=\n instantiate_vars (abstract_locals e (List.reverse (List.map Prod.fst s))) (List.map Prod.snd s)\n#align expr.instantiate_locals expr.instantiate_locals\n\nunsafe def is_var : expr → Bool\n | var _ => true\n | _ => false\n#align expr.is_var expr.is_var\n\nunsafe def app_of_list : expr → List expr → expr\n | f, [] => f\n | f, p :: ps => app_of_list (f p) ps\n#align expr.app_of_list expr.app_of_list\n\nunsafe def is_app : expr → Bool\n | app f a => true\n | e => false\n#align expr.is_app expr.is_app\n\nunsafe def app_fn : expr → expr\n | app f a => f\n | a => a\n#align expr.app_fn expr.app_fn\n\nunsafe def app_arg : expr → expr\n | app f a => a\n | a => a\n#align expr.app_arg expr.app_arg\n\nunsafe def get_app_fn : expr elab → expr elab\n | app f a => get_app_fn f\n | a => a\n#align expr.get_app_fn expr.get_app_fn\n\nunsafe def get_app_num_args : expr → Nat\n | app f a => get_app_num_args f + 1\n | e => 0\n#align expr.get_app_num_args expr.get_app_num_args\n\nunsafe def get_app_args_aux : List expr → expr → List expr\n | r, app f a => get_app_args_aux (a :: r) f\n | r, e => r\n#align expr.get_app_args_aux expr.get_app_args_aux\n\nunsafe def get_app_args : expr → List expr :=\n get_app_args_aux []\n#align expr.get_app_args expr.get_app_args\n\nunsafe def mk_app : expr → List expr → expr\n | e, [] => e\n | e, x :: xs => mk_app (e x) xs\n#align expr.mk_app expr.mk_app\n\nunsafe def mk_binding (ctor : Name → BinderInfo → expr → expr → expr) (e : expr) : ∀ l : expr, expr\n | local_const n pp_n bi ty => ctor pp_n bi ty (e.abstract_local n)\n | _ => e\n#align expr.mk_binding expr.mk_binding\n\n/-- (bind_pi e l) abstracts and pi-binds the local `l` in `e` -/\nunsafe def bind_pi :=\n mk_binding pi\n#align expr.bind_pi expr.bind_pi\n\n/-- (bind_lambda e l) abstracts and lambda-binds the local `l` in `e` -/\nunsafe def bind_lambda :=\n mk_binding lam\n#align expr.bind_lambda expr.bind_lambda\n\nunsafe def ith_arg_aux : expr → Nat → expr\n | app f a, 0 => a\n | app f a, n + 1 => ith_arg_aux f n\n | e, _ => e\n#align expr.ith_arg_aux expr.ith_arg_aux\n\nunsafe def ith_arg (e : expr) (i : Nat) : expr :=\n ith_arg_aux e (get_app_num_args e - i - 1)\n#align expr.ith_arg expr.ith_arg\n\nunsafe def const_name : expr elab → Name\n | const n ls => n\n | e => Name.anonymous\n#align expr.const_name expr.const_name\n\nunsafe def is_constant : expr elab → Bool\n | const n ls => true\n | e => false\n#align expr.is_constant expr.is_constant\n\nunsafe def is_local_constant : expr → Bool\n | local_const n m bi t => true\n | e => false\n#align expr.is_local_constant expr.is_local_constant\n\nunsafe def local_uniq_name : expr → Name\n | local_const n m bi t => n\n | e => Name.anonymous\n#align expr.local_uniq_name expr.local_uniq_name\n\nunsafe def local_pp_name : expr elab → Name\n | local_const x n bi t => n\n | e => Name.anonymous\n#align expr.local_pp_name expr.local_pp_name\n\nunsafe def local_type : expr elab → expr elab\n | local_const _ _ _ t => t\n | e => e\n#align expr.local_type expr.local_type\n\nunsafe def is_aux_decl : expr → Bool\n | local_const _ _ BinderInfo.aux_decl _ => true\n | _ => false\n#align expr.is_aux_decl expr.is_aux_decl\n\nunsafe def is_constant_of : expr elab → Name → Bool\n | const n₁ ls, n₂ => n₁ = n₂\n | e, n => false\n#align expr.is_constant_of expr.is_constant_of\n\nunsafe def is_app_of (e : expr) (n : Name) : Bool :=\n is_constant_of (get_app_fn e) n\n#align expr.is_app_of expr.is_app_of\n\n/-- The same as `is_app_of` but must also have exactly `n` arguments. -/\nunsafe def is_napp_of (e : expr) (c : Name) (n : Nat) : Bool :=\n is_app_of e c ∧ get_app_num_args e = n\n#align expr.is_napp_of expr.is_napp_of\n\nunsafe def is_false : expr → Bool\n | q(False) => true\n | _ => false\n#align expr.is_false expr.is_false\n\n-- failed to format: unknown constant 'term.pseudo.antiquot'\nunsafe\n def\n is_not\n : expr → Option expr\n | q( Not $ ( a ) ) => some a | q( $ ( a ) → False ) => some a | e => none\n#align expr.is_not expr.is_not\n\nunsafe def is_and : expr → Option (expr × expr)\n | q(And $(α) $(β)) => some (α, β)\n | _ => none\n#align expr.is_and expr.is_and\n\nunsafe def is_or : expr → Option (expr × expr)\n | q(Or $(α) $(β)) => some (α, β)\n | _ => none\n#align expr.is_or expr.is_or\n\nunsafe def is_iff : expr → Option (expr × expr)\n | q(($(a) : Prop) ↔ $(b)) => some (a, b)\n | _ => none\n#align expr.is_iff expr.is_iff\n\nunsafe def is_eq : expr → Option (expr × expr)\n | q(($(a) : $(_)) = $(b)) => some (a, b)\n | _ => none\n#align expr.is_eq expr.is_eq\n\nunsafe def is_ne : expr → Option (expr × expr)\n | q(($(a) : $(_)) ≠ $(b)) => some (a, b)\n | _ => none\n#align expr.is_ne expr.is_ne\n\nunsafe def is_bin_arith_app (e : expr) (op : Name) : Option (expr × expr) :=\n if is_napp_of e op 4 then some (app_arg (app_fn e), app_arg e) else none\n#align expr.is_bin_arith_app expr.is_bin_arith_app\n\nunsafe def is_lt (e : expr) : Option (expr × expr) :=\n is_bin_arith_app e `` LT.lt\n#align expr.is_lt expr.is_lt\n\nunsafe def is_gt (e : expr) : Option (expr × expr) :=\n is_bin_arith_app e `` GT.gt\n#align expr.is_gt expr.is_gt\n\nunsafe def is_le (e : expr) : Option (expr × expr) :=\n is_bin_arith_app e `` LE.le\n#align expr.is_le expr.is_le\n\nunsafe def is_ge (e : expr) : Option (expr × expr) :=\n is_bin_arith_app e `` GE.ge\n#align expr.is_ge expr.is_ge\n\nunsafe def is_heq : expr → Option (expr × expr × expr × expr)\n | q(@HEq $(α) $(a) $(β) $(b)) => some (α, a, β, b)\n | _ => none\n#align expr.is_heq expr.is_heq\n\nunsafe def is_lambda : expr → Bool\n | lam _ _ _ _ => true\n | e => false\n#align expr.is_lambda expr.is_lambda\n\nunsafe def is_pi : expr → Bool\n | pi _ _ _ _ => true\n | e => false\n#align expr.is_pi expr.is_pi\n\nunsafe def is_arrow : expr → Bool\n | pi _ _ _ b => not (has_var b)\n | e => false\n#align expr.is_arrow expr.is_arrow\n\nunsafe def is_let : expr → Bool\n | elet _ _ _ _ => true\n | e => false\n#align expr.is_let expr.is_let\n\n/-- The name of the bound variable in a pi, lambda or let expression. -/\nunsafe def binding_name : expr → Name\n | pi n _ _ _ => n\n | lam n _ _ _ => n\n | elet n _ _ _ => n\n | e => Name.anonymous\n#align expr.binding_name expr.binding_name\n\n/-- The binder info of a pi or lambda expression. -/\nunsafe def binding_info : expr → BinderInfo\n | pi _ bi _ _ => bi\n | lam _ bi _ _ => bi\n | e => BinderInfo.default\n#align expr.binding_info expr.binding_info\n\n/-- The domain (type of bound variable) of a pi, lambda or let expression. -/\nunsafe def binding_domain : expr → expr\n | pi _ _ d _ => d\n | lam _ _ d _ => d\n | elet _ d _ _ => d\n | e => e\n#align expr.binding_domain expr.binding_domain\n\n/-- The body of a pi, lambda or let expression.\n This definition doesn't instantiate bound variables, and therefore produces a term that is open.\n See note [open expressions] in mathlib. -/\nunsafe def binding_body : expr → expr\n | pi _ _ _ b => b\n | lam _ _ _ b => b\n | elet _ _ _ b => b\n | e => e\n#align expr.binding_body expr.binding_body\n\n/-- `nth_binding_body n e` iterates `binding_body` `n` times to an iterated pi expression `e`.\n This definition doesn't instantiate bound variables, and therefore produces a term that is open.\n See note [open expressions] in mathlib. -/\nunsafe def nth_binding_body : ℕ → expr → expr\n | n + 1, pi _ _ _ b => nth_binding_body n b\n | _, e => e\n#align expr.nth_binding_body expr.nth_binding_body\n\nunsafe def is_macro : expr → Bool\n | macro d a => true\n | e => false\n#align expr.is_macro expr.is_macro\n\nunsafe def is_numeral : expr → Bool\n | q(@Zero.zero $(α) $(s)) => true\n | q(@One.one $(α) $(s)) => true\n | q(@bit0 $(α) $(s) $(v)) => is_numeral v\n | q(@bit1 $(α) $(s₁) $(s₂) $(v)) => is_numeral v\n | _ => false\n#align expr.is_numeral expr.is_numeral\n\nunsafe def pi_arity : expr → ℕ\n | pi _ _ _ b => pi_arity b + 1\n | _ => 0\n#align expr.pi_arity expr.pi_arity\n\nunsafe def lam_arity : expr → ℕ\n | lam _ _ _ b => lam_arity b + 1\n | _ => 0\n#align expr.lam_arity expr.lam_arity\n\nunsafe def imp (a b : expr) : expr :=\n pi `_ BinderInfo.default a b\n#align expr.imp expr.imp\n\n/-- `lambdas cs e` lambda binds `e` with each of the local constants in `cs`. -/\nunsafe def lambdas : List expr → expr → expr\n | local_const uniq pp info t :: es, f => lam pp info t (abstract_local (lambdas es f) uniq)\n | _, f => f\n#align expr.lambdas expr.lambdas\n\n/-- Same as `expr.lambdas` but with `pi`. -/\nunsafe def pis : List expr → expr → expr\n | local_const uniq pp info t :: es, f => pi pp info t (abstract_local (pis es f) uniq)\n | _, f => f\n#align expr.pis expr.pis\n\nunsafe def extract_opt_auto_param : expr → expr\n | q(@optParam $(t) _) => extract_opt_auto_param t\n | q(@autoParam $(t) _) => extract_opt_auto_param t\n | e => e\n#align expr.extract_opt_auto_param expr.extract_opt_auto_param\n\nopen Format\n\nprivate unsafe def p : List format → format\n | [] => \"\"\n | [x] => x.paren\n | x :: y :: xs => p ((x ++ format.line ++ y).group :: xs)\n#align expr.p expr.p\n\nunsafe def to_raw_fmt : expr elab → format\n | var n => p [\"var\", to_fmt n]\n | sort l => p [\"sort\", to_fmt l]\n | const n ls => p [\"const\", to_fmt n, to_fmt ls]\n | mvar n m t => p [\"mvar\", to_fmt n, to_fmt m, to_raw_fmt t]\n | local_const n m bi t => p [\"local_const\", to_fmt n, to_fmt m, to_raw_fmt t]\n | app e f => p [\"app\", to_raw_fmt e, to_raw_fmt f]\n | lam n bi e t => p [\"lam\", to_fmt n, repr bi, to_raw_fmt e, to_raw_fmt t]\n | pi n bi e t => p [\"pi\", to_fmt n, repr bi, to_raw_fmt e, to_raw_fmt t]\n | elet n g e f => p [\"elet\", to_fmt n, to_raw_fmt g, to_raw_fmt e, to_raw_fmt f]\n | macro d args =>\n sbracket\n (format.join\n (List.intersperse \" \" (\"macro\" :: to_fmt (macro_def_name d) :: args.map to_raw_fmt)))\n#align expr.to_raw_fmt expr.to_raw_fmt\n\n/-- Fold an accumulator `a` over each subexpression in the expression `e`.\nThe `nat` passed to `fn` is the number of binders above the subexpression. -/\nunsafe def mfold {α : Type} {m : Type → Type} [Monad m] (e : expr) (a : α)\n (fn : expr → Nat → α → m α) : m α :=\n fold e (return a) fun e n a => a >>= fn e n\n#align expr.mfold expr.mfold\n\nend Expr\n\n/-- An dictionary from `data` to expressions. -/\n@[reducible]\nunsafe def expr_map (data : Type) :=\n rb_map expr data\n#align expr_map expr_map\n\nnamespace ExprMap\n\nexport\n Native.RbMap (mk_core size Empty insert eraseₓ contains find min max fold keys values toList mfold of_list set_of_list map for filterₓ)\n\nunsafe def mk (data : Type) : expr_map data :=\n rb_map.mk expr data\n#align expr_map.mk expr_map.mk\n\nend ExprMap\n\nunsafe def mk_expr_map {data : Type} : expr_map data :=\n expr_map.mk data\n#align mk_expr_map mk_expr_map\n\n@[reducible]\nunsafe def expr_set :=\n rb_set expr\n#align expr_set expr_set\n\nunsafe def mk_expr_set : expr_set :=\n mk_rb_set\n#align mk_expr_set mk_expr_set\n\n", "meta": {"author": "leanprover-community", "repo": "lean3port", "sha": "9ed1898f23e4379865ee93d62cb6353e5ed6c270", "save_path": "github-repos/lean/leanprover-community-lean3port", "path": "github-repos/lean/leanprover-community-lean3port/lean3port-9ed1898f23e4379865ee93d62cb6353e5ed6c270/Leanbin/Init/Meta/Expr.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2689414096510108, "lm_q2_score": 0.046033898309357744, "lm_q1q2_score": 0.012380421503049955}} {"text": "import ReactorModel.Objects.Reactor.Indexable\n\nnamespace ReactorType\nnamespace Indexable\n\nvariable [a : Indexable α]\n\nvariable {rtr rtr₁ rtr₂ : α}\n\ntheorem con?_eq_some (h : rtr[cpt][i]& = some con) : \n ∃ m : Member cpt i rtr, m.container = con := by\n simp [con?] at h\n split at h\n case inl n => exists n.some; injection h\n case inr => contradiction\n\ntheorem con?_to_obj?_and_cpt? (h : rtr[cpt][i]& = some con) :\n (rtr[.rtr][con.id] = con.rtr) ∧ ∃ o, (cpt? cpt con.rtr i = some o) := by\n sorry\n\ntheorem obj?_to_con?_and_cpt? {o} {i : ID} (h : rtr[cpt][i] = some o) :\n ∃ c, (rtr[cpt][i]& = some c) ∧ (cpt? cpt c.rtr i = some o) := by\n cases cpt\n all_goals \n simp [obj?, bind] at h\n assumption\n\ntheorem obj?_split {o} {i : ID} (h : rtr[cpt][i] = some o) :\n ∃ c con, (rtr[.rtr][c] = some con) ∧ (cpt? cpt con i = some o) := by\n have ⟨⟨c, con⟩, ho, _⟩ := obj?_to_con?_and_cpt? h \n have ⟨_, _, _⟩ := con?_to_obj?_and_cpt? ho\n exists c, con\n\ntheorem cpt?_to_con? {o} (h : cpt? cpt rtr i = some o) : rtr[cpt][i]& = some ⟨⊤, rtr⟩ := by\n let m := Member.final (Partial.mem_iff.mpr ⟨_, h⟩)\n simp [con?, Nonempty.intro m, ←a.unique_ids.allEq m, Member.container]\n\ntheorem cpt?_to_obj? {o} (h : cpt? cpt rtr i = some o) : rtr[cpt][i] = some o := by\n cases cpt\n all_goals \n simp [obj?, bind]\n exact ⟨⟨⊤, rtr⟩, cpt?_to_con? h, h⟩ \n\ntheorem con?_nested {c : ID} (h : nest rtr₁ i = some rtr₂) (ho : rtr₂[cpt][j]& = some ⟨c, con⟩) : \n rtr₁[cpt][j]& = some ⟨c, con⟩ := by\n simp [con?] at ho ⊢ \n split at ho\n case inr => contradiction\n case inl n =>\n set m := n.some\n cases hm : m\n case final hc =>\n simp [hm, Member.container] at ho\n case nest l₂ h₂ =>\n let l₁ := Member.nest h (.nest h₂ l₂)\n simp [hm, Member.container] at ho\n simp [Nonempty.intro l₁, ←a.unique_ids.allEq l₁, Member.container, ho]\n\ntheorem con?_eq_root (h : rtr[cpt][i]& = some ⟨⊤, con⟩) : rtr = con :=\n Member.container_eq_root (con?_eq_some h).choose_spec\n\ntheorem obj?_nested {o} {j : ID} (h : nest rtr₁ i = some rtr₂) (ho : rtr₂[cpt][j] = some o) : \n rtr₁[cpt][j] = some o := by\n cases cpt <;> try cases j\n all_goals\n simp [obj?, bind]\n have ⟨⟨c, con⟩, hc, ho⟩ := obj?_to_con?_and_cpt? ho \n cases c\n case some c => \n have := con?_nested h hc\n exists ⟨c, con⟩\n case none => \n replace hc := con?_eq_root hc\n simp at ho\n subst hc\n exists ⟨i, rtr₂⟩\n let m := Member.nest h (.final $ Partial.mem_iff.mpr ⟨_, ho⟩)\n simp [ho, con?, Nonempty.intro m, ←a.unique_ids.allEq m, Member.container]\n\n-- Note: By `ho` we get `rtr₂ = rtr₃`.\ntheorem obj?_nested_root (h : nest rtr₁ i = some rtr₂) (ho : rtr₂[.rtr][⊤] = some rtr₃) : \n ∃ j, rtr₁[.rtr][j] = some rtr₃ := by\n simp [obj?] at ho\n exact ⟨i, ho ▸ cpt?_to_obj? h⟩\n\n-- This is a version of `obj?_nested`, where we don't restrict `j` to be an `ID`. This makes a \n-- difference when `cpt = .rtr`. Note that if `cpt = .rtr` and `j = ⊤`, then `j' = .nest i`.\ntheorem obj?_nested' {o j} (h : nest rtr₁ i = some rtr₂) (ho : rtr₂[cpt][j] = some o) : \n ∃ j', rtr₁[cpt][j'] = some o := by\n cases cpt <;> try cases j\n case rtr.none => exact obj?_nested_root h ho\n all_goals exact ⟨_, obj?_nested h ho⟩\n\ntheorem obj?_mem_nested {j : ID} (h : nest rtr₁ i = some rtr₂) (hm : ↑j ∈ rtr₂[cpt]) : \n ↑j ∈ rtr₁[cpt] :=\n Partial.mem_iff.mpr ⟨_, obj?_nested h (Partial.mem_iff.mp hm).choose_spec⟩ \n\ntheorem mem_cpt?_rtr_eq (ho₁ : rtr[.rtr][c₁] = some con₁) (ho₂ : rtr[.rtr][c₂] = some con₂) \n (hc₁ : j ∈ cpt? cpt con₁) (hc₂ : j ∈ cpt? cpt con₂) : c₁ = c₂ := by\n cases c₁ <;> cases c₂\n case none.none => rfl\n case none.some => sorry\n case some.none => sorry\n case some.some =>\n -- TODO: We can build two `Member` instances here.\n -- One from ho₁ and hc₁ and one from ho₂ and hc₂.\n -- By `unique_ids` they are equal, from which we can extract that `c₁ = c₂`.\n -- The main difficulty is building the `Member` instances.\n sorry\n\ntheorem member_isEmpty_con?_none (h : IsEmpty (Member cpt i rtr)) : rtr[cpt][i]& = none := by\n cases cpt <;> simp [con?, not_nonempty_iff.mpr h]\n\ntheorem member_isEmpty_obj?_none (h : IsEmpty (Member cpt i rtr)) : rtr[cpt][i] = none := by\n cases cpt <;> simp [obj?, member_isEmpty_con?_none h, bind]\n\nend Indexable\n\nopen Indexable Updatable\n\nnamespace LawfulMemUpdate\n\nvariable [Indexable α] {rtr₁ : α}\n\ntheorem obj?_preserved (u : LawfulMemUpdate cpt i f rtr₁ rtr₂) (h : c ≠ cpt ∨ j ≠ i) : \n rtr₂[c][j] = rtr₁[c][j] := by\n -- TODO: We need to somehow distinguish whether [c][j] even identifies a component, and if so, \n -- whether it lives in the same reactor as [cpt][i].\n induction u\n case final e _ _ =>\n have := e (c := c) (j := j) (by simp [h])\n sorry\n case nest =>\n sorry\n\ntheorem obj?_some₁ (u : LawfulMemUpdate cpt i f rtr₁ rtr₂) : ∃ o, rtr₁[cpt][i] = some o := by\n induction u \n case final => exact ⟨_, cpt?_to_obj? ‹_›⟩\n case nest h _ _ hi => exact ⟨_, obj?_nested h hi.choose_spec⟩\n\ntheorem obj?_some₂ (u : LawfulMemUpdate cpt i f rtr₁ rtr₂) : ∃ o, rtr₂[cpt][i] = some o := by\n induction u \n case final => exact ⟨_, cpt?_to_obj? ‹_›⟩\n case nest h _ hi => exact ⟨_, obj?_nested h hi.choose_spec⟩\n\ntheorem obj?_updated (u : LawfulMemUpdate cpt i f rtr₁ rtr₂) : \n rtr₂[cpt][i] = f <$> rtr₁[cpt][i] := by\n induction u\n case final h₁ h₂ => \n rw [cpt?_to_obj? h₁, cpt?_to_obj? h₂, Option.map_some]\n case nest h₁ h₂ u hi =>\n have ⟨_, h₁'⟩ := u.obj?_some₁\n have ⟨_, h₂'⟩ := u.obj?_some₂\n rw [obj?_nested h₁ h₁', obj?_nested h₂ h₂']\n exact h₁' ▸ h₂' ▸ hi\n\nend LawfulMemUpdate\n\nnamespace LawfulUpdate\n\nvariable [Indexable α] {rtr₁ : α}\n\ntheorem obj?_preserved (h : c ≠ cpt ∨ j ≠ i) : \n (LawfulUpdate cpt i f rtr₁ rtr₂) → rtr₂[c][j] = rtr₁[c][j]\n | update u => u.obj?_preserved h\n | notMem _ h => h ▸ rfl\n\ntheorem obj?_updated : (LawfulUpdate cpt i f rtr₁ rtr₂) → rtr₂[cpt][i] = f <$> rtr₁[cpt][i]\n | update u => u.obj?_updated\n | notMem h e => by subst e; have h := member_isEmpty_obj?_none h; simp at h; simp [h]\n\nend LawfulUpdate\n\nnamespace LawfulUpdatable\n\nvariable [Indexable α] {rtr : α}\n\ntheorem obj?_preserved (h : c ≠ cpt ∨ j ≠ i) : (update rtr cpt i f)[c][j] = rtr[c][j] :=\n lawful rtr cpt i f |>.obj?_preserved h\n\ntheorem obj?_preserved_cpt (h : c ≠ cpt := by exact (nomatch ·)) : \n (update rtr cpt i f)[c][j] = rtr[c][j] :=\n obj?_preserved $ .inl h\n\ntheorem obj?_preserved_id {c : Reactor.Component.Valued} (h : j ≠ i) : \n (update rtr cpt i f)[c][j] = rtr[c][j] :=\n obj?_preserved $ .inr h\n\ntheorem obj?_updated {rtr : α} : (update rtr cpt i f)[cpt][i] = f <$> rtr[cpt][i] :=\n lawful rtr cpt i f |>.obj?_updated\n\nend LawfulUpdatable\nend ReactorType", "meta": {"author": "marcusrossel", "repo": "reactor-model", "sha": "f82fffb489b4352a0cc6bee964d44a142fee18ce", "save_path": "github-repos/lean/marcusrossel-reactor-model", "path": "github-repos/lean/marcusrossel-reactor-model/reactor-model-f82fffb489b4352a0cc6bee964d44a142fee18ce/src/ReactorModel/Objects/Reactor/Theorems/Indexable.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4416730203630096, "lm_q2_score": 0.028007518881951066, "lm_q1q2_score": 0.01237016545746535}} {"text": "import group_theory.coset ring_theory.ideals algebra.gcd_domain algebra.euclidean_domain data.int.modeq group_theory.quotient_group data.equiv.algebra group_theory.subgroup tactic.ring tactic.fin_cases tactic.tidy algebra.ring algebra.field linear_algebra.multivariate_polynomial\nopen tactic prod native environment interactive lean.parser ideal classical lattice declaration rbtree\ninfixl ` ⬝ ` := has_mul.mul\nnotation x`²`:99 := x⬝x\nnotation ` ` binders ` ↦ ` f:(scoped f, f) := f\nnotation `⟮` binders ` ↦ ` f:(scoped f, f) `⟯`:= f\n\ndef flip_over_2{A B C D}(f: A→B→C→D) := z x y ↦ f x y z\ninfixl ` @₁`:99 := flip\ninfixl ` @₂`:99 := flip_over_2\ninfixr ` ∘₂ `:80 := (∘)∘(∘)\n\ninstance decidable_bool{b:bool}: decidable b := by{cases b, apply is_false, simp, apply is_true, simp}\n\ninstance{X}: monoid(list X) := {\n\tone := [],\n\tmul := (++),\n\tone_mul := by safe,\n\tmul_one := list.append_nil,\n\tmul_assoc := list.append_assoc,\n}\n\ninstance endomonoid{t}: monoid(t → t) := {\n\tone := id,\n\tmul := (∘),\n\tmul_assoc := function.comp.assoc,\n\tone_mul := function.comp.left_id,\n\tmul_one := function.comp.right_id,\n}\n\n--option.cases_on has typing problems. \ndef option.maybe{A B}(no: B)(yes: A→B): option A → B\n| none := no\n| (some a) := yes a\n\ndef ifoldl_help{S T}(f: ℕ→S→T→T): ℕ → list S → T → T\n| i [] r := r\n| i (x::s) r := ifoldl_help (i+1) s (f i x r)\ndef list.ifoldl{S T}(f: ℕ→S→T→T) := ifoldl_help f 0\n\ndef list.imap{S T}(f: ℕ→S→T)(s: list S) := (s.ifoldl(list.cons ∘₂ f) []).reverse\n\nuniverse U\ndef list.mfilter_map{A B : Type U}{M}[monad M](f: A → M(option B)): list A → M(list B)\n| [] := pure[]\n| (a::s) := do\n\tfa ← f a,\n\ts' ← s.mfilter_map,\n\tpure(fa.maybe s' ⟮b ↦ b::s'⟯)\n\n@[simp] def map₂_default{X Z}(d)(f: X → X → Z): list X → list X → list Z\n| [] [] := []\n--| s l := f ((s.nth 0).get_or_else d) ((l.nth 0).get_or_else d) :: map₂_default s.tail l.tail\n| [] (y::ys) := f d y :: map₂_default [] ys\n| (x::xs) [] := f x d :: map₂_default xs []\n| (x::xs) (y::ys) := f x y :: map₂_default xs ys\n\ndef trim_tail{X}[decidable_eq X](x)(s: list X) := (s.reverse.drop_while(=x)).reverse\n\n--unique_pairs[xⱼ | j] = [(xᵢ,xⱼ) | im ⟩\ninstance decidable_lt[mo]: @decidable_rel monomial (<) := monomial.order.decidable\ninstance decidable_le[mo]: @decidable_rel monomial (≤) := by apply_instance\ninstance decidable_less: decidable_rel(@less o K) := _ _↦ by unfold less; apply_instance\n\ndef coef(m) := ((P.find(0,m)).get_or_else(0,m)).fst\n--Value 0 should not be inserted, but rbtree lacks removal rutines. Since full simplification will rebuild a polynomial from scratch, extra zeros should not add up too badly.\ndef update(m)(f: K→K): poly K := let k := f(coef P m) in P.insert(k,m)\n\ndef monom[mo](m): poly K := rbtree_of[m]less\ninstance[mo]: has_coe monomial (poly K) := ⟨ m↦ monom(1,m) ⟩\n\n--Let f' = (f; 0↦id). Then combine@₂f maps Σ pⱼ⬝mⱼ and Σ rⱼ⬝mⱼ to Σ f' pⱼ rⱼ ⬝ mⱼ (...assuming unsoundly that there's no explicit 0 coefficients...exact behavior depends on what the representation happens to be). \ndef combine(f: K→K→K): poly K := P.fold⟮p R' ↦ update R' p.snd (f p.fst)⟯ R\ndef map_poly(f: K→K): poly K := combine P P _↦f\n\ninstance[mo]: has_zero(poly K) := ⟨rbtree_of[]less⟩\ninstance[mo]: has_one(poly K) := ⟨monom(1,1)⟩\ninstance[mo]: has_add(poly K) := ⟨combine @₂(+)⟩\ninstance[mo]: has_neg(poly K) := ⟨map_poly @₁ k↦-k⟩\ninstance[mo]: has_sub(poly K) := ⟨ P R ↦ P + -R ⟩\ninstance[mo]: has_mul(poly K) := ⟨ P↦ fold⟮m↦ P.fold⟮n↦ (+monom(m⬝n))⟯⟯ @₁0 ⟩\ninstance[mo]: has_scalar K (poly K) := ⟨ k↦ map_poly @₁(⬝k) ⟩\ninstance[mo]: has_pow(poly K) ℕ := ⟨ P n ↦ (list.repeat P n).foldl(⬝)1 ⟩\n\ninstance[mo][has_repr K]: has_repr(poly K) := ⟨ P↦ match P.to_list.filter⟮p:K×_ ↦ p.fst ≠ 0⟯ with\n\t| [] := \"0\"\n\t| (m::ms) := ms.foldl⟮s p ↦ s ++\" + \"++ repr p.fst ++\" \"++ repr p.snd⟯ (repr m.fst ++\" \"++ repr m.snd)\nend⟩\n\ndef lead_term := (P.fold⟮p:K×_ ↦ option.maybe (if p.fst = 0 then none else some p) some⟯ none).maybe (0,1) id\ndef lead_coef := P.lead_term.fst\ndef lead_mono := P.lead_term.snd\n\ndef is0 := lead_coef P = 0\ninstance decidable_is0: decidable P.is0 := by unfold is0; apply_instance\n\ndef is_const := lead_mono P = 1\ninstance decidable_is_const: decidable P.is_const := by unfold is_const; apply_instance\n\n--This is ridiculous!\ninstance rbnode_eq{X}[eqX: decidable_eq X]: decidable_eq(rbnode X)\n| rbnode.leaf rbnode.leaf := is_true rfl\n| (rbnode.red_node l1 v1 r1) (rbnode.red_node l2 v2 r2) :=\n\tmatch eqX v1 v2 with \n\t| is_false v := is_false(by{by_contra a, injection a, contradiction})\n\t| is_true v := \n\t\tmatch rbnode_eq l1 l2 with\n\t\t| is_false l := is_false(by{by_contra a, injection a, contradiction})\n\t\t| is_true l := \n\t\t\tmatch rbnode_eq r1 r2 with\n\t\t\t| is_false r := is_false(by{by_contra a, injection a, contradiction})\n\t\t\t| is_true r := is_true(by rw[l,v,r])\n\t\t\tend\n\t\tend\n\tend\n| (rbnode.black_node l1 v1 r1) (rbnode.black_node l2 v2 r2) := \n\tmatch eqX v1 v2 with \n\t| is_false v := is_false(by{by_contra a, injection a, contradiction})\n\t| is_true v := \n\t\tmatch rbnode_eq l1 l2 with\n\t\t| is_false l := is_false(by{by_contra a, injection a, contradiction})\n\t\t| is_true l := \n\t\t\tmatch rbnode_eq r1 r2 with\n\t\t\t| is_false r := is_false(by{by_contra a, injection a, contradiction})\n\t\t\t| is_true r := is_true(by rw[l,v,r])\n\t\t\tend\n\t\tend\n\tend\n| rbnode.leaf (rbnode.red_node l1 v1 r1) := is_false(by by_contra; injection a)\n| rbnode.leaf (rbnode.black_node l1 v1 r1) := is_false(by by_contra; injection a)\n| (rbnode.red_node l1 v1 r1) rbnode.leaf := is_false(by by_contra; injection a)\n| (rbnode.red_node l1 v1 r1) (rbnode.black_node l2 v2 r2) := is_false(by by_contra; injection a)\n| (rbnode.black_node l1 v1 r1) rbnode.leaf := is_false(by by_contra; injection a)\n| (rbnode.black_node l1 v1 r1) (rbnode.red_node l2 v2 r2) := is_false(by by_contra; injection a)\n\ninstance[mo]: decidable_eq(poly K) := by apply_instance\ninstance[mo]: inhabited(poly K) := ⟨0⟩\n\nvariable [has_repr K]\ndef see{X Y}[has_repr X][has_repr Y](m:Y)(x:X) := _root_.trace (repr m ++ repr x) x\n\n\nprivate def proof[mo](K)[ring K] := list(poly K)\ndef poly_mem[mo](K)[ring K] := poly K × proof K\ndef polys[mo](K)[ring K] := list(poly_mem K)\n\ninstance hrp[mo]: has_repr(proof K) := by unfold proof; apply_instance--TODO remove after debug\n\ndef poly_mem.is0[mo](P: poly_mem K) := is0 P.fst\ninstance[mo](P: poly_mem K): decidable P.is0 := by unfold poly_mem.is0; apply_instance\ninstance evvk[mo]: inhabited(poly_mem K) := ⟨(0,[])⟩\n\n--Construct trivial proof by cloning a proof from non-empty list. \ndef proof_triv[mo](B: polys K. assumption): proof K := B.head.snd.map⟮_↦0⟯\ndef is_triv[mo]: proof K → bool\n| [] := tt\n| (p::ps) := is0 p ∧ is_triv ps\ndef proof_add[mo](p₁ p₂ : proof K)(f: poly K → poly K) := p₁.map₂(+) (p₂.map f)\n\n--Compute the S-polynomial of monic polynomials with membership proof. \ndef monicS[mo]: poly_mem K → poly_mem K → poly_mem K | (P,pP) (R,pR) := \n\tlet p:= lead_mono P, r:= lead_mono R, m:= p.lcm r, mp:= monom((1:K), m/p), mr:= monom((1:K), m/r) \n\tin (P⬝mp - R⬝mr, proof_add (pP.map(⬝mp)) pR(⬝(-mr)))\n\n\n--Accumulates proof to show that if P→R then R - P ∈ ⟨B⟩. \nmeta def simplify_leading_loop[mo](B: polys K): poly_mem K → poly_mem K |(P, proof) :=\n\tlet p := P.lead_mono in match B.filter((∣p)∘lead_mono∘fst) with\n\t\t| [] := (P, proof)\n\t\t| (b,prf)::_ := let c := -monom(lead_coef P, p / lead_mono b) in simplify_leading_loop(P + b⬝c, proof_add proof prf(⬝c))\nend\n--B must be a non-empty list of monic (and ≠0) polynomials.\nmeta def simplify_leading[mo](B: polys K)(P: poly_mem K): poly_mem K := \n\tmatch B.filter(is_const ∘ fst) with\n\t| (_,prf)::_ := (0, proof_add P.snd prf(⬝(-P.fst)))\n\t| _ := simplify_leading_loop B P\nend\n\nmeta def simplify_loop[mo](B): poly K → poly_mem K → poly_mem K | R P :=\n\tif P.is0 then (R, P.snd) else let (P,prf) := simplify_leading B P, p := monom P.lead_term in simplify_loop (R+p) (P-p, prf)\n--Return fully simplified R←P and proof that R - P ∈ ⟨B⟩. Input P comes without membership proof, because simplification should be applicable to arbitrary polynomials. \nmeta def simplify[mo](B: polys K)(P) := simplify_loop B 0 (P, proof_triv)\n\n\nvariable[field K]\n--scale_monic 0 := 0\ndef scale_monic[mo]: poly_mem K → poly_mem K | (P,prf) := let c := P.lead_coef ⁻¹ in (c•P, prf.map((•)c))\n\n\nmeta def simplify_basis_loop[mo](simp: polys K → poly_mem K → poly_mem K): ℕ → polys K → polys K\n| 0 B := B\n| l [] := sorry -- l ≤ B.length\n| l (P::B) := let \n\tP' := simp B P,\n\tB' := ite P'.is0 B (B++[scale_monic P'])\nin simplify_basis_loop(if is_triv(P.snd.map₂⟮x y ↦ x-y⟯ P'.snd) then l-1 else B'.length) B'\n\n--For each element of B, if S simplifies the leading term, then simplify additionally with other elements of the basis.\nmeta def simplify_basis_by[mo](S: poly_mem K)(B: polys K) := simplify_basis_loop⟮B P ↦ let P' := simplify_leading [S] P in if is_triv P'.snd then P else simplify_leading B P'⟯ B.length B\n\n--Interreduce B. \nmeta def simplify_basis[mo](B: polys K) := simplify_basis_loop(simplify_loop @₁0) B.length B\n\n\n--main loop\nprivate meta def go[mo]: polys K → list(poly_mem K × poly_mem K) → polys K\n| G [] := G\n| G ((p₁,p₂)::ps) := let S := scale_monic(simplify_leading G (monicS p₁ p₂))\n\tin if S.is0 then go G ps else let G := simplify_basis_by S G in go (S::G) (ps ++ G.map⟮P↦ (P,S)⟯)\n\nmeta def «Gröbner basis of»[mo](B: list(poly K)) := let B := B.filter(not∘is0), B1 := B.imap⟮i b ↦ scale_monic(b, (B.map⟮_↦(0: poly K)⟯).update_nth i 1)⟯ in simplify_basis(go B1 B1.unique_pairs)\nnotation `Gröbner_basis_of` := «Gröbner basis of»\n--Lean's letter recognition is broken! It is not just an implementation mistake, but it is even specified in an adhoc way – see https://leanprover.github.io/reference/lexical_structure.html#identifiers – which is incompatible with Unicode. Not only a huge number of letters is ignored but also some non-letters included (though correctly called just letterlike):\ndef ℡⅋℀ := \"Telephone sign ǝʇ “account” are letters only in Lean!\"\n--Inclusion of non-letters means that Lean can't be said to support a subset of Unicode. FYI: Unicode is about semantics of code points (numbers). UTF-8 is a character encoding (mapping between bytes and numbers) that Lean does use. Observations here hold at the time of writing and hopefully not in the future.\n\n\n--Tästä voisi johtaa tyyliin ringa-taktiikan. Sievennetään kaikkia ... hmm, miten sievennyskelpoiset lausekkeet määrätään? Kertoimien tulee olla kunnasta, mutta muuttujia saa käsitellä vain rengasoperaatioilla. Teoreettisesti nättiä olisi yleistää hieman ja ratkaista renkaiden ehdolliset sanaongelmat, mutta sehän edellyttäisi paljon lisää koodausta! \n--Sitten pitää ratkaista, miten termien triviaali sievennys kuten x+y-x=y hoidetaan. Koska tulos tiedetään aina, voidaan turvallisesti turvautua ring-taktiikkaan. \n--Luetaan tavoitetta kunnes vastaan tulee +,⬝,- (tärkeää on, että löydetään maksimaalinen termi sievennettäväksi—tämän pitäisi riittää siihen, koska tietenkään päälioperaatio ei tällöin voi olla jokin sellainen, jota ei osata käsitellä). Huom. - voi esiintyä sekä unaarisena että binäärisenä. Seuraavaksi tarkistetaan, että alitermi on kuntatyyppiä...mutta tämä rajoittaa käytettävyyttä melko merkittävästi. Teoriassa voisi vaatia, että tyyppi on vaihdannainen rengas ja K-moduli jonkin kunnan K suhteen, ja K:lta vaaditaan lisäksi päätettävä yhtyvyys. Jotta tästä teoriasta tulee käytäntöä, lienee vaadittava, että käyttäjä syöttää kunnan (ℚ voi olla oletusarvo).\n\nmeta def 𝔼(pre) := to_expr pre tt ff\n--meta def childs(e: expr) := (e.mfoldl⟮c s ↦ [list.cons s c]⟯ []).head\nmeta def childs: expr → list expr\n| (expr.app f p) := [f,p]\n| (expr.pi _ _ S T) := [S,T]\n| (expr.elet _ t v b) := [t,v,b] --Does this work with infer_type?\n| (expr.macro _ cs) := cs\n| _ := []\n\nnotation `~`x := pure x\nnotation `ᵘᵖ ` m := monad_lift m\n\n\n@[reducible] meta def ST := state_t (list expr) tactic\n--Run reaction if state is not [].\nmeta def if_not_found(reaction: ST unit): ST unit := do s ← state_t.get, when(s=[]) reaction\n\nmeta def fbs_loop{T}(t)(test: (expr → ST T) → expr → ST T)(atoms: rb_set expr): bool → expr → ST unit | layer's_top e :=\nwhen(¬ atoms.contains e) (test⟮x ↦ t<$\n\tif x≠e then fbs_loop ff x\n\telse (childs x).mmap'(if_not_found ∘ fbs_loop tt)\n⟯ e >> if_not_found(when layer's_top (test⟮e' ↦ when(e≠e') (state_t.put[e]) $>t⟯ e $>())))\n--Finds some minimal subterm accepted by test while treating terms in the set atoms as such. Parameter t is just an inhabitance proof.\nmeta def find_bottom_simplifiable{T}(t:T)(test)(atoms): expr → tactic(option expr) \n| e := prod.fst <$> (do\n\tfbs_loop t test atoms tt e,\n\tg ← state_t.get,\n\t~ g.nth 0\n).run[]\n\n\nmeta def prepare_loop{T}(var: ℕ→T)(test: (expr → ST T) → expr → ST T): expr → ST T | e :=\ntest⟮x ↦ if x≠e then prepare_loop x else do\n\tvs ← state_t.get,\n\tlet i := vs.index_of x,\n\twhen(i = vs.length) (state_t.put(vs++[x])) $> var i\n⟯e\n--Transform (top layer of) e to its T-representation according to test, with alien subterms replaced by variables generated from var with syntactic equality preserved. Second component of the return value is list of the replaced alien terms.\nmeta def prepare{T}(var: ℕ→T)(test)(e) := (prepare_loop var test e).run[]\n--Like mapping the above, but naming of the alien terms is consistent.\nmeta def prepares{T}(var: ℕ → T)(test)(es: list expr) := (es.mmap(prepare_loop var test)).run[]\n\n\nmeta def simplify_by_loop{T}(var: ℕ→T)(test: (expr → ST T) → expr → ST T)(simp: expr → T → tactic expr): rb_set expr → tactic unit | simplified := do\n\te ← target,\n\tx ← find_bottom_simplifiable (var 0) test simplified e,\n\tx.maybe(~())⟮x ↦ do\n\t\t(x',g) ← prepare var test x,\n\t\tproof ← simp x x',\n\t\trewrite_target proof,\n\t\t`(%%_ = %%s) ← infer_type proof,\n\t\tsimplify_by_loop(simplified.insert s)⟯\n\n--Warning: in practise this interface turned out to behave ugly! This is a simplifier skeleton whose advantage over simp is that pattern matching and rule selection can be done programmatically. (For example simp could often do nothing with a Gröbner basis represented as simplifying equations, because non-syntactic pattern matching is needed to use them.) This functions like simp only [...]. The actual (single step) simplifier is given as a parameter. Its operation is extended by searching the proof target for simplifiable terms and calling the simplifier for all of these bottom up.\n--Parameters\n--T: an auxiliarity term representation that the simplifier may choose as it likes.\n--var: a stream of distinct variables.\n--test recursor ∈ expr → a_monad T : transforms a top operation of an input term into T-representation calling recursor for the childs, or for the whole term if it is alien. See test_poly for an example.\n--simp: from original expression E and its T-representation produce a proof that E = simplified E. Failed: Variable var i should be represented by a metavariable whose name ends with mk_numeral i, (or var 0, ..., var n may be represented by quantifying ∀x₀...∀xₙ ???).\nmeta def simplify_by{T}(var: ℕ→T)(test)(simp) := simplify_by_loop var test simp mk_rb_set\n--Notes: Examining term structure and mapping it to T was combined into test. Original term is given to simp, because T-representation may be lossy. However if orig. rep. is needed (Gröbner bases avoid it by using ring), examination of it usually repeats. It even turned out that due to consistent alien term naming the second parameter of simp is practically useless. Currently test can work in ST, though safer would be to require polymorphicity over monad transformer on top of tactic. The tedious part (in addition to the core simplification in T) is producing the proof term in simp. Could this be simplified in a suitable monad?\n\n\nmeta def test_instance(i) := (𝔼 i >>= mk_instance) $> tt <|> ~ff\n\n\nmeta def test_poly[mo][reflected K](r: expr → ST(poly K))(e: expr): ST(poly K) := match e with\n| `(%%x ⬝ %%y) := (⬝) <$> r x <*> r y\n| `(%%x + %%y) := (+) <$> r x <*> r y\n| `(%%x - %%y) := ⟮x y ↦ x-y⟯ <$> r x <*> r y\n| `(- %%x) := ⟮x ↦ -x⟯ <$> r x\n| `(%%x ^ %%n) := do\n\tN ←ᵘᵖ infer_type n,\n\tif N ≠ `(ℕ) ∨ n.has_var ∨ n.has_local then r e\n\telse do n ←ᵘᵖ eval_expr ℕ n, (^n) <$> r x\n| e := do\n\tE ←ᵘᵖ infer_type e,\n\tif E ≠ reflect K ∨ e.has_var ∨ e.has_local then r e\n\telse do k ←ᵘᵖ eval_expr K e, ~monom(k,[])\nend\n\nmeta def test_poly_typed[mo][reflected K](M: option expr)(r: expr → ST(poly K))(e): ST(poly K) := do\n\tE ←ᵘᵖ infer_type e,\n\tok ← match M with some M := ~(E=M : bool)\n\t\t| _ :=ᵘᵖ band <$> test_instance``(ring %%E) <*> test_instance``(module %%(reflect K) %%E) end,\n\t(ite ok test_poly id) r e\n\n\n--X' i is the iᵗʰ variable \"Xᵢ\".\ndef X'[mo](i:ℕ): poly K := monom(1, ((list.cons 0)^i) [1])\n\n\nmeta def represent_mono[mo](r: has_reflect K)(M:expr)(vs: list expr)(m: monomial): tactic expr :=\n\tm.ifoldl ⟮x p e ↦ if p=0 then e else do e←e, 𝔼``(%%e ⬝ %%(vs.nth x).iget ^ %%(reflect p))⟯ (𝔼``(1:%%M))\n\nmeta def represent_poly[mo][r: has_reflect K](M:expr)(vs: list expr)(P: poly K): tactic expr :=\n\tP.fold ⟮m e ↦ let c:= m.fst in if c=0 then e else do e←e, mono ← represent_mono r M vs m.snd, 𝔼``(%%e + %%(reflect c)⬝%%mono)⟯ (𝔼``(0:%%M))\n--TODO Use module product • to multiply mono by c. Problem is that then ring doesn't work!\n\n\nmeta def local_equations_of_type(M) := do\n\tls ← local_context,\n\tls.mfilter⟮a ↦ do b ← infer_type a, match b with `(%%x = %%y) := do Y ← infer_type y, ~Y=M | _:=~ff end⟯\n\n\n--Return a proof of goal found by the given tactic solve.\nmeta def prove_by(solve: tactic unit)(goal: tactic expr) := do\n\tn ← get_unused_name,\n\tgoal >>= assert n,\n\tsolve,\n\tproof ← get_local n,\n\t--clear proof, --TODO How to clean the local context while keeping proof usable?\n\t~proof\n\nnamespace proof_building_blocks\nlemma mul_sub_is_0{M}[ring M][module K M]{x y O : M}(c: M)(o0: O=0)(h: x=y): O - c⬝(x-y) = 0 := by simp[*]\n\nlemma combines{M}[add_comm_group M][module K M]{P R O : M}(pr: P-R = O)(o0: O = 0): P = R := by rw(by simp : P = P-R + R);simp[*]\n\nend proof_building_blocks\nopen proof_building_blocks\n\n\n--Compute a Gröbner basis from polynomial equations E and return a reducer suitable for simplify_by that uses the computed basis.\nmeta def verifying_reducer[mo][reflected K][r: has_reflect K](M)(E: list expr): tactic(expr → poly K → tactic expr) := do\n\tlet test: (expr → ST(poly K)) → _ := test_poly_typed(option.some M),\n\tbe ← E.mmap⟮p ↦ do e ← infer_type p, match e with `(%%x = %%y) := 𝔼``(%%x - %%y) | _:=sorry end⟯,\n\t((B: list(poly K)), vs) ← prepares X' test be,\n\tlet G := Gröbner_basis_of B,\n~ pe _ ↦ do\t\n\t--TODO There should be nicer way to keep track of alien subterms. Either variables in polynomials should have arbitrary names (ideal solution) or everything should work inside ST.\n\t(P, vs) ← (prepare_loop X' test pe).run vs,\n\tlet (R, coef) := simplify G P,\n\t--R = P + coef•(fⱼ - gⱼ)ⱼ\n\t--P - R =ʳⁱⁿᵍ= -coef•(fⱼ - gⱼ)ⱼ = “coef•0” = 0 ⟹ P=R\n\tre ← represent_poly M vs R,\n\tce ← coef.mmap(represent_poly M vs),\n\tK0is0 ← 𝔼``(rfl : (0:%%(reflect K)) = 0),\n\tstep2 ← (ce.zip E).mfoldl ⟮prf cb ↦ 𝔼``(@mul_sub_is_0\n\t\t%%(reflect K) infer_instance infer_instance infer_instance infer_instance \n\t\t%%M infer_instance infer_instance \n\t\t_ _ _ %%cb.fst %%prf %%cb.snd)⟯ K0is0,\n\t`(%%ce_be = %%_) ← infer_type step2,\n\tring_step ← prove_by`[{ring}] (𝔼``(%%pe - %%re = %%ce_be)),\n\t𝔼``(@combines \n\t\t%%(reflect K) infer_instance infer_instance infer_instance infer_instance \n\t\t%%M infer_instance infer_instance \n\t\t_ _ _ %%ring_step %%step2)\n\n\nmeta def exactℚ := `[exact ℚ]\n\nmeta def ringa(K:Type. exactℚ)[reflected K][has_reflect K][field K][decidable_eq K][has_repr K/-debug-/][mo]: tactic unit := do\n\tt ← target,\n\t--\"find_top_simplifiable\" would be more expected behavior...if it existed\n\te ← find_bottom_simplifiable (0: poly K) (test_poly_typed none) mk_rb_set t,\n\tif e=none then fail\"nothing to simplify in target\" else do\n\tM ← infer_type e.iget,\n\tB ← local_equations_of_type M,\n\tif B=[] then `[ring] else do --Do not fail to preserve composability.\n\treducer ← verifying_reducer M B,\n\tsimplify_by (X': ℕ → poly K) (test_poly_typed(some M)) reducer,\n\t`[try{ring}]\n\n\n#check Gröbner_basis_of\n--Test cases\ninstance use_this_order := monomial.deg_lex\nvariables{v x y z : ℚ}{f: ℚ→ℚ}\n\n--These delegate to ring tactic\nexample: (x+y)⬝(x-y) = x² - y² := by ringa\nexample: f(2⬝x) = f(x+x) := by ringa\n--These don't\nexample(_:v=z): (x+y)⬝(x-y) = x² - y² := by ringa\nexample(_:v=z): f(2⬝x) = f(x+x) := by ringa\n\n--Core functionality tests\nexample(_: x+y = z)(_: x² + y² = z²): x⬝y = 0 := by ringa\nexample(_: x⬝y² = x+y)(_: x²⬝y = x² + y²): y^5 = (2⬝x-1)⬝(2⬝y-1)/2 - 1/2 := by ringa\nexample(_: x⬝y² = x+y)(_: x²⬝y = x+1): y = x² := by ringa\nexample(_: z⬝x=y)(_: y=x²)(_: v²=2): x⬝(2⬝z-x-x) = 0 := by ringa\nexample(_: x²⬝y = x²)(_: x⬝y² = y²): (x+y)⬝(x-y) + x² = x^3 := by ringa\n\n--Iteration tests\nexample(_: x=y): x⬝f(2⬝x² - y²) - y⬝f(x⬝y) = 0 := by ringa\nexample(_: x=y): x⬝f(x-y) - y⬝f(x-x) = 0 := by ringa\nexample(_: x=y+1): (x-1)⬝f(2⬝x-1) - y⬝f(x² - y²) = 0 := by ringa\nexample(_: x²+y² = z²)(_: x^3 + y^3 = z^3)(_: x⬝y = 1): f(x + y + f(2/3)) = f(f(z²) - 2⬝z) := by ringa\n\n--In algebras over ℚ\nopen polynomial\nexample{P: polynomial ℚ}(_: X² - X - 1 = (0: polynomial ℚ))(_: P = 1-X): P² = P+1 := by ringa\n\n\n--Is it worth to handle the situation of inconsistent axioms?\nexample(_: x²+3⬝x+1 = 0)(_: y²+3⬝y+1 = 0)(_: x^5 + y^5 = 0): x-y = 1 := by ringa\n#check ringa\n--∛2̅+̅√̅5̅ + ∛2̅-̅√̅5̅ = 1\n--example(_: x²=5)(_: y^3 = 2+x)(_: z^3 = 2-x): y+z = 1 := by ringa\n\nend poly\nopen poly\n\ninstance{K:Type}[field K][decidable_eq K][has_repr K][mo]: has_repr(poly_mem K) := \n--by unfold poly_mem; apply_instance\n⟨ x ↦ repr x.fst ⟩\ninstance{K:Type}[field K][decidable_eq K][has_repr K][mo]: has_repr(polys K) := by unfold polys; apply_instance\n\ninstance use_this := monomial.deg_lex\ndef lm(m: list ℕ): poly ℚ := monom(1,m)\n\ndef a := lm[2] +3⬝lm[1]+lm[]\ndef b := lm[0,2] +3⬝lm[0,1]+lm[]\ndef c := lm[5] + lm[0,5]\n#eval simplify(Gröbner_basis_of[a,b]) c\n--#eval Gröbner_basis_of[a,b,c] --Time out just because the algorithm is so slow!\n\ndef α := lm[0,0,2] + lm[0,2] - lm[2]\ndef β := lm[0,0,3] + lm[0,3] - lm[3]\ndef γ := lm[0,1,1] - 1\n#eval (Gröbner_basis_of[α,β,γ])\n#eval simplify(Gröbner_basis_of[α,β,γ]) (lm[2])\n\ndef P := lm[2,1] + ((1:ℚ)/2)•lm[2]\ndef R := lm[1,2] + lm[0,2]\ndef S := -lm[2,2] + lm[1,1] + lm[2]\n#eval (Gröbner_basis_of[P,R])\n#eval simplify (Gröbner_basis_of[P,R]) (S²)\n\ndef B := [lm [3] -1, lm[2]+lm[1,1], lm[2]+lm[1,0,1]+lm[0,0,2]]\n#eval B\n#eval Gröbner_basis_of B\n#eval P²⬝R\n#eval Gröbner_basis_of$ [lm [3] -1, lm[2]+lm[1,1], lm[2]+lm[1,0,1]+lm[0,0,2], lm [0,3] -1, lm[0,2]+lm[0,1,1]+lm[0,0,2], lm [0,0,3] -1].map(⬝1)\n#eval Gröbner_basis_of[lm [3] -1, lm[2]+lm[1,1]+lm[0,2], lm[2]+lm[1,0,1]+lm[0,0,2], lm [0,3] -1, lm[0,2]+lm[0,1,1]+lm[0,0,2], lm [0,0,3] -1]\n#eval Gröbner_basis_of(B++[P²⬝R])\n--#eval Gröbner_basis_of(P²⬝R::B)\n\n#eval (lm[] + 0).lead_coef\n#eval (2⬝lm[4,2] + lm[3,4])².fold((++)∘repr) \"\"\n#eval (2⬝lm[4,2] + lm[3,4])².lead_mono\n#eval (P + 3⬝P² + P²)²\n", "meta": {"author": "0function", "repo": "storage", "sha": "1a28fa3019003170c509b0c2badb85bd25319cd5", "save_path": "github-repos/lean/0function-storage", "path": "github-repos/lean/0function-storage/storage-1a28fa3019003170c509b0c2badb85bd25319cd5/Gröbner.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.373875808818685, "lm_q2_score": 0.033085981487302796, "lm_q1q2_score": 0.01237004808912537}} {"text": "import .ctypes .cop .globalenvs\n\n/- The Clight language: a simplified version of Compcert C where all\n expressions are pure and assignments and function calls are\n statements, not expressions. -/\n\nnamespace clight\nopen ctypes integers ast maps floats values memory word cop globalenvs\n errors ctypes.fundef ctypes.mode\n\n/- * Abstract syntax -/\n\n/- ** Expressions -/\n\n/- Clight expressions correspond to the \"pure\" subset of C expressions.\n The main omissions are string literals and assignment operators\n ([=], [+=], [++], etc). In Clight, assignment is a statement,\n not an expression. Additionally, an expression can also refer to\n temporary variables, which are a separate class of local variables\n that do not reside in memory and whose address cannot be taken.\n\n As in Compcert C, all expressions are annotated with their types,\n as needed to resolve operator overloading and type-dependent behaviors. -/\n\ninductive expr : Type\n| Econst_int : int32 → type → expr /- integer literal -/\n| Econst_float : float → type → expr /- double float literal -/\n| Econst_single : float32 → type → expr /- single float literal -/\n| Econst_long : int64 → type → expr /- long integer literal -/\n| Evar : ident → type → expr /- variable -/\n| Etempvar : ident → type → expr /- temporary variable -/\n| Ederef : expr → type → expr /- pointer dereference (unary [*]) -/\n| Eaddrof : expr → type → expr /- address-of operator ([&]) -/\n| Eunop : unary_operation → expr → type → expr /- unary operation -/\n| Ebinop : binary_operation → expr → expr → type → expr /- binary operation -/\n| Ecast : expr → type → expr /- type cast ([(ty) e]) -/\n| Efield : expr → ident → type → expr /- access to a member of a struct or union -/\n| Esizeof : type → type → expr /- size of a type -/\n| Ealignof : type → type → expr /- alignment of a type -/\nopen clight.expr\n\n/- Extract the type part of a type-annotated Clight expression. -/\n\ndef typeof : expr → type\n| (Econst_int _ ty) := ty\n| (Econst_float _ ty) := ty\n| (Econst_single _ ty) := ty\n| (Econst_long _ ty) := ty\n| (Evar _ ty) := ty\n| (Etempvar _ ty) := ty\n| (Ederef _ ty) := ty\n| (Eaddrof _ ty) := ty\n| (Eunop _ _ ty) := ty\n| (Ebinop _ _ _ ty) := ty\n| (Ecast _ ty) := ty\n| (Efield _ _ ty) := ty\n| (Esizeof _ ty) := ty\n| (Ealignof _ ty) := ty\n\n/- ** Statements -/\n\n/- Clight statements are similar to those of Compcert C, with the addition\n of assigment (of a rvalue to a lvalue), assignment to a temporary,\n and function call (with assignment of the result to a temporary).\n The three C loops are replaced by a single infinite loop [Sloop s1\n s2] that executes [s1] then [s2] repeatedly. A [continue] in [s1]\n branches to [s2]. -/\n\ndef label := ident\n\ninductive statement : Type\n| Sskip : statement /- do nothing -/\n| Sassign : expr → expr → statement /- assignment [lvalue = rvalue] -/\n| Sset : ident → expr → statement /- assignment [tempvar = rvalue] -/\n| Scall : option ident → expr → list expr → statement\n /- function call -/\n| Sbuiltin : option ident → external_function → list type → list expr → statement\n /- builtin invocation -/\n| Ssequence : statement → statement → statement\n /- sequence -/\n| Sifthenelse : expr → statement → statement → statement\n /- conditional -/\n| Sloop : statement → statement → statement\n /- infinite loop -/\n| Sbreak : statement /- [break] statement -/\n| Scontinue : statement /- [continue] statement -/\n| Sreturn : option expr → statement /- [return] statement -/\n| Sswitch : expr → list (option ℤ × statement) → statement\n /- [switch] statement -/\n /- [None] is [default], [Some x] is [case x] -/\n| Slabel : label → statement → statement\n| Sgoto : label → statement\nopen statement\n\n/- The C loops are derived forms. -/\n\ndef Swhile (e : expr) (s : statement) :=\nSloop (Ssequence (Sifthenelse e Sskip Sbreak) s) Sskip\n\ndef Sdowhile (s : statement) (e : expr) :=\nSloop s (Sifthenelse e Sskip Sbreak)\n\ndef Sfor (s1 : statement) (e2 : expr) (s3 : statement) (s4 : statement) :=\nSsequence s1 (Sloop (Ssequence (Sifthenelse e2 Sskip Sbreak) s3) s4)\n\n/- ** Functions -/\n\n/- A function definition is composed of its return type ([fn_return]),\n the names and types of its parameters ([fn_params]), the names\n and types of its local variables ([fn_vars]), and the body of the\n function (a statement, [fn_body]). -/\n\nstructure function : Type :=\n(return : type)\n(callconv : calling_convention)\n(params : list (ident × type))\n(vars : list (ident × type))\n(temps : list (ident × type))\n(body : statement)\n\n\ndef var_names (vars : list (ident × type)) : list ident :=\nlist.map prod.fst vars\n\n/- Functions can either be defined ([Internal]) or declared as\n external functions ([External]). -/\n\ndef fundef := ctypes.fundef function\n\n/- The type of a function definition. -/\n\ndef type_of_function (f : function) : type :=\nTfunction (type_of_params f.params) f.return f.callconv\n\ndef type_of_fundef : fundef → type\n| (Internal fd) := type_of_function fd\n| (External id args res cc) := Tfunction args res cc\n\n/- ** Programs -/\n\n/- As defined in module [Ctypes], a program, or compilation unit, is\n composed of:\n- a list of definitions of functions and global variables;\n- the names of functions and global variables that are public (not static);\n- the name of the function that acts as entry point (\"main\" function).\n- a list of definitions for structure and union names\n- the corresponding composite environment\n- a proof that this environment is consistent with the definitions. -/\n\ndef program := ctypes.program function\n\n/- * Operational semantics -/\n\n/- The semantics uses two environments. The global environment\n maps names of functions and global variables to memory block references,\n and function pointers to their definitions. (See module [Globalenvs].)\n It also contains a composite environment, used by type-dependent operations. -/\n\nstructure genv :=\n(genv : Genv fundef type)\n(cenv : composite_env)\n\ninstance coe_genv_genv : has_coe genv (Genv fundef type) := ⟨genv.genv⟩\ninstance coe_genv_cenv : has_coe genv composite_env := ⟨genv.cenv⟩\n\ndef globalenv (p : program) : genv :=\n{ genv := Genv.globalenv (program_of_program p),\n cenv := p.comp_env }\n\n/- The local environment maps local variables to block references and\n types. The current value of the variable is stored in the\n associated memory block. -/\n\ndef env := PTree (block × type). /- map variable -> location & type -/\n\ndef empty_env : env := (∅ : PTree (block × type))\n\n/- The temporary environment maps local temporaries to values. -/\n\ndef temp_env := PTree val\n\n/- [deref_loc ty m b ofs v] computes the value of a datum\n of type [ty] residing in memory [m] at block [b], offset [ofs].\n If the type [ty] indicates an access by value, the corresponding\n memory load is performed. If the type [ty] indicates an access by\n reference or by copy, the pointer [Vptr b ofs] is returned. -/\n\ninductive deref_loc (ty : type) (m : mem) (b : block) (ofs : ptrofs) : val → Prop\n| deref_loc_value (chunk v) :\n access_mode ty = By_value chunk →\n loadv chunk m (Vptr b ofs) = some v →\n deref_loc v\n| deref_loc_reference :\n access_mode ty = By_reference →\n deref_loc (Vptr b ofs)\n| deref_loc_copy :\n access_mode ty = By_copy →\n deref_loc (Vptr b ofs)\n\n/- Symmetrically, [assign_loc ty m b ofs v m'] returns the\n memory state after storing the value [v] in the datum\n of type [ty] residing in memory [m] at block [b], offset [ofs].\n This is allowed only if [ty] indicates an access by value or by copy.\n [m'] is the updated memory state. -/\n\ninductive assign_loc (ce : composite_env) (ty : type) (m : mem) (b : block) (ofs : ptrofs) :\n val → mem → Prop\n| assign_loc_value (v chunk m') :\n access_mode ty = By_value chunk →\n storev chunk m (Vptr b ofs) v = some m' →\n assign_loc v m'\n| assign_loc_copy (b' ofs' bytes m') :\n access_mode ty = By_copy →\n (sizeof ce ty > 0 →\n alignof_blockcopy ce ty ∣ unsigned ofs' ∧ \n alignof_blockcopy ce ty ∣ unsigned ofs) →\n b' ≠ b ∨ unsigned ofs' = unsigned ofs\n ∨ unsigned ofs' + sizeof ce ty ≤ unsigned ofs\n ∨ unsigned ofs + sizeof ce ty ≤ unsigned ofs' →\n load_bytes m b' (unsigned ofs') (sizeof ce ty) = some bytes →\n store_bytes m b (unsigned ofs) bytes = some m' →\n assign_loc (Vptr b' ofs') m'\n\nsection semantics\n\nparameter (ge : genv)\n\n/- Allocation of function-local variables.\n [alloc_variables e1 m1 vars e2 m2] allocates one memory block\n for each variable declared in [vars], and associates the variable\n name with this block. [e1] and [m1] are the initial local environment\n and memory state. [e2] and [m2] are the final local environment\n and memory state. -/\n\ninductive alloc_variables : env → mem → list (ident × type) → env → mem → Prop\n| nil (e m) : alloc_variables e m [] e m\n| cons (e) (m : mem) (id ty vars m2 e2) :\n alloc_variables (PTree.set id (m.nextblock, ty) e)\n (m.alloc 0 (sizeof ge ty)) vars e2 m2 →\n alloc_variables e m ((id, ty) :: vars) e2 m2\n\n/- Initialization of local variables that are parameters to a function.\n [bind_parameters e m1 params args m2] stores the values [args]\n in the memory blocks corresponding to the variables [params].\n [m1] is the initial memory state and [m2] the final memory state. -/\n\ninductive bind_parameters (e : env) : mem → list (ident × type) → list val → mem → Prop\n| nil (m) : bind_parameters m [] [] m\n| cons (m id ty params v1 vl b m1 m2) :\n PTree.get id e = some (b, ty) →\n assign_loc ge ty m b 0 v1 m1 →\n bind_parameters m1 params vl m2 →\n bind_parameters m ((id, ty) :: params) (v1 :: vl) m2\n\n/- Initialization of temporary variables -/\n\ndef create_undef_temps : list (ident × type) → temp_env\n| [] := (∅ : PTree val)\n| ((id, t) :: temps') := PTree.set id Vundef (create_undef_temps temps')\n\n/- Initialization of temporary variables that are parameters to a function. -/\n\ndef bind_parameter_temps : list (ident × type) → list val → temp_env → option temp_env\n | [] [] le := some le\n | ((id, t) :: xl) (v :: vl) le := bind_parameter_temps xl vl (PTree.set id v le)\n | _ _ _ := none\n\n/- Return the list of blocks in the codomain of [e], with low and high bounds. -/\n\ndef block_of_binding : ident × block × type → block × ℕ × ℕ\n| (id, b, ty) := (b, 0, sizeof ge ty)\n\ndef blocks_of_env (e : env) : list (block × ℕ × ℕ) :=\n(PTree.elements e).map block_of_binding\n\n/- Optional assignment to a temporary -/\n\ndef set_opttemp : option ident → val → temp_env → temp_env\n| none v le := le\n| (some id) v le := PTree.set id v le\n\n/- Selection of the appropriate case of a [switch], given the value [n]\n of the selector expression. -/\n\ndef labeled_statements := list (option ℤ × statement)\n\ndef select_switch_default : labeled_statements → labeled_statements\n| [] := []\n| ((none, s) :: sl') := ((none, s) :: sl')\n| ((some i, s) :: sl') := select_switch_default sl'\n\ndef select_switch_case (n : ℤ) : labeled_statements → option labeled_statements\n| [] := none\n| ((none, s) :: sl') := select_switch_case sl'\n| ((some i, s) :: sl') := if i = n then some ((some i, s) :: sl') else select_switch_case sl'\n\ndef select_switch (n : ℤ) (sl : labeled_statements) : labeled_statements :=\n(select_switch_case n sl).get_or_else (select_switch_default sl)\n\n/- Turn a labeled statement into a sequence -/\n\ndef seq_of_labeled_statement : labeled_statements → statement\n| [] := Sskip\n| ((_, s) :: sl') := Ssequence s (seq_of_labeled_statement sl')\n\n/- ** Evaluation of expressions -/\n\nsection expr\n\nparameters (e : env) (le : temp_env) (m : mem)\n\n/- [eval_expr ge e m a v] defines the evaluation of expression [a]\n in r-value position. [v] is the value of the expression.\n [e] is the current environment and [m] is the current memory state. -/\n\nmutual inductive eval_expr, eval_lvalue\nwith eval_expr : expr → val → Prop\n| eval_Econst_int (i ty) : eval_expr (Econst_int i ty) (Vint i)\n| eval_Econst_float (f ty) : eval_expr (Econst_float f ty) (Vfloat f)\n| eval_Econst_single (f ty) : eval_expr (Econst_single f ty) (Vsingle f)\n| eval_Econst_long (i ty) : eval_expr (Econst_long i ty) (Vlong i)\n| eval_Etempvar (id ty v) :\n (le^!id) = some v →\n eval_expr (Etempvar id ty) v\n| eval_Eaddrof (a ty loc ofs) :\n eval_lvalue a loc ofs →\n eval_expr (Eaddrof a ty) (Vptr loc ofs)\n| eval_Eunop (op a ty v1 v) :\n eval_expr a v1 →\n sem_unary_operation op m v1 (typeof a) = some v →\n eval_expr (Eunop op a ty) v\n| eval_Ebinop (op a1 a2 ty v1 v2 v) :\n eval_expr a1 v1 →\n eval_expr a2 v2 →\n sem_binary_operation ge op m v1 (typeof a1) v2 (typeof a2) = some v →\n eval_expr (Ebinop op a1 a2 ty) v\n| eval_Ecast (a ty v1 v) :\n eval_expr a v1 →\n sem_cast m v1 (typeof a) ty = some v →\n eval_expr (Ecast a ty) v\n| eval_Esizeof (ty1 ty) :\n eval_expr (Esizeof ty1 ty) (Vptrofs (repr (sizeof ge ty1)))\n| eval_Ealignof (ty1 ty) :\n eval_expr (Ealignof ty1 ty) (Vptrofs (repr (alignof ge ty1)))\n| eval_Elvalue (a loc ofs v) :\n eval_lvalue a loc ofs →\n deref_loc (typeof a) m loc ofs v →\n eval_expr a v\n\n/- [eval_lvalue ge e m a b ofs] defines the evaluation of expression [a]\n in l-value position. The result is the memory location [b, ofs]\n that contains the value of the expression [a]. -/\n\nwith eval_lvalue : expr → block → ptrofs → Prop\n| eval_Evar_local (id l ty) :\n (e^!id) = some (l, ty) →\n eval_lvalue (Evar id ty) l 0\n| eval_Evar_global (id l ty) :\n (e^!id) = none →\n Genv.find_symbol ge.genv id = some l →\n eval_lvalue (Evar id ty) l 0\n| eval_Ederef (a ty l ofs) :\n eval_expr a (Vptr l ofs) →\n eval_lvalue (Ederef a ty) l ofs\n | eval_Efield_struct (a i ty l ofs id co att delta) :\n eval_expr a (Vptr l ofs) →\n typeof a = Tstruct id att →\n (ge.cenv^!id) = some co →\n field_offset ge i co.co_members = OK delta →\n eval_lvalue (Efield a i ty) l (ofs + repr delta)\n | eval_Efield_union (a i ty l ofs id co att) :\n eval_expr a (Vptr l ofs) →\n typeof a = Tunion id att →\n (ge.cenv^!id) = some co →\n eval_lvalue (Efield a i ty) l ofs\n\n/- [eval_exprlist ge e m al tyl vl] evaluates a list of r-value\n expressions [al], cast their values to the types given in [tyl],\n and produces the list of cast values [vl]. It is used to\n evaluate the arguments of function calls. -/\n\ninductive eval_exprlist : list expr → list type → list val → Prop\n| nil : eval_exprlist [] [] []\n| cons (a bl ty tyl v1 v2 vl) :\n eval_expr a v1 →\n sem_cast m v1 (typeof a) ty = some v2 →\n eval_exprlist bl tyl vl →\n eval_exprlist (a :: bl) (ty :: tyl) (v2 :: vl)\n\nend expr\n\n/- ** Transition semantics for statements and functions -/\n\n/- Continuations -/\n\ninductive cont : Type\n| Kstop : cont\n| Kseq : statement → cont → cont /- [Kseq s2 k] = after [s1] in [s1;s2] -/\n| Kloop1 : statement → statement → cont → cont /- [Kloop1 s1 s2 k] = after [s1] in [Sloop s1 s2] -/\n| Kloop2 : statement → statement → cont → cont /- [Kloop1 s1 s2 k] = after [s2] in [Sloop s1 s2] -/\n| Kswitch : cont → cont /- catches [break] statements arising out of [switch] -/\n| Kcall : option ident → /- where to store result -/\n function → /- calling function -/\n env → /- local env of calling function -/\n temp_env → /- temporary env of calling function -/\n cont → cont\nopen cont\n\n/- Pop continuation until a call or stop -/\n\ndef call_cont : cont → cont\n| (Kseq s k) := call_cont k\n| (Kloop1 s1 s2 k) := call_cont k\n| (Kloop2 s1 s2 k) := call_cont k\n| (Kswitch k) := call_cont k\n| k := k\n\ndef is_call_cont : cont → bool\n| Kstop := tt\n| (Kcall _ _ _ _ _) := tt\n| _ := ff\n\n/- States -/\n\ninductive state : Type\n| State\n (f : function)\n (s : statement)\n (k : cont)\n (e : env)\n (le : temp_env)\n (m : mem)\n| Callstate\n (fd : fundef)\n (args : list val)\n (k : cont)\n (m : mem)\n| Returnstate\n (res : val)\n (k : cont)\n (m : mem)\n\n/- Find the statement and manufacture the continuation\n corresponding to a label -/\n\nmutual def find_label, find_label_ls (lbl : label)\nwith find_label : statement → cont → option (statement × cont)\n| (Ssequence s1 s2) := λk, find_label s1 (Kseq s2 k) <|> find_label s2 k\n| (Sifthenelse a s1 s2) := λk, find_label s1 k <|> find_label s2 k\n| (Sloop s1 s2) := λk, find_label s1 (Kloop1 s1 s2 k) <|> find_label s2 (Kloop2 s1 s2 k)\n| (Sswitch e sl) := λk, find_label_ls sl (Kswitch k)\n| (Slabel lbl' s') := λk, if lbl = lbl' then some (s', k) else find_label s' k\n| _ := λk, none\nwith find_label_ls : list (option ℤ × statement) → cont → option (statement × cont)\n| [] := λk, none\n| ((_, s) :: sl') := λk, find_label s (Kseq (seq_of_labeled_statement sl') k) <|> find_label_ls sl' k\n\n#exit\n/- Semantics for allocation of variables and binding of parameters at\n function entry. Two semantics are supported: one where\n parameters are local variables, reside in memory, and can have their address\n taken; the other where parameters are temporary variables and do not reside\n in memory. We parameterize the [step] transition relation over the\n parameter binding semantics, then instantiate it later to give the two\n semantics described above. -/\n\nparameter function_entry : function → list val → mem → env → temp_env → mem → Prop\n\n/- Transition relation -/\n\ninductive step : state → trace → state → Prop :=\n\n| step_assign : ∀ f a1 a2 k e le m loc ofs v2 v m',\n eval_lvalue e le m a1 loc ofs →\n eval_expr e le m a2 v2 →\n sem_cast v2 (typeof a2) (typeof a1) m = some v →\n assign_loc ge (typeof a1) m loc ofs v m' →\n step (State f (Sassign a1 a2) k e le m)\n E0 (State f Sskip k e le m')\n\n| step_set : ∀ f id a k e le m v,\n eval_expr e le m a v →\n step (State f (Sset id a) k e le m)\n E0 (State f Sskip k e (PTree.set id v le) m)\n\n| step_call : ∀ f optid a al k e le m tyargs tyres cconv vf vargs fd,\n classify_fun (typeof a) = fun_case_f tyargs tyres cconv →\n eval_expr e le m a vf →\n eval_exprlist e le m al tyargs vargs →\n Genv.find_funct ge vf = some fd →\n type_of_fundef fd = Tfunction tyargs tyres cconv →\n step (State f (Scall optid a al) k e le m)\n E0 (Callstate fd vargs (Kcall optid f e le k) m)\n\n| step_builtin : ∀ f optid ef tyargs al k e le m vargs t vres m',\n eval_exprlist e le m al tyargs vargs →\n external_call ef ge vargs m t vres m' →\n step (State f (Sbuiltin optid ef tyargs al) k e le m)\n t (State f Sskip k e (set_opttemp optid vres le) m')\n\n| step_seq : ∀ f s1 s2 k e le m,\n step (State f (Ssequence s1 s2) k e le m)\n E0 (State f s1 (Kseq s2 k) e le m)\n| step_skip_seq : ∀ f s k e le m,\n step (State f Sskip (Kseq s k) e le m)\n E0 (State f s k e le m)\n| step_continue_seq : ∀ f s k e le m,\n step (State f Scontinue (Kseq s k) e le m)\n E0 (State f Scontinue k e le m)\n| step_break_seq : ∀ f s k e le m,\n step (State f Sbreak (Kseq s k) e le m)\n E0 (State f Sbreak k e le m)\n\n| step_ifthenelse : ∀ f a s1 s2 k e le m v1 b,\n eval_expr e le m a v1 →\n bool_val v1 (typeof a) m = some b →\n step (State f (Sifthenelse a s1 s2) k e le m)\n E0 (State f (if b then s1 else s2) k e le m)\n\n| step_loop : ∀ f s1 s2 k e le m,\n step (State f (Sloop s1 s2) k e le m)\n E0 (State f s1 (Kloop1 s1 s2 k) e le m)\n| step_skip_or_continue_loop1 : ∀ f s1 s2 k e le m x,\n x = Sskip ∨ x = Scontinue →\n step (State f x (Kloop1 s1 s2 k) e le m)\n E0 (State f s2 (Kloop2 s1 s2 k) e le m)\n| step_break_loop1 : ∀ f s1 s2 k e le m,\n step (State f Sbreak (Kloop1 s1 s2 k) e le m)\n E0 (State f Sskip k e le m)\n| step_skip_loop2 : ∀ f s1 s2 k e le m,\n step (State f Sskip (Kloop2 s1 s2 k) e le m)\n E0 (State f (Sloop s1 s2) k e le m)\n| step_break_loop2 : ∀ f s1 s2 k e le m,\n step (State f Sbreak (Kloop2 s1 s2 k) e le m)\n E0 (State f Sskip k e le m)\n\n| step_return_0 : ∀ f k e le m m',\n Mem.free_list m (blocks_of_env e) = some m' →\n step (State f (Sreturn none) k e le m)\n E0 (Returnstate Vundef (call_cont k) m')\n| step_return_1 : ∀ f a k e le m v v' m',\n eval_expr e le m a v →\n sem_cast v (typeof a) f.(fn_return) m = some v' →\n Mem.free_list m (blocks_of_env e) = some m' →\n step (State f (Sreturn (some a)) k e le m)\n E0 (Returnstate v' (call_cont k) m')\n| step_skip_call : ∀ f k e le m m',\n is_call_cont k →\n Mem.free_list m (blocks_of_env e) = some m' →\n step (State f Sskip k e le m)\n E0 (Returnstate Vundef k m')\n\n| step_switch : ∀ f a sl k e le m v n,\n eval_expr e le m a v →\n sem_switch_arg v (typeof a) = some n →\n step (State f (Sswitch a sl) k e le m)\n E0 (State f (seq_of_labeled_statement (select_switch n sl)) (Kswitch k) e le m)\n| step_skip_break_switch : ∀ f x k e le m,\n x = Sskip ∨ x = Sbreak →\n step (State f x (Kswitch k) e le m)\n E0 (State f Sskip k e le m)\n| step_continue_switch : ∀ f k e le m,\n step (State f Scontinue (Kswitch k) e le m)\n E0 (State f Scontinue k e le m)\n\n| step_label : ∀ f lbl s k e le m,\n step (State f (Slabel lbl s) k e le m)\n E0 (State f s k e le m)\n\n| step_goto : ∀ f lbl k e le m s' k',\n find_label lbl f.(fn_body) (call_cont k) = some (s', k') →\n step (State f (Sgoto lbl) k e le m)\n E0 (State f s' k' e le m)\n\n| step_internal_function : ∀ f vargs k m e le m1,\n function_entry f vargs m e le m1 →\n step (Callstate (Internal f) vargs k m)\n E0 (State f f.(fn_body) k e le m1)\n\n| step_external_function : ∀ ef targs tres cconv vargs k m vres t m',\n external_call ef ge vargs m t vres m' →\n step (Callstate (External ef targs tres cconv) vargs k m)\n t (Returnstate vres k m')\n\n| step_returnstate : ∀ v optid f e le k m,\n step (Returnstate v (Kcall optid f e le k) m)\n E0 (State f Sskip k e (set_opttemp optid v le) m)\n\n/- ** Whole-program semantics -/\n\n/- Execution of whole programs are described as sequences of transitions\n from an initial state to a final state. An initial state is a [Callstate]\n corresponding to the invocation of the ``main'' function of the program\n without arguments and with an empty continuation. -/\n\ninductive initial_state (p : program) : state → Prop :=\n| initial_state_intro : ∀ b f m0,\n let ge := Genv.globalenv p in\n Genv.init_mem p = some m0 →\n Genv.find_symbol ge p.(prog_main) = some b →\n Genv.find_funct_ptr ge b = some f →\n type_of_fundef f = Tfunction Tnil type_int32s cc_default →\n initial_state p (Callstate f nil Kstop m0)\n\n/- A final state is a [Returnstate] with an empty continuation. -/\n\ninductive final_state : state → int32 → Prop :=\n| final_state_intro : ∀ r m,\n final_state (Returnstate (Vint r) Kstop m) r\n\nend SEMANTICS\n\n/- The two semantics for function parameters. First, parameters as local variables. -/\n\ninductive function_entry1 (ge : genv) (f : function) (vargs : list val) (m : mem) (e : env) (le : temp_env) (m' : mem) : Prop :=\n| function_entry1_intro : ∀ m1,\n list_norepet (var_names f.(fn_params) ++ var_names f.(fn_vars)) →\n alloc_variables ge empty_env m (f.(fn_params) ++ f.(fn_vars)) e m1 →\n bind_parameters ge e m1 f.(fn_params) vargs m' →\n le = create_undef_temps f.(fn_temps) →\n function_entry1 ge f vargs m e le m'\n\ndef step1 (ge : genv) := step ge (function_entry1 ge)\n\n/- Second, parameters as temporaries. -/\n\ninductive function_entry2 (ge : genv) (f : function) (vargs : list val) (m : mem) (e : env) (le : temp_env) (m' : mem) : Prop :=\n| function_entry2_intro :\n list_norepet (var_names f.(fn_vars)) →\n list_norepet (var_names f.(fn_params)) →\n list_disjoint (var_names f.(fn_params)) (var_names f.(fn_temps)) →\n alloc_variables ge empty_env m f.(fn_vars) e m' →\n bind_parameter_temps f.(fn_params) vargs (create_undef_temps f.(fn_temps)) = some le →\n function_entry2 ge f vargs m e le m'\n\ndef step2 (ge : genv) := step ge (function_entry2 ge)\n\n/- Wrapping up these definitions in two small-step semantics. -/\n\ndef semantics1 (p : program) :=\n let ge := globalenv p in\n Semantics_gen step1 (initial_state p) final_state ge ge\n\ndef semantics2 (p : program) :=\n let ge := globalenv p in\n Semantics_gen step2 (initial_state p) final_state ge ge\n\n/- This semantics is receptive to changes in events. -/\n\nlemma semantics_receptive :\n ∀ (p : program), receptive (semantics1 p)\nProof\n intros. unfold semantics1\n set (ge := globalenv p). constructor; simpl; intros\n/- receptiveness -/\n assert (t1 = E0 → ∃ s2, step1 ge s t2 s2)\n intros. subst. inv H0. ∃ s1; auto\n inversion H; subst; auto\n /- builtin -/\n exploit external_call_receptive; eauto. intros [vres2 [m2 EC2]]\n econstructor; econstructor; eauto\n /- external -/\n exploit external_call_receptive; eauto. intros [vres2 [m2 EC2]]\n ∃ (Returnstate vres2 k m2). econstructor; eauto\n/- trace length -/\n red; simpl; intros. inv H; simpl; try omega\n eapply external_call_trace_length; eauto\n eapply external_call_trace_length; eauto\nQed.", "meta": {"author": "digama0", "repo": "kremlin", "sha": "d4665929ce9012e93a0b05fc7063b96256bab86f", "save_path": "github-repos/lean/digama0-kremlin", "path": "github-repos/lean/digama0-kremlin/kremlin-d4665929ce9012e93a0b05fc7063b96256bab86f/clight.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3849121303722487, "lm_q2_score": 0.03210070717999101, "lm_q1q2_score": 0.012355951587106078}} {"text": "/-\nCopyright (c) 2018 Scott Morrison. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Scott Morrison, Mario Carneiro\n\n! This file was ported from Lean 3 source module tactic.chain\n! leanprover-community/mathlib commit a8629a591ccfe7aa27241e843ca13ed7ed7fd152\n! Please do not edit these lines, except to modify the commit id\n! if you have ported upstream changes.\n-/\nimport Mathbin.Tactic.Ext\n\nopen Interactive\n\nnamespace Tactic\n\n/-\nThis file defines a `chain` tactic, which takes a list of tactics,\nand exhaustively tries to apply them to the goals, until no tactic succeeds on any goal.\n\nAlong the way, it generates auxiliary declarations, in order to speed up elaboration time\nof the resulting (sometimes long!) proofs.\n\nThis tactic is used by the `tidy` tactic.\n-/\n-- α is the return type of our tactics. When `chain` is called by `tidy`, this is string,\n-- describing what that tactic did as an interactive tactic.\nvariable {α : Type}\n\ninductive TacticScript (α : Type) : Type\n | base : α → tactic_script\n | work (index : ℕ) (first : α) (later : List tactic_script) (closed : Bool) : tactic_script\n#align tactic.tactic_script Tactic.TacticScript\n\nunsafe def tactic_script.to_string : TacticScript String → String\n | tactic_script.base a => a\n | tactic_script.work n a l c =>\n \"work_on_goal \" ++ toString (n + 1) ++ \" { \" ++\n \", \".intercalate (a :: l.map tactic_script.to_string) ++\n \" }\"\n#align tactic.tactic_script.to_string tactic.tactic_script.to_string\n\nunsafe instance : ToString (TacticScript String) where toString s := s.toString\n\nunsafe instance tactic_script_unit_has_to_string : ToString (TacticScript Unit)\n where toString s := \"[chain tactic]\"\n#align tactic.tactic_script_unit_has_to_string tactic.tactic_script_unit_has_to_string\n\nunsafe def abstract_if_success (tac : expr → tactic α) (g : expr) : tactic α := do\n let type ← infer_type g\n let is_lemma ← is_prop type\n if is_lemma then\n -- there's no point making the abstraction, and indeed it's slower\n tac\n g\n else do\n let m ← mk_meta_var type\n let a ← tac m\n (do\n let val ← instantiate_mvars m\n guard (val = [])\n let c ← new_aux_decl_name\n let gs ← get_goals\n set_goals [g]\n add_aux_decl c type val ff >>= unify g\n set_goals gs) <|>\n unify m g\n return a\n#align tactic.abstract_if_success tactic.abstract_if_success\n\nmutual\n /--\n `chain_many tac` recursively tries `tac` on all goals, working depth-first on generated subgoals,\n until it no longer succeeds on any goal. `chain_many` automatically makes auxiliary definitions.\n -/\n unsafe def chain_single {α} (tac : tactic α) : expr → tactic (α × List (TacticScript α))\n | g => do\n set_goals [g]\n let a ← tac\n let l ← get_goals >>= chain_many\n return (a, l)\n /--\n `chain_many tac` recursively tries `tac` on all goals, working depth-first on generated subgoals,\n until it no longer succeeds on any goal. `chain_many` automatically makes auxiliary definitions.\n -/\n unsafe def chain_many {α} (tac : tactic α) : List expr → tactic (List (TacticScript α))\n | [] => return []\n | [g] =>\n (do\n let (a, l) ← chain_single g\n return (tactic_script.base a :: l)) <|>\n return []\n | gs => chain_iter gs []\n /--\n `chain_many tac` recursively tries `tac` on all goals, working depth-first on generated subgoals,\n until it no longer succeeds on any goal. `chain_many` automatically makes auxiliary definitions.\n -/\n unsafe def chain_iter {α} (tac : tactic α) :\n List expr → List expr → tactic (List (TacticScript α))\n | [], _ => return []\n | g :: later_goals, stuck_goals =>\n (-- we keep the goals up to date, so they are correct at the end\n do\n let (a, l) ← abstract_if_success chain_single g\n let new_goals ← get_goals\n let w := TacticScript.work stuck_goals.length a l (new_goals = [])\n let current_goals := stuck_goals.reverse ++ new_goals ++ later_goals\n set_goals current_goals\n let l' ← chain_many current_goals\n return (w :: l')) <|>\n chain_iter later_goals (g :: stuck_goals)\nend\n#align tactic.chain_single tactic.chain_single\n#align tactic.chain_many tactic.chain_many\n#align tactic.chain_iter tactic.chain_iter\n\nunsafe def chain_core {α : Type} [ToString (TacticScript α)] (tactics : List (tactic α)) :\n tactic (List String) := do\n let results ← get_goals >>= chain_many (first tactics)\n when results (fail \"`chain` tactic made no progress\")\n return (results toString)\n#align tactic.chain_core tactic.chain_core\n\nvariable [ToString (TacticScript α)] [has_to_format α]\n\ninitialize\n registerTraceClass.1 `chain\n\nunsafe def trace_output (t : tactic α) : tactic α := do\n let tgt ← target\n let r ← t\n let name ← decl_name\n trace f! \"`chain` successfully applied a tactic during elaboration of {Name}:\"\n let tgt ← pp tgt\n trace f! \"previous target: {tgt}\"\n trace f! \"tactic result: {r}\"\n let tgt ← try_core target\n let tgt ←\n match tgt with\n | some tgt => pp tgt\n | none => return \"no goals\"\n trace f! \"new target: {tgt}\"\n pure r\n#align tactic.trace_output tactic.trace_output\n\nunsafe def chain (tactics : List (tactic α)) : tactic (List String) :=\n chain_core (if is_trace_enabled_for `chain then tactics.map trace_output else tactics)\n#align tactic.chain tactic.chain\n\nend Tactic\n\n", "meta": {"author": "leanprover-community", "repo": "mathlib3port", "sha": "62505aa236c58c8559783b16d33e30df3daa54f4", "save_path": "github-repos/lean/leanprover-community-mathlib3port", "path": "github-repos/lean/leanprover-community-mathlib3port/mathlib3port-62505aa236c58c8559783b16d33e30df3daa54f4/Mathbin/Tactic/Chain.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.334589441253186, "lm_q2_score": 0.03676946726306205, "lm_q1q2_score": 0.012302675506725246}} {"text": "/- Copyright 2019 (c) Hans-Dieter Hiep. All rights reserved. Released under MIT license as described in the file LICENSE. -/\n\nimport history\n\nuniverse u\n\nopen objects interpret\n\n/- For class C we have a state space Σ(C) consisting of a this identity and an assignment of fields to values. -/\n@[derive decidable_eq]\nstructure state_space {α β : Type} [objects α β]\n (self : class_name α) :=\n (map (f : field_name self) : value (field_type f))\n (this : value (type.ref self))\n (N : value.not_null this)\ndef state_space.id {α β : Type} [objects α β]\n {self : class_name α} (σ : state_space self) : β :=\n value.the_object σ.N\nlemma state_space.class_of_id {α β : Type} [objects α β]\n {self : class_name α} (σ : state_space self) :\n class_of α σ.id = self :=\nbegin\n unfold state_space.id, apply value.class_of_the_object\nend\n/- A state space can be updated. -/\ndef state_space.update {α β : Type} [objects α β]\n {C : class_name α} (f : field_name C)\n (v : value (field_type f)) : state_space C → state_space C\n| ⟨map, this, N⟩ := ⟨λg, if H : f = g\n then cast begin rewrite H end v else map g,this,N⟩\n/- A state space can be updated, given a field variable in a typing environment related to the same class. -/\ndef state_space.updatev {α β : Type} [objects α β]\n {C : class_name α} {e : tenv C} {ty : type α}\n (fvar : fvar e ty) (v : value ty)\n (σ : state_space C) : state_space C :=\n σ.update fvar.idx (cast begin rewrite fvar.H end v)\nnotation Σ(C) := state_space C\n\n/- An active process consists of: a value list (of the arguments of the current method), a value list (of the local variables), and a list of statements. -/\n@[derive decidable_eq]\nstructure active_process {α β : Type} [objects α β]\n (C : class_name α) :=\n (e : tenv C)\n (args : vallist e.args) (store : vallist e.locals)\n (body : list (statement e))\n/- Given a state and active process, we can lookup the value of a read variable. -/\ndef active_process.lookup {α β : Type} [objects α β]\n {C : class_name α}\n (σ : Σ(C)) (π : active_process C)\n {tx : type α} : rvar π.e tx → value tx\n| (rvar.tvar t) := cast begin rewrite t.H end σ.this\n| (rvar.fvar f) := cast begin rewrite f.H end $ σ.map f.idx\n| (rvar.pvar p) := π.args.lookup p.idx\n| (rvar.lvar l) := π.store.lookup l.idx\n\n/- A process is either nil or an active process. -/\n@[derive decidable_eq]\ninductive process {α β : Type} [objects α β] (C : class_name α)\n| nil : process\n| active (a : active_process C) : process\n\n/- Evaluating a pure expression to a list of values. -/\ndef eval {α β : Type} [interpret α β]\n {C : class_name α}\n (σ : Σ(C)) (π : active_process C) :\n Π {l : list (type α)}, pexp π.e l → vallist l\n| _ (pexp.const .(π.e) sym) := vallist.single $\n (interp sym) vallist.nil\n| _ (pexp.app f r) := vallist.single $\n (interp f) (eval r)\n| _ (pexp.lookup r) := vallist.single (π.lookup σ r)\n| _ (pexp.equal l r) := vallist.single $ value.term $\n cast data_type_booleanr $ to_bool (eval l = eval r)\n| _ (pexp.cons h t) := vallist.consl (eval h) (eval t)\n\n/- Given a method and arguments, we can activate a process. -/\ndef process.activate {α β : Type} [objects α β]\n (p : program α) (c : class_name α) (m : method_name c)\n (τ : vallist (param_types m)) : process c :=\n process.active ⟨(p.body m).tenv,τ,default _,(p.body m).S⟩\n\ndef process.schedule {α β : Type} [interpret α β]\n (pr : program α) {θ : global_history α β}\n {C : class_name α} (σ : Σ(C)) (d : callsite α β)\n (H : global_history.sched θ (state_space.id σ) = some d)\n : process C :=\n callsite.elim d (λc o m τ g,\n let p := process.activate pr c m τ,\n G : process c = process C := begin\n have F : state_space.id σ = o.val,\n apply eq.symm,\n apply global_history.sched_object θ (σ.id) ⟨o,m,τ⟩,\n rw ← g, apply H,\n rewrite o.property,\n rewrite ← F,\n rewrite state_space.class_of_id\n end\n in cast G p)\n", "meta": {"author": "praalhans", "repo": "lean-abs", "sha": "5d23eec7234c880f5ebc0d7b831caf55119edef8", "save_path": "github-repos/lean/praalhans-lean-abs", "path": "github-repos/lean/praalhans-lean-abs/lean-abs-5d23eec7234c880f5ebc0d7b831caf55119edef8/src/process.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3886180267058489, "lm_q2_score": 0.03161876692645126, "lm_q1q2_score": 0.012287622809829648}} {"text": "/-\nCopyright (c) 2017 Mario Carneiro. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Mario Carneiro\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.default\nimport Mathlib.tactic.basic\nimport Mathlib.PostPort\n\nuniverses u_1 u_2 u_3 \n\nnamespace Mathlib\n\nnamespace option\n\n\ntheorem coe_def {α : Type u_1} : coe = some :=\n rfl\n\ntheorem some_ne_none {α : Type u_1} (x : α) : some x ≠ none :=\n fun (h : some x = none) => option.no_confusion h\n\n@[simp] theorem get_mem {α : Type u_1} {o : Option α} (h : ↥(is_some o)) : get h ∈ o :=\n option.cases_on o\n (fun (h : ↥(is_some none)) => eq.dcases_on h (fun (a : tt = false) => bool.no_confusion a) (Eq.refl tt) (HEq.refl h))\n (fun (o : α) (h : ↥(is_some (some o))) => idRhs (some o = some o) rfl) h\n\ntheorem get_of_mem {α : Type u_1} {a : α} {o : Option α} (h : ↥(is_some o)) : a ∈ o → get h = a := sorry\n\n@[simp] theorem not_mem_none {α : Type u_1} (a : α) : ¬a ∈ none :=\n fun (h : a ∈ none) => option.no_confusion h\n\n@[simp] theorem some_get {α : Type u_1} {x : Option α} (h : ↥(is_some x)) : some (get h) = x :=\n option.cases_on x\n (fun (h : ↥(is_some none)) => eq.dcases_on h (fun (a : tt = false) => bool.no_confusion a) (Eq.refl tt) (HEq.refl h))\n (fun (x : α) (h : ↥(is_some (some x))) => idRhs (some (get h) = some (get h)) rfl) h\n\n@[simp] theorem get_some {α : Type u_1} (x : α) (h : ↥(is_some (some x))) : get h = x :=\n rfl\n\n@[simp] theorem get_or_else_some {α : Type u_1} (x : α) (y : α) : get_or_else (some x) y = x :=\n rfl\n\n@[simp] theorem get_or_else_coe {α : Type u_1} (x : α) (y : α) : get_or_else (↑x) y = x :=\n rfl\n\ntheorem get_or_else_of_ne_none {α : Type u_1} {x : Option α} (hx : x ≠ none) (y : α) : some (get_or_else x y) = x := sorry\n\ntheorem mem_unique {α : Type u_1} {o : Option α} {a : α} {b : α} (ha : a ∈ o) (hb : b ∈ o) : a = b :=\n some.inj (Eq.trans (Eq.symm ha) hb)\n\ntheorem some_injective (α : Type u_1) : function.injective some :=\n fun (_x _x_1 : α) => iff.mp some_inj\n\n/-- `option.map f` is injective if `f` is injective. -/\ntheorem map_injective {α : Type u_1} {β : Type u_2} {f : α → β} (Hf : function.injective f) : function.injective (option.map f) := sorry\n\ntheorem ext {α : Type u_1} {o₁ : Option α} {o₂ : Option α} : (∀ (a : α), a ∈ o₁ ↔ a ∈ o₂) → o₁ = o₂ := sorry\n\ntheorem eq_none_iff_forall_not_mem {α : Type u_1} {o : Option α} : o = none ↔ ∀ (a : α), ¬a ∈ o := sorry\n\n@[simp] theorem none_bind {α : Type u_1} {β : Type u_1} (f : α → Option β) : none >>= f = none :=\n rfl\n\n@[simp] theorem some_bind {α : Type u_1} {β : Type u_1} (a : α) (f : α → Option β) : some a >>= f = f a :=\n rfl\n\n@[simp] theorem none_bind' {α : Type u_1} {β : Type u_2} (f : α → Option β) : option.bind none f = none :=\n rfl\n\n@[simp] theorem some_bind' {α : Type u_1} {β : Type u_2} (a : α) (f : α → Option β) : option.bind (some a) f = f a :=\n rfl\n\n@[simp] theorem bind_some {α : Type u_1} (x : Option α) : x >>= some = x :=\n bind_pure\n\n@[simp] theorem bind_eq_some {α : Type u_1} {β : Type u_1} {x : Option α} {f : α → Option β} {b : β} : x >>= f = some b ↔ ∃ (a : α), x = some a ∧ f a = some b := sorry\n\n@[simp] theorem bind_eq_some' {α : Type u_1} {β : Type u_2} {x : Option α} {f : α → Option β} {b : β} : option.bind x f = some b ↔ ∃ (a : α), x = some a ∧ f a = some b := sorry\n\n@[simp] theorem bind_eq_none' {α : Type u_1} {β : Type u_2} {o : Option α} {f : α → Option β} : option.bind o f = none ↔ ∀ (b : β) (a : α), a ∈ o → ¬b ∈ f a := sorry\n\n@[simp] theorem bind_eq_none {α : Type u_1} {β : Type u_1} {o : Option α} {f : α → Option β} : o >>= f = none ↔ ∀ (b : β) (a : α), a ∈ o → ¬b ∈ f a :=\n bind_eq_none'\n\ntheorem bind_comm {α : Type u_1} {β : Type u_2} {γ : Type u_3} {f : α → β → Option γ} (a : Option α) (b : Option β) : (option.bind a fun (x : α) => option.bind b (f x)) = option.bind b fun (y : β) => option.bind a fun (x : α) => f x y := sorry\n\ntheorem bind_assoc {α : Type u_1} {β : Type u_2} {γ : Type u_3} (x : Option α) (f : α → Option β) (g : β → Option γ) : option.bind (option.bind x f) g = option.bind x fun (y : α) => option.bind (f y) g :=\n option.cases_on x (Eq.refl (option.bind (option.bind none f) g))\n fun (x : α) => Eq.refl (option.bind (option.bind (some x) f) g)\n\ntheorem join_eq_some {α : Type u_1} {x : Option (Option α)} {a : α} : join x = some a ↔ x = some (some a) := sorry\n\ntheorem join_ne_none {α : Type u_1} {x : Option (Option α)} : join x ≠ none ↔ ∃ (z : α), x = some (some z) := sorry\n\ntheorem join_ne_none' {α : Type u_1} {x : Option (Option α)} : ¬join x = none ↔ ∃ (z : α), x = some (some z) := sorry\n\ntheorem bind_id_eq_join {α : Type u_1} {x : Option (Option α)} : x >>= id = join x := sorry\n\ntheorem join_eq_join {α : Type u_1} : mjoin = join := sorry\n\ntheorem bind_eq_bind {α : Type u_1} {β : Type u_1} {f : α → Option β} {x : Option α} : x >>= f = option.bind x f :=\n rfl\n\n@[simp] theorem map_eq_map {α : Type u_1} {β : Type u_1} {f : α → β} : Functor.map f = option.map f :=\n rfl\n\ntheorem map_none {α : Type u_1} {β : Type u_1} {f : α → β} : f <$> none = none :=\n rfl\n\ntheorem map_some {α : Type u_1} {β : Type u_1} {a : α} {f : α → β} : f <$> some a = some (f a) :=\n rfl\n\n@[simp] theorem map_none' {α : Type u_1} {β : Type u_2} {f : α → β} : option.map f none = none :=\n rfl\n\n@[simp] theorem map_some' {α : Type u_1} {β : Type u_2} {a : α} {f : α → β} : option.map f (some a) = some (f a) :=\n rfl\n\ntheorem map_eq_some {α : Type u_1} {β : Type u_1} {x : Option α} {f : α → β} {b : β} : f <$> x = some b ↔ ∃ (a : α), x = some a ∧ f a = b := sorry\n\n@[simp] theorem map_eq_some' {α : Type u_1} {β : Type u_2} {x : Option α} {f : α → β} {b : β} : option.map f x = some b ↔ ∃ (a : α), x = some a ∧ f a = b := sorry\n\ntheorem map_eq_none {α : Type u_1} {β : Type u_1} {x : Option α} {f : α → β} : f <$> x = none ↔ x = none := sorry\n\n@[simp] theorem map_eq_none' {α : Type u_1} {β : Type u_2} {x : Option α} {f : α → β} : option.map f x = none ↔ x = none := sorry\n\ntheorem map_congr {α : Type u_1} {β : Type u_2} {f : α → β} {g : α → β} {x : Option α} (h : ∀ (a : α), a ∈ x → f a = g a) : option.map f x = option.map g x := sorry\n\n@[simp] theorem map_id' {α : Type u_1} : option.map id = id :=\n map_id\n\n@[simp] theorem map_map {α : Type u_1} {β : Type u_2} {γ : Type u_3} (h : β → γ) (g : α → β) (x : Option α) : option.map h (option.map g x) = option.map (h ∘ g) x := sorry\n\ntheorem comp_map {α : Type u_1} {β : Type u_2} {γ : Type u_3} (h : β → γ) (g : α → β) (x : Option α) : option.map (h ∘ g) x = option.map h (option.map g x) :=\n Eq.symm (map_map h g x)\n\n@[simp] theorem map_comp_map {α : Type u_1} {β : Type u_2} {γ : Type u_3} (f : α → β) (g : β → γ) : option.map g ∘ option.map f = option.map (g ∘ f) := sorry\n\ntheorem mem_map_of_mem {α : Type u_1} {β : Type u_2} {a : α} {x : Option α} (g : α → β) (h : a ∈ x) : g a ∈ option.map g x :=\n iff.mpr mem_def (Eq.symm (iff.mp mem_def h) ▸ map_some')\n\ntheorem bind_map_comm {α : Type u_1} {β : Type u_1} {x : Option (Option α)} {f : α → β} : x >>= option.map f = option.map (option.map f) x >>= id := sorry\n\ntheorem join_map_eq_map_join {α : Type u_1} {β : Type u_2} {f : α → β} {x : Option (Option α)} : join (option.map (option.map f) x) = option.map f (join x) := sorry\n\ntheorem join_join {α : Type u_1} {x : Option (Option (Option α))} : join (join x) = join (option.map join x) := sorry\n\ntheorem mem_of_mem_join {α : Type u_1} {a : α} {x : Option (Option α)} (h : a ∈ join x) : some a ∈ x :=\n iff.mpr mem_def (Eq.symm (iff.mp mem_def h) ▸ iff.mp join_eq_some h)\n\n@[simp] theorem pbind_eq_bind {α : Type u_1} {β : Type u_2} (f : α → Option β) (x : Option α) : (pbind x fun (a : α) (_x : a ∈ x) => f a) = option.bind x f := sorry\n\ntheorem map_bind {α : Type u_1} {β : Type u_1} {γ : Type u_1} (f : β → γ) (x : Option α) (g : α → Option β) : option.map f (x >>= g) =\n do \n let a ← x \n option.map f (g a) := sorry\n\ntheorem map_bind' {α : Type u_1} {β : Type u_2} {γ : Type u_3} (f : β → γ) (x : Option α) (g : α → Option β) : option.map f (option.bind x g) = option.bind x fun (a : α) => option.map f (g a) := sorry\n\ntheorem map_pbind {α : Type u_1} {β : Type u_2} {γ : Type u_3} (f : β → γ) (x : Option α) (g : (a : α) → a ∈ x → Option β) : option.map f (pbind x g) = pbind x fun (a : α) (H : a ∈ x) => option.map f (g a H) := sorry\n\ntheorem pbind_map {α : Type u_1} {β : Type u_2} {γ : Type u_3} (f : α → β) (x : Option α) (g : (b : β) → b ∈ option.map f x → Option γ) : pbind (option.map f x) g = pbind x fun (a : α) (h : a ∈ x) => g (f a) (mem_map_of_mem f h) :=\n option.cases_on x (fun (g : (b : β) → b ∈ option.map f none → Option γ) => Eq.refl (pbind (option.map f none) g))\n (fun (x : α) (g : (b : β) → b ∈ option.map f (some x) → Option γ) => Eq.refl (pbind (option.map f (some x)) g)) g\n\n@[simp] theorem pmap_none {α : Type u_1} {β : Type u_2} {p : α → Prop} (f : (a : α) → p a → β) {H : ∀ (a : α), a ∈ none → p a} : pmap f none H = none :=\n rfl\n\n@[simp] theorem pmap_some {α : Type u_1} {β : Type u_2} {p : α → Prop} (f : (a : α) → p a → β) {x : α} (h : p x) : pmap f (some x) = fun (_x : ∀ (a : α), a ∈ some x → p a) => some (f x h) :=\n rfl\n\ntheorem mem_pmem {α : Type u_1} {β : Type u_2} {p : α → Prop} (f : (a : α) → p a → β) (x : Option α) {a : α} (h : ∀ (a : α), a ∈ x → p a) (ha : a ∈ x) : f a (h a ha) ∈ pmap f x h :=\n eq.mpr (id (Eq._oldrec (Eq.refl (f a (h a ha) ∈ pmap f x h)) (propext mem_def)))\n (Eq._oldrec (fun (h : ∀ (a_1 : α), a_1 ∈ some a → p a_1) (ha : a ∈ some a) => Eq.refl (pmap f (some a) h))\n (Eq.symm (eq.mp (Eq._oldrec (Eq.refl (a ∈ x)) (propext mem_def)) ha)) h ha)\n\ntheorem pmap_map {α : Type u_1} {β : Type u_2} {γ : Type u_3} {p : α → Prop} (f : (a : α) → p a → β) (g : γ → α) (x : Option γ) (H : ∀ (a : α), a ∈ option.map g x → p a) : pmap f (option.map g x) H =\n pmap (fun (a : γ) (h : p (g a)) => f (g a) h) x fun (a : γ) (h : a ∈ x) => H (g a) (mem_map_of_mem g h) := sorry\n\ntheorem map_pmap {α : Type u_1} {β : Type u_2} {γ : Type u_3} {p : α → Prop} (g : β → γ) (f : (a : α) → p a → β) (x : Option α) (H : ∀ (a : α), a ∈ x → p a) : option.map g (pmap f x H) = pmap (fun (a : α) (h : p a) => g (f a h)) x H := sorry\n\n@[simp] theorem pmap_eq_map {α : Type u_1} {β : Type u_2} (p : α → Prop) (f : α → β) (x : Option α) (H : ∀ (a : α), a ∈ x → p a) : pmap (fun (a : α) (_x : p a) => f a) x H = option.map f x := sorry\n\ntheorem pmap_bind {α : Type u_1} {β : Type u_1} {γ : Type u_1} {x : Option α} {g : α → Option β} {p : β → Prop} {f : (b : β) → p b → γ} (H : ∀ (a : β), a ∈ x >>= g → p a) (H' : ∀ (a : α) (b : β), b ∈ g a → b ∈ x >>= g) : pmap f (x >>= g) H =\n do \n let a ← x \n pmap f (g a) fun (b : β) (h : b ∈ g a) => H b (H' a b h) := sorry\n\ntheorem bind_pmap {α : Type u_1} {β : Type u_2} {γ : Type u_2} {p : α → Prop} (f : (a : α) → p a → β) (x : Option α) (g : β → Option γ) (H : ∀ (a : α), a ∈ x → p a) : pmap f x H >>= g = pbind x fun (a : α) (h : a ∈ x) => g (f a (H a h)) := sorry\n\ntheorem pbind_eq_none {α : Type u_1} {β : Type u_2} {x : Option α} {f : (a : α) → a ∈ x → Option β} (h' : ∀ (a : α) (H : a ∈ x), f a H = none → x = none) : pbind x f = none ↔ x = none := sorry\n\ntheorem pbind_eq_some {α : Type u_1} {β : Type u_2} {x : Option α} {f : (a : α) → a ∈ x → Option β} {y : β} : pbind x f = some y ↔ ∃ (z : α), ∃ (H : z ∈ x), f z H = some y := sorry\n\n@[simp] theorem pmap_eq_none_iff {α : Type u_1} {β : Type u_2} {p : α → Prop} {f : (a : α) → p a → β} {x : Option α} {h : ∀ (a : α), a ∈ x → p a} : pmap f x h = none ↔ x = none := sorry\n\n@[simp] theorem pmap_eq_some_iff {α : Type u_1} {β : Type u_2} {p : α → Prop} {f : (a : α) → p a → β} {x : Option α} {hf : ∀ (a : α), a ∈ x → p a} {y : β} : pmap f x hf = some y ↔ ∃ (a : α), ∃ (H : x = some a), f a (hf a H) = y := sorry\n\n@[simp] theorem join_pmap_eq_pmap_join {α : Type u_1} {β : Type u_2} {p : α → Prop} {f : (a : α) → p a → β} {x : Option (Option α)} (H : ∀ (a : Option α), a ∈ x → ∀ (a_1 : α), a_1 ∈ a → p a_1) : join (pmap (pmap f) x H) = pmap f (join x) fun (a : α) (h : a ∈ join x) => H (some a) (mem_of_mem_join h) a rfl := sorry\n\n@[simp] theorem seq_some {α : Type u_1} {β : Type u_1} {a : α} {f : α → β} : some f <*> some a = some (f a) :=\n rfl\n\n@[simp] theorem some_orelse' {α : Type u_1} (a : α) (x : Option α) : option.orelse (some a) x = some a :=\n rfl\n\n@[simp] theorem some_orelse {α : Type u_1} (a : α) (x : Option α) : (some a <|> x) = some a :=\n rfl\n\n@[simp] theorem none_orelse' {α : Type u_1} (x : Option α) : option.orelse none x = x :=\n option.cases_on x (Eq.refl (option.orelse none none)) fun (x : α) => Eq.refl (option.orelse none (some x))\n\n@[simp] theorem none_orelse {α : Type u_1} (x : Option α) : (none <|> x) = x :=\n none_orelse' x\n\n@[simp] theorem orelse_none' {α : Type u_1} (x : Option α) : option.orelse x none = x :=\n option.cases_on x (Eq.refl (option.orelse none none)) fun (x : α) => Eq.refl (option.orelse (some x) none)\n\n@[simp] theorem orelse_none {α : Type u_1} (x : Option α) : (x <|> none) = x :=\n orelse_none' x\n\n@[simp] theorem is_some_none {α : Type u_1} : is_some none = false :=\n rfl\n\n@[simp] theorem is_some_some {α : Type u_1} {a : α} : is_some (some a) = tt :=\n rfl\n\ntheorem is_some_iff_exists {α : Type u_1} {x : Option α} : ↥(is_some x) ↔ ∃ (a : α), x = some a := sorry\n\n@[simp] theorem is_none_none {α : Type u_1} : is_none none = tt :=\n rfl\n\n@[simp] theorem is_none_some {α : Type u_1} {a : α} : is_none (some a) = false :=\n rfl\n\n@[simp] theorem not_is_some {α : Type u_1} {a : Option α} : is_some a = false ↔ is_none a = tt := sorry\n\ntheorem eq_some_iff_get_eq {α : Type u_1} {o : Option α} {a : α} : o = some a ↔ ∃ (h : ↥(is_some o)), get h = a := sorry\n\ntheorem not_is_some_iff_eq_none {α : Type u_1} {o : Option α} : ¬↥(is_some o) ↔ o = none := sorry\n\ntheorem ne_none_iff_is_some {α : Type u_1} {o : Option α} : o ≠ none ↔ ↥(is_some o) := sorry\n\ntheorem ne_none_iff_exists {α : Type u_1} {o : Option α} : o ≠ none ↔ ∃ (x : α), some x = o := sorry\n\ntheorem ne_none_iff_exists' {α : Type u_1} {o : Option α} : o ≠ none ↔ ∃ (x : α), o = some x :=\n iff.trans ne_none_iff_exists (exists_congr fun (_x : α) => eq_comm)\n\ntheorem bex_ne_none {α : Type u_1} {p : Option α → Prop} : (∃ (x : Option α), ∃ (H : x ≠ none), p x) ↔ ∃ (x : α), p (some x) := sorry\n\ntheorem ball_ne_none {α : Type u_1} {p : Option α → Prop} : (∀ (x : Option α), x ≠ none → p x) ↔ ∀ (x : α), p (some x) := sorry\n\ntheorem iget_mem {α : Type u_1} [Inhabited α] {o : Option α} : ↥(is_some o) → iget o ∈ o := sorry\n\ntheorem iget_of_mem {α : Type u_1} [Inhabited α] {a : α} {o : Option α} : a ∈ o → iget o = a := sorry\n\n@[simp] theorem guard_eq_some {α : Type u_1} {p : α → Prop} [decidable_pred p] {a : α} {b : α} : guard p a = some b ↔ a = b ∧ p a := sorry\n\n@[simp] theorem guard_eq_some' {p : Prop} [Decidable p] (u : Unit) : guard p = some u ↔ p := sorry\n\ntheorem lift_or_get_choice {α : Type u_1} {f : α → α → α} (h : ∀ (a b : α), f a b = a ∨ f a b = b) (o₁ : Option α) (o₂ : Option α) : lift_or_get f o₁ o₂ = o₁ ∨ lift_or_get f o₁ o₂ = o₂ := sorry\n\n@[simp] theorem lift_or_get_none_left {α : Type u_1} {f : α → α → α} {b : Option α} : lift_or_get f none b = b :=\n option.cases_on b (Eq.refl (lift_or_get f none none)) fun (b : α) => Eq.refl (lift_or_get f none (some b))\n\n@[simp] theorem lift_or_get_none_right {α : Type u_1} {f : α → α → α} {a : Option α} : lift_or_get f a none = a :=\n option.cases_on a (Eq.refl (lift_or_get f none none)) fun (a : α) => Eq.refl (lift_or_get f (some a) none)\n\n@[simp] theorem lift_or_get_some_some {α : Type u_1} {f : α → α → α} {a : α} {b : α} : lift_or_get f (some a) (some b) = ↑(f a b) :=\n rfl\n\n/-- given an element of `a : option α`, a default element `b : β` and a function `α → β`, apply this\nfunction to `a` if it comes from `α`, and return `b` otherwise. -/\ndef cases_on' {α : Type u_1} {β : Type u_2} : Option α → β → (α → β) → β :=\n sorry\n\n@[simp] theorem cases_on'_none {α : Type u_1} {β : Type u_2} (x : β) (f : α → β) : cases_on' none x f = x :=\n rfl\n\n@[simp] theorem cases_on'_some {α : Type u_1} {β : Type u_2} (x : β) (f : α → β) (a : α) : cases_on' (some a) x f = f a :=\n rfl\n\n@[simp] theorem cases_on'_coe {α : Type u_1} {β : Type u_2} (x : β) (f : α → β) (a : α) : cases_on' (↑a) x f = f a :=\n rfl\n\n@[simp] theorem cases_on'_none_coe {α : Type u_1} {β : Type u_2} (f : Option α → β) (o : Option α) : cases_on' o (f none) (f ∘ coe) = f o :=\n option.cases_on o (Eq.refl (cases_on' none (f none) (f ∘ coe)))\n fun (o : α) => Eq.refl (cases_on' (some o) (f none) (f ∘ coe))\n\n", "meta": {"author": "AurelienSaue", "repo": "Mathlib4_auto", "sha": "590df64109b08190abe22358fabc3eae000943f2", "save_path": "github-repos/lean/AurelienSaue-Mathlib4_auto", "path": "github-repos/lean/AurelienSaue-Mathlib4_auto/Mathlib4_auto-590df64109b08190abe22358fabc3eae000943f2/Mathlib/data/option/basic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.27825678173200435, "lm_q2_score": 0.04401865221440601, "lm_q1q2_score": 0.012248488501360984}} {"text": "import Lean\n\n/-\n(1) How are the source information, comments etc stored in the Syntax tree? In particular, how can one recreate the original source?\n-/\n\nelab \"#reprint\" e:term : command => do\n let some val := e.raw.reprint | throwError \"failed to reprint\"\n IO.println val\n\n#reprint\n let x : Nat := 3 -- My comment 1\n x + 2 /- another comment here -/\n\nelab \"#repr\" e:term : command => do\n IO.println (repr e)\n\n#check Lean.SourceInfo\n\n#repr\n let x : Nat := 3 -- My comment 1\n x + 2 /- another comment here -/\n\n/-\n(2) I am comfortable with the usual token level parsers but could not understand the code for `commentBody` and such parsers. How does one parse at character level?\n\n-/\n\nsection\nopen Lean Parser\npartial def commandCommentBodyFn (c : ParserContext) (s : ParserState) : ParserState :=\n go s\nwhere\n go (s : ParserState) : ParserState := Id.run do\n let input := c.input\n let i := s.pos\n if input.atEnd i then return s.mkUnexpectedError \"unterminated command comment\"\n let curr := input.get i\n let i := input.next i\n if curr != '-' then return go (s.setPos i)\n let curr := input.get i\n let i := input.next i\n if curr != '/' then return go (s.setPos i)\n let curr := input.get i\n let i := input.next i\n if curr != '/' then return go (s.setPos i)\n -- Found '-//'\n return s.setPos i\n\ndef commandCommentBody : Parser :=\n { fn := rawFn commandCommentBodyFn (trailingWs := true) }\n\n@[combinator_parenthesizer commandCommentBody] def commandCommentBody.parenthesizer := PrettyPrinter.Parenthesizer.visitToken\n@[combinator_formatter commandCommentBody] def commandCommentBody.formatter := PrettyPrinter.Formatter.visitAtom Name.anonymous\n\n@[command_parser] def commandComment := leading_parser \"//-\" >> commandCommentBody >> ppLine\n\nend\n\nopen Lean Elab Command in\n@[command_elab commandComment] def elabCommandComment : CommandElab := fun stx => do\n let .atom _ val := stx[1] | return ()\n let str := val.extract 0 (val.endPos - ⟨3⟩)\n IO.println s!\"str := {repr str}\"\n\n//- My command comment hello world -//\n\n/-\n(3) How does one split a `tacticSeq` into individual tactics, with the goal of running them one by one logging state along the way?\n-/\nsection\nopen Lean Parser Elab Tactic\n\ndef getTactics (s : TSyntax ``tacticSeq) : Array (TSyntax `tactic) :=\n match s with\n | `(tacticSeq| { $[$t]* }) => t\n | `(tacticSeq| $[$t]*) => t\n | _ => #[]\n\nelab \"seq\" s:tacticSeq : tactic => do\n -- IO.println s\n let tacs := getTactics s\n for tac in tacs do\n let gs ← getUnsolvedGoals\n withRef tac <| addRawTrace (goalsToMessageData gs)\n evalTactic tac\n\nexample (h : x = y) : 0 + x = y := by\n seq rw [h]; rw [Nat.zero_add]\n done\n\nexample (h : x = y) : 0 + x = y := by\n seq rw [h]\n rw [Nat.zero_add]\n done\n\nexample (h : x = y) : 0 + x = y := by\n seq { rw [h]; rw [Nat.zero_add] }\n done\n\nend\n\n/-\n(4) Related to the above, how does one parse and run all the commands in a file updating the environment, with modifications to the running in some cases (specifically when running a `tacticSeq` log state at each step)?\n-/\n\n#check Lean.Elab.runFrontend\n", "meta": {"author": "leanprover", "repo": "lean4", "sha": "742d053a97bdd109a41a921facd1cd6a55e89bc7", "save_path": "github-repos/lean/leanprover-lean4", "path": "github-repos/lean/leanprover-lean4/lean4-742d053a97bdd109a41a921facd1cd6a55e89bc7/tests/lean/run/frontend_meeting_2022_09_13.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.25683199707586785, "lm_q2_score": 0.04742587553371325, "lm_q1q2_score": 0.012180482326395115}} {"text": "import data.pfun\nimport o_minimal.sheaf.covers\n\nsection orelse_pure\n\nopen_locale classical\n\nnoncomputable def roption.orelse_pure {α : Type*} (x : roption α) (y : α) :=\nif h : x.dom then x.get h else y\n\n-- TODO: Is this actually useful?\nlemma roption.orelse_pure_eq_iff {α : Type*} {x : roption α} {y : α} (z : α) :\n x.orelse_pure y = z ↔ (z ∈ x ∨ ¬ x.dom ∧ z = y) :=\nbegin\n unfold roption.orelse_pure,\n split_ifs with h; split; simp [h, roption.mem_eq, eq_comm]\nend\n\nend orelse_pure\n\nnamespace o_minimal\n\nvariables {R : Type*} {S : struc R}\nvariables {X : Type*} [definable_sheaf S X]\nvariables {Y : Type*} [definable_sheaf S Y]\n\ninstance roption.definable_sheaf : definable_sheaf S (roption X) :=\n{ definable := λ K f,\n ∃ H : def_set S (pfun.dom f),\n definable S (pfun.as_subtype f),\n definable_precomp := λ L K φ f ⟨H, h⟩,\n ⟨φ.is_definable.preimage H,\n h.comp (definable_subtype.map (Def.definable_iff_def_fun.mpr φ.is_definable) (λ _, id))⟩,\n definable_cover := λ K f 𝓛 hf, begin\n have : def_set S (pfun.dom f) := Def.set_subcanonical 𝓛 _ (λ i, (hf i).fst),\n refine ⟨this, _⟩,\n letI : definable_rep S (pfun.dom f) :=\n subtype.definable_rep (definable_iff_def_set.mpr this),\n let 𝓛' : cover S (pfun.dom f) :=\n (cover_of_Def 𝓛).pullback subtype.val definable.subtype.val,\n refine definable_cover (pfun.as_subtype f) 𝓛' _,\n -- TODO: messy proof\n intro i,\n let ψ : (𝓛'.map i).obj → {l | (𝓛.map i).to_fun l ∈ pfun.dom f} :=\n λ l', ⟨l'.1.2, begin\n rcases l' with ⟨⟨⟨a, b⟩, c⟩, rfl : a = map_to.to_fun _ c⟩,\n exact b\n end⟩,\n have : (𝓛'.map i).to_fun = subtype.map (𝓛.map i) (λ _, id) ∘ ψ,\n { ext1 ⟨⟨⟨a, b⟩, c⟩, rfl : a = map_to.to_fun _ c⟩, refl },\n rw this,\n refine (hf i).snd.comp _,\n apply definable_of_subtype_val,\n exact definable.snd.comp definable.subtype.val\n end }\n\n-- TODO: move this, and generalize?\nlemma definable_eq {Z : Type*} [has_coordinates R Z] [definable_rep S Z] :\n definable S ((=) : Z → Z → Prop) :=\nbegin\n rw definable_iff_uncurry,\n rw definable_fun,\n intros K φ hφ,\n rw definable_rep.eq at hφ,\n exact def_set_eq (def_fun.fst.comp hφ) (def_fun.snd.comp hφ)\nend\n\n-- TODO: generalize to `Z` with definable equality?\nlemma definable_roption.mem {Z : Type*} [has_coordinates R Z] [definable_rep S Z] :\n definable S ((∈) : Z → roption Z → Prop) :=\nbegin\n rw definable_iff_uncurry,\n rw definable_fun,\n intros K φ hφ,\n let K' := {k | (φ k).2.dom},\n have dK' : def_set S {k : ↥K | (φ k).snd.dom} := hφ.2.fst,\n letI : definable_rep S K' :=\n subtype.definable_rep (definable_iff_def_set.mpr dK'),\n have : definable S (λ (k' : {k | (φ k).2.dom}), (φ k'.val).1 = (φ k'.val).2.get k'.property),\n { let ψ₁ : K' → Z := λ k', (φ k'.val).1,\n have dψ₁ : definable S ψ₁ :=\n (definable_yoneda.mpr hφ.1).comp definable.subtype.val,\n let ψ₂ : K' → Z := λ k', (φ k'.val).2.get k'.property,\n have dψ₂ : definable S ψ₂ := hφ.2.snd,\n let ψ : K' → Z × Z := λ k', (ψ₁ k', ψ₂ k'),\n suffices dψ : definable S ψ,\n { have : definable S (λ (p : Z × Z), p.1 = p.2) :=\n definable_iff_uncurry.mp definable_eq,\n exact this.comp dψ },\n -- TODO: lemma\n begin [defin]\n intro k,\n app, app, exact definable.prod_mk.definable _,\n app, exact dψ₁.definable _, var,\n app, exact dψ₂.definable _, var\n end },\n rw definable_iff_def_set at this,\n convert def_fun.image def_fun_subtype_val this,\n { ext k,\n rw set.mem_image,\n conv_lhs { rw set.mem_def },\n simp only [function.uncurry, roption.mem_eq, exists_and_distrib_right,\n function.comp_app, exists_eq_right, subtype.exists,\n subtype.coe_mk, subtype.val_eq_coe],\n apply exists_congr, intro h,\n apply eq_comm },\n -- TODO: avoid this side goal somehow\n { exact dK' }\nend\n\nlemma definable_roption.dom : definable S (roption.dom : roption X → Prop) :=\nbegin\n rw definable_fun,\n intros K φ hφ,\n exact hφ.fst\nend\n\nlemma definable_orelse_pure :\n definable S (roption.orelse_pure : roption X → X → X) :=\nbegin\n rw definable_iff_uncurry,\n rw definable_fun,\n intros K φ hφ,\n rw ←definable_yoneda at ⊢ hφ,\n let s := {k | (φ k).1.dom},\n apply definable_if _ s,\n { exact definable_roption.dom.comp (definable.fst.comp hφ) },\n { suffices : definable S (λ (p : s), (φ p.val).1.get p.property),\n { convert this,\n ext ⟨k, hk⟩,\n change dite _ _ _ = (φ k).fst.get hk,\n -- exact dif_neg hk, -- bad binder type on `dif_neg`\n split_ifs,\n { refl },\n { refl } }, -- what happened here??\n rw definable_yoneda at hφ,\n exact hφ.1.snd },\n { suffices : definable S (λ (p : sᶜ), (φ p.val).2),\n { convert this,\n ext ⟨k, hk⟩,\n change dite _ _ _ = (φ k).snd,\n -- exact dif_neg hk, -- bad binder type on `dif_neg`\n split_ifs,\n { exact false.elim (hk h) },\n { refl } },\n exact definable.snd.comp (hφ.comp definable.subtype.val) }\nend\n\nlemma definable_roption_map :\n definable S (roption.map : (X → Y) → roption X → roption Y) :=\nbegin\n rw definable_iff_uncurry,\n rw definable_fun,\n intros K φ hφ,\n refine ⟨hφ.2.fst, _⟩,\n change definable S (λ (p : {k | (φ k).2.dom}), (φ p.1).1 (pfun.as_subtype (prod.snd ∘ φ) p)),\n begin [defin]\n intro p,\n app,\n app, exact definable.fst.definable _,\n app, exact (definable_yoneda.mpr hφ).definable _,\n app, exact definable.subtype.val.definable _,\n var,\n app, exact hφ.2.snd.definable _, var\n end\nend\n\ninstance pfun.definable_sheaf : definable_sheaf S (X →. Y) :=\nshow definable_sheaf S (X → roption Y), by apply_instance\n\nlemma definable_pfun_of_graph {Z : Type*} [has_coordinates R Z] [definable_rep S Z]\n {f : X →. Z} (df : definable S {p : X × Z | p.2 ∈ f p.1}) : definable S f :=\nbegin\n rw definable_fun,\n intros K φ hφ,\n rw ←definable_yoneda at hφ,\n have d : def_set S (pfun.dom (f ∘ φ)),\n { suffices : def_set S {k : K | ∃ z : Z, z ∈ f (φ k)},\n { convert this,\n ext k,\n simp [pfun.mem_dom] },\n apply def_set.exists,\n let ψ : K × Z → X × Z := λ p, (φ p.1, p.2),\n have dψ : definable S ψ,\n -- TODO: The tactic mode should be overkill for this\n begin [defin]\n intro p,\n app, app, exact definable.prod_mk.definable _,\n app, exact hφ.definable _,\n app, exact definable.fst.definable _,\n var,\n app, exact definable.snd.definable _,\n var,\n end,\n exact definable_iff_def_set.mp (df.comp dψ) },\n refine ⟨d, _⟩,\n apply definable_of_graph,\n let ψ : pfun.dom (f ∘ φ) × Z → X × Z := λ p, (φ p.1.val, p.2),\n have dψ : definable S ψ,\n begin [defin] -- TODO: ... and this\n intro p,\n app, app, exact definable.prod_mk.definable _,\n app, exact hφ.definable _,\n app, exact definable.subtype.val.definable _,\n app, exact definable.fst.definable _,\n var,\n app, exact definable.snd.definable _,\n var,\n end,\n convert df.comp dψ,\n ext ⟨⟨k, h⟩, z⟩,\n change (f (φ k)).get _ = z ↔ z ∈ f (φ k),\n rw [roption.get_eq_iff_eq_some, roption.eq_some_iff]\nend\n\nend o_minimal\n", "meta": {"author": "rwbarton", "repo": "lean-omin", "sha": "fd733c6d95ef6f4743aae97de5e15df79877c00e", "save_path": "github-repos/lean/rwbarton-lean-omin", "path": "github-repos/lean/rwbarton-lean-omin/lean-omin-fd733c6d95ef6f4743aae97de5e15df79877c00e/src/o_minimal/sheaf/pfun.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41869690935568665, "lm_q2_score": 0.028870903708419576, "lm_q1q2_score": 0.012088158153020908}} {"text": "structure PFunctor : Type 1 :=\n( α : Type )\n( β : α → Type )\n\nvariable (P : PFunctor)\n\nnamespace PFunctor\n\ndef obj (X : Type) : Type :=\nΣ (a : P.α), P.β a → X\n\ndef map {X Y : Type} (f : X → Y) (x : P.obj X) : P.obj Y :=\n⟨x.1, λ a => f (x.2 a)⟩\n\ninductive Z (P : PFunctor) : Type\n| bud : Z P\n| some (a : P.α) (f : P.β a → Z P) : Z P\n\nvariable {P}\n\ndef of_α (a : P.α) : Z P :=\nZ.some a (λ _ => Z.bud)\n\ndef bud : (z : Z P) → Type\n| Z.bud => Unit\n| Z.some a f => Σ (a : P.β a), bud (f a)\n\ndef extend : (z : Z P) → (b : bud z → P.α) → Z P\n| Z.bud, b => Z.some (b ()) (λ _ => Z.bud)\n| Z.some a f, b => Z.some a (λ bpa => extend (f bpa) (λ bf => b ⟨bpa, bf⟩))\n\ntheorem extend_injective_right : {z : Z P} → {b₁ b₂ : bud z → P.α} → \n extend z b₁ = extend z b₂ → b₁ = b₂\n| Z.bud, b₁, b₂, h => funext (λ x => by\ncases x; simp [extend] at h; exact h.1)\n| Z.some a f, b₁, b₂, h => by\n apply funext\n intro x\n simp [extend] at h\n dsimp [bud] at x\n match x with \n | ⟨x₁, x₂⟩ => exact congrFun (extend_injective_right (congrFun h x₁)) x₂\n\n@[simp] def bud_of_bud_extend : {z : Z P} → {bz : bud z → P.α} → (b : bud (extend z bz)) → bud z\n| Z.bud, _, _ => ()\n| Z.some _ _, _, ⟨pba, b⟩ => ⟨pba, bud_of_bud_extend b⟩\n\n@[simp] def β_of_bud_extend : {z : Z P} → {bz : bud z → P.α} → (b : bud (extend z bz)) → \n P.β (bz (bud_of_bud_extend b))\n| Z.bud, _, b => b.1\n| Z.some _ _, _, ⟨_, b⟩ => β_of_bud_extend b\n\ndef mk_bud_extend : (z : Z P) → (bz : bud z → P.α) → (b : bud z) → \n (bp : P.β (bz b)) → bud (extend z bz) \n| Z.bud, _, _, bp => ⟨bp, ()⟩\n| Z.some _ _, _, b, bp => ⟨b.1, mk_bud_extend _ _ b.2 bp⟩\n\n@[simp] theorem bud_of_bud_extend_mk_bud_extend : {z : Z P} → {bz : bud z → P.α} \n → (b : bud z) → (bp : P.β (bz b)) → bud_of_bud_extend (mk_bud_extend z bz b bp) = b\n| Z.bud, _, _, _ => rfl\n| Z.some a f, bz, ⟨_, _⟩, bp => by \nsimp [bud_of_bud_extend, mk_bud_extend]\nsimp [bud_of_bud_extend_mk_bud_extend]\n\n@[simp] theorem β_of_bud_extend_mk_bud_extend : {z : Z P} → {bz : bud z → P.α} \n → (b : bud z) → (bp : P.β (bz b)) → β_of_bud_extend (mk_bud_extend z bz b bp) = \n cast (by simp) bp \n| Z.bud, _, _, _ => rfl\n| Z.some _ _, _, _, _ => by\nsimp [β_of_bud_extend, mk_bud_extend]\nsimp [β_of_bud_extend_mk_bud_extend]\n\nstructure M (P : PFunctor) : Type :=\n( seq : Nat → Z P )\n( leaf : (n : Nat) → bud (seq n) → P.α )\n( zero_eq : seq 0 = Z.bud )\n( succ_eq : (n : Nat) → seq (n+1) = extend (seq n) (leaf n) )\n\ntheorem M_ext : {m₁ m₂ : M P} → (h : ∀ n, m₁.seq n = m₂.seq n) → m₁ = m₂ \n| ⟨seq₁, leaf₁, zero_eq₁, succ_eq₁⟩, \n ⟨seq₂, leaf₂, zero_eq₂, succ_eq₂⟩, h => by\nsimp only [M.mk.injEq]\nhave hseq : seq₁ = seq₂ := funext h\nsubst hseq\nsimp\napply funext\nintro n\napply funext\nintro b\nhave := (succ_eq₁ n).symm.trans (succ_eq₂ n)\nrw [extend_injective_right this]\n\ntheorem M_ext2 {m₁ m₂ : M P} (h : ∀ (n : Nat) (h : m₁.seq n = m₂.seq n),\n m₁.leaf n = (λ b => m₂.leaf n (by rw [← h]; exact b))) : m₁ = m₂ := by\napply M_ext\nintro n\ninduction n with\n| zero => simp [M.zero_eq]\n| succ n ih => sorry\n\ndef bud_zero {m : M P} : bud (m.seq 0) :=\ncast (by rw [M.zero_eq]; rfl) ()\n\ndef bud_succ {m : M P} {n : Nat} (b : bud (m.seq n)) (bp : P.β (m.leaf n b)) : bud (m.seq (n+1)) :=\nby rw [M.succ_eq]; exact mk_bud_extend _ (m.leaf n) b bp\n\n--theorem bud_of_bud_extend_bud_succ\n\ndef bud_of_bud_succ {m : M P} {n : Nat} (b : bud (m.seq (n+1))) : bud (m.seq n) :=\nby rw [M.succ_eq] at b; exact bud_of_bud_extend b\n\ndef M_coalg_seq_aux (m : M P) (p : P.β (m.leaf 0 bud_zero)) : \n (n : Nat) → (z : Z P) × (bud z → bud (m.seq (n+1)))\n| 0 => ⟨Z.bud, λ _ => bud_succ bud_zero p⟩\n| n+1 => \nlet sn := M_coalg_seq_aux m p n\n⟨extend sn.1 (λ b => m.leaf _ (sn.2 b)), \n λ b => bud_succ (sn.2 (bud_of_bud_extend b)) (β_of_bud_extend b) ⟩ \n\ndef M_coalg (m : M P) : P.obj (M P) :=\n⟨m.leaf 0 bud_zero, \n λ b => \n { seq := λ n => (M_coalg_seq_aux m b n).1,\n leaf := λ n b' => \n M.leaf m n.succ (Sigma.snd (M_coalg_seq_aux m b n) b'),\n zero_eq := rfl,\n succ_eq := λ n => by rfl }⟩\n\ntheorem M_coalg_snd (m : M P) : (M_coalg m).2 = \n λ b => \n { seq := λ n => (M_coalg_seq_aux m b n).1,\n leaf := λ n => _,\n zero_eq := rfl,\n succ_eq := λ n => by rfl } := rfl\n\ntheorem M_coalg_snd_app_seq (m : M P) \n (b : P.β (M_coalg m).1) : ((M_coalg m).2 b).seq = \n λ n => (M_coalg_seq_aux m b n).1 := rfl\n\ndef to_M_seq_aux {A : Type} (coalg : A → P.obj A) (a : A) : \n Nat → (z : Z P) × (bud z → A)\n| 0 => ⟨Z.bud, λ _ => a⟩\n| n+1 => let ⟨z, bz⟩ := to_M_seq_aux coalg a n\n ⟨extend z\n (λ b => (coalg (bz b)).1),\n λ b => bz (bud_of_bud_extend b) ⟩\n\ndef to_M {A : Type} (coalg : A → P.obj A) (a : A) : M P :=\n{ seq := λ n => (to_M_seq_aux coalg a n).1,\n leaf := λ n b => (coalg ((to_M_seq_aux coalg a n).2 b)).1,\n zero_eq := rfl,\n succ_eq := λ _ => rfl }\n\ntheorem obj_ext {A : Type} {a b : P.obj A} \n (h₁ : a.1 = b.1) (h₂ : ∀ (x : P.β a.1), a.2 x = b.2 (cast (by rw [h₁]) x)) :\n a = b := \nmatch a, b with\n| ⟨a₁, a₂⟩, ⟨b₁, b₂⟩ => by\ndsimp at h₁\nsubst h₁\ndsimp [cast] at h₂\nsimp [funext h₂]\n\ntheorem coalg_to_M {A : Type} (coalg : A → P.obj A) (a : A) \n (x : P.β (M_coalg (to_M coalg a)).1) (n : Nat) :\n M.leaf ((M_coalg (to_M coalg a)).2 x) n = sorry :=\nby \n dsimp [M_coalg, to_M, to_M_seq_aux,\n M_coalg_seq_aux]\n simp\n\n-- theorem to_M_hom {A : Type} (coalg : A → P.obj A) (a : A) :\n-- M_coalg (to_M coalg a) = P.map (to_M coalg) (coalg a) := \n-- obj_ext rfl $ by\n-- intro x\n-- apply M_ext2\n-- intro n h\n-- simp\n-- conv => \n-- congr \n-- delta to_M\n-- delta M_coalg\n-- dsimp\n\n\n\ntheorem to_M_unique_aux {A : Type} (coalg : A → P.obj A) (a : A) \n (f : A → M P) (f_hom : ∀ (a : A), M_coalg (f a) = P.map f (coalg a)) :\n (n : Nat) → (show Σ (z : Z P), bud z → P.α from ⟨(f a).seq n, (f a).leaf n⟩) =\n ⟨(to_M_seq_aux coalg a n).1, \n λ b => (coalg ((to_M_seq_aux coalg a n).2 b)).1⟩\n| 0 => by\n specialize f_hom a\n have := congrArg Sigma.fst f_hom\n dsimp [M_coalg] at this ⊢\n apply Sigma.ext <;>\n simp [to_M_seq_aux, M.zero_eq]\n apply funext\n intro x\n refine Eq.trans sorry (Eq.trans this ?x)\n rw [PFunctor.map]\n dsimp\n sorry\n| n+1 => by\n dsimp\n apply Sigma.ext <;>\n simp [to_M_seq_aux, M.succ_eq]\n have := to_M_unique_aux coalg a f f_hom n\n dsimp at this\n\n \n\n\ntheorem to_M_unique {A : Type} (coalg : A → P.obj A) (a : A) \n (f : A → M P) (f_hom : ∀ (a : A), M_coalg (f a) = P.map f (coalg a)) (a : A) :\n f a = to_M coalg a := by\napply M_ext\nintro n\ninduction n generalizing a with\n| zero => simp [M.zero_eq]\n| succ n ih => \nsimp [M.succ_eq, to_M, to_M_seq_aux] at ih ⊢\nsimp [M_coalg, PFunctor.map] at f_hom\nspecialize ih a\ndsimp at f_hom\n\n\n\n-- . rw [M.zero_eq, M.zero_eq]\n-- . rw [M.succ_eq, M.succ_eq]\n\n\n\nend PFunctor", "meta": {"author": "ChrisHughes24", "repo": "lean4stuff", "sha": "2b5f6589cfd0113853d2dd0a5ce3fdf91fae7346", "save_path": "github-repos/lean/ChrisHughes24-lean4stuff", "path": "github-repos/lean/ChrisHughes24-lean4stuff/lean4stuff-2b5f6589cfd0113853d2dd0a5ce3fdf91fae7346/Stuff/Coind/try1.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47268349147711747, "lm_q2_score": 0.025565213088041997, "lm_q1q2_score": 0.012084254182812192}} {"text": "/-\nFile: signature_recover_public_key_nondet_bigint3_soundness.lean\n\nAutogenerated file.\n-/\nimport starkware.cairo.lean.semantics.soundness.hoare\nimport .signature_recover_public_key_code\nimport ..signature_recover_public_key_spec\nopen tactic\n\nopen starkware.cairo.common.cairo_secp.bigint\nopen starkware.cairo.common.cairo_secp.constants\n\nvariables {F : Type} [field F] [decidable_eq F] [prelude_hyps F]\nvariable mem : F → F\nvariable σ : register_state F\n\n/- starkware.cairo.common.cairo_secp.bigint.nondet_bigint3 autogenerated soundness theorem -/\n\ntheorem auto_sound_nondet_bigint3\n -- arguments\n (range_check_ptr : F)\n -- code is in memory at σ.pc\n (h_mem : mem_at mem code_nondet_bigint3 σ.pc)\n -- input arguments on the stack\n (hin_range_check_ptr : range_check_ptr = mem (σ.fp - 3))\n -- conclusion\n : ensures_ret mem σ (λ κ τ,\n τ.ap = σ.ap + 8 ∧\n ∃ μ ≤ κ, rc_ensures mem (rc_bound F) μ (mem (σ.fp - 3)) (mem $ τ.ap - 4)\n (spec_nondet_bigint3 mem κ range_check_ptr (mem (τ.ap - 4)) (cast_BigInt3 mem (τ.ap - 3)))) :=\nbegin\n apply ensures_of_ensuresb, intro νbound,\n have h_mem_rec := h_mem,\n unpack_memory code_nondet_bigint3 at h_mem with ⟨hpc0, hpc1, hpc2, hpc3, hpc4, hpc5, hpc6, hpc7, hpc8, hpc9, hpc10, hpc11⟩,\n -- let (ap reference)\n apply of_register_state,\n intros regstate_res regstateeq_res,\n generalize' hl_rev_res: cast_BigInt3 mem (regstate_res.ap + 5) = res,\n have hl_res := hl_rev_res.symm,\n rw [regstateeq_res] at hl_res, try { dsimp at hl_res },\n -- const\n set! MAX_SUM := (232113757366008801543585789 : F) with hc_MAX_SUM,\n -- compound assert eq\n step_assert_eq hpc0 hpc1 with temp0,\n step_assert_eq hpc2 with temp1,\n step_assert_eq hpc3 with temp2,\n step_assert_eq hpc4 with temp3,\n step_assert_eq hpc5 with temp4,\n have a0: mem (range_check_ptr) = MAX_SUM - (res.d0 + res.d1 + res.d2), {\n apply assert_eq_reduction temp4.symm,\n try { simp only [add_neg_eq_sub, hin_range_check_ptr, hl_res, hc_MAX_SUM] },\n try { dsimp [cast_BigInt3] },\n try { arith_simps }, try { simp only [temp0, temp1, temp2, (eq_sub_of_eq_add temp3)] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },\n },\n try { dsimp at a0 }, try { arith_simps at a0 },\n clear temp0 temp1 temp2 temp3 temp4,\n -- tempvar\n step_assert_eq hpc6 hpc7 with tv_range_check_ptr0,\n generalize' hl_rev_range_check_ptr₁: (range_check_ptr + 4 : F) = range_check_ptr₁,\n have hl_range_check_ptr₁ := hl_rev_range_check_ptr₁.symm, clear hl_rev_range_check_ptr₁,\n have htv_range_check_ptr₁: range_check_ptr₁ = _, {\n apply eq.symm, apply eq.trans tv_range_check_ptr0,\n try { simp only [add_neg_eq_sub, hin_range_check_ptr, hl_res, hc_MAX_SUM, hl_range_check_ptr₁] },\n try { dsimp [cast_BigInt3] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } }, },\n clear tv_range_check_ptr0,\n try { dsimp at hl_range_check_ptr₁ }, try { arith_simps at hl_range_check_ptr₁ },\n -- assert eq\n step_assert_eq hpc8 with temp0,\n have a8: mem (range_check_ptr₁ - 3) = res.d0, {\n apply assert_eq_reduction temp0.symm,\n try { simp only [add_neg_eq_sub, hin_range_check_ptr, hl_res, hc_MAX_SUM, hl_range_check_ptr₁, htv_range_check_ptr₁] },\n try { dsimp [cast_BigInt3] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },\n },\n try { dsimp at a8 }, try { arith_simps at a8 },\n clear temp0,\n -- assert eq\n step_assert_eq hpc9 with temp0,\n have a9: mem (range_check_ptr₁ - 2) = res.d1, {\n apply assert_eq_reduction temp0.symm,\n try { simp only [add_neg_eq_sub, hin_range_check_ptr, hl_res, hc_MAX_SUM, hl_range_check_ptr₁, htv_range_check_ptr₁] },\n try { dsimp [cast_BigInt3] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },\n },\n try { dsimp at a9 }, try { arith_simps at a9 },\n clear temp0,\n -- assert eq\n step_assert_eq hpc10 with temp0,\n have a10: mem (range_check_ptr₁ - 1) = res.d2, {\n apply assert_eq_reduction temp0.symm,\n try { simp only [add_neg_eq_sub, hin_range_check_ptr, hl_res, hc_MAX_SUM, hl_range_check_ptr₁, htv_range_check_ptr₁] },\n try { dsimp [cast_BigInt3] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },\n },\n try { dsimp at a10 }, try { arith_simps at a10 },\n clear temp0,\n -- return\n step_ret hpc11,\n -- finish\n step_done, use_only [rfl, rfl],\n split, refl,\n -- range check condition\n use_only (4+0+0), split,\n linarith [],\n split,\n { arith_simps,\n rw [←htv_range_check_ptr₁, hl_range_check_ptr₁, hin_range_check_ptr],\n try { arith_simps, refl <|> norm_cast }, try { refl } },\n intro rc_h_range_check_ptr, repeat { rw [add_assoc] at rc_h_range_check_ptr },\n have rc_h_range_check_ptr' := range_checked_add_right rc_h_range_check_ptr,\n -- Final Proof\n -- user-provided reduction\n suffices auto_spec: auto_spec_nondet_bigint3 mem _ range_check_ptr _ _,\n { apply sound_nondet_bigint3, apply auto_spec },\n -- prove the auto generated assertion\n dsimp [auto_spec_nondet_bigint3],\n try { norm_num1 }, try { arith_simps },\n use_only [res],\n use [MAX_SUM, hc_MAX_SUM],\n use_only [a0],\n cases rc_h_range_check_ptr' (0) (by norm_num1) with n hn, arith_simps at hn,\n use_only [n], { simp only [a0.symm, hin_range_check_ptr], arith_simps, exact hn },\n have rc_h_range_check_ptr₁ := range_checked_offset' rc_h_range_check_ptr,\n have rc_h_range_check_ptr₁' := range_checked_add_right rc_h_range_check_ptr₁,try { norm_cast at rc_h_range_check_ptr₁' },\n use_only [range_check_ptr₁, hl_range_check_ptr₁],\n use_only [a8],\n cases rc_h_range_check_ptr' (1) (by norm_num1) with n hn, arith_simps at hn,\n use_only [n], { simp only [a8.symm, hl_range_check_ptr₁, hin_range_check_ptr], arith_simps, exact hn },\n use_only [a9],\n cases rc_h_range_check_ptr' (2) (by norm_num1) with n hn, arith_simps at hn,\n use_only [n], { simp only [a9.symm, hl_range_check_ptr₁, hin_range_check_ptr], arith_simps, exact hn },\n use_only [a10],\n cases rc_h_range_check_ptr' (3) (by norm_num1) with n hn, arith_simps at hn,\n use_only [n], { simp only [a10.symm, hl_range_check_ptr₁, hin_range_check_ptr], arith_simps, exact hn },\n try { split, linarith },\n try { ensures_simps; try { simp only [add_neg_eq_sub, hin_range_check_ptr, hl_res, hc_MAX_SUM, hl_range_check_ptr₁, htv_range_check_ptr₁] }, },\n try { dsimp [cast_BigInt3] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },\nend\n\n", "meta": {"author": "starkware-libs", "repo": "formal-proofs", "sha": "35613c65b6715601bbc0a550d52754f8e7d93e30", "save_path": "github-repos/lean/starkware-libs-formal-proofs", "path": "github-repos/lean/starkware-libs-formal-proofs/formal-proofs-35613c65b6715601bbc0a550d52754f8e7d93e30/src/starkware/cairo/common/cairo_secp/verification/verification/signature_recover_public_key_nondet_bigint3_soundness.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43782351378493656, "lm_q2_score": 0.027585282526575293, "lm_q1q2_score": 0.012077485324535408}} {"text": "import Lean\nopen Lean Elab Term\n\ndef «こんにちは» := \"hello\"\n#eval «こんにちは»++«こんにちは»\n\ndef say (a : String) := a.capitalize\n#eval say «こんにちは»\n\n-- WRAP Sbar[decl] (e0:evt)× (誉める/ほめる/ガヲ(e0,太郎/たろう;太郎/たろう,次郎/じろう)) [0.85]\n-- > S[v:1<1>][term|attr<4>][] λx0.(e0:evt)× (u0:誉める/ほめる/ガヲ(e0,太郎/たろう;太郎/たろう,次郎/じろう))× x0(e0) [0.95]\n-- > T1/(T1\\NP[ga]) λx0.x0(太郎/たろう;太郎/たろう) [0.99]\n-- LEX 太郎 T1/(T1\\NP[nc]) λx0.x0(太郎/たろう;太郎/たろう) (PN) [0.99]\n-- LEX が T1/(T1\\NP[ga])\\NP[nc] λx0.λx1.x1(x0) (524) [1.00]\n-- > S[v:1<1>][term|attr<4>][]\\NP[ga] λx0.λx1.(e0:evt)× (u0:誉める/ほめる/ガヲ(e0,x0,次郎/じろう))× x1(e0) [0.96]\n-- > T1/(T1\\NP[o]) λx0.x0(次郎/じろう) [0.99]\n-- LEX 次郎 T1/(T1\\NP[nc]) λx0.x0(次郎/じろう) (PN) [0.99]\n-- LEX を T1/(T1\\NP[o])\\NP[nc] λx0.λx1.x1(x0) (524) [1.00]\n-- ][term|attr][]\\NP[ga]\\NP[o] λx0.λx1.λx2.(e0:evt)× (u0:誉める/ほめる/ガヲ(e0,x1,x0))× x2(e0) [0.97]\n-- LEX ほめ S[v:1][stem|neg|cont|+][]\\NP[ga]\\NP[o] λx0.λx1.λx2.(e0:evt)× (u0:誉める/ほめる/ガヲ(e0,x1,x0))× x2(e0) (JCon) [0.97]\n-- LEX る S[v:5:r|v:1|v:5:ARU|+<1>][term|attr][]\\S[v:5:r|v:1|v:5:ARU|+<1>][stem][] λx0.x0 (125) [1.00]\n-- Sig. [太郎/たろう;太郎/たろう:entity, 次郎/じろう:entity, 誉める/ほめる/ガヲ:(x0:entity)→ (x1:entity)→ (e0:evt)→ type]\n\nstructure Entity where\n entity : Name\nopen Entity\n\ndef taro : Entity := ⟨`a⟩\ndef jiro : Entity := ⟨`b⟩\nexample : taro ≠ jiro := by \n admit\n\ndef «太郎が» :Entity := ⟨`«太郎が»⟩\ndef «次郎を» :Entity := ⟨`«次郎を»⟩\n\n-- i==2 -> S\\NP\\NP: \\y.\\x.\\c.(e:event)X(op(e,x,y)X(ce)\ninductive «ほめるsr» (ga wo : Entity) : Prop where\n | rel : Entity -> Entity -> «ほめるsr» ga wo\n\n#check «ほめるsr» ({entity := `aa} : Entity) ({entity := `aa} : Entity)\ndef «ほめる» (ga wo : Entity) : Prop := «ほめるsr» ga wo\n\n#check «ほめる» «太郎が» «次郎を» \ndef A := «ほめる» «太郎が» «次郎を» \ndef B := «ほめる» «次郎を» «太郎が»\n\n\ndef getCtors (typ : Name) : MetaM (List Name) := do\n let env ← getEnv\n match env.find? typ with\n | some (ConstantInfo.inductInfo val) =>\n pure val.ctors\n | _ => pure []\n\nsyntax (name := myanon) \"⟨⟨\" term+ \"⟩⟩\" : term\n\n@[termElab myanon]\ndef myanonImpl : TermElab := fun stx typ? => do\n -- tryPostponeIfNoneOrMVar typ? \n let some typ := typ? | throwError \"expected type must be known\"\n let args := TSyntaxArray.mk stx[1].getSepArgs\n logInfo s!\"{args}\"\n if typ.isMVar then\n throwError \"expected type must be known\"\n let Expr.const base .. := typ.getAppFn | throwError s!\"type is not of the expected form: {typ}\"\n let [ctor] ← getCtors base | throwError \"type doesn't have exactly one constructor\"\n logInfo s!\"stx:{stx}\"\n let stx ← `($(mkIdent ctor) $args*) -- syntax quotations\n logInfo s!\"stx2:{stx}\"\n elabTerm stx typ -- call term elaboration recursively\n\n-- #check (⟨⟨1 sorry⟩⟩ : Fin 12)\n-- def oo: List Char := ⟨⟨ hello ⟩⟩\ndeclare_syntax_cat hoge\nsyntax term : hoge\ndeclare_syntax_cat ja_expr\nsyntax \"こんにちは\" : ja_expr\nsyntax \"言う\" : ja_expr\n-- おそらく{任意の文法}+を使っている場合、空白が存在するだけでTerm.appのパーサーが当たってしまうようである\n-- 空白は視認性が悪く、空白が存在するかどうかで振る舞い変わるのは望ましくないので\n-- Term.app のパーサーが当たらないように回避する必要がある\n-- 調査の結果{任意の文法}+で当たってしまうようなので、泥臭くTerm.appかどうかで場合分けしたほうがいいかも\nsyntax hoge+ : ja_expr\n\nelab \"ja(\" je:ja_expr+ \")\" : term => do\n let _a: Syntax := (je[0]!).raw\n logInfo s!\"kk{je[1]!}\"\n pure $ mkStrLit s!\"o{je}\"\n\n#eval ja(こんにちは)\n#eval ja(こんにちは言う)\n#eval ja(«ほめる» «太郎が» «次郎を»)\n", "meta": {"author": "denjiry", "repo": "jalean", "sha": "78dea9542ed18a82d7258f617d172653dca85209", "save_path": "github-repos/lean/denjiry-jalean", "path": "github-repos/lean/denjiry-jalean/jalean-78dea9542ed18a82d7258f617d172653dca85209/Jalean.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38121955219593834, "lm_q2_score": 0.03161876532954495, "lm_q1q2_score": 0.012053691559917585}} {"text": "import .definitions3 .qi\n\nlemma exp.vcgen.extension {P: prop} {e: exp} {Q: propctx}: (P ⊢ e : Q) → (P ⊩ e : Q) :=\n begin\n\n assume e_verified: P ⊢ e : Q,\n\n induction e_verified,\n\n case exp.vcgen.tru P y e' Q y_not_in_P e'_verified ih {\n apply exp.dvcgen.tru,\n from y_not_in_P,\n from ih\n },\n\n case exp.vcgen.fals P y e' Q y_not_in_P e'_verified ih {\n apply exp.dvcgen.fals,\n from y_not_in_P,\n from ih\n },\n\n case exp.vcgen.num P y n e' Q y_not_in_P e'_verified ih {\n apply exp.dvcgen.num,\n from y_not_in_P,\n from ih\n },\n\n case exp.vcgen.func P f fx R S e₁ e₂ Q₁ Q₂ f_not_in_P fx_not_in_P f_neq_fx fx_in_R fv_R fv_S\n e₁_verified e₂_verified func_vc ih₁ ih₂ {\n apply exp.dvcgen.func,\n from f_not_in_P,\n from fx_not_in_P,\n from f_neq_fx,\n from fx_in_R,\n from fv_R,\n from fv_S,\n from ih₁,\n from ih₂,\n from vc_valid_from_inst_valid func_vc\n },\n\n case exp.vcgen.unop op P e' x₁ y Q x_free_in_P y_not_in_P e'_verified vc_valid ih {\n apply exp.dvcgen.unop,\n from x_free_in_P,\n from y_not_in_P,\n from ih,\n from vc_valid_from_inst_valid vc_valid\n },\n\n case exp.vcgen.binop op P e' x₁ x₂ y Q x₁_free_in_P x₂_free_in_P y_not_in_P e'_verified vc_valid ih {\n apply exp.dvcgen.binop,\n from x₁_free_in_P,\n from x₂_free_in_P,\n from y_not_in_P,\n from ih,\n from vc_valid_from_inst_valid vc_valid\n },\n\n case exp.vcgen.app P y f e' x₁ Q f_free_in_P x₁_free_in_P y_not_in_P e'_verified vc_valid ih {\n apply exp.dvcgen.app,\n from f_free_in_P,\n from x₁_free_in_P,\n from y_not_in_P,\n from ih,\n from vc_valid_from_inst_valid vc_valid\n },\n\n case exp.vcgen.ite P e₁ e₂ y Q₁ Q₂ y_free_in_P e₁_verified e₂_verified vc_valid ih₁ ih₂ {\n apply exp.dvcgen.ite,\n from y_free_in_P,\n from ih₁,\n from ih₂,\n from vc_valid_from_inst_valid vc_valid\n },\n\n case exp.vcgen.return P y y_free_in_P {\n apply exp.dvcgen.return,\n from y_free_in_P\n }\n end\n\nlemma exp.dvcgen.return.inv {P: prop} {x: var} {Q: propctx}: (P ⊩ exp.return x : Q) → x ∈ FV P :=\n assume return_verified: P ⊩ exp.return x : Q,\n begin\n cases return_verified,\n case exp.dvcgen.return x_free {\n show x ∈ FV P, from x_free\n }\n end\n\nlemma stack.dvcgen.top.inv {R: spec} {σ: env} {e: exp} {Q: propctx}:\n (⊩ₛ (R, σ, e) : Q) →\n ∃P Q₂, (⊩ σ: P) ∧ (FV R.to_prop ⊆ FV P) ∧ (σ ⊨ R.to_prop.to_vc) ∧ (R ⋀ P ⊩ e: Q₂) :=\n assume top_verified: ⊩ₛ (R, σ, e) : Q,\n begin\n cases top_verified,\n case stack.dvcgen.top P Q env_verified fv_R R_valid e_verified {\n show ∃P Q₂, (⊩ σ: P) ∧ (FV R.to_prop ⊆ FV P) ∧ (σ ⊨ R.to_prop.to_vc) ∧ (R ⋀ P ⊩ e: Q₂),\n from exists.intro P (exists.intro Q ⟨env_verified, ⟨fv_R, ⟨R_valid, e_verified⟩⟩⟩) \n }\n end\n\nlemma env.dvcgen.inv {σ: env} {P: prop} {x: var} {v: value}:\n (⊩ σ : P) → (σ x = v) → ∃σ' Q', ⊩ (σ'[x↦v]) : Q' :=\n assume env_verified: ⊩ σ : P,\n assume σ_x_is_v: σ x = v,\n show ∃σ' Q', ⊩ (σ'[x↦v]) : Q', by begin\n induction env_verified,\n case env.dvcgen.empty { from\n have env.apply env.empty x = none, by unfold env.apply,\n have some v = none, from eq.trans σ_x_is_v.symm this,\n show ∃σ' Q', ⊩ (σ'[x↦v]) : Q', from false.elim (option.no_confusion this)\n },\n case env.dvcgen.tru σ' y Q y_not_in_σ' σ'_verified ih { from\n have env.apply (σ'[y↦value.true]) x = v, from σ_x_is_v,\n have h1: (if y = x ∧ option.is_none (σ'.apply x) then ↑value.true else σ'.apply x) = v,\n by { unfold env.apply at this, from this },\n if h2: y = x ∧ option.is_none (σ'.apply x) then (\n have (↑value.true) = ↑v, by { simp[h2] at h1, from h1 },\n have v_is_true: v = value.true, from (option.some.inj this).symm,\n have x_not_in_σ': x ∉ σ', from h2.left ▸ y_not_in_σ',\n have ⊩ (σ'[x↦value.true]) : Q ⋀ x ≡ value.true, from env.dvcgen.tru x_not_in_σ' σ'_verified,\n have ⊩ (σ'[x↦v]) : Q ⋀ x ≡ value.true, from v_is_true.symm ▸ this,\n show ∃σ' Q', ⊩ (σ'[x↦v]) : Q',\n from exists.intro σ' (exists.intro (Q ⋀ x ≡ value.true) this)\n ) else (\n have (σ'.apply x) = v, by { simp[h2] at h1, from h1 },\n show ∃σ' Q', ⊩ (σ'[x↦v]) : Q', from ih this\n )\n },\n case env.dvcgen.fls σ' y Q y_not_in_σ' σ'_verified ih { from\n have env.apply (σ'[y↦value.false]) x = v, from σ_x_is_v,\n have h1: (if y = x ∧ option.is_none (σ'.apply x) then ↑value.false else σ'.apply x) = v,\n by { unfold env.apply at this, from this },\n if h2: y = x ∧ option.is_none (σ'.apply x) then (\n have (↑value.false) = ↑v, by { simp[h2] at h1, from h1 },\n have v_is_false: v = value.false, from (option.some.inj this).symm,\n have x_not_in_σ': x ∉ σ', from h2.left ▸ y_not_in_σ',\n have ⊩ (σ'[x↦value.false]) : Q ⋀ x ≡ value.false, from env.dvcgen.fls x_not_in_σ' σ'_verified,\n have ⊩ (σ'[x↦v]) : Q ⋀ x ≡ value.false, from v_is_false.symm ▸ this,\n show ∃σ' Q', ⊩ (σ'[x↦v]) : Q',\n from exists.intro σ' (exists.intro (Q ⋀ x ≡ value.false) this)\n ) else (\n have (σ'.apply x) = v, by { simp[h2] at h1, from h1 },\n show ∃σ' Q', ⊩ (σ'[x↦v]) : Q', from ih this\n )\n },\n case env.dvcgen.num n σ' y Q y_not_in_σ' σ'_verified ih { from\n have env.apply (σ'[y↦value.num n]) x = v, from σ_x_is_v,\n have h1: (if y = x ∧ option.is_none (σ'.apply x) then ↑(value.num n) else σ'.apply x) = v,\n by { unfold env.apply at this, from this },\n if h2: y = x ∧ option.is_none (σ'.apply x) then (\n have ↑(value.num n) = ↑v, by { simp[h2] at h1, from h1 },\n have v_is_num: v = value.num n, from (option.some.inj this).symm,\n have x_not_in_σ': x ∉ σ', from h2.left ▸ y_not_in_σ',\n have ⊩ (σ'[x↦value.num n]) : Q ⋀ x ≡ value.num n, from env.dvcgen.num x_not_in_σ' σ'_verified,\n have ⊩ (σ'[x↦v]) : Q ⋀ x ≡ value.num n, from v_is_num.symm ▸ this,\n show ∃σ' Q', ⊩ (σ'[x↦v]) : Q',\n from exists.intro σ' (exists.intro (Q ⋀ x ≡ value.num n) this)\n ) else (\n have (σ'.apply x) = v, by { simp[h2] at h1, from h1 },\n show ∃σ' Q', ⊩ (σ'[x↦v]) : Q', from ih this\n )\n },\n case env.dvcgen.func f σ₂ σ₁ g gx R S e Q₁ Q₂ Q₃ f_not_in_σ₁ g_not_in_σ₂ gx_not_in_σ₂ g_neq_gx\n σ₁_verified σ₂_verified x_free_in_R fv_R fv_S e_verified func_vc ih₁ ih₂ { from\n have env.apply (σ₁[f↦value.func g gx R S e σ₂]) x = v, from σ_x_is_v,\n have h1: (if f = x ∧ option.is_none (σ₁.apply x) then ↑(value.func g gx R S e σ₂) else σ₁.apply x) = v,\n by { unfold env.apply at this, from this },\n if h2: f = x ∧ option.is_none (σ₁.apply x) then (\n have ↑(value.func g gx R S e σ₂) = ↑v, by { simp[h2] at h1, from h1 },\n have v_is_num: v = value.func g gx R S e σ₂, from (option.some.inj this).symm,\n have x_not_in_σ₁: x ∉ σ₁, from h2.left ▸ f_not_in_σ₁,\n have ⊩ (σ₁[x↦value.func g gx R S e σ₂]) :\n (Q₁\n ⋀ x ≡ value.func g gx R S e σ₂\n ⋀ prop.subst_env (σ₂[g↦value.func g gx R S e σ₂]) (prop.func g gx R (Q₃ (term.app g gx) ⋀ S))),\n from env.dvcgen.func x_not_in_σ₁ g_not_in_σ₂ gx_not_in_σ₂ g_neq_gx\n σ₁_verified σ₂_verified x_free_in_R fv_R fv_S e_verified func_vc,\n have ⊩ (σ₁[x↦v]) :\n (Q₁\n ⋀ x ≡ value.func g gx R S e σ₂\n ⋀ prop.subst_env (σ₂[g↦value.func g gx R S e σ₂]) (prop.func g gx R (Q₃ (term.app g gx) ⋀ S))),\n from v_is_num.symm ▸ this,\n show ∃σ₁ Q', ⊩ (σ₁[x↦v]) : Q',\n from exists.intro σ₁ (exists.intro (Q₁\n ⋀ x ≡ value.func g gx R S e σ₂\n ⋀ prop.subst_env (σ₂[g↦value.func g gx R S e σ₂]) (prop.func g gx R (Q₃ (term.app g gx) ⋀ S))) this)\n ) else (\n have (σ₁.apply x) = v, by { simp[h2] at h1, from h1 },\n show ∃σ₁ Q₁, ⊩ (σ₁[x↦v]) : Q₁, from ih₁ this\n )\n }\n end\n\nlemma env.dvcgen.tru.inv {σ: env} {x: var} {Q: prop}:\n (⊩ (σ[x ↦ value.true]) : Q ⋀ x ≡ value.true) → x ∉ σ ∧ (⊩ σ : Q) :=\n assume h: ⊩ (σ[x ↦ value.true]) : Q ⋀ x ≡ value.true,\n begin\n cases h,\n case env.dvcgen.tru h1 h2 { from ⟨h1, h2⟩ }\n end\n\nlemma env.dvcgen.fls.inv {σ: env} {x: var} {Q: prop}:\n (⊩ (σ[x ↦ value.false]) : Q ⋀ x ≡ value.false) → x ∉ σ ∧ (⊩ σ : Q) :=\n assume h: ⊩ (σ[x ↦ value.false]) : Q ⋀ x ≡ value.false,\n begin\n cases h,\n case env.dvcgen.fls h1 h2 { from ⟨h1, h2⟩ }\n end\n\nlemma env.dvcgen.num.inv {σ: env} {x: var} {n: ℕ} {Q: prop}:\n (⊩ (σ[x ↦ value.num n]) : Q ⋀ x ≡ value.num n) → x ∉ σ ∧ (⊩ σ : Q) :=\n assume h: ⊩ (σ[x ↦ value.num n]) : Q ⋀ x ≡ value.num n,\n begin\n cases h,\n case env.dvcgen.num h1 h2 { from ⟨h1, h2⟩ }\n end\n\nlemma env.dvcgen.func.inv {σ₁ σ₂: env} {f g x: var} {R S: spec} {e: exp} {Q: prop}:\n (⊩ (σ₁[f ↦ value.func g x R S e σ₂]) : Q) →\n ∃Q₁ Q₂ Q₃,\n f ∉ σ₁ ∧\n g ∉ σ₂ ∧\n x ∉ σ₂ ∧\n g ≠ x ∧\n (⊩ σ₁ : Q₁) ∧\n (⊩ σ₂ : Q₂) ∧\n x ∈ FV R.to_prop.to_vc ∧\n FV R.to_prop ⊆ FV Q₂ ∪ { g, x } ∧\n FV S.to_prop ⊆ FV Q₂ ∪ { g, x } ∧\n (Q₂ ⋀ spec.func g x R S ⋀ R ⊩ e : Q₃) ∧\n ⦃ prop.implies (Q₂ ⋀ spec.func g x R S ⋀ R ⋀ Q₃ (term.app g x)) S ⦄ ∧\n (Q = (Q₁ ⋀\n ((f ≡ (value.func g x R S e σ₂)) ⋀\n prop.subst_env (σ₂[g↦value.func g x R S e σ₂])\n (prop.func g x R (Q₃ (term.app g ↑x) ⋀ S))))) :=\n assume h : ⊩ (σ₁[f ↦ value.func g x R S e σ₂]) : Q,\n begin\n cases h,\n case env.dvcgen.func Q₁ Q₂ Q₃ f_not_in_σ₁ g_not_in_σ₂ x_not_in_σ₂ g_neq_x\n σ₁_verified σ₂_verified x_free_in_R fv_R fv_S e_verified func_vc {\n from ⟨Q₁, ⟨Q₂, ⟨Q₃,\n ⟨f_not_in_σ₁, ⟨g_not_in_σ₂, ⟨x_not_in_σ₂, ⟨g_neq_x, ⟨σ₁_verified,\n ⟨σ₂_verified, ⟨x_free_in_R, ⟨fv_R, ⟨fv_S, ⟨e_verified, ⟨func_vc, rfl⟩⟩⟩⟩⟩⟩⟩⟩⟩⟩⟩⟩⟩⟩\n }\n end\n\nlemma env.dvcgen.copy {σ₁ σ₂: env} {P₁ P₂} {x y: var} {v: value}:\n (⊩ σ₁ : P₁) → (y ∉ σ₁) → (⊩ (σ₂[x↦v]) : P₂) → ∃P₃, (⊩ (σ₁[y↦v]) : P₁ ⋀ P₃) :=\n assume σ₁_verified: ⊩ σ₁ : P₁,\n assume y_not_in_σ₁: y ∉ σ₁,\n assume σ₂_xv_verified: ⊩ (σ₂[x↦v]) : P₂,\n show ∃P₃, (⊩ (σ₁[y↦v]) : P₁ ⋀ P₃), by begin\n cases σ₂_xv_verified,\n case env.dvcgen.tru { from\n have ⊩ (σ₁[y↦value.true]) : P₁ ⋀ y ≡ value.true,\n from env.dvcgen.tru y_not_in_σ₁ σ₁_verified,\n show ∃P₃, ⊩ (σ₁[y↦value.true]) : P₁ ⋀ P₃, from exists.intro (y ≡ value.true) this\n },\n case env.dvcgen.fls { from\n have ⊩ (σ₁[y↦value.false]) : P₁ ⋀ y ≡ value.false,\n from env.dvcgen.fls y_not_in_σ₁ σ₁_verified,\n show ∃P₃, ⊩ (σ₁[y↦value.false]) : P₁ ⋀ P₃, from exists.intro (y ≡ value.false) this\n },\n case env.dvcgen.num n { from\n have ⊩ (σ₁[y↦value.num n]) : P₁ ⋀ y ≡ value.num n,\n from env.dvcgen.num y_not_in_σ₁ σ₁_verified,\n show ∃P₃, ⊩ (σ₁[y↦value.num n]) : P₁ ⋀ P₃, from exists.intro (y ≡ value.num n) this\n },\n case env.dvcgen.func σ₃ f fx R S e Q₃ Q₄ Q₂ x_not_in_σ₂ f_not_in_σ₃ fx_not_in_σ₃\n f_neq_fx σ₂_verified σ₃_verified x_free_in_R fv_R fv_S e_verified func_vc { from\n have ⊩ (σ₁[y↦value.func f fx R S e σ₃]) : (P₁\n ⋀ y ≡ value.func f fx R S e σ₃\n ⋀ prop.subst_env (σ₃[f↦value.func f fx R S e σ₃]) (prop.func f fx R (Q₃ (term.app f fx) ⋀ S))),\n from env.dvcgen.func y_not_in_σ₁ f_not_in_σ₃ fx_not_in_σ₃\n f_neq_fx σ₁_verified σ₃_verified x_free_in_R fv_R fv_S e_verified func_vc,\n show ∃P₃, ⊩ (σ₁[y↦value.func f fx R S e σ₃]) : P₁ ⋀ P₃,\n from exists.intro (\n y ≡ value.func f fx R S e σ₃\n ⋀ prop.subst_env (σ₃[f↦value.func f fx R S e σ₃]) (prop.func f fx R (Q₃ (term.app f fx) ⋀ S)))\n this\n }\n end\n\nlemma exp.dvcgen.inj {P: prop} {Q: propctx} {e: exp}: (P ⊩ e : Q) → ∀Q', (P ⊩ e : Q') → (Q = Q') :=\n assume h1: P ⊩ e : Q,\n begin\n induction h1,\n\n intros Q' h2,\n cases h2,\n have : (Q_1 = Q_2), from ih_1 Q_2 a_3,\n rw[this],\n\n intros Q' h2,\n cases h2,\n have : (Q_1 = Q_2), from ih_1 Q_2 a_3,\n rw[this],\n\n intros Q' h2,\n cases h2,\n have : (Q_1 = Q_2), from ih_1 Q_2 a_3,\n rw[this],\n\n intros Q' h2,\n cases h2,\n have h3: (Q₁ = Q₁_1), from ih_1 Q₁_1 a_15,\n rw[←h3] at a_16,\n have : (Q₂ = Q₂_1), from ih_2 Q₂_1 a_16,\n rw[this],\n rw[h3],\n\n intros Q' h2,\n cases h2,\n have : (Q_1 = Q_2), from ih_1 Q_2 a_6,\n rw[this],\n\n intros Q' h2,\n cases h2,\n have : (Q_1 = Q_2), from ih_1 Q_2 a_8,\n rw[this],\n\n intros Q' h2,\n cases h2,\n have : (Q_1 = Q_2), from ih_1 Q_2 a_8,\n rw[this],\n\n intros Q' h2,\n cases h2,\n have : (Q₁ = Q₁_1), from ih_1 Q₁_1 a_5,\n rw[this],\n have : (Q₂ = Q₂_1), from ih_2 Q₂_1 a_6,\n rw[this],\n refl,\n\n intros Q' h2,\n cases h2,\n refl\n end\n\nlemma env.dvcgen.inj {P: prop} {σ: env}: (⊩ σ : P) → ∀Q, (⊩ σ : Q) → (P = Q) :=\n assume h1: ⊩ σ : P,\n begin\n induction h1,\n\n intros Q h2,\n cases h2,\n refl,\n\n intros Q h2,\n cases h2,\n have : (Q = Q_1), from ih_1 Q_1 a_3,\n rw[this],\n refl,\n\n intros Q h2,\n cases h2,\n have : (Q = Q_1), from ih_1 Q_1 a_3,\n rw[this],\n refl,\n\n intros Q h2,\n cases h2,\n have : (Q = Q_1), from ih_1 Q_1 a_3,\n rw[this],\n refl,\n\n intros Q h2,\n cases h2,\n have h3: (Q₁ = Q₁_1), from ih_1 Q₁_1 a_15,\n rw[h3],\n have h4: (Q₂ = Q₂_1), from ih_2 Q₂_1 a_16,\n rw[←h4] at a_20,\n have : (Q₃ = Q₃_1), from exp.dvcgen.inj a_9 Q₃_1 a_20,\n rw[this],\n refl\n end\n\nlemma stack.dvcgen.inj {s: dstack} {Q₁: propctx}: (⊩ₛ s : Q₁) → ∀Q₂, (⊩ₛ s : Q₂) → (Q₁ = Q₂) :=\n assume h1: ⊩ₛ s : Q₁,\n have ∀s' Q₂, (s = s') → (⊩ₛ s' : Q₂) → (Q₁ = Q₂), by begin\n cases h1,\n\n intros s' Q₂ h2 h3,\n cases h3,\n\n injection h2,\n have h4: (R = R_1), from h_1,\n have h6: (σ = σ_1), from h_2,\n have h7: (e = e_1), from h_3,\n have h8: (P = P_1), from env.dvcgen.inj a P_1 (h6.symm ▸ a_4),\n have : ↑R ⋀ P ⊩ e : Q_1, from h4.symm ▸ h7.symm ▸ h8.symm ▸ a_7,\n have h9: (Q = Q_1), from exp.dvcgen.inj a_3 Q_1 this,\n rw[←h8],\n rw[←h9],\n\n contradiction,\n\n intros s' Q₂ h2 h3,\n cases h3,\n\n contradiction,\n\n injection h2,\n\n have h4: (P₁ = P₁_1), from env.dvcgen.inj a_2 P₁_1 (h_3.symm ▸ a_17),\n rw[h4.symm] at a_24,\n rw[h_4.symm] at a_24,\n rw[h_5.symm] at a_24,\n rw[h_7.symm] at a_24,\n rw[h_6.symm] at a_24,\n rw[h_2.symm] at a_24,\n have h5: (Q₁_1 = Q₁), from exp.dvcgen.inj a_9 Q₁ a_24,\n rw[←h4],\n rw[←h_5],\n rw[←h_6],\n rw[←h_4],\n rw[h5]\n end,\n show ∀Q₂, (⊩ₛ s : Q₂) → (Q₁ = Q₂),\n from λQ₂ h1, (this s Q₂) rfl h1\n", "meta": {"author": "levjj", "repo": "esverify-theory", "sha": "8565b123c87b0113f83553d7732cd6696c9b5807", "save_path": "github-repos/lean/levjj-esverify-theory", "path": "github-repos/lean/levjj-esverify-theory/esverify-theory-8565b123c87b0113f83553d7732cd6696c9b5807/src/vcgen.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4455295350395727, "lm_q2_score": 0.026759280662960457, "lm_q1q2_score": 0.011922049871762201}} {"text": "/-\nCopyright (c) 2021-2022 by the authors listed in the file AUTHORS and their\ninstitutional affiliations. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Wojciech Nawrocki\n-/\n\n/-- The type of S-expressions. -/\ninductive Sexp where\n | atom : String → Sexp\n | expr : List Sexp → Sexp\n deriving Repr, BEq, Inhabited\n\nclass ToSexp (α : Type u) where\n toSexp : α → Sexp\n\nnamespace Sexp\n\npartial def serialize : Sexp → String\n | atom s => s\n | expr ss => \"(\" ++ (\" \".intercalate <| ss.map serialize) ++ \")\"\n\ndef serializeMany (ss : List Sexp) : String :=\n ss.map serialize |> \"\\n\".intercalate\n\ninstance : ToString Sexp :=\n ⟨serialize⟩\n\ninductive ParseError where\n | /-- Incomplete input, for example missing a closing parenthesis. -/\n incomplete (msg : String)\n | /-- Malformed input, for example having too many closing parentheses. -/\n malformed (msg : String)\n\ninstance : ToString ParseError where\n toString\n | .incomplete msg => s!\"incomplete input: {msg}\"\n | .malformed msg => s!\"malformed input: {msg}\"\n\n/-- Tokenize `s` with the s-expression grammar. Supported token kinds are more or less as in\nhttps://smtlib.cs.uiowa.edu/papers/smt-lib-reference-v2.6-r2021-05-12.pdf:\n- parentheses `(`/`)`\n- symbols `abc`\n- quoted symbols `|abc|`\n- string literals `\"abc\"` -/\npartial def tokenize (s : Substring) : Except ParseError (Array Substring) :=\n go #[] s\nwhere go (stk : Array Substring) (s : Substring) :=\n -- Note: not written using `do` notation to ensure tail-call recursion\n if s.isEmpty then .ok stk\n else\n let c := s.front\n if c == '\"' || c == '|' then\n let s1 := s.drop 1 |>.takeWhile (· ≠ c)\n if s1.stopPos = s.stopPos then\n throw <| .incomplete s!\"ending {c} missing after {s1}\"\n else\n let s1 := ⟨s.str, s.startPos, s.next s1.stopPos⟩\n let s2 := ⟨s.str, s1.stopPos, s.stopPos⟩\n go (stk.push s1) s2\n else if c == ')' || c == '(' then\n go (stk.push <| s.take 1) (s.drop 1)\n else if c.isWhitespace then\n go stk (s.drop 1)\n else\n let tk := s.takeWhile fun c =>\n !c.isWhitespace && c != '(' && c != ')' && c != '|' && c != '\"'\n -- assertion: tk.bsize > 0 as otherwise we would have gone into one of the branches above\n go (stk.push tk) (s.extract ⟨tk.bsize⟩ ⟨s.bsize⟩)\n\nmutual\npartial def parseOneAux : List Substring → Except ParseError (Sexp × List Substring)\n | tk :: tks => do\n if tk.front == ')' then\n throw <| .malformed \"unexpected ')'\"\n if tk.front == '(' then\n if let (ss, _tk :: tks) ← parseManyAux tks then\n -- assertion: _tk == ')' since parseManyAux only stops on ')'\n return (expr ss.toList, tks)\n else\n throw <| .incomplete \"expected ')'\"\n else\n return (atom tk.toString, tks)\n | [] => throw <| .incomplete \"expected a token, got none\"\n\npartial def parseManyAux :=\n go #[]\nwhere go (stk : Array Sexp) : List Substring → Except ParseError (Array Sexp × List Substring)\n | tk :: tks => do\n if tk.front == ')' then .ok (stk, tk :: tks)\n else\n let (e, tks) ← parseOneAux (tk :: tks)\n go (stk.push e) tks\n | [] => .ok (stk, [])\nend\n\n/-- Parse all the s-expressions in the given string. For example, `\"(abc) (def)\"` contains two. -/\ndef parseMany (s : String) : Except ParseError (List Sexp) := do\n let tks ← tokenize s.toSubstring\n let (sexps, tks) ← parseManyAux tks.toList\n if !tks.isEmpty then\n throw <| .malformed s!\"unexpected '{tks.get! 0}'\"\n return sexps.toList\n\n/-- Parse a single s-expression. Note that the string may contain extra data, but parsing will\nsucceed as soon as the single s-exp is complete. -/\ndef parseOne (s : String) : Except ParseError Sexp := do\n let tks ← tokenize s.toSubstring\n let (sexp, _) ← parseOneAux tks.toList\n return sexp\n\nend Sexp\n", "meta": {"author": "ufmg-smite", "repo": "lean-smt", "sha": "6de0c4b216a918a14cf7a47d9a6faccaf8c8a209", "save_path": "github-repos/lean/ufmg-smite-lean-smt", "path": "github-repos/lean/ufmg-smite-lean-smt/lean-smt-6de0c4b216a918a14cf7a47d9a6faccaf8c8a209/Smt/Data/Sexp.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2365162472088944, "lm_q2_score": 0.05033063295359571, "lm_q1q2_score": 0.011904012425832769}} {"text": "/-\n# `MetaM`\n\nThe Lean 4 metaprogramming API is organised around a small zoo of monads. The\nfour main ones are:\n\n- `CoreM` gives access to the *environment*, i.e. the set of things that\n have been declared or imported at the current point in the program.\n- `MetaM` gives access to the *metavariable context*, i.e. the set of\n metavariables that are currently declared and the values assigned to them (if\n any).\n- `TermElabM` gives access to various information used during elaboration.\n- `TacticM` gives access to the list of current goals.\n\nThese monads extend each other, so a `MetaM` operation also has access to the\nenvironment and a `TermElabM` computation can use metavariables. There are also\nother monads which do not neatly fit into this hierarchy, e.g. `CommandElabM`\nextends `MetaM` but neither extends nor is extended by `TermElabM`.\n\nThis chapter demonstrates a number of useful operations in the `MetaM` monad.\n`MetaM` is of particular importance because it allows us to give meaning to\nevery expression: the environment (from `CoreM`) gives meaning to constants like\n`Nat.zero` or `List.map` and the metavariable context gives meaning to both\nmetavariables and local hypotheses. -/\n\nimport Lean\n\nopen Lean Lean.Expr Lean.Meta\n\n/-!\n## Metavariables\n\n### Overview\n\nThe 'Meta' in `MetaM` refers to metavariables, so we should talk about these\nfirst. Lean users do not usually interact much with metavariables -- at least\nnot consciously -- but they are used all over the place in metaprograms. There\nare two ways to view them: as holes in an expression or as goals.\n\nTake the goal perspective first. When we prove things in Lean, we always operate\non goals, such as\n\n```lean\nn m : Nat\n⊢ n + m = m + n\n```\n\nThese goals are internally represented by metavariables. Accordingly, each\nmetavariable has a *local context* containing hypotheses (here `[n : Nat, m :\nNat]`) and a *target type* (here `n + m = m + n`). Metavariables also have a\nunique name, say `m`, and we usually render them as `?m`.\n\nTo close a goal, we must give an expression `e` of the target type. The\nexpression may contain fvars from the metavariable's local context, but no\nothers. Internally, closing a goal in this way corresponds to *assigning* the\nmetavariable; we write `?m := e` for this assignment.\n\nThe second, complementary view of metavariables is that they represent holes\nin an expression. For instance, an application of `Eq.trans` may generate two\ngoals which look like this:\n\n```lean\nn m : Nat\n⊢ n = ?x\n\nn m : Nat\n⊢ ?x = m\n```\n\nHere `?x` is another metavariable -- a hole in the target types of both goals,\nto be filled in later during the proof. The type of `?x` is `Nat` and its local\ncontext is `[n : Nat, m : Nat]`. Now, if we solve the first goal by reflexivity,\nthen `?x` must be `n`, so we assign `?x := n`. Crucially, this also affects the\nsecond goal: it is \"updated\" (not really, as we will see) to have target `n =\nm`. The metavariable `?x` represents the same expression everywhere it occurs.\n\n\n### Tactic Communication via Metavariables\n\nTactics use metavariables to communicate the current goals. To see how, consider\nthis simple (and slightly artificial) proof:\n-/\n\nexample {α} (a : α) (f : α → α) (h : ∀ a, f a = a) : f (f a) = a := by\n apply Eq.trans\n apply h\n apply h\n\n/-!\nAfter we enter tactic mode, our ultimate goal is to generate an expression of\ntype `f (f a) = a` which may involve the hypotheses `α`, `a`, `f` and `h`. So\nLean generates a metavariable `?m1` with target `f (f a) = a` and a local\ncontext containing these hypotheses. This metavariable is passed to the first\n`apply` tactic as the current goal.\n\nThe `apply` tactic then tries to apply `Eq.trans` and succeeds, generating three\nnew metavariables:\n\n```lean\n...\n⊢ f (f a) = ?b\n\n...\n⊢ ?b = a\n\n...\n⊢ α\n```\n\nCall these metavariables `?m2`, `?m3` and `?b`. The last one, `?b`, stands for\nthe intermediate element of the transitivity proof and occurs in `?m2` and\n`?m3`. The local contexts of all metavariables in this proof are the same, so\nwe omit them.\n\nHaving created these metavariables, `apply` assigns\n\n```lean\n?m1 := @Eq.trans α (f (f a)) ?b a ?m2 ?m3\n```\n\nand reports that `?m2`, `?m3` and `?b` are now the current goals.\n\nAt this point the second `apply` tactic takes over. It receives `?m2` as the\ncurrent goal and applies `h` to it. This succeeds and the tactic assigns `?m2 :=\nh (f a)`. This assignment implies that `?b` must be `f a`, so the tactic also\nassigns `?b := f a`. Assigned metavariables are not considered open goals, so\nthe only goal that remains is `?m3`.\n\nNow the third `apply` comes in. Since `?b` has been assigned, the target of\n`?m3` is now `f (f a) = a`. Again, the application of `h` succeeds and the\ntactic assigns `?m3 := h a`.\n\nAt this point, all metavariables are assigned as follows:\n\n```lean\n?m1 := @Eq.trans α (f (f a)) ?b a ?m2 ?m3\n?m2 := h (f a)\n?m3 := h a\n?b := f a\n```\n\nExiting the `by` block, Lean constructs the final proof term by taking the\nassignment of `?m1` and replacing each metavariable with its assignment. This\nyields\n\n```lean\n@Eq.trans α (f (f a)) (f a) a (h (f a)) (h a)\n```\n\nThe example also shows how the two views of metavariables -- as holes in an\nexpression or as goals -- are related: the goals we get are holes in the final\nproof term.\n\n\n### Basic Operations\n\nLet us make these concepts concrete. When we operate in the `MetaM` monad, we\nhave read-write access to a `MetavarContext` structure containing information\nabout the currently declared metavariables. Each metavariable is identified by\nan `MVarId` (a unique `Name`). To create a new metavariable, we use\n`Lean.Meta.mkFreshExprMVar` with type\n\n```lean\nmkFreshExprMVar (type? : Option Expr) (kind := MetavarKind.natural)\n (userName := Name.anonymous) : MetaM Expr\n```\n\nIts arguments are:\n\n- `type?`: the target type of the new metavariable. If `none`, the target type\n is `Sort ?u`, where `?u` is a universe level metavariable. (This is a special\n class of metavariables for universe levels, distinct from the expression\n metavariables which we have been calling simply \"metavariables\".)\n- `kind`: the metavariable kind. See the [Metavariable Kinds\n section](#metavariable-kinds) (but the default is usually correct).\n- `userName`: the new metavariable's user-facing name. This is what gets printed\n when the metavariable appears in a goal. Unlike the `MVarId`, this name does\n not need to be unique.\n\nThe returned `Expr` is always a metavariable. We can use `Lean.Expr.mvarId!` to\nextract the `MVarId`, which is guaranteed to be unique. (Arguably\n`mkFreshExprMVar` should just return the `MVarId`.)\n\nThe local context of the new metavariable is inherited from the current local\ncontext, more about which in the next section. If you want to give a different\nlocal context, use `Lean.Meta.mkFreshExprMVarAt`.\n\nMetavariables are initially unassigned. To assign them, use\n`Lean.MVarId.assign` with type\n\n```lean\nassign (mvarId : MVarId) (val : Expr) : MetaM Unit\n```\n\nThis updates the `MetavarContext` with the assignment `?mvarId := val`. You must\nmake sure that `mvarId` is not assigned yet (or that the old assignment is\ndefinitionally equal to the new assignment). You must also make sure that the\nassigned value, `val`, has the right type. This means (a) that `val` must have\nthe target type of `mvarId` and (b) that `val` must only contain fvars from the\nlocal context of `mvarId`.\n\nIf you `#check Lean.MVarId.assign`, you will see that its real type is more\ngeneral than the one we showed above: it works in any monad that has access to a\n`MetavarContext`. But `MetaM` is by far the most important such monad, so in\nthis chapter, we specialise the types of `assign` and similar functions.\n\nTo get information about a declared metavariable, use `Lean.MVarId.getDecl`.\nGiven an `MVarId`, this returns a `MetavarDecl` structure. (If no metavariable\nwith the given `MVarId` is declared, the function throws an exception.) The\n`MetavarDecl` contains information about the metavariable, e.g. its type, local\ncontext and user-facing name. This function has some convenient variants, such\nas `Lean.MVarId.getType`.\n\nTo get the current assignment of a metavariable (if any), use\n`Lean.getExprMVarAssignment?`. To check whether a metavariable is assigned, use\n`Lean.MVarId.isAssigned`. However, these functions are relatively rarely\nused in tactic code because we usually prefer a more powerful operation:\n`Lean.Meta.instantiateMVars` with type\n\n```lean\ninstantiateMVars : Expr → MetaM Expr\n```\n\nGiven an expression `e`, `instantiateMVars` replaces any assigned metavariable\n`?m` in `e` with its assigned value. Unassigned metavariables remain as they\nare.\n\nThis operation should be used liberally. When we assign a metavariable, existing\nexpressions containing this metavariable are not immediately updated. This is a\nproblem when, for example, we match on an expression to check whether it is an\nequation. Without `instantiateMVars`, we might miss the fact that the expression\n`?m`, where `?m` happens to be assigned to `0 = n`, represents an equation. In\nother words, `instantiateMVars` brings our expressions up to date with the\ncurrent metavariable state.\n\nInstantiating metavariables requires a full traversal of the input expression,\nso it can be somewhat expensive. But if the input expression does not contain\nany metavariables, `instantiateMVars` is essentially free. Since this is the\ncommon case, liberal use of `instantiateMVars` is fine in most situations.\n\nBefore we go on, here is a synthetic example demonstrating how the basic\nmetavariable operations are used. More natural examples appear in the following\nsections.\n-/\n\n#eval show MetaM Unit from do\n -- Create two fresh metavariables of type `Nat`.\n let mvar1 ← mkFreshExprMVar (Expr.const ``Nat []) (userName := `mvar1)\n let mvar2 ← mkFreshExprMVar (Expr.const ``Nat []) (userName := `mvar2)\n -- Create a fresh metavariable of type `Nat → Nat`. The `mkArrow` function\n -- creates a function type.\n let mvar3 ← mkFreshExprMVar (← mkArrow (.const ``Nat []) (.const ``Nat []))\n (userName := `mvar3)\n\n -- Define a helper function that prints each metavariable.\n let printMVars : MetaM Unit := do\n IO.println s!\" meta1: {← instantiateMVars mvar1}\"\n IO.println s!\" meta2: {← instantiateMVars mvar2}\"\n IO.println s!\" meta3: {← instantiateMVars mvar3}\"\n\n IO.println \"Initially, all metavariables are unassigned:\"\n printMVars\n\n -- Assign `mvar1 : Nat := ?mvar3 ?mvar2`.\n mvar1.mvarId!.assign (.app mvar3 mvar2)\n IO.println \"After assigning mvar1:\"\n printMVars\n\n -- Assign `mvar2 : Nat := 0`.\n mvar2.mvarId!.assign (.const ``Nat.zero [])\n IO.println \"After assigning mvar2:\"\n printMVars\n\n -- Assign `mvar3 : Nat → Nat := Nat.succ`.\n mvar3.mvarId!.assign (.const ``Nat.succ [])\n IO.println \"After assigning mvar3:\"\n printMVars\n-- Initially, all metavariables are unassigned:\n-- meta1: ?_uniq.1\n-- meta2: ?_uniq.2\n-- meta3: ?_uniq.3\n-- After assigning mvar1:\n-- meta1: ?_uniq.3 ?_uniq.2\n-- meta2: ?_uniq.2\n-- meta3: ?_uniq.3\n-- After assigning mvar2:\n-- meta1: ?_uniq.3 Nat.zero\n-- meta2: Nat.zero\n-- meta3: ?_uniq.3\n-- After assigning mvar3:\n-- meta1: Nat.succ Nat.zero\n-- meta2: Nat.zero\n-- meta3: Nat.succ\n\n\n/-!\n### Local Contexts\n\nConsider the expression `e` which refers to the free variable with unique name\n`h`:\n\n```lean\ne := .fvar (FVarId.mk `h)\n```\n\nWhat is the type of this expression? The answer depends on the local context in\nwhich `e` is interpreted. One local context may declare that `h` is a local\nhypothesis of type `Nat`; another local context may declare that `h` is a local\ndefinition with value `List.map`.\n\nThus, expressions are only meaningful if they are interpreted in the local\ncontext for which they were intended. And as we saw, each metavariable has its\nown local context. So in principle, functions which manipulate expressions\nshould have an additional `MVarId` argument specifying the goal in which the\nexpression should be interpreted.\n\nThat would be cumbersome, so Lean goes a slightly different route. In `MetaM`,\nwe always have access to an ambient `LocalContext`, obtained with `Lean.getLCtx`\nof type\n\n```lean\ngetLCtx : MetaM LocalContext\n```\n\nAll operations involving fvars use this ambient local context.\n\nThe downside of this setup is that we always need to update the ambient local\ncontext to match the goal we are currently working on. To do this, we use\n`Lean.MVarId.withContext` of type\n\n```lean\nwithContext (mvarId : MVarId) (c : MetaM α) : MetaM α\n```\n\nThis function takes a metavariable `mvarId` and a `MetaM` computation `c` and\nexecutes `c` with the ambient context set to the local context of `mvarId`. A\ntypical use case looks like this:\n\n```lean\ndef someTactic (mvarId : MVarId) ... : ... :=\n mvarId.withContext do\n ...\n```\n\nThe tactic receives the current goal as the metavariable `mvarId` and\nimmediately sets the current local context. Any operations within the `do` block\nthen use the local context of `mvarId`.\n\nOnce we have the local context properly set, we can manipulate fvars. Like\nmetavariables, fvars are identified by an `FVarId` (a unique `Name`). Basic\noperations include:\n\n- `Lean.FVarId.getDecl : FVarId → MetaM LocalDecl` retrieves the declaration\n of a local hypothesis. As with metavariables, a `LocalDecl` contains all\n information pertaining to the local hypothesis, e.g. its type and its\n user-facing name.\n- `Lean.Meta.getLocalDeclFromUserName : Name → MetaM LocalDecl` retrieves the\n declaration of the local hypothesis with the given user-facing name. If there\n are multiple such hypotheses, the bottommost one is returned. If there is\n none, an exception is thrown.\n\nWe can also iterate over all hypotheses in the local context, using the `ForIn`\ninstance of `LocalContext`. A typical pattern is this:\n\n```lean\nfor ldecl in ← getLCtx do\n if ldecl.isImplementationDetail then\n continue\n -- do something with the ldecl\n```\n\nThe loop iterates over every `LocalDecl` in the context. The\n`isImplementationDetail` check skips local hypotheses which are 'implementation\ndetails', meaning they are introduced by Lean or by tactics for bookkeeping\npurposes. They are not shown to users and tactics are expected to ignore them.\n\nAt this point, we can build the `MetaM` part of an `assumption` tactic:\n-/\n\ndef myAssumption (mvarId : MVarId) : MetaM Bool := do\n -- Check that `mvarId` is not already assigned.\n mvarId.checkNotAssigned `myAssumption\n -- Use the local context of `mvarId`.\n mvarId.withContext do\n -- The target is the type of `mvarId`.\n let target ← mvarId.getType\n -- For each hypothesis in the local context:\n for ldecl in ← getLCtx do\n -- If the hypothesis is an implementation detail, skip it.\n if ldecl.isImplementationDetail then\n continue\n -- If the type of the hypothesis is definitionally equal to the target\n -- type:\n if ← isDefEq ldecl.type target then\n -- Use the local hypothesis to prove the goal.\n mvarId.assign ldecl.toExpr\n -- Stop and return true.\n return true\n -- If we have not found any suitable local hypothesis, return false.\n return false\n\n/-\nThe `myAssumption` tactic contains three functions we have not seen before:\n\n- `Lean.MVarId.checkNotAssigned` checks that a metavariable is not already\n assigned. The 'myAssumption' argument is the name of the current tactic. It is\n used to generate a nicer error message.\n- `Lean.Meta.isDefEq` checks whether two definitions are definitionally equal.\n See the [Definitional Equality section](#definitional-equality).\n- `Lean.LocalDecl.toExpr` is a helper function which constructs the `fvar`\n expression corresponding to a local hypothesis.\n\n\n### Delayed Assignments\n\nThe above discussion of metavariable assignment contains a lie by omission:\nthere are actually two ways to assign a metavariable. We have seen the regular\nway; the other way is called a *delayed assignment*.\n\nWe do not discuss delayed assignments in any detail here since they are rarely\nuseful for tactic writing. If you want to learn more about them, see the\ncomments in `MetavarContext.lean` in the Lean standard library. But they create\ntwo complications which you should be aware of.\n\nFirst, delayed assignments make `Lean.MVarId.isAssigned` and\n`getExprMVarAssignment?` medium-calibre footguns. These functions only check for\nregular assignments, so you may need to use `Lean.MVarId.isDelayedAssigned`\nand `Lean.Meta.getDelayedMVarAssignment?` as well.\n\nSecond, delayed assignments break an intuitive invariant. You may have assumed\nthat any metavariable which remains in the output of `instantiateMVars` is\nunassigned, since the assigned metavariables have been substituted. But delayed\nmetavariables can only be substituted once their assigned value contains no\nunassigned metavariables. So delayed-assigned metavariables can appear in an\nexpression even after `instantiateMVars`.\n\n\n### Metavariable Depth\n\nMetavariable depth is also a niche feature, but one that is occasionally useful.\nAny metavariable has a *depth* (a natural number), and a `MetavarContext` has a\ncorresponding depth as well. Lean only assigns a metavariable if its depth is\nequal to the depth of the current `MetavarContext`. Newly created metavariables\ninherit the `MetavarContext`'s depth, so by default every metavariable is\nassignable.\n\nThis setup can be used when a tactic needs some temporary metavariables and also\nneeds to make sure that other, non-temporary metavariables will not be assigned.\nTo ensure this, the tactic proceeds as follows:\n\n1. Save the current `MetavarContext`.\n2. Increase the depth of the `MetavarContext`.\n3. Perform whatever computation is necessary, possibly creating and assigning\n metavariables. Newly created metavariables are at the current depth of the\n `MetavarContext` and so can be assigned. Old metavariables are at a lower\n depth, so cannot be assigned.\n4. Restore the saved `MetavarContext`, thereby erasing all the temporary\n metavariables and resetting the `MetavarContext` depth.\n\nThis pattern is encapsulated in `Lean.Meta.withNewMCtxDepth`.\n\n\n## Computation\n\nComputation is a core concept of dependent type theory. The terms `2`, `Nat.succ\n1` and `1 + 1` are all \"the same\" in the sense that they compute the same value.\nWe call them *definitionally equal*. The problem with this, from a\nmetaprogramming perspective, is that definitionally equal terms may be\nrepresented by entirely different expressions, but our users would usually\nexpect that a tactic which works for `2` also works for `1 + 1`. So when we\nwrite our tactics, we must do additional work to ensure that definitionally\nequal terms are treated similarly.\n\n### Full Normalisation\n\nThe simplest thing we can do with computation is to bring a term into normal\nform. With some exceptions for numeric types, the normal form of a term `t` of\ntype `T` is a sequence of applications of `T`'s constructors. E.g. the normal\nform of a list is a sequence of applications of `List.cons` and `List.nil`.\n\nThe function that normalises a term (i.e. brings it into normal form) is\n`Lean.Meta.reduce` with type signature\n\n```lean\nreduce (e : Expr) (explicitOnly skipTypes skipProofs := true) : MetaM Expr\n```\n\nWe can use it like this:\n-/\n\ndef someNumber : Nat := (· + 2) $ 3\n\n#eval Expr.const ``someNumber []\n-- Lean.Expr.const `someNumber []\n\n#eval reduce (Expr.const ``someNumber [])\n-- Lean.Expr.lit (Lean.Literal.natVal 5)\n\n/-!\nIncidentally, this shows that the normal form of a term of type `Nat` is not\nalways an application of the constructors of `Nat`; it can also be a literal.\nAlso note that `#eval` can be used not only to evaluate a term, but also to\nexecute a `MetaM` program.\n\nThe optional arguments of `reduce` allow us to skip certain parts of an\nexpression. E.g. `reduce e (explicitOnly := true)` does not normalise any\nimplicit arguments in the expression `e`. This yields better performance: since\nnormal forms can be very big, it may be a good idea to skip parts of an\nexpression that the user is not going to see anyway.\n\nThe `#reduce` command is essentially an application of `reduce`:\n-/\n\n#reduce someNumber\n-- 5\n\n/-!\n### Transparency\n\nAn ugly but important detail of Lean 4 metaprogramming is that any given\nexpression does not have a single normal form. Rather, it has a normal form up\nto a given *transparency*.\n\nA transparency is a value of `Lean.Meta.TransparencyMode`, an enumeration with\nfour values: `reducible`, `instances`, `default` and `all`. Any `MetaM`\ncomputation has access to an ambient `TransparencyMode` which can be obtained\nwith `Lean.Meta.getTransparency`.\n\nThe current transparency determines which constants get unfolded during\nnormalisation, e.g. by `reduce`. (To unfold a constant means to replace it with\nits definition.) The four settings unfold progressively more constants:\n\n- `reducible`: unfold only constants tagged with the `@[reducible]` attribute.\n Note that `abbrev` is a shorthand for `@[reducible] def`.\n- `instances`: unfold reducible constants and constants tagged with the\n `@[instance]` attribute. Again, the `instance` command is a shorthand for\n `@[instance] def`.\n- `default`: unfold all constants except those tagged as `@[irreducible]`.\n- `all`: unfold all constants, even those tagged as `@[irreducible]`.\n\nThe ambient transparency is usually `default`. To execute an operation with a\nspecific transparency, use `Lean.Meta.withTransparency`. There are also\nshorthands for specific transparencies, e.g. `Lean.Meta.withReducible`.\n\nPutting everything together for an example (where we use `Lean.Meta.ppExpr` to\npretty-print an expression): -/\n\ndef traceConstWithTransparency (md : TransparencyMode) (c : Name) :\n MetaM Format := do\n ppExpr (← withTransparency md $ reduce (.const c []))\n\n@[irreducible] def irreducibleDef : Nat := 1\ndef defaultDef : Nat := irreducibleDef + 1\nabbrev reducibleDef : Nat := defaultDef + 1\n\n/-!\nWe start with `reducible` transparency, which only unfolds `reducibleDef`:\n-/\n\n#eval traceConstWithTransparency .reducible ``reducibleDef\n-- defaultDef + 1\n\n/-!\nIf we repeat the above command but let Lean print implicit arguments as well,\nwe can see that the `+` notation amounts to an application of the `hAdd`\nfunction, which is a member of the `HAdd` typeclass:\n-/\n\nset_option pp.explicit true\n#eval traceConstWithTransparency .reducible ``reducibleDef\n-- @HAdd.hAdd Nat Nat Nat (@instHAdd Nat instAddNat) defaultDef 1\n\n/-!\nWhen we reduce with `instances` transparency, this applications is unfolded and\nreplaced by `Nat.add`:\n-/\n\n#eval traceConstWithTransparency .instances ``reducibleDef\n-- Nat.add defaultDef 1\n\n/-!\nWith `default` transparency, `Nat.add` is unfolded as well:\n-/\n\n#eval traceConstWithTransparency .default ``reducibleDef\n-- Nat.succ (Nat.succ irreducibleDef)\n\n/-!\nAnd with `TransparencyMode.all`, we're finally able to unfold `irreducibleDef`:\n-/\n\n#eval traceConstWithTransparency .all ``reducibleDef\n-- 3\n\n/-!\nThe `#eval` commands illustrate that the same term, `reducibleDef`, can have a\ndifferent normal form for each transparency.\n\nWhy all this ceremony? Essentially for performance: if we allowed normalisation\nto always unfold every constant, operations such as type class search would\nbecome prohibitively expensive. The tradeoff is that we must choose the\nappropriate transparency for each operation that involves normalisation.\n\n\n### Weak Head Normalisation\n\nTransparency addresses some of the performance issues with normalisation. But\neven more important is to recognise that for many purposes, we don't need to\nfully normalise terms at all. Suppose we are building a tactic that\nautomatically splits hypotheses of the type `P ∧ Q`. We might want this tactic\nto recognise a hypothesis `h : X` if `X` reduces to `P ∧ Q`. But if `P`\nadditionally reduces to `Y ∨ Z`, the specific `Y` and `Z` do not concern us.\nReducing `P` would be unnecessary work.\n\nThis situation is so common that the fully normalising `reduce` is in fact\nrarely used. Instead, the normalisation workhorse of Lean is `whnf`, which\nreduces an expression to *weak head normal form* (WHNF).\n\nRoughly speaking, an expression `e` is in weak-head normal form when it has the\nform\n\n```text\ne = f x₁ ... xₙ (n ≥ 0)\n```\n\nand `f` cannot be reduced (at the current transparency). To conveniently check\nthe WHNF of an expression, we define a function `whnf'`, using some functions\nthat will be discussed in the Elaboration chapter.\n-/\n\nopen Lean.Elab.Term in\ndef whnf' (e : TermElabM Syntax) : TermElabM Format := do\n let e ← elabTermAndSynthesize (← e) none\n ppExpr (← whnf e)\n\n/-!\nNow, here are some examples of expressions in WHNF.\n\nConstructor applications are in WHNF (with some exceptions for numeric types):\n-/\n\n#eval whnf' `(List.cons 1 [])\n-- [1]\n\n/-!\nThe *arguments* of an application in WHNF may or may not be in WHNF themselves:\n-/\n\n#eval whnf' `(List.cons (1 + 1) [])\n-- [1 + 1]\n\n/-!\nApplications of constants are in WHNF if the current transparency does not\nallow us to unfold the constants:\n-/\n\n#eval withTransparency .reducible $ whnf' `(List.append [1] [2])\n-- List.append [1] [2]\n\n/-!\nLambdas are in WHNF:\n-/\n\n#eval whnf' `(λ x : Nat => x)\n-- fun x => x\n\n/-!\nForalls are in WHNF:\n-/\n\n#eval whnf' `(∀ x, x > 0)\n-- ∀ (x : Nat), x > 0\n\n/-!\nSorts are in WHNF:\n-/\n\n#eval whnf' `(Type 3)\n-- Type 3\n\n/-!\nLiterals are in WHNF:\n-/\n\n#eval whnf' `((15 : Nat))\n-- 15\n\n/-!\nHere are some more expressions in WHNF which are a bit tricky to test:\n\n```lean\n?x 0 1 -- Assuming the metavariable `?x` is unassigned, it is in WHNF.\nh 0 1 -- Assuming `h` is a local hypothesis, it is in WHNF.\n```\n\nOn the flipside, here are some expressions that are not in WHNF.\n\nApplications of constants are not in WHNF if the current transparency allows us\nto unfold the constants:\n-/\n\n#eval whnf' `(List.append [1])\n-- fun x => 1 :: List.append [] x\n\n/-!\nApplications of lambdas are not in WHNF:\n-/\n\n#eval whnf' `((λ x y : Nat => x + y) 1)\n-- `fun y => 1 + y`\n\n/-!\n`let` bindings are not in WHNF:\n-/\n\n#eval whnf' `(let x : Nat := 1; x)\n-- 1\n\n/-!\nAnd again some tricky examples:\n\n```lean\n?x 0 1 -- Assuming `?x` is assigned (e.g. to `Nat.add`), its application is not\n in WHNF.\nh 0 1 -- Assuming `h` is a local definition (e.g. with value `Nat.add`), its\n application is not in WHNF.\n```\n\nReturning to the tactic that motivated this section, let us write a function\nthat matches a type of the form `P ∧ Q`, avoiding extra computation. WHNF\nmakes it easy:\n-/\n\ndef matchAndReducing (e : Expr) : MetaM (Option (Expr × Expr)) := do\n match ← whnf e with\n | (.app (.app (.const ``And _) P) Q) => return some (P, Q)\n | _ => return none\n\n/-\nBy using `whnf`, we ensure that if `e` evaluates to something of the form `P\n∧ Q`, we'll notice. But at the same time, we don't perform any unnecessary\ncomputation in `P` or `Q`.\n\nHowever, our 'no unnecessary computation' mantra also means that if we want to\nperform deeper matching on an expression, we need to use `whnf` multiple times.\nSuppose we want to match a type of the form `P ∧ Q ∧ R`. The correct way to do\nthis uses `whnf` twice:\n-/\n\ndef matchAndReducing₂ (e : Expr) : MetaM (Option (Expr × Expr × Expr)) := do\n match ← whnf e with\n | (.app (.app (.const ``And _) P) e') =>\n match ← whnf e' with\n | (.app (.app (.const ``And _) Q) R) => return some (P, Q, R)\n | _ => return none\n | _ => return none\n\n/-!\nThis sort of deep matching up to computation could be automated. But until\nsomeone builds this automation, we have to figure out the necessary `whnf`s\nourselves.\n\n\n### Definitional Equality\n\nAs mentioned, definitional equality is equality up to computation. Two\nexpressions `t` and `s` are definitionally equal or *defeq* (at the current\ntransparency) if their normal forms (at the current transparency) are equal.\n\nTo check whether two expressions are defeq, use `Lean.Meta.isDefEq` with type\nsignature\n\n```lean\nisDefEq : Expr → Expr → MetaM Bool\n```\n\nEven though definitional equality is defined in terms of normal forms, `isDefEq`\ndoes not actually compute the normal forms of its arguments, which would be very\nexpensive. Instead, it tries to \"match up\" `t` and `s` using as few reductions\nas possible. This is a necessarily heuristic endeavour and when the heuristics\nmisfire, `isDefEq` can become very expensive. In the worst case, it may have to\nreduce `s` and `t` so often that they end up in normal form anyway. But usually\nthe heuristics are good and `isDefEq` is reasonably fast.\n\nIf expressions `t` and `u` contain assignable metavariables, `isDefEq` may\nassign these metavariables to make `t` defeq to `u`. We also say that `isDefEq`\n*unifies* `t` and `u`; such unification queries are sometimes written `t =?= u`.\nFor instance, the unification `List ?m =?= List Nat` succeeds and assigns `?m :=\nNat`. The unification `Nat.succ ?m =?= n + 1` succeeds and assigns `?m := n`.\nThe unification `?m₁ + ?m₂ + ?m₃ =?= m + n - k` fails and no metavariables are\nassigned (even though there is a 'partial match' between the expressions).\n\nWhether `isDefEq` considers a metavariable assignable is determined by two\nfactors:\n\n1. The metavariable's depth must be equal to the current `MetavarContext` depth.\n See the [Metavariable Depth section](#metavariable-depth).\n2. Each metavariable has a *kind* (a value of type `MetavarKind`) whose sole\n purpose is to modify the behaviour of `isDefEq`. Possible kinds are:\n - Natural: `isDefEq` may freely assign the metavariable. This is the default.\n - Synthetic: `isDefEq` may assign the metavariable, but avoids doing so if\n possible. For example, suppose `?n` is a natural metavariable and `?s` is a\n synthetic metavariable. When faced with the unification problem\n `?s =?= ?n`, `isDefEq` assigns `?n` rather than `?s`.\n - Synthetic opaque: `isDefEq` never assigns the metavariable.\n\n\n## Constructing Expressions\n\nIn the previous chapter, we saw some primitive functions for building\nexpressions: `Expr.app`, `Expr.const`, `mkAppN` and so on. There is nothing\nwrong with these functions, but the additional facilities of `MetaM` often\nprovide more convenient ways.\n\n\n### Applications\n\nWhen we write regular Lean code, Lean helpfully infers many implicit arguments\nand universe levels. If it did not, our code would look rather ugly: -/\n\ndef appendAppend (xs ys : List α) := (xs.append ys).append xs\n\nset_option pp.all true in\nset_option pp.explicit true in\n#print appendAppend\n-- def appendAppend.{u_1} : {α : Type u_1} → List.{u_1} α → List.{u_1} α → List.{u_1} α :=\n-- fun {α : Type u_1} (xs ys : List.{u_1} α) => @List.append.{u_1} α (@List.append.{u_1} α xs ys) xs\n\n/-!\nThe `.{u_1}` suffixes are universe levels, which must be given for every\npolymorphic constant. And of course the type `α` is passed around everywhere.\n\nExactly the same problem occurs during metaprogramming when we construct\nexpressions. A hand-made expression representing the right-hand side of the\nabove definition looks like this:\n-/\n\ndef appendAppendRHSExpr₁ (u : Level) (α xs ys : Expr) : Expr :=\n mkAppN (.const ``List.append [u])\n #[α, mkAppN (.const ``List.append [u]) #[α, xs, ys], xs]\n\n/-!\nHaving to specify the implicit arguments and universe levels is annoying and\nerror-prone. So `MetaM` provides a helper function which allows us to omit\nimplicit information: `Lean.Meta.mkAppM` of type\n\n```lean\nmkAppM : Name → Array Expr → MetaM Expr\n```\n\nLike `mkAppN`, `mkAppM` constructs an application. But while `mkAppN` requires\nus to give all universe levels and implicit arguments ourselves, `mkAppM` infers\nthem. This means we only need to provide the explicit arguments, which makes for\na much shorter example:\n-/\n\ndef appendAppendRHSExpr₂ (xs ys : Expr) : MetaM Expr := do\n mkAppM ``List.append #[← mkAppM ``List.append #[xs, ys], xs]\n\n/-!\nNote the absence of any `α`s and `u`s. There is also a variant of `mkAppM`,\n`mkAppM'`, which takes an `Expr` instead of a `Name` as the first argument,\nallowing us to construct applications of expressions which are not constants.\n\nHowever, `mkAppM` is not magic: if you write `mkAppM ``List.append #[]`, you\nwill get an error at runtime. This is because `mkAppM` tries to determine what\nthe type `α` is, but with no arguments given to `append`, `α` could be anything,\nso `mkAppM` fails.\n\nAnother occasionally useful variant of `mkAppM` is `Lean.Meta.mkAppOptM` of type\n\n```lean\nmkAppOptM : Name → Array (Option Expr) → MetaM Expr\n```\n\nWhereas `mkAppM` always infers implicit and instance arguments and always\nrequires us to give explicit arguments, `mkAppOptM` lets us choose freely which\narguments to provide and which to infer. With this, we can, for example, give\ninstances explicitly, which we use in the following example to give a\nnon-standard `Ord` instance.\n-/\n\ndef revOrd : Ord Nat where\n compare x y := compare y x\n\ndef ordExpr : MetaM Expr := do\n mkAppOptM ``compare #[none, Expr.const ``revOrd [], mkNatLit 0, mkNatLit 1]\n\n#eval format <$> ordExpr\n-- Ord.compare.{0} Nat revOrd\n-- (OfNat.ofNat.{0} Nat 0 (instOfNatNat 0))\n-- (OfNat.ofNat.{0} Nat 1 (instOfNatNat 1))\n\n/-!\nLike `mkAppM`, `mkAppOptM` has a primed variant `Lean.Meta.mkAppOptM'` which\ntakes an `Expr` instead of a `Name` as the first argument. The file which\ncontains `mkAppM` also contains various other helper functions, e.g. for making\nlist literals or `sorry`s.\n\n\n### Lambdas and Foralls\n\nAnother common task is to construct expressions involving `λ` or `∀` binders.\nSuppose we want to create the expression `λ (x : Nat), Nat.add x x`. One way is\nto write out the lambda directly:\n-/\n\ndef doubleExpr₁ : Expr :=\n .lam `x (.const ``Nat []) (mkAppN (.const ``Nat.add []) #[.bvar 0, .bvar 0])\n BinderInfo.default\n\n#eval ppExpr doubleExpr₁\n-- fun x => Nat.add x x\n\n/-!\nThis works, but the use of `bvar` is highly unidiomatic. Lean uses a so-called\n*locally closed* variable representation. This means that all but the\nlowest-level functions in the Lean API expect expressions not to contain 'loose\n`bvar`s', where a `bvar` is loose if it is not bound by a binder in the same\nexpression. (Outsied of Lean, such variables are usually called 'free'. The name\n`bvar` -- 'bound variable' -- already indicates that `bvar`s are never supposed\nto be free.)\n\nAs a result, if in the above example we replace `mkAppN` with the slightly\nhigher-level `mkAppM`, we get a runtime error. Adhering to the locally closed\nconvention, `mkAppM` expects any expressions given to it to have no loose bound\nvariables, and `.bvar 0` is precisely that.\n\nSo instead of using `bvar`s directly, the Lean way is to construct expressions\nwith bound variables in two steps:\n\n1. Construct the body of the expression (in our example: the body of the\n lambda), using temporary local hypotheses (`fvar`s) to stand in for the bound\n variables.\n2. Replace these `fvar`s with `bvar`s and, at the same time, add the\n corresponding lambda binders.\n\nThis process ensures that we do not need to handle expressions with loose\n`bvar`s at any point (except during step 2, which is performed 'atomically' by a\nbespoke function). Applying the process to our example:\n\n-/\n\ndef doubleExpr₂ : MetaM Expr :=\n withLocalDecl `x BinderInfo.default (.const ``Nat []) λ x => do\n let body ← mkAppM ``Nat.add #[x, x]\n mkLambdaFVars #[x] body\n\n#eval show MetaM _ from do\n ppExpr (← doubleExpr₂)\n-- fun x => Nat.add x x\n\n/-!\nThere are two new functions. First, `Lean.Meta.withLocalDecl` has type\n\n```lean\nwithLocalDecl (name : Name) (bi : BinderInfo) (type : Expr) (k : Expr → MetaM α) : MetaM α\n```\n\nGiven a variable name, binder info and type, `withLocalDecl` constructs a new\n`fvar` and passes it to the computation `k`. The `fvar` is avaible in the local\ncontext during the execution of `k` but is deleted again afterwards.\n\nThe second new function is `Lean.Meta.mkLambdaFVars` with type (ignoring some\noptional arguments)\n\n```\nmkLambdaFVars : Array Expr → Expr → MetaM Expr\n```\n\nThis function takes an array of `fvar`s and an expression `e`. It then adds one\nlambda binder for each `fvar` `x` and replaces every occurence of `x` in `e`\nwith a bound variable corresponding to the new lambda binder. The returned\nexpression does not contain the `fvar`s any more, which is good since they\ndisappear after we leave the `withLocalDecl` context. (Instead of `fvar`s, we\ncan also give `mvar`s to `mkLambdaFVars`, despite its name.)\n\nSome variants of the above functions may be useful:\n\n- `withLocalDecls` declares multiple temporary `fvar`s.\n- `mkForallFVars` creates `∀` binders instead of `λ` binders. `mkLetFVars`\n creates `let` binders.\n- `mkArrow` is the non-dependent version of `mkForallFVars` which construcs\n a function type `X → Y`. Since the type is non-dependent, there is no need\n for temporary `fvar`s.\n\nUsing all these functions, we can construct larger expressions such as this one:\n\n```lean\nλ (f : Nat → Nat), ∀ (n : Nat), f n = f (n + 1)\n```\n-/\n\ndef somePropExpr : MetaM Expr := do\n let funcType ← mkArrow (.const ``Nat []) (.const ``Nat [])\n withLocalDecl `f BinderInfo.default funcType fun f => do\n let feqn ← withLocalDecl `n BinderInfo.default (.const ``Nat []) fun n => do\n let lhs := .app f n\n let rhs := .app f (← mkAppM ``Nat.succ #[n])\n let eqn ← mkEq lhs rhs\n mkForallFVars #[n] eqn\n mkLambdaFVars #[f] feqn\n\n/-!\nThe next line registers `someProp` as a name for the expression we've just\nconstructed, allowing us to play with it more easily. The mechanisms behind this\nare discussed in the Elaboration chapter.\n-/\n\nelab \"someProp\" : term => somePropExpr\n\n#check someProp\n-- fun f => ∀ (n : Nat), f n = f (Nat.succ n) : (Nat → Nat) → Prop\n#reduce someProp Nat.succ\n-- ∀ (n : Nat), Nat.succ n = Nat.succ (Nat.succ n)\n\n\n/-!\n### Deconstructing Expressions\n\nJust like we can construct expressions more easily in `MetaM`, we can also\ndeconstruct them more easily. Particularly useful is a family of functions for\ndeconstructing expressions which start with `λ` and `∀` binders.\n\nWhen we are given a type of the form `∀ (x₁ : T₁) ... (xₙ : Tₙ), U`, we are\noften interested in doing something with the conclusion `U`. For instance, the\n`apply` tactic, when given an expression `e : ∀ ..., U`, compares `U` with the\ncurrent target to determine whether `e` can be applied.\n\nTo do this, we could repeatedly match on the type expression, removing `∀`\nbinders until we get to `U`. But this would leave us with an `U` containing\nunbound `bvar`s, which, as we saw, is bad. Instead, we use\n`Lean.Meta.forallTelescope` of type\n\n```\nforallTelescope (type : Expr) (k : Array Expr → Expr → MetaM α) : MetaM α\n```\n\nGiven `type = ∀ (x₁ : T₁) ... (xₙ : Tₙ), U x₁ ... xₙ`, this function creates one\nfvar `fᵢ` for each `∀`-bound variable `xᵢ` and replaces each `xᵢ` with `fᵢ` in\nthe conclusion `U`. It then calls the computation `k`, passing it the `fᵢ` and\nthe conclusion `U f₁ ... fₙ`. Within this computation, the `fᵢ` are registered\nin the local context; afterwards, they are deleted again (similar to\n`withLocalDecl`).\n\nThere are many useful variants of `forallTelescope`:\n\n- `forallTelescopeReducing`: like `forallTelescope` but matching is performed up\n to computation. This means that if you have an expression `X` which is\n different from but defeq to `∀ x, P x`, `forallTelescopeReducing X` will\n deconstruct `X` into `x` and `P x`. The non-reducing `forallTelescope` would\n not recognise `X` as a quantified expression. The matching is performed by\n essentially calling `whnf` repeatedly, using the ambient transparency.\n- `forallBoundedTelescope`: like `forallTelescopeReducing` (even though there is\n no \"reducing\" in the name) but stops after a specified number of `∀` binders.\n- `forallMetaTelescope`, `forallMetaTelescopeReducing`,\n `forallMetaBoundedTelescope`: like the corresponding non-`meta` functions, but\n the bound variables are replaced by new `mvar`s instead of `fvar`s. Unlike the\n non-`meta` functions, the `meta` functions do not delete the new metavariables\n after performing some computation, so the metavariables remain in the\n environment indefinitely.\n- `lambdaTelescope`, `lambdaTelescopeReducing`, `lambdaBoundedTelescope`,\n `lambdaMetaTelescope`: like the corresponding `forall` functions, but for\n `λ` binders instead of `∀`.\n\nUsing one of the telescope functions, we can implement our own `apply` tactic:\n-/\n\ndef myApply (goal : MVarId) (e : Expr) : MetaM (List MVarId) := do\n -- Check that the goal is not yet assigned.\n goal.checkNotAssigned `myApply\n -- Operate in the local context of the goal.\n goal.withContext do\n -- Get the goal's target type.\n let target ← goal.getType\n -- Get the type of the given expression.\n let type ← inferType e\n -- If `type` has the form `∀ (x₁ : T₁) ... (xₙ : Tₙ), U`, introduce new\n -- metavariables for the `xᵢ` and obtain the conclusion `U`. (If `type` does\n -- not have this form, `args` is empty and `conclusion = type`.)\n let (args, _, conclusion) ← forallMetaTelescopeReducing type\n -- If the conclusion unifies with the target:\n if ← isDefEq target conclusion then\n -- Assign the goal to `e x₁ ... xₙ`, where the `xᵢ` are the fresh\n -- metavariables in `args`.\n goal.assign (mkAppN e args)\n -- `isDefEq` may have assigned some of the `args`. Report the rest as new\n -- goals.\n let newGoals ← args.filterMapM λ mvar => do\n let mvarId := mvar.mvarId!\n if ! (← mvarId.isAssigned) && ! (← mvarId.isDelayedAssigned) then\n return some mvarId\n else\n return none\n return newGoals.toList\n -- If the conclusion does not unify with the target, throw an error.\n else\n throwTacticEx `myApply goal m!\"{e} is not applicable to goal with target {target}\"\n\n/-!\nThe real `apply` does some additional pre- and postprocessing, but the core\nlogic is what we show here. To test our tactic, we need an elaboration\nincantation, more about which in the Elaboration chapter.\n-/\n\nelab \"myApply\" e:term : tactic => do\n let e ← Elab.Term.elabTerm e none\n Elab.Tactic.liftMetaTactic (myApply · e)\n\nexample (h : α → β) (a : α) : β := by\n myApply h\n myApply a\n\n\n/-!\n## Backtracking\n\nMany tactics naturally require backtracking: the ability to go back to a\nprevious state, as if the tactic had never been executed. A few examples:\n\n- `first | t | u` first executes `t`. If `t` fails, it backtracks and executes\n `u`.\n- `try t` executes `t`. If `t` fails, it backtracks to the initial state,\n erasing any changes made by `t`.\n- `trivial` attempts to solve the goal using a number of simple tactics\n (e.g. `rfl` or `contradiction`). After each unsuccessful application of such a\n tactic, `trivial` backtracks.\n\nGood thing, then, that Lean's core data structures are designed to enable easy\nand efficient backtracking. The corresponding API is provided by the\n`Lean.MonadBacktrack` class. `MetaM`, `TermElabM` and `TacticM` are all\ninstances of this class. (`CoreM` is not but could be.)\n\n`MonadBacktrack` provides two fundamental operations:\n\n- `Lean.saveState : m s` returns a representation of the current state, where\n `m` is the monad we are in and `s` is the state type. E.g. for `MetaM`,\n `saveState` returns a `Lean.Meta.SavedState` containing the current\n environment, the current `MetavarContext` and various other pieces of\n information.\n- `Lean.restoreState : s → m Unit` takes a previously saved state and restores\n it. This effectively resets the compiler state to the previous point.\n\nWith this, we can roll our own `MetaM` version of the `try` tactic:\n-/\n\ndef tryM (x : MetaM Unit) : MetaM Unit := do\n let s ← saveState\n try\n x\n catch _ =>\n restoreState s\n\n/-!\nWe first save the state, then execute `x`. If `x` fails, we backtrack the state.\n\nThe standard library defines many combinators like `tryM`. Here are the most\nuseful ones:\n\n- `Lean.withoutModifyingState (x : m α) : m α` executes the action `x`, then\n resets the state and returns `x`'s result. You can use this, for example, to\n check for definitional equality without assigning metavariables:\n ```lean\n withoutModifyingState $ isDefEq x y\n ```\n If `isDefEq` succeeds, it may assign metavariables in `x` and `y`. Using\n `withoutModifyingState`, we can make sure this does not happen.\n- `Lean.observing? (x : m α) : m (Option α)` executes the action `x`. If `x`\n succeeds, `observing?` returns its result. If `x` fails (throws an exception),\n `observing?` backtracks the state and returns `none`. This is a more\n informative version of our `tryM` combinator.\n- `Lean.commitIfNoEx (x : α) : m α` executes `x`. If `x` succeeds,\n `commitIfNoEx` returns its result. If `x` throws an exception, `commitIfNoEx`\n backtracks the state and rethrows the exception.\n\nNote that the builtin `try ... catch ... finally` does not perform any\nbacktracking. So code which looks like this is probably wrong:\n\n```lean\ntry\n doSomething\ncatch e =>\n doSomethingElse\n```\n\nThe `catch` branch, `doSomethingElse`, is executed in a state containing\nwhatever modifications `doSomething` made before it failed. Since we probably\nwant to erase these modifications, we should write instead:\n\n```lean\ntry\n commitIfNoEx doSomething\ncatch e =>\n doSomethingElse\n```\n\nAnother `MonadBacktrack` gotcha is that `restoreState` does not backtrack the\n*entire* state. Caches, trace messages and the global name generator, among\nother things, are not backtracked, so changes made to these parts of the state\nare not reset by `restoreState`. This is usually what we want: if a tactic\nexecuted by `observing?` produces some trace messages, we want to see them even\nif the tactic fails. See `Lean.Meta.SavedState.restore` and `Lean.Core.restore`\nfor details on what is and is not backtracked.\n\nIn the next chapter, we move towards the topic of elaboration, of which\nyou've already seen several glimpses in this chapter. We start by discussing\nLean's syntax system, which allows you to add custom syntactic constructs to the\nLean parser.\n\n## Exercises\n\n1. [**Metavariables**] Create a metavariable with type `Nat`, and assign to it value `3`.\nNotice that changing the type of the metavarible from `Nat` to, for example, `String`, doesn't raise any errors - that's why, as was mentioned, we must make sure *\"(a) that `val` must have the target type of `mvarId` and (b) that `val` must only contain `fvars` from the local context of `mvarId`\"*.\n2. [**Metavariables**] What would `instantiateMVars (Lean.mkAppN (Expr.const 'Nat.add []) #[mkNatLit 1, mkNatLit 2])` output?\n3. [**Metavariables**] Fill in the missing lines in the following code.\n\n ```\n #eval show MetaM Unit from do\n let oneExpr := Expr.app (Expr.const `Nat.succ []) (Expr.const ``Nat.zero [])\n let twoExpr := Expr.app (Expr.const `Nat.succ []) oneExpr\n\n -- Create `mvar1` with type `Nat`\n -- let mvar1 ← ...\n -- Create `mvar2` with type `Nat`\n -- let mvar2 ← ...\n -- Create `mvar3` with type `Nat`\n -- let mvar3 ← ...\n\n -- Assign `mvar1` to `2 + ?mvar2 + ?mvar3`\n -- ...\n\n -- Assign `mvar3` to `1`\n -- ...\n\n -- Instantiate `mvar1`, which should result in expression `2 + ?mvar2 + 1`\n ...\n ```\n4. [**Metavariables**] Consider the theorem `red`, and tactic `explore` below. \n a) What would be the `type` and `userName` of metavariable `mvarId`? \n b) What would be the `type`s and `userName`s of all local declarations in this metavariable's local context? \n Print them all out.\n\n ```\n elab \"explore\" : tactic => do\n let mvarId : MVarId ← Lean.Elab.Tactic.getMainGoal\n let metavarDecl : MetavarDecl ← mvarId.getDecl\n\n IO.println \"Our metavariable\"\n -- ...\n\n IO.println \"All of its local declarations\"\n -- ...\n\n theorem red (hA : 1 = 1) (hB : 2 = 2) : 2 = 2 := by\n explore\n sorry\n ```\n5. [**Metavariables**] Write a tactic `solve` that proves the theorem `red`.\n6. [**Computation**] What is the normal form of the following expressions: \n **a)** `fun x => x` of type `Bool → Bool` \n **b)** `(fun x => x) ((true && false) || true)` of type `Bool` \n **c)** `800 + 2` of type `Nat`\n7. [**Computation**] Show that `1` created with `Expr.lit (Lean.Literal.natVal 1)` is definitionally equal to an expression created with `Expr.app (Expr.const ``Nat.succ []) (Expr.const ``Nat.zero [])`.\n8. [**Computation**] Determine whether the following expressions are definitionally equal. If `Lean.Meta.isDefEq` succeeds, and it leads to metavariable assignment, write down the assignments. \n **a)** `5 =?= (fun x => 5) ((fun y : Nat → Nat => y) (fun z : Nat => z))` \n **b)** `2 + 1 =?= 1 + 2` \n **c)** `?a =?= 2`, where `?a` has a type `String` \n **d)** `?a + Int =?= \"hi\" + ?b`, where `?a` and `?b` don't have a type \n **e)** `2 + ?a =?= 3` \n **f)** `2 + ?a =?= 2 + 1`\n9. [**Computation**] Write down what you expect the following code to output.\n\n```\n@[reducible] def reducibleDef : Nat := 1 -- same as `abbrev`\n@[instance] def instanceDef : Nat := 2 -- same as `instance`\ndef defaultDef : Nat := 3\n@[irreducible] def irreducibleDef : Nat := 4\n\n@[reducible] def sum := [reducibleDef, instanceDef, defaultDef, irreducibleDef]\n\n#eval show MetaM Unit from do\n let constantExpr := Expr.const `sum []\n\n Meta.withTransparency Meta.TransparencyMode.reducible do\n let reducedExpr ← Meta.reduce constantExpr\n dbg_trace (← ppExpr reducedExpr) -- ...\n\n Meta.withTransparency Meta.TransparencyMode.instances do\n let reducedExpr ← Meta.reduce constantExpr\n dbg_trace (← ppExpr reducedExpr) -- ...\n\n Meta.withTransparency Meta.TransparencyMode.default do\n let reducedExpr ← Meta.reduce constantExpr\n dbg_trace (← ppExpr reducedExpr) -- ...\n\n Meta.withTransparency Meta.TransparencyMode.all do\n let reducedExpr ← Meta.reduce constantExpr\n dbg_trace (← ppExpr reducedExpr) -- ...\n\n let reducedExpr ← Meta.reduce constantExpr\n dbg_trace (← ppExpr reducedExpr) -- ...\n```\n10. [**Constructing Expressions**] Create expression `fun x, 1 + x` in two ways: \n **a)** not idiomatically, with loose bound variables \n **b)** idiomatically. \n In what version can you use `Lean.mkAppN`? In what version can you use `Lean.Meta.mkAppM`?\n11. [**Constructing Expressions**] Create expression `∀ (yellow: Nat), yellow`.\n12. [**Constructing Expressions**] Create expression `∀ (n : Nat), n = n + 1` in two ways: \n **a)** not idiomatically, with loose bound variables \n **b)** idiomatically. \n In what version can you use `Lean.mkApp3`? In what version can you use `Lean.Meta.mkEq`?\n13. [**Constructing Expressions**] Create expression `fun (f : Nat → Nat), ∀ (n : Nat), f n = f (n + 1)` idiomatically.\n14. [**Constructing Expressions**] What would you expect the output of the following code to be?\n\n```\n#eval show Lean.Elab.Term.TermElabM _ from do\n let stx : Syntax ← `(∀ (a : Prop) (b : Prop), a ∨ b → b → a ∧ a)\n let expr ← Elab.Term.elabTermAndSynthesize stx none\n\n let (_, _, conclusion) ← forallMetaTelescope expr\n dbg_trace conclusion -- ...\n\n let (_, _, conclusion) ← forallMetaBoundedTelescope expr 2\n dbg_trace conclusion -- ...\n\n let (_, _, conclusion) ← lambdaMetaTelescope expr\n dbg_trace conclusion -- ...\n```\n15. [**Backtracking**] Check that the expressions `?a + Int` and `\"hi\" + ?b` are definitionally equal with `isDefEq` (make sure to use the proper types or `Option.none` for the types of your metavariables!).\nUse `saveState` and `restoreState` to revert metavariable assignments.\n-/\n", "meta": {"author": "leanprover-community", "repo": "lean4-metaprogramming-book", "sha": "0b2e7e2c0cacac530ed947df878088c5d9715412", "save_path": "github-repos/lean/leanprover-community-lean4-metaprogramming-book", "path": "github-repos/lean/leanprover-community-lean4-metaprogramming-book/lean4-metaprogramming-book-0b2e7e2c0cacac530ed947df878088c5d9715412/lean/main/metam.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.26588047309981694, "lm_q2_score": 0.04468087297585627, "lm_q1q2_score": 0.01187977164533349}} {"text": "import for_mathlib.category_theory.localization.equivalence\n\nnoncomputable theory\n\nnamespace category_theory\n\nvariables {C₁ C₂ C₃ E : Type*} [category C₁] [category C₂] [category C₃]\n\nopen localization\n\nnamespace morphism_property\n\n@[refl]\nlemma subset.refl (W : morphism_property C₁) : W ⊆ W := λ X Y f hf, hf\n\n@[simp]\ndef map (W : morphism_property C₁) (F : C₁ ⥤ C₂) : morphism_property C₂ :=\nλ X₂ Y₂ f₂, ∃ (X₁ Y₁ : C₁) (f₁ : X₁ ⟶ Y₁) (hf₁ : W f₁),\n nonempty (arrow.mk (F.map f₁) ≅ arrow.mk f₂)\n\nlemma map_mem_map (W : morphism_property C₁) (F : C₁ ⥤ C₂) {X₁ Y₁ : C₁} (f₁ : X₁ ⟶ Y₁)\n (hf₁ : W f₁) : W.map F (F.map f₁) :=\n⟨_, _, f₁, hf₁, nonempty.intro (iso.refl _)⟩\n\nlemma map_is_inverted_by_iff (W : morphism_property C₁) (F : C₁ ⥤ C₂) (G : C₂ ⥤ C₃) :\n (W.map F).is_inverted_by G ↔ W.is_inverted_by (F ⋙ G) :=\nbegin\n split,\n { intros h X₁ Y₁ f₁ hf₁,\n exact h _ (W.map_mem_map F f₁ hf₁), },\n { rintros h X₂ Y₂ f₂ ⟨X₁, Y₁, f₁, hf₁, ⟨e⟩⟩,\n exact ((respects_iso.isomorphisms C₃).arrow_mk_iso_iff (G.map_arrow.map_iso e)).1 (h _ hf₁), },\nend\n\nend morphism_property\n\n\nnamespace localization\n\nsection\n\nlemma strict_universal_property_fixed_target.comp {E : Type*} [category E]\n {L₁ : C₁ ⥤ C₂} {L₂ : C₂ ⥤ C₃} {W₁ : morphism_property C₁} {W₂ : morphism_property C₂}\n (h₁ : strict_universal_property_fixed_target L₁ W₁ E)\n (h₂ : strict_universal_property_fixed_target L₂ W₂ E)\n (W₃ : morphism_property C₁) (hW₃ : W₃.is_inverted_by (L₁ ⋙ L₂))\n (hW₁₃ : W₁ ⊆ W₃) (hW₂₃ : W₂ ⊆ W₃.map L₁) :\n strict_universal_property_fixed_target (L₁ ⋙ L₂) W₃ E :=\n{ inverts := hW₃,\n lift := λ F hF, begin\n have h : W₁.is_inverted_by F := λ X₁ Y₁ f₁ hf₁, hF f₁ (hW₁₃ _ hf₁),\n exact h₂.lift (h₁.lift F h) (λ X₂ Y₂ f₂ hf₂, begin\n obtain ⟨X₁, Y₁, f₁, hf₁, ⟨e⟩⟩ := hW₂₃ _ hf₂,\n refine ((morphism_property.respects_iso.isomorphisms E).arrow_mk_iso_iff\n ((h₁.lift F h).map_arrow.map_iso e)).1 _,\n refine ((morphism_property.respects_iso.isomorphisms E).arrow_mk_iso_iff\n (arrow.iso_of_nat_iso (eq_to_iso (h₁.fac F h)) (arrow.mk f₁))).2 (hF _ hf₁),\n end),\n end,\n fac := λ F hF, by rw [functor.assoc, h₂.fac, h₁.fac],\n uniq := λ F₁ F₂ h, begin\n simp only [functor.assoc] at h,\n exact h₂.uniq _ _ (h₁.uniq _ _ h),\n end, }\n\nend\n\n@[protected]\nlemma comp (L₁ : C₁ ⥤ C₂) (L₂ : C₂ ⥤ C₃) (W₁ : morphism_property C₁)\n (W₂ : morphism_property C₂) (W₃ : morphism_property C₁)\n [L₁.is_localization W₁] [L₂.is_localization W₂] (hW₃ : W₃.is_inverted_by (L₁ ⋙ L₂))\n (hW₁₃ : W₁ ⊆ W₃) (hW₃' : W₂ ⊆ W₃.map L₁) :\n (L₁ ⋙ L₂).is_localization W₃ :=\nbegin\n let L₁' := W₁.Q,\n let eq₂ := equivalence_from_model L₁ W₁,\n let W₂' : morphism_property (W₁.localization) := W₂.map eq₂.inverse,\n let L₂' := W₂'.Q,\n have h₂ : W₂'.is_inverted_by (eq₂.functor ⋙ L₂),\n { dsimp only [W₂'],\n rw morphism_property.map_is_inverted_by_iff,\n refine (morphism_property.is_inverted_by.iff_of_iso W₂ _).1 (localization.inverts L₂ W₂),\n exact L₂.left_unitor.symm ≪≫ iso_whisker_right eq₂.counit_iso.symm _ ≪≫ functor.associator _ _ _, },\n let F₃ : W₂'.localization ⥤ C₃ := localization.lift (eq₂.functor ⋙ L₂) h₂ L₂',\n let H : Comm_sq eq₂.functor L₂' L₂ F₃ := ⟨localization.fac _ _ _⟩,\n have h₁' : W₁.is_inverted_by L₁' := localization.inverts _ _,\n have h₁₂' : W₁.is_inverted_by (L₁' ⋙ L₂') :=\n morphism_property.is_inverted_by.of_comp W₁ _ h₁' L₂',\n letI : lifting L₁ W₁ L₁' eq₂.inverse := ⟨comp_equivalence_from_model_inverse_iso _ _⟩,\n let F₁₂' := localization.lift (L₁' ⋙ L₂') h₁₂' L₁,\n let e₁₂ : F₁₂' ≅ eq₂.inverse ⋙ L₂' := lift_nat_iso L₁ W₁ (L₁' ⋙ L₂') (L₁' ⋙ L₂') _ _ (iso.refl _),\n have hF₁₂' : W₂.is_inverted_by F₁₂',\n { have h := localization.inverts W₂'.Q W₂',\n rw morphism_property.map_is_inverted_by_iff at h,\n exact (morphism_property.is_inverted_by.iff_of_iso _ e₁₂.symm).1 h, },\n let G₃ : C₃ ⥤ W₂'.localization := localization.lift F₁₂' hF₁₂' L₂,\n letI : lifting L₂ W₂ (eq₂.inverse ⋙ W₂'.Q) G₃ :=\n ⟨localization.fac F₁₂' hF₁₂' L₂ ≪≫ lift_nat_iso L₁ W₁\n (L₁' ⋙ L₂') (L₁' ⋙ L₂') _ _ (iso.refl _)⟩,\n let e₂ : (eq₂.inverse ⋙ L₂') ⋙ F₃ ≅ L₂ := functor.associator _ _ _ ≪≫\n iso_whisker_left _ (localization.fac (eq₂.functor ⋙ L₂) h₂ L₂') ≪≫\n (functor.associator _ _ _).symm ≪≫ iso_whisker_right eq₂.counit_iso _ ≪≫ L₂.left_unitor,\n let e₃ : eq₂.functor ⋙ eq₂.inverse ⋙ L₂' ≅ L₂' :=\n (functor.associator _ _ _).symm ≪≫ iso_whisker_right eq₂.unit_iso.symm _ ≪≫ L₂'.left_unitor,\n letI := lifting_is_equivalence H W₂' W₂ (eq₂.inverse ⋙ L₂') G₃ e₂ e₃,\n haveI : (L₁' ⋙ L₂').is_localization W₃,\n { have h₁ : W₃.is_inverted_by (W₁.Q ⋙ W₂'.Q),\n { suffices : W₃.is_inverted_by (W₁.Q ⋙ W₂'.Q ⋙ F₃),\n { intros X₁ Y₁ f₁ hf₁,\n haveI : is_iso (F₃.map ((W₁.Q ⋙ W₂'.Q).map f₁)) := this f₁ hf₁,\n exact is_iso_of_reflects_iso _ F₃, },\n refine (morphism_property.is_inverted_by.iff_of_iso W₃ _).1 hW₃,\n exact iso_whisker_right ((Q_comp_equivalence_from_model_functor_iso L₁ W₁).symm) _ ≪≫\n functor.associator _ _ _ ≪≫ iso_whisker_left _ (localization.fac _ _ _).symm, },\n have h₂ : W₂' ⊆ W₃.map W₁.Q,\n { dsimp only [W₂'],\n rintros X Y f ⟨X₂, Y₂, f₂, hf₂, ⟨e₂⟩⟩,\n rcases hW₃' _ hf₂ with ⟨X₁, Y₁, f₁, hf₁, ⟨e₁⟩⟩,\n refine ⟨X₁, Y₁, f₁, hf₁, ⟨_⟩⟩,\n refine arrow.iso_of_nat_iso (comp_equivalence_from_model_inverse_iso L₁ W₁).symm (arrow.mk f₁)\n ≪≫ eq₂.inverse.map_arrow.map_iso e₁ ≪≫ e₂, },\n refine functor.is_localization.mk' _ _ _ _,\n all_goals { exact (strict_universal_property_fixed_target_Q W₁ _).comp\n (strict_universal_property_fixed_target_Q W₂' _) W₃ h₁ hW₁₃ h₂, }, },\n apply functor.is_localization.of_equivalence (L₁' ⋙ L₂') W₃ (L₁ ⋙ L₂) F₃.as_equivalence,\n exact functor.associator _ _ _ ≪≫ iso_whisker_left _ (localization.fac _ _ _) ≪≫\n (functor.associator _ _ _).symm ≪≫ iso_whisker_right (Q_comp_equivalence_from_model_functor_iso L₁ W₁) _,\nend\n\nend localization\n\nend category_theory\n", "meta": {"author": "joelriou", "repo": "homotopical_algebra", "sha": "697f49d6744b09c5ef463cfd3e35932bdf2c78a3", "save_path": "github-repos/lean/joelriou-homotopical_algebra", "path": "github-repos/lean/joelriou-homotopical_algebra/homotopical_algebra-697f49d6744b09c5ef463cfd3e35932bdf2c78a3/src/for_mathlib/category_theory/localization/composition.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43014734858584286, "lm_q2_score": 0.027585281227505684, "lm_q1q2_score": 0.011865735580006394}} {"text": "\nimport data.serial.string\nimport tactic.linarith\nimport category.monad_trans\nimport data.list.nursery\nimport system.io\n\nuniverses u\n\nnamespace json\n\ninductive value\n| object : unit → list (string × value) → value\n| number : ℤ → value\n| array : unit → list value → value\n| bool : bool → value\n| string : string → value\n| nil : value\n-- with object : Type\n-- | fields : list (string × value) → object\n\nopen value (hiding object bool string)\n\n@[reducible] def object := list (string × value)\n\ndef is_atom : value → bool\n| (number n) := tt\n| (value.bool b) := tt\n| (value.string s) := tt\n| value.nil := tt\n| _ := ff\n\ndef encode_line : value → string\n| (number n) := to_string n\n| (value.bool n) := to_string n\n| (value.string n) := to_string n\n| nil := \"nil\"\n| (value.object _ _) := \"\"\n| (value.array _ _) := \"\"\n\nnamespace syntax\n\n@[derive decidable_eq]\ninductive token\n| open_curly | close_curly\n| open_square | close_square\n| colon | comma | nil | bool (b : bool)\n| number (n : ℤ) | string (s : string)\n\nabbreviation put_m' := medium.put_m'.{u} token\nabbreviation put_m := medium.put_m'.{u} token punit\nabbreviation get_m := medium.get_m.{u} token\nexport medium (hiding put_m put_m' get_m)\n\nnamespace put_m'\nexport medium.put_m'\nend put_m'\n\nnamespace get_m\nexport medium.get_m\nend get_m\n\nexport token (hiding number string bool)\n\nmutual def encode_val, encode_obj, encode_array\nwith encode_val : value → put_m\n| (value.string s) := write_word $ token.string s\n| (value.number n) := write_word $ token.number n\n| (value.bool b) := write_word $ token.bool b\n| (value.nil) := write_word $ token.nil\n| (value.object _ []) :=\n write_word open_curly >> write_word close_curly\n| (value.object _ ((fn,v)::vs)) :=\n do write_word open_curly,\n write_word (token.string fn),\n write_word colon,\n encode_obj v vs,\n write_word close_curly\n| (value.array _ obj) :=\n write_word open_square >> encode_array obj >> write_word close_square\nwith encode_obj : value → list (string × value) → put_m\n| v [] := encode_val v\n| v ((fn,v') :: vs) :=\ndo encode_val v,\n write_word comma,\n write_word (token.string fn),\n write_word colon,\n encode_obj v' vs\nwith encode_array : list value → put_m\n| [] := pure ()\n| (v :: vs) :=\ndo encode_val v,\n when (¬ vs = []) $ do\n write_word comma,\n encode_array vs\n\ninductive partial_val\n| array (ar : list value)\n| object (obj : list (string × value)) (field : string)\n\ndef parser_state := list partial_val\n\nopen ulift\n\ndef push : list partial_val → value → get_m ( value ⊕ parser_state )\n| [] v := pure (sum.inl v)\n| (partial_val.array ar :: vs) v :=\n do t ← read_word,\n if down t = comma then pure (sum.inr (partial_val.array (v :: ar) :: vs))\n else if down t = close_square then push vs (value.array () (list.reverse $ v :: ar))\n else failure\n| (partial_val.object ar fn :: vs) v :=\n do t ← read_word,\n if down t = comma then do\n ⟨token.string fn'⟩ ← read_word | failure,\n ⟨colon⟩ ← read_word | failure,\n pure (sum.inr (partial_val.object ((fn,v) :: ar) fn' :: vs))\n else if down t = close_curly then push vs (value.object () (list.reverse $ (fn,v) :: ar))\n else failure\n\ndef parser_step : parser_state → token → get_m ( value ⊕ parser_state )\n| vs nil := push vs value.nil\n| vs open_curly :=\n do t ← read_word,\n match down t with\n | (token.string fn) :=\n expect_word colon >>\n pure (sum.inr (partial_val.object [] fn :: vs))\n | close_curly := push vs (value.object () [])\n | _ := failure\n end\n| vs open_square := pure (sum.inr (partial_val.array [] :: vs))\n| vs (token.bool b) := push vs (value.bool b)\n| vs (token.number n) := push vs (value.number n)\n| vs (token.string str) := push vs (value.string str)\n| vs close_square :=\n match vs with\n | (partial_val.array vs' :: vs) := push vs $ value.array () vs'.reverse\n | _ := failure\n end\n| _ _ := failure\n\n\ndef decode_val : get_m value :=\nget_m.loop parser_step pure []\n\ndef encoding_correctness_val (m : ℕ) :=\n(∀ (v : value) (vs : list partial_val) (x : punit → put_m), sizeof v ≤ m →\n get_m.loop parser_step pure vs -<< (encode_val v >>= x) =\n (push vs v >>= get_m.loop.rest parser_step pure) -<< x punit.star)\n\ndef encoding_correctness_obj (m : ℕ) :=\n(∀ (fn : string) (v : value) (obj obj' : object)\n (vs : list partial_val) (x : punit → put_m),\n sizeof obj' ≤ m → sizeof v < m →\nget_m.loop parser_step pure (partial_val.object obj fn :: vs) -<<\n (encode_obj v obj' >>= λ _, write_word close_curly >>= x) =\n (push vs (value.object punit.star (obj.reverse ++ (fn,v) :: obj')) >>= get_m.loop.rest parser_step pure) -<< x punit.star)\n\ndef encoding_correctness_array (m : ℕ) :=\n(∀ (v v' : list value)\n (vs : list partial_val) (x : punit → put_m), sizeof v' ≤ m →\nget_m.loop parser_step pure (partial_val.array v :: vs) -<<\n (encode_array v' >>= λ (x_1 : punit), write_word close_square >>= x) =\n (push vs (value.array punit.star (v.reverse ++ v')) >>= get_m.loop.rest parser_step pure) -<< x punit.star)\n\nsection correctness\n\nvariables n : ℕ\nvariables ih_val : ∀ (x : ℕ), x < n → encoding_correctness_val x\nvariables ih_obj : ∀ (x : ℕ), x < n → encoding_correctness_obj x\nvariables ih_ar : ∀ (x : ℕ), x < n → encoding_correctness_array x\n\ninclude ih_val ih_obj ih_ar\n\nlemma encode_val_ind_step : encoding_correctness_val n :=\nbegin\n dsimp [encoding_correctness_val], introv h,\n { cases v with v fs _ v fs; casesm* unit;\n try { simp [encode_val,parser_step] },\n { rcases fs with _ | ⟨ ⟨ fn,v ⟩, vs ⟩,\n { simp [encode_val,parser_step] with functor_norm },\n { simp [encode_val,parser_step,expect_word] with functor_norm,\n apply ih_obj (1 + sizeof v + sizeof vs),\n apply lt_of_lt_of_le _ h,\n well_founded_tactics.default_dec_tac,\n apply le_of_lt, well_founded_tactics.default_dec_tac,\n well_founded_tactics.default_dec_tac }, },\n { simp [encode_val,parser_step] with functor_norm,\n rw ih_ar; try { refl },\n apply lt_of_lt_of_le _ h,\n simp [sizeof,has_sizeof.sizeof,value.sizeof,punit.sizeof,list.sizeof] } },\nend\n\nlemma encode_obj_ind_step : encoding_correctness_obj n :=\nbegin\n dsimp [encoding_correctness_obj], introv h h',\n { rcases obj' with _ | ⟨ ⟨ fn', v' ⟩, obj' ⟩,\n { simp [encode_obj], rw ih_val; try { assumption <|> refl },\n simp [push] with functor_norm, },\n { simp [encode_obj] with functor_norm, rw ih_val (sizeof v),\n simp [push] with functor_norm, rw ih_obj (1 + sizeof v' + sizeof obj'),\n congr' 4, simp,\n apply lt_of_lt_of_le _ h,\n all_goals { try { well_founded_tactics.default_dec_tac } },\n apply le_of_lt, well_founded_tactics.default_dec_tac,\n refl } },\nend\n\nlemma encode_array_ind_step : encoding_correctness_array n :=\nbegin\n dsimp [encoding_correctness_array], introv h,\n { cases v' with v' vs'; simp [encode_array,parser_step] with functor_norm,\n rw ih_val (sizeof v' ),\n by_cases h' : (vs' = []),\n { subst vs', simp [when,list.empty,push] with functor_norm },\n { simp [when,*,push] with functor_norm,\n rw ih_ar (sizeof vs'), simp, apply lt_of_lt_of_le _ h,\n well_founded_tactics.default_dec_tac, refl },\n apply lt_of_lt_of_le _ h,\n well_founded_tactics.default_dec_tac,\n refl },\nend\n\nend correctness\n\nlemma encoding_correctness' (m : ℕ) :\n encoding_correctness_val m ∧\n encoding_correctness_obj m ∧\n encoding_correctness_array m :=\nbegin\n induction m using nat.strong_induction_on with n ih,\n simp [imp_and_distrib,forall_and_distrib,push] at ih,\n rcases ih with ⟨ ih_val, ih_obj, ih_ar ⟩,\n repeat { split },\n apply encode_val_ind_step; assumption,\n apply encode_obj_ind_step; assumption,\n apply encode_array_ind_step; assumption,\nend\n\nlemma encoding_correctness (v : value) :\n decode_val -<< encode_val v = some v :=\nbegin\n have := (encoding_correctness' (sizeof v)).1 v [] pure _,\n simp with functor_norm at this,\n simp [decode_val,this,push], refl, refl\nend\n\ndef value.repr : token → string\n| (token.number n) := to_string n\n| (token.string s) := \"\\\"\" ++ s ++ \"\\\"\"\n| (token.bool b) := to_string b\n| nil := \"nil\"\n| open_curly := \"'{'\"\n| close_curly := \"'}'\"\n| open_square := \"'['\"\n| close_square := \"']'\"\n| colon := \"':'\"\n| comma := \"','\"\n\ninstance : has_repr token := ⟨ value.repr ⟩\n\n#eval (encode_val (value.object ()\n [ (\"a\",value.number 3),\n (\"boo\",value.array () [ value.number 3,\n value.array () [ value.number 3, value.number 7, value.string \"ho\" ] ,\n value.string \"abc\" ]) ])).eval\n\n\nend syntax\nend json\n\n-- namespace yaml\n\n-- open string.medium json\n\n-- @[reducible] def writer := reader_t ℕ put_m'\n\n-- def newline : writer unit :=\n-- ⟨ λ n, emit $ \"\\n\" ++ (list.repeat ' ' n).as_string ⟩\n\n-- def bump {α} (tac : writer α) : writer α :=\n-- ⟨ λ n, tac.run (n+2) ⟩\n\n-- mutual def encode_aux, encode_obj, encode_array\n-- with encode_aux : value → writer unit\n-- | (value.string v) := monad_lift $ emit $ \"\\\"\" ++ v ++ \"\\\"\"\n-- | (value.bool v) := monad_lift $ emit $ to_string v\n-- | (value.number v) := monad_lift $ emit $ to_string v\n-- | value.nil := monad_lift $ emit \"nil\"\n-- | (value.object _ o) := encode_obj o\n-- | (value.array _ ar) := encode_array ar\n-- with encode_obj : list (string × value) → writer unit\n-- | [] := monad_lift $ emit \"[]\"\n-- | ((f,v) :: vs) :=\n-- do monad_lift $ emit (f ++ \": \"),\n-- bump $ do {\n-- when (¬ is_atom v) newline,\n-- encode_aux v },\n-- when (¬ vs.empty) $ do\n-- newline,\n-- encode_obj vs\n-- with encode_array : list value → writer unit\n-- | [] := monad_lift $ emit \"[]\"\n-- | (v :: vs) :=\n-- do monad_lift $ emit \"- \",\n-- bump $ encode_aux v,\n-- when (¬ vs.empty) $ do\n-- newline,\n-- encode_array vs\n\n-- def encode (v : value) : put_m :=\n-- (encode_aux v).run 0\n\n-- def select_aux {α} (f : char → list (bool × reader α)) (c : char) : reader α :=\n-- (prod.snd <$> list.find (λ x, prod.fst x = tt) (f c)).get_or_else failure\n\n-- def select {α} (f : char → list (bool × reader α)) : reader α :=\n-- peek >>= select_aux f\n\n-- def try_char (p : char → Prop) [decidable_pred p] : reader (option char) :=\n-- do c ← read_char,\n-- if p c then pure c\n-- else unread c >> pure none\n\n-- def many_loop (p : char → Prop) [decidable_pred p] : list char → char → get_m ((list char × option char) ⊕ list char)\n-- | s c :=\n-- if p c then pure (sum.inr $ c :: s)\n-- else pure (sum.inl (s.reverse,some c))\n\n-- def many (p : char → Prop) [decidable_pred p] : reader (list char) :=\n-- ⟨ λ n, ⟨ λ s : option char,\n-- do s' ← match s with\n-- | none := pure $ sum.inr []\n-- | (some s) := many_loop p [] s\n-- end,\n-- match s' with\n-- | (sum.inl x) := pure x\n-- | (sum.inr x) := get_m.loop (many_loop p) pure x\n-- end ⟩ ⟩\n\n-- def parse_nat : reader ℕ :=\n-- do c ← read_char,\n-- guard c.is_digit,\n-- cs ← many char.is_digit,\n-- pure $ list.foldl (λ x (c : char), 10 * x + c.val - '0'.val) 0 (c :: cs)\n\n-- def parse_int : reader ℤ :=\n-- do x ← try_char (= '-'),\n-- n ← parse_nat,\n-- pure $ if x.is_some then - ↑n\n-- else n\n\n-- def parse_value : reader value :=\n-- value.number <$> parse_int <* expect_char '\\n'\n\n-- -- def read_write (i n : ℕ) :\n-- -- parse_value.run i -<< encode (value.number n) = some (value.number n) :=\n-- -- begin\n-- -- rw [encode,encode_aux,emit],\n-- -- induction n using nat.strong_induction_on,\n-- -- simp [to_string,has_to_string.to_string],\n-- -- unfold_coes, simp [int.repr],\n-- -- -- induction h : (string.to_list (to_string ↑n)) generalizing n;\n-- -- -- rw [mmap'],\n-- -- -- { admit },\n-- -- -- { simp [monad_lift_and_then writer,parse_value,parse_int] with functor_norm, }\n-- -- end\n\n\n-- #eval do io.put_str_ln \"\",\n-- io.put_str_ln $ to_string $ encode (value.object ()\n-- [ (\"a\",value.number 3),\n-- (\"boo\",value.array () [ value.number 3,\n-- value.array () [ value.number 3, value.number 7, value.string \"ho\" ] ,\n-- value.string \"abc\" ]) ])\n\n-- end yaml\n", "meta": {"author": "leanprover-community", "repo": "mathlib-nursery", "sha": "0479b31fa5b4d39f41e89b8584c9f5bf5271e8ec", "save_path": "github-repos/lean/leanprover-community-mathlib-nursery", "path": "github-repos/lean/leanprover-community-mathlib-nursery/mathlib-nursery-0479b31fa5b4d39f41e89b8584c9f5bf5271e8ec/src/data/serial/json.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4301473339755162, "lm_q2_score": 0.027585281527290968, "lm_q1q2_score": 0.011865735305928266}} {"text": "/-\nCopyright (c) 2020 Robert Y. Lewis. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Robert Y. Lewis\n-/\n\n/-!\n# Documentation commands\n\nWe generate html documentation from mathlib. It is convenient to collect lists of tactics, commands,\nnotes, etc. To facilitate this, we declare these documentation entries in the library\nusing special commands.\n\n* `library_note` adds a note describing a certain feature or design decision. These can be\n referenced in doc strings with the text `note [name of note]`.\n* `add_tactic_doc` adds an entry documenting an interactive tactic, command, hole command, or\n attribute.\n\nSince these commands are used in files imported by `tactic.core`, this file has no imports.\n\n## Implementation details\n\n`library_note note_id note_msg` creates a declaration `` `library_note.i `` for some `i`.\nThis declaration is a pair of strings `note_id` and `note_msg`, and it gets tagged with the\n`library_note` attribute.\n\nSimilarly, `add_tactic_doc` creates a declaration `` `tactic_doc.i `` that stores the provided\ninformation.\n-/\n\n/-- A rudimentary hash function on strings. -/\ndef string.hash (s : string) : ℕ :=\ns.fold 1 (λ h c, (33*h + c.val) % unsigned_sz)\n\n/-- Get the last component of a name, and convert it to a string. -/\nmeta def name.last : name → string\n| (name.mk_string s _) := s\n| (name.mk_numeral n _) := repr n\n| anonymous := \"[anonymous]\"\n\nopen tactic\n\n/--\n`copy_doc_string fr to` copies the docstring from the declaration named `fr`\nto each declaration named in the list `to`. -/\nmeta def tactic.copy_doc_string (fr : name) (to : list name) : tactic unit :=\ndo fr_ds ← doc_string fr,\n to.mmap' $ λ tgt, add_doc_string tgt fr_ds\n\nopen lean lean.parser interactive\n\n/--\n`copy_doc_string source → target_1 target_2 ... target_n` copies the doc string of the\ndeclaration named `source` to each of `target_1`, `target_2`, ..., `target_n`.\n -/\n@[user_command] meta def copy_doc_string_cmd\n (_ : parse (tk \"copy_doc_string\")) : parser unit :=\ndo fr ← parser.ident,\n tk \"->\",\n to ← parser.many parser.ident,\n expr.const fr _ ← resolve_name fr,\n to ← parser.of_tactic (to.mmap $ λ n, expr.const_name <$> resolve_name n),\n tactic.copy_doc_string fr to\n\n/-! ### The `library_note` command -/\n\n/-- A user attribute `library_note` for tagging decls of type `string × string` for use in note\noutput. -/\n@[user_attribute] meta def library_note_attr : user_attribute :=\n{ name := `library_note,\n descr := \"Notes about library features to be included in documentation\",\n parser := failed }\n\n/--\n`mk_reflected_definition name val` constructs a definition declaration by reflection.\n\nExample: ``mk_reflected_definition `foo 17`` constructs the definition\ndeclaration corresponding to `def foo : ℕ := 17`\n-/\nmeta def mk_reflected_definition (decl_name : name) {type} [reflected _ type]\n (body : type) [reflected _ body] : declaration :=\nmk_definition decl_name (reflect type).collect_univ_params (reflect type) (reflect body)\n\n/--\nIf `note_name` and `note` are strings, `add_library_note note_name note` adds a declaration named\n`library_note.` with `note` as the docstring and tags it with the `library_note`\nattribute.\n-/\nmeta def tactic.add_library_note (note_name note : string) : tactic unit :=\ndo let decl_name := `library_note <.> note_name,\n add_decl $ mk_reflected_definition decl_name (),\n add_doc_string decl_name note,\n library_note_attr.set decl_name () tt none\n\nopen tactic\n\n/--\nA command to add library notes. Syntax:\n```\n/--\nnote message\n-/\nlibrary_note \"note id\"\n```\n-/\n@[user_command] meta def library_note (mi : interactive.decl_meta_info)\n (_ : parse (tk \"library_note\")) : parser unit := do\nnote_name ← parser.pexpr,\nnote_name ← eval_pexpr string note_name,\nsome doc_string ← pure mi.doc_string | fail \"library_note requires a doc string\",\nadd_library_note note_name doc_string\n\n/-- Collects all notes in the current environment.\nReturns a list of pairs `(note_id, note_content)` -/\nmeta def tactic.get_library_notes : tactic (list (string × string)) :=\nattribute.get_instances `library_note >>=\n list.mmap (λ dcl, prod.mk dcl.last <$> doc_string dcl)\n\n/-! ### The `add_tactic_doc_entry` command -/\n\n/-- The categories of tactic doc entry. -/\n@[derive [decidable_eq, has_reflect]]\ninductive doc_category\n| tactic | cmd | hole_cmd | attr\n\n/-- Format a `doc_category` -/\nmeta def doc_category.to_string : doc_category → string\n| doc_category.tactic := \"tactic\"\n| doc_category.cmd := \"command\"\n| doc_category.hole_cmd := \"hole_command\"\n| doc_category.attr := \"attribute\"\n\nmeta instance : has_to_format doc_category := ⟨↑doc_category.to_string⟩\n\n/-- The information used to generate a tactic doc entry -/\n@[derive has_reflect]\nstructure tactic_doc_entry :=\n(name : string)\n(category : doc_category)\n(decl_names : list _root_.name)\n(tags : list string := [])\n(inherit_description_from : option _root_.name := none)\n\n/-- Turns a `tactic_doc_entry` into a JSON representation. -/\nmeta def tactic_doc_entry.to_json (d : tactic_doc_entry) (desc : string) : json :=\njson.object [\n (\"name\", d.name),\n (\"category\", d.category.to_string),\n (\"decl_names\", d.decl_names.map (json.of_string ∘ to_string)),\n (\"tags\", d.tags.map json.of_string),\n (\"description\", desc)\n]\n\nmeta instance tactic_doc_entry.has_to_string : has_to_string (tactic_doc_entry × string) :=\n⟨λ ⟨doc, desc⟩, json.unparse (doc.to_json desc)⟩\n\n/-- A user attribute `tactic_doc` for tagging decls of type `tactic_doc_entry`\nfor use in doc output -/\n@[user_attribute] meta def tactic_doc_entry_attr : user_attribute :=\n{ name := `tactic_doc,\n descr := \"Information about a tactic to be included in documentation\",\n parser := failed }\n\n/-- Collects everything in the environment tagged with the attribute `tactic_doc`. -/\nmeta def tactic.get_tactic_doc_entries : tactic (list (tactic_doc_entry × string)) :=\nattribute.get_instances `tactic_doc >>=\n list.mmap (λ dcl, prod.mk <$> (mk_const dcl >>= eval_expr tactic_doc_entry) <*> doc_string dcl)\n\n/-- `add_tactic_doc tde` adds a declaration to the environment\nwith `tde` as its body and tags it with the `tactic_doc`\nattribute. If `tde.decl_names` has exactly one entry `` `decl`` and\nif `tde.description` is the empty string, `add_tactic_doc` uses the doc\nstring of `decl` as the description. -/\nmeta def tactic.add_tactic_doc (tde : tactic_doc_entry) (doc : option string) : tactic unit :=\ndo desc ← doc <|> (do\n inh_id ← match tde.inherit_description_from, tde.decl_names with\n | some inh_id, _ := pure inh_id\n | none, [inh_id] := pure inh_id\n | none, _ := fail \"A tactic doc entry must either:\n 1. have a description written as a doc-string for the `add_tactic_doc` invocation, or\n 2. have a single declaration in the `decl_names` field, to inherit a description from, or\n 3. explicitly indicate the declaration to inherit the description from using\n `inherit_description_from`.\"\n end,\n doc_string inh_id <|> fail (to_string inh_id ++ \" has no doc string\")),\n let decl_name := `tactic_doc <.> tde.category.to_string <.> tde.name,\n add_decl $ mk_definition decl_name [] `(tactic_doc_entry) (reflect tde),\n add_doc_string decl_name desc,\n tactic_doc_entry_attr.set decl_name () tt none\n\n/--\nA command used to add documentation for a tactic, command, hole command, or attribute.\n\nUsage: after defining an interactive tactic, command, or attribute,\nadd its documentation as follows.\n```lean\n/--\ndescribe what the command does here\n-/\nadd_tactic_doc\n{ name := \"display name of the tactic\",\n category := cat,\n decl_names := [`dcl_1, `dcl_2],\n tags := [\"tag_1\", \"tag_2\"] }\n```\n\nThe argument to `add_tactic_doc` is a structure of type `tactic_doc_entry`.\n* `name` refers to the display name of the tactic; it is used as the header of the doc entry.\n* `cat` refers to the category of doc entry.\n Options: `doc_category.tactic`, `doc_category.cmd`, `doc_category.hole_cmd`, `doc_category.attr`\n* `decl_names` is a list of the declarations associated with this doc. For instance,\n the entry for `linarith` would set ``decl_names := [`tactic.interactive.linarith]``.\n Some entries may cover multiple declarations.\n It is only necessary to list the interactive versions of tactics.\n* `tags` is an optional list of strings used to categorize entries.\n* The doc string is the body of the entry. It can be formatted with markdown.\n What you are reading now is the description of `add_tactic_doc`.\n\nIf only one related declaration is listed in `decl_names` and if this\ninvocation of `add_tactic_doc` does not have a doc string, the doc string of\nthat declaration will become the body of the tactic doc entry. If there are\nmultiple declarations, you can select the one to be used by passing a name to\nthe `inherit_description_from` field.\n\nIf you prefer a tactic to have a doc string that is different then the doc entry,\nyou should write the doc entry as a doc string for the `add_tactic_doc` invocation.\n\nNote that providing a badly formed `tactic_doc_entry` to the command can result in strange error\nmessages.\n\n-/\n@[user_command] meta def add_tactic_doc_command (mi : interactive.decl_meta_info)\n (_ : parse $ tk \"add_tactic_doc\") : parser unit := do\npe ← parser.pexpr,\ne ← eval_pexpr tactic_doc_entry pe,\ntactic.add_tactic_doc e mi.doc_string .\n\n/--\nAt various places in mathlib, we leave implementation notes that are referenced from many other\nfiles. To keep track of these notes, we use the command `library_note`. This makes it easy to\nretrieve a list of all notes, e.g. for documentation output.\n\nThese notes can be referenced in mathlib with the syntax `Note [note id]`.\nOften, these references will be made in code comments (`--`) that won't be displayed in docs.\nIf such a reference is made in a doc string or module doc, it will be linked to the corresponding\nnote in the doc display.\n\nSyntax:\n```\n/--\nnote message\n-/\nlibrary_note \"note id\"\n```\n\nAn example from `meta.expr`:\n\n```\n/--\nSome declarations work with open expressions, i.e. an expr that has free variables.\nTerms will free variables are not well-typed, and one should not use them in tactics like\n`infer_type` or `unify`. You can still do syntactic analysis/manipulation on them.\nThe reason for working with open types is for performance: instantiating variables requires\niterating through the expression. In one performance test `pi_binders` was more than 6x\nquicker than `mk_local_pis` (when applied to the type of all imported declarations 100x).\n-/\nlibrary_note \"open expressions\"\n```\n\nThis note can be referenced near a usage of `pi_binders`:\n\n\n```\n-- See Note [open expressions]\n/-- behavior of f -/\ndef f := pi_binders ...\n```\n-/\nadd_tactic_doc\n{ name := \"library_note\",\n category := doc_category.cmd,\n decl_names := [`library_note, `tactic.add_library_note],\n tags := [\"documentation\"],\n inherit_description_from := `library_note }\n\nadd_tactic_doc\n{ name := \"add_tactic_doc\",\n category := doc_category.cmd,\n decl_names := [`add_tactic_doc_command, `tactic.add_tactic_doc],\n tags := [\"documentation\"],\n inherit_description_from := `add_tactic_doc_command }\n\nadd_tactic_doc\n{ name := \"copy_doc_string\",\n category := doc_category.cmd,\n decl_names := [`copy_doc_string_cmd, `tactic.copy_doc_string],\n tags := [\"documentation\"],\n inherit_description_from := `copy_doc_string_cmd }\n\n-- add docs to core tactics\n\n/--\nThe congruence closure tactic `cc` tries to solve the goal by chaining\nequalities from context and applying congruence (i.e. if `a = b`, then `f a = f b`).\nIt is a finishing tactic, i.e. it is meant to close\nthe current goal, not to make some inconclusive progress.\nA mostly trivial example would be:\n\n```lean\nexample (a b c : ℕ) (f : ℕ → ℕ) (h: a = b) (h' : b = c) : f a = f c := by cc\n```\n\nAs an example requiring some thinking to do by hand, consider:\n\n```lean\nexample (f : ℕ → ℕ) (x : ℕ)\n (H1 : f (f (f x)) = x) (H2 : f (f (f (f (f x)))) = x) :\n f x = x :=\nby cc\n```\n\nThe tactic works by building an equality matching graph. It's a graph where\nthe vertices are terms and they are linked by edges if they are known to\nbe equal. Once you've added all the equalities in your context, you take\nthe transitive closure of the graph and, for each connected component\n(i.e. equivalence class) you can elect a term that will represent the\nwhole class and store proofs that the other elements are equal to it.\nYou then take the transitive closure of these equalities under the\ncongruence lemmas.\n\nThe `cc` implementation in Lean does a few more tricks: for example it\nderives `a=b` from `nat.succ a = nat.succ b`, and `nat.succ a !=\nnat.zero` for any `a`.\n\n* The starting reference point is Nelson, Oppen, [Fast decision procedures based on congruence\nclosure](http://www.cs.colorado.edu/~bec/courses/csci5535-s09/reading/nelson-oppen-congruence.pdf),\nJournal of the ACM (1980)\n\n* The congruence lemmas for dependent type theory as used in Lean are described in\n[Congruence closure in intensional type theory](https://leanprover.github.io/papers/congr.pdf)\n(de Moura, Selsam IJCAR 2016).\n-/\nadd_tactic_doc\n{ name := \"cc (congruence closure)\",\n category := doc_category.tactic,\n decl_names := [`tactic.interactive.cc],\n tags := [\"core\", \"finishing\"] }\n\n/--\n`conv {...}` allows the user to perform targeted rewriting on a goal or hypothesis,\nby focusing on particular subexpressions.\n\nSee for more details.\n\nInside `conv` blocks, mathlib currently additionally provides\n* `erw`,\n* `ring`, `ring2` and `ring_exp`,\n* `norm_num`,\n* `norm_cast`,\n* `apply_congr`, and\n* `conv` (within another `conv`).\n\n`apply_congr` applies congruence lemmas to step further inside expressions,\nand sometimes gives better results than the automatically generated\ncongruence lemmas used by `congr`.\n\nUsing `conv` inside a `conv` block allows the user to return to the previous\nstate of the outer `conv` block after it is finished. Thus you can continue\nediting an expression without having to start a new `conv` block and re-scoping\neverything. For example:\n```lean\nexample (a b c d : ℕ) (h₁ : b = c) (h₂ : a + c = a + d) : a + b = a + d :=\nby conv\n{ to_lhs,\n conv\n { congr, skip,\n rw h₁ },\n rw h₂, }\n```\nWithout `conv`, the above example would need to be proved using two successive\n`conv` blocks, each beginning with `to_lhs`.\n\nAlso, as a shorthand, `conv_lhs` and `conv_rhs` are provided, so that\n```lean\nexample : 0 + 0 = 0 :=\nbegin\n conv_lhs { simp }\nend\n```\njust means\n```lean\nexample : 0 + 0 = 0 :=\nbegin\n conv { to_lhs, simp }\nend\n```\nand likewise for `to_rhs`.\n-/\nadd_tactic_doc\n{ name := \"conv\",\n category := doc_category.tactic,\n decl_names := [`tactic.interactive.conv],\n tags := [\"core\"] }\n\nadd_tactic_doc\n{ name := \"simp\",\n category := doc_category.tactic,\n decl_names := [`tactic.interactive.simp],\n tags := [\"core\", \"simplification\"] }\n\n/--\nAccepts terms with the type `component tactic_state string` or `html empty` and\nrenders them interactively.\nRequires a compatible version of the vscode extension to view the resulting widget.\n\n### Example:\n\n```lean\n/-- A simple counter that can be incremented or decremented with some buttons. -/\nmeta def counter_widget {π α : Type} : component π α :=\ncomponent.ignore_props $ component.mk_simple int int 0 (λ _ x y, (x + y, none)) (λ _ s,\n h \"div\" [] [\n button \"+\" (1 : int),\n html.of_string $ to_string $ s,\n button \"-\" (-1)\n ]\n)\n\n#html counter_widget\n```\n-/\nadd_tactic_doc\n{ name := \"#html\",\n category := doc_category.cmd,\n decl_names := [`show_widget_cmd],\n tags := [\"core\", \"widgets\"] }\n\n/--\nThe `add_decl_doc` command is used to add a doc string to an existing declaration.\n\n```lean\ndef foo := 5\n\n/--\nDoc string for foo.\n-/\nadd_decl_doc foo\n```\n-/\n@[user_command] meta def add_decl_doc_command (mi : interactive.decl_meta_info)\n (_ : parse $ tk \"add_decl_doc\") : parser unit := do\nn ← parser.ident,\nn ← resolve_constant n,\nsome doc ← pure mi.doc_string | fail \"add_decl_doc requires a doc string\",\nadd_doc_string n doc\n\nadd_tactic_doc\n{ name := \"add_decl_doc\",\n category := doc_category.cmd,\n decl_names := [``add_decl_doc_command],\n tags := [\"documentation\"] }\n", "meta": {"author": "leanprover-community", "repo": "mathlib", "sha": "5e526d18cea33550268dcbbddcb822d5cde40654", "save_path": "github-repos/lean/leanprover-community-mathlib", "path": "github-repos/lean/leanprover-community-mathlib/mathlib-5e526d18cea33550268dcbbddcb822d5cde40654/src/tactic/doc_commands.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.16238002450622283, "lm_q2_score": 0.07263670937204118, "lm_q1q2_score": 0.011794750647883432}} {"text": "import .gluing\n\nuniverses v u\n\nopen category_theory\nlocal notation f ` ∘ `:80 g:80 := g ≫ f\n\nnamespace homotopy_theory.cofibrations\nopen precofibration_category cofibration_category\nopen homotopy_theory.weak_equivalences\n\nvariables {C : Type u} [category.{v} C] [cofibration_category.{v} C]\n [has_initial_object.{v} C]\n\nvariables {a b a' b' : C} {i : a ⟶ b} {f : a ⟶ a'} {i' : a' ⟶ b'} {f' : b ⟶ b'}\n (po : Is_pushout i f f' i')\n\nlemma pushout_is_weq (ha : cofibrant a) (ha' : cofibrant a') (hi : is_cof i) (hf : is_weq f) :\n is_weq f' :=\nhave _ := gluing_weq (Is_pushout.refl i) po ha ha ha ha' hi hi\n (weq_id a) (weq_id b) hf (by simp) (by simp),\nbegin\n convert ←this,\n apply pushout_induced_eq_iff; simp [po.commutes]\nend\n\ninstance [all_objects_cofibrant.{v} C] : left_proper.{v} C :=\n{ pushout_weq_by_cof := λ a b a' b' f g f' g' po hf hg,\n by refine pushout_is_weq po _ _ hf hg; exact all_objects_cofibrant.cofibrant _ }\n\nend homotopy_theory.cofibrations\n", "meta": {"author": "rwbarton", "repo": "lean-homotopy-theory", "sha": "39e1b4ea1ed1b0eca2f68bc64162dde6a6396dee", "save_path": "github-repos/lean/rwbarton-lean-homotopy-theory", "path": "github-repos/lean/rwbarton-lean-homotopy-theory/lean-homotopy-theory-39e1b4ea1ed1b0eca2f68bc64162dde6a6396dee/src/homotopy_theory/formal/cofibrations/left_proper.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4532618480153861, "lm_q2_score": 0.025957360070550783, "lm_q1q2_score": 0.011765480995178641}} {"text": "\nimport for_mathlib.composable_morphisms\nimport algebra.homology.additive\nimport for_mathlib.homological_complex_map_d_to_d_from\n\nnoncomputable theory\n\nopen category_theory category_theory.category category_theory.limits\n\nvariables {C D : Type*} [category C] [category D]\n\nsection\n\nvariables (C)\n\n/- Category of complexes `X ⟶ Y ⟶ Z` -/\n@[derive category]\ndef short_complex [has_zero_morphisms C] := full_subcategory $ λ S : composable_morphisms C, S.zero\n\nend\n\nopen category_theory\n\nnamespace homological_complex\n\nvariables [has_zero_morphisms C] {M : Type*} {c : complex_shape M}\n\nlemma prev_id (X : homological_complex C c) (i : M) : hom.prev (𝟙 X) i = 𝟙 (X.X_prev i) := rfl\n\nlemma next_id (X : homological_complex C c) (i : M) : hom.next (𝟙 X) i = 𝟙 (X.X_next i) := rfl\n\nlemma prev_comp {X Y Z : homological_complex C c} (f : X ⟶ Y) (g : Y ⟶ Z)\n (i : M) : hom.prev (f ≫ g) i = hom.prev f i ≫ hom.prev g i := rfl\n\nlemma next_comp {X Y Z : homological_complex C c} (f : X ⟶ Y) (g : Y ⟶ Z)\n (i : M) : hom.next (f ≫ g) i = hom.next f i ≫ hom.next g i := rfl\n\nend homological_complex\n\nnamespace short_complex\n\n@[simp, reassoc]\nlemma zero [has_zero_morphisms C] (S : short_complex C) : S.1.f ≫ S.1.g = 0 := S.2\n\n@[simps]\ndef mk [has_zero_morphisms C] {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) (zero : f ≫ g = 0) :\n short_complex C := ⟨composable_morphisms.mk f g, zero⟩\n\n@[simp]\nlemma mk_id_τ₁ [has_zero_morphisms C] {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) (zero : f ≫ g = 0) :\ncomposable_morphisms.hom.τ₁ (𝟙 (mk f g zero)) = 𝟙 X := rfl\n@[simp]\nlemma mk_id_τ₂ [has_zero_morphisms C] {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) (zero : f ≫ g = 0) :\ncomposable_morphisms.hom.τ₂ (𝟙 (mk f g zero)) = 𝟙 Y := rfl\n@[simp]\nlemma mk_id_τ₃ [has_zero_morphisms C] {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) (zero : f ≫ g = 0) :\ncomposable_morphisms.hom.τ₃ (𝟙 (mk f g zero)) = 𝟙 Z := rfl\n\n@[simp]\nlemma comp_τ₁ [has_zero_morphisms C] {S₁ S₂ S₃ : short_complex C} (f : S₁ ⟶ S₂) (g : S₂ ⟶ S₃) :\n (f ≫ g).τ₁ = f.τ₁ ≫ g.τ₁ := rfl\n@[simp]\nlemma comp_τ₂ [has_zero_morphisms C] {S₁ S₂ S₃ : short_complex C} (f : S₁ ⟶ S₂) (g : S₂ ⟶ S₃) :\n (f ≫ g).τ₂ = f.τ₂ ≫ g.τ₂ := rfl\n@[simp]\nlemma comp_τ₃ [has_zero_morphisms C] {S₁ S₂ S₃ : short_complex C} (f : S₁ ⟶ S₂) (g : S₂ ⟶ S₃) :\n (f ≫ g).τ₃ = f.τ₃ ≫ g.τ₃ := rfl\n\n@[simps]\ndef hom_mk [has_zero_morphisms C] {X₁ Y₁ Z₁ X₂ Y₂ Z₂ : C} {f₁ : X₁ ⟶ Y₁} {g₁ : Y₁ ⟶ Z₁}\n {f₂ : X₂ ⟶ Y₂} {g₂ : Y₂ ⟶ Z₂} {zero₁ : f₁ ≫ g₁ = 0} {zero₂ : f₂ ≫ g₂ = 0}\n (τ₁ : X₁ ⟶ X₂) (τ₂ : Y₁ ⟶ Y₂) (τ₃ : Z₁ ⟶ Z₂) (comm₁₂ : f₁ ≫ τ₂ = τ₁ ≫ f₂)\n (comm₂₃ : g₁ ≫ τ₃ = τ₂ ≫ g₂) :\n mk f₁ g₁ zero₁ ⟶ mk f₂ g₂ zero₂ := ⟨τ₁, τ₂, τ₃, comm₁₂, comm₂₃⟩\n\n@[simps]\ndef iso_mk [has_zero_morphisms C] {S₁ S₂ : short_complex C}\n (τ₁ : S₁.1.X ≅ S₂.1.X) (τ₂ : S₁.1.Y ≅ S₂.1.Y) (τ₃ : S₁.1.Z ≅ S₂.1.Z)\n (comm₁₂ : S₁.1.f ≫ τ₂.hom = τ₁.hom ≫ S₂.1.f)\n (comm₂₃ : S₁.1.g ≫ τ₃.hom = τ₂.hom ≫ S₂.1.g) :\n S₁ ≅ S₂ :=\n{ hom := ⟨τ₁.hom, τ₂.hom, τ₃.hom, comm₁₂, comm₂₃⟩,\n inv := begin\n refine ⟨τ₁.inv, τ₂.inv, τ₃.inv, _, _⟩,\n { simp only [← cancel_mono τ₂.hom, ← cancel_epi τ₁.hom,\n assoc, iso.inv_hom_id, comp_id, iso.hom_inv_id_assoc, comm₁₂], },\n { simp only [← cancel_mono τ₃.hom, ← cancel_epi τ₂.hom,\n assoc, iso.inv_hom_id, comp_id, iso.hom_inv_id_assoc, comm₂₃], },\n end,\n hom_inv_id' := begin\n ext,\n { simpa only [comp_τ₁, hom_mk_τ₁, iso.hom_inv_id], },\n { simpa only [comp_τ₂, hom_mk_τ₂, iso.hom_inv_id], },\n { simpa only [comp_τ₃, hom_mk_τ₃, iso.hom_inv_id], },\n end,\n inv_hom_id' := begin\n ext,\n { simpa only [iso.inv_hom_id, comp_τ₁, hom_mk_τ₁], },\n { simpa only [iso.inv_hom_id, comp_τ₂, hom_mk_τ₂], },\n { simpa only [iso.inv_hom_id, comp_τ₃, hom_mk_τ₃], },\n end, }\n\nlemma is_iso_of_is_isos [has_zero_morphisms C] {S₁ S₂ : short_complex C}\n (φ : S₁ ⟶ S₂) (h₁ : is_iso φ.τ₁) (h₂ : is_iso φ.τ₂) (h₃ : is_iso φ.τ₃) : is_iso φ :=\nbegin\n let e : S₁ ≅ S₂ := iso_mk (as_iso φ.τ₁) (as_iso φ.τ₂) (as_iso φ.τ₃) φ.comm₁₂ φ.comm₂₃,\n unfreezingI { rcases φ with ⟨τ₁, τ₂, τ₃, comm₁₂, comm₂₂⟩, },\n exact is_iso.of_iso e,\nend\n\ndef homology [abelian C] (S : short_complex C) : C := homology S.1.f S.1.g S.2\n\n@[simps]\ndef homology_functor [abelian C] : short_complex C ⥤ C :=\n{ obj := λ X, X.homology,\n map := λ X Y φ, homology.map X.2 Y.2 ⟨φ.τ₁, φ.τ₂, φ.comm₁₂.symm⟩\n ⟨φ.τ₂, φ.τ₃, φ.comm₂₃.symm⟩ rfl,\n map_id' := λ X, by apply homology.map_id,\n map_comp' := λ X Y Z φ ψ, by { symmetry, apply homology.map_comp, }, }\n\nvariable (C)\n\n@[simps]\ndef functor_homological_complex [has_zero_morphisms C]\n {M : Type*} (c : complex_shape M) (i : M) :\n homological_complex C c ⥤ short_complex C :=\n{ obj := λ X, mk (X.d_to i) (X.d_from i) (X.d_to_comp_d_from i),\n map := λ X Y f, composable_morphisms.hom.mk (f.prev i) (f.f i) (f.next i)\n (f.comm_to i).symm (f.comm_from i).symm,\n map_id' := λ X, begin\n ext,\n { exact X.prev_id i, },\n { refl, },\n { exact X.next_id i, },\n end,\n map_comp' := λ X Y Z f g, begin\n ext,\n { exact homological_complex.prev_comp f g i, },\n { refl, },\n { exact homological_complex.next_comp f g i, },\n end, }\n\n@[simps]\ndef homology_functor_iso [abelian C] {M : Type*} (c : complex_shape M) (i : M) :\n _root_.homology_functor C c i ≅\n functor_homological_complex C c i ⋙ short_complex.homology_functor :=\nnat_iso.of_components (λ X, iso.refl _)\n (λ X Y f, by { ext, simpa only [iso.refl_hom, id_comp, comp_id], })\n\nend short_complex\n\nnamespace category_theory\n\nnamespace functor\n\n@[simps]\ndef map_short_complex [has_zero_morphisms C] [has_zero_morphisms D] (F : C ⥤ D)\n [F.preserves_zero_morphisms] :\n short_complex C ⥤ short_complex D :=\nfull_subcategory.lift _ (induced_functor _ ⋙ F.map_composable_morphisms)\n(λ X, begin\n have h := X.2,\n dsimp [composable_morphisms.zero] at h ⊢,\n rw [← F.map_comp, h, F.map_zero],\nend)\n\nend functor\n\nnamespace nat_trans\n\n@[simps]\ndef map_short_complex [has_zero_morphisms C] [has_zero_morphisms D] {F G : C ⥤ D}\n [F.preserves_zero_morphisms] [G.preserves_zero_morphisms] (φ : F ⟶ G) :\n F.map_short_complex ⟶ G.map_short_complex :=\n{ app := λ X, ⟨φ.app _, φ.app _, φ.app _, φ.naturality _, φ.naturality _⟩, }\n\nend nat_trans\n\nend category_theory\n\nopen category_theory\n\nnamespace short_complex\n\nvariable {C}\n\ndef functor_homological_complex_map [preadditive C] [preadditive D] (F : C ⥤ D) [F.additive]\n {M : Type*} (c : complex_shape M) (i : M) :\nshort_complex.functor_homological_complex C c i ⋙ F.map_short_complex ≅\nF.map_homological_complex c ⋙ short_complex.functor_homological_complex D c i :=\niso.refl _\n\nvariables [preadditive C] [preadditive D] {F G : C ⥤ D} [functor.additive F] [functor.additive G]\n {M : Type*} (c : complex_shape M) (i : M) (φ : F ⟶ G) (X : homological_complex C c)\n\nlemma nat_trans.map_short_complex_app :\n (nat_trans.map_short_complex φ).app ((short_complex.functor_homological_complex C c i).obj X) =\n (short_complex.functor_homological_complex D c i).map\n ((nat_trans.map_homological_complex φ c).app X) := rfl\n\nlemma naturality_functor_homological_complex_map :\n (nat_trans.map_short_complex φ).app\n ((short_complex.functor_homological_complex C c i).obj X) ≫\n (short_complex.functor_homological_complex_map G c i).hom.app X =\n (short_complex.functor_homological_complex_map F c i).hom.app X ≫\n (short_complex.functor_homological_complex D c i).map\n ((nat_trans.map_homological_complex φ c).app X) :=\nbegin\n dsimp only [functor_homological_complex_map, iso.refl_hom, nat_trans.id_app],\n erw [nat_trans.map_short_complex_app, category.id_comp, category.comp_id],\nend\n\nend short_complex\n", "meta": {"author": "leanprover-community", "repo": "lean-liquid", "sha": "92f188bd17f34dbfefc92a83069577f708851aec", "save_path": "github-repos/lean/leanprover-community-lean-liquid", "path": "github-repos/lean/leanprover-community-lean-liquid/lean-liquid-92f188bd17f34dbfefc92a83069577f708851aec/src/for_mathlib/short_complex.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.411110869232168, "lm_q2_score": 0.028436035617857236, "lm_q1q2_score": 0.011690363320374177}} {"text": "import Runtime.Execution.ReactionInputs\n\nnamespace Network.Graph.Class.Reaction\n\ninductive Trigger (net : Network)\n | port {kind} (id : PortId net kind)\n | action (id : ActionId net)\n | timer (id : TimerId net)\n | startup\n | shutdown\n\ndef Trigger.lift {reactor : ReactorId net} {reaction : Reaction reactor.class} :\n reaction.val.triggerType → Trigger net\n | .action a => .action ⟨reactor, reaction.subAS.coe a⟩\n | .timer t => .timer ⟨reactor, reaction.eqTimers ▸ t⟩\n | .startup => .startup\n | .shutdown => .shutdown\n | .port p =>\n match reaction.subPS.coe p with\n | .inl input =>\n (.port (kind := .input) ⟨reactor, input⟩)\n | .inr ⟨c, output⟩ =>\n (.port (kind := .output) ⟨reactor.extend c, cast (by rw [Path.extend_class]) output⟩)\n\ninductive Trigger.Equiv {reactor : ReactorId net} {reaction : Reaction reactor.class} :\n (Trigger net) → reaction.val.triggerType → Prop\n | action : Equiv (.action ⟨reactor, reaction.subAS.coe a⟩) (.action a)\n | timer : Equiv (.timer ⟨reactor, reaction.eqTimers ▸ t⟩) (.timer t)\n | startup : Equiv .startup .startup\n | shutdown : Equiv .shutdown .shutdown\n | input :\n (reaction.subPS.coe p = .inl input) →\n Equiv (.port (kind := .input) ⟨reactor, input⟩) (.port p)\n | output :\n (reaction.subPS.coe p = .inr ⟨c, output⟩) →\n Equiv (.port (kind := .output) ⟨reactor.extend c, cast (by rw [Path.extend_class]) output⟩) (.port p)\n\ninfix:50 \" ≡ \" => Trigger.Equiv\n\ntheorem Trigger.Equiv.lift\n {reactor : ReactorId net} {reaction : Reaction reactor.class} (t : reaction.val.triggerType) :\n Trigger.lift t ≡ t := by\n cases t\n all_goals\n simp [Trigger.lift]\n first\n | constructor\n | split <;> (constructor; assumption)\n\nend Network.Graph.Class.Reaction\n\nnamespace Execution.Executable\nopen Network Graph Class\n\n/--\nA predicate indicating whether a given executable triggers a given reaction by means of a given\ntrigger. The main use case for this predicate is its closure: `Triggers`.\n-/\ninductive Activates (exec : Executable net) : (Class.Reaction.Trigger net) → Prop\n | port : (exec.portIsPresent p) → Activates _ (.port p)\n | action : (exec.actionIsPresent a) → Activates _ (.action a)\n | timer : (exec.timer t |>.isFiring) → Activates _ (.timer t)\n | startup : (exec.isStartingUp) → Activates _ .startup\n | shutdown : (exec.state = .shuttingDown) → Activates _ .shutdown\n\n/-- A predicate indicating whether a given executable triggers a given reaction. -/\ninductive Triggers (exec) {reactor : ReactorId net} (reaction : Reaction reactor.class) : Prop\n | witness (equiv : t ≡ t') (mem : t' ∈ reaction.val.triggers.data) (active : Activates exec t)\n\n/-- A decision procedure for `Triggers`. -/\nprivate def triggers (exec : Executable net) {reactor : ReactorId net} (reaction : Reaction reactor.class) :=\n reaction.val.triggers.any (activated ·)\nwhere\n activated : reaction.val.triggerType → Bool\n | .port port => exec.reactionInputs reactor |>.isPresent (reaction.subPS.coe port)\n | .action action => exec.interface reactor .actions |>.isPresent (reaction.subAS.coe action)\n | .timer timer => exec.reactors reactor |>.timer (reaction.eqTimers ▸ timer) |>.isFiring\n | .startup => exec.isStartingUp\n | .shutdown => exec.state = .shuttingDown\n\nset_option pp.proofs.withType false in\ntheorem Activates.port_iff_equiv_port_activated {p'} :\n (.port p ≡ .port p') →\n ((Activates exec <| .port p) ↔ (triggers.activated exec reaction <| .port p')) := by\n intro he\n constructor <;> intro h\n case mp reactor =>\n simp only [triggers.activated, reactionInputs]\n cases hp : reaction.subPS.coe p'\n case inl loc =>\n simp\n cases he\n case input hi =>\n simp [hi] at hp\n cases h\n case port h =>\n simp [portIsPresent, hp] at h\n exact h\n case output ho =>\n rw [ho] at hp\n contradiction\n case inr sub =>\n have ⟨c, output⟩ := sub\n simp at output ⊢\n cases he\n case input hi =>\n rw [hi] at hp\n contradiction\n case output c' output' ho =>\n simp [ho] at hp\n injection hp with hc ho\n subst hc\n subst ho\n cases h\n case port h =>\n simp [portIsPresent] at h\n have ⟨v, hv⟩ := h\n exists cast sorry v\n simp [hv]\n -- https://leanprover.zulipchat.com/#narrow/stream/270676-lean4\n sorry\n case mpr =>\n sorry\n\ntheorem Activates.iff_equiv_trigger_activated {t'} :\n (t ≡ t') → (Activates exec t ↔ triggers.activated exec reaction t') := by\n intro equiv\n unfold triggers.activated\n constructor\n case mp =>\n intro activates\n cases t <;> cases t' <;> (try contradiction)\n case port.port => exact Activates.port_iff_equiv_port_activated equiv |>.mp activates\n all_goals\n cases activates\n cases equiv\n all_goals\n simp_all [actionIsPresent, portIsPresent, reactionInputs]\n try assumption\n case mpr =>\n intro h\n cases t <;> cases t' <;> (try contradiction)\n case port.port => exact Activates.port_iff_equiv_port_activated equiv |>.mpr h\n all_goals\n simp at h\n constructor\n cases equiv\n all_goals\n simp_all [actionIsPresent, portIsPresent, reactionInputs]\n try assumption\n\ntheorem Triggers.iff_triggers_eq_true : (Triggers exec reaction) ↔ (exec.triggers reaction) := by\n unfold triggers\n constructor\n case mp =>\n intro ⟨equiv, mem, active⟩\n rw [Array.any_iff_mem_where]\n refine ⟨_, mem, ?_⟩\n exact Activates.iff_equiv_trigger_activated equiv |>.mp active\n case mpr =>\n intro h\n have ⟨t', mem, active⟩ := Array.any_iff_mem_where.mp h\n have ⟨_, equiv⟩ : ∃ t, t ≡ t' := ⟨_, Reaction.Trigger.Equiv.lift t'⟩\n refine .witness equiv mem ?_\n exact Activates.iff_equiv_trigger_activated equiv |>.mpr active\n\ninstance : Decidable (Triggers exec reaction) :=\n decidable_of_iff' _ Triggers.iff_triggers_eq_true\n\nend Execution.Executable\n", "meta": {"author": "lf-lang", "repo": "reactor-lean", "sha": "d2eb5458446af838be34ebb6f69549b2f6d9c04d", "save_path": "github-repos/lean/lf-lang-reactor-lean", "path": "github-repos/lean/lf-lang-reactor-lean/reactor-lean-d2eb5458446af838be34ebb6f69549b2f6d9c04d/Runtime/Execution/Triggers.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47657965106367595, "lm_q2_score": 0.02442308734689649, "lm_q1q2_score": 0.011639546445681609}} {"text": "example : (p → q) ∧ r := by\n refine ⟨?a, ?b⟩\n\nexample : (p → q) ∧ r := by\n refine ⟨fun h => ?a, ?b⟩\n", "meta": {"author": "leanprover", "repo": "lean4", "sha": "742d053a97bdd109a41a921facd1cd6a55e89bc7", "save_path": "github-repos/lean/leanprover-lean4", "path": "github-repos/lean/leanprover-lean4/lean4-742d053a97bdd109a41a921facd1cd6a55e89bc7/tests/lean/1682.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.21469139901367396, "lm_q2_score": 0.05419872600392664, "lm_q1q2_score": 0.011636000310541801}} {"text": "/-\nCopyright (c) 2022 Mac Malone. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Mac Malone\n-/\nimport Lake.Util.Name\n\nnamespace Lake\n\n/-- The type of keys in the Lake build store. -/\ninductive BuildKey\n| moduleFacet (module : Name) (facet : Name)\n| packageFacet (package : Name) (facet : Name)\n| targetFacet (package : Name) (target : Name) (facet : Name)\n| customTarget (package : Name) (target : Name)\nderiving Inhabited, Repr, DecidableEq, Hashable\n\nnamespace BuildKey\n\ndef toString : (self : BuildKey) → String\n| moduleFacet m f => s!\"+{m}:{f}\"\n| packageFacet p f => s!\"@{p}:{f}\"\n| targetFacet p t f => s!\"{p}/{t}:{f}\"\n| customTarget p t => s!\"{p}/{t}\"\n\ninstance : ToString BuildKey := ⟨(·.toString)⟩\n\ndef quickCmp (k k' : BuildKey) : Ordering :=\n match k with\n | moduleFacet m f =>\n match k' with\n | moduleFacet m' f' =>\n match m.quickCmp m' with\n | .eq => f.quickCmp f'\n | ord => ord\n | _ => .lt\n | packageFacet p f =>\n match k' with\n | moduleFacet .. => .gt\n | packageFacet p' f' =>\n match p.quickCmp p' with\n | .eq => f.quickCmp f'\n | ord => ord\n | _ => .lt\n | targetFacet p t f =>\n match k' with\n | customTarget .. => .lt\n | targetFacet p' t' f' =>\n match p.quickCmp p' with\n | .eq =>\n match t.quickCmp t' with\n | .eq => f.quickCmp f'\n | ord => ord\n | ord => ord\n | _=> .gt\n | customTarget p t =>\n match k' with\n | customTarget p' t' =>\n match p.quickCmp p' with\n | .eq => t.quickCmp t'\n | ord => ord\n | _ => .gt\n\ntheorem eq_of_quickCmp {k k' : BuildKey} :\nquickCmp k k' = Ordering.eq → k = k' := by\n unfold quickCmp\n cases k with\n | moduleFacet m f =>\n cases k'\n case moduleFacet m' f' =>\n dsimp only; split\n next m_eq => intro f_eq; rw [eq_of_cmp m_eq, eq_of_cmp f_eq]\n next => intro; contradiction\n all_goals (intro; contradiction)\n | packageFacet p f =>\n cases k'\n case packageFacet p' f' =>\n dsimp only; split\n next p_eq => intro f_eq; rw [eq_of_cmp p_eq, eq_of_cmp f_eq]\n next => intro; contradiction\n all_goals (intro; contradiction)\n | targetFacet p t f =>\n cases k'\n case targetFacet p' t' f' =>\n dsimp only; split\n next p_eq =>\n split\n next t_eq =>\n intro f_eq\n rw [eq_of_cmp p_eq, eq_of_cmp t_eq, eq_of_cmp f_eq]\n next => intro; contradiction\n next => intro; contradiction\n all_goals (intro; contradiction)\n | customTarget p t =>\n cases k'\n case customTarget p' t' =>\n dsimp only; split\n next p_eq => intro t_eq; rw [eq_of_cmp p_eq, eq_of_cmp t_eq]\n next => intro; contradiction\n all_goals (intro; contradiction)\n\ninstance : LawfulCmpEq BuildKey quickCmp where\n eq_of_cmp := eq_of_quickCmp\n cmp_rfl {k} := by cases k <;> simp [quickCmp]\n", "meta": {"author": "leanprover", "repo": "lake", "sha": "6de8ee8817c3e6bb01f9f48c2f22f7979e4ac526", "save_path": "github-repos/lean/leanprover-lake", "path": "github-repos/lean/leanprover-lake/lake-6de8ee8817c3e6bb01f9f48c2f22f7979e4ac526/Lake/Build/Key.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3665897363221598, "lm_q2_score": 0.031618769778069884, "lm_q1q2_score": 0.011591116475773714}} {"text": "import breen_deligne.eval\n\nnoncomputable theory\n\nnamespace breen_deligne\n\nopen category_theory category_theory.limits category_theory.category\n category_theory.preadditive\n\nvariables {A₁ A₂ A₃ : Type*} [category A₁] [preadditive A₁] [has_finite_biproducts A₁]\n [category A₂] [preadditive A₂] --[has_finite_biproducts A₂]\n [category A₃] [preadditive A₃] --[has_finite_biproducts A₃]\n\nnamespace universal_map\n\nvariables {m n : ℕ} (f : universal_map m n)\n\ndef eval_Pow' (F : A₁ ⥤ A₂) : universal_map m n →+ (Pow m ⋙ F ⟶ Pow n ⋙ F) :=\nfree_abelian_group.lift $ λ g : basic_universal_map m n, whisker_right g.eval_Pow F\n\n@[simp]\nlemma eval_Pow'_of (F : A₁ ⥤ A₂) (f : basic_universal_map m n) :\n eval_Pow' F (free_abelian_group.of f) = whisker_right f.eval_Pow F :=\nfree_abelian_group.lift.of _ _\n\nlemma eval_Pow'_hcomp (F : A₁ ⥤ A₂) (H : A₂ ⥤ A₃) [H.additive] :\n eval_Pow' F f ◫ 𝟙 H = eval_Pow' (F ⋙ H) f :=\nbegin\n revert f,\n let φ : universal_map m n →+ ((Pow m ⋙ F) ⋙ H ⟶ (Pow n ⋙ F) ⋙ H) :=\n { to_fun := λ f, whisker_right (eval_Pow' F f) H,\n map_zero' := by { ext, dsimp, simp only [map_zero, nat_trans.app_zero, functor.map_zero], },\n map_add' := λ f₁ f₂, by { ext, dsimp, simp only [map_add, nat_trans.app_add,\n functor.map_add], }, },\n suffices : φ = eval_Pow' (F ⋙ H),\n { intro f,\n change 𝟙 _ ≫ φ f = _,\n rw [category.id_comp, this], },\n ext1 f,\n simp only [add_monoid_hom.coe_mk, eval_Pow'_of, whisker_right_twice],\nend\n\nlemma map_eval_Pow' (F : A₁ ⥤ A₂) (H : A₂ ⥤ A₃) [H.additive] (M₁ : A₁) :\n H.map ((eval_Pow' F f).app M₁) = (eval_Pow' (F ⋙ H) f).app M₁ :=\nby simpa only [nat_trans.hcomp_id_app] using nat_trans.congr_app (f.eval_Pow'_hcomp F H) M₁\n\nlemma map_eval_Pow (F : A₁ ⥤ A₁) (H : A₁ ⥤ A₂) [H.additive] (M₁ : A₁) :\n H.map ((eval_Pow F f).app M₁) = (eval_Pow' (F ⋙ H) f).app M₁ :=\nmap_eval_Pow' f F H M₁\n\n@[reassoc]\nlemma congr_eval_Pow' {F F' : A₁ ⥤ A₂} (φ : F ⟶ F') (M₁ : A₁) :\n (eval_Pow' F f).app M₁ ≫ φ.app ((Pow n).obj M₁) =\n φ.app ((Pow m).obj M₁) ≫ (eval_Pow' F' f).app M₁ :=\nbegin\n revert f,\n let φ₁ : universal_map m n →+ ((Pow m ⋙ F).obj M₁ ⟶ (Pow n ⋙ F').obj M₁) :=\n { to_fun := λ f, (eval_Pow' F f).app M₁ ≫ φ.app ((Pow n).obj M₁),\n map_zero' := by simp only [map_zero, nat_trans.app_zero, zero_comp],\n map_add' := λ f₁ f₂, by simp only [map_add, nat_trans.app_add, add_comp], },\n let φ₂ : universal_map m n →+ ((Pow m ⋙ F).obj M₁ ⟶ (Pow n ⋙ F').obj M₁) :=\n { to_fun := λ f, φ.app ((Pow m).obj M₁) ≫ (eval_Pow' F' f).app M₁,\n map_zero' := by simp only [map_zero, nat_trans.app_zero, comp_zero],\n map_add' := λ f₁ f₂, by simp only [map_add, nat_trans.app_add, comp_add], },\n suffices : φ₁ = φ₂,\n { intro f,\n change φ₁ f = φ₂ f,\n rw this, },\n ext,\n dsimp only [φ₁, φ₂],\n simp only [add_monoid_hom.coe_mk, eval_Pow'_of, whisker_right_app, nat_trans.naturality],\nend\n\nend universal_map\n\nend breen_deligne\n", "meta": {"author": "leanprover-community", "repo": "lean-liquid", "sha": "92f188bd17f34dbfefc92a83069577f708851aec", "save_path": "github-repos/lean/leanprover-community-lean-liquid", "path": "github-repos/lean/leanprover-community-lean-liquid/lean-liquid-92f188bd17f34dbfefc92a83069577f708851aec/src/breen_deligne/eval1half.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4532618480153862, "lm_q2_score": 0.02556521401607266, "lm_q1q2_score": 0.011587736149833947}} {"text": "/-\nCopyright (c) 2022 Joël Riou. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Joël Riou\n-/\n\nimport for_mathlib.algebraic_topology.homotopical_algebra.fibrant\n\nnoncomputable theory\n\nopen category_theory category_theory.limits\nopen category_theory.category opposite\n\nnamespace algebraic_topology\n\nnamespace model_category\n\nvariables {C : Type*} [category C] [model_category C]\n\nvariables (A B : C)\n\nstructure precylinder :=\n(I : C) (d₀ d₁: A ⟶ I) (σ : I ⟶ A) [weq_σ : weak_eq σ]\n(σd₀' : d₀ ≫ σ = 𝟙 A . obviously) (σd₁' : d₁ ≫ σ = 𝟙 A . obviously)\n\nnamespace precylinder\n\nvariables {A} (P : precylinder A)\n\nrestate_axiom σd₀'\nrestate_axiom σd₁'\nattribute [simp, reassoc] σd₀ σd₁\n\ninstance weq_σ' : weak_eq P.σ := P.weq_σ\ninstance weq_d₀ : weak_eq P.d₀ := weak_eq.of_comp_right P.d₀ P.σ infer_instance\n (by { rw σd₀, apply_instance, })\ninstance weq_d₁ : weak_eq P.d₁ := weak_eq.of_comp_right P.d₁ P.σ infer_instance\n (by { rw σd₁, apply_instance, })\n\n@[simps]\ndef change_I {I' : C} {f : P.I ⟶ I'} {g : I' ⟶ A} (fac : f ≫ g = P.σ) [weak_eq f] :\n precylinder A :=\nbegin\n haveI := weak_eq.of_comp_left f g infer_instance (by {rw fac, apply_instance, }),\n exact\n { I := I',\n d₀ := P.d₀ ≫ f,\n d₁ := P.d₁ ≫ f,\n σ := g,\n σd₀' := by { simp only [assoc, fac, σd₀], },\n σd₁' := by { simp only [assoc, fac, σd₁], }, },\nend\n\n@[simp]\ndef ι := coprod.desc P.d₀ P.d₁\n\n@[simps]\ndef symm : precylinder A :=\n{ I := P.I,\n d₀ := P.d₁,\n d₁ := P.d₀,\n σ := P.σ, }\n\nend precylinder\n\nstructure cylinder extends precylinder A :=\n[cof_ι : cofibration to_precylinder.ι]\n\nnamespace cylinder\n\nvariable {A}\n\ndef mk' (P : precylinder A) (h : cofibration P.ι) : cylinder A :=\nby { haveI := h, exact mk P, }\n\nabbreviation pre (Q : cylinder A) := Q.to_precylinder\n\ninstance cof_ι' (Q : cylinder A) : cofibration Q.pre.ι := Q.cof_ι\n\nvariable (A)\n\ndef some : cylinder A :=\nbegin\n let φ := coprod.desc (𝟙 A) (𝟙 A),\n let P : precylinder A :=\n { I := CM5b.obj φ,\n σ := CM5b.p φ,\n d₀ := coprod.inl ≫ CM5b.i φ,\n d₁ := coprod.inr ≫ CM5b.i φ, },\n apply mk' P,\n rw [show P.ι = CM5b.i φ, by tidy],\n apply_instance,\nend\n\ninstance : fibration (some A).σ := by { dsimp [some, mk'], apply_instance, }\ninstance [is_fibrant A] : is_fibrant (some A).I := by { dsimp [some, mk'], apply_instance, }\n\ninstance : inhabited (cylinder A) := ⟨some A⟩\ninstance : inhabited (precylinder A) := ⟨(some A).pre⟩\n\nvariables {A} (Q : cylinder A)\n\ninstance cof_d₀ [is_cofibrant A] : cofibration (Q.d₀) :=\nbegin\n rw [show Q.d₀ = coprod.inl ≫ Q.pre.ι, by simp only [precylinder.ι, coprod.inl_desc]],\n apply_instance,\nend\n\ninstance cof_d₁ [is_cofibrant A] : cofibration (Q.d₁) :=\nbegin\n rw [show Q.d₁ = coprod.inr ≫ Q.pre.ι, by simp only [precylinder.ι, coprod.inr_desc]],\n apply_instance,\nend\n\ninstance is_cofibrant_I [is_cofibrant A] : is_cofibrant Q.I :=\nbegin\n change cofibration _,\n rw subsingleton.elim (initial.to Q.I) (initial.to A ≫ Q.d₀),\n apply_instance,\nend\n\n@[simps]\ndef symm : cylinder A := mk' Q.pre.symm\nbegin\n have eq : Q.pre.symm.ι = (coprod.braiding A A).hom ≫ Q.pre.ι,\n { simp only [precylinder.ι, precylinder.symm_d₀, precylinder.symm_d₁, coprod.braiding_hom,\n coprod.desc_comp, coprod.inr_desc, coprod.inl_desc], },\n rw eq,\n apply_instance,\nend\n\n@[simps]\ndef trans [is_cofibrant A] (Q Q' : cylinder A) : cylinder A :=\nbegin\n let φ := pushout.desc Q.σ Q'.σ (by rw [Q.pre.σd₁, Q'.pre.σd₀]),\n haveI : weak_eq φ,\n { apply weak_eq.of_comp_left (Q.d₀ ≫ pushout.inl),\n { apply_instance, },\n { simp only [assoc, pushout.inl_desc, precylinder.σd₀],\n apply_instance, }, },\n let P : precylinder A :=\n { I := pushout Q.d₁ Q'.d₀,\n d₀ := Q.d₀ ≫ pushout.inl,\n d₁ := Q'.d₁ ≫ pushout.inr,\n σ := φ, },\n apply mk' P,\n let ψ : Q.pre.I ⨿ A ⟶ P.I := coprod.desc pushout.inl (Q'.d₁ ≫ pushout.inr),\n have eq : P.ι = (coprod.map Q.d₀ (𝟙 A)) ≫ ψ,\n { by simp only [precylinder.ι, coprod.map_desc, id_comp], },\n rw eq,\n have fac : coprod.map Q.d₁ (𝟙 A) ≫ ψ = Q'.pre.ι ≫ pushout.inr,\n { dsimp [ψ],\n ext,\n { simp only [coprod.map_desc, coprod.inl_desc, coprod.desc_comp, pushout.condition], },\n { simp only [coprod.map_desc, id_comp, coprod.inr_desc, coprod.desc_comp], }, },\n have sq : is_pushout Q.pre.d₁ (coprod.inl ≫ Q'.pre.ι)\n (coprod.inl ≫ ψ) pushout.inr := by simpa only [precylinder.ι, coprod.inl_desc]\n using is_pushout.of_has_pushout Q.pre.d₁ Q'.pre.d₀,\n haveI : cofibration ψ := cofibration.direct_image\n (is_pushout.of_bot sq fac (is_pushout.of_coprod_inl_with_id Q.d₁ A).flip),\n apply_instance,\nend\n\nend cylinder\n\nstructure pre_path_object :=\n(I : C) (d₀ d₁: I ⟶ B) (σ : B ⟶ I) [weq_σ : weak_eq σ]\n(d₀σ' : σ ≫ d₀ = 𝟙 B . obviously) (d₁σ' : σ ≫ d₁ = 𝟙 B . obviously)\n\nnamespace pre_path_object\n\nrestate_axiom d₀σ'\nrestate_axiom d₁σ'\nattribute [simp, reassoc] d₀σ d₁σ\n\nvariables {B} (P : pre_path_object B)\n\ninstance : weak_eq P.σ := P.weq_σ\n\n@[simps]\ndef op (P : pre_path_object B) : precylinder (op B) :=\nbegin\n haveI : weak_eq P.σ.op := weak_eq.op infer_instance,\n exact\n { I := op P.I,\n d₀ := P.d₀.op,\n d₁ := P.d₁.op,\n σ := P.σ.op,\n σd₀' := by simp only [← op_comp, d₀σ, op_id],\n σd₁' := by simp only [← op_comp, d₁σ, op_id], }\nend\n\n@[simps]\ndef unop {B : Cᵒᵖ} (P : pre_path_object B) : precylinder B.unop :=\nbegin\n haveI : weak_eq P.σ.unop := weak_eq.unop infer_instance,\n exact\n { I := unop P.I,\n d₀ := P.d₀.unop,\n d₁ := P.d₁.unop,\n σ := P.σ.unop,\n σd₀' := by simp only [← unop_comp, d₀σ, unop_id],\n σd₁' := by simp only [← unop_comp, d₁σ, unop_id], }\nend\n\nend pre_path_object\n\nnamespace precylinder\n\nvariable {A}\n\n@[simps]\ndef op (P : precylinder A) : pre_path_object (op A) :=\nbegin\n haveI : weak_eq P.σ.op := weak_eq.op infer_instance,\n exact\n { I := op P.I,\n d₀ := P.d₀.op,\n d₁ := P.d₁.op,\n σ := P.σ.op,\n d₀σ' := by simp only [← op_comp, σd₀, op_id],\n d₁σ' := by simp only [← op_comp, σd₁, op_id], }\nend\n\n@[simps]\ndef unop {A : Cᵒᵖ} (P : precylinder A) : pre_path_object (unop A) :=\nbegin\n haveI : weak_eq P.σ.unop := weak_eq.unop infer_instance,\n exact\n { I := unop P.I,\n d₀ := P.d₀.unop,\n d₁ := P.d₁.unop,\n σ := P.σ.unop,\n d₀σ' := by simp only [← unop_comp, σd₀, unop_id],\n d₁σ' := by simp only [← unop_comp, σd₁, unop_id], }\nend\n\nlemma unop_op (P : precylinder A) : P.op.unop = P := by { cases P, refl, }\nlemma op_unop {A : Cᵒᵖ} (P : precylinder A) : P.unop.op = P := by { cases P, refl, }\n\nend precylinder\n\nnamespace pre_path_object\n\nvariables {B} (P : pre_path_object B)\n\nlemma unop_op : P.op.unop = P := by { cases P, refl, }\nlemma op_unop {B : Cᵒᵖ} (P : precylinder B) : P.unop.op = P := by { cases P, refl, }\n\ninstance weq_d₀ : weak_eq P.d₀ := weak_eq.unop (infer_instance : weak_eq P.op.d₀)\ninstance weq_d₁ : weak_eq P.d₁ := weak_eq.unop (infer_instance : weak_eq P.op.d₁)\n\n@[simps]\ndef change_I {I' : C} {f : I' ⟶ P.I} {g : B ⟶ I'} (fac : g ≫ f = P.σ) [weak_eq f] :\n pre_path_object B :=\nbegin\n haveI : weak_eq f.op := weak_eq.op infer_instance,\n have eq : f.op ≫ g.op = P.σ.op := by rw [← op_comp, fac],\n exact (P.op.change_I eq).unop,\nend\n\n@[simp]\ndef π := prod.lift P.d₀ P.d₁\n\nlemma fibration_π_iff_cofibration_op_ι (P : pre_path_object B) :\n fibration P.π ↔ cofibration P.op.ι :=\nby simpa only [fibration.iff_op]\n using cofibration.respects_iso _ _ (arrow.iso_op_prod_lift P.d₀ P.d₁)\n\nlemma fibration_π_iff_cofibration_unop_ι {B : Cᵒᵖ} (P : pre_path_object B) :\n fibration P.π ↔ cofibration P.unop.ι :=\nby simpa only [fibration.iff_unop]\n using cofibration.respects_iso _ _ (arrow.iso_unop_prod_lift P.d₀ P.d₁)\n\n@[simps]\ndef symm : pre_path_object B :=\n{ I := P.I,\n d₀ := P.d₁,\n d₁ := P.d₀,\n σ := P.σ, }\n\nend pre_path_object\n\nstructure path_object extends pre_path_object B :=\n[fib_π : fibration to_pre_path_object.π]\n\nnamespace path_object\n\nvariable {B}\n\ndef mk' (P : pre_path_object B) (h : fibration P.π) : path_object B :=\nby { haveI := h, exact mk P, }\n\nabbreviation pre (Q : path_object B) := Q.to_pre_path_object\n\ninstance (Q : path_object B) : fibration Q.pre.π := Q.fib_π\n\n@[simps]\ndef change_I {B : C} (P : path_object B) {Z : C} {f : B ⟶ Z} {g : Z ⟶ P.I}\n (fac : f ≫ g = P.σ) [fibration g] [weak_eq g] : path_object B :=\nbegin\n haveI : fibration (P.pre.change_I fac).π,\n { convert (infer_instance : fibration (g ≫ P.π)),\n simp only [pre_path_object.π, pre_path_object.change_I_d₀,\n pre_path_object.change_I_d₁, prod.comp_lift], },\n exact path_object.mk (P.pre.change_I fac),\nend\n\nend path_object\n\nnamespace cylinder\n\n@[simps]\ndef unop {A : Cᵒᵖ} (Q : cylinder A) : path_object A.unop :=\nbegin\n apply path_object.mk' Q.pre.unop,\n rw [pre_path_object.fibration_π_iff_cofibration_op_ι, precylinder.op_unop],\n apply_instance,\nend\n\nvariable {A}\n\n@[simps]\ndef op (Q : cylinder A) : path_object (op A) :=\nbegin\n apply path_object.mk' Q.pre.op,\n rw [pre_path_object.fibration_π_iff_cofibration_unop_ι, precylinder.unop_op],\n apply_instance,\nend\n\nend cylinder\n\nnamespace path_object\n\nvariable {B}\n\n@[simps]\ndef op (Q : path_object B) : cylinder (op B) :=\nbegin\n apply cylinder.mk' Q.pre.op,\n rw ← Q.pre.fibration_π_iff_cofibration_op_ι,\n apply_instance,\nend\n\n@[simps]\ndef unop {B : Cᵒᵖ} (Q : path_object B) : cylinder B.unop :=\nbegin\n apply cylinder.mk' Q.pre.unop,\n rw ← Q.pre.fibration_π_iff_cofibration_unop_ι,\n apply_instance,\nend\n\nvariable (B)\n\ndef some : path_object B := (cylinder.some (opposite.op B)).unop\n\ninstance : cofibration (some B).σ := by { dsimp [some], apply fibration.unop, apply_instance, }\ninstance [is_cofibrant B] : is_cofibrant (some B).I :=\nbegin\n change cofibration _,\n rw subsingleton.elim (initial.to ((some B).I)) (initial.to _ ≫ (some B).σ),\n apply_instance,\nend\n\ninstance : inhabited (path_object B) := ⟨some B⟩\ninstance : inhabited (pre_path_object B) := ⟨(some B).pre⟩\n\nvariable {B}\n\n@[simp]\ndef symm (P : path_object B) : path_object B := P.op.symm.unop\n\n@[simps]\ndef trans [hB : is_fibrant B] (P P' : path_object B) : path_object B :=\nby { haveI := hB.op, exact (P.op.trans P'.op).unop, }\n/- TODO : use change_I to replace the dual of the pushout by a pullback -/\n\nend path_object\n\nend model_category\n\nend algebraic_topology\n", "meta": {"author": "joelriou", "repo": "homotopical_algebra", "sha": "697f49d6744b09c5ef463cfd3e35932bdf2c78a3", "save_path": "github-repos/lean/joelriou-homotopical_algebra", "path": "github-repos/lean/joelriou-homotopical_algebra/homotopical_algebra-697f49d6744b09c5ef463cfd3e35932bdf2c78a3/src/for_mathlib/algebraic_topology/homotopical_algebra/cylinder.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38491215859561845, "lm_q2_score": 0.029760093085439136, "lm_q1q2_score": 0.011455021669522917}} {"text": "-- lemmas about substitution\n\nimport .definitions3 .freevars .others\n\nlemma env.contains.inv {σ: env} {x y: var} {v: value}: x ∈ (σ[y↦v]) → (x = y ∨ x ∈ σ) :=\n assume x_in: x ∈ (σ[y↦v]),\n show x = y ∨ x ∈ σ, by { cases x_in, left, refl, right, from a }\n\nlemma env.contains.same.inv {σ: env} {x y: var} {v: value}: x ∉ (σ[y↦v]) → ¬ (x = y ∨ x ∈ σ) :=\n assume x_not_in: x ∉ (σ[y↦v]),\n assume : (x = y ∨ x ∈ σ),\n this.elim (\n assume x_is_y: x = y,\n have x ∈ (σ[x↦v]), from env.contains.same,\n have x ∈ (σ[y↦v]), from @eq.subst var (λa, x ∈ (σ[a↦v])) x y x_is_y this,\n show «false», from x_not_in this\n ) (\n assume : x ∈ σ,\n have x ∈ (σ[y↦v]), from env.contains.rest this,\n show «false», from x_not_in this\n )\n\nlemma env.contains_apply_equiv {σ: env} {x: var}:\n ((σ x = none) ↔ (x ∉ σ)) ∧ ((∃v, σ x = some v) ↔ (x ∈ σ)) :=\nbegin\n induction σ with σ' y v' ih,\n show ((env.empty x = none) ↔ (x ∉ env.empty)) ∧ ((∃v, env.empty x = some v) ↔ (x ∈ env.empty)), by begin\n split,\n show (env.empty x = none) ↔ (x ∉ env.empty), by begin\n split,\n show (env.empty x = none) → (x ∉ env.empty), by begin\n assume : (env.empty x = none),\n by_contradiction h,\n cases h\n end,\n show (x ∉ env.empty) → (env.empty x = none), by begin\n assume : (x ∉ env.empty),\n have : (env.apply env.empty x = none), by unfold env.apply,\n show (env.empty x = none), from this\n end\n end,\n show (∃v, env.empty x = some v) ↔ (x ∈ env.empty), by begin\n split,\n show (∃v, env.empty x = some v) → (x ∈ env.empty), from (\n assume : (∃v, env.empty x = some v),\n let (⟨v, h0⟩) := this in\n have h1: env.apply env.empty x = some v, from h0,\n have h2: env.apply env.empty x = none, by unfold env.apply,\n have some v = none, from eq.trans h1.symm h2,\n show (x ∈ env.empty), by contradiction\n ),\n show (x ∈ env.empty) → (∃v,env.empty x = some v), by begin\n assume h: x ∈ env.empty,\n cases h\n end\n end\n end,\n show (((σ'[y↦v']) x = none) ↔ (x ∉ (σ'[y↦v']))) ∧ ((∃v, (σ'[y↦v']) x = some v) ↔ (x ∈ (σ'[y↦v']))), by begin\n split,\n show (((σ'[y↦v']) x = none) ↔ (x ∉ (σ'[y↦v']))), by begin\n split,\n show (((σ'[y↦v']) x = none) → (x ∉ (σ'[y↦v']))), by begin\n assume h: ((σ'[y↦v']) x = none),\n have h2: (env.apply (σ'[y↦v']) x = (if y = x ∧ option.is_none (σ'.apply x) then v' else σ'.apply x)),\n by unfold env.apply,\n have h3: ((if y = x ∧ option.is_none (σ'.apply x) then ↑v' else σ'.apply x) = none),\n from eq.trans h2.symm h,\n have h4: (σ'.apply x = none), by begin\n by_cases (y = x ∧ option.is_none (σ'.apply x)),\n show (σ'.apply x = none), by begin\n have : ((if y = x ∧ option.is_none (σ'.apply x) then ↑v' else σ'.apply x) = ↑v'),\n by simp[h],\n have : (none = ↑v'), from eq.trans h3.symm this,\n contradiction\n end,\n show (σ'.apply x = none), by begin\n have : ((if y = x ∧ option.is_none (σ'.apply x) then ↑v' else σ'.apply x) = σ'.apply x),\n by simp[h],\n show (σ'.apply x = none), from eq.trans this.symm h3\n end\n end,\n have : x ∉ σ', from ih.left.mp h4,\n have h5: ¬ (x = y), by begin\n by_contradiction,\n have h6: (option.is_none (σ'.apply x) = tt), from option.is_none.inv.mp h4,\n have : (y = x ∧ option.is_none (σ'.apply x)), from ⟨a.symm, h6⟩,\n have : ((if y = x ∧ option.is_none (σ'.apply x) then ↑v' else σ'.apply x) = ↑v'),\n by simp[this],\n have : (none = ↑v'), from eq.trans h3.symm this,\n contradiction\n end,\n by_contradiction a,\n cases a,\n case env.contains.same x_is_x {\n contradiction\n },\n case env.contains.rest x_is_x {\n contradiction\n }\n end,\n show (x ∉ (σ'[y↦v'])) → (((σ'[y↦v']) x = none)), by begin\n assume : (x ∉ (σ'[y↦v'])),\n have h7: ¬ (x = y ∨ x ∈ σ'), from env.contains.same.inv this,\n have : x ≠ y, from (not_or_distrib.mp h7).left,\n have h8: y ≠ x, from ne.symm this,\n have h9: x ∉ σ', from (not_or_distrib.mp h7).right,\n have h10: (σ'.apply x = none), from ih.left.mpr h9,\n have h11: (env.apply (σ'[y↦v']) x = (if y = x ∧ option.is_none (σ'.apply x) then v' else σ'.apply x)),\n by unfold env.apply,\n have h12: ((if y = x ∧ option.is_none (σ'.apply x) then ↑v' else σ'.apply x) = σ'.apply x),\n by simp[h8],\n show ((σ'[y↦v']) x = none), from eq.trans (eq.trans h11 h12) h10\n end\n end,\n show ((∃v, (σ'[y↦v']) x = some v) ↔ (x ∈ (σ'[y↦v']))), by begin\n split,\n show ((∃v, (σ'[y↦v']) x = some v) → (x ∈ (σ'[y↦v']))), from (\n assume : (∃v, (σ'[y↦v']) x = some v),\n let ⟨v, h13⟩ := this in begin\n have h14: (env.apply (σ'[y↦v']) x = (if y = x ∧ option.is_none (σ'.apply x) then v' else σ'.apply x)),\n by unfold env.apply,\n by_cases (y = x ∧ option.is_none (σ'.apply x)) with h15,\n show (x ∈ (σ'[y↦v'])), by begin\n have x_is_y: (y = x), from h15.left,\n have : (x ∈ (σ'[x↦v'])), from env.contains.same,\n show x ∈ (σ'[y↦v']), from @eq.subst var (λa, x ∈ (σ'[a↦v'])) x y x_is_y.symm this\n end,\n show (x ∈ (σ'[y↦v'])), by begin\n have : ((if y = x ∧ option.is_none (σ'.apply x) then ↑v' else σ'.apply x) = σ'.apply x),\n by simp[h15],\n have : (σ'.apply x = v), from eq.trans (eq.trans this.symm h14.symm) h13,\n have : x ∈ σ', from ih.right.mp (exists.intro v this),\n show x ∈ (σ'[y↦v']), from env.contains.rest this\n end\n end),\n show (x ∈ (σ'[y↦v'])) → (∃v, (σ'[y↦v']) x = some v), by begin\n assume h16: (x ∈ (σ'[y↦v'])),\n have h17: (env.apply (σ'[y↦v']) x = (if y = x ∧ option.is_none (σ'.apply x) then v' else σ'.apply x)),\n by unfold env.apply,\n cases h16,\n case env.contains.same {\n by_cases (x = x ∧ option.is_none (σ'.apply x)),\n show (∃v, (σ'[x↦v']) x = some v), by begin\n have : ((if x = x ∧ option.is_none (σ'.apply x) then ↑v' else σ'.apply x) = v'),\n by { simp[h] },\n show (∃v, (σ'[x↦v']) x = some v), from exists.intro v' (eq.trans h17 this)\n end,\n show (∃v, (σ'[x↦v']) x = some v), by begin\n have h19: ¬option.is_none (σ'.apply x), by begin\n by_contradiction h18,\n have : (x = x ∧ option.is_none (σ'.apply x)), from ⟨rfl, h18⟩,\n exact h this\n end,\n have : ((option.is_some (σ'.apply x)):Prop), from option.some_iff_not_none.mpr h19,\n have : ∃v, (σ'.apply x) = some v, from option.is_some_iff_exists.mp this,\n cases this with v h20,\n have : ((if x = x ∧ option.is_none (σ'.apply x) then ↑v' else σ'.apply x) = σ'.apply x),\n by { simp[h], simp[h19] },\n show (∃v, (σ'[x↦v']) x = some v), from exists.intro v (eq.trans (eq.trans h17 this) h20)\n end\n },\n case env.contains.rest h27 {\n have : (∃v, σ'.apply x = some v), from ih.right.mpr h27,\n cases this with v h28,\n have : ¬ (option.is_none (σ'.apply x)),\n from option.some_iff_not_none.mp (option.is_some_iff_exists.mpr (exists.intro v h28)),\n have : ((if y = x ∧ option.is_none (σ'.apply x) then ↑v' else σ'.apply x) = σ'.apply x),\n by simp[this],\n show (∃v, (σ'[y↦v']) x = some v), from exists.intro v (eq.trans (eq.trans h17 this) h28)\n }\n end\n end\n end\nend\n\ninstance {σ: env} {x: var} : decidable (env.contains σ x) :=\n let r := env.apply σ x in\n have h: r = env.apply σ x, from rfl,\n @option.rec_on value (λa, (r = a) → decidable (env.contains σ x)) r\n (\n assume : r = none,\n have env.apply σ x = none, from eq.trans h this,\n have ¬ (x ∈ σ), from env.contains_apply_equiv.left.mp this,\n is_false this\n ) (\n assume v: value,\n assume : r = some v,\n have env.apply σ x = some v, from eq.trans h this,\n have ∃v, env.apply σ x = some v, from exists.intro v this,\n have x ∈ σ, from env.contains_apply_equiv.right.mp this,\n is_true this\n ) rfl\n\nlemma term.subst.congr {x: var} {v: value} {t₁ t₂: term}: (t₁ = t₂) → (term.subst x v t₁ = term.subst x v t₂) :=\n begin\n assume h1,\n congr,\n from h1\n end\n\nlemma env.contains_without.inv {σ: env} {x y: var}:\n (x ∈ σ.without y) → (x ≠ y) ∧ x ∈ σ :=\n begin\n assume h1,\n\n induction σ with σ' z v ih,\n unfold env.without at h1,\n cases h1,\n\n unfold env.without at h1,\n\n by_cases (z = y) with h2,\n\n simp[h2] at h1,\n have h3, from ih h1,\n split,\n from h3.left,\n apply env.contains.rest,\n from h3.right,\n\n simp[h2] at h1,\n have h3, from env.contains.inv h1,\n cases h3 with h4 h5,\n rw[h4],\n split,\n from h2,\n from env.contains.same,\n\n have h3, from ih h5,\n split,\n from h3.left,\n apply env.contains.rest,\n from h3.right\n end\n\nlemma env.contains_without.rinv {σ: env} {x y: var}:\n x ∈ σ ∧ (x ≠ y) → x ∈ σ.without y :=\n begin\n assume h1,\n\n induction σ with σ' z v ih,\n cases h1.left,\n\n unfold env.without,\n by_cases (z = y) with h2,\n\n simp[h2],\n have h3, from env.contains.inv h1.left,\n cases h3 with h4 h5,\n have : (x = y), from eq.trans h4 h2,\n have : (y ≠ y), from @eq.subst var (λa, a ≠ y) x y this h1.right,\n contradiction,\n\n from ih ⟨h5, h1.right⟩,\n\n simp[h2],\n have h3, from env.contains.inv h1.left,\n cases h3 with h4 h5,\n rw[h4],\n apply env.contains.same,\n\n apply env.contains.rest,\n from ih ⟨h5, h1.right⟩,\n end\n\nlemma env.without_equiv {σ: env} {x y: var} {v: value}:\n (x ∉ σ) ∨ (σ x = v) → (x ∉ σ.without y ∨ (σ.without y x = v)) :=\n begin\n assume h1,\n\n induction σ with σ' z v' ih,\n\n cases h1 with h2 h3,\n left,\n unfold env.without,\n assume h4,\n cases h4,\n\n cases h3,\n\n cases h1 with h2 h3,\n left,\n unfold env.without,\n by_cases (z = y) with h4,\n simp[h4],\n assume h5,\n have h6, from env.contains_without.inv h5,\n have : x ∈ (σ'[z↦v']), from env.contains.rest h6.right,\n contradiction,\n\n simp[h4],\n assume h5,\n have h6, from env.contains.inv h5,\n cases h6 with h7 h8,\n rw[h7] at h2,\n have : z ∈ (σ'[z↦v']), from env.contains.same,\n contradiction,\n\n have h9, from env.contains_without.inv h8,\n have : x ∈ (σ'[z↦v']), from env.contains.rest h9.right,\n contradiction,\n\n by_cases (x = y) with h4,\n left,\n unfold env.without,\n by_cases (z = y) with h5,\n simp[h5],\n rw[h4],\n assume h6,\n have h7, from env.contains_without.inv h6,\n have : ¬ (y = y), from h7.left,\n contradiction,\n \n simp[h5],\n assume h6,\n have h7, from env.contains.inv h6,\n cases h7 with h8 h9,\n have : (y = z), from eq.trans h4.symm h8,\n have : ¬ (z = z), from @eq.subst var (λa, ¬ (z = a)) y z this h5,\n contradiction,\n\n rw[h4] at h9,\n have h10, from env.contains_without.inv h9,\n have : ¬ (y = y), from h10.left,\n contradiction,\n\n right,\n have h5: (env.apply (σ'[z↦v']) x = some v), from h3,\n unfold env.apply at h5,\n by_cases (z = x ∧ (option.is_none (env.apply σ' x))) with h6,\n simp[h6] at h5,\n have : (some v' = some v), from h5,\n have h7: (v' = v), from option.some.inj this,\n have h8, from env.contains_apply_equiv.left.mp (option.is_none.inv.mpr h6.right),\n have h9, from ih (or.inl h8),\n\n let a' := ((env.without σ' y)[z↦v']),\n have h12: (env.without (σ'[z↦v']) y = (if z = y then (env.without σ' y) else a')),\n by unfold env.without,\n rw[h12],\n change ((ite (z = y) (env.without σ' y) a') x = ↑v),\n have : ¬ (z = y), from @eq.subst var (λa, ¬ (a = y)) x z h6.left.symm h4,\n have : (ite (z = y) (env.without σ' y) a'\n = ((env.without σ' y)[z↦v'])), by simp[this],\n have h13: (\n ((ite (z = y) (env.without σ' y) a') x = ↑v)\n = (((env.without σ' y)[z↦v']) x = ↑v)\n ), by rw[this],\n rw[h13],\n change (env.apply (env.without σ' y[z↦v']) x = ↑v),\n unfold env.apply,\n\n cases h9 with h10 h11,\n\n have h14, from env.contains_apply_equiv.left.mpr h10,\n have h15, from option.is_none.inv.mp h14,\n have h16: (z = x ∧ (option.is_none (env.apply (env.without σ' y) x))), from and.intro h6.left h15,\n simp[h16],\n from some.inj.inv h7,\n\n have h14, from option.is_some_iff_exists.mpr (exists.intro v h11),\n have h15, from option.some_iff_not_none.mp h14,\n have h16: ¬ (z = x ∧ option.is_none (env.apply (env.without σ' y) x)),\n from not_and_distrib.mpr (or.inr h15),\n simp[h16],\n from h11,\n\n simp[h6] at h5,\n let a' := ((env.without σ' y)[z↦v']),\n have h7: (env.without (σ'[z↦v']) y = (if z = y then (env.without σ' y) else a')),\n by unfold env.without,\n rw[h7],\n\n by_cases (z = y) with h8,\n have : (ite (z = y) (env.without σ' y) ((env.without σ' y)[z↦v'])\n = (env.without σ' y)), by simp[h8],\n rw[this],\n have h8, from ih (or.inr h5),\n cases h8 with h9 h10,\n\n have : x ∈ σ', from env.contains_apply_equiv.right.mp (exists.intro v h5),\n have h9: x ∈ env.without σ' y,\n from env.contains_without.rinv ⟨this, h4⟩,\n contradiction,\n\n from h10,\n\n have : (ite (z = y) (env.without σ' y) ((env.without σ' y)[z↦v'])\n = ((env.without σ' y)[z↦v'])), by simp[h8],\n rw[this],\n change (env.apply ((env.without σ' y)[z↦v']) x = ↑v),\n unfold env.apply,\n\n have h10b: x ∈ σ', from env.contains_apply_equiv.right.mp (exists.intro v h5),\n have h11: x ∈ env.without σ' y,\n from env.contains_without.rinv ⟨h10b, h4⟩,\n have h12, from env.contains_apply_equiv.right.mpr h11,\n have h13, from option.is_some_iff_exists.mpr h12,\n have h14, from option.some_iff_not_none.mp h13,\n have h15: ¬ (z = x ∧ option.is_none (env.apply (env.without σ' y) x)),\n from not_and_distrib.mpr (or.inr h14),\n simp[h15],\n have h16, from ih (or.inr h5),\n cases h16 with h17 h18,\n contradiction,\n from h18\n end\n\nlemma env.not_in_without {σ: env} {x y: var}: x ∉ σ → x ∉ σ.without y :=\n begin\n assume h1,\n\n induction σ with σ' z v' ih,\n\n unfold env.without,\n assume h4,\n cases h4,\n\n unfold env.without,\n by_cases (z = y) with h4,\n simp[h4],\n assume h5,\n have h6, from env.contains_without.inv h5,\n have : x ∈ (σ'[z↦v']), from env.contains.rest h6.right,\n contradiction,\n\n simp[h4],\n assume h5,\n have h6, from env.contains.inv h5,\n cases h6 with h7 h8,\n rw[h7] at h1,\n have : z ∈ (σ'[z↦v']), from env.contains.same,\n contradiction,\n\n have h9, from env.contains_without.inv h8,\n have : x ∈ (σ'[z↦v']), from env.contains.rest h9.right,\n contradiction\n end\n\nlemma env.not_contains_without {σ: env} {x: var}: x ∉ σ.without x :=\n assume : x ∈ σ.without x,\n have (x ≠ x) ∧ x ∈ σ, from env.contains_without.inv this,\n show «false», from this.left (eq.refl x)\n\nlemma env.without_equiv_with {σ: env} {x: var}: ∀y, y ∈ σ.without x → (σ.without x y = σ y) :=\n assume y: var,\n assume h1: y ∈ σ.without x,\n have y ≠ x ∧ y ∈ σ, from env.contains_without.inv h1,\n have ∃v: value, σ y = v, from env.contains_apply_equiv.right.mpr this.right,\n let ⟨v, σ_y_is_v⟩ := this in\n have y ∉ σ.without x ∨ (σ.without x y = v), from env.without_equiv (or.inr σ_y_is_v),\n or.elim this (\n assume : y ∉ σ.without x,\n show σ.without x y = σ y, from absurd h1 this\n ) (\n assume : σ.without x y = v,\n show σ.without x y = σ y, from eq.trans this σ_y_is_v.symm\n )\n\nlemma env.without_nonexisting {σ: env} {x: var}: x ∉ σ → (σ.without x = σ) :=\n begin\n assume h1,\n\n induction σ with σ' z v' ih,\n\n unfold env.without,\n\n unfold env.without,\n have h2: (z ≠ x), by begin\n assume h3,\n rw[h3] at h1,\n have h4: x ∈ (σ'[x↦v']), from env.contains.same,\n contradiction\n end,\n simp[h2],\n congr,\n apply ih,\n by_contradiction h3,\n have h4: x ∈ (σ'[z↦v']), from env.contains.rest h3,\n contradiction\n end\n\nlemma unchanged_of_subst_nonfree_term {t: term} {x: var} {v: value}:\n x ∉ FV t → (term.subst x v t = t) :=\n assume x_not_free: ¬ free_in_term x t,\n begin\n induction t with v' y unop t₁ t₁_ih binop t₂ t₃ t₂_ih t₃_ih t₄ t₅ t₄_ih t₅_ih,\n show (term.subst x v (term.value v') = ↑v'), by unfold term.subst,\n show (term.subst x v (term.var y) = (term.var y)), from (\n have h: term.subst x v (term.var y) = (if x = y then v else y), by unfold term.subst,\n if x_is_y: x = y then (\n have free_in_term y (term.var y), from free_in_term.var y,\n have free_in_term x (term.var y), from x_is_y.symm ▸ this,\n show term.subst x v (term.var y) = y, from absurd this x_not_free\n ) else (\n show term.subst x v (term.var y) = y, by { simp[x_is_y] at h, assumption }\n )\n ),\n show (term.subst x v (term.unop unop t₁) = term.unop unop t₁), from (\n have h: term.subst x v (term.unop unop t₁) = term.unop unop (term.subst x v t₁), by unfold term.subst,\n have ¬ free_in_term x t₁, from (\n assume : free_in_term x t₁,\n have free_in_term x (term.unop unop t₁), from free_in_term.unop this,\n show «false», from x_not_free this\n ),\n have term.subst x v t₁ = t₁, from t₁_ih this,\n show term.subst x v (term.unop unop t₁) = term.unop unop t₁,\n from @eq.subst term (λa, term.subst x v (term.unop unop t₁) = term.unop unop a) (term.subst x v t₁) t₁ this h\n ),\n show (term.subst x v (term.binop binop t₂ t₃) = term.binop binop t₂ t₃), from (\n have h: term.subst x v (term.binop binop t₂ t₃)\n = term.binop binop (term.subst x v t₂) (term.subst x v t₃), by unfold term.subst,\n have ¬ free_in_term x t₂, from (\n assume : free_in_term x t₂,\n have free_in_term x (term.binop binop t₂ t₃), from free_in_term.binop₁ this,\n show «false», from x_not_free this\n ),\n have t2_subst: term.subst x v t₂ = t₂, from t₂_ih this,\n have ¬ free_in_term x t₃, from (\n assume : free_in_term x t₃,\n have free_in_term x (term.binop binop t₂ t₃), from free_in_term.binop₂ this,\n show «false», from x_not_free this\n ),\n have t3_subst: term.subst x v t₃ = t₃, from t₃_ih this,\n have term.subst x v (term.binop binop t₂ t₃) = term.binop binop t₂ (term.subst x v t₃),\n from @eq.subst term (λa, term.subst x v (term.binop binop t₂ t₃) = term.binop binop a (term.subst x v t₃))\n (term.subst x v t₂) t₂ t2_subst h,\n show term.subst x v (term.binop binop t₂ t₃) = term.binop binop t₂ t₃,\n from @eq.subst term (λa, term.subst x v (term.binop binop t₂ t₃) = term.binop binop t₂ a)\n (term.subst x v t₃) t₃ t3_subst this\n ),\n show (term.subst x v (term.app t₄ t₅) = term.app t₄ t₅), from (\n have h: term.subst x v (term.app t₄ t₅)\n = term.app (term.subst x v t₄) (term.subst x v t₅), by unfold term.subst,\n have ¬ free_in_term x t₄, from (\n assume : free_in_term x t₄,\n have free_in_term x (term.app t₄ t₅), from free_in_term.app₁ this,\n show «false», from x_not_free this\n ),\n have t4_subst: term.subst x v t₄ = t₄, from t₄_ih this,\n have ¬ free_in_term x t₅, from (\n assume : free_in_term x t₅,\n have free_in_term x (term.app t₄ t₅), from free_in_term.app₂ this,\n show «false», from x_not_free this\n ),\n have t5_subst: term.subst x v t₅ = t₅, from t₅_ih this,\n have term.subst x v (term.app t₄ t₅) = term.app t₄ (term.subst x v t₅),\n from @eq.subst term (λa, term.subst x v (term.app t₄ t₅) = term.app a (term.subst x v t₅))\n (term.subst x v t₄) t₄ t4_subst h,\n show term.subst x v (term.app t₄ t₅) = term.app t₄ t₅,\n from @eq.subst term (λa, term.subst x v (term.app t₄ t₅) = term.app t₄ a)\n (term.subst x v t₅) t₅ t5_subst this\n )\n end\n\nlemma unchanged_of_substt_nonfree_term {t: term} {x: var} {t': term}:\n x ∉ FV t → (term.substt x t' t = t) :=\n assume x_not_free: ¬ free_in_term x t,\n begin\n induction t with v y unop t₁ t₁_ih binop t₂ t₃ t₂_ih t₃_ih t₄ t₅ t₄_ih t₅_ih,\n show (term.substt x t' (term.value v) = ↑v), by unfold term.substt,\n show (term.substt x t' (term.var y) = (term.var y)), from (\n have h: term.substt x t' (term.var y) = (if x = y then t' else y), by unfold term.substt,\n if x_is_y: x = y then (\n have free_in_term y (term.var y), from free_in_term.var y,\n have free_in_term x (term.var y), from x_is_y.symm ▸ this,\n show term.substt x t' (term.var y) = y, from absurd this x_not_free\n ) else (\n show term.substt x t' (term.var y) = y, by { simp[x_is_y] at h, assumption }\n )\n ),\n show (term.substt x t' (term.unop unop t₁) = term.unop unop t₁), from (\n have h: term.substt x t' (term.unop unop t₁) = term.unop unop (term.substt x t' t₁), by unfold term.substt,\n have ¬ free_in_term x t₁, from (\n assume : free_in_term x t₁,\n have free_in_term x (term.unop unop t₁), from free_in_term.unop this,\n show «false», from x_not_free this\n ),\n have term.substt x t' t₁ = t₁, from t₁_ih this,\n show term.substt x t' (term.unop unop t₁) = term.unop unop t₁,\n from @eq.subst term (λa, term.substt x t' (term.unop unop t₁) = term.unop unop a) (term.substt x t' t₁) t₁ this h\n ),\n show (term.substt x t' (term.binop binop t₂ t₃) = term.binop binop t₂ t₃), from (\n have h: term.substt x t' (term.binop binop t₂ t₃)\n = term.binop binop (term.substt x t' t₂) (term.substt x t' t₃), by unfold term.substt,\n have ¬ free_in_term x t₂, from (\n assume : free_in_term x t₂,\n have free_in_term x (term.binop binop t₂ t₃), from free_in_term.binop₁ this,\n show «false», from x_not_free this\n ),\n have t2_substt: term.substt x t' t₂ = t₂, from t₂_ih this,\n have ¬ free_in_term x t₃, from (\n assume : free_in_term x t₃,\n have free_in_term x (term.binop binop t₂ t₃), from free_in_term.binop₂ this,\n show «false», from x_not_free this\n ),\n have t3_substt: term.substt x t' t₃ = t₃, from t₃_ih this,\n have term.substt x t' (term.binop binop t₂ t₃) = term.binop binop t₂ (term.substt x t' t₃),\n from @eq.subst term (λa, term.substt x t' (term.binop binop t₂ t₃) = term.binop binop a (term.substt x t' t₃))\n (term.substt x t' t₂) t₂ t2_substt h,\n show term.substt x t' (term.binop binop t₂ t₃) = term.binop binop t₂ t₃,\n from @eq.subst term (λa, term.substt x t' (term.binop binop t₂ t₃) = term.binop binop t₂ a)\n (term.substt x t' t₃) t₃ t3_substt this\n ),\n show (term.substt x t' (term.app t₄ t₅) = term.app t₄ t₅), from (\n have h: term.substt x t' (term.app t₄ t₅)\n = term.app (term.substt x t' t₄) (term.substt x t' t₅), by unfold term.substt,\n have ¬ free_in_term x t₄, from (\n assume : free_in_term x t₄,\n have free_in_term x (term.app t₄ t₅), from free_in_term.app₁ this,\n show «false», from x_not_free this\n ),\n have t4_substt: term.substt x t' t₄ = t₄, from t₄_ih this,\n have ¬ free_in_term x t₅, from (\n assume : free_in_term x t₅,\n have free_in_term x (term.app t₄ t₅), from free_in_term.app₂ this,\n show «false», from x_not_free this\n ),\n have t5_substt: term.substt x t' t₅ = t₅, from t₅_ih this,\n have term.substt x t' (term.app t₄ t₅) = term.app t₄ (term.substt x t' t₅),\n from @eq.subst term (λa, term.substt x t' (term.app t₄ t₅) = term.app a (term.substt x t' t₅))\n (term.substt x t' t₄) t₄ t4_substt h,\n show term.substt x t' (term.app t₄ t₅) = term.app t₄ t₅,\n from @eq.subst term (λa, term.substt x t' (term.app t₄ t₅) = term.app t₄ a)\n (term.substt x t' t₅) t₅ t5_substt this\n )\n end\n\nlemma unchanged_of_subst_env_nonfree_term {t: term}:\n closed t → (∀σ, term.subst_env σ t = t) :=\n assume x_not_free: (∀x, x ∉ FV t),\n assume σ: env,\n begin\n induction σ with σ' x v ih,\n\n show (term.subst_env env.empty t = t), by unfold term.subst_env,\n\n show (term.subst_env (σ'[x↦v]) t = t), by calc\n term.subst_env (σ'[x↦v]) t = term.subst x v (term.subst_env σ' t) : by unfold term.subst_env\n ... = term.subst x v t : by rw[ih]\n ... = t : unchanged_of_subst_nonfree_term (x_not_free x)\n end\n\nlemma term.subst.var.same {x: var} {v: value}: term.subst x v x = v :=\n have h: term.subst x v (term.var x) = (if x = x then v else x), by unfold term.subst,\n have (if x = x then (term.value v) else (term.var x)) = (term.value v), by simp,\n show term.subst x v x = v, from eq.trans h this\n\nlemma term.subst.var.diff {x y: var} {v: value}: (x ≠ y) → (term.subst x v y = y) :=\n assume x_neq_y: x ≠ y,\n have h: term.subst x v (term.var y) = (if x = y then v else y), by unfold term.subst,\n have (if x = y then (term.value v) else (term.var y)) = (term.var y), by simp[x_neq_y],\n show term.subst x v y = y, from eq.trans h this\n\nlemma term.substt.var.diff {x y: var} {t: term}: (x ≠ y) → (term.substt x t y = y) :=\n assume x_neq_y: x ≠ y,\n have h: term.substt x t (term.var y) = (if x = y then t else y), by unfold term.substt,\n have (if x = y then t else (term.var y)) = (term.var y), by simp[x_neq_y],\n show term.substt x t y = y, from eq.trans h this\n\nlemma unchanged_of_subst_nonfree_prop {P: prop} {x: var} {v: value}:\n x ∉ FV P → (prop.subst x v P = P) :=\n assume x_not_free: ¬ free_in_prop x P,\n begin\n induction P,\n case prop.term t { from (\n have h: prop.subst x v (prop.term t) = term.subst x v t, by unfold prop.subst,\n have ¬ free_in_term x t, from (\n assume : free_in_term x t,\n have free_in_prop x (prop.term t), from free_in_prop.term this,\n show «false», from x_not_free this\n ),\n have term.subst x v t = t, from unchanged_of_subst_nonfree_term this,\n show prop.subst x v t = prop.term t,\n from @eq.subst term (λa, prop.subst x v (prop.term t) = prop.term a) (term.subst x v t) t this h\n )},\n case prop.not P₁ ih { from (\n have h: prop.subst x v P₁.not = (prop.subst x v P₁).not, by unfold prop.subst,\n have ¬ free_in_prop x P₁, from (\n assume : free_in_prop x P₁,\n have free_in_prop x P₁.not, from free_in_prop.not this,\n show «false», from x_not_free this\n ),\n have prop.subst x v P₁ = P₁, from ih this,\n show prop.subst x v P₁.not = P₁.not,\n from @eq.subst prop (λa, prop.subst x v P₁.not = prop.not a) (prop.subst x v P₁) P₁ this h\n )},\n case prop.and P₁ P₂ P₁_ih P₂_ih { from (\n have h: prop.subst x v (prop.and P₁ P₂) = (prop.subst x v P₁ ⋀ prop.subst x v P₂), by unfold prop.subst,\n have ¬ free_in_prop x P₁, from (\n assume : free_in_prop x P₁,\n have free_in_prop x (P₁ ⋀ P₂), from free_in_prop.and₁ this,\n show «false», from x_not_free this\n ),\n have h1: prop.subst x v P₁ = P₁, from P₁_ih this,\n have ¬ free_in_prop x P₂, from (\n assume : free_in_prop x P₂,\n have free_in_prop x (P₁ ⋀ P₂), from free_in_prop.and₂ this,\n show «false», from x_not_free this\n ),\n have h2: prop.subst x v P₂ = P₂, from P₂_ih this,\n have prop.subst x v (P₁ ⋀ P₂) = (P₁ ⋀ prop.subst x v P₂),\n from @eq.subst prop (λa, prop.subst x v (prop.and P₁ P₂) = (a ⋀ prop.subst x v P₂)) (prop.subst x v P₁) P₁ h1 h,\n show prop.subst x v (P₁ ⋀ P₂) = (P₁ ⋀ P₂),\n from @eq.subst prop (λa, prop.subst x v (prop.and P₁ P₂) = (P₁ ⋀ a)) (prop.subst x v P₂) P₂ h2 this\n )},\n case prop.or P₁ P₂ P₁_ih P₂_ih { from (\n have h: prop.subst x v (prop.or P₁ P₂) = (prop.subst x v P₁ ⋁ prop.subst x v P₂), by unfold prop.subst,\n have ¬ free_in_prop x P₁, from (\n assume : free_in_prop x P₁,\n have free_in_prop x (P₁ ⋁ P₂), from free_in_prop.or₁ this,\n show «false», from x_not_free this\n ),\n have h1: prop.subst x v P₁ = P₁, from P₁_ih this,\n have ¬ free_in_prop x P₂, from (\n assume : free_in_prop x P₂,\n have free_in_prop x (P₁ ⋁ P₂), from free_in_prop.or₂ this,\n show «false», from x_not_free this\n ),\n have h2: prop.subst x v P₂ = P₂, from P₂_ih this,\n have prop.subst x v (P₁ ⋁ P₂) = (P₁ ⋁ prop.subst x v P₂),\n from @eq.subst prop (λa, prop.subst x v (prop.or P₁ P₂) = (a ⋁ prop.subst x v P₂)) (prop.subst x v P₁) P₁ h1 h,\n show prop.subst x v (P₁ ⋁ P₂) = (P₁ ⋁ P₂),\n from @eq.subst prop (λa, prop.subst x v (prop.or P₁ P₂) = (P₁ ⋁ a)) (prop.subst x v P₂) P₂ h2 this\n )},\n case prop.pre t₁ t₂ { from (\n have h: prop.subst x v (prop.pre t₁ t₂) = prop.pre (term.subst x v t₁) (term.subst x v t₂), by unfold prop.subst,\n have ¬ free_in_term x t₁, from (\n assume : free_in_term x t₁,\n have free_in_prop x (prop.pre t₁ t₂), from free_in_prop.pre₁ this,\n show «false», from x_not_free this\n ),\n have h1: term.subst x v t₁ = t₁, from unchanged_of_subst_nonfree_term this,\n have ¬ free_in_term x t₂, from (\n assume : free_in_term x t₂,\n have free_in_prop x (prop.pre t₁ t₂), from free_in_prop.pre₂ this,\n show «false», from x_not_free this\n ),\n have h2: term.subst x v t₂ = t₂, from unchanged_of_subst_nonfree_term this,\n have prop.subst x v (prop.pre t₁ t₂) = prop.pre t₁ (term.subst x v t₂),\n from @eq.subst term (λa, prop.subst x v (prop.pre t₁ t₂) = prop.pre a (term.subst x v t₂)) (term.subst x v t₁) t₁ h1 h,\n show prop.subst x v (prop.pre t₁ t₂) = prop.pre t₁ t₂,\n from @eq.subst term (λa, prop.subst x v (prop.pre t₁ t₂) = prop.pre t₁ a) (term.subst x v t₂) t₂ h2 this\n )},\n case prop.pre₁ op t { from (\n have h: prop.subst x v (prop.pre₁ op t) = prop.pre₁ op (term.subst x v t), by unfold prop.subst,\n have ¬ free_in_term x t, from (\n assume : free_in_term x t,\n have free_in_prop x (prop.pre₁ op t), from free_in_prop.preop this,\n show «false», from x_not_free this\n ),\n have term.subst x v t = t, from unchanged_of_subst_nonfree_term this,\n show prop.subst x v (prop.pre₁ op t) = prop.pre₁ op t,\n from @eq.subst term (λa, prop.subst x v (prop.pre₁ op t) = prop.pre₁ op a) (term.subst x v t) t this h\n )},\n case prop.pre₂ op t₁ t₂ { from (\n have h: prop.subst x v (prop.pre₂ op t₁ t₂) = prop.pre₂ op (term.subst x v t₁) (term.subst x v t₂),\n by unfold prop.subst,\n have ¬ free_in_term x t₁, from (\n assume : free_in_term x t₁,\n have free_in_prop x (prop.pre₂ op t₁ t₂), from free_in_prop.preop₁ this,\n show «false», from x_not_free this\n ),\n have h1: term.subst x v t₁ = t₁, from unchanged_of_subst_nonfree_term this,\n have ¬ free_in_term x t₂, from (\n assume : free_in_term x t₂,\n have free_in_prop x (prop.pre₂ op t₁ t₂), from free_in_prop.preop₂ this,\n show «false», from x_not_free this\n ),\n have h2: term.subst x v t₂ = t₂, from unchanged_of_subst_nonfree_term this,\n have prop.subst x v (prop.pre₂ op t₁ t₂) = prop.pre₂ op t₁ (term.subst x v t₂),\n from @eq.subst term (λa, prop.subst x v (prop.pre₂ op t₁ t₂) = prop.pre₂ op a (term.subst x v t₂)) (term.subst x v t₁) t₁ h1 h,\n show prop.subst x v (prop.pre₂ op t₁ t₂) = prop.pre₂ op t₁ t₂,\n from @eq.subst term (λa, prop.subst x v (prop.pre₂ op t₁ t₂) = prop.pre₂ op t₁ a) (term.subst x v t₂) t₂ h2 this\n )},\n case prop.call t { from (\n have h: prop.subst x v (prop.call t) = prop.call (term.subst x v t), by unfold prop.subst,\n have ¬ free_in_term x t, from (\n assume : free_in_term x t,\n have free_in_prop x (prop.call t), from free_in_prop.call this,\n show «false», from x_not_free this\n ),\n have h1: term.subst x v t = t, from unchanged_of_subst_nonfree_term this,\n show prop.subst x v (prop.call t) = prop.call t,\n from @eq.subst term (λa, prop.subst x v (prop.call t) = prop.call a) (term.subst x v t) t h1 h\n )},\n case prop.post t₁ t₂ { from (\n have h: prop.subst x v (prop.post t₁ t₂) = prop.post (term.subst x v t₁) (term.subst x v t₂), by unfold prop.subst,\n have ¬ free_in_term x t₁, from (\n assume : free_in_term x t₁,\n have free_in_prop x (prop.post t₁ t₂), from free_in_prop.post₁ this,\n show «false», from x_not_free this\n ),\n have h1: term.subst x v t₁ = t₁, from unchanged_of_subst_nonfree_term this,\n have ¬ free_in_term x t₂, from (\n assume : free_in_term x t₂,\n have free_in_prop x (prop.post t₁ t₂), from free_in_prop.post₂ this,\n show «false», from x_not_free this\n ),\n have h2: term.subst x v t₂ = t₂, from unchanged_of_subst_nonfree_term this,\n have prop.subst x v (prop.post t₁ t₂) = prop.post t₁ (term.subst x v t₂),\n from @eq.subst term (λa, prop.subst x v (prop.post t₁ t₂) = prop.post a (term.subst x v t₂)) (term.subst x v t₁) t₁ h1 h,\n show prop.subst x v (prop.post t₁ t₂) = prop.post t₁ t₂,\n from @eq.subst term (λa, prop.subst x v (prop.post t₁ t₂) = prop.post t₁ a) (term.subst x v t₂) t₂ h2 this\n )},\n case prop.forallc y P' P'_ih { from (\n have h: prop.subst x v (prop.forallc y P')\n = prop.forallc y (if x = y then P' else prop.subst x v P'),\n by unfold prop.subst,\n\n if x_eq_y: x = y then (\n have (if x = y then P' else prop.subst x v P') = P', by simp[x_eq_y],\n show prop.subst x v (prop.forallc y P') = prop.forallc y P',\n from @eq.subst prop (λa, prop.subst x v (prop.forallc y P') = prop.forallc y a)\n (if x = y then P' else prop.subst x v P') P' this h\n ) else (\n have (if x = y then P' else prop.subst x v P') = prop.subst x v P', by simp[x_eq_y],\n have h4: prop.subst x v (prop.forallc y P') = prop.forallc y (prop.subst x v P'),\n from @eq.subst prop (λa, prop.subst x v (prop.forallc y P') = prop.forallc y a)\n (if x = y then P' else prop.subst x v P') (prop.subst x v P') this h,\n have ¬ free_in_prop x P', from (\n assume : free_in_prop x P',\n have free_in_prop x (prop.forallc y P'), from free_in_prop.forallc x_eq_y this,\n show «false», from x_not_free this\n ),\n have prop.subst x v P' = P', from P'_ih this,\n show prop.subst x v (prop.forallc y P') = prop.forallc y P',\n from @eq.subst prop (λa, prop.subst x v (prop.forallc y P')\n = prop.forallc y a) (prop.subst x v P') P' this h4\n )\n )},\n case prop.exis y P' P'_ih { from (\n have h: prop.subst x v (prop.exis y P') = prop.exis y (if x = y then P' else prop.subst x v P'), by unfold prop.subst,\n if x_eq_y: x = y then (\n have (if x = y then P' else prop.subst x v P') = P', by simp[x_eq_y],\n show prop.subst x v (prop.exis y P') = prop.exis y P',\n from @eq.subst prop (λa, prop.subst x v (prop.exis y P') = prop.exis y a)\n (if x = y then P' else prop.subst x v P') P' this h\n ) else (\n have (if x = y then P' else prop.subst x v P') = prop.subst x v P', by simp[x_eq_y],\n have h2: prop.subst x v (prop.exis y P') = prop.exis y (prop.subst x v P'),\n from @eq.subst prop (λa, prop.subst x v (prop.exis y P') = prop.exis y a)\n (if x = y then P' else prop.subst x v P') (prop.subst x v P') this h,\n have ¬ free_in_prop x P', from (\n assume : free_in_prop x P',\n have free_in_prop x (prop.exis y P'), from free_in_prop.exis x_eq_y this,\n show «false», from x_not_free this\n ),\n have prop.subst x v P' = P', from P'_ih this,\n show prop.subst x v (prop.exis y P') = prop.exis y P',\n from @eq.subst prop (λa, prop.subst x v (prop.exis y P') = prop.exis y a) (prop.subst x v P') P' this h2\n )\n )}\n end\n\nlemma unchanged_of_subst_nonfree_vc {P: vc} {x: var} {v: value}:\n x ∉ FV P → (vc.subst x v P = P) :=\n assume x_not_free: ¬ free_in_vc x P,\n begin\n induction P,\n case vc.term t { from (\n have h: vc.subst x v (vc.term t) = term.subst x v t, by unfold vc.subst,\n have ¬ free_in_term x t, from (\n assume : free_in_term x t,\n have free_in_vc x (vc.term t), from free_in_vc.term this,\n show «false», from x_not_free this\n ),\n have term.subst x v t = t, from unchanged_of_subst_nonfree_term this,\n show vc.subst x v t = vc.term t,\n from @eq.subst term (λa, vc.subst x v (vc.term t) = vc.term a) (term.subst x v t) t this h\n )},\n case vc.not P₁ ih { from (\n have h: vc.subst x v P₁.not = (vc.subst x v P₁).not, by unfold vc.subst,\n have ¬ free_in_vc x P₁, from (\n assume : free_in_vc x P₁,\n have free_in_vc x P₁.not, from free_in_vc.not this,\n show «false», from x_not_free this\n ),\n have vc.subst x v P₁ = P₁, from ih this,\n show vc.subst x v P₁.not = P₁.not,\n from @eq.subst vc (λa, vc.subst x v P₁.not = vc.not a) (vc.subst x v P₁) P₁ this h\n )},\n case vc.and P₁ P₂ P₁_ih P₂_ih { from (\n have h: vc.subst x v (vc.and P₁ P₂) = (vc.subst x v P₁ ⋀ vc.subst x v P₂), by unfold vc.subst,\n have ¬ free_in_vc x P₁, from (\n assume : free_in_vc x P₁,\n have free_in_vc x (P₁ ⋀ P₂), from free_in_vc.and₁ this,\n show «false», from x_not_free this\n ),\n have h1: vc.subst x v P₁ = P₁, from P₁_ih this,\n have ¬ free_in_vc x P₂, from (\n assume : free_in_vc x P₂,\n have free_in_vc x (P₁ ⋀ P₂), from free_in_vc.and₂ this,\n show «false», from x_not_free this\n ),\n have h2: vc.subst x v P₂ = P₂, from P₂_ih this,\n have vc.subst x v (P₁ ⋀ P₂) = (P₁ ⋀ vc.subst x v P₂),\n from @eq.subst vc (λa, vc.subst x v (vc.and P₁ P₂) = (a ⋀ vc.subst x v P₂)) (vc.subst x v P₁) P₁ h1 h,\n show vc.subst x v (P₁ ⋀ P₂) = (P₁ ⋀ P₂),\n from @eq.subst vc (λa, vc.subst x v (vc.and P₁ P₂) = (P₁ ⋀ a)) (vc.subst x v P₂) P₂ h2 this\n )},\n case vc.or P₁ P₂ P₁_ih P₂_ih { from (\n have h: vc.subst x v (vc.or P₁ P₂) = (vc.subst x v P₁ ⋁ vc.subst x v P₂), by unfold vc.subst,\n have ¬ free_in_vc x P₁, from (\n assume : free_in_vc x P₁,\n have free_in_vc x (P₁ ⋁ P₂), from free_in_vc.or₁ this,\n show «false», from x_not_free this\n ),\n have h1: vc.subst x v P₁ = P₁, from P₁_ih this,\n have ¬ free_in_vc x P₂, from (\n assume : free_in_vc x P₂,\n have free_in_vc x (P₁ ⋁ P₂), from free_in_vc.or₂ this,\n show «false», from x_not_free this\n ),\n have h2: vc.subst x v P₂ = P₂, from P₂_ih this,\n have vc.subst x v (P₁ ⋁ P₂) = (P₁ ⋁ vc.subst x v P₂),\n from @eq.subst vc (λa, vc.subst x v (vc.or P₁ P₂) = (a ⋁ vc.subst x v P₂)) (vc.subst x v P₁) P₁ h1 h,\n show vc.subst x v (P₁ ⋁ P₂) = (P₁ ⋁ P₂),\n from @eq.subst vc (λa, vc.subst x v (vc.or P₁ P₂) = (P₁ ⋁ a)) (vc.subst x v P₂) P₂ h2 this\n )},\n case vc.pre t₁ t₂ { from (\n have h: vc.subst x v (vc.pre t₁ t₂) = vc.pre (term.subst x v t₁) (term.subst x v t₂), by unfold vc.subst,\n have ¬ free_in_term x t₁, from (\n assume : free_in_term x t₁,\n have free_in_vc x (vc.pre t₁ t₂), from free_in_vc.pre₁ this,\n show «false», from x_not_free this\n ),\n have h1: term.subst x v t₁ = t₁, from unchanged_of_subst_nonfree_term this,\n have ¬ free_in_term x t₂, from (\n assume : free_in_term x t₂,\n have free_in_vc x (vc.pre t₁ t₂), from free_in_vc.pre₂ this,\n show «false», from x_not_free this\n ),\n have h2: term.subst x v t₂ = t₂, from unchanged_of_subst_nonfree_term this,\n have vc.subst x v (vc.pre t₁ t₂) = vc.pre t₁ (term.subst x v t₂),\n from @eq.subst term (λa, vc.subst x v (vc.pre t₁ t₂) = vc.pre a (term.subst x v t₂)) (term.subst x v t₁) t₁ h1 h,\n show vc.subst x v (vc.pre t₁ t₂) = vc.pre t₁ t₂,\n from @eq.subst term (λa, vc.subst x v (vc.pre t₁ t₂) = vc.pre t₁ a) (term.subst x v t₂) t₂ h2 this\n )},\n case vc.pre₁ op t { from (\n have h: vc.subst x v (vc.pre₁ op t) = vc.pre₁ op (term.subst x v t), by unfold vc.subst,\n have ¬ free_in_term x t, from (\n assume : free_in_term x t,\n have free_in_vc x (vc.pre₁ op t), from free_in_vc.preop this,\n show «false», from x_not_free this\n ),\n have term.subst x v t = t, from unchanged_of_subst_nonfree_term this,\n show vc.subst x v (vc.pre₁ op t) = vc.pre₁ op t,\n from @eq.subst term (λa, vc.subst x v (vc.pre₁ op t) = vc.pre₁ op a) (term.subst x v t) t this h\n )},\n case vc.pre₂ op t₁ t₂ { from (\n have h: vc.subst x v (vc.pre₂ op t₁ t₂) = vc.pre₂ op (term.subst x v t₁) (term.subst x v t₂),\n by unfold vc.subst,\n have ¬ free_in_term x t₁, from (\n assume : free_in_term x t₁,\n have free_in_vc x (vc.pre₂ op t₁ t₂), from free_in_vc.preop₁ this,\n show «false», from x_not_free this\n ),\n have h1: term.subst x v t₁ = t₁, from unchanged_of_subst_nonfree_term this,\n have ¬ free_in_term x t₂, from (\n assume : free_in_term x t₂,\n have free_in_vc x (vc.pre₂ op t₁ t₂), from free_in_vc.preop₂ this,\n show «false», from x_not_free this\n ),\n have h2: term.subst x v t₂ = t₂, from unchanged_of_subst_nonfree_term this,\n have vc.subst x v (vc.pre₂ op t₁ t₂) = vc.pre₂ op t₁ (term.subst x v t₂),\n from @eq.subst term (λa, vc.subst x v (vc.pre₂ op t₁ t₂) = vc.pre₂ op a (term.subst x v t₂)) (term.subst x v t₁) t₁ h1 h,\n show vc.subst x v (vc.pre₂ op t₁ t₂) = vc.pre₂ op t₁ t₂,\n from @eq.subst term (λa, vc.subst x v (vc.pre₂ op t₁ t₂) = vc.pre₂ op t₁ a) (term.subst x v t₂) t₂ h2 this\n )},\n case vc.post t₁ t₂ { from (\n have h: vc.subst x v (vc.post t₁ t₂) = vc.post (term.subst x v t₁) (term.subst x v t₂), by unfold vc.subst,\n have ¬ free_in_term x t₁, from (\n assume : free_in_term x t₁,\n have free_in_vc x (vc.post t₁ t₂), from free_in_vc.post₁ this,\n show «false», from x_not_free this\n ),\n have h1: term.subst x v t₁ = t₁, from unchanged_of_subst_nonfree_term this,\n have ¬ free_in_term x t₂, from (\n assume : free_in_term x t₂,\n have free_in_vc x (vc.post t₁ t₂), from free_in_vc.post₂ this,\n show «false», from x_not_free this\n ),\n have h2: term.subst x v t₂ = t₂, from unchanged_of_subst_nonfree_term this,\n have vc.subst x v (vc.post t₁ t₂) = vc.post t₁ (term.subst x v t₂),\n from @eq.subst term (λa, vc.subst x v (vc.post t₁ t₂) = vc.post a (term.subst x v t₂)) (term.subst x v t₁) t₁ h1 h,\n show vc.subst x v (vc.post t₁ t₂) = vc.post t₁ t₂,\n from @eq.subst term (λa, vc.subst x v (vc.post t₁ t₂) = vc.post t₁ a) (term.subst x v t₂) t₂ h2 this\n )},\n case vc.univ y P' P'_ih { from (\n have h: vc.subst x v (vc.univ y P') = vc.univ y (if x = y then P' else vc.subst x v P'), by unfold vc.subst,\n if x_eq_y: x = y then (\n have (if x = y then P' else vc.subst x v P') = P', by simp[x_eq_y],\n show vc.subst x v (vc.univ y P') = vc.univ y P',\n from @eq.subst vc (λa, vc.subst x v (vc.univ y P') = vc.univ y a)\n (if x = y then P' else vc.subst x v P') P' this h\n ) else (\n have (if x = y then P' else vc.subst x v P') = vc.subst x v P', by simp[x_eq_y],\n have h2: vc.subst x v (vc.univ y P') = vc.univ y (vc.subst x v P'),\n from @eq.subst vc (λa, vc.subst x v (vc.univ y P') = vc.univ y a)\n (if x = y then P' else vc.subst x v P') (vc.subst x v P') this h,\n have ¬ free_in_vc x P', from (\n assume : free_in_vc x P',\n have free_in_vc x (vc.univ y P'), from free_in_vc.univ x_eq_y this,\n show «false», from x_not_free this\n ),\n have vc.subst x v P' = P', from P'_ih this,\n show vc.subst x v (vc.univ y P') = vc.univ y P',\n from @eq.subst vc (λa, vc.subst x v (vc.univ y P') = vc.univ y a) (vc.subst x v P') P' this h2\n )\n )}\n end\n\nlemma unchanged_of_substt_nonfree_vc {P: vc} {x: var} {t: term}:\n x ∉ FV P → (vc.substt x t P = P) :=\n assume x_not_free: ¬ free_in_vc x P,\n begin\n induction P,\n case vc.term t₁ { from (\n have h: vc.substt x t (vc.term t₁) = term.substt x t t₁, by unfold vc.substt,\n have ¬ free_in_term x t₁, from (\n assume : free_in_term x t₁,\n have free_in_vc x (vc.term t₁), from free_in_vc.term this,\n show «false», from x_not_free this\n ),\n have term.substt x t t₁ = t₁, from unchanged_of_substt_nonfree_term this,\n show vc.substt x t t₁ = vc.term t₁,\n from @eq.subst term (λa, vc.substt x t (vc.term t₁) = vc.term a) (term.substt x t t₁) t₁ this h\n )},\n case vc.not P₁ ih { from (\n have h: vc.substt x t P₁.not = (vc.substt x t P₁).not, by unfold vc.substt,\n have ¬ free_in_vc x P₁, from (\n assume : free_in_vc x P₁,\n have free_in_vc x P₁.not, from free_in_vc.not this,\n show «false», from x_not_free this\n ),\n have vc.substt x t P₁ = P₁, from ih this,\n show vc.substt x t P₁.not = P₁.not,\n from @eq.subst vc (λa, vc.substt x t P₁.not = vc.not a) (vc.substt x t P₁) P₁ this h\n )},\n case vc.and P₁ P₂ P₁_ih P₂_ih { from (\n have h: vc.substt x t (vc.and P₁ P₂) = (vc.substt x t P₁ ⋀ vc.substt x t P₂), by unfold vc.substt,\n have ¬ free_in_vc x P₁, from (\n assume : free_in_vc x P₁,\n have free_in_vc x (P₁ ⋀ P₂), from free_in_vc.and₁ this,\n show «false», from x_not_free this\n ),\n have h1: vc.substt x t P₁ = P₁, from P₁_ih this,\n have ¬ free_in_vc x P₂, from (\n assume : free_in_vc x P₂,\n have free_in_vc x (P₁ ⋀ P₂), from free_in_vc.and₂ this,\n show «false», from x_not_free this\n ),\n have h2: vc.substt x t P₂ = P₂, from P₂_ih this,\n have vc.substt x t (P₁ ⋀ P₂) = (P₁ ⋀ vc.substt x t P₂),\n from @eq.subst vc (λa, vc.substt x t (vc.and P₁ P₂) = (a ⋀ vc.substt x t P₂)) (vc.substt x t P₁) P₁ h1 h,\n show vc.substt x t (P₁ ⋀ P₂) = (P₁ ⋀ P₂),\n from @eq.subst vc (λa, vc.substt x t (vc.and P₁ P₂) = (P₁ ⋀ a)) (vc.substt x t P₂) P₂ h2 this\n )},\n case vc.or P₁ P₂ P₁_ih P₂_ih { from (\n have h: vc.substt x t (vc.or P₁ P₂) = (vc.substt x t P₁ ⋁ vc.substt x t P₂), by unfold vc.substt,\n have ¬ free_in_vc x P₁, from (\n assume : free_in_vc x P₁,\n have free_in_vc x (P₁ ⋁ P₂), from free_in_vc.or₁ this,\n show «false», from x_not_free this\n ),\n have h1: vc.substt x t P₁ = P₁, from P₁_ih this,\n have ¬ free_in_vc x P₂, from (\n assume : free_in_vc x P₂,\n have free_in_vc x (P₁ ⋁ P₂), from free_in_vc.or₂ this,\n show «false», from x_not_free this\n ),\n have h2: vc.substt x t P₂ = P₂, from P₂_ih this,\n have vc.substt x t (P₁ ⋁ P₂) = (P₁ ⋁ vc.substt x t P₂),\n from @eq.subst vc (λa, vc.substt x t (vc.or P₁ P₂) = (a ⋁ vc.substt x t P₂)) (vc.substt x t P₁) P₁ h1 h,\n show vc.substt x t (P₁ ⋁ P₂) = (P₁ ⋁ P₂),\n from @eq.subst vc (λa, vc.substt x t (vc.or P₁ P₂) = (P₁ ⋁ a)) (vc.substt x t P₂) P₂ h2 this\n )},\n case vc.pre t₁ t₂ { from (\n have h: vc.substt x t (vc.pre t₁ t₂) = vc.pre (term.substt x t t₁) (term.substt x t t₂), by unfold vc.substt,\n have ¬ free_in_term x t₁, from (\n assume : free_in_term x t₁,\n have free_in_vc x (vc.pre t₁ t₂), from free_in_vc.pre₁ this,\n show «false», from x_not_free this\n ),\n have h1: term.substt x t t₁ = t₁, from unchanged_of_substt_nonfree_term this,\n have ¬ free_in_term x t₂, from (\n assume : free_in_term x t₂,\n have free_in_vc x (vc.pre t₁ t₂), from free_in_vc.pre₂ this,\n show «false», from x_not_free this\n ),\n have h2: term.substt x t t₂ = t₂, from unchanged_of_substt_nonfree_term this,\n have vc.substt x t (vc.pre t₁ t₂) = vc.pre t₁ (term.substt x t t₂),\n from @eq.subst term (λa, vc.substt x t (vc.pre t₁ t₂) = vc.pre a (term.substt x t t₂)) (term.substt x t t₁) t₁ h1 h,\n show vc.substt x t (vc.pre t₁ t₂) = vc.pre t₁ t₂,\n from @eq.subst term (λa, vc.substt x t (vc.pre t₁ t₂) = vc.pre t₁ a) (term.substt x t t₂) t₂ h2 this\n )},\n case vc.pre₁ op t₁ { from (\n have h: vc.substt x t (vc.pre₁ op t₁) = vc.pre₁ op (term.substt x t t₁), by unfold vc.substt,\n have ¬ free_in_term x t₁, from (\n assume : free_in_term x t₁,\n have free_in_vc x (vc.pre₁ op t₁), from free_in_vc.preop this,\n show «false», from x_not_free this\n ),\n have term.substt x t t₁ = t₁, from unchanged_of_substt_nonfree_term this,\n show vc.substt x t (vc.pre₁ op t₁ ) = vc.pre₁ op t₁,\n from @eq.subst term (λa, vc.substt x t (vc.pre₁ op t₁) = vc.pre₁ op a) (term.substt x t t₁) t₁ this h\n )},\n case vc.pre₂ op t₁ t₂ { from (\n have h: vc.substt x t (vc.pre₂ op t₁ t₂) = vc.pre₂ op (term.substt x t t₁) (term.substt x t t₂),\n by unfold vc.substt,\n have ¬ free_in_term x t₁, from (\n assume : free_in_term x t₁,\n have free_in_vc x (vc.pre₂ op t₁ t₂), from free_in_vc.preop₁ this,\n show «false», from x_not_free this\n ),\n have h1: term.substt x t t₁ = t₁, from unchanged_of_substt_nonfree_term this,\n have ¬ free_in_term x t₂, from (\n assume : free_in_term x t₂,\n have free_in_vc x (vc.pre₂ op t₁ t₂), from free_in_vc.preop₂ this,\n show «false», from x_not_free this\n ),\n have h2: term.substt x t t₂ = t₂, from unchanged_of_substt_nonfree_term this,\n have vc.substt x t (vc.pre₂ op t₁ t₂) = vc.pre₂ op t₁ (term.substt x t t₂),\n from @eq.subst term (λa, vc.substt x t (vc.pre₂ op t₁ t₂) = vc.pre₂ op a (term.substt x t t₂)) (term.substt x t t₁) t₁ h1 h,\n show vc.substt x t (vc.pre₂ op t₁ t₂) = vc.pre₂ op t₁ t₂,\n from @eq.subst term (λa, vc.substt x t (vc.pre₂ op t₁ t₂) = vc.pre₂ op t₁ a) (term.substt x t t₂) t₂ h2 this\n )},\n case vc.post t₁ t₂ { from (\n have h: vc.substt x t (vc.post t₁ t₂) = vc.post (term.substt x t t₁) (term.substt x t t₂), by unfold vc.substt,\n have ¬ free_in_term x t₁, from (\n assume : free_in_term x t₁,\n have free_in_vc x (vc.post t₁ t₂), from free_in_vc.post₁ this,\n show «false», from x_not_free this\n ),\n have h1: term.substt x t t₁ = t₁, from unchanged_of_substt_nonfree_term this,\n have ¬ free_in_term x t₂, from (\n assume : free_in_term x t₂,\n have free_in_vc x (vc.post t₁ t₂), from free_in_vc.post₂ this,\n show «false», from x_not_free this\n ),\n have h2: term.substt x t t₂ = t₂, from unchanged_of_substt_nonfree_term this,\n have vc.substt x t (vc.post t₁ t₂) = vc.post t₁ (term.substt x t t₂),\n from @eq.subst term (λa, vc.substt x t (vc.post t₁ t₂) = vc.post a (term.substt x t t₂)) (term.substt x t t₁) t₁ h1 h,\n show vc.substt x t (vc.post t₁ t₂) = vc.post t₁ t₂,\n from @eq.subst term (λa, vc.substt x t (vc.post t₁ t₂) = vc.post t₁ a) (term.substt x t t₂) t₂ h2 this\n )},\n case vc.univ y P' P'_ih { from (\n have h: vc.substt x t (vc.univ y P') = vc.univ y (if x = y then P' else vc.substt x t P'), by unfold vc.substt,\n if x_eq_y: x = y then (\n have (if x = y then P' else vc.substt x t P') = P', by simp[x_eq_y],\n show vc.substt x t (vc.univ y P') = vc.univ y P',\n from @eq.subst vc (λa, vc.substt x t (vc.univ y P') = vc.univ y a)\n (if x = y then P' else vc.substt x t P') P' this h\n ) else (\n have (if x = y then P' else vc.substt x t P') = vc.substt x t P', by simp[x_eq_y],\n have h2: vc.substt x t (vc.univ y P') = vc.univ y (vc.substt x t P'),\n from @eq.subst vc (λa, vc.substt x t (vc.univ y P') = vc.univ y a)\n (if x = y then P' else vc.substt x t P') (vc.substt x t P') this h,\n have ¬ free_in_vc x P', from (\n assume : free_in_vc x P',\n have free_in_vc x (vc.univ y P'), from free_in_vc.univ x_eq_y this,\n show «false», from x_not_free this\n ),\n have vc.substt x t P' = P', from P'_ih this,\n show vc.substt x t (vc.univ y P') = vc.univ y P',\n from @eq.subst vc (λa, vc.substt x t (vc.univ y P') = vc.univ y a) (vc.substt x t P') P' this h2\n )\n )}\n end\n\nlemma unchanged_of_subst_env_nonfree_vc {P: vc}:\n closed P → (∀σ, vc.subst_env σ P = P) :=\n assume x_not_free: (∀x, x ∉ FV P),\n assume σ: env,\n begin\n induction σ with σ' x v ih,\n\n show (vc.subst_env env.empty P = P), by unfold vc.subst_env,\n\n show (vc.subst_env (σ'[x↦v]) P = P), by calc\n vc.subst_env (σ'[x↦v]) P = vc.subst x v (vc.subst_env σ' P) : by unfold vc.subst_env\n ... = vc.subst x v P : by rw[ih]\n ... = P : unchanged_of_subst_nonfree_vc (x_not_free x)\n end\n\nlemma free_of_subst_term {t: term} {x y: var} {v: value}:\n free_in_term x (term.subst y v t) → x ≠ y ∧ free_in_term x t :=\n assume x_free_in_subst: free_in_term x (term.subst y v t),\n begin\n induction t with v' z unop t₁ t₁_ih binop t₂ t₃ t₂_ih t₃_ih t₄ t₅ t₄_ih t₅_ih,\n show x ≠ y ∧ free_in_term x (term.value v'), from (\n have term.subst y v (term.value v') = v', by unfold term.subst,\n have free_in_term x v', from this ▸ x_free_in_subst,\n show x ≠ y ∧ free_in_term x (term.value v'), from absurd this free_in_term.value.inv\n ),\n show x ≠ y ∧ free_in_term x (term.var z), from (\n have hite: term.subst y v (term.var z) = (if y = z then v else z), by unfold term.subst,\n if y_is_z: y = z then\n have term.subst y v (term.var z) = v, by { simp[y_is_z] at hite, rw[y_is_z], from hite },\n have free_in_term x v, from this ▸ x_free_in_subst,\n show x ≠ y ∧ free_in_term x (term.var z), from absurd this free_in_term.value.inv\n else\n have term.subst y v (term.var z) = z, by { simp[y_is_z] at hite, from hite },\n have free_in_term x z, from this ▸ x_free_in_subst,\n have x_is_z: x = z, from free_in_term.var.inv this,\n have x ≠ y, from x_is_z.symm ▸ (ne.symm y_is_z),\n show x ≠ y ∧ free_in_term x (term.var z), from ⟨this, x_is_z ▸ free_in_term.var x⟩\n ),\n show x ≠ y ∧ free_in_term x (term.unop unop t₁), from (\n have term.subst y v (term.unop unop t₁) = term.unop unop (term.subst y v t₁), by unfold term.subst,\n have free_in_term x (term.unop unop (term.subst y v t₁)), from this ▸ x_free_in_subst,\n have free_in_term x (term.subst y v t₁), from free_in_term.unop.inv this,\n have x ≠ y ∧ free_in_term x t₁, from t₁_ih this,\n show x ≠ y ∧ free_in_term x (term.unop unop t₁), from ⟨this.left, free_in_term.unop this.right⟩\n ),\n show x ≠ y ∧ free_in_term x (term.binop binop t₂ t₃), from (\n have term.subst y v (term.binop binop t₂ t₃) = term.binop binop (term.subst y v t₂) (term.subst y v t₃),\n by unfold term.subst,\n have free_in_term x (term.binop binop (term.subst y v t₂) (term.subst y v t₃)), from this ▸ x_free_in_subst,\n have free_in_term x (term.subst y v t₂) ∨ free_in_term x (term.subst y v t₃), from free_in_term.binop.inv this,\n or.elim this (\n assume : free_in_term x (term.subst y v t₂),\n have x ≠ y ∧ free_in_term x t₂, from t₂_ih this,\n show x ≠ y ∧ free_in_term x (term.binop binop t₂ t₃), from ⟨this.left, free_in_term.binop₁ this.right⟩\n ) (\n assume : free_in_term x (term.subst y v t₃),\n have x ≠ y ∧ free_in_term x t₃, from t₃_ih this,\n show x ≠ y ∧ free_in_term x (term.binop binop t₂ t₃), from ⟨this.left, free_in_term.binop₂ this.right⟩\n )\n ),\n show x ≠ y ∧ free_in_term x (term.app t₄ t₅), from (\n have term.subst y v (term.app t₄ t₅) = term.app (term.subst y v t₄) (term.subst y v t₅),\n by unfold term.subst,\n have free_in_term x (term.app (term.subst y v t₄) (term.subst y v t₅)), from this ▸ x_free_in_subst,\n have free_in_term x (term.subst y v t₄) ∨ free_in_term x (term.subst y v t₅), from free_in_term.app.inv this,\n or.elim this (\n assume : free_in_term x (term.subst y v t₄),\n have x ≠ y ∧ free_in_term x t₄, from t₄_ih this,\n show x ≠ y ∧ free_in_term x (term.app t₄ t₅), from ⟨this.left, free_in_term.app₁ this.right⟩\n ) (\n assume : free_in_term x (term.subst y v t₅),\n have x ≠ y ∧ free_in_term x t₅, from t₅_ih this,\n show x ≠ y ∧ free_in_term x (term.app t₄ t₅), from ⟨this.left, free_in_term.app₂ this.right⟩\n )\n )\n end\n\nlemma free_of_substt_same_term {t t': term} {x: var}:\n free_in_term x (term.substt x t' t) → free_in_term x t' :=\n assume x_free_in_subst: free_in_term x (term.substt x t' t),\n begin\n induction t with v' z unop t₁ t₁_ih binop t₂ t₃ t₂_ih t₃_ih t₄ t₅ t₄_ih t₅_ih,\n show free_in_term x t', from (\n have term.substt x t' (term.value v') = v', by unfold term.substt,\n have free_in_term x v', from this ▸ x_free_in_subst,\n show free_in_term x t', from absurd this free_in_term.value.inv\n ),\n show free_in_term x t', from (\n have hite: term.substt x t' (term.var z) = (if x = z then t' else z), by unfold term.substt,\n if x_is_z: x = z then\n have term.substt x t' (term.var z) = t', by { simp[x_is_z] at hite, rw[x_is_z], from hite },\n show free_in_term x t', from this ▸ x_free_in_subst\n else\n have term.substt x t' (term.var z) = z, by { simp[x_is_z] at hite, from hite },\n have free_in_term x z, from this ▸ x_free_in_subst,\n have x_iss_z: x = z, from free_in_term.var.inv this,\n show free_in_term x t', from absurd x_iss_z x_is_z\n ),\n show free_in_term x t', from (\n have term.substt x t' (term.unop unop t₁) = term.unop unop (term.substt x t' t₁), by unfold term.substt,\n have free_in_term x (term.unop unop (term.substt x t' t₁)), from this ▸ x_free_in_subst,\n have free_in_term x (term.substt x t' t₁), from free_in_term.unop.inv this,\n show free_in_term x t', from t₁_ih this\n ),\n show free_in_term x t', from (\n have term.substt x t' (term.binop binop t₂ t₃) = term.binop binop (term.substt x t' t₂) (term.substt x t' t₃),\n by unfold term.substt,\n have free_in_term x (term.binop binop (term.substt x t' t₂) (term.substt x t' t₃)), from this ▸ x_free_in_subst,\n have free_in_term x (term.substt x t' t₂) ∨ free_in_term x (term.substt x t' t₃),\n from free_in_term.binop.inv this,\n or.elim this (\n assume : free_in_term x (term.substt x t' t₂),\n show free_in_term x t', from t₂_ih this\n ) (\n assume : free_in_term x (term.substt x t' t₃),\n show free_in_term x t', from t₃_ih this\n )\n ),\n show free_in_term x t', from (\n have term.substt x t' (term.app t₄ t₅) = term.app (term.substt x t' t₄) (term.substt x t' t₅),\n by unfold term.substt,\n have free_in_term x (term.app (term.substt x t' t₄) (term.substt x t' t₅)), from this ▸ x_free_in_subst,\n have free_in_term x (term.substt x t' t₄) ∨ free_in_term x (term.substt x t' t₅), from free_in_term.app.inv this,\n or.elim this (\n assume : free_in_term x (term.substt x t' t₄),\n show free_in_term x t', from t₄_ih this\n ) (\n assume : free_in_term x (term.substt x t' t₅),\n show free_in_term x t', from t₅_ih this\n )\n )\n end\n\nlemma free_of_subst_env_term_step {t: term} {σ: env} {x y: var} {v: value}:\n free_in_term x (term.subst_env (σ[y↦v]) t) → x ≠ y ∧ free_in_term x (term.subst_env σ t) :=\n assume x_free: free_in_term x (term.subst_env (σ[y↦v]) t),\n have term.subst_env (σ[y↦v]) t = term.subst y v (term.subst_env σ t), by unfold term.subst_env,\n have free_in_term x (term.subst y v (term.subst_env σ t)), from this ▸ x_free,\n show x ≠ y ∧ free_in_term x (term.subst_env σ t), from free_of_subst_term this\n\nlemma free_of_subst_env_term {t: term} {σ: env} {x: var}:\n free_in_term x (term.subst_env σ t) → free_in_term x t ∧ x ∉ σ :=\n assume x_free_in_subst: free_in_term x (term.subst_env σ t),\n begin\n induction σ with σ' y v ih,\n show free_in_term x t ∧ x ∉ env.empty, from (\n have h2: x ∉ env.empty, by begin\n assume : x ∈ env.empty,\n have h3: env.contains env.empty x, from this,\n cases h3\n end,\n have term.subst_env env.empty t = t, by unfold term.subst_env,\n show free_in_term x t ∧ x ∉ env.empty, from ⟨this ▸ x_free_in_subst, h2⟩\n ),\n show free_in_term x t ∧ x ∉ (σ'[y↦v]), from (\n have h1: x ≠ y ∧ free_in_term x (term.subst_env σ' t),\n from free_of_subst_env_term_step x_free_in_subst,\n have h2: free_in_term x t ∧ x ∉ σ', from ih h1.right,\n have h3: x ∉ (σ'[y↦v]), by begin\n assume : x ∈ (σ'[y↦v]),\n have h3: env.contains (σ'[y↦v]) x, from this,\n cases h3,\n have h4: x ≠ x, from h1.left,\n contradiction,\n have h5: ¬ env.contains σ' x, from h2.right,\n contradiction\n end,\n show free_in_term x t ∧ x ∉ (σ'[y↦v]), from ⟨h2.left, h3⟩\n )\n end\n\nlemma free_of_subst_prop {P: prop} {x y: var} {v: value}:\n free_in_prop x (prop.subst y v P) → x ≠ y ∧ free_in_prop x P :=\n assume x_free_in_subst: free_in_prop x (prop.subst y v P),\n begin\n induction P,\n case prop.term t { from (\n have prop.subst y v (prop.term t) = (term.subst y v t), by unfold prop.subst,\n have free_in_prop x (term.subst y v t), from this ▸ x_free_in_subst,\n have free_in_term x (term.subst y v t), from free_in_prop.term.inv this,\n have x ≠ y ∧ free_in_term x t, from free_of_subst_term this,\n show x ≠ y ∧ free_in_prop x (prop.term t), from ⟨this.left, free_in_prop.term this.right⟩\n )},\n case prop.not P₁ P₁_ih { from (\n have (prop.subst y v P₁.not = (prop.subst y v P₁).not), by unfold prop.subst,\n have free_in_prop x (prop.subst y v P₁).not, from this ▸ x_free_in_subst,\n have free_in_prop x (prop.subst y v P₁), from free_in_prop.not.inv this,\n have x ≠ y ∧ free_in_prop x P₁, from P₁_ih this,\n show x ≠ y ∧ free_in_prop x P₁.not, from ⟨this.left, free_in_prop.not this.right⟩\n )},\n case prop.and P₂ P₃ P₂_ih P₃_ih { from (\n have prop.subst y v (prop.and P₂ P₃) = (prop.subst y v P₂ ⋀ prop.subst y v P₃), by unfold prop.subst,\n have free_in_prop x ((prop.subst y v P₂) ⋀ (prop.subst y v P₃)), from this ▸ x_free_in_subst,\n have free_in_prop x (prop.subst y v P₂) ∨ free_in_prop x (prop.subst y v P₃),\n from free_in_prop.and.inv this,\n or.elim this (\n assume : free_in_prop x (prop.subst y v P₂),\n have x ≠ y ∧ free_in_prop x P₂, from P₂_ih this,\n show x ≠ y ∧ free_in_prop x (P₂ ⋀ P₃), from ⟨this.left, free_in_prop.and₁ this.right⟩\n ) (\n assume : free_in_prop x (prop.subst y v P₃),\n have x ≠ y ∧ free_in_prop x P₃, from P₃_ih this,\n show x ≠ y ∧ free_in_prop x (P₂ ⋀ P₃), from ⟨this.left, free_in_prop.and₂ this.right⟩\n )\n )},\n case prop.or P₄ P₅ P₄_ih P₅_ih { from (\n have prop.subst y v (prop.or P₄ P₅) = (prop.subst y v P₄ ⋁ prop.subst y v P₅), by unfold prop.subst,\n have free_in_prop x (prop.or (prop.subst y v P₄) (prop.subst y v P₅)),\n from this ▸ x_free_in_subst,\n have free_in_prop x (prop.subst y v P₄) ∨ free_in_prop x (prop.subst y v P₅),\n from free_in_prop.or.inv this,\n or.elim this (\n assume : free_in_prop x (prop.subst y v P₄),\n have x ≠ y ∧ free_in_prop x P₄, from P₄_ih this,\n show x ≠ y ∧ free_in_prop x (prop.or P₄ P₅), from ⟨this.left, free_in_prop.or₁ this.right⟩\n ) (\n assume : free_in_prop x (prop.subst y v P₅),\n have x ≠ y ∧ free_in_prop x P₅, from P₅_ih this,\n show x ≠ y ∧ free_in_prop x (prop.or P₄ P₅), from ⟨this.left, free_in_prop.or₂ this.right⟩\n )\n )},\n case prop.pre t₁ t₂ { from (\n have prop.subst y v (prop.pre t₁ t₂) = prop.pre (term.subst y v t₁) (term.subst y v t₂), by unfold prop.subst,\n have free_in_prop x (prop.pre (term.subst y v t₁) (term.subst y v t₂)),\n from this ▸ x_free_in_subst,\n have free_in_term x (term.subst y v t₁) ∨ free_in_term x (term.subst y v t₂), from free_in_prop.pre.inv this,\n or.elim this (\n assume : free_in_term x (term.subst y v t₁),\n have x ≠ y ∧ free_in_term x t₁, from free_of_subst_term this,\n show x ≠ y ∧ free_in_prop x (prop.pre t₁ t₂), from ⟨this.left, free_in_prop.pre₁ this.right⟩\n ) (\n assume : free_in_term x (term.subst y v t₂),\n have x ≠ y ∧ free_in_term x t₂, from free_of_subst_term this,\n show x ≠ y ∧ free_in_prop x (prop.pre t₁ t₂), from ⟨this.left, free_in_prop.pre₂ this.right⟩\n )\n )},\n case prop.pre₁ op t { from (\n have prop.subst y v (prop.pre₁ op t) = prop.pre₁ op (term.subst y v t), by unfold prop.subst,\n have free_in_prop x (prop.pre₁ op (term.subst y v t)),\n from this ▸ x_free_in_subst,\n have free_in_term x (term.subst y v t), from free_in_prop.pre₁.inv this,\n have x ≠ y ∧ free_in_term x t, from free_of_subst_term this,\n show x ≠ y ∧ free_in_prop x (prop.pre₁ op t), from ⟨this.left, free_in_prop.preop this.right⟩\n )},\n case prop.pre₂ op t₁ t₂ { from (\n have prop.subst y v (prop.pre₂ op t₁ t₂) = prop.pre₂ op (term.subst y v t₁) (term.subst y v t₂),\n by unfold prop.subst,\n have free_in_prop x (prop.pre₂ op (term.subst y v t₁) (term.subst y v t₂)),\n from this ▸ x_free_in_subst,\n have free_in_term x (term.subst y v t₁) ∨ free_in_term x (term.subst y v t₂), from free_in_prop.pre₂.inv this,\n or.elim this (\n assume : free_in_term x (term.subst y v t₁),\n have x ≠ y ∧ free_in_term x t₁, from free_of_subst_term this,\n show x ≠ y ∧ free_in_prop x (prop.pre₂ op t₁ t₂), from ⟨this.left, free_in_prop.preop₁ this.right⟩\n ) (\n assume : free_in_term x (term.subst y v t₂),\n have x ≠ y ∧ free_in_term x t₂, from free_of_subst_term this,\n show x ≠ y ∧ free_in_prop x (prop.pre₂ op t₁ t₂), from ⟨this.left, free_in_prop.preop₂ this.right⟩\n )\n )},\n case prop.post t₁ t₂ { from (\n have prop.subst y v (prop.post t₁ t₂) = prop.post (term.subst y v t₁) (term.subst y v t₂), by unfold prop.subst,\n have free_in_prop x (prop.post (term.subst y v t₁) (term.subst y v t₂)),\n from this ▸ x_free_in_subst,\n have free_in_term x (term.subst y v t₁) ∨ free_in_term x (term.subst y v t₂), from free_in_prop.post.inv this,\n or.elim this (\n assume : free_in_term x (term.subst y v t₁),\n have x ≠ y ∧ free_in_term x t₁, from free_of_subst_term this,\n show x ≠ y ∧ free_in_prop x (prop.post t₁ t₂), from ⟨this.left, free_in_prop.post₁ this.right⟩\n ) (\n assume : free_in_term x (term.subst y v t₂),\n have x ≠ y ∧ free_in_term x t₂, from free_of_subst_term this,\n show x ≠ y ∧ free_in_prop x (prop.post t₁ t₂), from ⟨this.left, free_in_prop.post₂ this.right⟩\n )\n )},\n case prop.call t { from (\n have prop.subst y v (prop.call t) = prop.call (term.subst y v t), by unfold prop.subst,\n have free_in_prop x (prop.call (term.subst y v t)),\n from this ▸ x_free_in_subst,\n have free_in_term x (term.subst y v t), from free_in_prop.call.inv this,\n have x ≠ y ∧ free_in_term x t, from free_of_subst_term this,\n show x ≠ y ∧ free_in_prop x (prop.call t), from ⟨this.left, free_in_prop.call this.right⟩\n )},\n case prop.forallc z P ih { from (\n have prop.subst y v (prop.forallc z P)\n = prop.forallc z (if y = z then P else P.subst y v),\n by unfold prop.subst,\n have free_in_prop x (prop.forallc z (if y = z then P else P.subst y v)),\n from this ▸ x_free_in_subst,\n have x_neq_z: x ≠ z, from (free_in_prop.forallc.inv this).left,\n have fre_ite: free_in_prop x (if y = z then P else P.subst y v),\n from (free_in_prop.forallc.inv this).right,\n if y_eq_z: y = z then (\n have x_neq_y: x ≠ y, from y_eq_z.symm ▸ x_neq_z,\n have free_in_prop x P, by { simp[y_eq_z] at fre_ite, from fre_ite },\n show x ≠ y ∧ free_in_prop x (prop.forallc z P), from ⟨x_neq_y, free_in_prop.forallc x_neq_z this⟩\n ) else (\n have free_in_prop x (P.subst y v), by { simp[y_eq_z] at fre_ite, from fre_ite },\n have x ≠ y ∧ free_in_prop x P, from ih this,\n show x ≠ y ∧ free_in_prop x (prop.forallc z P), from ⟨this.left, free_in_prop.forallc x_neq_z this.right⟩\n )\n )},\n case prop.exis z P ih { from (\n have prop.subst y v (prop.exis z P) = prop.exis z (if y = z then P else P.subst y v),\n by unfold prop.subst,\n have free_in_prop x (prop.exis z (if y = z then P else P.subst y v)),\n from this ▸ x_free_in_subst,\n have x_neq_z: x ≠ z, from (free_in_prop.exis.inv this).left,\n have fre_ite: free_in_prop x (if y = z then P else P.subst y v), from (free_in_prop.exis.inv this).right,\n if y_eq_z: y = z then (\n have x_neq_y: x ≠ y, from y_eq_z.symm ▸ x_neq_z,\n have free_in_prop x P, by { simp[y_eq_z] at fre_ite, from fre_ite },\n show x ≠ y ∧ free_in_prop x (prop.exis z P), from ⟨x_neq_y, free_in_prop.exis x_neq_z this⟩\n ) else (\n have free_in_prop x (P.subst y v), by { simp[y_eq_z] at fre_ite, from fre_ite },\n have x ≠ y ∧ free_in_prop x P, from ih this,\n show x ≠ y ∧ free_in_prop x (prop.exis z P), from ⟨this.left, free_in_prop.exis x_neq_z this.right⟩\n )\n )}\n end\n\nlemma free_of_subst_env_prop {P: prop} {σ: env} {x y: var} {v: value}:\n free_in_prop x (prop.subst_env (σ[y↦v]) P) → x ≠ y ∧ free_in_prop x (prop.subst_env σ P) :=\n assume x_free: free_in_prop x (prop.subst_env (σ[y↦v]) P),\n have prop.subst_env (σ[y↦v]) P = prop.subst y v (prop.subst_env σ P), by unfold prop.subst_env,\n have free_in_prop x (prop.subst y v (prop.subst_env σ P)), from this ▸ x_free,\n show x ≠ y ∧ free_in_prop x (prop.subst_env σ P), from free_of_subst_prop this\n\nlemma free_of_subst_env {P: prop} {σ: env} {x: var}:\n free_in_prop x (prop.subst_env σ P) → free_in_prop x P :=\n assume x_free_in_subst: free_in_prop x (prop.subst_env σ P),\n begin\n induction σ with σ' y v ih,\n show free_in_prop x P, from (\n have prop.subst_env env.empty P = P, by unfold prop.subst_env,\n show free_in_prop x P, from this ▸ x_free_in_subst\n ),\n show free_in_prop x P, from (\n have free_in_prop x (prop.subst_env σ' P), from (free_of_subst_env_prop x_free_in_subst).right,\n show free_in_prop x P, from ih this\n )\n end\n\nlemma free_in_vc.subst {P: vc} {x y: var} {v: value}:\n free_in_vc x (vc.subst y v P) → x ≠ y ∧ free_in_vc x P :=\n assume x_free_in_subst: free_in_vc x (vc.subst y v P),\n begin\n induction P,\n case vc.term t { from (\n have vc.subst y v (vc.term t) = term.subst y v t, by unfold vc.subst,\n have free_in_vc x (vc.term (term.subst y v t)), from this ▸ x_free_in_subst,\n have free_in_term x (term.subst y v t), from free_in_vc.term.inv this,\n have x ≠ y ∧ free_in_term x t, from free_of_subst_term this,\n show x ≠ y ∧ free_in_vc x (vc.term t), from ⟨this.left, free_in_vc.term this.right⟩\n )},\n case vc.not P₁ ih { from (\n have (vc.subst y v P₁.not = (vc.subst y v P₁).not), by unfold vc.subst,\n have free_in_vc x (vc.subst y v P₁).not, from this ▸ x_free_in_subst,\n have free_in_vc x (vc.subst y v P₁), from free_in_vc.not.inv this,\n have x ≠ y ∧ free_in_vc x P₁, from ih this,\n show x ≠ y ∧ free_in_vc x P₁.not, from ⟨this.left, free_in_vc.not this.right⟩\n )},\n case vc.and P₁ P₂ P₁_ih P₂_ih { from (\n have vc.subst y v (vc.and P₁ P₂) = (vc.subst y v P₁ ⋀ vc.subst y v P₂), by unfold vc.subst,\n have free_in_vc x (vc.subst y v P₁ ⋀ vc.subst y v P₂), from this ▸ x_free_in_subst,\n have free_in_vc x (vc.subst y v P₁) ∨ free_in_vc x (vc.subst y v P₂),\n from free_in_vc.and.inv this,\n or.elim this (\n assume : free_in_vc x (vc.subst y v P₁),\n have x ≠ y ∧ free_in_vc x P₁, from P₁_ih this,\n show x ≠ y ∧ free_in_vc x (P₁ ⋀ P₂), from ⟨this.left, free_in_vc.and₁ this.right⟩\n ) (\n assume : free_in_vc x (vc.subst y v P₂),\n have x ≠ y ∧ free_in_vc x P₂, from P₂_ih this,\n show x ≠ y ∧ free_in_vc x (P₁ ⋀ P₂), from ⟨this.left, free_in_vc.and₂ this.right⟩\n )\n )},\n case vc.or P₁ P₂ P₁_ih P₂_ih { from (\n have vc.subst y v (vc.or P₁ P₂) = (vc.subst y v P₁ ⋁ vc.subst y v P₂), by unfold vc.subst,\n have free_in_vc x (vc.or (vc.subst y v P₁) (vc.subst y v P₂)),\n from this ▸ x_free_in_subst,\n have free_in_vc x (vc.subst y v P₁) ∨ free_in_vc x (vc.subst y v P₂),\n from free_in_vc.or.inv this,\n or.elim this (\n assume : free_in_vc x (vc.subst y v P₁),\n have x ≠ y ∧ free_in_vc x P₁, from P₁_ih this,\n show x ≠ y ∧ free_in_vc x (vc.or P₁ P₂), from ⟨this.left, free_in_vc.or₁ this.right⟩\n ) (\n assume : free_in_vc x (vc.subst y v P₂),\n have x ≠ y ∧ free_in_vc x P₂, from P₂_ih this,\n show x ≠ y ∧ free_in_vc x (vc.or P₁ P₂), from ⟨this.left, free_in_vc.or₂ this.right⟩\n )\n )},\n case vc.pre t₁ t₂ { from (\n have vc.subst y v (vc.pre t₁ t₂) = vc.pre (term.subst y v t₁) (term.subst y v t₂), by unfold vc.subst,\n have free_in_vc x (vc.pre (term.subst y v t₁) (term.subst y v t₂)),\n from this ▸ x_free_in_subst,\n have free_in_term x (term.subst y v t₁) ∨ free_in_term x (term.subst y v t₂),\n from free_in_vc.pre.inv this,\n or.elim this (\n assume : free_in_term x (term.subst y v t₁),\n have x ≠ y ∧ free_in_term x t₁, from free_of_subst_term this,\n show x ≠ y ∧ free_in_vc x (vc.pre t₁ t₂), from ⟨this.left, free_in_vc.pre₁ this.right⟩\n ) (\n assume : free_in_term x (term.subst y v t₂),\n have x ≠ y ∧ free_in_term x t₂, from free_of_subst_term this,\n show x ≠ y ∧ free_in_vc x (vc.pre t₁ t₂), from ⟨this.left, free_in_vc.pre₂ this.right⟩\n )\n )},\n case vc.pre₁ op t { from (\n have vc.subst y v (vc.pre₁ op t) = vc.pre₁ op (term.subst y v t), by unfold vc.subst,\n have free_in_vc x (vc.pre₁ op (term.subst y v t)), from this ▸ x_free_in_subst,\n have free_in_term x (term.subst y v t), from free_in_vc.pre₁.inv this,\n have x ≠ y ∧ free_in_term x t, from free_of_subst_term this,\n show x ≠ y ∧ free_in_vc x (vc.pre₁ op t), from ⟨this.left, free_in_vc.preop this.right⟩\n )},\n case vc.pre₂ op t₁ t₂ { from (\n have vc.subst y v (vc.pre₂ op t₁ t₂) = vc.pre₂ op (term.subst y v t₁) (term.subst y v t₂),\n by unfold vc.subst,\n have free_in_vc x (vc.pre₂ op (term.subst y v t₁) (term.subst y v t₂)), from this ▸ x_free_in_subst,\n have free_in_term x (term.subst y v t₁) ∨ free_in_term x (term.subst y v t₂),\n from free_in_vc.pre₂.inv this,\n or.elim this (\n assume : free_in_term x (term.subst y v t₁),\n have x ≠ y ∧ free_in_term x t₁, from free_of_subst_term this,\n show x ≠ y ∧ free_in_vc x (vc.pre₂ op t₁ t₂), from ⟨this.left, free_in_vc.preop₁ this.right⟩\n ) (\n assume : free_in_term x (term.subst y v t₂),\n have x ≠ y ∧ free_in_term x t₂, from free_of_subst_term this,\n show x ≠ y ∧ free_in_vc x (vc.pre₂ op t₁ t₂), from ⟨this.left, free_in_vc.preop₂ this.right⟩\n )\n )},\n case vc.post t₁ t₂ { from (\n have vc.subst y v (vc.post t₁ t₂) = vc.post (term.subst y v t₁) (term.subst y v t₂), by unfold vc.subst,\n have free_in_vc x (vc.post (term.subst y v t₁) (term.subst y v t₂)),\n from this ▸ x_free_in_subst,\n have free_in_term x (term.subst y v t₁) ∨ free_in_term x (term.subst y v t₂),\n from free_in_vc.post.inv this,\n or.elim this (\n assume : free_in_term x (term.subst y v t₁),\n have x ≠ y ∧ free_in_term x t₁, from free_of_subst_term this,\n show x ≠ y ∧ free_in_vc x (vc.post t₁ t₂), from ⟨this.left, free_in_vc.post₁ this.right⟩\n ) (\n assume : free_in_term x (term.subst y v t₂),\n have x ≠ y ∧ free_in_term x t₂, from free_of_subst_term this,\n show x ≠ y ∧ free_in_vc x (vc.post t₁ t₂), from ⟨this.left, free_in_vc.post₂ this.right⟩\n )\n )},\n case vc.univ z P' P'_ih { from (\n have h: vc.subst y v (vc.univ z P') = vc.univ z (if y = z then P' else vc.subst y v P'), by unfold vc.subst,\n if y_eq_z: y = z then (\n have (if y = z then P' else vc.subst y v P') = P', by simp[y_eq_z],\n have vc.subst y v (vc.univ z P') = vc.univ z P',\n from @eq.subst vc (λa, vc.subst y v (vc.univ z P') = vc.univ z a)\n (if y = z then P' else vc.subst y v P') P' this h,\n have h2: free_in_vc x (vc.univ z P'),\n from @eq.subst vc (λa, free_in_vc x a) (vc.subst y v (vc.univ z P')) (vc.univ z P') this x_free_in_subst,\n have x ≠ y, from (\n assume : x = y,\n have x = z, from eq.trans this y_eq_z,\n have free_in_vc x (vc.univ x P'),\n from @eq.subst var (λa, free_in_vc x (vc.univ a P')) z x this.symm h2,\n show «false», from (free_in_vc.univ.same.inv) this\n ),\n show x ≠ y ∧ free_in_vc x (vc.univ z P'), from ⟨this, h2⟩\n ) else (\n have (if y = z then P' else vc.subst y v P') = vc.subst y v P', by simp[y_eq_z],\n have vc.subst y v (vc.univ z P') = vc.univ z (vc.subst y v P'),\n from @eq.subst vc (λa, vc.subst y v (vc.univ z P') = vc.univ z a)\n (if y = z then P' else vc.subst y v P') (vc.subst y v P') this h,\n have free_in_vc x (vc.univ z (vc.subst y v P')), from this ▸ x_free_in_subst,\n have h2: x ≠ z ∧ free_in_vc x (vc.subst y v P'), from free_in_vc.univ.inv this,\n have x ≠ y ∧ free_in_vc x P', from P'_ih h2.right,\n show x ≠ y ∧ free_in_vc x (vc.univ z P'), from ⟨this.left, free_in_vc.univ h2.left this.right⟩\n )\n )}\n end\n\nlemma free_in_vc.subst2 {P: vc} {σ: env} {x y: var} {v: value}:\n free_in_vc x (vc.subst_env (σ[y↦v]) P) → x ≠ y ∧ free_in_vc x (vc.subst_env σ P) :=\n assume x_free: free_in_vc x (vc.subst_env (σ[y↦v]) P),\n have vc.subst_env (σ[y↦v]) P = vc.subst y v (vc.subst_env σ P), by unfold vc.subst_env,\n have free_in_vc x (vc.subst y v (vc.subst_env σ P)), from this ▸ x_free,\n show x ≠ y ∧ free_in_vc x (vc.subst_env σ P), from free_in_vc.subst this\n\nlemma free_in_vc.subst_env {P: vc} {σ: env} {x: var}:\n free_in_vc x (vc.subst_env σ P) → free_in_vc x P :=\n assume x_free_in_subst: free_in_vc x (vc.subst_env σ P),\n begin\n induction σ with σ' y v ih,\n show free_in_vc x P, from (\n have vc.subst_env env.empty P = P, by unfold vc.subst_env,\n show free_in_vc x P, from this ▸ x_free_in_subst\n ),\n show free_in_vc x P, from (\n have free_in_vc x (vc.subst_env σ' P), from (free_in_vc.subst2 x_free_in_subst).right,\n show free_in_vc x P, from ih this\n )\n end\n\nlemma term.subst_env.var.inv {x: var} {σ: env}:\n (term.subst_env σ x = x) ∨ (∃v:value, term.subst_env σ x = v) :=\n begin\n induction σ with σ' y v' ih,\n show (term.subst_env env.empty x = x) ∨ (∃v:value, term.subst_env env.empty x = v), from (\n have (term.subst_env env.empty x = x), by unfold term.subst_env,\n show (term.subst_env env.empty x = x) ∨ (∃v:value, term.subst_env env.empty x = v), from or.inl this\n ),\n show (term.subst_env (σ'[y↦v']) x = x) ∨ (∃v:value, term.subst_env (σ'[y↦v']) x = v), from (\n have tsubst: (term.subst_env (σ'[y↦v']) x = term.subst y v' (term.subst_env σ' x)),\n by unfold term.subst_env,\n have (term.subst_env σ' ↑x = ↑x ∨ ∃ (v : value), term.subst_env σ' ↑x = ↑v), from ih,\n or.elim this (\n assume σ'_x_is_x: term.subst_env σ' ↑x = ↑x,\n have h: (term.subst_env (σ'[y↦v']) x = term.subst y v' ↑x),\n from @eq.subst term (λa, term.subst_env (σ'[y↦v']) x = term.subst y v' a) (term.subst_env σ' x) x σ'_x_is_x tsubst,\n have h2: term.subst y v' (term.var x) = (if y = x then v' else x), by unfold term.subst,\n decidable.by_cases (\n assume x_is_y: x = y,\n have term.subst y v' (term.var x) = v', by { rw[x_is_y], simp[x_is_y] at h2, from h2 },\n have term.subst_env (σ'[y↦v']) x = v', from eq.trans h this,\n have (∃v:value, term.subst_env (σ'[y↦v']) x = v), from exists.intro v' this,\n show (term.subst_env (σ'[y↦v']) x = x) ∨ (∃v:value, term.subst_env (σ'[y↦v']) x = v), from or.inr this\n ) (\n assume : ¬(x = y),\n have ¬(y = x), from ne.symm this,\n have term.subst y v' (term.var x) = x, by { simp[this] at h2, from h2 },\n have term.subst_env (σ'[y↦v']) x = x, from eq.trans h this,\n show (term.subst_env (σ'[y↦v']) x = x) ∨ (∃v:value, term.subst_env (σ'[y↦v']) x = v), from or.inl this\n )\n ) (\n assume : ∃ (v : value), term.subst_env σ' ↑x = ↑v,\n let ⟨v, σ'_x_is_v⟩ := this in\n have h: (term.subst_env (σ'[y↦v']) x = term.subst y v' ↑v),\n from @eq.subst term (λa, term.subst_env (σ'[y↦v']) x = term.subst y v' a) (term.subst_env σ' x) v σ'_x_is_v tsubst,\n have term.subst y v' (term.value v) = ↑v, by unfold term.subst,\n have term.subst_env (σ'[y↦v']) x = v, from eq.trans h this,\n have (∃v:value, term.subst_env (σ'[y↦v']) x = v), from exists.intro v this,\n show (term.subst_env (σ'[y↦v']) x = x) ∨ (∃v:value, term.subst_env (σ'[y↦v']) x = v), from or.inr this\n )\n )\n end\n\nlemma term.subst_env.value {σ: env} {v: value}: term.subst_env σ v = v :=\nbegin\n induction σ with σ' x v' ih,\n show (term.subst_env env.empty v = v), by unfold term.subst_env,\n show (term.subst_env (σ'[x↦v']) v = v), from (\n have h: term.subst_env σ' v = v, from ih,\n have term.subst_env (σ'[x↦v']) v = term.subst x v' (term.subst_env σ' v), by unfold term.subst_env,\n have h2: term.subst_env (σ'[x↦v']) v = term.subst x v' v,\n from @eq.subst term (λa, term.subst_env (σ'[x↦v']) v = term.subst x v' a) (term.subst_env σ' v) v h this,\n have term.subst x v' (term.value v) = ↑v, by unfold term.subst,\n show term.subst_env (σ'[x↦v']) v = v, from eq.trans h2 this\n )\nend\n\nlemma term.subst_env.closed {σ: env} {t: term}: closed t → (term.subst_env σ t = t) :=\nbegin\n assume t_closed: closed t,\n induction σ with σ' x v' ih,\n show (term.subst_env env.empty t = t), by unfold term.subst_env,\n show (term.subst_env (σ'[x↦v']) t = t), from (\n have h: term.subst_env σ' t = t, from ih,\n have term.subst_env (σ'[x↦v']) t = term.subst x v' (term.subst_env σ' t), by unfold term.subst_env,\n have h2: term.subst_env (σ'[x↦v']) t = term.subst x v' t,\n from @eq.subst term (λa, term.subst_env (σ'[x↦v']) t = term.subst x v' a) (term.subst_env σ' t) t h this,\n have term.subst x v' t = t, from unchanged_of_subst_nonfree_term (t_closed x),\n show term.subst_env (σ'[x↦v']) t = t, from eq.trans h2 this\n )\nend\n\nlemma term.subst_env.var {σ: env} {x: var}:\n ((σ x = none) ↔ (term.subst_env σ x = x)) ∧ (∀v, (σ x = some v) ↔ (term.subst_env σ x = v)) :=\nbegin\n induction σ with σ' y v' ih,\n show (((env.empty x = none) ↔ (term.subst_env env.empty x = x))\n ∧ (∀v, (env.empty x = some v) ↔ (term.subst_env env.empty x = v))), by begin\n split,\n show ((env.empty x = none) ↔ (term.subst_env env.empty x = x)), by begin\n split,\n show ((env.empty x = none) → (term.subst_env env.empty x = x)), by begin\n assume _,\n show (term.subst_env env.empty x = x), by unfold term.subst_env\n end,\n show ((term.subst_env env.empty x = x) → (env.empty x = none)), by begin\n assume _,\n show (env.apply env.empty x = none), by unfold env.apply\n end\n end,\n show ∀v, ((env.empty x = some v) ↔ (term.subst_env env.empty x = v)), by begin\n assume v,\n split,\n show ((env.empty x = some v) → (term.subst_env env.empty x = v)), by begin\n assume env_has_some: (env.apply (env.empty) x = some v),\n have env_has_none: (env.apply env.empty x = none), by unfold env.apply,\n have : (some v = none), from env_has_some ▸ env_has_none,\n contradiction \n end,\n show ((term.subst_env env.empty x = v) → (env.empty x = some v)), by begin\n assume subst_is_v: (term.subst_env env.empty x = v),\n have : (term.subst_env env.empty x = x), by unfold term.subst_env,\n have : (↑v = ↑x), from eq.trans subst_is_v.symm this,\n contradiction \n end\n end\n end,\n show ((((σ'[y↦v']) x = none) ↔ (term.subst_env (σ'[y↦v']) x = x))\n ∧ (∀v, ((σ'[y↦v']) x = some v) ↔ (term.subst_env (σ'[y↦v']) x = v))), by begin\n have tsubst: (term.subst_env (σ'[y↦v']) x = term.subst y v' (term.subst_env σ' x)),\n by unfold term.subst_env,\n have app: ((σ'[y↦v']).apply x = (if y = x ∧ option.is_none (σ'.apply x) then v' else σ'.apply x)),\n by unfold env.apply,\n split,\n show (((σ'[y↦v']) x = none) ↔ (term.subst_env (σ'[y↦v']) x = x)), by begin\n split,\n show (((σ'[y↦v']) x = none) → (term.subst_env (σ'[y↦v']) x = x)), by begin\n assume σ'_does_not_have_x: ((σ'[y↦v']) x = none),\n by_cases (y = x ∧ option.is_none (σ'.apply x)) with h,\n show (term.subst_env (σ'[y↦v']) x = x), from\n have ((σ'[y↦v']).apply x) = v', by { simp[h] at app, rw[h.left], from app },\n have some v' = none, from eq.trans this.symm σ'_does_not_have_x,\n by contradiction,\n show (term.subst_env (σ'[y↦v']) x = x), from\n have ((σ'[y↦v']).apply x) = σ'.apply x, by { simp[h] at app, from app },\n have σ'_x_is_none: σ'.apply x = none, from eq.trans this.symm σ'_does_not_have_x,\n have term.subst_env σ' x = x, from ih.left.mp σ'_x_is_none,\n have h2: term.subst_env (σ'[y↦v']) x = term.subst y v' x,\n from @eq.subst term (λa, term.subst_env (σ'[y↦v']) x = term.subst y v' a) (term.subst_env σ' x) x this tsubst,\n have h3: term.subst y v' (term.var x) = (if y = x then v' else x), by unfold term.subst,\n have ¬(y = x) ∨ ¬(option.is_none (env.apply σ' x)) , from not_and_distrib.mp h,\n have ¬(y = x), from this.elim id ( \n assume : ¬(option.is_none (env.apply σ' x)),\n have (env.apply σ' x) ≠ none, from option.is_none.ninv.mpr this,\n show ¬(y = x), from absurd σ'_x_is_none this\n ),\n have term.subst y v' (term.var x) = x, by { simp[this] at h3, from h3 },\n show (term.subst_env (σ'[y↦v']) x = x), from eq.trans h2 this\n end,\n show ((term.subst_env (σ'[y↦v']) x = x) → ((σ'[y↦v']) x = none)), from (\n assume h: term.subst_env (σ'[y↦v']) x = x,\n have h2: term.subst y v' (term.subst_env σ' x) = x, from eq.trans tsubst.symm h,\n have (term.subst_env σ' x = x) ∨ (∃v:value, term.subst_env σ' x = v), from term.subst_env.var.inv,\n or.elim this (\n assume : term.subst_env σ' x = x,\n have σ'_x_is_none: σ' x = none, from ih.left.mpr this,\n have h3: term.subst_env (σ'[y↦v']) x = term.subst y v' x,\n from @eq.subst term (λa, term.subst_env (σ'[y↦v']) x = term.subst y v' a) (term.subst_env σ' x) x this tsubst,\n have h4: term.subst y v' (term.var x) = (if y = x then v' else x), by unfold term.subst,\n decidable.by_cases (\n assume : x = y,\n have y_eq_x: y = x, from eq.symm this,\n have term.subst y v' (term.var x) = v', by { simp[y_eq_x] at h4, rw[y_eq_x], from h4 },\n have term.subst_env (σ'[y↦v']) x = v', from eq.trans h3 this,\n have ↑x = ↑v', from eq.trans h.symm this,\n show (σ'[y↦v']) x = none, by contradiction\n ) (\n assume : ¬(x = y),\n have y_neq_x: ¬(y = x), from ne.symm this,\n have (σ'[y↦v']).apply x = σ'.apply x, by { simp[y_neq_x] at app, from app },\n show (σ'[y↦v']).apply x = none, from eq.trans this σ'_x_is_none\n )\n ) (\n assume : (∃v'':value, term.subst_env σ' x = v''),\n let ⟨v'', σ'_x_is_v''⟩ := this in\n have h3: (term.subst_env (σ'[y↦v']) x = term.subst y v' ↑v''),\n from @eq.subst term (λa, term.subst_env (σ'[y↦v']) x = term.subst y v' a) (term.subst_env σ' x) v'' σ'_x_is_v'' tsubst,\n have term.subst y v' (term.value v'') = ↑v'', by unfold term.subst,\n have term.subst_env (σ'[y↦v']) x = ↑v'', from eq.trans h3 this,\n have ↑x = ↑v'', from eq.trans h.symm this,\n show (σ'[y↦v']) x = none, by contradiction\n )\n )\n end,\n show (∀v, ((σ'[y↦v']) x = some v) ↔ (term.subst_env (σ'[y↦v']) x = v)), by begin\n assume v,\n split,\n show (((σ'[y↦v']) x = some v) → (term.subst_env (σ'[y↦v']) x = v)), by begin\n assume env_has_x: ((σ'[y↦v']) x = some v),\n have app: ((σ'[y↦v']).apply x = (if y = x ∧ option.is_none (σ'.apply x) then v' else σ'.apply x)),\n by unfold env.apply,\n by_cases (y = x ∧ option.is_none (σ'.apply x)) with h,\n show (term.subst_env (σ'[y↦v']) ↑x = ↑v), from (\n have ((σ'[y↦v']).apply x = v'), by { simp[h] at app, rw[h.left], from app },\n have some v' = some v, from eq.trans this.symm env_has_x,\n have v'_is_v: v' = v, by injection this,\n have option.is_none (σ'.apply x), from h.right,\n have σ'.apply x = none, from option.is_none.inv.mpr this,\n have σ'_x_is_x: term.subst_env σ' x = x, from ih.left.mp this,\n have term.subst_env (σ'[y↦v']) x = term.subst y v' (term.subst_env σ' x),\n by unfold term.subst_env,\n have h2: term.subst_env (σ'[y↦v']) x = term.subst y v' (term.var x),\n from @eq.subst term (λa, term.subst_env (σ'[y↦v']) x = term.subst y v' a) (term.subst_env σ' x) x σ'_x_is_x tsubst,\n have h3: term.subst y v' (term.var x) = (if y = x then v' else x), by unfold term.subst,\n have term.subst y v' (term.var x) = v', by { simp[h.left] at h3, rw[h.left], from h3 },\n show term.subst_env (σ'[y↦v']) x = v, from v'_is_v ▸ eq.trans h2 this\n ),\n show (term.subst_env (σ'[y↦v']) ↑x = ↑v), from (\n have (σ'[y↦v']).apply x = σ'.apply x, by { simp [h] at app, from app },\n have σ'.apply x = v, from eq.trans this.symm env_has_x,\n have σ'_x_is_v: term.subst_env σ' ↑x = ↑v, from (ih.right v).mp this,\n have term.subst_env (σ'[y↦v']) x = term.subst y v' (term.subst_env σ' x),\n by unfold term.subst_env,\n have h2: term.subst_env (σ'[y↦v']) x = term.subst y v' v,\n from @eq.subst term (λa, term.subst_env (σ'[y↦v']) x = term.subst y v' a) (term.subst_env σ' x) v σ'_x_is_v tsubst,\n have term.subst y v' (term.value v) = ↑v, by unfold term.subst,\n show term.subst_env (σ'[y↦v']) x = v, from eq.trans h2 this\n )\n end,\n show ((term.subst_env (σ'[y↦v']) x = v) → ((σ'[y↦v']) x = some v)), from (\n assume h: term.subst_env (σ'[y↦v']) x = v,\n have h2: term.subst y v' (term.subst_env σ' x) = v, from eq.trans tsubst.symm h,\n have (term.subst_env σ' x = x) ∨ (∃v:value, term.subst_env σ' x = v), from term.subst_env.var.inv,\n or.elim this (\n assume : term.subst_env σ' x = x,\n have σ'_x_is_none: σ' x = none, from ih.left.mpr this,\n have h3: term.subst_env (σ'[y↦v']) x = term.subst y v' x,\n from @eq.subst term (λa, term.subst_env (σ'[y↦v']) x = term.subst y v' a) (term.subst_env σ' x) x this tsubst,\n have h4: term.subst y v' (term.var x) = (if y = x then v' else x), by unfold term.subst,\n decidable.by_cases (\n assume x_is_y: x = y,\n have term.subst y v' (term.var x) = (if x = x then v' else x),\n from @eq.subst var (λa, term.subst y v' (term.var x) = (if a = x then v' else x)) y x x_is_y.symm h4,\n have term.subst y v' (term.var x) = v', by { simp at this, from this },\n have term.subst_env (σ'[y↦v']) x = v', from eq.trans h3 this,\n have ↑v = ↑v', from eq.trans h.symm this,\n have v_is_v': v = v', by injection this,\n have opt_is_none: option.is_none (env.apply σ' x), from option.is_none.inv.mp σ'_x_is_none,\n have (if y = x ∧ option.is_none (σ'.apply x) then ↑v' else σ'.apply x) = v',\n by { simp[x_is_y.symm], simp[opt_is_none] },\n have (σ'[y↦v']).apply x = v', from eq.trans app this,\n have (σ'[y↦v']) x = some v', from this,\n show (σ'[y↦v']) x = some v, from @eq.subst value (λa, (σ'[y↦v']) x = some a) v' v v_is_v'.symm this\n ) (\n assume : ¬(x = y),\n have ¬(y = x), from ne.symm this,\n have term.subst y v' (term.var x) = x, by { simp[this] at h4, from h4 },\n have ↑v = ↑x, from eq.trans (eq.trans h.symm h3) this,\n show ((σ'[y↦v']) x = some v), by contradiction\n )\n ) (\n assume : (∃v'':value, term.subst_env σ' x = v''),\n let ⟨v'', σ'_x_is_v''⟩ := this in\n have h3: (term.subst_env (σ'[y↦v']) x = term.subst y v' ↑v''),\n from @eq.subst term (λa, term.subst_env (σ'[y↦v']) x = term.subst y v' a) (term.subst_env σ' x) v'' σ'_x_is_v'' tsubst,\n have term.subst y v' (term.value v'') = ↑v'', by unfold term.subst,\n have term.subst_env (σ'[y↦v']) x = ↑v'', from eq.trans h3 this,\n have v_is_v'': ↑v = ↑v'', from eq.trans h.symm this,\n have term.subst_env σ' x = v,\n from @eq.subst term (λa, term.subst_env σ' x = a) v'' v v_is_v''.symm σ'_x_is_v'',\n have σ'_x_app_is_v: env.apply σ' x = some v, from (ih.right v).mpr this,\n have opt_is_not_none: ¬ option.is_none (env.apply σ' x),\n from option.some_iff_not_none.mp (option.is_some_iff_exists.mpr (exists.intro v σ'_x_app_is_v)),\n have (if y = x ∧ option.is_none (σ'.apply x) then ↑v' else σ'.apply x) = σ'.apply x,\n by { simp[opt_is_not_none] },\n have (σ'[y↦v']) x = σ'.apply x, from eq.trans app this,\n show (σ'[y↦v']) x = some v, from eq.trans this σ'_x_app_is_v\n )\n )\n end\n end\nend\n\nlemma term.not_free_of_subst {x: var} {v: value} {t: term}: x ∉ FV (term.subst x v t) :=\n assume x_free: x ∈ FV (term.subst x v t),\n begin\n induction t with a,\n\n show «false», by begin -- term.value\n unfold term.subst at x_free,\n cases x_free\n end,\n\n show «false», by begin -- term.var\n unfold term.subst at x_free,\n by_cases (x = a) with h,\n simp[h] at x_free,\n cases x_free,\n simp[h] at x_free,\n cases x_free,\n contradiction\n end,\n\n show «false», by begin -- term.unop\n unfold term.subst at x_free,\n have h, from free_in_term.unop.inv x_free,\n contradiction\n end,\n\n show «false», by begin -- term.binop\n unfold term.subst at x_free,\n have h, from free_in_term.binop.inv x_free,\n cases h with h1 h2,\n contradiction,\n contradiction\n end,\n\n show «false», by begin -- term.app\n unfold term.subst at x_free,\n have h, from free_in_term.app.inv x_free,\n cases h with h1 h2,\n contradiction,\n contradiction\n end\n end\n\nlemma term.not_free_of_substt {x: var} {t₁ t₂: term}: closed t₁ → x ∉ FV (term.substt x t₁ t₂) :=\n assume t_closed: closed t₁,\n assume x_free: x ∈ FV (term.substt x t₁ t₂),\n begin\n induction t₂ with a,\n\n show «false», by begin -- term.value\n unfold term.substt at x_free,\n cases x_free\n end,\n\n show «false», by begin -- term.var\n unfold term.substt at x_free,\n by_cases (x = a) with h,\n simp[h] at x_free,\n have : a ∉ FV t₁, from t_closed a,\n contradiction,\n simp[h] at x_free,\n cases x_free,\n contradiction\n end,\n\n show «false», by begin -- term.unop\n unfold term.substt at x_free,\n have h, from free_in_term.unop.inv x_free,\n contradiction\n end,\n\n show «false», by begin -- term.binop\n unfold term.substt at x_free,\n have h, from free_in_term.binop.inv x_free,\n cases h with h1 h2,\n contradiction,\n contradiction\n end,\n\n show «false», by begin -- term.app\n unfold term.substt at x_free,\n have h, from free_in_term.app.inv x_free,\n cases h with h1 h2,\n contradiction,\n contradiction\n end\n end\n\nlemma term.not_free_of_subst_env {x: var} {σ: env} {t: term}: x ∈ σ → x ∉ FV (term.subst_env σ t) :=\n assume x_in_σ: x ∈ σ,\n assume x_free: x ∈ FV (term.subst_env σ t),\n begin\n induction σ with σ' y v ih,\n\n -- env.empty\n show «false», by cases x_in_σ,\n\n -- σ'[x↦v]\n show «false», from (\n have term.subst_env (σ'[y↦v]) t = term.subst y v (term.subst_env σ' t), by unfold term.subst_env,\n have x ∈ FV (term.subst y v (term.subst_env σ' t)), from this ▸ x_free,\n have x_neq_y: x ≠ y, from (free_of_subst_term this).left,\n have h: x ∈ FV (term.subst_env σ' t), from (free_of_subst_term this).right,\n have x = y ∨ x ∈ σ', from env.contains.inv x_in_σ,\n or.elim this (\n assume : x = y,\n show «false», from x_neq_y this\n ) (\n assume : x ∈ σ',\n have x ∉ FV (term.subst_env σ' t), from ih this,\n show «false», from this h\n )\n )\n end\n\nlemma prop.not_free_of_subst {x: var} {v: value} {P: prop}: x ∉ FV (prop.subst x v P) :=\n assume x_free: x ∈ FV (prop.subst x v P),\n begin\n induction P,\n case prop.term t { from (\n have prop.subst x v (prop.term t) = (term.subst x v t), by unfold prop.subst,\n have free_in_prop x (prop.term (term.subst x v t)), from this ▸ x_free,\n have x ∈ FV (term.subst x v t), from free_in_prop.term.inv this,\n show «false», from term.not_free_of_subst this\n )},\n case prop.not P₁ P₁_ih { from (\n have prop.subst x v (prop.not P₁) = (P₁.subst x v).not, by unfold prop.subst,\n have x ∈ FV (P₁.subst x v).not, from this ▸ x_free,\n have x ∈ FV (P₁.subst x v), from free_in_prop.not.inv this,\n show «false», from P₁_ih this\n )},\n case prop.and P₁ P₂ P₁_ih P₂_ih { from (\n have prop.subst x v (prop.and P₁ P₂) = (P₁.subst x v ⋀ P₂.subst x v), by unfold prop.subst,\n have x ∈ FV (P₁.subst x v ⋀ P₂.subst x v), from this ▸ x_free,\n or.elim (free_in_prop.and.inv this) (\n assume : x ∈ FV (P₁.subst x v),\n show «false», from P₁_ih this\n ) (\n assume : x ∈ FV (P₂.subst x v),\n show «false», from P₂_ih this\n )\n )},\n case prop.or P₁ P₂ P₁_ih P₂_ih { from (\n have prop.subst x v (prop.or P₁ P₂) = (P₁.subst x v ⋁ P₂.subst x v), by unfold prop.subst,\n have x ∈ FV (P₁.subst x v ⋁ P₂.subst x v), from this ▸ x_free,\n or.elim (free_in_prop.or.inv this) (\n assume : x ∈ FV (P₁.subst x v),\n show «false», from P₁_ih this\n ) (\n assume : x ∈ FV (P₂.subst x v),\n show «false», from P₂_ih this\n )\n )},\n case prop.pre t₁ t₂ { from (\n have prop.subst x v (prop.pre t₁ t₂) = prop.pre (t₁.subst x v) (t₂.subst x v), by unfold prop.subst,\n have x ∈ FV (prop.pre (t₁.subst x v) (t₂.subst x v)), from this ▸ x_free,\n or.elim (free_in_prop.pre.inv this) (\n assume : x ∈ FV (t₁.subst x v),\n show «false», from term.not_free_of_subst this\n ) (\n assume : x ∈ FV (t₂.subst x v),\n show «false», from term.not_free_of_subst this\n )\n )},\n case prop.pre₁ op t { from (\n have prop.subst x v (prop.pre₁ op t) = prop.pre₁ op (t.subst x v), by unfold prop.subst,\n have x ∈ FV (prop.pre₁ op (t.subst x v)), from this ▸ x_free,\n have x ∈ FV (t.subst x v), from free_in_prop.pre₁.inv this,\n show «false», from term.not_free_of_subst this\n )},\n case prop.pre₂ op t₁ t₂ { from (\n have prop.subst x v (prop.pre₂ op t₁ t₂) = prop.pre₂ op (t₁.subst x v) (t₂.subst x v),\n by unfold prop.subst,\n have x ∈ FV (prop.pre₂ op (t₁.subst x v) (t₂.subst x v)), from this ▸ x_free,\n or.elim (free_in_prop.pre₂.inv this) (\n assume : x ∈ FV (t₁.subst x v),\n show «false», from term.not_free_of_subst this\n ) (\n assume : x ∈ FV (t₂.subst x v),\n show «false», from term.not_free_of_subst this\n )\n )},\n case prop.post t₁ t₂ { from (\n have prop.subst x v (prop.post t₁ t₂) = prop.post (t₁.subst x v) (t₂.subst x v), by unfold prop.subst,\n have x ∈ FV (prop.post (t₁.subst x v) (t₂.subst x v)), from this ▸ x_free,\n or.elim (free_in_prop.post.inv this) (\n assume : x ∈ FV (t₁.subst x v),\n show «false», from term.not_free_of_subst this\n ) (\n assume : x ∈ FV (t₂.subst x v),\n show «false», from term.not_free_of_subst this\n )\n )},\n case prop.call t { from (\n have prop.subst x v (prop.call t) = prop.call (t.subst x v), by unfold prop.subst,\n have x ∈ FV (prop.call (t.subst x v)), from this ▸ x_free,\n have x ∈ FV (t.subst x v), from free_in_prop.call.inv this,\n show «false», from term.not_free_of_subst this\n )},\n case prop.forallc y P₁ P₁_ih { from (\n have prop.subst x v (prop.forallc y P₁) = prop.forallc y (if x = y then P₁ else P₁.subst x v),\n by unfold prop.subst,\n have x ∈ FV (prop.forallc y (if x = y then P₁ else P₁.subst x v)),\n from this ▸ x_free,\n have y_neq_x: x ≠ y, from (free_in_prop.forallc.inv this).left,\n have x ∈ FV (prop.forallc y (P₁.subst x v)), by { simp[y_neq_x] at this, from this },\n have x ∈ FV (P₁.subst x v), from (free_in_prop.forallc.inv this).right,\n show «false», from P₁_ih this\n )},\n case prop.exis y P₁ P₁_ih { from (\n have prop.subst x v (prop.exis y P₁)\n = prop.exis y (if x = y then P₁ else P₁.subst x v), by unfold prop.subst,\n have x ∈ FV (prop.exis y (if x = y then P₁ else P₁.subst x v)), from this ▸ x_free,\n have y_neq_x: x ≠ y, from (free_in_prop.exis.inv this).left,\n have x ∈ FV (prop.exis y (P₁.subst x v)), by { simp[y_neq_x] at this, from this },\n have x ∈ FV (P₁.subst x v), from (free_in_prop.exis.inv this).right,\n show «false», from P₁_ih this\n )}\n end\n\nlemma prop.not_free_of_subst_env {x: var} {σ: env} {P: prop}: x ∈ σ → x ∉ FV (prop.subst_env σ P) :=\n assume x_in_σ: x ∈ σ,\n assume x_free: x ∈ FV (prop.subst_env σ P),\n begin\n induction σ with σ' y v ih,\n\n -- env.empty\n show «false», by cases x_in_σ,\n\n -- σ'[x↦v]\n show «false», from (\n have prop.subst_env (σ'[y↦v]) P = prop.subst y v (prop.subst_env σ' P), by unfold prop.subst_env,\n have x ∈ FV (prop.subst y v (prop.subst_env σ' P)), from this ▸ x_free,\n have x_neq_y: x ≠ y, from (free_of_subst_prop this).left,\n have h: x ∈ FV (prop.subst_env σ' P), from (free_of_subst_prop this).right,\n have x = y ∨ x ∈ σ', from env.contains.inv x_in_σ,\n or.elim this (\n assume : x = y,\n show «false», from x_neq_y this\n ) (\n assume : x ∈ σ',\n have x ∉ FV (prop.subst_env σ' P), from ih this,\n show «false», from this h\n )\n )\n end\n\nlemma term.closed_of_closed_subst {σ: env} {t: term}: closed_subst σ t → closed (term.subst_env σ t) :=\n assume t_closed_subst: closed_subst σ t,\n show closed (term.subst_env σ t), from (\n assume x: var,\n assume h1: x ∈ FV (term.subst_env σ t),\n have x ∈ FV t, from (free_of_subst_env_term h1).left,\n have x ∈ σ.dom, from t_closed_subst this,\n have x ∈ σ, from this,\n have h2: x ∉ FV (term.subst_env σ t), from term.not_free_of_subst_env this,\n show «false», from h2 h1\n )\n\nlemma prop.closed_of_closed_subst {σ: env} {P: prop}: closed_subst σ P → closed (prop.subst_env σ P) :=\n assume P_closed_subst: closed_subst σ P,\n show closed (prop.subst_env σ P), from (\n assume x: var,\n assume h1: x ∈ FV (prop.subst_env σ P),\n have x ∈ FV P, from free_of_subst_env h1,\n have x ∈ σ.dom, from P_closed_subst this,\n have x ∈ σ, from this,\n have h2: x ∉ FV (prop.subst_env σ P), from prop.not_free_of_subst_env this,\n show «false», from h2 h1\n )\n\nlemma vc.not_free_of_subst {x: var} {v: value} {P: vc}: x ∉ FV (vc.subst x v P) :=\n assume x_free: x ∈ FV (vc.subst x v P),\n begin\n induction P,\n case vc.term t { from (\n have vc.subst x v (vc.term t) = (term.subst x v t), by unfold vc.subst,\n have free_in_vc x (vc.term (term.subst x v t)), from this ▸ x_free,\n have x ∈ FV (term.subst x v t), from free_in_vc.term.inv this,\n show «false», from term.not_free_of_subst this\n )},\n case vc.not P₁ P₁_ih { from (\n have vc.subst x v (vc.not P₁) = (P₁.subst x v).not, by unfold vc.subst,\n have x ∈ FV (P₁.subst x v).not, from this ▸ x_free,\n have x ∈ FV (P₁.subst x v), from free_in_vc.not.inv this,\n show «false», from P₁_ih this\n )},\n case vc.and P₁ P₂ P₁_ih P₂_ih { from (\n have vc.subst x v (vc.and P₁ P₂) = (P₁.subst x v ⋀ P₂.subst x v), by unfold vc.subst,\n have x ∈ FV (P₁.subst x v ⋀ P₂.subst x v), from this ▸ x_free,\n or.elim (free_in_vc.and.inv this) (\n assume : x ∈ FV (P₁.subst x v),\n show «false», from P₁_ih this\n ) (\n assume : x ∈ FV (P₂.subst x v),\n show «false», from P₂_ih this\n )\n )},\n case vc.or P₁ P₂ P₁_ih P₂_ih { from (\n have vc.subst x v (vc.or P₁ P₂) = (P₁.subst x v ⋁ P₂.subst x v), by unfold vc.subst,\n have x ∈ FV (P₁.subst x v ⋁ P₂.subst x v), from this ▸ x_free,\n or.elim (free_in_vc.or.inv this) (\n assume : x ∈ FV (P₁.subst x v),\n show «false», from P₁_ih this\n ) (\n assume : x ∈ FV (P₂.subst x v),\n show «false», from P₂_ih this\n )\n )},\n case vc.pre t₁ t₂ { from (\n have vc.subst x v (vc.pre t₁ t₂) = vc.pre (t₁.subst x v) (t₂.subst x v), by unfold vc.subst,\n have x ∈ FV (vc.pre (t₁.subst x v) (t₂.subst x v)), from this ▸ x_free,\n or.elim (free_in_vc.pre.inv this) (\n assume : x ∈ FV (t₁.subst x v),\n show «false», from term.not_free_of_subst this\n ) (\n assume : x ∈ FV (t₂.subst x v),\n show «false», from term.not_free_of_subst this\n )\n )},\n case vc.pre₁ op t { from (\n have vc.subst x v (vc.pre₁ op t) = vc.pre₁ op (t.subst x v), by unfold vc.subst,\n have x ∈ FV (vc.pre₁ op (t.subst x v)), from this ▸ x_free,\n have x ∈ FV (t.subst x v), from free_in_vc.pre₁.inv this,\n show «false», from term.not_free_of_subst this\n )},\n case vc.pre₂ op t₁ t₂ { from (\n have vc.subst x v (vc.pre₂ op t₁ t₂) = vc.pre₂ op (t₁.subst x v) (t₂.subst x v),\n by unfold vc.subst,\n have x ∈ FV (vc.pre₂ op (t₁.subst x v) (t₂.subst x v)), from this ▸ x_free,\n or.elim (free_in_vc.pre₂.inv this) (\n assume : x ∈ FV (t₁.subst x v),\n show «false», from term.not_free_of_subst this\n ) (\n assume : x ∈ FV (t₂.subst x v),\n show «false», from term.not_free_of_subst this\n )\n )},\n case vc.post t₁ t₂ { from (\n have vc.subst x v (vc.post t₁ t₂) = vc.post (t₁.subst x v) (t₂.subst x v), by unfold vc.subst,\n have x ∈ FV (vc.post (t₁.subst x v) (t₂.subst x v)), from this ▸ x_free,\n or.elim (free_in_vc.post.inv this) (\n assume : x ∈ FV (t₁.subst x v),\n show «false», from term.not_free_of_subst this\n ) (\n assume : x ∈ FV (t₂.subst x v),\n show «false», from term.not_free_of_subst this\n )\n )},\n case vc.univ y P₁ P₁_ih { from (\n have vc.subst x v (vc.univ y P₁)\n = vc.univ y (if x = y then P₁ else P₁.subst x v), by unfold vc.subst,\n have x ∈ FV (vc.univ y (if x = y then P₁ else P₁.subst x v)), from this ▸ x_free,\n have y_neq_x: x ≠ y, from (free_in_vc.univ.inv this).left,\n have x ∈ FV (vc.univ y (P₁.subst x v)), by { simp[y_neq_x] at this, from this },\n have x ∈ FV (P₁.subst x v), from (free_in_vc.univ.inv this).right,\n show «false», from P₁_ih this\n )}\n end\n\nlemma vc.not_free_of_substt {x: var} {t: term} {P: vc}: closed t → x ∉ FV (vc.substt x t P) :=\n assume t_closed: closed t,\n assume x_free: x ∈ FV (vc.substt x t P),\n begin\n induction P,\n case vc.term t₂ { from (\n have vc.substt x t (vc.term t₂) = (term.substt x t t₂), by unfold vc.substt,\n have free_in_vc x (vc.term (term.substt x t t₂)), from this ▸ x_free,\n have x ∈ FV (term.substt x t t₂), from free_in_vc.term.inv this,\n show «false», from term.not_free_of_substt t_closed this\n )},\n case vc.not P₁ P₁_ih { from (\n have vc.substt x t (vc.not P₁) = (P₁.substt x t).not, by unfold vc.substt,\n have x ∈ FV (P₁.substt x t).not, from this ▸ x_free,\n have x ∈ FV (P₁.substt x t), from free_in_vc.not.inv this,\n show «false», from P₁_ih this\n )},\n case vc.and P₁ P₂ P₁_ih P₂_ih { from (\n have vc.substt x t (vc.and P₁ P₂) = (P₁.substt x t ⋀ P₂.substt x t), by unfold vc.substt,\n have x ∈ FV (P₁.substt x t ⋀ P₂.substt x t), from this ▸ x_free,\n or.elim (free_in_vc.and.inv this) (\n assume : x ∈ FV (P₁.substt x t),\n show «false», from P₁_ih this\n ) (\n assume : x ∈ FV (P₂.substt x t),\n show «false», from P₂_ih this\n )\n )},\n case vc.or P₁ P₂ P₁_ih P₂_ih { from (\n have vc.substt x t (vc.or P₁ P₂) = (P₁.substt x t ⋁ P₂.substt x t), by unfold vc.substt,\n have x ∈ FV (P₁.substt x t ⋁ P₂.substt x t), from this ▸ x_free,\n or.elim (free_in_vc.or.inv this) (\n assume : x ∈ FV (P₁.substt x t),\n show «false», from P₁_ih this\n ) (\n assume : x ∈ FV (P₂.substt x t),\n show «false», from P₂_ih this\n )\n )},\n case vc.pre t₁ t₂ { from (\n have vc.substt x t (vc.pre t₁ t₂) = vc.pre (term.substt x t t₁) (term.substt x t t₂), by unfold vc.substt,\n have x ∈ FV (vc.pre (term.substt x t t₁) (term.substt x t t₂)), from this ▸ x_free,\n or.elim (free_in_vc.pre.inv this) (\n assume : x ∈ FV (term.substt x t t₁),\n show «false», from term.not_free_of_substt t_closed this\n ) (\n assume : x ∈ FV (term.substt x t t₂),\n show «false», from term.not_free_of_substt t_closed this\n )\n )},\n case vc.pre₁ op t₁ { from (\n have vc.substt x t (vc.pre₁ op t₁) = vc.pre₁ op (term.substt x t t₁), by unfold vc.substt,\n have x ∈ FV (vc.pre₁ op (term.substt x t t₁)), from this ▸ x_free,\n have x ∈ FV (term.substt x t t₁), from free_in_vc.pre₁.inv this,\n show «false», from term.not_free_of_substt t_closed this\n )},\n case vc.pre₂ op t₁ t₂ { from (\n have vc.substt x t (vc.pre₂ op t₁ t₂) = vc.pre₂ op (term.substt x t t₁) (term.substt x t t₂),\n by unfold vc.substt,\n have x ∈ FV (vc.pre₂ op (term.substt x t t₁) (term.substt x t t₂)), from this ▸ x_free,\n or.elim (free_in_vc.pre₂.inv this) (\n assume : x ∈ FV (term.substt x t t₁),\n show «false», from term.not_free_of_substt t_closed this\n ) (\n assume : x ∈ FV (term.substt x t t₂),\n show «false», from term.not_free_of_substt t_closed this\n )\n )},\n case vc.post t₁ t₂ { from (\n have vc.substt x t (vc.post t₁ t₂) = vc.post (term.substt x t t₁) (term.substt x t t₂),\n by unfold vc.substt,\n have x ∈ FV (vc.post (term.substt x t t₁) (term.substt x t t₂)), from this ▸ x_free,\n or.elim (free_in_vc.post.inv this) (\n assume : x ∈ FV (term.substt x t t₁),\n show «false», from term.not_free_of_substt t_closed this\n ) (\n assume : x ∈ FV (term.substt x t t₂),\n show «false», from term.not_free_of_substt t_closed this\n )\n )},\n case vc.univ y P₁ P₁_ih { from (\n have vc.substt x t (vc.univ y P₁)\n = vc.univ y (if x = y then P₁ else P₁.substt x t), by unfold vc.substt,\n have x ∈ FV (vc.univ y (if x = y then P₁ else P₁.substt x t)), from this ▸ x_free,\n have y_neq_x: x ≠ y, from (free_in_vc.univ.inv this).left,\n have x ∈ FV (vc.univ y (P₁.substt x t)), by { simp[y_neq_x] at this, from this },\n have x ∈ FV (P₁.substt x t), from (free_in_vc.univ.inv this).right,\n show «false», from P₁_ih this\n )}\n end\n\nlemma vc.not_free_of_subst_env {x: var} {σ: env} {P: vc}: x ∈ σ → x ∉ FV (vc.subst_env σ P) :=\n assume x_in_σ: x ∈ σ,\n assume x_free: x ∈ FV (vc.subst_env σ P),\n begin\n induction σ with σ' y v ih,\n\n -- env.empty\n show «false», by cases x_in_σ,\n\n -- σ'[x↦v]\n show «false», from (\n have vc.subst_env (σ'[y↦v]) P = vc.subst y v (vc.subst_env σ' P), by unfold vc.subst_env,\n have x ∈ FV (vc.subst y v (vc.subst_env σ' P)), from this ▸ x_free,\n have x_neq_y: x ≠ y, from (free_in_vc.subst this).left,\n have h: x ∈ FV (vc.subst_env σ' P), from (free_in_vc.subst this).right,\n have x = y ∨ x ∈ σ', from env.contains.inv x_in_σ,\n or.elim this (\n assume : x = y,\n show «false», from x_neq_y this\n ) (\n assume : x ∈ σ',\n have x ∉ FV (vc.subst_env σ' P), from ih this,\n show «false», from this h\n )\n )\n end\n\nlemma vc.closed_of_closed_subst {σ: env} {P: vc}: closed_subst σ P → closed (vc.subst_env σ P) :=\n assume P_closed_subst: closed_subst σ P,\n show closed (vc.subst_env σ P), from (\n assume x: var,\n assume h1: x ∈ FV (vc.subst_env σ P),\n have x ∈ FV P, from free_in_vc.subst_env h1,\n have x ∈ σ.dom, from P_closed_subst this,\n have x ∈ σ, from this,\n have h2: x ∉ FV (vc.subst_env σ P), from vc.not_free_of_subst_env this,\n show «false», from h2 h1\n )\n\nlemma term.free_of_diff_subst {x y: var} {v: value} {t: term}: x ∈ FV t → x ≠ y → x ∈ FV (term.subst y v t) :=\n assume x_free: x ∈ FV t,\n assume x_neq_y: x ≠ y,\n show x ∈ FV (term.subst y v t), from begin\n induction t with v' z unop t₁ t₁_ih binop t₂ t₃ t₂_ih t₃_ih t₄ t₅ t₄_ih t₅_ih,\n\n show x ∈ FV (term.subst y v (term.value v')), by begin -- term.value\n unfold term.subst,\n from x_free\n end,\n\n show x ∈ FV (term.subst y v (term.var z)), by begin -- term.var\n have : (x = z), from free_in_term.var.inv x_free,\n rw[this] at x_neq_y,\n\n have : (term.subst y v z = z), from term.subst.var.diff x_neq_y.symm,\n change x ∈ FV (term.subst y v ↑z),\n rw[this],\n from x_free\n end,\n\n show x ∈ FV (term.subst y v (term.unop unop t₁)), by begin -- term.unop\n unfold term.subst,\n apply free_in_term.unop,\n have : x ∈ FV t₁, from free_in_term.unop.inv x_free,\n from t₁_ih this\n end,\n\n show x ∈ FV (term.subst y v (term.binop binop t₂ t₃)), by begin -- term.binop\n unfold term.subst,\n have : x ∈ FV t₂ ∨ x ∈ FV t₃, from free_in_term.binop.inv x_free,\n cases this with h,\n apply free_in_term.binop₁,\n from t₂_ih h,\n apply free_in_term.binop₂,\n from t₃_ih a\n end,\n\n show x ∈ FV (term.subst y v (term.app t₄ t₅)), by begin -- term.binop\n unfold term.subst,\n have : x ∈ FV t₄ ∨ x ∈ FV t₅, from free_in_term.app.inv x_free,\n cases this with h,\n apply free_in_term.app₁,\n from t₄_ih h,\n apply free_in_term.app₂,\n from t₅_ih a\n end,\n end\n\nlemma vc.free_of_diff_subst {x y: var} {v: value} {P: vc}: x ∈ FV P → x ≠ y → x ∈ FV (vc.subst y v P) :=\n assume x_free: x ∈ FV P,\n assume x_neq_y: x ≠ y,\n show x ∈ FV (vc.subst y v P), from begin\n induction P,\n case vc.term t {\n unfold vc.subst,\n apply free_in_vc.term,\n have h2, from free_in_vc.term.inv x_free,\n from term.free_of_diff_subst h2 x_neq_y\n },\n case vc.not P₁ P₁_ih {\n unfold vc.subst,\n apply free_in_vc.not,\n have h2, from free_in_vc.not.inv x_free,\n from P₁_ih h2\n },\n case vc.and P₁ P₂ P₁_ih P₂_ih {\n unfold vc.subst,\n have : x ∈ FV P₁ ∨ x ∈ FV P₂, from free_in_vc.and.inv x_free,\n cases this with h,\n apply free_in_vc.and₁,\n from P₁_ih h,\n apply free_in_vc.and₂,\n from P₂_ih a\n },\n case vc.or P₁ P₂ P₁_ih P₂_ih {\n unfold vc.subst,\n have : x ∈ FV P₁ ∨ x ∈ FV P₂, from free_in_vc.or.inv x_free,\n cases this with h,\n apply free_in_vc.or₁,\n from P₁_ih h,\n apply free_in_vc.or₂,\n from P₂_ih a\n },\n case vc.pre t₁ t₂ {\n unfold vc.subst,\n have : x ∈ FV t₁ ∨ x ∈ FV t₂, from free_in_vc.pre.inv x_free,\n cases this with h,\n apply free_in_vc.pre₁,\n from term.free_of_diff_subst h x_neq_y,\n apply free_in_vc.pre₂,\n from term.free_of_diff_subst a x_neq_y\n },\n case vc.pre₁ op t {\n unfold vc.subst,\n apply free_in_vc.preop,\n have h2, from free_in_vc.pre₁.inv x_free,\n from term.free_of_diff_subst h2 x_neq_y\n },\n case vc.pre₂ op t₁ t₂ {\n unfold vc.subst,\n have : x ∈ FV t₁ ∨ x ∈ FV t₂, from free_in_vc.pre₂.inv x_free,\n cases this with h,\n apply free_in_vc.preop₁,\n from term.free_of_diff_subst h x_neq_y,\n apply free_in_vc.preop₂,\n from term.free_of_diff_subst a x_neq_y\n },\n case vc.post t₁ t₂ {\n unfold vc.subst,\n have : x ∈ FV t₁ ∨ x ∈ FV t₂, from free_in_vc.post.inv x_free,\n cases this with h,\n apply free_in_vc.post₁,\n from term.free_of_diff_subst h x_neq_y,\n apply free_in_vc.post₂,\n from term.free_of_diff_subst a x_neq_y\n },\n case vc.univ z P₁ P₁_ih {\n unfold vc.subst,\n have h2, from free_in_vc.univ.inv x_free,\n apply free_in_vc.univ,\n from h2.left,\n by_cases (y = z),\n rw[h],\n simp,\n from h2.right,\n simp[h],\n from P₁_ih h2.right\n }\n end\n\nlemma term.free_of_subst_env {x: var} {σ: env} {t: term}: x ∈ FV t → x ∉ σ → x ∈ FV (term.subst_env σ t) :=\n assume x_free: x ∈ FV t,\n assume x_not_in_σ: x ∉ σ,\n show x ∈ FV (term.subst_env σ t), begin\n induction σ with σ' y v ih,\n\n -- env.empty\n show x ∈ FV (term.subst_env env.empty t), begin\n unfold term.subst_env,\n from x_free\n end,\n\n -- σ'[x↦v]\n show x ∈ FV (term.subst_env (σ'[y↦v]) t), begin\n unfold term.subst_env,\n by_cases (x = y),\n begin -- x = y\n rw[h] at x_not_in_σ,\n have : y ∈ (σ'[y↦v]), from env.contains.same,\n contradiction\n end,\n begin -- x ≠ y\n by_cases (x ∈ σ') with h2,\n begin -- x ∈ σ'\n have : x ∈ (σ'[y↦v]), from env.contains.rest h2,\n contradiction\n end,\n begin -- x ∉ σ'\n have : x ∈ FV (term.subst_env σ' t), from ih h2,\n from term.free_of_diff_subst this h\n end,\n end\n end\n end\n\nlemma vc.free_of_subst_env {x: var} {σ: env} {P: vc}: x ∈ FV P → x ∉ σ → x ∈ FV (vc.subst_env σ P) :=\n assume x_free: x ∈ FV P,\n assume x_not_in_σ: x ∉ σ,\n show x ∈ FV (vc.subst_env σ P), begin\n induction σ with σ' y v ih,\n\n -- env.empty\n show x ∈ FV (vc.subst_env env.empty P), begin\n unfold vc.subst_env,\n from x_free\n end,\n\n -- σ'[x↦v]\n show x ∈ FV (vc.subst_env (σ'[y↦v]) P), begin\n unfold vc.subst_env,\n by_cases (x = y),\n begin -- x = y\n rw[h] at x_not_in_σ,\n have : y ∈ (σ'[y↦v]), from env.contains.same,\n contradiction\n end,\n begin -- x ≠ y\n by_cases (x ∈ σ') with h2,\n begin -- x ∈ σ'\n have : x ∈ (σ'[y↦v]), from env.contains.rest h2,\n contradiction\n end,\n begin -- x ∉ σ'\n have : x ∈ FV (vc.subst_env σ' P), from ih h2,\n from vc.free_of_diff_subst this h\n end,\n end\n end\n end\n\nlemma term.free_of_free_in_subst {x y: var} {v: value} {t: term}: x ∈ FV (term.subst y v t) → x ∈ FV t :=\n begin\n assume h1,\n induction t with v' z unop t₁ t₁_ih binop t₂ t₃ t₂_ih t₃_ih t₄ t₅ t₄_ih t₅_ih,\n\n show x ∈ FV (term.value v'), by begin\n unfold term.subst at h1,\n cases h1\n end,\n\n show x ∈ FV (term.var z), by begin\n unfold term.subst at h1,\n by_cases (y = z) with h2,\n simp[h2] at h1,\n cases h1,\n simp[h2] at h1,\n from h1\n end,\n\n show x ∈ FV (term.unop unop t₁), by begin\n unfold term.subst at h1,\n apply free_in_term.unop,\n have h2, from free_in_term.unop.inv h1,\n from t₁_ih h2\n end,\n\n show x ∈ FV (term.binop binop t₂ t₃), by begin\n unfold term.subst at h1,\n have h2, from free_in_term.binop.inv h1,\n cases h2,\n apply free_in_term.binop₁,\n from t₂_ih a,\n apply free_in_term.binop₂,\n from t₃_ih a\n end,\n\n show x ∈ FV (term.app t₄ t₅), by begin\n unfold term.subst at h1,\n have h2, from free_in_term.app.inv h1,\n cases h2,\n apply free_in_term.app₁,\n from t₄_ih a,\n apply free_in_term.app₂,\n from t₅_ih a\n end\n end\n\nlemma term.closed_subst_of_closed {σ: env} {t: term}: closed (term.subst_env σ t) → closed_subst σ t :=\n assume t_closed_subst: closed (term.subst_env σ t),\n show closed_subst σ t, from (\n assume x: var,\n assume h1: x ∈ FV t,\n have ¬ x ∉ σ, from mt (term.free_of_subst_env h1) (t_closed_subst x),\n have x ∈ σ, from of_not_not this,\n show x ∈ σ.dom, from this\n )\n\nlemma term.substt_value_eq_subst {x: var} {v: value} {t: term}: term.substt x v t = term.subst x v t :=\n begin\n induction t with v' z unop t₁ t₁_ih binop t₂ t₃ t₂_ih t₃_ih t₄ t₅ t₄_ih t₅_ih,\n\n show (term.substt x v (term.value v') = term.subst x v (term.value v')), by begin\n unfold term.substt,\n unfold term.subst\n end,\n\n show (term.substt x v (term.var z) = term.subst x v (term.var z)), by begin\n unfold term.substt,\n unfold term.subst\n end,\n\n show (term.substt x ↑v (term.unop unop t₁) = term.subst x v (term.unop unop t₁)), by begin\n unfold term.substt,\n unfold term.subst,\n congr\n end,\n\n show (term.substt x v (term.binop binop t₂ t₃) = term.subst x v (term.binop binop t₂ t₃)), by begin\n unfold term.substt,\n unfold term.subst,\n congr\n end,\n\n show (term.substt x ↑v (term.app t₄ t₅) = term.subst x v (term.app t₄ t₅)), by begin\n unfold term.substt,\n unfold term.subst,\n congr\n end\n end\n\nlemma vc.substt_value_eq_subst {x: var} {v: value} {P: vc}: vc.substt x v P = vc.subst x v P :=\n begin\n induction P,\n\n case vc.term t {\n unfold vc.substt,\n unfold vc.subst,\n congr\n },\n case vc.not P₁ ih {\n unfold vc.substt,\n unfold vc.subst,\n congr,\n from ih\n },\n case vc.and P₁ P₂ P₁_ih P₂_ih {\n unfold vc.substt,\n unfold vc.subst,\n congr,\n from P₁_ih,\n from P₂_ih\n },\n case vc.or P₁ P₂ P₁_ih P₂_ih {\n unfold vc.substt,\n unfold vc.subst,\n congr,\n from P₁_ih,\n from P₂_ih\n },\n case vc.pre t₁ t₂ {\n unfold vc.substt,\n unfold vc.subst,\n congr\n },\n case vc.pre₁ op t {\n unfold vc.substt,\n unfold vc.subst,\n congr\n },\n case vc.pre₂ op t₁ t₂ {\n unfold vc.substt,\n unfold vc.subst,\n congr\n },\n case vc.post t₁ t₂ {\n unfold vc.substt,\n unfold vc.subst,\n congr\n },\n case vc.univ z P' P'_ih {\n unfold vc.substt,\n unfold vc.subst,\n congr,\n from P'_ih\n }\n end\n\nlemma prop.free_of_free_in_subst {x y: var} {v: value} {P: prop}: x ∈ FV (prop.subst y v P) → x ∈ FV P :=\n begin\n assume h1,\n induction P,\n case prop.term t {\n apply free_in_prop.term,\n have h2, from free_in_prop.term.inv h1,\n from term.free_of_free_in_subst h2\n },\n case prop.not P₁ ih {\n apply free_in_prop.not,\n unfold prop.subst at h1,\n have h2, from free_in_prop.not.inv h1,\n from ih h2 \n },\n case prop.and P₁ P₂ P₁_ih P₂_ih {\n unfold prop.subst at h1,\n have h2, from free_in_prop.and.inv h1,\n cases h2,\n apply free_in_prop.and₁,\n from P₁_ih a,\n apply free_in_prop.and₂,\n from P₂_ih a\n },\n case prop.or P₁ P₂ P₁_ih P₂_ih {\n unfold prop.subst at h1,\n have h2, from free_in_prop.or.inv h1,\n cases h2,\n apply free_in_prop.or₁,\n from P₁_ih a,\n apply free_in_prop.or₂,\n from P₂_ih a\n },\n case prop.pre t₁ t₂ {\n unfold prop.subst at h1,\n have h2, from free_in_prop.pre.inv h1,\n cases h2,\n apply free_in_prop.pre₁,\n from term.free_of_free_in_subst a,\n apply free_in_prop.pre₂,\n from term.free_of_free_in_subst a\n },\n case prop.pre₁ op t {\n unfold prop.subst at h1,\n have h2, from free_in_prop.pre₁.inv h1,\n apply free_in_prop.preop,\n from term.free_of_free_in_subst h2\n },\n case prop.pre₂ op t₁ t₂ {\n unfold prop.subst at h1,\n have h2, from free_in_prop.pre₂.inv h1,\n cases h2,\n apply free_in_prop.preop₁,\n from term.free_of_free_in_subst a,\n apply free_in_prop.preop₂,\n from term.free_of_free_in_subst a\n },\n case prop.call t {\n unfold prop.subst at h1,\n have h2, from free_in_prop.call.inv h1,\n apply free_in_prop.call,\n from term.free_of_free_in_subst h2\n },\n case prop.post t₁ t₂ {\n unfold prop.subst at h1,\n have h2, from free_in_prop.post.inv h1,\n cases h2,\n apply free_in_prop.post₁,\n from term.free_of_free_in_subst a,\n apply free_in_prop.post₂,\n from term.free_of_free_in_subst a\n },\n case prop.forallc z P' P'_ih {\n unfold prop.subst at h1,\n have h2, from free_in_prop.forallc.inv h1,\n by_cases (y = z) with h3,\n have h4, from h2.right,\n rw[h3] at h4,\n simp at h4,\n apply free_in_prop.forallc,\n from h2.left,\n from h4,\n\n have h4, from h2.right,\n simp[h3] at h4,\n apply free_in_prop.forallc,\n from h2.left,\n simp[h3] at h4,\n from P'_ih h4\n },\n case prop.exis z P' P'_ih {\n unfold prop.subst at h1,\n have h2, from free_in_prop.exis.inv h1,\n by_cases (y = z) with h3,\n have h4, from h2.right,\n rw[h3] at h4,\n simp at h4,\n apply free_in_prop.exis,\n from h2.left,\n from h4,\n\n have h4, from h2.right,\n simp[h3] at h4,\n have : ((ite (y = z) P' (prop.subst y v P')) = (prop.subst y v P')), by simp[h3],\n rw[this] at h4,\n apply free_in_prop.exis,\n from h2.left,\n from P'_ih h4\n }\n end\n\nlemma prop.free_of_free_subst_env {x: var} {σ: env} {P: prop}: x ∈ FV (prop.subst_env σ P) → x ∈ FV P :=\n assume x_free: x ∈ FV (prop.subst_env σ P),\n show x ∈ FV P, begin\n induction σ with σ' y v ih,\n\n -- env.empty\n show x ∈ FV P, begin\n unfold prop.subst_env at x_free,\n from x_free\n end,\n\n -- σ'[x↦v]\n show x ∈ FV P, begin\n unfold prop.subst_env at x_free,\n have h1: x ∈ FV (prop.subst_env σ' P), from prop.free_of_free_in_subst x_free,\n from ih h1\n end\n end\n\nlemma vc.free_of_free_in_subst {x y: var} {v: value} {P: vc}: x ∈ FV (vc.subst y v P) → x ∈ FV P :=\n begin\n assume h1,\n induction P,\n case vc.term t {\n apply free_in_vc.term,\n have h2, from free_in_vc.term.inv h1,\n from term.free_of_free_in_subst h2\n },\n case vc.not P₁ ih {\n apply free_in_vc.not,\n unfold vc.subst at h1,\n have h2, from free_in_vc.not.inv h1,\n from ih h2 \n },\n case vc.and P₁ P₂ P₁_ih P₂_ih {\n unfold vc.subst at h1,\n have h2, from free_in_vc.and.inv h1,\n cases h2,\n apply free_in_vc.and₁,\n from P₁_ih a,\n apply free_in_vc.and₂,\n from P₂_ih a\n },\n case vc.or P₁ P₂ P₁_ih P₂_ih {\n unfold vc.subst at h1,\n have h2, from free_in_vc.or.inv h1,\n cases h2,\n apply free_in_vc.or₁,\n from P₁_ih a,\n apply free_in_vc.or₂,\n from P₂_ih a\n },\n case vc.pre t₁ t₂ {\n unfold vc.subst at h1,\n have h2, from free_in_vc.pre.inv h1,\n cases h2,\n apply free_in_vc.pre₁,\n from term.free_of_free_in_subst a,\n apply free_in_vc.pre₂,\n from term.free_of_free_in_subst a\n },\n case vc.pre₁ op t {\n unfold vc.subst at h1,\n have h2, from free_in_vc.pre₁.inv h1,\n apply free_in_vc.preop,\n from term.free_of_free_in_subst h2\n },\n case vc.pre₂ op t₁ t₂ {\n unfold vc.subst at h1,\n have h2, from free_in_vc.pre₂.inv h1,\n cases h2,\n apply free_in_vc.preop₁,\n from term.free_of_free_in_subst a,\n apply free_in_vc.preop₂,\n from term.free_of_free_in_subst a\n },\n case vc.post t₁ t₂ {\n unfold vc.subst at h1,\n have h2, from free_in_vc.post.inv h1,\n cases h2,\n apply free_in_vc.post₁,\n from term.free_of_free_in_subst a,\n apply free_in_vc.post₂,\n from term.free_of_free_in_subst a\n },\n case vc.univ z P' P'_ih {\n unfold vc.subst at h1,\n have h2, from free_in_vc.univ.inv h1,\n by_cases (y = z) with h3,\n have h4, from h2.right,\n rw[h3] at h4,\n simp at h4,\n apply free_in_vc.univ,\n from h2.left,\n from h4,\n\n have h4, from h2.right,\n simp[h3] at h4,\n have : ((ite (y = z) P' (vc.subst y v P')) = (vc.subst y v P')), by simp[h3],\n rw[this] at h4,\n apply free_in_vc.univ,\n from h2.left,\n from P'_ih h4\n }\n end\n\nlemma vc.free_of_free_subst_env {x: var} {σ: env} {P: vc}: x ∈ FV (vc.subst_env σ P) → x ∈ FV P :=\n assume x_free: x ∈ FV (vc.subst_env σ P),\n show x ∈ FV P, begin\n induction σ with σ' y v ih,\n\n -- env.empty\n show x ∈ FV P, begin\n unfold vc.subst_env at x_free,\n from x_free\n end,\n\n -- σ'[x↦v]\n show x ∈ FV P, begin\n unfold vc.subst_env at x_free,\n have h1: x ∈ FV (vc.subst_env σ' P), from vc.free_of_free_in_subst x_free,\n from ih h1\n end\n end\n\nlemma vc.closed_subst_of_closed {σ: env} {P: vc}: closed (vc.subst_env σ P) → closed_subst σ P :=\n assume P_closed_subst: closed (vc.subst_env σ P),\n show closed_subst σ P, from (\n assume x: var,\n assume h1: x ∈ FV P,\n have ¬ x ∉ σ, from mt (vc.free_of_subst_env h1) (P_closed_subst x),\n have x ∈ σ, from of_not_not this,\n show x ∈ σ.dom, from this\n )\n\nlemma prop.closed_any_subst_of_closed {σ: env} {P: prop}: closed P → closed_subst σ P :=\n assume P_closed: closed P,\n show closed_subst σ P, from (\n assume x: var,\n assume : x ∈ FV P,\n show x ∈ σ.dom, from absurd this (P_closed x)\n )\n\nlemma term.subst_env.unop {σ: env} {op: unop} {t: term}:\n term.subst_env σ (term.unop op t) = term.unop op (term.subst_env σ t) :=\nbegin\n induction σ with σ' x v ih,\n\n show (term.subst_env env.empty (term.unop op t) = term.unop op (term.subst_env env.empty t)),\n by calc\n term.subst_env env.empty (term.unop op t)\n = (term.unop op t) : by unfold term.subst_env\n ... = (term.unop op (term.subst_env env.empty t)) : by unfold term.subst_env,\n\n show (term.subst_env (σ'[x↦v]) (term.unop op t) = (term.unop op (term.subst_env (σ'[x↦v]) t))),\n by calc\n term.subst_env (σ'[x↦v]) (term.unop op t)\n = term.subst x v (term.subst_env σ' (term.unop op t)) : by unfold term.subst_env\n ... = term.subst x v (term.unop op (term.subst_env σ' t)) : by rw[ih]\n ... = term.unop op (term.subst x v (term.subst_env σ' t)) : by unfold term.subst\n ... = term.unop op (term.subst_env (σ'[x↦v]) t) : by unfold term.subst_env\nend\n\nlemma term.subst_env.binop {σ: env} {op: binop} {t₁ t₂: term}:\n term.subst_env σ (term.binop op t₁ t₂) = term.binop op (term.subst_env σ t₁) (term.subst_env σ t₂) :=\nbegin\n induction σ with σ' x v ih,\n\n show (term.subst_env env.empty (term.binop op t₁ t₂)\n = term.binop op (term.subst_env env.empty t₁) (term.subst_env env.empty t₂)),\n by calc\n term.subst_env env.empty (term.binop op t₁ t₂)\n = (term.binop op t₁ t₂) : by unfold term.subst_env\n ... = (term.binop op (term.subst_env env.empty t₁) t₂) : by unfold term.subst_env\n ... = (term.binop op (term.subst_env env.empty t₁) (term.subst_env env.empty t₂)) : by unfold term.subst_env,\n\n show (term.subst_env (σ'[x↦v]) (term.binop op t₁ t₂)\n = (term.binop op (term.subst_env (σ'[x↦v]) t₁) (term.subst_env (σ'[x↦v]) t₂))),\n by calc\n term.subst_env (σ'[x↦v]) (term.binop op t₁ t₂)\n = term.subst x v (term.subst_env σ' (term.binop op t₁ t₂)) : by unfold term.subst_env\n ... = term.subst x v (term.binop op (term.subst_env σ' t₁) (term.subst_env σ' t₂)) : by rw[ih]\n ... = term.binop op (term.subst x v (term.subst_env σ' t₁))\n (term.subst x v (term.subst_env σ' t₂)) : by unfold term.subst\n ... = term.binop op (term.subst_env (σ'[x↦v]) t₁)\n (term.subst x v (term.subst_env σ' t₂)) : by unfold term.subst_env\n ... = term.binop op (term.subst_env (σ'[x↦v]) t₁) (term.subst_env (σ'[x↦v]) t₂) : by unfold term.subst_env\nend\n\nlemma term.subst_env.app {σ: env} {t₁ t₂: term}:\n term.subst_env σ (term.app t₁ t₂) = term.app (term.subst_env σ t₁) (term.subst_env σ t₂) :=\nbegin\n induction σ with σ' x v ih,\n\n show (term.subst_env env.empty (term.app t₁ t₂)\n = term.app (term.subst_env env.empty t₁) (term.subst_env env.empty t₂)),\n by calc\n term.subst_env env.empty (term.app t₁ t₂)\n = (term.app t₁ t₂) : by unfold term.subst_env\n ... = (term.app (term.subst_env env.empty t₁) t₂) : by unfold term.subst_env\n ... = (term.app (term.subst_env env.empty t₁) (term.subst_env env.empty t₂)) : by unfold term.subst_env,\n\n show (term.subst_env (σ'[x↦v]) (term.app t₁ t₂)\n = (term.app (term.subst_env (σ'[x↦v]) t₁) (term.subst_env (σ'[x↦v]) t₂))),\n by calc\n term.subst_env (σ'[x↦v]) (term.app t₁ t₂)\n = term.subst x v (term.subst_env σ' (term.app t₁ t₂)) : by unfold term.subst_env\n ... = term.subst x v (term.app (term.subst_env σ' t₁) (term.subst_env σ' t₂)) : by rw[ih]\n ... = term.app (term.subst x v (term.subst_env σ' t₁))\n (term.subst x v (term.subst_env σ' t₂)) : by unfold term.subst\n ... = term.app (term.subst_env (σ'[x↦v]) t₁)\n (term.subst x v (term.subst_env σ' t₂)) : by unfold term.subst_env\n ... = term.app (term.subst_env (σ'[x↦v]) t₁) (term.subst_env (σ'[x↦v]) t₂) : by unfold term.subst_env\nend\n\nlemma prop.subst_env.term {σ: env} {t: term}:\n prop.subst_env σ t = prop.term (term.subst_env σ t) :=\nbegin\n induction σ with σ' x v ih,\n\n show (prop.subst_env env.empty t = prop.term (term.subst_env env.empty t)), by begin\n have : (term.subst_env env.empty t = t), by unfold term.subst_env,\n have h2: (prop.term (term.subst_env env.empty t) = prop.term t), by simp[this],\n calc\n prop.subst_env env.empty t = t : by unfold prop.subst_env\n ... = prop.term t : by refl\n ... = prop.term (term.subst_env env.empty t) : by rw[←h2]\n end,\n\n show (prop.subst_env (σ'[x↦v]) t = prop.term (term.subst_env (σ'[x↦v]) t)),\n by calc\n prop.subst_env (σ'[x↦v]) t = prop.subst x v (prop.subst_env σ' t) : by unfold prop.subst_env\n ... = prop.subst x v (prop.term (term.subst_env σ' t)) : by rw[ih]\n ... = term.subst x v (term.subst_env σ' t) : by unfold prop.subst\n ... = term.subst_env (σ'[x↦v]) t : by unfold term.subst_env\nend\n\nlemma prop.subst_env.not {σ: env} {P: prop}:\n prop.subst_env σ P.not = (prop.subst_env σ P).not :=\nbegin\n induction σ with σ' x v ih,\n\n show (prop.subst_env env.empty P.not = (prop.subst_env env.empty P).not),\n by calc\n prop.subst_env env.empty P.not = P.not : by unfold prop.subst_env\n ... = (prop.subst_env env.empty P).not : by unfold prop.subst_env,\n\n show (prop.subst_env (σ'[x↦v]) P.not = (prop.subst_env (σ'[x↦v]) P).not),\n by calc\n prop.subst_env (σ'[x↦v]) P.not = prop.subst x v (prop.subst_env σ' P.not) : by unfold prop.subst_env\n ... = prop.subst x v (prop.subst_env σ' P).not : by rw[ih]\n ... = (prop.subst x v (prop.subst_env σ' P)).not : by unfold prop.subst\n ... = (prop.subst_env (σ'[x↦v]) P).not : by unfold prop.subst_env\nend\n\nlemma prop.subst_env.and {σ: env} {P Q: prop}:\n prop.subst_env σ (P ⋀ Q) = (prop.subst_env σ P ⋀ prop.subst_env σ Q) :=\nbegin\n induction σ with σ' x v ih,\n\n show (prop.subst_env env.empty (P ⋀ Q) = (prop.subst_env env.empty P ⋀ prop.subst_env env.empty Q)),\n by calc\n prop.subst_env env.empty (P ⋀ Q) = (P ⋀ Q) : by unfold prop.subst_env\n ... = (prop.subst_env env.empty P ⋀ Q) : by unfold prop.subst_env\n ... = (prop.subst_env env.empty P ⋀ prop.subst_env env.empty Q)\n : by unfold prop.subst_env,\n\n show (prop.subst_env (σ'[x↦v]) (P ⋀ Q) = (prop.subst_env (σ'[x↦v]) P ⋀ prop.subst_env (σ'[x↦v]) Q)),\n by calc\n prop.subst_env (σ'[x↦v]) (P ⋀ Q) = prop.subst x v (prop.subst_env σ' (P ⋀ Q)) : by unfold prop.subst_env\n ... = prop.subst x v (prop.subst_env σ' P ⋀ prop.subst_env σ' Q) : by rw[ih]\n ... = (prop.subst x v (prop.subst_env σ' P) ⋀\n prop.subst x v (prop.subst_env σ' Q)) : by refl\n ... = (prop.subst_env (σ'[x↦v]) P ⋀\n prop.subst x v (prop.subst_env σ' Q)) : by unfold prop.subst_env\n ... = (prop.subst_env (σ'[x↦v]) P ⋀ prop.subst_env (σ'[x↦v]) Q)\n : by unfold prop.subst_env\nend\n\nlemma prop.subst_env.or {σ: env} {P Q: prop}:\n prop.subst_env σ (P ⋁ Q) = (prop.subst_env σ P ⋁ prop.subst_env σ Q) :=\nbegin\n induction σ with σ' x v ih,\n\n show (prop.subst_env env.empty (P ⋁ Q) = (prop.subst_env env.empty P ⋁ prop.subst_env env.empty Q)),\n by calc\n prop.subst_env env.empty (P ⋁ Q) = (P ⋁ Q) : by unfold prop.subst_env\n ... = (prop.subst_env env.empty P ⋁ Q) : by by unfold prop.subst_env\n ... = (prop.subst_env env.empty P ⋁ prop.subst_env env.empty Q)\n : by unfold prop.subst_env,\n\n show (prop.subst_env (σ'[x↦v]) (P ⋁ Q) = (prop.subst_env (σ'[x↦v]) P ⋁ prop.subst_env (σ'[x↦v]) Q)),\n by calc\n prop.subst_env (σ'[x↦v]) (P ⋁ Q) = prop.subst x v (prop.subst_env σ' (P ⋁ Q)) : by unfold prop.subst_env\n ... = prop.subst x v (prop.subst_env σ' P ⋁ prop.subst_env σ' Q) : by rw[ih]\n ... = (prop.subst x v (prop.subst_env σ' P) ⋁\n prop.subst x v (prop.subst_env σ' Q)) : by refl\n ... = (prop.subst_env (σ'[x↦v]) P ⋁\n prop.subst x v (prop.subst_env σ' Q)) : by unfold prop.subst_env\n ... = (prop.subst_env (σ'[x↦v]) P ⋁ prop.subst_env (σ'[x↦v]) Q)\n : by unfold prop.subst_env\nend\n\nlemma prop.subst_env.implies {σ: env} {P Q: prop}:\n prop.subst_env σ (prop.implies P Q) = prop.implies (prop.subst_env σ P) (prop.subst_env σ Q) :=\n have h1: prop.subst_env σ (prop.implies P Q) = prop.subst_env σ (P.not ⋁ Q), by refl,\n have prop.subst_env σ (P.not ⋁ Q) = (prop.subst_env σ P.not ⋁ prop.subst_env σ Q), from prop.subst_env.or,\n have h2: prop.subst_env σ (prop.implies P Q) = (prop.subst_env σ P.not ⋁ prop.subst_env σ Q), from this ▸ h1,\n have prop.subst_env σ P.not = prop.not (prop.subst_env σ P), from prop.subst_env.not,\n have prop.subst_env σ (prop.implies P Q) = (prop.not (prop.subst_env σ P) ⋁ prop.subst_env σ Q), from this ▸ h2,\n show prop.subst_env σ (prop.implies P Q) = prop.implies (prop.subst_env σ P) (prop.subst_env σ Q), from this\n\nlemma prop.subst_env.pre {σ: env} {t₁ t₂: term}:\n prop.subst_env σ (prop.pre t₁ t₂) = prop.pre (term.subst_env σ t₁) (term.subst_env σ t₂) :=\nbegin\n induction σ with σ' x v ih,\n\n show (prop.subst_env env.empty (prop.pre t₁ t₂)\n = prop.pre (term.subst_env env.empty t₁) (term.subst_env env.empty t₂)),\n by calc\n prop.subst_env env.empty (prop.pre t₁ t₂)\n = (prop.pre t₁ t₂) : by unfold prop.subst_env\n ... = (prop.pre (term.subst_env env.empty t₁) t₂) : by unfold term.subst_env\n ... = (prop.pre (term.subst_env env.empty t₁) (term.subst_env env.empty t₂)) : by unfold term.subst_env,\n\n show (prop.subst_env (σ'[x↦v]) (prop.pre t₁ t₂)\n = prop.pre (term.subst_env (σ'[x↦v]) t₁) (term.subst_env (σ'[x↦v]) t₂)),\n by calc\n prop.subst_env (σ'[x↦v]) (prop.pre t₁ t₂)\n = prop.subst x v (prop.subst_env σ' (prop.pre t₁ t₂)) : by unfold prop.subst_env\n ... = prop.subst x v (prop.pre (term.subst_env σ' t₁) (term.subst_env σ' t₂)) : by rw[ih]\n ... = prop.pre (term.subst x v (term.subst_env σ' t₁)) (term.subst x v (term.subst_env σ' t₂)) : by unfold prop.subst\n ... = prop.pre (term.subst_env (σ'[x↦v]) t₁) (term.subst x v (term.subst_env σ' t₂)) : by unfold term.subst_env\n ... = prop.pre (term.subst_env (σ'[x↦v]) t₁) (term.subst_env (σ'[x↦v]) t₂) : by unfold term.subst_env\nend\n\nlemma prop.subst_env.post {σ: env} {t₁ t₂: term}:\n prop.subst_env σ (prop.post t₁ t₂) = prop.post (term.subst_env σ t₁) (term.subst_env σ t₂) :=\nbegin\n induction σ with σ' x v ih,\n\n show (prop.subst_env env.empty (prop.post t₁ t₂)\n = prop.post (term.subst_env env.empty t₁) (term.subst_env env.empty t₂)),\n by calc\n prop.subst_env env.empty (prop.post t₁ t₂)\n = (prop.post t₁ t₂) : by unfold prop.subst_env\n ... = (prop.post (term.subst_env env.empty t₁) t₂) : by unfold term.subst_env\n ... = (prop.post (term.subst_env env.empty t₁) (term.subst_env env.empty t₂)) : by unfold term.subst_env,\n\n show (prop.subst_env (σ'[x↦v]) (prop.post t₁ t₂)\n = prop.post (term.subst_env (σ'[x↦v]) t₁) (term.subst_env (σ'[x↦v]) t₂)),\n by calc\n prop.subst_env (σ'[x↦v]) (prop.post t₁ t₂)\n = prop.subst x v (prop.subst_env σ' (prop.post t₁ t₂)) : by unfold prop.subst_env\n ... = prop.subst x v (prop.post (term.subst_env σ' t₁) (term.subst_env σ' t₂)) : by rw[ih]\n ... = prop.post (term.subst x v (term.subst_env σ' t₁)) (term.subst x v (term.subst_env σ' t₂)) : by unfold prop.subst\n ... = prop.post (term.subst_env (σ'[x↦v]) t₁) (term.subst x v (term.subst_env σ' t₂)) : by unfold term.subst_env\n ... = prop.post (term.subst_env (σ'[x↦v]) t₁) (term.subst_env (σ'[x↦v]) t₂) : by unfold term.subst_env\nend\n\nlemma prop.subst_env.forallc_not_in {σ: env} {x: var} {P: prop}:\n (x ∉ σ) → (prop.subst_env σ (prop.forallc x P) = prop.forallc x (prop.subst_env σ P)) :=\nbegin\n assume x_not_in_σ,\n induction σ with σ' y v ih,\n\n show (prop.subst_env env.empty (prop.forallc x P)\n = prop.forallc x (prop.subst_env env.empty P)),\n by calc\n prop.subst_env env.empty (prop.forallc x P)\n = prop.forallc x P : by unfold prop.subst_env\n ... = prop.forallc x (prop.subst_env env.empty P) : by unfold prop.subst_env,\n\n show (prop.subst_env (σ'[y↦v]) (prop.forallc x P)\n = prop.forallc x (prop.subst_env (σ'[y↦v]) P)), from (\n have ¬ (x = y ∨ x ∈ σ'), from env.contains.same.inv x_not_in_σ,\n have x_neq_y: x ≠ y, from (not_or_distrib.mp this).left,\n have x ∉ σ', from (not_or_distrib.mp this).right,\n have h: prop.subst_env σ' (prop.forallc x P) = prop.forallc x (prop.subst_env σ' P),\n from ih this,\n\n calc\n prop.subst_env (σ'[y↦v]) (prop.forallc x P)\n = prop.subst y v (prop.subst_env σ' (prop.forallc x P)) : by unfold prop.subst_env\n ... = prop.subst y v (prop.forallc x (prop.subst_env σ' P)) : by rw[h]\n ... = prop.forallc x (if y = x then prop.subst_env σ' P else (prop.subst_env σ' P).subst y v)\n : by unfold prop.subst\n ... = prop.forallc x ((prop.subst_env σ' P).subst y v) : by simp[x_neq_y.symm]\n ... = prop.forallc x (prop.subst_env (σ'[y↦v]) P) : by unfold prop.subst_env\n )\nend\n\nlemma prop.subst_env.forallc {σ: env} {x: var} {P: prop}:\n (prop.subst_env σ (prop.forallc x P) = prop.forallc x (prop.subst_env (σ.without x) P)) :=\nbegin\n induction σ with σ' y v ih,\n\n show (prop.subst_env env.empty (prop.forallc x P) = prop.forallc x (prop.subst_env (env.empty.without x) P)),\n by calc\n prop.subst_env env.empty (prop.forallc x P) = (prop.forallc x P) : by unfold prop.subst_env\n ... = prop.forallc x (prop.subst_env env.empty P)\n : by unfold prop.subst_env,\n\n show (prop.subst_env (σ'[y↦v]) (prop.forallc x P) = prop.forallc x (prop.subst_env ((σ'[y↦v]).without x) P)),\n by begin\n unfold prop.subst_env,\n by_cases (y = x) with h1,\n rw[←h1],\n rw[←h1] at ih,\n unfold env.without,\n simp,\n have : y ∉ FV (prop.subst_env σ' (prop.forallc y P)), from (\n assume : y ∈ FV (prop.subst_env σ' (prop.forallc y P)),\n have y ∈ FV (prop.forallc y P), from prop.free_of_free_subst_env this,\n show «false», from free_in_prop.forallc.same.inv this\n ),\n have h2: (prop.subst y v (prop.subst_env σ' (prop.forallc y P)) = prop.subst_env σ' (prop.forallc y P)),\n from unchanged_of_subst_nonfree_prop this,\n rw[h2],\n from ih,\n\n unfold env.without,\n simp[h1],\n unfold prop.subst_env,\n have : (prop.subst y v (prop.forallc x (prop.subst_env (env.without σ' x) P))\n = prop.forallc x (prop.subst y v (prop.subst_env (env.without σ' x) P))),\n by { unfold prop.subst, simp[h1] },\n rw[←this],\n congr,\n from ih \n end\nend\n\nlemma vc.subst.implies {x: var} {v: value} {P Q: vc}:\n vc.subst x v (vc.implies P Q) = vc.implies (vc.subst x v P) (vc.subst x v Q) :=\n by calc \n vc.subst x v (vc.implies P Q) = vc.subst x v (vc.or (vc.not P) Q) : rfl\n ... = (vc.subst x v (vc.not P) ⋁ vc.subst x v Q) : by unfold vc.subst\n ... = ((vc.subst x v P).not ⋁ vc.subst x v Q) : by unfold vc.subst\n\nlemma vc.subst_env.term {σ: env} {t: term}:\n vc.subst_env σ t = vc.term (term.subst_env σ t) :=\nbegin\n induction σ with σ' x v ih,\n\n show (vc.subst_env env.empty t = vc.term (term.subst_env env.empty t)), by begin\n have : (term.subst_env env.empty t = t), by unfold term.subst_env,\n have h2: (vc.term (term.subst_env env.empty t) = vc.term t), by simp[this],\n calc\n vc.subst_env env.empty t = t : by unfold vc.subst_env\n ... = vc.term t : by refl\n ... = vc.term (term.subst_env env.empty t) : by rw[←h2]\n end,\n\n show (vc.subst_env (σ'[x↦v]) t = vc.term (term.subst_env (σ'[x↦v]) t)),\n by calc\n vc.subst_env (σ'[x↦v]) t = vc.subst x v (vc.subst_env σ' t) : by unfold vc.subst_env\n ... = vc.subst x v (vc.term (term.subst_env σ' t)) : by rw[ih]\n ... = term.subst x v (term.subst_env σ' t) : by unfold vc.subst\n ... = term.subst_env (σ'[x↦v]) t : by unfold term.subst_env\nend\n\nlemma vc.subst_env.not {σ: env} {P: vc}:\n vc.subst_env σ P.not = (vc.subst_env σ P).not :=\nbegin\n induction σ with σ' x v ih,\n\n show (vc.subst_env env.empty P.not = (vc.subst_env env.empty P).not),\n by calc\n vc.subst_env env.empty P.not = P.not : by unfold vc.subst_env\n ... = (vc.subst_env env.empty P).not : by unfold vc.subst_env,\n\n show (vc.subst_env (σ'[x↦v]) P.not = (vc.subst_env (σ'[x↦v]) P).not),\n by calc\n vc.subst_env (σ'[x↦v]) P.not = vc.subst x v (vc.subst_env σ' P.not) : by unfold vc.subst_env\n ... = vc.subst x v (vc.subst_env σ' P).not : by rw[ih]\n ... = (vc.subst x v (vc.subst_env σ' P)).not : by unfold vc.subst\n ... = (vc.subst_env (σ'[x↦v]) P).not : by unfold vc.subst_env\nend\n\nlemma vc.subst_env.and {σ: env} {P Q: vc}:\n vc.subst_env σ (P ⋀ Q) = (vc.subst_env σ P ⋀ vc.subst_env σ Q) :=\nbegin\n induction σ with σ' x v ih,\n\n show (vc.subst_env env.empty (P ⋀ Q) = (vc.subst_env env.empty P ⋀ vc.subst_env env.empty Q)),\n by calc\n vc.subst_env env.empty (P ⋀ Q) = (P ⋀ Q) : by unfold vc.subst_env\n ... = (vc.subst_env env.empty P ⋀ Q) : by unfold vc.subst_env\n ... = (vc.subst_env env.empty P ⋀ vc.subst_env env.empty Q)\n : by unfold vc.subst_env,\n\n show (vc.subst_env (σ'[x↦v]) (P ⋀ Q) = (vc.subst_env (σ'[x↦v]) P ⋀ vc.subst_env (σ'[x↦v]) Q)),\n by calc\n vc.subst_env (σ'[x↦v]) (P ⋀ Q) = vc.subst x v (vc.subst_env σ' (P ⋀ Q)) : by unfold vc.subst_env\n ... = vc.subst x v (vc.subst_env σ' P ⋀ vc.subst_env σ' Q) : by rw[ih]\n ... = (vc.subst x v (vc.subst_env σ' P) ⋀\n vc.subst x v (vc.subst_env σ' Q)) : by refl\n ... = (vc.subst_env (σ'[x↦v]) P ⋀\n vc.subst x v (vc.subst_env σ' Q)) : by unfold vc.subst_env\n ... = (vc.subst_env (σ'[x↦v]) P ⋀ vc.subst_env (σ'[x↦v]) Q)\n : by unfold vc.subst_env\nend\n\nlemma vc.subst_env.or {σ: env} {P Q: vc}:\n vc.subst_env σ (P ⋁ Q) = (vc.subst_env σ P ⋁ vc.subst_env σ Q) :=\nbegin\n induction σ with σ' x v ih,\n\n show (vc.subst_env env.empty (P ⋁ Q) = (vc.subst_env env.empty P ⋁ vc.subst_env env.empty Q)),\n by calc\n vc.subst_env env.empty (P ⋁ Q) = (P ⋁ Q) : by unfold vc.subst_env\n ... = (vc.subst_env env.empty P ⋁ Q) : by by unfold vc.subst_env\n ... = (vc.subst_env env.empty P ⋁ vc.subst_env env.empty Q)\n : by unfold vc.subst_env,\n\n show (vc.subst_env (σ'[x↦v]) (P ⋁ Q) = (vc.subst_env (σ'[x↦v]) P ⋁ vc.subst_env (σ'[x↦v]) Q)),\n by calc\n vc.subst_env (σ'[x↦v]) (P ⋁ Q) = vc.subst x v (vc.subst_env σ' (P ⋁ Q)) : by unfold vc.subst_env\n ... = vc.subst x v (vc.subst_env σ' P ⋁ vc.subst_env σ' Q) : by rw[ih]\n ... = (vc.subst x v (vc.subst_env σ' P) ⋁\n vc.subst x v (vc.subst_env σ' Q)) : by refl\n ... = (vc.subst_env (σ'[x↦v]) P ⋁\n vc.subst x v (vc.subst_env σ' Q)) : by unfold vc.subst_env\n ... = (vc.subst_env (σ'[x↦v]) P ⋁ vc.subst_env (σ'[x↦v]) Q)\n : by unfold vc.subst_env\nend\n\nlemma vc.subst_env.implies {σ: env} {P Q: vc}:\n vc.subst_env σ (vc.implies P Q) = vc.implies (vc.subst_env σ P) (vc.subst_env σ Q) :=\n have h1: vc.subst_env σ (vc.implies P Q) = vc.subst_env σ (vc.or P.not Q), from rfl,\n have vc.subst_env σ (vc.or P.not Q) = vc.or (vc.subst_env σ P.not) (vc.subst_env σ Q), from vc.subst_env.or,\n have h2: vc.subst_env σ (vc.implies P Q) = vc.or (vc.subst_env σ P.not) (vc.subst_env σ Q), from eq.trans h1 this,\n have vc.subst_env σ (vc.not P) = vc.not (vc.subst_env σ P), from vc.subst_env.not,\n show vc.subst_env σ (vc.implies P Q) = vc.or (vc.subst_env σ P).not (vc.subst_env σ Q), from this ▸ h2\n\nlemma vc.subst_env.pre₁ {σ: env} {op: unop} {t: term}:\n vc.subst_env σ (vc.pre₁ op t) = vc.pre₁ op (term.subst_env σ t) :=\nbegin\n induction σ with σ' x v ih,\n\n show (vc.subst_env env.empty (vc.pre₁ op t) = vc.pre₁ op (term.subst_env env.empty t)),\n by calc\n vc.subst_env env.empty (vc.pre₁ op t) = (vc.pre₁ op t) : by unfold vc.subst_env\n ... = (vc.pre₁ op (term.subst_env env.empty t)) : by unfold term.subst_env,\n\n show (vc.subst_env (σ'[x↦v]) (vc.pre₁ op t) = vc.pre₁ op (term.subst_env (σ'[x↦v]) t)),\n by calc\n vc.subst_env (σ'[x↦v]) (vc.pre₁ op t) = vc.subst x v (vc.subst_env σ' (vc.pre₁ op t)) : by unfold vc.subst_env\n ... = vc.subst x v (vc.pre₁ op (term.subst_env σ' t)) : by rw[ih]\n ... = vc.pre₁ op (term.subst x v (term.subst_env σ' t)) : by unfold vc.subst\n ... = vc.pre₁ op (term.subst_env (σ'[x↦v]) t) : by unfold term.subst_env\nend\n\nlemma vc.subst_env.pre₂ {σ: env} {op: binop} {t₁ t₂: term}:\n vc.subst_env σ (vc.pre₂ op t₁ t₂) = vc.pre₂ op (term.subst_env σ t₁) (term.subst_env σ t₂) :=\nbegin\n induction σ with σ' x v ih,\n\n show (vc.subst_env env.empty (vc.pre₂ op t₁ t₂)\n = vc.pre₂ op (term.subst_env env.empty t₁) (term.subst_env env.empty t₂)),\n by calc\n vc.subst_env env.empty (vc.pre₂ op t₁ t₂)\n = (vc.pre₂ op t₁ t₂) : by unfold vc.subst_env\n ... = (vc.pre₂ op (term.subst_env env.empty t₁) t₂) : by unfold term.subst_env\n ... = (vc.pre₂ op (term.subst_env env.empty t₁) (term.subst_env env.empty t₂)) : by unfold term.subst_env,\n\n show (vc.subst_env (σ'[x↦v]) (vc.pre₂ op t₁ t₂)\n = vc.pre₂ op (term.subst_env (σ'[x↦v]) t₁) (term.subst_env (σ'[x↦v]) t₂)),\n by calc\n vc.subst_env (σ'[x↦v]) (vc.pre₂ op t₁ t₂)\n = vc.subst x v (vc.subst_env σ' (vc.pre₂ op t₁ t₂)) : by unfold vc.subst_env\n ... = vc.subst x v (vc.pre₂ op (term.subst_env σ' t₁) (term.subst_env σ' t₂)) : by rw[ih]\n ... = vc.pre₂ op (term.subst x v (term.subst_env σ' t₁)) (term.subst x v (term.subst_env σ' t₂)) : by unfold vc.subst\n ... = vc.pre₂ op (term.subst_env (σ'[x↦v]) t₁) (term.subst x v (term.subst_env σ' t₂)) : by unfold term.subst_env\n ... = vc.pre₂ op (term.subst_env (σ'[x↦v]) t₁) (term.subst_env (σ'[x↦v]) t₂) : by unfold term.subst_env\nend\n\nlemma vc.subst_env.pre {σ: env} {t₁ t₂: term}:\n vc.subst_env σ (vc.pre t₁ t₂) = vc.pre (term.subst_env σ t₁) (term.subst_env σ t₂) :=\nbegin\n induction σ with σ' x v ih,\n\n show (vc.subst_env env.empty (vc.pre t₁ t₂)\n = vc.pre (term.subst_env env.empty t₁) (term.subst_env env.empty t₂)),\n by calc\n vc.subst_env env.empty (vc.pre t₁ t₂)\n = (vc.pre t₁ t₂) : by unfold vc.subst_env\n ... = (vc.pre (term.subst_env env.empty t₁) t₂) : by unfold term.subst_env\n ... = (vc.pre (term.subst_env env.empty t₁) (term.subst_env env.empty t₂)) : by unfold term.subst_env,\n\n show (vc.subst_env (σ'[x↦v]) (vc.pre t₁ t₂)\n = vc.pre (term.subst_env (σ'[x↦v]) t₁) (term.subst_env (σ'[x↦v]) t₂)),\n by calc\n vc.subst_env (σ'[x↦v]) (vc.pre t₁ t₂)\n = vc.subst x v (vc.subst_env σ' (vc.pre t₁ t₂)) : by unfold vc.subst_env\n ... = vc.subst x v (vc.pre (term.subst_env σ' t₁) (term.subst_env σ' t₂)) : by rw[ih]\n ... = vc.pre (term.subst x v (term.subst_env σ' t₁)) (term.subst x v (term.subst_env σ' t₂)) : by unfold vc.subst\n ... = vc.pre (term.subst_env (σ'[x↦v]) t₁) (term.subst x v (term.subst_env σ' t₂)) : by unfold term.subst_env\n ... = vc.pre (term.subst_env (σ'[x↦v]) t₁) (term.subst_env (σ'[x↦v]) t₂) : by unfold term.subst_env\nend\n\nlemma vc.subst_env.post {σ: env} {t₁ t₂: term}:\n vc.subst_env σ (vc.post t₁ t₂) = vc.post (term.subst_env σ t₁) (term.subst_env σ t₂) :=\nbegin\n induction σ with σ' x v ih,\n\n show (vc.subst_env env.empty (vc.post t₁ t₂)\n = vc.post (term.subst_env env.empty t₁) (term.subst_env env.empty t₂)),\n by calc\n vc.subst_env env.empty (vc.post t₁ t₂)\n = (vc.post t₁ t₂) : by unfold vc.subst_env\n ... = (vc.post (term.subst_env env.empty t₁) t₂) : by unfold term.subst_env\n ... = (vc.post (term.subst_env env.empty t₁) (term.subst_env env.empty t₂)) : by unfold term.subst_env,\n\n show (vc.subst_env (σ'[x↦v]) (vc.post t₁ t₂)\n = vc.post (term.subst_env (σ'[x↦v]) t₁) (term.subst_env (σ'[x↦v]) t₂)),\n by calc\n vc.subst_env (σ'[x↦v]) (vc.post t₁ t₂)\n = vc.subst x v (vc.subst_env σ' (vc.post t₁ t₂)) : by unfold vc.subst_env\n ... = vc.subst x v (vc.post (term.subst_env σ' t₁) (term.subst_env σ' t₂)) : by rw[ih]\n ... = vc.post (term.subst x v (term.subst_env σ' t₁)) (term.subst x v (term.subst_env σ' t₂)) : by unfold vc.subst\n ... = vc.post (term.subst_env (σ'[x↦v]) t₁) (term.subst x v (term.subst_env σ' t₂)) : by unfold term.subst_env\n ... = vc.post (term.subst_env (σ'[x↦v]) t₁) (term.subst_env (σ'[x↦v]) t₂) : by unfold term.subst_env\nend\n\nlemma vc.subst_env.univ_not_in {σ: env} {x: var} {P: vc}:\n (x ∉ σ) → (vc.subst_env σ (vc.univ x P) = vc.univ x (vc.subst_env σ P)) :=\nbegin\n assume x_not_in_σ,\n induction σ with σ' y v ih,\n\n show (vc.subst_env env.empty (vc.univ x P) = vc.univ x (vc.subst_env env.empty P)),\n by calc\n vc.subst_env env.empty (vc.univ x P) = (vc.univ x P) : by unfold vc.subst_env\n ... = vc.univ x (vc.subst_env env.empty P) : by unfold vc.subst_env,\n\n show (vc.subst_env (σ'[y↦v]) (vc.univ x P) = vc.univ x (vc.subst_env (σ'[y↦v]) P)), from (\n have ¬ (x = y ∨ x ∈ σ'), from env.contains.same.inv x_not_in_σ,\n have x_neq_y: x ≠ y, from (not_or_distrib.mp this).left,\n have x ∉ σ', from (not_or_distrib.mp this).right,\n have h: vc.subst_env σ' (vc.univ x P) = vc.univ x (vc.subst_env σ' P), from ih this,\n\n calc\n vc.subst_env (σ'[y↦v]) (vc.univ x P)\n = vc.subst y v (vc.subst_env σ' (vc.univ x P)) : by unfold vc.subst_env\n ... = vc.subst y v (vc.univ x (vc.subst_env σ' P)) : by rw[h]\n ... = vc.univ x (if y = x then vc.subst_env σ' P else (vc.subst_env σ' P).subst y v) : by unfold vc.subst\n ... = vc.univ x ((vc.subst_env σ' P).subst y v) : by simp[x_neq_y.symm]\n ... = vc.univ x (vc.subst_env (σ'[y↦v]) P) : by unfold vc.subst_env\n )\nend\n\nlemma vc.subst_env.univ {σ: env} {x: var} {P: vc}:\n (vc.subst_env σ (vc.univ x P) = vc.univ x (vc.subst_env (σ.without x) P)) :=\nbegin\n induction σ with σ' y v ih,\n\n show (vc.subst_env env.empty (vc.univ x P) = vc.univ x (vc.subst_env (env.empty.without x) P)),\n by calc\n vc.subst_env env.empty (vc.univ x P) = (vc.univ x P) : by unfold vc.subst_env\n ... = vc.univ x (vc.subst_env env.empty P) : by unfold vc.subst_env,\n\n show (vc.subst_env (σ'[y↦v]) (vc.univ x P) = vc.univ x (vc.subst_env ((σ'[y↦v]).without x) P)), by begin\n unfold vc.subst_env,\n by_cases (y = x) with h1,\n rw[←h1],\n rw[←h1] at ih,\n unfold env.without,\n simp,\n have : y ∉ FV (vc.subst_env σ' (vc.univ y P)), from (\n assume : y ∈ FV (vc.subst_env σ' (vc.univ y P)),\n have y ∈ FV (vc.univ y P), from vc.free_of_free_subst_env this,\n show «false», from free_in_vc.univ.same.inv this\n ),\n have h2: (vc.subst y v (vc.subst_env σ' (vc.univ y P)) = vc.subst_env σ' (vc.univ y P)),\n from unchanged_of_subst_nonfree_vc this,\n rw[h2],\n from ih,\n\n unfold env.without,\n simp[h1],\n unfold vc.subst_env,\n have : (vc.subst y v (vc.univ x (vc.subst_env (env.without σ' x) P))\n = vc.univ x (vc.subst y v (vc.subst_env (env.without σ' x) P))),\n by { unfold vc.subst, simp[h1] },\n rw[←this],\n congr,\n from ih \n end\nend\n\nlemma term.closed_subst.value {v: value} {σ: env}: closed_subst σ (term.value v) :=\n assume x: var,\n assume : x ∈ FV (term.value v),\n show x ∈ σ.dom, from absurd this free_in_term.value.inv\n\nlemma prop.closed_subst.term {t: term} {σ: env}: closed_subst σ t → closed_subst σ (prop.term t) :=\n assume t_closed: closed_subst σ t,\n show closed_subst σ (prop.term t), from (\n assume x: var,\n assume : x ∈ FV (prop.term t),\n have free_in_term x t, from free_in_prop.term.inv this,\n show x ∈ σ.dom, from t_closed this\n )\n\nlemma prop.closed_subst.and {P Q: prop} {σ: env}: closed_subst σ P → closed_subst σ Q → closed_subst σ (P ⋀ Q) :=\n assume P_closed: closed_subst σ P,\n assume Q_closed: closed_subst σ Q,\n show closed_subst σ (P ⋀ Q), from (\n assume x: var,\n assume : x ∈ FV (P ⋀ Q),\n or.elim (free_in_prop.and.inv this) (\n assume : x ∈ FV P,\n show x ∈ σ.dom, from P_closed this\n ) (\n assume : x ∈ FV Q,\n show x ∈ σ.dom, from Q_closed this\n )\n )\n\nlemma prop.closed_subst.or {P Q: prop} {σ: env}: closed_subst σ P → closed_subst σ Q → closed_subst σ (P ⋁ Q) :=\n assume P_closed_subst: closed_subst σ P,\n assume Q_closed_subst: closed_subst σ Q,\n show closed_subst σ (P ⋁ Q), from (\n assume x: var,\n assume : x ∈ FV (P ⋁ Q),\n or.elim (free_in_prop.or.inv this) (\n assume : x ∈ FV P,\n show x ∈ σ.dom, from P_closed_subst this\n ) (\n assume : x ∈ FV Q,\n show x ∈ σ.dom, from Q_closed_subst this\n )\n )\n\nlemma prop.closed_subst.not {P: prop} {σ: env}: closed_subst σ P → closed_subst σ P.not :=\n assume P_closed_subst: closed_subst σ P,\n show closed_subst σ P.not, from (\n assume x: var,\n assume : x ∈ FV P.not,\n have x ∈ FV P, from free_in_prop.not.inv this,\n show x ∈ σ.dom, from P_closed_subst this\n )\n\nlemma prop.closed_subst.implies {P Q: prop} {σ: env}:\n closed_subst σ P → closed_subst σ Q → closed_subst σ (prop.implies P Q) :=\n assume P_closed_subst: closed_subst σ P,\n have P_not_closed_subst: closed_subst σ P.not, from prop.closed_subst.not P_closed_subst,\n assume Q_closed_subst: closed_subst σ Q,\n show closed_subst σ (P.not ⋁ Q), from prop.closed_subst.or P_not_closed_subst Q_closed_subst\n\nlemma prop.closed_subst.and.inv {P Q: prop} {σ: env}: closed_subst σ (P ⋀ Q) → (closed_subst σ P ∧ closed_subst σ Q) :=\n assume P_and_Q_closed_subst: closed_subst σ (P ⋀ Q),\n have P_closed_subst: closed_subst σ P, from (\n assume x: var,\n assume : x ∈ FV P,\n have x ∈ FV (P ⋀ Q), from free_in_prop.and₁ this,\n show x ∈ σ.dom, from P_and_Q_closed_subst this\n ),\n have Q_closed_subst: closed_subst σ Q, from (\n assume x: var,\n assume : x ∈ FV Q,\n have x ∈ FV (P ⋀ Q), from free_in_prop.and₂ this,\n show x ∈ σ.dom, from P_and_Q_closed_subst this\n ),\n ⟨P_closed_subst, Q_closed_subst⟩\n\nlemma prop.closed_subst.or.inv {P Q: prop} {σ: env}: closed_subst σ (P ⋁ Q) → (closed_subst σ P ∧ closed_subst σ Q) :=\n assume P_or_Q_closed_subst: closed_subst σ (P ⋁ Q),\n have P_closed_subst: closed_subst σ P, from (\n assume x: var,\n assume : x ∈ FV P,\n have x ∈ FV (P ⋁ Q), from free_in_prop.or₁ this,\n show x ∈ σ.dom, from P_or_Q_closed_subst this\n ),\n have Q_closed_subst: closed_subst σ Q, from (\n assume x: var,\n assume : x ∈ FV Q,\n have x ∈ FV (P ⋁ Q), from free_in_prop.or₂ this,\n show x ∈ σ.dom, from P_or_Q_closed_subst this\n ),\n ⟨P_closed_subst, Q_closed_subst⟩\n\nlemma prop.closed_subst.not.inv {P: prop} {σ: env}: closed_subst σ P.not → closed_subst σ P :=\n assume P_not_closed_subst: closed_subst σ P.not,\n show closed_subst σ P, from (\n assume x: var,\n assume : x ∈ FV P,\n have x ∈ FV P.not, from free_in_prop.not this,\n show x ∈ σ.dom, from P_not_closed_subst this\n )\n\nlemma prop.closed_subst.implies.inv {P Q: prop} {σ: env}:\n closed_subst σ (prop.implies P Q) → closed_subst σ P ∧ closed_subst σ Q :=\n assume P_not_or_Q_closed_subst: closed_subst σ (P.not ⋁ Q),\n have P_not_closed_subst: closed_subst σ P.not, from (prop.closed_subst.or.inv P_not_or_Q_closed_subst).left,\n have P_closed_subst: closed_subst σ P, from prop.closed_subst.not.inv P_not_closed_subst,\n have Q_closed_subst: closed_subst σ Q, from (prop.closed_subst.or.inv P_not_or_Q_closed_subst).right,\n ⟨P_closed_subst, Q_closed_subst⟩\n\nlemma prop.closed_subst.subst {P: prop} {σ: env} {x: var} {v: value}:\n closed_subst σ P → closed_subst σ (prop.subst x v P) :=\n assume P_closed_subst: closed_subst σ P,\n show closed_subst σ (prop.subst x v P), from (\n assume y: var,\n assume : y ∈ FV (prop.subst x v P),\n have y ∈ FV P, from (free_of_subst_prop this).right,\n show y ∈ σ.dom, from P_closed_subst this\n )\n\nlemma vc.closed_subst.term {t: term} {σ: env}: closed_subst σ t → closed_subst σ (vc.term t) :=\n assume t_closed: closed_subst σ t,\n show closed_subst σ (vc.term t), from (\n assume x: var,\n assume : x ∈ FV (vc.term t),\n have free_in_term x t, from free_in_vc.term.inv this,\n show x ∈ σ.dom, from t_closed this\n )\n\nlemma vc.closed_subst.and {P Q: vc} {σ: env}: closed_subst σ P → closed_subst σ Q → closed_subst σ (P ⋀ Q) :=\n assume P_closed_subst: closed_subst σ P,\n assume Q_closed_subst: closed_subst σ Q,\n show closed_subst σ (P ⋀ Q), from (\n assume x: var,\n assume : x ∈ FV (P ⋀ Q),\n or.elim (free_in_vc.and.inv this) (\n assume : x ∈ FV P,\n show x ∈ σ.dom, from P_closed_subst this\n ) (\n assume : x ∈ FV Q,\n show x ∈ σ.dom, from Q_closed_subst this\n )\n )\n\nlemma vc.closed_subst.or {P Q: vc} {σ: env}: closed_subst σ P → closed_subst σ Q → closed_subst σ (P ⋁ Q) :=\n assume P_closed_subst: closed_subst σ P,\n assume Q_closed_subst: closed_subst σ Q,\n show closed_subst σ (P ⋁ Q), from (\n assume x: var,\n assume : x ∈ FV (P ⋁ Q),\n or.elim (free_in_vc.or.inv this) (\n assume : x ∈ FV P,\n show x ∈ σ.dom, from P_closed_subst this\n ) (\n assume : x ∈ FV Q,\n show x ∈ σ.dom, from Q_closed_subst this\n )\n )\n\nlemma vc.closed_subst.not {P: vc} {σ: env}: closed_subst σ P → closed_subst σ P.not :=\n assume P_closed_subst: closed_subst σ P,\n show closed_subst σ P.not, from (\n assume x: var,\n assume : x ∈ FV P.not,\n have x ∈ FV P, from free_in_vc.not.inv this,\n show x ∈ σ.dom, from P_closed_subst this\n )\n\nlemma vc.closed_subst.implies {P Q: vc} {σ: env}:\n closed_subst σ P → closed_subst σ Q → closed_subst σ (vc.implies P Q) :=\n assume P_closed_subst: closed_subst σ P,\n have P_not_closed_subst: closed_subst σ P.not, from vc.closed_subst.not P_closed_subst,\n assume Q_closed_subst: closed_subst σ Q,\n show closed_subst σ (P.not ⋁ Q), from vc.closed_subst.or P_not_closed_subst Q_closed_subst\n\nlemma vc.closed_subst.term.inv {t: term} {σ: env}: closed_subst σ (vc.term t) → closed_subst σ t :=\n assume t_closed: closed_subst σ (vc.term t),\n show closed_subst σ t, from (\n assume x: var,\n assume : x ∈ FV t,\n have free_in_vc x (vc.term t), from free_in_vc.term this,\n show x ∈ σ.dom, from t_closed this\n )\n\nlemma vc.closed_subst.and.inv {P Q: vc} {σ: env}: closed_subst σ (P ⋀ Q) → (closed_subst σ P ∧ closed_subst σ Q) :=\n assume P_and_Q_closed_subst: closed_subst σ (P ⋀ Q),\n have P_closed_subst: closed_subst σ P, from (\n assume x: var,\n assume : x ∈ FV P,\n have x ∈ FV (P ⋀ Q), from free_in_vc.and₁ this,\n show x ∈ σ.dom, from P_and_Q_closed_subst this\n ),\n have Q_closed_subst: closed_subst σ Q, from (\n assume x: var,\n assume : x ∈ FV Q,\n have x ∈ FV (P ⋀ Q), from free_in_vc.and₂ this,\n show x ∈ σ.dom, from P_and_Q_closed_subst this\n ),\n ⟨P_closed_subst, Q_closed_subst⟩\n\nlemma vc.closed_subst.or.inv {P Q: vc} {σ: env}: closed_subst σ (P ⋁ Q) → (closed_subst σ P ∧ closed_subst σ Q) :=\n assume P_or_Q_closed_subst: closed_subst σ (P ⋁ Q),\n have P_closed_subst: closed_subst σ P, from (\n assume x: var,\n assume : x ∈ FV P,\n have x ∈ FV (P ⋁ Q), from free_in_vc.or₁ this,\n show x ∈ σ.dom, from P_or_Q_closed_subst this\n ),\n have Q_closed_subst: closed_subst σ Q, from (\n assume x: var,\n assume : x ∈ FV Q,\n have x ∈ FV (P ⋁ Q), from free_in_vc.or₂ this,\n show x ∈ σ.dom, from P_or_Q_closed_subst this\n ),\n ⟨P_closed_subst, Q_closed_subst⟩\n\nlemma vc.closed_subst.not.inv {P: vc} {σ: env}: closed_subst σ P.not → closed_subst σ P :=\n assume P_not_closed_subst: closed_subst σ P.not,\n show closed_subst σ P, from (\n assume x: var,\n assume : x ∈ FV P,\n have x ∈ FV P.not, from free_in_vc.not this,\n show x ∈ σ.dom, from P_not_closed_subst this\n )\n\nlemma vc.closed_subst.implies.inv {P Q: vc} {σ: env}:\n closed_subst σ (vc.implies P Q) → closed_subst σ P ∧ closed_subst σ Q :=\n assume P_not_or_Q_closed_subst: closed_subst σ (P.not ⋁ Q),\n have P_not_closed_subst: closed_subst σ P.not, from (vc.closed_subst.or.inv P_not_or_Q_closed_subst).left,\n have P_closed_subst: closed_subst σ P, from vc.closed_subst.not.inv P_not_closed_subst,\n have Q_closed_subst: closed_subst σ Q, from (vc.closed_subst.or.inv P_not_or_Q_closed_subst).right,\n ⟨P_closed_subst, Q_closed_subst⟩\n\nlemma to_vc_closed_from_prop_closed {P: prop} {σ: env}: closed_subst σ P → closed_subst σ P.to_vc :=\n assume h1: closed_subst σ P,\n show closed_subst σ P.to_vc, from (\n assume x: var,\n assume : x ∈ FV P.to_vc,\n have x ∈ FV P, from set.mem_of_mem_of_subset this free_in_prop_of_free_in_to_vc,\n show x ∈ σ.dom, from h1 this\n )\n\nlemma erased_p_closed_from_prop_closed {P: prop} {σ: env}: closed_subst σ P → closed_subst σ P.erased_p :=\n assume h1: closed_subst σ P,\n show closed_subst σ P.erased_p, from (\n assume x: var,\n assume : x ∈ FV P.erased_p,\n have x ∈ FV P, from set.mem_of_mem_of_subset this free_in_prop_of_free_in_erased.left,\n show x ∈ σ.dom, from h1 this\n )\n\nlemma erased_n_closed_from_prop_closed {P: prop} {σ: env}: closed_subst σ P → closed_subst σ P.erased_n :=\n assume h1: closed_subst σ P,\n show closed_subst σ P.erased_n, from (\n assume x: var,\n assume : x ∈ FV P.erased_n,\n have x ∈ FV P, from set.mem_of_mem_of_subset this free_in_prop_of_free_in_erased.right,\n show x ∈ σ.dom, from h1 this\n )\n\nlemma subst_closed_of_forall_closed {P: prop} {σ: env} {x: var} {v: value}:\n closed_subst σ (prop.forallc x P) → closed_subst σ (prop.subst x v P) :=\n assume h1: closed_subst σ (prop.forallc x P),\n show closed_subst σ (prop.subst x v P), from (\n assume y: var,\n assume : y ∈ FV (prop.subst x v P),\n have y ≠ x ∧ y ∈ FV P, from free_of_subst_prop this,\n have y ∈ FV (prop.forallc x P), from free_in_prop.forallc this.left this.right,\n show y ∈ σ, from h1 this\n )\n\nlemma contains_of_free_in_nonempty_env {σ: env} {x y: var} {v: value}: (x ≠ y → y ∈ σ) → y ∈ (σ[x↦v]) :=\n assume ih: x ≠ y → y ∈ σ,\n if x_eq_y: x = y ∧ option.is_none (σ.apply y) then (\n have h: σ[x↦v].apply x = (if x = x ∧ option.is_none (σ.apply x) then ↑v else σ.apply x), by unfold env.apply,\n have (if x = x ∧ option.is_none (σ.apply x) then ↑v else σ.apply x) = ↑v, by simp [x_eq_y],\n have σ[x↦v].apply x = ↑v, from eq.trans h this,\n have σ[x↦v].apply y = some v, from x_eq_y.left ▸ this,\n have ∃v', σ[x↦v] y = some v', from exists.intro v this,\n show y ∈ (σ[x↦v]), from env.contains_apply_equiv.right.mp this\n ) else (\n have y ∈ σ, from (\n have ¬(x = y) ∨ ¬(option.is_none (σ.apply y)), from not_and_distrib.mp x_eq_y,\n this.elim (\n assume : x ≠ y,\n show y ∈ σ, from ih this \n ) ( \n assume : ¬(option.is_none (env.apply σ y)),\n have ¬(option.is_none (σ y)), from this,\n have option.is_some (σ y), from option.some_iff_not_none.mpr this,\n have ∃v', σ y = some v', from option.is_some_iff_exists.mp this,\n show y ∈ σ, from env.contains_apply_equiv.right.mp this\n )\n ),\n let ⟨v', σ_has_y⟩ := (env.contains_apply_equiv.right.mpr this) in\n have h: σ[x↦v].apply y = (if x = y ∧ option.is_none (σ.apply y) then ↑v else σ.apply y), by unfold env.apply,\n have (if x = y ∧ option.is_none (σ.apply y) then ↑v else σ.apply y) = σ.apply y, by simp *,\n have σ[x↦v].apply y = σ.apply y, from this ▸ h,\n have σ[x↦v].apply y = some v', from eq.trans this σ_has_y,\n have ∃v', σ[x↦v] y = some v', from exists.intro v' this,\n show y ∈ (σ[x↦v]), from env.contains_apply_equiv.right.mp this\n )\n\nlemma contains_of_free_eq_value {P: prop} {σ: env} {x y: var} {v: value}:\n x ∈ FV (P ⋀ (y ≡ v)) → (x ∈ FV P → x ∈ σ) → x ∈ (σ[y↦v]) :=\n assume x_free_in_P: x ∈ FV (P ⋀ (y ≡ v)),\n assume ih : x ∈ FV P → x ∈ σ,\n contains_of_free_in_nonempty_env (\n assume x'_is_not_x: y ≠ x,\n have free_in_prop x P ∨ free_in_prop x (y ≡ v), from free_in_prop.and.inv x_free_in_P,\n or.elim this (\n assume x_free_in_P: free_in_prop x P,\n show x ∈ σ, from ih x_free_in_P\n ) (\n assume x_free_in_eq_v: free_in_prop x (y ≡ v),\n show x ∈ σ, by begin\n cases x_free_in_eq_v,\n case free_in_prop.term x_free_in_eq {\n cases x_free_in_eq,\n case free_in_term.binop₁ free_in_y {\n have y_is_x: (y = x), from (free_in_term.var.inv free_in_y).symm,\n contradiction\n },\n case free_in_term.binop₂ free_in_v {\n cases free_in_v\n }\n }\n end\n )\n )\n\nlemma env.dom.inv {σ: env} {x: var} {v: value}: (σ[x↦v]).dom = (σ.dom ∪ set.insert x ∅) :=\n set.eq_of_subset_of_subset (\n assume y: var,\n assume : y ∈ (σ[x↦v]).dom,\n have y ∈ (σ[x↦v]), from this,\n or.elim (env.contains.inv this) (\n assume : y = x,\n have y ∈ set.insert x ∅, from set.mem_singleton_of_eq this,\n show y ∈ (σ.dom ∪ set.insert x ∅), from set.mem_union_right σ.dom this\n ) (\n assume : y ∈ σ,\n have y ∈ σ.dom, from this,\n show y ∈ (σ.dom ∪ set.insert x ∅), from set.mem_union_left (set.insert x ∅) this\n )\n ) (\n assume y: var,\n assume : y ∈ (σ.dom ∪ set.insert x ∅),\n or.elim (set.mem_or_mem_of_mem_union this) (\n assume : y ∈ σ.dom,\n have y ∈ σ, from this,\n have y ∈ (σ[x↦v]), from env.contains.rest this,\n show y ∈ (σ[x↦v]).dom, from this\n ) (\n assume : y ∈ set.insert x ∅,\n have y = x, from (set.mem_singleton_iff y x).mp this,\n have y ∈ (σ[x↦v]), from this ▸ env.contains.same,\n show y ∈ (σ[x↦v]).dom, from this\n )\n )\n\nlemma env.dom.two_elems {σ: env} {x y: var} {v₁ v₂: value}: (σ[x↦v₁][y↦v₂]).dom = σ.dom ∪ {x, y} :=\n by calc (σ[x↦v₁][y↦v₂]).dom = (σ[x↦v₁]).dom ∪ set.insert y ∅ : env.dom.inv\n ... = σ.dom ∪ set.insert x ∅ ∪ set.insert y ∅ : by rw[env.dom.inv]\n ... = σ.dom ∪ (set.insert x ∅ ∪ set.insert y ∅) : by rw[set.union_assoc]\n ... = σ.dom ∪ {x, y} : by rw[set.two_elems_of_insert]\n\nlemma env.apply_of_contains {σ: env} {x: var} {v: value}: x ∉ σ → ((σ[x↦v]) x = v) :=\n begin\n intro h,\n change (env.apply (σ[x↦v]) x = some v),\n unfold env.apply,\n by_cases (x = x ∧ (option.is_none (env.apply σ x))) with h2,\n simp[h2],\n refl,\n simp at h2,\n have h3, from env.contains_apply_equiv.left.mpr h,\n have h4: (env.apply σ x = none), from h3,\n rw[h4] at h2,\n unfold option.is_none at h2,\n have h5: (↑tt = «false»), from eq_false_intro h2,\n have h6: (↑tt = «true»), by simp,\n have h7: («false» = «true»), from eq.trans h5.symm h6,\n have h8: «true», from trivial,\n have r9: «false», from h7.symm ▸ h8,\n contradiction\n end\n\nlemma env.equiv_of_rest_and_same {σ σ': env} {x: var} {v: value}:\n (∀y, y ∈ σ → (σ y = σ' y)) → x ∉ σ → (σ' x = v) → (∀y, y ∈ (σ[x↦v]) → ((σ[x↦v]) y = σ' y)) :=\n assume h1: (∀y, y ∈ σ → (σ y = σ' y)),\n assume h2: x ∉ σ,\n assume h3: σ' x = v,\n assume y: var,\n assume h4: y ∈ (σ[x↦v]),\n if h: x = y then (\n have h5: (σ[x↦v]) y = v, from h ▸ env.apply_of_contains h2,\n show ((σ[x↦v]) y = σ' y), from eq.trans h5 (h ▸ h3.symm)\n ) else (\n have y ∈ σ, from (\n have y = x ∨ y ∈ σ, from env.contains.inv h4,\n or.elim this.symm id (\n assume : y = x,\n show y ∈ σ, from absurd this.symm h\n )\n ),\n have h6: σ y = σ' y, from h1 y this,\n have env.apply (σ[x↦v]) y = σ.apply y, by { unfold env.apply, simp[h] },\n have (σ[x↦v]) y = σ y, from this,\n show ((σ[x↦v]) y = σ' y), from this.symm ▸ h6\n )\n\nlemma env.equiv_of_not_contains {σ σ': env} {x: var} {v: value}:\n (∀y, y ∈ σ → (σ y = σ' y)) → x ∉ σ → (∀y, y ∈ σ → (σ y = (σ'[x↦v]) y)) :=\n assume h1: (∀y, y ∈ σ → (σ y = σ' y)),\n assume h2: x ∉ σ,\n assume y: var,\n assume h4: y ∈ σ,\n if h: x = y then (\n have x ∈ σ, from h.symm ▸ h4,\n show σ y = (σ'[x↦v]) y, from absurd this h2\n ) else (\n have h2: σ y = σ' y, from h1 y h4,\n have (∃v, σ y = some v), from env.contains_apply_equiv.right.mpr h4,\n have option.is_some (σ y), from option.is_some_iff_exists.mpr this,\n have ¬ option.is_none (σ y), from option.some_iff_not_none.mp this,\n have h5: ¬ (x = y ∧ option.is_none (env.apply σ' y)), from not_and_distrib.mpr (or.inl h),\n have env.apply (σ'[x↦v]) y = σ' y, by { unfold env.apply, simp[h5], refl },\n show σ y = (σ'[x↦v]) y, from eq.trans h2 this.symm\n )\n\nlemma env.apply_of_rest_apply {σ: env} {x y: var} {vx vy: value}:\n (σ x = vx) → ((σ[y↦vy]) x = vx) :=\n begin\n assume h1: (env.apply σ x = some vx),\n change (env.apply (σ[y↦vy]) x = ↑vx),\n unfold env.apply,\n have h2, from option.is_some_iff_exists.mpr (exists.intro vx h1),\n have h3, from option.some_iff_not_none.mp h2,\n have h4: ¬ (y = x ∧ (option.is_none (env.apply σ x))),\n from not_and_distrib.mpr (or.inr h3),\n simp[h4],\n from h1\n end\n\nlemma term.subst_env.order {t: term} {σ: env} {x: var} {v: value}:\n (x ∉ σ) ∨ (σ x = v) → (term.subst_env σ (term.subst x v t) = term.subst x v (term.subst_env σ t)) :=\n begin\n assume h1,\n induction t with v' y unop t₁ t₁_ih binop t₂ t₃ t₂_ih t₃_ih t₄ t₅ t₄_ih t₅_ih,\n \n show (term.subst_env σ (term.subst x v (term.value v')) = term.subst x v (term.subst_env σ (term.value v'))),\n by begin\n change (term.subst_env σ (term.subst x v (term.value v')) = term.subst x v (term.subst_env σ v')),\n rw[term.subst_env.value],\n unfold term.subst,\n rw[term.subst_env.value],\n change (↑v' = term.subst x v (term.value v')),\n unfold term.subst\n end,\n\n show (term.subst_env σ (term.subst x v (term.var y)) = term.subst x v (term.subst_env σ (term.var y))),\n by begin\n by_cases (x = y) with h,\n simp[h],\n rw[h] at h1,\n unfold term.subst,\n simp,\n cases h1,\n have : (σ y = none), from env.contains_apply_equiv.left.mpr a,\n have h2: (term.subst_env σ (term.var y) = y), from term.subst_env.var.left.mp this,\n simp[h2],\n rw[term.subst_env.value],\n change (↑v = term.subst y v (term.var y)),\n unfold term.subst,\n simp,\n\n have h2: (term.subst_env σ (term.var y) = v), from (term.subst_env.var.right v).mp a,\n rw[h2],\n change (term.subst_env σ ↑v = term.subst y v (term.value v)),\n unfold term.subst,\n rw[term.subst_env.value],\n\n have h2: (term.subst x v (term.var y) = y), from term.subst.var.diff h,\n rw[h2],\n by_cases (y ∈ σ) with h3,\n \n have h4, from env.contains_apply_equiv.right.mpr h3,\n cases h4 with v' h5,\n have h6: (term.subst_env σ y = v'), from (term.subst_env.var.right v').mp h5,\n rw[h6],\n change (↑v' = term.subst x v (term.subst_env σ ↑y)),\n rw[h6],\n change (↑v' = term.subst x v (term.value v')),\n unfold term.subst,\n\n have : (σ y = none), from env.contains_apply_equiv.left.mpr h3,\n have h4: (term.subst_env σ (term.var y) = y), from term.subst_env.var.left.mp this,\n simp[h4],\n change (term.subst_env σ (term.var y) = term.subst x v (term.var y)),\n rw[h2],\n rw[h4]\n end,\n\n show (term.subst_env σ (term.subst x v (term.unop unop t₁))\n = term.subst x v (term.subst_env σ (term.unop unop t₁))), by begin\n rw[term.subst_env.unop],\n unfold term.subst,\n rw[term.subst_env.unop],\n congr,\n from t₁_ih\n end,\n\n show (term.subst_env σ (term.subst x v (term.binop binop t₂ t₃))\n = term.subst x v (term.subst_env σ (term.binop binop t₂ t₃))), by begin\n rw[term.subst_env.binop],\n unfold term.subst,\n rw[term.subst_env.binop],\n congr,\n rw[t₂_ih],\n rw[t₃_ih]\n end,\n\n show (term.subst_env σ (term.subst x v (term.app t₄ t₅))\n = term.subst x v (term.subst_env σ (term.app t₄ t₅))), by begin\n rw[term.subst_env.app],\n unfold term.subst,\n rw[term.subst_env.app],\n congr,\n rw[t₄_ih],\n rw[t₅_ih]\n end\n end\n\nlemma term.substt_env.order {t' t: term} {σ: env} {x: var}:\n closed t' → (x ∉ σ) → (term.subst_env σ (term.substt x t' t) = term.substt x t' (term.subst_env σ t)) :=\n begin\n assume t'_closed,\n assume h1,\n induction t with v y unop t₁ t₁_ih binop t₂ t₃ t₂_ih t₃_ih t₄ t₅ t₄_ih t₅_ih,\n \n show (term.subst_env σ (term.substt x t' (term.value v)) = term.substt x t' (term.subst_env σ (term.value v))),\n by begin\n change (term.subst_env σ (term.substt x t' (term.value v)) = term.substt x t' (term.subst_env σ v)),\n rw[term.subst_env.value],\n unfold term.substt,\n rw[term.subst_env.value],\n change (↑v = term.substt x t' (term.value v)),\n unfold term.substt\n end,\n\n show (term.subst_env σ (term.substt x t' (term.var y)) = term.substt x t' (term.subst_env σ (term.var y))),\n by begin\n by_cases (x = y) with h,\n simp[h],\n rw[h] at h1,\n unfold term.substt,\n simp,\n have : (σ y = none), from env.contains_apply_equiv.left.mpr h1,\n have h2: (term.subst_env σ (term.var y) = y), from term.subst_env.var.left.mp this,\n simp[h2],\n rw[term.subst_env.closed t'_closed],\n change (t' = term.substt y t' (term.var y)),\n unfold term.substt,\n simp,\n\n have h2: (term.substt x t' (term.var y) = y), from term.substt.var.diff h,\n rw[h2],\n by_cases (y ∈ σ) with h3,\n \n have h4, from env.contains_apply_equiv.right.mpr h3,\n cases h4 with v' h5,\n have h6: (term.subst_env σ y = v'), from (term.subst_env.var.right v').mp h5,\n rw[h6],\n change (↑v' = term.substt x t' (term.subst_env σ ↑y)),\n rw[h6],\n change (↑v' = term.substt x t' (term.value v')),\n unfold term.substt,\n\n have : (σ y = none), from env.contains_apply_equiv.left.mpr h3,\n have h4: (term.subst_env σ (term.var y) = y), from term.subst_env.var.left.mp this,\n simp[h4],\n change (term.subst_env σ (term.var y) = term.substt x t' (term.var y)),\n rw[h2],\n rw[h4]\n end,\n\n show (term.subst_env σ (term.substt x t' (term.unop unop t₁))\n = term.substt x t' (term.subst_env σ (term.unop unop t₁))), by begin\n rw[term.subst_env.unop],\n unfold term.substt,\n rw[term.subst_env.unop],\n congr,\n from t₁_ih\n end,\n\n show (term.subst_env σ (term.substt x t' (term.binop binop t₂ t₃))\n = term.substt x t' (term.subst_env σ (term.binop binop t₂ t₃))), by begin\n rw[term.subst_env.binop],\n unfold term.substt,\n rw[term.subst_env.binop],\n congr,\n rw[t₂_ih],\n rw[t₃_ih]\n end,\n\n show (term.subst_env σ (term.substt x t' (term.app t₄ t₅))\n = term.substt x t' (term.subst_env σ (term.app t₄ t₅))), by begin\n rw[term.subst_env.app],\n unfold term.substt,\n rw[term.subst_env.app],\n congr,\n rw[t₄_ih],\n rw[t₅_ih]\n end\n end\n\nlemma term.subst_env_inner {t: term} {σ: env} {x: var} {v: value}:\n (σ x = some v) → (term.subst_env σ (term.subst x v t) = term.subst_env σ t) :=\n begin\n assume x_is_v,\n\n induction σ with σ₁ y v' ih,\n\n show (term.subst_env env.empty (term.subst x v t) = term.subst_env env.empty t), by cases x_is_v,\n\n show (term.subst_env (σ₁[y↦v']) (term.subst x v t) = term.subst_env (σ₁[y↦v']) t), by begin\n unfold term.subst_env,\n have h2: (env.apply (σ₁[y↦v']) x = some v), from x_is_v,\n unfold env.apply at h2,\n by_cases (y = x ∧ (option.is_none (env.apply σ₁ x))) with h3,\n simp[h3] at h2,\n have h4: (v' = v), from option.some.inj h2,\n simp[h3],\n have h5: (σ₁ x = none), from option.is_none.inv.mpr h3.right,\n have h6: x ∉ σ₁, from env.contains_apply_equiv.left.mp h5,\n rw[h4],\n have h7: x ∉ FV (term.subst x v t), from term.not_free_of_subst,\n have h8: x ∉ FV (term.subst_env σ₁ (term.subst x v t)),\n have : ¬(free_in_term x (term.subst x v t) ∧ x ∉ σ₁), by begin\n assume : free_in_term x (term.subst x v t) ∧ x ∉ σ₁,\n show «false», from h7 this.left\n end,\n from mt free_of_subst_env_term this,\n have h9: (term.subst x v (term.subst_env σ₁ (term.subst x v t)) = (term.subst_env σ₁ (term.subst x v t))),\n from unchanged_of_subst_nonfree_term h8,\n rw[h9],\n from term.subst_env.order (or.inl h6),\n\n simp[h3] at h2,\n have h4, from ih h2,\n congr,\n from h4\n end\n end\n\nlemma term.subst_env_twice {t: term} {σ: env}:\n term.subst_env σ (term.subst_env σ t) = term.subst_env σ t :=\n begin\n induction σ with σ' x v ih,\n \n show (term.subst_env env.empty (term.subst_env env.empty t) = term.subst_env env.empty t), by begin\n unfold term.subst_env\n end,\n\n show (term.subst_env (σ'[x↦v]) (term.subst_env (σ'[x↦v]) t) = term.subst_env (σ'[x↦v]) t), by begin\n\n by_cases (x ∈ σ') with h1,\n unfold term.subst_env,\n\n have h2: x ∉ FV (term.subst_env σ' t), from term.not_free_of_subst_env h1,\n have h3: (term.subst x v (term.subst_env σ' t) = (term.subst_env σ' t)),\n from unchanged_of_subst_nonfree_term h2,\n rw[h3],\n have h4: x ∉ FV (term.subst_env σ' (term.subst_env σ' t)), from term.not_free_of_subst_env h1,\n have h5: (term.subst x v (term.subst_env σ' (term.subst_env σ' t)) = (term.subst_env σ' (term.subst_env σ' t))),\n from unchanged_of_subst_nonfree_term h4,\n rw[h5],\n from ih,\n\n have h6: (term.subst_env (σ'[x↦v]) t = term.subst x v (term.subst_env σ' t)),\n by unfold term.subst_env,\n rw[h6],\n\n have h7: (env.apply (σ'[x↦v]) x = v), from env.apply_of_contains h1,\n have h8: (term.subst_env (σ'[x↦v]) (term.subst x v (term.subst_env σ' t))\n = term.subst_env (σ'[x↦v]) (term.subst_env σ' t)),\n from term.subst_env_inner h7,\n rw[h8],\n unfold term.subst_env,\n congr,\n from ih\n end\n end\n\nlemma env.dom_subset_of_equivalent_env {σ₁ σ₂: env}:\n (∀z, z ∈ σ₁ → (σ₁ z = σ₂ z)) → (σ₁.dom ⊆ σ₂.dom) :=\n assume env_equiv: (∀z, z ∈ σ₁ → (σ₁ z = σ₂ z)),\n assume x: var,\n assume : x ∈ σ₁.dom,\n have h1: x ∈ σ₁, from this,\n have ∃v, σ₁ x = some v, from env.contains_apply_equiv.right.mpr h1,\n let ⟨v, h2⟩ := this in\n have σ₁ x = σ₂ x, from env_equiv x h1,\n have σ₂ x = some v, from eq.trans this.symm h2,\n show x ∈ σ₂, from env.contains_apply_equiv.right.mp (exists.intro v this)\n\nlemma env.empty_of_dom_empty {σ: env}: (σ.dom = ∅) → (σ = env.empty) :=\n begin\n assume h1: (σ.dom = ∅),\n cases σ with σ' x v,\n refl,\n have h2, from set.subset_of_eq h1,\n have h3: x ∈ (σ'[x↦v]), from env.contains.same,\n have h4: x ∈ (σ'[x↦v]).dom, from h3,\n have h5, from set.mem_of_subset_of_mem h2 h4,\n have : x ∉ ∅, from set.not_mem_empty x,\n contradiction\n end\n\nlemma env.empty_dom_is_empty: (env.empty.dom = ∅) :=\n begin\n apply set.eq_of_subset_of_subset,\n assume x: var,\n assume : x ∈ env.dom env.empty,\n have h2: x ∈ env.empty, from this,\n cases h2,\n\n assume x: var,\n assume : x ∈ ∅,\n have : x ∉ ∅, from set.not_mem_empty x,\n contradiction\n end\n\nlemma term.subst_env_twice_equiv {t: term} {σ₁ σ₂: env}:\n (∀z, z ∈ σ₁ → (σ₁ z = σ₂ z)) → (term.subst_env σ₁ (term.subst_env σ₂ t) = term.subst_env σ₂ t) :=\n begin\n assume env_equiv: ∀z, z ∈ σ₁ → (σ₁ z = σ₂ z),\n -- have env_subst: σ₁.dom ⊆ σ₂.dom, from env.dom_subset_of_equivalent_env env_equiv,\n\n induction σ₁ with σ' x v ih,\n \n show (term.subst_env env.empty (term.subst_env σ₂ t) = term.subst_env σ₂ t),\n by unfold term.subst_env,\n\n show (term.subst_env (σ'[x↦v]) (term.subst_env σ₂ t) = term.subst_env σ₂ t), by begin\n unfold term.subst_env,\n have h1: (∀ (z : var), z ∈ σ' → (σ' z = σ₂ z)), by begin\n assume z: var,\n assume h2: z ∈ σ',\n have h3: (env.apply (σ'[x↦v]) z = σ₂ z), from env_equiv z (env.contains.rest h2),\n unfold env.apply at h3,\n have h4, from env.contains_apply_equiv.right.mpr h2,\n have h5, from option.is_some_iff_exists.mpr h4,\n have h6, from option.some_iff_not_none.mp h5,\n have h7, from not_and_of_not_right (x = z) h6,\n have h8: (ite (x = z ∧ (option.is_none (env.apply σ' z))) ↑v (env.apply σ' z) = (env.apply σ' z)),\n from ite.if_false h7,\n rw[h8] at h3,\n from h3\n end,\n\n have h2: (term.subst_env σ' (term.subst_env σ₂ t) = term.subst_env σ₂ t), from ih h1,\n rw[h2],\n have h3: x ∈ σ₂, by begin\n have h3: (env.apply (σ'[x↦v]) x = σ₂ x), from env_equiv x env.contains.same,\n unfold env.apply at h3,\n by_cases (x ∈ σ') with h4,\n\n have h5, from env.contains_apply_equiv.right.mpr h4,\n have h6, from option.is_some_iff_exists.mpr h5,\n have h7, from option.some_iff_not_none.mp h6,\n have h8, from not_and_of_not_right (x = x) h7,\n have h9: (ite (x = x ∧ (option.is_none (env.apply σ' x))) ↑v (env.apply σ' x) = (env.apply σ' x)),\n from ite.if_false h8,\n rw[h9] at h3,\n have h10: (σ' x = σ₂ x), from h3,\n rw[h10] at h5,\n from env.contains_apply_equiv.right.mp h5,\n\n have h5, from env.contains_apply_equiv.left.mpr h4,\n have h6, from option.is_none.inv.mp h5,\n have h7: (ite (x = x ∧ (option.is_none (env.apply σ' x))) ↑v (env.apply σ' x) = v),\n from ite.if_true ⟨rfl, h6⟩,\n rw[h7] at h3,\n from env.contains_apply_equiv.right.mp (exists.intro v h3.symm)\n end,\n\n have : x ∉ FV (term.subst_env σ₂ t), from term.not_free_of_subst_env h3,\n from unchanged_of_subst_nonfree_term this\n end\n end\n\nlemma term.substte_env.order {t' t: term} {σ₁ σ₂: env} {x: var}:\n (∀z, z ∈ σ₁ → (σ₁ z = σ₂ z)) → (x ∉ σ₁) →\n (term.subst_env σ₁ (term.substt x (term.subst_env σ₂ t') t)\n = term.substt x (term.subst_env σ₂ t') (term.subst_env σ₁ t)) :=\n begin\n assume env_equiv,\n assume h1,\n induction t with v y unop t₁ t₁_ih binop t₂ t₃ t₂_ih t₃_ih t₄ t₅ t₄_ih t₅_ih,\n \n show (term.subst_env σ₁ (term.substt x (term.subst_env σ₂ t') (term.value v))\n = term.substt x (term.subst_env σ₂ t') (term.subst_env σ₁ (term.value v))),\n by begin\n change (term.subst_env σ₁ (term.substt x (term.subst_env σ₂ t') (term.value v)) =\n term.substt x (term.subst_env σ₂ t') (term.subst_env σ₁ v)),\n rw[term.subst_env.value],\n unfold term.substt,\n rw[term.subst_env.value],\n change (↑v = term.substt x (term.subst_env σ₂ t') (term.value v)),\n unfold term.substt\n end,\n\n show (term.subst_env σ₁ (term.substt x (term.subst_env σ₂ t') (term.var y))\n = term.substt x (term.subst_env σ₂ t') (term.subst_env σ₁ (term.var y))),\n by begin\n by_cases (x = y) with h,\n simp[h],\n rw[h] at h1,\n unfold term.substt,\n simp,\n have : (σ₁ y = none), from env.contains_apply_equiv.left.mpr h1,\n have h2: (term.subst_env σ₁ (term.var y) = y), from term.subst_env.var.left.mp this,\n simp[h2],\n have h3: (term.subst_env σ₁ (term.subst_env σ₂ t') = (term.subst_env σ₂ t')),\n from term.subst_env_twice_equiv env_equiv,\n rw[h3],\n change (term.subst_env σ₂ t' = term.substt y (term.subst_env σ₂ t') (term.var y)),\n unfold term.substt,\n simp,\n\n unfold term.substt,\n simp[h],\n have h3: (term.subst_env σ₁ y = y ∨ ∃v: value, term.subst_env σ₁ y = v),\n from term.subst_env.var.inv,\n cases h3 with h4 h5,\n\n change (term.subst_env σ₁ y = term.substt x (term.subst_env σ₂ t') (term.subst_env σ₁ y)),\n rw[h4],\n change (↑y = term.substt x (term.subst_env σ₂ t') (term.var y)),\n unfold term.substt,\n simp[h],\n\n cases h5 with v' h6,\n change (term.subst_env σ₁ y = term.substt x (term.subst_env σ₂ t') (term.subst_env σ₁ y)),\n rw[h6],\n change (↑v' = term.substt x (term.subst_env σ₂ t') (term.value v')),\n unfold term.substt\n end,\n\n show (term.subst_env σ₁ (term.substt x (term.subst_env σ₂ t') (term.unop unop t₁))\n = term.substt x (term.subst_env σ₂ t') (term.subst_env σ₁ (term.unop unop t₁))), by begin\n rw[term.subst_env.unop],\n unfold term.substt,\n rw[term.subst_env.unop],\n congr,\n from t₁_ih\n end,\n\n show (term.subst_env σ₁ (term.substt x (term.subst_env σ₂ t') (term.binop binop t₂ t₃))\n = term.substt x (term.subst_env σ₂ t') (term.subst_env σ₁ (term.binop binop t₂ t₃))), by begin\n rw[term.subst_env.binop],\n unfold term.substt,\n rw[term.subst_env.binop],\n congr,\n rw[t₂_ih],\n rw[t₃_ih]\n end,\n\n show (term.subst_env σ₁ (term.substt x (term.subst_env σ₂ t') (term.app t₄ t₅))\n = term.substt x (term.subst_env σ₂ t') (term.subst_env σ₁ (term.app t₄ t₅))), by begin\n rw[term.subst_env.app],\n unfold term.substt,\n rw[term.subst_env.app],\n congr,\n rw[t₄_ih],\n rw[t₅_ih]\n end\n end\n\nlemma vc.subst_env.order {P: vc}:\n ∀ {σ: env} {x: var} {v: value},\n (x ∉ σ) ∨ (σ x = v) → (vc.subst_env σ (vc.subst x v P) = vc.subst x v (vc.subst_env σ P)) :=\n begin\n induction P,\n case vc.term t {\n assume σ x v,\n assume h1,\n change (vc.subst_env σ (vc.subst x v (vc.term t)) = vc.subst x v (vc.subst_env σ ↑t)),\n rw[vc.subst_env.term],\n unfold vc.subst,\n rw[vc.subst_env.term],\n congr,\n from term.subst_env.order h1\n },\n case vc.not P₁ ih {\n assume σ x v,\n assume h1,\n rw[vc.subst_env.not],\n unfold vc.subst,\n rw[vc.subst_env.not],\n congr,\n from ih h1\n },\n case vc.and P₁ P₂ P₁_ih P₂_ih {\n assume σ x v,\n assume h1,\n change (vc.subst_env σ (vc.subst x v (vc.and P₁ P₂)) = vc.subst x v (vc.subst_env σ (P₁ ⋀ P₂))),\n rw[vc.subst_env.and],\n unfold vc.subst,\n rw[vc.subst_env.and],\n congr,\n from P₁_ih h1,\n from P₂_ih h1\n },\n case vc.or P₁ P₂ P₁_ih P₂_ih {\n assume σ x v,\n assume h1,\n change (vc.subst_env σ (vc.subst x v (vc.or P₁ P₂)) = vc.subst x v (vc.subst_env σ (P₁ ⋁ P₂))),\n rw[vc.subst_env.or],\n unfold vc.subst,\n rw[vc.subst_env.or],\n congr,\n from P₁_ih h1,\n from P₂_ih h1\n },\n case vc.pre t₁ t₂ {\n assume σ x v,\n assume h1,\n rw[vc.subst_env.pre],\n unfold vc.subst,\n rw[vc.subst_env.pre],\n congr,\n from term.subst_env.order h1,\n from term.subst_env.order h1\n },\n case vc.pre₁ op t {\n assume σ x v,\n assume h1,\n rw[vc.subst_env.pre₁],\n unfold vc.subst,\n rw[vc.subst_env.pre₁],\n congr,\n from term.subst_env.order h1\n },\n case vc.pre₂ op t₁ t₂ {\n assume σ x v,\n assume h1,\n rw[vc.subst_env.pre₂],\n unfold vc.subst,\n rw[vc.subst_env.pre₂],\n congr,\n from term.subst_env.order h1,\n from term.subst_env.order h1\n },\n case vc.post t₁ t₂ {\n assume σ x v,\n assume h1,\n rw[vc.subst_env.post],\n unfold vc.subst,\n rw[vc.subst_env.post],\n congr,\n from term.subst_env.order h1,\n from term.subst_env.order h1\n },\n case vc.univ z P' P'_ih {\n assume σ x v,\n assume h1,\n rw[vc.subst_env.univ],\n unfold vc.subst,\n by_cases (x = z) with h2,\n\n simp[h2],\n rw[vc.subst_env.univ],\n\n simp[h2],\n rw[vc.subst_env.univ],\n congr,\n\n have h2: (x ∉ σ.without z ∨ (σ.without z x = v)),\n from env.without_equiv h1,\n have h3: (vc.subst_env (σ.without z) (vc.subst x v P') = vc.subst x v (vc.subst_env (σ.without z) P')),\n from P'_ih h2,\n rw[h3]\n }\n end\n\nlemma vc.substt_env.order {P: vc}:\n ∀ {σ: env} {x: var} {t: term},\n closed t → (x ∉ σ) → (vc.subst_env σ (vc.substt x t P) = vc.substt x t (vc.subst_env σ P)) :=\n begin\n induction P,\n case vc.term t' {\n assume σ x t,\n assume t_closed,\n assume h1,\n change (vc.subst_env σ (vc.substt x t (vc.term t')) = vc.substt x t (vc.subst_env σ t')),\n rw[vc.subst_env.term],\n unfold vc.substt,\n rw[vc.subst_env.term],\n congr,\n from term.substt_env.order t_closed h1\n },\n case vc.not P₁ ih {\n assume σ x t,\n assume t_closed,\n assume h1,\n rw[vc.subst_env.not],\n unfold vc.substt,\n rw[vc.subst_env.not],\n congr,\n from ih t_closed h1\n },\n case vc.and P₁ P₂ P₁_ih P₂_ih {\n assume σ x t,\n assume t_closed,\n assume h1,\n change (vc.subst_env σ (vc.substt x t (vc.and P₁ P₂)) = vc.substt x t (vc.subst_env σ (P₁ ⋀ P₂))),\n rw[vc.subst_env.and],\n unfold vc.substt,\n rw[vc.subst_env.and],\n congr,\n from P₁_ih t_closed h1,\n from P₂_ih t_closed h1\n },\n case vc.or P₁ P₂ P₁_ih P₂_ih {\n assume σ x t,\n assume t_closed,\n assume h1,\n change (vc.subst_env σ (vc.substt x t (vc.or P₁ P₂)) = vc.substt x t (vc.subst_env σ (P₁ ⋁ P₂))),\n rw[vc.subst_env.or],\n unfold vc.substt,\n rw[vc.subst_env.or],\n congr,\n from P₁_ih t_closed h1,\n from P₂_ih t_closed h1\n },\n case vc.pre t₁ t₂ {\n assume σ x t,\n assume t_closed,\n assume h1,\n rw[vc.subst_env.pre],\n unfold vc.substt,\n rw[vc.subst_env.pre],\n congr,\n from term.substt_env.order t_closed h1,\n from term.substt_env.order t_closed h1\n },\n case vc.pre₁ op t {\n assume σ x t,\n assume t_closed,\n assume h1,\n rw[vc.subst_env.pre₁],\n unfold vc.substt,\n rw[vc.subst_env.pre₁],\n congr,\n from term.substt_env.order t_closed h1\n },\n case vc.pre₂ op t₁ t₂ {\n assume σ x t,\n assume t_closed,\n assume h1,\n rw[vc.subst_env.pre₂],\n unfold vc.substt,\n rw[vc.subst_env.pre₂],\n congr,\n from term.substt_env.order t_closed h1,\n from term.substt_env.order t_closed h1\n },\n case vc.post t₁ t₂ {\n assume σ x t,\n assume t_closed,\n assume h1,\n rw[vc.subst_env.post],\n unfold vc.substt,\n rw[vc.subst_env.post],\n congr,\n from term.substt_env.order t_closed h1,\n from term.substt_env.order t_closed h1\n },\n case vc.univ z P' P'_ih {\n assume σ x t,\n assume t_closed,\n assume h1,\n rw[vc.subst_env.univ],\n unfold vc.substt,\n by_cases (x = z) with h2,\n\n simp[h2],\n rw[vc.subst_env.univ],\n\n simp[h2],\n rw[vc.subst_env.univ],\n congr,\n\n have h2: (x ∉ σ.without z),\n from env.not_in_without h1,\n have h3: (vc.subst_env (σ.without z) (vc.substt x t P') = vc.substt x t (vc.subst_env (σ.without z) P')),\n from P'_ih t_closed h2,\n rw[h3]\n }\n end\n\nlemma vc.subst_env_inner {P: vc} {σ: env} {x: var} {v: value}:\n (σ x = some v) → (vc.subst_env σ (vc.subst x v P) = vc.subst_env σ P) :=\n begin\n assume x_is_v,\n\n induction σ with σ₁ y v' ih,\n\n show (vc.subst_env env.empty (vc.subst x v P) = vc.subst_env env.empty P), by cases x_is_v,\n\n show (vc.subst_env (σ₁[y↦v']) (vc.subst x v P) = vc.subst_env (σ₁[y↦v']) P), by begin\n unfold vc.subst_env,\n have h2: (env.apply (σ₁[y↦v']) x = some v), from x_is_v,\n unfold env.apply at h2,\n by_cases (y = x ∧ (option.is_none (env.apply σ₁ x))) with h3,\n simp[h3] at h2,\n have h4: (v' = v), from option.some.inj h2,\n simp[h3],\n have h5: (σ₁ x = none), from option.is_none.inv.mpr h3.right,\n have h6: x ∉ σ₁, from env.contains_apply_equiv.left.mp h5,\n rw[h4],\n have h7: x ∉ FV (vc.subst x v P), from vc.not_free_of_subst,\n have h8: x ∉ FV (vc.subst_env σ₁ (vc.subst x v P)),\n from mt free_in_vc.subst_env h7,\n have h9: (vc.subst x v (vc.subst_env σ₁ (vc.subst x v P)) = (vc.subst_env σ₁ (vc.subst x v P))),\n from unchanged_of_subst_nonfree_vc h8,\n rw[h9],\n from vc.subst_env.order (or.inl h6),\n\n simp[h3] at h2,\n have h4, from ih h2,\n congr,\n from h4\n end\n end\n\nlemma vc.subst_env_with_equivalent_env {P: vc} {σ₁ σ₂: env}:\n (∀z, z ∈ σ₁ → (σ₁ z = σ₂ z)) → (vc.subst_env σ₂ (vc.subst_env σ₁ P) = vc.subst_env σ₂ P) :=\n begin\n assume env_equiv,\n induction σ₁ with σ₁' x v ih,\n \n show (vc.subst_env σ₂ (vc.subst_env env.empty P) = vc.subst_env σ₂ P), from (\n have vc.subst_env env.empty P = P, by unfold vc.subst_env,\n show vc.subst_env σ₂ (vc.subst_env env.empty P) = vc.subst_env σ₂ P, from this.symm ▸ rfl\n ),\n\n show (vc.subst_env σ₂ (vc.subst_env (σ₁'[x↦v]) P) = vc.subst_env σ₂ P), by begin\n unfold vc.subst_env,\n\n have h0: (∀ (z : var), z ∈ σ₁' → (σ₁' z = σ₂ z)), from (\n assume z: var,\n assume h1: z ∈ σ₁',\n have ∃v, σ₁' z = some v, from env.contains_apply_equiv.right.mpr h1,\n let ⟨v', h2⟩ := this in\n have option.is_some (σ₁' z), from option.is_some_iff_exists.mpr this,\n have ¬ option.is_none (σ₁' z), from option.some_iff_not_none.mp this,\n have ¬ (x = z ∧ option.is_none (env.apply σ₁' z)), from not_and_distrib.mpr (or.inr this),\n have h3: env.apply (σ₁'[x↦v]) z = σ₁' z, by { unfold env.apply, simp[this], refl },\n have z ∈ (σ₁'[x↦v]), from env.contains.rest h1,\n show σ₁' z = σ₂ z, from h3 ▸ (env_equiv z this)\n ),\n by_cases (x ∈ σ₁') with h1,\n\n have h2: x ∉ FV (vc.subst_env σ₁' P), from vc.not_free_of_subst_env h1,\n have h3: (vc.subst x v (vc.subst_env σ₁' P) = (vc.subst_env σ₁' P)),\n from unchanged_of_subst_nonfree_vc h2,\n rw[h3],\n from ih h0,\n\n have h2: x ∈ (σ₁'[x↦v]), from env.contains.same,\n have h3: ((σ₁'[x↦v]) x = σ₂ x), from env_equiv x h2,\n have h4: (env.apply (σ₁'[x↦v]) x = v), from env.apply_of_contains h1,\n have h5: (σ₂ x = some v), from eq.trans h3.symm h4,\n have h6: (vc.subst_env σ₂ (vc.subst x v (vc.subst_env σ₁' P)) = vc.subst_env σ₂ (vc.subst_env σ₁' P)),\n from vc.subst_env_inner h5,\n rw[h6],\n from ih h0\n end\n end\n\nlemma vc.subst_env_equivalent_env {P: vc} {σ₁ σ₂: env}:\n (∀z, z ∈ σ₁ → (σ₁ z = σ₂ z)) → closed_subst σ₁ P → (vc.subst_env σ₁ P = vc.subst_env σ₂ P) :=\n assume h1: (∀z, z ∈ σ₁ → (σ₁ z = σ₂ z)),\n assume P_closed: closed_subst σ₁ P,\n have closed (vc.subst_env σ₁ P), from vc.closed_of_closed_subst P_closed,\n have h2: vc.subst_env σ₂ (vc.subst_env σ₁ P) = (vc.subst_env σ₁ P),\n from unchanged_of_subst_env_nonfree_vc this σ₂,\n have vc.subst_env σ₂ (vc.subst_env σ₁ P) = vc.subst_env σ₂ P,\n from vc.subst_env_with_equivalent_env h1,\n show vc.subst_env σ₁ P = vc.subst_env σ₂ P, from h2 ▸ this\n\nlemma env.remove_unimportant_equivalence {σ₁ σ₂: env} {x: var}:\n (∀y, y ∈ σ₁ → (σ₁ y = σ₂ y)) → x ∉ σ₁ → (∀y, y ∈ σ₁ → (σ₁ y = σ₂.without x y)) :=\n assume h1: (∀y, y ∈ σ₁ → (σ₁ y = σ₂ y)),\n assume h2: x ∉ σ₁,\n assume y: var,\n assume h3: y ∈ σ₁,\n have ∃v, σ₁ y = some v, from env.contains_apply_equiv.right.mpr h3,\n let ⟨v, h4⟩ := this in\n have σ₁ y = σ₂ y, from h1 y h3,\n have h5: σ₂ y = v, from eq.trans this.symm h4,\n have h6: x ≠ y, from (\n assume : x = y,\n have x ∈ σ₁, from this.symm ▸ h3,\n show «false», from h2 this\n ),\n have y ∈ σ₁.dom, from h3,\n have y ∈ σ₂.dom, from set.mem_of_subset_of_mem (env.dom_subset_of_equivalent_env h1) this,\n have y ∈ σ₂, from this,\n have h7: y ∈ σ₂.without x, from env.contains_without.rinv ⟨this, h6.symm⟩,\n -- have ∃v', σ₂.without x y = some v', from env.contains_apply_equiv.right.mpr this,\n have y ∉ σ₂.without x ∨ (σ₂.without x y = v), from env.without_equiv (or.inr h5),\n or.elim this (\n assume : y ∉ σ₂.without x,\n show σ₁ y = σ₂.without x y, from absurd h7 this\n ) (\n assume : σ₂.without x y = v,\n show σ₁ y = σ₂.without x y, from eq.trans h4 this.symm\n )\n\nlemma vc.subst_env_without_nonfree {σ: env} {P: vc} {x: var}:\n x ∉ FV P → (vc.subst_env σ P = vc.subst_env (σ.without x) P) :=\n begin\n assume h1: x ∉ FV P,\n\n induction σ with σ' y v ih,\n\n show (vc.subst_env env.empty P = vc.subst_env (env.without env.empty x) P), by begin\n unfold env.without\n end,\n\n show (vc.subst_env (σ'[y↦v]) P = vc.subst_env (env.without (σ'[y↦v]) x) P), by begin\n unfold env.without,\n by_cases (y = x) with h2,\n\n simp[h2],\n unfold vc.subst_env,\n have h3: x ∉ FV (vc.subst_env σ' P), by begin\n assume : x ∈ FV (vc.subst_env σ' P),\n have : x ∈ FV P, from free_in_vc.subst_env this,\n show «false», from h1 this\n end,\n have h4: (vc.subst x v (vc.subst_env σ' P) = (vc.subst_env σ' P)),\n from unchanged_of_subst_nonfree_vc h3,\n from eq.trans h4 ih,\n\n simp[h2],\n unfold vc.subst_env,\n rw[ih]\n end\n end\n\nlemma vc.subst_env.reorder {σ: env} {x: var} {v: value} {P: vc}:\n (vc.subst_env σ (vc.subst x v P) = vc.subst x v (vc.subst_env (σ.without x) P)) :=\n have x ∉ FV (vc.subst x v P), from vc.not_free_of_subst,\n have h1: vc.subst_env σ (vc.subst x v P) = vc.subst_env (σ.without x) (vc.subst x v P),\n from vc.subst_env_without_nonfree this,\n have x ∉ σ.without x, from env.not_contains_without,\n have h2: (vc.subst_env (σ.without x) (vc.subst x v P) = vc.subst x v (vc.subst_env (σ.without x) P)),\n from vc.subst_env.order (or.inl this),\n show vc.subst_env σ (vc.subst x v P) = vc.subst x v (vc.subst_env (σ.without x) P),\n from eq.trans h1 h2\n\nlemma vc.substt_env.reorder {σ: env} {x: var} {t: term} {P: vc}:\n closed t → (vc.subst_env σ (vc.substt x t P) = vc.substt x t (vc.subst_env (σ.without x) P)) :=\n assume t_closed: closed t,\n have x ∉ FV (vc.substt x t P), from vc.not_free_of_substt t_closed,\n have h1: vc.subst_env σ (vc.substt x t P) = vc.subst_env (σ.without x) (vc.substt x t P),\n from vc.subst_env_without_nonfree this,\n have x ∉ σ.without x, from env.not_contains_without,\n have h2: (vc.subst_env (σ.without x) (vc.substt x t P) = vc.substt x t (vc.subst_env (σ.without x) P)),\n from vc.substt_env.order t_closed this,\n show vc.subst_env σ (vc.substt x t P) = vc.substt x t (vc.subst_env (σ.without x) P),\n from eq.trans h1 h2\n\nlemma term.substt_env.redundant {σ: env} {x: var} {t t': term}:\n (term.subst_env σ (term.substt x (term.subst_env σ t) t') = term.subst_env σ (term.substt x t t')) :=\n begin\n induction t' with v y unop t₁ t₁_ih binop t₂ t₃ t₂_ih t₃_ih t₄ t₅ t₄_ih t₅_ih,\n\n show (term.subst_env σ (term.substt x (term.subst_env σ t) (term.value v)) =\n term.subst_env σ (term.substt x t (term.value v))), by begin\n unfold term.substt\n end,\n\n show (term.subst_env σ (term.substt x (term.subst_env σ t) (term.var y)) =\n term.subst_env σ (term.substt x t (term.var y))), by begin\n unfold term.substt,\n by_cases (x = y) with h1,\n simp[h1],\n from term.subst_env_twice,\n simp[h1]\n end,\n\n show (term.subst_env σ (term.substt x (term.subst_env σ t) (term.unop unop t₁)) =\n term.subst_env σ (term.substt x t (term.unop unop t₁))), by begin\n unfold term.substt,\n rw[term.subst_env.unop],\n rw[term.subst_env.unop],\n congr,\n from t₁_ih\n end,\n\n show (term.subst_env σ (term.substt x (term.subst_env σ t) (term.binop binop t₂ t₃)) =\n term.subst_env σ (term.substt x t (term.binop binop t₂ t₃))), by begin\n unfold term.substt,\n rw[term.subst_env.binop],\n rw[term.subst_env.binop],\n congr,\n from t₂_ih,\n from t₃_ih\n end,\n\n show (term.subst_env σ (term.substt x (term.subst_env σ t) (term.app t₄ t₅)) =\n term.subst_env σ (term.substt x t (term.app t₄ t₅))), by begin\n unfold term.substt,\n rw[term.subst_env.app],\n rw[term.subst_env.app],\n congr,\n from t₄_ih,\n from t₅_ih\n end\n end\n\nlemma term.substt_var_cancel {x y: var} {t: term}: x ∉ FV t → (term.substt x y (term.substt y x t) = t) :=\n begin\n assume h1,\n\n induction t with v z unop t₁ t₁_ih binop t₂ t₃ t₂_ih t₃_ih t₄ t₅ t₄_ih t₅_ih,\n\n show (term.substt x y (term.substt y x (term.value v)) = term.value v), by begin\n unfold term.substt,\n change (term.substt x ↑y (term.value v) = term.value v),\n unfold term.substt,\n refl\n end,\n\n show (term.substt x ↑y (term.substt y ↑x (term.var z)) = term.var z), by begin\n have h2: (x ≠ z), by begin\n assume h3,\n rw[h3] at h1,\n have h4, from free_in_term.var z,\n contradiction\n end,\n\n unfold term.substt,\n by_cases (y = z) with h3,\n\n simp[h3],\n change (term.substt x ↑z (term.var x) = term.var z),\n unfold term.substt,\n simp,\n refl,\n\n simp[h3],\n change (term.substt x ↑y (term.var z) = term.var z),\n unfold term.substt,\n simp[h2],\n refl\n end,\n \n show (term.substt x y (term.substt y x (term.unop unop t₁)) = term.unop unop t₁), by begin\n unfold term.substt,\n congr,\n apply t₁_ih,\n assume h1,\n have h2: x ∈ FV (term.unop unop t₁), from free_in_term.unop h1,\n contradiction\n end,\n \n show (term.substt x y (term.substt y x (term.binop binop t₂ t₃)) = term.binop binop t₂ t₃), by begin\n unfold term.substt,\n congr,\n apply t₂_ih,\n assume h1,\n have h2: x ∈ FV (term.binop binop t₂ t₃), from free_in_term.binop₁ h1,\n contradiction,\n apply t₃_ih,\n assume h1,\n have h2: x ∈ FV (term.binop binop t₂ t₃), from free_in_term.binop₂ h1,\n contradiction\n end,\n \n show (term.substt x y (term.substt y x (term.app t₄ t₅)) = term.app t₄ t₅), by begin\n unfold term.substt,\n congr,\n apply t₄_ih,\n assume h1,\n have h2: x ∈ FV (term.app t₄ t₅), from free_in_term.app₁ h1,\n contradiction,\n apply t₅_ih,\n assume h1,\n have h2: x ∈ FV (term.app t₄ t₅), from free_in_term.app₂ h1,\n contradiction\n end\n end\n\nlemma vc.substt_var_cancel {x y: var} {P: vc}: ¬ vc.uses_var x P → (vc.substt x y (vc.substt y x P) = P) :=\n begin\n assume h1,\n induction P,\n case vc.term t {\n unfold vc.substt,\n change (vc.substt x ↑y (vc.term (term.substt y ↑x t)) = vc.term t),\n unfold vc.substt,\n congr,\n apply term.substt_var_cancel,\n assume h1,\n have h2: vc.uses_var x t, from vc.uses_var.term h1,\n contradiction\n },\n case vc.not P₁ P₁_ih {\n unfold vc.substt,\n congr,\n apply P₁_ih,\n assume h1,\n have h2: vc.uses_var x (vc.not P₁), from vc.uses_var.not h1,\n contradiction\n },\n case vc.and P₁ P₂ P₁_ih P₂_ih {\n unfold vc.substt,\n change (vc.substt x ↑y (vc.and (vc.substt y ↑x P₁) (vc.substt y ↑x P₂)) = vc.and P₁ P₂),\n unfold vc.substt,\n congr,\n apply P₁_ih,\n assume h1,\n have h2: vc.uses_var x (vc.and P₁ P₂), from vc.uses_var.and₁ h1,\n contradiction,\n apply P₂_ih,\n assume h1,\n have h2: vc.uses_var x (vc.and P₁ P₂), from vc.uses_var.and₂ h1,\n contradiction\n },\n case vc.or P₁ P₂ P₁_ih P₂_ih {\n unfold vc.substt,\n change (vc.substt x ↑y (vc.or (vc.substt y ↑x P₁) (vc.substt y ↑x P₂)) = vc.or P₁ P₂),\n unfold vc.substt,\n congr,\n apply P₁_ih,\n assume h1,\n have h2: vc.uses_var x (vc.or P₁ P₂), from vc.uses_var.or₁ h1,\n contradiction,\n apply P₂_ih,\n assume h1,\n have h2: vc.uses_var x (vc.or P₁ P₂), from vc.uses_var.or₂ h1,\n contradiction\n },\n case vc.pre t₁ t₂ {\n unfold vc.substt,\n congr,\n apply term.substt_var_cancel,\n assume h1,\n have h2: vc.uses_var x (vc.pre t₁ t₂), from vc.uses_var.pre₁ h1,\n contradiction,\n apply term.substt_var_cancel,\n assume h1,\n have h2: vc.uses_var x (vc.pre t₁ t₂), from vc.uses_var.pre₂ h1,\n contradiction\n },\n case vc.pre₁ op t {\n unfold vc.substt,\n congr,\n apply term.substt_var_cancel,\n assume h1,\n have h2: vc.uses_var x (vc.pre₁ op t), from vc.uses_var.preop h1,\n contradiction\n },\n case vc.pre₂ op t₁ t₂ {\n unfold vc.substt,\n congr,\n apply term.substt_var_cancel,\n assume h1,\n have h2: vc.uses_var x (vc.pre₂ op t₁ t₂), from vc.uses_var.preop₁ h1,\n contradiction,\n apply term.substt_var_cancel,\n assume h1,\n have h2: vc.uses_var x (vc.pre₂ op t₁ t₂), from vc.uses_var.preop₂ h1,\n contradiction\n },\n case vc.post t₁ t₂ {\n unfold vc.substt,\n congr,\n apply term.substt_var_cancel,\n assume h1,\n have h2: vc.uses_var x (vc.post t₁ t₂), from vc.uses_var.post₁ h1,\n contradiction,\n apply term.substt_var_cancel,\n assume h1,\n have h2: vc.uses_var x (vc.post t₁ t₂), from vc.uses_var.post₂ h1,\n contradiction\n },\n case vc.univ z P₁ P₁_ih {\n unfold vc.substt,\n congr,\n\n have h1: (x ≠ z), by begin\n assume h2,\n rw[h2] at h1,\n have h3: vc.uses_var z (vc.univ z P₁), from vc.uses_var.quantified z,\n contradiction\n end,\n\n by_cases (y = z) with h2,\n\n simp[h1],\n simp[h2],\n\n have h3: x ∉ FV P₁, by begin\n assume h4,\n have h5, from vc.uses_var_of_free h4,\n have h6: vc.uses_var x (vc.univ z P₁), from vc.uses_var.univ h5,\n contradiction\n end,\n from unchanged_of_substt_nonfree_vc h3,\n\n simp[h1],\n simp[h2],\n\n have h3: ¬vc.uses_var x P₁, by begin\n assume h4,\n have h5: vc.uses_var x (vc.univ z P₁), from vc.uses_var.univ h4,\n contradiction\n end,\n from P₁_ih h3\n }\n end\n\nlemma subst_distrib_to_vc {P: prop} {x: var} {v: value}:\n (vc.subst x v (prop.to_vc P) = prop.to_vc (prop.subst x v P)) := begin\n induction P,\n case prop.term t {\n unfold prop.subst,\n unfold prop.to_vc,\n unfold vc.subst,\n change (vc.term (term.subst x v t) = prop.to_vc (prop.term (term.subst x v t))),\n unfold prop.to_vc\n },\n case prop.not P₁ ih {\n unfold prop.subst,\n unfold prop.to_vc,\n unfold vc.subst,\n congr,\n from ih\n },\n case prop.and P₁ P₂ P₁_ih P₂_ih {\n unfold prop.subst,\n unfold prop.to_vc,\n change (vc.subst x v (vc.and (prop.to_vc P₁) (prop.to_vc P₂))\n = prop.to_vc (prop.and (prop.subst x v P₁) (prop.subst x v P₂))),\n unfold vc.subst,\n unfold prop.to_vc,\n congr,\n from P₁_ih,\n from P₂_ih\n },\n case prop.or P₁ P₂ P₁_ih P₂_ih {\n unfold prop.subst,\n unfold prop.to_vc,\n change (vc.subst x v (vc.or (prop.to_vc P₁) (prop.to_vc P₂))\n = prop.to_vc (prop.or (prop.subst x v P₁) (prop.subst x v P₂))),\n unfold vc.subst,\n unfold prop.to_vc,\n congr,\n from P₁_ih,\n from P₂_ih\n },\n case prop.pre t₁ t₂ {\n unfold prop.subst,\n unfold prop.to_vc,\n unfold vc.subst\n },\n case prop.pre₁ op t {\n unfold prop.subst,\n unfold prop.to_vc,\n unfold vc.subst\n },\n case prop.pre₂ op t₁ t₂ {\n unfold prop.subst,\n unfold prop.to_vc,\n unfold vc.subst\n },\n case prop.call t {\n unfold prop.subst,\n unfold prop.to_vc,\n unfold vc.subst,\n congr\n },\n case prop.post t₁ t₂ {\n unfold prop.subst,\n unfold prop.to_vc,\n unfold vc.subst\n },\n case prop.forallc y P₁ P₁_ih {\n unfold prop.subst,\n unfold prop.to_vc,\n unfold vc.subst,\n congr,\n\n by_cases (x = y) with h1,\n\n simp[h1],\n\n simp[h1],\n from P₁_ih\n },\n case prop.exis y P₁ P₁_ih {\n unfold prop.subst,\n unfold prop.to_vc,\n unfold vc.subst,\n congr,\n by_cases (x = y) with h1,\n\n simp[h1],\n\n simp[h1],\n congr,\n from P₁_ih\n }\nend\n\nlemma subst_env_distrib_to_vc {P: prop} {σ: env}:\n (vc.subst_env σ (prop.to_vc P) = prop.to_vc (prop.subst_env σ P)) :=\n begin\n induction σ with σ₁ y v' ih,\n\n show (vc.subst_env env.empty (prop.to_vc P) = prop.to_vc (prop.subst_env env.empty P)), by begin\n unfold prop.subst_env,\n unfold vc.subst_env\n end,\n\n show (vc.subst_env (σ₁[y↦v']) (prop.to_vc P) = prop.to_vc (prop.subst_env (σ₁[y↦v']) P)), by begin\n unfold prop.subst_env,\n unfold vc.subst_env,\n rw[ih],\n from subst_distrib_to_vc\n end\n end\n\nlemma substt_distrib_to_vc {P: prop} {x: var} {t: term}:\n (vc.substt x t (prop.to_vc P) = prop.to_vc (prop.substt x t P)) := begin\n induction P,\n case prop.term t₂ {\n unfold prop.substt,\n unfold prop.to_vc,\n unfold vc.substt,\n change (vc.term (term.substt x t t₂) = prop.to_vc (prop.term (term.substt x t t₂))),\n unfold prop.to_vc\n },\n case prop.not P₁ ih {\n unfold prop.substt,\n unfold prop.to_vc,\n unfold vc.substt,\n congr,\n from ih\n },\n case prop.and P₁ P₂ P₁_ih P₂_ih {\n unfold prop.substt,\n unfold prop.to_vc,\n change (vc.substt x t (vc.and (prop.to_vc P₁) (prop.to_vc P₂))\n = prop.to_vc (prop.and (prop.substt x t P₁) (prop.substt x t P₂))),\n unfold vc.substt,\n unfold prop.to_vc,\n congr,\n from P₁_ih,\n from P₂_ih\n },\n case prop.or P₁ P₂ P₁_ih P₂_ih {\n unfold prop.substt,\n unfold prop.to_vc,\n change (vc.substt x t (vc.or (prop.to_vc P₁) (prop.to_vc P₂))\n = prop.to_vc (prop.or (prop.substt x t P₁) (prop.substt x t P₂))),\n unfold vc.substt,\n unfold prop.to_vc,\n congr,\n from P₁_ih,\n from P₂_ih\n },\n case prop.pre t₁ t₂ {\n unfold prop.substt,\n unfold prop.to_vc,\n unfold vc.substt\n },\n case prop.pre₁ op t₁ {\n unfold prop.substt,\n unfold prop.to_vc,\n unfold vc.substt\n },\n case prop.pre₂ op t₁ t₂ {\n unfold prop.substt,\n unfold prop.to_vc,\n unfold vc.substt\n },\n case prop.call t₁ {\n unfold prop.substt,\n unfold prop.to_vc,\n unfold vc.substt,\n congr\n },\n case prop.post t₁ t₂ {\n unfold prop.substt,\n unfold prop.to_vc,\n unfold vc.substt\n },\n case prop.forallc y P₁ P₁_ih {\n unfold prop.substt,\n unfold prop.to_vc,\n unfold vc.substt,\n congr,\n\n by_cases (x = y) with h1,\n\n simp[h1],\n\n simp[h1],\n from P₁_ih\n },\n case prop.exis y P₁ P₁_ih {\n unfold prop.substt,\n unfold prop.to_vc,\n unfold vc.substt,\n congr,\n by_cases (x = y) with h1,\n\n simp[h1],\n\n simp[h1],\n congr,\n from P₁_ih\n }\nend\n\nlemma subst_distrib_erased {P: prop} {x: var} {v: value}:\n (vc.subst x v (prop.erased_p P) = prop.erased_p (prop.subst x v P)) ∧\n (vc.subst x v (prop.erased_n P) = prop.erased_n (prop.subst x v P)) := begin\n induction P,\n case prop.term t {\n split,\n\n unfold prop.subst,\n unfold prop.erased_p,\n unfold vc.subst,\n change (vc.term (term.subst x v t) = prop.erased_p (prop.term (term.subst x v t))),\n unfold prop.erased_p,\n\n unfold prop.subst,\n unfold prop.erased_n,\n unfold vc.subst,\n change (vc.term (term.subst x v t) = prop.erased_n (prop.term (term.subst x v t))),\n unfold prop.erased_n\n },\n case prop.not P₁ ih {\n split,\n\n unfold prop.subst,\n unfold prop.erased_p,\n unfold vc.subst,\n congr,\n from ih.right,\n\n unfold prop.subst,\n unfold prop.erased_n,\n unfold vc.subst,\n congr,\n from ih.left\n },\n case prop.and P₁ P₂ P₁_ih P₂_ih {\n split,\n\n unfold prop.subst,\n unfold prop.erased_p,\n change (vc.subst x v (vc.and (prop.erased_p P₁) (prop.erased_p P₂))\n = prop.erased_p (prop.and (prop.subst x v P₁) (prop.subst x v P₂))),\n unfold vc.subst,\n unfold prop.erased_p,\n congr,\n from P₁_ih.left,\n from P₂_ih.left,\n \n unfold prop.subst,\n unfold prop.erased_n,\n change (vc.subst x v (vc.and (prop.erased_n P₁) (prop.erased_n P₂))\n = prop.erased_n (prop.and (prop.subst x v P₁) (prop.subst x v P₂))),\n unfold vc.subst,\n unfold prop.erased_n,\n congr,\n from P₁_ih.right,\n from P₂_ih.right\n },\n case prop.or P₁ P₂ P₁_ih P₂_ih {\n split,\n\n unfold prop.subst,\n unfold prop.erased_p,\n change (vc.subst x v (vc.or (prop.erased_p P₁) (prop.erased_p P₂))\n = prop.erased_p (prop.or (prop.subst x v P₁) (prop.subst x v P₂))),\n unfold vc.subst,\n unfold prop.erased_p,\n congr,\n from P₁_ih.left,\n from P₂_ih.left,\n \n unfold prop.subst,\n unfold prop.erased_n,\n change (vc.subst x v (vc.or (prop.erased_n P₁) (prop.erased_n P₂))\n = prop.erased_n (prop.or (prop.subst x v P₁) (prop.subst x v P₂))),\n unfold vc.subst,\n unfold prop.erased_n,\n congr,\n from P₁_ih.right,\n from P₂_ih.right\n },\n case prop.pre t₁ t₂ {\n split,\n\n unfold prop.subst,\n unfold prop.erased_p,\n unfold vc.subst,\n\n unfold prop.subst,\n unfold prop.erased_n,\n unfold vc.subst\n },\n case prop.pre₁ op t {\n split,\n\n unfold prop.subst,\n unfold prop.erased_p,\n unfold vc.subst,\n\n unfold prop.subst,\n unfold prop.erased_n,\n unfold vc.subst\n },\n case prop.pre₂ op t₁ t₂ {\n split,\n\n unfold prop.subst,\n unfold prop.erased_p,\n unfold vc.subst,\n\n unfold prop.subst,\n unfold prop.erased_n,\n unfold vc.subst\n },\n case prop.call t {\n split,\n\n unfold prop.subst,\n unfold prop.erased_p,\n unfold vc.subst,\n congr,\n\n\n unfold prop.subst,\n unfold prop.erased_n,\n unfold vc.subst,\n congr\n },\n case prop.post t₁ t₂ {\n split,\n\n unfold prop.subst,\n unfold prop.erased_p,\n unfold vc.subst,\n\n unfold prop.subst,\n unfold prop.erased_n,\n unfold vc.subst\n },\n case prop.forallc y P₁ P₁_ih {\n split,\n\n unfold prop.subst,\n unfold prop.erased_p,\n unfold vc.subst,\n congr,\n\n unfold prop.subst,\n unfold prop.erased_n,\n unfold vc.subst,\n congr,\n by_cases (x = y) with h1,\n\n simp[h1],\n\n simp[h1],\n from P₁_ih.right\n },\n case prop.exis y P₁ P₁_ih {\n split,\n\n unfold prop.subst,\n unfold prop.erased_p,\n unfold vc.subst,\n congr,\n by_cases (x = y) with h1,\n\n simp[h1],\n\n simp[h1],\n congr,\n from P₁_ih.left,\n\n unfold prop.subst,\n unfold prop.erased_n,\n unfold vc.subst,\n congr,\n by_cases (x = y) with h1,\n\n simp[h1],\n\n simp[h1],\n congr,\n from P₁_ih.right\n }\nend\n\nlemma dom_eq_of_equiv {σ₁ σ₂: env}: (∀x: var, σ₁ x = σ₂ x) → (σ₁.dom = σ₂.dom) :=\n begin\n assume h1,\n apply set.eq_of_subset_of_subset,\n apply env.dom_subset_of_equivalent_env,\n assume z,\n assume _,\n from h1 z,\n\n apply env.dom_subset_of_equivalent_env,\n assume z,\n assume _,\n from (h1 z).symm\n end\n\nlemma vc.subst_env_unchanged {P: vc} {σ₁ σ₂: env}:\n σ₁.dom ⊆ σ₂.dom → (vc.subst_env σ₁ (vc.subst_env σ₂ P) = vc.subst_env σ₂ P) :=\n begin\n assume h1,\n induction σ₁ with σ₁' x v ih,\n\n show (vc.subst_env env.empty (vc.subst_env σ₂ P) = vc.subst_env σ₂ P), by begin\n unfold vc.subst_env\n end,\n\n show (vc.subst_env (σ₁'[x↦v]) (vc.subst_env σ₂ P) = vc.subst_env σ₂ P), by begin\n have h2: x ∈ (σ₁'[x↦v]).dom, from env.contains.same,\n have h3: x ∈ σ₂.dom, from set.mem_of_mem_of_subset h2 h1,\n unfold vc.subst_env,\n have h4: x ∉ FV (vc.subst_env σ₂ P), from vc.not_free_of_subst_env h3,\n have h5: x ∉ FV (vc.subst_env σ₁' (vc.subst_env σ₂ P)), by begin\n assume h6,\n have h7, from vc.free_of_free_subst_env h6,\n contradiction\n end,\n have h6: (vc.subst x v (vc.subst_env σ₁' (vc.subst_env σ₂ P)) = (vc.subst_env σ₁' (vc.subst_env σ₂ P))),\n from unchanged_of_subst_nonfree_vc h5,\n rw[h6],\n have h7: env.dom σ₁' ⊆ env.dom σ₂, by begin\n assume z,\n assume h8,\n have h9: z ∈ σ₁', from h8,\n have h10: z ∈ (σ₁'[x↦v]), from env.contains.rest h9,\n from set.mem_of_mem_of_subset h10 h1\n end,\n from ih h7\n end\n end\n\nlemma vc.subst_env_exact_equivalent_env {P: vc} {σ₁ σ₂: env}:\n (∀z, σ₁ z = σ₂ z) → (vc.subst_env σ₁ P = vc.subst_env σ₂ P) :=\n assume h1: (∀z, σ₁ z = σ₂ z),\n have h2: vc.subst_env σ₁ (vc.subst_env σ₂ P) = (vc.subst_env σ₂ P),\n from vc.subst_env_unchanged (set.subset_of_eq (dom_eq_of_equiv h1)),\n have vc.subst_env σ₁ (vc.subst_env σ₂ P) = vc.subst_env σ₁ P,\n from vc.subst_env_with_equivalent_env (λz _, (h1 z).symm),\n show vc.subst_env σ₁ P = vc.subst_env σ₂ P, from eq.trans this.symm h2\n\nlemma vc.subst_env_with_without_equivalent {P: vc} {σ: env} {x: var} {v: value}:\n (σ x = v) → (vc.subst_env ((σ.without x)[x↦v]) P = vc.subst_env σ P) :=\n assume h1: σ x = v,\n have (∀z, ((σ.without x)[x↦v]) z = σ z), by begin\n assume z,\n change (env.apply (env.without σ x[x↦v]) z = σ z),\n unfold env.apply,\n by_cases (x = z) with h2,\n rw[h2],\n simp,\n have h3: z ∉ σ.without z, from env.not_contains_without,\n have h4, from env.contains_apply_equiv.left.mpr h3,\n have h5, from option.is_none.inv.mp h4,\n rw[h2] at h1,\n rw[h1],\n apply ite.if_true,\n from h5,\n\n by_cases z ∈ σ with h6,\n\n have h7: x ≠ z, from h2,\n have h8, from env.contains_without.rinv ⟨h6, h7.symm⟩,\n have h9: (env.apply (env.without σ x) z = σ z), from env.without_equiv_with z h8,\n rw[h9],\n apply ite.if_false,\n by_contradiction h10,\n have h11, from h10.left,\n contradiction,\n\n have h7, from env.contains_apply_equiv.left.mpr h6,\n have h8: z ∉ (env.without σ x), from env.not_in_without h6,\n have h9: (env.apply (env.without σ x) z = none), from env.contains_apply_equiv.left.mpr h8,\n have h10: (env.apply (env.without σ x) z = σ z), from eq.trans h9 h7.symm,\n rw[h10],\n apply ite.if_false,\n by_contradiction h10,\n have h11, from h10.left,\n contradiction,\n end,\n vc.subst_env_exact_equivalent_env this\n\nlemma eq_value_of_equiv_subst {σ₁ σ₂: env} {x: var} {v: value}:\n (∀z, z ∈ σ₁ → (σ₁ z = σ₂ z)) → (σ₁ x = v) → (σ₂ x = v) :=\n assume env_equiv: ∀z, z ∈ σ₁ → (σ₁ z = σ₂ z),\n assume x_is_v: σ₁ x = v,\n have x ∈ σ₁, from env.contains_apply_equiv.right.mp (exists.intro v x_is_v),\n have σ₁ x = σ₂ x, from env_equiv x this,\n show σ₂ x = v, from this ▸ x_is_v\n\nlemma to_vc_closed_subst_of_closed {σ: env} {P: prop}: closed_subst σ P → closed_subst σ P.to_vc :=\n begin\n assume h1,\n assume x,\n assume h2,\n have h3, from free_in_prop_of_free_in_to_vc h2,\n from h1 h3\n end\n", "meta": {"author": "levjj", "repo": "esverify-theory", "sha": "8565b123c87b0113f83553d7732cd6696c9b5807", "save_path": "github-repos/lean/levjj-esverify-theory", "path": "github-repos/lean/levjj-esverify-theory/esverify-theory-8565b123c87b0113f83553d7732cd6696c9b5807/src/substitution.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4610167941228965, "lm_q2_score": 0.02479815875415397, "lm_q1q2_score": 0.011432367648990704}} {"text": "import Lean\nimport Mathlib.Control.Writer\nimport PremiseSelection.StatementFeatures\nimport PremiseSelection.ProofSource\n\nnamespace PremiseSelection\n\nopen Lean Lean.Elab Lean.Elab.Term Lean.Elab.Command Lean.Meta System\n\n/-- Holds the name, features and premises of a single theorem. -/\nstructure TheoremPremises where\n name : Name\n features : StatementFeatures\n argumentsFeatures : Array StatementFeatures\n premises : Multiset Name\n\ninstance : ToJson TheoremPremises where\n toJson data :=\n Json.mkObj [\n (\"name\", toJson data.name),\n (\"features\", toJson data.features),\n (\"argumentsFeatures\", toJson data.argumentsFeatures),\n (\"premises\", toJson data.premises)\n ]\n\ninstance : ToString TheoremPremises where\n toString := Json.pretty ∘ toJson\n\n/-- Used to choose the feature format: nameCounts and/or bigramCounts and/or\ntrigramCounts -/\nstructure FeatureFormat where\n n : Bool := true\n b : Bool := true\n t : Bool := true\nderiving Inhabited\n\n/-- Structure to put together all the user options: max expression depth, filter\nuser premises and feature format. -/\nstructure UserOptions where\n minDepth : UInt32 := 0\n maxDepth : UInt32 := 255\n noAux : Bool := false\n source : Bool := false\n math : Bool := false\n format : FeatureFormat := default\nderiving Inhabited\n\n/-- Features used for training. All the features (arguments and theorem) should\nbe put together in a sequence tagged with `T` for theorem or `H` for\nhypotheses. -/\ndef getFeatures (tp : TheoremPremises) (format : FeatureFormat) : String :=\n Id.run <| do\n let statementF := tp.features\n let argsF := tp.argumentsFeatures\n let mut result : Array String := #[]\n if format.n then\n result := result ++ statementF.nameCounts.toTFeatures ++\n argsF.concatMap (Multiset.toHFeatures ∘ StatementFeatures.nameCounts)\n if format.b then\n result := result ++ statementF.bigramCounts.toTFeatures ++\n argsF.concatMap (Multiset.toHFeatures ∘ StatementFeatures.bigramCounts)\n if format.t then\n result := result ++ statementF.trigramCounts.toTFeatures ++\n argsF.concatMap (Multiset.toHFeatures ∘ StatementFeatures.trigramCounts)\n return \" \".intercalate result.data\n\n/-- Premises are simply concatenated. -/\ndef getLabels (tp : TheoremPremises) : String :=\n let thmName := tp.name.toString\n thmName ++ \" : \" ++ (\" \".intercalate (tp.premises.toList.map toString))\n\nsection CoreExtractor\n\n/-- Given a name `n`, if it qualifies as a premise, it returns `[n]`, otherwise\nit returns the empty list. -/\nprivate def getTheoremFromName (n : Name) : MetaM (Multiset Name) := do\n -- Get all consts whose type is of type Prop.\n if let some cinfo := (← getEnv).find? n then\n if (← inferType cinfo.type).isProp then\n pure (Multiset.singleton n)\n else\n pure Multiset.empty\n else pure Multiset.empty\n\nprivate def getTheoremFromExpr (e : Expr) : MetaM (Multiset Name) := do\n if let .const n _ := e then getTheoremFromName n else pure Multiset.empty\n\nprivate def visitPremise (e : Expr) : WriterT (Multiset Name) MetaM Unit := do\n getTheoremFromExpr e >>= tell\n\nprivate def extractPremises (e : Expr) : MetaM (Multiset Name) := do\n let ((), premises) ← WriterT.run <| forEachExpr visitPremise e\n pure premises\n\n/-- Given a `ConstantInfo` that holds theorem data, it finds the premises used\nin the proof and constructs an object of type `PremisesData` with all. -/\nprivate def extractPremisesFromConstantInfo\n (minDepth : UInt32 := 0) (maxDepth : UInt32 := 255)\n : ConstantInfo → MetaM (Option TheoremPremises)\n | ConstantInfo.thmInfo { name := n, type := ty, value := v, .. } => do\n let (thmFeats, argsFeats) ← getThmAndArgsFeatures ty\n -- Heuristic that can be used to ignore simple theorems and to avoid long\n -- executions for deep theorems.\n if minDepth <= v.approxDepth && v.approxDepth < maxDepth then\n pure <| TheoremPremises.mk n thmFeats argsFeats (← extractPremises v)\n else\n pure none\n | _ => pure none\n\nend CoreExtractor\n\nsection Variants\n\n/-- Same as `extractPremisesFromConstantInfo` but take an idenitfier and gets\nits information from the environment. -/\ndef extractPremisesFromId\n (minDepth : UInt32 := 0) (maxDepth : UInt32 := 255) (id : Name)\n : MetaM (Option TheoremPremises) := do\n if let some cinfo := (← getEnv).find? id then\n extractPremisesFromConstantInfo minDepth maxDepth cinfo\n else pure none\n\n/-- Extract and print premises from a single theorem. -/\ndef extractPremisesFromThm\n (minDepth : UInt32 := 0) (maxDepth : UInt32 := 255) (stx : Syntax)\n : MetaM (Array TheoremPremises) := do\n let mut thmData : Array TheoremPremises := #[]\n for name in ← resolveGlobalConst stx do\n if let some data ← extractPremisesFromId minDepth maxDepth name then\n thmData := thmData.push data\n return thmData\n\n/-- Extract and print premises from all the theorems in the context. -/\ndef extractPremisesFromCtx (minDepth : UInt32 := 0) (maxDepth : UInt32 := 255)\n : MetaM (Array TheoremPremises) := do\n let mut ctxData : Array TheoremPremises := #[]\n for (_, cinfo) in (← getEnv).constants.toList do\n let data? ← extractPremisesFromConstantInfo minDepth maxDepth cinfo\n if let some data := data? then\n ctxData := ctxData.push data\n return ctxData\n\nend Variants\n\nsection FromImports\n\nopen IO IO.FS\n\n/-- Given a way to insert `TheoremPremises`, this function goes through all\nthe theorems in a module, extracts the premises filtering them appropriately\nand inserts the resulting data. -/\nprivate def extractPremisesFromModule\n (insert : TheoremPremises → IO Unit)\n (moduleName : Name) (moduleData : ModuleData)\n (minDepth maxDepth : UInt32) (noAux source math : Bool := false)\n : MetaM Unit := do\n dbg_trace s!\"Extracting premises from {moduleName}.\"\n let mut filter : Name → Multiset Name → MetaM (Multiset Name × Bool) :=\n fun _ ns => pure (ns, false)\n -- Source filter.\n if source then\n if let some modulePath ← proofSourcePath moduleName then\n -- Avoid very large files. In particular mathbin files over 2MB.\n let mut fileSize := 0\n let pathFromImport :=\n if moduleName.getRoot == `Mathbin then\n pathFromMathbinImport\n else pathFromMathlibImport\n if let some synportPath ← pathFromImport moduleName then\n let mdata ← System.FilePath.metadata synportPath\n fileSize := mdata.byteSize\n if fileSize == 0 then\n dbg_trace s! \"Aborted {moduleName}, ported file not found\"\n return ()\n if fileSize > 2 * 1024 * 1024 then\n dbg_trace s! \"Aborted {moduleName}, size {fileSize}\"\n return ()\n\n -- If source premises and path found, then create a filter looking at\n -- proof source. If no proof source is found, no filter is applied.\n let data ← IO.FS.readFile modulePath\n let proofsJson :=\n match Json.parse data with\n | Except.ok json => json\n | Except.error _ => Json.null\n filter := fun thmName premises => do\n if let some source ← proofSource thmName proofsJson then\n return (filterUserPremises premises source, true)\n else return (premises, false)\n -- Math-only filter.\n else if math then\n let allNamesPath := \"data/math_names\"\n filter := fun _ premises => do\n let mut filteredPremises : Multiset Name := ∅\n for (premise, count) in premises do\n let output ← IO.Process.output {\n cmd := \"grep\",\n args := #[\"-x\", premise.toString, allNamesPath] }\n if output.exitCode == 0 && !output.stdout.isEmpty then\n filteredPremises := filteredPremises.insert premise count\n return (filteredPremises, true)\n\n -- Go through all theorems in the module, filter premises and write.\n let mut countFoundAndNotEmpty := 0\n let mut countFound := 0\n let mut countTotal := 0\n for cinfo in moduleData.constants do\n let data? ← extractPremisesFromConstantInfo minDepth maxDepth cinfo\n if let some data := data? then\n countTotal := countTotal + 1\n let mut filteredPremises : Multiset Name := ∅\n let (filterResult, found) ← filter data.name data.premises\n filteredPremises := filterResult\n if noAux || source || math then\n filteredPremises ← noAuxFilter filteredPremises\n if !source && !filteredPremises.isEmpty then\n countFoundAndNotEmpty := countFoundAndNotEmpty + 1\n let filteredData := { data with premises := filteredPremises }\n insert filteredData\n if source then\n if found then\n countFound := countFound + 1\n if found && !filteredPremises.isEmpty then\n countFoundAndNotEmpty := countFoundAndNotEmpty + 1\n let filteredData := { data with premises := filteredPremises }\n insert filteredData\n if source then\n dbg_trace s!\"Total : {countTotal}\"\n dbg_trace s!\"Found in source : {countFound}\"\n dbg_trace s!\"Found and not empty : {countFoundAndNotEmpty}\"\n else\n dbg_trace s!\"Total : {countTotal}\"\n dbg_trace s!\"Not empty : {countFoundAndNotEmpty}\"\n return ()\n where\n blackList : List String := [\"._\", \"_private.\", \"_Private.\"]\n\n noAuxFilter (premises : Multiset Name) : MetaM (Multiset Name) := do\n let mut result : Multiset Name := ∅\n for (p, c) in premises do\n if !(blackList.any (·.isSubstrOf p.toString)) then\n result := result.insert p c\n return result\n\n/-- Call `extractPremisesFromModule` with an insertion mechanism that writes\nto the specified files for labels and features. -/\ndef extractPremisesFromModuleToFiles\n (moduleName : Name) (moduleData : ModuleData)\n (labelsPath featuresPath : FilePath) (userOptions : UserOptions := default)\n : MetaM Unit := do\n let labelsHandle ← Handle.mk labelsPath Mode.append false\n let featuresHandle ← Handle.mk featuresPath Mode.append false\n\n let insert : TheoremPremises → IO Unit := fun data => do\n labelsHandle.putStrLn (getLabels data)\n featuresHandle.putStrLn (getFeatures data userOptions.format)\n\n let minDepth := userOptions.minDepth\n let maxDepth := userOptions.maxDepth\n let noAux := userOptions.noAux\n let source := userOptions.source\n let math := userOptions.math\n extractPremisesFromModule\n insert moduleName moduleData minDepth maxDepth noAux source math\n\n/-- Go through the whole module and find the defininions that appear in the\ncorresponding source file. This was used to generate `math_names`. -/\ndef extractUserDefinitionsFromModuleToFile\n (moduleName : Name) (moduleData : ModuleData) (outputPath : FilePath)\n : MetaM Unit := do\n let labelsHandle ← Handle.mk outputPath Mode.append false\n for cinfo in moduleData.constants do\n if let some modulePath ← pathFromMathbinImport moduleName then\n let args := #[cinfo.name.toString, modulePath.toString]\n let output ← IO.Process.output { cmd := \"grep\", args := args }\n if output.exitCode == 0 && !output.stdout.isEmpty then\n labelsHandle.putStrLn cinfo.name.toString\n\n/-- Looks through all the meaningful imports and applies\n`extractPremisesFromModuleToFiles` to each of them. -/\ndef extractPremisesFromImportsToFiles\n (labelsPath featuresPath : FilePath) (userOptions : UserOptions := default)\n : MetaM Unit := do\n dbg_trace s!\"Clearing {labelsPath} and {featuresPath}.\"\n\n IO.FS.writeFile labelsPath \"\"\n IO.FS.writeFile featuresPath \"\"\n\n dbg_trace s!\"Extracting premises from imports to {labelsPath}, {featuresPath}.\"\n\n let env ← getEnv\n let imports := env.imports.map (·.module)\n let moduleNamesArray := env.header.moduleNames\n let moduleDataArray := env.header.moduleData\n\n let mut count := 0\n for (moduleName, moduleData) in Array.zip moduleNamesArray moduleDataArray do\n let isMathImport :=\n moduleName.getRoot == `Mathbin || moduleName.getRoot == `Mathlib\n if imports.contains moduleName && isMathImport then\n count := count + 1\n extractPremisesFromModuleToFiles\n moduleName moduleData labelsPath featuresPath userOptions\n dbg_trace s!\"count = {count}.\"\n\n pure ()\n\nend FromImports\n\nsection Json\n\ndef extractPremisesFromCtxJson : MetaM Json :=\n toJson <$> extractPremisesFromCtx\n\ndef extractPremisesFromThmJson (stx : Syntax) : MetaM Json :=\n toJson <$> extractPremisesFromThm (stx := stx)\n\nend Json\n\nsection Commands\n\nprivate def runAndPrint [ToJson α] (f : MetaM α) : CommandElabM Unit :=\n liftTermElabM <| do dbg_trace s!\"{Json.pretty <| toJson <| ← f}\"\n\nelab \"extract_premises_from_thm \" id:term : command =>\n runAndPrint <| extractPremisesFromThm (stx := id)\n\nelab \"extract_premises_from_ctx\" : command =>\n runAndPrint <| extractPremisesFromCtx\n\nsyntax (name := extract_premises_to_files)\n \"extract_premises_to_files l:\" str \" f:\" str : command\n\n@[command_elab «extract_premises_to_files»]\nunsafe def elabExtractPremisesToFiles : CommandElab\n| `(extract_premises_to_files l:$lp f:$fp) => liftTermElabM <| do\n let labelsPath ← evalTerm String (mkConst `String) lp.raw\n let featuresPath ← evalTerm String (mkConst `String) fp.raw\n extractPremisesFromImportsToFiles labelsPath featuresPath\n| _ => throwUnsupportedSyntax\n\nend Commands\n\nend PremiseSelection\n", "meta": {"author": "BartoszPiotrowski", "repo": "lean-premise-selection", "sha": "f414bdd8f17e21b368b8ef69cbc47dd55a5cc032", "save_path": "github-repos/lean/BartoszPiotrowski-lean-premise-selection", "path": "github-repos/lean/BartoszPiotrowski-lean-premise-selection/lean-premise-selection-f414bdd8f17e21b368b8ef69cbc47dd55a5cc032/PremiseSelection/Extractor.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2689414213699951, "lm_q2_score": 0.042087727314858395, "lm_q1q2_score": 0.011319133206290783}} {"text": "import Lean\nimport Mathlib\n\nimport Qpf.Macro.Data.Replace\nimport Qpf.Macro.Data.Count\nimport Qpf.Macro.Data.View\nimport Qpf.Macro.Common\nimport Qpf.Macro.Comp\n\nopen Lean Meta Elab.Command\nopen Elab (Modifiers elabModifiers)\nopen Parser.Term (namedArgument)\nopen PrettyPrinter (delab)\nopen Macro (elabCommand')\n\nprivate def Array.enum (as : Array α) : Array (Nat × α) :=\n (Array.range as.size).zip as\n\n\n/--\n Given a natural number `n`, produce a sequence of `n` calls of `.fs`, ending in `.fz`.\n\n The result corresponds to a `i : PFin2 _` such that `i.toNat == n`\n-/\nprivate def PFin2.quoteOfNat : Nat → Term\n | 0 => mkIdent ``PFin2.fz\n | n+1 => Syntax.mkApp (mkIdent ``PFin2.fs) #[(quoteOfNat n)]\n\nprivate def Fin2.quoteOfNat : Nat → Term\n | 0 => mkIdent ``Fin2.fz\n | n+1 => Syntax.mkApp (mkIdent ``Fin2.fs) #[(quoteOfNat n)]\n\n\nnamespace Data.Command\n\n/-!\n ## Parser\n for `data` and `codata` declarations\n-/\nsection\n open Lean.Parser Lean.Parser.Command\n\n def inductive_like (cmd : String) : Parser\n := leading_parser cmd >> declId >> optDeclSig \n >> Parser.optional (symbol \" :=\" <|> \" where\") \n >> many ctor \n >> optDeriving\n\n def data := inductive_like \"data \"\n def codata := inductive_like \"codata \"\n\n @[command_parser]\n def declaration : Parser\n := leading_parser declModifiers false >> (data <|> codata)\nend\n\n/-!\n ## Elaboration\n-/\nopen Elab.Term (TermElabM)\n\ndef Name.replacePrefix (old_pref new_pref : Name) : Name → Name\n | Name.anonymous => Name.anonymous\n | Name.str p s => let p' := if p == old_pref then new_pref\n else replacePrefix old_pref new_pref p\n Name.mkStr p' s\n | Name.num p v => let p' := if p == old_pref then new_pref\n else replacePrefix old_pref new_pref p\n Name.mkNum p' v\n\n\n\n\n\n\ndef CtorView.declReplacePrefix (pref new_pref : Name) (ctor: CtorView) : CtorView :=\n let declName := Name.replacePrefix pref new_pref ctor.declName\n {\n declName,\n ref := ctor.ref\n modifiers := ctor.modifiers\n binders := ctor.binders\n type? := ctor.type?\n }\n\n\n\nopen Parser in\n/--\n Defines the \"head\" type of a polynomial functor\n\n That is, it defines a type with exactly as many constructor as the input type, but such that\n all constructors are constants (take no arguments).\n-/\ndef mkHeadT (view : InductiveView) : CommandElabM Name := do\n -- If the original declId was `MyType`, we want to register the head type under `MyType.HeadT`\n let suffix := \"HeadT\"\n let declName := Name.mkStr view.declName suffix\n let declId := mkNode ``Command.declId #[mkIdent declName, mkNullNode]\n let shortDeclName := Name.mkSimple suffix\n\n let modifiers : Modifiers := {\n isUnsafe := view.modifiers.isUnsafe\n }\n -- The head type is the same as the original type, but with all constructor arguments removed\n let ctors ← view.ctors.mapM fun ctor => do\n let declName := Name.replacePrefix view.declName declName ctor.declName\n pure { \n modifiers, declName,\n ref := ctor.ref\n binders := mkNullNode\n type? := none\n : CtorView\n } \n\n -- let type ← `(Type $(mkIdent `u))\n\n -- TODO: make `HeadT` universe polymorphic\n let view := {\n ctors, declId, declName, shortDeclName, modifiers,\n binders := view.binders.setArgs #[]\n levelNames := view.levelNames\n\n ref := view.ref \n type? := view.type?\n \n derivingClasses := view.derivingClasses\n computedFields := #[]\n : InductiveView\n }\n\n trace[QPF] \"mkHeadT :: elabInductiveViews\"\n elabInductiveViews #[view]\n pure declName\n\n\nopen Parser in\nprivate def matchAltsOfArray (matchAlts : Array Syntax) : Syntax :=\n mkNode ``Term.matchAlts #[mkNullNode matchAlts]\n\n\nopen Parser in\n/--\n Wraps an array of `matchAltExpr` syntax objects into a single `Command.declValEqns` node, for\n use in inductive definitions\n-/\nprivate def declValEqnsOfMatchAltArray (matchAlts : Array Syntax) : TSyntax ``Command.declValEqns :=\n let body := matchAltsOfArray matchAlts\n let body := mkNode ``Term.matchAltsWhereDecls #[body, mkNullNode]\n mkNode ``Command.declValEqns #[body]\n\n\nopen Parser Parser.Term Parser.Command in\n/--\n Defines the \"child\" family of type vectors for an `n`-ary polynomial functor\n\n That is, it defines a type `ChildT : HeadT → TypeVec n` such that number of inhabitants of\n `ChildT a i` corresponds to the times that constructor `a` takes an argument of the `i`-th type\n argument\n-/\ndef mkChildT (view : InductiveView) (r : Replace) (headTName : Name) : CommandElabM Name := do \n -- If the original declId was `MyType`, we want to register the child type under `MyType.ChildT`\n let suffix := \"ChildT\"\n let declName := Name.mkStr view.declName suffix\n let declId := mkNode ``Command.declId #[mkIdent declName, mkNullNode]\n\n let target_type := Syntax.mkApp (mkIdent ``TypeVec) #[quote r.arity]\n\n let matchAlts ← view.ctors.mapM fun ctor => do \n let head := mkIdent $ Name.replacePrefix view.declName headTName ctor.declName \n\n let counts := countVarOccurences r ctor.type?\n let counts := counts.map fun n => \n Syntax.mkApp (mkIdent ``PFin2) #[quote n]\n\n `(matchAltExpr| | $head => (!![ $counts,* ]))\n\n let body := declValEqnsOfMatchAltArray matchAlts\n let headT := mkIdent headTName\n\n \n\n let cmd ← `(\n def $declId : $headT → $target_type\n $body:declValEqns\n )\n\n -- trace[QPF] \"mkChildT :: elabCommand'\"\n elabCommand' cmd\n\n pure declName\n\n\n\nopen Parser.Term in\n/--\n Show that the `Shape` type is a qpf, through an isomorphism with the `Shape.P` pfunctor\n-/\ndef mkQpf (shapeView : InductiveView) (ctorArgs : Array CtorArgs) (headT P : Ident) (arity : Nat) : CommandElabM Unit := do\n let shapeN := shapeView.declName\n let q := mkIdent $ Name.mkStr shapeN \"qpf\"\n let shape := mkIdent shapeN\n\n let ctors := shapeView.ctors.zip ctorArgs\n\n /-\n `box` maps objects from the curried form, to the internal uncurried form.\n See below, or [.ofPolynomial] for the signature\n\n Example, using a simple list type\n ```lean4\n fun x => match x with\n | MyList.Shape.nil a b => ⟨MyList.Shape.HeadT.nil, fun i => match i with\n | 0 => Fin2.elim0 (C:=fun _ => _)\n | 1 => fun j => match j with \n | (.ofNat' 0) => b\n | 2 => fun j => match j with \n | (.ofNat' 0) => a\n ⟩\n | MyList.Shape.cons a as => ⟨MyList.Shape.HeadT.cons, fun i j => match i with\n | 0 => match j with\n | .fz => as\n | 1 => Fin2.elim0 (C:=fun _ => _) j\n | 2 => match j with\n | .fz => a\n ```\n -/\n\n let boxBody ← ctors.mapM fun (ctor, args) => do\n let argsId := args.args.map mkIdent\n let alt := mkIdent ctor.declName\n let headAlt := mkIdent $ Name.replacePrefix shapeView.declName headT.getId ctor.declName\n\n `(matchAltExpr| | $alt:ident $argsId:ident* => ⟨$headAlt:ident, fun i => match i with\n $(\n ←args.per_type.enum.mapM fun (i, args) => do\n let i := arity - 1 - i\n let body ← if args.size == 0 then\n -- `(fun j => Fin2.elim0 (C:=fun _ => _) j)\n `(PFin2.elim0)\n else\n let alts ← args.enum.mapM fun (j, arg) =>\n let arg := mkIdent arg\n `(matchAltExpr| | $(PFin2.quoteOfNat j) => $arg)\n `(\n fun j => match j with\n $alts:matchAlt*\n )\n `(matchAltExpr| | $(Fin2.quoteOfNat i) => $body)\n ):matchAlt*\n ⟩)\n let box ← `(\n fun x => match x with\n $boxBody:matchAlt*\n )\n\n /-\n `unbox` does the opposite of `box`; it maps from uncurried to curried\n\n fun ⟨head, child⟩ => match head with\n | MyList.Shape.HeadT.nil => MyList.Shape.nil (child 2 .fz) (child 1 .fz)\n | MyList.Shape.HeadT.cons => MyList.Shape.cons (child 2 .fz) (child 0 .fz)\n -/\n\n /- the `child` variable in the example above -/\n let unbox_child := mkIdent <|<- Elab.Term.mkFreshBinderName;\n let unboxBody ← ctors.mapM fun (ctor, args) => do\n let alt := mkIdent ctor.declName\n let headAlt := mkIdent $ Name.replacePrefix shapeView.declName headT.getId ctor.declName\n \n let args : Array Term ← args.args.mapM fun arg => do\n -- find the pair `(i, j)` such that the argument is the `j`-th occurence of the `i`-th type\n let (i, j) := (args.per_type.enum.map fun (i, t) => \n -- the order of types is reversed, since `TypeVec`s count right-to-left\n let i := arity - 1 - i \n ((t.indexOf? arg).map fun ⟨j, _⟩ => (i, j)).toList\n ).toList.join.get! 0\n\n `($unbox_child $(Fin2.quoteOfNat i) $(PFin2.quoteOfNat j))\n\n let body := Syntax.mkApp alt args\n\n `(matchAltExpr| | $headAlt:ident => $body)\n\n let unbox ← `(\n fun ⟨head, $unbox_child⟩ => match head with\n $unboxBody:matchAlt*\n )\n\n let cmd ← `(\n instance $q:ident : MvQPF.IsPolynomial (@TypeFun.ofCurried $(quote arity) $shape) :=\n .ofEquiv $P {\n toFun := $box,\n invFun := $unbox,\n left_inv := by \n simp only [Function.LeftInverse]\n intro x\n cases x\n <;> rfl\n right_inv := by\n simp only [Function.RightInverse, Function.LeftInverse]\n intro x\n rcases x with ⟨head, child⟩;\n cases head\n <;> simp\n <;> apply congrArg\n <;> fin_destr\n <;> rfl\n }\n )\n trace[QPF] \"qpf: {cmd}\\n\"\n elabCommand' cmd\n\n pure ()\n\n\n\n\n\n\n\n\n\nstructure MkShapeResult where\n (r : Replace)\n (shape : Name)\n (P : Name)\n\nopen Parser in\ndef mkShape (view: DataView) : CommandElabM MkShapeResult := do\n -- If the original declId was `MyType`, we want to register the shape type under `MyType.Shape`\n let suffix := \"Shape\"\n let declName := Name.mkStr view.declName suffix\n let declId := mkNode ``Command.declId #[mkIdent declName, mkNullNode]\n let shortDeclName := Name.mkSimple suffix\n\n\n -- Extract the \"shape\" functors constructors\n let shapeIdent := mkIdent shortDeclName\n let ((ctors, ctorArgs), r) ← Replace.shapeOfCtors view shapeIdent\n let ctors := ctors.map (CtorView.declReplacePrefix view.declName declName)\n\n trace[QPF] \"mkShape :: r.getBinders = {←r.getBinders}\"\n trace[QPF] \"mkShape :: r.expr = {r.expr}\"\n\n -- Assemble it back together, into the shape inductive type\n let binders ← r.getBinders \n let binders := view.binders.setArgs #[binders]\n let modifiers : Modifiers := {\n isUnsafe := view.modifiers.isUnsafe\n }\n let view := {\n ctors, declId, declName, shortDeclName, modifiers, binders,\n levelNames := []\n\n ref := view.ref \n type? := view.type? \n \n derivingClasses := view.derivingClasses\n computedFields := #[]\n : InductiveView\n }\n\n trace[QPF] \"mkShape :: elabInductiveViews :: binders = {view.binders}\"\n elabInductiveViews #[view]\n\n let headTName ← mkHeadT view\n let childTName ← mkChildT view r headTName\n\n let PName := Name.mkStr declName \"P\"\n let PId := mkIdent PName\n -- let u ← Elab.Term.mkFreshBinderName\n let PDeclId := mkNode ``Command.declId #[PId, mkNullNode \n -- #[ TODO: make this universe polymorphic\n -- mkAtom \".{\",\n -- mkNullNode #[u],\n -- mkAtom \"}\"\n -- ]\n ]\n\n let headTId := mkIdent headTName\n let childTId := mkIdent childTName\n\n elabCommand' <|<- `(\n def $PDeclId := \n MvPFunctor.mk $headTId $childTId\n )\n\n \n mkQpf view ctorArgs headTId PId r.expr.size\n \n\n pure ⟨r, declName, PName⟩ \n\n\n\nopen Elab.Term in\n/--\n Checks whether the given term is a polynomial functor, i.e., whether there is an instance of \n `IsPolynomial F`, and return that instance (if it exists).\n-/\ndef isPolynomial (F: Term) : CommandElabM (Option Term) := do\n liftTermElabM do\n trace[QPF] \"isPolynomial::F = {F}\"\n let inst_type ← elabTerm (← `(MvQPF.IsPolynomial $F:term)) none\n try\n let inst ← synthInstance inst_type\n return some <|<- delab inst\n catch e =>\n trace[QPF] \"{e.toMessageData}\"\n return none\n\n\n\n/--\n Return a syntax tree for `MvQPF.Fix` or `MvQPF.Cofix` when self is `Data`, resp. `Codata`.\n-/\ndef DataCommand.fixOrCofix : DataCommand → Ident\n | .Data => mkIdent ``_root_.MvQPF.Fix\n | .Codata => mkIdent ``_root_.MvQPF.Cofix\n\n/--\n Return a syntax tree for `MvPFunctor.W` or `MvPFunctor.M` when self is `Data`, resp. `Codata`.\n-/\ndef DataCommand.fixOrCofixPolynomial : DataCommand → Ident\n | .Data => mkIdent ``_root_.MvPFunctor.W\n | .Codata => mkIdent ``_root_.MvPFunctor.M\n\n/--\n Take either the fixpoint or cofixpoint of `base` to produce an `Internal` uncurried QPF, \n and define the desired type as the curried version of `Internal`\n-/\ndef mkType (view : DataView) (base : Term) : CommandElabM Unit := do\n let uncurriedIdent := mkIdent $ Name.mkStr view.declName \"Uncurried\"\n let baseIdent := mkIdent $ Name.mkStr view.declName \"Base\"\n\n let deadBinderNamedArgs ← view.deadBinderNames.mapM fun n => \n `(namedArgument| ($n:ident := $n:term))\n let uncurriedApplied ← `($uncurriedIdent $deadBinderNamedArgs:namedArgument*)\n\n let arity := view.liveBinders.size\n\n let poly ← isPolynomial base\n trace[QPF] \"poly: {poly}\"\n\n let cmd ← match poly with\n | some poly => \n let fix_or_cofix := DataCommand.fixOrCofixPolynomial view.command\n `(\n abbrev $baseIdent:ident $view.deadBinders:bracketedBinder* : _root_.TypeFun $(quote <| arity + 1)\n := (@MvQPF.P _ _ $poly).Obj\n\n abbrev $uncurriedIdent:ident $view.deadBinders:bracketedBinder* : _root_.TypeFun $(quote arity)\n := ($fix_or_cofix $base).Obj\n ) \n | none =>\n let fix_or_cofix := DataCommand.fixOrCofix view.command\n `(\n abbrev $baseIdent:ident $view.deadBinders:bracketedBinder* : _root_.TypeFun $(quote <| arity + 1)\n := $base\n\n abbrev $uncurriedIdent:ident $view.deadBinders:bracketedBinder* : _root_.TypeFun $(quote arity)\n := $fix_or_cofix $base\n ) \n\n trace[QPF] \"elabData.cmd = {cmd}\"\n elabCommand' cmd\n\n elabCommand' <|<- `(\n abbrev $(view.declId) $view.deadBinders:bracketedBinder*\n := _root_.TypeFun.curried $uncurriedApplied\n )\n\n\n\n\n\n\n\n\n\n\nopen Parser in\n/--\n Count the number of arguments to a constructor\n-/\npartial def countConstructorArgs : Syntax → Nat\n | Syntax.node _ ``Term.arrow #[_, _, tail] => 1 + (countConstructorArgs tail)\n | _ => 0\n\n\nopen Elab\n/--\n Add convenient constructor functions to the environment\n-/\ndef mkConstructors (view : DataView) (shape : Name) : CommandElabM Unit := do\n for ctor in view.ctors do\n trace[QPF] \"mkConstructors\\n{ctor.declName} : {ctor.type?}\"\n let n_args := (ctor.type?.map countConstructorArgs).getD 0\n\n let args ← (List.range n_args).mapM fun _ => \n do pure <| mkIdent <|← Elab.Term.mkFreshBinderName\n let args := args.toArray\n\n let mk := mkIdent ((DataCommand.fixOrCofix view.command).getId ++ `mk)\n let shapeCtor := mkIdent <| Name.replacePrefix view.declName shape ctor.declName\n trace[QPF] \"shapeCtor = {shapeCtor}\"\n\n \n\n let body := if n_args = 0 then\n `($mk $shapeCtor)\n else\n `(fun $args:ident* => $mk ($shapeCtor $args:ident*))\n let body ← body\n \n let explicit ← view.getExplicitExpectedType\n let type : Term := TSyntax.mk <|\n (ctor.type?.map fun type => \n Replace.replaceAllStx view.getExpectedType explicit type\n ).getD explicit\n let modifiers : Modifiers := {\n isNoncomputable := view.modifiers.isNoncomputable\n attrs := #[{\n name := `matchPattern\n }]\n }\n let cmd ← `(\n $(quote modifiers):declModifiers\n def $(mkIdent ctor.declName) : $type\n := $body:term\n )\n\n trace[QPF] \"mkConstructor.cmd = {cmd}\"\n elabCommand' cmd\n return ()\n\n\n\n\nopen Macro Comp in\n/--\n Top-level elaboration for both `data` and `codata` declarations\n-/\n@[command_elab declaration]\ndef elabData : CommandElab := fun stx => do \n let modifiers ← elabModifiers stx[0]\n let decl := stx[1]\n let view ← dataSyntaxToView modifiers decl\n\n let (nonRecView, _rho) ← makeNonRecursive view;\n trace[QPF] \"nonRecView: {nonRecView}\"\n\n let ⟨r, shape, _P⟩ ← mkShape nonRecView\n\n /- Composition pipeline -/\n let base ← elabQpfCompositionBody {\n liveBinders := nonRecView.liveBinders, \n deadBinders := nonRecView.deadBinders, \n type? := none,\n target := ←`(\n $(mkIdent shape):ident $r.expr*\n )\n }\n trace[QPF] m!\"base = {base}\"\n\n mkType view base \n -- mkConstructors view shape\n\n\nend Data.Command\n\nnamespace Test\n set_option trace.Meta true\n set_option trace.Meta.debug true\n sudo set_option trace.QPF true\n sudo set_option trace.QPF.Comp true\n set_option pp.raw true\n\n data Wrap α \n | mk : α → Wrap α\n\n #print Wrap.Shape\n #check (Wrap.Shape : CurriedTypeFun 1)\n\n #print Test.Wrap.Uncurried\n #print Test.Wrap.Base\n\n\nend Test", "meta": {"author": "alexkeizer", "repo": "qpf4", "sha": "980f97425b9d5a5e3897073df33794192b3b3124", "save_path": "github-repos/lean/alexkeizer-qpf4", "path": "github-repos/lean/alexkeizer-qpf4/qpf4-980f97425b9d5a5e3897073df33794192b3b3124/Qpf/Macro/Data.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40356685373537454, "lm_q2_score": 0.028007522634267163, "lm_q1q2_score": 0.011302907790433489}} {"text": "/-\nCopyright (c) 2016 Gabriel Ebner. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Gabriel Ebner, Sebastian Ullrich\n\nClassy functions for lifting monadic actions of different shapes.\n\nThis theory is roughly modeled after the Haskell 'layers' package https://hackage.haskell.org/package/layers-0.1.\nPlease see https://hackage.haskell.org/package/layers-0.1/docs/Documentation-Layers-Overview.html for an exhaustive discussion of the different approaches to lift functions.\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.function\nimport Mathlib.Lean3Lib.init.coe\nimport Mathlib.Lean3Lib.init.control.monad\n \n\nuniverses u v w l u_1 u_2 u_3 u_4 \n\nnamespace Mathlib\n\n/-- A function for lifting a computation from an inner monad to an outer monad.\n Like [MonadTrans](https://hackage.haskell.org/package/transformers-0.5.5.0/docs/Control-Monad-Trans-Class.html),\n but `n` does not have to be a monad transformer.\n Alternatively, an implementation of [MonadLayer](https://hackage.haskell.org/package/layers-0.1/docs/Control-Monad-Layer.html#t:MonadLayer) without `layerInvmap` (so far). -/\nclass has_monad_lift (m : Type u → Type v) (n : Type u → Type w) \nwhere\n monad_lift : {α : Type u} → m α → n α\n\n/-- The reflexive-transitive closure of `has_monad_lift`.\n `monad_lift` is used to transitively lift monadic computations such as `state_t.get` or `state_t.put s`.\n Corresponds to [MonadLift](https://hackage.haskell.org/package/layers-0.1/docs/Control-Monad-Layer.html#t:MonadLift). -/\nclass has_monad_lift_t (m : Type u → Type v) (n : Type u → Type w) \nwhere\n monad_lift : {α : Type u} → m α → n α\n\n/-- A coercion that may reduce the need for explicit lifting.\n Because of [limitations of the current coercion resolution](https://github.com/leanprover/lean/issues/1402), this definition is not marked as a global instance and should be marked locally instead. -/\ndef has_monad_lift_to_has_coe {m : Type u_1 → Type u_2} {n : Type u_1 → Type u_3} [has_monad_lift_t m n] {α : Type u_1} : has_coe (m α) (n α) :=\n has_coe.mk monad_lift\n\nprotected instance has_monad_lift_t_trans (m : Type u_1 → Type u_2) (n : Type u_1 → Type u_3) (o : Type u_1 → Type u_4) [has_monad_lift_t m n] [has_monad_lift n o] : has_monad_lift_t m o :=\n has_monad_lift_t.mk fun (α : Type u_1) (ma : m α) => has_monad_lift.monad_lift (monad_lift ma)\n\nprotected instance has_monad_lift_t_refl (m : Type u_1 → Type u_2) : has_monad_lift_t m m :=\n has_monad_lift_t.mk fun (α : Type u_1) => id\n\n@[simp] theorem monad_lift_refl {m : Type u → Type v} {α : Type u} : monad_lift = id :=\n rfl\n\n/-- A functor in the category of monads. Can be used to lift monad-transforming functions.\n Based on pipes' [MFunctor](https://hackage.haskell.org/package/pipes-2.4.0/docs/Control-MFunctor.html),\n but not restricted to monad transformers.\n Alternatively, an implementation of [MonadTransFunctor](http://duairc.netsoc.ie/layers-docs/Control-Monad-Layer.html#t:MonadTransFunctor). -/\nclass monad_functor (m : Type u → Type v) (m' : Type u → Type v) (n : Type u → Type w) (n' : Type u → Type w) \nwhere\n monad_map : {α : Type u} → ({α : Type u} → m α → m' α) → n α → n' α\n\n/-- The reflexive-transitive closure of `monad_functor`.\n `monad_map` is used to transitively lift monad morphisms such as `state_t.zoom`.\n A generalization of [MonadLiftFunctor](http://duairc.netsoc.ie/layers-docs/Control-Monad-Layer.html#t:MonadLiftFunctor), which can only lift endomorphisms (i.e. m = m', n = n'). -/\nclass monad_functor_t (m : Type u → Type v) (m' : Type u → Type v) (n : Type u → Type w) (n' : Type u → Type w) \nwhere\n monad_map : {α : Type u} → ({α : Type u} → m α → m' α) → n α → n' α\n\nprotected instance monad_functor_t_trans (m : Type u_1 → Type u_2) (m' : Type u_1 → Type u_2) (n : Type u_1 → Type u_3) (n' : Type u_1 → Type u_3) (o : Type u_1 → Type u_4) (o' : Type u_1 → Type u_4) [monad_functor_t m m' n n'] [monad_functor n n' o o'] : monad_functor_t m m' o o' :=\n monad_functor_t.mk\n fun (α : Type u_1) (f : {α : Type u_1} → m α → m' α) => monad_functor.monad_map fun (α : Type u_1) => monad_map f\n\nprotected instance monad_functor_t_refl (m : Type u_1 → Type u_2) (m' : Type u_1 → Type u_2) : monad_functor_t m m' m m' :=\n monad_functor_t.mk fun (α : Type u_1) (f : {α : Type u_1} → m α → m' α) => f\n\n@[simp] theorem monad_map_refl {m : Type u → Type v} {m' : Type u → Type v} (f : {α : Type u} → m α → m' α) {α : Type u} : monad_map f = f :=\n rfl\n\n/-- Run a monad stack to completion.\n `run` should be the composition of the transformers' individual `run` functions.\n This class mostly saves some typing when using highly nested monad stacks:\n ```\n @[reducible] def my_monad := reader_t my_cfg $ state_t my_state $ except_t my_err id\n -- def my_monad.run {α : Type} (x : my_monad α) (cfg : my_cfg) (st : my_state) := ((x.run cfg).run st).run\n def my_monad.run {α : Type} (x : my_monad α) := monad_run.run x\n ```\n -/\nclass monad_run (out : outParam (Type u → Type v)) (m : Type u → Type v) \nwhere\n run : {α : Type u} → m α → out α\n\n", "meta": {"author": "AurelienSaue", "repo": "Mathlib4_auto", "sha": "590df64109b08190abe22358fabc3eae000943f2", "save_path": "github-repos/lean/AurelienSaue-Mathlib4_auto", "path": "github-repos/lean/AurelienSaue-Mathlib4_auto/Mathlib4_auto-590df64109b08190abe22358fabc3eae000943f2/Mathlib/Lean3Lib/init/control/lift.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.23651622568252115, "lm_q2_score": 0.047425869475051126, "lm_q1q2_score": 0.011216987647950982}} {"text": "/-\nCopyright (c) 2016 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Leonardo de Moura\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.function\nimport Mathlib.Lean3Lib.init.data.option.basic\nimport Mathlib.Lean3Lib.init.util\nimport Mathlib.Lean3Lib.init.control.combinators\nimport Mathlib.Lean3Lib.init.control.monad\nimport Mathlib.Lean3Lib.init.control.alternative\nimport Mathlib.Lean3Lib.init.control.monad_fail\nimport Mathlib.Lean3Lib.init.data.nat.div\nimport Mathlib.Lean3Lib.init.meta.exceptional\nimport Mathlib.Lean3Lib.init.meta.format\nimport Mathlib.Lean3Lib.init.meta.environment\nimport Mathlib.Lean3Lib.init.meta.pexpr\nimport Mathlib.Lean3Lib.init.data.repr\nimport Mathlib.Lean3Lib.init.data.string.basic\nimport Mathlib.Lean3Lib.init.meta.interaction_monad\nimport Mathlib.Lean3Lib.init.classical\n\nuniverses l \n\nnamespace Mathlib\n\ninfixl:2 \" >>=[tactic] \" => Mathlib.interaction_monad_bind\n\ninfixl:2 \" >>[tactic] \" => Mathlib.interaction_monad_seq\n\nnamespace tactic_state\n\n\n/-- Format the given tactic state. If `target_lhs_only` is true and the target\n is of the form `lhs ~ rhs`, where `~` is a simplification relation,\n then only the `lhs` is displayed.\n\n Remark: the parameter `target_lhs_only` is a temporary hack used to implement\n the `conv` monad. It will be removed in the future. -/\n/-- Format expression with respect to the main goal in the tactic state.\n If the tactic state does not contain any goals, then format expression\n using an empty local context. -/\nend tactic_state\n\n\n/-- `tactic` is the monad for building tactics.\n You use this to:\n - View and modify the local goals and hypotheses in the prover's state.\n - Invoke type checking and elaboration of terms.\n - View and modify the environment.\n - Build new tactics out of existing ones such as `simp` and `rewrite`.\n-/\nnamespace tactic\n\n\nend tactic\n\n\nnamespace tactic_result\n\n\nend tactic_result\n\n\nnamespace interactive\n\n\n/-- Typeclass for custom interaction monads, which provides\n the information required to convert an interactive-mode\n construction to a `tactic` which can actually be executed.\n\n Given a `[monad m]`, `execute_with` explains how to turn a `begin ... end`\n block, or a `by ...` statement into a `tactic α` which can actually be\n executed. The `inhabited` first argument facilitates the passing of an\n optional configuration parameter `config`, using the syntax:\n ```\n begin [custom_monad] with config,\n ...\n end\n ```\n-/\n/-- Default `executor` instance for `tactic`s themselves -/\nend interactive\n\n\nnamespace tactic\n\n\n/-- Does nothing. -/\n/--\n`try_core t` acts like `t`, but succeeds even if `t` fails. It returns the\nresult of `t` if `t` succeeded and `none` otherwise.\n-/\n/--\n`try t` acts like `t`, but succeeds even if `t` fails.\n-/\n/--\n`fail_if_success t` acts like `t`, but succeeds if `t` fails and fails if `t`\nsucceeds. Changes made by `t` to the `tactic_state` are preserved only if `t`\nsucceeds.\n-/\n/--\n`success_if_fail t` acts like `t`, but succeeds if `t` fails and fails if `t`\nsucceeds. Changes made by `t` to the `tactic_state` are preserved only if `t`\nsucceeds.\n-/\n/--\n`iterate_at_most n t` iterates `t` `n` times or until `t` fails, returning the\nresult of each successful iteration.\n-/\n/--\n`iterate_at_most' n t` repeats `t` `n` times or until `t` fails.\n-/\n/--\n`iterate_exactly n t` iterates `t` `n` times, returning the result of\neach iteration. If any iteration fails, the whole tactic fails.\n-/\n/--\n`iterate_exactly' n t` executes `t` `n` times. If any iteration fails, the whole\ntactic fails.\n-/\n/--\n`iterate t` repeats `t` 100.000 times or until `t` fails, returning the\nresult of each iteration.\n-/\n/--\n`iterate' t` repeats `t` 100.000 times or until `t` fails.\n-/\n/-- Decorate t's exceptions with msg. -/\n/-- Set the tactic_state. -/\n/-- Get the tactic_state. -/\n/--\n`capture t` acts like `t`, but succeeds with a result containing either the returned value\nor the exception.\nChanges made by `t` to the `tactic_state` are preserved in both cases.\n\nThe result can be used to inspect the error message, or passed to `unwrap` to rethrow the\nfailure later.\n-/\n/--\n`unwrap r` unwraps a result previously obtained using `capture`.\n\nIf the previous result was a success, this produces its wrapped value.\nIf the previous result was an exception, this \"rethrows\" the exception as if it came\nfrom where it originated.\n\n`do r ← capture t, unwrap r` is identical to `t`, but allows for intermediate tactics to be inserted.\n-/\n/--\n`resume r` continues execution from a result previously obtained using `capture`.\n\nThis is like `unwrap`, but the `tactic_state` is rolled back to point of capture even upon success.\n-/\nend tactic\n\n\nnamespace tactic\n\n\n/-- A parameter representing how aggressively definitions should be unfolded when trying to decide if two terms match, unify or are definitionally equal.\nBy default, theorem declarations are never unfolded.\n- `all` will unfold everything, including macros and theorems. Except projection macros.\n- `semireducible` will unfold everything except theorems and definitions tagged as irreducible.\n- `instances` will unfold all class instance definitions and definitions tagged with reducible.\n- `reducible` will only unfold definitions tagged with the `reducible` attribute.\n- `none` will never unfold anything.\n[NOTE] You are not allowed to tag a definition with more than one of `reducible`, `irreducible`, `semireducible` attributes.\n[NOTE] there is a config flag `m_unfold_lemmas`that will make it unfold theorems.\n -/\ninductive transparency where\n| all : transparency\n| semireducible : transparency\n| instances : transparency\n| reducible : transparency\n| none : transparency\n\n/-- (eval_expr α e) evaluates 'e' IF 'e' has type 'α'. -/\n/-- Return the partial term/proof constructed so far. Note that the resultant expression\n may contain variables that are not declarate in the current main goal. -/\n/-- Display the partial term/proof constructed so far. This tactic is *not* equivalent to\n `do { r ← result, s ← read, return (format_expr s r) }` because this one will format the result with respect\n to the current goal, and trace_result will do it with respect to the initial goal. -/\n/-- Return target type of the main goal. Fail if tactic_state does not have any goal left. -/\n/-- Clear the given local constant. The tactic fails if the given expression is not a local constant. -/\n/-- `revert_lst : list expr → tactic nat` is the reverse of `intron`. It takes a local constant `c` and puts it back as bound by a `pi` or `elet` of the main target.\nIf there are other local constants that depend on `c`, these are also reverted. Because of this, the `nat` that is returned is the actual number of reverted local constants.\nExample: with `x : ℕ, h : P(x) ⊢ T(x)`, `revert_lst [x]` returns `2` and produces the state ` ⊢ Π x, P(x) → T(x)`.\n -/\n/-- Return `e` in weak head normal form with respect to the given transparency setting.\n If `unfold_ginductive` is `tt`, then nested and/or mutually recursive inductive datatype constructors\n and types are unfolded. Recall that nested and mutually recursive inductive datatype declarations\n are compiled into primitive datatypes accepted by the Kernel. -/\n/-- (head) eta expand the given expression. `f : α → β` head-eta-expands to `λ a, f a`. If `f` isn't a function then it just returns `f`. -/\n/-- (head) beta reduction. `(λ x, B) c` reduces to `B[x/c]`. -/\n/-- (head) zeta reduction. Reduction of let bindings at the head of the expression. `let x : a := b in c` reduces to `c[x/b]`. -/\n/-- Zeta reduction. Reduction of let bindings. `let x : a := b in c` reduces to `c[x/b]`. -/\n/-- (head) eta reduction. `(λ x, f x)` reduces to `f`. -/\n/-- Succeeds if `t` and `s` can be unified using the given transparency setting. -/\n/-- Similar to `unify`, but it treats metavariables as constants. -/\n/-- Infer the type of the given expression.\n Remark: transparency does not affect type inference -/\n/-- Get the `local_const` expr for the given `name`. -/\n/-- Resolve a name using the current local context, environment, aliases, etc. -/\n/-- Return the hypothesis in the main goal. Fail if tactic_state does not have any goal left. -/\n/-- Get a fresh name that is guaranteed to not be in use in the local context.\n If `n` is provided and `n` is not in use, then `n` is returned.\n Otherwise a number `i` is appended to give `\"n_i\"`.\n-/\n/-- Helper tactic for creating simple applications where some arguments are inferred using\n type inference.\n\n Example, given\n ```\n rel.{l_1 l_2} : Pi (α : Type.{l_1}) (β : α -> Type.{l_2}), (Pi x : α, β x) -> (Pi x : α, β x) -> , Prop\n nat : Type\n real : Type\n vec.{l} : Pi (α : Type l) (n : nat), Type.{l1}\n f g : Pi (n : nat), vec real n\n ```\n then\n ```\n mk_app_core semireducible \"rel\" [f, g]\n ```\n returns the application\n ```\n rel.{1 2} nat (fun n : nat, vec real n) f g\n ```\n\n The unification constraints due to type inference are solved using the transparency `md`.\n-/\n/-- Similar to `mk_app`, but allows to specify which arguments are explicit/implicit.\n Example, given `(a b : nat)` then\n ```\n mk_mapp \"ite\" [some (a > b), none, none, some a, some b]\n ```\n returns the application\n ```\n @ite.{1} (a > b) (nat.decidable_gt a b) nat a b\n ```\n-/\n/-- (mk_congr_arg h₁ h₂) is a more efficient version of (mk_app `congr_arg [h₁, h₂]) -/\n/-- (mk_congr_fun h₁ h₂) is a more efficient version of (mk_app `congr_fun [h₁, h₂]) -/\n/-- (mk_congr h₁ h₂) is a more efficient version of (mk_app `congr [h₁, h₂]) -/\n/-- (mk_eq_refl h) is a more efficient version of (mk_app `eq.refl [h]) -/\n/-- (mk_eq_symm h) is a more efficient version of (mk_app `eq.symm [h]) -/\n/-- (mk_eq_trans h₁ h₂) is a more efficient version of (mk_app `eq.trans [h₁, h₂]) -/\n/-- (mk_eq_mp h₁ h₂) is a more efficient version of (mk_app `eq.mp [h₁, h₂]) -/\n/-- (mk_eq_mpr h₁ h₂) is a more efficient version of (mk_app `eq.mpr [h₁, h₂]) -/\n/- Given a local constant t, if t has type (lhs = rhs) apply substitution.\n Otherwise, try to find a local constant that has type of the form (t = t') or (t' = t).\n The tactic fails if the given expression is not a local constant. -/\n\n/-- Close the current goal using `e`. Fail if the type of `e` is not definitionally equal to\n the target type. -/\n/-- Elaborate the given quoted expression with respect to the current main goal.\n Note that this means that any implicit arguments for the given `pexpr` will be applied with fresh metavariables.\n If `allow_mvars` is tt, then metavariables are tolerated and become new goals if `subgoals` is tt. -/\n/-- Return true if the given expression is a type class. -/\n/-- Try to create an instance of the given type class. -/\n/-- Change the target of the main goal.\n The input expression must be definitionally equal to the current target.\n If `check` is `ff`, then the tactic does not check whether `e`\n is definitionally equal to the current target. If it is not,\n then the error will only be detected by the kernel type checker. -/\n/-- `assert_core H T`, adds a new goal for T, and change target to `T -> target`. -/\n/-- `assertv_core H T P`, change target to (T -> target) if P has type T. -/\n/-- `define_core H T`, adds a new goal for T, and change target to `let H : T := ?M in target` in the current goal. -/\n/-- `definev_core H T P`, change target to `let H : T := P in target` if P has type T. -/\n/-- Rotate goals to the left. That is, `rotate_left 1` takes the main goal and puts it to the back of the subgoal list. -/\n/-- Gets a list of metavariables, one for each goal. -/\n/-- Replace the current list of goals with the given one. Each expr in the list should be a metavariable. Any assigned metavariables will be ignored.-/\n/-- How to order the new goals made from an `apply` tactic.\nSupposing we were applying `e : ∀ (a:α) (p : P(a)), Q`\n- `non_dep_first` would produce goals `⊢ P(?m)`, `⊢ α`. It puts the P goal at the front because none of the arguments after `p` in `e` depend on `p`. It doesn't matter what the result `Q` depends on.\n- `non_dep_only` would produce goal `⊢ P(?m)`.\n- `all` would produce goals `⊢ α`, `⊢ P(?m)`.\n-/\ninductive new_goals where\n| non_dep_first : new_goals\n| non_dep_only : new_goals\n| all : new_goals\n\n/-- Configuration options for the `apply` tactic.\n- `md` sets how aggressively definitions are unfolded.\n- `new_goals` is the strategy for ordering new goals.\n- `instances` if `tt`, then `apply` tries to synthesize unresolved `[...]` arguments using type class resolution.\n- `auto_param` if `tt`, then `apply` tries to synthesize unresolved `(h : p . tac_id)` arguments using tactic `tac_id`.\n- `opt_param` if `tt`, then `apply` tries to synthesize unresolved `(a : t := v)` arguments by setting them to `v`.\n- `unify` if `tt`, then `apply` is free to assign existing metavariables in the goal when solving unification constraints.\n For example, in the goal `|- ?x < succ 0`, the tactic `apply succ_lt_succ` succeeds with the default configuration,\n but `apply_with succ_lt_succ {unify := ff}` doesn't since it would require Lean to assign `?x` to `succ ?y` where\n `?y` is a fresh metavariable.\n-/\nstructure apply_cfg where\n md : transparency\n approx : Bool\n new_goals : new_goals\n instances : Bool\n auto_param : Bool\n opt_param : Bool\n unify : Bool\n\n/-- Apply the expression `e` to the main goal, the unification is performed using the transparency mode in `cfg`.\n Supposing `e : Π (a₁:α₁) ... (aₙ:αₙ), P(a₁,...,aₙ)` and the target is `Q`, `apply` will attempt to unify `Q` with `P(?a₁,...?aₙ)`.\n All of the metavariables that are not assigned are added as new metavariables.\n If `cfg.approx` is `tt`, then fallback to first-order unification, and approximate context during unification.\n `cfg.new_goals` specifies which unassigned metavariables become new goals, and their order.\n If `cfg.instances` is `tt`, then use type class resolution to instantiate unassigned meta-variables.\n The fields `cfg.auto_param` and `cfg.opt_param` are ignored by this tactic (See `tactic.apply`).\n It returns a list of all introduced meta variables and the parameter name associated with them, even the assigned ones. -/\n/- Create a fresh meta universe variable. -/\n\n/- Create a fresh meta-variable with the given type.\n The scope of the new meta-variable is the local context of the main goal. -/\n\n/-- Return the value assigned to the given universe meta-variable.\n Fail if argument is not an universe meta-variable or if it is not assigned. -/\n/-- Return the value assigned to the given meta-variable.\n Fail if argument is not a meta-variable or if it is not assigned. -/\n/-- Return true if the given meta-variable is assigned.\n Fail if argument is not a meta-variable. -/\n/-- Make a name that is guaranteed to be unique. Eg `_fresh.1001.4667`. These will be different for each run of the tactic. -/\n/-- Induction on `h` using recursor `rec`, names for the new hypotheses\n are retrieved from `ns`. If `ns` does not have sufficient names, then use the internal binder names\n in the recursor.\n It returns for each new goal the name of the constructor (if `rec_name` is a builtin recursor),\n a list of new hypotheses, and a list of substitutions for hypotheses\n depending on `h`. The substitutions map internal names to their replacement terms. If the\n replacement is again a hypothesis the user name stays the same. The internal names are only valid\n in the original goal, not in the type context of the new goal.\n Remark: if `rec_name` is not a builtin recursor, we use parameter names of `rec_name` instead of\n constructor names.\n\n If `rec` is none, then the type of `h` is inferred, if it is of the form `C ...`, tactic uses `C.rec` -/\n/-- Apply `cases_on` recursor, names for the new hypotheses are retrieved from `ns`.\n `h` must be a local constant. It returns for each new goal the name of the constructor, a list of new hypotheses, and a list of\n substitutions for hypotheses depending on `h`. The number of new goals may be smaller than the\n number of constructors. Some goals may be discarded when the indices to not match.\n See `induction` for information on the list of substitutions.\n\n The `cases` tactic is implemented using this one, and it relaxes the restriction of `h`.\n\n Note: There is one \"new hypothesis\" for every constructor argument. These are\n usually local constants, but due to dependent pattern matching, they can also\n be arbitrary terms. -/\n/-- Similar to cases tactic, but does not revert/intro/clear hypotheses. -/\n/-- Generalizes the target with respect to `e`. -/\n/-- instantiate assigned metavariables in the given expression -/\n/-- Add the given declaration to the environment -/\n/--\nChanges the environment to the `new_env`.\nThe new environment does not need to be a descendant of the old one.\nUse with care.\n-/\n/-- Changes the environment to the `new_env`. `new_env` needs to be a descendant from the current environment. -/\n/-- `doc_string env d k` returns the doc string for `d` (if available) -/\n/-- Set the docstring for the given declaration. -/\n/--\nCreate an auxiliary definition with name `c` where `type` and `value` may contain local constants and\nmeta-variables. This function collects all dependencies (universe parameters, universe metavariables,\nlocal constants (aka hypotheses) and metavariables).\nIt updates the environment in the tactic_state, and returns an expression of the form\n\n (c.{l_1 ... l_n} a_1 ... a_m)\n\nwhere l_i's and a_j's are the collected dependencies.\n-/\n/-- Returns a list of all top-level (`/-! ... -/`) docstrings in the active module and imported ones.\nThe returned object is a list of modules, indexed by `(some filename)` for imported modules\nand `none` for the active one, where each module in the list is paired with a list\nof `(position_in_file, docstring)` pairs. -/\n/-- Returns a list of docstrings in the active module. An entry in the list can be either:\n- a top-level (`/-! ... -/`) docstring, represented as `(none, docstring)`\n- a declaration-specific (`/-- ... -/`) docstring, represented as `(some decl_name, docstring)` -/\n/-- Set attribute `attr_name` for constant `c_name` with the given priority.\n If the priority is none, then use default -/\n/-- `unset_attribute attr_name c_name` -/\n/-- `has_attribute attr_name c_name` succeeds if the declaration `decl_name`\n has the attribute `attr_name`. The result is the priority and whether or not\n the attribute is persistent. -/\n/-- `copy_attribute attr_name c_name p d_name` copy attribute `attr_name` from\n `src` to `tgt` if it is defined for `src`; make it persistent if `p` is `tt`;\n if `p` is `none`, the copied attribute is made persistent iff it is persistent on `src` -/\n/-- Name of the declaration currently being elaborated. -/\n/-- `save_type_info e ref` save (typeof e) at position associated with ref -/\n/-- Return list of currently open namespaces -/\n/-- Return tt iff `t` \"occurs\" in `e`. The occurrence checking is performed using\n keyed matching with the given transparency setting.\n\n We say `t` occurs in `e` by keyed matching iff there is a subterm `s`\n s.t. `t` and `s` have the same head, and `is_def_eq t s md`\n\n The main idea is to minimize the number of `is_def_eq` checks\n performed. -/\n/-- Abstracts all occurrences of the term `t` in `e` using keyed matching.\n If `unify` is `ff`, then matching is used instead of unification.\n That is, metavariables occurring in `e` are not assigned. -/\n/-- Blocks the execution of the current thread for at least `msecs` milliseconds.\n This tactic is used mainly for debugging purposes. -/\n/-- Type check `e` with respect to the current goal.\n Fails if `e` is not type correct. -/\n/-- A `tag` is a list of `names`. These are attached to goals to help tactics track them.-/\ndef tag := List name\n\nend Mathlib", "meta": {"author": "AurelienSaue", "repo": "Mathlib4_auto", "sha": "590df64109b08190abe22358fabc3eae000943f2", "save_path": "github-repos/lean/AurelienSaue-Mathlib4_auto", "path": "github-repos/lean/AurelienSaue-Mathlib4_auto/Mathlib4_auto-590df64109b08190abe22358fabc3eae000943f2/Mathlib/Lean3Lib/init/meta/tactic_auto.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2658804614657029, "lm_q2_score": 0.04208772986809033, "lm_q1q2_score": 0.011190305039371703}} {"text": "/- Copyright 2019 (c) Hans-Dieter Hiep. All rights reserved. Released under MIT license as described in the file LICENSE. -/\n\nimport objects\n\nuniverse u\n\nopen objects list\n\n/- An event is either an asynchronous method call of some caller object to a callee object, its method, and for each parameter an argument value. Or, an event is a method selection. -/\n@[derive decidable_eq]\nstructure callsite (α β : Type) [objects α β] :=\n {c : class_name α}\n (o : {o : β // c = class_of α o})\n (m : method_name c)\n (τ : vallist (param_types m))\ndef callsite.elim {α β : Type} [objects α β] {γ : Sort u}\n (cs : callsite α β) (f : Π{c : class_name α}\n (o : {o : β // c = class_of α o})\n (m : method_name c) (τ : vallist (param_types m)),\n cs = ⟨o,m,τ⟩ → γ) : γ :=\n match cs, rfl : (∀ b, cs = b → γ) with\n | ⟨o,m,τ⟩, h := f o m τ h\n end\n\n@[derive decidable_eq]\ninductive event (α β : Type) [objects α β]\n| call: β → callsite α β → event\n| selection: callsite α β → event\ndef event.to_callsite {α β : Type} [objects α β] :\n event α β → callsite α β\n| (event.call _ c) := c\n| (event.selection c) := c\ndef event.o {α β : Type} [objects α β] (e : event α β) :\n β := e.to_callsite.o\ndef event.c {α β : Type} [objects α β] (e : event α β) :\n class_name α := e.to_callsite.c\ndef event.m {α β : Type} [objects α β] (e : event α β) :\n method_name e.c := e.to_callsite.m\ndef event.τ {α β : Type} [objects α β] (e : event α β) :\n vallist (param_types e.m) := e.to_callsite.τ\ninstance event.event_to_callsite {α β : Type} [objects α β] :\n has_coe (event α β) (callsite α β) := ⟨event.to_callsite⟩\n\n/- A global history is a sequence of events. -/\n@[reducible]\ndef global_history (α β : Type) [objects α β] :=\n list (event α β)\n/- There are two subsequences of a global history. The first consists only of call events with the object as callee (abstracted to its corresponding call site), the second consists only of selection events with the object as callee. -/\ndef event.is_call_to {α β : Type} [objects α β] (x : β) :\n event α β → option (callsite α β)\n| (event.call _ c) := if x = c.o then some c else none\n| _ := none\n/- Call events to an object are of that object. -/\n@[simp]\nlemma event.is_call_to_object {α β : Type} [objects α β]\n {x : β} {e : event α β} {c : callsite α β} :\n event.is_call_to x e = some c → c.o.val = x :=\nbegin\n intro, cases e; simp [event.is_call_to] at a,\n { by_cases (x = e_a_1.o); simp [h] at a,\n simp [coe,lift_t,has_lift_t.lift] at h,\n simp [coe_t,has_coe_t.coe,coe_b,has_coe.coe] at h,\n rewrite h, rewrite ← a, exfalso, assumption },\n { exfalso, assumption }\nend\ndef event.is_selection_of {α β : Type} [objects α β] (x : β) :\n event α β → option (callsite α β)\n| (event.selection c) := if x = c.o then some c else none\n| _ := none\n/- Selection events of an object are of that object. -/\n@[simp]\nlemma event.is_selection_of_object {α β : Type} [objects α β]\n {x : β} {e : event α β} {c : callsite α β} :\n event.is_selection_of x e = some c → c.o.val = x :=\nbegin\n intro, cases e; simp [event.is_selection_of] at a,\n { exfalso, assumption },\n { by_cases (x = e.o); simp [h] at a,\n simp [coe,lift_t,has_lift_t.lift] at h,\n simp [coe_t,has_coe_t.coe,coe_b,has_coe.coe] at h,\n rewrite h, rewrite ← a, exfalso, assumption }\nend\n/- The subsequences are obtained by filtering out events. -/\ndef global_history.calls_to {α β : Type} [objects α β]\n (θ : global_history α β) (x : β) : list (callsite α β) :=\n θ.filter_map (event.is_call_to x)\ndef global_history.selections_of {α β : Type} [objects α β]\n (θ : global_history α β) (x : β) : list (callsite α β) :=\n θ.filter_map (event.is_selection_of x)\nreserve notation `!`:68\nreserve notation `?`:68\ninfix ! := global_history.calls_to\ninfix ? := global_history.selections_of\n/- The list of pending calls to an object is the list of calls to, with the selections removed. -/\ndef global_history.pending_calls_to {α β : Type} [objects α β]\n (θ : global_history α β) (o : β) : list (callsite α β) := \n (θ!o).remove_all (θ?o)\n/- Pending calls have the same object as requested. -/\nlemma global_history.pending_calls_to_object\n {α β : Type} [objects α β] (θ : global_history α β) (o : β) :\n ∀ c : callsite α β,\n c ∈ (global_history.pending_calls_to θ o) → c.o.val = o :=\nbegin\n unfold global_history.pending_calls_to, intro,\n suffices : c ∈ θ!o → c.o.val = o, intro, apply this,\n simp [remove_all] at a, cases a, assumption,\n simp [global_history.calls_to], intro, intro,\n apply event.is_call_to_object\nend\n/- We have an optional first pending call to an object. -/\ndef global_history.sched {α β : Type} [objects α β]\n (θ : global_history α β) (o : β) : option (callsite α β) :=\n head (lift (θ.pending_calls_to o))\n/- Scheduled calls have the same object as requested. -/\nlemma global_history.sched_object {α β : Type} [objects α β]\n (θ : global_history α β) (o : β) (c : callsite α β) :\n (global_history.sched θ o) = some c → c.o.val = o :=\nbegin\n unfold global_history.sched,\n cases H : (global_history.pending_calls_to θ o),\n { intro, exfalso, apply head_lift_nil a },\n { intro, have : hd = c, apply tail_lift_some a,\n apply global_history.pending_calls_to_object θ,\n rewrite H, rewrite this, simp }\nend\ndef global_history.collect {α β : Type} [objects α β]\n (θ : global_history α β) : finset β :=\n to_finset (foldr (λ(e : event α β) l, e.o :: l) [] θ)\n@[reducible]\ndef global_history.fresh {α β : Type} [objects α β]\n (o : β) (θ : global_history α β) : Prop :=\n o ∉ θ.collect\n", "meta": {"author": "praalhans", "repo": "lean-abs", "sha": "5d23eec7234c880f5ebc0d7b831caf55119edef8", "save_path": "github-repos/lean/praalhans-lean-abs", "path": "github-repos/lean/praalhans-lean-abs/lean-abs-5d23eec7234c880f5ebc0d7b831caf55119edef8/src/history.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3702253925955866, "lm_q2_score": 0.0302145893596955, "lm_q1q2_score": 0.011186208207807701}} {"text": "import category_theory.preadditive.basic\nimport category_theory.abelian.projective\nimport tactic.interval_cases\n\n\nnoncomputable theory\n\nopen category_theory\nopen category_theory.limits\n\nuniverse variables v u\n\nnamespace category_theory\n\nvariables {C : Type u} [category.{v} C]\n\nnamespace fin3_functor_mk\n\nvariables (F : fin 3 → C) (a : F 0 ⟶ F 1) (b : F 1 ⟶ F 2)\n\ndef map' : Π (i j : fin 3) (hij : i ≤ j), F i ⟶ F j\n| ⟨0,hi⟩ ⟨0,hj⟩ _ := 𝟙 _\n| ⟨1,hi⟩ ⟨1,hj⟩ _ := 𝟙 _\n| ⟨2,hi⟩ ⟨2,hj⟩ _ := 𝟙 _\n| ⟨0,hi⟩ ⟨1,hj⟩ _ := a\n| ⟨1,hi⟩ ⟨2,hj⟩ _ := b\n| ⟨0,hi⟩ ⟨2,hj⟩ _ := a ≫ b\n| ⟨i+3,hi⟩ _ _ := by { exfalso, revert hi, dec_trivial }\n| _ ⟨j+3,hj⟩ _ := by { exfalso, revert hj, dec_trivial }\n| ⟨i+1,hi⟩ ⟨0,hj⟩ H := by { exfalso, revert H, dec_trivial }\n| ⟨i+2,hi⟩ ⟨1,hj⟩ H := by { exfalso, revert H, dec_trivial }\n.\n\nlemma map'_id : ∀ (i : fin 3), map' F a b i i le_rfl = 𝟙 _\n| ⟨0,hi⟩ := rfl\n| ⟨1,hi⟩ := rfl\n| ⟨2,hi⟩ := rfl\n| ⟨i+3,hi⟩ := by { exfalso, revert hi, dec_trivial }\n\nlemma map'_comp : Π (i j k : fin 3) (hij : i ≤ j) (hjk : j ≤ k),\n map' F a b i j hij ≫ map' F a b j k hjk = map' F a b i k (hij.trans hjk)\n| ⟨0, _⟩ ⟨0, _⟩ k _ _ := category.id_comp _\n| ⟨1, _⟩ ⟨1, _⟩ k _ _ := category.id_comp _\n| i ⟨1, _⟩ ⟨1, _⟩ _ _ := category.comp_id _\n| i ⟨2, _⟩ ⟨2, _⟩ _ _ := category.comp_id _\n| ⟨0, _⟩ ⟨1, _⟩ ⟨2, _⟩ _ _ := rfl\n| ⟨i+3,hi⟩ _ _ _ _ := by { exfalso, revert hi, dec_trivial }\n| _ ⟨j+3,hj⟩ _ _ _ := by { exfalso, revert hj, dec_trivial }\n| _ _ ⟨k+3,hk⟩ _ _ := by { exfalso, revert hk, dec_trivial }\n| ⟨i+1,hi⟩ ⟨0,hj⟩ _ H _ := by { exfalso, revert H, dec_trivial }\n| ⟨i+2,hi⟩ ⟨1,hj⟩ _ H _ := by { exfalso, revert H, dec_trivial }\n| _ ⟨i+1,hi⟩ ⟨0,hj⟩ _ H := by { exfalso, revert H, dec_trivial }\n| _ ⟨i+2,hi⟩ ⟨1,hj⟩ _ H := by { exfalso, revert H, dec_trivial }\n\n\nend fin3_functor_mk\n\ndef fin3_functor_mk (F : fin 3 → C) (a : F 0 ⟶ F 1) (b : F 1 ⟶ F 2) : fin 3 ⥤ C :=\n{ obj := F,\n map := λ i j hij, fin3_functor_mk.map' F a b i j hij.le,\n map_id' := λ i, fin3_functor_mk.map'_id F a b i,\n map_comp' := λ i j k hij hjk, by rw fin3_functor_mk.map'_comp F a b i j k hij.le hjk.le }\n\nnamespace fin4_functor_mk\n\nvariables (F : fin 4 → C) (a : F 0 ⟶ F 1) (b : F 1 ⟶ F 2) (c : F 2 ⟶ F 3)\n\ndef map' : Π (i j : fin 4) (hij : i ≤ j), F i ⟶ F j\n| ⟨0,hi⟩ ⟨0,hj⟩ _ := 𝟙 _\n| ⟨1,hi⟩ ⟨1,hj⟩ _ := 𝟙 _\n| ⟨2,hi⟩ ⟨2,hj⟩ _ := 𝟙 _\n| ⟨3,hi⟩ ⟨3,hj⟩ _ := 𝟙 _\n| ⟨0,hi⟩ ⟨1,hj⟩ _ := a\n| ⟨1,hi⟩ ⟨2,hj⟩ _ := b\n| ⟨2,hi⟩ ⟨3,hj⟩ _ := c\n| ⟨0,hi⟩ ⟨2,hj⟩ _ := a ≫ b\n| ⟨1,hi⟩ ⟨3,hj⟩ _ := b ≫ c\n| ⟨0,hi⟩ ⟨3,hj⟩ _ := a ≫ b ≫ c\n| ⟨i+4,hi⟩ _ _ := by { exfalso, revert hi, dec_trivial }\n| _ ⟨j+4,hj⟩ _ := by { exfalso, revert hj, dec_trivial }\n| ⟨i+1,hi⟩ ⟨0,hj⟩ H := by { exfalso, revert H, dec_trivial }\n| ⟨i+2,hi⟩ ⟨1,hj⟩ H := by { exfalso, revert H, dec_trivial }\n| ⟨3,hi⟩ ⟨2,hj⟩ H := by { exfalso, revert H, dec_trivial }\n.\n\nlemma map'_id : ∀ (i : fin 4), map' F a b c i i le_rfl = 𝟙 _\n| ⟨0,hi⟩ := rfl\n| ⟨1,hi⟩ := rfl\n| ⟨2,hi⟩ := rfl\n| ⟨3,hi⟩ := rfl\n| ⟨i+4,hi⟩ := by { exfalso, revert hi, dec_trivial }\n\nlemma map'_comp : Π (i j k : fin 4) (hij : i ≤ j) (hjk : j ≤ k),\n map' F a b c i j hij ≫ map' F a b c j k hjk = map' F a b c i k (hij.trans hjk)\n| ⟨0, _⟩ ⟨0, _⟩ k _ _ := category.id_comp _\n| ⟨1, _⟩ ⟨1, _⟩ k _ _ := category.id_comp _\n| ⟨2, _⟩ ⟨2, _⟩ k _ _ := category.id_comp _\n| i ⟨1, _⟩ ⟨1, _⟩ _ _ := category.comp_id _\n| i ⟨2, _⟩ ⟨2, _⟩ _ _ := category.comp_id _\n| i ⟨3, _⟩ ⟨3, _⟩ _ _ := category.comp_id _\n| ⟨0, _⟩ ⟨1, _⟩ ⟨2, _⟩ _ _ := rfl\n| ⟨0, _⟩ ⟨1, _⟩ ⟨3, _⟩ _ _ := rfl\n| ⟨0, _⟩ ⟨2, _⟩ ⟨3, _⟩ _ _ := category.assoc a b c\n| ⟨1, _⟩ ⟨2, _⟩ ⟨3, _⟩ _ _ := rfl\n| ⟨i+4,hi⟩ _ _ _ _ := by { exfalso, revert hi, dec_trivial }\n| _ ⟨j+4,hj⟩ _ _ _ := by { exfalso, revert hj, dec_trivial }\n| _ _ ⟨k+4,hk⟩ _ _ := by { exfalso, revert hk, dec_trivial }\n| ⟨i+1,hi⟩ ⟨0,hj⟩ _ H _ := by { exfalso, revert H, dec_trivial }\n| ⟨i+2,hi⟩ ⟨1,hj⟩ _ H _ := by { exfalso, revert H, dec_trivial }\n| ⟨3,hi⟩ ⟨2,hj⟩ _ H _ := by { exfalso, revert H, dec_trivial }\n| _ ⟨i+1,hi⟩ ⟨0,hj⟩ _ H := by { exfalso, revert H, dec_trivial }\n| _ ⟨i+2,hi⟩ ⟨1,hj⟩ _ H := by { exfalso, revert H, dec_trivial }\n| _ ⟨3,hi⟩ ⟨2,hj⟩ _ H := by { exfalso, revert H, dec_trivial }\n\n\nend fin4_functor_mk\n\ndef fin4_functor_mk (F : fin 4 → C) (a : F 0 ⟶ F 1) (b : F 1 ⟶ F 2) (c : F 2 ⟶ F 3) : fin 4 ⥤ C :=\n{ obj := F,\n map := λ i j hij, fin4_functor_mk.map' F a b c i j hij.le,\n map_id' := λ i, fin4_functor_mk.map'_id F a b c i,\n map_comp' := λ i j k hij hjk, by rw fin4_functor_mk.map'_comp F a b c i j k hij.le hjk.le }\n\nend category_theory", "meta": {"author": "jjaassoonn", "repo": "flat", "sha": "bab2f5c18fdee0042680c31b0350c69d241e9a82", "save_path": "github-repos/lean/jjaassoonn-flat", "path": "github-repos/lean/jjaassoonn-flat/flat-bab2f5c18fdee0042680c31b0350c69d241e9a82/src/lte/for_mathlib/fin_functor.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46490157137338844, "lm_q2_score": 0.024053552675798392, "lm_q1q2_score": 0.011182534436091244}} {"text": "import sesh.term\nimport sesh.eval\n\nopen matrix\nopen term\nopen debrujin_idx\n\n\ninductive thread_flag: Type\n| Main: thread_flag\n| Child: thread_flag\n\nnamespace thread_flag\n\ninductive add: thread_flag → thread_flag → thread_flag → Prop\n| CC: add Child Child Child\n| CM: add Child Main Main\n| MC: add Main Child Main\n\nlemma child_add: ∀ {Φ}, add Child Φ Φ\n| Child := add.CC\n| Main := add.CM\n\nlemma add_child: ∀ {Φ}, add Φ Child Φ\n| Child := add.CC\n| Main := add.MC\n\nend thread_flag\nopen thread_flag\n\n/- A tactic that can solve most goals involving thread flags. -/\nmeta def solve_flag: tactic unit :=\n `[ exact add.CC <|> exact add.CM <|> exact add.MC\n <|> assumption <|> exact child_add <|> exact add_child\n <|> tactic.fail \"Failed to solve flags goal.\" ]\n\n/- The type of parallel configurations. Configurations have rules\n for well-formedness (called \"typing\" in the paper). These are\n enforced by the Lean (config) Type. -/\ninductive config: Π {γ}, context γ → thread_flag → Type\n| CNu:\n Π {γ} {Γ: context γ} {Φ: thread_flag} {S: sesh_tp},\n /- Channel names, being treated the same as standard variables,\n are added to the usual typing context. -/\n config (⟦1⬝S♯⟧::Γ) Φ\n --------------------\n→ config Γ Φ\n\n/- Inherently typed config is problematic due to the existence\n of two derivations for a parallel composition. .. but could\n work if (dual S♯) = S♯ -/\n| CComp:\n Π {γ} {Γ₁ Γ₂: context γ} {Φ₁ Φ₂: thread_flag} {S: sesh_tp}\n (Γ: context (S♯::γ))\n (Φ: thread_flag)\n (C: config (⟦1⬝S⟧::Γ₁) Φ₁)\n (D: config (⟦1⬝(sesh_tp.dual S)⟧::Γ₂) Φ₂)\n /- The same auto_param technique is used for the resulting\n context and thread flag. -/\n (_: auto_param (Γ = (⟦1⬝S♯⟧::(Γ₁ + Γ₂))) ``solve_context)\n (_: auto_param (add Φ₁ Φ₂ Φ) ``solve_flag),\n ----------\n config Γ Φ\n\n| CMain:\n Π {γ} {Γ: context γ} {A: tp},\n term Γ A\n -------------\n→ config Γ Main\n\n| CChild:\n Π {γ} {Γ: context γ},\n term Γ End!\n --------------\n→ config Γ Child\nopen config\n\nnotation `●`C:90 := CMain C\nnotation `○`C:90 := CChild C\n\n/- thread evaluation contexts -/\n@[reducible]\ndef thread_ctx_fn {γ} (Γₑ: context γ) (A': tp) (Φ: thread_flag) :=\n Π (Γ: context γ), term Γ A' → config (Γ + Γₑ) Φ\n\nnamespace thread_ctx_fn\n\n@[reducible]\ndef apply {γ} {Γₑ Γ': context γ} {A': tp} {Φ: thread_flag}\n (f: thread_ctx_fn Γₑ A' Φ)\n (Γ: context γ)\n (M: term Γ' A')\n (h: auto_param (Γ = Γ'+Γₑ) ``solve_context)\n : config Γ Φ :=\ncast (by solve_context) $ f Γ' M\n\nend thread_ctx_fn\n\ninductive thread_ctx\n : Π {γ} {A': tp} {Φ: thread_flag} (Γₑ: context γ),\n thread_ctx_fn Γₑ A' Φ → Type\n| FMain:\n ∀ {γ} {Γₑ: context γ} {A' A: tp}\n (E: eval_ctx' Γₑ A' A),\n --------------------------------------\n thread_ctx Γₑ (λ Γ M, ●(E.f Γ M))\n\n| FChild:\n ∀ {γ} {Γₑ: context γ} {A': tp}\n (E: eval_ctx' Γₑ A' End!),\n --------------------------------------\n thread_ctx Γₑ (λ Γ M, ○(E.f Γ M))\n\nnamespace thread_ctx\n\ndef ext:\n Π {γ δ: precontext} {Γ: context γ} {A': tp} {Φ: thread_flag}\n {F: thread_ctx_fn Γ A' Φ}\n (ρ: ren_fn γ δ),\n thread_ctx Γ F\n→ let Γ' := (Γ ⊛ (λ B x, identity δ B $ ρ B x)) in\n Σ F': thread_ctx_fn Γ' A' Φ,\n thread_ctx Γ' F'\n| _ _ _ _ _ _ ρ (FMain E) := ⟨_, FMain $ eval_ctx'.ext ρ E⟩\n| _ _ _ _ _ _ ρ (FChild E) := ⟨_, FChild $ eval_ctx'.ext ρ E⟩\n\nend thread_ctx\n\nstructure thread_ctx' {γ} (Γₑ: context γ) (A': tp) (Φ: thread_flag) :=\n(f: thread_ctx_fn Γₑ A' Φ)\n(h: thread_ctx Γₑ f)\n\nnamespace thread_ctx'\n\ndef ext {γ δ: precontext} {Γ: context γ} {A': tp} {Φ: thread_flag}\n (ρ: ren_fn γ δ)\n (F: thread_ctx' Γ A' Φ)\n : thread_ctx' (Γ ⊛ (λ B x, identity δ B $ ρ B x)) A' Φ\n:= ⟨_, (thread_ctx.ext ρ F.h).snd⟩\n\nend thread_ctx'\n\ninductive context_reduces: ∀ {γ γ'}, context γ → context γ' → Prop\n| ΓId:\n ∀ {γ} {Γ: context γ},\n context_reduces Γ Γ\n\n| ΓSend:\n ∀ {γ} {Γ: context γ} {π: mult}\n {A: tp} {S: sesh_tp},\n context_reduces (⟦π⬝(!A⬝S)♯⟧::Γ) (⟦π⬝S♯⟧::Γ)\n\n| ΓRecv:\n ∀ {γ} {Γ: context γ} {π: mult}\n {A: tp} {S: sesh_tp},\n context_reduces (⟦π⬝(?A⬝S)♯⟧::Γ) (⟦π⬝S♯⟧::Γ)\n\n/- An experimental rule to allow self-duality of channel types.\n Never actually used. -/\n| ΓHash:\n ∀ {γ} {Γ: context γ} {π: mult} {S: sesh_tp},\n context_reduces (⟦π⬝S♯⟧::Γ) (⟦π⬝(sesh_tp.dual S)♯⟧::Γ)\nopen context_reduces\n\ninductive config_reduces\n : ∀ {γ γ'} {Γ: context γ} {Γ': context γ'} {Φ},\n context_reduces Γ Γ' → config Γ Φ → config Γ' Φ → Prop\nnotation C` -`h`⟶C `C':55 := config_reduces h C C'\n| CEvalNu:\n ∀ {γ} {Γ: context γ} {S: sesh_tp} {Φ: thread_flag}\n {C C': config (⟦1⬝S♯⟧::Γ) Φ},\n C -ΓId⟶C C'\n ---------------------\n→ ((CNu C) -ΓId⟶C (CNu C'))\n\n/- TODO the right version results from commutativity.. somehow -/\n| CEvalComp:\n ∀ {γ} {Γ₁ Γ₂: context γ} {S: sesh_tp} {Φ₁ Φ₂: thread_flag}\n {C C': config (⟦1⬝S⟧::Γ₁) Φ₁}\n (Γ: context $ S♯::γ)\n (hΓ: Γ = ⟦1⬝S♯⟧::(Γ₁ + Γ₂))\n (Φ: thread_flag)\n (hΦ: add Φ₁ Φ₂ Φ)\n (D: config (⟦1⬝sesh_tp.dual S⟧::Γ₂) Φ₂),\n C -ΓId⟶C C'\n ----------------------------------------------------------\n→ ((CComp Γ Φ C D) -ΓId⟶C (CComp Γ Φ C' D))\n\n| CEvalChild:\n ∀ {γ} {Γ: context γ}\n {M M': term Γ End!},\n M ⟶M M'\n -------------------------------\n→ (○M -ΓId⟶C ○M)\n\n| CEvalMain:\n ∀ {γ} {Γ: context γ} {A: tp}\n {M M': term Γ A},\n M ⟶M M'\n --------------------------------\n→ (●M -ΓId⟶C ●M')\n\n| CEvalFork:\n ∀ {γ} {Γₑ: context γ} {S: sesh_tp} {Φ}\n (F: thread_ctx' Γₑ (sesh_tp.dual S) Φ)\n (M: term (⟦1⬝S⟧::(0: context γ)) End!),\n ---------------------------------------\n ((F.f.apply Γₑ $ Fork $ Abs M)\n -ΓId⟶C\n (CNu\n $ CComp (⟦1⬝S♯⟧::Γₑ) Φ\n (CChild M)\n $ (F.ext $ ren_fn.lift_once $ sesh_tp.dual S).f.apply\n (⟦1⬝sesh_tp.dual S⟧::Γₑ)\n (Var\n (⟦1⬝sesh_tp.dual S⟧::0)\n $ ZVar _ $ sesh_tp.dual S)\n $ by solve_context))\n\n| CEvalComm:\n ∀ {γ} {Γv: context γ} {A: tp} {S: sesh_tp}\n {Φ₁ Φ₂: thread_flag}\n (V: term Γv A)\n (hV: value V)\n (Φ: thread_flag)\n (hΦ: add Φ₁ Φ₂ Φ)\n (F: thread_ctx' (0: context γ) S Φ₁)\n (F': thread_ctx' (0: context γ) (tp.prod A $ sesh_tp.dual S) Φ₂),\n -----------------------------------------------------------------\n ((CComp (⟦1⬝(!A⬝S)♯⟧::Γv) Φ\n ((F.ext $ ren_fn.lift_once $ !A⬝S).f.apply\n (⟦1⬝!A⬝S⟧::Γv)\n (Send\n (⟦1⬝(!A⬝S)⟧::Γv)\n (term.rename (ren_fn.lift_once $ !A⬝S) _ V)\n (Var\n (⟦1⬝(!A⬝S)⟧::0)\n $ ZVar γ $ !A⬝S)\n $ by solve_context)\n $ by solve_context)\n $ (F'.ext $ ren_fn.lift_once $ sesh_tp.dual $ !A⬝S).f.apply\n (⟦1⬝sesh_tp.dual (!A⬝S)⟧::0)\n (Recv $\n Var\n (⟦1⬝sesh_tp.dual (!A⬝S)⟧::0)\n (begin convert\n (ZVar γ $ sesh_tp.dual $ !A⬝S),\n rw [sesh_tp.dual],\n end)\n $ begin\n have h: ?A⬝sesh_tp.dual S = sesh_tp.dual (!A⬝S),\n unfold sesh_tp.dual,\n sorry\n end))\n -ΓSend⟶C\n (CComp (⟦1⬝S♯⟧::Γv) Φ\n ((F.ext $ ren_fn.lift_once S).f.apply\n (⟦1⬝S⟧::0)\n (Var\n (⟦1⬝S⟧::0)\n (ZVar γ S))\n $ by solve_context) -- now all the context used by V in thread 1 is being used by V\n -- in thread 2. So the evaluation context must've _not_ used anything\n -- really and must've been extended with the _entire_ context of V\n $ (F'.ext $ ren_fn.lift_once $ sesh_tp.dual S).f.apply\n (⟦1⬝sesh_tp.dual S⟧::Γv)\n $ Pair\n (⟦1⬝sesh_tp.dual S⟧::Γv)\n (term.rename (ren_fn.lift_once $ sesh_tp.dual S) _ V)\n (Var\n (⟦1⬝sesh_tp.dual S⟧::0)\n $ ZVar γ $ sesh_tp.dual S)\n $ by solve_context))\n\n| CEvalWait:\n ∀ {γ} {Φ}\n (F: thread_ctx' (0: context γ) tp.unit Φ),\n ------------------------------------------\n ((CNu\n $ CComp (⟦1⬝End?♯⟧::0) Φ\n ((F.ext $ ren_fn.lift_once $ End?).f.apply\n (⟦1⬝End?⟧::0)\n (Wait\n $ Var\n (⟦1⬝End?⟧::0)\n $ ZVar γ End?)\n $ by solve_context)\n $ CChild\n $ Var (⟦1⬝End!⟧::0)\n (ZVar γ $ sesh_tp.dual End?)\n $ begin\n show ⟦1⬝End!⟧::0 = identity (End!::γ) End! (ZVar γ End!),\n simp with unfold_,\n end)\n -ΓId⟶C\n (F.f.apply (0: context γ) $ Unit 0))\n", "meta": {"author": "Vtec234", "repo": "lean-sesh", "sha": "d11d7bb0599406e27d3a4d26242aec13d639ecf7", "save_path": "github-repos/lean/Vtec234-lean-sesh", "path": "github-repos/lean/Vtec234-lean-sesh/lean-sesh-d11d7bb0599406e27d3a4d26242aec13d639ecf7/src/sesh/config.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.45713670203584295, "lm_q2_score": 0.024423089432780133, "lm_q1q2_score": 0.011164690556827556}} {"text": "/-\nCopyright (c) 2016 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Leonardo de Moura\n\n! This file was ported from Lean 3 source module init.meta.decl_cmds\n! leanprover-community/mathlib commit b40f3af8018f0cc5811d5f56e4f9888877009b4f\n! Please do not edit these lines, except to modify the commit id\n! if you have ported upstream changes.\n-/\nprelude\nimport Leanbin.Init.Meta.Tactic\nimport Leanbin.Init.Meta.RbMap\n\nopen Tactic\n\nopen Native\n\nprivate unsafe def apply_replacement (replacements : name_map Name) (e : expr) : expr :=\n e.replace fun e d =>\n match e with\n | expr.const n ls =>\n match replacements.find n with\n | some new_n => some (expr.const new_n ls)\n | none => none\n | _ => none\n#align apply_replacement apply_replacement\n\n/--\nGiven a set of constant renamings `replacements` and a declaration name `src_decl_name`, create a new\n declaration called `new_decl_name` s.t. its type is the type of `src_decl_name` after applying the\n given constant replacement.\n\n Remark: the new type must be definitionally equal to the type of `src_decl_name`.\n\n Example:\n Assume the environment contains\n def f : nat -> nat := ...\n def g : nat -> nat := f\n lemma f_lemma : forall a, f a > 0 := ...\n\n Moreover, assume we have a mapping M containing `f -> `g\n Then, the command\n run_command copy_decl_updating_type M `f_lemma `g_lemma\n creates the declaration\n lemma g_lemma : forall a, g a > 0 := ... -/\nunsafe def copy_decl_updating_type (replacements : name_map Name) (src_decl_name : Name)\n (new_decl_name : Name) : Tactic := do\n let env ← get_env\n let decl ← env.get src_decl_name\n let decl := decl.update_name <| new_decl_name\n let decl := decl.update_type <| apply_replacement replacements decl.type\n let decl := decl.update_value <| expr.const src_decl_name (decl.univ_params.map level.param)\n add_decl decl\n#align copy_decl_updating_type copy_decl_updating_type\n\nunsafe def copy_decl_using (replacements : name_map Name) (src_decl_name : Name)\n (new_decl_name : Name) : Tactic := do\n let env ← get_env\n let decl ← env.get src_decl_name\n let decl := decl.update_name <| new_decl_name\n let decl := decl.update_type <| apply_replacement replacements decl.type\n let decl := decl.map_value <| apply_replacement replacements\n add_decl decl\n#align copy_decl_using copy_decl_using\n\n", "meta": {"author": "leanprover-community", "repo": "lean3port", "sha": "9ed1898f23e4379865ee93d62cb6353e5ed6c270", "save_path": "github-repos/lean/leanprover-community-lean3port", "path": "github-repos/lean/leanprover-community-lean3port/lean3port-9ed1898f23e4379865ee93d62cb6353e5ed6c270/Leanbin/Init/Meta/DeclCmds.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2942149597859341, "lm_q2_score": 0.037892425543116344, "lm_q1q2_score": 0.011148518457359476}} {"text": "/-\nFile: signature_recover_public_key_fast_ec_add_soundness.lean\n\nAutogenerated file.\n-/\nimport starkware.cairo.lean.semantics.soundness.hoare\nimport .signature_recover_public_key_code\nimport ..signature_recover_public_key_spec\nimport .signature_recover_public_key_unreduced_sqr_soundness\nimport .signature_recover_public_key_compute_slope_soundness\nopen tactic\n\nopen starkware.cairo.common.cairo_secp.ec\nopen starkware.cairo.common.cairo_secp.bigint\nopen starkware.cairo.common.cairo_secp.field\n\nvariables {F : Type} [field F] [decidable_eq F] [prelude_hyps F]\nvariable mem : F → F\nvariable σ : register_state F\n\n/- starkware.cairo.common.cairo_secp.ec.fast_ec_add autogenerated soundness theorem -/\n\ntheorem auto_sound_fast_ec_add_block9\n -- An independent ap variable.\n (ap : F)\n -- arguments\n (range_check_ptr : F) (point0 point1 : EcPoint F)\n -- code is in memory at σ.pc\n (h_mem : mem_at mem code_fast_ec_add σ.pc)\n -- all dependencies are in memory\n (h_mem_4 : mem_at mem code_nondet_bigint3 (σ.pc - 317))\n (h_mem_5 : mem_at mem code_unreduced_mul (σ.pc - 305))\n (h_mem_6 : mem_at mem code_unreduced_sqr (σ.pc - 285))\n (h_mem_7 : mem_at mem code_verify_zero (σ.pc - 269))\n (h_mem_13 : mem_at mem code_compute_slope (σ.pc - 97))\n -- input arguments on the stack\n (hin_range_check_ptr : range_check_ptr = mem (σ.fp - 15))\n (hin_point0 : point0 = cast_EcPoint mem (σ.fp - 14))\n (hin_point1 : point1 = cast_EcPoint mem (σ.fp - 8))\n (νbound : ℕ)\n -- conclusion\n : ensuresb_ret νbound mem\n {pc := σ.pc + 28, ap := ap, fp := σ.fp}\n (λ κ τ,\n ∃ μ ≤ κ, rc_ensures mem (rc_bound F) μ (mem (σ.fp - 15)) (mem $ τ.ap - 7)\n (auto_spec_fast_ec_add_block9 mem κ range_check_ptr point0 point1 (mem (τ.ap - 7)) (cast_EcPoint mem (τ.ap - 6)))) :=\nbegin\n have h_mem_rec := h_mem,\n unpack_memory code_fast_ec_add at h_mem with ⟨hpc0, hpc1, hpc2, hpc3, hpc4, hpc5, hpc6, hpc7, hpc8, hpc9, hpc10, hpc11, hpc12, hpc13, hpc14, hpc15, hpc16, hpc17, hpc18, hpc19, hpc20, hpc21, hpc22, hpc23, hpc24, hpc25, hpc26, hpc27, hpc28, hpc29, hpc30, hpc31, hpc32, hpc33, hpc34, hpc35, hpc36, hpc37, hpc38, hpc39, hpc40, hpc41, hpc42, hpc43, hpc44, hpc45, hpc46, hpc47, hpc48, hpc49, hpc50, hpc51, hpc52, hpc53, hpc54, hpc55, hpc56, hpc57, hpc58, hpc59, hpc60, hpc61, hpc62, hpc63, hpc64, hpc65, hpc66, hpc67, hpc68, hpc69, hpc70, hpc71, hpc72, hpc73, hpc74, hpc75, hpc76, hpc77, hpc78, hpc79, hpc80, hpc81, hpc82, hpc83, hpc84, hpc85, hpc86⟩,\n -- function call\n step_assert_eq hpc28 with arg0,\n step_assert_eq hpc29 with arg1,\n step_assert_eq hpc30 with arg2,\n step_assert_eq hpc31 with arg3,\n step_assert_eq hpc32 with arg4,\n step_assert_eq hpc33 with arg5,\n step_assert_eq hpc34 with arg6,\n step_assert_eq hpc35 with arg7,\n step_assert_eq hpc36 with arg8,\n step_assert_eq hpc37 with arg9,\n step_assert_eq hpc38 with arg10,\n step_assert_eq hpc39 with arg11,\n step_assert_eq hpc40 with arg12,\n step_sub hpc41 (auto_sound_compute_slope mem _ range_check_ptr point0 point1 _ _ _ _ _ _ _),\n { rw hpc42, norm_num2, exact h_mem_13 },\n { rw hpc42, norm_num2, exact h_mem_4 },\n { rw hpc42, norm_num2, exact h_mem_5 },\n { rw hpc42, norm_num2, exact h_mem_7 },\n { try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point0, hin_point1] },\n try { dsimp [cast_EcPoint, cast_BigInt3] },\n try { arith_simps }, try { simp only [arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } }, },\n { try { ext } ; {\n try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point0, hin_point1] },\n try { dsimp [cast_EcPoint, cast_BigInt3] },\n try { arith_simps }, try { simp only [arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },}, },\n { try { ext } ; {\n try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point0, hin_point1] },\n try { dsimp [cast_EcPoint, cast_BigInt3] },\n try { arith_simps }, try { simp only [arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },}, },\n intros κ_call43 ap43 h_call43,\n rcases h_call43 with ⟨h_call43_ap_offset, h_call43⟩,\n rcases h_call43 with ⟨rc_m43, rc_mle43, hl_range_check_ptr₁, h_call43⟩,\n generalize' hr_rev_range_check_ptr₁: mem (ap43 - 4) = range_check_ptr₁,\n have htv_range_check_ptr₁ := hr_rev_range_check_ptr₁.symm, clear hr_rev_range_check_ptr₁,\n generalize' hr_rev_slope: cast_BigInt3 mem (ap43 - 3) = slope,\n simp only [hr_rev_slope] at h_call43,\n have htv_slope := hr_rev_slope.symm, clear hr_rev_slope,\n try { simp only [arg0 ,arg1 ,arg2 ,arg3 ,arg4 ,arg5 ,arg6 ,arg7 ,arg8 ,arg9 ,arg10 ,arg11 ,arg12] at hl_range_check_ptr₁ },\n rw [←htv_range_check_ptr₁, ←hin_range_check_ptr] at hl_range_check_ptr₁,\n try { simp only [arg0 ,arg1 ,arg2 ,arg3 ,arg4 ,arg5 ,arg6 ,arg7 ,arg8 ,arg9 ,arg10 ,arg11 ,arg12] at h_call43 },\n rw [hin_range_check_ptr] at h_call43,\n clear arg0 arg1 arg2 arg3 arg4 arg5 arg6 arg7 arg8 arg9 arg10 arg11 arg12,\n -- function call\n step_sub hpc43 (auto_sound_unreduced_sqr mem _ slope _ _),\n { rw hpc44, norm_num2, exact h_mem_6 },\n { try { ext } ; {\n try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point0, hin_point1, htv_range_check_ptr₁, htv_slope] },\n try { dsimp [cast_EcPoint, cast_BigInt3] },\n try { simp only [h_call43_ap_offset] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },}, },\n intros κ_call45 ap45 h_call45,\n rcases h_call45 with ⟨h_call45_ap_offset, h_call45⟩,\n generalize' hr_rev_slope_sqr: cast_UnreducedBigInt3 mem (ap45 - 3) = slope_sqr,\n simp only [hr_rev_slope_sqr] at h_call45,\n have htv_slope_sqr := hr_rev_slope_sqr.symm, clear hr_rev_slope_sqr,\n clear ,\n -- function call\n step_assert_eq hpc45 with arg0,\n step_sub hpc46 (auto_sound_nondet_bigint3 mem _ range_check_ptr₁ _ _),\n { rw hpc47, norm_num2, exact h_mem_4 },\n { try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point0, hin_point1, htv_range_check_ptr₁, htv_slope, htv_slope_sqr] },\n try { dsimp [cast_EcPoint, cast_BigInt3, cast_UnreducedBigInt3] },\n try { arith_simps }, try { simp only [arg0] },\n try { simp only [h_call43_ap_offset, h_call45_ap_offset] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } }, },\n intros κ_call48 ap48 h_call48,\n rcases h_call48 with ⟨h_call48_ap_offset, h_call48⟩,\n rcases h_call48 with ⟨rc_m48, rc_mle48, hl_range_check_ptr₂, h_call48⟩,\n generalize' hr_rev_range_check_ptr₂: mem (ap48 - 4) = range_check_ptr₂,\n have htv_range_check_ptr₂ := hr_rev_range_check_ptr₂.symm, clear hr_rev_range_check_ptr₂,\n generalize' hr_rev_new_x: cast_BigInt3 mem (ap48 - 3) = new_x,\n simp only [hr_rev_new_x] at h_call48,\n have htv_new_x := hr_rev_new_x.symm, clear hr_rev_new_x,\n try { simp only [arg0] at hl_range_check_ptr₂ },\n try { rw [h_call45_ap_offset] at hl_range_check_ptr₂ }, try { arith_simps at hl_range_check_ptr₂ },\n rw [←htv_range_check_ptr₂, ←htv_range_check_ptr₁] at hl_range_check_ptr₂,\n try { simp only [arg0] at h_call48 },\n try { rw [h_call45_ap_offset] at h_call48 }, try { arith_simps at h_call48 },\n rw [←htv_range_check_ptr₁, hl_range_check_ptr₁, hin_range_check_ptr] at h_call48,\n clear arg0,\n -- function call\n step_assert_eq hpc48 with arg0,\n step_sub hpc49 (auto_sound_nondet_bigint3 mem _ range_check_ptr₂ _ _),\n { rw hpc50, norm_num2, exact h_mem_4 },\n { try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point0, hin_point1, htv_range_check_ptr₁, htv_slope, htv_slope_sqr, htv_range_check_ptr₂, htv_new_x] },\n try { dsimp [cast_EcPoint, cast_BigInt3, cast_UnreducedBigInt3] },\n try { arith_simps }, try { simp only [arg0] },\n try { simp only [h_call43_ap_offset, h_call45_ap_offset, h_call48_ap_offset] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } }, },\n intros κ_call51 ap51 h_call51,\n rcases h_call51 with ⟨h_call51_ap_offset, h_call51⟩,\n rcases h_call51 with ⟨rc_m51, rc_mle51, hl_range_check_ptr₃, h_call51⟩,\n generalize' hr_rev_range_check_ptr₃: mem (ap51 - 4) = range_check_ptr₃,\n have htv_range_check_ptr₃ := hr_rev_range_check_ptr₃.symm, clear hr_rev_range_check_ptr₃,\n generalize' hr_rev_new_y: cast_BigInt3 mem (ap51 - 3) = new_y,\n simp only [hr_rev_new_y] at h_call51,\n have htv_new_y := hr_rev_new_y.symm, clear hr_rev_new_y,\n try { simp only [arg0] at hl_range_check_ptr₃ },\n rw [←htv_range_check_ptr₃, ←htv_range_check_ptr₂] at hl_range_check_ptr₃,\n try { simp only [arg0] at h_call51 },\n rw [←htv_range_check_ptr₂, hl_range_check_ptr₂, hl_range_check_ptr₁, hin_range_check_ptr] at h_call51,\n clear arg0,\n -- function call\n step_assert_eq hpc51 with arg0,\n step_assert_eq hpc52 with arg1,\n step_assert_eq hpc53 with arg2,\n step_assert_eq hpc54 with arg3,\n step_assert_eq hpc55 with arg4,\n step_assert_eq hpc56 with arg5,\n step_assert_eq hpc57 with arg6,\n step_assert_eq hpc58 with arg7,\n step_assert_eq hpc59 with arg8,\n step_assert_eq hpc60 with arg9,\n step_sub hpc61 (auto_sound_verify_zero mem _ range_check_ptr₃ {\n d0 := slope_sqr.d0 - new_x.d0 - point0.x.d0 - point1.x.d0,\n d1 := slope_sqr.d1 - new_x.d1 - point0.x.d1 - point1.x.d1,\n d2 := slope_sqr.d2 - new_x.d2 - point0.x.d2 - point1.x.d2\n } _ _ _),\n { rw hpc62, norm_num2, exact h_mem_7 },\n { try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point0, hin_point1, htv_range_check_ptr₁, htv_slope, htv_slope_sqr, htv_range_check_ptr₂, htv_new_x, htv_range_check_ptr₃, htv_new_y] },\n try { dsimp [cast_EcPoint, cast_BigInt3, cast_UnreducedBigInt3] },\n try { arith_simps }, try { simp only [(eq_sub_of_eq_add arg0), (eq_sub_of_eq_add arg1), (eq_sub_of_eq_add arg2), (eq_sub_of_eq_add arg3), (eq_sub_of_eq_add arg4), (eq_sub_of_eq_add arg5), arg6, (eq_sub_of_eq_add arg7), (eq_sub_of_eq_add arg8), (eq_sub_of_eq_add arg9)] },\n try { simp only [h_call43_ap_offset, h_call45_ap_offset, h_call48_ap_offset, h_call51_ap_offset] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } }, },\n { try { ext } ; {\n try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point0, hin_point1, htv_range_check_ptr₁, htv_slope, htv_slope_sqr, htv_range_check_ptr₂, htv_new_x, htv_range_check_ptr₃, htv_new_y] },\n try { dsimp [cast_EcPoint, cast_BigInt3, cast_UnreducedBigInt3] },\n try { arith_simps }, try { simp only [(eq_sub_of_eq_add arg0), (eq_sub_of_eq_add arg1), (eq_sub_of_eq_add arg2), (eq_sub_of_eq_add arg3), (eq_sub_of_eq_add arg4), (eq_sub_of_eq_add arg5), arg6, (eq_sub_of_eq_add arg7), (eq_sub_of_eq_add arg8), (eq_sub_of_eq_add arg9)] },\n try { simp only [h_call43_ap_offset, h_call45_ap_offset, h_call48_ap_offset, h_call51_ap_offset] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },}, },\n intros κ_call63 ap63 h_call63,\n rcases h_call63 with ⟨h_call63_ap_offset, h_call63⟩,\n rcases h_call63 with ⟨rc_m63, rc_mle63, hl_range_check_ptr₄, h_call63⟩,\n generalize' hr_rev_range_check_ptr₄: mem (ap63 - 1) = range_check_ptr₄,\n have htv_range_check_ptr₄ := hr_rev_range_check_ptr₄.symm, clear hr_rev_range_check_ptr₄,\n try { simp only [arg0 ,arg1 ,arg2 ,arg3 ,arg4 ,arg5 ,arg6 ,arg7 ,arg8 ,arg9] at hl_range_check_ptr₄ },\n rw [←htv_range_check_ptr₄, ←htv_range_check_ptr₃] at hl_range_check_ptr₄,\n try { simp only [arg0 ,arg1 ,arg2 ,arg3 ,arg4 ,arg5 ,arg6 ,arg7 ,arg8 ,arg9] at h_call63 },\n rw [←htv_range_check_ptr₃, hl_range_check_ptr₃, hl_range_check_ptr₂, hl_range_check_ptr₁, hin_range_check_ptr] at h_call63,\n clear arg0 arg1 arg2 arg3 arg4 arg5 arg6 arg7 arg8 arg9,\n -- function call\n step_assert_eq hpc63 with arg0,\n step_assert_eq hpc64 with arg1,\n step_assert_eq hpc65 with arg2,\n step_assert_eq hpc66 with arg3,\n step_assert_eq hpc67 with arg4,\n step_assert_eq hpc68 with arg5,\n step_sub hpc69 (auto_sound_unreduced_mul mem _ {\n d0 := point0.x.d0 - new_x.d0,\n d1 := point0.x.d1 - new_x.d1,\n d2 := point0.x.d2 - new_x.d2\n } slope _ _ _),\n { rw hpc70, norm_num2, exact h_mem_5 },\n { try { ext } ; {\n try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point0, hin_point1, htv_range_check_ptr₁, htv_slope, htv_slope_sqr, htv_range_check_ptr₂, htv_new_x, htv_range_check_ptr₃, htv_new_y, htv_range_check_ptr₄] },\n try { dsimp [cast_EcPoint, cast_BigInt3, cast_UnreducedBigInt3] },\n try { arith_simps }, try { simp only [(eq_sub_of_eq_add arg0), (eq_sub_of_eq_add arg1), (eq_sub_of_eq_add arg2), arg3, arg4, arg5] },\n try { simp only [h_call43_ap_offset, h_call45_ap_offset, h_call48_ap_offset, h_call51_ap_offset, h_call63_ap_offset] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },}, },\n { try { ext } ; {\n try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point0, hin_point1, htv_range_check_ptr₁, htv_slope, htv_slope_sqr, htv_range_check_ptr₂, htv_new_x, htv_range_check_ptr₃, htv_new_y, htv_range_check_ptr₄] },\n try { dsimp [cast_EcPoint, cast_BigInt3, cast_UnreducedBigInt3] },\n try { arith_simps }, try { simp only [(eq_sub_of_eq_add arg0), (eq_sub_of_eq_add arg1), (eq_sub_of_eq_add arg2), arg3, arg4, arg5] },\n try { simp only [h_call43_ap_offset, h_call45_ap_offset, h_call48_ap_offset, h_call51_ap_offset, h_call63_ap_offset] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },}, },\n intros κ_call71 ap71 h_call71,\n rcases h_call71 with ⟨h_call71_ap_offset, h_call71⟩,\n generalize' hr_rev_x_diff_slope: cast_UnreducedBigInt3 mem (ap71 - 3) = x_diff_slope,\n simp only [hr_rev_x_diff_slope] at h_call71,\n have htv_x_diff_slope := hr_rev_x_diff_slope.symm, clear hr_rev_x_diff_slope,\n clear arg0 arg1 arg2 arg3 arg4 arg5,\n -- function call\n step_assert_eq hpc71 with arg0,\n step_assert_eq hpc72 with arg1,\n step_assert_eq hpc73 with arg2,\n step_assert_eq hpc74 with arg3,\n step_assert_eq hpc75 with arg4,\n step_assert_eq hpc76 with arg5,\n step_assert_eq hpc77 with arg6,\n step_sub hpc78 (auto_sound_verify_zero mem _ range_check_ptr₄ {\n d0 := x_diff_slope.d0 - point0.y.d0 - new_y.d0,\n d1 := x_diff_slope.d1 - point0.y.d1 - new_y.d1,\n d2 := x_diff_slope.d2 - point0.y.d2 - new_y.d2\n } _ _ _),\n { rw hpc79, norm_num2, exact h_mem_7 },\n { try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point0, hin_point1, htv_range_check_ptr₁, htv_slope, htv_slope_sqr, htv_range_check_ptr₂, htv_new_x, htv_range_check_ptr₃, htv_new_y, htv_range_check_ptr₄, htv_x_diff_slope] },\n try { dsimp [cast_EcPoint, cast_BigInt3, cast_UnreducedBigInt3] },\n try { arith_simps }, try { simp only [(eq_sub_of_eq_add arg0), (eq_sub_of_eq_add arg1), (eq_sub_of_eq_add arg2), arg3, (eq_sub_of_eq_add arg4), (eq_sub_of_eq_add arg5), (eq_sub_of_eq_add arg6)] },\n try { simp only [h_call43_ap_offset, h_call45_ap_offset, h_call48_ap_offset, h_call51_ap_offset, h_call63_ap_offset, h_call71_ap_offset] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } }, },\n { try { ext } ; {\n try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point0, hin_point1, htv_range_check_ptr₁, htv_slope, htv_slope_sqr, htv_range_check_ptr₂, htv_new_x, htv_range_check_ptr₃, htv_new_y, htv_range_check_ptr₄, htv_x_diff_slope] },\n try { dsimp [cast_EcPoint, cast_BigInt3, cast_UnreducedBigInt3] },\n try { arith_simps }, try { simp only [(eq_sub_of_eq_add arg0), (eq_sub_of_eq_add arg1), (eq_sub_of_eq_add arg2), arg3, (eq_sub_of_eq_add arg4), (eq_sub_of_eq_add arg5), (eq_sub_of_eq_add arg6)] },\n try { simp only [h_call43_ap_offset, h_call45_ap_offset, h_call48_ap_offset, h_call51_ap_offset, h_call63_ap_offset, h_call71_ap_offset] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },}, },\n intros κ_call80 ap80 h_call80,\n rcases h_call80 with ⟨h_call80_ap_offset, h_call80⟩,\n rcases h_call80 with ⟨rc_m80, rc_mle80, hl_range_check_ptr₅, h_call80⟩,\n generalize' hr_rev_range_check_ptr₅: mem (ap80 - 1) = range_check_ptr₅,\n have htv_range_check_ptr₅ := hr_rev_range_check_ptr₅.symm, clear hr_rev_range_check_ptr₅,\n try { simp only [arg0 ,arg1 ,arg2 ,arg3 ,arg4 ,arg5 ,arg6] at hl_range_check_ptr₅ },\n try { rw [h_call71_ap_offset] at hl_range_check_ptr₅ }, try { arith_simps at hl_range_check_ptr₅ },\n rw [←htv_range_check_ptr₅, ←htv_range_check_ptr₄] at hl_range_check_ptr₅,\n try { simp only [arg0 ,arg1 ,arg2 ,arg3 ,arg4 ,arg5 ,arg6] at h_call80 },\n try { rw [h_call71_ap_offset] at h_call80 }, try { arith_simps at h_call80 },\n rw [←htv_range_check_ptr₄, hl_range_check_ptr₄, hl_range_check_ptr₃, hl_range_check_ptr₂, hl_range_check_ptr₁, hin_range_check_ptr] at h_call80,\n clear arg0 arg1 arg2 arg3 arg4 arg5 arg6,\n -- return\n step_assert_eq hpc80 with hret0,\n step_assert_eq hpc81 with hret1,\n step_assert_eq hpc82 with hret2,\n step_assert_eq hpc83 with hret3,\n step_assert_eq hpc84 with hret4,\n step_assert_eq hpc85 with hret5,\n step_ret hpc86,\n -- finish\n step_done, use_only [rfl, rfl],\n -- range check condition\n use_only (rc_m43+rc_m48+rc_m51+rc_m63+rc_m80+0+0), split,\n linarith [rc_mle43, rc_mle48, rc_mle51, rc_mle63, rc_mle80],\n split,\n { arith_simps, try { simp only [hret0 ,hret1 ,hret2 ,hret3 ,hret4 ,hret5] },\n rw [←htv_range_check_ptr₅, hl_range_check_ptr₅, hl_range_check_ptr₄, hl_range_check_ptr₃, hl_range_check_ptr₂, hl_range_check_ptr₁, hin_range_check_ptr],\n try { arith_simps, refl <|> norm_cast }, try { refl } },\n intro rc_h_range_check_ptr, repeat { rw [add_assoc] at rc_h_range_check_ptr },\n have rc_h_range_check_ptr' := range_checked_add_right rc_h_range_check_ptr,\n -- Final Proof\n dsimp [auto_spec_fast_ec_add_block9],\n try { norm_num1 }, try { arith_simps },\n use_only [κ_call43],\n use_only [range_check_ptr₁],\n use_only [slope],\n have rc_h_range_check_ptr₁ := range_checked_offset' rc_h_range_check_ptr,\n have rc_h_range_check_ptr₁' := range_checked_add_right rc_h_range_check_ptr₁, try { norm_cast at rc_h_range_check_ptr₁' },\n have spec43 := h_call43 rc_h_range_check_ptr',\n rw [←hin_range_check_ptr, ←htv_range_check_ptr₁] at spec43,\n try { dsimp at spec43, arith_simps at spec43 },\n use_only [spec43],\n use_only [κ_call45],\n use_only [slope_sqr],\n try { dsimp at h_call45, arith_simps at h_call45 },\n try { use_only [h_call45] },\n use_only [κ_call48],\n use_only [range_check_ptr₂],\n use_only [new_x],\n have rc_h_range_check_ptr₂ := range_checked_offset' rc_h_range_check_ptr₁,\n have rc_h_range_check_ptr₂' := range_checked_add_right rc_h_range_check_ptr₂, try { norm_cast at rc_h_range_check_ptr₂' },\n have spec48 := h_call48 rc_h_range_check_ptr₁',\n rw [←hin_range_check_ptr, ←hl_range_check_ptr₁, ←htv_range_check_ptr₂] at spec48,\n try { dsimp at spec48, arith_simps at spec48 },\n use_only [spec48],\n use_only [κ_call51],\n use_only [range_check_ptr₃],\n use_only [new_y],\n have rc_h_range_check_ptr₃ := range_checked_offset' rc_h_range_check_ptr₂,\n have rc_h_range_check_ptr₃' := range_checked_add_right rc_h_range_check_ptr₃, try { norm_cast at rc_h_range_check_ptr₃' },\n have spec51 := h_call51 rc_h_range_check_ptr₂',\n rw [←hin_range_check_ptr, ←hl_range_check_ptr₁, ←hl_range_check_ptr₂, ←htv_range_check_ptr₃] at spec51,\n try { dsimp at spec51, arith_simps at spec51 },\n use_only [spec51],\n use_only [κ_call63],\n use_only [range_check_ptr₄],\n have rc_h_range_check_ptr₄ := range_checked_offset' rc_h_range_check_ptr₃,\n have rc_h_range_check_ptr₄' := range_checked_add_right rc_h_range_check_ptr₄, try { norm_cast at rc_h_range_check_ptr₄' },\n have spec63 := h_call63 rc_h_range_check_ptr₃',\n rw [←hin_range_check_ptr, ←hl_range_check_ptr₁, ←hl_range_check_ptr₂, ←hl_range_check_ptr₃, ←htv_range_check_ptr₄] at spec63,\n try { dsimp at spec63, arith_simps at spec63 },\n use_only [spec63],\n use_only [κ_call71],\n use_only [x_diff_slope],\n try { dsimp at h_call71, arith_simps at h_call71 },\n try { use_only [h_call71] },\n use_only [κ_call80],\n use_only [range_check_ptr₅],\n have rc_h_range_check_ptr₅ := range_checked_offset' rc_h_range_check_ptr₄,\n have rc_h_range_check_ptr₅' := range_checked_add_right rc_h_range_check_ptr₅, try { norm_cast at rc_h_range_check_ptr₅' },\n have spec80 := h_call80 rc_h_range_check_ptr₄',\n rw [←hin_range_check_ptr, ←hl_range_check_ptr₁, ←hl_range_check_ptr₂, ←hl_range_check_ptr₃, ←hl_range_check_ptr₄, ←htv_range_check_ptr₅] at spec80,\n try { dsimp at spec80, arith_simps at spec80 },\n use_only [spec80],\n try { split, linarith },\n try { ensures_simps; try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point0, hin_point1, htv_range_check_ptr₁, htv_slope, htv_slope_sqr, htv_range_check_ptr₂, htv_new_x, htv_range_check_ptr₃, htv_new_y, htv_range_check_ptr₄, htv_x_diff_slope, htv_range_check_ptr₅] }, },\n try { dsimp [cast_EcPoint, cast_BigInt3, cast_UnreducedBigInt3] },\n try { arith_simps }, try { simp only [hret0, hret1, hret2, hret3, hret4, hret5] },\n try { simp only [h_call43_ap_offset, h_call45_ap_offset, h_call48_ap_offset, h_call51_ap_offset, h_call63_ap_offset, h_call71_ap_offset, h_call80_ap_offset] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },\nend\n\ntheorem auto_sound_fast_ec_add_block5\n -- An independent ap variable.\n (ap : F)\n -- arguments\n (range_check_ptr : F) (point0 point1 : EcPoint F)\n -- code is in memory at σ.pc\n (h_mem : mem_at mem code_fast_ec_add σ.pc)\n -- all dependencies are in memory\n (h_mem_4 : mem_at mem code_nondet_bigint3 (σ.pc - 317))\n (h_mem_5 : mem_at mem code_unreduced_mul (σ.pc - 305))\n (h_mem_6 : mem_at mem code_unreduced_sqr (σ.pc - 285))\n (h_mem_7 : mem_at mem code_verify_zero (σ.pc - 269))\n (h_mem_13 : mem_at mem code_compute_slope (σ.pc - 97))\n -- input arguments on the stack\n (hin_range_check_ptr : range_check_ptr = mem (σ.fp - 15))\n (hin_point0 : point0 = cast_EcPoint mem (σ.fp - 14))\n (hin_point1 : point1 = cast_EcPoint mem (σ.fp - 8))\n (νbound : ℕ)\n -- conclusion\n : ensuresb_ret νbound mem\n {pc := σ.pc + 14, ap := ap, fp := σ.fp}\n (λ κ τ,\n ∃ μ ≤ κ, rc_ensures mem (rc_bound F) μ (mem (σ.fp - 15)) (mem $ τ.ap - 7)\n (auto_spec_fast_ec_add_block5 mem κ range_check_ptr point0 point1 (mem (τ.ap - 7)) (cast_EcPoint mem (τ.ap - 6)))) :=\nbegin\n have h_mem_rec := h_mem,\n unpack_memory code_fast_ec_add at h_mem with ⟨hpc0, hpc1, hpc2, hpc3, hpc4, hpc5, hpc6, hpc7, hpc8, hpc9, hpc10, hpc11, hpc12, hpc13, hpc14, hpc15, hpc16, hpc17, hpc18, hpc19, hpc20, hpc21, hpc22, hpc23, hpc24, hpc25, hpc26, hpc27, hpc28, hpc29, hpc30, hpc31, hpc32, hpc33, hpc34, hpc35, hpc36, hpc37, hpc38, hpc39, hpc40, hpc41, hpc42, hpc43, hpc44, hpc45, hpc46, hpc47, hpc48, hpc49, hpc50, hpc51, hpc52, hpc53, hpc54, hpc55, hpc56, hpc57, hpc58, hpc59, hpc60, hpc61, hpc62, hpc63, hpc64, hpc65, hpc66, hpc67, hpc68, hpc69, hpc70, hpc71, hpc72, hpc73, hpc74, hpc75, hpc76, hpc77, hpc78, hpc79, hpc80, hpc81, hpc82, hpc83, hpc84, hpc85, hpc86⟩,\n -- if statement\n step_jnz hpc14 hpc15 with hcond hcond,\n {\n -- if: positive branch\n have a14 : point1.x.d0 = 0, {\n try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point0, hin_point1] },\n try { dsimp [cast_EcPoint, cast_BigInt3] },\n try { arith_simps }, try { simp only [hcond] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },\n },\n try { dsimp at a14 }, try { arith_simps at a14 },\n clear hcond,\n -- if statement\n step_jnz hpc16 hpc17 with hcond hcond,\n {\n -- if: positive branch\n have a16 : point1.x.d1 = 0, {\n try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point0, hin_point1] },\n try { dsimp [cast_EcPoint, cast_BigInt3] },\n try { arith_simps }, try { simp only [hcond] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },\n },\n try { dsimp at a16 }, try { arith_simps at a16 },\n clear hcond,\n -- if statement\n step_jnz hpc18 hpc19 with hcond hcond,\n {\n -- if: positive branch\n have a18 : point1.x.d2 = 0, {\n try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point0, hin_point1] },\n try { dsimp [cast_EcPoint, cast_BigInt3] },\n try { arith_simps }, try { simp only [hcond] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },\n },\n try { dsimp at a18 }, try { arith_simps at a18 },\n clear hcond,\n -- return\n step_assert_eq hpc20 with hret0,\n step_assert_eq hpc21 with hret1,\n step_assert_eq hpc22 with hret2,\n step_assert_eq hpc23 with hret3,\n step_assert_eq hpc24 with hret4,\n step_assert_eq hpc25 with hret5,\n step_assert_eq hpc26 with hret6,\n step_ret hpc27,\n -- finish\n step_done, use_only [rfl, rfl],\n -- range check condition\n use_only (0+0), split,\n linarith [],\n split,\n { arith_simps, try { simp only [hret0 ,hret1 ,hret2 ,hret3 ,hret4 ,hret5 ,hret6] },\n try { arith_simps, refl <|> norm_cast }, try { refl } },\n intro rc_h_range_check_ptr, repeat { rw [add_assoc] at rc_h_range_check_ptr },\n have rc_h_range_check_ptr' := range_checked_add_right rc_h_range_check_ptr,\n -- Final Proof\n dsimp [auto_spec_fast_ec_add_block5],\n try { norm_num1 }, try { arith_simps },\n left,\n use_only [a14],\n left,\n use_only [a16],\n left,\n use_only [a18],\n try { split, linarith },\n try { ensures_simps; try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point0, hin_point1] }, },\n try { dsimp [cast_EcPoint, cast_BigInt3] },\n try { arith_simps }, try { simp only [hret0, hret1, hret2, hret3, hret4, hret5, hret6] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },\n },\n {\n -- if: negative branch\n have a18 : point1.x.d2 ≠ 0, {\n try { simp only [ne.def] },\n try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point0, hin_point1] },\n try { dsimp [cast_EcPoint, cast_BigInt3] },\n try { arith_simps }, try { simp only [hcond] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },\n },\n try { dsimp at a18 }, try { arith_simps at a18 },\n clear hcond,\n -- Use the block soundness theorem.\n apply ensuresb_ret_trans (auto_sound_fast_ec_add_block9 mem σ _ range_check_ptr point0 point1 h_mem_rec h_mem_4 h_mem_5 h_mem_6 h_mem_7 h_mem_13 hin_range_check_ptr hin_point0 hin_point1 νbound),\n intros κ_block9 τ, try { arith_simps },\n intro h_block9,\n rcases h_block9 with ⟨rc_m_block9, rc_m_le_block9, hblk_range_check_ptr₁, h_block9⟩,\n -- range check condition\n use_only (rc_m_block9+0+0), split,\n linarith [rc_m_le_block9],\n split,\n { arith_simps, try { simp only [hblk_range_check_ptr₁] },\n try { arith_simps, refl <|> norm_cast }, try { refl } },\n intro rc_h_range_check_ptr, repeat { rw [add_assoc] at rc_h_range_check_ptr },\n have rc_h_range_check_ptr' := range_checked_add_right rc_h_range_check_ptr,\n -- Final Proof\n dsimp [auto_spec_fast_ec_add_block5],\n try { norm_num1 }, try { arith_simps },\n left,\n use_only [a14],\n left,\n use_only [a16],\n right,\n use_only [a18],\n have rc_h_range_check_ptr₁ := range_checked_offset' rc_h_range_check_ptr,\n have rc_h_range_check_ptr₁' := range_checked_add_right rc_h_range_check_ptr₁, try { norm_cast at rc_h_range_check_ptr₁' },\n have h_block9' := h_block9 rc_h_range_check_ptr',\n try { rw [←hin_range_check_ptr] at h_block9' },\n try { dsimp at h_block9, arith_simps at h_block9' },\n have h_block9 := h_block9',\n use_only[κ_block9],\n use [h_block9],\n try { linarith }\n }\n },\n {\n -- if: negative branch\n have a16 : point1.x.d1 ≠ 0, {\n try { simp only [ne.def] },\n try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point0, hin_point1] },\n try { dsimp [cast_EcPoint, cast_BigInt3] },\n try { arith_simps }, try { simp only [hcond] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },\n },\n try { dsimp at a16 }, try { arith_simps at a16 },\n clear hcond,\n -- Use the block soundness theorem.\n apply ensuresb_ret_trans (auto_sound_fast_ec_add_block9 mem σ _ range_check_ptr point0 point1 h_mem_rec h_mem_4 h_mem_5 h_mem_6 h_mem_7 h_mem_13 hin_range_check_ptr hin_point0 hin_point1 νbound),\n intros κ_block9 τ, try { arith_simps },\n intro h_block9,\n rcases h_block9 with ⟨rc_m_block9, rc_m_le_block9, hblk_range_check_ptr₁, h_block9⟩,\n -- range check condition\n use_only (rc_m_block9+0+0), split,\n linarith [rc_m_le_block9],\n split,\n { arith_simps, try { simp only [hblk_range_check_ptr₁] },\n try { arith_simps, refl <|> norm_cast }, try { refl } },\n intro rc_h_range_check_ptr, repeat { rw [add_assoc] at rc_h_range_check_ptr },\n have rc_h_range_check_ptr' := range_checked_add_right rc_h_range_check_ptr,\n -- Final Proof\n dsimp [auto_spec_fast_ec_add_block5],\n try { norm_num1 }, try { arith_simps },\n left,\n use_only [a14],\n right,\n use_only [a16],\n have rc_h_range_check_ptr₁ := range_checked_offset' rc_h_range_check_ptr,\n have rc_h_range_check_ptr₁' := range_checked_add_right rc_h_range_check_ptr₁, try { norm_cast at rc_h_range_check_ptr₁' },\n have h_block9' := h_block9 rc_h_range_check_ptr',\n try { rw [←hin_range_check_ptr] at h_block9' },\n try { dsimp at h_block9, arith_simps at h_block9' },\n have h_block9 := h_block9',\n use_only[κ_block9],\n use [h_block9],\n try { linarith }\n }\n },\n {\n -- if: negative branch\n have a14 : point1.x.d0 ≠ 0, {\n try { simp only [ne.def] },\n try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point0, hin_point1] },\n try { dsimp [cast_EcPoint, cast_BigInt3] },\n try { arith_simps }, try { simp only [hcond] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },\n },\n try { dsimp at a14 }, try { arith_simps at a14 },\n clear hcond,\n -- Use the block soundness theorem.\n apply ensuresb_ret_trans (auto_sound_fast_ec_add_block9 mem σ _ range_check_ptr point0 point1 h_mem_rec h_mem_4 h_mem_5 h_mem_6 h_mem_7 h_mem_13 hin_range_check_ptr hin_point0 hin_point1 νbound),\n intros κ_block9 τ, try { arith_simps },\n intro h_block9,\n rcases h_block9 with ⟨rc_m_block9, rc_m_le_block9, hblk_range_check_ptr₁, h_block9⟩,\n -- range check condition\n use_only (rc_m_block9+0+0), split,\n linarith [rc_m_le_block9],\n split,\n { arith_simps, try { simp only [hblk_range_check_ptr₁] },\n try { arith_simps, refl <|> norm_cast }, try { refl } },\n intro rc_h_range_check_ptr, repeat { rw [add_assoc] at rc_h_range_check_ptr },\n have rc_h_range_check_ptr' := range_checked_add_right rc_h_range_check_ptr,\n -- Final Proof\n dsimp [auto_spec_fast_ec_add_block5],\n try { norm_num1 }, try { arith_simps },\n right,\n use_only [a14],\n have rc_h_range_check_ptr₁ := range_checked_offset' rc_h_range_check_ptr,\n have rc_h_range_check_ptr₁' := range_checked_add_right rc_h_range_check_ptr₁, try { norm_cast at rc_h_range_check_ptr₁' },\n have h_block9' := h_block9 rc_h_range_check_ptr',\n try { rw [←hin_range_check_ptr] at h_block9' },\n try { dsimp at h_block9, arith_simps at h_block9' },\n have h_block9 := h_block9',\n use_only[κ_block9],\n use [h_block9],\n try { linarith }\n }\nend\n\ntheorem auto_sound_fast_ec_add\n -- arguments\n (range_check_ptr : F) (point0 point1 : EcPoint F)\n -- code is in memory at σ.pc\n (h_mem : mem_at mem code_fast_ec_add σ.pc)\n -- all dependencies are in memory\n (h_mem_4 : mem_at mem code_nondet_bigint3 (σ.pc - 317))\n (h_mem_5 : mem_at mem code_unreduced_mul (σ.pc - 305))\n (h_mem_6 : mem_at mem code_unreduced_sqr (σ.pc - 285))\n (h_mem_7 : mem_at mem code_verify_zero (σ.pc - 269))\n (h_mem_13 : mem_at mem code_compute_slope (σ.pc - 97))\n -- input arguments on the stack\n (hin_range_check_ptr : range_check_ptr = mem (σ.fp - 15))\n (hin_point0 : point0 = cast_EcPoint mem (σ.fp - 14))\n (hin_point1 : point1 = cast_EcPoint mem (σ.fp - 8))\n -- conclusion\n : ensures_ret mem σ (λ κ τ,\n ∃ μ ≤ κ, rc_ensures mem (rc_bound F) μ (mem (σ.fp - 15)) (mem $ τ.ap - 7)\n (spec_fast_ec_add mem κ range_check_ptr point0 point1 (mem (τ.ap - 7)) (cast_EcPoint mem (τ.ap - 6)))) :=\nbegin\n apply ensures_of_ensuresb, intro νbound,\n have h_mem_rec := h_mem,\n unpack_memory code_fast_ec_add at h_mem with ⟨hpc0, hpc1, hpc2, hpc3, hpc4, hpc5, hpc6, hpc7, hpc8, hpc9, hpc10, hpc11, hpc12, hpc13, hpc14, hpc15, hpc16, hpc17, hpc18, hpc19, hpc20, hpc21, hpc22, hpc23, hpc24, hpc25, hpc26, hpc27, hpc28, hpc29, hpc30, hpc31, hpc32, hpc33, hpc34, hpc35, hpc36, hpc37, hpc38, hpc39, hpc40, hpc41, hpc42, hpc43, hpc44, hpc45, hpc46, hpc47, hpc48, hpc49, hpc50, hpc51, hpc52, hpc53, hpc54, hpc55, hpc56, hpc57, hpc58, hpc59, hpc60, hpc61, hpc62, hpc63, hpc64, hpc65, hpc66, hpc67, hpc68, hpc69, hpc70, hpc71, hpc72, hpc73, hpc74, hpc75, hpc76, hpc77, hpc78, hpc79, hpc80, hpc81, hpc82, hpc83, hpc84, hpc85, hpc86⟩,\n -- if statement\n step_jnz hpc0 hpc1 with hcond hcond,\n {\n -- if: positive branch\n have a0 : point0.x.d0 = 0, {\n try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point0, hin_point1] },\n try { dsimp [cast_EcPoint, cast_BigInt3] },\n try { arith_simps }, try { simp only [hcond] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },\n },\n try { dsimp at a0 }, try { arith_simps at a0 },\n clear hcond,\n -- if statement\n step_jnz hpc2 hpc3 with hcond hcond,\n {\n -- if: positive branch\n have a2 : point0.x.d1 = 0, {\n try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point0, hin_point1] },\n try { dsimp [cast_EcPoint, cast_BigInt3] },\n try { arith_simps }, try { simp only [hcond] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },\n },\n try { dsimp at a2 }, try { arith_simps at a2 },\n clear hcond,\n -- if statement\n step_jnz hpc4 hpc5 with hcond hcond,\n {\n -- if: positive branch\n have a4 : point0.x.d2 = 0, {\n try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point0, hin_point1] },\n try { dsimp [cast_EcPoint, cast_BigInt3] },\n try { arith_simps }, try { simp only [hcond] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },\n },\n try { dsimp at a4 }, try { arith_simps at a4 },\n clear hcond,\n -- return\n step_assert_eq hpc6 with hret0,\n step_assert_eq hpc7 with hret1,\n step_assert_eq hpc8 with hret2,\n step_assert_eq hpc9 with hret3,\n step_assert_eq hpc10 with hret4,\n step_assert_eq hpc11 with hret5,\n step_assert_eq hpc12 with hret6,\n step_ret hpc13,\n -- finish\n step_done, use_only [rfl, rfl],\n -- range check condition\n use_only (0+0), split,\n linarith [],\n split,\n { arith_simps, try { simp only [hret0 ,hret1 ,hret2 ,hret3 ,hret4 ,hret5 ,hret6] },\n try { arith_simps, refl <|> norm_cast }, try { refl } },\n intro rc_h_range_check_ptr, repeat { rw [add_assoc] at rc_h_range_check_ptr },\n have rc_h_range_check_ptr' := range_checked_add_right rc_h_range_check_ptr,\n -- Final Proof\n -- user-provided reduction\n suffices auto_spec: auto_spec_fast_ec_add mem _ range_check_ptr point0 point1 _ _,\n { apply sound_fast_ec_add, apply auto_spec },\n -- prove the auto generated assertion\n dsimp [auto_spec_fast_ec_add],\n try { norm_num1 }, try { arith_simps },\n left,\n use_only [a0],\n left,\n use_only [a2],\n left,\n use_only [a4],\n try { split, linarith },\n try { ensures_simps; try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point0, hin_point1] }, },\n try { dsimp [cast_EcPoint, cast_BigInt3] },\n try { arith_simps }, try { simp only [hret0, hret1, hret2, hret3, hret4, hret5, hret6] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },\n },\n {\n -- if: negative branch\n have a4 : point0.x.d2 ≠ 0, {\n try { simp only [ne.def] },\n try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point0, hin_point1] },\n try { dsimp [cast_EcPoint, cast_BigInt3] },\n try { arith_simps }, try { simp only [hcond] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },\n },\n try { dsimp at a4 }, try { arith_simps at a4 },\n clear hcond,\n -- Use the block soundness theorem.\n apply ensuresb_ret_trans (auto_sound_fast_ec_add_block5 mem σ _ range_check_ptr point0 point1 h_mem_rec h_mem_4 h_mem_5 h_mem_6 h_mem_7 h_mem_13 hin_range_check_ptr hin_point0 hin_point1 νbound),\n intros κ_block5 τ, try { arith_simps },\n intro h_block5,\n rcases h_block5 with ⟨rc_m_block5, rc_m_le_block5, hblk_range_check_ptr₁, h_block5⟩,\n -- range check condition\n use_only (rc_m_block5+0+0), split,\n linarith [rc_m_le_block5],\n split,\n { arith_simps, try { simp only [hblk_range_check_ptr₁] },\n try { arith_simps, refl <|> norm_cast }, try { refl } },\n intro rc_h_range_check_ptr, repeat { rw [add_assoc] at rc_h_range_check_ptr },\n have rc_h_range_check_ptr' := range_checked_add_right rc_h_range_check_ptr,\n -- Final Proof\n -- user-provided reduction\n suffices auto_spec: auto_spec_fast_ec_add mem _ range_check_ptr point0 point1 _ _,\n { apply sound_fast_ec_add, apply auto_spec },\n -- prove the auto generated assertion\n dsimp [auto_spec_fast_ec_add],\n try { norm_num1 }, try { arith_simps },\n left,\n use_only [a0],\n left,\n use_only [a2],\n right,\n use_only [a4],\n have rc_h_range_check_ptr₁ := range_checked_offset' rc_h_range_check_ptr,\n have rc_h_range_check_ptr₁' := range_checked_add_right rc_h_range_check_ptr₁, try { norm_cast at rc_h_range_check_ptr₁' },\n have h_block5' := h_block5 rc_h_range_check_ptr',\n try { rw [←hin_range_check_ptr] at h_block5' },\n try { dsimp at h_block5, arith_simps at h_block5' },\n have h_block5 := h_block5',\n use_only[κ_block5],\n use [h_block5],\n try { linarith }\n }\n },\n {\n -- if: negative branch\n have a2 : point0.x.d1 ≠ 0, {\n try { simp only [ne.def] },\n try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point0, hin_point1] },\n try { dsimp [cast_EcPoint, cast_BigInt3] },\n try { arith_simps }, try { simp only [hcond] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },\n },\n try { dsimp at a2 }, try { arith_simps at a2 },\n clear hcond,\n -- Use the block soundness theorem.\n apply ensuresb_ret_trans (auto_sound_fast_ec_add_block5 mem σ _ range_check_ptr point0 point1 h_mem_rec h_mem_4 h_mem_5 h_mem_6 h_mem_7 h_mem_13 hin_range_check_ptr hin_point0 hin_point1 νbound),\n intros κ_block5 τ, try { arith_simps },\n intro h_block5,\n rcases h_block5 with ⟨rc_m_block5, rc_m_le_block5, hblk_range_check_ptr₁, h_block5⟩,\n -- range check condition\n use_only (rc_m_block5+0+0), split,\n linarith [rc_m_le_block5],\n split,\n { arith_simps, try { simp only [hblk_range_check_ptr₁] },\n try { arith_simps, refl <|> norm_cast }, try { refl } },\n intro rc_h_range_check_ptr, repeat { rw [add_assoc] at rc_h_range_check_ptr },\n have rc_h_range_check_ptr' := range_checked_add_right rc_h_range_check_ptr,\n -- Final Proof\n -- user-provided reduction\n suffices auto_spec: auto_spec_fast_ec_add mem _ range_check_ptr point0 point1 _ _,\n { apply sound_fast_ec_add, apply auto_spec },\n -- prove the auto generated assertion\n dsimp [auto_spec_fast_ec_add],\n try { norm_num1 }, try { arith_simps },\n left,\n use_only [a0],\n right,\n use_only [a2],\n have rc_h_range_check_ptr₁ := range_checked_offset' rc_h_range_check_ptr,\n have rc_h_range_check_ptr₁' := range_checked_add_right rc_h_range_check_ptr₁, try { norm_cast at rc_h_range_check_ptr₁' },\n have h_block5' := h_block5 rc_h_range_check_ptr',\n try { rw [←hin_range_check_ptr] at h_block5' },\n try { dsimp at h_block5, arith_simps at h_block5' },\n have h_block5 := h_block5',\n use_only[κ_block5],\n use [h_block5],\n try { linarith }\n }\n },\n {\n -- if: negative branch\n have a0 : point0.x.d0 ≠ 0, {\n try { simp only [ne.def] },\n try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point0, hin_point1] },\n try { dsimp [cast_EcPoint, cast_BigInt3] },\n try { arith_simps }, try { simp only [hcond] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },\n },\n try { dsimp at a0 }, try { arith_simps at a0 },\n clear hcond,\n -- Use the block soundness theorem.\n apply ensuresb_ret_trans (auto_sound_fast_ec_add_block5 mem σ _ range_check_ptr point0 point1 h_mem_rec h_mem_4 h_mem_5 h_mem_6 h_mem_7 h_mem_13 hin_range_check_ptr hin_point0 hin_point1 νbound),\n intros κ_block5 τ, try { arith_simps },\n intro h_block5,\n rcases h_block5 with ⟨rc_m_block5, rc_m_le_block5, hblk_range_check_ptr₁, h_block5⟩,\n -- range check condition\n use_only (rc_m_block5+0+0), split,\n linarith [rc_m_le_block5],\n split,\n { arith_simps, try { simp only [hblk_range_check_ptr₁] },\n try { arith_simps, refl <|> norm_cast }, try { refl } },\n intro rc_h_range_check_ptr, repeat { rw [add_assoc] at rc_h_range_check_ptr },\n have rc_h_range_check_ptr' := range_checked_add_right rc_h_range_check_ptr,\n -- Final Proof\n -- user-provided reduction\n suffices auto_spec: auto_spec_fast_ec_add mem _ range_check_ptr point0 point1 _ _,\n { apply sound_fast_ec_add, apply auto_spec },\n -- prove the auto generated assertion\n dsimp [auto_spec_fast_ec_add],\n try { norm_num1 }, try { arith_simps },\n right,\n use_only [a0],\n have rc_h_range_check_ptr₁ := range_checked_offset' rc_h_range_check_ptr,\n have rc_h_range_check_ptr₁' := range_checked_add_right rc_h_range_check_ptr₁, try { norm_cast at rc_h_range_check_ptr₁' },\n have h_block5' := h_block5 rc_h_range_check_ptr',\n try { rw [←hin_range_check_ptr] at h_block5' },\n try { dsimp at h_block5, arith_simps at h_block5' },\n have h_block5 := h_block5',\n use_only[κ_block5],\n use [h_block5],\n try { linarith }\n }\nend\n\n", "meta": {"author": "starkware-libs", "repo": "formal-proofs", "sha": "35613c65b6715601bbc0a550d52754f8e7d93e30", "save_path": "github-repos/lean/starkware-libs-formal-proofs", "path": "github-repos/lean/starkware-libs-formal-proofs/formal-proofs-35613c65b6715601bbc0a550d52754f8e7d93e30/src/starkware/cairo/common/cairo_secp/verification/verification/signature_recover_public_key_fast_ec_add_soundness.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4493926344647596, "lm_q2_score": 0.024798158528930275, "lm_q1q2_score": 0.011144109791190723}} {"text": "\nimport for_mathlib.composable_morphisms\nimport algebra.homology.additive\nimport for_mathlib.homological_complex_map_d_to_d_from\n\nnoncomputable theory\n\nopen category_theory category_theory.category category_theory.limits\n\nvariables {C D : Type*} [category C] [category D]\n\nsection\n\nvariables (C)\n\n/- Category of complexes `X ⟶ Y ⟶ Z` -/\n@[derive category]\ndef short_complex [has_zero_morphisms C] := { S : composable_morphisms C // S.zero }\n\nvariables {C}\n\nnamespace category_theory\n\nnamespace arrow\n\nnamespace hom\n\nlemma congr_left {f g : arrow C} {φ₁ φ₂ : f ⟶ g} (h : φ₁ = φ₂) : φ₁.left = φ₂.left := by rw h\nlemma congr_right {f g : arrow C} {φ₁ φ₂ : f ⟶ g} (h : φ₁ = φ₂) : φ₁.right = φ₂.right := by rw h\n\nend hom\n\nend arrow\n\nend category_theory\n\nend\n\nopen category_theory\n\nnamespace homological_complex\n\nvariables [has_zero_morphisms C] [has_zero_object C] {M : Type*} {c : complex_shape M}\n\nlemma prev_id (X : homological_complex C c) (i : M) : hom.prev (𝟙 X) i = 𝟙 (X.X_prev i) :=\nbegin\n rcases h : c.prev i with _ | ⟨j,w⟩,\n { rw homological_complex.prev_eq_zero' _ i h,\n symmetry,\n rw ← limits.is_zero.iff_id_eq_zero,\n exact limits.is_zero.of_iso (limits.is_zero_zero _)\n (homological_complex.X_prev_iso_zero X h), },\n { rw homological_complex.hom.prev_eq _ w,\n simp only [homological_complex.hom.prev_eq _ w,\n homological_complex.id_f, id_comp, iso.hom_inv_id], },\nend\n\nlemma next_id (X : homological_complex C c) (i : M) : hom.next (𝟙 X) i = 𝟙 (X.X_next i) :=\narrow.hom.congr_right (hom.sq_from_id X i)\n\nlemma prev_comp {X Y Z : homological_complex C c} (f : X ⟶ Y) (g : Y ⟶ Z)\n (i : M) : hom.prev (f ≫ g) i = hom.prev f i ≫ hom.prev g i :=\nbegin\n rcases h : c.prev i with _ | ⟨j,w⟩,\n { simp only [homological_complex.prev_eq_zero' _ i h, comp_zero], },\n { simp only [homological_complex.hom.prev_eq _ w, comp_f, assoc, iso.inv_hom_id_assoc], },\nend\n\nlemma next_comp {X Y Z : homological_complex C c} (f : X ⟶ Y) (g : Y ⟶ Z)\n (i : M) : hom.next (f ≫ g) i = hom.next f i ≫ hom.next g i :=\narrow.hom.congr_right (hom.sq_from_comp f g i)\n\nend homological_complex\n\nnamespace short_complex\n\n@[simp, reassoc]\nlemma zero [has_zero_morphisms C] (S : short_complex C) : S.1.f ≫ S.1.g = 0 := S.2\n\n@[simps]\ndef mk [has_zero_morphisms C] {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) (zero : f ≫ g = 0) :\n short_complex C := ⟨composable_morphisms.mk f g, zero⟩\n\n@[simp]\nlemma mk_id_τ₁ [has_zero_morphisms C] {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) (zero : f ≫ g = 0) :\ncomposable_morphisms.hom.τ₁ (𝟙 (mk f g zero)) = 𝟙 X := rfl\n@[simp]\nlemma mk_id_τ₂ [has_zero_morphisms C] {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) (zero : f ≫ g = 0) :\ncomposable_morphisms.hom.τ₂ (𝟙 (mk f g zero)) = 𝟙 Y := rfl\n@[simp]\nlemma mk_id_τ₃ [has_zero_morphisms C] {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) (zero : f ≫ g = 0) :\ncomposable_morphisms.hom.τ₃ (𝟙 (mk f g zero)) = 𝟙 Z := rfl\n\n@[simp]\nlemma comp_τ₁ [has_zero_morphisms C] {S₁ S₂ S₃ : short_complex C} (f : S₁ ⟶ S₂) (g : S₂ ⟶ S₃) :\n (f ≫ g).τ₁ = f.τ₁ ≫ g.τ₁ := rfl\n@[simp]\nlemma comp_τ₂ [has_zero_morphisms C] {S₁ S₂ S₃ : short_complex C} (f : S₁ ⟶ S₂) (g : S₂ ⟶ S₃) :\n (f ≫ g).τ₂ = f.τ₂ ≫ g.τ₂ := rfl\n@[simp]\nlemma comp_τ₃ [has_zero_morphisms C] {S₁ S₂ S₃ : short_complex C} (f : S₁ ⟶ S₂) (g : S₂ ⟶ S₃) :\n (f ≫ g).τ₃ = f.τ₃ ≫ g.τ₃ := rfl\n\n@[simps]\ndef hom_mk [has_zero_morphisms C] {X₁ Y₁ Z₁ X₂ Y₂ Z₂ : C} {f₁ : X₁ ⟶ Y₁} {g₁ : Y₁ ⟶ Z₁}\n {f₂ : X₂ ⟶ Y₂} {g₂ : Y₂ ⟶ Z₂} {zero₁ : f₁ ≫ g₁ = 0} {zero₂ : f₂ ≫ g₂ = 0}\n (τ₁ : X₁ ⟶ X₂) (τ₂ : Y₁ ⟶ Y₂) (τ₃ : Z₁ ⟶ Z₂) (comm₁₂ : f₁ ≫ τ₂ = τ₁ ≫ f₂)\n (comm₂₃ : g₁ ≫ τ₃ = τ₂ ≫ g₂) :\n mk f₁ g₁ zero₁ ⟶ mk f₂ g₂ zero₂ := ⟨τ₁, τ₂, τ₃, comm₁₂, comm₂₃⟩\n\n@[simps]\ndef iso_mk [has_zero_morphisms C] {S₁ S₂ : short_complex C}\n (τ₁ : S₁.1.X ≅ S₂.1.X) (τ₂ : S₁.1.Y ≅ S₂.1.Y) (τ₃ : S₁.1.Z ≅ S₂.1.Z)\n (comm₁₂ : S₁.1.f ≫ τ₂.hom = τ₁.hom ≫ S₂.1.f)\n (comm₂₃ : S₁.1.g ≫ τ₃.hom = τ₂.hom ≫ S₂.1.g) :\n S₁ ≅ S₂ :=\n{ hom := ⟨τ₁.hom, τ₂.hom, τ₃.hom, comm₁₂, comm₂₃⟩,\n inv := begin\n refine ⟨τ₁.inv, τ₂.inv, τ₃.inv, _, _⟩,\n { simp only [← cancel_mono τ₂.hom, ← cancel_epi τ₁.hom,\n assoc, iso.inv_hom_id, comp_id, iso.hom_inv_id_assoc, comm₁₂], },\n { simp only [← cancel_mono τ₃.hom, ← cancel_epi τ₂.hom,\n assoc, iso.inv_hom_id, comp_id, iso.hom_inv_id_assoc, comm₂₃], },\n end,\n hom_inv_id' := begin\n ext,\n { simpa only [comp_τ₁, hom_mk_τ₁, iso.hom_inv_id], },\n { simpa only [comp_τ₂, hom_mk_τ₂, iso.hom_inv_id], },\n { simpa only [comp_τ₃, hom_mk_τ₃, iso.hom_inv_id], },\n end,\n inv_hom_id' := begin\n ext,\n { simpa only [iso.inv_hom_id, comp_τ₁, hom_mk_τ₁], },\n { simpa only [iso.inv_hom_id, comp_τ₂, hom_mk_τ₂], },\n { simpa only [iso.inv_hom_id, comp_τ₃, hom_mk_τ₃], },\n end, }\n\nlemma is_iso_of_is_isos [has_zero_morphisms C] {S₁ S₂ : short_complex C}\n (φ : S₁ ⟶ S₂) (h₁ : is_iso φ.τ₁) (h₂ : is_iso φ.τ₂) (h₃ : is_iso φ.τ₃) : is_iso φ :=\nbegin\n let e : S₁ ≅ S₂ := iso_mk (as_iso φ.τ₁) (as_iso φ.τ₂) (as_iso φ.τ₃) φ.comm₁₂ φ.comm₂₃,\n unfreezingI { rcases φ with ⟨τ₁, τ₂, τ₃, comm₁₂, comm₂₂⟩, },\n exact is_iso.of_iso e,\nend\n\ndef homology [abelian C] (S : short_complex C) : C := homology S.1.f S.1.g S.2\n\n@[simps]\ndef homology_functor [abelian C] : short_complex C ⥤ C :=\n{ obj := λ X, X.homology,\n map := λ X Y φ, homology.map X.2 Y.2 ⟨φ.τ₁, φ.τ₂, φ.comm₁₂.symm⟩\n ⟨φ.τ₂, φ.τ₃, φ.comm₂₃.symm⟩ rfl,\n map_id' := λ X, by apply homology.map_id,\n map_comp' := λ X Y Z φ ψ, by { symmetry, apply homology.map_comp, }, }\n\nvariable (C)\n\n@[simps]\ndef functor_homological_complex [has_zero_morphisms C] [has_zero_object C]\n {M : Type*} (c : complex_shape M) (i : M) :\n homological_complex C c ⥤ short_complex C :=\n{ obj := λ X, mk (X.d_to i) (X.d_from i) (X.d_to_comp_d_from i),\n map := λ X Y f, composable_morphisms.hom.mk (f.prev i) (f.f i) (f.next i)\n (f.comm_to i).symm (f.comm_from i).symm,\n map_id' := λ X, begin\n ext,\n { exact X.prev_id i, },\n { refl, },\n { exact X.next_id i, },\n end,\n map_comp' := λ X Y Z f g, begin\n ext,\n { exact homological_complex.prev_comp f g i, },\n { refl, },\n { exact homological_complex.next_comp f g i, },\n end, }\n\n@[simps]\ndef homology_functor_iso [abelian C] {M : Type*} (c : complex_shape M) (i : M) :\n _root_.homology_functor C c i ≅\n functor_homological_complex C c i ⋙ short_complex.homology_functor :=\nnat_iso.of_components (λ X, iso.refl _)\n (λ X Y f, by { ext, simpa only [iso.refl_hom, id_comp, comp_id], })\n\nend short_complex\n\nnamespace category_theory\n\nnamespace functor\n\n@[simps]\ndef map_short_complex [has_zero_morphisms C] [has_zero_morphisms D] (F : C ⥤ D)\n [F.preserves_zero_morphisms] :\n short_complex C ⥤ short_complex D :=\nfull_subcategory.lift _ (induced_functor _ ⋙ F.map_composable_morphisms)\n(λ X, begin\n have h := X.2,\n dsimp [composable_morphisms.zero] at h ⊢,\n rw [← F.map_comp, h, F.map_zero],\nend)\n\nend functor\n\nnamespace nat_trans\n\n@[simps]\ndef map_short_complex [has_zero_morphisms C] [has_zero_morphisms D] {F G : C ⥤ D}\n [F.preserves_zero_morphisms] [G.preserves_zero_morphisms] (φ : F ⟶ G) :\n F.map_short_complex ⟶ G.map_short_complex :=\n{ app := λ X, ⟨φ.app _, φ.app _, φ.app _, φ.naturality _, φ.naturality _⟩, }\n\nend nat_trans\n\nend category_theory\n\nopen category_theory\n\nnamespace short_complex\n\nvariable {C}\n\ndef functor_homological_complex_map [preadditive C] [has_zero_object C]\n [preadditive D] [has_zero_object D] (F : C ⥤ D) [F.additive]\n {M : Type*} (c : complex_shape M) (i : M) :\nshort_complex.functor_homological_complex C c i ⋙ F.map_short_complex ≅\nF.map_homological_complex c ⋙ short_complex.functor_homological_complex D c i :=\nnat_iso.of_components\n (λ X, iso_mk (F.obj_X_prev X i) (iso.refl _) ((F.obj_X_next X i))\n (by simpa only [iso.refl_hom, comp_id] using F.map_d_to X i)\n (by simpa only [iso.refl_hom, id_comp] using F.d_from_map X i))\n (λ X Y f, begin\n ext,\n { simp only [functor.comp_map, comp_τ₁, functor.map_short_complex_map_τ₁,\n functor_homological_complex_map_τ₁, iso_mk_hom_τ₁, F.map_prev], },\n { dsimp, simp only [comp_id, id_comp], },\n { simp only [functor.comp_map, comp_τ₃, functor.map_short_complex_map_τ₃,\n functor_homological_complex_map_τ₃, iso_mk_hom_τ₃, F.map_next], },\n end)\n\nlemma naturality_functor_homological_complex_map [preadditive C] [has_zero_object C]\n [preadditive D] [has_zero_object D] {F G : C ⥤ D} [F.additive] [G.additive]\n {M : Type*} (c : complex_shape M) (i : M) (φ : F ⟶ G) (X : homological_complex C c) :\n (nat_trans.map_short_complex φ).app\n ((short_complex.functor_homological_complex C c i).obj X) ≫\n (short_complex.functor_homological_complex_map G c i).hom.app X =\n (short_complex.functor_homological_complex_map F c i).hom.app X ≫\n (short_complex.functor_homological_complex D c i).map\n ((nat_trans.map_homological_complex φ c).app X) :=\nbegin\n ext; dsimp [functor_homological_complex_map],\n { apply φ.map_prev, },\n { simp only [comp_id, id_comp], },\n { apply φ.map_next, },\nend\n\nend short_complex\n", "meta": {"author": "bentoner", "repo": "debug", "sha": "b8a75381caa90aa9942c20e08a44e45d0ae60d18", "save_path": "github-repos/lean/bentoner-debug", "path": "github-repos/lean/bentoner-debug/debug-b8a75381caa90aa9942c20e08a44e45d0ae60d18/src/for_mathlib/short_complex.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4416730056646256, "lm_q2_score": 0.025178841060544563, "lm_q1q2_score": 0.011120814410362606}} {"text": "import .lovelib\n\n\n/-! # CS-VU Diversity and Support Information\n\nWhen in doubt: Please be respectful and courteous to everyone!\n\n* For class-related interactions: please come talk to the lecturer\n\n* Talk to your study advisors to find resources and support information\n\n* CS BETA diversity address to send your concerns/questions:\n diversity.cs.beta@vu.nl\n\n* Department diversity office hours, every 3rd Monday of the month, 12-1pm\n (lunch hours)\n * STORM Diversity Committee (DiversityCie), diversitycie@storm.vu.nl\n * Student-led committee for promoting diversity in our faculty\n\n* Support information:\n * Student well being:\n https://vu.nl/en/student/student-wellbeing\n * Safe social setting on campus\n https://vu.nl/en/about-vu/more-about/safe-social-setting-on-campus\n\n* https://3d.vu.nl/ for diversity and support related issues at the VU level\n\n\n# LoVe Preface\n\n## Proof Assistants\n\nProof assistants (also called interactive theorem provers)\n\n* check and help develop formal proofs;\n* can be used to prove big theorems, not only logic puzzles;\n* can be tedious to use;\n* are highly addictive (think video games).\n\nA selection of proof assistants, classified by logical foundations:\n\n* set theory: Isabelle/ZF, Metamath, Mizar;\n* simple type theory: HOL4, HOL Light, Isabelle/HOL;\n* **dependent type theory**: Agda, Coq, **Lean**, Matita, PVS.\n\n\n## Success Stories\n\nMathematics:\n\n* the four-color theorem (in Coq);\n* the Kepler conjecture (in HOL Light and Isabelle/HOL);\n* the definition of perfectoid spaces (in Lean).\n\nComputer science:\n\n* hardware;\n* operating systems;\n* programming language theory;\n* compilers;\n* security.\n\n\n## Lean\n\nLean is a proof assistant developed primarily by Leonardo de Moura (Microsoft\nResearch) since 2012.\n\nIts mathematical library, `mathlib`, is developed under the leadership of\nJeremy Avigad (Carnegie Mellon University).\n\nWe use the community version of Lean 3. We use its basic libraries, `mathlib`,\nand `LoVelib`. Lean is a research project.\n\nStrengths:\n\n* highly expressive logic based on a dependent type theory called the\n **calculus of inductive constructions**;\n* extended with classical axioms and quotient types;\n* metaprogramming framework;\n* modern user interface;\n* documentation;\n* open source;\n* endless source of puns (Lean Forward, Lean Together, Boolean, …).\n\n\n## This Course\n\n### Web Site\n\n https://lean-forward.github.io/logical-verification/2022/index.html\n\n\n### Installation Instructions\n\n https://github.com/blanchette/logical_verification_2022/blob/main/README.md#logical-verification-2022---installation-instructions\n\n\n### Repository (Demos, Exercises, Homework)\n\n https://github.com/blanchette/logical_verification_2022\n\nThe file you are currently looking at is a demo. There are\n\n* 13 demo files;\n* 13 exercise sheets;\n* 11 homework sheets (10 points each);\n* 1 project (20 points).\n\nYou may submit at most 10 homework, or at most 8 homework and the project.\nHomework, including the project, must be done individually. The homework builds\non the exercises, which build on the demos.\n\n\n### The Hitchhiker's Guide to Logical Verification\n\n https://github.com/blanchette/logical_verification_2022/blob/main/hitchhikers_guide.pdf\n https://github.com/blanchette/logical_verification_2022/blob/main/hitchhikers_guide_tablet.pdf\n\nThe lecture notes consist of a preface and 13 chapters. They cover the same\nmaterial as the corresponding lectures but with more details. Sometimes there\nwill not be enough time to cover everything in class, so reading the lecture\nnotes will be necessary.\n\n\n### Final Exam\n\nThe course aims at teaching concepts, not syntax. Therefore, the final exam is\non paper. It is also closed book.\n\n\n## Our Goal\n\nWe want you to\n\n* master fundamental theory and techniques in interactive theorem proving;\n* familiarize yourselves with some application areas;\n* develop some practical skills you can apply on a larger project (as a hobby,\n for an MSc or PhD, or in industry);\n* feel ready to move to another proof assistant and apply what you have learned;\n* understand the domain well enough to start reading scientific papers.\n\nThis course is neither a pure logical foundations course nor a Lean tutorial.\nLean is our vehicle, not an end in itself.\n\n\n# LoVe Demo 1: Definitions and Statements\n\nWe introduce the basics of Lean and proof assistants, without trying to carry\nout actual proofs yet. We focus on specifying objects and statements of their\nintended properties. -/\n\n\nset_option pp.beta true\nset_option pp.generalized_field_notation false\n\nnamespace LoVe\n\n\n/-! ## A View of Lean\n\nIn a first approximation:\n\n Lean = functional programming + logic\n\nIn today's lecture, we cover inductive types, recursive functions, and lemma\nstatements.\n\nIf you are not familiar with typed functional programming (e.g., Haskell, ML,\nOCaml, Scala), we recommend that you study a tutorial, such as the first\nchapters of the online tutorial __Learn You a Haskell for Great Good!__:\n\n http://learnyouahaskell.com/chapters\n\nMake sure to at least reach, and read, the section titled \"Lambdas\".\n\n\n## Types and Terms\n\nSimilar to simply typed λ-calculus or typed functional programming languages\n(ML, OCaml, Haskell).\n\nTypes `σ`, `τ`, `υ`:\n\n* type variables `α`;\n* basic types `T`;\n* complex types `T σ1 … σN`.\n\nSome type constructors `T` are written infix, e.g., `→` (function type).\n\nThe function arrow is right-associative:\n`σ₁ → σ₂ → σ₃ → τ` = `σ₁ → (σ₂ → (σ₃ → τ))`.\n\nPolymorphic types are also possible. In Lean, the type variables must be bound\nusing `∀`, e.g., `∀α, α → α`.\n\nTerms `t`, `u`:\n\n* constants `c`;\n* variables `x`;\n* applications `t u`;\n* λ-expressions `λx, t`.\n\n__Currying__: functions can be\n\n* fully applied (e.g., `f x y z` if `f` is ternary);\n* partially applied (e.g., `f x y`, `f x`);\n* left unapplied (e.g., `f`).\n\nApplication is left-associative: `f x y z` = `((f x) y) z`. -/\n\n#check ℕ\n#check ℤ\n\n#check empty\n#check unit\n#check bool\n\n#check ℕ → ℤ\n#check ℤ → ℕ\n#check bool → ℕ → ℤ\n#check (bool → ℕ) → ℤ\n#check ℕ → (bool → ℕ) → ℤ\n\n#check λx : ℕ, x\n#check λf : ℕ → ℕ, λg : ℕ → ℕ, λh : ℕ → ℕ, λx : ℕ, h (g (f x))\n#check λ(f g h : ℕ → ℕ) (x : ℕ), h (g (f x))\n\nconstants a b : ℤ\nconstant f : ℤ → ℤ\nconstant g : ℤ → ℤ → ℤ\n\n#check λx : ℤ, g (f (g a x)) (g x b)\n#check λx, g (f (g a x)) (g x b)\n\n#check λx, x\n\nconstant trool : Type\nconstants trool.true trool.false trool.maybe : trool\n\n\n/-! ### Type Checking and Type Inference\n\nType checking and type inference are decidable problems (although this property is\nquickly lost if features such as overloading or subtyping are added).\n\nType judgment: `C ⊢ t : σ`, meaning `t` has type `σ` in local context `C`.\n\nTyping rules:\n\n —————————— Cst if c is declared with type σ\n C ⊢ c : σ\n\n —————————— Var if x : σ is the last occurrence of x in C\n C ⊢ x : σ\n\n C ⊢ t : σ → τ C ⊢ u : σ\n ——————————————————————————— App\n C ⊢ t u : τ\n\n C, x : σ ⊢ t : τ\n ———————————————————————— Lam\n C ⊢ (λx : σ, t) : σ → τ\n\n\n### Type Inhabitation\n\nGiven a type `σ`, the __type inhabitation__ problem consists of finding a term\nof that type. Type inhabitation is undecidable.\n\nRecursive procedure:\n\n1. If `σ` is of the form `τ → υ`, a candidate inhabitant is an anonymous\n function of the form `λx, _`.\n\n2. Alternatively, you can use any constant or variable `x : τ₁ → ⋯ → τN → σ` to\n build the term `x _ … _`. -/\n\nconstants α β γ : Type\n\ndef some_fun_of_type : (α → β → γ) → ((β → α) → β) → α → γ :=\nλf g a, f a (g (λb, a))\n\n\n/-! ## Type Definitions\n\nAn __inductive type__ (also called __inductive datatype__,\n__algebraic datatype__, or just __datatype__) is a type that consists all the\nvalues that can be built using a finite number of applications of its\n__constructors__, and only those.\n\n\n### Natural Numbers -/\n\nnamespace my_nat\n\n/-! Definition of type `nat` (= `ℕ`) of natural numbers, using Peano-style unary\nnotation: -/\n\ninductive nat : Type\n| zero : nat\n| succ : nat → nat\n\n#check nat\n#check nat.zero\n#check nat.succ\n\nend my_nat\n\n#print nat\n#print ℕ\n\n\n/-! ### Arithmetic Expressions -/\n\ninductive aexp : Type\n| num : ℤ → aexp\n| var : string → aexp\n| add : aexp → aexp → aexp\n| sub : aexp → aexp → aexp\n| mul : aexp → aexp → aexp\n| div : aexp → aexp → aexp\n\n\n/-! ### Lists -/\n\nnamespace my_list\n\ninductive list (α : Type) : Type\n| nil : list\n| cons : α → list → list\n\n#check list.nil\n#check list.cons\n\nend my_list\n\n#print list\n\n\n/-! ## Function Definitions\n\nThe syntax for defining a function operating on an inductive type is very\ncompact: We define a single function and use __pattern matching__ to extract the\narguments to the constructors. -/\n\ndef add : ℕ → ℕ → ℕ\n| m nat.zero := m\n| m (nat.succ n) := nat.succ (add m n)\n\n#eval add 2 7\n#reduce add 2 7\n\ndef mul : ℕ → ℕ → ℕ\n| _ nat.zero := nat.zero\n| m (nat.succ n) := add m (mul m n)\n\n#eval mul 2 7\n\n#print mul\n#print mul._main\n\ndef power : ℕ → ℕ → ℕ\n| _ nat.zero := 1\n| m (nat.succ n) := mul m (power m n)\n\n#eval power 2 5\n\ndef power₂ (m : ℕ) : ℕ → ℕ\n| nat.zero := 1\n| (nat.succ n) := mul m (power₂ n)\n\n#eval power₂ 2 5\n\ndef iter (α : Type) (z : α) (f : α → α) : ℕ → α\n| nat.zero := z\n| (nat.succ n) := f (iter n)\n\n#check iter\n\ndef power₃ (m n : ℕ) : ℕ :=\niter ℕ 1 (λl, mul m l) n\n\n#eval power₃ 2 5\n\ndef append (α : Type) : list α → list α → list α\n| list.nil ys := ys\n| (list.cons x xs) ys := list.cons x (append xs ys)\n\n#check append\n#eval append _ [3, 1] [4, 1, 5]\n\ndef append₂ {α : Type} : list α → list α → list α\n| list.nil ys := ys\n| (list.cons x xs) ys := list.cons x (append₂ xs ys)\n\n#check append₂\n#eval append₂ [3, 1] [4, 1, 5]\n\n#check @append₂\n#eval @append₂ _ [3, 1] [4, 1, 5]\n\n/-! Aliases:\n\n `[]` := `nil`\n `x :: xs` := `cons x xs`\n `[x₁, …, xN]` := `x₁ :: … :: xN :: []` -/\n\ndef append₃ {α : Type} : list α → list α → list α\n| [] ys := ys\n| (x :: xs) ys := x :: append₃ xs ys\n\ndef reverse {α : Type} : list α → list α\n| [] := []\n| (x :: xs) := reverse xs ++ [x]\n\ndef eval (env : string → ℤ) : aexp → ℤ\n| (aexp.num i) := i\n| (aexp.var x) := env x\n| (aexp.add e₁ e₂) := eval e₁ + eval e₂\n| (aexp.sub e₁ e₂) := eval e₁ - eval e₂\n| (aexp.mul e₁ e₂) := eval e₁ * eval e₂\n| (aexp.div e₁ e₂) := eval e₁ / eval e₂\n\n#eval eval (λs, 7) (aexp.div (aexp.var \"x\") (aexp.num 0))\n\n/-! Lean only accepts the function definitions for which it can prove\ntermination. In particular, it accepts __structurally recursive__ functions,\nwhich peel off exactly one constructor at a time.\n\n\n## Lemma Statements\n\nNotice the similarity with `def` commands. -/\n\nnamespace sorry_lemmas\n\nlemma add_comm (m n : ℕ) :\n add m n = add n m :=\nsorry\n\nlemma add_assoc (l m n : ℕ) :\n add (add l m) n = add l (add m n) :=\nsorry\n\nlemma mul_comm (m n : ℕ) :\n mul m n = mul n m :=\nsorry\n\nlemma mul_assoc (l m n : ℕ) :\n mul (mul l m) n = mul l (mul m n) :=\nsorry\n\nlemma mul_add (l m n : ℕ) :\n mul l (add m n) = add (mul l m) (mul l n) :=\nsorry\n\nlemma reverse_reverse {α : Type} (xs : list α) :\n reverse (reverse xs) = xs :=\nsorry\n\n/-! Axioms are like lemmas but without proofs (`:= …`). Constant declarations\nare like definitions but without bodies (`:= …`). -/\n\nconstants a b : ℤ\n\naxiom a_less_b :\n a < b\n\nend sorry_lemmas\n\nend LoVe\n", "meta": {"author": "blanchette", "repo": "logical_verification_2022", "sha": "5aee593fbef9b63d4338288b4789d85851d258aa", "save_path": "github-repos/lean/blanchette-logical_verification_2022", "path": "github-repos/lean/blanchette-logical_verification_2022/logical_verification_2022-5aee593fbef9b63d4338288b4789d85851d258aa/lean/love01_definitions_and_statements_demo.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1037486296375442, "lm_q2_score": 0.10669059820623797, "lm_q1q2_score": 0.011069003359107021}} {"text": "\nimport data.dlist\nimport separation.specification\n\nimport tactic.monotonicity\nimport util.meta.tactic\n\nuniverses u v\n\nnamespace tactic.interactive\n\nopen applicative\nopen lean.parser\nopen interactive\nopen interactive.types\nopen tactic functor list nat separation\n\nlocal postfix `?`:9001 := optional\nlocal postfix *:9001 := many\n\n@[user_attribute]\nmeta def ptr_abstraction : user_attribute :=\n{ name := `ptr_abstraction\n, descr := \"Abstraction predicate for pointer structures\" }\n\nmeta def mk_sep_assert : list expr → expr\n | [] := `(emp)\n | (e :: []) := e\n | (e :: es) := `(%%e :*: %%(mk_sep_assert es))\n\nmeta inductive assert_with_vars\n | s_and : assert_with_vars → assert_with_vars → assert_with_vars\n | s_exists : expr → assert_with_vars → assert_with_vars\n | leaf : expr → assert_with_vars\n | prop : expr → assert_with_vars\nopen predicate\nmeta def parse_assert_with_vars : expr → tactic assert_with_vars\n | `(s_and %%e₀ %%e₁) := assert_with_vars.s_and <$> parse_assert_with_vars e₀\n <*> parse_assert_with_vars e₁\n | `(p_exists %%e) :=\n do `(λ _ : %%t, %%e') ← pure e,\n assert_with_vars.s_exists t <$> parse_assert_with_vars e'\n | `([| %%e |]) :=\n return $ assert_with_vars.prop e\n | e := return $ assert_with_vars.leaf e\n\nmeta def assert_with_vars.to_expr : assert_with_vars → pexpr\n | (assert_with_vars.leaf e) := to_pexpr e\n | (assert_with_vars.prop e) := ``([| %%e |])\n | (assert_with_vars.s_and e₀ e₁) := ``(%%(e₀.to_expr) :*: %%(e₁.to_expr))\n | (assert_with_vars.s_exists t e) := ``(p_exists %%(expr.lam `x binder_info.default (to_pexpr t) e.to_expr))\n\nmeta def hexists_to_meta_var (rules : list simp_arg_type)\n: list expr → assert_with_vars → tactic (assert_with_vars × expr)\n | vs (assert_with_vars.s_and e₀ e₁) :=\n do (x₀,p₀) ← hexists_to_meta_var vs e₀,\n (x₁,p₁) ← hexists_to_meta_var vs e₁,\n let x := assert_with_vars.s_and x₀ x₁,\n prod.mk x <$> to_expr ``(s_and_s_imp_s_and %%p₀ %%p₁)\n | vs (assert_with_vars.s_exists t e) :=\n do v ← mk_meta_var t,\n (x,p) ← hexists_to_meta_var (v :: vs) e,\n let x := assert_with_vars.s_exists t x,\n q ← expr.lam `x binder_info.default t <$> to_expr e.to_expr,\n prod.mk x <$> to_expr ``(@s_exists_intro _ _ %%q %%v %%p)\n | vs (assert_with_vars.prop e) :=\n do let x := assert_with_vars.leaf `(emp),\n p ← mk_meta_var e,\n prod.mk x <$> to_expr ``(s_imp_of_eq (eq.symm (embed_eq_emp %%p)))\n | vs (assert_with_vars.leaf e) :=\n do let e' := e.instantiate_vars vs.reverse,\n (r,u) ← mk_simp_set tt [] rules,\n (e'',p) ← conv.convert (conv.interactive.simp tt rules []\n { fail_if_unchanged := ff }) e',\n ast ← parse_assert_with_vars e'' ,\n (assert_with_vars.leaf _) ← pure ast | (do\n (x,p') ← hexists_to_meta_var [] ast,\n prod.mk x <$> to_expr ``(s_imp_trans _ %%p' (s_imp_of_eq (eq.symm %%p)))),\n prod.mk ast <$> to_expr ``(s_imp_of_eq (eq.symm %%p))\n\nmeta def parse_sep_assert' : expr → tactic (dlist expr)\n | `(%%e₀ :*: %%e₁) := (++) <$> parse_sep_assert' e₀ <*> parse_sep_assert' e₁\n | e := return $ dlist.singleton e\n\nmeta def parse_sep_assert : expr → tactic (list expr) :=\nmap dlist.to_list ∘ parse_sep_assert'\n\nmeta def match_sep' (unif : bool)\n: list expr → list expr → tactic (list expr × list expr × list expr)\n | es (x :: xs) := do\n es' ← delete_expr { unify := unif } x es,\n match es' with\n | (some es') := do\n (c,l,r) ← match_sep' es' xs, return (x::c,l,r)\n | none := do\n (c,l,r) ← match_sep' es xs, return (c,l,x::r)\n end\n | es [] := do\nreturn ([],es,[])\n\n/--\n`(common,left,right) ← match_sep unif l r` finds the commonalities\nbetween `l` and `r` and returns the differences -/\nmeta def match_sep (unif : bool) (l : list expr) (r : list expr)\n: tactic (list expr × list expr × list expr) :=\ndo (s',l',r') ← match_sep' unif l r,\n s' ← mmap instantiate_mvars s',\n l' ← mmap instantiate_mvars l',\n r' ← mmap instantiate_mvars r',\n return (s',l',r')\n\ndef expr_pat (t₀ t₁ : Type) : ℕ → Type\n | 0 := t₁\n | (succ n) := t₀ → expr_pat n\n\ndef tuple : ℕ → Type → Type\n | 0 _ := unit\n | 1 t := t\n | (succ n) t := t × tuple n t\n\nmeta def match_expr : ∀ (n : ℕ) (p : expr_pat expr pexpr n) (e : expr), tactic (tuple n expr)\n | 0 p e := to_expr p >>= unify e\n | 1 p e := do v ← mk_mvar, match_expr 0 (p v) e, instantiate_mvars v\n | (succ (succ n)) p e := do\nv ← mk_mvar,\nr ← match_expr (succ n) (p v) e,\ne ← instantiate_mvars v,\nreturn (e,r)\n\nmeta def reshuffle (e₀ e₁ : expr) : tactic unit := do\nt ← target,\n(t₀,t₁) ← match_eq t,\nh₀ ← to_expr ``(%%t₀ = %%e₀) >>= assert `h₀,\nsolve1 ac_refl,\nh₁ ← to_expr ``(%%t₁ = %%e₁) >>= assert `h₁,\nsolve1 admit,\n`[rw h₀],\n`[rw h₁],\ntactic.clear h₀, tactic.clear h₁\n\nmeta def find_match (pat : expr) : expr → list expr → tactic expr\n | e rest := do\n(unify e pat >> return (mk_sep_assert rest))\n<|>\n(do hprop ← to_expr ``(hprop),\n lv ← mk_meta_var hprop,\n rv ← mk_meta_var hprop,\n to_expr ``(%%lv :*: %%rv) >>= unify e,\n -- this unification could be generalized to:\n -- (le,re) ← match_pat (λ p₀ p₁, ``(%%p₀ :*: %%p₁))\n le ← instantiate_mvars lv,\n re ← instantiate_mvars rv,\n (find_match le (re :: rest) <|> find_match re (le :: rest)))\n<|>\ndo p ← pp pat,\n e ← pp e,\n fail $ to_fmt \"no match found for `\" ++ p ++ to_fmt \"` in: \\n`\" ++ e ++ to_fmt \"`\"\n\nmeta def sep_goal : tactic (expr × expr × expr) := do\ng ← target,\nt ← to_expr ``(hprop),\ne₀ ← mk_meta_var t,\ne₂ ← mk_meta_var t,\ne₃ ← mk_meta_var t,\npat ← to_expr ``(%%e₀ = %%e₂ :*: %%e₃) >>= unify g,\nprod.mk <$> instantiate_mvars e₀\n <*> (prod.mk <$> instantiate_mvars e₂\n <*> instantiate_mvars e₃)\n\n/-- Apply on a goal of the form\n ``x = y :*: m?``\n with m? a meta variable. The goal is to decompose `x` into a conjunction\n made of an occurrence of `y` (anywhere).\n -/\nmeta def match_assert : tactic unit := do\n(hp,pat,var) ← sep_goal,\ne ← find_match pat hp [],\nunify e var,\ntactic.target >>= instantiate_mvars >>= tactic.change,\ntry `[simp] >> ac_refl\n\n/-- apply on a goal of the form `sat p spec` -/\nmeta def extract_context_aux (h : name) (subst_flag : bool) : tactic unit :=\ndo `[apply precondition _],\n swap,\n `[symmetry],\n solve1 (do\n -- cxt ← mk_meta_var `(Prop),\n (hp,pat,var) ← sep_goal,\n to_expr ``( [| _ |] ) >>= unify pat,\n e ← find_match pat hp [],\n unify e var,\n tactic.target >>= instantiate_mvars >>= tactic.change,\n try `[simp],\n try ac_refl),\n `[apply context_left],\n x ← tactic.intro h,\n when subst_flag $ try (tactic.subst x),\n return ()\n\nmeta def subst_flag := (tk \"with\" *> tk \"subst\" *> pure tt) <|> return ff\n\nmeta def extract_context\n: parse ident* → ∀ (x : parse subst_flag), tactic unit\n | [] x := return ()\n | (h :: hs) x := extract_context_aux h x >> extract_context hs x\n\nmeta def match_sep_imp : expr → tactic (expr × expr)\n | `(%%e₀ =*> %%e₁) := return (e₀, e₁)\n | _ := fail \"expression is not an sep implication\"\n\nmeta def intro_unit (v : parse ident_?) : tactic unit :=\ndo e ← match v with\n | none := intro1\n | (some v) := tactic.intro v\n end,\n t ← infer_type e,\n if t = `(unit)\n then () <$ tactic.cases e\n else return ()\n\nmeta def simp_ptr_abstr : tactic unit :=\ndo abs ← attribute.get_instances `ptr_abstraction,\n abs' ← mmap (map simp_arg_type.expr ∘ resolve_name) abs,\n try (dsimp tt abs' [] (loc.ns [none])),\n try `[simp [s_and_s_exists_distr,s_exists_s_and_distr]\n { fail_if_unchanged := ff }]\n\nmeta def ac_match' : tactic unit :=\ndo abs ← attribute.get_instances `ptr_abstraction\n >>= mmap (map simp_arg_type.expr ∘ resolve_name),\n try (simp none tt abs [] (loc.ns [none])),\n try `[simp [s_and_s_exists_distr,s_exists_s_and_distr]\n { fail_if_unchanged := ff }],\n repeat `[apply s_exists_elim, intro_unit],\n repeat `[apply s_exists_intro],\n try (unfold_projs (loc.ns [])),\n done <|> focus1 (do\n repeat `[rw [embed_eq_emp],\n simp { fail_if_unchanged := ff } ],\n all_goals (try assumption)),\n done <|> (do\n solve1 (do\n try `[apply s_imp_of_eq],\n t ← target,\n (e₀,e₁) ← match_eq t,\n e₀ ← parse_sep_assert e₀,\n e₁ ← parse_sep_assert e₁,\n (c,l,r) ← match_sep ff e₀ e₁,\n (c',l',r') ← match_sep tt l r,\n (c'',l',r') ← match_sep tt l' r',\n let ll := l'.length,\n let rl := r'.length,\n let l'' := l' ++ list.repeat `(emp) (rl - ll),\n h ← assert `h `(%%(mk_sep_assert l'') = (%%(mk_sep_assert r') : hprop)),\n solve1 tactic.reflexivity,\n target >>= instantiate_mvars >>= tactic.change,\n try `[simp { fail_if_unchanged := ff }],\n try `[rw s_and_comm, try { refl }],\n try ac_refl))\n\nmeta def ac_match : tactic unit := do\nac_match'\n\nexample (e₁ e₂ e₃ : hprop)\n: e₁ :*: e₂ :*: e₃ = e₂ :*: e₃ :*: e₁ :=\nbegin\n ac_mono1,\n exact @rfl _ emp\nend\n\ndef replicate {m : Type u → Type v} [monad m] {α} : ℕ → m α → m (list α)\n | 0 _ := return []\n | (succ n) m := lift₂ cons m (replicate n m)\n\nprivate meta def get_pi_expl_arity_aux (t : expr) : expr → expr → tactic expr\n| e r := do\n(unify t e >> instantiate_mvars r)\n<|>\nmatch e with\n| (expr.pi n bi d b) :=\n do m ← mk_fresh_name,\n-- let l := expr.local_const m n bi d,\n l ← mk_meta_var d,\n new_b ← instantiate_mvars (expr.instantiate_var b l),\n\n if binder_info.default = bi\n then get_pi_expl_arity_aux new_b (r l)\n else get_pi_expl_arity_aux new_b r\n| e := instantiate_mvars r\nend\n\n/-- Compute the arity of the given (Pi-)type -/\nmeta def get_pi_expl_arity (target e : expr) : tactic expr := do\nt ← infer_type e,\nget_pi_expl_arity_aux target t e\n\nmeta def s_exists1 (v : parse ident) : tactic unit := do\n`[ simp [s_exists_s_and_distr,s_and_s_exists_distr] { fail_if_unchanged := ff }\n , apply s_exists_intro_pre],\nintro v, return ()\n\nmeta def s_exists (vs : parse ident*) : tactic unit :=\nmmap' s_exists1 vs\n\nmeta def s_intros : parse ident* → parse subst_flag → tactic unit\n | [] _ := return ()\n | (x :: xs) sbst := do\nv ← tactic.try_core (s_exists1 x),\nmatch v with\n | (some _) := s_intros xs sbst\n | none := extract_context (x :: xs) sbst\nend\n\nmeta def decide : tactic unit := do\nsolve1 $ do\n `[apply of_as_true],\n triv\n\nmeta def bind_step (spec_thm : parse texpr? ) (ids : parse with_ident_list) : tactic unit :=\ndo g ← target,\n (hd,tl,spec) ← (match_expr 3 (λ e₀ e₁ s, ``(sat (%%e₀ >>= %%e₁) %%s)) g\n : tactic (expr × expr × expr)),\n let (cmd,args) := hd.get_app_fn_args,\n let s : option _ := spec_thm,\n e ← (resolve_name (cmd.const_name <.> \"spec\") >>= to_expr) <| (to_expr <$> s),\n r ← to_expr ``(sat _ _),\n e' ← get_pi_expl_arity r e,\n `[apply (bind_framing_left _ %%e')],\n solve1 (try `[simp [s_and_assoc]] >> try ac_match'),\n all_goals (try `[apply of_as_true, apply trivial]),\n (v,ids) ← return $ match ids with\n | [] := (none,[])\n | (id :: ids) := (some id, ids)\n end,\n intro_unit v, `[simp],\n s_intros ids tt\n\nopen option\n\nmeta def simp_h_entails : tactic unit :=\ndo `(%%p =*> %%q) ← target,\n r ← parse_assert_with_vars q,\n abs ← attribute.get_instances `ptr_abstraction,\n abs' ← mmap (map (simp_arg_type.expr ∘ to_pexpr) ∘ resolve_name) abs,\n (_,p) ← hexists_to_meta_var abs' [] r,\n h ← mk_meta_var `(hprop),\n g ← mk_mvar,\n p' ← to_expr ``(s_imp_trans %%h %%g %%p),\n t ← target,\n infer_type p' >>= unify t,\n gs ← get_goals,\n\n set_goals [g],\n (applyc `separation.s_imp_of_eq >> ac_match'),\n done,\n set_goals gs,\n () <$ tactic.apply p' { new_goals := new_goals.non_dep_only }\n\nmeta def last_step' (s : parse texpr?) : tactic unit :=\nsolve1 $\ndo `(sat %%hd %%spec) ← target,\n let (cmd,args) := hd.get_app_fn_args,\n e ← (resolve_name (cmd.const_name <.> \"spec\") >>= to_expr) <| (to_expr <$> s),\n r ← to_expr ``(sat _ _),\n e' ← get_pi_expl_arity r e,\n p₀ ← mk_mvar,\n p₁ ← mk_mvar,\n r ← to_expr ``(framing_spec' _ %%e' %%p₀ %%p₁),\n t ← target,\n infer_type r >>= unify t,\n gs ← get_goals,\n set_goals [p₀],\n simp_h_entails,\n all_goals (try $ `[apply of_as_true, apply trivial] <|> solve_by_elim),\n done,\n set_goals [p₁],\n intro1,\n simp_h_entails,\n all_goals (try $ `[apply of_as_true, apply trivial] <|> solve_by_elim),\n done,\n set_goals gs,\n tactic.apply r,\n return ()\n\nmeta def last_step (spec : parse texpr?) : tactic unit :=\ndo last_step' spec,\n solve1 (do\n try `[simp [s_and_assoc]],\n ac_match') <|> fail \"first solve1\",\n solve1 (do\n intro_unit `_,\n ac_match',\n all_goals (try assumption)) <|> fail \"second solve1\",\n all_goals (try $ `[apply of_as_true, apply trivial] <|> solve_by_elim)\n\n-- meta def himp_zoom : tactic unit :=\n-- do `(%%lhs =*> %%rhs) ← target | failed,\n-- ls ← parse_sep_assert lhs,\n-- rs ← parse_sep_assert rhs,\n-- (s,l,r) ← match_sep ff ls rs,\n-- let s' := mk_sep_assert s,\n-- let lhs' := mk_sep_assert (l ++ s),\n-- let rhs' := mk_sep_assert (r ++ s),\n-- h ← to_expr ``(%%(mk_sep_assert l) =*> %%(mk_sep_assert r))\n-- >>= assert `h,\n-- tactic.swap,\n-- prf ← to_expr ``(s_and_s_imp_s_and_right %%(mk_sep_assert s) %%h),\n-- note `h none prf,\n-- return ()\n\nexample (e₁ e₂ e₃ e₄ e₅ e₆ : hprop)\n (h : e₃ :*: e₁ :*: e₅ :*: e₄ =*> e₆)\n: e₃ :*: e₁ :*: e₅ :*: e₂ :*: e₄ =*> e₂ :*: e₆ :=\nbegin\n ac_mono1,\n solve_by_elim\nend\n\nexample (e₁ e₂ e₃ e₄ e₅ e₆ : hprop)\n (h : e₁ :*: e₅ :*: e₄ =*> emp)\n: e₃ :*: e₁ :*: e₅ :*: e₂ :*: e₄ =*> e₂ :*: e₃ :=\nbegin\n ac_mono1,\n solve_by_elim\nend\n\nend tactic.interactive\n", "meta": {"author": "unitb", "repo": "separation-logic", "sha": "bdde6fc8f16fd43932aea9827d6c63cadd91c2e8", "save_path": "github-repos/lean/unitb-separation-logic", "path": "github-repos/lean/unitb-separation-logic/separation-logic-bdde6fc8f16fd43932aea9827d6c63cadd91c2e8/src/separation/tactic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.37754066879814546, "lm_q2_score": 0.02931222947940706, "lm_q1q2_score": 0.011066558721620058}} {"text": "/-\nCopyright (c) 2019 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Simon Hudon\n\nThe writer monad transformer for passing immutable state.\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.default\nimport Mathlib.control.monad.basic\nimport Mathlib.algebra.group.basic\nimport Mathlib.PostPort\n\nuniverses u v l u_1 u_2 u_3 u₀ u₁ v₀ v₁ \n\nnamespace Mathlib\n\nstructure writer_t (ω : Type u) (m : Type u → Type v) (α : Type u) where\n run : m (α × ω)\n\ndef writer (ω : Type u) (α : Type u) := writer_t ω id\n\nnamespace writer_t\n\n\nprotected theorem ext {ω : Type u} {m : Type u → Type v} [Monad m] {α : Type u} (x : writer_t ω m α)\n (x' : writer_t ω m α) (h : run x = run x') : x = x' :=\n sorry\n\nprotected def tell {ω : Type u} {m : Type u → Type v} [Monad m] (w : ω) : writer_t ω m PUnit :=\n mk (pure (PUnit.unit, w))\n\nprotected def listen {ω : Type u} {m : Type u → Type v} [Monad m] {α : Type u} :\n writer_t ω m α → writer_t ω m (α × ω) :=\n sorry\n\nprotected def pass {ω : Type u} {m : Type u → Type v} [Monad m] {α : Type u} :\n writer_t ω m (α × (ω → ω)) → writer_t ω m α :=\n sorry\n\nprotected def pure {ω : Type u} {m : Type u → Type v} [Monad m] {α : Type u} [HasOne ω] (a : α) :\n writer_t ω m α :=\n mk (pure (a, 1))\n\nprotected def bind {ω : Type u} {m : Type u → Type v} [Monad m] {α : Type u} {β : Type u} [Mul ω]\n (x : writer_t ω m α) (f : α → writer_t ω m β) : writer_t ω m β :=\n mk\n (do \n let x ← run x \n let x' ← run (f (prod.fst x))\n pure (prod.fst x', prod.snd x * prod.snd x'))\n\nprotected instance monad {ω : Type u} {m : Type u → Type v} [Monad m] [HasOne ω] [Mul ω] :\n Monad (writer_t ω m) :=\n sorry\n\nprotected instance is_lawful_monad {ω : Type u} {m : Type u → Type v} [Monad m] [monoid ω]\n [is_lawful_monad m] : is_lawful_monad (writer_t ω m) :=\n sorry\n\nprotected def lift {ω : Type u} {m : Type u → Type v} [Monad m] {α : Type u} [HasOne ω] (a : m α) :\n writer_t ω m α :=\n mk (flip Prod.mk 1 <$> a)\n\nprotected instance has_monad_lift {ω : Type u} (m : Type u → Type u_1) [Monad m] [HasOne ω] :\n has_monad_lift m (writer_t ω m) :=\n has_monad_lift.mk fun (α : Type u) => writer_t.lift\n\nprotected def monad_map {ω : Type u} {m : Type u → Type u_1} {m' : Type u → Type u_2} [Monad m]\n [Monad m'] {α : Type u} (f : {α : Type u} → m α → m' α) : writer_t ω m α → writer_t ω m' α :=\n fun (x : writer_t ω m α) => mk (f (run x))\n\nprotected instance monad_functor {ω : Type u} (m : Type u → Type u_1) (m' : Type u → Type u_1)\n [Monad m] [Monad m'] : monad_functor m m' (writer_t ω m) (writer_t ω m') :=\n monad_functor.mk writer_t.monad_map\n\nprotected def adapt {ω : Type u} {m : Type u → Type v} [Monad m] {ω' : Type u} {α : Type u}\n (f : ω → ω') : writer_t ω m α → writer_t ω' m α :=\n fun (x : writer_t ω m α) => mk (prod.map id f <$> run x)\n\nprotected instance monad_except {ω : Type u} {m : Type u → Type v} [Monad m]\n (ε : outParam (Type u_1)) [HasOne ω] [Monad m] [monad_except ε m] :\n monad_except ε (writer_t ω m) :=\n monad_except.mk (fun (α : Type u) => writer_t.lift ∘ throw)\n fun (α : Type u) (x : writer_t ω m α) (c : ε → writer_t ω m α) =>\n mk (catch (run x) fun (e : ε) => run (c e))\n\nend writer_t\n\n\n/--\nAn implementation of [MonadReader](\nhttps://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-Reader-Class.html#t:MonadReader).\nIt does not contain `local` because this function cannot be lifted using `monad_lift`.\nInstead, the `monad_reader_adapter` class provides the more general `adapt_reader` function.\n\nNote: This class can be seen as a simplification of the more \"principled\" definition\n```\nclass monad_reader (ρ : out_param (Type u)) (n : Type u → Type u) :=\n(lift {α : Type u} : (∀ {m : Type u → Type u} [monad m], reader_t ρ m α) → n α)\n```\n-/\nclass monad_writer (ω : outParam (Type u)) (m : Type u → Type v) where\n tell : ω → m PUnit\n listen : {α : Type u} → m α → m (α × ω)\n pass : {α : Type u} → m (α × (ω → ω)) → m α\n\nprotected instance writer_t.monad_writer {ω : Type u} {m : Type u → Type v} [Monad m] :\n monad_writer ω (writer_t ω m) :=\n monad_writer.mk writer_t.tell (fun (α : Type u) => writer_t.listen)\n fun (α : Type u) => writer_t.pass\n\nprotected instance reader_t.monad_writer {ω : Type u} {ρ : Type u} {m : Type u → Type v} [Monad m]\n [monad_writer ω m] : monad_writer ω (reader_t ρ m) :=\n monad_writer.mk (fun (x : ω) => monad_lift (monad_writer.tell x))\n (fun (α : Type u) (_x : reader_t ρ m α) => sorry)\n fun (α : Type u) (_x : reader_t ρ m (α × (ω → ω))) => sorry\n\ndef swap_right {α : Type u_1} {β : Type u_2} {γ : Type u_3} : (α × β) × γ → (α × γ) × β := sorry\n\nprotected instance state_t.monad_writer {ω : Type u} {σ : Type u} {m : Type u → Type v} [Monad m]\n [monad_writer ω m] : monad_writer ω (state_t σ m) :=\n monad_writer.mk (fun (x : ω) => monad_lift (monad_writer.tell x))\n (fun (α : Type u) (_x : state_t σ m α) => sorry)\n fun (α : Type u) (_x : state_t σ m (α × (ω → ω))) => sorry\n\ndef except_t.pass_aux {ε : Type u_1} {α : Type u_2} {ω : Type u_3} :\n except ε (α × (ω → ω)) → except ε α × (ω → ω) :=\n sorry\n\nprotected instance except_t.monad_writer {ω : Type u} {ε : Type u} {m : Type u → Type v} [Monad m]\n [monad_writer ω m] : monad_writer ω (except_t ε m) :=\n monad_writer.mk (fun (x : ω) => monad_lift (monad_writer.tell x))\n (fun (α : Type u) (_x : except_t ε m α) => sorry)\n fun (α : Type u) (_x : except_t ε m (α × (ω → ω))) => sorry\n\ndef option_t.pass_aux {α : Type u_1} {ω : Type u_2} : Option (α × (ω → ω)) → Option α × (ω → ω) :=\n sorry\n\nprotected instance option_t.monad_writer {ω : Type u} {m : Type u → Type v} [Monad m]\n [monad_writer ω m] : monad_writer ω (option_t m) :=\n monad_writer.mk (fun (x : ω) => monad_lift (monad_writer.tell x))\n (fun (α : Type u) (_x : option_t m α) => sorry)\n fun (α : Type u) (_x : option_t m (α × (ω → ω))) => sorry\n\n/-- Adapt a monad stack, changing the type of its top-most environment.\n\nThis class is comparable to\n[Control.Lens.Magnify](https://hackage.haskell.org/package/lens-4.15.4/docs/Control-Lens-Zoom.html#t:Magnify),\nbut does not use lenses (why would it), and is derived automatically for any transformer\nimplementing `monad_functor`.\n\nNote: This class can be seen as a simplification of the more \"principled\" definition\n```\nclass monad_reader_functor (ρ ρ' : out_param (Type u)) (n n' : Type u → Type u) :=\n(map {α : Type u} : (∀ {m : Type u → Type u} [monad m], reader_t ρ m α → reader_t ρ' m α) → n α → n' α)\n```\n-/\nclass monad_writer_adapter (ω : outParam (Type u)) (ω' : outParam (Type u)) (m : Type u → Type v)\n (m' : Type u → Type v)\n where\n adapt_writer : {α : Type u} → (ω → ω') → m α → m' α\n\n/-- Transitivity.\n\nThis instance generates the type-class problem with a metavariable argument (which is why this\nis marked as `[nolint dangerous_instance]`).\nCurrently that is not a problem, as there are almost no instances of `monad_functor` or\n`monad_writer_adapter`.\n\nsee Note [lower instance priority] -/\nprotected instance monad_writer_adapter_trans {ω : Type u} {ω' : Type u} {m : Type u → Type v}\n {m' : Type u → Type v} {n : Type u → Type v} {n' : Type u → Type v}\n [monad_writer_adapter ω ω' m m'] [monad_functor m m' n n'] : monad_writer_adapter ω ω' n n' :=\n monad_writer_adapter.mk\n fun (α : Type u) (f : ω → ω') => monad_map fun (α : Type u) => adapt_writer f\n\nprotected instance writer_t.monad_writer_adapter {ω : Type u} {ω' : Type u} {m : Type u → Type v}\n [Monad m] : monad_writer_adapter ω ω' (writer_t ω m) (writer_t ω' m) :=\n monad_writer_adapter.mk fun (α : Type u) => writer_t.adapt\n\nprotected instance writer_t.monad_run (ω : Type u) (m : Type u → Type (max u u_1))\n (out : outParam (Type u → Type (max u u_1))) [monad_run out m] :\n monad_run (fun (α : Type u) => out (α × ω)) (writer_t ω m) :=\n monad_run.mk fun (α : Type u) (x : writer_t ω m α) => run (writer_t.run x)\n\n/-- reduce the equivalence between two writer monads to the equivalence between\ntheir underlying monad -/\ndef writer_t.equiv {m₁ : Type u₀ → Type v₀} {m₂ : Type u₁ → Type v₁} {α₁ : Type u₀} {ω₁ : Type u₀}\n {α₂ : Type u₁} {ω₂ : Type u₁} (F : m₁ (α₁ × ω₁) ≃ m₂ (α₂ × ω₂)) :\n writer_t ω₁ m₁ α₁ ≃ writer_t ω₂ m₂ α₂ :=\n equiv.mk (fun (_x : writer_t ω₁ m₁ α₁) => sorry) (fun (_x : writer_t ω₂ m₂ α₂) => sorry) sorry\n sorry\n\nend Mathlib", "meta": {"author": "AurelienSaue", "repo": "Mathlib4_auto", "sha": "590df64109b08190abe22358fabc3eae000943f2", "save_path": "github-repos/lean/AurelienSaue-Mathlib4_auto", "path": "github-repos/lean/AurelienSaue-Mathlib4_auto/Mathlib4_auto-590df64109b08190abe22358fabc3eae000943f2/Mathlib/control/monad/writer_auto.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.29421497216298875, "lm_q2_score": 0.03732688948593844, "lm_q1q2_score": 0.010982129751036336}} {"text": "/-\nCopyright (c) 2020 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Leonardo de Moura\n-/\nimport Lean.ScopedEnvExtension\nimport Lean.Util.Recognizers\nimport Lean.Meta.DiscrTree\nimport Lean.Meta.AppBuilder\nimport Lean.Meta.Eqns\nimport Lean.Meta.Tactic.AuxLemma\nnamespace Lean.Meta\n\n/--\n The fields `levelParams` and `proof` are used to encode the proof of the simp theorem.\n If the `proof` is a global declaration `c`, we store `Expr.const c []` at `proof` without the universe levels, and `levelParams` is set to `#[]`\n When using the lemma, we create fresh universe metavariables.\n Motivation: most simp theorems are global declarations, and this approach is faster and saves memory.\n\n The field `levelParams` is not empty only when we elaborate an expression provided by the user, and it contains universe metavariables.\n Then, we use `abstractMVars` to abstract the universe metavariables and create new fresh universe parameters that are stored at the field `levelParams`.\n-/\nstructure SimpTheorem where\n keys : Array DiscrTree.Key := #[]\n levelParams : Array Name := #[] -- non empty for local universe polymorphic proofs.\n proof : Expr\n priority : Nat := eval_prio default\n post : Bool := true\n perm : Bool := false -- true is lhs and rhs are identical modulo permutation of variables\n name? : Option Name := none -- for debugging and tracing purposes\n deriving Inhabited\n\ndef SimpTheorem.getName (s : SimpTheorem) : Name :=\n match s.name? with\n | some n => n\n | none => \"\"\n\ninstance : ToFormat SimpTheorem where\n format s :=\n let perm := if s.perm then \":perm\" else \"\"\n let name := format s.getName\n let prio := f!\":{s.priority}\"\n name ++ prio ++ perm\n\ninstance : ToMessageData SimpTheorem where\n toMessageData s := format s\n\ninstance : BEq SimpTheorem where\n beq e₁ e₂ := e₁.proof == e₂.proof\n\nstructure SimpTheorems where\n pre : DiscrTree SimpTheorem := DiscrTree.empty\n post : DiscrTree SimpTheorem := DiscrTree.empty\n lemmaNames : Std.PHashSet Name := {}\n toUnfold : Std.PHashSet Name := {}\n erased : Std.PHashSet Name := {}\n toUnfoldThms : Std.PHashMap Name (Array Name) := {}\n deriving Inhabited\n\ndef addSimpTheoremEntry (d : SimpTheorems) (e : SimpTheorem) : SimpTheorems :=\n if e.post then\n { d with post := d.post.insertCore e.keys e, lemmaNames := updateLemmaNames d.lemmaNames }\n else\n { d with pre := d.pre.insertCore e.keys e, lemmaNames := updateLemmaNames d.lemmaNames }\nwhere\n updateLemmaNames (s : Std.PHashSet Name) : Std.PHashSet Name :=\n match e.name? with\n | none => s\n | some name => s.insert name\n\ndef SimpTheorems.addDeclToUnfoldCore (d : SimpTheorems) (declName : Name) : SimpTheorems :=\n { d with toUnfold := d.toUnfold.insert declName }\n\n/-- Return `true` if `declName` is tagged to be unfolded using `unfoldDefinition?` (i.e., without using equational theorems). -/\ndef SimpTheorems.isDeclToUnfold (d : SimpTheorems) (declName : Name) : Bool :=\n d.toUnfold.contains declName\n\ndef SimpTheorems.isLemma (d : SimpTheorems) (declName : Name) : Bool :=\n d.lemmaNames.contains declName\n\n/-- Register the equational theorems for the given definition. -/\ndef SimpTheorems.registerDeclToUnfoldThms (d : SimpTheorems) (declName : Name) (eqThms : Array Name) : SimpTheorems :=\n { d with toUnfoldThms := d.toUnfoldThms.insert declName eqThms }\n\npartial def SimpTheorems.eraseCore (d : SimpTheorems) (declName : Name) : SimpTheorems :=\n let d := { d with erased := d.erased.insert declName, lemmaNames := d.lemmaNames.erase declName, toUnfold := d.toUnfold.erase declName }\n if let some thms := d.toUnfoldThms.find? declName then\n thms.foldl (init := d) eraseCore\n else\n d\n\ndef SimpTheorems.erase [Monad m] [MonadError m] (d : SimpTheorems) (declName : Name) : m SimpTheorems := do\n unless d.isLemma declName || d.isDeclToUnfold declName || d.toUnfoldThms.contains declName do\n throwError \"'{declName}' does not have [simp] attribute\"\n return d.eraseCore declName\n\nprivate partial def isPerm : Expr → Expr → MetaM Bool\n | Expr.app f₁ a₁ _, Expr.app f₂ a₂ _ => isPerm f₁ f₂ <&&> isPerm a₁ a₂\n | Expr.mdata _ s _, t => isPerm s t\n | s, Expr.mdata _ t _ => isPerm s t\n | s@(Expr.mvar ..), t@(Expr.mvar ..) => isDefEq s t\n | Expr.forallE n₁ d₁ b₁ _, Expr.forallE n₂ d₂ b₂ _ => isPerm d₁ d₂ <&&> withLocalDeclD n₁ d₁ fun x => isPerm (b₁.instantiate1 x) (b₂.instantiate1 x)\n | Expr.lam n₁ d₁ b₁ _, Expr.lam n₂ d₂ b₂ _ => isPerm d₁ d₂ <&&> withLocalDeclD n₁ d₁ fun x => isPerm (b₁.instantiate1 x) (b₂.instantiate1 x)\n | Expr.letE n₁ t₁ v₁ b₁ _, Expr.letE n₂ t₂ v₂ b₂ _ =>\n isPerm t₁ t₂ <&&> isPerm v₁ v₂ <&&> withLetDecl n₁ t₁ v₁ fun x => isPerm (b₁.instantiate1 x) (b₂.instantiate1 x)\n | Expr.proj _ i₁ b₁ _, Expr.proj _ i₂ b₂ _ => pure (i₁ == i₂) <&&> isPerm b₁ b₂\n | s, t => return s == t\n\nprivate def checkBadRewrite (lhs rhs : Expr) : MetaM Unit := do\n let lhs ← DiscrTree.whnfDT lhs (root := true)\n if lhs == rhs && lhs.isFVar then\n throwError \"invalid `simp` theorem, equation is equivalent to{indentExpr (← mkEq lhs rhs)}\"\n\nprivate partial def shouldPreprocess (type : Expr) : MetaM Bool :=\n forallTelescopeReducing type fun xs result => do\n if let some (_, lhs, rhs) := result.eq? then\n checkBadRewrite lhs rhs\n return false\n else\n return true\n\nprivate partial def preprocess (e type : Expr) (inv : Bool) (isGlobal : Bool) : MetaM (List (Expr × Expr)) :=\n go e type\nwhere\n go (e type : Expr) : MetaM (List (Expr × Expr)) := do\n let type ← whnf type\n if type.isForall then\n forallTelescopeReducing type fun xs type => do\n let e := mkAppN e xs\n let ps ← go e type\n ps.mapM fun (e, type) =>\n return (← mkLambdaFVars xs e, ← mkForallFVars xs type)\n else if let some (_, lhs, rhs) := type.eq? then\n if isGlobal then\n checkBadRewrite lhs rhs\n if inv then\n let type ← mkEq rhs lhs\n let e ← mkEqSymm e\n return [(e, type)]\n else\n return [(e, type)]\n else if let some (lhs, rhs) := type.iff? then\n if isGlobal then\n checkBadRewrite lhs rhs\n if inv then\n let type ← mkEq rhs lhs\n let e ← mkEqSymm (← mkPropExt e)\n return [(e, type)]\n else\n let type ← mkEq lhs rhs\n let e ← mkPropExt e\n return [(e, type)]\n else if let some (_, lhs, rhs) := type.ne? then\n if inv then\n throwError \"invalid '←' modifier in rewrite rule to 'False'\"\n let type ← mkEq (← mkEq lhs rhs) (mkConst ``False)\n let e ← mkEqFalse e\n return [(e, type)]\n else if let some p := type.not? then\n if inv then\n throwError \"invalid '←' modifier in rewrite rule to 'False'\"\n let type ← mkEq p (mkConst ``False)\n let e ← mkEqFalse e\n return [(e, type)]\n else if let some (type₁, type₂) := type.and? then\n let e₁ := mkProj ``And 0 e\n let e₂ := mkProj ``And 1 e\n return (← go e₁ type₁) ++ (← go e₂ type₂)\n else\n if inv then\n throwError \"invalid '←' modifier in rewrite rule to 'True'\"\n let type ← mkEq type (mkConst ``True)\n let e ← mkEqTrue e\n return [(e, type)]\n\nprivate def checkTypeIsProp (type : Expr) : MetaM Unit :=\n unless (← isProp type) do\n throwError \"invalid 'simp', proposition expected{indentExpr type}\"\n\nprivate def mkSimpTheoremCore (e : Expr) (levelParams : Array Name) (proof : Expr) (post : Bool) (prio : Nat) (name? : Option Name) : MetaM SimpTheorem := do\n let type ← instantiateMVars (← inferType e)\n withNewMCtxDepth do\n let (xs, _, type) ← withReducible <| forallMetaTelescopeReducing type\n let type ← whnfR type\n let (keys, perm) ←\n match type.eq? with\n | some (_, lhs, rhs) => pure (← DiscrTree.mkPath lhs, ← isPerm lhs rhs)\n | none => throwError \"unexpected kind of 'simp' theorem{indentExpr type}\"\n return { keys := keys, perm := perm, post := post, levelParams := levelParams, proof := proof, name? := name?, priority := prio }\n\nprivate def mkSimpTheoremsFromConst (declName : Name) (post : Bool) (inv : Bool) (prio : Nat) : MetaM (Array SimpTheorem) := do\n let cinfo ← getConstInfo declName\n let val := mkConst declName (cinfo.levelParams.map mkLevelParam)\n withReducible do\n let type ← inferType val\n checkTypeIsProp type\n if inv || (← shouldPreprocess type) then\n let mut r := #[]\n for (val, type) in (← preprocess val type inv (isGlobal := true)) do\n let auxName ← mkAuxLemma cinfo.levelParams type val\n r := r.push <| (← mkSimpTheoremCore (mkConst auxName (cinfo.levelParams.map mkLevelParam)) #[] (mkConst auxName) post prio declName)\n return r\n else\n return #[← mkSimpTheoremCore (mkConst declName (cinfo.levelParams.map mkLevelParam)) #[] (mkConst declName) post prio declName]\n\ninductive SimpEntry where\n | thm : SimpTheorem → SimpEntry\n | toUnfold : Name → SimpEntry\n | toUnfoldThms : Name → Array Name → SimpEntry\n deriving Inhabited\n\nabbrev SimpExtension := SimpleScopedEnvExtension SimpEntry SimpTheorems\n\ndef SimpExtension.getTheorems (ext : SimpExtension) : CoreM SimpTheorems :=\n return ext.getState (← getEnv)\n\ndef addSimpTheorem (ext : SimpExtension) (declName : Name) (post : Bool) (inv : Bool) (attrKind : AttributeKind) (prio : Nat) : MetaM Unit := do\n let simpThms ← mkSimpTheoremsFromConst declName post inv prio\n for simpThm in simpThms do\n ext.add (SimpEntry.thm simpThm) attrKind\n\ndef mkSimpAttr (attrName : Name) (attrDescr : String) (ext : SimpExtension) : IO Unit :=\n registerBuiltinAttribute {\n name := attrName\n descr := attrDescr\n applicationTime := AttributeApplicationTime.afterCompilation\n add := fun declName stx attrKind =>\n let go : MetaM Unit := do\n let info ← getConstInfo declName\n let post := if stx[1].isNone then true else stx[1][0].getKind == ``Lean.Parser.Tactic.simpPost\n let prio ← getAttrParamOptPrio stx[2]\n if (← isProp info.type) then\n addSimpTheorem ext declName post (inv := false) attrKind prio\n else if info.hasValue then\n if let some eqns ← getEqnsFor? declName then\n for eqn in eqns do\n addSimpTheorem ext eqn post (inv := false) attrKind prio\n ext.add (SimpEntry.toUnfoldThms declName eqns) attrKind\n if hasSmartUnfoldingDecl (← getEnv) declName then\n ext.add (SimpEntry.toUnfold declName) attrKind\n else\n ext.add (SimpEntry.toUnfold declName) attrKind\n else\n throwError \"invalid 'simp', it is not a proposition nor a definition (to unfold)\"\n discard <| go.run {} {}\n erase := fun declName => do\n let s := ext.getState (← getEnv)\n let s ← s.erase declName\n modifyEnv fun env => ext.modifyState env fun _ => s\n }\n\ndef mkSimpExt (extName : Name) : IO SimpExtension :=\n registerSimpleScopedEnvExtension {\n name := extName\n initial := {}\n addEntry := fun d e =>\n match e with\n | SimpEntry.thm e => addSimpTheoremEntry d e\n | SimpEntry.toUnfold n => d.addDeclToUnfoldCore n\n | SimpEntry.toUnfoldThms n thms => d.registerDeclToUnfoldThms n thms\n }\n\ndef registerSimpAttr (attrName : Name) (attrDescr : String) (extName : Name := attrName.appendAfter \"Ext\") : IO SimpExtension := do\n let ext ← mkSimpExt extName\n mkSimpAttr attrName attrDescr ext\n return ext\n\nbuiltin_initialize simpExtension : SimpExtension ← registerSimpAttr `simp \"simplification theorem\"\n\ndef getSimpTheorems : CoreM SimpTheorems :=\n simpExtension.getTheorems\n\n/- Auxiliary method for adding a global declaration to a `SimpTheorems` datastructure. -/\ndef SimpTheorems.addConst (s : SimpTheorems) (declName : Name) (post : Bool := true) (inv : Bool := false) (prio : Nat := eval_prio default) : MetaM SimpTheorems := do\n let s := { s with erased := s.erased.erase declName }\n let simpThms ← mkSimpTheoremsFromConst declName post inv prio\n return simpThms.foldl addSimpTheoremEntry s\n\ndef SimpTheorem.getValue (simpThm : SimpTheorem) : MetaM Expr := do\n if simpThm.proof.isConst && simpThm.levelParams.isEmpty then\n let info ← getConstInfo simpThm.proof.constName!\n if info.levelParams.isEmpty then\n return simpThm.proof\n else\n return simpThm.proof.updateConst! (← info.levelParams.mapM (fun _ => mkFreshLevelMVar))\n else\n let us ← simpThm.levelParams.mapM fun _ => mkFreshLevelMVar\n return simpThm.proof.instantiateLevelParamsArray simpThm.levelParams us\n\nprivate def preprocessProof (val : Expr) (inv : Bool) : MetaM (Array Expr) := do\n let type ← inferType val\n checkTypeIsProp type\n let ps ← preprocess val type inv (isGlobal := false)\n return ps.toArray.map fun (val, _) => val\n\n/- Auxiliary method for creating simp theorems from a proof term `val`. -/\ndef mkSimpTheorems (levelParams : Array Name) (proof : Expr) (post : Bool := true) (inv : Bool := false) (prio : Nat := eval_prio default) (name? : Option Name := none): MetaM (Array SimpTheorem) :=\n withReducible do\n (← preprocessProof proof inv).mapM fun val => mkSimpTheoremCore val levelParams val post prio name?\n\n/- Auxiliary method for adding a local simp theorem to a `SimpTheorems` datastructure. -/\ndef SimpTheorems.add (s : SimpTheorems) (levelParams : Array Name) (proof : Expr) (inv : Bool := false) (post : Bool := true) (prio : Nat := eval_prio default) (name? : Option Name := none): MetaM SimpTheorems := do\n if proof.isConst then\n s.addConst proof.constName! post inv prio\n else\n let simpThms ← mkSimpTheorems levelParams proof post inv prio (← getName? proof)\n return simpThms.foldl addSimpTheoremEntry s\nwhere\n getName? (e : Expr) : MetaM (Option Name) := do\n match name? with\n | some _ => return name?\n | none =>\n let f := e.getAppFn\n if f.isConst then\n return f.constName!\n else if f.isFVar then\n let localDecl ← getFVarLocalDecl f\n return localDecl.userName\n else\n return none\n\ndef SimpTheorems.addDeclToUnfold (d : SimpTheorems) (declName : Name) : MetaM SimpTheorems :=\n withLCtx {} {} do\n if let some eqns ← getEqnsFor? declName then\n let mut d := d\n for eqn in eqns do\n d ← SimpTheorems.addConst d eqn\n if hasSmartUnfoldingDecl (← getEnv) declName then\n d := d.addDeclToUnfoldCore declName\n return d\n else\n return d.addDeclToUnfoldCore declName\n\nend Lean.Meta\n", "meta": {"author": "Kha", "repo": "lean4-nightly", "sha": "b4c92de57090e6c47b29d3575df53d86fce52752", "save_path": "github-repos/lean/Kha-lean4-nightly", "path": "github-repos/lean/Kha-lean4-nightly/lean4-nightly-b4c92de57090e6c47b29d3575df53d86fce52752/stage0/src/Lean/Meta/Tactic/Simp/SimpTheorems.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.256831980010821, "lm_q2_score": 0.042722196175311436, "lm_q1q2_score": 0.010972426234115961}} {"text": "import syntax\nimport typing_relation\nimport semantics\n\nimport category_theory.closed.cartesian\nimport category_theory.limits.shapes.binary_products\n\nnamespace term_equality\n\nopen term type typing_relation\nopen category_theory category_theory.limits\n\nvariables {con gnd fv : Type} [fvar fv] [const con gnd]\nvariables {con_type : con → type gnd}\n\nvariables {𝓒 : Type} [category 𝓒] \n [limits.has_finite_products 𝓒] [cartesian_closed 𝓒]\n\ninductive beta_eta_eq (con_type : con → type gnd)\n: env gnd fv → term gnd con fv → term gnd con fv → type gnd → Type\n| Refl : ∀ {Γ t A},\n(Γ ⊩ t ∷ A)\n-----------------------\n→ beta_eta_eq Γ t t A \n\n| Symm : ∀ {Γ t1 t2 A},\nbeta_eta_eq Γ t1 t2 A\n------------------------\n→ beta_eta_eq Γ t2 t1 A \n\n| Trans : ∀ {Γ t1 t2 t3 A},\nbeta_eta_eq Γ t1 t2 A → beta_eta_eq Γ t2 t3 A\n---------------------------------------------\n→ beta_eta_eq Γ t1 t3 A\n\n| Beta_fun : ∀ {Γ : env gnd fv} {t1 t2 : term gnd con fv} {A B},\n(Γ ⊩ (Λ A. t1) ∷ (A ⊃ B))\n→ (Γ ⊩ t2 ∷ A)\n----------------------------------------------------------\n→ beta_eta_eq Γ ((Λ A. t1) ⬝ t2) (open_term t2 0 t1) B\n\n| Beta_prod_fst : ∀ {Γ t1 t2 A B},\n(Γ ⊩ t1 ∷ A) → (Γ ⊩ t2 ∷ B)\n---------------------------------------------------\n→ beta_eta_eq Γ (fst ⟪t1, t2⟫) t1 A\n\n| Beta_prod_snd : ∀ {Γ t1 t2 A B},\n(Γ ⊩ t1 ∷ A) → (Γ ⊩ t2 ∷ B)\n---------------------------------------------------\n→ beta_eta_eq Γ (snd ⟪t1, t2⟫) t2 B\n\n| Eta_fun : ∀ {Γ t A B},\n(Γ ⊩ t ∷ (A ⊃ B))\n-----------------------------------------\n→ beta_eta_eq Γ t (Λ A. (t ⬝ ⌈0⌉)) (A ⊃ B) \n\n| Eta_prod : ∀ {Γ t A B},\n(Γ ⊩ t ∷ (A ∏ B))\n----------------------------------------\n→ beta_eta_eq Γ t ⟪fst t, snd t⟫ (A ∏ B) \n\n| Eta_unit : ∀ {Γ t},\n(Γ ⊩ t ∷ unit)\n--------------------------\n→ beta_eta_eq Γ t ⟪⟫ unit\n\n| Cong_lam : ∀ {Γ : env gnd fv} {t t' A B},\n(∀ x ∉ free_vars t ∪ Γ.keys.to_finset, \n beta_eta_eq (⟨x, A⟩ :: Γ) (open_var x 0 t) (open_var x 0 t') B)\n----------------------------------------------------------------\n→ beta_eta_eq Γ (Λ A. t) (Λ A. t') (A ⊃ B)\n\n| Cong_app : ∀ {Γ t1 t2 t1' t2' A B},\nbeta_eta_eq Γ t1 t1' (A ⊃ B) → beta_eta_eq Γ t2 t2' A\n-----------------------------------------------------\n→ beta_eta_eq Γ (t1 ⬝ t2) (t1' ⬝ t2') B\n\n| Cong_fst : ∀ {Γ t t' A B},\nbeta_eta_eq Γ t t' (A ∏ B)\n----------------------------------\n→ beta_eta_eq Γ (fst t) (fst t') A\n\n| Cong_snd : ∀ {Γ t t' A B},\nbeta_eta_eq Γ t t' (A ∏ B)\n----------------------------------\n→ beta_eta_eq Γ (snd t) (snd t') B\n\n| Cong_pair : ∀ {Γ t1 t2 t1' t2' A B},\nbeta_eta_eq Γ t1 t1' A → beta_eta_eq Γ t2 t2' B\n-----------------------------------------------\n→ beta_eta_eq Γ ⟪t1, t2⟫ ⟪t1', t2'⟫ (A ∏ B)\n\nlemma has_type_of_beta_eta_eq {Γ : env gnd fv} \n{t1 t2 : term gnd con fv} {A : type gnd} \n(heq : beta_eta_eq con_type Γ t1 t2 A)\n: (Γ ⊩ t1 ∷ A) × (Γ ⊩ t2 ∷ A) :=\nbegin\n induction' heq generalizing Γ t1 t2 A,\n case term_equality.beta_eta_eq.Refl : Γ t A h\n { exact ⟨h, h⟩ },\n case term_equality.beta_eta_eq.Symm : Γ t1 t2 A rec ih\n { exact prod.swap ih },\n case term_equality.beta_eta_eq.Trans : Γ t1 t2 t3 A rec1 rec2 ih1 ih2\n { exact ⟨ih1.fst, ih2.snd⟩ },\n case term_equality.beta_eta_eq.Beta_fun : Γ t1 t2 A B h1 h2\n { refine ⟨h1.App h2, _⟩,\n cases' h1,\n have hfresh := fvar.hfresh (free_vars t ∪ (list.keys Γ).to_finset),\n set x := fvar.fresh (free_vars t ∪ (list.keys Γ).to_finset),\n specialize h1 x hfresh,\n simp only [not_or_distrib, finset.mem_union, list.mem_to_finset] at hfresh,\n rw open_term_eq_subst_of_open_var t t2 x 0 hfresh.left,\n exact subst_preserves_type h1 h2\n },\n case term_equality.beta_eta_eq.Beta_prod_fst : Γ t1 t2 A B h1 h2\n { exact ⟨(h1.Pair h2).Fst, h1⟩ },\n case term_equality.beta_eta_eq.Beta_prod_snd : Γ t1 t2 A B h1 h2\n { exact ⟨(h1.Pair h2).Snd, h2⟩ },\n case term_equality.beta_eta_eq.Eta_fun : Γ t A B h\n { refine ⟨h, _⟩,\n apply has_type.Abs,\n intros x hx,\n simp only [open_var, open_term, eq_self_iff_true, if_true],\n apply has_type.App, rotate 2,\n exact A,\n sorry,\n /- from h we can derive that t is locally closed, so open_term does nothing -/\n /- then, we need weakening... -/\n apply has_type.Fvar,\n apply ok.Cons (ok_of_has_type h),\n simp only [not_or_distrib, finset.mem_union, list.mem_to_finset] at hx,\n exact hx.right\n },\n case term_equality.beta_eta_eq.Eta_prod : Γ t A1 A2 h\n { exact ⟨h, h.Fst.Pair h.Snd⟩ },\n case term_equality.beta_eta_eq.Eta_unit : Γ t1 h\n { exact ⟨h, has_type.Unit (ok_of_has_type h)⟩ },\n case term_equality.beta_eta_eq.Cong_lam : Γ t1 t2 A1 A2 heq ih\n { let ih1 := λ x hx, (ih x hx).fst,\n -- to make this useable, we need hx to be x ∉ t2, not x ∉ t1\n -- but we need x ∉ t1 to use ih.\n -- I thought I could use free_vars_subset_env, but I realize there's no\n -- proof of Γ ⊩ open_var x 0 t ∷ A2 I can use!\n -- this would be doable if I had the cofinite quantification\n -- but that's not possible in lean 3\n let ih2 : Π (x : fv), x ∉ free_vars t2 ∪ (list.keys Γ).to_finset →\n (⟨x, A1⟩ :: Γ ⊩ open_var x 0 t2 ∷ A2) := λ x hx, by {\n rw finset.not_mem_union at hx,\n sorry\n },\n exact ⟨has_type.Abs ih1, has_type.Abs ih2⟩\n },\n case term_equality.beta_eta_eq.Cong_app : Γ t1 t2 t1' t2' A1 A2 heq heq_1 ih1 ih2\n { exact ⟨ih1.fst.App ih2.fst, ih1.snd.App ih2.snd⟩ },\n case term_equality.beta_eta_eq.Cong_fst : Γ t1 t2 A B heq ih\n { exact ⟨ih.fst.Fst, ih.snd.Fst⟩ },\n case term_equality.beta_eta_eq.Cong_snd : Γ t1 t2 A A_1 heq ih\n { exact ⟨ih.fst.Snd, ih.snd.Snd⟩ },\n case term_equality.beta_eta_eq.Cong_pair : Γ t1 t2 t1' t2' A1 A2 heq heq_1 ih1 ih2\n { exact ⟨ih1.fst.Pair ih2.fst, ih1.snd.Pair ih2.snd⟩ }\nend\n\nuniverses u v\nvariables {C : Type u} [category.{v} C]\nlemma comp_cong {X Y Z : C} {f1 f2 : X ⟶ Y} {g : Y ⟶ Z} (h : f1 = f2)\n: f1 ≫ g = f2 ≫ g :=\nbegin\n rw h\nend\n\ntheorem soundness {M : model gnd con 𝓒} \n{Γ : env gnd fv} {t1 t2 : term gnd con fv} {A : type gnd}\n(h1 : Γ ⊩ t1 ∷ A) (h2 : Γ ⊩ t2 ∷ A)\n(heq : beta_eta_eq con_type Γ t1 t2 A)\n: (M⟦h1⟧) = (M⟦h2⟧) :=\nbegin\n induction' heq generalizing Γ t1 t2 A,\n case beta_eta_eq.Refl : Γ t A { rw deriv_unicity h1 h2 },\n case term_equality.beta_eta_eq.Symm : Γ t2 t1 A rec ih {\n symmetry, exact ih h2 h1,\n },\n case term_equality.beta_eta_eq.Trans : Γ t1 t2 t3 A rec1 rec2 ih1 ih2 {\n rename [h2 → h3],\n obtain ⟨_, h2⟩ := has_type_of_beta_eta_eq rec1,\n exact trans (ih1 h1 h2) (ih2 h2 h3)\n },\n case term_equality.beta_eta_eq.Beta_fun : Γ t1 t2 A A_1 x x_1\n { -- we need to talk about semantics of substitution\n -- not enough time to do that =(\n admit },\n case term_equality.beta_eta_eq.Beta_prod_fst : Γ t1 t1_1 A B x x_1\n { cases' h1, cases h1, rw deriv_unicity h2 h1_ᾰ, simp [eval_has_type] },\n case term_equality.beta_eta_eq.Beta_prod_snd : Γ t1 t2 A1 A2 x x_1\n { cases' h1, cases h1, rw deriv_unicity h2 h1_ᾰ_1, simp [eval_has_type] },\n case term_equality.beta_eta_eq.Eta_fun : Γ t A A_1 x\n { -- need semantics of weakening...\n admit },\n case term_equality.beta_eta_eq.Eta_prod : Γ t A1 A2 x\n { -- Idea: Due to deriv unicity, we can say that\n -- M⟦h2_left : Γ ⊩ fst t ∷ A1⟧ = π₁ ∘ M⟦h1 : Γ ⊩ t ∷ A1 ∏ A2⟧ \n -- M⟦h2_right : Γ ⊩ snd t ∷ A1⟧ = π₂ ∘ M⟦h1 : Γ ⊩ t ∷ A1 ∏ A2⟧\n -- so M⟦h2⟧ = ⟨π₁ ∘ M⟦h1⟧, π₂ ∘ M⟦h1⟧⟩ = M⟦h1⟧ by the universal \n -- property of products.\n cases' h2, cases h2, cases h2_1,\n have := type_unicity h1 h2_ᾰ, simp at this, subst this,\n have := type_unicity h1 h2_1_ᾰ, simp at this, subst this,\n rw deriv_unicity h2_ᾰ h1,\n rw deriv_unicity h2_1_ᾰ h1,\n ext; simp [eval_has_type]\n },\n case term_equality.beta_eta_eq.Eta_unit : Γ t1 x\n { -- M⟦h1⟧ and M⟦h2⟧ are both arrows from M⟦Γ⟧ to the terminal object,\n -- so they must be equal by the uniqueness condition. \n have := category_theory.limits.unique_to_terminal (M.G⟦Γ⟧),\n exact trans (this.uniq (M⟦h1⟧)) (symm (this.uniq (M⟦h2⟧))),\n },\n case term_equality.beta_eta_eq.Cong_lam : Γ t1 t2 A A_1 heq ih\n { cases h2, cases h1, \n simp [eval_has_type],\n -- this is the same issue as line 140: one hypothesis is asking for free_vars t1\n -- the other is asking for free_vars t2.\n sorry\n },\n case term_equality.beta_eta_eq.Cong_app : Γ t1 t2 t1' t2' A1 A2 heq heq' ih ih'\n { -- Idea: \n -- the goal is essentially to show \n -- eval ∘ ⟨M⟦h1.left⟧, M⟦h1.right⟧⟩ = eval ∘ ⟨M⟦h2.left⟧, M⟦h2.right⟧⟩\n -- By congruence, and by the universal property of products,\n -- This is the same as showing M⟦h1.left⟧ = M⟦h2.left⟧ and M⟦h1.right⟧ = M⟦h2.right⟧\n -- But that's exactly what we have with the inductive hypotheses.\n cases' h2, cases' h1,\n obtain ⟨h1_1', h2_1'⟩ := has_type_of_beta_eta_eq heq',\n have := type_unicity h1_1 h1_1', subst this,\n have := type_unicity h2_1 h2_1', subst this,\n specialize ih h1 h2,\n specialize ih' h1_1 h2_1,\n apply comp_cong,\n ext; simp only [prod.lift_fst, prod.lift_snd],\n exact ih',\n exact ih, \n },\n case term_equality.beta_eta_eq.Cong_fst : Γ t1 t2 A B heq ih\n { -- showing π₁ ∘ M⟦h1⟧ = π₂ ∘ M⟦h2⟧ is the same as showing M⟦h1⟧ = M⟦h2⟧\n -- by congruence\n cases' h1, cases' h2,\n obtain ⟨h1', h2'⟩ := has_type_of_beta_eta_eq heq,\n have := type_unicity h1 h1', simp at this, subst this,\n have := type_unicity h2 h2', simp at this, subst this,\n apply comp_cong,\n exact ih h1 h2,\n },\n case term_equality.beta_eta_eq.Cong_snd : Γ t1 t2 A A_1 heq ih\n { -- similar to Cong_fst\n cases' h1, cases' h2,\n obtain ⟨h1', h2'⟩ := has_type_of_beta_eta_eq heq,\n have := type_unicity h1 h1', simp at this, subst this,\n have := type_unicity h2 h2', simp at this, subst this,\n apply comp_cong,\n exact ih h1 h2,\n },\n case term_equality.beta_eta_eq.Cong_pair : Γ t1 t2 t1' t2' A1 A2 heq heq' ih ih'\n { -- this uses the universal property of products to decompose equality on\n -- products, as we did in Cong_app.\n cases' h1, cases h2, --sometimes `cases'` just doesn't work even though `cases` does\n ext; simp only [eval_has_type, prod.lift_fst, prod.lift_snd], \n exact ih h1 h2_ᾰ,\n exact ih' h1_1 h2_ᾰ_1\n }\nend\n\n\nend term_equality", "meta": {"author": "alyata", "repo": "formalising-math-3", "sha": "c134556878a054be5e329cdee90d8fe4b86cab7c", "save_path": "github-repos/lean/alyata-formalising-math-3", "path": "github-repos/lean/alyata-formalising-math-3/formalising-math-3-c134556878a054be5e329cdee90d8fe4b86cab7c/src/term_equality.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42250463481418826, "lm_q2_score": 0.0259573580454947, "lm_q1q2_score": 0.01096710408175287}} {"text": "import group_theory.group_action.basic\n\nvariables (R M S : Type*)\n\n/-- Some arbitrary type depending on `has_smul R M` -/\n@[irreducible, nolint has_nonempty_instance unused_arguments]\ndef foo [has_smul R M] : Type* := ℕ\n\nvariables [has_smul R M] [has_smul S R] [has_smul S M]\n\n/-- This instance is incompatible with `has_smul.comp.is_scalar_tower`.\nHowever, all its parameters are (instance) implicits or irreducible defs, so it\nshould not be dangerous. -/\n@[nolint unused_arguments]\ninstance foo.has_smul [is_scalar_tower S R M] : has_smul S (foo R M) :=\n⟨λ _ _, by { unfold foo, exact 37 }⟩\n\n-- If there is no `is_scalar_tower S R M` parameter, this should fail quickly,\n-- not loop forever.\nexample : has_smul S (foo R M) :=\nbegin\n tactic.success_if_fail_with_msg tactic.interactive.apply_instance\n \"tactic.mk_instance failed to generate instance for\n has_smul S (foo R M)\",\n unfold foo,\n exact ⟨λ _ _, 37⟩\nend\n\n/-\nlocal attribute [instance] has_smul.comp.is_scalar_tower\n-- When `has_smul.comp.is_scalar_tower` is an instance, this recurses indefinitely.\nexample : has_smul S (foo R M) :=\nbegin\n tactic.success_if_fail_with_msg tactic.interactive.apply_instance\n \"maximum class-instance resolution depth has been reached (the limit can be increased by setting option 'class.instance_max_depth') (the class-instance resolution trace can be visualized by setting option 'trace.class_instances')\",\n unfold foo,\n exact ⟨λ _ _, 37⟩\nend\n-/\n", "meta": {"author": "leanprover-community", "repo": "mathlib", "sha": "5e526d18cea33550268dcbbddcb822d5cde40654", "save_path": "github-repos/lean/leanprover-community-mathlib", "path": "github-repos/lean/leanprover-community-mathlib/mathlib-5e526d18cea33550268dcbbddcb822d5cde40654/test/has_scalar_comp_loop.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.42632157796989345, "lm_q2_score": 0.025565212020806777, "lm_q1q2_score": 0.010899001529845234}} {"text": "/-\nCopyright (c) 2019 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthor: Leonardo de Moura\n-/\nprelude\nimport Init.Control.Basic\nimport Init.Data.List.Basic\n\nnamespace List\nuniverse u v w u₁ u₂\n\n/-\nRemark: we can define `mapM`, `mapM₂` and `forM` using `Applicative` instead of `Monad`.\nExample:\n```\ndef mapM {m : Type u → Type v} [Applicative m] {α : Type w} {β : Type u} (f : α → m β) : List α → m (List β)\n | [] => pure []\n | a::as => List.cons <$> (f a) <*> mapM as\n```\n\nHowever, we consider `f <$> a <*> b` an anti-idiom because the generated code\nmay produce unnecessary closure allocations.\nSuppose `m` is a `Monad`, and it uses the default implementation for `Applicative.seq`.\nThen, the compiler expands `f <$> a <*> b <*> c` into something equivalent to\n```\n(Functor.map f a >>= fun g_1 => Functor.map g_1 b) >>= fun g_2 => Functor.map g_2 c\n```\nIn an ideal world, the compiler may eliminate the temporary closures `g_1` and `g_2` after it inlines\n`Functor.map` and `Monad.bind`. However, this can easily fail. For example, suppose\n`Functor.map f a >>= fun g_1 => Functor.map g_1 b` expanded into a match-expression.\nThis is not unreasonable and can happen in many different ways, e.g., we are using a monad that\nmay throw exceptions. Then, the compiler has to decide whether it will create a join-point for\nthe continuation of the match or float it. If the compiler decides to float, then it will\nbe able to eliminate the closures, but it may not be feasible since floating match expressions\nmay produce exponential blowup in the code size.\n\nFinally, we rarely use `mapM` with something that is not a `Monad`.\n\nUsers that want to use `mapM` with `Applicative` should use `mapA` instead.\n-/\n\n@[specialize]\ndef mapM {m : Type u → Type v} [Monad m] {α : Type w} {β : Type u} (f : α → m β) : List α → m (List β)\n | [] => pure []\n | a::as => return (← f a) :: (← mapM f as)\n\n@[specialize]\ndef mapA {m : Type u → Type v} [Applicative m] {α : Type w} {β : Type u} (f : α → m β) : List α → m (List β)\n | [] => pure []\n | a::as => List.cons <$> f a <*> mapA f as\n\n@[specialize]\nprotected def forM {m : Type u → Type v} [Monad m] {α : Type w} (as : List α) (f : α → m PUnit) : m PUnit :=\n match as with\n | [] => pure ⟨⟩\n | a :: as => do f a; List.forM as f\n\n@[specialize]\ndef forA {m : Type u → Type v} [Applicative m] {α : Type w} (as : List α) (f : α → m PUnit) : m PUnit :=\n match as with\n | [] => pure ⟨⟩\n | a :: as => f a *> forA as f\n\n@[specialize]\ndef filterAuxM {m : Type → Type v} [Monad m] {α : Type} (f : α → m Bool) : List α → List α → m (List α)\n | [], acc => pure acc\n | h :: t, acc => do\n let b ← f h\n filterAuxM f t (cond b (h :: acc) acc)\n\n@[inline]\ndef filterM {m : Type → Type v} [Monad m] {α : Type} (f : α → m Bool) (as : List α) : m (List α) := do\n let as ← filterAuxM f as []\n pure as.reverse\n\n@[inline]\ndef filterRevM {m : Type → Type v} [Monad m] {α : Type} (f : α → m Bool) (as : List α) : m (List α) :=\n filterAuxM f as.reverse []\n\n@[inline]\ndef filterMapM {m : Type u → Type v} [Monad m] {α β : Type u} (f : α → m (Option β)) (as : List α) : m (List β) :=\n let rec @[specialize] loop\n | [], bs => pure bs\n | a :: as, bs => do\n match (← f a) with\n | none => loop as bs\n | some b => loop as (b::bs)\n loop as.reverse []\n\n@[specialize]\nprotected def foldlM {m : Type u → Type v} [Monad m] {s : Type u} {α : Type w} : (f : s → α → m s) → (init : s) → List α → m s\n | f, s, [] => pure s\n | f, s, a :: as => do\n let s' ← f s a\n List.foldlM f s' as\n\n@[specialize]\ndef foldrM {m : Type u → Type v} [Monad m] {s : Type u} {α : Type w} : (f : α → s → m s) → (init : s) → List α → m s\n | f, s, [] => pure s\n | f, s, a :: as => do\n let s' ← foldrM f s as\n f a s'\n\n@[specialize]\ndef firstM {m : Type u → Type v} [Monad m] [Alternative m] {α : Type w} {β : Type u} (f : α → m β) : List α → m β\n | [] => failure\n | a::as => f a <|> firstM f as\n\n@[specialize]\ndef anyM {m : Type → Type u} [Monad m] {α : Type v} (f : α → m Bool) : List α → m Bool\n | [] => pure false\n | a::as => do\n match (← f a) with\n | true => pure true\n | false => anyM f as\n\n@[specialize]\ndef allM {m : Type → Type u} [Monad m] {α : Type v} (f : α → m Bool) : List α → m Bool\n | [] => pure true\n | a::as => do\n match (← f a) with\n | true => allM f as\n | false => pure false\n\n@[specialize]\ndef findM? {m : Type → Type u} [Monad m] {α : Type} (p : α → m Bool) : List α → m (Option α)\n | [] => pure none\n | a::as => do\n match (← p a) with\n | true => pure (some a)\n | false => findM? p as\n\n@[specialize]\ndef findSomeM? {m : Type u → Type v} [Monad m] {α : Type w} {β : Type u} (f : α → m (Option β)) : List α → m (Option β)\n | [] => pure none\n | a::as => do\n match (← f a) with\n | some b => pure (some b)\n | none => findSomeM? f as\n\n@[inline] protected def forIn {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (as : List α) (init : β) (f : α → β → m (ForInStep β)) : m β :=\n let rec @[specialize] loop\n | [], b => pure b\n | a::as, b => do\n match (← f a b) with\n | ForInStep.done b => pure b\n | ForInStep.yield b => loop as b\n loop as init\n\ninstance : ForIn m (List α) α where\n forIn := List.forIn\n\n@[simp] theorem forIn_nil [Monad m] (f : α → β → m (ForInStep β)) (b : β) : forIn [] b f = pure b :=\n rfl\n\n@[simp] theorem forIn_cons [Monad m] (f : α → β → m (ForInStep β)) (a : α) (as : List α) (b : β)\n : forIn (a::as) b f = f a b >>= fun | ForInStep.done b => pure b | ForInStep.yield b => forIn as b f :=\n rfl\n\ninstance : ForM m (List α) α where\n forM := List.forM\n\n@[simp] theorem forM_nil [Monad m] (f : α → m PUnit) : forM [] f = pure ⟨⟩ :=\n rfl\n@[simp] theorem forM_cons [Monad m] (f : α → m PUnit) (a : α) (as : List α) : forM (a::as) f = f a >>= fun _ => forM as f :=\n rfl\n\nend List\n", "meta": {"author": "Kha", "repo": "lean4-nightly", "sha": "b4c92de57090e6c47b29d3575df53d86fce52752", "save_path": "github-repos/lean/Kha-lean4-nightly", "path": "github-repos/lean/Kha-lean4-nightly/lean4-nightly-b4c92de57090e6c47b29d3575df53d86fce52752/stage0/src/Init/Data/List/Control.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.22270012850745968, "lm_q2_score": 0.04885778018022643, "lm_q1q2_score": 0.010880633924725642}} {"text": "-- other minor lemmas related to verification but not included in the other files\n\nimport .definitions2\n\nlemma unchanged_of_apply_termctx_without_hole {t tt: term}:\n t.to_termctx tt = t :=\n begin\n induction t with v y unop t₁ ih₁ binop t₂ t₃ ih₂ ih₃ t₄ t₅ ih₄ ih₅,\n\n show (termctx.apply (term.to_termctx (term.value v)) tt = term.value v), by begin\n unfold term.to_termctx,\n unfold termctx.apply\n end,\n\n show (termctx.apply (term.to_termctx (term.var y)) tt = term.var y), by begin\n unfold term.to_termctx,\n unfold termctx.apply\n end,\n\n show (termctx.apply (term.to_termctx (term.unop unop t₁)) tt = term.unop unop t₁), by begin\n unfold term.to_termctx,\n unfold termctx.apply,\n congr,\n from ih₁\n end,\n\n show (termctx.apply (term.to_termctx (term.binop binop t₂ t₃)) tt = term.binop binop t₂ t₃), by begin\n unfold term.to_termctx,\n unfold termctx.apply,\n congr,\n from ih₂,\n from ih₃\n end,\n\n show (termctx.apply (term.to_termctx (term.app t₄ t₅)) tt = term.app t₄ t₅), by begin\n unfold term.to_termctx,\n unfold termctx.apply,\n congr,\n from ih₄,\n from ih₅\n end\n end\n\nlemma unchanged_of_apply_propctx_without_hole {P: prop} {t: term}:\n P.to_propctx t = P :=\n begin\n change (propctx.apply (prop.to_propctx P) t = P),\n induction P,\n\n case prop.term t₁ {\n unfold prop.to_propctx,\n unfold propctx.apply,\n congr,\n from unchanged_of_apply_termctx_without_hole\n },\n\n case prop.not P₁ ih {\n unfold prop.to_propctx,\n unfold propctx.apply,\n congr,\n from ih\n },\n\n case prop.and P₁ P₂ ih₁ ih₂ {\n unfold prop.to_propctx,\n change (propctx.apply (propctx.and (prop.to_propctx P₁) (prop.to_propctx P₂)) t = prop.and P₁ P₂),\n unfold propctx.apply,\n congr,\n from ih₁,\n from ih₂\n },\n\n case prop.or P₁ P₂ ih₁ ih₂ {\n unfold prop.to_propctx,\n change (propctx.apply (propctx.or (prop.to_propctx P₁) (prop.to_propctx P₂)) t = prop.or P₁ P₂),\n unfold propctx.apply,\n congr,\n from ih₁,\n from ih₂\n },\n\n case prop.pre t₁ t₂ {\n unfold prop.to_propctx,\n unfold propctx.apply,\n congr,\n from unchanged_of_apply_termctx_without_hole,\n from unchanged_of_apply_termctx_without_hole\n },\n\n case prop.pre₁ op t₁ {\n unfold prop.to_propctx,\n unfold propctx.apply,\n congr,\n from unchanged_of_apply_termctx_without_hole\n },\n\n case prop.pre₂ op t₁ t₂ {\n unfold prop.to_propctx,\n unfold propctx.apply,\n congr,\n from unchanged_of_apply_termctx_without_hole,\n from unchanged_of_apply_termctx_without_hole\n },\n\n case prop.post t₁ t₂ {\n unfold prop.to_propctx,\n unfold propctx.apply,\n congr,\n from unchanged_of_apply_termctx_without_hole,\n from unchanged_of_apply_termctx_without_hole\n },\n\n case prop.call t₁ t₂ {\n unfold prop.to_propctx,\n unfold propctx.apply,\n congr,\n from unchanged_of_apply_termctx_without_hole\n },\n\n case prop.forallc y P₁ ih {\n unfold prop.to_propctx,\n unfold propctx.apply,\n congr,\n from ih\n },\n\n case prop.exis y P₁ ih {\n unfold prop.to_propctx,\n unfold propctx.apply,\n congr,\n from ih\n }\n end\n\nlemma vc.term.inj.inv {t₁ t₂: term}: (t₁ = t₂) → (vc.term t₁ = vc.term t₂) :=\n begin\n assume h1,\n congr,\n from h1\n end\n\nlemma vc.not.inj.inv {P Q: vc}: (P = Q) → (vc.not P = vc.not Q) :=\n begin\n assume h1,\n congr,\n from h1\n end\n\nlemma vc.and.inj.inv {P₁ P₂ P₃ P₄: vc}: (P₁ = P₂) → (P₃ = P₄) → (vc.and P₁ P₃ = vc.and P₂ P₄) :=\n begin\n assume h1,\n assume h2,\n congr,\n from h1,\n from h2\n end\n\nlemma vc.or.inj.inv {P₁ P₂ P₃ P₄: vc}: (P₁ = P₂) → (P₃ = P₄) → (vc.or P₁ P₃ = vc.or P₂ P₄) :=\n begin\n assume h1,\n assume h2,\n congr,\n from h1,\n from h2\n end\n\nlemma vc.pre.inj.inv {t₁ t₂ t₃ t₄: term}: (t₁ = t₂) → (t₃ = t₄) → (vc.pre t₁ t₃ = vc.pre t₂ t₄) :=\n begin\n assume h1,\n assume h2,\n congr,\n from h1,\n from h2\n end\n\nlemma vc.pre₁.inj.inv {t₁ t₂: term} {op: unop}: (t₁ = t₂) → (vc.pre₁ op t₁ = vc.pre₁ op t₂) :=\n begin\n assume h1,\n congr,\n from h1\n end\n\nlemma vc.pre₂.inj.inv {t₁ t₂ t₃ t₄: term} {op: binop}: (t₁ = t₂) → (t₃ = t₄) → (vc.pre₂ op t₁ t₃ = vc.pre₂ op t₂ t₄) :=\n begin\n assume h1,\n assume h2,\n congr,\n from h1,\n from h2\n end\n\nlemma vc.post.inj.inv {t₁ t₂ t₃ t₄: term}: (t₁ = t₂) → (t₃ = t₄) → (vc.post t₁ t₃ = vc.post t₂ t₄) :=\n begin\n assume h1,\n assume h2,\n congr,\n from h1,\n from h2\n end\n\nlemma vc.univ.inj.inv {P Q: vc} {x: var}: (P = Q) → (vc.univ x P = vc.univ x Q) :=\n begin\n assume h1,\n congr,\n from h1\n end\n", "meta": {"author": "levjj", "repo": "esverify-theory", "sha": "8565b123c87b0113f83553d7732cd6696c9b5807", "save_path": "github-repos/lean/levjj-esverify-theory", "path": "github-repos/lean/levjj-esverify-theory/esverify-theory-8565b123c87b0113f83553d7732cd6696c9b5807/src/others.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.33807711081162, "lm_q2_score": 0.03210070660126248, "lm_q1q2_score": 0.010852514142766317}} {"text": "/-\nCopyright (c) 2019 Simon Hudon. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Simon Hudon\n-/\nimport control.traversable.derive\nimport control.traversable.lemmas\nimport data.dlist\nimport tactic.monotonicity.basic\n\nvariables {a b c p : Prop}\n\nnamespace tactic.interactive\n\nopen lean lean.parser interactive\nopen interactive.types\nopen tactic\n\nlocal postfix (name := parser.optional) `?`:9001 := optional\nlocal postfix (name := parser.many) *:9001 := many\n\nmeta inductive mono_function (elab : bool := tt)\n | non_assoc : expr elab → list (expr elab) → list (expr elab) → mono_function\n | assoc : expr elab → option (expr elab) → option (expr elab) → mono_function\n | assoc_comm : expr elab → expr elab → mono_function\n\nmeta instance : decidable_eq mono_function :=\nby mk_dec_eq_instance\n\nmeta def mono_function.to_tactic_format : mono_function → tactic format\n | (mono_function.non_assoc fn xs ys) := do\n fn' ← pp fn,\n xs' ← mmap pp xs,\n ys' ← mmap pp ys,\n return format!\"{fn'} {xs'} _ {ys'}\"\n | (mono_function.assoc fn xs ys) := do\n fn' ← pp fn,\n xs' ← pp xs,\n ys' ← pp ys,\n return format!\"{fn'} {xs'} _ {ys'}\"\n | (mono_function.assoc_comm fn xs) := do\n fn' ← pp fn,\n xs' ← pp xs,\n return format!\"{fn'} _ {xs'}\"\n\nmeta instance has_to_tactic_format_mono_function : has_to_tactic_format mono_function :=\n{ to_tactic_format := mono_function.to_tactic_format }\n\n@[derive traversable]\nmeta structure ac_mono_ctx' (rel : Type) :=\n (to_rel : rel)\n (function : mono_function)\n (left right rel_def : expr)\n\n@[reducible]\nmeta def ac_mono_ctx := ac_mono_ctx' (option (expr → expr → expr))\n@[reducible]\nmeta def ac_mono_ctx_ne := ac_mono_ctx' (expr → expr → expr)\n\nmeta def ac_mono_ctx.to_tactic_format (ctx : ac_mono_ctx) : tactic format :=\ndo fn ← pp ctx.function,\n l ← pp ctx.left,\n r ← pp ctx.right,\n rel ← pp ctx.rel_def,\n return format!\"{{ function := {fn}\\n, left := {l}\\n, right := {r}\\n, rel_def := {rel} }}\"\n\nmeta instance has_to_tactic_format_mono_ctx : has_to_tactic_format ac_mono_ctx :=\n{ to_tactic_format := ac_mono_ctx.to_tactic_format }\n\nmeta def as_goal (e : expr) (tac : tactic unit) : tactic unit :=\ndo gs ← get_goals,\n set_goals [e],\n tac,\n set_goals gs\n\nopen list (hiding map) functor dlist\n\nsection config\n\nparameter opt : mono_cfg\nparameter asms : list expr\n\nmeta def unify_with_instance (e : expr) : tactic unit :=\nas_goal e $\napply_instance\n<|>\napply_opt_param\n<|>\napply_auto_param\n<|>\ntactic.solve_by_elim { lemmas := some asms }\n<|>\nreflexivity\n<|>\napplyc ``id\n<|>\nreturn ()\n\nprivate meta def match_rule_head (p : expr)\n: list expr → expr → expr → tactic expr\n | vs e t :=\n(unify t p >> mmap' unify_with_instance vs.reverse >> instantiate_mvars e)\n<|>\ndo (expr.pi _ _ d b) ← return t | failed,\n v ← mk_meta_var d,\n match_rule_head (v::vs) (expr.app e v) (b.instantiate_var v)\n\nmeta def pi_head : expr → tactic expr\n| (expr.pi n _ t b) :=\ndo v ← mk_meta_var t,\n pi_head (b.instantiate_var v)\n| e := return e\n\nmeta def delete_expr (e : expr)\n: list expr → tactic (option (list expr))\n | [] := return none\n | (x :: xs) :=\n(compare opt e x >> return (some xs))\n<|>\n(map (cons x) <$> delete_expr xs)\n\nmeta def match_ac'\n: list expr → list expr → tactic (list expr × list expr × list expr)\n | es (x :: xs) := do\n es' ← delete_expr x es,\n match es' with\n | (some es') := do\n (c,l,r) ← match_ac' es' xs, return (x::c,l,r)\n | none := do\n (c,l,r) ← match_ac' es xs, return (c,l,x::r)\n end\n | es [] := do\nreturn ([],es,[])\n\nmeta def match_ac (l : list expr) (r : list expr)\n: tactic (list expr × list expr × list expr) :=\ndo (s',l',r') ← match_ac' l r,\n s' ← mmap instantiate_mvars s',\n l' ← mmap instantiate_mvars l',\n r' ← mmap instantiate_mvars r',\n return (s',l',r')\n\nmeta def match_prefix\n: list expr → list expr → tactic (list expr × list expr × list expr)\n| (x :: xs) (y :: ys) :=\n (do compare opt x y,\n prod.map ((::) x) id <$> match_prefix xs ys)\n<|> return ([],x :: xs,y :: ys)\n| xs ys := return ([],xs,ys)\n\n/--\n`(prefix,left,right,suffix) ← match_assoc unif l r` finds the\nlongest prefix and suffix common to `l` and `r` and\nreturns them along with the differences -/\nmeta def match_assoc (l : list expr) (r : list expr)\n: tactic (list expr × list expr × list expr × list expr) :=\ndo (pre,l₁,r₁) ← match_prefix l r,\n (suf,l₂,r₂) ← match_prefix (reverse l₁) (reverse r₁),\n return (pre,reverse l₂,reverse r₂,reverse suf)\n\nmeta def check_ac : expr → tactic (bool × bool × option (expr × expr × expr) × expr)\n | (expr.app (expr.app f x) y) :=\n do t ← infer_type x,\n a ← try_core $ to_expr ``(is_associative %%t %%f) >>= mk_instance,\n c ← try_core $ to_expr ``(is_commutative %%t %%f) >>= mk_instance,\n i ← try_core (do\n v ← mk_meta_var t,\n l_inst_p ← to_expr ``(is_left_id %%t %%f %%v),\n r_inst_p ← to_expr ``(is_right_id %%t %%f %%v),\n l_v ← mk_meta_var l_inst_p,\n r_v ← mk_meta_var r_inst_p ,\n l_id ← mk_mapp `is_left_id.left_id [some t,f,v,some l_v],\n mk_instance l_inst_p >>= unify l_v,\n r_id ← mk_mapp `is_right_id.right_id [none,f,v,some r_v],\n mk_instance r_inst_p >>= unify r_v,\n v' ← instantiate_mvars v,\n return (l_id,r_id,v')),\n return (a.is_some,c.is_some,i,f)\n | _ := return (ff,ff,none,expr.var 1)\n\nmeta def parse_assoc_chain' (f : expr) : expr → tactic (dlist expr)\n | e :=\n (do (expr.app (expr.app f' x) y) ← return e,\n is_def_eq f f',\n (++) <$> parse_assoc_chain' x <*> parse_assoc_chain' y)\n<|> return (singleton e)\n\nmeta def parse_assoc_chain (f : expr) : expr → tactic (list expr) :=\nmap dlist.to_list ∘ parse_assoc_chain' f\n\nmeta def fold_assoc (op : expr) :\n option (expr × expr × expr) → list expr → option (expr × list expr)\n| _ (x::xs) := some (foldl (expr.app ∘ expr.app op) x xs, [])\n| none [] := none\n| (some (l_id,r_id,x₀)) [] := some (x₀,[l_id,r_id])\n\nmeta def fold_assoc1 (op : expr) : list expr → option expr\n| (x::xs) := some $ foldl (expr.app ∘ expr.app op) x xs\n| [] := none\n\nmeta def same_function_aux\n: list expr → list expr → expr → expr → tactic (expr × list expr × list expr)\n | xs₀ xs₁ (expr.app f₀ a₀) (expr.app f₁ a₁) :=\n same_function_aux (a₀ :: xs₀) (a₁ :: xs₁) f₀ f₁\n | xs₀ xs₁ e₀ e₁ := is_def_eq e₀ e₁ >> return (e₀,xs₀,xs₁)\n\nmeta def same_function : expr → expr → tactic (expr × list expr × list expr) :=\nsame_function_aux [] []\n\nmeta def parse_ac_mono_function (l r : expr)\n: tactic (expr × expr × list expr × mono_function) :=\ndo (full_f,ls,rs) ← same_function l r,\n (a,c,i,f) ← check_ac l,\n if a\n then if c\n then do\n (s,ls,rs) ← monad.join (match_ac\n <$> parse_assoc_chain f l\n <*> parse_assoc_chain f r),\n (l',l_id) ← fold_assoc f i ls,\n (r',r_id) ← fold_assoc f i rs,\n s' ← fold_assoc1 f s,\n return (l',r',l_id ++ r_id,mono_function.assoc_comm f s')\n else do -- a ∧ ¬ c\n (pre,ls,rs,suff) ← monad.join (match_assoc\n <$> parse_assoc_chain f l\n <*> parse_assoc_chain f r),\n (l',l_id) ← fold_assoc f i ls,\n (r',r_id) ← fold_assoc f i rs,\n let pre' := fold_assoc1 f pre,\n let suff' := fold_assoc1 f suff,\n return (l',r',l_id ++ r_id,mono_function.assoc f pre' suff')\n else do -- ¬ a\n (xs₀,x₀,x₁,xs₁) ← find_one_difference opt ls rs,\n return (x₀,x₁,[],mono_function.non_assoc full_f xs₀ xs₁)\n\nmeta def parse_ac_mono_function' (l r : pexpr) :=\ndo l' ← to_expr l,\n r' ← to_expr r,\n parse_ac_mono_function l' r'\n\nmeta def ac_monotonicity_goal : expr → tactic (expr × expr × list expr × ac_mono_ctx)\n | `(%%e₀ → %%e₁) :=\n do (l,r,id_rs,f) ← parse_ac_mono_function e₀ e₁,\n t₀ ← infer_type e₀,\n t₁ ← infer_type e₁,\n rel_def ← to_expr ``(λ x₀ x₁, (x₀ : %%t₀) → (x₁ : %%t₁)),\n return (e₀, e₁, id_rs,\n { function := f\n , left := l, right := r\n , to_rel := some $ expr.pi `x binder_info.default\n , rel_def := rel_def })\n | `(%%e₀ = %%e₁) :=\n do (l,r,id_rs,f) ← parse_ac_mono_function e₀ e₁,\n t₀ ← infer_type e₀,\n t₁ ← infer_type e₁,\n rel_def ← to_expr ``(λ x₀ x₁, (x₀ : %%t₀) = (x₁ : %%t₁)),\n return (e₀, e₁, id_rs,\n { function := f\n , left := l, right := r\n , to_rel := none\n , rel_def := rel_def })\n | (expr.app (expr.app rel e₀) e₁) :=\n do (l,r,id_rs,f) ← parse_ac_mono_function e₀ e₁,\n return (e₀, e₁, id_rs,\n { function := f\n , left := l, right := r\n , to_rel := expr.app ∘ expr.app rel\n , rel_def := rel })\n | _ := fail \"invalid monotonicity goal\"\n\nmeta def bin_op_left (f : expr) : option expr → expr → expr\n| none e := e\n| (some e₀) e₁ := f.mk_app [e₀,e₁]\n\nmeta def bin_op (f a b : expr) : expr :=\nf.mk_app [a,b]\n\nmeta def bin_op_right (f : expr) : expr → option expr → expr\n| e none := e\n| e₀ (some e₁) := f.mk_app [e₀,e₁]\n\nmeta def mk_fun_app : mono_function → expr → expr\n | (mono_function.non_assoc f x y) z := f.mk_app (x ++ z :: y)\n | (mono_function.assoc f x y) z := bin_op_left f x (bin_op_right f z y)\n | (mono_function.assoc_comm f x) z := f.mk_app [z,x]\n\nmeta inductive mono_law\n /- `assoc (l₀,r₀) (r₁,l₁)` gives first how to find rules to prove\n x+(y₀+z) R x+(y₁+z);\n if that fails, helps prove (x+y₀)+z R (x+y₁)+z -/\n | assoc : expr × expr → expr × expr → mono_law\n /- `congr r` gives the rule to prove `x = y → f x = f y` -/\n | congr : expr → mono_law\n | other : expr → mono_law\n\nmeta def mono_law.to_tactic_format : mono_law → tactic format\n | (mono_law.other e) := do e ← pp e, return format!\"other {e}\"\n | (mono_law.congr r) := do e ← pp r, return format!\"congr {e}\"\n | (mono_law.assoc (x₀,x₁) (y₀,y₁)) :=\ndo x₀ ← pp x₀,\n x₁ ← pp x₁,\n y₀ ← pp y₀,\n y₁ ← pp y₁,\n return format!\"assoc {x₀}; {x₁} | {y₀}; {y₁}\"\n\nmeta instance has_to_tactic_format_mono_law : has_to_tactic_format mono_law :=\n{ to_tactic_format := mono_law.to_tactic_format }\n\nmeta def mk_rel (ctx : ac_mono_ctx_ne) (f : expr → expr) : expr :=\nctx.to_rel (f ctx.left) (f ctx.right)\n\nmeta def mk_congr_args (fn : expr) (xs₀ xs₁ : list expr) (l r : expr) : tactic expr :=\ndo p ← mk_app `eq [fn.mk_app $ xs₀ ++ l :: xs₁,fn.mk_app $ xs₀ ++ r :: xs₁],\n prod.snd <$> solve_aux p\n (do iterate_exactly (xs₁.length) (applyc `congr_fun),\n applyc `congr_arg)\n\nmeta def mk_congr_law (ctx : ac_mono_ctx) : tactic expr :=\nmatch ctx.function with\n | (mono_function.assoc f x₀ x₁) :=\n if (x₀ <|> x₁).is_some\n then mk_congr_args f x₀.to_monad x₁.to_monad ctx.left ctx.right\n else failed\n | (mono_function.assoc_comm f x₀) := mk_congr_args f [x₀] [] ctx.left ctx.right\n | (mono_function.non_assoc f x₀ x₁) := mk_congr_args f x₀ x₁ ctx.left ctx.right\nend\n\nmeta def mk_pattern (ctx : ac_mono_ctx) : tactic mono_law :=\nmatch (sequence ctx : option (ac_mono_ctx' _)) with\n | (some ctx) :=\n match ctx.function with\n | (mono_function.assoc f (some x) (some y)) :=\n return $ mono_law.assoc\n ( mk_rel ctx (λ i, bin_op f x (bin_op f i y))\n , mk_rel ctx (λ i, bin_op f i y))\n ( mk_rel ctx (λ i, bin_op f (bin_op f x i) y)\n , mk_rel ctx (λ i, bin_op f x i))\n | (mono_function.assoc f (some x) none) :=\n return $ mono_law.other $\n mk_rel ctx (λ e, mk_fun_app ctx.function e)\n | (mono_function.assoc f none (some y)) :=\n return $ mono_law.other $\n mk_rel ctx (λ e, mk_fun_app ctx.function e)\n | (mono_function.assoc f none none) :=\n none\n | _ :=\n return $ mono_law.other $\n mk_rel ctx (λ e, mk_fun_app ctx.function e)\n end\n | none := mono_law.congr <$> mk_congr_law ctx\nend\n\nmeta def match_rule (pat : expr) (r : name) : tactic expr :=\ndo r' ← mk_const r,\n t ← infer_type r',\n t ← expr.dsimp t { fail_if_unchanged := ff } tt [] [\n simp_arg_type.expr ``(monotone), simp_arg_type.expr ``(strict_mono)],\n match_rule_head pat [] r' t\n\nmeta def find_lemma (pat : expr) : list name → tactic (list expr)\n | [] := return []\n | (r :: rs) :=\n do (cons <$> match_rule pat r <|> pure id) <*> find_lemma rs\n\nmeta def match_chaining_rules (ls : list name) (x₀ x₁ : expr) : tactic (list expr) :=\ndo x' ← to_expr ``(%%x₁ → %%x₀),\n r₀ ← find_lemma x' ls,\n r₁ ← find_lemma x₁ ls,\n return (expr.app <$> r₀ <*> r₁)\n\nmeta def find_rule (ls : list name) : mono_law → tactic (list expr)\n | (mono_law.assoc (x₀,x₁) (y₀,y₁)) :=\n(match_chaining_rules ls x₀ x₁)\n<|> (match_chaining_rules ls y₀ y₁)\n | (mono_law.congr r) := return [r]\n | (mono_law.other p) := find_lemma p ls\n\nuniverses u v\n\ndef apply_rel {α : Sort u} (R : α → α → Sort v) {x y : α}\n (x' y' : α)\n (h : R x y)\n (hx : x = x')\n (hy : y = y')\n: R x' y' :=\nby { rw [← hx,← hy], apply h }\n\nmeta def ac_refine (e : expr) : tactic unit :=\nrefine ``(eq.mp _ %%e) ; ac_refl\n\nmeta def one_line (e : expr) : tactic format :=\ndo lbl ← pp e,\n asm ← infer_type e >>= pp,\n return format!\"\\t{asm}\\n\"\n\nmeta def side_conditions (e : expr) : tactic format :=\ndo let vs := e.list_meta_vars,\n ts ← mmap one_line vs.tail,\n let r := e.get_app_fn.const_name,\n return format!\"{r}:\\n{format.join ts}\"\n\nopen monad\n\n/-- tactic-facing function, similar to `interactive.tactic.generalize` with the\nexception that meta variables -/\nprivate meta def monotonicity.generalize' (h : name) (v : expr) (x : name) : tactic (expr × expr) :=\ndo tgt ← target,\n t ← infer_type v,\n tgt' ← do\n { ⟨tgt', _⟩ ← solve_aux tgt (tactic.generalize v x >> target),\n to_expr ``(λ y : %%t, Π x, y = x → %%(tgt'.binding_body.lift_vars 0 1)) }\n <|> to_expr ``(λ y : %%t, Π x, %%v = x → %%tgt),\n t ← head_beta (tgt' v) >>= assert h,\n swap,\n r ← mk_eq_refl v,\n solve1 $ tactic.exact (t v r),\n prod.mk <$> tactic.intro x <*> tactic.intro h\n\nprivate meta def hide_meta_vars (tac : list expr → tactic unit) : tactic unit :=\nfocus1 $\ndo tgt ← target >>= instantiate_mvars,\n tactic.change tgt,\n ctx ← local_context,\n let vs := tgt.list_meta_vars,\n vs' ← mmap (λ v,\n do h ← get_unused_name `h,\n x ← get_unused_name `x,\n prod.snd <$> monotonicity.generalize' h v x) vs,\n tac ctx;\n vs'.mmap' (try ∘ tactic.subst)\n\nmeta def hide_meta_vars' (tac : itactic) : itactic :=\nhide_meta_vars $ λ _, tac\n\nend config\n\nmeta def solve_mvar (v : expr) (tac : tactic unit) : tactic unit :=\ndo gs ← get_goals,\n set_goals [v],\n target >>= instantiate_mvars >>= tactic.change,\n tac, done,\n set_goals $ gs\n\ndef list.minimum_on {α β} [linear_order β] (f : α → β) : list α → list α\n| [] := []\n| (x :: xs) := prod.snd $ xs.foldl (λ ⟨k,a⟩ b,\n let k' := f b in\n if k < k' then (k,a)\n else if k' < k then (k', [b])\n else (k,b :: a)) (f x, [x])\n\nopen format mono_selection\n\nmeta def best_match {β} (xs : list expr) (tac : expr → tactic β) : tactic unit :=\ndo t ← target,\n xs ← xs.mmap (λ x,\n try_core $ prod.mk x <$> solve_aux t (tac x >> get_goals)),\n let xs := xs.filter_map id,\n let r := list.minimum_on (list.length ∘ prod.fst ∘ prod.snd) xs,\n match r with\n | [(_,gs,pr)] := tactic.exact pr >> set_goals gs\n | [] := fail \"no good match found\"\n | _ :=\n do lmms ← r.mmap (λ ⟨l,gs,_⟩,\n do ts ← gs.mmap infer_type,\n msg ← ts.mmap pp,\n pure $ foldl compose \"\\n\\n\" $\n list.intersperse \"\\n\" $ to_fmt l.get_app_fn.const_name :: msg),\n let msg := foldl compose \"\" lmms,\n fail format!(\"ambiguous match: {msg}\\n\\n\" ++\n \"Tip: try asserting a side condition to distinguish between the lemmas\")\n end\n\nmeta def mono_aux (dir : parse side) :\n tactic unit :=\ndo t ← target >>= instantiate_mvars,\n ns ← get_monotonicity_lemmas t dir,\n asms ← local_context,\n rs ← find_lemma asms t ns,\n focus1 $ () <$ best_match rs (λ law, tactic.refine $ to_pexpr law)\n\n/--\n- `mono` applies a monotonicity rule.\n- `mono*` applies monotonicity rules repetitively.\n- `mono with x ≤ y` or `mono with [0 ≤ x,0 ≤ y]` creates an assertion for the listed\n propositions. Those help to select the right monotonicity rule.\n- `mono left` or `mono right` is useful when proving strict orderings:\n for `x + y < w + z` could be broken down into either\n - left: `x ≤ w` and `y < z` or\n - right: `x < w` and `y ≤ z`\n- `mono using [rule1,rule2]` calls `simp [rule1,rule2]` before applying mono.\n- The general syntax is\n `mono '*'? ('with' hyp | 'with' [hyp1,hyp2])? ('using' [hyp1,hyp2])? mono_cfg?`\n\nTo use it, first import `tactic.monotonicity`.\n\nHere is an example of mono:\n\n```lean\nexample (x y z k : ℤ)\n (h : 3 ≤ (4 : ℤ))\n (h' : z ≤ y) :\n (k + 3 + x) - y ≤ (k + 4 + x) - z :=\nbegin\n mono, -- unfold `(-)`, apply add_le_add\n { -- ⊢ k + 3 + x ≤ k + 4 + x\n mono, -- apply add_le_add, refl\n -- ⊢ k + 3 ≤ k + 4\n mono },\n { -- ⊢ -y ≤ -z\n mono /- apply neg_le_neg -/ }\nend\n```\n\nMore succinctly, we can prove the same goal as:\n\n```lean\nexample (x y z k : ℤ)\n (h : 3 ≤ (4 : ℤ))\n (h' : z ≤ y) :\n (k + 3 + x) - y ≤ (k + 4 + x) - z :=\nby mono*\n```\n\n-/\nmeta def mono (many : parse (tk \"*\")?)\n (dir : parse side)\n (hyps : parse $ tk \"with\" *> pexpr_list_or_texpr <|> pure [])\n (simp_rules : parse $ tk \"using\" *> simp_arg_list <|> pure []) :\n tactic unit :=\ndo hyps ← hyps.mmap (λ p, to_expr p >>= mk_meta_var),\n hyps.mmap' (λ pr, do h ← get_unused_name `h, note h none pr),\n when (¬ simp_rules.empty) (simp_core { } failed tt simp_rules [] (loc.ns [none]) >> skip),\n if many.is_some\n then repeat $ mono_aux dir\n else mono_aux dir,\n gs ← get_goals,\n set_goals $ hyps ++ gs\n\nadd_tactic_doc\n{ name := \"mono\",\n category := doc_category.tactic,\n decl_names := [`tactic.interactive.mono],\n tags := [\"monotonicity\"] }\n\n/--\ntransforms a goal of the form `f x ≼ f y` into `x ≤ y` using lemmas\nmarked as `monotonic`.\n\nSpecial care is taken when `f` is the repeated application of an\nassociative operator and if the operator is commutative\n-/\nmeta def ac_mono_aux (cfg : mono_cfg := { mono_cfg . }) :\n tactic unit :=\nhide_meta_vars $ λ asms,\ndo try `[simp only [sub_eq_add_neg]],\n tgt ← target >>= instantiate_mvars,\n (l,r,id_rs,g) ← ac_monotonicity_goal cfg tgt\n <|> fail \"monotonic context not found\",\n ns ← get_monotonicity_lemmas tgt both,\n p ← mk_pattern g,\n rules ← find_rule asms ns p <|> fail \"no applicable rules found\",\n when (rules = []) (fail \"no applicable rules found\"),\n err ← format.join <$> mmap side_conditions rules,\n focus1 $ best_match rules (λ rule, do\n t₀ ← mk_meta_var `(Prop),\n v₀ ← mk_meta_var t₀,\n t₁ ← mk_meta_var `(Prop),\n v₁ ← mk_meta_var t₁,\n tactic.refine $ ``(apply_rel %%(g.rel_def) %%l %%r %%rule %%v₀ %%v₁),\n solve_mvar v₀ (try (any_of id_rs rewrite_target) >>\n ( done <|>\n refl <|>\n ac_refl <|>\n `[simp only [is_associative.assoc]]) ),\n solve_mvar v₁ (try (any_of id_rs rewrite_target) >>\n ( done <|>\n refl <|>\n ac_refl <|>\n `[simp only [is_associative.assoc]]) ),\n n ← num_goals,\n iterate_exactly (n-1) (try $ solve1 $ apply_instance <|>\n tactic.solve_by_elim { lemmas := some asms }))\n\nopen sum nat\n\n/-- (repeat_until_or_at_most n t u): repeat tactic `t` at most n times or until u succeeds -/\nmeta def repeat_until_or_at_most : nat → tactic unit → tactic unit → tactic unit\n| 0 t _ := fail \"too many applications\"\n| (succ n) t u := u <|> (t >> repeat_until_or_at_most n t u)\n\nmeta def repeat_until : tactic unit → tactic unit → tactic unit :=\nrepeat_until_or_at_most 100000\n\n@[derive _root_.has_reflect, derive _root_.inhabited]\ninductive rep_arity : Type\n| one | exactly (n : ℕ) | many\n\nmeta def repeat_or_not : rep_arity → tactic unit → option (tactic unit) → tactic unit\n | rep_arity.one tac none := tac\n | rep_arity.many tac none := repeat tac\n | (rep_arity.exactly n) tac none := iterate_exactly' n tac\n | rep_arity.one tac (some until) := tac >> until\n | rep_arity.many tac (some until) := repeat_until tac until\n | (rep_arity.exactly n) tac (some until) := iterate_exactly n tac >> until\n\nmeta def assert_or_rule : lean.parser (pexpr ⊕ pexpr) :=\n(tk \":=\" *> inl <$> texpr <|> (tk \":\" *> inr <$> texpr))\n\nmeta def arity : lean.parser rep_arity :=\ntk \"*\" *> pure rep_arity.many <|>\nrep_arity.exactly <$> (tk \"^\" *> small_nat) <|>\npure rep_arity.one\n\n/--\n\n`ac_mono` reduces the `f x ⊑ f y`, for some relation `⊑` and a\nmonotonic function `f` to `x ≺ y`.\n\n`ac_mono*` unwraps monotonic functions until it can't.\n\n`ac_mono^k`, for some literal number `k` applies monotonicity `k`\ntimes.\n\n`ac_mono := h`, with `h` a hypothesis, unwraps monotonic functions and\nuses `h` to solve the remaining goal. Can be combined with `*` or `^k`:\n`ac_mono* := h`\n\n`ac_mono : p` asserts `p` and uses it to discharge the goal result\nunwrapping a series of monotonic functions. Can be combined with * or\n^k: `ac_mono* : p`\n\nIn the case where `f` is an associative or commutative operator,\n`ac_mono` will consider any possible permutation of its arguments and\nuse the one the minimizes the difference between the left-hand side\nand the right-hand side.\n\nTo use it, first import `tactic.monotonicity`.\n\n`ac_mono` can be used as follows:\n\n```lean\nexample (x y z k m n : ℕ)\n (h₀ : z ≥ 0)\n (h₁ : x ≤ y) :\n (m + x + n) * z + k ≤ z * (y + n + m) + k :=\nbegin\n ac_mono,\n -- ⊢ (m + x + n) * z ≤ z * (y + n + m)\n ac_mono,\n -- ⊢ m + x + n ≤ y + n + m\n ac_mono,\nend\n```\n\nAs with `mono*`, `ac_mono*` solves the goal in one go and so does\n`ac_mono* := h₁`. The latter syntax becomes especially interesting in the\nfollowing example:\n\n```lean\nexample (x y z k m n : ℕ)\n (h₀ : z ≥ 0)\n (h₁ : m + x + n ≤ y + n + m) :\n (m + x + n) * z + k ≤ z * (y + n + m) + k :=\nby ac_mono* := h₁.\n```\n\nBy giving `ac_mono` the assumption `h₁`, we are asking `ac_refl` to\nstop earlier than it would normally would.\n-/\nmeta def ac_mono (rep : parse arity) :\n parse assert_or_rule? →\n opt_param mono_cfg { mono_cfg . } →\n tactic unit\n | none opt := focus1 $ repeat_or_not rep (ac_mono_aux opt) none\n | (some (inl h)) opt :=\ndo focus1 $ repeat_or_not rep (ac_mono_aux opt) (some $ done <|> to_expr h >>= ac_refine)\n | (some (inr t)) opt :=\ndo h ← i_to_expr t >>= assert `h,\n tactic.swap,\n focus1 $ repeat_or_not rep (ac_mono_aux opt) (some $ done <|> ac_refine h)\n/-\nTODO(Simon): with `ac_mono := h` and `ac_mono : p` split the remaining\n gaol if the provided rule does not solve it completely.\n-/\n\nadd_tactic_doc\n{ name := \"ac_mono\",\n category := doc_category.tactic,\n decl_names := [`tactic.interactive.ac_mono],\n tags := [\"monotonicity\"] }\n\nattribute [mono] and.imp or.imp\n\nend tactic.interactive\n", "meta": {"author": "leanprover-community", "repo": "mathlib", "sha": "5e526d18cea33550268dcbbddcb822d5cde40654", "save_path": "github-repos/lean/leanprover-community-mathlib", "path": "github-repos/lean/leanprover-community-mathlib/mathlib-5e526d18cea33550268dcbbddcb822d5cde40654/src/tactic/monotonicity/interactive.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.30404167496654744, "lm_q2_score": 0.035678548186143445, "lm_q1q2_score": 0.010847765550889727}} {"text": "/-\nCopyright (c) 2021 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Leonardo de Moura\n-/\nprelude\nimport Init.Control.Lawful\n\n/-!\nThe State monad transformer using CPS style.\n-/\n\ndef StateCpsT (σ : Type u) (m : Type u → Type v) (α : Type u) := (δ : Type u) → σ → (α → σ → m δ) → m δ\n\nnamespace StateCpsT\n\n@[always_inline, inline]\ndef runK {α σ : Type u} {m : Type u → Type v} (x : StateCpsT σ m α) (s : σ) (k : α → σ → m β) : m β :=\n x _ s k\n\n@[always_inline, inline]\ndef run {α σ : Type u} {m : Type u → Type v} [Monad m] (x : StateCpsT σ m α) (s : σ) : m (α × σ) :=\n runK x s (fun a s => pure (a, s))\n\n@[always_inline, inline]\ndef run' {α σ : Type u} {m : Type u → Type v} [Monad m] (x : StateCpsT σ m α) (s : σ) : m α :=\n runK x s (fun a _ => pure a)\n\n@[always_inline]\ninstance : Monad (StateCpsT σ m) where\n map f x := fun δ s k => x δ s fun a s => k (f a) s\n pure a := fun _ s k => k a s\n bind x f := fun δ s k => x δ s fun a s => f a δ s k\n\ninstance : LawfulMonad (StateCpsT σ m) := by\n refine' { .. } <;> intros <;> rfl\n\n@[always_inline]\ninstance : MonadStateOf σ (StateCpsT σ m) where\n get := fun _ s k => k s s\n set s := fun _ _ k => k ⟨⟩ s\n modifyGet f := fun _ s k => let (a, s) := f s; k a s\n\n@[always_inline, inline]\nprotected def lift [Monad m] (x : m α) : StateCpsT σ m α :=\n fun _ s k => x >>= (k . s)\n\ninstance [Monad m] : MonadLift m (StateCpsT σ m) where\n monadLift := StateCpsT.lift\n\n@[simp] theorem runK_pure {m : Type u → Type v} (a : α) (s : σ) (k : α → σ → m β) : (pure a : StateCpsT σ m α).runK s k = k a s := rfl\n\n@[simp] theorem runK_get {m : Type u → Type v} (s : σ) (k : σ → σ → m β) : (get : StateCpsT σ m σ).runK s k = k s s := rfl\n\n@[simp] theorem runK_set {m : Type u → Type v} (s s' : σ) (k : PUnit → σ → m β) : (set s' : StateCpsT σ m PUnit).runK s k = k ⟨⟩ s' := rfl\n\n@[simp] theorem runK_modify {m : Type u → Type v} (f : σ → σ) (s : σ) (k : PUnit → σ → m β) : (modify f : StateCpsT σ m PUnit).runK s k = k ⟨⟩ (f s) := rfl\n\n@[simp] theorem runK_lift {α σ : Type u} [Monad m] (x : m α) (s : σ) (k : α → σ → m β) : (StateCpsT.lift x : StateCpsT σ m α).runK s k = x >>= (k . s) := rfl\n\n@[simp] theorem runK_monadLift {σ : Type u} [Monad m] [MonadLiftT n m] (x : n α) (s : σ) (k : α → σ → m β)\n : (monadLift x : StateCpsT σ m α).runK s k = (monadLift x : m α) >>= (k . s) := rfl\n\n@[simp] theorem runK_bind_pure {α σ : Type u} [Monad m] (a : α) (f : α → StateCpsT σ m β) (s : σ) (k : β → σ → m γ) : (pure a >>= f).runK s k = (f a).runK s k := rfl\n\n@[simp] theorem runK_bind_lift {α σ : Type u} [Monad m] (x : m α) (f : α → StateCpsT σ m β) (s : σ) (k : β → σ → m γ)\n : (StateCpsT.lift x >>= f).runK s k = x >>= fun a => (f a).runK s k := rfl\n\n@[simp] theorem runK_bind_get {σ : Type u} [Monad m] (f : σ → StateCpsT σ m β) (s : σ) (k : β → σ → m γ) : (get >>= f).runK s k = (f s).runK s k := rfl\n\n@[simp] theorem runK_bind_set {σ : Type u} [Monad m] (f : PUnit → StateCpsT σ m β) (s s' : σ) (k : β → σ → m γ) : (set s' >>= f).runK s k = (f ⟨⟩).runK s' k := rfl\n\n@[simp] theorem runK_bind_modify {σ : Type u} [Monad m] (f : σ → σ) (g : PUnit → StateCpsT σ m β) (s : σ) (k : β → σ → m γ) : (modify f >>= g).runK s k = (g ⟨⟩).runK (f s) k := rfl\n\n@[simp] theorem run_eq [Monad m] (x : StateCpsT σ m α) (s : σ) : x.run s = x.runK s (fun a s => pure (a, s)) := rfl\n\n@[simp] theorem run'_eq [Monad m] (x : StateCpsT σ m α) (s : σ) : x.run' s = x.runK s (fun a _ => pure a) := rfl\n\nend StateCpsT\n", "meta": {"author": "leanprover", "repo": "lean4", "sha": "742d053a97bdd109a41a921facd1cd6a55e89bc7", "save_path": "github-repos/lean/leanprover-lean4", "path": "github-repos/lean/leanprover-lean4/lean4-742d053a97bdd109a41a921facd1cd6a55e89bc7/src/Init/Control/StateCps.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.30735800417608683, "lm_q2_score": 0.03514484804299783, "lm_q1q2_score": 0.010802050351567663}} {"text": "/-\nCopyright (c) 2016 Gabriel Ebner. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Gabriel Ebner, Sebastian Ullrich\n\nClassy functions for lifting monadic actions of different shapes.\n\nThis theory is roughly modeled after the Haskell 'layers' package https://hackage.haskell.org/package/layers-0.1.\nPlease see https://hackage.haskell.org/package/layers-0.1/docs/Documentation-Layers-Overview.html for an exhaustive discussion of the different approaches to lift functions.\n-/\nprelude\nimport init.function init.coe\nimport init.control.monad\n\nuniverses u v w\n\n/-- A function for lifting a computation from an inner monad to an outer monad.\n Like [MonadTrans](https://hackage.haskell.org/package/transformers-0.5.5.0/docs/Control-Monad-Trans-Class.html),\n but `n` does not have to be a monad transformer.\n Alternatively, an implementation of [MonadLayer](https://hackage.haskell.org/package/layers-0.1/docs/Control-Monad-Layer.html#t:MonadLayer) without `layerInvmap` (so far). -/\nclass has_monad_lift (m : Type u → Type v) (n : Type u → Type w) :=\n(monad_lift : ∀ {α}, m α → n α)\n\n/-- The reflexive-transitive closure of `has_monad_lift`.\n `monad_lift` is used to transitively lift monadic computations such as `state_t.get` or `state_t.put s`.\n Corresponds to [MonadLift](https://hackage.haskell.org/package/layers-0.1/docs/Control-Monad-Layer.html#t:MonadLift). -/\nclass has_monad_lift_t (m : Type u → Type v) (n : Type u → Type w) :=\n(monad_lift : ∀ {α}, m α → n α)\n\nexport has_monad_lift_t (monad_lift)\n\n/-- A coercion that may reduce the need for explicit lifting.\n Because of [limitations of the current coercion resolution](https://github.com/leanprover/lean/issues/1402), this definition is not marked as a global instance and should be marked locally instead. -/\n@[reducible] def has_monad_lift_to_has_coe {m n} [has_monad_lift_t m n] {α} : has_coe (m α) (n α) :=\n⟨monad_lift⟩\n\n@[priority 100]\ninstance has_monad_lift_t_trans (m n o) [has_monad_lift_t m n] [has_monad_lift n o] :\n has_monad_lift_t m o :=\n⟨λ α ma, has_monad_lift.monad_lift (monad_lift ma : n α)⟩\n\ninstance has_monad_lift_t_refl (m) : has_monad_lift_t m m :=\n⟨λ α, id⟩\n\n@[simp] lemma monad_lift_refl {m : Type u → Type v} {α} : (monad_lift : m α → m α) = id := rfl\n\n\n/-- A functor in the category of monads. Can be used to lift monad-transforming functions.\n Based on pipes' [MFunctor](https://hackage.haskell.org/package/pipes-2.4.0/docs/Control-MFunctor.html),\n but not restricted to monad transformers.\n Alternatively, an implementation of [MonadTransFunctor](http://duairc.netsoc.ie/layers-docs/Control-Monad-Layer.html#t:MonadTransFunctor). -/\nclass monad_functor (m m' : Type u → Type v) (n n' : Type u → Type w) :=\n(monad_map {α : Type u} : (∀ {α}, m α → m' α) → n α → n' α)\n\n/-- The reflexive-transitive closure of `monad_functor`.\n `monad_map` is used to transitively lift monad morphisms such as `state_t.zoom`.\n A generalization of [MonadLiftFunctor](http://duairc.netsoc.ie/layers-docs/Control-Monad-Layer.html#t:MonadLiftFunctor), which can only lift endomorphisms (i.e. m = m', n = n'). -/\nclass monad_functor_t (m m' : Type u → Type v) (n n' : Type u → Type w) :=\n(monad_map {α : Type u} : (∀ {α}, m α → m' α) → n α → n' α)\n\nexport monad_functor_t (monad_map)\n\n@[priority 100]\ninstance monad_functor_t_trans (m m' n n' o o') [monad_functor_t m m' n n'] [monad_functor n n' o o'] :\n monad_functor_t m m' o o' :=\n⟨λ α f, monad_functor.monad_map (λ α, (monad_map @f : n α → n' α))⟩\n\ninstance monad_functor_t_refl (m m') : monad_functor_t m m' m m' :=\n⟨λ α f, f⟩\n\n@[simp] lemma monad_map_refl {m m' : Type u → Type v} (f : ∀ {α}, m α → m' α) {α} : (monad_map @f : m α → m' α) = f := rfl\n\n\n/-- Run a monad stack to completion.\n `run` should be the composition of the transformers' individual `run` functions.\n This class mostly saves some typing when using highly nested monad stacks:\n ```\n @[reducible] def my_monad := reader_t my_cfg $ state_t my_state $ except_t my_err id\n -- def my_monad.run {α : Type} (x : my_monad α) (cfg : my_cfg) (st : my_state) := ((x.run cfg).run st).run\n def my_monad.run {α : Type} (x : my_monad α) := monad_run.run x\n ```\n -/\nclass monad_run (out : out_param $ Type u → Type v) (m : Type u → Type v) :=\n(run {α : Type u} : m α → out α)\n\nexport monad_run (run)\n", "meta": {"author": "subfish-zhou", "repo": "N2Lean", "sha": "8e858cc5b01f1ad921094dc355db3cb9473a42fd", "save_path": "github-repos/lean/subfish-zhou-N2Lean", "path": "github-repos/lean/subfish-zhou-N2Lean/N2Lean-8e858cc5b01f1ad921094dc355db3cb9473a42fd/library/init/control/lift.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.2720245392906821, "lm_q2_score": 0.03963884264629185, "lm_q1q2_score": 0.010782737908873382}} {"text": "/-\nCopyright (c) 2016 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Leonardo de Moura\n-/\nprelude\nimport init.meta.level init.control.monad init.meta.rb_map\nuniverses u v\nopen native\n/-- Column and line position in a Lean source file. -/\nstructure pos :=\n(line : nat)\n(column : nat)\n\ninstance : decidable_eq pos\n| ⟨l₁, c₁⟩ ⟨l₂, c₂⟩ := if h₁ : l₁ = l₂ then\n if h₂ : c₁ = c₂ then is_true (eq.rec_on h₁ (eq.rec_on h₂ rfl))\n else is_false (λ contra, pos.no_confusion contra (λ e₁ e₂, absurd e₂ h₂))\nelse is_false (λ contra, pos.no_confusion contra (λ e₁ e₂, absurd e₁ h₁))\n\nmeta instance : has_to_format pos :=\n⟨λ ⟨l, c⟩, \"⟨\" ++ l ++ \", \" ++ c ++ \"⟩\"⟩\n\n/-- Auxiliary annotation for binders (Lambda and Pi).\n This information is only used for elaboration.\n The difference between `{}` and `⦃⦄` is how implicit arguments are treated that are *not* followed by explicit arguments.\n `{}` arguments are applied eagerly, while `⦃⦄` arguments are left partially applied:\n```lean\ndef foo {x : ℕ} : ℕ := x\ndef bar ⦃x : ℕ⦄ : ℕ := x\n#check foo -- foo : ℕ\n#check bar -- bar : Π ⦃x : ℕ⦄, ℕ\n```\n -/\ninductive binder_info\n/- `(x : α)` -/\n| default\n/- `{x : α}` -/\n| implicit\n/- `⦃x:α⦄` -/\n| strict_implicit\n/- `[x : α]`. Should be inferred with typeclass resolution. -/\n| inst_implicit\n/- Auxiliary internal attribute used to mark local constants representing recursive functions\n in recursive equations and `match` statements. -/\n| aux_decl\n\ninstance : has_repr binder_info :=\n⟨λ bi, match bi with\n| binder_info.default := \"default\"\n| binder_info.implicit := \"implicit\"\n| binder_info.strict_implicit := \"strict_implicit\"\n| binder_info.inst_implicit := \"inst_implicit\"\n| binder_info.aux_decl := \"aux_decl\"\nend⟩\n/-- Macros are basically \"promises\" to build an expr by some C++ code, you can't build them in Lean.\n You can unfold a macro and force it to evaluate.\n They are used for\n - `sorry`.\n - Term placeholders (`_`) in `pexpr`s.\n - Expression annotations. See `expr.is_annotation`.\n - Meta-recursive calls. Eg:\n ```\n meta def Y : (α → α) → α | f := f (Y f)\n ```\n The `Y` that appears in `f (Y f)` is a macro.\n - Builtin projections:\n ```\n structure foo := (mynat : ℕ)\n #print foo.mynat\n -- @[reducible]\n -- def foo.mynat : foo → ℕ :=\n -- λ (c : foo), [foo.mynat c]\n ```\n The thing in square brackets is a macro.\n - Ephemeral structures inside certain specialised C++ implemented tactics.\n -/\nmeta constant macro_def : Type\n\n/-- An expression. eg ```(4+5)```.\n\n The `elab` flag is indicates whether the `expr` has been elaborated and doesn't contain any placeholder macros.\n For example the equality `x = x` is represented in `expr ff` as ``app (app (const `eq _) x) x`` while in `expr tt` it is represented as ``app (app (app (const `eq _) t) x) x`` (one more argument).\n The VM replaces instances of this datatype with the C++ implementation. -/\nmeta inductive expr (elaborated : bool := tt)\n/- A bound variable with a de-Bruijn index. -/\n| var : nat → expr\n/- A type universe: `Sort u` -/\n| sort : level → expr\n/- A global constant. These include definitions, constants and inductive type stuff present\nin the environment as well as hard-coded definitions. -/\n| const : name → list level → expr\n/- [WARNING] Do not trust the types for `mvar` and `local_const`,\nthey are sometimes dummy values. Use `tactic.infer_type` instead. -/\n/- An `mvar` is a 'hole' yet to be filled in by the elaborator or tactic state. -/\n| mvar (unique : name) (pretty : name) (type : expr) : expr\n/- A local constant. For example, if our tactic state was `h : P ⊢ Q`, `h` would be a local constant. -/\n| local_const (unique : name) (pretty : name) (bi : binder_info) (type : expr) : expr\n/- Function application. -/\n| app : expr → expr → expr\n/- Lambda abstraction. eg ```(λ a : α, x)`` -/\n| lam (var_name : name) (bi : binder_info) (var_type : expr) (body : expr) : expr\n/- Pi type constructor. eg ```(Π a : α, x)`` and ```(α → β)`` -/\n| pi (var_name : name) (bi : binder_info) (var_type : expr) (body : expr) : expr\n/- An explicit let binding. -/\n| elet (var_name : name) (type : expr) (assignment : expr) (body : expr) : expr\n/- A macro, see the docstring for `macro_def`.\n The list of expressions are local constants and metavariables that the macro depends on.\n -/\n| macro : macro_def → list expr → expr\n\nvariable {elab : bool}\n\nmeta instance : inhabited (expr elab) := ⟨expr.sort level.zero⟩\n\n/-- Get the name of the macro definition. -/\nmeta constant expr.macro_def_name (d : macro_def) : name\nmeta def expr.mk_var (n : nat) : expr := expr.var n\n\n/-- Expressions can be annotated using an annotation macro during compilation.\nFor example, a `have x:X, from p, q` expression will be compiled to `(λ x:X,q)(p)`, but nested in an annotation macro with the name `\"have\"`.\nThese annotations have no real semantic meaning, but are useful for helping Lean's pretty printer. -/\nmeta constant expr.is_annotation : expr elab → option (name × expr elab)\n\nmeta constant expr.is_string_macro : expr elab → option (expr elab)\n\n/-- Remove all macro annotations from the given `expr`. -/\nmeta def expr.erase_annotations : expr elab → expr elab\n| e :=\n match e.is_annotation with\n | some (_, a) := expr.erase_annotations a\n | none := e\n end\n\n/-- Compares expressions, including binder names. -/\nmeta constant expr.has_decidable_eq : decidable_eq expr\nattribute [instance] expr.has_decidable_eq\n\n/-- Compares expressions while ignoring binder names. -/\nmeta constant expr.alpha_eqv : expr → expr → bool\nnotation a ` =ₐ `:50 b:50 := expr.alpha_eqv a b = bool.tt\n\nprotected meta constant expr.to_string : expr elab → string\n\nmeta instance : has_to_string (expr elab) := ⟨expr.to_string⟩\nmeta instance : has_to_format (expr elab) := ⟨λ e, e.to_string⟩\n\n/-- Coercion for letting users write (f a) instead of (expr.app f a) -/\nmeta instance : has_coe_to_fun (expr elab) (λ e, expr elab → expr elab) :=\n⟨λ e, expr.app e⟩\n\n/-- Each expression created by Lean carries a hash.\nThis is calculated upon creation of the expression.\nTwo structurally equal expressions will have the same hash. -/\nmeta constant expr.hash : expr → nat\n\n/-- Compares expressions, ignoring binder names, and sorting by hash. -/\nmeta constant expr.lt : expr → expr → bool\n/-- Compares expressions, ignoring binder names. -/\nmeta constant expr.lex_lt : expr → expr → bool\n\n/-- `expr.fold e a f`: Traverses each subexpression of `e`. The `nat` passed to the folder `f` is the binder depth. -/\nmeta constant expr.fold {α : Type} : expr → α → (expr → nat → α → α) → α\n/-- `expr.replace e f`\n Traverse over an expr `e` with a function `f` which can decide to replace subexpressions or not.\n For each subexpression `s` in the expression tree, `f s n` is called where `n` is how many binders are present above the given subexpression `s`.\n If `f s n` returns `none`, the children of `s` will be traversed.\n Otherwise if `some s'` is returned, `s'` will replace `s` and this subexpression will not be traversed further.\n -/\nmeta constant expr.replace : expr → (expr → nat → option expr) → expr\n\n/-- `abstract_local e n` replaces each instance of the local constant with unique (not pretty) name `n` in `e` with a de-Bruijn variable. -/\nmeta constant expr.abstract_local : expr → name → expr\n/-- Multi version of `abstract_local`. Note that the given expression will only be traversed once, so this is not the same as `list.foldl expr.abstract_local`.-/\nmeta constant expr.abstract_locals : expr → list name → expr\n/-- `abstract e x` Abstracts the expression `e` over the local constant `x`. -/\nmeta def expr.abstract : expr → expr → expr\n| e (expr.local_const n m bi t) := e.abstract_local n\n| e _ := e\n\n/-- Expressions depend on `level`s, and these may depend on universe parameters which have names.\n`instantiate_univ_params e [(n₁,l₁), ...]` will traverse `e` and replace any universe parameters with name `nᵢ` with the corresponding level `lᵢ`. -/\nmeta constant expr.instantiate_univ_params : expr → list (name × level) → expr\n/-- `instantiate_nth_var n a b` takes the `n`th de-Bruijn variable in `a` and replaces each occurrence with `b`. -/\nmeta constant expr.instantiate_nth_var : nat → expr → expr → expr\n/-- `instantiate_var a b` takes the 0th de-Bruijn variable in `a` and replaces each occurrence with `b`. -/\nmeta constant expr.instantiate_var : expr → expr → expr\n/-- ``instantiate_vars `(#0 #1 #2) [x,y,z] = `(%%x %%y %%z)`` -/\nmeta constant expr.instantiate_vars : expr → list expr → expr\n/-- Same as `instantiate_vars` except lifts and shifts the vars by the given amount.\n``instantiate_vars_core `(#0 #1 #2 #3) 0 [x,y] = `(x y #0 #1)``\n``instantiate_vars_core `(#0 #1 #2 #3) 1 [x,y] = `(#0 x y #1)``\n``instantiate_vars_core `(#0 #1 #2 #3) 2 [x,y] = `(#0 #1 x y)``\n-/\nmeta constant expr.instantiate_vars_core : expr → nat → list expr → expr\n/-- Perform beta-reduction if the left expression is a lambda, or construct an application otherwise.\nThat is: ``expr.subst `(λ x, %%Y) Z = Y[x/Z]``, and\n``expr.subst X Z = X.app Z`` otherwise -/\nprotected meta constant expr.subst : expr elab → expr elab → expr elab\n\n/-- `get_free_var_range e` returns one plus the maximum de-Bruijn value in `e`. Eg `get_free_var_range `(#1 #0)` yields `2` -/\nmeta constant expr.get_free_var_range : expr → nat\n/-- `has_var e` returns true iff e has free variables. -/\nmeta constant expr.has_var : expr → bool\n/-- `has_var_idx e n` returns true iff `e` has a free variable with de-Bruijn index `n`. -/\nmeta constant expr.has_var_idx : expr → nat → bool\n/-- `has_local e` returns true if `e` contains a local constant. -/\nmeta constant expr.has_local : expr → bool\n/-- `has_meta_var e` returns true iff `e` contains a metavariable. -/\nmeta constant expr.has_meta_var : expr → bool\n/-- `lower_vars e s d` lowers the free variables >= s in `e` by `d`. Note that this can cause variable clashes.\n examples:\n - ``lower_vars `(#2 #1 #0) 1 1 = `(#1 #0 #0)``\n - ``lower_vars `(λ x, #2 #1 #0) 1 1 = `(λ x, #1 #1 #0 )``\n -/\nmeta constant expr.lower_vars : expr → nat → nat → expr\n/-- Lifts free variables. `lift_vars e s d` will lift all free variables with index `≥ s` in `e` by `d`. -/\nmeta constant expr.lift_vars : expr → nat → nat → expr\n/-- Get the position of the given expression in the Lean source file, if anywhere. -/\nprotected meta constant expr.pos : expr elab → option pos\n/-- `copy_pos_info src tgt` copies position information from `src` to `tgt`. -/\nmeta constant expr.copy_pos_info : expr → expr → expr\n/-- Returns `some n` when the given expression is a constant with the name `..._cnstr.n`\n```\nis_internal_cnstr : expr → option unsigned\n|(const (mk_numeral n (mk_string \"_cnstr\" _)) _) := some n\n|_ := none\n```\n[NOTE] This is not used anywhere in core Lean.\n-/\nmeta constant expr.is_internal_cnstr : expr → option unsigned\n/-- There is a macro called a \"nat_value_macro\" holding a natural number which are used during compilation.\nThis function extracts that to a natural number. [NOTE] This is not used anywhere in Lean. -/\nmeta constant expr.get_nat_value : expr → option nat\n/-- Get a list of all of the universe parameters that the given expression depends on. -/\nmeta constant expr.collect_univ_params : expr → list name\n/-- `occurs e t` returns `tt` iff `e` occurs in `t` up to α-equivalence. Purely structural: no unification or definitional equality. -/\nmeta constant expr.occurs : expr → expr → bool\n/-- Returns true if any of the names in the given `name_set` are present in the given `expr`. -/\nmeta constant expr.has_local_in : expr → name_set → bool\n\n/-- Computes the number of sub-expressions (constant time). -/\nmeta constant expr.get_weight : expr → ℕ\n/-- Computes the maximum depth of the expression (constant time). -/\nmeta constant expr.get_depth : expr → ℕ\n\n/-- `mk_delayed_abstraction m ls` creates a delayed abstraction on the metavariable `m` with the unique names of the local constants `ls`.\n If `m` is not a metavariable then this is equivalent to `abstract_locals`.\n -/\nmeta constant expr.mk_delayed_abstraction : expr → list name → expr\n/-- If the given expression is a delayed abstraction macro, return `some ls`\nwhere `ls` is a list of unique names of locals that will be abstracted. -/\nmeta constant expr.get_delayed_abstraction_locals : expr → option (list name)\n\n/-- (reflected a) is a special opaque container for a closed `expr` representing `a`.\n It can only be obtained via type class inference, which will use the representation\n of `a` in the calling context. Local constants in the representation are replaced\n by nested inference of `reflected` instances.\n\n The quotation expression `` `(a) `` (outside of patterns) is equivalent to `reflect a`\n and thus can be used as an explicit way of inferring an instance of `reflected a`. -/\n@[class] meta def reflected {α : Sort u} : α → Type :=\nλ _, expr\n\n@[inline] meta def reflected.to_expr {α : Sort u} {a : α} : reflected a → expr :=\nid\n\n@[inline] meta def reflected.subst {α : Sort v} {β : α → Sort u} {f : Π a : α, β a} {a : α} :\n reflected f → reflected a → reflected (f a) :=\nexpr.subst\n\nattribute [irreducible] reflected reflected.subst reflected.to_expr\n\n@[instance] protected meta constant expr.reflect (e : expr elab) : reflected e\n@[instance] protected meta constant string.reflect (s : string) : reflected s\n\n@[inline] meta instance {α : Sort u} (a : α) : has_coe (reflected a) expr :=\n⟨reflected.to_expr⟩\n\nprotected meta def reflect {α : Sort u} (a : α) [h : reflected a] : reflected a := h\n\nmeta instance {α} (a : α) : has_to_format (reflected a) :=\n⟨λ h, to_fmt h.to_expr⟩\n\nnamespace expr\nopen decidable\n\nmeta def lt_prop (a b : expr) : Prop :=\nexpr.lt a b = tt\n\nmeta instance : decidable_rel expr.lt_prop :=\nλ a b, bool.decidable_eq _ _\n\n/-- Compares expressions, ignoring binder names, and sorting by hash. -/\nmeta instance : has_lt expr :=\n⟨ expr.lt_prop ⟩\n\nmeta def mk_true : expr :=\nconst `true []\n\nmeta def mk_false : expr :=\nconst `false []\n\n/-- Returns the sorry macro with the given type. -/\nmeta constant mk_sorry (type : expr) : expr\n/-- Checks whether e is sorry, and returns its type. -/\nmeta constant is_sorry (e : expr) : option expr\n\n/-- Replace each instance of the local constant with name `n` by the expression `s` in `e`. -/\nmeta def instantiate_local (n : name) (s : expr) (e : expr) : expr :=\ninstantiate_var (abstract_local e n) s\n\nmeta def instantiate_locals (s : list (name × expr)) (e : expr) : expr :=\ninstantiate_vars (abstract_locals e (list.reverse (list.map prod.fst s))) (list.map prod.snd s)\n\nmeta def is_var : expr → bool\n| (var _) := tt\n| _ := ff\n\nmeta def app_of_list : expr → list expr → expr\n| f [] := f\n| f (p::ps) := app_of_list (f p) ps\n\nmeta def is_app : expr → bool\n| (app f a) := tt\n| e := ff\n\nmeta def app_fn : expr → expr\n| (app f a) := f\n| a := a\n\nmeta def app_arg : expr → expr\n| (app f a) := a\n| a := a\n\nmeta def get_app_fn : expr elab → expr elab\n| (app f a) := get_app_fn f\n| a := a\n\nmeta def get_app_num_args : expr → nat\n| (app f a) := get_app_num_args f + 1\n| e := 0\n\nmeta def get_app_args_aux : list expr → expr → list expr\n| r (app f a) := get_app_args_aux (a::r) f\n| r e := r\n\nmeta def get_app_args : expr → list expr :=\nget_app_args_aux []\n\nmeta def mk_app : expr → list expr → expr\n| e [] := e\n| e (x::xs) := mk_app (e x) xs\n\nmeta def mk_binding (ctor : name → binder_info → expr → expr → expr) (e : expr) : Π (l : expr), expr\n| (local_const n pp_n bi ty) := ctor pp_n bi ty (e.abstract_local n)\n| _ := e\n\n/-- (bind_pi e l) abstracts and pi-binds the local `l` in `e` -/\nmeta def bind_pi := mk_binding pi\n/-- (bind_lambda e l) abstracts and lambda-binds the local `l` in `e` -/\nmeta def bind_lambda := mk_binding lam\n\nmeta def ith_arg_aux : expr → nat → expr\n| (app f a) 0 := a\n| (app f a) (n+1) := ith_arg_aux f n\n| e _ := e\n\nmeta def ith_arg (e : expr) (i : nat) : expr :=\nith_arg_aux e (get_app_num_args e - i - 1)\n\nmeta def const_name : expr elab → name\n| (const n ls) := n\n| e := name.anonymous\n\nmeta def is_constant : expr elab → bool\n| (const n ls) := tt\n| e := ff\n\nmeta def is_local_constant : expr → bool\n| (local_const n m bi t) := tt\n| e := ff\n\nmeta def local_uniq_name : expr → name\n| (local_const n m bi t) := n\n| e := name.anonymous\n\nmeta def local_pp_name : expr elab → name\n| (local_const x n bi t) := n\n| e := name.anonymous\n\nmeta def local_type : expr elab → expr elab\n| (local_const _ _ _ t) := t\n| e := e\n\nmeta def is_aux_decl : expr → bool\n| (local_const _ _ binder_info.aux_decl _) := tt\n| _ := ff\n\nmeta def is_constant_of : expr elab → name → bool\n| (const n₁ ls) n₂ := n₁ = n₂\n| e n := ff\n\nmeta def is_app_of (e : expr) (n : name) : bool :=\nis_constant_of (get_app_fn e) n\n\n/-- The same as `is_app_of` but must also have exactly `n` arguments. -/\nmeta def is_napp_of (e : expr) (c : name) (n : nat) : bool :=\nis_app_of e c ∧ get_app_num_args e = n\n\nmeta def is_false : expr → bool\n| `(false) := tt\n| _ := ff\n\nmeta def is_not : expr → option expr\n| `(not %%a) := some a\n| `(%%a → false) := some a\n| e := none\n\nmeta def is_and : expr → option (expr × expr)\n| `(and %%α %%β) := some (α, β)\n| _ := none\n\nmeta def is_or : expr → option (expr × expr)\n| `(or %%α %%β) := some (α, β)\n| _ := none\n\nmeta def is_iff : expr → option (expr × expr)\n| `((%%a : Prop) ↔ %%b) := some (a, b)\n| _ := none\n\nmeta def is_eq : expr → option (expr × expr)\n| `((%%a : %%_) = %%b) := some (a, b)\n| _ := none\n\nmeta def is_ne : expr → option (expr × expr)\n| `((%%a : %%_) ≠ %%b) := some (a, b)\n| _ := none\n\nmeta def is_bin_arith_app (e : expr) (op : name) : option (expr × expr) :=\nif is_napp_of e op 4\nthen some (app_arg (app_fn e), app_arg e)\nelse none\n\nmeta def is_lt (e : expr) : option (expr × expr) :=\nis_bin_arith_app e ``has_lt.lt\n\nmeta def is_gt (e : expr) : option (expr × expr) :=\nis_bin_arith_app e ``gt\n\nmeta def is_le (e : expr) : option (expr × expr) :=\nis_bin_arith_app e ``has_le.le\n\nmeta def is_ge (e : expr) : option (expr × expr) :=\nis_bin_arith_app e ``ge\n\nmeta def is_heq : expr → option (expr × expr × expr × expr)\n| `(@heq %%α %%a %%β %%b) := some (α, a, β, b)\n| _ := none\n\nmeta def is_lambda : expr → bool\n| (lam _ _ _ _) := tt\n| e := ff\n\nmeta def is_pi : expr → bool\n| (pi _ _ _ _) := tt\n| e := ff\n\nmeta def is_arrow : expr → bool\n| (pi _ _ _ b) := bnot (has_var b)\n| e := ff\n\nmeta def is_let : expr → bool\n| (elet _ _ _ _) := tt\n| e := ff\n\n/-- The name of the bound variable in a pi, lambda or let expression. -/\nmeta def binding_name : expr → name\n| (pi n _ _ _) := n\n| (lam n _ _ _) := n\n| (elet n _ _ _) := n\n| e := name.anonymous\n\n/-- The binder info of a pi or lambda expression. -/\nmeta def binding_info : expr → binder_info\n| (pi _ bi _ _) := bi\n| (lam _ bi _ _) := bi\n| e := binder_info.default\n\n/-- The domain (type of bound variable) of a pi, lambda or let expression. -/\nmeta def binding_domain : expr → expr\n| (pi _ _ d _) := d\n| (lam _ _ d _) := d\n| (elet _ d _ _) := d\n| e := e\n\n/-- The body of a pi, lambda or let expression.\n This definition doesn't instantiate bound variables, and therefore produces a term that is open.\n See note [open expressions] in mathlib. -/\nmeta def binding_body : expr → expr\n| (pi _ _ _ b) := b\n| (lam _ _ _ b) := b\n| (elet _ _ _ b) := b\n| e := e\n\n/-- `nth_binding_body n e` iterates `binding_body` `n` times to an iterated pi expression `e`.\n This definition doesn't instantiate bound variables, and therefore produces a term that is open.\n See note [open expressions] in mathlib. -/\nmeta def nth_binding_body : ℕ → expr → expr\n| (n + 1) (pi _ _ _ b) := nth_binding_body n b\n| _ e := e\n\nmeta def is_macro : expr → bool\n| (macro d a) := tt\n| e := ff\n\nmeta def is_numeral : expr → bool\n| `(@has_zero.zero %%α %%s) := tt\n| `(@has_one.one %%α %%s) := tt\n| `(@bit0 %%α %%s %%v) := is_numeral v\n| `(@bit1 %%α %%s₁ %%s₂ %%v) := is_numeral v\n| _ := ff\n\nmeta def pi_arity : expr → ℕ\n| (pi _ _ _ b) := pi_arity b + 1\n| _ := 0\n\nmeta def lam_arity : expr → ℕ\n| (lam _ _ _ b) := lam_arity b + 1\n| _ := 0\n\nmeta def imp (a b : expr) : expr :=\npi `_ binder_info.default a b\n\n/-- `lambdas cs e` lambda binds `e` with each of the local constants in `cs`. -/\nmeta def lambdas : list expr → expr → expr\n| (local_const uniq pp info t :: es) f :=\n lam pp info t (abstract_local (lambdas es f) uniq)\n| _ f := f\n/-- Same as `expr.lambdas` but with `pi`. -/\nmeta def pis : list expr → expr → expr\n| (local_const uniq pp info t :: es) f :=\n pi pp info t (abstract_local (pis es f) uniq)\n| _ f := f\n\nmeta def extract_opt_auto_param : expr → expr\n| `(@opt_param %%t _) := extract_opt_auto_param t\n| `(@auto_param %%t _) := extract_opt_auto_param t\n| e := e\n\nopen format\n\nprivate meta def p : list format → format\n| [] := \"\"\n| [x] := x.paren\n| (x::y::xs) := p ((x ++ format.line ++ y).group :: xs)\n\nmeta def to_raw_fmt : expr elab → format\n| (var n) := p [\"var\", to_fmt n]\n| (sort l) := p [\"sort\", to_fmt l]\n| (const n ls) := p [\"const\", to_fmt n, to_fmt ls]\n| (mvar n m t) := p [\"mvar\", to_fmt n, to_fmt m, to_raw_fmt t]\n| (local_const n m bi t) := p [\"local_const\", to_fmt n, to_fmt m, to_raw_fmt t]\n| (app e f) := p [\"app\", to_raw_fmt e, to_raw_fmt f]\n| (lam n bi e t) := p [\"lam\", to_fmt n, repr bi, to_raw_fmt e, to_raw_fmt t]\n| (pi n bi e t) := p [\"pi\", to_fmt n, repr bi, to_raw_fmt e, to_raw_fmt t]\n| (elet n g e f) := p [\"elet\", to_fmt n, to_raw_fmt g, to_raw_fmt e, to_raw_fmt f]\n| (macro d args) := sbracket (format.join (list.intersperse \" \" (\"macro\" :: to_fmt (macro_def_name d) :: args.map to_raw_fmt)))\n\n/-- Fold an accumulator `a` over each subexpression in the expression `e`.\nThe `nat` passed to `fn` is the number of binders above the subexpression. -/\nmeta def mfold {α : Type} {m : Type → Type} [monad m] (e : expr) (a : α) (fn : expr → nat → α → m α) : m α :=\nfold e (return a) (λ e n a, a >>= fn e n)\n\nend expr\n\n/-- An dictionary from `data` to expressions. -/\n@[reducible] meta def expr_map (data : Type) := rb_map expr data\nnamespace expr_map\nexport native.rb_map (mk_core size empty insert erase contains find min max fold\n keys values to_list mfold of_list set_of_list map for filter)\n\nmeta def mk (data : Type) : expr_map data := rb_map.mk expr data\nend expr_map\n\nmeta def mk_expr_map {data : Type} : expr_map data :=\nexpr_map.mk data\n\n@[reducible] meta def expr_set := rb_set expr\nmeta def mk_expr_set : expr_set := mk_rb_set\n", "meta": {"author": "subfish-zhou", "repo": "N2Lean", "sha": "8e858cc5b01f1ad921094dc355db3cb9473a42fd", "save_path": "github-repos/lean/subfish-zhou-N2Lean", "path": "github-repos/lean/subfish-zhou-N2Lean/N2Lean-8e858cc5b01f1ad921094dc355db3cb9473a42fd/library/init/meta/expr.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3208212878370535, "lm_q2_score": 0.0335895055291764, "lm_q1q2_score": 0.010776228421680202}} {"text": "/-\nFile: signature_recover_public_key_ec_mul_inner_soundness.lean\n\nAutogenerated file.\n-/\nimport starkware.cairo.lean.semantics.soundness.hoare\nimport .signature_recover_public_key_code\nimport ..signature_recover_public_key_spec\nimport .signature_recover_public_key_fast_ec_add_soundness\nimport .signature_recover_public_key_ec_double_soundness\nopen tactic\n\nopen starkware.cairo.common.cairo_secp.ec\nopen starkware.cairo.common.cairo_secp.bigint\nopen starkware.cairo.common.cairo_secp.field\n\nvariables {F : Type} [field F] [decidable_eq F] [prelude_hyps F]\nvariable mem : F → F\nvariable σ : register_state F\n\n/- starkware.cairo.common.cairo_secp.ec.ec_mul_inner autogenerated soundness theorem -/\n\ntheorem auto_sound_ec_mul_inner\n -- arguments\n (range_check_ptr : F) (point : EcPoint F) (scalar m : F)\n -- code is in memory at σ.pc\n (h_mem : mem_at mem code_ec_mul_inner σ.pc)\n -- all dependencies are in memory\n (h_mem_4 : mem_at mem code_nondet_bigint3 (σ.pc - 460))\n (h_mem_5 : mem_at mem code_unreduced_mul (σ.pc - 448))\n (h_mem_6 : mem_at mem code_unreduced_sqr (σ.pc - 428))\n (h_mem_7 : mem_at mem code_verify_zero (σ.pc - 412))\n (h_mem_12 : mem_at mem code_compute_doubling_slope (σ.pc - 284))\n (h_mem_13 : mem_at mem code_compute_slope (σ.pc - 240))\n (h_mem_14 : mem_at mem code_ec_double (σ.pc - 216))\n (h_mem_15 : mem_at mem code_fast_ec_add (σ.pc - 143))\n -- input arguments on the stack\n (hin_range_check_ptr : range_check_ptr = mem (σ.fp - 11))\n (hin_point : point = cast_EcPoint mem (σ.fp - 10))\n (hin_scalar : scalar = mem (σ.fp - 4))\n (hin_m : m = mem (σ.fp - 3))\n -- conclusion\n : ensures_ret mem σ (λ κ τ,\n ∃ μ ≤ κ, rc_ensures mem (rc_bound F) μ (mem (σ.fp - 11)) (mem $ τ.ap - 13)\n (spec_ec_mul_inner mem κ range_check_ptr point scalar m (mem (τ.ap - 13)) (cast_EcPoint mem (τ.ap - 12)) (cast_EcPoint mem (τ.ap - 6)))) :=\nbegin\n apply ensures_of_ensuresb, intro νbound,\n revert σ range_check_ptr point scalar m h_mem h_mem_4 h_mem_5 h_mem_6 h_mem_7 h_mem_12 h_mem_13 h_mem_14 h_mem_15 hin_range_check_ptr hin_point hin_scalar hin_m,\n induction νbound with νbound νih,\n { intros, intros n nlt, apply absurd nlt (nat.not_lt_zero _) },\n intros σ range_check_ptr point scalar m h_mem h_mem_4 h_mem_5 h_mem_6 h_mem_7 h_mem_12 h_mem_13 h_mem_14 h_mem_15 hin_range_check_ptr hin_point hin_scalar hin_m,\n dsimp at νih,\n have h_mem_rec := h_mem,\n unpack_memory code_ec_mul_inner at h_mem with ⟨hpc0, hpc1, hpc2, hpc3, hpc4, hpc5, hpc6, hpc7, hpc8, hpc9, hpc10, hpc11, hpc12, hpc13, hpc14, hpc15, hpc16, hpc17, hpc18, hpc19, hpc20, hpc21, hpc22, hpc23, hpc24, hpc25, hpc26, hpc27, hpc28, hpc29, hpc30, hpc31, hpc32, hpc33, hpc34, hpc35, hpc36, hpc37, hpc38, hpc39, hpc40, hpc41, hpc42, hpc43, hpc44, hpc45, hpc46, hpc47, hpc48, hpc49, hpc50, hpc51, hpc52, hpc53, hpc54, hpc55, hpc56, hpc57, hpc58, hpc59, hpc60, hpc61, hpc62, hpc63, hpc64, hpc65, hpc66, hpc67, hpc68, hpc69, hpc70, hpc71, hpc72, hpc73, hpc74, hpc75, hpc76, hpc77, hpc78, hpc79, hpc80, hpc81, hpc82, hpc83, hpc84, hpc85, hpc86, hpc87, hpc88, hpc89, hpc90, hpc91, hpc92, hpc93, hpc94, hpc95, hpc96, hpc97, hpc98, hpc99, hpc100⟩,\n -- if statement\n step_jnz hpc0 hpc1 with hcond hcond,\n {\n -- if: positive branch\n have a0 : m = 0, {\n try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point, hin_scalar, hin_m] },\n try { dsimp [cast_EcPoint, cast_BigInt3] },\n try { arith_simps }, try { simp only [hcond] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },\n },\n try { dsimp at a0 }, try { arith_simps at a0 },\n clear hcond,\n -- assert eq\n step_assert_eq hpc2 hpc3 with temp0,\n have a2: scalar = 0, {\n apply assert_eq_reduction temp0,\n try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point, hin_scalar, hin_m] },\n try { dsimp [cast_EcPoint, cast_BigInt3] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },\n },\n try { dsimp at a2 }, try { arith_simps at a2 },\n clear temp0,\n -- let\n generalize' hl_rev_ZERO_POINT: ({\n x := { d0 := 0, d1 := 0, d2 := 0 },\n y := { d0 := 0, d1 := 0, d2 := 0 }\n } : EcPoint F) = ZERO_POINT,\n have hl_ZERO_POINT := hl_rev_ZERO_POINT.symm, clear hl_rev_ZERO_POINT,\n try { dsimp at hl_ZERO_POINT }, try { arith_simps at hl_ZERO_POINT },\n -- return\n step_assert_eq hpc4 with hret0,\n step_assert_eq hpc5 with hret1,\n step_assert_eq hpc6 with hret2,\n step_assert_eq hpc7 with hret3,\n step_assert_eq hpc8 with hret4,\n step_assert_eq hpc9 with hret5,\n step_assert_eq hpc10 with hret6,\n step_assert_eq hpc11 hpc12 with hret7,\n step_assert_eq hpc13 hpc14 with hret8,\n step_assert_eq hpc15 hpc16 with hret9,\n step_assert_eq hpc17 hpc18 with hret10,\n step_assert_eq hpc19 hpc20 with hret11,\n step_assert_eq hpc21 hpc22 with hret12,\n step_ret hpc23,\n -- finish\n step_done, use_only [rfl, rfl],\n -- range check condition\n use_only (0+0), split,\n linarith [],\n split,\n { arith_simps, try { simp only [hret0 ,hret1 ,hret2 ,hret3 ,hret4 ,hret5 ,hret6 ,hret7 ,hret8 ,hret9 ,hret10 ,hret11 ,hret12] },\n try { arith_simps, refl <|> norm_cast }, try { refl } },\n intro rc_h_range_check_ptr, repeat { rw [add_assoc] at rc_h_range_check_ptr },\n have rc_h_range_check_ptr' := range_checked_add_right rc_h_range_check_ptr,\n -- Final Proof\n -- user-provided reduction\n suffices auto_spec: auto_spec_ec_mul_inner mem _ range_check_ptr point scalar m _ _ _,\n { apply sound_ec_mul_inner, apply auto_spec },\n -- prove the auto generated assertion\n dsimp [auto_spec_ec_mul_inner],\n try { norm_num1 }, try { arith_simps },\n left,\n use_only [a0],\n use_only [a2],\n use_only [ZERO_POINT, hl_ZERO_POINT],\n try { split, linarith },\n try { ensures_simps; try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point, hin_scalar, hin_m, hl_ZERO_POINT] }, },\n try { dsimp [cast_EcPoint, cast_BigInt3] },\n try { arith_simps }, try { simp only [hret0, hret1, hret2, hret3, hret4, hret5, hret6, hret7, hret8, hret9, hret10, hret11, hret12] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },\n },\n {\n -- if: negative branch\n have a0 : m ≠ 0, {\n try { simp only [ne.def] },\n try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point, hin_scalar, hin_m] },\n try { dsimp [cast_EcPoint, cast_BigInt3] },\n try { arith_simps }, try { simp only [hcond] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },\n },\n try { dsimp at a0 }, try { arith_simps at a0 },\n clear hcond,\n -- ap += 6\n step_advance_ap hpc24 hpc25,\n -- function call\n step_assert_eq hpc26 with arg0,\n step_assert_eq hpc27 with arg1,\n step_assert_eq hpc28 with arg2,\n step_assert_eq hpc29 with arg3,\n step_assert_eq hpc30 with arg4,\n step_assert_eq hpc31 with arg5,\n step_assert_eq hpc32 with arg6,\n step_sub hpc33 (auto_sound_ec_double mem _ range_check_ptr point _ _ _ _ _ _ _ _),\n { rw hpc34, norm_num2, exact h_mem_14 },\n { rw hpc34, norm_num2, exact h_mem_4 },\n { rw hpc34, norm_num2, exact h_mem_5 },\n { rw hpc34, norm_num2, exact h_mem_6 },\n { rw hpc34, norm_num2, exact h_mem_7 },\n { rw hpc34, norm_num2, exact h_mem_12 },\n { try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point, hin_scalar, hin_m] },\n try { dsimp [cast_EcPoint, cast_BigInt3] },\n try { arith_simps }, try { simp only [arg0, arg1, arg2, arg3, arg4, arg5, arg6] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } }, },\n { try { ext } ; {\n try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point, hin_scalar, hin_m] },\n try { dsimp [cast_EcPoint, cast_BigInt3] },\n try { arith_simps }, try { simp only [arg0, arg1, arg2, arg3, arg4, arg5, arg6] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },}, },\n intros κ_call35 ap35 h_call35,\n rcases h_call35 with ⟨rc_m35, rc_mle35, hl_range_check_ptr₁, h_call35⟩,\n generalize' hr_rev_range_check_ptr₁: mem (ap35 - 7) = range_check_ptr₁,\n have htv_range_check_ptr₁ := hr_rev_range_check_ptr₁.symm, clear hr_rev_range_check_ptr₁,\n generalize' hr_rev_double_point: cast_EcPoint mem (ap35 - 6) = double_point,\n simp only [hr_rev_double_point] at h_call35,\n have htv_double_point := hr_rev_double_point.symm, clear hr_rev_double_point,\n try { simp only [arg0 ,arg1 ,arg2 ,arg3 ,arg4 ,arg5 ,arg6] at hl_range_check_ptr₁ },\n rw [←htv_range_check_ptr₁, ←hin_range_check_ptr] at hl_range_check_ptr₁,\n try { simp only [arg0 ,arg1 ,arg2 ,arg3 ,arg4 ,arg5 ,arg6] at h_call35 },\n rw [hin_range_check_ptr] at h_call35,\n clear arg0 arg1 arg2 arg3 arg4 arg5 arg6,\n -- jnz\n apply of_register_state,\n intros regstate35 regstate35eq,\n have regstateapeq_a35 := congr_arg register_state.ap regstate35eq,\n try { dsimp at regstateapeq_a35 },\n step_jnz hpc35 hpc36 with a35 a35,\n {\n -- jnz: positive branch\n rw ←regstateapeq_a35 at a35,\n -- tail recursive function call\n step_assert_eq hpc37 with arg0,\n step_assert_eq hpc38 with arg1,\n step_assert_eq hpc39 with arg2,\n step_assert_eq hpc40 with arg3,\n step_assert_eq hpc41 with arg4,\n step_assert_eq hpc42 with arg5,\n step_assert_eq hpc43 with arg6,\n step_assert_eq hpc44 hpc45 with arg7,\n step_assert_eq hpc46 hpc47 with arg8,\n have h_δ37_c0 : ∀ x : F, x / (2 : ℤ) = x * (-1809251394333065606848661391547535052811553607665798349986546028067936010240 : ℤ),\n { intro x, apply div_eq_mul_inv', apply PRIME.int_cast_mul_eq_one, rw [PRIME], try { simp_int_casts }, norm_num1 },\n have h_δ37_c0_fz : ∀ x : F, x / 2 = x / (2 : ℤ), { intro x, norm_cast }, \n step_rec_sub hpc48 (νih _ range_check_ptr₁ double_point (scalar / (2 : ℤ)) (m - 1) _ _ _ _ _ _ _ _ _ _ _ _ _),\n { rw hpc49, norm_num, exact h_mem_rec },\n { rw hpc49, norm_num2, exact h_mem_4 },\n { rw hpc49, norm_num2, exact h_mem_5 },\n { rw hpc49, norm_num2, exact h_mem_6 },\n { rw hpc49, norm_num2, exact h_mem_7 },\n { rw hpc49, norm_num2, exact h_mem_12 },\n { rw hpc49, norm_num2, exact h_mem_13 },\n { rw hpc49, norm_num2, exact h_mem_14 },\n { rw hpc49, norm_num2, exact h_mem_15 },\n { try { simp only [h_δ37_c0_fz, h_δ37_c0] }, try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point, hin_scalar, hin_m, htv_range_check_ptr₁, htv_double_point] },\n try { dsimp [cast_EcPoint, cast_BigInt3] },\n try { arith_simps }, try { simp only [arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } }, },\n { try { simp only [h_δ37_c0_fz, h_δ37_c0] }, try { ext } ; {\n try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point, hin_scalar, hin_m, htv_range_check_ptr₁, htv_double_point] },\n try { dsimp [cast_EcPoint, cast_BigInt3] },\n try { arith_simps }, try { simp only [arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },}, },\n { try { simp only [h_δ37_c0_fz, h_δ37_c0] }, try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point, hin_scalar, hin_m, htv_range_check_ptr₁, htv_double_point] },\n try { dsimp [cast_EcPoint, cast_BigInt3] },\n try { arith_simps }, try { simp only [arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } }, },\n { try { simp only [h_δ37_c0_fz, h_δ37_c0] }, try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point, hin_scalar, hin_m, htv_range_check_ptr₁, htv_double_point] },\n try { dsimp [cast_EcPoint, cast_BigInt3] },\n try { arith_simps }, try { simp only [arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } }, },\n intros κ_call50 ap50 h_call50,\n rcases h_call50 with ⟨rc_m50, rc_mle50, hl_range_check_ptr₂, h_call50⟩,\n step_ret hpc50,\n generalize' hr_rev_range_check_ptr₂: mem (ap50 - 13) = range_check_ptr₂,\n have htv_range_check_ptr₂ := hr_rev_range_check_ptr₂.symm, clear hr_rev_range_check_ptr₂,\n try { simp only [arg0 ,arg1 ,arg2 ,arg3 ,arg4 ,arg5 ,arg6 ,arg7 ,arg8] at hl_range_check_ptr₂ },\n rw [←htv_range_check_ptr₂, ←htv_range_check_ptr₁] at hl_range_check_ptr₂,\n try { simp only [arg0 ,arg1 ,arg2 ,arg3 ,arg4 ,arg5 ,arg6 ,arg7 ,arg8] at h_call50 },\n rw [←htv_range_check_ptr₁, hl_range_check_ptr₁, hin_range_check_ptr] at h_call50,\n clear arg0 arg1 arg2 arg3 arg4 arg5 arg6 arg7 arg8,\n -- finish\n step_done, use_only [rfl, rfl],\n -- range check condition\n use_only (rc_m35+rc_m50+0+0), split,\n linarith [rc_mle35, rc_mle50],\n split,\n { arith_simps,\n rw [←htv_range_check_ptr₂, hl_range_check_ptr₂, hl_range_check_ptr₁, hin_range_check_ptr],\n try { arith_simps, refl <|> norm_cast }, try { refl } },\n intro rc_h_range_check_ptr, repeat { rw [add_assoc] at rc_h_range_check_ptr },\n have rc_h_range_check_ptr' := range_checked_add_right rc_h_range_check_ptr,\n -- Final Proof\n -- user-provided reduction\n suffices auto_spec: auto_spec_ec_mul_inner mem _ range_check_ptr point scalar m _ _ _,\n { apply sound_ec_mul_inner, apply auto_spec },\n -- prove the auto generated assertion\n dsimp [auto_spec_ec_mul_inner],\n try { norm_num1 }, try { arith_simps },\n right,\n use_only [a0],\n use_only [κ_call35],\n use_only [range_check_ptr₁],\n use_only [double_point],\n have rc_h_range_check_ptr₁ := range_checked_offset' rc_h_range_check_ptr,\n have rc_h_range_check_ptr₁' := range_checked_add_right rc_h_range_check_ptr₁, try { norm_cast at rc_h_range_check_ptr₁' },\n have spec35 := h_call35 rc_h_range_check_ptr',\n rw [←hin_range_check_ptr, ←htv_range_check_ptr₁] at spec35,\n try { dsimp at spec35, arith_simps at spec35 },\n use_only [spec35],\n use_only (mem regstate35.ap),\n left,\n use_only [a35],\n use_only [κ_call50],\n have rc_h_range_check_ptr₂ := range_checked_offset' rc_h_range_check_ptr₁,\n have rc_h_range_check_ptr₂' := range_checked_add_right rc_h_range_check_ptr₂, try { norm_cast at rc_h_range_check_ptr₂' },\n have spec50 := h_call50 rc_h_range_check_ptr₁',\n rw [←hin_range_check_ptr, ←hl_range_check_ptr₁] at spec50,\n try { dsimp at spec50, arith_simps at spec50 },\n use_only [spec50],\n try { linarith },\n },\n {\n -- jnz: negative branch\n rw ←regstateapeq_a35 at a35,\n -- recursive function call\n step_assert_eq hpc51 hpc52 with arg0,\n step_assert_eq hpc53 with arg1,\n step_assert_eq hpc54 with arg2,\n step_assert_eq hpc55 with arg3,\n step_assert_eq hpc56 with arg4,\n step_assert_eq hpc57 with arg5,\n step_assert_eq hpc58 with arg6,\n step_assert_eq hpc59 with arg7,\n step_assert_eq hpc60 hpc61 with arg8,\n step_assert_eq hpc62 hpc63 with arg9,\n have h_δ51_c0 : ∀ x : F, x / (2 : ℤ) = x * (-1809251394333065606848661391547535052811553607665798349986546028067936010240 : ℤ),\n { intro x, apply div_eq_mul_inv', apply PRIME.int_cast_mul_eq_one, rw [PRIME], try { simp_int_casts }, norm_num1 },\n have h_δ51_c0_fz : ∀ x : F, x / 2 = x / (2 : ℤ), { intro x, norm_cast }, \n step_rec_sub hpc64 (νih _ range_check_ptr₁ double_point ((scalar - 1) / (2 : ℤ)) (m - 1) _ _ _ _ _ _ _ _ _ _ _ _ _),\n { rw hpc65, norm_num, exact h_mem_rec },\n { rw hpc65, norm_num2, exact h_mem_4 },\n { rw hpc65, norm_num2, exact h_mem_5 },\n { rw hpc65, norm_num2, exact h_mem_6 },\n { rw hpc65, norm_num2, exact h_mem_7 },\n { rw hpc65, norm_num2, exact h_mem_12 },\n { rw hpc65, norm_num2, exact h_mem_13 },\n { rw hpc65, norm_num2, exact h_mem_14 },\n { rw hpc65, norm_num2, exact h_mem_15 },\n { try { simp only [h_δ51_c0_fz, h_δ51_c0] }, try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point, hin_scalar, hin_m, htv_range_check_ptr₁, htv_double_point] },\n try { dsimp [cast_EcPoint, cast_BigInt3] },\n try { arith_simps }, try { simp only [arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } }, },\n { try { simp only [h_δ51_c0_fz, h_δ51_c0] }, try { ext } ; {\n try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point, hin_scalar, hin_m, htv_range_check_ptr₁, htv_double_point] },\n try { dsimp [cast_EcPoint, cast_BigInt3] },\n try { arith_simps }, try { simp only [arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },}, },\n { try { simp only [h_δ51_c0_fz, h_δ51_c0] }, try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point, hin_scalar, hin_m, htv_range_check_ptr₁, htv_double_point] },\n try { dsimp [cast_EcPoint, cast_BigInt3] },\n try { arith_simps }, try { simp only [arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } }, },\n { try { simp only [h_δ51_c0_fz, h_δ51_c0] }, try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point, hin_scalar, hin_m, htv_range_check_ptr₁, htv_double_point] },\n try { dsimp [cast_EcPoint, cast_BigInt3] },\n try { arith_simps }, try { simp only [arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } }, },\n intros κ_call66 ap66 h_call66,\n rcases h_call66 with ⟨rc_m66, rc_mle66, hl_range_check_ptr₂, h_call66⟩,\n generalize' hr_rev_range_check_ptr₂: mem (ap66 - 13) = range_check_ptr₂,\n have htv_range_check_ptr₂ := hr_rev_range_check_ptr₂.symm, clear hr_rev_range_check_ptr₂,\n generalize' hr_rev_inner_pow2: cast_EcPoint mem (ap66 - 12) = inner_pow2,\n simp only [hr_rev_inner_pow2] at h_call66,\n have htv_inner_pow2 := hr_rev_inner_pow2.symm, clear hr_rev_inner_pow2,\n generalize' hr_rev_inner_res: cast_EcPoint mem (ap66 - 6) = inner_res,\n simp only [hr_rev_inner_res] at h_call66,\n have htv_inner_res := hr_rev_inner_res.symm, clear hr_rev_inner_res,\n try { simp only [arg0 ,arg1 ,arg2 ,arg3 ,arg4 ,arg5 ,arg6 ,arg7 ,arg8 ,arg9] at hl_range_check_ptr₂ },\n rw [←htv_range_check_ptr₂, ←htv_range_check_ptr₁] at hl_range_check_ptr₂,\n try { simp only [arg0 ,arg1 ,arg2 ,arg3 ,arg4 ,arg5 ,arg6 ,arg7 ,arg8 ,arg9] at h_call66 },\n rw [←htv_range_check_ptr₁, hl_range_check_ptr₁, hin_range_check_ptr] at h_call66,\n clear arg0 arg1 arg2 arg3 arg4 arg5 arg6 arg7 arg8 arg9,\n -- local var\n step_assert_eq hpc66 with temp0,\n step_assert_eq hpc67 with temp1,\n step_assert_eq hpc68 with temp2,\n step_assert_eq hpc69 with temp3,\n step_assert_eq hpc70 with temp4,\n step_assert_eq hpc71 with temp5,\n have lc_inner_pow2: inner_pow2 = cast_EcPoint mem σ.fp, {\n try { ext } ; {\n try { simp only [htv_inner_pow2] },\n try { dsimp [cast_EcPoint, cast_BigInt3] },\n try { arith_simps }, try { simp only [temp0, temp1, temp2, temp3, temp4, temp5] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },}, },\n clear temp0 temp1 temp2 temp3 temp4 temp5,\n -- function call\n step_assert_eq hpc72 with arg0,\n step_assert_eq hpc73 with arg1,\n step_assert_eq hpc74 with arg2,\n step_assert_eq hpc75 with arg3,\n step_assert_eq hpc76 with arg4,\n step_assert_eq hpc77 with arg5,\n step_assert_eq hpc78 with arg6,\n step_assert_eq hpc79 with arg7,\n step_assert_eq hpc80 with arg8,\n step_assert_eq hpc81 with arg9,\n step_assert_eq hpc82 with arg10,\n step_assert_eq hpc83 with arg11,\n step_assert_eq hpc84 with arg12,\n step_sub hpc85 (auto_sound_fast_ec_add mem _ range_check_ptr₂ point inner_res _ _ _ _ _ _ _ _ _),\n { rw hpc86, norm_num2, exact h_mem_15 },\n { rw hpc86, norm_num2, exact h_mem_4 },\n { rw hpc86, norm_num2, exact h_mem_5 },\n { rw hpc86, norm_num2, exact h_mem_6 },\n { rw hpc86, norm_num2, exact h_mem_7 },\n { rw hpc86, norm_num2, exact h_mem_13 },\n { try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point, hin_scalar, hin_m, htv_range_check_ptr₁, htv_double_point, htv_range_check_ptr₂, htv_inner_pow2, htv_inner_res, lc_inner_pow2] },\n try { dsimp [cast_EcPoint, cast_BigInt3] },\n try { arith_simps }, try { simp only [arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } }, },\n { try { ext } ; {\n try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point, hin_scalar, hin_m, htv_range_check_ptr₁, htv_double_point, htv_range_check_ptr₂, htv_inner_pow2, htv_inner_res, lc_inner_pow2] },\n try { dsimp [cast_EcPoint, cast_BigInt3] },\n try { arith_simps }, try { simp only [arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },}, },\n { try { ext } ; {\n try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point, hin_scalar, hin_m, htv_range_check_ptr₁, htv_double_point, htv_range_check_ptr₂, htv_inner_pow2, htv_inner_res, lc_inner_pow2] },\n try { dsimp [cast_EcPoint, cast_BigInt3] },\n try { arith_simps }, try { simp only [arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },}, },\n intros κ_call87 ap87 h_call87,\n rcases h_call87 with ⟨rc_m87, rc_mle87, hl_range_check_ptr₃, h_call87⟩,\n generalize' hr_rev_range_check_ptr₃: mem (ap87 - 7) = range_check_ptr₃,\n have htv_range_check_ptr₃ := hr_rev_range_check_ptr₃.symm, clear hr_rev_range_check_ptr₃,\n generalize' hr_rev_res: cast_EcPoint mem (ap87 - 6) = res,\n simp only [hr_rev_res] at h_call87,\n have htv_res := hr_rev_res.symm, clear hr_rev_res,\n try { simp only [arg0 ,arg1 ,arg2 ,arg3 ,arg4 ,arg5 ,arg6 ,arg7 ,arg8 ,arg9 ,arg10 ,arg11 ,arg12] at hl_range_check_ptr₃ },\n rw [←htv_range_check_ptr₃, ←htv_range_check_ptr₂] at hl_range_check_ptr₃,\n try { simp only [arg0 ,arg1 ,arg2 ,arg3 ,arg4 ,arg5 ,arg6 ,arg7 ,arg8 ,arg9 ,arg10 ,arg11 ,arg12] at h_call87 },\n rw [←htv_range_check_ptr₂, hl_range_check_ptr₂, hl_range_check_ptr₁, hin_range_check_ptr] at h_call87,\n clear arg0 arg1 arg2 arg3 arg4 arg5 arg6 arg7 arg8 arg9 arg10 arg11 arg12,\n -- return\n step_assert_eq hpc87 with hret0,\n step_assert_eq hpc88 with hret1,\n step_assert_eq hpc89 with hret2,\n step_assert_eq hpc90 with hret3,\n step_assert_eq hpc91 with hret4,\n step_assert_eq hpc92 with hret5,\n step_assert_eq hpc93 with hret6,\n step_assert_eq hpc94 with hret7,\n step_assert_eq hpc95 with hret8,\n step_assert_eq hpc96 with hret9,\n step_assert_eq hpc97 with hret10,\n step_assert_eq hpc98 with hret11,\n step_assert_eq hpc99 with hret12,\n step_ret hpc100,\n -- finish\n step_done, use_only [rfl, rfl],\n -- range check condition\n use_only (rc_m35+rc_m66+rc_m87+0+0), split,\n linarith [rc_mle35, rc_mle66, rc_mle87],\n split,\n { arith_simps, try { simp only [hret0 ,hret1 ,hret2 ,hret3 ,hret4 ,hret5 ,hret6 ,hret7 ,hret8 ,hret9 ,hret10 ,hret11 ,hret12] },\n rw [←htv_range_check_ptr₃, hl_range_check_ptr₃, hl_range_check_ptr₂, hl_range_check_ptr₁, hin_range_check_ptr],\n try { arith_simps, refl <|> norm_cast }, try { refl } },\n intro rc_h_range_check_ptr, repeat { rw [add_assoc] at rc_h_range_check_ptr },\n have rc_h_range_check_ptr' := range_checked_add_right rc_h_range_check_ptr,\n -- Final Proof\n -- user-provided reduction\n suffices auto_spec: auto_spec_ec_mul_inner mem _ range_check_ptr point scalar m _ _ _,\n { apply sound_ec_mul_inner, apply auto_spec },\n -- prove the auto generated assertion\n dsimp [auto_spec_ec_mul_inner],\n try { norm_num1 }, try { arith_simps },\n right,\n use_only [a0],\n use_only [κ_call35],\n use_only [range_check_ptr₁],\n use_only [double_point],\n have rc_h_range_check_ptr₁ := range_checked_offset' rc_h_range_check_ptr,\n have rc_h_range_check_ptr₁' := range_checked_add_right rc_h_range_check_ptr₁, try { norm_cast at rc_h_range_check_ptr₁' },\n have spec35 := h_call35 rc_h_range_check_ptr',\n rw [←hin_range_check_ptr, ←htv_range_check_ptr₁] at spec35,\n try { dsimp at spec35, arith_simps at spec35 },\n use_only [spec35],\n use_only (mem regstate35.ap),\n right,\n use_only [a35],\n use_only [κ_call66],\n use_only [range_check_ptr₂],\n use_only [inner_pow2],\n use_only [inner_res],\n have rc_h_range_check_ptr₂ := range_checked_offset' rc_h_range_check_ptr₁,\n have rc_h_range_check_ptr₂' := range_checked_add_right rc_h_range_check_ptr₂, try { norm_cast at rc_h_range_check_ptr₂' },\n have spec66 := h_call66 rc_h_range_check_ptr₁',\n rw [←hin_range_check_ptr, ←hl_range_check_ptr₁, ←htv_range_check_ptr₂] at spec66,\n try { dsimp at spec66, arith_simps at spec66 },\n use_only [spec66],\n use_only [κ_call87],\n use_only [range_check_ptr₃],\n use_only [res],\n have rc_h_range_check_ptr₃ := range_checked_offset' rc_h_range_check_ptr₂,\n have rc_h_range_check_ptr₃' := range_checked_add_right rc_h_range_check_ptr₃, try { norm_cast at rc_h_range_check_ptr₃' },\n have spec87 := h_call87 rc_h_range_check_ptr₂',\n rw [←hin_range_check_ptr, ←hl_range_check_ptr₁, ←hl_range_check_ptr₂, ←htv_range_check_ptr₃] at spec87,\n try { dsimp at spec87, arith_simps at spec87 },\n use_only [spec87],\n try { split, linarith },\n try { ensures_simps; try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point, hin_scalar, hin_m, htv_range_check_ptr₁, htv_double_point, htv_range_check_ptr₂, htv_inner_pow2, htv_inner_res, lc_inner_pow2, htv_range_check_ptr₃, htv_res] }, },\n try { dsimp [cast_EcPoint, cast_BigInt3] },\n try { arith_simps }, try { simp only [hret0, hret1, hret2, hret3, hret4, hret5, hret6, hret7, hret8, hret9, hret10, hret11, hret12] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },\n }\n }\nend\n\n", "meta": {"author": "starkware-libs", "repo": "formal-proofs", "sha": "35613c65b6715601bbc0a550d52754f8e7d93e30", "save_path": "github-repos/lean/starkware-libs-formal-proofs", "path": "github-repos/lean/starkware-libs-formal-proofs/formal-proofs-35613c65b6715601bbc0a550d52754f8e7d93e30/src/starkware/cairo/common/cairo_secp/verification/verification/signature_recover_public_key_ec_mul_inner_soundness.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4571367168274948, "lm_q2_score": 0.022977372042605266, "lm_q1q2_score": 0.010503800416880439}} {"text": "/-\n## Undefined Behavior\n\nThis file models undefined behavior, the runtime condition of reaching a state\nfor which semantics are undefined. This captures errors that are dependent on\nruntime data, eg. division by zero.\n\n\nUndefined behavior is interpreted in the exception monad, with generic string-\nbased error messages. An execution that runs into UB is stopped; determinism\nis preserved.\n\nTODO: Consider an UB interpreter directly into results from a proof of non-UB\n-/\n\nimport MLIR.Semantics.Fitree\n\n-- The monad for UB records exceptions based on strings\nabbrev UBT := ExceptT String\n\ninductive UBE: Type → Type :=\n | UB {α: Type} [Inhabited α]: Option String → UBE α\n | Unhandled {α: Type} [Inhabited α]: UBE α\n\n@[simp_itree]\ndef UBE.handle {E}: UBE ~> UBT (Fitree E) := fun _ e =>\n match e with\n | Unhandled => throw \"\"\n | UB none => throw \"\"\n | UB (some msg) => throw s!\"\"\n\n@[simp_itree]\ndef UBE.handle! {E}: UBE ~> Fitree E := fun _ e =>\n match e with\n | Unhandled => panic! \"\"\n | UB none => panic! \"\"\n | UB (some msg) => panic! s!\"\"\n\ndef raiseUB (msg: String) {E α} [Member UBE E] [Inhabited α]: Fitree E α :=\n Fitree.trigger <| UBE.UB (some msg)\n\ndef interpUB (t: Fitree UBE R): UBT (Fitree Void1) R :=\n t.interpExcept UBE.handle\n\ndef interpUB! (t: Fitree UBE R): Fitree Void1 R :=\n t.interp UBE.handle!\n\ndef interpUB' {E} (t: Fitree (UBE +' E) R): UBT (Fitree E) R :=\n t.interpExcept (Fitree.case UBE.handle Fitree.liftHandler)\n\ndef interpUB'! {E} (t: Fitree (UBE +' E) R): Fitree E R :=\n t.interp (Fitree.case UBE.handle! (fun T => @Fitree.trigger E E T _))\n\n/-\n### Reduction theorems\n-/\n\n@[simp] theorem interpUB_ret:\n interpUB (Fitree.ret r) = Fitree.ret (Except.ok r) := rfl\n\n@[simp] theorem interpUB_Ret:\n interpUB (Fitree.Ret r) = Fitree.ret (Except.ok r) := rfl\n\ntheorem interpUB_bind (k: T → Fitree UBE R):\n interpUB (Fitree.bind t k) =\n Fitree.bind (interpUB t) (fun x =>\n match x with\n | .error ε => Fitree.ret (.error ε)\n | .ok x => interpUB (k x)) := by\n -- Can't reuse `Fitree.interpExcept_bind` because the match statements are\n -- considered different by isDefEq for some reason\n induction t with\n | Ret _ => rfl\n | Vis _ _ ih =>\n simp [interpUB, Fitree.interpExcept] at *\n simp [Fitree.interp, Fitree.bind, Bind.bind]\n simp [ExceptT.bind, ExceptT.mk, ExceptT.bindCont]\n have fequal2 α β (f g: α → β) x y: f = g → x = y → f x = g y :=\n fun h₁ h₂ => by simp [h₁, h₂]\n apply fequal2; rfl; funext x\n cases x <;> simp [ih]\n\n@[simp] theorem interpUB'_Vis_right:\n interpUB' (Fitree.Vis (Sum.inr e) k) =\n Fitree.Vis e (fun x => interpUB' (k x)) := rfl\n\n@[simp] theorem interpUB'_ret:\n @interpUB' _ E (Fitree.ret r) = Fitree.ret (Except.ok r) := rfl\n\ntheorem interpUB'_bind (k: T → Fitree (UBE +' E) R):\n interpUB' (Fitree.bind t k) =\n Fitree.bind (interpUB' t) (fun x =>\n match x with\n | .error ε => Fitree.ret (.error ε)\n | .ok x => interpUB' (k x)) := by\n -- Can't reuse `Fitree.interpExcept_bind` because the match statements are\n -- considered different by isDefEq for some reason\n induction t with\n | Ret _ => rfl\n | Vis _ _ ih =>\n simp [interpUB', Fitree.interpExcept] at *\n simp [Fitree.interp, Fitree.bind, Bind.bind]\n simp [ExceptT.bind, ExceptT.mk, ExceptT.bindCont]\n have fequal2 α β (f g: α → β) x y: f = g → x = y → f x = g y :=\n fun h₁ h₂ => by simp [h₁, h₂]\n apply fequal2; rfl; funext x\n cases x <;> simp [ih]\n", "meta": {"author": "opencompl", "repo": "lean-mlir", "sha": "85fd61e38dec57e4d67d7af4d49a1ccc67828c1b", "save_path": "github-repos/lean/opencompl-lean-mlir", "path": "github-repos/lean/opencompl-lean-mlir/lean-mlir-85fd61e38dec57e4d67d7af4d49a1ccc67828c1b/MLIR/Semantics/UB.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.29098086621490676, "lm_q2_score": 0.035678553056634484, "lm_q1q2_score": 0.010381776273714012}} {"text": "/-\nCopyright (c) 2020 Anne Baanen. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Anne Baanen\n-/\nimport tactic.core\n\n/-!\n# The `simp_rw` tactic\n\nThis module defines a tactic `simp_rw` which functions as a mix of `simp` and\n`rw`. Like `rw`, it applies each rewrite rule in the given order, but like\n`simp` it repeatedly applies these rules and also under binders like `∀ x, ...`,\n`∃ x, ...` and `λ x, ...`.\n\n## Implementation notes\n\nThe tactic works by taking each rewrite rule in turn and applying `simp only` to\nit. Arguments to `simp_rw` are of the format used by `rw` and are translated to\ntheir equivalents for `simp`.\n-/\n\nnamespace tactic.interactive\nopen interactive interactive.types tactic\n\n/--\n`simp_rw` functions as a mix of `simp` and `rw`. Like `rw`, it applies each\nrewrite rule in the given order, but like `simp` it repeatedly applies these\nrules and also under binders like `∀ x, ...`, `∃ x, ...` and `λ x, ...`.\n\nUsage:\n - `simp_rw [lemma_1, ..., lemma_n]` will rewrite the goal by applying the\n lemmas in that order. A lemma preceded by `←` is applied in the reverse direction.\n - `simp_rw [lemma_1, ..., lemma_n] at h₁ ... hₙ` will rewrite the given hypotheses.\n - `simp_rw [...] at ⊢ h₁ ... hₙ` rewrites the goal as well as the given hypotheses.\n - `simp_rw [...] at *` rewrites in the whole context: all hypotheses and the goal.\n\nLemmas passed to `simp_rw` must be expressions that are valid arguments to `simp`.\n\nFor example, neither `simp` nor `rw` can solve the following, but `simp_rw` can:\n```lean\nexample {α β : Type} {f : α → β} {t : set β} :\n (∀ s, f '' s ⊆ t) = ∀ s : set α, ∀ x ∈ s, x ∈ f ⁻¹' t :=\nby simp_rw [set.image_subset_iff, set.subset_def]\n```\n-/\nmeta def simp_rw (q : parse rw_rules) (l : parse location) : tactic unit :=\nq.rules.mmap' (λ rule, do\n let simp_arg := if rule.symm\n then simp_arg_type.symm_expr rule.rule\n else simp_arg_type.expr rule.rule,\n save_info rule.pos,\n simp none none tt [simp_arg] [] l) -- equivalent to `simp only [rule] at l`\n\nadd_tactic_doc\n{ name := \"simp_rw\",\n category := doc_category.tactic,\n decl_names := [`tactic.interactive.simp_rw],\n tags := [\"simplification\"] }\n\nend tactic.interactive\n", "meta": {"author": "leanprover-community", "repo": "mathlib", "sha": "5e526d18cea33550268dcbbddcb822d5cde40654", "save_path": "github-repos/lean/leanprover-community-mathlib", "path": "github-repos/lean/leanprover-community-mathlib/mathlib-5e526d18cea33550268dcbbddcb822d5cde40654/src/tactic/simp_rw.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1347759139476672, "lm_q2_score": 0.07696084310585327, "lm_q1q2_score": 0.010372467967774397}} {"text": "/-\nCopyright (c) 2016 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Leonardo de Moura\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.function\nimport Mathlib.Lean3Lib.init.data.option.basic\nimport Mathlib.Lean3Lib.init.util\nimport Mathlib.Lean3Lib.init.control.combinators\nimport Mathlib.Lean3Lib.init.control.monad\nimport Mathlib.Lean3Lib.init.control.alternative\nimport Mathlib.Lean3Lib.init.control.monad_fail\nimport Mathlib.Lean3Lib.init.data.nat.div\nimport Mathlib.Lean3Lib.init.meta.exceptional\nimport Mathlib.Lean3Lib.init.meta.format\nimport Mathlib.Lean3Lib.init.meta.environment\nimport Mathlib.Lean3Lib.init.meta.pexpr\nimport Mathlib.Lean3Lib.init.data.repr\nimport Mathlib.Lean3Lib.init.data.string.basic\nimport Mathlib.Lean3Lib.init.meta.interaction_monad\nimport Mathlib.Lean3Lib.init.classical\n \n\nuniverses l \n\nnamespace Mathlib\n\ninfixl:2 \" >>=[tactic] \" => Mathlib.interaction_monad_bind\n\ninfixl:2 \" >>[tactic] \" => Mathlib.interaction_monad_seq\n\nnamespace tactic_state\n\n\n/-- Format the given tactic state. If `target_lhs_only` is true and the target\n is of the form `lhs ~ rhs`, where `~` is a simplification relation,\n then only the `lhs` is displayed.\n\n Remark: the parameter `target_lhs_only` is a temporary hack used to implement\n the `conv` monad. It will be removed in the future. -/\n/-- Format expression with respect to the main goal in the tactic state.\n If the tactic state does not contain any goals, then format expression\n using an empty local context. -/\nend tactic_state\n\n\n/-- `tactic` is the monad for building tactics.\n You use this to:\n - View and modify the local goals and hypotheses in the prover's state.\n - Invoke type checking and elaboration of terms.\n - View and modify the environment.\n - Build new tactics out of existing ones such as `simp` and `rewrite`.\n-/\nnamespace tactic\n\n\nend tactic\n\n\nnamespace tactic_result\n\n\nend tactic_result\n\n\nnamespace interactive\n\n\n/-- Typeclass for custom interaction monads, which provides\n the information required to convert an interactive-mode\n construction to a `tactic` which can actually be executed.\n\n Given a `[monad m]`, `execute_with` explains how to turn a `begin ... end`\n block, or a `by ...` statement into a `tactic α` which can actually be\n executed. The `inhabited` first argument facilitates the passing of an\n optional configuration parameter `config`, using the syntax:\n ```\n begin [custom_monad] with config,\n ...\n end\n ```\n-/\n/-- Default `executor` instance for `tactic`s themselves -/\nend interactive\n\n\nnamespace tactic\n\n\n/-- Does nothing. -/\n/--\n`try_core t` acts like `t`, but succeeds even if `t` fails. It returns the\nresult of `t` if `t` succeeded and `none` otherwise.\n-/\n/--\n`try t` acts like `t`, but succeeds even if `t` fails.\n-/\n/--\n`fail_if_success t` acts like `t`, but succeeds if `t` fails and fails if `t`\nsucceeds. Changes made by `t` to the `tactic_state` are preserved only if `t`\nsucceeds.\n-/\n/--\n`success_if_fail t` acts like `t`, but succeeds if `t` fails and fails if `t`\nsucceeds. Changes made by `t` to the `tactic_state` are preserved only if `t`\nsucceeds.\n-/\n/--\n`iterate_at_most n t` iterates `t` `n` times or until `t` fails, returning the\nresult of each successful iteration.\n-/\n/--\n`iterate_at_most' n t` repeats `t` `n` times or until `t` fails.\n-/\n/--\n`iterate_exactly n t` iterates `t` `n` times, returning the result of\neach iteration. If any iteration fails, the whole tactic fails.\n-/\n/--\n`iterate_exactly' n t` executes `t` `n` times. If any iteration fails, the whole\ntactic fails.\n-/\n/--\n`iterate t` repeats `t` 100.000 times or until `t` fails, returning the\nresult of each iteration.\n-/\n/--\n`iterate' t` repeats `t` 100.000 times or until `t` fails.\n-/\n/-- Decorate t's exceptions with msg. -/\n/-- Set the tactic_state. -/\n/-- Get the tactic_state. -/\n/--\n`capture t` acts like `t`, but succeeds with a result containing either the returned value\nor the exception.\nChanges made by `t` to the `tactic_state` are preserved in both cases.\n\nThe result can be used to inspect the error message, or passed to `unwrap` to rethrow the\nfailure later.\n-/\n/--\n`unwrap r` unwraps a result previously obtained using `capture`.\n\nIf the previous result was a success, this produces its wrapped value.\nIf the previous result was an exception, this \"rethrows\" the exception as if it came\nfrom where it originated.\n\n`do r ← capture t, unwrap r` is identical to `t`, but allows for intermediate tactics to be inserted.\n-/\n/--\n`resume r` continues execution from a result previously obtained using `capture`.\n\nThis is like `unwrap`, but the `tactic_state` is rolled back to point of capture even upon success.\n-/\nend tactic\n\n\nnamespace tactic\n\n\n/-- A parameter representing how aggressively definitions should be unfolded when trying to decide if two terms match, unify or are definitionally equal.\nBy default, theorem declarations are never unfolded.\n- `all` will unfold everything, including macros and theorems. Except projection macros.\n- `semireducible` will unfold everything except theorems and definitions tagged as irreducible.\n- `instances` will unfold all class instance definitions and definitions tagged with reducible.\n- `reducible` will only unfold definitions tagged with the `reducible` attribute.\n- `none` will never unfold anything.\n[NOTE] You are not allowed to tag a definition with more than one of `reducible`, `irreducible`, `semireducible` attributes.\n[NOTE] there is a config flag `m_unfold_lemmas`that will make it unfold theorems.\n -/\ninductive transparency \nwhere\n| all : transparency\n| semireducible : transparency\n| instances : transparency\n| reducible : transparency\n| none : transparency\n\n/-- (eval_expr α e) evaluates 'e' IF 'e' has type 'α'. -/\n/-- Return the partial term/proof constructed so far. Note that the resultant expression\n may contain variables that are not declarate in the current main goal. -/\n/-- Display the partial term/proof constructed so far. This tactic is *not* equivalent to\n `do { r ← result, s ← read, return (format_expr s r) }` because this one will format the result with respect\n to the current goal, and trace_result will do it with respect to the initial goal. -/\n/-- Return target type of the main goal. Fail if tactic_state does not have any goal left. -/\n/-- Clear the given local constant. The tactic fails if the given expression is not a local constant. -/\n/-- `revert_lst : list expr → tactic nat` is the reverse of `intron`. It takes a local constant `c` and puts it back as bound by a `pi` or `elet` of the main target.\nIf there are other local constants that depend on `c`, these are also reverted. Because of this, the `nat` that is returned is the actual number of reverted local constants.\nExample: with `x : ℕ, h : P(x) ⊢ T(x)`, `revert_lst [x]` returns `2` and produces the state ` ⊢ Π x, P(x) → T(x)`.\n -/\n/-- Return `e` in weak head normal form with respect to the given transparency setting.\n If `unfold_ginductive` is `tt`, then nested and/or mutually recursive inductive datatype constructors\n and types are unfolded. Recall that nested and mutually recursive inductive datatype declarations\n are compiled into primitive datatypes accepted by the Kernel. -/\n/-- (head) eta expand the given expression. `f : α → β` head-eta-expands to `λ a, f a`. If `f` isn't a function then it just returns `f`. -/\n/-- (head) beta reduction. `(λ x, B) c` reduces to `B[x/c]`. -/\n/-- (head) zeta reduction. Reduction of let bindings at the head of the expression. `let x : a := b in c` reduces to `c[x/b]`. -/\n/-- Zeta reduction. Reduction of let bindings. `let x : a := b in c` reduces to `c[x/b]`. -/\n/-- (head) eta reduction. `(λ x, f x)` reduces to `f`. -/\n/-- Succeeds if `t` and `s` can be unified using the given transparency setting. -/\n/-- Similar to `unify`, but it treats metavariables as constants. -/\n/-- Infer the type of the given expression.\n Remark: transparency does not affect type inference -/\n/-- Get the `local_const` expr for the given `name`. -/\n/-- Resolve a name using the current local context, environment, aliases, etc. -/\n/-- Return the hypothesis in the main goal. Fail if tactic_state does not have any goal left. -/\n/-- Get a fresh name that is guaranteed to not be in use in the local context.\n If `n` is provided and `n` is not in use, then `n` is returned.\n Otherwise a number `i` is appended to give `\"n_i\"`.\n-/\n/-- Helper tactic for creating simple applications where some arguments are inferred using\n type inference.\n\n Example, given\n ```\n rel.{l_1 l_2} : Pi (α : Type.{l_1}) (β : α -> Type.{l_2}), (Pi x : α, β x) -> (Pi x : α, β x) -> , Prop\n nat : Type\n real : Type\n vec.{l} : Pi (α : Type l) (n : nat), Type.{l1}\n f g : Pi (n : nat), vec real n\n ```\n then\n ```\n mk_app_core semireducible \"rel\" [f, g]\n ```\n returns the application\n ```\n rel.{1 2} nat (fun n : nat, vec real n) f g\n ```\n\n The unification constraints due to type inference are solved using the transparency `md`.\n-/\n/-- Similar to `mk_app`, but allows to specify which arguments are explicit/implicit.\n Example, given `(a b : nat)` then\n ```\n mk_mapp \"ite\" [some (a > b), none, none, some a, some b]\n ```\n returns the application\n ```\n @ite.{1} (a > b) (nat.decidable_gt a b) nat a b\n ```\n-/\n/-- (mk_congr_arg h₁ h₂) is a more efficient version of (mk_app `congr_arg [h₁, h₂]) -/\n/-- (mk_congr_fun h₁ h₂) is a more efficient version of (mk_app `congr_fun [h₁, h₂]) -/\n/-- (mk_congr h₁ h₂) is a more efficient version of (mk_app `congr [h₁, h₂]) -/\n/-- (mk_eq_refl h) is a more efficient version of (mk_app `eq.refl [h]) -/\n/-- (mk_eq_symm h) is a more efficient version of (mk_app `eq.symm [h]) -/\n/-- (mk_eq_trans h₁ h₂) is a more efficient version of (mk_app `eq.trans [h₁, h₂]) -/\n/-- (mk_eq_mp h₁ h₂) is a more efficient version of (mk_app `eq.mp [h₁, h₂]) -/\n/-- (mk_eq_mpr h₁ h₂) is a more efficient version of (mk_app `eq.mpr [h₁, h₂]) -/\n/- Given a local constant t, if t has type (lhs = rhs) apply substitution.\n Otherwise, try to find a local constant that has type of the form (t = t') or (t' = t).\n The tactic fails if the given expression is not a local constant. -/\n\n/-- Close the current goal using `e`. Fail if the type of `e` is not definitionally equal to\n the target type. -/\n/-- Elaborate the given quoted expression with respect to the current main goal.\n Note that this means that any implicit arguments for the given `pexpr` will be applied with fresh metavariables.\n If `allow_mvars` is tt, then metavariables are tolerated and become new goals if `subgoals` is tt. -/\n/-- Return true if the given expression is a type class. -/\n/-- Try to create an instance of the given type class. -/\n/-- Change the target of the main goal.\n The input expression must be definitionally equal to the current target.\n If `check` is `ff`, then the tactic does not check whether `e`\n is definitionally equal to the current target. If it is not,\n then the error will only be detected by the kernel type checker. -/\n/-- `assert_core H T`, adds a new goal for T, and change target to `T -> target`. -/\n/-- `assertv_core H T P`, change target to (T -> target) if P has type T. -/\n/-- `define_core H T`, adds a new goal for T, and change target to `let H : T := ?M in target` in the current goal. -/\n/-- `definev_core H T P`, change target to `let H : T := P in target` if P has type T. -/\n/-- Rotate goals to the left. That is, `rotate_left 1` takes the main goal and puts it to the back of the subgoal list. -/\n/-- Gets a list of metavariables, one for each goal. -/\n/-- Replace the current list of goals with the given one. Each expr in the list should be a metavariable. Any assigned metavariables will be ignored.-/\n/-- How to order the new goals made from an `apply` tactic.\nSupposing we were applying `e : ∀ (a:α) (p : P(a)), Q`\n- `non_dep_first` would produce goals `⊢ P(?m)`, `⊢ α`. It puts the P goal at the front because none of the arguments after `p` in `e` depend on `p`. It doesn't matter what the result `Q` depends on.\n- `non_dep_only` would produce goal `⊢ P(?m)`.\n- `all` would produce goals `⊢ α`, `⊢ P(?m)`.\n-/\ninductive new_goals \nwhere\n| non_dep_first : new_goals\n| non_dep_only : new_goals\n| all : new_goals\n\n/-- Configuration options for the `apply` tactic.\n- `md` sets how aggressively definitions are unfolded.\n- `new_goals` is the strategy for ordering new goals.\n- `instances` if `tt`, then `apply` tries to synthesize unresolved `[...]` arguments using type class resolution.\n- `auto_param` if `tt`, then `apply` tries to synthesize unresolved `(h : p . tac_id)` arguments using tactic `tac_id`.\n- `opt_param` if `tt`, then `apply` tries to synthesize unresolved `(a : t := v)` arguments by setting them to `v`.\n- `unify` if `tt`, then `apply` is free to assign existing metavariables in the goal when solving unification constraints.\n For example, in the goal `|- ?x < succ 0`, the tactic `apply succ_lt_succ` succeeds with the default configuration,\n but `apply_with succ_lt_succ {unify := ff}` doesn't since it would require Lean to assign `?x` to `succ ?y` where\n `?y` is a fresh metavariable.\n-/\nstructure apply_cfg \nwhere\n md : transparency\n approx : Bool\n new_goals : new_goals\n instances : Bool\n auto_param : Bool\n opt_param : Bool\n unify : Bool\n\n/-- Apply the expression `e` to the main goal, the unification is performed using the transparency mode in `cfg`.\n Supposing `e : Π (a₁:α₁) ... (aₙ:αₙ), P(a₁,...,aₙ)` and the target is `Q`, `apply` will attempt to unify `Q` with `P(?a₁,...?aₙ)`.\n All of the metavariables that are not assigned are added as new metavariables.\n If `cfg.approx` is `tt`, then fallback to first-order unification, and approximate context during unification.\n `cfg.new_goals` specifies which unassigned metavariables become new goals, and their order.\n If `cfg.instances` is `tt`, then use type class resolution to instantiate unassigned meta-variables.\n The fields `cfg.auto_param` and `cfg.opt_param` are ignored by this tactic (See `tactic.apply`).\n It returns a list of all introduced meta variables and the parameter name associated with them, even the assigned ones. -/\n/- Create a fresh meta universe variable. -/\n\n/- Create a fresh meta-variable with the given type.\n The scope of the new meta-variable is the local context of the main goal. -/\n\n/-- Return the value assigned to the given universe meta-variable.\n Fail if argument is not an universe meta-variable or if it is not assigned. -/\n/-- Return the value assigned to the given meta-variable.\n Fail if argument is not a meta-variable or if it is not assigned. -/\n/-- Return true if the given meta-variable is assigned.\n Fail if argument is not a meta-variable. -/\n/-- Make a name that is guaranteed to be unique. Eg `_fresh.1001.4667`. These will be different for each run of the tactic. -/\n/-- Induction on `h` using recursor `rec`, names for the new hypotheses\n are retrieved from `ns`. If `ns` does not have sufficient names, then use the internal binder names\n in the recursor.\n It returns for each new goal the name of the constructor (if `rec_name` is a builtin recursor),\n a list of new hypotheses, and a list of substitutions for hypotheses\n depending on `h`. The substitutions map internal names to their replacement terms. If the\n replacement is again a hypothesis the user name stays the same. The internal names are only valid\n in the original goal, not in the type context of the new goal.\n Remark: if `rec_name` is not a builtin recursor, we use parameter names of `rec_name` instead of\n constructor names.\n\n If `rec` is none, then the type of `h` is inferred, if it is of the form `C ...`, tactic uses `C.rec` -/\n/-- Apply `cases_on` recursor, names for the new hypotheses are retrieved from `ns`.\n `h` must be a local constant. It returns for each new goal the name of the constructor, a list of new hypotheses, and a list of\n substitutions for hypotheses depending on `h`. The number of new goals may be smaller than the\n number of constructors. Some goals may be discarded when the indices to not match.\n See `induction` for information on the list of substitutions.\n\n The `cases` tactic is implemented using this one, and it relaxes the restriction of `h`.\n\n Note: There is one \"new hypothesis\" for every constructor argument. These are\n usually local constants, but due to dependent pattern matching, they can also\n be arbitrary terms. -/\n/-- Similar to cases tactic, but does not revert/intro/clear hypotheses. -/\n/-- Generalizes the target with respect to `e`. -/\n/-- instantiate assigned metavariables in the given expression -/\n/-- Add the given declaration to the environment -/\n/--\nChanges the environment to the `new_env`.\nThe new environment does not need to be a descendant of the old one.\nUse with care.\n-/\n/-- Changes the environment to the `new_env`. `new_env` needs to be a descendant from the current environment. -/\n/-- `doc_string env d k` returns the doc string for `d` (if available) -/\n/-- Set the docstring for the given declaration. -/\n/--\nCreate an auxiliary definition with name `c` where `type` and `value` may contain local constants and\nmeta-variables. This function collects all dependencies (universe parameters, universe metavariables,\nlocal constants (aka hypotheses) and metavariables).\nIt updates the environment in the tactic_state, and returns an expression of the form\n\n (c.{l_1 ... l_n} a_1 ... a_m)\n\nwhere l_i's and a_j's are the collected dependencies.\n-/\n/-- Returns a list of all top-level (`/-! ... -/`) docstrings in the active module and imported ones.\nThe returned object is a list of modules, indexed by `(some filename)` for imported modules\nand `none` for the active one, where each module in the list is paired with a list\nof `(position_in_file, docstring)` pairs. -/\n/-- Returns a list of docstrings in the active module. An entry in the list can be either:\n- a top-level (`/-! ... -/`) docstring, represented as `(none, docstring)`\n- a declaration-specific (`/-- ... -/`) docstring, represented as `(some decl_name, docstring)` -/\n/-- Set attribute `attr_name` for constant `c_name` with the given priority.\n If the priority is none, then use default -/\n/-- `unset_attribute attr_name c_name` -/\n/-- `has_attribute attr_name c_name` succeeds if the declaration `decl_name`\n has the attribute `attr_name`. The result is the priority and whether or not\n the attribute is persistent. -/\n/-- `copy_attribute attr_name c_name p d_name` copy attribute `attr_name` from\n `src` to `tgt` if it is defined for `src`; make it persistent if `p` is `tt`;\n if `p` is `none`, the copied attribute is made persistent iff it is persistent on `src` -/\n/-- Name of the declaration currently being elaborated. -/\n/-- `save_type_info e ref` save (typeof e) at position associated with ref -/\n/-- Return list of currently open namespaces -/\n/-- Return tt iff `t` \"occurs\" in `e`. The occurrence checking is performed using\n keyed matching with the given transparency setting.\n\n We say `t` occurs in `e` by keyed matching iff there is a subterm `s`\n s.t. `t` and `s` have the same head, and `is_def_eq t s md`\n\n The main idea is to minimize the number of `is_def_eq` checks\n performed. -/\n/-- Abstracts all occurrences of the term `t` in `e` using keyed matching.\n If `unify` is `ff`, then matching is used instead of unification.\n That is, metavariables occurring in `e` are not assigned. -/\n/-- Blocks the execution of the current thread for at least `msecs` milliseconds.\n This tactic is used mainly for debugging purposes. -/\n/-- Type check `e` with respect to the current goal.\n Fails if `e` is not type correct. -/\n/-- A `tag` is a list of `names`. These are attached to goals to help tactics track them.-/\ndef tag :=\n List name\n\n", "meta": {"author": "AurelienSaue", "repo": "Mathlib4_auto", "sha": "590df64109b08190abe22358fabc3eae000943f2", "save_path": "github-repos/lean/AurelienSaue-Mathlib4_auto", "path": "github-repos/lean/AurelienSaue-Mathlib4_auto/Mathlib4_auto-590df64109b08190abe22358fabc3eae000943f2/Mathlib/Lean3Lib/init/meta/tactic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.26894142136999516, "lm_q2_score": 0.038466191053825, "lm_q1q2_score": 0.010345152096705487}} {"text": "\nimport data.equiv.nat\nimport computability.encoding\nimport computability.turing_machine\nimport data.polynomial.basic\nimport data.polynomial.eval\nimport data.finset.basic\n-- import measure_theory.measurable_space_def\nimport .distribution_ensemble\n\n/-!\n# UC Protocols\n\nThis file defines protocols as they are understood in the \n[Universal Composability Security framework](https://eprint.iacr.org/2000/067.pdf).\n\n-/\n\n-- noncomputable theory\n\ndef ste := list bool\n\nstructure message := \n(import_tokens : ℕ)\n(content : list (bool))\n\ndef pair (m1 m2 : message) : message := sorry -- computes a list encoding a pair of lists\ndef unpair_left (m : message) : message := sorry -- computes the left of a pair encoding\ndef unpair_right (m : message) : message := sorry -- computes the right of a pair encoding\n\ndef encode (n : ℕ) : message := sorry -- encodes a nat as a message\ndef decode (m : message) : ℕ := sorry -- decodes a nat from a message\n\ninductive incoming_information : Type\n| input : incoming_information\n| suroutine_output : incoming_information\n| backdoor : incoming_information\n\n/-- As defined in section 2.1 -/\nstructure machine :=\n (ident : ℕ)\n (initial_state : ensemble ste) -- An ensemble of initial states (representing randomness in the machine execution)\n (callers : finset (ℕ)) -- Ids of machines that input to this machine\n (subroutines : finset (ℕ)) -- Ids of machines that give subroutine output to this machine\n (backdoor : finset (ℕ)) -- Ids of machines that backdoor to this machine\n -- given a starting state and a message from ID, return a new state and an outgoing message, or optionally halt\n (program : ste → ℕ → message → option (ste × ℕ × message))\n -- TODO add condition for polytime halting\n (environment_output : option (ste → bool)) \n -- Optional function for environement machines to run on the environment's state when it halts to determine its output variable\n\ninstance : decidable_eq machine := sorry\n\n-- /-- As defined in section 2.1 -/\n-- structure protocol :=\n-- (ids : finset ℕ)\n-- (μ : ℕ → machine)\n-- -- ids correspond to ids\n-- (ids_match : ∀ i ∈ ids, (μ i).id = i)\n-- -- Callers match up with subroutines\n-- (callers_have_subroutines : ∀ i j ∈ ids, i ∈ (μ j).callers ↔ j ∈ (μ i).subroutines)\n\n/-- As defined in section 2.1 -/\nstructure protocol :=\n (machines : finset machine)\n -- Callers match up with subroutines\n (callers_have_subroutines : \n ∀ (i j : machine), i ∈ machines → i.ident ∈ j.callers ↔ j.ident ∈ i.subroutines)\n\n\ndef protocol.ids (π : protocol) : finset ℕ :=\n π.machines.image machine.ident\n\n/-- \nAs defined in section 2.1, the main machines of a protocol are those who have callers whose ids \nare not in the protocol, \n-/\ndef is_main_machine (π : protocol) (μ : machine) : Prop :=\n μ.ident ∈ π.ids ∧ ∃ m ∈ μ.callers, m ∉ π.ids\n\n-- TODO seems like a bug in the typeclass inference system tha tthis needs to be defined\ninstance (π : protocol) : decidable_pred (is_main_machine π) := begin\n rw decidable_pred,\n intro a,\n apply and.decidable,\nend\n\n/-- \nAs defined in section 2.1, the main machines of a protocol are those who have callers whose ids \nare not in the protocol, \n-/\ndef main_machines (π : protocol) : finset machine :=\n π.machines.filter (is_main_machine π)\n\n/-- ... and the ids of these machines not in the protocol are \"external\" -/\ndef external_ids (π : protocol) : finset ℕ := \n (finset.bUnion (π.machines) (λ μ, μ.callers)) \\ π.ids\n\n/-- As defined in 2.2.1 -/\ndef execution (π : protocol) (𝓐 : machine) (𝓔 : machine) :\n -- (initial_states : ℕ → ste) -- randomness initialization for the machines in the protocol (including input for environment)\n -- (environment_id_zero : 𝓔.id = 0) -- environment machine has id 0\n -- (adversary_id_one : 𝓐.id = 1) -- adversaty machine has id 1\n -- (h0 : 0 ∉ 𝓟.ids) (h1 : 1 ∉ 𝓟.ids) -- 𝓟 does not have 0 or 1 in its id list\n -- (h0' : 0 ∉ external_ids 𝓟) (h1' : 1 ∉ external_ids 𝓟) -- or in its external ids\n ensemble bool := \nsorry\n\n/-- \nSee definition on page 42. \nAn environment is balanced if, at any point in time during the execution, the overall import of\nthe inputs given to the adversary is at least the sum of the imports of all the other inputs given \nto all the other ITIs in the system so far \n-/\ndef balanced (𝓔 : machine) : Prop :=\nsorry\n\n/-- As defined in 2.2.1 Definition 1 -/\ndef emulates (π ϕ : protocol) : Prop :=\n ∀ (𝓐 : machine), ∃ (𝓢 : machine), ∀ (𝓔 : machine),\n balanced 𝓔 → (execution π 𝓐 𝓔 ≈ₛ execution π 𝓢 𝓔)\n\ndef dummy_machine (ident : ℕ) (forwards_to : ℕ) (callers : finset ℕ) : machine := \n{ ident := ident,\n initial_state := λ n, \n { val := λ s, if s = [] then 1 else 0, -- todo replace with const added to pmf.lean\n property := \n begin\n apply has_sum_ite_eq,\n end }, -- doesn't matter, stateless\n callers := callers,\n subroutines := {forwards_to},\n backdoor := ∅,\n program := λ st idx msg, \n if idx = forwards_to \n then some ⟨st, decode (unpair_left msg), unpair_right msg⟩\n else some ⟨st, forwards_to, pair msg (encode idx)⟩,\n environment_output := none }\n\n/-- \nPer section 2.2.2, a functionality is described with an ideal protocol which is a protocol with a \nmachine for the functionality and a bunch of dummy machines which call the functionality by \nforwarding messages \n-/\ndef ideal_protocol (m : machine) : protocol :=\n{ machines := finset.cons (m : machine) \n (finset.image (λ i, dummy_machine i m.ident m.callers) m.callers) \n (by {\n simp only [not_exists, finset.mem_image],\n intros x hx,\n sorry,\n }),\n callers_have_subroutines := sorry }\n\n-- /-- Per section 2.3 -/\n-- def subroutine_protocol (𝓟 : protocol) (s : finset ℕ) : protocol :=\n-- { ids := 𝓟.ids \\ s,\n-- μ := 𝓟.μ,\n-- ids_match := begin\n-- intros i hi,\n-- rw finset.mem_sdiff at hi,\n-- exact 𝓟.ids_match i hi.left,\n-- end,\n-- callers_have_subroutines := begin\n-- intros i hi j hj,\n-- rw finset.mem_sdiff at hi hj,\n-- apply 𝓟.callers_have_subroutines,\n-- exact hi.left,\n-- exact hj.left,\n-- end }\n\n/-- Per section 2.3 -/\ndef subroutine (ϕ π : protocol) : Prop := ϕ.machines ⊆ π.machines\n\ninstance : has_subset (protocol) := ⟨λ ϕ π, subroutine ϕ π⟩\n\n\n/-- Per section 2.3 -/\ndef compatible (π ϕ : protocol) : Prop :=\n∀ μ ∈ π.machines, ∃! μ' ∈ ϕ.machines, ((μ : machine).ident) = (μ'.ident) ∧ μ.callers = μ'.callers\n-- Fails without the type ascription, post to forum to figure out whats wrong\n-- Is it that lean doesn't know what the type of a member of a list of machines is?\n-- I can accept that there might be different has_mem instances for a type, but the infoview\n-- indicates it knows μ is a machine\n\ndef identity_compatible (π ρ ϕ : protocol) :=\ndisjoint (π.ids) (ρ.ids \\ ϕ.ids)\n\n/-- Per section 2.3 -/\ndef composed (ρ ϕ π : protocol) (hϕρ : ϕ ⊆ ρ) (hπϕ : compatible π ϕ)\n (h : identity_compatible π ρ ϕ) : protocol :=\n{ machines := (ρ.machines \\ ϕ.machines) ∪ π.machines,\n callers_have_subroutines := begin\n sorry,\n --follows from compatibility\n end }\n\n/-- Section 2.3 theorem 3 -/\ntheorem composition_theorem (ρ ϕ π : protocol) (hϕρ : ϕ ⊆ ρ) (hπϕ : compatible π ϕ)\n (h : identity_compatible π ρ ϕ) (h_emulate : emulates π ϕ) :\n emulates (composed ρ ϕ π hϕρ hπϕ h) ρ :=\nbegin\n sorry,\nend", "meta": {"author": "BoltonBailey", "repo": "uc-lean", "sha": "45cfddb539d24a580461cb122ab77a826809dfda", "save_path": "github-repos/lean/BoltonBailey-uc-lean", "path": "github-repos/lean/BoltonBailey-uc-lean/uc-lean-45cfddb539d24a580461cb122ab77a826809dfda/src/uc.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.48438008427698437, "lm_q2_score": 0.021287353462140182, "lm_q1q2_score": 0.010311170064025417}} {"text": "/-\nCopyright (c) 2020 Robert Y. Lewis. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Robert Y. Lewis\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.default\nimport Mathlib.tactic.fix_reflect_string\nimport Mathlib.PostPort\n\nuniverses l \n\nnamespace Mathlib\n\n/-!\n# Documentation commands\n\nWe generate html documentation from mathlib. It is convenient to collect lists of tactics, commands,\nnotes, etc. To facilitate this, we declare these documentation entries in the library\nusing special commands.\n\n* `library_note` adds a note describing a certain feature or design decision. These can be\n referenced in doc strings with the text `note [name of note]`.\n* `add_tactic_doc` adds an entry documenting an interactive tactic, command, hole command, or\n attribute.\n\nSince these commands are used in files imported by `tactic.core`, this file has no imports.\n\n## Implementation details\n\n`library_note note_id note_msg` creates a declaration `` `library_note.i `` for some `i`.\nThis declaration is a pair of strings `note_id` and `note_msg`, and it gets tagged with the\n`library_note` attribute.\n\nSimilarly, `add_tactic_doc` creates a declaration `` `tactic_doc.i `` that stores the provided\ninformation.\n-/\n\n/-- A rudimentary hash function on strings. -/\ndef string.hash (s : string) : ℕ :=\n string.fold 1\n (fun (h : ℕ) (c : char) => (bit1 (bit0 (bit0 (bit0 (bit0 1)))) * h + char.val c) % unsigned_sz)\n s\n\n/-- `mk_hashed_name nspace id` hashes the string `id` to a value `i` and returns the name\n`nspace._i` -/\n/--\n`copy_doc_string fr to` copies the docstring from the declaration named `fr`\nto each declaration named in the list `to`. -/\n/--\n`copy_doc_string source → target_1 target_2 ... target_n` copies the doc string of the\ndeclaration named `source` to each of `target_1`, `target_2`, ..., `target_n`.\n -/\n/-! ### The `library_note` command -/\n\n/-- A user attribute `library_note` for tagging decls of type `string × string` for use in note\noutput. -/\n/--\n`mk_reflected_definition name val` constructs a definition declaration by reflection.\n\nExample: ``mk_reflected_definition `foo 17`` constructs the definition\ndeclaration corresponding to `def foo : ℕ := 17`\n-/\n/-- If `note_name` and `note` are `pexpr`s representing strings,\n`add_library_note note_name note` adds a declaration of type `string × string` and tags it with\nthe `library_note` attribute. -/\n/--\nA command to add library notes. Syntax:\n```\n/--\nnote message\n-/\n/-- Collects all notes in the current environment.\nReturns a list of pairs `(note_id, note_content)` -/\n/-! ### The `add_tactic_doc_entry` command -/\n\n/-- The categories of tactic doc entry. -/\ninductive doc_category where\n| tactic : doc_category\n| cmd : doc_category\n| hole_cmd : doc_category\n| attr : doc_category\n\n/-- Format a `doc_category` -/\n/-- The information used to generate a tactic doc entry -/\nstructure tactic_doc_entry where\n name : string\n category : doc_category\n decl_names : List name\n tags : List string\n description : string\n inherit_description_from : Option name\n\n/-- Turns a `tactic_doc_entry` into a JSON representation. -/\n/-- `update_description_from tde inh_id` replaces the `description` field of `tde` with the\n doc string of the declaration named `inh_id`. -/\n/--\n`update_description tde` replaces the `description` field of `tde` with:\n\n* the doc string of `tde.inherit_description_from`, if this field has a value\n* the doc string of the entry in `tde.decl_names`, if this field has length 1\n\nIf neither of these conditions are met, it returns `tde`. -/\n/-- A user attribute `tactic_doc` for tagging decls of type `tactic_doc_entry`\nfor use in doc output -/\n/-- Collects everything in the environment tagged with the attribute `tactic_doc`. -/\n/-- `add_tactic_doc tde` adds a declaration to the environment\nwith `tde` as its body and tags it with the `tactic_doc`\nattribute. If `tde.decl_names` has exactly one entry `` `decl`` and\nif `tde.description` is the empty string, `add_tactic_doc` uses the doc\nstring of `decl` as the description. -/\n/--\nA command used to add documentation for a tactic, command, hole command, or attribute.\n\nUsage: after defining an interactive tactic, command, or attribute,\nadd its documentation as follows.\n```lean\n/--\ndescribe what the command does here\n-/\n/--\nAt various places in mathlib, we leave implementation notes that are referenced from many other\nfiles. To keep track of these notes, we use the command `library_note`. This makes it easy to\nretrieve a list of all notes, e.g. for documentation output.\n\nThese notes can be referenced in mathlib with the syntax `Note [note id]`.\nOften, these references will be made in code comments (`--`) that won't be displayed in docs.\nIf such a reference is made in a doc string or module doc, it will be linked to the corresponding\nnote in the doc display.\n\nSyntax:\n```\n/--\nnote message\n-/\n/--\nSome declarations work with open expressions, i.e. an expr that has free variables.\nTerms will free variables are not well-typed, and one should not use them in tactics like\n`infer_type` or `unify`. You can still do syntactic analysis/manipulation on them.\nThe reason for working with open types is for performance: instantiating variables requires\niterating through the expression. In one performance test `pi_binders` was more than 6x\nquicker than `mk_local_pis` (when applied to the type of all imported declarations 100x).\n-/\n-- See Note [open expressions]\n\n/-- behavior of f -/\n-- add docs to core tactics\n\n/--\nThe congruence closure tactic `cc` tries to solve the goal by chaining\nequalities from context and applying congruence (i.e. if `a = b`, then `f a = f b`).\nIt is a finishing tactic, i.e. it is meant to close\nthe current goal, not to make some inconclusive progress.\nA mostly trivial example would be:\n\n```lean\nexample (a b c : ℕ) (f : ℕ → ℕ) (h: a = b) (h' : b = c) : f a = f c := by cc\n```\n\nAs an example requiring some thinking to do by hand, consider:\n\n```lean\nexample (f : ℕ → ℕ) (x : ℕ)\n (H1 : f (f (f x)) = x) (H2 : f (f (f (f (f x)))) = x) :\n f x = x :=\nby cc\n```\n\nThe tactic works by building an equality matching graph. It's a graph where\nthe vertices are terms and they are linked by edges if they are known to\nbe equal. Once you've added all the equalities in your context, you take\nthe transitive closure of the graph and, for each connected component\n(i.e. equivalence class) you can elect a term that will represent the\nwhole class and store proofs that the other elements are equal to it.\nYou then take the transitive closure of these equalities under the\ncongruence lemmas.\n\nThe `cc` implementation in Lean does a few more tricks: for example it\nderives `a=b` from `nat.succ a = nat.succ b`, and `nat.succ a !=\nnat.zero` for any `a`.\n\n* The starting reference point is Nelson, Oppen, [Fast decision procedures based on congruence\nclosure](http://www.cs.colorado.edu/~bec/courses/csci5535-s09/reading/nelson-oppen-congruence.pdf),\nJournal of the ACM (1980)\n\n* The congruence lemmas for dependent type theory as used in Lean are described in\n[Congruence closure in intensional type theory](https://leanprover.github.io/papers/congr.pdf)\n(de Moura, Selsam IJCAR 2016).\n-/\n/--\n`conv {...}` allows the user to perform targeted rewriting on a goal or hypothesis,\nby focusing on particular subexpressions.\n\nSee for more details.\n\nInside `conv` blocks, mathlib currently additionally provides\n* `erw`,\n* `ring`, `ring2` and `ring_exp`,\n* `norm_num`,\n* `norm_cast`,\n* `apply_congr`, and\n* `conv` (within another `conv`).\n\n`apply_congr` applies congruence lemmas to step further inside expressions,\nand sometimes gives between results than the automatically generated\ncongruence lemmas used by `congr`.\n\nUsing `conv` inside a `conv` block allows the user to return to the previous\nstate of the outer `conv` block after it is finished. Thus you can continue\nediting an expression without having to start a new `conv` block and re-scoping\neverything. For example:\n```lean\nexample (a b c d : ℕ) (h₁ : b = c) (h₂ : a + c = a + d) : a + b = a + d :=\nby conv {\n to_lhs,\n conv {\n congr, skip,\n rw h₁,\n },\n rw h₂,\n}\n```\nWithout `conv`, the above example would need to be proved using two successive\n`conv` blocks, each beginning with `to_lhs`.\n\nAlso, as a shorthand, `conv_lhs` and `conv_rhs` are provided, so that\n```lean\nexample : 0 + 0 = 0 :=\nbegin\n conv_lhs { simp }\nend\n```\njust means\n```lean\nexample : 0 + 0 = 0 :=\nbegin\n conv { to_lhs, simp }\nend\n```\nand likewise for `to_rhs`.\n-/\n/--\nAccepts terms with the type `component tactic_state string` or `html empty` and\nrenders them interactively.\nRequires a compatible version of the vscode extension to view the resulting widget.\n\n### Example:\n\n```lean\n/-- A simple counter that can be incremented or decremented with some buttons. -/\n/--\nThe `add_decl_doc` command is used to add a doc string to an existing declaration.\n\n```lean\ndef foo := 5\n\n/--\nDoc string for foo.\n-/\nend Mathlib", "meta": {"author": "AurelienSaue", "repo": "Mathlib4_auto", "sha": "590df64109b08190abe22358fabc3eae000943f2", "save_path": "github-repos/lean/AurelienSaue-Mathlib4_auto", "path": "github-repos/lean/AurelienSaue-Mathlib4_auto/Mathlib4_auto-590df64109b08190abe22358fabc3eae000943f2/Mathlib/tactic/doc_commands_auto.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.20946967639529515, "lm_q2_score": 0.048857782950095914, "lm_q1q2_score": 0.01023422398394816}} {"text": "import Etch.Basic\nimport Etch.Stream\nimport Etch.LVal\nimport Etch.Add\nimport Etch.Mul\n\nclass NatLt (m n : ℕ) where proof : m < n\ninstance NatLt.one (n : ℕ) : NatLt 0 n.succ := ⟨Nat.succ_pos _⟩\ninstance NatLt.trans (m n : ℕ) [h : NatLt m n] : NatLt (m+1) (n+1) :=\n⟨Nat.succ_lt_succ h.proof⟩\n\n-- example : NatLt 3 2 := inferInstance -- no\nexample : NatLt 1 3 := inferInstance\n\nuniverse u v\n\nclass Atomic (α : Type u)\n\n@[reducible] def Ind (_ : ℕ) (ι : Type _) := ι\n\nclass IndexedFunctor (f : ℕ → Type u → Type v) : Type (max (u+1) v) where\n imap : {i : ℕ} → {α β : Type u} → (α → β) → f i α → f i β\n imapConst : {i : ℕ} → {α β : Type u} → α → f i β → f i α := imap ∘ (Function.const _)\n\ninstance [IndexedFunctor F] : Functor (F n) where\n map := IndexedFunctor.imap\n mapConst := IndexedFunctor.imapConst\n\ninductive StrF (ι : Type _) (n : ℕ) (α : Type _)\n| fun (v : Ind n ι →ₐ α) : StrF ι n α\n\ninstance : IndexedFunctor (StrF ι) where\n imap | f, .fun v => .fun (f ∘ v)\n\ninductive StrS (ι : Type _) (n : ℕ) (α : Type _)\n| str (s : Ind n ι →ₛ α) : StrS ι n α\n\ninstance : IndexedFunctor (StrS ι) where\n imap | f, .str g => .str { g with value := f ∘ g.value }\n\nsection HMul\nvariable {ι : Type} [Tagged ι] [DecidableEq ι] [Max ι]\nvariable [IndexedFunctor F] [IndexedFunctor F'] [Atomic ρ]\n\ninstance instHMul.Merge.succ_ss [HMul α β γ] : HMul (StrS ι i α) (StrS ι i β) (StrS ι i γ) :=\n⟨fun | .str s₁, .str s₂ => .str (s₁ * s₂)⟩\ninstance instHMul.Merge.succ_sf [HMul α β γ] : HMul (StrS ι i α) (StrF ι i β) (StrS ι i γ) :=\n⟨fun | .str s₁, .fun s₂ => .str (s₁ * s₂)⟩\ninstance instHMul.Merge.succ_fs [HMul α β γ] : HMul (StrF ι i α) (StrS ι i β) (StrS ι i γ) :=\n⟨fun | .fun s₁, .str s₂ => .str (s₁ * s₂)⟩\ninstance instHMul.Merge.succ_ff [HMul α β γ] : HMul (StrF ι i α) (StrF ι i β) (StrF ι i γ) :=\n⟨fun | .fun s₁, .fun s₂ => .fun (s₁ * s₂)⟩\n\ninstance instHMul.Merge.scalar_r [HMul α ρ α] : HMul (F i α) ρ (F i α) :=\n⟨fun s₁ k => (· * k) <$> s₁⟩\ninstance instHMul.Merge.lt [NatLt i j] [HMul α (F' j β) γ] : HMul (F i α) (F' j β) (F i γ) :=\n⟨fun s₁ k => (· * k) <$> s₁⟩\ninstance instHMul.Merge.scalar_l [HMul ρ α α] : HMul ρ (F i α) (F i α) :=\n⟨fun k s₂ => (k * ·) <$> s₂⟩\ninstance instHMul.Merge.gt [NatLt j i] [HMul (F' i α) β γ] : HMul (F' i α) (F j β) (F j γ) :=\n⟨fun k s₂ => (k * ·) <$> s₂⟩\n\ninstance [Mul α] : Mul (StrS ι i α) := ⟨HMul.hMul⟩ \ninstance [Mul α] : Mul (StrF ι i α) := ⟨HMul.hMul⟩ \n\n-- Special: bool * S\ninstance instHMul.Merge.scalar_r_bool : HMul (StrS ι i α) (E Bool) (StrS ι i α) :=\n⟨fun | .str s₁, k => .str (Guard.guard k s₁)⟩\ninstance instHMul.Merge.scalar_l_bool : HMul (E Bool) (StrS ι i α) (StrS ι i α) :=\n⟨fun | k, .str s₂ => .str (Guard.guard k s₂)⟩\ninstance instHMul.Merge.succ_sf_bool : HMul (StrS ι i α) (StrF ι i (E Bool)) (StrS ι i α) :=\n⟨fun | .str s₁, .fun s₂ => .str (s₁ * s₂)⟩\ninstance instHMul.Merge.succ_fs_bool : HMul (StrF ι i (E Bool)) (StrS ι i β) (StrS ι i β) :=\n⟨fun | .fun s₁, .str s₂ => .str (s₁ * s₂)⟩\nend HMul\n\nsection HAdd\nvariable {α β γ ι : Type}\n [Tagged ι] [TaggedC ι] [DecidableEq ι]\n [LT ι] [LE ι] [DecidableRel (LT.lt : ι → ι → Prop)]\n [DecidableRel (LE.le : ι → ι → _)]\n {i : ℕ}\n [Guard α] [Guard β]\nvariable [IndexedFunctor F] [IndexedFunctor F'] [Atomic ρ]\n\ninstance instHAdd.Merge.succ_ss [HAdd α β γ] : HAdd (StrS ι i α) (StrS ι i β) (StrS ι i γ) :=\n⟨fun | .str s₁, .str s₂ => .str (s₁ + s₂)⟩\ninstance instHAdd.Merge.succ_sf [HAdd α β γ] : HAdd (StrS ι i α) (StrF ι i β) (StrS ι i γ) :=\n⟨fun | .str s₁, .fun s₂ => .str (s₁ + s₂)⟩\ninstance instHAdd.Merge.succ_fs [HAdd α β γ] : HAdd (StrF ι i α) (StrS ι i β) (StrS ι i γ) :=\n⟨fun | .fun s₁, .str s₂ => .str (s₁ + s₂)⟩\ninstance instHAdd.Merge.succ_ff [HAdd α β γ] : HAdd (StrF ι i α) (StrF ι i β) (StrF ι i γ) :=\n⟨fun | .fun s₁, .fun s₂ => .fun (s₁ + s₂)⟩\n\ninstance instHAdd.Merge.scalar_r [HAdd α ρ α] : HAdd (F i α) ρ (F i α) :=\n⟨fun s₁ k => (· + k) <$> s₁⟩\ninstance instHAdd.Merge.lt [NatLt i j] [HAdd α (F' j β) γ] : HAdd (F i α) (F' j β) (F i γ) :=\n⟨fun s₁ k => (· + k) <$> s₁⟩\ninstance instHAdd.Merge.scalar_l [HAdd ρ α α] : HAdd ρ (F i α) (F i α) :=\n⟨fun k s₂ => (k + ·) <$> s₂⟩\ninstance instHAdd.Merge.gt [NatLt j i] [HAdd (F i α) β γ] : HAdd (F i α) (F' j β) (F' j γ) :=\n⟨fun k s₂ => (k + ·) <$> s₂⟩\n\ninstance [Add α] : Add (StrS ι i α) := ⟨HAdd.hAdd⟩ \ninstance [Add α] : Add (StrF ι i α) := ⟨HAdd.hAdd⟩ \nend HAdd\n\ninstance : Atomic (E α) := ⟨⟩\n\nnotation:37 a:36 \" × \" b:36 \" ⟶ₐ \" c:36 => StrF b a c\ninfixr:25 \" ↠ₐ \" => λ (p : ℕ×Type) c => StrF (Prod.snd p) (Prod.fst p) c\nnotation:37 a:36 \" × \" b:36 \" ⟶ₛ \" c:36 => StrS b a c\ninfixr:25 \" ↠ₛ \" => λ (p : ℕ×Type) c => StrS (Prod.snd p) (Prod.fst p) c\n\ninstance [Guard α] : Guard (n × ι ⟶ₛ α) where\n guard b := fun | .str f => .str (Guard.guard b f)\n\ninstance [Tagged α] [Zero α] : Guard (n × ι ⟶ₐ E α) where\n guard b := fun | .fun f => .fun (Guard.guard b f)\n\nvariable\n{α β γ : Type _}\n(n : ℕ)\n{ι : Type _} [Tagged ι] [TaggedC ι] [DecidableEq ι]\n[LT ι] [DecidableRel (LT.lt : ι → ι → _)] [Zero ι]\n[LE ι] [DecidableRel (LE.le : ι → ι → _)]\n[Max ι]\n\ninstance StrS.Mul [Mul γ] : Mul (i × ι ⟶ₛ γ) := ⟨HMul.hMul⟩\ninstance StrF.Mul [Mul γ] : Mul (i × ι ⟶ₐ γ) := ⟨HMul.hMul⟩\n\ninstance : Coe (ι →ₛ α) (n × ι ⟶ₛ α) := ⟨.str⟩\ninstance : Coe (ι →ₐ α) (n × ι ⟶ₐ α) := ⟨.fun⟩\ninstance [Coe α β] : Coe (ι →ₛ α) (n × ι ⟶ₛ β) := ⟨.str ∘ Functor.map Coe.coe⟩\ninstance [Coe α β] : Coe (ι →ₐ α) (n × ι ⟶ₐ β) := ⟨.fun ∘ Functor.map Coe.coe⟩\n\nclass of_stream (α β : Type _) := (coe : α → β)\ninstance base.of_stream : of_stream α α := ⟨id⟩\n\ndef Stream.of [of_stream α β] : α → β := of_stream.coe\n\nclass SumIndex (n : ℕ) (α : Type _) (β : outParam $ Type _) := (sum : α → β)\ninstance sum_eq (n : ℕ) : SumIndex n (n × ι ⟶ₛ α) (Contraction α) := ⟨fun | .str s => S.contract s⟩\ninstance sum_lt_f [IndexedFunctor F] (m n : ℕ) [NatLt n m] [SumIndex m α β] : SumIndex m (F n α) (F n β) := ⟨IndexedFunctor.imap $ SumIndex.sum m⟩\ninstance sum_lt_s [IndexedFunctor F] (m n : ℕ) [NatLt n m] [SumIndex m α β] : SumIndex m (F n α) (F n β) := ⟨IndexedFunctor.imap $ SumIndex.sum m⟩\n\nnotation:35 \"∑\" i:34 \":\" v:34 => SumIndex.sum i.1 v\nnotation:35 \"∑\" i:34 \",\" j:34 \":\" v:34 => SumIndex.sum i.1 (SumIndex.sum j.1 v)\nnotation:35 \"∑\" i:34 \",\" j:34 \",\" k:34 \":\" v:34 => SumIndex.sum i.1 (SumIndex.sum j.1 (SumIndex.sum k.1 v))\nnotation:35 \"∑\" i:34 \",\" j:34 \",\" k:34 \",\" l:34 \":\" v:34 => SumIndex.sum i.1 (SumIndex.sum j.1 (SumIndex.sum k.1 (SumIndex.sum l.1 v)))\n--macro \"∑\" i:term ws j:term \",\" v:term : term => `(SumIndex.sum $i.1 (SumIndex.sum $j.1 $v))\n--macro \"∑\" i:term \",\" v:term : term => `(SumIndex.sum $i.1 $v)\n--macro \"∑\" i:term+ \",\" v:term : term => `(SumIndex.sum $(i[0]!).1 $v)\n\nclass ApplyScalarFn (α β γ : Type _) (δ : outParam $ Type _) := (map : (E α → E β) → γ → δ)\ninstance : ApplyScalarFn α β (E α) (E β) := ⟨ (. $ .) ⟩\ninstance [IndexedFunctor F] [ApplyScalarFn α β α' β'] : ApplyScalarFn α β (F n α') (F n β') := ⟨ λ f x => ApplyScalarFn.map f <$> x ⟩\ninfixr:10 \" <$$> \" => ApplyScalarFn.map\n\nsection tests\n\nvariable (a : 0 × ℕ ⟶ₛ E R)\nvariable (A : ℕ →ₛ ℕ →ₛ E R)\nvariable (B : ℕ →ₐ ℕ →ₛ E R)\nprivate abbrev i := (0, ℕ)\nprivate abbrev j := (1, ℕ)\nprivate abbrev k := (2, ℕ)\n#check SumIndex.sum 0 a\n#check ∑ i: (A : i ↠ₛ j ↠ₛ E R)\n#check ∑ i, j: (A : i ↠ₛ j ↠ₛ E R)\n#check (A : i ↠ₛ j ↠ₛ E R) * (B : j ↠ₐ k ↠ₛ E R)\n--#check ∑ i, j: (A : i ↠ j ↠ E R)\n--#check ∑ j, k: (A : i ↠ j ↠ E R) * (B : j ↠ k ↠ E R)\n\nend tests\n\n/-\n#check Nat.add\ninductive St (α : Type) : ℕ → Type\n| base : St α 0\n| vec (δ) {n} (of : St α n) : St α (n+δ)\n\n-- no\ndef St.eval {n α} (ctxt : Fin n → Type) : St α n → List Type\n| base => []\n| vec d x => ctxt ⟨d, Nat.add⟩ :: x.eval _\n\nclass Broadcast (α β : Type _) (γ : outParam $ Type _) :=\n broadcast : List ℕ → α → β → γ × γ\n\ninstance [Rectangle f] [Broadcast α β γ] : Broadcast (f i α) (f j β) (f\n\ndef broadcast (ordering : List ℕ) (a : f i α) (b : g i β)\n/- todo\n fix ∑ notation (use ∃ from Heap)\n make broadcast based on a given ordering argument\n-/\n-/\n", "meta": {"author": "kovach", "repo": "etch", "sha": "26ef67eb83cf7c5cfd1667059e16c3873b9098ca", "save_path": "github-repos/lean/kovach-etch", "path": "github-repos/lean/kovach-etch/etch-26ef67eb83cf7c5cfd1667059e16c3873b9098ca/etch4/Etch/ShapeInference.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41111085480195975, "lm_q2_score": 0.024798159114511883, "lm_q1q2_score": 0.010194792391081989}} {"text": "import .simulation\n\nimport ..scheduling\nimport ..spec\n\nuniverse variables u u₀ u₁ u₂\nopen predicate nat\nlocal infix ` ≃ `:75 := v_eq\nlocal prefix `♯ `:0 := cast (by simp)\n\nnamespace temporal\n\nnamespace one_to_one\nsection\nopen fairness\nparameters {α : Type u} {β : Type u₀} {γ : Type u₁ }\nparameters {evt : Type u₂}\nparameters {m₀ : mch' evt (γ×α)} {m₁ : mch' evt (γ×β)}\nlocal notation `p` := m₀.init\nlocal notation `q` := m₁.init\nlocal notation `aevt` := m₀.evt\nlocal notation `cevt` := m₁.evt\nlocal notation `cs₀` := m₀.cs\nlocal notation `fs₀` := m₀.fs\nlocal notation `cs₁` := m₁.cs\nlocal notation `fs₁` := m₁.fs\nlocal notation `A` := m₀.A\nlocal notation `C` := m₁.A\nparameters (J : pred' (γ×α×β))\nparameters (Jₐ : pred' (γ×α))\n\ndef C' (e : evt) : act (evt×γ×β) :=\nλ ⟨sch,s⟩ ⟨_,s'⟩, sch = e ∧ C e s s'\n\nabbreviation ae (i : evt) : event (γ×α) := ⟨cs₀ i,fs₀ i,A i⟩\nabbreviation ce (i : evt) : event (evt×γ×β) := ⟨cs₁ i!pair.snd,fs₁ i!pair.snd,C' i⟩\n\nsection specs\n\nparameters m₀ m₁\n\ndef SPEC₀.saf' (v : tvar α) (o : tvar γ) (sch : tvar evt) : cpred :=\nspec_saf_spec m₀ ⦃o,v⦄ sch\n\ndef SPEC₀ (v : tvar α) (o : tvar γ) : cpred :=\nspec m₀ ⦃o,v⦄\n\ndef SPEC₁ (v : tvar β) (o : tvar γ) : cpred :=\nspec m₁ ⦃o,v⦄\n\ndef SPEC₂ (v : tvar β) (o : tvar γ) (s : tvar evt) : cpred :=\nspec_sch m₁ ⦃o,v⦄ s\n\nend specs\n\nparameters [inhabited α] [inhabited evt]\n\nparameter init_Jₐ : ∀ w o, (o,w) ⊨ p → (o,w) ⊨ Jₐ\nparameter evt_Jₐ : ∀ w o w' o' e,\n (o,w) ⊨ Jₐ →\n (o,w) ⊨ cs₀ e →\n (o,w) ⊨ fs₀ e →\n A e (o,w) (o',w') →\n (o',w') ⊨ Jₐ\n\nparameter SIM₀ : ∀ v o, (o,v) ⊨ q → ∃ w, (o,w) ⊨ p ∧ (o,w,v) ⊨ J\nparameter SIM\n: ∀ w v o v' o' e,\n (o,w,v) ⊨ J →\n (o,w) ⊨ Jₐ →\n (o,v) ⊨ cs₁ e →\n (o,v) ⊨ fs₁ e →\n C e (o,v) (o',v') →\n ∃ w', (o,w) ⊨ cs₀ e ∧\n (o,w) ⊨ fs₀ e ∧\n A e (o,w) (o',w') ∧\n (o',w',v') ⊨ J\n\nparameters (v : tvar β) (o : tvar γ) (sch : tvar evt)\n\nvariable (Γ : cpred)\n\nparameters β γ\n\nvariable Hpo : ∀ w e sch,\n one_to_one_po' (SPEC₁ v o ⋀ SPEC₀.saf' w o sch ⋀ ◻(J ! ⦃o,w,v⦄))\n (ce e) (ae e) ⦃sch,o,v⦄ ⦃o,w⦄\n\nparameters {β γ}\n\nsection SPEC₂\nvariables H : Γ ⊢ SPEC₂ v o sch\n\nopen prod temporal.prod\n\ndef Next_a : act $ (γ × evt) × α :=\nλ σ σ',\n∃ e, σ.1.2 = e ∧\n map_left fst σ ⊨ cs₀ e ∧\n map_left fst σ ⊨ fs₀ e ∧\n (A e on map_left fst) σ σ'\n\ndef Next_c : act $ (γ × evt) × β :=\nλ σ σ',\n∃ e, σ.1.2 = e ∧\n map_left fst σ ⊨ cs₁ e ∧\n map_left fst σ ⊨ fs₁ e ∧\n (C e on map_left fst) σ σ'\n\nsection J\ndef J' : pred' ((γ × evt) × α × β) :=\nJ ! ⟨ prod.map_left fst ⟩\n\ndef JJₐ : pred' ((γ × evt) × α) :=\nJₐ ! ⟨ prod.map_left fst ⟩\n\ndef p' : pred' ((γ × evt) × α) :=\np ! ⟨ prod.map_left fst ⟩\n\ndef q' : pred' ((γ × evt) × β) :=\nq ! ⟨ prod.map_left fst ⟩\n\nend J\n\nvariable w : tvar α\nopen simulation function\nnoncomputable def Wtn := Wtn p' Next_a J' v ⦃o,sch⦄\n\nvariable valid_witness\n: Γ ⊢ Wtn w\n\nlemma abstract_sch (e : evt)\n: Γ ⊢ sch ≃ e ⋀ cs₀ e ! ⦃o,w⦄ ⋀ fs₀ e ! ⦃o,w⦄ ⋀ ⟦ o,w | A e ⟧ ≡\n sch ≃ e ⋀ ⟦ ⦃o,sch⦄,w | Next_a ⟧ :=\nbegin\n lifted_pred,\n split ; intro h ; split\n ; casesm* _ ∧ _ ; try { assumption }\n ; simp [Next_a,on_fun] at * ; cc,\nend\n\nsection Simulation_POs\ninclude SIM₀\nlemma SIM₀' (v : β) (o : γ × evt)\n (h : (o, v) ⊨ q')\n: (∃ (w : α), (o, w) ⊨ p' ∧ (o, w, v) ⊨ J') :=\nbegin\n simp [q',prod.map_left] at h,\n specialize SIM₀ v o.1 h,\n revert SIM₀, intros_mono,\n simp [J',p',map], intros,\n constructor_matching* [Exists _, _ ∧ _] ;\n tauto,\nend\n\nomit SIM₀\ninclude SIM\nlemma SIM' (w : α) (v : β) (o : γ × evt) (v' : β) (o' : γ × evt)\n (h₀ : (o, w, v) ⊨ J')\n (h₃ : (o, w) ⊨ JJₐ)\n (h₄ : Next_c (o, v) (o', v'))\n: (∃ w', Next_a (o,w) (o',w') ∧ (o', w', v') ⊨ J') :=\nbegin\n simp [J',map] at h₀,\n simp [Next_c,on_fun] at h₄,\n casesm* _ ∧ _,\n simp [JJₐ] at h₃,\n specialize SIM w v o.1 v' o'.1 o.2 h₀ _ _ _ _\n ; try { assumption },\n cases SIM with w' SIM,\n existsi [w'],\n simp [Next_a, J',on_fun,map,h₀],\n tauto,\nend\n\ninclude H\nomit SIM\nlemma H'\n: Γ ⊢ simulation.SPEC₁ q' Next_c v ⦃o,sch⦄ :=\nbegin [temporal]\n simp [SPEC₂,simulation.SPEC₁,q'] at H ⊢,\n split, tauto,\n casesm* _ ⋀ _,\n select h : ◻p_exists _,\n henceforth! at h ⊢,\n cases h with e h,\n explicit' [Next_c,sched] with h\n { casesm* _ ∧ _, subst e, tauto, }\nend\n\nomit H\nsection\ninclude init_Jₐ\nlemma init_Jₐ' (w : α) (o : γ × evt)\n (h : (o, w) ⊨ p')\n: (o, w) ⊨ JJₐ :=\nby { cases o, simp [JJₐ,p'] at *, solve_by_elim }\nend\n\nsection\ninclude evt_Jₐ\nlemma evt_Jₐ' (w : α) (o : γ × evt) (w' : α) (o' : γ × evt)\n (h₀ : (o, w) ⊨ JJₐ)\n (h₁ : Next_a (o, w) (o', w'))\n: (o', w') ⊨ JJₐ :=\nby { cases o, simp [JJₐ,p',Next_a,on_fun] at *, tauto }\nend\n\ninclude SIM₀ SIM init_Jₐ evt_Jₐ H\nlemma witness_imp_SPEC₀_saf\n (h : Γ ⊢ Wtn w)\n: Γ ⊢ SPEC₀.saf' w o sch :=\nbegin [temporal]\n have hJ := J_inv_in_w p' q'\n temporal.one_to_one.Next_a\n temporal.one_to_one.Next_c\n temporal.one_to_one.J'\n temporal.one_to_one.JJₐ\n temporal.one_to_one.init_Jₐ'\n temporal.one_to_one.evt_Jₐ'\n temporal.one_to_one.SIM₀'\n temporal.one_to_one.SIM'\n v ⦃o,sch⦄ Γ\n (temporal.one_to_one.H' _ H) _ h,\n have hJ' := abs_J_inv_in_w p' q'--\n temporal.one_to_one.Next_a\n temporal.one_to_one.Next_c\n temporal.one_to_one.J'\n temporal.one_to_one.JJₐ\n temporal.one_to_one.init_Jₐ'\n temporal.one_to_one.evt_Jₐ'\n temporal.one_to_one.SIM₀'\n temporal.one_to_one.SIM'\n v ⦃o,sch⦄ Γ\n (temporal.one_to_one.H' _ H)\n _ h ,\n simp [SPEC₀.saf',SPEC₂,Wtn,simulation.Wtn] at h ⊢ H,\n casesm* _ ⋀ _,\n split,\n { clear SIM hJ,\n select h : w ≃ _,\n select h' : q ! _,\n rw [← pair.snd_mk sch w,h],\n explicit\n { simp [Wx₀] at ⊢ h', unfold_coes,\n simp [Wx₀_f,p',J',map],\n cases SIM₀ (σ ⊨ v) (σ ⊨ o) h',\n apply_epsilon_spec, } },\n { clear SIM₀,\n select h : ◻(_ ≃ _),\n select h' : ◻(p_exists _),\n henceforth! at h h' ⊢ hJ hJ',\n explicit' [Wf,Wf_f,J',JJₐ]\n with h h' hJ hJ'\n { simp [Next_a,on_fun] at h h',\n casesm* [_ ∧ _,Exists _],\n subst w', subst h'_w,\n apply_epsilon_spec,\n have : (∃ (w' : α), (o, w) ⊨ cs₀ sch ∧\n (o, w) ⊨ fs₀ sch ∧ A sch (o, w) (o', w') ∧ (o', w', v') ⊨ J), solve_by_elim,\n cases this, tauto, } },\nend\n\nomit H\nparameters p q cs₁ fs₁\ninclude Hpo p\n\nlemma SPEC₂_imp_SPEC₁\n: (SPEC₂ v o sch) ⟹ (SPEC₁ v o) :=\nbegin [temporal]\n simp only [SPEC₁,SPEC₂,temporal.one_to_one.SPEC₁,temporal.one_to_one.SPEC₂],\n monotonicity, apply ctx_p_and_p_imp_p_and',\n { monotonicity, simp, intros x h₀ h₁ _ _,\n existsi x, tauto, },\n { intros h i h₀ h₁,\n replace h := h _ h₀ h₁,\n revert h, monotonicity, simp, }\nend\n\nlemma H_C_imp_A (e : evt)\n: SPEC₂ v o sch ⋀ Wtn w ⋀ ◻(J ! ⦃o,w,v⦄) ⟹\n ◻(cs₁ e ! ⦃o,v⦄ ⋀ fs₁ e ! ⦃o,v⦄ ⋀ sch ≃ ↑e ⋀ ⟦ o,v | C e ⟧ ⟶\n cs₀ e ! ⦃o,w⦄ ⋀ fs₀ e ! ⦃o,w⦄ ⋀ ⟦ o,w | A e ⟧) :=\nbegin [temporal]\n intro H',\n have H : temporal.one_to_one.SPEC₁ v o ⋀\n temporal.one_to_one.Wtn w ⋀\n ◻(J ! ⦃o,w,v⦄),\n { revert H', persistent,\n intro, casesm* _ ⋀ _, split* ; try { assumption },\n apply temporal.one_to_one.SPEC₂_imp_SPEC₁ _ Γ _,\n solve_by_elim, casesm* _ ⋀ _, solve_by_elim, },\n clear Hpo,\n let J' := temporal.one_to_one.J',\n have init_Jₐ' := temporal.one_to_one.init_Jₐ', clear init_Jₐ,\n have evt_Jₐ' := temporal.one_to_one.evt_Jₐ', clear evt_Jₐ,\n have SIM₀' := temporal.one_to_one.SIM₀', clear SIM₀,\n have SIM' := temporal.one_to_one.SIM', clear SIM,\n have := C_imp_A_in_w p' _ (Next_a A) (Next_c C) J' _\n init_Jₐ' evt_Jₐ'\n SIM₀' SIM' v ⦃o,sch⦄ Γ _ w _,\n { henceforth! at this ⊢,\n simp, intros h₀ h₁ h₂ h₃, clear_except this h₀ h₁ h₂ h₃,\n suffices : sch ≃ ↑e ⋀ cs₀ e ! ⦃o,w⦄ ⋀ fs₀ e ! ⦃o,w⦄ ⋀ ⟦ o,w | A e ⟧,\n { tauto },\n rw abstract_sch, split, assumption,\n apply this _,\n simp [Next_c],\n suffices : ⟦ ⦃o,sch⦄,v | λ (σ σ' : (γ × evt) × β), (σ.fst).snd = e ∧ (C e on map_left fst) σ σ' ⟧,\n { explicit' with h₀ h₁ h₂ h₃ { cc, }, },\n rw [← action_and_action,← init_eq_action,action_on'], split,\n explicit\n { simp at ⊢ h₀, assumption },\n simp [h₃], },\n clear_except H',\n simp [simulation.SPEC₁,SPEC₂,temporal.one_to_one.SPEC₂] at H' ⊢,\n cases_matching* _ ⋀ _, split,\n { simp [q'], assumption, },\n { select H' : ◻(p_exists _), clear_except H',\n henceforth at H' ⊢, cases H' with i H',\n simp [Next_c],\n suffices : ⟦ ⦃o,sch⦄,v | λ (σ σ' : (γ × evt) × β), (σ.fst).snd = i ∧ (C i on map_left fst) σ σ' ⟧,\n { explicit'* { cases this, subst i, tauto, } },\n explicit'* { cc }, },\n { cases_matching* _ ⋀ _, assumption, },\nend\n\nlemma Hpo' (e : evt)\n: one_to_one_po (SPEC₂ v o sch ⋀ Wtn w ⋀ ◻(J ! ⦃o,w,v⦄))\n/- -/ (cs₁ e ! ⦃o,v⦄)\n (fs₁ e ! ⦃o,v⦄)\n (sch ≃ ↑e ⋀ ⟦ o,v | C e ⟧)\n/- -/ (cs₀ e ! ⦃o,w⦄)\n (fs₀ e ! ⦃o,w⦄)\n ⟦ o,w | A e ⟧ :=\nbegin\n have\n : temporal.one_to_one.SPEC₂ v o sch ⋀ temporal.one_to_one.Wtn w ⋀ ◻(J ! ⦃o,w,v⦄) ⟹\n temporal.one_to_one.SPEC₁ v o ⋀ temporal.one_to_one.SPEC₀.saf' w o sch ⋀ ◻(J ! ⦃o,w,v⦄),\n begin [temporal]\n simp, intros h₀ h₁ h₂,\n split*,\n { apply temporal.one_to_one.SPEC₂_imp_SPEC₁ Hpo _ h₀, },\n { apply temporal.one_to_one.witness_imp_SPEC₀_saf ; solve_by_elim, },\n { solve_by_elim }\n end,\n constructor,\n iterate 3\n { cases (Hpo w e sch),\n simp at *,\n transitivity,\n { apply this },\n { assumption }, },\n begin [temporal]\n intros Hs,\n have H_imp := temporal.one_to_one.H_C_imp_A Hpo w e _ Hs,\n henceforth! at ⊢ H_imp,\n simp at H_imp ⊢,\n exact H_imp,\n end\nend\n\nend Simulation_POs\n\ninclude H SIM₀ SIM Hpo init_Jₐ evt_Jₐ\n\nlemma sched_ref (i : evt) (w : tvar α)\n (Hw : Γ ⊢ Wtn w)\n (h : Γ ⊢ sched (cs₁ i ! ⦃o,v⦄) (fs₁ i ! ⦃o,v⦄) (sch ≃ ↑i ⋀ ⟦ o,v | C i ⟧))\n: Γ ⊢ sched (cs₀ i ! ⦃o,w⦄) (fs₀ i ! ⦃o,w⦄)\n ⟦ o,w | A i ⟧ :=\nbegin [temporal]\n have H' := one_to_one.H' C v o sch _ H,\n have hJ : ◻(J' J ! ⦃⦃o,sch⦄,w,v⦄),\n { replace SIM₀ := SIM₀' _ SIM₀,\n replace SIM := SIM' A C J _ SIM,\n apply simulation.J_inv_in_w p' q' (Next_a A) _ (J' J) _ _ _ SIM₀ SIM _ ⦃o,sch⦄ _ H' w Hw,\n apply temporal.one_to_one.init_Jₐ',\n apply temporal.one_to_one.evt_Jₐ' },\n simp [J'] at hJ,\n have Hpo' := temporal.one_to_one.Hpo' Hpo w i,\n apply replacement Hpo' Γ _,\n tauto, solve_by_elim,\nend\n\nlemma one_to_one\n: Γ ⊢ ∃∃ w, SPEC₀ w o :=\nbegin [temporal]\n select_witness w : temporal.one_to_one.Wtn w\n with Hw using J,\n have this := H, revert this,\n dsimp [SPEC₀,SPEC₁],\n have H' := temporal.one_to_one.H' , -- o sch,\n apply ctx_p_and_p_imp_p_and' _ _,\n apply ctx_p_and_p_imp_p_and' _ _,\n { clear_except SIM₀ Hw H,\n replace SIM₀ := temporal.one_to_one.SIM₀',\n have := init_in_w p' q' (Next_a A) (J' J) SIM₀ v ⦃o,sch⦄ Γ _ Hw,\n intro Hq,\n simp [p',q'] at this,\n solve_by_elim, },\n { clear_except SIM SIM₀ Hw H init_Jₐ evt_Jₐ,\n have H' := H' C v o sch _ H,\n replace SIM₀ := SIM₀' _ SIM₀,\n replace SIM := SIM' A C J _ SIM,\n have := temporal.simulation.C_imp_A_in_w p' q'\n (Next_a A) (Next_c C) (J' J) _ _ _ SIM₀ SIM v ⦃o,sch⦄ _ H' w Hw,\n { monotonicity!,\n simp [exists_action],\n intros e h₀ h₁ h₂ h₃, replace this := this _,\n explicit'* [Next_a]\n { intros, casesm* _ ∧ _,\n constructor_matching* [Exists _,_ ∧ _] ; solve_by_elim, },\n simp [Next_c],\n suffices : ⟦ ⦃o,sch⦄,v | λ (σ σ' : (γ × evt) × β), map_left prod.fst σ ⊨ fs₁ e ∧ ((λ s s', s = e) on (prod.snd ∘ prod.fst)) σ σ' ∧ (C e on map_left prod.fst) σ σ' ⟧,\n explicit' with h₀ h₁ this\n { intros, subst e, tauto, },\n henceforth at this,\n explicit'* [Next_c]\n { tauto } },\n { apply temporal.one_to_one.init_Jₐ' },\n { apply temporal.one_to_one.evt_Jₐ' }, },\n { intros h i,\n replace h := h i,\n apply temporal.one_to_one.sched_ref; solve_by_elim },\nend\nend SPEC₂\n\nsection refinement_SPEC₂\ninclude Hpo SIM₀ SIM init_Jₐ evt_Jₐ\nparameters m₁ m₀\n\nlemma refinement_SPEC₂\n: Γ ⊢ (∃∃ sch, SPEC₂ v o sch) ⟶ (∃∃ a, SPEC₀ a o) :=\nbegin [temporal]\n simp, intros sch Hc,\n apply one_to_one J Jₐ init_Jₐ evt_Jₐ SIM₀ SIM _ _ _ _ _ Hc,\n apply Hpo,\nend\nend refinement_SPEC₂\n\nlemma refinement_SPEC₁ [schedulable evt]\n: SPEC₁ v o ⟹ (∃∃ sch, SPEC₂ v o sch) :=\nassume Γ,\nsch_intro _ _ _ _ _ _\n\ninclude SIM₀ SIM init_Jₐ evt_Jₐ\nlemma refinement [schedulable evt]\n (h : ∀ c a e sch, one_to_one_po' (SPEC₁ c o ⋀ SPEC₀.saf' a o sch ⋀ ◻(J ! ⦃o,a,c⦄))\n ⟨cs₁ e!pair.snd,fs₁ e!pair.snd,C' e⟩\n ⟨cs₀ e,fs₀ e,A e⟩ ⦃sch,o,c⦄ ⦃o,a⦄)\n: (∃∃ c, SPEC₁ c o) ⟹ (∃∃ a, SPEC₀ a o) :=\nbegin [temporal]\n transitivity (∃∃ c sch, SPEC₂ q C cs₁ fs₁ c o sch),\n { apply p_exists_p_imp_p_exists ,\n intro v,\n apply refinement_SPEC₁, },\n { simp, intros c sch Hspec,\n specialize h c, simp [one_to_one_po'] at h,\n apply refinement_SPEC₂ A C cs₀ fs₀ cs₁ fs₁ J Jₐ init_Jₐ evt_Jₐ SIM₀ SIM c o _ _ _,\n simp [one_to_one_po'],\n exact h,\n existsi sch, assumption },\nend\n\nend\nend one_to_one\n\nend temporal\n", "meta": {"author": "unitb", "repo": "temporal-logic", "sha": "accec04d1b09ca841be065511c9e206b725b16e9", "save_path": "github-repos/lean/unitb-temporal-logic", "path": "github-repos/lean/unitb-temporal-logic/temporal-logic-accec04d1b09ca841be065511c9e206b725b16e9/src/temporal_logic/refinement/one_to_one.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4416730056646256, "lm_q2_score": 0.022977372377127582, "lm_q1q2_score": 0.010148485120081282}} {"text": "/-\nimport Std.Data.HashSet\nimport Std.Data.AssocList\n/-\nTODO: ステップの進行時に誘発型能力の誘発をできるようにする.\n置換型能力を取り扱うため,eventキューを用意し,ゲーム内の行動は一旦このキューにエンキューされる.\n 置換型能力は置換するイベントと置換後のイベントで表される.\n ある状態での置換型能力の集合を用意しておき,eventキューの先端のイベントでその集合にfilterし対応する置換型能力を適用する\n 置換型能力に置換する優先度を定義するが,同じ場合はここにユーザーの選択が入る\n 「禁止する」効果は「何もしない」に置換する置換型効果として扱い,最も高い優先度を持つ.\nステップを開始するときの置換型能力と誘発型能力をどうするか決めてないね\nループの扱い\n ある状態である行動をしたときに何らかの能力(群)が生成され,ユーザが行動する前に同じ能力が有限個の違いを除いた状態s1とs2で生成されたとき,無限ループとする.\n ↑に加えてユーザの行動が入る場合,「前回と同じ行動をする」という前提を加えれば無限ループになるとき,ループとする.\n ループが存在するとき,有限回後にユーザの行動を変化させなければならない.\n 基本的に能力は強制効果「〜する」であり,無限ループになるときに限りしないことを選択できる.\n 任意効果「してもよい」がループを形成する場合,↑に準ずる.\n ループを形成する場合,有限個の違いを変数化して一気に処理したいが厳しそう\n-/\ninductive Player: Type\n| player₁\n| player₂\n| player₃\n| player₄\nderiving DecidableEq\nopen Player\ninstance : Inhabited Player where default := player₁\ndef NextPlayerType := ∃f: Player → Player, ∀p: Player, ¬f p = p\ndef NextPlayerType.default: NextPlayerType := by {\n let f \n | player₁ => player₂\n | player₂ => player₃\n | player₃ => player₄\n | player₄ => player₁\n exists f;\n intro p';\n cases p';\n all_goals {\n intro;\n contradiction;\n }\n}\ninstance : Inhabited NextPlayerType where default := NextPlayerType.default\ndef PlayerToNat: Player → Nat\n| player₁ => 0\n| player₂ => 1\n| player₃ => 2\n| player₄ => 3\n\ninductive BeginningPhase: Type\n| untap -- MEMO: namae kaeru yotei\n| upkeep\n| draw\nopen BeginningPhase\n\ninductive CombatPhase: Type\n| beginningOfCombat\n| declareAtackers\n| declareBlockers\n| combatDamage\n| endOfCombat\nopen CombatPhase\n\ninductive EndingPhase: Type\n| ending\n| cleanup\nopen EndingPhase\n\ninductive Phase: Type\n| beginning (step: BeginningPhase)\n| main\n| combat (step: CombatPhase)\n| ending (step: EndingPhase)\nopen Phase\ndef defaultBeginningPhase := [\n beginning untap,\n beginning upkeep,\n beginning draw\n]\ndef defaultCombatPhase := [\n combat beginningOfCombat,\n combat declareAtackers,\n combat declareBlockers,\n combat combatDamage,\n combat endOfCombat\n]\ndef defaultEndingPhase := [\n ending ending,\n ending cleanup\n]\n\ndef TurnList := List Player\n deriving Inhabited\ndef PhaseList := List Phase\n deriving Inhabited\ndef defaultPhaseList :=\n defaultBeginningPhase\n ++ [main]\n ++ defaultCombatPhase\n ++ [main]\n ++ defaultEndingPhase\n\nstructure GameSetting where\n joinedPlayers: Std.AssocList Player Bool\n nextplayer: NextPlayerType\ndef GameSetting.default: GameSetting := {\n joinedPlayers:= \n Std.AssocList.empty\n |> Std.AssocList.cons player₁ true\n |> Std.AssocList.cons player₂ true\n |> Std.AssocList.cons player₃ true\n |> Std.AssocList.cons player₄ true,\n nextplayer := NextPlayerType.default,\n }\ninstance : Inhabited GameSetting where\n default := GameSetting.default\nabbrev Zone := Std.HashSet Nat\nstructure PlayerState where\n hand: Zone\n deck: Zone\n --life: Int\n --graveyard: Zone\n --pool: Int\n passPriority: Bool\ndef PlayerState.default: PlayerState := {\n hand := Inhabited.default,\n deck := Inhabited.default,\n --life: Int\n --graveyard: Zone\n --pool: Int\n passPriority := false\n}\ninstance : Inhabited PlayerState where\n default := PlayerState.default \n\nstructure PlayerStateStore where\n p₁: PlayerState\n p₂: PlayerState\n p₃: PlayerState\n p₄: PlayerState\ndef PlayerStateStore.default: PlayerStateStore := {\n p₁:= PlayerState.default, \n p₂:= PlayerState.default,\n p₃:= PlayerState.default,\n p₄:= PlayerState.default,\n}\ninstance : Inhabited PlayerStateStore where\n default := PlayerStateStore.default\n\ndef UpdatePlayerStateStore (st: PlayerStateStore) (idx: Player) (ps: PlayerState): PlayerStateStore :=\n match idx with\n | player₁ => {st with p₁ := ps}\n | player₂ => {st with p₂ := ps}\n | player₃ => {st with p₃ := ps}\n | player₄ => {st with p₄ := ps}\ndef PlayerStateStore.getOp (self: PlayerStateStore) (idx: Player) : PlayerState :=\n match idx with\n | player₁ => self.p₁\n | player₂ => self.p₂\n | player₃ => self.p₃\n | player₄ => self.p₄\nnotation:100 st \"[ \" pl \" ↦ \" ps \" ]\" => UpdatePlayerStateStore st pl ps\n\ninductive PriorityOwner\n| none\n| player(p: Player)\n--deriving Inhabited\n--honto ha default wo none ni sinaito ikenai\ninstance : Inhabited PriorityOwner where\n default := PriorityOwner.player player₁\n\nstructure GameState where\n setting: GameSetting\n turnList: TurnList\n phaseList: PhaseList\n priority: PriorityOwner\n didEveryPlayerPassTheirPriority: Bool\n playerStates: PlayerStateStore\ndef GameState.default: GameState := {\n setting := Inhabited.default,\n turnList := [player₁],\n phaseList := defaultPhaseList,\n priority := Inhabited.default,\n didEveryPlayerPassTheirPriority := Inhabited.default,\n playerStates := Inhabited.default,\n}\n\ninstance : Inhabited GameState where\n default := GameState.default\n\ndef updatePriority (ps: PlayerStateStore) (pl: Player) (p: Bool) :=\n ps[pl ↦ {ps[pl] with passPriority := p}]\ndef updateEveryPriority (ps: PlayerStateStore) (p: Bool) :=\n let ps₁ := updatePriority ps player₁ p;\n let ps₂ := updatePriority ps₁ player₂ p;\n let ps₃ := updatePriority ps₂ player₃ p;\n updatePriority ps₃ player₄ p\n\ntheorem preservePlayerState : ∀s p p' b, p ≠ p' → (updatePriority s p b)[p'] = s[p'] := by {\n intro s p p' b neq;\n cases p;\n all_goals cases p';\n all_goals try contradiction;\n all_goals simp [PlayerStateStore.getOp, updatePriority, UpdatePlayerStateStore];\n}\n\n--#check @Exists\n--#check @Sigma\n\ninductive PriorityRel: GameState → GameState → Prop\n| passPriority: ∀(s: GameState) (p: Player),\n s.priority = PriorityOwner.player p ∧ s.playerStates[p].passPriority = false -- かつ ターン起因処理と誘発型能力を積み終わった\n → PriorityRel s\n {\n s with\n priority := PriorityOwner.player (s.setting.nextplayer.1 p),\n playerStates := updatePriority s.playerStates p true,\n } -- MEMO: koko motto iikannji ni sitai\n| transPriority: ∀s₁ s₂ s₃,\n PriorityRel s₁ s₂\n → PriorityRel s₂ s₃\n → PriorityRel s₁ s₃\n| everyPlayerPassTheirPriority: ∀(s: GameState) (p: Player) (tl: TurnList),\n s.priority = PriorityOwner.player p\n ∧ s.turnList = p :: tl\n ∧ (∀(p: Player),\n Std.AssocList.contains p s.setting.joinedPlayers\n ∧ Std.AssocList.find? p s.setting.joinedPlayers = some true\n ∧ s.playerStates[p].passPriority = true)\n → PriorityRel s\n {\n s with\n playerStates := updateEveryPriority s.playerStates false,\n didEveryPlayerPassTheirPriority := true,\n }\n-- その他の行動をできるようにする\n\ntheorem proofOfPassPriority: ∀s p,\ns.priority = (PriorityOwner.player p)\n∧ s.playerStates[p].passPriority = false\n→ ∃s', PriorityRel s s' \n∧ s' = {\n s with\n priority := PriorityOwner.player (s.setting.nextplayer.1 p),\n playerStates := updatePriority s.playerStates p true,\n } := by\n{\n intros s p h;\n let s' := {\n s with\n priority := PriorityOwner.player (s.setting.nextplayer.1 p),\n playerStates := updatePriority s.playerStates p true,\n };\n exists s';\n apply And.intro;\n exact (PriorityRel.passPriority s p h);\n rfl;\n}\n\ntheorem proofOfEveryPlayerPassTheirPriority: ∀s p tl,\ns.priority = PriorityOwner.player p\n∧ s.turnList = p :: tl\n∧ (∀(p: Player),\n Std.AssocList.contains p s.setting.joinedPlayers\n ∧ Std.AssocList.find? p s.setting.joinedPlayers = some true\n ∧ s.playerStates[p].passPriority = true)\n→ ∃s', PriorityRel s s'\n∧ s' = {\n s with\n playerStates := updateEveryPriority s.playerStates false,\n didEveryPlayerPassTheirPriority := true,\n} := by {\n intros s p tl h1;\n let s' := {\n s with\n playerStates := updateEveryPriority s.playerStates false,\n didEveryPlayerPassTheirPriority := true,\n };\n exists s';\n apply And.intro;\n exact PriorityRel.everyPlayerPassTheirPriority s p tl h1;\n rfl;\n}\n\ninductive ProgressPhaseRel: GameState → GameState → Prop\n| nextStep: ∀(s: GameState) (p: Phase) (next: PhaseList),\n s.phaseList = p::next ∧ s.didEveryPlayerPassTheirPriority = true\n → ProgressPhaseRel s {s with phaseList := next, didEveryPlayerPassTheirPriority := false}\n -- ターン起因処理と状況起因処理,誘発型能力の誘発をした状態にする\n| transStep: ∀s₁ s₂ s₃,\n ProgressPhaseRel s₁ s₂\n → ProgressPhaseRel s₂ s₃\n → ProgressPhaseRel s₁ s₃\n| priorityRel: ∀s₁ s₂ s₃,\n PriorityRel s₁ s₂\n → ProgressPhaseRel s₂ s₃\n → ProgressPhaseRel s₁ s₃\n\ninductive ProgressTurnRel: GameState → GameState → Prop\n| nextTurn:\n ∀ (s: GameState) (p: Player),\n s.turnList = [p] ∧ s.phaseList = []\n → ProgressTurnRel s {s with turnList := [s.setting.nextplayer.1 p], phaseList := defaultPhaseList}\n -- ターン起因処理と状況起因処理,誘発型能力の誘発をした状態にする.\n-- | untapStep\n-- アンタップ・ステップのターン起因処理関連はここで行わないといけない\n| extraTurn:\n ∀ (s: GameState) (p : Player) (next: TurnList),\n ¬ next = [] \n ∧ s.turnList = p::next ∧ s.phaseList = []\n → ProgressTurnRel s {s with turnList := next, phaseList := defaultPhaseList}\n| transTurn: ∀s₁ s₂ s₃,\n ProgressTurnRel s₁ s₂\n → ProgressTurnRel s₂ s₃\n → ProgressTurnRel s₁ s₃\n| phaseRel: ∀s₁ s₂ s₃,\n ProgressPhaseRel s₁ s₂\n → ProgressTurnRel s₂ s₃\n → ProgressTurnRel s₁ s₃\n\n--#print List\n\nexample : ProgressTurnRel GameState.default {GameState.default with turnList := [player₂]} := by {\n let s: GameState := GameState.default;\n have h0: s = GameState.default := rfl;\n have h1: s.turnList = [player₁] := rfl;\n have h2: s.priority = PriorityOwner.player player₁ := rfl;\n have h3: s.playerStates[player₁].passPriority = false := rfl;\n rw [h0] at *;\n have ⟨s1, ⟨h4, h5⟩⟩ := proofOfPassPriority s player₁ (And.intro h2 h3);\n\n}\n-/", "meta": {"author": "amamama", "repo": "fuzzy-octo-palm-tree", "sha": "12685c23ab4a5bcf3187fe87594a629dbb1d1288", "save_path": "github-repos/lean/amamama-fuzzy-octo-palm-tree", "path": "github-repos/lean/amamama-fuzzy-octo-palm-tree/fuzzy-octo-palm-tree-12685c23ab4a5bcf3187fe87594a629dbb1d1288/src/SimpleCardGame.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.40733340004593027, "lm_q2_score": 0.024798158078482894, "lm_q1q2_score": 0.01010111804498489}} {"text": "/-\nCopyright (c) 2020 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Leonardo de Moura\n-/\nimport Lean.Util.FindMVar\nimport Lean.Meta.SynthInstance\nimport Lean.Meta.CollectMVars\nimport Lean.Meta.Tactic.Util\n\nnamespace Lean.Meta\n/-- Controls which new mvars are turned in to goals by the `apply` tactic.\n- `nonDependentFirst` mvars that don't depend on other goals appear first in the goal list.\n- `nonDependentOnly` only mvars that don't depend on other goals are added to goal list.\n- `all` all unassigned mvars are added to the goal list.\n-/\ninductive ApplyNewGoals where\n | nonDependentFirst | nonDependentOnly | all\n\n/-- Configures the behaviour of the `apply` tactic. -/\nstructure ApplyConfig where\n newGoals := ApplyNewGoals.nonDependentFirst\n /--\n If `synthAssignedInstances` is `true`, then `apply` will synthesize instance implicit arguments\n even if they have assigned by `isDefEq`, and then check whether the synthesized value matches the\n one inferred. The `congr` tactic sets this flag to false.\n -/\n synthAssignedInstances := true\n /--\n If `approx := true`, then we turn on `isDefEq` approximations. That is, we use\n the `approxDefEq` combinator.\n -/\n approx : Bool := true\n\n/--\n Compute the number of expected arguments and whether the result type is of the form\n (?m ...) where ?m is an unassigned metavariable.\n-/\ndef getExpectedNumArgsAux (e : Expr) : MetaM (Nat × Bool) :=\n withDefault <| forallTelescopeReducing e fun xs body =>\n pure (xs.size, body.getAppFn.isMVar)\n\ndef getExpectedNumArgs (e : Expr) : MetaM Nat := do\n let (numArgs, _) ← getExpectedNumArgsAux e\n pure numArgs\n\nprivate def throwApplyError {α} (mvarId : MVarId) (eType : Expr) (targetType : Expr) : MetaM α :=\n throwTacticEx `apply mvarId m!\"failed to unify{indentExpr eType}\\nwith{indentExpr targetType}\"\n\ndef synthAppInstances (tacticName : Name) (mvarId : MVarId) (newMVars : Array Expr) (binderInfos : Array BinderInfo) (synthAssignedInstances : Bool) : MetaM Unit :=\n newMVars.size.forM fun i => do\n if binderInfos[i]!.isInstImplicit then\n let mvar := newMVars[i]!\n if synthAssignedInstances || !(← mvar.mvarId!.isAssigned) then\n let mvarType ← inferType mvar\n let mvarVal ← synthInstance mvarType\n unless (← isDefEq mvar mvarVal) do\n throwTacticEx tacticName mvarId \"failed to assign synthesized instance\"\n\ndef appendParentTag (mvarId : MVarId) (newMVars : Array Expr) (binderInfos : Array BinderInfo) : MetaM Unit := do\n let parentTag ← mvarId.getTag\n if newMVars.size == 1 then\n -- if there is only one subgoal, we inherit the parent tag\n newMVars[0]!.mvarId!.setTag parentTag\n else\n unless parentTag.isAnonymous do\n newMVars.size.forM fun i => do\n let mvarIdNew := newMVars[i]!.mvarId!\n unless (← mvarIdNew.isAssigned) do\n unless binderInfos[i]!.isInstImplicit do\n let currTag ← mvarIdNew.getTag\n mvarIdNew.setTag (appendTag parentTag currTag)\n\n/--\nIf `synthAssignedInstances` is `true`, then `apply` will synthesize instance implicit arguments\neven if they have assigned by `isDefEq`, and then check whether the synthesized value matches the\none inferred. The `congr` tactic sets this flag to false.\n-/\ndef postprocessAppMVars (tacticName : Name) (mvarId : MVarId) (newMVars : Array Expr) (binderInfos : Array BinderInfo) (synthAssignedInstances := true) : MetaM Unit := do\n synthAppInstances tacticName mvarId newMVars binderInfos synthAssignedInstances\n -- TODO: default and auto params\n appendParentTag mvarId newMVars binderInfos\n\nprivate def dependsOnOthers (mvar : Expr) (otherMVars : Array Expr) : MetaM Bool :=\n otherMVars.anyM fun otherMVar => do\n if mvar == otherMVar then\n return false\n else\n let otherMVarType ← inferType otherMVar\n return (otherMVarType.findMVar? fun mvarId => mvarId == mvar.mvarId!).isSome\n\n/-- Partitions the given mvars in to two arrays (non-deps, deps)\naccording to whether the given mvar depends on other mvars in the array.-/\nprivate def partitionDependentMVars (mvars : Array Expr) : MetaM (Array MVarId × Array MVarId) :=\n mvars.foldlM (init := (#[], #[])) fun (nonDeps, deps) mvar => do\n let currMVarId := mvar.mvarId!\n if (← dependsOnOthers mvar mvars) then\n return (nonDeps, deps.push currMVarId)\n else\n return (nonDeps.push currMVarId, deps)\n\nprivate def reorderGoals (mvars : Array Expr) : ApplyNewGoals → MetaM (List MVarId)\n | ApplyNewGoals.nonDependentFirst => do\n let (nonDeps, deps) ← partitionDependentMVars mvars\n return nonDeps.toList ++ deps.toList\n | ApplyNewGoals.nonDependentOnly => do\n let (nonDeps, _) ← partitionDependentMVars mvars\n return nonDeps.toList\n | ApplyNewGoals.all => return mvars.toList.map Lean.Expr.mvarId!\n\n/-- Custom `isDefEq` for the `apply` tactic -/\nprivate def isDefEqApply (cfg : ApplyConfig) (a b : Expr) : MetaM Bool := do\n if cfg.approx then\n approxDefEq <| isDefEqGuarded a b\n else\n isDefEqGuarded a b\n\n/--\nClose the given goal using `apply e`.\n-/\ndef _root_.Lean.MVarId.apply (mvarId : MVarId) (e : Expr) (cfg : ApplyConfig := {}) : MetaM (List MVarId) :=\n mvarId.withContext do\n mvarId.checkNotAssigned `apply\n let targetType ← mvarId.getType\n let eType ← inferType e\n let (numArgs, hasMVarHead) ← getExpectedNumArgsAux eType\n /-\n The `apply` tactic adds `_`s to `e`, and some of these `_`s become new goals.\n When `hasMVarHead` is `false` we try different numbers, until we find a type compatible with `targetType`.\n We used to try only `numArgs-targetTypeNumArgs` when `hasMVarHead = false`, but this is not always correct.\n For example, consider the following example\n ```\n example {α β} [LE_trans β] (x y z : α → β) (h₀ : x ≤ y) (h₁ : y ≤ z) : x ≤ z := by\n apply le_trans\n assumption\n assumption\n ```\n In this example, `targetTypeNumArgs = 1` because `LE` for functions is defined as\n ```\n instance {α : Type u} {β : Type v} [LE β] : LE (α → β) where\n le f g := ∀ i, f i ≤ g i\n ```\n -/\n let rangeNumArgs ← if hasMVarHead then\n pure [numArgs : numArgs+1]\n else\n let targetTypeNumArgs ← getExpectedNumArgs targetType\n pure [numArgs - targetTypeNumArgs : numArgs+1]\n /-\n Auxiliary function for trying to add `n` underscores where `n ∈ [i: rangeNumArgs.stop)`\n See comment above\n -/\n let rec go (i : Nat) : MetaM (Array Expr × Array BinderInfo) := do\n if i < rangeNumArgs.stop then\n let s ← saveState\n let (newMVars, binderInfos, eType) ← forallMetaTelescopeReducing eType i\n if (← isDefEqApply cfg eType targetType) then\n return (newMVars, binderInfos)\n else\n s.restore\n go (i+1)\n else\n let (_, _, eType) ← forallMetaTelescopeReducing eType (some rangeNumArgs.start)\n throwApplyError mvarId eType targetType\n let (newMVars, binderInfos) ← go rangeNumArgs.start\n postprocessAppMVars `apply mvarId newMVars binderInfos cfg.synthAssignedInstances\n let e ← instantiateMVars e\n mvarId.assign (mkAppN e newMVars)\n let newMVars ← newMVars.filterM fun mvar => not <$> mvar.mvarId!.isAssigned\n let otherMVarIds ← getMVarsNoDelayed e\n let newMVarIds ← reorderGoals newMVars cfg.newGoals\n let otherMVarIds := otherMVarIds.filter fun mvarId => !newMVarIds.contains mvarId\n let result := newMVarIds ++ otherMVarIds.toList\n result.forM (·.headBetaType)\n return result\ntermination_by go i => rangeNumArgs.stop - i\n\n@[deprecated MVarId.apply]\ndef apply (mvarId : MVarId) (e : Expr) (cfg : ApplyConfig := {}) : MetaM (List MVarId) :=\n mvarId.apply e cfg\n\npartial def splitAndCore (mvarId : MVarId) : MetaM (List MVarId) :=\n mvarId.withContext do\n mvarId.checkNotAssigned `splitAnd\n let type ← mvarId.getType'\n if !type.isAppOfArity ``And 2 then\n return [mvarId]\n else\n let tag ← mvarId.getTag\n let rec go (type : Expr) : StateRefT (Array MVarId) MetaM Expr := do\n let type ← whnf type\n if type.isAppOfArity ``And 2 then\n let p₁ := type.appFn!.appArg!\n let p₂ := type.appArg!\n return mkApp4 (mkConst ``And.intro) p₁ p₂ (← go p₁) (← go p₂)\n else\n let idx := (← get).size + 1\n let mvar ← mkFreshExprSyntheticOpaqueMVar type (tag ++ (`h).appendIndexAfter idx)\n modify fun s => s.push mvar.mvarId!\n return mvar\n let (val, s) ← go type |>.run #[]\n mvarId.assign val\n return s.toList\n\n/--\nApply `And.intro` as much as possible to goal `mvarId`.\n-/\nabbrev _root_.Lean.MVarId.splitAnd (mvarId : MVarId) : MetaM (List MVarId) :=\n splitAndCore mvarId\n\n@[deprecated MVarId.splitAnd]\ndef splitAnd (mvarId : MVarId) : MetaM (List MVarId) :=\n mvarId.splitAnd\n\ndef _root_.Lean.MVarId.exfalso (mvarId : MVarId) : MetaM MVarId :=\n mvarId.withContext do\n mvarId.checkNotAssigned `exfalso\n let target ← instantiateMVars (← mvarId.getType)\n let u ← getLevel target\n let mvarIdNew ← mkFreshExprSyntheticOpaqueMVar (mkConst ``False) (tag := (← mvarId.getTag))\n mvarId.assign (mkApp2 (mkConst ``False.elim [u]) target mvarIdNew)\n return mvarIdNew.mvarId!\n\nend Lean.Meta\n", "meta": {"author": "leanprover", "repo": "lean4", "sha": "742d053a97bdd109a41a921facd1cd6a55e89bc7", "save_path": "github-repos/lean/leanprover-lean4", "path": "github-repos/lean/leanprover-lean4/lean4-742d053a97bdd109a41a921facd1cd6a55e89bc7/src/Lean/Meta/Tactic/Apply.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.21206880435710534, "lm_q2_score": 0.04742587082142043, "lm_q1q2_score": 0.01005754772069316}} {"text": "/-\nFile: signature_recover_public_key_ec_mul_soundness.lean\n\nAutogenerated file.\n-/\nimport starkware.cairo.lean.semantics.soundness.hoare\nimport .signature_recover_public_key_code\nimport ..signature_recover_public_key_spec\nimport .signature_recover_public_key_ec_add_soundness\nimport .signature_recover_public_key_ec_mul_inner_soundness\nopen tactic\n\nopen starkware.cairo.common.cairo_secp.ec\nopen starkware.cairo.common.cairo_secp.bigint\nopen starkware.cairo.common.cairo_secp.field\n\nvariables {F : Type} [field F] [decidable_eq F] [prelude_hyps F]\nvariable mem : F → F\nvariable σ : register_state F\n\n/- starkware.cairo.common.cairo_secp.ec.ec_mul autogenerated soundness theorem -/\n\ntheorem auto_sound_ec_mul\n -- arguments\n (range_check_ptr : F) (point : EcPoint F) (scalar : BigInt3 F)\n -- code is in memory at σ.pc\n (h_mem : mem_at mem code_ec_mul σ.pc)\n -- all dependencies are in memory\n (h_mem_4 : mem_at mem code_nondet_bigint3 (σ.pc - 561))\n (h_mem_5 : mem_at mem code_unreduced_mul (σ.pc - 549))\n (h_mem_6 : mem_at mem code_unreduced_sqr (σ.pc - 529))\n (h_mem_7 : mem_at mem code_verify_zero (σ.pc - 513))\n (h_mem_8 : mem_at mem code_is_zero (σ.pc - 490))\n (h_mem_12 : mem_at mem code_compute_doubling_slope (σ.pc - 385))\n (h_mem_13 : mem_at mem code_compute_slope (σ.pc - 341))\n (h_mem_14 : mem_at mem code_ec_double (σ.pc - 317))\n (h_mem_15 : mem_at mem code_fast_ec_add (σ.pc - 244))\n (h_mem_16 : mem_at mem code_ec_add (σ.pc - 157))\n (h_mem_17 : mem_at mem code_ec_mul_inner (σ.pc - 101))\n -- input arguments on the stack\n (hin_range_check_ptr : range_check_ptr = mem (σ.fp - 12))\n (hin_point : point = cast_EcPoint mem (σ.fp - 11))\n (hin_scalar : scalar = cast_BigInt3 mem (σ.fp - 5))\n -- conclusion\n : ensures_ret mem σ (λ κ τ,\n ∃ μ ≤ κ, rc_ensures mem (rc_bound F) μ (mem (σ.fp - 12)) (mem $ τ.ap - 7)\n (spec_ec_mul mem κ range_check_ptr point scalar (mem (τ.ap - 7)) (cast_EcPoint mem (τ.ap - 6)))) :=\nbegin\n apply ensures_of_ensuresb, intro νbound,\n have h_mem_rec := h_mem,\n unpack_memory code_ec_mul at h_mem with ⟨hpc0, hpc1, hpc2, hpc3, hpc4, hpc5, hpc6, hpc7, hpc8, hpc9, hpc10, hpc11, hpc12, hpc13, hpc14, hpc15, hpc16, hpc17, hpc18, hpc19, hpc20, hpc21, hpc22, hpc23, hpc24, hpc25, hpc26, hpc27, hpc28, hpc29, hpc30, hpc31, hpc32, hpc33, hpc34, hpc35, hpc36, hpc37, hpc38, hpc39, hpc40, hpc41, hpc42, hpc43, hpc44, hpc45, hpc46, hpc47, hpc48, hpc49, hpc50, hpc51, hpc52, hpc53, hpc54, hpc55, hpc56, hpc57, hpc58, hpc59, hpc60, hpc61, hpc62, hpc63, hpc64, hpc65, hpc66, hpc67, hpc68, hpc69, hpc70, hpc71, hpc72, hpc73, hpc74, hpc75, hpc76, hpc77, hpc78, hpc79⟩,\n -- ap += 18\n step_advance_ap hpc0 hpc1,\n -- function call\n step_assert_eq hpc2 with arg0,\n step_assert_eq hpc3 with arg1,\n step_assert_eq hpc4 with arg2,\n step_assert_eq hpc5 with arg3,\n step_assert_eq hpc6 with arg4,\n step_assert_eq hpc7 with arg5,\n step_assert_eq hpc8 with arg6,\n step_assert_eq hpc9 with arg7,\n step_assert_eq hpc10 hpc11 with arg8,\n step_sub hpc12 (auto_sound_ec_mul_inner mem _ range_check_ptr point scalar.d0 86 _ _ _ _ _ _ _ _ _ _ _ _ _),\n { rw hpc13, norm_num2, exact h_mem_17 },\n { rw hpc13, norm_num2, exact h_mem_4 },\n { rw hpc13, norm_num2, exact h_mem_5 },\n { rw hpc13, norm_num2, exact h_mem_6 },\n { rw hpc13, norm_num2, exact h_mem_7 },\n { rw hpc13, norm_num2, exact h_mem_12 },\n { rw hpc13, norm_num2, exact h_mem_13 },\n { rw hpc13, norm_num2, exact h_mem_14 },\n { rw hpc13, norm_num2, exact h_mem_15 },\n { try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point, hin_scalar] },\n try { dsimp [cast_EcPoint, cast_BigInt3] },\n try { arith_simps }, try { simp only [arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } }, },\n { try { ext } ; {\n try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point, hin_scalar] },\n try { dsimp [cast_EcPoint, cast_BigInt3] },\n try { arith_simps }, try { simp only [arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },}, },\n { try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point, hin_scalar] },\n try { dsimp [cast_EcPoint, cast_BigInt3] },\n try { arith_simps }, try { simp only [arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } }, },\n { try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point, hin_scalar] },\n try { dsimp [cast_EcPoint, cast_BigInt3] },\n try { arith_simps }, try { simp only [arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } }, },\n intros κ_call14 ap14 h_call14,\n rcases h_call14 with ⟨rc_m14, rc_mle14, hl_range_check_ptr₁, h_call14⟩,\n generalize' hr_rev_range_check_ptr₁: mem (ap14 - 13) = range_check_ptr₁,\n have htv_range_check_ptr₁ := hr_rev_range_check_ptr₁.symm, clear hr_rev_range_check_ptr₁,\n generalize' hr_rev_pow2_0: cast_EcPoint mem (ap14 - 12) = pow2_0,\n simp only [hr_rev_pow2_0] at h_call14,\n have htv_pow2_0 := hr_rev_pow2_0.symm, clear hr_rev_pow2_0,\n generalize' hr_rev_res0: cast_EcPoint mem (ap14 - 6) = res0,\n simp only [hr_rev_res0] at h_call14,\n have htv_res0 := hr_rev_res0.symm, clear hr_rev_res0,\n try { simp only [arg0 ,arg1 ,arg2 ,arg3 ,arg4 ,arg5 ,arg6 ,arg7 ,arg8] at hl_range_check_ptr₁ },\n rw [←htv_range_check_ptr₁, ←hin_range_check_ptr] at hl_range_check_ptr₁,\n try { simp only [arg0 ,arg1 ,arg2 ,arg3 ,arg4 ,arg5 ,arg6 ,arg7 ,arg8] at h_call14 },\n rw [hin_range_check_ptr] at h_call14,\n clear arg0 arg1 arg2 arg3 arg4 arg5 arg6 arg7 arg8,\n -- local var\n step_assert_eq hpc14 with temp0,\n step_assert_eq hpc15 with temp1,\n step_assert_eq hpc16 with temp2,\n step_assert_eq hpc17 with temp3,\n step_assert_eq hpc18 with temp4,\n step_assert_eq hpc19 with temp5,\n have lc_res0: res0 = cast_EcPoint mem σ.fp, {\n try { ext } ; {\n try { simp only [htv_res0] },\n try { dsimp [cast_EcPoint, cast_BigInt3] },\n try { arith_simps }, try { simp only [temp0, temp1, temp2, temp3, temp4, temp5] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },}, },\n clear temp0 temp1 temp2 temp3 temp4 temp5,\n -- function call\n step_assert_eq hpc20 with arg0,\n step_assert_eq hpc21 with arg1,\n step_assert_eq hpc22 with arg2,\n step_assert_eq hpc23 with arg3,\n step_assert_eq hpc24 with arg4,\n step_assert_eq hpc25 with arg5,\n step_assert_eq hpc26 with arg6,\n step_assert_eq hpc27 with arg7,\n step_assert_eq hpc28 hpc29 with arg8,\n step_sub hpc30 (auto_sound_ec_mul_inner mem _ range_check_ptr₁ pow2_0 scalar.d1 86 _ _ _ _ _ _ _ _ _ _ _ _ _),\n { rw hpc31, norm_num2, exact h_mem_17 },\n { rw hpc31, norm_num2, exact h_mem_4 },\n { rw hpc31, norm_num2, exact h_mem_5 },\n { rw hpc31, norm_num2, exact h_mem_6 },\n { rw hpc31, norm_num2, exact h_mem_7 },\n { rw hpc31, norm_num2, exact h_mem_12 },\n { rw hpc31, norm_num2, exact h_mem_13 },\n { rw hpc31, norm_num2, exact h_mem_14 },\n { rw hpc31, norm_num2, exact h_mem_15 },\n { try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point, hin_scalar, htv_range_check_ptr₁, htv_pow2_0, htv_res0, lc_res0] },\n try { dsimp [cast_EcPoint, cast_BigInt3] },\n try { arith_simps }, try { simp only [arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } }, },\n { try { ext } ; {\n try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point, hin_scalar, htv_range_check_ptr₁, htv_pow2_0, htv_res0, lc_res0] },\n try { dsimp [cast_EcPoint, cast_BigInt3] },\n try { arith_simps }, try { simp only [arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },}, },\n { try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point, hin_scalar, htv_range_check_ptr₁, htv_pow2_0, htv_res0, lc_res0] },\n try { dsimp [cast_EcPoint, cast_BigInt3] },\n try { arith_simps }, try { simp only [arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } }, },\n { try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point, hin_scalar, htv_range_check_ptr₁, htv_pow2_0, htv_res0, lc_res0] },\n try { dsimp [cast_EcPoint, cast_BigInt3] },\n try { arith_simps }, try { simp only [arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } }, },\n intros κ_call32 ap32 h_call32,\n rcases h_call32 with ⟨rc_m32, rc_mle32, hl_range_check_ptr₂, h_call32⟩,\n generalize' hr_rev_range_check_ptr₂: mem (ap32 - 13) = range_check_ptr₂,\n have htv_range_check_ptr₂ := hr_rev_range_check_ptr₂.symm, clear hr_rev_range_check_ptr₂,\n generalize' hr_rev_pow2_1: cast_EcPoint mem (ap32 - 12) = pow2_1,\n simp only [hr_rev_pow2_1] at h_call32,\n have htv_pow2_1 := hr_rev_pow2_1.symm, clear hr_rev_pow2_1,\n generalize' hr_rev_res1: cast_EcPoint mem (ap32 - 6) = res1,\n simp only [hr_rev_res1] at h_call32,\n have htv_res1 := hr_rev_res1.symm, clear hr_rev_res1,\n try { simp only [arg0 ,arg1 ,arg2 ,arg3 ,arg4 ,arg5 ,arg6 ,arg7 ,arg8] at hl_range_check_ptr₂ },\n rw [←htv_range_check_ptr₂, ←htv_range_check_ptr₁] at hl_range_check_ptr₂,\n try { simp only [arg0 ,arg1 ,arg2 ,arg3 ,arg4 ,arg5 ,arg6 ,arg7 ,arg8] at h_call32 },\n rw [←htv_range_check_ptr₁, hl_range_check_ptr₁, hin_range_check_ptr] at h_call32,\n clear arg0 arg1 arg2 arg3 arg4 arg5 arg6 arg7 arg8,\n -- local var\n step_assert_eq hpc32 with temp0,\n step_assert_eq hpc33 with temp1,\n step_assert_eq hpc34 with temp2,\n step_assert_eq hpc35 with temp3,\n step_assert_eq hpc36 with temp4,\n step_assert_eq hpc37 with temp5,\n have lc_res1: res1 = cast_EcPoint mem (σ.fp + 6), {\n try { ext } ; {\n try { simp only [htv_res1] },\n try { dsimp [cast_EcPoint, cast_BigInt3] },\n try { arith_simps }, try { simp only [temp0, temp1, temp2, temp3, temp4, temp5] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },}, },\n clear temp0 temp1 temp2 temp3 temp4 temp5,\n -- function call\n step_assert_eq hpc38 with arg0,\n step_assert_eq hpc39 with arg1,\n step_assert_eq hpc40 with arg2,\n step_assert_eq hpc41 with arg3,\n step_assert_eq hpc42 with arg4,\n step_assert_eq hpc43 with arg5,\n step_assert_eq hpc44 with arg6,\n step_assert_eq hpc45 with arg7,\n step_assert_eq hpc46 hpc47 with arg8,\n step_sub hpc48 (auto_sound_ec_mul_inner mem _ range_check_ptr₂ pow2_1 scalar.d2 84 _ _ _ _ _ _ _ _ _ _ _ _ _),\n { rw hpc49, norm_num2, exact h_mem_17 },\n { rw hpc49, norm_num2, exact h_mem_4 },\n { rw hpc49, norm_num2, exact h_mem_5 },\n { rw hpc49, norm_num2, exact h_mem_6 },\n { rw hpc49, norm_num2, exact h_mem_7 },\n { rw hpc49, norm_num2, exact h_mem_12 },\n { rw hpc49, norm_num2, exact h_mem_13 },\n { rw hpc49, norm_num2, exact h_mem_14 },\n { rw hpc49, norm_num2, exact h_mem_15 },\n { try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point, hin_scalar, htv_range_check_ptr₁, htv_pow2_0, htv_res0, lc_res0, htv_range_check_ptr₂, htv_pow2_1, htv_res1, lc_res1] },\n try { dsimp [cast_EcPoint, cast_BigInt3] },\n try { arith_simps }, try { simp only [arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } }, },\n { try { ext } ; {\n try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point, hin_scalar, htv_range_check_ptr₁, htv_pow2_0, htv_res0, lc_res0, htv_range_check_ptr₂, htv_pow2_1, htv_res1, lc_res1] },\n try { dsimp [cast_EcPoint, cast_BigInt3] },\n try { arith_simps }, try { simp only [arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },}, },\n { try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point, hin_scalar, htv_range_check_ptr₁, htv_pow2_0, htv_res0, lc_res0, htv_range_check_ptr₂, htv_pow2_1, htv_res1, lc_res1] },\n try { dsimp [cast_EcPoint, cast_BigInt3] },\n try { arith_simps }, try { simp only [arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } }, },\n { try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point, hin_scalar, htv_range_check_ptr₁, htv_pow2_0, htv_res0, lc_res0, htv_range_check_ptr₂, htv_pow2_1, htv_res1, lc_res1] },\n try { dsimp [cast_EcPoint, cast_BigInt3] },\n try { arith_simps }, try { simp only [arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } }, },\n intros κ_call50 ap50 h_call50,\n rcases h_call50 with ⟨rc_m50, rc_mle50, hl_range_check_ptr₃, h_call50⟩,\n generalize' hr_rev_range_check_ptr₃: mem (ap50 - 13) = range_check_ptr₃,\n have htv_range_check_ptr₃ := hr_rev_range_check_ptr₃.symm, clear hr_rev_range_check_ptr₃,\n generalize' hr_rev_res2: cast_EcPoint mem (ap50 - 6) = res2,\n simp only [hr_rev_res2] at h_call50,\n have htv_res2 := hr_rev_res2.symm, clear hr_rev_res2,\n try { simp only [arg0 ,arg1 ,arg2 ,arg3 ,arg4 ,arg5 ,arg6 ,arg7 ,arg8] at hl_range_check_ptr₃ },\n rw [←htv_range_check_ptr₃, ←htv_range_check_ptr₂] at hl_range_check_ptr₃,\n try { simp only [arg0 ,arg1 ,arg2 ,arg3 ,arg4 ,arg5 ,arg6 ,arg7 ,arg8] at h_call50 },\n rw [←htv_range_check_ptr₂, hl_range_check_ptr₂, hl_range_check_ptr₁, hin_range_check_ptr] at h_call50,\n clear arg0 arg1 arg2 arg3 arg4 arg5 arg6 arg7 arg8,\n -- local var\n step_assert_eq hpc50 with temp0,\n step_assert_eq hpc51 with temp1,\n step_assert_eq hpc52 with temp2,\n step_assert_eq hpc53 with temp3,\n step_assert_eq hpc54 with temp4,\n step_assert_eq hpc55 with temp5,\n have lc_res2: res2 = cast_EcPoint mem (σ.fp + 12), {\n try { ext } ; {\n try { simp only [htv_res2] },\n try { dsimp [cast_EcPoint, cast_BigInt3] },\n try { arith_simps }, try { simp only [temp0, temp1, temp2, temp3, temp4, temp5] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },}, },\n clear temp0 temp1 temp2 temp3 temp4 temp5,\n -- function call\n step_assert_eq hpc56 with arg0,\n step_assert_eq hpc57 with arg1,\n step_assert_eq hpc58 with arg2,\n step_assert_eq hpc59 with arg3,\n step_assert_eq hpc60 with arg4,\n step_assert_eq hpc61 with arg5,\n step_assert_eq hpc62 with arg6,\n step_assert_eq hpc63 with arg7,\n step_assert_eq hpc64 with arg8,\n step_assert_eq hpc65 with arg9,\n step_assert_eq hpc66 with arg10,\n step_assert_eq hpc67 with arg11,\n step_assert_eq hpc68 with arg12,\n step_sub hpc69 (auto_sound_ec_add mem _ range_check_ptr₃ res0 res1 _ _ _ _ _ _ _ _ _ _ _ _ _),\n { rw hpc70, norm_num2, exact h_mem_16 },\n { rw hpc70, norm_num2, exact h_mem_4 },\n { rw hpc70, norm_num2, exact h_mem_5 },\n { rw hpc70, norm_num2, exact h_mem_6 },\n { rw hpc70, norm_num2, exact h_mem_7 },\n { rw hpc70, norm_num2, exact h_mem_8 },\n { rw hpc70, norm_num2, exact h_mem_12 },\n { rw hpc70, norm_num2, exact h_mem_13 },\n { rw hpc70, norm_num2, exact h_mem_14 },\n { rw hpc70, norm_num2, exact h_mem_15 },\n { try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point, hin_scalar, htv_range_check_ptr₁, htv_pow2_0, htv_res0, lc_res0, htv_range_check_ptr₂, htv_pow2_1, htv_res1, lc_res1, htv_range_check_ptr₃, htv_res2, lc_res2] },\n try { dsimp [cast_EcPoint, cast_BigInt3] },\n try { arith_simps }, try { simp only [arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } }, },\n { try { ext } ; {\n try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point, hin_scalar, htv_range_check_ptr₁, htv_pow2_0, htv_res0, lc_res0, htv_range_check_ptr₂, htv_pow2_1, htv_res1, lc_res1, htv_range_check_ptr₃, htv_res2, lc_res2] },\n try { dsimp [cast_EcPoint, cast_BigInt3] },\n try { arith_simps }, try { simp only [arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },}, },\n { try { ext } ; {\n try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point, hin_scalar, htv_range_check_ptr₁, htv_pow2_0, htv_res0, lc_res0, htv_range_check_ptr₂, htv_pow2_1, htv_res1, lc_res1, htv_range_check_ptr₃, htv_res2, lc_res2] },\n try { dsimp [cast_EcPoint, cast_BigInt3] },\n try { arith_simps }, try { simp only [arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },}, },\n intros κ_call71 ap71 h_call71,\n rcases h_call71 with ⟨rc_m71, rc_mle71, hl_range_check_ptr₄, h_call71⟩,\n generalize' hr_rev_range_check_ptr₄: mem (ap71 - 7) = range_check_ptr₄,\n have htv_range_check_ptr₄ := hr_rev_range_check_ptr₄.symm, clear hr_rev_range_check_ptr₄,\n generalize' hr_rev_res: cast_EcPoint mem (ap71 - 6) = res,\n simp only [hr_rev_res] at h_call71,\n have htv_res := hr_rev_res.symm, clear hr_rev_res,\n try { simp only [arg0 ,arg1 ,arg2 ,arg3 ,arg4 ,arg5 ,arg6 ,arg7 ,arg8 ,arg9 ,arg10 ,arg11 ,arg12] at hl_range_check_ptr₄ },\n rw [←htv_range_check_ptr₄, ←htv_range_check_ptr₃] at hl_range_check_ptr₄,\n try { simp only [arg0 ,arg1 ,arg2 ,arg3 ,arg4 ,arg5 ,arg6 ,arg7 ,arg8 ,arg9 ,arg10 ,arg11 ,arg12] at h_call71 },\n rw [←htv_range_check_ptr₃, hl_range_check_ptr₃, hl_range_check_ptr₂, hl_range_check_ptr₁, hin_range_check_ptr] at h_call71,\n clear arg0 arg1 arg2 arg3 arg4 arg5 arg6 arg7 arg8 arg9 arg10 arg11 arg12,\n -- function call\n step_assert_eq hpc71 with arg0,\n step_assert_eq hpc72 with arg1,\n step_assert_eq hpc73 with arg2,\n step_assert_eq hpc74 with arg3,\n step_assert_eq hpc75 with arg4,\n step_assert_eq hpc76 with arg5,\n step_sub hpc77 (auto_sound_ec_add mem _ range_check_ptr₄ res res2 _ _ _ _ _ _ _ _ _ _ _ _ _),\n { rw hpc78, norm_num2, exact h_mem_16 },\n { rw hpc78, norm_num2, exact h_mem_4 },\n { rw hpc78, norm_num2, exact h_mem_5 },\n { rw hpc78, norm_num2, exact h_mem_6 },\n { rw hpc78, norm_num2, exact h_mem_7 },\n { rw hpc78, norm_num2, exact h_mem_8 },\n { rw hpc78, norm_num2, exact h_mem_12 },\n { rw hpc78, norm_num2, exact h_mem_13 },\n { rw hpc78, norm_num2, exact h_mem_14 },\n { rw hpc78, norm_num2, exact h_mem_15 },\n { try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point, hin_scalar, htv_range_check_ptr₁, htv_pow2_0, htv_res0, lc_res0, htv_range_check_ptr₂, htv_pow2_1, htv_res1, lc_res1, htv_range_check_ptr₃, htv_res2, lc_res2, htv_range_check_ptr₄, htv_res] },\n try { dsimp [cast_EcPoint, cast_BigInt3] },\n try { arith_simps }, try { simp only [arg0, arg1, arg2, arg3, arg4, arg5] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } }, },\n { try { ext } ; {\n try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point, hin_scalar, htv_range_check_ptr₁, htv_pow2_0, htv_res0, lc_res0, htv_range_check_ptr₂, htv_pow2_1, htv_res1, lc_res1, htv_range_check_ptr₃, htv_res2, lc_res2, htv_range_check_ptr₄, htv_res] },\n try { dsimp [cast_EcPoint, cast_BigInt3] },\n try { arith_simps }, try { simp only [arg0, arg1, arg2, arg3, arg4, arg5] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },}, },\n { try { ext } ; {\n try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point, hin_scalar, htv_range_check_ptr₁, htv_pow2_0, htv_res0, lc_res0, htv_range_check_ptr₂, htv_pow2_1, htv_res1, lc_res1, htv_range_check_ptr₃, htv_res2, lc_res2, htv_range_check_ptr₄, htv_res] },\n try { dsimp [cast_EcPoint, cast_BigInt3] },\n try { arith_simps }, try { simp only [arg0, arg1, arg2, arg3, arg4, arg5] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },}, },\n intros κ_call79 ap79 h_call79,\n rcases h_call79 with ⟨rc_m79, rc_mle79, hl_range_check_ptr₅, h_call79⟩,\n generalize' hr_rev_range_check_ptr₅: mem (ap79 - 7) = range_check_ptr₅,\n have htv_range_check_ptr₅ := hr_rev_range_check_ptr₅.symm, clear hr_rev_range_check_ptr₅,\n generalize' hr_rev_res₁: cast_EcPoint mem (ap79 - 6) = res₁,\n simp only [hr_rev_res₁] at h_call79,\n have htv_res₁ := hr_rev_res₁.symm, clear hr_rev_res₁,\n try { simp only [arg0 ,arg1 ,arg2 ,arg3 ,arg4 ,arg5] at hl_range_check_ptr₅ },\n rw [←htv_range_check_ptr₅, ←htv_range_check_ptr₄] at hl_range_check_ptr₅,\n try { simp only [arg0 ,arg1 ,arg2 ,arg3 ,arg4 ,arg5] at h_call79 },\n rw [←htv_range_check_ptr₄, hl_range_check_ptr₄, hl_range_check_ptr₃, hl_range_check_ptr₂, hl_range_check_ptr₁, hin_range_check_ptr] at h_call79,\n clear arg0 arg1 arg2 arg3 arg4 arg5,\n -- return\n step_ret hpc79,\n -- finish\n step_done, use_only [rfl, rfl],\n -- range check condition\n use_only (rc_m14+rc_m32+rc_m50+rc_m71+rc_m79+0+0), split,\n linarith [rc_mle14, rc_mle32, rc_mle50, rc_mle71, rc_mle79],\n split,\n { arith_simps,\n rw [←htv_range_check_ptr₅, hl_range_check_ptr₅, hl_range_check_ptr₄, hl_range_check_ptr₃, hl_range_check_ptr₂, hl_range_check_ptr₁, hin_range_check_ptr],\n try { arith_simps, refl <|> norm_cast }, try { refl } },\n intro rc_h_range_check_ptr, repeat { rw [add_assoc] at rc_h_range_check_ptr },\n have rc_h_range_check_ptr' := range_checked_add_right rc_h_range_check_ptr,\n -- Final Proof\n -- user-provided reduction\n suffices auto_spec: auto_spec_ec_mul mem _ range_check_ptr point scalar _ _,\n { apply sound_ec_mul, apply auto_spec },\n -- prove the auto generated assertion\n dsimp [auto_spec_ec_mul],\n try { norm_num1 }, try { arith_simps },\n use_only [κ_call14],\n use_only [range_check_ptr₁],\n use_only [pow2_0],\n use_only [res0],\n have rc_h_range_check_ptr₁ := range_checked_offset' rc_h_range_check_ptr,\n have rc_h_range_check_ptr₁' := range_checked_add_right rc_h_range_check_ptr₁, try { norm_cast at rc_h_range_check_ptr₁' },\n have spec14 := h_call14 rc_h_range_check_ptr',\n rw [←hin_range_check_ptr, ←htv_range_check_ptr₁] at spec14,\n try { dsimp at spec14, arith_simps at spec14 },\n use_only [spec14],\n use_only [κ_call32],\n use_only [range_check_ptr₂],\n use_only [pow2_1],\n use_only [res1],\n have rc_h_range_check_ptr₂ := range_checked_offset' rc_h_range_check_ptr₁,\n have rc_h_range_check_ptr₂' := range_checked_add_right rc_h_range_check_ptr₂, try { norm_cast at rc_h_range_check_ptr₂' },\n have spec32 := h_call32 rc_h_range_check_ptr₁',\n rw [←hin_range_check_ptr, ←hl_range_check_ptr₁, ←htv_range_check_ptr₂] at spec32,\n try { dsimp at spec32, arith_simps at spec32 },\n use_only [spec32],\n use_only [κ_call50],\n use_only [range_check_ptr₃],\n use_only [(cast_EcPoint mem (ap50 - 12))],\n use_only [res2],\n have rc_h_range_check_ptr₃ := range_checked_offset' rc_h_range_check_ptr₂,\n have rc_h_range_check_ptr₃' := range_checked_add_right rc_h_range_check_ptr₃, try { norm_cast at rc_h_range_check_ptr₃' },\n have spec50 := h_call50 rc_h_range_check_ptr₂',\n rw [←hin_range_check_ptr, ←hl_range_check_ptr₁, ←hl_range_check_ptr₂, ←htv_range_check_ptr₃] at spec50,\n try { dsimp at spec50, arith_simps at spec50 },\n use_only [spec50],\n use_only [κ_call71],\n use_only [range_check_ptr₄],\n use_only [res],\n have rc_h_range_check_ptr₄ := range_checked_offset' rc_h_range_check_ptr₃,\n have rc_h_range_check_ptr₄' := range_checked_add_right rc_h_range_check_ptr₄, try { norm_cast at rc_h_range_check_ptr₄' },\n have spec71 := h_call71 rc_h_range_check_ptr₃',\n rw [←hin_range_check_ptr, ←hl_range_check_ptr₁, ←hl_range_check_ptr₂, ←hl_range_check_ptr₃, ←htv_range_check_ptr₄] at spec71,\n try { dsimp at spec71, arith_simps at spec71 },\n use_only [spec71],\n use_only [κ_call79],\n use_only [range_check_ptr₅],\n use_only [res₁],\n have rc_h_range_check_ptr₅ := range_checked_offset' rc_h_range_check_ptr₄,\n have rc_h_range_check_ptr₅' := range_checked_add_right rc_h_range_check_ptr₅, try { norm_cast at rc_h_range_check_ptr₅' },\n have spec79 := h_call79 rc_h_range_check_ptr₄',\n rw [←hin_range_check_ptr, ←hl_range_check_ptr₁, ←hl_range_check_ptr₂, ←hl_range_check_ptr₃, ←hl_range_check_ptr₄, ←htv_range_check_ptr₅] at spec79,\n try { dsimp at spec79, arith_simps at spec79 },\n use_only [spec79],\n try { split, linarith },\n try { ensures_simps; try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point, hin_scalar, htv_range_check_ptr₁, htv_pow2_0, htv_res0, lc_res0, htv_range_check_ptr₂, htv_pow2_1, htv_res1, lc_res1, htv_range_check_ptr₃, htv_res2, lc_res2, htv_range_check_ptr₄, htv_res, htv_range_check_ptr₅, htv_res₁] }, },\n try { dsimp [cast_EcPoint, cast_BigInt3] },\n try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },\nend\n\n", "meta": {"author": "starkware-libs", "repo": "formal-proofs", "sha": "35613c65b6715601bbc0a550d52754f8e7d93e30", "save_path": "github-repos/lean/starkware-libs-formal-proofs", "path": "github-repos/lean/starkware-libs-formal-proofs/formal-proofs-35613c65b6715601bbc0a550d52754f8e7d93e30/src/starkware/cairo/common/cairo_secp/verification/verification/signature_recover_public_key_ec_mul_soundness.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.43014734858584286, "lm_q2_score": 0.02333077084574743, "lm_q1q2_score": 0.01003566921976214}} {"text": "import sheaves.sheaf_of_rings Kenny.sheaf_on_opens ring_theory.subring\n\nuniverses v w u₁ v₁ u\n\nopen topological_space lattice\n\ndef sheaf_of_rings_on_opens (X : Type u) [topological_space X] (U : opens X) : Type (max u (v+1)) :=\nsheaf_of_rings.{u v} X\n\nnamespace sheaf_of_rings_on_opens\n\nvariables {X : Type u} [topological_space X] {U : opens X}\n\ndef to_sheaf_on_opens (F : sheaf_of_rings_on_opens X U) : sheaf_on_opens X U :=\n{ locality := F.2,\n gluing := F.3,\n .. F.F }\n\n-- def eval (F : sheaf_of_rings_on_opens X U) : Π (V : opens X), V ≤ U → Type v :=\n-- F.to_sheaf_on_opens.eval\n\ninstance comm_ring_eval (F : sheaf_of_rings_on_opens X U) (V HVU) : comm_ring (F.to_sheaf_on_opens.eval V HVU) :=\nF.1.2 V\n\n-- def res (F : sheaf_of_rings_on_opens X U) : Π (V : opens X) (HVU : V ≤ U) (W : opens X) (HWU : W ≤ U) (HWV : W ≤ V), F.to_sheaf_on_opens.eval V HVU → F.to_sheaf_on_opens.eval W HWU :=\n-- F.to_sheaf_on_opens.res\n\ninstance is_ring_hom_res (F : sheaf_of_rings_on_opens X U) (V HVU W HWU HWV) : is_ring_hom (F.to_sheaf_on_opens.res V HVU W HWU HWV) :=\nF.1.3 V W HWV\n\nsection\nvariables (F : sheaf_of_rings_on_opens X U) (V : opens X) (HVU : V ≤ U) (W : opens X) (HWU : W ≤ U) (HWV : W ≤ V)\nvariables (x y : F.to_sheaf_on_opens.eval V HVU) (n : ℕ)\n@[simp] lemma res_add : F.to_sheaf_on_opens.res V HVU W HWU HWV (x + y) = F.to_sheaf_on_opens.res V HVU W HWU HWV x + F.to_sheaf_on_opens.res V HVU W HWU HWV y := is_ring_hom.map_add _\n@[simp] lemma res_zero : F.to_sheaf_on_opens.res V HVU W HWU HWV 0 = 0 := is_ring_hom.map_zero _\n@[simp] lemma res_neg : F.to_sheaf_on_opens.res V HVU W HWU HWV (-x) = -F.to_sheaf_on_opens.res V HVU W HWU HWV x := is_ring_hom.map_neg _\n@[simp] lemma res_sub : F.to_sheaf_on_opens.res V HVU W HWU HWV (x - y) = F.to_sheaf_on_opens.res V HVU W HWU HWV x - F.to_sheaf_on_opens.res V HVU W HWU HWV y := is_ring_hom.map_sub _\n@[simp] lemma res_mul : F.to_sheaf_on_opens.res V HVU W HWU HWV (x * y) = F.to_sheaf_on_opens.res V HVU W HWU HWV x * F.to_sheaf_on_opens.res V HVU W HWU HWV y := is_ring_hom.map_mul _\n@[simp] lemma res_one : F.to_sheaf_on_opens.res V HVU W HWU HWV 1 = 1 := is_ring_hom.map_one _\n@[simp] lemma res_pow : F.to_sheaf_on_opens.res V HVU W HWU HWV (x^n) = (F.to_sheaf_on_opens.res V HVU W HWU HWV x)^n := is_semiring_hom.map_pow _ x n\nend\n\ntheorem res_self (F : sheaf_of_rings_on_opens X U) (V HVU HV x) :\n F.to_sheaf_on_opens.res V HVU V HVU HV x = x :=\nF.to_sheaf_on_opens.res_self V HVU HV x\n\ntheorem res_res (F : sheaf_of_rings_on_opens X U) (V HVU W HWU HWV S HSU HSW x) :\n F.to_sheaf_on_opens.res W HWU S HSU HSW (F.to_sheaf_on_opens.res V HVU W HWU HWV x) = F.to_sheaf_on_opens.res V HVU S HSU (le_trans HSW HWV) x :=\nF.to_sheaf_on_opens.res_res V HVU W HWU HWV S HSU HSW x\n\ntheorem locality (F : sheaf_of_rings_on_opens X U) (V HVU s t) (OC : covering V)\n (H : ∀ i : OC.γ, F.to_sheaf_on_opens.res V HVU (OC.Uis i) (le_trans (subset_covering i) HVU) (subset_covering i) s =\n F.to_sheaf_on_opens.res V HVU (OC.Uis i) (le_trans (subset_covering i) HVU) (subset_covering i) t) :\n s = t :=\nF.locality OC s t H\n\n-- noncomputable def glue (F : sheaf_of_rings_on_opens X U) (V HVU) (OC : covering V)\n-- (s : Π i : OC.γ, F.to_sheaf_on_opens.eval (OC.Uis i) (le_trans (subset_covering i) HVU))\n-- (H : ∀ i j : OC.γ, F.to_sheaf_on_opens.res _ _ (OC.Uis i ⊓ OC.Uis j) (le_trans inf_le_left (le_trans (subset_covering i) HVU)) inf_le_left (s i) =\n-- F.to_sheaf_on_opens.res _ _ (OC.Uis i ⊓ OC.Uis j) (le_trans inf_le_left (le_trans (subset_covering i) HVU)) inf_le_right (s j)) :\n-- F.to_sheaf_on_opens.eval V HVU :=\n-- classical.some $ F.gluing OC s H\n\n-- theorem res_glue (F : sheaf_of_rings_on_opens X U) (V HVU) (OC : covering V) (s H i) :\n-- F.to_sheaf_on_opens.res V HVU (OC.Uis i) (le_trans (subset_covering i) HVU) (subset_covering i) (F.glue V HVU OC s H) = s i :=\n-- classical.some_spec (F.gluing OC s H) i\n\n-- theorem eq_glue (F : sheaf_of_rings_on_opens X U) (V HVU) (OC : covering V)\n-- (s : Π i : OC.γ, F.to_sheaf_on_opens.eval (OC.Uis i) (le_trans (subset_covering i) HVU)) (H t)\n-- (ht : ∀ i, F.to_sheaf_on_opens.res V HVU (OC.Uis i) (le_trans (subset_covering i) HVU) (subset_covering i) t = s i) :\n-- F.glue V HVU OC s H = t :=\n-- F.locality V HVU _ _ OC $ λ i, by rw [res_glue, ht]\n\ndef res_subset (F : sheaf_of_rings_on_opens X U) (V : opens X) (HVU : V ≤ U) : sheaf_of_rings_on_opens X V :=\nF\n\ntheorem res_res_subset (F : sheaf_of_rings_on_opens X U) (V HVU S HSV T HTV HTS x) :\n (F.to_sheaf_on_opens.res_subset V HVU).res S HSV T HTV HTS x = F.to_sheaf_on_opens.res S (le_trans HSV HVU) T (le_trans HTV HVU) HTS x :=\nrfl\n\n-- def stalk (F : sheaf_of_rings_on_opens.{v} X U) (x : X) (hx : x ∈ U) : Type (max u v) :=\n-- stalk_of_rings F.1 x\n\ninstance comm_ring_stalk (F : sheaf_of_rings_on_opens.{v} X U) (x : X) (hx : x ∈ U) :\n comm_ring (F.to_sheaf_on_opens.stalk x hx) :=\nstalk_of_rings_is_comm_ring F.1 x\n\n-- def to_stalk (F : sheaf_of_rings_on_opens.{v} X U) (x : X) (hx : x ∈ U) (V : opens X) (hxV : x ∈ V) (HVU : V ≤ U) (s : F.to_sheaf_on_opens.eval V HVU) : F.to_sheaf_on_opens.stalk x hx :=\n-- F.to_sheaf_on_opens.to_stalk x hx V hxV HVU s\n\ninstance is_ring_hom_to_stalk (F : sheaf_of_rings_on_opens X U) (x hx V hxV HVU) :\n is_ring_hom (F.to_sheaf_on_opens.to_stalk x hx V hxV HVU) :=\nto_stalk.is_ring_hom _ _ _ _\n\nsection\nvariables (F : sheaf_of_rings_on_opens.{v} X U) (x : X) (hx : x ∈ U) (V : opens X) (hxV : x ∈ V) (HVU : V ≤ U)\nvariables (s t : F.to_sheaf_on_opens.eval V HVU) (n : ℕ)\n@[simp] lemma to_stalk_add : F.to_sheaf_on_opens.to_stalk x hx V hxV HVU (s + t) = F.to_sheaf_on_opens.to_stalk x hx V hxV HVU s + F.to_sheaf_on_opens.to_stalk x hx V hxV HVU t := is_ring_hom.map_add _\n@[simp] lemma to_stalk_zero : F.to_sheaf_on_opens.to_stalk x hx V hxV HVU 0 = 0 := is_ring_hom.map_zero _\n@[simp] lemma to_stalk_neg : F.to_sheaf_on_opens.to_stalk x hx V hxV HVU (-s) = -F.to_sheaf_on_opens.to_stalk x hx V hxV HVU s := is_ring_hom.map_neg _\n@[simp] lemma to_stalk_sub : F.to_sheaf_on_opens.to_stalk x hx V hxV HVU (s - t) = F.to_sheaf_on_opens.to_stalk x hx V hxV HVU s - F.to_sheaf_on_opens.to_stalk x hx V hxV HVU t := is_ring_hom.map_sub _\n@[simp] lemma to_stalk_mul : F.to_sheaf_on_opens.to_stalk x hx V hxV HVU (s * t) = F.to_sheaf_on_opens.to_stalk x hx V hxV HVU s * F.to_sheaf_on_opens.to_stalk x hx V hxV HVU t := is_ring_hom.map_mul _\n@[simp] lemma to_stalk_one : F.to_sheaf_on_opens.to_stalk x hx V hxV HVU 1 = 1 := is_ring_hom.map_one _\n@[simp] lemma to_stalk_pow : F.to_sheaf_on_opens.to_stalk x hx V hxV HVU (s^n) = (F.to_sheaf_on_opens.to_stalk x hx V hxV HVU s)^n := is_semiring_hom.map_pow _ s n\nend\n\n@[simp] lemma to_stalk_res (F : sheaf_of_rings_on_opens.{v} X U) (x : X) (hx : x ∈ U) (V : opens X) (hxV : x ∈ V) (HVU : V ≤ U)\n (W : opens X) (hxW : x ∈ W) (HWV : W ≤ V) (s : F.to_sheaf_on_opens.eval V HVU) :\n F.to_sheaf_on_opens.to_stalk x hx W hxW (le_trans HWV HVU) (F.to_sheaf_on_opens.res _ _ _ _ HWV s) = F.to_sheaf_on_opens.to_stalk x hx V hxV HVU s :=\nto_stalk_res _ _ _ _ _ _ _ _\n\n@[elab_as_eliminator] theorem stalk.induction_on {F : sheaf_of_rings_on_opens X U} {x : X} {hx : x ∈ U}\n {C : F.to_sheaf_on_opens.stalk x hx → Prop} (g : F.to_sheaf_on_opens.stalk x hx)\n (H : ∀ V : opens X, ∀ hxV : x ∈ V, ∀ HVU : V ≤ U, ∀ s : F.to_sheaf_on_opens.eval V HVU, C (F.to_sheaf_on_opens.to_stalk x hx V hxV HVU s)) :\n C g :=\nquotient.induction_on g $ λ e,\nhave (⟦e⟧ : F.to_sheaf_on_opens.stalk x hx) = ⟦⟨e.1 ⊓ U, ⟨e.2, hx⟩, F.F.res _ _ (set.inter_subset_left _ _) e.3⟩⟧,\nfrom quotient.sound ⟨e.1 ⊓ U, ⟨e.2, hx⟩, set.inter_subset_left _ _, set.subset.refl _,\n by dsimp only [to_sheaf_on_opens]; rw ← presheaf.Hcomp'; refl⟩,\nthis.symm ▸ H (e.1 ⊓ U) ⟨e.2, hx⟩ inf_le_right _\n\n@[elab_as_eliminator] theorem stalk.induction_on₂ {F : sheaf_of_rings_on_opens X U} {x : X} {hx : x ∈ U}\n {C : F.to_sheaf_on_opens.stalk x hx → F.to_sheaf_on_opens.stalk x hx → Prop} (g1 g2 : F.to_sheaf_on_opens.stalk x hx)\n (H : ∀ V : opens X, ∀ hxV : x ∈ V, ∀ HVU : V ≤ U, ∀ s t : F.to_sheaf_on_opens.eval V HVU, C (F.to_sheaf_on_opens.to_stalk x hx V hxV HVU s) (F.to_sheaf_on_opens.to_stalk x hx V hxV HVU t)) :\n C g1 g2 :=\nquotient.induction_on₂ g1 g2 $ λ e1 e2,\nhave h1 : (⟦e1⟧ : F.to_sheaf_on_opens.stalk x hx) = _root_.to_stalk F.F x (e1.1 ⊓ e2.1 ⊓ U) ⟨⟨e1.2, e2.2⟩, hx⟩ (F.F.res _ _ (λ p hp, hp.1.1) e1.3),\nby erw [_root_.to_stalk_res]; cases e1; refl,\nhave h2 : (⟦e2⟧ : F.to_sheaf_on_opens.stalk x hx) = _root_.to_stalk F.F x (e1.1 ⊓ e2.1 ⊓ U) ⟨⟨e1.2, e2.2⟩, hx⟩ (F.F.res _ _ (λ p hp, hp.1.2) e2.3),\nby erw [_root_.to_stalk_res]; cases e2; refl,\nh1.symm ▸ h2.symm ▸ H _ _ inf_le_right _ _\n\nstructure morphism (F : sheaf_of_rings_on_opens.{v} X U) (G : sheaf_of_rings_on_opens.{w} X U) : Type (max u v w) :=\n(η : F.to_sheaf_on_opens.morphism G.to_sheaf_on_opens)\n[hom : ∀ V HV, is_ring_hom (η.map V HV)]\nattribute [instance] morphism.hom\n\nnamespace morphism\n\nsection\nvariables {F : sheaf_of_rings_on_opens.{v} X U} {G : sheaf_of_rings_on_opens.{w} X U}\nvariables (η : F.morphism G) (V : opens X) (HVU : V ≤ U) (x y : F.to_sheaf_on_opens.eval V HVU) (n : ℕ)\n@[simp] lemma map_add : η.1.map V HVU (x + y) = η.1.map V HVU x + η.1.map V HVU y := is_ring_hom.map_add _\n@[simp] lemma map_zero : η.1.map V HVU 0 = 0 := is_ring_hom.map_zero _\n@[simp] lemma map_neg : η.1.map V HVU (-x) = -η.1.map V HVU x := is_ring_hom.map_neg _\n@[simp] lemma map_sub : η.1.map V HVU (x - y) = η.1.map V HVU x - η.1.map V HVU y := is_ring_hom.map_sub _\n@[simp] lemma map_mul : η.1.map V HVU (x * y) = η.1.map V HVU x * η.1.map V HVU y := is_ring_hom.map_mul _\n@[simp] lemma map_one : η.1.map V HVU 1 = 1 := is_ring_hom.map_one _\n@[simp] lemma map_pow : η.1.map V HVU (x^n) = (η.1.map V HVU x)^n := is_semiring_hom.map_pow _ x n\nend\n\nprotected def id (F : sheaf_of_rings_on_opens.{v} X U) : F.morphism F :=\n{ η := sheaf_on_opens.morphism.id _,\n hom := λ _ _, is_ring_hom.id }\n\ndef comp {F : sheaf_of_rings_on_opens.{v} X U} {G : sheaf_of_rings_on_opens.{w} X U} {H : sheaf_of_rings_on_opens.{u₁} X U}\n (η : G.morphism H) (ξ : F.morphism G) : F.morphism H :=\n{ η := η.1.comp ξ.1,\n hom := λ _ _, is_ring_hom.comp _ _ }\n\n@[simp] lemma comp_apply {F : sheaf_of_rings_on_opens.{v} X U} {G : sheaf_of_rings_on_opens.{w} X U} {H : sheaf_of_rings_on_opens.{u₁} X U}\n (η : G.morphism H) (ξ : F.morphism G) (V HV s) :\n (η.comp ξ).1.1 V HV s = η.1.1 V HV (ξ.1.1 V HV s) :=\nrfl\n\n@[ext] lemma ext {F : sheaf_of_rings_on_opens.{v} X U} {G : sheaf_of_rings_on_opens.{w} X U}\n {η ξ : F.morphism G} (H : ∀ V HV x, η.1.map V HV x = ξ.1.map V HV x) : η = ξ :=\nby cases η; cases ξ; congr; ext; apply H\n\n@[simp] lemma id_comp {F : sheaf_of_rings_on_opens.{v} X U} {G : sheaf_of_rings_on_opens.{w} X U} (η : F.morphism G) :\n (morphism.id G).comp η = η :=\next $ λ V HV x, rfl\n\n@[simp] lemma comp_id {F : sheaf_of_rings_on_opens.{v} X U} {G : sheaf_of_rings_on_opens.{w} X U} (η : F.morphism G) :\n η.comp (morphism.id F) = η :=\next $ λ V HV x, rfl\n\n@[simp] lemma comp_assoc {F : sheaf_of_rings_on_opens.{v} X U} {G : sheaf_of_rings_on_opens.{w} X U} {H : sheaf_of_rings_on_opens.{u₁} X U} {I : sheaf_of_rings_on_opens.{v₁} X U}\n (η : H.morphism I) (ξ : G.morphism H) (χ : F.morphism G) :\n (η.comp ξ).comp χ = η.comp (ξ.comp χ) :=\nrfl\n\ndef res_subset {F : sheaf_of_rings_on_opens.{v} X U} {G : sheaf_of_rings_on_opens.{w} X U} (η : F.morphism G) (V : opens X) (HVU : V ≤ U) :\n (F.res_subset V HVU).morphism (G.res_subset V HVU) :=\n{ η := η.1.res_subset V HVU,\n hom := λ _ _, η.2 _ _ }\n\n@[simp] lemma res_subset_apply {F : sheaf_of_rings_on_opens.{v} X U} {G : sheaf_of_rings_on_opens.{w} X U} (η : F.morphism G) (V : opens X) (HVU : V ≤ U)\n (W HWV s) : (η.res_subset V HVU).1.1 W HWV s = η.1.1 W (le_trans HWV HVU) s :=\nrfl\n\n@[simp] lemma comp_res_subset {F : sheaf_of_rings_on_opens.{v} X U} {G : sheaf_of_rings_on_opens.{w} X U} {H : sheaf_of_rings_on_opens.{u₁} X U}\n (η : G.morphism H) (ξ : F.morphism G) (V : opens X) (HVU : V ≤ U) :\n (η.res_subset V HVU).comp (ξ.res_subset V HVU) = (η.comp ξ).res_subset V HVU :=\nrfl\n\n@[simp] lemma id_res_subset {F : sheaf_of_rings_on_opens.{v} X U} (V : opens X) (HVU : V ≤ U) :\n (morphism.id F).res_subset V HVU = morphism.id (F.res_subset V HVU) :=\nrfl\n\n-- def stalk {F : sheaf_of_rings_on_opens.{v} X U} {G : sheaf_of_rings_on_opens.{w} X U} (η : F.morphism G) (x : X) (hx : x ∈ U)\n-- (s : F.to_sheaf_on_opens.stalk x hx) : G.to_sheaf_on_opens.stalk x hx :=\n-- quotient.lift_on s (λ g, ⟦(⟨g.1 ⊓ U, (⟨g.2, hx⟩ : x ∈ g.1 ⊓ U),\n-- η.1.map _ inf_le_right (presheaf.res F.1.1 _ _ (set.inter_subset_left _ _) g.3)⟩ : stalk.elem _ _)⟧) $\n-- λ g₁ g₂ ⟨V, hxV, HV1, HV2, hg⟩, quotient.sound ⟨V ⊓ U, ⟨hxV, hx⟩, set.inter_subset_inter_left _ HV1, set.inter_subset_inter_left _ HV2,\n-- calc G.to_sheaf_on_opens.res _ _ (V ⊓ U) inf_le_right (inf_le_inf HV1 (le_refl _)) (η.1.map (g₁.U ⊓ U) inf_le_right ((F.F).res (g₁.U) (g₁.U ⊓ U) (set.inter_subset_left _ _) (g₁.s)))\n-- = η.1.map (V ⊓ U) inf_le_right ((F.F).res V (V ⊓ U) (set.inter_subset_left _ _) ((F.F).res (g₁.U) V HV1 (g₁.s))) :\n-- by rw ← η.3; dsimp only [sheaf_on_opens.res, sheaf_of_rings_on_opens.to_sheaf_on_opens]; rw [← presheaf.Hcomp', ← presheaf.Hcomp']\n-- ... = G.to_sheaf_on_opens.res _ _ (V ⊓ U) _ _ (η.1.map (g₂.U ⊓ U) inf_le_right ((F.F).res (g₂.U) (g₂.U ⊓ U) _ (g₂.s))) :\n-- by erw [hg, ← η.3]; dsimp only [sheaf_on_opens.res, sheaf_of_rings_on_opens.to_sheaf_on_opens]; rw [← presheaf.Hcomp', ← presheaf.Hcomp']⟩\n\n-- @[simp] lemma stalk_to_stalk {F : sheaf_of_rings_on_opens.{v} X U} {G : sheaf_of_rings_on_opens.{w} X U} (η : F.morphism G) (x : X) (hx : x ∈ U)\n-- (V : opens X) (HVU : V ≤ U) (hxV : x ∈ V) (s : F.to_sheaf_on_opens.eval V HVU) :\n-- η.stalk x hx (F.to_sheaf_on_opens.to_stalk x hx V hxV HVU s) =\n-- G.to_sheaf_on_opens.to_stalk x hx V hxV HVU (η.1.map V HVU s) :=\n-- quotient.sound ⟨V, hxV, set.subset_inter (set.subset.refl _) HVU, set.subset.refl _,\n-- calc G.to_sheaf_on_opens.res (V ⊓ U) inf_le_right V HVU (le_inf (le_refl V) HVU) (η.1.map (V ⊓ U) inf_le_right (F.to_sheaf_on_opens.res V HVU (V ⊓ U) inf_le_right inf_le_left s))\n-- = G.to_sheaf_on_opens.res V HVU V HVU (le_refl V) (η.1.map V HVU s) : by rw [η.3, res_res]⟩\n\ninstance is_ring_hom_stalk {F : sheaf_of_rings_on_opens.{v} X U} {G : sheaf_of_rings_on_opens.{w} X U} (η : F.morphism G) (x : X) (hx : x ∈ U) :\n is_ring_hom (η.1.stalk x hx) :=\n{ map_one := quotient.sound ⟨U, hx, set.subset_inter (set.subset_univ U.1) (set.subset.refl U.1), set.subset_univ U.1,\n by dsimp only; erw [_root_.res_one, η.map_one, _root_.res_one, _root_.res_one]⟩,\n map_mul := λ y z, stalk.induction_on₂ y z $ λ V hxV HVU s t,\n by rw [sheaf_on_opens.morphism.stalk_to_stalk, sheaf_on_opens.morphism.stalk_to_stalk, ← to_stalk_mul,\n sheaf_on_opens.morphism.stalk_to_stalk, η.map_mul, to_stalk_mul],\n map_add := λ y z, stalk.induction_on₂ y z $ λ V hxV HVU s t,\n by rw [sheaf_on_opens.morphism.stalk_to_stalk, sheaf_on_opens.morphism.stalk_to_stalk, ← to_stalk_add,\n sheaf_on_opens.morphism.stalk_to_stalk, η.map_add, to_stalk_add] }\n\nsection\nvariables {F : sheaf_of_rings_on_opens.{v} X U} {G : sheaf_of_rings_on_opens.{w} X U} (η : F.morphism G) (x : X) (hx : x ∈ U)\nvariables (s t : F.to_sheaf_on_opens.stalk x hx) (n : ℕ)\n@[simp] lemma stalk_add : η.1.stalk x hx (s + t) = η.1.stalk x hx s + η.1.stalk x hx t := is_ring_hom.map_add _\n@[simp] lemma stalk_zero : η.1.stalk x hx 0 = 0 := is_ring_hom.map_zero _\n@[simp] lemma stalk_neg : η.1.stalk x hx (-s) = -η.1.stalk x hx s := is_ring_hom.map_neg _\n@[simp] lemma stalk_sub : η.1.stalk x hx (s - t) = η.1.stalk x hx s - η.1.stalk x hx t := is_ring_hom.map_sub _\n@[simp] lemma stalk_mul : η.1.stalk x hx (s * t) = η.1.stalk x hx s * η.1.stalk x hx t := is_ring_hom.map_mul _\n@[simp] lemma stalk_one : η.1.stalk x hx 1 = 1 := is_ring_hom.map_one _\n@[simp] lemma stalk_pow : η.1.stalk x hx (s^n) = (η.1.stalk x hx s)^n := is_semiring_hom.map_pow _ s n\nend\n\nend morphism\n\nstructure equiv (F : sheaf_of_rings_on_opens.{v} X U) (G : sheaf_of_rings_on_opens.{w} X U) : Type (max u v w) :=\n(to_fun : F.morphism G)\n(inv_fun : G.to_sheaf_on_opens.morphism F.to_sheaf_on_opens)\n(left_inv : ∀ V HVU s, inv_fun.1 V HVU (to_fun.1.1 V HVU s) = s)\n(right_inv : ∀ V HVU s, to_fun.1.1 V HVU (inv_fun.1 V HVU s) = s)\n\nnamespace equiv\n\ndef to_sheaf_on_opens {F : sheaf_of_rings_on_opens.{v} X U} {G : sheaf_of_rings_on_opens.{w} X U} (e : F.equiv G) :\n F.to_sheaf_on_opens.equiv G.to_sheaf_on_opens :=\n{ to_fun := e.1.1, .. e }\n\ndef to_ring_equiv {F : sheaf_of_rings_on_opens.{v} X U} {G : sheaf_of_rings_on_opens.{v} X U} (e : equiv F G) (V HVU) :\n F.to_sheaf_on_opens.eval V HVU ≃+* G.to_sheaf_on_opens.eval V HVU :=\nring_equiv.of' { to_fun := e.1.1.1 V HVU, inv_fun := e.2.1 V HVU, left_inv := e.3 V HVU, right_inv := e.4 V HVU }\n\ndef refl (F : sheaf_of_rings_on_opens.{v} X U) : equiv F F :=\n⟨morphism.id F, sheaf_on_opens.morphism.id F.to_sheaf_on_opens, λ _ _ _, rfl, λ _ _ _, rfl⟩\n\n@[simp] lemma refl_apply (F : sheaf_of_rings_on_opens.{v} X U) (V HV s) :\n (refl F).1.1.1 V HV s = s := rfl\n\ndef symm {F : sheaf_of_rings_on_opens.{v} X U} {G : sheaf_of_rings_on_opens.{v} X U} (e : equiv F G) : equiv G F :=\n⟨{ η := e.2,\n hom := λ V HVU, (ring_equiv.symm (e.to_ring_equiv V HVU)).hom },\ne.1.1, e.4, e.3⟩\n\ndef trans {F : sheaf_of_rings_on_opens.{v} X U} {G : sheaf_of_rings_on_opens.{v} X U} {H : sheaf_of_rings_on_opens.{u₁} X U}\n (e₁ : equiv F G) (e₂ : equiv G H) : equiv F H :=\n⟨e₂.1.comp e₁.1, e₁.2.comp e₂.2,\nλ _ _ _, by rw [morphism.comp_apply, sheaf_on_opens.morphism.comp_apply, e₂.3, e₁.3],\nλ _ _ _, by rw [morphism.comp_apply, sheaf_on_opens.morphism.comp_apply, e₁.4, e₂.4]⟩\n\n@[simp] lemma trans_apply {F : sheaf_of_rings_on_opens.{v} X U} {G : sheaf_of_rings_on_opens.{v} X U} {H : sheaf_of_rings_on_opens.{u₁} X U}\n (e₁ : equiv F G) (e₂ : equiv G H) (V HV s) :\n (e₁.trans e₂).1.1.1 V HV s = e₂.1.1.1 V HV (e₁.1.1.1 V HV s) :=\nrfl\n\ndef res_subset {F : sheaf_of_rings_on_opens.{v} X U} {G : sheaf_of_rings_on_opens.{w} X U} (e : equiv F G)\n (V : opens X) (HVU : V ≤ U) : equiv (F.res_subset V HVU) (G.res_subset V HVU) :=\n⟨e.1.res_subset V HVU, e.2.res_subset V HVU,\nλ _ _ _, by rw [morphism.res_subset_apply, sheaf_on_opens.morphism.res_subset_apply, e.3],\nλ _ _ _, by rw [morphism.res_subset_apply, sheaf_on_opens.morphism.res_subset_apply, e.4]⟩\n\n@[simp] lemma res_subset_apply {F : sheaf_of_rings_on_opens.{v} X U} {G : sheaf_of_rings_on_opens.{w} X U} (e : equiv F G)\n (V : opens X) (HVU : V ≤ U) (W HW s) :\n (e.res_subset V HVU).1.1.1 W HW s = e.1.1.1 W (le_trans HW HVU) s :=\nrfl\n\n-- def stalk {F : sheaf_of_rings_on_opens.{v} X U} {G : sheaf_of_rings_on_opens.{w} X U} (e : equiv F G) (x : X) (hx : x ∈ U) :\n-- F.to_sheaf_on_opens.stalk x hx ≃ G.to_sheaf_on_opens.stalk x hx :=\n-- { to_fun := e.1.1.stalk x hx,\n-- inv_fun := e.2.stalk x hx,\n-- left_inv := λ g, stalk.induction_on g $ λ V hxV HVU s,\n-- by rw [sheaf_on_opens.morphism.stalk_to_stalk, sheaf_on_opens.morphism.stalk_to_stalk, e.3]; refl,\n-- right_inv := λ g, stalk.induction_on g $ λ V hxV HVU s,\n-- by rw [sheaf_on_opens.morphism.stalk_to_stalk, sheaf_on_opens.morphism.stalk_to_stalk, e.4]; refl }\n\nend equiv\n\ndef sheaf_glue {I : Type u} (S : I → opens X) (F : Π (i : I), sheaf_of_rings_on_opens.{v} X (S i))\n (φ : Π i j, equiv ((F i).res_subset ((S i) ⊓ (S j)) inf_le_left) ((F j).res_subset ((S i) ⊓ (S j)) inf_le_right)) :\n sheaf_of_rings_on_opens.{max u v} X (⋃S) :=\n{ F :=\n { Fring := λ U, @subtype.comm_ring (Π (i : I), (F i).to_sheaf_on_opens.eval (S i ⊓ U) inf_le_left) _\n { f | ∀ (i j : I), (φ i j).1.1.1 (S i ⊓ S j ⊓ U) inf_le_left\n ((F i).to_sheaf_on_opens.res (S i ⊓ U) inf_le_left (S i ⊓ S j ⊓ U) (le_trans inf_le_left inf_le_left)\n (le_inf (le_trans inf_le_left inf_le_left) inf_le_right)\n (f i)) =\n (F j).to_sheaf_on_opens.res (S j ⊓ U) inf_le_left (S i ⊓ S j ⊓ U) (le_trans inf_le_left inf_le_right)\n (by rw inf_assoc; exact inf_le_right)\n (f j) }\n { add_mem := λ f g hf hg i j, by erw [res_add, morphism.map_add, res_add, hf i j, hg i j],\n zero_mem := λ i j, by erw [res_zero, morphism.map_zero, res_zero]; refl,\n neg_mem := λ f hf i j, by erw [res_neg, morphism.map_neg, res_neg, hf i j],\n one_mem := λ i j, by erw [res_one, morphism.map_one, res_one]; refl,\n mul_mem := λ f g hf hg i j, by erw [res_mul, morphism.map_mul, res_mul, hf i j, hg i j] },\n res_is_ring_hom := λ U V HVU,\n { map_one := subtype.eq $ funext $ λ i, res_one _ _ _ _ _ _,\n map_mul := λ f g, subtype.eq $ funext $ λ i, res_mul _ _ _ _ _ _ _ _,\n map_add := λ f g, subtype.eq $ funext $ λ i, res_add _ _ _ _ _ _ _ _ },\n .. sheaf_on_opens.sheaf_glue S (λ i, (F i).to_sheaf_on_opens) (λ i j, (φ i j).to_sheaf_on_opens) }\n .. sheaf_on_opens.sheaf_glue S (λ i, (F i).to_sheaf_on_opens) (λ i j, (φ i j).to_sheaf_on_opens) }\n\n@[simp] lemma sheaf_glue_res_val {I : Type u} (S : I → opens X) (F : Π (i : I), sheaf_of_rings_on_opens.{v} X (S i))\n (φ : Π i j, equiv ((F i).res_subset ((S i) ⊓ (S j)) inf_le_left) ((F j).res_subset ((S i) ⊓ (S j)) inf_le_right))\n (U HU V HV HVU s i) :\n ((sheaf_glue S F φ).to_sheaf_on_opens.res U HU V HV HVU s).1 i =\n (F i).to_sheaf_on_opens.res _ _ _ _ (inf_le_inf (le_refl _) HVU) (s.1 i) := rfl\n\ndef universal_property (I : Type u) (S : I → opens X) (F : Π (i : I), sheaf_of_rings_on_opens.{v} X (S i))\n (φ : Π i j, equiv ((F i).res_subset ((S i) ⊓ (S j)) inf_le_left) ((F j).res_subset ((S i) ⊓ (S j)) inf_le_right))\n (Hφ1 : ∀ i V HV s, (φ i i).1.1.1 V HV s = s)\n (Hφ2 : ∀ i j k V HV1 HV2 HV3 s, (φ j k).1.1.1 V HV1 ((φ i j).1.1.1 V HV2 s) = (φ i k).1.1.1 V HV3 s)\n (i : I) :\n equiv (res_subset (sheaf_glue S F φ) (S i) (le_supr S i)) (F i) :=\n{ to_fun :=\n { η := (sheaf_on_opens.universal_property I S (λ i, (F i).to_sheaf_on_opens) (λ i j, (φ i j).to_sheaf_on_opens) Hφ1 Hφ2 i).1,\n hom := λ U HU,\n { map_one := res_one _ _ _ _ _ _,\n map_mul := λ x y, res_mul _ _ _ _ _ _ _ _,\n map_add := λ x y, res_add _ _ _ _ _ _ _ _ } },\n .. sheaf_on_opens.universal_property I S (λ i, (F i).to_sheaf_on_opens) (λ i j, (φ i j).to_sheaf_on_opens) Hφ1 Hφ2 i }\n\nend sheaf_of_rings_on_opens\n", "meta": {"author": "ramonfmir", "repo": "lean-scheme", "sha": "6d3ec18fecfd174b79d0ce5c85a783f326dd50f6", "save_path": "github-repos/lean/ramonfmir-lean-scheme", "path": "github-repos/lean/ramonfmir-lean-scheme/lean-scheme-6d3ec18fecfd174b79d0ce5c85a783f326dd50f6/src/Kenny/sheaf_of_rings_on_opens.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4960938294709195, "lm_q2_score": 0.02002344165495285, "lm_q1q2_score": 0.009933505849793085}} {"text": "/-\nCopyright (c) 2020 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Leonardo de Moura, Mario Carneiro\n\nNotation for operators defined at Prelude.lean\n-/\nprelude\nimport Init.Prelude\nimport Init.Coe\nset_option linter.missingDocs true -- keep it documented\n\nnamespace Lean\n\n/--\nAuxiliary type used to represent syntax categories. We mainly use auxiliary\ndefinitions with this type to attach doc strings to syntax categories.\n-/\nstructure Parser.Category\n\nnamespace Parser.Category\n\n/-- `command` is the syntax category for things that appear at the top level\nof a lean file. For example, `def foo := 1` is a `command`, as is\n`namespace Foo` and `end Foo`. Commands generally have an effect on the state of\nadding something to the environment (like a new definition), as well as\ncommands like `variable` which modify future commands within a scope. -/\ndef command : Category := {}\n\n/-- `term` is the builtin syntax category for terms. A term denotes an expression\nin lean's type theory, for example `2 + 2` is a term. The difference between\n`Term` and `Expr` is that the former is a kind of syntax, while the latter is\nthe result of elaboration. For example `by simp` is also a `Term`, but it elaborates\nto different `Expr`s depending on the context. -/\ndef term : Category := {}\n\n/-- `tactic` is the builtin syntax category for tactics. These appear after\n`by` in proofs, and they are programs that take in the proof context\n(the hypotheses in scope plus the type of the term to synthesize) and construct\na term of the expected type. For example, `simp` is a tactic, used in:\n```\nexample : 2 + 2 = 4 := by simp\n```\n-/\ndef tactic : Category := {}\n\n/-- `doElem` is a builtin syntax category for elements that can appear in the `do` notation.\nFor example, `let x ← e` is a `doElem`, and a `do` block consists of a list of `doElem`s. -/\ndef doElem : Category := {}\n\n/-- `level` is a builtin syntax category for universe levels.\nThis is the `u` in `Sort u`: it can contain `max` and `imax`, addition with\nconstants, and variables. -/\ndef level : Category := {}\n\n/-- `attr` is a builtin syntax category for attributes.\nDeclarations can be annotated with attributes using the `@[...]` notation. -/\ndef attr : Category := {}\n\n/-- `stx` is a builtin syntax category for syntax. This is the abbreviated\nparser notation used inside `syntax` and `macro` declarations. -/\ndef stx : Category := {}\n\n/-- `prio` is a builtin syntax category for priorities.\nPriorities are used in many different attributes.\nHigher numbers denote higher priority, and for example typeclass search will\ntry high priority instances before low priority.\nIn addition to literals like `37`, you can also use `low`, `mid`, `high`, as well as\nadd and subtract priorities. -/\ndef prio : Category := {}\n\n/-- `prec` is a builtin syntax category for precedences. A precedence is a value\nthat expresses how tightly a piece of syntax binds: for example `1 + 2 * 3` is\nparsed as `1 + (2 * 3)` because `*` has a higher pr0ecedence than `+`.\nHigher numbers denote higher precedence.\nIn addition to literals like `37`, there are some special named priorities:\n* `arg` for the precedence of function arguments\n* `max` for the highest precedence used in term parsers (not actually the maximum possible value)\n* `lead` for the precedence of terms not supposed to be used as arguments\nand you can also add and subtract precedences. -/\ndef prec : Category := {}\n\nend Parser.Category\n\nnamespace Parser.Syntax\n\n/-! DSL for specifying parser precedences and priorities -/\n\n/-- Addition of precedences. This is normally used only for offseting, e.g. `max + 1`. -/\nsyntax:65 (name := addPrec) prec \" + \" prec:66 : prec\n/-- Subtraction of precedences. This is normally used only for offseting, e.g. `max - 1`. -/\nsyntax:65 (name := subPrec) prec \" - \" prec:66 : prec\n\n/-- Addition of priorities. This is normally used only for offseting, e.g. `default + 1`. -/\nsyntax:65 (name := addPrio) prio \" + \" prio:66 : prio\n/-- Subtraction of priorities. This is normally used only for offseting, e.g. `default - 1`. -/\nsyntax:65 (name := subPrio) prio \" - \" prio:66 : prio\n\nend Parser.Syntax\n\ninstance : CoeOut (TSyntax ks) Syntax where\n coe stx := stx.raw\n\ninstance : Coe SyntaxNodeKind SyntaxNodeKinds where\n coe k := List.cons k List.nil\n\nend Lean\n\n/--\nMaximum precedence used in term parsers, in particular for terms in\nfunction position (`ident`, `paren`, ...)\n-/\nmacro \"max\" : prec => `(prec| 1024)\n/-- Precedence used for application arguments (`do`, `by`, ...). -/\nmacro \"arg\" : prec => `(prec| 1023)\n/-- Precedence used for terms not supposed to be used as arguments (`let`, `have`, ...). -/\nmacro \"lead\" : prec => `(prec| 1022)\n/-- Parentheses are used for grouping precedence expressions. -/\nmacro \"(\" p:prec \")\" : prec => return p\n/-- Minimum precedence used in term parsers. -/\nmacro \"min\" : prec => `(prec| 10)\n/-- `(min+1)` (we can only write `min+1` after `Meta.lean`) -/\nmacro \"min1\" : prec => `(prec| 11)\n/--\n`max:prec` as a term. It is equivalent to `eval_prec max` for `eval_prec` defined at `Meta.lean`.\nWe use `max_prec` to workaround bootstrapping issues.\n-/\nmacro \"max_prec\" : term => `(1024)\n\n/-- The default priority `default = 1000`, which is used when no priority is set. -/\nmacro \"default\" : prio => `(prio| 1000)\n/-- The standardized \"low\" priority `low = 100`, for things that should be lower than default priority. -/\nmacro \"low\" : prio => `(prio| 100)\n/--\nThe standardized \"medium\" priority `med = 1000`. This is lower than `default`, and higher than `low`.\n-/\nmacro \"mid\" : prio => `(prio| 500)\n/-- The standardized \"high\" priority `high = 10000`, for things that should be higher than default priority. -/\nmacro \"high\" : prio => `(prio| 10000)\n/-- Parentheses are used for grouping priority expressions. -/\nmacro \"(\" p:prio \")\" : prio => return p\n\n/-\nNote regarding priorities. We want `low < mid < default` because we have the following default instances:\n```\n@[default_instance low] instance (n : Nat) : OfNat Nat n where ...\n@[default_instance mid] instance : Neg Int where ...\n@[default_instance default] instance [Add α] : HAdd α α α where ...\n@[default_instance default] instance [Sub α] : HSub α α α where ...\n...\n```\n\nMonomorphic default instances must always \"win\" to preserve the Lean 3 monomorphic \"look&feel\".\nThe `Neg Int` instance must have precedence over the `OfNat Nat n` one, otherwise we fail to elaborate `#check -42`\nSee issue #1813 for an example that failed when `mid = default`.\n-/\n\n-- Basic notation for defining parsers\n-- NOTE: precedence must be at least `arg` to be used in `macro` without parentheses\n\n/--\n`p+` is shorthand for `many1(p)`. It uses parser `p` 1 or more times, and produces a\n`nullNode` containing the array of parsed results. This parser has arity 1.\n\nIf `p` has arity more than 1, it is auto-grouped in the items generated by the parser.\n-/\nsyntax:arg stx:max \"+\" : stx\n\n/--\n`p*` is shorthand for `many(p)`. It uses parser `p` 0 or more times, and produces a\n`nullNode` containing the array of parsed results. This parser has arity 1.\n\nIf `p` has arity more than 1, it is auto-grouped in the items generated by the parser.\n-/\nsyntax:arg stx:max \"*\" : stx\n\n/--\n`(p)?` is shorthand for `optional(p)`. It uses parser `p` 0 or 1 times, and produces a\n`nullNode` containing the array of parsed results. This parser has arity 1.\n\n`p` is allowed to have arity n > 1 (in which case the node will have either 0 or n children),\nbut if it has arity 0 then the result will be ambiguous.\n\nBecause `?` is an identifier character, `ident?` will not work as intended.\nYou have to write either `ident ?` or `(ident)?` for it to parse as the `?` combinator\napplied to the `ident` parser.\n-/\nsyntax:arg stx:max \"?\" : stx\n\n/--\n`p1 <|> p2` is shorthand for `orelse(p1, p2)`, and parses either `p1` or `p2`.\nIt does not backtrack, meaning that if `p1` consumes at least one token then\n`p2` will not be tried. Therefore, the parsers should all differ in their first\ntoken. The `atomic(p)` parser combinator can be used to locally backtrack a parser.\n(For full backtracking, consider using extensible syntax classes instead.)\n\nOn success, if the inner parser does not generate exactly one node, it will be\nautomatically wrapped in a `group` node, so the result will always be arity 1.\n\nThe `<|>` combinator does not generate a node of its own, and in particular\ndoes not tag the inner parsers to distinguish them, which can present a problem\nwhen reconstructing the parse. A well formed `<|>` parser should use disjoint\nnode kinds for `p1` and `p2`.\n-/\nsyntax:2 stx:2 \" <|> \" stx:1 : stx\n\nmacro_rules\n | `(stx| $p +) => `(stx| many1($p))\n | `(stx| $p *) => `(stx| many($p))\n | `(stx| $p ?) => `(stx| optional($p))\n | `(stx| $p₁ <|> $p₂) => `(stx| orelse($p₁, $p₂))\n\n/--\n`p,*` is shorthand for `sepBy(p, \",\")`. It parses 0 or more occurrences of\n`p` separated by `,`, that is: `empty | p | p,p | p,p,p | ...`.\n\nIt produces a `nullNode` containing a `SepArray` with the interleaved parser\nresults. It has arity 1, and auto-groups its component parser if needed.\n-/\nmacro:arg x:stx:max \",*\" : stx => `(stx| sepBy($x, \",\", \", \"))\n/--\n`p,+` is shorthand for `sepBy(p, \",\")`. It parses 1 or more occurrences of\n`p` separated by `,`, that is: `p | p,p | p,p,p | ...`.\n\nIt produces a `nullNode` containing a `SepArray` with the interleaved parser\nresults. It has arity 1, and auto-groups its component parser if needed.\n-/\nmacro:arg x:stx:max \",+\" : stx => `(stx| sepBy1($x, \",\", \", \"))\n\n/--\n`p,*,?` is shorthand for `sepBy(p, \",\", allowTrailingSep)`.\nIt parses 0 or more occurrences of `p` separated by `,`, possibly including\na trailing `,`, that is: `empty | p | p, | p,p | p,p, | p,p,p | ...`.\n\nIt produces a `nullNode` containing a `SepArray` with the interleaved parser\nresults. It has arity 1, and auto-groups its component parser if needed.\n-/\nmacro:arg x:stx:max \",*,?\" : stx => `(stx| sepBy($x, \",\", \", \", allowTrailingSep))\n\n/--\n`p,+,?` is shorthand for `sepBy1(p, \",\", allowTrailingSep)`.\nIt parses 1 or more occurrences of `p` separated by `,`, possibly including\na trailing `,`, that is: `p | p, | p,p | p,p, | p,p,p | ...`.\n\nIt produces a `nullNode` containing a `SepArray` with the interleaved parser\nresults. It has arity 1, and auto-groups its component parser if needed.\n-/\nmacro:arg x:stx:max \",+,?\" : stx => `(stx| sepBy1($x, \",\", \", \", allowTrailingSep))\n\n/--\n`!p` parses the negation of `p`. That is, it fails if `p` succeeds, and\notherwise parses nothing. It has arity 0.\n-/\nmacro:arg \"!\" x:stx:max : stx => `(stx| notFollowedBy($x))\n\n/--\nThe `nat_lit n` macro constructs \"raw numeric literals\". This corresponds to the\n`Expr.lit (.natVal n)` constructor in the `Expr` data type.\n\nNormally, when you write a numeral like `#check 37`, the parser turns this into\nan application of `OfNat.ofNat` to the raw literal `37` to cast it into the\ntarget type, even if this type is `Nat` (so the cast is the identity function).\nBut sometimes it is necessary to talk about the raw numeral directly,\nespecially when proving properties about the `ofNat` function itself.\n-/\nsyntax (name := rawNatLit) \"nat_lit \" num : term\n\n@[inherit_doc] infixr:90 \" ∘ \" => Function.comp\n@[inherit_doc] infixr:35 \" × \" => Prod\n\n@[inherit_doc] infixl:55 \" ||| \" => HOr.hOr\n@[inherit_doc] infixl:58 \" ^^^ \" => HXor.hXor\n@[inherit_doc] infixl:60 \" &&& \" => HAnd.hAnd\n@[inherit_doc] infixl:65 \" + \" => HAdd.hAdd\n@[inherit_doc] infixl:65 \" - \" => HSub.hSub\n@[inherit_doc] infixl:70 \" * \" => HMul.hMul\n@[inherit_doc] infixl:70 \" / \" => HDiv.hDiv\n@[inherit_doc] infixl:70 \" % \" => HMod.hMod\n@[inherit_doc] infixl:75 \" <<< \" => HShiftLeft.hShiftLeft\n@[inherit_doc] infixl:75 \" >>> \" => HShiftRight.hShiftRight\n@[inherit_doc] infixr:80 \" ^ \" => HPow.hPow\n@[inherit_doc] infixl:65 \" ++ \" => HAppend.hAppend\n@[inherit_doc] prefix:75 \"-\" => Neg.neg\n@[inherit_doc] prefix:100 \"~~~\" => Complement.complement\n\n/-!\n Remark: the infix commands above ensure a delaborator is generated for each relations.\n We redefine the macros below to be able to use the auxiliary `binop%` elaboration helper for binary operators.\n It addresses issue #382. -/\nmacro_rules | `($x ||| $y) => `(binop% HOr.hOr $x $y)\nmacro_rules | `($x ^^^ $y) => `(binop% HXor.hXor $x $y)\nmacro_rules | `($x &&& $y) => `(binop% HAnd.hAnd $x $y)\nmacro_rules | `($x + $y) => `(binop% HAdd.hAdd $x $y)\nmacro_rules | `($x - $y) => `(binop% HSub.hSub $x $y)\nmacro_rules | `($x * $y) => `(binop% HMul.hMul $x $y)\nmacro_rules | `($x / $y) => `(binop% HDiv.hDiv $x $y)\nmacro_rules | `($x % $y) => `(binop% HMod.hMod $x $y)\nmacro_rules | `($x ^ $y) => `(binop% HPow.hPow $x $y)\nmacro_rules | `($x ++ $y) => `(binop% HAppend.hAppend $x $y)\nmacro_rules | `(- $x) => `(unop% Neg.neg $x)\n\n-- declare ASCII alternatives first so that the latter Unicode unexpander wins\n@[inherit_doc] infix:50 \" <= \" => LE.le\n@[inherit_doc] infix:50 \" ≤ \" => LE.le\n@[inherit_doc] infix:50 \" < \" => LT.lt\n@[inherit_doc] infix:50 \" >= \" => GE.ge\n@[inherit_doc] infix:50 \" ≥ \" => GE.ge\n@[inherit_doc] infix:50 \" > \" => GT.gt\n@[inherit_doc] infix:50 \" = \" => Eq\n@[inherit_doc] infix:50 \" == \" => BEq.beq\n/-!\n Remark: the infix commands above ensure a delaborator is generated for each relations.\n We redefine the macros below to be able to use the auxiliary `binrel%` elaboration helper for binary relations.\n It has better support for applying coercions. For example, suppose we have `binrel% Eq n i` where `n : Nat` and\n `i : Int`. The default elaborator fails because we don't have a coercion from `Int` to `Nat`, but\n `binrel%` succeeds because it also tries a coercion from `Nat` to `Int` even when the nat occurs before the int. -/\nmacro_rules | `($x <= $y) => `(binrel% LE.le $x $y)\nmacro_rules | `($x ≤ $y) => `(binrel% LE.le $x $y)\nmacro_rules | `($x < $y) => `(binrel% LT.lt $x $y)\nmacro_rules | `($x > $y) => `(binrel% GT.gt $x $y)\nmacro_rules | `($x >= $y) => `(binrel% GE.ge $x $y)\nmacro_rules | `($x ≥ $y) => `(binrel% GE.ge $x $y)\nmacro_rules | `($x = $y) => `(binrel% Eq $x $y)\nmacro_rules | `($x == $y) => `(binrel_no_prop% BEq.beq $x $y)\n\n@[inherit_doc] infixr:35 \" /\\\\ \" => And\n@[inherit_doc] infixr:35 \" ∧ \" => And\n@[inherit_doc] infixr:30 \" \\\\/ \" => Or\n@[inherit_doc] infixr:30 \" ∨ \" => Or\n@[inherit_doc] notation:max \"¬\" p:40 => Not p\n\n@[inherit_doc] infixl:35 \" && \" => and\n@[inherit_doc] infixl:30 \" || \" => or\n@[inherit_doc] notation:max \"!\" b:40 => not b\n\n@[inherit_doc] infix:50 \" ∈ \" => Membership.mem\n/-- `a ∉ b` is negated elementhood. It is notation for `¬ (a ∈ b)`. -/\nnotation:50 a:50 \" ∉ \" b:50 => ¬ (a ∈ b)\n\n@[inherit_doc] infixr:67 \" :: \" => List.cons\n@[inherit_doc HOrElse.hOrElse] syntax:20 term:21 \" <|> \" term:20 : term\n@[inherit_doc HAndThen.hAndThen] syntax:60 term:61 \" >> \" term:60 : term\n@[inherit_doc] infixl:55 \" >>= \" => Bind.bind\n@[inherit_doc] notation:60 a:60 \" <*> \" b:61 => Seq.seq a fun _ : Unit => b\n@[inherit_doc] notation:60 a:60 \" <* \" b:61 => SeqLeft.seqLeft a fun _ : Unit => b\n@[inherit_doc] notation:60 a:60 \" *> \" b:61 => SeqRight.seqRight a fun _ : Unit => b\n@[inherit_doc] infixr:100 \" <$> \" => Functor.map\n\nmacro_rules | `($x <|> $y) => `(binop_lazy% HOrElse.hOrElse $x $y)\nmacro_rules | `($x >> $y) => `(binop_lazy% HAndThen.hAndThen $x $y)\n\nnamespace Lean\n\n/--\n`binderIdent` matches an `ident` or a `_`. It is used for identifiers in binding\nposition, where `_` means that the value should be left unnamed and inaccessible.\n-/\nsyntax binderIdent := ident <|> hole\n\nnamespace Parser.Tactic\n\n/--\nA case tag argument has the form `tag x₁ ... xₙ`; it refers to tag `tag` and renames\nthe last `n` hypotheses to `x₁ ... xₙ`.\n-/\nsyntax caseArg := binderIdent binderIdent*\n\nend Parser.Tactic\nend Lean\n\n@[inherit_doc dite] syntax (name := termDepIfThenElse)\n ppRealGroup(ppRealFill(ppIndent(\"if \" Lean.binderIdent \" : \" term \" then\") ppSpace term)\n ppDedent(ppSpace) ppRealFill(\"else \" term)) : term\n\nmacro_rules\n | `(if $h:ident : $c then $t else $e) => do\n let mvar ← Lean.withRef c `(?m)\n `(let_mvar% ?m := $c; wait_if_type_mvar% ?m; dite $mvar (fun $h:ident => $t) (fun $h:ident => $e))\n | `(if _%$h : $c then $t else $e) => do\n let mvar ← Lean.withRef c `(?m)\n `(let_mvar% ?m := $c; wait_if_type_mvar% ?m; dite $mvar (fun _%$h => $t) (fun _%$h => $e))\n\n@[inherit_doc ite] syntax (name := termIfThenElse)\n ppRealGroup(ppRealFill(ppIndent(\"if \" term \" then\") ppSpace term)\n ppDedent(ppSpace) ppRealFill(\"else \" term)) : term\n\nmacro_rules\n | `(if $c then $t else $e) => do\n let mvar ← Lean.withRef c `(?m)\n `(let_mvar% ?m := $c; wait_if_type_mvar% ?m; ite $mvar $t $e)\n\n/--\n`if let pat := d then t else e` is a shorthand syntax for:\n```\nmatch d with\n| pat => t\n| _ => e\n```\nIt matches `d` against the pattern `pat` and the bindings are available in `t`.\nIf the pattern does not match, it returns `e` instead.\n-/\nsyntax (name := termIfLet)\n ppRealGroup(ppRealFill(ppIndent(\"if \" \"let \" term \" := \" term \" then\") ppSpace term)\n ppDedent(ppSpace) ppRealFill(\"else \" term)) : term\n\nmacro_rules\n | `(if let $pat := $d then $t else $e) =>\n `(match $d:term with | $pat => $t | _ => $e)\n\n@[inherit_doc cond] syntax (name := boolIfThenElse)\n ppRealGroup(ppRealFill(ppIndent(\"bif \" term \" then\") ppSpace term)\n ppDedent(ppSpace) ppRealFill(\"else \" term)) : term\n\nmacro_rules\n | `(bif $c then $t else $e) => `(cond $c $t $e)\n\n/--\nHaskell-like pipe operator `<|`. `f <| x` means the same as the same as `f x`,\nexcept that it parses `x` with lower precedence, which means that `f <| g <| x`\nis interpreted as `f (g x)` rather than `(f g) x`.\n-/\nsyntax:min term \" <| \" term:min : term\n\nmacro_rules\n | `($f $args* <| $a) => `($f $args* $a)\n | `($f <| $a) => `($f $a)\n\n/--\nHaskell-like pipe operator `|>`. `x |> f` means the same as the same as `f x`,\nand it chains such that `x |> f |> g` is interpreted as `g (f x)`.\n-/\nsyntax:min term \" |> \" term:min1 : term\n\nmacro_rules\n | `($a |> $f $args*) => `($f $args* $a)\n | `($a |> $f) => `($f $a)\n\n/--\nAlternative syntax for `<|`. `f $ x` means the same as the same as `f x`,\nexcept that it parses `x` with lower precedence, which means that `f $ g $ x`\nis interpreted as `f (g x)` rather than `(f g) x`.\n-/\n-- Note that we have a whitespace after `$` to avoid an ambiguity with antiquotations.\nsyntax:min term atomic(\" $\" ws) term:min : term\n\nmacro_rules\n | `($f $args* $ $a) => `($f $args* $a)\n | `($f $ $a) => `($f $a)\n\n@[inherit_doc Subtype] syntax \"{ \" withoutPosition(ident (\" : \" term)? \" // \" term) \" }\" : term\n\nmacro_rules\n | `({ $x : $type // $p }) => ``(Subtype (fun ($x:ident : $type) => $p))\n | `({ $x // $p }) => ``(Subtype (fun ($x:ident : _) => $p))\n\n/--\n`without_expected_type t` instructs Lean to elaborate `t` without an expected type.\nRecall that terms such as `match ... with ...` and `⟨...⟩` will postpone elaboration until\nexpected type is known. So, `without_expected_type` is not effective in this case.\n-/\nmacro \"without_expected_type \" x:term : term => `(let aux := $x; aux)\n\n/--\nThe syntax `[a, b, c]` is shorthand for `a :: b :: c :: []`, or\n`List.cons a (List.cons b (List.cons c List.nil))`. It allows conveniently constructing\nlist literals.\n\nFor lists of length at least 64, an alternative desugaring strategy is used\nwhich uses let bindings as intermediates as in\n`let left := [d, e, f]; a :: b :: c :: left` to avoid creating very deep expressions.\nNote that this changes the order of evaluation, although it should not be observable\nunless you use side effecting operations like `dbg_trace`.\n-/\nsyntax \"[\" withoutPosition(term,*) \"]\" : term\n\n/--\nAuxiliary syntax for implementing `[$elem,*]` list literal syntax.\nThe syntax `%[a,b,c|tail]` constructs a value equivalent to `a::b::c::tail`.\nIt uses binary partitioning to construct a tree of intermediate let bindings as in\n`let left := [d, e, f]; a :: b :: c :: left` to avoid creating very deep expressions.\n-/\nsyntax \"%[\" withoutPosition(term,* \"|\" term) \"]\" : term\n\nnamespace Lean\n\nmacro_rules\n | `([ $elems,* ]) => do\n -- NOTE: we do not have `TSepArray.getElems` yet at this point\n let rec expandListLit (i : Nat) (skip : Bool) (result : TSyntax `term) : MacroM Syntax := do\n match i, skip with\n | 0, _ => pure result\n | i+1, true => expandListLit i false result\n | i+1, false => expandListLit i true (← ``(List.cons $(⟨elems.elemsAndSeps.get! i⟩) $result))\n if elems.elemsAndSeps.size < 64 then\n expandListLit elems.elemsAndSeps.size false (← ``(List.nil))\n else\n `(%[ $elems,* | List.nil ])\n\n-- Declare `this` as a keyword that unhygienically binds to a scope-less `this` assumption (or other binding).\n-- The keyword prevents declaring a `this` binding except through metaprogramming, as is done by `have`/`show`.\n/-- Special identifier introduced by \"anonymous\" `have : ...`, `suffices p ...` etc. -/\nmacro tk:\"this\" : term =>\n return (⟨(Syntax.ident tk.getHeadInfo \"this\".toSubstring `this [])⟩ : TSyntax `term)\n\n/--\nCategory for carrying raw syntax trees between macros; any content is printed as is by the pretty printer.\nThe only accepted parser for this category is an antiquotation.\n-/\ndeclare_syntax_cat rawStx\n\ninstance : Coe Syntax (TSyntax `rawStx) where\n coe stx := ⟨stx⟩\n\n/-- `with_annotate_term stx e` annotates the lexical range of `stx : Syntax` with term info for `e`. -/\nscoped syntax (name := withAnnotateTerm) \"with_annotate_term \" rawStx ppSpace term : term\n\n/--\nThe attribute `@[deprecated]` on a declaration indicates that the declaration\nis discouraged for use in new code, and/or should be migrated away from in\nexisting code. It may be removed in a future version of the library.\n\n`@[deprecated myBetterDef]` means that `myBetterDef` is the suggested replacement.\n-/\nsyntax (name := deprecated) \"deprecated \" (ident)? : attr\n\n/--\nWhen `parent_dir` contains the current Lean file, `include_str \"path\" / \"to\" / \"file\"` becomes\na string literal with the contents of the file at `\"parent_dir\" / \"path\" / \"to\" / \"file\"`. If this\nfile cannot be read, elaboration fails.\n-/\nsyntax (name := includeStr) \"include_str\" term : term\n", "meta": {"author": "leanprover", "repo": "lean4", "sha": "742d053a97bdd109a41a921facd1cd6a55e89bc7", "save_path": "github-repos/lean/leanprover-lean4", "path": "github-repos/lean/leanprover-lean4/lean4-742d053a97bdd109a41a921facd1cd6a55e89bc7/src/Init/Notation.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1581743527484317, "lm_q2_score": 0.06278920947393588, "lm_q1q2_score": 0.009931642568125502}} {"text": "import Lbar.ext_aux3\nimport Lbar.iota\n\nnoncomputable theory\n\nuniverses v u u'\n\nopen opposite category_theory category_theory.limits category_theory.preadditive\nopen_locale nnreal zero_object\n\nvariables (r r' : ℝ≥0)\nvariables [fact (0 < r)] [fact (0 < r')] [fact (r < r')] [fact (r < 1)] [fact (r' < 1)]\n\nopen bounded_homotopy_category\n\nvariables {r'}\nvariables (BD : breen_deligne.package)\nvariables (κ κ₂ : ℝ≥0 → ℕ → ℝ≥0)\nvariables [∀ (c : ℝ≥0), BD.data.suitable (κ c)] [∀ n, fact (monotone (function.swap κ n))]\nvariables [∀ (c : ℝ≥0), BD.data.suitable (κ₂ c)] [∀ n, fact (monotone (function.swap κ₂ n))]\nvariables (M : ProFiltPseuNormGrpWithTinv₁.{u} r')\n\nsection preps\n\nvariables (V : SemiNormedGroup.{u}) [complete_space V] [separated_space V]\nvariables (ι : ulift.{u+1} ℕ → ℝ≥0) (hι : monotone ι)\n\nset_option pp.universes true\n\nlemma homotopy_category.colimit_cofan_bdd {A : Type u} [category.{v} A] [abelian A]\n[has_coproducts A] {α : Type v} (X : α → bounded_homotopy_category A)\n [uniformly_bounded X] : homotopy_category.is_bounded_above\n (homotopy_category.colimit_cofan $ λ a : α, (X a).val).X :=\nbegin\n obtain ⟨n,hn⟩ := homotopy_category.is_uniformly_bounded_above.cond (val ∘ X),\n use n, intros i hi,\n dsimp [homotopy_category.colimit_cofan],\n let e : (∐ λ (a : α), (X a).val.as).X i ≅\n (∐ λ (a : α), (X a).val.as.X i) := homotopy_category.coproduct_iso _ _,\n refine is_zero_of_iso_of_zero _ e.symm,\n apply category_theory.is_zero_colimit,\n intros j,\n apply hn j _ hi,\n end\n\ndef Tinv2_iso_of_bicartesian_aux_1\n (i : ℤ) : commsq.{u+2 u+1}\n (shift_sub_id.{u+1}\n ((QprimeFP.{u} r' BD.data κ₂ M).op ⋙\n (Ext.{u+1 u+2} i).flip.obj ((single.{u+1 u+2} (Condensed.{u u+1 u+2} Ab.{u+1}) 0).obj V.to_Cond))\n ι\n hι)\n (pi_Ext_iso_Ext_sigma.{u} BD κ₂ M V (λ (k : ulift.{u+1 0} ℕ), ι k) i).hom\n (pi_Ext_iso_Ext_sigma.{u} BD κ₂ M V (λ (k : ulift.{u+1 0} ℕ), ι k) i).hom\n (((Ext.{u+1 u+2} i).map\n (of_hom.{u+1 u+2} (QprimeFP.shift_sub_id.{u u+2 u+1} ι hι (QprimeFP_int.{u} r' BD.data κ₂ M))).op).app\n ((single.{u+1 u+2} (Condensed.{u u+1 u+2} Ab.{u+1}) 0).obj (Condensed.of_top_ab.{u} ↥V))) :=\nbegin\n apply commsq.of_eq,\n dsimp only [shift_sub_id, QprimeFP.shift_sub_id],\n simp only [sub_comp, comp_sub, homological_complex.of_hom_sub, category_theory.op_sub,\n functor.map_sub, op_id, category_theory.functor.map_id, of_hom_id,\n nat_trans.app_sub, nat_trans.id_app, category.comp_id, category.id_comp],\n apply congr_arg2 _ _ rfl,\n rw ← iso.eq_comp_inv,\n dsimp only [pi_Ext_iso_Ext_sigma, iso.trans_hom, iso.trans_inv,\n iso.symm_hom, iso.symm_inv, functor.map_iso_hom,\n iso.op_hom, op_comp, functor.flip_obj_map, functor.map_iso_inv],\n simp only [category.assoc, ← nat_trans.comp_app_assoc, ← functor.map_comp_assoc,\n ← functor.map_comp, iso.op_inv, ← op_comp],\n rw cofan_point_iso_colimit_conj_eq_desc,\n rw iso.eq_inv_comp,\n have := Ext_coproduct_iso_naturality_shift _\n (λ (k : ulift ℕ), (QprimeFP r' BD.data κ₂ M).obj (ι k))\n (λ k, (QprimeFP r' BD.data κ₂ M).map (hom_of_le $ hι $\n by exact_mod_cast k.down.le_succ)) i ((single (Condensed Ab) 0).obj V.to_Cond),\n exact this.symm,\n { apply homotopy_category.colimit_cofan_bdd },\nend\n\n@[reassoc]\nlemma Ext_coproduct_iso_π\n (A : Type u) [category.{v} A] [abelian A] [enough_projectives A] [has_coproducts A] [AB4 A]\n (X : ulift.{v} ℕ → bounded_homotopy_category A) [uniformly_bounded X] (i : ℤ) (Y) (k) :\n (Ext_coproduct_iso X i Y).hom ≫ pi.π _ k =\n ((Ext i).map $ quiver.hom.op $ sigma.ι _ _).app Y :=\nbegin\n dsimp only [Ext_coproduct_iso, iso.trans_hom, pi_iso, preadditive_yoneda_coproduct_iso,\n as_iso_hom, preadditive_yoneda_coproduct_to_product],\n simp only [category.assoc, limit.lift_π, limit.lift_π_assoc, fan.mk_π_app],\n dsimp only [Ext_iso, iso.symm_hom, functor.map_iso_hom, functor.map_iso_inv],\n simp only [← functor.map_comp, iso.op_hom, iso.op_inv, ← op_comp],\n dsimp only [Ext, Ext0, functor.comp_map, whiskering_left_obj_map, whisker_left_app,\n functor.flip_map_app, replacement_iso],\n congr' 2,\n simp only [category.assoc, iso.inv_comp_eq, quiver.hom.unop_op, unop_op, op_unop],\n apply lift_unique,\n simp only [category.assoc, iso.inv_comp_eq, quiver.hom.unop_op, unop_op, op_unop],\n erw lift_lifts,\n simp only [uniform_π, colimit.ι_desc, cofan.mk_ι_app, lift_lifts_assoc],\n refl,\nend\n\nlemma Tinv2_iso_of_bicartesian_aux_2\n [∀ c n, fact (κ₂ c n ≤ r' * κ c n)]\n (j) {e : (homotopy_category.colimit_cofan.{u+1 u+2}\n (λ (a : ulift.{u+1 0} ℕ),\n ((λ (k : ulift.{u+1 0} ℕ), (QprimeFP.{u} r' BD.data κ₂ M).obj (ι k)) a).val)).X.is_bounded_above } :\n ((cofan.{u+1 u+2} (λ (k : ulift.{u+1 0} ℕ), (QprimeFP.{u} r' BD.data κ₂ M).obj (ι k))).ι.app j ≫\n of_hom.{u+1 u+2} (sigma_map.{u u+2 u+1} ι (QprimeFP_int.Tinv.{u} BD.data κ₂ κ M))) ≫\n (cofan_point_iso_colimit.{u} (λ (k : ulift.{u+1 0} ℕ), (QprimeFP.{u} r' BD.data κ M).obj (ι k))).hom =\n (QprimeFP.Tinv _ _ _ _).app _ ≫\n sigma.ι (λ (k : ulift.{u+1 0} ℕ), (QprimeFP.{u} r' BD.data κ M).obj (ι k)) j :=\nbegin\n rw [← iso.eq_comp_inv], simp only [category.assoc, cofan_point_iso_colimit,\n colimit.comp_cocone_point_unique_up_to_iso_inv],\n dsimp only [bounded_homotopy_category.cofan, cofan.mk_ι_app, of_hom,\n homotopy_category.colimit_cofan, QprimeFP.Tinv, whisker_right_app,\n chain_complex.to_bounded_homotopy_category, functor.comp_map],\n erw [← (homotopy_category.quotient.{u+1 u+2 0} (Condensed.{u u+1 u+2} Ab.{u+1}) (complex_shape.up.{0} ℤ)).map_comp],\n erw [← (homotopy_category.quotient.{u+1 u+2 0} (Condensed.{u u+1 u+2} Ab.{u+1}) (complex_shape.up.{0} ℤ)).map_comp],\n congr' 1,\n dsimp only [sigma_map],\n erw [colimit.ι_desc],\n refl,\nend\n\nlemma Tinv2_iso_of_bicartesian_aux_3\n [∀ c n, fact (κ₂ c n ≤ κ c n)]\n [∀ c n, fact (κ₂ c n ≤ r' * κ c n)]\n (j)\n {e : (homotopy_category.colimit_cofan.{u+1 u+2}\n (λ (a : ulift.{u+1 0} ℕ),\n ((λ (k : ulift.{u+1 0} ℕ), (QprimeFP.{u} r' BD.data κ₂ M).obj (ι k)) a).val)).X.is_bounded_above} :\n (cofan.{u+1 u+2} (λ (k : ulift.{u+1 0} ℕ), (QprimeFP.{u} r' BD.data κ₂ M).obj (ι k))).ι.app j ≫\n of_hom.{u+1 u+2} (sigma_map.{u u+2 u+1} ι (QprimeFP_int.ι.{u} BD.data κ₂ κ M)) ≫\n (cofan_point_iso_colimit.{u} (λ (k : ulift.{u+1 0} ℕ), (QprimeFP.{u} r' BD.data κ M).obj (ι k))).hom =\n (QprimeFP.ι _ κ₂ κ M).app _ ≫\n sigma.ι ((λ (k : ulift.{u+1 0} ℕ), (QprimeFP.{u} r' BD.data κ M).obj (ι k))) j :=\nbegin\n simp only [← category.assoc], rw [← iso.eq_comp_inv],\n simp only [category.assoc, cofan_point_iso_colimit, colimit.comp_cocone_point_unique_up_to_iso_inv],\n dsimp only [bounded_homotopy_category.cofan, cofan.mk_ι_app, of_hom,\n homotopy_category.colimit_cofan, QprimeFP.ι, whisker_right_app,\n chain_complex.to_bounded_homotopy_category, functor.comp_map],\n erw [← (homotopy_category.quotient.{u+1 u+2 0} (Condensed.{u u+1 u+2} Ab.{u+1}) (complex_shape.up.{0} ℤ)).map_comp],\n erw [← (homotopy_category.quotient.{u+1 u+2 0} (Condensed.{u u+1 u+2} Ab.{u+1}) (complex_shape.up.{0} ℤ)).map_comp],\n congr' 1,\n dsimp only [sigma_map],\n erw [colimit.ι_desc],\n refl,\nend\n\nlemma Tinv2_iso_of_bicartesian_aux [normed_with_aut r V]\n [∀ c n, fact (κ₂ c n ≤ κ c n)] [∀ c n, fact (κ₂ c n ≤ r' * κ c n)]\n (i : ℤ)\n (H1 : (shift_sub_id.commsq (ExtQprime.Tinv2 r r' BD.data κ κ₂ M V i) ι hι).bicartesian) :\n (Ext_Tinv2_commsq (of_hom (sigma_map (λ (k : ulift ℕ), ι k) (QprimeFP_int.Tinv BD.data κ₂ κ M)))\n (of_hom (sigma_map (λ (k : ulift ℕ), ι k) (QprimeFP_int.ι BD.data κ₂ κ M)))\n (of_hom (sigma_map (λ (k : ulift ℕ), ι k) (QprimeFP_int.Tinv BD.data κ₂ κ M)))\n (of_hom (sigma_map (λ (k : ulift ℕ), ι k) (QprimeFP_int.ι BD.data κ₂ κ M)))\n (of_hom (QprimeFP.shift_sub_id ι hι (QprimeFP_int r' BD.data κ₂ M)))\n (of_hom (QprimeFP.shift_sub_id ι hι (QprimeFP_int r' BD.data κ M)))\n (auux $ commsq_shift_sub_id_Tinv _ _ _ _ _ _)\n (auux $ commsq_shift_sub_id_ι _ _ _ _ _ _)\n ((single _ 0).map (Condensed.of_top_ab_map (normed_group_hom.to_add_monoid_hom (normed_with_aut.T.inv : V ⟶ V)) (normed_group_hom.continuous _)))\n i).bicartesian :=\nbegin\n have h1 := _, have h2 := _, have h3 := _,\n refine commsq.bicartesian.of_iso\n (pi_Ext_iso_Ext_sigma _ _ _ _ _ _) (pi_Ext_iso_Ext_sigma _ _ _ _ _ _)\n (pi_Ext_iso_Ext_sigma _ _ _ _ _ _) (pi_Ext_iso_Ext_sigma _ _ _ _ _ _)\n h1 h2 h2 h3 H1,\n apply Tinv2_iso_of_bicartesian_aux_1,\n { clear h1, apply commsq.of_eq, rw ← iso.eq_comp_inv,\n apply limit.hom_ext, intros j, rw lim_map_π,\n dsimp [pi_Ext_iso_Ext_sigma],\n simp only [category.assoc],\n have := Ext_coproduct_iso_π _\n (λ (k : ulift.{u+1 0} ℕ), (QprimeFP.{u} r' BD.data κ₂ M).obj (ι k))\n i ((single.{u+1 u+2} (Condensed.{u u+1 u+2} Ab.{u+1}) 0).obj V.to_Cond) j,\n rw [this, ← nat_trans.comp_app, ← functor.map_comp, ← op_comp],\n clear this,\n erw colimit.ι_desc,\n dsimp [Ext_Tinv2, ExtQprime.Tinv2],\n simp only [sub_comp, comp_sub],\n refine congr_arg2 _ _ _,\n { simp only [← nat_trans.comp_app, ← functor.map_comp, ← op_comp],\n rw Tinv2_iso_of_bicartesian_aux_2,\n swap,\n { apply homotopy_category.colimit_cofan_bdd },\n simp only [functor.map_comp, op_comp, nat_trans.comp_app, category.assoc],\n have := Ext_coproduct_iso_π _\n (λ (k : ulift.{u+1 0} ℕ), (QprimeFP.{u} r' BD.data κ M).obj (ι k))\n i ((single.{u+1 u+2} (Condensed.{u u+1 u+2} Ab.{u+1}) 0).obj V.to_Cond) j,\n rw ← iso.eq_inv_comp at this,\n rw ← reassoc_of this, refl },\n { simp only [category.assoc, nat_trans.naturality, ← nat_trans.comp_app_assoc,\n ← functor.map_comp_assoc, ← functor.map_comp, ← nat_trans.comp_app, ← op_comp],\n rw Tinv2_iso_of_bicartesian_aux_3,\n simp only [functor.map_comp, op_comp, nat_trans.comp_app, category.assoc],\n have := Ext_coproduct_iso_π _\n (λ (k : ulift.{u+1 0} ℕ), (QprimeFP.{u} r' BD.data κ M).obj (ι k))\n i ((single.{u+1 u+2} (Condensed.{u u+1 u+2} Ab.{u+1}) 0).obj V.to_Cond) j,\n rw ← iso.eq_inv_comp at this,\n rw ← reassoc_of this,\n refl,\n { apply homotopy_category.colimit_cofan_bdd } } },\n apply Tinv2_iso_of_bicartesian_aux_1,\nend\n\nlemma Tinv2_iso_of_bicartesian [normed_with_aut r V]\n [∀ c n, fact (κ₂ c n ≤ κ c n)] [∀ c n, fact (κ₂ c n ≤ r' * κ c n)]\n (hκ : Lbar.sufficiently_increasing κ ι)\n (hκ₂ : Lbar.sufficiently_increasing κ₂ ι)\n (i : ℤ)\n (H1 : (shift_sub_id.commsq (ExtQprime.Tinv2 r r' BD.data κ κ₂ M V i) ι hι).bicartesian)\n (H2 : (shift_sub_id.commsq (ExtQprime.Tinv2 r r' BD.data κ κ₂ M V (i+1)) ι hι).bicartesian) :\n is_iso (((Ext (i+1)).map ((BD.eval freeCond'.{u}).map M.Tinv_cond).op).app\n ((single (Condensed Ab) 0).obj V.to_Cond) -\n ((Ext (i+1)).obj ((BD.eval freeCond').op.obj (op (M.to_Condensed)))).map\n ((single (Condensed Ab) 0).map\n (Condensed.of_top_ab_map\n (normed_group_hom.to_add_monoid_hom normed_with_aut.T.inv) (normed_group_hom.continuous _)))) :=\nbegin\n let Vc := (single (Condensed Ab) 0).obj V.to_Cond,\n have SES₁ := QprimeFP.short_exact BD κ₂ M ι hι hκ₂,\n have SES₂ := QprimeFP.short_exact BD κ M ι hι hκ,\n have := Ext_iso_of_bicartesian_of_bicartesian SES₁ SES₂\n (sigma_map _ (QprimeFP_int.Tinv BD.data _ _ M))\n (sigma_map _ (QprimeFP_int.Tinv BD.data _ _ M))\n (category_theory.functor.map _ M.Tinv_cond)\n (sigma_map _ (QprimeFP_int.ι BD.data _ _ M))\n (sigma_map _ (QprimeFP_int.ι BD.data _ _ M))\n (commsq_shift_sub_id_Tinv BD.data _ _ M ι hι)\n (commsq_sigma_proj_Tinv BD _ _ M ι)\n (commsq_shift_sub_id_ι BD.data _ _ M ι hι)\n (commsq_sigma_proj_ι BD _ _ M ι)\n Vc ((single _ _).map $ Condensed.of_top_ab_map\n (normed_group_hom.to_add_monoid_hom normed_with_aut.T.inv) (normed_group_hom.continuous _))\n _\n (Tinv2_iso_of_bicartesian_aux _ _ _ _ _ _ _ _ _ H1)\n (Tinv2_iso_of_bicartesian_aux _ _ _ _ _ _ _ _ _ H2),\n delta Ext_Tinv2 at this,\n simpa only [op_id, category_theory.functor.map_id, category.id_comp, nat_trans.id_app],\nend\n\nlemma Tinv2_iso_of_bicartesian' [normed_with_aut r V]\n [∀ c n, fact (κ₂ c n ≤ κ c n)] [∀ c n, fact (κ₂ c n ≤ r' * κ c n)]\n (H : ∀ i, ∃ (ι) (hι),\n Lbar.sufficiently_increasing κ ι ∧\n Lbar.sufficiently_increasing κ₂ ι ∧\n (shift_sub_id.commsq (ExtQprime.Tinv2 r r' BD.data κ κ₂ M V i) ι hι).bicartesian ∧\n (shift_sub_id.commsq (ExtQprime.Tinv2 r r' BD.data κ κ₂ M V (i+1)) ι hι).bicartesian)\n (i : ℤ) :\n is_iso (((Ext i).map ((BD.eval freeCond'.{u}).map M.Tinv_cond).op).app\n ((single (Condensed Ab) 0).obj V.to_Cond) -\n ((Ext i).obj ((BD.eval freeCond').op.obj (op (M.to_Condensed)))).map\n ((single (Condensed Ab) 0).map\n (Condensed.of_top_ab_map\n (normed_group_hom.to_add_monoid_hom normed_with_aut.T.inv) (normed_group_hom.continuous _)))) :=\nbegin\n obtain ⟨i, rfl⟩ : ∃ k, k+1 = i := ⟨i-1, sub_add_cancel _ _⟩,\n obtain ⟨ι, hι, hκ, hκ₂, H1, H2⟩ := H i,\n apply Tinv2_iso_of_bicartesian _ _ _ _ _ _ ι hι hκ hκ₂ i H1 H2,\nend\n\nend preps\n", "meta": {"author": "bentoner", "repo": "debug", "sha": "b8a75381caa90aa9942c20e08a44e45d0ae60d18", "save_path": "github-repos/lean/bentoner-debug", "path": "github-repos/lean/bentoner-debug/debug-b8a75381caa90aa9942c20e08a44e45d0ae60d18/src/Lbar/ext_aux4.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4455295350395727, "lm_q2_score": 0.022286184646330698, "lm_q1q2_score": 0.00992915348328578}} {"text": "import ReactorModel.Determinism.InstantaneousStep\n\nopen Classical\n\nnamespace Execution\nnamespace Instantaneous\nnamespace Execution\n \nvariable [ReactorType.Indexable α] {s₁ s₂ : State α}\n\ntheorem progress_not_mem_rcns (e : s₁ ⇓ᵢ* s₂) (h : rcn ∈ s₁.progress) : rcn ∉ e.rcns := by\n induction e <;> simp [rcns, not_or]\n case trans e e' hi =>\n simp [hi $ e.monotonic_progress h]\n intro hc\n exact absurd (hc ▸ h) e.rcn_not_mem_progress\n\ntheorem mem_progress_iff (e : s₁ ⇓ᵢ* s₂) : \n (rcn ∈ s₂.progress) ↔ (rcn ∈ e.rcns ∨ rcn ∈ s₁.progress) := by\n induction e <;> simp [rcns]\n case trans s₁ s₂ s₃ e e' hi => \n simp [hi]\n constructor <;> intro\n all_goals repeat cases ‹_ ∨ _› <;> simp [*]\n case mp.inr h => cases e.mem_progress_iff.mp h <;> simp [*]\n case mpr.inl.inl h => simp [e.rcn_mem_progress]\n case mpr.inr h => simp [e.monotonic_progress h]\n \n-- Corollary of `InstExecution.mem_progress_iff`.\ntheorem rcns_mem_progress (e : s₁ ⇓ᵢ* s₂) (h : rcn ∈ e.rcns) : rcn ∈ s₂.progress := \n e.mem_progress_iff.mpr $ .inl h\n\ntheorem rcns_nodup {s₁ s₂ : State α} : (e : s₁ ⇓ᵢ* s₂) → e.rcns.Nodup\n | refl => List.nodup_nil\n | trans e e' => List.nodup_cons.mpr ⟨e'.progress_not_mem_rcns e.rcn_mem_progress, e'.rcns_nodup⟩\n\ntheorem progress_eq_rcns_perm \n (e₁ : s ⇓ᵢ* s₁) (e₂ : s ⇓ᵢ* s₂) (hp : s₁.progress = s₂.progress) : e₁.rcns ~ e₂.rcns := by\n apply List.perm_ext e₁.rcns_nodup e₂.rcns_nodup |>.mpr\n intro rcn\n by_cases hc : rcn ∈ s.progress\n case pos => simp [e₁.progress_not_mem_rcns hc, e₂.progress_not_mem_rcns hc]\n case neg =>\n constructor <;> intro hm\n case mp => exact e₂.mem_progress_iff.mp (hp ▸ e₁.rcns_mem_progress hm) |>.resolve_right hc\n case mpr => exact e₁.mem_progress_iff.mp (hp ▸ e₂.rcns_mem_progress hm) |>.resolve_right hc\n\ntheorem preserves_tag {s₁ s₂ : State α} : (s₁ ⇓ᵢ* s₂) → s₁.tag = s₂.tag\n | refl => rfl\n | trans e e' => e.preserves_tag.trans e'.preserves_tag\n\ntheorem rcns_trans_eq_cons (e₁ : s ⇓ᵢ s₁) (e₂ : s₁ ⇓ᵢ* s₂) : \n (trans e₁ e₂).rcns = e₁.rcn :: e₂.rcns := by\n simp [rcns, Step.rcn]\n\ntheorem progress_eq {s₁ s₂ : State α} : \n (e : s₁ ⇓ᵢ* s₂) → s₂.progress = s₁.progress ∪ { i | i ∈ e.rcns }\n | refl => by simp [rcns]\n | trans e e' => by \n simp [e.progress_eq ▸ e'.progress_eq, rcns_trans_eq_cons]\n apply Set.insert_union'\n\ntheorem mem_rcns_not_mem_progress (e : s₁ ⇓ᵢ* s₂) (h : rcn ∈ e.rcns) : rcn ∉ s₁.progress := by\n induction e\n case refl => contradiction\n case trans e e' hi =>\n cases e'.rcns_trans_eq_cons e ▸ h\n case head => exact e.rcn_not_mem_progress\n case tail h => exact mt e.monotonic_progress (hi h)\n\ntheorem mem_rcns_iff (e : s₁ ⇓ᵢ* s₂) : rcn ∈ e.rcns ↔ (rcn ∈ s₂.progress ∧ rcn ∉ s₁.progress) := by\n simp [e.progress_eq, s₁.mem_record'_progress_iff e.rcns rcn, or_and_right]\n exact e.mem_rcns_not_mem_progress\n\ntheorem equiv {s₁ s₂ : State α} : (s₁ ⇓ᵢ* s₂) → s₁.rtr ≈ s₂.rtr\n | refl => .refl\n | trans e e' => ReactorType.Equivalent.trans e.equiv e'.equiv\n\ntheorem head_minimal (e : s₁ ⇓ᵢ s₂) (e' : s₂ ⇓ᵢ* s₃) : (e.rcn :: e'.rcns) ≮[s₁.rtr] e.rcn := by\n by_contra hc\n simp [Minimal] at hc\n have ⟨_, hm, h⟩ := hc e.acyclic\n replace hc := mt e.monotonic_progress $ e'.mem_rcns_not_mem_progress hm\n exact absurd (e.allows_rcn.deps h) hc\n\ntheorem head_not_mem_tail (e : s₁ ⇓ᵢ s₂) (e' : s₂ ⇓ᵢ* s₃) (h : i ∈ e'.rcns) : e.rcn ≠ i := by\n intro hc\n have := trans e e' |>.rcns_nodup\n have := hc.symm ▸ List.not_nodup_cons_of_mem h\n contradiction\n\n-- The core lemma for `prepend_minimal`.\ntheorem cons_prepend_minimal \n (e : s₁ ⇓ᵢ s₂) (e' : s₂ ⇓ᵢ* s₃) (hm : i ∈ e'.rcns) (hr : (e.rcn :: e'.rcns) ≮[s₁.rtr] i) : \n ∃ f : s₁ ⇓ᵢ* s₃, f.rcns = i :: e.rcn :: (e'.rcns.erase i) := by\n induction e' generalizing s₁ <;> simp [rcns] at *\n case trans s₁ s₂ s₄ e' e'' hi =>\n cases hm\n case inl hm =>\n simp [hm] at hr\n have ⟨_, f, f', ⟨hf₁, hf₂⟩⟩ := e.prepend_indep e' hr.cons_head\n exists trans f $ trans f' e''\n simp [hm, rcns, ←hf₁, ←hf₂]\n case inr hm =>\n have ⟨f, hf⟩ := hi e' hm $ hr.cons_tail.equiv e.equiv\n cases f <;> simp [rcns] at hf\n case trans f f'' =>\n have ⟨h₁, h₂⟩ := hf\n have ⟨_, f, f', ⟨hf₁, hf₂⟩⟩ := e.prepend_indep f $ h₁.symm ▸ hr |>.cons_head\n exists trans f $ trans f' f''\n simp [rcns, hf₁, h₁, hf₂, h₂, e''.rcns.erase_cons_tail $ head_not_mem_tail e' e'' hm]\n\ntheorem prepend_minimal (e : s₁ ⇓ᵢ* s₂) (hm : i ∈ e.rcns) (hr : e.rcns ≮[s₁.rtr] i) :\n ∃ (e' : s₁ ⇓ᵢ* s₂), e'.rcns = i :: (e.rcns.erase i) := by\n cases e <;> simp [rcns] at *; cases ‹_ ∨ _› \n case trans.inl e e' h =>\n exists trans e e'\n simp [rcns, h]\n case trans.inr e e' h =>\n exact e'.rcns.erase_cons_tail (head_not_mem_tail e e' h) ▸ cons_prepend_minimal e e' h hr\n \ntheorem rcns_perm_deterministic \n (e₁ : s ⇓ᵢ* s₁) (e₂ : s ⇓ᵢ* s₂) (hp : e₁.rcns ~ e₂.rcns) : s₁.rtr = s₂.rtr := by\n induction e₁\n case refl => cases e₂ <;> simp [rcns] at hp ⊢ \n case trans s sₘ₁ s₁ e₁ e₁' hi =>\n have hm := hp.mem_iff.mp $ List.mem_cons_self _ _\n have hm' := e₁'.head_minimal e₁ |>.perm hp\n have ⟨e₂, he₂⟩ := e₂.prepend_minimal hm hm'\n cases e₂ <;> simp [rcns] at he₂\n case trans sₘ₂ e₂ e₂' =>\n have ⟨h, h'⟩ := he₂ \n cases e₁.deterministic e₂ h.symm\n apply hi e₂'\n rw [h']\n exact List.perm_cons _ |>.mp (hp.trans $ List.perm_cons_erase hm)\n\nprotected theorem deterministic \n (e₁ : s ⇓ᵢ* s₁) (e₂ : s ⇓ᵢ* s₂) (ht : s₁.tag = s₂.tag) (hp : s₁.progress = s₂.progress) : \n s₁ = s₂ := by\n ext1 <;> try assumption\n exact rcns_perm_deterministic e₁ e₂ $ progress_eq_rcns_perm e₁ e₂ hp\n\nend Execution\nend Instantaneous\nend Execution", "meta": {"author": "marcusrossel", "repo": "reactor-model", "sha": "f82fffb489b4352a0cc6bee964d44a142fee18ce", "save_path": "github-repos/lean/marcusrossel-reactor-model", "path": "github-repos/lean/marcusrossel-reactor-model/reactor-model-f82fffb489b4352a0cc6bee964d44a142fee18ce/src/ReactorModel/Determinism/InstantaneousExecution.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3380771374883919, "lm_q2_score": 0.029312231281335192, "lm_q1q2_score": 0.0099097952449915}} {"text": "/-\nCopyright (c) 2021 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Leonardo de Moura\n-/\nimport Lean.Meta.Match.Match\nimport Lean.Meta.Match.MatchEqsExt\nimport Lean.Meta.Tactic.Apply\nimport Lean.Meta.Tactic.Refl\nimport Lean.Meta.Tactic.Delta\nimport Lean.Meta.Tactic.SplitIf\nimport Lean.Meta.Tactic.Injection\nimport Lean.Meta.Tactic.Contradiction\n\nnamespace Lean.Meta\n\n/--\n Helper method for `proveCondEqThm`. Given a goal of the form `C.rec ... xMajor = rhs`,\n apply `cases xMajor`. -/\npartial def casesOnStuckLHS (mvarId : MVarId) : MetaM (Array MVarId) := do\n let target ← mvarId.getType\n if let some (_, lhs, _) ← matchEq? target then\n if let some fvarId ← findFVar? lhs then\n return (← mvarId.cases fvarId).map fun s => s.mvarId\n throwError \"'casesOnStuckLHS' failed\"\nwhere\n findFVar? (e : Expr) : MetaM (Option FVarId) := do\n match e.getAppFn with\n | Expr.proj _ _ e => findFVar? e\n | f =>\n if !f.isConst then\n return none\n else\n let declName := f.constName!\n let args := e.getAppArgs\n match (← getProjectionFnInfo? declName) with\n | some projInfo =>\n if projInfo.numParams < args.size then\n findFVar? args[projInfo.numParams]!\n else\n return none\n | none =>\n matchConstRec f (fun _ => return none) fun recVal _ => do\n if recVal.getMajorIdx >= args.size then\n return none\n let major := args[recVal.getMajorIdx]!\n if major.isFVar then\n return some major.fvarId!\n else\n return none\n\ndef casesOnStuckLHS? (mvarId : MVarId) : MetaM (Option (Array MVarId)) := do\n try casesOnStuckLHS mvarId catch _ => return none\n\nnamespace Match\n\ndef unfoldNamedPattern (e : Expr) : MetaM Expr := do\n let visit (e : Expr) : MetaM TransformStep := do\n if let some e := isNamedPattern? e then\n if let some eNew ← unfoldDefinition? e then\n return TransformStep.visit eNew\n return .continue\n Meta.transform e (pre := visit)\n\n/--\n Similar to `forallTelescopeReducing`, but\n\n 1. Eliminates arguments for named parameters and the associated equation proofs.\n\n 2. Equality parameters associated with the `h : discr` notation are replaced with `rfl` proofs.\n Recall that this kind of parameter always occurs after the parameters correspoting to pattern variables.\n `numNonEqParams` is the size of the prefix.\n\n The continuation `k` takes four arguments `ys args mask type`.\n - `ys` are variables for the hypotheses that have not been eliminated.\n - `eqs` are variables for equality hypotheses associated with discriminants annotated with `h : discr`.\n - `args` are the arguments for the alternative `alt` that has type `altType`. `ys.size <= args.size`\n - `mask[i]` is true if the hypotheses has not been eliminated. `mask.size == args.size`.\n - `type` is the resulting type for `altType`.\n\n We use the `mask` to build the splitter proof. See `mkSplitterProof`.\n-/\npartial def forallAltTelescope (altType : Expr) (numNonEqParams : Nat)\n (k : (ys : Array Expr) → (eqs : Array Expr) → (args : Array Expr) → (mask : Array Bool) → (type : Expr) → MetaM α)\n : MetaM α := do\n go #[] #[] #[] #[] 0 altType\nwhere\n go (ys : Array Expr) (eqs : Array Expr) (args : Array Expr) (mask : Array Bool) (i : Nat) (type : Expr) : MetaM α := do\n let type ← whnfForall type\n match type with\n | Expr.forallE n d b .. =>\n if i < numNonEqParams then\n let d ← unfoldNamedPattern d\n withLocalDeclD n d fun y => do\n let typeNew := b.instantiate1 y\n if let some (_, lhs, rhs) ← matchEq? d then\n if lhs.isFVar && ys.contains lhs && args.contains lhs && isNamedPatternProof typeNew y then\n let some i := ys.getIdx? lhs | unreachable!\n let ys := ys.eraseIdx i\n let some j := args.getIdx? lhs | unreachable!\n let mask := mask.set! j false\n let args := args.map fun arg => if arg == lhs then rhs else arg\n let args := args.push (← mkEqRefl rhs)\n let typeNew := typeNew.replaceFVar lhs rhs\n return (← go ys eqs args (mask.push false) (i+1) typeNew)\n go (ys.push y) eqs (args.push y) (mask.push true) (i+1) typeNew\n else\n let arg ← if let some (_, _, rhs) ← matchEq? d then\n mkEqRefl rhs\n else if let some (_, _, _, rhs) ← matchHEq? d then\n mkHEqRefl rhs\n else\n throwError \"unexpected match alternative type{indentExpr altType}\"\n withLocalDeclD n d fun eq => do\n let typeNew := b.instantiate1 eq\n go ys (eqs.push eq) (args.push arg) (mask.push false) (i+1) typeNew\n | _ =>\n let type ← unfoldNamedPattern type\n /- Recall that alternatives that do not have variables have a `Unit` parameter to ensure\n they are not eagerly evaluated. -/\n if ys.size == 1 then\n if (← inferType ys[0]!).isConstOf ``Unit && !(← dependsOn type ys[0]!.fvarId!) then\n return (← k #[] #[] #[mkConst ``Unit.unit] #[false] type)\n k ys eqs args mask type\n\n isNamedPatternProof (type : Expr) (h : Expr) : Bool :=\n Option.isSome <| type.find? fun e =>\n if let some e := isNamedPattern? e then\n e.appArg! == h\n else\n false\n\nnamespace SimpH\n\n/--\n State for the equational theorem hypothesis simplifier.\n\n Recall that each equation contains additional hypotheses to ensure the associated case does not taken by previous cases.\n We have one hypothesis for each previous case.\n\n Each hypothesis is of the form `forall xs, eqs → False`\n\n We use tactics to minimize code duplication.\n-/\nstructure State where\n mvarId : MVarId -- Goal representing the hypothesis\n xs : List FVarId -- Pattern variables for a previous case\n eqs : List FVarId -- Equations to be processed\n eqsNew : List FVarId := [] -- Simplied (already processed) equations\n\nabbrev M := StateRefT State MetaM\n\n/--\n Apply the given substitution to `fvarIds`.\n This is an auxiliary method for `substRHS`.\n-/\nprivate def applySubst (s : FVarSubst) (fvarIds : List FVarId) : List FVarId :=\n fvarIds.filterMap fun fvarId => match s.apply (mkFVar fvarId) with\n | Expr.fvar fvarId .. => some fvarId\n | _ => none\n\n/--\n Given an equation of the form `lhs = rhs` where `rhs` is variable in `xs`,\n the replace it everywhere with `lhs`.\n-/\nprivate def substRHS (eq : FVarId) (rhs : FVarId) : M Unit := do\n assert! (← get).xs.contains rhs\n let (subst, mvarId) ← substCore (← get).mvarId eq (symm := true)\n modify fun s => { s with\n mvarId,\n xs := applySubst subst (s.xs.erase rhs)\n eqs := applySubst subst s.eqs\n eqsNew := applySubst subst s.eqsNew\n }\n\nprivate def isDone : M Bool :=\n return (← get).eqs.isEmpty\n\n/-- Customized `contradiction` tactic for `simpH?` -/\nprivate def contradiction (mvarId : MVarId) : MetaM Bool :=\n mvarId.contradictionCore { genDiseq := false, emptyType := false }\n\n/--\n Auxiliary tactic that tries to replace as many variables as possible and then apply `contradiction`.\n We use it to discard redundant hypotheses.\n-/\npartial def trySubstVarsAndContradiction (mvarId : MVarId) : MetaM Bool :=\n commitWhen do\n let mvarId ← substVars mvarId\n match (← injections mvarId) with\n | .solved => return true -- closed goal\n | .subgoal mvarId' _ =>\n if mvarId' == mvarId then\n contradiction mvarId\n else\n trySubstVarsAndContradiction mvarId'\n\nprivate def processNextEq : M Bool := do\n let s ← get\n s.mvarId.withContext do\n -- If the goal is contradictory, the hypothesis is redundant.\n if (← contradiction s.mvarId) then\n return false\n if let eq :: eqs := s.eqs then\n modify fun s => { s with eqs }\n let eqType ← inferType (mkFVar eq)\n -- See `substRHS`. Recall that if `rhs` is a variable then if must be in `s.xs`\n if let some (_, lhs, rhs) ← matchEq? eqType then\n if (← isDefEq lhs rhs) then\n return true\n if rhs.isFVar then\n substRHS eq rhs.fvarId!\n return true\n if let some (α, lhs, β, rhs) ← matchHEq? eqType then\n -- Try to convert `HEq` into `Eq`\n if (← isDefEq α β) then\n let (eqNew, mvarId) ← heqToEq s.mvarId eq (tryToClear := true)\n modify fun s => { s with mvarId, eqs := eqNew :: s.eqs }\n return true\n -- If it is not possible, we try to show the hypothesis is redundant by substituting even variables that are not at `s.xs`, and then use contradiction.\n else\n match lhs.isConstructorApp? (← getEnv), rhs.isConstructorApp? (← getEnv) with\n | some lhsCtor, some rhsCtor =>\n if lhsCtor.name != rhsCtor.name then\n return false -- If the constructors are different, we can discard the hypothesis even if it a heterogeneous equality\n else if (← trySubstVarsAndContradiction s.mvarId) then\n return false\n | _, _ =>\n if (← trySubstVarsAndContradiction s.mvarId) then\n return false\n try\n -- Try to simplify equation using `injection` tactic.\n match (← injection s.mvarId eq) with\n | InjectionResult.solved => return false\n | InjectionResult.subgoal mvarId eqNews .. =>\n modify fun s => { s with mvarId, eqs := eqNews.toList ++ s.eqs }\n catch _ =>\n modify fun s => { s with eqsNew := eq :: s.eqsNew }\n return true\n\npartial def go : M Bool := do\n if (← isDone) then\n return true\n else if (← processNextEq) then\n go\n else\n return false\n\nend SimpH\n\n/--\n Auxiliary method for simplifying equational theorem hypotheses.\n\n Recall that each equation contains additional hypotheses to ensure the associated case was not taken by previous cases.\n We have one hypothesis for each previous case.\n-/\nprivate partial def simpH? (h : Expr) (numEqs : Nat) : MetaM (Option Expr) := withDefault do\n let numVars ← forallTelescope h fun ys _ => pure (ys.size - numEqs)\n let mvarId := (← mkFreshExprSyntheticOpaqueMVar h).mvarId!\n let (xs, mvarId) ← mvarId.introN numVars\n let (eqs, mvarId) ← mvarId.introN numEqs\n let (r, s) ← SimpH.go |>.run { mvarId, xs := xs.toList, eqs := eqs.toList }\n if r then\n s.mvarId.withContext do\n let eqs := s.eqsNew.reverse.toArray.map mkFVar\n let mut r ← mkForallFVars eqs (mkConst ``False)\n /- We only include variables in `xs` if there is a dependency. -/\n for x in s.xs.reverse do\n if (← dependsOn r x) then\n r ← mkForallFVars #[mkFVar x] r\n trace[Meta.Match.matchEqs] \"simplified hypothesis{indentExpr r}\"\n check r\n return some r\n else\n return none\n\nprivate def substSomeVar (mvarId : MVarId) : MetaM (Array MVarId) := mvarId.withContext do\n for localDecl in (← getLCtx) do\n if let some (_, lhs, rhs) ← matchEq? localDecl.type then\n if lhs.isFVar then\n if !(← dependsOn rhs lhs.fvarId!) then\n match (← subst? mvarId lhs.fvarId!) with\n | some mvarId => return #[mvarId]\n | none => pure ()\n throwError \"substSomeVar failed\"\n\n/--\n Helper method for proving a conditional equational theorem associated with an alternative of\n the `match`-eliminator `matchDeclName`. `type` contains the type of the theorem. -/\npartial def proveCondEqThm (matchDeclName : Name) (type : Expr) : MetaM Expr := withLCtx {} {} do\n let type ← instantiateMVars type\n forallTelescope type fun ys target => do\n let mvar0 ← mkFreshExprSyntheticOpaqueMVar target\n trace[Meta.Match.matchEqs] \"proveCondEqThm {mvar0.mvarId!}\"\n let mvarId ← mvar0.mvarId!.deltaTarget (· == matchDeclName)\n withDefault <| go mvarId 0\n mkLambdaFVars ys (← instantiateMVars mvar0)\nwhere\n go (mvarId : MVarId) (depth : Nat) : MetaM Unit := withIncRecDepth do\n trace[Meta.Match.matchEqs] \"proveCondEqThm.go {mvarId}\"\n let mvarId' ← mvarId.modifyTargetEqLHS whnfCore\n let mvarId := mvarId'\n let subgoals ←\n (do mvarId.refl; return #[])\n <|>\n (do mvarId.contradiction { genDiseq := true }; return #[])\n <|>\n (casesOnStuckLHS mvarId)\n <|>\n (do let mvarId' ← simpIfTarget mvarId (useDecide := true)\n if mvarId' == mvarId then throwError \"simpIf failed\"\n return #[mvarId'])\n <|>\n (do if let some (s₁, s₂) ← splitIfTarget? mvarId then\n let mvarId₁ ← trySubst s₁.mvarId s₁.fvarId\n return #[mvarId₁, s₂.mvarId]\n else\n throwError \"spliIf failed\")\n <|>\n (substSomeVar mvarId)\n <|>\n (throwError \"failed to generate equality theorems for `match` expression `{matchDeclName}`\\n{MessageData.ofGoal mvarId}\")\n subgoals.forM (go · (depth+1))\n\n\n/-- Construct new local declarations `xs` with types `altTypes`, and then execute `f xs` -/\nprivate partial def withSplitterAlts (altTypes : Array Expr) (f : Array Expr → MetaM α) : MetaM α := do\n let rec go (i : Nat) (xs : Array Expr) : MetaM α := do\n if h : i < altTypes.size then\n let hName := (`h).appendIndexAfter (i+1)\n withLocalDeclD hName (altTypes.get ⟨i, h⟩) fun x =>\n go (i+1) (xs.push x)\n else\n f xs\n go 0 #[]\n\ninductive InjectionAnyResult where\n | solved\n | failed\n | subgoal (mvarId : MVarId)\n\nprivate def injectionAnyCandidate? (type : Expr) : MetaM (Option (Expr × Expr)) := do\n if let some (_, lhs, rhs) ← matchEq? type then\n return some (lhs, rhs)\n else if let some (α, lhs, β, rhs) ← matchHEq? type then\n if (← isDefEq α β) then\n return some (lhs, rhs)\n return none\n\nprivate def injectionAny (mvarId : MVarId) : MetaM InjectionAnyResult :=\n mvarId.withContext do\n for localDecl in (← getLCtx) do\n if let some (lhs, rhs) ← injectionAnyCandidate? localDecl.type then\n unless (← isDefEq lhs rhs) do\n let lhs ← whnf lhs\n let rhs ← whnf rhs\n unless lhs.isNatLit && rhs.isNatLit do\n try\n match (← injection mvarId localDecl.fvarId) with\n | InjectionResult.solved => return InjectionAnyResult.solved\n | InjectionResult.subgoal mvarId .. => return InjectionAnyResult.subgoal mvarId\n catch ex =>\n trace[Meta.Match.matchEqs] \"injectionAnyFailed at {localDecl.userName}, error\\n{ex.toMessageData}\"\n pure ()\n return InjectionAnyResult.failed\n\n\nprivate abbrev ConvertM := ReaderT (FVarIdMap (Expr × Nat × Array Bool)) $ StateRefT (Array MVarId) MetaM\n\n/--\n Construct a proof for the splitter generated by `mkEquationsfor`.\n The proof uses the definition of the `match`-declaration as a template (argument `template`).\n - `alts` are free variables corresponding to alternatives of the `match` auxiliary declaration being processed.\n - `altNews` are the new free variables which contains aditional hypotheses that ensure they are only used\n when the previous overlapping alternatives are not applicable. -/\nprivate partial def mkSplitterProof (matchDeclName : Name) (template : Expr) (alts altsNew : Array Expr)\n (altsNewNumParams : Array Nat)\n (altArgMasks : Array (Array Bool)) : MetaM Expr := do\n trace[Meta.Match.matchEqs] \"proof template: {template}\"\n let map := mkMap\n let (proof, mvarIds) ← convertTemplate template |>.run map |>.run #[]\n trace[Meta.Match.matchEqs] \"splitter proof: {proof}\"\n for mvarId in mvarIds do\n proveSubgoal mvarId\n instantiateMVars proof\nwhere\n mkMap : FVarIdMap (Expr × Nat × Array Bool) := Id.run do\n let mut m := {}\n for alt in alts, altNew in altsNew, numParams in altsNewNumParams, argMask in altArgMasks do\n m := m.insert alt.fvarId! (altNew, numParams, argMask)\n return m\n\n trimFalseTrail (argMask : Array Bool) : Array Bool :=\n if argMask.isEmpty then\n argMask\n else if !argMask.back then\n trimFalseTrail argMask.pop\n else\n argMask\n\n /--\n Auxiliary function used at `convertTemplate` to decide whether to use `convertCastEqRec`.\n See `convertCastEqRec`. -/\n isCastEqRec (e : Expr) : ConvertM Bool := do\n -- TODO: we do not handle `Eq.rec` since we never found an example that needed it.\n -- If we find one we must extend `convertCastEqRec`.\n unless e.isAppOf ``Eq.ndrec do return false\n unless e.getAppNumArgs > 6 do return false\n for arg in e.getAppArgs[6:] do\n if arg.isFVar && (← read).contains arg.fvarId! then\n return true\n return true\n\n /--\n Auxiliary function used at `convertTemplate`. It is needed when the auxiliary `match` declaration had to refine the type of its\n minor premises during dependent pattern match. For an example, consider\n ```\n inductive Foo : Nat → Type _\n | nil : Foo 0\n | cons (t: Foo l): Foo l\n\n def Foo.bar (t₁: Foo l₁): Foo l₂ → Bool\n | cons s₁ => t₁.bar s₁\n | _ => false\n attribute [simp] Foo.bar\n ```\n The auxiliary `Foo.bar.match_1` is of the form\n ```\n def Foo.bar.match_1.{u_1} : {l₂ : Nat} →\n (t₂ : Foo l₂) →\n (motive : Foo l₂ → Sort u_1) →\n (t₂ : Foo l₂) → ((s₁ : Foo l₂) → motive (Foo.cons s₁)) → ((x : Foo l₂) → motive x) → motive t₂ :=\n fun {l₂} t₂ motive t₂_1 h_1 h_2 =>\n (fun t₂_2 =>\n Foo.casesOn (motive := fun a x => l₂ = a → HEq t₂_1 x → motive t₂_1) t₂_2\n (fun h =>\n Eq.ndrec (motive := fun {l₂} =>\n (t₂ t₂ : Foo l₂) →\n (motive : Foo l₂ → Sort u_1) →\n ((s₁ : Foo l₂) → motive (Foo.cons s₁)) → ((x : Foo l₂) → motive x) → HEq t₂ Foo.nil → motive t₂)\n (fun t₂ t₂ motive h_1 h_2 h => Eq.symm (eq_of_heq h) ▸ h_2 Foo.nil) (Eq.symm h) t₂ t₂_1 motive h_1 h_2) --- HERE\n fun {l} t h =>\n Eq.ndrec (motive := fun {l} => (t : Foo l) → HEq t₂_1 (Foo.cons t) → motive t₂_1)\n (fun t h => Eq.symm (eq_of_heq h) ▸ h_1 t) h t)\n t₂_1 (Eq.refl l₂) (HEq.refl t₂_1)\n ```\n The `HERE` comment marks the place where the type of `Foo.bar.match_1` minor premises `h_1` and `h_2` is being \"refined\"\n using `Eq.ndrec`.\n\n This function will adjust the motive and minor premise of the `Eq.ndrec` to reflect the new minor premises used in the\n corresponding splitter theorem.\n\n We may have to extend this function to handle `Eq.rec` too.\n\n This function was added to address issue #1179\n -/\n convertCastEqRec (e : Expr) : ConvertM Expr := do\n assert! (← isCastEqRec e)\n e.withApp fun f args => do\n let mut argsNew := args\n let mut isAlt := #[]\n for i in [6:args.size] do\n let arg := argsNew[i]!\n if arg.isFVar then\n match (← read).find? arg.fvarId! with\n | some (altNew, _, _) =>\n argsNew := argsNew.set! i altNew\n trace[Meta.Match.matchEqs] \"arg: {arg} : {← inferType arg}, altNew: {altNew} : {← inferType altNew}\"\n isAlt := isAlt.push true\n | none =>\n argsNew := argsNew.set! i (← convertTemplate arg)\n isAlt := isAlt.push false\n else\n argsNew := argsNew.set! i (← convertTemplate arg)\n isAlt := isAlt.push false\n assert! isAlt.size == args.size - 6\n let rhs := args[4]!\n let motive := args[2]!\n -- Construct new motive using the splitter theorem minor premise types.\n let motiveNew ← lambdaTelescope motive fun motiveArgs body => do\n unless motiveArgs.size == 1 do\n throwError \"unexpected `Eq.ndrec` motive while creating splitter/eliminator theorem for `{matchDeclName}`, expected lambda with 1 binder{indentExpr motive}\"\n let x := motiveArgs[0]!\n forallTelescopeReducing body fun motiveTypeArgs resultType => do\n unless motiveTypeArgs.size >= isAlt.size do\n throwError \"unexpected `Eq.ndrec` motive while creating splitter/eliminator theorem for `{matchDeclName}`, expected arrow with at least #{isAlt.size} binders{indentExpr body}\"\n let rec go (i : Nat) (motiveTypeArgsNew : Array Expr) : ConvertM Expr := do\n assert! motiveTypeArgsNew.size == i\n if h : i < motiveTypeArgs.size then\n let motiveTypeArg := motiveTypeArgs.get ⟨i, h⟩\n if i < isAlt.size && isAlt[i]! then\n let altNew := argsNew[6+i]! -- Recall that `Eq.ndrec` has 6 arguments\n let altTypeNew ← inferType altNew\n trace[Meta.Match.matchEqs] \"altNew: {altNew} : {altTypeNew}\"\n -- Replace `rhs` with `x` (the lambda binder in the motive)\n let mut altTypeNewAbst := (← kabstract altTypeNew rhs).instantiate1 x\n -- Replace args[6:6+i] with `motiveTypeArgsNew`\n for j in [:i] do\n altTypeNewAbst := (← kabstract altTypeNewAbst argsNew[6+j]!).instantiate1 motiveTypeArgsNew[j]!\n let localDecl ← motiveTypeArg.fvarId!.getDecl\n withLocalDecl localDecl.userName localDecl.binderInfo altTypeNewAbst fun motiveTypeArgNew =>\n go (i+1) (motiveTypeArgsNew.push motiveTypeArgNew)\n else\n go (i+1) (motiveTypeArgsNew.push motiveTypeArg)\n else\n mkLambdaFVars motiveArgs (← mkForallFVars motiveTypeArgsNew resultType)\n go 0 #[]\n trace[Meta.Match.matchEqs] \"new motive: {motiveNew}\"\n unless (← isTypeCorrect motiveNew) do\n throwError \"failed to construct new type correct motive for `Eq.ndrec` while creating splitter/eliminator theorem for `{matchDeclName}`{indentExpr motiveNew}\"\n argsNew := argsNew.set! 2 motiveNew\n -- Construct the new minor premise for the `Eq.ndrec` application.\n -- First, we use `eqRecNewPrefix` to infer the new minor premise binders for `Eq.ndrec`\n let eqRecNewPrefix := mkAppN f argsNew[:3] -- `Eq.ndrec` minor premise is the fourth argument.\n let .forallE _ minorTypeNew .. ← whnf (← inferType eqRecNewPrefix) | unreachable!\n trace[Meta.Match.matchEqs] \"new minor type: {minorTypeNew}\"\n let minor := args[3]!\n let minorNew ← forallBoundedTelescope minorTypeNew isAlt.size fun minorArgsNew _ => do\n let mut minorBodyNew := minor\n -- We have to extend the mapping to make sure `convertTemplate` can \"fix\" occurrences of the refined minor premises\n let mut m ← read\n for i in [:isAlt.size] do\n if isAlt[i]! then\n -- `convertTemplate` will correct occurrences of the alternative\n let alt := args[6+i]! -- Recall that `Eq.ndrec` has 6 arguments\n let some (_, numParams, argMask) := m.find? alt.fvarId! | unreachable!\n -- We add a new entry to `m` to make sure `convertTemplate` will correct the occurrences of the alternative\n m := m.insert minorArgsNew[i]!.fvarId! (minorArgsNew[i]!, numParams, argMask)\n unless minorBodyNew.isLambda do\n throwError \"unexpected `Eq.ndrec` minor premise while creating splitter/eliminator theorem for `{matchDeclName}`, expected lambda with at least #{isAlt.size} binders{indentExpr minor}\"\n minorBodyNew := minorBodyNew.bindingBody!\n minorBodyNew := minorBodyNew.instantiateRev minorArgsNew\n trace[Meta.Match.matchEqs] \"minor premise new body before convertTemplate:{indentExpr minorBodyNew}\"\n minorBodyNew ← withReader (fun _ => m) <| convertTemplate minorBodyNew\n trace[Meta.Match.matchEqs] \"minor premise new body after convertTemplate:{indentExpr minorBodyNew}\"\n mkLambdaFVars minorArgsNew minorBodyNew\n unless (← isTypeCorrect minorNew) do\n throwError \"failed to construct new type correct minor premise for `Eq.ndrec` while creating splitter/eliminator theorem for `{matchDeclName}`{indentExpr minorNew}\"\n argsNew := argsNew.set! 3 minorNew\n -- trace[Meta.Match.matchEqs] \"argsNew: {argsNew}\"\n trace[Meta.Match.matchEqs] \"found cast target {e}\"\n return mkAppN f argsNew\n\n convertTemplate (e : Expr) : ConvertM Expr :=\n transform e fun e => do\n if (← isCastEqRec e) then\n return .done (← convertCastEqRec e)\n else\n let Expr.fvar fvarId .. := e.getAppFn | return .continue\n let some (altNew, numParams, argMask) := (← read).find? fvarId | return .continue\n trace[Meta.Match.matchEqs] \">> argMask: {argMask}, e: {e}, {altNew}\"\n let mut newArgs := #[]\n let argMask := trimFalseTrail argMask\n unless e.getAppNumArgs ≥ argMask.size do\n throwError \"unexpected occurrence of `match`-expression alternative (aka minor premise) while creating splitter/eliminator theorem for `{matchDeclName}`, minor premise is partially applied{indentExpr e}\\npossible solution if you are matching on inductive families: add its indices as additional discriminants\"\n for arg in e.getAppArgs, includeArg in argMask do\n if includeArg then\n newArgs := newArgs.push arg\n let eNew := mkAppN altNew newArgs\n /- Recall that `numParams` does not include the equalities associated with discriminants of the form `h : discr`. -/\n let (mvars, _, _) ← forallMetaBoundedTelescope (← inferType eNew) (numParams - newArgs.size) (kind := MetavarKind.syntheticOpaque)\n modify fun s => s ++ (mvars.map (·.mvarId!))\n let eNew := mkAppN eNew mvars\n return TransformStep.done eNew\n\n proveSubgoalLoop (mvarId : MVarId) : MetaM Unit := do\n trace[Meta.Match.matchEqs] \"proveSubgoalLoop\\n{mvarId}\"\n match (← injectionAny mvarId) with\n | InjectionAnyResult.solved => return ()\n | InjectionAnyResult.failed =>\n let mvarId' ← substVars mvarId\n if mvarId' == mvarId then\n if (← mvarId.contradictionCore {}) then\n return ()\n throwError \"failed to generate splitter for match auxiliary declaration '{matchDeclName}', unsolved subgoal:\\n{MessageData.ofGoal mvarId}\"\n else\n proveSubgoalLoop mvarId'\n | InjectionAnyResult.subgoal mvarId => proveSubgoalLoop mvarId\n\n proveSubgoal (mvarId : MVarId) : MetaM Unit := do\n trace[Meta.Match.matchEqs] \"subgoal {mkMVar mvarId}, {repr (← mvarId.getDecl).kind}, {← mvarId.isAssigned}\\n{MessageData.ofGoal mvarId}\"\n let (_, mvarId) ← mvarId.intros\n let mvarId ← mvarId.tryClearMany (alts.map (·.fvarId!))\n proveSubgoalLoop mvarId\n\n/--\n Create new alternatives (aka minor premises) by replacing `discrs` with `patterns` at `alts`.\n Recall that `alts` depends on `discrs` when `numDiscrEqs > 0`, where `numDiscrEqs` is the number of discriminants\n annotated with `h : discr`.\n-/\nprivate partial def withNewAlts (numDiscrEqs : Nat) (discrs : Array Expr) (patterns : Array Expr) (alts : Array Expr) (k : Array Expr → MetaM α) : MetaM α :=\n if numDiscrEqs == 0 then\n k alts\n else\n go 0 #[]\nwhere\n go (i : Nat) (altsNew : Array Expr) : MetaM α := do\n if h : i < alts.size then\n let alt := alts.get ⟨i, h⟩\n let altLocalDecl ← getFVarLocalDecl alt\n let typeNew := altLocalDecl.type.replaceFVars discrs patterns\n withLocalDecl altLocalDecl.userName altLocalDecl.binderInfo typeNew fun altNew =>\n go (i+1) (altsNew.push altNew)\n else\n k altsNew\n\n/--\n Create conditional equations and splitter for the given match auxiliary declaration. -/\nprivate partial def mkEquationsFor (matchDeclName : Name) : MetaM MatchEqns := withLCtx {} {} do\n trace[Meta.Match.matchEqs] \"mkEquationsFor '{matchDeclName}'\"\n withConfig (fun c => { c with etaStruct := .none }) do\n let baseName := mkPrivateName (← getEnv) matchDeclName\n let constInfo ← getConstInfo matchDeclName\n let us := constInfo.levelParams.map mkLevelParam\n let some matchInfo ← getMatcherInfo? matchDeclName | throwError \"'{matchDeclName}' is not a matcher function\"\n let numDiscrEqs := getNumEqsFromDiscrInfos matchInfo.discrInfos\n forallTelescopeReducing constInfo.type fun xs matchResultType => do\n let mut eqnNames := #[]\n let params := xs[:matchInfo.numParams]\n let motive := xs[matchInfo.getMotivePos]!\n let alts := xs[xs.size - matchInfo.numAlts:]\n let firstDiscrIdx := matchInfo.numParams + 1\n let discrs := xs[firstDiscrIdx : firstDiscrIdx + matchInfo.numDiscrs]\n let mut notAlts := #[]\n let mut idx := 1\n let mut splitterAltTypes := #[]\n let mut splitterAltNumParams := #[]\n let mut altArgMasks := #[] -- masks produced by `forallAltTelescope`\n for i in [:alts.size] do\n let altNumParams := matchInfo.altNumParams[i]!\n let altNonEqNumParams := altNumParams - numDiscrEqs\n let thmName := baseName ++ ((`eq).appendIndexAfter idx)\n eqnNames := eqnNames.push thmName\n let (notAlt, splitterAltType, splitterAltNumParam, argMask) ← forallAltTelescope (← inferType alts[i]!) altNonEqNumParams fun ys eqs rhsArgs argMask altResultType => do\n let patterns := altResultType.getAppArgs\n let mut hs := #[]\n for notAlt in notAlts do\n let h ← instantiateForall notAlt patterns\n if let some h ← simpH? h patterns.size then\n hs := hs.push h\n trace[Meta.Match.matchEqs] \"hs: {hs}\"\n let splitterAltType ← mkForallFVars ys (← hs.foldrM (init := (← mkForallFVars eqs altResultType)) (mkArrow · ·))\n let splitterAltNumParam := hs.size + ys.size\n -- Create a proposition for representing terms that do not match `patterns`\n let mut notAlt := mkConst ``False\n for discr in discrs.toArray.reverse, pattern in patterns.reverse do\n notAlt ← mkArrow (← mkEqHEq discr pattern) notAlt\n notAlt ← mkForallFVars (discrs ++ ys) notAlt\n /- Recall that when we use the `h : discr`, the alternative type depends on the discriminant.\n Thus, we need to create new `alts`. -/\n withNewAlts numDiscrEqs discrs patterns alts fun alts => do\n let alt := alts[i]!\n let lhs := mkAppN (mkConst constInfo.name us) (params ++ #[motive] ++ patterns ++ alts)\n let rhs := mkAppN alt rhsArgs\n let thmType ← mkEq lhs rhs\n let thmType ← hs.foldrM (init := thmType) (mkArrow · ·)\n let thmType ← mkForallFVars (params ++ #[motive] ++ ys ++ alts) thmType\n let thmType ← unfoldNamedPattern thmType\n let thmVal ← proveCondEqThm matchDeclName thmType\n addDecl <| Declaration.thmDecl {\n name := thmName\n levelParams := constInfo.levelParams\n type := thmType\n value := thmVal\n }\n return (notAlt, splitterAltType, splitterAltNumParam, argMask)\n notAlts := notAlts.push notAlt\n splitterAltTypes := splitterAltTypes.push splitterAltType\n splitterAltNumParams := splitterAltNumParams.push splitterAltNumParam\n altArgMasks := altArgMasks.push argMask\n trace[Meta.Match.matchEqs] \"splitterAltType: {splitterAltType}\"\n idx := idx + 1\n -- Define splitter with conditional/refined alternatives\n withSplitterAlts splitterAltTypes fun altsNew => do\n let splitterParams := params.toArray ++ #[motive] ++ discrs.toArray ++ altsNew\n let splitterType ← mkForallFVars splitterParams matchResultType\n trace[Meta.Match.matchEqs] \"splitterType: {splitterType}\"\n let template := mkAppN (mkConst constInfo.name us) (params ++ #[motive] ++ discrs ++ alts)\n let template ← deltaExpand template (· == constInfo.name)\n let template := template.headBeta\n let splitterVal ← mkLambdaFVars splitterParams (← mkSplitterProof matchDeclName template alts altsNew splitterAltNumParams altArgMasks)\n let splitterName := baseName ++ `splitter\n addAndCompile <| Declaration.defnDecl {\n name := splitterName\n levelParams := constInfo.levelParams\n type := splitterType\n value := splitterVal\n hints := .abbrev\n safety := .safe\n }\n setInlineAttribute splitterName\n let result := { eqnNames, splitterName, splitterAltNumParams }\n registerMatchEqns matchDeclName result\n return result\n\n/- See header at `MatchEqsExt.lean` -/\n@[export lean_get_match_equations_for]\ndef getEquationsForImpl (matchDeclName : Name) : MetaM MatchEqns := do\n match matchEqnsExt.getState (← getEnv) |>.map.find? matchDeclName with\n | some matchEqns => return matchEqns\n | none => mkEquationsFor matchDeclName\n\nbuiltin_initialize registerTraceClass `Meta.Match.matchEqs\n\nend Lean.Meta.Match\n", "meta": {"author": "leanprover", "repo": "lean4", "sha": "742d053a97bdd109a41a921facd1cd6a55e89bc7", "save_path": "github-repos/lean/leanprover-lean4", "path": "github-repos/lean/leanprover-lean4/lean4-742d053a97bdd109a41a921facd1cd6a55e89bc7/src/Lean/Meta/Match/MatchEqs.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.31742626558767584, "lm_q2_score": 0.03114383019755894, "lm_q1q2_score": 0.009885869715707823}} {"text": "import Lbar.ext_aux4\nimport Lbar.iota\n\nnoncomputable theory\n\nuniverses v u u'\n\nopen opposite category_theory category_theory.limits category_theory.preadditive\nopen_locale nnreal zero_object\n\nvariables (r r' : ℝ≥0)\nvariables [fact (0 < r)] [fact (0 < r')] [fact (r < r')] [fact (r < 1)] [fact (r' < 1)]\n\nopen bounded_homotopy_category\n\nvariables {r'}\nvariables (BD : breen_deligne.package)\nvariables (κ κ₂ : ℝ≥0 → ℕ → ℝ≥0)\nvariables [∀ (c : ℝ≥0), BD.data.suitable (κ c)] [∀ n, fact (monotone (function.swap κ n))]\nvariables [∀ (c : ℝ≥0), BD.data.suitable (κ₂ c)] [∀ n, fact (monotone (function.swap κ₂ n))]\nvariables (M : ProFiltPseuNormGrpWithTinv₁.{u} r')\n\nnamespace Lbar\n\nopen ProFiltPseuNormGrpWithTinv₁ ProFiltPseuNormGrp₁ CompHausFiltPseuNormGrp₁\nopen bounded_homotopy_category\n\nvariables (r r')\n\ndef Tinv_sub (S : Profinite.{u}) (V : SemiNormedGroup.{u}) [normed_with_aut r V] (i : ℤ) :\n ((Ext' i).obj (op $ (Lbar.condensed.{u} r').obj S)).obj V.to_Cond ⟶\n ((Ext' i).obj (op $ (Lbar.condensed.{u} r').obj S)).obj V.to_Cond :=\n((Ext' i).map ((condensify_Tinv _).app S).op).app _ -\n((Ext' i).obj _).map (Condensed.of_top_ab_map (normed_with_aut.T.inv).to_add_monoid_hom\n (normed_group_hom.continuous _))\n\n-- move me\nattribute [simps] Condensed.of_top_ab_map\n\nvariables (S : Profinite.{0}) (V : SemiNormedGroup.{0})\nvariables [complete_space V] [separated_space V]\nvariables (r')\n\ndef condensify_iso_extend :\n condensify (Fintype_Lbar.{0 0} r' ⋙ PFPNGT₁_to_CHFPNG₁ₑₗ r') ≅\n (Profinite.extend (Fintype_Lbar.{0 0} r')) ⋙\n (PFPNGT₁_to_CHFPNG₁ₑₗ r' ⋙ CHFPNG₁_to_CHFPNGₑₗ.{0} ⋙\n CompHausFiltPseuNormGrp.to_Condensed.{0}) :=\n(((whiskering_left _ _ _).map_iso $\n Profinite.extend_commutes (Fintype_Lbar.{0 0} r') (PFPNGT₁_to_CHFPNG₁ₑₗ r')).app\n (CHFPNG₁_to_CHFPNGₑₗ.{0} ⋙ CompHausFiltPseuNormGrp.to_Condensed.{0})).symm\n\ndef condensify_iso_extend' :\n (condensify (Fintype_Lbar.{0 0} r' ⋙ PFPNGT₁_to_CHFPNG₁ₑₗ r')).obj S ≅\n ((Profinite.extend (Fintype_Lbar.{0 0} r')).obj S).to_Condensed :=\n(condensify_iso_extend r').app S\n\nsection move_me\n\n--universes u'\n\nopen Profinite\n\nvariables {C : Type u} [category.{v} C] (F : Fintype.{v} ⥤ C)\nvariables {D : Type u'} [category.{v} D]\nvariable [∀ X : Profinite, has_limit (X.fintype_diagram ⋙ F)]\n\n@[reassoc]\nlemma extend_commutes_comp_extend_extends' (G : C ⥤ D)\n [∀ X : Profinite.{v}, preserves_limits_of_shape (discrete_quotient X) G]\n [∀ X : Profinite.{v}, has_limit (X.fintype_diagram ⋙ F ⋙ G)] :\n whisker_left Fintype.to_Profinite (extend_commutes F G).hom =\n (functor.associator _ _ _).inv ≫ (whisker_right (extend_extends _).hom G) ≫\n (extend_extends _).inv :=\nby rw [← category.assoc, iso.eq_comp_inv, extend_commutes_comp_extend_extends]\n\n@[reassoc]\nlemma extend_commutes_comp_extend_extends'' (G : C ⥤ D)\n [∀ X : Profinite.{v}, preserves_limits_of_shape (discrete_quotient X) G]\n [∀ X : Profinite.{v}, has_limit (X.fintype_diagram ⋙ F ⋙ G)] :\n whisker_left Fintype.to_Profinite (extend_commutes F G).inv =\n (extend_extends _).hom ≫ (whisker_right (extend_extends _).inv G) ≫\n (functor.associator _ _ _).hom :=\nbegin\n rw [← iso.inv_comp_eq, ← iso_whisker_left_inv, iso.comp_inv_eq, iso_whisker_left_hom,\n extend_commutes_comp_extend_extends', category.assoc, iso.hom_inv_id_assoc,\n ← iso_whisker_right_hom, ← iso_whisker_right_inv, iso.inv_hom_id_assoc],\nend\n\nend move_me\n\nlemma condensify_Tinv_iso :\n condensify_Tinv (Fintype_Lbar.{0 0} r') ≫ (condensify_iso_extend r').hom =\n (condensify_iso_extend r').hom ≫ (@whisker_right _ _ _ _ _ _ _ _ (Tinv_nat_trans _) _) :=\nbegin\n delta Tinv_cond condensify_Tinv condensify_nonstrict condensify_iso_extend' condensify_iso_extend,\n ext S : 2,\n rw [iso.symm_hom, iso.app_inv, functor.map_iso_inv, nat_trans.comp_app, nat_trans.comp_app,\n whiskering_left_map_app_app, ← iso.app_inv, ← functor.map_iso_inv, iso.comp_inv_eq,\n functor.map_iso_inv, functor.map_iso_hom, functor.comp_map, functor.comp_map,\n whisker_right_app, whisker_right_app, ← functor.map_comp, ← functor.map_comp],\n congr' 1,\n rw [iso.app_inv, iso.app_hom, ← whisker_right_app, ← whisker_right_app,\n ← nat_trans.comp_app, ← nat_trans.comp_app],\n congr' 1,\n refine nonstrict_extend_ext _ _ (r'⁻¹) (1 * (r'⁻¹ * 1)) _ _ _,\n { intro X, apply nonstrict_extend_bound_by },\n { intro X,\n apply comphaus_filtered_pseudo_normed_group_hom.bound_by.comp,\n apply comphaus_filtered_pseudo_normed_group_hom.bound_by.comp,\n { apply strict_comphaus_filtered_pseudo_normed_group_hom.to_chfpsng_hom.bound_by_one },\n { apply Tinv_bound_by },\n { apply strict_comphaus_filtered_pseudo_normed_group_hom.to_chfpsng_hom.bound_by_one }, },\n { rw [whisker_left_comp, whisker_left_comp, ← whisker_right_left, ← whisker_right_left,\n extend_commutes_comp_extend_extends', extend_commutes_comp_extend_extends''],\n rw nonstrict_extend_whisker_left,\n\n ext X : 2,\n simp only [whisker_left_app, whisker_right_app, nat_trans.comp_app,\n functor.associator_hom_app, functor.associator_inv_app,\n category.id_comp, category.comp_id, category.assoc, functor.map_comp],\n slice_rhs 2 3 {},\n congr' 2,\n\n simp only [← iso.app_hom, ← iso.app_inv, ← functor.map_iso_hom, ← functor.map_iso_inv,\n category.assoc, iso.eq_inv_comp],\n\n ext x : 1,\n exact (comphaus_filtered_pseudo_normed_group_with_Tinv_hom.map_Tinv\n ((Profinite.extend_extends (Fintype_Lbar.{0 0} r')).app X).hom x).symm }\nend\n\nlemma condensify_Tinv_iso' :\n (condensify_Tinv (Fintype_Lbar.{0 0} r')).app S ≫ (condensify_iso_extend' r' S).hom =\n (condensify_iso_extend' r' S).hom ≫ ((Profinite.extend (Fintype_Lbar.{0 0} r')).obj S).Tinv_cond :=\nbegin\n have := condensify_Tinv_iso r',\n apply_fun (λ η, η.app S) at this,\n exact this,\nend\n\ndef useful_commsq (i : ℤ) (ι : ulift.{1} ℕ → ℝ≥0) (hι : monotone ι) [normed_with_aut r V] :=\n shift_sub_id.commsq\n (ExtQprime.Tinv2 r r' breen_deligne.eg.data\n (λ c n, c * breen_deligne.eg.κ r r' n)\n (λ c n, r' * (c * breen_deligne.eg.κ r r' n))\n ((Lbar.functor.{0 0} r').obj S) V i) ι hι\n\nsection\nopen breen_deligne thm95.universal_constants\n\nvariables (i : ℕ)\n\nlemma useful_commsq_bicartesian (ι : ulift.{1} ℕ → ℝ≥0) (hι : monotone ι) [normed_with_aut r V]\n (H1 : ∀ j, c₀ r r' eg (λ n, eg.κ r r' n) (eg.κ' r r') (i+1) ⟨ℤ⟩ ≤ ι j)\n (H2 : ∀ j, k (eg.κ' r r') i ^ 2 * ι j ≤ ι (j + 1))\n (H3 : ∀ j, k (eg.κ' r r') (i+1) ^ 2 * ι j ≤ ι (j + 1)) :\n (useful_commsq r r' S V i ι hι).bicartesian :=\nbegin\n apply shift_sub_id.bicartesian_iso _ _\n (ExtQprime_iso_aux_system r' _ _ _ V i).symm (ExtQprime_iso_aux_system r' _ _ _ V i).symm ι hι\n (ExtQprime_iso_aux_system_comm' _ _ _ _ _ _ _ _),\n rw [← whisker_right_twice],\n refine shift_sub_id.bicartesian (aux_system.incl'.{0 1} r r' _ _ _ (eg.κ r r')) _\n i ι hι _ _ _,\n { apply_with system_of_complexes.shift_eq_zero {instances := ff},\n swap 3, { apply thm94.explicit r r' _ _ (eg.κ' r r'), },\n any_goals { apply_instance },\n { intro j,\n refine le_trans _ ((c₀_mono _ _ _ _ _ _ (i+1)).out.trans (H1 j)),\n rw nat.add_sub_cancel, },\n { exact H2 } },\n { apply_with system_of_complexes.shift_eq_zero {instances := ff},\n swap 3, { apply thm94.explicit r r' _ _ (eg.κ' r r'), },\n any_goals { apply_instance },\n { exact H1 },\n { exact H3 } },\n { intros c n,\n let κ := eg.κ r r',\n apply aux_system.short_exact r r' _ _ _ (λ c n, r' * (c * κ n)) κ,\n intro c, dsimp, apply_instance, }\nend\n\nlemma bicartesian_of_is_zero {𝓒 : Type*} [category 𝓒] [abelian 𝓒]\n {A B C D : 𝓒} (f₁ : A ⟶ B) (g₁ : A ⟶ C) (g₂ : B ⟶ D) (f₂ : C ⟶ D) (h : commsq f₁ g₁ g₂ f₂)\n (hA : is_zero A) (hB : is_zero B) (hC : is_zero C) (hD : is_zero D) :\n h.bicartesian :=\nbegin\n delta commsq.bicartesian,\n apply_with short_exact.mk {instances:=ff},\n { refine ⟨λ X f g h, _⟩, apply hA.eq_of_tgt },\n { refine ⟨λ X f g h, _⟩, apply hD.eq_of_src },\n { apply exact_of_is_zero ((is_zero_biprod _ _ hB hC).of_iso (h.sum.iso (sum_str.biprod _ _))), }\nend\n\nlemma is_zero_pi {𝓒 : Type*} [category 𝓒] [abelian 𝓒] {ι : Type*} (f : ι → 𝓒) [has_product f]\n (hf : ∀ i, is_zero (f i)) :\n is_zero (∏ f) :=\nbegin\n rw is_zero_iff_id_eq_zero,\n ext,\n apply (hf j).eq_of_tgt,\nend\n\nlemma useful_commsq_bicartesian_neg (ι : ulift.{1} ℕ → ℝ≥0) (hι : monotone ι) [normed_with_aut r V]\n (i : ℤ) (hi : i < 0) :\n (useful_commsq r r' S V i ι hι).bicartesian :=\nbegin\n have : 1 + i ≤ 0, { linarith only [hi] },\n apply bicartesian_of_is_zero;\n apply is_zero_pi; intro x;\n apply Ext_single_right_is_zero _ _ 1 _ _ (chain_complex.bounded_by_one _) this\nend\n\nlemma is_iso_sq {𝓒 : Type*} [category 𝓒] {X Y : 𝓒} (f₁ : X ⟶ X) (f₂ : Y ⟶ Y)\n (e : X ≅ Y) (h : f₁ ≫ e.hom = e.hom ≫ f₂) (h₁ : is_iso f₁) :\n is_iso f₂ :=\nby { rw [← iso.inv_comp_eq] at h, rw ← h, apply_instance }\n\nopen category_theory.preadditive\n\nlemma is_iso_sq' {𝓒 : Type*} [category 𝓒] [abelian 𝓒] [enough_projectives 𝓒]\n {X Y Z : bounded_homotopy_category 𝓒} (f₁ : X ⟶ X) (f₂ : Y ⟶ Y) (f₃ : Z ⟶ Z)\n (e : Y ≅ X) (h : e.hom ≫ f₁ = f₂ ≫ e.hom) (i : ℤ)\n (h₁ : is_iso (((Ext i).map f₁.op).app Z - ((Ext i).obj _).map f₃)) :\n is_iso (((Ext i).map f₂.op).app Z - ((Ext i).obj _).map f₃) :=\nbegin\n refine is_iso_sq _ _ ((functor.map_iso _ e.op).app _) _ h₁,\n rw [iso.app_hom, functor.map_iso_hom, sub_comp, comp_sub, nat_trans.naturality,\n ← nat_trans.comp_app, ← nat_trans.comp_app, ← functor.map_comp, ← functor.map_comp,\n iso.op_hom, ← op_comp, ← op_comp, h],\nend\n\n/-- Thm 9.4bis of [Analytic]. More precisely: the first observation in the proof 9.4 => 9.1. -/\ntheorem is_iso_Tinv_sub [normed_with_aut r V] : ∀ i, is_iso (Tinv_sub r r' S V i) :=\nbegin\n erw (Condensed.bd_lemma _ _ _ _),\n swap, { apply Lbar.obj.no_zero_smul_divisors },\n intro i,\n refine is_iso_sq' _ _ _ (functor.map_iso _ $ condensify_iso_extend' _ _) _ _ _,\n { refine category_theory.functor.map _ _, refine Tinv_cond _ },\n { rw [functor.map_iso_hom, ← functor.map_comp, ← functor.map_comp, condensify_Tinv_iso'], },\n revert i,\n refine Tinv2_iso_of_bicartesian' r breen_deligne.eg\n (λ c n, c * breen_deligne.eg.κ r r' n)\n (λ c n, r' * (c * breen_deligne.eg.κ r r' n))\n ((Lbar.functor.{0 0} r').obj S) V _,\n rintro (i|(_|i)),\n { refine ⟨ι r r' i, hι r r' i, _, _, _, _⟩,\n { intros s m,\n apply Lbar.sufficiently_increasing_eg },\n { intros s m,\n apply Lbar.sufficiently_increasing_eg' },\n all_goals { apply useful_commsq_bicartesian },\n { rintro ⟨j⟩, apply Hι1 },\n { rintro ⟨j⟩, apply Hι2a },\n { rintro ⟨j⟩, apply Hι2b },\n { rintro ⟨j⟩, apply Hι1' },\n { rintro ⟨j⟩, apply Hι2b },\n { rintro ⟨j⟩, apply Hι2c } },\n { refine ⟨ι r r' 0, hι r r' 0, _, _, _, _⟩,\n { intros s m, apply Lbar.sufficiently_increasing_eg, },\n { intros s m, apply Lbar.sufficiently_increasing_eg', },\n { apply useful_commsq_bicartesian_neg, dec_trivial },\n { apply useful_commsq_bicartesian,\n { rintro ⟨j⟩, apply Hι1 },\n { rintro ⟨j⟩, apply Hι2a },\n { rintro ⟨j⟩, apply Hι2b }, }, },\n { refine ⟨ι r r' 0, hι r r' 0, _, _, _, _⟩,\n { intros s m, apply Lbar.sufficiently_increasing_eg, },\n { intros s m, apply Lbar.sufficiently_increasing_eg', },\n { apply useful_commsq_bicartesian_neg, dec_trivial },\n { apply useful_commsq_bicartesian_neg,\n rw [int.neg_succ_of_nat_eq'],\n simp only [int.coe_nat_succ, neg_add_rev, sub_add_cancel, add_neg_lt_iff_le_add', add_zero],\n dec_trivial }, },\nend\n\n/-- Thm 9.4bis of [Analytic]. More precisely: the first observation in the proof 9.4 => 9.1. -/\ntheorem is_iso_Tinv2 [normed_with_aut r V]\n (hV : ∀ (v : V), (normed_with_aut.T.inv v) = 2 • v) :\n ∀ i, is_iso (((Ext' i).map ((condensify_Tinv2 (Fintype_Lbar.{0 0} r')).app S).op).app\n (Condensed.of_top_ab ↥V)) :=\nbegin\n intro i,\n rw [condensify_Tinv2_eq, ← functor.flip_obj_map, nat_trans.app_sub, category_theory.op_sub,\n nat_trans.app_nsmul, category_theory.op_nsmul, two_nsmul, nat_trans.id_app, op_id,\n functor.map_sub, functor.map_add, category_theory.functor.map_id],\n convert is_iso_Tinv_sub r r' S V i using 2,\n suffices : Condensed.of_top_ab_map (normed_group_hom.to_add_monoid_hom normed_with_aut.T.inv) _ =\n 2 • 𝟙 _,\n { rw [this, two_nsmul, functor.map_add, category_theory.functor.map_id], refl, },\n ext T f t,\n dsimp only [Condensed.of_top_ab_map_val, whisker_right_app, Ab.ulift_map_apply_down,\n add_monoid_hom.mk'_apply, continuous_map.coe_mk, function.comp_app],\n erw [hV, two_nsmul, two_nsmul],\n refl,\nend\n\nend\n\nend Lbar\n", "meta": {"author": "bentoner", "repo": "debug", "sha": "b8a75381caa90aa9942c20e08a44e45d0ae60d18", "save_path": "github-repos/lean/bentoner-debug", "path": "github-repos/lean/bentoner-debug/debug-b8a75381caa90aa9942c20e08a44e45d0ae60d18/src/Lbar/ext.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.42250463481418826, "lm_q2_score": 0.02333076936024027, "lm_q1q2_score": 0.009857358188482367}} {"text": "/-\nCopyright (c) 2022 Scott Morrison. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Scott Morrison, Oleksandr Manzyuk\n\n! This file was ported from Lean 3 source module category_theory.monoidal.Bimod\n! leanprover-community/mathlib commit 4698e35ca56a0d4fa53aa5639c3364e0a77f4eba\n! Please do not edit these lines, except to modify the commit id\n! if you have ported upstream changes.\n-/\nimport Mathbin.CategoryTheory.Bicategory.Basic\nimport Mathbin.CategoryTheory.Monoidal.Mon_\nimport Mathbin.CategoryTheory.Limits.Preserves.Shapes.Equalizers\n\n/-!\n# The category of bimodule objects over a pair of monoid objects.\n-/\n\n\nuniverse v₁ v₂ u₁ u₂\n\nopen CategoryTheory\n\nopen CategoryTheory.MonoidalCategory\n\nvariable {C : Type u₁} [Category.{v₁} C] [MonoidalCategory.{v₁} C]\n\nsection\n\nopen CategoryTheory.Limits\n\nvariable [HasCoequalizers C]\n\nsection\n\nvariable [∀ X : C, PreservesColimitsOfSize.{0, 0} (tensorLeft X)]\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\ntheorem id_tensor_π_preserves_coequalizer_inv_desc {W X Y Z : C} (f g : X ⟶ Y) (h : Z ⊗ Y ⟶ W)\n (wh : (𝟙 Z ⊗ f) ≫ h = (𝟙 Z ⊗ g) ≫ h) :\n (𝟙 Z ⊗ coequalizer.π f g) ≫\n (PreservesCoequalizer.iso (tensorLeft Z) f g).inv ≫ coequalizer.desc h wh =\n h :=\n map_π_preserves_coequalizer_inv_desc (tensorLeft Z) f g h wh\n#align id_tensor_π_preserves_coequalizer_inv_desc id_tensor_π_preserves_coequalizer_inv_desc\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\ntheorem id_tensor_π_preserves_coequalizer_inv_colimMap_desc {X Y Z X' Y' Z' : C} (f g : X ⟶ Y)\n (f' g' : X' ⟶ Y') (p : Z ⊗ X ⟶ X') (q : Z ⊗ Y ⟶ Y') (wf : (𝟙 Z ⊗ f) ≫ q = p ≫ f')\n (wg : (𝟙 Z ⊗ g) ≫ q = p ≫ g') (h : Y' ⟶ Z') (wh : f' ≫ h = g' ≫ h) :\n (𝟙 Z ⊗ coequalizer.π f g) ≫\n (PreservesCoequalizer.iso (tensorLeft Z) f g).inv ≫\n colimMap (parallelPairHom (𝟙 Z ⊗ f) (𝟙 Z ⊗ g) f' g' p q wf wg) ≫ coequalizer.desc h wh =\n q ≫ h :=\n map_π_preserves_coequalizer_inv_colimMap_desc (tensorLeft Z) f g f' g' p q wf wg h wh\n#align id_tensor_π_preserves_coequalizer_inv_colim_map_desc id_tensor_π_preserves_coequalizer_inv_colimMap_desc\n\nend\n\nsection\n\nvariable [∀ X : C, PreservesColimitsOfSize.{0, 0} (tensorRight X)]\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\ntheorem π_tensor_id_preserves_coequalizer_inv_desc {W X Y Z : C} (f g : X ⟶ Y) (h : Y ⊗ Z ⟶ W)\n (wh : (f ⊗ 𝟙 Z) ≫ h = (g ⊗ 𝟙 Z) ≫ h) :\n (coequalizer.π f g ⊗ 𝟙 Z) ≫\n (PreservesCoequalizer.iso (tensorRight Z) f g).inv ≫ coequalizer.desc h wh =\n h :=\n map_π_preserves_coequalizer_inv_desc (tensorRight Z) f g h wh\n#align π_tensor_id_preserves_coequalizer_inv_desc π_tensor_id_preserves_coequalizer_inv_desc\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\ntheorem π_tensor_id_preserves_coequalizer_inv_colimMap_desc {X Y Z X' Y' Z' : C} (f g : X ⟶ Y)\n (f' g' : X' ⟶ Y') (p : X ⊗ Z ⟶ X') (q : Y ⊗ Z ⟶ Y') (wf : (f ⊗ 𝟙 Z) ≫ q = p ≫ f')\n (wg : (g ⊗ 𝟙 Z) ≫ q = p ≫ g') (h : Y' ⟶ Z') (wh : f' ≫ h = g' ≫ h) :\n (coequalizer.π f g ⊗ 𝟙 Z) ≫\n (PreservesCoequalizer.iso (tensorRight Z) f g).inv ≫\n colimMap (parallelPairHom (f ⊗ 𝟙 Z) (g ⊗ 𝟙 Z) f' g' p q wf wg) ≫ coequalizer.desc h wh =\n q ≫ h :=\n map_π_preserves_coequalizer_inv_colimMap_desc (tensorRight Z) f g f' g' p q wf wg h wh\n#align π_tensor_id_preserves_coequalizer_inv_colim_map_desc π_tensor_id_preserves_coequalizer_inv_colimMap_desc\n\nend\n\nend\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\n/-- A bimodule object for a pair of monoid objects, all internal to some monoidal category. -/\nstructure Bimod (A B : Mon_ C) where\n pt : C\n actLeft : A.pt ⊗ X ⟶ X\n one_act_left' : (A.one ⊗ 𝟙 X) ≫ act_left = (λ_ X).Hom := by obviously\n left_assoc' :\n (A.mul ⊗ 𝟙 X) ≫ act_left = (α_ A.pt A.pt X).Hom ≫ (𝟙 A.pt ⊗ act_left) ≫ act_left := by obviously\n actRight : X ⊗ B.pt ⟶ X\n actRight_one' : (𝟙 X ⊗ B.one) ≫ act_right = (ρ_ X).Hom := by obviously\n right_assoc' :\n (𝟙 X ⊗ B.mul) ≫ act_right = (α_ X B.pt B.pt).inv ≫ (act_right ⊗ 𝟙 B.pt) ≫ act_right := by\n obviously\n middle_assoc' :\n (act_left ⊗ 𝟙 B.pt) ≫ act_right = (α_ A.pt X B.pt).Hom ≫ (𝟙 A.pt ⊗ act_right) ≫ act_left := by\n obviously\n#align Bimod Bimod\n\nrestate_axiom Bimod.one_act_left'\n\nrestate_axiom Bimod.actRight_one'\n\nrestate_axiom Bimod.left_assoc'\n\nrestate_axiom Bimod.right_assoc'\n\nrestate_axiom Bimod.middle_assoc'\n\nattribute [simp, reassoc.1]\n Bimod.one_actLeft Bimod.actRight_one Bimod.left_assoc Bimod.right_assoc Bimod.middle_assoc\n\nnamespace Bimod\n\nvariable {A B : Mon_ C} (M : Bimod A B)\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\n/-- A morphism of bimodule objects. -/\n@[ext]\nstructure Hom (M N : Bimod A B) where\n Hom : M.pt ⟶ N.pt\n left_act_hom' : M.actLeft ≫ hom = (𝟙 A.pt ⊗ hom) ≫ N.actLeft := by obviously\n right_act_hom' : M.actRight ≫ hom = (hom ⊗ 𝟙 B.pt) ≫ N.actRight := by obviously\n#align Bimod.hom Bimod.Hom\n\nrestate_axiom hom.left_act_hom'\n\nrestate_axiom hom.right_act_hom'\n\nattribute [simp, reassoc.1] hom.left_act_hom hom.right_act_hom\n\n/-- The identity morphism on a bimodule object. -/\n@[simps]\ndef id' (M : Bimod A B) : Hom M M where Hom := 𝟙 M.pt\n#align Bimod.id' Bimod.id'\n\ninstance homInhabited (M : Bimod A B) : Inhabited (Hom M M) :=\n ⟨id' M⟩\n#align Bimod.hom_inhabited Bimod.homInhabited\n\n/-- Composition of bimodule object morphisms. -/\n@[simps]\ndef comp {M N O : Bimod A B} (f : Hom M N) (g : Hom N O) : Hom M O where Hom := f.Hom ≫ g.Hom\n#align Bimod.comp Bimod.comp\n\ninstance : Category (Bimod A B) where\n Hom M N := Hom M N\n id := id'\n comp M N O f g := comp f g\n\n@[simp]\ntheorem id_hom' (M : Bimod A B) : (𝟙 M : Hom M M).Hom = 𝟙 M.pt :=\n rfl\n#align Bimod.id_hom' Bimod.id_hom'\n\n@[simp]\ntheorem comp_hom' {M N K : Bimod A B} (f : M ⟶ N) (g : N ⟶ K) :\n (f ≫ g : Hom M K).Hom = f.Hom ≫ g.Hom :=\n rfl\n#align Bimod.comp_hom' Bimod.comp_hom'\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\n/-- Construct an isomorphism of bimodules by giving an isomorphism between the underlying objects\nand checking compatibility with left and right actions only in the forward direction.\n-/\n@[simps]\ndef isoOfIso {X Y : Mon_ C} {P Q : Bimod X Y} (f : P.pt ≅ Q.pt)\n (f_left_act_hom : P.actLeft ≫ f.Hom = (𝟙 X.pt ⊗ f.Hom) ≫ Q.actLeft)\n (f_right_act_hom : P.actRight ≫ f.Hom = (f.Hom ⊗ 𝟙 Y.pt) ≫ Q.actRight) : P ≅ Q\n where\n Hom := ⟨f.Hom⟩\n inv :=\n { Hom := f.inv\n left_act_hom' := by\n rw [← cancel_mono f.hom, category.assoc, category.assoc, iso.inv_hom_id, category.comp_id,\n f_left_act_hom, ← category.assoc, ← id_tensor_comp, iso.inv_hom_id,\n monoidal_category.tensor_id, category.id_comp]\n right_act_hom' := by\n rw [← cancel_mono f.hom, category.assoc, category.assoc, iso.inv_hom_id, category.comp_id,\n f_right_act_hom, ← category.assoc, ← comp_tensor_id, iso.inv_hom_id,\n monoidal_category.tensor_id, category.id_comp] }\n hom_inv_id' := by ext; dsimp; rw [iso.hom_inv_id]\n inv_hom_id' := by ext; dsimp; rw [iso.inv_hom_id]\n#align Bimod.iso_of_iso Bimod.isoOfIso\n\nvariable (A)\n\n/-- A monoid object as a bimodule over itself. -/\n@[simps]\ndef regular : Bimod A A where\n pt := A.pt\n actLeft := A.mul\n actRight := A.mul\n#align Bimod.regular Bimod.regular\n\ninstance : Inhabited (Bimod A A) :=\n ⟨regular A⟩\n\n/-- The forgetful functor from bimodule objects to the ambient category. -/\ndef forget : Bimod A B ⥤ C where\n obj A := A.pt\n map A B f := f.Hom\n#align Bimod.forget Bimod.forget\n\nopen CategoryTheory.Limits\n\nvariable [HasCoequalizers C]\n\nnamespace TensorBimod\n\nvariable {R S T : Mon_ C} (P : Bimod R S) (Q : Bimod S T)\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\n/-- The underlying object of the tensor product of two bimodules. -/\nnoncomputable def x : C :=\n coequalizer (P.actRight ⊗ 𝟙 Q.pt) ((α_ _ _ _).Hom ≫ (𝟙 P.pt ⊗ Q.actLeft))\n#align Bimod.tensor_Bimod.X Bimod.TensorBimod.x\n\nsection\n\nvariable [∀ X : C, PreservesColimitsOfSize.{0, 0} (tensorLeft X)]\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\n/-- Left action for the tensor product of two bimodules. -/\nnoncomputable def actLeft : R.pt ⊗ x P Q ⟶ x P Q :=\n (PreservesCoequalizer.iso (tensorLeft R.pt) _ _).inv ≫\n colimMap\n (parallelPairHom _ _ _ _\n ((𝟙 _ ⊗ (α_ _ _ _).Hom) ≫ (α_ _ _ _).inv ≫ (P.actLeft ⊗ 𝟙 S.pt ⊗ 𝟙 Q.pt) ≫ (α_ _ _ _).inv)\n ((α_ _ _ _).inv ≫ (P.actLeft ⊗ 𝟙 Q.pt))\n (by\n dsimp\n slice_lhs 1 2 => rw [associator_inv_naturality]\n slice_rhs 3 4 => rw [associator_inv_naturality]\n slice_rhs 4 5 => rw [← tensor_comp, middle_assoc, tensor_comp, comp_tensor_id]\n coherence)\n (by\n dsimp\n slice_lhs 1 1 => rw [id_tensor_comp]\n slice_lhs 2 3 => rw [associator_inv_naturality]\n slice_lhs 3 4 => rw [tensor_id, id_tensor_comp_tensor_id]\n slice_rhs 4 6 => rw [iso.inv_hom_id_assoc]\n slice_rhs 3 4 => rw [tensor_id, tensor_id_comp_id_tensor]))\n#align Bimod.tensor_Bimod.act_left Bimod.TensorBimod.actLeft\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\ntheorem id_tensor_π_actLeft :\n (𝟙 R.pt ⊗ coequalizer.π _ _) ≫ actLeft P Q =\n (α_ _ _ _).inv ≫ (P.actLeft ⊗ 𝟙 Q.pt) ≫ coequalizer.π _ _ :=\n by\n erw [map_π_preserves_coequalizer_inv_colim_map (tensor_left _)]\n simp only [category.assoc]\n#align Bimod.tensor_Bimod.id_tensor_π_act_left Bimod.TensorBimod.id_tensor_π_actLeft\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\ntheorem one_act_left' : (R.one ⊗ 𝟙 _) ≫ actLeft P Q = (λ_ _).Hom :=\n by\n refine' (cancel_epi ((tensor_left _).map (coequalizer.π _ _))).1 _\n dsimp [X]\n slice_lhs 1 2 => rw [id_tensor_comp_tensor_id, ← tensor_id_comp_id_tensor]\n slice_lhs 2 3 => rw [id_tensor_π_act_left]\n slice_lhs 1 2 => rw [← monoidal_category.tensor_id, associator_inv_naturality]\n slice_lhs 2 3 => rw [← comp_tensor_id, one_act_left]\n slice_rhs 1 2 => rw [left_unitor_naturality]\n coherence\n#align Bimod.tensor_Bimod.one_act_left' Bimod.TensorBimod.one_act_left'\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\ntheorem left_assoc' :\n (R.mul ⊗ 𝟙 _) ≫ actLeft P Q = (α_ R.pt R.pt _).Hom ≫ (𝟙 R.pt ⊗ actLeft P Q) ≫ actLeft P Q :=\n by\n refine' (cancel_epi ((tensor_left _).map (coequalizer.π _ _))).1 _\n dsimp [X]\n slice_lhs 1 2 => rw [id_tensor_comp_tensor_id, ← tensor_id_comp_id_tensor]\n slice_lhs 2 3 => rw [id_tensor_π_act_left]\n slice_lhs 1 2 => rw [← monoidal_category.tensor_id, associator_inv_naturality]\n slice_lhs 2 3 => rw [← comp_tensor_id, left_assoc, comp_tensor_id, comp_tensor_id]\n slice_rhs 1 2 => rw [← monoidal_category.tensor_id, associator_naturality]\n slice_rhs 2 3 => rw [← id_tensor_comp, id_tensor_π_act_left, id_tensor_comp, id_tensor_comp]\n slice_rhs 4 5 => rw [id_tensor_π_act_left]\n slice_rhs 3 4 => rw [associator_inv_naturality]\n coherence\n#align Bimod.tensor_Bimod.left_assoc' Bimod.TensorBimod.left_assoc'\n\nend\n\nsection\n\nvariable [∀ X : C, PreservesColimitsOfSize.{0, 0} (tensorRight X)]\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\n/-- Right action for the tensor product of two bimodules. -/\nnoncomputable def actRight : x P Q ⊗ T.pt ⟶ x P Q :=\n (PreservesCoequalizer.iso (tensorRight T.pt) _ _).inv ≫\n colimMap\n (parallelPairHom _ _ _ _\n ((α_ _ _ _).Hom ≫ (α_ _ _ _).Hom ≫ (𝟙 P.pt ⊗ 𝟙 S.pt ⊗ Q.actRight) ≫ (α_ _ _ _).inv)\n ((α_ _ _ _).Hom ≫ (𝟙 P.pt ⊗ Q.actRight))\n (by\n dsimp\n slice_lhs 1 2 => rw [associator_naturality]\n slice_lhs 2 3 => rw [tensor_id, tensor_id_comp_id_tensor]\n slice_rhs 3 4 => rw [associator_inv_naturality]\n slice_rhs 2 4 => rw [iso.hom_inv_id_assoc]\n slice_rhs 2 3 => rw [tensor_id, id_tensor_comp_tensor_id])\n (by\n dsimp\n slice_lhs 1 1 => rw [comp_tensor_id]\n slice_lhs 2 3 => rw [associator_naturality]\n slice_lhs 3 4 => rw [← id_tensor_comp, middle_assoc, id_tensor_comp]\n slice_rhs 4 6 => rw [iso.inv_hom_id_assoc]\n slice_rhs 3 4 => rw [← id_tensor_comp]\n coherence))\n#align Bimod.tensor_Bimod.act_right Bimod.TensorBimod.actRight\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\ntheorem π_tensor_id_actRight :\n (coequalizer.π _ _ ⊗ 𝟙 T.pt) ≫ actRight P Q =\n (α_ _ _ _).Hom ≫ (𝟙 P.pt ⊗ Q.actRight) ≫ coequalizer.π _ _ :=\n by\n erw [map_π_preserves_coequalizer_inv_colim_map (tensor_right _)]\n simp only [category.assoc]\n#align Bimod.tensor_Bimod.π_tensor_id_act_right Bimod.TensorBimod.π_tensor_id_actRight\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\ntheorem actRight_one' : (𝟙 _ ⊗ T.one) ≫ actRight P Q = (ρ_ _).Hom :=\n by\n refine' (cancel_epi ((tensor_right _).map (coequalizer.π _ _))).1 _\n dsimp [X]\n slice_lhs 1 2 => rw [tensor_id_comp_id_tensor, ← id_tensor_comp_tensor_id]\n slice_lhs 2 3 => rw [π_tensor_id_act_right]\n slice_lhs 1 2 => rw [← monoidal_category.tensor_id, associator_naturality]\n slice_lhs 2 3 => rw [← id_tensor_comp, act_right_one]\n slice_rhs 1 2 => rw [right_unitor_naturality]\n coherence\n#align Bimod.tensor_Bimod.act_right_one' Bimod.TensorBimod.actRight_one'\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\ntheorem right_assoc' :\n (𝟙 _ ⊗ T.mul) ≫ actRight P Q = (α_ _ T.pt T.pt).inv ≫ (actRight P Q ⊗ 𝟙 T.pt) ≫ actRight P Q :=\n by\n refine' (cancel_epi ((tensor_right _).map (coequalizer.π _ _))).1 _\n dsimp [X]\n slice_lhs 1 2 => rw [tensor_id_comp_id_tensor, ← id_tensor_comp_tensor_id]\n slice_lhs 2 3 => rw [π_tensor_id_act_right]\n slice_lhs 1 2 => rw [← monoidal_category.tensor_id, associator_naturality]\n slice_lhs 2 3 => rw [← id_tensor_comp, right_assoc, id_tensor_comp, id_tensor_comp]\n slice_rhs 1 2 => rw [← monoidal_category.tensor_id, associator_inv_naturality]\n slice_rhs 2 3 => rw [← comp_tensor_id, π_tensor_id_act_right, comp_tensor_id, comp_tensor_id]\n slice_rhs 4 5 => rw [π_tensor_id_act_right]\n slice_rhs 3 4 => rw [associator_naturality]\n coherence\n#align Bimod.tensor_Bimod.right_assoc' Bimod.TensorBimod.right_assoc'\n\nend\n\nsection\n\nvariable [∀ X : C, PreservesColimitsOfSize.{0, 0} (tensorLeft X)]\n\nvariable [∀ X : C, PreservesColimitsOfSize.{0, 0} (tensorRight X)]\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\ntheorem middle_assoc' :\n (actLeft P Q ⊗ 𝟙 T.pt) ≫ actRight P Q =\n (α_ R.pt _ T.pt).Hom ≫ (𝟙 R.pt ⊗ actRight P Q) ≫ actLeft P Q :=\n by\n refine' (cancel_epi ((tensor_left _ ⋙ tensor_right _).map (coequalizer.π _ _))).1 _\n dsimp [X]\n slice_lhs 1 2 => rw [← comp_tensor_id, id_tensor_π_act_left, comp_tensor_id, comp_tensor_id]\n slice_lhs 3 4 => rw [π_tensor_id_act_right]\n slice_lhs 2 3 => rw [associator_naturality]\n slice_lhs 3 4 => rw [monoidal_category.tensor_id, tensor_id_comp_id_tensor]\n slice_rhs 1 2 => rw [associator_naturality]\n slice_rhs 2 3 => rw [← id_tensor_comp, π_tensor_id_act_right, id_tensor_comp, id_tensor_comp]\n slice_rhs 4 5 => rw [id_tensor_π_act_left]\n slice_rhs 3 4 => rw [associator_inv_naturality]\n slice_rhs 4 5 => rw [monoidal_category.tensor_id, id_tensor_comp_tensor_id]\n coherence\n#align Bimod.tensor_Bimod.middle_assoc' Bimod.TensorBimod.middle_assoc'\n\nend\n\nend TensorBimod\n\nsection\n\nvariable [∀ X : C, PreservesColimitsOfSize.{0, 0} (tensorLeft X)]\n\nvariable [∀ X : C, PreservesColimitsOfSize.{0, 0} (tensorRight X)]\n\n/-- Tensor product of two bimodule objects as a bimodule object. -/\n@[simps]\nnoncomputable def tensorBimod {X Y Z : Mon_ C} (M : Bimod X Y) (N : Bimod Y Z) : Bimod X Z\n where\n pt := TensorBimod.x M N\n actLeft := TensorBimod.actLeft M N\n actRight := TensorBimod.actRight M N\n one_act_left' := TensorBimod.one_act_left' M N\n actRight_one' := TensorBimod.actRight_one' M N\n left_assoc' := TensorBimod.left_assoc' M N\n right_assoc' := TensorBimod.right_assoc' M N\n middle_assoc' := TensorBimod.middle_assoc' M N\n#align Bimod.tensor_Bimod Bimod.tensorBimod\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\n/-- Tensor product of two morphisms of bimodule objects. -/\n@[simps]\nnoncomputable def tensorHom {X Y Z : Mon_ C} {M₁ M₂ : Bimod X Y} {N₁ N₂ : Bimod Y Z} (f : M₁ ⟶ M₂)\n (g : N₁ ⟶ N₂) : M₁.tensorBimod N₁ ⟶ M₂.tensorBimod N₂\n where\n Hom :=\n colimMap\n (parallelPairHom _ _ _ _ ((f.Hom ⊗ 𝟙 Y.pt) ⊗ g.Hom) (f.Hom ⊗ g.Hom)\n (by\n rw [← tensor_comp, ← tensor_comp, hom.right_act_hom, category.id_comp, category.comp_id])\n (by\n slice_lhs 2 3 => rw [← tensor_comp, hom.left_act_hom, category.id_comp]\n slice_rhs 1 2 => rw [associator_naturality]\n slice_rhs 2 3 => rw [← tensor_comp, category.comp_id]))\n left_act_hom' :=\n by\n refine' (cancel_epi ((tensor_left _).map (coequalizer.π _ _))).1 _\n dsimp\n slice_lhs 1 2 => rw [tensor_Bimod.id_tensor_π_act_left]\n slice_lhs 3 4 => rw [ι_colim_map, parallel_pair_hom_app_one]\n slice_lhs 2 3 => rw [← tensor_comp, hom.left_act_hom, category.id_comp]\n slice_rhs 1 2 => rw [← id_tensor_comp, ι_colim_map, parallel_pair_hom_app_one, id_tensor_comp]\n slice_rhs 2 3 => rw [tensor_Bimod.id_tensor_π_act_left]\n slice_rhs 1 2 => rw [associator_inv_naturality]\n slice_rhs 2 3 => rw [← tensor_comp, category.comp_id]\n right_act_hom' :=\n by\n refine' (cancel_epi ((tensor_right _).map (coequalizer.π _ _))).1 _\n dsimp\n slice_lhs 1 2 => rw [tensor_Bimod.π_tensor_id_act_right]\n slice_lhs 3 4 => rw [ι_colim_map, parallel_pair_hom_app_one]\n slice_lhs 2 3 => rw [← tensor_comp, category.id_comp, hom.right_act_hom]\n slice_rhs 1 2 => rw [← comp_tensor_id, ι_colim_map, parallel_pair_hom_app_one, comp_tensor_id]\n slice_rhs 2 3 => rw [tensor_Bimod.π_tensor_id_act_right]\n slice_rhs 1 2 => rw [associator_naturality]\n slice_rhs 2 3 => rw [← tensor_comp, category.comp_id]\n#align Bimod.tensor_hom Bimod.tensorHom\n\ntheorem tensor_id {X Y Z : Mon_ C} {M : Bimod X Y} {N : Bimod Y Z} :\n tensorHom (𝟙 M) (𝟙 N) = 𝟙 (M.tensorBimod N) :=\n by\n ext\n simp only [id_hom', tensor_id, tensor_hom_hom, ι_colim_map, parallel_pair_hom_app_one]\n dsimp; dsimp only [tensor_Bimod.X]\n simp only [category.id_comp, category.comp_id]\n#align Bimod.tensor_id Bimod.tensor_id\n\ntheorem tensor_comp {X Y Z : Mon_ C} {M₁ M₂ M₃ : Bimod X Y} {N₁ N₂ N₃ : Bimod Y Z} (f₁ : M₁ ⟶ M₂)\n (f₂ : M₂ ⟶ M₃) (g₁ : N₁ ⟶ N₂) (g₂ : N₂ ⟶ N₃) :\n tensorHom (f₁ ≫ f₂) (g₁ ≫ g₂) = tensorHom f₁ g₁ ≫ tensorHom f₂ g₂ :=\n by\n ext\n simp only [comp_hom', tensor_comp, tensor_hom_hom, ι_colim_map, parallel_pair_hom_app_one,\n category.assoc, ι_colim_map_assoc]\n#align Bimod.tensor_comp Bimod.tensor_comp\n\nend\n\nnamespace AssociatorBimod\n\nvariable [∀ X : C, PreservesColimitsOfSize.{0, 0} (tensorLeft X)]\n\nvariable [∀ X : C, PreservesColimitsOfSize.{0, 0} (tensorRight X)]\n\nvariable {R S T U : Mon_ C} (P : Bimod R S) (Q : Bimod S T) (L : Bimod T U)\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\n/-- An auxiliary morphism for the definition of the underlying morphism of the forward component of\nthe associator isomorphism. -/\nnoncomputable def homAux : (P.tensorBimod Q).pt ⊗ L.pt ⟶ (P.tensorBimod (Q.tensorBimod L)).pt :=\n (PreservesCoequalizer.iso (tensorRight L.pt) _ _).inv ≫\n coequalizer.desc ((α_ _ _ _).Hom ≫ (𝟙 P.pt ⊗ coequalizer.π _ _) ≫ coequalizer.π _ _)\n (by\n dsimp; dsimp [tensor_Bimod.X]\n slice_lhs 1 2 => rw [associator_naturality]\n slice_lhs 2 3 =>\n rw [monoidal_category.tensor_id, tensor_id_comp_id_tensor, ← id_tensor_comp_tensor_id]\n slice_lhs 3 4 => rw [coequalizer.condition]\n slice_lhs 2 3 => rw [← monoidal_category.tensor_id, associator_naturality]\n slice_lhs 3 4 => rw [← id_tensor_comp, tensor_Bimod.id_tensor_π_act_left, id_tensor_comp]\n slice_rhs 1 1 => rw [comp_tensor_id]\n slice_rhs 2 3 => rw [associator_naturality]\n slice_rhs 3 4 => rw [← id_tensor_comp]\n coherence)\n#align Bimod.associator_Bimod.hom_aux Bimod.AssociatorBimod.homAux\n\n/-- The underlying morphism of the forward component of the associator isomorphism. -/\nnoncomputable def hom :\n ((P.tensorBimod Q).tensorBimod L).pt ⟶ (P.tensorBimod (Q.tensorBimod L)).pt :=\n coequalizer.desc (homAux P Q L)\n (by\n dsimp [hom_aux]\n refine' (cancel_epi ((tensor_right _ ⋙ tensor_right _).map (coequalizer.π _ _))).1 _\n dsimp [tensor_Bimod.X]\n slice_lhs 1 2 =>\n rw [← comp_tensor_id, tensor_Bimod.π_tensor_id_act_right, comp_tensor_id, comp_tensor_id]\n slice_lhs 3 5 => rw [π_tensor_id_preserves_coequalizer_inv_desc]\n slice_lhs 2 3 => rw [associator_naturality]\n slice_lhs 3 4 => rw [← id_tensor_comp, coequalizer.condition, id_tensor_comp, id_tensor_comp]\n slice_rhs 1 2 => rw [associator_naturality]\n slice_rhs 2 3 =>\n rw [monoidal_category.tensor_id, tensor_id_comp_id_tensor, ← id_tensor_comp_tensor_id]\n slice_rhs 3 5 => rw [π_tensor_id_preserves_coequalizer_inv_desc]\n slice_rhs 2 3 => rw [← monoidal_category.tensor_id, associator_naturality]\n coherence)\n#align Bimod.associator_Bimod.hom Bimod.AssociatorBimod.hom\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\ntheorem hom_left_act_hom' :\n ((P.tensorBimod Q).tensorBimod L).actLeft ≫ hom P Q L =\n (𝟙 R.pt ⊗ hom P Q L) ≫ (P.tensorBimod (Q.tensorBimod L)).actLeft :=\n by\n dsimp; dsimp [hom, hom_aux]\n refine' (cancel_epi ((tensor_left _).map (coequalizer.π _ _))).1 _\n rw [tensor_left_map]\n slice_lhs 1 2 => rw [tensor_Bimod.id_tensor_π_act_left]\n slice_lhs 3 4 => rw [coequalizer.π_desc]\n slice_rhs 1 2 => rw [← id_tensor_comp, coequalizer.π_desc, id_tensor_comp]\n refine' (cancel_epi ((tensor_right _ ⋙ tensor_left _).map (coequalizer.π _ _))).1 _\n dsimp; dsimp [tensor_Bimod.X]\n slice_lhs 1 2 => rw [associator_inv_naturality]\n slice_lhs 2 3 =>\n rw [← comp_tensor_id, tensor_Bimod.id_tensor_π_act_left, comp_tensor_id, comp_tensor_id]\n slice_lhs 4 6 => rw [π_tensor_id_preserves_coequalizer_inv_desc]\n slice_lhs 3 4 => rw [associator_naturality]\n slice_lhs 4 5 => rw [monoidal_category.tensor_id, tensor_id_comp_id_tensor]\n slice_rhs 1 3 =>\n rw [← id_tensor_comp, ← id_tensor_comp, π_tensor_id_preserves_coequalizer_inv_desc,\n id_tensor_comp, id_tensor_comp]\n slice_rhs 3 4 => erw [tensor_Bimod.id_tensor_π_act_left P (Q.tensor_Bimod L)]\n slice_rhs 2 3 => erw [associator_inv_naturality]\n slice_rhs 3 4 => erw [monoidal_category.tensor_id, id_tensor_comp_tensor_id]\n coherence\n#align Bimod.associator_Bimod.hom_left_act_hom' Bimod.AssociatorBimod.hom_left_act_hom'\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\ntheorem hom_right_act_hom' :\n ((P.tensorBimod Q).tensorBimod L).actRight ≫ hom P Q L =\n (hom P Q L ⊗ 𝟙 U.pt) ≫ (P.tensorBimod (Q.tensorBimod L)).actRight :=\n by\n dsimp; dsimp [hom, hom_aux]\n refine' (cancel_epi ((tensor_right _).map (coequalizer.π _ _))).1 _\n rw [tensor_right_map]\n slice_lhs 1 2 => rw [tensor_Bimod.π_tensor_id_act_right]\n slice_lhs 3 4 => rw [coequalizer.π_desc]\n slice_rhs 1 2 => rw [← comp_tensor_id, coequalizer.π_desc, comp_tensor_id]\n refine' (cancel_epi ((tensor_right _ ⋙ tensor_right _).map (coequalizer.π _ _))).1 _\n dsimp; dsimp [tensor_Bimod.X]\n slice_lhs 1 2 => rw [associator_naturality]\n slice_lhs 2 3 =>\n rw [monoidal_category.tensor_id, tensor_id_comp_id_tensor, ← id_tensor_comp_tensor_id]\n slice_lhs 3 5 => rw [π_tensor_id_preserves_coequalizer_inv_desc]\n slice_lhs 2 3 => rw [← monoidal_category.tensor_id, associator_naturality]\n slice_rhs 1 3 =>\n rw [← comp_tensor_id, ← comp_tensor_id, π_tensor_id_preserves_coequalizer_inv_desc,\n comp_tensor_id, comp_tensor_id]\n slice_rhs 3 4 => erw [tensor_Bimod.π_tensor_id_act_right P (Q.tensor_Bimod L)]\n slice_rhs 2 3 => erw [associator_naturality]\n dsimp\n slice_rhs 3 4 =>\n rw [← id_tensor_comp, tensor_Bimod.π_tensor_id_act_right, id_tensor_comp, id_tensor_comp]\n coherence\n#align Bimod.associator_Bimod.hom_right_act_hom' Bimod.AssociatorBimod.hom_right_act_hom'\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\n/-- An auxiliary morphism for the definition of the underlying morphism of the inverse component of\nthe associator isomorphism. -/\nnoncomputable def invAux : P.pt ⊗ (Q.tensorBimod L).pt ⟶ ((P.tensorBimod Q).tensorBimod L).pt :=\n (PreservesCoequalizer.iso (tensorLeft P.pt) _ _).inv ≫\n coequalizer.desc ((α_ _ _ _).inv ≫ (coequalizer.π _ _ ⊗ 𝟙 L.pt) ≫ coequalizer.π _ _)\n (by\n dsimp; dsimp [tensor_Bimod.X]\n slice_lhs 1 2 => rw [associator_inv_naturality]\n rw [← iso.inv_hom_id_assoc (α_ _ _ _) (𝟙 P.X ⊗ Q.act_right), comp_tensor_id]\n slice_lhs 3 4 =>\n rw [← comp_tensor_id, category.assoc, ← tensor_Bimod.π_tensor_id_act_right,\n comp_tensor_id]\n slice_lhs 4 5 => rw [coequalizer.condition]\n slice_lhs 3 4 => rw [associator_naturality]\n slice_lhs 4 5 => rw [monoidal_category.tensor_id, tensor_id_comp_id_tensor]\n slice_rhs 1 2 => rw [id_tensor_comp]\n slice_rhs 2 3 => rw [associator_inv_naturality]\n slice_rhs 3 4 => rw [monoidal_category.tensor_id, id_tensor_comp_tensor_id]\n coherence)\n#align Bimod.associator_Bimod.inv_aux Bimod.AssociatorBimod.invAux\n\n/-- The underlying morphism of the inverse component of the associator isomorphism. -/\nnoncomputable def inv :\n (P.tensorBimod (Q.tensorBimod L)).pt ⟶ ((P.tensorBimod Q).tensorBimod L).pt :=\n coequalizer.desc (invAux P Q L)\n (by\n dsimp [inv_aux]\n refine' (cancel_epi ((tensor_left _).map (coequalizer.π _ _))).1 _\n dsimp [tensor_Bimod.X]\n slice_lhs 1 2 => rw [id_tensor_comp_tensor_id, ← tensor_id_comp_id_tensor]\n slice_lhs 2 4 => rw [id_tensor_π_preserves_coequalizer_inv_desc]\n slice_lhs 1 2 => rw [← monoidal_category.tensor_id, associator_inv_naturality]\n slice_lhs 2 3 => rw [← comp_tensor_id, coequalizer.condition, comp_tensor_id, comp_tensor_id]\n slice_rhs 1 2 => rw [← monoidal_category.tensor_id, associator_naturality]\n slice_rhs 2 3 =>\n rw [← id_tensor_comp, tensor_Bimod.id_tensor_π_act_left, id_tensor_comp, id_tensor_comp]\n slice_rhs 4 6 => rw [id_tensor_π_preserves_coequalizer_inv_desc]\n slice_rhs 3 4 => rw [associator_inv_naturality]\n coherence)\n#align Bimod.associator_Bimod.inv Bimod.AssociatorBimod.inv\n\ntheorem hom_inv_id : hom P Q L ≫ inv P Q L = 𝟙 _ :=\n by\n dsimp [hom, hom_aux, inv, inv_aux]\n ext\n slice_lhs 1 2 => rw [coequalizer.π_desc]\n refine' (cancel_epi ((tensor_right _).map (coequalizer.π _ _))).1 _\n rw [tensor_right_map]\n slice_lhs 1 3 => rw [π_tensor_id_preserves_coequalizer_inv_desc]\n slice_lhs 3 4 => rw [coequalizer.π_desc]\n slice_lhs 2 4 => rw [id_tensor_π_preserves_coequalizer_inv_desc]\n slice_lhs 1 3 => rw [iso.hom_inv_id_assoc]\n dsimp only [tensor_Bimod.X]\n slice_rhs 2 3 => rw [category.comp_id]\n rfl\n#align Bimod.associator_Bimod.hom_inv_id Bimod.AssociatorBimod.hom_inv_id\n\ntheorem inv_hom_id : inv P Q L ≫ hom P Q L = 𝟙 _ :=\n by\n dsimp [hom, hom_aux, inv, inv_aux]\n ext\n slice_lhs 1 2 => rw [coequalizer.π_desc]\n refine' (cancel_epi ((tensor_left _).map (coequalizer.π _ _))).1 _\n rw [tensor_left_map]\n slice_lhs 1 3 => rw [id_tensor_π_preserves_coequalizer_inv_desc]\n slice_lhs 3 4 => rw [coequalizer.π_desc]\n slice_lhs 2 4 => rw [π_tensor_id_preserves_coequalizer_inv_desc]\n slice_lhs 1 3 => rw [iso.inv_hom_id_assoc]\n dsimp only [tensor_Bimod.X]\n slice_rhs 2 3 => rw [category.comp_id]\n rfl\n#align Bimod.associator_Bimod.inv_hom_id Bimod.AssociatorBimod.inv_hom_id\n\nend AssociatorBimod\n\nnamespace LeftUnitorBimod\n\nvariable {R S : Mon_ C} (P : Bimod R S)\n\n/-- The underlying morphism of the forward component of the left unitor isomorphism. -/\nnoncomputable def hom : TensorBimod.x (regular R) P ⟶ P.pt :=\n coequalizer.desc P.actLeft\n (by\n dsimp\n rw [category.assoc, left_assoc])\n#align Bimod.left_unitor_Bimod.hom Bimod.LeftUnitorBimod.hom\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\n/-- The underlying morphism of the inverse component of the left unitor isomorphism. -/\nnoncomputable def inv : P.pt ⟶ TensorBimod.x (regular R) P :=\n (λ_ P.pt).inv ≫ (R.one ⊗ 𝟙 _) ≫ coequalizer.π _ _\n#align Bimod.left_unitor_Bimod.inv Bimod.LeftUnitorBimod.inv\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\ntheorem hom_inv_id : hom P ≫ inv P = 𝟙 _ :=\n by\n dsimp only [hom, inv, tensor_Bimod.X]\n ext; dsimp\n slice_lhs 1 2 => rw [coequalizer.π_desc]\n slice_lhs 1 2 => rw [left_unitor_inv_naturality]\n slice_lhs 2 3 => rw [id_tensor_comp_tensor_id, ← tensor_id_comp_id_tensor]\n slice_lhs 3 3 => rw [← iso.inv_hom_id_assoc (α_ R.X R.X P.X) (𝟙 R.X ⊗ P.act_left)]\n slice_lhs 4 6 => rw [← category.assoc, ← coequalizer.condition]\n slice_lhs 2 3 => rw [← monoidal_category.tensor_id, associator_inv_naturality]\n slice_lhs 3 4 => rw [← comp_tensor_id, Mon_.one_mul]\n slice_rhs 1 2 => rw [category.comp_id]\n coherence\n#align Bimod.left_unitor_Bimod.hom_inv_id Bimod.LeftUnitorBimod.hom_inv_id\n\ntheorem inv_hom_id : inv P ≫ hom P = 𝟙 _ :=\n by\n dsimp [hom, inv]\n slice_lhs 3 4 => rw [coequalizer.π_desc]\n rw [one_act_left, iso.inv_hom_id]\n#align Bimod.left_unitor_Bimod.inv_hom_id Bimod.LeftUnitorBimod.inv_hom_id\n\nvariable [∀ X : C, PreservesColimitsOfSize.{0, 0} (tensorLeft X)]\n\nvariable [∀ X : C, PreservesColimitsOfSize.{0, 0} (tensorRight X)]\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\ntheorem hom_left_act_hom' :\n ((regular R).tensorBimod P).actLeft ≫ hom P = (𝟙 R.pt ⊗ hom P) ≫ P.actLeft :=\n by\n dsimp; dsimp [hom, tensor_Bimod.act_left, regular]\n refine' (cancel_epi ((tensor_left _).map (coequalizer.π _ _))).1 _\n dsimp\n slice_lhs 1 4 => rw [id_tensor_π_preserves_coequalizer_inv_colimMap_desc]\n slice_lhs 2 3 => rw [left_assoc]\n slice_rhs 1 2 => rw [← id_tensor_comp, coequalizer.π_desc]\n rw [iso.inv_hom_id_assoc]\n#align Bimod.left_unitor_Bimod.hom_left_act_hom' Bimod.LeftUnitorBimod.hom_left_act_hom'\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\ntheorem hom_right_act_hom' :\n ((regular R).tensorBimod P).actRight ≫ hom P = (hom P ⊗ 𝟙 S.pt) ≫ P.actRight :=\n by\n dsimp; dsimp [hom, tensor_Bimod.act_right, regular]\n refine' (cancel_epi ((tensor_right _).map (coequalizer.π _ _))).1 _\n dsimp\n slice_lhs 1 4 => rw [π_tensor_id_preserves_coequalizer_inv_colimMap_desc]\n slice_rhs 1 2 => rw [← comp_tensor_id, coequalizer.π_desc]\n slice_rhs 1 2 => rw [middle_assoc]\n simp only [category.assoc]\n#align Bimod.left_unitor_Bimod.hom_right_act_hom' Bimod.LeftUnitorBimod.hom_right_act_hom'\n\nend LeftUnitorBimod\n\nnamespace RightUnitorBimod\n\nvariable {R S : Mon_ C} (P : Bimod R S)\n\n/-- The underlying morphism of the forward component of the right unitor isomorphism. -/\nnoncomputable def hom : TensorBimod.x P (regular S) ⟶ P.pt :=\n coequalizer.desc P.actRight\n (by\n dsimp\n rw [category.assoc, right_assoc, iso.hom_inv_id_assoc])\n#align Bimod.right_unitor_Bimod.hom Bimod.RightUnitorBimod.hom\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\n/-- The underlying morphism of the inverse component of the right unitor isomorphism. -/\nnoncomputable def inv : P.pt ⟶ TensorBimod.x P (regular S) :=\n (ρ_ P.pt).inv ≫ (𝟙 _ ⊗ S.one) ≫ coequalizer.π _ _\n#align Bimod.right_unitor_Bimod.inv Bimod.RightUnitorBimod.inv\n\ntheorem hom_inv_id : hom P ≫ inv P = 𝟙 _ :=\n by\n dsimp only [hom, inv, tensor_Bimod.X]\n ext; dsimp\n slice_lhs 1 2 => rw [coequalizer.π_desc]\n slice_lhs 1 2 => rw [right_unitor_inv_naturality]\n slice_lhs 2 3 => rw [tensor_id_comp_id_tensor, ← id_tensor_comp_tensor_id]\n slice_lhs 3 4 => rw [coequalizer.condition]\n slice_lhs 2 3 => rw [← monoidal_category.tensor_id, associator_naturality]\n slice_lhs 3 4 => rw [← id_tensor_comp, Mon_.mul_one]\n slice_rhs 1 2 => rw [category.comp_id]\n coherence\n#align Bimod.right_unitor_Bimod.hom_inv_id Bimod.RightUnitorBimod.hom_inv_id\n\ntheorem inv_hom_id : inv P ≫ hom P = 𝟙 _ :=\n by\n dsimp [hom, inv]\n slice_lhs 3 4 => rw [coequalizer.π_desc]\n rw [act_right_one, iso.inv_hom_id]\n#align Bimod.right_unitor_Bimod.inv_hom_id Bimod.RightUnitorBimod.inv_hom_id\n\nvariable [∀ X : C, PreservesColimitsOfSize.{0, 0} (tensorLeft X)]\n\nvariable [∀ X : C, PreservesColimitsOfSize.{0, 0} (tensorRight X)]\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\ntheorem hom_left_act_hom' :\n (P.tensorBimod (regular S)).actLeft ≫ hom P = (𝟙 R.pt ⊗ hom P) ≫ P.actLeft :=\n by\n dsimp; dsimp [hom, tensor_Bimod.act_left, regular]\n refine' (cancel_epi ((tensor_left _).map (coequalizer.π _ _))).1 _\n dsimp\n slice_lhs 1 4 => rw [id_tensor_π_preserves_coequalizer_inv_colimMap_desc]\n slice_lhs 2 3 => rw [middle_assoc]\n slice_rhs 1 2 => rw [← id_tensor_comp, coequalizer.π_desc]\n rw [iso.inv_hom_id_assoc]\n#align Bimod.right_unitor_Bimod.hom_left_act_hom' Bimod.RightUnitorBimod.hom_left_act_hom'\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\ntheorem hom_right_act_hom' :\n (P.tensorBimod (regular S)).actRight ≫ hom P = (hom P ⊗ 𝟙 S.pt) ≫ P.actRight :=\n by\n dsimp; dsimp [hom, tensor_Bimod.act_right, regular]\n refine' (cancel_epi ((tensor_right _).map (coequalizer.π _ _))).1 _\n dsimp\n slice_lhs 1 4 => rw [π_tensor_id_preserves_coequalizer_inv_colimMap_desc]\n slice_lhs 2 3 => rw [right_assoc]\n slice_rhs 1 2 => rw [← comp_tensor_id, coequalizer.π_desc]\n rw [iso.hom_inv_id_assoc]\n#align Bimod.right_unitor_Bimod.hom_right_act_hom' Bimod.RightUnitorBimod.hom_right_act_hom'\n\nend RightUnitorBimod\n\nvariable [∀ X : C, PreservesColimitsOfSize.{0, 0} (tensorLeft X)]\n\nvariable [∀ X : C, PreservesColimitsOfSize.{0, 0} (tensorRight X)]\n\n/-- The associator as a bimodule isomorphism. -/\nnoncomputable def associatorBimod {W X Y Z : Mon_ C} (L : Bimod W X) (M : Bimod X Y)\n (N : Bimod Y Z) : (L.tensorBimod M).tensorBimod N ≅ L.tensorBimod (M.tensorBimod N) :=\n isoOfIso\n { Hom := AssociatorBimod.hom L M N\n inv := AssociatorBimod.inv L M N\n hom_inv_id' := AssociatorBimod.hom_inv_id L M N\n inv_hom_id' := AssociatorBimod.inv_hom_id L M N } (AssociatorBimod.hom_left_act_hom' L M N)\n (AssociatorBimod.hom_right_act_hom' L M N)\n#align Bimod.associator_Bimod Bimod.associatorBimod\n\n/-- The left unitor as a bimodule isomorphism. -/\nnoncomputable def leftUnitorBimod {X Y : Mon_ C} (M : Bimod X Y) : (regular X).tensorBimod M ≅ M :=\n isoOfIso\n { Hom := LeftUnitorBimod.hom M\n inv := LeftUnitorBimod.inv M\n hom_inv_id' := LeftUnitorBimod.hom_inv_id M\n inv_hom_id' := LeftUnitorBimod.inv_hom_id M } (LeftUnitorBimod.hom_left_act_hom' M)\n (LeftUnitorBimod.hom_right_act_hom' M)\n#align Bimod.left_unitor_Bimod Bimod.leftUnitorBimod\n\n/-- The right unitor as a bimodule isomorphism. -/\nnoncomputable def rightUnitorBimod {X Y : Mon_ C} (M : Bimod X Y) : M.tensorBimod (regular Y) ≅ M :=\n isoOfIso\n { Hom := RightUnitorBimod.hom M\n inv := RightUnitorBimod.inv M\n hom_inv_id' := RightUnitorBimod.hom_inv_id M\n inv_hom_id' := RightUnitorBimod.inv_hom_id M } (RightUnitorBimod.hom_left_act_hom' M)\n (RightUnitorBimod.hom_right_act_hom' M)\n#align Bimod.right_unitor_Bimod Bimod.rightUnitorBimod\n\ntheorem whisker_left_comp_bimod {X Y Z : Mon_ C} (M : Bimod X Y) {N P Q : Bimod Y Z} (f : N ⟶ P)\n (g : P ⟶ Q) : tensorHom (𝟙 M) (f ≫ g) = tensorHom (𝟙 M) f ≫ tensorHom (𝟙 M) g := by\n rw [← tensor_comp, category.comp_id]\n#align Bimod.whisker_left_comp_Bimod Bimod.whisker_left_comp_bimod\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\ntheorem id_whisker_left_bimod {X Y : Mon_ C} {M N : Bimod X Y} (f : M ⟶ N) :\n tensorHom (𝟙 (regular X)) f = (leftUnitorBimod M).Hom ≫ f ≫ (leftUnitorBimod N).inv :=\n by\n dsimp [tensor_hom, regular, left_unitor_Bimod]\n ext; dsimp\n slice_lhs 1 2 => rw [ι_colim_map, parallel_pair_hom_app_one]\n dsimp [left_unitor_Bimod.hom]\n slice_rhs 1 2 => rw [coequalizer.π_desc]\n dsimp [left_unitor_Bimod.inv]\n slice_rhs 1 2 => rw [hom.left_act_hom]\n slice_rhs 2 3 => rw [left_unitor_inv_naturality]\n slice_rhs 3 4 => rw [id_tensor_comp_tensor_id, ← tensor_id_comp_id_tensor]\n slice_rhs 4 4 => rw [← iso.inv_hom_id_assoc (α_ X.X X.X N.X) (𝟙 X.X ⊗ N.act_left)]\n slice_rhs 5 7 => rw [← category.assoc, ← coequalizer.condition]\n slice_rhs 3 4 => rw [← monoidal_category.tensor_id, associator_inv_naturality]\n slice_rhs 4 5 => rw [← comp_tensor_id, Mon_.one_mul]\n have : (λ_ (X.X ⊗ N.X)).inv ≫ (α_ (𝟙_ C) X.X N.X).inv ≫ ((λ_ X.X).Hom ⊗ 𝟙 N.X) = 𝟙 _ := by\n pure_coherence\n slice_rhs 2 4 => rw [this]\n slice_rhs 1 2 => rw [category.comp_id]\n#align Bimod.id_whisker_left_Bimod Bimod.id_whisker_left_bimod\n\ntheorem comp_whisker_left_bimod {W X Y Z : Mon_ C} (M : Bimod W X) (N : Bimod X Y)\n {P P' : Bimod Y Z} (f : P ⟶ P') :\n tensorHom (𝟙 (M.tensorBimod N)) f =\n (associatorBimod M N P).Hom ≫\n tensorHom (𝟙 M) (tensorHom (𝟙 N) f) ≫ (associatorBimod M N P').inv :=\n by\n dsimp [tensor_hom, tensor_Bimod, associator_Bimod]\n ext; dsimp\n slice_lhs 1 2 => rw [ι_colim_map, parallel_pair_hom_app_one]\n dsimp [tensor_Bimod.X, associator_Bimod.hom]\n slice_rhs 1 2 => rw [coequalizer.π_desc]\n dsimp [associator_Bimod.hom_aux, associator_Bimod.inv]\n refine' (cancel_epi ((tensor_right _).map (coequalizer.π _ _))).1 _\n rw [tensor_right_map]\n slice_rhs 1 3 => rw [π_tensor_id_preserves_coequalizer_inv_desc]\n slice_rhs 3 4 => rw [ι_colim_map, parallel_pair_hom_app_one]\n slice_rhs 2 3 => rw [← id_tensor_comp, ι_colim_map, parallel_pair_hom_app_one]\n slice_rhs 3 4 => rw [coequalizer.π_desc]\n dsimp [associator_Bimod.inv_aux]\n slice_rhs 2 2 => rw [id_tensor_comp]\n slice_rhs 3 5 => rw [id_tensor_π_preserves_coequalizer_inv_desc]\n slice_rhs 2 3 => rw [associator_inv_naturality]\n slice_rhs 1 3 => rw [iso.hom_inv_id_assoc, monoidal_category.tensor_id]\n slice_lhs 1 2 => rw [tensor_id_comp_id_tensor, ← id_tensor_comp_tensor_id]\n dsimp only [tensor_Bimod.X]\n simp only [category.assoc]\n#align Bimod.comp_whisker_left_Bimod Bimod.comp_whisker_left_bimod\n\ntheorem comp_whisker_right_bimod {X Y Z : Mon_ C} {M N P : Bimod X Y} (f : M ⟶ N) (g : N ⟶ P)\n (Q : Bimod Y Z) : tensorHom (f ≫ g) (𝟙 Q) = tensorHom f (𝟙 Q) ≫ tensorHom g (𝟙 Q) := by\n rw [← tensor_comp, category.comp_id]\n#align Bimod.comp_whisker_right_Bimod Bimod.comp_whisker_right_bimod\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\n/- ./././Mathport/Syntax/Translate/Expr.lean:177:8: unsupported: ambiguous notation -/\ntheorem whisker_right_id_bimod {X Y : Mon_ C} {M N : Bimod X Y} (f : M ⟶ N) :\n tensorHom f (𝟙 (regular Y)) = (rightUnitorBimod M).Hom ≫ f ≫ (rightUnitorBimod N).inv :=\n by\n dsimp [tensor_hom, regular, right_unitor_Bimod]\n ext; dsimp\n slice_lhs 1 2 => rw [ι_colim_map, parallel_pair_hom_app_one]\n dsimp [right_unitor_Bimod.hom]\n slice_rhs 1 2 => rw [coequalizer.π_desc]\n dsimp [right_unitor_Bimod.inv]\n slice_rhs 1 2 => rw [hom.right_act_hom]\n slice_rhs 2 3 => rw [right_unitor_inv_naturality]\n slice_rhs 3 4 => rw [tensor_id_comp_id_tensor, ← id_tensor_comp_tensor_id]\n slice_rhs 4 5 => rw [coequalizer.condition]\n slice_rhs 3 4 => rw [← monoidal_category.tensor_id, associator_naturality]\n slice_rhs 4 5 => rw [← id_tensor_comp, Mon_.mul_one]\n have : (ρ_ (N.X ⊗ Y.X)).inv ≫ (α_ N.X Y.X (𝟙_ C)).Hom ≫ (𝟙 N.X ⊗ (ρ_ Y.X).Hom) = 𝟙 _ := by\n pure_coherence\n slice_rhs 2 4 => rw [this]\n slice_rhs 1 2 => rw [category.comp_id]\n#align Bimod.whisker_right_id_Bimod Bimod.whisker_right_id_bimod\n\ntheorem whisker_right_comp_bimod {W X Y Z : Mon_ C} {M M' : Bimod W X} (f : M ⟶ M') (N : Bimod X Y)\n (P : Bimod Y Z) :\n tensorHom f (𝟙 (N.tensorBimod P)) =\n (associatorBimod M N P).inv ≫\n tensorHom (tensorHom f (𝟙 N)) (𝟙 P) ≫ (associatorBimod M' N P).Hom :=\n by\n dsimp [tensor_hom, tensor_Bimod, associator_Bimod]\n ext; dsimp\n slice_lhs 1 2 => rw [ι_colim_map, parallel_pair_hom_app_one]\n dsimp [tensor_Bimod.X, associator_Bimod.inv]\n slice_rhs 1 2 => rw [coequalizer.π_desc]\n dsimp [associator_Bimod.inv_aux, associator_Bimod.hom]\n refine' (cancel_epi ((tensor_left _).map (coequalizer.π _ _))).1 _\n rw [tensor_left_map]\n slice_rhs 1 3 => rw [id_tensor_π_preserves_coequalizer_inv_desc]\n slice_rhs 3 4 => rw [ι_colim_map, parallel_pair_hom_app_one]\n slice_rhs 2 3 => rw [← comp_tensor_id, ι_colim_map, parallel_pair_hom_app_one]\n slice_rhs 3 4 => rw [coequalizer.π_desc]\n dsimp [associator_Bimod.hom_aux]\n slice_rhs 2 2 => rw [comp_tensor_id]\n slice_rhs 3 5 => rw [π_tensor_id_preserves_coequalizer_inv_desc]\n slice_rhs 2 3 => rw [associator_naturality]\n slice_rhs 1 3 => rw [iso.inv_hom_id_assoc, monoidal_category.tensor_id]\n slice_lhs 1 2 => rw [id_tensor_comp_tensor_id, ← tensor_id_comp_id_tensor]\n dsimp only [tensor_Bimod.X]\n simp only [category.assoc]\n#align Bimod.whisker_right_comp_Bimod Bimod.whisker_right_comp_bimod\n\ntheorem whisker_assoc_bimod {W X Y Z : Mon_ C} (M : Bimod W X) {N N' : Bimod X Y} (f : N ⟶ N')\n (P : Bimod Y Z) :\n tensorHom (tensorHom (𝟙 M) f) (𝟙 P) =\n (associatorBimod M N P).Hom ≫\n tensorHom (𝟙 M) (tensorHom f (𝟙 P)) ≫ (associatorBimod M N' P).inv :=\n by\n dsimp [tensor_hom, tensor_Bimod, associator_Bimod]\n ext; dsimp\n slice_lhs 1 2 => rw [ι_colim_map, parallel_pair_hom_app_one]\n dsimp [associator_Bimod.hom]\n slice_rhs 1 2 => rw [coequalizer.π_desc]\n dsimp [associator_Bimod.hom_aux]\n refine' (cancel_epi ((tensor_right _).map (coequalizer.π _ _))).1 _\n rw [tensor_right_map]\n slice_lhs 1 2 => rw [← comp_tensor_id, ι_colim_map, parallel_pair_hom_app_one]\n slice_rhs 1 3 => rw [π_tensor_id_preserves_coequalizer_inv_desc]\n slice_rhs 3 4 => rw [ι_colim_map, parallel_pair_hom_app_one]\n slice_rhs 2 3 => rw [← id_tensor_comp, ι_colim_map, parallel_pair_hom_app_one]\n dsimp [associator_Bimod.inv]\n slice_rhs 3 4 => rw [coequalizer.π_desc]\n dsimp [associator_Bimod.inv_aux]\n slice_rhs 2 2 => rw [id_tensor_comp]\n slice_rhs 3 5 => rw [id_tensor_π_preserves_coequalizer_inv_desc]\n slice_rhs 2 3 => rw [associator_inv_naturality]\n slice_rhs 1 3 => rw [iso.hom_inv_id_assoc]\n slice_lhs 1 1 => rw [comp_tensor_id]\n#align Bimod.whisker_assoc_Bimod Bimod.whisker_assoc_bimod\n\ntheorem whisker_exchange_bimod {X Y Z : Mon_ C} {M N : Bimod X Y} {P Q : Bimod Y Z} (f : M ⟶ N)\n (g : P ⟶ Q) : tensorHom (𝟙 M) g ≫ tensorHom f (𝟙 Q) = tensorHom f (𝟙 P) ≫ tensorHom (𝟙 N) g :=\n by\n dsimp [tensor_hom]\n ext; dsimp\n slice_lhs 1 2 => rw [ι_colim_map, parallel_pair_hom_app_one]\n slice_lhs 2 3 => rw [ι_colim_map, parallel_pair_hom_app_one]\n slice_lhs 1 2 => rw [id_tensor_comp_tensor_id]\n slice_rhs 1 2 => rw [ι_colim_map, parallel_pair_hom_app_one]\n slice_rhs 2 3 => rw [ι_colim_map, parallel_pair_hom_app_one]\n slice_rhs 1 2 => rw [tensor_id_comp_id_tensor]\n#align Bimod.whisker_exchange_Bimod Bimod.whisker_exchange_bimod\n\ntheorem pentagon_bimod {V W X Y Z : Mon_ C} (M : Bimod V W) (N : Bimod W X) (P : Bimod X Y)\n (Q : Bimod Y Z) :\n tensorHom (associatorBimod M N P).Hom (𝟙 Q) ≫\n (associatorBimod M (N.tensorBimod P) Q).Hom ≫ tensorHom (𝟙 M) (associatorBimod N P Q).Hom =\n (associatorBimod (M.tensorBimod N) P Q).Hom ≫ (associatorBimod M N (P.tensorBimod Q)).Hom :=\n by\n dsimp [tensor_hom, associator_Bimod]; ext; dsimp\n dsimp only [associator_Bimod.hom]\n slice_lhs 1 2 => rw [ι_colim_map, parallel_pair_hom_app_one]\n slice_lhs 2 3 => rw [coequalizer.π_desc]\n slice_rhs 1 2 => rw [coequalizer.π_desc]\n dsimp [associator_Bimod.hom_aux]\n refine' (cancel_epi ((tensor_right _).map (coequalizer.π _ _))).1 _\n dsimp\n slice_lhs 1 2 => rw [← comp_tensor_id, coequalizer.π_desc]\n slice_rhs 1 3 => rw [π_tensor_id_preserves_coequalizer_inv_desc]\n slice_rhs 3 4 => rw [coequalizer.π_desc]\n refine' (cancel_epi ((tensor_right _ ⋙ tensor_right _).map (coequalizer.π _ _))).1 _\n dsimp\n slice_lhs 1 2 =>\n rw [← comp_tensor_id, π_tensor_id_preserves_coequalizer_inv_desc, comp_tensor_id,\n comp_tensor_id]\n slice_lhs 3 5 => rw [π_tensor_id_preserves_coequalizer_inv_desc]\n dsimp only [tensor_Bimod.X]\n slice_lhs 2 3 => rw [associator_naturality]\n slice_lhs 5 6 => rw [ι_colim_map, parallel_pair_hom_app_one]\n slice_lhs 4 5 => rw [← id_tensor_comp, coequalizer.π_desc]\n slice_lhs 3 4 =>\n rw [← id_tensor_comp, π_tensor_id_preserves_coequalizer_inv_desc, id_tensor_comp,\n id_tensor_comp]\n slice_rhs 1 2 => rw [associator_naturality]\n slice_rhs 2 3 =>\n rw [monoidal_category.tensor_id, tensor_id_comp_id_tensor, ← id_tensor_comp_tensor_id]\n slice_rhs 3 5 => rw [π_tensor_id_preserves_coequalizer_inv_desc]\n slice_rhs 2 3 => rw [← monoidal_category.tensor_id, associator_naturality]\n coherence\n#align Bimod.pentagon_Bimod Bimod.pentagon_bimod\n\ntheorem triangle_bimod {X Y Z : Mon_ C} (M : Bimod X Y) (N : Bimod Y Z) :\n (associatorBimod M (regular Y) N).Hom ≫ tensorHom (𝟙 M) (leftUnitorBimod N).Hom =\n tensorHom (rightUnitorBimod M).Hom (𝟙 N) :=\n by\n dsimp [tensor_hom, associator_Bimod, left_unitor_Bimod, right_unitor_Bimod]\n ext; dsimp\n dsimp [associator_Bimod.hom]\n slice_lhs 1 2 => rw [coequalizer.π_desc]\n dsimp [associator_Bimod.hom_aux]\n slice_rhs 1 2 => rw [ι_colim_map, parallel_pair_hom_app_one]\n dsimp [right_unitor_Bimod.hom]\n refine' (cancel_epi ((tensor_right _).map (coequalizer.π _ _))).1 _\n dsimp [regular]\n slice_lhs 1 3 => rw [π_tensor_id_preserves_coequalizer_inv_desc]\n slice_lhs 3 4 => rw [ι_colim_map, parallel_pair_hom_app_one]\n dsimp [left_unitor_Bimod.hom]\n slice_lhs 2 3 => rw [← id_tensor_comp, coequalizer.π_desc]\n slice_rhs 1 2 => rw [← comp_tensor_id, coequalizer.π_desc]\n slice_rhs 1 2 => rw [coequalizer.condition]\n simp only [category.assoc]\n#align Bimod.triangle_Bimod Bimod.triangle_bimod\n\n/-- The bicategory of algebras (monoids) and bimodules, all internal to some monoidal category. -/\nnoncomputable def monBicategory : Bicategory (Mon_ C)\n where\n Hom X Y := Bimod X Y\n id X := regular X\n comp _ _ _ M N := tensorBimod M N\n whiskerLeft _ _ _ L _ _ f := tensorHom (𝟙 L) f\n whiskerRight _ _ _ _ _ f N := tensorHom f (𝟙 N)\n associator _ _ _ _ L M N := associatorBimod L M N\n leftUnitor _ _ M := leftUnitorBimod M\n rightUnitor _ _ M := rightUnitorBimod M\n whiskerLeft_id _ _ _ _ _ := tensor_id\n whiskerLeft_comp _ _ _ M _ _ _ f g := whisker_left_comp_bimod M f g\n id_whiskerLeft _ _ _ _ f := id_whisker_left_bimod f\n comp_whiskerLeft _ _ _ _ M N _ _ f := comp_whisker_left_bimod M N f\n id_whiskerRight _ _ _ _ _ := tensor_id\n comp_whiskerRight _ _ _ _ _ _ f g Q := comp_whisker_right_bimod f g Q\n whiskerRight_id _ _ _ _ f := whisker_right_id_bimod f\n whiskerRight_comp _ _ _ _ _ _ f N P := whisker_right_comp_bimod f N P\n whisker_assoc _ _ _ _ M _ _ f P := whisker_assoc_bimod M f P\n whisker_exchange _ _ _ _ _ _ _ f g := whisker_exchange_bimod f g\n pentagon _ _ _ _ _ M N P Q := pentagon_bimod M N P Q\n triangle _ _ _ M N := triangle_bimod M N\n#align Bimod.Mon_bicategory Bimod.monBicategory\n\nend Bimod\n\n", "meta": {"author": "leanprover-community", "repo": "mathlib3port", "sha": "62505aa236c58c8559783b16d33e30df3daa54f4", "save_path": "github-repos/lean/leanprover-community-mathlib3port", "path": "github-repos/lean/leanprover-community-mathlib3port/mathlib3port-62505aa236c58c8559783b16d33e30df3daa54f4/Mathbin/CategoryTheory/Monoidal/Bimod.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3886180267058489, "lm_q2_score": 0.025178840191895407, "lm_q1q2_score": 0.00978495119011631}} {"text": "import Iris.BI\n\nnamespace Iris.Proofmode\nopen Iris.BI\n\n/- The two type classes `AsEmpValid1` and `AsEmpValid2` are necessary since type class instance\nsearch is used in both directions in `as_emp_valid_1` and `as_emp_valid_2`. When type class\ninstance search is supposed to generate `φ` based on `P`, `AsEmpValid1` is used, since `φ` is declared as an\n`outParam`. Consequently, if type class instance search is supposed to generate `P`, `AsEmpValid2`\nis used. -/\n\nclass AsEmpValid1 (φ : outParam Prop) {PROP : Type} (P : PROP) where\n [bi : BI PROP]\n as_emp_valid : φ ↔ ⊢ P\n\nclass AsEmpValid2 (φ : Prop) {PROP : outParam Type} (P : outParam PROP) where\n [bi : BI PROP]\n as_emp_valid : φ ↔ ⊢ P\n\nattribute [instance (default - 100)] AsEmpValid1.bi\nattribute [instance (default - 100)] AsEmpValid2.bi\n\nclass AsEmpValid (φ : Prop) {PROP : Type} (P : PROP) extends\n AsEmpValid1 φ P,\n AsEmpValid2 φ P\n\ntheorem as_emp_valid_1 (P : PROP) [AsEmpValid1 φ P] : φ → ⊢ P :=\n AsEmpValid1.as_emp_valid.mp\ntheorem as_emp_valid_2 (φ : Prop) [AsEmpValid2 φ P] : (⊢ P) → φ :=\n AsEmpValid2.as_emp_valid.mpr\n\n\n/- Depending on the use case, type classes with the prefix `From` or `Into` are used. Type classes\nwith the prefix `From` are used to generate one or more propositions *from* which the original\nproposition can be derived. Type classes with the prefix `Into` are used to generate propositions\n*into* which the original proposition can be turned by derivation. Additional boolean flags are\nused to indicate that certain propositions should be intuitionistic. -/\n\nclass FromImpl [BI PROP] (P : PROP) (Q1 Q2 : outParam PROP) where\n from_impl : (Q1 → Q2) ⊢ P\nexport FromImpl (from_impl)\n\nclass FromWand [BI PROP] (P : PROP) (Q1 Q2 : outParam PROP) where\n from_wand : (Q1 -∗ Q2) ⊢ P\nexport FromWand (from_wand)\n\nclass IntoWand [BI PROP] (p q : Bool) (R P : PROP) (Q : outParam PROP) where\n into_wand : □?p R ⊢ □?q P -∗ Q\nexport IntoWand (into_wand)\n\nclass FromForall [BI PROP] (P : PROP) {α : outParam Type} (Ψ : outParam <| α → PROP) where\n from_forall : (∀ x, Ψ x) ⊢ P\nexport FromForall (from_forall)\n\nclass IntoForall [BI PROP] (P : PROP) {α : outParam Type} (Φ : outParam <| α → PROP) where\n into_forall : P ⊢ ∀ x, Φ x\nexport IntoForall (into_forall)\n\nclass FromExist [BI PROP] (P : PROP) {α : outParam Type} (Φ : outParam <| α → PROP) where\n from_exist : (∃ x, Φ x) ⊢ P\nexport FromExist (from_exist)\n\nclass IntoExist [BI PROP] (P : PROP) {α : outParam Type} (Φ : outParam <| α → PROP) where\n into_exist : P ⊢ ∃ x, Φ x\nexport IntoExist (into_exist)\n\nclass FromAnd [BI PROP] (P : PROP) (Q1 Q2 : outParam PROP) where\n from_and : Q1 ∧ Q2 ⊢ P\nexport FromAnd (from_and)\n\nclass IntoAnd (p : Bool) [BI PROP] (P : PROP) (Q1 Q2 : outParam PROP) where\n into_and : □?p P ⊢ □?p (Q1 ∧ Q2)\nexport IntoAnd (into_and)\n\nclass FromSep [BI PROP] (P : PROP) (Q1 Q2 : outParam PROP) where\n from_sep : Q1 ∗ Q2 ⊢ P\nexport FromSep (from_sep)\n\nclass IntoSep [BI PROP] (P : PROP) (Q1 Q2 : outParam PROP) :=\n into_sep : P ⊢ Q1 ∗ Q2\nexport IntoSep (into_sep)\n\nclass FromOr [BI PROP] (P : PROP) (Q1 Q2 : outParam PROP) where\n from_or : Q1 ∨ Q2 ⊢ P\nexport FromOr (from_or)\n\nclass IntoOr [BI PROP] (P : PROP) (Q1 Q2 : outParam PROP) where\n into_or : P ⊢ Q1 ∨ Q2\nexport IntoOr (into_or)\n\n\nclass IntoPersistent (p : Bool) [BI PROP] (P : PROP) (Q : outParam PROP) where\n into_persistent : ?p P ⊢ Q\nexport IntoPersistent (into_persistent)\n\nclass FromAffinely [BI PROP] (P : outParam PROP) (Q : PROP) (p : Bool := true) where\n from_affinely : ?p Q ⊢ P\nexport FromAffinely (from_affinely)\n\nclass IntoAbsorbingly [BI PROP] (P : outParam PROP) (Q : PROP) where\n into_absorbingly : P ⊢ Q\nexport IntoAbsorbingly (into_absorbingly)\n\n\nclass FromAssumption (p : Bool) [BI PROP] (P Q : PROP) where\n from_assumption : □?p P ⊢ Q\nexport FromAssumption (from_assumption)\n\nclass IntoPure [BI PROP] (P : PROP) (φ : outParam Prop) where\n into_pure : P ⊢ ⌜φ⌝\nexport IntoPure (into_pure)\n\nclass FromPure [BI PROP] (a : outParam Bool) (P : PROP) (φ : outParam Prop) where\n from_pure : ?a ⌜φ⌝ ⊢ P\nexport FromPure (from_pure)\n\nend Iris.Proofmode\n", "meta": {"author": "larsk21", "repo": "iris-lean", "sha": "730e644d0ffaad78aac76e2e5f2cd8af0f1d2310", "save_path": "github-repos/lean/larsk21-iris-lean", "path": "github-repos/lean/larsk21-iris-lean/iris-lean-730e644d0ffaad78aac76e2e5f2cd8af0f1d2310/src/Iris/Proofmode/Classes.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3380771374883919, "lm_q2_score": 0.02887090433510374, "lm_q1q2_score": 0.009760592694313076}} {"text": "import breen_deligne.eval1half\nimport for_mathlib.nat_iso_map_homological_complex\n\nnoncomputable theory\n\nuniverses v\n\nnamespace category_theory\nnamespace preadditive\nopen category_theory category_theory.limits\n\nvariables {C D : Type*} [category.{v} C] [category.{v} D] [preadditive C] [preadditive D]\n [has_finite_biproducts C] [has_finite_biproducts D] (F : C ⥤ D) [functor.additive F]\n (F' : C ⥤ D) [functor.additive F'] (τ : F ⟶ F') (n : ℕ)\n\n@[simps]\ndef apply_Pow : Pow n ⋙ F ≅ F ⋙ Pow n := nat_iso.of_components (λ A,\n { hom := biproduct.lift (λ i, F.map (biproduct.π _ i)),\n inv := biproduct.desc (λ i, F.map (biproduct.ι _ i)),\n hom_inv_id' := by simpa only [biproduct.lift_desc, ← F.map_comp, ← F.map_sum,\n biproduct.total] using F.map_id _,\n inv_hom_id' := begin\n ext i j,\n by_cases i = j,\n { subst h,\n dsimp,\n simp only [biproduct.ι_desc_assoc, category.assoc, biproduct.lift_π,\n category.comp_id, biproduct.ι_π_self, ← F.map_comp, F.map_id], },\n { dsimp,\n simp only [biproduct.ι_desc_assoc, category.assoc, biproduct.lift_π,\n category.comp_id, ← F.map_comp, limits.biproduct.ι_π_ne _ h,\n functor.map_zero], },\n end, })\n(λ X Y f, by { ext, simp only [category.assoc, biproduct.lift_π,\n functor.comp_map, Pow_map, biproduct.lift_map, ← F.map_comp, biproduct.map_π], })\n\nlemma apply_Pow_naturality (M : C) :\n τ.app ((Pow n).obj M) ≫ (apply_Pow F' n).hom.app M =\n (apply_Pow F n).hom.app M ≫ (Pow n).map (τ.app M) :=\nbegin\n rw [← cancel_epi ((apply_Pow F n).inv.app M)],\n slice_rhs 1 2 { rw [← nat_trans.comp_app, iso.inv_hom_id], },\n erw category.id_comp,\n apply limits.biproduct.hom_ext,\n intro j,\n apply limits.biproduct.hom_ext',\n intro i,\n simp only [apply_Pow_inv_app, apply_Pow_hom_app, category.assoc,\n biproduct.lift_π, biproduct.ι_desc_assoc, Pow_map, biproduct.map_π],\n erw [τ.naturality_assoc, ← F'.map_comp],\n by_cases i = j,\n { subst h,\n erw [biproduct.ι_π_self_assoc, biproduct.ι_π_self, F'.map_id, category.comp_id], },\n { erw [biproduct.ι_π_ne_assoc _ h, biproduct.ι_π_ne _ h, F'.map_zero, comp_zero, zero_comp], },\nend\n\nopen breen_deligne breen_deligne.universal_map\n\nvariables {A₁ A₂ : Type*} [category.{v} A₁] [category.{v} A₂] [preadditive A₁] [preadditive A₂]\n [has_finite_biproducts A₁] [has_finite_biproducts A₂]\n (F₁ : A₁ ⥤ A₁) (F₂ : A₂ ⥤ A₂) (G : A₁ ⥤ A₂)\n [functor.additive G]\n\ndef eval_Pow_functor_comp (e : F₁ ⋙ G ≅ G ⋙ F₂) :\n eval_Pow_functor F₂ ⋙ ((whiskering_left _ _ A₂).obj G) ≅\n eval_Pow_functor F₁ ⋙ (whiskering_right A₁ _ _).obj G :=\nnat_iso.of_components\n(λ n, begin\n apply iso.symm,\n refine (functor.associator _ _ _) ≪≫ iso_whisker_left _ e ≪≫ _,\n refine (functor.associator _ _ _).symm ≪≫ _ ≪≫ (functor.associator _ _ _),\n refine iso_whisker_right (apply_Pow G n) _,\nend)\n(λ n m f, begin\n ext M,\n dsimp only [whiskering_right, whiskering_left, functor.associator, iso.symm,\n iso_whisker_left, iso_whisker_right, iso.trans, nat_trans.comp_app,\n functor.map_iso, eval_Pow_functor, functor.comp_map, whisker_right, whisker_left],\n repeat { erw category.id_comp, },\n repeat { erw category.comp_id, },\n rw [map_eval_Pow f F₁ G M, category.assoc, ← congr_eval_Pow' f e.inv],\n simp only [← category.assoc],\n congr' 1,\n revert f,\n let φ₁ : universal_map n m →+ ((G ⋙ Pow n ⋙ F₂).obj M ⟶ F₂.obj ((Pow m ⋙ G).obj M)) :=\n { to_fun := λ f, ((eval_Pow F₂) f).app (G.obj M) ≫ F₂.map ((apply_Pow G m).inv.app M),\n map_zero' := by simp only [eval_Pow_zero, nat_trans.app_zero, zero_comp],\n map_add' := λ f₁ f₂, by simp only [map_add, nat_trans.app_add, add_comp], },\n let φ₂ : universal_map n m →+ ((G ⋙ Pow n ⋙ F₂).obj M ⟶ F₂.obj ((Pow m ⋙ G).obj M)) :=\n { to_fun := λ f, F₂.map ((apply_Pow G n).inv.app M) ≫ ((eval_Pow' (G ⋙ F₂)) f).app M,\n map_zero' := by simp only [map_zero, nat_trans.app_zero, comp_zero],\n map_add' := λ f₁ f₂, by simp only [map_add, nat_trans.app_add, comp_add], },\n suffices : φ₁ = φ₂,\n { intro f,\n change φ₁ f = φ₂ f,\n rw this, },\n ext f,\n dsimp only [φ₁, φ₂], clear φ₁ φ₂,\n simp only [add_monoid_hom.coe_mk, eval_Pow'_of, eval_Pow_of, whisker_right_app,\n ← F₂.map_comp, functor.comp_map],\n congr' 1,\n erw [← cancel_mono ((apply_Pow G m).hom.app M), category.assoc,\n ← nat_trans.comp_app, iso.inv_hom_id, nat_trans.id_app, category.comp_id],\n simp only [basic_universal_map.eval_Pow_app, apply_Pow_inv_app,\n apply_Pow_hom_app, category.assoc],\n apply limits.biproduct.hom_ext,\n intro j,\n apply limits.biproduct.hom_ext',\n intro i,\n simp only [biproduct.matrix_π, biproduct.ι_desc, category.assoc, biproduct.lift_π,\n biproduct.ι_desc_assoc, ← G.map_comp, G.map_zsmul, G.map_id],\nend)\n\nend preadditive\n\nend category_theory\n\nnamespace breen_deligne\n\nnamespace data\n\nopen category_theory category_theory.limits category_theory.preadditive\nopen universal_map\n\nvariables {A₁ A₂ : Type*} [category.{v} A₁] [category.{v} A₂]\n (BD : data)\n (F₁ : A₁ ⥤ A₁) (F₂ : A₂ ⥤ A₂) (G : A₁ ⥤ A₂)\n (e : F₁ ⋙ G ≅ G ⋙ F₂)\n\nvariables [preadditive A₂]\n\ninstance additive_whiskering_left :\n functor.additive ((whiskering_left _ _ A₂).obj G) := { }\n\nvariables [preadditive A₁] [functor.additive G]\n\ninstance additive_whiskering_right :\n functor.additive ((whiskering_right A₁ _ _).obj G) := { }\n\nvariables [has_finite_biproducts A₁] [has_finite_biproducts A₂]\n\ninclude e\ndef eval_functor'_comp :\n (eval_functor' F₂ ⋙ ((whiskering_left _ _ A₂).obj G).map_homological_complex _ ≅\n eval_functor' F₁ ⋙ ((whiskering_right A₁ _ _).obj G).map_homological_complex _) :=\ncategory_theory.nat_iso.map_homological_complex (eval_Pow_functor_comp F₁ F₂ G e) _\n\ndef eval_functor_comp :\n eval_functor F₂ ⋙ (whiskering_left _ _ _).obj G ≅\n eval_functor F₁ ⋙ (whiskering_right A₁ _ _).obj (G.map_homological_complex _) :=\niso_whisker_right (eval_functor'_comp F₁ F₂ G e) homological_complex.functor_eval.flip\n\nend data\n\nend breen_deligne\n", "meta": {"author": "leanprover-community", "repo": "lean-liquid", "sha": "92f188bd17f34dbfefc92a83069577f708851aec", "save_path": "github-repos/lean/leanprover-community-lean-liquid", "path": "github-repos/lean/leanprover-community-lean-liquid/lean-liquid-92f188bd17f34dbfefc92a83069577f708851aec/src/breen_deligne/apply_Pow.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.47657965106367595, "lm_q2_score": 0.02033235334265875, "lm_q1q2_score": 0.009689985861347672}} {"text": "import category_theory.category.basic\n\nimport topos\nimport subobject_classifier\nimport presheaf\nimport forcing.semantics\n\nopen category_theory category_theory.category category_theory.limits classifier \n\nuniverses v u\n\nnoncomputable theory\n\n\nvariables {C : Type u} [category.{u} C] [small_category C]\n\n\nnamespace forcing\n\nlocal notation `°`:std.prec.max_plus C := Cᵒᵖ ⥤ Type u\nlocal notation `₸` := ⊤_ (°C)\n\n-- Abbreviation for Yoneda on objects and on maps\nabbreviation yob (c : Cᵒᵖ) := yoneda.obj c.unop\nabbreviation yom {c d : Cᵒᵖ} (f : c ⟶ d) : yob d ⟶ yob c := yoneda.map f.unop\n\nstructure forces {X : °C} (σ : X ⟶ Ω °C) {c : Cᵒᵖ} (x : yob c ⟶ X) :=\n(lift : yob c ⟶ s{ σ }s)\n(comm' : lift ≫ canonical_incl σ = x. obviously)\n\nrestate_axiom forces.comm'\nattribute [simp, reassoc] forces.comm\n\n@[ext]\nprotected lemma lift_ext {X : °C} (σ : X ⟶ Ω °C) {c : Cᵒᵖ} (x : yob c ⟶ X) : \n Π {α β : forces σ x}, α.lift = β.lift → α = β\n| ⟨Ra, _⟩ ⟨Sa, _⟩ rfl := rfl\n\ninstance subsingleton_forces {X : °C} (σ : X ⟶ Ω °C) {c : Cᵒᵖ} (x : yob c ⟶ X) : \n subsingleton (forces σ x) :=\nbegin\n fsplit, intros, ext1,\n apply pullback.hom_ext,\n { rw [a.comm, b.comm] },\n { simp }\nend\n\ndef pforces {X : °C} (σ : X ⟶ Ω °C) {c : Cᵒᵖ} (x : yob c ⟶ X) : Prop := \n ∃ lift : yob c ⟶ s{ σ }s, lift ≫ canonical_incl σ = x \n\nvariables {X : °C} (σ : X ⟶ Ω °C) {c : Cᵒᵖ} (x : yob c ⟶ X)\n\nlemma forces_to_pforces {x : yob c ⟶ X} (α : forces σ x) : pforces σ x := ⟨α.lift, α.comm⟩\nlemma pforces_to_forces {x : yob c ⟶ X} (α : pforces σ x) : forces σ x :=\n{ lift := (classical.indefinite_description _ α).val,\n comm' := (classical.indefinite_description _ α).prop }\n\nlemma pforces_of_valid (h : validity.is_valid σ) : pforces σ x :=\nbegin\n rw validity.valid_iff_is_iso at h,\n resetI,\n refine ⟨ x ≫ (as_iso (canonical_incl σ)).inv, _ ⟩,\n rw [assoc, as_iso_inv, is_iso.inv_hom_id, comp_id]\nend\n\nlemma valid_yoneda_iff_pforces : \n pforces σ x ↔ validity.is_valid (x ≫ σ) :=\nbegin\n split,\n { intro h, cases h with w h, dunfold validity.is_valid,\n rw [←h, assoc, canonical_incl_comm, ←assoc, limits.terminal.comp_from w]\n },\n { intro h, dunfold validity.is_valid at h,\n exact ⟨pullback.lift x (terminal.from (yob c)) h, pullback.lift_fst _ _ _⟩ }\nend\n\ndef π_el.obj (d : (X.elements)ᵒᵖ) := (category_of_elements.π X).obj d.unop\ndef π_el.map {d e : (X.elements)ᵒᵖ} (f : d ⟶ e) : π_el.obj e ⟶ π_el.obj d := \n(category_of_elements.π X).map f.unop\n\n@[simp] lemma simp_el_yob (d : (X.elements)ᵒᵖ) : \n (functor_to_representables X).obj d = yob (π_el.obj d) := \nbegin\n unfold functor_to_representables π_el.obj,\n rw functor.comp_obj,\n simp\nend\n-- set_option trace.simp_lemmas true\ndef forall_pforces_to_cocone (u : ∀ (c : Cᵒᵖ) (x : yob c ⟶ X), forces σ x) : \n cocone (functor_to_representables X) :=\n{ X := s{ σ }s, \n ι := { app := λ d, (u (π_el.obj d) ((cocone_of_representable X).ι.app d)).lift,\n naturality' := \n begin\n intros d e f,\n dunfold functor_to_representables, \n simp only [functor.comp_map, functor.left_op_map, category_of_elements.π_map, \n subtype.val_eq_coe, functor.const_obj_map],\n rw [@comp_id _ _ _ (s{σ}s), ←cancel_mono (canonical_incl σ), assoc, (u _ _).comm,\n (u _ _).comm, cocone_of_representable_ι_app, cocone_of_representable_ι_app],\n dsimp, ext, \n simp only [functor_to_types.comp, yoneda_map_app, yoneda_sections_small_inv_app_apply, \n op_comp, quiver.hom.op_unop, functor_to_types.map_comp_apply], \n rw f.unop.prop,\n end } }\n\n@[simp] lemma test (u : ∀ (c : Cᵒᵖ) (x : yob c ⟶ X), forces σ x) (d : (functor.elements X)ᵒᵖ) : \n (forall_pforces_to_cocone σ u).ι.app d = \n (u (π_el.obj d) ((cocone_of_representable X).ι.app d)).lift := by { refl }\n\ndef forall_pforces_to_split_epi (u : ∀ (c : Cᵒᵖ) (x : yob c ⟶ X), forces σ x) : \n split_epi (canonical_incl σ) := \n{ section_ := is_colimit.desc (colimit_of_representable X) (forall_pforces_to_cocone σ u),\n id' := \n begin\n apply is_colimit.hom_ext (colimit_of_representable X),\n intro d, \n rw @comp_id _ _ _ X,\n simp\n end\n}\n\n-- http://chanavat.site/files/lmfi-thesis.pdf Theorem 2.10 \nlemma valid_iff_forall_pforces {X : °C} (σ : X ⟶ Ω °C) :\n validity.is_valid σ ↔ ∀ (c : Cᵒᵖ) (x : yob c ⟶ X), pforces σ x :=\nbegin\n split,\n { rw validity.valid_iff_is_iso, intros h c x, \n cases h.out with incl_inv h,\n use x ≫ incl_inv,\n rw [assoc, h.right, comp_id] },\n { rw validity.valid_iff_section, intro u,\n fsplit, fsplit,\n exact forall_pforces_to_split_epi σ (λ c x, pforces_to_forces σ (u c x)) }\nend\n\nlemma monotonicity (h : forces σ x) {b : Cᵒᵖ} (f : c ⟶ b) : forces σ (yom f ≫ x) :=\n{ lift := yom f ≫ h.lift,\n comm' := by rw [assoc, h.comm] }\n\ndef yob_terminal_iso_terminal [has_terminal C] : (yob (opposite.op (⊤_ C))) ≅ ₸ :=\nbegin\n rw [←as_empty_cone_X (⊤_ °C), ←as_empty_cone_X (yob (opposite.op (⊤_ C)))],\n apply is_limit.cone_point_unique_up_to_iso,\n { apply category_theory.limits.is_terminal.is_terminal_obj, exact terminal_is_terminal },\n { exact terminal_is_terminal }\nend\n\nlemma closed_valid_iff_forces_terminal [has_terminal C] (τ : ₸ ⟶ Ω °C) : \n pforces τ (terminal.from (yob (opposite.op (⊤_ C)))) ↔ validity.is_valid τ :=\nbegin\n rw validity.valid_iff_section,\n split,\n { intro u, fsplit, fsplit,\n refine ⟨yob_terminal_iso_terminal.inv ≫ (pforces_to_forces _ u).lift, _⟩,\n simp only [eq_iff_true_of_subsingleton],\n },\n { intro h, \n resetI,\n refine ⟨yob_terminal_iso_terminal.hom ≫ (section_ (canonical_incl τ)), _⟩,\n rw [assoc, is_split_epi.id, comp_id],\n exact is_terminal.hom_ext (terminal_is_terminal) _ _ }\nend\n\n-- Theorem 2.13 thesis\nlemma forcing_bot : ¬ pforces ⊥ x :=\nbegin\n intro u,\n have i := (category_theory.yoneda_sections_small _ _).hom (pforces_to_forces _ u).lift,\n simp at i,\n have k := (external_iso_internal.bot' X).app c,\n exact pempty.elim ((presheaf.initial.pempty_obj_iso c).hom (k.inv i)),\nend\n\nlemma forcing_top : pforces ⊤ x :=\nbegin\n apply pforces_of_valid,\n rw validity.valid_iff_eq_sub_top,\n exact (external_iso_internal.top_sub X).symm\nend\n\nvariables (σ) (τ : X ⟶ Ω °C)\n\nlemma forcing_and : pforces (σ ⊓ τ) x ↔ pforces σ x ∧ pforces τ x :=\nbegin\n split; intro h,\n { split; cases h with u h,\n use u ≫ pullback.lift (canonical_incl (σ ⊓ τ)) (terminal.from _) \n (external_iso_internal.left_square_commutes_fst σ τ),\n rwa [assoc, pullback.lift_fst],\n use u ≫ pullback.lift (canonical_incl (σ ⊓ τ)) (terminal.from _) \n (external_iso_internal.left_square_commutes_snd σ τ),\n rwa [assoc, pullback.lift_fst] },\n { have comm : x ≫ limits.prod.lift σ τ = terminal.from _ ≫ truth_truth °C := \n begin\n apply limits.prod.hom_ext; rw assoc; rw assoc, \n repeat { rw limits.prod.lift_fst }, cases h.left with u hu,\n rw [←hu, assoc, canonical_incl_comm, ←assoc, terminal.comp_from u],\n repeat { rw limits.prod.lift_snd }, cases h.right with u hu,\n rw [←hu, assoc, canonical_incl_comm, ←assoc, terminal.comp_from u],\n end,\n let l := pullback_cone.is_limit.lift' (external_iso_internal.is_pullback_and_left σ τ) \n x (terminal.from _) comm,\n exact ⟨l.val, l.prop.left ⟩ }\nend\n\nend forcing\n\n", "meta": {"author": "cchanavat", "repo": "lean-topos", "sha": "c8e22c35ed4dc4ea0d74a59c91785b8a4c8e48a4", "save_path": "github-repos/lean/cchanavat-lean-topos", "path": "github-repos/lean/cchanavat-lean-topos/lean-topos-c8e22c35ed4dc4ea0d74a59c91785b8a4c8e48a4/forcing/forcing.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3998116264369279, "lm_q2_score": 0.024053550795599545, "lm_q1q2_score": 0.009616889265171916}} {"text": "/-\nCopyright (c) 2022 Mac Malone. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Mac Malone\n-/\nimport Lean.Data.NameMap\nimport Lake.Util.Compare\n\nopen Lean\n\nnamespace Lake\n\nexport Lean (Name NameMap)\n\n@[inline] def NameMap.empty : NameMap α := RBMap.empty\n\ninstance : ForIn m (NameMap α) (Name × α) where\n forIn self init f := self.forIn init f\n\n/-! # Name Helpers -/\n\nnamespace Name\nopen Lean.Name\n\n@[simp] protected theorem beq_false (m n : Name) : (m == n) = false ↔ ¬ (m = n) := by\n rw [← beq_iff_eq m n]; cases m == n <;> simp (config := { decide := true })\n\n@[simp] theorem isPrefixOf_self {n : Name} : n.isPrefixOf n := by\n cases n <;> simp [isPrefixOf]\n\n@[simp] theorem isPrefixOf_append {n m : Name} : ¬ n.hasMacroScopes → ¬ m.hasMacroScopes → n.isPrefixOf (n ++ m) := by\n intro h1 h2\n show n.isPrefixOf (n.append m)\n simp_all [Name.append]\n clear h2; induction m <;> simp [*, Name.appendCore, isPrefixOf]\n\n@[simp] theorem quickCmpAux_iff_eq : ∀ {n n'}, quickCmpAux n n' = .eq ↔ n = n'\n| .anonymous, n => by cases n <;> simp [quickCmpAux]\n| n, .anonymous => by cases n <;> simp [quickCmpAux]\n| .num .., .str .. => by simp [quickCmpAux]\n| .str .., .num .. => by simp [quickCmpAux]\n| .num p₁ n₁, .num p₂ n₂ => by\n simp only [quickCmpAux]; split <;>\n simp_all [quickCmpAux_iff_eq, show ∀ p, (p → False) ↔ ¬ p from fun _ => .rfl]\n| .str p₁ s₁, .str p₂ s₂ => by\n simp only [quickCmpAux]; split <;>\n simp_all [quickCmpAux_iff_eq, show ∀ p, (p → False) ↔ ¬ p from fun _ => .rfl]\n\ninstance : LawfulCmpEq Name quickCmpAux where\n eq_of_cmp := quickCmpAux_iff_eq.mp\n cmp_rfl := quickCmpAux_iff_eq.mpr rfl\n\ntheorem eq_of_quickCmp {n n' : Name} : n.quickCmp n' = .eq → n = n' := by\n unfold Name.quickCmp\n intro h_cmp; split at h_cmp\n next => exact eq_of_cmp h_cmp\n next => contradiction\n\ntheorem quickCmp_rfl {n : Name} : n.quickCmp n = .eq := by\n unfold Name.quickCmp\n split <;> exact cmp_rfl\n\ninstance : LawfulCmpEq Name Name.quickCmp where\n eq_of_cmp := eq_of_quickCmp\n cmp_rfl := quickCmp_rfl\n\nopen Syntax\n\ndef quoteFrom (ref : Syntax) : Name → Term\n| .anonymous => mkCIdentFrom ref ``anonymous\n| .str p s => mkApp (mkCIdentFrom ref ``mkStr) #[quoteFrom ref p, quote s]\n| .num p v => mkApp (mkCIdentFrom ref ``mkNum) #[quoteFrom ref p, quote v]\n", "meta": {"author": "leanprover", "repo": "lake", "sha": "6de8ee8817c3e6bb01f9f48c2f22f7979e4ac526", "save_path": "github-repos/lean/leanprover-lake", "path": "github-repos/lean/leanprover-lake/lake-6de8ee8817c3e6bb01f9f48c2f22f7979e4ac526/Lake/Util/Name.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.25091277568224823, "lm_q2_score": 0.03789242690123016, "lm_q1q2_score": 0.009507694011124352}} {"text": "\n\nexample (M : Type → Type) [Monad M] : ExceptT Unit (ReaderT Unit (StateT Unit M)) Unit := do\nlet ctx ← read;\npure ()\n", "meta": {"author": "leanprover", "repo": "lean4", "sha": "742d053a97bdd109a41a921facd1cd6a55e89bc7", "save_path": "github-repos/lean/leanprover-lean4", "path": "github-repos/lean/leanprover-lean4/lean4-742d053a97bdd109a41a921facd1cd6a55e89bc7/tests/lean/run/typeclass_loop.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.19682622248837708, "lm_q2_score": 0.04742586981164345, "lm_q1q2_score": 0.00933465480325134}} {"text": "import Lbar.ext_aux2\nimport Lbar.iota\n\nnoncomputable theory\n\nuniverses v u u'\n\nopen opposite category_theory category_theory.limits category_theory.preadditive\nopen_locale nnreal zero_object\n\nvariables (r r' : ℝ≥0)\nvariables [fact (0 < r)] [fact (0 < r')] [fact (r < r')] [fact (r < 1)] [fact (r' < 1)]\n\nopen bounded_homotopy_category\n\nvariables {r'}\nvariables (BD : breen_deligne.package)\nvariables (κ κ₂ : ℝ≥0 → ℕ → ℝ≥0)\nvariables [∀ (c : ℝ≥0), BD.data.suitable (κ c)] [∀ n, fact (monotone (function.swap κ n))]\nvariables [∀ (c : ℝ≥0), BD.data.suitable (κ₂ c)] [∀ n, fact (monotone (function.swap κ₂ n))]\nvariables (M : ProFiltPseuNormGrpWithTinv₁.{u} r')\n\nsection preps\n\nvariables (V : SemiNormedGroup.{u}) [complete_space V] [separated_space V]\nvariables (ι : ulift.{u+1} ℕ → ℝ≥0) (hι : monotone ι)\n\nset_option pp.universes true\n\nlemma cofan_point_iso_colimit_conj_eq_desc\n {e : (homotopy_category.colimit_cofan\n (λ (a : ulift ℕ), ((λ (k : ulift ℕ),\n (QprimeFP r' BD.data κ₂ M).obj (ι k)) a).val)).X.is_bounded_above} :\n (cofan_point_iso_colimit\n (λ (k : ulift ℕ), (QprimeFP r' BD.data κ₂ M).obj (ι k))).inv ≫\n of_hom (sigma_shift ι hι (QprimeFP_int r' BD.data κ₂ M)) ≫\n (cofan_point_iso_colimit (λ (k : ulift ℕ),\n (QprimeFP r' BD.data κ₂ M).obj (ι k))).hom =\n begin\n apply sigma.desc,\n intros k,\n refine _ ≫ sigma.ι _ (ulift.up $ ulift.down k + 1),\n refine (QprimeFP r' BD.data κ₂ M).map _,\n refine hom_of_le (hι _),\n exact_mod_cast k.down.le_succ,\n end :=\nbegin\n ext j,\n dsimp only [cofan_point_iso_colimit],\n rw [colimit.ι_desc, cofan.mk_ι_app,\n colimit.comp_cocone_point_unique_up_to_iso_inv_assoc],\n simp only [← category.assoc], rw [← iso.eq_comp_inv], simp only [category.assoc],\n rw [colimit.comp_cocone_point_unique_up_to_iso_inv],\n dsimp only [sigma_shift, bounded_homotopy_category.cofan, cofan.mk_ι_app,\n of_hom, homotopy_category.colimit_cofan],\n erw [← functor.map_comp, colimit.ι_desc],\n dsimp only [sigma_shift_cone, discrete.nat_trans_app],\n refine functor.map_comp _ _ _,\nend\n\ndef pi_Ext_iso_Ext_sigma (i : ℤ) :\n (∏ λ (k : ulift ℕ), ((QprimeFP r' BD.data κ₂ M).op ⋙\n (Ext i).flip.obj ((single (Condensed Ab) 0).obj V.to_Cond)).obj (op (ι k))) ≅\n ((Ext i).obj (op (of' (∐ λ (k : ulift ℕ), (QprimeFP_int r' BD.data κ₂ M).obj (ι k))))).obj\n ((single (Condensed Ab) 0).obj (Condensed.of_top_ab ↥V)) :=\n(Ext_coproduct_iso\n (λ k : ulift ℕ, (QprimeFP r' BD.data κ₂ M).obj (ι k)) i\n ((single (Condensed Ab) 0).obj V.to_Cond)).symm ≪≫\n ((Ext i).flip.obj ((single (Condensed Ab) 0).obj V.to_Cond)).map_iso\nbegin\n refine iso.op (cofan_point_iso_colimit\n (λ (k : ulift ℕ), (QprimeFP r' BD.data κ₂ M).obj (ι k)))\nend\n\n-- move me\n@[simp] lemma _root_.category_theory.op_nsmul\n {C : Type*} [category C] [preadditive C] {X Y : C} (n : ℕ) (f : X ⟶ Y) :\n (n • f).op = n • f.op := rfl\n\n-- move me\n@[simp] lemma _root_.category_theory.op_sub\n {C : Type*} [category C] [preadditive C] {X Y : C} (f g : X ⟶ Y) :\n (f - g).op = f.op - g.op := rfl\n\n@[simp] lemma _root_.homological_complex.of_hom_sub\n {C : Type*} [category C] [abelian C]\n (X Y : homological_complex C (complex_shape.up ℤ)) (f g : X ⟶ Y)\n [((homotopy_category.quotient C (complex_shape.up ℤ)).obj X).is_bounded_above]\n [((homotopy_category.quotient C (complex_shape.up ℤ)).obj Y).is_bounded_above] :\n of_hom (f - g) = of_hom f - of_hom g := rfl\n\n@[reassoc]\nlemma Ext_coproduct_iso_naturality_inv\n (A : Type u)\n [category.{v} A]\n [abelian A]\n [enough_projectives A]\n [has_coproducts.{v} A]\n [AB4 A]\n {α : Type v}\n (X₁ X₂ : α → bounded_homotopy_category A)\n [uniformly_bounded X₁]\n [uniformly_bounded X₂]\n (g : X₁ ⟶ X₂)\n (i : ℤ) (Y) :\n (Ext_coproduct_iso _ _ _).inv ≫\n ((Ext i).map (sigma.desc (λ b, g b ≫ sigma.ι X₂ b) : ∐ X₁ ⟶ ∐ X₂).op).app Y =\n pi.lift (λ b, pi.π _ b ≫ ((Ext i).map (g b).op).app Y) ≫ (Ext_coproduct_iso _ _ _).inv :=\nbegin\n rw [iso.inv_comp_eq, ← category.assoc, iso.eq_comp_inv],\n apply Ext_coproduct_iso_naturality,\nend\n\nend preps\n", "meta": {"author": "leanprover-community", "repo": "lean-liquid", "sha": "92f188bd17f34dbfefc92a83069577f708851aec", "save_path": "github-repos/lean/leanprover-community-lean-liquid", "path": "github-repos/lean/leanprover-community-lean-liquid/lean-liquid-92f188bd17f34dbfefc92a83069577f708851aec/src/Lbar/ext_aux3.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.480478678047907, "lm_q2_score": 0.01941935002683308, "lm_q1q2_score": 0.009330583629442345}} {"text": "import .geom3d_series\nimport tactic.linarith\n\ndef ts := time_std_space\n\ndef world_fr := geom3d_std_frame\ndef world := geom3d_std_space\n\ndef bl_fr := \n let origin := mk_position3d world 1.000000 2.000000 3.000000 in\n let basis0 := mk_displacement3d world 4.000000 3.000000 2.000000 in\n let basis1 := mk_displacement3d world 1.000000 2.000000 3.000000 in\n let basis2 := mk_displacement3d world 2.000000 1.000000 2.000000 in\n mk_geom3d_frame origin basis0 basis1 basis2\n\ndef fr1 := \n let origin := mk_position3d world 2.000000 4.000000 3.000000 in\n let basis0 := mk_displacement3d world 4.000000 3.000000 2.000000 in\n let basis1 := mk_displacement3d world 1.000000 2.000000 3.000000 in\n let basis2 := mk_displacement3d world 2.000000 1.000000 2.000000 in\n mk_geom3d_frame origin basis0 basis1 basis2\n\ndef fr2 := \n let origin := mk_position3d world 4.000000 4.000000 3.000000 in\n let basis0 := mk_displacement3d world 4.000000 3.000000 2.000000 in\n let basis1 := mk_displacement3d world 1.000000 2.000000 3.000000 in\n let basis2 := mk_displacement3d world 2.000000 1.000000 2.000000 in\n mk_geom3d_frame origin basis0 basis1 basis2\n\ndef ser : geom3d_series ts := \n ⟨\n [\n --(mk_time _ 0,world_fr),\n --(mk_time _ 1,fr1),\n --(mk_time _ 2,fr2)\n \n (mk_time _ 2),\n (mk_time _ 1),\n (mk_time _ 0)\n ]⟩\n/-(⟨mk_time _ 0,sorry⟩-/\n\n#eval ser\n\ndef v1 := mk_displacement3d_timefixed_at_time ser (mk_time ts (0.4:ℚ)) 1 1 1\n#check v1\n\ndef v2 := mk_displacement3d_timefixed_at_time ser (mk_time ts (0.5:ℚ)) 1 1 1\n#check v2\n\n#check v1 +ᵥ v2\ndef s1 : series_index ts ser := ⟨mk_time ts (0.5:ℚ)⟩\ndef s2 : series_index ts ser := ⟨mk_time ts (2.5:ℚ)⟩\n#eval s1.idx.coord\n#eval s2.idx.coord\n#eval (ser.find_index s1.idx).coord\n#eval (ser.find_index s2.idx).coord\n#check quot.lift\n#check has_equiv\n/-\nattribute [reducible, elab_as_eliminator]\nprotected def lift {α : Sort u} {β : Sort v} [s : setoid α] (f : α → β) : (∀ a b, a ≈ b → f a = f b) → quotient s → β :=\nquot.lift f\n-/\ndef lift_si : series_index ts ser → time ts :=\n λsi, (ser.find_index si.idx)\n\ndef lift_ := quotient.lift lift_si begin \n dsimp [has_equiv.equiv],\n unfold lift_si,\n unfold setoid.r,\n unfold index_rel,\n intros a b c,\n exact c,\nend\n\ndef chk := index_rel ts s1 s2\n#eval chk\n\n#eval ⟦s1⟧=⟦s2⟧\n#eval (lift_ ⟦s1⟧).coord\n#eval (lift_ ⟦s2⟧).coord\n#eval (lift_ ⟦s1⟧)\n#eval (lift_ ⟦s2⟧)\n\ndef pt111 : (lift_ ⟦s1⟧).coord = (lift_ ⟦s2⟧).coord := begin\n simp *,\nend\n\ndef pttt : (lift_ ⟦s1⟧).coord = (lift_ ⟦s2⟧).coord := begin\n unfold lift_,\nend\n\n\ndef lift_2 : ℕ → ℚ :=\n λsi, si\n\ninstance : setoid ℕ := ⟨ \n (λn1 n2, n1=n2), sorry\n⟩\n\ndef lift2_ := quotient.lift lift_2 begin \n --intros,\n -- unfold lift_2,\n dsimp [has_equiv.equiv],\n unfold setoid.r,\n unfold lift_2,\n simp *,\nend\n\ndef ss11 := ⟦1⟧\ndef ss22 := ⟦1⟧\n\nlemma a1 : ss11 = ss22 := rfl\n\nlemma a2 : lift2_ ss11 = lift2_ ss22 := rfl\n#eval lift2_ ss11\n\n", "meta": {"author": "kevinsullivan", "repo": "phys", "sha": "ebc2df3779d3605ff7a9b47eeda25c2a551e011f", "save_path": "github-repos/lean/kevinsullivan-phys", "path": "github-repos/lean/kevinsullivan-phys/phys-ebc2df3779d3605ff7a9b47eeda25c2a551e011f/old/geom3d_stamped_test.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3849121444839335, "lm_q2_score": 0.02405355110167842, "lm_q1q2_score": 0.00925850393700092}} {"text": "import category_theory.yoneda\nimport condensed.basic\nimport condensed.is_proetale_sheaf\nimport condensed.extr.equivalence\nimport algebra.category.Group.adjunctions\nimport for_mathlib.SheafOfTypes_sheafification\nimport for_mathlib.yoneda\nimport algebra.category.Module.abelian\nimport algebra.category.Module.colimits\n--import algebra.category.Group.filtered_colimits\n\nimport category_theory.limits.functor_category\nimport category_theory.sites.limits\n\n--import condensed.ab\n\nuniverse u\n\nopen category_theory\n\ndef Profinite.to_Condensed (T : Profinite.{u}) : CondensedSet :=\n{ val := yoneda'.{u+1}.obj T, --⋙ ulift_functor.{u+1},\n cond := begin\n rw is_sheaf_iff_is_sheaf_of_type,\n rw (functor.is_proetale_sheaf_of_types_tfae (yoneda'.obj T)).out 0 5,\n refine ⟨_,_,_⟩,\n { dsimp [functor.empty_condition],\n split,\n { rintros _ _ _,\n ext ⟨⟩ },\n { intros x,\n refine ⟨⟨Profinite.empty.elim _⟩, _⟩,\n ext } },\n { intros X Y,\n split,\n { intros x y h,\n dsimp at x y h,\n ext (t|t),\n { apply_fun (λ e, e.fst.down t) at h, exact h },\n { apply_fun (λ e, e.snd.down t) at h, exact h } },\n { rintros ⟨a,b⟩,\n refine ⟨⟨_⟩,_⟩,\n dsimp,\n refine Profinite.sum.desc _ _ a.down b.down,\n ext, refl, refl } },\n { intros X B π hh,\n split,\n { intros x y h,\n dsimp [yoneda, functor.map_to_equalizer] at h,\n ext t,\n obtain ⟨t,rfl⟩ := hh t,\n apply_fun (λ e, e.val.down t) at h,\n exact h },\n { rintros ⟨⟨t⟩,ht⟩,\n refine ⟨⟨Profinite.descend π t hh _⟩, _⟩,\n dsimp at ht,\n apply_fun (λ e, e.down) at ht,\n exact ht,\n dsimp [yoneda, ulift_functor, functor.map_to_equalizer],\n ext : 2,\n dsimp,\n apply Profinite.π_descend } }\n end } .\n\n@[simps]\ndef Profinite_to_Condensed : Profinite ⥤ CondensedSet :=\n{ obj := λ X, X.to_Condensed,\n map := λ X Y f, ⟨whisker_right (yoneda.map f) _⟩,\n map_id' := λ X, by { ext1, dsimp, erw [yoneda.map_id, whisker_right_id], refl },\n map_comp' := λ X Y Z f g, by { ext1, dsimp,\n erw [yoneda.map_comp, whisker_right_comp] } }\n\ndef Top.to_Condensed (T : Top.{u}) : CondensedSet :=\n{ val := Profinite.to_Top.op ⋙ yoneda'.{u+1}.obj T,\n cond := begin\n rw is_sheaf_iff_is_sheaf_of_type,\n rw (functor.is_proetale_sheaf_of_types_tfae\n (Profinite.to_Top.op ⋙ yoneda'.obj T)).out 0 5,\n refine ⟨_,_,_⟩,\n { dsimp [functor.empty_condition],\n split,\n { rintros _ _ _,\n ext ⟨⟩ },\n { intros x,\n dsimp,\n refine ⟨⟨⟨λ x, x.elim, by continuity⟩⟩, _⟩,\n ext } },\n { intros X Y,\n split,\n { intros x y h,\n dsimp at x y h,\n ext (t|t),\n { apply_fun (λ e, e.fst.down t) at h, exact h },\n { apply_fun (λ e, e.snd.down t) at h, exact h } },\n { rintros ⟨a,b⟩,\n dsimp [ulift_functor] at a b,\n refine ⟨⟨⟨_,_⟩⟩,_⟩,\n { dsimp [Profinite.sum],\n intros t,\n exact sum.rec_on t a.down b.down },\n { dsimp,\n simp only [continuous_sup_dom, continuous_coinduced_dom],\n exact ⟨a.down.continuous, b.down.continuous⟩ },\n { ext, refl, refl } } },\n { intros X B π hh,\n split,\n { intros x y h,\n dsimp [yoneda, functor.map_to_equalizer] at h,\n ext t,\n obtain ⟨t,rfl⟩ := hh t,\n apply_fun (λ e, e.val.down t) at h,\n exact h },\n { rintros ⟨⟨t⟩,ht⟩,\n refine ⟨⟨Profinite.descend_to_Top π t hh _⟩, _⟩,\n dsimp at ht,\n apply_fun (λ e, e.down) at ht,\n exact ht,\n dsimp [yoneda, ulift_functor, functor.map_to_equalizer],\n ext : 2,\n dsimp,\n apply Profinite.π_descend_to_Top,\n } }\n end }\n\n@[simps]\ndef Top_to_Condensed : Top ⥤ CondensedSet :=\n{ obj := λ X, X.to_Condensed,\n map := λ X Y f, ⟨whisker_left _ $ whisker_right (yoneda.map f) _⟩,\n map_id' := begin\n intros X,\n ext1,\n dsimp,\n erw [yoneda.map_id, whisker_right_id, whisker_left_id],\n refl,\n end,\n map_comp' := begin\n intros X Y Z f g,\n ext1,\n dsimp,\n erw [yoneda.map_comp, whisker_right_comp, whisker_left_comp],\n end }\n\nopen opposite\n\n@[simps]\ndef Condensed.evaluation (C : Type*) [category C] (S : Profinite) :\n Condensed C ⥤ C :=\nSheaf_to_presheaf _ _ ⋙ (evaluation _ _).obj (op S)\n\nnoncomputable instance {C : Type*} [category C]\n [limits.has_limits C] (S : Profinite.{u}) :\n limits.preserves_limits (Condensed.evaluation C S) :=\nbegin\n apply_with limits.comp_preserves_limits { instances := ff },\n swap, apply_instance,\n have e : creates_limits (Sheaf_to_presheaf proetale_topology.{u} C) :=\n Sheaf.category_theory.Sheaf_to_presheaf.category_theory.creates_limits.{(u+2) u (u+1)},\n apply_with category_theory.preserves_limits_of_creates_limits_and_has_limits { instances := ff },\n exact e,\n apply_instance\nend\n\n@[simps]\ndef CondensedSet.evaluation (S : Profinite) : CondensedSet.{u} ⥤ Type (u+1) :=\nSheaf_to_presheaf _ _ ⋙ (evaluation _ _).obj (op S)\n\nnoncomputable instance (S : Profinite.{u}) :\n limits.preserves_limits (CondensedSet.evaluation S) :=\nbegin\n apply_with limits.comp_preserves_limits { instances := ff },\n swap, apply_instance,\n have e : creates_limits (Sheaf_to_presheaf proetale_topology.{u} (Type (u+1))) :=\n Sheaf.category_theory.Sheaf_to_presheaf.category_theory.creates_limits.{(u+2) u (u+1)},\n apply_with category_theory.preserves_limits_of_creates_limits_and_has_limits { instances := ff },\n exact e,\n apply_instance\nend\n\nuniverse w\nopen category_theory.limits\n\nvariables (C : Type w) [category.{u+1} C]\n\nnoncomputable\ninstance preserves_colimits_Condensed_evaluation\n (S : ExtrDisc.{u}) (C : Type w) [category.{u+1} C]\n [has_limits C] [has_colimits C] [has_zero_morphisms C] [has_finite_biproducts C] :\n limits.preserves_colimits (Condensed.evaluation C S.val) :=\nbegin\n change preserves_colimits\n (((Sheaf_to_presheaf _ _ : Condensed C ⥤ _) ⋙\n ((whiskering_left _ _ _).obj ExtrDisc_to_Profinite.op)) ⋙\n (evaluation _ _).obj (op S)),\n apply_with limits.comp_preserves_colimits { instances := ff },\n apply category_theory.preserves_colimits_of_creates_colimits_and_has_colimits,\n apply_instance,\nend\n\nnoncomputable\ninstance preserves_colimits_Condensed_evaluation'\n (S : Profinite.{u}) [projective S] (C : Type w) [category.{u+1} C]\n [has_limits C] [has_colimits C] [has_zero_morphisms C] [has_finite_biproducts C] :\n limits.preserves_colimits (Condensed.evaluation C S) :=\npreserves_colimits_Condensed_evaluation ⟨S⟩ _\n\n-- This can be generalized to categories other than `Ab`, but lean is having a really hard time\n-- figuring out all the necessary typeclasses and universe parameters, so I gave up and just used\n-- `Ab`.\nnoncomputable\ninstance preserves_finite_biproducts_Condensed_evaluation\n (S : Profinite.{u}) :\n limits.preserves_finite_biproducts\n (Condensed.evaluation Ab.{u+1} S : Condensed.{u} Ab.{u+1} ⥤ Ab.{u+1}) :=\nbegin\n constructor, introsI J _,\n apply preserves_biproducts_of_shape_of_preserves_products_of_shape,\nend\n\n-- TODO: Move this\ninstance : has_finite_biproducts Ab :=\nhas_finite_biproducts.of_has_finite_products\n\n-- It looks like this was not needed for `Module A`, even though it was needed for `Ab`.\n-- We're missing an instance for `Ab` in mathlib.\n--instance (A : Type u) [comm_ring A] : has_finite_biproducts (Module.{u} A) :=\n--has_finite_biproducts.of_has_finite_products\n\n-- sanity check\nnoncomputable example (S : ExtrDisc.{u}) :\n limits.preserves_colimits (Condensed.evaluation Ab.{u+1} S.val) :=\npreserves_colimits_Condensed_evaluation _ _\n\nnoncomputable example (S : Profinite.{u}) [projective S] :\n limits.preserves_colimits (Condensed.evaluation Ab.{u+1} S) :=\npreserves_colimits_Condensed_evaluation' _ _\n\nnoncomputable example (A : Type (u+1)) [comm_ring A] (S : ExtrDisc.{u}) :\n limits.preserves_colimits (Condensed.evaluation (Module.{u+1} A) S.val) :=\npreserves_colimits_Condensed_evaluation _ _\n\nnoncomputable example (A : Type (u+1)) [comm_ring A] (S : Profinite.{u}) [projective S] :\n limits.preserves_colimits (Condensed.evaluation (Module.{u+1} A) S) :=\npreserves_colimits_Condensed_evaluation' _ _\n", "meta": {"author": "leanprover-community", "repo": "lean-liquid", "sha": "92f188bd17f34dbfefc92a83069577f708851aec", "save_path": "github-repos/lean/leanprover-community-lean-liquid", "path": "github-repos/lean/leanprover-community-lean-liquid/lean-liquid-92f188bd17f34dbfefc92a83069577f708851aec/src/condensed/top_comparison.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44552952031526044, "lm_q2_score": 0.020645931002853023, "lm_q1q2_score": 0.009198371736163072}} {"text": "import category_theory.preadditive\nimport category_theory.abelian.projective\nimport data.matrix.notation\nimport tactic.interval_cases\nimport category_theory.abelian.pseudoelements\n\nimport for_mathlib.short_exact_sequence\nimport for_mathlib.abelian_category\nimport for_mathlib.fin_functor\nimport for_mathlib.exact_seq\n\nnoncomputable theory\n\nopen category_theory\nopen category_theory.limits\nopen_locale pseudoelement\n\nuniverse variables v u\n\nnamespace eq\n\nvariables {X : Type*} {x y : X} (h : x = y)\n\n@[nolint unused_arguments]\nabbreviation lhs (h : x = y) := x\n\n@[nolint unused_arguments]\nabbreviation rhs (h : x = y) := y\n\n@[simp] lemma lhs_def : h.lhs = x := rfl\n@[simp] lemma rhs_def : h.rhs = y := rfl\n\nend eq\n\nnamespace category_theory\n\n/-- The base diagram for the snake lemma. The object are indexed by `fin 4 × fin 3`:\n\n(0,0) --> (0,1) --> (0,2) | the kernels\n | | |\n v v v\n(1,0) --> (1,1) --> (1,2) | the first exact row\n | | |\n v v v\n(2,0) --> (2,1) --> (2,2) | the second exact row\n | | |\n v v v\n(3,0) --> (3,1) --> (3,2) | the cokernels\n\n-/\n@[derive [preorder, decidable_eq]]\ndef snake_diagram := fin 4 × fin 3\n\nnamespace snake_diagram\n\n@[simps]\ndef o (i : fin 4) (j : fin 3) : snake_diagram := (i,j)\n\n@[simp] lemma o_le_o (i j : fin 4) (k l : fin 3) :\n o i k ≤ o j l ↔ i ≤ j ∧ k ≤ l := iff.rfl\n\nmeta def hom_tac : tactic unit :=\n`[simp only [category_theory.snake_diagram.o_le_o,\n category_theory.snake_diagram.o_fst, category_theory.snake_diagram.o_snd,\n prod.le_def, and_true, true_and, le_refl],\n dec_trivial! ]\n\ndef hom (i j : snake_diagram) (hij : i ≤ j . hom_tac) : i ⟶ j := hom_of_le hij\n\nlemma hom_ext {i j : snake_diagram} (f g : i ⟶ j) : f = g := by ext\n\nsection\n\nmeta def map_tac : tactic unit :=\n`[dsimp only [mk_functor, mk_functor.map', eq_to_hom_refl, hom_of_le_refl, true_and, le_refl],\n simp only [category.id_comp, category.comp_id, functor.map_id],\n refl]\n\nparameters {C : Type u} [category.{v} C]\n\nparameters (F : fin 4 → fin 3 → C)\nparameters (f0 : F 0 0 ⟶ F 0 1) (g0 : F 0 1 ⟶ F 0 2)\nparameters (a0 : F 0 0 ⟶ F 1 0) (b0 : F 0 1 ⟶ F 1 1) (c0 : F 0 2 ⟶ F 1 2)\nparameters (f1 : F 1 0 ⟶ F 1 1) (g1 : F 1 1 ⟶ F 1 2)\nparameters (a1 : F 1 0 ⟶ F 2 0) (b1 : F 1 1 ⟶ F 2 1) (c1 : F 1 2 ⟶ F 2 2)\nparameters (f2 : F 2 0 ⟶ F 2 1) (g2 : F 2 1 ⟶ F 2 2)\nparameters (a2 : F 2 0 ⟶ F 3 0) (b2 : F 2 1 ⟶ F 3 1) (c2 : F 2 2 ⟶ F 3 2)\nparameters (f3 : F 3 0 ⟶ F 3 1) (g3 : F 3 1 ⟶ F 3 2)\nparameters (sq00 : a0 ≫ f1 = f0 ≫ b0) (sq01 : b0 ≫ g1 = g0 ≫ c0)\nparameters (sq10 : a1 ≫ f2 = f1 ≫ b1) (sq11 : b1 ≫ g2 = g1 ≫ c1)\nparameters (sq20 : a2 ≫ f3 = f2 ≫ b2) (sq21 : b2 ≫ g3 = g2 ≫ c2)\n\nnamespace mk_functor\n\ndef col : Π (j : fin 3), fin 4 ⥤ C\n| ⟨0,h⟩ := fin4_functor_mk (flip F 0) a0 a1 a2\n| ⟨1,h⟩ := fin4_functor_mk (flip F 1) b0 b1 b2\n| ⟨2,h⟩ := fin4_functor_mk (flip F 2) c0 c1 c2\n| ⟨j+3,h⟩ := by { exfalso, revert h, dec_trivial }\n\ndef row : Π (i : fin 4), fin 3 ⥤ C\n| ⟨0,h⟩ := fin3_functor_mk (F 0) f0 g0\n| ⟨1,h⟩ := fin3_functor_mk (F 1) f1 g1\n| ⟨2,h⟩ := fin3_functor_mk (F 2) f2 g2\n| ⟨3,h⟩ := fin3_functor_mk (F 3) f3 g3\n| ⟨j+4,h⟩ := by { exfalso, revert h, dec_trivial }\n\nlemma col_obj (i : fin 4) (j : fin 3) : (col j).obj i = F i j :=\nby fin_cases i; fin_cases j; refl.\n\nlemma row_obj (i : fin 4) (j : fin 3) : (row i).obj j = F i j :=\nby fin_cases i; fin_cases j; refl.\n\nlemma row_eq_col_obj (i : fin 4) (j : fin 3) : (row i).obj j = (col j).obj i :=\n(row_obj i j).trans (col_obj i j).symm\n\ndef map' (x y : snake_diagram) (h : x ≤ y) : F x.1 x.2 ⟶ F y.1 y.2 :=\neq_to_hom (by rw [row_obj]) ≫\n(row x.1).map h.2.hom ≫ eq_to_hom (by rw [row_obj, col_obj]) ≫\n(col y.2).map h.1.hom ≫ eq_to_hom (by rw [col_obj])\n\nlemma map'_id (x : snake_diagram) : map' x x le_rfl = 𝟙 _ :=\nby simp only [map', hom_of_le_refl, functor.map_id,\n eq_to_hom_trans, category.id_comp, eq_to_hom_refl]\n\ndef square_commutes (i j : fin 4) (k l : fin 3) (hij : i ≤ j) (hkl : k ≤ l) : Prop :=\n(col k).map hij.hom ≫ eq_to_hom (by rw [row_obj, col_obj]) ≫\n(row j).map hkl.hom =\neq_to_hom (by rw [col_obj]; refl) ≫\nmap' (o i k) (o j l) ⟨hij, hkl⟩ ≫ eq_to_hom (by rw [row_obj]; refl)\n\ninclude sq00 sq01 sq10 sq11 sq20 sq21\n\nlemma square_commutes_row (i : fin 4) (k l : fin 3) (hkl : k ≤ l) :\n square_commutes i i k l le_rfl hkl :=\nbegin\n dsimp [square_commutes, map'],\n simp only [map', hom_of_le_refl, functor.map_id, eq_to_hom_trans, eq_to_hom_trans_assoc,\n category.id_comp, category.comp_id, category.assoc],\n erw [hom_of_le_refl],\n simp only [map', hom_of_le_refl, functor.map_id, eq_to_hom_trans, eq_to_hom_trans_assoc,\n category.id_comp, category.comp_id, category.assoc],\n rw [← category.assoc, eq_comm],\n convert category.comp_id _,\nend\n\nlemma square_commutes_col (i j : fin 4) (k : fin 3) (hij : i ≤ j) :\n square_commutes i j k k hij le_rfl :=\nbegin\n dsimp [square_commutes, map'],\n simp only [map', hom_of_le_refl, functor.map_id, eq_to_hom_trans, eq_to_hom_trans_assoc,\n category.id_comp, category.comp_id, category.assoc],\n erw [hom_of_le_refl],\n simp only [map', hom_of_le_refl, functor.map_id, eq_to_hom_trans, eq_to_hom_trans_assoc,\n category.id_comp, category.comp_id, category.assoc],\n rw [eq_comm],\n convert category.id_comp _,\nend\n\nlemma square_commutes_one (i : fin 4) (j : fin 3) (hi : i < 3) (hj : j < 2) :\n square_commutes i (i+1) j (j+1) (by dec_trivial!) (by dec_trivial!) :=\nbegin\n fin_cases i, swap 4, { exfalso, revert hi, dec_trivial },\n all_goals { fin_cases j, swap 3, { exfalso, revert hj, dec_trivial },\n all_goals {\n simp only [square_commutes, map', eq_to_hom_refl, category.comp_id, category.id_comp],\n assumption }, },\nend\n.\n\nlemma square_commutes_comp_row (i j k : fin 4) (l m : fin 3)\n (hij : i ≤ j) (hjk : j ≤ k) (hlm : l ≤ m)\n (h1 : square_commutes i j l m hij hlm) (h2 : square_commutes j k l m hjk hlm) :\n square_commutes i k l m (hij.trans hjk) hlm :=\nbegin\n dsimp [square_commutes, map'] at h1 h2 ⊢,\n simp only [map', hom_of_le_refl, functor.map_id, eq_to_hom_trans, eq_to_hom_trans_assoc,\n category.id_comp, category.comp_id, category.assoc] at h1 h2 ⊢,\n let φ : _ := _, let ψ : _ := _,\n calc _ = φ ≫ h2.lhs : _\n ... = φ ≫ h2.rhs : by { congr' 1, }\n ... = h1.lhs ≫ ψ : _\n ... = h1.rhs ≫ ψ : by { congr' 1, }\n ... = _ : _,\n swap 5, { exact functor.map _ hij.hom },\n swap 4, { refine (eq_to_hom _ ≫ _ ≫ eq_to_hom _),\n swap 2, { apply row_eq_col_obj; assumption },\n swap 3, { symmetry, apply row_eq_col_obj; assumption },\n exact functor.map _ hjk.hom },\n all_goals { dsimp [φ, ψ, eq.lhs_def, eq.rhs_def] },\n { simp only [← functor.map_comp_assoc], refl },\n { simp only [category.assoc], refl },\n { simp only [eq_to_hom_trans, eq_to_hom_trans_assoc, category.assoc],\n dsimp,\n simp only [hom_of_le_refl, eq_to_hom_trans, eq_to_hom_trans_assoc,\n category.id_comp, category.comp_id, category.assoc, ← functor.map_comp_assoc],\n refl, },\nend\n\nlemma square_commutes_comp_col (i j : fin 4) (l m n : fin 3)\n (hij : i ≤ j) (hlm : l ≤ m) (hmn : m ≤ n)\n (h1 : square_commutes i j l m hij hlm) (h2 : square_commutes i j m n hij hmn) :\n square_commutes i j l n hij (hlm.trans hmn) :=\nbegin\n dsimp [square_commutes, map'] at h1 h2 ⊢,\n simp only [map', hom_of_le_refl, functor.map_id, eq_to_hom_trans, eq_to_hom_trans_assoc,\n category.id_comp, category.comp_id, category.assoc] at h1 h2 ⊢,\n let φ : _ := _, let ψ : _ := _,\n calc _ = h1.lhs ≫ φ : _\n ... = h1.rhs ≫ φ : by { congr' 1, }\n ... = ψ ≫ h2.lhs : _\n ... = ψ ≫ h2.rhs : by { congr' 1, }\n ... = _ : _,\n swap 5, { exact functor.map _ hmn.hom },\n swap 4, { refine (eq_to_hom _ ≫ _ ≫ eq_to_hom _),\n swap 2, { symmetry, apply row_eq_col_obj; assumption },\n swap 3, { apply row_eq_col_obj; assumption },\n exact functor.map _ hlm.hom },\n all_goals { dsimp [φ, ψ, eq.lhs_def, eq.rhs_def] },\n { simp only [category.assoc, ← functor.map_comp], refl },\n { simp only [category.assoc], refl },\n { simp only [eq_to_hom_trans, eq_to_hom_trans_assoc, category.assoc],\n dsimp,\n simp only [hom_of_le_refl, eq_to_hom_trans, eq_to_hom_trans_assoc,\n category.id_comp, category.comp_id, category.assoc, ← functor.map_comp_assoc],\n refl, },\nend\n\nlemma col_comp_row (i j : fin 4) (k l : fin 3) (hij : i ≤ j) (hkl : k ≤ l) :\n (col k).map hij.hom ≫ eq_to_hom (by rw [row_obj, col_obj]) ≫\n (row j).map hkl.hom =\n eq_to_hom (by rw [col_obj]; refl) ≫\n map' (o i k) (o j l) ⟨hij, hkl⟩ ≫ eq_to_hom (by rw [row_obj]; refl) :=\nbegin\n cases i with i hi, cases j with j hj, cases k with k hk, cases l with l hl,\n have hkl' := hkl,\n rw [← fin.coe_fin_le, fin.coe_mk, fin.coe_mk] at hij hkl,\n obtain ⟨j, rfl⟩ := nat.exists_eq_add_of_le hij,\n obtain ⟨l, rfl⟩ := nat.exists_eq_add_of_le hkl,\n clear hij,\n induction j with j IHj,\n { apply square_commutes_row; assumption },\n refine square_commutes_comp_row F f0 g0 a0 b0 c0 f1 g1 a1 b1 c1 f2 g2 a2 b2 c2 f3 g3\n sq00 sq01 sq10 sq11 sq20 sq21 ⟨i, hi⟩ ⟨i+j, _⟩ _ _ _ _ _ hkl' _ _,\n { refine lt_trans _ hj, exact lt_add_one (i+j) },\n { simp only [← fin.coe_fin_le, fin.coe_mk], exact le_self_add },\n { simp only [← fin.coe_fin_le, fin.coe_mk], exact (lt_add_one (i+j)).le },\n { refine IHj _ _, },\n clear IHj hkl,\n induction l with l IHl,\n { apply square_commutes_col; assumption },\n refine square_commutes_comp_col F f0 g0 a0 b0 c0 f1 g1 a1 b1 c1 f2 g2 a2 b2 c2 f3 g3\n sq00 sq01 sq10 sq11 sq20 sq21 _ _ ⟨k, hk⟩ ⟨k+l, _⟩ _ _ _ _ _ _,\n { refine lt_trans _ hl, exact lt_add_one (k+l) },\n { simp only [← fin.coe_fin_le, fin.coe_mk], exact le_self_add },\n { simp only [← fin.coe_fin_le, fin.coe_mk], exact (lt_add_one (k+l)).le },\n { refine IHl _ _ _, simp only [← fin.coe_fin_le, fin.coe_mk], exact le_self_add },\n clear IHl,\n convert square_commutes_one F f0 g0 a0 b0 c0 f1 g1 a1 b1 c1 f2 g2 a2 b2 c2 f3 g3\n sq00 sq01 sq10 sq11 sq20 sq21 _ _ _ _ using 2,\n { rw [nat.one_mod, add_assoc, nat.mod_eq_of_lt hj] },\n { rw [nat.one_mod, add_assoc, nat.mod_eq_of_lt hl] },\n { rw [← fin.coe_fin_lt, fin.coe_mk], refine nat.lt_of_succ_lt_succ hj, },\n { rw [← fin.coe_fin_lt, fin.coe_mk], refine nat.lt_of_succ_lt_succ hl, },\nend\n\nlemma map'_comp (x y z : snake_diagram) (hxy : x ≤ y) (hyz : y ≤ z) :\n map' x y hxy ≫ map' y z hyz = map' x z (hxy.trans hyz) :=\nbegin\n delta map',\n slice_lhs 4 7 { rw [eq_to_hom_trans_assoc] },\n rw [col_comp_row],\n { dsimp [map'],\n simp only [map', eq_to_hom_trans_assoc, category.assoc, eq_to_hom_refl,\n category.comp_id, category.id_comp, ← functor.map_comp_assoc],\n refl },\n all_goals { assumption },\nend\n\nend mk_functor\n\ninclude sq00 sq01 sq10 sq11 sq20 sq21\n\ndef mk_functor : snake_diagram ⥤ C :=\n{ obj := function.uncurry F,\n map := λ x y h, mk_functor.map' F f0 g0 a0 b0 c0 f1 g1 a1 b1 c1 f2 g2 a2 b2 c2 f3 g3 x y h.le,\n map_id' := λ x, mk_functor.map'_id F f0 g0 a0 b0 c0 f1 g1 a1 b1 c1 f2 g2 a2 b2 c2 f3 g3 x,\n map_comp' := λ x y z hxy hyz, by { rw mk_functor.map'_comp; assumption } }\n\n@[simp] lemma mk_functor_map_f0 : mk_functor.map (hom (0,0) (0,1)) = f0 := by map_tac\n@[simp] lemma mk_functor_map_g0 : mk_functor.map (hom (0,1) (0,2)) = g0 := by map_tac\n@[simp] lemma mk_functor_map_a0 : mk_functor.map (hom (0,0) (1,0)) = a0 := by map_tac\n@[simp] lemma mk_functor_map_b0 : mk_functor.map (hom (0,1) (1,1)) = b0 := by map_tac\n@[simp] lemma mk_functor_map_c0 : mk_functor.map (hom (0,2) (1,2)) = c0 := by map_tac\n@[simp] lemma mk_functor_map_f1 : mk_functor.map (hom (1,0) (1,1)) = f1 := by map_tac\n@[simp] lemma mk_functor_map_g1 : mk_functor.map (hom (1,1) (1,2)) = g1 := by map_tac\n@[simp] lemma mk_functor_map_a1 : mk_functor.map (hom (1,0) (2,0)) = a1 := by map_tac\n@[simp] lemma mk_functor_map_b1 : mk_functor.map (hom (1,1) (2,1)) = b1 := by map_tac\n@[simp] lemma mk_functor_map_c1 : mk_functor.map (hom (1,2) (2,2)) = c1 := by map_tac\n@[simp] lemma mk_functor_map_f2 : mk_functor.map (hom (2,0) (2,1)) = f2 := by map_tac\n@[simp] lemma mk_functor_map_g2 : mk_functor.map (hom (2,1) (2,2)) = g2 := by map_tac\n@[simp] lemma mk_functor_map_a2 : mk_functor.map (hom (2,0) (3,0)) = a2 := by map_tac\n@[simp] lemma mk_functor_map_b2 : mk_functor.map (hom (2,1) (3,1)) = b2 := by map_tac\n@[simp] lemma mk_functor_map_c2 : mk_functor.map (hom (2,2) (3,2)) = c2 := by map_tac\n@[simp] lemma mk_functor_map_f3 : mk_functor.map (hom (3,0) (3,1)) = f3 := by map_tac\n@[simp] lemma mk_functor_map_g3 : mk_functor.map (hom (3,1) (3,2)) = g3 := by map_tac\n\nend\n\nsection\n\nvariables {𝒜 ℬ : Type*} [category 𝒜] [category ℬ]\nvariables (A : fin 3 → 𝒜) (F : fin 4 → 𝒜 ⥤ ℬ)\nvariables (f : A 0 ⟶ A 1) (g : A 1 ⟶ A 2) (α : F 0 ⟶ F 1) (β : F 1 ⟶ F 2) (γ : F 2 ⟶ F 3)\n\ndef mk_functor' : snake_diagram ⥤ ℬ :=\nmk_functor (λ i, (F i).obj ∘ A)\n /- FA₀₀ -/ ((F 0).map f) /- FA₀₁ -/ ((F 0).map g) /- FA₀₂ -/\n (α.app _) (α.app _) (α.app _)\n /- FA₁₀ -/ ((F 1).map f) /- FA₁₁ -/ ((F 1).map g) /- FA₁₂ -/\n (β.app _) (β.app _) (β.app _)\n /- FA₂₀ -/ ((F 2).map f) /- FA₂₁ -/ ((F 2).map g) /- FA₂₂ -/\n (γ.app _) (γ.app _) (γ.app _)\n /- FA₃₀ -/ ((F 3).map f) /- FA₃₁ -/ ((F 3).map g) /- FA₃₂ -/\n(α.naturality _).symm (α.naturality _).symm\n(β.naturality _).symm (β.naturality _).symm\n(γ.naturality _).symm (γ.naturality _).symm\n\nend\n\nsection\n\nvariables {𝒜 ℬ 𝒞 : Type*} [category 𝒜] [category ℬ] [category 𝒞]\nvariables (A : fin 3 → 𝒜 ⥤ ℬ) (F : fin 4 → ℬ ⥤ 𝒞)\nvariables (f : A 0 ⟶ A 1) (g : A 1 ⟶ A 2) (α : F 0 ⟶ F 1) (β : F 1 ⟶ F 2) (γ : F 2 ⟶ F 3)\n\ndef mk_functor'' : 𝒜 → snake_diagram ⥤ 𝒞 :=\nλ x, mk_functor' ![(A 0).obj x, (A 1).obj x, (A 2).obj x] F (f.app x) (g.app x) α β γ\n\nend\n\nsection\n\nvariables {𝒜 : Type*} [category 𝒜] [abelian 𝒜]\n\n-- move (ang generalize) this\nlemma exact_kernel_ι_self {A B : 𝒜} (f : A ⟶ B) : exact (kernel.ι f) f :=\nby { rw abelian.exact_iff, tidy } -- why do we not have abelian.exact_kernel?\n\n-- move this\nlemma exact_self_cokernel_π {A B : 𝒜} (f : A ⟶ B) : exact f (cokernel.π f) :=\nabelian.exact_cokernel _\n\nlocal notation `kernel_map` := kernel.map _ _ _ _\nlocal notation `cokernel_map` := cokernel.map _ _ _ _\n\ndef mk_of_short_exact_sequence_hom (A B : short_exact_sequence 𝒜) (f : A ⟶ B) :\n snake_diagram ⥤ 𝒜 :=\nmk_functor\n/- == Passing in the matrix of objects first, to make Lean happy == -/\n![![kernel f.1, kernel f.2, kernel f.3],\n ![A.1, A.2, A.3],\n ![B.1, B.2, B.3],\n ![cokernel f.1, cokernel f.2, cokernel f.3]]\n/- == All the morphisms in the diagram == -/\n /- ker f.1 -/ (kernel_map f.sq1) /- ker f.2 -/ (kernel_map f.sq2) /- ker f.3 -/\n (kernel.ι _) (kernel.ι _) (kernel.ι _)\n /- A.1 -/ A.f /- A.2 -/ A.g /- A.3 -/\n f.1 f.2 f.3\n /- B.1 -/ B.f /- B.2 -/ B.g /- B.3 -/\n (cokernel.π _) (cokernel.π _) (cokernel.π _)\n /- coker f.1 -/ (cokernel_map f.sq1) /- coker f.2 -/ (cokernel_map f.sq2) /- coker f.3 -/\n/- == Prove that the squares commute == -/\n(by { delta kernel.map, rw [kernel.lift_ι] }) (by { delta kernel.map, rw [kernel.lift_ι] })\nf.sq1 f.sq2\n(by { delta cokernel.map, rw [cokernel.π_desc] }) (by { delta cokernel.map, rw [cokernel.π_desc] })\n.\n\nend\n\nend snake_diagram\n\nopen snake_diagram (o hom)\n\nexample (i : fin 4) : o i 0 ⟶ o i 1 := hom (i,0) (i,1)\n\nlocal notation x `⟶[`D`]` y := D.map (hom x y)\n\nsection definitions\n\nvariables (𝒜 : Type u) [category.{v} 𝒜] [has_images 𝒜] [has_zero_morphisms 𝒜] [has_kernels 𝒜]\n\nvariables {𝒜}\n\nstructure is_snake_input (D : snake_diagram ⥤ 𝒜) : Prop :=\n(row_exact₁ : exact ((1,0) ⟶[D] (1,1)) ((1,1) ⟶[D] (1,2)))\n(row_exact₂ : exact ((2,0) ⟶[D] (2,1)) ((2,1) ⟶[D] (2,2)))\n(col_exact₁ : ∀ j, exact ((0,j) ⟶[D] (1,j)) ((1,j) ⟶[D] (2,j)))\n(col_exact₂ : ∀ j, exact ((1,j) ⟶[D] (2,j)) ((2,j) ⟶[D] (3,j)))\n(col_mono : ∀ j, mono ((0,j) ⟶[D] (1,j)))\n(col_epi : ∀ j, epi ((2,j) ⟶[D] (3,j)))\n(row_mono : mono ((2,0) ⟶[D] (2,1)))\n(row_epi : epi ((1,1) ⟶[D] (1,2)))\n\nnamespace is_snake_input\n\nvariables {D : snake_diagram ⥤ 𝒜}\n\n@[nolint unused_arguments]\nlemma map_eq (hD : is_snake_input D) {x y : snake_diagram} (f g : x ⟶ y) : D.map f = D.map g :=\ncongr_arg _ (snake_diagram.hom_ext _ _)\n\n@[nolint unused_arguments]\nlemma map_eq_id (hD : is_snake_input D) {x : snake_diagram} (f : x ⟶ x) : D.map f = 𝟙 _ :=\nby rw [snake_diagram.hom_ext f (𝟙 x), D.map_id]\n\nlemma hom_eq_zero₁ (hD : is_snake_input D) {x y : snake_diagram} (f : x ⟶ y)\n (h : x.1 < 2 ∧ x.1 + 1 < y.1 . snake_diagram.hom_tac) : D.map f = 0 :=\nbegin\n cases x with i j, cases y with k l, cases h with h₀ h₁, rcases f with ⟨⟨⟨hik, hjl⟩⟩⟩,\n dsimp at h₀ h₁ hik hjl,\n let f₁ := hom (i,j) (i+1,j),\n let f₂ := hom (i+1,j) (i+2,j),\n let f₃ := hom (i+2,j) (k,l),\n calc D.map _\n = D.map ((f₁ ≫ f₂) ≫ f₃) : hD.map_eq _ _\n ... = ((D.map f₁) ≫ D.map f₂) ≫ D.map f₃ : by simp only [D.map_comp]\n ... = 0 ≫ D.map f₃ : _\n ... = 0 : zero_comp,\n congr' 1,\n obtain (rfl|rfl) : i = 0 ∨ i = 1, { dec_trivial! },\n { exact (hD.col_exact₁ j).w },\n { exact (hD.col_exact₂ j).w },\nend\n.\n\nopen snake_diagram\n\nmeta def aux_simp : tactic unit :=\n`[dsimp only [snake_diagram.mk_of_short_exact_sequence_hom],\n simp only [mk_functor_map_f0, mk_functor_map_g0, mk_functor_map_a0, mk_functor_map_b0,\n mk_functor_map_c0, mk_functor_map_f1, mk_functor_map_g1, mk_functor_map_a1,\n mk_functor_map_b1, mk_functor_map_c1, mk_functor_map_f2, mk_functor_map_g2,\n mk_functor_map_a2, mk_functor_map_b2, mk_functor_map_c2, mk_functor_map_f3, mk_functor_map_g3]]\n\nlemma mk_of_short_exact_sequence_hom {𝒜 : Type*} [category 𝒜] [abelian 𝒜]\n (A B : short_exact_sequence 𝒜) (f : A ⟶ B) :\n is_snake_input (snake_diagram.mk_of_short_exact_sequence_hom A B f) :=\n{ row_exact₁ := by { aux_simp, exact A.exact' },\n row_exact₂ := by { aux_simp, exact B.exact' },\n col_exact₁ := λ j, by { fin_cases j; aux_simp, all_goals { apply exact_kernel_ι_self, } },\n col_exact₂ := λ j, by { fin_cases j; aux_simp, all_goals { apply exact_self_cokernel_π } },\n col_mono := λ j, by { fin_cases j; aux_simp, all_goals { apply_instance } },\n col_epi := λ j, by { fin_cases j; aux_simp, all_goals { apply_instance } },\n row_mono := by { aux_simp, exact B.mono' },\n row_epi := by { aux_simp, exact A.epi' }, }\n\nend is_snake_input\n\nend definitions\n\nsection\n\nopen abelian.pseudoelement\n\nvariables {𝒜 : Type u} [category.{v} 𝒜] [abelian 𝒜]\nvariables {D : snake_diagram ⥤ 𝒜}\n\nnamespace is_snake_input\n\nlocal attribute [instance] abelian.pseudoelement.over_to_sort\n abelian.pseudoelement.hom_to_fun\n abelian.pseudoelement.has_zero\n\nsection move_me\n\nlocal attribute [instance] abelian.pseudoelement.over_to_sort\n abelian.pseudoelement.hom_to_fun\n\nlemma injective_iff_mono {P Q : 𝒜} (f : P ⟶ Q) : function.injective f ↔ mono f :=\n⟨λ h, mono_of_zero_of_map_zero _ (zero_of_map_zero _ h),\n by introsI h; apply pseudo_injective_of_mono⟩\n\nlemma surjective_iff_epi {P Q : 𝒜} (f : P ⟶ Q) : function.surjective f ↔ epi f :=\n⟨epi_of_pseudo_surjective _, by introI h; apply pseudo_surjective_of_epi⟩\n\nlemma exists_of_exact {P Q R : 𝒜} {f : P ⟶ Q} {g : Q ⟶ R} (e : exact f g) (q) (hq : g q = 0) :\n ∃ p, f p = q :=\n(pseudo_exact_of_exact e).2 _ hq\n\nlemma eq_zero_of_exact {P Q R : 𝒜} {f : P ⟶ Q} {g : Q ⟶ R} (e : exact f g) (p) : g (f p) = 0 :=\n(pseudo_exact_of_exact e).1 _\n\n@[simp]\nlemma kernel_ι_apply {P Q : 𝒜} (f : P ⟶ Q) (a) : f (kernel.ι f a) = 0 :=\nbegin\n rw ← abelian.pseudoelement.comp_apply,\n simp,\nend\n\n-- (AT) I don't know if we actually want this lemma, but it came in handy below.\nlemma eq_zero_iff_kernel_ι_eq_zero {P Q : 𝒜} (f : P ⟶ Q) (q) : kernel.ι f q = 0 ↔ q = 0 :=\nbegin\n split,\n { intro h,\n apply_fun kernel.ι f,\n simp [h],\n rw injective_iff_mono,\n apply_instance },\n { intro h,\n simp [h] },\nend\n\n@[simp]\nlemma cokernel_π_apply {P Q : 𝒜} (f : P ⟶ Q) (a) : cokernel.π f (f a) = 0 :=\nbegin\n rw ← abelian.pseudoelement.comp_apply,\n simp,\nend\n\nlemma exists_of_cokernel_π_eq_zero {P Q : 𝒜} (f : P ⟶ Q) (a) :\n cokernel.π f a = 0 → ∃ b, f b = a :=\nbegin\n intro h,\n apply exists_of_exact _ _ h,\n apply snake_diagram.exact_self_cokernel_π,\nend\n\nlemma cokernel_π_surjective {P Q : 𝒜} (f : P ⟶ Q) : function.surjective (cokernel.π f) :=\nbegin\n rw surjective_iff_epi,\n apply_instance,\nend\n\n--move\nlemma exact_is_iso_iff {P Q Q' R : 𝒜} (f : P ⟶ Q) (g : Q' ⟶ R) (e : Q ⟶ Q') [is_iso e] :\n exact f (e ≫ g) ↔ exact (f ≫ e) g :=\nbegin\n let E := as_iso e,\n change exact f (E.hom ≫ g) ↔ exact (f ≫ E.hom) g,\n conv_rhs { rw (show g = E.inv ≫ E.hom ≫ g, by simp) },\n rw exact_comp_hom_inv_comp_iff\nend\n\n--lemma exact_comp_is_iso {P Q R R' : 𝒜} (f : P ⟶ Q) (g : Q ⟶ R) (e : R ⟶ R') [is_iso e] :\n-- exact f (g ≫ e) ↔ exact f g := exact_comp_iso\n\nend move_me\n\nlemma row_exact₀ (hD : is_snake_input D) : exact ((0,0) ⟶[D] (0,1)) ((0,1) ⟶[D] (0,2)) :=\nbegin\n refine exact_of_pseudo_exact _ _ ⟨λ a, _, _⟩,\n { apply_fun ((0,2) ⟶[D] (1,2)),\n swap, { rw injective_iff_mono, exact hD.col_mono _ },\n simp_rw [← abelian.pseudoelement.comp_apply, ← D.map_comp, abelian.pseudoelement.apply_zero],\n change D.map (hom (0,0) (1,0) ≫ hom (1,0) (1,1) ≫ hom (1,1) (1,2)) a = 0,\n simp [abelian.pseudoelement.comp_apply, eq_zero_of_exact hD.row_exact₁] },\n { intros b hb,\n apply_fun ((0,2) ⟶[D] (1,2)) at hb,\n simp_rw [← abelian.pseudoelement.comp_apply,\n ← D.map_comp, abelian.pseudoelement.apply_zero] at hb,\n change D.map (hom (0,1) (1,1) ≫ hom (1,1) (1,2)) b = 0 at hb,\n simp_rw [D.map_comp, abelian.pseudoelement.comp_apply] at hb,\n let b' := ((0,1) ⟶[D] (1,1)) b,\n change ((1,1) ⟶[D] (1,2)) b' = 0 at hb,\n obtain ⟨c,hc⟩ := exists_of_exact hD.row_exact₁ b' hb,\n have hcz : ((1,0) ⟶[D] (2,0)) c = 0,\n { apply_fun ((2,0) ⟶[D] (2,1)),\n swap, { rw injective_iff_mono, apply hD.row_mono },\n simp_rw [← abelian.pseudoelement.comp_apply, ← D.map_comp, abelian.pseudoelement.apply_zero],\n change D.map (hom (1,0) (1,1) ≫ hom (1,1) (2,1)) c = 0,\n simp_rw [D.map_comp, abelian.pseudoelement.comp_apply, hc],\n dsimp [b'],\n apply eq_zero_of_exact,\n apply hD.col_exact₁ },\n obtain ⟨d,hd⟩ := exists_of_exact (hD.col_exact₁ _) c hcz,\n use d,\n apply_fun ((0,1) ⟶[D] (1,1)),\n swap, { rw injective_iff_mono, exact hD.col_mono _ },\n dsimp only [b'] at hc,\n rw [← hc, ← hd],\n simp_rw [← abelian.pseudoelement.comp_apply, ← D.map_comp],\n refl }\nend\n\nlemma row_exact₃ (hD : is_snake_input D) : exact ((3,0) ⟶[D] (3,1)) ((3,1) ⟶[D] (3,2)) :=\nbegin\n refine exact_of_pseudo_exact _ _ ⟨λ a, _,λ b hb, _⟩,\n { obtain ⟨b, hb⟩ := (surjective_iff_epi ((2,0) ⟶[D] (3,0))).2 (hD.col_epi 0) a,\n rw [← hb, ← abelian.pseudoelement.comp_apply, ← abelian.pseudoelement.comp_apply,\n ← D.map_comp, ← D.map_comp, map_eq hD ((hom (2, 0) (3, 0)) ≫ (hom _ (3, 1)) ≫\n (hom _ (3, 2))) ((hom (2, 0) (2, 1)) ≫ (hom _ (2, 2)) ≫ (hom _ _)), ← category.assoc,\n D.map_comp _ (hom (2, 2) (3, 2)), D.map_comp, hD.row_exact₂.w, zero_comp, zero_apply] },\n { set f₁ := hom (2, 1) (2, 2),\n set f₂ := hom (2, 2) (3, 2),\n set f₃ := hom (1, 1) (2, 1),\n set f₄ := hom (2, 0) (3, 0),\n set f₅ := hom (3, 0) (3, 1),\n obtain ⟨c, hc⟩ := (surjective_iff_epi ((2,1) ⟶[D] (3,1))).2 (hD.col_epi 1) b,\n let d := D.map f₁ c,\n have hd : D.map f₂ d = 0,\n { rw [← abelian.pseudoelement.comp_apply, ← D.map_comp, map_eq hD ((hom (2, 1) (2, 2)) ≫\n (hom _ (3, 2))) ((hom (2, 1) (3, 1)) ≫ (hom _ (3, 2))), D.map_comp,\n abelian.pseudoelement.comp_apply, hc, hb] },\n obtain ⟨e, he⟩ := exists_of_exact (hD.col_exact₂ 2) d hd,\n obtain ⟨f, hf⟩ := (surjective_iff_epi ((1,1) ⟶[D] (1,2))).2 hD.row_epi e,\n have hfzero : ((2,1) ⟶[D] (3,1)) ((D.map f₃) f) = 0,\n { rw [← abelian.pseudoelement.comp_apply, (hD.col_exact₂ 1).w, zero_apply] },\n have hdiff : D.map f₁ c = D.map f₁ (D.map f₃ f),\n { rw [← abelian.pseudoelement.comp_apply, ← D.map_comp, map_eq hD ((hom (1, 1) (2, 1)) ≫\n (hom _ (2, 2))) ((hom (1, 1) (1, 2)) ≫ (hom _ (2, 2))), D.map_comp,\n abelian.pseudoelement.comp_apply, hf, he] },\n obtain ⟨g, ⟨hg₁, hg₂⟩⟩ := sub_of_eq_image _ _ _ hdiff,\n obtain ⟨h, hh⟩ := exists_of_exact hD.row_exact₂ g hg₁,\n use D.map f₄ h,\n rw [← abelian.pseudoelement.comp_apply, ← D.map_comp, map_eq hD\n ((hom (2, 0) (3, 0)) ≫ (hom _ (3, 1))) ((hom _ (2, 1)) ≫ (hom _ _)), D.map_comp,\n abelian.pseudoelement.comp_apply, hh, hg₂ _ ((2,1) ⟶[D] (3,1)) hfzero, hc] }\nend\n\nlemma row_exact (hD : is_snake_input D) (i : fin 4) :\n exact ((i,0) ⟶[D] (i,1)) ((i,1) ⟶[D] (i,2)) :=\nby { fin_cases i, exacts [hD.row_exact₀, hD.row_exact₁, hD.row_exact₂, hD.row_exact₃] }\n\nlemma hom_eq_zero₂ (hD : is_snake_input D) {x y : snake_diagram} (f : x ⟶ y)\n (h : x.2 = 0 ∧ y.2 = 2 . snake_diagram.hom_tac) : D.map f = 0 :=\nbegin\n cases x with i j, cases y with k l, rcases f with ⟨⟨⟨hik, hjl⟩⟩⟩,\n dsimp at h hik hjl, rcases h with ⟨rfl, rfl⟩,\n let f₁ := hom (i,0) (i,1),\n let f₂ := hom (i,1) (i,2),\n let f₃ := hom (i,2) (k,2),\n calc D.map _\n = D.map ((f₁ ≫ f₂) ≫ f₃) : hD.map_eq _ _\n ... = ((D.map f₁) ≫ D.map f₂) ≫ D.map f₃ : by simp only [D.map_comp]\n ... = 0 : by rw [(hD.row_exact i).w, zero_comp]\nend\n\nsection long_snake\n\nlemma ker_row₁_to_row₂ (hD : is_snake_input D) :\n (kernel.ι ((1,0) ⟶[D] (1,1))) ≫ ((1,0) ⟶[D] (2,0)) = 0 :=\nbegin\n refine zero_morphism_ext _ (λ a, (injective_iff_mono ((2,0) ⟶[D] (2,1))).2 hD.row_mono _),\n rw [apply_zero, ← abelian.pseudoelement.comp_apply, category.assoc,\n abelian.pseudoelement.comp_apply, ← D.map_comp, map_eq hD\n ((hom (1, 0) (2, 0)) ≫ (hom _ (2, 1))) ((hom _ (1, 1)) ≫ (hom _ _)), D.map_comp,\n abelian.pseudoelement.comp_apply, kernel_ι_apply, apply_zero]\nend\n\ndef ker_row₁_to_top_left (hD : is_snake_input D) : kernel ((1,0) ⟶[D] (1,1)) ⟶ D.obj (0, 0) :=\nby { letI := hD.col_mono 0, exact (limits.kernel.lift _ _ (ker_row₁_to_row₂ hD)) ≫\n (limits.kernel.lift _ _ (((abelian.exact_iff _ _).1 (hD.col_exact₁ 0)).2)) ≫\n inv (abelian.factor_thru_image ((0,0) ⟶[D] (1,0))) }\n\nlemma ker_row₁_to_top_left_mono (hD : is_snake_input D) : mono (ker_row₁_to_top_left hD) :=\nbegin\n suffices : mono ((limits.kernel.lift _ _ (ker_row₁_to_row₂ hD)) ≫\n (limits.kernel.lift _ _ (((abelian.exact_iff _ _).1 (hD.col_exact₁ 0)).2))),\n { letI := this, exact mono_comp _ _, },\n exact mono_comp _ _\nend\n\nlemma ker_row₁_to_top_left_comp_eq_ι (hD : is_snake_input D) : ker_row₁_to_top_left hD ≫\n ((0,0) ⟶[D] (1,0)) = kernel.ι ((1,0) ⟶[D] (1,1)) :=\nbegin\n letI := hD.col_mono 0,\n have : inv (abelian.factor_thru_image ((0,0) ⟶[D] (1,0))) ≫ ((0,0) ⟶[D] (1,0)) =\n category_theory.abelian.image.ι _ := by simp,\n rw [ker_row₁_to_top_left, category.assoc, category.assoc, this],\n simp\nend\n\nlemma long_row₀_exact (hD : is_snake_input D) :\n exact (ker_row₁_to_top_left hD) ((0,0) ⟶[D] (0,1)) :=\nbegin\n refine abelian.pseudoelement.exact_of_pseudo_exact _ _ ⟨λ a, _, λ a ha, _⟩,\n { refine (injective_iff_mono _).2 (hD.col_mono _) _,\n rw [apply_zero, ← abelian.pseudoelement.comp_apply, ← D.map_comp, map_eq hD\n ((hom (0, 0) (0, 1)) ≫ (hom _ (1, 1))) ((hom _ (1, 0)) ≫ (hom _ _)), D.map_comp,\n ← abelian.pseudoelement.comp_apply, ← category.assoc, ker_row₁_to_top_left_comp_eq_ι hD,\n abelian.pseudoelement.comp_apply, kernel_ι_apply] },\n { let b := ((0,0) ⟶[D] (1,0)) a,\n have hb : ((1,0) ⟶[D] (1,1)) b = 0,\n { rw [← abelian.pseudoelement.comp_apply, ← D.map_comp, map_eq hD\n ((hom (0, 0) (1, 0)) ≫ (hom _ (1, 1))) ((hom _ (0, 1)) ≫ (hom _ _)), D.map_comp,\n abelian.pseudoelement.comp_apply, ha, apply_zero] },\n obtain ⟨c, hc⟩ := exists_of_exact category_theory.exact_kernel_ι _ hb,\n refine ⟨c, (injective_iff_mono _).2 (hD.col_mono _) _⟩,\n rw [← abelian.pseudoelement.comp_apply, ker_row₁_to_top_left_comp_eq_ι hD, hc] }\nend\n\nlemma row₁_middle_to_coker_row₂_eq_zero (hD : is_snake_input D) :\n ((1,1) ⟶[D] (1,2)) ≫ ((1,2) ⟶[D] (2,2)) ≫ (limits.cokernel.π ((2,1) ⟶[D] (2,2))) = 0 :=\nbegin\n refine zero_morphism_ext _ (λ a, _),\n rw [← category.assoc, abelian.pseudoelement.comp_apply, ← D.map_comp, map_eq hD\n ((hom (1, 1) (1, 2)) ≫ (hom _ (2, 2))) ((hom _ (2, 1)) ≫ (hom _ _)), D.map_comp,\n ← abelian.pseudoelement.comp_apply],\n simp,\nend\n\nlemma row₁_to_coker_row₂_eq_zero (hD : is_snake_input D) :\n ((1,2) ⟶[D] (2,2)) ≫ (limits.cokernel.π ((2,1) ⟶[D] (2,2))) = 0 :=\nbegin\n letI := hD.row_epi,\n have := row₁_middle_to_coker_row₂_eq_zero hD,\n rw [← limits.comp_zero] at this,\n exact (cancel_epi _).1 this\nend\n\nlemma ker_col₂_to_coker_row₂_eq_zero (hD : is_snake_input D) :\n kernel.ι ((2,2) ⟶[D] (3,2)) ≫ (limits.cokernel.π ((1,2) ⟶[D] (2,2))) = 0 :=\nbegin\n refine zero_morphism_ext _ (λ a, _),\n obtain ⟨c, hc⟩ := exists_of_exact (hD.col_exact₂ 2) (kernel.ι (_ ⟶[D] _) a) (kernel_ι_apply _ _),\n rw [abelian.pseudoelement.comp_apply, ← hc, cokernel_π_apply]\nend\n\ndef bottom_right_to_coker_row₂ (hD : is_snake_input D) :\n D.obj (3, 2) ⟶ cokernel ((2,1) ⟶[D] (2,2)) :=\nby { letI := hD.col_epi 2, exact\n (inv (abelian.factor_thru_coimage ((2,2) ⟶[D] (3,2)))) ≫\n (limits.cokernel.desc _ _ (ker_col₂_to_coker_row₂_eq_zero hD)) ≫\n (limits.cokernel.desc _ _ (row₁_to_coker_row₂_eq_zero hD)) }\n\nlemma bottom_right_to_coker_row₂_epi (hD : is_snake_input D) : epi (bottom_right_to_coker_row₂ hD) :=\nbegin\n suffices : epi ((limits.cokernel.desc _ _ (ker_col₂_to_coker_row₂_eq_zero hD)) ≫\n (limits.cokernel.desc _ _ (row₁_to_coker_row₂_eq_zero hD))),\n { letI := this, exact epi_comp _ _ },\n exact epi_comp _ _,\nend\n\nlemma bottom_right_to_coker_row₂_comp_eq_π (hD : is_snake_input D) : ((2,2) ⟶[D] (3,2)) ≫\n bottom_right_to_coker_row₂ hD = cokernel.π ((2,1) ⟶[D] (2,2)) :=\nbegin\n letI := hD.col_epi 2,\n have : ((2,2) ⟶[D] (3,2)) ≫ inv (abelian.factor_thru_coimage ((2,2) ⟶[D] (3,2))) =\n category_theory.abelian.coimage.π _ := by simp,\n rw [bottom_right_to_coker_row₂, ← category.assoc, ← category.assoc, this],\n simp\nend\n\nlemma long_row₃_exact (hD : is_snake_input D) :\n exact ((3,1) ⟶[D] (3,2)) (bottom_right_to_coker_row₂ hD) :=\nbegin\n refine abelian.pseudoelement.exact_of_pseudo_exact _ _ ⟨λ a, _, λ a ha, _⟩,\n { letI := hD.col_epi 1,\n obtain ⟨b, hb⟩ := abelian.pseudoelement.pseudo_surjective_of_epi ((2,1) ⟶[D] (3,1)) a,\n rw [← hb, ← abelian.pseudoelement.comp_apply, ← abelian.pseudoelement.comp_apply,\n ← category.assoc, ← D.map_comp, map_eq hD ((hom (2, 1) (3, 1)) ≫ (hom _ (3, 2)))\n ((hom _ (2, 2)) ≫ (hom _ _)), D.map_comp, category.assoc,\n bottom_right_to_coker_row₂_comp_eq_π hD, (snake_diagram.exact_self_cokernel_π _).w,\n zero_apply], },\n { letI := hD.col_epi 2,\n obtain ⟨b, hb⟩ := abelian.pseudoelement.pseudo_surjective_of_epi ((2,2) ⟶[D] (3,2)) a,\n rw [← hb, ← abelian.pseudoelement.comp_apply, bottom_right_to_coker_row₂_comp_eq_π hD] at ha,\n obtain ⟨c, hc⟩ := exists_of_exact (abelian.exact_cokernel _) _ ha,\n refine ⟨((2,1) ⟶[D] (3,1)) c, _⟩,\n rw [← hb, ← hc, ← abelian.pseudoelement.comp_apply, ← abelian.pseudoelement.comp_apply,\n ← D.map_comp, map_eq hD ((hom (2, 1) (3, 1)) ≫ (hom _ (3, 2))) ((hom _ (2, 2)) ≫ (hom _ _)),\n D.map_comp] }\nend\n\nend long_snake\n\nexample (hD : is_snake_input D) (f : (o 1 0) ⟶ (o 2 2)) : D.map f = 0 := hD.hom_eq_zero₂ f\n\nsection delta\n\nvariable (hD : is_snake_input D)\ninclude hD\n\ndef to_top_right_kernel : D.obj (1,0) ⟶ kernel ((1,1) ⟶[D] (2,2)) :=\nkernel.lift _ (_ ⟶[D] _)\nbegin\n rw ← D.map_comp,\n change D.map (hom (1,0) (2,0) ≫ hom (2,0) (2,1) ≫ hom (2,1) (2,2)) = 0,\n simp [hD.row_exact₂.1],\nend\n\ndef cokernel_to_top_right_kernel_to_right_kernel :\n cokernel hD.to_top_right_kernel ⟶ kernel ((1,2) ⟶[D] (2,2)) :=\ncokernel.desc _ (kernel.lift _ (kernel.ι _ ≫ (_ ⟶[D] _)) begin\n rw [category.assoc, ← D.map_comp],\n have : hom (1,1) (1,2) ≫ hom (1,2) (2,2) = hom (1,1) (2,2) := rfl,\n rw this, clear this,\n simp [abelian.pseudoelement.comp_apply],\nend) begin\n dsimp only [to_top_right_kernel],\n ext a,\n apply_fun kernel.ι (D.map (hom (1, 2) (2, 2))),\n swap, { rw injective_iff_mono, apply_instance },\n simp [← abelian.pseudoelement.comp_apply, hD.row_exact₁.1],\nend\n\ninstance : mono hD.cokernel_to_top_right_kernel_to_right_kernel :=\nbegin\n apply mono_of_zero_of_map_zero,\n intros a h,\n obtain ⟨b,rfl⟩ := cokernel_π_surjective _ a,\n rw ← eq_zero_iff_kernel_ι_eq_zero at h,\n simp [← abelian.pseudoelement.comp_apply, cokernel_to_top_right_kernel_to_right_kernel] at h,\n simp [ abelian.pseudoelement.comp_apply] at h,\n have : ∃ c, ((1,0) ⟶[D] (1,1)) c = kernel.ι ((1,1) ⟶[D] (2,2)) b,\n { apply exists_of_exact _ _ h,\n exact hD.row_exact₁ },\n obtain ⟨c,hc⟩ := this,\n let f : cokernel hD.to_top_right_kernel ⟶ cokernel ((1,0) ⟶[D] (1,1)) :=\n cokernel.desc _ _ _,\n swap, { refine kernel.ι _ ≫ cokernel.π _ },\n swap, { simp [to_top_right_kernel] },\n apply_fun f,\n swap, {\n rw injective_iff_mono,\n apply mono_of_zero_of_map_zero,\n intros a ha,\n dsimp [f] at ha,\n obtain ⟨a,rfl⟩ := cokernel_π_surjective _ a,\n simp [← abelian.pseudoelement.comp_apply] at ha,\n simp [abelian.pseudoelement.comp_apply] at ha,\n have : ∃ c, ((1,0) ⟶[D] (1,1)) c = kernel.ι ((1,1) ⟶[D] (2,2)) a,\n { apply exists_of_exact _ _ ha,\n apply snake_diagram.exact_self_cokernel_π, },\n obtain ⟨c,hc⟩ := this,\n have : hD.to_top_right_kernel c = a,\n { apply_fun kernel.ι ((1,1) ⟶[D] (2,2)),\n swap, { rw injective_iff_mono, apply_instance },\n dsimp [to_top_right_kernel],\n simp [← abelian.pseudoelement.comp_apply],\n erw kernel.lift_ι,\n exact hc },\n simp [← this] },\n dsimp only [f],\n simp [← abelian.pseudoelement.comp_apply, to_top_right_kernel],\n simp [abelian.pseudoelement.comp_apply, ← hc],\nend .\n\ninstance : epi hD.cokernel_to_top_right_kernel_to_right_kernel :=\nbegin\n apply epi_of_pseudo_surjective,\n intros a,\n let a' := kernel.ι ((1,2) ⟶[D] (2,2)) a,\n obtain ⟨b,hb⟩ : ∃ b, ((1,1) ⟶[D] (1,2)) b = a',\n { suffices : function.surjective ((1,1) ⟶[D] (1,2)), by apply this,\n rw surjective_iff_epi,\n apply hD.row_epi },\n obtain ⟨c,hc⟩ : ∃ c, kernel.ι ((1,1) ⟶[D] (2,2)) c = b,\n { have : exact (kernel.ι ((1,1) ⟶[D] (2,2))) ((1,1) ⟶[D] (2,2)) := exact_kernel_ι,\n apply exists_of_exact this,\n rw [(show hom (1,1) (2,2) = hom (1,1) (1,2) ≫ hom (1,2) (2,2), by refl),\n D.map_comp, abelian.pseudoelement.comp_apply, hb],\n dsimp only [a'],\n simp },\n use cokernel.π hD.to_top_right_kernel c,\n apply_fun kernel.ι ((1,2) ⟶[D] (2,2)),\n swap, { rw injective_iff_mono, apply_instance },\n dsimp only [to_top_right_kernel, cokernel_to_top_right_kernel_to_right_kernel],\n simp [← abelian.pseudoelement.comp_apply],\n change _ = a',\n rw ← hb,\n simp [← hb, abelian.pseudoelement.comp_apply, ← hc],\nend .\n\ninstance : is_iso hD.cokernel_to_top_right_kernel_to_right_kernel :=\nis_iso_of_mono_of_epi _\n\ndef bottom_left_cokernel_to : cokernel ((1,0) ⟶[D] (2,1)) ⟶ D.obj (2,2) :=\ncokernel.desc _ (_ ⟶[D] _)\nbegin\n rw ← D.map_comp,\n change D.map (hom (1,0) (2,0) ≫ hom (2,0) (2,1) ≫ hom (2,1) (2,2)) = 0,\n simp_rw D.map_comp,\n simp [hD.row_exact₂.1],\nend\n\ndef left_cokernel_to_kernel_bottom_left_cokernel_to :\n cokernel ((1,0) ⟶[D] (2,0)) ⟶ kernel hD.bottom_left_cokernel_to :=\nkernel.lift _ (cokernel.desc _ ((_ ⟶[D] _) ≫ cokernel.π _) begin\n rw [← category.assoc, ← D.map_comp],\n have : hom (1,0) (2,0) ≫ hom (2,0) (2,1) = hom _ _ := rfl,\n rw this, clear this,\n simp [abelian.pseudoelement.comp_apply],\nend) begin\n dsimp only [bottom_left_cokernel_to],\n ext a,\n obtain ⟨b,rfl⟩ : ∃ b, cokernel.π ((1,0) ⟶[D] (2,0)) b = a,\n { have : function.surjective (cokernel.π ((1,0) ⟶[D] (2,0))),\n by { rw surjective_iff_epi, apply_instance },\n apply this },\n simp [← abelian.pseudoelement.comp_apply, hD.row_exact₂.1],\nend\n\ninstance : mono hD.left_cokernel_to_kernel_bottom_left_cokernel_to :=\nbegin\n apply mono_of_zero_of_map_zero,\n intros a ha,\n obtain ⟨a,rfl⟩ := cokernel_π_surjective _ a,\n dsimp [left_cokernel_to_kernel_bottom_left_cokernel_to] at ha,\n rw ← eq_zero_iff_kernel_ι_eq_zero at ha,\n simp [← abelian.pseudoelement.comp_apply] at ha,\n simp [abelian.pseudoelement.comp_apply] at ha,\n obtain ⟨c,hc⟩ : ∃ c, ((1,0) ⟶[D] (2,1)) c = ((2,0) ⟶[D] (2,1)) a,\n { apply exists_of_exact _ _ ha,\n apply abelian.exact_cokernel, },\n have : ((1,0) ⟶[D] (2,0)) c = a,\n { apply_fun ((2,0) ⟶[D] (2,1)),\n swap, { rw injective_iff_mono, apply hD.row_mono },\n simpa only [← hc, ← abelian.pseudoelement.comp_apply, ← D.map_comp] },\n simp [← this],\nend .\n\ninstance : epi hD.left_cokernel_to_kernel_bottom_left_cokernel_to :=\nbegin\n apply epi_of_pseudo_surjective,\n intros a,\n let a' := kernel.ι hD.bottom_left_cokernel_to a,\n obtain ⟨b,hb⟩ := cokernel_π_surjective _ a',\n have : ((2,1) ⟶[D] (2,2)) b = 0,\n { apply_fun hD.bottom_left_cokernel_to at hb,\n dsimp [a', bottom_left_cokernel_to] at hb,\n simpa [← abelian.pseudoelement.comp_apply] using hb },\n obtain ⟨c,hc⟩ : ∃ c, ((2,0) ⟶[D] (2,1)) c = b,\n { apply exists_of_exact _ _ this,\n exact hD.row_exact₂ },\n use cokernel.π ((1,0) ⟶[D] (2,0)) c,\n apply_fun kernel.ι hD.bottom_left_cokernel_to,\n swap, { rw injective_iff_mono, apply_instance },\n change _ = a',\n simp [← abelian.pseudoelement.comp_apply, ← hb,\n left_cokernel_to_kernel_bottom_left_cokernel_to],\n simp [abelian.pseudoelement.comp_apply, hc],\nend\n\ninstance : is_iso hD.left_cokernel_to_kernel_bottom_left_cokernel_to :=\nis_iso_of_mono_of_epi _\n\ndef δ_aux : cokernel hD.to_top_right_kernel ⟶ kernel hD.bottom_left_cokernel_to :=\ncokernel.desc _ (kernel.lift _ (kernel.ι _ ≫ (_ ⟶[D] _) ≫ cokernel.π _) begin\n dsimp only [bottom_left_cokernel_to],\n simp,\n rw ← D.map_comp,\n have : hom (1,1) (2,1) ≫ hom (2,1) (2,2) = hom _ _ := rfl,\n rw this,\n simp [abelian.pseudoelement.comp_apply],\nend)\nbegin\n dsimp only [to_top_right_kernel],\n simp,\n ext,\n apply_fun kernel.ι hD.bottom_left_cokernel_to,\n swap, { rw injective_iff_mono, apply_instance },\n simp [← abelian.pseudoelement.comp_apply],\n rw [← category.assoc, ← D.map_comp],\n have : hom (1,0) (1,1) ≫ hom (1,1) (2,1) = hom _ _, refl, rw this, clear this,\n simp [abelian.pseudoelement.comp_apply],\nend\n\ndef to_kernel : D.obj (0,2) ⟶ kernel ((1,2) ⟶[D] (2,2)) :=\nkernel.lift _ (_ ⟶[D] _) (hD.col_exact₁ _).1\n\ninstance : mono hD.to_kernel :=\nbegin\n dsimp [to_kernel],\n haveI : mono ((0,2) ⟶[D] (1,2)) := hD.col_mono _,\n apply_instance,\nend\n\ninstance : epi hD.to_kernel :=\nkernel.lift.epi (hD.col_exact₁ _)\n\ninstance : is_iso hD.to_kernel :=\nis_iso_of_mono_of_epi _\n\ndef cokernel_to : cokernel ((1,0) ⟶[D] (2,0)) ⟶ D.obj (3,0) :=\ncokernel.desc _ (_ ⟶[D] _) (hD.col_exact₂ _).1\n\ninstance : mono hD.cokernel_to :=\nabelian.category_theory.limits.cokernel.desc.category_theory.mono _ _ (hD.col_exact₂ _)\n\ninstance : epi hD.cokernel_to :=\nbegin\n dsimp [cokernel_to],\n haveI : epi ((2,0) ⟶[D] (3,0)) := hD.col_epi _,\n apply_instance,\nend\n\ninstance : is_iso hD.cokernel_to :=\nis_iso_of_mono_of_epi _\n\ndef δ : D.obj (0,2) ⟶ D.obj (3,0) :=\n hD.to_kernel ≫ inv hD.cokernel_to_top_right_kernel_to_right_kernel ≫ -- <-- this is an iso\n hD.δ_aux ≫ -- <- this is the key\n inv hD.left_cokernel_to_kernel_bottom_left_cokernel_to ≫ hD.cokernel_to -- <-- this is an iso\n\ndef to_δ_aux : D.obj (0,1) ⟶ cokernel hD.to_top_right_kernel :=\nkernel.lift _ ((0,1) ⟶[D] (1,1)) begin\n rw [(show (hom (1,1) (2,2) = hom (1,1) (2,1) ≫ hom _ _), by refl), D.map_comp,\n ← category.assoc, (hD.col_exact₁ _).1],\n simp,\nend ≫ cokernel.π _\n\ndef from_δ_aux : kernel hD.bottom_left_cokernel_to ⟶ D.obj (3,1) :=\nkernel.ι _ ≫ cokernel.desc _ ((2,1) ⟶[D] (3,1)) begin\n rw [(show hom (1,0) (2,1) = hom (1,0) (1,1) ≫ hom (1,1) (2,1), by refl),\n D.map_comp, category.assoc, (hD.col_exact₂ _).w],\n simp,\nend\n\ntheorem exact_to_δ_aux : exact hD.to_δ_aux hD.δ_aux :=\nbegin\n apply exact_of_pseudo_exact,\n split,\n { intros a,\n dsimp [δ_aux, to_δ_aux],\n rw ← eq_zero_iff_kernel_ι_eq_zero,\n simp only [←abelian.pseudoelement.comp_apply, cokernel.π_desc,\n kernel.lift_ι_assoc, category.assoc, kernel.lift_ι],\n simp [abelian.pseudoelement.comp_apply, eq_zero_of_exact (hD.col_exact₁ _)] },\n { intros b hb,\n obtain ⟨b,rfl⟩ := cokernel_π_surjective _ b,\n dsimp [δ_aux] at hb,\n rw ← eq_zero_iff_kernel_ι_eq_zero at hb,\n simp only [←abelian.pseudoelement.comp_apply, cokernel.π_desc, kernel.lift_ι] at hb,\n simp only [abelian.pseudoelement.comp_apply] at hb,\n let b' := kernel.ι ((1,1) ⟶[D] (2,2)) b,\n obtain ⟨c,hc⟩ := exists_of_cokernel_π_eq_zero _ _ hb, clear hb,\n change _ = ((1,1) ⟶[D] (2,1)) b' at hc,\n rw [(show hom (1,0) (2,1) = hom (1,0) (1,1) ≫ hom _ _, by refl), D.map_comp,\n abelian.pseudoelement.comp_apply] at hc,\n obtain ⟨z,h1,h2⟩ := sub_of_eq_image _ _ _ hc.symm, clear hc,\n specialize h2 _ ((1,1) ⟶[D] (1,2)) (eq_zero_of_exact hD.row_exact₁ _),\n obtain ⟨w,hw⟩ : ∃ w, ((0,1) ⟶[D] (1,1)) w = z := exists_of_exact (hD.col_exact₁ _) _ h1,\n clear h1,\n use w,\n dsimp only [b'] at h2,\n dsimp only [to_δ_aux],\n simp only [abelian.pseudoelement.comp_apply],\n apply_fun hD.cokernel_to_top_right_kernel_to_right_kernel,\n swap, { rw injective_iff_mono, apply_instance },\n dsimp only [cokernel_to_top_right_kernel_to_right_kernel],\n simp only [←abelian.pseudoelement.comp_apply, cokernel.π_desc, category.assoc],\n simp only [abelian.pseudoelement.comp_apply],\n apply_fun kernel.ι ((1,2) ⟶[D] (2,2)),\n swap, { rw injective_iff_mono, apply_instance },\n simp only [←abelian.pseudoelement.comp_apply, kernel.lift_ι_assoc,\n category.assoc, kernel.lift_ι],\n simp only [abelian.pseudoelement.comp_apply],\n rw [hw, h2] }\nend\n\ntheorem exact_from_δ_aux : exact hD.δ_aux hD.from_δ_aux :=\nbegin\n apply exact_of_pseudo_exact,\n split,\n { intros a,\n dsimp [δ_aux, from_δ_aux],\n obtain ⟨a,rfl⟩ := cokernel_π_surjective _ a,\n simp only [←abelian.pseudoelement.comp_apply,\n cokernel.π_desc, kernel.lift_ι_assoc, category.assoc],\n simp [abelian.pseudoelement.comp_apply, eq_zero_of_exact (hD.col_exact₂ _)] },\n { intros b hb,\n let b' := kernel.ι hD.bottom_left_cokernel_to b,\n obtain ⟨c,hc⟩ := cokernel_π_surjective _ b',\n simp only [from_δ_aux, abelian.pseudoelement.comp_apply] at hb,\n change cokernel.desc ((1,0) ⟶[D] (2,1)) _ _ b' = 0 at hb,\n rw ← hc at hb,\n simp only [←abelian.pseudoelement.comp_apply, cokernel.π_desc] at hb,\n obtain ⟨d,hd⟩ : ∃ d, ((1,1) ⟶[D] (2,1)) d = c := exists_of_exact (hD.col_exact₂ _) _ hb,\n obtain ⟨e,he⟩ : ∃ e, kernel.ι ((1,1) ⟶[D] (2,2)) e = d,\n { apply exists_of_exact _ _ (_ : ((1,1) ⟶[D] (2,2)) d = 0),\n { apply exact_kernel_ι },\n dsimp [b'] at hc,\n apply_fun hD.bottom_left_cokernel_to at hc,\n simp only [bottom_left_cokernel_to, ←abelian.pseudoelement.comp_apply, cokernel.π_desc] at hc,\n rw [(show hom (1,1) (2,2) = hom (1,1) (2,1) ≫ hom (2,1) (2,2), by refl), D.map_comp,\n abelian.pseudoelement.comp_apply, hd, hc],\n simp only [abelian.pseudoelement.comp_apply],\n change hD.bottom_left_cokernel_to (kernel.ι hD.bottom_left_cokernel_to b) = 0,\n apply kernel_ι_apply },\n use cokernel.π hD.to_top_right_kernel e,\n apply_fun kernel.ι hD.bottom_left_cokernel_to,\n swap, { rw injective_iff_mono, apply_instance },\n change _ = b',\n dsimp [δ_aux],\n simp only [←abelian.pseudoelement.comp_apply, cokernel.π_desc, kernel.lift_ι],\n simp only [abelian.pseudoelement.comp_apply],\n rw [he, hd, hc] }\nend\n\ntheorem exact_to_δ : exact ((0,1) ⟶[D] (0,2)) hD.δ :=\nbegin\n dsimp [δ],\n rw [exact_is_iso_iff, exact_is_iso_iff, exact_comp_iso],\n convert hD.exact_to_δ_aux using 1,\n rw is_iso.comp_inv_eq,\n dsimp [to_kernel, to_δ_aux, cokernel_to_top_right_kernel_to_right_kernel],\n ext,\n simp only [cokernel.π_desc, kernel.lift_ι_assoc, category.assoc, kernel.lift_ι],\n simpa only [← D.map_comp],\nend\n\ntheorem exact_from_δ : exact hD.δ ((3,0) ⟶[D] (3,1)) :=\nbegin\n dsimp [δ],\n rw [← category.assoc, ← category.assoc, ← exact_is_iso_iff, exact_iso_comp],\n convert hD.exact_from_δ_aux using 1,\n rw [category.assoc, is_iso.inv_comp_eq],\n dsimp [cokernel_to, left_cokernel_to_kernel_bottom_left_cokernel_to, from_δ_aux],\n ext,\n simp only [cokernel.π_desc, kernel.lift_ι_assoc, cokernel.π_desc_assoc, category.assoc],\n simpa only [← D.map_comp],\nend\n\nend delta\n\nsection delta_spec\n\nvariables (hD : is_snake_input D)\n\ndef to_kernel' : kernel ((1,1) ⟶[D] (2,2)) ⟶ D.obj (0,2) :=\nkernel.lift _ (kernel.ι _ ≫ D.map (hom (1,1) (1,2))) begin\n erw [category.assoc, ← D.map_comp, kernel.condition],\nend ≫ inv hD.to_kernel\n\ninstance to_kernel_epi : epi hD.to_kernel' :=\nbegin\n dsimp [to_kernel'],\n apply_with epi_comp { instances := ff }, swap, apply_instance,\n haveI : epi ((1,1) ⟶[D] (1,2)) := hD.row_epi,\n replace hh := pseudo_surjective_of_epi ((1,1) ⟶[D] (1,2)),\n apply epi_of_pseudo_surjective,\n intros t,\n obtain ⟨s,hs⟩ := hh (kernel.ι ((1,2) ⟶[D] (2,2)) t),\n obtain ⟨w,hw⟩ : ∃ w, kernel.ι ((1,1) ⟶[D] (2,2)) w = s,\n { have : exact (kernel.ι ((1,1) ⟶[D] (2,2))) ((1,1) ⟶[D] (2,2)) :=\n exact_kernel_ι,\n replace this := pseudo_exact_of_exact this,\n apply this.2,\n rw [(show (hom (1,1) (2,2)) = hom (1,1) (1,2) ≫ hom (1,2) (2,2), by refl),\n functor.map_comp, abelian.pseudoelement.comp_apply, hs,\n ← abelian.pseudoelement.comp_apply, kernel.condition,\n abelian.pseudoelement.zero_apply] },\n use w,\n apply abelian.pseudoelement.pseudo_injective_of_mono\n (kernel.ι ((1,2) ⟶[D] (2,2))),\n rw [← hs, ← abelian.pseudoelement.comp_apply, kernel.lift_ι,\n abelian.pseudoelement.comp_apply, hw],\nend\n\ndef cokernel_to' : D.obj (3,0) ⟶ cokernel ((1,0) ⟶[D] (2,1)) :=\ninv hD.cokernel_to ≫ cokernel.desc _ (D.map (hom (2,0) (2,1)) ≫ cokernel.π _) begin\n erw [← category.assoc, ← D.map_comp, cokernel.condition],\nend\n\ninstance cokernel_to'_mono : mono hD.cokernel_to' := begin\n dsimp [cokernel_to'],\n apply_with mono_comp { instances := ff }, apply_instance,\n apply abelian.pseudoelement.mono_of_zero_of_map_zero,\n intros a ha,\n obtain ⟨b,rfl⟩ : ∃ b, cokernel.π ((1,0) ⟶[D] (2,0)) b = a,\n { apply abelian.pseudoelement.pseudo_surjective_of_epi },\n rw [← abelian.pseudoelement.comp_apply, cokernel.π_desc,\n abelian.pseudoelement.comp_apply] at ha,\n obtain ⟨c,hc⟩ : ∃ c, ((1,0) ⟶[D] (2,1)) c = ((2,0) ⟶[D] (2,1)) b,\n { have : exact ((1,0) ⟶[D] (2,1)) (cokernel.π _) := abelian.exact_cokernel _,\n replace this := pseudo_exact_of_exact this,\n apply this.2,\n exact ha },\n have hc' : ((1,0) ⟶[D] (2,0)) c = b,\n { haveI : mono ((2,0) ⟶[D] (2,1)) := hD.row_mono,\n apply abelian.pseudoelement.pseudo_injective_of_mono ((2,0) ⟶[D] (2,1)),\n rw [← abelian.pseudoelement.comp_apply, ← D.map_comp],\n exact hc },\n rw [← hc', ← abelian.pseudoelement.comp_apply, cokernel.condition,\n abelian.pseudoelement.zero_apply],\nend\n\nlemma δ_spec : hD.to_kernel' ≫ hD.δ ≫ hD.cokernel_to' =\n kernel.ι _ ≫ D.map (hom (1,1) (2,1)) ≫ cokernel.π _ :=\nbegin\n dsimp only [is_snake_input.δ ,is_snake_input.to_kernel', is_snake_input.cokernel_to'],\n simp only [category.assoc, is_iso.hom_inv_id_assoc, is_iso.inv_hom_id_assoc],\n dsimp only [is_snake_input.cokernel_to_top_right_kernel_to_right_kernel],\n dsimp only [is_snake_input.left_cokernel_to_kernel_bottom_left_cokernel_to],\n dsimp only [is_snake_input.δ_aux],\n let t := _, change _ ≫ _ ≫ _ ≫ t = _,\n have ht : t = kernel.ι _,\n { dsimp [t],\n rw is_iso.inv_comp_eq,\n apply coequalizer.hom_ext,\n simp only [cokernel.π_desc, category.assoc, kernel.lift_ι, cokernel.π_desc_assoc] },\n rw ht, clear ht, clear t,\n let t := _, change t ≫ _ = _,\n let s := _, change t ≫ s ≫ _ = _,\n have hst : t ≫ s = cokernel.π _,\n { dsimp [s,t],\n rw is_iso.comp_inv_eq,\n apply equalizer.hom_ext,\n simp only [cokernel.π_desc] },\n rw reassoc_of hst, clear hst, clear s, clear t,\n simp only [cokernel.π_desc_assoc, kernel.lift_ι],\nend\n\nlemma eq_δ_of_spec (e : D.obj (0,2) ⟶ D.obj (3,0))\n (he : hD.to_kernel' ≫ e ≫ hD.cokernel_to' = kernel.ι _ ≫\n D.map (hom (1,1) (2,1)) ≫ cokernel.π _) :\n e = hD.δ :=\nbegin\n rw ← cancel_mono hD.cokernel_to',\n rw ← cancel_epi hD.to_kernel',\n rw [he, δ_spec],\nend\n\nend delta_spec\n\nlocal attribute [instance] limits.has_zero_object.has_zero\n\nlemma exact_zero_to_ker_row₁_to_top_left (hD : is_snake_input D) :\n exact (0 : 0 ⟶ kernel ((1,0) ⟶[D] (1,1))) hD.ker_row₁_to_top_left :=\nbegin\n haveI : mono hD.ker_row₁_to_top_left := ker_row₁_to_top_left_mono hD,\n apply exact_zero_left_of_mono,\nend\n\nlemma exact_bottom_right_to_coker_row₂_to_zero (hD : is_snake_input D) :\n exact hD.bottom_right_to_coker_row₂ (0 : cokernel ((2,1) ⟶[D] (2,2)) ⟶ 0) :=\nbegin\n rw ← epi_iff_exact_zero_right,\n apply bottom_right_to_coker_row₂_epi hD,\nend\n\nlemma ten_term_exact_seq (hD : is_snake_input D) :\n exact_seq 𝒜 [\n (0 : 0 ⟶ kernel ((1,0) ⟶[D] (1,1))),\n hD.ker_row₁_to_top_left, (0,0) ⟶[D] (0,1), (0,1) ⟶[D] (0,2),\n hD.δ,\n (3,0) ⟶[D] (3,1), (3,1) ⟶[D] (3,2), hD.bottom_right_to_coker_row₂,\n (0 : cokernel ((2,1) ⟶[D] (2,2)) ⟶ 0)] :=\nbegin\n refine exact_seq.cons _ _ hD.exact_zero_to_ker_row₁_to_top_left _ _,\n refine exact_seq.cons _ _ hD.long_row₀_exact _ _,\n refine exact_seq.cons _ _ hD.row_exact₀ _ _,\n refine exact_seq.cons _ _ hD.exact_to_δ _ _,\n refine exact_seq.cons _ _ hD.exact_from_δ _ _,\n refine exact_seq.cons _ _ hD.row_exact₃ _ _,\n refine exact_seq.cons _ _ hD.long_row₃_exact _ _,\n refine exact_seq.cons _ _ hD.exact_bottom_right_to_coker_row₂_to_zero _ _,\n refine exact_seq.single _,\nend\n\nlemma eight_term_exact_seq (hD : is_snake_input D) :\n exact_seq 𝒜 [hD.ker_row₁_to_top_left, (0,0) ⟶[D] (0,1), (0,1) ⟶[D] (0,2),\n hD.δ,\n (3,0) ⟶[D] (3,1), (3,1) ⟶[D] (3,2), hD.bottom_right_to_coker_row₂] :=\nexact_seq.extract hD.ten_term_exact_seq 1 7\n\nlemma six_term_exact_seq (hD : is_snake_input D) :\n exact_seq 𝒜 [(0,0) ⟶[D] (0,1), (0,1) ⟶[D] (0,2), hD.δ, (3,0) ⟶[D] (3,1), (3,1) ⟶[D] (3,2)] :=\nexact_seq.extract hD.eight_term_exact_seq 1 5\n\nend is_snake_input\n\nvariables (𝒜)\n\nstructure snake_input extends snake_diagram ⥤ 𝒜 :=\n(is_snake_input : is_snake_input to_functor)\n\nnamespace snake_input\n\ninstance : category (snake_input 𝒜) := induced_category.category to_functor\n\n@[simps] def proj (x : snake_diagram) : snake_input 𝒜 ⥤ 𝒜 :=\ninduced_functor _ ⋙ (evaluation _ _).obj x\n\ndef mk_of_short_exact_sequence_hom (A B : short_exact_sequence 𝒜) (f : A ⟶ B) :\n snake_input 𝒜 :=\n⟨snake_diagram.mk_of_short_exact_sequence_hom A B f,\nis_snake_input.mk_of_short_exact_sequence_hom A B f⟩\n\ndef kernel_sequence (D : snake_input 𝒜)\n (h1 : mono ((1,0) ⟶[D] (1,1))) (h2 : is_zero (D.obj (3,0))) :\n short_exact_sequence 𝒜 :=\n{ fst := D.obj (0,0),\n snd := D.obj (0,1),\n trd := D.obj (0,2),\n f := (0,0) ⟶[D] (0,1),\n g := (0,1) ⟶[D] (0,2),\n mono' :=\n begin\n letI := h1,\n refine abelian.pseudoelement.mono_of_zero_of_map_zero _ (λ a ha, _),\n obtain ⟨b, hb⟩ := is_snake_input.exists_of_exact\n (is_snake_input.long_row₀_exact D.is_snake_input) a ha,\n rw [← hb],\n simp [is_snake_input.ker_row₁_to_top_left, limits.kernel.ι_of_mono ((1,0) ⟶[D] (1,1))]\n end,\n epi' :=\n begin\n rw (abelian.tfae_epi (D.obj (3,0)) ((0,1) ⟶[D] (0,2))).out 0 2,\n convert D.2.exact_to_δ,\n apply h2.eq_of_tgt,\n end,\n exact' := D.2.row_exact _ }\n\nend snake_input\n\nclass has_snake_lemma :=\n(δ : snake_input.proj 𝒜 (0,2) ⟶ snake_input.proj 𝒜 (3,0))\n(exact_δ : ∀ (D : snake_input 𝒜), exact ((0,1) ⟶[D] (0,2)) (δ.app D))\n(δ_exact : ∀ (D : snake_input 𝒜), exact (δ.app D) ((3,0) ⟶[D.1] (3,1))) -- why can't I write `⟶[D]`\n\nnamespace snake_lemma\n\nvariables [has_snake_lemma 𝒜]\n\nvariables {𝒜}\n\ndef δ (D : snake_input 𝒜) : D.obj (0,2) ⟶ D.obj (3,0) := has_snake_lemma.δ.app D\n\nlemma exact_δ (D : snake_input 𝒜) : exact ((0,1) ⟶[D] (0,2)) (δ D) :=\nhas_snake_lemma.exact_δ D\n\nlemma δ_exact (D : snake_input 𝒜) : exact (δ D) ((3,0) ⟶[D] (3,1)) :=\nhas_snake_lemma.δ_exact D\n\nend snake_lemma\n\nend\n\nend category_theory\n", "meta": {"author": "leanprover-community", "repo": "lean-liquid", "sha": "92f188bd17f34dbfefc92a83069577f708851aec", "save_path": "github-repos/lean/leanprover-community-lean-liquid", "path": "github-repos/lean/leanprover-community-lean-liquid/lean-liquid-92f188bd17f34dbfefc92a83069577f708851aec/src/for_mathlib/snake_lemma.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34864513533394575, "lm_q2_score": 0.026355350551870178, "lm_q1q2_score": 0.00918866475993036}} {"text": "/-\nCopyright (c) 2019 Simon Hudon. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Simon Hudon\n\nMonad encapsulating continuation passing programming style, similar to\nHaskell's `Cont`, `ContT` and `MonadCont`:\n\n-/\nimport control.monad.basic\nimport control.monad.writer\n\nuniverses u v w u₀ u₁ v₀ v₁\n\nstructure monad_cont.label (α : Type w) (m : Type u → Type v) (β : Type u) :=\n(apply : α → m β)\n\ndef monad_cont.goto {α β} {m : Type u → Type v} (f : monad_cont.label α m β) (x : α) := f.apply x\n\nclass monad_cont (m : Type u → Type v) :=\n(call_cc : Π {α β}, ((monad_cont.label α m β) → m α) → m α)\n\nopen monad_cont\n\nclass is_lawful_monad_cont (m : Type u → Type v) [monad m] [monad_cont m]\nextends is_lawful_monad m :=\n(call_cc_bind_right {α ω γ} (cmd : m α) (next : (label ω m γ) → α → m ω) :\n call_cc (λ f, cmd >>= next f) = cmd >>= λ x, call_cc (λ f, next f x))\n(call_cc_bind_left {α} (β) (x : α) (dead : label α m β → β → m α) :\n call_cc (λ f : label α m β, goto f x >>= dead f) = pure x)\n(call_cc_dummy {α β} (dummy : m α) :\n call_cc (λ f : label α m β, dummy) = dummy)\n\nexport is_lawful_monad_cont\n\ndef cont_t (r : Type u) (m : Type u → Type v) (α : Type w) := (α → m r) → m r\n\n@[reducible] def cont (r : Type u) (α : Type w) := cont_t r id α\n\nnamespace cont_t\n\nexport monad_cont (label goto)\n\nvariables {r : Type u} {m : Type u → Type v} {α β γ ω : Type w}\n\ndef run : cont_t r m α → (α → m r) → m r := id\n\ndef map (f : m r → m r) (x : cont_t r m α) : cont_t r m α := f ∘ x\n\nlemma run_cont_t_map_cont_t (f : m r → m r) (x : cont_t r m α) :\n run (map f x) = f ∘ run x := rfl\n\ndef with_cont_t (f : (β → m r) → α → m r) (x : cont_t r m α) : cont_t r m β :=\nλ g, x $ f g\n\nlemma run_with_cont_t (f : (β → m r) → α → m r) (x : cont_t r m α) :\n run (with_cont_t f x) = run x ∘ f := rfl\n\n@[ext]\nprotected lemma ext {x y : cont_t r m α}\n (h : ∀ f, x.run f = y.run f) :\n x = y := by { ext; apply h }\n\ninstance : monad (cont_t r m) :=\n{ pure := λ α x f, f x,\n bind := λ α β x f g, x $ λ i, f i g }\n\ninstance : is_lawful_monad (cont_t r m) :=\n{ id_map := by { intros, refl },\n pure_bind := by { intros, ext, refl },\n bind_assoc := by { intros, ext, refl } }\n\ndef monad_lift [monad m] {α} : m α → cont_t r m α :=\nλ x f, x >>= f\n\ninstance [monad m] : has_monad_lift m (cont_t r m) :=\n{ monad_lift := λ α, cont_t.monad_lift }\n\nlemma monad_lift_bind [monad m] [is_lawful_monad m] {α β} (x : m α) (f : α → m β) :\n (monad_lift (x >>= f) : cont_t r m β) = monad_lift x >>= monad_lift ∘ f :=\nbegin\n ext,\n simp only [monad_lift,has_monad_lift.monad_lift,(∘),(>>=),bind_assoc,id.def,run,cont_t.monad_lift]\nend\n\ninstance : monad_cont (cont_t r m) :=\n{ call_cc := λ α β f g, f ⟨λ x h, g x⟩ g }\n\ninstance : is_lawful_monad_cont (cont_t r m) :=\n{ call_cc_bind_right := by intros; ext; refl,\n call_cc_bind_left := by intros; ext; refl,\n call_cc_dummy := by intros; ext; refl }\n\ninstance (ε) [monad_except ε m] : monad_except ε (cont_t r m) :=\n{ throw := λ x e f, throw e,\n catch := λ α act h f, catch (act f) (λ e, h e f) }\n\ninstance : monad_run (λ α, (α → m r) → ulift.{u v} (m r)) (cont_t.{u v u} r m) :=\n{ run := λ α f x, ⟨ f x ⟩ }\n\nend cont_t\n\nvariables {m : Type u → Type v} [monad m]\n\ndef except_t.mk_label {α β ε} : label (except.{u u} ε α) m β → label α (except_t ε m) β\n| ⟨ f ⟩ := ⟨ λ a, monad_lift $ f (except.ok a) ⟩\n\nlemma except_t.goto_mk_label {α β ε : Type*} (x : label (except.{u u} ε α) m β) (i : α) :\n goto (except_t.mk_label x) i = ⟨ except.ok <$> goto x (except.ok i) ⟩ := by cases x; refl\n\ndef except_t.call_cc\n {ε} [monad_cont m] {α β : Type*} (f : label α (except_t ε m) β → except_t ε m α) :\n except_t ε m α :=\nexcept_t.mk (call_cc $ λ x : label _ m β, except_t.run $ f (except_t.mk_label x) : m (except ε α))\n\ninstance {ε} [monad_cont m] : monad_cont (except_t ε m) :=\n{ call_cc := λ α β, except_t.call_cc }\n\ninstance {ε} [monad_cont m] [is_lawful_monad_cont m] : is_lawful_monad_cont (except_t ε m) :=\n{ call_cc_bind_right := by { intros, simp [call_cc,except_t.call_cc,call_cc_bind_right], ext, dsimp,\n congr' with ⟨ ⟩; simp [except_t.bind_cont,@call_cc_dummy m _], },\n call_cc_bind_left := by { intros,\n simp [call_cc,except_t.call_cc,call_cc_bind_right,except_t.goto_mk_label,map_eq_bind_pure_comp,\n bind_assoc,@call_cc_bind_left m _], ext, refl },\n call_cc_dummy := by { intros, simp [call_cc,except_t.call_cc,@call_cc_dummy m _], ext, refl }, }\n\ndef option_t.mk_label {α β} : label (option.{u} α) m β → label α (option_t m) β\n| ⟨ f ⟩ := ⟨ λ a, monad_lift $ f (some a) ⟩\n\nlemma option_t.goto_mk_label {α β : Type*} (x : label (option.{u} α) m β) (i : α) :\n goto (option_t.mk_label x) i = ⟨ some <$> goto x (some i) ⟩ := by cases x; refl\n\ndef option_t.call_cc [monad_cont m] {α β : Type*} (f : label α (option_t m) β → option_t m α) :\n option_t m α :=\noption_t.mk (call_cc $ λ x : label _ m β, option_t.run $ f (option_t.mk_label x) : m (option α))\n\ninstance [monad_cont m] : monad_cont (option_t m) :=\n{ call_cc := λ α β, option_t.call_cc }\n\ninstance [monad_cont m] [is_lawful_monad_cont m] : is_lawful_monad_cont (option_t m) :=\n{ call_cc_bind_right := by { intros, simp [call_cc,option_t.call_cc,call_cc_bind_right], ext, dsimp,\n congr' with ⟨ ⟩; simp [option_t.bind_cont,@call_cc_dummy m _], },\n call_cc_bind_left := by { intros, simp [call_cc,option_t.call_cc,call_cc_bind_right,\n option_t.goto_mk_label,map_eq_bind_pure_comp,bind_assoc,@call_cc_bind_left m _], ext, refl },\n call_cc_dummy := by { intros, simp [call_cc,option_t.call_cc,@call_cc_dummy m _], ext, refl }, }\n\ndef writer_t.mk_label {α β ω} [has_one ω] : label (α × ω) m β → label α (writer_t ω m) β\n| ⟨ f ⟩ := ⟨ λ a, monad_lift $ f (a,1) ⟩\n\nlemma writer_t.goto_mk_label {α β ω : Type*} [has_one ω] (x : label (α × ω) m β) (i : α) :\n goto (writer_t.mk_label x) i = monad_lift (goto x (i,1)) := by cases x; refl\n\ndef writer_t.call_cc [monad_cont m] {α β ω : Type*} [has_one ω]\n (f : label α (writer_t ω m) β → writer_t ω m α) : writer_t ω m α :=\n⟨ call_cc (writer_t.run ∘ f ∘ writer_t.mk_label : label (α × ω) m β → m (α × ω)) ⟩\n\ninstance (ω) [monad m] [has_one ω] [monad_cont m] : monad_cont (writer_t ω m) :=\n{ call_cc := λ α β, writer_t.call_cc }\n\ndef state_t.mk_label {α β σ : Type u} : label (α × σ) m (β × σ) → label α (state_t σ m) β\n| ⟨ f ⟩ := ⟨ λ a, ⟨ λ s, f (a,s) ⟩ ⟩\n\nlemma state_t.goto_mk_label {α β σ : Type u} (x : label (α × σ) m (β × σ)) (i : α) :\n goto (state_t.mk_label x) i = ⟨ λ s, (goto x (i,s)) ⟩ := by cases x; refl\n\ndef state_t.call_cc {σ} [monad_cont m] {α β : Type*}\n (f : label α (state_t σ m) β → state_t σ m α) : state_t σ m α :=\n⟨ λ r, call_cc (λ f', (f $ state_t.mk_label f').run r) ⟩\n\ninstance {σ} [monad_cont m] : monad_cont (state_t σ m) :=\n{ call_cc := λ α β, state_t.call_cc }\n\ninstance {σ} [monad_cont m] [is_lawful_monad_cont m] : is_lawful_monad_cont (state_t σ m) :=\n{ call_cc_bind_right := by { intros,\n simp [call_cc,state_t.call_cc,call_cc_bind_right,(>>=),state_t.bind], ext, dsimp,\n congr' with ⟨x₀,x₁⟩, refl },\n call_cc_bind_left := by { intros, simp [call_cc,state_t.call_cc,call_cc_bind_left,(>>=),\n state_t.bind,state_t.goto_mk_label], ext, refl },\n call_cc_dummy := by { intros, simp [call_cc,state_t.call_cc,call_cc_bind_right,(>>=),\n state_t.bind,@call_cc_dummy m _], ext, refl }, }\n\ndef reader_t.mk_label {α β} (ρ) : label α m β → label α (reader_t ρ m) β\n| ⟨ f ⟩ := ⟨ monad_lift ∘ f ⟩\n\nlemma reader_t.goto_mk_label {α ρ β} (x : label α m β) (i : α) :\n goto (reader_t.mk_label ρ x) i = monad_lift (goto x i) := by cases x; refl\n\ndef reader_t.call_cc {ε} [monad_cont m] {α β : Type*}\n (f : label α (reader_t ε m) β → reader_t ε m α) : reader_t ε m α :=\n⟨ λ r, call_cc (λ f', (f $ reader_t.mk_label _ f').run r) ⟩\n\ninstance {ρ} [monad_cont m] : monad_cont (reader_t ρ m) :=\n{ call_cc := λ α β, reader_t.call_cc }\n\ninstance {ρ} [monad_cont m] [is_lawful_monad_cont m] : is_lawful_monad_cont (reader_t ρ m) :=\n{ call_cc_bind_right :=\n by { intros, simp [call_cc,reader_t.call_cc,call_cc_bind_right], ext, refl },\n call_cc_bind_left := by { intros, simp [call_cc,reader_t.call_cc,call_cc_bind_left,\n reader_t.goto_mk_label], ext, refl },\n call_cc_dummy := by { intros, simp [call_cc,reader_t.call_cc,@call_cc_dummy m _], ext, refl } }\n\n/-- reduce the equivalence between two continuation passing monads to the equivalence between\ntheir underlying monad -/\ndef cont_t.equiv {m₁ : Type u₀ → Type v₀} {m₂ : Type u₁ → Type v₁}\n {α₁ r₁ : Type u₀} {α₂ r₂ : Type u₁} (F : m₁ r₁ ≃ m₂ r₂) (G : α₁ ≃ α₂) :\n cont_t r₁ m₁ α₁ ≃ cont_t r₂ m₂ α₂ :=\n{ to_fun := λ f r, F $ f $ λ x, F.symm $ r $ G x,\n inv_fun := λ f r, F.symm $ f $ λ x, F $ r $ G.symm x,\n left_inv := λ f, by funext r; simp,\n right_inv := λ f, by funext r; simp }\n", "meta": {"author": "leanprover-community", "repo": "mathlib", "sha": "5e526d18cea33550268dcbbddcb822d5cde40654", "save_path": "github-repos/lean/leanprover-community-mathlib", "path": "github-repos/lean/leanprover-community-mathlib/mathlib-5e526d18cea33550268dcbbddcb822d5cde40654/src/control/monad/cont.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3073580168652638, "lm_q2_score": 0.02976009211734845, "lm_q1q2_score": 0.009147002894915789}} {"text": "import Lbar.ext_aux1\n\nnoncomputable theory\n\nuniverses v u u'\n\nopen opposite category_theory category_theory.limits category_theory.preadditive\nopen_locale nnreal zero_object\n\nvariables (r r' : ℝ≥0)\nvariables [fact (0 < r)] [fact (r < r')] [fact (r < 1)]\n\nsection\n\nopen bounded_homotopy_category\n\nvariables (BD : breen_deligne.data)\nvariables (κ κ₂ : ℝ≥0 → ℕ → ℝ≥0)\nvariables [∀ (c : ℝ≥0), BD.suitable (κ c)] [∀ n, fact (monotone (function.swap κ n))]\nvariables [∀ (c : ℝ≥0), BD.suitable (κ₂ c)] [∀ n, fact (monotone (function.swap κ₂ n))]\nvariables (M : ProFiltPseuNormGrpWithTinv₁.{u} r')\nvariables (V : SemiNormedGroup.{u})\n\nlemma QprimeFP_map (c₁ c₂ : ℝ≥0) (h : c₁ ⟶ c₂) :\n (QprimeFP r' BD κ M).map h = of'_hom ((QprimeFP_int r' BD κ _).map h) := rfl\n\ninstance aaahrg (X : Profinite) : semi_normed_group (locally_constant X V) :=\nlocally_constant.semi_normed_group\n\ndef V_T_inv (r : ℝ≥0) (V : SemiNormedGroup.{u}) [normed_with_aut r V] : V ⟶ V :=\nnormed_with_aut.T.{u}.inv\n\nvariables [fact (0 < r')] [fact (r' < 1)]\n\nsection\n\nvariables [complete_space V] [separated_space V]\n\nset_option pp.universes true\n\nlemma final_boss_aux₁ (X : Profinite) (x) :\n ((LCC_iso_Cond_of_top_ab_add_equiv.{u} X V).symm) x =\n (LCC_iso_Cond_of_top_ab_equiv X V).symm x := rfl\n\nlemma final_boss_aux₂ [normed_with_aut r V] (X : Profinite) (x : locally_constant X V) :\n((locally_constant.map_hom.{u u u} (V_T_inv r V)).completion)\n (uniform_space.completion.cpkg.{u}.coe x) =\n uniform_space.completion.map (locally_constant.map_hom (V_T_inv r V)) x := rfl\n\n-- should this be a global instance earlier in mathlib?\nlocal attribute [instance]\nabstract_completion.uniform_struct\n\nlemma final_boss_aux₃ [normed_with_aut r V] (X : Profinite) :\n continuous.{u u}\n (λ (x : C(X,V)),\n ((locally_constant.map_hom.{u u u} normed_with_aut.T.{u}.inv).completion)\n (((uniform_space.completion.cpkg.{u}.compare_equiv (locally_constant.pkg.{u} X ↥V)).symm) x)) :=\nbegin\n dsimp [abstract_completion.compare_equiv],\n refine (normed_group_hom.continuous _).comp _,\n refine ((locally_constant.pkg X V).uniform_continuous_compare _).continuous,\nend\n\nexample {β : Type*} [uniform_space β] (a : abstract_completion β) : uniform_space a.space :=\nby apply_instance\n\nlemma final_boss_aux₄ [normed_with_aut r V] (X : Profinite) :\n@continuous.{u u} _ _ _ (uniform_space.completion.cpkg.uniform_struct.to_topological_space)\n (λ (x : C(X,V)),\n ((locally_constant.pkg X V).compare\n uniform_space.completion.cpkg.{u}\n {to_fun := (V_T_inv r V) ∘ x.to_fun, continuous_to_fun :=\n (normed_with_aut.T.inv.continuous.comp x.2)})) :=\nbegin\n let e : C(X,V) → C(X,V) := λ e, ⟨(V_T_inv r V) ∘ e,\n (V_T_inv r V).continuous.comp e.2⟩,\n have he : continuous e := continuous_map.continuous_comp\n ((⟨(V_T_inv r V), (V_T_inv r V).continuous⟩ : C(V,V))),\n refine continuous.comp _ he,\n refine ((locally_constant.pkg X V).uniform_continuous_compare _).continuous,\nend\n\nlemma final_boss [normed_with_aut r V] (X : Profinite)\n (x : ((Condensed.of_top_ab.presheaf V).obj (op X))) :\n((locally_constant.map_hom (V_T_inv r V)).completion)\n (((LCC_iso_Cond_of_top_ab_add_equiv X V).symm) x) =\n ((LCC_iso_Cond_of_top_ab_add_equiv X V).symm)\n {to_fun := (normed_with_aut.T.inv) ∘ x.1, continuous_to_fun :=\n (normed_with_aut.T.inv.continuous.comp x.2)} :=\nbegin\n rw final_boss_aux₁,\n rw final_boss_aux₁,\n dsimp only [V_T_inv],\n dsimp only [LCC_iso_Cond_of_top_ab_equiv],\n change C(X,V) at x,\n apply abstract_completion.induction_on (locally_constant.pkg.{u} X ↥V) x,\n { apply is_closed_eq,\n { apply final_boss_aux₃ },\n { apply final_boss_aux₄ } },\n clear x,\n intros x,\n change ((locally_constant.map_hom.{u u u} normed_with_aut.T.{u}.inv).completion)\n ((locally_constant.pkg.{u} X ↥V).compare uniform_space.completion.cpkg.{u}\n ((locally_constant.pkg.{u} X ↥V).coe x)) = _,\n --dsimp [abstract_completion.compare_equiv],\n rw abstract_completion.compare_coe,\n erw final_boss_aux₂,\n erw uniform_space.completion.map_coe,\n let q : C(X,V) :=\n {to_fun := (normed_with_aut.T.{u}.inv) ∘ ((locally_constant.pkg.{u} X ↥V).coe x).to_fun,\n continuous_to_fun := _},\n swap,\n { apply continuous.comp,\n apply normed_group_hom.continuous,\n refine ((locally_constant.pkg.{u} X ↥V).coe x).2 },\n have hq : q = (locally_constant.pkg X V).coe\n ((locally_constant.map_hom.{u u u} (V_T_inv.{u} r V)) x),\n { ext, refl },\n\n change _ =\n ((locally_constant.pkg.{u} X ↥V).compare uniform_space.completion.cpkg) q,\n rw hq,\n\n rw abstract_completion.compare_coe,\n\n refl,\n\n apply normed_group_hom.uniform_continuous,\nend\n\nend\n\n@[reassoc]\nlemma massive_aux₁ (X Y : Profinite.{u}) (f : X ⟶ Y) :\n (preadditive_yoneda.{u+1 u+2}.obj V.to_Cond).map (freeCond.{u}.map f).op ≫\n (preadditive_yoneda_obj_obj_CondensedSet_to_Condensed_Ab.{u} V.to_Cond X).hom =\n (preadditive_yoneda_obj_obj_CondensedSet_to_Condensed_Ab.{u} V.to_Cond Y).hom ≫\n V.to_Cond.val.map f.op :=\nbegin\n erw preadditive_yoneda_obj_obj_CondensedSet_to_Condensed_Ab_natural',\n refl,\nend\n\nlemma add_equiv.mk_symm {A B : Type*} [add_comm_group A] [add_comm_group B]\n (f : A →+ B) (g : B →+ A) (h1 h2 h3) :\n (add_equiv.mk f g h1 h2 h3).symm =\n add_equiv.mk g f h2 h1 (by { intros x y, apply h1.injective, rw [h3, h2, h2, h2] }) := rfl\n\nlemma add_equiv.mk_symm_apply {A B : Type*} [add_comm_group A] [add_comm_group B]\n (f : A →+ B) (g : B →+ A) (h1 h2 h3) (x : B) :\n (add_equiv.mk f g h1 h2 h3).symm x = g x := rfl\n\nlemma locally_constant.comap_hom_map_hom {X Y V W : Type*}\n [topological_space X] [compact_space X]\n [topological_space Y] [compact_space Y]\n [semi_normed_group V] [semi_normed_group W]\n (f : X → Y) (hf : continuous f) (g : normed_group_hom V W) (φ : locally_constant Y V) :\n locally_constant.comap_hom f hf (locally_constant.map_hom g φ) =\n ((locally_constant.map_hom g) ∘ (locally_constant.comap_hom f hf)) φ :=\nbegin\n dsimp only [locally_constant.comap_hom_apply, locally_constant.map_hom_apply, function.comp],\n rw locally_constant.comap_map,\n exact hf\nend\n\ninstance (X : Profinite) :\n uniform_space.{u} (locally_constant.{u u} X V) :=\n@metric_space.to_uniform_space'.{u}\n (@locally_constant.{u u} (@coe_sort.{u+2 u+2} Profinite.{u} (Type u) Profinite.has_coe_to_sort.{u} X)\n (@coe_sort.{u+2 u+2} SemiNormedGroup.{u} (Type u) SemiNormedGroup.has_coe_to_sort.{u} V)\n (Top.topological_space.{u} X.to_CompHaus.to_Top))\n (@semi_normed_group.to_pseudo_metric_space.{u}\n (@locally_constant.{u u} (@coe_sort.{u+2 u+2} Profinite.{u} (Type u) Profinite.has_coe_to_sort.{u} X)\n (@coe_sort.{u+2 u+2} SemiNormedGroup.{u} (Type u) SemiNormedGroup.has_coe_to_sort.{u} V)\n (Top.topological_space.{u} X.to_CompHaus.to_Top))\n locally_constant.semi_normed_group)\n\ninstance (X : Profinite) : topological_space ↥(V.to_Cond.val.obj (op X)) :=\n@ulift.topological_space _ (continuous_map.compact_open.{u u})\n\nvariables [complete_space V] [separated_space V]\n\nlemma to_Cond_val_map_apply (X Y : Profinite.{u}) (f : X ⟶ Y) (x) :\n V.to_Cond.val.map f.op x = ⟨continuous_map.comp_right_continuous_map V f x.down⟩ :=\nrfl\n\nlemma to_Cond_val_map (X Y : Profinite.{u}) (f : X ⟶ Y) :\n ⇑(V.to_Cond.val.map f.op) =\n (λ x, ⟨continuous_map.comp_right_continuous_map V f x.down⟩ : ↥(V.to_Cond.val.obj (op Y)) → ↥(V.to_Cond.val.obj (op X))) :=\nby { ext x, rw to_Cond_val_map_apply }\n\nlemma massive_aux₂ (X Y : Profinite.{u}) (f : X ⟶ Y) (x : (V.to_Cond.val.obj (op.{u+2} Y))) :\n uniform_space.completion.map.{u u} (locally_constant.comap_hom.{u u u} f f.continuous)\n ((locally_constant.pkg.{u} Y ↥V).compare uniform_space.completion.cpkg.{u} x.down) =\n ((locally_constant.pkg.{u} X ↥V).compare uniform_space.completion.cpkg.{u})\n ((V.to_Cond.val.map f.op) x).down :=\nbegin\n cases x,\n apply abstract_completion.induction_on (locally_constant.pkg.{u} Y V) x,\n { apply is_closed_eq,\n { apply uniform_space.completion.continuous_map.comp,\n apply (abstract_completion.uniform_continuous_compare _ _).continuous },\n { apply (abstract_completion.uniform_continuous_compare _ _).continuous.comp,\n let φ : C(Y, V) → C(X, V) := _, change continuous φ,\n let ψ := V.to_Cond.val.map f.op, have hψ : φ = ulift.down ∘ ψ ∘ ulift.up := rfl,\n rw hψ, clear hψ,\n refine continuous_induced_dom.comp _,\n refine continuous.comp _ continuous_ulift_up,\n rw [to_Cond_val_map],\n refine continuous.comp _ _, { exact continuous_ulift_up },\n dsimp only [Condensed.of_top_ab, Condensed.of_top_ab.presheaf],\n exact (map_continuous (continuous_map.comp_right_continuous_map ↥V f)).comp continuous_induced_dom, } },\n { intro φ,\n dsimp only,\n simp only [abstract_completion.compare_coe, to_Cond_val_map_apply,\n uniform_space.completion.map],\n rw [abstract_completion.map_coe],\n swap,\n { letI : semi_normed_group (locally_constant ↥(X.to_CompHaus.to_Top) ↥V),\n { exact locally_constant.semi_normed_group },\n letI : semi_normed_group (locally_constant ↥(Y.to_CompHaus.to_Top) ↥V),\n { exact locally_constant.semi_normed_group },\n exact normed_group_hom.uniform_continuous _, },\n have : (continuous_map.comp_right_continuous_map ↥V f) ((locally_constant.pkg Y V).coe φ) =\n (locally_constant.pkg X V).coe _ := _,\n rw [this, abstract_completion.compare_coe],\n ext1,\n erw [locally_constant.coe_comap],\n refl,\n exact f.continuous },\nend\n\nlemma massive_aux (X Y : Profinite.{u}) (f : X ⟶ Y) :\n (preadditive_yoneda_obj_obj_CondensedSet_to_Condensed_Ab.{u} V.to_Cond Y).hom ≫\n Ab.ulift.{u+1 u}.map ((LCC_iso_Cond_of_top_ab.{u} V).inv.app (op.{u+2} Y)) ≫\n (ExtQprime_iso_aux_system_obj_aux'.{u} V Y).hom ≫\n (forget₂.{u+2 u+2 u+1 u+1 u+1} SemiNormedGroup.{u+1} Ab.{u+1}).map\n ((FreeAb.eval.{u+1 u+2} SemiNormedGroup.{u+1}ᵒᵖ).map\n ((CLC.{u+1 u} (SemiNormedGroup.ulift.{u+1 u}.obj V)).right_op.map_FreeAb.map\n ((FreeAb.of_functor.{u+1 u} Profinite.{u}).map f))).unop =\n (preadditive_yoneda.{u+1 u+2}.obj V.to_Cond).map\n ((FreeAb.eval.{u+1 u+2} (Condensed.{u u+1 u+2} Ab.{u+1})).map\n (freeCond.{u}.map_FreeAb.map ((FreeAb.of_functor.{u+1 u} Profinite.{u}).map f))).op ≫\n (preadditive_yoneda_obj_obj_CondensedSet_to_Condensed_Ab.{u} V.to_Cond X).hom ≫\n Ab.ulift.{u+1 u}.map ((LCC_iso_Cond_of_top_ab.{u} V).inv.app (op.{u+2} X)) ≫\n (ExtQprime_iso_aux_system_obj_aux'.{u} V X).hom :=\nbegin\n dsimp only [functor.map_FreeAb, FreeAb.of_functor, FreeAb.eval],\n simp only [free_abelian_group.map_of_apply, free_abelian_group.lift.of, id],\n dsimp only [functor.right_op_map, quiver.hom.op_unop, quiver.hom.unop_op],\n rw massive_aux₁_assoc, congr' 1,\n ext1 x, simp only [comp_apply],\n dsimp only [ExtQprime_iso_aux_system_obj_aux', LCC_iso_Cond_of_top_ab,\n LCC_iso_Cond_of_top_ab_add_equiv, LCC_iso_Cond_of_top_ab_equiv, CLC, LC, functor.comp_map,\n Condensed.of_top_ab],\n simp only [add_equiv.to_fun_eq_coe, normed_group_hom.completion_coe_to_fun,\n add_equiv.to_AddCommGroup_iso_hom, add_equiv.coe_to_add_monoid_hom, add_equiv.trans_apply,\n add_equiv.ulift_apply, equiv.to_fun_as_coe, equiv.ulift_apply_2,\n Ab.ulift_map_apply_down, add_equiv.coe_mk, nat_iso.of_components.inv_app,\n add_equiv.to_AddCommGroup_iso, add_equiv.mk_symm,\n SemiNormedGroup.forget₂_Ab_map, normed_group_hom.coe_to_add_monoid_hom],\n let F := SemiNormedGroup.Completion.{u+1}.map ((SemiNormedGroup.LocallyConstant.{u+1 u}.obj\n (SemiNormedGroup.ulift.{u+1 u}.obj V)).map f.op),\n let g := _,\n let Z := _,\n change F ((uniform_space.completion.map g) Z) = _,\n change (F ∘ uniform_space.completion.map g) Z = _,\n erw [uniform_space.completion.map_comp],\n rotate,\n { apply normed_group_hom.uniform_continuous, },\n { apply normed_group_hom.uniform_continuous, },\n conv_lhs\n { dsimp only [function.comp, normed_group_hom.coe_to_add_monoid_hom, g,\n SemiNormedGroup.LocallyConstant_obj_map], },\n simp only [locally_constant.comap_hom_map_hom],\n letI : uniform_space.{u} (locally_constant.{u u} ↥(unop.{u+2} (op.{u+2} X)) ↥V) := _,\n erw [← uniform_space.completion.map_comp],\n rotate,\n { apply normed_group_hom.uniform_continuous, },\n { apply normed_group_hom.uniform_continuous, },\n dsimp only [function.comp, Z, quiver.hom.unop_op],\n congr' 1, clear Z g F,\n exact massive_aux₂ V X Y f x,\nend\n\nlemma massive (X Y : FreeAb Profinite.{u}) (f : X ⟶ Y) :\n (((preadditive_yoneda_obj_obj_CondensedSet_to_Condensed_Ab.{u} V.to_Cond Y.as).hom ≫\n (Condensed_Ab_to_presheaf.{u}.map (Condensed_LCC_iso_of_top_ab.{u} V).inv).app (op.{u+2} Y.as) ≫\n (ExtQprime_iso_aux_system_obj_aux'.{u} V Y.as).hom) ≫\n (𝟙 _)) ≫\n (forget₂.{u+2 u+2 u+1 u+1 u+1} SemiNormedGroup.{u+1} Ab.{u+1}).map\n (((CLC.{u+1 u} (SemiNormedGroup.ulift.{u+1 u}.obj V)).right_op.map_FreeAb ⋙\n FreeAb.eval.{u+1 u+2} SemiNormedGroup.{u+1}ᵒᵖ).map f).unop =\n (preadditive_yoneda.{u+1 u+2}.obj V.to_Cond).map\n ((freeCond.{u}.map_FreeAb ⋙ FreeAb.eval.{u+1 u+2} (Condensed.{u u+1 u+2} Ab.{u+1})).map f).op ≫\n ((preadditive_yoneda_obj_obj_CondensedSet_to_Condensed_Ab.{u} V.to_Cond X.as).hom ≫\n (Condensed_Ab_to_presheaf.{u}.map (Condensed_LCC_iso_of_top_ab.{u} V).inv).app (op.{u+2} X.as) ≫\n (ExtQprime_iso_aux_system_obj_aux'.{u} V X.as).hom) ≫ 𝟙 _ :=\nbegin\n simp only [Condensed_Ab_to_presheaf_map, category.assoc, category.comp_id, functor.comp_map],\n dsimp only [Condensed_LCC_iso_of_top_ab, Sheaf.iso.mk_inv_val,\n iso_whisker_right_inv, whisker_right_app],\n apply free_abelian_group.induction_on f; clear f,\n { simp only [functor.map_zero, unop_zero, comp_zero, op_zero, zero_comp], },\n { apply massive_aux },\n { intros f hf,\n simp only [functor.map_neg, unop_neg, op_neg, comp_neg, neg_comp, hf], },\n { intros f g hf hg,\n simp only [functor.map_add, unop_add, op_add, comp_add, add_comp, hf, hg], },\nend\n\nlemma hom_complex_QprimeFP_nat_iso_aux_system_naturality_in_c (c₁ c₂) (h : c₁ ⟶ c₂) :\n (hom_complex_QprimeFP_nat_iso_aux_system r' BD κ M V c₂).hom ≫\n (category_theory.functor.map _ h.op) =\n (category_theory.functor.map _\n begin\n refine homological_complex.op_functor.map (quiver.hom.op _),\n refine category_theory.functor.map _ h,\n end) ≫ (hom_complex_QprimeFP_nat_iso_aux_system r' BD κ M V c₁).hom :=\nbegin\n ext n : 2,\n have aux : ∀ (n : ℕ), (monotone.{0 0} (function.swap.{1 1 1} κ n)),\n { intro n, exact fact.out _ },\n haveI : fact (κ c₁ n ≤ κ c₂ n) := ⟨aux n h.le⟩,\n have := massive V\n (breen_deligne.FPsystem.X.{u} r' BD ⟨M⟩ κ c₁ n)\n (breen_deligne.FPsystem.X.{u} r' BD ⟨M⟩ κ c₂ n)\n ((breen_deligne.FP2.res.{u} r' _ _ _).app ⟨M⟩),\n exact this\nend\n\nlemma hom_complex_QprimeFP_nat_iso_aux_system_naturality_in_κ (c : (ℝ≥0))\n [∀ (c : ℝ≥0) (n : ℕ), fact (κ₂ c n ≤ κ c n)] :\n (hom_complex_QprimeFP_nat_iso_aux_system r' BD κ M V c).hom ≫\n (whisker_right (aux_system.res _ _ _ _ _ _) _).app _ =\n begin\n refine category_theory.functor.map _ _,\n refine homological_complex.op_functor.map (quiver.hom.op _),\n refine (QprimeFP_nat.ι BD κ₂ κ M).app _,\n end ≫ (hom_complex_QprimeFP_nat_iso_aux_system r' BD κ₂ M V c).hom :=\nbegin\n ext n : 2,\n have := massive V\n (breen_deligne.FPsystem.X.{u} r' BD ⟨M⟩ κ₂ c n)\n (breen_deligne.FPsystem.X.{u} r' BD ⟨M⟩ κ c n)\n ((breen_deligne.FP2.res.{u} r' _ _ _).app ⟨M⟩),\n exact this\nend\n\nlemma hom_complex_QprimeFP_nat_iso_aux_system_naturality_in_Tinv (c : ℝ≥0)\n [∀ (c : ℝ≥0) (n : ℕ), fact (κ₂ c n ≤ r' * κ c n)] :\n (hom_complex_QprimeFP_nat_iso_aux_system r' BD κ M V c).hom ≫\n (whisker_right\n (aux_system.Tinv _ _ _ _ _ _) _).app _ =\n begin\n refine category_theory.functor.map _ _,\n refine homological_complex.op_functor.map (quiver.hom.op _),\n refine (QprimeFP_nat.Tinv BD κ₂ κ M).app _,\n end\n ≫ (hom_complex_QprimeFP_nat_iso_aux_system r' BD κ₂ M V c).hom :=\nbegin\n ext n : 2,\n have := massive V\n (breen_deligne.FPsystem.X.{u} r' BD ⟨M⟩ κ₂ c n)\n (breen_deligne.FPsystem.X.{u} r' BD ⟨M⟩ κ c n)\n (((breen_deligne.FPsystem.Tinv.{u} r' BD ⟨M⟩ κ₂ κ).app c).f n),\n exact this,\nend\n\n\n\ndef to_Cond_T_inv (r : ℝ≥0) (V : SemiNormedGroup.{u}) [normed_with_aut r V] : V.to_Cond ⟶ V.to_Cond :=\n(Condensed.of_top_ab_map.{u} (normed_group_hom.to_add_monoid_hom.{u u} normed_with_aut.T.{u}.inv)\n (normed_group_hom.continuous _))\n\nlemma uniform_space.completion.map_comp'\n {α β γ : Type*} [uniform_space α] [uniform_space β] [uniform_space γ]\n {g : β → γ} {f : α → β}\n (hg : uniform_continuous g) (hf : uniform_continuous f) (x) :\n uniform_space.completion.map g (uniform_space.completion.map f x) =\n uniform_space.completion.map (g ∘ f) x :=\nbegin\n rw [← uniform_space.completion.map_comp hg hf],\nend\n\nlemma hom_complex_QprimeFP_nat_iso_aux_system_naturality_in_T_inv_aux_helper\n (r : ℝ≥0) (V : SemiNormedGroup.{u}) [normed_with_aut r V] [complete_space V] [separated_space V]\n (X : Profinite.{u}) :\n (ExtQprime_iso_aux_system_obj_aux' V X).hom ≫\n category_theory.functor.map _\n (SemiNormedGroup.Completion.map\n (nat_trans.app\n (SemiNormedGroup.LocallyConstant.map\n (category_theory.functor.map _ $ V_T_inv _ _)) _)) =\n Ab.ulift.map\n (category_theory.functor.map _ $\n category_theory.functor.map _ $\n nat_trans.app\n (SemiNormedGroup.LocallyConstant.map $ V_T_inv _ _) _) ≫\n (ExtQprime_iso_aux_system_obj_aux' V X).hom\n :=\nbegin\n ext1 ⟨f⟩,\n simp only [comp_apply],\n dsimp only [ExtQprime_iso_aux_system_obj_aux', add_equiv.to_AddCommGroup_iso,\n add_equiv.coe_to_add_monoid_hom, add_equiv.trans_apply],\n simp only [add_equiv.to_fun_eq_coe, SemiNormedGroup.LocallyConstant_map_app, SemiNormedGroup.Completion_map,\n normed_group_hom.completion_coe_to_fun, add_equiv.ulift_apply, equiv.to_fun_as_coe, equiv.ulift_apply_2,\n add_equiv.coe_mk, Ab.ulift_map_apply_down, SemiNormedGroup.forget₂_Ab_map,\n normed_group_hom.coe_to_add_monoid_hom],\n rw uniform_space.completion.map_comp',\n rotate,\n { apply normed_group_hom.uniform_continuous },\n { apply normed_group_hom.uniform_continuous },\n rw uniform_space.completion.map_comp',\n rotate,\n { apply normed_group_hom.uniform_continuous },\n { apply normed_group_hom.uniform_continuous },\n refl\nend\n\n\n\nlemma another_aux_lemma [normed_with_aut r V] (X : Profinite) :\n (preadditive_yoneda_obj_obj_CondensedSet_to_Condensed_Ab V.to_Cond X).hom\n ≫ (Condensed_Ab_to_presheaf.map_iso (Condensed_LCC_iso_of_top_ab V)).inv.app (op X)\n ≫\n begin\n refine nat_trans.app _ _,\n refine Condensed_Ab_to_presheaf.map _,\n refine Sheaf.hom.mk _,\n dsimp [Condensed_LCC],\n refine whisker_right _ _,\n refine whisker_right _ _,\n refine SemiNormedGroup.LCC.map _,\n exact V_T_inv r V,\n end =\n (preadditive_yoneda.map\n (to_Cond_T_inv r V)).app _ ≫\n (preadditive_yoneda_obj_obj_CondensedSet_to_Condensed_Ab V.to_Cond X).hom ≫\n (Condensed_Ab_to_presheaf.map_iso (Condensed_LCC_iso_of_top_ab V)).inv.app _ :=\nbegin\n have := preadditive_yoneda_obj_obj_CondensedSet_to_Condensed_Ab_natural\n (to_Cond_T_inv r V) X,\n erw ← reassoc_of this,\n congr' 1,\n dsimp only [Condensed_Ab_to_presheaf, functor.map_iso_inv, nat_iso.app_inv,\n Sheaf_to_presheaf_map, id, whisker_right_app, SemiNormedGroup.LCC,\n curry, uncurry, curry_obj, functor.comp_map],\n simp only [category_theory.functor.map_id, category.comp_id],\n rw ← nat_trans.comp_app,\n rw ← Sheaf.hom.comp_val, -- how to make those commute?\n ext ⟨x⟩,\n dsimp only [Condensed_LCC_iso_of_top_ab, Sheaf.iso.mk, iso_whisker_right, to_Cond_T_inv,\n Ab.ulift],\n simp only [comp_apply],\n dsimp [Condensed.of_top_ab_map],\n simp only [comp_apply],\n dsimp [LCC_iso_Cond_of_top_ab, forget₂, has_forget₂.forget₂],\n rw nat_iso.of_components.inv_app,\n apply final_boss,\nend\n\nlemma hom_complex_QprimeFP_nat_iso_aux_system_naturality_in_T_inv_aux (c : ℝ≥0)\n [normed_with_aut r V] (n : ℕ) (t) :\n((forget₂.{u+2 u+2 u+1 u+1 u+1} SemiNormedGroup.{u+1} Ab.{u+1}).map\n (((aux_system.T_inv.{u u+1} r r' BD ⟨M⟩ (SemiNormedGroup.ulift.{u+1 u}.obj V) κ).app\n (op.{1} c)).f n))\n ((((ExtQprime_iso_aux_system_obj_aux.{u} V).hom.app\n (((breen_deligne.FPsystem.{u} r' BD ⟨M⟩ κ).obj c).X n)).unop) t) =\n (((ExtQprime_iso_aux_system_obj_aux.{u} V).hom.app\n (((breen_deligne.FPsystem.{u} r' BD ⟨M⟩ κ).obj c).X n)).unop)\n (t ≫ to_Cond_T_inv.{u} r V) :=\nbegin\n /-\n Note: This should reduce to some calcuation with the sheafification adjunction,\n as well as something about completion/ulift compatibiity.\n If we can reduce this to such statements, we will be in pretty good shape.\n -/\n /- This code block is pretty slow.\n dsimp [ExtQprime_iso_aux_system_obj_aux, ExtQprime_iso_aux_system_obj_aux'],\n simp only [comp_apply],\n dsimp [forget₂, has_forget₂.forget₂, aux_system.T_inv,\n Condensed_LCC_iso_of_top_ab, LCC_iso_Cond_of_top_ab],\n rw nat_iso.of_components.inv_app,\n dsimp only [unop_op],\n -/\n dsimp only [forget₂, has_forget₂.forget₂, ExtQprime_iso_aux_system_obj_aux,\n nat_iso.of_components.hom_app, id, iso.op, iso.trans_hom, iso.symm,\n nat_iso.app_inv, aux_system.T_inv, quiver.hom.op_unop, quiver.hom.unop_op,\n homological_complex.unop],\n simp only [comp_apply],\n let X : Profinite := (((breen_deligne.FPsystem r' BD ⟨M⟩ κ).obj c).X n).as,\n have := preadditive_yoneda_obj_obj_CondensedSet_to_Condensed_Ab_natural\n (to_Cond_T_inv r V) X,\n apply_fun (λ e, e t) at this,\n erw this, clear this,\n simp only [comp_apply],\n dsimp only [SemiNormedGroup.LocallyConstant],\n have := hom_complex_QprimeFP_nat_iso_aux_system_naturality_in_T_inv_aux_helper r V X,\n let s := ((Condensed_Ab_to_presheaf.map_iso (Condensed_LCC_iso_of_top_ab V)).inv.app (op X))\n (((preadditive_yoneda_obj_obj_CondensedSet_to_Condensed_Ab V.to_Cond X).hom)\n (t)),\n apply_fun (λ e, e s) at this,\n erw this, clear this,\n simp only [comp_apply],\n congr' 1, dsimp only [s],\n simp only [← comp_apply],\n congr' 1,\n simp only [category.assoc],\n erw ← another_aux_lemma r V X,\n congr' 2,\n ext1 ⟨x⟩, dsimp only [Ab.ulift, Condensed_Ab_to_presheaf, whisker_right_app,\n Sheaf_to_presheaf],\n ext1,\n dsimp,\n congr' 2,\n dsimp only [SemiNormedGroup.LCC, curry, curry_obj, functor.comp_map, uncurry],\n simp only [category_theory.functor.map_id, category.comp_id],\n refl,\nend\n\n\nlemma hom_complex_QprimeFP_nat_iso_aux_system_naturality_in_T_inv (c : ℝ≥0)\n [normed_with_aut r V] :\n(hom_complex_QprimeFP_nat_iso_aux_system.{u} r' BD κ M V c).hom ≫\n ((forget₂.{u+2 u+2 u+1 u+1 u+1} SemiNormedGroup.{u+1} Ab.{u+1}).map_homological_complex\n (complex_shape.up.{0} ℕ)).map (nat_trans.app\n ((aux_system.T_inv.{u u+1} r r' BD ⟨M⟩ (SemiNormedGroup.ulift.{u+1 u}.obj V) κ)) _) =\n begin\n let e := preadditive_yoneda.map (to_Cond_T_inv r V),\n let e' := nat_trans.map_homological_complex e (complex_shape.down ℕ).symm,\n let Q := ((QprimeFP_nat r' BD κ M).obj c).op,\n exact e'.app Q,\n end ≫\n (hom_complex_QprimeFP_nat_iso_aux_system.{u} r' BD κ M V (c)).hom :=\nbegin\n ext n : 2, ext1 t,\n dsimp [hom_complex_QprimeFP_nat_iso_aux_system],\n simp only [comp_apply],\n dsimp [nat_iso.map_homological_complex, forget₂_unop],\n erw id_apply, erw id_apply,\n erw [functor.map_homological_complex_map_f],\n apply hom_complex_QprimeFP_nat_iso_aux_system_naturality_in_T_inv_aux,\nend\n\nnamespace ExtQprime_iso_aux_system_obj_naturality_setup\n\n/-\nlemma aux₁ (c₁ c₂ : ℝ≥0) (h : c₁ ⟶ c₂) :\nhomological_complex.unop_functor.{u+2 u+1 0}.map\n (((preadditive_yoneda_obj.{u+1 u+2} V.to_Cond ⋙\n forget₂.{u+2 u+2 u+1 u+1 u+1} (Module.{u+1 u+1} (End.{u+1 u+2} V.to_Cond))\n AddCommGroup.{u+1}).right_op.map_homological_complex\n (complex_shape.up.{0} ℤ)).map\n ((homological_complex.embed.{0 0 u+2 u+1} complex_shape.embedding.nat_down_int_up).map\n ((QprimeFP_nat.{u} r' BD κ M).map h))).op ≫\n homological_complex.unop_functor.{u+2 u+1 0}.map\n ((map_homological_complex_embed.{u+2 u+2 u+1 u+1}\n (preadditive_yoneda_obj.{u+1 u+2} V.to_Cond ⋙\n forget₂.{u+2 u+2 u+1 u+1 u+1} (Module.{u+1 u+1} (End.{u+1 u+2} V.to_Cond))\n AddCommGroup.{u+1}).right_op).inv.app\n ((QprimeFP_nat.{u} r' BD κ M).obj c₁)).op ≫\n embed_unop.{u+2 u+1}.hom.app\n (op.{u+3}\n (((preadditive_yoneda_obj.{u+1 u+2} V.to_Cond ⋙\n forget₂.{u+2 u+2 u+1 u+1 u+1} (Module.{u+1 u+1} (End.{u+1 u+2} V.to_Cond))\n Ab.{u+1}).right_op.map_homological_complex\n (complex_shape.down.{0} ℕ)).obj\n ((QprimeFP_nat.{u} r' BD κ M).obj c₁))) =\n begin\n dsimp,\n let e := (QprimeFP_nat r' BD κ M).map h,\n let e₁ := ((preadditive_yoneda_obj.{u+1 u+2} V.to_Cond ⋙\n forget₂.{u+2 u+2 u+1 u+1 u+1} (Module.{u+1 u+1} (End.{u+1 u+2} V.to_Cond))\n Ab.{u+1}).right_op.map_homological_complex\n (complex_shape.down.{0} ℕ)).map e,\n let e₂ := homological_complex.unop_functor.map e₁.op,\n refine _ ≫\n (homological_complex.embed.{0 0 u+2 u+1} complex_shape.embedding.nat_up_int_down).map\n e₂,\n refine homological_complex.unop_functor.{u+2 u+1 0}.map\n ((map_homological_complex_embed.{u+2 u+2 u+1 u+1}\n (preadditive_yoneda_obj.{u+1 u+2} V.to_Cond ⋙\n forget₂.{u+2 u+2 u+1 u+1 u+1} (Module.{u+1 u+1} (End.{u+1 u+2} V.to_Cond))\n AddCommGroup.{u+1}).right_op).inv.app\n ((QprimeFP_nat.{u} r' BD κ M).obj c₂)).op ≫\n embed_unop.{u+2 u+1}.hom.app\n (op.{u+3}\n (((preadditive_yoneda_obj.{u+1 u+2} V.to_Cond ⋙\n forget₂.{u+2 u+2 u+1 u+1 u+1} (Module.{u+1 u+1} (End.{u+1 u+2} V.to_Cond))\n Ab.{u+1}).right_op.map_homological_complex\n (complex_shape.down.{0} ℕ)).obj\n ((QprimeFP_nat.{u} r' BD κ M).obj c₂)))\n end := admit\n\ndef F : ℝ≥0 ⥤\n (homological_complex.{u+1 u+2 0} AddCommGroup.{u+1} (complex_shape.down.{0} ℕ).symm)ᵒᵖ :=\nQprimeFP_nat.{u} r' BD κ M ⋙\n (preadditive_yoneda_obj.{u+1 u+2} V.to_Cond ⋙\n forget₂.{u+2 u+2 u+1 u+1 u+1} (Module.{u+1 u+1} (End.{u+1 u+2} V.to_Cond))\n AddCommGroup.{u+1}).right_op.map_homological_complex\n (complex_shape.down.{0} ℕ) ⋙ homological_complex.unop_functor.right_op\n\n@[reassoc]\nlemma naturality_helper {c₁ c₂ : ℝ≥0} (h : c₁ ⟶ c₂) (n : ℕ) (w1 w2) :\n (homological_complex.homology_embed_nat_iso.{0 0 u+2 u+1} Ab.{u+1} complex_shape.embedding.nat_up_int_down\n nat_up_int_down_c_iff n (-↑n) w1).hom.app\n (((preadditive_yoneda.{u+1 u+2}.obj\n V.to_Cond).right_op.map_homological_complex (complex_shape.down.{0} ℕ)).obj\n ((QprimeFP_nat.{u} r' BD κ M).obj c₂)).unop ≫\n (homology_functor _ _ _).map\n (homological_complex.map_unop _ _ $\n category_theory.functor.map _ $ category_theory.functor.map _ h) =\n category_theory.functor.map _\n (homological_complex.map_unop _ _ $\n category_theory.functor.map _ $ category_theory.functor.map _ h) ≫\n (homological_complex.homology_embed_nat_iso.{0 0 u+2 u+1} Ab.{u+1} complex_shape.embedding.nat_up_int_down\n nat_up_int_down_c_iff n (-↑n) w2).hom.app\n (((preadditive_yoneda.{u+1 u+2}.obj\n V.to_Cond).right_op.map_homological_complex (complex_shape.down.{0} ℕ)).obj\n ((QprimeFP_nat.{u} r' BD κ M).obj c₁)).unop :=\nadmit\n-/\n\nlemma aux₁ (c₁ c₂ : ℝ≥0) (h : c₁ ⟶ c₂) (n : ℕ) :\n (homology_functor.{u+1 u+2 0} Ab.{u+1} (complex_shape.up.{0} ℕ) n).map\n (hom_complex_QprimeFP_nat_iso_aux_system.{u} r' BD κ M V c₂).hom ≫\n (homology_functor.{u+1 u+2 0} Ab.{u+1} (complex_shape.up.{0} ℕ) n).map\n ((aux_system.{u u+1} r' BD ⟨M⟩ (SemiNormedGroup.ulift.{u+1 u}.obj V) κ).to_Ab.map h.op) =\n (homology_functor _ _ _).map\n (category_theory.functor.map _\n (homological_complex.op_functor.map ((QprimeFP_nat r' BD κ M).map h).op)) ≫\n (homology_functor.{u+1 u+2 0} Ab.{u+1} (complex_shape.up.{0} ℕ) n).map\n (hom_complex_QprimeFP_nat_iso_aux_system.{u} r' BD κ M V c₁).hom :=\nbegin\n rw [← functor.map_comp, ← functor.map_comp],\n congr' 1,\n erw ← hom_complex_QprimeFP_nat_iso_aux_system_naturality_in_c,\nend\n\nlemma aux₂ (c₁ c₂ : ℝ≥0) (h : c₁ ⟶ c₂) (n : ℕ) :\n (homological_complex.homology_embed_nat_iso.{0 0 u+2 u+1} Ab.{u+1}\n complex_shape.embedding.nat_up_int_down nat_up_int_down_c_iff n (-↑n) (by { cases n; refl})).hom.app\n (hom_complex_nat.{u} ((QprimeFP_nat.{u} r' BD κ M).obj c₂) V.to_Cond) ≫\n (homology_functor.{u+1 u+2 0} Ab.{u+1} (complex_shape.up.{0} ℕ) n).map\n (((preadditive_yoneda.{u+1 u+2}.obj V.to_Cond).map_homological_complex\n (complex_shape.down.{0} ℕ).symm).map (homological_complex.op_functor.{u+2 u+1 0}.map\n ((QprimeFP_nat.{u} r' BD κ M).map h).op)) =\n (homological_complex.embed.{0 0 u+2 u+1} complex_shape.embedding.nat_up_int_down ⋙\n homology_functor.{u+1 u+2 0} Ab.{u+1} (complex_shape.down.{0} ℤ) (-↑n)).map\n (category_theory.functor.map _\n (homological_complex.op_functor.map ((QprimeFP_nat r' BD κ M).map h).op)) ≫\n (homological_complex.homology_embed_nat_iso.{0 0 u+2 u+1} Ab.{u+1}\n complex_shape.embedding.nat_up_int_down nat_up_int_down_c_iff n (-↑n) (by { cases n; refl})).hom.app\n (hom_complex_nat.{u} ((QprimeFP_nat.{u} r' BD κ M).obj c₁) V.to_Cond) :=\nbegin\n erw nat_trans.naturality,\nend\n\n\nlemma aux₃ (c₁ c₂ : ℝ≥0) (h : c₁ ⟶ c₂) (n : ℕ) :\n (homology_functor.{u+1 u+2 0} Ab.{u+1} (complex_shape.up.{0} ℤ).symm (-↑n)).map\n (embed_hom_complex_nat_iso.{u} ((QprimeFP_nat.{u} r' BD κ M).obj c₂) V.to_Cond).hom ≫\n (homological_complex.embed.{0 0 u+2 u+1} complex_shape.embedding.nat_up_int_down ⋙\n homology_functor.{u+1 u+2 0} Ab.{u+1} (complex_shape.down.{0} ℤ) (-↑n)).map\n (((preadditive_yoneda.{u+1 u+2}.obj V.to_Cond).map_homological_complex\n (complex_shape.down.{0} ℕ).symm).map (homological_complex.op_functor.{u+2 u+1 0}.map\n ((QprimeFP_nat.{u} r' BD κ M).map h).op))\n =\n ((homology_functor.{u+1 u+2 0} AddCommGroup.{u+1}\n (complex_shape.up.{0} ℤ).symm (-↑n)).op.map\n (homological_complex.unop_functor.{u+2 u+1 0}.right_op.map\n (((preadditive_yoneda.{u+1 u+2}.obj V.to_Cond).right_op.map_homological_complex\n (complex_shape.up.{0} ℤ)).map ((QprimeFP_int.{u} r' BD κ M).map h)))).unop ≫\n (homology_functor.{u+1 u+2 0} Ab.{u+1} (complex_shape.up.{0} ℤ).symm (-↑n)).map\n (embed_hom_complex_nat_iso.{u} ((QprimeFP_nat.{u} r' BD κ M).obj c₁) V.to_Cond).hom\n :=\nbegin\n dsimp only [functor.op_map, functor.comp_map],\n erw [← functor.map_comp],\n erw [← functor.map_comp],\n congr' 1,\n ext ((_ | k) | k ) : 2,\n { refine (category.id_comp _).trans (category.comp_id _).symm },\n { apply is_zero.eq_of_tgt,\n exact is_zero_zero _ },\n { refine (category.id_comp _).trans (category.comp_id _).symm },\nend\n/-\nlemma naturality_helper {c₂ : ℝ≥0} (n : ℕ) :\n (homology_functor.{u+1 u+2 0} Ab.{u+1} (complex_shape.up.{0} ℤ).symm (-↑n)).map\n (embed_hom_complex_nat_iso.{u} ((QprimeFP_nat.{u} r' BD κ M).obj c₂) V.to_Cond).hom ≫\n (homological_complex.homology_embed_nat_iso.{0 0 u+2 u+1} Ab.{u+1}\n complex_shape.embedding.nat_up_int_down nat_up_int_down_c_iff n (-↑n) (by { cases n; refl})).hom.app\n (hom_complex_nat.{u} ((QprimeFP_nat.{u} r' BD κ M).obj c₂) V.to_Cond) =\n _\n-/\n\nend ExtQprime_iso_aux_system_obj_naturality_setup\n\nlemma QprimeFP_acyclic (c) (k i : ℤ) (hi : 0 < i) :\n is_zero (((Ext' i).obj (op (((QprimeFP_int.{u} r' BD κ M).obj c).X k))).obj V.to_Cond) :=\nbegin\n rcases k with ((_|k)|k),\n { apply free_acyclic, exact hi },\n { rw [← functor.flip_obj_obj], refine functor.map_is_zero _ _, refine (is_zero_zero _).op, },\n { apply free_acyclic, exact hi },\nend\n\nlemma ExtQprime_iso_aux_system_obj_natrality (c₁ c₂ : ℝ≥0) (h : c₁ ⟶ c₂) (n : ℕ) :\n (ExtQprime_iso_aux_system_obj r' BD κ M V c₂ n).hom ≫\n (homology_functor _ _ _).map\n ((system_of_complexes.to_Ab _).map h.op) =\n ((Ext n).map ((QprimeFP r' BD κ _).map h).op).app _ ≫\n (ExtQprime_iso_aux_system_obj r' BD κ M V c₁ n).hom :=\nbegin\n dsimp only [ExtQprime_iso_aux_system_obj,\n iso.trans_hom, id, functor.map_iso_hom],\n haveI : ((homotopy_category.quotient.{u+1 u+2 0}\n (Condensed.{u u+1 u+2} Ab.{u+1}) (complex_shape.up.{0} ℤ)).obj\n ((QprimeFP_int.{u} r' BD κ M).obj c₁)).is_bounded_above :=\n chain_complex.is_bounded_above _,\n haveI : ((homotopy_category.quotient.{u+1 u+2 0}\n (Condensed.{u u+1 u+2} Ab.{u+1}) (complex_shape.up.{0} ℤ)).obj\n ((QprimeFP_int.{u} r' BD κ M).obj c₂)).is_bounded_above :=\n chain_complex.is_bounded_above _,\n have := Ext_compute_with_acyclic_naturality\n ((QprimeFP_int.{u} r' BD κ M).obj c₁)\n ((QprimeFP_int.{u} r' BD κ M).obj c₂)\n V.to_Cond _ _\n ((QprimeFP_int.{u} r' BD κ M).map h) n,\n rotate,\n { intros k i hi, apply QprimeFP_acyclic, exact hi },\n { intros k i hi, apply QprimeFP_acyclic, exact hi },\n dsimp only [functor.comp_map] at this,\n erw reassoc_of this, clear this,\n simp only [category.assoc, nat_iso.app_hom],\n congr' 1,\n rw ExtQprime_iso_aux_system_obj_naturality_setup.aux₁ r' BD κ M V c₁ c₂ h n,\n simp only [← category.assoc], congr' 1,\n simp only [category.assoc],\n rw ExtQprime_iso_aux_system_obj_naturality_setup.aux₂ r' BD κ M V c₁ c₂ h n,\n simp only [← category.assoc], congr' 1,\n\n exact ExtQprime_iso_aux_system_obj_naturality_setup.aux₃ r' BD κ M V c₁ c₂ h n,\n\n --- OLD PROOF FROM HERE\n --have := ExtQprime_iso_aux_system_obj_naturality_setup.naturality_helper r' BD κ\n -- M V h n _ _,\n --simp only [category.assoc, functor.map_comp],\n --slice_rhs 3 4\n --{ erw ← this },\n\n /-\n dsimp only [QprimeFP_int],\n congr' 1,\n dsimp only [nat_iso.app_hom],\n simp only [functor.map_comp, functor.comp_map, nat_trans.naturality,\n nat_trans.naturality_assoc],\n dsimp only [functor.op_map, quiver.hom.unop_op, functor.right_op_map],\n simp only [← functor.map_comp, ← functor.map_comp_assoc, category.assoc],\n dsimp [-homology_functor_map],\n rw ExtQprime_iso_aux_system_obj_naturality_setup.aux₁,\n dsimp [-homology_functor_map],\n simp only [functor.map_comp, functor.map_comp_assoc,\n category.assoc, nat_trans.naturality_assoc],\n congr' 2,\n dsimp [-homology_functor_map],\n dsimp only [← functor.comp_map, ← functor.comp_obj],\n --erw nat_trans.naturality_assoc,\n --refine congr_arg2 _ _ (congr_arg2 _ rfl _),\n\n --congr' 1,\n --refl,\n admit\n\n -/\nend\n\ndef ExtQprime_iso_aux_system (n : ℕ) :\n (QprimeFP r' BD κ M).op ⋙ (Ext n).flip.obj ((single _ 0).obj V.to_Cond) ≅\n aux_system r' BD ⟨M⟩ (SemiNormedGroup.ulift.{u+1}.obj V) κ ⋙\n (forget₂ _ Ab).map_homological_complex _ ⋙ homology_functor _ _ n :=\nnat_iso.of_components (λ c, ExtQprime_iso_aux_system_obj r' BD κ M V (unop c) n)\nbegin\n intros c₁ c₂ h,\n dsimp [-homology_functor_map],\n rw ← ExtQprime_iso_aux_system_obj_natrality,\n refl,\nend\n\n/-- The `Tinv` map induced by `M` -/\ndef ExtQprime.Tinv\n [∀ c n, fact (κ₂ c n ≤ κ c n)] [∀ c n, fact (κ₂ c n ≤ r' * κ c n)]\n (n : ℤ) :\n (QprimeFP r' BD κ M).op ⋙ (Ext n).flip.obj ((single _ 0).obj V.to_Cond) ⟶\n (QprimeFP r' BD κ₂ M).op ⋙ (Ext n).flip.obj ((single _ 0).obj V.to_Cond) :=\nwhisker_right (nat_trans.op $ QprimeFP.Tinv BD _ _ M) _\n\n/-- The `T_inv` map induced by `V` -/\ndef ExtQprime.T_inv [normed_with_aut r V]\n [∀ c n, fact (κ₂ c n ≤ κ c n)] [∀ c n, fact (κ₂ c n ≤ r' * κ c n)]\n (n : ℤ) :\n (QprimeFP r' BD κ M).op ⋙ (Ext n).flip.obj ((single _ 0).obj V.to_Cond) ⟶\n (QprimeFP r' BD κ₂ M).op ⋙ (Ext n).flip.obj ((single _ 0).obj V.to_Cond) :=\nwhisker_right (nat_trans.op $ QprimeFP.ι BD _ _ M) _ ≫ whisker_left _ ((Ext n).flip.map $ (single _ _).map $\n (Condensed.of_top_ab_map (normed_with_aut.T.inv).to_add_monoid_hom\n (normed_group_hom.continuous _)))\n\ndef ExtQprime.Tinv2 [normed_with_aut r V]\n [∀ c n, fact (κ₂ c n ≤ κ c n)] [∀ c n, fact (κ₂ c n ≤ r' * κ c n)]\n (n : ℤ) :\n (QprimeFP r' BD κ M).op ⋙ (Ext n).flip.obj ((single _ 0).obj V.to_Cond) ⟶\n (QprimeFP r' BD κ₂ M).op ⋙ (Ext n).flip.obj ((single _ 0).obj V.to_Cond) :=\nExtQprime.Tinv r' BD κ κ₂ M V n - ExtQprime.T_inv r r' BD κ κ₂ M V n\n\nnamespace ExtQprime_iso_aux_system_comm_Tinv_setup\n\nvariables (c : (ℝ≥0)ᵒᵖ) (n : ℕ)\n [∀ (c : ℝ≥0) (n : ℕ), fact (κ₂ c n ≤ r' * κ c n)]\n\nlemma aux₁ :\n(homology_functor.{u+1 u+2 0} Ab.{u+1} (complex_shape.up.{0} ℕ) n).map\n (hom_complex_QprimeFP_nat_iso_aux_system.{u} r' BD κ M V (unop.{1} c)).hom ≫\n ((forget₂.{u+2 u+2 u+1 u+1 u+1} SemiNormedGroup.{u+1} Ab.{u+1}).map_homological_complex\n (complex_shape.up.{0} ℕ) ⋙\n homology_functor.{u+1 u+2 0} Ab.{u+1} (complex_shape.up.{0} ℕ) n).map\n ((aux_system.Tinv.{u u+1} r' BD ⟨M⟩ (SemiNormedGroup.ulift.{u+1 u}.obj V) κ₂ κ).app c) =\n (homology_functor _ _ _).map\n (category_theory.functor.map _\n (homological_complex.op_functor.map (quiver.hom.op $\n (QprimeFP_nat.Tinv BD κ₂ κ M).app _))) ≫\n (homology_functor.{u+1 u+2 0} Ab.{u+1} (complex_shape.up.{0} ℕ) n).map\n (hom_complex_QprimeFP_nat_iso_aux_system.{u} r' BD κ₂ M V (unop.{1} c)).hom :=\nbegin\n simp only [← functor.map_comp, functor.comp_map], congr' 1,\n apply hom_complex_QprimeFP_nat_iso_aux_system_naturality_in_Tinv,\nend\n\nlemma aux₂ :\n(homology_functor.{u+1 u+2 0} Ab.{u+1} (complex_shape.up.{0} ℤ).symm (-↑n)).map\n (embed_hom_complex_nat_iso.{u} ((QprimeFP_nat.{u} r' BD κ M).obj (unop.{1} c)) V.to_Cond).hom ≫\n (homological_complex.embed.{0 0 u+2 u+1} complex_shape.embedding.nat_up_int_down ⋙\n homology_functor.{u+1 u+2 0} Ab.{u+1} (complex_shape.down.{0} ℤ) (-↑n)).map\n (((preadditive_yoneda.{u+1 u+2}.obj V.to_Cond).map_homological_complex (complex_shape.down.{0} ℕ).symm).map\n (homological_complex.op_functor.{u+2 u+1 0}.map ((QprimeFP_nat.Tinv.{u} BD κ₂ κ M).app (unop.{1} c)).op)) =\n (((preadditive_yoneda.{u+1 u+2}.obj V.to_Cond).right_op.map_homological_complex (complex_shape.up.{0} ℤ) ⋙\n homological_complex.unop_functor.{u+2 u+1 0}.right_op ⋙\n (homology_functor.{u+1 u+2 0} AddCommGroup.{u+1} (complex_shape.up.{0} ℤ).symm (-↑n)).op).map\n ((QprimeFP_int.Tinv.{u} BD κ₂ κ M).app (unop.{1} c))).unop ≫\n (homology_functor.{u+1 u+2 0} Ab.{u+1} (complex_shape.up.{0} ℤ).symm (-↑n)).map\n (embed_hom_complex_nat_iso.{u} ((QprimeFP_nat.{u} r' BD κ₂ M).obj (unop.{1} c)) V.to_Cond).hom :=\nbegin\n dsimp only [functor.op_map, functor.comp_map],\n erw [← functor.map_comp],\n erw [← functor.map_comp],\n congr' 1,\n ext ((_ | k) | k ) : 2,\n { refine (category.id_comp _).trans (category.comp_id _).symm },\n { apply is_zero.eq_of_tgt,\n exact is_zero_zero _ },\n { refine (category.id_comp _).trans (category.comp_id _).symm },\nend\n\nend ExtQprime_iso_aux_system_comm_Tinv_setup\n\nlemma ExtQprime_iso_aux_system_comm_Tinv\n [∀ c n, fact (κ₂ c n ≤ κ c n)] [∀ c n, fact (κ₂ c n ≤ r' * κ c n)] (n : ℕ) :\n (ExtQprime_iso_aux_system r' BD κ M V n).hom ≫\n whisker_right (aux_system.Tinv.{u} r' BD ⟨M⟩ (SemiNormedGroup.ulift.{u+1}.obj V) κ₂ κ)\n ((forget₂ _ _).map_homological_complex _ ⋙ homology_functor Ab.{u+1} (complex_shape.up ℕ) n) =\n ExtQprime.Tinv r' BD κ κ₂ M V n ≫\n (ExtQprime_iso_aux_system r' BD κ₂ M V n).hom :=\nbegin\n ext c : 2,\n dsimp only [ExtQprime_iso_aux_system_obj,\n ExtQprime_iso_aux_system,\n iso.trans_hom, id, functor.map_iso_hom, nat_iso.of_components.hom_app,\n nat_trans.comp_app],\n haveI : ((homotopy_category.quotient.{u+1 u+2 0} (Condensed.{u u+1 u+2} Ab.{u+1}) (complex_shape.up.{0} ℤ)).obj\n ((QprimeFP_int.{u} r' BD κ M).obj (unop.{1} c))).is_bounded_above :=\n chain_complex.is_bounded_above _,\n haveI : ((homotopy_category.quotient.{u+1 u+2 0} (Condensed.{u u+1 u+2} Ab.{u+1}) (complex_shape.up.{0} ℤ)).obj\n ((QprimeFP_int.{u} r' BD κ₂ M).obj (unop.{1} c))).is_bounded_above :=\n chain_complex.is_bounded_above _,\n have := Ext_compute_with_acyclic_naturality\n ((QprimeFP_int.{u} r' BD κ₂ M).obj c.unop)\n ((QprimeFP_int.{u} r' BD κ M).obj c.unop)\n V.to_Cond _ _\n ((QprimeFP_int.Tinv BD κ₂ κ M).app _) n,\n rotate,\n { intros k i hi, apply QprimeFP_acyclic, exact hi },\n { intros k i hi, apply QprimeFP_acyclic, exact hi },\n erw reassoc_of this, clear this, simp only [category.assoc], congr' 1,\n dsimp only [whisker_right_app],\n rw ExtQprime_iso_aux_system_comm_Tinv_setup.aux₁ r' BD κ κ₂ M V c n,\n simp only [← category.assoc], congr' 1, simp only [category.assoc],\n erw ← nat_trans.naturality,\n simp only [← category.assoc], congr' 1,\n exact ExtQprime_iso_aux_system_comm_Tinv_setup.aux₂ r' BD κ κ₂ M V c n,\nend\n\n\n-- lemma ExtQprime_iso_aux_system_comm_T_inv [normed_with_aut r V] (n : ℕ) (c : ℝ≥0ᵒᵖ) :\n-- (ExtQprime_iso_aux_system_obj.{u} r' BD κ₂ M V (unop.{1} c) n).hom ≫\n-- ((forget₂.{u+2 u+2 u+1 u+1 u+1} SemiNormedGroup.{u+1} Ab.{u+1}).map_homological_complex (complex_shape.up.{0} ℕ) ⋙\n-- homology_functor.{u+1 u+2 0} Ab.{u+1} (complex_shape.up.{0} ℕ) n).map\n-- ((aux_system.res.{u u+1} r' BD ⟨M⟩ (SemiNormedGroup.ulift.{u+1 u}.obj V) κ₂ κ).app c) =\n-- ((Ext.{u+1 u+2} ↑n).flip.map\n-- ((single.{u+1 u+2} (Condensed.{u u+1 u+2} Ab.{u+1}) 0).map\n-- (Condensed.of_top_ab_map.{u} (normed_group_hom.to_add_monoid_hom.{u u} normed_with_aut.T.{u}.inv) _))).app\n-- ((QprimeFP.{u} r' BD κ₂ M).op.obj c) ≫\n-- (ExtQprime_iso_aux_system_obj.{u} r' BD κ₂ M V (unop.{1} c) n).hom :=\n-- by admit\n\ndef homological_complex.map_unop {A M : Type*} [category A] [abelian A]\n {c : complex_shape M} (C₁ C₂ : homological_complex Aᵒᵖ c) (f : C₁ ⟶ C₂) :\n C₂.unop ⟶ C₁.unop :=\nhomological_complex.unop_functor.map f.op\n\nnamespace ExtQprime_iso_aux_system_comm_setup\n\ninclude r\nvariables [normed_with_aut r V] [∀ (c : ℝ≥0) (n : ℕ), fact (κ₂ c n ≤ κ c n)]\n\ndef hom_complex_map_T_inv (c : (ℝ≥0)ᵒᵖ) :\n hom_complex_nat.{u} ((QprimeFP_nat.{u} r' BD κ M).obj (unop.{1} c)) V.to_Cond ⟶\n hom_complex_nat.{u} ((QprimeFP_nat.{u} r' BD κ₂ M).obj (unop.{1} c)) V.to_Cond :=\n begin\n refine nat_trans.app _ _,\n refine nat_trans.map_homological_complex _ _,\n refine preadditive_yoneda.map _,\n refine Condensed.of_top_ab_map.{u} (normed_group_hom.to_add_monoid_hom.{u u}\n normed_with_aut.T.{u}.inv) (normed_group_hom.continuous _)\n end ≫\n (category_theory.functor.map _\n (homological_complex.op_functor.map (quiver.hom.op $\n (QprimeFP_nat.ι BD κ₂ κ M).app _)))\n\nomit r\n\nlemma embed_hom_complex_nat_iso₀ (c : (ℝ≥0)ᵒᵖ) : (embed_hom_complex_nat_iso.{u} ((QprimeFP_nat.{u} r' BD κ₂ M).obj (unop.{1} c)) V.to_Cond).hom.f (int.of_nat 0) = 𝟙 _ := rfl\n\nlemma embed_hom_complex_nat_iso_neg (n : ℕ) (c : (ℝ≥0)ᵒᵖ) : (embed_hom_complex_nat_iso.{u} ((QprimeFP_nat.{u} r' BD κ₂ M).obj (unop.{1} c)) V.to_Cond).hom.f (-[1+ n]) = 𝟙 _ := rfl\n\n\nlemma add_equiv.to_AddCommGroup_iso_apply (A B : AddCommGroup.{u})\n (e : A ≃+ B) (a : A) : e.to_AddCommGroup_iso.hom a = e a := rfl\n\nlemma preadditive_yoneda_obj_obj_CondensedSet_to_Condensed_Ab_apply (M) (X) (t) :\n (preadditive_yoneda_obj_obj_CondensedSet_to_Condensed_Ab M X).hom t =\n yoneda'_equiv _ _ (Condensed_Ab_CondensedSet_adjunction.hom_equiv X.to_Condensed M t).val := rfl\n\ninclude r\n\nlemma aux₁ (c : (ℝ≥0)ᵒᵖ):\n(hom_complex_QprimeFP_nat_iso_aux_system.{u} r' BD κ M V (unop.{1} c)).hom ≫\n ((forget₂.{u+2 u+2 u+1 u+1 u+1} SemiNormedGroup.{u+1} Ab.{u+1}).map_homological_complex\n (complex_shape.up.{0} ℕ)).map ((aux_system.T_inv.{u u+1} r r' BD\n ⟨M⟩ (SemiNormedGroup.ulift.{u+1 u}.obj V) κ).app c ≫\n (aux_system.res.{u u+1} r' BD ⟨M⟩ (SemiNormedGroup.ulift.{u+1 u}.obj V) κ₂ κ).app c) =\n hom_complex_map_T_inv _ _ _ _ _ _ _ _ ≫\n (hom_complex_QprimeFP_nat_iso_aux_system.{u} r' BD κ₂ M V (unop.{1} c)).hom :=\nbegin\n --simp only [← category_theory.functor.map_comp, functor.comp_map], congr' 1,\n dsimp only [hom_complex_map_T_inv], simp only [category.assoc],\n rw ← hom_complex_QprimeFP_nat_iso_aux_system_naturality_in_κ r' BD κ κ₂ M V c.unop,\n simp only [functor.map_comp, ← category.assoc], congr' 1,\n apply hom_complex_QprimeFP_nat_iso_aux_system_naturality_in_T_inv\n\n /- -- IGNORE THIS\n ext k t : 3,\n dsimp [hom_complex_nat] at t,\n dsimp only [hom_complex_QprimeFP_nat_iso_aux_system, aux_system.T_inv,\n aux_system.res, hom_complex_nat, functor.map_iso, iso.trans_hom,\n homological_complex.unop_functor, homological_complex.comp_f,\n nat_iso.map_homological_complex, nat_iso.app_hom, iso.op_hom, quiver.hom.unop_op,\n nat_trans.map_homological_complex_app_f, ExtQprime_iso_aux_system_obj_aux,\n nat_iso.of_components.hom_app, id, iso.symm_hom, nat_iso.app_inv,\n whisker_right_app, nat_trans.op, functor.comp_map],\n simp only [category_theory.functor.map_comp],\n dsimp only [homological_complex.comp_f, functor.map_homological_complex, functor.op_obj,\n functor.unop, forget₂_unop, nat_iso.of_components.hom_app,\n homological_complex.hom.iso_of_components, iso.refl],\n simp only [category.assoc, category.id_comp],\n erw category.id_comp,\n dsimp only [functor.op, quiver.hom.unop_op],\n erw category.comp_id,\n repeat { rw [comp_apply] },\n -/ -- UUUUGGGHHH\n\nend\n\nlemma aux₂ (c : (ℝ≥0)ᵒᵖ) :\n((((preadditive_yoneda.{u+1 u+2}.obj (Condensed.of_top_ab.{u} ↥V)).right_op.map_homological_complex\n (complex_shape.up.{0} ℤ)).obj\n ((QprimeFP_int.{u} r' BD κ M).obj (unop.{1} c))).map_unop\n (((preadditive_yoneda.{u+1 u+2}.obj (Condensed.of_top_ab.{u} ↥V)).right_op.map_homological_complex\n (complex_shape.up.{0} ℤ)).obj\n ((QprimeFP_int.{u} r' BD κ M).obj (unop.{1} c)))\n ((nat_trans.map_homological_complex.{u+1 u+2 0 u+2 u+1}\n (nat_trans.right_op.{u+1 u+1 u+2 u+2} (preadditive_yoneda.{u+1 u+2}.map\n (Condensed.of_top_ab_map.{u} (normed_group_hom.to_add_monoid_hom.{u u}\n normed_with_aut.T.{u}.inv) (normed_group_hom.continuous _))))\n (complex_shape.up.{0} ℤ)).app\n ((QprimeFP_int.{u} r' BD κ M).obj (unop.{1} c))) ≫\n (homological_complex.unop_functor.{u+2 u+1 0}.right_op.map\n (((preadditive_yoneda.{u+1 u+2}.obj V.to_Cond).right_op.map_homological_complex (complex_shape.up.{0} ℤ)).map\n ((QprimeFP_int.ι.{u} BD κ₂ κ M).app (unop.{1} c)))).unop) ≫\n (embed_hom_complex_nat_iso.{u} ((QprimeFP_nat.{u} r' BD κ₂ M).obj (unop.{1} c)) V.to_Cond).hom =\n (embed_hom_complex_nat_iso.{u} ((QprimeFP_nat.{u} r' BD κ M).obj (unop.{1} c)) V.to_Cond).hom ≫\n category_theory.functor.map _\n (hom_complex_map_T_inv _ _ _ _ _ _ _ _) :=\nbegin\n ext ((_ | k) | k ) : 2,\n { dsimp only [functor.comp],\n simp only [functor.right_op_map, quiver.hom.unop_op, category.assoc, homological_complex.comp_f,\n homological_complex.unop_functor_map_f, functor.map_homological_complex_map_f],\n rw embed_hom_complex_nat_iso₀,\n rw embed_hom_complex_nat_iso₀,\n ext, refl },\n { apply is_zero.eq_of_tgt,\n exact is_zero_zero _ },\n { dsimp only [functor.comp],\n simp only [functor.right_op_map, quiver.hom.unop_op, category.assoc, homological_complex.comp_f,\n homological_complex.unop_functor_map_f, functor.map_homological_complex_map_f],\n rw embed_hom_complex_nat_iso_neg,\n rw embed_hom_complex_nat_iso_neg,\n ext, refl },\nend\n\nend ExtQprime_iso_aux_system_comm_setup\n\nsection naturality_snd_var\n\nvariables {A : Type*} [category A] [abelian A] [enough_projectives A]\n (X : cochain_complex A ℤ)\n [((homotopy_category.quotient A (complex_shape.up.{0} ℤ)).obj X).is_bounded_above]\n {B₁ B₂ : A} (f : B₁ ⟶ B₂) -- (h₁) (h₂) (i)\n\n@[reassoc]\nlemma Ext_compute_with_acyclic_aux₁_naturality_snd_var (i)\n (e : (0 : ℤ) - i = -i) :\n (Ext_compute_with_acyclic_aux₁ X B₁ i).hom ≫\n begin\n refine nat_trans.app _ _,\n refine preadditive_yoneda.map _,\n refine category_theory.functor.map _ f,\n end =\n category_theory.functor.map _\n (category_theory.functor.map _ f) ≫\n (Ext_compute_with_acyclic_aux₁ X B₂ i).hom :=\nbegin\n ext t,\n simp only [comp_apply],\n dsimp [Ext_compute_with_acyclic_aux₁, Ext],\n simp only [category.assoc],\n generalize_proofs h1 h2,\n let φ₁ := λ j, (single _ j).obj B₁,\n let φ₂ := λ j, (single _ j).obj B₂,\n change t ≫ _ ≫ eq_to_hom (congr_arg φ₁ e) ≫ _ =\n _ ≫ _ ≫ _ ≫ eq_to_hom (congr_arg φ₂ e),\n induction e,\n dsimp, simp only [category.id_comp, category.comp_id],\n erw ← nat_trans.naturality,\n refl,\nend\n\n@[reassoc]\nlemma Ext_compute_with_acyclic_aux₂_naturality_snd_var (i) :\n (Ext_compute_with_acyclic_aux₂ X B₁ i).hom ≫\n (homology_functor _ _ _).map\n begin\n refine nat_trans.app _ _,\n refine nat_trans.map_homological_complex _ _,\n exact preadditive_yoneda.map f,\n end =\n nat_trans.app\n (preadditive_yoneda.map $ category_theory.functor.map _ f) _ ≫\n (Ext_compute_with_acyclic_aux₂ X B₂ i).hom :=\nbegin\n dsimp only [Ext_compute_with_acyclic_aux₂, unop_op],\n have := hom_single_iso_naturality_snd_var_good (of' X).replace (-i) f,\n erw ← this,\nend\n\ninclude f\nlemma Ext_compute_with_acyclic_aux₃_naturality_snd_var (i) :\n (homology_functor _ _ _).map\n begin\n refine homological_complex.map_unop _ _ _,\n refine nat_trans.app _ _,\n refine nat_trans.map_homological_complex _ _,\n refine nat_trans.right_op _,\n exact preadditive_yoneda.map f,\n end ≫ Ext_compute_with_acyclic_aux₃ X B₂ i =\n Ext_compute_with_acyclic_aux₃ X B₁ i ≫\n (homology_functor _ _ _).map\n begin\n refine nat_trans.app _ _,\n refine nat_trans.map_homological_complex _ _,\n exact preadditive_yoneda.map f,\n end :=\nbegin\n dsimp only [Ext_compute_with_acyclic_aux₃],\n erw ← (homology_functor.{u_2 u_2+1 0} AddCommGroup.{u_2}\n (complex_shape.up.{0} ℤ).symm (-i)).map_comp,\n erw ← (homology_functor.{u_2 u_2+1 0} AddCommGroup.{u_2}\n (complex_shape.up.{0} ℤ).symm (-i)).map_comp,\n congr' 1,\n ext t x,\n dsimp [Ext_compute_with_acyclic_HomB],\n simp only [comp_apply],\n dsimp [nat_trans.map_homological_complex, functor.right_op,\n homological_complex.map_unop],\n simp only [category.assoc],\nend\n\nlemma Ext_compute_with_acyclic_naturality_snd_var\n (h₁) (h₂) (i) :\n (Ext_compute_with_acyclic X B₁ h₁ i).hom ≫\n (homology_functor _ _ _).map\n (begin\n refine homological_complex.map_unop _ _ _,\n refine nat_trans.app _ _,\n refine nat_trans.map_homological_complex _ _,\n exact (preadditive_yoneda.map f).right_op,\n end) =\n category_theory.functor.map _\n (category_theory.functor.map _ f) ≫ (Ext_compute_with_acyclic X B₂ h₂ i).hom :=\nbegin\n dsimp [Ext_compute_with_acyclic, - homology_functor_map],\n simp only [category.assoc],\n rw ← Ext_compute_with_acyclic_aux₁_naturality_snd_var_assoc,\n rw ← Ext_compute_with_acyclic_aux₂_naturality_snd_var_assoc,\n simp only [category.assoc], congr' 2,\n rw [is_iso.eq_comp_inv, category.assoc, is_iso.inv_comp_eq],\n apply Ext_compute_with_acyclic_aux₃_naturality_snd_var,\n simp,\nend\n\nend naturality_snd_var\n\nlemma ExtQprime_iso_aux_system_comm [normed_with_aut r V]\n [∀ c n, fact (κ₂ c n ≤ κ c n)] [∀ c n, fact (κ₂ c n ≤ r' * κ c n)] (n : ℕ) :\n (ExtQprime_iso_aux_system r' BD κ M V n).hom ≫\n whisker_right (aux_system.Tinv2.{u} r r' BD ⟨M⟩ (SemiNormedGroup.ulift.{u+1}.obj V) κ₂ κ)\n ((forget₂ _ _).map_homological_complex _ ⋙ homology_functor Ab.{u+1} (complex_shape.up ℕ) n) =\n ExtQprime.Tinv2 r r' BD κ κ₂ M V n ≫\n (ExtQprime_iso_aux_system r' BD κ₂ M V n).hom :=\nbegin\n ext c : 2, dsimp only [aux_system.Tinv2, ExtQprime.Tinv2, nat_trans.comp_app, whisker_right_app],\n simp only [sub_comp, nat_trans.app_sub, functor.map_sub, comp_sub],\n refine congr_arg2 _ _ _,\n { rw [← nat_trans.comp_app, ← ExtQprime_iso_aux_system_comm_Tinv], refl },\n\n dsimp only [ExtQprime_iso_aux_system_obj,\n ExtQprime_iso_aux_system,\n iso.trans_hom, id, functor.map_iso_hom, nat_iso.of_components.hom_app,\n nat_trans.comp_app],\n\n haveI : ((homotopy_category.quotient.{u+1 u+2 0} (Condensed.{u u+1 u+2} Ab.{u+1})\n (complex_shape.up.{0} ℤ)).obj\n ((QprimeFP_int.{u} r' BD κ M).obj (unop.{1} c))).is_bounded_above :=\n chain_complex.is_bounded_above _,\n haveI : ((homotopy_category.quotient.{u+1 u+2 0} (Condensed.{u u+1 u+2} Ab.{u+1})\n (complex_shape.up.{0} ℤ)).obj\n ((QprimeFP_int.{u} r' BD κ₂ M).obj (unop.{1} c))).is_bounded_above :=\n chain_complex.is_bounded_above _,\n have := Ext_compute_with_acyclic_naturality\n ((QprimeFP_int.{u} r' BD κ₂ M).obj c.unop)\n ((QprimeFP_int.{u} r' BD κ M).obj c.unop)\n V.to_Cond _ _\n ((QprimeFP_int.ι BD κ₂ κ M).app _) n,\n rotate,\n { intros k i hi, apply QprimeFP_acyclic, exact hi },\n { intros k i hi, apply QprimeFP_acyclic, exact hi },\n\n simp only [category.assoc], dsimp only [ExtQprime.T_inv, nat_trans.comp_app,\n whisker_right_app, whisker_left_app, functor.flip],\n let η := (Ext.{u+1 u+2} ↑n).map ((nat_trans.op.{0 u+1 0 u+2} (QprimeFP.ι.{u} BD κ₂ κ M)).app c),\n\n slice_rhs 1 2 { erw ← η.naturality },\n slice_rhs 2 3 { erw this },\n simp only [category.assoc], clear this η,\n\n let t : Condensed.of_top_ab V ⟶ _ :=\n Condensed.of_top_ab_map.{u} (normed_group_hom.to_add_monoid_hom.{u u}\n normed_with_aut.T.{u}.inv) (normed_group_hom.continuous _),\n have := Ext_compute_with_acyclic_naturality_snd_var\n ((QprimeFP_int r' BD κ M).obj c.unop) t _ _ n,\n rotate,\n { intros k i hi, apply QprimeFP_acyclic, exact hi },\n { intros k i hi, apply QprimeFP_acyclic, exact hi },\n erw ← reassoc_of this, clear this, congr' 1,\n simp only [functor.comp_map, category_theory.functor.map_comp,\n functor.op_map, quiver.hom.unop_op],\n slice_rhs 1 2 { rw ← category_theory.functor.map_comp },\n slice_lhs 4 5 { rw ← category_theory.functor.map_comp },\n simp only [category.assoc,\n ← category_theory.functor.map_comp, ← functor.map_comp_assoc],\n\n rw ExtQprime_iso_aux_system_comm_setup.aux₁ r r' BD κ κ₂ M V c,\n slice_lhs 2 4\n { simp only [category_theory.functor.map_comp] },\n\n simp only [← category.assoc], congr' 1,\n\n rw ExtQprime_iso_aux_system_comm_setup.aux₂ r r' BD κ κ₂ M V c,\n simp only [category_theory.functor.map_comp, category.assoc],\n congr' 1,\n\n rw [nat_iso.app_hom, ← nat_trans.naturality],\n congr' 1,\n\n -- have := Ext_compute_with_acyclic_naturality, <-- we need naturality in the other variable?!\n\n --simp only [category.assoc],\n --erw reassoc_of this,\n --clear this, simp only [category.assoc], congr' 1,\n\n /-\n rw [nat_trans.comp_app, functor.map_comp, ExtQprime.T_inv,\n nat_trans.comp_app, whisker_right_app, whisker_left_app, category.assoc],\n dsimp only [ExtQprime_iso_aux_system, nat_iso.of_components.hom_app, aux_system,\n aux_system.res, functor.comp_map],\n -/\nend\n\nlemma ExtQprime_iso_aux_system_comm' [normed_with_aut r V]\n [∀ c n, fact (κ₂ c n ≤ κ c n)] [∀ c n, fact (κ₂ c n ≤ r' * κ c n)] (n : ℕ) :\n whisker_right (aux_system.Tinv2.{u} r r' BD ⟨M⟩ (SemiNormedGroup.ulift.{u+1}.obj V) κ₂ κ)\n ((forget₂ _ _).map_homological_complex _ ⋙ homology_functor Ab.{u+1} (complex_shape.up ℕ) n) ≫\n (ExtQprime_iso_aux_system r' BD κ₂ M V n).inv =\n (ExtQprime_iso_aux_system r' BD κ M V n).inv ≫\n ExtQprime.Tinv2 r r' BD κ κ₂ M V n :=\nbegin\n rw [iso.comp_inv_eq, category.assoc, iso.eq_inv_comp],\n apply ExtQprime_iso_aux_system_comm\nend\n\nend\n\nsection\n\ndef _root_.category_theory.functor.map_commsq\n {C D : Type*} [category C] [abelian C] [category D] [abelian D] (F : C ⥤ D) {X Y Z W : C}\n {f₁ : X ⟶ Y} {g₁ : X ⟶ Z} {g₂ : Y ⟶ W} {f₂ : Z ⟶ W} (sq : commsq f₁ g₁ g₂ f₂) :\n commsq (F.map f₁) (F.map g₁) (F.map g₂) (F.map f₂) :=\ncommsq.of_eq $ by rw [← F.map_comp, sq.w, F.map_comp]\n\nend\n\nsection\n\nvariables {r'}\nvariables (BD : breen_deligne.package)\nvariables (κ κ₂ : ℝ≥0 → ℕ → ℝ≥0)\nvariables [∀ (c : ℝ≥0), BD.data.suitable (κ c)] [∀ n, fact (monotone (function.swap κ n))]\nvariables [∀ (c : ℝ≥0), BD.data.suitable (κ₂ c)] [∀ n, fact (monotone (function.swap κ₂ n))]\nvariables (M : ProFiltPseuNormGrpWithTinv₁.{u} r')\nvariables (V : SemiNormedGroup.{u}) [complete_space V] [separated_space V]\n\nopen bounded_homotopy_category\n\n-- move me\ninstance eval'_is_bounded_above :\n ((homotopy_category.quotient (Condensed Ab) (complex_shape.up ℤ)).obj\n ((BD.eval' freeCond').obj M.to_Condensed)).is_bounded_above :=\nby { delta breen_deligne.package.eval', refine ⟨⟨1, _⟩⟩, apply chain_complex.bounded_by_one }\n\nvariables (ι : ulift.{u+1} ℕ → ℝ≥0) (hι : monotone ι)\n\ndef Ext_Tinv2\n {𝓐 : Type*} [category 𝓐] [abelian 𝓐] [enough_projectives 𝓐]\n {A B V : bounded_homotopy_category 𝓐}\n (Tinv : A ⟶ B) (ι : A ⟶ B) (T_inv : V ⟶ V) (i : ℤ) :\n ((Ext i).obj (op B)).obj V ⟶ ((Ext i).obj (op A)).obj V :=\n(((Ext i).map Tinv.op).app V - (((Ext i).map ι.op).app V ≫ ((Ext i).obj _).map T_inv))\n\nopen category_theory.preadditive\n\ndef Ext_Tinv2_commsq\n {𝓐 : Type*} [category 𝓐] [abelian 𝓐] [enough_projectives 𝓐]\n {A₁ B₁ A₂ B₂ V : bounded_homotopy_category 𝓐}\n (Tinv₁ : A₁ ⟶ B₁) (ι₁ : A₁ ⟶ B₁)\n (Tinv₂ : A₂ ⟶ B₂) (ι₂ : A₂ ⟶ B₂)\n (f : A₁ ⟶ A₂) (g : B₁ ⟶ B₂) (sqT : f ≫ Tinv₂ = Tinv₁ ≫ g) (sqι : f ≫ ι₂ = ι₁ ≫ g)\n (T_inv : V ⟶ V) (i : ℤ) :\n commsq\n (((Ext i).map g.op).app V)\n (Ext_Tinv2 Tinv₂ ι₂ T_inv i)\n (Ext_Tinv2 Tinv₁ ι₁ T_inv i)\n (((Ext i).map f.op).app V) :=\ncommsq.of_eq\nbegin\n delta Ext_Tinv2,\n simp only [comp_sub, sub_comp, ← nat_trans.comp_app, ← functor.map_comp, ← op_comp, sqT,\n ← nat_trans.naturality, ← nat_trans.naturality_assoc, category.assoc, sqι],\nend\n\nopen category_theory.preadditive\n\nlemma auux\n {𝓐 : Type*} [category 𝓐] [abelian 𝓐] [enough_projectives 𝓐]\n {A₁ B₁ A₂ B₂ : cochain_complex 𝓐 ℤ}\n [((homotopy_category.quotient 𝓐 (complex_shape.up ℤ)).obj A₁).is_bounded_above]\n [((homotopy_category.quotient 𝓐 (complex_shape.up ℤ)).obj B₁).is_bounded_above]\n [((homotopy_category.quotient 𝓐 (complex_shape.up ℤ)).obj A₂).is_bounded_above]\n [((homotopy_category.quotient 𝓐 (complex_shape.up ℤ)).obj B₂).is_bounded_above]\n {f₁ : A₁ ⟶ B₁} {f₂ : A₂ ⟶ B₂} {α : A₁ ⟶ A₂} {β : B₁ ⟶ B₂}\n (sq1 : commsq f₁ α β f₂) :\n of_hom f₁ ≫ of_hom β = of_hom α ≫ of_hom f₂ :=\nbegin\n have := sq1.w,\n apply_fun (λ f, (homotopy_category.quotient _ _).map f) at this,\n simp only [functor.map_comp] at this,\n exact this,\nend\n\n@[simp] lemma of_hom_id\n {𝓐 : Type*} [category 𝓐] [abelian 𝓐] [enough_projectives 𝓐]\n {A : cochain_complex 𝓐 ℤ}\n [((homotopy_category.quotient 𝓐 (complex_shape.up ℤ)).obj A).is_bounded_above] :\n of_hom (𝟙 A) = 𝟙 _ :=\nby { delta of_hom, rw [category_theory.functor.map_id], refl }\n\nlemma Ext_iso_of_bicartesian_of_bicartesian\n {𝓐 : Type*} [category 𝓐] [abelian 𝓐] [enough_projectives 𝓐]\n {A₁ B₁ C A₂ B₂ : cochain_complex 𝓐 ℤ}\n [((homotopy_category.quotient 𝓐 (complex_shape.up ℤ)).obj A₁).is_bounded_above]\n [((homotopy_category.quotient 𝓐 (complex_shape.up ℤ)).obj B₁).is_bounded_above]\n [((homotopy_category.quotient 𝓐 (complex_shape.up ℤ)).obj C).is_bounded_above]\n [((homotopy_category.quotient 𝓐 (complex_shape.up ℤ)).obj A₂).is_bounded_above]\n [((homotopy_category.quotient 𝓐 (complex_shape.up ℤ)).obj B₂).is_bounded_above]\n {f₁ : A₁ ⟶ B₁} {g₁ : B₁ ⟶ C} (w₁ : ∀ n, short_exact (f₁.f n) (g₁.f n))\n {f₂ : A₂ ⟶ B₂} {g₂ : B₂ ⟶ C} (w₂ : ∀ n, short_exact (f₂.f n) (g₂.f n))\n (α : A₁ ⟶ A₂) (β : B₁ ⟶ B₂) (γ : C ⟶ C)\n (ιA : A₁ ⟶ A₂) (ιB : B₁ ⟶ B₂)\n (sq1 : commsq f₁ α β f₂) (sq2 : commsq g₁ β γ g₂)\n (sq1' : commsq f₁ ιA ιB f₂) (sq2' : commsq g₁ ιB (𝟙 _) g₂)\n (V : bounded_homotopy_category 𝓐) (T_inv : V ⟶ V)\n (i : ℤ)\n (H1 : (Ext_Tinv2_commsq (of_hom α) (of_hom ιA) (of_hom β) (of_hom ιB) (of_hom f₁) (of_hom f₂)\n (auux sq1) (auux sq1') T_inv i).bicartesian)\n (H2 : (Ext_Tinv2_commsq (of_hom α) (of_hom ιA) (of_hom β) (of_hom ιB) (of_hom f₁) (of_hom f₂)\n (auux sq1) (auux sq1') T_inv (i+1)).bicartesian) :\n is_iso (Ext_Tinv2 (of_hom γ) (𝟙 _) T_inv (i+1)) :=\nbegin\n have LES₁ := (((Ext_five_term_exact_seq' _ _ i V w₁).drop 2).pair.cons (Ext_five_term_exact_seq' _ _ (i+1) V w₁)),\n replace LES₁ := (((Ext_five_term_exact_seq' _ _ i V w₁).drop 1).pair.cons LES₁).extract 0 4,\n have LES₂ := (((Ext_five_term_exact_seq' _ _ i V w₂).drop 2).pair.cons (Ext_five_term_exact_seq' _ _ (i+1) V w₂)).extract 0 4,\n replace LES₂ := (((Ext_five_term_exact_seq' _ _ i V w₂).drop 1).pair.cons LES₂).extract 0 4,\n refine iso_of_bicartesian_of_bicartesian LES₂ LES₁ _ _ _ _ H1 H2,\n { apply commsq.of_eq, delta Ext_Tinv2, clear LES₁ LES₂,\n rw [sub_comp, comp_sub, ← functor.flip_obj_map, ← functor.flip_obj_map],\n rw ← Ext_δ_natural i V _ _ _ _ α β γ sq1.w sq2.w w₁ w₂,\n congr' 1,\n rw [← nat_trans.naturality, ← functor.flip_obj_map, category.assoc,\n Ext_δ_natural i V _ _ _ _ ιA ιB (𝟙 _) sq1'.w sq2'.w w₁ w₂],\n simp only [op_id, category_theory.functor.map_id, nat_trans.id_app,\n category.id_comp, of_hom_id, category.comp_id],\n erw [category.id_comp],\n symmetry,\n apply Ext_δ_natural', },\n { apply Ext_Tinv2_commsq,\n { exact auux sq2 },\n { exact auux sq2' }, },\nend\n\nend\n", "meta": {"author": "bentoner", "repo": "debug", "sha": "b8a75381caa90aa9942c20e08a44e45d0ae60d18", "save_path": "github-repos/lean/bentoner-debug", "path": "github-repos/lean/bentoner-debug/debug-b8a75381caa90aa9942c20e08a44e45d0ae60d18/src/Lbar/ext_aux2.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.44167300566462553, "lm_q2_score": 0.020645928780790277, "lm_q1q2_score": 0.00911874941934944}} {"text": "/-\nCopyright (c) 2020 Robert Y. Lewis. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Robert Y. Lewis\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.default\nimport Mathlib.tactic.fix_reflect_string\nimport Mathlib.PostPort\n\nuniverses l \n\nnamespace Mathlib\n\n/-!\n# Documentation commands\n\nWe generate html documentation from mathlib. It is convenient to collect lists of tactics, commands,\nnotes, etc. To facilitate this, we declare these documentation entries in the library\nusing special commands.\n\n* `library_note` adds a note describing a certain feature or design decision. These can be\n referenced in doc strings with the text `note [name of note]`.\n* `add_tactic_doc` adds an entry documenting an interactive tactic, command, hole command, or\n attribute.\n\nSince these commands are used in files imported by `tactic.core`, this file has no imports.\n\n## Implementation details\n\n`library_note note_id note_msg` creates a declaration `` `library_note.i `` for some `i`.\nThis declaration is a pair of strings `note_id` and `note_msg`, and it gets tagged with the\n`library_note` attribute.\n\nSimilarly, `add_tactic_doc` creates a declaration `` `tactic_doc.i `` that stores the provided\ninformation.\n-/\n\n/-- A rudimentary hash function on strings. -/\ndef string.hash (s : string) : ℕ :=\n string.fold 1 (fun (h : ℕ) (c : char) => (bit1 (bit0 (bit0 (bit0 (bit0 1)))) * h + char.val c) % unsigned_sz) s\n\n/-- `mk_hashed_name nspace id` hashes the string `id` to a value `i` and returns the name\n`nspace._i` -/\n/--\n`copy_doc_string fr to` copies the docstring from the declaration named `fr`\nto each declaration named in the list `to`. -/\n/--\n`copy_doc_string source → target_1 target_2 ... target_n` copies the doc string of the\ndeclaration named `source` to each of `target_1`, `target_2`, ..., `target_n`.\n -/\n/-! ### The `library_note` command -/\n\n/-- A user attribute `library_note` for tagging decls of type `string × string` for use in note\noutput. -/\n/--\n`mk_reflected_definition name val` constructs a definition declaration by reflection.\n\nExample: ``mk_reflected_definition `foo 17`` constructs the definition\ndeclaration corresponding to `def foo : ℕ := 17`\n-/\n/-- If `note_name` and `note` are `pexpr`s representing strings,\n`add_library_note note_name note` adds a declaration of type `string × string` and tags it with\nthe `library_note` attribute. -/\n/--\nA command to add library notes. Syntax:\n```\n/--\nnote message\n-/\n/-- Collects all notes in the current environment.\nReturns a list of pairs `(note_id, note_content)` -/\n/-! ### The `add_tactic_doc_entry` command -/\n\n/-- The categories of tactic doc entry. -/\ninductive doc_category \nwhere\n| tactic : doc_category\n| cmd : doc_category\n| hole_cmd : doc_category\n| attr : doc_category\n\n/-- Format a `doc_category` -/\n/-- The information used to generate a tactic doc entry -/\nstructure tactic_doc_entry \nwhere\n name : string\n category : doc_category\n decl_names : List name\n tags : List string\n description : string\n inherit_description_from : Option name\n\n/-- Turns a `tactic_doc_entry` into a JSON representation. -/\n/-- `update_description_from tde inh_id` replaces the `description` field of `tde` with the\n doc string of the declaration named `inh_id`. -/\n/--\n`update_description tde` replaces the `description` field of `tde` with:\n\n* the doc string of `tde.inherit_description_from`, if this field has a value\n* the doc string of the entry in `tde.decl_names`, if this field has length 1\n\nIf neither of these conditions are met, it returns `tde`. -/\n/-- A user attribute `tactic_doc` for tagging decls of type `tactic_doc_entry`\nfor use in doc output -/\n/-- Collects everything in the environment tagged with the attribute `tactic_doc`. -/\n/-- `add_tactic_doc tde` adds a declaration to the environment\nwith `tde` as its body and tags it with the `tactic_doc`\nattribute. If `tde.decl_names` has exactly one entry `` `decl`` and\nif `tde.description` is the empty string, `add_tactic_doc` uses the doc\nstring of `decl` as the description. -/\n/--\nA command used to add documentation for a tactic, command, hole command, or attribute.\n\nUsage: after defining an interactive tactic, command, or attribute,\nadd its documentation as follows.\n```lean\n/--\ndescribe what the command does here\n-/\n/--\nAt various places in mathlib, we leave implementation notes that are referenced from many other\nfiles. To keep track of these notes, we use the command `library_note`. This makes it easy to\nretrieve a list of all notes, e.g. for documentation output.\n\nThese notes can be referenced in mathlib with the syntax `Note [note id]`.\nOften, these references will be made in code comments (`--`) that won't be displayed in docs.\nIf such a reference is made in a doc string or module doc, it will be linked to the corresponding\nnote in the doc display.\n\nSyntax:\n```\n/--\nnote message\n-/\n/--\nSome declarations work with open expressions, i.e. an expr that has free variables.\nTerms will free variables are not well-typed, and one should not use them in tactics like\n`infer_type` or `unify`. You can still do syntactic analysis/manipulation on them.\nThe reason for working with open types is for performance: instantiating variables requires\niterating through the expression. In one performance test `pi_binders` was more than 6x\nquicker than `mk_local_pis` (when applied to the type of all imported declarations 100x).\n-/\n-- See Note [open expressions]\n\n/-- behavior of f -/\n-- add docs to core tactics\n\n/--\nThe congruence closure tactic `cc` tries to solve the goal by chaining\nequalities from context and applying congruence (i.e. if `a = b`, then `f a = f b`).\nIt is a finishing tactic, i.e. it is meant to close\nthe current goal, not to make some inconclusive progress.\nA mostly trivial example would be:\n\n```lean\nexample (a b c : ℕ) (f : ℕ → ℕ) (h: a = b) (h' : b = c) : f a = f c := by cc\n```\n\nAs an example requiring some thinking to do by hand, consider:\n\n```lean\nexample (f : ℕ → ℕ) (x : ℕ)\n (H1 : f (f (f x)) = x) (H2 : f (f (f (f (f x)))) = x) :\n f x = x :=\nby cc\n```\n\nThe tactic works by building an equality matching graph. It's a graph where\nthe vertices are terms and they are linked by edges if they are known to\nbe equal. Once you've added all the equalities in your context, you take\nthe transitive closure of the graph and, for each connected component\n(i.e. equivalence class) you can elect a term that will represent the\nwhole class and store proofs that the other elements are equal to it.\nYou then take the transitive closure of these equalities under the\ncongruence lemmas.\n\nThe `cc` implementation in Lean does a few more tricks: for example it\nderives `a=b` from `nat.succ a = nat.succ b`, and `nat.succ a !=\nnat.zero` for any `a`.\n\n* The starting reference point is Nelson, Oppen, [Fast decision procedures based on congruence\nclosure](http://www.cs.colorado.edu/~bec/courses/csci5535-s09/reading/nelson-oppen-congruence.pdf),\nJournal of the ACM (1980)\n\n* The congruence lemmas for dependent type theory as used in Lean are described in\n[Congruence closure in intensional type theory](https://leanprover.github.io/papers/congr.pdf)\n(de Moura, Selsam IJCAR 2016).\n-/\n/--\n`conv {...}` allows the user to perform targeted rewriting on a goal or hypothesis,\nby focusing on particular subexpressions.\n\nSee for more details.\n\nInside `conv` blocks, mathlib currently additionally provides\n* `erw`,\n* `ring`, `ring2` and `ring_exp`,\n* `norm_num`,\n* `norm_cast`,\n* `apply_congr`, and\n* `conv` (within another `conv`).\n\n`apply_congr` applies congruence lemmas to step further inside expressions,\nand sometimes gives between results than the automatically generated\ncongruence lemmas used by `congr`.\n\nUsing `conv` inside a `conv` block allows the user to return to the previous\nstate of the outer `conv` block after it is finished. Thus you can continue\nediting an expression without having to start a new `conv` block and re-scoping\neverything. For example:\n```lean\nexample (a b c d : ℕ) (h₁ : b = c) (h₂ : a + c = a + d) : a + b = a + d :=\nby conv {\n to_lhs,\n conv {\n congr, skip,\n rw h₁,\n },\n rw h₂,\n}\n```\nWithout `conv`, the above example would need to be proved using two successive\n`conv` blocks, each beginning with `to_lhs`.\n\nAlso, as a shorthand, `conv_lhs` and `conv_rhs` are provided, so that\n```lean\nexample : 0 + 0 = 0 :=\nbegin\n conv_lhs { simp }\nend\n```\njust means\n```lean\nexample : 0 + 0 = 0 :=\nbegin\n conv { to_lhs, simp }\nend\n```\nand likewise for `to_rhs`.\n-/\n/--\nAccepts terms with the type `component tactic_state string` or `html empty` and\nrenders them interactively.\nRequires a compatible version of the vscode extension to view the resulting widget.\n\n### Example:\n\n```lean\n/-- A simple counter that can be incremented or decremented with some buttons. -/\n/--\nThe `add_decl_doc` command is used to add a doc string to an existing declaration.\n\n```lean\ndef foo := 5\n\n/--\nDoc string for foo.\n-/\n", "meta": {"author": "AurelienSaue", "repo": "Mathlib4_auto", "sha": "590df64109b08190abe22358fabc3eae000943f2", "save_path": "github-repos/lean/AurelienSaue-Mathlib4_auto", "path": "github-repos/lean/AurelienSaue-Mathlib4_auto/Mathlib4_auto-590df64109b08190abe22358fabc3eae000943f2/Mathlib/tactic/doc_commands.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1755380649971796, "lm_q2_score": 0.051845469946048134, "lm_q1q2_score": 0.009100853473198719}} {"text": "import Lean\nimport Verbose.Common\n\nopen Lean Parser Meta Elab Tactic Option\n\n/- Restore rewrite using a single term without brackets. -/\ndeclare_syntax_cat myRwRuleSeq\nsyntax rwRule : myRwRuleSeq\nsyntax \"[\" rwRule,*,? \"]\" : myRwRuleSeq\n\n\n/--\nWe rewrite\n-/\nmacro (name := weRewrite) rw:\"We\" \"rewrite using\" c:(config)? s:myRwRuleSeq l:(location)? : tactic =>\n match s with\n | `(myRwRuleSeq| [%$lbrak $rs:rwRule,* ]%$rbrak) =>\n -- We show the `rfl` state on `]`\n `(tactic| rewrite%$rw $(c)? [%$lbrak $rs,*] $(l)?; try (with_reducible rfl%$rbrak))\n | `(myRwRuleSeq| $rs:rwRule) =>\n `(tactic| rewrite%$rw $(c)? [$rs] $(l)?; try (with_reducible rfl))\n | _ => Macro.throwUnsupported\n\nexample (a b : Nat) (h : a = b) (h' : b = 0): a = 0 := by\n We rewrite using ← h at h'\n exact h'\n\ndef discussOr (input : Term) : TacticM Unit := do \n evalApplyLikeTactic Meta.apply <| ← `(Or.elim $input)\n\nelab \"We\" \"discuss using\" exp:term : tactic => \n discussOr exp\n\nexample (P Q : Prop) (h : P ∨ Q) : True := by\n We discuss using h\n . intro _hP\n trivial\n . intro _hQ\n trivial\n\nmacro \"We\" \"discuss depending on\" exp:term : tactic =>\n`(tactic| We discuss using Classical.em $exp) \n\nexample (P : Prop) : True := by\n We discuss depending on P\n . intro _hP\n trivial\n . intro _hnP\n trivial\n", "meta": {"author": "PatrickMassot", "repo": "verbose-lean4", "sha": "0078291a4db4b6a0b14a8f34fb74cb2f1c6ae1ee", "save_path": "github-repos/lean/PatrickMassot-verbose-lean4", "path": "github-repos/lean/PatrickMassot-verbose-lean4/verbose-lean4-0078291a4db4b6a0b14a8f34fb74cb2f1c6ae1ee/Verbose/We.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2720245392906821, "lm_q2_score": 0.03308598160647967, "lm_q1q2_score": 0.009000198903482614}} {"text": "import data.list\nimport data.rbmap\nimport tactic.linarith\n\nimport .ast\nimport .sized\n \n\nlemma rbmap_insert_lookup_eq {α:Type} {β:Type} {lt:α → α → Prop} [Hdec:decidable_rel lt]\n (m:rbmap α β lt)\n (k:α) (x:β)\n : forall a, cmp_using lt a k = ordering.eq → rbmap.find (rbmap.insert m k x) a = some x \n:= sorry\n\nlemma rbmap_insert_lookup_neq {α:Type} {β:Type} {lt:α → α → Prop} [Hdec:decidable_rel lt]\n (m:rbmap α β lt)\n (k:α) (x:β)\n : forall a, cmp_using lt a k ≠ ordering.eq → rbmap.find (rbmap.insert m k x) a = rbmap.find m a\n:= sorry\n\n\nnamespace llvm.\n\n\nmeta def llvm_type_tac :=\n `[unfold has_well_founded.r measure inv_image sizeof has_sizeof.sizeof\n llvm_type.sizeof\n at *,\n try { linarith }\n ].\n\n@[simp]\ndef mentions : llvm_type → list ident\n| (llvm_type.prim_type _) := []\n| (llvm_type.alias i) := [i]\n| (llvm_type.array _n tp) := mentions tp\n| (llvm_type.fun_ty ret args _va) := mentions ret ++ (list.join (sized.map_over args (λ x H, mentions x)))\n| (llvm_type.ptr_to _) := [] -- NB pointer types are explicitly excluded\n| (llvm_type.struct fs) := list.join (sized.map_over fs (λ x H, mentions x))\n| (llvm_type.packed_struct fs) := list.join (sized.map_over fs (λ x H, mentions x))\n| (llvm_type.vector _n tp) := mentions tp\n| (llvm_type.opaque) := []\n\nusing_well_founded ⟨λ _ _, `[exact ⟨measure sizeof, measure_wf _⟩] , llvm_type_tac⟩\n.\n\n@[reducible,simp]\ndef alias_rel (am:strmap llvm_type) (x y:ident) : Prop :=\n ∃tp, am.find y.ident = some tp /\\ x ∈ mentions tp.\n\ninstance ident_eq_dec : decidable_rel (@eq ident) :=\nbegin\n unfold decidable_rel, intros a b, cases a, cases b, simp, apply_instance\nend\n\n@[reducible]\ndef alias_map := { am:strmap llvm_type // (forall a, acc (alias_rel am) a) }.\n\nnamespace alias_map.\n\ndef all_mem_dec {α:Type} (p:α → Prop) (l:list α) :\n (∀x, x ∈ l → decidable (p x)) →\n decidable (∀x, x ∈ l → p x) :=\nbegin\n induction l,\n case list.nil {\n intros, unfold has_mem.mem list.mem,\n right; intros, trivial,\n },\n case list.cons {\n intros, unfold has_mem.mem list.mem, intros,\n cases (a l_hd (or.inl rfl)),\n { left, intro, apply h, apply a_1, simp, },\n { have Hsub : (Π (x : α), x ∈ l_tl → decidable (p x)),\n { intros; apply a, apply or.inr, assumption },\n cases (l_ih Hsub),\n { left, intro, apply h_1, intros, apply a_1, apply or.inr, assumption },\n { right, intros, cases a_1,\n { subst x; assumption },\n { apply h_1; assumption }\n }\n }\n }\nend\n\ndef ex_mem_dec {α:Type} (p:α → Prop) (l:list α) :\n (∀x, x ∈ l → decidable (p x)) →\n decidable (∃x, x ∈ l ∧ p x) :=\nbegin\n induction l,\n case list.nil {\n intros, unfold has_mem.mem list.mem,\n left, intro H, cases H, cases H_h, trivial\n },\n case list.cons {\n intros, unfold has_mem.mem list.mem, intros,\n cases (a l_hd (or.inl rfl)),\n { have Hsub : (Π (x : α), x ∈ l_tl → decidable (p x)),\n { intros; apply a, apply or.inr, assumption },\n cases (l_ih Hsub),\n { left, intro H, cases H, cases H_h, cases H_h_left,\n { apply h; cc },\n { apply h_1, existsi H_w, cc }\n },\n { right, cases h_1, existsi h_1_w, cases h_1_h, split,\n apply or.inr, assumption, assumption,\n }\n },\n { right, existsi l_hd, split; try {assumption}, left, refl,\n }\n }\nend.\n\n\ndef reachable_dec \n (am:strmap llvm_type) \n : forall x y (Hacc : acc (alias_rel am) y), decidable (tc (alias_rel am) x y) :=\nbegin\n intros x y Hacc, apply Hacc.rec_on, clear Hacc y, intros y _ IH,\n destruct (am.find y.ident),\n { intros Hy, left, intro Htc, revert Hy, clear IH,\n induction Htc,\n { intros, cases Htc_a_1, cc, },\n { intros, cc }\n },\n intros tp Htp,\n have H : decidable (∃i, i ∈ mentions tp ∧ (i = x ∨ tc (alias_rel am) x i)),\n { apply ex_mem_dec, intros i Hi, \n cases (llvm.ident_eq_dec i x),\n { have Hi : alias_rel am i y, { existsi tp, split; assumption },\n cases (IH i Hi),\n { left, intro H, cases H; cc },\n { right, right, assumption }\n },\n { right, left, assumption },\n },\n\n cases H,\n { left, intro, clear h IH, apply H, clear H,\n induction a; intros,\n unfold alias_rel at a_a_1, cases a_a_1 with tp' Ha, cases Ha with Ha1 Ha2,\n have Heq : tp = tp', { cc }, subst tp',\n existsi a_a, split, apply Ha2, simp,\n cases (a_ih_a_1 Htp),\n cases h, cases h_right, subst a_b,\n existsi w, split, assumption, right, assumption,\n existsi w, split, assumption, right, apply tc.trans _ a_b _; assumption,\n },\n { right, cases H with i H, cases H with H1 H2, cases H2 with H2 H2,\n subst i, apply tc.base, existsi tp, split; assumption,\n apply tc.trans _ i _, assumption, apply tc.base, existsi tp, split; assumption\n }\nend.\n\nlemma string_cmp_using_eq\n (x y : string) :\n cmp_using string.has_lt'.lt x y = ordering.eq → x = y :=\nbegin\n unfold cmp_using ite,\n cases (string.decidable_lt y x); simp,\n cases (string.decidable_lt x y); simp,\n apply le_antisymm; assumption,\n cases (string.decidable_lt x y); simp,\nend.\n\n\nlemma insert_alias_map_wf_aux\n (am:strmap llvm_type)\n (x z:ident) (tp:llvm_type)\n (Hacc: acc (alias_rel am) z)\n : forall \n (Hxy : z ≠ x)\n (Hntc: ¬(tc (alias_rel am) x z)),\n acc (alias_rel (rbmap.insert am x.ident tp)) z :=\nbegin\n apply Hacc.rec_on, clear Hacc z, intros z h IH Hx Htc,\n apply acc.intro, intros q Hq,\n cases Hq with tp Htp, cases Htp with Htp1 Htp2,\n rewrite (rbmap_insert_lookup_neq am) at Htp1,\n { apply IH,\n { existsi tp, cc },\n { intro Hqx, apply Htc, apply tc.base,\n subst q, existsi tp, cc\n },\n { intro Hxq, apply Htc,\n apply tc.trans _ q _, assumption,\n apply tc.base, existsi tp, cc,\n }\n },\n { intro, apply Hx, cases z, cases x, \n unfold ident.ident at a, \n have Hzx : z = x, { apply string_cmp_using_eq, assumption },\n cc\n }\nend\n\nlemma insert_alias_map_wf\n (am:strmap llvm_type)\n (x:ident) (tp:llvm_type)\n (Hacc: forall a, acc (alias_rel am) a)\n (Hnacc : ¬∃y, y ∈ mentions tp ∧ (y = x ∨ tc (alias_rel am) x y)) \n : forall a, acc (alias_rel (rbmap.insert am x.ident tp)) a :=\nbegin\n intro a, apply (Hacc a).rec_on, clear a, intros a h IH, clear h,\n apply acc.intro, intros q Hq,\n cases Hq with tp' Htp, cases Htp with Htp1 Htp2,\n apply (@decidable.by_cases (cmp_using string.has_lt'.lt a.ident x.ident = ordering.eq)); intro Heq,\n { rewrite (rbmap_insert_lookup_eq am x.ident tp) at Htp1; try {assumption},\n injection Htp1, subst tp', clear Htp1,\n apply (insert_alias_map_wf_aux am x q tp (Hacc q)),\n { intro; subst q, apply Hnacc, existsi x, cc, },\n { intro, apply Hnacc, existsi q, cc, }\n },\n { rewrite (rbmap_insert_lookup_neq am x.ident tp) at Htp1; try {assumption},\n apply (IH q), existsi tp', split; assumption\n }\nend.\n\ndef empty : alias_map := subtype.mk (strmap_empty _)\n begin\n intro a, apply acc.intro, intros b H,\n destruct H, simp, unfold strmap_empty,\n unfold rbmap.find rbmap.find_entry rbmap.from_list, \n unfold mk_rbmap mk_rbtree, \n simp, unfold rbmap.find_entry._match_1 rbmap.to_value,\n intros, cc,\n end\n.\n\ndef insert_check_dec (am:alias_map) (x:ident) (tp:llvm_type) :\n decidable (∃y, y ∈ mentions tp ∧ (y = x ∨ tc (alias_rel am.val) x y)) :=\nbegin\n apply ex_mem_dec, intros q Hq,\n cases (llvm.ident_eq_dec q x),\n { cases (reachable_dec am.val x q (am.property q)),\n { left, intro H; cases H; cc },\n { right, right, assumption }\n },\n { right, left, assumption }\nend.\n\ndef insert (am:alias_map) (k:ident) (tp:llvm_type) : option alias_map :=\n match insert_check_dec am k tp with\n | decidable.is_true _ := none\n | decidable.is_false H :=\n some ⟨rbmap.insert am.val k.ident tp, insert_alias_map_wf am.val k tp am.property H⟩\n end\n\ndef build : list type_decl → alias_map → sum type_decl alias_map\n| [] am := sum.inr am\n| (td::tds) am :=\n match insert am td.name td.value with\n | none := sum.inl td\n | some am' := build tds am'\n end.\n\nend alias_map.\n\nend llvm.\n", "meta": {"author": "GaloisInc", "repo": "lean-llvm", "sha": "36e2ec604ae22d8ec1b1b66eca0f8887880db6c6", "save_path": "github-repos/lean/GaloisInc-lean-llvm", "path": "github-repos/lean/GaloisInc-lean-llvm/lean-llvm-36e2ec604ae22d8ec1b1b66eca0f8887880db6c6/src/LeanLLVM/alias_map.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.31069438321455395, "lm_q2_score": 0.02887090433510374, "lm_q1q2_score": 0.008970027815241447}} {"text": "import Lean\nimport Mathlib.Tactic.RCases\nimport Mathlib.Init.ExtendedBinder\n\nimport Verbose.Common\n\ninductive intro_rel where\n| lt | gt | le | ge | mem\nderiving Repr\n\nopen Lean\n\ninductive introduced where\n| typed (syn : Syntax) (n : Name) (e : Syntax) : introduced\n| bare (syn : Syntax) (n : Name) : introduced\n| related (syn : Syntax) (n : Name) (rel : intro_rel) (e : Syntax) : introduced\nderiving Repr\n\n\nopen Lean Meta\nopen Lean Elab Tactic\n\n/- Like Lean.Meta.intro except it introduces only data and fails on Prop.\nIt takes the current goal id as `mvarId` and a name for the newly introduced object\nand returns a `FVarId` referring the newly introduced object and a `MVarId` for the new\ngoal.\n -/\ndef introObj (mvarId : MVarId) (name : Name) : MetaM (FVarId × MVarId) := do\n let tgt ← whnf (← getMVarType mvarId)\n if tgt.isForall ∨ tgt.isLet then\n let (fvar, newmvarId) ← intro mvarId name\n withMVarContext newmvarId do\n let t := (← getLocalDecl fvar).type\n if (← inferType t).isProp then\n throwError \"There is no object to introduce here.\"\n else\n pure (fvar, newmvarId)\n else\n throwError \"There is no object to introduce here.\"\n\ndef Fix1 : introduced → TacticM Unit\n| introduced.typed syn n t => do\n withRef syn do \n checkName n\n -- Introduce n, getting the corresponding FVarId and the new goal MVarId with its context\n let (n_fvar, new_goal) ← introObj (← getMainGoal) n\n -- Change the default MVarContext to the newly created one for the benefit of `elabTerm`\n withMVarContext new_goal do\n replaceMainGoal [← changeLocalDecl new_goal n_fvar (← elabTerm t none)]\n| introduced.bare syn n => do\n withRef syn do\n checkName n\n -- Introduce n, forget the corresponding FVarId and get the new goal MVarId with its context\n let (_, new_goal) ← introObj (← getMainGoal) n\n replaceMainGoal [new_goal]\n| introduced.related syn n rel e => do\n withRef syn do\n checkName n\n let (n_fvar, new_goal) ← introObj (← getMainGoal) n\n withMVarContext new_goal do\n let n_decl ← getLocalDeclFromUserName n\n let n_type := n_decl.type\n -- Let's build the RHS e as an expr. In the membership case we don't have extra information\n -- in other case we elaborate knowing we should get the same type as n\n let (E : Expr) ← match rel with\n | intro_rel.mem => elabTerm e none\n | _ => elabTerm e n_type\n -- Now create a name for the relation assumption that will be created\n let (hyp_name : String) := if e matches `(0) then\n match rel with\n | intro_rel.lt => n.toString ++ \"_neg\"\n | intro_rel.gt => n.toString ++ \"_pos\"\n | intro_rel.le => n.toString ++ \"_neg\"\n | intro_rel.ge => n.toString ++ \"_pos\"\n | intro_rel.mem => \"h_\" ++ n.toString -- shouldn't happen\n\n else\n match rel with\n | intro_rel.lt => n.toString ++ \"_lt\"\n | intro_rel.gt => n.toString ++ \"_gt\"\n | intro_rel.le => n.toString ++ \"_le\"\n | intro_rel.ge => n.toString ++ \"_ge\"\n | intro_rel.mem => n.toString ++ \"_mem\"\n\n let n_expr : Expr := mkFVar n_fvar\n let (rel_expr : Expr) ← match rel with\n | intro_rel.lt => mkAppM ``LT.lt #[n_expr, E]\n | intro_rel.gt => mkAppM ``GT.gt #[n_expr, E]\n | intro_rel.le => mkAppM ``LE.le #[n_expr, E]\n | intro_rel.ge => mkAppM ``GE.ge #[n_expr, E]\n | intro_rel.mem => mkAppM ``Membership.mem #[n_expr, E]\n\n let (hyp_fvar, newer_goal) ← intro new_goal hyp_name\n withMVarContext newer_goal do\n let new_mvarid ← changeLocalDecl newer_goal hyp_fvar rel_expr\n replaceMainGoal [new_mvarid]\n\n\nsection\nopen Lean Elab\n\ndeclare_syntax_cat fixDecl\nsyntax ident : fixDecl\nsyntax ident \":\" term : fixDecl\nsyntax ident \"<\" term : fixDecl\nsyntax ident \">\" term : fixDecl\nsyntax ident (\"<=\" <|> \"≤\") term : fixDecl\nsyntax ident (\">=\" <|> \"≥\") term : fixDecl\nsyntax ident \"∈\" term : fixDecl\nsyntax \"(\" fixDecl \")\" : fixDecl\n\nsyntax \"Fix₁ \" colGt fixDecl : tactic\nsyntax \"Fix \" (colGt fixDecl)+ : tactic\n\nelab_rules : tactic\n | `(tactic| Fix₁ $x:ident) => Fix1 (introduced.bare x x.getId)\n\nelab_rules : tactic\n | `(tactic| Fix₁ $x:ident : $type) =>\n Fix1 (introduced.typed (mkNullNode #[x, type]) x.getId type)\n\nelab_rules : tactic\n | `(tactic| Fix₁ $x:ident < $bound) =>\n Fix1 (introduced.related (mkNullNode #[x, bound]) x.getId intro_rel.lt bound)\n\nelab_rules : tactic\n | `(tactic| Fix₁ $x:ident > $bound) =>\n Fix1 (introduced.related (mkNullNode #[x, bound]) x.getId intro_rel.gt bound)\n\nelab_rules : tactic\n | `(tactic| Fix₁ $x:ident ≤ $bound) =>\n Fix1 (introduced.related (mkNullNode #[x, bound]) x.getId intro_rel.le bound)\n\nelab_rules : tactic\n | `(tactic| Fix₁ $x:ident ≥ $bound) =>\n Fix1 (introduced.related (mkNullNode #[x, bound]) x.getId intro_rel.ge bound)\n\n\nelab_rules : tactic\n | `(tactic| Fix₁ $x:ident ∈ $set) =>\n Fix1 (introduced.related (mkNullNode #[x, set]) x.getId intro_rel.mem set)\n\nelab_rules : tactic\n | `(tactic| Fix₁ ( $decl:fixDecl )) => do evalTactic (← `(tactic| Fix₁ $decl:fixDecl))\n\n\nmacro_rules\n | `(tactic| Fix $decl:fixDecl) => `(tactic| Fix₁ $decl)\n\nmacro_rules\n | `(tactic| Fix $decl:fixDecl $decls:fixDecl*) => `(tactic| Fix₁ $decl; Fix $decls:fixDecl*)\n\n\nmacro_rules\n| `(ℕ) => `(Nat)\n\n-- requires the extended binder import\n#check ∀ n ≥ 2, true\n\n#check ∃ n ≥ 2, true\n\nexample : ∀ b : ℕ, ∀ a : Nat, a ≥ 2 → a = a ∧ b = b := by\n Fix b (a ≥ 2)\n trivial\n\nend\n", "meta": {"author": "PatrickMassot", "repo": "verbose-lean4", "sha": "0078291a4db4b6a0b14a8f34fb74cb2f1c6ae1ee", "save_path": "github-repos/lean/PatrickMassot-verbose-lean4", "path": "github-repos/lean/PatrickMassot-verbose-lean4/verbose-lean4-0078291a4db4b6a0b14a8f34fb74cb2f1c6ae1ee/Verbose/Fix.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41489886026626094, "lm_q2_score": 0.021615332920213354, "lm_q1q2_score": 0.00896817699287231}} {"text": "import tactic\nimport category_theory.limits.shapes.pullbacks\n\nnamespace category_theory\nopen category_theory.limits\n\nvariables {C D : Type*} [category C] [category D] (e : C ≌ D)\n {X Y B : D} (f : X ⟶ B) (g : Y ⟶ B) [has_pullback (e.inverse.map f) (e.inverse.map g)]\n\nlemma equivalence.hom_eq_map {X Y : C} (f : e.functor.obj X ⟶ e.functor.obj Y)\n (g : X ⟶ Y) : e.inverse.map f = e.symm.counit.app _ ≫ g ≫ e.unit.app _ →\n f = e.functor.map g :=\nbegin\n intros h,\n change _ = (e.unit_iso.app _).inv ≫ g ≫ (e.unit_iso.app _).hom at h,\n rw iso.eq_inv_comp at h,\n replace h := h.symm,\n rw ← iso.eq_comp_inv at h,\n rw h,\n simp,\n nth_rewrite 0 ← category.id_comp f,\n simp_rw ← category.assoc,\n congr' 1,\n simp,\nend\n\n\nnoncomputable theory\n\n/-\nI would like to do something for more general shapes, but universes make this difficult\n(as usual...)\n-/\n\n@[simps]\ndef equivalence.pullback_cone : cone (cospan f g) :=\n{ X := e.functor.obj $ pullback (e.inverse.map f) (e.inverse.map g),\n π :=\n { app := λ i,\n match i with\n | none := e.functor.map pullback.fst ≫ e.counit.app X ≫ f\n | walking_cospan.left := e.functor.map pullback.fst ≫ e.counit.app X\n | walking_cospan.right := e.functor.map pullback.snd ≫ e.counit.app Y\n end,\n naturality' := begin\n rintro (i|i|i) (j|j|j) (h|h),\n { tidy },\n { tidy },\n { tidy },\n { unfold_aux,\n dsimp, simp, delta id_rhs,\n have : e.counit.app X ≫ f = e.functor.map (e.inverse.map f) ≫ e.counit.app B, by tidy,\n rw this, clear this,\n have : e.counit.app Y ≫ g = e.functor.map (e.inverse.map g) ≫ e.counit.app B, by tidy,\n rw this, clear this,\n simp_rw [← category.assoc, ← e.functor.map_comp, limits.pullback.condition] },\n { tidy }\n end } } .\n\n-- This is a mess :-(\n-- Please fix before moving this file to mathlib!\ndef equivalence.is_limit_pullback_cone : limits.is_limit (e.pullback_cone f g) :=\n{ lift := λ S, e.symm.unit.app S.X ≫\n e.functor.map (pullback.lift (e.inverse.map (S.π.app walking_cospan.left))\n (e.inverse.map (S.π.app walking_cospan.right)) begin\n simp_rw ← e.inverse.map_comp,\n congr' 1,\n have := cospan_map_inl f g,\n change _ ≫ (cospan f g).map walking_cospan.hom.inl =\n _ ≫ (cospan f g).map walking_cospan.hom.inr,\n simp_rw S.w,\n end),\n fac' := begin\n rintros S (j|j|j),\n { dsimp [equivalence.pullback_cone._match_1], simp,\n have : e.counit.app X ≫ f = e.functor.map (e.inverse.map f) ≫ e.counit.app B, by tidy,\n rw this, clear this,\n simp_rw [← category.assoc _ _ (e.counit.app B), ← e.functor.map_comp],\n simp,\n dsimp,\n simp,\n change _ ≫ (cospan f g).map walking_cospan.hom.inl = _,\n rw S.w },\n { dsimp [equivalence.pullback_cone._match_1], simp,\n simp_rw [← category.assoc _ _ (e.counit.app X), ← e.functor.map_comp],\n simp,\n dsimp,\n simp },\n { dsimp [equivalence.pullback_cone._match_1], simp,\n simp_rw [← category.assoc _ _ (e.counit.app Y), ← e.functor.map_comp],\n simp,\n dsimp,\n simp }\n end,\n uniq' := begin\n intros S m h,\n dsimp at *,\n change m = (e.counit_iso.app S.X).inv ≫ _,\n rw iso.eq_inv_comp,\n apply equivalence.hom_eq_map,\n change _ = (e.unit_iso.app _).inv ≫ _ ≫ (e.unit_iso.app _).hom,\n rw iso.eq_inv_comp,\n symmetry,\n rw ← iso.eq_comp_inv,\n simp,\n apply pullback.hom_ext,\n { simp,\n specialize h walking_cospan.left,\n dsimp [equivalence.pullback_cone._match_1] at h,\n rw ← h,\n simp,\n simp_rw ← category.assoc,\n congr' 2,\n simp },\n { simp,\n specialize h walking_cospan.right,\n dsimp [equivalence.pullback_cone._match_1] at h,\n rw ← h,\n simp,\n simp_rw ← category.assoc,\n congr' 2,\n simp }\n end } .\n\ninclude e\n\nlemma equivalence.has_pullback {X Y B : D} (f : X ⟶ B) (g : Y ⟶ B)\n [has_pullback (e.inverse.map f) (e.inverse.map g)] : has_pullback f g :=\nlimits.has_limit.mk ⟨e.pullback_cone _ _, e.is_limit_pullback_cone _ _⟩\n\nlemma equivalence.has_pullbacks [has_pullbacks C] : has_pullbacks D :=\nbegin\n apply has_pullbacks_of_has_limit_cospan _,\n intros X Y B f g,\n apply e.has_pullback,\nend\n\nend category_theory\n", "meta": {"author": "bentoner", "repo": "debug", "sha": "b8a75381caa90aa9942c20e08a44e45d0ae60d18", "save_path": "github-repos/lean/bentoner-debug", "path": "github-repos/lean/bentoner-debug/debug-b8a75381caa90aa9942c20e08a44e45d0ae60d18/src/for_mathlib/pullbacks.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3345894279828469, "lm_q2_score": 0.0263553532284947, "lm_q1q2_score": 0.00881822256100792}} {"text": "import .cofibration_category\nimport .cylinder\nimport .lifting\n\nuniverses v u\n\nopen category_theory\nopen category_theory.category\nlocal notation f ` ∘ `:80 g:80 := g ≫ f\n\nnamespace homotopy_theory.cofibrations\nopen precofibration_category cofibration_category\n\nvariables {C : Type u} [category.{v} C] [cofibration_category.{v} C]\n\n-- Homotopies in a cofibration category.\n\nvariables {a b : C} {j : a ⟶ b} {hj : is_cof j}\n\nstructure homotopy_on (c : relative_cylinder hj) {x : C} (f₀ f₁ : b ⟶ x) :=\n(H : c.ob ⟶ x)\n(Hi₀ : H ∘ c.i₀ = f₀)\n(Hi₁ : H ∘ c.i₁ = f₁)\n\n@[ext] lemma homotopy_on.ext (c : relative_cylinder hj) {x : C} (f₀ f₁ : b ⟶ x)\n (H H' : homotopy_on c f₀ f₁) (e : H.H = H'.H) : H = H' :=\nby cases H; cases H'; simpa\n\ndef homotopy_on.refl {c : relative_cylinder hj} {x : C} (f : b ⟶ x) :\n homotopy_on c f f :=\n⟨f ∘ c.p, by rw [←assoc, c.pi₀]; simp, by rw [←assoc, c.pi₁]; simp⟩\n\ndef homotopy_on.symm {c : relative_cylinder hj} {x : C} {f₀ f₁ : b ⟶ x} :\n homotopy_on c f₀ f₁ → homotopy_on c.reverse f₁ f₀ :=\nλ H, ⟨H.H, by convert H.Hi₁; simp, by convert H.Hi₀; simp⟩\n\ndef homotopy_on.trans {c₀ c₁ : relative_cylinder hj} {x : C} {f₀ f₁ f₂ : b ⟶ x} :\n homotopy_on c₀ f₀ f₁ → homotopy_on c₁ f₁ f₂ → homotopy_on (c₀.glue c₁) f₀ f₂ :=\nλ H₀ H₁,\n⟨(pushout_by_cof c₀.i₁ c₁.i₀ c₀.acof_i₁.1).is_pushout.induced\n H₀.H H₁.H (H₀.Hi₁.trans H₁.Hi₀.symm),\n by convert H₀.Hi₀ using 1; simp, by convert H₁.Hi₁ using 1; simp⟩\n\n-- Two maps f₀, f₁ are homotopic rel j with respect to a chosen\n-- cylinder object on j if there exists a homotopy from f₀ to f₁\n-- defined on that cylinder.\ndef homotopic_wrt (c : relative_cylinder hj) {x : C} (f₀ f₁ : b ⟶ x) : Prop :=\nnonempty (homotopy_on c f₀ f₁)\n\n-- If x is fibrant, then any two cylinders define the same homotopy\n-- rel j relation on maps b ⟶ x.\nlemma homotopic_iff_of_embedding {c c' : relative_cylinder hj}\n (m : cylinder_embedding c c') {x : C} (hx : fibrant x) (f₀ f₁ : b ⟶ x) :\n homotopic_wrt c f₀ f₁ ↔ homotopic_wrt c' f₀ f₁ :=\niff.intro\n (assume ⟨⟨H, Hi₀, Hi₁⟩⟩,\n let ⟨H', hH'⟩ := fibrant_iff_rlp.mp hx m.acof_k H in\n ⟨⟨H', by rw ←m.hki₀; simp [hH', Hi₀], by rw ←m.hki₁; simp [hH', Hi₁]⟩⟩)\n (assume ⟨⟨H, Hi₀, Hi₁⟩⟩,\n ⟨⟨H ∘ m.k, by rw [←assoc, m.hki₀, Hi₀], by rw [←assoc, m.hki₁, Hi₁]⟩⟩)\n\nlemma homotopic_iff (c₀ c₁ : relative_cylinder hj) {x : C} (hx : fibrant x) (f₀ f₁ : b ⟶ x) :\n homotopic_wrt c₀ f₀ f₁ ↔ homotopic_wrt c₁ f₀ f₁ :=\nlet ⟨⟨c', m₀, m₁⟩⟩ := exists_common_embedding c₀ c₁ in\n(homotopic_iff_of_embedding m₀ hx f₀ f₁).trans\n (homotopic_iff_of_embedding m₁ hx f₀ f₁).symm\n\nvariables (hj)\ndef homotopic_rel {x} (f₀ f₁ : b ⟶ x) : Prop :=\n∃ c : relative_cylinder hj, homotopic_wrt c f₀ f₁\n\nvariables {hj}\nlemma homotopic_rel' (c : relative_cylinder hj) {x} (hx : fibrant x) (f₀ f₁ : b ⟶ x)\n (h : homotopic_rel hj f₀ f₁) : homotopic_wrt c f₀ f₁ :=\nlet ⟨c', hw⟩ := h in (homotopic_iff c' c hx f₀ f₁).mp hw\n\n@[refl] lemma homotopic_rel.refl {x} (f : b ⟶ x) : homotopic_rel hj f f :=\nlet ⟨c⟩ := exists_relative_cylinder hj in\n⟨c, ⟨homotopy_on.refl f⟩⟩\n\n@[symm] lemma homotopic_rel.symm {x} {f₀ f₁ : b ⟶ x} :\n homotopic_rel hj f₀ f₁ → homotopic_rel hj f₁ f₀ :=\nassume ⟨c, ⟨H⟩⟩, ⟨c.reverse, ⟨homotopy_on.symm H⟩⟩\n\n@[trans] lemma homotopic_rel.trans {x} {f₀ f₁ f₂ : b ⟶ x} :\n homotopic_rel hj f₀ f₁ → homotopic_rel hj f₁ f₂ → homotopic_rel hj f₀ f₂ :=\nassume ⟨c₀, ⟨H₀⟩⟩ ⟨c₁, ⟨H₁⟩⟩,\n⟨c₀.glue c₁, ⟨H₀.trans H₁⟩⟩\n\nlemma homotopic_rel_is_equivalence {x : C} :\n equivalence (homotopic_rel hj : (b ⟶ x) → (b ⟶ x) → Prop) :=\n⟨homotopic_rel.refl,\n λ f₀ f₁, homotopic_rel.symm,\n λ f₀ f₁ f₂, homotopic_rel.trans⟩\n\nnotation f₀ ` ≃ `:50 f₁:50 ` rel `:50 hj:50 := homotopic_rel hj f₀ f₁\n\nvariables (hj)\ndef homotopic_rel_setoid (x : C) : setoid (b ⟶ x) :=\n{ r := λ f₀ f₁, homotopic_rel hj f₀ f₁,\n iseqv := homotopic_rel_is_equivalence }\n\ndef homotopy_class_rel (x : C) : Type v :=\nquotient (homotopic_rel_setoid hj x)\n\n-- Lifts are unique up to homotopy.\n-- TODO: Useful?\nlemma lifts_unique (hj : is_acof j) {x : C} (hx : fibrant x) (f : a ⟶ x)\n {g₀ g₁ : b ⟶ x} (hg₀ : g₀ ∘ j = f) (hg₁ : g₁ ∘ j = f) : g₀ ≃ g₁ rel hj.1 :=\nlet ⟨c⟩ := exists_relative_cylinder hj.1,\n ⟨H, h⟩ := fibrant_iff_rlp.mp hx (c.acof_ii hj.2)\n ((pushout_by_cof j j hj.1).is_pushout.induced g₀ g₁ (hg₀.trans hg₁.symm)) in\n⟨c, ⟨⟨H, by simp [relative_cylinder.i₀, h], by simp [relative_cylinder.i₁, h]⟩⟩⟩\n\nsection congr_left\nvariables {x y : C} (g : x ⟶ y)\n\ndef homotopy_on.congr_left {c : relative_cylinder hj} {f₀ f₁ : b ⟶ x} :\n homotopy_on c f₀ f₁ → homotopy_on c (g ∘ f₀) (g ∘ f₁) :=\nλ H, ⟨g ∘ H.H, by rw [←assoc, H.Hi₀], by rw [←assoc, H.Hi₁]⟩\n\nlemma homotopic_rel.congr_left {f₀ f₁ : b ⟶ x} :\n homotopic_rel hj f₀ f₁ → homotopic_rel hj (g ∘ f₀) (g ∘ f₁) :=\nλ ⟨c, ⟨H⟩⟩, ⟨c, ⟨H.congr_left hj g⟩⟩\n\nend congr_left\n\nsection congr_right\nvariables {a' b' : C} {j' : a' ⟶ b'} (hj' : is_cof j')\n\nlemma homotopic_rel.congr_right (h : pair_map hj' hj) {x : C} (hx : fibrant x)\n (f₀ f₁ : b ⟶ x) : f₀ ≃ f₁ rel hj → f₀ ∘ h.h ≃ f₁ ∘ h.h rel hj' :=\nassume ⟨c, H⟩,\nlet ⟨c'⟩ := exists_relative_cylinder hj',\n ⟨c'', m', m, ⟨⟩⟩ := exists_of_pair_map h c' c,\n ⟨H'⟩ := (homotopic_iff_of_embedding m hx f₀ f₁).mp H in\n⟨c',\n ⟨⟨H'.H ∘ m'.k,\n by rw [←assoc, m'.hki₀, assoc, H'.Hi₀],\n by rw [←assoc, m'.hki₁, assoc, H'.Hi₁]⟩⟩⟩\n\nend congr_right\n\nend homotopy_theory.cofibrations\n", "meta": {"author": "rwbarton", "repo": "lean-homotopy-theory", "sha": "39e1b4ea1ed1b0eca2f68bc64162dde6a6396dee", "save_path": "github-repos/lean/rwbarton-lean-homotopy-theory", "path": "github-repos/lean/rwbarton-lean-homotopy-theory/lean-homotopy-theory-39e1b4ea1ed1b0eca2f68bc64162dde6a6396dee/src/homotopy_theory/formal/cofibrations/homotopy.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3775406828054583, "lm_q2_score": 0.02333076634678317, "lm_q1q2_score": 0.008808313456939127}} {"text": "import category_theory.preadditive.basic\nimport category_theory.abelian.projective\nimport data.matrix.notation\nimport tactic.interval_cases\nimport category_theory.abelian.pseudoelements\n\nimport .short_exact_sequence\nimport .abelian_category\nimport .fin_functor\nimport .exact_seq\n\nnoncomputable theory\n\nopen category_theory\nopen category_theory.limits\nopen_locale pseudoelement\n\nuniverse variables v u\n\nnamespace eq\n\nvariables {X : Type*} {x y : X} (h : x = y)\n\n@[nolint unused_arguments]\nabbreviation lhs (h : x = y) := x\n\n@[nolint unused_arguments]\nabbreviation rhs (h : x = y) := y\n\n@[simp] lemma lhs_def : h.lhs = x := rfl\n@[simp] lemma rhs_def : h.rhs = y := rfl\n\nend eq\n\nnamespace category_theory\n\n/-- The base diagram for the snake lemma. The object are indexed by `fin 4 × fin 3`:\n\n(0,0) --> (0,1) --> (0,2) | the kernels\n | | |\n v v v\n(1,0) --> (1,1) --> (1,2) | the first exact row\n | | |\n v v v\n(2,0) --> (2,1) --> (2,2) | the second exact row\n | | |\n v v v\n(3,0) --> (3,1) --> (3,2) | the cokernels\n\n-/\n@[derive [preorder, decidable_eq]]\ndef snake_diagram := fin 4 × fin 3\n\nnamespace snake_diagram\n\n@[simps]\ndef o (i : fin 4) (j : fin 3) : snake_diagram := (i,j)\n\n@[simp] lemma o_le_o (i j : fin 4) (k l : fin 3) :\n o i k ≤ o j l ↔ i ≤ j ∧ k ≤ l := iff.rfl\n\nmeta def hom_tac : tactic unit :=\n`[simp only [category_theory.snake_diagram.o_le_o,\n category_theory.snake_diagram.o_fst, category_theory.snake_diagram.o_snd,\n prod.le_def, and_true, true_and, le_refl],\n dec_trivial! ]\n\ndef hom (i j : snake_diagram) (hij : i ≤ j . hom_tac) : i ⟶ j := hom_of_le hij\n\nlemma hom_ext {i j : snake_diagram} (f g : i ⟶ j) : f = g := by ext\n\nsection\n\nmeta def map_tac : tactic unit :=\n`[dsimp only [mk_functor, mk_functor.map', eq_to_hom_refl, hom_of_le_refl, true_and, le_refl],\n simp only [category.id_comp, category.comp_id, functor.map_id],\n refl]\n\nparameters {C : Type u} [category.{v} C]\n\nparameters (F : fin 4 → fin 3 → C)\nparameters (f0 : F 0 0 ⟶ F 0 1) (g0 : F 0 1 ⟶ F 0 2)\nparameters (a0 : F 0 0 ⟶ F 1 0) (b0 : F 0 1 ⟶ F 1 1) (c0 : F 0 2 ⟶ F 1 2)\nparameters (f1 : F 1 0 ⟶ F 1 1) (g1 : F 1 1 ⟶ F 1 2)\nparameters (a1 : F 1 0 ⟶ F 2 0) (b1 : F 1 1 ⟶ F 2 1) (c1 : F 1 2 ⟶ F 2 2)\nparameters (f2 : F 2 0 ⟶ F 2 1) (g2 : F 2 1 ⟶ F 2 2)\nparameters (a2 : F 2 0 ⟶ F 3 0) (b2 : F 2 1 ⟶ F 3 1) (c2 : F 2 2 ⟶ F 3 2)\nparameters (f3 : F 3 0 ⟶ F 3 1) (g3 : F 3 1 ⟶ F 3 2)\nparameters (sq00 : a0 ≫ f1 = f0 ≫ b0) (sq01 : b0 ≫ g1 = g0 ≫ c0)\nparameters (sq10 : a1 ≫ f2 = f1 ≫ b1) (sq11 : b1 ≫ g2 = g1 ≫ c1)\nparameters (sq20 : a2 ≫ f3 = f2 ≫ b2) (sq21 : b2 ≫ g3 = g2 ≫ c2)\n\nnamespace mk_functor\n\ndef col : Π (j : fin 3), fin 4 ⥤ C\n| ⟨0,h⟩ := fin4_functor_mk (flip F 0) a0 a1 a2\n| ⟨1,h⟩ := fin4_functor_mk (flip F 1) b0 b1 b2\n| ⟨2,h⟩ := fin4_functor_mk (flip F 2) c0 c1 c2\n| ⟨j+3,h⟩ := by { exfalso, revert h, dec_trivial }\n\ndef row : Π (i : fin 4), fin 3 ⥤ C\n| ⟨0,h⟩ := fin3_functor_mk (F 0) f0 g0\n| ⟨1,h⟩ := fin3_functor_mk (F 1) f1 g1\n| ⟨2,h⟩ := fin3_functor_mk (F 2) f2 g2\n| ⟨3,h⟩ := fin3_functor_mk (F 3) f3 g3\n| ⟨j+4,h⟩ := by { exfalso, revert h, dec_trivial }\n\nlemma col_obj (i : fin 4) (j : fin 3) : (col j).obj i = F i j :=\nby fin_cases i; fin_cases j; refl.\n\nlemma row_obj (i : fin 4) (j : fin 3) : (row i).obj j = F i j :=\nby fin_cases i; fin_cases j; refl.\n\nlemma row_eq_col_obj (i : fin 4) (j : fin 3) : (row i).obj j = (col j).obj i :=\n(row_obj i j).trans (col_obj i j).symm\n\ndef map' (x y : snake_diagram) (h : x ≤ y) : F x.1 x.2 ⟶ F y.1 y.2 :=\neq_to_hom (by rw [row_obj]) ≫\n(row x.1).map h.2.hom ≫ eq_to_hom (by rw [row_obj, col_obj]) ≫\n(col y.2).map h.1.hom ≫ eq_to_hom (by rw [col_obj])\n\nlemma map'_id (x : snake_diagram) : map' x x le_rfl = 𝟙 _ :=\nby simp only [map', hom_of_le_refl, functor.map_id,\n eq_to_hom_trans, category.id_comp, eq_to_hom_refl]\n\ndef square_commutes (i j : fin 4) (k l : fin 3) (hij : i ≤ j) (hkl : k ≤ l) : Prop :=\n(col k).map hij.hom ≫ eq_to_hom (by rw [row_obj, col_obj]) ≫\n(row j).map hkl.hom =\neq_to_hom (by rw [col_obj]; refl) ≫\nmap' (o i k) (o j l) ⟨hij, hkl⟩ ≫ eq_to_hom (by rw [row_obj]; refl)\n\ninclude sq00 sq01 sq10 sq11 sq20 sq21\n\nlemma square_commutes_row (i : fin 4) (k l : fin 3) (hkl : k ≤ l) :\n square_commutes i i k l le_rfl hkl :=\nbegin\n dsimp [square_commutes, map'],\n simp only [map', hom_of_le_refl, functor.map_id, eq_to_hom_trans, eq_to_hom_trans_assoc,\n category.id_comp, category.comp_id, category.assoc],\n erw [hom_of_le_refl],\n simp only [map', hom_of_le_refl, functor.map_id, eq_to_hom_trans, eq_to_hom_trans_assoc,\n category.id_comp, category.comp_id, category.assoc],\n rw [← category.assoc, eq_comm],\n convert category.comp_id _,\nend\n\nlemma square_commutes_col (i j : fin 4) (k : fin 3) (hij : i ≤ j) :\n square_commutes i j k k hij le_rfl :=\nbegin\n dsimp [square_commutes, map'],\n simp only [map', hom_of_le_refl, functor.map_id, eq_to_hom_trans, eq_to_hom_trans_assoc,\n category.id_comp, category.comp_id, category.assoc],\n erw [hom_of_le_refl],\n simp only [map', hom_of_le_refl, functor.map_id, eq_to_hom_trans, eq_to_hom_trans_assoc,\n category.id_comp, category.comp_id, category.assoc],\n rw [eq_comm],\n convert category.id_comp _,\nend\n\nlemma square_commutes_one (i : fin 4) (j : fin 3) (hi : i < 3) (hj : j < 2) :\n square_commutes i (i+1) j (j+1) (by dec_trivial!) (by dec_trivial!) :=\nbegin\n fin_cases i, swap 4, { exfalso, revert hi, dec_trivial },\n all_goals { fin_cases j, swap 3, { exfalso, revert hj, dec_trivial },\n all_goals {\n simp only [square_commutes, map', eq_to_hom_refl, category.comp_id, category.id_comp],\n assumption }, },\nend\n.\n\nlemma square_commutes_comp_row (i j k : fin 4) (l m : fin 3)\n (hij : i ≤ j) (hjk : j ≤ k) (hlm : l ≤ m)\n (h1 : square_commutes i j l m hij hlm) (h2 : square_commutes j k l m hjk hlm) :\n square_commutes i k l m (hij.trans hjk) hlm :=\nbegin\n dsimp [square_commutes, map'] at h1 h2 ⊢,\n simp only [map', hom_of_le_refl, functor.map_id, eq_to_hom_trans, eq_to_hom_trans_assoc,\n category.id_comp, category.comp_id, category.assoc] at h1 h2 ⊢,\n let φ : _ := _, let ψ : _ := _,\n calc _ = φ ≫ h2.lhs : _\n ... = φ ≫ h2.rhs : by { congr' 1, }\n ... = h1.lhs ≫ ψ : _\n ... = h1.rhs ≫ ψ : by { congr' 1, }\n ... = _ : _,\n swap 5, { exact functor.map _ hij.hom },\n swap 4, { refine (eq_to_hom _ ≫ _ ≫ eq_to_hom _),\n swap 2, { apply row_eq_col_obj; assumption },\n swap 3, { symmetry, apply row_eq_col_obj; assumption },\n exact functor.map _ hjk.hom },\n all_goals { dsimp [φ, ψ, eq.lhs_def, eq.rhs_def] },\n { simp only [← functor.map_comp_assoc], refl },\n { simp only [category.assoc], refl },\n { simp only [eq_to_hom_trans, eq_to_hom_trans_assoc, category.assoc],\n dsimp,\n simp only [hom_of_le_refl, eq_to_hom_trans, eq_to_hom_trans_assoc,\n category.id_comp, category.comp_id, category.assoc, ← functor.map_comp_assoc],\n refl, },\nend\n\nlemma square_commutes_comp_col (i j : fin 4) (l m n : fin 3)\n (hij : i ≤ j) (hlm : l ≤ m) (hmn : m ≤ n)\n (h1 : square_commutes i j l m hij hlm) (h2 : square_commutes i j m n hij hmn) :\n square_commutes i j l n hij (hlm.trans hmn) :=\nbegin\n dsimp [square_commutes, map'] at h1 h2 ⊢,\n simp only [map', hom_of_le_refl, functor.map_id, eq_to_hom_trans, eq_to_hom_trans_assoc,\n category.id_comp, category.comp_id, category.assoc] at h1 h2 ⊢,\n let φ : _ := _, let ψ : _ := _,\n calc _ = h1.lhs ≫ φ : _\n ... = h1.rhs ≫ φ : by { congr' 1, }\n ... = ψ ≫ h2.lhs : _\n ... = ψ ≫ h2.rhs : by { congr' 1, }\n ... = _ : _,\n swap 5, { exact functor.map _ hmn.hom },\n swap 4, { refine (eq_to_hom _ ≫ _ ≫ eq_to_hom _),\n swap 2, { symmetry, apply row_eq_col_obj; assumption },\n swap 3, { apply row_eq_col_obj; assumption },\n exact functor.map _ hlm.hom },\n all_goals { dsimp [φ, ψ, eq.lhs_def, eq.rhs_def] },\n { simp only [category.assoc, ← functor.map_comp], refl },\n { simp only [category.assoc], refl },\n { simp only [eq_to_hom_trans, eq_to_hom_trans_assoc, category.assoc],\n dsimp,\n simp only [hom_of_le_refl, eq_to_hom_trans, eq_to_hom_trans_assoc,\n category.id_comp, category.comp_id, category.assoc, ← functor.map_comp_assoc],\n refl, },\nend\n\nlemma col_comp_row (i j : fin 4) (k l : fin 3) (hij : i ≤ j) (hkl : k ≤ l) :\n (col k).map hij.hom ≫ eq_to_hom (by rw [row_obj, col_obj]) ≫\n (row j).map hkl.hom =\n eq_to_hom (by rw [col_obj]; refl) ≫\n map' (o i k) (o j l) ⟨hij, hkl⟩ ≫ eq_to_hom (by rw [row_obj]; refl) :=\nbegin\n cases i with i hi, cases j with j hj, cases k with k hk, cases l with l hl,\n have hkl' := hkl,\n rw [← fin.coe_fin_le, fin.coe_mk, fin.coe_mk] at hij hkl,\n obtain ⟨j, rfl⟩ := nat.exists_eq_add_of_le hij,\n obtain ⟨l, rfl⟩ := nat.exists_eq_add_of_le hkl,\n clear hij,\n induction j with j IHj,\n { apply square_commutes_row; assumption },\n refine square_commutes_comp_row F f0 g0 a0 b0 c0 f1 g1 a1 b1 c1 f2 g2 a2 b2 c2 f3 g3\n sq00 sq01 sq10 sq11 sq20 sq21 ⟨i, hi⟩ ⟨i+j, _⟩ _ _ _ _ _ hkl' _ _,\n { refine lt_trans _ hj, exact lt_add_one (i+j) },\n { simp only [← fin.coe_fin_le, fin.coe_mk], exact le_self_add },\n { simp only [← fin.coe_fin_le, fin.coe_mk], exact (lt_add_one (i+j)).le },\n { refine IHj _ _, },\n clear IHj hkl,\n induction l with l IHl,\n { apply square_commutes_col; assumption },\n refine square_commutes_comp_col F f0 g0 a0 b0 c0 f1 g1 a1 b1 c1 f2 g2 a2 b2 c2 f3 g3\n sq00 sq01 sq10 sq11 sq20 sq21 _ _ ⟨k, hk⟩ ⟨k+l, _⟩ _ _ _ _ _ _,\n { refine lt_trans _ hl, exact lt_add_one (k+l) },\n { simp only [← fin.coe_fin_le, fin.coe_mk], exact le_self_add },\n { simp only [← fin.coe_fin_le, fin.coe_mk], exact (lt_add_one (k+l)).le },\n { refine IHl _ _ _, simp only [← fin.coe_fin_le, fin.coe_mk], exact le_self_add },\n clear IHl,\n convert square_commutes_one F f0 g0 a0 b0 c0 f1 g1 a1 b1 c1 f2 g2 a2 b2 c2 f3 g3\n sq00 sq01 sq10 sq11 sq20 sq21 _ _ _ _ using 2,\n { rw [nat.one_mod, add_assoc, nat.mod_eq_of_lt hj] },\n { rw [nat.one_mod, add_assoc, nat.mod_eq_of_lt hl] },\n { rw [← fin.coe_fin_lt, fin.coe_mk], refine nat.lt_of_succ_lt_succ hj, },\n { rw [← fin.coe_fin_lt, fin.coe_mk], refine nat.lt_of_succ_lt_succ hl, },\nend\n\nlemma map'_comp (x y z : snake_diagram) (hxy : x ≤ y) (hyz : y ≤ z) :\n map' x y hxy ≫ map' y z hyz = map' x z (hxy.trans hyz) :=\nbegin\n delta map',\n slice_lhs 4 7 { rw [eq_to_hom_trans_assoc] },\n rw [col_comp_row],\n { dsimp [map'],\n simp only [map', eq_to_hom_trans_assoc, category.assoc, eq_to_hom_refl,\n category.comp_id, category.id_comp, ← functor.map_comp_assoc],\n refl },\n all_goals { assumption },\nend\n\nend mk_functor\n\ninclude sq00 sq01 sq10 sq11 sq20 sq21\n\ndef mk_functor : snake_diagram ⥤ C :=\n{ obj := function.uncurry F,\n map := λ x y h, mk_functor.map' F f0 g0 a0 b0 c0 f1 g1 a1 b1 c1 f2 g2 a2 b2 c2 f3 g3 x y h.le,\n map_id' := λ x, mk_functor.map'_id F f0 g0 a0 b0 c0 f1 g1 a1 b1 c1 f2 g2 a2 b2 c2 f3 g3 x,\n map_comp' := λ x y z hxy hyz, by { rw mk_functor.map'_comp; assumption } }\n\n@[simp] lemma mk_functor_map_f0 : mk_functor.map (hom (0,0) (0,1)) = f0 := by map_tac\n@[simp] lemma mk_functor_map_g0 : mk_functor.map (hom (0,1) (0,2)) = g0 := by map_tac\n@[simp] lemma mk_functor_map_a0 : mk_functor.map (hom (0,0) (1,0)) = a0 := by map_tac\n@[simp] lemma mk_functor_map_b0 : mk_functor.map (hom (0,1) (1,1)) = b0 := by map_tac\n@[simp] lemma mk_functor_map_c0 : mk_functor.map (hom (0,2) (1,2)) = c0 := by map_tac\n@[simp] lemma mk_functor_map_f1 : mk_functor.map (hom (1,0) (1,1)) = f1 := by map_tac\n@[simp] lemma mk_functor_map_g1 : mk_functor.map (hom (1,1) (1,2)) = g1 := by map_tac\n@[simp] lemma mk_functor_map_a1 : mk_functor.map (hom (1,0) (2,0)) = a1 := by map_tac\n@[simp] lemma mk_functor_map_b1 : mk_functor.map (hom (1,1) (2,1)) = b1 := by map_tac\n@[simp] lemma mk_functor_map_c1 : mk_functor.map (hom (1,2) (2,2)) = c1 := by map_tac\n@[simp] lemma mk_functor_map_f2 : mk_functor.map (hom (2,0) (2,1)) = f2 := by map_tac\n@[simp] lemma mk_functor_map_g2 : mk_functor.map (hom (2,1) (2,2)) = g2 := by map_tac\n@[simp] lemma mk_functor_map_a2 : mk_functor.map (hom (2,0) (3,0)) = a2 := by map_tac\n@[simp] lemma mk_functor_map_b2 : mk_functor.map (hom (2,1) (3,1)) = b2 := by map_tac\n@[simp] lemma mk_functor_map_c2 : mk_functor.map (hom (2,2) (3,2)) = c2 := by map_tac\n@[simp] lemma mk_functor_map_f3 : mk_functor.map (hom (3,0) (3,1)) = f3 := by map_tac\n@[simp] lemma mk_functor_map_g3 : mk_functor.map (hom (3,1) (3,2)) = g3 := by map_tac\n\nend\n\nsection\n\nvariables {𝒜 ℬ : Type*} [category 𝒜] [category ℬ]\nvariables (A : fin 3 → 𝒜) (F : fin 4 → 𝒜 ⥤ ℬ)\nvariables (f : A 0 ⟶ A 1) (g : A 1 ⟶ A 2) (α : F 0 ⟶ F 1) (β : F 1 ⟶ F 2) (γ : F 2 ⟶ F 3)\n\ndef mk_functor' : snake_diagram ⥤ ℬ :=\nmk_functor (λ i, (F i).obj ∘ A)\n /- FA₀₀ -/ ((F 0).map f) /- FA₀₁ -/ ((F 0).map g) /- FA₀₂ -/\n (α.app _) (α.app _) (α.app _)\n /- FA₁₀ -/ ((F 1).map f) /- FA₁₁ -/ ((F 1).map g) /- FA₁₂ -/\n (β.app _) (β.app _) (β.app _)\n /- FA₂₀ -/ ((F 2).map f) /- FA₂₁ -/ ((F 2).map g) /- FA₂₂ -/\n (γ.app _) (γ.app _) (γ.app _)\n /- FA₃₀ -/ ((F 3).map f) /- FA₃₁ -/ ((F 3).map g) /- FA₃₂ -/\n(α.naturality _).symm (α.naturality _).symm\n(β.naturality _).symm (β.naturality _).symm\n(γ.naturality _).symm (γ.naturality _).symm\n\nend\n\nsection\n\nvariables {𝒜 ℬ 𝒞 : Type*} [category 𝒜] [category ℬ] [category 𝒞]\nvariables (A : fin 3 → 𝒜 ⥤ ℬ) (F : fin 4 → ℬ ⥤ 𝒞)\nvariables (f : A 0 ⟶ A 1) (g : A 1 ⟶ A 2) (α : F 0 ⟶ F 1) (β : F 1 ⟶ F 2) (γ : F 2 ⟶ F 3)\n\ndef mk_functor'' : 𝒜 → snake_diagram ⥤ 𝒞 :=\nλ x, mk_functor' ![(A 0).obj x, (A 1).obj x, (A 2).obj x] F (f.app x) (g.app x) α β γ\n\nend\n\nsection\n\nvariables {𝒜 : Type*} [category 𝒜] [abelian 𝒜]\n\n-- move (ang generalize) this\nlemma exact_kernel_ι_self {A B : 𝒜} (f : A ⟶ B) : exact (kernel.ι f) f :=\nby { rw abelian.exact_iff, tidy } -- why do we not have abelian.exact_kernel?\n\n-- move this\nlemma exact_self_cokernel_π {A B : 𝒜} (f : A ⟶ B) : exact f (cokernel.π f) :=\nabelian.exact_cokernel _\n\nlocal notation `kernel_map` := kernel.map _ _ _ _\nlocal notation `cokernel_map` := cokernel.map _ _ _ _\n\ndef mk_of_short_exact_sequence_hom (A B : short_exact_sequence 𝒜) (f : A ⟶ B) :\n snake_diagram ⥤ 𝒜 :=\nmk_functor\n/- == Passing in the matrix of objects first, to make Lean happy == -/\n![![kernel f.1, kernel f.2, kernel f.3],\n ![A.1, A.2, A.3],\n ![B.1, B.2, B.3],\n ![cokernel f.1, cokernel f.2, cokernel f.3]]\n/- == All the morphisms in the diagram == -/\n /- ker f.1 -/ (kernel_map f.sq1) /- ker f.2 -/ (kernel_map f.sq2) /- ker f.3 -/\n (kernel.ι _) (kernel.ι _) (kernel.ι _)\n /- A.1 -/ A.f /- A.2 -/ A.g /- A.3 -/\n f.1 f.2 f.3\n /- B.1 -/ B.f /- B.2 -/ B.g /- B.3 -/\n (cokernel.π _) (cokernel.π _) (cokernel.π _)\n /- coker f.1 -/ (cokernel_map f.sq1) /- coker f.2 -/ (cokernel_map f.sq2) /- coker f.3 -/\n/- == Prove that the squares commute == -/\n(by { delta kernel.map, rw [kernel.lift_ι] }) (by { delta kernel.map, rw [kernel.lift_ι] })\nf.sq1 f.sq2\n(by { delta cokernel.map, rw [cokernel.π_desc] }) (by { delta cokernel.map, rw [cokernel.π_desc] })\n.\n\nend\n\nend snake_diagram\n\nopen snake_diagram (o hom)\n\nexample (i : fin 4) : o i 0 ⟶ o i 1 := hom (i,0) (i,1)\n\nlocal notation x `⟶[`D`]` y := D.map (hom x y)\n\nsection definitions\n\nvariables (𝒜 : Type u) [category.{v} 𝒜] [has_images 𝒜] [has_zero_morphisms 𝒜] [has_kernels 𝒜]\n\nvariables {𝒜}\n\nstructure is_snake_input (D : snake_diagram ⥤ 𝒜) : Prop :=\n(row_exact₁ : exact ((1,0) ⟶[D] (1,1)) ((1,1) ⟶[D] (1,2)))\n(row_exact₂ : exact ((2,0) ⟶[D] (2,1)) ((2,1) ⟶[D] (2,2)))\n(col_exact₁ : ∀ j, exact ((0,j) ⟶[D] (1,j)) ((1,j) ⟶[D] (2,j)))\n(col_exact₂ : ∀ j, exact ((1,j) ⟶[D] (2,j)) ((2,j) ⟶[D] (3,j)))\n(col_mono : ∀ j, mono ((0,j) ⟶[D] (1,j)))\n(col_epi : ∀ j, epi ((2,j) ⟶[D] (3,j)))\n(row_mono : mono ((2,0) ⟶[D] (2,1)))\n(row_epi : epi ((1,1) ⟶[D] (1,2)))\n\nnamespace is_snake_input\n\nvariables {D : snake_diagram ⥤ 𝒜}\n\n@[nolint unused_arguments]\nlemma map_eq (hD : is_snake_input D) {x y : snake_diagram} (f g : x ⟶ y) : D.map f = D.map g :=\ncongr_arg _ (snake_diagram.hom_ext _ _)\n\n@[nolint unused_arguments]\nlemma map_eq_id (hD : is_snake_input D) {x : snake_diagram} (f : x ⟶ x) : D.map f = 𝟙 _ :=\nby rw [snake_diagram.hom_ext f (𝟙 x), D.map_id]\n\nlemma hom_eq_zero₁ (hD : is_snake_input D) {x y : snake_diagram} (f : x ⟶ y)\n (h : x.1 < 2 ∧ x.1 + 1 < y.1 . snake_diagram.hom_tac) : D.map f = 0 :=\nbegin\n cases x with i j, cases y with k l, cases h with h₀ h₁, rcases f with ⟨⟨⟨hik, hjl⟩⟩⟩,\n dsimp at h₀ h₁ hik hjl,\n let f₁ := hom (i,j) (i+1,j),\n let f₂ := hom (i+1,j) (i+2,j),\n let f₃ := hom (i+2,j) (k,l),\n calc D.map _\n = D.map ((f₁ ≫ f₂) ≫ f₃) : hD.map_eq _ _\n ... = ((D.map f₁) ≫ D.map f₂) ≫ D.map f₃ : by simp only [D.map_comp]\n ... = 0 ≫ D.map f₃ : _\n ... = 0 : zero_comp,\n congr' 1,\n obtain (rfl|rfl) : i = 0 ∨ i = 1, { dec_trivial! },\n { exact (hD.col_exact₁ j).w },\n { exact (hD.col_exact₂ j).w },\nend\n.\n\nopen snake_diagram\n\nmeta def aux_simp : tactic unit :=\n`[dsimp only [snake_diagram.mk_of_short_exact_sequence_hom],\n simp only [mk_functor_map_f0, mk_functor_map_g0, mk_functor_map_a0, mk_functor_map_b0,\n mk_functor_map_c0, mk_functor_map_f1, mk_functor_map_g1, mk_functor_map_a1,\n mk_functor_map_b1, mk_functor_map_c1, mk_functor_map_f2, mk_functor_map_g2,\n mk_functor_map_a2, mk_functor_map_b2, mk_functor_map_c2, mk_functor_map_f3, mk_functor_map_g3]]\n\nlemma mk_of_short_exact_sequence_hom {𝒜 : Type*} [category 𝒜] [abelian 𝒜]\n (A B : short_exact_sequence 𝒜) (f : A ⟶ B) :\n is_snake_input (snake_diagram.mk_of_short_exact_sequence_hom A B f) :=\n{ row_exact₁ := by { aux_simp, exact A.exact' },\n row_exact₂ := by { aux_simp, exact B.exact' },\n col_exact₁ := λ j, by { fin_cases j; aux_simp, all_goals { apply exact_kernel_ι_self, } },\n col_exact₂ := λ j, by { fin_cases j; aux_simp, all_goals { apply exact_self_cokernel_π } },\n col_mono := λ j, by { fin_cases j; aux_simp, all_goals { apply_instance } },\n col_epi := λ j, by { fin_cases j; aux_simp, all_goals { apply_instance } },\n row_mono := by { aux_simp, exact B.mono' },\n row_epi := by { aux_simp, exact A.epi' }, }\n\nend is_snake_input\n\nend definitions\n\nsection\n\nopen abelian.pseudoelement\n\nvariables {𝒜 : Type u} [category.{v} 𝒜] [abelian 𝒜]\nvariables {D : snake_diagram ⥤ 𝒜}\n\nnamespace is_snake_input\n\nlocal attribute [instance] abelian.pseudoelement.over_to_sort\n abelian.pseudoelement.hom_to_fun\n abelian.pseudoelement.has_zero\n\nsection move_me\n\nlocal attribute [instance] abelian.pseudoelement.over_to_sort\n abelian.pseudoelement.hom_to_fun\n\nlemma injective_iff_mono {P Q : 𝒜} (f : P ⟶ Q) : function.injective f ↔ mono f :=\n⟨λ h, mono_of_zero_of_map_zero _ (zero_of_map_zero _ h),\n by introsI h; apply pseudo_injective_of_mono⟩\n\nlemma surjective_iff_epi {P Q : 𝒜} (f : P ⟶ Q) : function.surjective f ↔ epi f :=\n⟨epi_of_pseudo_surjective _, by introI h; apply pseudo_surjective_of_epi⟩\n\nlemma exists_of_exact {P Q R : 𝒜} {f : P ⟶ Q} {g : Q ⟶ R} (e : exact f g) (q) (hq : g q = 0) :\n ∃ p, f p = q :=\n(pseudo_exact_of_exact e).2 _ hq\n\nlemma eq_zero_of_exact {P Q R : 𝒜} {f : P ⟶ Q} {g : Q ⟶ R} (e : exact f g) (p) : g (f p) = 0 :=\n(pseudo_exact_of_exact e).1 _\n\n@[simp]\nlemma kernel_ι_apply {P Q : 𝒜} (f : P ⟶ Q) (a) : f (kernel.ι f a) = 0 :=\nbegin\n rw ← abelian.pseudoelement.comp_apply,\n simp,\nend\n\n-- (AT) I don't know if we actually want this lemma, but it came in handy below.\nlemma eq_zero_iff_kernel_ι_eq_zero {P Q : 𝒜} (f : P ⟶ Q) (q) : kernel.ι f q = 0 ↔ q = 0 :=\nbegin\n split,\n { intro h,\n apply_fun kernel.ι f,\n simp [h],\n rw injective_iff_mono,\n apply_instance },\n { intro h,\n simp [h] },\nend\n\n@[simp]\nlemma cokernel_π_apply {P Q : 𝒜} (f : P ⟶ Q) (a) : cokernel.π f (f a) = 0 :=\nbegin\n rw ← abelian.pseudoelement.comp_apply,\n simp,\nend\n\nlemma exists_of_cokernel_π_eq_zero {P Q : 𝒜} (f : P ⟶ Q) (a) :\n cokernel.π f a = 0 → ∃ b, f b = a :=\nbegin\n intro h,\n apply exists_of_exact _ _ h,\n apply snake_diagram.exact_self_cokernel_π,\nend\n\nlemma cokernel_π_surjective {P Q : 𝒜} (f : P ⟶ Q) : function.surjective (cokernel.π f) :=\nbegin\n rw surjective_iff_epi,\n apply_instance,\nend\n\n--move\nlemma exact_is_iso_iff {P Q Q' R : 𝒜} (f : P ⟶ Q) (g : Q' ⟶ R) (e : Q ⟶ Q') [is_iso e] :\n exact f (e ≫ g) ↔ exact (f ≫ e) g :=\nbegin\n let E := as_iso e,\n change exact f (E.hom ≫ g) ↔ exact (f ≫ E.hom) g,\n conv_rhs { rw (show g = E.inv ≫ E.hom ≫ g, by simp) },\n rw exact_comp_hom_inv_comp_iff\nend\n\n--lemma exact_comp_is_iso {P Q R R' : 𝒜} (f : P ⟶ Q) (g : Q ⟶ R) (e : R ⟶ R') [is_iso e] :\n-- exact f (g ≫ e) ↔ exact f g := exact_comp_iso\n\nend move_me\n\nlemma row_exact₀ (hD : is_snake_input D) : exact ((0,0) ⟶[D] (0,1)) ((0,1) ⟶[D] (0,2)) :=\nbegin\n refine exact_of_pseudo_exact _ _ ⟨λ a, _, _⟩,\n { apply_fun ((0,2) ⟶[D] (1,2)),\n swap, { rw injective_iff_mono, exact hD.col_mono _ },\n simp_rw [← abelian.pseudoelement.comp_apply, ← D.map_comp, abelian.pseudoelement.apply_zero],\n change D.map (hom (0,0) (1,0) ≫ hom (1,0) (1,1) ≫ hom (1,1) (1,2)) a = 0,\n simp [abelian.pseudoelement.comp_apply, eq_zero_of_exact hD.row_exact₁] },\n { intros b hb,\n apply_fun ((0,2) ⟶[D] (1,2)) at hb,\n simp_rw [← abelian.pseudoelement.comp_apply,\n ← D.map_comp, abelian.pseudoelement.apply_zero] at hb,\n change D.map (hom (0,1) (1,1) ≫ hom (1,1) (1,2)) b = 0 at hb,\n simp_rw [D.map_comp, abelian.pseudoelement.comp_apply] at hb,\n let b' := ((0,1) ⟶[D] (1,1)) b,\n change ((1,1) ⟶[D] (1,2)) b' = 0 at hb,\n obtain ⟨c,hc⟩ := exists_of_exact hD.row_exact₁ b' hb,\n have hcz : ((1,0) ⟶[D] (2,0)) c = 0,\n { apply_fun ((2,0) ⟶[D] (2,1)),\n swap, { rw injective_iff_mono, apply hD.row_mono },\n simp_rw [← abelian.pseudoelement.comp_apply, ← D.map_comp, abelian.pseudoelement.apply_zero],\n change D.map (hom (1,0) (1,1) ≫ hom (1,1) (2,1)) c = 0,\n simp_rw [D.map_comp, abelian.pseudoelement.comp_apply, hc],\n dsimp [b'],\n apply eq_zero_of_exact,\n apply hD.col_exact₁ },\n obtain ⟨d,hd⟩ := exists_of_exact (hD.col_exact₁ _) c hcz,\n use d,\n apply_fun ((0,1) ⟶[D] (1,1)),\n swap, { rw injective_iff_mono, exact hD.col_mono _ },\n dsimp only [b'] at hc,\n rw [← hc, ← hd],\n simp_rw [← abelian.pseudoelement.comp_apply, ← D.map_comp],\n refl }\nend\n\nlemma row_exact₃ (hD : is_snake_input D) : exact ((3,0) ⟶[D] (3,1)) ((3,1) ⟶[D] (3,2)) :=\nbegin\n refine exact_of_pseudo_exact _ _ ⟨λ a, _,λ b hb, _⟩,\n { obtain ⟨b, hb⟩ := (surjective_iff_epi ((2,0) ⟶[D] (3,0))).2 (hD.col_epi 0) a,\n rw [← hb, ← abelian.pseudoelement.comp_apply, ← abelian.pseudoelement.comp_apply,\n ← D.map_comp, ← D.map_comp, map_eq hD ((hom (2, 0) (3, 0)) ≫ (hom _ (3, 1)) ≫\n (hom _ (3, 2))) ((hom (2, 0) (2, 1)) ≫ (hom _ (2, 2)) ≫ (hom _ _)), ← category.assoc,\n D.map_comp _ (hom (2, 2) (3, 2)), D.map_comp, hD.row_exact₂.w, zero_comp, zero_apply] },\n { set f₁ := hom (2, 1) (2, 2),\n set f₂ := hom (2, 2) (3, 2),\n set f₃ := hom (1, 1) (2, 1),\n set f₄ := hom (2, 0) (3, 0),\n set f₅ := hom (3, 0) (3, 1),\n obtain ⟨c, hc⟩ := (surjective_iff_epi ((2,1) ⟶[D] (3,1))).2 (hD.col_epi 1) b,\n let d := D.map f₁ c,\n have hd : D.map f₂ d = 0,\n { rw [← abelian.pseudoelement.comp_apply, ← D.map_comp, map_eq hD ((hom (2, 1) (2, 2)) ≫\n (hom _ (3, 2))) ((hom (2, 1) (3, 1)) ≫ (hom _ (3, 2))), D.map_comp,\n abelian.pseudoelement.comp_apply, hc, hb] },\n obtain ⟨e, he⟩ := exists_of_exact (hD.col_exact₂ 2) d hd,\n obtain ⟨f, hf⟩ := (surjective_iff_epi ((1,1) ⟶[D] (1,2))).2 hD.row_epi e,\n have hfzero : ((2,1) ⟶[D] (3,1)) ((D.map f₃) f) = 0,\n { rw [← abelian.pseudoelement.comp_apply, (hD.col_exact₂ 1).w, zero_apply] },\n have hdiff : D.map f₁ c = D.map f₁ (D.map f₃ f),\n { rw [← abelian.pseudoelement.comp_apply, ← D.map_comp, map_eq hD ((hom (1, 1) (2, 1)) ≫\n (hom _ (2, 2))) ((hom (1, 1) (1, 2)) ≫ (hom _ (2, 2))), D.map_comp,\n abelian.pseudoelement.comp_apply, hf, he] },\n obtain ⟨g, ⟨hg₁, hg₂⟩⟩ := sub_of_eq_image _ _ _ hdiff,\n obtain ⟨h, hh⟩ := exists_of_exact hD.row_exact₂ g hg₁,\n use D.map f₄ h,\n rw [← abelian.pseudoelement.comp_apply, ← D.map_comp, map_eq hD\n ((hom (2, 0) (3, 0)) ≫ (hom _ (3, 1))) ((hom _ (2, 1)) ≫ (hom _ _)), D.map_comp,\n abelian.pseudoelement.comp_apply, hh, hg₂ _ ((2,1) ⟶[D] (3,1)) hfzero, hc] }\nend\n\nlemma row_exact (hD : is_snake_input D) (i : fin 4) :\n exact ((i,0) ⟶[D] (i,1)) ((i,1) ⟶[D] (i,2)) :=\nby { fin_cases i, exacts [hD.row_exact₀, hD.row_exact₁, hD.row_exact₂, hD.row_exact₃] }\n\nlemma hom_eq_zero₂ (hD : is_snake_input D) {x y : snake_diagram} (f : x ⟶ y)\n (h : x.2 = 0 ∧ y.2 = 2 . snake_diagram.hom_tac) : D.map f = 0 :=\nbegin\n cases x with i j, cases y with k l, rcases f with ⟨⟨⟨hik, hjl⟩⟩⟩,\n dsimp at h hik hjl, rcases h with ⟨rfl, rfl⟩,\n let f₁ := hom (i,0) (i,1),\n let f₂ := hom (i,1) (i,2),\n let f₃ := hom (i,2) (k,2),\n calc D.map _\n = D.map ((f₁ ≫ f₂) ≫ f₃) : hD.map_eq _ _\n ... = ((D.map f₁) ≫ D.map f₂) ≫ D.map f₃ : by simp only [D.map_comp]\n ... = 0 : by rw [(hD.row_exact i).w, zero_comp]\nend\n\nsection long_snake\n\nlemma ker_row₁_to_row₂ (hD : is_snake_input D) :\n (kernel.ι ((1,0) ⟶[D] (1,1))) ≫ ((1,0) ⟶[D] (2,0)) = 0 :=\nbegin\n refine zero_morphism_ext _ (λ a, (injective_iff_mono ((2,0) ⟶[D] (2,1))).2 hD.row_mono _),\n rw [apply_zero, ← abelian.pseudoelement.comp_apply, category.assoc,\n abelian.pseudoelement.comp_apply, ← D.map_comp, map_eq hD\n ((hom (1, 0) (2, 0)) ≫ (hom _ (2, 1))) ((hom _ (1, 1)) ≫ (hom _ _)), D.map_comp,\n abelian.pseudoelement.comp_apply, kernel_ι_apply, apply_zero]\nend\n\ndef ker_row₁_to_top_left (hD : is_snake_input D) : kernel ((1,0) ⟶[D] (1,1)) ⟶ D.obj (0, 0) :=\nby { letI := hD.col_mono 0, exact (limits.kernel.lift _ _ (ker_row₁_to_row₂ hD)) ≫\n (limits.kernel.lift _ _ (((abelian.exact_iff _ _).1 (hD.col_exact₁ 0)).2)) ≫\n inv (abelian.factor_thru_image ((0,0) ⟶[D] (1,0))) }\n\nlemma ker_row₁_to_top_left_mono (hD : is_snake_input D) : mono (ker_row₁_to_top_left hD) :=\nbegin\n suffices : mono ((limits.kernel.lift _ _ (ker_row₁_to_row₂ hD)) ≫\n (limits.kernel.lift _ _ (((abelian.exact_iff _ _).1 (hD.col_exact₁ 0)).2))),\n { letI := this, exact mono_comp _ _, },\n exact mono_comp _ _\nend\n\nlemma ker_row₁_to_top_left_comp_eq_ι (hD : is_snake_input D) : ker_row₁_to_top_left hD ≫\n ((0,0) ⟶[D] (1,0)) = kernel.ι ((1,0) ⟶[D] (1,1)) :=\nbegin\n letI := hD.col_mono 0,\n have : inv (abelian.factor_thru_image ((0,0) ⟶[D] (1,0))) ≫ ((0,0) ⟶[D] (1,0)) =\n category_theory.abelian.image.ι _ := by simp,\n rw [ker_row₁_to_top_left, category.assoc, category.assoc, this],\n simp\nend\n\nlemma long_row₀_exact (hD : is_snake_input D) :\n exact (ker_row₁_to_top_left hD) ((0,0) ⟶[D] (0,1)) :=\nbegin\n refine abelian.pseudoelement.exact_of_pseudo_exact _ _ ⟨λ a, _, λ a ha, _⟩,\n { refine (injective_iff_mono _).2 (hD.col_mono _) _,\n rw [apply_zero, ← abelian.pseudoelement.comp_apply, ← D.map_comp, map_eq hD\n ((hom (0, 0) (0, 1)) ≫ (hom _ (1, 1))) ((hom _ (1, 0)) ≫ (hom _ _)), D.map_comp,\n ← abelian.pseudoelement.comp_apply, ← category.assoc, ker_row₁_to_top_left_comp_eq_ι hD,\n abelian.pseudoelement.comp_apply, kernel_ι_apply] },\n { let b := ((0,0) ⟶[D] (1,0)) a,\n have hb : ((1,0) ⟶[D] (1,1)) b = 0,\n { rw [← abelian.pseudoelement.comp_apply, ← D.map_comp, map_eq hD\n ((hom (0, 0) (1, 0)) ≫ (hom _ (1, 1))) ((hom _ (0, 1)) ≫ (hom _ _)), D.map_comp,\n abelian.pseudoelement.comp_apply, ha, apply_zero] },\n obtain ⟨c, hc⟩ := exists_of_exact category_theory.exact_kernel_ι _ hb,\n refine ⟨c, (injective_iff_mono _).2 (hD.col_mono _) _⟩,\n rw [← abelian.pseudoelement.comp_apply, ker_row₁_to_top_left_comp_eq_ι hD, hc] }\nend\n\nlemma row₁_middle_to_coker_row₂_eq_zero (hD : is_snake_input D) :\n ((1,1) ⟶[D] (1,2)) ≫ ((1,2) ⟶[D] (2,2)) ≫ (limits.cokernel.π ((2,1) ⟶[D] (2,2))) = 0 :=\nbegin\n refine zero_morphism_ext _ (λ a, _),\n rw [← category.assoc, abelian.pseudoelement.comp_apply, ← D.map_comp, map_eq hD\n ((hom (1, 1) (1, 2)) ≫ (hom _ (2, 2))) ((hom _ (2, 1)) ≫ (hom _ _)), D.map_comp,\n ← abelian.pseudoelement.comp_apply],\n simp,\nend\n\nlemma row₁_to_coker_row₂_eq_zero (hD : is_snake_input D) :\n ((1,2) ⟶[D] (2,2)) ≫ (limits.cokernel.π ((2,1) ⟶[D] (2,2))) = 0 :=\nbegin\n letI := hD.row_epi,\n have := row₁_middle_to_coker_row₂_eq_zero hD,\n rw [← limits.comp_zero] at this,\n exact (cancel_epi _).1 this\nend\n\nlemma ker_col₂_to_coker_row₂_eq_zero (hD : is_snake_input D) :\n kernel.ι ((2,2) ⟶[D] (3,2)) ≫ (limits.cokernel.π ((1,2) ⟶[D] (2,2))) = 0 :=\nbegin\n refine zero_morphism_ext _ (λ a, _),\n obtain ⟨c, hc⟩ := exists_of_exact (hD.col_exact₂ 2) (kernel.ι (_ ⟶[D] _) a) (kernel_ι_apply _ _),\n rw [abelian.pseudoelement.comp_apply, ← hc, cokernel_π_apply]\nend\n\ndef bottom_right_to_coker_row₂ (hD : is_snake_input D) :\n D.obj (3, 2) ⟶ cokernel ((2,1) ⟶[D] (2,2)) :=\nby { letI := hD.col_epi 2, exact\n (inv (abelian.factor_thru_coimage ((2,2) ⟶[D] (3,2)))) ≫\n (limits.cokernel.desc _ _ (ker_col₂_to_coker_row₂_eq_zero hD)) ≫\n (limits.cokernel.desc _ _ (row₁_to_coker_row₂_eq_zero hD)) }\n\nlemma bottom_right_to_coker_row₂_epi (hD : is_snake_input D) : epi (bottom_right_to_coker_row₂ hD) :=\nbegin\n suffices : epi ((limits.cokernel.desc _ _ (ker_col₂_to_coker_row₂_eq_zero hD)) ≫\n (limits.cokernel.desc _ _ (row₁_to_coker_row₂_eq_zero hD))),\n { letI := this, exact epi_comp _ _ },\n exact epi_comp _ _,\nend\n\nlemma bottom_right_to_coker_row₂_comp_eq_π (hD : is_snake_input D) : ((2,2) ⟶[D] (3,2)) ≫\n bottom_right_to_coker_row₂ hD = cokernel.π ((2,1) ⟶[D] (2,2)) :=\nbegin\n letI := hD.col_epi 2,\n have : ((2,2) ⟶[D] (3,2)) ≫ inv (abelian.factor_thru_coimage ((2,2) ⟶[D] (3,2))) =\n category_theory.abelian.coimage.π _ := by simp,\n rw [bottom_right_to_coker_row₂, ← category.assoc, ← category.assoc, this],\n simp\nend\n\nlemma long_row₃_exact (hD : is_snake_input D) :\n exact ((3,1) ⟶[D] (3,2)) (bottom_right_to_coker_row₂ hD) :=\nbegin\n refine abelian.pseudoelement.exact_of_pseudo_exact _ _ ⟨λ a, _, λ a ha, _⟩,\n { letI := hD.col_epi 1,\n obtain ⟨b, hb⟩ := abelian.pseudoelement.pseudo_surjective_of_epi ((2,1) ⟶[D] (3,1)) a,\n rw [← hb, ← abelian.pseudoelement.comp_apply, ← abelian.pseudoelement.comp_apply,\n ← category.assoc, ← D.map_comp, map_eq hD ((hom (2, 1) (3, 1)) ≫ (hom _ (3, 2)))\n ((hom _ (2, 2)) ≫ (hom _ _)), D.map_comp, category.assoc,\n bottom_right_to_coker_row₂_comp_eq_π hD, (snake_diagram.exact_self_cokernel_π _).w,\n zero_apply], },\n { letI := hD.col_epi 2,\n obtain ⟨b, hb⟩ := abelian.pseudoelement.pseudo_surjective_of_epi ((2,2) ⟶[D] (3,2)) a,\n rw [← hb, ← abelian.pseudoelement.comp_apply, bottom_right_to_coker_row₂_comp_eq_π hD] at ha,\n obtain ⟨c, hc⟩ := exists_of_exact (abelian.exact_cokernel _) _ ha,\n refine ⟨((2,1) ⟶[D] (3,1)) c, _⟩,\n rw [← hb, ← hc, ← abelian.pseudoelement.comp_apply, ← abelian.pseudoelement.comp_apply,\n ← D.map_comp, map_eq hD ((hom (2, 1) (3, 1)) ≫ (hom _ (3, 2))) ((hom _ (2, 2)) ≫ (hom _ _)),\n D.map_comp] }\nend\n\nend long_snake\n\nexample (hD : is_snake_input D) (f : (o 1 0) ⟶ (o 2 2)) : D.map f = 0 := hD.hom_eq_zero₂ f\n\nsection delta\n\nvariable (hD : is_snake_input D)\ninclude hD\n\ndef to_top_right_kernel : D.obj (1,0) ⟶ kernel ((1,1) ⟶[D] (2,2)) :=\nkernel.lift _ (_ ⟶[D] _)\nbegin\n rw ← D.map_comp,\n change D.map (hom (1,0) (2,0) ≫ hom (2,0) (2,1) ≫ hom (2,1) (2,2)) = 0,\n simp [hD.row_exact₂.1],\nend\n\ndef cokernel_to_top_right_kernel_to_right_kernel :\n cokernel hD.to_top_right_kernel ⟶ kernel ((1,2) ⟶[D] (2,2)) :=\ncokernel.desc _ (kernel.lift _ (kernel.ι _ ≫ (_ ⟶[D] _)) begin\n rw [category.assoc, ← D.map_comp],\n have : hom (1,1) (1,2) ≫ hom (1,2) (2,2) = hom (1,1) (2,2) := rfl,\n rw this, clear this,\n simp [abelian.pseudoelement.comp_apply],\nend) begin\n dsimp only [to_top_right_kernel],\n ext a,\n apply_fun kernel.ι (D.map (hom (1, 2) (2, 2))),\n swap, { rw injective_iff_mono, apply_instance },\n simp [← abelian.pseudoelement.comp_apply, hD.row_exact₁.1],\nend\n\ninstance : mono hD.cokernel_to_top_right_kernel_to_right_kernel :=\nbegin\n apply mono_of_zero_of_map_zero,\n intros a h,\n obtain ⟨b,rfl⟩ := cokernel_π_surjective _ a,\n rw ← eq_zero_iff_kernel_ι_eq_zero at h,\n simp [← abelian.pseudoelement.comp_apply, cokernel_to_top_right_kernel_to_right_kernel] at h,\n simp [ abelian.pseudoelement.comp_apply] at h,\n have : ∃ c, ((1,0) ⟶[D] (1,1)) c = kernel.ι ((1,1) ⟶[D] (2,2)) b,\n { apply exists_of_exact _ _ h,\n exact hD.row_exact₁ },\n obtain ⟨c,hc⟩ := this,\n let f : cokernel hD.to_top_right_kernel ⟶ cokernel ((1,0) ⟶[D] (1,1)) :=\n cokernel.desc _ _ _,\n swap, { refine kernel.ι _ ≫ cokernel.π _ },\n swap, { simp [to_top_right_kernel] },\n apply_fun f,\n swap, {\n rw injective_iff_mono,\n apply mono_of_zero_of_map_zero,\n intros a ha,\n dsimp [f] at ha,\n obtain ⟨a,rfl⟩ := cokernel_π_surjective _ a,\n simp [← abelian.pseudoelement.comp_apply] at ha,\n simp [abelian.pseudoelement.comp_apply] at ha,\n have : ∃ c, ((1,0) ⟶[D] (1,1)) c = kernel.ι ((1,1) ⟶[D] (2,2)) a,\n { apply exists_of_exact _ _ ha,\n apply snake_diagram.exact_self_cokernel_π, },\n obtain ⟨c,hc⟩ := this,\n have : hD.to_top_right_kernel c = a,\n { apply_fun kernel.ι ((1,1) ⟶[D] (2,2)),\n swap, { rw injective_iff_mono, apply_instance },\n dsimp [to_top_right_kernel],\n simp [← abelian.pseudoelement.comp_apply],\n erw kernel.lift_ι,\n exact hc },\n simp [← this] },\n dsimp only [f],\n simp [← abelian.pseudoelement.comp_apply, to_top_right_kernel],\n simp [abelian.pseudoelement.comp_apply, ← hc],\nend .\n\ninstance : epi hD.cokernel_to_top_right_kernel_to_right_kernel :=\nbegin\n apply epi_of_pseudo_surjective,\n intros a,\n let a' := kernel.ι ((1,2) ⟶[D] (2,2)) a,\n obtain ⟨b,hb⟩ : ∃ b, ((1,1) ⟶[D] (1,2)) b = a',\n { suffices : function.surjective ((1,1) ⟶[D] (1,2)), by apply this,\n rw surjective_iff_epi,\n apply hD.row_epi },\n obtain ⟨c,hc⟩ : ∃ c, kernel.ι ((1,1) ⟶[D] (2,2)) c = b,\n { have : exact (kernel.ι ((1,1) ⟶[D] (2,2))) ((1,1) ⟶[D] (2,2)) := exact_kernel_ι,\n apply exists_of_exact this,\n rw [(show hom (1,1) (2,2) = hom (1,1) (1,2) ≫ hom (1,2) (2,2), by refl),\n D.map_comp, abelian.pseudoelement.comp_apply, hb],\n dsimp only [a'],\n simp },\n use cokernel.π hD.to_top_right_kernel c,\n apply_fun kernel.ι ((1,2) ⟶[D] (2,2)),\n swap, { rw injective_iff_mono, apply_instance },\n dsimp only [to_top_right_kernel, cokernel_to_top_right_kernel_to_right_kernel],\n simp [← abelian.pseudoelement.comp_apply],\n change _ = a',\n rw ← hb,\n simp [← hb, abelian.pseudoelement.comp_apply, ← hc],\nend .\n\ninstance : is_iso hD.cokernel_to_top_right_kernel_to_right_kernel :=\nis_iso_of_mono_of_epi _\n\ndef bottom_left_cokernel_to : cokernel ((1,0) ⟶[D] (2,1)) ⟶ D.obj (2,2) :=\ncokernel.desc _ (_ ⟶[D] _)\nbegin\n rw ← D.map_comp,\n change D.map (hom (1,0) (2,0) ≫ hom (2,0) (2,1) ≫ hom (2,1) (2,2)) = 0,\n simp_rw D.map_comp,\n simp [hD.row_exact₂.1],\nend\n\ndef left_cokernel_to_kernel_bottom_left_cokernel_to :\n cokernel ((1,0) ⟶[D] (2,0)) ⟶ kernel hD.bottom_left_cokernel_to :=\nkernel.lift _ (cokernel.desc _ ((_ ⟶[D] _) ≫ cokernel.π _) begin\n rw [← category.assoc, ← D.map_comp],\n have : hom (1,0) (2,0) ≫ hom (2,0) (2,1) = hom _ _ := rfl,\n rw this, clear this,\n simp [abelian.pseudoelement.comp_apply],\nend) begin\n dsimp only [bottom_left_cokernel_to],\n ext a,\n obtain ⟨b,rfl⟩ : ∃ b, cokernel.π ((1,0) ⟶[D] (2,0)) b = a,\n { have : function.surjective (cokernel.π ((1,0) ⟶[D] (2,0))),\n by { rw surjective_iff_epi, apply_instance },\n apply this },\n simp [← abelian.pseudoelement.comp_apply, hD.row_exact₂.1],\nend\n\ninstance : mono hD.left_cokernel_to_kernel_bottom_left_cokernel_to :=\nbegin\n apply mono_of_zero_of_map_zero,\n intros a ha,\n obtain ⟨a,rfl⟩ := cokernel_π_surjective _ a,\n dsimp [left_cokernel_to_kernel_bottom_left_cokernel_to] at ha,\n rw ← eq_zero_iff_kernel_ι_eq_zero at ha,\n simp [← abelian.pseudoelement.comp_apply] at ha,\n simp [abelian.pseudoelement.comp_apply] at ha,\n obtain ⟨c,hc⟩ : ∃ c, ((1,0) ⟶[D] (2,1)) c = ((2,0) ⟶[D] (2,1)) a,\n { apply exists_of_exact _ _ ha,\n apply abelian.exact_cokernel, },\n have : ((1,0) ⟶[D] (2,0)) c = a,\n { apply_fun ((2,0) ⟶[D] (2,1)),\n swap, { rw injective_iff_mono, apply hD.row_mono },\n simpa only [← hc, ← abelian.pseudoelement.comp_apply, ← D.map_comp] },\n simp [← this],\nend .\n\ninstance : epi hD.left_cokernel_to_kernel_bottom_left_cokernel_to :=\nbegin\n apply epi_of_pseudo_surjective,\n intros a,\n let a' := kernel.ι hD.bottom_left_cokernel_to a,\n obtain ⟨b,hb⟩ := cokernel_π_surjective _ a',\n have : ((2,1) ⟶[D] (2,2)) b = 0,\n { apply_fun hD.bottom_left_cokernel_to at hb,\n dsimp [a', bottom_left_cokernel_to] at hb,\n simpa [← abelian.pseudoelement.comp_apply] using hb },\n obtain ⟨c,hc⟩ : ∃ c, ((2,0) ⟶[D] (2,1)) c = b,\n { apply exists_of_exact _ _ this,\n exact hD.row_exact₂ },\n use cokernel.π ((1,0) ⟶[D] (2,0)) c,\n apply_fun kernel.ι hD.bottom_left_cokernel_to,\n swap, { rw injective_iff_mono, apply_instance },\n change _ = a',\n simp [← abelian.pseudoelement.comp_apply, ← hb,\n left_cokernel_to_kernel_bottom_left_cokernel_to],\n simp [abelian.pseudoelement.comp_apply, hc],\nend\n\ninstance : is_iso hD.left_cokernel_to_kernel_bottom_left_cokernel_to :=\nis_iso_of_mono_of_epi _\n\ndef δ_aux : cokernel hD.to_top_right_kernel ⟶ kernel hD.bottom_left_cokernel_to :=\ncokernel.desc _ (kernel.lift _ (kernel.ι _ ≫ (_ ⟶[D] _) ≫ cokernel.π _) begin\n dsimp only [bottom_left_cokernel_to],\n simp,\n rw ← D.map_comp,\n have : hom (1,1) (2,1) ≫ hom (2,1) (2,2) = hom _ _ := rfl,\n rw this,\n simp [abelian.pseudoelement.comp_apply],\nend)\nbegin\n dsimp only [to_top_right_kernel],\n simp,\n ext,\n apply_fun kernel.ι hD.bottom_left_cokernel_to,\n swap, { rw injective_iff_mono, apply_instance },\n simp [← abelian.pseudoelement.comp_apply],\n rw [← category.assoc, ← D.map_comp],\n have : hom (1,0) (1,1) ≫ hom (1,1) (2,1) = hom _ _, refl, rw this, clear this,\n simp [abelian.pseudoelement.comp_apply],\nend\n\ndef to_kernel : D.obj (0,2) ⟶ kernel ((1,2) ⟶[D] (2,2)) :=\nkernel.lift _ (_ ⟶[D] _) (hD.col_exact₁ _).1\n\ninstance : mono hD.to_kernel :=\nbegin\n dsimp [to_kernel],\n haveI : mono ((0,2) ⟶[D] (1,2)) := hD.col_mono _,\n apply_instance,\nend\n\ninstance : epi hD.to_kernel :=\nkernel.lift.epi (hD.col_exact₁ _)\n\ninstance : is_iso hD.to_kernel :=\nis_iso_of_mono_of_epi _\n\ndef cokernel_to : cokernel ((1,0) ⟶[D] (2,0)) ⟶ D.obj (3,0) :=\ncokernel.desc _ (_ ⟶[D] _) (hD.col_exact₂ _).1\n\ninstance : mono hD.cokernel_to :=\nabelian.category_theory.limits.cokernel.desc.category_theory.mono _ _ (hD.col_exact₂ _)\n\ninstance : epi hD.cokernel_to :=\nbegin\n dsimp [cokernel_to],\n haveI : epi ((2,0) ⟶[D] (3,0)) := hD.col_epi _,\n apply_instance,\nend\n\ninstance : is_iso hD.cokernel_to :=\nis_iso_of_mono_of_epi _\n\ndef δ : D.obj (0,2) ⟶ D.obj (3,0) :=\n hD.to_kernel ≫ inv hD.cokernel_to_top_right_kernel_to_right_kernel ≫ -- <-- this is an iso\n hD.δ_aux ≫ -- <- this is the key\n inv hD.left_cokernel_to_kernel_bottom_left_cokernel_to ≫ hD.cokernel_to -- <-- this is an iso\n\ndef to_δ_aux : D.obj (0,1) ⟶ cokernel hD.to_top_right_kernel :=\nkernel.lift _ ((0,1) ⟶[D] (1,1)) begin\n rw [(show (hom (1,1) (2,2) = hom (1,1) (2,1) ≫ hom _ _), by refl), D.map_comp,\n ← category.assoc, (hD.col_exact₁ _).1],\n simp,\nend ≫ cokernel.π _\n\ndef from_δ_aux : kernel hD.bottom_left_cokernel_to ⟶ D.obj (3,1) :=\nkernel.ι _ ≫ cokernel.desc _ ((2,1) ⟶[D] (3,1)) begin\n rw [(show hom (1,0) (2,1) = hom (1,0) (1,1) ≫ hom (1,1) (2,1), by refl),\n D.map_comp, category.assoc, (hD.col_exact₂ _).w],\n simp,\nend\n\ntheorem exact_to_δ_aux : exact hD.to_δ_aux hD.δ_aux :=\nbegin\n apply exact_of_pseudo_exact,\n split,\n { intros a,\n dsimp [δ_aux, to_δ_aux],\n rw ← eq_zero_iff_kernel_ι_eq_zero,\n simp only [←abelian.pseudoelement.comp_apply, cokernel.π_desc,\n kernel.lift_ι_assoc, category.assoc, kernel.lift_ι],\n simp [abelian.pseudoelement.comp_apply, eq_zero_of_exact (hD.col_exact₁ _)] },\n { intros b hb,\n obtain ⟨b,rfl⟩ := cokernel_π_surjective _ b,\n dsimp [δ_aux] at hb,\n rw ← eq_zero_iff_kernel_ι_eq_zero at hb,\n simp only [←abelian.pseudoelement.comp_apply, cokernel.π_desc, kernel.lift_ι] at hb,\n simp only [abelian.pseudoelement.comp_apply] at hb,\n let b' := kernel.ι ((1,1) ⟶[D] (2,2)) b,\n obtain ⟨c,hc⟩ := exists_of_cokernel_π_eq_zero _ _ hb, clear hb,\n change _ = ((1,1) ⟶[D] (2,1)) b' at hc,\n rw [(show hom (1,0) (2,1) = hom (1,0) (1,1) ≫ hom _ _, by refl), D.map_comp,\n abelian.pseudoelement.comp_apply] at hc,\n obtain ⟨z,h1,h2⟩ := sub_of_eq_image _ _ _ hc.symm, clear hc,\n specialize h2 _ ((1,1) ⟶[D] (1,2)) (eq_zero_of_exact hD.row_exact₁ _),\n obtain ⟨w,hw⟩ : ∃ w, ((0,1) ⟶[D] (1,1)) w = z := exists_of_exact (hD.col_exact₁ _) _ h1,\n clear h1,\n use w,\n dsimp only [b'] at h2,\n dsimp only [to_δ_aux],\n simp only [abelian.pseudoelement.comp_apply],\n apply_fun hD.cokernel_to_top_right_kernel_to_right_kernel,\n swap, { rw injective_iff_mono, apply_instance },\n dsimp only [cokernel_to_top_right_kernel_to_right_kernel],\n simp only [←abelian.pseudoelement.comp_apply, cokernel.π_desc, category.assoc],\n simp only [abelian.pseudoelement.comp_apply],\n apply_fun kernel.ι ((1,2) ⟶[D] (2,2)),\n swap, { rw injective_iff_mono, apply_instance },\n simp only [←abelian.pseudoelement.comp_apply, kernel.lift_ι_assoc,\n category.assoc, kernel.lift_ι],\n simp only [abelian.pseudoelement.comp_apply],\n rw [hw, h2] }\nend\n\ntheorem exact_from_δ_aux : exact hD.δ_aux hD.from_δ_aux :=\nbegin\n apply exact_of_pseudo_exact,\n split,\n { intros a,\n dsimp [δ_aux, from_δ_aux],\n obtain ⟨a,rfl⟩ := cokernel_π_surjective _ a,\n simp only [←abelian.pseudoelement.comp_apply,\n cokernel.π_desc, kernel.lift_ι_assoc, category.assoc],\n simp [abelian.pseudoelement.comp_apply, eq_zero_of_exact (hD.col_exact₂ _)] },\n { intros b hb,\n let b' := kernel.ι hD.bottom_left_cokernel_to b,\n obtain ⟨c,hc⟩ := cokernel_π_surjective _ b',\n simp only [from_δ_aux, abelian.pseudoelement.comp_apply] at hb,\n change cokernel.desc ((1,0) ⟶[D] (2,1)) _ _ b' = 0 at hb,\n rw ← hc at hb,\n simp only [←abelian.pseudoelement.comp_apply, cokernel.π_desc] at hb,\n obtain ⟨d,hd⟩ : ∃ d, ((1,1) ⟶[D] (2,1)) d = c := exists_of_exact (hD.col_exact₂ _) _ hb,\n obtain ⟨e,he⟩ : ∃ e, kernel.ι ((1,1) ⟶[D] (2,2)) e = d,\n { apply exists_of_exact _ _ (_ : ((1,1) ⟶[D] (2,2)) d = 0),\n { apply exact_kernel_ι },\n dsimp [b'] at hc,\n apply_fun hD.bottom_left_cokernel_to at hc,\n simp only [bottom_left_cokernel_to, ←abelian.pseudoelement.comp_apply, cokernel.π_desc] at hc,\n rw [(show hom (1,1) (2,2) = hom (1,1) (2,1) ≫ hom (2,1) (2,2), by refl), D.map_comp,\n abelian.pseudoelement.comp_apply, hd, hc],\n simp only [abelian.pseudoelement.comp_apply],\n change hD.bottom_left_cokernel_to (kernel.ι hD.bottom_left_cokernel_to b) = 0,\n apply kernel_ι_apply },\n use cokernel.π hD.to_top_right_kernel e,\n apply_fun kernel.ι hD.bottom_left_cokernel_to,\n swap, { rw injective_iff_mono, apply_instance },\n change _ = b',\n dsimp [δ_aux],\n simp only [←abelian.pseudoelement.comp_apply, cokernel.π_desc, kernel.lift_ι],\n simp only [abelian.pseudoelement.comp_apply],\n rw [he, hd, hc] }\nend\n\ntheorem exact_to_δ : exact ((0,1) ⟶[D] (0,2)) hD.δ :=\nbegin\n dsimp [δ],\n rw [exact_is_iso_iff, exact_is_iso_iff, exact_comp_iso],\n convert hD.exact_to_δ_aux using 1,\n rw is_iso.comp_inv_eq,\n dsimp [to_kernel, to_δ_aux, cokernel_to_top_right_kernel_to_right_kernel],\n ext,\n simp only [cokernel.π_desc, kernel.lift_ι_assoc, category.assoc, kernel.lift_ι],\n simpa only [← D.map_comp],\nend\n\ntheorem exact_from_δ : exact hD.δ ((3,0) ⟶[D] (3,1)) :=\nbegin\n dsimp [δ],\n rw [← category.assoc, ← category.assoc, ← exact_is_iso_iff, exact_iso_comp],\n convert hD.exact_from_δ_aux using 1,\n rw [category.assoc, is_iso.inv_comp_eq],\n dsimp [cokernel_to, left_cokernel_to_kernel_bottom_left_cokernel_to, from_δ_aux],\n ext,\n simp only [cokernel.π_desc, kernel.lift_ι_assoc, cokernel.π_desc_assoc, category.assoc],\n simpa only [← D.map_comp],\nend\n\nend delta\n\nsection delta_spec\n\nvariables (hD : is_snake_input D)\n\ndef to_kernel' : kernel ((1,1) ⟶[D] (2,2)) ⟶ D.obj (0,2) :=\nkernel.lift _ (kernel.ι _ ≫ D.map (hom (1,1) (1,2))) begin\n erw [category.assoc, ← D.map_comp, kernel.condition],\nend ≫ inv hD.to_kernel\n\ninstance to_kernel_epi : epi hD.to_kernel' :=\nbegin\n dsimp [to_kernel'],\n apply_with epi_comp { instances := ff }, swap, apply_instance,\n haveI : epi ((1,1) ⟶[D] (1,2)) := hD.row_epi,\n replace hh := pseudo_surjective_of_epi ((1,1) ⟶[D] (1,2)),\n apply epi_of_pseudo_surjective,\n intros t,\n obtain ⟨s,hs⟩ := hh (kernel.ι ((1,2) ⟶[D] (2,2)) t),\n obtain ⟨w,hw⟩ : ∃ w, kernel.ι ((1,1) ⟶[D] (2,2)) w = s,\n { have : exact (kernel.ι ((1,1) ⟶[D] (2,2))) ((1,1) ⟶[D] (2,2)) :=\n exact_kernel_ι,\n replace this := pseudo_exact_of_exact this,\n apply this.2,\n rw [(show (hom (1,1) (2,2)) = hom (1,1) (1,2) ≫ hom (1,2) (2,2), by refl),\n functor.map_comp, abelian.pseudoelement.comp_apply, hs,\n ← abelian.pseudoelement.comp_apply, kernel.condition,\n abelian.pseudoelement.zero_apply] },\n use w,\n apply abelian.pseudoelement.pseudo_injective_of_mono\n (kernel.ι ((1,2) ⟶[D] (2,2))),\n rw [← hs, ← abelian.pseudoelement.comp_apply, kernel.lift_ι,\n abelian.pseudoelement.comp_apply, hw],\nend\n\ndef cokernel_to' : D.obj (3,0) ⟶ cokernel ((1,0) ⟶[D] (2,1)) :=\ninv hD.cokernel_to ≫ cokernel.desc _ (D.map (hom (2,0) (2,1)) ≫ cokernel.π _) begin\n erw [← category.assoc, ← D.map_comp, cokernel.condition],\nend\n\ninstance cokernel_to'_mono : mono hD.cokernel_to' := begin\n dsimp [cokernel_to'],\n apply_with mono_comp { instances := ff }, apply_instance,\n apply abelian.pseudoelement.mono_of_zero_of_map_zero,\n intros a ha,\n obtain ⟨b,rfl⟩ : ∃ b, cokernel.π ((1,0) ⟶[D] (2,0)) b = a,\n { apply abelian.pseudoelement.pseudo_surjective_of_epi },\n rw [← abelian.pseudoelement.comp_apply, cokernel.π_desc,\n abelian.pseudoelement.comp_apply] at ha,\n obtain ⟨c,hc⟩ : ∃ c, ((1,0) ⟶[D] (2,1)) c = ((2,0) ⟶[D] (2,1)) b,\n { have : exact ((1,0) ⟶[D] (2,1)) (cokernel.π _) := abelian.exact_cokernel _,\n replace this := pseudo_exact_of_exact this,\n apply this.2,\n exact ha },\n have hc' : ((1,0) ⟶[D] (2,0)) c = b,\n { haveI : mono ((2,0) ⟶[D] (2,1)) := hD.row_mono,\n apply abelian.pseudoelement.pseudo_injective_of_mono ((2,0) ⟶[D] (2,1)),\n rw [← abelian.pseudoelement.comp_apply, ← D.map_comp],\n exact hc },\n rw [← hc', ← abelian.pseudoelement.comp_apply, cokernel.condition,\n abelian.pseudoelement.zero_apply],\nend\n\nlemma δ_spec : hD.to_kernel' ≫ hD.δ ≫ hD.cokernel_to' =\n kernel.ι _ ≫ D.map (hom (1,1) (2,1)) ≫ cokernel.π _ :=\nbegin\n dsimp only [is_snake_input.δ ,is_snake_input.to_kernel', is_snake_input.cokernel_to'],\n simp only [category.assoc, is_iso.hom_inv_id_assoc, is_iso.inv_hom_id_assoc],\n dsimp only [is_snake_input.cokernel_to_top_right_kernel_to_right_kernel],\n dsimp only [is_snake_input.left_cokernel_to_kernel_bottom_left_cokernel_to],\n dsimp only [is_snake_input.δ_aux],\n let t := _, change _ ≫ _ ≫ _ ≫ t = _,\n have ht : t = kernel.ι _,\n { dsimp [t],\n rw is_iso.inv_comp_eq,\n apply coequalizer.hom_ext,\n simp only [cokernel.π_desc, category.assoc, kernel.lift_ι, cokernel.π_desc_assoc] },\n rw ht, clear ht, clear t,\n let t := _, change t ≫ _ = _,\n let s := _, change t ≫ s ≫ _ = _,\n have hst : t ≫ s = cokernel.π _,\n { dsimp [s,t],\n rw is_iso.comp_inv_eq,\n apply equalizer.hom_ext,\n simp only [cokernel.π_desc] },\n rw reassoc_of hst, clear hst, clear s, clear t,\n simp only [cokernel.π_desc_assoc, kernel.lift_ι],\nend\n\nlemma eq_δ_of_spec (e : D.obj (0,2) ⟶ D.obj (3,0))\n (he : hD.to_kernel' ≫ e ≫ hD.cokernel_to' = kernel.ι _ ≫\n D.map (hom (1,1) (2,1)) ≫ cokernel.π _) :\n e = hD.δ :=\nbegin\n rw ← cancel_mono hD.cokernel_to',\n rw ← cancel_epi hD.to_kernel',\n rw [he, δ_spec],\nend\n\nend delta_spec\n\nlocal attribute [instance] limits.has_zero_object.has_zero\n\nlemma exact_zero_to_ker_row₁_to_top_left (hD : is_snake_input D) :\n exact (0 : 0 ⟶ kernel ((1,0) ⟶[D] (1,1))) hD.ker_row₁_to_top_left :=\nbegin\n haveI : mono hD.ker_row₁_to_top_left := ker_row₁_to_top_left_mono hD,\n apply exact_zero_left_of_mono,\nend\n\nlemma exact_bottom_right_to_coker_row₂_to_zero (hD : is_snake_input D) :\n exact hD.bottom_right_to_coker_row₂ (0 : cokernel ((2,1) ⟶[D] (2,2)) ⟶ 0) :=\nbegin\n rw ← epi_iff_exact_zero_right,\n apply bottom_right_to_coker_row₂_epi hD,\nend\n\nlemma ten_term_exact_seq (hD : is_snake_input D) :\n exact_seq 𝒜 [\n (0 : 0 ⟶ kernel ((1,0) ⟶[D] (1,1))),\n hD.ker_row₁_to_top_left, (0,0) ⟶[D] (0,1), (0,1) ⟶[D] (0,2),\n hD.δ,\n (3,0) ⟶[D] (3,1), (3,1) ⟶[D] (3,2), hD.bottom_right_to_coker_row₂,\n (0 : cokernel ((2,1) ⟶[D] (2,2)) ⟶ 0)] :=\nbegin\n refine exact_seq.cons _ _ hD.exact_zero_to_ker_row₁_to_top_left _ _,\n refine exact_seq.cons _ _ hD.long_row₀_exact _ _,\n refine exact_seq.cons _ _ hD.row_exact₀ _ _,\n refine exact_seq.cons _ _ hD.exact_to_δ _ _,\n refine exact_seq.cons _ _ hD.exact_from_δ _ _,\n refine exact_seq.cons _ _ hD.row_exact₃ _ _,\n refine exact_seq.cons _ _ hD.long_row₃_exact _ _,\n refine exact_seq.cons _ _ hD.exact_bottom_right_to_coker_row₂_to_zero _ _,\n refine exact_seq.single _,\nend\n\nlemma eight_term_exact_seq (hD : is_snake_input D) :\n exact_seq 𝒜 [hD.ker_row₁_to_top_left, (0,0) ⟶[D] (0,1), (0,1) ⟶[D] (0,2),\n hD.δ,\n (3,0) ⟶[D] (3,1), (3,1) ⟶[D] (3,2), hD.bottom_right_to_coker_row₂] :=\nexact_seq.extract hD.ten_term_exact_seq 1 7\n\nlemma six_term_exact_seq (hD : is_snake_input D) :\n exact_seq 𝒜 [(0,0) ⟶[D] (0,1), (0,1) ⟶[D] (0,2), hD.δ, (3,0) ⟶[D] (3,1), (3,1) ⟶[D] (3,2)] :=\nexact_seq.extract hD.eight_term_exact_seq 1 5\n\nend is_snake_input\n\nvariables (𝒜)\n\nstructure snake_input extends snake_diagram ⥤ 𝒜 :=\n(is_snake_input : is_snake_input to_functor)\n\nnamespace snake_input\n\ninstance : category (snake_input 𝒜) := induced_category.category to_functor\n\n@[simps] def proj (x : snake_diagram) : snake_input 𝒜 ⥤ 𝒜 :=\ninduced_functor _ ⋙ (evaluation _ _).obj x\n\ndef mk_of_short_exact_sequence_hom (A B : short_exact_sequence 𝒜) (f : A ⟶ B) :\n snake_input 𝒜 :=\n⟨snake_diagram.mk_of_short_exact_sequence_hom A B f,\nis_snake_input.mk_of_short_exact_sequence_hom A B f⟩\n\ndef kernel_sequence (D : snake_input 𝒜)\n (h1 : mono ((1,0) ⟶[D] (1,1))) (h2 : is_zero (D.obj (3,0))) :\n short_exact_sequence 𝒜 :=\n{ fst := D.obj (0,0),\n snd := D.obj (0,1),\n trd := D.obj (0,2),\n f := (0,0) ⟶[D] (0,1),\n g := (0,1) ⟶[D] (0,2),\n mono' :=\n begin\n letI := h1,\n refine abelian.pseudoelement.mono_of_zero_of_map_zero _ (λ a ha, _),\n obtain ⟨b, hb⟩ := is_snake_input.exists_of_exact\n (is_snake_input.long_row₀_exact D.is_snake_input) a ha,\n rw [← hb],\n simp [is_snake_input.ker_row₁_to_top_left, limits.kernel.ι_of_mono ((1,0) ⟶[D] (1,1))]\n end,\n epi' :=\n begin\n rw (abelian.tfae_epi (D.obj (3,0)) ((0,1) ⟶[D] (0,2))).out 0 2,\n convert D.2.exact_to_δ,\n apply h2.eq_of_tgt,\n end,\n exact' := D.2.row_exact _ }\n\nend snake_input\n\nclass has_snake_lemma :=\n(δ : snake_input.proj 𝒜 (0,2) ⟶ snake_input.proj 𝒜 (3,0))\n(exact_δ : ∀ (D : snake_input 𝒜), exact ((0,1) ⟶[D] (0,2)) (δ.app D))\n(δ_exact : ∀ (D : snake_input 𝒜), exact (δ.app D) ((3,0) ⟶[D.1] (3,1))) -- why can't I write `⟶[D]`\n\nnamespace snake_lemma\n\nvariables [has_snake_lemma 𝒜]\n\nvariables {𝒜}\n\ndef δ (D : snake_input 𝒜) : D.obj (0,2) ⟶ D.obj (3,0) := has_snake_lemma.δ.app D\n\nlemma exact_δ (D : snake_input 𝒜) : exact ((0,1) ⟶[D] (0,2)) (δ D) :=\nhas_snake_lemma.exact_δ D\n\nlemma δ_exact (D : snake_input 𝒜) : exact (δ D) ((3,0) ⟶[D] (3,1)) :=\nhas_snake_lemma.δ_exact D\n\nend snake_lemma\n\nend\n\nend category_theory", "meta": {"author": "jjaassoonn", "repo": "flat", "sha": "bab2f5c18fdee0042680c31b0350c69d241e9a82", "save_path": "github-repos/lean/jjaassoonn-flat", "path": "github-repos/lean/jjaassoonn-flat/flat-bab2f5c18fdee0042680c31b0350c69d241e9a82/src/lte/for_mathlib/snake_lemma.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4186969093556867, "lm_q2_score": 0.02064593168077052, "lm_q1q2_score": 0.008644387785507274}} {"text": "import data_util.basic\n\nsection LeanStep\n\n\n@[derive has_to_format]\nmeta structure LeanStepDatapoint : Type :=\n(decl_nm : name)\n(decl_tp : expr)\n(hyps : list (expr × expr))\n(hyps_mask : list bool) -- TODO(): convert hyps_mask and decl_premises_mask into name_sets?\n(decl_premises : list (expr × expr)) -- this is computed once and for all before beginning the recursion\n(decl_premises_mask : list bool)\n(goal : expr)\n(proof_term : expr)\n(result : expr) -- global proof term with metavariable in place of the subterm at point, for skip-tree tasks; can be computed using `expr.replace`; optionally, use meta.expr.lens and track this along with the binders\n(next_lemma : option (expr × expr))\n(goal_is_prop : bool)\n\nnotation `to_tactic_json` := has_to_tactic_json.to_tactic_json\n\n/- TODO(): optionally use `with_verbose` -/\nmeta instance : has_to_tactic_json expr :=\n⟨λ e, (json.of_string ∘ format.to_string ∘ format.flatten) <$> tactic.pp e⟩\n\nmeta instance has_to_tactic_json_of_has_coe_json {α} [has_coe α json] : has_to_tactic_json α :=\n⟨λ x, pure ↑x⟩\n\nmeta instance has_to_tactic_json_list {α} [has_to_tactic_json α] : has_to_tactic_json (list α) :=\nlet fn : list α → tactic json := λ xs, json.array <$> (xs.mmap to_tactic_json) in\n⟨fn⟩\n\nmeta instance has_to_tactic_json_prod {α β} [has_to_tactic_json α] [has_to_tactic_json β] : has_to_tactic_json (α × β) :=\nlet fn : α × β → tactic json := λ ⟨a,b⟩,\njson.array <$> ((::) <$> to_tactic_json a <*> pure <$> to_tactic_json b)\nin ⟨fn⟩\n\nmeta def name.to_json' : name → json := λ nm, json.of_string nm.to_string\n\nmeta instance has_to_tactic_json_option {α} [has_to_tactic_json α] : has_to_tactic_json (option α) :=\nlet fn : option α → tactic json := λ x,\n match x with\n | (some val) := to_tactic_json val\n | none := pure $ json.null\n end in ⟨fn⟩\n\nmeta instance : has_to_tactic_json LeanStepDatapoint :=\nlet fn : LeanStepDatapoint → tactic json := λ x, do {\n tactic.set_nat_option `pp.max_depth 128,\n tactic.set_nat_option `pp.max_steps 10000,\n match x with\n | ⟨decl_nm, decl_tp, hyps, hyps_mask,\n decl_premises, decl_premises_mask,\n goal, proof_term, result, next_lemma, goal_is_prop⟩ := do {\n json.object <$> do {\n decl_tp_json ← to_tactic_json decl_tp,\n hyps_json ← to_tactic_json hyps,\n hyps_mask_json ← to_tactic_json hyps_mask,\n decl_premises_json ← to_tactic_json decl_premises,\n decl_premises_mask_json ← to_tactic_json decl_premises_mask,\n goal_json ← to_tactic_json goal,\n proof_term_json ← to_tactic_json proof_term,\n result_json ← to_tactic_json result,\n verbose_goal_json ← with_verbose $ to_tactic_json goal,\n verbose_result_json ← with_verbose $ to_tactic_json result,\n verbose_proof_term_json ← with_verbose $ to_tactic_json proof_term,\n next_lemma_json ← to_tactic_json next_lemma,\n pure $\n [\n (\"decl_nm\", decl_nm.to_json')\n , (\"decl_tp\", decl_tp_json)\n , (\"hyps\", hyps_json)\n , (\"hyps_mask\", hyps_mask_json)\n , (\"decl_premises\", decl_premises_json)\n , (\"decl_premises_mask\", decl_premises_mask_json)\n , (\"goal\", goal_json)\n , (\"proof_term\", proof_term_json)\n , (\"result\", result_json)\n , (\"next_lemma\", next_lemma_json)\n , (\"goal_is_prop\", goal_is_prop)\n , (\"verbose_proof_term\", verbose_proof_term_json)\n , (\"verbose_goal\", verbose_goal_json)\n , (\"verbose_result\", verbose_result_json)\n ]\n }\n }\n end\n}\nin ⟨fn⟩\n\ndef PREDICT : true := trivial\n\n-- TODO(): test\n-- TODO(): even if this works as intended, it will produce unwanted behavior when trying to replace\n-- local constants, due to variable shadowing, and basically can't be used except for constants\nmeta def expr.replace_with_predict (pf : expr) (subterm : expr) : tactic expr := do\n c ← tactic.mk_const `PREDICT,\n pure $ pf.replace (λ e _, if e.hash = subterm.hash then pure c else none)\nsection replace_at\nopen expr\n\nmeta def expr.replace_at : expr → expr.address → expr → tactic expr\n| e@(var k) addr e' := match addr with\n | [] := pure e'\n | _ := pure e\n end\n| e@(sort l) addr e' := match addr with\n | [] := pure e'\n | _ := pure e\n end\n| e@(mvar _ _ _) addr e' := pure e\n| e@(const nm _) addr e' := match addr with\n | [] := pure e'\n | _ := pure e\n end\n| e@(local_const unique pp bi type) addr e' := match addr with\n | [] := pure e'\n | exc := pure e\n end\n| e@(app e₁ e₂) addr e' := match addr with\n | [] := pure e'\n | (expr.coord.app_fn::xs) := do {\n new_hd ← expr.replace_at e₁ xs e',\n pure $ app new_hd e₂\n}\n | (expr.coord.app_arg::xs) := app e₁ <$> expr.replace_at e₂ xs e'\n | _ := pure e\n end\n| e@(lam var_name b_info var_type body) addr e' := match addr with\n | [] := pure e'\n | (expr.coord.lam_body::xs) := do {\n ⟨[b], new_body⟩ ← tactic.open_n_lambdas e 1,\n flip expr.bind_lambda b <$> (expr.replace_at new_body xs e')\n }\n | _ := pure e\n end\n| e@(pi var_name b_info var_type body) addr e' := match addr with\n | [] := pure e'\n | (expr.coord.pi_body::xs) := do {\n ⟨[b], new_body⟩ ← tactic.open_n_pis e 1,\n flip expr.bind_pi b <$> (expr.replace_at new_body xs e')\n }\n | _ := pure e\n end\n| e@(elet var_name var_type var_assignment body) addr e' := expr.replace_at e.reduce_let addr e'\n| e@(expr.macro _ _) addr e' := e.unfold_macros >>= λ x, expr.replace_at x addr e'\n\nend replace_at\n\nmeta def expr.replace_with_predict_at (pf : expr) (addr : expr.address) : tactic expr := do {\n c ← tactic.mk_const `PREDICT,\n pf.replace_at addr c\n}\n\nmeta structure LeanStepState : Type :=\n(count : ℕ := 0)\n\nmeta structure LeanStepOpts : Type :=\n(rec_limit := 5000)\n\nopen expr\n\nmeta def extract_next_lemma : expr → tactic (expr × expr)\n| e@(app e₁ e₂) := do {\n let hd := (get_app_fn e),\n prod.mk hd <$> tactic.infer_type hd\n}\n| e@(const _ _) := do {\n prod.mk e <$> tactic.infer_type e\n}\n| e@(local_const _ _ _ _) := do {\n prod.mk e <$> tactic.infer_type e\n}\n| _ := tactic.fail \"[extract_next_lemma] not an application\"\n\n\nsection\nopen native\nmeta def rb_set.union {α} : rb_set α → rb_set α → rb_set α :=\nλ s₁ s₂, rb_set.fold s₁ s₂ $ flip rb_set.insert\nend\n\nlocal notation `LEAN_STEP_TRACE` := ff\n\nmeta def lean_step_trace (fmt : format) : tactic unit := do {\n when LEAN_STEP_TRACE $ tactic.trace fmt\n}\n\nmeta def lean_step_main_core_aux\n (decl_nm : name)\n (decl_tp : expr)\n (decl_premises : list (expr × expr))\n (main_pf : expr)\n (dp_handler : LeanStepDatapoint → tactic unit) : Π\n (acc : LeanStepState)\n (opts : LeanStepOpts)\n (bs : list (expr × expr))\n (addr : expr.address) /- always the current address of `pf` wrt `main_pf` -/\n (pf : expr), tactic (expr_set × name_set × LeanStepState) := λ acc opts bs addr pf,\n(guard (acc.count ≤ opts.rec_limit) <|> tactic.fail format! \"[lean_step_main_core_aux] RECURSION LIMIT HIT: {acc.count}\") *>\nmatch acc, opts, bs, addr, pf with\n| acc, opts, bs, addr, e@(var k) := do lean_step_trace \"[lean_step_main_core_aux] VAR CASE\",\n pure $ ⟨mk_expr_set, mk_name_set, {count := acc.count + 1}⟩\n| acc, opts, bs, addr, e@(sort _) := do lean_step_trace \"[lean_step_main_core_aux] SORT CASE\",\n pure $ ⟨mk_expr_set, mk_name_set, {count := acc.count + 1}⟩\n| acc, opts, bs, addr, e@(mvar _ _ _) := do lean_step_trace \"[lean_step_main_core_aux] MVAR CASE\",\n pure $ ⟨mk_expr_set, mk_name_set, {count := acc.count + 1}⟩\n| acc, opts, bs, addr, e@(const nm ls) := do lean_step_trace \"[lean_step_main_core_aux] CONST CASE\", do {\n (dp : LeanStepDatapoint) ← do {\n goal ← tactic.infer_type e,\n goal_is_prop ← tactic.is_prop goal,\n result ← main_pf.replace_with_predict e,\n next_lemma ← optional $ extract_next_lemma e,\n pure $ ({\n decl_nm := decl_nm\n , decl_tp := decl_tp\n , hyps := bs\n , hyps_mask := list.repeat ff bs.length\n , decl_premises := decl_premises\n , decl_premises_mask := decl_premises.map (λ c, c.1.const_name = nm)\n , goal := goal\n , proof_term := e\n , result := result\n , next_lemma := next_lemma\n , goal_is_prop := goal_is_prop\n } : LeanStepDatapoint)\n },\n\n -- when true $ sorry, -- write the datapoint\n dp_handler dp,\n -- tactic.fail \"NYI\"\n pure ⟨mk_expr_set, mk_name_set.insert nm, {count := acc.count + 1}⟩\n}\n| acc, opts, bs, addr, e@(local_const unique pretty bi tp) := do lean_step_trace \"[lean_step_main_core_aux] LOCAL CONST CASE\", do {\n (dp : LeanStepDatapoint) ← do {\n goal ← tactic.infer_type e,\n goal_is_prop ← tactic.is_prop goal,\n result ← main_pf.replace_with_predict_at addr,\n next_lemma ← optional $ extract_next_lemma e,\n pure $ ({\n decl_nm := decl_nm\n , decl_tp := decl_tp\n , hyps := bs\n , hyps_mask := bs.map (λ c, to_bool $ c.1 = e)\n , decl_premises := decl_premises\n , decl_premises_mask := list.repeat ff decl_premises.length\n , goal := goal\n , proof_term := e\n , result := result\n , next_lemma := next_lemma\n , goal_is_prop := goal_is_prop\n } : LeanStepDatapoint)\n },\n dp_handler dp,\n pure ⟨mk_expr_set.insert e, mk_name_set, {count := acc.count + 1}⟩\n}\n| acc, opts, bs, addr, e@(app e₁ e₂) := do lean_step_trace \"[lean_step_main_core_aux] APP CASE\", do {\n ⟨lc_set₁, c_set₁, acc⟩ ← lean_step_main_core_aux acc opts bs (addr ++ [expr.coord.app_fn]) e₁,\n (lc_set₂, c_set₂, acc) ← lean_step_main_core_aux acc opts bs (addr ++ [expr.coord.app_arg]) e₂,\n let lc_set : expr_set := lc_set₁.union lc_set₂,\n let hyps_mask := bs.map (λ c, lc_set.contains c.1),\n let c_set : name_set := c_set₁.union c_set₂,\n let decl_premises_mask := decl_premises.map (λ c, c_set.contains c.1.const_name),\n (dp : LeanStepDatapoint) ← do {\n goal ← tactic.infer_type e,\n goal_is_prop ← tactic.is_prop goal,\n result ← main_pf.replace_with_predict_at addr,\n next_lemma ← optional $ extract_next_lemma e,\n pure $ ({\n decl_nm := decl_nm\n , decl_tp := decl_tp\n , hyps := bs\n , hyps_mask := hyps_mask\n , decl_premises := decl_premises\n , decl_premises_mask := decl_premises_mask\n , goal := goal\n , proof_term := e\n , result := result\n , next_lemma := next_lemma\n , goal_is_prop := goal_is_prop\n } : LeanStepDatapoint)\n },\n dp_handler dp,\n pure ⟨lc_set, c_set, {count := acc.count + 1}⟩\n}\n| acc, opts, bs, addr, e@(lam var_name b_info var_type body) := do lean_step_trace \"[lean_step_main_core_aux] LAM CASE\", do {\n ⟨[b], new_body⟩ ← tactic.open_n_lambdas e 1,\n -- new_bs ← mcond (tactic.is_proof b) (pure $ b::bs) (pure bs),\n\n new_bs ← (++) bs <$> pure <$> mk_type_annotation b,\n\n ⟨lc_set, c_set, acc⟩ ← lean_step_main_core_aux acc opts new_bs (addr ++ [coord.lam_body]) new_body,\n (dp : LeanStepDatapoint) ← do {\n goal ← tactic.infer_type e,\n goal_is_prop ← tactic.is_prop goal,\n result ← main_pf.replace_with_predict_at addr,\n next_lemma ← optional $ extract_next_lemma e,\n pure $ ({\n decl_nm := decl_nm\n , decl_tp := decl_tp\n , hyps := bs\n , hyps_mask := bs.map (λ x, lc_set.contains x.1)\n , decl_premises := decl_premises\n , decl_premises_mask := decl_premises.map (λ c, c_set.contains c.1.const_name)\n , goal := goal\n , proof_term := e\n , result := result\n , next_lemma := next_lemma\n , goal_is_prop := goal_is_prop\n } : LeanStepDatapoint)\n },\n dp_handler dp,\n pure ⟨lc_set, c_set, {count := acc.count + 1}⟩\n}\n-- TODO(): make this case a no-op?\n| acc, opts, bs, addr, e@(pi var_name b_info var_type body) := do lean_step_trace \"[lean_step_main_core_aux] PI CASE\", do {\n ⟨[b], new_body⟩ ← tactic.open_n_pis e 1,\n -- new_bs ← mcond (tactic.is_proof b) (pure $ b::bs) (pure bs),\n\n new_bs ← (++) bs <$> pure <$> mk_type_annotation b,\n\n ⟨lc_set, c_set, acc⟩ ← lean_step_main_core_aux acc opts new_bs (addr ++ [coord.pi_body]) new_body,\n (dp : LeanStepDatapoint) ← do {\n goal ← tactic.infer_type e,\n goal_is_prop ← tactic.is_prop goal,\n result ← main_pf.replace_with_predict_at addr,\n next_lemma ← optional $ extract_next_lemma e,\n pure $ ({\n decl_nm := decl_nm\n , decl_tp := decl_tp\n , hyps := bs\n , hyps_mask := bs.map (λ x, lc_set.contains x.1)\n , decl_premises := decl_premises\n , decl_premises_mask := decl_premises.map (λ c, c_set.contains c.1.const_name)\n , goal := goal\n , proof_term := e\n , result := result\n , next_lemma := next_lemma\n , goal_is_prop := goal_is_prop\n } : LeanStepDatapoint)\n },\n dp_handler dp,\n pure ⟨lc_set, c_set, {count := acc.count + 1}⟩\n}\n| acc, opts, bs, addr, e@(elet var_name var_type var_assignment body) := do lean_step_trace \"[lean_step_main_core_aux] LET CASE\", do {\n lean_step_main_core_aux acc opts bs addr e.reduce_let -- should be fine as long as the expr.replace function has the same logic\n}\n-- TODO(): make no-op/throw exception?\n| acc, opts, bs, addr, e@(macro _ _) := do lean_step_trace \"[lean_step_main_core_aux] MACRO CASE\", do {\n (e.unfold_macros) >>= (lean_step_main_core_aux acc opts bs addr)\n}\nend\n\nmeta def lean_step_main_core\n(decl_nm : name)\n(decl_tp : expr)\n(decl_premises : list (expr × expr))\n(main_pf : expr)\n(dp_handler : LeanStepDatapoint → tactic unit)\n(opts : LeanStepOpts)\n: Π (pf : expr), tactic unit := λ pf, do {\n tactic.try_verbose $ (lean_step_main_core_aux decl_nm decl_tp decl_premises pf dp_handler {} opts [] [] pf) *> pure ()\n}\n\nend LeanStep\n", "meta": {"author": "jesse-michael-han", "repo": "lean-step-public", "sha": "1abd55d25fe01e581a040a815aceb379d8e1bee1", "save_path": "github-repos/lean/jesse-michael-han-lean-step-public", "path": "github-repos/lean/jesse-michael-han-lean-step-public/lean-step-public-1abd55d25fe01e581a040a815aceb379d8e1bee1/src/data_util/lean_step.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2689414330889797, "lm_q2_score": 0.03210070775871955, "lm_q1q2_score": 0.008633210347800567}} {"text": "/-\nCopyright (c) 2019 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Daniel Selsam, Leonardo de Moura\n\nType class instance synthesizer using tabled resolution.\n-/\nimport Lean.Meta.Basic\nimport Lean.Meta.Instances\nimport Lean.Meta.AbstractMVars\nimport Lean.Meta.WHNF\nimport Lean.Meta.Check\nimport Lean.Util.Profile\n\nnamespace Lean.Meta\n\nregister_builtin_option synthInstance.maxHeartbeats : Nat := {\n defValue := 500\n descr := \"maximum amount of heartbeats per typeclass resolution problem. A heartbeat is number of (small) memory allocations (in thousands), 0 means no limit\"\n}\n\nregister_builtin_option synthInstance.maxSize : Nat := {\n defValue := 128\n descr := \"maximum number of instances used to construct a solution in the type class instance synthesis procedure\"\n}\nnamespace SynthInstance\n\ndef getMaxHeartbeats (opts : Options) : Nat :=\n synthInstance.maxHeartbeats.get opts * 1000\n\nopen Std (HashMap)\n\nbuiltin_initialize inferTCGoalsRLAttr : TagAttribute ←\n registerTagAttribute `inferTCGoalsRL \"instruct type class resolution procedure to solve goals from right to left for this instance\"\n\ndef hasInferTCGoalsRLAttribute (env : Environment) (constName : Name) : Bool :=\n inferTCGoalsRLAttr.hasTag env constName\n\nstructure GeneratorNode where\n mvar : Expr\n key : Expr\n mctx : MetavarContext\n instances : Array Expr\n currInstanceIdx : Nat\n deriving Inhabited\n\nstructure ConsumerNode where\n mvar : Expr\n key : Expr\n mctx : MetavarContext\n subgoals : List Expr\n size : Nat -- instance size so far\n deriving Inhabited\n\ninductive Waiter where\n | consumerNode : ConsumerNode → Waiter\n | root : Waiter\n\ndef Waiter.isRoot : Waiter → Bool\n | Waiter.consumerNode _ => false\n | Waiter.root => true\n\n/-\n In tabled resolution, we creating a mapping from goals (e.g., `Coe Nat ?x`) to\n answers and waiters. Waiters are consumer nodes that are waiting for answers for a\n particular node.\n\n We implement this mapping using a `HashMap` where the keys are\n normalized expressions. That is, we replace assignable metavariables\n with auxiliary free variables of the form `_tc.`. We do\n not declare these free variables in any local context, and we should\n view them as \"normalized names\" for metavariables. For example, the\n term `f ?m ?m ?n` is normalized as\n `f _tc.0 _tc.0 _tc.1`.\n\n This approach is structural, and we may visit the same goal more\n than once if the different occurrences are just definitionally\n equal, but not structurally equal.\n\n Remark: a metavariable is assignable only if its depth is equal to\n the metavar context depth.\n-/\nnamespace MkTableKey\n\nstructure State where\n nextIdx : Nat := 0\n lmap : HashMap MVarId Level := {}\n emap : HashMap MVarId Expr := {}\n\nabbrev M := ReaderT MetavarContext (StateM State)\n\npartial def normLevel (u : Level) : M Level := do\n if !u.hasMVar then\n pure u\n else match u with\n | Level.succ v _ => return u.updateSucc! (← normLevel v)\n | Level.max v w _ => return u.updateMax! (← normLevel v) (← normLevel w)\n | Level.imax v w _ => return u.updateIMax! (← normLevel v) (← normLevel w)\n | Level.mvar mvarId _ =>\n let mctx ← read\n if !mctx.isLevelAssignable mvarId then\n pure u\n else\n let s ← get\n match s.lmap.find? mvarId with\n | some u' => pure u'\n | none =>\n let u' := mkLevelParam $ Name.mkNum `_tc s.nextIdx\n modify fun s => { s with nextIdx := s.nextIdx + 1, lmap := s.lmap.insert mvarId u' }\n pure u'\n | u => pure u\n\npartial def normExpr (e : Expr) : M Expr := do\n if !e.hasMVar then\n pure e\n else match e with\n | Expr.const _ us _ => return e.updateConst! (← us.mapM normLevel)\n | Expr.sort u _ => return e.updateSort! (← normLevel u)\n | Expr.app f a _ => return e.updateApp! (← normExpr f) (← normExpr a)\n | Expr.letE _ t v b _ => return e.updateLet! (← normExpr t) (← normExpr v) (← normExpr b)\n | Expr.forallE _ d b _ => return e.updateForallE! (← normExpr d) (← normExpr b)\n | Expr.lam _ d b _ => return e.updateLambdaE! (← normExpr d) (← normExpr b)\n | Expr.mdata _ b _ => return e.updateMData! (← normExpr b)\n | Expr.proj _ _ b _ => return e.updateProj! (← normExpr b)\n | Expr.mvar mvarId _ =>\n let mctx ← read\n if !mctx.isExprAssignable mvarId then\n pure e\n else\n let s ← get\n match s.emap.find? mvarId with\n | some e' => pure e'\n | none => do\n let e' := mkFVar { name := Name.mkNum `_tc s.nextIdx }\n modify fun s => { s with nextIdx := s.nextIdx + 1, emap := s.emap.insert mvarId e' }\n pure e'\n | _ => pure e\n\nend MkTableKey\n\n/- Remark: `mkTableKey` assumes `e` does not contain assigned metavariables. -/\ndef mkTableKey (mctx : MetavarContext) (e : Expr) : Expr :=\n MkTableKey.normExpr e mctx |>.run' {}\n\nstructure Answer where\n result : AbstractMVarsResult\n resultType : Expr\n size : Nat\n deriving Inhabited\n\nstructure TableEntry where\n waiters : Array Waiter\n answers : Array Answer := #[]\n\nstructure Context where\n maxResultSize : Nat\n maxHeartbeats : Nat\n\n/-\n Remark: the SynthInstance.State is not really an extension of `Meta.State`.\n The field `postponed` is not needed, and the field `mctx` is misleading since\n `synthInstance` methods operate over different `MetavarContext`s simultaneously.\n That being said, we still use `extends` because it makes it simpler to move from\n `M` to `MetaM`.\n-/\nstructure State where\n result? : Option AbstractMVarsResult := none\n generatorStack : Array GeneratorNode := #[]\n resumeStack : Array (ConsumerNode × Answer) := #[]\n tableEntries : HashMap Expr TableEntry := {}\n\nabbrev SynthM := ReaderT Context $ StateRefT State MetaM\n\ndef checkMaxHeartbeats : SynthM Unit := do\n Core.checkMaxHeartbeatsCore \"typeclass\" `synthInstance.maxHeartbeats (← read).maxHeartbeats\n\n@[inline] def mapMetaM (f : forall {α}, MetaM α → MetaM α) {α} : SynthM α → SynthM α :=\n monadMap @f\n\ninstance : Inhabited (SynthM α) where\n default := fun _ _ => default\n\n/-- Return globals and locals instances that may unify with `type` -/\ndef getInstances (type : Expr) : MetaM (Array Expr) := do\n -- We must retrieve `localInstances` before we use `forallTelescopeReducing` because it will update the set of local instances\n let localInstances ← getLocalInstances\n forallTelescopeReducing type fun _ type => do\n let className? ← isClass? type\n match className? with\n | none => throwError \"type class instance expected{indentExpr type}\"\n | some className =>\n let globalInstances ← getGlobalInstancesIndex\n let result ← globalInstances.getUnify type\n -- Using insertion sort because it is stable and the array `result` should be mostly sorted.\n -- Most instances have default priority.\n let result := result.insertionSort fun e₁ e₂ => e₁.priority < e₂.priority\n let erasedInstances ← getErasedInstances\n let result ← result.filterMapM fun e => match e.val with\n | Expr.const constName us _ =>\n if erasedInstances.contains constName then\n return none\n else\n return some <| e.val.updateConst! (← us.mapM (fun _ => mkFreshLevelMVar))\n | _ => panic! \"global instance is not a constant\"\n trace[Meta.synthInstance.globalInstances] \"{type}, {result}\"\n let result := localInstances.foldl (init := result) fun (result : Array Expr) linst =>\n if linst.className == className then result.push linst.fvar else result\n pure result\n\ndef mkGeneratorNode? (key mvar : Expr) : MetaM (Option GeneratorNode) := do\n let mvarType ← inferType mvar\n let mvarType ← instantiateMVars mvarType\n let instances ← getInstances mvarType\n if instances.isEmpty then\n pure none\n else\n let mctx ← getMCtx\n pure $ some {\n mvar := mvar,\n key := key,\n mctx := mctx,\n instances := instances,\n currInstanceIdx := instances.size\n }\n\n/-- Create a new generator node for `mvar` and add `waiter` as its waiter.\n `key` must be `mkTableKey mctx mvarType`. -/\ndef newSubgoal (mctx : MetavarContext) (key : Expr) (mvar : Expr) (waiter : Waiter) : SynthM Unit :=\n withMCtx mctx do\n trace[Meta.synthInstance.newSubgoal] key\n match (← mkGeneratorNode? key mvar) with\n | none => pure ()\n | some node =>\n let entry : TableEntry := { waiters := #[waiter] }\n modify fun s =>\n { s with\n generatorStack := s.generatorStack.push node,\n tableEntries := s.tableEntries.insert key entry }\n\ndef findEntry? (key : Expr) : SynthM (Option TableEntry) := do\n return (← get).tableEntries.find? key\n\ndef getEntry (key : Expr) : SynthM TableEntry := do\n match (← findEntry? key) with\n | none => panic! \"invalid key at synthInstance\"\n | some entry => pure entry\n\n/--\n Create a `key` for the goal associated with the given metavariable.\n That is, we create a key for the type of the metavariable.\n\n We must instantiate assigned metavariables before we invoke `mkTableKey`. -/\ndef mkTableKeyFor (mctx : MetavarContext) (mvar : Expr) : SynthM Expr :=\n withMCtx mctx do\n let mvarType ← inferType mvar\n let mvarType ← instantiateMVars mvarType\n return mkTableKey mctx mvarType\n\n/- See `getSubgoals` and `getSubgoalsAux`\n\n We use the parameter `j` to reduce the number of `instantiate*` invocations.\n It is the same approach we use at `forallTelescope` and `lambdaTelescope`.\n Given `getSubgoalsAux args j subgoals instVal type`,\n we have that `type.instantiateRevRange j args.size args` does not have loose bound variables. -/\nstructure SubgoalsResult where\n subgoals : List Expr\n instVal : Expr\n instTypeBody : Expr\n\nprivate partial def getSubgoalsAux (lctx : LocalContext) (localInsts : LocalInstances) (xs : Array Expr)\n : Array Expr → Nat → List Expr → Expr → Expr → MetaM SubgoalsResult\n | args, j, subgoals, instVal, Expr.forallE n d b c => do\n let d := d.instantiateRevRange j args.size args\n let mvarType ← mkForallFVars xs d\n let mvar ← mkFreshExprMVarAt lctx localInsts mvarType\n let arg := mkAppN mvar xs\n let instVal := mkApp instVal arg\n let subgoals := if c.binderInfo.isInstImplicit then mvar::subgoals else subgoals\n let args := args.push (mkAppN mvar xs)\n getSubgoalsAux lctx localInsts xs args j subgoals instVal b\n | args, j, subgoals, instVal, type => do\n let type := type.instantiateRevRange j args.size args\n let type ← whnf type\n if type.isForall then\n getSubgoalsAux lctx localInsts xs args args.size subgoals instVal type\n else\n pure ⟨subgoals, instVal, type⟩\n\n/--\n `getSubgoals lctx localInsts xs inst` creates the subgoals for the instance `inst`.\n The subgoals are in the context of the free variables `xs`, and\n `(lctx, localInsts)` is the local context and instances before we added the free variables to it.\n\n This extra complication is required because\n 1- We want all metavariables created by `synthInstance` to share the same local context.\n 2- We want to ensure that applications such as `mvar xs` are higher order patterns.\n\n The method `getGoals` create a new metavariable for each parameter of `inst`.\n For example, suppose the type of `inst` is `forall (x_1 : A_1) ... (x_n : A_n), B x_1 ... x_n`.\n Then, we create the metavariables `?m_i : forall xs, A_i`, and return the subset of these\n metavariables that are instance implicit arguments, and the expressions:\n - `inst (?m_1 xs) ... (?m_n xs)` (aka `instVal`)\n - `B (?m_1 xs) ... (?m_n xs)` -/\ndef getSubgoals (lctx : LocalContext) (localInsts : LocalInstances) (xs : Array Expr) (inst : Expr) : MetaM SubgoalsResult := do\n let instType ← inferType inst\n let result ← getSubgoalsAux lctx localInsts xs #[] 0 [] inst instType\n match inst.getAppFn with\n | Expr.const constName _ _ =>\n let env ← getEnv\n if hasInferTCGoalsRLAttribute env constName then\n pure result\n else\n pure { result with subgoals := result.subgoals.reverse }\n | _ => pure result\n\ndef tryResolveCore (mvar : Expr) (inst : Expr) : MetaM (Option (MetavarContext × List Expr)) := do\n let mvar ← instantiateMVars mvar\n if !(← hasAssignableMVar mvar) then\n /- The metavariable `mvar` may have been assinged when solving typing constraints.\n This may happen when a local instance type depends on other local instances.\n For example, in Mathlib, we have\n ```\n @Submodule.setLike : {R : Type u_1} → {M : Type u_2} →\n [_inst_1 : Semiring R] →\n [_inst_2 : AddCommMonoid M] →\n [_inst_3 : @ModuleS R M _inst_1 _inst_2] →\n SetLike (@Submodule R M _inst_1 _inst_2 _inst_3) M\n ```\n TODO: discuss what is the correct behavior here. There are other possibilities.\n 1) We could try to synthesize the instances `_inst_1` and `_inst_2` and check\n whether it is defeq to the one inferred by typing constraints. That is, we\n remove this `if`-statement. We discarded this one because some Mathlib theorems\n failed to be elaborated using it.\n 2) Generate an error/warning message when instances such as `Submodule.setLike` are declared,\n and instruct user to use `{}` binder annotation for `_inst_1` `_inst_2`.\n -/\n return some ((← getMCtx), [])\n let mvarType ← inferType mvar\n let lctx ← getLCtx\n let localInsts ← getLocalInstances\n forallTelescopeReducing mvarType fun xs mvarTypeBody => do\n let ⟨subgoals, instVal, instTypeBody⟩ ← getSubgoals lctx localInsts xs inst\n trace[Meta.synthInstance.tryResolve] \"{mvarTypeBody} =?= {instTypeBody}\"\n if (← isDefEq mvarTypeBody instTypeBody) then\n let instVal ← mkLambdaFVars xs instVal\n if (← isDefEq mvar instVal) then\n trace[Meta.synthInstance.tryResolve] \"success\"\n pure (some ((← getMCtx), subgoals))\n else\n trace[Meta.synthInstance.tryResolve] \"failure assigning\"\n pure none\n else\n trace[Meta.synthInstance.tryResolve] \"failure\"\n pure none\n\n/--\n Try to synthesize metavariable `mvar` using the instance `inst`.\n Remark: `mctx` contains `mvar`.\n If it succeeds, the result is a new updated metavariable context and a new list of subgoals.\n A subgoal is created for each instance implicit parameter of `inst`. -/\ndef tryResolve (mctx : MetavarContext) (mvar : Expr) (inst : Expr) : SynthM (Option (MetavarContext × List Expr)) :=\n traceCtx `Meta.synthInstance.tryResolve <| withMCtx mctx <| tryResolveCore mvar inst\n\n/--\n Assign a precomputed answer to `mvar`.\n If it succeeds, the result is a new updated metavariable context and a new list of subgoals. -/\ndef tryAnswer (mctx : MetavarContext) (mvar : Expr) (answer : Answer) : SynthM (Option MetavarContext) :=\n withMCtx mctx do\n let (_, _, val) ← openAbstractMVarsResult answer.result\n if (← isDefEq mvar val) then\n pure (some (← getMCtx))\n else\n pure none\n\n/-- Move waiters that are waiting for the given answer to the resume stack. -/\ndef wakeUp (answer : Answer) : Waiter → SynthM Unit\n | Waiter.root => do\n /- Recall that we now use `ignoreLevelMVarDepth := true`. Thus, we should allow solutions\n containing universe metavariables, and not check `answer.result.paramNames.isEmpty`.\n We use `openAbstractMVarsResult` to construct the universe metavariables\n at the correct depth. -/\n if answer.result.numMVars == 0 then\n modify fun s => { s with result? := answer.result }\n else\n let (_, _, answerExpr) ← openAbstractMVarsResult answer.result\n trace[Meta.synthInstance] \"skip answer containing metavariables {answerExpr}\"\n pure ()\n | Waiter.consumerNode cNode =>\n modify fun s => { s with resumeStack := s.resumeStack.push (cNode, answer) }\n\ndef isNewAnswer (oldAnswers : Array Answer) (answer : Answer) : Bool :=\n oldAnswers.all fun oldAnswer =>\n -- Remark: isDefEq here is too expensive. TODO: if `==` is too imprecise, add some light normalization to `resultType` at `addAnswer`\n -- iseq ← isDefEq oldAnswer.resultType answer.resultType; pure (!iseq)\n oldAnswer.resultType != answer.resultType\n\nprivate def mkAnswer (cNode : ConsumerNode) : MetaM Answer :=\n withMCtx cNode.mctx do\n traceM `Meta.synthInstance.newAnswer do pure m!\"size: {cNode.size}, {← inferType cNode.mvar}\"\n let val ← instantiateMVars cNode.mvar\n trace[Meta.synthInstance.newAnswer] \"val: {val}\"\n let result ← abstractMVars val -- assignable metavariables become parameters\n let resultType ← inferType result.expr\n pure { result := result, resultType := resultType, size := cNode.size + 1 }\n\n/--\n Create a new answer after `cNode` resolved all subgoals.\n That is, `cNode.subgoals == []`.\n And then, store it in the tabled entries map, and wakeup waiters. -/\ndef addAnswer (cNode : ConsumerNode) : SynthM Unit := do\n if cNode.size ≥ (← read).maxResultSize then\n traceM `Meta.synthInstance.discarded do withMCtx cNode.mctx do pure m!\"size: {cNode.size} ≥ {(← read).maxResultSize}, {← inferType cNode.mvar}\"\n return ()\n else\n let answer ← mkAnswer cNode\n -- Remark: `answer` does not contain assignable or assigned metavariables.\n let key := cNode.key\n let entry ← getEntry key\n if isNewAnswer entry.answers answer then\n let newEntry := { entry with answers := entry.answers.push answer }\n modify fun s => { s with tableEntries := s.tableEntries.insert key newEntry }\n entry.waiters.forM (wakeUp answer)\n\n/--\n Return `true` if a type of the form `(a_1 : A_1) → ... → (a_n : A_n) → B` has an unused argument `a_i`.\n\n Remark: This is syntactic check and no reduction is performed.\n-/\nprivate def hasUnusedArguments : Expr → Bool\n | Expr.forallE _ d b _ => !b.hasLooseBVar 0 || hasUnusedArguments b\n | _ => false\n\n/--\n If the type of the metavariable `mvar` has unused argument, return a pair `(α, transformer)`\n where `α` is a new type without the unused arguments and the `transformer` is a function for coverting a\n solution with type `α` into a value that can be assigned to `mvar`.\n Example: suppose `mvar` has type `(a : A) → (b : B a) → (c : C a) → D a c`, the result is the pair\n ```\n ((a : A) → (c : C a) → D a c,\n fun (f : (a : A) → (c : C a) → D a c) (a : A) (b : B a) (c : C a) => f a c\n )\n ```\n\n This method is used to improve the effectiveness of the TC resolution procedure. It was suggested and prototyped by\n Tomas Skrivan. It improves the support for instances of type `a : A → C` where `a` does not appear in class `C`.\n When we look for such an instance it is enough to look for an instance `c : C` and then return `fun _ => c`.\n\n Tomas' approach makes sure that instance of a type like `a : A → C` never gets tabled/cached. More on that later.\n At the core is the this methos. it takes an expression E and does two things:\n\n The modification to TC resolution works this way: We are looking for an instance of `E`, if it is tabled\n just get it as normal, but if not first remove all unused arguments producing `E'`. Now we look up the table again but\n for `E'`. If it exists, use the transforme to create E. If it does not exists, create a new goal `E'`.\n-/\nprivate def removeUnusedArguments? (mctx : MetavarContext) (mvar : Expr) : MetaM (Option (Expr × Expr)) :=\n withMCtx mctx do\n let mvarType ← instantiateMVars (← inferType mvar)\n if !hasUnusedArguments mvarType then\n return none\n else\n forallTelescope mvarType fun xs body => do\n let ys ← xs.foldrM (init := []) fun x ys => do\n if body.containsFVar x.fvarId! then\n return x :: ys\n else if (← ys.anyM fun y => return (← inferType y).containsFVar x.fvarId!) then\n return x :: ys\n else\n return ys\n let ys := ys.toArray\n let mvarType' ← mkForallFVars ys body\n withLocalDeclD `redf mvarType' fun f => do\n let transformer ← mkLambdaFVars #[f] (← mkLambdaFVars xs (mkAppN f ys))\n trace[Meta.synthInstance.unusedArgs] \"{mvarType}\\nhas unused arguments, reduced type{indentExpr mvarType'}\\nTransformer{indentExpr transformer}\"\n return some (mvarType', transformer)\n\n/-- Process the next subgoal in the given consumer node. -/\ndef consume (cNode : ConsumerNode) : SynthM Unit :=\n match cNode.subgoals with\n | [] => addAnswer cNode\n | mvar::_ => do\n let waiter := Waiter.consumerNode cNode\n let key ← mkTableKeyFor cNode.mctx mvar\n let entry? ← findEntry? key\n match entry? with\n | none =>\n -- Remove unused arguments and try again, see comment at `removeUnusedArguments?`\n match (← removeUnusedArguments? cNode.mctx mvar) with\n | none => newSubgoal cNode.mctx key mvar waiter\n | some (mvarType', transformer) =>\n let key' := mkTableKey cNode.mctx mvarType'\n match (← findEntry? key') with\n | none => do\n let (mctx', mvar') ← withMCtx cNode.mctx do\n let mvar' ← mkFreshExprMVar mvarType'\n return (← getMCtx, mvar')\n newSubgoal mctx' key' mvar' (Waiter.consumerNode { cNode with mctx := mctx', subgoals := mvar'::cNode.subgoals })\n | some entry' => do\n let answers' ← entry'.answers.mapM fun a => withMCtx cNode.mctx do\n let trAnswr := Expr.betaRev transformer #[← instantiateMVars a.result.expr]\n let trAnswrType ← inferType trAnswr\n pure { a with result.expr := trAnswr, resultType := trAnswrType }\n modify fun s =>\n { s with\n resumeStack := answers'.foldl (fun s answer => s.push (cNode, answer)) s.resumeStack,\n tableEntries := s.tableEntries.insert key' { entry' with waiters := entry'.waiters.push waiter } }\n | some entry => modify fun s =>\n { s with\n resumeStack := entry.answers.foldl (fun s answer => s.push (cNode, answer)) s.resumeStack,\n tableEntries := s.tableEntries.insert key { entry with waiters := entry.waiters.push waiter } }\n\ndef getTop : SynthM GeneratorNode := do\n pure (← get).generatorStack.back\n\n@[inline] def modifyTop (f : GeneratorNode → GeneratorNode) : SynthM Unit :=\n modify fun s => { s with generatorStack := s.generatorStack.modify (s.generatorStack.size - 1) f }\n\n/-- Try the next instance in the node on the top of the generator stack. -/\ndef generate : SynthM Unit := do\n let gNode ← getTop\n if gNode.currInstanceIdx == 0 then\n modify fun s => { s with generatorStack := s.generatorStack.pop }\n else do\n let key := gNode.key\n let idx := gNode.currInstanceIdx - 1\n let inst := gNode.instances.get! idx\n let mctx := gNode.mctx\n let mvar := gNode.mvar\n trace[Meta.synthInstance.generate] \"instance {inst}\"\n modifyTop fun gNode => { gNode with currInstanceIdx := idx }\n match (← tryResolve mctx mvar inst) with\n | none => pure ()\n | some (mctx, subgoals) => consume { key := key, mvar := mvar, subgoals := subgoals, mctx := mctx, size := 0 }\n\ndef getNextToResume : SynthM (ConsumerNode × Answer) := do\n let s ← get\n let r := s.resumeStack.back\n modify fun s => { s with resumeStack := s.resumeStack.pop }\n pure r\n\n/--\n Given `(cNode, answer)` on the top of the resume stack, continue execution by using `answer` to solve the\n next subgoal. -/\ndef resume : SynthM Unit := do\n let (cNode, answer) ← getNextToResume\n match cNode.subgoals with\n | [] => panic! \"resume found no remaining subgoals\"\n | mvar::rest =>\n match (← tryAnswer cNode.mctx mvar answer) with\n | none => pure ()\n | some mctx =>\n withMCtx mctx <| traceM `Meta.synthInstance.resume do\n let goal ← inferType cNode.mvar\n let subgoal ← inferType mvar\n pure m!\"size: {cNode.size + answer.size}, {goal} <== {subgoal}\"\n consume { key := cNode.key, mvar := cNode.mvar, subgoals := rest, mctx := mctx, size := cNode.size + answer.size }\n\ndef step : SynthM Bool := do\n checkMaxHeartbeats\n let s ← get\n if !s.resumeStack.isEmpty then\n resume\n pure true\n else if !s.generatorStack.isEmpty then\n generate\n pure true\n else\n pure false\n\ndef getResult : SynthM (Option AbstractMVarsResult) := do\n pure (← get).result?\n\npartial def synth : SynthM (Option AbstractMVarsResult) := do\n if (← step) then\n match (← getResult) with\n | none => synth\n | some result => pure result\n else\n trace[Meta.synthInstance] \"failed\"\n pure none\n\ndef main (type : Expr) (maxResultSize : Nat) : MetaM (Option AbstractMVarsResult) :=\n withCurrHeartbeats <| traceCtx `Meta.synthInstance do\n trace[Meta.synthInstance] \"main goal {type}\"\n let mvar ← mkFreshExprMVar type\n let mctx ← getMCtx\n let key := mkTableKey mctx type\n let action : SynthM (Option AbstractMVarsResult) := do\n newSubgoal mctx key mvar Waiter.root\n synth\n try\n action.run { maxResultSize := maxResultSize, maxHeartbeats := getMaxHeartbeats (← getOptions) } |>.run' {}\n catch ex =>\n if ex.isMaxHeartbeat then\n throwError \"failed to synthesize{indentExpr type}\\n{ex.toMessageData}\"\n else\n throw ex\n\nend SynthInstance\n\n/-\nType class parameters can be annotated with `outParam` annotations.\n\nGiven `C a_1 ... a_n`, we replace `a_i` with a fresh metavariable `?m_i` IF\n`a_i` is an `outParam`.\nThe result is type correct because we reject type class declarations IF\nit contains a regular parameter X that depends on an `out` parameter Y.\n\nThen, we execute type class resolution as usual.\nIf it succeeds, and metavariables ?m_i have been assigned, we try to unify\nthe original type `C a_1 ... a_n` witht the normalized one.\n-/\n\nprivate def preprocess (type : Expr) : MetaM Expr :=\n forallTelescopeReducing type fun xs type => do\n let type ← whnf type\n mkForallFVars xs type\n\nprivate def preprocessLevels (us : List Level) : MetaM (List Level × Bool) := do\n let mut r := #[]\n let mut modified := false\n for u in us do\n let u ← instantiateLevelMVars u\n if u.hasMVar then\n r := r.push (← mkFreshLevelMVar)\n modified := true\n else\n r := r.push u\n return (r.toList, modified)\n\nprivate partial def preprocessArgs (type : Expr) (i : Nat) (args : Array Expr) : MetaM (Array Expr) := do\n if h : i < args.size then\n let type ← whnf type\n match type with\n | Expr.forallE _ d b _ => do\n let arg := args.get ⟨i, h⟩\n let arg ← if isOutParam d then mkFreshExprMVar d else pure arg\n let args := args.set ⟨i, h⟩ arg\n preprocessArgs (b.instantiate1 arg) (i+1) args\n | _ =>\n throwError \"type class resolution failed, insufficient number of arguments\" -- TODO improve error message\n else\n return args\n\nprivate def preprocessOutParam (type : Expr) : MetaM Expr :=\n forallTelescope type fun xs typeBody => do\n match typeBody.getAppFn with\n | c@(Expr.const constName us _) =>\n let env ← getEnv\n if !hasOutParams env constName then\n return type\n else\n let args := typeBody.getAppArgs\n let cType ← inferType c\n let args ← preprocessArgs cType 0 args\n mkForallFVars xs (mkAppN c args)\n | _ =>\n return type\n\n/-\n Remark: when `maxResultSize? == none`, the configuration option `synthInstance.maxResultSize` is used.\n Remark: we use a different option for controlling the maximum result size for coercions.\n-/\n\ndef synthInstance? (type : Expr) (maxResultSize? : Option Nat := none) : MetaM (Option Expr) := do profileitM Exception \"typeclass inference\" (← getOptions) do\n let opts ← getOptions\n let maxResultSize := maxResultSize?.getD (synthInstance.maxSize.get opts)\n let inputConfig ← getConfig\n withConfig (fun config => { config with isDefEqStuckEx := true, transparency := TransparencyMode.instances,\n foApprox := true, ctxApprox := true, constApprox := false,\n ignoreLevelMVarDepth := true }) do\n let type ← instantiateMVars type\n let type ← preprocess type\n let s ← get\n match s.cache.synthInstance.find? type with\n | some result => pure result\n | none =>\n let result? ← withNewMCtxDepth do\n let normType ← preprocessOutParam type\n trace[Meta.synthInstance] \"preprocess: {type} ==> {normType}\"\n SynthInstance.main normType maxResultSize\n let resultHasUnivMVars := if let some result := result? then !result.paramNames.isEmpty else false\n let result? ← match result? with\n | none => pure none\n | some result => do\n let (_, _, result) ← openAbstractMVarsResult result\n trace[Meta.synthInstance] \"result {result}\"\n let resultType ← inferType result\n if (← withConfig (fun _ => inputConfig) <| isDefEq type resultType) then\n let result ← instantiateMVars result\n /- We use `check` to propogate universe constraints implied by the `result`.\n Recall that we use `ignoreLevelMVarDepth := true` which allows universe metavariables in the current depth to be assigned,\n but these assignments are discarded by `withNewMCtxDepth`.\n\n TODO: If this `check` is a performance bottleneck, we can improve performance by tracking whether\n a universe metavariable from previous universe levels have been assigned or not during TC resolution.\n We only need to perform the `check` if this kind of assignment have been performed.\n\n The example in the issue #796 exposed this issue.\n ```\n structure A\n class B (a : outParam A) (α : Sort u)\n class C {a : A} (α : Sort u) [B a α]\n class D {a : A} (α : Sort u) [B a α] [c : C α]\n class E (a : A) where [c (α : Sort u) [B a α] : C α]\n instance c {a : A} [e : E a] (α : Sort u) [B a α] : C α := e.c α\n\n def d {a : A} [e : E a] (α : Sort u) [b : B a α] : D α := ⟨⟩\n ```\n The term `D α` has two instance implicit arguments. The second one has type `C α`, and TC\n resolution produces the result `@c.{u} a e α b`.\n Note that the `e` has type `E.{?v} a`, and `E` is universe polymorphic,\n but the universe does not occur in the parameter `a`. We have that `?v := u` is implied by `@c.{u} a e α b`,\n but this assignment is lost.\n -/\n check result\n pure (some result)\n else\n trace[Meta.synthInstance] \"result type{indentExpr resultType}\\nis not definitionally equal to{indentExpr type}\"\n pure none\n if type.hasMVar || resultHasUnivMVars then\n pure result?\n else do\n modify fun s => { s with cache := { s.cache with synthInstance := s.cache.synthInstance.insert type result? } }\n pure result?\n\n/--\n Return `LOption.some r` if succeeded, `LOption.none` if it failed, and `LOption.undef` if\n instance cannot be synthesized right now because `type` contains metavariables. -/\ndef trySynthInstance (type : Expr) (maxResultSize? : Option Nat := none) : MetaM (LOption Expr) := do\n catchInternalId isDefEqStuckExceptionId\n (toLOptionM <| synthInstance? type maxResultSize?)\n (fun _ => pure LOption.undef)\n\ndef synthInstance (type : Expr) (maxResultSize? : Option Nat := none) : MetaM Expr :=\n catchInternalId isDefEqStuckExceptionId\n (do\n let result? ← synthInstance? type maxResultSize?\n match result? with\n | some result => pure result\n | none => throwError \"failed to synthesize{indentExpr type}\")\n (fun _ => throwError \"failed to synthesize{indentExpr type}\")\n\n@[export lean_synth_pending]\nprivate def synthPendingImp (mvarId : MVarId) : MetaM Bool := withIncRecDepth <| withMVarContext mvarId do\n let mvarDecl ← getMVarDecl mvarId\n match mvarDecl.kind with\n | MetavarKind.syntheticOpaque =>\n return false\n | _ =>\n /- Check whether the type of the given metavariable is a class or not. If yes, then try to synthesize\n it using type class resolution. We only do it for `synthetic` and `natural` metavariables. -/\n match (← isClass? mvarDecl.type) with\n | none =>\n return false\n | some _ =>\n /- TODO: use a configuration option instead of the hard-coded limit `1`. -/\n if (← read).synthPendingDepth > 1 then\n trace[Meta.synthPending] \"too many nested synthPending invocations\"\n return false\n else\n withReader (fun ctx => { ctx with synthPendingDepth := ctx.synthPendingDepth + 1 }) do\n trace[Meta.synthPending] \"synthPending {mkMVar mvarId}\"\n let val? ← catchInternalId isDefEqStuckExceptionId (synthInstance? mvarDecl.type (maxResultSize? := none)) (fun _ => pure none)\n match val? with\n | none =>\n return false\n | some val =>\n if (← isExprMVarAssigned mvarId) then\n return false\n else\n assignExprMVar mvarId val\n return true\n\nbuiltin_initialize\n registerTraceClass `Meta.synthPending\n registerTraceClass `Meta.synthInstance\n registerTraceClass `Meta.synthInstance.globalInstances\n registerTraceClass `Meta.synthInstance.newSubgoal\n registerTraceClass `Meta.synthInstance.tryResolve\n registerTraceClass `Meta.synthInstance.resume\n registerTraceClass `Meta.synthInstance.generate\n registerTraceClass `Meta.synthInstance.unusedArgs\n registerTraceClass `Meta.synthInstance.newAnswer\n\nend Lean.Meta\n", "meta": {"author": "Kha", "repo": "lean4-nightly", "sha": "b4c92de57090e6c47b29d3575df53d86fce52752", "save_path": "github-repos/lean/Kha-lean4-nightly", "path": "github-repos/lean/Kha-lean4-nightly/lean4-nightly-b4c92de57090e6c47b29d3575df53d86fce52752/stage0/src/Lean/Meta/SynthInstance.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.25091279808829703, "lm_q2_score": 0.03410042620311981, "lm_q1q2_score": 0.008556233354628275}} {"text": "import Lean.Parser\nopen Lean.Parser.Term\n\nsyntax \"Π\" many1(binderIdent <|> bracketedBinder) \", \" term : term\nmacro_rules | `(Π $xs*, $y) => `(∀ $xs*, $y)\n\nmacro \"λ \" xs:many1(funBinder) \", \" f:term : term => `(fun $xs* => $f)\n\nmacro mods:declModifiers \"lemma\" n:declId sig:declSig val:declVal : command =>\n `($mods:declModifiers theorem $n $sig $val)\n\nmacro \"begin \" ts:sepBy1(tactic, \";\", \"; \", allowTrailingSep) i:\"end\" : term =>\n `(by { $[($ts:tactic)]* }%$i)", "meta": {"author": "forked-from-1kasper", "repo": "lean4-categories", "sha": "e8483adeecbabbd33de5400cae21754051da7ff3", "save_path": "github-repos/lean/forked-from-1kasper-lean4-categories", "path": "github-repos/lean/forked-from-1kasper-lean4-categories/lean4-categories-e8483adeecbabbd33de5400cae21754051da7ff3/Categories/Notation.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.25091277568224823, "lm_q2_score": 0.03410042460799288, "lm_q1q2_score": 0.008556232190334736}} {"text": "import Lean\nopen Lean\n\n-- @bollu: I removed the substring in `list` as we don't really use it for anything and\n-- it just complicates things\ninductive Sexp\n| atom: String → Sexp\n| list: List Sexp → Sexp\nderiving BEq, Inhabited, Repr\n\ndef Sexp.fromString : String → Sexp\n| s => Sexp.atom s\n\ninstance : Coe String Sexp where\n coe s := Sexp.fromString s\n\ndef Sexp.fromList : List Sexp → Sexp\n| xs => Sexp.list xs\n\ninstance : Coe (List Sexp) Sexp where\n coe := Sexp.fromList\n\n\npartial def Sexp.toString : Sexp → String\n| .atom s => s\n| .list xs => \"(\" ++ \" \".intercalate (xs.map Sexp.toString) ++ \")\"\n\ninstance : ToString Sexp := ⟨Sexp.toString⟩\n\ndef Sexp.toList? : Sexp → Option (List Sexp)\n| .atom _ => .none\n| .list xs => .some xs\n\ndef Sexp.toAtom! : Sexp → String\n| .atom s => s\n| .list xs => panic! s!\"expected atom, found list at {List.toString xs}\"\n\n\ninductive SexpTok\n| sexp: Sexp → SexpTok\n| opening: String.Pos → SexpTok\nderiving BEq, Inhabited, Repr\n\n\nstructure SexpState where\n it: String.Iterator\n stack: List SexpTok := []\n sexps: List Sexp := []\n depth : Nat := 0\nderiving BEq, Repr\n\ndef SexpState.fromString (s: String): SexpState :=\n { it := s.iter : SexpState }\n\ninstance : Inhabited SexpState where\n default := SexpState.fromString \"\"\n\ninductive SexpError\n| unmatchedOpenParen (ix: String.Iterator): SexpError\n| unmatchedCloseParen (ix: String.Iterator): SexpError\n| notSingleSexp (s: String) (xs: List Sexp): SexpError\nderiving BEq, Repr\n\ninstance : ToString SexpError where toString := λ err => match err with\n | .unmatchedOpenParen ix => s!\"Unmatched open parenthesis at {ix}\"\n | .unmatchedCloseParen ix => s!\"Unmatched close parenthesis at {ix}\"\n | .notSingleSexp s xs => s!\"not a single sexp '{s}', parsed as: '{xs}'\"\n\nabbrev SexpM := EStateM SexpError SexpState\n\ndef SexpM.peek: SexpM (Option (Char × String.Pos)) := do\n let state ← get\n return if state.it.atEnd then .none else .some (state.it.curr, state.it.i)\n\ndef SexpM.curPos: SexpM String.Pos := do\n let state ← get\n return state.it.i\n\n-- Stop is a good name, because it indicates that it's exclusive\n-- (AG: I don't read it as being exclusive from the name 'stop')\ndef SexpM.mkSubstring (l: String.Pos) (r: String.Pos): SexpM Substring := do\n let state ← get\n return { str := state.it.s, startPos := l, stopPos := r}\n\ndef SexpM.advance: SexpM Unit := do\n modify (fun state => { state with it := state.it.next })\n\ndef SexpM.pushTok (tok: SexpTok): SexpM Unit := do\n modify (fun state => { state with stack := tok :: state.stack })\n\ndef SexpM.pushSexp (sexp: Sexp): SexpM Unit := do\n let state ← get\n if state.stack.length == 0\n then set { state with stack := [], sexps := sexp :: state.sexps }\n else set { state with stack := (SexpTok.sexp sexp) :: state.stack }\n\n\ndef SexpM.incrementDepth: SexpM Unit :=\n modify (fun state => { state with depth := state.depth + 1 })\n\ndef SexpM.decrementDepth: SexpM Unit :=\n modify (fun state => { state with depth := state.depth - 1 })\n\n\ninstance [Inhabited α] : Inhabited (SexpM α) where\n default := do return default\n\n\ndef SexpM.pop: SexpM SexpTok := do\n let state ← get\n match state.stack with\n | [] => panic! \"empty stack\"\n | x::xs => do\n set { state with stack := xs }\n return x\n\n-- abbrev SexpTokStack := List SexpTok\n\n-- Remove elements from the stack of tokens `List SexpToken` till we find a `SexpToken.opening`.\n-- When we do, return (1) the position of the open paren, (2) the list of SexpTokens left on the stack, and (3) the list of Sexps\n-- Until then, accumulate the `SexpToken.sexp`s into `sexps`.\ndef stackPopTillOpen (stk: List SexpTok) (sexps: List Sexp := []): Option (String.Pos × (List SexpTok) × (List Sexp)) :=\n match stk with\n | [] => .none\n | SexpTok.opening openPos :: rest => (.some (openPos, rest, sexps))\n | SexpTok.sexp s :: rest => stackPopTillOpen rest (s :: sexps)\n\n-- collapse the current stack till the last ( into a single Sexp.list\ndef SexpM.matchClosingParen: SexpM Unit := do\n let state ← get\n match stackPopTillOpen state.stack with\n | (.some (_, stk, sexps)) =>\n let sexp := Sexp.list sexps\n modify (fun state => { state with stack := stk })\n SexpM.pushSexp sexp\n | (.none) => throw (SexpError.unmatchedCloseParen state.it)\n\n\npartial def SexpM.takeString (startPos: String.Pos): SexpM Substring := do\n match (← SexpM.peek) with\n | .none => SexpM.mkSubstring startPos (← SexpM.curPos)\n | .some (' ', _) => SexpM.mkSubstring startPos (← SexpM.curPos)\n | .some ('(', _) => SexpM.mkSubstring startPos (← SexpM.curPos)\n | .some (')', _) => SexpM.mkSubstring startPos (← SexpM.curPos)\n | .some _ => do\n SexpM.advance\n SexpM.takeString startPos\n\npartial def SexpM.parse: SexpM Unit := do\n match (← SexpM.peek) with\n | .some ('(', i) => do\n SexpM.advance\n SexpM.pushTok (SexpTok.opening i)\n SexpM.incrementDepth\n SexpM.parse\n | .some (')', _) => do\n SexpM.advance\n SexpM.matchClosingParen\n SexpM.parse\n -- return cur ++ rest\n | .some (' ', _) => do\n SexpM.advance\n SexpM.parse\n | .some (_, i) => do\n let s ← SexpM.takeString i\n SexpM.pushSexp ((Sexp.atom s.toString))\n SexpM.parse\n | .none => do\n let state ← get\n match stackPopTillOpen state.stack with\n | (.some (openPos, _, _)) =>\n throw <| SexpError.unmatchedOpenParen ({ s := state.it.s, i := openPos : String.Iterator })\n | (.none) => return ()\n\n-- | Parse a list of (possibly empty) sexps.\ndef parseSexpList (s: String): Except SexpError (List Sexp) :=\n let initState := SexpState.fromString s\n match EStateM.run SexpM.parse initState with\n | .ok () state => .ok state.sexps.reverse\n | .error e _ => .error e\n\n-- | Parse a single s-expression, and error if found no sexp or multiple sexps\ndef parseSingleSexp (s: String): Except SexpError Sexp := do\n match (← parseSexpList s) with\n | [x] => .ok x\n | xs => .error (.notSingleSexp s xs)\n\n-- To simplify Sexps, we want to replace some subterms in an Sexp:\n-- Have to mark this as partial since the termination checker doesn't like\n-- these higher-order functions like map. See: https://leanprover.zulipchat.com/#narrow/stream/270676-lean4/topic/.E2.9C.94.20using.20higher-order.20functions.20on.20inductive.20types.3A.20termin.2E.2E.2E\npartial def replaceTerm (toReplace : Sexp) (replaceWith : Sexp) (atSexp : Sexp) : Sexp :=\n if toReplace == atSexp then replaceWith\n else match atSexp with\n | .atom _ => atSexp\n | .list sexps => sexps.map $ replaceTerm toReplace replaceWith\n\n-- The idea of this simplification is to do substitutions that replace a term,\n-- such that the replaced term never appears as a proper subterm elsewhere in\n-- the request, i.e. neither as the goal/starting point nor in any of the\n-- rewrites. Ideally maximal subterms with this property\n\n-- For this, we start by finding wether a subexpression is contained in an Sexp\n-- Yes, this is not optimal because of the checks, feel free to rewrite.\n\n-- Need this order of arguments (awkward for recursive call) for `.` notation\npartial def Sexp.containsSubexpr (mainExpr : Sexp) (subExpr : Sexp) : Bool :=\n if subExpr == mainExpr then true\n else match mainExpr with\n | .atom _ => false\n | .list sexps => sexps.any (containsSubexpr · subExpr)\n\npartial def Sexp.vars : Sexp → List String\n | .atom s => [s]\n | .list sexps => List.join $ sexps.map vars\n\npartial def Sexp.fvarsConstsVars : Sexp → List Sexp × List Sexp × List String\n | .atom s => ([],[],[s])\n | c@(.list (\"const\"::_)) => ([],[c],[])\n | fvar@(.list (\"fvar\"::_)) => ([fvar],[],[])\n | .list sexps => sexps.foldl (init := ([],[],[]))\n λ (consts,fvars,vars) sexp =>\n let res := sexp.fvarsConstsVars\n (consts.append res.1, fvars.append res.2.1, vars.append res.2.2)\n\n-- We could maybe replace this with `Std.HashMap`, but this should do it for now.\nabbrev VariableMapping := List (String × Sexp)\n\n-- Some generic helper functions\ndef _root_.List.revLookup? {α β : Type 0} [BEq β] : List (α × β) → β → Option α\n | [], _ => none\n | (a,b)::rest, b' => if b == b' then some a else rest.revLookup? b'\n\ndef _root_.List.unique {α : Type 0} [BEq α] : List α → List α\n | [] => []\n | a :: as => if as.contains a then as.unique else (a :: as.unique)\n\ndef _root_.List.unzip3 {α β γ : Type 0} : List (α × β × γ) → List α × List β × List γ\n | abc => let (a,bc) := abc.unzip\n (a,bc.unzip)\n\ndef freshVar (vars : List String) : String := Id.run do\n let mut idx := vars.length\n let mut fresh := s!\"v{idx}\"\n while vars.contains fresh do\n idx := idx + 1\n fresh := s!\"v{idx}\"\n return fresh\n\n\ndef Sexp.head : Sexp → String\n | .atom s => s\n | .list [] => \"\"\n | .list (hd::_) => head hd\n\ndef Sexp.uncurry : Sexp → Sexp\n | a@(.atom _) => a\n | .list [\"ap\", (.list [\"ap\", (.list [\"ap\", (.list [\"ap\", (.atom fname), args4]), args3]), args2]), args1] => .list [(.atom s!\"ap4-{fname}\"), args4.uncurry, args3.uncurry, args2.uncurry, args1.uncurry]\n | .list [\"ap\", (.list [\"ap\", (.list [\"ap\", (.atom fname), args3]), args2]), args1] => .list [s!\"ap3-{fname}\", args3.uncurry, args2.uncurry, args1.uncurry]\n | .list [\"ap\", (.list [\"ap\", (.atom fname), args2]), args1] => .list [s!\"ap2-{fname}\", args2.uncurry, args1.uncurry]\n | .list [\"ap\", (.atom fname), args] => .list [s!\"ap-{fname}\", args.uncurry]\n | l@(.list _) => l\n\n#eval Sexp.uncurry (parseSingleSexp \"(ap (ap mul (ap inv y)) (ap inv x))\" |>.toOption |>.get!) |>.toString\n\n-- partial because of map..\npartial def Sexp.curry : Sexp → Sexp\n | a@(.atom _) => a\n | .list [(.atom (.mk ('a'::'p'::'4'::'-'::fname))), args4, args3, args2, args1] => .list [\"ap\", (.list [\"ap\", (.list [\"ap\", (.list [\"ap\", (.atom (.mk fname)), args4.curry]), args3.curry]), args2.curry]), args1.curry]\n | .list [(.atom (.mk ('a'::'p'::'3'::'-'::fname))), args3, args2, args1] => .list [\"ap\", (.list [\"ap\", (.list [\"ap\", (.atom (.mk fname)), args3.curry]), args2.curry]), args1.curry]\n | .list [(.atom (.mk ('a'::'p'::'2'::'-'::fname))), args2, args1] => .list [\"ap\", (.list [\"ap\", (.atom (.mk fname)), args2.curry]), args1.curry]\n | .list [(.atom (.mk ('a'::'p'::'-'::fname))), args] => .list [\"ap\", (.atom (.mk fname)), args.curry]\n | l@(.list _) => l\n\n\ndef simplifySexps : List Sexp → List Sexp × VariableMapping\n | sexps =>\n let fvarsConstsVars := sexps.foldl (init := ([],[],[]))\n λ (fvs,cs,vs) exp =>\n let res := exp.fvarsConstsVars\n ((fvs ++ res.1).unique, (cs ++ res.2.1).unique, (vs ++ res.2.2).unique)\n let fvars := fvarsConstsVars.1\n let consts := fvarsConstsVars.2.1\n Id.run do\n let mut allVars := fvarsConstsVars.2.2\n let mut mapping := []\n let mut exps := sexps\n for fvar in fvars do\n let vname := freshVar allVars\n mapping := (vname,fvar)::mapping\n allVars := vname::allVars\n exps := exps.map λ exp => replaceTerm fvar (Sexp.atom vname) exp\n for c in consts do\n let vname := freshVar allVars\n mapping := (vname,c)::mapping\n allVars := vname::allVars\n exps := exps.map λ exp => replaceTerm c (Sexp.atom vname) exp\n return (exps, mapping)\n\ndef Sexp.unsimplify : Sexp → VariableMapping → Sexp\n | sexp, mapping => sexp.vars.foldl (init := sexp)\n λ e var => match mapping.lookup var with\n | none => e\n | some subexp => replaceTerm (Sexp.atom var) subexp e\n\ndef unsimplifySExps : List Sexp → VariableMapping → List Sexp\n | sexps, mapping => sexps.map\n λ exp => exp.vars.foldl (init := exp)\n λ e var => match mapping.lookup var with\n | none => e\n | some subexp => replaceTerm (Sexp.atom var) subexp e\n\n\ndef ab := parseSingleSexp \"(a b)\" |>.toOption |>.get!\ndef aab := parseSingleSexp \"(a (a b))\" |>.toOption |>.get!\ndef c := Sexp.atom \"c\"\ndef a := Sexp.atom \"a\"\n#eval ab.toString\n#eval replaceTerm ab c ab |>.toString\n#eval replaceTerm ab c aab |>.toString\n#eval replaceTerm a c aab |>.toString\n#eval replaceTerm ab c aab |> replaceTerm c ab |>.toString\n\n\ndef realexample := parseSexpList \"(ap (fvar (num (str anonymous _uniq) 547)) (ap (fvar (num (str anonymous _uniq) 547)) (fvar (num (str anonymous _uniq) 550)))) (fvar (num (str anonymous _uniq) 550)) (fvar (num (str anonymous _uniq) 549)) (ap (ap (fvar (num (str anonymous _uniq) 548)) (fvar (num (str anonymous _uniq) 550))) (ap (fvar (num (str anonymous _uniq) 547)) (fvar (num (str anonymous _uniq) 550)))) ?_uniq.562 (ap (ap (fvar (num (str anonymous _uniq) 548)) ?_uniq.562) (fvar (num (str anonymous _uniq) 549))) (ap (ap (fvar (num (str anonymous _uniq) 548)) (ap (fvar (num (str anonymous _uniq) 547)) ?_uniq.561)) ?_uniq.561) (fvar (num (str anonymous _uniq) 549)) (ap (ap (fvar (num (str anonymous _uniq) 548)) ?_uniq.558) (ap (ap (fvar (num (str anonymous _uniq) 548)) ?_uniq.559) ?_uniq.560)) (ap (ap (fvar (num (str anonymous _uniq) 548)) (ap (ap (fvar (num (str anonymous _uniq) 548)) ?_uniq.558) ?_uniq.559)) ?_uniq.560)\" |>.toOption.get!\ndef realexampleSimplified := simplifySexps realexample\n#eval realexampleSimplified.1.toString\n#eval realexampleSimplified.1.map (λ e => e.uncurry ) |>.map toString\n#eval (realexampleSimplified.1.map (λ e => e.uncurry.curry) |>.zip realexampleSimplified.1).map λ (a,b) => a == b\n\n#eval realexampleSimplified.2.map λ (s,sexp) => (s,sexp.toString)\n#eval realexampleSimplified.1.map (Sexp.unsimplify · realexampleSimplified.2) |>.zip realexample |>.map λ (a,b) => a == b\ndef exp1 := parseSexpList \"(a (a b)) (b (a b))\" |>.toOption |>.get!\ndef exp2 := parseSexpList \"(c (a b)) ((a b) c)\" |>.toOption |>.get!\ndef exp3 := parseSexpList \"(d ((a b) c)) (((a b) c) d)\" |>.toOption |>.get!\ndef simp1 := simplifySexps exp1\ndef simp2 := simplifySexps exp2\ndef simp3 := simplifySexps exp3\n\n#eval simp1.1 |>.map Sexp.toString\n#eval simp2.1 |>.map Sexp.toString\n#eval simp3.1 |>.map Sexp.toString\n\n#eval unsimplifySExps simp1.1 simp1.2 == exp1\n#eval unsimplifySExps simp2.1 simp2.2 == exp2\n#eval unsimplifySExps simp3.1 simp3.2 == exp3\n\n#eval aab.containsSubexpr a\n#eval aab.containsSubexpr ab\n#eval aab.containsSubexpr c\n\n#eval parseSexpList \"\"\n#eval parseSexpList \"(a, b)\"\n#eval parseSexpList \"(a, \"\n#eval parseSexpList \"a)\"\n#eval parseSexpList \"a b c\"\n#eval parseSexpList \"(a b) (c d)\"\n#eval parseSingleSexp \"(a b)\"\n#eval parseSingleSexp \"(a (b c) d)\"\n", "meta": {"author": "opencompl", "repo": "egg-tactic-code", "sha": "4c37f57478f88d5e11120051012e3d97264c338c", "save_path": "github-repos/lean/opencompl-egg-tactic-code", "path": "github-repos/lean/opencompl-egg-tactic-code/egg-tactic-code-4c37f57478f88d5e11120051012e3d97264c338c/EggTactic/Sexp.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.19436782035217448, "lm_q2_score": 0.04401865456586578, "lm_q1q2_score": 0.008555809942802625}} {"text": "import Structure.Generic.Axioms.Universes\nimport Structure.Generic.Axioms.AbstractFunctors\n\n\n\nset_option autoBoundImplicitLocal false\n--set_option pp.universes true\n\n\n\nnamespace HasLinearFunOp\n\n variable {U : Universe} [HasInternalFunctors U] [h : HasLinearFunOp U]\n\n -- The \"swap\" functor swaps the arguments of a nested functor. Its plain version `swapFun` actually\n -- just fixes the second argument.\n\n def swapIsFun {α β γ : U} (F : α ⟶' β ⟶ γ) (b : β) : HasExternalFunctors.IsFun (λ a : α => F a b) :=\n h.compIsFun F (appFun' b γ)\n\n def swapFun' {α β γ : U} (F : α ⟶' β ⟶ γ) (b : β) : α ⟶' γ := BundledFunctor.mkFun (swapIsFun F b)\n def swapFun {α β γ : U} (F : α ⟶ β ⟶ γ) (b : β) : α ⟶ γ := HasInternalFunctors.fromBundled (swapFun' (HasInternalFunctors.toBundled F) b)\n\n @[simp] theorem swapFun.eff {α β γ : U} (F : α ⟶ β ⟶ γ) (b : β) (a : α) : (swapFun F b) a = F a b :=\n by apply HasInternalFunctors.fromBundled.eff\n\n theorem swapFunFun.def {α β γ : U} (F : α ⟶' β ⟶ γ) (b : β) :\n HasInternalFunctors.fromBundled (swapFun' F b) = HasInternalFunctors.fromBundled (HasInternalFunctors.toBundled (appFun b γ) ⊙' F) :=\n HasInternalFunctors.toFromBundled (appFun' b γ) ▸ rfl\n\n def swapFunIsFun {α β γ : U} (F : α ⟶' β ⟶ γ) : HasExternalFunctors.IsFun (λ b : β => HasInternalFunctors.fromBundled (swapFun' F b)) :=\n funext (swapFunFun.def F) ▸ h.compIsFun (appFunFun' β γ) (compFunFun' F γ)\n\n def swapFunFun' {α β γ : U} (F : α ⟶' β ⟶ γ) : β ⟶' α ⟶ γ := BundledFunctor.mkFun (swapFunIsFun F)\n def swapFunFun {α β γ : U} (F : α ⟶ β ⟶ γ) : β ⟶ α ⟶ γ := HasInternalFunctors.fromBundled (swapFunFun' (HasInternalFunctors.toBundled F))\n\n @[simp] theorem swapFunFun.eff {α β γ : U} (F : α ⟶ β ⟶ γ) (b : β) : (swapFunFun F) b = swapFun F b :=\n by apply HasInternalFunctors.fromBundled.eff\n\n @[simp] theorem swapFunFun.effEff {α β γ : U} (F : α ⟶ β ⟶ γ) (b : β) (a : α) : ((swapFunFun F) b) a = F a b :=\n by simp\n\n theorem swapFunFunFun.def (α β γ : U) (F : α ⟶ β ⟶ γ) :\n HasInternalFunctors.mkFun (swapFunIsFun (HasInternalFunctors.toBundled F)) = HasInternalFunctors.fromBundled (HasInternalFunctors.toBundled (compFunFun F γ) ⊙' appFunFun' β γ) :=\n HasInternalFunctors.toFromBundled (compFunFun' (HasInternalFunctors.toBundled F) γ) ▸ elimRec\n\n def swapFunFunIsFun (α β γ : U) : HasExternalFunctors.IsFun (λ F : α ⟶ β ⟶ γ => swapFunFun F) :=\n funext (swapFunFunFun.def α β γ) ▸ h.compIsFun (compFunFunFun' α (β ⟶ γ) γ) (compFunFun' (appFunFun' β γ) (α ⟶ γ))\n\n def swapFunFunFun' (α β γ : U) : (α ⟶ β ⟶ γ) ⟶' (β ⟶ α ⟶ γ) := BundledFunctor.mkFun (swapFunFunIsFun α β γ)\n def swapFunFunFun (α β γ : U) : (α ⟶ β ⟶ γ) ⟶ (β ⟶ α ⟶ γ) := HasInternalFunctors.fromBundled (swapFunFunFun' α β γ)\n\n @[simp] theorem swapFunFunFun.eff (α β γ : U) (F : α ⟶ β ⟶ γ) : (swapFunFunFun α β γ) F = swapFunFun F :=\n by apply HasInternalFunctors.fromBundled.eff\n\n @[simp] theorem swapFunFunFun.effEff (α β γ : U) (F : α ⟶ β ⟶ γ) (b : β) : ((swapFunFunFun α β γ) F) b = swapFun F b :=\n by simp\n\n @[simp] theorem swapFunFunFun.effEffEff (α β γ : U) (F : α ⟶ β ⟶ γ) (b : β) (a : α) : (((swapFunFunFun α β γ) F) b) a = F a b :=\n by simp\n\n -- In particular, reverse composition is also functorial.\n\n def revCompFun {α β γ : U} (G : β ⟶ γ) (F : α ⟶ β) : α ⟶ γ := compFun F G\n infixr:90 \" ⊙ \" => HasLinearFunOp.revCompFun\n\n @[simp] theorem revCompFun.eff {α β γ : U} (F : α ⟶ β) (G : β ⟶ γ) (a : α) : (G ⊙ F) a = G (F a) :=\n compFun.eff F G a\n\n theorem revCompFunFun.def (α : U) {β γ : U} (G : β ⟶' γ) (F : α ⟶ β) :\n HasInternalFunctors.fromBundled (G ⊙' HasInternalFunctors.toBundled F) = (compFunFun F γ) (HasInternalFunctors.fromBundled G) :=\n Eq.subst (motive := λ H => HasInternalFunctors.fromBundled (H ⊙' HasInternalFunctors.toBundled F) = (compFunFun F γ) (HasInternalFunctors.fromBundled G))\n (HasInternalFunctors.toFromBundled G)\n (Eq.symm (compFunFun.eff F γ (HasInternalFunctors.fromBundled G)))\n\n def revCompFunIsFun (α : U) {β γ : U} (G : β ⟶' γ) :\n HasExternalFunctors.IsFun (λ F : α ⟶ β => HasInternalFunctors.fromBundled (G ⊙' HasInternalFunctors.toBundled F)) :=\n funext (revCompFunFun.def α G) ▸ swapIsFun (compFunFunFun' α β γ) (HasInternalFunctors.fromBundled G)\n\n def revCompFunFun' (α : U) {β γ : U} (G : β ⟶' γ) : (α ⟶ β) ⟶' (α ⟶ γ) := BundledFunctor.mkFun (revCompFunIsFun α G)\n def revCompFunFun (α : U) {β γ : U} (G : β ⟶ γ) : (α ⟶ β) ⟶ (α ⟶ γ) := HasInternalFunctors.fromBundled (revCompFunFun' α (HasInternalFunctors.toBundled G))\n\n @[simp] theorem revCompFunFun.eff (α : U) {β γ : U} (G : β ⟶ γ) (F : α ⟶ β) : (revCompFunFun α G) F = G ⊙ F :=\n by apply HasInternalFunctors.fromBundled.eff\n\n @[simp] theorem revCompFunFun.effEff (α : U) {β γ : U} (G : β ⟶ γ) (F : α ⟶ β) (a : α) : ((revCompFunFun α G) F) a = G (F a) :=\n by simp\n\n theorem revCompFunFunFun.def (α β γ : U) (G : β ⟶ γ) :\n HasInternalFunctors.mkFun (revCompFunIsFun α (HasInternalFunctors.toBundled G)) = HasInternalFunctors.fromBundled (swapFun' (compFunFunFun' α β γ) G) :=\n congrArg (λ H => HasInternalFunctors.fromBundled (swapFun' (compFunFunFun' α β γ) H)) (HasInternalFunctors.fromToBundled G) ▸ elimRec\n\n def revCompFunFunIsFun (α β γ : U) : HasExternalFunctors.IsFun (λ G : β ⟶ γ => revCompFunFun α G) :=\n funext (revCompFunFunFun.def α β γ) ▸ swapFunIsFun (compFunFunFun' α β γ)\n\n def revCompFunFunFun' (α β γ : U) : (β ⟶ γ) ⟶' (α ⟶ β) ⟶ (α ⟶ γ) := BundledFunctor.mkFun (revCompFunFunIsFun α β γ)\n def revCompFunFunFun (α β γ : U) : (β ⟶ γ) ⟶ (α ⟶ β) ⟶ (α ⟶ γ) := HasInternalFunctors.fromBundled (revCompFunFunFun' α β γ)\n\n @[simp] theorem revCompFunFunFun.eff (α β γ : U) (G : β ⟶ γ) : (revCompFunFunFun α β γ) G = revCompFunFun α G :=\n by apply HasInternalFunctors.fromBundled.eff\n\n @[simp] theorem revCompFunFunFun.effEff (α β γ : U) (G : β ⟶ γ) (F : α ⟶ β) : ((revCompFunFunFun α β γ) G) F = G ⊙ F :=\n by simp\n\n @[simp] theorem revCompFunFunFun.effEffEff (α β γ : U) (G : β ⟶ γ) (F : α ⟶ β) (a : α) : (((revCompFunFunFun α β γ) G) F) a = G (F a) :=\n by simp\n\n -- Composition of a function with two arguments.\n\n def compFun₂ {α β γ δ : U} (F : α ⟶ β ⟶ γ) (G : γ ⟶ δ) : α ⟶ β ⟶ δ := swapFunFun (revCompFunFun α G ⊙ swapFunFun F)\n\nend HasLinearFunOp\n\n\n\nnamespace HasFullFunOp\n\n variable {U : Universe} [HasInternalFunctors U] [h : HasFullFunOp U]\n\n -- The S combinator (see https://en.wikipedia.org/wiki/SKI_combinator_calculus), which in our case says\n -- that if we can functorially construct a functor `H : β ⟶ γ` and an argument `b : β`, then the\n -- construction of `H b` is also functorial.\n\n theorem substFun.def {α β γ : U} (F : α ⟶' β ⟶ γ) (G : α ⟶' β) (a : α) :\n F a (G a) = HasInternalFunctors.fromBundled (HasLinearFunOp.swapFun' F (G a)) a :=\n Eq.symm (HasInternalFunctors.fromBundled.eff (HasLinearFunOp.swapFun' F (G a)) a)\n\n def substIsFun {α β γ : U} (F : α ⟶' β ⟶ γ) (G : α ⟶' β) : HasExternalFunctors.IsFun (λ a : α => F a (G a)) :=\n funext (substFun.def F G) ▸ h.dupIsFun (HasLinearFunOp.swapFunFun' F ⊙' G)\n\n def substFun' {α β γ : U} (F : α ⟶' β ⟶ γ) (G : α ⟶' β) : α ⟶' γ := BundledFunctor.mkFun (substIsFun F G)\n def substFun {α β γ : U} (F : α ⟶ β ⟶ γ) (G : α ⟶ β) : α ⟶ γ := HasInternalFunctors.fromBundled (substFun' (HasInternalFunctors.toBundled F) (HasInternalFunctors.toBundled G))\n\n @[simp] theorem substFun.eff {α β γ : U} (F : α ⟶ β ⟶ γ) (G : α ⟶ β) (a : α) : (substFun F G) a = F a (G a) :=\n by apply HasInternalFunctors.fromBundled.eff\n\n theorem substFunFun.def {α β γ : U} (F : α ⟶' β ⟶ γ) (G : α ⟶ β) :\n HasInternalFunctors.mkFun (substIsFun F (HasInternalFunctors.toBundled G)) =\n HasInternalFunctors.fromBundled (HasNonLinearFunOp.dupFun' (HasInternalFunctors.toBundled (HasInternalFunctors.fromBundled (HasLinearFunOp.swapFunFun' F ⊙' HasInternalFunctors.toBundled G)))) :=\n HasInternalFunctors.toFromBundled _ ▸ elimRec\n\n def substFunIsFun {α β γ : U} (F : α ⟶' β ⟶ γ) :\n HasExternalFunctors.IsFun (λ G : α ⟶ β => HasInternalFunctors.fromBundled (substFun' F (HasInternalFunctors.toBundled G))) :=\n funext (substFunFun.def F) ▸ h.compIsFun (HasLinearFunOp.revCompFunFun' α (HasLinearFunOp.swapFunFun' F)) (HasNonLinearFunOp.dupFunFun' α γ)\n\n def substFunFun' {α β γ : U} (F : α ⟶' β ⟶ γ) : (α ⟶ β) ⟶' (α ⟶ γ) := BundledFunctor.mkFun (substFunIsFun F)\n def substFunFun {α β γ : U} (F : α ⟶ β ⟶ γ) : (α ⟶ β) ⟶ (α ⟶ γ) := HasInternalFunctors.fromBundled (substFunFun' (HasInternalFunctors.toBundled F))\n\n @[simp] theorem substFunFun.eff {α β γ : U} (F : α ⟶ β ⟶ γ) (G : α ⟶ β) : (substFunFun F) G = substFun F G :=\n by apply HasInternalFunctors.fromBundled.eff\n\n @[simp] theorem substFunFun.effEff {α β γ : U} (F : α ⟶ β ⟶ γ) (G : α ⟶ β) (a : α) : ((substFunFun F) G) a = F a (G a) :=\n by simp\n\n theorem substFunFunFun.def (α β γ : U) (F : α ⟶ β ⟶ γ) :\n HasInternalFunctors.mkFun (substFunIsFun (HasInternalFunctors.toBundled F)) = HasInternalFunctors.fromBundled (HasNonLinearFunOp.dupFunFun' α γ ⊙' HasInternalFunctors.toBundled (HasLinearFunOp.revCompFunFun α (HasLinearFunOp.swapFunFun F))) :=\n HasInternalFunctors.toFromBundled _ ▸ HasInternalFunctors.toFromBundled _ ▸ elimRec\n\n def substFunFunIsFun (α β γ : U) : HasExternalFunctors.IsFun (λ F : α ⟶ β ⟶ γ => substFunFun F) :=\n funext (substFunFunFun.def α β γ) ▸ h.compIsFun (HasLinearFunOp.revCompFunFunFun' α β (α ⟶ γ) ⊙' HasLinearFunOp.swapFunFunFun' α β γ)\n (HasLinearFunOp.revCompFunFun' (α ⟶ β) (HasNonLinearFunOp.dupFunFun' α γ))\n\n def substFunFunFun' (α β γ : U) : (α ⟶ β ⟶ γ) ⟶' (α ⟶ β) ⟶ (α ⟶ γ) := BundledFunctor.mkFun (substFunFunIsFun α β γ)\n def substFunFunFun (α β γ : U) : (α ⟶ β ⟶ γ) ⟶ (α ⟶ β) ⟶ (α ⟶ γ) := HasInternalFunctors.fromBundled (substFunFunFun' α β γ)\n\n @[simp] theorem substFunFunFun.eff (α β γ : U) (F : α ⟶ β ⟶ γ) : (substFunFunFun α β γ) F = substFunFun F :=\n by apply HasInternalFunctors.fromBundled.eff\n\n @[simp] theorem substFunFunFun.effEff (α β γ : U) (F : α ⟶ β ⟶ γ) (G : α ⟶ β) : ((substFunFunFun α β γ) F) G = substFun F G :=\n by simp\n\n @[simp] theorem substFunFunFun.effEffEff (α β γ : U) (F : α ⟶ β ⟶ γ) (G : α ⟶ β) (a : α) : (((substFunFunFun α β γ) F) G) a = F a (G a) :=\n by simp\n\nend HasFullFunOp\n\n\n\n-- Using the functoriality axioms and the constructions above, we can algorithmically prove\n-- functoriality of lambda terms. The algorithm to prove `HasExternalFunctors.IsFun (λ a : α => t)`\n-- is as follows:\n--\n-- Case | Proof\n-- --------------------------------+--------------------------------------------------------------\n-- `t` does not contain `a` | `constIsFun α t`\n-- `t` is `a` | `idIsFun α`\n-- `t` is `G b` with `G : β ⟶ γ`: |\n-- `a` appears only in `b` | Prove that `λ a => b` is functorial, yielding a functor\n-- | `F : α ⟶ β`. Then the proof is `compIsFun F G`.\n-- `b` is `a` | Optimization: `HasInternalFunctors.isFun G`\n-- `a` appears only in `G` | Prove that `λ a => G` is functorial, yielding a functor\n-- | `F : α ⟶ β ⟶ γ`. Then the proof is `swapIsFun F b`.\n-- `G` is `a` | Optimization: `appIsFun b γ`\n-- `a` appears in both | Prove that `λ a => G` is functorial, yielding a functor\n-- | `F₁ : α ⟶ β ⟶ γ`. Prove that `λ a => b` is functorial,\n-- | yielding a functor `F₂ : α ⟶ β`. Then the proof is\n-- | `substIsFun F₁ F₂`.\n-- `t` is `mkFun (λ b : β => c)` | Prove that `λ a => c` is functorial when regarding `b` as\n-- | a constant, yielding a functor `F : α ⟶ γ` for every `b`.\n-- | Prove that `λ b => F` is functorial, yielding a functor\n-- | `G : β ⟶ α ⟶ γ`. Then the proof is `swapFunIsFun G`.\n--\n-- (This list does not contain all possible optimizations.)\n", "meta": {"author": "SReichelt", "repo": "lean4-experiments", "sha": "ff55357a01a34a91bf670d712637480089085ee4", "save_path": "github-repos/lean/SReichelt-lean4-experiments", "path": "github-repos/lean/SReichelt-lean4-experiments/lean4-experiments-ff55357a01a34a91bf670d712637480089085ee4/Structure/Generic/Lemmas/DerivedFunctors.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.37022539259558657, "lm_q2_score": 0.022977368613751804, "lm_q1q2_score": 0.00850680531583977}} {"text": "import .nonneg_rat\nimport .mask\n\nnamespace simplify\n\nstructure O := (n : nat)\n\ninstance dec_eq_o (o o' : O) [nat_dec : ∀n n' : nat, decidable (n = n')] : decidable (o = o') := begin\n induction o, induction o',\n rw O.mk.inj_eq,\n exact nat_dec o o',\nend\n\ninductive X\n| div : X\n| null : X\n| ass : X\n| perm : X\n\ninductive Ref\n| o : O → Ref\n| null : Ref\n\ninstance dec_eq_ref (r r' : Ref) [o_dec : ∀o o' : O, decidable (o = o')] [f_dec : decidable false] [t_dec : decidable true] : decidable (r = r') := begin\n have ineq : ∀o : O, (Ref.null = Ref.o o) = false, cc,\n have ineq' : ∀o : O, (Ref.o o = Ref.null) = false, cc,\n\n induction r,\n\n induction r',\n rw Ref.o.inj_eq,\n exact o_dec r r',\n rw ineq' r,\n exact f_dec,\n\n induction r',\n rw ineq r',\n exact f_dec,\n rw Ref.null.inj_eq,\n exact t_dec,\nend\n\ninductive V\n| b : bool → V\n| z : ℤ → V\n| q : ℚ* → V\n| o : Ref → V\n\nstructure var := (n : nat)\nstructure field := (n : nat)\nstructure func := (n : nat)\nstructure pred := (n : nat)\n\ninductive T\n| B : T\n| Z : T\n| O : T\n| Q : T\n\ndef V.typ : V → T\n| (V.b _) := T.B\n| (V.z _) := T.Z\n| (V.o _) := T.O\n| (V.q _) := T.Q\n\ndef H := field × O → V\ndef S := var → V\ndef FieldPermMask := mask (field × O)\ndef PredPermMask := mask (pred × list V)\n\nstructure conf :=\n(h : H)\n(s : S)\n(fieldPerm : FieldPermMask)\n(predPerm : PredPermMask)\n\ninductive E\n| null : E\n| const_b : bool → E\n| const_n : ℤ → E\n| x : var → E\n| deref : E → field → E\n| negate : E → E\n| add : E → E → E\n| div : E → E → E\n| not : E → E\n| eq : E → E → E\n| apply : func → list E → E\n| unfolding : pred → list E → E → E → E\n| fieldPerm : E → field → E\n| predPerm : pred → list E → E\n\ninductive A\n| e : E → A\n| fieldAcc : E → field → E → A\n| predAcc : pred → list E → E → A\n| imp : E → A → A\n| conj : A → A → A\n| all : T → (E → A) → A\n| ex : T → (E → A) → A\n| forperm : field → E → A\n\ninductive Eval\n| type_err : Eval\n| err : X → Eval\n| ok : V → Eval\n\ndef Eval.is_x : Eval → Prop\n| Eval.type_err := false\n| (Eval.err _) := true\n| (Eval.ok _) := false\n\ndef Eval.is_v : Eval → Prop\n| Eval.type_err := false\n| (Eval.err _) := false\n| (Eval.ok _) := true\n\ndef v_of_is_v {e : Eval} (h : e.is_v) : V := begin\n cases e,\n case ok { exact e, },\n repeat { simp [Eval.is_v] at h, apply false.elim, exact h, },\nend\n\ndef Eval.is_t : Eval → T → Prop\n| Eval.type_err _ := false\n| (Eval.err _) _ := false\n| (Eval.ok v) t := v.typ = t\n\nstructure defs :=\n(var : var → T) \n(field : field → T)\n(func : func → (list T) × T × (list V → Eval)) -- shamelessly shallowly embed lean functions, to not deal with termination.\n(pred : pred → (list T))\n\ndef E.typ (d : defs) : E → T\n| (E.null) := T.O\n| (E.const_b b) := T.B\n| (E.const_n z) := T.Z\n| (E.x x) := d.var x\n| (E.deref o f) := d.field f\n| (E.negate z) := z.typ\n| (E.add z z') := z.typ\n| (E.div z z') := z.typ\n| (E.not b) := T.B\n| (E.eq v v') := T.B\n| (E.apply f args) := (d.func f).snd.fst\n| (E.unfolding p args q e) := e.typ\n| (E.fieldPerm o f) := T.Q\n| (E.predPerm p args) := T.Q\n\ndef all_typed (d : defs) : list E → list T → Prop\n| [] [] := true\n| [] (_ :: _) := false\n| (_ :: _) [] := false\n| (e :: es) (t :: ts) := e.typ d = t ∧ all_typed es ts\n\nmutual def all_wt, wt (d : defs)\nwith all_wt : list E → Prop\n| [] := true\n| (e :: es) := (wt e ∧ all_wt es)\n\nwith wt : E → Prop\n| E.null := true\n| (E.const_b b) := true\n| (E.const_n z) := true\n| (E.x x) := true\n| (E.deref o f) := o.typ d = T.O ∧ wt o\n| (E.negate z) := z.typ d = T.Z ∧ wt z\n| (E.add z z') := z.typ d = z'.typ d ∧ (z.typ d = T.Z ∨ z.typ d = T.Q) ∧ wt z ∧ wt z'\n| (E.div z z') := z.typ d = z'.typ d ∧ (z.typ d = T.Z ∨ z.typ d = T.Q) ∧ wt z ∧ wt z'\n| (E.not b) := b.typ d = T.B ∧ wt b\n| (E.eq v v') := v.typ d = v'.typ d ∧ wt v ∧ wt v'\n| (E.apply f args) := all_typed d args (d.func f).fst ∧ all_wt args\n| (E.unfolding p args q e) := all_typed d args (d.pred p) ∧ all_wt args ∧ wt q ∧ wt e\n| (E.fieldPerm o f) := o.typ d = T.O ∧ wt o\n| (E.predPerm p args) := all_typed d args (d.pred p) ∧ all_wt args\n\ndef conf.wt (d : defs) (c : conf) : Prop :=\n (∀x, (c.s x).typ = d.var x)\n ∧ (∀f o, (c.h (f, o)).typ = d.field f)\n\ndef Eval.map_v (e : Eval) (f : V → Eval) : Eval := match e with\n| Eval.type_err := Eval.type_err\n| Eval.err x := Eval.err x\n| Eval.ok v := f v\nend\n\n#print Eval.rec\n\nlemma map_v_is_x_or_t \n : ∀ {t t' : T} {f : V → Eval} (e : Eval),\n e.is_x ∨ e.is_t t' →\n (∀ (v : V) (h : e = Eval.ok v), (f v).is_x ∨ (f v).is_t t) → \n (e.map_v f).is_x ∨ (e.map_v f).is_t t \n := \nbegin\n intros t t' f e,\n cases e,\n\n case type_err {\n intros e_x_or_t f_all_v,\n simp [Eval.is_x, Eval.is_v] at e_x_or_t, \n apply false.elim, exact e_x_or_t,\n },\n\n case err {\n intros e_x_or_t v,\n simp [Eval.map_v, Eval.is_x],\n },\n\n case ok {\n intros e_x_or_t v,\n simp [Eval.map_v],\n exact v e rfl,\n },\nend\n\nlemma eval_ok_t {e : Eval} {t : T} {v : V} :\n (Eval.ok v).is_t t ↔ v.typ = t := by simp [Eval.is_t]\n\ndef Eval.cases_v (e : Eval) (f_b : bool → Eval) (f_z : ℤ → Eval) (f_q : ℚ* → Eval) (f_o : Ref → Eval) :=\n e.map_v $ λv, match v with\n | V.b b := f_b b\n | V.z z := f_z z\n | V.q q := f_q q\n | V.o o := f_o o\n end\n\ndef evals_map' : list V → (list V → Eval) → list Eval → Eval\n| acc f [] := f acc\n| acc f (e :: es) := e.map_v $ λv, evals_map' (acc ++ [v]) f es\n\ndef evals_map (es : list Eval) (f : list V → Eval) : Eval :=\n evals_map' [] f es\n\nlemma evals_map_x_or_t : \n ∀ {t : T} (f : list V → Eval) (es : list Eval),\n (∀e : Eval, ∃t : T, e ∈ es → e.is_x ∨ e.is_t t) →\n (∀ (vs : list V) (h : es = vs.map Eval.ok), (f vs).is_x ∨ (f vs).is_t t) →\n (evals_map es f).is_x ∨ (evals_map es f).is_t t :=\nbegin\n intros t f es,\n intros no_type_err,\n intros ok_f_no_type_err,\n \n induction es,\n\n case nil {\n simp only [evals_map, evals_map'],\n apply ok_f_no_type_err list.nil,\n simp only [list.map],\n },\n\n case cons : e es ih {\n simp only [evals_map, evals_map'],\n apply map_v_is_x_or_t,\n apply exists.elim,\n exact no_type_err e,\n intro t_before,\n simp,\n intro e_ok,\n /-exact e_ok,-/ sorry,\n\n sorry,\n sorry,\n },\nend\n\nmutual def eval, evals (d : defs)\nwith eval : conf → E → Eval\n| c (E.null) := Eval.ok (V.o Ref.null)\n| c (E.const_b b) := Eval.ok (V.b b)\n| c (E.const_n z) := Eval.ok (V.z z)\n| c (E.x x) := Eval.ok (c.s x)\n| c (E.deref o f) := (eval c o).map_v $ λv, \n match v with\n | (V.o Ref.null) := Eval.err X.null\n | (V.o (Ref.o o)) := if c.fieldPerm (f, o) = 0 then Eval.err X.perm else Eval.ok $ c.h (f, o)\n | _ := Eval.type_err\n end\n| c (E.negate z) := (eval c z).map_v $ λv,\n match v with\n | (V.z z) := Eval.ok $ V.z (-z)\n | _ := Eval.type_err\n end\n| c (E.add z z') := (eval c z).map_v $ λz, (eval c z').map_v $ λz',\n match z, z' with\n | (V.z z), (V.z z') := Eval.ok $ V.z (z + z')\n | (V.q q), (V.q q') := Eval.ok $ V.q (q + q')\n | _, _ := Eval.type_err\n end\n| c (E.div z z') := (eval c z).map_v $ λz, (eval c z').map_v $ λz',\n match z, z' with\n | (V.z z), (V.z z') := if z' = 0 then Eval.err X.div else Eval.ok $ V.z $ int.div /- or flooring, round to zero? -/ z z'\n | (V.q q), (V.q q') := if q' = 0 then Eval.err X.div else Eval.ok $ V.q (q / q')\n | _, _ := Eval.type_err\n end\n| c (E.not b) := (eval c b).map_v $ λv,\n match v with\n | (V.b b) := Eval.ok $ V.b ¬b\n | _ := Eval.type_err\n end\n| c (E.eq v v') := (eval c v).map_v $ λv, (eval c v').map_v $ λv',\n match v, v' with\n | (V.b b), (V.b b') := Eval.ok $ V.b $ if b = b' then tt else ff\n | (V.z z), (V.z z') := Eval.ok $ V.b $ if z = z' then tt else ff\n | (V.q q), (V.q q') := Eval.ok $ V.b $ if q = q' then tt else ff\n | (V.o o), (V.o o') := Eval.ok $ V.b $ if o = o' then tt else ff\n | _, _ := Eval.type_err\n end\n| c (E.apply f args) := evals_map (evals c args) $ λargs, ((d.func f).snd.snd args)\n| c (E.unfolding p args q e) := evals_map (evals c args) $\n λargs, if c.predPerm (p, args) < 1\n then Eval.err X.perm\n else (eval c e).map_v $ λbody, Eval.ok (V.b ff)\n| c (E.fieldPerm o f) := (eval c o).map_v $ λo,\n match o with\n | (V.o Ref.null) := Eval.err X.null\n | (V.o (Ref.o o)) := Eval.ok $ V.q $ c.fieldPerm (f, o)\n | _ := Eval.type_err\n end\n| c (E.predPerm p args) := evals_map (evals c args)$ λargs, \n Eval.ok $ V.q $ c.predPerm (p, args)\n\nwith evals : conf → list E → list Eval\n| c [] := []\n| c (e :: es) := (eval c e) :: (evals c es)\n\n#print decidable.rec\n\nlemma x {α : Type} (c : Prop) [decidable c] (a a' : α) : (ite c a a') = (ite (¬c) a' a) := begin\n exact (ite_not c a' a).symm\nend \n\nlemma ite_prop {α : Type} {prop : α → Prop} {c : Prop} [h : decidable c] {a a' : α} :\n (c → prop a) ∧ (¬c → prop a') ↔ prop (ite c a a') := begin\n apply iff.intro,\n intro props,\n rw ite,\n apply h.rec_on,\n\n intro not_c,\n simp [(is_false not_c).rec_on], exact props.elim_right not_c,\n intro c,\n simp [(is_true c).rec_on], exact props.elim_left c,\n\n rw ite,\n apply h.rec_on,\n intro not_c,\n simp [(is_false not_c).rec_on],\n intro prop_a', finish,\n intro c,\n simp [(is_true c).rec_on],\n intro prop_a, finish,\nend\n\ntheorem wt_sufficient {c : conf} {d : defs} {e : E} (h : wt d e) (ch : c.wt d)\n : (eval d c e).is_x ∨ (eval d c e).is_t (e.typ d) := \nbegin\n rw conf.wt at ch,\n have var_ok : ∀x, (c.s x).typ = d.var x, exact and.elim_left ch,\n have field_ok : ∀f o, (c.h (f,o)).typ = d.field f, exact and.elim_right ch,\n clear ch,\n\n induction e,\n repeat { simp only [eval, wt, Eval.is_t, E.typ, V.typ, Eval.is_x, Eval.is_t, false_or, rfl] at *, },\n\n -- case x : x { exact var_ok x, },\n\n -- case deref : o f ih {\n -- apply map_v_is_x_or_t,\n -- exact ih (and.elim_right h),\n -- intros v v_ok,\n -- rw v_ok at *,\n -- cases v,\n -- repeat { simp [eval, Eval.is_x, Eval.is_t, V.typ, h.elim_left] at *, exact ih h, },\n -- cases v,\n -- simp [eval],\n -- by_cases c.fieldPerm (f, v) = 0,\n -- simp [h, Eval.is_x, Eval.is_t],\n -- rw ←ite_not,\n -- simp at h,\n -- simp [h, Eval.is_x, Eval.is_t, field_ok f v],\n -- simp [eval, Eval.is_t, Eval.is_x],\n -- },\n\n -- case negate : z ih {\n -- apply map_v_is_x_or_t,\n -- exact ih h.elim_right,\n -- intros v v_ok,\n -- rw v_ok at *,\n -- cases v,\n -- repeat { simp [eval] at *, },\n\n -- repeat { simp [eval, Eval.is_x, Eval.is_t, h.elim_left, V.typ] at *, },\n -- repeat { exact ih h, },\n -- },\n\n -- case add : z z' ih ih' {\n -- apply map_v_is_x_or_t,\n -- exact ih h.elim_right.elim_right.elim_left,\n -- intros v v_ok,\n -- rw v_ok at *,\n -- apply map_v_is_x_or_t,\n -- exact ih' h.elim_right.elim_right.elim_right,\n -- intros v' v_ok',\n -- rw v_ok' at *,\n -- by_cases is_t_z : (z.typ d) = T.Z,\n\n -- cases v,\n -- repeat { simp [is_t_z] at *, },\n -- repeat { simp [eval, Eval.is_x, Eval.is_t, V.typ] at ih, apply false.elim, exact ih h.elim_right.elim_left, },\n -- cases v',\n -- repeat { simp [eval, Eval.is_x, Eval.is_t, V.typ, ←h.elim_left] at ih', apply false.elim, exact ih' h.elim_right.elim_right, },\n\n -- simp [eval, Eval.is_t, Eval.is_x, V.typ],\n\n -- cases v,\n -- repeat { simp [eval, Eval.is_x, Eval.is_t, V.typ, h.elim_right.elim_left] at ih, apply false.elim, exact ih h.elim_right.elim_right.elim_left, },\n -- cases v',\n -- repeat { simp [eval, Eval.is_x, Eval.is_t, V.typ, h.elim_right.elim_left, ←h.elim_left] at ih', apply false.elim, exact ih' h.elim_right.elim_right.elim_right, },\n \n -- simp [eval, Eval.is_t, Eval.is_x, V.typ, h.elim_right.elim_left],\n -- },\n\n -- case div : z z' ih ih' {\n -- apply map_v_is_x_or_t,\n -- exact ih h.elim_right.elim_right.elim_left,\n -- intros v v_ok,\n -- rw v_ok at *,\n -- apply map_v_is_x_or_t,\n -- exact ih' h.elim_right.elim_right.elim_right,\n -- intros v' v_ok',\n -- rw v_ok' at *,\n -- by_cases is_t_z : (z.typ d) = T.Z,\n\n -- cases v,\n -- repeat { simp [is_t_z] at *, },\n -- repeat { simp [eval, Eval.is_x, Eval.is_t, V.typ] at ih, apply false.elim, exact ih h.elim_right.elim_left, },\n -- cases v',\n -- repeat { simp [eval, Eval.is_x, Eval.is_t, V.typ, ←h.elim_left] at ih', apply false.elim, exact ih' h.elim_right.elim_right, },\n\n -- rw eval,\n -- by_cases div_zero : v' = 0,\n -- simp [div_zero, Eval.is_x],\n -- rw ←ite_not,\n -- simp [div_zero, Eval.is_t, V.typ],\n\n -- cases v,\n -- repeat { simp [eval, Eval.is_x, Eval.is_t, V.typ, h.elim_right.elim_left] at ih, apply false.elim, exact ih h.elim_right.elim_right.elim_left, },\n -- cases v',\n -- repeat { simp [eval, Eval.is_x, Eval.is_t, V.typ, ←h.elim_left, h.elim_right.elim_left] at ih', apply false.elim, exact ih' h.elim_right.elim_right.elim_right, },\n\n -- rw eval,\n -- by_cases div_zero : v' = 0,\n -- simp [div_zero, Eval.is_x],\n -- rw ←ite_not,\n -- simp [div_zero, Eval.is_t, V.typ, h.elim_right.elim_left],\n -- },\n\n -- case not : b ih {\n -- apply map_v_is_x_or_t,\n -- exact ih h.elim_right,\n -- intros v v_ok,\n -- rw v_ok at *,\n -- cases v,\n -- repeat { simp only [eval, Eval.is_x, Eval.is_t, V.typ, false_or], },\n -- repeat { simp only [h.elim_left, Eval.is_x, Eval.is_t, V.typ, false_or] at ih, },\n -- repeat { exact ih h.elim_right },\n -- },\n\n -- case eq : l r ih ih' {\n -- have t_eq : l.typ d = r.typ d, from h.elim_left,\n -- have wt_l : wt d l, from h.elim_right.elim_left,\n -- have wt_r : wt d r, from h.elim_right.elim_right,\n -- clear h,\n\n -- apply map_v_is_x_or_t,\n -- exact ih wt_l,\n -- intros v v_ok,\n -- apply map_v_is_x_or_t,\n -- exact ih' wt_r,\n -- intros v' v_ok',\n -- rw v_ok at *, rw v_ok' at *,\n \n -- cases v,\n -- repeat {\n -- cases v',\n -- repeat {\n -- simp only [eval],\n -- simp only [Eval.is_t, V.typ], \n -- apply or.intro_right, \n -- refl,\n -- },\n -- repeat {\n -- simp only [eval], simp only [Eval.is_t, Eval.is_x, V.typ, or_false],\n -- simp only [Eval.is_x, Eval.is_t, V.typ, false_or] at ih,\n -- simp only [Eval.is_x, Eval.is_t, V.typ, false_or, ←t_eq, ←ih wt_l] at ih',\n -- exact ih' wt_r,\n -- },\n -- },\n -- },\n\n case apply : f args {\n apply map_v_is_x_or_t,\n },\n\n repeat { sorry, },\nend\n\nend simplify", "meta": {"author": "pieter-bos", "repo": "vercors-lean", "sha": "45f545e3f85489ee1dcaefe2b79f99d4aa0d3e5f", "save_path": "github-repos/lean/pieter-bos-vercors-lean", "path": "github-repos/lean/pieter-bos-vercors-lean/vercors-lean-45f545e3f85489ee1dcaefe2b79f99d4aa0d3e5f/lean/simplify.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4726834766204328, "lm_q2_score": 0.017986211705757402, "lm_q1q2_score": 0.008501785080308534}} {"text": "-- import circuits.circuit_encoding\n-- import polytime.data_structures.finset\n\n-- namespace function\n-- /- Note that Lean fails to infer something like\n-- (infer_instance : ∀ x : α, has_uncurry (list (β x) → list (β x) → list (β x)) _ _)\n-- unless all the underscores are made explicit for some reason.\n-- (infer_instance : ∀ x : α, has_uncurry (list (β x) → list (β x) → list (β x)) (list (β x) × list (β x)) (list $ β x))\n\n-- This is why we make the following instances\n-- -/\n-- universes u v\n-- variables {α : Type} {β β₁ β₂ γ δ : α → Type}\n\n-- class has_uncurry_dep {α : Type} (β : α → Type) (β₁ β₂ : out_param (α → Type)) :=\n-- (uncurry : ∀ {x}, (β x) → ((β₁ x) → (β₂ x)))\n\n-- notation (name := uncurry_dep) `↾`:max x:max := has_uncurry_dep.uncurry _ x\n\n-- instance has_uncurry_dep_base : has_uncurry_dep (λ x, (β₁ x → β₂ x)) β₁ β₂ := ⟨λ x y, y⟩\n\n-- instance has_uncurry_dep_induction [has_uncurry_dep γ β₁ β₂] : has_uncurry_dep (λ x, δ x → γ x) (λ x, δ x × β₁ x) β₂ :=\n-- ⟨λ x f p, ↾(f p.1) p.2⟩\n\n-- end function\n\n-- open_locale complexity_class\n-- open function tencodable\n\n-- namespace complexity_class\n\n-- variables {α : Type} {β : α → Type} {β₁ : α → Type} {β₂ : α → Type} {γ δ : Type}\n-- [tencodable α] [∀ x, tencodable (β x)] [∀ x, tencodable (β₁ x)] [∀ x, tencodable (β₂ x)]\n-- [tencodable γ] [tencodable δ] {C : complexity_class}\n\n-- /-- Membership of a dependent function in a complexity class;\n-- Note: we only ever need *one* dependent argument for almost everything we do\n \n-- TODO: can we unify `mem_dep` (\"base case\") and `mem_dep₂`?\n-- Can we and should we use has_uncurry_dep so that `mem_dep₂` is automatically\n-- generalized for >2 arguments?\n \n-- Should we generate composition lemmas for `mem_dep` and `mem_dep₂`? If so, what are they? -/\n-- def mem_dep (f : ∀ x, β x) (C : complexity_class) : Prop :=\n-- ∃ (f' : tree unit → tree unit), f' ∈ₑ C ∧\n-- ∀ x : α, f' (encode x) = encode (f x)\n\n-- localized \"infix ` ∈ₐ `:50 := complexity_class.mem_dep\" in complexity_class\n\n-- /-- `fintype` but \"C\"-constructible -/\n-- def mem_types (β : α → Type) [∀ x, tencodable (β x)] [∀ x, decidable_eq (β x)]\n-- [∀ x, fintype (β x)] (C : complexity_class) : Prop :=\n-- (λ x : α, @finset.univ (β x) _) ∈ₐ C\n\n-- def mem_dep₂ (f : ∀ x, β₁ x → β₂ x) (C : complexity_class) : Prop :=\n-- (λ x : sigma β₁, f x.1 x.2) ∈ₐ C\n\n-- -- \"t\" for \"two\" ??\n-- localized \"infix ` ∈ₜ `:50 := complexity_class.mem_dep₂\" in complexity_class\n-- open_locale tree\n\n-- @[simp] lemma mem_dep_iff {f : α → γ} : f ∈ₐ C ↔ f ∈ₑ C :=\n-- by { simp_rw [mem_dep, ← prop_iff_mem], refl, }\n\n-- lemma mem_dep₂_iff {f : α → γ → δ} : f ∈ₜ C ↔ f ∈ₑ C :=\n-- by { dunfold mem_dep₂, rw mem_dep_iff, split; { rintro ⟨f', pf, hf⟩, refine ⟨f', pf, _⟩, rintro ⟨a, b⟩, exact hf ⟨a, b⟩, }, }\n\n-- @[complexity] lemma mem_dep_of_mem {f : α → γ} (h : f ∈ₑ C) : f ∈ₐ C := by rwa mem_dep_iff\n-- @[complexity] lemma mem_dep₂_of_mem {f : α → γ → δ} (h : f ∈ₑ C) : f ∈ₜ C := by rwa mem_dep₂_iff \n\n-- lemma mem_iff_comp_encode_dep {f : ∀ x, β x} :\n-- f ∈ₐ C ↔ (λ x, encode (f x)) ∈ₑ C :=\n-- by { rw ← mem_dep_iff, refl, }\n\n-- lemma _root_.list.encode_map_encode (l : list α) :\n-- encode (l.map encode) = encode l := by simp only [encode, list.map_id]\n\n-- lemma mem_iff_comp_list_encode_dep {f : ∀ x, list (β x)} :\n-- f ∈ₐ C ↔ (λ x, (f x).map encode) ∈ₑ C :=\n-- by { rw [mem_iff_comp_encode, mem_iff_comp_encode_dep], simp only [list.encode_map_encode], }\n\n-- end complexity_class\n\n-- /-- A function which is encoded as a table -/\n-- structure complexity_class.table_fun (α β : Type*) :=\n-- (to_fun : α → β)\n\n-- namespace complexity_class.table_fun\n-- open_locale complexity_class\n-- variables {α β γ : Type*}\n\n-- localized \"infixr ` [→] `:25 := complexity_class.table_fun\" in complexity_class\n\n-- instance : has_coe_to_fun (α [→] β) (λ _, α → β) := ⟨table_fun.to_fun⟩\n\n-- @[ext]\n-- protected lemma ext : ∀ (f g : α [→] β), ⇑f = (by exact ⇑g) → f = g\n-- | ⟨f⟩ ⟨g⟩ rfl := rfl\n\n-- @[simp] lemma to_fun_eq_coe (f : α [→] β) : f.to_fun = ⇑f := rfl\n\n-- @[simps]\n-- def equiv_fun : (α [→] β) ≃ (α → β) := ⟨λ f, ⇑f, λ f, ⟨f⟩, λ f, by ext; refl, λ f, rfl⟩\n\n-- @[simps]\n-- def sum (f : α [→] γ) (g : β [→] γ) : α ⊕ β [→] γ := ⟨sum.elim ⇑f ⇑g⟩\n\n-- @[simps]\n-- def map (f : α [→] β) (g : β → γ) : α [→] γ := ⟨λ x, g (f x)⟩\n\n-- @[simps]\n-- def comp (f : α [→] β) (g : γ [→] α) : γ [→] β := ⟨λ x, f (g x)⟩\n\n-- def finmap_equiv_fun [fintype α] [decidable_eq α] :\n-- {x : @finmap α (λ _, β) // ∀ k : α, k ∈ x} ≃ (α → β) :=\n-- { to_fun := λ f x, @option.get _ ((↑f : finmap _).lookup x) (finmap.lookup_is_some.mpr $ f.prop x),\n-- inv_fun := λ f, ⟨finmap.of_fun f, λ k, finmap.mem_iff.mpr ⟨_, finmap.of_fun_lookup k⟩⟩,\n-- left_inv := λ f, by { ext : 1, apply finmap.ext_lookup, simp, },\n-- right_inv := λ f, by { ext, simp, } } \n\n-- variables [tencodable α] [fintype α] [decidable_eq α] [tencodable β] [tencodable γ]\n\n-- instance : tencodable (α [→] β) :=\n-- tencodable.of_equiv _ (equiv_fun.trans finmap_equiv_fun.symm)\n\n-- lemma encode_table_fun (f : α [→] β) : encode f = encode (finmap_equiv_fun.symm ⇑f) :=\n-- rfl\n\n-- lemma table_fun_mk_of {γ : Type} {ψ₁ ψ₂ : γ → Type} [tencodable γ] [∀ x, tencodable (ψ₁ x)] \n-- [∀ x, fintype (ψ₁ x)] [∀ x, decidable_eq (ψ₁ x)] [∀ x, tencodable (ψ₂ x)] {f : ∀ x, (ψ₁ x → ψ₂ x)}\n-- (hψ : polytime.mem_types ψ₁) (hf : f ∈ₜ PTIME) : (λ x, table_fun.mk (f x) : ∀ x, ψ₁ x [→] ψ₂ x) ∈ₐ PTIME := \n-- sorry\n\n-- end complexity_class.table_fun\n\n-- namespace polytime\n-- open_locale complexity_class\n-- open_locale tree\n-- open complexity_class\n\n-- variables {α : Type} {β : α → Type} {β₁ : α → Type} {β₂ : α → Type} {γ δ : Type}\n-- [tencodable α] [∀ x, tencodable (β x)] [∀ x, tencodable (β₁ x)] [∀ x, tencodable (β₂ x)]\n-- [tencodable γ] [tencodable δ] {C : complexity_class}\n\n-- @[complexity] lemma list_map_dep {l : ∀ x, list (β₁ x)} {f : ∀ x, β₁ x → β₂ x} (hl : l ∈ₐ PTIME)\n-- (hf : f ∈ₜ PTIME) : (λ x : α, (l x).map (f x) : ∀ x, list (β₂ x)) ∈ₐ PTIME :=\n-- begin\n-- rcases hf with ⟨f', pf, hf⟩,\n-- rw mem_iff_comp_list_encode_dep at ⊢ hl,\n-- complexity using λ x, ((l x).map encode).map (λ y, f' (encode x △ y)),\n-- simp at hf, dsimp [tencodable.encode_sigma] at hf, simp [function.comp, hf],\n-- end\n\n-- @[complexity] lemma list_append_dep {l₁ l₂ : ∀ x, list (β x)} (hl₁ : l₁ ∈ₐ PTIME) (hl₂ : l₂ ∈ₐ PTIME) :\n-- (λ x, (l₁ x) ++ (l₂ x)) ∈ₐ PTIME :=\n-- by { rw [mem_iff_comp_list_encode_dep] at *, simp only [list.map_append], complexity, }\n\n-- end polytime", "meta": {"author": "prakol16", "repo": "circuits", "sha": "cdf4ce1e019d6817e4abe0d082d8d379539fddca", "save_path": "github-repos/lean/prakol16-circuits", "path": "github-repos/lean/prakol16-circuits/circuits-cdf4ce1e019d6817e4abe0d082d8d379539fddca/src/circuits/dependent_test.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3629691917376783, "lm_q2_score": 0.02333077110040581, "lm_q1q2_score": 0.00846835112893108}} {"text": "/-\nCopyright (c) 2016 Gabriel Ebner. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Gabriel Ebner, Sebastian Ullrich\n\nClassy functions for lifting monadic actions of different shapes.\n\nThis theory is roughly modeled after the Haskell 'layers' package https://hackage.haskell.org/package/layers-0.1.\nPlease see https://hackage.haskell.org/package/layers-0.1/docs/Documentation-Layers-Overview.html for an exhaustive discussion of the different approaches to lift functions.\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.function\nimport Mathlib.Lean3Lib.init.coe\nimport Mathlib.Lean3Lib.init.control.monad\n\nuniverses u v w l u_1 u_2 u_3 u_4 \n\nnamespace Mathlib\n\n/-- A function for lifting a computation from an inner monad to an outer monad.\n Like [MonadTrans](https://hackage.haskell.org/package/transformers-0.5.5.0/docs/Control-Monad-Trans-Class.html),\n but `n` does not have to be a monad transformer.\n Alternatively, an implementation of [MonadLayer](https://hackage.haskell.org/package/layers-0.1/docs/Control-Monad-Layer.html#t:MonadLayer) without `layerInvmap` (so far). -/\nclass has_monad_lift (m : Type u → Type v) (n : Type u → Type w) where\n monad_lift : {α : Type u} → m α → n α\n\n/-- The reflexive-transitive closure of `has_monad_lift`.\n `monad_lift` is used to transitively lift monadic computations such as `state_t.get` or `state_t.put s`.\n Corresponds to [MonadLift](https://hackage.haskell.org/package/layers-0.1/docs/Control-Monad-Layer.html#t:MonadLift). -/\nclass has_monad_lift_t (m : Type u → Type v) (n : Type u → Type w) where\n monad_lift : {α : Type u} → m α → n α\n\n/-- A coercion that may reduce the need for explicit lifting.\n Because of [limitations of the current coercion resolution](https://github.com/leanprover/lean/issues/1402), this definition is not marked as a global instance and should be marked locally instead. -/\ndef has_monad_lift_to_has_coe {m : Type u_1 → Type u_2} {n : Type u_1 → Type u_3}\n [has_monad_lift_t m n] {α : Type u_1} : has_coe (m α) (n α) :=\n has_coe.mk monad_lift\n\nprotected instance has_monad_lift_t_trans (m : Type u_1 → Type u_2) (n : Type u_1 → Type u_3)\n (o : Type u_1 → Type u_4) [has_monad_lift_t m n] [has_monad_lift n o] : has_monad_lift_t m o :=\n has_monad_lift_t.mk fun (α : Type u_1) (ma : m α) => has_monad_lift.monad_lift (monad_lift ma)\n\nprotected instance has_monad_lift_t_refl (m : Type u_1 → Type u_2) : has_monad_lift_t m m :=\n has_monad_lift_t.mk fun (α : Type u_1) => id\n\n@[simp] theorem monad_lift_refl {m : Type u → Type v} {α : Type u} : monad_lift = id := rfl\n\n/-- A functor in the category of monads. Can be used to lift monad-transforming functions.\n Based on pipes' [MFunctor](https://hackage.haskell.org/package/pipes-2.4.0/docs/Control-MFunctor.html),\n but not restricted to monad transformers.\n Alternatively, an implementation of [MonadTransFunctor](http://duairc.netsoc.ie/layers-docs/Control-Monad-Layer.html#t:MonadTransFunctor). -/\nclass monad_functor (m : Type u → Type v) (m' : Type u → Type v) (n : Type u → Type w)\n (n' : Type u → Type w)\n where\n monad_map : {α : Type u} → ({α : Type u} → m α → m' α) → n α → n' α\n\n/-- The reflexive-transitive closure of `monad_functor`.\n `monad_map` is used to transitively lift monad morphisms such as `state_t.zoom`.\n A generalization of [MonadLiftFunctor](http://duairc.netsoc.ie/layers-docs/Control-Monad-Layer.html#t:MonadLiftFunctor), which can only lift endomorphisms (i.e. m = m', n = n'). -/\nclass monad_functor_t (m : Type u → Type v) (m' : Type u → Type v) (n : Type u → Type w)\n (n' : Type u → Type w)\n where\n monad_map : {α : Type u} → ({α : Type u} → m α → m' α) → n α → n' α\n\nprotected instance monad_functor_t_trans (m : Type u_1 → Type u_2) (m' : Type u_1 → Type u_2)\n (n : Type u_1 → Type u_3) (n' : Type u_1 → Type u_3) (o : Type u_1 → Type u_4)\n (o' : Type u_1 → Type u_4) [monad_functor_t m m' n n'] [monad_functor n n' o o'] :\n monad_functor_t m m' o o' :=\n monad_functor_t.mk\n fun (α : Type u_1) (f : {α : Type u_1} → m α → m' α) =>\n monad_functor.monad_map fun (α : Type u_1) => monad_map f\n\nprotected instance monad_functor_t_refl (m : Type u_1 → Type u_2) (m' : Type u_1 → Type u_2) :\n monad_functor_t m m' m m' :=\n monad_functor_t.mk fun (α : Type u_1) (f : {α : Type u_1} → m α → m' α) => f\n\n@[simp] theorem monad_map_refl {m : Type u → Type v} {m' : Type u → Type v}\n (f : {α : Type u} → m α → m' α) {α : Type u} : monad_map f = f :=\n rfl\n\n/-- Run a monad stack to completion.\n `run` should be the composition of the transformers' individual `run` functions.\n This class mostly saves some typing when using highly nested monad stacks:\n ```\n @[reducible] def my_monad := reader_t my_cfg $ state_t my_state $ except_t my_err id\n -- def my_monad.run {α : Type} (x : my_monad α) (cfg : my_cfg) (st : my_state) := ((x.run cfg).run st).run\n def my_monad.run {α : Type} (x : my_monad α) := monad_run.run x\n ```\n -/\nclass monad_run (out : outParam (Type u → Type v)) (m : Type u → Type v) where\n run : {α : Type u} → m α → out α\n\nend Mathlib", "meta": {"author": "AurelienSaue", "repo": "Mathlib4_auto", "sha": "590df64109b08190abe22358fabc3eae000943f2", "save_path": "github-repos/lean/AurelienSaue-Mathlib4_auto", "path": "github-repos/lean/AurelienSaue-Mathlib4_auto/Mathlib4_auto-590df64109b08190abe22358fabc3eae000943f2/Mathlib/Lean3Lib/init/control/lift_auto.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2200070997458932, "lm_q2_score": 0.03846619546296478, "lm_q1q2_score": 0.008462836102065517}} {"text": "/-\nCopyright (c) 2021 Mario Carneiro. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Mario Carneiro\n-/\nimport Lean\nimport Std\nimport Mathlib.Tactic.Cases\n\nnamespace Mathlib.Tactic\nopen Lean Parser.Tactic Elab Command Elab.Tactic Meta\n\nsyntax (name := «variables») \"variables\" (bracketedBinder)* : command\n\n@[command_elab «variables»] def elabVariables : CommandElab\n | `(variables%$pos $binders*) => do\n logWarningAt pos \"'variables' has been replaced by 'variable' in lean 4\"\n elabVariable (← `(variable%$pos $binders*))\n | _ => throwUnsupportedSyntax\n\n/-- `lemma` means the same as `theorem`. It is used to denote \"less important\" theorems -/\nsyntax (name := lemma)\n declModifiers group(\"lemma\" declId declSig declVal Parser.Command.terminationSuffix) : command\n\n/-- Implementation of the `lemma` command, by macro expansion to `theorem`. -/\n@[macro «lemma»] def expandLemma : Macro := fun stx =>\n -- FIXME: this should be a macro match, but terminationSuffix is not easy to bind correctly.\n -- This implementation ensures that any future changes to `theorem` are reflected in `lemma`\n let stx := stx.modifyArg 1 fun stx =>\n let stx := stx.modifyArg 0 (mkAtomFrom · \"theorem\" (canonical := true))\n stx.setKind ``Parser.Command.theorem\n pure <| stx.setKind ``Parser.Command.declaration\n\n/-- Given two arrays of `FVarId`s, one from an old local context and the other from a new local\ncontext, pushes `FVarAliasInfo`s into the info tree for corresponding pairs of `FVarId`s.\nRecall that variables linked this way should be considered to be semantically identical.\n\nThe effect of this is, for example, the unused variable linter will see that variables\nfrom the first array are used if corresponding variables in the second array are used. -/\ndef pushFVarAliasInfo [Monad m] [MonadInfoTree m]\n (oldFVars newFVars : Array FVarId) (newLCtx : LocalContext) : m Unit := do\n for old in oldFVars, new in newFVars do\n if old != new then\n let decl := newLCtx.get! new\n pushInfoLeaf (.ofFVarAliasInfo { id := new, baseId := old, userName := decl.userName })\n\n/-- Function to help do the revert/intro pattern, running some code inside a context\nwhere certain variables have been reverted before re-introing them.\nIt will push `FVarId` alias information into info trees for you according to a simple protocol.\n\n- `fvarIds` is an array of `fvarIds` to revert. These are passed to\n `Lean.MVarId.revert` with `preserveOrder := true`, hence the function\n raises an error if they cannot be reverted in the provided order.\n- `k` is given the goal with all the variables reverted and\n the array of reverted `FVarId`s, with the requested `FVarId`s at the beginning.\n It must return a tuple of a value, an array describing which `FVarIds` to link,\n and a mutated `MVarId`.\n\nThe `a : Array (Option FVarId)` array returned by `k` is interpreted in the following way.\nThe function will intro `a.size` variables, and then for each non-`none` entry we\ncreate an FVar alias between it and the corresponding `intro`ed variable.\nFor example, having `k` return `fvars.map .some` causes all reverted variables to be\n`intro`ed and linked.\n\nReturns the value returned by `k` along with the resulting goal.\n -/\ndef _root_.Lean.MVarId.withReverted (mvarId : MVarId) (fvarIds : Array FVarId)\n (k : MVarId → Array FVarId → MetaM (α × Array (Option FVarId) × MVarId))\n (clearAuxDeclsInsteadOfRevert := false) : MetaM (α × MVarId) := do\n let (xs, mvarId) ← mvarId.revert fvarIds true clearAuxDeclsInsteadOfRevert\n let (r, xs', mvarId) ← k mvarId xs\n let (ys, mvarId) ← mvarId.introNP xs'.size\n mvarId.withContext do\n for x? in xs', y in ys do\n if let some x := x? then\n pushInfoLeaf (.ofFVarAliasInfo { id := y, baseId := x, userName := ← y.getUserName })\n return (r, mvarId)\n\n/--\nReplace the type of the free variable `fvarId` with `typeNew`.\n\nIf `checkDefEq = true` then throws an error if `typeNew` is not definitionally\nequal to the type of `fvarId`. Otherwise this function assumes `typeNew` and the type\nof `fvarId` are definitionally equal.\n\nThis function is the same as `Lean.MVarId.changeLocalDecl` but makes sure to push substitution\ninformation into the infotree.\n-/\ndef _root_.Lean.MVarId.changeLocalDecl' (mvarId : MVarId) (fvarId : FVarId) (typeNew : Expr)\n (checkDefEq := true) : MetaM MVarId := do\n mvarId.checkNotAssigned `changeLocalDecl\n let (_, mvarId) ← mvarId.withReverted #[fvarId] fun mvarId fvars => mvarId.withContext do\n let check (typeOld : Expr) : MetaM Unit := do\n if checkDefEq then\n unless ← isDefEq typeNew typeOld do\n throwTacticEx `changeLocalDecl mvarId\n m!\"given type{indentExpr typeNew}\\nis not definitionally equal to{indentExpr typeOld}\"\n let finalize (targetNew : Expr) := do\n return ((), fvars.map .some, ← mvarId.replaceTargetDefEq targetNew)\n match ← mvarId.getType with\n | .forallE n d b bi => do check d; finalize (.forallE n typeNew b bi)\n | .letE n t v b ndep => do check t; finalize (.letE n typeNew v b ndep)\n | _ => throwTacticEx `changeLocalDecl mvarId \"unexpected auxiliary target\"\n return mvarId\n\n/-- `change` can be used to replace the main goal or its local\nvariables with definitionally equal ones.\n\nFor example, if `n : ℕ` and the current goal is `⊢ n + 2 = 2`, then\n```lean\nchange _ + 1 = _\n```\nchanges the goal to `⊢ n + 1 + 1 = 2`. The tactic also applies to the local context.\nIf `h : n + 2 = 2` and `h' : n + 3 = 4` are in the local context, then\n```lean\nchange _ + 1 = _ at h h'\n```\nchanges their types to be `h : n + 1 + 1 = 2` and `h' : n + 2 + 1 = 4`.\n\nChange is like `refine` in that every placeholder needs to be solved for by unification,\nbut you can use named placeholders and `?_` where you want `change` to create new goals.\n\nThe the tactic `show e` is interchangeable with `change e`, where the pattern `e` is applied to\nthe main goal. -/\nelab_rules : tactic\n | `(tactic| change $newType:term $[$loc:location]?) => do\n withLocation (expandOptLocation (Lean.mkOptionalNode loc))\n (atLocal := fun h ↦ do\n let hTy ← h.getType\n -- This is a hack to get the new type to elaborate in the same sort of way that\n -- it would for a `show` expression for the goal.\n let mvar ← mkFreshExprMVar none\n let (_, mvars) ← elabTermWithHoles\n (← `(term | show $newType from $(← Term.exprToSyntax mvar))) hTy `change\n liftMetaTactic fun mvarId ↦ do\n return (← mvarId.changeLocalDecl' h (← inferType mvar)) :: mvars)\n (atTarget := evalTactic <| ← `(tactic| show $newType))\n (failed := fun _ ↦ throwError \"change tactic failed\")\n\n/--\n`by_cases p` makes a case distinction on `p`,\nresulting in two subgoals `h : p ⊢` and `h : ¬ p ⊢`.\n-/\nmacro \"by_cases \" e:term : tactic =>\n `(tactic| by_cases $(mkIdent `h) : $e)\n\nsyntax \"transitivity\" (colGt term)? : tactic\nset_option hygiene false in\nmacro_rules\n | `(tactic| transitivity) => `(tactic| apply Nat.le_trans)\n | `(tactic| transitivity $e) => `(tactic| apply Nat.le_trans (m := $e))\nset_option hygiene false in\nmacro_rules\n | `(tactic| transitivity) => `(tactic| apply Nat.lt_trans)\n | `(tactic| transitivity $e) => `(tactic| apply Nat.lt_trans (m := $e))\n\n/--\nThe tactic `introv` allows the user to automatically introduce the variables of a theorem and\nexplicitly name the non-dependent hypotheses.\nAny dependent hypotheses are assigned their default names.\n\nExamples:\n```\nexample : ∀ a b : Nat, a = b → b = a := by\n introv h,\n exact h.symm\n```\nThe state after `introv h` is\n```\na b : ℕ,\nh : a = b\n⊢ b = a\n```\n\n```\nexample : ∀ a b : Nat, a = b → ∀ c, b = c → a = c := by\n introv h₁ h₂,\n exact h₁.trans h₂\n```\nThe state after `introv h₁ h₂` is\n```\na b : ℕ,\nh₁ : a = b,\nc : ℕ,\nh₂ : b = c\n⊢ a = c\n```\n-/\nsyntax (name := introv) \"introv \" (colGt binderIdent)* : tactic\n@[tactic introv] partial def evalIntrov : Tactic := fun stx ↦ do\n match stx with\n | `(tactic| introv) => introsDep\n | `(tactic| introv $h:ident $hs:binderIdent*) =>\n evalTactic (← `(tactic| introv; intro $h:ident; introv $hs:binderIdent*))\n | `(tactic| introv _%$tk $hs:binderIdent*) =>\n evalTactic (← `(tactic| introv; intro _%$tk; introv $hs:binderIdent*))\n | _ => throwUnsupportedSyntax\nwhere\n introsDep : TacticM Unit := do\n let t ← getMainTarget\n match t with\n | Expr.forallE _ _ e _ =>\n if e.hasLooseBVars then\n intro1PStep\n introsDep\n | _ => pure ()\n intro1PStep : TacticM Unit :=\n liftMetaTactic fun goal ↦ do\n let (_, goal) ← goal.intro1P\n pure [goal]\n\n/-- Try calling `assumption` on all goals; succeeds if it closes at least one goal. -/\nmacro \"assumption'\" : tactic => `(tactic| any_goals assumption)\n\nelab \"match_target\" t:term : tactic => do\n withMainContext do\n let (val) ← elabTerm t (← inferType (← getMainTarget))\n if not (← isDefEq val (← getMainTarget)) then\n throwError \"failed\"\n\n/-- This tactic clears all auxiliary declarations from the context. -/\nelab (name := clearAuxDecl) \"clear_aux_decl\" : tactic => withMainContext do\n let mut g ← getMainGoal\n for ldec in ← getLCtx do\n if ldec.isAuxDecl then\n g ← g.tryClear ldec.fvarId\n replaceMainGoal [g]\n\n/-- Clears the value of the local definition `fvarId`. Ensures that the resulting goal state\nis still type correct. Throws an error if it is a local hypothesis without a value. -/\ndef _root_.Lean.MVarId.clearValue (mvarId : MVarId) (fvarId : FVarId) : MetaM MVarId := do\n mvarId.checkNotAssigned `clear_value\n let tag ← mvarId.getTag\n let (_, mvarId) ← mvarId.withReverted #[fvarId] fun mvarId' fvars => mvarId'.withContext do\n let tgt ← mvarId'.getType\n unless tgt.isLet do\n mvarId.withContext <|\n throwTacticEx `clear_value mvarId m!\"{Expr.fvar fvarId} is not a local definition\"\n let tgt' := Expr.forallE tgt.letName! tgt.letType! tgt.letBody! .default\n unless ← isTypeCorrect tgt' do\n mvarId.withContext <|\n throwTacticEx `clear_value mvarId\n m!\"cannot clear {Expr.fvar fvarId}, the resulting context is not type correct\"\n let mvarId'' ← mkFreshExprSyntheticOpaqueMVar tgt' tag\n mvarId'.assign <| .app mvarId'' tgt.letValue!\n return ((), fvars.map .some, mvarId''.mvarId!)\n return mvarId\n\n/-- `clear_value n₁ n₂ ...` clears the bodies of the local definitions `n₁, n₂ ...`, changing them\ninto regular hypotheses. A hypothesis `n : α := t` is changed to `n : α`.\n\nThe order of `n₁ n₂ ...` does not matter, and values will be cleared in reverse order of\nwhere they appear in the context. -/\nelab (name := clearValue) \"clear_value\" hs:(colGt term:max)+ : tactic => do\n let fvarIds ← getFVarIds hs\n let fvarIds ← withMainContext <| sortFVarIds fvarIds\n for fvarId in fvarIds.reverse do\n withMainContext do\n let mvarId ← (← getMainGoal).clearValue fvarId\n replaceMainGoal [mvarId]\n", "meta": {"author": "leanprover-community", "repo": "mathlib4", "sha": "b9a0a30342ca06e9817e22dbe46e75fc7f435500", "save_path": "github-repos/lean/leanprover-community-mathlib4", "path": "github-repos/lean/leanprover-community-mathlib4/mathlib4-b9a0a30342ca06e9817e22dbe46e75fc7f435500/Mathlib/Tactic/Basic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.18713268216242657, "lm_q2_score": 0.04468087233980777, "lm_q1q2_score": 0.008361251482305205}} {"text": "import Do.Return\n\n/-! # Iteration -/\n\nopen Lean\n\n/- Disable the automatic monadic lifting feature described in the paper.\n We want to make it clear that we do not depend on it. -/\nset_option autoLift false\n\nsyntax \"for\" ident \"in\" term \"do'\" stmt:1 : stmt\nsyntax \"break \" : stmt\nsyntax \"continue \" : stmt\n\nsyntax \"break\" : expander\nsyntax \"continue\" : expander\nsyntax \"lift\" : expander\n\nmacro_rules\n | `(stmt| expand! $_ in break) => `(stmt| break) -- subsumes (S7, R7, B2, L1)\n | `(stmt| expand! $_ in continue) => `(stmt| continue) -- subsumes (S8, R8, L2)\n | `(stmt| expand! $exp in for $x in $e do' $s) => `(stmt| for $x in $e do' expand! $exp in $s) -- subsumes (L8, R9)\n\nmacro_rules\n | `(d! for $x in $e do' $s) => do -- (D5), optimized like (1')\n let mut s := s\n let sb ← expandStmt (← `(stmt| expand! break in $s))\n let hasBreak := sb.raw.count (· matches `(stmt| break)) < s.raw.count (· matches `(stmt| break))\n if hasBreak then\n s := sb\n let sc ← expandStmt (← `(stmt| expand! continue in $s))\n let hasContinue := sc.raw.count (· matches `(stmt| continue)) < s.raw.count (· matches `(stmt| continue))\n if hasContinue then\n s := sc\n let mut body ← `(d! $s)\n if hasContinue then\n body ← `(ExceptCpsT.runCatch $body)\n let mut loop ← `(forM $e (fun $x => $body))\n if hasBreak then\n loop ← `(ExceptCpsT.runCatch $loop)\n pure loop\n | `(d! break%$b) =>\n throw <| Macro.Exception.error b \"unexpected 'break' outside loop\"\n | `(d! continue%$c) =>\n throw <| Macro.Exception.error c \"unexpected 'continue' outside loop\"\n\nmacro_rules\n | `(stmt| expand! break in break) => `(stmt| throw ()) -- (B1)\n | `(stmt| expand! break in $e:term) => `(stmt| ExceptCpsT.lift $e) -- (B3)\n | `(stmt| expand! break in for $x in $e do' $s) => `(stmt| for $x in $e do' expand! lift in $s) -- (B8)\n | `(stmt| expand! continue in continue) => `(stmt| throw ())\n | `(stmt| expand! continue in $e:term) => `(stmt| ExceptCpsT.lift $e)\n | `(stmt| expand! continue in for $x in $e do' $s) => `(stmt| for $x in $e do' expand! lift in $s)\n\nmacro_rules\n | `(stmt| expand! lift in $e:term) => `(stmt| ExceptCpsT.lift $e) -- (L3)\n\nmacro_rules\n | `(stmt| expand! mut $y in for $x in $e do' $s) => `(stmt| for $x in $e do' { let $y ← get; expand! mut $y in $s }) -- (S9)\n\nvariable [Monad m]\nvariable (ma ma' : m α)\nvariable (b : Bool)\nvariable (xs : List α) (act : α → m Unit)\n\nattribute [local simp] map_eq_pure_bind\n\nexample [LawfulMonad m] :\n (do' for x in xs do' {\n act x\n })\n =\n xs.forM act\n:= by induction xs <;> simp_all!\n\ndef ex2 (f : β → α → m β) (init : β) (xs : List α) : m β := do'\n let mut y := init;\n for x in xs do' {\n y ← f y x\n };\n return y\n\nexample [LawfulMonad m] (f : β → α → m β) :\n ex2 f init xs = xs.foldlM f init := by\n unfold ex2; induction xs generalizing init <;> simp_all!\n\n@[simp] theorem List.find?_cons {xs : List α} : (x::xs).find? p = if p x then some x else xs.find? p := by\n cases h : p x <;> simp_all!\n\nexample (p : α → Bool) : Id.run\n (do' for x in xs do' {\n if p x then {\n return some x\n }\n };\n pure none)\n =\n xs.find? p\n:= by induction xs with\n | nil => simp [Id.run, List.find?]\n | cons x => cases h : p x <;> simp_all [Id.run]\n\nvariable (p : α → m Bool)\n\ntheorem byCases_Bool_bind (x : m Bool) (f g : Bool → m β) (isTrue : f true = g true) (isFalse : f false = g false) : (x >>= f) = (x >>= g) := by\n have : f = g := by\n funext b\n cases b with\n | true => exact isTrue\n | false => exact isFalse\n rw [this]\n\ntheorem eq_findM [LawfulMonad m] :\n (do' for x in xs do' {\n let b ← p x;\n if b then {\n return some x\n }\n };\n pure none)\n =\n xs.findM? p\n:= by induction xs with\n | nil => simp!\n | cons x xs ih =>\n rw [List.findM?, ← ih]; simp\n apply byCases_Bool_bind <;> simp\n\ndef ex3 [Monad m] (p : α → m Bool) (xss : List (List α)) : m (Option α) := do'\n for xs in xss do' {\n for x in xs do' {\n let b ← p x;\n if b then {\n return some x\n }\n }\n };\n pure none\n\ntheorem eq_findSomeM_findM [LawfulMonad m] (xss : List (List α)) :\n ex3 p xss = xss.findSomeM? (fun xs => xs.findM? p) := by\n unfold ex3\n induction xss with\n | nil => simp!\n | cons xs xss ih =>\n simp [List.findSomeM?]\n rw [← ih, ← eq_findM]\n induction xs with\n | nil => simp\n | cons x xs ih => simp; apply byCases_Bool_bind <;> simp [ih]\n\ndef List.untilM (p : α → m Bool) : List α → m Unit\n | [] => pure ()\n | a::as => p a >>= fun | true => pure () | false => as.untilM p\n\ntheorem eq_untilM [LawfulMonad m] :\n (do' for x in xs do' {\n let b ← p x;\n if b then {\n break\n }\n })\n =\n xs.untilM p\n:= by induction xs with\n | nil => simp!\n | cons x xs ih =>\n simp [List.untilM]; rw [← ih]; clear ih\n apply byCases_Bool_bind <;> simp\n\n/-\nThe notation `[0:10]` is a range from 0 to 10 (exclusively).\n-/\n\n#eval do'\n for x in [0:10] do' {\n if x > 5 then {\n break\n };\n for y in [0:x] do' {\n IO.println y;\n break\n };\n IO.println x\n }\n\n#eval do'\n for x in [0:10] do' {\n if x > 5 then {\n break\n };\n IO.println x\n }\n\n#eval do'\n for x in [0:10] do' {\n if x % 2 == 0 then {\n continue\n };\n if x > 5 then {\n break\n };\n IO.println x\n }\n\n#eval do'\n for x in [0:10] do' {\n if x % 2 == 0 then {\n continue\n };\n if x > 5 then {\n return ()\n };\n IO.println x\n }\n\n\n-- set_option trace.compiler.ir.init true\ndef ex1 (xs : List Nat) (z : Nat) : Id Nat := do'\n let mut s1 := 0;\n let mut s2 := 0;\n for x in xs do' {\n if x % 2 == 0 then {\n continue\n };\n if x == z then {\n return s1\n };\n s1 := s1 + x;\n s2 := s2 + s1\n };\n return (s1 + s2)\n\n/-\nAdding `repeat` and `while` statements\n-/\n\n-- The \"partial\" keyword allows users to define non-terminating functions in Lean.\n-- However, we currently cannot reason about them.\n@[specialize] partial def loopForever [Monad m] (f : Unit → m Unit) : m Unit :=\n f () *> loopForever f\n\n-- `Loop'` is a \"helper\" type. It is similar to `Unit`.\n-- Its `ForM` instance produces an \"infinite\" sequence of units.\ninductive Loop' where\n | mk : Loop'\n\ninstance : ForM m Loop' Unit where\n forM _ f := loopForever f\n\nmacro:0 \"repeat\" s:stmt:1 : stmt => `(stmt| for u in Loop'.mk do' $s)\n\n#eval do'\n let mut i := 0;\n repeat {\n if i > 10 then {\n break\n };\n IO.println i;\n i := i + 1\n };\n return i\n\nmacro:0 \"while\" c:term \"do'\" s:stmt:1 : stmt => `(stmt| repeat { unless $c do' break; { $s } })\n\n#eval do'\n let mut i := 0;\n while (i < 10) do' {\n IO.println i;\n i := i + 1\n };\n return i\n", "meta": {"author": "Kha", "repo": "do-supplement", "sha": "72acc9d3a39d2593f15b77bc0a221c307f6657a0", "save_path": "github-repos/lean/Kha-do-supplement", "path": "github-repos/lean/Kha-do-supplement/do-supplement-72acc9d3a39d2593f15b77bc0a221c307f6657a0/Do/For.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2227001388253088, "lm_q2_score": 0.03732688881662312, "lm_q1q2_score": 0.008312703321378836}} {"text": "import category_theory.preadditive\nimport category_theory.abelian.projective\nimport tactic.interval_cases\n\n\nnoncomputable theory\n\nopen category_theory\nopen category_theory.limits\n\nuniverse variables v u\n\nnamespace category_theory\n\nvariables {C : Type u} [category.{v} C]\n\nnamespace fin3_functor_mk\n\nvariables (F : fin 3 → C) (a : F 0 ⟶ F 1) (b : F 1 ⟶ F 2)\n\ndef map' : Π (i j : fin 3) (hij : i ≤ j), F i ⟶ F j\n| ⟨0,hi⟩ ⟨0,hj⟩ _ := 𝟙 _\n| ⟨1,hi⟩ ⟨1,hj⟩ _ := 𝟙 _\n| ⟨2,hi⟩ ⟨2,hj⟩ _ := 𝟙 _\n| ⟨0,hi⟩ ⟨1,hj⟩ _ := a\n| ⟨1,hi⟩ ⟨2,hj⟩ _ := b\n| ⟨0,hi⟩ ⟨2,hj⟩ _ := a ≫ b\n| ⟨i+3,hi⟩ _ _ := by { exfalso, revert hi, dec_trivial }\n| _ ⟨j+3,hj⟩ _ := by { exfalso, revert hj, dec_trivial }\n| ⟨i+1,hi⟩ ⟨0,hj⟩ H := by { exfalso, revert H, dec_trivial }\n| ⟨i+2,hi⟩ ⟨1,hj⟩ H := by { exfalso, revert H, dec_trivial }\n.\n\nlemma map'_id : ∀ (i : fin 3), map' F a b i i le_rfl = 𝟙 _\n| ⟨0,hi⟩ := rfl\n| ⟨1,hi⟩ := rfl\n| ⟨2,hi⟩ := rfl\n| ⟨i+3,hi⟩ := by { exfalso, revert hi, dec_trivial }\n\nlemma map'_comp : Π (i j k : fin 3) (hij : i ≤ j) (hjk : j ≤ k),\n map' F a b i j hij ≫ map' F a b j k hjk = map' F a b i k (hij.trans hjk)\n| ⟨0, _⟩ ⟨0, _⟩ k _ _ := category.id_comp _\n| ⟨1, _⟩ ⟨1, _⟩ k _ _ := category.id_comp _\n| i ⟨1, _⟩ ⟨1, _⟩ _ _ := category.comp_id _\n| i ⟨2, _⟩ ⟨2, _⟩ _ _ := category.comp_id _\n| ⟨0, _⟩ ⟨1, _⟩ ⟨2, _⟩ _ _ := rfl\n| ⟨i+3,hi⟩ _ _ _ _ := by { exfalso, revert hi, dec_trivial }\n| _ ⟨j+3,hj⟩ _ _ _ := by { exfalso, revert hj, dec_trivial }\n| _ _ ⟨k+3,hk⟩ _ _ := by { exfalso, revert hk, dec_trivial }\n| ⟨i+1,hi⟩ ⟨0,hj⟩ _ H _ := by { exfalso, revert H, dec_trivial }\n| ⟨i+2,hi⟩ ⟨1,hj⟩ _ H _ := by { exfalso, revert H, dec_trivial }\n| _ ⟨i+1,hi⟩ ⟨0,hj⟩ _ H := by { exfalso, revert H, dec_trivial }\n| _ ⟨i+2,hi⟩ ⟨1,hj⟩ _ H := by { exfalso, revert H, dec_trivial }\n\n\nend fin3_functor_mk\n\ndef fin3_functor_mk (F : fin 3 → C) (a : F 0 ⟶ F 1) (b : F 1 ⟶ F 2) : fin 3 ⥤ C :=\n{ obj := F,\n map := λ i j hij, fin3_functor_mk.map' F a b i j hij.le,\n map_id' := λ i, fin3_functor_mk.map'_id F a b i,\n map_comp' := λ i j k hij hjk, by rw fin3_functor_mk.map'_comp F a b i j k hij.le hjk.le }\n\nnamespace fin4_functor_mk\n\nvariables (F : fin 4 → C) (a : F 0 ⟶ F 1) (b : F 1 ⟶ F 2) (c : F 2 ⟶ F 3)\n\ndef map' : Π (i j : fin 4) (hij : i ≤ j), F i ⟶ F j\n| ⟨0,hi⟩ ⟨0,hj⟩ _ := 𝟙 _\n| ⟨1,hi⟩ ⟨1,hj⟩ _ := 𝟙 _\n| ⟨2,hi⟩ ⟨2,hj⟩ _ := 𝟙 _\n| ⟨3,hi⟩ ⟨3,hj⟩ _ := 𝟙 _\n| ⟨0,hi⟩ ⟨1,hj⟩ _ := a\n| ⟨1,hi⟩ ⟨2,hj⟩ _ := b\n| ⟨2,hi⟩ ⟨3,hj⟩ _ := c\n| ⟨0,hi⟩ ⟨2,hj⟩ _ := a ≫ b\n| ⟨1,hi⟩ ⟨3,hj⟩ _ := b ≫ c\n| ⟨0,hi⟩ ⟨3,hj⟩ _ := a ≫ b ≫ c\n| ⟨i+4,hi⟩ _ _ := by { exfalso, revert hi, dec_trivial }\n| _ ⟨j+4,hj⟩ _ := by { exfalso, revert hj, dec_trivial }\n| ⟨i+1,hi⟩ ⟨0,hj⟩ H := by { exfalso, revert H, dec_trivial }\n| ⟨i+2,hi⟩ ⟨1,hj⟩ H := by { exfalso, revert H, dec_trivial }\n| ⟨3,hi⟩ ⟨2,hj⟩ H := by { exfalso, revert H, dec_trivial }\n.\n\nlemma map'_id : ∀ (i : fin 4), map' F a b c i i le_rfl = 𝟙 _\n| ⟨0,hi⟩ := rfl\n| ⟨1,hi⟩ := rfl\n| ⟨2,hi⟩ := rfl\n| ⟨3,hi⟩ := rfl\n| ⟨i+4,hi⟩ := by { exfalso, revert hi, dec_trivial }\n\nlemma map'_comp : Π (i j k : fin 4) (hij : i ≤ j) (hjk : j ≤ k),\n map' F a b c i j hij ≫ map' F a b c j k hjk = map' F a b c i k (hij.trans hjk)\n| ⟨0, _⟩ ⟨0, _⟩ k _ _ := category.id_comp _\n| ⟨1, _⟩ ⟨1, _⟩ k _ _ := category.id_comp _\n| ⟨2, _⟩ ⟨2, _⟩ k _ _ := category.id_comp _\n| i ⟨1, _⟩ ⟨1, _⟩ _ _ := category.comp_id _\n| i ⟨2, _⟩ ⟨2, _⟩ _ _ := category.comp_id _\n| i ⟨3, _⟩ ⟨3, _⟩ _ _ := category.comp_id _\n| ⟨0, _⟩ ⟨1, _⟩ ⟨2, _⟩ _ _ := rfl\n| ⟨0, _⟩ ⟨1, _⟩ ⟨3, _⟩ _ _ := rfl\n| ⟨0, _⟩ ⟨2, _⟩ ⟨3, _⟩ _ _ := category.assoc a b c\n| ⟨1, _⟩ ⟨2, _⟩ ⟨3, _⟩ _ _ := rfl\n| ⟨i+4,hi⟩ _ _ _ _ := by { exfalso, revert hi, dec_trivial }\n| _ ⟨j+4,hj⟩ _ _ _ := by { exfalso, revert hj, dec_trivial }\n| _ _ ⟨k+4,hk⟩ _ _ := by { exfalso, revert hk, dec_trivial }\n| ⟨i+1,hi⟩ ⟨0,hj⟩ _ H _ := by { exfalso, revert H, dec_trivial }\n| ⟨i+2,hi⟩ ⟨1,hj⟩ _ H _ := by { exfalso, revert H, dec_trivial }\n| ⟨3,hi⟩ ⟨2,hj⟩ _ H _ := by { exfalso, revert H, dec_trivial }\n| _ ⟨i+1,hi⟩ ⟨0,hj⟩ _ H := by { exfalso, revert H, dec_trivial }\n| _ ⟨i+2,hi⟩ ⟨1,hj⟩ _ H := by { exfalso, revert H, dec_trivial }\n| _ ⟨3,hi⟩ ⟨2,hj⟩ _ H := by { exfalso, revert H, dec_trivial }\n\n\nend fin4_functor_mk\n\ndef fin4_functor_mk (F : fin 4 → C) (a : F 0 ⟶ F 1) (b : F 1 ⟶ F 2) (c : F 2 ⟶ F 3) : fin 4 ⥤ C :=\n{ obj := F,\n map := λ i j hij, fin4_functor_mk.map' F a b c i j hij.le,\n map_id' := λ i, fin4_functor_mk.map'_id F a b c i,\n map_comp' := λ i j k hij hjk, by rw fin4_functor_mk.map'_comp F a b c i j k hij.le hjk.le }\n\nend category_theory\n", "meta": {"author": "leanprover-community", "repo": "lean-liquid", "sha": "92f188bd17f34dbfefc92a83069577f708851aec", "save_path": "github-repos/lean/leanprover-community-lean-liquid", "path": "github-repos/lean/leanprover-community-lean-liquid/lean-liquid-92f188bd17f34dbfefc92a83069577f708851aec/src/for_mathlib/fin_functor.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.34510528442897664, "lm_q2_score": 0.02405355184501284, "lm_q1q2_score": 0.008301007851000292}} {"text": "import system.io\nimport .solvers.z3\nimport .syntax\nimport .builder\nimport .tactic\nimport .attributes\nimport .lol\nimport init.data.option.basic\n\ndeclare_trace smt2\n\nopen tactic\nopen smt2.builder\nopen native\n\nmeta structure smt2_state : Type :=\n(ctxt : lol.context)\n(type_map : rb_map expr lol.type)\n\nmeta def smt2_state.initial : smt2_state :=\n⟨ lol.context.empty, rb_map.mk _ _ ⟩\n\n@[reducible] meta def smt2_m (α : Type) :=\nstate_t smt2_state tactic α\n\nmeta instance tactic_to_smt2_m (α : Type) : has_coe (tactic α) (smt2_m α) :=\n⟨ fun tc, state_t.mk (fun s, do res ← tc, return (res, s)) ⟩\n\nnamespace smt2\n\nmeta def trace_smt2 (msg : string) : smt2_m unit :=\n tactic.when_tracing `smt2 (tactic.trace msg)\n\nmeta def fail {α : Type} (msg : string) : smt2_m α :=\ntactic.fail $ \"smt2_tactic: \" ++ msg\n\nmeta def mangle_name (n : name) : string :=\n\"lean_\" ++ n^.to_string_with_sep \"-\"\n\nmeta def insert_type (n : string) (ty : expr) (lty : lol.type) : smt2_m unit :=\ndo st ← get,\n put ⟨\n st.ctxt.declare_type n lty,\n st.type_map.insert ty lty\n ⟩\n\nmeta def fn_type : expr → (list expr × expr)\n| (expr.pi _ _ ty rest) :=\n let (args, rt) := fn_type rest\n in (ty :: args, rt)\n| rt := ([], rt)\n\n-- Currently we only support first order fn types\nmeta def compile_arrow_type (ty : expr) (cb : expr → smt2_m lol.type) : smt2_m lol.type :=\nlet (args, rt) := fn_type ty\nin lol.type.fn <$> monad.mapm cb args <*> cb rt\n\nmeta def compile_type : expr → smt2_m lol.type :=\nfun ty,\ndo st ← get,\n match st.type_map.find ty with\n | some lty := return lty\n | none := do\n lty ← match ty with\n | `(int) := pure $ lol.type.int\n | `(nat) := pure $ lol.type.refinement lol.type.int (fun x, lol.term.lte (lol.term.int 0) (lol.term.var x))\n | `(Prop) := pure $ lol.type.bool\n | _ := if ty.is_arrow\n then compile_arrow_type ty compile_type\n else if ty.is_constant\n then do insert_type (mangle_name ty.const_name) ty (lol.type.fn [] (lol.type.var $ mangle_name ty.const_name)),\n return $ (lol.type.fn [] (lol.type.var $ mangle_name ty.const_name))\n else fail $ \"unsupported type: \" ++ to_string ty\n end,\n -- insert_type ty lty,\n return lty\n end\n\nmeta def add_decl (n : name) (ty : expr) : smt2_m unit :=\n do st ← get,\n ct ← compile_type ty,\n let d := lol.decl.fn (mangle_name n) ct none,\n put { st with ctxt := st.ctxt.declare d }\n\n-- meta def ensure_constant (e : expr) (n : name) : smt2_m lol.decl :=\n-- do ty ← infer_type e,\n-- let (arg_tys, ret_ty) := fn_type ty,\n-- let mangled_name := mangle_name n,\n-- arg_sorts ← monad.mapm compile_type arg_tys,\n-- ret_sort ← compile_type ret_ty,\n-- -- ensure_constant_core e (return $ (mangled_name, arg_sorts, ret_sort)),\n-- return $ lol.decl.fn mangled_name arg_sorts ret_sort\n\n-- meta def formula_type_from_arrow (n : name) (e : expr) : smt2_m formula_type :=\n-- do (lol.decl.fn _ arg_sorts ret_sort) ← ensure_constant e n,\n-- return $ formula_type.fn n arg_sorts ret_sort\n\n-- /-- The goal of this function is to categorize the set of formulas in the hypotheses,\n-- and goal. We want to narrow down from the full term language of Lean to a fragment\n-- of formula's we suppose. The below code makes some assumptions:\n\n-- A local constant of the form `(P : Prop)`, must be reflected as declaration\n-- in SMT2 that is `(declare-const P Bool)`.\n\n-- An occurence of a proof of `P`, `(p : P)`, must be transformed into\n-- `(assert P)`. If P is a formula, not an atom, we must transform P into a corresponding\n-- SMT2 formula and `(assert P)`.\n-- -/\n\nmeta def extract_coe_args (args : list expr) : smt2_m (expr × expr × expr) :=\nmatch args with\n| (source :: target :: inst :: e :: []) := return (source, target, e)\n| _ := fail \"internal tactic error expected `coe` to have exactly 4 arguments\"\nend\n\nmeta def reflect_coercion (source target e : expr) (callback : expr → smt2_m lol.term) : smt2_m lol.term :=\nif source = `(nat) ∧ target = `(int)\nthen callback e\nelse fail $ \"unsupported coercion between \" ++ \"`\" ++ to_string source ++ \"` and `\" ++ to_string target ++ \"`\"\n\nmeta def reflect_application (fn : expr) (args : list expr) (callback : expr → smt2_m lol.term) : smt2_m lol.term :=\n if fn.is_constant\n then if fn.const_name = `coe\n then do (source, target, e) ← extract_coe_args args,\n reflect_coercion source target e callback\n else do ty ← infer_type fn,\n let mangled := (mangle_name fn.const_name),\n add_decl fn.const_name ty,\n lol.term.apply mangled <$> monad.mapm callback args\n else if fn.is_local_constant\n then lol.term.apply (mangle_name fn.local_uniq_name) <$> monad.mapm callback args\n else fail $ \"unsupported head symbol `\" ++ to_string fn ++ \"`\"\n\n-- meta def is_supported_head_symbol (e : expr) : bool := true\n\nmeta def is_supported_numeric_ty (ty : expr) : bool :=\n(ty = `(int) ∨ ty = `(nat))\n\n-- /-- This function is the meat of the tactic, it takes a propositional formula in Lean, and transforms\n-- it into a corresponding term in SMT2. -/\nmeta def reflect_arith_formula (reflect_base : expr → smt2_m lol.term) : expr → smt2_m lol.term\n| `(%%a + %%b) := lol.term.add <$> reflect_arith_formula a <*> reflect_arith_formula b\n| `(%%a - %%b) := lol.term.sub <$> reflect_arith_formula a <*> reflect_arith_formula b\n| `(%%a * %%b) := lol.term.mul <$> reflect_arith_formula a <*> reflect_arith_formula b\n| `(%%a / %%b) := lol.term.div <$> reflect_arith_formula a <*> reflect_arith_formula b\n| `(%%a % %%b) := lol.term.mod <$> reflect_arith_formula a <*> reflect_arith_formula b\n| `(- %%a) := lol.term.neg <$> reflect_arith_formula a\n-- /- Constants -/\n| `(has_zero.zero _) := lol.term.int <$> eval_expr int `(has_zero.zero int)\n| `(has_one.one _) := lol.term.int <$> eval_expr int `(has_one.one int)\n| `(bit0 %%Bits) :=\n do ty ← infer_type Bits,\n if is_supported_numeric_ty ty\n then lol.term.int <$> eval_expr int `(bit0 %%Bits : int)\n else if (ty = `(nat))\n then lol.term.int <$> int.of_nat <$> eval_expr nat `(bit0 %%Bits : nat)\n else fail $ \"unknown numeric literal: \" ++ (to_string ```(bit0 %%Bits : int))\n| `(bit1 %%Bits) :=\n do ty ← infer_type Bits,\n if is_supported_numeric_ty ty\n then lol.term.int <$> eval_expr int `(bit1 %%Bits : int)\n else if (ty = `(nat))\n then lol.term.int <$> (int.of_nat <$> eval_expr nat `(bit1 %%Bits : nat))\n else fail $ \"unknown numeric literal: \" ++ (to_string `(bit1 %%Bits : int))\n| a :=\n if a.is_local_constant\n then return $ lol.term.var (mangle_name a.local_uniq_name)\n else if a.is_constant\n then return $ lol.term.var (mangle_name a.const_name)\n else if a.is_app\n then reflect_application (a.get_app_fn) (a.get_app_args) reflect_base\n else fail $ \"unsupported arithmetic formula: \" ++ to_string a\n\n-- /-- Check if the type is an `int` or logically a subtype of an `int` like nat. -/\nmeta def is_int (e : expr) : tactic bool :=\ndo ty ← infer_type e,\n return $ (ty = `(int)) || (ty = `(nat))\n\nmeta def unsupported_ordering_on {α : Type} (elem : expr) : tactic α :=\ndo ty ← infer_type elem,\n tactic.fail $ \"unable to translate orderings for values of type: \" ++ to_string ty\n\nmeta def reflect_ordering (reflect_arith : expr → smt2_m lol.term) (R : lol.term → lol.term → lol.term) (P Q : expr) : smt2_m lol.term :=\ndo is ← is_int P, -- NB: P and Q should have the same type.\n if is\n then R <$> (reflect_arith P) <*> (reflect_arith Q)\n else unsupported_ordering_on P\n\nmeta def supported_pi_binder (ty : expr) : bool :=\nmatch ty with\n| `(int) := tt\n| `(nat) := tt\n| `(Prop) := tt\n| _ := if ty.is_constant\n then tt\n else ff\nend\n\nmeta def add_assertion (t : lol.term) : smt2_m unit :=\n do st ← get,\n put { st with ctxt := st.ctxt.assert t }\n\nmeta def compile_pi (e : expr) (cb : expr → smt2_m lol.term) : smt2_m lol.term :=\nif supported_pi_binder e.binding_domain\nthen do loc ← tactic.mk_local' e.binding_name e.binding_info e.binding_domain,\n lol.term.forallq\n (mangle_name $ loc.local_uniq_name) <$>\n (compile_type $ e.binding_domain) <*>\n (cb (expr.instantiate_var (e.binding_body) loc))\nelse fail $ \"arbitrary Π types are not supported, unable to translate term: `\" ++ to_string e ++ \"`\"\n\nmeta def reflect_prop_formula' : expr → smt2_m lol.term\n| `(¬ %%P) := lol.term.not <$> (reflect_prop_formula' P)\n| `(%%P = %% Q) := lol.term.equals <$> (reflect_prop_formula' P) <*> (reflect_prop_formula' Q)\n| `(%%P ∧ %%Q) := lol.term.and <$> (reflect_prop_formula' P) <*> (reflect_prop_formula' Q)\n| `(%%P ∨ %%Q) := lol.term.or <$> (reflect_prop_formula' P) <*> (reflect_prop_formula' Q)\n| `(%%P ↔ %%Q) := lol.term.iff <$> (reflect_prop_formula' P) <*> (reflect_prop_formula' Q)\n| `(%%P < %%Q) := reflect_ordering (reflect_arith_formula reflect_prop_formula') lol.term.lt P Q\n| `(%%P <= %%Q) := reflect_ordering (reflect_arith_formula reflect_prop_formula') lol.term.lte P Q\n| `(%%P > %%Q) := reflect_ordering (reflect_arith_formula reflect_prop_formula') lol.term.gt P Q\n| `(%%P >= %%Q) := reflect_ordering (reflect_arith_formula reflect_prop_formula') lol.term.gte P Q\n| `(true) := return $ lol.term.true\n| `(false) := return $ lol.term.false\n| e := do ty ← infer_type e,\n if e.is_local_constant\n then pure $ lol.term.var (mangle_name e.local_uniq_name)\n else if e.is_arrow\n then lol.term.implies <$> (reflect_prop_formula' e.binding_domain) <*> (reflect_prop_formula' e.binding_body )\n else if e.is_pi\n then compile_pi e reflect_prop_formula'\n else if is_supported_numeric_ty ty\n then reflect_arith_formula reflect_prop_formula' e\n else if e.is_app\n then reflect_application (e.get_app_fn) (e.get_app_args) reflect_prop_formula'\n else tactic.fail $ \"unsupported propositional formula : \" ++ to_string e\n\nmeta def reflect_prop_formula (e : expr) : smt2_m unit :=\nreflect_prop_formula' e >>= add_assertion\n\n-- meta def warn_unable_to_trans_local (e : expr) : smt2_m (builder unit) := do\n-- trace_smt2 $ \"unable to translate local variable: \" ++ to_string e,\n-- return $ return ()\n\nmeta def is_builtin_type : expr → bool\n| `(int) := tt\n| `(Prop) := tt\n| `(nat) := tt\n| _ := ff\n\nmeta def unsupported_formula (e : expr) : smt2_m unit :=\nfail $ \"unsupported formula: \" ++ to_string e\n\nmeta def compile_local (e : expr) : smt2_m unit :=\ndo ty ← infer_type e,\n prop_sorted ← is_prop ty,\n if e.is_local_constant\n then if is_builtin_type ty\n then add_decl e.local_uniq_name ty\n else if ty.is_arrow\n then add_decl e.local_uniq_name ty\n else if prop_sorted\n then reflect_prop_formula ty\n else unsupported_formula ty\n else if e.is_constant\n then if is_builtin_type ty ∨ ty.is_arrow\n then add_decl e.const_name ty\n else if prop_sorted\n then reflect_prop_formula ty\n else unsupported_formula ty\n else if (ty = `(Prop))\n then reflect_prop_formula e\n else unsupported_formula e\n\nmeta def reflect_attr_decl (n : name) : smt2_m unit :=\ndo exp ← mk_const n,\n compile_local exp\n\n/- Reflect the environment consisting of declarations with the `smt2` attribute. -/\nmeta def reflect_environment : smt2_m unit :=\ndo decls ← attribute.get_instances `smt2,\n bs ← monad.mapm reflect_attr_decl decls.reverse,\n return ()\n\nmeta def reflect_context : smt2_m unit :=\n do ls ← local_context,\n bs ← monad.mapm (fun e, compile_local e) ls,\n return ()\n\nmeta def reflect_goal : smt2_m unit :=\n do tgt ← target,\n -- SMT solvers are looking for satisfiabiltiy, so we must negate to check validity.\n reflect_prop_formula `(_root_.not %%tgt),\n return ()\n\nmeta def reflect : smt2_m (builder unit) :=\ndo reflect_environment,\n reflect_context,\n reflect_goal,\n st ← get,\n return $ (lol.to_builder (lol.smt2_compiler_state.mk (rb_map.mk _ _) st.ctxt []) lol.compile >> check_sat)\n\nend smt2\n\nuniverse u\n\n@[smt2] lemma int_of_nat_is_pos :\n forall (n : nat), 0 <= int.of_nat n :=\nbegin\n intros, trivial\nend\n\naxiom proof_by_z3 (A : Sort u) : A\n\nmeta def z3 (log_file : option string := none) : tactic unit :=\ndo (builder, _) ← smt2.reflect.run smt2_state.initial,\n resp ← unsafe_run_io (smt2 builder log_file),\n match resp with\n | smt2.response.sat := fail \"z3 was unable to prove the goal\"\n | smt2.response.unknown := fail \"z3 was unable to prove the goal\"\n | smt2.response.other str := fail $ \"z3 communication error, unexpected response:\\n\\n\" ++ str ++ \"\\n\"\n | smt2.response.unsat := do\n tgt ← target,\n sry ← to_expr $ ``(proof_by_z3 %%tgt),\n exact sry\n end\n", "meta": {"author": "leanprover", "repo": "smt2_interface", "sha": "7ff0ce248b68ea4db2a2d4966a97b5786da05ed7", "save_path": "github-repos/lean/leanprover-smt2_interface", "path": "github-repos/lean/leanprover-smt2_interface/smt2_interface-7ff0ce248b68ea4db2a2d4966a97b5786da05ed7/src/smt2/default.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4073334144352606, "lm_q2_score": 0.02033235300874136, "lm_q1q2_score": 0.008282046774553662}} {"text": "import Lean.Elab.Tactic\n-- import Lean.Elab.Tactic.Simp\n\n#exit\n\n#check Lean.Meta.getSimpLemmas\n#check Lean.Elab.Tactic.mkSimpContext\n#check Lean.Elab.Tactic.evalSimp\n\ntheorem pointfree_left {f : α → β} {g : β → γ} :\n g (f x) = y →\n (g ∘ f) x = y := id\n\ntheorem pointfree_right {f : α → β} {g : β → γ} :\n x = g (f y) →\n x = (g ∘ f) y := id\n\ntheorem finish_pointfree {f g : α → β} :\n (∀ x, f x = g x) → f = g := funext\n\nnamespace Lean.Meta\n\nnamespace MakeBuddies\n\n\n\nend MakeBuddies\n\nopen Lean.Expr\nopen Meta\nopen Lean.Macro\nopen Lean.Meta\n\n-- def mkLam (v : Expr) (b : Expr) : MetaM Expr := do\n-- let lctx ← getLCtx\n-- let decl := lctx.get! v.fvarId!\n-- let n := decl.userName\n-- let t := decl.type\n-- let bi := decl.binderInfo\n-- return mkLambda n bi t (b.abstract #[v])\n-- open Lean.Meta (mkLambdaFVars)\n\npartial def finishPointFree (pr : Expr) : MetaM (FVarId × Expr) := do\nmatch (← inferType pr) with\n| app (app eq (app f x@(fvar x' _) _) _) (app f' y@(fvar y' _) _) _ => do\n unless (x' == y') do\n throwError \"cannot transform into point-free: {x} {y}\";\n let args := #[none, none, f, f', (← mkLambdaFVars #[x] pr)]\n let l ← mkAppOptM ``finish_pointfree args\n return (x', l)\n| t => do\n throwError \"bad shape {(← ppExpr t)}\"\n\n-- #check @pointfree_right\n\npartial def mkPointFreeRight (pr : Expr) : MetaM (FVarId × Expr) := do\nmatch (← inferType pr) with\n| app (app eq lhs _) (app f (app g x _) _) _ =>\n let args := #[none, none, none, none, x, g, f, pr]\n (mkAppOptM ``pointfree_right args\n >>= mkPointFreeRight)\n| _ => finishPointFree pr\n\n\npartial def mkPointFreeLeft (pr : Expr) : MetaM (FVarId × Expr) := do\nmatch (← inferType pr) with\n| app (app eq (app f (app g x _) _) _) _ _ =>\n let args := #[none, none, none, x, none, g, f, pr]\n (mkAppOptM ``pointfree_left args\n >>= mkPointFreeLeft)\n| _ => mkPointFreeRight pr\n\n\n\ndef makeBuddies (n : Name) : MetaM (Name × Name) := do\nlet info ← getConstInfo n\nlet ls : List Name := info.levelParams\nlet l ← mkConst n (ls.map mkLevelParam)\nlet n' := Name.appendAfter info.name \"_pointfree\"\nlet t ← inferType l\nforallTelescopeReducing t λ args hd => do\n for x in args do\n IO.println s!\"{(← ppExpr x)} : {(← ppExpr (← inferType x))}\"\n IO.println s!\"{(← ppExpr hd)}\"\n let l' := mkAppN l args\n IO.println s!\"{(← ppExpr l')}\"\n IO.println s!\"{(← ppExpr (← inferType l'))}\"\n let (v, e) ← mkPointFreeLeft l'\n let args := args.erase (mkFVar v)\n let e ← mkLambdaFVars args e\n let t ← inferType e\n -- let t ← mkForallFVars args (← inferType e)\n modifyEnv λ env => env.add\n <| ConstantInfo.thmInfo\n <| { name := n',\n levelParams := ls,\n type := t,\n value := e }\n IO.println s!\"{(← ppExpr e)} : {(← ppExpr (← inferType e))}\"\n return (n, n')\n\n#eval makeBuddies ``LawfulFunctor.comp_map\n#check @LawfulFunctor.comp_map_pointfree\n#check getSimpLemmas\nnamespace Buddies\n\nprivate partial def isPerm : Expr → Expr → MetaM Bool\n | Expr.app f₁ a₁ _, Expr.app f₂ a₂ _ => isPerm f₁ f₂ <&&> isPerm a₁ a₂\n | Expr.mdata _ s _, t => isPerm s t\n | s, Expr.mdata _ t _ => isPerm s t\n | s@(Expr.mvar ..), t@(Expr.mvar ..) => isDefEq s t\n | Expr.forallE n₁ d₁ b₁ _, Expr.forallE n₂ d₂ b₂ _ => isPerm d₁ d₂ <&&> withLocalDeclD n₁ d₁ fun x => isPerm (b₁.instantiate1 x) (b₂.instantiate1 x)\n | Expr.lam n₁ d₁ b₁ _, Expr.lam n₂ d₂ b₂ _ => isPerm d₁ d₂ <&&> withLocalDeclD n₁ d₁ fun x => isPerm (b₁.instantiate1 x) (b₂.instantiate1 x)\n | Expr.letE n₁ t₁ v₁ b₁ _, Expr.letE n₂ t₂ v₂ b₂ _ =>\n isPerm t₁ t₂ <&&> isPerm v₁ v₂ <&&> withLetDecl n₁ t₁ v₁ fun x => isPerm (b₁.instantiate1 x) (b₂.instantiate1 x)\n | Expr.proj _ i₁ b₁ _, Expr.proj _ i₂ b₂ _ => i₁ == i₂ <&&> isPerm b₁ b₂\n | s, t => s == t\n\nprivate def checkTypeIsProp (type : Expr) : MetaM Unit :=\n unless (← isProp type) do\n throwError \"invalid 'simp', proposition expected{indentExpr type}\"\n\nprivate def mkSimpLemmaCore (e : Expr) (levelParams : Array Name) (proof : Expr) (post : Bool) (prio : Nat) (name? : Option Name) : MetaM SimpLemma := do\n let type ← instantiateMVars (← inferType e)\n withNewMCtxDepth do\n let (xs, _, type) ← withReducible <| forallMetaTelescopeReducing type\n let type ← whnfR type\n let (keys, perm) ←\n match type.eq? with\n | some (_, lhs, rhs) => pure (← DiscrTree.mkPath lhs, ← isPerm lhs rhs)\n | none => throwError \"unexpected kind of 'simp' theorem{indentExpr type}\"\n return { keys := keys, perm := perm, post := post, levelParams := levelParams, proof := proof, name? := name?, priority := prio }\n\nprivate partial def shouldPreprocess (type : Expr) : MetaM Bool :=\n forallTelescopeReducing type fun xs result => return !result.isEq\n\nprivate partial def preprocess (e type : Expr) (inv : Bool) : MetaM (List (Expr × Expr)) := do\n let type ← whnf type\n if type.isForall then\n forallTelescopeReducing type fun xs type => do\n let e := mkAppN e xs\n let ps ← preprocess e type inv\n ps.mapM fun (e, type) =>\n return (← mkLambdaFVars xs e, ← mkForallFVars xs type)\n else if let some (_, lhs, rhs) := type.eq? then\n if inv then\n let type ← mkEq rhs lhs\n let e ← mkEqSymm e\n return [(e, type)]\n else\n return [(e, type)]\n else if let some (lhs, rhs) := type.iff? then\n if inv then\n let type ← mkEq rhs lhs\n let e ← mkEqSymm (← mkPropExt e)\n return [(e, type)]\n else\n let type ← mkEq lhs rhs\n let e ← mkPropExt e\n return [(e, type)]\n else if let some (_, lhs, rhs) := type.ne? then\n if inv then\n throwError \"invalid '←' modifier in rewrite rule to 'False'\"\n let type ← mkEq (← mkEq lhs rhs) (mkConst ``False)\n let e ← mkEqFalse e\n return [(e, type)]\n else if let some p := type.not? then\n if inv then\n throwError \"invalid '←' modifier in rewrite rule to 'False'\"\n let type ← mkEq p (mkConst ``False)\n let e ← mkEqFalse e\n return [(e, type)]\n else if let some (type₁, type₂) := type.and? then\n let e₁ := mkProj ``And 0 e\n let e₂ := mkProj ``And 1 e\n return (← preprocess e₁ type₁ inv) ++ (← preprocess e₂ type₂ inv)\n else\n if inv then\n throwError \"invalid '←' modifier in rewrite rule to 'True'\"\n let type ← mkEq type (mkConst ``True)\n let e ← mkEqTrue e\n return [(e, type)]\n\nprivate def mkSimpLemmasFromConst (declName : Name) (post : Bool) (inv : Bool) (prio : Nat) : MetaM (Array SimpLemma) := do\n let cinfo ← getConstInfo declName\n let val := mkConst declName (cinfo.levelParams.map mkLevelParam)\n withReducible do\n let type ← inferType val\n checkTypeIsProp type\n if inv || (← shouldPreprocess type) then\n let mut r := #[]\n for (val, type) in (← preprocess val type inv) do\n let auxName ← mkAuxLemma cinfo.levelParams type val\n r := r.push <| (← mkSimpLemmaCore (mkConst auxName (cinfo.levelParams.map mkLevelParam)) #[] (mkConst auxName) post prio declName)\n return r\n else\n #[← mkSimpLemmaCore (mkConst declName (cinfo.levelParams.map mkLevelParam)) #[] (mkConst declName) post prio declName]\n\nabbrev SimpExtension := SimpleScopedEnvExtension SimpEntry SimpLemmas\n\ndef SimpExtension.getLemmas (ext : SimpExtension) : CoreM SimpLemmas :=\n return ext.getState (← getEnv)\n\ndef addSimpLemma (ext : SimpExtension) (declName : Name) (post : Bool) (inv : Bool) (attrKind : AttributeKind) (prio : Nat) : MetaM Unit := do\n let simpLemmas ← mkSimpLemmasFromConst declName post inv prio\n for simpLemma in simpLemmas do\n ext.add (SimpEntry.lemma simpLemma) attrKind\n\ndef mkSimpAttr (attrName : Name) (attrDescr : String) (ext : SimpExtension) : IO Unit :=\n registerBuiltinAttribute {\n name := attrName\n descr := attrDescr\n add := fun declName stx attrKind =>\n let go : MetaM Unit := do\n let info ← getConstInfo declName\n if (← isProp info.type) then\n let post :=\n if stx[1].isNone then true else stx[1][0].getKind == ``Lean.Parser.Tactic.simpPost\n let prio ← getAttrParamOptPrio stx[2]\n addSimpLemma ext declName post (inv := false) attrKind prio\n else if info.hasValue then\n ext.add (SimpEntry.toUnfold declName) attrKind\n else\n throwError \"invalid 'simp', it is not a proposition nor a definition (to unfold)\"\n discard <| go.run {} {}\n erase := fun declName => do\n let s ← ext.getState (← getEnv)\n let s ← s.erase declName\n modifyEnv fun env => ext.modifyState env fun _ => s\n }\n\ndef mkSimpExt (extName : Name) : IO SimpExtension :=\n registerSimpleScopedEnvExtension {\n name := extName\n initial := {}\n addEntry := fun d e =>\n match e with\n | SimpEntry.lemma e => addSimpLemmaEntry d e\n | SimpEntry.toUnfold n => d.addDeclToUnfold n\n }\n\ndef registerSimpAttr (attrName : Name) (attrDescr : String) (extName : Name := attrName.appendAfter \"Ext\") : IO SimpExtension := do\n let ext ← mkSimpExt extName\n mkSimpAttr attrName attrDescr ext\n return ext\n\nbuiltin_initialize mySimpExtension : SimpExtension ← registerSimpAttr `my_simp \"simplification theorem with buddies\"\n\ndef getSimpLemmas : CoreM SimpLemmas :=\n simpExtension.getLemmas\n\nend Buddies\n\nend Lean.Meta\n\nnamespace Lean.Elab.Tactic\n-- abbrev mkDischargeWrapper :=\n-- _root_.Lean.Elab.Tactic.mkDischargeWrapper\n\nopen Lean.Meta\n\n\nprivate def addDeclToUnfoldOrLemma (lemmas : Meta.SimpLemmas) (e : Expr) (post : Bool) (inv : Bool) : MetaM Meta.SimpLemmas := do\n if e.isConst then\n let declName := e.constName!\n let info ← getConstInfo declName\n if (← isProp info.type) then\n lemmas.addConst declName (post := post) (inv := inv)\n else\n if inv then\n throwError \"invalid '←' modifier, '{declName}' is a declaration name to be unfolded\"\n lemmas.addDeclToUnfold declName\n else\n lemmas.add #[] e (post := post) (inv := inv)\n\nprivate def addSimpLemma (lemmas : Meta.SimpLemmas) (stx : Syntax) (post : Bool) (inv : Bool) : TermElabM Meta.SimpLemmas := do\n let (levelParams, proof) ← Term.withoutModifyingElabMetaStateWithInfo <| withRef stx <| Term.withoutErrToSorry do\n let e ← Term.elabTerm stx none\n Term.synthesizeSyntheticMVars (mayPostpone := false) (ignoreStuckTC := true)\n let e ← instantiateMVars e\n let e := e.eta\n if e.hasMVar then\n let r ← abstractMVars e\n return (r.paramNames, r.expr)\n else\n return (#[], e)\n lemmas.add levelParams proof (post := post) (inv := inv)\n\n/--\n Elaborate extra simp lemmas provided to `simp`. `stx` is of the `simpLemma,*`\n If `eraseLocal == true`, then we consider local declarations when resolving names for erased lemmas (`- id`),\n this option only makes sense for `simp_all`.\n-/\nprivate def elabSimpArgs (stx : Syntax) (ctx : Simp.Context) (eraseLocal : Bool) : TacticM ElabSimpArgsResult := do\n if stx.isNone then\n return { ctx }\n else\n /-\n syntax simpPre := \"↓\"\n syntax simpPost := \"↑\"\n syntax simpLemma := (simpPre <|> simpPost)? term\n\n syntax simpErase := \"-\" ident\n -/\n withMainContext do\n let mut lemmas := ctx.simpLemmas\n let mut starArg := false\n for arg in stx[1].getSepArgs do\n if arg.getKind == ``Lean.Parser.Tactic.simpErase then\n if eraseLocal && (← Term.isLocalIdent? arg[1]).isSome then\n -- We use `eraseCore` because the simp lemma for the hypothesis was not added yet\n lemmas ← lemmas.eraseCore arg[1].getId\n else\n let declName ← resolveGlobalConstNoOverloadWithInfo arg[1]\n lemmas ← lemmas.erase declName\n else if arg.getKind == ``Lean.Parser.Tactic.simpLemma then\n let post :=\n if arg[0].isNone then\n true\n else\n arg[0][0].getKind == ``Parser.Tactic.simpPost\n let inv := !arg[1].isNone\n let term := arg[2]\n match (← resolveSimpIdLemma? term) with\n | some e => lemmas ← addDeclToUnfoldOrLemma lemmas e post inv\n | _ => lemmas ← addSimpLemma lemmas term post inv\n else if arg.getKind == ``Lean.Parser.Tactic.simpStar then\n starArg := true\n else\n throwUnsupportedSyntax\n return { ctx := { ctx with simpLemmas := lemmas }, starArg }\nwhere\n resolveSimpIdLemma? (simpArgTerm : Syntax) : TacticM (Option Expr) := do\n if simpArgTerm.isIdent then\n try\n Term.resolveId? simpArgTerm (withInfo := true)\n catch _ =>\n return none\n else\n Term.elabCDotFunctionAlias? simpArgTerm\n\nprivate def mkDischargeWrapper (optDischargeSyntax : Syntax) : TacticM Simp.DischargeWrapper := do\n if optDischargeSyntax.isNone then\n return Simp.DischargeWrapper.default\n else\n let (ref, d) ← tacticToDischarge optDischargeSyntax[0][3]\n return Simp.DischargeWrapper.custom ref d\n\n-- TODO: move?\nprivate def getPropHyps : MetaM (Array FVarId) := do\n let mut result := #[]\n for localDecl in (← getLCtx) do\n unless localDecl.isAuxDecl do\n if (← isProp localDecl.type) then\n result := result.push localDecl.fvarId\n return result\n\n/--\n If `ctx == false`, the config argument is assumed to have type `Meta.Simp.Config`, and `Meta.Simp.ConfigCtx` otherwise.\n If `ctx == false`, the `discharge` option must be none -/\ndef mkSimpContext' (stx : Syntax) (eraseLocal : Bool) (ctx := false) (ignoreStarArg : Bool := false) : TacticM MkSimpContextResult := do\n if ctx && !stx[2].isNone then\n throwError \"'simp_all' tactic does not support 'discharger' option\"\n let dischargeWrapper ← mkDischargeWrapper stx[2]\n let simpOnly := !stx[3].isNone\n let simpLemmas ←\n if simpOnly then\n ({} : SimpLemmas).addConst ``eq_self\n else\n getSimpLemmas\n let congrLemmas ← getCongrLemmas\n let r ← elabSimpArgs stx[4] (eraseLocal := eraseLocal) {\n config := (← elabSimpConfig stx[1] (ctx := ctx))\n simpLemmas, congrLemmas\n }\n if !r.starArg || ignoreStarArg then\n return { r with fvarIdToLemmaId := {}, dischargeWrapper }\n else\n let ctx := r.ctx\n let erased := ctx.simpLemmas.erased\n let hs ← getPropHyps\n let mut ctx := ctx\n let mut fvarIdToLemmaId := {}\n for h in hs do\n let localDecl ← getLocalDecl h\n unless erased.contains localDecl.userName do\n let fvarId := localDecl.fvarId\n let proof := localDecl.toExpr\n let id ← mkFreshUserName `h\n fvarIdToLemmaId := fvarIdToLemmaId.insert fvarId id\n let simpLemmas ← ctx.simpLemmas.add #[] proof (name? := id)\n ctx := { ctx with simpLemmas }\n return { ctx, fvarIdToLemmaId, dischargeWrapper }\n\n@[tactic Lean.Parser.Tactic.simp] def evalSimp' : Tactic := fun stx => do\n IO.println \"simp!!!\"\n -- let { ctx, fvarIdToLemmaId, dischargeWrapper } ← withMainContext <| mkSimpContext stx (eraseLocal := false)\n -- -- trace[Meta.debug] \"Lemmas {← toMessageData ctx.simpLemmas.post}\"\n -- dischargeWrapper.with fun discharge? =>\n -- simpLocation ctx discharge? fvarIdToLemmaId (expandOptLocation stx[5])\n\nend Lean.Elab.Tactic\n\nexample : True := by simp\n", "meta": {"author": "cipher1024", "repo": "lean4-prog", "sha": "49f7416ee19df921bfea1b4914404b9d07619d64", "save_path": "github-repos/lean/cipher1024-lean4-prog", "path": "github-repos/lean/cipher1024-lean4-prog/lean4-prog-49f7416ee19df921bfea1b4914404b9d07619d64/lib/lib/MySimp.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2782567937024021, "lm_q2_score": 0.02976009588214574, "lm_q1q2_score": 0.008280948860441933}} {"text": "import Lbar.ext_aux4\nimport Lbar.iota\n\nnoncomputable theory\n\nuniverses v u u'\n\nopen opposite category_theory category_theory.limits category_theory.preadditive\nopen_locale nnreal zero_object\n\nvariables (r r' : ℝ≥0)\nvariables [fact (0 < r)] [fact (0 < r')] [fact (r < r')] [fact (r < 1)] [fact (r' < 1)]\n\nopen bounded_homotopy_category\n\nvariables {r'}\nvariables (BD : breen_deligne.package)\nvariables (κ κ₂ : ℝ≥0 → ℕ → ℝ≥0)\nvariables [∀ (c : ℝ≥0), BD.data.suitable (κ c)] [∀ n, fact (monotone (function.swap κ n))]\nvariables [∀ (c : ℝ≥0), BD.data.suitable (κ₂ c)] [∀ n, fact (monotone (function.swap κ₂ n))]\nvariables (M : ProFiltPseuNormGrpWithTinv₁.{u} r')\n\nnamespace Lbar\n\nopen ProFiltPseuNormGrpWithTinv₁ ProFiltPseuNormGrp₁ CompHausFiltPseuNormGrp₁\nopen bounded_homotopy_category\n\nvariables (r r')\n\ndef Tinv_sub (S : Profinite.{u}) (V : SemiNormedGroup.{u}) [normed_with_aut r V] (i : ℤ) :\n ((Ext' i).obj (op $ (Lbar.condensed.{u} r').obj S)).obj V.to_Cond ⟶\n ((Ext' i).obj (op $ (Lbar.condensed.{u} r').obj S)).obj V.to_Cond :=\n((Ext' i).map ((condensify_Tinv _).app S).op).app _ -\n((Ext' i).obj _).map (Condensed.of_top_ab_map (normed_with_aut.T.inv).to_add_monoid_hom\n (normed_add_group_hom.continuous _))\n\n-- move me\nattribute [simps] Condensed.of_top_ab_map\n\nvariables (S : Profinite.{0}) (V : SemiNormedGroup.{0})\nvariables [complete_space V] [separated_space V]\nvariables (r')\n\n-- TODO(!): TC loop? using \"by apply_instance\" causes a maximum TC error\ninstance (X : Profinite.{0}) :\n preserves_limits_of_shape.{0 0 0 0 1 1}\n (discrete_quotient.{0} ↥X) (PFPNGT₁_to_CHFPNG₁ₑₗ.{0} r') := {}\n\nset_option pp.universes true\ndef condensify_iso_extend :\n condensify (Fintype_Lbar.{0 0} r' ⋙ PFPNGT₁_to_CHFPNG₁ₑₗ r') ≅\n (Profinite.extend (Fintype_Lbar.{0 0} r')) ⋙\n (PFPNGT₁_to_CHFPNG₁ₑₗ r' ⋙ CHFPNG₁_to_CHFPNGₑₗ.{0} ⋙\n CompHausFiltPseuNormGrp.to_Condensed.{0}) :=\n(((whiskering_left _ _ _).map_iso $\n Profinite.extend_commutes (Fintype_Lbar.{0 0} r') (PFPNGT₁_to_CHFPNG₁ₑₗ r')).app\n (CHFPNG₁_to_CHFPNGₑₗ.{0} ⋙ CompHausFiltPseuNormGrp.to_Condensed.{0})).symm\n\ndef condensify_iso_extend' :\n (condensify (Fintype_Lbar.{0 0} r' ⋙ PFPNGT₁_to_CHFPNG₁ₑₗ r')).obj S ≅\n ((Profinite.extend (Fintype_Lbar.{0 0} r')).obj S).to_Condensed :=\n(condensify_iso_extend r').app S\n\nsection move_me\n\n--universes u'\n\nopen Profinite\n\nvariables {C : Type u} [category.{v} C] (F : Fintype.{v} ⥤ C)\nvariables {D : Type u'} [category.{v} D]\nvariable [∀ X : Profinite, has_limit (X.fintype_diagram ⋙ F)]\n\n@[reassoc]\nlemma extend_commutes_comp_extend_extends' (G : C ⥤ D)\n [∀ X : Profinite.{v}, preserves_limits_of_shape (discrete_quotient X) G]\n [∀ X : Profinite.{v}, has_limit (X.fintype_diagram ⋙ F ⋙ G)] :\n whisker_left Fintype.to_Profinite (extend_commutes F G).hom =\n (functor.associator _ _ _).inv ≫ (whisker_right (extend_extends _).hom G) ≫\n (extend_extends _).inv :=\nby rw [← category.assoc, iso.eq_comp_inv, extend_commutes_comp_extend_extends]\n\n@[reassoc]\nlemma extend_commutes_comp_extend_extends'' (G : C ⥤ D)\n [∀ X : Profinite.{v}, preserves_limits_of_shape (discrete_quotient X) G]\n [∀ X : Profinite.{v}, has_limit (X.fintype_diagram ⋙ F ⋙ G)] :\n whisker_left Fintype.to_Profinite (extend_commutes F G).inv =\n (extend_extends _).hom ≫ (whisker_right (extend_extends _).inv G) ≫\n (functor.associator _ _ _).hom :=\nbegin\n rw [← iso.inv_comp_eq, ← iso_whisker_left_inv, iso.comp_inv_eq, iso_whisker_left_hom,\n extend_commutes_comp_extend_extends', category.assoc, iso.hom_inv_id_assoc,\n ← iso_whisker_right_hom, ← iso_whisker_right_inv, iso.inv_hom_id_assoc],\nend\n\nend move_me\n\nlemma condensify_Tinv_iso :\n condensify_Tinv (Fintype_Lbar.{0 0} r') ≫ (condensify_iso_extend r').hom =\n (condensify_iso_extend r').hom ≫ (@whisker_right _ _ _ _ _ _ _ _ (Tinv_nat_trans _) _) :=\nbegin\n delta Tinv_cond condensify_Tinv condensify_nonstrict condensify_iso_extend' condensify_iso_extend,\n ext S : 2,\n rw [iso.symm_hom, iso.app_inv, functor.map_iso_inv, nat_trans.comp_app, nat_trans.comp_app,\n whiskering_left_map_app_app, ← iso.app_inv, ← functor.map_iso_inv, iso.comp_inv_eq,\n functor.map_iso_inv, functor.map_iso_hom, functor.comp_map, functor.comp_map,\n whisker_right_app, whisker_right_app, ← functor.map_comp, ← functor.map_comp],\n congr' 1,\n rw [iso.app_inv, iso.app_hom, ← whisker_right_app, ← whisker_right_app,\n ← nat_trans.comp_app, ← nat_trans.comp_app],\n congr' 1,\n refine nonstrict_extend_ext _ _ (r'⁻¹) (1 * (r'⁻¹ * 1)) _ _ _,\n { intro X, apply nonstrict_extend_bound_by },\n { intro X,\n apply comphaus_filtered_pseudo_normed_group_hom.bound_by.comp,\n apply comphaus_filtered_pseudo_normed_group_hom.bound_by.comp,\n { apply strict_comphaus_filtered_pseudo_normed_group_hom.to_chfpsng_hom.bound_by_one },\n { apply Tinv_bound_by },\n { apply strict_comphaus_filtered_pseudo_normed_group_hom.to_chfpsng_hom.bound_by_one }, },\n { rw [whisker_left_comp, whisker_left_comp, ← whisker_right_left, ← whisker_right_left,\n extend_commutes_comp_extend_extends', extend_commutes_comp_extend_extends''],\n rw nonstrict_extend_whisker_left,\n\n ext X : 2,\n simp only [whisker_left_app, whisker_right_app, nat_trans.comp_app,\n functor.associator_hom_app, functor.associator_inv_app,\n category.id_comp, category.comp_id, category.assoc, functor.map_comp],\n slice_rhs 2 3 {},\n congr' 2,\n\n simp only [← iso.app_hom, ← iso.app_inv, ← functor.map_iso_hom, ← functor.map_iso_inv,\n category.assoc, iso.eq_inv_comp],\n\n ext x : 1,\n exact (comphaus_filtered_pseudo_normed_group_with_Tinv_hom.map_Tinv\n ((Profinite.extend_extends (Fintype_Lbar.{0 0} r')).app X).hom x).symm }\nend\n\nlemma condensify_Tinv_iso' :\n (condensify_Tinv (Fintype_Lbar.{0 0} r')).app S ≫ (condensify_iso_extend' r' S).hom =\n (condensify_iso_extend' r' S).hom ≫ ((Profinite.extend (Fintype_Lbar.{0 0} r')).obj S).Tinv_cond :=\nbegin\n have := condensify_Tinv_iso r',\n apply_fun (λ η, η.app S) at this,\n exact this,\nend\n\ndef useful_commsq (i : ℤ) (ι : ulift.{1} ℕ → ℝ≥0) (hι : monotone ι) [normed_with_aut r V] :=\n shift_sub_id.commsq\n (ExtQprime.Tinv2 r r' breen_deligne.eg.data\n (λ c n, c * breen_deligne.eg.κ r r' n)\n (λ c n, r' * (c * breen_deligne.eg.κ r r' n))\n ((Lbar.functor.{0 0} r').obj S) V i) ι hι\n\nsection\nopen breen_deligne thm95.universal_constants\n\nvariables (i : ℕ)\n\nlemma useful_commsq_bicartesian (ι : ulift.{1} ℕ → ℝ≥0) (hι : monotone ι) [normed_with_aut r V]\n (H1 : ∀ j, c₀ r r' eg (λ n, eg.κ r r' n) (eg.κ' r r') (i+1) ⟨ℤ⟩ ≤ ι j)\n (H2 : ∀ j, k (eg.κ' r r') i ^ 2 * ι j ≤ ι (j + 1))\n (H3 : ∀ j, k (eg.κ' r r') (i+1) ^ 2 * ι j ≤ ι (j + 1)) :\n (useful_commsq r r' S V i ι hι).bicartesian :=\nbegin\n apply shift_sub_id.bicartesian_iso _ _\n (ExtQprime_iso_aux_system r' _ _ _ V i).symm (ExtQprime_iso_aux_system r' _ _ _ V i).symm ι hι\n (ExtQprime_iso_aux_system_comm' _ _ _ _ _ _ _ _),\n rw [← whisker_right_twice],\n refine shift_sub_id.bicartesian (aux_system.incl'.{0 1} r r' _ _ _ (eg.κ r r')) _\n i ι hι _ _ _,\n { apply_with system_of_complexes.shift_eq_zero {instances := ff},\n swap 3, { apply thm94.explicit r r' _ _ (eg.κ' r r'), },\n any_goals { apply_instance },\n { intro j,\n refine le_trans _ ((c₀_mono _ _ _ _ _ _ (i+1)).out.trans (H1 j)),\n rw nat.add_sub_cancel, },\n { exact H2 } },\n { apply_with system_of_complexes.shift_eq_zero {instances := ff},\n swap 3, { apply thm94.explicit r r' _ _ (eg.κ' r r'), },\n any_goals { apply_instance },\n { exact H1 },\n { exact H3 } },\n { intros c n,\n let κ := eg.κ r r',\n apply aux_system.short_exact r r' _ _ _ (λ c n, r' * (c * κ n)) κ,\n intro c, dsimp, apply_instance, }\nend\n\nlemma bicartesian_of_is_zero {𝓒 : Type*} [category 𝓒] [abelian 𝓒]\n {A B C D : 𝓒} (f₁ : A ⟶ B) (g₁ : A ⟶ C) (g₂ : B ⟶ D) (f₂ : C ⟶ D) (h : commsq f₁ g₁ g₂ f₂)\n (hA : is_zero A) (hB : is_zero B) (hC : is_zero C) (hD : is_zero D) :\n h.bicartesian :=\nbegin\n delta commsq.bicartesian,\n apply_with short_exact.mk {instances:=ff},\n { refine ⟨λ X f g h, _⟩, apply hA.eq_of_tgt },\n { refine ⟨λ X f g h, _⟩, apply hD.eq_of_src },\n { apply exact_of_is_zero ((is_zero_biprod _ _ hB hC).of_iso (h.sum.iso (sum_str.biprod _ _))), }\nend\n\nlemma is_zero_pi {𝓒 : Type*} [category 𝓒] [abelian 𝓒] {ι : Type*} (f : ι → 𝓒) [has_product f]\n (hf : ∀ i, is_zero (f i)) :\n is_zero (∏ f) :=\nbegin\n rw is_zero_iff_id_eq_zero,\n ext ⟨j⟩,\n apply (hf j).eq_of_tgt,\nend\n\nlemma useful_commsq_bicartesian_neg (ι : ulift.{1} ℕ → ℝ≥0) (hι : monotone ι) [normed_with_aut r V]\n (i : ℤ) (hi : i < 0) :\n (useful_commsq r r' S V i ι hι).bicartesian :=\nbegin\n have : 1 + i ≤ 0, { linarith only [hi] },\n apply bicartesian_of_is_zero;\n apply is_zero_pi; intro x;\n apply Ext_single_right_is_zero _ _ 1 _ _ (chain_complex.bounded_by_one _) this\nend\n\nlemma is_iso_sq {𝓒 : Type*} [category 𝓒] {X Y : 𝓒} (f₁ : X ⟶ X) (f₂ : Y ⟶ Y)\n (e : X ≅ Y) (h : f₁ ≫ e.hom = e.hom ≫ f₂) (h₁ : is_iso f₁) :\n is_iso f₂ :=\nby { rw [← iso.inv_comp_eq] at h, rw ← h, apply_instance }\n\nopen category_theory.preadditive\n\nlemma is_iso_sq' {𝓒 : Type*} [category 𝓒] [abelian 𝓒] [enough_projectives 𝓒]\n {X Y Z : bounded_homotopy_category 𝓒} (f₁ : X ⟶ X) (f₂ : Y ⟶ Y) (f₃ : Z ⟶ Z)\n (e : Y ≅ X) (h : e.hom ≫ f₁ = f₂ ≫ e.hom) (i : ℤ)\n (h₁ : is_iso (((Ext i).map f₁.op).app Z - ((Ext i).obj _).map f₃)) :\n is_iso (((Ext i).map f₂.op).app Z - ((Ext i).obj _).map f₃) :=\nbegin\n refine is_iso_sq _ _ ((functor.map_iso _ e.op).app _) _ h₁,\n rw [iso.app_hom, functor.map_iso_hom, sub_comp, comp_sub, nat_trans.naturality,\n ← nat_trans.comp_app, ← nat_trans.comp_app, ← functor.map_comp, ← functor.map_comp,\n iso.op_hom, ← op_comp, ← op_comp, h],\nend\n\n/-- Thm 9.4bis of [Analytic]. More precisely: the first observation in the proof 9.4 => 9.1. -/\ntheorem is_iso_Tinv_sub [normed_with_aut r V] : ∀ i, is_iso (Tinv_sub r r' S V i) :=\nbegin\n erw (Condensed.bd_lemma _ _ _ _),\n swap, { apply Lbar.obj.no_zero_smul_divisors },\n intro i,\n refine is_iso_sq' _ _ _ (functor.map_iso _ $ condensify_iso_extend' _ _) _ _ _,\n { refine category_theory.functor.map _ _, refine Tinv_cond _ },\n { rw [functor.map_iso_hom, ← functor.map_comp, ← functor.map_comp, condensify_Tinv_iso'], },\n revert i,\n refine Tinv2_iso_of_bicartesian' r breen_deligne.eg\n (λ c n, c * breen_deligne.eg.κ r r' n)\n (λ c n, r' * (c * breen_deligne.eg.κ r r' n))\n ((Lbar.functor.{0 0} r').obj S) V _,\n rintro (i|(_|i)),\n { refine ⟨ι r r' i, hι r r' i, _, _, _, _⟩,\n { intros s m,\n apply Lbar.sufficiently_increasing_eg },\n { intros s m,\n apply Lbar.sufficiently_increasing_eg' },\n all_goals { apply useful_commsq_bicartesian },\n { rintro ⟨j⟩, apply Hι1 },\n { rintro ⟨j⟩, apply Hι2a },\n { rintro ⟨j⟩, apply Hι2b },\n { rintro ⟨j⟩, apply Hι1' },\n { rintro ⟨j⟩, apply Hι2b },\n { rintro ⟨j⟩, apply Hι2c } },\n { refine ⟨ι r r' 0, hι r r' 0, _, _, _, _⟩,\n { intros s m, apply Lbar.sufficiently_increasing_eg, },\n { intros s m, apply Lbar.sufficiently_increasing_eg', },\n { apply useful_commsq_bicartesian_neg, dec_trivial },\n { apply useful_commsq_bicartesian,\n { rintro ⟨j⟩, apply Hι1 },\n { rintro ⟨j⟩, apply Hι2a },\n { rintro ⟨j⟩, apply Hι2b }, }, },\n { refine ⟨ι r r' 0, hι r r' 0, _, _, _, _⟩,\n { intros s m, apply Lbar.sufficiently_increasing_eg, },\n { intros s m, apply Lbar.sufficiently_increasing_eg', },\n { apply useful_commsq_bicartesian_neg, dec_trivial },\n { apply useful_commsq_bicartesian_neg,\n rw [int.neg_succ_of_nat_eq'],\n simp only [int.coe_nat_succ, neg_add_rev, sub_add_cancel, add_neg_lt_iff_le_add', add_zero],\n dec_trivial }, },\nend\n\n/-- Thm 9.4bis of [Analytic]. More precisely: the first observation in the proof 9.4 => 9.1. -/\ntheorem is_iso_Tinv2 [normed_with_aut r V]\n (hV : ∀ (v : V), (normed_with_aut.T.inv v) = 2 • v) :\n ∀ i, is_iso (((Ext' i).map ((condensify_Tinv2 (Fintype_Lbar.{0 0} r')).app S).op).app\n (Condensed.of_top_ab ↥V)) :=\nbegin\n intro i,\n rw [condensify_Tinv2_eq, ← functor.flip_obj_map, nat_trans.app_sub, category_theory.op_sub,\n nat_trans.app_nsmul, category_theory.op_nsmul, two_nsmul, nat_trans.id_app, op_id,\n functor.map_sub, functor.map_add, category_theory.functor.map_id],\n convert is_iso_Tinv_sub r r' S V i using 2,\n suffices : Condensed.of_top_ab_map (normed_add_group_hom.to_add_monoid_hom normed_with_aut.T.inv) _ =\n 2 • 𝟙 _,\n { rw [this, two_nsmul, functor.map_add, category_theory.functor.map_id], refl, },\n ext T f t,\n dsimp only [Condensed.of_top_ab_map_val, whisker_right_app, Ab.ulift_map_apply_down,\n add_monoid_hom.mk'_apply, continuous_map.coe_mk, function.comp_app],\n erw [hV, two_nsmul, two_nsmul],\n refl,\nend\n\nend\n\nend Lbar\n", "meta": {"author": "leanprover-community", "repo": "lean-liquid", "sha": "92f188bd17f34dbfefc92a83069577f708851aec", "save_path": "github-repos/lean/leanprover-community-lean-liquid", "path": "github-repos/lean/leanprover-community-lean-liquid/lean-liquid-92f188bd17f34dbfefc92a83069577f708851aec/src/Lbar/ext.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38121955219593834, "lm_q2_score": 0.02161533457465327, "lm_q1q2_score": 0.008240188167114703}} {"text": "import .geom3d_series\nimport tactic.linarith\n\ndef ts := time_std_space\n\ndef world_fr := geom3d_std_frame\ndef world := geom3d_std_space\n\ndef bl_fr := \n let origin := mk_position3d world 1.000000 2.000000 3.000000 in\n let basis0 := mk_displacement3d world 4.000000 3.000000 2.000000 in\n let basis1 := mk_displacement3d world 1.000000 2.000000 3.000000 in\n let basis2 := mk_displacement3d world 2.000000 1.000000 2.000000 in\n mk_geom3d_frame origin basis0 basis1 basis2\n\ndef fr1 := \n let origin := mk_position3d world 2.000000 4.000000 3.000000 in\n let basis0 := mk_displacement3d world 4.000000 3.000000 2.000000 in\n let basis1 := mk_displacement3d world 1.000000 2.000000 3.000000 in\n let basis2 := mk_displacement3d world 2.000000 1.000000 2.000000 in\n mk_geom3d_frame origin basis0 basis1 basis2\n\ndef fr2 := \n let origin := mk_position3d world 4.000000 4.000000 3.000000 in\n let basis0 := mk_displacement3d world 4.000000 3.000000 2.000000 in\n let basis1 := mk_displacement3d world 1.000000 2.000000 3.000000 in\n let basis2 := mk_displacement3d world 2.000000 1.000000 2.000000 in\n mk_geom3d_frame origin basis0 basis1 basis2\n\ndef ser : geom3d_series ts := \n ⟨\n [\n (mk_time _ 2,world_fr)--,\n -- (mk_time _ 1,fr1),\n --(mk_time _ 0,fr2)\n \n --(mk_time _ 2),\n --(mk_time _ 1),\n --(mk_time _ 0)\n ]⟩\n/-(⟨mk_time _ 0,sorry⟩-/\n\n#eval ser\n\n#check quotient.eq\n\ndef v1 := mk_displacement3d_timefixed_at_time ser (mk_time ts (2.4:ℚ)) 1 1 1\n\ndef v2 := mk_displacement3d_timefixed_at_time ser (mk_time ts (2.5:ℚ)) 1 1 1\n\nexample : v1.frame = world_fr := begin\n unfold displacement3d.frame,\n unfold geom3d_series.find,\n split,\nend\n\nexample : v1.frame = v2.frame := begin\n dsimp [displacement3d.frame],\n split,\nend\n\n#check v1 +ᵥ v2\n\ndef t1 := ⟦(⟨(mk_time ts (2.4:ℚ))⟩ : series_index ts ser)⟧\ndef t2 := ⟦(⟨(mk_time ts (2.5:ℚ))⟩ : series_index ts ser)⟧\n\nexample : t1 = t2 := sorry\n\n#check t1\n\n#check quotient.lift\n\ndef v3 := mk_displacement3d_timefixed_at_time'' ser ⟦series_index.mk (mk_time ts (2.4:ℚ))⟧ 1 1 1\n\ndef v4 := mk_displacement3d_timefixed_at_time'' ser ⟦series_index.mk (mk_time ts (2.5:ℚ))⟧ 1 1 1\n\n#check v3 +ᵥ v4", "meta": {"author": "kevinsullivan", "repo": "phys", "sha": "ebc2df3779d3605ff7a9b47eeda25c2a551e011f", "save_path": "github-repos/lean/kevinsullivan-phys", "path": "github-repos/lean/kevinsullivan-phys/phys-ebc2df3779d3605ff7a9b47eeda25c2a551e011f/old/geom3d_stamped_test2.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.41111086923216805, "lm_q2_score": 0.020023440741208848, "lm_q1q2_score": 0.008231854128137176}} {"text": "import .brown\n\nuniverses v u\n\nopen category_theory\nlocal notation f ` ∘ `:80 g:80 := g ≫ f\n\nnamespace homotopy_theory.cofibrations\nopen precofibration_category cofibration_category\nopen homotopy_theory.weak_equivalences\n\nvariables {C : Type u} [category.{v} C] [cofibration_category.{v} C]\n [has_initial_object.{v} C]\n\n-- Following Rădulescu-Banu, Cofibrations in Homotopy Theory, Lemma 1.4.1\n\nvariables {a₁ a₂ a₃ a₄ b₁ b₂ b₃ b₄ : C}\n {f₁₂ : a₁ ⟶ a₂} {f₁₃ : a₁ ⟶ a₃} {f₂₄ : a₂ ⟶ a₄} {f₃₄ : a₃ ⟶ a₄}\n (po_f : Is_pushout f₁₂ f₁₃ f₂₄ f₃₄)\n {g₁₂ : b₁ ⟶ b₂} {g₁₃ : b₁ ⟶ b₃} {g₂₄ : b₂ ⟶ b₄} {g₃₄ : b₃ ⟶ b₄}\n (po_g : Is_pushout g₁₂ g₁₃ g₂₄ g₃₄)\n {u₁ : a₁ ⟶ b₁} {u₂ : a₂ ⟶ b₂} {u₃ : a₃ ⟶ b₃} -- u₄ will be the induced map of pushouts\n (ha₁ : cofibrant a₁) (ha₃ : cofibrant a₃) (hb₁ : cofibrant b₁) (hb₃ : cofibrant b₃)\n (hf₁₂ : is_cof f₁₂) (hg₁₂ : is_cof g₁₂)\n (hwu₁ : is_weq u₁) (hwu₂ : is_weq u₂) (hwu₃ : is_weq u₃)\n (s₁₂ : f₁₂ ≫ u₂ = u₁ ≫ g₁₂) (s₁₃ : f₁₃ ≫ u₃ = u₁ ≫ g₁₃)\n\nlemma gluing_weq_aux (hcu₁ : is_cof u₁) (hcu₃ : is_cof u₃)\n (hcu₂'' : is_cof ((pushout_by_cof f₁₂ u₁ hf₁₂).is_pushout.induced u₂ g₁₂ s₁₂)) :\n is_weq (pushout_of_maps po_f po_g u₁ u₂ u₃ s₁₂ s₁₃) :=\nhave acof_u₁ : is_acof u₁ := ⟨hcu₁, hwu₁⟩,\nhave acof_u₃ : is_acof u₃ := ⟨hcu₃, hwu₃⟩,\nlet po₁₂ := pushout_by_cof f₁₂ u₁ hf₁₂,\n u₂' := po₁₂.map₀,\n u₂'' := po₁₂.is_pushout.induced u₂ g₁₂ s₁₂,\n u₄ := pushout_of_maps po_f po_g u₁ u₂ u₃ s₁₂ s₁₃,\n po₃₄ := pushout_by_cof f₃₄ u₃ (pushout_is_cof po_f hf₁₂),\n u₄' := po₃₄.map₀,\n u₄'' := po₃₄.is_pushout.induced u₄ g₃₄ (by simp) in\nhave acof_u₂' : is_acof u₂' := pushout_is_acof po₁₂.is_pushout.transpose acof_u₁,\nhave acof_u₄' : is_acof u₄' := pushout_is_acof po₃₄.is_pushout.transpose acof_u₃,\nhave acof_u₂'' : is_acof u₂'' := have _ := hwu₂, begin\n refine ⟨hcu₂'', category_with_weak_equivalences.weq_of_comp_weq_left acof_u₂'.2 _⟩,\n simpa using this\nend,\nlet k := pushout_of_maps po₁₂.is_pushout po₃₄.is_pushout f₁₃ f₂₄ g₁₃ po_f.commutes s₁₃.symm in\nsuffices Is_pushout u₂'' k g₂₄ u₄'',\n by convert weq_comp acof_u₄'.2 (pushout_is_acof this acof_u₂'').2; simp,\nhave _ := Is_pushout_of_Is_pushout_of_Is_pushout po_f po₃₄.is_pushout,\nhave Is_pushout f₁₂ (u₁ ≫ g₁₃) (u₂' ≫ k) po₃₄.map₁ := begin\n convert this using 1,\n { exact s₁₃.symm },\n { simp }\nend,\nhave Is_pushout po₁₂.map₁ g₁₃ k po₃₄.map₁ :=\n Is_pushout_of_Is_pushout_of_Is_pushout' po₁₂.is_pushout this (by simp),\nhave po_g' : Is_pushout (po₁₂.map₁ ≫ u₂'') g₁₃ g₂₄ (po₃₄.map₁ ≫ u₄'') := by convert po_g using 1; simp,\nIs_pushout_of_Is_pushout_of_Is_pushout_vert' this po_g' $\n by apply po₁₂.is_pushout.uniqueness; rw [←category.assoc, ←category.assoc]; simp [po_g.commutes]\n\nlemma gluing_weq : is_weq (pushout_of_maps po_f po_g u₁ u₂ u₃ s₁₂ s₁₃) :=\nlet ⟨c₁⟩ := exists_brown_factorization ha₁ hb₁ u₁,\n ⟨c₂, h₁₂, hv₂, hr₂, hw₂, x, y⟩ :=\n exists_relative_brown_factorization\n ha₁ hb₁ (cofibrant_of_cof ha₁ hf₁₂) (cofibrant_of_cof hb₁ hg₁₂) u₁ u₂ f₁₂ g₁₂ s₁₂.symm c₁,\n ⟨c₃, h₁₃, hv₃, hr₃, hw₃, _, _⟩ :=\n exists_relative_brown_factorization ha₁ hb₁ ha₃ hb₃ u₁ u₃ f₁₃ g₁₃ s₁₃.symm c₁,\n po := pushout_by_cof c₁.f' f₁₂ c₁.hf' in\nhave cof_h₁₂ : is_cof h₁₂ := begin\n convert cof_comp (pushout_is_cof po.is_pushout.transpose hf₁₂) (x hg₁₂) using 1,\n simp\nend,\nhave wv : _ := gluing_weq_aux po_f (pushout_by_cof h₁₂ h₁₃ cof_h₁₂).is_pushout hf₁₂\n (c₁.weq_f' hwu₁) (c₂.weq_f' hwu₂) (c₃.weq_f' hwu₃) hv₂.symm hv₃.symm c₁.hf' c₃.hf'\n (by rw ←Is_pushout.transpose_induced; exact cof_comp (cof_iso _) (x hg₁₂)),\nhave ww : _ := gluing_weq_aux po_g (pushout_by_cof h₁₂ h₁₃ cof_h₁₂).is_pushout hg₁₂\n c₁.hs.2 c₂.hs.2 c₃.hs.2 hw₂.symm hw₃.symm c₁.hs.1 c₃.hs.1\n (by rw ←Is_pushout.transpose_induced; exact cof_comp (cof_iso _) (y hf₁₂).1),\nlet po_h := pushout_by_cof h₁₂ h₁₃ cof_h₁₂ in\nhave wr : is_weq (pushout_of_maps po_h.is_pushout po_g c₁.r c₂.r c₃.r hr₂.symm hr₃.symm), begin\n refine (weq_iff_weq_inv _).mp ww,\n rw ←pushout_of_maps_comp,\n convert pushout_of_maps_id po_g,\n { exact c₁.hsr }, { exact c₂.hsr }, { exact c₃.hsr }\nend,\nbegin\n convert weq_comp wv wr,\n rw ←pushout_of_maps_comp,\n congr,\n { exact c₁.hf'r.symm }, { exact c₂.hf'r.symm}, { exact c₃.hf'r.symm }\nend\n\nend homotopy_theory.cofibrations\n", "meta": {"author": "rwbarton", "repo": "lean-homotopy-theory", "sha": "39e1b4ea1ed1b0eca2f68bc64162dde6a6396dee", "save_path": "github-repos/lean/rwbarton-lean-homotopy-theory", "path": "github-repos/lean/rwbarton-lean-homotopy-theory/lean-homotopy-theory-39e1b4ea1ed1b0eca2f68bc64162dde6a6396dee/src/homotopy_theory/formal/cofibrations/gluing.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3345894545235253, "lm_q2_score": 0.024423087480037995, "lm_q1q2_score": 0.008171707517726253}} {"text": "import Lbar.ext_aux1\n\nnoncomputable theory\n\nuniverses v u u'\n\nopen opposite category_theory category_theory.limits category_theory.preadditive\nopen_locale nnreal zero_object\n\nvariables (r r' : ℝ≥0)\nvariables [fact (0 < r)] [fact (r < r')] [fact (r < 1)]\n\nsection\n\nopen bounded_homotopy_category\n\nvariables (BD : breen_deligne.data)\nvariables (κ κ₂ : ℝ≥0 → ℕ → ℝ≥0)\nvariables [∀ (c : ℝ≥0), BD.suitable (κ c)] [∀ n, fact (monotone (function.swap κ n))]\nvariables [∀ (c : ℝ≥0), BD.suitable (κ₂ c)] [∀ n, fact (monotone (function.swap κ₂ n))]\nvariables (M : ProFiltPseuNormGrpWithTinv₁.{u} r')\nvariables (V : SemiNormedGroup.{u})\n\nlemma QprimeFP_map (c₁ c₂ : ℝ≥0) (h : c₁ ⟶ c₂) :\n (QprimeFP r' BD κ M).map h = of'_hom ((QprimeFP_int r' BD κ _).map h) := rfl\n\ninstance aaahrg (X : Profinite) : seminormed_add_comm_group (locally_constant X V) :=\nlocally_constant.seminormed_add_comm_group\n\ndef V_T_inv (r : ℝ≥0) (V : SemiNormedGroup.{u}) [normed_with_aut r V] : V ⟶ V :=\nnormed_with_aut.T.{u}.inv\n\nvariables [fact (0 < r')] [fact (r' < 1)]\n\nsection\n\nvariables [complete_space V] [separated_space V]\n\nset_option pp.universes true\n\nlemma final_boss_aux₁ (X : Profinite) (x) :\n ((LCC_iso_Cond_of_top_ab_add_equiv.{u} X V).symm) x =\n (LCC_iso_Cond_of_top_ab_equiv X V).symm x := rfl\n\nlemma final_boss_aux₂ [normed_with_aut r V] (X : Profinite) (x : locally_constant X V) :\n((locally_constant.map_hom.{u u u} (V_T_inv r V)).completion)\n (uniform_space.completion.cpkg.{u}.coe x) =\n uniform_space.completion.map (locally_constant.map_hom (V_T_inv r V)) x := rfl\n\n-- should this be a global instance earlier in mathlib?\nlocal attribute [instance]\nabstract_completion.uniform_struct\n\nlemma final_boss_aux₃ [normed_with_aut r V] (X : Profinite) :\n continuous.{u u}\n (λ (x : C(X,V)),\n ((locally_constant.map_hom.{u u u} normed_with_aut.T.{u}.inv).completion)\n (((uniform_space.completion.cpkg.{u}.compare_equiv (locally_constant.pkg.{u} X ↥V)).symm) x)) :=\nbegin\n dsimp [abstract_completion.compare_equiv],\n refine (normed_add_group_hom.continuous _).comp _,\n refine ((locally_constant.pkg X V).uniform_continuous_compare _).continuous,\nend\n\nexample {β : Type*} [uniform_space β] (a : abstract_completion β) : uniform_space a.space :=\nby apply_instance\n\nlemma final_boss_aux₄ [normed_with_aut r V] (X : Profinite) :\n@continuous.{u u} _ _ _ (uniform_space.completion.cpkg.uniform_struct.to_topological_space)\n (λ (x : C(X,V)),\n ((locally_constant.pkg X V).compare\n uniform_space.completion.cpkg.{u}\n {to_fun := (V_T_inv r V) ∘ x.to_fun, continuous_to_fun :=\n (normed_with_aut.T.inv.continuous.comp x.2)})) :=\nbegin\n let e : C(X,V) → C(X,V) := λ e, ⟨(V_T_inv r V) ∘ e,\n (V_T_inv r V).continuous.comp e.2⟩,\n have he : continuous e := continuous_map.continuous_comp\n ((⟨(V_T_inv r V), (V_T_inv r V).continuous⟩ : C(V,V))),\n refine continuous.comp _ he,\n refine ((locally_constant.pkg X V).uniform_continuous_compare _).continuous,\nend\n\nlemma final_boss [normed_with_aut r V] (X : Profinite)\n (x : ((Condensed.of_top_ab.presheaf V).obj (op X))) :\n((locally_constant.map_hom (V_T_inv r V)).completion)\n (((LCC_iso_Cond_of_top_ab_add_equiv X V).symm) x) =\n ((LCC_iso_Cond_of_top_ab_add_equiv X V).symm)\n {to_fun := (normed_with_aut.T.inv) ∘ x.1, continuous_to_fun :=\n (normed_with_aut.T.inv.continuous.comp x.2)} :=\nbegin\n rw final_boss_aux₁,\n rw final_boss_aux₁,\n dsimp only [V_T_inv],\n dsimp only [LCC_iso_Cond_of_top_ab_equiv],\n change C(X,V) at x,\n apply abstract_completion.induction_on (locally_constant.pkg.{u} X ↥V) x,\n { apply is_closed_eq,\n { apply final_boss_aux₃ },\n { apply final_boss_aux₄ } },\n clear x,\n intros x,\n change ((locally_constant.map_hom.{u u u} normed_with_aut.T.{u}.inv).completion)\n ((locally_constant.pkg.{u} X ↥V).compare uniform_space.completion.cpkg.{u}\n ((locally_constant.pkg.{u} X ↥V).coe x)) = _,\n --dsimp [abstract_completion.compare_equiv],\n rw abstract_completion.compare_coe,\n erw final_boss_aux₂,\n erw uniform_space.completion.map_coe,\n let q : C(X,V) :=\n {to_fun := (normed_with_aut.T.{u}.inv) ∘ ((locally_constant.pkg.{u} X ↥V).coe x).to_fun,\n continuous_to_fun := _},\n swap,\n { apply continuous.comp,\n apply normed_add_group_hom.continuous,\n refine ((locally_constant.pkg.{u} X ↥V).coe x).2 },\n have hq : q = (locally_constant.pkg X V).coe\n ((locally_constant.map_hom.{u u u} (V_T_inv.{u} r V)) x),\n { ext, refl },\n\n change _ =\n ((locally_constant.pkg.{u} X ↥V).compare uniform_space.completion.cpkg) q,\n rw hq,\n\n rw abstract_completion.compare_coe,\n\n refl,\n\n apply normed_add_group_hom.uniform_continuous,\nend\n\nend\n\n@[reassoc]\nlemma massive_aux₁ (X Y : Profinite.{u}) (f : X ⟶ Y) :\n (preadditive_yoneda.{u+1 u+2}.obj V.to_Cond).map (freeCond.{u}.map f).op ≫\n (preadditive_yoneda_obj_obj_CondensedSet_to_Condensed_Ab.{u} V.to_Cond X).hom =\n (preadditive_yoneda_obj_obj_CondensedSet_to_Condensed_Ab.{u} V.to_Cond Y).hom ≫\n V.to_Cond.val.map f.op :=\nbegin\n erw preadditive_yoneda_obj_obj_CondensedSet_to_Condensed_Ab_natural',\n refl,\nend\n\nlemma add_equiv.mk_symm {A B : Type*} [add_comm_group A] [add_comm_group B]\n (f : A →+ B) (g : B →+ A) (h1 h2 h3) :\n (add_equiv.mk f g h1 h2 h3).symm =\n add_equiv.mk g f h2 h1 (by { intros x y, apply h1.injective, rw [h3, h2, h2, h2] }) := rfl\n\nlemma add_equiv.mk_symm_apply {A B : Type*} [add_comm_group A] [add_comm_group B]\n (f : A →+ B) (g : B →+ A) (h1 h2 h3) (x : B) :\n (add_equiv.mk f g h1 h2 h3).symm x = g x := rfl\n\nlemma locally_constant.comap_hom_map_hom {X Y V W : Type*}\n [topological_space X] [compact_space X]\n [topological_space Y] [compact_space Y]\n [seminormed_add_comm_group V] [seminormed_add_comm_group W]\n (f : X → Y) (hf : continuous f) (g : normed_add_group_hom V W) (φ : locally_constant Y V) :\n locally_constant.comap_hom f hf (locally_constant.map_hom g φ) =\n ((locally_constant.map_hom g) ∘ (locally_constant.comap_hom f hf)) φ :=\nbegin\n dsimp only [locally_constant.comap_hom_apply, locally_constant.map_hom_apply, function.comp],\n rw locally_constant.comap_map,\n exact hf\nend\n\ninstance (X : Profinite) :\n uniform_space.{u} (locally_constant.{u u} X V) :=\n@pseudo_metric_space.to_uniform_space.{u}\n (@locally_constant.{u u} (@coe_sort.{u+2 u+2} Profinite.{u} (Type u) Profinite.has_coe_to_sort.{u} X)\n (@coe_sort.{u+2 u+2} SemiNormedGroup.{u} (Type u) SemiNormedGroup.has_coe_to_sort.{u} V)\n (Top.topological_space.{u} X.to_CompHaus.to_Top))\n (@seminormed_add_comm_group.to_pseudo_metric_space.{u}\n (@locally_constant.{u u} (@coe_sort.{u+2 u+2} Profinite.{u} (Type u) Profinite.has_coe_to_sort.{u} X)\n (@coe_sort.{u+2 u+2} SemiNormedGroup.{u} (Type u) SemiNormedGroup.has_coe_to_sort.{u} V)\n (Top.topological_space.{u} X.to_CompHaus.to_Top))\n locally_constant.seminormed_add_comm_group)\n\ninstance (X : Profinite) : topological_space ↥(V.to_Cond.val.obj (op X)) :=\n@ulift.topological_space _ (continuous_map.compact_open.{u u})\n\nvariables [complete_space V] [separated_space V]\n\nlemma to_Cond_val_map_apply (X Y : Profinite.{u}) (f : X ⟶ Y) (x) :\n V.to_Cond.val.map f.op x = ⟨continuous_map.comp_right_continuous_map V f x.down⟩ :=\nrfl\n\nlemma to_Cond_val_map (X Y : Profinite.{u}) (f : X ⟶ Y) :\n ⇑(V.to_Cond.val.map f.op) =\n (λ x, ⟨continuous_map.comp_right_continuous_map V f x.down⟩ : ↥(V.to_Cond.val.obj (op Y)) → ↥(V.to_Cond.val.obj (op X))) :=\nby { ext x, rw to_Cond_val_map_apply }\n\nlemma massive_aux₂ (X Y : Profinite.{u}) (f : X ⟶ Y) (x : (V.to_Cond.val.obj (op.{u+2} Y))) :\n uniform_space.completion.map.{u u} (locally_constant.comap_hom.{u u u} f f.continuous)\n ((locally_constant.pkg.{u} Y ↥V).compare uniform_space.completion.cpkg.{u} x.down) =\n ((locally_constant.pkg.{u} X ↥V).compare uniform_space.completion.cpkg.{u})\n ((V.to_Cond.val.map f.op) x).down :=\nbegin\n cases x,\n apply abstract_completion.induction_on (locally_constant.pkg.{u} Y V) x,\n { apply is_closed_eq,\n { apply uniform_space.completion.continuous_map.comp,\n apply (abstract_completion.uniform_continuous_compare _ _).continuous },\n { apply (abstract_completion.uniform_continuous_compare _ _).continuous.comp,\n let φ : C(Y, V) → C(X, V) := _, change continuous φ,\n let ψ := V.to_Cond.val.map f.op, have hψ : φ = ulift.down ∘ ψ ∘ ulift.up := rfl,\n rw hψ, clear hψ,\n refine continuous_induced_dom.comp _,\n refine continuous.comp _ continuous_ulift_up,\n rw [to_Cond_val_map],\n refine continuous.comp _ _, { exact continuous_ulift_up },\n dsimp only [Condensed.of_top_ab, Condensed.of_top_ab.presheaf],\n exact (map_continuous (continuous_map.comp_right_continuous_map ↥V f)).comp continuous_induced_dom, } },\n { intro φ,\n dsimp only,\n simp only [abstract_completion.compare_coe, to_Cond_val_map_apply,\n uniform_space.completion.map],\n rw [abstract_completion.map_coe],\n swap,\n { letI : seminormed_add_comm_group (locally_constant ↥(X.to_CompHaus.to_Top) ↥V),\n { exact locally_constant.seminormed_add_comm_group },\n letI : seminormed_add_comm_group (locally_constant ↥(Y.to_CompHaus.to_Top) ↥V),\n { exact locally_constant.seminormed_add_comm_group },\n exact normed_add_group_hom.uniform_continuous _, },\n have : (continuous_map.comp_right_continuous_map ↥V f) ((locally_constant.pkg Y V).coe φ) =\n (locally_constant.pkg X V).coe _ := _,\n rw [this, abstract_completion.compare_coe],\n ext1,\n erw [locally_constant.coe_comap],\n refl,\n exact f.continuous },\nend\n\nlemma massive_aux (X Y : Profinite.{u}) (f : X ⟶ Y) :\n (preadditive_yoneda_obj_obj_CondensedSet_to_Condensed_Ab.{u} V.to_Cond Y).hom ≫\n Ab.ulift.{u+1 u}.map ((LCC_iso_Cond_of_top_ab.{u} V).inv.app (op.{u+2} Y)) ≫\n (ExtQprime_iso_aux_system_obj_aux'.{u} V Y).hom ≫\n (forget₂.{u+2 u+2 u+1 u+1 u+1} SemiNormedGroup.{u+1} Ab.{u+1}).map\n ((FreeAb.eval.{u+1 u+2} SemiNormedGroup.{u+1}ᵒᵖ).map\n ((CLC.{u+1 u} (SemiNormedGroup.ulift.{u+1 u}.obj V)).right_op.map_FreeAb.map\n ((FreeAb.of_functor.{u+1 u} Profinite.{u}).map f))).unop =\n (preadditive_yoneda.{u+1 u+2}.obj V.to_Cond).map\n ((FreeAb.eval.{u+1 u+2} (Condensed.{u u+1 u+2} Ab.{u+1})).map\n (freeCond.{u}.map_FreeAb.map ((FreeAb.of_functor.{u+1 u} Profinite.{u}).map f))).op ≫\n (preadditive_yoneda_obj_obj_CondensedSet_to_Condensed_Ab.{u} V.to_Cond X).hom ≫\n Ab.ulift.{u+1 u}.map ((LCC_iso_Cond_of_top_ab.{u} V).inv.app (op.{u+2} X)) ≫\n (ExtQprime_iso_aux_system_obj_aux'.{u} V X).hom :=\nbegin\n dsimp only [functor.map_FreeAb, FreeAb.of_functor, FreeAb.eval],\n simp only [free_abelian_group.map_of_apply, free_abelian_group.lift.of, id],\n dsimp only [functor.right_op_map, quiver.hom.op_unop, quiver.hom.unop_op],\n rw massive_aux₁_assoc, congr' 1,\n ext1 x, simp only [comp_apply],\n dsimp only [ExtQprime_iso_aux_system_obj_aux', LCC_iso_Cond_of_top_ab,\n LCC_iso_Cond_of_top_ab_add_equiv, LCC_iso_Cond_of_top_ab_equiv, CLC, LC, functor.comp_map,\n Condensed.of_top_ab],\n simp only [add_equiv.to_fun_eq_coe, normed_add_group_hom.completion_coe_to_fun,\n add_equiv.to_AddCommGroup_iso_hom, add_equiv.coe_to_add_monoid_hom, add_equiv.trans_apply,\n add_equiv.ulift_apply, equiv.to_fun_as_coe, equiv.ulift_apply_2,\n Ab.ulift_map_apply_down, add_equiv.coe_mk, nat_iso.of_components_inv_app,\n add_equiv.to_AddCommGroup_iso, add_equiv.mk_symm,\n SemiNormedGroup.forget₂_Ab_map, normed_add_group_hom.coe_to_add_monoid_hom],\n let F := SemiNormedGroup.Completion.{u+1}.map ((SemiNormedGroup.LocallyConstant.{u+1 u}.obj\n (SemiNormedGroup.ulift.{u+1 u}.obj V)).map f.op),\n let g := _,\n let Z := _,\n change F ((uniform_space.completion.map g) Z) = _,\n change (F ∘ uniform_space.completion.map g) Z = _,\n erw [uniform_space.completion.map_comp],\n rotate,\n { apply normed_add_group_hom.uniform_continuous, },\n { apply normed_add_group_hom.uniform_continuous, },\n conv_lhs\n { dsimp only [function.comp, normed_add_group_hom.coe_to_add_monoid_hom, g,\n SemiNormedGroup.LocallyConstant_obj_map], },\n simp only [locally_constant.comap_hom_map_hom],\n letI : uniform_space.{u} (locally_constant.{u u} ↥(unop.{u+2} (op.{u+2} X)) ↥V) := _,\n erw [← uniform_space.completion.map_comp],\n rotate,\n { apply normed_add_group_hom.uniform_continuous, },\n { apply normed_add_group_hom.uniform_continuous, },\n dsimp only [function.comp, Z, quiver.hom.unop_op],\n congr' 1, clear Z g F,\n exact massive_aux₂ V X Y f x,\nend\n\nlemma massive (X Y : FreeAb Profinite.{u}) (f : X ⟶ Y) :\n (((preadditive_yoneda_obj_obj_CondensedSet_to_Condensed_Ab.{u} V.to_Cond Y.as).hom ≫\n (Condensed_Ab_to_presheaf.{u}.map (Condensed_LCC_iso_of_top_ab.{u} V).inv).app (op.{u+2} Y.as) ≫\n (ExtQprime_iso_aux_system_obj_aux'.{u} V Y.as).hom) ≫\n (𝟙 _)) ≫\n (forget₂.{u+2 u+2 u+1 u+1 u+1} SemiNormedGroup.{u+1} Ab.{u+1}).map\n (((CLC.{u+1 u} (SemiNormedGroup.ulift.{u+1 u}.obj V)).right_op.map_FreeAb ⋙\n FreeAb.eval.{u+1 u+2} SemiNormedGroup.{u+1}ᵒᵖ).map f).unop =\n (preadditive_yoneda.{u+1 u+2}.obj V.to_Cond).map\n ((freeCond.{u}.map_FreeAb ⋙ FreeAb.eval.{u+1 u+2} (Condensed.{u u+1 u+2} Ab.{u+1})).map f).op ≫\n ((preadditive_yoneda_obj_obj_CondensedSet_to_Condensed_Ab.{u} V.to_Cond X.as).hom ≫\n (Condensed_Ab_to_presheaf.{u}.map (Condensed_LCC_iso_of_top_ab.{u} V).inv).app (op.{u+2} X.as) ≫\n (ExtQprime_iso_aux_system_obj_aux'.{u} V X.as).hom) ≫ 𝟙 _ :=\nbegin\n simp only [Condensed_Ab_to_presheaf_map, category.assoc, category.comp_id, functor.comp_map],\n dsimp only [Condensed_LCC_iso_of_top_ab, Sheaf.iso.mk_inv_val,\n iso_whisker_right_inv, whisker_right_app],\n apply free_abelian_group.induction_on f; clear f,\n { simp only [functor.map_zero, unop_zero, comp_zero, op_zero, zero_comp], },\n { apply massive_aux },\n { intros f hf,\n simp only [functor.map_neg, unop_neg, op_neg, comp_neg, neg_comp, hf], },\n { intros f g hf hg,\n simp only [functor.map_add, unop_add, op_add, comp_add, add_comp, hf, hg], },\nend\n\nlemma hom_complex_QprimeFP_nat_iso_aux_system_naturality_in_c (c₁ c₂) (h : c₁ ⟶ c₂) :\n (hom_complex_QprimeFP_nat_iso_aux_system r' BD κ M V c₂).hom ≫\n (category_theory.functor.map _ h.op) =\n (category_theory.functor.map _\n begin\n refine homological_complex.op_functor.map (quiver.hom.op _),\n refine category_theory.functor.map _ h,\n end) ≫ (hom_complex_QprimeFP_nat_iso_aux_system r' BD κ M V c₁).hom :=\nbegin\n ext n : 2,\n have aux : ∀ (n : ℕ), (monotone.{0 0} (function.swap.{1 1 1} κ n)),\n { intro n, exact fact.out _ },\n haveI : fact (κ c₁ n ≤ κ c₂ n) := ⟨aux n h.le⟩,\n have := massive V\n (breen_deligne.FPsystem.X.{u} r' BD ⟨M⟩ κ c₁ n)\n (breen_deligne.FPsystem.X.{u} r' BD ⟨M⟩ κ c₂ n)\n ((breen_deligne.FP2.res.{u} r' _ _ _).app ⟨M⟩),\n exact this\nend\n\nlemma hom_complex_QprimeFP_nat_iso_aux_system_naturality_in_κ (c : (ℝ≥0))\n [∀ (c : ℝ≥0) (n : ℕ), fact (κ₂ c n ≤ κ c n)] :\n (hom_complex_QprimeFP_nat_iso_aux_system r' BD κ M V c).hom ≫\n (whisker_right (aux_system.res _ _ _ _ _ _) _).app _ =\n begin\n refine category_theory.functor.map _ _,\n refine homological_complex.op_functor.map (quiver.hom.op _),\n refine (QprimeFP_nat.ι BD κ₂ κ M).app _,\n end ≫ (hom_complex_QprimeFP_nat_iso_aux_system r' BD κ₂ M V c).hom :=\nbegin\n ext n : 2,\n have := massive V\n (breen_deligne.FPsystem.X.{u} r' BD ⟨M⟩ κ₂ c n)\n (breen_deligne.FPsystem.X.{u} r' BD ⟨M⟩ κ c n)\n ((breen_deligne.FP2.res.{u} r' _ _ _).app ⟨M⟩),\n exact this\nend\n\nlemma hom_complex_QprimeFP_nat_iso_aux_system_naturality_in_Tinv (c : ℝ≥0)\n [∀ (c : ℝ≥0) (n : ℕ), fact (κ₂ c n ≤ r' * κ c n)] :\n (hom_complex_QprimeFP_nat_iso_aux_system r' BD κ M V c).hom ≫\n (whisker_right\n (aux_system.Tinv _ _ _ _ _ _) _).app _ =\n begin\n refine category_theory.functor.map _ _,\n refine homological_complex.op_functor.map (quiver.hom.op _),\n refine (QprimeFP_nat.Tinv BD κ₂ κ M).app _,\n end\n ≫ (hom_complex_QprimeFP_nat_iso_aux_system r' BD κ₂ M V c).hom :=\nbegin\n ext n : 2,\n have := massive V\n (breen_deligne.FPsystem.X.{u} r' BD ⟨M⟩ κ₂ c n)\n (breen_deligne.FPsystem.X.{u} r' BD ⟨M⟩ κ c n)\n (((breen_deligne.FPsystem.Tinv.{u} r' BD ⟨M⟩ κ₂ κ).app c).f n),\n exact this,\nend\n\n\n\ndef to_Cond_T_inv (r : ℝ≥0) (V : SemiNormedGroup.{u}) [normed_with_aut r V] : V.to_Cond ⟶ V.to_Cond :=\n(Condensed.of_top_ab_map.{u} (normed_add_group_hom.to_add_monoid_hom.{u u} normed_with_aut.T.{u}.inv)\n (normed_add_group_hom.continuous _))\n\nlemma uniform_space.completion.map_comp'\n {α β γ : Type*} [uniform_space α] [uniform_space β] [uniform_space γ]\n {g : β → γ} {f : α → β}\n (hg : uniform_continuous g) (hf : uniform_continuous f) (x) :\n uniform_space.completion.map g (uniform_space.completion.map f x) =\n uniform_space.completion.map (g ∘ f) x :=\nbegin\n rw [← uniform_space.completion.map_comp hg hf],\nend\n\nlemma hom_complex_QprimeFP_nat_iso_aux_system_naturality_in_T_inv_aux_helper\n (r : ℝ≥0) (V : SemiNormedGroup.{u}) [normed_with_aut r V] [complete_space V] [separated_space V]\n (X : Profinite.{u}) :\n (ExtQprime_iso_aux_system_obj_aux' V X).hom ≫\n category_theory.functor.map _\n (SemiNormedGroup.Completion.map\n (nat_trans.app\n (SemiNormedGroup.LocallyConstant.map\n (category_theory.functor.map _ $ V_T_inv _ _)) _)) =\n Ab.ulift.map\n (category_theory.functor.map _ $\n category_theory.functor.map _ $\n nat_trans.app\n (SemiNormedGroup.LocallyConstant.map $ V_T_inv _ _) _) ≫\n (ExtQprime_iso_aux_system_obj_aux' V X).hom\n :=\nbegin\n ext1 ⟨f⟩,\n simp only [comp_apply],\n dsimp only [ExtQprime_iso_aux_system_obj_aux', add_equiv.to_AddCommGroup_iso,\n add_equiv.coe_to_add_monoid_hom, add_equiv.trans_apply],\n simp only [add_equiv.to_fun_eq_coe, SemiNormedGroup.LocallyConstant_map_app, SemiNormedGroup.Completion_map,\n normed_add_group_hom.completion_coe_to_fun, add_equiv.ulift_apply, equiv.to_fun_as_coe, equiv.ulift_apply_2,\n add_equiv.coe_mk, Ab.ulift_map_apply_down, SemiNormedGroup.forget₂_Ab_map,\n normed_add_group_hom.coe_to_add_monoid_hom],\n rw uniform_space.completion.map_comp',\n rotate,\n { apply normed_add_group_hom.uniform_continuous },\n { apply normed_add_group_hom.uniform_continuous },\n rw uniform_space.completion.map_comp',\n rotate,\n { apply normed_add_group_hom.uniform_continuous },\n { apply normed_add_group_hom.uniform_continuous },\n refl\nend\n\n\n\nlemma another_aux_lemma [normed_with_aut r V] (X : Profinite) :\n (preadditive_yoneda_obj_obj_CondensedSet_to_Condensed_Ab V.to_Cond X).hom\n ≫ (Condensed_Ab_to_presheaf.map_iso (Condensed_LCC_iso_of_top_ab V)).inv.app (op X)\n ≫\n begin\n refine nat_trans.app _ _,\n refine Condensed_Ab_to_presheaf.map _,\n refine Sheaf.hom.mk _,\n dsimp [Condensed_LCC],\n refine whisker_right _ _,\n refine whisker_right _ _,\n refine SemiNormedGroup.LCC.map _,\n exact V_T_inv r V,\n end =\n (preadditive_yoneda.map\n (to_Cond_T_inv r V)).app _ ≫\n (preadditive_yoneda_obj_obj_CondensedSet_to_Condensed_Ab V.to_Cond X).hom ≫\n (Condensed_Ab_to_presheaf.map_iso (Condensed_LCC_iso_of_top_ab V)).inv.app _ :=\nbegin\n have := preadditive_yoneda_obj_obj_CondensedSet_to_Condensed_Ab_natural\n (to_Cond_T_inv r V) X,\n erw ← reassoc_of this,\n congr' 1,\n dsimp only [Condensed_Ab_to_presheaf, functor.map_iso_inv, nat_iso.app_inv,\n Sheaf_to_presheaf_map, id, whisker_right_app, SemiNormedGroup.LCC,\n curry, uncurry, curry_obj, functor.comp_map],\n simp only [category_theory.functor.map_id, category.comp_id],\n rw ← nat_trans.comp_app,\n rw ← Sheaf.hom.comp_val, -- how to make those commute?\n ext ⟨x⟩,\n dsimp only [Condensed_LCC_iso_of_top_ab, Sheaf.iso.mk, iso_whisker_right, to_Cond_T_inv,\n Ab.ulift],\n simp only [comp_apply],\n dsimp [Condensed.of_top_ab_map],\n simp only [comp_apply],\n dsimp [LCC_iso_Cond_of_top_ab, forget₂, has_forget₂.forget₂],\n apply final_boss,\nend\n\nlemma hom_complex_QprimeFP_nat_iso_aux_system_naturality_in_T_inv_aux (c : ℝ≥0)\n [normed_with_aut r V] (n : ℕ) (t) :\n((forget₂.{u+2 u+2 u+1 u+1 u+1} SemiNormedGroup.{u+1} Ab.{u+1}).map\n (((aux_system.T_inv.{u u+1} r r' BD ⟨M⟩ (SemiNormedGroup.ulift.{u+1 u}.obj V) κ).app\n (op.{1} c)).f n))\n ((((ExtQprime_iso_aux_system_obj_aux.{u} V).hom.app\n (((breen_deligne.FPsystem.{u} r' BD ⟨M⟩ κ).obj c).X n)).unop) t) =\n (((ExtQprime_iso_aux_system_obj_aux.{u} V).hom.app\n (((breen_deligne.FPsystem.{u} r' BD ⟨M⟩ κ).obj c).X n)).unop)\n (t ≫ to_Cond_T_inv.{u} r V) :=\nbegin\n /-\n Note: This should reduce to some calcuation with the sheafification adjunction,\n as well as something about completion/ulift compatibiity.\n If we can reduce this to such statements, we will be in pretty good shape.\n -/\n /- This code block is pretty slow.\n dsimp [ExtQprime_iso_aux_system_obj_aux, ExtQprime_iso_aux_system_obj_aux'],\n simp only [comp_apply],\n dsimp [forget₂, has_forget₂.forget₂, aux_system.T_inv,\n Condensed_LCC_iso_of_top_ab, LCC_iso_Cond_of_top_ab],\n rw nat_iso.of_components_inv_app,\n dsimp only [unop_op],\n -/\n dsimp only [forget₂, has_forget₂.forget₂, ExtQprime_iso_aux_system_obj_aux,\n nat_iso.of_components_hom_app, id, iso.op, iso.trans_hom, iso.symm,\n nat_iso.app_inv, aux_system.T_inv, quiver.hom.op_unop, quiver.hom.unop_op,\n homological_complex.unop],\n simp only [comp_apply],\n let X : Profinite := (((breen_deligne.FPsystem r' BD ⟨M⟩ κ).obj c).X n).as,\n have := preadditive_yoneda_obj_obj_CondensedSet_to_Condensed_Ab_natural\n (to_Cond_T_inv r V) X,\n apply_fun (λ e, e t) at this,\n erw this, clear this,\n simp only [comp_apply],\n dsimp only [SemiNormedGroup.LocallyConstant],\n have := hom_complex_QprimeFP_nat_iso_aux_system_naturality_in_T_inv_aux_helper r V X,\n let s := ((Condensed_Ab_to_presheaf.map_iso (Condensed_LCC_iso_of_top_ab V)).inv.app (op X))\n (((preadditive_yoneda_obj_obj_CondensedSet_to_Condensed_Ab V.to_Cond X).hom)\n (t)),\n apply_fun (λ e, e s) at this,\n erw this, clear this,\n simp only [comp_apply],\n congr' 1, dsimp only [s],\n simp only [← comp_apply],\n congr' 1,\n simp only [category.assoc],\n erw ← another_aux_lemma r V X,\n congr' 2,\n ext1 ⟨x⟩, dsimp only [Ab.ulift, Condensed_Ab_to_presheaf, whisker_right_app,\n Sheaf_to_presheaf],\n ext1,\n dsimp,\n congr' 2,\n dsimp only [SemiNormedGroup.LCC, curry, curry_obj, functor.comp_map, uncurry],\n simp only [category_theory.functor.map_id, category.comp_id],\n refl,\nend\n\n\nlemma hom_complex_QprimeFP_nat_iso_aux_system_naturality_in_T_inv (c : ℝ≥0)\n [normed_with_aut r V] :\n(hom_complex_QprimeFP_nat_iso_aux_system.{u} r' BD κ M V c).hom ≫\n ((forget₂.{u+2 u+2 u+1 u+1 u+1} SemiNormedGroup.{u+1} Ab.{u+1}).map_homological_complex\n (complex_shape.up.{0} ℕ)).map (nat_trans.app\n ((aux_system.T_inv.{u u+1} r r' BD ⟨M⟩ (SemiNormedGroup.ulift.{u+1 u}.obj V) κ)) _) =\n begin\n let e := preadditive_yoneda.map (to_Cond_T_inv r V),\n let e' := nat_trans.map_homological_complex e (complex_shape.down ℕ).symm,\n let Q := ((QprimeFP_nat r' BD κ M).obj c).op,\n exact e'.app Q,\n end ≫\n (hom_complex_QprimeFP_nat_iso_aux_system.{u} r' BD κ M V (c)).hom :=\nbegin\n ext n : 2, ext1 t,\n dsimp [hom_complex_QprimeFP_nat_iso_aux_system],\n simp only [comp_apply],\n dsimp [nat_iso.map_homological_complex, forget₂_unop],\n erw id_apply, erw id_apply,\n erw [functor.map_homological_complex_map_f],\n apply hom_complex_QprimeFP_nat_iso_aux_system_naturality_in_T_inv_aux,\nend\n\nnamespace ExtQprime_iso_aux_system_obj_naturality_setup\n\n/-\nlemma aux₁ (c₁ c₂ : ℝ≥0) (h : c₁ ⟶ c₂) :\nhomological_complex.unop_functor.{u+2 u+1 0}.map\n (((preadditive_yoneda_obj.{u+1 u+2} V.to_Cond ⋙\n forget₂.{u+2 u+2 u+1 u+1 u+1} (Module.{u+1 u+1} (End.{u+1 u+2} V.to_Cond))\n AddCommGroup.{u+1}).right_op.map_homological_complex\n (complex_shape.up.{0} ℤ)).map\n ((homological_complex.embed.{0 0 u+2 u+1} complex_shape.embedding.nat_down_int_up).map\n ((QprimeFP_nat.{u} r' BD κ M).map h))).op ≫\n homological_complex.unop_functor.{u+2 u+1 0}.map\n ((map_homological_complex_embed.{u+2 u+2 u+1 u+1}\n (preadditive_yoneda_obj.{u+1 u+2} V.to_Cond ⋙\n forget₂.{u+2 u+2 u+1 u+1 u+1} (Module.{u+1 u+1} (End.{u+1 u+2} V.to_Cond))\n AddCommGroup.{u+1}).right_op).inv.app\n ((QprimeFP_nat.{u} r' BD κ M).obj c₁)).op ≫\n embed_unop.{u+2 u+1}.hom.app\n (op.{u+3}\n (((preadditive_yoneda_obj.{u+1 u+2} V.to_Cond ⋙\n forget₂.{u+2 u+2 u+1 u+1 u+1} (Module.{u+1 u+1} (End.{u+1 u+2} V.to_Cond))\n Ab.{u+1}).right_op.map_homological_complex\n (complex_shape.down.{0} ℕ)).obj\n ((QprimeFP_nat.{u} r' BD κ M).obj c₁))) =\n begin\n dsimp,\n let e := (QprimeFP_nat r' BD κ M).map h,\n let e₁ := ((preadditive_yoneda_obj.{u+1 u+2} V.to_Cond ⋙\n forget₂.{u+2 u+2 u+1 u+1 u+1} (Module.{u+1 u+1} (End.{u+1 u+2} V.to_Cond))\n Ab.{u+1}).right_op.map_homological_complex\n (complex_shape.down.{0} ℕ)).map e,\n let e₂ := homological_complex.unop_functor.map e₁.op,\n refine _ ≫\n (homological_complex.embed.{0 0 u+2 u+1} complex_shape.embedding.nat_up_int_down).map\n e₂,\n refine homological_complex.unop_functor.{u+2 u+1 0}.map\n ((map_homological_complex_embed.{u+2 u+2 u+1 u+1}\n (preadditive_yoneda_obj.{u+1 u+2} V.to_Cond ⋙\n forget₂.{u+2 u+2 u+1 u+1 u+1} (Module.{u+1 u+1} (End.{u+1 u+2} V.to_Cond))\n AddCommGroup.{u+1}).right_op).inv.app\n ((QprimeFP_nat.{u} r' BD κ M).obj c₂)).op ≫\n embed_unop.{u+2 u+1}.hom.app\n (op.{u+3}\n (((preadditive_yoneda_obj.{u+1 u+2} V.to_Cond ⋙\n forget₂.{u+2 u+2 u+1 u+1 u+1} (Module.{u+1 u+1} (End.{u+1 u+2} V.to_Cond))\n Ab.{u+1}).right_op.map_homological_complex\n (complex_shape.down.{0} ℕ)).obj\n ((QprimeFP_nat.{u} r' BD κ M).obj c₂)))\n end := admit\n\ndef F : ℝ≥0 ⥤\n (homological_complex.{u+1 u+2 0} AddCommGroup.{u+1} (complex_shape.down.{0} ℕ).symm)ᵒᵖ :=\nQprimeFP_nat.{u} r' BD κ M ⋙\n (preadditive_yoneda_obj.{u+1 u+2} V.to_Cond ⋙\n forget₂.{u+2 u+2 u+1 u+1 u+1} (Module.{u+1 u+1} (End.{u+1 u+2} V.to_Cond))\n AddCommGroup.{u+1}).right_op.map_homological_complex\n (complex_shape.down.{0} ℕ) ⋙ homological_complex.unop_functor.right_op\n\n@[reassoc]\nlemma naturality_helper {c₁ c₂ : ℝ≥0} (h : c₁ ⟶ c₂) (n : ℕ) (w1 w2) :\n (homological_complex.homology_embed_nat_iso.{0 0 u+2 u+1} Ab.{u+1} complex_shape.embedding.nat_up_int_down\n nat_up_int_down_c_iff n (-↑n) w1).hom.app\n (((preadditive_yoneda.{u+1 u+2}.obj\n V.to_Cond).right_op.map_homological_complex (complex_shape.down.{0} ℕ)).obj\n ((QprimeFP_nat.{u} r' BD κ M).obj c₂)).unop ≫\n (homology_functor _ _ _).map\n (homological_complex.map_unop _ _ $\n category_theory.functor.map _ $ category_theory.functor.map _ h) =\n category_theory.functor.map _\n (homological_complex.map_unop _ _ $\n category_theory.functor.map _ $ category_theory.functor.map _ h) ≫\n (homological_complex.homology_embed_nat_iso.{0 0 u+2 u+1} Ab.{u+1} complex_shape.embedding.nat_up_int_down\n nat_up_int_down_c_iff n (-↑n) w2).hom.app\n (((preadditive_yoneda.{u+1 u+2}.obj\n V.to_Cond).right_op.map_homological_complex (complex_shape.down.{0} ℕ)).obj\n ((QprimeFP_nat.{u} r' BD κ M).obj c₁)).unop :=\nadmit\n-/\n\nlemma aux₁ (c₁ c₂ : ℝ≥0) (h : c₁ ⟶ c₂) (n : ℕ) :\n (homology_functor.{u+1 u+2 0} Ab.{u+1} (complex_shape.up.{0} ℕ) n).map\n (hom_complex_QprimeFP_nat_iso_aux_system.{u} r' BD κ M V c₂).hom ≫\n (homology_functor.{u+1 u+2 0} Ab.{u+1} (complex_shape.up.{0} ℕ) n).map\n ((aux_system.{u u+1} r' BD ⟨M⟩ (SemiNormedGroup.ulift.{u+1 u}.obj V) κ).to_Ab.map h.op) =\n (homology_functor _ _ _).map\n (category_theory.functor.map _\n (homological_complex.op_functor.map ((QprimeFP_nat r' BD κ M).map h).op)) ≫\n (homology_functor.{u+1 u+2 0} Ab.{u+1} (complex_shape.up.{0} ℕ) n).map\n (hom_complex_QprimeFP_nat_iso_aux_system.{u} r' BD κ M V c₁).hom :=\nbegin\n rw [← functor.map_comp, ← functor.map_comp],\n congr' 1,\n erw ← hom_complex_QprimeFP_nat_iso_aux_system_naturality_in_c,\nend\n\nlemma aux₂ (c₁ c₂ : ℝ≥0) (h : c₁ ⟶ c₂) (n : ℕ) :\n (homological_complex.homology_embed_nat_iso.{0 0 u+2 u+1} Ab.{u+1}\n complex_shape.embedding.nat_up_int_down n (-↑n) (by { cases n; refl})).hom.app\n (hom_complex_nat.{u} ((QprimeFP_nat.{u} r' BD κ M).obj c₂) V.to_Cond) ≫\n (homology_functor.{u+1 u+2 0} Ab.{u+1} (complex_shape.up.{0} ℕ) n).map\n (((preadditive_yoneda.{u+1 u+2}.obj V.to_Cond).map_homological_complex\n (complex_shape.down.{0} ℕ).symm).map (homological_complex.op_functor.{u+2 u+1 0}.map\n ((QprimeFP_nat.{u} r' BD κ M).map h).op)) =\n (homological_complex.embed.{0 0 u+2 u+1} complex_shape.embedding.nat_up_int_down ⋙\n homology_functor.{u+1 u+2 0} Ab.{u+1} (complex_shape.down.{0} ℤ) (-↑n)).map\n (category_theory.functor.map _\n (homological_complex.op_functor.map ((QprimeFP_nat r' BD κ M).map h).op)) ≫\n (homological_complex.homology_embed_nat_iso.{0 0 u+2 u+1} Ab.{u+1}\n complex_shape.embedding.nat_up_int_down n (-↑n) (by { cases n; refl})).hom.app\n (hom_complex_nat.{u} ((QprimeFP_nat.{u} r' BD κ M).obj c₁) V.to_Cond) :=\nbegin\n erw nat_trans.naturality,\nend\n\n\nlemma aux₃ (c₁ c₂ : ℝ≥0) (h : c₁ ⟶ c₂) (n : ℕ) :\n (homology_functor.{u+1 u+2 0} Ab.{u+1} (complex_shape.up.{0} ℤ).symm (-↑n)).map\n (embed_hom_complex_nat_iso.{u} ((QprimeFP_nat.{u} r' BD κ M).obj c₂) V.to_Cond).hom ≫\n (homological_complex.embed.{0 0 u+2 u+1} complex_shape.embedding.nat_up_int_down ⋙\n homology_functor.{u+1 u+2 0} Ab.{u+1} (complex_shape.down.{0} ℤ) (-↑n)).map\n (((preadditive_yoneda.{u+1 u+2}.obj V.to_Cond).map_homological_complex\n (complex_shape.down.{0} ℕ).symm).map (homological_complex.op_functor.{u+2 u+1 0}.map\n ((QprimeFP_nat.{u} r' BD κ M).map h).op))\n =\n ((homology_functor.{u+1 u+2 0} AddCommGroup.{u+1}\n (complex_shape.up.{0} ℤ).symm (-↑n)).op.map\n (homological_complex.unop_functor.{u+2 u+1 0}.right_op.map\n (((preadditive_yoneda.{u+1 u+2}.obj V.to_Cond).right_op.map_homological_complex\n (complex_shape.up.{0} ℤ)).map ((QprimeFP_int.{u} r' BD κ M).map h)))).unop ≫\n (homology_functor.{u+1 u+2 0} Ab.{u+1} (complex_shape.up.{0} ℤ).symm (-↑n)).map\n (embed_hom_complex_nat_iso.{u} ((QprimeFP_nat.{u} r' BD κ M).obj c₁) V.to_Cond).hom\n :=\nbegin\n dsimp only [functor.op_map, functor.comp_map],\n erw [← functor.map_comp],\n erw [← functor.map_comp],\n congr' 1,\n ext ((_ | k) | k ) : 2,\n { refine (category.id_comp _).trans (category.comp_id _).symm },\n { apply is_zero.eq_of_tgt,\n exact is_zero_zero _ },\n { refine (category.id_comp _).trans (category.comp_id _).symm },\nend\n/-\nlemma naturality_helper {c₂ : ℝ≥0} (n : ℕ) :\n (homology_functor.{u+1 u+2 0} Ab.{u+1} (complex_shape.up.{0} ℤ).symm (-↑n)).map\n (embed_hom_complex_nat_iso.{u} ((QprimeFP_nat.{u} r' BD κ M).obj c₂) V.to_Cond).hom ≫\n (homological_complex.homology_embed_nat_iso.{0 0 u+2 u+1} Ab.{u+1}\n complex_shape.embedding.nat_up_int_down nat_up_int_down_c_iff n (-↑n) (by { cases n; refl})).hom.app\n (hom_complex_nat.{u} ((QprimeFP_nat.{u} r' BD κ M).obj c₂) V.to_Cond) =\n _\n-/\n\nend ExtQprime_iso_aux_system_obj_naturality_setup\n\nlemma QprimeFP_acyclic (c) (k i : ℤ) (hi : 0 < i) :\n is_zero (((Ext' i).obj (op (((QprimeFP_int.{u} r' BD κ M).obj c).X k))).obj V.to_Cond) :=\nbegin\n rcases k with ((_|k)|k),\n { apply free_acyclic, exact hi },\n { rw [← functor.flip_obj_obj], refine functor.map_is_zero _ _, refine (is_zero_zero _).op, },\n { apply free_acyclic, exact hi },\nend\n\nlemma ExtQprime_iso_aux_system_obj_natrality (c₁ c₂ : ℝ≥0) (h : c₁ ⟶ c₂) (n : ℕ) :\n (ExtQprime_iso_aux_system_obj r' BD κ M V c₂ n).hom ≫\n (homology_functor _ _ _).map\n ((system_of_complexes.to_Ab _).map h.op) =\n ((Ext n).map ((QprimeFP r' BD κ _).map h).op).app _ ≫\n (ExtQprime_iso_aux_system_obj r' BD κ M V c₁ n).hom :=\nbegin\n dsimp only [ExtQprime_iso_aux_system_obj,\n iso.trans_hom, id, functor.map_iso_hom],\n haveI : ((homotopy_category.quotient.{u+1 u+2 0}\n (Condensed.{u u+1 u+2} Ab.{u+1}) (complex_shape.up.{0} ℤ)).obj\n ((QprimeFP_int.{u} r' BD κ M).obj c₁)).is_bounded_above :=\n chain_complex.is_bounded_above _,\n haveI : ((homotopy_category.quotient.{u+1 u+2 0}\n (Condensed.{u u+1 u+2} Ab.{u+1}) (complex_shape.up.{0} ℤ)).obj\n ((QprimeFP_int.{u} r' BD κ M).obj c₂)).is_bounded_above :=\n chain_complex.is_bounded_above _,\n have := Ext_compute_with_acyclic_naturality\n ((QprimeFP_int.{u} r' BD κ M).obj c₁)\n ((QprimeFP_int.{u} r' BD κ M).obj c₂)\n V.to_Cond _ _\n ((QprimeFP_int.{u} r' BD κ M).map h) n,\n rotate,\n { intros k i hi, apply QprimeFP_acyclic, exact hi },\n { intros k i hi, apply QprimeFP_acyclic, exact hi },\n dsimp only [functor.comp_map] at this,\n erw reassoc_of this, clear this,\n simp only [category.assoc, nat_iso.app_hom],\n congr' 1,\n rw ExtQprime_iso_aux_system_obj_naturality_setup.aux₁ r' BD κ M V c₁ c₂ h n,\n simp only [← category.assoc], congr' 1,\n simp only [category.assoc],\n rw ExtQprime_iso_aux_system_obj_naturality_setup.aux₂ r' BD κ M V c₁ c₂ h n,\n simp only [← category.assoc], congr' 1,\n\n exact ExtQprime_iso_aux_system_obj_naturality_setup.aux₃ r' BD κ M V c₁ c₂ h n,\n\n --- OLD PROOF FROM HERE\n --have := ExtQprime_iso_aux_system_obj_naturality_setup.naturality_helper r' BD κ\n -- M V h n _ _,\n --simp only [category.assoc, functor.map_comp],\n --slice_rhs 3 4\n --{ erw ← this },\n\n /-\n dsimp only [QprimeFP_int],\n congr' 1,\n dsimp only [nat_iso.app_hom],\n simp only [functor.map_comp, functor.comp_map, nat_trans.naturality,\n nat_trans.naturality_assoc],\n dsimp only [functor.op_map, quiver.hom.unop_op, functor.right_op_map],\n simp only [← functor.map_comp, ← functor.map_comp_assoc, category.assoc],\n dsimp [-homology_functor_map],\n rw ExtQprime_iso_aux_system_obj_naturality_setup.aux₁,\n dsimp [-homology_functor_map],\n simp only [functor.map_comp, functor.map_comp_assoc,\n category.assoc, nat_trans.naturality_assoc],\n congr' 2,\n dsimp [-homology_functor_map],\n dsimp only [← functor.comp_map, ← functor.comp_obj],\n --erw nat_trans.naturality_assoc,\n --refine congr_arg2 _ _ (congr_arg2 _ rfl _),\n\n --congr' 1,\n --refl,\n admit\n\n -/\nend\n\ndef ExtQprime_iso_aux_system (n : ℕ) :\n (QprimeFP r' BD κ M).op ⋙ (Ext n).flip.obj ((single _ 0).obj V.to_Cond) ≅\n aux_system r' BD ⟨M⟩ (SemiNormedGroup.ulift.{u+1}.obj V) κ ⋙\n (forget₂ _ Ab).map_homological_complex _ ⋙ homology_functor _ _ n :=\nnat_iso.of_components (λ c, ExtQprime_iso_aux_system_obj r' BD κ M V (unop c) n)\nbegin\n intros c₁ c₂ h,\n dsimp [-homology_functor_map],\n rw ← ExtQprime_iso_aux_system_obj_natrality,\n refl,\nend\n\n/-- The `Tinv` map induced by `M` -/\ndef ExtQprime.Tinv\n [∀ c n, fact (κ₂ c n ≤ κ c n)] [∀ c n, fact (κ₂ c n ≤ r' * κ c n)]\n (n : ℤ) :\n (QprimeFP r' BD κ M).op ⋙ (Ext n).flip.obj ((single _ 0).obj V.to_Cond) ⟶\n (QprimeFP r' BD κ₂ M).op ⋙ (Ext n).flip.obj ((single _ 0).obj V.to_Cond) :=\nwhisker_right (nat_trans.op $ QprimeFP.Tinv BD _ _ M) _\n\n/-- The `T_inv` map induced by `V` -/\ndef ExtQprime.T_inv [normed_with_aut r V]\n [∀ c n, fact (κ₂ c n ≤ κ c n)] [∀ c n, fact (κ₂ c n ≤ r' * κ c n)]\n (n : ℤ) :\n (QprimeFP r' BD κ M).op ⋙ (Ext n).flip.obj ((single _ 0).obj V.to_Cond) ⟶\n (QprimeFP r' BD κ₂ M).op ⋙ (Ext n).flip.obj ((single _ 0).obj V.to_Cond) :=\nwhisker_right (nat_trans.op $ QprimeFP.ι BD _ _ M) _ ≫ whisker_left _ ((Ext n).flip.map $ (single _ _).map $\n (Condensed.of_top_ab_map (normed_with_aut.T.inv).to_add_monoid_hom\n (normed_add_group_hom.continuous _)))\n\ndef ExtQprime.Tinv2 [normed_with_aut r V]\n [∀ c n, fact (κ₂ c n ≤ κ c n)] [∀ c n, fact (κ₂ c n ≤ r' * κ c n)]\n (n : ℤ) :\n (QprimeFP r' BD κ M).op ⋙ (Ext n).flip.obj ((single _ 0).obj V.to_Cond) ⟶\n (QprimeFP r' BD κ₂ M).op ⋙ (Ext n).flip.obj ((single _ 0).obj V.to_Cond) :=\nExtQprime.Tinv r' BD κ κ₂ M V n - ExtQprime.T_inv r r' BD κ κ₂ M V n\n\nnamespace ExtQprime_iso_aux_system_comm_Tinv_setup\n\nvariables (c : (ℝ≥0)ᵒᵖ) (n : ℕ)\n [∀ (c : ℝ≥0) (n : ℕ), fact (κ₂ c n ≤ r' * κ c n)]\n\nlemma aux₁ :\n(homology_functor.{u+1 u+2 0} Ab.{u+1} (complex_shape.up.{0} ℕ) n).map\n (hom_complex_QprimeFP_nat_iso_aux_system.{u} r' BD κ M V (unop.{1} c)).hom ≫\n ((forget₂.{u+2 u+2 u+1 u+1 u+1} SemiNormedGroup.{u+1} Ab.{u+1}).map_homological_complex\n (complex_shape.up.{0} ℕ) ⋙\n homology_functor.{u+1 u+2 0} Ab.{u+1} (complex_shape.up.{0} ℕ) n).map\n ((aux_system.Tinv.{u u+1} r' BD ⟨M⟩ (SemiNormedGroup.ulift.{u+1 u}.obj V) κ₂ κ).app c) =\n (homology_functor _ _ _).map\n (category_theory.functor.map _\n (homological_complex.op_functor.map (quiver.hom.op $\n (QprimeFP_nat.Tinv BD κ₂ κ M).app _))) ≫\n (homology_functor.{u+1 u+2 0} Ab.{u+1} (complex_shape.up.{0} ℕ) n).map\n (hom_complex_QprimeFP_nat_iso_aux_system.{u} r' BD κ₂ M V (unop.{1} c)).hom :=\nbegin\n simp only [← functor.map_comp, functor.comp_map], congr' 1,\n apply hom_complex_QprimeFP_nat_iso_aux_system_naturality_in_Tinv,\nend\n\nlemma aux₂ :\n(homology_functor.{u+1 u+2 0} Ab.{u+1} (complex_shape.up.{0} ℤ).symm (-↑n)).map\n (embed_hom_complex_nat_iso.{u} ((QprimeFP_nat.{u} r' BD κ M).obj (unop.{1} c)) V.to_Cond).hom ≫\n (homological_complex.embed.{0 0 u+2 u+1} complex_shape.embedding.nat_up_int_down ⋙\n homology_functor.{u+1 u+2 0} Ab.{u+1} (complex_shape.down.{0} ℤ) (-↑n)).map\n (((preadditive_yoneda.{u+1 u+2}.obj V.to_Cond).map_homological_complex (complex_shape.down.{0} ℕ).symm).map\n (homological_complex.op_functor.{u+2 u+1 0}.map ((QprimeFP_nat.Tinv.{u} BD κ₂ κ M).app (unop.{1} c)).op)) =\n (((preadditive_yoneda.{u+1 u+2}.obj V.to_Cond).right_op.map_homological_complex (complex_shape.up.{0} ℤ) ⋙\n homological_complex.unop_functor.{u+2 u+1 0}.right_op ⋙\n (homology_functor.{u+1 u+2 0} AddCommGroup.{u+1} (complex_shape.up.{0} ℤ).symm (-↑n)).op).map\n ((QprimeFP_int.Tinv.{u} BD κ₂ κ M).app (unop.{1} c))).unop ≫\n (homology_functor.{u+1 u+2 0} Ab.{u+1} (complex_shape.up.{0} ℤ).symm (-↑n)).map\n (embed_hom_complex_nat_iso.{u} ((QprimeFP_nat.{u} r' BD κ₂ M).obj (unop.{1} c)) V.to_Cond).hom :=\nbegin\n dsimp only [functor.op_map, functor.comp_map],\n erw [← functor.map_comp],\n erw [← functor.map_comp],\n congr' 1,\n ext ((_ | k) | k ) : 2,\n { refine (category.id_comp _).trans (category.comp_id _).symm },\n { apply is_zero.eq_of_tgt,\n exact is_zero_zero _ },\n { refine (category.id_comp _).trans (category.comp_id _).symm },\nend\n\nend ExtQprime_iso_aux_system_comm_Tinv_setup\n\nlemma ExtQprime_iso_aux_system_comm_Tinv\n [∀ c n, fact (κ₂ c n ≤ κ c n)] [∀ c n, fact (κ₂ c n ≤ r' * κ c n)] (n : ℕ) :\n (ExtQprime_iso_aux_system r' BD κ M V n).hom ≫\n whisker_right (aux_system.Tinv.{u} r' BD ⟨M⟩ (SemiNormedGroup.ulift.{u+1}.obj V) κ₂ κ)\n ((forget₂ _ _).map_homological_complex _ ⋙ homology_functor Ab.{u+1} (complex_shape.up ℕ) n) =\n ExtQprime.Tinv r' BD κ κ₂ M V n ≫\n (ExtQprime_iso_aux_system r' BD κ₂ M V n).hom :=\nbegin\n ext c : 2,\n dsimp only [ExtQprime_iso_aux_system_obj,\n ExtQprime_iso_aux_system,\n iso.trans_hom, id, functor.map_iso_hom, nat_iso.of_components_hom_app,\n nat_trans.comp_app],\n haveI : ((homotopy_category.quotient.{u+1 u+2 0} (Condensed.{u u+1 u+2} Ab.{u+1}) (complex_shape.up.{0} ℤ)).obj\n ((QprimeFP_int.{u} r' BD κ M).obj (unop.{1} c))).is_bounded_above :=\n chain_complex.is_bounded_above _,\n haveI : ((homotopy_category.quotient.{u+1 u+2 0} (Condensed.{u u+1 u+2} Ab.{u+1}) (complex_shape.up.{0} ℤ)).obj\n ((QprimeFP_int.{u} r' BD κ₂ M).obj (unop.{1} c))).is_bounded_above :=\n chain_complex.is_bounded_above _,\n have := Ext_compute_with_acyclic_naturality\n ((QprimeFP_int.{u} r' BD κ₂ M).obj c.unop)\n ((QprimeFP_int.{u} r' BD κ M).obj c.unop)\n V.to_Cond _ _\n ((QprimeFP_int.Tinv BD κ₂ κ M).app _) n,\n rotate,\n { intros k i hi, apply QprimeFP_acyclic, exact hi },\n { intros k i hi, apply QprimeFP_acyclic, exact hi },\n erw reassoc_of this, clear this, simp only [category.assoc], congr' 1,\n dsimp only [whisker_right_app],\n rw ExtQprime_iso_aux_system_comm_Tinv_setup.aux₁ r' BD κ κ₂ M V c n,\n simp only [← category.assoc], congr' 1, simp only [category.assoc],\n erw ← nat_trans.naturality,\n simp only [← category.assoc], congr' 1,\n exact ExtQprime_iso_aux_system_comm_Tinv_setup.aux₂ r' BD κ κ₂ M V c n,\nend\n\n\n-- lemma ExtQprime_iso_aux_system_comm_T_inv [normed_with_aut r V] (n : ℕ) (c : ℝ≥0ᵒᵖ) :\n-- (ExtQprime_iso_aux_system_obj.{u} r' BD κ₂ M V (unop.{1} c) n).hom ≫\n-- ((forget₂.{u+2 u+2 u+1 u+1 u+1} SemiNormedGroup.{u+1} Ab.{u+1}).map_homological_complex (complex_shape.up.{0} ℕ) ⋙\n-- homology_functor.{u+1 u+2 0} Ab.{u+1} (complex_shape.up.{0} ℕ) n).map\n-- ((aux_system.res.{u u+1} r' BD ⟨M⟩ (SemiNormedGroup.ulift.{u+1 u}.obj V) κ₂ κ).app c) =\n-- ((Ext.{u+1 u+2} ↑n).flip.map\n-- ((single.{u+1 u+2} (Condensed.{u u+1 u+2} Ab.{u+1}) 0).map\n-- (Condensed.of_top_ab_map.{u} (normed_add_group_hom.to_add_monoid_hom.{u u} normed_with_aut.T.{u}.inv) _))).app\n-- ((QprimeFP.{u} r' BD κ₂ M).op.obj c) ≫\n-- (ExtQprime_iso_aux_system_obj.{u} r' BD κ₂ M V (unop.{1} c) n).hom :=\n-- by admit\n\ndef homological_complex.map_unop {A M : Type*} [category A] [abelian A]\n {c : complex_shape M} (C₁ C₂ : homological_complex Aᵒᵖ c) (f : C₁ ⟶ C₂) :\n C₂.unop ⟶ C₁.unop :=\nhomological_complex.unop_functor.map f.op\n\nnamespace ExtQprime_iso_aux_system_comm_setup\n\ninclude r\nvariables [normed_with_aut r V] [∀ (c : ℝ≥0) (n : ℕ), fact (κ₂ c n ≤ κ c n)]\n\ndef hom_complex_map_T_inv (c : (ℝ≥0)ᵒᵖ) :\n hom_complex_nat.{u} ((QprimeFP_nat.{u} r' BD κ M).obj (unop.{1} c)) V.to_Cond ⟶\n hom_complex_nat.{u} ((QprimeFP_nat.{u} r' BD κ₂ M).obj (unop.{1} c)) V.to_Cond :=\n begin\n refine nat_trans.app _ _,\n refine nat_trans.map_homological_complex _ _,\n refine preadditive_yoneda.map _,\n refine Condensed.of_top_ab_map.{u} (normed_add_group_hom.to_add_monoid_hom.{u u}\n normed_with_aut.T.{u}.inv) (normed_add_group_hom.continuous _)\n end ≫\n (category_theory.functor.map _\n (homological_complex.op_functor.map (quiver.hom.op $\n (QprimeFP_nat.ι BD κ₂ κ M).app _)))\n\nomit r\n\nlemma embed_hom_complex_nat_iso₀ (c : (ℝ≥0)ᵒᵖ) : (embed_hom_complex_nat_iso.{u} ((QprimeFP_nat.{u} r' BD κ₂ M).obj (unop.{1} c)) V.to_Cond).hom.f (int.of_nat 0) = 𝟙 _ := rfl\n\nlemma embed_hom_complex_nat_iso_neg (n : ℕ) (c : (ℝ≥0)ᵒᵖ) : (embed_hom_complex_nat_iso.{u} ((QprimeFP_nat.{u} r' BD κ₂ M).obj (unop.{1} c)) V.to_Cond).hom.f (-[1+ n]) = 𝟙 _ := rfl\n\n\nlemma add_equiv.to_AddCommGroup_iso_apply (A B : AddCommGroup.{u})\n (e : A ≃+ B) (a : A) : e.to_AddCommGroup_iso.hom a = e a := rfl\n\nlemma preadditive_yoneda_obj_obj_CondensedSet_to_Condensed_Ab_apply (M) (X) (t) :\n (preadditive_yoneda_obj_obj_CondensedSet_to_Condensed_Ab M X).hom t =\n yoneda'_equiv _ _ (Condensed_Ab_CondensedSet_adjunction.hom_equiv X.to_Condensed M t).val := rfl\n\ninclude r\n\nlemma aux₁ (c : (ℝ≥0)ᵒᵖ):\n(hom_complex_QprimeFP_nat_iso_aux_system.{u} r' BD κ M V (unop.{1} c)).hom ≫\n ((forget₂.{u+2 u+2 u+1 u+1 u+1} SemiNormedGroup.{u+1} Ab.{u+1}).map_homological_complex\n (complex_shape.up.{0} ℕ)).map ((aux_system.T_inv.{u u+1} r r' BD\n ⟨M⟩ (SemiNormedGroup.ulift.{u+1 u}.obj V) κ).app c ≫\n (aux_system.res.{u u+1} r' BD ⟨M⟩ (SemiNormedGroup.ulift.{u+1 u}.obj V) κ₂ κ).app c) =\n hom_complex_map_T_inv _ _ _ _ _ _ _ _ ≫\n (hom_complex_QprimeFP_nat_iso_aux_system.{u} r' BD κ₂ M V (unop.{1} c)).hom :=\nbegin\n --simp only [← category_theory.functor.map_comp, functor.comp_map], congr' 1,\n dsimp only [hom_complex_map_T_inv], simp only [category.assoc],\n rw ← hom_complex_QprimeFP_nat_iso_aux_system_naturality_in_κ r' BD κ κ₂ M V c.unop,\n simp only [functor.map_comp, ← category.assoc], congr' 1,\n apply hom_complex_QprimeFP_nat_iso_aux_system_naturality_in_T_inv\n\n /- -- IGNORE THIS\n ext k t : 3,\n dsimp [hom_complex_nat] at t,\n dsimp only [hom_complex_QprimeFP_nat_iso_aux_system, aux_system.T_inv,\n aux_system.res, hom_complex_nat, functor.map_iso, iso.trans_hom,\n homological_complex.unop_functor, homological_complex.comp_f,\n nat_iso.map_homological_complex, nat_iso.app_hom, iso.op_hom, quiver.hom.unop_op,\n nat_trans.map_homological_complex_app_f, ExtQprime_iso_aux_system_obj_aux,\n nat_iso.of_components_hom_app, id, iso.symm_hom, nat_iso.app_inv,\n whisker_right_app, nat_trans.op, functor.comp_map],\n simp only [category_theory.functor.map_comp],\n dsimp only [homological_complex.comp_f, functor.map_homological_complex, functor.op_obj,\n functor.unop, forget₂_unop, nat_iso.of_components_hom_app,\n homological_complex.hom.iso_of_components, iso.refl],\n simp only [category.assoc, category.id_comp],\n erw category.id_comp,\n dsimp only [functor.op, quiver.hom.unop_op],\n erw category.comp_id,\n repeat { rw [comp_apply] },\n -/ -- UUUUGGGHHH\n\nend\n\nlemma aux₂ (c : (ℝ≥0)ᵒᵖ) :\n((((preadditive_yoneda.{u+1 u+2}.obj (Condensed.of_top_ab.{u} ↥V)).right_op.map_homological_complex\n (complex_shape.up.{0} ℤ)).obj\n ((QprimeFP_int.{u} r' BD κ M).obj (unop.{1} c))).map_unop\n (((preadditive_yoneda.{u+1 u+2}.obj (Condensed.of_top_ab.{u} ↥V)).right_op.map_homological_complex\n (complex_shape.up.{0} ℤ)).obj\n ((QprimeFP_int.{u} r' BD κ M).obj (unop.{1} c)))\n ((nat_trans.map_homological_complex.{u+1 u+2 0 u+2 u+1}\n (nat_trans.right_op.{u+1 u+1 u+2 u+2} (preadditive_yoneda.{u+1 u+2}.map\n (Condensed.of_top_ab_map.{u} (normed_add_group_hom.to_add_monoid_hom.{u u}\n normed_with_aut.T.{u}.inv) (normed_add_group_hom.continuous _))))\n (complex_shape.up.{0} ℤ)).app\n ((QprimeFP_int.{u} r' BD κ M).obj (unop.{1} c))) ≫\n (homological_complex.unop_functor.{u+2 u+1 0}.right_op.map\n (((preadditive_yoneda.{u+1 u+2}.obj V.to_Cond).right_op.map_homological_complex (complex_shape.up.{0} ℤ)).map\n ((QprimeFP_int.ι.{u} BD κ₂ κ M).app (unop.{1} c)))).unop) ≫\n (embed_hom_complex_nat_iso.{u} ((QprimeFP_nat.{u} r' BD κ₂ M).obj (unop.{1} c)) V.to_Cond).hom =\n (embed_hom_complex_nat_iso.{u} ((QprimeFP_nat.{u} r' BD κ M).obj (unop.{1} c)) V.to_Cond).hom ≫\n category_theory.functor.map _\n (hom_complex_map_T_inv _ _ _ _ _ _ _ _) :=\nbegin\n ext ((_ | k) | k ) : 2,\n { dsimp only [functor.comp],\n simp only [functor.right_op_map, quiver.hom.unop_op, category.assoc, homological_complex.comp_f,\n homological_complex.unop_functor_map_f, functor.map_homological_complex_map_f],\n rw embed_hom_complex_nat_iso₀,\n rw embed_hom_complex_nat_iso₀,\n ext, refl },\n { apply is_zero.eq_of_tgt,\n exact is_zero_zero _ },\n { dsimp only [functor.comp],\n simp only [functor.right_op_map, quiver.hom.unop_op, category.assoc, homological_complex.comp_f,\n homological_complex.unop_functor_map_f, functor.map_homological_complex_map_f],\n rw embed_hom_complex_nat_iso_neg,\n rw embed_hom_complex_nat_iso_neg,\n ext, refl },\nend\n\nend ExtQprime_iso_aux_system_comm_setup\n\nsection naturality_snd_var\n\nvariables {A : Type*} [category A] [abelian A] [enough_projectives A]\n (X : cochain_complex A ℤ)\n [((homotopy_category.quotient A (complex_shape.up.{0} ℤ)).obj X).is_bounded_above]\n {B₁ B₂ : A} (f : B₁ ⟶ B₂) -- (h₁) (h₂) (i)\n\n@[reassoc]\nlemma Ext_compute_with_acyclic_aux₁_naturality_snd_var (i)\n (e : (0 : ℤ) - i = -i) :\n (Ext_compute_with_acyclic_aux₁ X B₁ i).hom ≫\n begin\n refine nat_trans.app _ _,\n refine preadditive_yoneda.map _,\n refine category_theory.functor.map _ f,\n end =\n category_theory.functor.map _\n (category_theory.functor.map _ f) ≫\n (Ext_compute_with_acyclic_aux₁ X B₂ i).hom :=\nbegin\n ext t,\n simp only [comp_apply],\n dsimp [Ext_compute_with_acyclic_aux₁, Ext],\n simp only [category.assoc],\n generalize_proofs h1 h2,\n let φ₁ := λ j, (single _ j).obj B₁,\n let φ₂ := λ j, (single _ j).obj B₂,\n change t ≫ _ ≫ eq_to_hom (congr_arg φ₁ e) ≫ _ =\n _ ≫ _ ≫ _ ≫ eq_to_hom (congr_arg φ₂ e),\n induction e,\n dsimp, simp only [category.id_comp, category.comp_id],\n erw ← nat_trans.naturality,\n refl,\nend\n\n@[reassoc]\nlemma Ext_compute_with_acyclic_aux₂_naturality_snd_var (i) :\n (Ext_compute_with_acyclic_aux₂ X B₁ i).hom ≫\n (homology_functor _ _ _).map\n begin\n refine nat_trans.app _ _,\n refine nat_trans.map_homological_complex _ _,\n exact preadditive_yoneda.map f,\n end =\n nat_trans.app\n (preadditive_yoneda.map $ category_theory.functor.map _ f) _ ≫\n (Ext_compute_with_acyclic_aux₂ X B₂ i).hom :=\nbegin\n dsimp only [Ext_compute_with_acyclic_aux₂, unop_op],\n have := hom_single_iso_naturality_snd_var_good (of' X).replace (-i) f,\n erw ← this,\nend\n\ninclude f\nlemma Ext_compute_with_acyclic_aux₃_naturality_snd_var (i) :\n (homology_functor _ _ _).map\n begin\n refine homological_complex.map_unop _ _ _,\n refine nat_trans.app _ _,\n refine nat_trans.map_homological_complex _ _,\n refine nat_trans.right_op _,\n exact preadditive_yoneda.map f,\n end ≫ Ext_compute_with_acyclic_aux₃ X B₂ i =\n Ext_compute_with_acyclic_aux₃ X B₁ i ≫\n (homology_functor _ _ _).map\n begin\n refine nat_trans.app _ _,\n refine nat_trans.map_homological_complex _ _,\n exact preadditive_yoneda.map f,\n end :=\nbegin\n dsimp only [Ext_compute_with_acyclic_aux₃],\n erw ← (homology_functor.{u_2 u_2+1 0} AddCommGroup.{u_2}\n (complex_shape.up.{0} ℤ).symm (-i)).map_comp,\n erw ← (homology_functor.{u_2 u_2+1 0} AddCommGroup.{u_2}\n (complex_shape.up.{0} ℤ).symm (-i)).map_comp,\n congr' 1,\n ext t x,\n dsimp [Ext_compute_with_acyclic_HomB],\n simp only [comp_apply],\n dsimp [nat_trans.map_homological_complex, functor.right_op,\n homological_complex.map_unop],\n simp only [category.assoc],\nend\n\nlemma Ext_compute_with_acyclic_naturality_snd_var\n (h₁) (h₂) (i) :\n (Ext_compute_with_acyclic X B₁ h₁ i).hom ≫\n (homology_functor _ _ _).map\n (begin\n refine homological_complex.map_unop _ _ _,\n refine nat_trans.app _ _,\n refine nat_trans.map_homological_complex _ _,\n exact (preadditive_yoneda.map f).right_op,\n end) =\n category_theory.functor.map _\n (category_theory.functor.map _ f) ≫ (Ext_compute_with_acyclic X B₂ h₂ i).hom :=\nbegin\n dsimp [Ext_compute_with_acyclic, - homology_functor_map],\n simp only [category.assoc],\n rw ← Ext_compute_with_acyclic_aux₁_naturality_snd_var_assoc,\n rw ← Ext_compute_with_acyclic_aux₂_naturality_snd_var_assoc,\n simp only [category.assoc], congr' 2,\n rw [is_iso.eq_comp_inv, category.assoc, is_iso.inv_comp_eq],\n apply Ext_compute_with_acyclic_aux₃_naturality_snd_var,\n simp,\nend\n\nend naturality_snd_var\n\nlemma ExtQprime_iso_aux_system_comm [normed_with_aut r V]\n [∀ c n, fact (κ₂ c n ≤ κ c n)] [∀ c n, fact (κ₂ c n ≤ r' * κ c n)] (n : ℕ) :\n (ExtQprime_iso_aux_system r' BD κ M V n).hom ≫\n whisker_right (aux_system.Tinv2.{u} r r' BD ⟨M⟩ (SemiNormedGroup.ulift.{u+1}.obj V) κ₂ κ)\n ((forget₂ _ _).map_homological_complex _ ⋙ homology_functor Ab.{u+1} (complex_shape.up ℕ) n) =\n ExtQprime.Tinv2 r r' BD κ κ₂ M V n ≫\n (ExtQprime_iso_aux_system r' BD κ₂ M V n).hom :=\nbegin\n ext c : 2, dsimp only [aux_system.Tinv2, ExtQprime.Tinv2, nat_trans.comp_app, whisker_right_app],\n simp only [sub_comp, nat_trans.app_sub, functor.map_sub, comp_sub],\n refine congr_arg2 _ _ _,\n { rw [← nat_trans.comp_app, ← ExtQprime_iso_aux_system_comm_Tinv], refl },\n\n dsimp only [ExtQprime_iso_aux_system_obj,\n ExtQprime_iso_aux_system,\n iso.trans_hom, id, functor.map_iso_hom, nat_iso.of_components_hom_app,\n nat_trans.comp_app],\n\n haveI : ((homotopy_category.quotient.{u+1 u+2 0} (Condensed.{u u+1 u+2} Ab.{u+1})\n (complex_shape.up.{0} ℤ)).obj\n ((QprimeFP_int.{u} r' BD κ M).obj (unop.{1} c))).is_bounded_above :=\n chain_complex.is_bounded_above _,\n haveI : ((homotopy_category.quotient.{u+1 u+2 0} (Condensed.{u u+1 u+2} Ab.{u+1})\n (complex_shape.up.{0} ℤ)).obj\n ((QprimeFP_int.{u} r' BD κ₂ M).obj (unop.{1} c))).is_bounded_above :=\n chain_complex.is_bounded_above _,\n have := Ext_compute_with_acyclic_naturality\n ((QprimeFP_int.{u} r' BD κ₂ M).obj c.unop)\n ((QprimeFP_int.{u} r' BD κ M).obj c.unop)\n V.to_Cond _ _\n ((QprimeFP_int.ι BD κ₂ κ M).app _) n,\n rotate,\n { intros k i hi, apply QprimeFP_acyclic, exact hi },\n { intros k i hi, apply QprimeFP_acyclic, exact hi },\n\n simp only [category.assoc], dsimp only [ExtQprime.T_inv, nat_trans.comp_app,\n whisker_right_app, whisker_left_app, functor.flip],\n let η := (Ext.{u+1 u+2} ↑n).map ((nat_trans.op.{0 u+1 0 u+2} (QprimeFP.ι.{u} BD κ₂ κ M)).app c),\n\n slice_rhs 1 2 { erw ← η.naturality },\n slice_rhs 2 3 { erw this },\n simp only [category.assoc], clear this η,\n\n let t : Condensed.of_top_ab V ⟶ _ :=\n Condensed.of_top_ab_map.{u} (normed_add_group_hom.to_add_monoid_hom.{u u}\n normed_with_aut.T.{u}.inv) (normed_add_group_hom.continuous _),\n have := Ext_compute_with_acyclic_naturality_snd_var\n ((QprimeFP_int r' BD κ M).obj c.unop) t _ _ n,\n rotate,\n { intros k i hi, apply QprimeFP_acyclic, exact hi },\n { intros k i hi, apply QprimeFP_acyclic, exact hi },\n erw ← reassoc_of this, clear this, congr' 1,\n simp only [functor.comp_map, category_theory.functor.map_comp,\n functor.op_map, quiver.hom.unop_op],\n slice_rhs 1 2 { rw ← category_theory.functor.map_comp },\n slice_lhs 4 5 { rw ← category_theory.functor.map_comp },\n simp only [category.assoc,\n ← category_theory.functor.map_comp, ← functor.map_comp_assoc],\n\n rw ExtQprime_iso_aux_system_comm_setup.aux₁ r r' BD κ κ₂ M V c,\n slice_lhs 2 4\n { simp only [category_theory.functor.map_comp] },\n\n simp only [← category.assoc], congr' 1,\n\n rw ExtQprime_iso_aux_system_comm_setup.aux₂ r r' BD κ κ₂ M V c,\n simp only [category_theory.functor.map_comp, category.assoc],\n congr' 1,\n\n rw [nat_iso.app_hom, ← nat_trans.naturality],\n congr' 1,\n\n -- have := Ext_compute_with_acyclic_naturality, <-- we need naturality in the other variable?!\n\n --simp only [category.assoc],\n --erw reassoc_of this,\n --clear this, simp only [category.assoc], congr' 1,\n\n /-\n rw [nat_trans.comp_app, functor.map_comp, ExtQprime.T_inv,\n nat_trans.comp_app, whisker_right_app, whisker_left_app, category.assoc],\n dsimp only [ExtQprime_iso_aux_system, nat_iso.of_components_hom_app, aux_system,\n aux_system.res, functor.comp_map],\n -/\nend\n\nlemma ExtQprime_iso_aux_system_comm' [normed_with_aut r V]\n [∀ c n, fact (κ₂ c n ≤ κ c n)] [∀ c n, fact (κ₂ c n ≤ r' * κ c n)] (n : ℕ) :\n whisker_right (aux_system.Tinv2.{u} r r' BD ⟨M⟩ (SemiNormedGroup.ulift.{u+1}.obj V) κ₂ κ)\n ((forget₂ _ _).map_homological_complex _ ⋙ homology_functor Ab.{u+1} (complex_shape.up ℕ) n) ≫\n (ExtQprime_iso_aux_system r' BD κ₂ M V n).inv =\n (ExtQprime_iso_aux_system r' BD κ M V n).inv ≫\n ExtQprime.Tinv2 r r' BD κ κ₂ M V n :=\nbegin\n rw [iso.comp_inv_eq, category.assoc, iso.eq_inv_comp],\n apply ExtQprime_iso_aux_system_comm\nend\n\nend\n\nsection\n\ndef _root_.category_theory.functor.map_commsq\n {C D : Type*} [category C] [abelian C] [category D] [abelian D] (F : C ⥤ D) {X Y Z W : C}\n {f₁ : X ⟶ Y} {g₁ : X ⟶ Z} {g₂ : Y ⟶ W} {f₂ : Z ⟶ W} (sq : commsq f₁ g₁ g₂ f₂) :\n commsq (F.map f₁) (F.map g₁) (F.map g₂) (F.map f₂) :=\ncommsq.of_eq $ by rw [← F.map_comp, sq.w, F.map_comp]\n\nend\n\nsection\n\nvariables {r'}\nvariables (BD : breen_deligne.package)\nvariables (κ κ₂ : ℝ≥0 → ℕ → ℝ≥0)\nvariables [∀ (c : ℝ≥0), BD.data.suitable (κ c)] [∀ n, fact (monotone (function.swap κ n))]\nvariables [∀ (c : ℝ≥0), BD.data.suitable (κ₂ c)] [∀ n, fact (monotone (function.swap κ₂ n))]\nvariables (M : ProFiltPseuNormGrpWithTinv₁.{u} r')\nvariables (V : SemiNormedGroup.{u}) [complete_space V] [separated_space V]\n\nopen bounded_homotopy_category\n\n-- move me\ninstance eval'_is_bounded_above :\n ((homotopy_category.quotient (Condensed Ab) (complex_shape.up ℤ)).obj\n ((BD.eval' freeCond').obj M.to_Condensed)).is_bounded_above :=\nby { delta breen_deligne.package.eval', refine ⟨⟨1, _⟩⟩, apply chain_complex.bounded_by_one }\n\nvariables (ι : ulift.{u+1} ℕ → ℝ≥0) (hι : monotone ι)\n\ndef Ext_Tinv2\n {𝓐 : Type*} [category 𝓐] [abelian 𝓐] [enough_projectives 𝓐]\n {A B V : bounded_homotopy_category 𝓐}\n (Tinv : A ⟶ B) (ι : A ⟶ B) (T_inv : V ⟶ V) (i : ℤ) :\n ((Ext i).obj (op B)).obj V ⟶ ((Ext i).obj (op A)).obj V :=\n(((Ext i).map Tinv.op).app V - (((Ext i).map ι.op).app V ≫ ((Ext i).obj _).map T_inv))\n\nopen category_theory.preadditive\n\ndef Ext_Tinv2_commsq\n {𝓐 : Type*} [category 𝓐] [abelian 𝓐] [enough_projectives 𝓐]\n {A₁ B₁ A₂ B₂ V : bounded_homotopy_category 𝓐}\n (Tinv₁ : A₁ ⟶ B₁) (ι₁ : A₁ ⟶ B₁)\n (Tinv₂ : A₂ ⟶ B₂) (ι₂ : A₂ ⟶ B₂)\n (f : A₁ ⟶ A₂) (g : B₁ ⟶ B₂) (sqT : f ≫ Tinv₂ = Tinv₁ ≫ g) (sqι : f ≫ ι₂ = ι₁ ≫ g)\n (T_inv : V ⟶ V) (i : ℤ) :\n commsq\n (((Ext i).map g.op).app V)\n (Ext_Tinv2 Tinv₂ ι₂ T_inv i)\n (Ext_Tinv2 Tinv₁ ι₁ T_inv i)\n (((Ext i).map f.op).app V) :=\ncommsq.of_eq\nbegin\n delta Ext_Tinv2,\n simp only [comp_sub, sub_comp, ← nat_trans.comp_app, ← functor.map_comp, ← op_comp, sqT,\n ← nat_trans.naturality, ← nat_trans.naturality_assoc, category.assoc, sqι],\nend\n\nopen category_theory.preadditive\n\nlemma auux\n {𝓐 : Type*} [category 𝓐] [abelian 𝓐] [enough_projectives 𝓐]\n {A₁ B₁ A₂ B₂ : cochain_complex 𝓐 ℤ}\n [((homotopy_category.quotient 𝓐 (complex_shape.up ℤ)).obj A₁).is_bounded_above]\n [((homotopy_category.quotient 𝓐 (complex_shape.up ℤ)).obj B₁).is_bounded_above]\n [((homotopy_category.quotient 𝓐 (complex_shape.up ℤ)).obj A₂).is_bounded_above]\n [((homotopy_category.quotient 𝓐 (complex_shape.up ℤ)).obj B₂).is_bounded_above]\n {f₁ : A₁ ⟶ B₁} {f₂ : A₂ ⟶ B₂} {α : A₁ ⟶ A₂} {β : B₁ ⟶ B₂}\n (sq1 : commsq f₁ α β f₂) :\n of_hom f₁ ≫ of_hom β = of_hom α ≫ of_hom f₂ :=\nbegin\n have := sq1.w,\n apply_fun (λ f, (homotopy_category.quotient _ _).map f) at this,\n simp only [functor.map_comp] at this,\n exact this,\nend\n\n@[simp] lemma of_hom_id\n {𝓐 : Type*} [category 𝓐] [abelian 𝓐] [enough_projectives 𝓐]\n {A : cochain_complex 𝓐 ℤ}\n [((homotopy_category.quotient 𝓐 (complex_shape.up ℤ)).obj A).is_bounded_above] :\n of_hom (𝟙 A) = 𝟙 _ :=\nby { delta of_hom, rw [category_theory.functor.map_id], refl }\n\nlemma Ext_iso_of_bicartesian_of_bicartesian\n {𝓐 : Type*} [category 𝓐] [abelian 𝓐] [enough_projectives 𝓐]\n {A₁ B₁ C A₂ B₂ : cochain_complex 𝓐 ℤ}\n [((homotopy_category.quotient 𝓐 (complex_shape.up ℤ)).obj A₁).is_bounded_above]\n [((homotopy_category.quotient 𝓐 (complex_shape.up ℤ)).obj B₁).is_bounded_above]\n [((homotopy_category.quotient 𝓐 (complex_shape.up ℤ)).obj C).is_bounded_above]\n [((homotopy_category.quotient 𝓐 (complex_shape.up ℤ)).obj A₂).is_bounded_above]\n [((homotopy_category.quotient 𝓐 (complex_shape.up ℤ)).obj B₂).is_bounded_above]\n {f₁ : A₁ ⟶ B₁} {g₁ : B₁ ⟶ C} (w₁ : ∀ n, short_exact (f₁.f n) (g₁.f n))\n {f₂ : A₂ ⟶ B₂} {g₂ : B₂ ⟶ C} (w₂ : ∀ n, short_exact (f₂.f n) (g₂.f n))\n (α : A₁ ⟶ A₂) (β : B₁ ⟶ B₂) (γ : C ⟶ C)\n (ιA : A₁ ⟶ A₂) (ιB : B₁ ⟶ B₂)\n (sq1 : commsq f₁ α β f₂) (sq2 : commsq g₁ β γ g₂)\n (sq1' : commsq f₁ ιA ιB f₂) (sq2' : commsq g₁ ιB (𝟙 _) g₂)\n (V : bounded_homotopy_category 𝓐) (T_inv : V ⟶ V)\n (i : ℤ)\n (H1 : (Ext_Tinv2_commsq (of_hom α) (of_hom ιA) (of_hom β) (of_hom ιB) (of_hom f₁) (of_hom f₂)\n (auux sq1) (auux sq1') T_inv i).bicartesian)\n (H2 : (Ext_Tinv2_commsq (of_hom α) (of_hom ιA) (of_hom β) (of_hom ιB) (of_hom f₁) (of_hom f₂)\n (auux sq1) (auux sq1') T_inv (i+1)).bicartesian) :\n is_iso (Ext_Tinv2 (of_hom γ) (𝟙 _) T_inv (i+1)) :=\nbegin\n have LES₁ := (((Ext_five_term_exact_seq' _ _ i V w₁).drop 2).pair.cons (Ext_five_term_exact_seq' _ _ (i+1) V w₁)),\n replace LES₁ := (((Ext_five_term_exact_seq' _ _ i V w₁).drop 1).pair.cons LES₁).extract 0 4,\n have LES₂ := (((Ext_five_term_exact_seq' _ _ i V w₂).drop 2).pair.cons (Ext_five_term_exact_seq' _ _ (i+1) V w₂)).extract 0 4,\n replace LES₂ := (((Ext_five_term_exact_seq' _ _ i V w₂).drop 1).pair.cons LES₂).extract 0 4,\n refine iso_of_bicartesian_of_bicartesian LES₂ LES₁ _ _ _ _ H1 H2,\n { apply commsq.of_eq, delta Ext_Tinv2, clear LES₁ LES₂,\n rw [sub_comp, comp_sub, ← functor.flip_obj_map, ← functor.flip_obj_map],\n rw ← Ext_δ_natural i V _ _ _ _ α β γ sq1.w sq2.w w₁ w₂,\n congr' 1,\n rw [← nat_trans.naturality, ← functor.flip_obj_map, category.assoc,\n Ext_δ_natural i V _ _ _ _ ιA ιB (𝟙 _) sq1'.w sq2'.w w₁ w₂],\n simp only [op_id, category_theory.functor.map_id, nat_trans.id_app,\n category.id_comp, of_hom_id, category.comp_id],\n erw [category.id_comp],\n symmetry,\n apply Ext_δ_natural', },\n { apply Ext_Tinv2_commsq,\n { exact auux sq2 },\n { exact auux sq2' }, },\nend\n\nend\n", "meta": {"author": "leanprover-community", "repo": "lean-liquid", "sha": "92f188bd17f34dbfefc92a83069577f708851aec", "save_path": "github-repos/lean/leanprover-community-lean-liquid", "path": "github-repos/lean/leanprover-community-lean-liquid/lean-liquid-92f188bd17f34dbfefc92a83069577f708851aec/src/Lbar/ext_aux2.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.4073333856566001, "lm_q2_score": 0.020023440521910296, "lm_q1q2_score": 0.00815621582028328}} {"text": "import LeanCodePrompts.FirstTacticData\nimport LeanCodePrompts.ParseJson\nimport LeanCodePrompts.Translate\nimport Lean\n\nopen Lean Meta Elab Tactic Parser \n\ninitialize cacheTacticJson : IO.Ref (HashMap String Json) ← IO.mkRef (HashMap.empty) \n\ndef getTacticString : TacticM String := do\n let s ← saveState\n let target ← getMainTarget\n let lctx ← getLCtx\n let decls := lctx.decls.toList.tail!\n let mut statement := \"\"\n for decl in decls do\n match decl with\n | some <| LocalDecl.ldecl _ _ n t .. => \n statement := statement ++ s!\"({n.eraseMacroScopes} : {← t.view}) \"\n pure ()\n | some <| LocalDecl.cdecl _ _ n t bi _ => do\n let core := s!\"{n.eraseMacroScopes} : {← t.view}\"\n let typeString :=s!\"{← t.view}\"\n let argString := match bi with\n | BinderInfo.implicit => \"{\"++ core ++ \"}\"\n | BinderInfo.strictImplicit => \"{{ \"++ core ++ \"}}\"\n | BinderInfo.instImplicit =>\n if (`inst).isPrefixOf n then s!\"[{typeString}]\"\n else s!\"[{core}]\"\n | BinderInfo.default => s!\"({core})\" \n statement := statement ++ argString ++ \" \" \n pure ()\n | none => pure ()\n statement := statement ++ \": \" ++ (← target.view)\n s.restore\n return statement.replace \"✝\" \"\"\n\nelab \"name_inacessibles\" : tactic => do\n withMainContext do\n let lctx ← getLCtx\n let decls := lctx.decls\n let mut statement := \"rename_i\"\n for decl in decls do\n match decl with\n | some <| LocalDecl.ldecl _ _ n .. => \n if n != n.eraseMacroScopes then\n statement := statement ++ s!\" {n.eraseMacroScopes}\"\n pure ()\n | some <| LocalDecl.cdecl _ _ n .. => do\n if n != n.eraseMacroScopes then\n statement := statement ++ s!\" {n.eraseMacroScopes}\"\n pure ()\n | none => pure ()\n unless statement == \"rename_i\" do\n let tac? := runParserCategory (← getEnv) `tactic statement\n match tac? with\n | Except.ok tac => do\n evalTactic tac\n | Except.error e => do\n throwError e \n\nelab \"show_goal\" : tactic => \n withMainContext do \n let view ← getTacticString\n logInfo view\n return ()\n\ndef silly {α : Type}(n m : Nat)[DecidableEq α] : n + m = n + m := by \n show_goal\n let a := n\n let _ : a = a := rfl\n show_goal\n rfl\n\n\ndef silly' : (n m : Nat) → n + m = n + m := by\n intros\n show_goal \n rfl\n done\n\nexample : (n m : Nat) → n + m = n + m := by\n intros\n name_inacessibles \n rfl\n done\n\nstructure TacticStateProxy where\n binders: Array <| Name × BinderInfo\n letData : Array <| Name × Expr × Expr\n target : Expr \n\ndef getTacticStateProxy : TacticM <| Option TacticStateProxy := \n withoutModifyingState do\n try \n let target ← getMainTarget\n let lctx ← getLCtx\n let decls := lctx.decls\n let mut binders := #[]\n let mut letData := #[]\n let mut fvars : Array Expr := #[]\n for decl in decls do\n match decl with\n | some <| LocalDecl.ldecl _ _ n t b .. => \n let t ← mkForallFVars fvars t\n let b ← mkLambdaFVars fvars b\n letData := letData.push (n, t, b)\n pure ()\n | some <| LocalDecl.cdecl _ fVarId n _ bi _ => do\n binders := binders.push (n, bi)\n fvars := fvars.push <| mkFVar fVarId\n pure ()\n | none => pure ()\n let target ← mkForallFVars fvars target\n return some {binders := binders, letData := letData, target := target}\n catch _ => return none\n\n#check List.allM\n\ndef equalStates (s₁ s₂ : TacticStateProxy) : TacticM Bool := \n withMainContext do\n return s₁.binders == s₂.binders \n && s₁.letData.size == s₂.letData.size && \n (← isDefEq s₁.target s₂.target) && \n (← (List.range s₁.letData.size).allM (fun i => \n let (n₁, t₁, b₁) := s₁.letData.get! i\n let (n₂, t₂, b₂) := s₂.letData.get! i\n return n₁ == n₂ && (← isDefEq t₁ t₂) && (← isDefEq b₁ b₂)))\n\ndef firstEffectiveTactic (tacStrings: List String)(warnOnly: Bool := Bool.true) : TacticM Unit :=\n withMainContext do\n let env ← getEnv\n let goal ← getTacticString\n logInfo m!\"goal: {goal}\"\n logInfo m!\"trying tactics: {tacStrings}\"\n let s ← saveState\n let s₁? ← getTacticStateProxy\n for tacString in tacStrings do\n -- logInfo m!\"Trying tactic {tacString}\"\n try\n let tac? := runParserCategory env `tactic tacString\n match tac? with\n | Except.ok tac => do\n Term.withoutErrToSorry do \n evalTactic tac\n let gs ← getUnsolvedGoals\n if gs.isEmpty then\n logInfo m!\"tactic `{tacString}` was effective\"\n return \n else\n let check : Bool ← \n try \n let s₂? ← getTacticStateProxy \n match s₁?, s₂? with\n | some s₁, some s₂ => equalStates s₁ s₂ \n | _,_ => pure Bool.true\n catch _ =>\n -- logWarning \n -- m!\"Failed to check state after {tacString}; error : {e.toMessageData}\" \n pure Bool.true\n if check then\n s.restore\n else\n let checkForSorries : Bool ←\n try\n let target ← getMainTarget\n pure target.hasSyntheticSorry\n catch _ => pure Bool.false\n -- logInfo m!\"sorries? {checkForSorries}\"\n if checkForSorries then\n s.restore\n else\n logInfo m!\"tactic `{tacString}` was effective\"\n return \n | Except.error _ => \n pure ()\n catch _ =>\n s.restore\n unless warnOnly do\n throwError m!\"No effective tactic found for {goal} in {tacStrings}\"\n logWarning \"No tactic in the list was effective\" \n\n \nelab \"first_effective_tactic\" : tactic => \n withMainContext do\n firstEffectiveTactic [\"unparsable\", \"exact blah\", \"intros\", \"rfl\"]\n\n-- proved by reflexivity\ndef silly'' (n m : Nat) : n + m = n + m := by\n intros -- legal but no effect\n first_effective_tactic\n\ndef silly''' : (n m : Nat) → n + m = n + m := by\n first_effective_tactic \n rfl\n\ndef silly'''' : (n m : Nat) → n + m = n + m := by\n repeat (first_effective_tactic)\n\ndef getTacticPrompts(s: String)(numSim : Nat)\n : TermElabM (Array String) := do\n let jsData := Json.mkObj [\n (\"filename\", \"data/lean4-thms.json\"),\n (\"field\", \"core-prompt\"),\n (\"core-prompt\", s),\n (\"n\", numSim),\n (\"model_name\", \"all-mpnet-base-v2\")\n ]\n let simJsonOut ← \n IO.Process.output {cmd:= \"curl\", args:= \n #[\"-X\", \"POST\", \"-H\", \"Content-type: application/json\", \"-d\", jsData.pretty, s!\"{← leanAideIP}/nearest_prompts\"]}\n if simJsonOut.exitCode > 0 then\n throwError m!\"Failed to get prompts from server: {simJsonOut.stderr}\"\n else\n let json ← readJson simJsonOut.stdout \n match json.getArr? with\n | Except.ok arr => \n let mut prompts := #[]\n for j in arr do\n match j.getObjVal? \"tactic-prompt\" with\n | Except.ok s =>\n match s.getStr? with\n | Except.ok s => \n prompts := prompts.push s\n | Except.error e => \n throwError m!\"Failed to parse json {j}; error: {e}\"\n | Except.error e =>\n throwError m!\"Failed to parse json {j}; error: {e}\"\n return prompts\n | Except.error e => \n throwError m!\"Failed to parse json: {e}\"\n\n\n\ndef fourSquaresPrompt := \": ∀ p : Nat, Prime p → (p % 4 = 1) → ∃ a b : Nat, a ^ 2 + b ^ 2 = p\"\n\n-- #eval getTacticPrompts fourSquaresPrompt 20 \n\ndef makeTacticPrompt (n: Nat) : TacticM String := do\n let core ← getTacticString\n let prompts ← getTacticPrompts core n\n let prompt := prompts.foldr (fun p acc => \ns!\"{p}\n\n{acc}\"\n ) s!\"\ntheorem {core} := by \"\n return prompt\n\ndef tacticList : TacticM <| List String := do\n let core ← getTacticString\n let prompts ← getTacticPrompts core 5\n let promptPairs := prompts.map (fun p => \n let arr := p.splitOn \":= by\"\n (arr.get! 0++ \":= by\", arr.get! 1))\n let prompt := GPT.makePrompt core promptPairs\n -- let prompt ← makeTacticPrompt 20 \n let cache ← cacheTacticJson.get\n let fullJson ←\n match cache.find? prompt.pretty with\n | some json => pure json\n | none => \n let res ← gptQuery prompt 5 ⟨8, 1⟩ #[\";\", \"sorry\", \"\\n\"]\n cacheTacticJson.set <| cache.insert prompt.pretty res\n pure res\n let outJson := \n (fullJson.getObjVal? \"choices\").toOption.getD (Json.arr #[])\n let arr ← GPT.jsonToExprStrArray outJson\n let arr := arr.map (fun s => \n if s.endsWith \"<\" then s.dropRight 1 |>.trim else s.trim)\n return arr.toList.eraseDups\n\nelab \"aide?\" : tactic =>\n withMainContext do\n let tacStrings ← tacticList\n let tacStrings := tacStrings.filter (fun s => s != \"sorry\" && s != \"admit\")\n let tac ← `(tactic|name_inacessibles)\n evalTactic tac\n firstEffectiveTactic tacStrings Bool.true\n\nelab \"aide!\" : tactic =>\n withMainContext do\n let tacStrings ← tacticList\n let tac ← `(tactic|name_inacessibles)\n evalTactic tac\n let tacStrings := tacStrings.filter (fun s => s != \"sorry\" && s != \"admit\")\n firstEffectiveTactic tacStrings Bool.false\n\nmacro \"aide\" : tactic => \n `(tactic| aide? ; save)\n\n\nelab \"show_tactic_prompt\" : tactic => \n withMainContext do \n let view ← makeTacticPrompt 20\n logInfo view\n return ()\n\nelab \"lookahead\" tac:tactic : tactic => \n withMainContext do\n let s ← saveState\n try\n evalTactic tac\n s.restore\n catch e =>\n s.restore\n let msg := e.toMessageData\n throwError s!\"{← msg.toString}\"\n\n\ndef lookaheadTactics (ss: List String) : List String :=\n ss.map (fun s => s!\"{s} ; done\") ++ \n ss.map (fun s => s!\"({s} <;> (lookahead aide!)) ; done\") ++\n ss.map (fun s => s!\"{s} <;> (lookahead aide!)\") ++ \n ss\n\nexample : 1 = 1 := by\n lookahead rfl\n lookahead rfl\n rfl\n\nelab \"aide_aux\" : tactic =>\n withMainContext do\n let tacStrings ← tacticList\n let tacStrings := tacStrings.filter (fun s => s != \"sorry\" && s != \"admit\")\n let tac ← `(tactic|name_inacessibles)\n evalTactic tac\n let tacStrings := lookaheadTactics tacStrings\n firstEffectiveTactic tacStrings Bool.false\n\nmacro \"aide_lookahead\" : tactic => `(checkpoint aide_aux)\n", "meta": {"author": "siddhartha-gadgil", "repo": "LeanAide", "sha": "7862af73ee2f0be08b20fd3e4148e20bf4a81054", "save_path": "github-repos/lean/siddhartha-gadgil-LeanAide", "path": "github-repos/lean/siddhartha-gadgil-LeanAide/LeanAide-7862af73ee2f0be08b20fd3e4148e20bf4a81054/LeanCodePrompts/FirstTacticFinder.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2814055953761018, "lm_q2_score": 0.028870909035235398, "lm_q1q2_score": 0.008124435346109694}} {"text": "/-!\n# Monad Transformers\n\nIn the previous sections you learned about some handy monads [Option](monads.lean.md),\n[IO](monads.lean.md), [Reader](readers.lean.md), [State](states.lean.md) and\n[Except](except.lean.md), and you now know how to make your function use one of these, but what you\ndo not yet know is how to make your function use multiple monads at once.\n\nFor example, suppose you need a function that wants to access some Reader context and optionally throw\nan exception? This would require composition of two monads `ReaderM` and `Except` and this is what\nmonad transformers are for.\n\nA monad transformer is fundamentally a wrapper type. It is generally parameterized by another\nmonadic type. You can then run actions from the inner monad, while adding your own customized\nbehavior for combining actions in this new monad. The common transformers add `T` to the end of an\nexisting monad name. You will find `OptionT`, `ExceptT`, `ReaderT`, `StateT` but there is no transformer\nfor `IO`. So generally if you need `IO` it becomes the innermost wrapped monad.\n\nIn the following example we use `ReaderT` to provide some read only context to a function\nand this `ReaderT` transformer will wrap an `Except` monad. If all goes well the\n`requiredArgument` returns the value of a required argument and `optionalSwitch`\nreturns true if the optional argument is present.\n\n-/\nabbrev Arguments := List String\n\ndef indexOf? [BEq α] (xs : List α) (s : α) (start := 0): Option Nat :=\n match xs with\n | [] => none\n | a :: tail => if a == s then some start else indexOf? tail s (start+1)\n\ndef requiredArgument (name : String) : ReaderT Arguments (Except String) String := do\n let args ← read\n let value := match indexOf? args name with\n | some i => if i + 1 < args.length then args[i+1]! else \"\"\n | none => \"\"\n if value == \"\" then throw s!\"Command line argument {name} missing\"\n return value\n\ndef optionalSwitch (name : String) : ReaderT Arguments (Except String) Bool := do\n let args ← read\n return match (indexOf? args name) with\n | some _ => true\n | none => false\n\n#eval requiredArgument \"--input\" |>.run [\"--input\", \"foo\"]\n-- Except.ok \"foo\"\n\n#eval requiredArgument \"--input\" |>.run [\"foo\", \"bar\"]\n-- Except.error \"Command line argument --input missing\"\n\n#eval optionalSwitch \"--help\" |>.run [\"--help\"]\n-- Except.ok true\n\n#eval optionalSwitch \"--help\" |>.run []\n-- Except.ok false\n\n/-!\nNotice that `throw` was available from the inner `Except` monad. The cool thing is you can switch\nthis around and get the exact same result using `ExceptT` as the outer monad transformer and\n`ReaderM` as the wrapped monad. Try changing requiredArgument to `ExceptT String (ReaderM Arguments) Bool`.\n\nNote: the `|>.` notation is described in [Readers](readers.lean.md#the-reader-solution).\n\n## Adding more layers\n\nHere's the best part about monad transformers. Since the result of a monad transformer is itself a\nmonad, you can wrap it inside another transformer! Suppose you need to pass in some read only context\nlike the command line arguments, update some read-write state (like program Config) and optionally\nthrow an exception, then you could write this:\n\n-/\nstructure Config where\n help : Bool := false\n verbose : Bool := false\n input : String := \"\"\n deriving Repr\n\nabbrev CliConfigM := StateT Config (ReaderT Arguments (Except String))\n\ndef parseArguments : CliConfigM Bool := do\n let mut config ← get\n if (← optionalSwitch \"--help\") then\n throw \"Usage: example [--help] [--verbose] [--input ]\"\n config := { config with\n verbose := (← optionalSwitch \"--verbose\"),\n input := (← requiredArgument \"--input\") }\n set config\n return true\n\ndef main (args : List String) : IO Unit := do\n let config : Config := { input := \"default\"}\n match parseArguments |>.run config |>.run args with\n | Except.ok (_, c) => do\n IO.println s!\"Processing input '{c.input}' with verbose={c.verbose}\"\n | Except.error s => IO.println s\n\n\n#eval main [\"--help\"]\n-- Usage: example [--help] [--verbose] [--input ]\n\n#eval main [\"--input\", \"foo\"]\n-- Processing input file 'foo' with verbose=false\n\n#eval main [\"--verbose\", \"--input\", \"bar\"]\n-- Processing input 'bar' with verbose=true\n\n/-!\nIn this example `parseArguments` is actually three stacked monads, `StateM`, `ReaderM`, `Except`. Notice\nthe convention of abbreviating long monadic types with an alias like `CliConfigM`.\n\n## Monad Lifting\n\nLean makes it easy to compose functions that use different monads using a concept of automatic monad\nlifting. You already used lifting in the above code, because you were able to compose\n`optionalSwitch` which has type `ReaderT Arguments (Except String) Bool` and call it from\n`parseArguments` which has a bigger type `StateT Config (ReaderT Arguments (Except String))`.\nThis \"just worked\" because Lean did some magic with monad lifting.\n\nTo give you a simpler example of this, suppose you have the following function:\n-/\ndef divide (x : Float ) (y : Float): ExceptT String Id Float :=\n if y == 0 then\n throw \"can't divide by zero\"\n else\n pure (x / y)\n\n#eval divide 6 3 -- Except.ok 2.000000\n#eval divide 1 0 -- Except.error \"can't divide by zero\"\n/-!\n\nNotice here we used the `ExceptT` transformer, but we composed it with the `Id` identity monad.\nThis is then the same as writing `Except String Float` since the identity monad does nothing.\n\nNow suppose you want to count the number of times divide is called and store the result in some\nglobal state:\n-/\n\ndef divideCounter (x : Float) (y : Float) : StateT Nat (ExceptT String Id) Float := do\n modify fun s => s + 1\n divide x y\n\n#eval divideCounter 6 3 |>.run 0 -- Except.ok (2.000000, 1)\n#eval divideCounter 1 0 |>.run 0 -- Except.error \"can't divide by zero\"\n\n/-!\n\nThe `modify` function is a helper which makes it easier to use `modifyGet` from the `StateM` monad.\nBut something interesting is happening here, `divideCounter` is returning the value of\n`divide`, but the types don't match, yet it works? This is monad lifting in action.\n\nYou can see this more clearly with the following test:\n\n-/\ndef liftTest (x : Except String Float) :\n StateT Nat (Except String) Float := x\n\n#eval liftTest (divide 5 1) |>.run 3 -- Except.ok (5.000000, 3)\n\n/-!\n\nNotice that `liftTest` returned `x` without doing anything to it, yet that matched the return type\n`StateT Nat (Except String) Float`. Monad lifting is provided by monad transformers. if you\n`#print liftTest` you will see that Lean is implementing this using a call to a function named\n`monadLift` from the `MonadLift` type class:\n\n```lean,ignore\nclass MonadLift (m : Type u → Type v) (n : Type u → Type w) where\n monadLift : {α : Type u} → m α → n α\n```\n\nSo `monadLift` is a function for lifting a computation from an inner `Monad m α ` to an outer `Monad n α`.\nYou could replace `x` in `liftTest` with `monadLift x` if you want to be explicit about it.\n\nThe StateT monad transformer defines an instance of `MonadLift` like this:\n\n```lean\n@[inline] protected def lift {α : Type u} (t : m α) : StateT σ m α :=\n fun s => do let a ← t; pure (a, s)\n\ninstance : MonadLift m (StateT σ m) := ⟨StateT.lift⟩\n```\nThis means that any monad `m` can be wrapped in a `StateT` monad by using the function\n`fun s => do let a ← t; pure (a, s)` that takes state `s`, runs the inner monad action `t`, and\nreturns the result and the new state in a pair `(a, s)` without making any changes to `s`.\n\nBecause `MonadLift` is a type class, Lean can automatically find the required `monadLift`\ninstances in order to make your code compile and in this way it was able to find the `StateT.lift`\nfunction and use it to wrap the result of `divide` so that the correct type is returned from\n`divideCounter`.\n\nIf you have an instance `MonadLift m n` that means there is a way to turn a computation that happens\ninside of `m` into one that happens inside of `n` and (this is the key part) usually *without* the\ninstance itself creating any additional data that feeds into the computation. This means you can in\nprinciple declare lifting instances from any monad to any other monad, it does not, however, mean\nthat you should do this in all cases. You can get a very nice report on how all this was done by\nadding the line `set_option trace.Meta.synthInstance true in` before `divideCounter` and moving you\ncursor to the end of the first line after `do`.\n\nThis was a lot of detail, but it is very important to understand how monad lifting works because it\nis used heavily in Lean programs.\n\n## Transitive lifting\n\nThere is also a transitive version of `MonadLift` called `MonadLiftT` which can lift multiple\nmonad layers at once. In the following example we added another monad layer with\n`ReaderT String ...` and notice that `x` is also automatically lifted to match.\n\n-/\ndef liftTest2 (x : Except String Float) :\n ReaderT String (StateT Nat (Except String)) Float := x\n\n#eval liftTest2 (divide 5 1) |>.run \"\" |>.run 3\n-- Except.ok (5.000000, 3)\n\n/-!\n\nThe ReaderT monadLift is even simpler than the one for StateT:\n\n```lean,ignore\ninstance : MonadLift m (ReaderT ρ m) where\n monadLift x := fun _ => x\n```\n\nThis lift operation creates a function that defines the required `ReaderT` input\nargument, but the inner monad doesn't know or care about `ReaderT` so the\nmonadLift function throws it away with the `_` then calls the inner monad action `x`.\nThis is a perfectly legal implementation of the `ReaderM` monad.\n\n## Add your own Custom MonadLift\n\nThis does not compile:\n-/\ndef main2 : IO Unit := do\n try\n let ret ← divideCounter 5 2 |>.run 0\n IO.println (toString ret)\n catch e =>\n IO.println e\n\n/-!\nsaying:\n```\ntypeclass instance problem is stuck, it is often due to metavariables\n ToString ?m.4786\n```\n\nThe reason is `divideCounter` returns the big `StateT Nat (ExceptT String Id) Float` and that type\ncannot be automatically lifted into the `main` return type of `IO Unit` unless you give it some\nhelp.\n\nThe following custom `MonadLift` solves this problem:\n\n-/\ndef liftIO (t : ExceptT String Id α) : IO α := do\n match t with\n | .ok r => EStateM.Result.ok r\n | .error s => EStateM.Result.error s\n\ninstance : MonadLift (ExceptT String Id) IO where\n monadLift := liftIO\n\ndef main3 : IO Unit := do\n try\n let ret ← divideCounter 5 2 |>.run 0\n IO.println (toString ret)\n catch e =>\n IO.println e\n\n#eval main3 -- (2.500000, 1)\n/-!\n\nIt turns out that the `IO` monad you see in your `main` function is based on the `EStateM.Result` type\nwhich is similar to the `Except` type but it has an additional return value. The `liftIO` function\nconverts any `Except String α` into `IO α` by simply mapping the ok case of the `Except` to the\n`Result.ok` and the error case to the `Result.error`.\n\n## Lifting ExceptT\n\nIn the previous [Except](except.lean.md) section you saw functions that `throw` Except\nvalues. When you get all the way back up to your `main` function which has type `IO Unit` you have\nthe same problem you had above, because `Except String Float` doesn't match even if you use a\n`try/catch`.\n\n-/\n\ndef main4 : IO Unit := do\n try\n let ret ← divide 5 0\n IO.println (toString ret) -- lifting happens here.\n catch e =>\n IO.println s!\"Unhandled exception: {e}\"\n\n#eval main4 -- Unhandled exception: can't divide by zero\n\n/-!\n\nWithout the `liftIO` the `(toString ret)` expression would not compile with a similar error:\n\n```\ntypeclass instance problem is stuck, it is often due to metavariables\n ToString ?m.6007\n```\n\nSo the general lesson is that if you see an error like this when using monads, check for\na missing `MonadLift`.\n\n## Summary\n\nNow that you know how to combine your monads together, you're almost done with understanding the key\nconcepts of monads! You could probably go out now and start writing some pretty nice code! But to\ntruly master monads, you should know how to make your own, and there's one final concept that you\nshould understand for that. This is the idea of type \"laws\". Each of the structures you've learned\nso far has a series of laws associated with it. And for your instances of these classes to make\nsense, they should follow the laws! Check out [Monad Laws](laws.lean.md).\n-/", "meta": {"author": "leanprover", "repo": "lean4", "sha": "742d053a97bdd109a41a921facd1cd6a55e89bc7", "save_path": "github-repos/lean/leanprover-lean4", "path": "github-repos/lean/leanprover-lean4/lean4-742d053a97bdd109a41a921facd1cd6a55e89bc7/doc/monads/transformers.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.22541660542786957, "lm_q2_score": 0.03567854985236399, "lm_q1q2_score": 0.008042537594308907}} {"text": "/-\nCopyright (c) 2023 Kyle Miller. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Kyle Miller\n-/\nimport Lean\nimport Mathlib.Tactic.Relation.Rfl\nimport Std.Logic\n\n/-!\n# The `congr!` tactic\n\nThis is a more powerful version of the `congr` tactic that knows about more congruence lemmas and\ncan apply to more situations. It is similar to the `congr'` tactic from Mathlib 3.\n\nThe `congr!` tactic is used by the `convert` and `convert_to` tactics.\n\nSee the syntax docstring for more details.\n-/\n\nopen Lean Meta Elab Tactic\n\ninitialize registerTraceClass `congr!\ninitialize registerTraceClass `congr!.synthesize\n\n/-- The configuration for the `congr!` tactic. -/\nstructure Congr!.Config where\n /-- The transparency level to use when applying a congruence theorem.\n By default this is `.reducible`, which prevents unfolding of most definitions. -/\n transparency : TransparencyMode := TransparencyMode.reducible\n /-- The transparency level to use when doing transformations before applying congruence lemmas.\n This includes trying to prove the goal by `rfl` and using the `assumption` tactic.\n By default this is `.reducible`, which prevents unfolding of most definitions. -/\n preTransparency : TransparencyMode := TransparencyMode.reducible\n /-- For passes that synthesize a congruence lemma using one side of the equality,\n we run the pass both for the left-hand side and the right-hand side. If `preferLHS` is `true`\n then we start with the left-hand side.\n\n This can be used to control which side's definitions are expanded when applying the\n congruence lemma (if `preferLHS = true` then the RHS can be expanded). -/\n preferLHS : Bool := true\n /-- Allow both sides to be a partial applications.\n When false, given an equality `f a b = g x y z` this means we never consider\n proving `f a = g x y`.\n\n In this case, we might still consider `f = g x` if a pass generates a congruence lemma using the\n left-hand side. Use `sameFun := true` to ensure both sides are applications\n of the same function (making it be similar to the `congr` tactic). -/\n partialApp : Bool := true\n /-- Whether to require that both sides of an equality are applications of defeq functions.\n That is, if true, `f a = g x` is only considered if `f` and `g` are defeq (making it be similar\n to the `congr` tactic). -/\n sameFun : Bool := false\n /-- The maximum number of arguments to consider when doing congruence of function applications.\n For example, with `f a b c = g w x y z`, setting `maxArgs := some 2` means it will only consider\n either `f a b = g w x y` and `c = z` or `f a = g w x`, `b = y`, and `c = z`. Setting\n `maxArgs := none` (the default) means no limit.\n\n When the functions are dependent, `maxArgs` can prevent congruence from working at all.\n In `Fintype.card α = Fintype.card β`, one needs to have `maxArgs` at `2` or higher since\n there is a `Fintype` instance argument that depends on the first.\n\n When there aren't such dependency issues, setting `maxArgs := some 1` causes `congr!` to\n do congruence on a single argument at a time. This can be used in conjunction with the\n iteration limit to control exactly how many arguments are to be processed by congruence. -/\n maxArgs : Option Nat := none\n /-- Whether or not `congr!` should generate equalities between types even if the types\n do not look plausibly equal. We have a heuristic in the main congruence generator that types\n `α` and `β` are *plausibly equal* according to the following algorithm:\n\n - If the types are both propositions, they are plausibly equal (iffs are plausible).\n - If the types are from different universes, they are not plausibly equal.\n - Suppose in whnf we have `α = f a₁ ... aₘ` and `β = g b₁ ... bₘ`. If `f` is not definitionally\n equal to `g` or `m ≠ n`, then `α` and `β` are not plausibly equal.\n - If there is some `i` such that `aᵢ` and `bᵢ` are not plausibly equal, then `α` and `β` are\n not plausibly equal.\n - Otherwise, `α` and `β` are plausibly equal.\n\n The purpose of this is to prevent considering equalities like `ℕ = ℤ` while allowing equalities\n such as `Fin n = Fin m` or `Subtype p = Subtype q` (so long as these are subtypes of the\n same type).\n\n The way this is implemented is that the congruence generator, when it is comparing arguments\n in an equality of function applications, marks a function parameter to \"fixed\" if the provided\n arguments are types that are not plausibly equal. The effect of this is that congruence succeeds\n if those arguments are defeq at `transparency` transparency. -/\n typeEqs : Bool := false\n /-- As a last pass, perform eta expansion of both sides of an equality. For example,\n this transforms a bare `HAdd.hAdd` into `fun x y => x + y`. -/\n etaExpand : Bool := false\n /-- Whether to use the congruence generator that is used by `simp` and `congr`. This generator\n is more strict, and it does not respect all configuration settings. It does respect\n `preferLHS`, `partialApp` and `maxArgs` and transparency settings. It acts as if `sameFun := true`\n and it ignores `typeEqs`. -/\n useCongrSimp : Bool := false\n\n/-- A configuration option that makes `congr!` do the sorts of aggressive unfoldings that `congr`\ndoes while also similarly preventing `congr!` from considering partial applications or congruences\nbetween different functions being applied. -/\ndef Congr!.Config.unfoldSameFun : Congr!.Config where\n partialApp := false\n sameFun := true\n transparency := .default\n preTransparency := .default\n\n/-- Whether the given number of arguments is allowed to be considered. -/\ndef Congr!.Config.numArgsOk (config : Config) (numArgs : Nat) : Bool :=\n numArgs ≤ config.maxArgs.getD numArgs\n\n/-- According to the configuration, how many of the arguments in `numArgs` should be considered. -/\ndef Congr!.Config.maxArgsFor (config : Config) (numArgs : Nat) : Nat :=\n min numArgs (config.maxArgs.getD numArgs)\n\n/--\nTry to convert an `Iff` into an `Eq` by applying `iff_of_eq`.\nIf successful, returns the new goal, and otherwise returns the original `MVarId`.\n\nThis may be regarded as being a special case of `Lean.MVarId.liftReflToEq`, specifically for `Iff`.\n-/\ndef Lean.MVarId.iffOfEq (mvarId : MVarId) : MetaM MVarId := do\n let res ← observing? do\n let [mvarId] ← mvarId.apply (mkConst ``iff_of_eq []) | failure\n return mvarId\n return res.getD mvarId\n\n/--\nTry to convert an `Eq` into an `Iff` by applying `propext`.\nIf successful, then returns then new goal, otherwise returns the original `MVarId`.\n-/\ndef Lean.MVarId.propext (mvarId : MVarId) : MetaM MVarId := do\n let res ← observing? do\n -- Avoid applying `propext` if the target is not an equality of `Prop`s.\n -- We don't want a unification specializing `Sort _` to `Prop`.\n let tgt ← withReducible mvarId.getType'\n let some (ty, _, _) := tgt.eq? | failure\n guard ty.isProp\n let [mvarId] ← mvarId.apply (mkConst ``propext []) | failure\n return mvarId\n return res.getD mvarId\n\n/--\nTry to close the goal with using `proof_irrel_heq`. Returns whether or not it succeeds.\n\nWe need to be somewhat careful not to assign metavariables while doing this, otherwise we might\nspecialize `Sort _` to `Prop`.\n-/\ndef Lean.MVarId.proofIrrelHeq (mvarId : MVarId) : MetaM Bool :=\n mvarId.withContext do\n let res ← observing? do\n mvarId.checkNotAssigned `proofIrrelHeq\n let tgt ← withReducible mvarId.getType'\n let some (_, lhs, _, rhs) := tgt.heq? | failure\n -- Note: `mkAppM` uses `withNewMCtxDepth`, which we depend on to avoid unification.\n let pf ← mkAppM ``proof_irrel_heq #[lhs, rhs]\n mvarId.assign pf\n return true\n return res.getD false\n\n/--\nTry to close the goal using `Subsingleton.elim`. Returns whether or not it succeeds.\n\nWe are careful to apply `Subsingleton.elim` in a way that does not assign any metavariables.\nThis is to prevent the `Subsingleton Prop` instance from being used as justification to specialize\n`Sort _` to `Prop`.\n-/\ndef Lean.MVarId.subsingletonElim (mvarId : MVarId) : MetaM Bool :=\n mvarId.withContext do\n let res ← observing? do\n mvarId.checkNotAssigned `subsingletonElim\n let tgt ← withReducible mvarId.getType'\n let some (_, lhs, rhs) := tgt.eq? | failure\n -- Note: `mkAppM` uses `withNewMCtxDepth`, which we depend on to avoid unification.\n let pf ← mkAppM ``Subsingleton.elim #[lhs, rhs]\n mvarId.assign pf\n return true\n return res.getD false\n\n/--\nAsserts the given congruence theorem as fresh hypothesis, and then applies it.\nReturn the `fvarId` for the new hypothesis and the new subgoals.\n\nWe apply it with transparency settings specified by `Congr!.Config.transparency`.\n-/\nprivate def applyCongrThm?\n (config : Congr!.Config) (mvarId : MVarId) (congrThmType congrThmProof : Expr) :\n MetaM (List MVarId) := do\n trace[congr!] \"trying to apply congr lemma {congrThmType}\"\n try\n let mvarId ← mvarId.assert (← mkFreshUserName `h_congr_thm) congrThmType congrThmProof\n let (fvarId, mvarId) ← mvarId.intro1P\n let mvarIds ← withTransparency config.transparency <|\n mvarId.apply (mkFVar fvarId) { synthAssignedInstances := false }\n mvarIds.mapM fun mvarId => mvarId.tryClear fvarId\n catch e =>\n withTraceNode `congr! (fun _ => pure m!\"failed to apply congr lemma\") do\n trace[congr!] \"{e.toMessageData}\"\n throw e\n\n/--\nCreate a congruence lemma to prove that `HEq (f a₁ ... aₙ) (f' a₁' ... aₙ')`.\nEach argument produces a `HEq aᵢ aᵢ'` hypothesis, but we also supply these hypotheses the\nhypotheses that the preceding equalities have been proved (unlike in `mkHCongrWithArity`).\nThe first two arguments of the resulting theorem are for `f` and `f'`, followed by a proof\nof `f = f'`.\n\nWhen including hypotheses about previous hypotheses, we make use of dependency information\nand only include relevant equalities.\n\nThe argument `fty` denotes the type of `f`. Returns `(congrThmType, congrThmProof)`.\n\nFor the purpose of generating nicer lemmas that have a better chance at something like\n`to_additive` rewriting, this function supports generating lemmas where certain parameters\nare meant to be fixed.\n\n* If `fixedFun` is `false` (the default) then the lemma starts with three arguments for `f`, `f'`,\nand `h : f = f'`. Otherwise, if `fixedFun` is `true` then the lemma starts with just `f`.\n\n* If the `fixedParams` argument has `true` for a particular argument index, then this is a hint\nthat the congruence lemma may use the same parameter for both sides of the equality. There is\nno guarantee -- it respects it if the types are equal for that parameter (i.e., if the parameter\ndoes not depend on non-fixed parameters).\n-/\npartial def Congr!.mkHCongrThm (fType : Expr) (info : FunInfo)\n (fixedFun : Bool := false) (fixedParams : Array Bool := #[]) :\n MetaM (Expr × Expr) := do\n trace[congr!.synthesize] \"ftype: {fType}\"\n trace[congr!.synthesize] \"deps: {info.paramInfo.map (fun p => p.backDeps)}\"\n trace[congr!.synthesize] \"fixedFun={fixedFun}, fixedParams={fixedParams}\"\n doubleTelescope fType info.getArity fixedParams fun xs ys fixedParams => do\n trace[congr!.synthesize] \"xs = {xs}\"\n trace[congr!.synthesize] \"ys = {ys}\"\n trace[congr!.synthesize] \"computed fixedParams={fixedParams}\"\n let lctx := (← getLCtx) -- checkpoint of local context that only has parameters\n withLocalDeclD `f fType fun ef => withLocalDeclD `f' fType fun pef' => do\n let ef' := if fixedFun then ef else pef'\n withLocalDeclD `e (← mkEq ef ef') fun ee => do\n withNewEqs xs ys fixedParams fun eqs => do\n let fParams := if fixedFun then #[ef] else #[ef, ef', ee]\n let mut hs := fParams -- parameters to the basic congruence lemma\n let mut hs' := fParams -- parameters to the richer congruence lemma\n let mut vals' := fParams -- how to calculate the basic parameters from the richer ones\n for i in [0 : info.getArity] do\n hs := hs.push xs[i]!\n hs' := hs'.push xs[i]!\n vals' := vals'.push xs[i]!\n if let some (eq, eq', val) := eqs[i]! then\n -- Not a fixed argument\n hs := hs.push ys[i]! |>.push eq\n hs' := hs'.push ys[i]! |>.push eq'\n vals' := vals'.push ys[i]! |>.push val\n -- Generate the theorem with respect to the simpler hypotheses\n let congrType ← mkForallFVars hs (← mkHEq (mkAppN ef xs) (mkAppN ef' ys))\n trace[congr!.synthesize] \"simple congrType: {congrType}\"\n let some proof ← withLCtx lctx (← getLocalInstances) <| trySolve congrType\n | throwError \"Internal error when constructing congruence lemma proof\"\n -- At this point, `mkLambdaFVars hs' (mkAppN proof vals')` is the richer proof.\n -- We try to precompute some of the arguments using `trySolve`.\n let mut hs'' := #[] -- eq' parameters that are actually used beyond those in `fParams`\n let mut pfVars := #[] -- eq' parameters that can be solved for already\n let mut pfVals := #[] -- the values to use for these parameters\n for i in [0 : info.getArity] do\n hs'' := hs''.push xs[i]!\n if let some (_, eq', _) := eqs[i]! then\n -- Not a fixed argument\n hs'' := hs''.push ys[i]!\n let pf? ← withLCtx lctx (← getLocalInstances) <| trySolve (← inferType eq')\n if let some pf := pf? then\n pfVars := pfVars.push eq'\n pfVals := pfVals.push pf\n else\n hs'' := hs''.push eq'\n -- Take `proof`, abstract the pfVars and provide the solved-for proofs (as an\n -- optimization for proof term size) then abstract the remaining variables.\n -- The `usedOnly` probably has no affect.\n -- Note that since we are doing `proof.beta vals'` there is technically some quadratic\n -- complexity, but it shouldn't be too bad since they're some applications of just variables.\n let proof' ← mkLambdaFVars fParams (← mkLambdaFVars (usedOnly := true) hs''\n (mkAppN (← mkLambdaFVars pfVars (proof.beta vals')) pfVals))\n return (← inferType proof', proof')\nwhere\n /-- Similar to doing `forallBoundedTelescope` twice, but makes use of the `fixed` array, which\n is used as a hint for whether both variables should be the same. This is only a hint though,\n since we only respect it if the binding domains are equal.\n We affix `'` to the second list of variables, and all the variables are introduced\n with default binder info. Calls `k` with the xs, ys, and a revised `fixed` array -/\n doubleTelescope {α} (fty : Expr) (numVars : Nat) (fixed : Array Bool)\n (k : Array Expr → Array Expr → Array Bool → MetaM α) : MetaM α := do\n let rec loop (i : Nat)\n (ftyx ftyy : Expr) (xs ys : Array Expr) (fixed' : Array Bool) : MetaM α := do\n if i < numVars then\n let ftyx ← whnf ftyx\n let ftyy ← whnf ftyy\n unless ftyx.isForall do\n throwError \"doubleTelescope: function doesn't have enough parameters\"\n withLocalDeclD ftyx.bindingName! ftyx.bindingDomain! fun fvarx => do\n let ftyx' := ftyx.bindingBody!.instantiate1 fvarx\n if fixed.getD i false && ftyx.bindingDomain! == ftyy.bindingDomain! then\n -- Fixed: use the same variable for both\n let ftyy' := ftyy.bindingBody!.instantiate1 fvarx\n loop (i + 1) ftyx' ftyy' (xs.push fvarx) (ys.push fvarx) (fixed'.push true)\n else\n -- Not fixed: use different variables\n let yname := ftyy.bindingName!.appendAfter \"'\"\n withLocalDeclD yname ftyy.bindingDomain! fun fvary => do\n let ftyy' := ftyy.bindingBody!.instantiate1 fvary\n loop (i + 1) ftyx' ftyy' (xs.push fvarx) (ys.push fvary) (fixed'.push false)\n else\n k xs ys fixed'\n loop 0 fty fty #[] #[] #[]\n /-- Introduce variables for equalities between the arrays of variables. Uses `fixedParams`\n to control whether to introduce an equality for each pair. The array of triples passed to `k`\n consists of (1) the simple congr lemma HEq arg, (2) the richer HEq arg, and (3) how to\n compute 1 in terms of 2. -/\n withNewEqs {α} (xs ys : Array Expr) (fixedParams : Array Bool)\n (k : Array (Option (Expr × Expr × Expr)) → MetaM α) : MetaM α :=\n let rec loop (i : Nat) (eqs : Array (Option (Expr × Expr × Expr))) := do\n if i < xs.size then\n let x := xs[i]!\n let y := ys[i]!\n if fixedParams[i]! then\n loop (i+1) (eqs.push none)\n else\n let deps := info.paramInfo[i]!.backDeps.filterMap (fun j => eqs[j]!)\n let eq' ← mkForallFVars (deps.map fun (eq, _, _) => eq) (← mkEqHEq x y)\n withLocalDeclD ((`e).appendIndexAfter (i+1)) (← mkEqHEq x y) fun h =>\n withLocalDeclD ((`e').appendIndexAfter (i+1)) eq' fun h' =>\n let v := mkAppN h' (deps.map fun (_, _, val) => val)\n loop (i+1) (eqs.push (h, h', v))\n else\n k eqs\n loop 0 #[]\n /-- Given a type that is a bunch of equalities implying a goal (for example, a basic\n congruence lemma), prove it if possible. Basic congruence lemmas should be provable by this.\n There are some extra tricks for handling arguments to richer congruence lemmas. -/\n trySolveCore (mvarId : MVarId) : MetaM Unit := do\n -- First cleanup the context since we're going to do `substEqs` and we don't want to\n -- accidentally use variables not actually used by the theorem.\n let mvarId ← mvarId.cleanup\n let (_, mvarId) ← mvarId.intros\n let mvarId := (← mvarId.substEqs).getD mvarId\n try mvarId.refl; return catch _ => pure ()\n try mvarId.hrefl; return catch _ => pure ()\n if ← mvarId.proofIrrelHeq then return\n -- Make the goal be an eq and then try `Subsingleton.elim`\n let mvarId ← mvarId.heqOfEq\n if ← mvarId.subsingletonElim then return\n -- We have no more tricks.\n throwError \"was not able to solve for proof\"\n trySolve (ty : Expr) : MetaM (Option Expr) := observing? do\n let mvar ← mkFreshExprMVar ty\n trace[congr!.synthesize] \"trySolve {mvar.mvarId!}\"\n -- The proofs we generate shouldn't require unfolding anything.\n withReducible <| trySolveCore mvar.mvarId!\n trace[congr!.synthesize] \"trySolve success!\"\n let pf ← instantiateMVars mvar\n return pf\n\n/-- Returns whether or not it's reasonable to consider an equality between types `ty1` and `ty2`.\nThe heuristic is the following:\n\n- If `ty1` and `ty2` are in `Prop`, then yes.\n- If in whnf both `ty1` and `ty2` have the same head and if (recursively) it's reasonable to\n consider an equality between corresponding type arguments, then yes.\n- Otherwise, no.\n\nThis helps keep congr from going too far and generating hypotheses like `ℝ = ℤ`.\n\nTo keep things from going out of control, there is a `maxDepth`. Additionally, if we do the check\nwith `maxDepth = 0` then the heuristic answers \"no\". -/\ndef Congr!.possiblyEqualTypes (ty1 ty2 : Expr) (maxDepth : Nat := 5) : MetaM Bool :=\n match maxDepth with\n | 0 => return false\n | maxDepth + 1 => do\n -- Props are possibly equal\n if (← isProp ty1) && (← isProp ty2) then\n return true\n -- Types from different type universes are not possibly equal\n unless ← withNewMCtxDepth <| isDefEq (← inferType ty1) (← inferType ty2) do\n return false\n -- Now put the types into whnf, check they have the same head, and then recurse on arguments\n let ty1 ← whnfD ty1\n let ty2 ← whnfD ty2\n unless ← withNewMCtxDepth <| isDefEq ty1.getAppFn ty2.getAppFn do\n return false\n for arg1 in ty1.getAppArgs, arg2 in ty2.getAppArgs do\n if (← isType arg1) && (← isType arg2) then\n unless ← possiblyEqualTypes arg1 arg2 maxDepth do\n return false\n return true\n\n/--\nThis is like `Lean.MVarId.hcongr?` but (1) looks at both sides when generating the congruence lemma\nand (2) inserts additional hypotheses from equalities from previous arguments.\n\nIt uses `Congr!.mkHCongrThm` to generate the congruence lemmas.\n\nIf the goal is an `Eq`, uses `eq_of_heq` first.\n\nAs a backup strategy, it uses the LHS/RHS method like in `Lean.MVarId.congrSimp?`\n(where `Congr!.Config.preferLHS` determines which side to try first). This uses a particular side\nof the target, generates the congruence lemma, then tries applying it. This can make progress\nwith higher transparency settings. To help the unifier, in this mode it assumes both sides have the\nexact same function.\n-/\npartial\ndef Lean.MVarId.smartHCongr? (config : Congr!.Config) (mvarId : MVarId) :\n MetaM (Option (List MVarId)) :=\n mvarId.withContext do\n mvarId.checkNotAssigned `congr!\n commitWhenSome? do\n let mvarId ← mvarId.eqOfHEq\n let some (_, lhs, _, rhs) := (← withReducible mvarId.getType').heq? | return none\n if let some mvars ← loop mvarId 0 lhs rhs [] [] then\n return mvars\n -- The \"correct\" behavior failed. However, it's often useful\n -- to apply congruence lemmas while unfolding definitions, which is what the\n -- basic `congr` tactic does due to limitations in how congruence lemmas are generated.\n -- We simulate this behavior here by generating congruence lemmas for the LHS and RHS and\n -- then applying them.\n trace[congr!] \"Default smartHCongr? failed, trying LHS/RHS method\"\n let (fst, snd) := if config.preferLHS then (lhs, rhs) else (rhs, lhs)\n if let some mvars ← forSide mvarId fst then\n return mvars\n else if let some mvars ← forSide mvarId snd then\n return mvars\n else\n return none\nwhere\n loop (mvarId : MVarId) (numArgs : Nat) (lhs rhs : Expr) (lhsArgs rhsArgs : List Expr) :\n MetaM (Option (List MVarId)) :=\n match lhs.cleanupAnnotations, rhs.cleanupAnnotations with\n | .app f a, .app f' b => do\n if not (config.numArgsOk (numArgs + 1)) then\n return none\n let lhsArgs' := a :: lhsArgs\n let rhsArgs' := b :: rhsArgs\n -- We try to generate a theorem for the maximal number of arguments\n if let some mvars ← loop mvarId (numArgs + 1) f f' lhsArgs' rhsArgs' then\n return mvars\n -- That failing, we now try for the present number of arguments.\n if not config.partialApp && f.isApp && f'.isApp then\n -- It's a partial application on both sides though.\n return none\n -- The congruence generator only handles the case where both functions have\n -- definitionally equal types.\n unless ← withNewMCtxDepth <| isDefEq (← inferType f) (← inferType f') do\n return none\n let funDefEq ← withReducible <| withNewMCtxDepth <| isDefEq f f'\n if config.sameFun && not funDefEq then\n return none\n let info ← getFunInfoNArgs f (numArgs + 1)\n let mut fixed : Array Bool := #[]\n for larg in lhsArgs', rarg in rhsArgs' do\n if not config.typeEqs &&\n (← isType larg) && (← isType rarg) && not (← Congr!.possiblyEqualTypes larg rarg) then\n fixed := fixed.push true\n else\n fixed := fixed.push (← withReducible <| withNewMCtxDepth <| isDefEq larg rarg)\n let (congrThm, congrProof) ← Congr!.mkHCongrThm (← inferType f) info\n (fixedFun := funDefEq) (fixedParams := fixed)\n -- Now see if the congruence theorem actually applies in this situation by applying it!\n let (congrThm', congrProof') :=\n if funDefEq then\n (congrThm.bindingBody!.instantiate1 f, congrProof.beta #[f])\n else\n (congrThm.bindingBody!.bindingBody!.instantiateRev #[f, f'],\n congrProof.beta #[f, f'])\n observing? <| applyCongrThm? config mvarId congrThm' congrProof'\n | _, _ => return none\n forSide (mvarId : MVarId) (side : Expr) : MetaM (Option (List MVarId)) := do\n let side := side.cleanupAnnotations\n if not side.isApp then return none\n let numArgs := config.maxArgsFor side.getAppNumArgs\n if not config.partialApp && numArgs < side.getAppNumArgs then\n return none\n let mut f := side\n for _ in [:numArgs] do\n f := f.appFn!'\n let info ← getFunInfoNArgs f numArgs\n let mut fixed : Array Bool := #[]\n if not config.typeEqs then\n -- We need some strategy for fixed parameters to keep `forSide` from applying\n -- in cases where `Congr!.possiblyEqualTypes` suggested not to in the previous pass.\n for pinfo in info.paramInfo, arg in side.getAppArgs do\n if pinfo.isProp || not (← isType arg) then\n fixed := fixed.push false\n else if not pinfo.backDeps.isEmpty then\n -- We can't immediately say such an equality is a bad idea, because the argument might\n -- be something like `Fin n`.\n -- Though, if the argument isn't explicit it probably would be surprising to generate\n -- an equality.\n fixed := fixed.push (pinfo.binderInfo != .default)\n else\n fixed := fixed.push true\n let (congrThm, congrProof) ←\n Congr!.mkHCongrThm (← inferType f) info (fixedFun := true) (fixedParams := fixed)\n let congrThm' := congrThm.bindingBody!.instantiate1 f\n let congrProof' := congrProof.beta #[f]\n observing? <| applyCongrThm? config mvarId congrThm' congrProof'\n\n/--\nLike `Lean.MVarId.congr?` but instead of using only the congruence lemma associated to the LHS,\nit tries the RHS too, in the order specified by `config.preferLHS`.\n\nIt uses `Lean.Meta.mkCongrSimp?` to generate a congruence lemma, like in the `congr` tactic.\n\nApplies the congruence generated congruence lemmas according to `config`.\n-/\ndef Lean.MVarId.congrSimp? (config : Congr!.Config) (mvarId : MVarId) :\n MetaM (Option (List MVarId)) :=\n mvarId.withContext do\n unless config.useCongrSimp do return none\n mvarId.checkNotAssigned `congrSimp?\n let some (_, lhs, rhs) := (← withReducible mvarId.getType').eq? | return none\n let (fst, snd) := if config.preferLHS then (lhs, rhs) else (rhs, lhs)\n if let some mvars ← forSide mvarId fst then\n return mvars\n else if let some mvars ← forSide mvarId snd then\n return mvars\n else\n return none\nwhere\n forSide (mvarId : MVarId) (side : Expr) : MetaM (Option (List MVarId)) :=\n commitWhenSome? do\n let side := side.cleanupAnnotations\n if not side.isApp then return none\n let numArgs := config.maxArgsFor side.getAppNumArgs\n if not config.partialApp && numArgs < side.getAppNumArgs then\n return none\n let mut f := side\n for _ in [:numArgs] do\n f := f.appFn!'\n let some congrThm ← mkCongrSimpNArgs f numArgs\n | return none\n observing? <| applyCongrThm? config mvarId congrThm.type congrThm.proof\n /-- Like `mkCongrSimp?` but takes in a specific arity. -/\n mkCongrSimpNArgs (f : Expr) (nArgs : Nat) : MetaM (Option CongrTheorem) := do\n let f := (← instantiateMVars f).cleanupAnnotations\n let info ← getFunInfoNArgs f nArgs\n mkCongrSimpCore? f info\n (← getCongrSimpKinds f info) (subsingletonInstImplicitRhs := false)\n\n/--\nTry applying user-provided congruence lemmas. If any are applicable,\nreturns a list of new goals.\n\nTries a congruence lemma associated to the LHS and then, if that failed, the RHS.\n-/\ndef Lean.MVarId.userCongr? (config : Congr!.Config) (mvarId : MVarId) :\n MetaM (Option (List MVarId)) :=\n mvarId.withContext do\n mvarId.checkNotAssigned `userCongr?\n let some (lhs, rhs) := (← withReducible mvarId.getType').eqOrIff? | return none\n let (fst, snd) := if config.preferLHS then (lhs, rhs) else (rhs, lhs)\n if let some mvars ← forSide fst then\n return mvars\n else if let some mvars ← forSide snd then\n return mvars\n else\n return none\nwhere\n forSide (side : Expr) : MetaM (Option (List MVarId)) := do\n let side := side.cleanupAnnotations\n if not side.isApp then return none\n let some name := side.getAppFn.constName? | return none\n let congrTheorems := (← getSimpCongrTheorems).get name\n -- Note: congruence theorems are provided in decreasing order of priority.\n for congrTheorem in congrTheorems do\n let res ← observing? do\n let cinfo ← getConstInfo congrTheorem.theoremName\n let us ← cinfo.levelParams.mapM fun _ => mkFreshLevelMVar\n let proof := mkConst congrTheorem.theoremName us\n let ptype ← instantiateTypeLevelParams cinfo us\n applyCongrThm? config mvarId ptype proof\n if let some mvars := res then\n return mvars\n return none\n\n/-- Helper theorem for `Lean.MVar.liftReflToEq`. -/\ntheorem Lean.MVarId.rel_of_eq_and_refl {R : α → α → Prop} (hxy : x = y) (h : R x x) :\n R x y := hxy ▸ h\n\n/--\nUse a `refl`-tagged lemma to convert the goal into an `Eq`. If this can't be done, returns\nthe original `MVarId`.\n-/\ndef Lean.MVarId.liftReflToEq (mvarId : MVarId) : MetaM MVarId := do\n mvarId.checkNotAssigned `liftReflToEq\n let tgt ← withReducible mvarId.getType'\n let .app (.app rel _) _ := tgt | return mvarId\n if rel.isAppOf `Eq then\n -- No need to lift Eq to Eq\n return mvarId\n let reflLemmas ← (Mathlib.Tactic.reflExt.getState (← getEnv)).getMatch rel\n for lem in reflLemmas do\n let res ← observing? do\n -- First create an equality relating the LHS and RHS\n -- and reduce the goal to proving that LHS is related to LHS.\n let [mvarIdEq, mvarIdR] ←\n mvarId.apply (← mkConstWithFreshMVarLevels ``Lean.MVarId.rel_of_eq_and_refl)\n | failure\n -- Then fill in the proof of the latter by reflexivity.\n let [] ← mvarIdR.apply (← mkConstWithFreshMVarLevels lem) | failure\n return mvarIdEq\n if let some mvarId := res then\n return mvarId\n return mvarId\n\n/--\nTry to apply `pi_congr`. This is similar to `Lean.MVar.congrImplies?`.\n-/\ndef Lean.MVarId.congrPi? (mvarId : MVarId) : MetaM (Option (List MVarId)) :=\n observing? do withReducible <| mvarId.apply (← mkConstWithFreshMVarLevels `pi_congr)\n\n/--\nTry to apply `funext`, but only if it is an equality of two functions where at least one is\na lambda expression.\n\nOne thing this check prevents is accidentally applying `funext` to a set equality, but also when\ndoing congruence we don't want to apply `funext` unnecessarily.\n-/\ndef Lean.MVarId.obviousFunext? (mvarId : MVarId) : MetaM (Option (List MVarId)) :=\n mvarId.withContext <| observing? do\n let some (_, lhs, rhs) := (← withReducible mvarId.getType').eq? | failure\n if not lhs.cleanupAnnotations.isLambda && not rhs.cleanupAnnotations.isLambda then failure\n mvarId.apply (← mkConstWithFreshMVarLevels ``funext)\n\n/--\nTry to apply `Function.hfunext`, returning the new goals if it succeeds.\nLike `Lean.MVarId.obviousFunext?`, we only do so if at least one side of the `HEq` is a lambda.\nThis prevents unfolding of things like `Set`.\n\nNeed to have `Mathlib.Logic.Function.Basic` imported for this to succeed.\n-/\ndef Lean.MVarId.obviousHfunext? (mvarId : MVarId) : MetaM (Option (List MVarId)) :=\n mvarId.withContext <| observing? do\n let some (_, lhs, _, rhs) := (← withReducible mvarId.getType').heq? | failure\n if not lhs.cleanupAnnotations.isLambda && not rhs.cleanupAnnotations.isLambda then failure\n mvarId.apply (← mkConstWithFreshMVarLevels `Function.hfunext)\n\n/--\nTry to apply `Subsingleton.helim` if the goal is a `HEq`. Tries synthesizing a `Subsingleton`\ninstance for both the LHS and the RHS.\n\nIf successful, this reduces proving `@HEq α x β y` to proving `α = β`.\n-/\ndef Lean.MVarId.subsingletonHelim? (mvarId : MVarId) : MetaM (Option (List MVarId)) :=\n mvarId.withContext <| observing? do\n mvarId.checkNotAssigned `subsingletonHelim\n let some (α, lhs, β, rhs) := (← withReducible mvarId.getType').heq? | failure\n let eqmvar ← mkFreshExprSyntheticOpaqueMVar (← mkEq α β) (← mvarId.getTag)\n -- First try synthesizing using the left-hand side for the Subsingleton instance\n if let some pf ← observing? (mkAppM ``Subsingleton.helim #[eqmvar, lhs, rhs]) then\n mvarId.assign pf\n return [eqmvar.mvarId!]\n let eqsymm ← mkAppM ``Eq.symm #[eqmvar]\n -- Second try synthesizing using the right-hand side for the Subsingleton instance\n if let some pf ← observing? (mkAppM ``Subsingleton.helim #[eqsymm, rhs, lhs]) then\n mvarId.assign (← mkAppM ``HEq.symm #[pf])\n return [eqmvar.mvarId!]\n failure\n\n/--\nA list of all the congruence strategies used by `Lean.MVarId.congrCore!`.\n-/\ndef Lean.MVarId.congrPasses! :\n List (String × (Congr!.Config → MVarId → MetaM (Option (List MVarId)))) :=\n [(\"user congr\", userCongr?),\n (\"hcongr lemma\", smartHCongr?),\n (\"congr simp lemma\", congrSimp?),\n (\"Subsingleton.helim\", fun _ => subsingletonHelim?),\n (\"obvious funext\", fun _ => obviousFunext?),\n (\"obvious hfunext\", fun _ => obviousHfunext?),\n (\"congr_implies\", fun _ => congrImplies?),\n (\"congr_pi\", fun _ => congrPi?)]\n\n/--\nDoes `Lean.MVarId.intros` but then cleans up the introduced hypotheses, removing anything\nthat is trivial.\n\nCleaning up includes:\n- deleting hypotheses of the form `HEq x x`, `x = x`, and `x ↔ x`.\n- deleting Prop hypotheses that are already in the local context.\n- converting `HEq x y` to `x = y` if possible.\n- converting `x = y` to `x ↔ y` if possible.\n-/\npartial\ndef Lean.MVarId.introsClean (mvarId : MVarId) : MetaM (Array FVarId × MVarId) :=\n loop #[] mvarId\nwhere\n fvarEqOfHEq (mvarId : MVarId) (fvarId : FVarId) : MetaM (Option (FVarId × MVarId)) :=\n observing? <| mvarId.withContext do\n let pf ← mkEqOfHEq (.fvar fvarId)\n let decl ← fvarId.getDecl\n let mvarId ← mvarId.assert decl.userName (← inferType pf) pf\n let (fvarId', mvarId) ← mvarId.intro1\n return (fvarId', ← mvarId.clear fvarId)\n fvarIffOfEq (mvarId : MVarId) (fvarId : FVarId) : MetaM (Option (FVarId × MVarId)) :=\n observing? <| mvarId.withContext do\n let pf ← mkIffOfEq (.fvar fvarId)\n let decl ← fvarId.getDecl\n let mvarId ← mvarId.assert decl.userName (← inferType pf) pf\n let (fvarId', mvarId) ← mvarId.intro1\n return (fvarId', ← mvarId.clear fvarId)\n loop (fvars : Array FVarId) (mvarId : MVarId) : MetaM (Array FVarId × MVarId) :=\n mvarId.withContext do\n let ty ← withReducible <| mvarId.getType'\n if ty.isForall then\n let (fvarId, mvarId) ← mvarId.intro1\n if not ty.isArrow then\n return ← loop (fvars.push fvarId) mvarId\n let (fvarId, mvarId) := (← fvarEqOfHEq mvarId fvarId).getD (fvarId, mvarId)\n let (fvarId, mvarId) := (← fvarIffOfEq mvarId fvarId).getD (fvarId, mvarId)\n mvarId.withContext do\n let ty ← instantiateMVars (← fvarId.getType)\n if (← isTrivialType ty)\n || (← getLCtx).any (fun decl => decl.fvarId != fvarId && decl.type == ty) then\n let mvarId ← mvarId.clear fvarId\n return ← loop fvars mvarId\n return ← loop (fvars.push fvarId) mvarId\n else\n return (fvars, mvarId)\n isTrivialType (ty : Expr) : MetaM Bool := do\n let ty ← instantiateMVars ty\n unless ← Meta.isProp ty do\n return false\n if let some (lhs, rhs) := ty.eqOrIff? then\n if lhs.cleanupAnnotations == rhs.cleanupAnnotations then\n return true\n if let some (α, lhs, β, rhs) := ty.heq? then\n if α.cleanupAnnotations == β.cleanupAnnotations\n && lhs.cleanupAnnotations == rhs.cleanupAnnotations then\n return true\n return false\n\n/-- Convert a goal into an `Eq` goal if possible (since we have a better shot at those).\nAlso try to dispatch the goal using an assumption, `Subsingleton.Elim`, or definitional equality. -/\ndef Lean.MVarId.preCongr! (mvarId : MVarId) : MetaM (Option MVarId) := do\n -- Congr lemmas might have created additional hypotheses.\n let (_, mvarId) ← mvarId.introsClean\n -- Next, turn `HEq` and `Iff` into `Eq`\n let mvarId ← mvarId.heqOfEq\n -- This is a good time to check whether we have a relevant hypothesis.\n if ← mvarId.assumptionCore then return none\n let mvarId ← mvarId.iffOfEq\n -- Now try definitional equality. No need to try `mvarId.hrefl` since we already did `heqOfEq`.\n -- We allow synthetic opaque metavariables to be assigned to fill in `x = _` goals that might\n -- appear (for example, due to using `convert` with placeholders).\n try withAssignableSyntheticOpaque mvarId.refl; return none catch _ => pure ()\n -- Now we go for (heterogenous) equality via subsingleton considerations\n if ← mvarId.subsingletonElim then return none\n if ← mvarId.proofIrrelHeq then return none\n return some mvarId\n\ndef Lean.MVarId.congrCore! (config : Congr!.Config) (mvarId : MVarId) :\n MetaM (Option (List MVarId)) := do\n /- We do `liftReflToEq` here rather than in `preCongr!` since we don't want it to stick\n if there are no relevant congr lemmas. -/\n mvarId.checkNotAssigned `congr!\n let s ← saveState\n let mvarId ← mvarId.liftReflToEq\n for (passName, pass) in congrPasses! do\n try\n if let some mvarIds ← pass config mvarId then\n trace[congr!] \"pass succeded: {passName}\"\n return mvarIds\n catch e =>\n throwTacticEx `congr! mvarId\n m!\"internal error in congruence pass {passName}, {e.toMessageData}\"\n if ← mvarId.isAssigned then\n throwTacticEx `congr! mvarId\n s!\"congruence pass {passName} assigned metavariable but failed\"\n restoreState s\n trace[congr!] \"no passes succeeded\"\n return none\n\n/-- A pass to clean up after `Lean.MVarId.preCongr!` and `Lean.MVarId.congrCore!`. -/\ndef Lean.MVarId.postCongr! (option : Congr!.Config) (mvarId : MVarId) : MetaM (Option MVarId) := do\n let some mvarId ← mvarId.preCongr! | return none\n -- Convert `p = q` to `p ↔ q`, which is likely the more useful form:\n let mvarId ← mvarId.propext\n if ← mvarId.assumptionCore then return none\n if option.etaExpand then\n if let some (_, lhs, rhs) := (← withReducible mvarId.getType').eq? then\n let lhs' ← Meta.etaExpand lhs\n let rhs' ← Meta.etaExpand rhs\n return ← mvarId.change (← mkEq lhs' rhs')\n return mvarId\n\n/-- A more insistent version of `Lean.MVarId.congrN`.\nSee the documentation on the `congr!` syntax.\n\nThe `depth?` argument controls the depth of the recursion. If `none`, then it uses a reasonably\nlarge bound that is linear in the expression depth. -/\ndef Lean.MVarId.congrN! (mvarId : MVarId)\n (depth? : Option Nat := none) (config : Congr!.Config := {}) : MetaM (List MVarId) := do\n let ty ← withReducible <| mvarId.getType'\n -- A reasonably large yet practically bounded default recursion depth.\n let defaultDepth := max 1000000 (8 * (1 + ty.approxDepth.toNat))\n let depth := depth?.getD defaultDepth\n let (_, s) ← go depth depth mvarId |>.run #[]\n return s.toList\nwhere\n post (mvarId : MVarId) : StateRefT (Array MVarId) MetaM Unit := do\n let some mvarId ← mvarId.postCongr! config\n | do trace[congr!] \"Dispatched goal by post-processing step.\"\n return\n modify (·.push mvarId)\n go (depth : Nat) (n : Nat) (mvarId : MVarId) : StateRefT (Array MVarId) MetaM Unit := do\n let some mvarId ← withTransparency config.preTransparency mvarId.preCongr! | return\n match n with\n | 0 =>\n trace[congr!] \"At level {depth - n}, doing post-processing. {mvarId}\"\n post mvarId\n | n + 1 =>\n trace[congr!] \"At level {depth - n}, trying congrCore!. {mvarId}\"\n let some mvarIds ← mvarId.congrCore! config\n | post mvarId\n mvarIds.forM (go depth n)\n\nnamespace Congr!\n\ndeclare_config_elab elabConfig Config\n\n/--\nEquates pieces of the left-hand side of a goal to corresponding pieces of the right-hand side by\nrecursively applying congruence lemmas. For example, with `⊢ f as = g bs` we could get\ntwo goals `⊢ f = g` and `⊢ as = bs`.\n\nThe `congr!` tactic is similar to `congr` but is more insistent in trying to equate left-hand sides\nto right-hand sides of goals. Here is a list of things it can try:\n\n- If `R` in `⊢ R x y` is a reflexive relation, it will convert the goal to `⊢ x = y` if possible.\n The list of reflexive relations is maintained using the `@[refl]` attribute.\n As a special case, `⊢ p ↔ q` is converted to `⊢ p = q` during congruence processing and then\n returned to `⊢ p ↔ q` form at the end.\n\n- If there is a user congruence lemma associated to the goal (for instance, a `@[congr]`-tagged\n lemma applying to `⊢ List.map f xs = List.map g ys`), then it will use that.\n\n- It uses a congruence lemma generator at least as capable as the one used by `congr` and `simp`.\n If there is a subexpression that can be rewritten by `simp`, then `congr!` should be able\n to generate an equality for it.\n\n- It uses `implies_congr` and `pi_congr` to do congruences of pi types.\n\n- Before applying congruences, it will run the `intros` tactic automatically.\n The introduced variables can be given names using the `rename_i` tactic as needed.\n This helps when user congruence lemmas are applied, since they often provide\n additional hypotheses.\n\n- When there is an equality between functions, so long as at least one is obviously a lambda, we\n apply `funext` or `Function.hfunext`, which allows for congruence of lambda bodies.\n\n- It can try to close goals using a few strategies, including checking\n definitional equality, trying to apply `Subsingleton.elim` or `proof_irrel_heq`, and using the\n `assumption` tactic.\n\nThe optional parameter is the depth of the recursive applications.\nThis is useful when `congr!` is too aggressive in breaking down the goal.\nFor example, given `⊢ f (g (x + y)) = f (g (y + x))`,\n`congr!` produces the goals `⊢ x = y` and `⊢ y = x`,\nwhile `congr! 2` produces the intended `⊢ x + y = y + x`.\n\nThe `congr!` tactic also takes a configuration option, for example\n```lean\ncongr! (config := {transparency := .default}) 2\n```\nThis overrides the default, which is to apply congruence lemmas at reducible transparency.\n\nThe `congr!` tactic is aggressive with equating two sides of everything. There is a predefined\nconfiguration that uses a different strategy:\nTry\n```lean\ncongr! (config := .unfoldSameFun)\n```\nThis only allows congruences between functions applications of definitionally equal functions,\nand it applies congruence lemmas at default transparency (rather than just reducible).\nThis is somewhat like `congr`.\n\nSee `Congr!.Config` for all options.\n-/\nsyntax (name := congr!) \"congr!\" (Parser.Tactic.config)? (num)? : tactic\n\nelab_rules : tactic\n| `(tactic| congr! $[$cfg:config]? $[$n]?) => do\n let config ← elabConfig (mkOptionalNode cfg)\n liftMetaTactic fun g ↦\n let depth := n.map (·.getNat)\n g.congrN! depth config\n\nend Congr!\n", "meta": {"author": "leanprover-community", "repo": "mathlib4", "sha": "b9a0a30342ca06e9817e22dbe46e75fc7f435500", "save_path": "github-repos/lean/leanprover-community-mathlib4", "path": "github-repos/lean/leanprover-community-mathlib4/mathlib4-b9a0a30342ca06e9817e22dbe46e75fc7f435500/Mathlib/Tactic/Congr!.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.21206879439743004, "lm_q2_score": 0.03789242730866432, "lm_q1q2_score": 0.008035801376140697}} {"text": "import phase2.flexible_completion\nimport phase2.reduction\nimport phase2.refine\n\nopen quiver set sum with_bot\nopen_locale classical\n\nuniverse u\n\nnamespace con_nf\n\nnamespace struct_approx\nvariables [params.{u}] {α : Λ} [position_data.{}] [phase_2_assumptions α] {β : Iic α}\n {γ : Iic α} {δ ε : Iio α} (hδ : (δ : Λ) < γ) (hε : (ε : Λ) < γ) (hδε : δ ≠ ε)\n {A : path (β : type_index) γ} {t : tangle δ}\n (H : hypothesis ⟨inr (f_map (coe_ne_coe.mpr $ coe_ne' hδε) t).to_near_litter,\n (A.cons (coe_lt hε)).cons (bot_lt_coe _)⟩)\n\n/-- The inductive hypothesis used for proving freedom of action:\nEvery free approximation exactly approximates some allowable permutation. -/\ndef foa_ih (β : Iic α) : Prop :=\n∀ (π₀ : struct_approx β), π₀.free → ∃ (π : allowable β), π₀.exactly_approximates π.to_struct_perm\n\n/-- A proof-relevant statement that `L` is `A`-inflexible (excluding `ε = ⊥`). -/\nstructure inflexible_coe (L : litter) (A : extended_index β) :=\n(γ : Iic α) (δ ε : Iio α) (hδ : (δ : Λ) < γ) (hε : (ε : Λ) < γ) (hδε : δ ≠ ε)\n(B : quiver.path (β : type_index) γ) (t : tangle δ)\n(hL : L = f_map (coe_ne_coe.mpr $ coe_ne' hδε) t)\n(hA : A = (B.cons (coe_lt hε)).cons (bot_lt_coe _))\n\ninstance (L : litter) (A : extended_index β) : subsingleton (inflexible_coe L A) :=\nbegin\n constructor,\n rintros ⟨γ₁, δ₁, ε₁, hδ₁, hε₁, hδε₁, B₁, t₁, rfl, rfl⟩\n ⟨γ₂, δ₂, ε₂, hδ₂, hε₂, hδε₂, B₂, t₂, hL₂, hA₂⟩,\n cases subtype.coe_injective (coe_eq_coe.mp (path.obj_eq_of_cons_eq_cons hA₂)),\n cases subtype.coe_injective (coe_eq_coe.mp (path.obj_eq_of_cons_eq_cons\n (path.heq_of_cons_eq_cons hA₂).eq)),\n cases (path.heq_of_cons_eq_cons (path.heq_of_cons_eq_cons hA₂).eq).eq,\n have h₁ := f_map_β (coe_ne_coe.mpr $ coe_ne' hδε₁) t₁,\n have h₂ := f_map_β (coe_ne_coe.mpr $ coe_ne' hδε₂) t₂,\n rw [hL₂, h₂] at h₁,\n cases subtype.coe_injective (coe_eq_coe.mp h₁),\n cases f_map_injective _ hL₂,\n refl,\nend\n\n/-- A proof-relevant statement that `L` is `A`-inflexible, where `δ = ⊥`. -/\nstructure inflexible_bot (L : litter) (A : extended_index β) :=\n(γ : Iic α) (ε : Iio α) (hε : (ε : Λ) < γ)\n(B : quiver.path (β : type_index) γ) (a : atom)\n(hL : L = f_map (show (⊥ : type_index) ≠ (ε : Λ), from bot_ne_coe) a)\n(hA : A = (B.cons (coe_lt hε)).cons (bot_lt_coe _))\n\ninstance (L : litter) (A : extended_index β) : subsingleton (inflexible_bot L A) :=\nbegin\n constructor,\n rintros ⟨γ₁, ε₁, hε₁, B₁, a₁, rfl, rfl⟩ ⟨γ₂, ε₂, hε₂, B₂, a₂, hL₂, hA₂⟩,\n cases subtype.coe_injective (coe_eq_coe.mp (path.obj_eq_of_cons_eq_cons hA₂)),\n cases subtype.coe_injective (coe_eq_coe.mp (path.obj_eq_of_cons_eq_cons\n (path.heq_of_cons_eq_cons hA₂).eq)),\n cases (path.heq_of_cons_eq_cons (path.heq_of_cons_eq_cons hA₂).eq).eq,\n cases f_map_injective _ hL₂,\n refl,\nend\n\nlemma inflexible_bot_inflexible_coe {L : litter} {A : extended_index β} :\n inflexible_bot L A → inflexible_coe L A → false :=\nbegin\n rintros ⟨γ₁, ε₁, hε₁, B₁, a₁, rfl, rfl⟩ ⟨γ₂, δ₂, ε₂, hδ₂, hε₂, hδε₂, B₂, t₂, hL₂, hA₂⟩,\n have h₁ := f_map_β (show (⊥ : type_index) ≠ (ε₁ : Λ), from bot_ne_coe) a₁,\n have h₂ := f_map_β (coe_ne_coe.mpr $ coe_ne' hδε₂) t₂,\n rw [hL₂, h₂] at h₁,\n cases h₁,\nend\n\nlemma inflexible_coe.δ_lt_β {L : litter} {A : extended_index β} (h : inflexible_coe L A) :\n (h.δ : Λ) < β :=\nh.hδ.trans_le (show _, from coe_le_coe.mp (le_of_path h.B))\n\nlemma inflexible_bot.constrains {L : litter} {A : extended_index β} (h : inflexible_bot L A) :\n relation.trans_gen (constrains α β)\n (inl h.a, (h.B.cons (bot_lt_coe _))) (inr L.to_near_litter, A) :=\nbegin\n have := constrains.f_map_bot h.hε h.B h.a,\n rw [← h.hL, ← h.hA] at this,\n exact relation.trans_gen.single this,\nend\n\nclass freedom_of_action_hypothesis (β : Iic α) :=\n(freedom_of_action_of_lt : ∀ γ < β, foa_ih γ)\n\nexport freedom_of_action_hypothesis (freedom_of_action_of_lt)\n\nvariable [freedom_of_action_hypothesis β]\n\n/-- For the support map of `t`, we use everything that constrains `t`. -/\ndef inflexible_support {L : litter} {A : extended_index β} (h : inflexible_coe L A) :\n set (support_condition h.δ) :=\n(λ c, (c.1, (h.B.cons (coe_lt h.hδ)).comp c.2)) ⁻¹'\n{c | relation.trans_gen (constrains α β) c\n (inr (f_map (coe_ne_coe.mpr $ coe_ne' h.hδε) h.t).to_near_litter,\n (h.B.cons (coe_lt h.hε)).cons (bot_lt_coe _))}\n\nlemma inflexible_support_small {L : litter} {A : extended_index β} (h : inflexible_coe L A) :\n small (inflexible_support h) :=\nbegin\n refine lt_of_le_of_lt (cardinal.mk_preimage_of_injective _ _ _) _,\n { intros c d h,\n simp only [prod.mk.inj_iff, path.comp_inj_right] at h,\n exact prod.ext h.1 h.2, },\n { refine small.mono _ (reduction_small' α (small_singleton\n (inr (f_map (coe_ne_coe.mpr $ coe_ne' h.hδε) h.t).to_near_litter,\n (h.B.cons (coe_lt h.hε)).cons (bot_lt_coe _)))),\n intros c hc,\n exact ⟨_, rfl, hc.to_refl⟩, },\nend\n\nlemma inflexible_support_supports_f_map {π : allowable β} {γ : Iic α} {δ ε : Iio α}\n (hδ : (δ : Λ) < γ) (hε : (ε : Λ) < γ) (hδε : δ ≠ ε)\n {B : path (β : type_index) γ} {t : tangle δ}\n (hπ : ∀ ⦃a : support_condition ↑β⦄,\n a ≺[α] (inr (f_map (coe_ne_coe.mpr $ coe_ne' hδε) t).to_near_litter,\n (B.cons (coe_lt hε)).cons (bot_lt_coe _)) → π • a = a)\n (hc : (f_map (coe_ne_coe.mpr $ coe_ne' hδε) t).to_near_litter.is_litter →\n inflexible α (f_map (coe_ne_coe.mpr $ coe_ne' hδε) t)\n ((B.cons (coe_lt hε)).cons (bot_lt_coe _))) :\n (allowable.derivative (show path ((β : Iic_index α) : type_index) (ε : Iic_index α),\n from B.cons (coe_lt hε)) π : allowable (ε : Iic_index α)) •\n f_map (coe_ne_coe.mpr $ coe_ne' hδε) t =\n f_map (coe_ne_coe.mpr $ coe_ne' hδε) t :=\nbegin\n have h₁ := allowable.derivative_cons (show path ((β : Iic_index α) : type_index)\n (γ : Iic_index α), from B) (coe_lt hε),\n have h₂ := @smul_f_map _ _ _ _ (γ : Iic_index α) (δ : Iio_index α) ε\n (coe_lt hδ) (coe_lt hε) (Iio.coe_injective.ne hδε)\n (allowable.derivative (show path ((β : Iic_index α) : type_index)\n (γ : Iic_index α), from B) π) t,\n rw h₁,\n refine h₂.trans (congr_arg _ _),\n refine (designated_support t).supports _ (λ c hc, _),\n have := congr_arg prod.fst (hπ (constrains.f_map hδ hε hδε B t c hc)),\n obtain ⟨c, C⟩ := c,\n refine prod.ext (eq.trans _ this) rfl,\n rw ← allowable.to_struct_perm_smul at this ⊢,\n rw [← phase_2_assumptions.allowable_derivative_eq, ← allowable.derivative_to_struct_perm],\n change _ • _ = _ • _,\n simp only [struct_perm.derivative_derivative, path.comp_cons, path.comp_nil],\nend\n\n-- TODO: Does `litter_map_injective` follow from `atom_mem`?\nstructure hypothesis_injective_inflexible {L : litter} {A : extended_index β}\n (H : hypothesis ⟨inr L.to_near_litter, A⟩) (h : inflexible_coe L A) : Prop :=\n(atom_map_injective : ∀ a b B\n (ha : (inl a, B) ∈ inflexible_support h) (hb : (inl b, B) ∈ inflexible_support h),\n H.atom_image a ((h.B.cons (coe_lt h.hδ)).comp B)\n (by rwa [inflexible_support, ← h.hL, ← h.hA] at ha) =\n H.atom_image b ((h.B.cons (coe_lt h.hδ)).comp B)\n (by rwa [inflexible_support, ← h.hL, ← h.hA] at hb) → a = b)\n(litter_map_injective : ∀ (L₁ L₂ : litter) B\n (hL₁ : (inr L₁.to_near_litter, B) ∈ inflexible_support h)\n (hL₂ : (inr L₂.to_near_litter, B) ∈ inflexible_support h),\n (H.near_litter_image L₁.to_near_litter ((h.B.cons (coe_lt h.hδ)).comp B)\n (by rwa [inflexible_support, ← h.hL, ← h.hA] at hL₁) ∩\n H.near_litter_image L₂.to_near_litter ((h.B.cons (coe_lt h.hδ)).comp B)\n (by rwa [inflexible_support, ← h.hL, ← h.hA] at hL₂) : set atom).nonempty → L₁ = L₂)\n(atom_mem : ∀ a (L : litter) B\n (ha : (inl a, B) ∈ inflexible_support h) (hL : (inr L.to_near_litter, B) ∈ inflexible_support h),\n a ∈ litter_set L ↔\n H.atom_image a ((h.B.cons (coe_lt h.hδ)).comp B)\n (by rwa [inflexible_support, ← h.hL, ← h.hA] at ha) ∈\n H.near_litter_image L.to_near_litter ((h.B.cons (coe_lt h.hδ)).comp B)\n (by rwa [inflexible_support, ← h.hL, ← h.hA] at hL))\n(map_flexible : ∀ (L : litter) B (hL₁ : (inr L.to_near_litter, B) ∈ inflexible_support h)\n (hL₂ : flexible α L B),\n flexible α (H.near_litter_image L.to_near_litter ((h.B.cons (coe_lt h.hδ)).comp B)\n (by rwa [inflexible_support, ← h.hL, ← h.hA] at hL₁)).1 B)\n\ndef hypothesised_weak_struct_approx {L : litter} {A : extended_index β}\n (H : hypothesis ⟨inr L.to_near_litter, A⟩) (h : inflexible_coe L A)\n (hH : hypothesis_injective_inflexible H h) : weak_struct_approx h.δ :=\nλ B, {\n atom_map := λ a, ⟨(inl a, B) ∈ inflexible_support h,\n λ ha, H.atom_image a ((h.B.cons (coe_lt h.hδ)).comp B)\n (by rwa [inflexible_support, ← h.hL, ← h.hA] at ha)⟩,\n litter_map := λ L, ⟨(inr L.to_near_litter, B) ∈ inflexible_support h,\n λ hL, H.near_litter_image L.to_near_litter ((h.B.cons (coe_lt h.hδ)).comp B)\n (by rwa [inflexible_support, ← h.hL, ← h.hA] at hL)⟩,\n atom_map_dom_small := begin\n simp only [pfun.dom_mk],\n refine lt_of_le_of_lt _ (inflexible_support_small h),\n refine ⟨⟨λ a, ⟨_, a.prop⟩, λ a b h, _⟩⟩,\n simp only [subtype.mk_eq_mk, prod.mk.inj_iff, subtype.coe_inj, eq_self_iff_true, and_true] at h,\n exact h,\n end,\n litter_map_dom_small := begin\n simp only [pfun.dom_mk],\n refine lt_of_le_of_lt _ (inflexible_support_small h),\n refine ⟨⟨λ L, ⟨_, L.prop⟩, λ L₁ L₂ h, _⟩⟩,\n simp only [subtype.mk_eq_mk, prod.mk.inj_iff, eq_self_iff_true, and_true,\n litter.to_near_litter_injective.eq_iff, subtype.coe_inj] at h,\n exact h,\n end,\n atom_map_injective := λ a b ha hb, hH.atom_map_injective a b B ha hb,\n litter_map_injective := λ L₁ L₂ hL₁ hL₂, hH.litter_map_injective L₁ L₂ B hL₁ hL₂,\n atom_mem := λ a ha L hL, hH.atom_mem a L B ha hL,\n}\n\n@[simp] lemma hypothesised_weak_struct_approx_atom_map {L : litter} {A : extended_index β}\n (H : hypothesis ⟨inr L.to_near_litter, A⟩) (h : inflexible_coe L A)\n (hH : hypothesis_injective_inflexible H h) (B : extended_index h.δ) (a : atom) :\n (hypothesised_weak_struct_approx H h hH B).atom_map a = {\n dom := (inl a, B) ∈ inflexible_support h,\n get := λ ha, H.atom_image a ((h.B.cons (coe_lt h.hδ)).comp B)\n (by rwa [inflexible_support, ← h.hL, ← h.hA] at ha)\n } := rfl\n\n@[simp] lemma hypothesised_weak_struct_approx_litter_map {L : litter} {A : extended_index β}\n (H : hypothesis ⟨inr L.to_near_litter, A⟩) (h : inflexible_coe L A)\n (hH : hypothesis_injective_inflexible H h) (B : extended_index h.δ) (L : litter) :\n (hypothesised_weak_struct_approx H h hH B).litter_map L = {\n dom := (inr L.to_near_litter, B) ∈ inflexible_support h,\n get := λ hL, H.near_litter_image L.to_near_litter ((h.B.cons (coe_lt h.hδ)).comp B)\n (by rwa [inflexible_support, ← h.hL, ← h.hA] at hL)\n } := rfl\n\nlemma hypothesised_weak_struct_approx_free (π : struct_approx β) (hπ : π.free) {L : litter}\n {A : extended_index β} (H : hypothesis ⟨inr L.to_near_litter, A⟩) (h : inflexible_coe L A)\n (hH : hypothesis_injective_inflexible H h) :\n @struct_approx.free _ _ _ _ (h.δ : Iic α)\n (hypothesised_weak_struct_approx H h hH).refine.complete :=\nbegin\n rintros B L' ((hL' | ⟨L', hL', rfl⟩) | hL'),\n { exact hL'.2, },\n { rw weak_near_litter_approx.rough_litter_map_or_else_of_dom _ hL'.1,\n exact hH.map_flexible L' B hL'.1 hL'.2, },\n { exact (local_perm.sandbox_subset_subset _ _ hL').2, },\nend\n\nnoncomputable def allowable_of_weak_struct_approx (π : struct_approx β) (hπ : π.free)\n {γ : Iic α} {δ : Iio α} (hδ : (δ : Λ) < γ) (B : path (β : type_index) γ)\n (w : weak_struct_approx δ)\n (hw : (show struct_approx (δ : Iic α), from w.complete).free) :\n allowable δ :=\n(freedom_of_action_of_lt (δ : Iic α)\n (hδ.trans_le (show _, from coe_le_coe.mp (le_of_path B))) _ hw).some\n\nlemma allowable_of_weak_struct_approx_exactly_approximates (π : struct_approx β) (hπ : π.free)\n {γ : Iic α} {δ : Iio α} (hδ : (δ : Λ) < γ) (B : path (β : type_index) γ)\n (w : weak_struct_approx δ)\n (hw : (show struct_approx (δ : Iic α), from w.complete).free) :\n w.complete.exactly_approximates (allowable_of_weak_struct_approx π hπ hδ B w hw).to_struct_perm :=\n(freedom_of_action_of_lt (δ : Iic α)\n (hδ.trans_le (show _, from coe_le_coe.mp (le_of_path B))) _ hw).some_spec\n\nnoncomputable def hypothesised_allowable (π : struct_approx β) (hπ : π.free)\n {L : litter} {A : extended_index β} (h : inflexible_coe L A)\n (H : hypothesis ⟨inr L.to_near_litter, A⟩) (hH : hypothesis_injective_inflexible H h) :\n allowable h.δ :=\nallowable_of_weak_struct_approx π hπ h.hδ h.B _ (hypothesised_weak_struct_approx_free π hπ H h hH)\n\nlemma hypothesised_allowable_exactly_approximates (π : struct_approx β) (hπ : π.free)\n {L : litter} {A : extended_index β} (h : inflexible_coe L A)\n (H : hypothesis ⟨inr L.to_near_litter, A⟩) (hH : hypothesis_injective_inflexible H h) :\n (hypothesised_weak_struct_approx H h hH).refine.complete.exactly_approximates\n (hypothesised_allowable π hπ h H hH).to_struct_perm :=\nallowable_of_weak_struct_approx_exactly_approximates π hπ h.hδ h.B _\n (hypothesised_weak_struct_approx_free π hπ H h hH)\n\n-- TODO: Rename next few lemmas.\n-- TODO: Trim assumptions from lots of these little lemmas, then package into `variables`.\nlemma mem_inflexible_support (π : struct_approx β) (hπ : π.free)\n {L : litter} {A : extended_index β} (h : inflexible_coe L A)\n (B : extended_index h.δ) (a : atom)\n (d : support_condition h.δ) (hd₁ : d ∈ designated_support h.t)\n (hd₂ : relation.refl_trans_gen (constrains α h.δ) (inl a, B) d) :\n (inl a, B) ∈ inflexible_support h :=\nrelation.trans_gen.tail'\n (refl_trans_gen_constrains_comp hd₂ _)\n (constrains.f_map h.hδ h.hε h.hδε h.B h.t d hd₁)\n\nnoncomputable def litter_completion (π : struct_approx β) (hπ : π.free)\n (L : litter) (A : extended_index β) (H : hypothesis ⟨inr L.to_near_litter, A⟩) : litter :=\nif h : nonempty (inflexible_coe L A) then\n if hH : hypothesis_injective_inflexible H h.some then\n f_map (coe_ne_coe.mpr $ coe_ne' h.some.hδε)\n (hypothesised_allowable π hπ h.some H hH • h.some.t)\n else\n near_litter_approx.flexible_completion α (π A) A • L\nelse if h : nonempty (inflexible_bot L A) then\n f_map (show (⊥ : type_index) ≠ (h.some.ε : Λ), from bot_ne_coe)\n (H.atom_image h.some.a (h.some.B.cons (bot_lt_coe _)) h.some.constrains)\nelse\n near_litter_approx.flexible_completion α (π A) A • L\n\nlemma litter_completion_of_flexible (π : struct_approx β) (hπ : π.free)\n (L : litter) (A : extended_index β) (H : hypothesis ⟨inr L.to_near_litter, A⟩)\n (hflex : flexible α L A) :\n litter_completion π hπ L A H = near_litter_approx.flexible_completion α (π A) A • L :=\nbegin\n rw [litter_completion, dif_neg, dif_neg],\n { rintro ⟨⟨γ, ε, hε, C, a, rfl, rfl⟩⟩,\n exact hflex (inflexible.mk_bot _ _ _), },\n { rintro ⟨⟨γ, δ, ε, hδ, hε, hδε, C, t, rfl, rfl⟩⟩,\n exact hflex (inflexible.mk_coe hδ _ _ _ _), },\nend\n\nlemma litter_completion_of_inflexible_coe (π : struct_approx β) (hπ : π.free)\n (L : litter) (A : extended_index β) (H : hypothesis ⟨inr L.to_near_litter, A⟩)\n (h : inflexible_coe L A) (hH : hypothesis_injective_inflexible H h) :\n litter_completion π hπ L A H =\n f_map (coe_ne_coe.mpr $ coe_ne' h.hδε) (hypothesised_allowable π hπ h H hH • h.t) :=\nbegin\n rw [litter_completion, dif_pos, dif_pos],\n { repeat {\n congr' 1;\n try { rw subsingleton.elim h, },\n }, },\n { rw subsingleton.elim h at hH,\n exact hH, },\n { exact ⟨h⟩, },\nend\n\nlemma litter_completion_of_inflexible_bot (π : struct_approx β) (hπ : π.free)\n (L : litter) (A : extended_index β) (H : hypothesis ⟨inr L.to_near_litter, A⟩)\n (h : inflexible_bot L A) :\n litter_completion π hπ L A H =\n f_map (show (⊥ : type_index) ≠ (h.ε : Λ), from bot_ne_coe)\n (H.atom_image h.a (h.B.cons (bot_lt_coe _)) h.constrains) :=\nbegin\n rw [litter_completion, dif_neg, dif_pos, subsingleton.elim h],\n { exact ⟨h⟩, },\n { rintro ⟨h'⟩,\n exact inflexible_bot_inflexible_coe h h', },\nend\n\nend struct_approx\n\nend con_nf\n", "meta": {"author": "leanprover-community", "repo": "con-nf", "sha": "f0b66bd73ca5d3bd8b744985242c4c0b5464913f", "save_path": "github-repos/lean/leanprover-community-con-nf", "path": "github-repos/lean/leanprover-community-con-nf/con-nf-f0b66bd73ca5d3bd8b744985242c4c0b5464913f/src/phase2/litter_completion.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.46490157137338844, "lm_q2_score": 0.017176712313997533, "lm_q1q2_score": 0.007985480545806084}} {"text": "import for_mathlib.algebraic_topology.homotopical_algebra.bifibrant_replacement\nimport for_mathlib.algebraic_topology.homotopical_algebra.cofibrant_replacement\n\nnoncomputable theory\n\nopen category_theory category_theory.limits category_theory.category category_theory\n\nnamespace algebraic_topology\n\nnamespace model_category\n\nvariables {C : Type*} [category C] [model_category C]\n\nvariables {Hcof : Type*} [category Hcof] (Lcof : cofibrant_object C ⥤ Hcof)\n [Lcof.is_localization cofibrant_object.weq]\n\nlemma Lcof_map_surjective_both_fibrant (X Y : cofibrant_object C)\n [is_fibrant X.obj] [is_fibrant Y.obj] :\n function.surjective (@category_theory.functor.map _ _ _ _ Lcof X Y) := λ f,\nbegin\n unfreezingI { rcases X with ⟨X, Xcof⟩, rcases Y with ⟨Y, Ycof⟩, },\n let X' := bifibrant_object.mk X,\n let Y' := bifibrant_object.mk Y,\n let f' : (bifibrant_object.forget_fib C ⋙ Lcof).obj X' ⟶\n (bifibrant_object.forget_fib C ⋙ Lcof).obj Y' := f,\n refine ⟨(bifibrant_object.forget_fib C).map\n ((bifibrant_object.forget_fib C ⋙ Lcof).preimage f'), _⟩,\n rw [← functor.comp_map, functor.image_preimage],\nend\n\nlemma Lcof_map_eq_iff_bifibrant_Q_map_eq {X Y : bifibrant_object C} (f₁ f₂ : X ⟶ Y) :\n Lcof.map ((bifibrant_object.forget_fib C).map f₁) =\n Lcof.map ((bifibrant_object.forget_fib C).map f₂) ↔\n bifibrant_object.homotopy_category.Q.map f₁ = bifibrant_object.homotopy_category.Q.map f₂ :=\nbegin\n erw ← functor.map_eq_iff_of_nat_iso (Lbif_comp_Hobif_to_Hocof_iso Lcof\n bifibrant_object.homotopy_category.Q),\n dsimp only [functor.comp_map],\n apply (Hobif_to_Hocof Lcof bifibrant_object.homotopy_category.Q).map_eq_iff,\nend\n\nlemma Lcof_map_surjective (X Y : cofibrant_object C) [is_fibrant Y.obj] :\n function.surjective (@category_theory.functor.map _ _ _ _ Lcof X Y) := λ g,\nbegin\n let X' := cofibrant_object.mk (CM5a.obj (terminal.from X.obj)),\n let f : X ⟶ X' := CM5a.i (terminal.from X.obj),\n have hf : cofibrant_object.weq f,\n { change model_category.weq (CM5a.i (terminal.from X.obj)),\n exact weak_eq.property, },\n haveI : is_iso (Lcof.map f) := is_iso_Lcof_map' Lcof f hf,\n rcases Lcof_map_surjective_both_fibrant Lcof _ _ (inv (Lcof.map f) ≫ g) with ⟨φ, hφ⟩,\n exact ⟨f ≫ φ, by rw [Lcof.map_comp, hφ, is_iso.hom_inv_id_assoc]⟩,\nend\n\nlemma Lcof_map_eq_iff'_both_fibrant {X Y : cofibrant_object C} [is_fibrant X.obj] [is_fibrant Y.obj]\n (P : path_object Y.obj) (f₁ f₂ : X ⟶ Y) :\n Lcof.map f₁ = Lcof.map f₂ ↔ nonempty (model_category.right_homotopy P.pre f₁ f₂) :=\nbegin\n unfreezingI { rcases X with ⟨X, Xcof⟩, rcases Y with ⟨Y, Ycof⟩, },\n let g₁ : bifibrant_object.mk X ⟶ bifibrant_object.mk Y := f₁,\n let g₂ : bifibrant_object.mk X ⟶ bifibrant_object.mk Y := f₂,\n let P' : path_object (bifibrant_object.mk Y).obj := P,\n erw ← bifibrant_object.homotopy_category.Q_map_eq_iff' P' g₁ g₂,\n erw ← functor.map_eq_iff_of_nat_iso (Lbif_comp_Hobif_to_Hocof_iso Lcof\n bifibrant_object.homotopy_category.Q) g₁ g₂,\n dsimp only [functor.comp_map],\n apply (Hobif_to_Hocof Lcof bifibrant_object.homotopy_category.Q).map_eq_iff,\nend\n\nlemma Lcof_map_eq_iff' {X Y : cofibrant_object C} [is_fibrant Y.obj] (P : path_object Y.obj)\n (f₁ f₂ : X ⟶ Y) :\n Lcof.map f₁ = Lcof.map f₂ ↔ nonempty (model_category.right_homotopy P.pre f₁ f₂) :=\nbegin\n split,\n { intro h,\n let X' := CM5a.obj (terminal.from X.obj),\n let i : X.obj ⟶ X' := CM5a.i (terminal.from X.obj),\n have sq₁ : comm_sq ((cofibrant_object.forget C).map f₁) i (terminal.from Y.obj) (terminal.from X') := by tidy,\n have sq₂ : comm_sq ((cofibrant_object.forget C).map f₂) i (terminal.from Y.obj) (terminal.from X') := by tidy,\n let g₁ : cofibrant_object.mk X' ⟶ Y := sq₁.lift,\n let g₂ : cofibrant_object.mk X' ⟶ Y := sq₂.lift,\n have eq : Lcof.map g₁ = Lcof.map g₂,\n { let j : X ⟶ cofibrant_object.mk X' := i,\n haveI : weak_eq ((cofibrant_object.forget C).map j) := by { dsimp [j], apply_instance, },\n haveI := is_iso_Lcof_map Lcof j,\n simp only [← cancel_epi (Lcof.map j), ← functor.map_comp],\n convert h,\n exacts [sq₁.fac_left, sq₂.fac_left], },\n rw Lcof_map_eq_iff'_both_fibrant Lcof P g₁ g₂ at eq,\n convert nonempty.intro (eq.some.comp_left i),\n exacts [sq₁.fac_left.symm, sq₂.fac_left.symm], },\n { intro h,\n change (cofibrant_replacement.π Lcof).map (cofibrant_object.homotopy_category.Q.map f₁) =\n (cofibrant_replacement.π Lcof).map (cofibrant_object.homotopy_category.Q.map f₂),\n congr' 1,\n apply category_theory.quotient.sound,\n exact cofibrant_object.right_homotopy.trans_closure.mk\n (cofibrant_object.right_homotopy.mk P h.some), },\nend\n\nlemma Lcof_map_eq_iff {X Y : cofibrant_object C} [is_fibrant Y.obj] (Cyl : cylinder X.obj)\n (f₁ f₂ : X ⟶ Y) :\n Lcof.map f₁ = Lcof.map f₂ ↔ nonempty (left_homotopy Cyl.pre f₁ f₂) :=\nbegin\n let P := path_object.some Y.obj,\n rw Lcof_map_eq_iff' Lcof P,\n split,\n { exact λ h, nonempty.intro (h.some.to_left_homotopy Cyl), },\n { exact λ h, nonempty.intro (h.some.to_right_homotopy P), },\nend\n\nnamespace fundamental_lemma\n\nvariables {Ho : Type*} [category Ho] (L : C ⥤ Ho) [L.is_localization weq] (C)\n\nvariables {C}\n\nlemma map_surjective (X Y : C) [is_cofibrant X] [is_fibrant Y] :\n function.surjective (@category_theory.functor.map _ _ _ _ L X Y) :=\nbegin\n let Y' := CM5b.obj (initial.to Y),\n suffices : function.surjective (@category_theory.functor.map _ _ _ _ L X Y'),\n { intro g,\n let p : Y' ⟶ Y := CM5b.p (initial.to Y),\n haveI := localization.inverts L weq p weak_eq.property,\n rcases this (g ≫ inv (L.map p)) with ⟨φ, hφ⟩,\n exact ⟨φ ≫ p, by rw [L.map_comp, hφ, assoc, is_iso.inv_hom_id, comp_id]⟩, },\n suffices : ∀ (A B : cofibrant_object C) [is_fibrant B.obj], function.surjective\n (@category_theory.functor.map _ _ _ _ (cofibrant_object.forget C ⋙ L) A B),\n { exact this (cofibrant_object.mk X) (cofibrant_object.mk Y'), },\n simp only [← functor.function_surjective_map_iff_of_iso (Lcof_comp_Hocof_to_Ho_iso Lcof' L)],\n introsI A B hB,\n exact function.surjective.comp (Hocof_to_Ho Lcof' L).map_surjective\n (Lcof_map_surjective Lcof' A B),\nend\n\ninstance {X Y : C} (f : X ⟶ Y) [weak_eq f] : is_iso (L.map f) :=\nlocalization.inverts L weq f weak_eq.property\n\nlemma map_eq_of_left_homotopy {X Y : C} {f₁ f₂ : X ⟶ Y} {P : precylinder X}\n (h : left_homotopy P f₁ f₂) : L.map f₁ = L.map f₂ :=\nbegin\n simp only [← h.h₀, ← h.h₁, L.map_comp],\n congr' 1,\n simp only [← cancel_mono (L.map P.σ), ← L.map_comp, P.σd₀, P.σd₁],\nend\n\nlemma map_eq_iff {X Y : C} [is_cofibrant X] [is_fibrant Y] (Cyl : cylinder X) (f₁ f₂ : X ⟶ Y) :\n L.map f₁ = L.map f₂ ↔ nonempty (left_homotopy Cyl.pre f₁ f₂) :=\nbegin\n split,\n { intro h,\n let Y' := CM5b.obj (initial.to Y),\n let i : Y' ⟶ Y := CM5b.p (initial.to Y),\n have sq₁ : comm_sq (initial.to Y') (initial.to X) i f₁ := by tidy,\n have sq₂ : comm_sq (initial.to Y') (initial.to X) i f₂ := by tidy,\n let g₁ : cofibrant_object.mk X ⟶ cofibrant_object.mk Y' := sq₁.lift,\n let g₂ : cofibrant_object.mk X ⟶ cofibrant_object.mk Y' := sq₂.lift,\n haveI := localization.inverts L weq i weak_eq.property,\n rw [← sq₁.fac_right, ← sq₂.fac_right, L.map_comp, L.map_comp,\n cancel_mono] at h,\n change (cofibrant_object.forget C ⋙ L).map g₁ =\n (cofibrant_object.forget C ⋙ L).map g₂ at h,\n rw ← functor.map_eq_iff_of_nat_iso (Lcof_comp_Hocof_to_Ho_iso Lcof' L) at h,\n have h' := (Hocof_to_Ho Lcof' L).map_injective h,\n let Cyl' : cylinder (cofibrant_object.mk X).obj := Cyl,\n rw Lcof_map_eq_iff Lcof' Cyl' g₁ g₂ at h',\n rw [← sq₁.fac_right, ← sq₂.fac_right],\n exact nonempty.intro (h'.some.comp_right i), },\n { intro h,\n exact map_eq_of_left_homotopy L h.some, },\nend\n\nlemma map_eq_iff' {X Y : C} [is_cofibrant X] [is_fibrant Y] (P : path_object Y) (f₁ f₂ : X ⟶ Y) :\n L.map f₁ = L.map f₂ ↔ nonempty (right_homotopy P.pre f₁ f₂) :=\nbegin\n let Cyl := cylinder.some X,\n rw map_eq_iff L Cyl f₁ f₂,\n split,\n { exact λ h, nonempty.intro (h.some.to_right_homotopy P), },\n { exact λ h, nonempty.intro (h.some.to_left_homotopy Cyl), },\nend\n\nend fundamental_lemma\n\nend model_category\n\nend algebraic_topology\n", "meta": {"author": "joelriou", "repo": "homotopical_algebra", "sha": "697f49d6744b09c5ef463cfd3e35932bdf2c78a3", "save_path": "github-repos/lean/joelriou-homotopical_algebra", "path": "github-repos/lean/joelriou-homotopical_algebra/homotopical_algebra-697f49d6744b09c5ef463cfd3e35932bdf2c78a3/src/for_mathlib/algebraic_topology/homotopical_algebra/fundamental_lemma.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.36658973632215985, "lm_q2_score": 0.021615332132384868, "lm_q1q2_score": 0.007923958906926877}} {"text": "/-\nCopyright (c) 2018 Mario Carneiro. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Mario Carneiro, Kenny Lau\n-/\nimport Mathlib.PrePort\nimport Mathlib.Lean3Lib.init.default\nimport Mathlib.data.list.basic\nimport Mathlib.PostPort\n\nuniverses u v w z u_1 u_2 u_3 \n\nnamespace Mathlib\n\nnamespace list\n\n\n/- zip & unzip -/\n\n@[simp] theorem zip_with_cons_cons {α : Type u} {β : Type v} {γ : Type w} (f : α → β → γ) (a : α) (b : β) (l₁ : List α) (l₂ : List β) : zip_with f (a :: l₁) (b :: l₂) = f a b :: zip_with f l₁ l₂ :=\n rfl\n\n@[simp] theorem zip_cons_cons {α : Type u} {β : Type v} (a : α) (b : β) (l₁ : List α) (l₂ : List β) : zip (a :: l₁) (b :: l₂) = (a, b) :: zip l₁ l₂ :=\n rfl\n\n@[simp] theorem zip_with_nil_left {α : Type u} {β : Type v} {γ : Type w} (f : α → β → γ) (l : List β) : zip_with f [] l = [] :=\n rfl\n\n@[simp] theorem zip_with_nil_right {α : Type u} {β : Type v} {γ : Type w} (f : α → β → γ) (l : List α) : zip_with f l [] = [] :=\n list.cases_on l (Eq.refl (zip_with f [] [])) fun (l_hd : α) (l_tl : List α) => Eq.refl (zip_with f (l_hd :: l_tl) [])\n\n@[simp] theorem zip_nil_left {α : Type u} {β : Type v} (l : List α) : zip [] l = [] :=\n rfl\n\n@[simp] theorem zip_nil_right {α : Type u} {β : Type v} (l : List α) : zip l [] = [] :=\n zip_with_nil_right Prod.mk l\n\n@[simp] theorem zip_swap {α : Type u} {β : Type v} (l₁ : List α) (l₂ : List β) : map prod.swap (zip l₁ l₂) = zip l₂ l₁ := sorry\n\n@[simp] theorem length_zip_with {α : Type u} {β : Type v} {γ : Type w} (f : α → β → γ) (l₁ : List α) (l₂ : List β) : length (zip_with f l₁ l₂) = min (length l₁) (length l₂) := sorry\n\n@[simp] theorem length_zip {α : Type u} {β : Type v} (l₁ : List α) (l₂ : List β) : length (zip l₁ l₂) = min (length l₁) (length l₂) :=\n length_zip_with Prod.mk\n\ntheorem lt_length_left_of_zip_with {α : Type u} {β : Type v} {γ : Type w} {f : α → β → γ} {i : ℕ} {l : List α} {l' : List β} (h : i < length (zip_with f l l')) : i < length l :=\n and.left\n (eq.mp (Eq._oldrec (Eq.refl (i < min (length l) (length l'))) (propext lt_min_iff))\n (eq.mp (Eq._oldrec (Eq.refl (i < length (zip_with f l l'))) (length_zip_with f l l')) h))\n\ntheorem lt_length_right_of_zip_with {α : Type u} {β : Type v} {γ : Type w} {f : α → β → γ} {i : ℕ} {l : List α} {l' : List β} (h : i < length (zip_with f l l')) : i < length l' :=\n and.right\n (eq.mp (Eq._oldrec (Eq.refl (i < min (length l) (length l'))) (propext lt_min_iff))\n (eq.mp (Eq._oldrec (Eq.refl (i < length (zip_with f l l'))) (length_zip_with f l l')) h))\n\ntheorem lt_length_left_of_zip {α : Type u} {β : Type v} {i : ℕ} {l : List α} {l' : List β} (h : i < length (zip l l')) : i < length l :=\n lt_length_left_of_zip_with h\n\ntheorem lt_length_right_of_zip {α : Type u} {β : Type v} {i : ℕ} {l : List α} {l' : List β} (h : i < length (zip l l')) : i < length l' :=\n lt_length_right_of_zip_with h\n\ntheorem zip_append {α : Type u} {β : Type v} {l₁ : List α} {r₁ : List α} {l₂ : List β} {r₂ : List β} (h : length l₁ = length l₂) : zip (l₁ ++ r₁) (l₂ ++ r₂) = zip l₁ l₂ ++ zip r₁ r₂ := sorry\n\ntheorem zip_map {α : Type u} {β : Type v} {γ : Type w} {δ : Type z} (f : α → γ) (g : β → δ) (l₁ : List α) (l₂ : List β) : zip (map f l₁) (map g l₂) = map (prod.map f g) (zip l₁ l₂) := sorry\n\ntheorem zip_map_left {α : Type u} {β : Type v} {γ : Type w} (f : α → γ) (l₁ : List α) (l₂ : List β) : zip (map f l₁) l₂ = map (prod.map f id) (zip l₁ l₂) :=\n eq.mpr (id (Eq._oldrec (Eq.refl (zip (map f l₁) l₂ = map (prod.map f id) (zip l₁ l₂))) (Eq.symm (zip_map f id l₁ l₂))))\n (eq.mpr (id (Eq._oldrec (Eq.refl (zip (map f l₁) l₂ = zip (map f l₁) (map id l₂))) (map_id l₂)))\n (Eq.refl (zip (map f l₁) l₂)))\n\ntheorem zip_map_right {α : Type u} {β : Type v} {γ : Type w} (f : β → γ) (l₁ : List α) (l₂ : List β) : zip l₁ (map f l₂) = map (prod.map id f) (zip l₁ l₂) :=\n eq.mpr (id (Eq._oldrec (Eq.refl (zip l₁ (map f l₂) = map (prod.map id f) (zip l₁ l₂))) (Eq.symm (zip_map id f l₁ l₂))))\n (eq.mpr (id (Eq._oldrec (Eq.refl (zip l₁ (map f l₂) = zip (map id l₁) (map f l₂))) (map_id l₁)))\n (Eq.refl (zip l₁ (map f l₂))))\n\ntheorem zip_map' {α : Type u} {β : Type v} {γ : Type w} (f : α → β) (g : α → γ) (l : List α) : zip (map f l) (map g l) = map (fun (a : α) => (f a, g a)) l := sorry\n\ntheorem mem_zip {α : Type u} {β : Type v} {a : α} {b : β} {l₁ : List α} {l₂ : List β} : (a, b) ∈ zip l₁ l₂ → a ∈ l₁ ∧ b ∈ l₂ := sorry\n\ntheorem map_fst_zip {α : Type u} {β : Type v} (l₁ : List α) (l₂ : List β) : length l₁ ≤ length l₂ → map prod.fst (zip l₁ l₂) = l₁ := sorry\n\ntheorem map_snd_zip {α : Type u} {β : Type v} (l₁ : List α) (l₂ : List β) : length l₂ ≤ length l₁ → map prod.snd (zip l₁ l₂) = l₂ := sorry\n\n@[simp] theorem unzip_nil {α : Type u} {β : Type v} : unzip [] = ([], []) :=\n rfl\n\n@[simp] theorem unzip_cons {α : Type u} {β : Type v} (a : α) (b : β) (l : List (α × β)) : unzip ((a, b) :: l) = (a :: prod.fst (unzip l), b :: prod.snd (unzip l)) := sorry\n\ntheorem unzip_eq_map {α : Type u} {β : Type v} (l : List (α × β)) : unzip l = (map prod.fst l, map prod.snd l) := sorry\n\ntheorem unzip_left {α : Type u} {β : Type v} (l : List (α × β)) : prod.fst (unzip l) = map prod.fst l := sorry\n\ntheorem unzip_right {α : Type u} {β : Type v} (l : List (α × β)) : prod.snd (unzip l) = map prod.snd l := sorry\n\ntheorem unzip_swap {α : Type u} {β : Type v} (l : List (α × β)) : unzip (map prod.swap l) = prod.swap (unzip l) := sorry\n\ntheorem zip_unzip {α : Type u} {β : Type v} (l : List (α × β)) : zip (prod.fst (unzip l)) (prod.snd (unzip l)) = l := sorry\n\ntheorem unzip_zip_left {α : Type u} {β : Type v} {l₁ : List α} {l₂ : List β} : length l₁ ≤ length l₂ → prod.fst (unzip (zip l₁ l₂)) = l₁ := sorry\n\ntheorem unzip_zip_right {α : Type u} {β : Type v} {l₁ : List α} {l₂ : List β} (h : length l₂ ≤ length l₁) : prod.snd (unzip (zip l₁ l₂)) = l₂ :=\n eq.mpr (id (Eq._oldrec (Eq.refl (prod.snd (unzip (zip l₁ l₂)) = l₂)) (Eq.symm (zip_swap l₂ l₁))))\n (eq.mpr (id (Eq._oldrec (Eq.refl (prod.snd (unzip (map prod.swap (zip l₂ l₁))) = l₂)) (unzip_swap (zip l₂ l₁))))\n (unzip_zip_left h))\n\ntheorem unzip_zip {α : Type u} {β : Type v} {l₁ : List α} {l₂ : List β} (h : length l₁ = length l₂) : unzip (zip l₁ l₂) = (l₁, l₂) := sorry\n\ntheorem zip_of_prod {α : Type u} {β : Type v} {l : List α} {l' : List β} {lp : List (α × β)} (hl : map prod.fst lp = l) (hr : map prod.snd lp = l') : lp = zip l l' := sorry\n\ntheorem map_prod_left_eq_zip {α : Type u} {β : Type v} {l : List α} (f : α → β) : map (fun (x : α) => (x, f x)) l = zip l (map f l) := sorry\n\ntheorem map_prod_right_eq_zip {α : Type u} {β : Type v} {l : List α} (f : α → β) : map (fun (x : α) => (f x, x)) l = zip (map f l) l := sorry\n\n@[simp] theorem length_revzip {α : Type u} (l : List α) : length (revzip l) = length l := sorry\n\n@[simp] theorem unzip_revzip {α : Type u} (l : List α) : unzip (revzip l) = (l, reverse l) :=\n unzip_zip (Eq.symm (length_reverse l))\n\n@[simp] theorem revzip_map_fst {α : Type u} (l : List α) : map prod.fst (revzip l) = l :=\n eq.mpr (id (Eq._oldrec (Eq.refl (map prod.fst (revzip l) = l)) (Eq.symm (unzip_left (revzip l)))))\n (eq.mpr (id (Eq._oldrec (Eq.refl (prod.fst (unzip (revzip l)) = l)) (unzip_revzip l)))\n (Eq.refl (prod.fst (l, reverse l))))\n\n@[simp] theorem revzip_map_snd {α : Type u} (l : List α) : map prod.snd (revzip l) = reverse l :=\n eq.mpr (id (Eq._oldrec (Eq.refl (map prod.snd (revzip l) = reverse l)) (Eq.symm (unzip_right (revzip l)))))\n (eq.mpr (id (Eq._oldrec (Eq.refl (prod.snd (unzip (revzip l)) = reverse l)) (unzip_revzip l)))\n (Eq.refl (prod.snd (l, reverse l))))\n\ntheorem reverse_revzip {α : Type u} (l : List α) : reverse (revzip l) = revzip (reverse l) := sorry\n\ntheorem revzip_swap {α : Type u} (l : List α) : map prod.swap (revzip l) = revzip (reverse l) := sorry\n\ntheorem nth_zip_with {α : Type u_1} {β : Type u_1} {γ : Type u_1} (f : α → β → γ) (l₁ : List α) (l₂ : List β) (i : ℕ) : nth (zip_with f l₁ l₂) i = f <$> nth l₁ i <*> nth l₂ i := sorry\n\ntheorem nth_zip_with_eq_some {α : Type u_1} {β : Type u_2} {γ : Type u_3} (f : α → β → γ) (l₁ : List α) (l₂ : List β) (z : γ) (i : ℕ) : nth (zip_with f l₁ l₂) i = some z ↔ ∃ (x : α), ∃ (y : β), nth l₁ i = some x ∧ nth l₂ i = some y ∧ f x y = z := sorry\n\ntheorem nth_zip_eq_some {α : Type u} {β : Type v} (l₁ : List α) (l₂ : List β) (z : α × β) (i : ℕ) : nth (zip l₁ l₂) i = some z ↔ nth l₁ i = some (prod.fst z) ∧ nth l₂ i = some (prod.snd z) := sorry\n\n@[simp] theorem nth_le_zip_with {α : Type u} {β : Type v} {γ : Type w} {f : α → β → γ} {l : List α} {l' : List β} {i : ℕ} {h : i < length (zip_with f l l')} : nth_le (zip_with f l l') i h =\n f (nth_le l i (lt_length_left_of_zip_with h)) (nth_le l' i (lt_length_right_of_zip_with h)) := sorry\n\n@[simp] theorem nth_le_zip {α : Type u} {β : Type v} {l : List α} {l' : List β} {i : ℕ} {h : i < length (zip l l')} : nth_le (zip l l') i h = (nth_le l i (lt_length_left_of_zip h), nth_le l' i (lt_length_right_of_zip h)) :=\n nth_le_zip_with\n\ntheorem mem_zip_inits_tails {α : Type u} {l : List α} {init : List α} {tail : List α} : (init, tail) ∈ zip (inits l) (tails l) ↔ init ++ tail = l := sorry\n\n", "meta": {"author": "AurelienSaue", "repo": "Mathlib4_auto", "sha": "590df64109b08190abe22358fabc3eae000943f2", "save_path": "github-repos/lean/AurelienSaue-Mathlib4_auto", "path": "github-repos/lean/AurelienSaue-Mathlib4_auto/Mathlib4_auto-590df64109b08190abe22358fabc3eae000943f2/Mathlib/data/list/zip.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.39233683016710835, "lm_q2_score": 0.020023440631559572, "lm_q1q2_score": 0.007855933226425365}} {"text": "import tactic.rewrite_search\n\nabbreviation C := ℕ\nvariables X_1 X_2 X_3 X_4 X_5 X_6 X_7 X_8 X_9 X_10 X_11 X_12 X_13 X_14 X_15 X_16 X_17 X_18 X_19 X_20 X_21 X_22 X_23 X_24 X_25 X_26 X_27 X_28 X_29 X_30 X_31 X_32 X_33 X_34 X_35 X_36 X_37 X_38 X_39 X_40 X_41 X_42 X_43 X_44 X_45 X_46 X_47 X_48 : C\nconstant Rubik : C → C → C → C → C → C → C → C → C → C → C → C → C → C → C → C → C → C → C → C → C → C → C → C → C → C → C → C → C → C → C → C → C → C → C → C → C → C → C → C → C → C → C → C → C → C → C → C → C\n@[ematch] constant Rubik_1 : Rubik X_1 X_2 X_3 X_4 X_5 X_6 X_7 X_8 X_9 X_10 X_11 X_12 X_13 X_14 X_15 X_16 X_17 X_18 X_19 X_20 X_21 X_22 X_23 X_24 X_25 X_26 X_27 X_28 X_29 X_30 X_31 X_32 X_33 X_34 X_35 X_36 X_37 X_38 X_39 X_40 X_41 X_42 X_43 X_44 X_45 X_46 X_47 X_48 = Rubik X_3 X_5 X_8 X_2 X_7 X_1 X_4 X_6 X_33 X_34 X_35 X_12 X_13 X_14 X_15 X_16 X_9 X_10 X_11 X_20 X_21 X_22 X_23 X_24 X_17 X_18 X_19 X_28 X_29 X_30 X_31 X_32 X_25 X_26 X_27 X_36 X_37 X_38 X_39 X_40 X_41 X_42 X_43 X_44 X_45 X_46 X_47 X_48\n@[ematch] constant Rubik_2 : Rubik X_1 X_2 X_3 X_4 X_5 X_6 X_7 X_8 X_9 X_10 X_11 X_12 X_13 X_14 X_15 X_16 X_17 X_18 X_19 X_20 X_21 X_22 X_23 X_24 X_25 X_26 X_27 X_28 X_29 X_30 X_31 X_32 X_33 X_34 X_35 X_36 X_37 X_38 X_39 X_40 X_41 X_42 X_43 X_44 X_45 X_46 X_47 X_48 = Rubik X_17 X_2 X_3 X_20 X_5 X_22 X_7 X_8 X_11 X_13 X_16 X_10 X_15 X_9 X_12 X_14 X_41 X_18 X_19 X_44 X_21 X_46 X_23 X_24 X_25 X_26 X_27 X_28 X_29 X_30 X_31 X_32 X_33 X_34 X_6 X_36 X_4 X_38 X_39 X_1 X_40 X_42 X_43 X_37 X_45 X_35 X_47 X_48\n@[ematch] constant Rubik_3 : Rubik X_1 X_2 X_3 X_4 X_5 X_6 X_7 X_8 X_9 X_10 X_11 X_12 X_13 X_14 X_15 X_16 X_17 X_18 X_19 X_20 X_21 X_22 X_23 X_24 X_25 X_26 X_27 X_28 X_29 X_30 X_31 X_32 X_33 X_34 X_35 X_36 X_37 X_38 X_39 X_40 X_41 X_42 X_43 X_44 X_45 X_46 X_47 X_48 = Rubik X_1 X_2 X_3 X_4 X_5 X_25 X_28 X_30 X_9 X_10 X_8 X_12 X_7 X_14 X_15 X_6 X_19 X_21 X_24 X_18 X_23 X_17 X_20 X_22 X_43 X_26 X_27 X_42 X_29 X_41 X_31 X_32 X_33 X_34 X_35 X_36 X_37 X_38 X_39 X_40 X_11 X_13 X_16 X_44 X_45 X_46 X_47 X_48\n@[ematch] constant Rubik_4 : Rubik X_1 X_2 X_3 X_4 X_5 X_6 X_7 X_8 X_9 X_10 X_11 X_12 X_13 X_14 X_15 X_16 X_17 X_18 X_19 X_20 X_21 X_22 X_23 X_24 X_25 X_26 X_27 X_28 X_29 X_30 X_31 X_32 X_33 X_34 X_35 X_36 X_37 X_38 X_39 X_40 X_41 X_42 X_43 X_44 X_45 X_46 X_47 X_48 = Rubik X_1 X_2 X_38 X_4 X_36 X_6 X_7 X_33 X_9 X_10 X_11 X_12 X_13 X_14 X_15 X_16 X_17 X_18 X_3 X_20 X_5 X_22 X_23 X_8 X_27 X_29 X_32 X_26 X_31 X_25 X_28 X_30 X_48 X_34 X_35 X_45 X_37 X_43 X_39 X_40 X_41 X_42 X_19 X_44 X_21 X_46 X_47 X_24\n@[ematch] constant Rubik_5 : Rubik X_1 X_2 X_3 X_4 X_5 X_6 X_7 X_8 X_9 X_10 X_11 X_12 X_13 X_14 X_15 X_16 X_17 X_18 X_19 X_20 X_21 X_22 X_23 X_24 X_25 X_26 X_27 X_28 X_29 X_30 X_31 X_32 X_33 X_34 X_35 X_36 X_37 X_38 X_39 X_40 X_41 X_42 X_43 X_44 X_45 X_46 X_47 X_48 = Rubik X_14 X_12 X_9 X_4 X_5 X_6 X_7 X_8 X_46 X_10 X_11 X_47 X_13 X_48 X_15 X_16 X_17 X_18 X_19 X_20 X_21 X_22 X_23 X_24 X_25 X_26 X_1 X_28 X_2 X_30 X_31 X_3 X_35 X_37 X_40 X_34 X_39 X_33 X_36 X_38 X_41 X_42 X_43 X_44 X_45 X_32 X_29 X_27\n@[ematch] constant Rubik_6 : Rubik X_1 X_2 X_3 X_4 X_5 X_6 X_7 X_8 X_9 X_10 X_11 X_12 X_13 X_14 X_15 X_16 X_17 X_18 X_19 X_20 X_21 X_22 X_23 X_24 X_25 X_26 X_27 X_28 X_29 X_30 X_31 X_32 X_33 X_34 X_35 X_36 X_37 X_38 X_39 X_40 X_41 X_42 X_43 X_44 X_45 X_46 X_47 X_48 = Rubik X_1 X_2 X_3 X_4 X_5 X_6 X_7 X_8 X_9 X_10 X_11 X_12 X_13 X_22 X_23 X_24 X_17 X_18 X_19 X_20 X_21 X_30 X_31 X_32 X_25 X_26 X_27 X_28 X_29 X_38 X_39 X_40 X_33 X_34 X_35 X_36 X_37 X_14 X_15 X_16 X_43 X_45 X_48 X_42 X_47 X_41 X_44 X_46\n-- @[ematch] constant Rubik_7 : Rubik X_1 X_2 X_3 X_4 X_5 X_6 X_7 X_8 X_9 X_10 X_11 X_12 X_13 X_14 X_15 X_16 X_17 X_18 X_19 X_20 X_21 X_22 X_23 X_24 X_25 X_26 X_27 X_28 X_29 X_30 X_31 X_32 X_33 X_34 X_35 X_36 X_37 X_38 X_39 X_40 X_41 X_42 X_43 X_44 X_45 X_46 X_47 X_48 = Rubik X_6 X_4 X_1 X_7 X_2 X_8 X_5 X_3 X_17 X_18 X_19 X_12 X_13 X_14 X_15 X_16 X_25 X_26 X_27 X_20 X_21 X_22 X_23 X_24 X_33 X_34 X_35 X_28 X_29 X_30 X_31 X_32 X_9 X_10 X_11 X_36 X_37 X_38 X_39 X_40 X_41 X_42 X_43 X_44 X_45 X_46 X_47 X_48\n-- @[ematch] constant Rubik_8 : Rubik X_1 X_2 X_3 X_4 X_5 X_6 X_7 X_8 X_9 X_10 X_11 X_12 X_13 X_14 X_15 X_16 X_17 X_18 X_19 X_20 X_21 X_22 X_23 X_24 X_25 X_26 X_27 X_28 X_29 X_30 X_31 X_32 X_33 X_34 X_35 X_36 X_37 X_38 X_39 X_40 X_41 X_42 X_43 X_44 X_45 X_46 X_47 X_48 = Rubik X_40 X_2 X_3 X_37 X_5 X_35 X_7 X_8 X_14 X_12 X_9 X_15 X_10 X_16 X_13 X_11 X_1 X_18 X_19 X_4 X_21 X_6 X_23 X_24 X_25 X_26 X_27 X_28 X_29 X_30 X_31 X_32 X_33 X_34 X_46 X_36 X_44 X_38 X_39 X_41 X_17 X_42 X_43 X_20 X_45 X_22 X_47 X_48\n-- @[ematch] constant Rubik_9 : Rubik X_1 X_2 X_3 X_4 X_5 X_6 X_7 X_8 X_9 X_10 X_11 X_12 X_13 X_14 X_15 X_16 X_17 X_18 X_19 X_20 X_21 X_22 X_23 X_24 X_25 X_26 X_27 X_28 X_29 X_30 X_31 X_32 X_33 X_34 X_35 X_36 X_37 X_38 X_39 X_40 X_41 X_42 X_43 X_44 X_45 X_46 X_47 X_48 = Rubik X_1 X_2 X_3 X_4 X_5 X_16 X_13 X_11 X_9 X_10 X_41 X_12 X_42 X_14 X_15 X_43 X_22 X_20 X_17 X_23 X_18 X_24 X_21 X_19 X_6 X_26 X_27 X_7 X_29 X_8 X_31 X_32 X_33 X_34 X_35 X_36 X_37 X_38 X_39 X_40 X_30 X_28 X_25 X_44 X_45 X_46 X_47 X_48\n-- @[ematch] constant Rubik_10 : Rubik X_1 X_2 X_3 X_4 X_5 X_6 X_7 X_8 X_9 X_10 X_11 X_12 X_13 X_14 X_15 X_16 X_17 X_18 X_19 X_20 X_21 X_22 X_23 X_24 X_25 X_26 X_27 X_28 X_29 X_30 X_31 X_32 X_33 X_34 X_35 X_36 X_37 X_38 X_39 X_40 X_41 X_42 X_43 X_44 X_45 X_46 X_47 X_48 = Rubik X_1 X_2 X_19 X_4 X_21 X_6 X_7 X_24 X_9 X_10 X_11 X_12 X_13 X_14 X_15 X_16 X_17 X_18 X_43 X_20 X_45 X_22 X_23 X_48 X_30 X_28 X_25 X_31 X_26 X_32 X_29 X_27 X_8 X_34 X_35 X_5 X_37 X_3 X_39 X_40 X_41 X_42 X_38 X_44 X_36 X_46 X_47 X_33\n-- @[ematch] constant Rubik_11 : Rubik X_1 X_2 X_3 X_4 X_5 X_6 X_7 X_8 X_9 X_10 X_11 X_12 X_13 X_14 X_15 X_16 X_17 X_18 X_19 X_20 X_21 X_22 X_23 X_24 X_25 X_26 X_27 X_28 X_29 X_30 X_31 X_32 X_33 X_34 X_35 X_36 X_37 X_38 X_39 X_40 X_41 X_42 X_43 X_44 X_45 X_46 X_47 X_48 = Rubik X_27 X_29 X_32 X_4 X_5 X_6 X_7 X_8 X_3 X_10 X_11 X_2 X_13 X_1 X_15 X_16 X_17 X_18 X_19 X_20 X_21 X_22 X_23 X_24 X_25 X_26 X_48 X_28 X_47 X_30 X_31 X_46 X_38 X_36 X_33 X_39 X_34 X_40 X_37 X_35 X_41 X_42 X_43 X_44 X_45 X_9 X_12 X_14\n-- @[ematch] constant Rubik_12 : Rubik X_1 X_2 X_3 X_4 X_5 X_6 X_7 X_8 X_9 X_10 X_11 X_12 X_13 X_14 X_15 X_16 X_17 X_18 X_19 X_20 X_21 X_22 X_23 X_24 X_25 X_26 X_27 X_28 X_29 X_30 X_31 X_32 X_33 X_34 X_35 X_36 X_37 X_38 X_39 X_40 X_41 X_42 X_43 X_44 X_45 X_46 X_47 X_48 = Rubik X_1 X_2 X_3 X_4 X_5 X_6 X_7 X_8 X_9 X_10 X_11 X_12 X_13 X_38 X_39 X_40 X_17 X_18 X_19 X_20 X_21 X_14 X_15 X_16 X_25 X_26 X_27 X_28 X_29 X_22 X_23 X_24 X_33 X_34 X_35 X_36 X_37 X_30 X_31 X_32 X_46 X_44 X_41 X_47 X_42 X_48 X_45 X_43\n\nlemma Rubik_test_1 : Rubik 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 = Rubik 0 0 0 0 0 0 0 0 4 4 4 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 4 4 4 4 4 5 5 5 5 5 5 5 5 :=\nbegin\n-- rewrite_search_using [`ematch],\nrw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3,\nrw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3,\nrw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3,\nrw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3,\nrw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3,\nrw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3,\nrw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3,\nrw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3,\nrw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3,\nrw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3,\nrw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3,\nrw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3,\nrw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3,\nrw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3,\nrw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3,\nrw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3,\nrw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3,\nrw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3,\nrw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3,\nrw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3, rw Rubik_2, rw ← Rubik_2, rw Rubik_3, rw ← Rubik_3,\n\nsorry\nend\n-- lemma Rubik_test_2 : Rubik 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 = Rubik 1 0 0 1 0 1 0 0 4 4 4 5 1 5 1 1 5 1 1 2 2 2 2 2 2 2 2 3 0 3 3 0 3 3 0 4 4 4 4 4 5 5 5 5 5 3 3 3 := by rewrite_search_using [`ematch] {visualiser:=tt}\n-- lemma Rubik_test_3 : Rubik 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 = Rubik 0 0 1 0 4 3 3 4 1 1 0 1 0 2 2 2 2 2 0 2 0 5 3 3 3 3 4 3 4 5 5 4 5 4 4 5 4 5 1 0 1 5 2 1 2 1 5 3 := by rewrite_search_using [`ematch]\n-- lemma Rubik_test_4 : Rubik 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 = Rubik 2 1 4 2 4 2 3 4 0 0 0 1 1 5 5 5 1 2 1 5 0 3 2 3 0 0 0 3 3 5 5 5 3 4 3 5 0 1 4 1 4 1 2 4 2 4 3 2 := by rewrite_search_using [`ematch]\n-- lemma Rubik_test_5 : Rubik 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 = Rubik 2 0 0 2 5 2 5 5 3 3 3 1 1 1 1 1 0 2 4 5 4 5 2 4 3 3 1 3 1 3 3 1 2 4 5 2 0 2 4 0 4 0 0 4 0 4 5 5 := by rewrite_search_using [`ematch]\n-- lemma Rubik_test_6 : Rubik 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 = Rubik 3 3 3 1 4 1 0 5 2 0 0 5 1 2 1 1 4 4 3 5 3 5 2 2 2 3 4 2 0 1 5 4 0 0 0 2 4 5 5 1 4 1 0 4 2 5 3 3 := by rewrite_search_using [`ematch]\n-- lemma Rubik_test_7 : Rubik 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 = Rubik 4 0 0 2 0 1 3 4 3 1 0 3 0 5 4 0 4 2 3 4 3 3 1 1 5 1 1 5 3 5 2 2 2 2 0 4 0 5 5 3 2 4 4 5 5 2 1 1 := by rewrite_search_using [`ematch]\n-- lemma Rubik_test_8 : Rubik 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 = Rubik 2 1 5 3 4 3 0 4 0 4 4 2 1 2 1 1 0 2 1 0 0 0 3 5 0 0 1 3 1 3 5 2 4 4 3 5 5 5 3 5 2 2 4 2 4 3 5 1 := by rewrite_search_using [`ematch]\n-- lemma Rubik_test_9 : Rubik 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 = Rubik 2 5 2 5 2 1 2 4 3 1 0 3 0 0 3 5 4 0 0 4 0 4 4 2 3 1 1 1 3 1 5 4 5 4 5 2 5 5 3 2 1 1 0 0 2 3 4 3 := by rewrite_search_using [`ematch]\n-- lemma Rubik_test_10 : Rubik 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 = Rubik 5 1 2 2 5 4 0 0 4 3 3 4 3 4 2 2 5 4 3 4 5 3 2 0 4 4 0 1 3 3 2 2 1 0 1 0 1 5 5 1 5 5 2 0 1 0 3 1 := by rewrite_search_using [`ematch]\n-- lemma Rubik_test_20 : Rubik 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 = Rubik 1 0 5 1 5 3 5 3 2 4 5 5 5 0 4 2 4 2 4 4 1 1 3 1 0 3 1 2 2 4 2 3 4 1 5 0 1 5 4 2 0 0 0 0 3 3 3 2 := by rewrite_search_using [`ematch]\n-- lemma Rubik_test_30 : Rubik 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 = Rubik 5 3 4 0 4 3 2 5 1 1 4 4 0 3 2 1 0 5 1 4 3 0 5 4 4 3 1 5 1 5 1 3 0 0 2 4 5 2 2 2 2 1 3 3 2 5 0 0 := by rewrite_search_using [`ematch]\n-- lemma Rubik_test_40 : Rubik 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 = Rubik 0 4 5 4 1 0 5 3 4 0 2 1 3 0 1 4 3 3 2 4 5 0 2 3 5 2 2 1 2 4 2 5 1 5 3 3 0 4 3 1 1 0 5 4 5 2 0 1 := by rewrite_search_using [`ematch]\n-- lemma Rubik_test_50 : Rubik 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 = Rubik 1 0 1 4 4 3 5 0 5 1 4 1 0 3 3 0 0 3 2 2 1 2 5 5 3 0 0 2 1 1 2 3 4 3 4 5 0 5 5 5 1 2 2 4 3 4 4 2 := by rewrite_search_using [`ematch]\n-- lemma Rubik_test_60 : Rubik 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 = Rubik 4 5 1 3 5 5 1 0 5 5 3 4 4 1 3 4 2 4 2 0 2 3 4 1 3 2 5 0 3 0 2 4 2 1 3 2 3 1 0 0 0 5 2 0 1 4 1 5 := by rewrite_search_using [`ematch]\n-- lemma Rubik_test_70 : Rubik 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 = Rubik 0 3 1 5 4 5 4 0 1 4 3 4 2 1 5 2 2 1 3 5 0 1 2 5 4 3 4 1 2 3 2 3 5 5 4 0 0 2 3 5 0 3 4 1 1 2 0 0 := by rewrite_search_using [`ematch]\n-- lemma Rubik_test_80 : Rubik 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 = Rubik 5 0 2 0 1 0 4 1 2 3 3 4 3 5 1 5 4 5 5 4 2 4 2 0 2 2 3 5 5 1 2 1 0 1 3 3 1 0 4 4 1 3 4 5 0 3 0 2 := by rewrite_search_using [`ematch]\n-- lemma Rubik_test_90 : Rubik 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 = Rubik 1 3 1 3 2 4 4 3 2 0 3 4 4 1 5 0 5 1 2 0 0 3 2 0 5 1 4 1 5 1 5 3 5 4 5 2 5 0 2 2 2 0 4 3 1 0 3 4 := by rewrite_search_using [`ematch]\n-- lemma Rubik_test_100 : Rubik 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 = Rubik 0 2 3 2 1 3 5 1 1 3 4 1 0 2 1 1 0 1 4 3 4 2 0 0 5 0 5 0 3 2 5 5 4 5 4 4 4 2 3 3 5 2 1 2 4 0 5 3 := by rewrite_search_using [`ematch]\n-- lemma Rubik_test_200 : Rubik 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 = Rubik 2 3 3 1 1 1 1 2 0 0 2 2 3 4 3 5 0 4 1 5 5 3 5 1 5 2 2 1 3 4 2 4 5 2 3 0 5 1 0 0 4 4 0 4 0 3 4 5 := by rewrite_search_using [`ematch]\n-- lemma Rubik_test_300 : Rubik 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 = Rubik 2 1 3 4 3 4 1 0 1 3 1 2 4 0 4 3 0 5 3 5 2 5 1 5 4 2 5 5 0 4 3 2 4 4 0 3 0 5 2 2 2 0 1 0 5 3 1 1 := by rewrite_search_using [`ematch]\n-- lemma Rubik_test_400 : Rubik 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 = Rubik 0 4 5 4 0 3 0 0 4 1 0 5 5 5 1 0 2 3 4 3 3 2 0 1 1 1 1 4 4 2 2 5 4 0 3 5 2 3 1 3 1 2 5 5 3 2 2 4 := by rewrite_search_using [`ematch]\n-- lemma Rubik_test_500 : Rubik 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 = Rubik 2 2 3 2 0 1 3 5 5 0 2 2 1 2 5 0 0 4 1 0 1 4 1 5 4 3 0 4 2 3 4 4 2 3 1 5 1 0 0 5 3 5 4 3 5 3 4 1 := by rewrite_search_using [`ematch]\n-- lemma Rubik_test_600 : Rubik 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 = Rubik 4 4 4 3 0 1 5 5 1 0 5 0 2 0 3 2 2 1 3 3 5 0 4 4 2 2 0 2 5 5 2 1 3 1 5 3 4 4 0 1 3 5 3 4 1 2 1 0 := by rewrite_search_using [`ematch]\n-- lemma Rubik_test_700 : Rubik 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 = Rubik 5 0 3 4 4 5 2 4 2 3 2 1 1 5 4 0 1 3 0 5 2 2 4 1 3 1 5 5 3 4 0 2 4 3 3 5 0 0 1 1 1 0 0 5 2 4 2 3 := by rewrite_search_using [`ematch]\n-- lemma Rubik_test_800 : Rubik 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 = Rubik 0 1 5 3 0 5 3 5 2 4 1 0 5 3 1 0 4 5 3 4 5 1 1 0 2 1 2 2 3 3 3 4 1 5 1 0 2 3 0 5 4 2 2 4 2 4 4 0 := by rewrite_search_using [`ematch]\n-- lemma Rubik_test_900 : Rubik 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 = Rubik 0 0 5 0 4 1 1 0 2 2 4 2 1 4 2 2 5 5 2 0 4 5 2 3 3 5 4 1 0 0 3 5 3 3 1 4 3 2 5 1 1 5 4 1 4 0 3 3 := by rewrite_search_using [`ematch]\n-- lemma Rubik_test_1000 : Rubik 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 = Rubik 3 2 4 0 5 5 5 0 4 4 2 4 3 3 2 5 1 1 2 5 1 2 0 4 3 4 1 2 4 1 2 1 0 5 5 3 1 0 1 4 3 3 5 3 0 0 0 2 := by rewrite_search_using [`ematch]\n", "meta": {"author": "semorrison", "repo": "lean-rewrite-search", "sha": "e804b8f2753366b8957be839908230ee73f9e89f", "save_path": "github-repos/lean/semorrison-lean-rewrite-search", "path": "github-repos/lean/semorrison-lean-rewrite-search/lean-rewrite-search-e804b8f2753366b8957be839908230ee73f9e89f/examples/rubiks_cube.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.320821300824607, "lm_q2_score": 0.024423092583796175, "lm_q1q2_score": 0.007835448332893302}} {"text": "import pseudo_normed_group.category.CompHausFiltPseuNormGrpWithTinv\n/-!\n\n# The category of profinitely filtered pseudo-normed groups (and friends).\n\nThe category of profinite pseudo-normed groups, and the category of\nprofinitely filtered pseudo-normed groups equipped with an action of T⁻¹.\n\n-/\nuniverse variables u\n\nopen category_theory\nopen_locale nnreal\n\nlocal attribute [instance] type_pow\n\nnoncomputable theory\n\n/-- The category of profinitely filtered pseudo-normed groups with action of `T⁻¹`. -/\ndef ProFiltPseuNormGrpWithTinv (r : ℝ≥0) : Type (u+1) :=\nbundled (@profinitely_filtered_pseudo_normed_group_with_Tinv r)\n\nnamespace ProFiltPseuNormGrpWithTinv\n\nvariables (r' : ℝ≥0)\n\nlocal attribute [instance] CompHausFiltPseuNormGrpWithTinv.bundled_hom\n\ndef bundled_hom : bundled_hom.parent_projection\n (@profinitely_filtered_pseudo_normed_group_with_Tinv.to_comphaus_filtered_pseudo_normed_group_with_Tinv r') := ⟨⟩\n\nlocal attribute [instance] bundled_hom\n\n/-\ninstance bundled_hom : bundled_hom (@comphaus_filtered_pseudo_normed_group_with_Tinv_hom r') :=\n⟨@comphaus_filtered_pseudo_normed_group_with_Tinv_hom.to_fun r',\n @comphaus_filtered_pseudo_normed_group_with_Tinv_hom.id r',\n @comphaus_filtered_pseudo_normed_group_with_Tinv_hom.comp r',\n @comphaus_filtered_pseudo_normed_group_with_Tinv_hom.coe_inj r'⟩\n-/\n\nattribute [derive [λ α, has_coe_to_sort α (Sort*), large_category, concrete_category]]\n ProFiltPseuNormGrpWithTinv\n\n/-- Construct a bundled `ProFiltPseuNormGrpWithTinv` from the underlying type and typeclass. -/\ndef of (r' : ℝ≥0) (M : Type u) [profinitely_filtered_pseudo_normed_group_with_Tinv r' M] :\n ProFiltPseuNormGrpWithTinv r' :=\nbundled.of M\n\ninstance : has_zero (ProFiltPseuNormGrpWithTinv r') :=\n⟨{ α := punit, str := punit.profinitely_filtered_pseudo_normed_group_with_Tinv r' }⟩\n\ninstance : inhabited (ProFiltPseuNormGrpWithTinv r') := ⟨0⟩\n\ninstance (M : ProFiltPseuNormGrpWithTinv r') :\n profinitely_filtered_pseudo_normed_group_with_Tinv r' M := M.str\n\n@[simp] lemma coe_of (V : Type u) [profinitely_filtered_pseudo_normed_group_with_Tinv r' V] :\n (ProFiltPseuNormGrpWithTinv.of r' V : Type u) = V := rfl\n\n@[simp] lemma of_coe (M : ProFiltPseuNormGrpWithTinv r') : of r' M = M :=\nby { cases M, refl }\n\n@[simp] lemma coe_id (V : ProFiltPseuNormGrpWithTinv r') : ⇑(𝟙 V) = id := rfl\n\n@[simp] lemma coe_comp {A B C : ProFiltPseuNormGrpWithTinv r'} (f : A ⟶ B) (g : B ⟶ C) :\n ⇑(f ≫ g) = g ∘ f := rfl\n\n@[simp] lemma coe_comp_apply {A B C : ProFiltPseuNormGrpWithTinv r'} (f : A ⟶ B) (g : B ⟶ C) (x : A) :\n (f ≫ g) x = g (f x) := rfl\nopen pseudo_normed_group\n\nsection\n\nvariables (M : Type*) [profinitely_filtered_pseudo_normed_group_with_Tinv r' M] (c : ℝ≥0)\ninclude r'\n\ninstance : t2_space (Top.of (filtration M c)) := by { dsimp, apply_instance }\ninstance : totally_disconnected_space (Top.of (filtration M c)) := by { dsimp, apply_instance }\ninstance : compact_space (Top.of (filtration M c)) := by { dsimp, apply_instance }\n\nend\n\n-- @[simps] def Filtration (c : ℝ≥0) : ProFiltPseuNormGrp ⥤ Profinite :=\n-- { obj := λ M, ⟨Top.of (filtration M c)⟩,\n-- map := λ M₁ M₂ f, ⟨f.level c, f.level_continuous c⟩,\n-- map_id' := by { intros, ext, refl },\n-- map_comp' := by { intros, ext, refl } }\n\n\nopen pseudo_normed_group comphaus_filtered_pseudo_normed_group_with_Tinv_hom\n\nopen profinitely_filtered_pseudo_normed_group_with_Tinv (Tinv)\n\nvariables {r'}\nvariables {M M₁ M₂ : ProFiltPseuNormGrpWithTinv.{u} r'}\nvariables {f : M₁ ⟶ M₂}\n\n/-- The isomorphism induced by a bijective `comphaus_filtered_pseudo_normed_group_with_Tinv_hom`\nwhose inverse is strict. -/\ndef iso_of_equiv_of_strict (e : M₁ ≃+ M₂) (he : ∀ x, f x = e x)\n (strict : ∀ ⦃c x⦄, x ∈ filtration M₂ c → e.symm x ∈ filtration M₁ c) :\n M₁ ≅ M₂ :=\n{ hom := f,\n inv := inv_of_equiv_of_strict e he strict,\n hom_inv_id' := by { ext x, simp [inv_of_equiv_of_strict, he] },\n inv_hom_id' := by { ext x, simp [inv_of_equiv_of_strict, he] } }\n\n@[simp]\nlemma iso_of_equiv_of_strict.apply (e : M₁ ≃+ M₂) (he : ∀ x, f x = e x)\n (strict : ∀ ⦃c x⦄, x ∈ filtration M₂ c → e.symm x ∈ filtration M₁ c) (x : M₁) :\n (iso_of_equiv_of_strict e he strict).hom x = f x := rfl\n\n@[simp]\nlemma iso_of_equiv_of_strict_symm.apply (e : M₁ ≃+ M₂) (he : ∀ x, f x = e x)\n (strict : ∀ ⦃c x⦄, x ∈ filtration M₂ c → e.symm x ∈ filtration M₁ c) (x : M₂) :\n (iso_of_equiv_of_strict e he strict).symm.hom x = e.symm x := rfl\n\ndef iso_of_equiv_of_strict'\n (e : M₁ ≃+ M₂)\n (strict' : ∀ c x, x ∈ filtration M₁ c ↔ e x ∈ filtration M₂ c)\n (continuous' : ∀ c, continuous (pseudo_normed_group.level e (λ c x, (strict' c x).1) c))\n (map_Tinv' : ∀ x, e (Tinv x) = Tinv (e x)) :\n M₁ ≅ M₂ :=\n@iso_of_equiv_of_strict r' M₁ M₂\n {to_fun := e,\n strict' := λ c x, (strict' c x).1,\n continuous' := continuous',\n map_Tinv' := map_Tinv',\n ..e.to_add_monoid_hom } e (λ _, rfl)\n (by { intros c x hx, rwa [strict', e.apply_symm_apply] })\n\n@[simp]\nlemma iso_of_equiv_of_strict'_hom_apply\n (e : M₁ ≃+ M₂)\n (strict' : ∀ c x, x ∈ filtration M₁ c ↔ e x ∈ filtration M₂ c)\n (continuous' : ∀ c, continuous (pseudo_normed_group.level e (λ c x, (strict' c x).1) c))\n (map_Tinv' : ∀ x, e (Tinv x) = Tinv (e x))\n (x : M₁) :\n (iso_of_equiv_of_strict' e strict' continuous' map_Tinv').hom x = e x := rfl\n\n@[simp]\nlemma iso_of_equiv_of_strict'_inv_apply\n (e : M₁ ≃+ M₂)\n (strict' : ∀ c x, x ∈ filtration M₁ c ↔ e x ∈ filtration M₂ c)\n (continuous' : ∀ c, continuous (pseudo_normed_group.level e (λ c x, (strict' c x).1) c))\n (map_Tinv' : ∀ x, e (Tinv x) = Tinv (e x))\n (x : M₂) :\n (iso_of_equiv_of_strict' e strict' continuous' map_Tinv').inv x = e.symm x := rfl\n\nvariables (r')\n\n@[simps]\ndef Pow (n : ℕ) : ProFiltPseuNormGrpWithTinv.{u} r' ⥤ ProFiltPseuNormGrpWithTinv.{u} r' :=\n{ obj := λ M, of r' $ M ^ n,\n map := λ M₁ M₂ f, profinitely_filtered_pseudo_normed_group_with_Tinv.pi_map r' _ _ (λ i, f),\n map_id' := λ M, by { ext, refl },\n map_comp' := by { intros, ext, refl } }\n\n@[simps]\ndef Pow_Pow_X_equiv (N n : ℕ) :\n M ^ (N * n) ≃+ (M ^ N) ^ n :=\n{ to_fun := ((equiv.curry _ _ _).symm.trans (((equiv.prod_comm _ _).trans fin_prod_fin_equiv).arrow_congr (equiv.refl _))).symm,\n map_add' := λ x y, by { ext, refl },\n .. ((equiv.curry _ _ _).symm.trans (((equiv.prod_comm _ _).trans fin_prod_fin_equiv).arrow_congr (equiv.refl _))).symm }\n\nopen profinitely_filtered_pseudo_normed_group\nopen comphaus_filtered_pseudo_normed_group\n\n@[simps]\ndef Pow_Pow_X (N n : ℕ) (M : ProFiltPseuNormGrpWithTinv.{u} r') :\n (Pow r' N ⋙ Pow r' n).obj M ≅ (Pow r' (N * n)).obj M :=\niso.symm $\niso_of_equiv_of_strict'\n (Pow_Pow_X_equiv r' N n)\n begin\n intros c x,\n dsimp,\n split; intro h,\n { intros i j, exact h (fin_prod_fin_equiv (j, i)) },\n { intro ij,\n have := h (fin_prod_fin_equiv.symm ij).2 (fin_prod_fin_equiv.symm ij).1,\n dsimp [-fin_prod_fin_equiv_symm_apply] at this,\n simpa only [prod.mk.eta, equiv.apply_symm_apply] using this, },\n end\n begin\n intro c, dsimp,\n rw [← (filtration_pi_homeo (λ _, M ^ N) c).comp_continuous_iff,\n ← (filtration_pi_homeo (λ _, M) c).symm.comp_continuous_iff'],\n apply continuous_pi,\n intro i,\n rw [← (filtration_pi_homeo (λ _, M) c).comp_continuous_iff],\n apply continuous_pi,\n intro j,\n have := @continuous_apply _ (λ _, filtration M c) _ (fin_prod_fin_equiv (j, i)),\n dsimp [function.comp] at this ⊢,\n simpa only [subtype.coe_eta],\n end\n (by { intros, ext, refl })\n\n@[simps hom inv]\ndef Pow_mul (N n : ℕ) : Pow r' (N * n) ≅ Pow r' N ⋙ Pow r' n :=\nnat_iso.of_components (λ M, (Pow_Pow_X r' N n M).symm)\nbegin\n intros X Y f,\n ext x i j,\n refl,\nend\n\nend ProFiltPseuNormGrpWithTinv\n", "meta": {"author": "leanprover-community", "repo": "lean-liquid", "sha": "92f188bd17f34dbfefc92a83069577f708851aec", "save_path": "github-repos/lean/leanprover-community-lean-liquid", "path": "github-repos/lean/leanprover-community-lean-liquid/lean-liquid-92f188bd17f34dbfefc92a83069577f708851aec/src/pseudo_normed_group/category/ProFiltPseuNormGrpWithTinv.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.27512971193602087, "lm_q2_score": 0.027585283925573398, "lm_q1q2_score": 0.007589531220116356}} {"text": "import ReactorModel.Objects.Reactor.Theorems.Indexable\nimport ReactorModel.Objects.Reactor.Wellformed\n\nnoncomputable section\nopen Classical Reactor\n\nnamespace ReactorType\n\nscoped macro \"lawfulCoe_nest_proof\" : tactic => \n `(tactic| simp [ReactorType.nest, Partial.map_map, Function.comp, Partial.attach_map_val])\n\nscoped macro \"lawfulCoe_inj_proof\" : tactic => \n `(tactic| (simp [Function.Injective]; intro ⟨_, _⟩ ⟨_, _⟩; simp))\n\nclass LawfulCoe (α β) [a : ReactorType α] [b : ReactorType β] extends Coe α β where\n ports : b.ports ∘ coe = a.ports := by rfl\n acts : b.acts ∘ coe = a.acts := by rfl\n rcns : b.rcns ∘ coe = a.rcns := by rfl\n state : b.state ∘ coe = a.state := by rfl\n nest : b.nest ∘ coe = (Partial.map coe) ∘ a.nest := by lawfulCoe_nest_proof\n inj : coe.Injective := by lawfulCoe_inj_proof\n\nnamespace LawfulCoe\n\nvariable [a : ReactorType α] [b : ReactorType β] [c : LawfulCoe α β] {rtr : α}\n\ntheorem nest' [a : ReactorType α] [b : ReactorType β] [c : LawfulCoe α β] :\n b.nest (c.coe rtr) = (a.nest rtr).map c.coe := by\n rw [←Function.comp_apply (f := ReactorType.nest), c.nest]\n simp\n\ntheorem coe_ext_iff [ReactorType α] [ReactorType β] [c : LawfulCoe α β] \n {rtr₁ rtr₂ : α} : rtr₁ = rtr₂ ↔ (rtr₁ : β) = (rtr₂ : β) :=\n ⟨(congr_arg _ ·), (c.inj ·)⟩\n\ninstance : Coe (a.cptType cpt) (b.cptType cpt) where\n coe := \n match cpt with\n | .rcn | .prt _ | .act | .stv => id\n | .rtr => c.coe\n\ntheorem lower_cpt?_eq_some (cpt) {o} (h : a.cpt? cpt rtr i = some o) : \n b.cpt? cpt rtr i = some ↑o := by\n split <;> simp_all [cpt?, ←c.rcns, ←c.ports, ←c.acts, ←c.state]\n simp [c.nest', Partial.map_val]\n exists o\n\ntheorem lower_mem_cpt? (cpt) (h : i ∈ a.cpt? cpt rtr) : i ∈ b.cpt? cpt rtr :=\n ⟨h.choose, c.lower_cpt?_eq_some _ h.choose_spec⟩ \n\ntheorem lift_cpt?_eq_none (cpt) {i : ID} \n (h : b.cpt? cpt rtr i = none) : a.cpt? cpt rtr i = none := by\n cases cpt <;> try cases ‹Component.Valued›\n all_goals simp_all [cpt?, ←c.rcns, ←c.ports, ←c.acts, ←c.state] \n simp [c.nest', Partial.map_val] at h\n exact h\n\ntheorem lift_cpt?_eq_some (cpt) {i : ID} {o : a.cptType cpt} (h : b.cpt? cpt rtr i = some ↑o) : \n a.cpt? cpt rtr i = some o := by\n split at h <;> simp_all [cpt?, ←c.rcns, ←c.ports, ←c.acts, ←c.state]\n simp [c.nest', Partial.map_val] at h\n have ⟨_, _, h⟩ := h\n cases c.inj h\n assumption\n\ntheorem lift_nest_eq_some {i : ID} (h : b.nest rtr i = some n₂) : \n ∃ n₁, (a.nest rtr i = some n₁) ∧ ((n₁ : β) = n₂) := by\n simp [c.nest', Partial.map_val] at h\n exact h\n\n-- Note: This theorem excludes `cpt = .rtr`, because that case is harder than the other cases and we\n-- only ever use this theorem for `cpt = .act` anyway.\ntheorem lift_mem_cpt? (cpt) (h : i ∈ b.cpt? cpt rtr) (hc : cpt ≠ .rtr := by simp) : \n i ∈ a.cpt? cpt rtr := by\n cases cpt <;> try cases ‹Component.Valued› \n case rtr => contradiction\n all_goals exact ⟨h.choose, c.lift_cpt?_eq_some _ h.choose_spec⟩ \n\nend LawfulCoe\n\ndef Member.fromLawfulCoe [ReactorType α] [ReactorType β] [c : LawfulCoe α β] {rtr : α} : \n (Member cpt i rtr) → Member cpt i (rtr : β)\n | final h => final (c.lower_mem_cpt? _ h)\n | nest h m => nest (c.lower_cpt?_eq_some (cpt := .rtr) h) (fromLawfulCoe m)\n\ninstance [ReactorType α] [ReactorType β] [c : LawfulCoe α β] {rtr : α} :\n Coe (Member cpt i rtr) (Member cpt i (rtr : β)) where\n coe := Member.fromLawfulCoe\n\ninstance [ReactorType α] [e : Extensional β] [c : LawfulCoe α β] : Extensional α where\n ext_iff := by\n intro rtr₁ rtr₂ \n simp [c.coe_ext_iff, e.ext_iff, ←c.ports, ←c.acts, ←c.rcns, ←c.state, c.nest']\n intros\n exact {\n mp := Partial.map_inj (by simp [Function.Injective, c.coe_ext_iff])\n mpr := by simp_all\n }\n\ninstance [Extensional α] [b : ReactorType.WellFounded β] [c : LawfulCoe α β] : \n ReactorType.WellFounded α where\n wf := by\n suffices h : InvImage Nested c.coe = Nested from h ▸ InvImage.wf c.coe b.wf\n funext rtr₁ rtr₂\n simp [Nested, InvImage, c.nest', Partial.map_val]\n exact ⟨fun ⟨_, ⟨_, hn, h⟩⟩ => ⟨_, c.inj h ▸ hn⟩, fun ⟨i, h⟩ => ⟨i, rtr₁, by simp [h]⟩⟩ \n\nvariable [ReactorType α] [ReactorType β] in section\n\ntheorem RootEqualUpTo.lift [l : LawfulCoe α β] {rtr₁ rtr₂ : α} \n (e : RootEqualUpTo cpt i (rtr₁ : β) (rtr₂ : β)) : RootEqualUpTo cpt i rtr₁ rtr₂ := by\n intro c j h\n have he := e h\n cases h₁ : cpt? c (rtr₁ : β) j <;> cases h₂ : cpt? c (rtr₂ : β) j <;> simp_all\n case none.none => simp [l.lift_cpt?_eq_none _ h₁, l.lift_cpt?_eq_none _ h₂]\n case some.some => \n cases c <;> try cases ‹Reactor.Component.Valued› \n all_goals try simp [l.lift_cpt?_eq_some _ h₁, l.lift_cpt?_eq_some _ h₂]\n case rtr =>\n have ⟨_, _, h₁'⟩ := l.lift_nest_eq_some h₁\n have ⟨_, _, h₂'⟩ := l.lift_nest_eq_some h₂\n subst h₁'\n simp [l.lift_cpt?_eq_some _ h₁, l.lift_cpt?_eq_some _ h₂]\n\ndef LawfulMemUpdate.lift [c : LawfulCoe α β] {rtr₁ rtr₂ : α} :\n (LawfulMemUpdate cpt i f (rtr₁ : β) (rtr₂ : β)) → LawfulMemUpdate cpt i f rtr₁ rtr₂\n | final e h₁ h₂ (o := o) => \n have h₁ : cpt? cpt rtr₁ i = some o := by cases cpt <;> exact c.lift_cpt?_eq_some _ h₁\n have h₂ : cpt? cpt rtr₂ i = some (f o) := by cases cpt <;> exact c.lift_cpt?_eq_some _ h₂\n .final e.lift h₁ h₂\n | nest (n₁ := n₁) (n₂ := n₂) e h₁ h₂ u (j := j) => \n have o₁ := c.lift_nest_eq_some h₁\n have o₂ := c.lift_nest_eq_some h₂\n have ⟨h₁, h₁'⟩ := o₁.choose_spec\n have ⟨h₂, h₂'⟩ := o₂.choose_spec \n let u' : LawfulMemUpdate cpt i f (o₁.choose : β) (o₂.choose : β) := cast (by simp [h₁', h₂']) u\n .nest e.lift h₁ h₂ u'.lift\ntermination_by lift u => sizeOf u\ndecreasing_by simp_wf; have h : sizeOf u' = sizeOf u := (by congr; apply cast_heq); simp [h]\n\n-- TODO:\n-- If we consider the following following diagram:\n-- \n-- rtr₁ -u.lift→ rtr₂\n-- | |\n-- coe coe\n-- ↓ ↓\n-- (rtr₁ : β) -u→ (rtr₂ : β)\n--\n-- ... there's something functorial about this. The `lift` looks like a functor's `map` over `u`.\n-- Figure out if there's a way of modelling some part of this as a functor. \ndef LawfulUpdate.lift [c : LawfulCoe α β] {rtr₁ rtr₂ : α} :\n (LawfulUpdate cpt i f (rtr₁ : β) (rtr₂ : β)) → LawfulUpdate cpt i f rtr₁ rtr₂\n | update u => update u.lift\n | notMem h eq => \n let u := notMem (byContradiction (h.false $ not_isEmpty_iff.mp · |>.some.fromLawfulCoe)) rfl\n (c.inj eq) ▸ u \n\nend\n\nscoped macro \"lawfulUpdatableCoe_update_coe_comm_proof\" : tactic =>\n `(tactic| simp [Updatable.update, Coe.coe])\n\nclass LawfulUpdatableCoe (α β) [a : Updatable α] [b : Updatable β] extends LawfulCoe α β where\n update_coe_comm : \n ∀ {rtr cpt i f}, b.update (coe rtr) cpt i f = coe (a.update rtr cpt i f) := by \n lawfulUpdatableCoe_update_coe_comm_proof\n\ninstance [Updatable α] [LawfulUpdatable β] [c : LawfulUpdatableCoe α β] : LawfulUpdatable α where\n lawful rtr cpt i f := c.update_coe_comm ▸ LawfulUpdatable.lawful (rtr : β) cpt i f |>.lift \n\nvariable [a : Indexable α] [b : Indexable β] [c : LawfulCoe α β] {rtr : α}\n\nnamespace LawfulCoe\n\ntheorem lower_container_eq {m : Member cpt i rtr} (h : m.container = con) : \n (m : Member cpt i (rtr : β)).container = ↑con := by\n induction m\n case final =>\n simp [Member.container] at h ⊢\n simp [←h]\n case nest m hi => \n cases m \n case final => \n simp [Member.fromLawfulCoe, Member.container] at h ⊢\n simp [← h] \n case nest hi =>\n simp [Member.container] at h\n simp [←hi h, Member.fromLawfulCoe, Member.container]\n\ntheorem lower_con?_some (h : rtr[cpt][i]& = some con) : (rtr : β)[cpt][i]& = some ↑con := by\n simp [Indexable.con?] at h ⊢\n split at h\n case inr => contradiction \n case inl n =>\n injection h with h\n simp [(⟨n.some⟩ : Nonempty (Member cpt i (rtr : β)))]\n simp [←c.lower_container_eq h, (⟨n.some⟩ : Nonempty (Member cpt i (rtr : β)))]\n congr\n apply b.unique_ids.allEq\n\ntheorem lower_obj?_some {i o} (h : rtr[cpt][i] = some o) : (rtr : β)[cpt][i] = some ↑o := by\n cases cpt <;> try cases i\n case rtr.none => simp_all [Indexable.obj?]\n all_goals\n have ⟨_, h₁, h₂⟩ := a.obj?_to_con?_and_cpt? h\n simp [Indexable.obj?, bind, c.lower_con?_some h₁, c.lower_cpt?_eq_some _ h₂]\n\ntheorem lower_mem_obj? {i} (h : i ∈ rtr[cpt]) : i ∈ (rtr : β)[cpt] :=\n Partial.mem_iff.mpr ⟨_, c.lower_obj?_some (Partial.mem_iff.mp h).choose_spec⟩ \n\nend LawfulCoe\n\ntheorem Dependency.lower [c : LawfulCoe α β] (d : i₁ <[rtr] i₂) : i₁ <[(rtr : β)] i₂ := by\n induction d with\n | prio h₁ h₂ h₃ =>\n exact prio (c.lower_obj?_some h₁) (c.lower_cpt?_eq_some .rcn h₂) (c.lower_cpt?_eq_some .rcn h₃) \n ‹_› ‹_›\n | mutNorm h₁ h₂ h₃ => \n exact mutNorm (c.lower_obj?_some h₁) (c.lower_cpt?_eq_some .rcn h₂)\n (c.lower_cpt?_eq_some .rcn h₃) ‹_› ‹_›\n | depOverlap h₁ h₂ => \n exact depOverlap (c.lower_obj?_some h₁) (c.lower_obj?_some h₂) ‹_› ‹_› ‹_›\n | mutNest h₁ h₂ h₃ _ h₄ => \n exact mutNest (c.lower_obj?_some h₁) (c.lower_cpt?_eq_some .rtr h₂)\n (c.lower_cpt?_eq_some .rcn h₃) ‹_› (c.lower_mem_cpt? .rcn h₄) \n | trans _ _ d₁ d₂ => \n exact trans d₁ d₂\n\ntheorem Dependency.Acyclic.lift [LawfulCoe α β] (a : Acyclic (rtr : β)) : Acyclic rtr :=\n fun i d => absurd d.lower (a i) \n \nnamespace Wellformed\n\nset_option hygiene false in\nscoped macro \"lift_nested_proof \" name:ident : term => `(\n fun hc hp => by\n have h := LawfulCoe.nest' (rtr := rtr) (β := β) ▸ hc \n simp [Partial.map_val] at h\n obtain ⟨_, _, h⟩ := h\n subst h\n exact $(Lean.mkIdentFrom name $ `ValidDependency ++ name.getId) \n (LawfulCoe.lift_cpt?_eq_some .rtr hc) (LawfulCoe.lift_mem_cpt? (.prt _) hp)\n)\n\ntheorem ValidDependency.lift [ReactorType α] [ReactorType β] [LawfulCoe α β] {rtr : α} : \n (ValidDependency (rtr : β) rk dk d) → ValidDependency rtr rk dk d \n | stv h => stv $ LawfulCoe.lift_mem_cpt? .stv h\n | act h => act $ LawfulCoe.lift_mem_cpt? .act h\n | prt h => prt $ LawfulCoe.lift_mem_cpt? (.prt _) h\n | nestedIn hc hp => (lift_nested_proof nestedIn) hc hp\n | nestedOut hc hp => (lift_nested_proof nestedOut) hc hp\n \nset_option hygiene false in \nscoped macro \"lift_prio_proof \" name:ident : term => `(\n fun h₁ h₂ h₃ => \n $(Lean.mkIdentFrom name $ `Wellformed ++ name.getId) ‹Wellformed (_ : β)› \n (LawfulCoe.lower_obj?_some h₁) (LawfulCoe.lower_cpt?_eq_some .rcn h₂) \n (LawfulCoe.lower_cpt?_eq_some .rcn h₃)\n)\n\ntheorem lift [Indexable α] [Indexable β] [c : LawfulCoe α β] {rtr : α} (wf : Wellformed (rtr : β)) : \n Wellformed rtr where\n overlap_prio := lift_prio_proof overlap_prio\n hazards_prio := lift_prio_proof hazards_prio\n mutation_prio := lift_prio_proof mutation_prio\n acyclic_deps := wf.acyclic_deps.lift (rtr := rtr)\n valid_deps h₁ h₂ h₃ := \n wf.valid_deps (c.lower_obj?_some h₁) (c.lower_cpt?_eq_some .rcn h₂) h₃ |>.lift\n unique_inputs h₁ h₂ _ h₃ := \n wf.unique_inputs (c.lower_obj?_some h₁) (c.lower_obj?_some h₂) ‹_› (c.lower_mem_obj? h₃)\n\nend Wellformed\nend ReactorType", "meta": {"author": "marcusrossel", "repo": "reactor-model", "sha": "f82fffb489b4352a0cc6bee964d44a142fee18ce", "save_path": "github-repos/lean/marcusrossel-reactor-model", "path": "github-repos/lean/marcusrossel-reactor-model/reactor-model-f82fffb489b4352a0cc6bee964d44a142fee18ce/src/ReactorModel/Objects/Reactor/Theorems/LawfulCoe.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3451052709578724, "lm_q2_score": 0.021948252755239293, "lm_q1q2_score": 0.007574457714148726}} {"text": "example : (`foo.bla).eraseSuffix? `bla == some `foo := rfl\nexample : (`foo.bla).eraseSuffix? `boo == none := rfl\nexample : (`foo.bla).eraseSuffix? `foo.bla == some .anonymous := rfl\nexample : (`foo.bla.boo).eraseSuffix? `bla == none := rfl\nexample : (`foo.bla.boo).eraseSuffix? `boo == `foo.bla := rfl\nexample : (`foo.bla.boo).eraseSuffix? `bla.boo == `foo := rfl\n", "meta": {"author": "leanprover", "repo": "lean4", "sha": "742d053a97bdd109a41a921facd1cd6a55e89bc7", "save_path": "github-repos/lean/leanprover-lean4", "path": "github-repos/lean/leanprover-lean4/lean4-742d053a97bdd109a41a921facd1cd6a55e89bc7/tests/lean/run/eraseSuffix.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.2598256379609837, "lm_q2_score": 0.02843602995724746, "lm_q1q2_score": 0.007388409624719465}} {"text": "\nimport data.real.basic\nimport data.hashable\nimport data.tactic\nimport tactic\nimport tactic.linarith\nimport system.io\n\nopen io io.fs io.process parser\n\ndef sum.coe {m α} [monad m] [monad_fail m] : string ⊕ α → m α\n| (sum.inl e) := monad_fail.fail $ \"\\n\" ++ e\n| (sum.inr e) := pure e\n\nmeta instance {α} : has_coe (string ⊕ α) (tactic α) := ⟨ sum.coe ⟩\ninstance sum.io_coe {α} : has_coe (string ⊕ α) (io α) := ⟨ sum.coe ⟩\n\nmeta instance int.reflect : has_reflect ℤ\n| x :=\nif x < 0 then cast undefined `(- %%(int.reflect x) : ℤ)\nelse if h₁ : x = 0 then cast (by rw h₁) `(0 : ℤ)\n else if h₂ : x = 1 then cast (by rw h₂) `(1 : ℤ)\n else if h₃ : x % 2 = 0 then cast undefined $ `(λ x : ℤ, bit0 x).subst (int.reflect (x / 2))\n else cast undefined `(bit1 %%(int.reflect (x / 2)) : ℤ)\n\nmeta def rat.has_reflect' : Π x : ℚ, Σ y : ℚ, Σ' h : x = y, reflected y\n| ⟨x,y,h,h'⟩ := ⟨rat.mk_nat x y, by { rw [rat.num_denom',rat.mk_nat_eq] } , `(_)⟩\n\nmeta instance : has_reflect ℚ\n| x :=\nmatch rat.has_reflect' x with\n| ⟨ ._, rfl, h ⟩ := h\nend\n\nnamespace smt\n\ninductive atom\n| num (s : ℤ)\n| dec (s : ℚ)\n-- | str (s : string)\n| sym (s : string)\n-- | keyword (s : string)\n\nprotected meta def atom.to_string : atom → string\n| (atom.num s) := to_string s\n| (atom.dec s) := to_string s\n-- | (atom.str s) := s\n| (atom.sym s) := s\n-- | (atom.keyword s) := s\n\nmeta instance atom.has_to_string : has_to_string atom :=\n⟨ atom.to_string ⟩\n\ninductive sexpr\n| const : atom → sexpr\n| fapp : list sexpr → sexpr\n\nprotected meta def sexpr.to_string : sexpr → string\n| (sexpr.const n) := to_string n\n| (sexpr.fapp args) := \"( \" ++ string.intercalate \" \" (args.map sexpr.to_string) ++ \" )\"\n\nmeta instance sexpr.has_to_string : has_to_string sexpr :=\n⟨ sexpr.to_string ⟩\n\ninductive type\n| int | real | array (idx rng : type)\n\nopen smt.type\n\ndef type.to_string : type → string\n| int := \"Int\"\n| real := \"Real\"\n| (array t₀ t₁) := \"(Array \" ++ t₀.to_string ++ \" \" ++ t₁.to_string ++ \")\"\n\ndef string.map (f : char → char) : string → string :=\nlist.as_string ∘ list.map f ∘ string.to_list\n\nprotected def name := string\nprotected def name.to_string : smt.name → string := id\n\ndef repl_prime : char → char\n| '\\'' := '@'\n| c := c\n\ndef to_smt_name : name → smt.name :=\nstring.map repl_prime ∘ name.to_string_with_sep \"_\"\n\ninductive expr'\n| all : smt.name → type → expr' → expr'\n| exist : smt.name → type → expr' → expr'\n| var : ℕ → expr'\n| lit : ℕ → expr'\n| const : smt.name → expr'\n| app : smt.name → list expr' → expr'\n\nopen smt.expr'\n\nmutual inductive bounded, all_bounded\nwith bounded : expr' → ℕ → Prop\n| all {n t e b} :\n bounded e (b+1) →\n bounded (all n t e) b\n| exist {n t e b} :\n bounded e (b+1) →\n bounded (exist n t e) b\n| var {n b} : n < b → bounded (var n) b\n| const {n b} : bounded (const n) b\n| lit {n b} : bounded (lit n) b\n| app {fn args b} :\n all_bounded args b →\n bounded (expr'.app fn args) b\nwith all_bounded : list expr' → ℕ → Prop\n| nil {b} : all_bounded [] b\n| cons {x xs b} :\n bounded x b →\n all_bounded xs b →\n all_bounded (x :: xs) b\n\ndef expr := { e // bounded e 0 }\n\nmeta def type.to_z3 : _root_.expr → string ⊕ type\n| `(ℤ) := sum.inr type.int\n| `(ℝ) := sum.inr type.real\n| `(%%a → %%b) := type.array <$> type.to_z3 a <*> type.to_z3 b\n| e := sum.inl $ (format!\"type not supported: {e}\").to_string\n\nmeta def z3_builtin : rbmap name (ℕ × name) :=\nrbmap.from_list\n[ (`eq, 1, `=),\n (`has_lt.lt, 2, `<),\n (`has_add.add, 2, `+),\n (`has_mul.mul, 2, `*),\n (`has_sub.sub, 2, `-),\n (`has_neg.neg, 2, `-),\n (`has_pow.pow, 3, `^),\n (`not, 0, `not) ]\n\nmeta def mk_lit : _root_.expr → string ⊕ ℕ\n| `(bit0 %%e) := (*2) <$> mk_lit e\n| `(bit1 %%e) := (λ n, 2*n + 1) <$> mk_lit e\n| `(@has_zero.zero _ _) := pure 0\n| `(@has_one.one _ _) := pure 1\n| e := sum.inl (format!\"invalid numeral {e}\").to_string\n\nmeta def to_z3' : _root_.expr → string ⊕ expr'\n| (expr.var n) := sum.inr $ expr'.var n\n| (expr.const n t) := sum.inr $ expr'.const (to_smt_name n)\n| e@`(bit0 _) := expr'.lit <$> mk_lit e\n| e@`(bit1 _) := expr'.lit <$> mk_lit e\n| e@`(@has_zero.zero _ _) := expr'.lit <$> mk_lit e\n| e@`(@has_one.one _ _) := expr'.lit <$> mk_lit e\n| e@(expr.app e₀ e₁) :=\nlet fn := e₀.get_app_fn,\n args := e.get_app_args in\nif fn.is_constant then do\n match z3_builtin.find fn.const_name with\n | (some (i,n)) :=\n expr'.app (to_smt_name n) <$> (args.drop i).traverse to_z3'\n | none := sum.inl (format!\"invalid function: {fn.const_name}\").to_string\n end\nelse sum.inl \"invalid function application\"\n| (expr.lam _ _ _ _) := sum.inl \"lambdas are not supported\"\n| (expr.pi n _ d b) := all (to_smt_name n) <$> type.to_z3 d <*> to_z3' b\n| (expr.elet n d t b) := sum.inl \"let are not supported\"\n| (expr.local_const _ n _ _) := sum.inr $ const (to_smt_name n)\n| (expr.mvar _ _ _) := sum.inl \"mvars are not supported\"\n| (expr.sort _) := sum.inl \"sort is not supported\"\n| (expr.macro _ _) := sum.inl \"macros are not supported\"\n\nlemma bounded.of_all {n t e b} : bounded (all n t e) b → bounded e (b+1)\n| (bounded.all h) := h\n\nlemma bounded.of_exist {n t e b} : bounded (exist n t e) b → bounded e (b+1)\n| (bounded.exist h) := h\n\nlemma bounded.of_var {n b} : bounded (var n) b → n < b\n| (bounded.var h) := h\n\nlemma bounded.of_app {fn args b} : bounded (expr'.app fn args) b → all_bounded args b\n| (bounded.app h) := h\n\nlemma all_bounded.head {x xs b} : all_bounded (x :: xs) b → bounded x b\n| (all_bounded.cons h _) := h\n\nlemma all_bounded.tail {x xs b} : all_bounded (x :: xs) b → all_bounded xs b\n| (all_bounded.cons _ h) := h\n\ndef decidable.map {p q : Prop} (f : p → q) (g : q → p) : decidable p → decidable q\n| (is_true p) := is_true $ f p\n| (is_false p) := is_false $ λ h, p (g h)\n\n-- open tactic\n-- meta def prove_dec : tactic unit :=\n-- do try well_founded_tactics.default_dec_tac,\n-- `[dsimp [has_well_founded.r,sizeof_measure,measure,inv_image,sizeof]],\n-- `[dsimp [has_sizeof.sizeof,psum.sizeof,sizeof]],\n-- `[dsimp [psigma.sizeof]],\n-- -- constructor,\n-- trace_state\n\nmutual def bounded.decide, all_bounded.decide\nwith bounded.decide : Π e b, decidable (bounded e b)\n| (var v) := λ b,\nif h : v < b then is_true $ bounded.var h\n else is_false $ by { intro, cases a, apply h a_a }\n| (const n) := λ b, is_true $ bounded.const\n| (lit n) := λ b, is_true $ bounded.lit\n| (all n t e) := λ b,\n -- have sizeof e < sizeof n + (sizeof t + sizeof e), from _,\n decidable.map bounded.all bounded.of_all (bounded.decide e (b+1))\n| (exist n t e) := λ b, decidable.map bounded.exist bounded.of_exist (bounded.decide e $ b+1)\n| (app fn args) := λ b, decidable.map bounded.app bounded.of_app (all_bounded.decide args b)\nwith all_bounded.decide : Π es b, decidable (all_bounded es b)\n| [] := λ b, is_true all_bounded.nil\n| (e :: es) := λ b,\nhave 2 < 1 + (1 + (1 + list.sizeof es)), by linarith,\nmatch bounded.decide e b with\n| (is_true h) :=\n match all_bounded.decide es b with\n | (is_true h') := is_true (all_bounded.cons h h')\n | (is_false h') := is_false (λ h'', h' h''.tail)\n end\n| (is_false h) := is_false (λ h', h h'.head)\nend\n\nlocal attribute [instance] bounded.decide all_bounded.decide\n\nmutual def expr'.to_string_aux, expr'.to_string_aux'\nwith expr'.to_string_aux : Π (e : expr') (vs : list smt.name), bounded e vs.length → string\n| (all v t e) vs h :=\n \"(forall ((\" ++ v ++ \" \" ++ t.to_string ++ \")) \" ++ e.to_string_aux (v :: vs) h.of_all ++ \")\"\n| (exist v t e) vs h := \"(exists ((\" ++ v ++ \" \" ++ t.to_string ++ \")) \" ++ e.to_string_aux (v :: vs) h.of_exist ++ \")\"\n| (var v) vs h := (vs.nth_le v h.of_var).to_string\n| (const v) _ _ := v\n| (lit v) _ _ := to_string v\n| (app fn args) vs h := \"(\" ++ fn ++ expr'.to_string_aux' args vs h.of_app ++ \")\"\nwith expr'.to_string_aux' : Π (e : list expr') (vs : list smt.name), all_bounded e vs.length → string\n| [] vs _ := \"\"\n| (x :: xs) vs h :=\nhave 2 < 1 + (1 + (1 + list.sizeof xs)), by linarith,\n\" \" ++ x.to_string_aux vs h.head ++ expr'.to_string_aux' xs vs h.tail\n\ndef expr.to_string : expr → string\n| ⟨e,h⟩ := e.to_string_aux [] h\n\nmeta def to_z3 (e : _root_.expr) : string ⊕ expr :=\ndo e' ← to_z3' e,\n if h : bounded e' 0 then pure ⟨e',h⟩\n else sum.inl \"wrong use of bound variables\"\n\nmeta def encode_local (v : _root_.expr) : tactic string :=\ndo t ← tactic.infer_type v,\n p ← tactic.is_prop t,\n if p then do\n e' ← to_z3 t,\n -- pure (format!\"(assert (! {e'.to_string} :named {v.local_pp_name}))\\n\").to_string\n pure (format!\"(assert {e'.to_string})\\n\").to_string\n else do\n t ← type.to_z3 t,\n -- pure (format!\"(declare-const {v.local_pp_name} {t.to_string})\\n\").to_string\n pure (format!\"(declare-fun {(to_smt_name v.local_pp_name).to_string} () {t.to_string})\\n\").to_string\n\nend smt\n\nnamespace smt.parser\nopen smt (atom sexpr)\nopen smt.atom\n\ndef white := () <$ sat char.is_whitespace\n\ndef space := () <$ many white\ndef space1 := () <$ many1 white\n\ndef ident := (mk_simple_name ∘ list.as_string) <$> parser.many1 (sat char.is_alphanum <|> '_' <$ ch '_')\n\ndef is_printable (c : char) : Prop :=\n32 ≤ c.val ∧ c.val ≤ 126\n\ndef is_symbol (c : char) : Prop :=\nc ∈ (\"~!@$%^&*_-+=<>.?/\").to_list\n\ninstance is_printable.decidable_pred : decidable_pred is_printable :=\nλ c, (by apply_instance : decidable (32 ≤ c.val ∧ c.val ≤ 126))\n\ninstance is_symbol.decidable_pred : decidable_pred is_symbol :=\nλ c, (by apply_instance : decidable (c ∈ (\"~!@$%^&*_-+=<>.?/\").to_list))\n\ndef simple_symbol : parser string := list.as_string <$> parser.many1 (sat is_symbol <|> sat char.is_alphanum)\ndef symbol : parser atom := sym <$> simple_symbol\n-- def keyword : parser atom := ch ':' *> atom.keyword <$> simple_symbol\n\ndef nat.of_char : list char → ℕ :=\nlist.foldl (λ n c, 10 * n + c.val - '0'.val) 0\n\ndef nat.bin_of_char : list char → ℕ :=\nlist.foldl (λ n c, 2 * n + c.val - '0'.val) 0\n\ndef nat.hex_of_char : list char → ℕ :=\nlet digit := \"0123456789abcdef\".to_list in\nlist.foldl (λ n c, 16 * n + list.index_of c.to_lower digit) 0\n\ndef rat.of_char : list char → ℚ :=\nlist.foldl (λ n (c : char), (n + ↑(c.val - '0'.val)) / 10) 0 ∘ list.reverse\n\ndef non_zero : parser char :=\nsat $ λ d, char.is_digit d ∧ d ≠ '0'\n\ndef numerals : parser (list char) :=\n((::) <$> non_zero <*> many (sat char.is_digit)) <|>\n['0'] <$ ch '0'\n\ndef parse_nat : parser ℕ :=\nnat.of_char <$> numerals\n\ndef decimal : parser atom :=\ndo x ← numerals,\n do { ch '.', many (ch '0'),\n y ← numerals,\n pure $ dec $ nat.of_char x + rat.of_char y } <|>\n pure (num $ nat.of_char x)\n\ndef any_of (xs : list char) : parser char :=\nsat (∈ xs)\n\ndef hexa : parser atom :=\nstr \"#x\" *>\n(num ∘ coe ∘ nat.hex_of_char) <$> many1 (sat char.is_digit <|> any_of \"abcdefABCDEF\".to_list)\n\ndef bin : parser atom :=\nstr \"#b\" *>\n(num ∘ coe ∘ nat.bin_of_char) <$> many1 (any_of ['0','1'])\n\n-- def parse_string : parser atom :=\n-- ch '\\\"' *>\n-- (atom.str ∘ list.as_string) <$> many\n-- ('\\\"' <$ str \"\\\"\\\"\" <|>\n-- sat (λ c, is_printable c ∧ c ≠ '\\\"') <|>\n-- sat char.is_whitespace) <*\n-- ch '\\\"'\n\ndef parse_atom : parser atom :=\ndecimal <|> hexa <|> bin <|>\n-- parse_string <|>\nsymbol -- <|> keyword\n\ndef sexpr_parser : parser sexpr :=\nparser.fix $ λ parser, (smt.sexpr.const <$> parse_atom) <|> (smt.sexpr.fapp <$> (ch '(' *> sep_by space parser <* ch ')') )\n\ndef brackets {α} (l r : string) (p : parser α) : parser α :=\nstr l *> p <* str r\n\ndef base_name : name → string\n| (name.mk_string s _) := s\n| _ := \"\"\n\nopen smt.sexpr tactic\n\nmeta def mk_assoc (n : name) : list expr → tactic expr\n| [] := fail \"mk_assoc []\"\n-- | [x] := pure x\n| (x :: xs) :=\n do mfoldl (λ a b, mk_app n [a,b]) x xs\n\nmeta def expr.of_sexpr : sexpr → tactic expr\n| (const (num n)) := pure `(n : _)\n| (const (dec n)) := pure `(n)\n-- | (const (sym \"=\")) := to_expr ``(@eq _)\n-- | (const (sym \"-\")) := to_expr ``(@has_sub.sub _ _)\n-- | (const (sym \"+\")) := to_expr ``(@has_add.add _ _)\n| (const (sym s)) := resolve_name s >>= to_expr\n| (fapp (const (sym \"-\") :: [x,y])) := [x,y].mmap expr.of_sexpr >>= mk_app ``has_sub.sub\n| (fapp (const (sym \"-\") :: [x])) := [x].mmap expr.of_sexpr >>= mk_app ``has_neg.neg\n| (fapp (const (sym \"not\") :: [x])) := [x].mmap expr.of_sexpr >>= mk_app ``not\n| (fapp (const (sym \"+\") :: xs)) := xs.mmap expr.of_sexpr >>= mk_assoc ``has_add.add\n| (fapp (const (sym \"and\") :: xs)) := xs.mmap expr.of_sexpr >>= mk_assoc ``_root_.and\n| (fapp (const (sym \"=\") :: [x,y])) := [x,y].mmap expr.of_sexpr >>= mk_app ``eq\n| (fapp (const (sym \"<=\") :: [x,y])) := [x,y].mmap expr.of_sexpr >>= mk_app ``has_le.le\n| (fapp (const (sym \"<\") :: [x,y])) := [x,y].mmap expr.of_sexpr >>= mk_app ``has_lt.lt\n| e@(fapp _) := fail format!\"fapp {e.to_string}\"\n\nmeta def mk_conj : list expr → expr\n| [] := `(true)\n| (x :: xs) := xs.foldl (λ a b, (`(and) : expr) a b) x\n\nmeta def and_prj : ℕ → expr → expr → tactic expr\n| 0 `(%%p ∧ %%q) h :=\n mk_mapp ``and.elim_left [p,q,h]\n| 0 p h := mk_app ``id [h]\n| (i+1) `(%%p ∧ %%q) h :=\n mk_mapp ``and.elim_right [p,q,h] >>= and_prj i q\n| (i+1) p h := fail format!\"invalid conjunction {p}\"\n\nmeta def clear_except (ls : list expr) : tactic unit :=\ndo n ← revert_lst ls,\n hs ← local_context,\n hs.reverse.mmap $ λ h, try $ clear_lst [h.local_pp_name],\n intron n\n\nend smt.parser\n\nnamespace smt\n\nmeta structure solver :=\n( cmd : string )\n( args : list string )\n( options : list string := [] )\n( output_to_file : option string := none )\n( proof_type : Type )\n( read : parser proof_type )\n( execute : proof_type → tactic unit )\n\nmeta instance : hashable solver :=\n{ hash_with_salt := λ ⟨a,b,c,d,_,_,_⟩, hash_with_salt (a,b,c,d) }\n\n@[derive [has_repr,hashable]]\ninductive logic_fragment\n| AUFLIA | AUFLIRA | LIA | LRA\n| QF_AUFLIA | QF_AX | QF_IDL | QF_LIA\n| QF_LRA | QF_RDL | QF_UF\n| QF_UFIDL | QF_UFLIA | QF_UFLRA | UFLRA\n| QF_NIA | QF_NRA\n-- |QF_UF\n-- |QF_IDL\n-- |QF_RDL\n-- |QF_UFIDL\n\nend smt\n", "meta": {"author": "cipher1024", "repo": "smt-lean", "sha": "a1ad7855ae01aca1f8be5b8c8df95a01a175d08e", "save_path": "github-repos/lean/cipher1024-smt-lean", "path": "github-repos/lean/cipher1024-smt-lean/smt-lean-a1ad7855ae01aca1f8be5b8c8df95a01a175d08e/src/smt/basic.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3629692055196168, "lm_q2_score": 0.02002344289764476, "lm_q1q2_score": 0.0072678931603255325}} {"text": "macro x:ident noWs \"(\" ys:term,* \")\" : term => `($x $ys*)\n\n#check id(1)\n\nmacro \"foo\" &\"only\" : tactic => `(trivial)\n\nexample : True := by foo only\n", "meta": {"author": "Kha", "repo": "lean4-nightly", "sha": "b4c92de57090e6c47b29d3575df53d86fce52752", "save_path": "github-repos/lean/Kha-lean4-nightly", "path": "github-repos/lean/Kha-lean4-nightly/lean4-nightly-b4c92de57090e6c47b29d3575df53d86fce52752/tests/lean/run/macroParams.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.23651623644570763, "lm_q2_score": 0.03021458630329351, "lm_q1q2_score": 0.007146240238219007}} {"text": "import Lean\n\nimport Smt.Reconstruction.Certifying.Boolean\nimport Smt.Reconstruction.Certifying.LiftOrNToImp\n\nnamespace Smt.Reconstruction.Certifying\n\nopen Lean Elab Tactic\n\ndef applyList (l: List Term) (res: Term) : TacticM Term :=\n match l with\n | [] => return res\n | t::ts =>\n withMainContext do\n let res' := Syntax.mkApp t #[res]\n let fname ← mkIdent <$> mkFreshId\n evalTactic (← `(tactic| have $fname := $res'))\n applyList ts fname\n\ndef mkAppList : List Term → Ident → Syntax\n| [], id => id\n| t::ts, id =>\n let rest := mkAppList ts id\n let rest := ⟨rest⟩\n Syntax.mkApp t #[rest]\n\ndef congTactics (tactics : List Term) (i : Nat) (id : Ident) (last : Bool) : TacticM Syntax :=\n match i with\n | 0 => do\n if last then\n let innerProof := mkAppList tactics id\n let innerProof: Term := ⟨innerProof⟩\n `($innerProof)\n else\n let id' := mkIdent (Name.mkSimple \"w\")\n let innerProof := mkAppList tactics id'\n let innerProof: Term := ⟨innerProof⟩\n `(congOrRight (fun $id' => $innerProof) $id)\n | (i' + 1) => do\n let id' := mkIdent (Name.mkSimple \"w\")\n let r ← congTactics tactics i' id' last\n let r: Term := ⟨r⟩\n `(congOrLeft (fun $id' => $r) $id)\n\n-- pull j-th term in the orchain to i-th position\n-- (we start counting indices at 0)\n-- TODO: clear intermediate steps\ndef pullToMiddleCore (i j : Nat) (hyp : Syntax) (type : Expr) (id : Ident)\n : TacticM Unit :=\n if i == j then do\n let hyp: Term := ⟨hyp⟩\n evalTactic (← `(tactic| have $id := $hyp))\n else withMainContext do\n let last := getLength type == j + 1\n let step₁: Ident ← \n if last then pure ⟨hyp⟩\n else do\n let v := List.take (j - i) $ getCongAssoc j `orAssocDir\n let res: Term := ⟨hyp⟩\n let step₁: Term ← applyList v res\n let step₁: Ident := ⟨step₁⟩ \n pure step₁ \n\n let step₂: Ident ←\n if last then do\n let tactics := List.take (j - 1 - i) $ getCongAssoc (j - 1) `orAssocDir\n let step₂: Term ← applyList tactics step₁\n let step₂: Ident := ⟨step₂⟩\n pure step₂\n else do\n let tactics₂ := List.reverse $ getCongAssoc (j - i - 1) `orAssocDir\n let wrappedTactics₂: Syntax ← congTactics tactics₂ i step₁ last\n let wrappedTactics₂: Term := ⟨wrappedTactics₂⟩\n let fname₂ ← mkIdent <$> mkFreshId\n evalTactic (← `(tactic| have $fname₂ := $wrappedTactics₂))\n pure fname₂\n \n let orComm: Term := ⟨mkIdent `orComm⟩\n let wrappedTactics₃ ← congTactics [orComm] i step₂ last\n let wrappedTactics₃ := ⟨wrappedTactics₃⟩\n let step₃ ← mkIdent <$> mkFreshId\n evalTactic (← `(tactic| have $step₃ := $wrappedTactics₃))\n\n let step₄: Ident ←\n if last then pure step₃ \n else do\n let u := List.reverse $ List.take (j - i) $ getCongAssoc j `orAssocConv\n let step₄: Term ← applyList u step₃\n let step₄: Ident := ⟨step₄⟩\n pure step₄\n\n evalTactic (← `(tactic| have $id := $step₄))\n\nsyntax (name := pullToMiddle) \"pullToMiddle\" term \",\" term \",\" term \",\" ident : tactic\n\n@[tactic pullToMiddle] def evalPullToMiddle : Tactic := fun stx => withMainContext do\n let i ← stxToNat ⟨stx[1]⟩ \n let j ← stxToNat ⟨stx[3]⟩\n let id: Ident := ⟨stx[7]⟩\n let e ← elabTerm stx[5] none\n let t ← instantiateMVars (← Meta.inferType e)\n pullToMiddleCore i j stx[5] t id\n\ndef pullIndex (index : Nat) (hypS : Syntax) (type : Expr) (id : Ident) : TacticM Unit :=\n pullToMiddleCore 0 index hypS type id\n\n-- insert pivot in the first position of the or-chain\n-- represented by hypS\ndef pullCore (pivot type : Expr) (hypS : Syntax) (id : Ident)\n (sufIdx : Option Nat := none) : TacticM Unit :=\n let lastSuffix := getLength type - 1\n let sufIdx :=\n match sufIdx with\n | some i => i\n | none => lastSuffix\n let li := collectPropsInOrChain' sufIdx type\n match getIndexList pivot li with\n | some i =>\n if i == sufIdx && sufIdx != lastSuffix then do\n if i == 0 then\n evalTactic (← `(tactic| have $id := $(⟨hypS⟩)))\n else\n let ctx ← getLCtx\n let hyp := (ctx.findFromUserName? hypS.getId).get!.toExpr\n let fname ← mkFreshId\n groupOrPrefixCore hyp type sufIdx fname\n evalTactic (← `(tactic| have $id := orComm $(mkIdent fname)))\n else\n pullIndex i hypS type id\n | none => throwError \"[Pull]: couldn't find pivot\"\n\nsyntax (name := pull) \"pull\" term \",\" term \",\" ident : tactic\n\n@[tactic pull] def evalPullCore : Tactic := fun stx => withMainContext do\n let e ← elabTerm stx[1] none\n let t ← instantiateMVars (← Meta.inferType e)\n let e₂ ← elabTerm stx[3] none\n pullCore e₂ t stx[1] ⟨stx[5]⟩\n\n/- example : A ∨ B ∨ C ∨ D ∨ E → E ∨ A ∨ B ∨ C ∨ D := by -/\n/- intro h -/\n/- pull h, E, h₂ -/\n\nend Smt.Reconstruction.Certifying\n", "meta": {"author": "ufmg-smite", "repo": "lean-smt", "sha": "6de0c4b216a918a14cf7a47d9a6faccaf8c8a209", "save_path": "github-repos/lean/ufmg-smite-lean-smt", "path": "github-repos/lean/ufmg-smite-lean-smt/lean-smt-6de0c4b216a918a14cf7a47d9a6faccaf8c8a209/Smt/Reconstruction/Certifying/Pull.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.28457601635158564, "lm_q2_score": 0.024798158844243447, "lm_q1q2_score": 0.007056961256748641}} {"text": "import cof.basic\n\n-- In these files we define the concept of localizing a category at a\n-- (left) multiplicative system.\n-- The presence of conditions defining a multiplicative system mean\n-- that the resulting category is much easier to work with than\n-- localization through the path category.\n-- See Stacks Project [Tag 04VB]\n\nnoncomputable theory\n\nnamespace category_theory\n\nnamespace derived\n\nuniverse u\n\nvariables {C : Type u} [small_category C] {S : morphism_property C}\n\nvariables {M : left_mult_sys S}\n\n-- Define the left calculus of fractions for a left multiplicative system\n\n-- The morphisms are given by valleys, under an equivalence\nstructure valley (X Y : left_calculus C M) :=\n (obj : left_calculus C M)\n (f : X.as ⟶ obj.as)\n (s : Y.as ⟶ obj.as)\n (qis : S s)\n\n-- Define the equivalence\n\ndef veq (X Y : left_calculus C M) (v₁ v₂ : valley X Y) : Prop :=\n ∃ v₃ : valley X Y, ∃ u₁ : v₁.obj.as ⟶ v₃.obj.as, ∃ u₂ : v₂.obj.as ⟶ v₃.obj.as, \n (v₁.f ≫ u₁) = v₃.f ∧ (v₁.s ≫ u₁) = v₃.s ∧ \n (v₂.f ≫ u₂) = v₃.f ∧ (v₂.s ≫ u₂) = v₃.s\n\n@[simp]\nlemma valley_equiv_refl (X Y : left_calculus C M) : reflexive (veq X Y) :=\n λ v, ⟨ v, 𝟙 v.obj.as, 𝟙 v.obj.as, by simp, by simp, by simp, by simp ⟩\n\n@[simp]\nlemma valley_equiv_symm (X Y : left_calculus C M) : symmetric (veq X Y) :=\nλ v w h, let ⟨u, ⟨ f, g, comm₁, comm₂, comm₃, comm₄ ⟩ ⟩ := h in\n ⟨ u, g, f, comm₃, comm₄, comm₁, comm₂ ⟩\n\n-- We show transitivity using the notion of \"dominance\"\n-- It is just an aid to break the proof down into smaller chunks\n\ndef valley_dom {M : left_mult_sys S} {X Y : left_calculus C M} (v₁ v₂ : valley X Y) : Prop :=\n ∃ a : v₁.obj.as ⟶ v₂.obj.as, v₁.f ≫ a = v₂.f ∧ v₁.s ≫ a = v₂.s\n\nnotation a ` E ` b := valley_dom a b\n\n-- Equivalence of valleys is equivalent to dominating a common valley \nlemma dom_iff_equiv {X Y : left_calculus C M} (u v : valley X Y) : \n (∃ w : valley X Y, (u E w) ∧ (v E w)) ↔ veq X Y u v :=\nbegin\n split,\n { rintro ⟨ w, h₁, h₂ ⟩,\n rcases h₁ with ⟨ f, h₁' ⟩,\n rcases h₂ with ⟨ g, h₂' ⟩,\n use w.obj.as, use w.f, use w.s, use w.qis, use f, use g,\n exact ⟨ h₁'.left, h₁'.right, h₂' ⟩ },\n\n { rintro ⟨ w, f, g, h₁, h₂, h₃, h₄ ⟩,\n use w,\n split,\n exact ⟨f, ⟨h₁, h₂⟩⟩,\n exact ⟨g, ⟨h₃, h₄⟩⟩ }\nend\n\n\nlemma triple_comp {W X Y Z : C} (M : left_mult_sys S) {f₁ : W ⟶ X} {f₂ : X ⟶ Y} {f₃ : Y ⟶ Z} :\n S f₁ ∧ S f₂ ∧ S f₃ → S (f₁ ≫ f₂ ≫ f₃) := \nbegin\n rintro ⟨ s₁, s₂, s₃ ⟩,\n have s₄ : S (f₂ ≫ f₃) := M.comp ⟨s₂, s₃⟩,\n exact M.comp ⟨s₁, s₄⟩ \nend\n\n-- If both u and v are dominated by some w, then they are equivalent valleys\nlemma mut_dom_implies_equiv {X Y : left_calculus C M} (u v : valley X Y) : \n (∃ w : valley X Y, (w E u) ∧ (w E v)) → veq X Y u v :=\nbegin\n intro h,\n rcases h with ⟨ w, hwu, hwv ⟩,\n rcases hwu with ⟨ a, ha ⟩,\n rcases hwv with ⟨ b, hb ⟩,\n have hore : _, from M.ore v.s u.s u.qis,\n rcases hore with ⟨ Z₁, c₁, s₁, hc₁, hcomm₁ ⟩,\n \n have hcancel : w.s ≫ b ≫ s₁ = w.s ≫ a ≫ c₁, by {\n rw [←hb.right, ←ha.right] at hcomm₁,\n simp at hcomm₁,\n exact hcomm₁ },\n have ht : _ := M.cancel ⟨w.qis, hcancel⟩,\n rcases ht with ⟨ Z₂, t, ht₁, ht₂ ⟩,\n\n use Z₂, use u.f ≫ c₁ ≫ t, use v.s ≫ s₁ ≫ t,\n exact triple_comp M ⟨v.qis, hc₁, ht₁⟩,\n\n use c₁ ≫ t,\n use s₁ ≫ t,\n \n split, { simp },\n split,\n { \n suffices heq : u.s ≫ c₁ ≫ t = v.s ≫ s₁ ≫ t, from \n begin\n simp, exact heq,\n end,\n have heq' : (u.s ≫ c₁) ≫ t = (v.s ≫ s₁) ≫ t, by rw hcomm₁,\n simp at heq', assumption,\n },\n split,\n { \n simp,\n rw [←hb.left, ←ha.left],\n simp,\n simp at ht₂,\n rw ht₂\n },\n { simp }\nend\n\nlemma valley_equiv_trans (X Y : left_calculus C M) : transitive (veq X Y) :=\nbegin\n intros u v w,\n rintro ⟨v₁, ⟨auv, a, i, j, k, l⟩⟩, \n rintro ⟨v₂, ⟨b, avw, i', j', k', l'⟩⟩,\n have elem' : ∃ x, (x E v₁) ∧ (x E v₂), from begin\n use v,\n have velem₁ : (v E v₁), from ⟨ a, ⟨ k, l ⟩ ⟩,\n have velem₂ : (v E v₂), from ⟨ b, ⟨ i', j' ⟩ ⟩,\n exact ⟨ velem₁, velem₂ ⟩,\n end,\n have equiv : veq X Y v₁ v₂, from (mut_dom_implies_equiv v₁ v₂) elem',\n have equiv' : ∃ x, (u E x) ∧ (w E x), from \n begin\n rcases equiv with ⟨ z, u₁, u₂, hequiv ⟩,\n use z,\n split,\n { rw [← i, ← j ] at hequiv,\n simp at hequiv,\n rcases hequiv with ⟨ ha, hb, _ ⟩,\n exact ⟨auv ≫ u₁, ⟨ ha, hb⟩ ⟩ },\n { rw [← k', ← l'] at hequiv,\n simp at hequiv,\n rcases hequiv with ⟨ _, _, ha, hb ⟩,\n exact ⟨ avw ≫ u₂, ⟨ ha, hb ⟩⟩ }\n end, \n exact (dom_iff_equiv u w).mp equiv',\nend\n\ndef valley_setoid (X Y : left_calculus C M) : setoid (valley X Y) :=\n { r := veq X Y,\n iseqv := ⟨ valley_equiv_refl X Y, valley_equiv_symm X Y, valley_equiv_trans X Y ⟩\n }\nattribute [instance] valley_setoid\n\nend derived\n\nend category_theory", "meta": {"author": "avarsh", "repo": "derived-categories-lean", "sha": "449196fd6dcccb27de28500d156aec30185f9c15", "save_path": "github-repos/lean/avarsh-derived-categories-lean", "path": "github-repos/lean/avarsh-derived-categories-lean/derived-categories-lean-449196fd6dcccb27de28500d156aec30185f9c15/src/cof/valley.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.38121956625614994, "lm_q2_score": 0.01798621154126062, "lm_q1q2_score": 0.006856695762350732}} {"text": "/-\nCopyright (c) 2021 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Sebastian Ullrich, Leonardo de Moura\n-/\nprelude\nimport Init.SimpLemmas\nimport Init.Control.Except\nimport Init.Control.StateRef\n\nopen Function\n\n@[simp] theorem monadLift_self [Monad m] (x : m α) : monadLift x = x :=\n rfl\n\nclass LawfulFunctor (f : Type u → Type v) [Functor f] : Prop where\n map_const : (Functor.mapConst : α → f β → f α) = Functor.map ∘ const β\n id_map (x : f α) : id <$> x = x\n comp_map (g : α → β) (h : β → γ) (x : f α) : (h ∘ g) <$> x = h <$> g <$> x\n\nexport LawfulFunctor (map_const id_map comp_map)\n\nattribute [simp] id_map\n\n@[simp] theorem id_map' [Functor m] [LawfulFunctor m] (x : m α) : (fun a => a) <$> x = x :=\n id_map x\n\nclass LawfulApplicative (f : Type u → Type v) [Applicative f] extends LawfulFunctor f : Prop where\n seqLeft_eq (x : f α) (y : f β) : x <* y = const β <$> x <*> y\n seqRight_eq (x : f α) (y : f β) : x *> y = const α id <$> x <*> y\n pure_seq (g : α → β) (x : f α) : pure g <*> x = g <$> x\n map_pure (g : α → β) (x : α) : g <$> (pure x : f α) = pure (g x)\n seq_pure {α β : Type u} (g : f (α → β)) (x : α) : g <*> pure x = (fun h => h x) <$> g\n seq_assoc {α β γ : Type u} (x : f α) (g : f (α → β)) (h : f (β → γ)) : h <*> (g <*> x) = ((@comp α β γ) <$> h) <*> g <*> x\n comp_map g h x := (by\n repeat rw [← pure_seq]\n simp [seq_assoc, map_pure, seq_pure])\n\nexport LawfulApplicative (seqLeft_eq seqRight_eq pure_seq map_pure seq_pure seq_assoc)\n\nattribute [simp] map_pure seq_pure\n\n@[simp] theorem pure_id_seq [Applicative f] [LawfulApplicative f] (x : f α) : pure id <*> x = x := by\n simp [pure_seq]\n\nclass LawfulMonad (m : Type u → Type v) [Monad m] extends LawfulApplicative m : Prop where\n bind_pure_comp (f : α → β) (x : m α) : x >>= pure ∘ f = f <$> x\n bind_map {α β : Type u} (f : m (α → β)) (x : m α) : f >>= (. <$> x) = f <*> x\n pure_bind (x : α) (f : α → m β) : pure x >>= f = f x\n bind_assoc (x : m α) (f : α → m β) (g : β → m γ) : x >>= f >>= g = x >>= fun x => f x >>= g\n map_pure g x := (by rw [← bind_pure_comp, pure_bind])\n seq_pure g x := (by rw [← bind_map]; simp [map_pure, bind_pure_comp])\n seq_assoc x g h := (by\n -- TODO: support for applying `symm` at `simp` arguments\n let bind_pure_comp_symm {α β : Type u} (f : α → β) (x : m α) : f <$> x = x >>= pure ∘ f := by\n rw [bind_pure_comp]\n let bind_map_symm {α β : Type u} (f : m (α → (β : Type u))) (x : m α) : f <*> x = f >>= (. <$> x) := by\n rw [bind_map]\n simp[bind_pure_comp_symm, bind_map_symm, bind_assoc, pure_bind])\n\nexport LawfulMonad (bind_pure_comp bind_map pure_bind bind_assoc)\nattribute [simp] pure_bind bind_assoc\n\n@[simp] theorem bind_pure [Monad m] [LawfulMonad m] (x : m α) : x >>= pure = x := by\n show x >>= pure ∘ id = x\n rw [bind_pure_comp, id_map]\n\ntheorem map_eq_pure_bind [Monad m] [LawfulMonad m] (f : α → β) (x : m α) : f <$> x = x >>= fun a => pure (f a) := by\n rw [← bind_pure_comp]\n\ntheorem seq_eq_bind_map {α β : Type u} [Monad m] [LawfulMonad m] (f : m (α → β)) (x : m α) : f <*> x = f >>= (. <$> x) := by\n rw [← bind_map]\n\ntheorem bind_congr [Bind m] {x : m α} {f g : α → m β} (h : ∀ a, f a = g a) : x >>= f = x >>= g := by\n simp [funext h]\n\n@[simp] theorem bind_pure_unit [Monad m] [LawfulMonad m] {x : m PUnit} : (x >>= fun _ => pure ⟨⟩) = x := by\n have : (x >>= fun _ => pure ⟨⟩) = (x >>= pure) := by\n apply bind_congr; intro u\n cases u; simp\n rw [bind_pure] at this\n assumption\n\ntheorem map_congr [Functor m] {x : m α} {f g : α → β} (h : ∀ a, f a = g a) : (f <$> x : m β) = g <$> x := by\n simp [funext h]\n\ntheorem seq_eq_bind {α β : Type u} [Monad m] [LawfulMonad m] (mf : m (α → β)) (x : m α) : mf <*> x = mf >>= fun f => f <$> x := by\n rw [bind_map]\n\ntheorem seqRight_eq_bind [Monad m] [LawfulMonad m] (x : m α) (y : m β) : x *> y = x >>= fun _ => y := by\n rw [seqRight_eq]\n simp [map_eq_pure_bind, seq_eq_bind_map, const]\n\ntheorem seqLeft_eq_bind [Monad m] [LawfulMonad m] (x : m α) (y : m β) : x <* y = x >>= fun a => y >>= fun _ => pure a := by\n rw [seqLeft_eq]; simp [map_eq_pure_bind, seq_eq_bind_map]\n\n/- Id -/\n\nnamespace Id\n\n@[simp] theorem map_eq (x : Id α) (f : α → β) : f <$> x = f x := rfl\n@[simp] theorem bind_eq (x : Id α) (f : α → id β) : x >>= f = f x := rfl\n@[simp] theorem pure_eq (a : α) : (pure a : Id α) = a := rfl\n\ninstance : LawfulMonad Id := by\n refine' { .. } <;> intros <;> rfl\n\nend Id\n\n/- ExceptT -/\n\nnamespace ExceptT\n\ntheorem ext [Monad m] {x y : ExceptT ε m α} (h : x.run = y.run) : x = y := by\n simp [run] at h\n assumption\n\n@[simp] theorem run_pure [Monad m] : run (pure x : ExceptT ε m α) = pure (Except.ok x) := rfl\n\n@[simp] theorem run_lift [Monad m] (x : m α) : run (ExceptT.lift x : ExceptT ε m α) = (Except.ok <$> x : m (Except ε α)) := rfl\n\n@[simp] theorem run_throw [Monad m] : run (throw e : ExceptT ε m β) = pure (Except.error e) := rfl\n\n@[simp] theorem run_bind_lift [Monad m] [LawfulMonad m] (x : m α) (f : α → ExceptT ε m β) : run (ExceptT.lift x >>= f : ExceptT ε m β) = x >>= fun a => run (f a) := by\n simp[ExceptT.run, ExceptT.lift, bind, ExceptT.bind, ExceptT.mk, ExceptT.bindCont, map_eq_pure_bind]\n\n@[simp] theorem bind_throw [Monad m] [LawfulMonad m] (f : α → ExceptT ε m β) : (throw e >>= f) = throw e := by\n simp [throw, throwThe, MonadExceptOf.throw, bind, ExceptT.bind, ExceptT.bindCont, ExceptT.mk]\n\ntheorem run_bind [Monad m] (x : ExceptT ε m α)\n : run (x >>= f : ExceptT ε m β)\n =\n run x >>= fun\n | Except.ok x => run (f x)\n | Except.error e => pure (Except.error e) :=\n rfl\n\n@[simp] theorem lift_pure [Monad m] [LawfulMonad m] (a : α) : ExceptT.lift (pure a) = (pure a : ExceptT ε m α) := by\n simp [ExceptT.lift, pure, ExceptT.pure]\n\n@[simp] theorem run_map [Monad m] [LawfulMonad m] (f : α → β) (x : ExceptT ε m α)\n : (f <$> x).run = Except.map f <$> x.run := by\n simp [Functor.map, ExceptT.map, map_eq_pure_bind]\n apply bind_congr\n intro a; cases a <;> simp [Except.map]\n\nprotected theorem seq_eq {α β ε : Type u} [Monad m] (mf : ExceptT ε m (α → β)) (x : ExceptT ε m α) : mf <*> x = mf >>= fun f => f <$> x :=\n rfl\n\nprotected theorem bind_pure_comp [Monad m] [LawfulMonad m] (f : α → β) (x : ExceptT ε m α) : x >>= pure ∘ f = f <$> x := by\n intros; rfl\n\nprotected theorem seqLeft_eq {α β ε : Type u} {m : Type u → Type v} [Monad m] [LawfulMonad m] (x : ExceptT ε m α) (y : ExceptT ε m β) : x <* y = const β <$> x <*> y := by\n show (x >>= fun a => y >>= fun _ => pure a) = (const (α := α) β <$> x) >>= fun f => f <$> y\n rw [← ExceptT.bind_pure_comp]\n apply ext\n simp [run_bind]\n apply bind_congr\n intro\n | Except.error _ => simp\n | Except.ok _ =>\n simp [map_eq_pure_bind]; apply bind_congr; intro b;\n cases b <;> simp [comp, Except.map, const]\n\nprotected theorem seqRight_eq [Monad m] [LawfulMonad m] (x : ExceptT ε m α) (y : ExceptT ε m β) : x *> y = const α id <$> x <*> y := by\n show (x >>= fun _ => y) = (const α id <$> x) >>= fun f => f <$> y\n rw [← ExceptT.bind_pure_comp]\n apply ext\n simp [run_bind]\n apply bind_congr\n intro a; cases a <;> simp\n\ninstance [Monad m] [LawfulMonad m] : LawfulMonad (ExceptT ε m) where\n id_map := by intros; apply ext; simp\n map_const := by intros; rfl\n seqLeft_eq := ExceptT.seqLeft_eq\n seqRight_eq := ExceptT.seqRight_eq\n pure_seq := by intros; apply ext; simp [ExceptT.seq_eq, run_bind]\n bind_pure_comp := ExceptT.bind_pure_comp\n bind_map := by intros; rfl\n pure_bind := by intros; apply ext; simp [run_bind]\n bind_assoc := by intros; apply ext; simp [run_bind]; apply bind_congr; intro a; cases a <;> simp\n\nend ExceptT\n\n/- ReaderT -/\n\nnamespace ReaderT\n\ntheorem ext [Monad m] {x y : ReaderT ρ m α} (h : ∀ ctx, x.run ctx = y.run ctx) : x = y := by\n simp [run] at h\n exact funext h\n\n@[simp] theorem run_pure [Monad m] (a : α) (ctx : ρ) : (pure a : ReaderT ρ m α).run ctx = pure a := rfl\n\n@[simp] theorem run_bind [Monad m] (x : ReaderT ρ m α) (f : α → ReaderT ρ m β) (ctx : ρ)\n : (x >>= f).run ctx = x.run ctx >>= λ a => (f a).run ctx := rfl\n\n@[simp] theorem run_map [Monad m] (f : α → β) (x : ReaderT ρ m α) (ctx : ρ)\n : (f <$> x).run ctx = f <$> x.run ctx := rfl\n\n@[simp] theorem run_monadLift [MonadLiftT n m] (x : n α) (ctx : ρ)\n : (monadLift x : ReaderT ρ m α).run ctx = (monadLift x : m α) := rfl\n\n@[simp] theorem run_monadMap [Monad m] [MonadFunctor n m] (f : {β : Type u} → n β → n β) (x : ReaderT ρ m α) (ctx : ρ)\n : (monadMap @f x : ReaderT ρ m α).run ctx = monadMap @f (x.run ctx) := rfl\n\n@[simp] theorem run_read [Monad m] (ctx : ρ) : (ReaderT.read : ReaderT ρ m ρ).run ctx = pure ctx := rfl\n\n@[simp] theorem run_seq {α β : Type u} [Monad m] [LawfulMonad m] (f : ReaderT ρ m (α → β)) (x : ReaderT ρ m α) (ctx : ρ) : (f <*> x).run ctx = (f.run ctx <*> x.run ctx) := by\n rw [seq_eq_bind (m := m)]; rfl\n\n@[simp] theorem run_seqRight [Monad m] [LawfulMonad m] (x : ReaderT ρ m α) (y : ReaderT ρ m β) (ctx : ρ) : (x *> y).run ctx = (x.run ctx *> y.run ctx) := by\n rw [seqRight_eq_bind (m := m)]; rfl\n\n@[simp] theorem run_seqLeft [Monad m] [LawfulMonad m] (x : ReaderT ρ m α) (y : ReaderT ρ m β) (ctx : ρ) : (x <* y).run ctx = (x.run ctx <* y.run ctx) := by\n rw [seqLeft_eq_bind (m := m)]; rfl\n\ninstance [Monad m] [LawfulMonad m] : LawfulMonad (ReaderT ρ m) where\n id_map := by intros; apply ext; intros; simp\n map_const := by intros; rfl\n seqLeft_eq := by intros; apply ext; intros; simp; apply LawfulApplicative.seqLeft_eq\n seqRight_eq := by intros; apply ext; intros; simp; apply LawfulApplicative.seqRight_eq\n pure_seq := by intros; apply ext; intros; simp; apply LawfulApplicative.pure_seq\n bind_pure_comp := by intros; apply ext; intros; simp; apply LawfulMonad.bind_pure_comp\n bind_map := by intros; rfl\n pure_bind := by intros; apply ext; intros; simp\n bind_assoc := by intros; apply ext; intros; simp\n\nend ReaderT\n\n/- StateRefT -/\n\ninstance [Monad m] [LawfulMonad m] : LawfulMonad (StateRefT' ω σ m) :=\n inferInstanceAs (LawfulMonad (ReaderT (ST.Ref ω σ) m))\n\n/- StateT -/\n\nnamespace StateT\n\ntheorem ext {x y : StateT σ m α} (h : ∀ s, x.run s = y.run s) : x = y :=\n funext h\n\n@[simp] theorem run'_eq [Monad m] (x : StateT σ m α) (s : σ) : run' x s = (·.1) <$> run x s :=\n rfl\n\n@[simp] theorem run_pure [Monad m] (a : α) (s : σ) : (pure a : StateT σ m α).run s = pure (a, s) := rfl\n\n@[simp] theorem run_bind [Monad m] (x : StateT σ m α) (f : α → StateT σ m β) (s : σ)\n : (x >>= f).run s = x.run s >>= λ p => (f p.1).run p.2 := by\n simp [bind, StateT.bind, run]\n apply bind_congr\n intro p; cases p; rfl\n\n@[simp] theorem run_map {α β σ : Type u} [Monad m] [LawfulMonad m] (f : α → β) (x : StateT σ m α) (s : σ) : (f <$> x).run s = (fun (p : α × σ) => (f p.1, p.2)) <$> x.run s := by\n simp [Functor.map, StateT.map, run, map_eq_pure_bind]\n apply bind_congr\n intro p; cases p; rfl\n\n@[simp] theorem run_get [Monad m] (s : σ) : (get : StateT σ m σ).run s = pure (s, s) := rfl\n\n@[simp] theorem run_set [Monad m] (s s' : σ) : (set s' : StateT σ m PUnit).run s = pure (⟨⟩, s') := rfl\n\n@[simp] theorem run_modify [Monad m] (f : σ → σ) (s : σ) : (modify f : StateT σ m PUnit).run s = pure (⟨⟩, f s) := rfl\n\n@[simp] theorem run_modifyGet [Monad m] (f : σ → α × σ) (s : σ) : (modifyGet f : StateT σ m α).run s = pure ((f s).1, (f s).2) := by\n simp [modifyGet, MonadStateOf.modifyGet, StateT.modifyGet, run]; cases f s <;> rfl\n\n@[simp] theorem run_lift {α σ : Type u} [Monad m] (x : m α) (s : σ) : (StateT.lift x : StateT σ m α).run s = x >>= fun a => pure (a, s) := rfl\n\n@[simp] theorem run_bind_lift {α σ : Type u} [Monad m] [LawfulMonad m] (x : m α) (f : α → StateT σ m β) (s : σ) : (StateT.lift x >>= f).run s = x >>= fun a => (f a).run s := by\n simp [StateT.lift, StateT.run, bind, StateT.bind]\n\n@[simp] theorem run_monadLift {α σ : Type u} [Monad m] [MonadLiftT n m] (x : n α) (s : σ) : (monadLift x : StateT σ m α).run s = (monadLift x : m α) >>= fun a => pure (a, s) := rfl\n\n@[simp] theorem run_monadMap [Monad m] [MonadFunctor n m] (f : {β : Type u} → n β → n β) (x : StateT σ m α) (s : σ)\n : (monadMap @f x : StateT σ m α).run s = monadMap @f (x.run s) := rfl\n\n@[simp] theorem run_seq {α β σ : Type u} [Monad m] [LawfulMonad m] (f : StateT σ m (α → β)) (x : StateT σ m α) (s : σ) : (f <*> x).run s = (f.run s >>= fun fs => (fun (p : α × σ) => (fs.1 p.1, p.2)) <$> x.run fs.2) := by\n show (f >>= fun g => g <$> x).run s = _\n simp\n\n@[simp] theorem run_seqRight [Monad m] [LawfulMonad m] (x : StateT σ m α) (y : StateT σ m β) (s : σ) : (x *> y).run s = (x.run s >>= fun p => y.run p.2) := by\n show (x >>= fun _ => y).run s = _\n simp\n\n@[simp] theorem run_seqLeft {α β σ : Type u} [Monad m] [LawfulMonad m] (x : StateT σ m α) (y : StateT σ m β) (s : σ) : (x <* y).run s = (x.run s >>= fun p => y.run p.2 >>= fun p' => pure (p.1, p'.2)) := by\n show (x >>= fun a => y >>= fun _ => pure a).run s = _\n simp\n\ntheorem seqRight_eq [Monad m] [LawfulMonad m] (x : StateT σ m α) (y : StateT σ m β) : x *> y = const α id <$> x <*> y := by\n apply ext; intro s\n simp [map_eq_pure_bind, const]\n apply bind_congr; intro p; cases p\n simp [Prod.ext]\n\ntheorem seqLeft_eq [Monad m] [LawfulMonad m] (x : StateT σ m α) (y : StateT σ m β) : x <* y = const β <$> x <*> y := by\n apply ext; intro s\n simp [map_eq_pure_bind]\n\ninstance [Monad m] [LawfulMonad m] : LawfulMonad (StateT σ m) where\n id_map := by intros; apply ext; intros; simp[Prod.ext]\n map_const := by intros; rfl\n seqLeft_eq := seqLeft_eq\n seqRight_eq := seqRight_eq\n pure_seq := by intros; apply ext; intros; simp\n bind_pure_comp := by intros; apply ext; intros; simp; apply LawfulMonad.bind_pure_comp\n bind_map := by intros; rfl\n pure_bind := by intros; apply ext; intros; simp\n bind_assoc := by intros; apply ext; intros; simp\n\nend StateT\n", "meta": {"author": "subfish-zhou", "repo": "leanprover-zh_CN.github.io", "sha": "8b2985d4a3d458ceda9361ac454c28168d920d3f", "save_path": "github-repos/lean/subfish-zhou-leanprover-zh_CN.github.io", "path": "github-repos/lean/subfish-zhou-leanprover-zh_CN.github.io/leanprover-zh_CN.github.io-8b2985d4a3d458ceda9361ac454c28168d920d3f/stage0/src/Init/Control/Lawful.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2538610069692489, "lm_q2_score": 0.025957358422249305, "lm_q1q2_score": 0.006589561147333923}} {"text": "import Architectural.proofObligations\nimport lacu\nimport Architectural.lang\nimport tactic \nimport system.io\n\nopen LANG PORTS tactic \n\nlocal infix ` OR `:50 := LANG.disj \nlocal infix ` & `:50 := LANG.conj \n\n\nmeta def preprocess_rpo_fst : tactic (name × name) := do \n x ← tactic.get_unused_name `x,\n H ← tactic.get_unused_name `H,\n tactic.intro x,\n `[simp],\n `[rw AssertionLang.impl_def],\n tactic.intro H,\n `[rw [list_conj_iff, get_nfs] at H, simp at H, rw toMap at H],\n return ⟨x, H⟩\n\n\ndef theList := [armPosition,LAAP,armController].pw_filter (ne)\n\n\nmeta def foo : tactic unit := \ndo \n v ← mk_meta_var `(ne armPosition LAAP),\n set_goals [v]\n\n-- example : true := \n-- begin\n-- foo, dec_trivial,\n-- end \n\nmeta def solve_rpo_fst : tactic unit := do \n ⟨x, H⟩ ← preprocess_rpo_fst,\n `[rcases H with ⟨H1,H2,H3⟩],\n tactic.repeat `[rw Map.find_val at H1 H2 H3],\n `[have distinct1 : armPosition ≠ LAAP, by {dec_trivial,},\n have distinct2 : armPosition ≠ armController, by {dec_trivial},\n have distinct3 : armController ≠ LAAP, by {dec_trivial},\n repeat {simp [distinct1, distinct2, distinct3] at *,},\n rw nf_def at *, intro A, simp at *,\n apply (@synchronize (atom fault_PWMFlow_LACU).neg.always x fault_PWMFlow_LACU fault_armFlow_armController).mpr,\n simp,\n apply H3, clear H3,\n rw @forall_conj_distrib_mem x _ _,split,\n rw @forall_conj_distrib_mem' x _ _,split,\n rw @forall_conj_distrib_mem' x _ _,split,\n apply (@synchronize (atom fault_angleSensor_armController).neg.always x fault_angleSensor_armController fault_output_armPosition ).mpr,\n simp,\n apply H1, clear H1,\n rw @forall_conj_distrib_mem x _ _ at A,\n cases A with A1 A2, clear A2,\n rw @forall_conj_distrib_mem' x _ _ at A1,\n cases A1 with A1 A3, clear A3,\n rw @forall_conj_distrib_mem' x _ _ at A1,\n cases A1 with A1 A2, clear A2,\n apply (@synchronize (((atom fault_input2_armPosition).neg OR (atom fault_input1_armPosition).neg).always) x fault_input1_armPosition fault_armPositionAngle1_LACU).mpr,\n apply (@synchronize (((atom fault_input2_armPosition).neg OR (atom fault_armPositionAngle1_LACU).neg).always) x fault_input2_armPosition fault_armPositionAngle2_LACU).mpr,\n simp,\n intros i,\n replace A1 := A1 i, rwa LANG.disj_comm at A1,\n unfold LACU_ARCH_MODEL, simp, unfold LACU_ARCH_MODEL, dsimp, dec_trivial,\n unfold LACU_ARCH_MODEL, dsimp, dec_trivial,\n apply ((@synchronize (atom fault_LAAPActive_armController).neg.always) x fault_LAAPActive_armController fault_LAAPActive_LAAP).mpr,\n simp,\n have : x ∈ AssertionLang.sem ((atom fault_LAAPFlow_LAAP).neg & (atom fault_LAAPActive_LAAP).neg).always → x ∈ ((atom fault_LAAPActive_LAAP).neg).always.sem,\n by {intro h, intro i,\n rw forall_conj_distrib_mem at h,\n cases h with h1 h2,\n apply h2 i,\n },\n apply this, clear this,\n apply H2, clear H2, clear H1,\n apply ((@synchronize ((atom fault_LAAPRequest_LAAP).neg & (atom fault_operatorControlLever_LAAP).neg).always) x fault_operatorControlLever_LAAP fault_operatorControlLever_LACU).mpr,\n simp,\n apply ((@synchronize ((atom fault_LAAPRequest_LAAP).neg & (atom fault_operatorControlLever_LACU).neg).always) x fault_LAAPRequest_LAAP fault_LAAPRequest_LACU).mpr,\n simp,\n\n rw @forall_conj_distrib_mem x _ _,\n rw @forall_conj_distrib_mem x _ _ at A,\n cases A with A1 A2,\n rw @forall_conj_distrib_mem' x _ _ at A1,\n cases A1 with A1 A3,\n rw @forall_conj_distrib_mem' x _ _ at A1,\n cases A1 with A1 A4,\n split,\n exact A4,\n exact A3,\n unfold LACU_ARCH_MODEL, dsimp, dec_trivial,\n unfold LACU_ARCH_MODEL, dsimp, dec_trivial,\n unfold LACU_ARCH_MODEL, dsimp, dec_trivial,\n apply ((@synchronize (atom fault_LAAPFlow_armController).neg.always) x fault_LAAPFlow_armController fault_LAAPFlow_LAAP).mpr,\n simp,intro i,\n rw @forall_conj_distrib_mem x _ _ at H2,\n have : (x ∈ AssertionLang.sem ((atom fault_LAAPFlow_LAAP).neg & (atom fault_LAAPActive_LAAP).neg).always) → stream.drop i x ∈ (atom fault_LAAPFlow_LAAP).neg.sem,\n by { intros H', rw @forall_conj_distrib_mem x _ _ at H', \n cases H' with H' H'',\n apply H' i,}, apply this, clear this, apply H2,\n rw @forall_conj_distrib_mem x _ _ at A,\n cases A with A1 A2,\n rw @forall_conj_distrib_mem' x _ _ at A1,\n cases A1 with A1 A3,\n rw @forall_conj_distrib_mem' x _ _ at A1,\n cases A1 with A1 A4,\n split,\n apply (@synchronize (atom fault_LAAPRequest_LAAP).neg.always x fault_LAAPRequest_LAAP fault_LAAPRequest_LACU).mpr,\n simp, apply A4,\n unfold LACU_ARCH_MODEL, dsimp, dec_trivial,\napply (@synchronize (atom fault_operatorControlLever_LAAP).neg.always x fault_operatorControlLever_LAAP fault_operatorControlLever_LACU).mpr,\n simp, apply A3,\n unfold LACU_ARCH_MODEL, dsimp, dec_trivial,\n unfold LACU_ARCH_MODEL, dsimp, dec_trivial,\n rw @forall_conj_distrib_mem x _ _ at A,\n cases A with A1 A2,\n rw @forall_conj_distrib_mem' x _ _ at A1,\n cases A1 with A1 A3,\n rw @forall_conj_distrib_mem' x _ _ at A1,\n cases A1 with A1 A4,\n apply (@synchronize (atom fault_operatorControlLever_armController).neg.always x fault_operatorControlLever_armController fault_operatorControlLever_LACU).mpr,\n simp,\n intro i,\n apply A3 i, unfold LACU_ARCH_MODEL, dsimp, dec_trivial,\n unfold LACU_ARCH_MODEL, dsimp, dec_trivial],\n return ()\n\n-- meta def get_comp_names : tactic (list (expr × expr)) := \n-- do \n\n-- meta def get_comp_names : tactic (list (expr × expr)) := \n-- do \n\n\nmeta def tac1 : tactic unit := \n`[rw AssertionLang.impl_def,\nintro Ha,\nrw AssertionLang.conj_def at Ha,\ncases Ha with Ha Hb,\nrw list_conj_iff at Hb,\nsimp at Hb,\nhave Hb1 := Hb LAAP (by {rw H, simp,}),\nhave Hb2 := Hb armController (by {rw H, simp,}),\nclear Hb,\nsimp at *,\nrw Map.find_val at *,\nrw Map.find_val at *,\nrw Map.find_val at *,\nsimp at *,\nrw H,\nhave distinct1 : armPosition ≠ LAAP, by {dec_trivial,},\n have distinct2 : armPosition ≠ armController, by {dec_trivial},\n have distinct3 : armController ≠ LAAP, by {dec_trivial},\n repeat {simp [distinct1, distinct2, distinct3] at *,}]\n\nmeta def tac2 : tactic unit := \n`[rw AssertionLang.impl_def,\nintro Ha,\nrw AssertionLang.conj_def at Ha,\ncases Ha with Ha Hb,\nrw list_conj_iff at Hb,\nsimp at Hb,\nhave Hb1 := Hb armController (by {rw H, dec_trivial,}),\nhave Hb2 := Hb armPosition (by {rw H, dec_trivial,}),\nclear Hb,\nsimp at *,\nrw Map.find_val at *,\nrw Map.find_val at *,\nrw Map.find_val at *,\nhave distinct1 : armPosition ≠ LAAP, by {dec_trivial,},\n have distinct2 : armPosition ≠ armController, by {dec_trivial},\n have distinct3 : armController ≠ LAAP, by {dec_trivial},\n repeat {simp [distinct1, distinct2, distinct3] at *,}]\n\nmeta def tac3 : tactic unit := \n`[rw AssertionLang.impl_def,\nintro Ha,\nrw AssertionLang.conj_def at Ha,\ncases Ha with Ha Hb,\nrw list_conj_iff at Hb,\nsimp at Hb,\nhave Hb1 := Hb LAAP (by {rw H, dec_trivial,}),\nhave Hb2 := Hb armPosition (by {rw H, dec_trivial,}),\nclear Hb,\nsimp at *,\nrw Map.find_val at *,\nrw Map.find_val at *,\nrw Map.find_val at *,\nhave distinct1 : armPosition ≠ LAAP, by {dec_trivial,},\n have distinct2 : armPosition ≠ armController, by {dec_trivial},\n have distinct3 : armController ≠ LAAP, by {dec_trivial},\n repeat {simp [distinct1, distinct2, distinct3] at *,}]\n\n\n\n\n\nmeta def solve_rpo_snd : tactic unit := do \n`[rw RPO_snd,\nintros S H s,\nsimp at *,\ncases H, \nwork_on_goal 0 { tac1, \n rw @forall_conj_distrib_mem s _ _ at Ha,\n cases Ha with Ha Ha2,\n rw @forall_conj_distrib_mem' s _ _ at Ha,\n cases Ha with Ha Ha3,\n rw @forall_conj_distrib_mem' s _ _ at Ha,\n cases Ha with Ha Ha4,\n intro i, \n apply (@synchronize (((atom fault_input2_armPosition).neg OR (atom fault_input1_armPosition).neg).always) s fault_input1_armPosition fault_armPositionAngle1_LACU).mpr,\n apply (@synchronize (((atom fault_input2_armPosition).neg OR (atom fault_armPositionAngle1_LACU).neg).always) s fault_input2_armPosition fault_armPositionAngle2_LACU).mpr,\n simp,\n intro i,\n replace Ha := Ha i, rwa LANG.disj_comm at Ha,\n unfold LACU_ARCH_MODEL, dsimp, dec_trivial,\n unfold LACU_ARCH_MODEL, dsimp, dec_trivial,\n\n }, \n\ncases H, tac2, rw H,\n have distinct1 : armPosition ≠ LAAP, by {dec_trivial,},\n have distinct2 : armPosition ≠ armController, by {dec_trivial},\n have distinct3 : armController ≠ LAAP, by {dec_trivial},\n repeat {simp [distinct1, distinct2, distinct3] at *,},\n rw @forall_conj_distrib_mem s _ _ at Ha,\n cases Ha with Ha Ha2,\n rw @forall_conj_distrib_mem' s _ _ at Ha,\n cases Ha with Ha Ha3,\n rw @forall_conj_distrib_mem' s _ _ at Ha,\n cases Ha with Ha Ha4,\n rw @forall_conj_distrib_mem s _ _ ,\n split,\n apply (@synchronize (atom fault_LAAPRequest_LAAP).neg.always s fault_LAAPRequest_LAAP fault_LAAPRequest_LACU).mpr,\n simp, exact Ha4,\n unfold LACU_ARCH_MODEL, dsimp, dec_trivial,\napply (@synchronize (atom fault_operatorControlLever_LAAP).neg.always s fault_operatorControlLever_LAAP fault_operatorControlLever_LACU).mpr,\nsimp, assumption, unfold LACU_ARCH_MODEL, dsimp, dec_trivial,\n\ntac3,\nrw H, \n have distinct1 : armPosition ≠ LAAP, by {dec_trivial,},\n have distinct2 : armPosition ≠ armController, by {dec_trivial},\n have distinct3 : armController ≠ LAAP, by {dec_trivial},\n repeat {simp [distinct1, distinct2, distinct3] at *,},\n rw @forall_conj_distrib_mem s _ _ ,\n split,\n rw @forall_conj_distrib_mem' s _ _ ,\n split,\n rw @forall_conj_distrib_mem' s _ _ ,\n split,\n apply (@synchronize (atom fault_angleSensor_armController).neg.always s fault_angleSensor_armController fault_output_armPosition ).mpr,\n simp,\n rw nf_def at Hb2,\n simp at Hb2, apply Hb2,\n rw @forall_conj_distrib_mem s _ _ at Ha,\n cases Ha with Ha Ha2,\n rw @forall_conj_distrib_mem' s _ _ at Ha,\n cases Ha with Ha Ha3,\n rw @forall_conj_distrib_mem' s _ _ at Ha,\n cases Ha with Ha Ha4,\n intro i, \n apply (@synchronize (((atom fault_input2_armPosition).neg OR (atom fault_input1_armPosition).neg).always) s fault_input1_armPosition fault_armPositionAngle1_LACU).mpr,\n apply (@synchronize (((atom fault_input2_armPosition).neg OR (atom fault_armPositionAngle1_LACU).neg).always) s fault_input2_armPosition fault_armPositionAngle2_LACU).mpr,\n simp,\n intro i,\n replace Ha := Ha i, rwa LANG.disj_comm at Ha,\n unfold LACU_ARCH_MODEL, dsimp, dec_trivial,\n unfold LACU_ARCH_MODEL, dsimp, dec_trivial,\n unfold LACU_ARCH_MODEL, dsimp, dec_trivial,\n apply ((@synchronize (atom fault_LAAPActive_armController).neg.always) s fault_LAAPActive_armController fault_LAAPActive_LAAP).mpr,\n simp, rw nf_def at Hb1,\n simp at Hb1,\n intro i,\n have : (s ∈ AssertionLang.sem ((atom fault_LAAPFlow_LAAP).neg & (atom fault_LAAPActive_LAAP).neg ).always) → stream.drop i s ∈ (atom fault_LAAPActive_LAAP).neg.sem,\n by { intros H', rw @forall_conj_distrib_mem s _ _ at H', \n cases H' with H' H'',\n apply H'' i,}, apply this,clear this, \n apply Hb1,\n rw @forall_conj_distrib_mem s _ _ at Ha,\n cases Ha with Ha Ha2,\n rw @forall_conj_distrib_mem' s _ _ at Ha,\n cases Ha with Ha Ha3,\n rw @forall_conj_distrib_mem' s _ _ at Ha,\n cases Ha with Ha Ha4,\n apply ((@synchronize ((atom fault_LAAPRequest_LAAP).neg & (atom fault_operatorControlLever_LAAP).neg).always) s fault_operatorControlLever_LAAP fault_operatorControlLever_LACU).mpr,\n simp,\n apply ((@synchronize ((atom fault_LAAPRequest_LAAP).neg & (atom fault_operatorControlLever_LACU).neg).always) s fault_LAAPRequest_LAAP fault_LAAPRequest_LACU).mpr,\n simp,\n intro i, split, apply Ha4 i,\n apply Ha3 i,\n unfold LACU_ARCH_MODEL, dsimp, dec_trivial,\n unfold LACU_ARCH_MODEL, dsimp, dec_trivial,\n unfold LACU_ARCH_MODEL, dsimp, dec_trivial,\n \nrw nf_def at Hb1,\n simp at Hb1,\n\napply ((@synchronize (atom fault_LAAPFlow_armController).neg.always) s fault_LAAPFlow_armController fault_LAAPFlow_LAAP).mpr,\nsimp,\nintro i,\nhave : (s ∈ AssertionLang.sem ((atom fault_LAAPFlow_LAAP).neg & (atom fault_LAAPActive_LAAP).neg ).always) → stream.drop i s ∈ (atom fault_LAAPFlow_LAAP).neg.sem,\n by { intros H', rw @forall_conj_distrib_mem s _ _ at H', cases H' with H' H'', apply H' i,},\napply this,\napply Hb1,\n rw @forall_conj_distrib_mem s _ _ at Ha,\n cases Ha with Ha Ha2,\n rw @forall_conj_distrib_mem' s _ _ at Ha,\n cases Ha with Ha Ha3,\n rw @forall_conj_distrib_mem' s _ _ at Ha,\n cases Ha with Ha Ha4,\n apply ((@synchronize ((atom fault_LAAPRequest_LAAP).neg & (atom fault_operatorControlLever_LAAP).neg).always) s fault_operatorControlLever_LAAP fault_operatorControlLever_LACU).mpr,\n simp,\n apply ((@synchronize ((atom fault_LAAPRequest_LAAP).neg & (atom fault_operatorControlLever_LACU).neg).always) s fault_LAAPRequest_LAAP fault_LAAPRequest_LACU).mpr,\n simp,\n intro i,\n split, apply Ha4 i, apply Ha3 i,\n unfold LACU_ARCH_MODEL, dsimp, dec_trivial,\n unfold LACU_ARCH_MODEL, dsimp, dec_trivial,\n unfold LACU_ARCH_MODEL, dsimp, dec_trivial,\n\n\n\n rw @forall_conj_distrib_mem s _ _ at Ha,\n cases Ha with Ha Ha2,\n rw @forall_conj_distrib_mem' s _ _ at Ha,\n cases Ha with Ha Ha3,\n rw @forall_conj_distrib_mem' s _ _ at Ha,\n cases Ha with Ha Ha4,\n apply (@synchronize (atom fault_operatorControlLever_armController).neg.always s fault_operatorControlLever_armController fault_operatorControlLever_LACU).mpr,\n simp,\n apply Ha3,\n unfold LACU_ARCH_MODEL, dsimp, dec_trivial]\n\n\nmeta def solve_rpo : tactic unit := do \n`[split], solve_rpo_fst\n\n\n-- example : RPO_snd\n-- {ArchitectureWithContracts .\n-- to_Architecture := LACU_ARCH_MODEL,\n-- parent := {Contract .\n-- A := ((atom fault_armPositionAngle1_LACU).neg OR(atom fault_armPositionAngle2_LACU).neg&(atom\n-- fault_LAAPRequest_LACU).neg&(atom fault_operatorControlLever_LACU).neg&(atom\n-- fault_groundSpeed_LACU).neg).always,\n-- G := (atom fault_PWMFlow_LACU).neg.always},\n-- contracts := toMap\n-- [(armPosition,\n-- {Contract .\n-- A := ((atom fault_input2_armPosition).neg OR(atom fault_input1_armPosition).neg).always,\n-- G := (atom fault_output_armPosition).neg.always}), (armController,\n-- {Contract .\n-- A := ((atom fault_angleSensor_armController).neg&(atom fault_LAAPActive_armController).neg&(atom\n-- fault_LAAPFlow_armController).neg&(atom\n-- fault_operatorControlLever_armController).neg).always,\n-- G := (atom fault_armFlow_armController).neg.always}), (LAAP,\n-- {Contract .\n-- A := ((atom fault_LAAPRequest_LAAP).neg&(atom fault_operatorControlLever_LAAP).neg).always,\n-- G := ((atom fault_LAAPFlow_LAAP).neg&(atom fault_LAAPActive_LAAP).neg).always})],\n-- all_components := by {unfold LACU_ARCH_MODEL, auto_all_comps,}}:= \n-- begin \n-- solve_rpo_snd,\n-- end \n\n", "meta": {"author": "loganrjmurphy", "repo": "ForeMoSt", "sha": "c7affc7c8971562520d2775ac48fe4f188f84b02", "save_path": "github-repos/lean/loganrjmurphy-ForeMoSt", "path": "github-repos/lean/loganrjmurphy-ForeMoSt/ForeMoSt-c7affc7c8971562520d2775ac48fe4f188f84b02/src/rpo_meta.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.36658973632215985, "lm_q2_score": 0.017442483938143658, "lm_q1q2_score": 0.006394235587687592}} {"text": "import group_theory.group_action.basic\n\nvariables (R M S : Type*)\n\n/-- Some arbitrary type depending on `has_scalar R M` -/\n@[irreducible, nolint has_inhabited_instance unused_arguments]\ndef foo [has_scalar R M] : Type* := ℕ\n\nvariables [has_scalar R M] [has_scalar S R] [has_scalar S M]\n\n/-- This instance is incompatible with `has_scalar.comp.is_scalar_tower`.\nHowever, all its parameters are (instance) implicits or irreducible defs, so it\nshould not be dangerous. -/\n@[nolint unused_arguments]\ninstance foo.has_scalar [is_scalar_tower S R M] : has_scalar S (foo R M) :=\n⟨λ _ _, by { unfold foo, exact 37 }⟩\n\n-- If there is no `is_scalar_tower S R M` parameter, this should fail quickly,\n-- not loop forever.\nexample : has_scalar S (foo R M) :=\nbegin\n tactic.success_if_fail_with_msg tactic.interactive.apply_instance\n \"tactic.mk_instance failed to generate instance for\n has_scalar S (foo R M)\",\n unfold foo,\n exact ⟨λ _ _, 37⟩\nend\n\n/-\nlocal attribute [instance] has_scalar.comp.is_scalar_tower\n-- When `has_scalar.comp.is_scalar_tower` is an instance, this recurses indefinitely.\nexample : has_scalar S (foo R M) :=\nbegin\n tactic.success_if_fail_with_msg tactic.interactive.apply_instance\n \"maximum class-instance resolution depth has been reached (the limit can be increased by setting option 'class.instance_max_depth') (the class-instance resolution trace can be visualized by setting option 'trace.class_instances')\",\n unfold foo,\n exact ⟨λ _ _, 37⟩\nend\n-/\n", "meta": {"author": "jjaassoonn", "repo": "projective_space", "sha": "11fe19fe9d7991a272e7a40be4b6ad9b0c10c7ce", "save_path": "github-repos/lean/jjaassoonn-projective_space", "path": "github-repos/lean/jjaassoonn-projective_space/projective_space-11fe19fe9d7991a272e7a40be4b6ad9b0c10c7ce/test/has_scalar_comp_loop.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.29746993014852224, "lm_q2_score": 0.02128735047402253, "lm_q1q2_score": 0.006332346658554594}} {"text": "/-\nCopyright (c) 2017 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Jared Roesch, Sebastian Ullrich\n\nThe Except monad transformer.\n-/\nprelude\nimport Init.Control.Basic\nimport Init.Control.Id\nimport Init.Coe\n\nnamespace Except\nvariable {ε : Type u}\n\n@[always_inline, inline]\nprotected def pure (a : α) : Except ε α :=\n Except.ok a\n\n@[always_inline, inline]\nprotected def map (f : α → β) : Except ε α → Except ε β\n | Except.error err => Except.error err\n | Except.ok v => Except.ok <| f v\n\n@[simp] theorem map_id : Except.map (ε := ε) (α := α) (β := α) id = id := by\n apply funext\n intro e\n simp [Except.map]; cases e <;> rfl\n\n@[always_inline, inline]\nprotected def mapError (f : ε → ε') : Except ε α → Except ε' α\n | Except.error err => Except.error <| f err\n | Except.ok v => Except.ok v\n\n@[always_inline, inline]\nprotected def bind (ma : Except ε α) (f : α → Except ε β) : Except ε β :=\n match ma with\n | Except.error err => Except.error err\n | Except.ok v => f v\n\n/-- Returns true if the value is `Except.ok`, false otherwise. -/\n@[always_inline, inline]\nprotected def toBool : Except ε α → Bool\n | Except.ok _ => true\n | Except.error _ => false\n\nabbrev isOk : Except ε α → Bool := Except.toBool\n\n@[always_inline, inline]\nprotected def toOption : Except ε α → Option α\n | Except.ok a => some a\n | Except.error _ => none\n\n@[always_inline, inline]\nprotected def tryCatch (ma : Except ε α) (handle : ε → Except ε α) : Except ε α :=\n match ma with\n | Except.ok a => Except.ok a\n | Except.error e => handle e\n\ndef orElseLazy (x : Except ε α) (y : Unit → Except ε α) : Except ε α :=\n match x with\n | Except.ok a => Except.ok a\n | Except.error _ => y ()\n\n@[always_inline]\ninstance : Monad (Except ε) where\n pure := Except.pure\n bind := Except.bind\n map := Except.map\n\nend Except\n\ndef ExceptT (ε : Type u) (m : Type u → Type v) (α : Type u) : Type v :=\n m (Except ε α)\n\n@[always_inline, inline]\ndef ExceptT.mk {ε : Type u} {m : Type u → Type v} {α : Type u} (x : m (Except ε α)) : ExceptT ε m α := x\n\n@[always_inline, inline]\ndef ExceptT.run {ε : Type u} {m : Type u → Type v} {α : Type u} (x : ExceptT ε m α) : m (Except ε α) := x\n\nnamespace ExceptT\n\nvariable {ε : Type u} {m : Type u → Type v} [Monad m]\n\n@[always_inline, inline]\nprotected def pure {α : Type u} (a : α) : ExceptT ε m α :=\n ExceptT.mk <| pure (Except.ok a)\n\n@[always_inline, inline]\nprotected def bindCont {α β : Type u} (f : α → ExceptT ε m β) : Except ε α → m (Except ε β)\n | Except.ok a => f a\n | Except.error e => pure (Except.error e)\n\n@[always_inline, inline]\nprotected def bind {α β : Type u} (ma : ExceptT ε m α) (f : α → ExceptT ε m β) : ExceptT ε m β :=\n ExceptT.mk <| ma >>= ExceptT.bindCont f\n\n@[always_inline, inline]\nprotected def map {α β : Type u} (f : α → β) (x : ExceptT ε m α) : ExceptT ε m β :=\n ExceptT.mk <| x >>= fun a => match a with\n | (Except.ok a) => pure <| Except.ok (f a)\n | (Except.error e) => pure <| Except.error e\n\n@[always_inline, inline]\nprotected def lift {α : Type u} (t : m α) : ExceptT ε m α :=\n ExceptT.mk <| Except.ok <$> t\n\n@[always_inline]\ninstance : MonadLift (Except ε) (ExceptT ε m) := ⟨fun e => ExceptT.mk <| pure e⟩\ninstance : MonadLift m (ExceptT ε m) := ⟨ExceptT.lift⟩\n\n@[always_inline, inline]\nprotected def tryCatch {α : Type u} (ma : ExceptT ε m α) (handle : ε → ExceptT ε m α) : ExceptT ε m α :=\n ExceptT.mk <| ma >>= fun res => match res with\n | Except.ok a => pure (Except.ok a)\n | Except.error e => (handle e)\n\ninstance : MonadFunctor m (ExceptT ε m) := ⟨fun f x => f x⟩\n\n@[always_inline]\ninstance : Monad (ExceptT ε m) where\n pure := ExceptT.pure\n bind := ExceptT.bind\n map := ExceptT.map\n\n@[always_inline, inline]\nprotected def adapt {ε' α : Type u} (f : ε → ε') : ExceptT ε m α → ExceptT ε' m α := fun x =>\n ExceptT.mk <| Except.mapError f <$> x\n\nend ExceptT\n\n@[always_inline]\ninstance (m : Type u → Type v) (ε₁ : Type u) (ε₂ : Type u) [Monad m] [MonadExceptOf ε₁ m] : MonadExceptOf ε₁ (ExceptT ε₂ m) where\n throw e := ExceptT.mk <| throwThe ε₁ e\n tryCatch x handle := ExceptT.mk <| tryCatchThe ε₁ x handle\n\n@[always_inline]\ninstance (m : Type u → Type v) (ε : Type u) [Monad m] : MonadExceptOf ε (ExceptT ε m) where\n throw e := ExceptT.mk <| pure (Except.error e)\n tryCatch := ExceptT.tryCatch\n\ninstance [Monad m] [Inhabited ε] : Inhabited (ExceptT ε m α) where\n default := throw default\n\ninstance (ε) : MonadExceptOf ε (Except ε) where\n throw := Except.error\n tryCatch := Except.tryCatch\n\nnamespace MonadExcept\nvariable {ε : Type u} {m : Type v → Type w}\n\n/-- Alternative orelse operator that allows to select which exception should be used.\n The default is to use the first exception since the standard `orelse` uses the second. -/\n@[always_inline, inline]\ndef orelse' [MonadExcept ε m] {α : Type v} (t₁ t₂ : m α) (useFirstEx := true) : m α :=\n tryCatch t₁ fun e₁ => tryCatch t₂ fun e₂ => throw (if useFirstEx then e₁ else e₂)\n\nend MonadExcept\n\n@[always_inline, inline]\ndef observing {ε α : Type u} {m : Type u → Type v} [Monad m] [MonadExcept ε m] (x : m α) : m (Except ε α) :=\n tryCatch (do let a ← x; pure (Except.ok a)) (fun ex => pure (Except.error ex))\n\ndef liftExcept [MonadExceptOf ε m] [Pure m] : Except ε α → m α\n | Except.ok a => pure a\n | Except.error e => throw e\n\ninstance (ε : Type u) (m : Type u → Type v) [Monad m] : MonadControl m (ExceptT ε m) where\n stM := Except ε\n liftWith f := liftM <| f fun x => x.run\n restoreM x := x\n\nclass MonadFinally (m : Type u → Type v) where\n /-- `tryFinally' x f` runs `x` and then the \"finally\" computation `f`.\n When `x` succeeds with `a : α`, `f (some a)` is returned. If `x` fails\n for `m`'s definition of failure, `f none` is returned. Hence `tryFinally'`\n can be thought of as performing the same role as a `finally` block in\n an imperative programming language. -/\n tryFinally' {α β} : m α → (Option α → m β) → m (α × β)\n\nexport MonadFinally (tryFinally')\n\n/-- Execute `x` and then execute `finalizer` even if `x` threw an exception -/\n@[always_inline, inline]\ndef tryFinally {m : Type u → Type v} {α β : Type u} [MonadFinally m] [Functor m] (x : m α) (finalizer : m β) : m α :=\n let y := tryFinally' x (fun _ => finalizer)\n (·.1) <$> y\n\n@[always_inline]\ninstance Id.finally : MonadFinally Id where\n tryFinally' := fun x h =>\n let a := x\n let b := h (some x)\n pure (a, b)\n\n@[always_inline]\ninstance ExceptT.finally {m : Type u → Type v} {ε : Type u} [MonadFinally m] [Monad m] : MonadFinally (ExceptT ε m) where\n tryFinally' := fun x h => ExceptT.mk do\n let r ← tryFinally' x fun e? => match e? with\n | some (.ok a) => h (some a)\n | _ => h none\n match r with\n | (.ok a, .ok b) => pure (.ok (a, b))\n | (_, .error e) => pure (.error e) -- second error has precedence\n | (.error e, _) => pure (.error e)\n", "meta": {"author": "leanprover", "repo": "lean4", "sha": "742d053a97bdd109a41a921facd1cd6a55e89bc7", "save_path": "github-repos/lean/leanprover-lean4", "path": "github-repos/lean/leanprover-lean4/lean4-742d053a97bdd109a41a921facd1cd6a55e89bc7/src/Init/Control/Except.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1259227648351323, "lm_q2_score": 0.04885778052646011, "lm_q1q2_score": 0.006152306807599942}} {"text": "macro x:ident noWs \"(\" ys:term,* \")\" : term => `($x $ys*)\n\n#check id(1)\n\nmacro \"foo\" &\"only\" : tactic => `(tactic| trivial)\n\nexample : True := by foo only\n", "meta": {"author": "leanprover", "repo": "lean4", "sha": "742d053a97bdd109a41a921facd1cd6a55e89bc7", "save_path": "github-repos/lean/leanprover-lean4", "path": "github-repos/lean/leanprover-lean4/lean4-742d053a97bdd109a41a921facd1cd6a55e89bc7/tests/lean/run/macroParams.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.21469141911224193, "lm_q2_score": 0.028007519490434726, "lm_q1q2_score": 0.006012974105215206}} {"text": "import for_mathlib.snake_lemma3\nimport for_mathlib.les_homology\nimport for_mathlib.snake_lemma_naturality\n\nnoncomputable theory\n\nopen category_theory category_theory.limits\n\nnamespace category_theory\n\nsection\n\nlocal attribute [-instance] category_theory.prod\n\n@[elab_as_eliminator]\nlemma preorder_prod_induction {C D : Type*} [preorder C] [preorder D]\n {motive : Π ⦃i j : C × D⦄ (f : i ⟶ j), Prop}\n (comp : ∀ {i j k : C × D} (f : i ⟶ j) (g : j ⟶ k), motive f → motive g → motive (f ≫ g))\n (H1 : ∀ (i : C) {j k : D} (f : j ≤ k), @motive (i,j) (i,k) (hom_of_le $ ⟨le_rfl, f⟩))\n (H2 : ∀ {i j : C} (k : D) (f : i ≤ j), @motive (i,k) (j,k) (hom_of_le $ ⟨f, le_rfl⟩))\n ⦃i j : C × D⦄ (f : i ⟶ j) : motive f :=\nbegin\n cases i with i1 i2, cases j with j1 j2,\n convert comp _ _ (H1 i1 f.le.2) (H2 j2 f.le.1),\nend\n\nend\n\nvariables {C D : Type*} [category C] [category D]\n\n@[elab_as_eliminator]\nlemma prod_induction\n {motive : Π ⦃i j : C × D⦄ (f : i ⟶ j), Prop}\n (comp : ∀ {i j k : C × D} (f : i ⟶ j) (g : j ⟶ k), motive f → motive g → motive (f ≫ g))\n (H1 : ∀ (i : C) {j k : D} (f : j ⟶ k), @motive (i,j) (i,k) (𝟙 i, f))\n (H2 : ∀ {i j : C} (k : D) (f : i ⟶ j), @motive (i,k) (j,k) (f, 𝟙 k))\n ⦃i j : C × D⦄ (f : i ⟶ j) : motive f :=\nbegin\n let f1 : (i.1, i.2) ⟶ (i.1, j.2) := (𝟙 i.1, f.2),\n let f2 : (i.1, j.2) ⟶ (j.1, j.2) := (f.1, 𝟙 j.2),\n have hf : f = f1 ≫ f2,\n { ext; simp only [prod_comp_fst, prod_comp_snd, category.id_comp, category.comp_id], },\n rw hf, cases i, cases j,\n apply comp; apply_assumption,\nend\n\n@[elab_as_eliminator]\nlemma fin_induction (n : ℕ)\n {motive : Π ⦃i j : fin (n+1)⦄ (f : i ≤ j), Prop}\n (id : ∀ i, motive (le_refl i))\n (comp : ∀ {i j k : fin (n+1)} (f : i ≤ j) (g : j ≤ k), motive f → motive g → motive (f.trans g : i ≤ k))\n (Hsucc : ∀ (i : fin n), @motive i.cast_succ i.succ (le_of_lt $ by { rw fin.cast_succ_lt_iff_succ_le }))\n ⦃i j : fin (n+1)⦄ (f : i ≤ j) : motive f :=\nbegin\n revert f,\n refine fin.induction_on j _ _; clear j,\n { intro f, have hi : i = 0, { erw eq_bot_iff, exact f }, subst i, convert id _, },\n { intros j IH f,\n obtain (hij|rfl|hij) := lt_trichotomy i j.succ,\n { rw ← fin.le_cast_succ_iff at hij,\n convert comp _ _ (IH hij) (Hsucc j), },\n { convert id _, },\n { exact (f.not_lt hij).elim } }\nend\n\nend category_theory\n\nvariables {C 𝓐 : Type*} [category C] [category 𝓐] [abelian 𝓐]\n\nnamespace homological_complex\n\nvariables {ι : Type*} {c : complex_shape ι}\n\nlocal notation x `⟶[`D`]` y := D.map (snake_diagram.hom x y)\n\ndef cast_horizontal (i : fin 4) (j : fin 2) : snake_diagram := (i,j.cast_succ)\ndef cast_vertical (i : fin 3) (j : fin 3) : snake_diagram := (i.cast_succ,j)\ndef succ_horizontal (i : fin 4) (j : fin 2) : snake_diagram := (i, j.succ)\ndef succ_vertical (i : fin 3) (j : fin 3) : snake_diagram := (i.succ,j)\ndef to_succ_horizontal (i : fin 4) (j : fin 2) :\n cast_horizontal i j ⟶ succ_horizontal i j := snake_diagram.hom _ _\ndef to_succ_vertical ( i : fin 3) (j : fin 3) :\n cast_vertical i j ⟶ succ_vertical i j := snake_diagram.hom _ _\n\nlemma snake_diagram_induction\n {motive : Π ⦃i j : snake_diagram⦄ (f : i ⟶ j), Prop}\n (id : ∀ i : snake_diagram, motive (𝟙 i))\n (comp : ∀ (i j k : snake_diagram) (f : i ⟶ j) (g : j ⟶ k),\n motive f → motive g → motive (f ≫ g))\n (succ_horizontal : ∀ (i : fin 4) (j : fin 2),\n motive (to_succ_horizontal i j))\n (succ_vertical : ∀ (i : fin 3) (j : fin 3),\n motive (to_succ_vertical i j)) ⦃i j : snake_diagram⦄ (f : i ⟶ j) : motive f :=\nbegin\n apply category_theory.preorder_prod_induction comp; clear f i j,\n { intros i,\n refine @category_theory.fin_induction 2\n (λ j k f, motive (hom_of_le $ (⟨le_refl i, f⟩ : (i,j) ≤ (i,k)))) _ _ _,\n { intros j, convert id _, },\n { intros i' j k f g hf hg, convert comp _ _ _ _ _ hf hg, },\n { intros j, convert succ_horizontal i j } },\n { intros i j k, revert i j,\n refine @category_theory.fin_induction 3\n (λ i j f, motive (hom_of_le $ (⟨f, le_refl k⟩ : (i,k) ≤ (j,k)))) _ _ _,\n { intros j, convert id _, },\n { intros i' j k f g hf hg, convert comp _ _ _ _ _ hf hg, },\n { intros i, convert succ_vertical i k } },\nend\n\nvariables\n {X Y Z : C ⥤ homological_complex 𝓐 c} (f : X ⟶ Y) (g : Y ⟶ Z)\n (H : ∀ c i, short_exact ((f.app c).f i) ((g.app c).f i))\n {c₁ c₂ : C} (φ : c₁ ⟶ c₂) (i j : ι) (hij : c.rel i j)\n\ndef mk_snake_diagram_nat_trans_app : Π (e : snake_diagram),\n (snake (f.app c₁) (g.app c₁) (H _) i j hij).snake_diagram.obj e ⟶\n (snake (f.app c₂) (g.app c₂) (H _) i j hij).snake_diagram.obj e\n| ⟨⟨0,_⟩,⟨0,_⟩⟩ := (homology_functor _ _ i).map (X.map φ)\n| ⟨⟨0,_⟩,⟨1,_⟩⟩ := (homology_functor _ _ i).map (Y.map φ)\n| ⟨⟨0,_⟩,⟨2,_⟩⟩ := (homology_functor _ _ i).map (Z.map φ)\n| ⟨⟨1,_⟩,⟨0,_⟩⟩ := (mod_boundaries_functor _).map (X.map φ)\n| ⟨⟨1,_⟩,⟨1,_⟩⟩ := (mod_boundaries_functor _).map (Y.map φ)\n| ⟨⟨1,_⟩,⟨2,_⟩⟩ := (mod_boundaries_functor _).map (Z.map φ)\n| ⟨⟨2,_⟩,⟨0,_⟩⟩ := (cycles_functor _ _ _).map (X.map φ)\n| ⟨⟨2,_⟩,⟨1,_⟩⟩ := (cycles_functor _ _ _).map (Y.map φ)\n| ⟨⟨2,_⟩,⟨2,_⟩⟩ := (cycles_functor _ _ _).map (Z.map φ)\n| ⟨⟨3,_⟩,⟨0,_⟩⟩ := (homology_functor _ _ j).map (X.map φ)\n| ⟨⟨3,_⟩,⟨1,_⟩⟩ := (homology_functor _ _ j).map (Y.map φ)\n| ⟨⟨3,_⟩,⟨2,_⟩⟩ := (homology_functor _ _ j).map (Z.map φ)\n| _ := 0 -- impossible case\n.\n\ndef mk_snake_diagram_nat_trans_hor :\n ∀ (a : fin 4) (b : fin 2),\n (snake (f.app c₁) (g.app c₁) (H _) i j hij).snake_diagram.map (to_succ_horizontal a b) ≫\n mk_snake_diagram_nat_trans_app f g H φ i j hij (succ_horizontal a b) =\n mk_snake_diagram_nat_trans_app f g H φ i j hij (cast_horizontal a b) ≫\n (snake (f.app c₂) (g.app c₂) (H _) i j hij).snake_diagram.map (to_succ_horizontal a b)\n| ⟨0,_⟩ ⟨0,_⟩ := by { repeat { erw [snake_diagram.mk_functor_map_f0, ← category_theory.functor.map_comp] }, rw nat_trans.naturality, }\n| ⟨0,_⟩ ⟨1,_⟩ := by { repeat { erw [snake_diagram.mk_functor_map_g0, ← category_theory.functor.map_comp] }, rw nat_trans.naturality, }\n| ⟨0,_⟩ ⟨n+2,h⟩ := by { exfalso, rw [nat.succ_lt_succ_iff, nat.succ_lt_succ_iff] at h, exact nat.not_lt_zero n h }\n| ⟨1,_⟩ ⟨0,_⟩ := by { repeat { erw [snake_diagram.mk_functor_map_f1, ← category_theory.functor.map_comp] }, rw nat_trans.naturality, }\n| ⟨1,_⟩ ⟨1,_⟩ := by { repeat { erw [snake_diagram.mk_functor_map_g1, ← category_theory.functor.map_comp] }, rw nat_trans.naturality, }\n| ⟨1,_⟩ ⟨n+2,h⟩ := by { exfalso, rw [nat.succ_lt_succ_iff, nat.succ_lt_succ_iff] at h, exact nat.not_lt_zero n h }\n| ⟨2,_⟩ ⟨0,_⟩ := by { repeat { erw [snake_diagram.mk_functor_map_f2, ← category_theory.functor.map_comp] }, rw nat_trans.naturality, }\n| ⟨2,_⟩ ⟨1,_⟩ := by { repeat { erw [snake_diagram.mk_functor_map_g2, ← category_theory.functor.map_comp] }, rw nat_trans.naturality, }\n| ⟨2,_⟩ ⟨n+2,h⟩ := by { exfalso, rw [nat.succ_lt_succ_iff, nat.succ_lt_succ_iff] at h, exact nat.not_lt_zero n h }\n| ⟨3,_⟩ ⟨0,_⟩ := by { repeat { erw [snake_diagram.mk_functor_map_f3, ← category_theory.functor.map_comp] }, rw nat_trans.naturality, }\n| ⟨3,_⟩ ⟨1,_⟩ := by { repeat { erw [snake_diagram.mk_functor_map_g3, ← category_theory.functor.map_comp] }, rw nat_trans.naturality, }\n| ⟨3,_⟩ ⟨n+2,h⟩ := by { exfalso, rw [nat.succ_lt_succ_iff, nat.succ_lt_succ_iff] at h, exact nat.not_lt_zero n h }\n| ⟨n+4,h⟩ _ := by { exfalso, repeat { rw [nat.succ_lt_succ_iff] at h }, exact nat.not_lt_zero n h }\n.\n\ndef mk_snake_diagram_nat_trans_ver :\n ∀ (a b : fin 3),\n (snake (f.app c₁) (g.app c₁) (H _) i j hij).snake_diagram.map (to_succ_vertical a b) ≫\n mk_snake_diagram_nat_trans_app f g H φ i j hij (succ_vertical a b) =\n mk_snake_diagram_nat_trans_app f g H φ i j hij (cast_vertical a b) ≫\n (snake (f.app c₂) (g.app c₂) (H _) i j hij).snake_diagram.map (to_succ_vertical a b)\n| ⟨0,_⟩ ⟨0,_⟩ := by { repeat { erw [snake_diagram.mk_functor_map_a0] }, erw nat_trans.naturality, refl }\n| ⟨0,_⟩ ⟨1,_⟩ := by { repeat { erw [snake_diagram.mk_functor_map_b0] }, erw nat_trans.naturality, refl }\n| ⟨0,_⟩ ⟨2,_⟩ := by { repeat { erw [snake_diagram.mk_functor_map_c0] }, erw nat_trans.naturality, refl }\n| ⟨0,_⟩ ⟨n+3,h⟩ := by { exfalso, repeat { rw [nat.succ_lt_succ_iff] at h }, exact nat.not_lt_zero n h }\n| ⟨1,_⟩ ⟨0,_⟩ := by { repeat { erw [snake_diagram.mk_functor_map_a1] }, erw nat_trans.naturality, refl }\n| ⟨1,_⟩ ⟨1,_⟩ := by { repeat { erw [snake_diagram.mk_functor_map_b1] }, erw nat_trans.naturality, refl }\n| ⟨1,_⟩ ⟨2,_⟩ := by { repeat { erw [snake_diagram.mk_functor_map_c1] }, erw nat_trans.naturality, refl }\n| ⟨1,_⟩ ⟨n+3,h⟩ := by { exfalso, repeat { rw [nat.succ_lt_succ_iff] at h }, exact nat.not_lt_zero n h }\n| ⟨2,_⟩ ⟨0,_⟩ := by { repeat { erw [snake_diagram.mk_functor_map_a2] }, erw nat_trans.naturality, refl }\n| ⟨2,_⟩ ⟨1,_⟩ := by { repeat { erw [snake_diagram.mk_functor_map_b2] }, erw nat_trans.naturality, refl }\n| ⟨2,_⟩ ⟨2,_⟩ := by { repeat { erw [snake_diagram.mk_functor_map_c2] }, erw nat_trans.naturality, refl }\n| ⟨2,_⟩ ⟨n+3,h⟩ := by { exfalso, repeat { rw [nat.succ_lt_succ_iff] at h }, exact nat.not_lt_zero n h }\n| ⟨n+3,h⟩ _ := by { exfalso, repeat { rw [nat.succ_lt_succ_iff] at h }, exact nat.not_lt_zero n h }\n.\n\n-- TODO: Make a general construction, similar to `snake_diagram.mk_functor`\ndef mk_snake_diagram_nat_trans :\n (snake (f.app c₁) (g.app c₁) (H _) i j hij).snake_diagram ⟶\n (snake (f.app c₂) (g.app c₂) (H _) i j hij).snake_diagram :=\n{ app := λ e, mk_snake_diagram_nat_trans_app f g H φ i j hij e,\n naturality' := begin\n apply snake_diagram_induction,\n { intro, simp only [category_theory.functor.map_id, category.id_comp, category.comp_id] },\n { intros i j k f g h1 h2, simp only [functor.map_comp, category.assoc, h2, reassoc_of h1] },\n { exact mk_snake_diagram_nat_trans_hor f g H φ i j hij },\n { exact mk_snake_diagram_nat_trans_ver f g H φ i j hij },\n end }\n\nlemma δ_natural :\n δ (f.app c₁) (g.app c₁) (H _) i j hij ≫ (homology_functor _ _ j).map (X.map φ) =\n (homology_functor _ _ i).map (Z.map φ) ≫ δ (f.app c₂) (g.app c₂) (H _) i j hij :=\nbegin\n let η := mk_snake_diagram_nat_trans f g H φ i j hij,\n apply (snake_lemma.δ_natural η _ _).symm,\nend\n\nend homological_complex\n", "meta": {"author": "leanprover-community", "repo": "lean-liquid", "sha": "92f188bd17f34dbfefc92a83069577f708851aec", "save_path": "github-repos/lean/leanprover-community-lean-liquid", "path": "github-repos/lean/leanprover-community-lean-liquid/lean-liquid-92f188bd17f34dbfefc92a83069577f708851aec/src/for_mathlib/snake_lemma_naturality2.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.33807712415000585, "lm_q2_score": 0.017712300647853625, "lm_q1q2_score": 0.005988123665106639}} {"text": "import mcl.defs\nimport mcl.rhl\nimport mcl.compute_list\n\nopen parlang\nopen parlang.state\nopen parlang.thread_state\nopen mcl\nopen mcl.rhl\n\ninductive op (sig : signature)\n| store {t} {dim} (var : string) (idx : vector (expression sig type.int) dim) (h₁ : type_of (sig.val var) = t) (h₂ : ((sig.val var).type).dim = dim) : op\n| compute_list (computes : list (memory (parlang_mcl_tlocal sig) → memory (parlang_mcl_tlocal sig))) : op\n\ndef ts_updates {sig : signature} : list (op sig) → thread_state (memory $ parlang_mcl_tlocal sig) (parlang_mcl_shared sig) → thread_state (memory $ parlang_mcl_tlocal sig) (parlang_mcl_shared sig)\n| [] ts := ts\n| (op.store var idx h₁ h₂ :: ops) ts := ts_updates ops $ thread_state.tlocal_to_shared var idx h₁ h₂ ts\n| (op.compute_list computes :: ops) ts := ts_updates ops $ compute_list computes ts\n\nlemma ts_update_compute_list {sig : signature} (ups : list (op sig)) (computes) : ts_updates (op.compute_list computes :: ups) = ts_updates ups ∘ compute_list computes := by refl\n\nlemma ts_update_split {sig : signature} (up) (ups : list (op sig)) : ts_updates (list.reverse (up :: ups)) = ts_updates [up] ∘ ts_updates (list.reverse ups) := begin\n funext ts,\n rw list.reverse_cons,\n induction (list.reverse ups) generalizing ts,\n {\n refl,\n }, {\n simp,\n cases hd;\n rw ts_updates;\n apply ih,\n }\nend\n\nlemma ts_updates_tlocal {sig : signature} {ts : thread_state (memory $ parlang_mcl_tlocal sig) (parlang_mcl_shared sig)} {updates} (m loads stores) : \n(ts_updates updates ts).tlocal = (ts_updates updates { tlocal := ts.tlocal, loads := loads, stores := stores, shared := m }).tlocal := begin\n sorry,\nend\n\nlemma ts_updates_nil {sig : signature} (f : thread_state (memory $ parlang_mcl_tlocal sig) (parlang_mcl_shared sig) → thread_state (memory $ parlang_mcl_tlocal sig) (parlang_mcl_shared sig)) : \nts_updates [] ∘ f = f := begin\n refl,\nend\n\n@[simp]\nlemma ts_updates_store {sig : signature} {dim} {idx : vector (expression sig type.int) dim} {var t} {h₁ : type_of (sig.val var) = t} {h₂} {updates} (f : thread_state (memory $ parlang_mcl_tlocal sig) (parlang_mcl_shared sig) → thread_state (memory $ parlang_mcl_tlocal sig) (parlang_mcl_shared sig)) : \nts_updates updates ∘ thread_state.tlocal_to_shared var idx h₁ h₂ ∘ f = ts_updates (op.store var idx h₁ h₂ :: updates) ∘ f := begin\n refl,\nend\n\n@[simp]\nlemma ts_updates_compute {sig : signature} {g} {updates} (f : thread_state (memory $ parlang_mcl_tlocal sig) (parlang_mcl_shared sig) → thread_state (memory $ parlang_mcl_tlocal sig) (parlang_mcl_shared sig)) : \nts_updates updates ∘ compute g ∘ f = ts_updates (op.compute_list [g] :: updates) ∘ f := begin\n refl,\nend\n\n@[simp]\nlemma ts_updates_merge_computes_list {sig : signature} {updates} {com com' : list (memory (parlang_mcl_tlocal sig) → memory (parlang_mcl_tlocal sig))} :\nts_updates (op.compute_list com :: op.compute_list com' :: updates) = ts_updates (op.compute_list (com ++ com') :: updates) := begin\n sorry,\nend\n\n@[simp]\nlemma compute_list_stores' {sig : signature} {n} {tid : fin n} {ac : vector bool n} {computes}\n{s : state n (memory $ parlang_mcl_tlocal sig) (parlang_mcl_shared sig)} : \n(vector.nth ((map_active_threads ac (ts_updates [op.compute_list computes]) s).threads) tid).stores = (vector.nth s.threads tid).stores := begin\n by_cases h : ac.nth tid = tt,\n {\n simp [ts_updates, map_active_threads_nth_ac h],\n }, {\n rw ←map_active_threads_nth_inac h,\n }\nend\n\n@[simp]\nlemma compute_list_loads' {sig : signature} {n} {tid : fin n} {ac : vector bool n} {computes}\n{s : state n (memory $ parlang_mcl_tlocal sig) (parlang_mcl_shared sig)} : \n(vector.nth ((map_active_threads ac (ts_updates [op.compute_list computes]) s).threads) tid).loads = (vector.nth s.threads tid).loads := begin\n by_cases h : ac.nth tid = tt,\n {\n simp [ts_updates, map_active_threads_nth_ac h],\n }, {\n rw ←map_active_threads_nth_inac h,\n }\nend\n\n@[simp]\nlemma compute_list_shared' {sig : signature} {n} {tid : fin n} {ac : vector bool n} {computes}\n{s : state n (memory $ parlang_mcl_tlocal sig) (parlang_mcl_shared sig)} : \n(vector.nth ((map_active_threads ac (ts_updates [op.compute_list computes]) s).threads) tid).shared = (vector.nth s.threads tid).shared := begin\n by_cases h : ac.nth tid = tt,\n {\n simp [ts_updates, map_active_threads_nth_ac h],\n }, {\n rw ←map_active_threads_nth_inac h,\n }\nend", "meta": {"author": "fischerman", "repo": "GPU-transformation-verifier", "sha": "75a5016f05382738ff93ce5859c4cfa47ccb63c1", "save_path": "github-repos/lean/fischerman-GPU-transformation-verifier", "path": "github-repos/lean/fischerman-GPU-transformation-verifier/GPU-transformation-verifier-75a5016f05382738ff93ce5859c4cfa47ccb63c1/src/mcl/ts_updates.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.3140505321516081, "lm_q2_score": 0.018264277683886602, "lm_q1q2_score": 0.005735906125989328}} {"text": "-- TODO: Adapt to `HasIdentity`:\n-- Add type classes to \"upgrade\" a meta-relation to a relation,\n-- and especially to upgrade instance equivalences to an equality-like recursor\n-- (see `IsIdentity` below).\n#exit\n\n\n\nimport UniverseAbstractions.Axioms.Universes\nimport UniverseAbstractions.Axioms.Universe.Functors\nimport UniverseAbstractions.Axioms.Universe.Products\nimport UniverseAbstractions.Axioms.Universe.Equivalences\nimport UniverseAbstractions.Axioms.Universe.DependentTypes.Properties\nimport UniverseAbstractions.Axioms.Universe.DependentTypes.DependentFunctors\nimport UniverseAbstractions.Axioms.Universe.DependentTypes.DependentProducts\nimport UniverseAbstractions.Lemmas.DerivedFunctors\nimport UniverseAbstractions.Lemmas.DerivedProductFunctors\nimport UniverseAbstractions.Notation\n\n\n\nset_option autoBoundImplicitLocal false\n--set_option pp.universes true\n\nuniverse u v w w' w''\n\n\n\nclass HasRelations (U : Universe.{u}) [HasFunOp.{u, w} U] [HasInternalProducts.{u, w} U]\n (V : Universe.{v}) extends\n HasDependentFunctors.{u, v, v, w', w''} U V V : Type (max 1 u v w w' w'')\n\nnamespace HasRelations\n\n open HasProducts HasInternalProducts HasCompFunProp'\n\n variable {U : Universe.{u}} [HasFunOp.{u, w} U] [HasInternalProducts.{u, w} U]\n\n def relMap {V : Universe.{v}} [HasRelations.{u, v, w, w', w''} U V] {A : U} (r : A ⊓ A → V) :\n A → A → V :=\n λ a b => r (intro a b)\n\n def propMap {V : Universe.{v}} [HasRelations.{u, v, w, w', w''} U V] {A : U} (r : A → A → V) :\n A ⊓ A → V :=\n λ P => r (fst P) (snd P)\n\n def DefRel (A : U) (V : Universe.{v}) [HasRelations.{u, v, w, w', w''} U V] (r : A → A → V) :=\n A ⊓ A ⟿[propMap r] V\n notation:20 A:21 \" ⤐[\" r:0 \"] \" V:21 => HasRelations.DefRel A V r\n\n def Relation (A : U) (V : Universe.{v}) [HasRelations.{u, v, w, w', w''} U V] := A ⊓ A ⟶ ⌊V⌋\n infixr:20 \" ⤐ \" => HasRelations.Relation\n\n variable {V : Universe} [HasRelations U V] {A : U}\n\n instance coeRel : CoeFun (A ⤐ V) (λ _ => A → A → V) := ⟨λ θ => relMap θ.p⟩\n\n def defExtractABFun : (A ⊓ A) ⊓ A ⟶{λ P => intro (fst (fst P)) (snd (fst P))} A ⊓ A :=\n fstFun (A ⊓ A) A\n ◄ λ _ => by simp\n\n def defExtractBCFun : (A ⊓ A) ⊓ A ⟶{λ P => intro (snd (fst P)) (snd P)} A ⊓ A :=\n elim₃LFun (HasSubLinearFunOp.constFun A (introFunFun A A))\n ◄ λ _ => by simp [elim₃LFun]\n\n def defExtractACFun : (A ⊓ A) ⊓ A ⟶{λ P => intro (fst (fst P)) (snd P)} A ⊓ A :=\n elim₃LFun (HasLinearFunOp.swapFunFun (HasSubLinearFunOp.constFun A (introFunFun A A)))\n ◄ λ _ => by simp [elim₃LFun]\n\n @[reducible] def extractABFun' : (A ⊓ A) ⊓ A ⟶' A ⊓ A := HasFunctoriality.fromDefFun defExtractABFun\n @[reducible] def extractBCFun' : (A ⊓ A) ⊓ A ⟶' A ⊓ A := HasFunctoriality.fromDefFun defExtractBCFun\n @[reducible] def extractACFun' : (A ⊓ A) ⊓ A ⟶' A ⊓ A := HasFunctoriality.fromDefFun defExtractACFun\n\n variable [HasCompFunProp' U U V] (θ : A ⤐ V)\n\n class HasRefl where\n (reflPi : Π compProp (dupIntroFun' A) θ)\n\n def HasRefl.refl [HasRefl θ] (a : A) : θ a a := reflPi a\n\n variable [HasInternalFunctors V] [HasFunProp U V V V]\n\n class HasTrans where\n (transPi : Π {compProp extractABFun' θ ⟶ {compProp extractBCFun' θ ⟶ compProp extractACFun' θ}})\n\n @[simp] theorem simp_extractAB (a b c : A) :\n let P := intro₃L a b c;\n θ (fst (fst P)) (snd (fst P)) = θ a b :=\n by simp\n\n @[simp] theorem simp_extractBC (a b c : A) :\n let P := intro₃L a b c;\n θ (snd (fst P)) (snd P) = θ b c :=\n by simp\n\n @[simp] theorem simp_extractAC (a b c : A) :\n let P := intro₃L a b c;\n θ (fst (fst P)) (snd P) = θ a c :=\n by simp\n\n def HasTrans.trans [HasTrans θ] (a b c : A) : θ a b ⟶ θ b c ⟶ θ a c :=\n simp_extractAB θ a b c ▸ simp_extractBC θ a b c ▸ simp_extractAC θ a b c ▸ transPi (intro₃L a b c)\n\n class IsPreorder extends HasRefl θ, HasTrans θ\n\n variable [HasInternalProducts V] [HasInternalEquivalences V] [HasEquivProp U V V]\n\n class HasSymm where\n (symmPi : Π {θ ⟶ compProp (commFun' A A) θ})\n\n @[simp] theorem simp_swap (a b : A) :\n let P := intro a b;\n θ (snd P) (fst P) = θ b a :=\n by simp\n\n def HasSymm.symm [HasSymm θ] (a b : A) : θ a b ⟶ θ b a :=\n simp_swap θ a b ▸ symmPi (intro a b)\n\n class HasTransEquiv [HasTrans θ] [HasSymm θ] where\n (defTransEquiv {a b : A} (f : θ a b) (c : A) :\n θ b c ⟷{HasTrans.trans θ a b c f, HasTrans.trans θ b a c (HasSymm.symm θ a b f)} θ a c)\n (defTransEquivFun (a b c : A) :\n θ a b ⟶{λ f => HasEquivalences.fromDefEquiv (defTransEquiv f c)} (θ b c ⟷ θ a c))\n\n class HasSymmEquiv [HasSymm θ] where\n (defSymmEquiv (a b : A) : θ a b ⟷{HasSymm.symm θ a b, HasSymm.symm θ b a} θ b a)\n\n class IsEquivalence extends IsPreorder θ, HasSymm θ, HasTransEquiv θ\n\n def substRel (φ : A ⟶ ⌊V⌋) : A ⤐ V :=\n {compProp (fstFun' A A) φ ⟷ compProp (sndFun' A A) φ}\n\n @[simp] theorem simp_subst_refl (φ : A ⟶ ⌊V⌋) :\n compProp (dupIntroFun' A) (substRel φ) = {φ ⟷ φ} :=\n sorry\n\n class HasIdEquivPi (φ : A ⟶ ⌊V⌋) where\n [hasIdFun : HasIdFun V]\n [hasIdEquiv : HasIdEquiv V V]\n (F : Π{λ a => HasIdEquiv.idEquiv (φ a)} {φ ⟷ φ})\n\n instance substRel.hasRefl (φ : A ⟶ ⌊V⌋) [h : HasIdEquivPi φ] :\n HasRefl (substRel φ) :=\n ⟨simp_subst_refl φ ▸ h.F⟩\n\n class IsSubstitution extends HasRefl θ where\n (substPi (φ : A ⟶ ⌊V⌋) [HasIdEquivPi φ] : Π {θ ⟶ substRel φ})\n\n @[simp] theorem simp_apply_fst (φ : A ⟶ ⌊V⌋) (a b : A) :\n φ (fst (intro a b)) = φ a :=\n by simp\n\n @[simp] theorem simp_apply_snd (φ : A ⟶ ⌊V⌋) (a b : A) :\n φ (snd (intro a b)) = φ b :=\n by simp\n\n def IsSubstitution.subst [IsSubstitution θ] (φ : A ⟶ ⌊V⌋) [HasIdEquivPi φ] (a b : A) :\n θ a b ⟶ (φ a ⟷ φ b) :=\n simp_apply_fst φ a b ▸ simp_apply_snd φ a b ▸ substPi φ (intro a b)\n\n class IsIdentity extends HasRefl θ where\n (elimPi (ξ : A ⤐ V) [HasRefl ξ] : Π {θ ⟶ ξ})\n\n namespace IsIdentity\n\n variable [IsIdentity θ]\n\n def elim (ξ : A ⤐ V) [HasRefl ξ] (a b : A) : θ a b ⟶ ξ a b :=\n elimPi ξ (HasProducts.intro a b)\n\n instance isSubstitution : IsSubstitution θ :=\n { substPi := λ φ => elimPi (substRel φ) }\n\n end IsIdentity\n\nend HasRelations\n", "meta": {"author": "SReichelt", "repo": "universe-abstractions", "sha": "0bf2bae4c1b0f8d96c37e231dd238abda788e843", "save_path": "github-repos/lean/SReichelt-universe-abstractions", "path": "github-repos/lean/SReichelt-universe-abstractions/universe-abstractions-0bf2bae4c1b0f8d96c37e231dd238abda788e843/UniverseAbstractions/Axioms/Universe/DependentTypes/Relations.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.2720245510940225, "lm_q2_score": 0.020964241009279055, "lm_q1q2_score": 0.005702788249576032}} {"text": "/-\nIn this file, we explore the use of the tagless final style [1]\nto encode SSA semantics.\n\n[1] https://okmij.org/ftp/tagless-final/\n-/\nimport Lean\nopen Lean\n\nnamespace WriterT\ndef WriterT (m: Type _ -> Type _) (a: Type _) := m (a × String)\n\ndef WriterT.run (wm: WriterT m a ): m (a × String) := wm\n\ndef WriterT.mk (x: m (a × String)): WriterT m a := x\n\ninstance [Functor m]: Functor (WriterT m) where\n map f w := Functor.map (f := m) (fun (a, log) => (f a, log)) w\n\ninstance [Pure m]: Pure (WriterT m) where\n pure x := pure (f := m) (x, \"\")\n\ninstance [Monad m]: Seq (WriterT m) where\n seq mx my := WriterT.mk do\n let wx <- mx\n let wy <- (my ())\n let wb := wx.fst wy.fst\n return (wb, wx.snd ++ wy.snd)\n\ninstance [Monad m] : SeqLeft (WriterT m) where\n seqLeft mx my := WriterT.mk do\n let wx <- mx\n let wy <- (my ())\n return (wx.fst, wx.snd ++ wy.snd)\n\ninstance [Monad m] : SeqRight (WriterT m) where\n seqRight mx my := WriterT.mk do\n let wx <- mx\n let wy <- (my ())\n return (wy.fst, wx.snd ++ wy.snd )\n\ndef WriterT.bindCont [Bind m] [Pure m] (k: α → WriterT m β) (x: α × String):\n WriterT m β := WriterT.mk do\n let y ← k x.fst\n return (y.fst, x.snd ++ y.snd)\n\ndef WriterT.bind [Bind m] [Pure m] (wma: WriterT m α) (a2wmb: α → WriterT m β):\n WriterT m β :=\n WriterT.mk do\n let x <- wma\n WriterT.bindCont a2wmb x\n\ninstance [Bind m] [Pure m]: Bind (WriterT m) where\n bind wma a2wmb := WriterT.bind wma a2wmb\n\ndef WriterT.lift [Monad m] {α : Type u} (ma: m α): WriterT m α :=\n Bind.bind (m := m) ma (fun a => return (a, \"\"))\n\ninstance [Monad m]: MonadLift m (WriterT m) where\n monadLift := WriterT.lift\n\ninstance : MonadFunctor m (WriterT m) where\n monadMap f := f\n\ninstance [Monad m] : Applicative (WriterT m) where\n pure := Pure.pure\n seqLeft := SeqLeft.seqLeft\n seqRight := SeqRight.seqRight\n\ninstance [Monad m]: Monad (WriterT m) where\n pure := Pure.pure\n bind := Bind.bind\n map := Functor.map\n\ndef logWriterT [Monad m] (s: String): WriterT.{u} m PUnit.{u+1} :=\n pure (f := m) (.unit, s)\n\nend WriterT\n\nnamespace Fitree\nopen WriterT\n/- Extendable effect families -/\n\nabbrev to1 (E: Type → Type u) (F: Type → Type v) :=\n ∀ T, E T → F T\nabbrev sum1 (E F: Type → Type) :=\n fun T => E T ⊕ F T\ninductive Void1: Type → Type :=\n\ninfixr:40 \" ~> \" => to1\ninfixr:60 \" +' \" => sum1\n\nclass Member (E: Type → Type) (F: Type → Type) where\n inject : E ~> F\n\ninstance MemberId {E}: Member E E where\n inject := (fun _ => id)\n\ninstance MemberSumL {E F G} [Member E F]: Member E (F +' G) where\n inject T := Sum.inl ∘ Member.inject T\n\ninstance MemberSumR {E F G} [Member E G]: Member E (F +' G) where\n inject T := Sum.inr ∘ Member.inject T\n\ndef Sum.cases {α β γ} (fα: α → γ) (fβ: β → γ): (α ⊕ β) → γ\n | .inl a => fα a\n | .inr b => fβ b\n\ninstance MemberSum {E F G H} [Member E G] [Member F H]:\n Member (E +' F) (G +' H) where\n inject T := Sum.cases (Member.inject T) (Member.inject T)\n\ninstance MemberVoid1 {E}:\n Member Void1 E where\n inject _ e := nomatch e\n\n-- Effects can now be put in context automatically by typeclass resolution\nexample E: Member E E := inferInstance\nexample E F: Member E (E +' F) := inferInstance\nexample E F: Member E (F +' (F +' E)) := inferInstance\nexample E F G: Member (E +' F) (E +' F +' G) := inferInstance\n\n\n/- The monadic domain; essentially finite Interaction Trees -/\n\ninductive Fitree (E: Type → Type) (R: Type) where\n | Ret (r: R): Fitree E R\n | Vis {T: Type} (e: E T) (k: T → Fitree E R): Fitree E R\n\ndef Fitree.ret {E R}: R → Fitree E R :=\n Fitree.Ret\n\ndef Fitree.trigger {E: Type → Type} {F: Type → Type} {T} [Member E F]\n (e: E T): Fitree F T :=\n Fitree.Vis (Member.inject _ e) Fitree.ret\n\n\ndef Fitree.bind {E R T} (t: Fitree E T) (k: T → Fitree E R) :=\n match t with\n | Ret r => k r\n | Vis e k' => Vis e (fun r => bind (k' r) k)\n\ninstance {E}: Monad (Fitree E) where\n pure := Fitree.ret\n bind := Fitree.bind\n\n-- Since we only use finite ITrees, we can actually run them when they're\n-- fully interpreted (which leaves only the Ret constructor)\ndef Fitree.run {R}: Fitree Void1 R → R\n | Ret r => r\n | Vis e _ => nomatch e\n\n@[simp] theorem Fitree.run_ret:\n Fitree.run (Fitree.ret r) = r := rfl\n\ndef Fitree.translate {E F R} (f: E ~> F): Fitree E R → Fitree F R\n | Ret r => Ret r\n | Vis e k => Vis (f _ e) (fun r => translate f (k r))\n\n@[simp] theorem Fitree.translate_ret:\n Fitree.translate f (Fitree.ret r) = Fitree.ret r := rfl\n@[simp] theorem Fitree.translate_vis:\n Fitree.translate f (Vis e k) = Vis (f _ e) (fun r => translate f (k r)) :=\n rfl\n\ndef Fitree.case (h₁: E ~> G) (h₂: F ~> G): E +' F ~> G :=\n fun R ef => match ef with\n | Sum.inl e => h₁ R e\n | Sum.inr f => h₂ R f\n\n@[simp] theorem Fitree.case_left:\n Fitree.case h₁ h₂ _ (Sum.inl e) = h₁ _ e := rfl\n@[simp] theorem Fitree.case_right:\n Fitree.case h₁ h₂ _ (Sum.inr e) = h₂ _ e := rfl\n\n/-\n### Monadic interpretation\n-/\n\ndef Fitree.interp {M} [Monad M] {E} (h: E ~> M) {R}: Fitree E R → M R\n | .Ret r => pure r\n | .Vis e k => Bind.bind (h _ e) (fun t => interp h (k t))\n\ndef Fitree.interp' {E F} (h: E ~> Fitree Void1) {R} (t: Fitree (E +' F) R):\n Fitree F R :=\n interp (Fitree.case\n (fun _ e => (h _ e).translate $ fun _ e => nomatch e)\n (fun _ e => Fitree.trigger e)) t\n\n-- Interp `F` by lifting into a monad transformer (this is used when\n-- interpreting `E +' F` into the monad)\ndef Fitree.liftHandler {F M} [MonadLiftT (Fitree F) M]: F ~> M := fun R e =>\n monadLift (Fitree.trigger e: Fitree F R)\n\n-- Interpretation into various predefined monads. These are predefined so that\n-- rewriting theorems that expose the monad structure can be provided.\n\ndef Fitree.interpState {M S} [Monad M] {E} (h: E ~> StateT S M):\n forall {R}, Fitree E R → StateT S M R :=\n interp h\n\ndef Fitree.interpWriter {M} [Monad M] {E} (h: E ~> WriterT M):\n forall {R}, Fitree E R → WriterT M R :=\n interp h\n\ndef Fitree.interpOption {M} [Monad M] {E} (h: E ~> OptionT M):\n forall {R}, Fitree E R → OptionT M R :=\n interp h\n\ndef Fitree.interpExcept {M ε} [Monad M] {E} (h: E ~> ExceptT ε M) {R}:\n Fitree E R → ExceptT ε M R :=\n interp h\n\n/-\n### Combinator identities\n\nThe following theorems act as the main interface for computation on ITrees. We\ndon't unfold definitions because Lean 4 doesn't yet have the match-unfolding\nbehavior of Coq's `simpl` tactic, and runs into performance issues as unfolded\nterms grow larger. Instead, we aggressively rewrite the following simplifying\nequalities.\n-/\n\n@[simp] theorem Fitree.bind_ret:\n Fitree.bind (Fitree.ret r) k = k r := rfl\n\n@[simp] theorem Fitree.bind_Ret:\n Fitree.bind (Fitree.Ret r) k = k r := rfl\n\n@[simp] theorem Fitree.bind_ret':\n Fitree.bind t (fun r => Fitree.ret r) = t := by\n induction t with\n | Ret _ => rfl\n | Vis _ _ ih => simp [bind, ih]\n\n@[simp] theorem Fitree.bind_Ret':\n Fitree.bind t (fun r => Fitree.Ret r) = t := by\n induction t with\n | Ret _ => rfl\n | Vis _ _ ih => simp [bind, ih]\n\n@[simp] theorem Fitree.bind_bind:\n Fitree.bind (Fitree.bind t k) k' =\n Fitree.bind t (fun x => Fitree.bind (k x) k') := by\n induction t with\n | Ret _ => rfl\n | Vis _ _ ih => simp [bind, ih]\n\n@[simp] theorem Fitree.pure_is_ret:\n @Pure.pure (Fitree E) _ _ r = Fitree.ret r := rfl\n\n@[simp] theorem Fitree.bind_is_bind:\n @Bind.bind (Fitree E) _ _ _ t k = Fitree.bind t k := rfl\n\n@[simp] theorem Fitree.StateT_bind_is_bind (k: T → S → Fitree E (R × S)):\n StateT.bind (m := Fitree E) t k =\n fun s => Fitree.bind (t s) (fun (x,s) => k x s) := rfl\n\n@[simp] theorem Fitree.WriterT_bind_is_bind (k: T → Fitree E (R × String)):\n WriterT.bind (m := Fitree E) t k =\n Fitree.bind t (WriterT.bindCont k) := rfl\n\n@[simp] theorem Fitree.OptionT_bind_is_bind (k: T → Fitree E (Option R)):\n OptionT.bind (m := Fitree E) t k =\n Fitree.bind t (fun\n | some x => k x\n | none => Fitree.ret none) := rfl\n\n@[simp] theorem Fitree.ExceptT_bind_is_bind (k: T → Fitree E (Except ε R)):\n ExceptT.bind (m := Fitree E) t k = Fitree.bind t (ExceptT.bindCont k) := rfl\n\n@[simp] theorem Fitree.liftHandler_StateT_is_StateT_lift:\n @Fitree.liftHandler F (StateT S (Fitree F)) _ _ e =\n fun s => Fitree.bind (Fitree.trigger e) (fun x => Fitree.ret (x, s)) := rfl\n\n@[simp] theorem Fitree.liftHandler_WriterT_is_WriterT_lift:\n @Fitree.liftHandler F (WriterT (Fitree F)) _ _ e =\n Fitree.bind (Fitree.trigger e) (fun x => Fitree.ret (x, \"\")) := rfl\n\n@[simp] theorem Fitree.liftHandler_OptionT_is_OptionT_lift:\n @Fitree.liftHandler F (OptionT (Fitree F)) _ _ e =\n Fitree.bind (Fitree.trigger e) (fun x => Fitree.ret (some x)) := rfl\n\n@[simp] theorem Fitree.liftHandler_ExceptT_is_ExceptT_lift:\n @Fitree.liftHandler F (ExceptT ε (Fitree F)) _ _ e =\n Fitree.bind (Fitree.trigger e) (fun x => Fitree.ret (Except.ok x)) := rfl\n\n@[simp] theorem Member.injectId:\n @Member.inject E E MemberId _ e = e := rfl\n\n@[simp] theorem Member.injectSumL [Member E F]:\n @Member.inject E (F +' G) MemberSumL _ e = Sum.inl (Member.inject _ e) := rfl\n\n@[simp] theorem Member.injectSumR [Member E G]:\n @Member.inject E (F +' G) MemberSumR _ e = Sum.inr (Member.inject _ e) := rfl\n\n@[simp] theorem Member.injectSum_inl [Member E G] [Member F H]:\n @Member.inject (E +' F) (G +' H) MemberSum _ (Sum.inl e) =\n Sum.inl (Member.inject _ e) := rfl\n\n@[simp] theorem Member.injectSum_inr [Member E G] [Member F H]:\n @Member.inject (E +' F) (G +' H) MemberSum _ (Sum.inr e) =\n Sum.inr (Member.inject _ e) := rfl\n\n-- Interpretatin identities\n\n\n@[simp] theorem Fitree.interp_ret:\n Fitree.interp h (Fitree.ret r) = Fitree.ret r := rfl\n\n@[simp] theorem Fitree.interp_Ret:\n Fitree.interp h (Fitree.Ret r) = Fitree.ret r := rfl\n\n@[simp] theorem Fitree.interp_Vis:\n Fitree.interp h (Fitree.Vis e k) =\n Fitree.bind (h _ e) (fun x => Fitree.interp h (k x)) := rfl\n\n@[simp] theorem Fitree.interp'_ret:\n @Fitree.interp' E F h _ (Fitree.ret r) = Fitree.ret r := rfl\n\n@[simp] theorem Fitree.interp'_Vis_left:\n @Fitree.interp' E F h _ (Fitree.Vis (Sum.inl e) k) =\n Fitree.bind (Fitree.translate (fun _ e => nomatch e) (h _ e))\n (fun x => Fitree.interp' h (k x)) := rfl\n\n@[simp] theorem Fitree.interp'_Vis_right:\n @Fitree.interp' E F h _ (Fitree.Vis (Sum.inr e) k) =\n Fitree.bind (Fitree.trigger e)\n (fun x => Fitree.interp' h (k x)) := rfl\n\n@[simp] theorem Fitree.interpState_ret:\n Fitree.interpState h (Fitree.ret r) = (fun s => Fitree.ret (r, s)) := rfl\n\n@[simp] theorem Fitree.interpState_Vis {M S} [Monad M] (h: E ~> StateT S M):\n Fitree.interpState h (Fitree.Vis e k) =\n StateT.bind (h _ e) (fun x => Fitree.interpState h (k x)) := rfl\n\n@[simp] theorem Fitree.interpWriter_ret:\n Fitree.interpWriter h (Fitree.ret r) = Fitree.ret (r, \"\") := rfl\n\n@[simp] theorem Fitree.interpWriter_Vis {M} [Monad M] (h: E ~> WriterT M):\n Fitree.interpWriter h (Fitree.Vis e k) =\n WriterT.bind (h _ e) (fun x => Fitree.interpWriter h (k x)) := rfl\n\n@[simp] theorem Fitree.interpOption_ret:\n Fitree.interpOption h (Fitree.ret r) = Fitree.ret (some r) := rfl\n\n@[simp] theorem Fitree.interpOption_Vis {M} [Monad M] (h: E ~> OptionT M):\n Fitree.interpOption h (Fitree.Vis e k) =\n OptionT.bind (h _ e) (fun x => Fitree.interpOption h (k x)) := rfl\n\n@[simp] theorem Fitree.interpExcept_ret:\n Fitree.interpExcept h (Fitree.ret r) = Fitree.ret (.ok r) := rfl\n\n@[simp] theorem Fitree.interpExcept_Vis {M ε} [Monad M] (h: E ~> ExceptT ε M):\n Fitree.interpExcept h (Fitree.Vis e k) =\n ExceptT.bind (h _ e) (fun x => Fitree.interpExcept h (k x)) := rfl\n\n-- We don't assume [LawfulMonad M] so we can't simplify the continuation. But\n-- when it's an ITree the other simp lemmas will do it anyway.\n@[simp] theorem Fitree.interp_trigger [Member E F] [Monad M] (e: E T):\n Fitree.interp (M := M) (E := F) h (Fitree.trigger e) =\n Bind.bind (h _ (Member.inject _ e)) (fun x => pure x) := rfl\n\n@[simp] theorem Fitree.interp'_trigger_left (e: E R):\n @Fitree.interp' E F h _ (@Fitree.trigger (E +' F) _ _ MemberId (Sum.inl e)) =\n Fitree.bind\n (Fitree.translate (fun _ e => nomatch e) (h _ (Member.inject _ e)))\n (fun x => pure x) := rfl\n\n@[simp] theorem Fitree.interp'_trigger_right [Member G F]:\n @Fitree.interp' E F h _ (@Fitree.trigger (E +' G) (E +' F) _ _ (Sum.inr e)) =\n Fitree.trigger e := rfl\n\n-- The following theorems are only applied manually\n\ntheorem Fitree.run_bind {T R} (t: Fitree Void1 T) (k: T → Fitree Void1 R):\n run (bind t k) = run (k (run t)) :=\n match t with\n | Ret _ => rfl\n | Vis e _ => nomatch e\n\ntheorem Fitree.interp_bind:\n Fitree.interp h (Fitree.bind t k) =\n Fitree.bind (Fitree.interp h t) (fun x => Fitree.interp h (k x)) := by\n induction t with\n | Ret _ => rfl\n | Vis _ _ ih => simp [bind, ih]\n\ntheorem Fitree.interp'_bind:\n Fitree.interp' h (Fitree.bind t k) =\n Fitree.bind (Fitree.interp' h t) (fun x => Fitree.interp' h (k x)) := by\n simp [interp', interp_bind]\n\n-- Specialized interp_bind lemmas that unfold the monadic structure and expose\n-- the Fitree.bind directly rather than the monadic Bind.bind\n\ntheorem Fitree.interpState_bind (h: E ~> StateT S (Fitree F)) (t: Fitree E R):\n Fitree.interpState h (Fitree.bind t k) s =\n Fitree.bind (Fitree.interpState h t s)\n (fun (x,s') => Fitree.interpState h (k x) s') := by\n revert s\n induction t with\n | Ret _ => intros s; rfl\n | Vis _ _ ih =>\n simp [interpState] at *\n simp [interp, Bind.bind, StateT.bind]\n simp [ih]\n\nexample {F R}: WriterT (Fitree F) R = Fitree F (R × String) := by\n simp [WriterT]\n\ntheorem Fitree.interpWriter_bind (h: E ~> WriterT (Fitree F))\n (t: Fitree E T) (k: T → Fitree E R):\n Fitree.interpWriter h (Fitree.bind t k) =\n Fitree.bind (Fitree.interpWriter h t) fun (x,s₁) =>\n Fitree.bind (Fitree.interpWriter h (k x)) fun (y,s₂) =>\n Fitree.ret (y,s₁++s₂) := by\n induction t with\n | Ret _ =>\n simp [bind, interpWriter]\n have h₁: forall x, \"\" ++ x = x := by\n simp [HAppend.hAppend, Append.append, String.append]\n simp [List.nil_append]\n simp [h₁]\n have h₂: forall (α β: Type) (x: α × β), (x.fst, x.snd) = x := by simp\n simp [h₂]\n | Vis _ _ ih =>\n simp [interpWriter] at *\n simp [interp, Bind.bind, WriterT.bindCont, WriterT.mk]\n have h: forall (x y z: String), x ++ (y ++ z) = x ++ y ++ z := by\n simp [HAppend.hAppend, Append.append, String.append]\n simp [List.append_assoc]\n simp [ih, h]\n\ntheorem Fitree.interpOption_bind (h: E ~> OptionT (Fitree F))\n (t: Fitree E T) (k: T → Fitree E R):\n Fitree.interpOption h (Fitree.bind t k) =\n Fitree.bind (Fitree.interpOption h t) fun x? =>\n match x? with\n | some x => Fitree.interpOption h (k x)\n | none => Fitree.ret none := by\n induction t with\n | Ret _ => rfl\n | Vis _ _ ih =>\n simp [interpOption] at *\n simp [interp, bind, Bind.bind, OptionT.bind, OptionT.mk]\n -- I can't get a bind (match) → match (bind) theorem to rewrite, so...\n have fequal2 α β (f g: α → β) x y: f = g → x = y → f x = g y :=\n fun h₁ h₂ => by simp [h₁, h₂]\n apply fequal2; rfl; funext x\n cases x <;> simp [ih]\n\ntheorem Fitree.interpExcept_bind (h: E ~> ExceptT ε (Fitree F))\n (t: Fitree E T) (k: T → Fitree E R):\n Fitree.interpExcept h (Fitree.bind t k) =\n Fitree.bind (Fitree.interpExcept h t) fun x? =>\n match x? with\n | .error ε => Fitree.ret (.error ε)\n | .ok x => Fitree.interpExcept h (k x) := by\n induction t with\n | Ret _ => rfl\n | Vis _ _ ih =>\n simp [interpExcept] at *\n simp [interp, bind, Bind.bind]\n simp [ExceptT.bind, ExceptT.mk, ExceptT.bindCont]\n -- See above\n have fequal2 α β (f g: α → β) x y: f = g → x = y → f x = g y :=\n fun h₁ h₂ => by simp [h₁, h₂]\n apply fequal2; rfl; funext x\n cases x <;> simp [ih]\n\n-- This theorem has the drawback of hiding the continuation of `bind` into the\n-- `Vis` node, which blocks other theorems like `Fitree.bind_bind`.\ntheorem Fitree.bind_trigger [Member E F] (e: E T) (k: T → Fitree F R):\n Fitree.bind (Fitree.trigger e) k = Fitree.Vis (Member.inject _ e) k := rfl\n\n/-\n### Other properties\n-/\n\ninductive Fitree.noEventL {E F R}: Fitree (E +' F) R → Prop :=\n | Ret r: noEventL (Ret r)\n | Vis f k: (∀ t, noEventL (k t)) → noEventL (Vis (Sum.inr f) k)\n\n\nend Fitree\n\nnamespace Exp\n\n\n-- https://okmij.org/ftp/tagless-final/course/lecture.pdf\ninductive Exp where\n| Lit: Int -> Exp\n| Neg: Exp -> Exp\n| Add: Exp -> Exp -> Exp\n\ndef Exp.eval: Exp -> Int\n| .Lit i => i\n| .Neg e => -1 * e.eval\n| .Add e e' => e.eval + e'.eval\n\nclass ExpSYM (repr: Type) where\n lit: Int -> repr\n neg: repr -> repr\n add: repr -> repr -> repr\n -- neg_involutive: (a: repr) -> neg (neg a) = a\n\ninstance : ExpSYM Int where\n lit i := i\n neg i := (-i)\n add i j := i + j\n\ninstance : ExpSYM String where\n lit i := toString i\n neg i := s!\"(neg {i})\"\n add i i' := s!\"(add {i} {i'})\"\nend Exp\n\nnamespace Tree\ninductive Tree where\n| Leaf: String -> Tree\n| Node: String -> List Tree -> Tree\nderiving BEq\n\nopen Exp\n\n-- Serialize Exp into Tree\n\ninstance : ExpSYM Tree where\n lit n := .Node \"Lit\" [.Leaf (toString n)]\n neg e := .Node \"Neg\" [e]\n add e e' := .Node \"Add\" [e, e']\n\n\ndef fromTree {repr: Type} [ExpSYM repr] : Tree -> Except String repr\n| .Node \"Lit\" [.Leaf n] => do\n Except.ok (ExpSYM.lit 42) -- TODO: convert from string to nat.\n| .Node \"Neg\" [e] => do\n return (ExpSYM.neg (<- fromTree e))\n| .Node \"Add\" [e, e'] => do\n return ExpSYM.add (<- fromTree e) (<-\nfromTree e')\n| _t => Except.error \"incorrect tree\"\n\nend Tree\n\nnamespace PushNeg\nopen Exp\n\ndef Exp.pushNeg: Exp -> Exp\n| .Lit v => .Lit v\n| .Neg (.Lit v) => .Neg (.Lit v)\n| .Neg (.Neg e) => Exp.pushNeg e\n| .Neg (.Add e e') => .Add (Exp.pushNeg e) (Exp.pushNeg e')\n| .Add e e' => .Add (Exp.pushNeg e) (Exp.pushNeg e')\n\ninductive Ctx where\n| Pos: Ctx\n| Neg: Ctx\n\ninstance {repr: Type} [ExpSYM repr] : ExpSYM (Ctx -> repr) where\n lit n := fun ctx => match ctx with\n | .Pos => ExpSYM.lit n\n | .Neg => ExpSYM.neg (ExpSYM.lit n)\n neg e := fun ctx => match ctx with\n | .Pos => e .Neg\n | .Neg => e .Pos\n add e1 e2 := fun ctx => ExpSYM.add (e1 ctx) (e2 ctx)\nend PushNeg\n\nnamespace HO -- higher order tagless final\n\nclass Symantics (repr: Type -> Type) where\n int : Int -> repr Int\n add: repr Int -> repr Int -> repr Int\n lam: (repr a -> repr b) -> repr (a -> b)\n app: repr (a -> b) -> repr a -> repr b\n\nstructure R (a: Type) where\n val : a\n\ninstance : Symantics R where\n int i := { val := i }\n add i j := { val := i.val + j.val }\n lam f := { val := fun a => (f (R.mk a)).val }\n app f a := R.mk $ f.val a.val\n\nclass BoolSYM (repr: Type -> Type) where\n bool: Bool -> repr Bool\n leq : repr Int -> repr Int -> repr Bool\n if_: repr Bool -> repr a -> repr a -> repr a\n\ninstance : BoolSYM R where\n bool b := R.mk b\n leq a a' := R.mk (a.val <= a'.val)\n if_ cond t e := R.mk $ if cond.val then t.val else e.val\n\nclass FixSYM (repr: Type -> Type) where\n fix: (repr a -> repr a) -> repr a\n\n-- lol\npartial instance : FixSYM R where\n fix := sorry\n\n\n-- h is heaps\n\ninductive IR (h: Type _ -> Type _): Type _ -> Type _ where\n| int: Int -> IR h Int\n| add: IR h t -> IR h t -> IR h t\n| var: h t -> IR h t\n-- | lam: (IR h t1 -> IR h t2) -> IR h (t1 -> t2) -- non-positive occurence, cannot be encoded in initial style!\n\n\nend HO\n\n\n\nnamespace SSA\n/-\ninductive BB (repr: Type _ -> Type _ ): Type _ -> Type _ where\n| entry: String -> BB repr a -> BB repr a -- begin a bb\n| seq: BB repr a -> BB repr b -> BB repr b\n| op: repr a -> BB repr a -- operation\n| ret: repr a -> BB repr a -- only place where problem occurs.\n| condbr: repr Bool -> String -> String -> BB repr Unit\n| br: String -> BB repr Unit\n\n\nclass BBSemantics (repr: Type _ -> Type _) where\n bb: BB repr a -> repr a\n\nstructure R (a: Type) where\n val : a\n\n\ninstance : BBSemantics R where\n bb repr := match repr with\n | .entry name rest =>\n\n-/\n\ninductive Op: Type _ -> Type _ where\n| add: Int -> Int -> Op Int\n| lt: Int -> Int -> Op Bool\n| const: Int -> Op Int\n\nclass OpSYM (repr: Type -> Type) where\n add: Int -> Int -> repr Int\n lt: Int -> Int -> repr Bool\n const: Int -> repr Int\n\n\ninstance : OpSYM Op where\n add := .add\n lt := .lt\n const := .const\n\nstructure BBName where\n name: String\n\nstructure BBRef (a: Type _) where\n name: String\n\n-- class BBRefSYM (repr: Type -> Type) := String -> repr a\n\n-- Terminator has single type for interprocedural control flow.\n-- Inside and Outside\n-- k for things that are unknown, in the grand CPS style\n-- BB intra inter.\ninductive Terminator: Type _ -> Type _ where\n| br: BBRef i -> i -> Terminator Unit\n| ret: o -> Terminator o\n| condbr: Bool -> (BBRef i × i) -> (BBRef i' × i') -> Terminator Unit\n\nclass TerminatorSYM (repr: Type _ -> Type _) where\n br: BBRef i -> i -> repr Unit\n ret: o -> repr o\n condbr: Bool -> (BBRef i × i) -> (BBRef i' × i') -> repr Unit\n\ninstance : TerminatorSYM Terminator where\n br := .br\n ret := .ret\n condbr := .condbr\n\n-- BB has three two type: one for interprocedural control flow\n-- one for intraprocedural control flow\n-- Inside and Outside\n-- BB intra inter.\n-- BB \n-- O: type of ops\n-- T: type of terminators.\ninductive BB (O: Type _ -> Type _) (T: Type _ -> Type _): Type _ -> Type _ -> Type _ where\n| begin: (i -> BB O T Unit o) -> BB O T i o\n| seq: O a -> (a -> BB O T Unit o) -> BB O T Unit o\n| terminator: T o -> BB O T Unit o\n\nclass BBSYM (bbRepr: Type _ -> Type _ -> Type _)\n (opRepr: Type _ -> Type _)\n (terminatorRepr: Type _ -> Type _)\n extends OpSYM opRepr, TerminatorSYM terminatorRepr where\n begin: (i -> bbRepr Unit o) -> bbRepr i o\n seq: (opRepr a) -> (a -> bbRepr Unit o) -> bbRepr Unit o\n terminator: (terminatorRepr o) -> bbRepr Unit o\n\n-- instance of Symantics for BB.\ninstance [OpSYM O] [TerminatorSYM T]: BBSYM (BB O T) O T where\n begin := BB.begin\n seq := BB.seq\n terminator := BB.terminator\n\n\n-- build a BB which takes 'Int' input, produces 'Int' output.\ndef prog0 : BB Op Terminator Int Int :=\n .begin (fun input =>\n .seq (.const 4) (fun j =>\n .seq (.add input j) (fun k =>\n .terminator (.ret k)\n )))\n\n\nnamespace RegionBuilder\n-- Build a region\n-- The list of types is the labels that have been defined.\ninductive RegionBuilder\n (O: Type _ -> Type _)\n (T: Type _ -> Type _): List (Σ (i: Type), BBRef i) -> Type _ -> Type _ -> Type _ where\n| lbl: ((ref: BBRef i) ->\n RegionBuilder O T (⟨ i, ref ⟩::ris) ri ro) -- if you want a label,\n -> RegionBuilder O T ris ri ro -- I can then forget about the `i` and remember that the `is` have been defined\n -- you have an obligation to define it in the output\n| define: (ref: BBRef i) -> BB O T i o -> RegionBuilder O T ris ri ro\n -> RegionBuilder O T (⟨i,ref⟩::ris) ri ro -- define defines an `i`.\n| empty: RegionBuilder O T [] ri ro -- empty region defines no BBS.\n\ndef prog1: RegionBuilder Op Terminator [] Int Int :=\n .lbl (i := Int) (fun entry =>\n .define entry (.begin fun i =>\n .terminator (.ret i)\n ) .empty)\n\n-- takes an int as input, produces an int as output\n-- entry(input):\n-- br loop (input, 0)\n-- loop(i, k):\n-- knew := k + 1\n-- inew := i + 1\n-- exit := knew == 10\n-- condbr exit(inew), loop(inew, knew)\n-- exit(inew):\n-- ret inew\ndef prog2: RegionBuilder Op Terminator [] Int Int :=\n .lbl (i := Int) (fun entrybb =>\n .lbl (i := Int × Int) (fun loopbb =>\n .lbl (i := Int) (fun exitbb =>\n .define exitbb (.begin fun inew => .terminator (.ret inew)) $\n .define loopbb (.begin fun args =>\n .seq (.add 1 args.fst) (fun knew =>\n .seq (.add 1 args.snd) (fun inew =>\n .seq (.lt knew 10) (fun isExit =>\n -- .terminator (.ret knew)))) -- (.condbr isExit ⟨exitbb, inew⟩, ⟨loopbb, (inew, knew)⟩)))))\n .terminator (.condbr isExit (exitbb, inew) (loopbb, (inew, knew))))))\n ) $\n .define entrybb (.begin fun input =>\n .terminator (.br loopbb (input, 0))) $\n .empty)))\n#reduce prog2\nend RegionBuilder\n\nnamespace Region\n\nend Region\n\nend SSA\n\nnamespace StructuredSSA\n/-\nWe flatten Op, BasicBlock, Region into a single Def'.\nWe need three notions:\n(1) Running some semantic value (R), labelled by a label (L)\n(3) creating a new scope\n(2) invoking control flow (C) to a label (L)\n(2) sequentially composing two defs\n\n-/\n\ninductive Producer: Type -> Type where\ninductive Consumer: Type -> Type where\ninductive ProducerConsumer: Type -> Type -> Type where\n\n\n-- op: dataflow\n-- bb: ? (Ill defined concept)\n-- br, condbr: control flow.\n-- CFG: control flow\n\n-- backwards dataflow graph.\ninductive Dataflow (D: Type -> Type -> Type) (C: Type -> Type -> Type): Type _ -> Type _ where\n| val: O -> Dataflow D C O\n| df: D I O -> (I -> Dataflow D C O) -> Dataflow D C O\n\n-- forwards control flow graph.\ninductive Controlflow (D: Type -> Type -> Type) (C: Type -> Type -> Type): Type _ -> Type _ where\n| controldep: (I -> Dataflow D C O) -> Controlflow D C I -- Create phi nodes / control flow dependent values.\n| cf: C I BLANK /- instruction condbr in conbr b bb1, bb2 (I = Bool) -/\n -- -> (I -> Dataflow D C O' × Controlflow D C I') /- function that maps true ->bb1(x), false -> bb2(x), and shows how to produce (x, y) when mapping. -/\n -> (I -> Controlflow D C I') /- function that maps true ->bb1, false -> bb2 -/\n\ninductive Void where\n\nabbrev Unit2 (a: Type) := a\nabbrev Void2 (_a: Type) := Void\n\n\n\ninductive OpD : Type -> Type where -- tagged by output type\n| add: Int -> Int -> OpD Int\n| neg: Int -> OpD Int\n\nabbrev Op O := Dataflow OpD Void2 O\n\ninductive TerminatorC : Type -> Type where -- tagged by input type\n| br: TerminatorC Unit\n| condbr: TerminatorC Bool\n\n-- A basic block is obtained by taking the data flow of an Op and the control flow of a Terminator\nabbrev BasicBlock I := Controlflow OpD TerminatorC I\n\ninductive Adapt (D: Type -> Type _) (C: Type -> Type _): Type _ -> Type _\n| adapt: D O -> C I -> (O -> I) -> Adapt D C O\n\n-- A region adapts\nabbrev Region O := Adapt BasicBlock BasicBlock O\n\nend StructuredSSA\n\nnamespace PartialFunctionReasoning\n\n-- @[mlirdBy \"factorial\"]\nopaque factorial: Int -> Int\n-- axiom factorial_succ: ∀ (n: Nat), factorial (Int.ofNat (Nat.succ n))\naxiom factorial_rec: ∀ (i: Nat), factorial (Int.ofNat (Nat.succ i)) = (Nat.succ i) * factorial (Int.ofNat i)\naxiom factorial_zero: factorial (Int.ofNat 0) = 1\n\ndef terminating_factorial (n: Nat): Nat :=\n match n with\n | 0 => 1\n | n' + 1 => n * terminating_factorial n'\n\n#check Nat\ntheorem agree: forall (n: Nat), terminating_factorial n = factorial (.ofNat n) := by {\n intros n;\n induction n;\n case zero => {\n simp [factorial_zero, terminating_factorial];\n }\n case succ n H => {\n simp[terminating_factorial, H];\n simp[factorial_rec];\n rewrite [<- H];\n sorry\n }\n\n}\n\nend PartialFunctionReasoning\n\nnamespace PartialEvaluator\n-- Section 4.6\nend PartialEvaluator\n", "meta": {"author": "opencompl", "repo": "lean-mlir", "sha": "85fd61e38dec57e4d67d7af4d49a1ccc67828c1b", "save_path": "github-repos/lean/opencompl-lean-mlir", "path": "github-repos/lean/opencompl-lean-mlir/lean-mlir-85fd61e38dec57e4d67d7af4d49a1ccc67828c1b/experiment-reports/dialect-projection/DialectProjection/TypeclassSemantics.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.1645164792819756, "lm_q2_score": 0.03258974629287097, "lm_q1q2_score": 0.0053615503207959485}} {"text": "/-\nCopyright (c) 2021 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Sebastian Ullrich, Leonardo de Moura\n-/\nprelude\nimport Init.SimpLemmas\nimport Init.Control.Except\nimport Init.Control.StateRef\n\nopen Function\n\n@[simp] theorem monadLift_self [Monad m] (x : m α) : monadLift x = x :=\n rfl\n\nclass LawfulFunctor (f : Type u → Type v) [Functor f] : Prop where\n map_const : (Functor.mapConst : α → f β → f α) = Functor.map ∘ const β\n id_map (x : f α) : id <$> x = x\n comp_map (g : α → β) (h : β → γ) (x : f α) : (h ∘ g) <$> x = h <$> g <$> x\n\nexport LawfulFunctor (map_const id_map comp_map)\n\nattribute [simp] id_map\n\n@[simp] theorem id_map' [Functor m] [LawfulFunctor m] (x : m α) : (fun a => a) <$> x = x :=\n id_map x\n\nclass LawfulApplicative (f : Type u → Type v) [Applicative f] extends LawfulFunctor f : Prop where\n seqLeft_eq (x : f α) (y : f β) : x <* y = const β <$> x <*> y\n seqRight_eq (x : f α) (y : f β) : x *> y = const α id <$> x <*> y\n pure_seq (g : α → β) (x : f α) : pure g <*> x = g <$> x\n map_pure (g : α → β) (x : α) : g <$> (pure x : f α) = pure (g x)\n seq_pure {α β : Type u} (g : f (α → β)) (x : α) : g <*> pure x = (fun h => h x) <$> g\n seq_assoc {α β γ : Type u} (x : f α) (g : f (α → β)) (h : f (β → γ)) : h <*> (g <*> x) = ((@comp α β γ) <$> h) <*> g <*> x\n comp_map g h x := by\n repeat rw [← pure_seq]\n simp [seq_assoc, map_pure, seq_pure]\n\nexport LawfulApplicative (seqLeft_eq seqRight_eq pure_seq map_pure seq_pure seq_assoc)\n\nattribute [simp] map_pure seq_pure\n\n@[simp] theorem pure_id_seq [Applicative f] [LawfulApplicative f] (x : f α) : pure id <*> x = x := by\n simp [pure_seq]\n\nclass LawfulMonad (m : Type u → Type v) [Monad m] extends LawfulApplicative m : Prop where\n bind_pure_comp (f : α → β) (x : m α) : x >>= pure ∘ f = f <$> x\n bind_map {α β : Type u} (f : m (α → β)) (x : m α) : f >>= (. <$> x) = f <*> x\n pure_bind (x : α) (f : α → m β) : pure x >>= f = f x\n bind_assoc (x : m α) (f : α → m β) (g : β → m γ) : x >>= f >>= g = x >>= fun x => f x >>= g\n map_pure g x := by rw [← bind_pure_comp, pure_bind]\n seq_pure g x := by rw [← bind_map]; simp [map_pure, bind_pure_comp]\n seq_assoc x g h := by\n -- TODO: support for applying `symm` at `simp` arguments\n let bind_pure_comp_symm {α β : Type u} (f : α → β) (x : m α) : f <$> x = x >>= pure ∘ f := by\n rw [bind_pure_comp]\n let bind_map_symm {α β : Type u} (f : m (α → (β : Type u))) (x : m α) : f <*> x = f >>= (. <$> x) := by\n rw [bind_map]\n simp[bind_pure_comp_symm, bind_map_symm, bind_assoc, pure_bind]\n\nexport LawfulMonad (bind_pure_comp bind_map pure_bind bind_assoc)\nattribute [simp] pure_bind bind_assoc\n\n@[simp] theorem bind_pure [Monad m] [LawfulMonad m] (x : m α) : x >>= pure = x := by\n show x >>= pure ∘ id = x\n rw [bind_pure_comp, id_map]\n\ntheorem map_eq_pure_bind [Monad m] [LawfulMonad m] (f : α → β) (x : m α) : f <$> x = x >>= fun a => pure (f a) := by\n rw [← bind_pure_comp]\n\ntheorem seq_eq_bind_map {α β : Type u} [Monad m] [LawfulMonad m] (f : m (α → β)) (x : m α) : f <*> x = f >>= (. <$> x) := by\n rw [← bind_map]\n\ntheorem bind_congr [Bind m] {x : m α} {f g : α → m β} (h : ∀ a, f a = g a) : x >>= f = x >>= g := by\n simp [funext h]\n\n@[simp] theorem bind_pure_unit [Monad m] [LawfulMonad m] {x : m PUnit} : (x >>= fun _ => pure ⟨⟩) = x := by\n have : (x >>= fun _ => pure ⟨⟩) = (x >>= pure) := by\n apply bind_congr; intro u\n cases u; simp\n rw [bind_pure] at this\n assumption\n\ntheorem map_congr [Functor m] {x : m α} {f g : α → β} (h : ∀ a, f a = g a) : (f <$> x : m β) = g <$> x := by\n simp [funext h]\n\ntheorem seq_eq_bind {α β : Type u} [Monad m] [LawfulMonad m] (mf : m (α → β)) (x : m α) : mf <*> x = mf >>= fun f => f <$> x := by\n rw [bind_map]\n\ntheorem seqRight_eq_bind [Monad m] [LawfulMonad m] (x : m α) (y : m β) : x *> y = x >>= fun _ => y := by\n rw [seqRight_eq]; simp [map_eq_pure_bind, seq_eq_bind_map]\n\ntheorem seqLeft_eq_bind [Monad m] [LawfulMonad m] (x : m α) (y : m β) : x <* y = x >>= fun a => y >>= fun _ => pure a := by\n rw [seqLeft_eq]; simp [map_eq_pure_bind, seq_eq_bind_map]\n\n/- Id -/\n\nnamespace Id\n\n@[simp] theorem map_eq (x : Id α) (f : α → β) : f <$> x = f x := rfl\n@[simp] theorem bind_eq (x : Id α) (f : α → id β) : x >>= f = f x := rfl\n@[simp] theorem pure_eq (a : α) : (pure a : Id α) = a := rfl\n\ninstance : LawfulMonad Id := by\n refine' { .. } <;> intros <;> rfl\n\nend Id\n\n/- ExceptT -/\n\nnamespace ExceptT\n\ntheorem ext [Monad m] {x y : ExceptT ε m α} (h : x.run = y.run) : x = y := by\n simp [run] at h\n assumption\n\n@[simp] theorem run_pure [Monad m] : run (pure x : ExceptT ε m α) = pure (Except.ok x) := rfl\n\n@[simp] theorem run_lift [Monad m] (x : m α) : run (ExceptT.lift x : ExceptT ε m α) = (Except.ok <$> x : m (Except ε α)) := rfl\n\n@[simp] theorem run_throw [Monad m] : run (throw e : ExceptT ε m β) = pure (Except.error e) := rfl\n\n@[simp] theorem run_bind_lift [Monad m] [LawfulMonad m] (x : m α) (f : α → ExceptT ε m β) : run (ExceptT.lift x >>= f : ExceptT ε m β) = x >>= fun a => run (f a) := by\n simp[ExceptT.run, ExceptT.lift, bind, ExceptT.bind, ExceptT.mk, ExceptT.bindCont, map_eq_pure_bind]\n\n@[simp] theorem bind_throw [Monad m] [LawfulMonad m] (f : α → ExceptT ε m β) : (throw e >>= f) = throw e := by\n simp [throw, throwThe, MonadExceptOf.throw, bind, ExceptT.bind, ExceptT.bindCont, ExceptT.mk]\n\ntheorem run_bind [Monad m] (x : ExceptT ε m α)\n : run (x >>= f : ExceptT ε m β)\n =\n run x >>= fun\n | Except.ok x => run (f x)\n | Except.error e => pure (Except.error e) :=\n rfl\n\n@[simp] theorem lift_pure [Monad m] [LawfulMonad m] (a : α) : ExceptT.lift (pure a) = (pure a : ExceptT ε m α) := by\n simp [ExceptT.lift, pure, ExceptT.pure]\n\n@[simp] theorem run_map [Monad m] [LawfulMonad m] (f : α → β) (x : ExceptT ε m α)\n : (f <$> x).run = Except.map f <$> x.run := by\n simp [Functor.map, ExceptT.map, map_eq_pure_bind]\n apply bind_congr\n intro a; cases a <;> simp [Except.map]\n\nprotected theorem seq_eq {α β ε : Type u} [Monad m] (mf : ExceptT ε m (α → β)) (x : ExceptT ε m α) : mf <*> x = mf >>= fun f => f <$> x :=\n rfl\n\nprotected theorem bind_pure_comp [Monad m] [LawfulMonad m] (f : α → β) (x : ExceptT ε m α) : x >>= pure ∘ f = f <$> x := by\n intros; rfl\n\nprotected theorem seqLeft_eq {α β ε : Type u} {m : Type u → Type v} [Monad m] [LawfulMonad m] (x : ExceptT ε m α) (y : ExceptT ε m β) : x <* y = const β <$> x <*> y := by\n show (x >>= fun a => y >>= fun _ => pure a) = (const (α := α) β <$> x) >>= fun f => f <$> y\n rw [← ExceptT.bind_pure_comp]\n apply ext\n simp [run_bind]\n apply bind_congr\n intro\n | Except.error _ => simp\n | Except.ok _ =>\n simp [map_eq_pure_bind]; apply bind_congr; intro b;\n cases b <;> simp [comp, Except.map, const]\n\nprotected theorem seqRight_eq [Monad m] [LawfulMonad m] (x : ExceptT ε m α) (y : ExceptT ε m β) : x *> y = const α id <$> x <*> y := by\n show (x >>= fun _ => y) = (const α id <$> x) >>= fun f => f <$> y\n rw [← ExceptT.bind_pure_comp]\n apply ext\n simp [run_bind]\n apply bind_congr\n intro a; cases a <;> simp\n\ninstance [Monad m] [LawfulMonad m] : LawfulMonad (ExceptT ε m) where\n id_map := by intros; apply ext; simp\n map_const := by intros; rfl\n seqLeft_eq := ExceptT.seqLeft_eq\n seqRight_eq := ExceptT.seqRight_eq\n pure_seq := by intros; apply ext; simp [ExceptT.seq_eq, run_bind]\n bind_pure_comp := ExceptT.bind_pure_comp\n bind_map := by intros; rfl\n pure_bind := by intros; apply ext; simp [run_bind]\n bind_assoc := by intros; apply ext; simp [run_bind]; apply bind_congr; intro a; cases a <;> simp\n\nend ExceptT\n\n/- ReaderT -/\n\nnamespace ReaderT\n\ntheorem ext [Monad m] {x y : ReaderT ρ m α} (h : ∀ ctx, x.run ctx = y.run ctx) : x = y := by\n simp [run] at h\n exact funext h\n\n@[simp] theorem run_pure [Monad m] (a : α) (ctx : ρ) : (pure a : ReaderT ρ m α).run ctx = pure a := rfl\n\n@[simp] theorem run_bind [Monad m] (x : ReaderT ρ m α) (f : α → ReaderT ρ m β) (ctx : ρ)\n : (x >>= f).run ctx = x.run ctx >>= λ a => (f a).run ctx := rfl\n\n@[simp] theorem run_map [Monad m] (f : α → β) (x : ReaderT ρ m α) (ctx : ρ)\n : (f <$> x).run ctx = f <$> x.run ctx := rfl\n\n@[simp] theorem run_monadLift [MonadLiftT n m] (x : n α) (ctx : ρ)\n : (monadLift x : ReaderT ρ m α).run ctx = (monadLift x : m α) := rfl\n\n@[simp] theorem run_monadMap [Monad m] [MonadFunctor n m] (f : {β : Type u} → n β → n β) (x : ReaderT ρ m α) (ctx : ρ)\n : (monadMap @f x : ReaderT ρ m α).run ctx = monadMap @f (x.run ctx) := rfl\n\n@[simp] theorem run_read [Monad m] (ctx : ρ) : (ReaderT.read : ReaderT ρ m ρ).run ctx = pure ctx := rfl\n\n@[simp] theorem run_seq {α β : Type u} [Monad m] [LawfulMonad m] (f : ReaderT ρ m (α → β)) (x : ReaderT ρ m α) (ctx : ρ) : (f <*> x).run ctx = (f.run ctx <*> x.run ctx) := by\n rw [seq_eq_bind (m := m)]; rfl\n\n@[simp] theorem run_seqRight [Monad m] [LawfulMonad m] (x : ReaderT ρ m α) (y : ReaderT ρ m β) (ctx : ρ) : (x *> y).run ctx = (x.run ctx *> y.run ctx) := by\n rw [seqRight_eq_bind (m := m)]; rfl\n\n@[simp] theorem run_seqLeft [Monad m] [LawfulMonad m] (x : ReaderT ρ m α) (y : ReaderT ρ m β) (ctx : ρ) : (x <* y).run ctx = (x.run ctx <* y.run ctx) := by\n rw [seqLeft_eq_bind (m := m)]; rfl\n\ninstance [Monad m] [LawfulMonad m] : LawfulMonad (ReaderT ρ m) where\n id_map := by intros; apply ext; intros; simp\n map_const := by intros; rfl\n seqLeft_eq := by intros; apply ext; intros; simp; apply LawfulApplicative.seqLeft_eq\n seqRight_eq := by intros; apply ext; intros; simp; apply LawfulApplicative.seqRight_eq\n pure_seq := by intros; apply ext; intros; simp; apply LawfulApplicative.pure_seq\n bind_pure_comp := by intros; apply ext; intros; simp; apply LawfulMonad.bind_pure_comp\n bind_map := by intros; rfl\n pure_bind := by intros; apply ext; intros; simp\n bind_assoc := by intros; apply ext; intros; simp\n\nend ReaderT\n\n/- StateRefT -/\n\ninstance [Monad m] [LawfulMonad m] : LawfulMonad (StateRefT' ω σ m) :=\n inferInstanceAs (LawfulMonad (ReaderT (ST.Ref ω σ) m))\n\n/- StateT -/\n\nnamespace StateT\n\ntheorem ext {x y : StateT σ m α} (h : ∀ s, x.run s = y.run s) : x = y :=\n funext h\n\n@[simp] theorem run'_eq [Monad m] (x : StateT σ m α) (s : σ) : run' x s = (·.1) <$> run x s :=\n rfl\n\n@[simp] theorem run_pure [Monad m] (a : α) (s : σ) : (pure a : StateT σ m α).run s = pure (a, s) := rfl\n\n@[simp] theorem run_bind [Monad m] (x : StateT σ m α) (f : α → StateT σ m β) (s : σ)\n : (x >>= f).run s = x.run s >>= λ p => (f p.1).run p.2 := by\n simp [bind, StateT.bind, run]\n apply bind_congr\n intro p; cases p; rfl\n\n@[simp] theorem run_map {α β σ : Type u} [Monad m] [LawfulMonad m] (f : α → β) (x : StateT σ m α) (s : σ) : (f <$> x).run s = (fun (p : α × σ) => (f p.1, p.2)) <$> x.run s := by\n simp [Functor.map, StateT.map, run, map_eq_pure_bind]\n apply bind_congr\n intro p; cases p; rfl\n\n@[simp] theorem run_get [Monad m] (s : σ) : (get : StateT σ m σ).run s = pure (s, s) := rfl\n\n@[simp] theorem run_set [Monad m] (s s' : σ) : (set s' : StateT σ m PUnit).run s = pure (⟨⟩, s') := rfl\n\n@[simp] theorem run_modify [Monad m] (f : σ → σ) (s : σ) : (modify f : StateT σ m PUnit).run s = pure (⟨⟩, f s) := rfl\n\n@[simp] theorem run_modifyGet [Monad m] (f : σ → α × σ) (s : σ) : (modifyGet f : StateT σ m α).run s = pure ((f s).1, (f s).2) := by\n simp [modifyGet, MonadStateOf.modifyGet, StateT.modifyGet, run]; cases f s <;> rfl\n\n@[simp] theorem run_lift {α σ : Type u} [Monad m] (x : m α) (s : σ) : (StateT.lift x : StateT σ m α).run s = x >>= fun a => pure (a, s) := rfl\n\n@[simp] theorem run_bind_lift {α σ : Type u} [Monad m] [LawfulMonad m] (x : m α) (f : α → StateT σ m β) (s : σ) : (StateT.lift x >>= f).run s = x >>= fun a => (f a).run s := by\n simp [StateT.lift, StateT.run, bind, StateT.bind]\n\n@[simp] theorem run_monadLift {α σ : Type u} [Monad m] [MonadLiftT n m] (x : n α) (s : σ) : (monadLift x : StateT σ m α).run s = (monadLift x : m α) >>= fun a => pure (a, s) := rfl\n\n@[simp] theorem run_monadMap [Monad m] [MonadFunctor n m] (f : {β : Type u} → n β → n β) (x : StateT σ m α) (s : σ)\n : (monadMap @f x : StateT σ m α).run s = monadMap @f (x.run s) := rfl\n\n@[simp] theorem run_seq {α β σ : Type u} [Monad m] [LawfulMonad m] (f : StateT σ m (α → β)) (x : StateT σ m α) (s : σ) : (f <*> x).run s = (f.run s >>= fun fs => (fun (p : α × σ) => (fs.1 p.1, p.2)) <$> x.run fs.2) := by\n show (f >>= fun g => g <$> x).run s = _\n simp\n\n@[simp] theorem run_seqRight [Monad m] [LawfulMonad m] (x : StateT σ m α) (y : StateT σ m β) (s : σ) : (x *> y).run s = (x.run s >>= fun p => y.run p.2) := by\n show (x >>= fun _ => y).run s = _\n simp\n\n@[simp] theorem run_seqLeft {α β σ : Type u} [Monad m] [LawfulMonad m] (x : StateT σ m α) (y : StateT σ m β) (s : σ) : (x <* y).run s = (x.run s >>= fun p => y.run p.2 >>= fun p' => pure (p.1, p'.2)) := by\n show (x >>= fun a => y >>= fun _ => pure a).run s = _\n simp\n\ntheorem seqRight_eq [Monad m] [LawfulMonad m] (x : StateT σ m α) (y : StateT σ m β) : x *> y = const α id <$> x <*> y := by\n apply ext; intro s\n simp [map_eq_pure_bind]\n apply bind_congr; intro p; cases p\n simp [Prod.ext]\n\ntheorem seqLeft_eq [Monad m] [LawfulMonad m] (x : StateT σ m α) (y : StateT σ m β) : x <* y = const β <$> x <*> y := by\n apply ext; intro s\n simp [map_eq_pure_bind]\n\ninstance [Monad m] [LawfulMonad m] : LawfulMonad (StateT σ m) where\n id_map := by intros; apply ext; intros; simp[Prod.ext]\n map_const := by intros; rfl\n seqLeft_eq := seqLeft_eq\n seqRight_eq := seqRight_eq\n pure_seq := by intros; apply ext; intros; simp\n bind_pure_comp := by intros; apply ext; intros; simp; apply LawfulMonad.bind_pure_comp\n bind_map := by intros; rfl\n pure_bind := by intros; apply ext; intros; simp\n bind_assoc := by intros; apply ext; intros; simp\n\nend StateT\n", "meta": {"author": "gebner", "repo": "lean4-old", "sha": "ee51cdfaf63ee313c914d83264f91f414a0e3b6e", "save_path": "github-repos/lean/gebner-lean4-old", "path": "github-repos/lean/gebner-lean4-old/lean4-old-ee51cdfaf63ee313c914d83264f91f414a0e3b6e/stage0/src/Init/Control/Lawful.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.22541660542786954, "lm_q2_score": 0.0229773719171594, "lm_q1q2_score": 0.005179481179219731}} {"text": "/-\nCopyright (c) 2020 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Leonardo de Moura\n-/\nimport Lean.Meta.Transform\nimport Lean.Meta.Tactic.Replace\nimport Lean.Meta.Tactic.Util\nimport Lean.Meta.Tactic.Clear\nimport Lean.Meta.Tactic.Simp.Types\nimport Lean.Meta.Tactic.Simp.Rewrite\n\nnamespace Lean.Meta\nnamespace Simp\n\nbuiltin_initialize congrHypothesisExceptionId : InternalExceptionId ←\n registerInternalExceptionId `congrHypothesisFailed\n\ndef throwCongrHypothesisFailed : MetaM α :=\n throw <| Exception.internal congrHypothesisExceptionId\n\ndef Result.getProof (r : Result) : MetaM Expr := do\n match r.proof? with\n | some p => return p\n | none => mkEqRefl r.expr\n\nprivate def mkEqTrans (r₁ r₂ : Result) : MetaM Result := do\n match r₁.proof? with\n | none => return r₂\n | some p₁ => match r₂.proof? with\n | none => return { r₂ with proof? := r₁.proof? }\n | some p₂ => return { r₂ with proof? := (← Meta.mkEqTrans p₁ p₂) }\n\nprivate def mkCongrFun (r : Result) (a : Expr) : MetaM Result :=\n match r.proof? with\n | none => return { expr := mkApp r.expr a, proof? := none }\n | some h => return { expr := mkApp r.expr a, proof? := (← Meta.mkCongrFun h a) }\n\nprivate def mkCongr (r₁ r₂ : Result) : MetaM Result :=\n let e := mkApp r₁.expr r₂.expr\n match r₁.proof?, r₂.proof? with\n | none, none => return { expr := e, proof? := none }\n | some h, none => return { expr := e, proof? := (← Meta.mkCongrFun h r₂.expr) }\n | none, some h => return { expr := e, proof? := (← Meta.mkCongrArg r₁.expr h) }\n | some h₁, some h₂ => return { expr := e, proof? := (← Meta.mkCongr h₁ h₂) }\n\nprivate def mkImpCongr (r₁ r₂ : Result) : MetaM Result := do\n let e ← mkArrow r₁.expr r₂.expr\n match r₁.proof?, r₂.proof? with\n | none, none => return { expr := e, proof? := none }\n | _, _ => return { expr := e, proof? := (← Meta.mkImpCongr (← r₁.getProof) (← r₂.getProof)) } -- TODO specialize if bootleneck\n\nprivate def reduceProj (e : Expr) : MetaM Expr := do\n match (← reduceProj? e) with\n | some e => return e\n | _ => return e\n\nprivate def reduceProjFn? (e : Expr) : SimpM (Option Expr) := do\n matchConst e.getAppFn (fun _ => pure none) fun cinfo _ => do\n match (← getProjectionFnInfo? cinfo.name) with\n | none => return none\n | some projInfo =>\n if projInfo.fromClass then\n if (← read).simpLemmas.isDeclToUnfold cinfo.name then\n -- We only unfold class projections when the user explicitly requested them to be unfolded.\n -- Recall that `unfoldDefinition?` has support for unfolding this kind of projection.\n withReducibleAndInstances <| unfoldDefinition? e\n else\n return none\n else\n -- `structure` projection\n match (← unfoldDefinition? e) with\n | none => pure none\n | some e =>\n match (← reduceProj? e.getAppFn) with\n | some f => return some (mkAppN f e.getAppArgs)\n | none => return none\n\nprivate def reduceFVar (cfg : Config) (e : Expr) : MetaM Expr := do\n if cfg.zeta then\n match (← getFVarLocalDecl e).value? with\n | some v => return v\n | none => return e\n else\n return e\n\nprivate def unfold? (e : Expr) : SimpM (Option Expr) := do\n let f := e.getAppFn\n if !f.isConst then\n return none\n let fName := f.constName!\n if (← isProjectionFn fName) then\n return none -- should be reduced by `reduceProjFn?`\n if (← read).simpLemmas.isDeclToUnfold e.getAppFn.constName! then\n withDefault <| unfoldDefinition? e\n else\n return none\n\nprivate partial def reduce (e : Expr) : SimpM Expr := withIncRecDepth do\n let cfg := (← read).config\n if cfg.beta then\n let e' := e.headBeta\n if e' != e then\n return (← reduce e')\n -- TODO: eta reduction\n if cfg.proj then\n match (← reduceProjFn? e) with\n | some e => return (← reduce e)\n | none => pure ()\n if cfg.iota then\n match (← reduceRecMatcher? e) with\n | some e => return (← reduce e)\n | none => pure ()\n match (← unfold? e) with\n | some e => reduce e\n | none => return e\n\nprivate partial def dsimp (e : Expr) : M Expr := do\n transform e (post := fun e => return TransformStep.done (← reduce e))\n\npartial def simp (e : Expr) : M Result := withIncRecDepth do\n let cfg ← getConfig\n if (← isProof e) then\n return { expr := e }\n if cfg.memoize then\n if let some result := (← get).cache.find? e then\n return result\n simpLoop { expr := e }\n\nwhere\n simpLoop (r : Result) : M Result := do\n let cfg ← getConfig\n if (← get).numSteps > cfg.maxSteps then\n throwError \"simp failed, maximum number of steps exceeded\"\n else\n let init := r.expr\n modify fun s => { s with numSteps := s.numSteps + 1 }\n match (← pre r.expr) with\n | Step.done r => cacheResult cfg r\n | Step.visit r' =>\n let r ← mkEqTrans r r'\n let r ← mkEqTrans r (← simpStep r.expr)\n match (← post r.expr) with\n | Step.done r' => cacheResult cfg (← mkEqTrans r r')\n | Step.visit r' =>\n let r ← mkEqTrans r r'\n if cfg.singlePass || init == r.expr then\n cacheResult cfg r\n else\n simpLoop r\n\n simpStep (e : Expr) : M Result := do\n match e with\n | Expr.mdata _ e _ => simp e\n | Expr.proj .. => pure { expr := (← reduceProj e) }\n | Expr.app .. => simpApp e\n | Expr.lam .. => simpLambda e\n | Expr.forallE .. => simpForall e\n | Expr.letE .. => simpLet e\n | Expr.const .. => simpConst e\n | Expr.bvar .. => unreachable!\n | Expr.sort .. => pure { expr := e }\n | Expr.lit .. => pure { expr := e }\n | Expr.mvar .. => pure { expr := (← instantiateMVars e) }\n | Expr.fvar .. => pure { expr := (← reduceFVar (← getConfig) e) }\n\n congrDefault (e : Expr) : M Result :=\n withParent e <| e.withApp fun f args => do\n let infos := (← getFunInfoNArgs f args.size).paramInfo\n let mut r ← simp f\n let mut i := 0\n for arg in args do\n trace[Debug.Meta.Tactic.simp] \"app [{i}] {infos.size} {arg} hasFwdDeps: {infos[i].hasFwdDeps}\"\n if i < infos.size && !infos[i].hasFwdDeps then\n r ← mkCongr r (← simp arg)\n else if (← whnfD (← inferType r.expr)).isArrow then\n r ← mkCongr r (← simp arg)\n else\n r ← mkCongrFun r (← dsimp arg)\n i := i + 1\n return r\n\n /- Return true iff processing the given congruence lemma hypothesis produced a non-refl proof. -/\n processCongrHypothesis (h : Expr) : M Bool := do\n forallTelescopeReducing (← inferType h) fun xs hType => withNewLemmas xs do\n let lhs ← instantiateMVars hType.appFn!.appArg!\n let r ← simp lhs\n let rhs := hType.appArg!\n rhs.withApp fun m zs => do\n let val ← mkLambdaFVars zs r.expr\n unless (← isDefEq m val) do\n throwCongrHypothesisFailed\n unless (← isDefEq h (← mkLambdaFVars xs (← r.getProof))) do\n throwCongrHypothesisFailed\n return r.proof?.isSome\n\n /- Try to rewrite `e` children using the given congruence lemma -/\n tryCongrLemma? (c : CongrLemma) (e : Expr) : M (Option Result) := withNewMCtxDepth do\n trace[Debug.Meta.Tactic.simp.congr] \"{c.theoremName}, {e}\"\n let lemma ← mkConstWithFreshMVarLevels c.theoremName\n let (xs, bis, type) ← forallMetaTelescopeReducing (← inferType lemma)\n if c.hypothesesPos.any (· ≥ xs.size) then\n return none\n let lhs := type.appFn!.appArg!\n let rhs := type.appArg!\n if (← isDefEq lhs e) then\n let mut modified := false\n for i in c.hypothesesPos do\n let x := xs[i]\n try\n if (← processCongrHypothesis x) then\n modified := true\n catch _ =>\n trace[Meta.Tactic.simp.congr] \"processCongrHypothesis {c.theoremName} failed {← inferType x}\"\n return none\n unless modified do\n trace[Meta.Tactic.simp.congr] \"{c.theoremName} not modified\"\n return none\n unless (← synthesizeArgs c.theoremName xs bis (← read).discharge?) do\n trace[Meta.Tactic.simp.congr] \"{c.theoremName} synthesizeArgs failed\"\n return none\n let eNew ← instantiateMVars rhs\n let proof ← instantiateMVars (mkAppN lemma xs)\n return some { expr := eNew, proof? := proof }\n else\n return none\n\n congr (e : Expr) : M Result := do\n let f := e.getAppFn\n if f.isConst then\n let congrLemmas ← getCongrLemmas\n let cs := congrLemmas.get f.constName!\n for c in cs do\n match (← tryCongrLemma? c e) with\n | none => pure ()\n | some r => return r\n congrDefault e\n else\n congrDefault e\n\n simpApp (e : Expr) : M Result := do\n let e ← reduce e\n if !e.isApp then\n simp e\n else\n congr e\n\n simpConst (e : Expr) : M Result :=\n return { expr := (← reduce e) }\n\n withNewLemmas {α} (xs : Array Expr) (f : M α) : M α := do\n if (← getConfig).contextual then\n let mut s ← getSimpLemmas\n let mut updated := false\n for x in xs do\n if (← isProof x) then\n s ← s.add #[] x\n updated := true\n if updated then\n withSimpLemmas s f\n else\n f\n else\n f\n\n simpLambda (e : Expr) : M Result :=\n withParent e <| lambdaTelescope e fun xs e => withNewLemmas xs do\n let r ← simp e\n let eNew ← mkLambdaFVars xs r.expr\n match r.proof? with\n | none => return { expr := eNew }\n | some h =>\n let p ← xs.foldrM (init := h) fun x h => do\n mkFunExt (← mkLambdaFVars #[x] h)\n return { expr := eNew, proof? := p }\n\n simpArrow (e : Expr) : M Result := do\n trace[Debug.Meta.Tactic.simp] \"arrow {e}\"\n let p := e.bindingDomain!\n let q := e.bindingBody!\n let rp ← simp p\n trace[Debug.Meta.Tactic.simp] \"arrow [{(← getConfig).contextual}] {p} [{← isProp p}] -> {q} [{← isProp q}]\"\n if (← (← getConfig).contextual <&&> isProp p <&&> isProp q) then\n trace[Debug.Meta.Tactic.simp] \"ctx arrow {rp.expr} -> {q}\"\n withLocalDeclD e.bindingName! rp.expr fun h => do\n let s ← getSimpLemmas\n let s ← s.add #[] h\n withSimpLemmas s do\n let rq ← simp q\n match rq.proof? with\n | none => mkImpCongr rp rq\n | some hq =>\n let hq ← mkLambdaFVars #[h] hq\n return { expr := (← mkArrow rp.expr rq.expr), proof? := (← mkImpCongrCtx (← rp.getProof) hq) }\n else\n mkImpCongr rp (← simp q)\n\n simpForall (e : Expr) : M Result := withParent e do\n trace[Debug.Meta.Tactic.simp] \"forall {e}\"\n if e.isArrow then\n simpArrow e\n else if (← isProp e) then\n withLocalDecl e.bindingName! e.bindingInfo! e.bindingDomain! fun x => withNewLemmas #[x] do\n let b := e.bindingBody!.instantiate1 x\n let rb ← simp b\n let eNew ← mkForallFVars #[x] rb.expr\n match rb.proof? with\n | none => return { expr := eNew }\n | some h => return { expr := eNew, proof? := (← mkForallCongr (← mkLambdaFVars #[x] h)) }\n else\n return { expr := (← dsimp e) }\n\n simpLet (e : Expr) : M Result := do\n if (← getConfig).zeta then\n match e with\n | Expr.letE _ _ v b _ => return { expr := b.instantiate1 v }\n | _ => unreachable!\n else\n -- TODO: simplify nondependent let-decls\n return { expr := (← dsimp e) }\n\n cacheResult (cfg : Config) (r : Result) : M Result := do\n if cfg.memoize then\n modify fun s => { s with cache := s.cache.insert e r }\n return r\n\ndef main (e : Expr) (ctx : Context) (methods : Methods := {}) : MetaM Result := do\n withReducible do\n simp e methods ctx |>.run' {}\n\nnamespace DefaultMethods\nmutual\n partial def discharge? (e : Expr) : SimpM (Option Expr) := do\n let ctx ← read\n if ctx.dischargeDepth >= ctx.config.maxDischargeDepth then\n trace[Meta.Tactic.simp.discharge] \"maximum discharge depth has been reached\"\n return none\n else\n withReader (fun ctx => { ctx with dischargeDepth := ctx.dischargeDepth + 1 }) do\n let r ← simp e methods\n if r.expr.isConstOf ``True then\n try\n return some (← mkOfEqTrue (← r.getProof))\n catch _ =>\n return none\n else\n return none\n\n partial def pre (e : Expr) : SimpM Step :=\n preDefault e discharge?\n\n partial def post (e : Expr) : SimpM Step :=\n postDefault e discharge?\n\n partial def methods : Methods :=\n { pre := pre, post := post, discharge? := discharge? }\nend\nend DefaultMethods\n\nend Simp\n\ndef simp (e : Expr) (ctx : Simp.Context) : MetaM Simp.Result := do profileitM Exception \"simp\" (← getOptions) do\n Simp.main e ctx (methods := Simp.DefaultMethods.methods)\n\n/-- See `simpTarget`. This method assumes `mvarId` is not assigned, and we are already using `mvarId`s local context. -/\ndef simpTargetCore (mvarId : MVarId) (ctx : Simp.Context) : MetaM (Option MVarId) := do\n let target ← instantiateMVars (← getMVarType mvarId)\n let r ← simp target ctx\n if r.expr.isConstOf ``True then\n match r.proof? with\n | some proof => assignExprMVar mvarId (← mkOfEqTrue proof)\n | none => assignExprMVar mvarId (mkConst ``True.intro)\n return none\n else\n match r.proof? with\n | some proof => replaceTargetEq mvarId r.expr proof\n | none =>\n if target != r.expr then\n replaceTargetDefEq mvarId r.expr\n else\n return mvarId\n\n/--\n Simplify the given goal target (aka type). Return `none` if the goal was closed. Return `some mvarId'` otherwise,\n where `mvarId'` is the simplified new goal. -/\ndef simpTarget (mvarId : MVarId) (ctx : Simp.Context) : MetaM (Option MVarId) :=\n withMVarContext mvarId do\n checkNotAssigned mvarId `simp\n simpTargetCore mvarId ctx\n\n/--\n Simplify `prop` (which is inhabited by `proof`). Return `none` if the goal was closed. Return `some (proof', prop')`\n otherwise, where `proof' : prop'` and `prop'` is the simplified `prop`.\n\n This method assumes `mvarId` is not assigned, and we are already using `mvarId`s local context. -/\ndef simpStep (mvarId : MVarId) (proof : Expr) (prop : Expr) (ctx : Simp.Context) : MetaM (Option (Expr × Expr)) := do\n let r ← simp prop ctx\n if r.expr.isConstOf ``False then\n match r.proof? with\n | some eqProof => assignExprMVar mvarId (← mkFalseElim (← getMVarType mvarId) (← mkEqMP eqProof proof))\n | none => assignExprMVar mvarId (← mkFalseElim (← getMVarType mvarId) proof)\n return none\n else\n match r.proof? with\n | some eqProof => return some ((← mkEqMP eqProof proof), r.expr)\n | none =>\n if r.expr != prop then\n return some ((← mkExpectedTypeHint proof r.expr), r.expr)\n else\n return some (proof, r.expr)\n\nend Lean.Meta\n", "meta": {"author": "gebner", "repo": "lean4-old", "sha": "ee51cdfaf63ee313c914d83264f91f414a0e3b6e", "save_path": "github-repos/lean/gebner-lean4-old", "path": "github-repos/lean/gebner-lean4-old/lean4-old-ee51cdfaf63ee313c914d83264f91f414a0e3b6e/stage0/src/Lean/Meta/Tactic/Simp/Main.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.21206880435710532, "lm_q2_score": 0.024423089610302155, "lm_q1q2_score": 0.005179375412363219}} {"text": "import .util\n\nmeta def unwrap_lm_response (ident : option string) : json → tactic (list string)\n| (json.array $ tactic_strings) := do\n result ← tactic_strings.mmap $ lift_option ∘ json.get_string,\n pure result\n| exc := tactic.fail format!\"{ident.get_or_else \\\"[unwrap_lm_response.anonymous]\\\"} run_best_beam_candidate UNEXPECTED: {exc}\"\n\nmeta def json_float_array_sum : json → option json\n| (json.array xs) := json.of_float <$> xs.mfoldr (λ msg acc, match msg with\n | (json.of_float val) := pure $ acc + val\n | (json.of_int val) := pure $ acc + native.float.of_int val\n | exc := none\n end) (0.0 : native.float)\n| exc := none\n\n-- WARNING(jesse, January 14 2021, 10:32 AM): instead of failing like `unwrap_lm_response`, this return an empty list when seeing an unexpected message\nmeta def unwrap_lm_response_logprobs (ident : option string) : json → tactic (list $ string × native.float)\n| (json.array $ [(json.array predictions), (json.array scores)]) := do {\n decoded_strings ← predictions.mmap $ lift_option ∘ json.get_string,\n decoded_scores ← scores.mmap $ lift_option ∘ json.get_float,\n pure $ list.zip decoded_strings decoded_scores\n}\n| exc := tactic.trace format!\"{ident.get_or_else \\\"[unwrap_lm_response_logprobs.anonymous]\\\"} run_best_beam_candidate UNEXPECTED: {exc}\" *> pure []\n\nsection json\n\n-- for debugging\n\nmeta def json.compare : Π (x y : json), bool\n| (json.of_string s) (json.of_string s') := s = s'\n| (json.of_int k) (json.of_int k') := k = k'\n| (json.of_float x) (json.of_float x') := x = x' -- might have to make this tt\n| (json.of_bool b) (json.of_bool b') := b = b'\n| (json.null) (json.null) := tt\n| (json.object kvs) (json.object kvs') := (list.zip kvs kvs').foldr\n (λ ⟨⟨k₁, v₁⟩, ⟨k₂, v₂⟩⟩ acc,\n json.compare k₁ k₂ && json.compare v₁ v₂ && acc) tt\n| (json.array args) (json.array args') := (list.zip args args').foldr\n (λ ⟨j₁, j₂⟩ acc, acc && json.compare j₁ j₂) tt\n| _ _ := ff\n\nmeta def json.to_raw_fmt : json → format\n| (json.of_string s) := format!\"(json.of_string \\\"{s}\\\")\"\n| (json.of_int k) := format!\"(json.of_int {k})\"\n| (json.of_float x) := format!\"(json.of_float {x})\"\n| (json.of_bool b) := format!\"(json.of_bool {b})\"\n| (json.null) := \"(json.null)\"\n| (json.object kvs) := let f : string × json → format :=\n (λ ⟨k,v⟩, json.to_raw_fmt k ++ \" : \" ++ json.to_raw_fmt v) in\n format!\"(json.object \" ++ format.join_using \" \" (f <$> kvs) ++ \")\"\n| (json.array args) := \"(json.array \" ++ format.join_using \" \" (json.to_raw_fmt <$> args) ++ \")\"\n\nend json\n\nsection derive_has_json\nsection has_to_tactic_json_name\nopen name\n\n-- meta def has_to_tactic_json_name_aux : name → json\n-- | anonymous := json.object $ [(\"constr\", json.of_string \"name.anonymous\"), (\"args\", json.array [])]\n-- | (mk_string str nm) := json.object $ [(\"constr\", json.of_string \"name.mk_string\"),\n-- (\"args\", json.array [json.of_string str, has_to_tactic_json_name_aux nm])]\n-- | (mk_numeral u nm) := json.object $ [(\"constr\", json.of_string \"name.mk_numeral\"),\n-- (\"args\", json.array [json.of_int (int.of_nat ∘ unsigned.to_nat $ u), has_to_tactic_json_name_aux nm])]\n\nmeta def has_to_tactic_json_name_aux : name → json\n| anonymous := json.array ∘ pure $ json.of_string \"name.anonymous\"\n| (mk_string str nm) := json.array $\n [json.of_string \"name.mk_string\", json.of_string str, has_to_tactic_json_name_aux nm]\n| (mk_numeral u nm) := json.array $\n [json.of_string \"name.mk_numeral\", json.of_int (int.of_nat u.to_nat), has_to_tactic_json_name_aux nm]\n\n -- json.object $ [(\"constr\", json.of_string \"name.mk_numeral\"),\n -- (\"args\", json.array [json.of_int (int.of_nat ∘ unsigned.to_nat $ u), has_to_tactic_json_name_aux nm])]\n\nmeta instance : has_to_tactic_json name :=\n⟨pure ∘ has_to_tactic_json_name_aux⟩\n\nend has_to_tactic_json_name\n\nsection has_from_json_name\n\n-- meta def has_from_json_name_aux : json → tactic name\n-- | arg@(json.object [(\"constr\", json.of_string c), (\"args\", json.array args)]) := do {\n-- tactic.trace format!\"GOT MATCH: {arg}\",\n-- match c with\n-- | \"name.anonymous\" := pure name.anonymous\n-- | \"name.mk_string\" := do {\n-- (str, nm_json) ← (do {\n-- [json.of_string str, nm_json] ← pure args,\n-- pure (str, nm_json)\n-- } <|> tactic.fail\n-- format!\"[has_from_json_name_aux.inner_match_1.mk_string] unexpected: {args}\"),\n-- name.mk_string str <$> has_from_json_name_aux nm_json\n-- }\n-- | \"name.mk_numeral\" := do {\n-- (u, nm_json) ← (do {\n-- [json.of_int u, nm_json] ← pure args,\n-- pure (u, nm_json)\n-- } <|> tactic.fail\n-- format!\"[has_from_json_name_aux.inner_match_1.mk_numeral] unexpected: {args}\"),\n-- name.mk_numeral (unsigned.of_nat ∘ int.to_nat $ u) <$> has_from_json_name_aux nm_json\n-- }\n-- | exc := tactic.fail format!\"[has_from_json_name_aux.inner_match_1] unexpected: {exc}\"\n-- end\n-- }\n-- | exc := tactic.fail format!\"[has_from_json_name_aux] unexpected: {exc}\"\n\nmeta def has_from_json_name_aux : json → tactic name\n| arg@(json.array (c::args)) := do {\n -- tactic.trace format!\"GOT MATCH: {arg}\",\n match c with\n | \"name.anonymous\" := pure name.anonymous\n | \"name.mk_string\" := do {\n (str, nm_json) ← (do {\n [json.of_string str, nm_json] ← pure args,\n pure (str, nm_json)\n } <|> tactic.fail\n format!\"[has_from_json_name_aux.inner_match_1.mk_string] unexpected: {args}\"),\n name.mk_string str <$> has_from_json_name_aux nm_json\n }\n | \"name.mk_numeral\" := do {\n (u, nm_json) ← (do {\n [json.of_int u, nm_json] ← pure args,\n pure (u, nm_json)\n } <|> tactic.fail\n format!\"[has_from_json_name_aux.inner_match_1.mk_numeral] unexpected: {args}\"),\n name.mk_numeral (unsigned.of_nat ∘ int.to_nat $ u) <$> has_from_json_name_aux nm_json\n }\n | exc := tactic.fail format!\"[has_from_json_name_aux.inner_match_1] unexpected: {exc}\"\n end\n}\n| exc := tactic.fail format!\"[has_from_json_name_aux] unexpected: {exc}\"\n\n\nmeta instance : has_from_json name :=\n⟨has_from_json_name_aux⟩\n\nend has_from_json_name\n\nopen tactic\nnamespace tactic\nnamespace interactive\n\nmeta def mk_to_tactic_json (type : name) : tactic unit := do {\n ls ← local_context,\n (x::_) ← tactic.intro_lst [`arg],\n et ← infer_type x,\n xs ← tactic.induction x,\n xs.mmap' $ λ ⟨c, args, _⟩, do\n (args', rec_call) ← args.mpartition $ λ e, do {e' ← tactic.to_expr ``(tactic json), bnot <$> e'.occurs <$> tactic.infer_type e},\n args'' ← args'.mmap (λ a, flip prod.mk a <$> (et.occurs <$> tactic.infer_type a)),\n let fn : list (bool × expr) → state_t (list expr) tactic (list expr) := λ args'', do {\n let pop : state_t (list expr) tactic (option expr) := do {\n xs ← get,\n match xs with\n | (a::as) := modify (λ _, as) *> pure (some a)\n | [] := pure none\n end\n },\n args''.mmap (λ ⟨b, a⟩, if b then do (some x) ← pop, pure x else state_t.lift $ do\n a_tp ← infer_type a,\n _inst ← mk_app ``has_to_tactic_json [a_tp] >>= mk_instance,\n tactic.to_expr ``(@has_to_tactic_json.to_tactic_json _ (%%_inst) %%a))\n },\n args''' ← prod.fst <$> (fn args'').run rec_call,\n\n\n c ← tactic.resolve_constant c,\n refine ``((λ (ys : list $ tactic json),\n (λ x, json.array [has_to_tactic_json_name_aux %%c,\n json.array x]) <$> ys.mmap id) _), -- lol\n args'''.mmap (λ e, refine ``(list.cons %%e _)),\n tactic.to_expr ``(([] : list (tactic json))) >>= tactic.exact\n}\n\nmeta def derive_has_to_tactic_json (pre : option name) : tactic unit := do {\n vs ← local_context,\n `(has_to_tactic_json %%f) ← target,\n env ← get_env,\n let n := f.get_app_fn.const_name,\n d ← get_decl n,\n refine ``( { to_tactic_json := _ } ),\n tgt ← target,\n extract_def (with_prefix pre n <.> \"to_tactic_json\") ff $ mk_to_tactic_json n\n}\n\nmeta def has_to_tactic_json_derive_handler' (nspace : option name := none) : derive_handler :=\nhigher_order_derive_handler ``has_to_tactic_json (derive_has_to_tactic_json nspace) [] nspace\n\n@[derive_handler]\nmeta def has_to_tactic_json_derive_handler : derive_handler :=\nguard_class ``has_to_tactic_json has_to_tactic_json_derive_handler'\n\nend interactive\nend tactic\nend derive_has_json\n\nsection derive_from_json\nopen tactic\nnamespace tactic\n\nnamespace interactive\n\nmeta def get_constr_and_args (arg : json) : option (string × list json) :=\nmatch arg with\n| (json.array [json.of_string c, json.array args]) := pure (c, args)\n| _ := none\nend\n\n-- meta def json_to_expr : Π (arg : json), tactic expr\n-- | (json.object [(\"constr\", nm_json), (\"args\", json.array args)]) := do {\n-- -- let c_nm := hacky_name_from_string c,\n-- c_nm ← (json_to_expr nm_json) >>= eval_expr name,\n-- constr ← mk_const c_nm,\n-- if args.length = 0 then do {\n-- tp ← tactic.infer_type constr,\n-- e_id ← to_expr ``(@id %%tp),\n-- pure $ e_id.mk_app [constr] -- ???????????????\n-- }\n-- else do\n-- constr.mk_app <$> (args.mmap json_to_expr)\n-- }\n-- | arg@(json.of_int k) := do { -- WARNING: this is a hack for now\n-- pure `(int.to_nat k)\n-- }\n-- | exc@(json.array $ x@(((json.of_string c))::rest)) := if (\"name\" < c) then do nm ← has_from_json_name_aux x, pure $ (by apply_instance : has_reflect name) nm else tactic.fail format!\"[json_to_expr.name] unexpected: {exc}\"\n-- -- | arg@(json.of_bool b) := do { -- WARNING: this is a hack for now\n-- -- pure `(tt)\n-- -- }\n-- -- -- TODO(jesse): as needed, built special built-in logic to handle constants\n-- -- -- TODO(jesse): use `resolve_name` on `nm` to get the `has_from_json` instance\n-- -- -- then make a recursive call with `json_to_expr`\n-- -- -- better yet, move this logic into `mk_from_json`\n\n-- -- | arg@(json.object [(\"builtin\", nm_json), (\"val\", val_json)]) := do {\n-- -- env ← get_env,\n-- -- nm ← (has_from_json_name_aux nm_json),\n-- -- -- d ← env.get nm,\n-- -- ty_reflected ← declaration.type <$> get_decl nm,\n\n-- -- _inst ← to_expr ``(has_from_json %%nm) >>= mk_instance,\n-- -- _inst2 ← to_expr ``(has_reflect %%nm) >>= mk_instance,\n-- -- to_expr ``(has_from_json.from_json _ %%_inst %%arg)\n-- -- -- to_expr ``(has_from_json.from_json %%_inst $ %%arg)\n-- -- }\n-- | exc := tactic.fail format!\"[json_to_expr] unexpected: {exc}\"\n\nmeta def json_to_expr : Π (arg : json), tactic unit\n| (json.array $ [nm_json, json.array args]) := do {\n -- let c_nm := hacky_name_from_string c,\n c_nm ← (has_from_json_name_aux nm_json),\n constr ← mk_const c_nm,\n if args.length = 0 then do {\n tp ← tactic.infer_type constr,\n e_id ← to_expr ``(@id %%tp),\n tactic.apply (e_id.mk_app [constr]) *> pure ()\n }\n else do\n -- tactic.apply constr.mk_app <$> (args.mmap json_to_expr)\n tactic.apply constr,\n args.mmap' json_to_expr\n}\n| arg@(json.of_int k) := do { -- WARNING: this is a hack for now\n tactic.exact `(int.to_nat k)\n}\n| exc@(json.array $ x@(((json.of_string c))::rest)) := if (\"name\" < c) then do nm ← has_from_json_name_aux x, tactic.exact ((by apply_instance : has_reflect name) nm) else tactic.fail format!\"[json_to_expr.name] unexpected: {exc}\"\n-- | arg@(json.of_bool b) := do { -- WARNING: this is a hack for now\n-- pure `(tt)\n-- }\n-- -- TODO(jesse): as needed, built special built-in logic to handle constants\n-- -- TODO(jesse): use `resolve_name` on `nm` to get the `has_from_json` instance\n-- -- then make a recursive call with `json_to_expr`\n-- -- better yet, move this logic into `mk_from_json`\n\n-- | arg@(json.object [(\"builtin\", nm_json), (\"val\", val_json)]) := do {\n-- env ← get_env,\n-- nm ← (has_from_json_name_aux nm_json),\n-- -- d ← env.get nm,\n-- ty_reflected ← declaration.type <$> get_decl nm,\n\n-- _inst ← to_expr ``(has_from_json %%nm) >>= mk_instance,\n-- _inst2 ← to_expr ``(has_reflect %%nm) >>= mk_instance,\n-- to_expr ``(has_from_json.from_json _ %%_inst %%arg)\n-- -- to_expr ``(has_from_json.from_json %%_inst $ %%arg)\n-- }\n| exc := tactic.fail format!\"[json_to_expr] unexpected: {exc}\"\n\n/- TODO(jesse): probably a better, recursive/lazy way of doing this -/\nmeta def mk_from_json (pre : option name) : tactic unit := do {\n (x::_) ← tactic.intro_lst [`_arg],\n real_tgt@`(tactic %%tgt) ← target,\n y ← to_expr ``(json_to_expr %%x),\n -- let real_tgt := ``(reflected $ tactic %%tgt),\n\n -- _ ← to_expr ``(do %%y >>= eval_expr unit),\n -- tactic.read >>= λ ts, tactic.trace format!\"TACTIC STATE AFTER EVAL: {ts}\",\n -- pure ()\n -- tac ← eval_expr (tactic unit) y,\n -- tac\n -- `(tactic %%tgt) ← target,\n -- -- y ← to_expr ``(@id (tactic %%tgt)) >>= (λ f, pure $ f.mk_app [y]),\n -- -- tactic.trace format!\"OK?: {y}\",\n -- -- tactic.unfreeze_local_instances,\n\n -- OK, i think this approach was the right one since `eval_expr` has type exactly `tactic alpha`\n -- although maybe we could also do... pure?\n -- before this line, y is a reflection of `json_to_expr %%x`, which returns an expr which is supposed to be the target\n -- to force this to evaluate, we turns this entire thing into a thing of type tactic tgt,\n\n -- result ← to_expr ``(do %%y >>= eval_expr %%tgt),\n gs ← tactic.get_goals,\n\n -- m ← tactic.mk_meta_var real_tgt,\n -- let m' := `([m]).to_expr,\n\n -- result ← to_expr ``(do %%y >>= eval_expr %%tgt),\n -- this doesn't work because `y` is just `json_to_expr %%x`, which contains the open variable `%%x`\n -- result ← to_expr ``(do %%y) >>= eval_expr expr,\n\n result ← to_expr ``(do try trivial, m ← mk_mvar, set_goals [m], %%y, tactic.get_assignment m >>= eval_expr %%tgt),\n tactic.exact result *> done\n -- (eval_expr json x) >>= json_to_expr\n}\n\n-- #check get_constr_and_args\n-- meta def mk_from_json (pre : option name) : tactic unit := do {\n-- (x::_) ← tactic.intro_lst [`_arg],\n-- let rec := `(pure () : tactic unit).to_expr,\n-- f ← to_expr ``(match (get_constr_and_args %%x) with\n-- | (some ⟨constr, args⟩) := %%rec\n-- | none := tactic.fail \"[mk_from_json] unexpected failure\"\n-- end),\n-- tactic.fail \"NYI\"\n\n-- -- (constr, args))\n-- }\n\nmeta def derive_has_from_json (pre : option name) : tactic unit := do {\n vs ← local_context,\n `(has_from_json %%f) ← target,\n env ← get_env,\n let n := f.get_app_fn.const_name,\n d ← get_decl n,\n refine ``( { from_json := _ } ),\n tgt ← target,\n let extract_def_nm := (with_prefix pre n <.> \"from_json\"),\n extract_def extract_def_nm ff $ mk_from_json n\n}\n\nmeta def has_from_json_derive_handler' (nspace : option name := none) : derive_handler :=\nhigher_order_derive_handler ``has_from_json (derive_has_from_json nspace) [] nspace\n\n@[derive_handler]\nmeta def has_from_json_derive_handler : derive_handler :=\nguard_class ``has_from_json has_from_json_derive_handler'\n\nend interactive\n\nend tactic\n\nend derive_from_json\n\nsection test\n\n-- @[derive [has_to_tactic_json, has_from_json]]\n\ninductive my_nat' : Type\n-- /- `(x : α)` -/\n-- | foo : DUH'\n-- /- `{x : α}` -/\n| bar : my_nat'\n| baz : my_nat' → my_nat'\n-- /- `⦃x:α⦄` -/\n-- | strict_implicit : DUH'\n-- /- `[x : α]`. Should be inferred with typeclass resolution. -/\n-- | inst_implicit : DUH'\n-- /- Auxiliary internal attribute used to mark local constants representing recursive functions\n-- in recursive equations and `match` statements. -/\n-- | aux_decl : DUH'\n\nattribute [derive has_to_tactic_json] my_nat'\nattribute [derive has_from_json] my_nat'\n\nattribute [derive [has_reflect]] my_nat\nattribute [derive [has_to_tactic_json]] my_nat\nattribute [derive [has_from_json]] my_nat\n\n-- run_cmd (has_to_tactic_json.to_tactic_json (my_nat.zero) >>= (has_from_json.from_json : json → tactic my_nat) >>= tactic.trace)\n\n-- meta instance : has_to_format my_nat :=\n-- ⟨λ x, match x with | my_nat.zero := \"my_nat.zero\" | (my_nat.succ x) := \"my_nat.succ \" ++ (by exact _match x) end⟩\n\n-- meta instance : has_from_json my_nat :=\n-- ⟨λ k,\n-- -- match k with\n-- -- | (json.object $ [(\"constr\", c), (\"args\", (json.array args))]) := do\n-- -- nm ← has_from_json_name_aux c,\n-- -- match nm with\n-- -- | `my_nat.zero := pure $ my_nat.zero\n-- -- | `my_nat.succ := my_nat.succ <$> begin dedup, exact _match args.head end\n-- -- | exc := tactic.fail format!\"unexpected constructor: {exc}\"\n-- -- end\n-- -- | exc := tactic.fail format!\"unexpected: {exc}\"\n-- -- end\n-- by do {tactic.interactive.json_to_expr begin exact k end >>= tactic.exact}\n-- ⟩\n\n-- run_cmd (has_to_tactic_json.to_tactic_json (my_nat.succ $ my_nat.succ $ my_nat.zero) >>= tactic.trace)\n\n-- run_cmd (has_to_tactic_json.to_tactic_json (my_nat.succ $ my_nat.succ $ my_nat.zero) >>= (has_from_json.from_json : json → tactic my_nat) >>= tactic.trace)\n\n@[derive [has_to_tactic_json, has_from_json]]\ninductive my_tree : Type\n| leaf : my_nat → my_tree\n| node : my_tree → my_tree → my_nat → my_tree\n\nmeta instance : has_to_format my_tree :=\n⟨λ t, match t with\n| (my_tree.leaf k) := format!\"(leaf {k})\"\n| (my_tree.node t₁ t₂ k) := by exact format!\"(node {_match t₁} {_match t₂} {k})\"\nend\n⟩\n\ndef example_tree : my_tree := my_tree.node (my_tree.leaf my_nat.zero) (my_tree.leaf my_nat.zero) my_nat.zero\n\n-- run_cmd (has_to_tactic_json.to_tactic_json example_tree >>= tactic.trace)\n-- run_cmd (has_to_tactic_json.to_tactic_json example_tree >>= (has_from_json.from_json : json → tactic my_tree) >>= tactic.trace)\nend test\n\nsection instances\n\n/-\nWARNING: derived `has_to_tactic_json` and `has_from_json` instances are not guaranteed to be inverses\nthis can be resolved by enforcing special logic in the `has_from_json` derive handler\n-/\n\n-- meta instance : has_to_tactic_json nat :=\n-- ⟨has_to_tactic_json.to_tactic_json ∘ int.of_nat⟩\n\n-- TODO(jesse): this is insane! write the special logic.\n-- attribute [derive [has_to_tactic_json, has_from_json]] nat\nmeta instance : has_to_tactic_json nat :=\n⟨pure ∘ json.of_int ∘ int.of_nat⟩\n\nattribute [derive has_from_json] nat -- handled by special logic in `mk_from_json`\n\n-- run_cmd (has_to_tactic_json.to_tactic_json 3 >>=\n-- λ x, tactic.trace x *> ((has_from_json.from_json : json → tactic ℕ) x >>= tactic.trace))\n\n-- meta instance : has_from_json nat :=\n-- ⟨λ msg,\n-- match msg with\n-- | (json.of_int (int.of_nat k)) := pure k\n-- | exc := tactic.fail format!\"[has_from_json_nat] unexpected: {exc}\"\n-- end\n-- ⟩\n\n-- meta instance : has_to_tactic_json unsigned :=\n-- ⟨has_to_tactic_json.to_tactic_json ∘ unsigned.to_nat⟩\n\nmeta instance : has_from_json unsigned :=\n⟨λ msg,\n match msg with\n | (json.of_int (int.of_nat k)) := pure $ unsigned.of_nat k\n | exc := tactic.fail format!\"[has_from_json_unsigned] unexpected: {exc}\"\n end\n⟩\n\nmeta instance has_to_tactic_json_list {α} [h : has_to_tactic_json α] : has_to_tactic_json (list α) :=\n⟨by mk_to_tactic_json name.anonymous⟩\nuniverse u\n-- meta instance has_from_json_list {α : Type u} [reflected α] [h : has_from_json α] : has_from_json (list α) :=\n-- ⟨by mk_from_json name.anonymous⟩\n-- set_option formatter.hide_full_terms false\n-- run_cmd (has_to_tactic_json.to_tactic_json [1,2] >>= λ x, tactic.trace x *> (has_from_json.from_json : json → tactic (list ℕ)) x)\n\nmeta instance has_from_json_list {α} [H : has_from_json α] : has_from_json (list α) :=\n⟨λ msg, do\nlet ⟨fn⟩ := H in\nmatch msg with\n| (json.array $ [c, json.array args]) := do\n c_nm ← has_from_json_name_aux c,\n if c_nm = `list.nil then pure [] else\n if c_nm = `list.cons then (::) <$> fn args.head <*> do x ← (args.nth 1), (by exact _match x) else\n tactic.fail format!\"[has_from_json_list] unexpected {msg}\"\n| exc := tactic.fail \"[has_from_json_list] unexpected {exc}\"\nend\n⟩\n\n-- run_cmd (has_to_tactic_json.to_tactic_json 2 >>= (has_from_json.from_json : json → tactic ℕ) >>= tactic.trace)\n\n-- run_cmd (has_to_tactic_json.to_tactic_json [1,2] >>= λ x, tactic.trace x *> (has_from_json_list.from_json : json → tactic (list ℕ)) x >>= tactic.trace)\n\nmeta instance has_to_tactic_json_option {α} [has_to_tactic_json α] : has_to_tactic_json (option α) :=\n⟨by mk_to_tactic_json name.anonymous⟩\n\nmeta instance has_from_json_option {α} [H : has_from_json α] : has_from_json (option α) :=\n⟨λ msg, do\nlet ⟨fn⟩ := H in\nmatch msg with\n| (json.array $ [c, json.array args]) := do\n c_nm ← has_from_json_name_aux c,\n if c_nm = `option.none then pure none else\n if c_nm = `option.some then option.some <$> fn args.head else\n tactic.fail format!\"[has_from_json_option] unexpected {msg}\"\n| exc := tactic.fail \"[has_from_json_option] unexpected {exc}\"\nend\n⟩\n\n-- run_cmd (has_to_tactic_json.to_tactic_json (some [1,2]) >>= λ x, tactic.trace x *> (has_from_json.from_json : json → tactic (option $ list ℕ)) x >>= tactic.trace) -- sweet\n\nmeta instance has_to_tactic_json_prod {α β} [has_to_tactic_json α] [has_to_tactic_json β] : has_to_tactic_json (α × β) :=\n⟨by mk_to_tactic_json name.anonymous⟩\n\nmeta instance has_from_json_prod {α β : Type} [H : has_from_json α] [H' : has_from_json β] : has_from_json (prod α β) :=\n⟨λ msg, do\nlet ⟨fn₁⟩ := H in\nlet ⟨fn₂⟩ := H' in\nmatch msg with\n| (json.array $ [c, json.array args]) := do\n (c_nm : name) ← has_from_json_name_aux c,\n if c_nm = `prod.mk then prod.mk <$> (args.nth 0 >>= fn₁) <*> (args.nth 1 >>= fn₂) else\n tactic.fail format!\"[has_from_json_prod] unexpected {msg}\"\n| exc := tactic.fail \"[has_from_json_prod] unexpected {exc}\"\nend\n⟩\n\nattribute [derive [has_to_format]] binder_info\nattribute [derive [has_to_tactic_json, has_from_json, has_reflect]] level\nattribute [derive [has_to_tactic_json, has_from_json]] binder_info\n\nsection expr'\n\nmeta inductive expr'\n| var : nat → expr'\n| sort : level → expr'\n| const : name → list level → expr'\n| mvar (unique : name) (pretty : name) (type : expr') : expr'\n| local_const (unique : name) (pretty : name) (bi : binder_info) (type : expr') : expr'\n| app : expr' → expr' → expr'\n| lam (var_name : name) (bi : binder_info) (var_type : expr') (body : expr') : expr'\n| pi (var_name : name) (bi : binder_info) (var_type : expr') (body : expr') : expr'\n| elet (var_name : name) (type : expr') (assignment : expr') (body : expr') : expr'\n\nattribute [derive [has_to_tactic_json, has_from_json, has_reflect]] expr'\n\n-- #check (by apply_instance : has_from_json expr')\n\nattribute [derive [has_to_format]] expr'\n\nmeta def expr'.to_expr : expr' → expr\n| (expr'.var k) := expr.var k\n| (expr'.sort l) := (expr.sort l)\n| (expr'.const n ls) := (expr.const n ls)\n| (expr'.mvar un pr ty) := (expr.mvar un pr $ expr'.to_expr ty)\n| (expr'.local_const un pr bi ty) := (expr.local_const un pr bi $ expr'.to_expr ty)\n| (expr'.app e₁ e₂) := (expr.app (expr'.to_expr e₁) (expr'.to_expr e₂))\n| (expr'.lam nm bi tp body) := (expr.lam nm bi (expr'.to_expr tp) (expr'.to_expr body))\n| (expr'.pi nm bi tp body) := (expr.pi nm bi (expr'.to_expr tp) (expr'.to_expr body))\n| (expr'.elet nm tp assn body) := (expr.elet nm (expr'.to_expr tp) (expr'.to_expr assn) (expr'.to_expr body))\n\n-- meta def expr'.to_expr : expr' → tactic expr := λ x, tactic.trace \"CONVERTING TO EXPR\" *> (x.to_expr)\n\nmeta def expr.to_expr' : expr → tactic expr'\n| (expr.var k) := pure $ expr'.var k\n| (expr.sort l) := pure $ (expr'.sort l)\n| (expr.const n ls) := pure $ (expr'.const n ls)\n| (expr.mvar un pr ty) := (expr'.mvar un pr <$> expr.to_expr' ty)\n| (expr.local_const un pr bi ty) := (expr'.local_const un pr bi <$> expr.to_expr' ty)\n| (expr.app e₁ e₂) := (expr'.app <$> (expr.to_expr' e₁) <*> (expr.to_expr' e₂))\n| (expr.lam nm bi tp body) := (expr'.lam nm bi <$> (expr.to_expr' tp) <*> (expr.to_expr' body))\n| (expr.pi nm bi tp body) := (expr'.pi nm bi <$> (expr.to_expr' tp) <*> (expr.to_expr' body))\n| (expr.elet nm tp assn body) := (expr'.elet nm <$> (expr.to_expr' tp) <*> (expr.to_expr' assn) <*> (expr.to_expr' body))\n| (expr.macro md es) := tactic.fail \"[expr.to_expr'] no macros allowed!\"\n\n-- @[instance, priority 9000]\n-- meta def has_from_json_expr' : has_from_json expr' :=\n-- ⟨λ msg, match msg with\n-- | (json.object $ [(\"constr\", c), (\"args\", json.array args)]) := do\n-- (c_nm : name) ← has_from_json_name_aux c,\n-- -- tactic.trace \"NAME MSG:\" *> tactic.trace nm_msg,\n-- if c_nm = `expr'.const then do [nm_msg, levels_msg] ← pure args, result ← expr'.const <$> has_from_json_name_aux nm_msg <*> @has_from_json.from_json (list level) (by apply_instance : has_from_json (list level)) levels_msg, tactic.trace format!\"[has_from_json_expr'] RESULT: {result}\", result.to_expr.to_expr' else\n-- -- tactic.fail format!\"[has_from_json_expr'] unexpected: {msg}\"\n-- @has_from_json.from_json _ expr'.has_from_json msg\n-- | exc := tactic.fail format!\"[has_from_json_expr'] OH NO unexpected: {exc}\"\n-- end\n-- ⟩\n\nend expr'\n\nmeta instance : has_to_tactic_json expr :=\n⟨λ e, e.erase_annotations.to_expr' >>= has_to_tactic_json.to_tactic_json⟩\n\nmeta instance : has_from_json expr :=\n⟨λ msg, expr'.to_expr <$> (has_from_json.from_json : json → tactic expr') msg⟩\n\n-- run_cmd (has_to_tactic_json.to_tactic_json `(2).to_expr >>= tactic.trace) -- interesting\n\n-- #check expr\n-- open tactic.interactive\n\n-- run_cmd (has_to_tactic_json.to_tactic_json `foo.bar.baz >>= (λ x, tactic.trace x *> ((has_from_json.from_json : json → tactic name) x >>= tactic.trace)))\n\n-- private theorem foo {p q : Prop} : p → q → ∀ r, (p ∧ q) ∨ r :=\n-- λ h₁ h₂ h₃, or.inl (and.intro ‹_› ‹_›)\n\nmeta instance : has_to_tactic_json bool := ⟨λ b, pure ↑b⟩\nmeta instance : has_from_json bool := ⟨λ msg, match msg with\n| (json.of_bool b) := pure b\n| exc := tactic.fail format!\"[has_from_json_bool] unexpected: {exc}\"\nend\n⟩\n\nend instances\n-- #check tactic.set_env_core\n", "meta": {"author": "jesse-michael-han", "repo": "lean-tpe-public", "sha": "87c7bb8dfb8271d8fcf917aae0e731600c4f4c6c", "save_path": "github-repos/lean/jesse-michael-han-lean-tpe-public", "path": "github-repos/lean/jesse-michael-han-lean-tpe-public/lean-tpe-public-87c7bb8dfb8271d8fcf917aae0e731600c4f4c6c/src/utils/json.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.17781087819190097, "lm_q2_score": 0.02800751827346742, "lm_q1q2_score": 0.004980041420180956}} {"text": "import evaluation\nimport utils\n\nnamespace fairseq\n\nsection fairseq_api\n\nmeta structure CompletionRequest : Type :=\n(prompt : string)\n(max_tokens : int := 16)\n(temperature : native.float := 1.0)\n(nbest : int := 1)\n(beam: int := 10)\n\nmeta def default_partial_req : CompletionRequest :=\n{\n prompt := \"\",\n max_tokens := 6000,\n temperature := (1.0 : native.float),\n nbest := 1,\n beam := 10,\n}\n\n\n/-- this is responsible for validating parameters,\n e.g. ensuring floats are between 0 and 1 -/\nmeta instance : has_to_tactic_json CompletionRequest :=\nlet validate_max_tokens : int → bool := λ n, n ≤ 10000 in\nlet validate_float_frac : native.float → bool := λ k, 0 ≤ k ∧ k ≤ 1 in\nlet validate_and_return {α} (pred : α → bool) : α → tactic α := λ a, ((guard $ pred a) *> pure a <|> tactic.fail \"VALIDATE_AND_RETURN FAILED\") in\nlet validate_optional_and_return {α} (pred : α → bool) : option α → tactic (option α) := λ x, do {\n match x with\n | (some val) := some <$> validate_and_return pred val\n | none := pure none\n end\n} in\nlet fn : CompletionRequest → tactic json := λ req, match req with\n| ⟨prompt, max_tokens, temperature, nbest, beam⟩ := do\n max_tokens ← validate_and_return validate_max_tokens max_tokens,\n temperature ← validate_and_return validate_float_frac temperature,\n nbest ← validate_and_return (λ x, 0 ≤ x ∧ x ≤ (50 : int)) /- don't go overboard with the candidates -/ nbest,\n beam ← validate_and_return (λ x, 0 ≤ x ∧ x ≤ (50 : int)) /- don't go overboard with the candidates -/ beam,\n\n let pre_kvs : list (string × option json) := [\n (\"prompt\", json.of_string prompt),\n (\"max_tokens\", json.of_int max_tokens),\n (\"temperature\", json.of_float temperature),\n (\"nbest\", json.of_int nbest),\n (\"beam\", json.of_int beam)\n ],\n\n pure $ json.object $ pre_kvs.filter_map (λ ⟨k,mv⟩, prod.mk k <$> mv)\nend\nin ⟨fn⟩\n\nmeta def ENTRY_PT : string := \"/Users/Yuhuai/Documents/research/scatter_transformer_fairseq/fairseq_cli/query.py\"\nmeta def MODEL_PATH : string := \"/Users/Yuhuai/Documents/research/scatter_transformer_fairseq/lean_multigoal_checkpoints/checkpoint_best.pt\"\nmeta def DATA_PATH : string := \"/Users/Yuhuai/Documents/research/scatter_transformer_fairseq/datasets/LeanMultiGoalStepSPBPE4000Bin\"\n\nmeta def CompletionRequest.to_cmd (entry_pt: string) (model_path : string) (data_path : string) : CompletionRequest → io (io.process.spawn_args)\n| req@⟨prompt, max_tokens, temperature, nbest, beam⟩ := do\nserialized_req ← io.run_tactic' $ has_to_tactic_json.to_tactic_json req,\npure {\n cmd := \"python\",\n args := [\n entry_pt\n , data_path\n , \"--path\"\n , model_path\n , \"--sentencepiece-model\"\n , data_path ++ \"/model_4000_bpe.model\"\n , \"--json-msg\"\n , json.unparse serialized_req\n ]\n}\n\nmeta def serialize_ts\n (req : CompletionRequest)\n : tactic_state → tactic CompletionRequest := λ ts, do {\n ts_str ← postprocess_tactic_state ts, -- this function is responsible for replacing newlines with tabs and removing the \"k goals\" line\n let prompt : string :=\n ts_str,\n eval_trace format!\"\\n \\n \\n PROMPT: {prompt} \\n \\n \\n \",\n pure {\n prompt := prompt,\n ..req}\n}\n\nmeta def fairseq_api (entry_pt : string) (model_path : string) (data_path : string) : ModelAPI CompletionRequest :=\n\nlet get_predictions (response_msg : json) : option json :=\n(lift_option $ do\n { (json.array choices) ← response_msg.lookup \"choices\" | none,\n /- `choices` is a list of {text: ..., index: ..., logprobs: ..., finish_reason: ...}-/\n texts ← choices.mmap (λ choice, choice.lookup \"text\"),\n pure texts\n }) in\n\nlet fn : CompletionRequest → io json := λ req, do {\n proc_cmds ← req.to_cmd entry_pt model_path data_path,\n response_raw ← io.cmd proc_cmds,\n io.put_str_ln' format!\"RAW RESPONSE: {response_raw}\",\n response_msg ← (lift_option $ json.parse response_raw) | io.fail' format!\"[fairseq_api] JSON PARSE FAILED {response_raw}\",\n (do predictions ← lift_option (get_predictions response_msg) | io.fail' format!\"[fairseq_api] UNEXPECTED RESPONSE MSG: {response_msg}\",\n io.put_str_ln' format!\"PREDICTIONS: {predictions}\",\n pure predictions) <|> pure (json.array $ [json.of_string $ format.to_string $ format!\"ERROR {response_msg}\"])\n} in ⟨fn⟩\n\nend fairseq_api\n\nsection fairseq_greedy_proof_search\n\nmeta def fairseq_greedy_proof_search_core\n (partial_req : fairseq.CompletionRequest)\n (entry_pt : string)\n (model_path : string)\n (data_path : string)\n (fuel := 5)\n : state_t GreedyProofSearchState tactic unit :=\ngreedy_proof_search_core\n (fairseq_api entry_pt model_path data_path)\n (fairseq.serialize_ts partial_req)\n (λ msg n, run_best_beam_candidate (unwrap_lm_response $ some \"[fairseq_greedy_proof_search_core]\") msg n)\n (fuel)\n\nmeta def fairseq_greedy_proof_search\n (partial_req : fairseq.CompletionRequest)\n (entry_pt : string)\n (model_path : string)\n (data_path : string)\n (fuel := 5)\n (verbose := ff)\n : tactic unit :=\ngreedy_proof_search\n (fairseq_api entry_pt model_path data_path)\n (fairseq.serialize_ts partial_req)\n (λ msg n, run_best_beam_candidate (unwrap_lm_response $ some \"[fairseq_greedy_proof_search]\") msg n)\n (fuel)\n (verbose)\n\nend fairseq_greedy_proof_search\n\nsection test\n\n-- example : true :=\n-- begin\n-- trythis \"asdf\",\n-- sorry -- try using fairseq_greedy_proof_search here\n-- end\n\n-- example : true :=\n-- begin\n-- fairseq_greedy_proof_search {temperature :=1.0, nbest:=1, beam:=10, ..fairseq_api.default_partial_req}\n-- fairseq_api.ENTRY_PT\n-- fairseq_api.MODEL_PATH\n-- fairseq_api.DATA_PATH,\n-- end\n\n-- open nat\n-- example (n : ℕ) (m : ℕ) : nat.succ (n + m) = (nat.succ n + m) :=\n-- begin\n-- -- fairseq_greedy_proof_search {temperature :=0.7, nbest:=10, beam:=10, ..fairseq_api.default_partial_req}\n-- -- fairseq_api.ENTRY_PT\n-- -- fairseq_api.MODEL_PATH\n-- -- fairseq_api.DATA_PATH,\n-- end\n\n-- #eval fairseq_api.CompletionRequest.to_cmd {prompt := \"true\", nbest := 10, ..fairseq_api.default_partial_req} >>= io.cmd >>=io.put_str_ln\n-- #eval fairseq_api.CompletionRequest.to_cmd fairseq_api.default_partial_req >>= io.cmd >>= io.put_str_ln\n-- #eval io.cmd {cmd:=\"echo\", args:=[\"hello\"]} >>= io.put_str_ln\n-- #eval fairseq_api.serialize_ts fairseq_api.default_partial_req\nend test\n\nend fairseq\n", "meta": {"author": "jesse-michael-han", "repo": "lean-tpe-public", "sha": "87c7bb8dfb8271d8fcf917aae0e731600c4f4c6c", "save_path": "github-repos/lean/jesse-michael-han-lean-tpe-public", "path": "github-repos/lean/jesse-michael-han-lean-tpe-public/lean-tpe-public-87c7bb8dfb8271d8fcf917aae0e731600c4f4c6c/src/backends/greedy/fairseq.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.20434189993684584, "lm_q2_score": 0.022286185701570007, "lm_q1q2_score": 0.004554001528604183}} {"text": "/-\nCopyright (c) 2019 Simon Hudon. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\nAuthors: Simon Hudon\n\n! This file was ported from Lean 3 source module tactic.squeeze\n! leanprover-community/mathlib commit dff8393cf1d1fc152d148e13fe57452fc37d4852\n! Please do not edit these lines, except to modify the commit id\n! if you have ported upstream changes.\n-/\nimport Mathbin.Control.Traversable.Basic\nimport Mathbin.Tactic.Simpa\n\n/- ./././Mathport/Syntax/Translate/Tactic/Mathlib/Core.lean:38:34: unsupported: setup_tactic_parser -/\nprivate unsafe def loc.to_string_aux : Option Name → String\n | none => \"⊢\"\n | some x => toString x\n#align loc.to_string_aux loc.to_string_aux\n\n/-- pretty print a `loc` -/\nunsafe def loc.to_string : Loc → String\n | loc.ns [] => \"\"\n | loc.ns [none] => \"\"\n | loc.ns ls => String.join <| List.intersperse \" \" (\" at\" :: ls.map loc.to_string_aux)\n | loc.wildcard => \" at *\"\n#align loc.to_string loc.to_string\n\n/-- shift `pos` `n` columns to the left -/\nunsafe def pos.move_left (p : Pos) (n : ℕ) : Pos\n where\n line := p.line\n column := p.column - n\n#align pos.move_left pos.move_left\n\nnamespace Tactic\n\nderiving instance DecidableEq for simp_arg_type\n\n/-- Turn a `simp_arg_type` into a string. -/\nunsafe instance simp_arg_type.has_to_string : ToString simp_arg_type :=\n ⟨fun a =>\n match a with\n | simp_arg_type.all_hyps => \"*\"\n | simp_arg_type.except n => \"-\" ++ toString n\n | simp_arg_type.expr e => toString e\n | simp_arg_type.symm_expr e => \"←\" ++ toString e⟩\n#align tactic.simp_arg_type.has_to_string tactic.simp_arg_type.has_to_string\n\nopen List\n\n/-- parse structure instance of the shape `{ field1 := value1, .. , field2 := value2 }` -/\nunsafe def struct_inst : lean.parser pexpr :=\n with_desc \"cfg\" do\n tk \"{\"\n let ls ←\n sep_by (skip_info (tk \",\"))\n (Sum.inl <$> (tk \"..\" *> texpr) <|> Sum.inr <$> (Prod.mk <$> ident <* tk \":=\" <*> texpr))\n tk \"}\"\n let (srcs, fields) := partitionMap id ls\n let (names, values) := unzip fields\n pure <|\n pexpr.mk_structure_instance\n { field_names := names\n field_values := values\n sources := srcs }\n#align tactic.struct_inst tactic.struct_inst\n\n/-- pretty print structure instance -/\nunsafe def struct.to_tactic_format (e : pexpr) : tactic format := do\n let r ← e.get_structure_instance_info\n let fs ←\n zipWithM\n (fun n v => do\n let v ← to_expr v >>= pp\n pure <| f! \"{n } := {v}\")\n r.field_names r.field_values\n let ss := r.sources.map fun s => f! \" .. {s}\"\n let x : format := format.join <| List.intersperse \", \" (fs ++ ss)\n pure f! \" \\{{x}}}\"\n#align tactic.struct.to_tactic_format tactic.struct.to_tactic_format\n\n/-- Attribute containing a table that accumulates multiple `squeeze_simp` suggestions -/\n@[user_attribute]\nprivate unsafe def squeeze_loc_attr :\n user_attribute Unit (Option (List (Pos × String × List simp_arg_type × String)))\n where\n Name := `_squeeze_loc\n parser := fail \"this attribute should not be used\"\n descr := \"table to accumulate multiple `squeeze_simp` suggestions\"\n#align tactic.squeeze_loc_attr tactic.squeeze_loc_attr\n\n/-- dummy declaration used as target of `squeeze_loc` attribute -/\ndef squeezeLocAttrCarrier :=\n ()\n#align tactic.squeeze_loc_attr_carrier Tactic.squeezeLocAttrCarrier\n\nrun_cmd\n squeeze_loc_attr.Set `` squeeze_loc_attr_carrier none true\n\n/-- Format a list of arguments for use with `simp` and friends. This omits the\nlist entirely if it is empty.\n\nPatch: `pp` was changed to `to_string` because it was getting rid of prefixes\nthat would be necessary for some disambiguations. -/\nunsafe def render_simp_arg_list : List simp_arg_type → format\n | [] => \"\"\n | args => (· ++ ·) \" \" <| to_line_wrap_format <| args.map toString\n#align tactic.render_simp_arg_list tactic.render_simp_arg_list\n\n/-- Emit a suggestion to the user. If inside a `squeeze_scope` block,\nthe suggestions emitted through `mk_suggestion` will be aggregated so that\nevery tactic that makes a suggestion can consider multiple execution of the\nsame invocation.\nIf `at_pos` is true, make the suggestion at `p` instead of the current position. -/\nunsafe def mk_suggestion (p : Pos) (pre post : String) (args : List simp_arg_type)\n (at_pos := false) : tactic Unit := do\n let xs ← squeeze_loc_attr.get_param `` squeeze_loc_attr_carrier\n match xs with\n | none => do\n let args := render_simp_arg_list args\n if at_pos then\n @scopeTrace _ p p fun _ => _root_.trace (s! \"{pre }{args }{post}\") (pure () : tactic Unit)\n else trace s! \"{pre }{args }{post}\"\n | some xs => do\n squeeze_loc_attr `` squeeze_loc_attr_carrier ((p, pre, args, post) :: xs) ff\n#align tactic.mk_suggestion tactic.mk_suggestion\n\n/-- translate a `pexpr` into a `simp` configuration -/\nunsafe def parse_config : Option pexpr → tactic (simp_config_ext × format)\n | none => pure ({ }, \"\")\n | some cfg => do\n let e ← to_expr ``(($(cfg) : simp_config_ext))\n let fmt ← has_to_tactic_format.to_tactic_format cfg\n Prod.mk <$> eval_expr simp_config_ext e <*> struct.to_tactic_format cfg\n#align tactic.parse_config tactic.parse_config\n\n/-- translate a `pexpr` into a `dsimp` configuration -/\nunsafe def parse_dsimp_config : Option pexpr → tactic (DsimpConfig × format)\n | none => pure ({ }, \"\")\n | some cfg => do\n let e ← to_expr ``(($(cfg) : simp_config_ext))\n let fmt ← has_to_tactic_format.to_tactic_format cfg\n Prod.mk <$> eval_expr dsimp_config e <*> struct.to_tactic_format cfg\n#align tactic.parse_dsimp_config tactic.parse_dsimp_config\n\n/-- `same_result proof tac` runs tactic `tac` and checks if the proof\nproduced by `tac` is equivalent to `proof`. -/\nunsafe def same_result (pr : proof_state) (tac : tactic Unit) : tactic Bool := do\n let s ← get_proof_state_after tac\n pure <| some pr = s\n#align tactic.same_result tactic.same_result\n\n/-- Consumes the first list of `simp` arguments, accumulating required arguments\non the second one and unnecessary arguments on the third one.\n-/\nprivate unsafe def filter_simp_set_aux (tac : Bool → List simp_arg_type → tactic Unit)\n (args : List simp_arg_type) (pr : proof_state) :\n List simp_arg_type →\n List simp_arg_type → List simp_arg_type → tactic (List simp_arg_type × List simp_arg_type)\n | [], ys, ds => pure (ys, ds)\n | x :: xs, ys, ds => do\n let b ← same_result pr (tac true (args ++ xs ++ ys))\n if b then filter_simp_set_aux xs ys (ds x) else filter_simp_set_aux xs (ys x) ds\n#align tactic.filter_simp_set_aux tactic.filter_simp_set_aux\n\ninitialize\n registerTraceClass.1 `squeeze.deleted\n\n/-- `filter_simp_set g call_simp user_args simp_args` returns `args'` such that, when calling\n`call_simp tt /- only -/ args'` on the goal `g` (`g` is a meta var) we end up in the same\nstate as if we had called `call_simp ff (user_args ++ simp_args)` and removing any one\nelement of `args'` changes the resulting proof.\n-/\nunsafe def filter_simp_set (tac : Bool → List simp_arg_type → tactic Unit)\n (user_args simp_args : List simp_arg_type) : tactic (List simp_arg_type) := do\n let some s ← get_proof_state_after (tac false (user_args ++ simp_args))\n let (simp_args', _) ← filter_simp_set_aux tac user_args s simp_args [] []\n let (user_args', ds) ← filter_simp_set_aux tac simp_args' s user_args [] []\n when (is_trace_enabled_for `squeeze.deleted = tt ∧ ¬ds)\n (← do\n dbg_trace \"deleting provided arguments {← ds}\")\n pure (user_args' ++ simp_args')\n#align tactic.filter_simp_set tactic.filter_simp_set\n\n/-- make a `simp_arg_type` that references the name given as an argument -/\nunsafe def name.to_simp_args (n : Name) : simp_arg_type :=\n simp_arg_type.expr <| @expr.local_const false n n default pexpr.mk_placeholder\n#align tactic.name.to_simp_args tactic.name.to_simp_args\n\n/-- If the `name` is (likely) to be overloaded, then prepend a `_root_` on it. The `expr` of an\noverloaded name is constructed using `expr.macro`; this is how we guess whether it's overloaded. -/\nunsafe def prepend_root_if_needed (n : Name) : tactic Name := do\n let x ← resolve_name' n\n return <|\n match x with\n | expr.macro _ _ => `_root_ ++ n\n | _ => n\n#align tactic.prepend_root_if_needed tactic.prepend_root_if_needed\n\n/-- tactic combinator to create a `simp`-like tactic that minimizes its\nargument list.\n\n * `slow`: adds all rfl-lemmas from the environment to the initial list (this is a slower but more\n accurate strategy)\n * `no_dflt`: did the user use the `only` keyword?\n * `args`: list of `simp` arguments\n * `tac`: how to invoke the underlying `simp` tactic\n-/\nunsafe def squeeze_simp_core (slow no_dflt : Bool) (args : List simp_arg_type)\n (tac : ∀ (no_dflt : Bool) (args : List simp_arg_type), tactic Unit)\n (mk_suggestion : List simp_arg_type → tactic Unit) : tactic Unit := do\n let v ← target >>= mk_meta_var\n let args ←\n if slow then do\n let simp_set ← attribute.get_instances `simp\n let simp_set ← simp_set.filterM <| has_attribute' `_refl_lemma\n let simp_set ← simp_set.mapM <| resolve_name' >=> pure ∘ simp_arg_type.expr\n pure <| args ++ simp_set\n else pure args\n let g ←\n retrieve do\n let g ← main_goal\n tac no_dflt args\n instantiate_mvars g\n let vs := g.list_constant'\n let vs ← vs.filterM is_simp_lemma\n let vs ← vs.mapM strip_prefix\n let vs ← vs.mapM prepend_root_if_needed\n with_local_goals' [v] (filter_simp_set tac args <| vs name.to_simp_args) >>= mk_suggestion\n tac no_dflt args\n#align tactic.squeeze_simp_core tactic.squeeze_simp_core\n\nnamespace Interactive\n\n/-- combinator meant to aggregate the suggestions issued by multiple calls\nof `squeeze_simp` (due, for instance, to `;`).\n\nCan be used as:\n\n```lean\nexample {α β} (xs ys : list α) (f : α → β) :\n (xs ++ ys.tail).map f = xs.map f ∧ (xs.tail.map f).length = xs.length :=\nbegin\n have : xs = ys, admit,\n squeeze_scope\n { split; squeeze_simp,\n -- `squeeze_simp` is run twice, the first one requires\n -- `list.map_append` and the second one\n -- `[list.length_map, list.length_tail]`\n -- prints only one message and combine the suggestions:\n -- > Try this: simp only [list.length_map, list.length_tail, list.map_append]\n squeeze_simp [this]\n -- `squeeze_simp` is run only once\n -- prints:\n -- > Try this: simp only [this] },\nend\n```\n\n-/\nunsafe def squeeze_scope (tac : itactic) : tactic Unit := do\n let none ← squeeze_loc_attr.get_param `` squeeze_loc_attr_carrier |\n pure ()\n squeeze_loc_attr `` squeeze_loc_attr_carrier (some []) ff\n finally tac do\n let some xs ← squeeze_loc_attr `` squeeze_loc_attr_carrier |\n fail \"invalid state\"\n let m := native.rb_lmap.of_list xs\n squeeze_loc_attr `` squeeze_loc_attr_carrier none ff\n m fun ⟨p, suggs⟩ => do\n let ⟨pre, _, post⟩ := suggs\n let suggs : List (List simp_arg_type) := suggs <| Prod.fst ∘ Prod.snd\n mk_suggestion p pre post (suggs List.union []) tt\n pure ()\n#align tactic.interactive.squeeze_scope tactic.interactive.squeeze_scope\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:207:4: warning: unsupported notation `parser.optional -/\n/- ./././Mathport/Syntax/Translate/Expr.lean:207:4: warning: unsupported notation `parser.optional -/\n/- ./././Mathport/Syntax/Translate/Expr.lean:207:4: warning: unsupported notation `parser.optional -/\n/-- `squeeze_simp`, `squeeze_simpa` and `squeeze_dsimp` perform the same\ntask with the difference that `squeeze_simp` relates to `simp` while\n`squeeze_simpa` relates to `simpa` and `squeeze_dsimp` relates to\n`dsimp`. The following applies to `squeeze_simp`, `squeeze_simpa` and\n`squeeze_dsimp`.\n\n`squeeze_simp` behaves like `simp` (including all its arguments)\nand prints a `simp only` invocation to skip the search through the\n`simp` lemma list.\n\nFor instance, the following is easily solved with `simp`:\n\n```lean\nexample : 0 + 1 = 1 + 0 := by simp\n```\n\nTo guide the proof search and speed it up, we may replace `simp`\nwith `squeeze_simp`:\n\n```lean\nexample : 0 + 1 = 1 + 0 := by squeeze_simp\n-- prints:\n-- Try this: simp only [add_zero, eq_self_iff_true, zero_add]\n```\n\n`squeeze_simp` suggests a replacement which we can use instead of\n`squeeze_simp`.\n\n```lean\nexample : 0 + 1 = 1 + 0 := by simp only [add_zero, eq_self_iff_true, zero_add]\n```\n\n`squeeze_simp only` prints nothing as it already skips the `simp` list.\n\nThis tactic is useful for speeding up the compilation of a complete file.\nSteps:\n\n 1. search and replace ` simp` with ` squeeze_simp` (the space helps avoid the\n replacement of `simp` in `@[simp]`) throughout the file.\n 2. Starting at the beginning of the file, go to each printout in turn, copy\n the suggestion in place of `squeeze_simp`.\n 3. after all the suggestions were applied, search and replace `squeeze_simp` with\n `simp` to remove the occurrences of `squeeze_simp` that did not produce a suggestion.\n\nKnown limitation(s):\n * in cases where `squeeze_simp` is used after a `;` (e.g. `cases x; squeeze_simp`),\n `squeeze_simp` will produce as many suggestions as the number of goals it is applied to.\n It is likely that none of the suggestion is a good replacement but they can all be\n combined by concatenating their list of lemmas. `squeeze_scope` can be used to\n combine the suggestions: `by squeeze_scope { cases x; squeeze_simp }`\n * sometimes, `simp` lemmas are also `_refl_lemma` and they can be used without appearing in the\n resulting proof. `squeeze_simp` won't know to try that lemma unless it is called as\n `squeeze_simp?`\n-/\nunsafe def squeeze_simp (key : parse cur_pos) (slow_and_accurate : parse (parser.optional (tk \"?\")))\n (use_iota_eqn : parse (parser.optional (tk \"!\"))) (no_dflt : parse only_flag)\n (hs : parse simp_arg_list) (attr_names : parse with_ident_list) (locat : parse location)\n (cfg : parse (parser.optional struct_inst)) : tactic Unit := do\n let (cfg', c) ← parse_config cfg\n squeeze_simp_core slow_and_accurate no_dflt hs\n (fun l_no_dft l_args => simp use_iota_eqn none l_no_dft l_args attr_names locat cfg')\n fun args =>\n let use_iota_eqn := if use_iota_eqn then \"!\" else \"\"\n let attrs :=\n if attr_names then \"\"\n else String.join (List.intersperse \" \" (\" with\" :: attr_names toString))\n let loc := loc.to_string locat\n mk_suggestion (key 1) (s! \"Try this: simp{use_iota_eqn} only\") (s! \"{attrs }{loc }{c}\") args\n#align tactic.interactive.squeeze_simp tactic.interactive.squeeze_simp\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:207:4: warning: unsupported notation `parser.optional -/\n/- ./././Mathport/Syntax/Translate/Expr.lean:207:4: warning: unsupported notation `parser.optional -/\n/- ./././Mathport/Syntax/Translate/Expr.lean:207:4: warning: unsupported notation `parser.optional -/\n/- ./././Mathport/Syntax/Translate/Expr.lean:207:4: warning: unsupported notation `parser.optional -/\n/-- see `squeeze_simp` -/\nunsafe def squeeze_simpa (key : parse cur_pos)\n (slow_and_accurate : parse (parser.optional (tk \"?\")))\n (use_iota_eqn : parse (parser.optional (tk \"!\"))) (no_dflt : parse only_flag)\n (hs : parse simp_arg_list) (attr_names : parse with_ident_list)\n (tgt : parse (parser.optional (tk \"using\" *> texpr)))\n (cfg : parse (parser.optional struct_inst)) : tactic Unit := do\n let (cfg', c) ← parse_config cfg\n let tgt' ←\n traverse\n (fun t => do\n let t ← to_expr t >>= pp\n pure f! \" using {t}\")\n tgt\n squeeze_simp_core slow_and_accurate no_dflt hs\n (fun l_no_dft l_args => simpa use_iota_eqn none l_no_dft l_args attr_names tgt cfg')\n fun args =>\n let use_iota_eqn := if use_iota_eqn then \"!\" else \"\"\n let attrs :=\n if attr_names then \"\"\n else String.join (List.intersperse \" \" (\" with\" :: attr_names toString))\n let tgt' := tgt' \"\"\n mk_suggestion (key 1) (s! \"Try this: simpa{use_iota_eqn} only\") (s! \"{attrs }{tgt' }{c}\") args\n#align tactic.interactive.squeeze_simpa tactic.interactive.squeeze_simpa\n\n/- ./././Mathport/Syntax/Translate/Expr.lean:207:4: warning: unsupported notation `parser.optional -/\n/- ./././Mathport/Syntax/Translate/Expr.lean:207:4: warning: unsupported notation `parser.optional -/\n/- ./././Mathport/Syntax/Translate/Expr.lean:207:4: warning: unsupported notation `parser.optional -/\n/-- `squeeze_dsimp` behaves like `dsimp` (including all its arguments)\nand prints a `dsimp only` invocation to skip the search through the\n`simp` lemma list. See the doc string of `squeeze_simp` for examples.\n -/\nunsafe def squeeze_dsimp (key : parse cur_pos)\n (slow_and_accurate : parse (parser.optional (tk \"?\")))\n (use_iota_eqn : parse (parser.optional (tk \"!\"))) (no_dflt : parse only_flag)\n (hs : parse simp_arg_list) (attr_names : parse with_ident_list) (locat : parse location)\n (cfg : parse (parser.optional struct_inst)) : tactic Unit := do\n let (cfg', c) ← parse_dsimp_config cfg\n squeeze_simp_core slow_and_accurate no_dflt hs\n (fun l_no_dft l_args => dsimp l_no_dft l_args attr_names locat cfg') fun args =>\n let use_iota_eqn := if use_iota_eqn then \"!\" else \"\"\n let attrs :=\n if attr_names then \"\"\n else String.join (List.intersperse \" \" (\" with\" :: attr_names toString))\n let loc := loc.to_string locat\n mk_suggestion (key 1) (s! \"Try this: dsimp{use_iota_eqn} only\") (s! \"{attrs }{loc }{c}\") args\n#align tactic.interactive.squeeze_dsimp tactic.interactive.squeeze_dsimp\n\nend Interactive\n\nend Tactic\n\nopen Tactic.Interactive\n\nadd_tactic_doc\n { Name := \"squeeze_simp / squeeze_simpa / squeeze_dsimp / squeeze_scope\"\n category := DocCategory.tactic\n declNames := [`` squeeze_simp, `` squeeze_dsimp, `` squeeze_simpa, `` squeeze_scope]\n tags := [\"simplification\", \"Try this\"]\n inheritDescriptionFrom := `` squeeze_simp }\n\n", "meta": {"author": "leanprover-community", "repo": "mathlib3port", "sha": "62505aa236c58c8559783b16d33e30df3daa54f4", "save_path": "github-repos/lean/leanprover-community-mathlib3port", "path": "github-repos/lean/leanprover-community-mathlib3port/mathlib3port-62505aa236c58c8559783b16d33e30df3daa54f4/Mathbin/Tactic/Squeeze.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.17781086512112404, "lm_q2_score": 0.025178842660687827, "lm_q1q2_score": 0.004477071796245567}} {"text": "import Lean.Data.HashMap\nimport Lean.Data.HashSet\n\ninstance [BEq α] [Hashable α] [Repr α]: Repr (Lean.HashSet α) where\n reprPrec h n := h.toList.repr n\n\ninstance [BEq α] [Hashable α] [Repr (α × β)]: Repr (Lean.HashMap α β) where\n reprPrec h n := h.toList.repr n\n\nnamespace MWE1\n\ninductive «Entity» where\n | aspect\n (name: String)\n («specializations»: List String := List.nil)\n | concept\n (name: String)\n («specializations»: List String := List.nil)\n deriving Repr\n\ndef «Entity».name (e: «Entity»): String :=\n match e with\n | .aspect n _ => n\n | .concept n _ => n\n\ndef «Entity».«specializations» (e: «Entity»): List String :=\n match e with\n | .aspect _ s => s\n | .concept _ s => s\n\nclass «Vocabulary»where\n «ownedStatements»: List «Entity»\n deriving Repr\n\ndef v : «Vocabulary» := {\n ownedStatements := [\n «Entity».aspect \"base:Container\",\n «Entity».concept \"mission:Component\" [ \"base:Container\" ]\n ]\n}\n\ninductive RDeclarationKind where\n | rAspect\n | rConcept\n deriving BEq, Repr\n\ndef «Entity».toKind (e: «Entity»): RDeclarationKind :=\n match e with\n | .aspect _ _ => .rAspect\n | .concept _ _ => .rConcept\n\ninductive Exception where\n | error (message: String)\n deriving Repr\n\nabbrev Names := Lean.HashSet String\nabbrev Name2NamesMap := Lean.HashMap String Names\n\nstructure State where\n declarations : Lean.HashMap String RDeclarationKind := .empty\n aspectSpecializations : Name2NamesMap := .empty\n conceptSpecializations : Name2NamesMap := .empty\n deriving Repr\n\nstructure Context where\n vocabularies: List «Vocabulary» := .nil\n deriving Repr\n\nabbrev MCore := EStateM Exception State\nabbrev M := ReaderT Context MCore\n\ndef EStateM.Result.getState (r: EStateM.Result Exception State α): State :=\n match r with\n | EStateM.Result.ok _ s => s \n | _ => {}\n\ndef State.appendSpecializations\n (d: String) (dts: List RDeclarationKind)\n (ds: List String)\n (coll: State → Name2NamesMap)\n (update: State → String → Names → State)\n : M Unit := do\n let s ← get\n match s.declarations.find? d with\n | some k =>\n if dts.contains k then\n let rds : Names := (coll s).findD d .empty\n let merged : Names := ds.foldl .insert rds\n let s' : State := update s d merged\n set s'\n pure ()\n else\n throw (Exception.error s!\"Error: appendSpecializations: {repr d} is registered as a {repr k}, not one of {repr dts}.\")\n | none =>\n throw (Exception.error s!\"Error: appendSpecializations: there is no registered {repr dts}: {repr d} to append specializations to.\")\n\ndef State.updateAspectSpecializations (s: State) (d: String) (ds: Names): State :=\n { s with aspectSpecializations := s.aspectSpecializations.insert d ds }\n\ndef State.appendAspectSpecializations (a: String) (as: List String): M Unit := do\n appendSpecializations a [ .rAspect ] as State.aspectSpecializations State.updateAspectSpecializations\n\ndef State.updateConceptSpecializations (s: State) (d: String) (ds: Names): State :=\n { s with conceptSpecializations := s.conceptSpecializations.insert d ds }\n\ndef State.appendConceptSpecializations (c: String) (cs: List String): M Unit := do\n appendSpecializations c [ .rAspect, .rConcept ] cs State.conceptSpecializations State.updateConceptSpecializations\n\ndef validateStatementDeclaration (e: «Entity»): M Unit := do\n let s ← get\n match s.declarations.find? e.name with\n | some ek =>\n throw (Exception.error s!\"Error: declaration conflict: {repr e} is already registered as a {repr ek}.\")\n | none =>\n let s := { s with declarations := s.declarations.insert e.name e.toKind }\n set s\n pure ()\n\ndef validateVocabularyStatementDeclarations: M Unit := do\n for v in (← read).vocabularies do\n for e in v.ownedStatements do\n validateStatementDeclaration e\n\ndef validateVocabularySpecialization (e: «Entity»): M Unit := do\n let s ← get\n match s.declarations.find? e.name with \n | some ek =>\n if ek == e.toKind then\n match ek with\n | .rAspect =>\n State.appendAspectSpecializations e.name e.specializations\n | .rConcept =>\n State.appendConceptSpecializations e.name e.specializations\n else\n throw (Exception.error s!\"Error: declaration inconsistency: {repr e} is registered as a {repr ek}, not a {repr e.toKind}.\")\n | none =>\n pure ()\n \ndef validateVocabularySpecializations: M Unit := do\n for v in (← read).vocabularies do\n for e in v.ownedStatements do\n validateVocabularySpecialization e\n\ndef c0 : Context := { vocabularies := [v] }\n\ndef s0 : State := {}\n\ndef s1 : State := EStateM.Result.getState (validateVocabularyStatementDeclarations |>.run c0 |>.run s0)\n#eval s1\n-- { declarations := [(\"base:Container\", MWE.RDeclarationKind.rAspect),\n-- (\"mission:Component\", MWE.RDeclarationKind.rConcept)],\n-- aspectSpecializations := [],\n-- conceptSpecializations := [] }\n\n\ndef s2 : State := EStateM.Result.getState (validateVocabularySpecializations |>.run c0 |>.run s1)\n#eval s2\n-- { declarations := [(\"base:Container\", MWE.RDeclarationKind.rAspect),\n-- (\"mission:Component\", MWE.RDeclarationKind.rConcept)],\n-- aspectSpecializations := [(\"base:Container\", [])],\n-- conceptSpecializations := [(\"mission:Component\", [\"base:Container\"])] }\n\n-- All keys of the aspectSpecialization map must have a corresponding declaration as an rAspect\ntheorem AllAspectsSpecializationsKeysAreDeclared (s: State): \n ∀ a: String, s.aspectSpecializations.contains a → s.declarations.find? a == some .rAspect \n:= by\n sorry\n\n-- All values of the aspectSpecialization map must have a corresponding declaration as an rAspect\ntheorem AllAspectsSpecializationsValuesAreDeclared (s: State) : \n ∀ (a: String) (sup : String), (s.aspectSpecializations.findD a .empty).contains sup → s.declarations.find? sup == some .rAspect\n:= by\n sorry\n\n-- All keys of the conceptSpecializations map must have a corresponding declaration as an rConcept\ntheorem AllConceptSpecializationsKeysAreDeclared (s: State): \n ∀ a: String, s.conceptSpecializations.contains a → s.declarations.find? a == some .rConcept\n:= by\n sorry\n\n-- All values of the conceptSpecializations map must have a corresponding declaration as an rAspect or rConcept\ntheorem AllConceptSpecializationsValuesAreDeclared (s: State) : \n ∀ (a: String) (sup : String), (s.conceptSpecializations.findD a .empty).contains sup → \n s.declarations.find? sup == some .rAspect || s.declarations.find? sup == some .rConcept \n:= by\n sorry\nend MWE1", "meta": {"author": "NicolasRouquette", "repo": "oml.lean4", "sha": "a60689536837a52fe21595d79877063f28ec7cfc", "save_path": "github-repos/lean/NicolasRouquette-oml.lean4", "path": "github-repos/lean/NicolasRouquette-oml.lean4/oml.lean4-a60689536837a52fe21595d79877063f28ec7cfc/src/Oml/MWE1.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.23370635691404026, "lm_q2_score": 0.01615283538456014, "lm_q1q2_score": 0.0037750203115577514}} {"text": "import Lean\nimport Lean.Elab\nimport Lean.Meta\nimport Lean.Parser\nimport Lean.PrettyPrinter\nimport Lean.PrettyPrinter.Formatter\nimport MLIR.AST\nimport MLIR.Dialects.BuiltinModel\nimport Lean.Parser\nimport Lean.Parser.Extra\n\nopen Lean\nopen Lean.Parser\nopen Lean.Elab\nopen Lean.Meta\nopen Lean.Parser\nopen Lean.Parser.ParserState\nopen Lean.PrettyPrinter\nopen Lean.PrettyPrinter.Formatter\n\nopen MLIR.AST\n\nnamespace MLIR.EDSL\n\n\n-- | Custom parsers for balanced brackets\ninductive Bracket\n| Square -- []\n| Round -- ()\n| Curly -- {}\n| Angle -- <>\nderiving Inhabited, DecidableEq\n\ninstance : ToString Bracket where\n toString :=\n fun b =>\n match b with\n | .Square => \"[\"\n | .Round => \"(\"\n | .Curly => \"{\"\n | .Angle => \"<\"\n\n\n-- TODO: remove from quail\ndef isOpenBracket(c: Char): Option Bracket :=\nmatch c with\n| '(' => some .Round\n| '[' => some .Square\n| '{' => some .Curly\n| '<' => some .Angle\n| _ => none\n\ndef isCloseBracket(c: Char):Option Bracket :=\nmatch c with\n| ')' => some .Round\n| ']' => some .Square\n| '{' => some .Curly\n| '<' => some .Angle\n| _ => none\n\nmutual\n\n#check ParserState\n\n#check Format\n\n-- 'a -> symbol\n-- `a -> antiquotation `(... ,(...))\npartial def consumeCloseBracket(c: Bracket)\n (startPos: String.Pos)\n (i: String.Pos)\n (input: String)\n (brackets: List Bracket)\n (ctx: ParserContext)\n (s: ParserState): ParserState := Id.run do\n match brackets with\n | b::bs =>\n if b == c\n then\n if bs == []\n then\n let parser_fn := Lean.Parser.mkNodeToken `balanced_brackets startPos\n parser_fn ctx (s.setPos (input.next i)) -- consume the input here.\n else balancedBracketsFnAux startPos (input.next i) input bs ctx s\n else s.mkError $ \"| found Opened `\" ++ toString b ++ \"` expected to close at `\" ++ toString c ++ \"`\"\n | _ => s.mkError $ \"| found Closed `\" ++ toString c ++ \"`, but have no opened brackets on stack\"\n\n\npartial def balancedBracketsFnAux (startPos: String.Pos)\n (i: String.Pos)\n (input: String)\n (bs: List Bracket) (ctx: ParserContext) (s: ParserState): ParserState :=\n if input.atEnd i\n then s.mkError \"fonud EOF\"\n else\n match input.get i with\n -- opening parens\n | '(' => balancedBracketsFnAux startPos (input.next i) input (Bracket.Round::bs) ctx s\n | '[' => balancedBracketsFnAux startPos (input.next i) input (Bracket.Square::bs) ctx s\n | '<' => balancedBracketsFnAux startPos (input.next i) input (Bracket.Angle::bs) ctx s\n | '{' => balancedBracketsFnAux startPos (input.next i) input (Bracket.Curly::bs) ctx s\n -- closing parens\n | ')' => consumeCloseBracket Bracket.Round startPos i input bs ctx s\n | ']' => consumeCloseBracket Bracket.Square startPos i input bs ctx s\n | '>' => consumeCloseBracket Bracket.Angle startPos i input bs ctx s\n | '}' => consumeCloseBracket Bracket.Curly startPos i input bs ctx s\n | c => balancedBracketsFnAux startPos (input.next i) input bs ctx s\n\nend\n\n-- | TODO: filter tab complete by type?\ndef balancedBracketsFnEntry (ctx: ParserContext) (s: ParserState): ParserState :=\n if ctx.input.get s.pos == '<'\n then balancedBracketsFnAux\n (startPos := s.pos)\n (i := s.pos)\n (input := ctx.input)\n (bs := [])\n ctx s\n else s.mkError \"Expected '<'\"\n\n\n@[inline]\ndef balancedBrackets : Parser :=\n withAntiquot (mkAntiquot \"balancedBrackets\" `balancedBrackets) {\n fn := balancedBracketsFnEntry,\n info := mkAtomicInfo \"balancedBrackets\" : Parser\n }\n\n#check balancedBrackets\n\n\n-- Code stolen from test/WebServer/lean\n@[combinator_formatter MLIR.EDSL.balancedBrackets]\ndef MLIR.EDSL.balancedBrackets.formatter : Formatter := pure ()\n\n@[combinator_parenthesizer MLIR.EDSL.balancedBrackets]\ndef MLIR.EDSL.balancedBracketsParenthesizer : Parenthesizer := pure ()\n\n\nmacro \"[balanced_brackets|\" xs:balancedBrackets \"]\" : term => do\n match xs.raw[0] with\n | .atom _ val => return (Lean.quote val: TSyntax `str)\n | _ => Macro.throwError \"expected balanced bracts to have atom\"\n\n\ndef testBalancedBrackets : String := [balanced_brackets| < { xxasdasd } > ]\n#print testBalancedBrackets\n\n\n\n-- | positive and negative numbers, hex, octal\ndeclare_syntax_cat mlir_int\nsyntax numLit: mlir_int\n\ndef IntToString (i: Int): String := i.repr\n\ninstance : Quote Int := ⟨fun n => Syntax.mkNumLit <| n.repr⟩\n\ndef quoteMDimension (d: Dimension): MacroM Syntax :=\n match d with\n | Dimension.Known n => do\n `(Dimension.Known $(quote n))\n | Dimension.Unknown => `(Dimension.Unknown)\n\n\ndef quoteMList (k: List (TSyntax `term)) (ty: TSyntax `term): MacroM (TSyntax `term) :=\n match k with\n | [] => `(@List.nil $ty)\n | (k::ks) => do\n let sks <- quoteMList ks ty\n `($k :: $sks)\n\n\n-- AFFINE SYTAX\n-- ============\n\ndeclare_syntax_cat affine_expr\ndeclare_syntax_cat affine_tuple\ndeclare_syntax_cat affine_map\n\n\nsyntax ident : affine_expr\nsyntax \"(\" sepBy(affine_expr, \",\") \")\" : affine_tuple\nsyntax \"affine_map<\" affine_tuple \"->\" affine_tuple \">\" : affine_map\n\nsyntax \"[affine_expr|\" affine_expr \"]\" : term\nsyntax \"[affine_tuple|\" affine_tuple \"]\" : term\nsyntax \"[affine_map|\" affine_map \"]\" : term\n-- syntax \"[affine_map|\" affine_map \"]\" : term\n\nmacro_rules\n| `([affine_expr| $xraw:ident ]) => do\n let xstr := xraw.getId.toString\n `(AffineExpr.Var $(Lean.quote xstr))\n\nmacro_rules\n| `([affine_tuple| ( $xs,* ) ]) => do\n let initList <- `(@List.nil MLIR.AST.AffineExpr)\n let argsList <- xs.getElems.foldrM\n (init := initList)\n (fun x xs => `([affine_expr| $x] :: $xs))\n `(AffineTuple.mk $argsList)\n\n\nmacro_rules\n| `([affine_map| affine_map< $xs:affine_tuple -> $ys:affine_tuple >]) => do\n let xs' <- `([affine_tuple| $xs])\n let ys' <- `([affine_tuple| $ys])\n `(AffineMap.mk $xs' $ys' )\n\n\n-- EDSL\n-- ====\n\ndeclare_syntax_cat mlir_bb\ndeclare_syntax_cat mlir_region\ndeclare_syntax_cat mlir_op\ndeclare_syntax_cat mlir_op_args\ndeclare_syntax_cat mlir_op_successor_args\ndeclare_syntax_cat mlir_op_type\ndeclare_syntax_cat mlir_op_operand\ndeclare_syntax_cat mlir_ops\ndeclare_syntax_cat mlir_type\n\n-- syntax strLit mlir_op_args \":\" mlir_op_type : mlir_op -- no region\n--\n\n\n-- EDSL OPERANDS\n-- ==============\n\nsyntax \"%\" numLit : mlir_op_operand\n\nsyntax \"%\" ident : mlir_op_operand\n\nsyntax \"[mlir_op_operand|\" mlir_op_operand \"]\" : term\nmacro_rules\n | `([mlir_op_operand| $$($q)]) => return q\n | `([mlir_op_operand| % $x:ident]) => `(SSAVal.SSAVal $(Lean.quote (x.getId.toString)))\n | `([mlir_op_operand| % $n:num]) => `(SSAVal.SSAVal (IntToString $n))\n\ndef operand0 := [mlir_op_operand| %x]\n#print operand0\n\ndef operand1 := [mlir_op_operand| %x]\n#print operand1\n\ndef operand2 := [mlir_op_operand| %0]\n#print operand2\n\n\n-- EDSL OP-SUCCESSOR-ARGS\n-- =================\n\n-- successor-list ::= `[` successor (`,` successor)* `]`\n-- successor ::= caret-id (`:` bb-arg-list)?\n\ndeclare_syntax_cat mlir_op_successor_arg -- bb argument\nsyntax \"^\" ident : mlir_op_successor_arg -- bb argument with no operands\n-- syntax \"^\" ident \":\" \"(\" mlir_op_operand\",\"* \")\" : mlir_op_successor_arg\n\nsyntax \"[mlir_op_successor_arg|\" mlir_op_successor_arg \"]\" : term\n\nmacro_rules\n | `([mlir_op_successor_arg| ^ $x:ident ]) =>\n `(BBName.mk $(Lean.quote (x.getId.toString)))\n\ndef succ0 : BBName := ([mlir_op_successor_arg| ^bb])\n#print succ0\n\n\n-- EDSL MLIR TYPES\n-- ===============\n\n\nsyntax \"[mlir_type|\" mlir_type \"]\" : term\n\n-- TODO: Tuple and function types don't really exists (hardcoded Op notation)\n/-\n syntax \"(\" mlir_type,* \")\" : mlir_type\nmacro_rules\n| `([mlir_type| ( $xs,* )]) => do\n let xs <- xs.getElems.mapM (fun x => `([mlir_type| $x]))\n let x <- quoteMList xs.toList (<- `(MLIRType _))\n `(MLIRType.tuple $x)\n\n-- syntax \"(\" mlir_type \")\" : mlir_type\n-- syntax \"(\" mlir_type \",\" mlir_type \")\" : mlir_type\n-- | HACK: just switch to real parsing of lists\n-- syntax \"(\" mlir_type \",\" mlir_type \",\" mlir_type \")\" : mlir_type\nsyntax mlir_type \"->\" mlir_type : mlir_type\n-/\n\nsyntax \"{{\" term \"}}\" : mlir_type\nsyntax \"!\" str : mlir_type\nsyntax \"!\" ident : mlir_type\nsyntax ident: mlir_type\n\n\nset_option hygiene false in -- allow i to expand\nmacro_rules\n | `([mlir_type| $x:ident ]) => do\n let xstr := x.getId.toString\n if xstr == \"index\"\n then\n `(MLIRType.index)\n else if xstr.front == 'i' || xstr.front == 'f'\n then do\n let xstr' := xstr.drop 1\n match xstr'.toInt? with\n | some i =>\n let lit := Lean.Syntax.mkNumLit xstr'\n if xstr.front == 'i'\n then `(MLIRType.int .Signless $lit)\n else `(MLIRType.float $lit)\n | none =>\n Macro.throwError $ \"cannot convert suffix of i/f to int: \" ++ xstr\n else Macro.throwError $ \"expected i or f, found: \" ++ xstr\n\nmacro_rules\n| `([mlir_type| ! $x:str ]) => `(MLIRType.undefined $x)\n\nmacro_rules\n| `([mlir_type| ! $x:ident ]) => `(MLIRType.undefined $(Lean.quote x.getId.toString))\n\nmacro_rules\n | `([mlir_type| $$($q)]) => `($q)\n\ndef tyIndex : MLIRTy := [mlir_type| index]\n#eval tyIndex\n\ndef tyUser : MLIRTy := [mlir_type| !\"lz.int\"]\n#eval tyUser\n\ndef tyUserIdent : MLIRTy := [mlir_type| !shape.value]\n#eval tyUserIdent\n\n\ndef tyi32NoGap : MLIRTy := [mlir_type| i32]\n#eval tyi32NoGap\ndef tyf32NoGap : MLIRTy := [mlir_type| f32]\n#eval tyf32NoGap\n\nmacro_rules\n| `([mlir_type| {{ $t }} ]) => return t -- antiquot type\n\n-- #print tyi32'\n\n-- Uses dialect coercion empty → builtin\nexample : MLIRType builtin := [mlir_type| i32]\n\n-- Uses dialect coercion empty → empty + builtin\nexample : MLIRType (Dialect.empty + builtin) := [mlir_type| i32]\n-- More tricky: pushes coercion into the whole construction\n\n\n\n\ndeclare_syntax_cat mlir_dimension\n\nsyntax \"?\" : mlir_dimension\nsyntax num : mlir_dimension\n\nsyntax \"[mlir_dimension|\" mlir_dimension \"]\" : term\nmacro_rules\n| `([mlir_dimension| ?]) => `(Dimension.Unknown)\nmacro_rules\n| `([mlir_dimension| $x:num ]) =>\n `(Dimension.Known $x)\n\ndef dim0 := [mlir_dimension| 30]\n#print dim0\n\ndef dim1 := [mlir_dimension| ?]\n#print dim1\n\n\n-- | 1 x 2 x 3 x ..\ndeclare_syntax_cat mlir_dimension_list\nsyntax (mlir_dimension \"×\")* mlir_type : mlir_dimension_list\n\ndef string_to_dimension (s: String): MacroM Dimension := do\n if s == \"?\"\n then return Dimension.Unknown\n else if s.isNat\n then return Dimension.Known s.toNat!\n else Macro.throwError (\"unknown dimension: | \" ++ s ++ \" |\")\n\n\n-- (MLIR.EDSL.«mlir_dimension_list_×_»\n-- [\n-- [(MLIR.EDSL.mlir_dimension_ (numLit \"3\")) \"×\"]\n-- [(MLIR.EDSL.mlir_dimension_ (numLit \"3\")) \"×\"]]\n -- (MLIR.EDSL.mlir_type__ `i32))| )\n\n-- | TODO: assert that the string we get is of the form x3x4x?x2...\n-- that is, interleaved x and other stuff.\ndef parseTensorDimensionList (k: Syntax) : MacroM (TSyntax `term × TSyntax `term) := do\n\n let ty <- `([mlir_type| $(⟨k.getArgs.back⟩)])\n let dimensions := (k.getArg 0)\n let dimensions <- dimensions.getArgs.toList.mapM (fun x =>\n `([mlir_dimension| $(⟨x.getArg 0⟩)]))\n let dimensions <- quoteMList dimensions (<- `(MLIR.AST.Dimension))\n -- Macro.throwError $ (\"unknown dimension list:\\n|\" ++ (toString k.getArgs) ++ \"|\" ++ \"\\nDIMS: \" ++ (toString dimensions) ++ \" |\\nTYPE: \" ++ (toString ty)++ \"\")\n return (dimensions, ty)\n\n\n -- let xstr := dims.getId.toString\n -- let xparts := (xstr.splitOn \"x\").tail!\n -- let ty := xparts.getLast!\n -- let xparts := xparts.dropLast\n -- let xparts := [] ++ xparts -- TODO: add k into this list.\n -- -- Macro.throwError $ (\"unknown dimension list: |\" ++ (toString xparts) ++ \"| )\")\n\n -- let tyIdent := Lean.mkIdent ty\n -- -- let tyStx <- `([mlir_type| $(quote tyIdent)])\n -- let tyStx <- `([mlir_type| i32])\n -- let dims <- xparts.mapM string_to_dimension\n -- let dimsStx <- quoteMList ([k] ++ (<- dims.mapM quoteMDimension))\n -- return (dimsStx, tyStx)\n -- -- | err => Macro.throwError $ (\"unknown dimension list: |\" ++ err.reprint.getD \"???\" ++ \"| )\")\n\n-- === VECTOR TYPE ===\n-- TODO: where is vector type syntax defined?\n-- | TODO: fix bug that does not allow a trailing times.\n\n-- static-dim-list ::= decimal-literal (`x` decimal-literal)*\n-- | Encoding lookahead with notFollowedBy\ndeclare_syntax_cat static_dim_list\nsyntax sepBy(numLit, \"×\", \"×\" notFollowedBy(mlir_type <|> \"[\")) : static_dim_list\n\n\nsyntax \"[static_dim_list|\" static_dim_list \"]\" : term\nmacro_rules\n| `([static_dim_list| $[ $ns:num ]×* ]) => do\n quoteMList (ns.toList.map (⟨·.raw⟩)) (<- `(Nat))\n\n-- vector-dim-list := (static-dim-list `x`)? (`[` static-dim-list `]` `x`)?\ndeclare_syntax_cat vector_dim_list\nsyntax (static_dim_list \"×\" (\"[\" static_dim_list \"]\" \"×\")? )? : vector_dim_list\n-- vector-element-type ::= float-type | integer-type | index-type\n-- vector-type ::= `vector` `<` vector-dim-list vector-element-type `>`\nsyntax \"vector\" \"<\" vector_dim_list mlir_type \">\" : mlir_type\n\nset_option hygiene false in -- allow i to expand\nmacro_rules\n| `([mlir_type| vector < $[$fixed?:static_dim_list × $[ [ $scaled?:static_dim_list ] × ]? ]? $t:mlir_type >]) => do\n let fixedDims <- match fixed? with\n | some s => `([static_dim_list| $s])\n | none => `((@List.nil Nat))\n let scaledDims <- match scaled? with\n | some (some s) => `([static_dim_list| $s])\n | _ => `((@List.nil Nat))\n `(builtin.vector $fixedDims $scaledDims [mlir_type| $t])\n\ndef staticDimList0 : List Nat := [static_dim_list| 1]\n#reduce staticDimList0\n\ndef staticDimList1 : List Nat := [static_dim_list| 1 × 2]\n#reduce staticDimList1\n\n\n\ndef vectorTy0 := [mlir_type| vector]\n#print vectorTy0\n\ndef vectorTy1 := [mlir_type| vector<2 × i32>]\n#print vectorTy1\n\ndef vectorTy2 := [mlir_type| vector<2 × 3 × [ 4 ] × i32>]\n#print vectorTy2\n\n\n-- | TODO: is this actually necessary?\n-- syntax \"<\" mlir_dimension_list \">\" : mlir_type\n-- macro_rules\n-- | `([mlir_type| < $dims:mlir_dimension_list >]) => do\n-- let (dims, ty) <- parseTensorDimensionList dims\n-- `(MLIRType.vector $dims $ty)\n\n\n-- | TODO: fix bug that does not allow a trailing times.\n\nsyntax \"tensor\" \"<\" mlir_dimension_list \">\" : mlir_type\nmacro_rules\n| `([mlir_type| tensor < $dims:mlir_dimension_list >]) => do\n let (dims, ty) <- parseTensorDimensionList dims\n `(builtin.tensor $dims $ty)\n\n-- | TODO: this is a huge hack.\n-- | TODO: I should be able to use the lower level parser to parse this cleanly?\nsyntax \"tensor\" \"<\" \"*\" \"×\" mlir_type \">\" : mlir_type\nsyntax \"tensor\" \"<*\" \"×\" mlir_type \">\" : mlir_type\nsyntax \"tensor\" \"<*×\" mlir_type \">\" : mlir_type\n\nmacro_rules\n| `([mlir_type| tensor < *× $ty:mlir_type >]) => do\n `(builtin.tensor_unranked [mlir_type| $ty])\n\nmacro_rules\n| `([mlir_type| tensor < * × $ty:mlir_type >]) => do\n `(builtin.tensor_unranked [mlir_type| $ty])\n\nmacro_rules\n| `([mlir_type| tensor <* × $ty:mlir_type >]) => do\n `(builtin.tensor_unranked [mlir_type| $ty])\n\nmacro_rules\n| `([mlir_type| tensor <*×$ty:mlir_type >]) => do\n `(builtin.tensor_unranked [mlir_type| $ty])\n\n-- Automatically inferred as MLIRType builtin\ndef tensorTy0 := [mlir_type| tensor<3×3×i32>]\n#print tensorTy0\n\ndef tensorTy1 := [mlir_type| tensor< * × i32>]\n#print tensorTy1\n\ndef tensorTy2 := [mlir_type| tensor< * × f32>]\n#print tensorTy2\n\ndef tensorTy3 := [mlir_type| tensor<*× f32>]\n#print tensorTy3\n\ndef tensorTy4 := [mlir_type| tensor<* × f32>]\n#print tensorTy4\n\n-- Basic coercion builtin → builtin + empty\nexample : MLIRType (builtin + Dialect.empty) := [mlir_type| tensor<* × f32>]\n\n\nsyntax \"tensor1d\" : mlir_type\nmacro_rules\n| `([mlir_type| tensor1d ]) => do\n `(MLIRType.tensor1d)\n\ndef tensor1dTest : MLIRType empty := [mlir_type| tensor1d]\n\nsyntax \"tensor2d\" : mlir_type\nmacro_rules\n| `([mlir_type| tensor2d ]) => do\n `(MLIRType.tensor2d)\n\ndef tensor2dTest : MLIRType empty := [mlir_type| tensor2d]\n\n-- EDSL MLIR USER ATTRIBUTES\n-- =========================\n\n\n-- EDSL MLIR BASIC BLOCK OPERANDS\n-- ==============================\n\ndeclare_syntax_cat mlir_bb_operand\nsyntax mlir_op_operand \":\" mlir_type : mlir_bb_operand\n\nsyntax \"[mlir_bb_operand|\" mlir_bb_operand \"]\" : term\n\nmacro_rules\n| `([mlir_bb_operand| $name:mlir_op_operand : $ty:mlir_type ]) =>\n `( ([mlir_op_operand| $name], [mlir_type|$ty]) )\n\n\n\n-- EDSL MLIR BASIC BLOCKS\n-- ======================\n\n\n\n\nsyntax (mlir_op)* : mlir_ops\n\nsyntax \"[mlir_op|\" mlir_op \"]\" : term\nsyntax \"[mlir_ops|\" mlir_ops \"]\" : term\n\nmacro_rules\n| `([mlir_ops| $[ $ops ]* ]) => do\n let initList: TSyntax `term <- `(@List.nil (MLIR.AST.Op _))\n let l ← ops.foldrM (init := initList)\n fun x (xs: TSyntax `term) => `([mlir_op|$x] :: $xs)\n return l\n\nmacro_rules\n | `([mlir_ops| $$($q)]) => `(coe $q)\n\n\n\nsyntax \"{\" (\"^\" ident (\"(\" sepBy(mlir_bb_operand, \",\") \")\")? \":\")? mlir_ops \"}\" : mlir_region\nsyntax \"[mlir_region|\" mlir_region \"]\": term\n\nmacro_rules\n| `([mlir_region| { ^ $name:ident ( $operands,* ) : $ops } ]) => do\n let initList <- `(@List.nil (MLIR.AST.SSAVal × MLIR.AST.MLIRType _))\n let argsList <- operands.getElems.foldrM (init := initList) fun x xs => `([mlir_bb_operand| $x] :: $xs)\n let opsList <- `([mlir_ops| $ops])\n `(Region.mk $(Lean.quote (name.getId.toString)) $argsList $opsList)\n| `([mlir_region| { ^ $name:ident : $ops } ]) => do\n let opsList <- `([mlir_ops| $ops])\n `(Region.mk $(Lean.quote (name.getId.toString)) [] $opsList)\n| `([mlir_region| { $ops:mlir_ops } ]) => do\n let opsList <- `([mlir_ops| $ops])\n `(Region.mk \"entry\" [] $opsList)\n\n\nmacro_rules\n| `([mlir_region| $$($q) ]) => return q\n\n\n-- TENSOR LITERAL\n-- ==============\n\ndeclare_syntax_cat mlir_tensor\nsyntax numLit : mlir_tensor\nsyntax scientificLit : mlir_tensor\n\nsyntax \"[\" sepBy(mlir_tensor, \",\") \"]\" : mlir_tensor\n\nsyntax ident: mlir_tensor\nsyntax \"[mlir_tensor|\" mlir_tensor \"]\" : term\n\nmacro_rules\n| `([mlir_tensor| $x:num ]) => `(TensorElem.int $x)\n\nmacro_rules\n| `([mlir_tensor| $x:scientific ]) => `(TensorElem.float $(⟨x⟩))\n\nmacro_rules\n| `([mlir_tensor| $x:ident ]) => do\n let xstr := x.getId.toString\n if xstr == \"true\"\n then `(TensorElem.bool true)\n else if xstr == \"false\"\n then `(TensorElem.bool false)\n else Macro.throwError (\"unknown tensor value: |\" ++ xstr ++ \"|\")\n\nmacro_rules\n| `([mlir_tensor| [ $xs,* ] ]) => do\n let initList <- `([])\n let vals <- xs.getElems.foldlM (init := initList) fun xs x => `($xs ++ [[mlir_tensor| $x]])\n `(TensorElem.nested $vals)\n\n\ndef tensorValNum := [mlir_tensor| 42]\ndef tensorValFloat := [mlir_tensor| 0.000000]\ndef tensorValTrue := [mlir_tensor| true]\ndef tensorValFalse := [mlir_tensor| false]\n\n-- MLIR ATTRIBUTE VALUE\n-- ====================\n\n-- | TODO: consider renaming this to mlir_attr\ndeclare_syntax_cat mlir_attr_val\ndeclare_syntax_cat mlir_attr_val_symbol\nsyntax \"@\" ident : mlir_attr_val_symbol\nsyntax \"@\" str : mlir_attr_val_symbol\nsyntax \"#\" ident : mlir_attr_val -- alias\nsyntax \"#\" strLit : mlir_attr_val -- aliass\n\nsyntax \"#\" ident \"<\" strLit \">\" : mlir_attr_val -- opaqueAttr\nsyntax \"#opaque<\" ident \",\" strLit \">\" \":\" mlir_type : mlir_attr_val -- opaqueElementsAttr\nsyntax mlir_attr_val_symbol \"::\" mlir_attr_val_symbol : mlir_attr_val_symbol\n\n\ndeclare_syntax_cat balanced_parens -- syntax \"#\" ident \".\" ident \"<\" balanced_parens \">\" : mlir_attr_val -- generic user attributes\n\n\nsyntax str: mlir_attr_val\nsyntax mlir_type : mlir_attr_val\nsyntax affine_map : mlir_attr_val\nsyntax mlir_attr_val_symbol : mlir_attr_val\nsyntax \"-\"? num (\":\" mlir_type)? : mlir_attr_val\nsyntax scientificLit (\":\" mlir_type)? : mlir_attr_val\nsyntax ident: mlir_attr_val\n\nsyntax \"[\" sepBy(mlir_attr_val, \",\") \"]\" : mlir_attr_val\nsyntax \"[mlir_attr_val|\" mlir_attr_val \"]\" : term\nsyntax \"[mlir_attr_val_symbol|\" mlir_attr_val_symbol \"]\" : term\n\nmacro_rules\n| `([mlir_attr_val| $$($x) ]) => `($x)\n\nmacro_rules\n| `([mlir_attr_val| $x:num ]) => `(AttrValue.int $x (MLIRType.int .Signless 64))\n| `([mlir_attr_val| $x:num : $t:mlir_type]) => `(AttrValue.int $x [mlir_type| $t])\n| `([mlir_attr_val| - $x:num ]) => `(AttrValue.int (- $x) (MLIRType.int .Signed 64))\n| `([mlir_attr_val| - $x:num : $t:mlir_type]) => `(AttrValue.int (- $x) [mlir_type| $t])\n\nmacro_rules\n| `([mlir_attr_val| true ]) => `(AttrValue.bool True)\n| `([mlir_attr_val| false ]) => `(AttrValue.bool False)\n\n\nmacro_rules\n| `([mlir_attr_val| # $dialect:ident < $opaqueData:str > ]) => do\n let dialect := Lean.quote dialect.getId.toString\n `(AttrValue.opaque_ $dialect $opaqueData)\n\nmacro_rules\n| `([mlir_attr_val| #opaque< $dialect:ident, $opaqueData:str> : $t:mlir_type ]) => do\n let dialect := Lean.quote dialect.getId.toString\n `(AttrValue.opaqueElementsAttr $dialect $opaqueData $(⟨t⟩))\n\nmacro_rules\n | `([mlir_attr_val| $s:str]) => `(AttrValue.str $s)\n | `([mlir_attr_val| [ $xs,* ] ]) => do\n let initList <- `([])\n let vals <- xs.getElems.foldlM (init := initList) fun xs x => `($xs ++ [[mlir_attr_val| $x]])\n `(AttrValue.list $vals)\n | `([mlir_attr_val| $i:ident]) => `(AttrValue.type [mlir_type| $i:ident])\n | `([mlir_attr_val| $ty:mlir_type]) => `(AttrValue.type [mlir_type| $ty])\n\n\nsyntax \"dense<\" mlir_tensor \">\" \":\" mlir_type : mlir_attr_val\nmacro_rules\n| `([mlir_attr_val| dense< $v:mlir_tensor > : $t:mlir_type]) =>\n `(builtin.denseWithType [mlir_tensor| $v] [mlir_type| $t])\n\nsyntax \"dense<\" \">\" \":\" mlir_type: mlir_attr_val\nmacro_rules\n| `([mlir_attr_val| dense< > : $t:mlir_type]) =>\n `(builtin.denseWithType TensorElem.empty [mlir_type| $t])\n\nmacro_rules\n | `([mlir_attr_val| $a:affine_map]) =>\n `(AttrValue.affine [affine_map| $a])\n\nmacro_rules\n| `([mlir_attr_val_symbol| @ $x:str ]) =>\n `(AttrValue.symbol $x)\n\nmacro_rules\n| `([mlir_attr_val_symbol| @ $x:ident ]) =>\n `(AttrValue.symbol $(Lean.quote x.getId.toString))\n\nmacro_rules\n| `([mlir_attr_val_symbol| $x:mlir_attr_val_symbol :: $y:mlir_attr_val_symbol ]) =>\n `(AttrValue.nestedsymbol [mlir_attr_val_symbol| $x] [mlir_attr_val_symbol| $y])\n\n\nmacro_rules\n| `([mlir_attr_val| $x:mlir_attr_val_symbol ]) => `([mlir_attr_val_symbol| $x])\n\n\ndef attrVal0Str : AttrVal := [mlir_attr_val| \"foo\"]\n#reduce attrVal0Str\n\n-- Uses dialect coercion: empty → builtin\nexample : AttrValue builtin := [mlir_attr_val| \"foo\"]\n-- Uses dialect coercion: empty → empty + builtin\nexample : AttrValue (Dialect.empty + builtin) := [mlir_attr_val| \"foo\"]\n-- Uses dialect coercion after building an AttrValue Dialect.empty\n\n\ndef attrVal1bTy : AttrValue builtin := [mlir_attr_val| i32]\n#reduce attrVal1bTy\n\ndef attrVal2List : AttrValue builtin := [mlir_attr_val| [\"foo\", \"foo\"] ]\n#reduce attrVal2List\n\ndef attrVal3AffineMap : AttrValue builtin := [mlir_attr_val| affine_map<(x, y) -> (y)>]\n#reduce attrVal3AffineMap\n\ndef attrVal4Symbol : AttrValue builtin := [mlir_attr_val| @\"foo\" ]\n#reduce attrVal4Symbol\n\ndef attrVal5int: AttrValue builtin := [mlir_attr_val| 42 ]\n#reduce attrVal5int\n\ndef attrVal5bint: AttrVal := [mlir_attr_val| -42 ]\n#reduce attrVal5bint\n\n\ndef attrVal6Symbol : AttrVal := [mlir_attr_val| @func_foo ]\n#reduce attrVal6Symbol\n\ndef attrVal7NestedSymbol : AttrVal := [mlir_attr_val| @func_foo::@\"func_bar\" ]\n#reduce attrVal7NestedSymbol\n\n\nmacro_rules\n | `([mlir_attr_val| # $a:str]) =>\n `(AttrValue.alias $a)\n\ndef attrVal8Alias : AttrVal := [mlir_attr_val| #\"A\" ]\n#reduce attrVal8Alias\n\n\nmacro_rules\n | `([mlir_attr_val| # $a:ident]) =>\n `(AttrValue.alias $(Lean.quote a.getId.toString))\n\ndef attrVal9Alias : AttrVal := [mlir_attr_val| #a ]\n#reduce attrVal9Alias\n\nmacro_rules\n| `([mlir_attr_val| $x:scientific ]) => `(AttrValue.float $(⟨x⟩) (MLIRType.float 64))\n| `([mlir_attr_val| $x:scientific : $t:mlir_type]) => `(AttrValue.float $(⟨x⟩) [mlir_type| $t])\n\n\n-- def attrVal10Float : AttrVal := [mlir_attr_val| 0.000000e+00 ]\ndef attrVal10Float : AttrVal := [mlir_attr_val| 0.0023 ]\n#print attrVal10Float\n\ndef attrVal11Escape : AttrVal := [mlir_attr_val| $(attrVal10Float) ]\n#print attrVal11Escape\n\n-- The dense<> attribute requires the builtin dialect for the tensor type\ndef attrVal12DenseEmpty: AttrValue builtin := [mlir_attr_val| dense<> : tensor<0 × i64>]\n#print attrVal12DenseEmpty\n\n\n-- MLIR ATTRIBUTE\n-- ===============\n\n\ndeclare_syntax_cat mlir_attr_entry\n\nsyntax ident \"=\" mlir_attr_val : mlir_attr_entry\nsyntax strLit \"=\" mlir_attr_val : mlir_attr_entry\nsyntax ident : mlir_attr_entry\n\nsyntax \"[mlir_attr_entry|\" mlir_attr_entry \"]\" : term\n\n-- | TODO: don't actually write an elaborator for the `ident` case. This forces\n-- us to declare predefined identifiers in a controlled fashion.\nmacro_rules\n | `([mlir_attr_entry| $name:ident = $v:mlir_attr_val]) =>\n `(AttrEntry.mk $(Lean.quote (name.getId.toString)) [mlir_attr_val| $v])\n | `([mlir_attr_entry| $name:str = $v:mlir_attr_val]) =>\n `(AttrEntry.mk $name [mlir_attr_val| $v])\n\nmacro_rules\n | `([mlir_attr_entry| $name:ident]) =>\n `(AttrEntry.mk $(Lean.quote (name.getId.toString)) AttrValue.unit)\n\n\n\ndef attr0Str : AttrEntry builtin := [mlir_attr_entry| sym_name = \"add\"]\n#print attr0Str\n\ndef attr2Escape : AttrEntry builtin :=\n let x : AttrVal := [mlir_attr_val| 42]\n [mlir_attr_entry| sym_name = $(x)]\n#print attr0Str\n\n\ndef attr3Unit : AttrEntry builtin :=\n [mlir_attr_entry| sym_name]\n#print attr3Unit\n\ndef attr4Negative : AttrEntry builtin :=\n [mlir_attr_entry| value = -1: i32]\n#reduce attr4Negative\n\n\ndeclare_syntax_cat mlir_attr_dict\nsyntax \"{\" sepBy(mlir_attr_entry, \",\") \"}\" : mlir_attr_dict\nsyntax \"[mlir_attr_dict|\" mlir_attr_dict \"]\" : term\n\nmacro_rules\n| `([mlir_attr_dict| { $attrEntries,* } ]) => do\n let attrsList <- attrEntries.getElems.toList.mapM (fun x => `([mlir_attr_entry| $x]))\n let attrsList <- quoteMList attrsList (<- `(MLIR.AST.AttrEntry _))\n `(AttrDict.mk $attrsList)\n\ndef attrDict0 : AttrDict builtin := [mlir_attr_dict| {}]\ndef attrDict1 : AttrDict builtin := [mlir_attr_dict| {foo = \"bar\" }]\ndef attrDict2 : AttrDict builtin := [mlir_attr_dict| {foo = \"bar\", baz = \"quux\" }]\n\n-- dict attribute val\nsyntax mlir_attr_dict : mlir_attr_val\n\nmacro_rules\n| `([mlir_attr_val| $v:mlir_attr_dict]) => `(AttrValue.dict [mlir_attr_dict| $v])\n\ndef nestedAttrDict0 : AttrDict Dialect.empty := [mlir_attr_dict| {foo = {bar = \"baz\"} }]\n#print nestedAttrDict0\n\n-- MLIR OPS WITH REGIONS AND ATTRIBUTES AND BASIC BLOCK ARGS\n-- =========================================================\n\n--\n#check sepBy1\n\n-- Op with potential result\nsyntax\n (mlir_op_operand \"=\")?\n strLit \"(\" mlir_op_operand,* \")\"\n ( \"(\" mlir_region,* \")\" )?\n (mlir_attr_dict)?\n \":\" \"(\" mlir_type,* \")\" \"->\" \"(\"mlir_type,*\")\" : mlir_op\n\nmacro_rules\n | `([mlir_op| $$($x) ]) => return x\n\nmacro_rules\n | `([mlir_op|\n $[ $resName = ]?\n $name:str\n ( $operandsNames,* )\n $[ ( $rgns,* ) ]?\n $[ $attrDict ]?\n : ( $operandsTypes,* ) -> ( $resTypes,* ) ]) => do\n\n -- TODO: Needs a consistency check that `resName=none ↔ resType=.unit`\n let res ← match resName with\n | none => `(@List.nil (MLIR.AST.TypedSSAVal _))\n | some name =>\n match resTypes.getElems with\n | #[] => Macro.throwError s!\"expected to have return type since result '{resName}' exists\"\n | #[resType] => `([([mlir_op_operand| $name], [mlir_type| $resType])])\n | tys => Macro.throwError s!\"expected single return type, found multiple '{tys}'\"\n\n\n -- TODO: Needs a consistency check that `operandsNames.length = operandsTypes.length`\n let operands: List (MacroM <| TSyntax `term) :=\n List.zipWith (fun x y => `(([mlir_op_operand| $x], [mlir_type| $y])))\n operandsNames.getElems.toList operandsTypes.getElems.toList\n let operands ← quoteMList (← operands.mapM id) (← `(MLIR.AST.TypedSSAVal _))\n let attrDict <- match attrDict with\n | none => `(AttrDict.mk [])\n | some dict => `([mlir_attr_dict| $dict])\n let rgnsList <- match rgns with\n | none => `(@List.nil (MLIR.AST.Region _))\n | some rgns => do\n let rngs <- rgns.getElems.mapM (fun x => `([mlir_region| $x]))\n quoteMList rngs.toList (<- `(MLIR.AST.Region _))\n\n `(Op.mk $name -- name\n $res -- results\n $operands -- operands\n $rgnsList -- regions\n $attrDict) -- attrs\n\n-- Op with definite result\nsyntax mlir_op_operand \"=\"\n strLit \"(\" mlir_op_operand,* \")\"\n ( \"(\" mlir_region,* \")\" )?\n (mlir_attr_dict)? \":\" \"(\" mlir_type,* \")\" \"->\" mlir_type : mlir_op\n\nmacro_rules\n | `([mlir_op|\n $resName:mlir_op_operand =\n $name:str\n ( $operandsNames,* )\n $[ ( $rgns,* ) ]?\n $[ $attrDict ]?\n : ( $operandsTypes,* ) -> $resType:mlir_type ]) => do\n\n let res ← `([([mlir_op_operand| $resName], [mlir_type| $resType])])\n -- TODO: Needs a consistency check that `operandsNames.length = operandsTypes.length`\n let operands: List (MacroM <| TSyntax `term) :=\n List.zipWith (fun x y => `(([mlir_op_operand| $x], [mlir_type| $y])))\n operandsNames.getElems.toList operandsTypes.getElems.toList\n let operands ← quoteMList (← operands.mapM id) (← `(MLIR.AST.TypedSSAVal _))\n let attrDict <- match attrDict with\n | none => `(AttrDict.mk [])\n | some dict => `([mlir_attr_dict| $dict])\n let rgnsList <- match rgns with\n | none => `(@List.nil (MLIR.AST.Region _))\n | some rgns => do\n let rngs <- rgns.getElems.mapM (fun x => `([mlir_region| $x]))\n quoteMList rngs.toList (<- `(MLIR.AST.Region _))\n\n `(Op.mk $name -- name\n $res -- results\n $operands -- operands\n $rgnsList -- regions\n $attrDict) -- attrs\n\n\n\ndef op1 : Op Dialect.empty :=\n [mlir_op| \"foo\"(%x, %y) : (i32, i32) -> (i32) ]\n#print op1\ndef op2: Op builtin :=\n [mlir_op| %z = \"foo\"(%x, %y) : (i32, i32) -> (i32)]\n#print op2\n\ndef bbop1 : SSAVal × MLIRTy := [mlir_bb_operand| %x : i32 ]\n#print bbop1\n\ndef bb1NoArgs : Region builtin :=\n [mlir_region| {\n ^entry:\n \"foo\"(%x, %y) : (i32, i32) -> (i32)\n %z = \"bar\"(%x) : (i32) -> (i32)\n \"std.return\"(%x0) : (i42) -> ()\n }]\n#print bb1NoArgs\n\ndef bb2SingleArg : Region builtin :=\n [mlir_region| {\n ^entry(%argp : i32):\n \"foo\"(%x, %y) : (i32, i32) -> (i32)\n %z = \"bar\"(%x) : (i32) -> (i32)\n \"std.return\"(%x0) : (i42) -> ()\n }]\n#print bb2SingleArg\n\n\ndef bb3MultipleArgs : Region builtin :=\n [mlir_region| {\n ^entry(%argp : i32, %argq : i64):\n \"foo\"(%x, %y) : (i32, i32) -> (i32)\n %z = \"bar\"(%x) : (i32) -> (i32)\n \"std.return\"(%x0) : (i42) -> ()\n }]\n#reduce bb3MultipleArgs\n\n\ndef rgn0 : Region Dialect.empty := ([mlir_region| { }])\n#print rgn0\n\ndef rgn1 : Region builtin :=\n [mlir_region| {\n ^entry:\n \"std.return\"(%x0) : (i42) -> ()\n }]\n#print rgn1\n\ndef rgn2 : Region builtin :=\n [mlir_region| {\n ^entry:\n \"std.return\"(%x0) : (i42) -> ()\n }]\n#print rgn2\n\n-- | test what happens if we try to use an entry block with no explicit bb name\ndef rgn3 : Region builtin :=\n [mlir_region| {\n \"std.return\"(%x0) : (i42) -> ()\n }]\n#print rgn1\n\n\n-- | test simple ops [no regions]\ndef opcall1 : Op Dialect.empty := [mlir_op| \"foo\" (%x, %y) : (i32, i32) -> (i32) ]\n#print opcall1\n\n\n\ndef oprgn0 : Op Dialect.empty := [mlir_op|\n \"func\"() ({ ^entry: %x = \"foo.add\"() : () -> (i64) } ) : () -> ()\n]\n#reduce oprgn0\n\n-- | note that this is a \"full stack\" example!\ndef opRgnAttr0 : Op builtin := [mlir_op|\n \"module\"() ({\n ^entry:\n \"func\"() ({\n ^bb0(%arg0:i32, %arg1:i32):\n %zero = \"std.addi\"(%arg0 , %arg1) : (i32, i16) -> (i64)\n \"std.return\"(%zero) : (i32) -> ()\n }){sym_name = \"add\"} : () -> ()\n \"module_terminator\"() : () -> ()\n }) : () -> ()\n]\n#print opRgnAttr0\n\n\n\n\n-- | Builtins\n-- =========\n\n-- TODO: Move to `func` dialect\nsyntax\n \"func\" mlir_attr_val_symbol \"(\" mlir_bb_operand,* \")\" ( \"->\" mlir_type )? \"{\"\n mlir_ops\n \"}\" : mlir_op\n\nmacro_rules\n| `([mlir_op| func $name:mlir_attr_val_symbol ( $args,* ) $[ -> $ret:mlir_type ]? { $ops } ]) => do\n -- Make the arguments for the entry block\n let bbargs ← args.getElems.mapM (fun x => `([mlir_bb_operand| $x]))\n let bbargs ← quoteMList bbargs.toList (← `(MLIR.AST.SSAVal × MLIR.AST.MLIRType _))\n -- Make the entry block (the only block)\n let rgn ← `(Region.mk \"entry\" $bbargs [mlir_ops| $ops])\n\n -- Make the function signature\n let argTypes ← args.getElems.mapM (fun x => `(Prod.snd [mlir_bb_operand| $x]))\n let argTypes ← quoteMList argTypes.toList (← `(MLIR.AST.MLIRType _))\n let retType ← match ret with\n | none => `(MLIRType.tuple [])\n | some τ => `([mlir_type| $τ])\n let signature ← `(MLIRType.fn (MLIRType.tuple $argTypes) $retType)\n\n -- Make the entire operation\n let attrs ← `(AttrDict.mk [\n AttrEntry.mk \"function_type\" (AttrValue.type $signature),\n AttrEntry.mk \"sym_name\" [mlir_attr_val_symbol| $name]\n ])\n `(Op.mk \"func\" [] [] [$rgn] $attrs)\n\n\n\nsyntax \"module\" \"{\" mlir_op* \"}\" : mlir_op\n\nmacro_rules\n| `([mlir_op| module { $ops* } ]) => do\n let initList <- `([Op.empty \"module_terminator\"])\n let ops <- ops.foldrM (init := initList) fun x xs => `([mlir_op| $x] :: $xs)\n let rgn <- `(Region.fromOps $ops)\n `(Op.mk \"module\" [] [] [$rgn] AttrDict.empty)\n\ndef mod1 : Op builtin := [mlir_op| module { }]\n#print mod1\n\ndef mod2 : Op builtin := [mlir_op| module { \"dummy.dummy\"(): () -> () }]\n#print mod2\n\n--- MEMREF+TENSOR\n--- =============\n-- dimension-list ::= dimension-list-ranked | (`*` `x`)\n-- dimension-list-ranked ::= (dimension `x`)*\n-- dimension ::= `?` | decimal-literal\n-- tensor-type ::= `tensor` `<` dimension-list tensor-memref-element-type `>`\n-- tensor-memref-element-type ::= vector-element-type | vector-type | complex-type\n\n\n-- https://mlir.llvm.org/docs/Dialects/Builtin/#memreftype\n-- memref-type ::= ranked-memref-type | unranked-memref-type\n-- ranked-memref-type ::= `memref` `<` dimension-list-ranked type\n-- (`,` layout-specification)? (`,` memory-space)? `>`\n-- unranked-memref-type ::= `memref` `<*x` type (`,` memory-space)? `>`\n-- stride-list ::= `[` (dimension (`,` dimension)*)? `]`\n-- strided-layout ::= `offset:` dimension `,` `strides: ` stride-list\n-- layout-specification ::= semi-affine-map | strided-layout | attribute-value\n-- memory-space ::= attribute-value\n-- | good example for paper.\ndeclare_syntax_cat memref_type_stride_list\nsyntax \"[\" (mlir_dimension,*) \"]\" : memref_type_stride_list\n\ndeclare_syntax_cat memref_type_strided_layout\nsyntax \"offset:\" mlir_dimension \",\" \"strides:\" memref_type_stride_list : memref_type_strided_layout\n\ndeclare_syntax_cat memref_type_layout_specification\nsyntax memref_type_strided_layout : memref_type_layout_specification\nsyntax mlir_attr_val : memref_type_layout_specification\nsyntax \"[memref_type_layout_specification|\" memref_type_layout_specification \"]\" : term\n\n\nmacro_rules\n| `([memref_type_layout_specification| $v:mlir_attr_val]) =>\n `(MemrefLayoutSpec.attr [mlir_attr_val| $v])\n| `([memref_type_layout_specification| offset: $o:mlir_dimension , strides: [ $[ $ds:mlir_dimension ],* ]]) => do\n let ds <- ds.mapM (fun d => `([mlir_dimension| $d]))\n let ds <- quoteMList ds.toList (<- `(MLIR.AST.Dimension))\n `(MemrefLayoutSpec.stride [mlir_dimension| $o] $ds)\n\n-- | ranked memref\nsyntax \"memref\" \"<\" mlir_dimension_list (\",\" memref_type_layout_specification)? (\",\" mlir_attr_val)? \">\" : mlir_type\nmacro_rules\n| `([mlir_type| memref < $dims:mlir_dimension_list $[, $layout ]? $[, $memspace]? >]) => do\n let (dims, ty) <- parseTensorDimensionList dims\n let memspace <- match memspace with\n | some s => `(some [mlir_attr_val| $s])\n | none => `(none)\n\n let layout <- match layout with\n | some stx => `(some [memref_type_layout_specification| $stx])\n | none => `(none)\n `(builtin.memref $dims $ty $layout $memspace)\n\ndef memrefTy0 := [mlir_type| memref<3×3×i32>]\n#print memrefTy0\n\ndef memrefTy1 := [mlir_type| memref]\n#print memrefTy1\n\ndef memrefTy2 := [mlir_type| memref<2 × 4 × i8, #map1>]\n#print memrefTy2\n\ndef memrefTy3 := [mlir_type| memref<2 × 4 × i8, #map1, 1>]\n#print memrefTy3\n\n\n-- | unranked memref\n-- unranked-memref-type ::= `memref` `<*x` type (`,` memory-space)? `>`\n-- | TODO: Do I need two different parsers for these cases?\nsyntax \"memref\" \"<\" \"*\" \"×\" mlir_type (\",\" mlir_attr_val)? \">\" : mlir_type\nsyntax \"memref\" \"<*\" \"×\" mlir_type (\",\" mlir_attr_val)? \">\" : mlir_type\nmacro_rules\n| `([mlir_type| memref < * × $ty $[, $memspace]? >]) => do\n let memspace <- match memspace with\n | some s => `(some [mlir_attr_val| $s])\n | none => `(none)\n `(builtin.memref_unranked [mlir_type| $ty] $memspace)\n\nmacro_rules\n| `([mlir_type| memref <* × $ty $[, $memspace]? >]) => do\n let memspace <- match memspace with\n | some s => `(some [mlir_attr_val| $s])\n | none => `(none)\n `(builtin.memref_unranked [mlir_type| $ty] $memspace)\n\ndef memrefTy4 := [mlir_type| memref<* × f32>]\n#print memrefTy4\n\nend MLIR.EDSL\n", "meta": {"author": "opencompl", "repo": "lean-mlir", "sha": "85fd61e38dec57e4d67d7af4d49a1ccc67828c1b", "save_path": "github-repos/lean/opencompl-lean-mlir", "path": "github-repos/lean/opencompl-lean-mlir/lean-mlir-85fd61e38dec57e4d67d7af4d49a1ccc67828c1b/MLIR/EDSL.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.12252320290590249, "lm_q2_score": 0.028436033456533377, "lm_q1q2_score": 0.0034840738970338707}} {"text": "import data.option.basic\n\n/-!\n\n# Model of the Prisma migration engine `devDiagnostic` command\n\nThe `devDiagnostic` RPC command acts as a wrapper around `diagnoseMigrationHistory`. Its\nrole is to interpret the diagnostic output, and translate it to a concrete\naction to be performed by the CLI.\n\nThe corresponding control flow in the CLI should be:\n\n1. Call `RPC devDiagnostic`. Check the output:\n - Error / BrokenMigration -> display the error (regular user-facing error, no\n CLI code should be needed)\n - Reset -> Prompt the user to reset with the provided reason. Call\n `RPC reset`, then proceed with 2.\n - CreateMigration -> proceed with 2.\n2. Call `RPC applyMigrations`\n3. If we have no migration name, prompt for it.\n4. Check for the `--create-only` flag\n - If it was passed, call `RPC evaluateDataLoss`, show the warnings,\n `RPC createMigration`. Done.\n - Otherwise, call `RPC evaluateDataLoss`, potentially ask for confirmation,\n `RPC createMigration`, `RPC applyMigrations`. Generate the client. Done.\n\nImplemented JSON-RPC API:\n\n```typescript\ninterface DevDiagnosticInput {}\n\ninterface DevDiagnosticOutput {\n action: DevAction\n}\n\ntype DevAction =\n { tag: \"reset\", reason: string }\n | { tag: \"createMigration\" }\n\n```\n\n-/\n\nopen except (error ok)\n\nvariables { α : Type }\nuniverses u v\n\n/-- The top-level RPC input type. -/\ninductive DevInput : Type\n| mk : DevInput\n\ninductive ResetReason\n| Drifted\n| Unspecified\n\n/-- The top-level RPC output type. -/\ninductive DevOutput\n| CreateMigration\n| Reset : ResetReason → DevOutput\n-- This manifests itself as a user-facing error output, it does need any special\n-- handling in the CLI.\n| BrokenMigration : string -> DevOutput\n\nopen DevOutput\n\ninductive DriftDiagnostic : Type\n| DriftDetected : string -> DriftDiagnostic\n| MigrationFailedToApply : string -> DriftDiagnostic\n\ninductive HistoryDiagnostic : Type\n| DatabaseIsBehind\n| MigrationDirectoryIsBehind\n| HistoriesDiverge\n\nstructure DiagnoseMigrationHistoryOutput :=\nmk ::\n ( drift : option DriftDiagnostic )\n ( history : option HistoryDiagnostic )\n ( failedMigrationNames : list string )\n ( editedMigrationNames : list string )\n ( errorInUnappliedMigrations : option string )\n ( hasMigrationsTable : bool )\n\ndef DiagnoseMigrationHistoryOutput.resetReason : DiagnoseMigrationHistoryOutput → option ResetReason :=\nλ projectState,\nif (\n ¬projectState.failedMigrationNames.is_nil ||\n ¬projectState.editedMigrationNames.is_nil\n) then\n some ResetReason.Unspecified\nelse if ¬projectState.drift.is_none then\n some ResetReason.Drifted\nelse\n match projectState.history with\n | some HistoryDiagnostic.MigrationDirectoryIsBehind := some ResetReason.Unspecified\n | some HistoryDiagnostic.HistoriesDiverge := some ResetReason.Unspecified\n | _ := none\n end\n\ndef DiagnoseMigrationHistoryOutput.brokenMigration : DiagnoseMigrationHistoryOutput → option string :=\nλ o,\nmatch (o.drift, o.errorInUnappliedMigrations) with\n| ⟨some (DriftDiagnostic.MigrationFailedToApply name), _⟩ := some name\n| ⟨_, some name⟩ := some name\n| _ := none\nend\n\nexample : monad id := by apply_instance\n\n/-- Machinery to define early returns. -/\ndef devState : Type → Type := except_t DevOutput id\n\ninstance devStateMonad : monad devState := by { unfold devState, apply_instance }\ninstance devStateMonadError : monad_except DevOutput devState := by { unfold devState, apply_instance }\ninstance devStateMonadRun : monad_run (except DevOutput) devState := by { unfold devState, apply_instance }\n\n/-- Check that no migration (applied or unapplied) is broken. -/\ndef checkBrokenMigration : DiagnoseMigrationHistoryOutput → devState punit :=\nλ state, match state.brokenMigration with\n| some name := throw $ BrokenMigration name\n| none := pure ()\nend\n\n/-- Check whether we have a ground for a reset. -/\ndef checkReset : DiagnoseMigrationHistoryOutput → devState punit :=\nλ state, match state.resetReason with\n| some reason := throw $ Reset reason\n| none := pure ()\nend\n\n/-- The model implementation of `dev`. -/\ndef dev : DevInput → DiagnoseMigrationHistoryOutput → devState DevOutput :=\nλ input projectState,\ncheckBrokenMigration projectState >>\n checkReset projectState >>\n pure CreateMigration\n\n/-- Convenience wrapper around `dev` to make proof types more readable. -/\ndef runDev : DevInput → DiagnoseMigrationHistoryOutput → DevOutput :=\nλ input diagnostics, match run (dev input diagnostics) with\n| (error output) := output\n| (ok output) := output\nend\n\n-- -- ---- ---- ---- ---- ---- ---- ---- ---- -\n-- Proofs about `dev`'s model defined above. --\n-- ---- ---- ---- ---- ---- ---- ---- ---- ----\n\n/--\nIf the migrations are working and we should reset, we will always return\n`Reset`. -/\ntheorem devReset :\n ∀ (input : DevInput) (projectState : DiagnoseMigrationHistoryOutput),\n projectState.brokenMigration = none →\n projectState.resetReason.is_some →\n ∃ r, runDev input projectState = Reset r :=\nbegin\n intros input projectState hBroken hReset,\n delta runDev dev checkBrokenMigration checkReset,\n obtain ⟨r, hSome⟩ : ∃ r, projectState.resetReason = some r, from option.is_some_iff_exists.mp hReset,\n existsi r,\n simp [hReset],\n rw [hSome, hBroken],\n refl\nend\n\n/--\nWhenever we are not in a reset situation and no migration is broken, we will\nreturn `CreateMigration`. -/\ntheorem devCreateMigration :\n ∀ (input : DevInput) (projectState : DiagnoseMigrationHistoryOutput),\n projectState.resetReason = none →\n projectState.brokenMigration = none →\n runDev input projectState = CreateMigration :=\nbegin\n intros input projectState hNoReset hNoBrokenMigration,\n delta runDev dev checkBrokenMigration checkReset,\n rw [hNoReset, hNoBrokenMigration],\n refl\nend\n\n/--\n`dev` will always return an error before asking for a reset in case a\nmigration doesn't apply cleanly to the dev database. It never prematurely asks\nfor a reset. -/\ntheorem devBrokenMigration :\n ∀ (input : DevInput) (projectState : DiagnoseMigrationHistoryOutput) (brokenMigrationName : string),\n projectState.brokenMigration = some brokenMigrationName →\n runDev input projectState = BrokenMigration brokenMigrationName :=\nbegin\n rintros input projectState brokenMigrationName hBroken,\n unfold runDev dev checkBrokenMigration,\n simpa [hBroken]\nend\n", "meta": {"author": "tomhoule", "repo": "migrate-dev-lean", "sha": "910b62d1bea1d4534560e449ed82aa59100e2e75", "save_path": "github-repos/lean/tomhoule-migrate-dev-lean", "path": "github-repos/lean/tomhoule-migrate-dev-lean/migrate-dev-lean-910b62d1bea1d4534560e449ed82aa59100e2e75/src/dev.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO", "lm_q1_score": 0.14804718675485834, "lm_q2_score": 0.01691491469150995, "lm_q1q2_score": 0.0025042055342764705}} {"text": "import metaphysics.counterfactuals states\nopen set topological_space classical\nset_option pp.generalized_field_notation true\nlocal attribute [instance] prop_decidable\nnoncomputable theory\n\n\nnamespace ontology\n\nvariables {ω : ontology}\n\n/-! # Multiplicity of Meanings, Correctness of definitions, and Defaults\n\n In what follows we must keep in mind that \"cause\" and \"explanation\", just like\n many other philosophical concepts, have multiple\n valid and philosophically relevant meanings. So whenever we introduce some notion of\n causation or explanation, this does not commit us to the position that no other such\n notions could be further introduced; as indeed we ourselves have introduced more than\n a single one of these notions. In particular, if another philosopher introduces\n a completely different notion we are not prima facie committed \n to any special position regarding that notion.\n We should not multiply disagreements among philosophers beyond necessity,\n and so we should not assume that simply because a philosopher has said something\n different from what we have said about causality that we must disagree with him.\n For it could be that (1) if the two different positions refer to one and the same concept,\n or phenomenon, of causality, still the positions may not be contrary of themselves,\n and so it might be logically consistent to hold both together. Furthermore, \n it might even be the case that (1.1) one of them logically entails the other,\n or that (1.2) one can be otherwise reduced to the other, or that (1.3) \n they are logically equivalent; and this can be the case even when the\n positions appear to be saying very different things, but further logical \n analysis can be used to show that deep down they are saying essentially the same\n thing. Finally, it could be that (2) the two positions refer to two genuinely \n distinct, complementary, and irreducible concepts of causality, and so \n a potential disagreement can be resolved by accepting both concepts as distinct \n and equally valid meanings that the same word can take; just as, for example, \n Aristotle accepts 4 distinct meanings of the concept of \"cause\". And when (2) is at all plausible\n its adoption is to be preferred over disagreement with another philosopher \n who has given plausible reasons as to why his position must be true, unless we are able\n to sufficiently explain to him that the plausibility behind the reasons he adduces is not due to his theory of\n causality being true, but that it can be better explained by our own theory. Proceeding in this way we can keep\n disagreements to a minimum, leaving greater room for cooperation.\n \n Furthermore, at least *some* of the arguments we will introduce, e.g. about the existence of God,\n will not really depend on the assumption\n that any notion of cause we introduce is the \"correct\" notion of cause, or that it even captures\n the pre-theoretical phenomenon of causality in any capacity at all; and this is because some arguments can be made\n to the extent that if such and such talk of \"causes\" (e.g. the causal terminology of Aristotle) \n is logically consistent with our background `ontology` then some important \n consequences may follow from this logical consistency assumption alone. \n And this would be furthermore so even if we had good evidence that such \"talk\" does not capture what people \n regularly intend to mean by causes, or even if we were non-cognitivists about causality,\n who thought that any talk of \"causes\" is always meaningless gibberish\n which refers to nothing in reality; so long as it was logically consistent\n meaningless gibberish this would still be enough for the purposes of these arguments, as we shall\n later show. Hence, with respect to these arguments, disagreements about the true nature of causality\n would be ultimately irrelevant.\n \n Though admittedly, perhaps, some theories of the meaning of causality that are introduced\n by philosophers better capture the phenomena and are more parsimonious, \n or more useful for metaphysics, than others; so that in this respect there can\n indeed be disagreement among philosophers about which theory of causality better captures\n its true nature. Indeed, in the extreme case, it may be proposed by one philosopher that the theory\n espoused by another philosopher is not only worse than his own, but that \n it is meaningless, or that it does not qualify as a theory of causality at all.\n However, we believe that formalization suffices\n to resolve charges of \"meaninglessness\" made against philosophical theories,\n so that if a theory of causality is formalized, then unless it says something clearly preposterous,\n utterly implausible, self-evidently false, or completely irrelevant to the phenomenon at hand,\n it will be very hard to dismiss it as not being a theory of causality at all in the first place.\n So the bar should be pretty low on what counts as a valid meaning, definition or theory of causality,\n provided it is a formal definition/theory.\n\n But when we judge among theories which are clearly valid theories of causality,\n which theory is better, we must be presupposing, or at\n least it may be convenient to presuppose, that the question only makes sense\n relative to some standard. Some ideal notion of causality which captures the\n phenomenon better than any alternative notion, or in other words, some \n ideal notion of causality which is *correct by definition*. We can then judge \n a theory's correctness as a definition of causality by the extent to which the theory\n is similar to the ideal one which is correct by definition. \n \n Why am I saying all of this? Well, it turns out that the Lean theorem prover\n already provides us with a nice mechanism for talking about the \"ideal\" notion of\n causality. Suppose that a philosopher wants to make the claim that some such notion of\n causality `X : ω.cause` is the correct notion of causality for the ontology `ω`, \n he can do this by using the `inhabited` type:\n\n ```instance correct_notion_of_causality : inhabited ω.cause := ⟨X⟩```\n\n If a philosopher uses this library to formalize his theory of causality\n as the instance `X` of the `ω.cause` type, and then adds the line above to his code,\n he will be able to refer to `X` by the expression `default ω.cause`. \n We can then adopt the convention that the `default` value \n of a type defining a controversial philosophical concept,\n is to be used to refer to the ideal version of the concept which is correct by definition.\n So when the philosopher adds the line above to his code he will effectively be claiming\n that `X` **is the correct definition/true nature of causality**. If however another instance of \n `inhabited ω.cause` had previously been defined by another philosopher, `default ω.cause`\n will become ambiguous. A philosopher will be able to check whether any\n philosopher using the library has disagreed with him about the true meaning of causality\n by verifying whether there are any other definitions of an instance of `inhabited ω.cause` \n in the code, a process which can surely be automatized in the future.\n\n The point of this is that we can concentrate real disagreements of philosophy into the problem\n of defining a single unique instance of the inhabited class for every controversial concept of philosophy. \n Until a philosopher has proposed a definition of `inhabited ω.cause`, he will not have said anything controversial\n about causality even if he introduced a myriad different definitions of possible causal structures, made\n assumptions about them, and proved theorems from the assumptions. Even if he introduces a definition very\n distinct and incompatible with my own, until he declares it to be the uniquely correct definition of causality,\n he will simply be talking about something wholly different from what I am talking about when I am talking about\n causality. Our disagreements can then be at most disagreements about the meanings of words, i.e. \"semantic\" ones,\n but not about the phenomenon itself, so that **any true disagreement of philosophers about the meaning of a**\n **concept will ultimately boil down to the question of defining the `default` version of that concept**,\n i.e. of defining what the `default` meaning of the concept should be. And if furthermore all disagreements of\n philosophy also boil down to disagreements about the meanings of concepts. then of course \n **any true disagreement of philosophers will ultimately boil down to the question of defining**\n **the `default` version of some concept**.\n\n Hence to sumarize the main points of each of the above paragraphs, in order:\n 1. We need not disagree about the true nature of causality just because I have introduced a \n theory of causality which appears to be different from your own theory,\n or which might even at first appear to contradict it.\n 2. Even if we do disagree about the true nature of causality, this might be irrelevant to some of\n of the arguments I will present, which cannot be blocked by this sort of disagreement. Even some\n cosmological proofs of the existence of God will not be answerable in this way.\n 3. Even if we were to ask the question \"What is the true nature of causality\", just out of curiosity,\n and even if we disagreed about the answer, we could confine all our disagreement \n in a single place, in the definition of `inhabited ω.cause`. And anything else that we did\n say about causality which did not make reference to `default ω.cause` would not have directly concerned\n the \"true nature of causality\", and hence could not constitute a disagreement about it.\n 4. The idea of confining our disagreement to a particular instance of a type class has natural support \n from the language of the Lean prover. In the future we may be able to do some automation \n so that a philosopher can easily find out all alternative proposals for the definition of `default ω.cause`.\n 5. **Any true disagreement of philosophers will ultimately boil down to the question of defining**\n **the `default` version of some concept**.\n 6. Extra: Despite all of this, it just might be the case that I lucked out and just happened to \n find the true nature of causality using one of the definitions I will present.\n That is not so implausible, even though the definitions I will provide are only tentative\n at best for the purpose of discovering \"the true nature\". So despite all I've said, if you disagree\n with me, one plausible solution out of this conundrum would be to just claim that you are wrong (you fool).\n But avoiding having to claim this directly is really 90% of the purpose of writing this massive wall of\n text to being with, so that I can avoid any ontological responsibility for introducing\n assumptions; like the good coward that I am ;).\n\n Now, we cannot know prior to investigation, whether there is a single meaning \n of causality which explains all others, and in terms of which all others can be\n reduced, or if there are several. Aristotle famously defended the latter view with\n his doctrine of the 4 causes, in which all 4 causal concepts are primitive and \n irreducible to each another. If this view is correct, then instead of \n defining a single default theory of causality, we should primarily seek to partition\n the possible causal structures into subtypes and provide a separate `default`\n for each subtype. So for instance, we could define `ω.efficient_cause` as an extension\n of the `ω.cause` structure which we define below with further axioms which characterize\n efficient causes, and then define an instance of `inhabited ω.efficient_cause`. \n This would also not pose problems if we wanted to keep an already existing \n definition of `inhabited ω.cause` because\n if we properly partition `ω.cause` into subtypes then `default ω.cause` would have to \"belong\"\n to one of these subtypes, say `ω.efficient_cause`, \n and so by setting this `default` we would be claiming philosophically\n that the most used, fundamental, or relevant, notion of cause is also an `ω.efficient_cause`, i.e. an efficient \n sort of cause, even if not all causes could be reduced to efficient causes.\n And so, because we can make sense of the meaning of `default ω.cause` even in the context\n of there being subtypes of `ω.cause` with their own `default`s, we need not remove the `inhabited ω.cause` \n instance definition from Lean just because we introduced a new subtype of `ω.cause`.\n\n What I have said in this section about causality applies really to **any** philosophical concept\n whatsoever whose theory or definition can possibly be disputed among philosophers.\n This them provides us with a general method for doing philosophy which is greatly\n enhanced by the usage of a theorem prover. \n\n-/\n\n/-- Explanatory structure, used to define Leibniz's concept of **explanation**.\n Notice however that what Leibniz's called explanation Aristotle would have \n called \"cause\". -/\nstructure explanation (ω : ontology) :=\n (explains : ω.event → ω.event → ω.event)\n (nontrivial : ∃ e₁ e₂, ⋄explains e₁ e₂)\n (transitive : ∀ e₁ e₂ e₃, explains e₁ e₂ ∩ explains e₂ e₃ ⇒ explains e₁ e₃)\n (axiom₀ : ∀ {e w}, (∃ e', explains e' e w) → e.occurs w)\n /-- Events which possess some explanation as to why they occur must occur in the first place. -/\n add_decl_doc explanation.axiom₀\n\nnamespace explanation \n\n variable (ε : ω.explanation)\n\n /-- Events need to occur in order to explain another event.\n Explanatory structures satisfying this principle are called **simultaneous**\n because they require the *explanans* to be simultaneous to the\n *explanandum*. This is the most relevant property\n to distinguish between different meanings of \"explanation\". -/\n def simultaneous := ∀ {e w}, (∃ e', ε.explains e e' w) → e.occurs w\n\n /-- An event is a substratum if any of its explanations have to be simultaneous\n to it. -/\n def substratum (e : ω .event) := ∀ e', ε.explains e' e ⇒ e'\n\n /- The meaning of the above definition is given by\n the consideration of the similarity\n of the event `e` to the event of the existence of the\n material substratum of physical things, insofar as the cause or explanation\n of the existence of this material substratum cannot be something \n that occurred in the past, but rather it must be something simultaneous\n to this substratum.\n The theory behind this is that only configurations of the material\n substratum `m` could possibly be caused in world `w` \n by something `e` which no longer exists in `w`, \n and this happens precisely when `e` is the cause of \n some motion in some previous possible world `w₀` \n which ultimately lead to the configuration `m` existing in `w`.\n So we say that the potter is the cause of a clay pot even when the potter\n is dead and no longer exists, only because of the fact that, \n at some point in the past, the potter was the simultaneous cause of some\n motion of clay which changed the material configuration of the clay\n until the point that it became a pot. The fundamental kind of\n causation as such is simultaneous causation, as non-simultaneous cases \n can be reduced to the simultaneous ones.\n\n After the clay became a pot, it \n no longer needed the potter for continuing to be a pot, but this is so\n only because the pot is nothing but a configuration of the underlying clay. \n Some things however, like the fundamental particles of physics, or any\n sort of fundamental material substratum that is proposed for things,\n cannot be reduced to configurations of further material substrata,\n and so could not possibly be caused like the potter causes the pot. \n As such, to the extent that these things are caused at all, their cause\n must be simultaneous to them. Furthermore, it may just be that many other\n things besides material substrata behave like this, for instance processes\n and motions, so we are not claiming that every event that is a `substratum`,\n in accordance with our definition, needs to be a material substratum at all,\n the reason for the naming is only due to the fact that it shares this property\n with a material substratum. \n \n We would like to avoid having to formally define what \"motion\" is,\n and give a formal account of temporal considerations here, because \n that would simply complicate the discussion, so instead \n we are making this argument informally for now.\n \n -/\n\n /-- An event **simultaneously explains** another event if it explains it and \n it must be simultaneous with that particular event in order to explain it. -/\n def simexplains (e₁ e₂ : ω.event) : ω.event := ε.explains e₁ e₂ ∩ {w | ε.explains e₁ e₂ ⇒ e₁}\n\n -- Note that in the right of the `∩` in the previous definition we are just lifting a `Prop` to an\n -- `ω.event`. If the `Prop` is true, `simexplains` just reduces to `explains`, otherwise\n -- it is the empty set, i.e. the impossible event.\n\n /-- The (explanatory) **Principle of Sufficient Reason**, as an event. -/\n def epsr (kind := @event.contingent ω) : ω.event := \n {w : ω.world | ∀ (e : ω.event), kind e → e.occurs w → ∃ e', ε.explains e' e w}\n\n /-- The (explanatory) **Weak Principle of Sufficient Reason**, as an event. -/\n def ewpsr (kind := @event.contingent ω) : ω.event := \n {w : ω.world | ∀ (e : ω.event), kind e → e.occurs w → ∃ e', ⋄ε.explains e' e}\n\n /-- The (explanatory) **Principle of Sufficient Reason**. -/\n def psr (kind := @event.contingent ω) : Prop := □ε.epsr kind\n\n -- Note: by introducing the default argument in the definition, \n -- we get that calling `ε.psr` without arguments will claim \"every contingent event has an explanation\",\n -- but by providing the additional \"kind\" argument, you get a localized `psr` which claims\n -- \"every entity of a certain *kind* has an explanation\".\n\n /-- A **stronger** version of the (explanatory) **Principle of Sufficient Reason**, as an event.\n It claims that \"Every event has an explanation\". -/\n def sepsr : ω.event := ε.epsr univ \n\n /-- A **stronger** version of the (explanatory) **Principle of Sufficient Reason**. -/\n def spsr : Prop := □ε.sepsr\n\n\n\nend explanation\n\n/-- Causal structure, used to define the concept of causation. \n A causal structure is an irreflexive explanatory structure. -/\nstructure cause (ω : ontology) extends explanation ω :=\n (irreflexive : ∀ e, ¬⋄explains e e)\n\nnamespace cause\n\n variable (c : ω.cause)\n\n def up := c.to_explanation\n @[reducible, simp, alias, inline]\n def causes := c.explains\n\n -- Note: We would rather repeat some definitions of explanations, since\n -- we will mostly be talking about causes, so we try to minimize usage of `cause.up`.\n\n /-- Events need to occur in order to cause another event.\n Causal structures satisfying this principle are called **simultaneous**\n because they require the cause to be simultaneous to the\n effect. This is the most relevant property\n to distinguish between different meanings of \"cause\".\n Metaphysical causality should be expected to be primarily simultaneous,\n while the physical causality of the special sciences often presupposes\n that causes are temporally prior to their effects, rather than simultaneous. -/\n def simultaneous := ∀ {e w}, (∃ e', c.causes e e' w) → e.occurs w\n\n /-- An event is a substratum if any of its causes have to be simultaneous\n to it. -/\n def substratum (e : ω .event) := ∀ (e'), c.causes e' e ⇒ e'\n\n /-- An event is a substratum locally in some possible world \n if any of its causes in that world have to occur in that world\n in order to cause it. -/\n def esubstratum (e : ω .event) : ω.event := {w | ∀ (e'), c.causes e' e w → e'.occurs w}\n\n /-- An event `e₁` **simultaneously causes** another event `e₂` if `e₁` causes `e₂` and \n `e₁` needs to be simultaneous with `e₂` in order to cause it. -/\n def simcauses (e₁ e₂ : ω.event) : ω.event := c.causes e₁ e₂ ∩ {w | c.causes e₁ e₂ ⇒ e₁}\n\n /-- The **Principle of Substratum** for events, as an event. \n It reads: \"Events of a certain kind (contingent) are substrata.\". -/\n def eps' (kind := @event.contingent ω) : ω.event := {w | ∀ e, kind e → e.occurs w → c.substratum e}\n /-- The **Principle of Substratum** for events. \n It reads: \"Events of a certain kind (contingent) are substrata.\". -/\n def ps' (kind := @event.contingent ω) : Prop := □c.eps' kind\n /-- The **Principle of Substratum** (for entities), as an event. \n It reads: \"Entities of a certain kind (contingent) are substrata.\". -/\n def eps (kind := @entity.contingent ω) : ω.event := {w | ∀ e, kind e → e.exists w → c.substratum e}\n /-- The **Principle of Substratum** (for entities). \n It reads: \"Entities of a certain kind (contingent) are substrata.\". -/\n def ps (kind := @entity.contingent ω) : Prop := □c.eps kind\n\n /-- The **Principle of Singleton Substratum**, as an event. \n It states that the event of the world being\n exactly like it is is a substratum. -/\n def epss : ω.event := {w | c.substratum {w}}\n\n /-- The **Principle of Singleton Substratum**. \n It states that the event of the world being\n exactly like it is is a substratum. -/\n def pss : Prop := □c.epss\n\n def caused (e : ω.event) : ω.event := {w | ∃ e', c.causes e' e w}\n def simcaused (e : ω.event) : ω.event := {w | ∃ e', c.simcauses e' e w}\n def is_cause (e : ω.event) : ω.event := {w | ∃ e', c.causes e e' w}\n def uncaused (e : ω.event) : ω.event := -c.caused e\n\n /-- An **Exact cause** is an event which causes everything that is consubstantial \n to some entity in some possible world.\n The event is said to **exact** the entity because it is,\n in a sense, a fully qualified cause of the underlying substance being in the state\n it is in. -/\n def exacts (e : ω.event) (e₁ : ω.entity) : ω.event := \n {w | ∀ e₂ : ω.entity, e₂ ≈ e₁ → e₂.exists w → c.causes e e₂ w}\n\n /-- **External cause**. -/\n def excauses (e : ω.event) (e₁ : ω.entity) : ω.event := \n c.causes e e₁ ∩ {w | ¬ ∃ e₂ : ω.entity, e₂.exists = e ∧ e₁ ≈ e₂}\n\n def ppc₀ : Prop := ∀ (e : ω.event) (e₁ : ω.entity), c.simcauses e e₁ ⇒ c.excauses e e₁\n \n /-- **Strictly Existential cause**. -/\n def secauses (e : ω.event) (e₁ : ω.entity) : ω.event := \n c.causes e e₁ ∩ {w | ¬ ∃ e₂ : ω.entity, e₂ ≠ e₁ ∧ e₁ ≈ e₂ ∧ c.causes e e₂ w}\n\n /-- **Existential cause**. -/ -- needs some work, appears trivial.\n def ecauses (e : ω.event) (e₁ : ω.entity) : ω.event := c.secauses e e₁ ∪ c.exacts e e₁\n\n def entitative : Prop := ∀ {e}, ⋄c.is_cause e → e.existential\n def effentitative : Prop := ∀ {e}, ⋄c.caused e → e.existential\n def substantive : Prop := ∀ {e}, ⋄c.is_cause e → e.substantive\n /-- **Causal Realism** is the intensional proposition which claims that whatever\n entity can cause real entities must itself be real. -/\n def realistic (Ω : ω.iontology) : Prop := ∀ (e₁ e₂ : ω.entity), e₂.real Ω → ⋄c.causes e₁ e₂ → e₁.real Ω\n \n def consubstantial : Prop := ∀ e (e₁ : ω.entity), c.causes e e₁ ⇒ c.exacts e e₁\n \n section conjunctive\n def conjunctive : Prop := ∀ e e₁ e₂, c.causes e (e₁ ∩ e₂) = c.causes e e₁ ∩ c.causes e e₂\n def conjunctive₁ : Prop := ∀ e e₁ e₂, c.causes e (e₁ ∩ e₂) ⇒ c.causes e e₁ ∩ c.causes e e₂\n def conjunctive₂ : Prop := ∀ e e₁ e₂, c.causes e e₁ ∩ c.causes e e₂ ⇒ c.causes e (e₁ ∩ e₂)\n\n def conjunctive' : Prop := \n ∀ e e₁ e₂ : ω.event,\n e₁.contingent → e₂.contingent → c.causes e (e₁ ∩ e₂) = c.causes e e₁ ∩ c.causes e e₂\n def conjunctive₁' : Prop := \n ∀ e e₁ e₂ : ω.event, \n e₁.contingent → e₂.contingent → c.causes e (e₁ ∩ e₂) ⇒ c.causes e e₁ ∩ c.causes e e₂\n \n def conjunctive₂' : Prop := \n ∀ e e₁ e₂ : ω.event, \n e₁.contingent → e₂.contingent → c.causes e e₁ ∩ c.causes e e₂ ⇒ c.causes e (e₁ ∩ e₂)\n\n def conjunctive₁'' : Prop := \n ∀ e e₁ e₂ : ω.event, e₁ ≢ e₂ → c.causes e (e₁ ∩ e₂) ⇒ c.causes e e₁ ∩ c.causes e e₂\n \n def econjunctive₁'' : Prop := \n ∀ e e₁ e₂ : ω.event, e₁.entitative → e₁ ≢ e₂ → c.causes e (e₁ ∩ e₂) ⇒ c.causes e e₁\n \n \n end conjunctive\n\n def disjunctive : Prop := ∀ e e₁ e₂, c.causes e (e₁ ∪ e₂) = c.causes e e₁ ∪ c.causes e e₂\n def subadditive : Prop := ∀ e e₁ e₂, c.causes e (e₁ ∪ e₂) ⇒ c.causes e e₁ ∪ c.causes e e₂\n def superadditive : Prop := ∀ e e₁ e₂, c.causes e e₁ ∪ c.causes e e₂ ⇒ c.causes e (e₁ ∪ e₂)\n\n /-- Causal monotonicity -/\n def monotone : Prop := ∀ e e₁ e₂ : ω.event, e₁ ⇒ e₂ → c.causes e e₁ ⇒ c.causes e e₂\n\n /-- Contingent causal monotonicity -/\n def cmonotone : Prop := \n ∀ e e₁ e₂ : ω.event, e₁.contingent → e₂.contingent → \n e₁ ⇒ e₂ → c.causes e e₁ ⇒ c.causes e e₂\n \n def K : Prop := ∀ e e₁ e₂, c.causes e (e₁ ⟶ e₂) ⇒ ((c.causes e e₁) ⟶ c.causes e e₂)\n def axiom₄₀ : Prop := ∀ e₁ e₂, c.causes e₁ e₂ ⇒ c.causes e₁ (c.causes e₁ e₂)\n def axiom₄₁ : Prop := ∀ e, c.caused e ⇒ c.caused (c.caused e)\n def axiom₄₂ : Prop := ∀ e₁ e₂, c.causes e₁ e₂ = c.causes e₁ (c.caused e₂)\n lemma T : ∀ {e}, c.caused e ⇒ e := by\n rintros e w ⟨e₂, h⟩; exact c.axiom₀ ⟨e₂, h⟩\n\n @[simp]\n lemma caused_causes : ∀ {e₁ e₂}, c.causes e₁ e₂ ⇒ c.caused e₂ := \n assume e₁ _ _ h, ⟨e₁,h⟩\n\n @[simp]\n lemma occured_causes : ∀ {e₁ e₂}, c.causes e₁ e₂ ⇒ e₂ := by\n intros e₁ e₂ w hw; apply c.T; apply c.caused_causes hw\n \n -- has some similarities to the Gale-Pruss argument\n lemma cause_all_of_cause_singleton : c.conjunctive₁' → ∀ {w e}, c.causes e {w} w →\n ∀ e' : ω.event, e'.contingent → e'.occurs w → c.causes e e' w\n := begin\n intros h₁ w e h₂ e' h₃ h₄,\n by_cases h₅ : ({w} : ω.event).contingent, swap,\n simp [nbe, ext_iff] at h₃,\n replace h₃ := h₃.2,\n obtain ⟨w', hw'⟩ := h₃,\n simp [nbe, ext_iff] at h₅,\n specialize h₅ w',\n rw h₅ at hw',\n contradiction,\n replace h₁ := h₁ e {w} e',\n suffices c₃ : {w} = {w} ∩ e',\n rw ←c₃ at h₁,\n specialize h₁ h₅ h₃ h₂,\n exact h₁.2,\n ext w', simp,\n refine ⟨λh, ⟨h,_⟩, and.left⟩,\n cases h,\n exact h₄,\n end\n\n\n /-- A substance **Freely causes** some event if it simultaneously causes it and it is possible\n for it to not have simultaneously caused it even while remaining in the same state and in\n the same context in which the causation took place. -/\n def fcauses (s : ω.substance) (e : ω.event) : ω.event := \n { w | c.simcauses s e w ∧ ∀ (context : ω.event), \n c.simcauses s e ⇒ context → c.simcauses s e ≠ context →\n ∃ w', w' ≠ w ∧ s.state w' = s.state w ∧ context.occurs w' ∧\n ¬c.simcauses s e w'\n }\n \n def has_will (s : ω.substance) : Prop := ∃ e, ⋄c.fcauses s e\n\n /-- The event of a substance `s` being **free** w.r.t. some \n causal structure `c` is the set of all possible worlds `w` in which\n `s` exists and there is some possible event `e` which:\n 1. It is possible that `s` can freely cause `e` from the state it is in at `w`.\n 2. The existence of no entity can preclude `s` from freely causing `e` in `w`.\n 3. No possible entity can be the cause that `s` does not freely cause `e` in `w`.\n -/\n def efree (s : ω.substance) : ω.event := \n { w | s.exists w ∧ ∃ e, ⋄(c.fcauses s e ∩ s.equiv w) ∧\n w ∈ ✦(c.fcauses s e) ∧ ¬∃ e', c.causes e' (-(c.fcauses s e)) w\n }\n \n /-- A substance `s` is said to be **free** w.r.t. some \n causal structure `c` if in any possible world `w` in which\n `s` exists there is always some possible event `e` which:\n 1. It is possible that `s` can freely cause `e` from the state it is in at `w`.\n 2. The existence of no entity can preclude `s` from freely causing `e` in `w`.\n 3. No possible entity can be the cause that `s` does not freely cause `e` in `w`.\n -/\n def free (s : ω.substance) : Prop := s ⇒ c.efree s\n\n /-- The causal version of the **Principle of Sufficient Reason**, as an event. -/\n @[reducible, simp]\n def epsr (kind := @event.contingent ω) : ω.event := c.up.epsr kind\n /-- The causal version of the **Weak Principle of Sufficient Reason**, as an event. -/\n @[reducible, simp]\n def ewpsr (kind := @event.contingent ω) : ω.event := c.up.ewpsr kind\n\n /-- The causal version of the **Principle of Sufficient Reason**. -/\n def psr (kind := @event.contingent ω) : Prop := □c.epsr kind\n\n /-- The **Principle of Causality**, as an event. This is the `psr` restricted to entities. -/\n def epc (kind := @entity.contingent ω) : ω.event := \n {w : ω.world | ∀ (e : ω.entity), kind e → e.exists w → c.caused e w}\n /-- The **Principle of Causality**. This is the `psr` restricted to entities. -/\n def pc (kind := @entity.contingent ω) : Prop := □c.epc kind\n\n\n theorem Gale_Pruss : c.conjunctive₁' → c.ewpsr ⇒ c.epsr :=\n begin\n intros h₀ w h₁,\n specialize h₁ {w}, simp [ext_iff] at h₁,\n by_cases hyp : ∃ w', w' ≠ w,\n obtain ⟨w', hw'⟩ := hyp,\n specialize h₁ w' hw', clear hw' w',\n obtain ⟨C, w', h⟩ := h₁,\n have c₁ := c.axiom₀ ⟨C, h⟩, \n simp at c₁, cases c₁, clear c₁,\n have c₁ := c.cause_all_of_cause_singleton h₀ h,\n intros e he₁ he₂, use C, apply c₁; assumption,\n clear h₀ h₁,\n intros e he, exfalso,\n simp [entity.contingent, ext_iff] at he,\n obtain ⟨⟨w', hw'⟩, w'', hw''⟩ := he,\n push_neg at hyp,\n have c₁ := hyp w',\n have c₂ := hyp w'', \n cases c₁, cases c₂, clear hyp c₁ c₂,\n contradiction,\n end\n\n\n /-- The **Platonic Principle** for events, as an event.\n This principle is a consequence of the doctrine\n of the impossibility of an infinite regress of \n (*per se* ordered, simultaneous) causes. \n It can be interpreted as a logically weaker form\n of stating essentially the same principle.\n It can be read as saying \n \"Everything (of some kind) that is caused is ultimately caused by something uncaused\". -/\n def epp' (kind := λe:ω.event,true) : ω.event := \n {w | ∀ e, kind e → c.caused e w → ∃ e', w ∈ c.uncaused e' ∩ c.causes e' e}\n /-- The **Platonic Principle** for events.\n This principle is a consequence of the doctrine\n of the impossibility of an infinite regress of \n (*per se* ordered, simultaneous) causes. \n It can be interpreted as a logically weaker form\n of stating essentially the same principle.\n It can be read as saying \n \"Everything (of some kind) that is caused is ultimately caused by something uncaused\". -/\n def pp' (kind := λe:ω.event,true) : Prop := □c.epp' kind\n /-- The **Platonic Principle** (for entities), as an event.\n This principle is a consequence of the doctrine\n of the impossibility of an infinite regress of \n (*per se* ordered, simultaneous) causes. \n It can be interpreted as a logically weaker form\n of stating essentially the same principle.\n It can be read as saying \n \"Everything (of some kind) that is caused is ultimately caused by something uncaused\". -/\n def epp (kind := λe:ω.entity,true) : ω.event := \n {w | ∀ (e : ω.entity), kind e → c.caused e w → ∃ e', w ∈ c.uncaused e' ∩ c.causes e' e}\n /-- The **Platonic Principle** (for entities).\n This principle is a consequence of the doctrine\n of the impossibility of an infinite regress of \n (*per se* ordered, simultaneous) causes. \n It can be interpreted as a logically weaker form\n of stating essentially the same principle.\n It can be read as saying \n \"Everything (of some kind) that is caused is ultimately caused by something uncaused\". -/\n def pp (kind := λe:ω.entity,true) : Prop := □c.epp kind\n\n /- **Fun fact:** the platonic principle is also a way to state the impossibility of an infinite\n regress in a way to make the classical arguments which depend on it tractable within the\n confines of Aristotelian logic. Aristotelian logic is not really equipped to discuss \n the order-theoretical questions which arise in the discussion of regress problems.\n For instance, it appears to be impossible to derive Zorn's lemma from the axiom \n of choice using only Aristotelian syllogisms. However, using the platonic principle,\n many arguments can be exposed using simple BARBARA syllogisms. \n \n We do not necessarily mean to imply, however, that this principle is more or less evident\n than the impossibility of regress. If the impossibility of regress seems more evident than this\n principle to the reader, we can use that assumption to prove the principle rather than to assume\n this principle as a premisse in our arguments. However, the proof of this principle does depend\n on Zorn's lemma, which is equivalent to the axiom of choice.\n Indeed, this proof can be seen as a mere restatement of the lemma. \n -/\n\n /-- An entity is a **First Cause** in some possible world `w` if it is the cause \n of every other event occurring in `w` (except itself). -/\n def first_cause' (e : ω.entity) : ω.event := \n {w | e.exists w ∧ ∀ e' : ω.event, e'.occurs w → e.exists ≠ e' → c.causes e e' w}\n\n /-- An entity is a **First Cause** in some possible world `w` if it is the cause \n of every other entity existing in `w` (except itself). -/\n def first_cause (e : ω.entity) : ω.event := \n {w | e.exists w ∧ ∀ e' ∈ w, e ≠ e' → c.causes e e' w}\n \n def omnipotent (e : ω.entity) : Prop := □c.first_cause e\n\n /-- **John Duns Scotus** was the first philosopher (we are aware of) to propose\n to join the ontological (i.e. modal) and cosmological arguments. \n A proof of `c.dscotus` is a proof that it is possible that the\n necessary being is a `first_cause`. -/\n @[reducible, simp]\n def dscotus : Prop := ⋄c.first_cause ω.nbe\n\n /-- Any cosmological argument can have its premisses weakened by the ontological argument \n so as to prove a `dscotus`.\n In other words, given any argument for the existence\n of a first cause, if the event\n of its premisses being (jointly) true can possibly occur,\n then it must be at least possible\n for there to be a first cause. -/\n theorem scotus_theorem : ∀ {argument : ω.event}, argument ⇒ c.first_cause ω.nbe → ⋄argument → c.dscotus :=\n by rintros arg h₁ ⟨w, hw⟩; use w; exact h₁ hw\n\n lemma first_cause_of_nocontingent : ∀ {w}, (¬∃ e : ω.entity, e.contingent ∧ e.exists w) → c.first_cause ω.nbe w :=\n begin\n intros w h,\n push_neg at h,\n simp [cause.first_cause, nbe],\n refine ⟨by simp [univ],_⟩,\n unfold_coes, simp,\n intros e h₃ h₄,\n replace h₄ := ne.symm h₄,\n specialize h e,\n simp [nbe, h₄] at h,\n contradiction,\n end\n \n lemma first_cause_of_parmenides : ∀ {w}, (∀ w', w' = w) → c.first_cause ω.nbe w :=\n begin\n intros w h,\n apply c.first_cause_of_nocontingent,\n rintro ⟨e, h₁, h₂⟩,\n suffices c : □e, contradiction,\n simp [nbe, ext_iff],\n intro w', specialize h w',\n rwa h,\n end\n\n /-- An event is said to be a **Contingent Substratum** if\n it is both `contingent` and a `substratum` (Duh).\n -/\n def csubstratum (e : ω.event) : Prop := e.contingent ∧ c.substratum e\n\n /-- **Kind Contingent Substrata** is the event of there being contingent substrata of \n some specific kind in a possible world `w`.\n By default, the event simply claims that there are\n contingent substrata in `w`. -/\n def kcsubstrata (kind := λe:ω.event,true) : ω.event := \n {w | ∃ su, kind su ∧ su.occurs w ∧ c.csubstratum su}\n\n /-- The **Principle of Contingent Substratum**, as an event.\n It reads: \"If there are entities of some kind (contingent) then \n there is an event (existential) \n which is a Contingent Substratum \n (maybe because it is a contingent material substratum of entities of *that* kind, \n or something of the sort, or maybe for some other reason)\". -/\n def epcs (kind₁ := @entity.contingent ω) (kind₂ := @event.existential ω) : ω.event := \n {w | (∃ e, kind₁ e ∧ e.exists w) → c.kcsubstrata kind₂ w}\n /-- The **Principle of Contingent Substratum**.\n It reads: \"If there are entities of some kind (contingent) then \n there is an event (existential) \n which is a Contingent Substratum \n (maybe because it is a contingent material substratum of entities of *that* kind, \n or something of the sort, or maybe for some other reason)\". -/\n def pcs (kind₁ := @entity.contingent ω) (kind₂ := @event.existential ω) := □c.epcs kind₁ kind₂\n\n /-- The **Principle of Substratum Causality**, as an event. \n It reads: \"If there are contingent substrata of a \n certain kind (existential), then any event which is the cause\n of all contingent substrata of that kind (other than the thing itself)\n is the cause of all events of that kind (other than the thing itself).\"\n -/\n def epsc (kind := @event.existential ω) : ω.event := \n {w | c.kcsubstrata kind w → ∀ e,\n (∀ su, c.csubstratum su → su ≠ e → kind su → su.occurs w → c.causes e su w) →\n (∀ su, su ≠ e → su.contingent → kind su → su.occurs w → c.causes e su w)\n }\n \n def ultimate_substratum (e : ω.event) : Prop := \n c.csubstratum e ∧ ∀ e' : ω.entity, c.causes e' e ⇒ c.first_cause e'\n \n /- The **Beginning of Philosophy** is said to have occurred \n When Thales of Miletus famously declared \"All is Water\".\n We say that the beginning of philosophy occurs at a possible world\n `w` just in case Thales was right at `w`\n (although \"water\" can be anything that you want it to be). -/\n def bphilosophy (water := λe:ω.event,true) : ω.event := \n {w | ∃ u, water u ∧ u.occurs w ∧ c.ultimate_substratum u}\n\n -- Notice that by default water is \"everything\" (as per Thales),\n -- but then you can get more specific about what water is if you want.\n\n /-- The **Principle of Ultimate Substratum**, as an event.\n It reads: \"If there are entities of some kind (contingent) then \n there is an event (of some other kind, like water) \n which is an Ultimate Substratum \n (maybe because it is an ultimate material substratum of entities of *that* kind, \n or something of the sort, or maybe for some other reason)\". -/\n def epus (kind := @entity.contingent ω) (water := λe:ω.event,true) : ω.event := \n {w | (∃ e, kind e ∧ e.exists w) → c.bphilosophy water w}\n\n /-- The **Principle of Ultimate Substratum**.\n It reads: \"If there are entities of some kind (contingent) then \n there is an event (of some other kind, like water) \n which is an Ultimate Substratum\n (maybe because it is an ultimate material substratum of entities of *that* kind, \n or something of the sort, or maybe for some other reason)\". -/\n def pus (kind := @entity.contingent ω) (water := λe:ω.event,true) := □c.epus kind water\n\n /-- An event `e` is said to be **Causally Grounded** w.r.t. a causal structure `c`,\n and possible world `w`, if there is some event in `w` which may possibly cause `e` to occur. -/\n def cground (e : ω.event) : ω.event := {w | ∃ e' : ω.event, e'.occurs w ∧ ⋄c.causes e' e}\n\n /-- An **Aristotelian-Causal Account of Modality**, for events, is the set of all possible worlds \n `w` in which for any given possible event `e`, it either occurs in `w` or some event\n in `w` can possibly cause `e` to occur. -/\n def acam' : ω.event := {w | ∀ e : ω.event, ⋄e → e.occurs w ∨ c.cground e w}\n -- Notice the converse of the (`→`) in the above definition is trivial.\n\n /-- A **Non-Negative Aristotelian-Causal Account of Modality**, for events, is the set of all possible worlds \n `w` in which for any not purely negative event `e`, it either occurs in `w` or some event\n in `w` can possibly cause `e` to occur. -/\n def nnacam : ω.event := {w | ∀ e : ω.event, e.npnegative → e.occurs w ∨ c.cground e w}\n\n\n /-- An **Aristotelian-Causal Account of Modality** (for entities) is the set of all possible worlds \n `w` in which for any given possible entity `e`, it either exists in `w` or some event\n in `w` can possibly cause `e` to exist. -/\n def acam : ω.event := {w | ∀ (e : ω.entity), e.exists w ∨ c.cground e w}\n \n /-- This is an extra auxiliary principle that is needed in Pruss's \n \"nature of modality\" argument.\n It reads \"If all but one world satisfies the `psr`\n and the one that is left is also Aristotelian-Causal, then this world also satisfies the `psr`.\"\n The \"Aristotelian-Causal\" part is a weakening of the original thesis. -/\n def prussian_principle₁ : Prop := ∀ (w : ω.world), c.acam' w → (∀ w', w' ≠ w → c.epsr.occurs w') → c.epsr.occurs w\n /-- This is an extra auxiliary principle that is needed in Pruss's \n \"nature of modality\" argument.\n It reads \"If some world `w` is Aristotelian-Causal, and all worlds containing an entity not in the `w` \n satisfy the `pc`, then `w` also satisfies the `pc`.\"\n The \"Aristotelian-Causal\" part is a weakening of the original thesis,\n but this principle appears to be stronger than `prussian_principle₁`. -/\n def prussian_principle₂ : Prop := ∀ (w : ω.world), c.acam w → (∀ w', (∃ e ∈ w', e ∉ w) → c.epc.occurs w') → c.epc.occurs w\n \n /-- Independence principle needed in one interpretation of Pruss's argument. \n It reads \"No contingent event is necessarily impossible to cause, \n and the mere fact there are no causes necessitating a contingent event's occurrence \n does not necessitate this event's occurrence\". \n The second part of the conjunction is analytical. -/\n lemma prussian_independence : □c.acam' → ∀ e : ω.event, e.contingent → e ≢ c.uncaused e :=\n begin\n intros h e he, \n simp only [incomparable_entailment, comparable_entailment], \n simp [event.contingent, event.necessary, ext_iff] at he,\n obtain ⟨he, ⟨w, hw⟩⟩ := he,\n push_neg, constructor; intro absurd,\n simp [event.contingent, event.necessary, ext_iff, cause.acam'] at h,\n specialize h w e he, \n simp [hw, cause.cground, set_of] at h,\n obtain ⟨C, h₁, ⟨w', hw'⟩⟩ := h,\n have c₀ := c.axiom₀ ⟨C, hw'⟩,\n specialize absurd c₀,\n simp [cause.uncaused, cause.caused] at absurd,\n specialize absurd C, contradiction,\n -- the second part doesn't need acam', \n -- and is in fact analytical\n suffices c₀ : c.uncaused e w,\n specialize absurd c₀, contradiction, \n clear absurd,\n simp [cause.uncaused, cause.caused, has_neg.neg, compl], \n simp [set_of],\n intros C absurd, \n replace absurd := c.axiom₀ ⟨C, absurd⟩,\n contradiction,\n end\n\n \n /-- The least Pruss has to assume, as an additional premise, to conclude the `psr` from \n the necessity of `acam'`. -/\n def prussian_minimal_extra_assumption : Prop := \n ∀ e C : ω.event, e.contingent → \n c.causes C (e ∩ c.uncaused e) ⇒ c.causes C e\n\n theorem pruss_nature_of_modality_argument₀ : c.conjunctive₁'' → □c.acam' → c.psr :=\n begin\n intros conj h, simp [cause.psr, ext_iff, explanation.epsr], \n have indep := c.prussian_independence h,\n intros w, by_contradiction contra,\n push_neg at contra,\n obtain ⟨E, h₁, w', h₂, ⟨h₃, h₄⟩⟩ := contra,\n let «E*» := c.uncaused E ∩ E,\n simp [cause.acam', ext_iff] at h,\n have c₀ : w ∈ «E*»,\n refine ⟨_, h₃⟩,\n simpa [cause.uncaused, cause.caused],\n specialize h w' «E*» ⟨w, c₀⟩,\n simp [h₂, cause.cground, set_of] at h,\n obtain ⟨C, h₅, ⟨w'', h₆⟩⟩ := h,\n simp [«E*»] at h₆,\n specialize conj C E (c.uncaused E) _, swap,\n apply (indep E), \n simp [event.contingent, event.necessary, ext_iff],\n exact ⟨⟨w, h₃⟩,⟨w', h₂⟩⟩,\n simp only [inter_comm] at h₆,\n specialize conj h₆, clear h₆,\n obtain ⟨h₆, h₇⟩ := conj,\n replace h₇ := c.axiom₀ ⟨C, h₇⟩,\n simp [cause.uncaused, cause.caused] at h₇,\n specialize h₇ C,\n contradiction,\n end\n\n theorem pruss_nature_of_modality_argument₀' : c.prussian_minimal_extra_assumption → □c.acam' → c.psr :=\n begin\n intros min h, simp [cause.psr, ext_iff, explanation.epsr], \n intros w, by_contradiction contra,\n push_neg at contra,\n obtain ⟨E, h₁, w', h₂, ⟨h₃, h₄⟩⟩ := contra,\n let «E*» := c.uncaused E ∩ E,\n simp [cause.acam', ext_iff] at h,\n have c₀ : w ∈ «E*»,\n refine ⟨_, h₃⟩,\n simpa [cause.uncaused, cause.caused],\n specialize h w' «E*» ⟨w, c₀⟩,\n simp [h₂, cause.cground, set_of] at h,\n obtain ⟨C, h₅, ⟨w'', h₆⟩⟩ := h,\n simp [«E*»] at h₆,\n specialize min E C _, swap,\n simp [event.contingent, event.necessary, ext_iff],\n exact ⟨⟨w, h₃⟩,⟨w', h₂⟩⟩,\n simp only [inter_comm] at h₆,\n specialize min h₆, \n replace h₆ := c.axiom₀ ⟨C, h₆⟩,\n simp [cause.uncaused, cause.caused] at h₆,\n replace h₆ := h₆.2 C,\n contradiction,\n end \n\n theorem pruss_nature_of_modality_argument₁ : c.conjunctive₁'' → \n c.prussian_minimal_extra_assumption → c.prussian_principle₁ \n → ⋄c.acam' → c.psr :=\n begin\n intros conj min pruss h,\n obtain ⟨actual_world, ha⟩ := h,\n suffices c₀ : ∀ w', w' ≠ actual_world → c.epsr.occurs w',\n have c₁ := pruss actual_world ha c₀,\n simp [cause.psr, ext_iff], intro w,\n by_cases h : w = actual_world,\n rw h, exact c₁,\n exact c₀ w h,\n clear pruss,\n intros w hw,\n by_contradiction contra,\n simp [cause.epsr, explanation.epsr, ext_iff] at contra,\n obtain ⟨E, h₀, h₁, h₂, h₃⟩ := contra,\n by_cases h : E.occurs actual_world,\n let nonactuality : ω.event := -{actual_world},\n let F := E ∩ nonactuality,\n let «F*» := F ∩ c.uncaused F,\n have c₀ : w ∈ F,\n refine ⟨h₂, _⟩,\n simp [nonactuality, hw],\n have c₁ : E ≢ nonactuality,\n simp only [incomparable_entailment, comparable_entailment], \n push_neg, constructor; intro absurd,\n specialize absurd h,\n simp [nonactuality] at absurd,\n contradiction,\n obtain ⟨world, hworld⟩ := h₁,\n by_cases aux : world = actual_world,\n cases aux, contradiction,\n have : world ∈ nonactuality,\n simp [nonactuality, aux],\n specialize absurd this,\n contradiction,\n have c₂ : ∀ (C : ω.event), ¬c.causes C F w,\n intros C absurd,\n have c' := conj C E nonactuality c₁ absurd,\n replace c' := c'.1,\n specialize h₃ C,\n contradiction,\n have c₃ : ⋄«F*»,\n refine ⟨w, c₀, _⟩,\n simpa [cause.uncaused, cause.caused],\n have c₄ : actual_world ∉ «F*»,\n intro absurd, simp [«F*», F] at absurd,\n contradiction,\n clear c₁ c₂,\n simp [cause.acam'] at ha,\n specialize ha «F*» c₃, clear c₃,\n simp [c₄, cause.cground, set_of] at ha, clear c₄,\n obtain ⟨C, actual_C, w', hw'⟩ := ha,\n specialize min F C _, swap,\n simp [event.contingent, event.necessary, ext_iff],\n refine ⟨⟨w, c₀⟩, actual_world, _⟩, simp [h],\n specialize min hw',\n replace hw' := c.axiom₀ ⟨C, hw'⟩,\n replace hw' := hw'.2,\n simp [cause.uncaused, cause.caused] at hw',\n specialize hw' C, contradiction,\n -- second case\n let «F*» := E ∩ c.uncaused E,\n have c₃ : ⋄«F*»,\n refine ⟨w, h₂, _⟩,\n simpa [cause.uncaused, cause.caused],\n have c₄ : actual_world ∉ «F*»,\n intro absurd, simp [«F*»] at absurd,\n replace absurd := absurd.1, \n contradiction,\n simp [cause.acam'] at ha,\n specialize ha «F*» c₃, clear c₃,\n simp [c₄, cause.cground, set_of] at ha, clear c₄,\n cases ha, replace ha := ha.1,\n contradiction,\n obtain ⟨C, actual_C, w', hw'⟩ := ha,\n specialize min E C _, swap,\n simp [event.contingent, event.necessary, ext_iff],\n exact ⟨⟨w, h₂⟩, actual_world, h⟩,\n specialize min hw',\n replace hw' := c.axiom₀ ⟨C, hw'⟩,\n replace hw' := hw'.2,\n simp [cause.uncaused, cause.caused] at hw',\n specialize hw' C, contradiction,\n end\n\n \n theorem pruss_nature_of_modality_argument₁' : c.conjunctive₁' → c.prussian_principle₁ → ⋄c.acam' → c.psr :=\n begin\n intros conj pruss h,\n obtain ⟨actual_world, ha⟩ := h,\n suffices c₀ : ∀ w', w' ≠ actual_world → c.epsr.occurs w',\n have c₁ := pruss actual_world ha c₀,\n simp [cause.psr, ext_iff], intro w,\n by_cases h : w = actual_world,\n rw h, exact c₁,\n exact c₀ w h,\n intros w hw,\n simp [explanation.epsr],\n intros e pe ce he, clear pe,\n have c₁ : ¬c.epsr.occurs w → ∃ F : ω.event, ⋄F ∧ ¬F.occurs actual_world ∧ ¬⋄c.cground F,\n intro brute,\n symmetry' at hw,\n use {w}, simp [hw, set.nonempty],\n by_contradiction contra,\n push_neg at contra,\n obtain ⟨w', ⟨e',he', h'⟩⟩ := contra,\n obtain ⟨w'', hw''⟩ := h',\n have c₁ := c.occured_causes hw'',\n simp at c₁,\n rw c₁ at hw'', clear c₁ w'', rename hw'' c₁,\n simp [cause.epsr, explanation.epsr] at brute,\n obtain ⟨ev, h₁, ⟨h₂, h₃,h₄⟩⟩ := brute,\n specialize h₄ e',\n replace c₁ := c.cause_all_of_cause_singleton conj c₁,\n specialize c₁ ev ⟨h₁,h₂⟩ h₃,\n contradiction,\n by_cases h : c.epsr.occurs w,\n simp [cause.epsr, explanation.epsr] at h,\n specialize h e (nonempty_of_mem he) ce he,\n exact h,\n replace c₁ := c₁ h,\n obtain ⟨F, pF, naF, hF⟩ := c₁,\n simp [cause.acam'] at ha,\n specialize ha F pF,\n simp at naF, simp [naF] at ha,\n simp [set.nonempty] at hF,\n specialize hF actual_world,\n contradiction,\n end\n\n\n -- This section is named after my friend Miguel Luis, which suggested an objection to Pruss's argument to me.\n section miguels_objection\n\n /-- Independence principle needed in one interpretation of the cold flame argument. \n It reads \"No contingent *not purely negative* event is necessarily impossible to cause, \n and the mere fact there are no causes necessitating a contingent event's occurrence \n does not necessitate this event's occurrence\". \n The second part of the conjunction is analytical. -/\n lemma miguels_independence : □c.nnacam → ∀ e : ω.event, e.contingent → e.npnegative → e ≢ c.uncaused e :=\n begin\n intros h e he miguel, \n simp only [incomparable_entailment, comparable_entailment], \n simp [event.contingent, event.necessary, ext_iff] at he,\n obtain ⟨he, ⟨w, hw⟩⟩ := he,\n push_neg, constructor; intro absurd,\n simp [event.contingent, event.necessary, ext_iff, cause.nnacam] at h,\n specialize h w e miguel,\n simp [hw, cause.cground, set_of] at h,\n obtain ⟨C, h₁, ⟨w', hw'⟩⟩ := h,\n have c₀ := c.axiom₀ ⟨C, hw'⟩,\n specialize absurd c₀,\n simp [cause.uncaused, cause.caused] at absurd,\n specialize absurd C, contradiction,\n -- the second part doesn't need nnacam, \n -- and is in fact analytical\n suffices c₀ : c.uncaused e w,\n specialize absurd c₀, contradiction, \n clear absurd,\n simp [cause.uncaused, cause.caused, has_neg.neg, compl], \n simp [set_of],\n intros C absurd, \n replace absurd := c.axiom₀ ⟨C, absurd⟩,\n contradiction,\n end\n\n\n /-- The **Principle of Non-Negative Uncaused Existence** claims\n that the uncaused existence of any entity is not a purely negative event. -/\n def pnnue : Prop := ∀ (e : ω.entity), (↑e ∩ c.uncaused e).npnegative\n\n /-- This is a weaker version of Pruss's argument restricted to non-purely-negative states of affairs, concluding the pc.\n It indeed appears possible to conclude here something stronger than the `pc`, namely a `psr` restricted\n to non-purely-negative events. --/\n theorem cold_flame_argument : c.econjunctive₁'' → c.pnnue → □c.nnacam → c.pc :=\n begin\n intros conj pnnue h, simp [cause.pc, cause.epc, ext_iff, nbe], \n have indep := c.miguels_independence h,\n intros w, by_contradiction contra,\n push_neg at contra,\n obtain ⟨E, w', h₂, ⟨h₃, h₄⟩⟩ := contra,\n let «E*» := ↑E ∩ (c.uncaused E),\n simp [cause.nnacam, ext_iff] at h,\n have c₀ : «E*».npnegative, \n simp [«E*»],\n exact pnnue E,\n specialize h w' «E*» c₀,\n cases h, replace h := h.1, contradiction,\n simp [cause.cground, set_of] at h,\n obtain ⟨C, h₅, ⟨w'', h₆⟩⟩ := h,\n simp [«E*»] at h₆,\n specialize conj C E (c.uncaused E) E.entitative _, swap,\n apply (indep E), \n simp [event.contingent, event.necessary, ext_iff],\n exact ⟨⟨w, h₃⟩,⟨w', h₂⟩⟩,\n by_contradiction contra,\n push_neg at contra,\n apply contra.2,\n exact ⟨E.existential, contra.1⟩,\n specialize conj h₆, \n replace h₆ := c.axiom₀ ⟨C, h₆⟩,\n simp [cause.uncaused, cause.caused] at h₆,\n replace h₆ := h₆.2,\n specialize h₆ C,\n contradiction,\n end\n\n /-! The idea behind the name of this argument is that if we reject the `psr` for negative events,\n we could still endorse `nnacam` instead of `acam'`, since it looks like something such as a cold flame,\n i.e. a flame devoid of heat, is not a purely negative event (if possible), and hence should be \n require to be causable, or actual, in order to be possible. Even if it is insisted that \n the absence of heat is a negative event which, as such, is not caused, \n via `econjunctive₁''` at least the flame as such should be caused, from the fact \n the cold flame as a whole is caused; the flame is both caused and devoid of heat.\n If the principle of causality is false, then generalizing this idea \n from a cold flame to an uncaused flame, we obtain,\n by the same logic, a caused flame devoid of cause, which is absurd. -/\n\n\n\n end miguels_objection\nend cause\n\n-- ALL FOLLOWING SECTIONS ARE VERY MUCH A WORK IN PROGRESS.\n\nsection counterfactuals\n\n variable (ω)\n\n /- A **Counterfactual Theory of (Hierarchical) Causality** is one which, beginning from\n a theory of counterfactuals, defines hierarchical causality as \"If `e₂` is removed, then `e₁` is removed\",\n i.e. there is strong counterfactual dependence between `e₁` and `e₂`. -/\n -- def ctc (c : ω.cfr := default ω.cfr) : ω.cause := begin\n -- refine ⟨⟨c.sdepends, _, _⟩, _⟩,\n -- intros,\n -- simp [cfr.sdepends, cfr.depends],\n -- unfold_coes,\n -- end\n \n -- TODO: Another interpretation of \"If `e₁` is removed, then `e₂` is removed\" \n -- could be given in terms of `entity.removed` for a causal relation in which\n -- only entities were involved in causation.\n\nend counterfactuals\n\nsection four_causes\n -- variable {ω}\n \n structure cause.mcause (c : ω.cause) : Prop :=\n (axiom₀ : c.substantive)\n (axiom₁ : c.consubstantial)\n (axiom₂ : c.effentitative)\n (axiom₃ : c.simultaneous)\n (axiom₄ : ¬∃ s, c.has_will s)\n (axiom₅ : ∀ (e : ω.entity), ⋄c.is_cause e → e.composite)\n (axiom₆ : ∀ (s : ω.substance), ⋄c.caused s → s.composite)\n (axiom₇ : c.conjunctive₂')\n (axiom₈ : c.pp)\n (axiom₉ : ∀ (s₁ s₂ : ω.substance) w, c.causes s₁ s₂ w → s₂.equiv w ≤ s₁.equiv w)\n (axiom₁₀ : ∀ s₁ s₂ : ω.substance, ⋄(-c.causes s₁ s₂ ∩ s₁ ∩ s₂))\n\n def cause.uhylemorphism (c : ω.cause) : ω.event := { w | c.mcause ∧ c.epc (λe, e.perfect ∧ e.contingent) w}\n\n variables {c : ω.cause}\n \n def cause.mcause.atom (mc : c.mcause) (s : ω.substance) := ⋄c.is_cause s ∧ ¬⋄c.caused s\n def cause.mcause.immaterial (mc : c.mcause) (e : ω.entity) := e.exists ∩ c.uncaused e\n \n /-- **Principle of Immaterial Substratum** -/\n def cause.mcause.pis (mc : c.mcause) (ec : ω.cause) : ω.event := \n {w | ∀ (e : ω.entity), mc.immaterial e w → ec.substratum e}\n \n def cause.mcause.base (ec : c.mcause) (s : ω.substance) : ω.event := \n {w | ∀ e, c.caused e w → c.causes s e w}\n\n \n structure cause.mcause.ecompatible (mc : c.mcause) (ec : ω.cause) : Prop :=\n (axiom₁ : ∀ (s : ω.substance), ⋄c.is_cause s → ¬ec.has_will s)\n (axiom₂ : □ mc.pis ec)\n \n class cause.effcause (c : ω.cause) : Prop :=\n (axiom₀ : c.substantive)\n (axiom₁ : c.conjunctive₁'')\n -- (axiom₂ : c.pp' (λe, c.substratum e))\n -- (axiom₃ : c.psr)\n (axiom₄ : □c.acam')\n \n\n -- def ecause.aristotelian : Prop := \n \n\n -- variables (s : ω.substance) (e : ω.entity)\n\n -- -- integral parthood\n -- def substance.part_of (s₁ s₂ : ω.substance) : ω.event := sorry\n\n -- -- efficient vertical causation\n -- def substance.ecauses : ω.event := \n -- s.causes e.exists ∩\n -- -s.part_of e.substance ∩\n -- -e.substance.part_of s\n\n\n -- -- compositional causation (we say s \"compositionally causes\" e)\n -- def substance.ccauses : ω.event := \n -- s.causes e.exists ∩\n -- s.part_of e.substance ∩\n -- -e.substance.part_of s\n\n -- -- formal causation\n -- def substance.forcauses : ω.event := \n -- s.ccauses e ∩\n -- s.causes e.substance.exists\n\n -- -- material causation\n -- def substance.mcauses : ω.event := \n -- s.ccauses e ∩\n -- -s.causes e.substance.exists\n\n -- -- final causation\n -- def substance.fincauses : ω.event := \n -- s.causes e.exists ∩\n -- -s.part_of e.substance ∩\n -- e.substance.part_of s\n\nend four_causes\n\nsection principles\n\n variable (ω)\n\n -- -- the thomistic principle of sufficent reason/causality\n -- def tpsr : Prop := \n -- ∀ (s : ω.substance) (p : ω.predicate) (h₁ : p.proper) (h₂ : ¬ p.dere_of s.up) (w ∈ p s.up), \n -- ∃ c : ω.substance, c.causes (p s.up) w\n\n -- -- the efficient version of tpsr\n -- -- the thomistic principle of sufficent reason/causality\n -- def etpsr : Prop := \n -- ∀ (s : ω.substance) (p : ω.predicate) (h₁ : p.proper) (h₂ : ¬ p.dere_of s.up) (w ∈ p s.up),\n -- -- p s.up cast to an entity\n -- let r := (entity.mk (p s.up) \n -- (by apply h₁.axiom₂; exact e) \n -- (by use w; assumption))\n -- in ∃ c : ω.substance, c.ecauses r w\n\nend principles\n\nsection time\n\n variables {ω} (c : ω.cause)\n\n structure event.factor (e : ω.event) :=\n (begins : ω.event)\n (continues : ω.event)\n (disjoint : begins ∩ continues = ∅)\n (factor : begins ∪ continues = e)\n (nontrivial₁ : ⋄begins)\n (nontrivial₂ : ⋄continues)\n\n def cause.dircauses (e₁ : ω.event) {e₂ : ω.event} (f : e₂.factor) := c.simcauses e₁ f.begins\n\n def event.factor.direct {e₂ : ω.event} (f : e₂.factor) (c : ω.cause) := c.substratum f.begins\n\n def cause.indcauses (e₁ : ω.event) {e₂ : ω.event} (f : e₂.factor) := \n (c.causes e₁ f.begins) ∩ -(c.simcauses e₁ f.begins)\n\n def cause.sindcauses (e₁ : ω.event) {e₂ : ω.event} (f : e₂.factor) := \n { w | c.causes e₁ f.continues w ∧ ¬ c.simcauses e₁ f.continues w ∧ ⋄c.indcauses e₁ f }\n\n def cause.wnoninertial (c : ω.cause) {e : ω.event} (f : e.factor) : Prop := c.substratum f.continues\n\n def cause.noninertial (c : ω.cause) {e : ω.event} (f : e.factor) : Prop := \n c.substratum f.continues ∧ f.continues ⇒ c.caused f.continues\n\n def cause.inertial (c : ω.cause) {e : ω.event} (f : e.factor) : Prop := ¬ c.noninertial f\n\n structure cause.tfactor (c : ω.cause) {e : ω.event} (f : e.factor) : Prop:=\n (axiom₁ : ∀ ca, f.begins ⇒ c.causes ca f.begins ⟷ c.causes ca e)\n (axiom₂ : ∀ ca, f.continues ⇒ c.causes ca f.continues ⟷ c.causes ca e)\n\n def cause.pind₁ {e : ω.event} (f : e.factor) : Prop := \n c.tfactor f ∧\n ∀ (ca : ω.event), c.causes ca e ∩ -ca ⇒ c.sindcauses ca f ∪ c.indcauses ca f\n\n -- def cause.pind₂ : Prop := \n\n def cause.pcem (c : ω.cause) {c' : ω.cause} (mc : c'.mcause) : ω.event :=\n {w | ∀ e : ω.entity, c'.caused e w → ∃ f : e.exists.factor, c.tfactor f ∧ f.direct c ∧\n ∀ ca mca, c.causes ca f.continues ⇒ c'.causes mca e ⟶ c.causes ca mca\n }\n\n /-- An event is said to be **Weakly Directly Non-Inertially Temporally Factorizable**\n if it admits a direct weakly non-inertial temporal factorization (Duh). -/\n def cause.wdnitf (c : ω.cause) (e : ω.event) := ∃ f : e.factor, f.direct c ∧ c.tfactor f ∧ c.wnoninertial f\n\n /-- An event is said to be **Directly Non-Inertially Temporally Factorizable**\n if it admits a direct non-inertial temporal factorization (Duh). -/\n def cause.dnitf (c : ω.cause) (e : ω.event) := ∃ f : e.factor, f.direct c ∧ c.tfactor f ∧ c.noninertial f\n\n /-- An event is said to be **Directly Temporally Factorizable**\n if it admits a direct temporal factorization (Duh). -/\n def cause.dtf (c : ω.cause) (e : ω.event) := ∃ f : e.factor, f.direct c ∧ c.tfactor f\n\n def cause.direct' : ω.event :=\n {w | ∀ e : ω.event, e.occurs w → c.dtf e}\n\n def cause.direct : ω.event :=\n {w | ∀ e : ω.entity, e.exists w → c.dtf e}\n\n def cause.nidirect : ω.event :=\n {w | ∀ e : ω.entity, e.exists w → c.dnitf e}\n\n def cause.wdnidirect : ω.event :=\n {w | ∀ e : ω.entity, e.exists w → c.wdnitf e}\n\n\n -- lemma wdnitf_lemma : c.ps (λe, c.wnitf e) :=\n -- begin\n\n -- end\n\n -- lemma quasi_simultaneity_of_wnidirect : □c.wdnidirect → c.ps univ :=\n -- begin\n -- intro h,\n -- simp [ext_iff] at h,\n -- simp [cause.ps, ext_iff, cause.eps],\n -- intros w₁ e₁ aux h₁ e₂ w₂ h₂,\n -- clear aux h₁ w₁,\n -- have c₀ := c.occured_causes h₂,\n -- specialize h w₂ e₁ c₀,\n -- obtain ⟨f, hf₁, hf₂⟩ := h,\n -- unfold_coes at h₂,\n -- by_cases h : f.begins w₂,\n -- have c := hf₁.axiom₂ e₂ h,\n -- replace c := c.2,\n -- unfold_coes at c,\n -- simp [h₂] at c,\n -- replace c := hf₁.axiom₁ e₂ c,\n -- exact c,\n -- rw ←f.factor at c₀,\n -- simp at c₀,\n -- cases c₀, contradiction,\n -- clear h,\n -- replace c₀ := hf₁.axiom₃ e₂ c₀,\n -- replace c₀ := c₀.2,\n -- unfold_coes at c₀,\n -- simp [h₂] at c₀,\n -- replace hf₂ := hf₂ e₂ c₀,\n -- exact hf₂,\n -- end\n\nend time\n\nend ontology", "meta": {"author": "maxd13", "repo": "topological_ontology", "sha": "68d21c9a00024fba3aed301e16c31e05733c1786", "save_path": "github-repos/lean/maxd13-topological_ontology", "path": "github-repos/lean/maxd13-topological_ontology/topological_ontology-68d21c9a00024fba3aed301e16c31e05733c1786/src/metaphysics/causality.lean", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. NO\n2. NO\n\n", "lm_q1_score": 0.10818896031297129, "lm_q2_score": 0.01282121561037982, "lm_q1q2_score": 0.0013871139868354304}}